{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/integral.hpp>\n\n#include <type_traits>\nusing namespace boost::hana;\n\n\n//! [integral_create]\nauto one = integral<int, 1>;\nauto yes = integral<bool, true>;\n//! [integral_create]\n\n//! [integral_api]\nusing One = decltype(one);\n\nstatic_assert(std::is_same<One::type, One>{}, \"\");\n\nstatic_assert(std::is_same<One::value_type, int>{}, \"\");\n\nstatic_assert(One::value == 1               &&\n              static_cast<int>(one) == 1    &&\n              one() == 1                    &&\n              value(one) == 1\n, \"these are all constant expressions\");\n//! [integral_api]\n\nnamespace anon1 {\n//! [integral_shorthands]\nauto one = int_<1>;\nauto yes = bool_<true>;\n//! [integral_shorthands]\n}\n\nnamespace anon2 {\n//! [literals]\nusing namespace literals; // <-- mandatory to use the _c suffix!\n\nBOOST_HANA_CONSTANT_ASSERT(1234_c == llong<1234>);\nBOOST_HANA_CONSTANT_ASSERT(-1234_c == llong<-1234>);\n//! [literals]\n}\n\n//! [integral_operators]\nBOOST_HANA_CONSTANT_ASSERT(int_<1> == integral<int, 1>);\nBOOST_HANA_CONSTANT_ASSERT(int_<1> + long_<2> == long_<3>);\nBOOST_HANA_CONSTANT_ASSERT(!(bool_<true> && bool_<false>));\n//! [integral_operators]\n\nint main() { }\n", "meta": {"hexsha": "4bf4a8f1d41be71b33b19f2696637a39a2ea730a", "size": 1382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/tutorial/basic_concepts/constant/integral.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/tutorial/basic_concepts/constant/integral.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/tutorial/basic_concepts/constant/integral.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6785714286, "max_line_length": 78, "alphanum_fraction": 0.6628075253, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.5999538396394584}}
{"text": "\n#include \"GeometryCalibration.h\"\n\n#include <LibRayCastBackproject/VoxelData.h>\n#include <LibRayCastBackproject/VolumeRendering.h>\n\n#include <Eigen/Dense>\n\n/// f(x)=1-x^2+x^4 is zero at +/-1, has zero derivative at +/-1 and a maxiumum at f(0)=1; Values outside [-1,1] are clamped to zero. \ninline double weighting(double x)\n{\n\tif (x<-1.0||x>1.0) return 0;\n\tdouble xx=x*x;\n\treturn 1.0-2*xx+xx*xx;\n}\n\nnamespace Calibration {\n\ttemplate <class VectorOfVectors>\n\tdouble computeRadiusThreshold(const VectorOfVectors& beads)\n\t{\n\t\tif (beads.empty()) return 0;\n\t\tdouble sum=0;\n\t\tfor (auto it=beads.begin();it!=beads.end();++it)\n\t\t\tsum+=it->tail(1)[0];\n\t\tdouble mean=sum/(double)beads.size();\n\t\tint n_large=0,n_small=0;\n\t\tdouble sum_large=0, sum_small=0;\n\t\tfor (auto it=beads.begin();it!=beads.end();++it)\n\t\t\tif (it->tail(1)[0]>mean)  { n_large++; sum_large+=it->tail(1)[0]; }\n\t\t\telse                      { n_small++; sum_small+=it->tail(1)[0]; }\n\t\tdouble mean_large=sum_large/(double)n_large;\n\t\tdouble mean_small=sum_small/(double)n_small;\n\t\treturn 0.5*(mean_large+mean_small);\n\t}\n\n\tdouble BeadPhantomDetection::computeRadiusThresholdMM(const std::vector<Eigen::Vector4d>& phantom_beads)\n\t{\n\t\treturn computeRadiusThreshold(phantom_beads);\n\t}\n\n\tdouble BeadPhantomDetection::computeRadiusThresholdPx(const std::vector<Eigen::Vector3d>& detected_beads)\n\t{\n\t\treturn computeRadiusThreshold(detected_beads);\n\t}\n\n\tvoid BeadPhantomDetection::gui_declare_section (const GetSetGui::Section& section) {\n\t\tGetSet<std::vector<Eigen::Vector4d>>(\"Location and Radius\", section, beads).setDescription(\"3D Location of beads (X,Y,Z) and their radius (R) in mm. Format: \\\"X0 Y0 Z0 R0; X1 Y1 Z1 R1; ...\\\"\");\n\t}\n\n\tvoid BeadPhantomDetection::gui_retreive_section(const GetSetGui::Section& section) {\n\t\tbeads=GetSet<std::vector<Eigen::Vector4d>>(\"Location and Radius\", section);\n\t}\n\t\n\tBeadPhantomSimulator::BeadPhantomSimulator() {}\n\n\tBeadPhantomSimulator::BeadPhantomSimulator(const BeadPhantomSimulator& other)\n\t{\n\t\tvoxelization=other.voxelization;\n\t\tdrr.voxel_data=0x0;\n\t\tdrr.raycaster=0x0;\n\t}\n\n\tBeadPhantomSimulator::~BeadPhantomSimulator() {\n\t\tif (drr.raycaster ) delete drr.raycaster ;\n\t\tif (drr.voxel_data) delete drr.voxel_data;\n\t\tdrr.raycaster =0x0;\n\t\tdrr.voxel_data=0x0;\n\t}\n\n\tGeometry::RP3Homography\tBeadPhantomSimulator::getModel() const {\n\t\treturn Geometry::Scale(voxelization.voxel_spacing)*Geometry::Translation(-0.5*voxelization.voxel_number.cast<double>());\n\t}\n\n\tvoid BeadPhantomSimulator::voxelize(NRRD::Image<float>& phantom, const std::vector<Eigen::Vector4d>& beads, GetSetGui::ProgressInterface &app) const\n\t{\n\t\t// Initilalize 3D voxel data\n\t\tconst auto& dim = voxelization.voxel_number;\n\t\tconst auto& spacing = voxelization.voxel_spacing ;\n\t\tphantom.set(dim[0], dim[1], dim[2]);\n\t\tphantom.spacing(0) = spacing[0];\n\t\tphantom.spacing(1) = spacing[1];\n\t\tphantom.spacing(2) = spacing[2];\n\t\tconst auto& model = getModel();\n\t\t// Set phantom to zero\n\t\tint l = phantom.length();\n\t\t#pragma omp parallel for\n\t\tfor (int i = 0; i<l; i++) phantom[i] = 0;\n\n\t\t// Start progress\n\t\tbool cancel_clicked = false;\n\t\tapp.progressStart(__FUNCTION__, \"Computing Voxelized version of the bead phantom...\", (int)beads.size(), &cancel_clicked);\n\n\t\t// Then loop over blocks with beads and draw them\n\t\tfor (int i = 0; i<(int)beads.size(); i++)\n\t\t{\n\t\t\tif (cancel_clicked) break;\n\t\t\tapp.progressUpdate(i);\n\t\t\t// Get Bead radius and transfrm bead to voxel coordinates.\n\t\t\tauto B(beads[i]);\n\t\t\tdouble r = B[3];\n\t\t\tdouble rc = std::ceil(r);\n\t\t\tB[3] = 1;\n\t\t\t// Figure out voxel range affected by bead (assumes model is affine)\n\t\t\tEigen::Vector3i min = (model.inverse()*(B - Geometry::RP3Point(rc+1, rc+1, rc+1, 0))).head(3).cast<int>();\n\t\t\tEigen::Vector3i max = (model.inverse()*(B + Geometry::RP3Point(rc+1, rc+1, rc+1, 0))).head(3).cast<int>();\n\t\t\tmin = min.cwiseMax(Eigen::Vector3i::Zero());\n\t\t\t// max = max.cwiseMin(dim);\n\t\t\tif (max[0]>=dim[0]) max[0]=dim[0]-1;\n\t\t\tif (max[1]>=dim[1]) max[1]=dim[1]-1;\n\t\t\tif (max[2]>=dim[2]) max[2]=dim[2]-1;\n\n\t\t\t// And draw bead\n\t\t\tfor (int z = min[2]; z<max[2]; z++)\n\t\t\t\tfor (int y = min[1]; y<max[1]; y++)\n\t\t\t\t\tfor (int x = min[0]; x<max[0]; x++)\n\t\t\t\t\t{\n\t\t\t\t\t\tGeometry::RP3Point X = model*Geometry::RP3Point(x+0.5, y+0.5, z+0.5, 1);\n\t\t\t\t\t\tGeometry::dehomogenize(X);\n\t\t\t\t\t\tdouble d = (X.head(3) - B.head(3)).norm();\n\t\t\t\t\t\tfloat opacity=0.0f;\n\t\t\t\t\t\tif      (d<r-0.25) opacity=1.0f;\n\t\t\t\t\t\telse if (d<r+0.5) opacity=(float)weighting((r-0.25-d)/0.75);\n\t\t\t\t\t\tphantom[x + y*phantom.size(0) + z*phantom.size(1)*phantom.size(0)]+=opacity;\n\t\t\t\t\t}\n\t\t}\n\t\tapp.progressEnd();\n\t\tif (cancel_clicked)\n\t\t\tphantom.set(0x0,0);\n\t\tif (drr.raycaster) delete drr.raycaster;\n\t\tdrr.raycaster=0x0;\n\t\tif (drr.voxel_data) delete drr.voxel_data;\n\t\tdrr.voxel_data=0x0;\n\t\tif (!!phantom) drr.voxel_data=new VolumeRendering::VoxelData(phantom,false);\n\t}\n\t\n\tvoid BeadPhantomSimulator::load_volume(const NRRD::ImageView<float>& phantom)\n\t{\n\t\tif (drr.raycaster) delete drr.raycaster;\n\t\tdrr.raycaster=0x0;\n\t\tif (drr.voxel_data) delete drr.voxel_data;\n\t\tdrr.voxel_data=0x0;\n\t\tif (!!phantom) drr.voxel_data=new VolumeRendering::VoxelData(phantom,false);\n\t}\n\t\n\tvoid BeadPhantomSimulator::project(NRRD::ImageView<float>& out, const Geometry::ProjectionMatrix& P) const\n\t{\n\t\t// Out must be allocated\n\t\tif (out.dimension()!=2) out.set(0,0x0);\n\t\t// Must call voxelize before use.\n\t\tif (!drr.voxel_data) {\n\t\t\tout.set(0,0x0);\n\t\t\treturn;\n\t\t}\n\n\t\t// Set up raycaster\n\t\tif (!drr.raycaster)\n\t\t\tdrr.raycaster=new VolumeRendering::Raycaster(*drr.voxel_data);\n\t\tdrr.raycaster->raycastPass<VolumeRendering::DigitallyReconstructedRadiograph>();//.setTransferFunction();\n\t\tdrr.raycaster->setSamplesPerVoxel(1.5);\n\n\t\t// Allocate output image and raycast\n\t\tNRRD::Image<float> tmp(4,out.size(0), out.size(1));\n\t\tdrr.raycaster->render(tmp,P);\n\n\t\t// Copy temporary image\n\t\tint l=out.length();\n\t\tfor (int i=0;i<l;i++) out[i]=tmp[i*4];\n\t\tout.meta_info[\"Projection Matrix\"]=toString(P);\n\t}\n\n\tvoid BeadPhantomSimulator::gui_declare_section (const GetSetGui::Section& section)\n\t{\n\t\tGetSet<Eigen::Vector3i              >(\"Voxelization/Voxel Number\"  , section, voxelization.voxel_number  ).setDescription(\"Volume dimension in voxels.\");\n\t\tGetSet<Eigen::Vector3d              >(\"Voxelization/Voxel Spacing\" , section, voxelization.voxel_spacing ).setDescription(\"Spacing between voxels in mm.\");\n\t\tGetSetGui::Section(\"Voxelization\",section).setGrouped();\n\t}\n\n\tvoid BeadPhantomSimulator::gui_retreive_section(const GetSetGui::Section& section) \n\t{\n\t\tvoxelization.voxel_number    =GetSet<Eigen::Vector3i              >(\"Voxelization/Voxel Number\"  ,section);\n\t\tvoxelization.voxel_spacing   =GetSet<Eigen::Vector3d              >(\"Voxelization/Voxel Spacing\" ,section);\n\t}\n\n} // namespace Calibration\n", "meta": {"hexsha": "b25b7247228d4ab40da69a7f46ddb9ea0b226bfb", "size": 6725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/LibGeometryCalibration/GeometryCalibration.cpp", "max_stars_repo_name": "mareikethies/EpipolarConsistency", "max_stars_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-21T16:33:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T03:03:00.000Z", "max_issues_repo_path": "code/LibGeometryCalibration/GeometryCalibration.cpp", "max_issues_repo_name": "mareikethies/EpipolarConsistency", "max_issues_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-14T07:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-14T07:48:55.000Z", "max_forks_repo_path": "code/LibGeometryCalibration/GeometryCalibration.cpp", "max_forks_repo_name": "mareikethies/EpipolarConsistency", "max_forks_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-05-15T21:38:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T07:20:47.000Z", "avg_line_length": 36.3513513514, "max_line_length": 195, "alphanum_fraction": 0.6889219331, "num_tokens": 2181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5998993911071651}}
{"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 <iostream>\n#include <blitz/array.h>\n#include <blitz/timer.h>\n\nint main() {\n    using namespace blitz;\n\n    typedef Array<double,3> Image;\n    Image A(512,512,512);\n    Timer timer;\n\n    A = 0.0;\n    timer.start();\n    for (unsigned j=0;j<10;++j) {\n        for (Image::iterator i=A.begin(),end=A.end();i!=end;++i) {\n            const TinyVector<int,3> pos = i.position();\n            *i += pos(0)+pos(1)+pos(2);\n        }\n    }\n    timer.stop();\n    double flops = 10.0*512*512*512*2;\n    double seconds = timer.elapsedSeconds();\n\n    double timePerOp = seconds / flops;\n\n    cout << \"ops = \" << flops << endl\n         << \"seconds = \" << seconds << endl;\n\n    double Mflops = flops / seconds / 1.0e+6;\n    cout << \"Mflops = \" << Mflops << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "1f2723198cc4d3a76a7071b77a26cfcf0314b4b3", "size": 770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/iter.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/iter.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/iter.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6470588235, "max_line_length": 66, "alphanum_fraction": 0.5402597403, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5998993754363325}}
{"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": "#include <jaco2_kin_dyn_lib/jaco2_residual_kalman.h>\n#include <jaco2_kin_dyn_lib/kdl_conversion.h>\n#include <Eigen/Dense>\nJaco2ResidualKalman::Jaco2ResidualKalman():\n    n_(0)\n{\n\n}\n\nvoid Jaco2ResidualKalman::setDimensions(std::size_t n)\n{\n    n_ = n;\n    eye_ = Eigen::MatrixXd::Identity(n,n);\n}\nvoid Jaco2ResidualKalman::initialize(std::size_t n, const Eigen::VectorXd& state)\n{\n    state_ = state;\n    n_ = n;\n    eye_ = Eigen::MatrixXd::Identity(n_,n_);\n    cov_ = Eigen::MatrixXd::Identity(n_,n_);\n}\n\nvoid Jaco2ResidualKalman::initialize(const std::vector<double> &state)\n{\n    Jaco2KinDynLib::convert(state, state_);\n    n_ = state.size();\n    eye_ = Eigen::MatrixXd::Identity(n_,n_);\n    cov_ = Eigen::MatrixXd::Identity(n_,n_);\n}\n\nvoid Jaco2ResidualKalman::setCovarianceProcess(const Eigen::MatrixXd& Q)\n{\n    cov_state_ = Q;\n}\n\nvoid Jaco2ResidualKalman::setCovarianceMeasurment(const Eigen::MatrixXd &R)\n{\n    cov_measurment_ = R;\n}\n\nEigen::VectorXd Jaco2ResidualKalman::update(Eigen::VectorXd& measurement)\n{\n\n    Eigen::MatrixXd cov_pri = cov_ + cov_measurment_;\n\n    Eigen::MatrixXd K = cov_pri * (cov_pri + cov_state_).inverse();\n    state_ += K *(measurement - state_);\n    cov_ = (eye_ - K)*cov_pri;\n\n    return state_;\n\n}\n\nvoid Jaco2ResidualKalman::update(const std::vector<double>& measurement, std::vector<double>& result)\n{\n    Eigen::VectorXd meas;\n    Jaco2KinDynLib::convert(measurement, meas);\n    Eigen::VectorXd res = update(meas);\n    Jaco2KinDynLib::convert(res, result);\n}\n\nEigen::MatrixXd Jaco2ResidualKalman::getCovariance() const\n{\n    return cov_;\n}\n", "meta": {"hexsha": "0d9b2d2d97ea89e1acd098d40ccad90c50a68ded", "size": 1581, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jaco2_kin_dyn_lib/src/jaco2_residual_kalman.cpp", "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_kin_dyn_lib/src/jaco2_residual_kalman.cpp", "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_kin_dyn_lib/src/jaco2_residual_kalman.cpp", "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": 23.9545454545, "max_line_length": 101, "alphanum_fraction": 0.7071473751, "num_tokens": 468, "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": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n    typedef std::complex<double>  cdouble;\n    \n    const unsigned n= 8;\n    dense2D<cdouble>              A(n, n);\n\n    A= 3.0;\n\n    dense_vector<cdouble>         v(n), w(n);\n    for (unsigned i= 0; i < size(v); i++)\n\tv[i]= cdouble(i+1, n-i), w[i]= cdouble(i+n);\n\n    rank_one_update(A, v, w);\n    std::cout << \"A after rank-one update is \\n\" \n\t      << with_format(A, 9, 3) << \"\\n\";\n\n    A= 3.0;\n    rank_two_update(A, v, w);\n    std::cout << \"A after rank-two update is \\n\"\n\t      << with_format(A, 9, 3) << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "42b4b8bc17b6b1e18aebf10aff22d8e3940df40f", "size": 641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/rank_two_update.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/rank_two_update.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/rank_two_update.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 22.1034482759, "max_line_length": 49, "alphanum_fraction": 0.5304212168, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5998969351322085}}
{"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\uff1aCC(creativecommons.org)BY-NC-SA\n *                      Copyleft! 2018 William Yu\n *      \u7248\u6743\u90e8\u5206\u6240\u6709\uff0c\u9075\u5faaCC(creativecommons.org)BY-NC-SA\u534f\u8bae\u6388\u6743\u65b9\u5f0f\u4f7f\u7528\n *\n * Filename                : \n * Description             : \u89c6\u89c9SLAM\u5341\u56db\u8bb2/ch6/g2o \u5b66\u4e60\u8bb0\u5f55\n * Reference               : \n * Programmer(s)           : William Yu, windmillyucong@163.com\n * Company                 : HUST, DMET\u56fd\u5bb6\u91cd\u70b9\u5b9e\u9a8c\u5ba4FOCUS\u56e2\u961f\n * Modification History\t   : ver1.0, 2018.04.05, William Yu\n                            \n=================================================================================*/\n\n/// Include Files\n#include <iostream>\n#include <g2o/core/base_vertex.h> //\u5b9a\u70b9\u7c7b\u578b\n#include <g2o/core/base_unary_edge.h> //\u4e00\u5143\u8fb9\u7c7b\u578b\n#include <g2o/core/block_solver.h> //\u6c42\u89e3\u5668\n#include <g2o/core/optimization_algorithm_levenberg.h> //\u83b1\u6587\u8d1d\u683c-\u9a6c\u5938\u7279\u65b9\u6cd5 Levenberg-Marquardt\u7b97\u6cd5\n#include <g2o/core/optimization_algorithm_gauss_newton.h> //\u9ad8\u65af\u725b\u987f\u6cd5\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> //\u8ba1\u65f6\u5e93\nusing namespace std; \n\n\n\n/*-----------------------------[Note]---------------------------\n# G2O\u56fe\u4f18\u5316\n\u6df1\u5165\u7406\u89e3\u56fe\u4f18\u5316\u4e0eg2o\uff1a\u56fe\u4f18\u5316\u7bc7 http://www.cnblogs.com/gaoxiang12/p/5244828.html\n\u6df1\u5165\u7406\u89e3\u56fe\u4f18\u5316\u4e0eg2o\uff1ag2o\u7bc7 https://www.cnblogs.com/gaoxiang12/p/5304272.html\n--------------------------------------------------------------*/\n\n\n/// Global Variables\n\n/**\n * @class \n * @brief \u5f85\u4f18\u5316\u53d8\u91cf\n */\n// \u66f2\u7ebf\u6a21\u578b\u7684\u9876\u70b9\uff0c\u6a21\u677f\u53c2\u6570\uff1a\u4f18\u5316\u53d8\u91cf\u7ef4\u5ea6\u548c\u6570\u636e\u7c7b\u578b\nclass CurveFittingVertex: public g2o::BaseVertex<3, Eigen::Vector3d>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    virtual void setToOriginImpl() // \u91cd\u7f6e\n    {\n        _estimate << 0,0,0;\n    }\n    \n    virtual void oplusImpl( const double* update ) // \u66f4\u65b0\n    {\n        _estimate += Eigen::Vector3d(update);\n    }\n    // \u5b58\u76d8\u548c\u8bfb\u76d8\uff1a\u7559\u7a7a\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 \u8bef\u5dee\u6a21\u578b\n */\n// \u8bef\u5dee\u6a21\u578b \u6a21\u677f\u53c2\u6570\uff1a\u89c2\u6d4b\u503c\u7ef4\u5ea6\uff0c\u7c7b\u578b\uff0c\u8fde\u63a5\u9876\u70b9\u7c7b\u578b\nclass CurveFittingEdge: public g2o::BaseUnaryEdge<1,double,CurveFittingVertex>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    CurveFittingEdge( double x ): BaseUnaryEdge(), _x(x) {}\n    // \u8ba1\u7b97\u66f2\u7ebf\u6a21\u578b\u8bef\u5dee\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 \u503c\uff0c y \u503c\u4e3a _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;         // \u771f\u5b9e\u53c2\u6570\u503c\n    int N=100;                          // \u6570\u636e\u70b9\n    double w_sigma=1.0;                 // \u566a\u58f0Sigma\u503c\n    cv::RNG rng;                        // OpenCV\u968f\u673a\u6570\u4ea7\u751f\u5668\n    double abc[3] = {0,0,0};            // abc\u53c2\u6570\u7684\u4f30\u8ba1\u503c\n\n    vector<double> x_data, y_data;      // \u6570\u636e\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 ) //\u4eba\u4e3a\u53e0\u52a0\u9ad8\u65af\u566a\u58f0\n        );\n        cout<<x_data[i]<<\" \"<<y_data[i]<<endl;\n    }\n    \n    //-- \u56fe\u4f18\u5316\u8fc7\u7a0b\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<3,1> > Block;   //\u8bef\u5dee\u9879\u4f18\u5316\u53d8\u91cf\u7ef4\u5ea6\u4e3a3\uff0c\u8bef\u5dee\u503c\u7ef4\u5ea6\u4e3a1\n    //\u7ebf\u6027\u6c42\u89e3\u5668\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); \n    //\u7a00\u758f\u77e9\u9635\u6c42\u89e3\n    Block* solver_ptr = new Block( linearSolver );     \n    //\u8fed\u4ee3\u7b97\u6cd5 \u4ece\u4e0b\u9762\u8fd9\u4e09\u884c \u68af\u5ea6\u4e0b\u964d\u65b9\u6cd5\uff0c\u4ece\u9ad8\u65af\u725b\u987fGN,  \u83b1\u6587\u8d1d\u683c\uff0d\u9a6c\u5938\u7279\u65b9\u6cd5LM, DogLeg\u4e2d\u9009\u62e9\u4e00\u4e2a\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    //\u4f18\u5316\u6a21\u578b\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    // // \u6784\u5efa\u56fe\u4f18\u5316\uff0c\u5148\u8bbe\u5b9ag2o\n    // typedef g2o::BlockSolver< g2o::BlockSolverTraits<3,1> > Block;  // \u6bcf\u4e2a\u8bef\u5dee\u9879\u4f18\u5316\u53d8\u91cf\u7ef4\u5ea6\u4e3a3\uff0c\u8bef\u5dee\u503c\u7ef4\u5ea6\u4e3a1\n    // Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    // Block* solver_ptr = new Block( std::unique_ptr<Block::LinearSolverType>(linearSolver) );      // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n    // // \u68af\u5ea6\u4e0b\u964d\u65b9\u6cd5\uff0c\u4eceGN, LM, DogLeg \u4e2d\u9009\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;     // \u56fe\u6a21\u578b\n    // optimizer.setAlgorithm( solver );   // \u8bbe\u7f6e\u6c42\u89e3\u5668\n    // optimizer.setVerbose( true );       // \u6253\u5f00\u8c03\u8bd5\u8f93\u51fa\n    \n    // \u5f80\u56fe\u4e2d\u589e\u52a0\u9876\u70b9\n    CurveFittingVertex* v = new CurveFittingVertex();\n    v->setEstimate( Eigen::Vector3d(0,0,0) );\n    v->setId(0);\n    optimizer.addVertex( v );\n    \n    // \u5f80\u56fe\u4e2d\u589e\u52a0\u8fb9\n    for ( int i=0; i<N; i++ )\n    {\n        CurveFittingEdge* edge = new CurveFittingEdge( x_data[i] );\n        edge->setId(i);\n        edge->setVertex( 0, v );                // \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n        edge->setMeasurement( y_data[i] );      // \u89c2\u6d4b\u6570\u503c\n        edge->setInformation( Eigen::Matrix<double,1,1>::Identity()*1/(w_sigma*w_sigma) ); // \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n        optimizer.addEdge( edge );\n    }\n    \n    // \u6267\u884c\u4f18\u5316\n    cout<<\"start optimization\"<<endl;\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    optimizer.initializeOptimization();\n    optimizer.optimize(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    // \u8f93\u51fa\u4f18\u5316\u503c\n    Eigen::Vector3d abc_estimate = v->estimate();\n    cout<<\"estimated model: \"<<abc_estimate.transpose()<<endl;\n    \n    return 0;\n}", "meta": {"hexsha": "f198dafc7dc4fe9db373e66f2c115d0198dc2e0c", "size": 6462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "5.\u975e\u7ebf\u6027\u4f18\u5316/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.\u975e\u7ebf\u6027\u4f18\u5316/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.\u975e\u7ebf\u6027\u4f18\u5316/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": "#include <tiny.h>\n#include <convex.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(convex_simplex);\n\nBOOST_AUTO_TEST_CASE(simplex_testing)\n{\n    typedef tiny::MathTypes<double>      math_types;\n    typedef math_types::vector3_type     V;\n    \n    typedef convex::Simplex<V>           S;\n    \n    V const not_in_simplex = V::make(1.5, 5.0, 1.0);\n    \n    S simplex;\n    \n    // Vertify that simplex have been initialized correctly as being empty and ``zeroed''\n    BOOST_CHECK( simplex.m_bitmask == 0u );\n    for(size_t i=0u; i<4; ++i)\n    {\n        BOOST_CHECK( simplex.m_w[0] == 0.0 );\n        for(size_t j=0u; j<3; ++j)\n        {\n            BOOST_CHECK( simplex.m_v[i](j) == 0.0 );\n            BOOST_CHECK( simplex.m_a[i](j) == 0.0 );\n            BOOST_CHECK( simplex.m_b[i](j) == 0.0 );\n        }\n    }\n    \n    // Vertify how different query methods behave on an empty Simplex\n    \n    BOOST_CHECK( !convex::is_point_in_simplex( not_in_simplex, simplex ) );\n    \n    BOOST_CHECK( !convex::is_full_simplex(simplex) );\n    \n    BOOST_CHECK( convex::dimension(simplex) == 0u );\n    \n    int bit_A    = 0;\n    size_t idx_A = 0;\n    BOOST_CHECK_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A ), std::invalid_argument );\n    \n    int bit_B    = 0;\n    size_t idx_B = 0;\n    BOOST_CHECK_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B ), std::invalid_argument );\n    \n    int bit_C    = 0;\n    size_t idx_C = 0;\n    BOOST_CHECK_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ), std::invalid_argument );\n    \n    // Next try to insert one simplex vertex into the simplex\n    \n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const a1 = V::make(1.0, 1.0, 0.0);\n    V const b1 = V::make(1.0, 0.0, 1.0);\n    \n    BOOST_CHECK_NO_THROW( convex::add_point_to_simplex( p1, a1, b1, simplex ) );\n    \n    // Verify how differnt query method works on a 1-simplex\n    BOOST_CHECK( !convex::is_full_simplex(simplex) );\n    BOOST_CHECK( convex::dimension(simplex) == 1u );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A ) );\n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    BOOST_CHECK_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B ), std::logic_error );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    bit_C  = 0xFFFF;\n    idx_C  = 0xFFFF;\n    BOOST_CHECK_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ), std::logic_error );\n    \n    BOOST_CHECK( !convex::is_point_in_simplex( not_in_simplex, simplex ) );\n    BOOST_CHECK(  convex::is_point_in_simplex( p1, simplex )             );\n    \n    // Next try to insert one more simplex vertex into the simplex\n    \n    V const p2 = V::make(2.0, 0.5, 1.0);\n    V const a2 = V::make(2.0, 1.0, 7.0);\n    V const b2 = V::make(2.0, 0.5, 1.0);\n    \n    BOOST_CHECK_NO_THROW( convex::add_point_to_simplex( p2, a2, b2, simplex ) );\n    \n    BOOST_CHECK( !convex::is_full_simplex(simplex) );\n    BOOST_CHECK( convex::dimension(simplex) == 2u );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A ) );\n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B ) );\n    \n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    BOOST_CHECK( bit_B == 2 );\n    BOOST_CHECK( idx_B == 1 );\n    BOOST_CHECK( simplex.m_v[idx_B] == p2 );\n    BOOST_CHECK( simplex.m_a[idx_B] == a2 );\n    BOOST_CHECK( simplex.m_b[idx_B] == b2 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    bit_C  = 0xFFFF;\n    idx_C  = 0xFFFF;\n    BOOST_CHECK_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ), std::logic_error );\n    \n    BOOST_CHECK( !convex::is_point_in_simplex( not_in_simplex, simplex ) );\n    BOOST_CHECK(  convex::is_point_in_simplex( p1, simplex )             );\n    BOOST_CHECK(  convex::is_point_in_simplex( p2, simplex )             );\n    \n    // Insert one more simplex vertex\n    \n    V const p3 = V::make(2.3, 7.5, 1.2);\n    V const a3 = V::make(2.1, 1.1, 2.3);\n    V const b3 = V::make(2.2, 2.5, 0.1);\n    \n    BOOST_CHECK_NO_THROW( convex::add_point_to_simplex( p3, a3, b3, simplex ) );\n    \n    BOOST_CHECK( !convex::is_full_simplex(simplex) );\n    BOOST_CHECK( convex::dimension(simplex) == 3u );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A ) );\n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B ) );\n    \n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    BOOST_CHECK( bit_B == 2 );\n    BOOST_CHECK( idx_B == 1 );\n    BOOST_CHECK( simplex.m_v[idx_B] == p2 );\n    BOOST_CHECK( simplex.m_a[idx_B] == a2 );\n    BOOST_CHECK( simplex.m_b[idx_B] == b2 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    bit_C  = 0xFFFF;\n    idx_C  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ) );\n    \n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    BOOST_CHECK( bit_B == 2 );\n    BOOST_CHECK( idx_B == 1 );\n    BOOST_CHECK( simplex.m_v[idx_B] == p2 );\n    BOOST_CHECK( simplex.m_a[idx_B] == a2 );\n    BOOST_CHECK( simplex.m_b[idx_B] == b2 );\n    \n    BOOST_CHECK( bit_C == 4 );\n    BOOST_CHECK( idx_C == 2 );\n    BOOST_CHECK( simplex.m_v[idx_C] == p3 );\n    BOOST_CHECK( simplex.m_a[idx_C] == a3 );\n    BOOST_CHECK( simplex.m_b[idx_C] == b3 );\n    \n    BOOST_CHECK( !convex::is_point_in_simplex( not_in_simplex, simplex ) );\n    BOOST_CHECK(  convex::is_point_in_simplex( p1, simplex )             );\n    BOOST_CHECK(  convex::is_point_in_simplex( p2, simplex )             );\n    BOOST_CHECK(  convex::is_point_in_simplex( p3, simplex )             );\n    \n    // Insert one more vertex then we have a full simplex\n    \n    V const p4 = V::make(1.3, 1.5, 1.2);\n    V const a4 = V::make(1.1, 1.1, 1.3);\n    V const b4 = V::make(1.2, 1.5, 1.1);\n    \n    BOOST_CHECK_NO_THROW( convex::add_point_to_simplex( p4, a4, b4, simplex ) );\n    \n    BOOST_CHECK( convex::is_full_simplex(simplex) );\n    BOOST_CHECK( convex::dimension(simplex) == 4u );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A ) );\n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B ) );\n    \n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    BOOST_CHECK( bit_B == 2 );\n    BOOST_CHECK( idx_B == 1 );\n    BOOST_CHECK( simplex.m_v[idx_B] == p2 );\n    BOOST_CHECK( simplex.m_a[idx_B] == a2 );\n    BOOST_CHECK( simplex.m_b[idx_B] == b2 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    bit_C  = 0xFFFF;\n    idx_C  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ) );\n    \n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    BOOST_CHECK( bit_B == 2 );\n    BOOST_CHECK( idx_B == 1 );\n    BOOST_CHECK( simplex.m_v[idx_B] == p2 );\n    BOOST_CHECK( simplex.m_a[idx_B] == a2 );\n    BOOST_CHECK( simplex.m_b[idx_B] == b2 );\n    \n    BOOST_CHECK( bit_C == 4 );\n    BOOST_CHECK( idx_C == 2 );\n    BOOST_CHECK( simplex.m_v[idx_C] == p3 );\n    BOOST_CHECK( simplex.m_a[idx_C] == a3 );\n    BOOST_CHECK( simplex.m_b[idx_C] == b3 );\n    \n    BOOST_CHECK( simplex.m_v[3] == p4 );\n    BOOST_CHECK( simplex.m_a[3] == a4 );\n    BOOST_CHECK( simplex.m_b[3] == b4 );\n    \n    BOOST_CHECK( !convex::is_point_in_simplex( not_in_simplex, simplex ) );\n    BOOST_CHECK(  convex::is_point_in_simplex( p1, simplex )             );\n    BOOST_CHECK(  convex::is_point_in_simplex( p2, simplex )             );\n    BOOST_CHECK(  convex::is_point_in_simplex( p3, simplex )             );\n    BOOST_CHECK(  convex::is_point_in_simplex( p4, simplex )             );\n    \n    // Test what happens if we try to insert five vertices into the simplex\n    \n    V const p5 = V::make(2.3, 2.5, 2.2);\n    V const a5 = V::make(2.1, 2.1, 2.3);\n    V const b5 = V::make(2.2, 2.5, 2.1);\n    \n    BOOST_CHECK_THROW( convex::add_point_to_simplex( p5, a5, b5, simplex ), std::logic_error );\n    \n    // Now let us erase one of the simplex vertices\n    \n    simplex.m_bitmask = simplex.m_bitmask & ~bit_B;\n    \n    BOOST_CHECK( !convex::is_full_simplex(simplex) );\n    BOOST_CHECK( convex::dimension(simplex) == 3u );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A ) );\n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B ) );\n    \n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    BOOST_CHECK( bit_B == 4 );\n    BOOST_CHECK( idx_B == 2 );\n    BOOST_CHECK( simplex.m_v[idx_B] == p3 );\n    BOOST_CHECK( simplex.m_a[idx_B] == a3 );\n    BOOST_CHECK( simplex.m_b[idx_B] == b3 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    bit_C  = 0xFFFF;\n    idx_C  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ) );\n    \n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    BOOST_CHECK( bit_B == 4 );\n    BOOST_CHECK( idx_B == 2 );\n    BOOST_CHECK( simplex.m_v[idx_B] == p3 );\n    BOOST_CHECK( simplex.m_a[idx_B] == a3 );\n    BOOST_CHECK( simplex.m_b[idx_B] == b3 );\n    \n    BOOST_CHECK( bit_C == 8 );\n    BOOST_CHECK( idx_C == 3 );\n    BOOST_CHECK( simplex.m_v[idx_C] == p4 );\n    BOOST_CHECK( simplex.m_a[idx_C] == a4 );\n    BOOST_CHECK( simplex.m_b[idx_C] == b4 );\n    \n    BOOST_CHECK( !convex::is_point_in_simplex( not_in_simplex, simplex ) );\n    BOOST_CHECK(  convex::is_point_in_simplex( p1, simplex )             );\n    BOOST_CHECK( !convex::is_point_in_simplex( p2, simplex )             );\n    BOOST_CHECK(  convex::is_point_in_simplex( p3, simplex )             );\n    BOOST_CHECK(  convex::is_point_in_simplex( p4, simplex )             );\n    \n    // Let us erase one more simplex\n    \n    simplex.m_bitmask = simplex.m_bitmask & ~bit_B;\n    \n    BOOST_CHECK( !convex::is_full_simplex(simplex) );\n    BOOST_CHECK( convex::dimension(simplex) == 2u );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A ) );\n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B ) );\n    \n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    BOOST_CHECK( bit_B == 8 );\n    BOOST_CHECK( idx_B == 3 );\n    BOOST_CHECK( simplex.m_v[idx_B] == p4 );\n    BOOST_CHECK( simplex.m_a[idx_B] == a4 );\n    BOOST_CHECK( simplex.m_b[idx_B] == b4 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    bit_C  = 0xFFFF;\n    idx_C  = 0xFFFF;\n    BOOST_CHECK_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ), std::logic_error );\n    \n    BOOST_CHECK( !convex::is_point_in_simplex( not_in_simplex, simplex ) );\n    BOOST_CHECK(  convex::is_point_in_simplex( p1, simplex )             );\n    BOOST_CHECK( !convex::is_point_in_simplex( p2, simplex )             );\n    BOOST_CHECK( !convex::is_point_in_simplex( p3, simplex )             );\n    BOOST_CHECK(  convex::is_point_in_simplex( p4, simplex )             );\n    \n    // Insert a new simplex vertex\n    \n    BOOST_CHECK_NO_THROW( convex::add_point_to_simplex( p5, a5, b5, simplex ) );\n    \n    BOOST_CHECK( !convex::is_full_simplex(simplex) );\n    BOOST_CHECK( convex::dimension(simplex) == 3u );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A ) );\n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B ) );\n    \n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    BOOST_CHECK( bit_B == 2 );\n    BOOST_CHECK( idx_B == 1 );\n    BOOST_CHECK( simplex.m_v[idx_B] == p5 );\n    BOOST_CHECK( simplex.m_a[idx_B] == a5 );\n    BOOST_CHECK( simplex.m_b[idx_B] == b5 );\n    \n    bit_A  = 0xFFFF;\n    idx_A  = 0xFFFF;\n    bit_B  = 0xFFFF;\n    idx_B  = 0xFFFF;\n    bit_C  = 0xFFFF;\n    idx_C  = 0xFFFF;\n    BOOST_CHECK_NO_THROW( convex::get_used_indices( simplex.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ) );\n    \n    BOOST_CHECK( bit_A == 1 );\n    BOOST_CHECK( idx_A == 0 );\n    BOOST_CHECK( simplex.m_v[idx_A] == p1 );\n    BOOST_CHECK( simplex.m_a[idx_A] == a1 );\n    BOOST_CHECK( simplex.m_b[idx_A] == b1 );\n    \n    BOOST_CHECK( bit_B == 2 );\n    BOOST_CHECK( idx_B == 1 );\n    BOOST_CHECK( simplex.m_v[idx_B] == p5 );\n    BOOST_CHECK( simplex.m_a[idx_B] == a5 );\n    BOOST_CHECK( simplex.m_b[idx_B] == b5 );\n    \n    BOOST_CHECK( bit_C == 8 );\n    BOOST_CHECK( idx_C == 3 );\n    BOOST_CHECK( simplex.m_v[idx_C] == p4 );\n    BOOST_CHECK( simplex.m_a[idx_C] == a4 );\n    BOOST_CHECK( simplex.m_b[idx_C] == b4 );\n    \n    BOOST_CHECK( !convex::is_point_in_simplex( not_in_simplex, simplex ) );\n    BOOST_CHECK(  convex::is_point_in_simplex( p1, simplex )             );\n    BOOST_CHECK( !convex::is_point_in_simplex( p2, simplex )             );\n    BOOST_CHECK( !convex::is_point_in_simplex( p3, simplex )             );\n    BOOST_CHECK(  convex::is_point_in_simplex( p4, simplex )             );\n    BOOST_CHECK(  convex::is_point_in_simplex( p5, simplex )             );\n    \n}\n\n// 2011-11-12: Kenny: The degenerate tests always test if a tetrahedron will be degenerate, what about triangle and line cases?\n// 2011-11-12: Kenny: It seems to me that you assume some order on the simplex vertices. In principle one could have bitmask = 11 = 13 = 14 = 14, corresponding to an used mask 0111, 1011, 1101, 1110. Does this order have any influence on your test? The same goes for triangle and line cases.\n// 2011-11-12: Kenny: There is no tests that confirm non-degenerate point is correctly classified.\n\nBOOST_AUTO_TEST_CASE(simplex_degenerate_point)\n{\n    typedef tiny::MathTypes<double>        math_types;\n    typedef math_types::vector3_type       V;\n    typedef math_types::real_type          T;\n    typedef convex::Simplex<V>             S;\n    \n    S simplex;\n    \n    // Vertify that simplex have been initialized correctly as being empty and ``zeroed''\n    BOOST_CHECK( simplex.m_bitmask == 0u );\n    \n    for(size_t i=0u; i<100u; ++i)\n    {\n        V const rand_in0 = V::random();\n        V const rand_in1 = V::random();\n        V const rand_in2 = V::random();\n        \n        simplex.m_v[0] = rand_in0;\n        simplex.m_v[1] = rand_in1;\n        simplex.m_v[2] = rand_in2;\n        simplex.m_bitmask = 7;\n\n        bool const is_degenerate = convex::is_degenerate_point(rand_in1, simplex);\n        BOOST_CHECK( is_degenerate == true);\n    }\n    \n    for(size_t i=0u; i<100u; ++i)\n    {\n        V const rand_in0 = V::random();\n        V const rand_in1 = V::random();\n        V const rand_in2 = V::random();\n        simplex.m_v[0] = rand_in0;\n        simplex.m_v[1] = rand_in1;\n        simplex.m_v[2] = rand_in2;\n        simplex.m_bitmask = 7;\n        \n        // 2011-11-12: Kenny Why not use tiny::Random value; w0 = value(); ????\n        T w0 = std::rand()/RAND_MAX;\n        T w1 = std::rand()/RAND_MAX;\n        \n        // 2011-11-12: Kenny Why use a while loop? You could just do tiny::Random value = tiny::Random( 0, 0.5) or someting like that? Or just divide by some positive number larger than or equal 2?\n        // 2011-11-12: Kenny Why not use value_traits or hardwire 1 to the floating point precision used in the test?\n        while (w0+w1 >= 1) \n        {\n            w0 = std::rand()/RAND_MAX;\n            w1 = std::rand()/RAND_MAX;\n        }\n        \n        // 2011-11-12: Kenny Why not use value_traits or hardwire 1 to the floating point precision used in the test?\n        // 2011-11-12: Kenny: If by design you initialize w0 and w1 to sum to one instead of using the while loop then all w's could be const declared.\n        T w2 = 1 - w0 - w1;\n        \n        V const new_in_plane = w0*rand_in0 + w1*rand_in1 + w2*rand_in2;\n        \n        bool const is_degenerate = convex::is_degenerate_point(new_in_plane, simplex);\n        BOOST_CHECK( is_degenerate == true);\n    }\n\n}\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "3af7cb84a22b3e933d0c6d538f54669a790bcf41", "size": 19988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/CONVEX/unit_tests/convex_simplex/convex_simplex.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/FOUNDATION/CONVEX/unit_tests/convex_simplex/convex_simplex.cpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/CONVEX/unit_tests/convex_simplex/convex_simplex.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": 36.8103130755, "max_line_length": 291, "alphanum_fraction": 0.614018411, "num_tokens": 6249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5998957227243822}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <boost/math/special_functions/laguerre.hpp>\n#include <eve/module/polynomial.hpp>\n\n//==================================================================================================\n//== Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of laguerre on wide\"\n        , eve::test::simd::ieee_reals\n\n        )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  using wi_t = eve::as_integer_t<T>;\n  using i_t  = eve::as_integer_t<v_t>;\n  TTS_EXPR_IS( eve::laguerre(i_t(), T())  , T);\n  TTS_EXPR_IS( eve::laguerre(wi_t(), T())  , T);\n  TTS_EXPR_IS( eve::laguerre(i_t(), v_t())  , v_t);\n  TTS_EXPR_IS( eve::laguerre(wi_t(), v_t())  , T);\n\n};\n\n//==================================================================================================\n//== laguerre tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of laguerre on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::between(-1, 1), eve::test::as_integer(eve::test::ramp(0)))\n        )\n  <typename T, typename I>(T const& a0,I const & i0)\n{\n  using v_t = eve::element_type_t<T>;\n  auto eve__laguerrev  =  [](auto n, auto x) { return eve::laguerre(n, x); };\n  for(unsigned int n=0; n < 5; ++n)\n  {\n    auto boost_laguerre =  [&](auto i, auto) { return boost::math::laguerre(n, a0.get(i)); };\n    TTS_ULP_EQUAL(eve__laguerrev(n, a0), T(boost_laguerre), 1024);\n  }\n  auto boost_laguerrev =  [&](auto i, auto) { return boost::math::laguerre(i0.get(i), a0.get(i)); };\n  TTS_RELATIVE_EQUAL(eve__laguerrev(i0    , a0), T(boost_laguerrev), 0.01);\n  for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n  {\n    auto boost_laguerre2 =  [&](auto i, auto) { return boost::math::laguerre(i0.get(i), a0.get(j)); };\n    TTS_RELATIVE_EQUAL(eve__laguerrev(i0 , a0.get(j)), T(boost_laguerre2), 0.01);\n  }\n  for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n  {\n    for(unsigned int n=0; n < eve::cardinal_v<T>; ++n)\n    {\n      TTS_RELATIVE_EQUAL(eve__laguerrev(i0.get(j) , a0.get(n)), v_t(boost::math::laguerre(i0.get(j), a0.get(n))), 0.01);\n    }\n  }\n};\n", "meta": {"hexsha": "b469111abbbd6a25f8d2260f1405e01debb88912", "size": 2569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/polynomial/laguerre.cpp", "max_stars_repo_name": "clayne/eve", "max_stars_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/polynomial/laguerre.cpp", "max_issues_repo_name": "clayne/eve", "max_issues_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/polynomial/laguerre.cpp", "max_forks_repo_name": "clayne/eve", "max_forks_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.435483871, "max_line_length": 120, "alphanum_fraction": 0.4803425457, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.5998957184616077}}
{"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": "//==============================================================================\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_LOGNPDF_HPP_INCLUDED\n#define NT2_STATISTICS_FUNCTIONS_GENERIC_LOGNPDF_HPP_INCLUDED\n#include <nt2/statistics/functions/lognpdf.hpp>\n#include <boost/assert.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/functions/globalall.hpp>\n#include <nt2/include/functions/if_else.hpp>\n#include <nt2/include/functions/is_gez.hpp>\n#include <nt2/include/functions/is_lez.hpp>\n#include <nt2/include/functions/log.hpp>\n#include <nt2/include/functions/normpdf.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( lognpdf_, tag::cpu_\n                              , (A0)\n                              , (generic_< floating_<A0> >)\n                              )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      A0 x = if_else(is_lez(a0), Inf<A0>(), a0);\n      return normpdf(log(x))/x;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( lognpdf_, 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        A0 x = if_else(is_lez(a0), Inf<A0>(), a0);\n        return normpdf(log(x), a1)/x;\n      }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( lognpdf_, 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_gez(a2)), \"sigma(s) must be positive\");\n      A0 x = if_else(is_lez(a0), Inf<A0>(), a0);\n      return  normpdf(log(x), a1, a2)/x;\n    }\n  };\n\n\n} }\n\n#endif\n", "meta": {"hexsha": "4ba51550a9ccb0b5d8141251311ba093c08fa24e", "size": 2345, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/statistics/include/nt2/statistics/functions/generic/lognpdf.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/lognpdf.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/lognpdf.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 33.5, "max_line_length": 85, "alphanum_fraction": 0.5142857143, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5998718702773428}}
{"text": "/**\n * @file  maximumprinciple_main.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 <Eigen/Dense>\n#include <Eigen/SparseCholesky>\n#include <functional>\n#include <iostream>\n\n#include \"maximumprinciple.h\"\n\nusing namespace MaximumPrinciple;\n\nint main() {\n  /* SAM_LISTING_BEGIN_3 */\n  unsigned int M = 4;\n  double c = 0.99;\n  std::function<double(double, double)> f = [](double x, double y) {\n    double ret = 0.0;\n    //====================\n    // Your code goes here\n    //====================\n    return ret;\n  };\n\n  Eigen::SimplicialLLT<Eigen::SparseMatrix<double>> solver;\n  Eigen::VectorXd phi = computeLoadVector(M, f);\n\n  Eigen::SparseMatrix<double> A = computeGalerkinMatrix(M, c);\n  Eigen::VectorXd mu = solver.compute(A).solve(phi);\n  std::cout << \"mu = \" << std::endl << mu << std::endl;\n  /* SAM_LISTING_END_3 */\n  // Output of inverse Galerkin matrix\n  Eigen::MatrixXd A_dense = A;\n  std::cout << \"Inverse of Galerkin matrix for M = 4, c = 0.99\" << std::endl\n            << A_dense.partialPivLu().inverse() << std::endl;\n\n  Eigen::SparseMatrix<double> A_TR = computeGalerkinMatrixTR(M, c);\n  Eigen::VectorXd mu_TR = solver.compute(A_TR).solve(phi);\n  std::cout << \"mu_TR = \" << std::endl << mu_TR << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "5289ac9e459dffcf86d809ac0fb5faa5b69d609b", "size": 1339, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MaximumPrinciple/templates/maximumprinciple_main.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/MaximumPrinciple/templates/maximumprinciple_main.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/MaximumPrinciple/templates/maximumprinciple_main.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 27.8958333333, "max_line_length": 76, "alphanum_fraction": 0.6370425691, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5998718702773428}}
{"text": "// C++ standard libs\n#include <algorithm>\n#include <exception>\n#include <queue>\n#include <stack>\n#include <tuple>\n#include <unordered_set>\n\n// Outside libs\n#include <boost/functional/hash.hpp>\n#include <personal.hpp>\n\n// Local libs\n#include \"include/knight.hpp\"\n\nnamespace kc{\n//==================================================================================\n// Tools\n//==================================================================================\nsize_t knight_steps(size_t board_size, int8_t opt_level/*=0*/) {\n    size_t solution;\n    switch(opt_level) {\n        case 0: solution = knight_steps_bfs(board_size); break;\n        case 1: solution = knight_steps_astar(board_size); break;\n        case 2: solution = knight_steps_parallel(board_size); break;\n    }\n    return solution;\n}\n\nvoid print_pos(const Pos& pos) {\n    std::cout << \"Pos: (\" << pos.first << \", \" << pos.second << \")\\n\";\n}\n\nvoid print_all(const Pos& pos, size_t steps) {\n    std::cout << \"Pos: (\" << pos.first << \", \" << pos.second \n        << \"); Steps: \" << steps << std::endl;\n}\n\n//==================================================================================\n// Breadth First\n//==================================================================================\nsize_t knight_steps_bfs(size_t board_size) {\n    // Initialize\n    int n = board_size;\n    std::queue<std::pair<Pos, size_t>> options;\n    Pos goal = std::make_pair(n-1, n-1);\n    Pos start = std::make_pair(0,0);\n    options.push(std::make_pair(start,0));\n    std::unordered_set<Pos, boost::hash<Pos>> visited;\n\n    std::vector<Pos> movement = {std::make_pair(1,2), std::make_pair(2,1),\n        std::make_pair(2,-1), std::make_pair(1,-2)};\n\n    auto bounds_check = [&](int num) -> bool {\n        return ((num >= 0) && (num < n));\n    };\n\n    while (!options.empty()) {\n        // Remove from queue\n        auto current = options.front();\n        options.pop();\n        Pos current_pos = current.first;\n        size_t current_steps = current.second;\n        //print_all(current_pos, current_steps);\n\n        // Check if visited before\n        if (visited.count(current_pos) > 0) {\n            continue;\n        } else {\n            visited.insert(current_pos);\n        }\n        \n        // Check if done\n        if (current_pos == goal) {\n            return current_steps;\n        }\n\n        // Otherwise add new options to queue\n        for (auto& delta: movement) {\n            auto forward_x = current_pos.first + delta.first;\n            auto forward_y = current_pos.second + delta.second;\n            auto back_x = current_pos.first - delta.first;\n            auto back_y = current_pos.second - delta.second;\n            if ((bounds_check(forward_x)) && (bounds_check(forward_y))) {\n                Pos forward_move = std::make_pair(forward_x, forward_y);\n                options.push(std::make_pair(forward_move, current_steps+1));\n            }\n            if ((bounds_check(back_x)) && (bounds_check(back_y))) {\n                Pos back_move = std::make_pair(back_x, back_y);\n                options.push(std::make_pair(back_move, current_steps+1));\n            }\n        }\n    }\n    return 0;\n}\n\n//==================================================================================\n// A* Star\n//==================================================================================\nsize_t knight_steps_astar(size_t board_size) {\n    // Initialize\n    // We want to prioritize a lower weight\n    // (Pos, steps, weight)\n    using Option = std::tuple<Pos, size_t, int>;\n    int n = board_size;\n    auto queue_sort = [] (const Option& a, const Option& b) {\n        return std::get<2>(a) > std::get<2>(b);\n    };\n\n    std::priority_queue<\n        Option, std::vector<Option>, decltype(queue_sort)> \n        options(queue_sort);\n    Pos goal = std::make_pair(n-1, n-1);\n    Pos start = std::make_pair(0,0);\n    auto calc_weight = [&](const Pos& current_pos, size_t steps) -> size_t {\n        auto future = std::min(std::abs((current_pos.first - goal.first)),std::abs((current_pos.second - goal.second)));\n        auto past = steps;\n        return future + past;\n    };\n    options.push(std::make_tuple(start, 0, calc_weight(start,0)));\n    std::unordered_set<Pos, boost::hash<Pos>> visited;\n\n    std::vector<Pos> movement = {std::make_pair(1,2), std::make_pair(2,1),\n        std::make_pair(2,-1), std::make_pair(1,-2)};\n\n    auto bounds_check = [&](int num) -> bool {\n        return ((num >= 0) && (num < n));\n    };\n\n    while (!options.empty()) {\n        // Remove from queue\n        auto current = options.top();\n        options.pop();\n        Pos current_pos = std::get<0>(current);\n        int current_steps = std::get<1>(current);\n        //print_all(current_pos, current_steps);\n\n        // Check if visited before\n        if (visited.count(current_pos) > 0) {\n            continue;\n        } else {\n            visited.insert(current_pos);\n        }\n        \n        // Check if done\n        if (current_pos == goal) {\n            return current_steps;\n        }\n\n        // Otherwise add new options to queue\n        for (auto& delta: movement) {\n            auto forward_x = current_pos.first + delta.first;\n            auto forward_y = current_pos.second + delta.second;\n            auto back_x = current_pos.first - delta.first;\n            auto back_y = current_pos.second - delta.second;\n            if ((bounds_check(forward_x)) && (bounds_check(forward_y))) {\n                Pos forward_move = std::make_pair(forward_x, forward_y);\n                options.push(std::make_tuple(\n                    forward_move, current_steps+1,calc_weight(forward_move, current_steps+1)\n                ));\n            }\n            if ((bounds_check(back_x)) && (bounds_check(back_y))) {\n                Pos back_move = std::make_pair(back_x, back_y);\n                options.push(std::make_tuple(\n                    back_move, current_steps+1, calc_weight(back_move, current_steps+1)\n                ));\n            }\n        }\n    }\n    return 0;\n}\n\n//==================================================================================\n// Async\n//==================================================================================\nsize_t knight_steps_async(size_t board_size) {\n    // Initialize\n    // We want to prioritize a lower weight\n    // (Pos, steps, weight)\n    using Option = std::tuple<Pos, size_t, int>;\n    int n = board_size;\n    auto queue_sort = [] (const Option& a, const Option& b) {\n        return std::get<2>(a) > std::get<2>(b);\n    };\n\n    std::priority_queue<\n        Option, std::vector<Option>, decltype(queue_sort)> \n        options(queue_sort);\n    Pos goal = std::make_pair(n-1, n-1);\n    Pos start = std::make_pair(0,0);\n    auto calc_weight = [&](const Pos& current_pos, size_t steps) -> size_t {\n        auto future = std::min(std::abs((current_pos.first - goal.first)),std::abs((current_pos.second - goal.second)));\n        auto past = steps;\n        return future + past;\n    };\n    options.push(std::make_tuple(start, 0, calc_weight(start,0)));\n    std::unordered_set<Pos, boost::hash<Pos>> visited;\n\n    std::vector<Pos> movement = {std::make_pair(1,2), std::make_pair(2,1),\n        std::make_pair(2,-1), std::make_pair(1,-2)};\n\n    auto bounds_check = [&](int num) -> bool {\n        return ((num >= 0) && (num < n));\n    };\n\n    while (!options.empty()) {\n        // Remove from queue\n        auto current = options.top();\n        options.pop();\n        Pos current_pos = std::get<0>(current);\n        int current_steps = std::get<1>(current);\n        //print_all(current_pos, current_steps);\n\n        // Check if visited before\n        if (visited.count(current_pos) > 0) {\n            continue;\n        } else {\n            visited.insert(current_pos);\n        }\n        \n        // Check if done\n        if (current_pos == goal) {\n            return current_steps;\n        }\n\n        // Otherwise add new options to queue\n        for (auto& delta: movement) {\n            auto forward_x = current_pos.first + delta.first;\n            auto forward_y = current_pos.second + delta.second;\n            auto back_x = current_pos.first - delta.first;\n            auto back_y = current_pos.second - delta.second;\n            if ((bounds_check(forward_x)) && (bounds_check(forward_y))) {\n                Pos forward_move = std::make_pair(forward_x, forward_y);\n                options.push(std::make_tuple(\n                    forward_move, current_steps+1,calc_weight(forward_move, current_steps+1)\n                ));\n            }\n            if ((bounds_check(back_x)) && (bounds_check(back_y))) {\n                Pos back_move = std::make_pair(back_x, back_y);\n                options.push(std::make_tuple(\n                    back_move, current_steps+1, calc_weight(back_move, current_steps+1)\n                ));\n            }\n        }\n    }\n    return 0;\n}\n\n//==================================================================================\n// Parallel\n//==================================================================================\nsize_t knight_steps_parallel(size_t board_size) {\n    return 0;\n}\n\n}\n\n", "meta": {"hexsha": "668815fbe64022bea4dd6a8aa86a15b9e600f249", "size": 9101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/knight.cpp", "max_stars_repo_name": "scotto3394/knight-chess", "max_stars_repo_head_hexsha": "d745b01600dfe8a616cb0d49d177d83ad585ce32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/knight.cpp", "max_issues_repo_name": "scotto3394/knight-chess", "max_issues_repo_head_hexsha": "d745b01600dfe8a616cb0d49d177d83ad585ce32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/knight.cpp", "max_forks_repo_name": "scotto3394/knight-chess", "max_forks_repo_head_hexsha": "d745b01600dfe8a616cb0d49d177d83ad585ce32", "max_forks_repo_licenses": ["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.2751937984, "max_line_length": 120, "alphanum_fraction": 0.5195033513, "num_tokens": 2027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757312, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5998718502090231}}
{"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": "#include <stdexcept>\n\n#include <catch2/catch.hpp>\n#define eigen_assert(x)                                                                       \\\n\tif (!(x)) {                                                                               \\\n\t\tthrow std::runtime_error(#x);                                                         \\\n\t}\n\n#include \"../../src/filters/MultiSensorEKF.h\"\n\n#include <Eigen/Core>\n\nusing namespace filters;\nusing namespace filters::statespace;\n\nTEST_CASE(\"Test Output Jacobian\", \"[filters]\") {\n\tauto outputFunc = [](const Eigen::VectorXd& x, const Eigen::VectorXd& b) {\n\t\treturn (2 * x + b).topRows(x.size()-1);\n\t};\n\n\tEigen::VectorXd std(Eigen::VectorXd::Ones(3));\n\tfilters::statespace::NoiseCovMatX cov(std, 3, 2);\n\tfilters::Output o(3, 2, 3, outputFunc, cov);\n\n\tEigen::VectorXd state(Eigen::VectorXd::Ones(3));\n\n\tEigen::MatrixXd jacobX = o.outputFuncJacobianX(state);\n\tEigen::MatrixXd jacobV = o.outputFuncJacobianV(state);\n\n\tEigen::MatrixXd jacobXTrue(2,3);\n\tjacobXTrue << 2, 0, 0,\n\t\t\t\t  0, 2, 0;\n\n\tREQUIRE((jacobX - jacobXTrue).array().abs().maxCoeff() <= 1e-4);\n\tREQUIRE((jacobV - jacobXTrue/2).array().abs().maxCoeff() <= 1e-4);\n}\n\nTEST_CASE(\"MultiSensorEKF Test Runtime Errors\", \"[filters]\") {\n\tconstexpr int stateDim = 3;\n\tconstexpr int inputDim = 2;\n\n\tauto outputFunc1 = [](const Eigen::VectorXd& x, const Eigen::VectorXd& b) {\n\t\treturn (2 * x + b.topRows(stateDim)).topRows(x.size() - 1);\n\t};\n\tauto outputFunc2 = [](const Eigen::VectorXd& x, const Eigen::VectorXd& b) {\n\t\treturn Eigen::Vector3d::Ones() * ((2 * x + b).norm());\n\t};\n\tauto stateFunc = [](const Vectord<stateDim>& x, const Vectord<inputDim>& u,\n\t\t\t\t\t\tconst Vectord<stateDim>& noise) { return x + noise; };\n\n\tNoiseCovMat<-1,-1,-1> covMat1(Eigen::MatrixXd::Identity(4, 4).eval(), stateDim, 2);\n\tOutput out1(stateDim, 2, 4, outputFunc1, covMat1);\n\tNoiseCovMat<-1,-1,-1> covMat2(Eigen::MatrixXd::Identity(3, 3).eval(), stateDim, 3);\n\tOutput out2(stateDim, 3, 3, outputFunc2, covMat2);\n\tNoiseCovMat<stateDim, stateDim, inputDim> processNoise(\n\t\tEigen::Matrix<double, stateDim, stateDim>::Identity().eval());\n\tstd::array<Output, 2> outputs = {out1, out2};\n\tfilters::MultiSensorEKF<stateDim, inputDim, stateDim, 2> ekf(stateFunc, processNoise, 0.1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t outputs);\n\tREQUIRE_NOTHROW(ekf.predict(Eigen::Vector2d::Zero().eval()));\n\tREQUIRE_NOTHROW(ekf.correct<0>(Eigen::Vector2d::Ones().eval()));\n\tREQUIRE_NOTHROW(ekf.correct<1>(Eigen::Vector3d::Ones().eval() * 3));\n}\n", "meta": {"hexsha": "8823cd18b079c38d0358f763a80208ff9b764f77", "size": 2464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/filters/MultiSensorEKFTest.cpp", "max_stars_repo_name": "huskyroboticsteam/Resurgence", "max_stars_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-23T23:31:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:17:41.000Z", "max_issues_repo_path": "tests/filters/MultiSensorEKFTest.cpp", "max_issues_repo_name": "huskyroboticsteam/Resurgence", "max_issues_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-22T05:33:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T07:01:47.000Z", "max_forks_repo_path": "tests/filters/MultiSensorEKFTest.cpp", "max_forks_repo_name": "huskyroboticsteam/Resurgence", "max_forks_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5, "max_line_length": 95, "alphanum_fraction": 0.6193181818, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5997981450334641}}
{"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 <arm_neon.h>\n#include <array>\n#include <random>\n#include <algorithm>\n#include <iostream>\n#include <cassert>\n#include <cmath>\n#include <functional>\n#include <boost/align/aligned_allocator.hpp>\n#include <utils.hpp>\n\n\nusing namespace std;\nusing dtype = int32_t;\n\nconst size_t MIN_TEST_VEC_SIZE = 32;\nconst size_t MAX_TEST_VEC_SIZE = 65536;\nconst dtype  MAX_ELEMENT_VALUE = 1000;\n\n\nvoid bitonic_sort(int32_t *data_in, int32_t *data_out, int32_t n)\n{\n    static vector<int32_t> merged_0_1(MAX_TEST_VEC_SIZE); \n    static vector<int32_t> merged_2_3(MAX_TEST_VEC_SIZE);\n\n    constexpr int vector_width_in_bytes =  16; //quadword=128bit\n    constexpr int vector_width =  vector_width_in_bytes / sizeof(data_in[0]);\n    int n_div_vec_width= n / vector_width;\n    int log2n = static_cast<int>(log2(n_div_vec_width));\n    assert(exp2(log2n) == n_div_vec_width);\n\n    for (auto i = 0; i < log2n ; ++i)\n    {\n        for (auto j = i ; j >= 0; --j)\n        {\n            int arrow_len = 1<<j;\n            for (auto k = 0; k < n_div_vec_width/2; k++)\n            {\n                bool is_up =  k & (1<<i);\n\n                uint32_t  mask = (1 << j) - 1;\n                size_t upper_idx = ((k & ~mask) << 1) | (k & mask);\n                size_t lower_idx = upper_idx + arrow_len;\n                int32x4_t v_upper = vld1q_s32(&data_in[upper_idx * vector_width]); \n                int32x4_t v_lower = vld1q_s32(&data_in[(upper_idx + arrow_len)*vector_width]); \n                int32x4_t v_min = vminq_s32(v_upper, v_lower);\n                int32x4_t v_max = vmaxq_s32(v_upper, v_lower);\n                auto max_idx = (upper_idx + static_cast<int>(is_up) * arrow_len) * vector_width;\n                auto min_idx = (upper_idx + static_cast<int>(!is_up) * arrow_len) * vector_width;\n                vst1q_s32(&data_in[max_idx], v_max);\n                vst1q_s32(&data_in[min_idx], v_min);\n            }\n        }\n    }\n\n    int32_t *to_merge[4] = {data_in, data_in+1, data_in+2, data_in+3};\n\n    merge_two_cols(to_merge[0], to_merge[1], 4, merged_0_1.data(), n >> 2);\n    merge_two_cols(to_merge[2], to_merge[3], 4, merged_2_3.data(), n >> 2);\n\n    to_merge[0] = merged_0_1.data();\n    to_merge[1] = merged_2_3.data();\n    merge_two_cols(to_merge[0], to_merge[1], 1, data_out, n>>1 );\n}\n\nint main()\n{\n    for (auto vec_size = MIN_TEST_VEC_SIZE; vec_size <= MAX_TEST_VEC_SIZE; vec_size *= 2)\n    {\n        using aligned_vector = vector<dtype,boost::alignment::aligned_allocator<dtype, 128>>;\n        aligned_vector vec(vec_size);\n        randomize(vec, -MAX_ELEMENT_VALUE, MAX_ELEMENT_VALUE);\n        aligned_vector vec_cpy{vec};\n        aligned_vector bitonic_out(vec_size);\n        int time_ref = measure_ms([&vec](){ std::sort(vec.begin(), vec.end(), greater<dtype>());});\n        int time_bitonic = measure_ms([&vec_cpy, &bitonic_out ,vec_size](){ bitonic_sort(vec_cpy.data(), bitonic_out.data(), vec_size);});\n        cout << \"acceleration for \" << vec_size << \" elements = \" << (float)time_ref/time_bitonic << endl;\n        assert(is_sorted(vec, greater_equal<dtype>()));\n        assert(is_sorted(vec_cpy, greater_equal<dtype>(), 4));\n        //for (auto &el : bitonic_result) cout << el << \" \";\n        assert(is_sorted(bitonic_out, greater_equal<dtype>()));\n    }\n    return 0;\n}", "meta": {"hexsha": "6deefce95c5740ca7f1f2360bee2166581963899", "size": 3279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "DanielZel/VectorizedSort", "max_stars_repo_head_hexsha": "34535bb466b8dccf63a5837d8e21385a913146d6", "max_stars_repo_licenses": ["MIT"], "max_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": "DanielZel/VectorizedSort", "max_issues_repo_head_hexsha": "34535bb466b8dccf63a5837d8e21385a913146d6", "max_issues_repo_licenses": ["MIT"], "max_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": "DanielZel/VectorizedSort", "max_forks_repo_head_hexsha": "34535bb466b8dccf63a5837d8e21385a913146d6", "max_forks_repo_licenses": ["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.0357142857, "max_line_length": 138, "alphanum_fraction": 0.6248856359, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5997893741325335}}
{"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": "#ifndef nomad__src__autodiff__second_order_hpp\n#define nomad__src__autodiff__second_order_hpp\n\n#include <iomanip>\n#include <string>\n#include <Eigen/Core>\n\n#include <src/var/var.hpp>\n#include <src/autodiff/first_order.hpp>\n\nnamespace nomad {\n\n  template<class T_var>\n  void second_order_forward_val(const T_var& v) {\n    for (nomad_idx_t i = 1; i <= v.node(); ++i)\n      var_nodes_[i].second_order_forward_val();\n  }\n  \n  template<class T_var>\n  void second_order_reverse_adj(const T_var& v) {\n    var_nodes_[v.node()].second_grad() = 0;\n    for (nomad_idx_t i = v.node(); i > 0; --i)\n      var_nodes_[i].second_order_reverse_adj();\n  }\n\n  template <typename F>\n  typename std::enable_if<is_var<typename F::var_type>::value && F::var_type::order() >= 2, void >::type\n  hessian(const F& functional,\n          const Eigen::VectorXd& x,\n          double& f,\n          Eigen::VectorXd& g,\n          Eigen::MatrixXd& H) {\n    \n    reset();\n    \n    eigen_idx_t d = x.size();\n    \n    try {\n      \n      auto f_var = functional(x);\n      \n      f = f_var.first_val();\n      \n      // First-order\n      first_order_reverse_adj(f_var);\n      \n      for (eigen_idx_t i = 0; i < d; ++i)\n      g(i) = var_nodes_[i + 1].first_grad();\n      \n      // Second-order\n      for (eigen_idx_t i = 0; i < d; ++i) {\n        \n        for (eigen_idx_t j = 0; j < d; ++j)\n        var_nodes_[j + 1].second_val() = static_cast<double>(i == j);\n        \n        second_order_forward_val(f_var);\n        second_order_reverse_adj(f_var);\n        \n        for (eigen_idx_t j = 0; j < d; ++j)\n        H(i, j) = var_nodes_[j + 1].second_grad();\n        \n      }\n      \n      reset();\n      \n    } catch (nomad_error& e) {\n      reset();\n      throw e;\n    }\n    \n  }\n  \n  template <typename F>\n  void hessian(const F& functional,\n               const Eigen::VectorXd& x,\n               Eigen::MatrixXd& H) {\n    double f;\n    Eigen::VectorXd g(x.size());\n    hessian(functional, x, f, g, H);\n  }\n  \n  template <typename F>\n  typename std::enable_if<is_var<typename F::var_type>::value && F::var_type::order() >= 1, void >::type\n  finite_diff_hessian(const F& functional,\n                      const Eigen::VectorXd& x,\n                      Eigen::MatrixXd& H,\n                      const double epsilon = 1e-6) {\n    \n    eigen_idx_t d = x.size();\n    \n    Eigen::VectorXd x_dynam(x);\n    Eigen::VectorXd g_auto(d);\n\n    for (eigen_idx_t i = 0; i < d; ++i) {\n      \n      Eigen::VectorXd g_diff = Eigen::VectorXd::Zero(d);\n      \n      x_dynam(i) += epsilon;\n      gradient(functional, x_dynam, g_auto);\n      g_diff += g_auto;\n      \n      x_dynam(i) -= 2.0 * epsilon;\n      gradient(functional, x_dynam, g_auto);\n      g_diff -= g_auto;\n      \n      x_dynam(i) += epsilon;\n      g_diff /= 2.0 * epsilon;\n      \n      H.col(i) = g_diff;\n      \n    }\n    \n  }\n  \n  template <typename F>\n  void test_hessian(const F& functional,\n                    const Eigen::VectorXd& x,\n                    const double epsilon = 1e-6) {\n    \n    eigen_idx_t d = x.size();\n    \n    Eigen::MatrixXd auto_H(x.size(), x.size());\n    try {\n      hessian(functional, x, auto_H);\n    } catch (nomad_error& e) {\n      std::cout << \"Cannot compute Hessian Test\" << std::endl;\n      throw e;\n    }\n    \n    Eigen::MatrixXd diff_H(x.size(), x.size());\n    try {\n      finite_diff_hessian(functional, x, diff_H, epsilon);\n    } catch (nomad_error& e) {\n      std::cout << \"Cannot compute Hessian Test\" << std::endl;\n      throw e;\n    }\n    \n    std::cout.precision(6);\n    int width = 12;\n    int n_column = 5;\n    \n    std::cout << \"Hessian Test:\" << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"Row\"\n              << std::setw(width) << std::left << \"Column\"\n              << std::setw(width) << std::left << \"Automatic\"\n              << std::setw(width) << std::left << \"Finite\"\n              << std::setw(width) << std::left << \"Delta / \"\n              << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"(i)\"\n              << std::setw(width) << std::left << \"(j)\"\n              << std::setw(width) << std::left << \"Derivative\"\n              << std::setw(width) << std::left << \"Difference\"\n              << std::setw(width) << std::left << \"Stepsize^{2}\"\n              << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    \n    for (eigen_idx_t i = 0; i < d; ++i) {\n      for (eigen_idx_t j = 0; j < d; ++j) {\n        std::cout << \"    \"\n                  << std::setw(width) << std::left << i\n                  << std::setw(width) << std::left << j\n                  << std::setw(width) << std::left << auto_H(i, j)\n                  << std::setw(width) << std::left << diff_H(i, j)\n                  << std::setw(width) << std::left\n                  << (auto_H(i, j) - diff_H(i, j)) / (epsilon * epsilon)\n                  << std::endl;\n      }\n    }\n    \n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << std::endl;\n    \n  }\n  \n  template <typename F>\n  typename std::enable_if<is_var<typename F::var_type>::value && F::var_type::order() >= 2, void >::type\n  hessian_dot_vector(const F& functional,\n                     const Eigen::VectorXd& x,\n                     const Eigen::VectorXd& v,\n                     double& f,\n                     Eigen::VectorXd& g,\n                     Eigen::VectorXd& hessian_dot_v) {\n    \n    reset();\n    \n    eigen_idx_t d = x.size();\n    \n    try {\n      \n      auto f_var = functional(x);\n      \n      f = f_var.first_val();\n      \n      // First-order\n      first_order_reverse_adj(f_var);\n      \n      for (eigen_idx_t i = 0; i < d; ++i)\n      g(i) = var_nodes_[i + 1].first_grad();\n      \n      // Second-order\n      for (eigen_idx_t i = 0; i < d; ++i)\n      var_nodes_[i + 1].second_val() = v(i);\n      \n      second_order_forward_val(f_var);\n      second_order_reverse_adj(f_var);\n      \n      for (eigen_idx_t i = 0; i < d; ++i)\n      hessian_dot_v(i) = var_nodes_[i + 1].second_grad();\n      \n      reset();\n      \n    } catch (nomad_error& e) {\n      reset();\n      throw e;\n    }\n    \n  }\n  \n  template <typename F>\n  void hessian_dot_vector(const F& functional,\n                          const Eigen::VectorXd& x,\n                          const Eigen::VectorXd& v,\n                          Eigen::VectorXd& hessian_dot_v) {\n    double f;\n    Eigen::VectorXd g(x.size());\n    hessian_dot_vector(functional, x, v, f, g, hessian_dot_v);\n  }\n  \n  template <typename F>\n  void test_hessian_dot_vector(const F& functional,\n                               const Eigen::VectorXd& x,\n                               const Eigen::VectorXd& v) {\n    \n    Eigen::MatrixXd H_auto(x.size(), x.size());\n    try {\n      hessian(functional, x, H_auto);\n    } catch (nomad_error& e) {\n      std::cout << \"Cannot compute Hessian Doc Vector Test\" << std::endl;\n      throw e;\n    }\n    \n    Eigen::VectorXd H_dot_v_auto(x.size());\n    try {\n      hessian_dot_vector(functional, x, v, H_dot_v_auto);\n    } catch (nomad_error& e) {\n      std::cout << \"Cannot compute Hessian Doc Vector Test\" << std::endl;\n      throw e;\n    }\n    \n    std::cout.precision(6);\n    int width = 12;\n    int n_column = 3;\n    \n    std::cout << \"Hessian Dot Vector Test:\" << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"Component\"\n              << std::setw(width) << std::left << \"Automatic\"\n              << std::setw(width) << std::left << \"Exact\"\n              << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"(i)\"\n              << std::setw(width) << std::left << \"Derivative\"\n              << std::setw(width) << std::left << \"\"\n              << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    \n    Eigen::VectorXd H_dot_v = H_auto * v;\n    \n    for (eigen_idx_t i = 0; i < x.size(); ++i) {\n      \n      std::cout << \"    \"\n                << std::setw(width) << std::left << i\n                << std::setw(width) << std::left << H_dot_v_auto(i)\n                << std::setw(width) << std::left << H_dot_v(i)\n                << std::endl;\n      \n    }\n    \n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << std::endl;\n    \n  }\n  \n  template <typename F>\n  typename std::enable_if<is_var<typename F::var_type>::value && F::var_type::order() >= 1, void >::type\n  trace_matrix_times_hessian(const F& functional,\n                             const Eigen::VectorXd& x,\n                             const Eigen::MatrixXd& M,\n                             double& f,\n                             Eigen::VectorXd& g,\n                             double& trace_m_times_h) {\n    \n    reset();\n    \n    eigen_idx_t d = x.size();\n\n    try {\n      \n      auto f_var = functional(x);\n      \n      f = f_var.first_val();\n      \n      // First-order\n      first_order_reverse_adj(f_var);\n      \n      for (eigen_idx_t i = 0; i < d; ++i)\n      g(i) = var_nodes_[i + 1].first_grad();\n      \n      // Second-order\n      trace_m_times_h = 0;\n      \n      for (eigen_idx_t i = 0; i < d; ++i) {\n        \n        for (eigen_idx_t j = 0; j < d; ++j)\n        var_nodes_[j + 1].second_val() = M(j, i);\n        \n        second_order_forward_val(f_var);\n        second_order_reverse_adj(f_var);\n        \n        trace_m_times_h += var_nodes_[i + 1].second_grad();\n        \n      }\n      \n      reset();\n      \n    } catch (nomad_error& e) {\n      reset();\n      throw e;\n    }\n    \n  }\n  \n  template <typename F>\n  void trace_matrix_times_hessian(const F& functional,\n                                  const Eigen::VectorXd& x,\n                                  const Eigen::MatrixXd& M,\n                                  double& trace_m_times_h) {\n    double f;\n    Eigen::VectorXd g(x.size());\n    trace_matrix_times_hessian(functional, x, M, f, g, trace_m_times_h);\n  }\n  \n  template <typename F>\n  void test_trace_matrix_times_hessian(const F& functional,\n                                       const Eigen::VectorXd& x,\n                                       const Eigen::MatrixXd& M) {\n    \n    Eigen::MatrixXd H_auto(x.size(), x.size());\n    try {\n      hessian(functional, x, H_auto);\n    } catch (nomad_error& e) {\n      std::cout << \"Cannot compute Trace Matrix Times Hessian Test\" << std::endl;\n      throw e;\n    }\n    \n    double trace_m_times_h = (M * H_auto).trace();\n    \n    double trace_m_times_h_auto;\n    try {\n      trace_matrix_times_hessian(functional, x, M, trace_m_times_h_auto);\n    } catch (nomad_error& e) {\n      std::cout << \"Cannot compute Trace Matrix Times Hessian Test\" << std::endl;\n      throw e;\n    }\n    \n    std::cout.precision(6);\n    int width = 12;\n    int n_column = 2;\n    \n    std::cout << \"Trace Matrix Times Hessian Test:\" << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"Automatic\"\n              << std::setw(width) << std::left << \"Exact\"\n              << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"Derivative\"\n              << std::setw(width) << std::left << \"\"\n              << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    \n    std::cout << \"    \"\n              << std::setw(width) << std::left << trace_m_times_h_auto\n              << std::setw(width) << std::left << trace_m_times_h\n              << std::endl;\n    \n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << std::endl;\n    \n  }\n  \n}\n\n#endif\n", "meta": {"hexsha": "2fb88130b1b267ada46750205a003770812bbdbd", "size": 12317, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/autodiff/second_order.hpp", "max_stars_repo_name": "stan-dev/nomad", "max_stars_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-12-11T20:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T18:59:58.000Z", "max_issues_repo_path": "src/autodiff/second_order.hpp", "max_issues_repo_name": "stan-dev/nomad", "max_issues_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-12-15T08:12:01.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-17T01:36:56.000Z", "max_forks_repo_path": "src/autodiff/second_order.hpp", "max_forks_repo_name": "stan-dev/nomad", "max_forks_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-10-13T17:40:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T19:17:51.000Z", "avg_line_length": 30.1887254902, "max_line_length": 104, "alphanum_fraction": 0.4864820979, "num_tokens": 3307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.599788135928224}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//! \\file\r\n//!\\brief Tests for the transcendental logarithm function of (fixed_point) for a tiny digit range.\r\n\r\n#define BOOST_TEST_MODULE test_negatable_func_log_tiny\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <cmath>\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nnamespace local\r\n{\r\n  template<typename FixedPointType>\r\n  const FixedPointType& tolerance_maker(const int fuzzy_bits)\r\n  {\r\n    static const FixedPointType the_tolerance = ldexp(FixedPointType(1), FixedPointType::resolution + fuzzy_bits);\r\n\r\n    return the_tolerance;\r\n  }\r\n\r\n  template<typename FixedPointType,\r\n           typename FloatPointType = typename FixedPointType::float_type>\r\n  void test_log(const int fuzzy_bits)\r\n  {\r\n    // Use at least 10 resolution bits.\r\n    // Use at least  5 range bits.\r\n\r\n    BOOST_STATIC_ASSERT(-FixedPointType::resolution >= 10);\r\n    BOOST_STATIC_ASSERT( FixedPointType::range      >=  4);\r\n\r\n    const FixedPointType a1(+2L    );                                      const FloatPointType b1(+2L    );\r\n    const FixedPointType a2(+3L    );                                      const FloatPointType b2(+3L    );\r\n    const FixedPointType a3(+4.375L);                                      const FloatPointType b3(+4.375L);\r\n    const FixedPointType a4(+1.125L);                                      const FloatPointType b4(+1.125L);\r\n    const FixedPointType a5(+0.125L);                                      const FloatPointType b5(+0.125L);\r\n    const FixedPointType a6(+0.875L);                                      const FloatPointType b6(+0.875L);\r\n    const FixedPointType a7(FixedPointType( 1) /  3);                      const FloatPointType b7(FloatPointType( 1) /  3);\r\n    const FixedPointType a8(FixedPointType(13) / 10);                      const FloatPointType b8(FloatPointType(13) / 10);\r\n    const FixedPointType a9(boost::math::constants::pi<FixedPointType>()); const FloatPointType b9(boost::math::constants::pi<FloatPointType>());\r\n\r\n    using std::log;\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(log(a1), FixedPointType(log(b1)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(log(a2), FixedPointType(log(b2)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(log(a3), FixedPointType(log(b3)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(log(a4), FixedPointType(log(b4)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(log(a5), FixedPointType(log(b5)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(log(a6), FixedPointType(log(b6)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(log(a7), FixedPointType(log(b7)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(log(a8), FixedPointType(log(b8)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(log(a9), FixedPointType(log(b9)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_func_log_tiny)\r\n{\r\n  typedef boost::fixed_point::negatable<4, -11> fixed_point_type;\r\n\r\n  local::test_log<fixed_point_type>(3);\r\n}\r\n", "meta": {"hexsha": "085955bd85e99c511ff97b25ff66f7e508734e35", "size": 3579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_func_log_tiny.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_func_log_tiny.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_func_log_tiny.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": 51.1285714286, "max_line_length": 146, "alphanum_fraction": 0.6702989662, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.5997492864807837}}
{"text": "//\n// Created by keszocze on 10.10.18.\n//\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <catch2/catch.hpp>\n#include <cudd/cplusplus/cuddObj.hh>\n#include <cudd_helpers.hpp>\n#include <simple.hpp>\n#include <from_papers.hpp>\n\n\n#include <iostream>\n#include <approximation_operators.hpp>\n\n\n\n\n\n/**\n * @brief Hardcoded example from the 2016 ASP-DAC paper by Soeken et al.\n */\nTEST_CASE(\"Example 3 from ASP-DAC 2016 paper\") {\n    Cudd mgr(2);\n\n    std::vector<BDD> fun = abo::example_bdds::example1a(mgr);\n    std::vector<BDD> expected_rounded_down = abo::example_bdds::example1b(mgr);\n    std::vector<BDD> expected_rounded_up = abo::example_bdds::example1c(mgr);\n    std::vector<BDD> expected_rounded = abo::example_bdds::example1d(mgr);\n\n\n    std::vector<BDD> self_rounded_up, self_rounded_down, self_rounded;\n\n    for (const BDD &b : fun) {\n        self_rounded_down.push_back(abo::operators::round_down(mgr, b, 2, 4));\n        self_rounded_up.push_back(abo::operators::round_up(mgr, b, 2, 4));\n        self_rounded.push_back(abo::operators::round_bdd(mgr, b, 2));\n    }\n\n    CHECK(expected_rounded_down == self_rounded_down);\n\n    CHECK(expected_rounded_up == self_rounded_up);\n\n    CHECK(expected_rounded == self_rounded);\n}\n", "meta": {"hexsha": "16c9b8260d3bce58338870e8db82c481190a627e", "size": 1229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/approximation_operations_test.cpp", "max_stars_repo_name": "keszocze/abo", "max_stars_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/approximation_operations_test.cpp", "max_issues_repo_name": "keszocze/abo", "max_issues_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/approximation_operations_test.cpp", "max_forks_repo_name": "keszocze/abo", "max_forks_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T14:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T14:50:31.000Z", "avg_line_length": 26.7173913043, "max_line_length": 79, "alphanum_fraction": 0.707078926, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5995946946209596}}
{"text": "#include <armadillo>\n\nvoid filter_active(mat &m, ivec active) {\n  mat _m(sum(active), m.n_cols);\n  int ind = 0;\n  for (int i = 0; i < (int)active.n_elem; i++) {\n    if (active(i)) {\n      _m.row(ind) = m.row(ind);\n      ind++;\n    }\n  }\n  m = _m;\n}\n\nvoid tag_observe_pos(vec obs, mat pos, vec &mu, mat &sigma) {\n  int k = obs.n_elem;\n  if (k < 2) {\n    return vec(pos.n_cols, fill::zeros); // this will be the only strange position\n  }\n\n  // compute the pose from the linear regression solver\n  mat obs_k = repmat(obs(span(k-1, k-1)), k-1, 1);\n  mat obs = obs(span(0, k-2));\n  mat pos_k = repmat(pos(span(k-1, k-1), span::all), k-1, 1);\n  mat pos = pos_(span(0, k-2), span::all);\n\n  mat A = 2 * pos - repmat(pos_k, pos.n_rows, 1);\n  mat b = obs % obs - obs_k % obs_k - sum(pos % pos, 1) + sum(pos_k % pos_k, 1);\n  \n  mat x = pinv(A.t() * A) * A.t() * b;\n  mu = x.col(0);\n\n  mat diff = repmat(z.t(), pos.n_rows, 1) + pos;\n  diff = sqrt(sum(diff % diff, 1));\n  diff -= obs;\n  sigma = diff.t() * diff / (double)diff.n_rows;\n}\n\nvoid tag_observe_theta(vec t, mat pos, vec z, vec &mu, mat &sigma) {\n  pos -= z;\n  vec theta = atan2(pos(1), pos(0));\n  vec dt = theta - t;\n  mu = mean(dt);\n  vec diff = ones<vec>(dt.n_elem) * mu - dt;\n  sigma = dot(diff, diff) / (double)diff.n_elem;\n}\n\nvoid tag_observe(mat obs, mat pos, ivec active, vec &mu, mat &sigma) {\n  // filter both the observation and the position\n  filter_active(obs, active);\n  filter_active(pos, active);\n  // get the obs and pos and put it into their respective functions\n  vec posmu;\n  mat possigma;\n  vec thetamu;\n  mat thetasigma;\n  tag_observe_pos(obs.col(0), pos, posmu, possigma);\n  tag_observe_theta(obs.col(1), pos, thetamu, thetasigma);\n  // assign the mus and sigmas\n  mu = vec({ posmu(0), posmu(1), thetamu });\n  sigma = mat(3, 3, fill::zeros);\n  sigma(span(0,1), span(0,1)) = possigma;\n  sigma(2, 2) = thetasigma;\n}\n\nvoid tag_generate(mat \n", "meta": {"hexsha": "42ac6ea51cbe342889adc9e6cb4b1525db17aaeb", "size": 1907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slam/kalman_filter/tag_observe.cpp", "max_stars_repo_name": "timrobot/Tachikoma-Project", "max_stars_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-11T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-11T19:04:33.000Z", "max_issues_repo_path": "slam/kalman_filter/tag_observe.cpp", "max_issues_repo_name": "TimothyYong/Tachikoma-Project", "max_issues_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slam/kalman_filter/tag_observe.cpp", "max_forks_repo_name": "TimothyYong/Tachikoma-Project", "max_forks_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4626865672, "max_line_length": 82, "alphanum_fraction": 0.6067121133, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5995928395034918}}
{"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 \"GaussSeq.h\"\n#include \"utils.h\"\n#include <boost/random/mersenne_twister.hpp>\nusing utils::normal;\nusing utils::my_float;\n\n\n/*\n *  Member variables\n */\nboost::random::mt19937 GaussSeq::gen {};        // define static generator\n\n/*\n *  Constructors and destructors\n */\nGaussSeq::GaussSeq(my_float mean, my_float std) {\n    normal new_n(mean, std);\n    this->n = new_n;\n}\n", "meta": {"hexsha": "e523f32d0ffbde11316efdf890d083e793ee1347", "size": 378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gen-data/lib/GaussSeq.cpp", "max_stars_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_stars_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gen-data/lib/GaussSeq.cpp", "max_issues_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_issues_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gen-data/lib/GaussSeq.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": 18.9, "max_line_length": 74, "alphanum_fraction": 0.6825396825, "num_tokens": 101, "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": "#pragma once\n\n#include <defines.h>\n\n#include <stdint.h>\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/QR>\n#include <unsupported/Eigen/MatrixFunctions>\n\n// CUDA runtime\n#include <cuda_runtime.h>\n// Utilities and system includes\n//#include <helper_functions.h>\n#include <nvidia/helper_cuda.h>\n#include <timer.hpp>\n\n#include \"sphereSimple.hpp\"\n#include \"optimizationSO3.hpp\"\n\nusing namespace Eigen;\n\nclass OptSO3Approx : public OptSO3\n{\n  public:\n  OptSO3Approx(float sigma, float *d_q, int w, int h, float *d_weights =NULL):\n    OptSO3(sigma,d_q,w,h,d_weights), Ss_(6,Matrix2f::Identity())\n  {\n    checkCudaErrors(cudaMalloc((void **)&d_mu_karch_, 6*4*sizeof(float)));\n    checkCudaErrors(cudaMalloc((void **)&d_p_, 6*3*sizeof(float)));\n    checkCudaErrors(cudaMalloc((void **)&d_SSs_, 6*7*sizeof(float)));\n    checkCudaErrors(cudaMalloc((void **)&d_Rnorths_, 6*6*sizeof(float)));\n    Matrix2f S = Matrix2f::Identity()*(15.0*M_PI/180.0)*(15.0*M_PI/180.0);\n    invSigma_ = S.inverse();\n    t_max_ = 5.0f;\n    dt_ = 0.05f; // 0.1\n  };\n\n  ~OptSO3Approx()\n  {\n    checkCudaErrors(cudaFree(d_mu_karch_));\n    checkCudaErrors(cudaFree(d_p_));\n    checkCudaErrors(cudaFree(d_SSs_));\n    checkCudaErrors(cudaFree(d_Rnorths_));\n  };\n  Matrix<float,3,6> karcherMeans(const Matrix<float,3,6>& p0, float thresh,\n      uint32_t maxIter);\n  void computeSuffcientStatistics();\n  Matrix<float,3,6> qKarch_; // karcher means for all axes\n\n\nprotected:\n  SphereSimple S2_;\n  float *d_mu_karch_, *d_p_;\n  float *d_Rnorths_, *d_SSs_;\n  Matrix2f invSigma_; // inverse of the sigma in the tangent space\n  Matrix<float,1,6> Ns_; // number of normals for each axis\n  Matrix<float,2,6> xSums_; // sum over all vectors for each axis\n  vector<Matrix2f> Ss_; // sum over outer products of data in tangent spaces\n\n\n  virtual void conjugateGradientPostparation_impl(Matrix3f& R);\n  virtual float conjugateGradientPreparation_impl(Matrix3f& R, uint32_t& N);\n  /* evaluate cost function for a given assignment of npormals to axes */\n  virtual float evalCostFunction(Matrix3f& R);\n  /* compute Jacobian */\n  virtual void computeJacobian(Matrix3f&J, Matrix3f& R, float N);\n  /* recompute assignment based on rotation R and return residual as well */\n  //float computeAssignment(Matrix3f& R, int& N);\n  /* compute all karcher means (for 6 axis) */\n  Matrix<float,3,6> meanInTpS2_GPU(Matrix<float,3,6>& p); \n};\n", "meta": {"hexsha": "90d833ccd17af4d8d4fe178ff5fbb49c9fca3a4d", "size": 2407, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/deprecated/optimizationSO3_approx.hpp", "max_stars_repo_name": "jstraub/rtmf", "max_stars_repo_head_hexsha": "eb348987959f118e0a9056eb0eede6435eef8842", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-10-07T14:33:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:45:16.000Z", "max_issues_repo_path": "include/deprecated/optimizationSO3_approx.hpp", "max_issues_repo_name": "jstraub/rtmf", "max_issues_repo_head_hexsha": "eb348987959f118e0a9056eb0eede6435eef8842", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/deprecated/optimizationSO3_approx.hpp", "max_forks_repo_name": "jstraub/rtmf", "max_forks_repo_head_hexsha": "eb348987959f118e0a9056eb0eede6435eef8842", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-10-19T20:44:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T08:30:12.000Z", "avg_line_length": 32.527027027, "max_line_length": 78, "alphanum_fraction": 0.7154133776, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5995728087080718}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/pblas_wrapper.hpp>\n\n#define BOOST_TEST_MODULE FrovedisTest\n#include <boost/test/unit_test.hpp>\n\nusing namespace frovedis;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( frovedis_test )\n{\n    int argc = 1;\n    char** argv = NULL;\n    use_frovedis use(argc, argv);\n\n    // dot product of two distributed std::vectors'\n    std::vector<float> x = {1,2,3,4}; \n    std::vector<float> y = {1,2,3,4};\n    auto xbm = vec_to_bcm<float> (x); // distributed vector x\n    auto ybm = vec_to_bcm<float> (y); // distrubuted vector y\n    auto d = dot<float> (xbm,ybm); // d = xbm.ybm\n    BOOST_CHECK (d == 30);\n\n    auto bm = make_blockcyclic_matrix_load<float> (\"./sample_4x4\");\n  \n    // checking dot() operation  \n    auto row1 = make_row_vector<float> (bm,1);\n    auto row2 = make_row_vector<float> (bm,2);\n    \n    // checking whether the dot operation successfully taken place \n    auto r = dot<float>(row1, row2); // r = row1 . row2\n    BOOST_CHECK (r == 2);\n}\n\n", "meta": {"hexsha": "6a6aa3a5dda65ad31b18ad4a6329c63e49880358", "size": 999, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix/test8.5/test.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "test/matrix/test8.5/test.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "test/matrix/test8.5/test.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 28.5428571429, "max_line_length": 67, "alphanum_fraction": 0.6556556557, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5995728075965513}}
{"text": "\n#include <iostream>\n#include <boost/timer/timer.hpp>\n#include \"strided_array.h\"\n#include \"linalg.h\"\n\ntemplate<class T>\ndouble test()\n{\n    int n = 700;\n    int m = 10;\n    StridedArray<T> a(n, n, T(0.0));\n    for (int i=0; i<n; i++)\n        a.setitem(i, i, i);\n    \n    StridedArray<T> b(n, n, T(0.0));\n    for (int i=0; i<n; i++)\n        b.setitem(i, i, 1);\n    \n    StridedArray<T> c(n, n, T(-1.0));\n    \n    boost::timer::cpu_timer t;\n    t.start();\n    for (int i=0; i<m; i++)\n       MM<T>(&a, &b, &c);\n    t.stop();\n\n    double dt = double(t.elapsed().wall) / 1.0e9;\n    double flops = 2 * m * pow(n, 3) / dt;\n    return flops;\n}\n\nint main(void)\n{\n    //printf(\"int:    %f GFLOPS\\n\", 1.0e-9 * test<int>());\n    printf(\"float:  %f GFLOPS\\n\", 1.0e-9 * test<float>());\n    //printf(\"double: %f GFLOPS\\n\", 1.0e-9 * test<double>());\n    return 0;\n}", "meta": {"hexsha": "81793d5e3290bb5613f8497d699e2efb15e5339c", "size": 849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "dmytrov/xGEMM", "max_stars_repo_head_hexsha": "dc435e968311d48e97fab6373e10fb3f8f459196", "max_stars_repo_licenses": ["MIT"], "max_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": "dmytrov/xGEMM", "max_issues_repo_head_hexsha": "dc435e968311d48e97fab6373e10fb3f8f459196", "max_issues_repo_licenses": ["MIT"], "max_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": "dmytrov/xGEMM", "max_forks_repo_head_hexsha": "dc435e968311d48e97fab6373e10fb3f8f459196", "max_forks_repo_licenses": ["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.7692307692, "max_line_length": 61, "alphanum_fraction": 0.5111896349, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5995728019578576}}
{"text": "#include <iostream>\n#include <ratio>\n#include <boost/type_index.hpp>\nusing namespace std;\nusing boost::typeindex::type_id_with_cvr;\n\n// \u5982\u679c\u4f7f\u7528 string \u4fdd\u7559\u5355\u4f4d\u540d\u79f0\u4f1a\u5bfc\u81f4\u81ea\u5b9a\u4e49\u5b57\u7b26\u4e32\u5b57\u9762\u503c\u51fa\u9519\uff0c\u56e0\u4e3a string \u6709\u4e00\u4e2a non_trivial \u7684\u6784\u9020\u51fd\u6570\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": "/**\n * \\file libs/numeric/ublasx/test/rank.cpp\n *\n * \\brief Test suite for the \\c rank operation.\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/detail/debug.hpp>\n#include <boost/numeric/ublasx/operation/rank.hpp>\n#include <iostream>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace ublasx = boost::numeric::ublasx;\n\n\nBOOST_UBLASX_TEST_DEF( rank_deficient )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Rank Deficient matrix\");\n\n\ttypedef double value_type;\n\ttypedef ublas::matrix<value_type> matrix_type;\n\ttypedef ublas::matrix_traits<matrix_type>::size_type size_type;\n\n\tconst std::size_t m = 3;\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(m,n);\n\tA(0,0) = 3; A(0,1) = 1; A(0,2) = 2;\n\tA(1,0) = 2; A(1,1) = 0; A(1,2) = 5;\n\tA(2,0) = 5; A(2,1) = 1; A(2,2) = 7;\n\n\tsize_type r = ublasx::rank(A);\n\tsize_type expect_r = n-1;\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"rank = \" << r);\n\tBOOST_UBLASX_TEST_CHECK( r == expect_r );\n}\n\n\nBOOST_UBLASX_TEST_DEF( full_rank )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Full Rank matrix\");\n\n\ttypedef double value_type;\n\ttypedef ublas::matrix<value_type> matrix_type;\n\ttypedef ublas::matrix_traits<matrix_type>::size_type size_type;\n\n\tconst std::size_t m = 3;\n\tconst std::size_t n = 3;\n\n\tmatrix_type A(m,n);\n\tA(0,0) = 3; A(0,1) = 1; A(0,2) = 2;\n\tA(1,0) = 2; A(1,1) = 0; A(1,2) = 5;\n\tA(2,0) = 1; A(2,1) = 2; A(2,2) = 3;\n\n\tsize_type r = ublasx::rank(A);\n\tsize_type expect_r = n;\n\tBOOST_UBLASX_DEBUG_TRACE(\"A = \" << A);\n\tBOOST_UBLASX_DEBUG_TRACE(\"rank = \" << r);\n\tBOOST_UBLASX_TEST_CHECK( r == expect_r );\n}\n\n\nint main()\n{\n\tBOOST_UBLASX_TEST_BEGIN();\n\n\tBOOST_UBLASX_TEST_DO( rank_deficient );\n\tBOOST_UBLASX_TEST_DO( full_rank );\n\n\tBOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "8c69e935fd8555bda508b0185bc48138baa195c6", "size": 2116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/rank.cpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/numeric/ublasx/test/rank.cpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/ublasx/test/rank.cpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8941176471, "max_line_length": 66, "alphanum_fraction": 0.6928166352, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.5995703470514333}}
{"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  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#include <boost/simd/function/scalar/remquo.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <utility>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\nSTF_CASE_TPL(\" remquo invalid\", STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::remquo;\n\n\n  using iT =  bd::as_integer_t<T,signed>;\n\n  STF_EXPR_IS( (remquo(T(), T()))\n                  , (std::pair<T,iT>)\n                  );\n\n  T inf_  = bs::Inf<T>();\n  T nan_  = bs::Nan<T>();\n  T zero_ = bs::Zero<T>();\n  T one_  = bs::One<T>();\n\n  // n is unspecified by the standard so we don't test it\n  std::pair<T,iT> p;\n\n  p =  remquo(one_,nan_);\n  STF_IEEE_EQUAL(p.first, nan_);\n\n  p =  remquo(one_,inf_);\n  STF_IEEE_EQUAL(p.first, nan_);\n\n  p =  remquo(one_,zero_);\n  STF_IEEE_EQUAL(p.first, nan_);\n\n  p =  remquo(inf_,zero_);\n  STF_IEEE_EQUAL(p.first, nan_);\n\n  p =  remquo(nan_,zero_);\n  STF_IEEE_EQUAL(p.first, nan_);\n\n  p =  remquo(nan_,one_);\n  STF_IEEE_EQUAL(p.first, nan_);\n\n  p =  remquo(nan_,nan_);\n  STF_IEEE_EQUAL(p.first, nan_);\n\n  p =  remquo(nan_,inf_);\n  STF_IEEE_EQUAL(p.first, nan_);\n}\n#endif\n\nSTF_CASE_TPL(\" remquo valid\", STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::remquo;\n\n  using iT =  bd::as_integer_t<T,signed>;\n\n  STF_EXPR_IS( (remquo(T(), T()))\n             , (std::pair<T,iT>)\n             );\n\n  T a0[] = { T(1), T(2), T(3), T(4.5) };\n  T a1[] = { T(2), T(1), T(7), T(3.2) };\n\n  std::size_t nb = sizeof(a0)/sizeof(T);\n\n  std::pair<T,iT> p;\n\n  for(std::size_t i=0;i<nb;++i)\n  {\n    p = remquo(a0[i],a1[i]);\n    STF_EQUAL(p.second, iT(a0[i] / a1[i]));\n    STF_EQUAL(p.first, a0[i] - p.second*a1[i]);\n  }\n}\n", "meta": {"hexsha": "9b80629adb4c6e4400d62474e36b485461bb02a4", "size": 2326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/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/function/scalar/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/function/scalar/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": 24.4842105263, "max_line_length": 100, "alphanum_fraction": 0.5726569218, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.59934039056887}}
{"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// \u4e0b\u9762\u8fd9\u5757\u51fa\u573a\u4ee3\u7801\u4e0e step-40 \u76f8\u540c\uff0c\u53ef\u4ee5\u5728PETSc\u548cTrilinos\u4e4b\u95f4\u5207\u6362\u3002\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// \u6211\u4eec\u9700\u8981\u4e00\u4e9b\u8f85\u52a9\u7c7b\u6765\u8868\u793a\u6211\u4eec\u5728\u4ecb\u7ecd\u4e2d\u63cf\u8ff0\u7684\u6c42\u89e3\u5668\u7b56\u7565\u3002\n\n  namespace LinearSolvers \n  { \n\n// \u8fd9\u4e2a\u7c7b\u66b4\u9732\u4e86\u901a\u8fc7\u51fd\u6570 InverseMatrix::vmult(). \u5e94\u7528\u7ed9\u5b9a\u77e9\u9635\u7684\u9006\u7684\u52a8\u4f5c\uff0c\u5728\u5185\u90e8\uff0c\u9006\u4e0d\u662f\u663e\u5f0f\u5f62\u6210\u7684\u3002\u76f8\u53cd\uff0c\u4e00\u4e2a\u5e26\u6709CG\u7684\u7ebf\u6027\u6c42\u89e3\u5668\u88ab\u6267\u884c\u3002\u8fd9\u4e2a\u7c7b\u6269\u5c55\u4e86 step-22 \u4e2d\u7684InverseMatrix\u7c7b\uff0c\u589e\u52a0\u4e86\u4e00\u4e2a\u6307\u5b9a\u9884\u5904\u7406\u7a0b\u5e8f\u7684\u9009\u9879\uff0c\u5e76\u5141\u8bb8\u5728vmult\u51fd\u6570\u4e2d\u4f7f\u7528\u4e0d\u540c\u7684\u77e2\u91cf\u7c7b\u578b\u3002\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// \u8be5\u7c7b\u662f\u4e00\u4e2a\u7b80\u5355\u76842x2\u77e9\u9635\u7684\u5757\u72b6\u5bf9\u89d2\u7ebf\u9884\u5904\u7406\u5668\u7684\u6a21\u677f\u7c7b\u3002\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// \u4e0b\u9762\u7684\u7c7b\u4ee3\u8868\u6d4b\u8bd5\u95ee\u9898\u7684\u53f3\u624b\u8fb9\u548c\u7cbe\u786e\u89e3\u3002\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// \u4e3b\u7c7b\u4e0e  step-40  \u975e\u5e38\u76f8\u4f3c\uff0c\u53ea\u662f\u77e9\u9635\u548c\u5411\u91cf\u73b0\u5728\u662f\u5757\u72b6\u7684\uff0c\u800c\u4e14\u6211\u4eec\u4e3a\u62e5\u6709\u7684\u548c\u76f8\u5173\u7684DoF\u5b58\u50a8\u4e00\u4e2a  std::vector<IndexSet>  \uff0c\u800c\u4e0d\u662f\u4e00\u4e2aIndexSet\u3002\u6211\u4eec\u6b63\u597d\u6709\u4e24\u4e2aIndexSets\uff0c\u4e00\u4e2a\u7528\u4e8e\u6240\u6709\u901f\u5ea6\u672a\u77e5\u6570\uff0c\u4e00\u4e2a\u7528\u4e8e\u6240\u6709\u538b\u529b\u672a\u77e5\u6570\u3002\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\u6d41\u5b9a\u4e49\u5728\u57df[-0.5, 1.5]^2\u4e0a\uff0c\u6211\u4eec\u901a\u8fc7\u5c06\u6700\u5c0f\u548c\u6700\u5927\u503c\u4f20\u9012\u7ed9 GridGenerator::hyper_cube. \u6765\u521b\u5efa\u8fd9\u4e2a\u57df\u3002\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// \u4e0e step-40 \u76f8\u6bd4\uff0c\u5757\u77e9\u9635\u548c\u5411\u91cf\u7684\u6784\u9020\u662f\u65b0\u7684\uff0c\u4e0e step-22 \u8fd9\u6837\u7684\u4e32\u884c\u4ee3\u7801\u76f8\u6bd4\u4e5f\u662f\u4e0d\u540c\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u9700\u8981\u63d0\u4f9b\u5c5e\u4e8e\u6211\u4eec\u5904\u7406\u5668\u7684\u884c\u7684\u96c6\u5408\u3002\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// \u5c06\u6240\u6709\u7684\u660f\u6697\u901f\u5ea6\u653e\u51650\u533a\u5757\uff0c\u538b\u529b\u653e\u51651\u533a\u5757\uff0c\u7136\u540e\u6309\u533a\u5757\u91cd\u65b0\u6392\u5217\u672a\u77e5\u6570\u3002\u6700\u540e\u8ba1\u7b97\u6bcf\u5757\u6709\u591a\u5c11\u4e2a\u672a\u77e5\u6570\u3002\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// \u6211\u4eec\u6839\u636e\u6211\u4eec\u60f3\u8981\u521b\u5efa\u5757\u72b6\u77e9\u9635\u548c\u5411\u91cf\u7684\u65b9\u5f0f\uff0c\u5c06\u672c\u5730\u62e5\u6709\u7684\u548c\u672c\u5730\u76f8\u5173\u7684DoF\u7684IndexSet\u5206\u5272\u6210\u4e24\u4e2aIndexSets\u3002\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// \u8bbe\u7f6e\u8fb9\u754c\u6761\u4ef6\u548c\u60ac\u6302\u8282\u70b9\u7684\u7ea6\u675f\u4e0e  step-40  \u76f8\u540c\u3002\u5c3d\u7ba1\u6211\u4eec\u6ca1\u6709\u4efb\u4f55\u60ac\u7a7a\u8282\u70b9\uff0c\u56e0\u4e3a\u6211\u4eec\u53ea\u8fdb\u884c\u5168\u5c40\u7ec6\u5316\uff0c\u4f46\u628a\u8fd9\u4e2a\u51fd\u6570\u8c03\u7528\u653e\u8fdb\u53bb\u4ecd\u7136\u662f\u4e2a\u597d\u4e3b\u610f\uff0c\u4ee5\u5907\u4ee5\u540e\u5f15\u5165\u81ea\u9002\u5e94\u7ec6\u5316\u3002\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// \u73b0\u5728\u6211\u4eec\u6839\u636eBlockDynamicSparsityPattern\u6765\u521b\u5efa\u7cfb\u7edf\u77e9\u9635\u3002\u6211\u4eec\u77e5\u9053\u6211\u4eec\u4e0d\u4f1a\u6709\u4e0d\u540c\u901f\u5ea6\u5206\u91cf\u4e4b\u95f4\u7684\u8026\u5408\uff08\u56e0\u4e3a\u6211\u4eec\u4f7f\u7528\u7684\u662f\u62c9\u666e\u62c9\u65af\u800c\u4e0d\u662f\u53d8\u5f62\u5f20\u91cf\uff09\uff0c\u4e5f\u4e0d\u4f1a\u6709\u538b\u529b\u4e0e\u5176\u6d4b\u8bd5\u51fd\u6570\u4e4b\u95f4\u7684\u8026\u5408\uff0c\u6240\u4ee5\u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u8868\u6765\u5c06\u8fd9\u4e2a\u8026\u5408\u4fe1\u606f\u4f20\u8fbe\u7ed9  DoFTools::make_sparsity_pattern.  \u3002\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// \u5148\u51b3\u6761\u4ef6\u77e9\u9635\u6709\u4e0d\u540c\u7684\u8026\u5408\uff08\u6211\u4eec\u53ea\u57281,1\u5757\u4e2d\u586b\u5165\u8d28\u91cf\u77e9\u9635\uff09\uff0c\u5426\u5219\u8fd9\u6bb5\u4ee3\u7801\u4e0e\u4e0a\u9762\u7684system_matrix\u7684\u6784\u9020\u662f\u76f8\u540c\u7684\u3002\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\u3002\n\n                                   dsp, \n                                   mpi_communicator); \n    } \n\n// \u6700\u540e\uff0c\u6211\u4eec\u4ee5\u6b63\u786e\u7684\u5c3a\u5bf8\u6784\u5efa\u5757\u72b6\u5411\u91cf\u3002\u5e26\u6709\u4e24\u4e2a std::vector<IndexSet> \u7684\u51fd\u6570\u8c03\u7528\u5c06\u521b\u5efa\u4e00\u4e2a\u91cd\u5f71\u5411\u91cf\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u5c06\u7cfb\u7edf\u77e9\u9635\u3001\u9884\u5904\u7406\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u96c6\u5408\u8d77\u6765\u3002\u5176\u4ee3\u7801\u975e\u5e38\u6807\u51c6\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u7528MINRES\u6c42\u89e3\u7ebf\u6027\u7cfb\u7edf\uff0c\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\uff0c\u5bf9\u4e24\u4e2a\u5bf9\u89d2\u7ebf\u5757\u4f7f\u7528\u5757\u72b6\u5bf9\u89d2\u7ebf\u9884\u5904\u7406\u548cAMG\u3002\u9884\u5904\u7406\u7a0b\u5e8f\u5bf90,0\u5757\u5e94\u7528v\u5faa\u73af\uff0c\u5bf91,1\u5757\u5e94\u7528\u8d28\u91cf\u77e9\u9635\u7684CG\uff08Schur\u8865\u5145\uff09\u3002\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\u7528\u4e8e\u89e3\u51b3\u8d28\u91cf\u77e9\u9635\u7684\u95ee\u9898\u3002\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// \u8fd9\u662f\u5728\u4e0a\u9762\u5b9a\u4e49\u7684\u5404\u4e2a\u5757\u7684\u9884\u5904\u7406\u7684\u57fa\u7840\u4e0a\u6784\u9020\u7684\u5757\u9884\u5904\u7406\u3002\n\n    const LinearSolvers::BlockDiagonalPreconditioner<LA::MPI::PreconditionAMG, \n                                                     mp_inverse_t> \n      preconditioner(prec_A, mp_inverse); \n\n// \u6709\u4e86\u8fd9\u4e9b\uff0c\u6211\u4eec\u7ec8\u4e8e\u53ef\u4ee5\u8bbe\u7f6e\u7ebf\u6027\u6c42\u89e3\u5668\u5e76\u6c42\u89e3\u8be5\u7cfb\u7edf\u3002\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// \u50cf\u5728  step-56  \u4e2d\u4e00\u6837\uff0c\u6211\u4eec\u51cf\u53bb\u5e73\u5747\u538b\u529b\uff0c\u4ee5\u4fbf\u4e0e\u6211\u4eec\u7684\u53c2\u8003\u89e3\u51b3\u65b9\u6848\u8fdb\u884c\u8bef\u5dee\u8ba1\u7b97\uff0c\u8be5\u89e3\u51b3\u65b9\u6848\u7684\u5e73\u5747\u503c\u4e3a\u96f6\u3002\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// \u5176\u4f59\u5904\u7406\u7f51\u683c\u7ec6\u5316\u3001\u8f93\u51fa\u548c\u4e3b\u5faa\u73af\u7684\u4ee3\u7801\u975e\u5e38\u6807\u51c6\u3002\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// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_random.h>\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/optimization/optimization_compute_generalized_minimal_map.h>\n#include <OpenTissue/core/math/optimization/optimization_compute_natural_merit.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n\ntemplate <typename T>\nclass BoundFunction\n{\npublic:\n\n  T    m_value;\n\npublic:\n\n  BoundFunction(T const & value)\n    : m_value(value)\n  {}\n\n  template<typename vector_type>\n  T operator()(vector_type const & x, size_t const & i) const  {    return m_value;  }\n\n};\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_compute_generalized_minimal_map);\n\nBOOST_AUTO_TEST_CASE(test_case)\n{\n\n\n  ublas::vector<double> x;\n  ublas::vector<double> y;\n  ublas::vector<double> H;\n\n  x.resize(10,false);\n  y.resize(10,false);\n  H.resize(10,false);\n\n  OpenTissue::math::Random<double> value(0.0,1.0);\n\n  x(0) = value();\n  x(1) = value();\n  x(2) = value();\n  x(3) = value();\n  x(4) = value();\n  x(5) = value();\n  x(6) = value();\n  x(7) = value();\n  x(8) = value();\n  x(9) = value();\n\n  y(0) = value();\n  y(1) = value();\n  y(2) = value();\n  y(3) = value();\n  y(4) = value();\n  y(5) = value();\n  y(6) = value();\n  y(7) = value();\n  y(8) = value();\n  y(9) = value();\n\n  BoundFunction<double> l(-value());\n  BoundFunction<double> u( value());\n\n  OpenTissue::math::optimization::compute_generalized_minimal_map(y,l,u,x, H );\n\n  double theta = OpenTissue::math::optimization::compute_natural_merit( H );\n  BOOST_CHECK ( theta >= 0.0 );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "6c294810a332b639b0ebc41dad64ab1d870070eb", "size": 2019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/compute_generalized_minimal_map/src/unit_comp_gen_min_map.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/compute_generalized_minimal_map/src/unit_comp_gen_min_map.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/compute_generalized_minimal_map/src/unit_comp_gen_min_map.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 22.9431818182, "max_line_length": 91, "alphanum_fraction": 0.6953937593, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5992905086188511}}
{"text": "//****************************************************************************\n// (c) 2008, 2009 by the openOR Team\n//****************************************************************************\n// The contents of this file are available under the GPL v2.0 license\n// or under the openOR comercial license. see\n//   /Doc/openOR_free_license.txt or\n//   /Doc/openOR_comercial_license.txt\n// for Details.\n//****************************************************************************\n//! OPENOR_INTERFACE_FILE(openOR_core)\n//****************************************************************************\n/**\n * @file\n * @author Christian Winne\n * @ingroup openOR_core\n */\n\n#ifndef openOR_core_vectorfunctions_hpp\n#define openOR_core_vectorfunctions_hpp\n\n#include <functional>\n\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/equal_to.hpp>\n\n#include <openOR/Utility/conceptcheck.hpp>\n#include <openOR/Math/traits.hpp>\n#include <openOR/Math/vector.hpp>\n#include <openOR/Math/constants.hpp>\n\n\nnamespace openOR {\n   namespace Math {\n      \n      /**\n       * @brief \n       * @ingroup openOR_core\n       */\n      template <class Type>\n      inline\n      OPENOR_CONCEPT_REQUIRES(\n         ((Concept::ConstVector<Type>)),\n         (typename VectorTraits<Type>::ValueType))\n      squaredNorm(const Type& vec) {\n         return dot(vec, vec);\n      }\n\n   \n      namespace Impl {\n      \n        template <class V, int I>\n        struct VectorAccess {\n           typename VectorTraits<V>::ValueType operator()(const V& vec) const { return get<I>(vec); }\n        };\n\n\n        template<class _Type>\n        struct Min : public std::binary_function<_Type, _Type, _Type> {\t\n           _Type operator()(const _Type& left, const _Type& right) const {\t\n              return std::min<_Type>(left, right);\n           }\n        };\n\n\n        template<class _Type>\n        struct Max : public std::binary_function<_Type, _Type, _Type> {\n           _Type operator()(const _Type& left, const _Type& right) const {\t\n              return std::max<_Type>(left, right);\n           }\n        };\n\n\n      }\n\n      /**\n       * @brief Returns the minimal element of a vector.\n       * @ingroup openOR_core\n       */\n      template <class Type>\n      inline\n      OPENOR_CONCEPT_REQUIRES(\n        ((Concept::ConstVector<Type>)),\n        (typename VectorTraits<Type>::ValueType))\n      minimalElement(const Type& vec) \n      {\n         typedef typename VectorTraits<Type>::ValueType ValueType;\n         return Impl::VectorCompileTimeIterator<Type>().template reduce<Impl::VectorAccess, ValueType, Impl::Min>(vec);\n      }\n\n\n      /**\n       * @brief \n       * @ingroup openOR_core\n       */\n      template <class Type>\n      inline\n      OPENOR_CONCEPT_REQUIRES(\n        ((Concept::ConstVector<Type>)),\n        (typename VectorTraits<Type>::ValueType))\n      maximalElement(const Type& vec) \n      {\n        typedef typename VectorTraits<Type>::ValueType ValueType;\n        return Impl::VectorCompileTimeIterator<Type>().template reduce<Impl::VectorAccess, ValueType, Impl::Max>(vec);\n      }\n\n\n      /**\n       * @brief \n       * @ingroup openOR_core\n       */\n      template <class Type>\n      inline\n      OPENOR_CONCEPT_REQUIRES(\n        ((Concept::ConstVector<Type>)),\n        (typename VectorTraits<Type>::ValueType))\n      summarizedElements(const Type& vec) \n      {\n        typedef typename VectorTraits<Type>::ValueType ValueType;\n        return Impl::VectorCompileTimeIterator<Type>().template reduce<Impl::VectorAccess, ValueType, std::plus>(vec);\n      }\n\n\n      /**\n       * @brief \n       * @ingroup openOR_core\n       */\n      template <class Type>\n      inline\n      OPENOR_CONCEPT_REQUIRES(\n        ((Concept::ConstVector<Type>)),\n        (typename VectorTraits<Type>::ValueType))\n      multipliedElements(const Type& vec) \n      {\n        typedef typename VectorTraits<Type>::ValueType ValueType;\n        return Impl::VectorCompileTimeIterator<Type>().template reduce<Impl::VectorAccess, ValueType, std::multiplies>(vec);\n      }\n\n\n      /**\n       * @brief \n       * @ingroup openOR_core\n       */\n      template <class Type>\n      inline\n      OPENOR_CONCEPT_REQUIRES(\n         ((Concept::Vector<Type>)),\n         (Type&))\n      normalize(Type& vec) {\n         BOOST_MPL_ASSERT((boost::is_floating_point<typename VectorTraits<Type>::ValueType>));\n         typedef typename ScalarTraits<typename VectorTraits<Type>::ValueType>::RealType RealType;\n         RealType invNorm = (RealType) 1.0 / norm(vec);\n         vec *= invNorm;\n         return vec;\n      }\n\n\n      namespace Impl\n      {\n         template <class Vec, class Vec2, class Vec3, int I>\n         struct ElementwiseMult {\n            inline void operator()(Vec& p1, const Vec2& p2 , const Vec3& p3) const \n            {\n               typedef typename VectorTraits<Vec>::ValueType ValueType;\n               ValueType v2 = static_cast<ValueType>(get<I>(p2));\n               ValueType v3 = static_cast<ValueType>(get<I>(p3));\n               get<I>(p1) = v2 * v3;\n            }\n         };\n      }\n\n      /**\n      * @brief \n      * @ingroup openOR_core\n      */\n      template <class Type, class Type2, class Type3>\n      inline\n         OPENOR_CONCEPT_REQUIRES(\n         ((Concept::Vector<Type>))\n         ((Concept::ConstVector<Type2))\n         ((Concept::ConstVector<Type3)),\n         (Type))\n         elementProd(const Type2& left, const Type3& right) \n      {\n         Type result;\n         Impl::VectorCompileTimeIterator<Type>().template apply<Impl::ElementwiseMult, Type2, Type3>(result, left, right);\n         return result;\n      }\n\n      template<class Type>\n      inline Type fromString(const std::string& str) {\n            Type retval;\n\n            std::stringstream in;\n            in.str(str);\n            in >> retval;\n            \n            return retval;\n      }\n\n\n      ///**\n      // * @brief \n      // * @ingroup openOR_core_math\n      // */\n      //template <class Type>\n      //inline\n      //OPENOR_CONCEPT_REQUIRES(\n      //                        ((Concept::Vector<Type>)),\n      //                        (Type&))\n      //normalize(const Type& vec) {\n      //   BOOST_MPL_ASSERT((boost::is_floating_point<typename VectorTraits<Type>::ValueType>));\n      //   typename ScalarTraits<typename VectorTraits<Type>::ValueType>::RealType invNorm = 1.0 / norm(vec);\n      //   Type res = vec * invNorm;\n      //   return res;\n      //}\n      \n\n      /**\n       * @brief \n       * @ingroup openOR_core\n       */\n      template <class Type>\n      inline\n      OPENOR_CONCEPT_REQUIRES(\n         ((Concept::ConstVector<Type>)),\n         (typename VectorTraits<Type>::RealVectorType))\n      normalized(const Type& vec) {\n         typename VectorTraits<Type>::RealVectorType v(vec);\n         normalize(v);\n         return v;\n      }\n\n\n      namespace Impl {\n\n         template <int I, class Type, class Type2>\n         struct Cross {\n            typedef invalid_type ResultType;\n         };\n\n         template<class Type, class Type2>\n         struct Cross<2, Type, Type2> {\n            typedef typename VectorTraits<Type>::ValueType ResultType;\n\n            ResultType operator()(const Type& left, const Type2& right) const {\n               return get<0>(left) * get<1>(right) - get<1>(left) * get<0>(right);\n            }\n         };\n\n\n         template <class Type, class Type2>\n         struct Cross<3, Type, Type2> {\n            typedef typename VectorTraits<Type>::Vector3Type ResultType;\n\n            ResultType operator()(const Type& left, const Type2& right) const {\n               BOOST_MPL_ASSERT((boost::mpl::equal_to<typename VectorTraits<typename VectorTraits<Type>::Vector3Type>::Dimension, boost::mpl::int_<3> >));\n               ResultType vec;\n               get<0>(vec) = get<1>(left) * get<2>(right) - get<2>(left) * get<1>(right);\n               get<1>(vec) = get<2>(left) * get<0>(right) - get<0>(left) * get<2>(right);\n               get<2>(vec) = get<0>(left) * get<1>(right) - get<1>(left) * get<0>(right);\n               return vec;\n            }\n         };\n\n      }\n\n\n       /**\n       * @brief \n       * @ingroup openOR_core\n       */\n      template <class Type, class Type2>\n      inline\n      OPENOR_CONCEPT_REQUIRES(\n         ((Concept::ConstVector<Type>))\n         ((Concept::ConstVector<Type2>))\n         ((Concept::Vector<typename VectorTraits<Type>::Vector3Type>)),\n         (typename Impl::Cross<VectorTraits<Type>::Dimension::value, Type, Type2>::ResultType))\n      cross(const Type& left, const Type2& right) {\n         BOOST_MPL_ASSERT((boost::mpl::equal_to<typename VectorTraits<typename VectorTraits<Type>::Vector3Type>::Dimension, boost::mpl::int_<3> >));\n         return typename Impl::Cross<VectorTraits<Type>::Dimension::value, Type, Type2>()(left, right);\n      }\n\n      \n      /**\n       * @brief \n       * @ingroup openOR_core\n       */\n      template <class Type>\n      inline\n      OPENOR_CONCEPT_REQUIRES(\n                              ((Concept::ConstVector<Type>)),\n                              (Type))\n      rotate3(const Type& vec, const Type& vecAxis, const typename ScalarTraits<typename VectorTraits<Type>::ValueType>::RealType angle) {\n         \n         typedef typename VectorTraits<Type>::RealVectorType RealVectorType;\n         typedef typename ScalarTraits<typename VectorTraits<Type>::ValueType>::RealType RealType;\n         RealVectorType vecReal(vec);\n         RealVectorType vecAxisReal(vecAxis);\n         normalize(vecAxisReal);\n         vecAxisReal *= static_cast<RealType>(dot(vec, vecAxis));\n         \n         \n         // first radius vector\n         RealVectorType vecRad1(vecReal - vecAxisReal);\n         RealType length = norm(vecRad1);\n         if (length < 0.0001) return vec;\n         \n         // second radius vector\n         RealVectorType vecRad2 = cross(RealVectorType(vecAxis), vecRad1);\n         normalize(vecRad1);\n         normalize(vecRad2);\n         \n         RealType factor1 = length * cos(angle);\n         RealType factor2 = length * sin(angle);\n         \n         RealVectorType result = vecAxisReal + vecRad1 * factor1 + vecRad2 * factor2;\n         return Type(result);\n      }\n      \n\n   }\n}\n\n\n\n#endif\n", "meta": {"hexsha": "59d9733855b8b04d22112b50fa7682c8a7755f54", "size": 10189, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/include/openOR/Math/vectorfunctions.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/vectorfunctions.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/vectorfunctions.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": 30.9696048632, "max_line_length": 154, "alphanum_fraction": 0.5605064285, "num_tokens": 2275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5992905062117195}}
{"text": "/*\nthis file should cover the following functions in hmm.h\n- hmm_vec2 HMM_DivideVec2(hmm_vec2 Left, hmm_vec2 Right);\n- hmm_vec2 HMM_DivideVec2f(hmm_vec2 Left, float Right);\n- hmm_vec3 HMM_DivideVec3(hmm_vec3 Left, hmm_vec3 Right);\n- hmm_vec3 HMM_DivideVec3f(hmm_vec3 Left, float Right);\n- hmm_vec4 HMM_DivideVec4(hmm_vec4 Left, hmm_vec4 Right);\n- hmm_vec4 HMM_DivideVec4f(hmm_vec4 Left, float Right);\n- hmm_mat4 HMM_DivideMat4f(hmm_mat4 Matrix, float Scalar);\ntake care of operator overloading also for these functions:\n- hmm_vec2 operator/(hmm_vec2 Left, hmm_vec2 Right);\n- hmm_vec3 operator/(hmm_vec3 Left, hmm_vec3 Right);\n- hmm_vec4 operator/(hmm_vec4 Left, hmm_vec4 Right);\n- hmm_vec2 operator/(hmm_vec2 Left, float Right);\n- hmm_vec3 operator/(hmm_vec3 Left, float Right);\n- hmm_vec4 operator/(hmm_vec4 Left, float Right);\n- hmm_mat4 operator/(hmm_mat4 Left, float Right);\n- hmm_vec2 &operator/=(hmm_vec2 &Left, hmm_vec2 Right);\n- hmm_vec3 &operator/=(hmm_vec3 &Left, hmm_vec3 Right);\n- hmm_vec4 &operator/=(hmm_vec4 &Left, hmm_vec4 Right);\n- hmm_vec2 &operator/=(hmm_vec2 &Left, float Right);\n- hmm_vec3 &operator/=(hmm_vec3 &Left, float Right);\n- hmm_vec4 &operator/=(hmm_vec4 &Left, float Right);\n- hmm_mat4 &operator/=(hmm_mat4 &Left, float Right);\n*/\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include \"HMM.h\"\n#include \"test_helpers.h\"\nnamespace utf = boost::unit_test;\n\nBOOST_AUTO_TEST_SUITE(division_test_suite)\n\nBOOST_AUTO_TEST_SUITE(division_vec2_by_int)\n\nBOOST_AUTO_TEST_CASE(test_HMM_DivideVec2_int_BothVecsZeros, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto zeros = HMM_Vec2i(0, 0);\n    //Act\n    auto res = HMM_DivideVec2(zeros, zeros);\n    //Assert\n    BOOST_TEST(isnan(res.Elements[0]));\n    BOOST_TEST(isnan(res.Elements[1]));\n}\n\nBOOST_AUTO_TEST_CASE(test_HMM_DivideVec2_int_V1_zeros, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto zeros = HMM_Vec2i(0, 0);\n    auto right = HMM_Vec2i(5, -10);\n    //Act\n    auto res = HMM_DivideVec2(zeros, right);\n    //Assert\n    float expectedRes[2] = {0, 0};\n    BOOST_TEST(res.Elements == expectedRes);\n}\n\nBOOST_AUTO_TEST_CASE(test_HMM_DivideVec2_int_postives, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2i(1, 5);\n    auto right = HMM_Vec2i(3, 4);\n    //Act\n    auto res = HMM_DivideVec2(left, right);\n    //Assert\n    float expectedRes[2] = {left.Elements[0] / right.Elements[0], left.Elements[1] / right.Elements[1]};\n    BOOST_TEST(res.Elements == expectedRes);\n}\n\nBOOST_AUTO_TEST_CASE(test_HMM_DivideVec2_int_pos_neg, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2i(1, 5);\n    auto right = HMM_Vec2i(-3, -4);\n    //Act\n    auto res = HMM_DivideVec2(left, right);\n    //Assert\n    BOOST_TEST(vector<float>(res.Elements, res.Elements + 2) == vector<float>({left.Elements[0] / right.Elements[0], left.Elements[1] / right.Elements[1]}));\n}\n\nBOOST_AUTO_TEST_CASE(test_HMM_DivideVec2_float_pos_neg, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2(10., 1.);\n    auto right = HMM_Vec2(-2, -5.);\n    //Act\n    auto res = HMM_DivideVec2(left, right);\n    //Assert\n    BOOST_TEST(vector<float>(res.Elements, res.Elements + 2) == vector<float>({left.Elements[0] / right.Elements[0], left.Elements[1] / right.Elements[1]}));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//--------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(division_vec2_by_float)\n\nBOOST_AUTO_TEST_CASE(test_HMM_DivideVec2f_vec_x_posfloat, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2(.5, .2);\n    float right = 10.;\n    //Act\n    auto res = HMM_DivideVec2f(left, right);\n    //Assert\n    BOOST_TEST(vector<float>(res.Elements, res.Elements + 2) == vector<float>({left.Elements[0] / right, left.Elements[1] / right}));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n//--------------------------------------------------------------\nBOOST_AUTO_TEST_SUITE(division_vec2_using_operators)\n\nBOOST_AUTO_TEST_CASE(test_division_vec2_by_vec2_using_division_operator, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2(10., 1.);\n    auto right = HMM_Vec2(-2, -5.);\n    //Act\n    auto res = left / right;\n    //Assert\n    BOOST_TEST(vector<float>(res.Elements, res.Elements + 2) == vector<float>({left.Elements[0] / right.Elements[0], left.Elements[1] / right.Elements[1]}));\n}\n\nBOOST_AUTO_TEST_CASE(test_division_vec2_by_float_using_division_operator, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2(.5, .2);\n    float right = 10.;\n    //Act\n    auto res = left / right;\n    //Assert\n    BOOST_TEST(vector<float>(res.Elements, res.Elements + 2) == vector<float>({left.Elements[0] / right, left.Elements[1] / right}));\n}\n\nBOOST_AUTO_TEST_CASE(test_division_vec2_by_vec2_using_division_equal_operator, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2(.5, .2);\n    auto right = HMM_Vec2(-2, -5.);\n    //Act\n    auto res = left;\n    res /= right;\n    //Assert\n    BOOST_TEST(vector<float>(res.Elements, res.Elements + 2) == vector<float>({left.Elements[0] / right.Elements[0], left.Elements[1] / right.Elements[1]}));\n}\n\nBOOST_AUTO_TEST_CASE(test_division_vec2_by_float_using_division_equal_operator, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2(.5, .2);\n    float right = 10.;\n    //Act\n    auto res = left;\n    res /= right;\n    //Assert\n    float expectedRes[2] = {left.Elements[0] / right, left.Elements[1] / right};\n    BOOST_TEST(res.Elements == expectedRes);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//-----------------------\nBOOST_AUTO_TEST_SUITE(division_mat4_by_floatscalar)\n\nBOOST_AUTO_TEST_CASE(test_HMM_DivideMat4f, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = hmm_mat4();\n    float arr[4][4] = {{1, 2, 3, 4},\n                       {5, -6, 7, 8},\n                       {9, 10, 11, 12},\n                       {0, 15, 0, 0}};\n    copy(&arr[0][0], &arr[0][0] + 4 * 4, &left.Elements[0][0]);\n\n    float right = .5;\n    //Act\n    hmm_mat4 res = HMM_DivideMat4f(left, right);\n\n    //Assert\n    float expMat[4][4] = {{arr[0][0] / right, arr[0][1] / right, arr[0][2] / right, arr[0][3] / right},\n                          {arr[1][0] / right, arr[1][1] / right, arr[1][2] / right, arr[1][3] / right},\n                          {arr[2][0] / right, arr[2][1] / right, arr[2][2] / right, arr[2][3] / right},\n                          {arr[3][0] / right, arr[3][1] / right, arr[3][2] / right, arr[3][3] / right}};\n\n    BOOST_TEST(res.Elements == expMat);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//-----------------------\nBOOST_AUTO_TEST_SUITE(division_mat4_using_operators)\n\nBOOST_AUTO_TEST_CASE(test_HMM_DivideMat4f, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = hmm_mat4();\n    float arr[4][4] = {{1, 2, 3, 4},\n                       {5, -6, 7, 8},\n                       {9, 10, 11, 12},\n                       {0, 15, 0, 0}};\n    copy(&arr[0][0], &arr[0][0] + 4 * 4, &left.Elements[0][0]);\n\n    float right = .5;\n    //Act\n    hmm_mat4 res = HMM_DivideMat4f(left, right);\n\n    //Assert\n    float expMat[4][4] = {{arr[0][0] / right, arr[0][1] / right, arr[0][2] / right, arr[0][3] / right},\n                          {arr[1][0] / right, arr[1][1] / right, arr[1][2] / right, arr[1][3] / right},\n                          {arr[2][0] / right, arr[2][1] / right, arr[2][2] / right, arr[2][3] / right},\n                          {arr[3][0] / right, arr[3][1] / right, arr[3][2] / right, arr[3][3] / right}};\n\n    BOOST_TEST(res.Elements == expMat);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "d0049fe8ee87038bc4b13f6439ba56b88758b99b", "size": 7513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Test-HMM/tests/tests_div.cpp", "max_stars_repo_name": "AmmarRabie/Test-HMM", "max_stars_repo_head_hexsha": "2fb6dac9b6144030b585200e89e516a53bc97e66", "max_stars_repo_licenses": ["MIT"], "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-HMM/tests/tests_div.cpp", "max_issues_repo_name": "AmmarRabie/Test-HMM", "max_issues_repo_head_hexsha": "2fb6dac9b6144030b585200e89e516a53bc97e66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test-HMM/tests/tests_div.cpp", "max_forks_repo_name": "AmmarRabie/Test-HMM", "max_forks_repo_head_hexsha": "2fb6dac9b6144030b585200e89e516a53bc97e66", "max_forks_repo_licenses": ["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.2946859903, "max_line_length": 157, "alphanum_fraction": 0.6323705577, "num_tokens": 2416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021788, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5992793017036203}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2013-2015 Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include <rokko/rokko.hpp>\n#include <rokko/utility/frank_matrix.hpp>\n#include <boost/foreach.hpp>\n#define BOOST_TEST_MODULE test_generator\n#ifndef BOOST_TEST_DYN_LINK\n#include <boost/test/included/unit_test.hpp>\n#else\n#include <boost/test/unit_test.hpp>\n#endif\n\ntemplate<typename T, typename MATRIX_MAJOR>\nvoid test(int dim) {\n  rokko::localized_matrix<T, MATRIX_MAJOR> mat(dim, dim);\n  rokko::frank_matrix::generate(mat);  \n  BOOST_CHECK_CLOSE(mat.trace(), dim * (dim+1) * 0.5, 10e-5);\n}\n\nBOOST_AUTO_TEST_CASE(test_generator) {\n  const int dim = 100;\n  std::cout << \"dimension = \" << dim << std::endl;\n\n  std::cout << \"  test for row major\" << std::endl;\n  test<double, rokko::matrix_row_major>(dim);\n  std::cout << \"  test for column major\" << std::endl;\n  test<double, rokko::matrix_col_major>(dim);\n}\n", "meta": {"hexsha": "48be2380c3549aa54de5fc3da8c143664d4429c1", "size": 1275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/generate_matrix/frank.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/generate_matrix/frank.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/generate_matrix/frank.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5526315789, "max_line_length": 79, "alphanum_fraction": 0.6392156863, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5992792876424241}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/ext/std/ratio.hpp>\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <laws/comparable.hpp>\n#include <laws/euclidean_ring.hpp>\n#include <laws/group.hpp>\n#include <laws/monoid.hpp>\n#include <laws/orderable.hpp>\n#include <laws/ring.hpp>\n#include <test/cnumeric.hpp>\n\n#include <ratio>\nusing namespace boost::hana;\n\n\nint main() {\n    auto ratios = make<tuple_tag>(\n          std::ratio<0>{}\n        , std::ratio<1, 3>{}\n        , std::ratio<1, 2>{}\n        , std::ratio<2, 6>{}\n        , std::ratio<3, 1>{}\n        , std::ratio<7, 8>{}\n        , std::ratio<3, 5>{}\n        , std::ratio<2, 1>{}\n    );\n    (void)ratios;\n\n#if BOOST_HANA_TEST_PART == 1\n    //////////////////////////////////////////////////////////////////////////\n    // Conversions\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // Constant -> Ratio\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                to<ext::std::ratio_tag>(test::cnumeric<int, 0>),\n                std::ratio<0>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                to<ext::std::ratio_tag>(test::cnumeric<int, 1>),\n                std::ratio<1>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                to<ext::std::ratio_tag>(test::cnumeric<int, 3>),\n                std::ratio<3>{}\n            ));\n        }\n    }\n\n    //////////////////////////////////////////////////////////////////////////\n    // Comparable\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // equal\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                std::ratio<0>{},\n                std::ratio<0>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                std::ratio<3, 5>{},\n                std::ratio<6, 10>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(not_(equal(\n                std::ratio<4, 5>{},\n                std::ratio<6, 10>{}\n            )));\n        }\n\n        // laws\n        test::TestComparable<ext::std::ratio_tag>{ratios};\n    }\n\n#elif BOOST_HANA_TEST_PART == 2\n    //////////////////////////////////////////////////////////////////////////\n    // Orderable\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // less\n        {\n            BOOST_HANA_CONSTANT_CHECK(less(\n                std::ratio<1>{},\n                std::ratio<3>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(less(\n                std::ratio<4, 10>{},\n                std::ratio<3, 5>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(not_(less(\n                std::ratio<3, 5>{},\n                std::ratio<4, 10>{}\n            )));\n        }\n\n        // laws\n        auto ratios = make<tuple_tag>(\n              std::ratio<0>{}\n            , std::ratio<1, 3>{}\n            , std::ratio<1, 2>{}\n            , std::ratio<2, 6>{}\n            , std::ratio<7, 8>{}\n            , std::ratio<3, 5>{}\n        );\n\n        test::TestOrderable<ext::std::ratio_tag>{ratios};\n    }\n\n#elif BOOST_HANA_TEST_PART == 3\n    //////////////////////////////////////////////////////////////////////////\n    // Monoid\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // plus\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                plus(std::ratio<3, 4>{}, std::ratio<5, 10>{}),\n                std::ratio<3*10 + 5*4, 4*10>{}\n            ));\n        }\n\n        // zero\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                zero<ext::std::ratio_tag>(),\n                std::ratio<0, 1>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                zero<ext::std::ratio_tag>(),\n                std::ratio<0, 2>{}\n            ));\n        }\n\n        // laws\n        test::TestMonoid<ext::std::ratio_tag>{ratios};\n    }\n\n    //////////////////////////////////////////////////////////////////////////\n    // Group\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // minus\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                minus(std::ratio<3, 4>{}, std::ratio<5, 10>{}),\n                std::ratio<3*10 - 5*4, 4*10>{}\n            ));\n        }\n\n        // laws\n        test::TestGroup<ext::std::ratio_tag>{ratios};\n    }\n\n#elif BOOST_HANA_TEST_PART == 4\n    //////////////////////////////////////////////////////////////////////////\n    // Ring\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // mult\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                mult(std::ratio<3, 4>{}, std::ratio<5, 10>{}),\n                std::ratio<3*5, 4*10>{}\n            ));\n        }\n\n        // one\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                one<ext::std::ratio_tag>(),\n                std::ratio<1, 1>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                one<ext::std::ratio_tag>(),\n                std::ratio<2, 2>{}\n            ));\n        }\n\n        // laws\n        test::TestRing<ext::std::ratio_tag>{ratios};\n    }\n\n#elif BOOST_HANA_TEST_PART == 5\n    //////////////////////////////////////////////////////////////////////////\n    // EuclideanRing\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // div\n        {\n            using boost::hana::div; // hide ::div\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                div(std::ratio<6>{}, std::ratio<4>{}),\n                std::ratio<6, 4>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                div(std::ratio<3, 4>{}, std::ratio<5, 10>{}),\n                std::ratio<3*10, 4*5>{}\n            ));\n        }\n\n        // mod\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                mod(std::ratio<6>{}, std::ratio<4>{}),\n                std::ratio<0>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                mod(std::ratio<3, 4>{}, std::ratio<5, 10>{}),\n                std::ratio<0>{}\n            ));\n        }\n\n        // laws\n        test::TestEuclideanRing<ext::std::ratio_tag>{ratios};\n    }\n#endif\n}\n", "meta": {"hexsha": "3c1b06121cc7aae24a94b653d79ed8607de080a7", "size": 6391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ext/std/ratio.cpp", "max_stars_repo_name": "qicosmos/hana", "max_stars_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-06T05:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T21:48:27.000Z", "max_issues_repo_path": "test/ext/std/ratio.cpp", "max_issues_repo_name": "qicosmos/hana", "max_issues_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/ext/std/ratio.cpp", "max_forks_repo_name": "qicosmos/hana", "max_forks_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-06T10:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-06T10:50:17.000Z", "avg_line_length": 27.0805084746, "max_line_length": 78, "alphanum_fraction": 0.3634798936, "num_tokens": 1444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5992588028490097}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// calculator.hpp\r\n//\r\n//  Copyright 2008 Eric Niebler. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/proto/core.hpp>\r\n#include <boost/proto/context.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n\r\nusing namespace boost;\r\n\r\nstruct placeholder {};\r\nproto::terminal<placeholder>::type const _1 = {{}};\r\n\r\nstruct calculator : proto::callable_context<calculator const>\r\n{\r\n    typedef int result_type;\r\n\r\n    calculator(int i)\r\n      : i_(i)\r\n    {}\r\n\r\n    int operator ()(proto::tag::terminal, placeholder) const\r\n    {\r\n        return this->i_;\r\n    }\r\n\r\n    int operator ()(proto::tag::terminal, int j) const\r\n    {\r\n        return j;\r\n    }\r\n\r\n    template<typename Left, typename Right>\r\n    int operator ()(proto::tag::plus, Left const &left, Right const &right) const\r\n    {\r\n        return proto::eval(left, *this) + proto::eval(right, *this);\r\n    }\r\n\r\n    template<typename Left, typename Right>\r\n    int operator ()(proto::tag::minus, Left const &left, Right const &right) const\r\n    {\r\n        return proto::eval(left, *this) - proto::eval(right, *this);\r\n    }\r\n\r\n    template<typename Left, typename Right>\r\n    int operator ()(proto::tag::multiplies, Left const &left, Right const &right) const\r\n    {\r\n        return proto::eval(left, *this) * proto::eval(right, *this);\r\n    }\r\n\r\n    template<typename Left, typename Right>\r\n    int operator ()(proto::tag::divides, Left const &left, Right const &right) const\r\n    {\r\n        return proto::eval(left, *this) / proto::eval(right, *this);\r\n    }\r\n\r\nprivate:\r\n    int i_;\r\n};\r\n\r\ntemplate<typename Fun, typename Expr>\r\nstruct functional\r\n{\r\n    typedef typename proto::result_of::eval<Expr, Fun>::type result_type;\r\n\r\n    functional(Expr const &expr)\r\n      : expr_(expr)\r\n    {}\r\n\r\n    template<typename T>\r\n    result_type operator ()(T const &t) const\r\n    {\r\n        Fun fun(t);\r\n        return proto::eval(this->expr_, fun);\r\n    }\r\n\r\nprivate:\r\n    Expr const &expr_;\r\n};\r\n\r\ntemplate<typename Fun, typename Expr>\r\nfunctional<Fun, Expr> as(Expr const &expr)\r\n{\r\n    return functional<Fun, Expr>(expr);\r\n}\r\n\r\nvoid test_calculator()\r\n{\r\n    BOOST_CHECK_EQUAL(10, proto::eval(((_1 + 42)-3)/4, calculator(1)));\r\n    BOOST_CHECK_EQUAL(11, proto::eval(((_1 + 42)-3)/4, calculator(5)));\r\n\r\n    BOOST_CHECK_EQUAL(10, as<calculator>(((_1 + 42)-3)/4)(1));\r\n    BOOST_CHECK_EQUAL(11, as<calculator>(((_1 + 42)-3)/4)(5));\r\n}\r\n\r\nusing namespace unit_test;\r\n///////////////////////////////////////////////////////////////////////////////\r\n// init_unit_test_suite\r\n//\r\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n    test_suite *test = BOOST_TEST_SUITE(\"test immediate evaluation of proto parse trees\");\r\n\r\n    test->add(BOOST_TEST_CASE(&test_calculator));\r\n\r\n    return test;\r\n}\r\n", "meta": {"hexsha": "a69480c9e5b51ac6ece9ff99f177734566965111", "size": 2955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/proto/test/calculator.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/proto/test/calculator.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/proto/test/calculator.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 26.8636363636, "max_line_length": 91, "alphanum_fraction": 0.592893401, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5992588015730219}}
{"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": "#pragma once\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n\n\nnamespace taiton {\n\n\nnamespace mp = boost::multiprecision;\nusing cint = mp::cpp_int;\nusing lfloat = mp::number<mp::cpp_dec_float<30>>;\n\n\n}\n", "meta": {"hexsha": "8cfedca9d5c485290daca7d14bc6106d700ebc82", "size": 250, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/template/boost_multiprecision.hpp", "max_stars_repo_name": "taiton-k/kyoupuro-template", "max_stars_repo_head_hexsha": "63b9989fa1576c1c380d3b4be277d50413745799", "max_stars_repo_licenses": ["MIT"], "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++/template/boost_multiprecision.hpp", "max_issues_repo_name": "taiton-k/kyoupuro-template", "max_issues_repo_head_hexsha": "63b9989fa1576c1c380d3b4be277d50413745799", "max_issues_repo_licenses": ["MIT"], "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++/template/boost_multiprecision.hpp", "max_forks_repo_name": "taiton-k/kyoupuro-template", "max_forks_repo_head_hexsha": "63b9989fa1576c1c380d3b4be277d50413745799", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.7058823529, "max_line_length": 49, "alphanum_fraction": 0.748, "num_tokens": 64, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5992534327157811}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\nusing namespace boost;\nusing namespace std;\ntypedef property<edge_weight_t, int> EdgeWeightProperty;\ntypedef property<edge_weight_t, int> EdgeWeightProperty;\ntypedef boost::adjacency_list < listS, vecS, undirectedS, no_property, EdgeWeightProperty> mygraph;\nint main()\n{\n    mygraph g;\n    add_edge (0, 1, 8, g);\n    add_edge (0, 3, 18, g);\n    add_edge (1, 2, 20, g);\n    add_edge (2, 3, 2, g);\n    add_edge (3, 1, 1, g);\n    add_edge (1, 3, 7, g);\n    cout << \"Number of edges: \" << num_edges(g) << \"\\n\";\n    cout << \"Number of vertices: \" << num_vertices(g) << \"\\n\";\n    mygraph::vertex_iterator vertexIt, vertexEnd;\n    tie(vertexIt, vertexEnd) = vertices(g);\n    for (; vertexIt != vertexEnd; ++vertexIt)\n    {\n        std::cout << \"in-degree for \" << *vertexIt << \": \"<< in_degree(*vertexIt, g) << \"\\n\";\n        std::cout << \"out-degree for \" << *vertexIt << \": \"<< out_degree(*vertexIt, g) << \"\\n\";\n    }\n    mygraph::edge_iterator edgeIt, edgeEnd;\n    tie(edgeIt, edgeEnd) = edges(g);\n    for (; edgeIt!= edgeEnd; ++edgeIt)\n    {\n        std::cout << \"edge \" << source(*edgeIt, g) << \"-->\"<< target(*edgeIt, g) << \"\\n\";\n    }\n}\n", "meta": {"hexsha": "5610b425a0cc434a6c9d241aecaf7bc4bae58eca", "size": 1198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "5Graph_accesses_using_BGL.cpp", "max_stars_repo_name": "mohsenuss91/BGL_workshop", "max_stars_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T18:40:32.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-12T18:40:32.000Z", "max_issues_repo_path": "5Graph_accesses_using_BGL.cpp", "max_issues_repo_name": "mohsenuss91/IBM_BGL", "max_issues_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5Graph_accesses_using_BGL.cpp", "max_forks_repo_name": "mohsenuss91/IBM_BGL", "max_forks_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.303030303, "max_line_length": 99, "alphanum_fraction": 0.6001669449, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5992534225512134}}
{"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": "#pragma once\n\n#include \"../PolynomialBasisGen.hh\"\n#include \"RBFKernel.hh\"\n#include \"FiniteDifferentiator.hh\"\n#include <Eigen/Dense>\n#include <boost/tuple/tuple.hpp>\n#include <boost/static_assert.hpp>\n#include <vector>\n\nnamespace kt84 {\n\ntemplate <int _DimIn, int _DimOut, class _RBFKernel_Core, int _DegreePolynomial>\nstruct GeneralizedMLS\n    : public FiniteDifferentiator<GeneralizedMLS<_DimIn, _DimOut, _RBFKernel_Core, _DegreePolynomial>, _DimIn, _DimOut>\n{\n    enum {\n        DimIn  = _DimIn,\n        DimOut = _DimOut,\n        DegreePolynomial = _DegreePolynomial,\n    };\n    \n    typedef Eigen::Matrix<double, DimIn , 1> Point;\n    typedef Eigen::Matrix<double, DimOut, 1> Value;\n    typedef Eigen::Matrix<double, DimOut, DimIn> Gradient;\n    typedef PolynomialBasisGen<DimIn, DegreePolynomial> PolynomialBasisGen;\n    typedef RBFKernel_Bivariate<DimIn, _RBFKernel_Core> Kernel;\n    typedef boost::tuple<Point, Value, Gradient> Constraint;\n    \n    BOOST_STATIC_ASSERT(Kernel::Decaying);\n    \n    std::vector<Constraint> constraints;\n    Kernel kernel;\n    \n    void clear_constraints() {\n        constraints.clear();\n    }\n    void add_constraint(const Point& point, const Value& value, const Gradient& gradient) {\n        constraints.push_back(Constraint(point, value, gradient));\n    }\n    Value operator()(const Point& point) const {\n        const int P = PolynomialBasisGen::DimOut;\n        Eigen::Matrix<double, P, P> A;\n        Eigen::Matrix<double, P, DimOut> b;\n        A.setZero();\n        b.setZero();\n        for (size_t i = 0; i < constraints.size(); ++i) {\n            const Point& point_i = constraints[i].get<0>();\n            const Value& value_i = constraints[i].get<1>();\n            const Gradient& gradient_i = constraints[i].get<2>();\n            double w_i = kernel(point, point_i);\n            if (w_i == std::numeric_limits<double>::infinity())\n                return value_i;\n            w_i = w_i * w_i;\n            // value constraint\n            PolynomialBasisGen::Basis basis_i = PolynomialBasisGen::basis(point_i);\n            A += w_i * basis_i * basis_i.transpose();\n            b += w_i * basis_i * value_i.transpose();\n            // gradient constraint\n            PolynomialBasisGen::Gradient basis_i_gradient = PolynomialBasisGen::gradient(point_i);\n            A += w_i * basis_i_gradient * basis_i_gradient.transpose();\n            b += w_i * basis_i_gradient * gradient_i.transpose();\n        }\n        Eigen::Matrix<double, P, DimOut> c = A.colPivHouseholderQr().solve(b);\n        return c.transpose() * PolynomialBasisGen::basis(point);\n    }\n};\n\n}\n\n", "meta": {"hexsha": "ceff0ac9369059fbad0ca8a3605ec8fecd54f479", "size": 2600, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/math/GeneralizedMLS.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/GeneralizedMLS.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/GeneralizedMLS.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": 36.6197183099, "max_line_length": 119, "alphanum_fraction": 0.6446153846, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5992220270185843}}
{"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": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2012-2015 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_SQRT_2O_2_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_SQRT_2O_2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate value \\f$\\frac{\\sqrt2}2\\f$\n\n    @par Semantic:\n\n    @code\n    T r = Sqrt_2o_2<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = T(sqrt(T(2)))/T(2);\n    @endcode\n\n    @return The Sqrt_2o_2 constant for the proper type\n  **/\n  template<typename T> T Sqrt_2o_2();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant sqrt_2o_2.\n\n      @return The Sqrt_2o_2 constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::sqrt_2o_2_> sqrt_2o_2 = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/sqrt_2o_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": "048fa32f8ae95dbb8aedcd6e057b40003ac694c8", "size": 1345, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/sqrt_2o_2.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/sqrt_2o_2.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/sqrt_2o_2.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0178571429, "max_line_length": 100, "alphanum_fraction": 0.5940520446, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.5992117784780516}}
{"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": "#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <fstream>\n#include <array>\n#include <random>\n#include <mutex>\n#include <iostream>\n#include <map>\n#include <gtest/gtest.h>\n#include <mpi.h>\n\n#include \"tasktorrent/tasktorrent.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace ttor;\n\ntypedef array<int, 2> int2;\ntypedef array<int, 3> int3;\n\nint VERB = 0;\nint n_threads_ = 4;\nint n_ = 50;\n\n// Simple pseudo random number\n// https://locklessinc.com/articles/prng/\ntypedef unsigned long long u64b;\nint rng64(u64b *s)\n{\n    u64b c = 7319936632422683419ULL;\n    u64b x = s[1];\n\n    /* Increment 128bit counter */\n    s[0] += c;\n    s[1] += c + (s[0] < c);\n\n    /* Two h iterations */\n    x ^= x >> 32;\n    x *= c;\n    x ^= x >> 32;\n    x *= c;\n\n    /* Perturb result */\n    return static_cast<int>(x + s[0]);\n}\n\nvoid ddot(int n_threads, int block_size)\n{\n    // MPI info\n    const int rank = comm_rank();\n    const int n_ranks = comm_size();\n\n    // Problem data\n    // Function used to initialize x and y\n    // i is a global index into the array\n    // x[i] and y[i] are initialized using the value returned by array_initializer(i)\n    function<int(int)> array_initializer = [](int i) {\n        u64b seed[2];\n        seed[0] = i;\n        seed[1] = i + 2019;\n        return rng64(seed) % 1000; // Do not make the integer too large\n    };\n\n    VectorXd z = VectorXd::Zero(n_threads);\n\n    double partial_sum = 0.0;\n    double ddot_sum = 0.0;\n\n    // Initialize the communicator structure\n    Communicator comm(MPI_COMM_WORLD, VERB);\n\n    // Threadpool\n    Threadpool tp(n_threads, &comm, VERB);\n\n    Taskflow<int> dot_tf(&tp, VERB);\n    Taskflow<int> add_tf(&tp, VERB);\n\n    // Create active message\n    auto am = comm.make_active_msg(\n        [&ddot_sum](double &partial_sum) {\n            ddot_sum += partial_sum;\n        });\n\n    // Log\n    DepsLogger dlog(1000000);\n    Logger log(1000000);\n    tp.set_logger(&log);\n\n    // task flow\n    dot_tf.set_mapping([&](int k) {\n              return (k % n_threads);\n          })\n        .set_name([&](int k) {\n            return \"ddot_\" + to_string(k) + \"_\" + to_string(rank);\n        })\n        .set_indegree([](int) {\n            return 1;\n        })\n        .set_task([&](int k) {\n            const int global_index = rank * n_threads * block_size + k * block_size;\n            auto a_init = [&, global_index](int i) {\n                return array_initializer(global_index + i);\n            };\n\n            VectorXd x = VectorXd::NullaryExpr(block_size, a_init);\n            VectorXd y = VectorXd::NullaryExpr(block_size, a_init);\n\n            z[k] = x.dot(y);\n        })\n        .set_fulfill([&](int k) {\n            add_tf.fulfill_promise(0); // same rank\n            dlog.add_event(make_unique<DepsEvent>(dot_tf.name(k), add_tf.name(0)));\n        });\n\n    add_tf.set_mapping([&](int) {\n              return 0;\n          })\n        .set_name([&](int k) {\n            return \"add_\" + to_string(k) + \"_\" + to_string(rank);\n        })\n        .set_indegree([&](int) {\n            return n_threads;\n        })\n        .set_task([&](int) {\n            partial_sum = z.sum();\n        })\n        .set_fulfill([&](int k) {\n            am->send(0, partial_sum);\n            dlog.add_event(make_unique<DepsEvent>(add_tf.name(k), \"Reduce\"));\n        });\n\n    // Seed tasks\n    for (int i = 0; i < n_threads; ++i)\n        dot_tf.fulfill_promise(i);\n\n    tp.join();\n\n    if (rank == 0)\n    {\n        VectorXd x = VectorXd::NullaryExpr(n_ranks * n_threads * block_size, array_initializer);\n        VectorXd y = VectorXd::NullaryExpr(n_ranks * n_threads * block_size, array_initializer);\n\n        double ddot_ref = x.dot(y);\n        auto err = abs(ddot_sum - ddot_ref);\n\n        if (VERB > 0 && err != 0)\n            printf(\"Error: %g, sum = %g; ref = %g\\n\", err, ddot_sum, ddot_ref);\n\n        ASSERT_EQ(err, 0);\n    }\n\n    // Logging\n    std::ofstream logfile;\n    string filename = \"ddot_\" + to_string(rank) + \".log\";\n    logfile.open(filename);\n    logfile << log;\n    logfile.close();\n\n    std::ofstream depsfile;\n    string dfilename = \"ddot_\" + to_string(rank) + \".dot\";\n    depsfile.open(dfilename);\n    depsfile << dlog;\n    depsfile.close();\n}\n\nTEST(ddot, one)\n{\n    int n_threads = n_threads_;\n    int n = n_;\n    ddot(n_threads, n);\n}\n\nint main(int argc, char **argv)\n{\n    ::testing::InitGoogleTest(&argc, argv);\n\n    int req = MPI_THREAD_FUNNELED;\n    int prov = -1;\n\n    MPI_Init_thread(NULL, NULL, req, &prov);\n\n    assert(prov == req);\n\n    if (argc >= 2)\n    {\n        n_threads_ = atoi(argv[1]);\n    }\n\n    if (argc >= 3)\n    {\n        n_ = atoi(argv[2]);\n    }\n\n    if (argc >= 4)\n    {\n        VERB = atoi(argv[3]);\n    }\n\n    if (VERB > 0)\n        printf(\"# threads = %d; block size = %d; VERB = %d\\n\", n_threads_, n_, VERB);\n\n    const int return_flag = RUN_ALL_TESTS();\n\n    MPI_Finalize();\n\n    return return_flag;\n}\n", "meta": {"hexsha": "7137aa2079ae560a127f6205d5434c7bff22a88c", "size": 4892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/mpi/ddot_test.cpp", "max_stars_repo_name": "qyz96/tasktorrent", "max_stars_repo_head_hexsha": "4418d83da7de657363ac99ee263602794a0b97a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2019-09-29T19:33:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:48:40.000Z", "max_issues_repo_path": "tests/mpi/ddot_test.cpp", "max_issues_repo_name": "qyz96/tasktorrent", "max_issues_repo_head_hexsha": "4418d83da7de657363ac99ee263602794a0b97a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-11T18:14:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T22:32:56.000Z", "max_forks_repo_path": "tests/mpi/ddot_test.cpp", "max_forks_repo_name": "qyz96/tasktorrent", "max_forks_repo_head_hexsha": "4418d83da7de657363ac99ee263602794a0b97a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-10-22T06:40:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T08:17:39.000Z", "avg_line_length": 23.5192307692, "max_line_length": 96, "alphanum_fraction": 0.5564186427, "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5990594258098275}}
{"text": "#include <stdio.h>\n#include <iostream>\n#include <math.h>\n#include <string>\n#include <Eigen/Dense>\n#include \"ros/ros.h\"\n\n#include <yaml-cpp/yaml.h>\n#include <ros/package.h>\n\n#include <std_msgs/Float32MultiArray.h>\n#include <sensor_msgs/JointState.h>\n#include <robot_localization_msgs/HeadTransform.h>\n\nusing namespace ros;\nusing namespace std;\nusing namespace Eigen;\n\nfloat angle_head_yaw=0.0;\nfloat angle_head_pitch=0.0;\n    \nvoid jointCallback(const sensor_msgs::JointState::ConstPtr& msg);\n\nbool RobotYamlRead(string path, float* length_pelvis2headyaw, float* length_headyaw2headpitch, float* length_headpitch2camera);\nbool ParticleYamlRead(string path, float& unit);\n\nMatrix4f makeYawMatrix(float& theta);\nMatrix4f makePitchMatrix(float& theta);\nMatrix4f makeTransMatrix(Vector3f& position);\nMatrix4f makeTransMatrix(Vector3f& position, float& unit);\n\nvoid insertMatrix2Message(Matrix4f& matrix, std_msgs::Float32MultiArray& msg);\nvoid insertMatrix2Message(Matrix4f& matrix, robot_localization_msgs::HeadTransform& msg, int flag); // flag=0 -> original, flag=1 -> unit\n\nint main(int argc, char** argv)\n{\n    //read setting\n    string yaml_robot_path = package::getPath(\"robot_localization_data\") + \"/data/kin_dyn_2.yaml\";\n    string yaml_particle_path = package::getPath(\"robot_localization_data\") + \"/data/particle_setting.yaml\";\n   \n    float length_pelvis2headyaw[3];\n    float length_headyaw2headpitch[3];\n    float length_headpitch2camera[3];\n\n    float unit;\n   \n    if( !RobotYamlRead(yaml_robot_path, length_pelvis2headyaw, length_headyaw2headpitch, length_headpitch2camera) ) exit(0);\n    if( !ParticleYamlRead(yaml_particle_path, unit) ) exit(0);\n    \n    Vector3f V_length_pelvis2headyaw(length_pelvis2headyaw[0],length_pelvis2headyaw[1],length_pelvis2headyaw[2]);\n    Vector3f V_length_headyaw2headpitch(length_headyaw2headpitch[0],length_headyaw2headpitch[1],length_headyaw2headpitch[2]);\n    Vector3f V_length_headpitch2camera(length_headpitch2camera[0], length_headpitch2camera[1], length_headpitch2camera[2]);\n    \n\n    //start ros\n    ros::init(argc, argv, \"robot_localization_head_receive2\");\n    ros::NodeHandle n;\n    ros::Rate loop_rate(100);\n\n    ros::Publisher headtransform_pub = n.advertise<std_msgs::Float32MultiArray>(\"/alice/camera_transform\",10);\n    ros::Publisher custom_headtransform_pub = n.advertise<robot_localization_msgs::HeadTransform>(\"/robot_localization/head_transform\",10);\n    ros::Subscriber joint_sub = n.subscribe(\"/robotis/present_joint_states\",10,jointCallback);\n\n    while(ros::ok())\n    {\n        std_msgs::Float32MultiArray headtransform_msg;\n        robot_localization_msgs::HeadTransform custom_headtransform_msg;\n\n        //real world\n        Matrix4f t_pelvis2headyaw = makeTransMatrix(V_length_pelvis2headyaw);\n        Matrix4f r_pelvis2headyaw = Matrix4f::Identity();\n        \n        Matrix4f t_headyaw2headpitch = makeTransMatrix(V_length_headyaw2headpitch);\n        Matrix4f r_headyaw2headpitch = makeYawMatrix(angle_head_yaw);\n\n        Matrix4f t_headpitch2camera = makeTransMatrix(V_length_headpitch2camera);\n        Matrix4f r_headpitch2camera = makePitchMatrix(angle_head_pitch);\n\n        Matrix4f TR01 = r_pelvis2headyaw * t_pelvis2headyaw;\n        Matrix4f TR12 = r_headyaw2headpitch * t_headyaw2headpitch;\n        Matrix4f TR23 = r_headpitch2camera * t_headpitch2camera;\n\n        Matrix4f Transform_pelvis2head = TR01 * TR12 * TR23;\n\n        //virtual world\n        Matrix4f t_pelvis2headyaw_V = makeTransMatrix(V_length_pelvis2headyaw, unit);\n        Matrix4f t_headyaw2headpitch_V = makeTransMatrix(V_length_headyaw2headpitch, unit);\n        Matrix4f t_headpitch2camera_V = makeTransMatrix(V_length_headpitch2camera, unit);\n\n        Matrix4f TV01 = r_pelvis2headyaw * t_pelvis2headyaw_V;\n        Matrix4f TV12 = r_headyaw2headpitch * t_headyaw2headpitch_V;\n        Matrix4f TV23 = r_headpitch2camera * t_headpitch2camera_V;\n\n        Matrix4f unit_Transform_pelvis2head = TV01 * TV12 * TV23;\n\n        insertMatrix2Message(Transform_pelvis2head, headtransform_msg); \n\n        insertMatrix2Message(Transform_pelvis2head, custom_headtransform_msg, 0);\n        insertMatrix2Message(unit_Transform_pelvis2head, custom_headtransform_msg, 1);\n\n        headtransform_pub.publish(headtransform_msg);\n        custom_headtransform_pub.publish(custom_headtransform_msg);\n      \n        cout << \"-----------------------------------------------\" << endl;\n        cout << \"head_yaw : \" << angle_head_yaw * 180 / M_PI << endl;\n        cout << \"head_pitch : \" << angle_head_pitch * 180 / M_PI << endl;\n        cout << \"-----------------------------------------------\" << endl;\n\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n\n    return 0;\n}\n\nvoid jointCallback(const sensor_msgs::JointState::ConstPtr& msg)\n{\n    int head_yaw_index, head_pitch_index;\n    for(int i=0; i<(msg->name).size(); i++)\n    {\n        if(msg->name[i] == \"head_yaw\"   ) head_yaw_index = i;\n        if(msg->name[i] == \"head_pitch\" ) head_pitch_index = i;\n    }\n\n    angle_head_yaw = msg->position[head_yaw_index];\n    angle_head_pitch = msg->position[head_pitch_index];\n}\n\nbool RobotYamlRead(string path, float* length_pelvis2headyaw, float* length_headyaw2headpitch, float* length_headpitch2camera)\n{\n    YAML::Node yaml_node;\n    try\n    {\n        yaml_node = YAML::LoadFile(path.c_str());\n        length_pelvis2headyaw[0]    = yaml_node[\"head_y\"][\"relative_position\"][0].as<float>();\n        length_pelvis2headyaw[1]    = yaml_node[\"head_y\"][\"relative_position\"][1].as<float>();\n        length_pelvis2headyaw[2]    = yaml_node[\"head_y\"][\"relative_position\"][2].as<float>();\n\n        length_headyaw2headpitch[0] = yaml_node[\"head_p\"][\"relative_position\"][0].as<float>();\n        length_headyaw2headpitch[1] = yaml_node[\"head_p\"][\"relative_position\"][1].as<float>();\n        length_headyaw2headpitch[2] = yaml_node[\"head_p\"][\"relative_position\"][2].as<float>();\n\n        length_headpitch2camera[0]  = yaml_node[\"cam\"][\"relative_position\"][0].as<float>();\n        length_headpitch2camera[1]  = yaml_node[\"cam\"][\"relative_position\"][1].as<float>();\n        length_headpitch2camera[2]  = yaml_node[\"cam\"][\"relative_position\"][2].as<float>();\n    }\n    catch(const exception& e)\n    {\n        ROS_ERROR(\"fail to read robot yaml file\");\n        return false;\n    }\n    return true;\n}\n\nbool ParticleYamlRead(string path, float& unit)\n{\n    YAML::Node yaml_node;\n    try\n    {\n        yaml_node = YAML::LoadFile(path.c_str());\n        unit = yaml_node[\"ETCSetting\"][\"unit\"].as<float>();\n    }\n    catch(const exception& e)\n    {\n        ROS_ERROR(\"fail to read particle yaml file\");\n        return false;\n    }\n    return true;\n}\n\nvoid insertMatrix2Message(Matrix4f& matrix, std_msgs::Float32MultiArray& msg)\n{\n    for(int i=0; i<4; i++)\n        for(int j=0; j<4; j++)\n            msg.data.push_back(matrix(i,j));\n}\n\nvoid insertMatrix2Message(Matrix4f& matrix, robot_localization_msgs::HeadTransform& msg, int flag)\n{\n    switch(flag)\n    {\n        case 0:\n            for(int i=0; i<4; i++)\n                for(int j=0; j<4; j++)\n                    msg.Tdata.push_back(matrix(i,j));\n            break;\n        case 1:\n            for(int i=0; i<4; i++)\n                for(int j=0; j<4; j++)\n                    msg.Udata.push_back(matrix(i,j));\n            break;\n        default:\n            break;\n    }\n}\n\nMatrix4f makeYawMatrix(float& theta)\n{\n    Matrix4f matrix;\n    matrix(0,0)=cos(theta); matrix(0,1)=-sin(theta); matrix(0,2)=0; matrix(0,3)=0;\n    matrix(1,0)=sin(theta); matrix(1,1)= cos(theta); matrix(1,2)=0; matrix(1,3)=0;\n    matrix(2,0)=0;          matrix(2,1)=0;           matrix(2,2)=1; matrix(2,3)=0;\n    matrix(3,0)=0;          matrix(3,1)=0;           matrix(3,2)=0; matrix(3,3)=1;\n\n    return matrix;\n}\n\nMatrix4f makePitchMatrix(float& theta)\n{\n    Matrix4f matrix;\n    matrix(0,0)= cos(theta); matrix(0,1)=0; matrix(0,2)=sin(theta); matrix(0,3)=0;\n    matrix(1,0)=0;           matrix(1,1)=1; matrix(1,2)=0;          matrix(1,3)=0;\n    matrix(2,0)=-sin(theta); matrix(2,1)=0; matrix(2,2)=cos(theta); matrix(2,3)=0;\n    matrix(3,0)=0;           matrix(3,1)=0; matrix(3,2)=0;          matrix(3,3)=1;\n\n    return matrix;\n}\n\nMatrix4f makeTransMatrix(Vector3f& position)\n{\n    Matrix4f matrix;\n    matrix(0,0)=1; matrix(0,1)=0; matrix(0,2)=0; matrix(0,3)=position(0);\n    matrix(1,0)=0; matrix(1,1)=1; matrix(1,2)=0; matrix(1,3)=position(1);\n    matrix(2,0)=0; matrix(2,1)=0; matrix(2,2)=1; matrix(2,3)=position(2);\n    matrix(3,0)=0; matrix(3,1)=0; matrix(3,2)=0; matrix(3,3)=1;\n\n    return matrix;\n}\n\nMatrix4f makeTransMatrix(Vector3f& position, float& unit)\n{\n    Matrix4f matrix;\n    matrix(0,0)=1; matrix(0,1)=0; matrix(0,2)=0; matrix(0,3)=position(0)*unit;\n    matrix(1,0)=0; matrix(1,1)=1; matrix(1,2)=0; matrix(1,3)=position(1)*unit;\n    matrix(2,0)=0; matrix(2,1)=0; matrix(2,2)=1; matrix(2,3)=position(2)*unit;\n    matrix(3,0)=0; matrix(3,1)=0; matrix(3,2)=0; matrix(3,3)=1;\n\n    return matrix;\n}\n", "meta": {"hexsha": "c8eec3a457241c241d280716368278b053726cd1", "size": 8957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "robot_localization_head_receive/src/robot_localization_head_receive2.cpp", "max_stars_repo_name": "lgkimjy/RobotLocalization_autumn", "max_stars_repo_head_hexsha": "c5caacb6b20a347e2a756d4f50124e1723b9b696", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-21T06:46:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T19:25:41.000Z", "max_issues_repo_path": "robot_localization_head_receive/src/robot_localization_head_receive2.cpp", "max_issues_repo_name": "lgkimjy/RobotLocalization_autumn", "max_issues_repo_head_hexsha": "c5caacb6b20a347e2a756d4f50124e1723b9b696", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "robot_localization_head_receive/src/robot_localization_head_receive2.cpp", "max_forks_repo_name": "lgkimjy/RobotLocalization_autumn", "max_forks_repo_head_hexsha": "c5caacb6b20a347e2a756d4f50124e1723b9b696", "max_forks_repo_licenses": ["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.3208333333, "max_line_length": 139, "alphanum_fraction": 0.6681924752, "num_tokens": 2579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5990136244742813}}
{"text": "#ifndef __HCINDEXSET__CLASS__\n#define __HCINDEXSET__CLASS__\n\n#include \"SparseIndexSet.hpp\"\n\n#include <Eigen/Dense>\n\n/** \\brief Hyperbolic cross is implemented as a simple addon for the\n*          sparseIndexSet class which provides the corresponding comparison\n*          functor. Weights my be unsorted in HC case and no sorting is\n*          performed.\n*/\nclass HCindexSet : public SparseIndexSet {\n public:\n  void computeIndexSet(int q, const Eigen::VectorXd &w) {\n    SparseIndexSet::computeIndexSet(q, w.size(), HCindexSet::cpFun(w));\n  };\n\n protected:\n  struct cpFun {\n    Eigen::VectorXd _w;\n    cpFun(const Eigen::VectorXd &w) : _w(w){};\n    double operator()(const Eigen::VectorXi &alpha) const {\n      double skap = 1;\n      for (int i = 0; i < _w.size(); ++i)\n        skap *= std::pow(alpha(i) + 1., _w(i));\n      return skap - 1.;\n    }\n  };\n};\n#endif\n", "meta": {"hexsha": "ffb40e7963f285bfadb180566479c2e037c99598", "size": 864, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "HCindexSet.hpp", "max_stars_repo_name": "T3ks/SPQR", "max_stars_repo_head_hexsha": "b554d172fc798caa7a708bfbbb71a21d136403b1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-09-11T12:02:57.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-11T12:02:57.000Z", "max_issues_repo_path": "HCindexSet.hpp", "max_issues_repo_name": "T3ks/SPQR", "max_issues_repo_head_hexsha": "b554d172fc798caa7a708bfbbb71a21d136403b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HCindexSet.hpp", "max_forks_repo_name": "T3ks/SPQR", "max_forks_repo_head_hexsha": "b554d172fc798caa7a708bfbbb71a21d136403b1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-01-28T02:25:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-12T16:43:19.000Z", "avg_line_length": 27.0, "max_line_length": 75, "alphanum_fraction": 0.6527777778, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5989426177316798}}
{"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 \u00a9 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": "// Test different solvers on mtx file\n// Author: Max Schwarz <max.schwarz@uni-bonn.de>\n\n#include <Eigen/Sparse>\n#include <unsupported/Eigen/SparseExtra>\n\n#ifdef KLU_SUPPORT\n#include \"../eigen_klu.h\"\n#endif\n\n#ifdef EIGEN_UMFPACK_SUPPORT\n#include \"UmfPackSupport.h\"\n#endif\n\n#include <chrono>\n\ntemplate<class Solver>\nvoid testSolver(const Eigen::SparseMatrix<double>& A, const Eigen::VectorXd& b)\n{\n\tstd::cout << \"\\n\\nSolving with solver \" << typeid(Solver).name() << \"\\n\";\n\n\tSolver solver;\n\n\tauto t0 = std::chrono::high_resolution_clock::now();\n\n\tsolver.compute(A);\n\tauto x = solver.solve(b);\n\n\tauto t1 = std::chrono::high_resolution_clock::now();\n\n\tstd::cout << \"... took \" << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count() << \" ms.\\n\";\n\n\tEigen::VectorXd residual = A*x - b;\n\n\tprintf(\"residual norm: %e\\n\", residual.norm());\n}\n\nint main(int argc, char** argv)\n{\n\tif(argc <= 1)\n\t{\n\t\tfprintf(stderr, \"Usage: solve_test <prefix>\\n\");\n\t}\n\n\tEigen::SparseMatrix<double> A;\n\tEigen::VectorXd b;\n\n\tA.makeCompressed();\n\n\tstd::string prefix = argv[1];\n\tEigen::loadMarket(A, prefix + \".mtx\");\n\tEigen::loadMarketVector(b, prefix + \"_b.mtx\");\n\n#ifdef KLU_SUPPORT\n\ttestSolver<Eigen::KLU<Eigen::SparseMatrix<double>>>(A, b);\n#endif\n#ifdef EIGEN_UMFPACK_SUPPORT\n\ttestSolver<Eigen::UmfPackLU<Eigen::SparseMatrix<double>>>(A, b);\n#endif\n\n\treturn 0;\n}\n", "meta": {"hexsha": "785f521017fce2d6c59cc897bd70a2e6a169835c", "size": 1355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depth_filler/src/solve_test/solve_test.cpp", "max_stars_repo_name": "warehouse-picking-automation-challenges/nimbro_picking", "max_stars_repo_head_hexsha": "857eee602beea9eebee45bbb67fce423b28f9db6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2017-11-02T03:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T19:40:15.000Z", "max_issues_repo_path": "depth_filler/src/solve_test/solve_test.cpp", "max_issues_repo_name": "warehouse-picking-automation-challenges/nimbro_picking", "max_issues_repo_head_hexsha": "857eee602beea9eebee45bbb67fce423b28f9db6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "depth_filler/src/solve_test/solve_test.cpp", "max_forks_repo_name": "warehouse-picking-automation-challenges/nimbro_picking", "max_forks_repo_head_hexsha": "857eee602beea9eebee45bbb67fce423b28f9db6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-16T02:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T14:06:35.000Z", "avg_line_length": 21.5079365079, "max_line_length": 112, "alphanum_fraction": 0.6885608856, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5988871666468085}}
{"text": "#include <test_common.h>\n#include <Eigen/Dense>\n\n#include <igl/copyleft/cgal/remesh_self_intersections.h>\n#include <igl/copyleft/cgal/RemeshSelfIntersectionsParam.h>\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n\nTEST_CASE(\"RemeshSelfIntersections: CubeWithFold\", \"[igl/copyleft/cgal]\")\n{\n    Eigen::MatrixXd V;\n    Eigen::MatrixXi F;\n    igl::read_triangle_mesh(test_common::data_path(\"cube_with_fold.ply\"), V, F);\n\n    typedef CGAL::Exact_predicates_exact_constructions_kernel K;\n    typedef Eigen::Matrix<K::FT, Eigen::Dynamic, Eigen::Dynamic> MatrixXe;\n\n    MatrixXe VV;\n    Eigen::MatrixXi FF, IF;\n    Eigen::VectorXi J, IM;\n    igl::copyleft::cgal::RemeshSelfIntersectionsParam param;\n    igl::copyleft::cgal::remesh_self_intersections(V, F, param, VV, FF, IF, J, IM);\n}\n", "meta": {"hexsha": "172a93d77be2b543c11025850880bab2de4eeafd", "size": 794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/libigl/tests/include/igl/copyleft/cgal/remesh_self_intersections.cpp", "max_stars_repo_name": "V-Sekai/godot-tri", "max_stars_repo_head_hexsha": "8f1c1529b26ebec5928800c7f87da72a0fd03748", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-25T04:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-30T14:16:34.000Z", "max_issues_repo_path": "external/libigl/tests/include/igl/copyleft/cgal/remesh_self_intersections.cpp", "max_issues_repo_name": "V-Sekai/godot-tri", "max_issues_repo_head_hexsha": "8f1c1529b26ebec5928800c7f87da72a0fd03748", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/libigl/tests/include/igl/copyleft/cgal/remesh_self_intersections.cpp", "max_forks_repo_name": "V-Sekai/godot-tri", "max_forks_repo_head_hexsha": "8f1c1529b26ebec5928800c7f87da72a0fd03748", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-05T01:11:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T01:12:03.000Z", "avg_line_length": 33.0833333333, "max_line_length": 83, "alphanum_fraction": 0.7455919395, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5988871666468085}}
{"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": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TOOLBOX_EXPONENTIAL_CONSTANTS_LOG_2_HPP_INCLUDED\n#define NT2_TOOLBOX_EXPONENTIAL_CONSTANTS_LOG_2_HPP_INCLUDED\n/*!\n * \\file\n**/\n#include <boost/simd/sdk/constant/constant.hpp>\n#include <boost/simd/sdk/constant/register.hpp>\n\n/*!\n * \\ingroup expon_constant\n * \\defgroup expon_constant_log_2 Log_2\n *\n * \\par Description\n * Constant log_2 : \\f$\\log(2)\\f$ constant.\n * \\par\n * The value of this constant is type dependant. This means that for different\n * types it does not represent the same mathematical number.\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/log_2.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::log_2_(A0)>::type\n *     log_2();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Log_2\n *\n * \\return type T value\n *\n *\n**/\n\nnamespace nt2\n{\n  namespace tag\n  {\n    BOOST_SIMD_CONSTANT_REGISTER( Log_2, double\n                                , 0, 0x3f317218\n                                , 0x3fe62e42fefa39efLL\n                                );\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Log_2, Log_2);\n}\n\n#endif\n", "meta": {"hexsha": "e9119ce13e78ac7523a568eb9277b45a8d37e055", "size": 1669, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/toolbox/exponential/constants/log_2.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/exponential/include/nt2/toolbox/exponential/constants/log_2.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/exponential/include/nt2/toolbox/exponential/constants/log_2.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9104477612, "max_line_length": 80, "alphanum_fraction": 0.5674056321, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7185943865443352, "lm_q1q2_score": 0.5988223704114719}}
{"text": "#pragma once\n\n#include <map>\n#include <set>\n#include <utility>\n#include <vector>\n\n#include <boost/serialization/utility.hpp>\n#include <boost/serialization/set.hpp>\n\n#include <gmpxx.h>\n\nstruct eval_mat {\n  friend class boost::serialization::access;\n\n  std::set<std::pair<std::pair<size_t, size_t>, int>> values;\n\n  template<class Archive>\n  void serialize (Archive & ar, unsigned int const);\n\n  void save (std::string const & filename) const;\n\n  void load (std::string const & filename);\n\n  std::set<size_t> row_set () const;\n\n};\n\nstd::set<size_t> findDependentVariables (std::set<std::pair<std::pair<size_t, size_t>, mpq_class>> const & matrix, size_t rows, size_t cols);\n\nstd::map<size_t, std::map<size_t, mpq_class>> solveLinearSystem (std::set<std::pair<std::pair<size_t, size_t>, mpq_class>> const & matrix, size_t rows, size_t cols);\n", "meta": {"hexsha": "b0cea40bee9da11dc5e090282dcb930e858c933d", "size": 839, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/LinearAlgebra.hxx", "max_stars_repo_name": "nilsalex/tensor-trees", "max_stars_repo_head_hexsha": "48b5b4f6932705bac7160bb3379f6066222f9b70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/LinearAlgebra.hxx", "max_issues_repo_name": "nilsalex/tensor-trees", "max_issues_repo_head_hexsha": "48b5b4f6932705bac7160bb3379f6066222f9b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/LinearAlgebra.hxx", "max_forks_repo_name": "nilsalex/tensor-trees", "max_forks_repo_head_hexsha": "48b5b4f6932705bac7160bb3379f6066222f9b70", "max_forks_repo_licenses": ["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.21875, "max_line_length": 165, "alphanum_fraction": 0.7163289631, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5988088829047181}}
{"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": "#include <iostream>\n#include <typeinfo>\r\n#define BOOST_TEST_MODULE DenseMIAFunctionTests\n\r\n\n\n#include \"MIAConfig.h\"\n\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\n\r\n#include \"DenseMIA.h\"\n#include \"Index.h\"\n\r\ntemplate<class _data_type>\r\nvoid functions_work(){\r\n\r\n    LibMIA::MIAINDEX i;\n    LibMIA::MIAINDEX j;\n    LibMIA::MIAINDEX k;\r\n    LibMIA::MIAINDEX l;\r\n\n//    size_t dim1=10;\r\n//    size_t dim2=11;\r\n//    size_t dim3=20;\r\n//    size_t dim4=15;\r\n    size_t dim1=2;\r\n    size_t dim2=3;\r\n    size_t dim3=4;\r\n    size_t dim4=15;\n\r\n    LibMIA::DenseMIA<_data_type,2> e(dim1,dim2);\r\n    LibMIA::DenseMIA<_data_type,2> e2(dim1,dim2);\r\n    LibMIA::DenseMIA<_data_type,2> f;\r\n    LibMIA::DenseMIA<_data_type,3> a(dim1,dim2,dim3);\r\n    LibMIA::DenseMIA<_data_type,3> a2(dim1,dim2,dim3);\r\n    LibMIA::DenseMIA<_data_type,3> b;\r\n    LibMIA::DenseMIA<_data_type,4> c(dim1,dim2,dim3,dim4);\r\n    LibMIA::DenseMIA<_data_type,4> c2(dim1,dim2,dim3,dim4);\r\n    LibMIA::DenseMIA<_data_type,4> d;\r\n\r\n    //****************In place permutation\r\n    e.randu(-50,50);\r\n    e2=e;\r\n    f(j,i)=e(i,j);\r\n    e2.inplace_permute(1,0);\r\n    //e.print();\r\n    //f.print();\r\n    //e2.print();\r\n    BOOST_CHECK_MESSAGE(f==e2,std::string(\"Second-order in place permutation 1 for \")+typeid(_data_type).name());\r\n\r\n    a.randu(-50,50);\r\n    //a.print();\r\n    a2=a;\r\n\r\n    b(j,k,i)=a(i,j,k);\r\n\r\n    a2.inplace_permute(1,2,0);\r\n\r\n    //b.print();\r\n    //a2.print();\r\n    BOOST_CHECK_MESSAGE(b==a2,std::string(\"Third-order in place permutation 1 for \")+typeid(_data_type).name());\r\n    a2=a;\r\n    b(k,i,j)=a(i,j,k);\r\n    a2.inplace_permute(2,0,1);\r\n    BOOST_CHECK_MESSAGE(b==a2,std::string(\"Third-order in place permutation 2 for \")+typeid(_data_type).name());\r\n\r\n    c.randu(-50,50);\r\n    c2=c;\r\n    d(k,l,i,j)=c(i,j,k,l);\r\n    c2.inplace_permute(2,3,0,1);\r\n    BOOST_CHECK_MESSAGE(d==c2,std::string(\"Fourth-order in place permutation 1 for \")+typeid(_data_type).name());\r\n\r\n    c2=c;\r\n    d(j,l,i,k)=c(i,j,k,l);\r\n    c2.inplace_permute(1,3,0,2);\r\n    BOOST_CHECK_MESSAGE(d==c2,std::string(\"Fourth-order in place permutation 2 for \")+typeid(_data_type).name());\r\n\r\n    auto lat1=d.toLatticeCopy(std::array<size_t, 1>{{3}},std::array<size_t, 2>{{2,1}},std::array<size_t, 1>{{0}});\r\n    auto lat2=d.toLatticePermute(std::array<size_t, 1>{{3}},std::array<size_t, 2>{{2,1}},std::array<size_t, 1>{{0}});\r\n    BOOST_CHECK_MESSAGE(lat1==lat2,std::string(\"Lattice Mapping test for \")+typeid(_data_type).name());\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( DenseMIAFunctionTests )\n{\n\n\r\n\r\n    functions_work<double>();\r\n\n    functions_work<float>();\r\n    functions_work<int>();\r\n    functions_work<long>();\r\n\r\n\r\n\r\n\r\n\n\n}\n", "meta": {"hexsha": "c2943be135a3dc5f72b5a6bbfdb232bb960628a6", "size": 2751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/DenseMIA/dense_mia_functions.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/DenseMIA/dense_mia_functions.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/DenseMIA/dense_mia_functions.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 26.2, "max_line_length": 118, "alphanum_fraction": 0.627044711, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.5987275848525431}}
{"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// \u524d\u9762\u51e0\u4e2a\u6587\u4ef6\u5df2\u7ecf\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u8bb2\u8fc7\u4e86\uff0c\u56e0\u6b64\u4e0d\u518d\u505a\u8fdb\u4e00\u6b65\u7684\u8bc4\u8bba\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n\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// \u4ece\u4e0b\u9762\u7684include\u6587\u4ef6\u4e2d\u6211\u4eec\u5c06\u5bfc\u5165H1-conforming\u6709\u9650\u5143\u5f62\u72b6\u51fd\u6570\u7684\u58f0\u660e\u3002\u8fd9\u4e2a\u6709\u9650\u5143\u7cfb\u5217\u88ab\u79f0\u4e3a  <code>FE_Q</code>  \uff0c\u5728\u4e4b\u524d\u7684\u6240\u6709\u4f8b\u5b50\u4e2d\u5df2\u7ecf\u88ab\u7528\u6765\u5b9a\u4e49\u901a\u5e38\u7684\u53cc\u7ebf\u6027\u6216\u4e09\u7ebf\u6027\u5143\u7d20\uff0c\u4f46\u6211\u4eec\u73b0\u5728\u5c06\u7528\u5b83\u6765\u5b9a\u4e49\u53cc\u4e8c\u6b21\u5143\u5143\u7d20\u3002\n\n#include <deal.II/fe/fe_q.h> \n\n// \u6211\u4eec\u4e0d\u4f1a\u50cf\u524d\u9762\u7684\u4f8b\u5b50\u90a3\u6837\u4ece\u6587\u4ef6\u4e2d\u8bfb\u53d6\u7f51\u683c\uff0c\u800c\u662f\u4f7f\u7528\u5e93\u4e2d\u7684\u4e00\u4e2a\u51fd\u6570\u751f\u6210\u7f51\u683c\u3002\u7136\u800c\uff0c\u6211\u4eec\u5c06\u5e0c\u671b\u5728\u6bcf\u4e00\u6b65\u4e2d\u5199\u51fa\u5c40\u90e8\u7ec6\u5316\u7684\u7f51\u683c\uff08\u53ea\u662f\u7f51\u683c\uff0c\u800c\u4e0d\u662f\u89e3\u51b3\u65b9\u6848\uff09\uff0c\u6240\u4ee5\u6211\u4eec\u9700\u8981\u4ee5\u4e0b\u7684include\u6587\u4ef6\uff0c\u800c\u4e0d\u662f <code>grid_in.h</code>  \u3002\n\n#include <deal.II/grid/grid_out.h> \n\n// \u5f53\u4f7f\u7528\u5c40\u90e8\u7ec6\u5316\u7f51\u683c\u65f6\uff0c\u6211\u4eec\u4f1a\u5f97\u5230\u6240\u8c13\u7684<code>\u60ac\u7a7a\u8282\u70b9</code>\u3002\u7136\u800c\uff0c\u6807\u51c6\u7684\u6709\u9650\u5143\u65b9\u6cd5\u5047\u5b9a\u79bb\u6563\u7684\u89e3\u7a7a\u95f4\u662f\u8fde\u7eed\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u9700\u8981\u786e\u4fdd\u60ac\u6302\u8282\u70b9\u4e0a\u7684\u81ea\u7531\u5ea6\u7b26\u5408\u4e00\u4e9b\u7ea6\u675f\u6761\u4ef6\uff0c\u8fd9\u6837\u5168\u5c40\u89e3\u662f\u8fde\u7eed\u7684\u3002\u6211\u4eec\u4e5f\u8981\u5728\u8fd9\u4e2a\u5bf9\u8c61\u4e2d\u5b58\u50a8\u8fb9\u754c\u6761\u4ef6\u3002\u4e0b\u9762\u7684\u6587\u4ef6\u5305\u542b\u4e00\u4e2a\u7528\u6765\u5904\u7406\u8fd9\u4e9b\u7ea6\u675f\u6761\u4ef6\u7684\u7c7b\u3002\n\n#include <deal.II/lac/affine_constraints.h> \n\n// \u4e3a\u4e86\u5728\u672c\u5730\u7ec6\u5316\u6211\u4eec\u7684\u7f51\u683c\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u6765\u81ea\u5e93\u7684\u51fd\u6570\uff0c\u6839\u636e\u6211\u4eec\u8ba1\u7b97\u7684\u8bef\u5dee\u6307\u6807\u6765\u51b3\u5b9a\u54ea\u4e9b\u5355\u5143\u9700\u8981\u7ec6\u5316\u6216\u7c97\u5316\u3002\u8fd9\u4e2a\u51fd\u6570\u88ab\u5b9a\u4e49\u5728\u8fd9\u91cc\u3002\n\n#include <deal.II/grid/grid_refinement.h> \n\n// \u6700\u540e\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u7b80\u5355\u7684\u65b9\u6cd5\u6765\u5b9e\u9645\u8ba1\u7b97\u57fa\u4e8e\u67d0\u79cd\u8bef\u5dee\u4f30\u8ba1\u7684\u7ec6\u5316\u6307\u6807\u3002\u867d\u7136\u4e00\u822c\u6765\u8bf4\uff0c\u9002\u5e94\u6027\u662f\u975e\u5e38\u5177\u4f53\u7684\u95ee\u9898\uff0c\u4f46\u4ee5\u4e0b\u6587\u4ef6\u4e2d\u7684\u8bef\u5dee\u6307\u6807\u901a\u5e38\u4f1a\u5bf9\u4e00\u5927\u7c7b\u95ee\u9898\u4ea7\u751f\u76f8\u5f53\u597d\u7684\u9002\u5e94\u7f51\u683c\u3002\n\n#include <deal.II/numerics/error_estimator.h> \n\n// \u6700\u540e\uff0c\u8fd9\u548c\u4ee5\u524d\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\nusing namespace dealii; \n// @sect3{The <code>Step6</code> class template}  \n\n// \u4e3b\u7c7b\u53c8\u662f\u51e0\u4e4e\u6ca1\u6709\u53d8\u5316\u7684\u3002\u7136\u800c\uff0c\u6211\u4eec\u589e\u52a0\u4e86\u4e24\u9879\u5185\u5bb9\uff1a\u6211\u4eec\u589e\u52a0\u4e86 <code>refine_grid</code> \u51fd\u6570\uff0c\u8be5\u51fd\u6570\u7528\u4e8e\u81ea\u9002\u5e94\u5730\u7ec6\u5316\u7f51\u683c\uff08\u800c\u4e0d\u662f\u4e4b\u524d\u4f8b\u5b50\u4e2d\u7684\u5168\u5c40\u7ec6\u5316\uff09\uff0c\u8fd8\u6709\u4e00\u4e2a\u53d8\u91cf\uff0c\u5b83\u5c06\u4fdd\u5b58\u7ea6\u675f\u6761\u4ef6\u3002\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// \u8fd9\u662f\u4e3b\u7c7b\u4e2d\u7684\u65b0\u53d8\u91cf\u3002\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u5bf9\u8c61\uff0c\u5b83\u6301\u6709\u4e00\u4e2a\u7ea6\u675f\u6761\u4ef6\u7684\u5217\u8868\uff0c\u4ee5\u4fdd\u6301\u60ac\u6302\u8282\u70b9\u548c\u8fb9\u754c\u6761\u4ef6\u3002\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//\u975e\u6052\u5b9a\u7cfb\u6570\u7684\u5b9e\u73b0\u662f\u9010\u5b57\u590d\u5236\u81ea  step-5  \u3002\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// \u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4e0e\u4e4b\u524d\u7684\u57fa\u672c\u76f8\u540c\uff0c\u4f46\u8fd9\u4e00\u6b21\u6211\u4eec\u8981\u4f7f\u7528\u4e8c\u6b21\u5143\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u53ea\u9700\u7528\u6240\u9700\u7684\u591a\u9879\u5f0f\u5ea6\u6570\uff08\u8fd9\u91cc\u662f <code>2</code> \uff09\u66ff\u6362\u6784\u9020\u51fd\u6570\u53c2\u6570\uff08\u5728\u4e4b\u524d\u7684\u6240\u6709\u4f8b\u5b50\u4e2d\u662f <code>1</code> \uff09\u3002\n\ntemplate <int dim> \nStep6<dim>::Step6() \n  : fe(2) \n  , dof_handler(triangulation) \n{} \n\n//  @sect4{Step6::setup_system}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u8bbe\u7f6e\u4e86\u6240\u6709\u63cf\u8ff0\u7ebf\u6027\u6709\u9650\u5143\u95ee\u9898\u7684\u53d8\u91cf\uff0c\u5982DoFHandler\u3001\u77e9\u9635\u548c\u5411\u91cf\u3002\u4e0e\u6211\u4eec\u5728 step-5 \u4e2d\u6240\u505a\u7684\u4e0d\u540c\u7684\u662f\uff0c\u6211\u4eec\u73b0\u5728\u8fd8\u5fc5\u987b\u5904\u7406\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u3002\u8fd9\u4e9b\u7ea6\u675f\u51e0\u4e4e\u5b8c\u5168\u7531\u5e93\u6765\u5904\u7406\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u4f60\u53ea\u9700\u8981\u77e5\u9053\u5b83\u4eec\u7684\u5b58\u5728\u4ee5\u53ca\u5982\u4f55\u83b7\u5f97\u5b83\u4eec\uff0c\u4f46\u4f60\u4e0d\u9700\u8981\u77e5\u9053\u5b83\u4eec\u662f\u5982\u4f55\u5f62\u6210\u7684\uff0c\u4e5f\u4e0d\u9700\u8981\u77e5\u9053\u5bf9\u5b83\u4eec\u5230\u5e95\u505a\u4e86\u4ec0\u4e48\u3002\n\n// \u5728\u51fd\u6570\u7684\u5f00\u5934\uff0c\u4f60\u4f1a\u53d1\u73b0\u6240\u6709\u4e0e step-5 \u4e2d\u76f8\u540c\u7684\u4e1c\u897f\uff1a\u8bbe\u7f6e\u81ea\u7531\u5ea6\uff08\u8fd9\u6b21\u6211\u4eec\u6709\u4e8c\u6b21\u5143\uff0c\u4f46\u4ece\u7528\u6237\u4ee3\u7801\u7684\u89d2\u5ea6\u770b\u4e0e\u7ebf\u6027--\u6216\u4efb\u4f55\u5176\u4ed6\u7a0b\u5ea6\u7684\u60c5\u51b5\u6ca1\u6709\u533a\u522b\uff09\uff0c\u751f\u6210\u7a00\u758f\u6a21\u5f0f\uff0c\u5e76\u521d\u59cb\u5316\u89e3\u548c\u53f3\u624b\u5411\u91cf\u3002\u8bf7\u6ce8\u610f\uff0c\u73b0\u5728\u6bcf\u884c\u7684\u7a00\u758f\u6a21\u5f0f\u5c06\u6709\u66f4\u591a\u7684\u6761\u76ee\uff0c\u56e0\u4e3a\u73b0\u5728\u6bcf\u4e2a\u5355\u5143\u67099\u4e2a\u81ea\u7531\u5ea6\uff08\u800c\u4e0d\u662f\u53ea\u67094\u4e2a\uff09\uff0c\u5b83\u4eec\u53ef\u4ee5\u76f8\u4e92\u8026\u5408\u3002\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// \u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u7528\u60ac\u6302\u8282\u70b9\u7684\u7ea6\u675f\u6765\u586b\u5145AffineConstraints\u5bf9\u8c61\u3002\u7531\u4e8e\u6211\u4eec\u5c06\u5728\u4e00\u4e2a\u5faa\u73af\u4e2d\u8c03\u7528\u8fd9\u4e2a\u51fd\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u9996\u5148\u6e05\u9664\u4e0a\u4e00\u4e2a\u7cfb\u7edf\u4e2d\u7684\u5f53\u524d\u7ea6\u675f\u96c6\uff0c\u7136\u540e\u8ba1\u7b97\u65b0\u7684\u7ea6\u675f\u3002\n\n  constraints.clear(); \n  DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n\n// \u73b0\u5728\u6211\u4eec\u51c6\u5907\u7528\u6307\u68070\uff08\u6574\u4e2a\u8fb9\u754c\uff09\u6765\u63d2\u503c\u8fb9\u754c\u503c\uff0c\u5e76\u5c06\u5f97\u5230\u7684\u7ea6\u675f\u5b58\u50a8\u5728\u6211\u4eec\u7684 <code>constraints</code> \u5bf9\u8c61\u4e2d\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u5e76\u4e0d\u50cf\u5728\u524d\u9762\u7684\u6b65\u9aa4\u4e2d\u90a3\u6837\uff0c\u5728\u88c5\u914d\u540e\u5e94\u7528\u8fb9\u754c\u6761\u4ef6\uff1a\u76f8\u53cd\uff0c\u6211\u4eec\u5c06\u6240\u6709\u7684\u7ea6\u675f\u6761\u4ef6\u653e\u5728AffineConstraints\u5bf9\u8c61\u4e2d\u7684\u6211\u4eec\u7684\u51fd\u6570\u7a7a\u95f4\u3002\u6211\u4eec\u53ef\u4ee5\u6309\u4efb\u4f55\u987a\u5e8f\u5411AffineConstraints\u5bf9\u8c61\u6dfb\u52a0\u7ea6\u675f\uff1a\u5982\u679c\u4e24\u4e2a\u7ea6\u675f\u53d1\u751f\u51b2\u7a81\uff0c\u90a3\u4e48\u7ea6\u675f\u77e9\u9635\u8981\u4e48\u4e2d\u6b62\uff0c\u8981\u4e48\u901a\u8fc7Assert\u5b8f\u629b\u51fa\u4e00\u4e2a\u5f02\u5e38\u3002\n\n  VectorTools::interpolate_boundary_values(dof_handler, \n                                           0, \n                                           Functions::ZeroFunction<dim>(), \n                                           constraints); \n\n// \u5728\u6240\u6709\u7ea6\u675f\u6761\u4ef6\u88ab\u6dfb\u52a0\u4e4b\u540e\uff0c\u9700\u8981\u5bf9\u5b83\u4eec\u8fdb\u884c\u6392\u5e8f\u548c\u91cd\u65b0\u6392\u5217\uff0c\u4ee5\u4fbf\u66f4\u6709\u6548\u5730\u6267\u884c\u4e00\u4e9b\u64cd\u4f5c\u3002\u8fd9\u79cd\u540e\u5904\u7406\u662f\u7528 <code>close()</code> \u51fd\u6570\u5b8c\u6210\u7684\uff0c\u4e4b\u540e\u5c31\u4e0d\u80fd\u518d\u6dfb\u52a0\u4efb\u4f55\u7ea6\u675f\u4e86\u3002\n\n  constraints.close(); \n\n// \u73b0\u5728\u6211\u4eec\u9996\u5148\u5efa\u7acb\u6211\u4eec\u7684\u538b\u7f29\u7a00\u758f\u6a21\u5f0f\uff0c\u5c31\u50cf\u6211\u4eec\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u505a\u7684\u90a3\u6837\u3002\u7136\u800c\uff0c\u6211\u4eec\u5e76\u6ca1\u6709\u7acb\u5373\u5c06\u5176\u590d\u5236\u5230\u6700\u7ec8\u7684\u7a00\u758f\u5ea6\u6a21\u5f0f\u4e2d\u3002 \u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u8c03\u7528\u4e86make_sparsity_pattern\u7684\u4e00\u4e2a\u53d8\u4f53\uff0c\u5b83\u628aAffineConstraints\u5bf9\u8c61\u4f5c\u4e3a\u7b2c\u4e09\u4e2a\u53c2\u6570\u3002\u6211\u4eec\u901a\u8fc7\u5c06\u53c2\u6570 <code>keep_constrained_dofs</code> \u8bbe\u7f6e\u4e3afalse\uff08\u6362\u53e5\u8bdd\u8bf4\uff0c\u6211\u4eec\u6c38\u8fdc\u4e0d\u4f1a\u5199\u5165\u77e9\u9635\u4e2d\u5bf9\u5e94\u4e8e\u53d7\u9650\u81ea\u7531\u5ea6\u7684\u6761\u76ee\uff09\uff0c\u8ba9\u8be5\u4f8b\u7a0b\u77e5\u9053\u6211\u4eec\u6c38\u8fdc\u4e0d\u4f1a\u5199\u5165 <code>constraints</code> \u6240\u7ed9\u7684\u4f4d\u7f6e\u3002\u5982\u679c\u6211\u4eec\u5728\u88c5\u914d\u540e\u5bf9\u7ea6\u675f\u8fdb\u884c\u538b\u7f29\uff0c\u6211\u4eec\u5c31\u5fc5\u987b\u901a\u8fc7 <code>true</code> \u6765\u4ee3\u66ff\uff0c\u56e0\u4e3a\u8fd9\u6837\u6211\u4eec\u5c31\u4f1a\u5148\u5199\u8fdb\u8fd9\u4e9b\u4f4d\u7f6e\uff0c\u7136\u540e\u5728\u538b\u7f29\u8fc7\u7a0b\u4e2d\u518d\u5c06\u5b83\u4eec\u8bbe\u7f6e\u4e3a\u96f6\u3002\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// \u73b0\u5728\uff0c\u77e9\u9635\u7684\u6240\u6709\u975e\u96f6\u6761\u76ee\u90fd\u662f\u5df2\u77e5\u7684\uff08\u5373\u90a3\u4e9b\u6765\u81ea\u5b9a\u671f\u7ec4\u88c5\u77e9\u9635\u7684\u6761\u76ee\u548c\u90a3\u4e9b\u901a\u8fc7\u6d88\u9664\u7ea6\u675f\u5f15\u5165\u7684\u6761\u76ee\uff09\u3002\u6211\u4eec\u53ef\u4ee5\u5c06\u6211\u4eec\u7684\u4e2d\u95f4\u5bf9\u8c61\u590d\u5236\u5230\u7a00\u758f\u6a21\u5f0f\u4e2d\u3002\n\n  sparsity_pattern.copy_from(dsp); \n\n// \u6211\u4eec\u73b0\u5728\u53ef\u4ee5\uff0c\u6700\u540e\uff0c\u521d\u59cb\u5316\u7a00\u758f\u77e9\u9635\u3002\n\n  system_matrix.reinit(sparsity_pattern); \n} \n// @sect4{Step6::assemble_system}  \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u8981\u5bf9\u77e9\u9635\u8fdb\u884c\u7ec4\u88c5\u3002\u7136\u800c\uff0c\u4e3a\u4e86\u5c06\u6bcf\u4e2a\u5355\u5143\u4e0a\u7684\u672c\u5730\u77e9\u9635\u548c\u5411\u91cf\u590d\u5236\u5230\u5168\u5c40\u7cfb\u7edf\u4e2d\uff0c\u6211\u4eec\u4e0d\u518d\u4f7f\u7528\u624b\u5199\u7684\u5faa\u73af\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u4f7f\u7528 AffineConstraints::distribute_local_to_global() \uff0c\u5728\u5185\u90e8\u6267\u884c\u8fd9\u4e2a\u5faa\u73af\uff0c\u540c\u65f6\u5bf9\u5bf9\u5e94\u4e8e\u53d7\u9650\u81ea\u7531\u5ea6\u7684\u884c\u548c\u5217\u8fdb\u884c\u9ad8\u65af\u6d88\u9664\u3002\n\n// \u6784\u6210\u5c40\u90e8\u8d21\u732e\u7684\u5176\u4f59\u4ee3\u7801\u4fdd\u6301\u4e0d\u53d8\u3002\u7136\u800c\uff0c\u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c\u5728\u5f15\u64ce\u76d6\u4e0b\uff0c\u6709\u51e0\u4ef6\u4e8b\u4e0e\u4ee5\u524d\u4e0d\u540c\u3002\u9996\u5148\uff0c\u53d8\u91cf <code>dofs_per_cell</code> \u548c\u8fd4\u56de\u503c <code>quadrature_formula.size()</code> \u73b0\u5728\u5404\u4e3a9\uff0c\u4ee5\u524d\u662f4\u3002\u5f15\u5165\u8fd9\u6837\u7684\u53d8\u91cf\u4f5c\u4e3a\u7f29\u5199\u662f\u4e00\u4e2a\u5f88\u597d\u7684\u7b56\u7565\uff0c\u53ef\u4ee5\u4f7f\u4ee3\u7801\u5728\u4e0d\u540c\u7684\u5143\u7d20\u4e0b\u5de5\u4f5c\uff0c\u800c\u4e0d\u9700\u8981\u6539\u53d8\u592a\u591a\u7684\u4ee3\u7801\u3002\u5176\u6b21\uff0c <code>fe_values</code> \u5bf9\u8c61\u5f53\u7136\u4e5f\u9700\u8981\u505a\u5176\u4ed6\u4e8b\u60c5\uff0c\u56e0\u4e3a\u73b0\u5728\u7684\u5f62\u72b6\u51fd\u6570\u662f\u4e8c\u6b21\u7684\uff0c\u800c\u4e0d\u662f\u7ebf\u6027\u7684\uff0c\u5728\u6bcf\u4e2a\u5750\u6807\u53d8\u91cf\u4e2d\u3002\u4e0d\u8fc7\uff0c\u8fd9\u4e5f\u662f\u5b8c\u5168\u7531\u5e93\u6765\u5904\u7406\u7684\u4e8b\u60c5\u3002\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// \u6700\u540e\uff0c\u5c06 @p cell_matrix \u548c @p cell_rhs \u4e2d\u7684\u8d21\u732e\u8f6c\u79fb\u5230\u5168\u5c40\u5bf9\u8c61\u4e2d\u3002\n\n      cell->get_dof_indices(local_dof_indices); \n      constraints.distribute_local_to_global( \n        cell_matrix, cell_rhs, local_dof_indices, system_matrix, system_rhs); \n    } \n\n// \u73b0\u5728\u6211\u4eec\u5df2\u7ecf\u5b8c\u6210\u4e86\u7ebf\u6027\u7cfb\u7edf\u7684\u7ec4\u88c5\u3002\u7ea6\u675f\u77e9\u9635\u5904\u7406\u4e86\u5e94\u7528\u8fb9\u754c\u6761\u4ef6\u7684\u95ee\u9898\uff0c\u4e5f\u6d88\u9664\u4e86\u60ac\u6302\u7684\u8282\u70b9\u7ea6\u675f\u3002\u53d7\u7ea6\u675f\u7684\u8282\u70b9\u4ecd\u7136\u5728\u7ebf\u6027\u7cfb\u7edf\u4e2d\uff08\u5728\u77e9\u9635\u7684\u5bf9\u89d2\u7ebf\u4e0a\u6709\u4e00\u4e2a\u975e\u96f6\u6761\u76ee\uff0c\u9009\u62e9\u7684\u65b9\u5f0f\u662f\u4f7f\u77e9\u9635\u5177\u6709\u826f\u597d\u7684\u6761\u4ef6\uff0c\u5e76\u4e14\u8fd9\u4e00\u884c\u7684\u6240\u6709\u5176\u4ed6\u6761\u76ee\u90fd\u88ab\u8bbe\u7f6e\u4e3a\u96f6\uff09\uff0c\u4f46\u662f\u8ba1\u7b97\u51fa\u6765\u7684\u503c\u662f\u65e0\u6548\u7684\uff08\u4e5f\u5c31\u662f\u8bf4\uff0c <code>system_rhs</code> \u4e2d\u7684\u76f8\u5e94\u6761\u76ee\u76ee\u524d\u662f\u6ca1\u6709\u610f\u4e49\u7684\uff09\u3002\u6211\u4eec\u5728 <code>solve</code> \u51fd\u6570\u7684\u6700\u540e\u4e3a\u8fd9\u4e9b\u8282\u70b9\u8ba1\u7b97\u51fa\u6b63\u786e\u7684\u503c\u3002\n\n} \n// @sect4{Step6::solve}  \n\n// \u6211\u4eec\u7ee7\u7eed\u9010\u6b65\u6539\u8fdb\u3002\u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\u518d\u6b21\u4f7f\u7528\u4e86SSOR\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u9664\u4e86\u6211\u4eec\u5fc5\u987b\u52a0\u5165\u60ac\u7a7a\u8282\u70b9\u7ea6\u675f\u5916\uff0c\u5176\u4ed6\u7684\u90fd\u6ca1\u6709\u6539\u53d8\u3002\u5982\u4e0a\u6240\u8ff0\uff0c\u901a\u8fc7\u5bf9\u77e9\u9635\u7684\u884c\u548c\u5217\u8fdb\u884c\u7279\u6b8a\u5904\u7406\uff0c\u4eceAffineConstraints\u5bf9\u8c61\u4e2d\u5220\u9664\u4e86\u5bf9\u5e94\u4e8e\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u548c\u8fb9\u754c\u503c\u7684\u81ea\u7531\u5ea6\u3002\u8fd9\u6837\u4e00\u6765\uff0c\u8fd9\u4e9b\u81ea\u7531\u5ea6\u7684\u503c\u5728\u6c42\u89e3\u7ebf\u6027\u7cfb\u7edf\u540e\u5c31\u6709\u4e86\u9519\u8bef\u7684\u3001\u4f46\u5b9a\u4e49\u660e\u786e\u7684\u503c\u3002\u7136\u540e\u6211\u4eec\u8981\u505a\u7684\u5c31\u662f\u5229\u7528\u7ea6\u675f\u6761\u4ef6\u7ed9\u5b83\u4eec\u5206\u914d\u5b83\u4eec\u5e94\u8be5\u6709\u7684\u503c\u3002\u8fd9\u4e2a\u8fc7\u7a0b\u88ab\u79f0\u4e3a <code>distributing</code> \u7ea6\u675f\uff0c\u4ece\u65e0\u7ea6\u675f\u7684\u8282\u70b9\u7684\u503c\u4e2d\u8ba1\u7b97\u51fa\u7ea6\u675f\u8282\u70b9\u7684\u503c\uff0c\u53ea\u9700\u8981\u4e00\u4e2a\u989d\u5916\u7684\u51fd\u6570\u8c03\u7528\uff0c\u4f60\u53ef\u4ee5\u5728\u8fd9\u4e2a\u51fd\u6570\u7684\u672b\u5c3e\u627e\u5230\u3002\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// \u6211\u4eec\u4f7f\u7528\u4e00\u4e2a\u590d\u6742\u7684\u8bef\u5dee\u4f30\u8ba1\u65b9\u6848\u6765\u7ec6\u5316\u7f51\u683c\uff0c\u800c\u4e0d\u662f\u5168\u5c40\u7ec6\u5316\u3002\u6211\u4eec\u5c06\u4f7f\u7528KellyErrorEstimator\u7c7b\uff0c\u8be5\u7c7b\u5b9e\u73b0\u4e86\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u7684\u8bef\u5dee\u4f30\u8ba1\u5668\uff1b\u539f\u5219\u4e0a\u5b83\u53ef\u4ee5\u5904\u7406\u53ef\u53d8\u7cfb\u6570\uff0c\u4f46\u6211\u4eec\u4e0d\u4f1a\u4f7f\u7528\u8fd9\u4e9b\u9ad8\u7ea7\u529f\u80fd\uff0c\u800c\u662f\u4f7f\u7528\u5176\u6700\u7b80\u5355\u7684\u5f62\u5f0f\uff0c\u56e0\u4e3a\u6211\u4eec\u5bf9\u5b9a\u91cf\u7ed3\u679c\u4e0d\u611f\u5174\u8da3\uff0c\u53ea\u5bf9\u751f\u6210\u5c40\u90e8\u7ec6\u5316\u7f51\u683c\u7684\u5feb\u901f\u65b9\u6cd5\u611f\u5174\u8da3\u3002\n\n// \u5c3d\u7ba1Kelly\u7b49\u4eba\u5f97\u51fa\u7684\u8bef\u5dee\u4f30\u8ba1\u5668\u6700\u521d\u662f\u4e3a\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u5f00\u53d1\u7684\uff0c\u4f46\u6211\u4eec\u53d1\u73b0\u5b83\u4e5f\u5f88\u9002\u5408\u4e8e\u4e3a\u4e00\u7c7b\u5e7f\u6cdb\u7684\u95ee\u9898\u5feb\u901f\u751f\u6210\u5c40\u90e8\u7ec6\u5316\u7f51\u683c\u3002\u8fd9\u4e2a\u8bef\u5dee\u4f30\u8ba1\u5668\u4f7f\u7528\u4e86\u89e3\u68af\u5ea6\u5728\u5355\u5143\u9762\u4e0a\u7684\u8df3\u8dc3\uff08\u8fd9\u662f\u4e00\u4e2a\u6d4b\u91cf\u4e8c\u9636\u5bfc\u6570\u7684\u65b9\u6cd5\uff09\uff0c\u5e76\u5c06\u5176\u6309\u5355\u5143\u7684\u5927\u5c0f\u8fdb\u884c\u7f29\u653e\u3002\u56e0\u6b64\uff0c\u5b83\u662f\u5bf9\u6bcf\u4e2a\u5355\u5143\u7684\u89e3\u7684\u5c40\u90e8\u5e73\u6ed1\u6027\u7684\u6d4b\u91cf\uff0c\u56e0\u6b64\u53ef\u4ee5\u7406\u89e3\uff0c\u5b83\u5bf9\u53cc\u66f2\u8fd0\u8f93\u95ee\u9898\u6216\u6ce2\u6d6a\u65b9\u7a0b\u4e5f\u80fd\u4ea7\u751f\u5408\u7406\u7684\u7f51\u683c\uff0c\u5c3d\u7ba1\u8fd9\u4e9b\u7f51\u683c\u4e0e\u4e13\u95e8\u9488\u5bf9\u8be5\u95ee\u9898\u7684\u65b9\u6cd5\u76f8\u6bd4\u80af\u5b9a\u662f\u6b21\u4f18\u7684\u3002\u56e0\u6b64\uff0c\u8fd9\u4e2a\u8bef\u5dee\u4f30\u8ba1\u5668\u53ef\u4ee5\u7406\u89e3\u4e3a\u6d4b\u8bd5\u81ea\u9002\u5e94\u7a0b\u5e8f\u7684\u4e00\u79cd\u5feb\u901f\u65b9\u6cd5\u3002\n\n// \u4f30\u7b97\u5668\u7684\u5de5\u4f5c\u65b9\u5f0f\u662f\u5c06\u63cf\u8ff0\u81ea\u7531\u5ea6\u7684 <code>DoFHandler</code> \u5bf9\u8c61\u548c\u6bcf\u4e2a\u81ea\u7531\u5ea6\u7684\u6570\u503c\u5411\u91cf\u4f5c\u4e3a\u8f93\u5165\uff0c\u4e3a\u4e09\u89d2\u5256\u5206\u7684\u6bcf\u4e2a\u6d3b\u52a8\u5355\u5143\u8ba1\u7b97\u4e00\u4e2a\u6307\u6807\u503c\uff08\u5373\u6bcf\u4e2a\u6d3b\u52a8\u5355\u5143\u4e00\u4e2a\u6570\u503c\uff09\u3002\u4e3a\u6b64\uff0c\u5b83\u9700\u8981\u4e24\u4e2a\u989d\u5916\u7684\u4fe1\u606f\uff1a\u4e00\u4e2a\u9762\u90e8\u6b63\u4ea4\u516c\u5f0f\uff0c\u5373 <code>dim-1</code> \u7ef4\u7269\u4f53\u4e0a\u7684\u6b63\u4ea4\u516c\u5f0f\u3002\u6211\u4eec\u518d\u6b21\u4f7f\u75283\u70b9\u9ad8\u65af\u6cd5\u5219\uff0c\u8fd9\u4e2a\u9009\u62e9\u4e0e\u672c\u7a0b\u5e8f\u4e2d\u7684\u53cc\u4e8c\u6b21\u65b9\u6709\u9650\u5143\u5f62\u72b6\u51fd\u6570\u662f\u4e00\u81f4\u548c\u5408\u9002\u7684\u3002\u5f53\u7136\uff0c\u4ec0\u4e48\u662f\u5408\u9002\u7684\u6b63\u4ea4\u89c4\u5219\u53d6\u51b3\u4e8e\u5bf9\u8bef\u5dee\u4f30\u8ba1\u5668\u8bc4\u4f30\u89e3\u573a\u7684\u65b9\u5f0f\u7684\u4e86\u89e3\u3002\u5982\u4e0a\u6240\u8ff0\uff0c\u68af\u5ea6\u7684\u8df3\u8dc3\u5728\u6bcf\u4e2a\u9762\u4e0a\u90fd\u662f\u96c6\u6210\u7684\uff0c\u5bf9\u4e8e\u672c\u4f8b\u4e2d\u4f7f\u7528\u7684\u4e8c\u6b21\u5143\u5143\u7d20\u6765\u8bf4\uff0c\u8fd9\u5c06\u662f\u6bcf\u4e2a\u9762\u4e0a\u7684\u4e8c\u6b21\u5143\u51fd\u6570\u3002\u7136\u800c\uff0c\u4e8b\u5b9e\u4e0a\uff0c\u5b83\u662f\u68af\u5ea6\u8df3\u52a8\u7684\u5e73\u65b9\uff0c\u6b63\u5982\u8be5\u7c7b\u6587\u4ef6\u4e2d\u6240\u89e3\u91ca\u7684\u90a3\u6837\uff0c\u8fd9\u662f\u4e00\u4e2a\u4e8c\u6b21\u51fd\u6570\uff0c\u5bf9\u4e8e\u5b83\u6765\u8bf4\uff0c3\u70b9\u9ad8\u65af\u516c\u5f0f\u5c31\u8db3\u591f\u4e86\uff0c\u56e0\u4e3a\u5b83\u53ef\u4ee5\u7cbe\u786e\u5730\u6574\u54085\u9636\u4ee5\u4e0b\u7684\u591a\u9879\u5f0f\u3002)\n\n// \u5176\u6b21\uff0c\u8be5\u51fd\u6570\u9700\u8981\u4e00\u4e2a\u8fb9\u754c\u6307\u793a\u5668\u7684\u5217\u8868\uff0c\u7528\u4e8e\u90a3\u4e9b\u6211\u4eec\u65bd\u52a0\u4e86 $\\partial_n u(\\mathbf x) = h(\\mathbf x)$ \u7c7b\u8bfa\u4f0a\u66fc\u503c\u7684\u8fb9\u754c\uff0c\u4ee5\u53ca\u6bcf\u4e2a\u6b64\u7c7b\u8fb9\u754c\u7684\u51fd\u6570 $h(\\mathbf x)$ \u3002\u8fd9\u4e9b\u4fe1\u606f\u7531\u4e00\u4e2a\u4ece\u8fb9\u754c\u6307\u6807\u5230\u63cf\u8ff0\u8bfa\u4f0a\u66fc\u8fb9\u754c\u503c\u7684\u51fd\u6570\u5bf9\u8c61\u7684\u6620\u5c04\u6765\u8868\u793a\u3002\u5728\u672c\u4f8b\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u4e0d\u4f7f\u7528\u8bfa\u4f0a\u66fc\u8fb9\u754c\u503c\uff0c\u6240\u4ee5\u8fd9\u4e2a\u6620\u5c04\u662f\u7a7a\u7684\uff0c\u5b9e\u9645\u4e0a\u662f\u5728\u51fd\u6570\u8c03\u7528\u671f\u671b\u5f97\u5230\u76f8\u5e94\u51fd\u6570\u53c2\u6570\u7684\u5730\u65b9\u4f7f\u7528\u6620\u5c04\u7684\u9ed8\u8ba4\u6784\u9020\u5668\u6784\u9020\u7684\u3002\n\n// \u8f93\u51fa\u662f\u4e00\u4e2a\u6240\u6709\u6d3b\u52a8\u5355\u5143\u7684\u503c\u7684\u5411\u91cf\u3002\u867d\u7136\u975e\u5e38\u7cbe\u786e\u5730\u8ba1\u7b97\u4e00\u4e2a\u89e3\u7684\u81ea\u7531\u5ea6\u7684<b>value</b>\u53ef\u80fd\u662f\u6709\u610f\u4e49\u7684\uff0c\u4f46\u901a\u5e38\u6ca1\u6709\u5fc5\u8981\u7279\u522b\u7cbe\u786e\u5730\u8ba1\u7b97\u4e00\u4e2a\u5355\u5143\u4e0a\u7684\u89e3\u5bf9\u5e94\u7684<b>error indicator</b>\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u901a\u5e38\u4f7f\u7528\u4e00\u4e2a\u6d6e\u70b9\u6570\u7684\u5411\u91cf\u800c\u4e0d\u662f\u4e00\u4e2a\u53cc\u6570\u7684\u5411\u91cf\u6765\u8868\u793a\u8bef\u5dee\u6307\u6807\u3002\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// \u4e0a\u8ff0\u51fd\u6570\u4e3a <code>estimated_error_per_cell</code> \u6570\u7ec4\u4e2d\u7684\u6bcf\u4e2a\u5355\u5143\u683c\u8fd4\u56de\u4e00\u4e2a\u9519\u8bef\u6307\u6807\u503c\u3002\u73b0\u5728\u7684\u7ec6\u5316\u5de5\u4f5c\u5982\u4e0b\uff1a\u7ec6\u5316\u90a3\u4e9b\u8bef\u5dee\u503c\u6700\u9ad8\u768430%\u7684\u5355\u5143\uff0c\u7c97\u5316\u90a3\u4e9b\u8bef\u5dee\u503c\u6700\u4f4e\u76843%\u7684\u5355\u5143\u3002\n\n// \u4eba\u4eec\u53ef\u4ee5\u5f88\u5bb9\u6613\u5730\u9a8c\u8bc1\uff0c\u5982\u679c\u7b2c\u4e8c\u4e2a\u6570\u5b57\u4e3a\u96f6\uff0c\u8fd9\u5927\u7ea6\u4f1a\u5bfc\u81f4\u5728\u4e24\u4e2a\u7a7a\u95f4\u7ef4\u5ea6\u4e0a\u7684\u6bcf\u4e00\u6b65\u7684\u7ec6\u80de\u7ffb\u500d\uff0c\u56e0\u4e3a\u5bf9\u4e8e\u6bcf\u4e00\u4e2a30%\u7684\u7ec6\u80de\uff0c\u56db\u4e2a\u65b0\u7684\u5c06\u88ab\u66ff\u6362\uff0c\u800c\u5176\u4f5970%\u7684\u7ec6\u80de\u4fdd\u6301\u4e0d\u52a8\u3002\u5728\u5b9e\u8df5\u4e2d\uff0c\u901a\u5e38\u4f1a\u4ea7\u751f\u4e00\u4e9b\u66f4\u591a\u7684\u5355\u5143\uff0c\u56e0\u4e3a\u4e0d\u5141\u8bb8\u4e00\u4e2a\u5355\u5143\u88ab\u7cbe\u70bc\u4e24\u6b21\u800c\u76f8\u90bb\u7684\u5355\u5143\u6ca1\u6709\u88ab\u7cbe\u70bc\uff1b\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u76f8\u90bb\u7684\u5355\u5143\u4e5f\u4f1a\u88ab\u7cbe\u70bc\u3002\n\n// \u5728\u8bb8\u591a\u5e94\u7528\u4e2d\uff0c\u88ab\u7c97\u5316\u7684\u5355\u5143\u683c\u6570\u91cf\u5c06\u88ab\u8bbe\u7f6e\u4e3a\u5927\u4e8e3%\u7684\u6570\u503c\u3002\u4e00\u4e2a\u975e\u96f6\u7684\u503c\u662f\u5f88\u6709\u7528\u7684\uff0c\u7279\u522b\u662f\u5f53\u521d\u59cb\uff08\u7c97\uff09\u7f51\u683c\u7531\u4e8e\u67d0\u79cd\u539f\u56e0\u5df2\u7ecf\u76f8\u5f53\u7cbe\u7ec6\u65f6\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u53ef\u80fd\u6709\u5fc5\u8981\u5728\u67d0\u4e9b\u533a\u57df\u8fdb\u884c\u7ec6\u5316\uff0c\u800c\u5728\u53e6\u4e00\u4e9b\u533a\u57df\u8fdb\u884c\u7c97\u5316\u662f\u6709\u7528\u7684\u3002\u5728\u6211\u4eec\u8fd9\u91cc\uff0c\u521d\u59cb\u7f51\u683c\u662f\u975e\u5e38\u7c97\u7684\uff0c\u6240\u4ee5\u7c97\u5316\u53ea\u9700\u8981\u5728\u4e00\u4e9b\u53ef\u80fd\u53d1\u751f\u8fc7\u5ea6\u7ec6\u5316\u7684\u533a\u57df\u3002\u56e0\u6b64\uff0c\u4e00\u4e2a\u5c0f\u7684\u3001\u975e\u96f6\u7684\u503c\u5728\u8fd9\u91cc\u662f\u5408\u9002\u7684\u3002\n\n// \u4e0b\u9762\u7684\u51fd\u6570\u73b0\u5728\u63a5\u53d7\u8fd9\u4e9b\u7ec6\u5316\u6307\u6807\uff0c\u5e76\u4f7f\u7528\u4e0a\u8ff0\u65b9\u6cd5\u5bf9\u4e09\u89d2\u5f62\u7684\u4e00\u4e9b\u5355\u5143\u8fdb\u884c\u7ec6\u5316\u6216\u7c97\u5316\u6807\u8bb0\u3002\u5b83\u6765\u81ea\u4e00\u4e2a\u5b9e\u73b0\u4e86\u51e0\u79cd\u4e0d\u540c\u7b97\u6cd5\u7684\u7c7b\uff0c\u53ef\u4ee5\u6839\u636e\u5355\u5143\u7684\u8bef\u5dee\u6307\u6807\u6765\u7ec6\u5316\u4e09\u89d2\u5f62\u3002\n\n  GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                  estimated_error_per_cell, \n                                                  0.3, \n                                                  0.03); \n\n// \u5728\u524d\u4e00\u4e2a\u51fd\u6570\u9000\u51fa\u540e\uff0c\u4e00\u4e9b\u5355\u5143\u88ab\u6807\u8bb0\u4e3a\u7ec6\u5316\uff0c\u53e6\u4e00\u4e9b\u5355\u5143\u88ab\u6807\u8bb0\u4e3a\u7c97\u5316\u3002\u7136\u800c\uff0c\u7ec6\u5316\u6216\u7c97\u5316\u672c\u8eab\u5e76\u6ca1\u6709\u88ab\u6267\u884c\uff0c\u56e0\u4e3a\u6709\u4e9b\u60c5\u51b5\u4e0b\uff0c\u8fdb\u4e00\u6b65\u4fee\u6539\u8fd9\u4e9b\u6807\u5fd7\u662f\u6709\u7528\u7684\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u4e0d\u60f3\u505a\u4efb\u4f55\u8fd9\u6837\u7684\u4e8b\u60c5\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u544a\u8bc9\u4e09\u89d2\u8ba1\u7b97\u6267\u884c\u5355\u5143\u683c\u88ab\u6807\u8bb0\u7684\u52a8\u4f5c\u3002\n\n  triangulation.execute_coarsening_and_refinement(); \n} \n// @sect4{Step6::output_results}  \n\n// \u5728\u6bcf\u4e2a\u7f51\u683c\u7684\u8ba1\u7b97\u7ed3\u675f\u540e\uff0c\u5728\u6211\u4eec\u7ee7\u7eed\u4e0b\u4e00\u4e2a\u7f51\u683c\u7ec6\u5316\u5468\u671f\u4e4b\u524d\uff0c\u6211\u4eec\u8981\u8f93\u51fa\u8fd9\u4e2a\u5468\u671f\u7684\u7ed3\u679c\u3002\n\n// \u6211\u4eec\u5df2\u7ecf\u5728 step-1 \u4e2d\u770b\u5230\u4e86\u5982\u4f55\u5b9e\u73b0\u5bf9\u7f51\u683c\u672c\u8eab\u7684\u8f93\u51fa\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u6539\u53d8\u4e00\u4e9b\u4e1c\u897f\u3002  <ol>  \n// <li>  \u6211\u4eec\u4f7f\u7528\u4e24\u79cd\u4e0d\u540c\u7684\u683c\u5f0f\u3002gnuplot\u548cVTU\u3002 </li>  \n// <li>  \u6211\u4eec\u5728\u8f93\u51fa\u6587\u4ef6\u540d\u4e2d\u5d4c\u5165\u4e86\u5468\u671f\u53f7\u3002 </li>  \n// <li>  \u5bf9\u4e8egnuplot\u8f93\u51fa\uff0c\u6211\u4eec\u8bbe\u7f6e\u4e86\u4e00\u4e2a GridOutFlags::Gnuplot \u5bf9\u8c61\uff0c\u4ee5\u63d0\u4f9b\u4e00\u4e9b\u989d\u5916\u7684\u53ef\u89c6\u5316\u53c2\u6570\uff0c\u4f7f\u8fb9\u7f18\u770b\u8d77\u6765\u662f\u5f2f\u66f2\u7684\u3002\u8fd9\u5728  step-10  \u4e2d\u6709\u8fdb\u4e00\u6b65\u7684\u8be6\u7ec6\u89e3\u91ca\u3002 </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> \u4e4b\u524d\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u53c8\u662f\u8be5\u7c7b\u7684\u4e3b\u8981\u9a71\u52a8\uff0c  <code>run()</code>  \u3002\u5b83\u4e0e  step-5  \u7684\u51fd\u6570\u7c7b\u4f3c\uff0c\u53ea\u662f\u6211\u4eec\u5728\u7a0b\u5e8f\u4e2d\u518d\u6b21\u751f\u6210\u4e00\u4e2a\u6587\u4ef6\uff0c\u800c\u4e0d\u662f\u4ece\u78c1\u76d8\u4e2d\u8bfb\u53d6\uff0c\u6211\u4eec\u81ea\u9002\u5e94\u5730\u800c\u4e0d\u662f\u5168\u5c40\u5730\u7ec6\u5316\u7f51\u683c\uff0c\u5e76\u4e14\u6211\u4eec\u5728\u672c\u51fd\u6570\u4e2d\u8f93\u51fa\u6700\u7ec8\u7f51\u683c\u4e0a\u7684\u89e3\u51b3\u65b9\u6848\u3002\n\n// \u8be5\u51fd\u6570\u4e3b\u5faa\u73af\u7684\u7b2c\u4e00\u4e2a\u5757\u662f\u5904\u7406\u7f51\u683c\u751f\u6210\u3002\u5982\u679c\u8fd9\u662f\u8be5\u7a0b\u5e8f\u7684\u7b2c\u4e00\u4e2a\u5faa\u73af\uff0c\u6211\u4eec\u73b0\u5728\u4e0d\u662f\u50cf\u4e0a\u4e00\u4e2a\u4f8b\u5b50\u90a3\u6837\u4ece\u78c1\u76d8\u4e0a\u7684\u6587\u4ef6\u4e2d\u8bfb\u53d6\u7f51\u683c\uff0c\u800c\u662f\u518d\u6b21\u4f7f\u7528\u5e93\u51fd\u6570\u6765\u521b\u5efa\u5b83\u3002\u57df\u8fd8\u662f\u4e00\u4e2a\u5706\uff0c\u4e2d\u5fc3\u5728\u539f\u70b9\uff0c\u534a\u5f84\u4e3a1\uff08\u8fd9\u662f\u51fd\u6570\u7684\u4e24\u4e2a\u9690\u85cf\u53c2\u6570\uff0c\u6709\u9ed8\u8ba4\u503c\uff09\u3002\n\n// \u4f60\u4f1a\u6ce8\u610f\u5230\u7c97\u7565\u7684\u7f51\u683c\u6bd4\u6211\u4eec\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u4ece\u6587\u4ef6\u4e2d\u8bfb\u51fa\u7684\u7f51\u683c\u8d28\u91cf\u8981\u5dee\uff1a\u5355\u5143\u683c\u7684\u5f62\u6210\u4e0d\u592a\u5e73\u5747\u3002\u7136\u800c\uff0c\u4f7f\u7528\u5e93\u51fd\u6570\uff0c\u8fd9\u4e2a\u7a0b\u5e8f\u5728\u4efb\u4f55\u7a7a\u95f4\u7ef4\u5ea6\u4e0a\u90fd\u53ef\u4ee5\u5de5\u4f5c\uff0c\u800c\u4ee5\u524d\u4e0d\u662f\u8fd9\u6837\u7684\u3002\n\n// \u5982\u679c\u6211\u4eec\u53d1\u73b0\u8fd9\u4e0d\u662f\u7b2c\u4e00\u4e2a\u5468\u671f\uff0c\u6211\u4eec\u8981\u7ec6\u5316\u7f51\u683c\u3002\u4e0e\u4e0a\u4e00\u4e2a\u4f8b\u5b50\u7a0b\u5e8f\u4e2d\u91c7\u7528\u7684\u5168\u5c40\u7ec6\u5316\u4e0d\u540c\uff0c\u6211\u4eec\u73b0\u5728\u4f7f\u7528\u4e0a\u8ff0\u7684\u81ea\u9002\u5e94\u7a0b\u5e8f\u3002\n\n// \u5faa\u73af\u7684\u5176\u4f59\u90e8\u5206\u770b\u8d77\u6765\u548c\u4ee5\u524d\u4e00\u6837\u3002\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// \u4e3b\u51fd\u6570\u7684\u529f\u80fd\u4e0e\u4e4b\u524d\u7684\u4f8b\u5b50\u76f8\u6bd4\u6ca1\u6709\u6539\u53d8\uff0c\u4f46\u6211\u4eec\u91c7\u53d6\u4e86\u989d\u5916\u7684\u8c28\u614e\u63aa\u65bd\u3002\u6709\u65f6\uff0c\u4f1a\u51fa\u73b0\u4e00\u4e9b\u95ee\u9898\uff08\u6bd4\u5982\u5199\u8f93\u51fa\u6587\u4ef6\u65f6\u78c1\u76d8\u7a7a\u95f4\u4e0d\u8db3\uff0c\u8bd5\u56fe\u5206\u914d\u5411\u91cf\u6216\u77e9\u9635\u65f6\u5185\u5b58\u4e0d\u8db3\uff0c\u6216\u8005\u7531\u4e8e\u67d0\u79cd\u539f\u56e0\u6211\u4eec\u65e0\u6cd5\u4ece\u6587\u4ef6\u4e2d\u8bfb\u53d6\u6216\u5199\u5165\u6587\u4ef6\uff09\uff0c\u5728\u8fd9\u4e9b\u60c5\u51b5\u4e0b\uff0c\u5e93\u4f1a\u629b\u51fa\u5f02\u5e38\u3002\u7531\u4e8e\u8fd9\u4e9b\u662f\u8fd0\u884c\u65f6\u7684\u95ee\u9898\uff0c\u800c\u4e0d\u662f\u53ef\u4ee5\u4e00\u52b3\u6c38\u9038\u7684\u7f16\u7a0b\u9519\u8bef\uff0c\u8fd9\u79cd\u5f02\u5e38\u5728\u4f18\u5316\u6a21\u5f0f\u4e0b\u4e0d\u4f1a\u88ab\u5173\u95ed\uff0c\u4e0e\u6211\u4eec\u7528\u6765\u6d4b\u8bd5\u7f16\u7a0b\u9519\u8bef\u7684 <code>Assert</code> \u5b8f\u76f8\u53cd\u3002\u5982\u679c\u6ca1\u6709\u88ab\u6355\u83b7\uff0c\u8fd9\u4e9b\u5f02\u5e38\u4f1a\u4f20\u64ad\u5230 <code>main</code> \u51fd\u6570\u7684\u8c03\u7528\u6811\u4e0a\uff0c\u5982\u679c\u5b83\u4eec\u5728\u90a3\u91cc\u4e5f\u6ca1\u6709\u88ab\u6355\u83b7\uff0c\u7a0b\u5e8f\u5c31\u4f1a\u88ab\u4e2d\u6b62\u3002\u5728\u5f88\u591a\u60c5\u51b5\u4e0b\uff0c\u6bd4\u5982\u5185\u5b58\u6216\u78c1\u76d8\u7a7a\u95f4\u4e0d\u8db3\uff0c\u6211\u4eec\u4ec0\u4e48\u4e5f\u505a\u4e0d\u4e86\uff0c\u4f46\u6211\u4eec\u81f3\u5c11\u53ef\u4ee5\u6253\u5370\u4e00\u4e9b\u6587\u5b57\uff0c\u8bd5\u56fe\u89e3\u91ca\u7a0b\u5e8f\u5931\u8d25\u7684\u539f\u56e0\u3002\u4e0b\u9762\u663e\u793a\u4e86\u4e00\u79cd\u65b9\u6cd5\u3002\u4ee5\u8fd9\u79cd\u65b9\u5f0f\u7f16\u5199\u4efb\u4f55\u8f83\u5927\u7684\u7a0b\u5e8f\u5f53\u7136\u662f\u6709\u7528\u7684\uff0c\u4f60\u53ef\u4ee5\u901a\u8fc7\u6216\u591a\u6216\u5c11\u5730\u590d\u5236\u8fd9\u4e2a\u51fd\u6570\u6765\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u4f46 <code>try</code> \u5757\u9664\u5916\uff0c\u5b83\u5b9e\u9645\u4e0a\u7f16\u7801\u4e86\u672c\u5e94\u7528\u7a0b\u5e8f\u6240\u7279\u6709\u7684\u529f\u80fd\u3002\n\nint main() \n{ \n\n// \u8fd9\u4e2a\u51fd\u6570\u5e03\u5c40\u7684\u603b\u4f53\u601d\u8def\u5982\u4e0b\uff1a\u8ba9\u6211\u4eec\u8bd5\u7740\u50cf\u4ee5\u524d\u90a3\u6837\u8fd0\u884c\u7a0b\u5e8f......\n\n  try \n    { \n      Step6<2> laplace_problem_2d; \n      laplace_problem_2d.run(); \n    } \n\n// ......\u5982\u679c\u8fd9\u5e94\u8be5\u662f\u5931\u8d25\u7684\uff0c\u5c3d\u91cf\u6536\u96c6\u5c3d\u53ef\u80fd\u591a\u7684\u4fe1\u606f\u3002\u5177\u4f53\u6765\u8bf4\uff0c\u5982\u679c\u88ab\u629b\u51fa\u7684\u5f02\u5e38\u662f\u4e00\u4e2a\u4eceC++\u6807\u51c6\u7c7b\u6d3e\u751f\u51fa\u6765\u7684\u5bf9\u8c61  <code>exception</code>, then we can use the <code>what</code>  \u6210\u5458\u51fd\u6570\uff0c\u4ee5\u83b7\u5f97\u4e00\u4e2a\u63cf\u8ff0\u5f02\u5e38\u88ab\u629b\u51fa\u539f\u56e0\u7684\u5b57\u7b26\u4e32\u3002\n\n// deal.II\u7684\u5f02\u5e38\u7c7b\u90fd\u662f\u4ece\u6807\u51c6\u7c7b\u6d3e\u751f\u51fa\u6765\u7684\uff0c\u7279\u522b\u662f <code>exc.what()</code> \u51fd\u6570\u5c06\u8fd4\u56de\u4e0e\u4f7f\u7528 <code>Assert</code> \u5b8f\u629b\u51fa\u7684\u5f02\u5e38\u6240\u4ea7\u751f\u7684\u5b57\u7b26\u4e32\u5927\u81f4\u76f8\u540c\u3002\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\uff0c\u4f60\u5df2\u7ecf\u770b\u5230\u4e86\u8fd9\u79cd\u5f02\u5e38\u7684\u8f93\u51fa\uff0c\u7136\u540e\u4f60\u77e5\u9053\u5b83\u5305\u542b\u4e86\u5f02\u5e38\u53d1\u751f\u7684\u6587\u4ef6\u548c\u884c\u53f7\uff0c\u4ee5\u53ca\u5176\u4ed6\u4e00\u4e9b\u4fe1\u606f\u3002\u8fd9\u4e5f\u662f\u4e0b\u9762\u7684\u8bed\u53e5\u4f1a\u6253\u5370\u7684\u5185\u5bb9\u3002\n\n// \u9664\u6b64\u4ee5\u5916\uff0c\u9664\u4e86\u7528\u9519\u8bef\u4ee3\u7801\u9000\u51fa\u7a0b\u5e8f\uff08\u8fd9\u5c31\u662f <code>return 1;</code> \u7684\u4f5c\u7528\uff09\uff0c\u6211\u4eec\u80fd\u505a\u7684\u5e76\u4e0d\u591a\u3002\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// \u5982\u679c\u5728\u67d0\u5904\u629b\u51fa\u7684\u5f02\u5e38\u4e0d\u662f\u4ece\u6807\u51c6 <code>exception</code> \u7c7b\u6d3e\u751f\u51fa\u6765\u7684\u5bf9\u8c61\uff0c\u90a3\u4e48\u6211\u4eec\u6839\u672c\u65e0\u6cd5\u505a\u4efb\u4f55\u4e8b\u60c5\u3002\u90a3\u4e48\u6211\u4eec\u5c31\u7b80\u5355\u5730\u6253\u5370\u4e00\u4e2a\u9519\u8bef\u4fe1\u606f\u5e76\u9000\u51fa\u3002\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// \u5982\u679c\u6211\u4eec\u8d70\u5230\u8fd9\u4e00\u6b65\uff0c\u5c31\u6ca1\u6709\u4efb\u4f55\u5f02\u5e38\u4f20\u64ad\u5230\u4e3b\u51fd\u6570\u4e0a\uff08\u53ef\u80fd\u6709\u5f02\u5e38\uff0c\u4f46\u5b83\u4eec\u5728\u7a0b\u5e8f\u6216\u5e93\u7684\u67d0\u4e2a\u5730\u65b9\u88ab\u6355\u83b7\uff09\u3002\u56e0\u6b64\uff0c\u7a0b\u5e8f\u6309\u9884\u671f\u6267\u884c\uff0c\u6211\u4eec\u53ef\u4ee5\u65e0\u8bef\u8fd4\u56de\u3002\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 * @file radauthreetimestepping_main.cc\n * @brief NPDE homework RadauThreeTimestepping\n * @author Erick Schulz\n * @date 08/04/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <lf/assemble/assemble.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <iostream>\n#include <memory>\n\n#include \"radauthreetimestepping.h\"\n#include \"radauthreetimesteppingode.h\"\n\nusing namespace RadauThreeTimestepping;\n\nint main(int /*argc*/, char ** /*argv*/) {\n  /* Solving the ODE problem */\n  // This function prints to the terminal the convergence rates and average rate\n  // of a convergence study performed for the ODE (d/dt)y = -y.\n  testConvergenceTwoStageRadauLinScalODE();\n\n  /* Solving the parabolic heat equation */\n  // Create a Lehrfem++ square tensor product mesh\n  lf::mesh::utils::TPTriagMeshBuilder builder(\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2));\n  // Set mesh parameters following the Builder pattern\n  // Domain is the unit square\n\n  builder.setBottomLeftCorner(Eigen::Vector2d{-1.0, -1.0})\n      .setTopRightCorner(Eigen::Vector2d{1, 1})\n      .setNumXCells(50)\n      .setNumYCells(50);\n  auto mesh_p = builder.Build();\n\n  /* SAM_LISTING_BEGIN_1 */\n  //====================\n  // Your code goes here\n  // augment the mian function that it calls the function solveHeatEvolution() from subproblem k\n  // with m =50 and outputs the final temperature \n\n  // finite element space: \n  auto fe_space = std::make_shared<lf::uscalfe::FeSpacelangrangeO1<double>>(mesh_p); \n\n  // obtain local-> global index mapping for the current finite elemet space\n  const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()}; \n  const lf::uscalfe::size_type N_dof(dofh.NumDofs()); \n\n\n\n  int m = 50; \n  double final_time = 1.0; \n\n  Eigen::VectorXd discrete_sol = solveHeatEvolution(dofh, m, final_time); \n\n  \n  //====================\n\n  return 0;\n}\n", "meta": {"hexsha": "ca04d1af0511c5c3b05b9d3e970be20737870b9e", "size": 1967, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/RadauThreeTimestepping/mysolution/radauthreetimestepping_main.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/RadauThreeTimestepping/mysolution/radauthreetimestepping_main.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/RadauThreeTimestepping/mysolution/radauthreetimestepping_main.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9264705882, "max_line_length": 96, "alphanum_fraction": 0.699034062, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.5987275544388941}}
{"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": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright 2018 John Maddock. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\n\r\n#include \"eigen.hpp\"\r\n\r\ntemplate <>\r\nstruct related_number<boost::multiprecision::cpp_dec_float_100>\r\n{\r\n   typedef boost::multiprecision::cpp_dec_float_50 type;\r\n};\r\n\r\n\r\nint main()\r\n{\r\n   using namespace boost::multiprecision;\r\n   //test_float_type_2<double>();\r\n   test_float_type_2<boost::multiprecision::cpp_dec_float_100>();\r\n   return 0;\r\n}\r\n", "meta": {"hexsha": "ef5d49ca2b2746a49d0ef0928be750b3cfa3f682", "size": 675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/test/test_eigen_interop_cpp_dec_float_2.cpp", "max_stars_repo_name": "Talustus/boost_src", "max_stars_repo_head_hexsha": "ffe074de008f6e8c46ae1f431399cf932164287f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/multiprecision/test/test_eigen_interop_cpp_dec_float_2.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "third_party/boost/libs/multiprecision/test/test_eigen_interop_cpp_dec_float_2.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 28.125, "max_line_length": 80, "alphanum_fraction": 0.64, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.598720053457573}}
{"text": "// Copyright (c) 2018 Inria\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org)\n//\n// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial\n//\n// Author(s)     : Marc Glisse\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/CGAL_Ipelet_base.h>\n#include <CGAL/boost/graph/graph_traits_Delaunay_triangulation_2.h>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/filtered_graph.hpp>\n\nnamespace CGAL_mst {\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef CGAL::Delaunay_triangulation_2<Kernel>              Triangulation;\n\nconst std::string Slab[] = {\n  \"MST\", \"Help\"\n};\n\nconst std::string Hmsg[] = {\n  \"Draw the minimum spanning tree of a set of points\"\n};\n\nstruct mstIpelet\n  : CGAL::Ipelet_base<Kernel, 2> {\n  mstIpelet() : CGAL::Ipelet_base<Kernel, 2>(\"Minimum spanning tree\", Slab, Hmsg){}\n  void protected_run(int);\n};\n\ntemplate <typename T>\nstruct Is_finite {\n  const T* t_;\n  Is_finite()\n    : t_(nullptr)\n  {}\n  Is_finite(const T& t)\n    : t_(&t)\n  { }\n  template <typename VertexOrEdge>\n  bool operator()(const VertexOrEdge& voe) const {\n    return ! t_->is_infinite(voe);\n  }\n};\ntypedef Is_finite<Triangulation> Filter;\ntypedef boost::filtered_graph<Triangulation,Filter,Filter> Finite_triangulation;\ntypedef boost::graph_traits<Finite_triangulation>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<Finite_triangulation>::vertex_iterator vertex_iterator;\ntypedef boost::graph_traits<Finite_triangulation>::edge_descriptor edge_descriptor;\n// The BGL makes use of indices associated to the vertices\n// We use a std::map to store the index\ntypedef std::map<vertex_descriptor,int> VertexIndexMap;\nVertexIndexMap vertex_id_map;\n// A std::map is not a property map, because it is not lightweight\ntypedef boost::associative_property_map<VertexIndexMap> VertexIdPropertyMap;\nVertexIdPropertyMap vertex_index_pmap(vertex_id_map);\n\nvoid mstIpelet::protected_run(int /*fn*/)\n{\n  std::list<Point_2> pt_list;\n\n  read_active_objects(\n    CGAL::dispatch_or_drop_output<Point_2>(\n      std::back_inserter(pt_list)\n    )\n  );\n\n  if (pt_list.empty()) {\n    print_error_message(\"No mark selected\");\n    return;\n  }\n\n  Triangulation t(pt_list.begin(), pt_list.end());\n  Filter is_finite(t);\n  Finite_triangulation ft(t, is_finite, is_finite);\n\n  vertex_iterator vit, ve;\n  // Associate indices to the vertices\n  int index = 0;\n  // boost::tie assigns the first and second element of the std::pair\n  // returned by boost::vertices to the variables vit and ve\n  for(boost::tie(vit,ve)=boost::vertices(ft); vit!=ve; ++vit ){\n    vertex_descriptor vd = *vit;\n    vertex_id_map[vd] = index++;\n    }\n  // We use the default edge weight which is the squared length of the edge\n  // This property map is defined in graph_traits_Triangulation_2.h\n  // In the function call you can see a named parameter: vertex_index_map\n   std::list<edge_descriptor> mst;\n   boost::kruskal_minimum_spanning_tree(ft,\n                    std::back_inserter(mst),\n                    vertex_index_map(vertex_index_pmap));\n   for(std::list<edge_descriptor>::iterator it = mst.begin(); it != mst.end(); ++it){\n     edge_descriptor ed = *it;\n     vertex_descriptor svd = source(ed,t);\n     vertex_descriptor tvd = target(ed,t);\n     Triangulation::Vertex_handle sv = svd;\n     Triangulation::Vertex_handle tv = tvd;\n     draw_in_ipe(Kernel::Segment_2(sv->point(), tv->point()));\n   }\n}\n}\n\nCGAL_IPELET(CGAL_mst::mstIpelet)\n", "meta": {"hexsha": "2d3f050d6cdf495e721374849c8f0735b361fff4", "size": 3558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CGAL_ipelets/demo/CGAL_ipelets/mst.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "CGAL_ipelets/demo/CGAL_ipelets/mst.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "CGAL_ipelets/demo/CGAL_ipelets/mst.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.3454545455, "max_line_length": 87, "alphanum_fraction": 0.7279370433, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5985730356375132}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Delaunay_triangulation_on_sphere_traits_2.h>\n#include <CGAL/Projection_on_sphere_traits_3.h>\n#include <CGAL/Delaunay_triangulation_on_sphere_2.h>\n\n#include <CGAL/utility.h>\n#include <CGAL/Qt/DemosMainWindow.h>\n\n#include <QApplication>\n#include <QMainWindow>\n#include <QFileDialog>\n#include <QInputDialog>\n#include <CGAL/Three/Three.h>\n\n#include <boost/iterator/transform_iterator.hpp>\n\n#include <list>\n#include <fstream>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel          Kernel;\ntypedef Kernel::FT                                                   FT;\ntypedef Kernel::Point_3                                              Point_3;\ntypedef Kernel::Segment_3                                            Segment_3;\n\ntypedef CGAL::Projection_on_sphere_traits_3<Kernel>                  Projection_traits;\ntypedef CGAL::Delaunay_triangulation_on_sphere_2<Projection_traits>  Projected_DToS2;\n\ntypedef std::list<std::vector<Point_3> >                             Subsampled_arcs;\n\n#include \"Viewer.h\"\n#include \"ui_Mainwindow.h\"\n\ntemplate <class Output_iterator>\nvoid read_points(const char* file_path, Output_iterator out)\n{\n  std::ifstream input(file_path);\n  if(!input)\n  {\n    std::cerr << \"Error while reading \" << file_path << std::endl;\n    std::exit(EXIT_FAILURE);\n  }\n\n  double x,y,z;\n  while(input >> x >> y >> z)\n    *out++ = Point_3(x, y, z);\n}\n\nclass MainWindow\n  : public CGAL::Qt::DemosMainWindow,\n    public Ui::MainWindow\n{\n  Q_OBJECT\npublic:\n  MainWindow()\n  {\n    setupUi(this);\n  }\n\npublic slots:\n  void open(QString filename)\n  {\n    std::vector<Point_3> lst_pt;\n    read_points(filename.toUtf8().data(), std::back_inserter(lst_pt));\n\n    const Point_3 center(0,0,0);\n    const QString infos = QInputDialog::getText(nullptr, \"Sphere\", \"Enter the sphere's information : (Radius center.x center.y center.z):\",\n                                                QLineEdit::Normal,\"100.0 0.0 0.0 0.0\");\n    QStringList list = infos.split(QRegExp(\"\\\\s+\"), CGAL_QT_SKIP_EMPTY_PARTS);\n    if (list.isEmpty()) return;\n    if (list.size()!=4){\n      QMessageBox *msgBox = new QMessageBox;\n      msgBox->setWindowTitle(\"Error\");\n      msgBox->setText(\"ERROR : Input should consists of 4 doubles: The radius first, then the coordinates of the center.\");\n      msgBox->exec();\n      return;\n    }\n\n    double coords[4];\n    for(int j=0; j<4; ++j)\n    {\n      bool ok;\n      coords[j] = list.at(j).toDouble(&ok);\n      if(!ok)\n      {\n          QMessageBox *msgBox = new QMessageBox;\n          msgBox->setWindowTitle(\"Error\");\n          msgBox->setText(\"ERROR : Input is invalid.\");\n          msgBox->exec();\n          return;\n      }\n    }\n\n    Projection_traits traits(Point_3(coords[1], coords[2], coords[3]), coords[0]);\n    Projected_DToS2 dtos(lst_pt.begin(), lst_pt.end(), traits);\n\n    std::cout << dtos.number_of_vertices() << \" vertices\" << std::endl;\n\n    // Instantiate the viewer\n    viewer->open(lst_pt.begin(), lst_pt.end(), dtos);\n  }\n\n  void on_action_Quit_triggered()\n  {\n    close();\n  }\n\n  void on_action_Open_triggered()\n  {\n    QString filename = QFileDialog::getOpenFileName(this);\n    if(!filename.isNull())\n      open(filename);\n  }\n};\n\nint main(int argc, char** argv)\n{\n  // Read command lines arguments\n  QApplication application(argc,argv);\n  MainWindow mainWindow;\n  mainWindow.show();\n\n  // Run main loop\n  return application.exec();\n}\n\n#include \"main.moc\"\n", "meta": {"hexsha": "9b492a82213274136d94ba3f74caf774f180951d", "size": 3483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Triangulation_on_sphere_2/demo/Triangulation_on_sphere_2/main.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/demo/Triangulation_on_sphere_2/main.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/demo/Triangulation_on_sphere_2/main.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 27.2109375, "max_line_length": 139, "alphanum_fraction": 0.6382428941, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5985730337321846}}
{"text": "/**\n * @file\n * @brief NPDE homework ProjectionOntoGradients code\n * @author ?, Philippe Peter\n * @date December 2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <lf/assemble/assemble.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <iostream>\n#include <memory>\n\n#include \"projectionontogradients.h\"\n\nint main() {\n  // for this exercise a main file is not required\n  // but feel free to use it to call some of your functions for debugging\n  // purposes\n  const auto f = [](Eigen::Vector2d x) { return Eigen::Vector2d(-x(1), x(0)); };\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\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  // Compute solution\n  const Eigen::VectorXd sol_vec =\n      ProjectionOntoGradients::projectOntoGradients(dofh, f);\n  std::cout << sol_vec << std::endl;\n\n  std::cout << \"You may use this main file to call your function \"\n               \"ProjectionOntoGradients::projectOntoGradients\"\n            << std::endl;\n}\n", "meta": {"hexsha": "cb16a8b21fcfe83aa245df2890d8e057fcf3b1c9", "size": 1140, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ProjectionOntoGradients/templates/projectionontogradients_main.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ProjectionOntoGradients/templates/projectionontogradients_main.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ProjectionOntoGradients/templates/projectionontogradients_main.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 30.0, "max_line_length": 80, "alphanum_fraction": 0.6956140351, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.598533512573091}}
{"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": "#ifndef RenderUtilities_h\n#define RenderUtilities_h\n\n#include \"PngWrapper.hpp\"\n\n#include <Eigen/Dense>\n\nclass Camera;\n\nuint8_t * render_scene(uint16_t width, uint16_t height,\n                       const Eigen::Matrix<float, 3, Eigen::Dynamic>& vertices,\n                       const Eigen::Matrix<float, 3, Eigen::Dynamic>& normals,\n                       const Camera & camera, const Eigen::Vector3f & light_source);\n\nPngWrapper * normals_as_png(uint16_t width, uint16_t height, const Eigen::Matrix<float,3,Eigen::Dynamic>& normals);\n/*\n * Implement Lambertian colouring as per https://www.cs.unc.edu/~rademach/xroads-RT/RTarticle.html\n * @param width The with of the image\n * @param height The height of the imahe\n * @param vertices A width x height array of Vertex coordinates in global space\n * @param normals A width x height array of surface normals in global space\n * @param camera The Camera for which to render\n * @param light_source THe global position of the light source\n */\nPngWrapper * scene_as_png(uint16_t width, uint16_t height,\n                          const Eigen::Matrix<float,3,Eigen::Dynamic>& vertices,\n                          const Eigen::Matrix<float,3,Eigen::Dynamic>& normals,\n                          const Camera & camera,\n                          const Eigen::Vector3f & light_source);\n\nvoid save_normals_as_colour_png( std::string filename, uint16_t width, uint16_t height, const Eigen::Matrix<float,3,Eigen::Dynamic>& normals );\nvoid save_rendered_scene_as_png( std::string filename, uint16_t width, uint16_t height, const Eigen::Matrix<float,3,Eigen::Dynamic>& vertices, const Eigen::Matrix<float,3,Eigen::Dynamic>& normals, const Camera & camera, const Eigen::Vector3f & light_source);\n\n#endif // RenderUtilities_h\n", "meta": {"hexsha": "027ebfe71c3ae8488b9fbf018e18099463383ccb", "size": 1755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/RenderUtilities.hpp", "max_stars_repo_name": "justanhduc/ray-casting", "max_stars_repo_head_hexsha": "25ea97f3ff10d2b0cb3c9e935f1adb9201e42908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T22:38:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T22:38:06.000Z", "max_issues_repo_path": "include/RenderUtilities.hpp", "max_issues_repo_name": "justanhduc/ray-casting", "max_issues_repo_head_hexsha": "25ea97f3ff10d2b0cb3c9e935f1adb9201e42908", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-12T02:19:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T02:46:41.000Z", "max_forks_repo_path": "include/RenderUtilities.hpp", "max_forks_repo_name": "justanhduc/ray-casting", "max_forks_repo_head_hexsha": "25ea97f3ff10d2b0cb3c9e935f1adb9201e42908", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.1428571429, "max_line_length": 258, "alphanum_fraction": 0.698005698, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5985224614769593}}
{"text": "/*!=======================================================\n  |                                                     |\n  |      test_micromorphic_linear_elasticity.cpp        |\n  |                                                     |\n  -------------------------------------------------------\n  | The unit test file for                              |\n  | micromorphic_linear_elasticity.h/cpp. This file     |\n  | tests the classes and functions defined in          |\n  | micromorphic_linear_elasticity.h/cpp.               |\n  |                                                     |\n  | Generated files:                                    |\n  |    Results.tex:  A LaTeX file which contains the    |\n  |                  results as they will be included   |\n  |                  in the generated report.           |\n  =======================================================\n  | Dependencies:                                       |\n  | Eigen:  An implementation of various matrix         |\n  |         commands. The implementation of the data    |\n  |         matrix uses such a matrix.                  |\n  | tensor: An implementation of a tensor which stores  |\n  |         the data in a 2D matrix but allows access   |\n  |         through n dimensional index notation.       |\n  | finite_difference: An implementation of the         |\n  |                    computation of the numeric       |\n  |                    gradient via finite differences. |\n  =======================================================*/\n  \n#include <functional>\n#include <iostream>\n#include <fstream>\n#include <numeric>\n#include <vector>\n#include <Eigen/Dense>\n#include <tensor.h>\n#include <micromorphic_linear_elasticity.h>\n#include <finite_difference.h>\n#include <ctime>\n#include <stdlib.h>\n\nvoid print_vector(std::string name, std::vector< double > V){\n    /*!======================\n    |    print_vector    |\n    ======================\n    \n    Print a vector to the screen\n    \n    */\n    \n    std::cout << name << \": \";\n    \n    for(int i=0; i<V.size(); i++){\n        std::cout << V[i] << \" \";\n    }\n    std::cout << \"\\n\";\n}\n\nvoid print_vector_of_vectors(std::string name, std::vector< std::vector< double > > V){\n    /*!=================================\n    |    print_vector_of_vectors    |\n    =================================\n    \n    Print a vector of vectors to the screen\n    \n    */\n    \n    for(int i=0; i<V.size(); i++){\n        std::cout << name << \"[\" << i << \"]: \";\n        for(int j=0; j<V[i].size(); j++){\n            std::cout << V[i][j] << \" \";\n        }\n        std::cout << \"\\n\";\n    }\n}\n\ntemplate< int n_m, int m_m>\nbool compare_vectors_matrix(std::vector<std::vector< double > > V, Eigen::Matrix<double,n_m,m_m> M, double tol=1e-5){\n    /*!================================\n    |    compare_vectors_matrix    |\n    ================================\n    \n    Compare a vector of equal length vectors to a matrix\n    \n    */\n    \n    bool result = true;\n    double abs_error;   //!The absolute error\n    double rel_error;   //!The relative error\n    \n    if(V.size() != M.rows()){std::cout << \"Error: vector of vectors and matrix do not have the same number of rows.\\n\";return false;}\n    \n    for(int i=0; i<M.rows(); i++){\n        if(V[i].size()!=M.cols()){std::cout << \"Error: vector of vectors and matrix do not have the same number of columns in row \"<<i <<\".\";return false;}\n        \n        for(int j=0; j<M.cols(); j++){\n            //std::cout << \"M(\"<<i<<\",\"<<j<<\"): \"<<M(i,j)<<\" V[\"<<i<<\"][\"<<j<<\"]: \" << V[i][j] <<\"\\n\";\n            abs_error = fabs(M(i,j)-V[i][j]);\n            rel_error = fabs(M(i,j)-V[i][j])/std::max(fabs(M(i,j)),fabs(V[i][j]));\n            //std::cout << \"abs error: \" << abs_error << \"\\n\";\n            //std::cout << \"rel error: \" << rel_error << \"\\n\";\n            if((tol<abs_error)&&(tol<rel_error)){return false;}\n        }\n    }\n    \n    return true;\n}\n\ntemplate< int n_m, int m_m>\nbool compare_vectors_matrix_transpose(std::vector<std::vector< double > > V, Eigen::Matrix<double,n_m,m_m> M, double tol=1e-5){\n    /*!================================\n    |    compare_vectors_matrix    |\n    ================================\n    \n    Compare a vector of equal length vectors to a matrix\n    \n    */\n    \n    bool result = true;\n    double abs_error;   //!The absolute error\n    double rel_error;   //!The relative error\n    \n    if(V.size() != M.cols()){std::cout << \"Error: vector of vectors and matrix do not have the same number of rows.\\n\";return false;}\n    \n    for(int i=0; i<M.cols(); i++){\n        if(V[i].size()!=M.rows()){std::cout << \"Error: vector of vectors and matrix do not have the same number of columns in row \"<<i <<\".\";return false;}\n        \n        for(int j=0; j<M.rows(); j++){\n            //std::cout << \"M(\"<<j<<\",\"<<i<<\"): \"<<M(j,i)<<\" V[\"<<i<<\"][\"<<j<<\"]: \" << V[i][j] <<\"\\n\";\n            abs_error = fabs(M(j,i)-V[i][j]);\n            rel_error = fabs(M(j,i)-V[i][j])/std::max(fabs(M(j,i)),fabs(V[i][j]));\n            //std::cout << \"abs error: \" << abs_error << \"\\n\";\n            //std::cout << \"rel error: \" << rel_error << \"\\n\";\n            if((tol<abs_error)&&(tol<rel_error)){return false;}\n            \n        }\n    }\n    return true;\n}\n\nvoid test_stiffness_tensors(std::ofstream &results){\n    /*!================================\n    |    test_stiffness_tensors    |\n    ================================\n    \n    Test the computation of the different \n    stiffness tensors to make sure they \n    are consistent with the expected value.\n    \n    */\n    \n    //!Initialize test results\n    int  test_num        = 4;\n    std::vector<bool> test_results(test_num, false);\n    \n    //!Initialize the floating point parameters\n    double fpointer[19];\n    Vector fparams = Vector_Xd_Map(fpointer,19,1);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    //!Initialize the common tensors\n    tensor::Tensor23 I = tensor::eye();\n    \n    //!initialize the tensor answers\n    tensor::Tensor43 A_answer({3,3,3,3});\n    tensor::Tensor43 B_answer({3,3,3,3});\n    tensor::Tensor63 C_answer({3,3,3,3,3,3});\n    tensor::Tensor43 D_answer({3,3,3,3});\n    \n    //!initialize the tensor results\n    tensor::Tensor43 A_result({3,3,3,3});\n    tensor::Tensor43 B_result({3,3,3,3});\n    tensor::Tensor63 C_result({3,3,3,3,3,3});\n    tensor::Tensor43 D_result({3,3,3,3});\n    \n    //!Compute the expected tensors\n    micro_material::generate_A_stiffness(fparams,A_result);\n    micro_material::generate_B_stiffness(fparams,B_result);\n    micro_material::generate_C_stiffness(fparams,C_result);\n    micro_material::generate_D_stiffness(fparams,D_result);\n    \n    //!Extract the values of fparams\n    double rho    = fparams[ 0];             //!The density\n    double lambda = fparams[ 1];             //!lambda micromorphic material parameter\n    double mu     = fparams[ 2];             //!mu micromorphic material parameter\n    double eta    = fparams[ 3];             //!eta micromorphic material parameter\n    double tau    = fparams[ 4];             //!tau micromorphic material parameter\n    double kappa  = fparams[ 5];             //!kappa micromorphic material parameter\n    double nu     = fparams[ 6];             //!nu micromorphic material parameter\n    double sigma  = fparams[ 7];             //!sigma micromorphic material parameter\n    double tau1   = fparams[ 8];             //!tau1  micromorphic material parameter\n    double tau2   = fparams[ 9];             //!tau2  micromorphic material parameter\n    double tau3   = fparams[10];             //!tau3  micromorphic material parameter\n    double tau4   = fparams[11];             //!tau4  micromorphic material parameter\n    double tau5   = fparams[12];             //!tau5  micromorphic material parameter\n    double tau6   = fparams[13];             //!tau6  micromorphic material parameter\n    double tau7   = fparams[14];             //!tau7  micromorphic material parameter\n    double tau8   = fparams[15];             //!tau8  micromorphic material parameter\n    double tau9   = fparams[16];             //!tau9  micromorphic material parameter\n    double tau10  = fparams[17];             //!tau10 micromorphic material parameter\n    double tau11  = fparams[18];             //!tau11 micromorphic material parameter\n    \n    //!Compute the expected value of the A stiffness tensor\n    for(int K=0; K<3; K++){\n        for(int L=0; L<3; L++){\n            for(int M=0; M<3; M++){\n                for(int N=0; N<3; N++){\n                    A_answer(K,L,M,N) = lambda*I(K,L)*I(M,N)+mu*(I(K,M)*I(L,N)+I(K,N)*I(L,M));\n                }\n            }\n        }\n    }\n    \n    //!Compute the expected value of the B stiffness tensor\n    for(int K=0; K<3; K++){\n        for(int L=0; L<3; L++){\n            for(int M=0; M<3; M++){\n                for(int N=0; N<3; N++){\n                    B_answer(K,L,M,N) = (eta-tau)*I(K,L)*I(M,N) + kappa*I(K,M)*I(L,N) + nu*I(K,N)*I(L,M)\n                                        - sigma*(I(K,M)*I(L,N) + I(K,N)*I(L,M));\n                }\n            }\n        }\n    }\n    \n    //!Compute the expected value of the C stiffness tensor\n    for(int K=0; K<3; K++){\n        for(int L=0; L<3; L++){\n            for(int M=0; M<3; M++){\n                for(int N=0; N<3; N++){\n                    for(int P=0; P<3; P++){\n                        for(int Q=0; Q<3; Q++){\n                            C_answer(K,L,M,N,P,Q) =    tau1*(I(K,L)*I(M,N)*I(P,Q) + I(K,Q)*I(L,M)*I(N,P))\n                                                    +  tau2*(I(K,L)*I(M,P)*I(N,Q) + I(K,M)*I(L,Q)*I(N,P))\n                                                    +  tau3*I(K,L)*I(M,Q)*I(N,P)  + tau4*I(K,N)*I(L,M)*I(P,Q)\n                                                    +  tau5*(I(K,M)*I(L,N)*I(P,Q) + I(K,P)*I(L,M)*I(N,Q))\n                                                    +  tau6*I(K,M)*I(L,P)*I(N,Q)  + tau7*(I(K,N)*I(L,P)*I(M,Q))\n                                                    +  tau8*(I(K,P)*I(L,Q)*I(M,N) + I(K,Q)*I(L,N)*I(M,P)) + tau9*I(K,N)*I(L,Q)*I(M,P)\n                                                    + tau10*I(K,P)*I(L,N)*I(M,Q)  + tau11*I(K,Q)*I(L,P)*I(M,N);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    //!Compute the expected value of the D stiffness tensor\n    for(int K=0; K<3; K++){\n        for(int L=0; L<3; L++){\n            for(int M=0; M<3; M++){\n                for(int N=0; N<3; N++){\n                    D_answer(K,L,M,N) = tau*I(K,L)*I(M,N) + sigma*(I(K,M)*I(L,N) + I(K,N)*I(L,M));\n                }\n            }\n        }\n    }\n    \n    //!Compare the answers to the results\n    test_results[0] = A_answer.data.isApprox(A_result.data);\n    test_results[1] = B_answer.data.isApprox(B_result.data);\n    test_results[2] = C_answer.data.isApprox(C_result.data);\n    test_results[3] = D_answer.data.isApprox(D_result.data);\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_stiffness_tensors & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_stiffness_tensors & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return;\n}\n\nstd::vector< double > test_deformation(std::vector< double > reference_position){\n    /*!==========================\n    |    test_deformation    |\n    ==========================\n    \n    Compute a test deformation \n    to show that the deformation gradient \n    and microdisplacement are being computed \n    correctly.\n    \n    */\n    \n    double X = reference_position[0];\n    double Y = reference_position[1];\n    double Z = reference_position[2];\n    \n    std::vector< double > U;\n    U.resize(12,0);\n    \n    //!Set the displacements\n    U[ 0] =  0.32*X-0.14*Y+0.61*Z;\n    U[ 1] = -0.50*X+0.24*Y-0.38*Z;\n    U[ 2] = -0.22*X+0.47*Y+0.62*Z;\n    U[ 3] = -1.10*X+0.04*Y+2.30*Z; //phi_11\n    U[ 4] = -0.74*X+1.22*Y+2.22*Z; //phi_22\n    U[ 5] = -2.24*X+5.51*Y+1.11*Z; //phi_33\n    U[ 6] = -5.75*X+2.26*Y+7.66*Z; //phi_23\n    U[ 7] = -6.22*X+8.63*Y+2.72*Z; //phi_13\n    U[ 8] = -2.76*X+3.37*Y+3.93*Z; //phi_12\n    U[ 9] = -6.32*X+6.73*Y+7.22*Z; //phi_32\n    U[10] = -3.83*X+4.29*Y+1.51*Z; //phi_31\n    U[11] = -9.18*X+3.61*Y+9.08*Z; //phi_21\n    \n    return U;\n    \n}\n\nstd::vector< std::vector< double > > compute_gradients(std::vector< double > reference_position){\n    /*!===========================\n    |    compute_gradients    |\n    ===========================\n    \n    Compute the gradients of the test \n    deformation numerically so that the \n    results are consistent.\n    \n    */\n    \n    finite_difference::FiniteDifference FD(test_deformation,2,reference_position,1e-6);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n    \n}\n\nvoid populate_deformation_measures(tensor::Tensor23& C, tensor::Tensor23& Psi, tensor::Tensor33& Gamma){\n    /*!=======================================\n    |    populate_deformation_measures    |\n    =======================================\n    \n    Populate the deformation measures in a consistent \n    way.\n    \n    */\n    \n    //!Initialize the fundamental deformation measures\n    tensor::Tensor F({3,3});\n    tensor::Tensor chi({3,3});\n    tensor::Tensor grad_chi({3,3,3});\n    \n    //!Populate the gradients\n    std::vector< double > position = {1.2, 2.4, -0.42};\n    std::vector< std::vector< double > > gradients = compute_gradients(position); //Compute the numeric gradients\n    \n    for(int i=0; i<3; i++){\n        //!Populate the deformation gradient\n        F(0,i)          = gradients[i][ 0];\n        F(1,i)          = gradients[i][ 1];\n        F(2,i)          = gradients[i][ 2];\n        //!Populate the gradient of chi\n        grad_chi(0,0,i) = gradients[i][ 3];\n        grad_chi(1,1,i) = gradients[i][ 4];\n        grad_chi(2,2,i) = gradients[i][ 5];\n        grad_chi(1,2,i) = gradients[i][ 6];\n        grad_chi(0,2,i) = gradients[i][ 7];\n        grad_chi(0,1,i) = gradients[i][ 8];\n        grad_chi(2,1,i) = gradients[i][ 9];\n        grad_chi(2,0,i) = gradients[i][10];\n        grad_chi(1,0,i) = gradients[i][11];\n    }\n    \n    //Because we are specifying the deformation, and \n    //not the actual current coordinates, we have to \n    //add 1 to the diagonal terms\n    F(0,0) += 1;\n    F(1,1) += 1;\n    F(2,2) += 1;\n    \n    //!Populate the chi\n    std::vector< double > U = test_deformation(position);\n    chi(0,0) = 1.+U[ 3];\n    chi(1,1) = 1.+U[ 4];\n    chi(2,2) = 1.+U[ 5];\n    chi(1,2) =    U[ 6];\n    chi(0,2) =    U[ 7];\n    chi(0,1) =    U[ 8];\n    chi(2,1) =    U[ 9];\n    chi(2,0) =    U[10];\n    chi(1,0) =    U[11];\n    \n    for(int I=0; I<3; I++){\n        for(int J=0; J<3; J++){\n            for(int i=0; i<3; i++){\n                C(I,J)   += F(i,I)*F(i,J);\n                Psi(I,J) += F(i,I)*chi(i,J);\n            }\n            for(int K=0; K<3; K++){\n                for(int i=0; i<3; i++){\n                    Gamma(I,J,K) += F(i,I)*grad_chi(i,J,K);\n                }\n            }\n        }\n    }\n    return;\n}\n\n\nstd::vector<double> dPK2dC_parser(std::vector<double> C_in){\n    /*!=======================\n    |    dPK2dC_parser    |\n    =======================\n    \n    A function which parses the PK2\n    stress being varied by the \n    right Cauchy-Green deformation \n    tensor.\n    \n    Input:\n    \n        C_in:    The perturbed value of C.\n    \n    */\n    \n    std::vector<double> parsed_stress; //!The stress after being parsed\n    parsed_stress.resize(9);\n    \n    //!Populate derived deformation measures\n    tensor::Tensor23 C({3,3});          //!The right Cauchy-Green deformation tensor (will be discarded)\n    tensor::Tensor23 Psi({3,3});        //!The micro-deformation measure\n    tensor::Tensor33 Gamma({3,3,3});    //!The higher order micro-deformation measure\n    \n    populate_deformation_measures(C,Psi,Gamma);\n    \n    //!The initialization of the result stress tensors\n    tensor::Tensor23 PK2_result({3,3});\n    tensor::Tensor23 SIGMA_result({3,3});\n    tensor::Tensor33 M_result({3,3,3});\n    \n    //!Reset C\n    C(0,0) = C_in[0];\n    C(0,1) = C_in[1];\n    C(0,2) = C_in[2];\n    C(1,0) = C_in[3];\n    C(1,1) = C_in[4];\n    C(1,2) = C_in[5];\n    C(2,0) = C_in[6];\n    C(2,1) = C_in[7];\n    C(2,2) = C_in[8];\n    \n    //!Set the floating point parameters\n    //!Initialize the floating point parameters\n    double fpointer[19];\n    Vector fparams = Vector_Xd_Map(fpointer,19,1);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = i+1;\n    }\n    \n    int ipointer[1];\n    Vectori iparams = Vector_Xi_Map(ipointer,1,1);\n    \n    //!Compute and assign the stresses to the result measures\n    micro_material::get_stress(fparams, iparams, C, Psi, Gamma, PK2_result, SIGMA_result, M_result);\n    \n    parsed_stress[0] = PK2_result(0,0);\n    parsed_stress[1] = PK2_result(0,1);\n    parsed_stress[2] = PK2_result(0,2);\n    parsed_stress[3] = PK2_result(1,0);\n    parsed_stress[4] = PK2_result(1,1);\n    parsed_stress[5] = PK2_result(1,2);\n    parsed_stress[6] = PK2_result(2,0);\n    parsed_stress[7] = PK2_result(2,1);\n    parsed_stress[8] = PK2_result(2,2);\n    \n    return parsed_stress;\n}\n\nstd::vector<double> dSIGMAdC_parser(std::vector<double> C_in){\n    /*!=========================\n    |    dSIGMAdC_parser    |\n    =========================\n    \n    A function which parses the symmetric\n    stress being varied by the \n    right Cauchy-Green deformation \n    tensor.\n    \n    Input:\n    \n        C_in:    The perturbed value of C.\n    \n    */\n    \n    std::vector<double> parsed_stress; //!The stress after being parsed\n    parsed_stress.resize(9);\n    \n    //!Populate derived deformation measures\n    tensor::Tensor23 C({3,3});          //!The right Cauchy-Green deformation tensor (will be discarded)\n    tensor::Tensor23 Psi({3,3});        //!The micro-deformation measure\n    tensor::Tensor33 Gamma({3,3,3});    //!The higher order micro-deformation measure\n    \n    populate_deformation_measures(C,Psi,Gamma);\n    \n    //!The initialization of the result stress tensors\n    tensor::Tensor23 PK2_result({3,3});\n    tensor::Tensor23 SIGMA_result({3,3});\n    tensor::Tensor33 M_result({3,3,3});\n    \n    //!Reset Psi\n    C(0,0) = C_in[0];\n    C(0,1) = C_in[1];\n    C(0,2) = C_in[2];\n    C(1,0) = C_in[3];\n    C(1,1) = C_in[4];\n    C(1,2) = C_in[5];\n    C(2,0) = C_in[6];\n    C(2,1) = C_in[7];\n    C(2,2) = C_in[8];\n    \n    //!Set the floating point parameters\n    double fpointer[19];\n    Vector fparams = Vector_Xd_Map(fpointer,19,1);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = i+1;\n    }\n    \n    int ipointer[1];\n    Vectori iparams = Vector_Xi_Map(ipointer,1,1);\n    \n    //!Compute and assign the stresses to the result measures\n    micro_material::get_stress(fparams, iparams, C, Psi, Gamma, PK2_result, SIGMA_result, M_result);\n    \n    parsed_stress[0] = SIGMA_result(0,0);\n    parsed_stress[1] = SIGMA_result(0,1);\n    parsed_stress[2] = SIGMA_result(0,2);\n    parsed_stress[3] = SIGMA_result(1,0);\n    parsed_stress[4] = SIGMA_result(1,1);\n    parsed_stress[5] = SIGMA_result(1,2);\n    parsed_stress[6] = SIGMA_result(2,0);\n    parsed_stress[7] = SIGMA_result(2,1);\n    parsed_stress[8] = SIGMA_result(2,2);\n    \n    return parsed_stress;\n}\n\nstd::vector<double> dPK2dPsi_parser(std::vector<double> Psi_in){\n    /*!=========================\n    |    dPK2dPsi_parser    |\n    =========================\n    \n    A function which parses the PK2\n    stress being varied by the \n    micro-deformation tensor Psi.\n    \n    Input:\n    \n        Psi_in:    The perturbed value of Psi.\n    \n    */\n    \n    std::vector<double> parsed_stress; //!The stress after being parsed\n    parsed_stress.resize(9);\n    \n    //!Populate derived deformation measures\n    tensor::Tensor23 C({3,3});          //!The right Cauchy-Green deformation tensor (will be discarded)\n    tensor::Tensor23 Psi({3,3});        //!The micro-deformation measure\n    tensor::Tensor33 Gamma({3,3,3});    //!The higher order micro-deformation measure\n    \n    populate_deformation_measures(C,Psi,Gamma);\n    \n    //!The initialization of the result stress tensors\n    tensor::Tensor23 PK2_result({3,3});\n    tensor::Tensor23 SIGMA_result({3,3});\n    tensor::Tensor33 M_result({3,3,3});\n    \n    //!Reset Psi\n    Psi(0,0) = Psi_in[0];\n    Psi(0,1) = Psi_in[1];\n    Psi(0,2) = Psi_in[2];\n    Psi(1,0) = Psi_in[3];\n    Psi(1,1) = Psi_in[4];\n    Psi(1,2) = Psi_in[5];\n    Psi(2,0) = Psi_in[6];\n    Psi(2,1) = Psi_in[7];\n    Psi(2,2) = Psi_in[8];\n    \n    //!Set the floating point parameters\n    double fpointer[19];\n    Vector fparams = Vector_Xd_Map(fpointer,19,1);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = i+1;\n    }\n    \n    int ipointer[1];\n    Vectori iparams = Vector_Xi_Map(ipointer,1,1);\n    \n    //!Compute and assign the stresses to the result measures\n    micro_material::get_stress(fparams, iparams, C, Psi, Gamma, PK2_result, SIGMA_result, M_result);\n    \n    parsed_stress[0] = PK2_result(0,0);\n    parsed_stress[1] = PK2_result(0,1);\n    parsed_stress[2] = PK2_result(0,2);\n    parsed_stress[3] = PK2_result(1,0);\n    parsed_stress[4] = PK2_result(1,1);\n    parsed_stress[5] = PK2_result(1,2);\n    parsed_stress[6] = PK2_result(2,0);\n    parsed_stress[7] = PK2_result(2,1);\n    parsed_stress[8] = PK2_result(2,2);\n    \n    return parsed_stress;\n}\n\nstd::vector<double> dSIGMAdPsi_parser(std::vector<double> Psi_in){\n    /*!===========================\n    |    dSIGMAdPsi_parser    |\n    ===========================\n    \n    A function which parses the symmetric\n    stress being varied by the \n    micro-deformation tensor Psi.\n    \n    Input:\n    \n        Psi_in:    The perturbed value of Psi.\n    \n    */\n    \n    std::vector<double> parsed_stress; //!The stress after being parsed\n    parsed_stress.resize(9);\n    \n    //!Populate derived deformation measures\n    tensor::Tensor23 C({3,3});          //!The right Cauchy-Green deformation tensor (will be discarded)\n    tensor::Tensor23 Psi({3,3});        //!The micro-deformation measure\n    tensor::Tensor33 Gamma({3,3,3});    //!The higher order micro-deformation measure\n    \n    populate_deformation_measures(C,Psi,Gamma);\n    \n    //!The initialization of the result stress tensors\n    tensor::Tensor23 PK2_result({3,3});\n    tensor::Tensor23 SIGMA_result({3,3});\n    tensor::Tensor33 M_result({3,3,3});\n    \n    //!Reset C\n    Psi(0,0) = Psi_in[0];\n    Psi(0,1) = Psi_in[1];\n    Psi(0,2) = Psi_in[2];\n    Psi(1,0) = Psi_in[3];\n    Psi(1,1) = Psi_in[4];\n    Psi(1,2) = Psi_in[5];\n    Psi(2,0) = Psi_in[6];\n    Psi(2,1) = Psi_in[7];\n    Psi(2,2) = Psi_in[8];\n    \n    //!Set the floating point parameters\n    double fpointer[19];\n    Vector fparams = Vector_Xd_Map(fpointer,19,1);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = i+1;\n    }\n    \n    int ipointer[1];\n    Vectori iparams = Vector_Xi_Map(ipointer,1,1);\n    \n    //!Compute and assign the stresses to the result measures\n    micro_material::get_stress(fparams, iparams, C, Psi, Gamma, PK2_result, SIGMA_result, M_result);\n    \n    parsed_stress[0] = SIGMA_result(0,0);\n    parsed_stress[1] = SIGMA_result(0,1);\n    parsed_stress[2] = SIGMA_result(0,2);\n    parsed_stress[3] = SIGMA_result(1,0);\n    parsed_stress[4] = SIGMA_result(1,1);\n    parsed_stress[5] = SIGMA_result(1,2);\n    parsed_stress[6] = SIGMA_result(2,0);\n    parsed_stress[7] = SIGMA_result(2,1);\n    parsed_stress[8] = SIGMA_result(2,2);\n    \n    return parsed_stress;\n}\n\nstd::vector<double> dPK2dGamma_parser(std::vector<double> Gamma_in){\n    /*!===========================\n    |    dPK2dGamma_parser    |\n    ===========================\n    \n    A function which parses the PK2\n    stress being varied by the \n    micro-deformation gradient tensor Gamma.\n    \n    Input:\n    \n        Psi_in:    The perturbed value of Psi.\n    \n    */\n    \n    std::vector<double> parsed_stress; //!The stress after being parsed\n    parsed_stress.resize(9);\n    \n    //!Populate derived deformation measures\n    tensor::Tensor23 C({3,3});          //!The right Cauchy-Green deformation tensor (will be discarded)\n    tensor::Tensor23 Psi({3,3});        //!The micro-deformation measure\n    tensor::Tensor33 Gamma({3,3,3});    //!The higher order micro-deformation measure\n    \n    populate_deformation_measures(C,Psi,Gamma);\n    \n    //!The initialization of the result stress tensors\n    tensor::Tensor23 PK2_result({3,3});\n    tensor::Tensor23 SIGMA_result({3,3});\n    tensor::Tensor33 M_result({3,3,3});\n    \n    //!Reset Gamma\n    int temp_indx = 0;\n    for(int K=0; K<3; K++){\n        for(int I=0; I<3; I++){\n            for(int J=0; J<3; J++){\n                Gamma(I,J,K) = Gamma_in[temp_indx];\n                temp_indx++;\n            }\n        }\n    }\n    \n    //!Set the floating point parameters\n    double fpointer[19];\n    Vector fparams = Vector_Xd_Map(fpointer,19,1);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = i+1;\n    }\n    \n    int ipointer[1];\n    Vectori iparams = Vector_Xi_Map(ipointer,1,1);\n    \n    //!Compute and assign the stresses to the result measures\n    micro_material::get_stress(fparams, iparams, C, Psi, Gamma, PK2_result, SIGMA_result, M_result);\n    \n    parsed_stress[0] = PK2_result(0,0);\n    parsed_stress[1] = PK2_result(0,1);\n    parsed_stress[2] = PK2_result(0,2);\n    parsed_stress[3] = PK2_result(1,0);\n    parsed_stress[4] = PK2_result(1,1);\n    parsed_stress[5] = PK2_result(1,2);\n    parsed_stress[6] = PK2_result(2,0);\n    parsed_stress[7] = PK2_result(2,1);\n    parsed_stress[8] = PK2_result(2,2);\n    \n    return parsed_stress;\n}\n\nstd::vector<double> dSIGMAdGamma_parser(std::vector<double> Gamma_in){\n    /*!=========================\n    |    dSIGMAdGamma_parser    |\n    =========================\n    \n    A function which parses the symmetric\n    stress being varied by the \n    micro-deformation gradient tensor Gamma.\n    \n    Input:\n    \n        Psi_in:    The perturbed value of Psi.\n    \n    */\n    \n    std::vector<double> parsed_stress; //!The stress after being parsed\n    parsed_stress.resize(9);\n    \n    //!Populate derived deformation measures\n    tensor::Tensor23 C({3,3});          //!The right Cauchy-Green deformation tensor (will be discarded)\n    tensor::Tensor23 Psi({3,3});        //!The micro-deformation measure\n    tensor::Tensor33 Gamma({3,3,3});    //!The higher order micro-deformation measure\n    \n    populate_deformation_measures(C,Psi,Gamma);\n    \n    //!The initialization of the result stress tensors\n    tensor::Tensor23 PK2_result({3,3});\n    tensor::Tensor23 SIGMA_result({3,3});\n    tensor::Tensor33 M_result({3,3,3});\n    \n    //!Reset Gamma\n    int temp_indx = 0;\n    for(int K=0; K<3; K++){\n        for(int I=0; I<3; I++){\n            for(int J=0; J<3; J++){\n                Gamma(I,J,K) = Gamma_in[temp_indx];\n                temp_indx++;\n            }\n        }\n    }\n    \n    //!Set the floating point parameters\n    double fpointer[19];\n    Vector fparams = Vector_Xd_Map(fpointer,19,1);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = i+1;\n    }\n    \n    int ipointer[1];\n    Vectori iparams = Vector_Xi_Map(ipointer,1,1);\n    \n    //!Compute and assign the stresses to the result measures\n    micro_material::get_stress(fparams, iparams, C, Psi, Gamma, PK2_result, SIGMA_result, M_result);\n    \n    parsed_stress[0] = SIGMA_result(0,0);\n    parsed_stress[1] = SIGMA_result(0,1);\n    parsed_stress[2] = SIGMA_result(0,2);\n    parsed_stress[3] = SIGMA_result(1,0);\n    parsed_stress[4] = SIGMA_result(1,1);\n    parsed_stress[5] = SIGMA_result(1,2);\n    parsed_stress[6] = SIGMA_result(2,0);\n    parsed_stress[7] = SIGMA_result(2,1);\n    parsed_stress[8] = SIGMA_result(2,2);\n    \n    return parsed_stress;\n}\n\nvoid test_get_stress(std::ofstream &results){\n    /*!=========================\n    |    test_get_stress    |\n    =========================\n    \n    A test for the computation of the \n    stress tensors. They are compared to \n    another formulation of the tensors \n    to ensure that they are consistent.\n    \n    */\n    \n    //!Initialize test results\n    int  test_num        = 10;\n    std::vector<bool> test_results(test_num,false);\n    \n    //!Seed the random number generator\n    srand (1);\n    \n    //!Initialize the common tensors\n    tensor::Tensor23 ITEN = tensor::eye();\n    \n    //!Initialize the floating point parameters\n    double fpointer[19];\n    Vector fparams = Vector_Xd_Map(fpointer,19,1);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = i+1;\n    }\n    \n    int ipointer[1];\n    \n    Vectori iparams = Vector_Xi_Map(ipointer,1,1);\n    \n    //!Populate derived deformation measures\n    tensor::Tensor23 C({3,3});          //!The right Cauchy-Green deformation tensor\n    tensor::Tensor23 Psi({3,3});        //!The micro-deformation measure\n    tensor::Tensor33 Gamma({3,3,3});    //!The higher order micro-deformation measure\n    \n    populate_deformation_measures(C,Psi,Gamma);\n    \n    tensor::Tensor23 Cinv = C.inverse();\n    \n    //!Compute the strain measures\n    tensor::Tensor23 macro_E = 0.5*(C-ITEN);\n    tensor::Tensor23 micro_E = Psi-ITEN;\n    \n    //!Initialize the stiffness tensors\n    tensor::Tensor43 A_stiffness({3,3,3,3});\n    tensor::Tensor43 B_stiffness({3,3,3,3});\n    tensor::Tensor63 C_stiffness({3,3,3,3,3,3});\n    tensor::Tensor43 D_stiffness({3,3,3,3});\n        \n    //!Compute the stiffness tensors\n    micro_material::generate_A_stiffness(fparams,A_stiffness);\n    micro_material::generate_B_stiffness(fparams,B_stiffness);\n    micro_material::generate_C_stiffness(fparams,C_stiffness);\n    micro_material::generate_D_stiffness(fparams,D_stiffness);\n    \n    tensor::Tensor23 PK2_answer({3,3});   //!The expected second Piola-Kirchhoff Stress\n    tensor::Tensor23 SIGMA_answer({3,3}); //!The symmetric micro-stress\n    tensor::Tensor33 M_answer({3,3,3});   //!The expected higher order stress\n    \n    //!Compute the answer stress tensors\n    for(int I=0; I<3; I++){\n        for(int J=0; J<3; J++){\n            for(int K=0; K<3; K++){\n                for(int L=0; L<3; L++){\n                    PK2_answer(I,J)   += A_stiffness(I,J,K,L)*macro_E(K,L) + D_stiffness(I,J,K,L)*micro_E(K,L);\n                    SIGMA_answer(I,J) += A_stiffness(I,J,K,L)*macro_E(K,L) + D_stiffness(I,J,K,L)*micro_E(K,L);\n                }\n            }\n            \n            for(int K=0; K<3; K++){\n                for(int L=0; L<3; L++){\n                    for(int Q=0; Q<3; Q++){\n                        for(int R=0; R<3; R++){\n                            PK2_answer(I,J)   +=   (B_stiffness(I,Q,K,L)*micro_E(K,L) + D_stiffness(I,Q,K,L)*macro_E(K,L))*(micro_E(R,Q) + ITEN(R,Q))*Cinv(J,R);\n                            SIGMA_answer(I,J) +=   (B_stiffness(I,Q,K,L)*micro_E(K,L) + D_stiffness(I,Q,K,L)*macro_E(K,L))*(micro_E(R,Q) + ITEN(R,Q))*Cinv(J,R)\n                                                 + (B_stiffness(J,Q,K,L)*micro_E(K,L) + D_stiffness(J,Q,K,L)*macro_E(K,L))*(micro_E(R,Q) + ITEN(R,Q))*Cinv(I,R);\n                        }\n                    }\n                }\n            }\n            \n            for(int Q=0; Q<3; Q++){\n                for(int R=0; R<3; R++){\n                    for(int L=0; L<3; L++){\n                        for(int M=0; M<3; M++){\n                            for(int N=0; N<3; N++){\n                                for(int S=0; S<3; S++){\n                                    PK2_answer(I,J)   +=   C_stiffness(I,Q,R,L,M,N)*Gamma(L,M,N)*Cinv(S,J)*Gamma(S,Q,R);\n                                    SIGMA_answer(I,J) +=   C_stiffness(I,Q,R,L,M,N)*Gamma(L,M,N)*Cinv(S,J)*Gamma(S,Q,R)\n                                                         + C_stiffness(J,Q,R,L,M,N)*Gamma(L,M,N)*Cinv(S,I)*Gamma(S,Q,R);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    for(int I=0; I<3; I++){\n        for(int J=0; J<3; J++){\n            for(int K=0; K<3; K++){\n                for(int L=0; L<3; L++){\n                    for(int M=0; M<3; M++){\n                        for(int N=0; N<3; N++){\n                            M_answer(I,J,K) += C_stiffness(I,J,K,L,M,N)*Gamma(L,M,N);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    //!The initialization of the result stress tensors\n    tensor::Tensor23 PK2_result({3,3});\n    tensor::Tensor23 SIGMA_result({3,3});\n    tensor::Tensor33 M_result({3,3,3});\n    \n    //!Compute and assign the stresses to the result measures\n    micro_material::get_stress(fparams, iparams, C, Psi, Gamma, PK2_result, SIGMA_result, M_result);\n    \n    test_results[0] = PK2_answer.data.isApprox(PK2_result.data);\n    test_results[1] = SIGMA_answer.data.isApprox(SIGMA_result.data);\n    test_results[2] = M_answer.data.isApprox(M_result.data);\n    \n    \n    //!Compute the tangents and compare them to the numeric results\n    \n    //!Initialize the tangents\n    tensor::Tensor43 dPK2dC = tensor::Tensor43({3,3,3,3});\n    tensor::Tensor43 dPK2dPsi = tensor::Tensor43({3,3,3,3});\n    tensor::Tensor53 dPK2dGamma = tensor::Tensor53({3,3,3,3,3});\n    \n    tensor::Tensor43 dSIGMAdC = tensor::Tensor43({3,3,3,3});\n    tensor::Tensor43 dSIGMAdPsi = tensor::Tensor43({3,3,3,3});\n    tensor::Tensor53 dSIGMAdGamma = tensor::Tensor53({3,3,3,3,3});\n    \n    tensor::Tensor53 dMdC = tensor::Tensor53({3,3,3,3,3});\n    tensor::Tensor53 dMdPsi = tensor::Tensor53({3,3,3,3,3});\n    tensor::Tensor63 dMdGamma = tensor::Tensor63({3,3,3,3,3,3});\n    \n    micro_material::get_stress( fparams,    iparams,            C, Psi, Gamma, PK2_result, SIGMA_result, M_result,\n                                 dPK2dC,   dPK2dPsi,   dPK2dGamma,\n                               dSIGMAdC, dSIGMAdPsi, dSIGMAdGamma,\n                                   dMdC,     dMdPsi,     dMdGamma);\n    \n    //!Compute the numeric results for dPK2dC\n    std::vector<double> vec_ten;\n    vec_ten.resize(9);\n    vec_ten[0] = C(0,0);\n    vec_ten[1] = C(0,1);\n    vec_ten[2] = C(0,2);\n    vec_ten[3] = C(1,0);\n    vec_ten[4] = C(1,1);\n    vec_ten[5] = C(1,2);\n    vec_ten[6] = C(2,0);\n    vec_ten[7] = C(2,1);\n    vec_ten[8] = C(2,2);\n    finite_difference::FiniteDifference FD(dPK2dC_parser,2,vec_ten,1e-6);\n    std::vector< std::vector< double > > temp_gradient = FD.numeric_gradient();\n    \n    test_results[3]=compare_vectors_matrix_transpose(temp_gradient,dPK2dC.data);\n    \n    //print_vector_of_vectors(\"dPK2dC_answer\",temp_gradient);\n    //std::cout << \"dPK2dC_result\\n\" << dPK2dC.data << \"\\n\";\n    \n    //!Compute the numeric results for dSIGMAdC\n    FD = finite_difference::FiniteDifference(dSIGMAdC_parser,2,vec_ten,1e-6);\n    temp_gradient = FD.numeric_gradient();\n    \n    //print_vector_of_vectors(\"dSIGMAdC_answer\",temp_gradient);\n    //std::cout << \"dSIGMAdC_result\\n\" << dSIGMAdC.data << \"\\n\";\n    \n    test_results[4] = compare_vectors_matrix_transpose(temp_gradient,dSIGMAdC.data);\n    \n    vec_ten[0] = Psi(0,0);\n    vec_ten[1] = Psi(0,1);\n    vec_ten[2] = Psi(0,2);\n    vec_ten[3] = Psi(1,0);\n    vec_ten[4] = Psi(1,1);\n    vec_ten[5] = Psi(1,2);\n    vec_ten[6] = Psi(2,0);\n    vec_ten[7] = Psi(2,1);\n    vec_ten[8] = Psi(2,2);\n    FD = finite_difference::FiniteDifference(dPK2dPsi_parser,2,vec_ten,1e-6);\n    temp_gradient = FD.numeric_gradient();\n    \n    //print_vector_of_vectors(\"dPK2dPsi_answer\",temp_gradient);\n    //std::cout << \"dPK2dPsi_result\\n\" << dPK2dPsi.data << \"\\n\";\n    \n    test_results[5] = compare_vectors_matrix_transpose(temp_gradient,dPK2dPsi.data);\n    \n    FD = finite_difference::FiniteDifference(dSIGMAdPsi_parser,2,vec_ten,1e-6);\n    temp_gradient = FD.numeric_gradient();\n    \n    //print_vector_of_vectors(\"dSIGMAdPsi_answer\",temp_gradient);\n    //std::cout << \"dSIGMAdPsi_result\\n\" << dSIGMAdPsi.data << \"\\n\";\n    \n    test_results[6] = compare_vectors_matrix_transpose(temp_gradient,dSIGMAdPsi.data);\n    \n    int temp_indx=0;\n    \n    vec_ten.resize(27);\n    for(int K=0; K<3; K++){\n        for(int I=0; I<3; I++){\n            for(int J=0; J<3; J++){\n                vec_ten[temp_indx] = Gamma(I,J,K);\n                temp_indx++;\n            }\n        }\n    }\n    \n    FD = finite_difference::FiniteDifference(dPK2dGamma_parser,2,vec_ten,1e-6);\n    temp_gradient = FD.numeric_gradient();\n    \n    //Rearrange the gradient into a form we can compare easily\n    std::vector< std::vector< double > > rearranged_gradient;\n    rearranged_gradient.resize(27);\n    for(int I=0; I<rearranged_gradient.size(); I++){rearranged_gradient[I].resize(9);}\n    \n    for(int N=0; N<9; N++){\n        for(int I=0; I<3; I++){\n            for(int J=0; J<3; J++){\n                for(int K=0; K<3; K++){\n                    rearranged_gradient[K+9*I+3*J][N] = temp_gradient[9*K+3*I+J][N];\n                }\n            }\n        }\n    }\n    //print_vector_of_vectors(\"dPK2dGamma_answer\",rearranged_gradient);\n    //std::cout << \"dPK2dGamma_result\\n\" << dPK2dGamma.data << \"\\n\";\n    \n    test_results[7] = compare_vectors_matrix_transpose(rearranged_gradient,dPK2dGamma.data);\n    \n    FD = finite_difference::FiniteDifference(dSIGMAdGamma_parser,2,vec_ten,1e-6);\n    temp_gradient = FD.numeric_gradient();\n    \n    //Rearrange the gradient into a form we can compare easily\n    \n    for(int N=0; N<9; N++){\n        for(int I=0; I<3; I++){\n            for(int J=0; J<3; J++){\n                for(int K=0; K<3; K++){\n                    rearranged_gradient[K+9*I+3*J][N] = temp_gradient[9*K+3*I+J][N];\n                }\n            }\n        }\n    }\n    //print_vector_of_vectors(\"dPK2dGamma_answer\",rearranged_gradient);\n    //std::cout << \"dPK2dGamma_result\\n\" << dPK2dGamma.data << \"\\n\";\n    \n    test_results[8] = compare_vectors_matrix_transpose(rearranged_gradient,dSIGMAdGamma.data);\n    \n    test_results[9] = dMdGamma.data.isApprox(C_stiffness.data);\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_get_stress & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_get_stress & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return;\n}\n\nint main(){\n    /*!==========================\n    |         main            |\n    ===========================\n    \n    The main loop which runs the tests defined in the \n    accompanying functions. Each function should output\n    the function name followed by & followed by True or \n    False if the test passes or fails respectively.*/\n    \n    std::ofstream results;\n    //Open the results file\n    results.open (\"results.tex\");\n    \n    //!Run the test functions\n    test_stiffness_tensors(results);\n    test_get_stress(results);\n    \n    //Close the results file\n    results.close();\n}\n\n", "meta": {"hexsha": "c41052efd76c33f753929f77c80c33ea17da8ace", "size": 39170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/tests/micromorphic_linear_elasticity/test_micromorphic_linear_elasticity.cpp", "max_stars_repo_name": "lanl/tardigrade-micromorphic-element", "max_stars_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/tests/micromorphic_linear_elasticity/test_micromorphic_linear_elasticity.cpp", "max_issues_repo_name": "lanl/tardigrade-micromorphic-element", "max_issues_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/tests/micromorphic_linear_elasticity/test_micromorphic_linear_elasticity.cpp", "max_forks_repo_name": "lanl/tardigrade-micromorphic-element", "max_forks_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4503078276, "max_line_length": 160, "alphanum_fraction": 0.5353331631, "num_tokens": 11392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5985224403017186}}
{"text": "#ifndef PARAMETERSSE3_HPP\n#define PARAMETERSSE3_HPP\n\n#include <Eigen/StdVector>\n#include <Eigen/Geometry>\n#include <iostream>\n\n#include <ceres/ceres.h>\n\n#include \"se3.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nclass CameraParameters\n{\nprotected:\n    double f;\n    double cx;\n    double cy;\npublic:\n    CameraParameters(double f_, double cx_, double cy_)\n        : f(f_), cx(cx_), cy(cy_) {}\n\n    Vector2d cam_map(const Vector3d& p)\n    {\n        Vector2d z;\n        z[0] = f * p[0] / p[2] + cx;\n        z[1] = f * p[1] / p[2] + cy;\n        return z;\n    }\n};\n\n/// PoseBlockSize can only be\n/// 7 (quaternion + translation vector) or\n/// 6 (rotation vector + translation vector)\ntemplate<int PoseBlockSize>\nclass ReprojectionErrorSE3XYZ: public ceres::SizedCostFunction<2, PoseBlockSize, 3>\n{\npublic:\n    ReprojectionErrorSE3XYZ(double f_,\n                            double cx_,\n                            double cy_,\n                            double observation_x,\n                            double observation_y)\n        : f(f_), cx(cx_), cy(cy_),\n          _observation_x(observation_x),\n          _observation_y(observation_y){}\n\n    virtual bool Evaluate(double const* const* parameters,\n                          double* residuals,\n                          double** jacobians) const;\n\n    double f;\n    double cx;\n    double cy;\n\nprivate:\n    double _observation_x;\n    double _observation_y;\n};\n\n/// PoseBlockSize can only be\n/// 7 (quaternion + translation vector) or\n/// 6 (rotation vector + translation vector)\ntemplate<int PoseBlockSize>\nclass PoseSE3Parameterization : public ceres::LocalParameterization {\npublic:\n    PoseSE3Parameterization() {}\n    virtual ~PoseSE3Parameterization() {}\n    virtual bool Plus(const double* x,\n                      const double* delta,\n                      double* x_plus_delta) const;\n    virtual bool ComputeJacobian(const double* x,\n                                 double* jacobian) const;\n    virtual int GlobalSize() const { return PoseBlockSize; }\n    virtual int LocalSize() const { return 6; }\n};\n\n/// PoseBlockSize can only be\n/// 7 (quaternion + translation vector) or\n/// 6 (rotation vector + translation vector)\ntemplate<int PoseBlockSize>\nclass PosePointParametersBlock\n{\npublic:\n    PosePointParametersBlock(){}\n    void create(int pose_num, int point_num)\n    {\n        poseNum = pose_num;\n        pointNum = point_num;\n        values = new double[pose_num * PoseBlockSize + point_num * 3];\n    }\n    PosePointParametersBlock(int pose_num, int point_num): poseNum(pose_num), pointNum(point_num)\n    {\n        values = new double[pose_num * PoseBlockSize + point_num * 3];\n    }\n    ~PosePointParametersBlock() { delete[] values; }\n\n    void setPose(int idx, const Quaterniond &q, const Vector3d &trans);\n\n    void getPose(int idx, Quaterniond &q, Vector3d &trans);\n\n    double* pose(int idx) {  return values + idx * PoseBlockSize; }\n\n    double* point(int idx) { return values + poseNum * PoseBlockSize + idx * 3; }\n\n    int poseNum;\n    int pointNum;\n    double *values;\n\n};\n\n\n#endif // PARAMETERSSE3_HPP\n", "meta": {"hexsha": "bf46faa213f3eb1b70307c2d12caeba53e5c6255", "size": 3085, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "parametersse3.hpp", "max_stars_repo_name": "geoeo/ba_demo_ceres", "max_stars_repo_head_hexsha": "c89b27f6c99b207ae3bf99e8fd992290a253da7a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T08:35:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T12:34:43.000Z", "max_issues_repo_path": "parametersse3.hpp", "max_issues_repo_name": "geoeo/ba_demo_ceres", "max_issues_repo_head_hexsha": "c89b27f6c99b207ae3bf99e8fd992290a253da7a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-10T10:48:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-30T09:18:58.000Z", "max_forks_repo_path": "parametersse3.hpp", "max_forks_repo_name": "geoeo/ba_demo_ceres", "max_forks_repo_head_hexsha": "c89b27f6c99b207ae3bf99e8fd992290a253da7a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2018-05-15T16:11:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T13:34:23.000Z", "avg_line_length": 26.5948275862, "max_line_length": 97, "alphanum_fraction": 0.6304700162, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5985224349956405}}
{"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": "#define BOOST_TEST_MODULE MixedLatticeMultTests\n\n\n\n#include \"DenseLattice.h\"\r\n#include \"SparseLattice.h\"\n#include \"MIAConfig.h\"\n\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\n\n\ntemplate<typename data_type>\nvoid multwork(size_t m1, size_t n1, size_t n2, size_t p){\n    typedef LibMIA::DenseLattice<data_type> denseType;\r\n    typedef LibMIA::SparseLattice<data_type> sparseType;\r\n    denseType DenseLat1(m1,n1,p);\r\n    denseType DenseLat2(n1,n2,p);\r\n\n    denseType DenseLat3_dense;\n    sparseType DenseLat3_sparse;\r\n\r\n    sparseType SparseLat1(m1,n1,p);\r\n    sparseType SparseLat2(n1,n2,p);\n\n\n\n\r\n    DenseLat1.randu(0,10);\r\n    DenseLat2.randu(0,10);\r\n    for(auto it=DenseLat1.data_begin();it<DenseLat1.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n    for(auto it=DenseLat2.data_begin();it<DenseLat2.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n\r\n\r\n    SparseLat1=DenseLat1;\r\n    SparseLat2=DenseLat2;\r\n\r\n\r\n    DenseLat3_dense=DenseLat1*DenseLat2;\r\n\r\n    DenseLat3_sparse=SparseLat1*DenseLat2;\r\n\r\n\r\n//    DenseLat3_dense.print();\r\n//    DenseLat3_sparse.print();\r\n    BOOST_CHECK_MESSAGE(DenseLat3_dense.fuzzy_equals(DenseLat3_sparse,test_precision<data_type>()),std::string(\"Full Dimension Mult Test 1 for \")+typeid(data_type).name());\r\n\r\n\r\n    DenseLat3_sparse=DenseLat1*SparseLat2;\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3_dense.fuzzy_equals(DenseLat3_sparse,test_precision<data_type>()),std::string(\"Full Dimension Mult Test 2 for \")+typeid(data_type).name());\r\n\r\n    DenseLat1=denseType(1,n1,p);\n    DenseLat2=denseType(n1,1,p);\r\n    DenseLat1.randu(0,10);\r\n    DenseLat2.randu(0,10);\n    for(auto it=DenseLat1.data_begin();it<DenseLat1.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n    for(auto it=DenseLat2.data_begin();it<DenseLat2.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n\r\n    SparseLat1=DenseLat1;\r\n    SparseLat2=DenseLat2;\r\n    //std::cout << \"About to dense mult\" << std::endl;\r\n    DenseLat3_dense=DenseLat1*DenseLat2;\r\n    //std::cout << \"About to mixed mult\" << std::endl;\r\n    DenseLat3_sparse=SparseLat1*DenseLat2;\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3_dense.fuzzy_equals(DenseLat3_sparse,test_precision<data_type>()),std::string(\"Repeated Inner Product Mult Test 1 for \")+typeid(data_type).name());\r\n\r\n    DenseLat3_sparse=DenseLat1*SparseLat2;\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3_dense.fuzzy_equals(DenseLat3_sparse,test_precision<data_type>()),std::string(\"Repeated Inner Product Mult Test 2 for \")+typeid(data_type).name());\r\n\r\n    DenseLat1=denseType(m1,1,p);\n    DenseLat2=denseType(1,n2,p);\r\n    DenseLat1.randu(0,10);\r\n    DenseLat2.randu(0,10);\n    for(auto it=DenseLat1.data_begin();it<DenseLat1.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n    for(auto it=DenseLat2.data_begin();it<DenseLat2.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n\r\n    SparseLat1=DenseLat1;\r\n    SparseLat2=DenseLat2;\r\n\r\n    DenseLat3_dense=DenseLat1*DenseLat2;\r\n    DenseLat3_sparse=SparseLat1*DenseLat2;\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3_dense.fuzzy_equals(DenseLat3_sparse,test_precision<data_type>()),std::string(\"Repeated Outer Product Mult Test 1 for \")+typeid(data_type).name());\r\n\r\n    DenseLat3_sparse=DenseLat1*SparseLat2;\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3_dense.fuzzy_equals(DenseLat3_sparse,test_precision<data_type>()),std::string(\"Repeated Outer Product Mult Test 2 for \")+typeid(data_type).name());\r\n\r\n    DenseLat1=denseType(m1,n1,1);\n    DenseLat2=denseType(n1,n2,1);\r\n    DenseLat1.randu(0,10);\r\n    DenseLat2.randu(0,10);\n    for(auto it=DenseLat1.data_begin();it<DenseLat1.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n    for(auto it=DenseLat2.data_begin();it<DenseLat2.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n\r\n    SparseLat1=DenseLat1;\r\n    SparseLat2=DenseLat2;\r\n\r\n    DenseLat3_dense=DenseLat1*DenseLat2;\r\n    DenseLat3_sparse=SparseLat1*DenseLat2;\r\n    BOOST_CHECK_MESSAGE(DenseLat3_dense.fuzzy_equals(DenseLat3_sparse,test_precision<data_type>()),std::string(\"No Depth Mult Test 1 for \")+typeid(data_type).name());\r\n    DenseLat3_sparse=DenseLat1*SparseLat2;\r\n    BOOST_CHECK_MESSAGE(DenseLat3_dense.fuzzy_equals(DenseLat3_sparse,test_precision<data_type>()),std::string(\"No Depth Mult Test 2 for \")+typeid(data_type).name());\r\n\r\n\r\n\r\n    DenseLat1=denseType(m1,1,p);\n    DenseLat2=denseType(1,1,p);\r\n    DenseLat1.randu(0,10);\r\n    DenseLat2.randu(0,10);\r\n\n    for(auto it=DenseLat1.data_begin();it<DenseLat1.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n    for(auto it=DenseLat2.data_begin();it<DenseLat2.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n\r\n    SparseLat1=DenseLat1;\r\n    SparseLat2=DenseLat2;\r\n\r\n    DenseLat3_dense=DenseLat1*DenseLat2;\r\n    DenseLat3_sparse=SparseLat1*DenseLat2;\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3_dense.fuzzy_equals(DenseLat3_sparse,test_precision<data_type>()),std::string(\"Outer product, one operand, test 1 for \")+typeid(data_type).name());\r\n    DenseLat3_sparse=DenseLat1*SparseLat2;\r\n    BOOST_CHECK_MESSAGE(DenseLat3_dense.fuzzy_equals(DenseLat3_sparse,test_precision<data_type>()),std::string(\"Outer product, one operand, test 2 for \")+typeid(data_type).name());\r\n\r\n\r\n\n\n}\n\nBOOST_AUTO_TEST_CASE( SparseLatticeMultTests )\n{\n\n\n    //multwork<double>(5,5,5,5);\r\n    multwork<double>(20,20,20,20);\n    multwork<float>(20,20,20,20);\r\n    multwork<int>(20,20,20,20);\r\n    multwork<long>(20,20,20,20);\n\n\n\n}\r\n", "meta": {"hexsha": "29ee626d0bcba1981e4c9f4725dc948a1094a089", "size": 5485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/Lattice/mixedlatticemulttests.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/Lattice/mixedlatticemulttests.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/Lattice/mixedlatticemulttests.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 32.4556213018, "max_line_length": 181, "alphanum_fraction": 0.6887876026, "num_tokens": 1587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5984780912455349}}
{"text": "//=======================================================================\n// Copyright 2013 Maciej Piechotka\n// Authors: Maciej Piechotka\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 <iostream>\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/edge_coloring.hpp>\n#include <boost/graph/properties.hpp>\n\n/*\n  Sample output\n  Colored using 5 colors\n    a-d: 4\n    a-f: 0\n    b-c: 2\n    b-e: 3\n    b-g: 1\n    b-j: 0\n    c-d: 0\n    c-e: 1\n    d-f: 2\n    d-i: 1\n    e-g: 4\n    f-g: 3\n    f-h: 1\n    g-h: 0\n*/\n\nint main(int, char *[])\n{\n  using namespace boost;\n  using namespace std;\n  typedef adjacency_list<vecS, vecS, undirectedS, no_property, size_t, no_property> Graph;\n\n  typedef std::pair<std::size_t, std::size_t> Pair;\n  Pair edges[14] = { Pair(0,3), //a-d\n                     Pair(0,5),  //a-f\n                     Pair(1,2),  //b-c\n                     Pair(1,4),  //b-e\n                     Pair(1,6),  //b-g\n                     Pair(1,9),  //b-j\n                     Pair(2,3),  //c-d\n                     Pair(2,4),  //c-e\n                     Pair(3,5),  //d-f\n                     Pair(3,8),  //d-i\n                     Pair(4,6),  //e-g\n                     Pair(5,6),  //f-g\n                     Pair(5,7),  //f-h\n                     Pair(6,7) }; //g-h\n\n  Graph G(10);\n\n  for (size_t i = 0; i < sizeof(edges)/sizeof(edges[0]); i++)\n    add_edge(edges[i].first, edges[i].second, G);\n\n  size_t colors = edge_coloring(G, get(edge_bundle, G));\n\n  cout << \"Colored using \" << colors << \" colors\" << endl;\n  for (size_t i = 0; i < sizeof(edges)/sizeof(edges[0]); i++) {\n    cout << \"  \" << (char)('a' + edges[i].first) << \"-\" << (char)('a' + edges[i].second) << \": \" << G[edge(edges[i].first, edges[i].second, G).first] << endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "9c18011701d9bdcf4ade4c40f7606f735c0ba22f", "size": 1997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/edge_coloring.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/edge_coloring.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/edge_coloring.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": 28.1267605634, "max_line_length": 158, "alphanum_fraction": 0.4621932899, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5984780846544948}}
{"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": "/*\n *  Distributed under the MIT License (See accompanying file /LICENSE )\n */\n#include \"pgcpp/ck_plane.hpp\"\n#include \"pgcpp/pg_line.hpp\"\n#include \"pgcpp/pg_point.hpp\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <doctest/doctest.h>\n// #include <iostream>\n\nusing namespace fun;\n\nstatic const auto Zero = doctest::Approx(0).epsilon(0.01);\n\n/*!\n * @brief\n *\n * @param[in] a\n * @return true\n * @return false\n */\ntemplate <typename T>\ninline auto ApproxZero(const T& a) -> bool\n{\n    return a[0] == Zero && a[1] == Zero && a[2] == Zero;\n}\n\n/*!\n * @brief\n *\n * @tparam PG\n * @param[in] myck\n */\ntemplate <typename PG>\nvoid chk_tri(const PG& myck)\n{\n    using Point = typename PG::point_t;\n    using K = Value_type<Point>;\n\n    auto a1 = Point {1, 3, 1};\n    auto a2 = Point {4, 2, 1};\n    auto a3 = Point {1, 1, -1};\n\n    // auto zero = std::array<K, 3> {0, 0, 0};\n\n    const auto triangle =\n        std::tuple {std::move(a1), std::move(a2), std::move(a3)};\n    const auto trilateral = tri_dual(triangle);\n\n    const auto& [l1, l2, l3] = trilateral;\n\n    const auto Q = std::tuple {myck.tri_quadrance(triangle)};\n    const auto S = std::tuple {myck.tri_spread(trilateral)};\n\n    auto a4 = plucker(2, a1, 3, a2);\n    const auto collin =\n        std::tuple {std::move(a1), std::move(a2), std::move(a4)};\n    const auto Q2 = myck.tri_quadrance(collin);\n\n    if constexpr (Integral<K>)\n    {\n        CHECK(myck.perp(myck.perp(a1)) == a1);\n        CHECK(myck.perp(myck.perp(l1)) == l1);\n        CHECK(myck.perp(myck.perp(l2)) == l2);\n        CHECK(myck.perp(myck.perp(l3)) == l3);\n        CHECK(check_cross_law(S, std::get<2>(Q)) == 0);\n        CHECK(check_cross_law(Q, std::get<2>(S)) == 0);\n        CHECK(check_cross_TQF(Q2) == 0);\n    }\n    else\n    {\n        CHECK(ApproxZero(cross(myck.perp(myck.perp(a1)), a1)));\n        CHECK(ApproxZero(cross(myck.perp(myck.perp(l1)), l1)));\n        CHECK(ApproxZero(cross(myck.perp(myck.perp(l2)), l2)));\n        CHECK(ApproxZero(cross(myck.perp(myck.perp(l3)), l3)));\n        CHECK(check_cross_law(S, std::get<2>(Q)) == Zero);\n        CHECK(check_cross_law(Q, std::get<2>(S)) == Zero);\n        CHECK(check_cross_TQF(Q2) == Zero);\n    }\n}\n\nTEST_CASE(\"Elliptic/Hyperbolic plane\")\n{\n    using boost::multiprecision::cpp_int;\n\n    chk_tri(ellck<pg_point<cpp_int>>());\n    chk_tri(ellck<pg_line<cpp_int>>());\n    chk_tri(hyck<pg_point<cpp_int>>());\n    chk_tri(hyck<pg_line<cpp_int>>());\n}\n\nTEST_CASE(\"Elliptic/Hyperbolic plane (double)\")\n{\n    chk_tri(ellck<pg_point<double>>());\n    chk_tri(ellck<pg_line<double>>());\n    chk_tri(hyck<pg_point<double>>());\n    chk_tri(hyck<pg_line<double>>());\n}\n", "meta": {"hexsha": "ce33ca2274bafed9461fb3bd99f2354cd4c56286", "size": 2635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/test/src/test_ell_plane.cpp", "max_stars_repo_name": "luk036/pgcpp", "max_stars_repo_head_hexsha": "acef09303ebaa1334b5d30b727d975495e488d4f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-21T09:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:08:51.000Z", "max_issues_repo_path": "lib/test/src/test_ell_plane.cpp", "max_issues_repo_name": "luk036/pgcpp", "max_issues_repo_head_hexsha": "acef09303ebaa1334b5d30b727d975495e488d4f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-25T11:01:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T13:23:34.000Z", "max_forks_repo_path": "lib/test/src/test_ell_plane.cpp", "max_forks_repo_name": "luk036/pgcpp", "max_forks_repo_head_hexsha": "acef09303ebaa1334b5d30b727d975495e488d4f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-06-03T08:58:05.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-03T08:58:05.000Z", "avg_line_length": 26.6161616162, "max_line_length": 71, "alphanum_fraction": 0.6075901328, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5983862209447716}}
{"text": "/**\n * @file radical_main.cpp\n * @author Nishant Mehta\n *\n * Test for RADICAL.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/radical/radical.hpp>\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nBOOST_AUTO_TEST_SUITE(RadicalTest);\n\nusing namespace mlpack;\nusing namespace mlpack::radical;\nusing namespace std;\nusing namespace arma;\n\nBOOST_AUTO_TEST_CASE(Radical_Test_Radical3D)\n{\n  mat matX;\n  data::Load(\"data_3d_mixed.txt\", matX);\n\n  Radical rad(0.175, 5, 100, matX.n_rows - 1);\n\n  mat matY;\n  mat matW;\n  rad.DoRadical(matX, matY, matW);\n\n  mat matYT = trans(matY);\n  double valEst = 0;\n\n  for (uword i = 0; i < matYT.n_cols; i++)\n  {\n    vec y = vec(matYT.col(i));\n    valEst += rad.Vasicek(y);\n  }\n\n  mat matS;\n  data::Load(\"data_3d_ind.txt\", matS);\n  rad.DoRadical(matS, matY, matW);\n\n  matYT = trans(matY);\n  double valBest = 0;\n\n  for (uword i = 0; i < matYT.n_cols; i++)\n  {\n    vec y = vec(matYT.col(i));\n    valBest += rad.Vasicek(y);\n  }\n\n  BOOST_REQUIRE_CLOSE(valBest, valEst, 0.25);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "c14f449ae7e05f6b286382d6ed33be2d0009ef61", "size": 1053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/radical_test.cpp", "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:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:16.000Z", "max_issues_repo_path": "src/mlpack/tests/radical_test.cpp", "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/tests/radical_test.cpp", "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": 18.8035714286, "max_line_length": 46, "alphanum_fraction": 0.6666666667, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5983862051907226}}
{"text": "#include \"gtest/gtest.h\"\n\n#include <iostream>\n\n#include <Eigen/Dense>\n\nnamespace {\n\nTEST(memstream, read_write)\n{\n    Eigen::Matrix<float, 4, 4> mat1;\n    Eigen::Matrix<float, 4, 4> mat2;\n    mat1.setConstant(2.0f);\n    mat2.setConstant(4.0f);\n    mat2(8) = 7.0f;\n\n    Eigen::Matrix<float, 4, 4> mat3 = mat1 - mat2;\n    float sum = mat3.sum();\n\n    std::cout << std::endl;\n    std::cout << mat1 << std::endl;\n    std::cout << std::endl;\n    std::cout << mat2 << std::endl;\n    std::cout << std::endl;\n    std::cout << mat3 << std::endl;\n    std::cout << std::endl;\n    std::cout << sum << std::endl;\n\n    std::cout << std::log2(256) + 1 << std::endl;\n\n    SUCCEED();\n}\n\n}\n\n", "meta": {"hexsha": "41fc1a623b8cea0ea1abf95f72945dfd075ff5b5", "size": 673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/UTest/debug/UTest_euclidianDistance.cpp", "max_stars_repo_name": "Shenmue-Mods/ShenmueDK", "max_stars_repo_head_hexsha": "feca9c937fe5cf6fb99b11336792f33d9797aca7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-27T21:15:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T10:42:30.000Z", "max_issues_repo_path": "tests/UTest/debug/UTest_euclidianDistance.cpp", "max_issues_repo_name": "Shenmue-Mods/ShenmueDK", "max_issues_repo_head_hexsha": "feca9c937fe5cf6fb99b11336792f33d9797aca7", "max_issues_repo_licenses": ["MIT"], "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/UTest/debug/UTest_euclidianDistance.cpp", "max_forks_repo_name": "Shenmue-Mods/ShenmueDK", "max_forks_repo_head_hexsha": "feca9c937fe5cf6fb99b11336792f33d9797aca7", "max_forks_repo_licenses": ["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.6944444444, "max_line_length": 50, "alphanum_fraction": 0.5557206538, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5983862041430997}}
{"text": "/* boost random/student_t_distribution.hpp header file\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * See http://www.boost.org for most recent version including documentation.\r\n *\r\n * $Id$\r\n */\r\n\r\n#ifndef BOOST_RANDOM_STUDENT_T_DISTRIBUTION_HPP\r\n#define BOOST_RANDOM_STUDENT_T_DISTRIBUTION_HPP\r\n\r\n#include <boost/config/no_tr1/cmath.hpp>\r\n#include <iosfwd>\r\n#include <boost/config.hpp>\r\n#include <boost/limits.hpp>\r\n#include <boost/random/detail/operators.hpp>\r\n#include <boost/random/chi_squared_distribution.hpp>\r\n#include <boost/random/normal_distribution.hpp>\r\n\r\nnamespace boost {\r\nnamespace random {\r\n\r\n/**\r\n * The Student t distribution is a real valued distribution with one\r\n * parameter n, the number of degrees of freedom.\r\n *\r\n * It has \\f$\\displaystyle p(x) =\r\n *   \\frac{1}{\\sqrt{n\\pi}}\r\n *   \\frac{\\Gamma((n+1)/2)}{\\Gamma(n/2)}\r\n *   \\left(1+\\frac{x^2}{n}\\right)^{-(n+1)/2}\r\n * \\f$.\r\n */\r\ntemplate<class RealType = double>\r\nclass student_t_distribution {\r\npublic:\r\n    typedef RealType result_type;\r\n    typedef RealType input_type;\r\n\r\n    class param_type {\r\n    public:\r\n        typedef student_t_distribution distribution_type;\r\n\r\n        /**\r\n         * Constructs a @c param_type with \"n\" degrees of freedom.\r\n         *\r\n         * Requires: n > 0\r\n         */\r\n        explicit param_type(RealType n_arg = RealType(1.0))\r\n          : _n(n_arg)\r\n        {}\r\n\r\n        /** Returns the number of degrees of freedom of the distribution. */\r\n        RealType n() const { return _n; }\r\n\r\n        /** Writes a @c param_type to a @c std::ostream. */\r\n        BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm)\r\n        { os << parm._n; return os; }\r\n\r\n        /** Reads a @c param_type from a @c std::istream. */\r\n        BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm)\r\n        { is >> parm._n; return is; }\r\n\r\n        /** Returns true if the two sets of parameters are the same. */\r\n        BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs)\r\n        { return lhs._n == rhs._n; }\r\n        \r\n        /** Returns true if the two sets of parameters are the different. */\r\n        BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type)\r\n\r\n    private:\r\n        RealType _n;\r\n    };\r\n\r\n    /**\r\n     * Constructs an @c student_t_distribution with \"n\" degrees of freedom.\r\n     *\r\n     * Requires: n > 0\r\n     */\r\n    explicit student_t_distribution(RealType n_arg = RealType(1.0))\r\n      : _normal(), _chi_squared(n_arg)\r\n    {}\r\n    /** Constructs an @c student_t_distribution from its parameters. */\r\n    explicit student_t_distribution(const param_type& parm)\r\n      : _normal(), _chi_squared(parm.n())\r\n    {}\r\n\r\n    /**\r\n     * Returns a random variate distributed according to the\r\n     * Student t distribution.\r\n     */\r\n    template<class URNG>\r\n    RealType operator()(URNG& urng)\r\n    {\r\n        using std::sqrt;\r\n        return _normal(urng) / sqrt(_chi_squared(urng) / n());\r\n    }\r\n\r\n    /**\r\n     * Returns a random variate distributed accordint to the Student\r\n     * t distribution with parameters specified by @c param.\r\n     */\r\n    template<class URNG>\r\n    RealType operator()(URNG& urng, const param_type& parm) const\r\n    {\r\n        return student_t_distribution(parm)(urng);\r\n    }\r\n\r\n    /** Returns the number of degrees of freedom. */\r\n    RealType n() const { return _chi_squared.n(); }\r\n\r\n    /** Returns the smallest value that the distribution can produce. */\r\n    RealType min BOOST_PREVENT_MACRO_SUBSTITUTION () const\r\n    { return -std::numeric_limits<RealType>::infinity(); }\r\n    /** Returns the largest value that the distribution can produce. */\r\n    RealType max BOOST_PREVENT_MACRO_SUBSTITUTION () const\r\n    { return std::numeric_limits<RealType>::infinity(); }\r\n\r\n    /** Returns the parameters of the distribution. */\r\n    param_type param() const { return param_type(n()); }\r\n    /** Sets the parameters of the distribution. */\r\n    void param(const param_type& parm)\r\n    {\r\n        typedef chi_squared_distribution<RealType> chi_squared_type;\r\n        typename chi_squared_type::param_type chi_squared_param(parm.n());\r\n        _chi_squared.param(chi_squared_param);\r\n    }\r\n\r\n    /**\r\n     * Effects: Subsequent uses of the distribution do not depend\r\n     * on values produced by any engine prior to invoking reset.\r\n     */\r\n    void reset()\r\n    {\r\n        _normal.reset();\r\n        _chi_squared.reset();\r\n    }\r\n\r\n    /** Writes a @c student_t_distribution to a @c std::ostream. */\r\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, student_t_distribution, td)\r\n    {\r\n        os << td.param();\r\n        return os;\r\n    }\r\n\r\n    /** Reads a @c student_t_distribution from a @c std::istream. */\r\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, student_t_distribution, td)\r\n    {\r\n        param_type parm;\r\n        if(is >> parm) {\r\n            td.param(parm);\r\n        }\r\n        return is;\r\n    }\r\n\r\n    /**\r\n     * Returns true if the two instances of @c student_t_distribution will\r\n     * return identical sequences of values given equal generators.\r\n     */\r\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(student_t_distribution, lhs, rhs)\r\n    { return lhs._normal == rhs._normal && lhs._chi_squared == rhs._chi_squared; }\r\n    \r\n    /**\r\n     * Returns true if the two instances of @c student_t_distribution will\r\n     * return different sequences of values given equal generators.\r\n     */\r\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(student_t_distribution)\r\n\r\nprivate:\r\n    normal_distribution<RealType> _normal;\r\n    chi_squared_distribution<RealType> _chi_squared;\r\n};\r\n\r\n} // namespace random\r\n} // namespace boost\r\n\r\n#endif // BOOST_RANDOM_STUDENT_T_DISTRIBUTION_HPP\r\n", "meta": {"hexsha": "414613b6de3e437f5b02353bad8a08bdcaeb4a49", "size": 5813, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/random/student_t_distribution.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/random/student_t_distribution.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/random/student_t_distribution.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 32.1160220994, "max_line_length": 83, "alphanum_fraction": 0.6430414588, "num_tokens": 1310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5983861950372308}}
{"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;          // \u786e\u5b9a\u7cfb\u6570\n\tlong p = 2147483647; // \u6a21\u91cf(\u7d20\u6570)\uff0c\u5b9a\u4e49\u8d85\u8fc7p/2\u7684\u6570\u4e3a\u8d1f\u6570\uff0c\u8d1f\u6570\u7684\u771f\u503cx=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// \u751f\u6210\u516c\u94a5\n\tFHESecKey secretKey(context);\n\tconst FHEPubKey& publicKey = secretKey;\n\tsecretKey.GenSecKey(w);\n\n\t// \u521d\u59cb\u5316\u5bc6\u6587\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 ||\u2207F(x)|| > \u03b5\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": "#include <bits/stdc++.h>\n#include <boost/optional.hpp>\nusing namespace std;\n\n/**\n * http://tsutaj.hatenablog.com/entry/2017/03/29/204841\n */\ntemplate<typename T>\nclass SegmentTree {\n private:\n  vector<T> nodes;\n  unsigned long long size;\n  function<T(T, T)> fn;\n\n public:\n  explicit SegmentTree(\n      unsigned long long size,\n      function<T(T, T)> fn = [](T a, T b) { return a + b; },\n      T initial = 0) {\n    // size \u4ee5\u4e0a\u306e\u6700\u5c0f\u306e2\u3079\u304d\n    long long sz = 1;\n    while (sz <= size) sz <<= 1;\n    this->size = sz;\n\n    // root \u304c 1\n    // i \u756a\u76ee\u306e\u8981\u7d20\u304c size + i \u306b\u3042\u308b\n    this->nodes = vector<T>(this->size * 2, initial);\n    this->fn = fn;\n  }\n\n  /**\n   * [from_i, to_i) \u306b fn \u3092\u9069\u7528\u3057\u305f\u7d50\u679c\n   * @param from_i\n   * @param to_i\n   * @param k\n   */\n  boost::optional<T> get(\n      unsigned long long from_i,\n      unsigned long long to_i,\n      unsigned long long k = 1,\n      long long l = 0,\n      long long r = -1) {\n    if (r < 0) r = size;\n\n    // \u88ab\u8986\u3057\u3066\u308b\n    if (from_i <= l && r <= to_i) return nodes[k];\n    // \u95a2\u4fc2\u306a\u3044\n    if (r <= from_i || to_i <= l) return boost::none;\n\n    // \u5b50\u304b\u3089\u3082\u3089\u3046\n    boost::optional<T> left = get(from_i, to_i, k * 2, l, (l + r) / 2);\n    boost::optional<T> right = get(from_i, to_i, k * 2 + 1, (l + r) / 2, r);\n\n    if (left && right) return fn(*left, *right);\n    if (left) return *left;\n    if (right) return *right;\n    return boost::none;\n  }\n\n  /**\n   * i \u3092 value \u3067\u66f4\u65b0\u3059\u308b\n   * @param i\n   * @param value\n   */\n  void set(unsigned long long i, T value) {\n    long long k = size + i;\n\n    nodes[k] = value;\n    k /= 2;\n    while (k > 0) {\n      nodes[k] = fn(nodes[k * 2], nodes[k * 2 + 1]);\n      k /= 2;\n    }\n  }\n\n  /**\n   * \u3082\u3068\u306e i \u756a\u76ee\u3068 value \u306b fn \u3092\u9069\u7528\u3057\u305f\u3082\u306e\u3092 i \u756a\u76ee\u306b\u8a2d\u5b9a\u3059\u308b\n   * @param i\n   * @param value\n   */\n  void add(unsigned long long i, T value) {\n    long long k = size + i;\n    set(i, fn(nodes[k], value));\n  }\n};\n", "meta": {"hexsha": "7d7261b3aba0bf7d7ce72638ce7389e04b5cc2d7", "size": 1827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "segment_tree.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": "segment_tree.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": "segment_tree.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": 21.2441860465, "max_line_length": 76, "alphanum_fraction": 0.5314723591, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5983448985268712}}
{"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 \"edlib/edlib.hpp\"\n\n#include <Eigen/Dense>\n\n#include <fstream>\n#include <ios>\n#include <iostream>\n#include <random>\n\nint main()\n{\n    using namespace edlib;\n    using UINT = uint32_t;\n\n    constexpr int N = 20;\n\n    std::cout << \"#N: \" << N << std::endl;\n\n    std::vector<double> hs;\n    for(int i = 0; i <= 20; i++)\n    {\n        hs.emplace_back(i * 0.1);\n    }\n    for(auto h : hs)\n    {\n        std::array<Eigen::VectorXd, 2> ev;\n        {\n            Basis1DZ2<UINT> basis(N, 0, 1, false);\n            TITFIsing<UINT> ham(basis, 1.0, h);\n            const int dim = basis.getDim();\n\n            NodeMV mv(dim, 0, dim, ham);\n            auto solver = ArpackSolver(mv, dim);\n\n            if(solver.solve(2) != ErrorType::NormalExit)\n            {\n                return 1;\n            }\n            ev[0] = solver.eigenvalues();\n        }\n        {\n            Basis1DZ2<UINT> basis(N, 0, -1, false);\n            TITFIsing<UINT> ham(basis, 1.0, h);\n            const int dim = basis.getDim();\n\n            NodeMV mv(dim, 0, dim, ham);\n            auto solver = ArpackSolver(mv, dim);\n\n            if(solver.solve(2) != ErrorType::NormalExit)\n            {\n                return 1;\n            }\n            ev[1] = solver.eigenvalues();\n        }\n        printf(\"%f\\t%.10f\\t%.10f\\t%.10f\\t%.10f\\n\", h, ev[0](0), ev[0](1), ev[1](0), ev[1](1));\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "f65333b91d73ee4f9fc1b28b50d084b76349a42e", "size": 1376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tfi_arpack.cpp", "max_stars_repo_name": "cecri/ExactDiagonalization", "max_stars_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/tfi_arpack.cpp", "max_issues_repo_name": "cecri/ExactDiagonalization", "max_issues_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tfi_arpack.cpp", "max_forks_repo_name": "cecri/ExactDiagonalization", "max_forks_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9333333333, "max_line_length": 94, "alphanum_fraction": 0.46875, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5982901489013703}}
{"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 <random>\n#include <benchmark/benchmark.h>\n#include <boost/math/special_functions/rsqrt.hpp>\n#include <boost/multiprecision/float128.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\nusing boost::multiprecision::number;\nusing boost::multiprecision::mpfr_float_backend;\nusing boost::multiprecision::float128;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::math::rsqrt;\n\ntemplate<class Real>\nvoid Rsqrt(benchmark::State& state)\n{\n    std::random_device rd;\n    std::mt19937_64 mt(rd());\n    std::uniform_real_distribution<long double> unif(1,100);\n\n    Real x = static_cast<Real>(unif(mt));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(rsqrt(x));\n        x += std::numeric_limits<Real>::epsilon();\n    }\n}\n\nBENCHMARK_TEMPLATE(Rsqrt, float);\nBENCHMARK_TEMPLATE(Rsqrt, double);\nBENCHMARK_TEMPLATE(Rsqrt, long double);\nBENCHMARK_TEMPLATE(Rsqrt, float128);\nBENCHMARK_TEMPLATE(Rsqrt, number<mpfr_float_backend<100>>);\nBENCHMARK_TEMPLATE(Rsqrt, number<mpfr_float_backend<200>>);\nBENCHMARK_TEMPLATE(Rsqrt, number<mpfr_float_backend<300>>);\nBENCHMARK_TEMPLATE(Rsqrt, number<mpfr_float_backend<400>>);\nBENCHMARK_TEMPLATE(Rsqrt, number<mpfr_float_backend<1000>>);\nBENCHMARK_TEMPLATE(Rsqrt, cpp_bin_float_50);\nBENCHMARK_TEMPLATE(Rsqrt, cpp_bin_float_100);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "4f797f7a615469c2046dbc576a9c98cce67ea55a", "size": 1627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reporting/performance/rsqrt_performance.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": "reporting/performance/rsqrt_performance.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/reporting/performance/rsqrt_performance.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 33.8958333333, "max_line_length": 68, "alphanum_fraction": 0.7701290719, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5982901380589791}}
{"text": "//\n//  cal_M.hpp\n//  hybrid_fem_bie\n//\n//  Created by Max on 2/10/18.\n//\n//\n\n#ifndef cal_M_hpp\n#define cal_M_hpp\n\n#include <stdio.h>\n#include <Eigen/Eigen>\n#include <Eigen/KroneckerProduct>\n\nusing namespace Eigen;\nvoid cal_M(MatrixXd coord, double density, MatrixXd &M_el);\n\n\n#endif /* cal_M_hpp */\n", "meta": {"hexsha": "447e52578afb35687015764230aa3dd407586987", "size": 299, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fem/cal_M.hpp", "max_stars_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_stars_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "src/fem/cal_M.hpp", "max_issues_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_issues_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fem/cal_M.hpp", "max_forks_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_forks_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 14.2380952381, "max_line_length": 59, "alphanum_fraction": 0.6989966555, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5982901334711489}}
{"text": "///////////////////////////////////////////////////////////////\r\n//  Copyright 2013 Christopher Kormanyos. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\r\n//\r\n\r\n// Test case for ticket:\r\n// #8065: Multiprecision rounding issue\r\n\r\n#ifdef _MSC_VER\r\n#  define _SCL_SECURE_NO_WARNINGS\r\n#endif\r\n\r\n#include <boost/detail/lightweight_test.hpp>\r\n#include \"test.hpp\"\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\n#include <boost/math/special_functions/round.hpp>\r\n\r\ntemplate<int N>\r\nstatic bool round_test_imp()\r\n{\r\n  typedef boost::multiprecision::cpp_dec_float<N> mp_backend_type;\r\n  typedef boost::multiprecision::number<mp_backend_type, boost::multiprecision::et_off> mp_type;\r\n\r\n  const mp_type original_digits(1.0F);\r\n\r\n  const mp_type scale = pow(mp_type(10), N);\r\n\r\n  mp_type these_digits = original_digits * scale;\r\n\r\n  these_digits  = boost::math::round(these_digits);\r\n  these_digits /= scale;\r\n\r\n  const std::string result = these_digits.str();\r\n\r\n  return (result == original_digits.str());\r\n}\r\n\r\ntemplate<int N>\r\nstruct round_test\r\n{\r\n  static bool test()\r\n  {\r\n    return (round_test_imp<N>() && round_test<N - 1>::test());\r\n  }\r\n};\r\n\r\ntemplate<>\r\nstruct round_test<0>\r\n{\r\n  static bool test()\r\n  {\r\n    return round_test_imp<0>();\r\n  }\r\n};\r\n\r\nint main()\r\n{\r\n   //\r\n   // Test cpp_dec_float rounding with boost::math::round() at various precisions:\r\n   //\r\n   const bool round_test_result = round_test<40>::test();\r\n\r\n   BOOST_CHECK_EQUAL(round_test_result, true);\r\n\r\n   return boost::report_errors();\r\n}\r\n", "meta": {"hexsha": "a60f616df3fbdb192598c83eed2b7a0c43262b34", "size": 1622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/multiprecision/test/test_cpp_dec_float_round.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/multiprecision/test/test_cpp_dec_float_round.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/multiprecision/test/test_cpp_dec_float_round.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 23.8529411765, "max_line_length": 97, "alphanum_fraction": 0.6639950678, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7217432182679957, "lm_q1q2_score": 0.5982809693652331}}
{"text": "/*\n    Boost Competency Test - GSoC 2020\n    digu_J - Digvijay Janartha\n    NIT Hamirpur - INDIA\n*/\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <utility>\n#include <vector>\n#include <random>\n#include <chrono>\n\n#include <boost/geometry/geometry.hpp>\n\n#include \"../includes/convex_hull_gift_wrapping.hpp\"\n\nnamespace bg = boost::geometry;\nusing bg::dsv;\n\ntypedef bg::model::point<double, 2, bg::cs::cartesian> point_t;\ntypedef bg::model::multi_point<point_t> mpoint_t;\ntypedef bg::model::polygon<point_t> polygon_t;\n\nstd::mt19937_64 rang(std::chrono::high_resolution_clock::now().time_since_epoch().count());\n\nint my_rand(int l, int r)\n{\n    if (l > r)\n    {\n        std::swap(l, r);\n    }\n\tstd::uniform_int_distribution <int> uid(l, r);\n\treturn uid(rang);\n}\n\nbool test(mpoint_t &hull1, mpoint_t &hull2)\n{   \n    // Checks if the convex hull generated by gift wrapping is the same as the convex hull generated by boost geometry.\n    polygon_t p1, p2;\n    for (int i = 0; i < boost::size(hull1); ++i)\n    {\n        bg::append(p1, hull1[i]);\n    }\n    for (int i = int(boost::size(hull2)) - 1; i >= 0; --i)\n    {\n        bg::append(p2, hull2[i]);\n    }\n    if (bg::covered_by(p1, p2) and bg::covered_by(p2, p1)) // both geometries must cover themselves to be same\n    {\n        return true;\n    }\n    std::cout << dsv(p1) << \"\\n\";\n    std::cout << dsv(p2) << \"\\n\";\n    return false;\n}\n\nint main()\n{\n    std::cout << std::fixed << std::setprecision(0);\n    #ifdef HOME\n        freopen(\"input.txt\", \"r\", stdin);\n        freopen(\"output.txt\", \"w\", stdout);\n    #endif\n\n    for (int tt = 1; tt <= 500; ++tt) // 500 random test cases\n    {\n        mpoint_t mpt1, hull1, hull2;\n\n        int points = 30;\n        for (int i = 0; i < points; ++i)\n        {\n            int x = my_rand(0, 100);\n            int y = my_rand(0, 100);\n            bg::append(mpt1, point_t(x, y));\n        }\n\n        algo1::GiftWrapping(mpt1, hull1);\n        bg::convex_hull(mpt1, hull2);\n        assert(test(hull1, hull2) == true);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "93ceda5dba8b66e572e8954516dbd13dcedea359", "size": 2047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/convex_hull.cpp", "max_stars_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_stars_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/convex_hull.cpp", "max_issues_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_issues_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/convex_hull.cpp", "max_forks_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_forks_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8023255814, "max_line_length": 119, "alphanum_fraction": 0.5872007816, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.598280969365233}}
{"text": "#pragma once\n\n#include \"Rational.hpp\"\n\n#include <Eigen/Core>\n\nnamespace eccd\n{\n\ntypedef Eigen::Matrix<Rational, 3, 1> Vector3r;\ntypedef Eigen::Matrix<double, 3, 1> Vector3d;\n\ntemplate <typename V1, typename V2>\nVector3r cross(const V1 &v1, const V2 &v2)\n{\n    Vector3r res;\n    res[0] = v1[1] * v2[2] - v1[2] * v2[1];\n    res[1] = v1[2] * v2[0] - v1[0] * v2[2];\n    res[2] = v1[0] * v2[1] - v1[1] * v2[0];\n\n    return res;\n}\n\ntemplate<typename V>\nvoid print(const V &v)\n{\n    std::cout << v[0] << \" \" << v[1] << \" \" << v[2] << std::endl;\n}\n\nvoid write(const Vector3d &v, std::ostream &out);\nVector3d read(std::istream &in);\n\nint orient3d(const Vector3r &a, const Vector3r &b, const Vector3r &c, const Vector3r &d);\n\nint origin_ray_triangle_inter(const Vector3d &dir, const Vector3r &t1, const Vector3r &t2, const Vector3r &t3);\n\nbool segment_segment_inter(const Vector3r &s0, const Vector3r &e0, const Vector3r &s1, const Vector3r &e1, Vector3r &res, int axis);\n\nint segment_triangle_inter(const Vector3d &e0, const Vector3d &e1, const Vector3d &t1, const Vector3d &t2, const Vector3d &t3);\n\n} // namespace eccd\n", "meta": {"hexsha": "671176ea68140a3a35068bafa273a093b204a8b5", "size": 1112, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils.hpp", "max_stars_repo_name": "Continous-Collision-Detection/Rational-Root-Parity", "max_stars_repo_head_hexsha": "812f8cc6bdd6768b4a70291f411581c3544bb227", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-12T06:15:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-11T15:56:04.000Z", "max_issues_repo_path": "src/Utils.hpp", "max_issues_repo_name": "Continuous-Collision-Detection/Rational-Root-Parity", "max_issues_repo_head_hexsha": "812f8cc6bdd6768b4a70291f411581c3544bb227", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils.hpp", "max_forks_repo_name": "Continuous-Collision-Detection/Rational-Root-Parity", "max_forks_repo_head_hexsha": "812f8cc6bdd6768b4a70291f411581c3544bb227", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-11T15:45:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-28T06:06:01.000Z", "avg_line_length": 26.4761904762, "max_line_length": 132, "alphanum_fraction": 0.6645683453, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5982809644038696}}
{"text": "//\n//  rsaUtil.hpp\n//  kcalg\n//\n//  Created by knightc on 2019/8/8.\n//  Copyright \u00a9 2019 knightc. All rights reserved.\n//\n\n#ifndef rsaUtil_hpp\n#define rsaUtil_hpp\n\n#include <NTL/ZZ.h>\n\nusing namespace NTL;\nusing namespace std;\n\nvoid oula(const ZZ p , const ZZ q , ZZ &n );\n\n\n#endif /* rsaUtil_hpp */\n", "meta": {"hexsha": "0cc0e5cec3147ba3157d3365887b076e40be135e", "size": 300, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kcalg/sec/rsa/rsaUtil.hpp", "max_stars_repo_name": "kn1ghtc/kctsb", "max_stars_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-16T00:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T00:10:51.000Z", "max_issues_repo_path": "kcalg/sec/rsa/rsaUtil.hpp", "max_issues_repo_name": "kn1ghtc/kctsb", "max_issues_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kcalg/sec/rsa/rsaUtil.hpp", "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": 14.2857142857, "max_line_length": 50, "alphanum_fraction": 0.6666666667, "num_tokens": 91, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5982809594425058}}
{"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_DEGINRAD_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_DEGINRAD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Constant radian in Degree multiplier, \\f$\\frac{180}\\pi\\f$.\n\n\n    @par Header <boost/simd/constant/deginrad.hpp>\n\n    @par Semantic:\n\n    For type T:\n\n    @code\n    T r = Deginrad<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = Ratio<T, 180>()/Pi<T>() ;\n    @endcode\n\n    @see  inrad, indeg, Radindeg, Radindegr, Ratio\n    @return a value of type T\n\n**/\n  template<typename T> T Deginrad();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Constant radian in Degree multiplier, \\f$\\frac{180}\\pi\\f$.\n\n      Generate the  constant deginrad.\n\n      @return The Deginrad constant for the proper type\n    **/\n    Value Deginrad();\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/deginrad.hpp>\n#include <boost/simd/constant/simd/deginrad.hpp>\n\n#endif\n", "meta": {"hexsha": "0df42ab15d7f6d8eaec753fd80afd58b8cbe8241", "size": 1389, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/deginrad.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/deginrad.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/deginrad.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 20.7313432836, "max_line_length": 100, "alphanum_fraction": 0.5745140389, "num_tokens": 335, "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": "#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": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_SDK_MEMORY_META_NEXT_POWER_OF_2_HPP_INCLUDED\n#define BOOST_SIMD_SDK_MEMORY_META_NEXT_POWER_OF_2_HPP_INCLUDED\n\n#include <cstddef>\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/integral_c.hpp>\n\nnamespace boost { namespace simd { namespace meta\n{\n  //////////////////////////////////////////////////////////////////////////////\n  // Integral meta-function computing the power of 2 less or equal to any\n  // integral constant.\n  // Documentation: next_power_of_2_c.rst\n  //////////////////////////////////////////////////////////////////////////////\n  template<std::size_t N>\n  struct prev_power_of_2_c\n  {\n    BOOST_STATIC_CONSTANT(std::size_t, x0    = N               );\n    BOOST_STATIC_CONSTANT(std::size_t, x1    = x0 | (x0 >>  1) );\n    BOOST_STATIC_CONSTANT(std::size_t, x2    = x1 | (x1 >>  2) );\n    BOOST_STATIC_CONSTANT(std::size_t, x3    = x2 | (x2 >>  4) );\n    BOOST_STATIC_CONSTANT(std::size_t, x4    = x3 | (x3 >>  8) );\n    BOOST_STATIC_CONSTANT(std::size_t, x5    = x4 | (x4 >> 16) );\n    BOOST_STATIC_CONSTANT(std::size_t, value = (x5 >> 1) + 1   );\n    typedef boost::mpl::size_t<value> type;\n  };\n  template<std::size_t N>\n  std::size_t const prev_power_of_2_c<N>::value;\n\n  //////////////////////////////////////////////////////////////////////////////\n  // Integral meta-function computing the power of 2 less or equal to any\n  // Integral Constant.\n  // Documentation: next_power_of_2.rst\n  //////////////////////////////////////////////////////////////////////////////\n  template<class N>\n  struct  prev_power_of_2\n        : boost::mpl::integral_c< typename N::value_type\n                                , prev_power_of_2_c<N::value>::value\n                                > {};\n\n  //////////////////////////////////////////////////////////////////////////////\n  // Integral meta-function computing the power of 2 greater or equal to any\n  // integral constant.\n  // Documentation: next_power_of_2_c.rst\n  //////////////////////////////////////////////////////////////////////////////\n  template<std::size_t N>\n  struct next_power_of_2_c\n  {\n    BOOST_STATIC_CONSTANT(std::size_t, x0    = N-1             );\n    BOOST_STATIC_CONSTANT(std::size_t, x1    = x0 | (x0 >>  1) );\n    BOOST_STATIC_CONSTANT(std::size_t, x2    = x1 | (x1 >>  2) );\n    BOOST_STATIC_CONSTANT(std::size_t, x3    = x2 | (x2 >>  4) );\n    BOOST_STATIC_CONSTANT(std::size_t, x4    = x3 | (x3 >>  8) );\n    BOOST_STATIC_CONSTANT(std::size_t, x5    = x4 | (x4 >> 16) );\n    BOOST_STATIC_CONSTANT(std::size_t, value = x5 + 1          );\n    typedef boost::mpl::size_t<value> type;\n  };\n\n  // MSVC warning fix\n  template<> struct next_power_of_2_c<0> : boost::mpl::size_t<0> {};\n\n  template<std::size_t N>\n  std::size_t const next_power_of_2_c<N>::value;\n\n  //////////////////////////////////////////////////////////////////////////////\n  // Integral meta-function computing the power of 2 greater or equal to any\n  // Integral Constant.\n  // Documentation: next_power_of_2.rst\n  //////////////////////////////////////////////////////////////////////////////\n  template<class N>\n  struct  next_power_of_2\n        : boost::mpl::integral_c< typename N::value_type\n                                , next_power_of_2_c<N::value>::value\n                                > {};\n} } }\n\n\n#endif\n", "meta": {"hexsha": "224b2ca886342b6d181e07b7d403b798bec96175", "size": 3804, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/include/boost/simd/sdk/memory/meta/next_power_of_2.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/sdk/include/boost/simd/sdk/memory/meta/next_power_of_2.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/sdk/include/boost/simd/sdk/memory/meta/next_power_of_2.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.724137931, "max_line_length": 80, "alphanum_fraction": 0.497108307, "num_tokens": 903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387956435734, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.598280944192262}}
{"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": "//////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::example::random2.cpp                               //\n//                                                                          //\n//  (C) Copyright 2009 Erwann Rogard                                        //\n//  Use, modification and distribution are subject to the                   //\n//  Boost Software License, Version 1.0. (See accompanying file             //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)        //\n//////////////////////////////////////////////////////////////////////////////\n#include <boost/typeof/typeof.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/chi_squared/include.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/exponential/include.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/gamma/include.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/normal/include.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/poisson/include.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/students_t/include.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/location_scale/include.hpp>\n#include <boost/statistics/detail/distribution_common/distributions/reference/include.hpp>\n#include <boost/statistics/detail/distribution_common/meta/random/generator.hpp>\n#include <boost/statistics/detail/non_parametric/kolmogorov_smirnov/check_convergence.hpp>\n\n#include <libs/statistics/detail/distribution_toolkit/example/random.h>\n\nvoid example_random(std::ostream& os)\n{\n    // Checks convergence of sample generated by make_random_generator(urng,d)\n    // to distribution b, by the kolmogorov-smirnov\n\n    os << \"-> test_random2 \" << std::endl;\n\n\tnamespace ks = boost::statistics::detail::kolmogorov_smirnov;\n\n    using namespace boost;\n    using namespace boost::statistics;\n    namespace stat = statistics::detail;\n\tnamespace dist = stat::distribution;\n\ttypedef int int_;\n    typedef double val_;\n\ttypedef boost::mt19937 urng_;\n\ttypedef ks::check_convergence<val_> check_;\n\n    const unsigned n_loops = 6;\n    const unsigned n1 = 1e1;\n    const unsigned n2 = 1e1;\n    \t\n    urng_ urng;\n    check_ check;\n    \n    {\n        typedef math::chi_squared_distribution<val_> dist_;\n        const val_ df = 10;\n        dist_ d( df );\n        os << d << std::endl;\n        BOOST_AUTO(\n        \tvg,\n            dist::make_random_generator(urng,d)\n        );\n        check(n_loops,n1,n2,d,vg,os);\n    }\n    {\n        typedef math::exponential_distribution<val_>     dist_;\n        const val_ lambda = 1.0;\n        dist_ d( lambda );\n        os << d << std::endl;\n        BOOST_AUTO(\n        \tvg,\n            dist::make_random_generator(urng,d)\n        );\n        check(n_loops,n1,n2,d,vg,os);\n    }\n    { \n        typedef math::gamma_distribution<val_>            dist_;\n        const val_ shape = 1.0;\n        const val_ scale = 0.5;\n        dist_ d( shape, scale );\n        dist_ d1( shape + 0.01, scale );\n        os << d << std::endl;\n            \n        BOOST_AUTO(\n        \tvg,\n            dist::make_random_generator(urng,d)\n        );\n        check(n_loops,n1,n2,d1,vg,os);\n    }\n    {\n        typedef math::normal_distribution<val_>            dist_;\n        const val_ m = 1.0;\n        const val_ s = 2.0;\n        dist_ d( m, s );\n        os << d << std::endl;\n            \n        BOOST_AUTO(\n        \tvg,\n            dist::make_random_generator(urng,d)\n        );\n        check(n_loops,n1,n2,d,vg,os);\n\n    }\n    {\n        typedef boost::math::poisson_distribution<val_>            dist_;\n        const val_ m = 10.0;\n        dist_ d( m );\n        os << d << std::endl;\n            \n        BOOST_AUTO(\n        \tvg,\n            dist::make_random_generator(urng,d)\n        );\n        check(n_loops,n1,n2,d,vg,os);\n\n    }\n    {\n        typedef math::students_t_distribution<val_>        dist_;\n        const val_ df = 4.0;\n        dist_ d( df );\n        os << d << std::endl;\n\n        BOOST_AUTO(\n        \tvg,\n            dist::make_random_generator(urng,d)\n        );\n        check(n_loops,n1,n2,d,vg,os);\n    }\n    {\n        typedef math::students_t_distribution<val_> dist_z_;\n        typedef dist::toolkit::location_scale_distribution<dist_z_> dist_; \n        const val_ df = 4.0;\n        const val_ m = 1.0;\n        const val_ s = 2.0;\n        dist_z_ dist_z( df );\n        dist_ d(m, s, dist_z);\n        os << d << std::endl;\n\n        BOOST_AUTO(\n        \tvg,\n            dist::make_random_generator(urng,d)\n        );\n        check(n_loops,n1,n2,d,vg,os);\n    }\n    {\n        typedef math::students_t_distribution<val_>         d0_;\n        typedef dist::reference_wrapper<d0_>                dist_; \n        const val_ df = 4.0;\n        d0_ d0( df );\n        dist_ d(d0);\n        os << d << std::endl;\n            \n        BOOST_AUTO(\n        \tvg,\n            dist::make_random_generator(urng,d)\n        );\n        check(n_loops,n1,n2,d,vg,os);\n    }\n\n    os << \"<-\" << std::endl;\n}", "meta": {"hexsha": "eb1ffc7fa3a5d22915e5a4bcade3bf8c599243e8", "size": 5157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/libs/statistics/detail/distribution_toolkit/example/random.cpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distribution_toolkit/libs/statistics/detail/distribution_toolkit/example/random.cpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distribution_toolkit/libs/statistics/detail/distribution_toolkit/example/random.cpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0576923077, "max_line_length": 96, "alphanum_fraction": 0.5633120031, "num_tokens": 1247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5980855745306509}}
{"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": "// -----------------------------------------------------------------------\r\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\r\n//\r\n// Copyright (c) German Cancer Research Center (DKFZ),\r\n// Software development for Integrated Diagnostics and Therapy (SIDT).\r\n// ALL RIGHTS RESERVED.\r\n// See rttbCopyright.txt or\r\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html [^]\r\n//\r\n// This software is distributed WITHOUT ANY WARRANTY; without even\r\n// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\r\n// PURPOSE. See the above copyright notices for more information.\r\n//\r\n//------------------------------------------------------------------------\r\n\r\n// this file defines the rttbCoreTests for the test driver\r\n// and all it expects is that you have a function called RegisterTests\r\n\r\n#include <boost/shared_ptr.hpp>\r\n\r\n#include \"litCheckMacros.h\"\r\n#include \"rttbBioModel.h\"\r\n#include \"rttbDVH.h\"\r\n#include \"rttbTCPLQModel.h\"\r\n#include \"rttbNTCPLKBModel.h\"\r\n#include \"rttbNTCPRSModel.h\"\r\n#include \"rttbBioModelScatterPlots.h\"\r\n#include \"rttbBioModelCurve.h\"\r\n#include \"rttbDvhBasedModels.h\"\r\n#include \"../models/rttbScatterTester.h\"\r\n#include \"rttbInvalidParameterException.h\"\r\n#include \"rttbDVHXMLFileReader.h\"\r\n\r\nnamespace rttb\r\n{\r\n\tnamespace testing\r\n\t{\r\n\r\n\r\n\t\t/*! @brief RTBioModelScatterPlotExampleTest.\r\n\t\tcalculating Curves and Scatterplots for TCP and NTCP models.\r\n\t\tThe values on curve and scatterplot need to be similar for similar dose values.\r\n\t\tThe range of difference is given by the variance used to generate the scatter.\r\n\r\n\t\tWARNING: The values for comparison need to be adjusted if the input files are changed!\r\n\t\t*/\r\n\t\tint RTBioModelScatterPlotExampleTest(int argc, char* argv[])\r\n\t\t{\r\n\t\t\tPREPARE_DEFAULT_TEST_REPORTING;\r\n\r\n\t\t\ttypedef rttb::models::CurveDataType CurveDataType;\r\n\t\t\ttypedef rttb::models::ScatterPlotType ScatterPlotType;\r\n\t\t\ttypedef core::DVH::Pointer DVHPointer;\r\n\r\n\t\t\t//increased accuracy requires double values in the calculation (rttbBaseType.h)\r\n\t\t\tdouble toleranceEUD = 1e-5;\r\n\r\n\t\t\t//ARGUMENTS: 1: ptv dvh file name\r\n\t\t\t//           2: normal tissue 1 dvh file name\r\n\t\t\t//           3: TV dvh file name\r\n\r\n\t\t\tstd::string DVH_FILENAME_PTV;\r\n\t\t\tstd::string DVH_FILENAME_NT1;\r\n\t\t\tstd::string DVH_FILENAME_TV_TEST;\r\n\r\n\t\t\tif (argc > 1)\r\n\t\t\t{\r\n\t\t\t\tDVH_FILENAME_PTV = argv[1];\r\n\t\t\t}\r\n\r\n\t\t\tif (argc > 2)\r\n\t\t\t{\r\n\t\t\t\tDVH_FILENAME_NT1 = argv[2];\r\n\t\t\t}\r\n\r\n\t\t\tif (argc > 3)\r\n\t\t\t{\r\n\t\t\t\tDVH_FILENAME_TV_TEST = argv[3];\r\n\t\t\t}\r\n\r\n\t\t\t//DVH PTV\r\n\t\t\trttb::io::other::DVHXMLFileReader dvhReader = rttb::io::other::DVHXMLFileReader(DVH_FILENAME_PTV);\r\n\t\t\tDVHPointer dvhPtr = dvhReader.generateDVH();\r\n\r\n\t\t\trttb::io::other::DVHXMLFileReader dvhReader_test_tv = rttb::io::other::DVHXMLFileReader(\r\n\t\t\t            DVH_FILENAME_TV_TEST);\r\n\t\t\tDVHPointer dvh_test_tv = dvhReader_test_tv.generateDVH();\r\n\r\n\t\t\t//test TCP LQ Model\r\n\t\t\tmodels::BioModelParamType alpha = 0.35;\r\n\t\t\tmodels::BioModelParamType beta = 0.023333333333333;\r\n\t\t\tmodels::BioModelParamType roh = 10000000;\r\n\t\t\tint numFractions = 2;\r\n\r\n\t\t\tDoseTypeGy normalizationDose = 68;\r\n\r\n\t\t\trttb::models::TCPLQModel tcplq = rttb::models::TCPLQModel(dvhPtr, alpha, beta, roh, numFractions);\r\n\r\n\t\t\tCHECK_NO_THROW(tcplq.init());\r\n\r\n\t\t\tCurveDataType curve = models::getCurveDoseVSBioModel(tcplq, normalizationDose);\r\n\r\n\t\t\tCHECK_NO_THROW(models::getScatterPlotVary1Parameter(tcplq, 0, alpha, 0, normalizationDose, 100));\r\n\t\t\tScatterPlotType tcpScatter = models::getScatterPlotVary1Parameter(tcplq, 0, alpha, 0,\r\n\t\t\t                             normalizationDose, 100);\r\n\t\t\tCHECK_EQUAL(100, tcpScatter.size());\r\n\r\n\t\t\tScatterTester scatterCompare(curve, tcpScatter);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\t//test also with other parameter\r\n\t\t\ttcpScatter = models::getScatterPlotVary1Parameter(tcplq, 3, roh, 0, normalizationDose, 100);\r\n\r\n\t\t\tscatterCompare.setCompareScatter(tcpScatter);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tstd::vector<int> paramIdVec;\r\n\t\t\tmodels::BioModel::ParamVectorType meanVec;\r\n\t\t\tmodels::BioModel::ParamVectorType meanVecTest;\r\n\t\t\tmeanVecTest.push_back(alpha);\r\n\t\t\tmodels::BioModel::ParamVectorType varianceVec;\r\n\t\t\t//\"alphaMean\":0,\"alphaVariance\":1,\"alpha_beta\":2, \"rho\":3\r\n\t\t\tparamIdVec.push_back(0);\r\n\t\t\tmeanVec.push_back(tcplq.getAlphaMean());\r\n\t\t\tvarianceVec.push_back(0);\r\n\t\t\t//setting parameter 1 will change the resulting scatter plot dramatically - is it meant to?\r\n\t\t\t//this is unexpected since the value was taken from the original calculation\r\n\t\t\t//paramIdVec.push_back(1); meanVec.push_back(tcplq.getAlphaVariance()); varianceVec.push_back(0);\r\n\t\t\tparamIdVec.push_back(2);\r\n\t\t\tmeanVec.push_back(tcplq.getAlphaBeta());\r\n\t\t\tvarianceVec.push_back(0);\r\n\t\t\tparamIdVec.push_back(3);\r\n\t\t\tmeanVec.push_back(tcplq.getRho());\r\n\t\t\tvarianceVec.push_back(0);\r\n\r\n\t\t\tCHECK_THROW_EXPLICIT(models::getScatterPlotVaryParameters(tcplq, paramIdVec, meanVecTest,\r\n\t\t\t                     varianceVec, normalizationDose, 50), core::InvalidParameterException);\r\n\t\t\tScatterPlotType scatterVary = models::getScatterPlotVaryParameters(tcplq, paramIdVec, meanVec,\r\n\t\t\t                              varianceVec, normalizationDose, 50);\r\n\t\t\tCHECK_EQUAL(50, scatterVary.size());\r\n\r\n\t\t\tscatterCompare.setCompareScatter(scatterVary);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tmodels::BioModelParamType variance = 0.00015;\r\n\t\t\tCHECK_NO_THROW(models::getScatterPlotVary1Parameter(tcplq, 0, alpha, variance, normalizationDose,\r\n\t\t\t               100));\r\n\t\t\ttcpScatter = models::getScatterPlotVary1Parameter(tcplq, 0, alpha, variance, normalizationDose,\r\n\t\t\t             100);\r\n\r\n\t\t\tscatterCompare.setVariance(variance);\r\n\t\t\tscatterCompare.setCompareScatter(tcpScatter);\r\n\t\t\t//allow 5% of the points to deviate more\r\n\t\t\tscatterCompare.setAllowExceptions(true);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\t//test also with other parameter\r\n\t\t\ttcpScatter = models::getScatterPlotVary1Parameter(tcplq, 3, roh, variance, normalizationDose, 100);\r\n\t\t\tscatterCompare.setCompareScatter(tcpScatter);\r\n\t\t\t//allow 5% of the points to deviate more\r\n\t\t\tscatterCompare.setAllowExceptions(true);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tparamIdVec.clear();\r\n\t\t\tmeanVec.clear();\r\n\t\t\tvarianceVec.clear();\r\n\t\t\tparamIdVec.push_back(0);\r\n\t\t\tmeanVec.push_back(tcplq.getAlphaMean());\r\n\t\t\tvarianceVec.push_back(variance);\r\n\t\t\t//paramIdVec.push_back(1); meanVec.push_back(tcplq.getAlphaVariance()); varianceVec.push_back(variance);\r\n\t\t\tparamIdVec.push_back(2);\r\n\t\t\tmeanVec.push_back(tcplq.getAlphaBeta());\r\n\t\t\tvarianceVec.push_back(variance);\r\n\t\t\tparamIdVec.push_back(3);\r\n\t\t\tmeanVec.push_back(tcplq.getRho());\r\n\t\t\tvarianceVec.push_back(variance);\r\n\r\n\t\t\tscatterVary = models::getScatterPlotVaryParameters(tcplq, paramIdVec, meanVec, varianceVec,\r\n\t\t\t              normalizationDose, 50);\r\n\r\n\t\t\tscatterCompare.setCompareScatter(scatterVary);\r\n\t\t\t//allow 5% of the points to deviate more\r\n\t\t\tscatterCompare.setAllowExceptions(true);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tmodels::BioModelParamType alphaBeta = 10;\r\n\t\t\ttcplq.setParameters(alpha, alphaBeta, roh, 0.08);\r\n\t\t\ttcplq.init();\r\n\r\n\t\t\tnormalizationDose = 40;\r\n\t\t\tcurve = models::getCurveDoseVSBioModel(tcplq, normalizationDose);\r\n\r\n\t\t\tCHECK_NO_THROW(models::getScatterPlotVary1Parameter(tcplq, 0, alpha, 0, normalizationDose, 100));\r\n\t\t\ttcpScatter = models::getScatterPlotVary1Parameter(tcplq, 0, alpha, 0, normalizationDose, 100);\r\n\r\n\t\t\tscatterCompare.setReferenceCurve(curve);\r\n\t\t\tscatterCompare.setVariance(0);\r\n\t\t\t//do not allow larger deviations\r\n\t\t\tscatterCompare.setAllowExceptions(false);\r\n\t\t\tscatterCompare.setCompareScatter(tcpScatter);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tvariance = 0.25;\r\n\t\t\tCHECK_NO_THROW(models::getScatterPlotVary1Parameter(tcplq, 0, alpha, variance, normalizationDose,\r\n\t\t\t               100));\r\n\t\t\ttcpScatter = models::getScatterPlotVary1Parameter(tcplq, 0, alpha, variance, normalizationDose,\r\n\t\t\t             100);\r\n\r\n\t\t\tscatterCompare.setCompareScatter(tcpScatter);\r\n\t\t\tscatterCompare.setVariance(variance);\r\n\t\t\t//allow 5% of the points to deviate more\r\n\t\t\tscatterCompare.setAllowExceptions(true);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\r\n\t\t\t/*TCP LQ Test*/\r\n\t\t\talpha = 0.3;\r\n\t\t\tbeta = 0.03;\r\n\t\t\troh = 10000000;\r\n\t\t\tnumFractions = 20;\r\n\t\t\trttb::models::TCPLQModel tcplq_test = rttb::models::TCPLQModel(dvh_test_tv, alpha, beta, roh,\r\n\t\t\t                                      numFractions);\r\n\r\n\t\t\tCHECK_NO_THROW(tcplq_test.init());\r\n\t\t\tnormalizationDose = 60;\r\n\t\t\tcurve = models::getCurveDoseVSBioModel(tcplq_test, normalizationDose);\r\n\r\n\t\t\tCHECK_NO_THROW(models::getScatterPlotVary1Parameter(tcplq_test, 0, alpha, 0, normalizationDose,\r\n\t\t\t               100));\r\n\t\t\ttcpScatter = models::getScatterPlotVary1Parameter(tcplq_test, 0, alpha, 0, normalizationDose, 100);\r\n\r\n\t\t\tscatterCompare.setReferenceCurve(curve);\r\n\t\t\tscatterCompare.setVariance(0);\r\n\t\t\tscatterCompare.setCompareScatter(tcpScatter);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\t//test also with other parameter\r\n\t\t\ttcpScatter = models::getScatterPlotVary1Parameter(tcplq_test, 3, roh, 0, normalizationDose, 100);\r\n\t\t\tscatterCompare.setCompareScatter(tcpScatter);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tparamIdVec.clear();\r\n\t\t\tmeanVec.clear();\r\n\t\t\tvarianceVec.clear();\r\n\t\t\tparamIdVec.push_back(0);\r\n\t\t\tmeanVec.push_back(tcplq_test.getAlphaMean());\r\n\t\t\tvarianceVec.push_back(0);\r\n\t\t\t//paramIdVec.push_back(1); meanVec.push_back(tcplq_test.getAlphaVariance()); varianceVec.push_back(0);\r\n\t\t\tparamIdVec.push_back(2);\r\n\t\t\tmeanVec.push_back(tcplq_test.getAlphaBeta());\r\n\t\t\tvarianceVec.push_back(0);\r\n\t\t\tparamIdVec.push_back(3);\r\n\t\t\tmeanVec.push_back(tcplq_test.getRho());\r\n\t\t\tvarianceVec.push_back(0);\r\n\r\n\t\t\tscatterVary = models::getScatterPlotVaryParameters(tcplq_test, paramIdVec, meanVec, varianceVec,\r\n\t\t\t              normalizationDose, 50);\r\n\r\n\t\t\tscatterCompare.setCompareScatter(scatterVary);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tvariance = 0.00025;\r\n\t\t\tCHECK_NO_THROW(models::getScatterPlotVary1Parameter(tcplq_test, 0, alpha, variance,\r\n\t\t\t               normalizationDose, 100));\r\n\t\t\ttcpScatter = models::getScatterPlotVary1Parameter(tcplq_test, 0, alpha, variance, normalizationDose,\r\n\t\t\t             100);\r\n\r\n\t\t\tscatterCompare.setCompareScatter(tcpScatter);\r\n\t\t\tscatterCompare.setVariance(variance);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\t//test also with other parameter\r\n\t\t\ttcpScatter = models::getScatterPlotVary1Parameter(tcplq_test, 3, roh, variance, normalizationDose,\r\n\t\t\t             100);\r\n\t\t\tscatterCompare.setCompareScatter(tcpScatter);\r\n\t\t\tscatterCompare.setAllowExceptions(true);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\t\t\tscatterCompare.setAllowExceptions(false);\r\n\r\n\t\t\tparamIdVec.clear();\r\n\t\t\tmeanVec.clear();\r\n\t\t\tvarianceVec.clear();\r\n\t\t\tparamIdVec.push_back(0);\r\n\t\t\tmeanVec.push_back(tcplq_test.getAlphaMean());\r\n\t\t\tvarianceVec.push_back(variance);\r\n\t\t\t//paramIdVec.push_back(1); meanVec.push_back(tcplq_test.getAlphaVariance()); varianceVec.push_back(variance);\r\n\t\t\tparamIdVec.push_back(2);\r\n\t\t\tmeanVec.push_back(tcplq_test.getAlphaBeta());\r\n\t\t\tvarianceVec.push_back(variance);\r\n\t\t\tparamIdVec.push_back(3);\r\n\t\t\tmeanVec.push_back(tcplq_test.getRho());\r\n\t\t\tvarianceVec.push_back(variance);\r\n\r\n\t\t\tscatterVary = models::getScatterPlotVaryParameters(tcplq_test, paramIdVec, meanVec, varianceVec,\r\n\t\t\t              normalizationDose, 50);\r\n\r\n\t\t\tscatterCompare.setCompareScatter(scatterVary);\r\n\t\t\t//allow 5% of the points to deviate more\r\n\t\t\tscatterCompare.setAllowExceptions(true);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\t//DVH HT 1\r\n\t\t\trttb::io::other::DVHXMLFileReader dvhReader2 = rttb::io::other::DVHXMLFileReader(DVH_FILENAME_NT1);\r\n\t\t\tDVHPointer dvhPtr2 = dvhReader2.generateDVH();\r\n\r\n\t\t\tCHECK_CLOSE(1.07920836034015810000e+001, models::getEUD(dvhPtr2, 10), toleranceEUD);\r\n\r\n\t\t\t//test RTNTCPLKBModel\r\n\t\t\trttb::models::NTCPLKBModel lkb = rttb::models::NTCPLKBModel();\r\n\t\t\tmodels::BioModelParamType aVal = 10;\r\n\t\t\tmodels::BioModelParamType mVal = 0.16;\r\n\t\t\tmodels::BioModelParamType d50Val = 55;\r\n\t\t\tlkb.setDVH(dvhPtr2);\r\n\t\t\tlkb.setA(aVal);\r\n\t\t\tlkb.setM(mVal);\r\n\t\t\tlkb.setD50(d50Val);\r\n\t\t\tCHECK_NO_THROW(lkb.init());\r\n\r\n\t\t\tnormalizationDose = 60;\r\n\t\t\tcurve = models::getCurveDoseVSBioModel(lkb, normalizationDose);\r\n\r\n\t\t\tCHECK_NO_THROW(models::getScatterPlotVary1Parameter(lkb, 2, aVal, 0, normalizationDose, 100));\r\n\t\t\tScatterPlotType scatter = models::getScatterPlotVary1Parameter(lkb, 2, aVal, 0, normalizationDose,\r\n\t\t\t                          100);\r\n\r\n\t\t\tscatterCompare.setReferenceCurve(curve);\r\n\t\t\tscatterCompare.setVariance(0);\r\n\t\t\tscatterCompare.setCompareScatter(scatter);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\t//\"d50\":0,\"m\":1,\"a\":2\r\n\t\t\t//test also with other parameter\r\n\t\t\tscatter = models::getScatterPlotVary1Parameter(lkb, 0, d50Val, 0, normalizationDose, 100);\r\n\t\t\tscatterCompare.setCompareScatter(scatter);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tparamIdVec.clear();\r\n\t\t\tmeanVec.clear();\r\n\t\t\tvarianceVec.clear();\r\n\t\t\tparamIdVec.push_back(0);\r\n\t\t\tmeanVec.push_back(lkb.getD50());\r\n\t\t\tvarianceVec.push_back(0);\r\n\t\t\tparamIdVec.push_back(1);\r\n\t\t\tmeanVec.push_back(lkb.getM());\r\n\t\t\tvarianceVec.push_back(0);\r\n\t\t\tparamIdVec.push_back(2);\r\n\t\t\tmeanVec.push_back(lkb.getA());\r\n\t\t\tvarianceVec.push_back(0);\r\n\r\n\t\t\tscatterVary = models::getScatterPlotVaryParameters(lkb, paramIdVec, meanVec, varianceVec,\r\n\t\t\t              normalizationDose, 50);\r\n\r\n\t\t\tscatterCompare.setCompareScatter(scatterVary);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tvariance = 0.00025;\r\n\t\t\tCHECK_NO_THROW(models::getScatterPlotVary1Parameter(lkb, 2, aVal, variance, normalizationDose,\r\n\t\t\t               100));\r\n\t\t\tscatter = models::getScatterPlotVary1Parameter(lkb, 2, aVal, variance, normalizationDose, 100);\r\n\r\n\t\t\tscatterCompare.setCompareScatter(scatter);\r\n\t\t\tscatterCompare.setVariance(variance);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\t//test also with other parameter\r\n\t\t\tscatter = models::getScatterPlotVary1Parameter(lkb, 0, d50Val, variance, normalizationDose, 100);\r\n\t\t\tscatterCompare.setCompareScatter(scatter);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tparamIdVec.clear();\r\n\t\t\tmeanVec.clear();\r\n\t\t\tvarianceVec.clear();\r\n\t\t\tparamIdVec.push_back(0);\r\n\t\t\tmeanVec.push_back(lkb.getD50());\r\n\t\t\tvarianceVec.push_back(variance);\r\n\t\t\tparamIdVec.push_back(1);\r\n\t\t\tmeanVec.push_back(lkb.getM());\r\n\t\t\tvarianceVec.push_back(variance);\r\n\t\t\tparamIdVec.push_back(2);\r\n\t\t\tmeanVec.push_back(lkb.getA());\r\n\t\t\tvarianceVec.push_back(variance);\r\n\r\n\t\t\tscatterVary = models::getScatterPlotVaryParameters(lkb, paramIdVec, meanVec, varianceVec,\r\n\t\t\t              normalizationDose, 50);\r\n\r\n\t\t\tscatterCompare.setCompareScatter(scatterVary);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\t//test RTNTCPRSModel\r\n\t\t\trttb::models::NTCPRSModel rs = rttb::models::NTCPRSModel();\r\n\t\t\tmodels::BioModelParamType gammaVal = 1.7;\r\n\t\t\tmodels::BioModelParamType sVal = 1;\r\n\t\t\trs.setDVH(dvhPtr2);\r\n\t\t\trs.setD50(d50Val);\r\n\t\t\trs.setGamma(gammaVal);\r\n\t\t\trs.setS(sVal);\r\n\t\t\tCHECK_NO_THROW(rs.init());\r\n\r\n\t\t\tnormalizationDose = 60;\r\n\t\t\tcurve = models::getCurveDoseVSBioModel(rs, normalizationDose);\r\n\r\n\t\t\tCHECK_NO_THROW(models::getScatterPlotVary1Parameter(rs, 0, d50Val, 0, normalizationDose, 100));\r\n\t\t\tscatter = models::getScatterPlotVary1Parameter(rs, 0, d50Val, 0, normalizationDose, 100);\r\n\r\n\t\t\tscatterCompare.setReferenceCurve(curve);\r\n\t\t\tscatterCompare.setVariance(0);\r\n\t\t\tscatterCompare.setCompareScatter(scatter);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\t//\"d50\":0,\"gamma\":1,\"s\":2\r\n\t\t\t//test also with other parameter\r\n\t\t\tscatter = models::getScatterPlotVary1Parameter(rs, 1, gammaVal, 0, normalizationDose, 100);\r\n\t\t\tscatterCompare.setCompareScatter(scatter);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tparamIdVec.clear();\r\n\t\t\tmeanVec.clear();\r\n\t\t\tvarianceVec.clear();\r\n\t\t\tparamIdVec.push_back(0);\r\n\t\t\tmeanVec.push_back(rs.getD50());\r\n\t\t\tvarianceVec.push_back(0);\r\n\t\t\tparamIdVec.push_back(1);\r\n\t\t\tmeanVec.push_back(rs.getGamma());\r\n\t\t\tvarianceVec.push_back(0);\r\n\t\t\tparamIdVec.push_back(2);\r\n\t\t\tmeanVec.push_back(rs.getS());\r\n\t\t\tvarianceVec.push_back(0);\r\n\r\n\t\t\tscatterVary = models::getScatterPlotVaryParameters(rs, paramIdVec, meanVec, varianceVec,\r\n\t\t\t              normalizationDose, 50);\r\n\r\n\t\t\tscatterCompare.setCompareScatter(scatterVary);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tvariance = 0.0075;\r\n\t\t\tCHECK_NO_THROW(models::getScatterPlotVary1Parameter(rs, 0, d50Val, variance, normalizationDose,\r\n\t\t\t               100));\r\n\t\t\tscatter = models::getScatterPlotVary1Parameter(rs, 0, d50Val, variance, normalizationDose, 100);\r\n\r\n\t\t\tscatterCompare.setCompareScatter(scatter);\r\n\t\t\tscatterCompare.setVariance(variance);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\t//test also with other parameter\r\n\t\t\tscatter = models::getScatterPlotVary1Parameter(rs, 2, sVal, variance, normalizationDose, 100);\r\n\t\t\tscatterCompare.setCompareScatter(scatter);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tparamIdVec.clear();\r\n\t\t\tmeanVec.clear();\r\n\t\t\tvarianceVec.clear();\r\n\t\t\tparamIdVec.push_back(0);\r\n\t\t\tmeanVec.push_back(rs.getD50());\r\n\t\t\tvarianceVec.push_back(variance);\r\n\t\t\tparamIdVec.push_back(1);\r\n\t\t\tmeanVec.push_back(rs.getGamma());\r\n\t\t\tvarianceVec.push_back(variance);\r\n\t\t\tparamIdVec.push_back(2);\r\n\t\t\tmeanVec.push_back(rs.getS());\r\n\t\t\tvarianceVec.push_back(variance);\r\n\r\n\t\t\tscatterVary = models::getScatterPlotVaryParameters(rs, paramIdVec, meanVec, varianceVec,\r\n\t\t\t              normalizationDose, 50);\r\n\r\n\t\t\tscatterCompare.setCompareScatter(scatterVary);\r\n\t\t\tCHECK_TESTER(scatterCompare);\r\n\r\n\t\t\tRETURN_AND_REPORT_TEST_SUCCESS;\r\n\r\n\t\t}\r\n\r\n\t}//testing\r\n}//rttb\r\n", "meta": {"hexsha": "9dd48967264f8c3e115c5c4a58fed7733b197844", "size": 17443, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/examples/RTBioModelScatterPlotExampleTest.cpp", "max_stars_repo_name": "MIC-DKFZ/RTTB", "max_stars_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T12:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:43:02.000Z", "max_issues_repo_path": "testing/examples/RTBioModelScatterPlotExampleTest.cpp", "max_issues_repo_name": "MIC-DKFZ/RTTB", "max_issues_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/examples/RTBioModelScatterPlotExampleTest.cpp", "max_forks_repo_name": "MIC-DKFZ/RTTB", "max_forks_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T21:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T09:30:49.000Z", "avg_line_length": 36.7995780591, "max_line_length": 113, "alphanum_fraction": 0.7089376827, "num_tokens": 4903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5980855579748363}}
{"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 * @file bigbatch_sgd_test.cpp\n * @author Marcus Edel\n *\n * Test file for big-batch SGD.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/core/optimizers/bigbatch_sgd/bigbatch_sgd.hpp>\n#include <mlpack/methods/logistic_regression/logistic_regression.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::optimization;\n\nusing namespace mlpack::distribution;\nusing namespace mlpack::regression;\n\nBOOST_AUTO_TEST_SUITE(BigBatchSGDTest);\n\n/**\n * Create the data for the logistic regression test case.\n */\nvoid CreateLogisticRegressionTestData(arma::mat& data,\n                                      arma::mat& testData,\n                                      arma::mat& shuffledData,\n                                      arma::Row<size_t>& responses,\n                                      arma::Row<size_t>& testResponses,\n                                      arma::Row<size_t>& shuffledResponses)\n{\n  // Generate a two-Gaussian dataset.\n  GaussianDistribution g1(arma::vec(\"1.0 1.0 1.0\"), arma::eye<arma::mat>(3, 3));\n  GaussianDistribution g2(arma::vec(\"9.0 9.0 9.0\"), arma::eye<arma::mat>(3, 3));\n\n  data = arma::mat(3, 1000);\n  responses = arma::Row<size_t>(1000);\n  for (size_t i = 0; i < 500; ++i)\n  {\n    data.col(i) = g1.Random();\n    responses[i] = 0;\n  }\n  for (size_t i = 500; i < 1000; ++i)\n  {\n    data.col(i) = g2.Random();\n    responses[i] = 1;\n  }\n\n  // Shuffle the dataset.\n  arma::uvec indices = arma::shuffle(arma::linspace<arma::uvec>(0,\n      data.n_cols - 1, data.n_cols));\n  shuffledData = arma::mat(3, 1000);\n  shuffledResponses = arma::Row<size_t>(1000);\n  for (size_t i = 0; i < data.n_cols; ++i)\n  {\n    shuffledData.col(i) = data.col(indices[i]);\n    shuffledResponses[i] = responses[indices[i]];\n  }\n\n  // Create a test set.\n  testData = arma::mat(3, 1000);\n  testResponses = arma::Row<size_t>(1000);\n  for (size_t i = 0; i < 500; ++i)\n  {\n    testData.col(i) = g1.Random();\n    testResponses[i] = 0;\n  }\n  for (size_t i = 500; i < 1000; ++i)\n  {\n    testData.col(i) = g2.Random();\n    testResponses[i] = 1;\n  }\n}\n\n/**\n * Run big-batch SGD using BBS_BB on logistic regression and make sure the\n * results are acceptable.\n */\nBOOST_AUTO_TEST_CASE(BBSBBLogisticRegressionTest)\n{\n  arma::mat data, testData, shuffledData;\n  arma::Row<size_t> responses, testResponses, shuffledResponses;\n\n  CreateLogisticRegressionTestData(data, testData, shuffledData,\n      responses, testResponses, shuffledResponses);\n\n  // Now run big-batch SGD with a couple of batch sizes.\n  for (size_t batchSize = 30; batchSize < 40; batchSize += 5)\n  {\n    BBS_BB bbsgd(batchSize, 0.01, 0.1, 6000, 1e-3);\n    LogisticRegression<> lr(shuffledData, shuffledResponses, bbsgd, 0.5);\n\n    // Ensure that the error is close to zero.\n    const double acc = lr.ComputeAccuracy(data, responses);\n    BOOST_REQUIRE_CLOSE(acc, 100.0, 0.3); // 0.3% error tolerance.\n\n    const double testAcc = lr.ComputeAccuracy(testData, testResponses);\n    BOOST_REQUIRE_CLOSE(testAcc, 100.0, 0.6); // 0.6% error tolerance.\n  }\n}\n\n/**\n * Run big-batch SGD using BBS_Armijo on logistic regression and make sure the\n * results are acceptable.\n */\nBOOST_AUTO_TEST_CASE(BBSArmijoLogisticRegressionTest)\n{\n  arma::mat data, testData, shuffledData;\n  arma::Row<size_t> responses, testResponses, shuffledResponses;\n\n  CreateLogisticRegressionTestData(data, testData, shuffledData,\n      responses, testResponses, shuffledResponses);\n\n  // Now run big-batch SGD with a couple of batch sizes.\n  for (size_t batchSize = 30; batchSize < 60; batchSize += 1)\n  {\n    BBS_Armijo bbsgd(batchSize, 0.01, 0.1, 6000, 1e-3);\n    LogisticRegression<> lr(shuffledData, shuffledResponses, bbsgd, 0.5);\n\n    // Ensure that the error is close to zero.\n    const double acc = lr.ComputeAccuracy(data, responses);\n    BOOST_REQUIRE_CLOSE(acc, 100.0, 0.3); // 0.3% error tolerance.\n\n    const double testAcc = lr.ComputeAccuracy(testData, testResponses);\n    BOOST_REQUIRE_CLOSE(testAcc, 100.0, 0.6); // 0.6% error tolerance.\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "a710563439df53d1499f355d2da4923deeef3fcd", "size": 4384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/bigbatch_sgd_test.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/bigbatch_sgd_test.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/bigbatch_sgd_test.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2352941176, "max_line_length": 80, "alphanum_fraction": 0.6665145985, "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5980855516775625}}
{"text": "#include \"utils/data_generator.cpp\"\n#include \"../src/numerical/gradient_descent/gd_solver.h\"\n#include \"../src/logging/easylogging++.h\"\n#include <armadillo>\n\nusing arma::mat;\n\nINITIALIZE_EASYLOGGINGPP\n\nmat WEIGHTS = {100, -20, 50, -0.5};\n\nint main(int argc, char *argv[])\n{\n    el::Configurations conf(\"./logging-config.conf\");\n    el::Loggers::reconfigureLogger(\"default\", conf);\n\n    auto data_generator = DataGenerator();\n    auto L = data_generator.generate_library();\n    auto s = data_generator.generate_signal(WEIGHTS);\n\n    LOG(INFO) << \"True: \" << WEIGHTS;\n\n    GDSolver solver = GDSolver(L, 1, 1000);\n    solver.find_optimal_lr(s);\n    auto result = solver.solve(s);\n    LOG(INFO) << \"Result: \" << result;\n\n    return 0;\n}", "meta": {"hexsha": "7cb7eeb99287af4d2905aa917ac8d04044908d73", "size": 731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/find_lr.cpp", "max_stars_repo_name": "omyllymaki/math", "max_stars_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T09:12:24.000Z", "max_issues_repo_path": "samples/find_lr.cpp", "max_issues_repo_name": "omyllymaki/math", "max_issues_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "samples/find_lr.cpp", "max_forks_repo_name": "omyllymaki/math", "max_forks_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2068965517, "max_line_length": 56, "alphanum_fraction": 0.6744186047, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5980855471322931}}
{"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": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#include <rw/math/VectorND.hpp>\n\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n\nusing namespace rw::math;\n\ntemplate< size_t N > VectorND< N > getVectorND (double value)\n{\n    VectorND< N > vec;\n    for (size_t i = 0; i < vec.size (); i++) {\n        vec[i] = value;\n    }\n    return vec;\n}\n\ntemplate< size_t N > VectorND< N > getVectorND (bool countUp, bool Digit=true)\n{\n    VectorND< N > vec;\n    for (size_t i = 0; i < vec.size (); i++) {\n        if(countUp){\n            vec[i] = i+1+ Digit*(i+1)%10/10.0;\n        }else {\n            vec[i] = i - vec.size() +Digit*(i+vec.size())%10/10.0 ;\n        }\n    }\n    return vec;\n}\n\nTEST(VectorND,Constructor){\n    VectorND< 3 > obj1(1,2,3);\n    EXPECT_EQ(obj1[0],1);\n    EXPECT_EQ(obj1[1],2);\n    EXPECT_EQ(obj1[2],3);\n\n    VectorND< 9 > obj2(1,2.1212142,long(3),4.0,float(5),6,double(7),8u,9);\n    EXPECT_DOUBLE_EQ(obj2[0],1);\n    EXPECT_DOUBLE_EQ(obj2[1],2.1212142);\n    EXPECT_DOUBLE_EQ(obj2[2],3);\n    EXPECT_DOUBLE_EQ(obj2[3],4);\n    EXPECT_DOUBLE_EQ(obj2[4],5);\n    EXPECT_DOUBLE_EQ(obj2[5],6);\n    EXPECT_DOUBLE_EQ(obj2[6],7);\n    EXPECT_DOUBLE_EQ(obj2[7],8);\n    EXPECT_DOUBLE_EQ(obj2[8],9);\n}\n\ntemplate< typename T > class VectorNDTest : public ::testing::Test\n{};\n\nusing test_types = ::testing::Types<\n    std::integral_constant< std::size_t, 2 >, std::integral_constant< std::size_t, 3 >,\n    std::integral_constant< std::size_t, 4 >, std::integral_constant< std::size_t, 5 >,\n    std::integral_constant< std::size_t, 6 >, std::integral_constant< std::size_t, 13 > >;\n\nTYPED_TEST_CASE (VectorNDTest, test_types);\n\nTYPED_TEST (VectorNDTest, MiscTest)\n{\n    static constexpr std::size_t N = TypeParam::value;\n    const VectorND< N > v1 =getVectorND<N>(true,false);\n    const VectorND< N > v2 (v1);\n    const VectorND< N > v3 = v1 + v2;\n    const VectorND< N > v4 = getVectorND<N>(true,false)*2;\n    EXPECT_EQ ((v3 - v4).normInf (), 0);\n\n    const VectorND< N > v5 = getVectorND<N>(true);\n    const VectorND< N > v5_norm = normalize (v5);\n    EXPECT_LT (fabs (v5_norm.norm2 () - 1), 1e-15);\n\n    const double len = v5.norm2 ();\n    EXPECT_LT (fabs (v5_norm (0) - v5 (0) / len), 1e-15);\n    EXPECT_LT (fabs (v5_norm (1) - v5 (1) / len), 1e-15);\n    (fabs (v5_norm (2) - v5 (2) / len) < 1e-15);\n\n    VectorND< N > v6;\n    v6 (0) = len;\n    EXPECT_EQ (v6 (0), len);\n\n    const VectorND< N, double > vd = getVectorND<N>(true);\n    const VectorND< N, int > vi = cast< int > (vd);\n    for(int i = 1; size_t (i) <= vi.size(); i++){\n        EXPECT_EQ(vi(i-1), i);\n    }\n}\n\nTYPED_TEST (VectorNDTest, scalarOperatorTest)\n{\n    static constexpr std::size_t N = TypeParam::value;\n    VectorND< N > obj = getVectorND<N>(3.0);\n\n    auto test1 = obj * 2;\n    auto test2 = 2 * obj;\n    auto test3 = obj / 2;\n    auto test4 = 2 / obj;\n    auto test5 = obj.elemAdd(2);\n    auto test7 = obj.elemSubtract(2);\n    auto test9 = obj;\n    test9 *= 2;\n    auto test10 = obj;\n    test10 /= 2;\n    auto test13 = -obj;\n\n    for (size_t i = 0; i < obj.size (); i++) {\n        EXPECT_DOUBLE_EQ (test1[i], 6.0);\n        EXPECT_DOUBLE_EQ (test2[i], 6.0);\n        EXPECT_DOUBLE_EQ (test3[i], 3.0 / 2.0);\n        EXPECT_DOUBLE_EQ (test4[i], 2.0 / 3.0);\n        EXPECT_DOUBLE_EQ (test5[i], 5.0);\n        EXPECT_DOUBLE_EQ (test7[i], 1.0);\n        EXPECT_DOUBLE_EQ (test9[i], 6.0);\n        EXPECT_DOUBLE_EQ (test10[i], 3.0 / 2.0);\n        EXPECT_DOUBLE_EQ (test13[i], -3.0);\n    }\n}\n\nTYPED_TEST (VectorNDTest, VectorNDOperatorTest)\n{\n    static constexpr std::size_t N = TypeParam::value;\n    VectorND< N > obj1 = getVectorND<N>(3.0);\n    VectorND< N > obj2 = getVectorND<N>(2.0);\n\n    auto test1 = obj1.elemMultiply(obj2);\n    auto test2 = obj1.elemDivide(obj2);\n    auto test3 = obj1 + obj2;\n    auto test4 = obj1 - obj2;\n    auto test7 = obj1;\n    test7 += obj2;\n    auto test8 = obj1;\n    test8 -= obj2;\n\n    for (size_t i = 0; i < obj1.size (); i++) {\n        EXPECT_DOUBLE_EQ (test1[i], 6.0);\n        EXPECT_DOUBLE_EQ (test2[i], 3.0 / 2.0);\n        EXPECT_DOUBLE_EQ (test3[i], 5.0);\n        EXPECT_DOUBLE_EQ (test4[i], 1.0);\n        EXPECT_DOUBLE_EQ (test7[i], 5.0);\n        EXPECT_DOUBLE_EQ (test8[i], 1.0);\n    }\n}\n\nTYPED_TEST (VectorNDTest, EigenOperatorTest)\n{\n    static constexpr std::size_t N = TypeParam::value;\n    VectorND< N > obj1             = getVectorND< N > (3.0);\n    Eigen::Matrix< double, N, 1 > obj2;\n    for (size_t i = 0; i < N; i++) {\n        obj2[i] = 2.0;\n    }\n\n    auto test1  = obj1.elemMultiply(obj2);\n    auto test2  = obj1.elemDivide(obj2);\n    auto test3  = obj1 + obj2;\n    auto test3x = obj2 + obj1;\n    auto test4  = obj1 - obj2;\n    auto test4x = obj2 - obj1;\n    auto test7 = obj1;\n    test7 += obj2;\n    auto test8 = obj1;\n    test8 -= obj2;\n\n    for (size_t i = 0; i < obj1.size (); i++) {\n        EXPECT_DOUBLE_EQ (test1[i], 6.0);\n        EXPECT_DOUBLE_EQ (test2[i], 3.0 / 2.0);\n        EXPECT_DOUBLE_EQ (test3[i], 5.0);\n        EXPECT_DOUBLE_EQ (test3x[i], 5.0);\n        EXPECT_DOUBLE_EQ (test4[i], 1.0);\n        EXPECT_DOUBLE_EQ (test4x[i], -1.0);\n        EXPECT_DOUBLE_EQ (test7[i], 5.0);\n        EXPECT_DOUBLE_EQ (test8[i], 1.0);\n    }\n\n    EXPECT_TRUE (obj1 != obj2);\n    EXPECT_TRUE (obj2 != obj1);\n    EXPECT_FALSE (obj1 == obj2);\n    EXPECT_FALSE (obj2 == obj1);\n    obj2 = obj1.e();\n    EXPECT_TRUE (obj1 == obj2);\n    EXPECT_TRUE (obj2 == obj1);\n    EXPECT_FALSE (obj1 != obj2);\n    EXPECT_FALSE (obj2 != obj1);\n}\n\nTYPED_TEST (VectorNDTest, ComparisonTest)\n{\n    static constexpr std::size_t N = TypeParam::value;\n    const VectorND< N, double > comp1 (getVectorND<N>(true));\n    auto comp2 = comp1;\n    auto comp3 = -comp1;\n    EXPECT_TRUE (comp1 == comp2);\n    EXPECT_FALSE (comp1 != comp2);\n    EXPECT_TRUE (comp1 != comp3);\n    EXPECT_FALSE (comp1 == comp3);\n}\n\nTYPED_TEST (VectorNDTest, MathOperators)\n{\n    static constexpr std::size_t N = TypeParam::value;\n    VectorND< N > obj1 = getVectorND<N>(true);\n    VectorND< N > obj2 = getVectorND<N>(false);\n\n    auto test2 = obj1.dot (obj2);\n    auto test3 = obj1.normalize ();\n\n    EXPECT_EQ (obj1.e ().dot (obj2.e ()), test2);\n    EXPECT_DOUBLE_EQ (test3.norm2 (), 1.0);\n    for(size_t i = 0; i < N; i++){\n        EXPECT_DOUBLE_EQ((test3 * obj1.norm2 ())[i],obj1[i]);\n    }\n}\n", "meta": {"hexsha": "3e57611582e556a50b2925083204b40d1f003cdc", "size": 7063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RobWork/gtest/math/VectorNDTest.cpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/gtest/math/VectorNDTest.cpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/gtest/math/VectorNDTest.cpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9780701754, "max_line_length": 90, "alphanum_fraction": 0.5904006796, "num_tokens": 2271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.5979115088819973}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n    This is an example that shows how you can perform model selection with the\n    dlib C++ Library.  \n\n    It will create a simple dataset and show you how to use cross validation and\n    global optimization to determine good parameters for the purpose of training\n    an svm to classify the data.\n\n    The data used in this example will be 2 dimensional data and will come from a\n    distribution where points with a distance less than 10 from the origin are\n    labeled +1 and all other points are labeled as -1.\n        \n\n    As an side, you should probably read the svm_ex.cpp and matrix_ex.cpp example\n    programs before you read this one.\n*/\n\n\n#include <iostream>\n#include <dlib/svm.h>\n#include <dlib/global_optimization.h>\n\nusing namespace std;\nusing namespace dlib;\n\n\nint main() try\n{\n    // The svm functions use column vectors to contain a lot of the data on which they \n    // operate. So the first thing we do here is declare a convenient typedef.  \n\n    // This typedef declares a matrix with 2 rows and 1 column.  It will be the\n    // object that contains each of our 2 dimensional samples.   \n    typedef matrix<double, 2, 1> sample_type;\n\n\n\n    // Now we make objects to contain our samples and their respective labels.\n    std::vector<sample_type> samples;\n    std::vector<double> labels;\n\n    // Now let's put some data into our samples and labels objects.  We do this\n    // by looping over a bunch of points and labeling them according to their\n    // distance from the origin.\n    for (double r = -20; r <= 20; r += 0.8)\n    {\n        for (double c = -20; c <= 20; c += 0.8)\n        {\n            sample_type samp;\n            samp(0) = r;\n            samp(1) = c;\n            samples.push_back(samp);\n\n            // if this point is less than 10 from the origin\n            if (sqrt(r*r + c*c) <= 10)\n                labels.push_back(+1);\n            else\n                labels.push_back(-1);\n        }\n    }\n\n    cout << \"Generated \" << samples.size() << \" points\" << endl;\n\n\n    // Here we normalize all the samples by subtracting their mean and dividing by their\n    // standard deviation.  This is generally a good idea since it often heads off\n    // numerical stability problems and also prevents one large feature from smothering\n    // others.  Doing this doesn't matter much in this example so I'm just doing this here\n    // so you can see an easy way to accomplish this with the library.  \n    vector_normalizer<sample_type> normalizer;\n    // let the normalizer learn the mean and standard deviation of the samples\n    normalizer.train(samples);\n    // now normalize each sample\n    for (unsigned long i = 0; i < samples.size(); ++i)\n        samples[i] = normalizer(samples[i]); \n\n\n    // Now that we have some data we want to train on it.  We are going to train a\n    // binary SVM with the RBF kernel to classify the data.  However, there are\n    // three parameters to the training.  These are the SVM C parameters for each\n    // class and the RBF kernel's gamma parameter.  Our choice for these\n    // parameters will influence how good the resulting decision function is.  To\n    // test how good a particular choice of these parameters is we can use the\n    // cross_validate_trainer() function to perform n-fold cross validation on our\n    // training data.  However, there is a problem with the way we have sampled\n    // our distribution above.  The problem is that there is a definite ordering\n    // to the samples.  That is, the first half of the samples look like they are\n    // from a different distribution than the second half.  This would screw up\n    // the cross validation process, but we can fix it by randomizing the order of\n    // the samples with the following function call.\n    randomize_samples(samples, labels);\n\n\n    // And now we get to the important bit.  Here we define a function,\n    // cross_validation_score(), that will do the cross-validation we\n    // mentioned and return a number indicating how good a particular setting\n    // of gamma, c1, and c2 is.\n    auto cross_validation_score = [&](const double gamma, const double c1, const double c2) \n    {\n        // Make a RBF SVM trainer and tell it what the parameters are supposed to be.\n        typedef radial_basis_kernel<sample_type> kernel_type;\n        svm_c_trainer<kernel_type> trainer;\n        trainer.set_kernel(kernel_type(gamma));\n        trainer.set_c_class1(c1);\n        trainer.set_c_class2(c2);\n\n        // Finally, perform 10-fold cross validation and then print and return the results.\n        matrix<double> result = cross_validate_trainer(trainer, samples, labels, 10);\n        cout << \"gamma: \" << setw(11) << gamma << \"  c1: \" << setw(11) << c1 <<  \"  c2: \" << setw(11) << c2 <<  \"  cross validation accuracy: \" << result;\n\n        // Now return a number indicating how good the parameters are.  Bigger is\n        // better in this example.  Here I'm returning the harmonic mean between the\n        // accuracies of each class.  However, you could do something else.  For\n        // example, you might care a lot more about correctly predicting the +1 class,\n        // so you could penalize results that didn't obtain a high accuracy on that\n        // class.  You might do this by using something like a weighted version of the\n        // F1-score (see http://en.wikipedia.org/wiki/F1_score).     \n        return 2*prod(result)/sum(result);\n    };\n\n\n    // And finally, we call this global optimizer that will search for the best parameters.\n    // It will call cross_validation_score() 30 times with different settings and return\n    // the best parameter setting it finds.  find_max_global() uses a global optimization\n    // method based on a combination of non-parametric global function modeling and\n    // quadratic trust region modeling to efficiently find a global maximizer.  It usually\n    // does a good job with a relatively small number of calls to cross_validation_score().\n    // In this example, you should observe that it finds settings that give perfect binary\n    // classification of the data.\n    auto result = find_max_global(cross_validation_score, \n                                  {1e-5, 1e-5, 1e-5},  // lower bound constraints on gamma, c1, and c2, respectively\n                                  {100,  1e6,  1e6},   // upper bound constraints on gamma, c1, and c2, respectively\n                                  max_function_calls(30));\n\n    double best_gamma = result.x(0);\n    double best_c1    = result.x(1);\n    double best_c2    = result.x(2);\n\n    cout << \" best cross-validation score: \" << result.y << endl;\n    cout << \" best gamma: \" << best_gamma << \"   best c1: \" << best_c1 << \"    best c2: \"<< best_c2  << endl;\n}\ncatch (exception& e)\n{\n    cout << e.what() << endl;\n}\n\n", "meta": {"hexsha": "81a975c18f6294db6690074ecdd58454ab99d560", "size": 6865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/model_selection_ex.cpp", "max_stars_repo_name": "dittovto/dlib", "max_stars_repo_head_hexsha": "4485543e7378a849ab192565e4f1fd109838b57f", "max_stars_repo_licenses": ["BSL-1.0"], "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/model_selection_ex.cpp", "max_issues_repo_name": "dittovto/dlib", "max_issues_repo_head_hexsha": "4485543e7378a849ab192565e4f1fd109838b57f", "max_issues_repo_licenses": ["BSL-1.0"], "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/model_selection_ex.cpp", "max_forks_repo_name": "dittovto/dlib", "max_forks_repo_head_hexsha": "4485543e7378a849ab192565e4f1fd109838b57f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.0738255034, "max_line_length": 154, "alphanum_fraction": 0.6664238893, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5979115061607693}}
{"text": "#pragma once\n#include <Eigen/Dense>\n\ninline void make_first_positive(Eigen::VectorXi& v)\n{\n\tfor(uint32_t n = 0; n < v.size(); ++ n) \n\t{\n\t\tif(v(n) == 0)\n\t\t\tcontinue;\n\t\tif(v(n) < 0)\n\t\t{\n\t\t\tv *= -1;\n\t\t\treturn ;\n\t\t}\n\t\telse\n\t\t\treturn ;\n\t}\n}\n\n\nstruct hash_vector\n{\n\tsize_t operator()(const Eigen::VectorXi& v) const\n\t{\n\t\tstd::size_t seed = v.size();\n\t\tfor(uint32_t n = 0; n < v.size(); ++ n) {\n\t\t\tseed ^= abs(v(n)) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n\t\t}\n\t\treturn seed;\n\t}\n};\n\nint powi(int base, unsigned int exp)\n{\n    int res = 1;\n    while (exp) {\n        if (exp & 1)\n            res *= base;\n        exp >>= 1;\n        base *= base;\n    }\n    return res;\n}\n\ntemplate<typename UINT, template<typename> class Basis>\nEigen::MatrixXd basisMatrix(const Basis<UINT>& basis)\n{\n\tEigen::MatrixXd res = Eigen::MatrixXd::Zero(1u << basis.getN(), basis.getDim());\n\tfor(unsigned int n = 0; n < basis.getDim(); ++n)\n\t{\n\t\tauto bvec = basis.basisVec(n);\n\t\tfor(const auto p: bvec)\n\t\t{\n\t\t\tres(p.first, n) = p.second;\n\t\t}\n\t}\n\treturn res;\n}\n\ntemplate<typename Basis>\nEigen::VectorXd flip(Basis&& basis, const Eigen::VectorXd& r)\n{\n\tEigen::VectorXd res(r.size());\n\tfor(int i = 0; i < r.size(); i++)\n\t{\n\t\tres(basis.flip(i)) = r(i);\n\t}\n\treturn res;\n}\n\n\n", "meta": {"hexsha": "9cbe9d05a47b60018d4908f4b1e4c42770487a6f", "size": 1235, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/utils.hpp", "max_stars_repo_name": "chaeyeunpark/ExactDiagonalization", "max_stars_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T08:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:47:05.000Z", "max_issues_repo_path": "tests/utils.hpp", "max_issues_repo_name": "chaeyeunpark/ExactDiagonalization", "max_issues_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T19:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T19:02:14.000Z", "max_forks_repo_path": "tests/utils.hpp", "max_forks_repo_name": "chaeyeunpark/ExactDiagonalization", "max_forks_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-22T18:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T18:59:11.000Z", "avg_line_length": 17.1527777778, "max_line_length": 81, "alphanum_fraction": 0.5668016194, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.5978571444878782}}
{"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": "#ifndef MLT_UTILS_LINEAR_SOLVERS_HPP\n#define MLT_UTILS_LINEAR_SOLVERS_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/SVD>\n\n#include \"../defs.hpp\"\n\nnamespace mlt {\nnamespace utils {\nnamespace linear_solvers {\n\ttemplate <typename ConcreteSolver, typename SolverImplementation>\n\tclass BaseSolver {\n\tpublic:\n\t\tConcreteSolver& compute(MatrixXdRef A) {\n\t\t\t_solver.compute(A);\n\t\t\treturn static_cast<ConcreteSolver&>(*this);\n\t\t}\n\n\t\tauto solve(MatrixXdRef B) const {\n\t\t\treturn MatrixXd{_solver.solve(B)};\n\t\t}\n\n\tprotected:\n\t\tBaseSolver() = default;\n\n\t\tSolverImplementation _solver;\n\t};\n\n\tclass CGSolver : public BaseSolver<CGSolver, ConjugateGradient<MatrixXd>> {};\n\n\tclass LLTSolver : public BaseSolver<LLTSolver, LLT<MatrixXd>> {};\n\n\tclass LDLTSolver : public BaseSolver<LDLTSolver, LDLT<MatrixXd>> {};\n\n\tclass SVDSolver : public BaseSolver<SVDSolver, JacobiSVD<MatrixXd>>\t{\n\tpublic:\n\t\tSVDSolver& compute(MatrixXdRef A) {\n\t\t\t_solver.compute(A, ComputeThinU | ComputeThinV);\n\t\t\treturn *this;\n\t\t}\n\t};\n}\n}\n}\n#endif", "meta": {"hexsha": "1dc6f68db9c52b90397cf14760cdb250205d65b1", "size": 1065, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/utils/linear_solvers.hpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/mlt/utils/linear_solvers.hpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlt/utils/linear_solvers.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": 22.1875, "max_line_length": 78, "alphanum_fraction": 0.744600939, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.682573734412324, "lm_q1q2_score": 0.5977891974388737}}
{"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 * 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\n#include \"gtest/gtest.h\"\n#include \"delfem2/view_vectorx.h\"\n#include \"delfem2/lsmats.h\"\n#include \"delfem2/lsilu_mats.h\"\n#include \"delfem2/vecxitrsol.h\"\n#include \"delfem2/femsolidlinear.h\"\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\n\n// ------------------------------------------\n\nvoid MakeMesh(\n    std::vector<double>& aXY1,\n    std::vector<unsigned int>& aTri1,\n    std::vector<int>& aBCFlag,\n    double elen,\n    unsigned int ndimval)\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,elen,elen);\n  MeshTri2D_Export(\n      aXY1,aTri1,\n      aVec2,aETri);\n  const unsigned int np = aXY1.size()/2;\n  aBCFlag.assign(np*ndimval, 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<ndimval;++idim) {\n      aBCFlag[ip * 2 + idim] = 1;\n    }\n  }\n//  std::cout<<\"  ntri;\"<<aTri1.size()/3<<\"  nXY:\"<<aXY1.size()/2<<std::endl;\n}\n\nTEST(ls,test1)\n{\n  namespace dfm2 = delfem2;\n  const double epsilon = 1.0e-5;\n  //\n  std::vector<unsigned int> aTri1;\n  std::vector<double> aXY1;\n  std::vector<int> aBCFlag;\n  MakeMesh(\n      aXY1,aTri1,aBCFlag,\n      0.08, 2);\n  const unsigned int np = aXY1.size()/2;\n  const unsigned int nDoF = np*2;\n  const std::vector<double> aVal(nDoF,0);\n  // -----------\n  delfem2::CMatrixSparseBlock<Eigen::Matrix2d,Eigen::aligned_allocator<Eigen::Matrix2d>> Aeig;\n  Eigen::VectorXd Veig0(nDoF);\n  Eigen::Matrix<double,-1,2,Eigen::RowMajor> Veig1(np,2);\n  dfm2::CMatrixSparse<double> Astd;\n  std::vector<double> Vstd(nDoF);\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    Aeig.Initialize(np);\n    Aeig.SetPattern(psup_ind0.data(), psup_ind0.size(), psup0.data(), psup0.size());\n    const double myu = 10.0, lambda = 10.0, rho = 1.0, g_x = 0.0, g_y = -3.0;\n    Aeig.setZero();\n    Veig0.setZero();\n    dfm2::MergeLinSys_SolidLinear_Static_MeshTri2D(\n        Aeig, Veig0.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(Aeig, aBCFlag.data(), 1.f);\n    SetFixedBC_Col(Aeig, aBCFlag.data());\n    SetFixedBC_Row(Aeig, aBCFlag.data());\n    delfem2::setZero_Flag(Veig0, aBCFlag, 0);\n    // ----------\n    for(unsigned int ip=0;ip<np;++ip){\n      Veig1(ip,0) = Veig0(ip*2+0);\n      Veig1(ip,1) = Veig0(ip*2+1);\n    }\n    // ----------\n    Astd.Initialize(np, 2, true);\n    Astd.SetPattern(psup_ind0.data(), psup_ind0.size(), psup0.data(), psup0.size());\n    Astd.setZero();\n    Vstd.assign(nDoF,0.0);\n    dfm2::MergeLinSys_SolidLinear_Static_MeshTri2D(\n        Astd, Vstd.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    Astd.SetFixedBC(aBCFlag.data());\n    dfm2::setRHS_Zero(Vstd, aBCFlag, 0);\n  }\n  // ---------------\n  double conv_ratio = 1.0e-6;\n  int iteration = 10000;\n  {\n    const unsigned int max_itr = 10;\n    const auto time0 = std::chrono::system_clock::now();\n    unsigned int nitr1 = 0;\n    for(int itr=0;itr<max_itr;++itr){ // CG method std::vector\n      const std::size_t n = Vstd.size();\n      std::vector<double> tmp0(n), tmp1(n), vx1(n), vB1(n);\n      vB1 = Vstd;\n      std::vector<double> aConv = Solve_CG(\n          dfm2::ViewAsVectorXd(vB1),\n          dfm2::ViewAsVectorXd(vx1),\n          dfm2::ViewAsVectorXd(tmp0),\n          dfm2::ViewAsVectorXd(tmp1),\n          conv_ratio, iteration, Astd);\n      nitr1 = aConv.size();\n    }\n    const auto time1 = std::chrono::system_clock::now();\n    // ---------------\n    unsigned int nitr0 = 0;\n    for(int itr=0;itr<max_itr;++itr){ // CG method with eigen\n      const std::size_t n = Veig0.size();\n      Eigen::VectorXd tmp0(n), tmp1(n), vx0(n), vB0(n);\n      vB0 = Veig0;\n      std::vector<double> aConv = delfem2::Solve_CG(\n          vB0, vx0, tmp0, tmp1,\n          conv_ratio, iteration, Aeig);\n      nitr0 = aConv.size();\n    }\n    const auto time2 = std::chrono::system_clock::now();\n    // ---------------\n    unsigned int nitr2 = 0;\n    for(int itr=0;itr<max_itr;++itr){ // CG method with eigen\n      Eigen::Matrix<double,-1,2,Eigen::RowMajor> tmp0(np,2), tmp1(np,2), vx0(np,2), vB0(np,2);\n      vB0 = Veig1;\n      std::vector<double> aConv = delfem2::Solve_CG(\n          vB0, vx0, tmp0, tmp1,\n          conv_ratio, iteration, Aeig);\n      nitr2 = aConv.size();\n    }\n    const auto time3 = std::chrono::system_clock::now();\n    EXPECT_NEAR(nitr0,nitr1,10);\n    EXPECT_NEAR(nitr1,nitr2,10);\n    long long elapsed01 = std::chrono::duration_cast<std::chrono::milliseconds>(time1 - time0).count();\n    long long elapsed12 = std::chrono::duration_cast<std::chrono::milliseconds>(time2 - time1).count();\n    long long elapsed23 = std::chrono::duration_cast<std::chrono::milliseconds>(time3 - time2).count();\n    std::cout << \"cg std::vector: \" << elapsed01 << \" \" << nitr0 << std::endl;\n    std::cout << \"cg eigen vec: \" << elapsed12 << \" \" << nitr1 << std::endl;\n    std::cout << \"cg eigen mat: \" << elapsed23 << \" \" << nitr2 << std::endl;\n  }\n  delfem2::CILU_SparseBlock<Eigen::Matrix2d,Eigen::aligned_allocator<Eigen::Matrix2d>> ilu0;\n  delfem2::CPreconditionerILU<double> ilu1;\n  { // LU\n    ilu1.SetPattern0(Astd);\n    ilu1.CopyValue(Astd);\n    ilu1.Decompose();\n    delfem2::ILU_SetPattern0(ilu0, Aeig);\n    delfem2::ILU_CopyValue(ilu0, Aeig);\n    delfem2::ILU_Decompose(ilu0);\n    // check if the entry is the same\n    for(unsigned int icrs=0;icrs<ilu0.valCrs.size();++icrs) {\n      EXPECT_NEAR(ilu0.valCrs[icrs](0, 0), ilu1.valCrs[icrs * 4 + 0], epsilon);\n      EXPECT_NEAR(ilu0.valCrs[icrs](0, 1), ilu1.valCrs[icrs * 4 + 1], epsilon);\n      EXPECT_NEAR(ilu0.valCrs[icrs](1, 0), ilu1.valCrs[icrs * 4 + 2], epsilon);\n      EXPECT_NEAR(ilu0.valCrs[icrs](1, 1), ilu1.valCrs[icrs * 4 + 3], epsilon);\n    }\n    for(unsigned int iblk=0;iblk<ilu0.valDia.size();++iblk) {\n      EXPECT_NEAR(ilu0.valDia[iblk](0, 0), ilu1.valDia[iblk * 4 + 0], epsilon);\n      EXPECT_NEAR(ilu0.valDia[iblk](0, 1), ilu1.valDia[iblk * 4 + 1], epsilon);\n      EXPECT_NEAR(ilu0.valDia[iblk](1, 0), ilu1.valDia[iblk * 4 + 2], epsilon);\n      EXPECT_NEAR(ilu0.valDia[iblk](1, 1), ilu1.valDia[iblk * 4 + 3], epsilon);\n    }\n  }\n  {\n    const auto time0 = std::chrono::system_clock::now();\n    const unsigned int max_itr = 10;\n    unsigned int nitr1 = 0;\n    for (int itr = 0; itr < max_itr; ++itr) { // solve with ILU-CG std::vector\n      ilu1.CopyValue(Astd);\n      ilu1.Decompose();\n      const std::size_t n = Vstd.size();\n      std::vector<double> tmp0(n), tmp1(n), vx1(n), vB1(n);\n      vB1 = Vstd;\n      std::vector<double> aConv = Solve_PCG(\n          dfm2::ViewAsVectorXd(vB1),\n          dfm2::ViewAsVectorXd(vx1),\n          dfm2::ViewAsVectorXd(tmp0),\n          dfm2::ViewAsVectorXd(tmp1),\n          conv_ratio, iteration, Astd, ilu1);\n      nitr1 = aConv.size();\n    }\n    const auto time1 = std::chrono::system_clock::now();\n    unsigned int nitr0 = 0;\n    for (int itr = 0; itr < max_itr; ++itr) { // solve with ILU-CG Eigen\n      delfem2::ILU_CopyValue(ilu0, Aeig);\n      delfem2::ILU_Decompose(ilu0);\n      const std::size_t n = Vstd.size();\n      Eigen::VectorXd tmp0(n), tmp1(n), vx0(n), vB0(n);\n      vB0 = Veig0;\n      std::vector<double> aConv = Solve_PCG(\n          vB0, vx0, tmp0, tmp1,\n          conv_ratio, iteration, Aeig, ilu0);\n      nitr0 = aConv.size();\n    }\n    const auto time2 = std::chrono::system_clock::now();\n    unsigned int nitr2 = 0;\n    for (int itr = 0; itr < max_itr; ++itr) { // solve with ILU-CG Eigen\n      delfem2::ILU_CopyValue(ilu0, Aeig);\n      delfem2::ILU_Decompose(ilu0);\n      Eigen::Matrix<double,-1,2,Eigen::RowMajor> tmp0(np,2), tmp1(np,2), vx0(np,2), vB0(np,2);\n      vB0 = Veig1;\n      std::vector<double> aConv = Solve_PCG(\n          vB0, vx0, tmp0, tmp1,\n          conv_ratio, iteration, Aeig, ilu0);\n      nitr2 = aConv.size();\n    }\n    const auto time3 = std::chrono::system_clock::now();\n    EXPECT_NEAR(nitr0,nitr1,10);\n    EXPECT_NEAR(nitr1,nitr2,10);\n    double elapsed01 = std::chrono::duration_cast<std::chrono::milliseconds>(time1 - time0).count();\n    double elapsed12 = std::chrono::duration_cast<std::chrono::milliseconds>(time2 - time1).count();\n    double elapsed23 = std::chrono::duration_cast<std::chrono::milliseconds>(time3 - time2).count();\n    std::cout << \"ilu-cg std::vector: \" << elapsed01 << \" \" << nitr0 << std::endl;\n    std::cout << \"ilu-cg eigen vec: \" << elapsed12 << \" \" << nitr1 << std::endl;\n    std::cout << \"ilu-cg eigen mat: \" << elapsed23 << \" \" << nitr2 << std::endl;\n  }\n}\n\nint main(int argc, char **argv)\n{\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "0f4387c9488aa52b423486ac3dc428f5bcedf3c2", "size": 9718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_eigen/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": "test_eigen/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": "test_eigen/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": 36.9505703422, "max_line_length": 103, "alphanum_fraction": 0.6101049599, "num_tokens": 3381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5977249668032835}}
{"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": "\r\n\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n#include <boost/format.hpp>\r\n\r\ntypedef boost::numeric::ublas::matrix<float> Matrix44;\r\n\r\n\r\nvoid Out(const char *const message)\r\n{\r\n\t\r\n}\r\n\r\n\r\nint main()\r\n{\r\n\tMatrix44 matrix = boost::numeric::ublas::identity_matrix<float> (4);\r\n\r\n\tOut(std::cout << matrix);\r\n\t//std::cout << matrix << std::endl;\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "95ce795c4085d8d4ee38838e2ee3259150c5f1b7", "size": 402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/IOTest/IOConfig.cpp", "max_stars_repo_name": "taku-xhift/labo", "max_stars_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/IOTest/IOConfig.cpp", "max_issues_repo_name": "taku-xhift/labo", "max_issues_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/IOTest/IOConfig.cpp", "max_forks_repo_name": "taku-xhift/labo", "max_forks_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.8888888889, "max_line_length": 70, "alphanum_fraction": 0.6368159204, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5977249537340125}}
{"text": "#include <iostream>\n\n#include <Eigen/Core>\n\n#include \"lib/utilities.h\"\n#include \"lib/pose_estimation.h\"\n\n\n#define DEBUG\n\nusing namespace std;\n\n\nbool testQuaternionFromMatrix() {\n  Eigen::Matrix4f mat;\n  mat << 0, 0, 1, 0,\n    1, 0, 0, 0,\n    0, 1, 0, 0,\n    0, 0, 0, 1;\n  Eigen::Quaternion<float> q;\n  Utilities::quaternionFromMatrix(mat, q);\n  cout << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" << q.w() << \" \" << endl;\n}\n\nbool testCVRotatedRect() {\n  PointCloudMono::Ptr hull(new PointCloudMono);\n  hull->points.resize(4);\n//  pcl::PointXYZ v0{1, 2, 0};\n//  pcl::PointXYZ v1{1, -2, 0};\n//  pcl::PointXYZ v2{-1, -2, 0};\n//  pcl::PointXYZ v3{-1, 2, 0};\n\n  // 70 deg\n  pcl::PointXYZ v0{-1.5373651,  1.62373291, 0};\n  pcl::PointXYZ v1{2.22140538, 0.25565233, 0};\n  pcl::PointXYZ v2{1.5373651, -1.62373291, 0};\n  pcl::PointXYZ v3{-2.22140538, -0.25565233, 0};\n\n  hull->points[0] = v0;\n  hull->points[1] = v1;\n  hull->points[2] = v2;\n  hull->points[3] = v3;\n\n  vector<pcl::PointXY> rect;\n  pcl::PointXY center{};\n  pcl::PointXY edge_center{};\n  float width, height, rotation;\n  Utilities::getRotatedRect2D(hull, rect,center,edge_center,width,height,rotation);\n}\n\n\nint main(int argc, char **argv)\n{\n  PointCloudMono::Ptr contour(new PointCloudMono);\n  contour->points.resize(4);\n  contour->points[0].x = 1;\n  contour->points[0].y = 1;\n  contour->points[0].z = -1;\n  contour->points[1].x = 1;\n  contour->points[1].y = -1;\n  contour->points[1].z = -1;\n  contour->points[2].x = -1;\n  contour->points[2].y = -1;\n  contour->points[2].z = -1;\n  contour->points[3].x = -1;\n  contour->points[3].y = 1;\n  contour->points[3].z = -1;\n\n  pcl::PointXY p{0.9, 0};\n  bool ok = Utilities::isInContour(contour, p);\n  cout << \"res 1: \" << ok << endl;  // should be true\n\n  p.x = 2;\n  p.y = 0;\n  ok = Utilities::isInContour(contour, p);\n  cout << \"res 2: \" << ok << endl;  // should be false\n\n  p.x = 1;\n  p.y = 0;\n  ok = Utilities::isInContour(contour, p);\n  cout << \"res 3: \" << ok << endl;  // should be true\n\n  testQuaternionFromMatrix();\n\n  testCVRotatedRect();\n\n//  float dsp_th = 0.005f;\n//  PoseEstimation *pe = new PoseEstimation(dsp_th);\n//  std::string scene_path = \"/home/dzp/scene.pcd\";\n//  PointCloudN::Ptr scene_cloud(new PointCloudN);\n//  pcl::io::loadPCDFile<PointN>(scene_path, *scene_cloud);\n//\n//  Eigen::Matrix4f trans;\n//  pe->estimate(scene_cloud, trans, true);\n\n\n  return 0;\n}\n\n", "meta": {"hexsha": "4cacb4a58a95be29062aabcfbafd4d28e446f34a", "size": 2380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hope_test.cpp", "max_stars_repo_name": "DrawZeroPoint/hope", "max_stars_repo_head_hexsha": "b41f2c3691127f6f760cf6eededb3911fa3efca3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T04:57:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T15:12:12.000Z", "max_issues_repo_path": "src/hope_test.cpp", "max_issues_repo_name": "DrawZeroPoint/hope", "max_issues_repo_head_hexsha": "b41f2c3691127f6f760cf6eededb3911fa3efca3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-06-06T00:03:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-15T02:53:40.000Z", "max_forks_repo_path": "src/hope_test.cpp", "max_forks_repo_name": "DrawZeroPoint/hope", "max_forks_repo_head_hexsha": "b41f2c3691127f6f760cf6eededb3911fa3efca3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T14:55:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T05:27:48.000Z", "avg_line_length": 23.8, "max_line_length": 83, "alphanum_fraction": 0.6100840336, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5977249486646915}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\n  Matrix3f m = Matrix3f::Random();\n  std::ptrdiff_t i, j;\n  float minOfM = m.minCoeff(&i,&j);\n  cout << \"Here is the matrix m:\\n\" << m << endl;\n  cout << \"Its minimum coefficient (\" << minOfM \n       << \") is at position (\" << i << \",\" << j << \")\\n\\n\";\n\n  RowVector4i v = RowVector4i::Random();\n  int maxOfV = v.maxCoeff(&i);\n  cout << \"Here is the vector v: \" << v << endl;\n  cout << \"Its maximum coefficient (\" << maxOfV \n       << \") is at position \" << i << endl;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "e65c8e903f423ebe69b7f1108f16e55e24d2035b", "size": 1001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_tut_arithmetic_redux_minmax.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_tut_arithmetic_redux_minmax.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_tut_arithmetic_redux_minmax.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8055555556, "max_line_length": 224, "alphanum_fraction": 0.6243756244, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.5977035967098777}}
{"text": "//=======================================================================\n// Copyright 2000 University of Notre Dame.\n// Authors: 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\n\n#include <boost/config.hpp>\n#include <set>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/edge_connectivity.hpp>\n\nusing namespace boost;\n\nint\nmain()\n{\n  const int N = 8;\n  typedef adjacency_list<vecS, vecS, undirectedS> UndirectedGraph;\n  UndirectedGraph g(N);\n\n  add_edge(0, 1, g);\n  add_edge(0, 2, g);\n  add_edge(0, 3, g);\n  add_edge(1, 2, g);\n  add_edge(1, 3, g);\n  add_edge(2, 3, g);\n  add_edge(3, 4, g);\n  add_edge(3, 7, g);\n  add_edge(4, 5, g);\n  add_edge(4, 6, g);\n  add_edge(4, 7, g);\n  add_edge(5, 6, g);\n  add_edge(5, 7, g);\n  add_edge(6, 7, g);\n\n  typedef graph_traits<UndirectedGraph>::edge_descriptor edge_descriptor;\n  typedef graph_traits<UndirectedGraph>::degree_size_type degree_size_type;\n  std::vector<edge_descriptor> disconnecting_set;\n\n  degree_size_type c = edge_connectivity(g, std::back_inserter(disconnecting_set));\n\n  std::cout << \"The edge connectivity is \" << c << \".\" << std::endl;\n  std::cout << \"The disconnecting set is {\";\n\n  std::copy(disconnecting_set.begin(), disconnecting_set.end(),\n            std::ostream_iterator<edge_descriptor>(std::cout, \" \"));\n  std::cout << \"}.\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "3a77e4dd60f61470ecf36517ca9493c83c6ea231", "size": 1630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/edge_connectivity.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/edge_connectivity.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/edge_connectivity.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": 28.1034482759, "max_line_length": 83, "alphanum_fraction": 0.6251533742, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.5976948505704185}}
{"text": "#ifndef KRAVERAGER_H\n#define KRAVERAGER_H\n\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <math.h>\n\n/**\n * @class KRAverager\n */\nclass KRAverager {\n    public:\n        KRAverager();\n\n        /**\n         * @param threshold\n         */\n        KRAverager(int threshold);\n\n        /**\n         * @param force_constant\n         * @param range\n         */\n        virtual void add_force_constant_tuple(double force_constant, double range);\n\n        /**\n         * @param force_constants\n         * @param ranges\n         */\n        virtual void add_force_constant_vector(const Eigen::VectorXd &force_constants, const Eigen::VectorXd &ranges);\n\n        /**\n         * @return the average range\n         */\n        double get_average_range() const;\n\n        /**\n         * @return the average force constant\n         */\n        double get_average_force_constant() const;\n\n        /**\n         * @return first error\n         */\n        double get_error_1() const;\n\n        /**\n         * @return second error\n         */\n        double get_error_2() const;\n    protected:\n        int threshold;\n        bool use_threshold = false;\n        double r_sum = 0;\n        double k_sum = 0;\n        double error_sum = 0;\n        long count = 0;\n};\n\n/**\n * @class KRAveragerCis\n */\nclass KRAveragerCis : public KRAverager {\n    public:\n        KRAveragerCis() : KRAverager() {};\n        KRAveragerCis(int threshhold) : KRAverager(threshhold) {};\n\n        /**\n         * @param force_constant\n         * @param range\n         */\n        void add_force_constant_tuple(double k, double r);\n\n        /**\n         * @param force_constants\n         * @param ranges\n         */\n        void add_force_constant_vector(const Eigen::VectorXd & ks, const Eigen::VectorXd & rs);\n\n        /**\n         * @return range cis\n         */\n        double get_range_cis() const;\n\n        /**\n         * @return force constant cis\n         */\n        double get_force_constant_cis() const;\n    private:\n        double cis_count = 0;\n        double r_cis_sum = 0;\n        double k_cis_sum = 0;\n};\n\n#endif\n\n// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n", "meta": {"hexsha": "b95191c3a99aca7dc704efb2b153d0e89bfbdba2", "size": 2129, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/KRAverager.hpp", "max_stars_repo_name": "AFriemann/LowCarb", "max_stars_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/KRAverager.hpp", "max_issues_repo_name": "AFriemann/LowCarb", "max_issues_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-15T13:57:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-15T13:57:26.000Z", "max_forks_repo_path": "src/KRAverager.hpp", "max_forks_repo_name": "AFriemann/LowCarb", "max_forks_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5050505051, "max_line_length": 118, "alphanum_fraction": 0.5448567403, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5976948361987046}}
{"text": "#include <array>\n#include <vector>\n#include \"plane3d.hpp\"\n#include \"found_path.hpp\"\n#include \"mesh_components.hpp\"\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\n#ifndef MESH_HPP\n#define MESH_HPP\n\nclass Mesh {\n    vector<Vertex3d> vertices;\n    vector<Tetrahedron> tetrahedrons;\n    vector<Face> faces;\n    Vector3d target;\n    unsigned long int targetTetId;\n    //used for testing\n    vector<int> sliceIds;\n  public:\n    Mesh (const int numVertices, const int numFaces, const int numCells);\n    void setVertices(const vector<array<double, 3>> & _vertices);\n    void addTetrahedron(const int id, const array<int, 4> vertexIds, const vector<unsigned long int> neighborIds, const double weight, const int label);\n    void addFace(const array<int, 3> vertexIds, const int tetId);\n    bool setTarget(const array<double, 3> _target);\n    vector<Shape3d> slice(Plane3d plane, vector<int> &tetsChecked);\n    vector<FoundPath> shortestPaths(const int epsilon, const int numThreads, double distBound);\n    vector<Shape3d> computeSliceComponent(Plane3d plane, vector<int> &tetsChecked, unsigned long int initTet);\n    vector<Shape3d> sliceIndv(array<double, 2> rotation);\n    vector<FoundPath> findPaths(vector<Plane3d> planes, double distBound);\n    //these functions are exposed to Python for testing purposes; while it is possible that a python application may require them, they are not required for any other purpose in this application\n    unsigned long int getTargetTetId();\n};\n\n#endif\n\n", "meta": {"hexsha": "32da4e5734ce2a2ec23a21d55c02bc92463684f6", "size": 1506, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mesh.hpp", "max_stars_repo_name": "myociss/pathfinder", "max_stars_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mesh.hpp", "max_issues_repo_name": "myociss/pathfinder", "max_issues_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mesh.hpp", "max_forks_repo_name": "myociss/pathfinder", "max_forks_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6153846154, "max_line_length": 194, "alphanum_fraction": 0.7490039841, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5976948361987046}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// standard_error_iid.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_STANDARD_ERROR_IID_HPP_ER_2008_04\n#define BOOST_ACCUMULATORS_STATISTICS_STANDARD_ERROR_IID_HPP_ER_2008_04\n#include <cmath>\n\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/placeholders.hpp>\n\n#include <boost/call_traits.hpp>\n//#include <boost/assert.hpp>\n#include <boost/array.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/type_traits/add_const.hpp>\n\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n\n#include <boost/accumulators/statistics/acv0.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n\nnamespace boost { namespace accumulators\n{\n\n\nnamespace impl\n{\n    ////////////////////////////////////////////////////////////////////////////\n    // standard_error_iid\n    template<typename T,typename I>\n    class standard_error_iid_impl\n      : public accumulator_base\n    {\n    public:\n        typedef T result_type;\n\n        standard_error_iid_impl(dont_care)\n        {}\n\n        template<typename Args>\n        void operator()(Args const &args)\n        {\n            T acv0_val = acv0<I>(args[accumulator]);\n            T n = (T)(count(args));\n            val = static_cast<T>(0);\n            if((acv0_val>static_cast<T>(0)) && (n>static_cast<T>(0))){val = sqrt(acv0_val/n);}\n        }\n\n\n        result_type result(dont_care) const\n        {\n            return val;\n        }\n    private:\n        T val;\n    };\n\n} // namespace impl\n///////////////////////////////////////////////////////////////////////////////\n// tag::standard_error_iid\n//\n\nnamespace tag\n{\n    template <typename I = default_delay_discriminator>\n    struct standard_error_iid\n      : depends_on<count,acv0<I> >\n    {\n        /// INTERNAL ONLY\n      typedef\n        accumulators::impl::standard_error_iid_impl<\n            mpl::_1,I> impl;\n\n    };\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::standard_error_iid\n//\n\nnamespace extract\n{\n\n//  extractor<tag::standard_error_iid<> >\n//    const standard_error_iid = {};\n\n  // see acvf about default_delay_discriminator\n  template<typename I,typename AccumulatorSet>\n  typename mpl::apply<\n    AccumulatorSet,tag::standard_error_iid<I>\n    >::type::result_type\n  standard_error_iid(AccumulatorSet const& acc){\n    typedef tag::standard_error_iid<I> the_tag;\n    return extract_result<the_tag>(acc);\n  }\n\n//  TODO\n//  overload (default) see acvf\n\n}\n\nusing extract::standard_error_iid;\n\n}}\n\n#endif\n", "meta": {"hexsha": "9db7f02a2dae66f12f300d5fa1ff78e12231a506", "size": 3358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "autocovariance/boost/accumulators/statistics/standard_error_iid.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/standard_error_iid.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/standard_error_iid.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.9833333333, "max_line_length": 94, "alphanum_fraction": 0.580405003, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5976948279913157}}
{"text": "// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n#include <OpenTissue/core/spline/spline.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n\n// Boost Test declaration and Checking macros\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/test_tools.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\ntypedef OpenTissue::spline::MathTypes<double, size_t>    math_types;\ntypedef math_types::vector_type                                vector_type;\ntypedef std::vector<double>                                    knot_container;\ntypedef std::vector<vector_type>                               point_container;\n\ntypedef OpenTissue::spline::NUBSpline<knot_container, point_container> spline_type;\n\nBOOST_AUTO_TEST_SUITE(opentissue_spline_make_cubic_interpolation);\n\nBOOST_AUTO_TEST_CASE(test_make_cubic_interpolation)\n{\n  point_container X;\n\n  vector_type p0(2);  p0(0) = 0.0; p0(1) = 0.0;\n  vector_type p1(2);  p1(0) = 1.0; p1(1) = 0.0;\n  vector_type p2(2);  p2(0) = 2.0; p2(1) = 0.0;\n  vector_type p3(2);  p3(0) = 3.0; p3(1) = 0.0;\n\n  X.push_back(p0);\n  X.push_back(p1);\n  X.push_back(p2);\n  X.push_back(p3);\n\n  knot_container U;\n  \n  OpenTissue::spline::compute_chord_length_knot_vector(4, X, U);\n\n  spline_type spline = OpenTissue::spline::make_cubic_interpolation( U, X );\n\n  BOOST_CHECK( spline.get_order() == 4 );\n\n  BOOST_CHECK( spline.get_knot_container().size() == 10 );\n  BOOST_CHECK( spline.get_knot_container().size() == (spline.get_control_container().size()+4) );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "76553a3743cfe9e686c890eda835fe89295ffe23", "size": 1686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/spline/make_cubic_interpolation/src/unit_make_cubic_interpolation.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/spline/make_cubic_interpolation/src/unit_make_cubic_interpolation.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/spline/make_cubic_interpolation/src/unit_make_cubic_interpolation.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 33.0588235294, "max_line_length": 97, "alphanum_fraction": 0.706405694, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5976948279913157}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <array>\n#include <csim/type.hpp>\n#include <string>\n\n#ifdef __GNUC__\n#if __GNUC__ >= 8\nusing namespace std::complex_literals;\n#endif\n#endif\n\n// random\nstatic UINT rand_int(UINT max) { return rand() % max; }\n\nstatic double rand_real() { return (rand() % RAND_MAX) / ((double)RAND_MAX); }\n\n// obtain single dense matrix\nstatic Eigen::MatrixXcd get_eigen_matrix_single_Pauli(UINT pauli_id) {\n    Eigen::MatrixXcd mat(2, 2);\n    if (pauli_id == 0)\n        mat << 1, 0, 0, 1;\n    else if (pauli_id == 1)\n        mat << 0, 1, 1, 0;\n    else if (pauli_id == 2)\n        mat << 0, -1.i, 1.i, 0;\n    else if (pauli_id == 3)\n        mat << 1, 0, 0, -1;\n    return mat;\n}\n\nstatic Eigen::MatrixXcd get_eigen_matrix_random_single_qubit_unitary() {\n    Eigen::MatrixXcd Identity, X, Y, Z;\n    Identity = get_eigen_matrix_single_Pauli(0);\n    X = get_eigen_matrix_single_Pauli(1);\n    Y = get_eigen_matrix_single_Pauli(2);\n    Z = get_eigen_matrix_single_Pauli(3);\n\n    double icoef, xcoef, ycoef, zcoef, norm;\n    icoef = rand_real();\n    xcoef = rand_real();\n    ycoef = rand_real();\n    zcoef = rand_real();\n    norm = sqrt(icoef * icoef + xcoef + xcoef + ycoef * ycoef + zcoef * zcoef);\n    icoef /= norm;\n    xcoef /= norm;\n    ycoef /= norm;\n    zcoef /= norm;\n    return icoef * Identity + 1.i * xcoef * X + 1.i * ycoef * Y +\n           1.i * zcoef * Z;\n}\n\nstatic Eigen::VectorXcd get_eigen_diagonal_matrix_random_multi_qubit_unitary(\n    UINT qubit_count) {\n    ITYPE dim = (1ULL) << qubit_count;\n    auto vec = Eigen::VectorXcd(dim);\n    for (ITYPE i = 0; i < dim; ++i) {\n        double angle = rand_real() * 2 * 3.14159;\n        vec[i] = cos(angle) + 1.i * sin(angle);\n    }\n    return vec;\n}\n\n// expand matrix\nstatic Eigen::MatrixXcd kronecker_product(\n    const Eigen::MatrixXcd& lhs, const Eigen::MatrixXcd& rhs) {\n    Eigen::MatrixXcd result(lhs.rows() * rhs.rows(), lhs.cols() * rhs.cols());\n    for (int i = 0; i < lhs.cols(); i++) {\n        for (int j = 0; j < lhs.rows(); j++) {\n            result.block(i * rhs.rows(), j * rhs.cols(), rhs.rows(),\n                rhs.cols()) = lhs(i, j) * rhs;\n        }\n    }\n    return result;\n}\n\nstatic Eigen::MatrixXcd get_expanded_eigen_matrix_with_identity(\n    UINT target_qubit_index, const Eigen::MatrixXcd& one_qubit_matrix,\n    UINT qubit_count) {\n    const ITYPE left_dim = 1ULL << target_qubit_index;\n    const ITYPE right_dim = 1ULL << (qubit_count - target_qubit_index - 1);\n    auto left_identity = Eigen::MatrixXcd::Identity(left_dim, left_dim);\n    auto right_identity = Eigen::MatrixXcd::Identity(right_dim, right_dim);\n    return kronecker_product(\n        kronecker_product(right_identity, one_qubit_matrix), left_identity);\n}\n\n// get expanded matrix\n\nstatic Eigen::MatrixXcd get_eigen_matrix_full_qubit_pauli(\n    std::vector<UINT> pauli_ids) {\n    Eigen::MatrixXcd result = Eigen::MatrixXcd::Identity(1, 1);\n    for (UINT i = 0; i < pauli_ids.size(); ++i) {\n        result = kronecker_product(\n            get_eigen_matrix_single_Pauli(pauli_ids[i]), result)\n                     .eval();\n    }\n    return result;\n}\n\nstatic Eigen::MatrixXcd get_eigen_matrix_full_qubit_pauli(\n    std::vector<UINT> index_list, std::vector<UINT> pauli_list,\n    UINT qubit_count) {\n    std::vector<UINT> whole_pauli_ids(qubit_count, 0);\n    for (UINT i = 0; i < index_list.size(); ++i) {\n        whole_pauli_ids[index_list[i]] = pauli_list[i];\n    }\n    return get_eigen_matrix_full_qubit_pauli(whole_pauli_ids);\n}\n\nstatic Eigen::MatrixXcd get_eigen_matrix_full_qubit_CNOT(\n    UINT control_qubit_index, UINT target_qubit_index, UINT qubit_count) {\n    ITYPE dim = 1ULL << qubit_count;\n    Eigen::MatrixXcd result = Eigen::MatrixXcd::Zero(dim, dim);\n    for (ITYPE ind = 0; ind < dim; ++ind) {\n        if (ind & (1ULL << control_qubit_index)) {\n            result(ind, ind ^ (1ULL << target_qubit_index)) = 1;\n        } else {\n            result(ind, ind) = 1;\n        }\n    }\n    return result;\n}\n\nstatic Eigen::MatrixXcd get_eigen_matrix_full_qubit_CZ(\n    UINT control_qubit_index, UINT target_qubit_index, UINT qubit_count) {\n    ITYPE dim = 1ULL << qubit_count;\n    Eigen::MatrixXcd result = Eigen::MatrixXcd::Zero(dim, dim);\n    for (ITYPE ind = 0; ind < dim; ++ind) {\n        if ((ind & (1ULL << control_qubit_index)) != 0 &&\n            (ind & (1ULL << target_qubit_index)) != 0) {\n            result(ind, ind) = -1;\n        } else {\n            result(ind, ind) = 1;\n        }\n    }\n    return result;\n}\n\nstatic Eigen::MatrixXcd get_eigen_matrix_full_qubit_SWAP(\n    UINT target_qubit_index1, UINT target_qubit_index2, UINT qubit_count) {\n    ITYPE dim = 1ULL << qubit_count;\n    Eigen::MatrixXcd result = Eigen::MatrixXcd::Zero(dim, dim);\n    for (ITYPE ind = 0; ind < dim; ++ind) {\n        bool flag1, flag2;\n        flag1 = (ind & (1ULL << target_qubit_index1)) != 0;\n        flag2 = (ind & (1ULL << target_qubit_index2)) != 0;\n        if (flag1 ^ flag2) {\n            result(ind, ind ^ (1ULL << target_qubit_index1) ^\n                            (1ULL << target_qubit_index2)) = 1;\n        } else {\n            result(ind, ind) = 1;\n        }\n    }\n    return result;\n}\n\n// utils\nstatic std::string convert_CTYPE_array_to_string(\n    const CTYPE* state, ITYPE dim) {\n    std::string str = \"\";\n    for (ITYPE ind = 0; ind < dim; ++ind) {\n        str += \"(\" + std::to_string(_creal(state[ind])) + \",\" +\n               std::to_string(_cimag(state[ind])) + \") \";\n    }\n    return str;\n}\n\nstatic Eigen::VectorXcd convert_CTYPE_array_to_eigen_vector(\n    const CTYPE* state, ITYPE dim) {\n    Eigen::VectorXcd vec(dim);\n    for (ITYPE i = 0; i < dim; ++i) vec[i] = state[i];\n    return vec;\n}\n\nstatic void state_equal(const CTYPE* state, const Eigen::VectorXcd& test_state,\n    ITYPE dim, std::string gate_string) {\n    const double eps = 1e-14;\n    Eigen::VectorXcd vec = convert_CTYPE_array_to_eigen_vector(state, dim);\n    for (ITYPE ind = 0; ind < dim; ++ind) {\n        ASSERT_NEAR(abs(vec[ind] - test_state[ind]), 0, eps)\n            << gate_string << \" at \" << ind << std::endl\n            << \"Eigen : \" << test_state.transpose() << std::endl\n            << \"CSIM : \" << convert_CTYPE_array_to_string(state, dim)\n            << std::endl;\n    }\n}\n\n#define _CHECK_NEAR(val1, val2, eps) \\\n    _check_near(val1, val2, eps, #val1, #val2, #eps, __FILE__, __LINE__)\nstatic std::string _check_near(double val1, double val2, double eps,\n    std::string val1_name, std::string val2_name, std::string eps_name,\n    std::string file, UINT line) {\n    double diff = std::abs(val1 - val2);\n    if (diff <= eps) return \"\";\n    std::stringstream error_message_stream;\n    error_message_stream << file << \":\" << line << \" Failure\\n\"\n                         << \"The difference between \" << val1_name << \" and \"\n                         << val2_name << \" is \" << diff << \", which exceeds \"\n                         << eps_name << \", where\\n\"\n                         << val1_name << \" evaluates to \" << val1 << \",\\n\"\n                         << val2_name << \" evaluates to \" << val2 << \", and\\n\"\n                         << eps_name << \" evaluates to \" << eps << \".\\n\";\n    return error_message_stream.str();\n}\n", "meta": {"hexsha": "f3882aa639c64703898afbf73afe7842cdecc385", "size": 7191, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/util/util.hpp", "max_stars_repo_name": "Qulacs-Osaka/qulacs-osaka", "max_stars_repo_head_hexsha": "9ec1044c8214a64dbd1e1de7ad077e5cf779b3b7", "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": "test/util/util.hpp", "max_issues_repo_name": "Qulacs-Osaka/qulacs-osaka", "max_issues_repo_head_hexsha": "9ec1044c8214a64dbd1e1de7ad077e5cf779b3b7", "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": "test/util/util.hpp", "max_forks_repo_name": "Qulacs-Osaka/qulacs-osaka", "max_forks_repo_head_hexsha": "9ec1044c8214a64dbd1e1de7ad077e5cf779b3b7", "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": 34.7391304348, "max_line_length": 79, "alphanum_fraction": 0.602558754, "num_tokens": 2118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5976526302532993}}
{"text": "// unit test file acosh.hpp for the special functions test suite\r\n\r\n//  (C) Copyright Hubert Holin 2003. Permission to copy, use, modify, sell and\r\n//  distribute this software is granted provided this copyright notice appears\r\n//  in all copies. This software is provided \"as is\" without express or implied\r\n//  warranty, and with no claim as to its suitability for any purpose.\r\n\r\n\r\n#include <functional>\r\n#include <iomanip>\r\n#include <iostream>\r\n\r\n\r\n#include <boost/math/special_functions/acosh.hpp>\r\n\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n\r\ntemplate<typename T>\r\nT    acosh_error_evaluator(T x)\r\n{\r\n    using    ::std::abs;\r\n    using    ::std::sinh;\r\n    using    ::std::cosh;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    using    ::boost::math::acosh;\r\n    \r\n    \r\n    static T const    epsilon = numeric_limits<float>::epsilon();\r\n    \r\n    T                y = cosh(x);\r\n    T                z = acosh(y);\r\n    \r\n    T                absolute_error = abs(z-abs(x));\r\n    T                relative_error = absolute_error*abs(sinh(x));\r\n    T                scaled_error = relative_error/epsilon;\r\n    \r\n    return(scaled_error);\r\n}\r\n\r\n\r\ntemplate<typename T>\r\nvoid    acosh_test(const char * more_blurb)\r\n{\r\n    BOOST_MESSAGE(\"Testing acosh in the real domain for \"\r\n        << more_blurb << \".\");\r\n    \r\n    for    (int i = 0; i <= 100; i++)\r\n    {\r\n        T    x = static_cast<T>(i-50)/static_cast<T>(5);\r\n        \r\n        BOOST_CHECK_PREDICATE(::std::less_equal<T>(), 2,\r\n            (\r\n                acosh_error_evaluator(x),\r\n                static_cast<T>(4)\r\n            ));\r\n    }\r\n}\r\n\r\n\r\nvoid    acosh_manual_check()\r\n{\r\n    BOOST_MESSAGE(\"acosh\");\r\n    \r\n    for    (int i = 0; i <= 100; i++)\r\n    {\r\n        float        xf = static_cast<float>(i-50)/static_cast<float>(5);\r\n        double       xd = static_cast<double>(i-50)/static_cast<double>(5);\r\n        long double  xl = \r\n                static_cast<long double>(i-50)/static_cast<long double>(5);\r\n        \r\n        BOOST_MESSAGE(  ::std::setw(15)\r\n                     << acosh_error_evaluator(xf)\r\n                     << ::std::setw(15)\r\n                     << acosh_error_evaluator(xd)\r\n                     << ::std::setw(15)\r\n                     << acosh_error_evaluator(xl));\r\n    }\r\n    \r\n    BOOST_MESSAGE(\" \");\r\n}\r\n\r\n", "meta": {"hexsha": "d687993c30c33265669eb70db0df34a33e75356e", "size": 2326, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/acosh_test.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/acosh_test.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/acosh_test.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0465116279, "max_line_length": 80, "alphanum_fraction": 0.5283748925, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5976279616759388}}
{"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": "#include <Eigen/Core>\n#include <Eigen/Array>\nUSING_PART_OF_NAMESPACE_EIGEN\nusing namespace std;\n\n// define a custom template unary functor\ntemplate<typename Scalar>\nstruct CwiseClampOp {\n  CwiseClampOp(const Scalar& inf, const Scalar& sup) : m_inf(inf), m_sup(sup) {}\n  const Scalar operator()(const Scalar& x) const { return x<m_inf ? m_inf : (x>m_sup ? m_sup : x); }\n  Scalar m_inf, m_sup;\n};\n\nint main(int, char**)\n{\n  Matrix4d m1 = Matrix4d::Random();\n  cout << m1 << endl << \"becomes: \" << endl << m1.unaryExpr(CwiseClampOp<double>(-0.5,0.5)) << endl;\n  return 0;\n}\n", "meta": {"hexsha": "3b94a17b41ac3f4a758110ab8f5ae8aeef2c1c05", "size": 571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "volna_init/external/eigen2/doc/examples/class_CwiseUnaryOp.cpp", "max_stars_repo_name": "Devaraj-G/volna", "max_stars_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-07-08T23:53:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T11:55:28.000Z", "max_issues_repo_path": "volna_init/external/eigen2/doc/examples/class_CwiseUnaryOp.cpp", "max_issues_repo_name": "Devaraj-G/volna", "max_issues_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-02T17:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-02T17:31:28.000Z", "max_forks_repo_path": "volna_init/external/eigen2/doc/examples/class_CwiseUnaryOp.cpp", "max_forks_repo_name": "Devaraj-G/volna", "max_forks_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-02-05T19:34:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T08:46:34.000Z", "avg_line_length": 28.55, "max_line_length": 100, "alphanum_fraction": 0.6865148862, "num_tokens": 178, "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": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of kernel_parameter_optimizer class.\n */\n#include \"num_collect/interp/kernel/impl/kernel_parameter_optimizer.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\n#include \"eigen_approx.h\"\n#include \"is_finite.h\"\n#include \"num_collect/interp/kernel/calc_kernel_mat.h\"\n#include \"num_collect/interp/kernel/euclidean_distance.h\"\n#include \"num_collect/interp/kernel/gaussian_rbf.h\"\n#include \"num_collect/interp/kernel/impl/auto_regularizer_wrapper.h\"\n#include \"num_collect/interp/kernel/rbf_kernel.h\"\n\nTEST_CASE(\"num_collect::interp::kernel::impl::kernel_parameter_optimizer\") {\n    using num_collect::interp::kernel::euclidean_distance;\n    using num_collect::interp::kernel::gaussian_rbf;\n    using num_collect::interp::kernel::rbf_kernel;\n    using num_collect::interp::kernel::impl::auto_regularizer_wrapper;\n    using num_collect::interp::kernel::impl::kernel_parameter_optimizer;\n\n    const auto vars = std::vector<double>{0.0, 0.1, 0.2, 0.4, 0.6, 1.0};\n    const auto data = Eigen::VectorXd{{0.0, 0.2, 0.4, 0.7, 1.0, 2.0}};\n\n    using kernel_type =\n        rbf_kernel<euclidean_distance<double>, gaussian_rbf<double>>;\n    auto kernel = kernel_type();\n\n    auto interpolator = auto_regularizer_wrapper<double>();\n\n    SECTION(\"compute\") {\n        auto optimizer =\n            kernel_parameter_optimizer<kernel_type>(interpolator, kernel);\n\n        optimizer.compute(vars, data);\n\n        kernel.kernel_param(optimizer.opt_param());\n        const Eigen::MatrixXd kernel_mat = calc_kernel_mat(kernel, vars);\n\n        interpolator.compute(kernel, vars, data);\n        Eigen::VectorXd coeff;\n        interpolator.solve(coeff);\n\n        const Eigen::VectorXd retrieved_data = kernel_mat * coeff;\n        constexpr double tol_error = 1e-4;\n        REQUIRE_THAT(retrieved_data, eigen_approx(data, tol_error));\n    }\n}\n", "meta": {"hexsha": "ce217891d080da726cd521d3bfdb91c8e94f4221", "size": 2525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/interp/kernel/impl/kernel_parameter_optimizer_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/units/interp/kernel/impl/kernel_parameter_optimizer_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/units/interp/kernel/impl/kernel_parameter_optimizer_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1323529412, "max_line_length": 76, "alphanum_fraction": 0.7291089109, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5976279429172026}}
{"text": "#include <igl/colon.h>\n#include <igl/directed_edge_orientations.h>\n#include <igl/directed_edge_parents.h>\n#include <igl/forward_kinematics.h>\n#include <igl/PI.h>\n#include <igl/partition.h>\n#include <igl/mat_max.h>\n#include <igl/lbs_matrix.h>\n#include <igl/slice.h>\n#include <igl/deform_skeleton.h>\n#include <igl/dqs.h>\n#include <igl/lbs_matrix.h>\n#include <igl/columnize.h>\n#include <igl/readDMAT.h>\n#include <igl/readOBJ.h>\n#include <igl/arap.h>\n#include <igl/arap_dof.h>\n#include <igl/opengl/glfw/Viewer.h>\n\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n#include <vector>\n#include <algorithm>\n#include <iostream>\n\n#include \"tutorial_shared_path.h\"\n\ntypedef \n  std::vector<Eigen::Quaterniond,Eigen::aligned_allocator<Eigen::Quaterniond> >\n  RotationList;\n\nconst Eigen::RowVector3d sea_green(70./255.,252./255.,167./255.);\nEigen::MatrixXd V,U,M;\nEigen::MatrixXi F;\nEigen::VectorXi S,b;\nEigen::MatrixXd L;\nEigen::RowVector3d mid;\ndouble anim_t = 0.0;\ndouble anim_t_dir = 0.03;\ndouble bbd = 1.0;\nbool resolve = true;\nigl::ARAPData arap_data,arap_grouped_data;\nigl::ArapDOFData<Eigen::MatrixXd,double> arap_dof_data;\nEigen::SparseMatrix<double> Aeq;\n\nenum ModeType\n{\n  MODE_TYPE_ARAP = 0,\n  MODE_TYPE_ARAP_GROUPED = 1,\n  MODE_TYPE_ARAP_DOF = 2,\n  NUM_MODE_TYPES = 4\n} mode = MODE_TYPE_ARAP;\n\nbool pre_draw(igl::opengl::glfw::Viewer & viewer)\n{\n  using namespace Eigen;\n  using namespace std;\n  if(resolve)\n  {\n    MatrixXd bc(b.size(),V.cols());\n    VectorXd Beq(3*b.size());\n    for(int i = 0;i<b.size();i++)\n    {\n      bc.row(i) = V.row(b(i));\n      switch(i%4)\n      {\n        case 2:\n          bc(i,0) += 0.15*bbd*sin(0.5*anim_t);\n          bc(i,1) += 0.15*bbd*(1.-cos(0.5*anim_t));\n          break;\n        case 1:\n          bc(i,1) += 0.10*bbd*sin(1.*anim_t*(i+1));\n          bc(i,2) += 0.10*bbd*(1.-cos(1.*anim_t*(i+1)));\n          break;\n        case 0:\n          bc(i,0) += 0.20*bbd*sin(2.*anim_t*(i+1));\n          break;\n      }\n      Beq(3*i+0) = bc(i,0);\n      Beq(3*i+1) = bc(i,1);\n      Beq(3*i+2) = bc(i,2);\n    }\n    switch(mode)\n    {\n      default:\n        assert(\"unknown mode\");\n      case MODE_TYPE_ARAP:\n        igl::arap_solve(bc,arap_data,U);\n        break;\n      case MODE_TYPE_ARAP_GROUPED:\n        igl::arap_solve(bc,arap_grouped_data,U);\n        break;\n      case MODE_TYPE_ARAP_DOF:\n      {\n        VectorXd L0 = L;\n        arap_dof_update(arap_dof_data,Beq,L0,30,0,L);\n        const auto & Ucol = M*L;\n        U.col(0) = Ucol.block(0*U.rows(),0,U.rows(),1);\n        U.col(1) = Ucol.block(1*U.rows(),0,U.rows(),1);\n        U.col(2) = Ucol.block(2*U.rows(),0,U.rows(),1);\n        break;\n      }\n    }\n    viewer.data().set_vertices(U);\n    viewer.data().set_points(bc,sea_green);\n    viewer.data().compute_normals();\n    if(viewer.core.is_animating)\n    {\n      anim_t += anim_t_dir;\n    }else\n    {\n      resolve = false;\n    }\n  }\n  return false;\n}\n\nbool key_down(igl::opengl::glfw::Viewer &viewer, unsigned char key, int mods)\n{\n  switch(key)\n  {\n    case '0':\n      anim_t = 0;\n      resolve = true;\n      return true;\n    case '.':\n      mode = (ModeType)(((int)mode+1)%((int)NUM_MODE_TYPES-1));\n      resolve = true;\n      return true;\n    case ',':\n      mode = (ModeType)(((int)mode-1)%((int)NUM_MODE_TYPES-1));\n      resolve = true;\n      return true;\n    case ' ':\n      viewer.core.is_animating = !viewer.core.is_animating;\n      if(viewer.core.is_animating)\n      {\n        resolve = true;\n      }\n      return true;\n  }\n  return false;\n}\n\nint main(int argc, char *argv[])\n{\n  using namespace Eigen;\n  using namespace std;\n  igl::readOBJ(TUTORIAL_SHARED_PATH \"/armadillo.obj\",V,F);\n  U=V;\n  MatrixXd W;\n  igl::readDMAT(TUTORIAL_SHARED_PATH \"/armadillo-weights.dmat\",W);\n  igl::lbs_matrix_column(V,W,M);\n\n  // Cluster according to weights\n  VectorXi G;\n  {\n    VectorXi S;\n    VectorXd D;\n    igl::partition(W,50,G,S,D);\n  }\n\n  // vertices corresponding to handles (those with maximum weight)\n  {\n    VectorXd maxW;\n    igl::mat_max(W,1,maxW,b);\n  }\n\n  // Precomputation for FAST\n  cout<<\"Initializing Fast Automatic Skinning Transformations...\"<<endl;\n  // number of weights\n  const int m = W.cols();\n  Aeq.resize(m*3,m*3*(3+1));\n  vector<Triplet<double> > ijv;\n  for(int i = 0;i<m;i++)\n  {\n    RowVector4d homo;\n    homo << V.row(b(i)),1.;\n    for(int d = 0;d<3;d++)\n    {\n      for(int c = 0;c<(3+1);c++)\n      {\n        ijv.push_back(Triplet<double>(3*i + d,i + c*m*3 + d*m, homo(c)));\n      }\n    }\n  }\n  Aeq.setFromTriplets(ijv.begin(),ijv.end());\n  igl::arap_dof_precomputation(V,F,M,G,arap_dof_data);\n  igl::arap_dof_recomputation(VectorXi(),Aeq,arap_dof_data);\n  // Initialize\n  MatrixXd Istack = MatrixXd::Identity(3,3+1).replicate(1,m);\n  igl::columnize(Istack,m,2,L);\n\n  // Precomputation for ARAP\n  cout<<\"Initializing ARAP...\"<<endl;\n  arap_data.max_iter = 1;\n  igl::arap_precomputation(V,F,V.cols(),b,arap_data);\n  // Grouped arap\n  cout<<\"Initializing ARAP with grouped edge-sets...\"<<endl;\n  arap_grouped_data.max_iter = 2;\n  arap_grouped_data.G = G;\n  igl::arap_precomputation(V,F,V.cols(),b,arap_grouped_data);\n\n\n  // bounding box diagonal\n  bbd = (V.colwise().maxCoeff()- V.colwise().minCoeff()).norm();\n\n  // Plot the mesh with pseudocolors\n  igl::opengl::glfw::Viewer viewer;\n  viewer.data().set_mesh(U, F);\n  viewer.data().add_points(igl::slice(V,b,1),sea_green);\n  viewer.data().show_lines = false;\n  viewer.callback_pre_draw = &pre_draw;\n  viewer.callback_key_down = &key_down;\n  viewer.core.is_animating = false;\n  viewer.core.animation_max_fps = 30.;\n  cout<<\n    \"Press [space] to toggle animation.\"<<endl<<\n    \"Press '0' to reset pose.\"<<endl<<\n    \"Press '.' to switch to next deformation method.\"<<endl<<\n    \"Press ',' to switch to previous deformation method.\"<<endl;\n  viewer.launch();\n}\n", "meta": {"hexsha": "f524383e07b46a31b3cd6d97b9985bf3ff057757", "size": 5767, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/tutorial/406_FastAutomaticSkinningTransformations/main.cpp", "max_stars_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_stars_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "isometric-deformation/ext/libigl/tutorial/406_FastAutomaticSkinningTransformations/main.cpp", "max_issues_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_issues_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isometric-deformation/ext/libigl/tutorial/406_FastAutomaticSkinningTransformations/main.cpp", "max_forks_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_forks_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7455357143, "max_line_length": 79, "alphanum_fraction": 0.6211201665, "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.5976279407222672}}
{"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": "#pragma once\n#include <Eigen/Dense>\n#include <random>\n\n// Macro for silencing  unused parameters on demand.\n#define SUPPRESS_WARNING(a) (void) a\n\n/**\n * Defining an alias for double. Used so that if we ever want to change\n * this to float (for improved speed, reduced accuracy), this is done\n * one place, as apposed to a project wide refactor.\n * \\typedef\n */\nusing Real = double;\n\nconstexpr Real PI = 3.14159265358979323846; /**< Circle constant. */\n\nconstexpr Real NUMMERIC_DIFF_STEP\n    = 0.001; /**< Default step used in numerical differentiation. */\n\n/**\n * Define various linear algebra types. Note that row-major storage order\n * is used. Eigen should be equally performing with both, but row-major is\n * compatible with NumPy and hence bindings are easy to make.\n */\nusing Matrix    = Eigen::Matrix<Real, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\nusing Array     = Eigen::Array<Real, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\nusing Vector    = Eigen::Matrix<Real, Eigen::Dynamic, 1>;\nusing RowVector = Eigen::Matrix<Real, 1, Eigen::Dynamic>;\n\n/**\n * Corresponding Eigen::Ref bindings for each linear algebra type.\n * Most computations can be used as one of these types, useful for writing\n * generic functions without having to use templates (which can make it\n * difficult writing bindings for).\n */\nusing MatrixRef    = Eigen::Ref<Matrix>;\nusing ArrayRef     = Eigen::Ref<Array>;\nusing VectorRef    = Eigen::Ref<Vector>;\nusing RowVectorRef = Eigen::Ref<RowVector>;\n\n/**\n * Generic template for computing x * x, for any type. Useful\n * when x is some expression which we do not want to compute twice.\n * @param x Value to multiply with itself.\n * @return Result of `x * x`.\n */\ntemplate <typename T>\nconstexpr auto square(T&& x)\n{\n    return x * x;\n}\ntemplate <typename T>\nconstexpr auto square(const T& x)\n{\n    return x * x;\n}\n\n/** Type safe sign(x). */\ntemplate <typename T>\ninline constexpr int sign(T x, std::false_type)\n{\n    return T(0) < x;\n}\ntemplate <typename T>\ninline constexpr int sign(T x, std::true_type)\n{\n    return (T(0) < x) - (x < T(0));\n}\ntemplate <typename T>\ninline constexpr int sign(T x)\n{\n    return sign(x, std::is_signed<T>());\n}\n\n// Random number generation.\nextern std::mt19937_64 rand_gen; /**< Random number generator used. */\nextern std::uniform_real_distribution<Real>\n    unif; /**< Uniform random distribution (0, 1). */\nextern std::uniform_real_distribution<Real>\n                                      centered; /**< Uniform random distribution (-.5, .5). */\nextern std::normal_distribution<Real> rnorm; /**< N(0, 1) random number distribution. */\nextern std::normal_distribution<Real>\n    rnorm_small; /**< N(0, 0.1) random number distribution. */\n\ninline auto unif_func()\n{\n    return unif(rand_gen);\n}\ninline auto centered_func()\n{\n    return centered(rand_gen);\n}\ninline auto rnorm_func()\n{\n    return rnorm(rand_gen);\n}\ninline auto rnorm_small_func()\n{\n    return rnorm_small(rand_gen);\n}\n", "meta": {"hexsha": "e197789e3a614767e673b70a66feea4f02975e71", "size": 2957, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qflow/definitions.hpp", "max_stars_repo_name": "johanere/qflow", "max_stars_repo_head_hexsha": "5453cd5c3230ad7f082adf9ec1aea63ab0a4312a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-07-24T21:46:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T18:18:24.000Z", "max_issues_repo_path": "qflow/definitions.hpp", "max_issues_repo_name": "johanere/qflow", "max_issues_repo_head_hexsha": "5453cd5c3230ad7f082adf9ec1aea63ab0a4312a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2019-02-19T10:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-18T09:42:13.000Z", "max_forks_repo_path": "qflow/definitions.hpp", "max_forks_repo_name": "bsamseth/FYS4411", "max_forks_repo_head_hexsha": "72b879e7978364498c48fc855b5df676c205f211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-04T15:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T16:37:38.000Z", "avg_line_length": 28.9901960784, "max_line_length": 94, "alphanum_fraction": 0.6936083869, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.5975500908117497}}
{"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// \u03b2-detected nuclear magnetic resonance (\u03b2-NMR)\nnamespace bnmr {\n\n// spin-lattice relaxation (SLR)\nnamespace slr {\n\n/// pulsed Gaussian distribution of exponentials integral\n/// (from 0 to time_p <= time)\ntemplate <typename T = double>\nT pulsed_gauss_dist_exp_integral(T time, T time_p, T nuclear_lifetime,\n                                 T slr_rate, T sigma) {\n  // 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 \"catch.hpp\"\n#include \"timer.hpp\"\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <fmt/format.h>\n#include <functional>\n#include <iostream>\n\nusing boost::math::cyl_bessel_j;\nusing namespace boost::math::quadrature;\nusing namespace std::placeholders;\n\ndouble f1(double x, double r) {\n  return 1.0 / (pow(x, 2) + 1.0) * cyl_bessel_j(0.0, r * x) * x +\n         1.0 / (pow(x, 2) + 2.0) * cyl_bessel_j(1.0, r * x) * x;\n}\n\ndouble f2(double x) { return pow(x, 2); }\n\nTEST_CASE(\"Guass-Kronrod (f1)\", \"[mW transform Integral]\") {\n  double kmin = 1.0;\n  double kmax = 2.0;\n  double r = 100.0;\n\n  std::function<double(double)> func = std::bind(f1, _1, r);\n  double error = 0;\n  double estimate1 = 0;\n  int nk = 4;\n  Timer timer;\n  timer.start();\n  double dk = (kmax - kmin) / nk;\n  for (int i = 0; i < nk; ++i) {\n    double k1 = kmin + i * dk;\n    double k2 = k1 + dk;\n    estimate1 +=\n        gauss_kronrod<double, 15>::integrate(func, k1, k2, 0, 0, &error);\n  }\n  timer.stop();\n  fmt::print(\"Milliseconds: {:f}\\n\", timer.elapsedMilliseconds());\n  timer.start();\n  double estimate2 =\n      gauss_kronrod<double, 61>::integrate(func, kmin, kmax, 0, 0, &error);\n  timer.stop();\n  fmt::print(\"Milliseconds: {:f}\\n\", timer.elapsedMilliseconds());\n\n  fmt::print(\"e2 - e1: {:15.8e} - {:15.8e} = {:15.8e}\\n\", estimate2, estimate1,\n             estimate2 - estimate1);\n  REQUIRE(estimate1 == Approx(0.000289257995979269));\n}\n\nTEST_CASE(\"Guass-Kronrod (f2)\", \"[mW transform Integral]\") {\n  double kmin = 1.0;\n  double kmax = 2.0;\n\n  double error;\n  double estimate =\n      gauss_kronrod<double, 15>::integrate(f2, kmin, kmax, 0, 0, &error);\n\n  REQUIRE(estimate == Approx(2.3333333333333335));\n}", "meta": {"hexsha": "9b4e230a7026f0fcc90633610326018453f37fa1", "size": 1746, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test_finite.cc", "max_stars_repo_name": "pan3rock/mWOI", "max_stars_repo_head_hexsha": "47f544cd29020616d2dfb4ce01e09da27ccf84c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_finite.cc", "max_issues_repo_name": "pan3rock/mWOI", "max_issues_repo_head_hexsha": "47f544cd29020616d2dfb4ce01e09da27ccf84c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_finite.cc", "max_forks_repo_name": "pan3rock/mWOI", "max_forks_repo_head_hexsha": "47f544cd29020616d2dfb4ce01e09da27ccf84c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6229508197, "max_line_length": 79, "alphanum_fraction": 0.6300114548, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927838, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5975170205139773}}
{"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": "#ifndef MYGRAPH_H\n#define MYGRAPH_H\n\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n\nusing std::vector;\nusing Eigen::MatrixXf;\n\nclass MyGraph{\n\npublic:\n\tMyGraph(Eigen::MatrixXf A);\n\t~MyGraph();\n\tvoid findConnComps();\n\tunsigned getNumConnComps();\n\tvector<vector<unsigned>> getConnComps();\n\nprivate:\n\tEigen::MatrixXi A_;\n\tvector<vector<unsigned>> ConnComps; // each vector is a connected component\t\n\n};\n\n\n#endif", "meta": {"hexsha": "4da29c77dc9db9190debeecbbeef244d144e6630", "size": 508, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clear/MyGraph.hpp", "max_stars_repo_name": "NamDinhRobotics/clear-fusion", "max_stars_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:53.000Z", "max_issues_repo_path": "include/clear/MyGraph.hpp", "max_issues_repo_name": "NamDinhRobotics/clear-fusion", "max_issues_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/clear/MyGraph.hpp", "max_forks_repo_name": "NamDinhRobotics/clear-fusion", "max_forks_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.9333333333, "max_line_length": 77, "alphanum_fraction": 0.7460629921, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5974511343467077}}
{"text": "#include <igl/writeDMAT.h>\n#include <Eigen/Core>\n\n\n\n\nvoid write_transformation(const std::string filename, const std::vector<Eigen::Matrix4d> Transformations){\n    Eigen::MatrixXd bigT;\n    bigT.resize(4*Transformations.size(),4);\n    for (int i = 0; i<Transformations.size(); i++) {\n        bigT.block(4*i,0,4,4) = Transformations[i];\n    }\n    igl::writeDMAT(filename,bigT);\n}\n", "meta": {"hexsha": "8a6cc43505f9b992d05ad252631ced1b2b675215", "size": 379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/write_transformation.cpp", "max_stars_repo_name": "sgsellan/swept-volumes", "max_stars_repo_head_hexsha": "12d1ec636e1f64dfd9cd0c13639e15ab9de67284", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2021-06-19T16:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T23:56:15.000Z", "max_issues_repo_path": "include/write_transformation.cpp", "max_issues_repo_name": "sgsellan/swept-volumes", "max_issues_repo_head_hexsha": "12d1ec636e1f64dfd9cd0c13639e15ab9de67284", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/write_transformation.cpp", "max_forks_repo_name": "sgsellan/swept-volumes", "max_forks_repo_head_hexsha": "12d1ec636e1f64dfd9cd0c13639e15ab9de67284", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-19T15:27:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T13:01:28.000Z", "avg_line_length": 25.2666666667, "max_line_length": 106, "alphanum_fraction": 0.672823219, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5974511317356932}}
{"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_MATRIXALGO__H_\n#define _PIMATH_MATRIXALGO__H_\n\n#include <boost/python.hpp>\n#include <ImathMatrixAlgo.h>\n#include \"util.h\"\n\n/*\n * extractSHRT,\n * extractScaling,\n * extractScalingAndShear:\n * Return the value(s) rather than a bool, or None where Imath would return False.\n *\n * removeScaling,\n * removeScalingAndShear,\n * sansScaling,\n * sansScalingAndShear:\n * Not implemented. Use 'm = withoutScaling(AndShear)(m)' instead.\n *\n * withoutScaling(AndShear) replaces sansScaling(AndShear), but behaviour is slightly different.\n * withoutScaling will return None, where removeScaling would have returned False. Otherwise,\n * it will return the same value as sansScaling.\n *\n * extractAndRemoveScalingAndShear:\n * Not implemented, use a combination of extractScalingAndShear and withoutScalingAndShear instead.\n *\n * extractSHRT:\n * The form of this function which takes args (M44, Vec3, Vec3, Euler, Vec3) is available\n * as the function 'extractEulerSHRT'.\n */\n\nnamespace pimath\n{\n\tnamespace bp = boost::python;\n\n\ttemplate<typename T>\n\tstruct MatrixAlgoBind\n\t{\n\t\ttypedef Imath::Vec2<T> \t\tvec2_type;\n\t\ttypedef Imath::Vec3<T> \t\tvec3_type;\n\t\ttypedef Imath::Quat<T> \t\tquat_type;\n\t\ttypedef Imath::Matrix33<T> \tmat33_type;\n\t\ttypedef Imath::Matrix44<T> \tmat44_type;\n\t\ttypedef Imath::Euler<T> \teuler_type;\n\n\t\tMatrixAlgoBind()\n\t\t{\n\t\t\tbp::def(\"extractQuat\", &Imath::extractQuat<T>);\n\t\t\tbp::def(\"rotationMatrix\", &Imath::rotationMatrix<T>);\n\t\t\tbp::def(\"rotationMatrixWithUpDir\", &Imath::rotationMatrixWithUpDir<T>);\n\t\t\tbp::def(\"alignZAxisWithTargetDir\", &Imath::alignZAxisWithTargetDir<T>);\n\n\t\t\tbp::def(\"extractScaling\", extractScaling<mat33_type>);\n\t\t\tbp::def(\"extractScaling\", extractScaling_<mat33_type>);\n\t\t\tbp::def(\"extractScaling\", extractScaling<mat44_type>);\n\t\t\tbp::def(\"extractScaling\", extractScaling_<mat44_type>);\n\n\t\t\tbp::def(\"withoutScaling\", removeScaling<mat33_type>);\n\t\t\tbp::def(\"withoutScaling\", removeScaling_<mat33_type>);\n\t\t\tbp::def(\"withoutScaling\", removeScaling<mat44_type>);\n\t\t\tbp::def(\"withoutScaling\", removeScaling_<mat44_type>);\n\n\t\t\tbp::def(\"withoutScalingAndShear\", removeScalingAndShear<mat33_type>);\n\t\t\tbp::def(\"withoutScalingAndShear\", removeScalingAndShear_<mat33_type>);\n\t\t\tbp::def(\"withoutScalingAndShear\", removeScalingAndShear<mat44_type>);\n\t\t\tbp::def(\"withoutScalingAndShear\", removeScalingAndShear_<mat44_type>);\n\n\t\t\tbp::def(\"extractScalingAndShear\", extractScalingAndShear33);\n\t\t\tbp::def(\"extractScalingAndShear\", extractScalingAndShear33_);\n\t\t\tbp::def(\"extractScalingAndShear\", extractScalingAndShear44);\n\t\t\tbp::def(\"extractScalingAndShear\", extractScalingAndShear44_);\n\n\t\t\tbp::def(\"extractSHRT\", extractSHRT33);\n\t\t\tbp::def(\"extractSHRT\", extractSHRT33_);\n\n\t\t\tbp::def(\"extractSHRT\", extractSHRT44);\n\t\t\tbp::def(\"extractSHRT\", extractSHRT44_);\n\t\t\tbp::def(\"extractSHRT\", extractSHRT44__);\n\n\t\t\tbp::def(\"extractEulerSHRT\", extractEulerSHRT);\n\t\t\tbp::def(\"extractEulerSHRT\", extractEulerSHRT_);\n\n\t\t\tbp::def(\"extractEuler\", extractEuler);\n\t\t\tbp::def(\"extractEulerXYZ\", extractEulerXYZ);\n\t\t\tbp::def(\"extractEulerZYX\", extractEulerZYX);\n\t\t}\n\n\t\tstatic bp::object extractEulerSHRT(const mat44_type& mat, bool exc)\n\t\t{\n\t\t\tvec3_type s, h, t;\n\t\t\teuler_type r;\n\t\t\treturn (Imath::extractSHRT(mat, s, h, r, t, exc))?\n\t\t\t\tbp::make_tuple(s,h,r,t) : bp::object();\n\t\t}\n\n\t\tstatic bp::object extractEulerSHRT_(const mat44_type& mat) {\n\t\t\treturn extractEulerSHRT(mat, true);\n\t\t}\n\n\t\tstatic bp::object extractSHRT44(const mat44_type& mat,\n\t\t\tbool exc, typename euler_type::Order order)\n\t\t{\n\t\t\tvec3_type s, h, r, t;\n\t\t\treturn (Imath::extractSHRT(mat, s, h, r, t, exc, order))?\n\t\t\t\tbp::make_tuple(s,h,r,t) : bp::object();\n\t\t}\n\n\t\tstatic bp::object extractSHRT44_(const mat44_type& mat, bool exc) {\n\t\t\treturn extractSHRT44(mat, exc, euler_type::XYZ);\n\t\t}\n\n\t\tstatic bp::object extractSHRT44__(const mat44_type& mat) {\n\t\t\treturn extractSHRT44(mat, true, euler_type::XYZ);\n\t\t}\n\n\t\tstatic bp::object extractSHRT33(const mat33_type& mat, bool exc)\n\t\t{\n\t\t\tvec2_type s, t;\n\t\t\tT h, r;\n\t\t\treturn (Imath::extractSHRT(mat, s, h, r, t, exc))?\n\t\t\t\tbp::make_tuple(s,h,r,t) : bp::object();\n\t\t}\n\n\t\tstatic bp::object extractSHRT33_(const mat33_type& mat) {\n\t\t\treturn extractSHRT33(mat, true);\n\t\t}\n\n\t\tstatic bp::object extractScalingAndShear33(const mat33_type& mat, bool exc)\n\t\t{\n\t\t\tvec2_type scl;\n\t\t\tT h;\n\t\t\treturn (Imath::extractScalingAndShear(mat, scl, h, exc))?\n\t\t\t\tbp::make_tuple(scl, h) : bp::object();\n\t\t}\n\n\t\tstatic bp::object extractScalingAndShear33_(const mat33_type& mat) {\n\t\t\treturn extractScalingAndShear33(mat, true);\n\t\t}\n\n\t\tstatic bp::object extractScalingAndShear44(const mat44_type& mat, bool exc)\n\t\t{\n\t\t\tvec3_type scl, shr;\n\t\t\treturn (Imath::extractScalingAndShear(mat, scl, shr, exc))?\n\t\t\t\tbp::make_tuple(scl, shr) : bp::object();\n\t\t}\n\n\t\tstatic bp::object extractScalingAndShear44_(const mat44_type& mat) {\n\t\t\treturn extractScalingAndShear44(mat, true);\n\t\t}\n\n\t\ttemplate<typename Matrix>\n\t\tstatic bp::object removeScalingAndShear(const Matrix& mat, bool exc)\n\t\t{\n\t\t\tMatrix m(mat);\n\t\t\treturn (Imath::removeScalingAndShear(m, exc))?\n\t\t\t\tbp::object(m) : bp::object();\n\t\t}\n\n\t\ttemplate<typename Matrix>\n\t\tstatic bp::object removeScalingAndShear_(const Matrix& mat, bool exc) {\n\t\t\treturn removeScalingAndShear(mat, true);\n\t\t}\n\n\t\ttemplate<typename Matrix>\n\t\tstatic bp::object removeScaling(const Matrix& mat, bool exc)\n\t\t{\n\t\t\tMatrix m(mat);\n\t\t\treturn (Imath::removeScaling(m, exc))?\n\t\t\t\tbp::object(m) : bp::object();\n\t\t}\n\n\t\ttemplate<typename Matrix>\n\t\tstatic bp::object removeScaling_(const Matrix& mat, bool exc) {\n\t\t\treturn removeScaling(mat, true);\n\t\t}\n\n\t\ttemplate<typename Matrix>\n\t\tstatic bp::object extractScaling(const Matrix& mat, bool exc)\n\t\t{\n\t\t\ttypedef imath_traits<Matrix> \t\t\t\t\t\t\t\tmat_traits;\n\t\t\ttypedef typename make_vec<mat_traits::_columns-1, T>::type \tvec_less1_type;\n\n\t\t\tvec_less1_type v;\n\t\t\treturn (Imath::extractScaling(mat, v, exc))?\n\t\t\t\tbp::object(v) : bp::object();\n\t\t}\n\n\t\ttemplate<typename Matrix>\n\t\tstatic bp::object extractScaling_(const Matrix& mat) {\n\t\t\treturn extractScaling(mat, true);\n\t\t}\n\n\t\tstatic T extractEuler(const mat33_type &mat)\n\t\t{\n\t\t\tT rot;\n\t\t\tImath::extractEuler(mat, rot);\n\t\t\treturn rot;\n\t\t}\n\n\t\tstatic vec3_type extractEulerXYZ(const mat44_type &mat)\n\t\t{\n\t\t\tvec3_type rot;\n\t\t\tImath::extractEulerXYZ(mat, rot);\n\t\t\treturn rot;\n\t\t}\n\n\t\tstatic vec3_type extractEulerZYX(const mat44_type &mat)\n\t\t{\n\t\t\tvec3_type rot;\n\t\t\tImath::extractEulerZYX(mat, rot);\n\t\t\treturn rot;\n\t\t}\n\t};\n\n}\n\n#endif\n", "meta": {"hexsha": "503c9c0bc34ced8dc571da49efbfa24c1a7f6a22", "size": 8065, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/MatrixAlgo.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/MatrixAlgo.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/MatrixAlgo.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": 32.7845528455, "max_line_length": 99, "alphanum_fraction": 0.7174209547, "num_tokens": 2244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519376, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5974275277202761}}
{"text": "/* Copyright (C) 2012-2020 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n\n/* GTestextractDigits.cpp - extracting digits.\n *   For a plaintext space modulo a prime-power $p^e$, extracting\n *   the base-$p$ representation of an encrypted values.\n */\n#include <NTL/ZZ.h>\n#include <helib/EncryptedArray.h>\n#include <helib/polyEval.h>\n\n#include \"gtest/gtest.h\"\n#include \"test_common.h\"\n\n#include <helib/debugging.h>\n\nnamespace {\n\nstruct Parameters\n{\n  Parameters(long p, long r, long m) : p(p), r(r), m(m)\n  {\n    if (p < 2)\n      throw std::invalid_argument(\"p must be at least 2\");\n  };\n  long p; // Plaintext base\n  long r; // Lifting\n  long m; // The cyclotomic ring\n\n  // Let googletest know how to print the Parameters\n  friend std::ostream& operator<<(std::ostream& os, const Parameters& params)\n  {\n    return os << \"{\"\n              << \"p=\" << params.p << \",\"\n              << \"r=\" << params.r << \",\"\n              << \"m=\" << params.m << \"}\";\n  };\n};\n\nclass GTestExtractDigits : public ::testing::TestWithParam<Parameters>\n{\nprotected:\n  long p;\n  long r;\n  long m;\n  long p2r;\n  long L;\n\n  helib::Context context;\n  helib::SecKey secretKey;\n  const helib::PubKey& publicKey;\n\n  // lifting value rOld requires some manipulation before being used.\n  // Utility function for calculating this.\n  static long correctLifting(long rOld, long p)\n  {\n    long r = rOld;\n    double lBound = 30.0;\n    long bound = floor(lBound / log2((double)p));\n    if (r < 2 || r > bound)\n      r = bound;\n    return r;\n  };\n\n  // Calculate how many levels we need\n  static long calculateLevels(long r, long p)\n  {\n    long ll = NTL::NextPowerOfTwo(p);\n    return 30 * (r * ll * 3 + 2);\n  };\n\n  GTestExtractDigits() :\n      p(GetParam().p),\n      r(correctLifting(GetParam().r, p)),\n      m(GetParam().m\n            ? GetParam().m\n            : p + 1), // FindM(/*secparam=*/80, L, /*c=*/4, p, /*d=*/1, 0, m);\n      p2r(NTL::power_long(p, r)),\n      L(calculateLevels(r, p)),\n      context(m, p, r),\n      secretKey((helib::buildModChain(context, L, /*c=*/4), context)),\n      publicKey(secretKey)\n  {}\n\n  virtual void SetUp() override\n  {\n    helib::setDryRun(helib_test::dry);\n    if (!helib_test::noPrint) {\n      if (helib_test::dry)\n        std::cout << \"dry run: \";\n      std::cout << \"m=\" << m << \", p=\" << p << \", r=\" << r << \", L=\" << L\n                << std::endl;\n    }\n\n    secretKey.GenSecKey(); // A +-1/0 secret key\n    helib::addSome1DMatrices(\n        secretKey); // compute key-switching matrices that we need\n    // On legacy test is debug, but used verbose for consistency with other\n    // tests\n    if (helib_test::verbose) {\n      helib::dbgKey = &secretKey; // debugging key and ea\n      helib::dbgEa = context.ea;\n    }\n\n#ifdef DEBUG_PRINTOUT\n    helib::dbgKey = &secretKey;\n    helib::dbgEa = context.ea;\n#endif // DEBUG_PRINTOUT\n  };\n\n  virtual void TearDown() override { helib::cleanupGlobals(); }\n};\n\nTEST_P(GTestExtractDigits, correctlyExtractsDigits)\n{\n  helib::EncryptedArray ea(context);\n  std::vector<long> v;\n  std::vector<long> pDigits;\n  ea.random(v); // random values in the slots\n\n  const helib::PubKey& publicKey = secretKey;\n\n  helib::Ctxt c(publicKey);\n  ea.encrypt(c, publicKey, v);\n  ea.decrypt(c, secretKey, pDigits);\n  if (ea.size() <= 20 && !helib_test::noPrint)\n    std::cout << \"plaintext=\" << helib::vecToStr(pDigits) << std::endl;\n\n  if (!helib_test::noPrint)\n    std::cout << \"extracting \" << r << \" digits...\" << std::flush;\n  std::vector<helib::Ctxt> digits;\n  helib::extractDigits(digits, c);\n  if (!helib_test::noPrint)\n    std::cout << \" done\\n\" << std::flush;\n\n  std::vector<long> tmp = v;\n  long pp = p2r;\n  for (long i = 0; i < (long)digits.size(); i++) {\n    if (!digits[i].isCorrect()) {\n      helib::CheckCtxt(digits[i], \"\");\n      FAIL() << \" potential decryption error for \" << i << \"th digit \";\n    }\n    ea.decrypt(digits[i], secretKey, pDigits);\n    if (ea.size() <= 20 && !helib_test::noPrint)\n      std::cout << i << \"th digit=\" << helib::vecToStr(pDigits) << std::endl;\n\n    // extract the next digit from the plaintext, compare to pDigits\n    for (long j = 0; j < (long)v.size(); j++) {\n      long digit = tmp[j] % p;\n      if (digit > p / 2)\n        digit -= p;\n      else if (digit < -p / 2)\n        digit += p;\n\n      EXPECT_EQ((pDigits[j] - digit) % pp, 0)\n          << \" error: v[\" << j << \"]=\" << v[j] << \" but \" << i\n          << \"th digit comes \" << pDigits[j] << \" rather than \" << digit\n          << std::endl\n          << std::endl;\n      tmp[j] -= digit;\n      tmp[j] /= p;\n    }\n    pp /= p;\n  }\n}\n\nINSTANTIATE_TEST_SUITE_P(variousPlaintextBases,\n                         GTestExtractDigits,\n                         ::testing::Values(\n                             // SLOW\n                             Parameters(5, 0, 2047)\n                             // FAST\n                             // Parameters(5, 0, 91)\n                             ));\n\n} // anonymous namespace\n", "meta": {"hexsha": "6a1ac1f7cff59976473b0055029e3dbed3fd4475", "size": 5503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/GTestExtractDigits.cpp", "max_stars_repo_name": "Souhail-MEFTAH/HElib", "max_stars_repo_head_hexsha": "5f97813b99407d6f9a6251cee920b4e419edc028", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/GTestExtractDigits.cpp", "max_issues_repo_name": "Souhail-MEFTAH/HElib", "max_issues_repo_head_hexsha": "5f97813b99407d6f9a6251cee920b4e419edc028", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/GTestExtractDigits.cpp", "max_forks_repo_name": "Souhail-MEFTAH/HElib", "max_forks_repo_head_hexsha": "5f97813b99407d6f9a6251cee920b4e419edc028", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5860215054, "max_line_length": 78, "alphanum_fraction": 0.5782300563, "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5974275170744021}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include \"entity.hpp\"\n\nnamespace cuauv {\nnamespace fishbowl {\n\nentity::entity(double m, double r, const inertia_tensor& I, const Eigen::Quaterniond& btom_rq)\n    : m(m)\n    , r(r)\n    , I(I)\n    , btom_rq(btom_rq)\n    , btom_rm(btom_rq.matrix())\n    , mtob_rm(btom_rq.conjugate().matrix())\n{\n    if (m <= 0) throw std::invalid_argument(\"expected m > 0.\");\n    if (r <= 0) throw std::invalid_argument(\"expected r > 0.\");\n\n    Eigen::Vector3d diag = I.diagonal();\n    if (diag[0] == 0 || diag[1] == 0 || diag[2] == 0) throw std::invalid_argument(\"expected I fully non-zero\");\n\n    Eigen::Vector3d& diagr = Ir.diagonal();\n    for (int i = 0; i < 3; i++)\n        diagr[i] = 1.0 / diag[i];\n}\n\ndouble entity::get_m() const { return m; }\ndouble entity::get_r() const { return r; }\n\ninertia_tensor entity::get_I() const { return I; }\ninertia_tensor entity::get_Ir() const { return Ir; }\n\nEigen::Matrix3d entity::get_btom_rm() const { return btom_rm; }\nEigen::Matrix3d entity::get_mtob_rm() const { return mtob_rm; }\nEigen::Quaterniond entity::get_model_q() const { return Eigen::Quaterniond(q * btom_rq.conjugate()).normalized(); }\n\n} // namespace fishbowl\n} // namespace cuauv\n", "meta": {"hexsha": "325a54c91f138080e7ea19f8e2c29faebd6c9914", "size": 1242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fishbowl/entity.cpp", "max_stars_repo_name": "cuauv/software", "max_stars_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T18:04:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T09:04:02.000Z", "max_issues_repo_path": "fishbowl/entity.cpp", "max_issues_repo_name": "cuauv/software", "max_issues_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-03T05:13:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-03T06:19:39.000Z", "max_forks_repo_path": "fishbowl/entity.cpp", "max_forks_repo_name": "cuauv/software", "max_forks_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T17:29:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T14:15:12.000Z", "avg_line_length": 30.2926829268, "max_line_length": 115, "alphanum_fraction": 0.652173913, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5973902417169751}}
{"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": "// \u51fa\u984c\u5143\r\n// \u9ebb\u5e03\u4e2d\u5b66\u6821 2008\u5e74 \u5165\u8a66\u554f\u984c \u7b97\u6570 \u554f4 \u89e3\u6cd5\r\n//\r\n// Boost C++ Libraries 1.63.0 (boost_1_63_0.zip) \u306b\u542b\u307e\u308c\u308b\r\n// libs/spirit/example/qi/calc_utree_ast.cpp \u3092\u6539\u5909\u3057\u305f\u3082\u306e\u3092\u7528\u3044\u3066\u3044\u307e\u3059\u3002\r\n// Boost Software License \u306f\u3001\u4ee5\u4e0b\u304b\u3089\u53c2\u7167\u3067\u304d\u307e\u3059\r\n// http://www.boost.org/LICENSE_1_0.txt\r\n//\r\n// \u69cb\u6587\u89e3\u6790\u7d50\u679c\u3092AST\u3068\u3057\u3066\u3067\u306f\u306a\u304f\u3001\u76f4\u63a5\u5024\u3068\u3057\u3066\u8fd4\u3059\u65b9\u6cd5\u306f\u3001\u4ee5\u4e0b\u3092\u53c2\u8003\u306b\u3057\u307e\u3057\u305f\u3002\r\n// http://www.kmonos.net/alang/boost/classes/spirit.html\r\n\r\n#include <algorithm>\r\n#include <iostream>\r\n#include <memory>\r\n#include <string>\r\n#include <type_traits>\r\n#include <unordered_map>\r\n#include <vector>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <boost/optional.hpp>\r\n#include <boost/spirit/include/qi.hpp>\r\n#include <boost/spirit/include/phoenix_operator.hpp>\r\n#include <boost/spirit/include/phoenix_function.hpp>\r\n\r\n#ifdef USE_BIG_INTETER\r\nusing BigNumber = boost::multiprecision::uint512_t;  // \u8a08\u7b97\u7d50\u679c\r\n#else\r\nusing BigNumber = size_t; // Rust\u4e92\u63db\r\n#endif\r\n\r\n// unordered_map\u306b\u683c\u7d0d\u3067\u304d\u308b\u3088\u3046\u306b\u3059\u308b\r\nnamespace std {\r\n#ifdef USE_BIG_INTETER\r\n    template <> struct hash<BigNumber> {\r\n        std::size_t operator()(const BigNumber& key) const {\r\n            using KeyType = size_t;\r\n            static_assert(std::is_unsigned<KeyType>::value, \"Expect unsigned key\");\r\n            return static_cast<KeyType>(key);\r\n        }\r\n    };\r\n#endif\r\n}\r\n\r\nclass NumberSet {\r\n    using Expression = std::string;\r\n    struct Result final {\r\n        Result(const Expression& argExpr, const boost::optional<BigNumber>& argValue) :\r\n            expr(argExpr), value(argValue) {}\r\n        Expression expr;\r\n        boost::optional<BigNumber> value;\r\n    };\r\n    using ExpressionSet = std::vector<Expression>;\r\n    using ResultSet = std::vector<std::shared_ptr<Result>>;\r\n    using ResultMap = std::unordered_map<BigNumber, std::vector<std::shared_ptr<Result>>>;\r\n\r\npublic:\r\n    enum class FILTER {\r\n        BY_EXPRESSION,\r\n        BY_VALUE,\r\n    };\r\n\r\n    enum class PRINT_VALUE {\r\n        NO_PRINT,\r\n        PRINT,\r\n    };\r\n\r\n    NumberSet(const BigNumber& minNumber, const BigNumber& maxNumber,\r\n              FILTER filter, PRINT_VALUE printValue) :\r\n        filter_(filter), printValue_(printValue) {\r\n        addExpressions(minNumber, maxNumber);\r\n        std::sort(results_.begin(), results_.end(),\r\n                  [&](auto& l, auto& r) { return (*(l->value) < *(r->value)); });\r\n    }\r\n\r\n    virtual ~NumberSet(void) = default;\r\n    NumberSet(const NumberSet&) = delete;\r\n    NumberSet& operator=(const NumberSet&) = delete;\r\n\r\n    void PrintSums(std::ostream& os) {\r\n        for(auto& result : results_) {\r\n            os << *(result->value) << \" = \" << result->expr << \"\\n\";\r\n        }\r\n    }\r\n\r\n    void PrintMatchedSums(const NumberSet& other, std::ostream& os) {\r\n        for(auto& result : results_) {\r\n            if (other.resultMap_.empty()) {\r\n                for(auto& otherResult : other.results_) {\r\n                    if (*(result->value) == *(otherResult->value)) {\r\n                        printValue(result->value, os);\r\n                        os << result->expr << \" == \" << otherResult->expr << \"\\n\";\r\n                    }\r\n                }\r\n            } else {\r\n                auto iResults = other.resultMap_.find(*(result->value));\r\n                if (iResults != other.resultMap_.end()) {\r\n                    printValue(result->value, os);\r\n                    os << result->expr;\r\n                    for(auto& otherResult : iResults->second) {\r\n                        os << \" == \" << otherResult->expr;\r\n                    }\r\n                    os << \"\\n\";\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\nprivate:\r\n    void addExpressions(const BigNumber& number, const BigNumber& maxNumber) {\r\n        ExpressionSet exprSet;\r\n        exprSet.push_back(boost::lexical_cast<std::string>(number));\r\n        addExpressions(exprSet, number + 1, maxNumber);\r\n        return;\r\n    }\r\n\r\n    void addExpressions(const ExpressionSet& exprSet, const BigNumber& number, const BigNumber& maxNumber) {\r\n        if (number > maxNumber) {\r\n            for(auto& expr : exprSet) {\r\n                registerExpressions(expr);\r\n            }\r\n        } else {\r\n            ExpressionSet exprSetPlus;\r\n            for(auto& expr : exprSet) {\r\n                exprSetPlus.push_back(expr + \"*\" + boost::lexical_cast<std::string>(number));\r\n                addExpressions(exprSetPlus, number + 1, maxNumber);\r\n            }\r\n\r\n            ExpressionSet exprSetMul;\r\n            for(auto& expr : exprSet) {\r\n                exprSetMul.push_back(expr + \"+\" + boost::lexical_cast<std::string>(number));\r\n                addExpressions(exprSetMul, number + 1, maxNumber);\r\n            }\r\n        }\r\n        return;\r\n    }\r\n\r\n    void registerExpressions(const Expression& expr) {\r\n        auto value = calculate(expr);\r\n        if (value) {\r\n            std::shared_ptr<Result> pResult = std::make_shared<Result>(expr, value);\r\n            results_.push_back(pResult);\r\n\r\n            if ((filter_ == FILTER::BY_VALUE) && value) {\r\n                resultMap_[*value].push_back(pResult);\r\n            }\r\n        }\r\n    }\r\n\r\n    template <typename Iterator>\r\n    struct calculator : boost::spirit::qi::grammar<Iterator, boost::spirit::ascii::space_type, BigNumber()> {\r\n        boost::spirit::qi::rule<Iterator, boost::spirit::ascii::space_type, BigNumber()> expression, term, factor;\r\n        calculator() : calculator::base_type(expression) {\r\n            expression = term[boost::spirit::qi::_val = boost::spirit::qi::_1]\r\n                >> *('+' >> term[boost::spirit::qi::_val += boost::spirit::qi::_1]);\r\n            term = factor[boost::spirit::qi::_val = boost::spirit::qi::_1]\r\n                >> *('*' >> factor[boost::spirit::qi::_val *= boost::spirit::qi::_1]);\r\n            factor = boost::spirit::qi::uint_[boost::spirit::qi::_val = boost::spirit::qi::_1];\r\n        }\r\n    };\r\n\r\n    boost::optional<BigNumber> calculate(const std::string& str) {\r\n        BigNumber number = 0;\r\n        boost::optional<BigNumber> result;\r\n\r\n        calculator<std::string::const_iterator> calc;\r\n        if (phrase_parse(str.begin(), str.end(), calc, boost::spirit::ascii::space, number)) {\r\n            result = number;\r\n        }\r\n\r\n        return result;\r\n    }\r\n\r\n    void printValue(const boost::optional<BigNumber>& value, std::ostream& os) {\r\n        if (printValue_ == NumberSet::PRINT_VALUE::PRINT) {\r\n            os << *value << \" : \";\r\n        }\r\n        return;\r\n    }\r\n\r\n    ResultSet results_;\r\n    ResultMap resultMap_;\r\n    FILTER filter_;\r\n    PRINT_VALUE printValue_;\r\n};\r\n\r\nint main(int argc, char* argv[]) {\r\n    NumberSet::PRINT_VALUE printValue = (argc < 2) ?\r\n        NumberSet::PRINT_VALUE::NO_PRINT : NumberSet::PRINT_VALUE::PRINT;\r\n\r\n    if (argc < 6) {\r\n        // \u554f4-1\r\n        NumberSet s(1,4, NumberSet::FILTER::BY_EXPRESSION, printValue);\r\n        s.PrintSums(std::cout);\r\n\r\n        // \u554f4-2\r\n        NumberSet l(1,5, NumberSet::FILTER::BY_EXPRESSION, printValue);\r\n        NumberSet r(2,6, NumberSet::FILTER::BY_EXPRESSION, printValue);\r\n        l.PrintMatchedSums(r, std::cout);\r\n    } else {\r\n        std::string mode(argv[1]);\r\n        // \u5f15\u6570map\u3092\u3064\u3051\u308b\u3068\u3001\u9023\u60f3\u914d\u5217\u3092\u4f7f\u3063\u3066\u89e3\u304f\r\n        // \u5f15\u6570slow\u3092\u3064\u3051\u308b\u3068\u7dcf\u5f53\u305f\u308a\u3067\u89e3\u304f\u3001\u5b9f\u306fmap\u4ee5\u5916\u306e\u6587\u5b57\u5217\u306a\u3089\u4f55\u3067\u3082\u3088\u3044\r\n        NumberSet::FILTER filter = (mode == \"map\") ?\r\n            NumberSet::FILTER::BY_VALUE : NumberSet::FILTER::BY_EXPRESSION;\r\n\r\n        unsigned int minLeft  = boost::lexical_cast<decltype(minLeft)>(argv[2]);\r\n        unsigned int maxLeft  = boost::lexical_cast<decltype(maxLeft)>(argv[3]);\r\n        unsigned int minRight = boost::lexical_cast<decltype(minRight)>(argv[4]);\r\n        unsigned int maxRight = boost::lexical_cast<decltype(maxRight)>(argv[5]);\r\n        NumberSet l(minLeft,  maxLeft,  filter, printValue);\r\n        NumberSet r(minRight, maxRight, filter, printValue);\r\n        l.PrintMatchedSums(r, std::cout);\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n/*\r\nLocal Variables:\r\nmode: c++\r\ncoding: utf-8-dos\r\ntab-width: nil\r\nc-file-style: \"stroustrup\"\r\nEnd:\r\n*/\r\n", "meta": {"hexsha": "b44e50cc546f727d8853c50854875d6c0d8874c3", "size": 7948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2008math4c.cpp", "max_stars_repo_name": "zettsu-t/examQuestions", "max_stars_repo_head_hexsha": "f0481b33b0b5f11cc895b5430160c521f08ef998", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2008math4c.cpp", "max_issues_repo_name": "zettsu-t/examQuestions", "max_issues_repo_head_hexsha": "f0481b33b0b5f11cc895b5430160c521f08ef998", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2008math4c.cpp", "max_forks_repo_name": "zettsu-t/examQuestions", "max_forks_repo_head_hexsha": "f0481b33b0b5f11cc895b5430160c521f08ef998", "max_forks_repo_licenses": ["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.013215859, "max_line_length": 115, "alphanum_fraction": 0.5743583291, "num_tokens": 1966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.5973454803443834}}
{"text": "#pragma once\n#include \"functions.hpp\"\n#include <armadillo>\n#include <algorithm>\n#include <random>\n#include <cassert>\n#include <vector>\n\ntemplate <typename activation = Logistic, typename error = Squared_Error>\nstruct FeedForward_Network {\n  FeedForward_Network(std::vector<int> layer_sizes_in) : layer_sizes(layer_sizes_in) {\n\n    //For the connections inbetween layers\n    for (int i = 0; i < layer_sizes.size()-1; ++i) {\n      weights.push_back(arma::Mat<float>(layer_sizes[i], layer_sizes[i+1], arma::fill::zeros));\n      last_weights.push_back(arma::Mat<float>(layer_sizes[i], layer_sizes[i+1], arma::fill::zeros));\n    }\n  }\n\n  inline void resize_activation(int num_trials) {\n    activations.clear();\n    for (int i = 0; i < layer_sizes.size(); ++i) {\n      activations.push_back(arma::Mat<float>(num_trials, layer_sizes[i], arma::fill::zeros));\n    }\n\n    //No deltas for input layer\n    deltas.clear();\n    for (int i = 0; i < layer_sizes.size() - 1; ++i) {\n      deltas.push_back(arma::Mat<float>(num_trials, layer_sizes[i+1]));\n    }\n  }\n\n  //configuration of layers\n  std::vector<int> layer_sizes;\n\n  std::vector<arma::Mat<float>> weights;\n  //used in backprop with momentum\n  std::vector<arma::Mat<float>> last_weights;\n  std::vector<arma::Mat<float>> activations;\n  //used in backprop\n  std::vector<arma::Mat<float>> deltas;\n};\n", "meta": {"hexsha": "f873dfe5708c3f92181451d772c812c5d6a0617c", "size": 1340, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/net.hpp", "max_stars_repo_name": "lukemetz/Neural-Net-Experiments", "max_stars_repo_head_hexsha": "c50e93ec2f0e4acac2db7815174af71cf191420f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-02-24T17:17:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-05T09:46:37.000Z", "max_issues_repo_path": "src/net.hpp", "max_issues_repo_name": "lukemetz/Neural-Net-Experiments", "max_issues_repo_head_hexsha": "c50e93ec2f0e4acac2db7815174af71cf191420f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-04-09T00:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-09T00:41:28.000Z", "max_forks_repo_path": "src/net.hpp", "max_forks_repo_name": "lukemetz/Neural-Net-Experiments", "max_forks_repo_head_hexsha": "c50e93ec2f0e4acac2db7815174af71cf191420f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-03-29T15:24:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-11T07:45:41.000Z", "avg_line_length": 31.1627906977, "max_line_length": 100, "alphanum_fraction": 0.6798507463, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5973359355043508}}
{"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 <set>\n#include <string>\n#include <vector>\n\n#include <boost/variant.hpp>\n\nnamespace pnmc { namespace properties {\n\n/*------------------------------------------------------------------------------------------------*/\n\n// Integer formulae :: Arithmetic operators\nstruct integer_constant;\nstruct integer_sum;\nstruct integer_product;\nstruct integer_difference;\nstruct integer_division;\n\n// Integer formulae :: Petri net operators\nstruct place_bound\n{\n  std::vector<std::string> places;\n};\n\nstruct tokens_count\n{\n  std::vector<std::string> places;\n};\n\nusing integer_expression = 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                                         , place_bound\n                                         , tokens_count>;\n\n// Integer formulae :: Arithmetic operators\nstruct integer_constant\n{\n  int value;\n};\n\nstruct integer_sum\n{\n  std::vector<integer_expression> expressions;\n};\n\nstruct integer_product\n{\n  std::vector<integer_expression> expressions;\n};\n\nstruct integer_difference\n{\n  integer_expression lhs_expression;\n  integer_expression rhs_expression;\n};\n\nstruct integer_division\n{\n  integer_expression lhs_expression;\n  integer_expression rhs_expression;\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\n// Boolean formulae :: Reachability operators\nstruct invariant;\nstruct impossibility;\nstruct possibility;\n\n// Boolean formulae :: Petri net operators\nstruct deadlock {};\nstruct is_fireable\n{\n  std::vector<std::string> transitions;\n};\n\n// Boolean formulae :: Boolean operators\nstruct true_ {};\nstruct false_ {};\nstruct negation;\nstruct conjunction;\nstruct disjunction;\nstruct exclusive_disjonction;\nstruct implication;\nstruct equivalence;\n\n// Boolean formulae :: Comparison operators\nstruct integer_eq;\nstruct integer_ne;\nstruct integer_lt;\nstruct integer_le;\nstruct integer_gt;\nstruct integer_ge;\n\nusing boolean_expression = boost::variant< boost::recursive_wrapper<invariant>\n                                         , boost::recursive_wrapper<impossibility>\n                                         , boost::recursive_wrapper<possibility>\n                                         , deadlock\n                                         , is_fireable\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\n//// Boolean formulae :: Reachability operators\nstruct invariant\n{\n  boolean_expression expression;\n};\n\nstruct impossibility\n{\n  boolean_expression expression;\n};\n\nstruct possibility\n{\n  boolean_expression expression;\n};\n\n// Boolean formulae :: Boolean operators\nstruct negation\n{\n  boolean_expression expression;\n};\n\nstruct conjunction\n{\n  std::vector<boolean_expression> expressions;\n};\n\nstruct disjunction\n{\n  std::vector<boolean_expression> expressions;\n};\n\nstruct exclusive_disjonction\n{\n  std::vector<boolean_expression> expressions;\n};\n\nstruct implication\n{\n  boolean_expression lhs_expression;\n  boolean_expression rhs_expression;\n};\n\nstruct equivalence\n{\n  boolean_expression lhs_expression;\n  boolean_expression rhs_expression;\n};\n\n// Boolean formulae :: Comparison operators\nstruct integer_eq\n{\n  integer_expression lhs_expression;\n  integer_expression rhs_expression;\n};\n\nstruct integer_ne\n{\n  integer_expression lhs_expression;\n  integer_expression rhs_expression;\n};\n\nstruct integer_lt\n{\n  integer_expression lhs_expression;\n  integer_expression rhs_expression;\n};\n\nstruct integer_le\n{\n  integer_expression lhs_expression;\n  integer_expression rhs_expression;\n};\n\nstruct integer_gt\n{\n  integer_expression lhs_expression;\n  integer_expression rhs_expression;\n};\n\nstruct integer_ge\n{\n  integer_expression lhs_expression;\n  integer_expression rhs_expression;\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\nusing formula = boost::variant<boolean_expression, integer_expression>;\n\n/*------------------------------------------------------------------------------------------------*/\n\nstruct formulae\n{\n  bool compute_deadlock;\n  std::set<std::string> places_bounds;\n  std::set<std::string> fireable_transitions;\n\n  struct boolean\n  {\n    std::string id;\n    std::set<std::string> targets;\n    boolean_expression expression;\n  };\n\n  struct integer\n  {\n    std::string id;\n    std::set<std::string> targets;\n    integer_expression expression;\n  };\n\n  std::vector<boolean> booleans;\n  std::vector<integer> integers;\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\n}} // namespace pnmc::properties\n", "meta": {"hexsha": "4eb30eb5e95a4543d63df97a7896b46dc0afc8ed", "size": 6087, "ext": "hh", "lang": "C++", "max_stars_repo_path": "support/properties/formulae.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": "support/properties/formulae.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": "support/properties/formulae.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.9467213115, "max_line_length": 100, "alphanum_fraction": 0.5861672417, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.597254737621874}}
{"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_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_RSQRT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing rsqrt capabilities\n\n    Returns the inverse of the square root of the input.\n\n    @par semantic:\n\n    For any given value @c x of floating type @c T:\n\n    @code\n    T r = rsqrt(x);\n    @endcode\n\n    For signed type is similar to:\n\n    @code\n    T r = T(1)/sqrt(x)\n    @endcode\n\n    @par Decorators\n\n    - raw_ for floating entries: if full accuracy is not needed a sometimes rawer less accurate version of the function\n    can be obtained using the the raw_ decorator : raw_(rsqrt)(x).\n\n    @par Decorators\n\n  **/\n  Value rsqrt(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/rsqrt.hpp>\n#include <boost/simd/function/scalar/rsqrt.hpp>\n#include <boost/simd/function/simd/rsqrt.hpp>\n\n#endif\n", "meta": {"hexsha": "cc4ff99e88d07cc97372812f3b8112aea997335b", "size": 1327, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/rsqrt.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "include/boost/simd/function/rsqrt.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/rsqrt.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 23.6964285714, "max_line_length": 119, "alphanum_fraction": 0.6028636021, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5972547266018077}}
{"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": "#include <ndt_map/ndt_cell.h>\n#include <ndt_map/lazy_grid.h>\n#include <ndt_map/pointcloud_utils.h>\n#include <ndt_registration/ndt_matcher_d2d_sc.h>\n#include <ndt_generic/eigen_utils.h>\n\n#include <Eigen/Eigen>\n#include <fstream>\n#include <omp.h>\n#include <sys/time.h>\n\n\nnamespace perception_oru\n{\n\n// inline void convertAffine3dToMatrix61(const Eigen::Affine3d &T, Eigen::Matrix<double,6,1> &v) {\n//     Eigen::Vector3d transl = T.translation();\n//     v(0) = transl(0);\n//     v(1) = transl(1);\n//     v(2) = transl(2);\n\n//     Eigen::Vector3d rot = T.rotation().eulerAngles(0,1,2);\n//     v(3) = rot(0);\n//     v(4) = rot(1);\n//     v(5) = rot(2);\n\n    \n// }\n\nEigen::MatrixXd computeHessianMahalanobis(const Eigen::MatrixXd &Q) {\n  // Compute the Hessian for the mahalanobis distance Q = the inverse of the covariance matrix(!)\n  Eigen::MatrixXd H(6,6);\n  H << Q(0,0)+Q(0,0), Q(1,0)+Q(0,1), Q(2,0)+Q(0,2), Q(3,0)+Q(0,3), Q(4,0)+Q(0,4), Q(5,0)+Q(0,5),\n       Q(0,1)+Q(1,0), Q(1,1)+Q(1,1), Q(2,1)+Q(1,2), Q(3,1)+Q(1,3), Q(4,1)+Q(1,4), Q(5,1)+Q(1,5),\n       Q(0,2)+Q(2,0), Q(1,2)+Q(2,1), Q(2,2)+Q(2,2), Q(3,2)+Q(2,3), Q(4,2)+Q(2,4), Q(5,2)+Q(2,5),\n       Q(0,3)+Q(3,0), Q(1,3)+Q(3,1), Q(2,3)+Q(3,2), Q(3,3)+Q(3,3), Q(4,3)+Q(3,4), Q(5,3)+Q(3,5),\n       Q(0,4)+Q(4,0), Q(1,4)+Q(4,1), Q(2,4)+Q(4,2), Q(3,4)+Q(4,3), Q(4,4)+Q(4,4), Q(5,4)+Q(4,5),\n       Q(0,5)+Q(5,0), Q(1,5)+Q(5,1), Q(2,5)+Q(5,2), Q(3,5)+Q(5,3), Q(4,5)+Q(5,4), Q(5,5)+Q(5,5);\n\n  // A 3DOF hessian...\n  // H << \n  //   Q(0,0)+Q(0,0), Q(1,0)+Q(0,1), 0., 0., 0., Q(5,0)+Q(0,5),\n  //   Q(0,1)+Q(1,0), Q(1,1)+Q(1,1), 0., 0., 0., Q(5,1)+Q(1,5),\n  //   0., 0., 0., 0., 0., 0.,\n  //   0., 0., 0., 0., 0., 0.,\n  //   0., 0., 0., 0., 0., 0.,\n  //   Q(0,5)+Q(5,0), Q(1,5)+Q(5,1), 0., 0., 0., Q(5,5)+Q(5,5);\n\n  //  H.setZero();\n       \n  return H;\n}\n\ndouble computeScoreMahalanobis(const Eigen::Matrix<double,6,1> &x,\n                               const Eigen::MatrixXd &Q) {\n  return x.transpose()*Q*x;\n  //  return 0.;\n}\n\nEigen::Matrix<double,6,1> computeGradientMahalanobis(const Eigen::Matrix<double,6,1> &x,\n                                                     const Eigen::MatrixXd &Q) {\n  return computeHessianMahalanobis(Q)*x;\n}\n\n\ndouble NDTMatcherD2DSC::lineSearchMTSC(Eigen::Matrix<double,6,1> &increment,\n                                       std::vector<NDTCell*> &sourceNDT,\n                                       NDTMap &targetNDT,\n                                       const Eigen::Matrix<double,6,1> &localpose,\n                                       const Eigen::MatrixXd &Q,\n                                       const Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> &T)\n{\n    // default params\n    double stp = 1.0; //default step\n    double recoverystep = 0.1;\n    double dginit = 0.0;\n    double ftol = 0.11111; //epsilon 1\n    double gtol = 0.99999; //epsilon 2\n    double stpmax = 4.0;\n    double stpmin = 0.001;\n    int maxfev = 40; //max function evaluations\n    double xtol = 0.01; //window of uncertainty around the optimal step\n\n    //my temporary variables\n    std::vector<NDTCell*> sourceNDTHere;\n    double score_init = 0.0;\n\n    Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> ps;\n    ps.setIdentity();\n\n    Eigen::Matrix<double,6,1> scg_here;\n    Eigen::MatrixXd pincr(6,1), score_gradient_here(6,1);\n    Eigen::MatrixXd pseudoH(6,6);\n    Eigen::Vector3d eulerAngles;\n    Eigen::Matrix<double,6,1> X = localpose;\n\n    /////\n\n    int info = 0;\t\t\t// return code\n    int infoc = 1;\t\t// return code for subroutine cstep\n\n    // Compute the initial gradient in the search direction and check\n    // that s is a descent direction.\n    score_gradient_here.setZero();\n    score_init = derivativesNDT(sourceNDT,targetNDT,score_gradient_here,pseudoH,false);\n    score_init += computeScoreMahalanobis(X,Q);\n    score_gradient_here += computeGradientMahalanobis(X,Q);\n\n    scg_here = score_gradient_here;\n    dginit = increment.dot(scg_here);\n\n    if (dginit >= 0.0)\n    {\n        std::cout << \"MoreThuente::cvsrch - wrong direction (dginit = \" << dginit << \")\" << std::endl;\n        //return recoverystep; //TODO TSV -1; //\n        //return -1;\n\n        increment = -increment;\n        dginit = -dginit;\n\n        if (dginit >= 0.0)\n        {\n            for(unsigned int i=0; i<sourceNDTHere.size(); i++)\n            {\n                if(sourceNDTHere[i]!=NULL)\n                    delete sourceNDTHere[i];\n            }\n            return recoverystep;\n        }\n    }\n    else\n    {\n\n    }\n\n    // Initialize local variables.\n\n    bool brackt = false;\t\t// has the soln been bracketed?\n    bool stage1 = true;\t\t// are we in stage 1?\n    int nfev = 0;\t\t\t// number of function evaluations\n    double dgtest = ftol * dginit; // f for curvature condition\n    double width = stpmax - stpmin; // interval width\n    double width1 = 2 * width;\t// ???\n\n    // initial function value\n    double finit = 0.0;\n    finit = score_init;\n\n    // The variables stx, fx, dgx contain the values of the step,\n    // function, and directional derivative at the best step.  The\n    // variables sty, fy, dgy contain the value of the step, function,\n    // and derivative at the other endpoint of the interval of\n    // uncertainty.  The variables stp, f, dg contain the values of the\n    // step, function, and derivative at the current step.\n\n    double stx = 0.0;\n    double fx = finit;\n    double dgx = dginit;\n    double sty = 0.0;\n    double fy = finit;\n    double dgy = dginit;\n\n    // Get the linear solve tolerance for adjustable forcing term\n    //double eta_original = -1.0;\n    //double eta = 0.0;\n    //eta = eta_original;\n\n    // Start of iteration.\n\n    double stmin, stmax;\n    double fm, fxm, fym, dgm, dgxm, dgym;\n\n    while (1)\n    {\n        // Set the minimum and maximum steps to correspond to the present\n        // interval of uncertainty.\n        if (brackt)\n        {\n            stmin = MoreThuente::min(stx, sty);\n            stmax = MoreThuente::max(stx, sty);\n        }\n        else\n        {\n            stmin = stx;\n            stmax = stp + 4 * (stp - stx);\n        }\n\n        // Force the step to be within the bounds stpmax and stpmin.\n        stp = MoreThuente::max(stp, stpmin);\n        stp = MoreThuente::min(stp, stpmax);\n\n        // If an unusual termination is to occur then let stp be the\n        // lowest point obtained so far.\n\n        if ((brackt && ((stp <= stmin) || (stp >= stmax))) ||\n                (nfev >= maxfev - 1) || (infoc == 0) ||\n                (brackt && (stmax - stmin <= xtol * stmax)))\n        {\n            stp = stx;\n        }\n\n        // Evaluate the function and gradient at stp\n        // and compute the directional derivative.\n        ///////////////////////////////////////////////////////////////////////////\n\n        pincr = stp*increment;\n\n        ps = Eigen::Translation<double,3>(pincr(0),pincr(1),pincr(2))*\n             Eigen::AngleAxisd(pincr(3),Eigen::Vector3d::UnitX())*\n             Eigen::AngleAxisd(pincr(4),Eigen::Vector3d::UnitY())*\n             Eigen::AngleAxisd(pincr(5),Eigen::Vector3d::UnitZ());\n\n        for(unsigned int i=0; i<sourceNDTHere.size(); i++)\n        {\n            if(sourceNDTHere[i]!=NULL)\n                delete sourceNDTHere[i];\n        }\n        sourceNDTHere.clear();\n        for(unsigned int i=0; i<sourceNDT.size(); i++)\n        {\n            NDTCell *cell = sourceNDT[i];\n            if(cell!=NULL)\n            {\n                Eigen::Vector3d mean = cell->getMean();\n                Eigen::Matrix3d cov = cell->getCov();\n                mean = ps*mean;\n                cov = ps.rotation()*cov*ps.rotation().transpose();\n                NDTCell* nd = (NDTCell*)cell->copy();\n                nd->setMean(mean);\n                nd->setCov(cov);\n                sourceNDTHere.push_back(nd);\n            }\n        }\n\n        Eigen::Affine3d T_previous = T;\n        Eigen::Affine3d T_current = ps*T; // Note that ps is not an incremental part, it is redefined in each loop from frame T.\n        \n        Eigen::Vector3d Tposition_diff = T_current.translation() - T_previous.translation();\n        \n        //        std::cerr << \"Tposition_diff : \" << Tposition_diff.transpose() << std::endl;\n        //        std::cerr << \"pincr : \" << pincr.transpose() << std::endl;\n\n        double f = 0.0;\n        score_gradient_here.setZero();\n\n        f = derivativesNDT(sourceNDTHere,targetNDT,score_gradient_here,pseudoH,false);\n        // X is defined in global coords...\n        X(0) = localpose(0) + Tposition_diff(0);\n        X(1) = localpose(1) + Tposition_diff(1);\n        X(2) = localpose(2) + Tposition_diff(2);\n        X(3) = localpose(3) + pincr(3);\n        X(4) = localpose(3) + pincr(4);\n        X(5) = localpose(3) + pincr(5);\n\n        f += computeScoreMahalanobis(X,Q);\n        score_gradient_here += computeGradientMahalanobis(X,Q);\n\n        double dg = 0.0;\n        scg_here = score_gradient_here;\n        dg = increment.dot(scg_here);\n\n\n        nfev ++;\n\n///////////////////////////////////////////////////////////////////////////\n\n        // Armijo-Goldstein sufficient decrease\n        double ftest1 = finit + stp * dgtest;\n\n        // Test for convergence.\n\n        if ((brackt && ((stp <= stmin) || (stp >= stmax))) || (infoc == 0))\n            info = 6;\t\t\t// Rounding errors\n\n        if ((stp == stpmax) && (f <= ftest1) && (dg <= dgtest))\n            info = 5;\t\t\t// stp=stpmax\n\n        if ((stp == stpmin) && ((f > ftest1) || (dg >= dgtest)))\n            info = 4;\t\t\t// stp=stpmin\n\n        if (nfev >= maxfev)\n            info = 3;\t\t\t// max'd out on fevals\n\n        if (brackt && (stmax-stmin <= xtol*stmax))\n            info = 2;\t\t\t// bracketed soln\n\n        // RPP sufficient decrease test can be different\n        bool sufficientDecreaseTest = false;\n        sufficientDecreaseTest = (f <= ftest1);  // Armijo-Golstein\n\n        if ((sufficientDecreaseTest) && (fabs(dg) <= gtol*(-dginit)))\n            info = 1;\t\t\t// Success!!!!\n\n        if (info != 0) \t\t// Line search is done\n        {\n            if (info != 1) \t\t// Line search failed\n            {\n                stp = recoverystep;\n            }\n            else \t\t\t// Line search succeeded\n            {\n\n            }\n            // Returning the line search flag\n            for(unsigned int i=0; i<sourceNDTHere.size(); i++)\n            {\n                if(sourceNDTHere[i]!=NULL)\n                    delete sourceNDTHere[i];\n            }\n            return stp;\n\n        } // info != 0\n\n        // In the first stage we seek a step for which the modified\n        // function has a nonpositive value and nonnegative derivative.\n\n        if (stage1 && (f <= ftest1) && (dg >= MoreThuente::min(ftol, gtol) * dginit))\n        {\n            stage1 = false;\n        }\n\n        // A modified function is used to predict the step only if we have\n        // not obtained a step for which the modified function has a\n        // nonpositive function value and nonnegative derivative, and if a\n        // lower function value has been obtained but the decrease is not\n        // sufficient.\n\n        if (stage1 && (f <= fx) && (f > ftest1))\n        {\n\n            // Define the modified function and derivative values.\n\n            fm = f - stp * dgtest;\n            fxm = fx - stx * dgtest;\n            fym = fy - sty * dgtest;\n            dgm = dg - dgtest;\n            dgxm = dgx - dgtest;\n            dgym = dgy - dgtest;\n\n            // Call cstep to update the interval of uncertainty\n            // and to compute the new step.\n\n            infoc = MoreThuente::cstep(stx,fxm,dgxm,sty,fym,dgym,stp,fm,dgm,\n                                       brackt,stmin,stmax);\n\n            // Reset the function and gradient values for f.\n\n            fx = fxm + stx*dgtest;\n            fy = fym + sty*dgtest;\n            dgx = dgxm + dgtest;\n            dgy = dgym + dgtest;\n\n        }\n\n        else\n        {\n\n            // Call cstep to update the interval of uncertainty\n            // and to compute the new step.\n\n            infoc = MoreThuente::cstep(stx,fx,dgx,sty,fy,dgy,stp,f,dg,\n                                       brackt,stmin,stmax);\n\n        }\n\n        // Force a sufficient decrease in the size of the\n        // interval of uncertainty.\n\n        if (brackt)\n        {\n            if (fabs(sty - stx) >= 0.66 * width1)\n                stp = stx + 0.5 * (sty - stx);\n            width1 = width;\n            width = fabs(sty-stx);\n        }\n\n    } // while-loop\n}\n\nvoid NDTMatcherD2DSC::scoreComparision( NDTMap& targetNDT,\n                                        NDTMap& sourceNDT,\n                                        const Eigen::Affine3d &T,\n                                        const Eigen::MatrixXd& Tcov,\n                                        double &score_NDT,\n                                        double &score_NDT_SC,\n                                        const Eigen::Affine3d &offset,\n                                        const Eigen::Affine3d &odom_offset,\n                                        double alpha)\n{\n    Eigen::MatrixXd Hessian(6,6), score_gradient(6,1);\n    std::vector<NDTCell*> nextNDT = sourceNDT.pseudoTransformNDT(T*offset);\n    score_NDT = derivativesNDT(nextNDT,targetNDT,score_gradient,Hessian,false);\n    Eigen::VectorXd X = ndt_generic::affine3dToVector(odom_offset);\n    ndt_generic::normalizeEulerAngles6dVec(X);\n    Eigen::MatrixXd Q = Tcov.inverse();\n\n    score_NDT_SC = score_NDT + alpha*computeScoreMahalanobis(X,Q);\n    \n    for(unsigned int i=0; i<nextNDT.size(); i++)\n    {\n        if(nextNDT[i]!=NULL)\n            delete nextNDT[i];\n    }\n}\n\nbool NDTMatcherD2DSC::match( NDTMap& targetNDT,\n        NDTMap& sourceNDT,\n        Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor>& T ,\n        const Eigen::MatrixXd& Tcov)\n{\n\n    //locals\n    bool convergence = false;\n    //double score=0;\n    double score_best = INT_MAX;\n    //double DELTA_SCORE = 0.0005;\n    //double NORM_MAX = current_resolution, ROT_MAX = M_PI/10; //\n    int itr_ctr = 0;\n    //double alpha = 0.95;\n    double step_size = 1;\n    Eigen::Matrix<double,6,1>  pose_increment_v, scg, pose_local_v, pose_increment_v_Tframe;\n    Eigen::MatrixXd Hessian(6,6), score_gradient(6,1); //column vectors, pose_increment_v(6,1)\n    Eigen::MatrixXd Q = Tcov.inverse();\n\n    //    std::cout << \"Q1 : \" << Q << std::endl;\n    if (only_xy_motion) {\n      Eigen::MatrixXd Q_tmp = Q;\n      Q.setZero();\n      Q.block(0,0,2,2) = Q_tmp.block(0,0,2,2);\n    }\n    if (lock_zrp_motion) {\n      Q(2,2) = 0; // !0\n      Q(3,3) = 1000000000;\n      Q(4,4) = 1000000000;\n    }\n    //    std::cout << \"Q2 : \" << Q << std::endl;\n\n    Eigen::Matrix<double,6,1> X;\n    Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> TR, Tbest;\n    Eigen::Vector3d transformed_vec, mean;\n    bool ret = true;\n\n    Eigen::Affine3d Tinit = T;\n\n    Tbest = T;\n    pose_local_v.setZero();\n\n\n    Eigen::Array<double,6,1> weights;\n    std::vector<NDTCell*> nextNDT = sourceNDT.pseudoTransformNDT(T);\n\n    int iter = 0;\n    int best_iter; \n    this->nb_match_calls++;\n    bool found_improvement = false;\n    \n    double alpha = 0.0; // \n\n    while(!convergence)\n    {\n      iter++;\n        TR.setIdentity();\n        Hessian.setZero();\n        score_gradient.setZero();\n\n        double score_here = derivativesNDT(nextNDT,targetNDT,score_gradient,Hessian,true);\n        X = pose_local_v;\n\n        if (lock_zrp_motion) {\n          // Assign the X to be the offset between global z and global roll, pitch.\n          X(2) = T.translation()[2];\n          // No Euler angles, simply compute the roll and pitch as separate angles.\n          double pitch = asin(T.rotation()(2,0)); // Z offset along the x axis...\n          double roll = asin(T.rotation()(2,1));  // Z offset along the y axis...\n          X(3) = roll;  //T.rotation().eulerAngles(0,1,2)[0];\n          X(4) = pitch; //T.rotation().eulerAngles(0,1,2)[1];\n          std::cout << \"[\" << X.transpose() << \"]\";\n        }\n\n        //        std::cout << \"score_here : \" << score_here << std::flush;\n        score_here += alpha*computeScoreMahalanobis(X,Q);\n        //        std::cout << \" <-> score_here2 : \" << computeScoreMahalanobis(X,Q) << std::endl;\n        score_gradient += alpha*computeGradientMahalanobis(X,Q);\n        //        std::cout << \"Hessian : \\n\" << Hessian << std::endl;\n        Hessian += alpha*computeHessianMahalanobis(Q);\n        //        std::cout << \"Hessian2 : \\n\" << computeHessianMahalanobis(Q) << std::endl;\n\n        scg = score_gradient;\n\tif(score_here < score_best) \n\t{\n\t    Tbest = T;\n\t    score_best = score_here;\n            if (iter > 1) {\n              if (!found_improvement) {\n                this->nb_success_reg++;\n                found_improvement = true;\n                alpha = 1.;\n              }\n              std::cerr << \"[\" << iter << \"] X : \" << X.transpose() << \" -- \" << score_here << std::endl;\n            }\n\t}\n        else {\n          //            std::cerr << \"X : \" << X.transpose() << std::flush;\n        }\n\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double,6,6> > Sol (Hessian);\n        Eigen::Matrix<double,6,1> evals = Sol.eigenvalues().real();\n        double minCoeff = evals.minCoeff();\n        double maxCoeff = evals.maxCoeff();\n        if(minCoeff < 0)  //|| evals.minCoeff()) // < 10e-5*evals.maxCoeff()) \n        {\n\t    if(regularize) {\n\t\tEigen::Matrix<double,6,6> evecs = Sol.eigenvectors().real();\n\t\tdouble regularizer = score_gradient.norm();\n\t\tregularizer = regularizer + minCoeff > 0 ? regularizer : 0.001*maxCoeff - minCoeff;\n\t\t//double regularizer = 0.001*maxCoeff - minCoeff;\n\t\tEigen::Matrix<double,6,1> reg;\n\t\t//ugly\n\t\treg<<regularizer,regularizer,regularizer,regularizer,regularizer,regularizer;\n\t\tevals += reg;\n\t\tEigen::Matrix<double,6,6> Lam;\n\t\tLam = evals.asDiagonal();\n\t\tHessian = evecs*Lam*(evecs.transpose());\n\t    } else {\n\t\tif(score_here > score_best) \n\t\t{\n\t\t    T = Tbest;\n\t\t}\n\t\t//de-alloc nextNDT\n\t\tfor(unsigned int i=0; i<nextNDT.size(); i++)\n\t\t{\n\t\t    if(nextNDT[i]!=NULL)\n\t\t\tdelete nextNDT[i];\n\t\t}\n\t\treturn true;\n\t    }\n        }\n        if (score_gradient.norm()<= DELTA_SCORE)\n        {\n\t    if(score_here > score_best) \n\t    {\n\t\tT = Tbest;\n\t    }\n            //de-alloc nextNDT\n            for(unsigned int i=0; i<nextNDT.size(); i++)\n            {\n                if(nextNDT[i]!=NULL)\n                    delete nextNDT[i];\n            }\n            return true;\n        }\n\n        //        std::cerr << \" score_here : \" << score_here << \" score_gradient : \" << score_gradient.transpose() << std::endl;\n\n        pose_increment_v = -Hessian.ldlt().solve(score_gradient);\n\n        double dginit = pose_increment_v.dot(scg);\n        if(dginit > 0)\n        {\n            //de-alloc nextNDT\n\t    if(score_here > score_best) \n\t    {\n\t\tT = Tbest;\n\t    }\n            for(unsigned int i=0; i<nextNDT.size(); i++)\n            {\n                if(nextNDT[i]!=NULL)\n                    delete nextNDT[i];\n            }\n            return true;\n        }\n        //check direction here:\n\n\tif(step_control) {\n          step_size = lineSearchMTSC(pose_increment_v,nextNDT,targetNDT,pose_local_v, Q, T);\n\t} else {\n\t    step_size = 1;\n\t}\n        pose_increment_v = step_size*pose_increment_v;\n\n        // const double max_step = 1.0;\n        // if (pose_increment_v.norm() > max_step) {\n        //   pose_increment_v.normalize();\n        //   pose_increment_v *= max_step;\n        // }\n\n        TR.setIdentity();\n        TR =  Eigen::Translation<double,3>(pose_increment_v(0),pose_increment_v(1),pose_increment_v(2))*\n              Eigen::AngleAxis<double>(pose_increment_v(3),Eigen::Vector3d::UnitX()) *\n              Eigen::AngleAxis<double>(pose_increment_v(4),Eigen::Vector3d::UnitY()) *\n              Eigen::AngleAxis<double>(pose_increment_v(5),Eigen::Vector3d::UnitZ()) ;\n\n        // Make sure that the pose_local_v is updated with the right frame(!)\n        Eigen::Affine3d T_previous = T;\n        T = TR*T;\n        Eigen::Affine3d T_current = T;\n        Eigen::Vector3d Tposition_diff = T_current.translation() - T_previous.translation();\n\n        pose_increment_v_Tframe = pose_increment_v;\n        pose_increment_v_Tframe(0) = Tposition_diff(0);\n        pose_increment_v_Tframe(1) = Tposition_diff(1);\n        pose_increment_v_Tframe(2) = Tposition_diff(2);\n        pose_local_v += pose_increment_v_Tframe;\n\n        for(unsigned int i=0; i<nextNDT.size(); i++)\n        {\n\t    //TRANSFORM\n\t    Eigen::Vector3d meanC = nextNDT[i]->getMean();\n\t    Eigen::Matrix3d covC = nextNDT[i]->getCov();\n\t    meanC = TR*meanC;\n\t    covC = TR.rotation()*covC*TR.rotation().transpose();\n\t    nextNDT[i]->setMean(meanC);\n\t    nextNDT[i]->setCov(covC);\n        }\n\n        if(itr_ctr>0)\n        {\n            convergence = ((pose_increment_v.norm()) < DELTA_SCORE);\n        }\n        if(itr_ctr>ITR_MAX)\n        {\n            convergence = true;\n            ret = false;\n        }\n        itr_ctr++;\n    }\n    \n    score_gradient.setZero();\n    double score_here = derivativesNDT(nextNDT,targetNDT,score_gradient,Hessian,false);\n    X = pose_local_v;\n    if (lock_zrp_motion) {\n      // Assign the X to be the offset between global z and global roll, pitch.\n      X(2) = T.translation()[2];\n      // No Euler angles, simply compute the roll and pitch as separate angles.\n      double pitch = asin(T.rotation()(2,0)); // Z offset along the x axis...\n      double roll = asin(T.rotation()(2,1));  // Z offset along the y axis...\n      X(3) = roll;  //T.rotation().eulerAngles(0,1,2)[0];\n      X(4) = pitch; //T.rotation().eulerAngles(0,1,2)[1];\n      std::cout << \"[\" << X.transpose() << \"]\";\n    }\n    \n    score_here += alpha*computeScoreMahalanobis(X,Q);\n    if(score_here > score_best) \n    {\n\tT = Tbest;\n    }\n    for(unsigned int i=0; i<nextNDT.size(); i++)\n    {\n\tif(nextNDT[i]!=NULL)\n\t    delete nextNDT[i];\n    }\n\n    return ret;\n}\n} // namespace\n", "meta": {"hexsha": "c84d5ba006d7fecd823ed5a445386869187aebc1", "size": 21844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_registration/src/ndt_matcher_d2d_sc.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_registration/src/ndt_matcher_d2d_sc.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_registration/src/ndt_matcher_d2d_sc.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.2987804878, "max_line_length": 129, "alphanum_fraction": 0.5373557956, "num_tokens": 6380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5971857319917532}}
{"text": "#include <igl/cat.h>\n#include <igl/edge_lengths.h>\n#include <igl/parula.h>\n#include <igl/per_edge_normals.h>\n#include <igl/per_face_normals.h>\n#include <igl/per_vertex_normals.h>\n#include <igl/point_mesh_squared_distance.h>\n#include <igl/readMESH.h>\n#include <igl/signed_distance.h>\n#include <igl/slice_mask.h>\n#include <igl/slice_tets.h>\n#include <igl/upsample.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <igl/writeOBJ.h>\n#include <Eigen/Sparse>\n#include <iostream>\n\n#include \"tutorial_shared_path.h\"\n\nEigen::MatrixXd V;\nEigen::MatrixXi T,F;\nigl::AABB<Eigen::MatrixXd,3> tree;\nEigen::MatrixXd FN,VN,EN;\nEigen::MatrixXi E;\nEigen::VectorXi EMAP;\ndouble max_distance = 1;\n\ndouble slice_z = 0.5;\nbool overlay = false;\n\nvoid update_visualization(igl::opengl::glfw::Viewer & viewer)\n{\n  using namespace Eigen;\n  using namespace std;\n  Eigen::Vector4d plane(\n    0,0,1,-((1-slice_z)*V.col(2).minCoeff()+slice_z*V.col(2).maxCoeff()));\n  MatrixXd V_vis;\n  MatrixXi F_vis;\n  // Extract triangle mesh slice through volume mesh and subdivide nasty\n  // triangles\n  {\n    VectorXi J;\n    SparseMatrix<double> bary;\n    {\n      // Value of plane's implicit function at all vertices\n      const VectorXd IV = \n        (V.col(0)*plane(0) + \n         V.col(1)*plane(1) + \n         V.col(2)*plane(2)).array()\n        + plane(3);\n      igl::slice_tets(V,T,IV,V_vis,F_vis,J,bary);\n      igl::writeOBJ(\"vis.obj\",V_vis,F_vis);\n    }\n    while(true)\n    {\n      MatrixXd l;\n      igl::edge_lengths(V_vis,F_vis,l);\n      l /= (V_vis.colwise().maxCoeff() - V_vis.colwise().minCoeff()).norm();\n      const double max_l = 0.03;\n      if(l.maxCoeff()<max_l)\n      {\n        break;\n      }\n      Array<bool,Dynamic,1> bad = l.array().rowwise().maxCoeff() > max_l;\n      MatrixXi F_vis_bad, F_vis_good;\n      igl::slice_mask(F_vis,bad,1,F_vis_bad);\n      igl::slice_mask(F_vis,(bad!=true).eval(),1,F_vis_good);\n      igl::upsample(V_vis,F_vis_bad);\n      F_vis = igl::cat(1,F_vis_bad,F_vis_good);\n    }\n  }\n\n  // Compute signed distance\n  VectorXd S_vis;\n  {\n    VectorXi I;\n    MatrixXd N,C;\n    // Bunny is a watertight mesh so use pseudonormal for signing\n    signed_distance_pseudonormal(V_vis,V,F,tree,FN,VN,EN,EMAP,S_vis,I,C,N);\n  }\n  // push to [0,1] range\n  S_vis.array() = 0.5*(S_vis.array()/max_distance)+0.5;\n  MatrixXd C_vis;\n  // color without normalizing\n  igl::parula(S_vis,false,C_vis);\n\n\n  const auto & append_mesh = [&C_vis,&F_vis,&V_vis](\n    const Eigen::MatrixXd & V,\n    const Eigen::MatrixXi & F,\n    const RowVector3d & color)\n  {\n    F_vis.conservativeResize(F_vis.rows()+F.rows(),3);\n    F_vis.bottomRows(F.rows()) = F.array()+V_vis.rows();\n    V_vis.conservativeResize(V_vis.rows()+V.rows(),3);\n    V_vis.bottomRows(V.rows()) = V;\n    C_vis.conservativeResize(C_vis.rows()+V.rows(),3);\n    C_vis.bottomRows(V.rows()).rowwise() = color;\n  };\n  if(overlay)\n  {\n    append_mesh(V,F,RowVector3d(0.8,0.8,0.8));\n  }\n  viewer.data().clear();\n  viewer.data().set_mesh(V_vis,F_vis);\n  viewer.data().set_colors(C_vis);\n  viewer.core.lighting_factor = overlay;\n}\n\nbool key_down(igl::opengl::glfw::Viewer& viewer, unsigned char key, int mod)\n{\n  switch(key)\n  {\n    default:\n      return false;\n    case ' ':\n      overlay ^= true;\n      break;\n    case '.':\n      slice_z = std::min(slice_z+0.01,0.99);\n      break;\n    case ',':\n      slice_z = std::max(slice_z-0.01,0.01);\n      break;\n  }\n  update_visualization(viewer);\n  return true;\n}\n\nint main(int argc, char *argv[])\n{\n  using namespace Eigen;\n  using namespace std;\n\n  cout<<\"Usage:\"<<endl;\n  cout<<\"[space]  toggle showing surface.\"<<endl;\n  cout<<\"'.'/','  push back/pull forward slicing plane.\"<<endl;\n  cout<<endl;\n\n  // Load mesh: (V,T) tet-mesh of convex hull, F contains original surface\n  // triangles\n  igl::readMESH(TUTORIAL_SHARED_PATH \"/bunny.mesh\",V,T,F);\n\n\n  // Encapsulated call to point_mesh_squared_distance to determine bounds\n  {\n    VectorXd sqrD;\n    VectorXi I;\n    MatrixXd C;\n    igl::point_mesh_squared_distance(V,V,F,sqrD,I,C);\n    max_distance = sqrt(sqrD.maxCoeff());\n  }\n\n  // Precompute signed distance AABB tree\n  tree.init(V,F);\n  // Precompute vertex,edge and face normals\n  igl::per_face_normals(V,F,FN);\n  igl::per_vertex_normals(\n    V,F,igl::PER_VERTEX_NORMALS_WEIGHTING_TYPE_ANGLE,FN,VN);\n  igl::per_edge_normals(\n    V,F,igl::PER_EDGE_NORMALS_WEIGHTING_TYPE_UNIFORM,FN,EN,E,EMAP);\n\n  // Plot the generated mesh\n  igl::opengl::glfw::Viewer viewer;\n  update_visualization(viewer);\n  viewer.callback_key_down = &key_down;\n  viewer.data().show_lines = false;\n  viewer.launch();\n}\n", "meta": {"hexsha": "67cadbffb805f1c7705069eba421f904d180a2ee", "size": 4565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FSDF/libs/libigl-master/tutorial/704_SignedDistance/main.cpp", "max_stars_repo_name": "szat/FSDF", "max_stars_repo_head_hexsha": "076129c0dfd2ac2354cc40ade363b96f4b6248fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FSDF/libs/libigl-master/tutorial/704_SignedDistance/main.cpp", "max_issues_repo_name": "szat/FSDF", "max_issues_repo_head_hexsha": "076129c0dfd2ac2354cc40ade363b96f4b6248fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FSDF/libs/libigl-master/tutorial/704_SignedDistance/main.cpp", "max_forks_repo_name": "szat/FSDF", "max_forks_repo_head_hexsha": "076129c0dfd2ac2354cc40ade363b96f4b6248fa", "max_forks_repo_licenses": ["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.8529411765, "max_line_length": 76, "alphanum_fraction": 0.6593647317, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5971303041587729}}
{"text": "#define BOOST_TEST_MODULE \"Testing Manhattan Functions\"\n\n#include <boost/test/unit_test.hpp>\n\n#include \"distance/Manhattan.hpp\"\n\nusing namespace genex;\n#define TOLERANCE 1e-9\n\nBOOST_AUTO_TEST_CASE( mandist, *boost::unit_test::tolerance(TOLERANCE) )\n{\n   Manhattan d;\n\n   TimeSeries ts_1 {NULL, 0, 0, 2};\n   TimeSeries ts_2 {NULL, 0, 0, 2};\n\n   data_t a = d.dist(100.0, 110.0);\n   data_t prev = d.init(); //0\n   data_t first  = d.reduce(prev, prev, 60.0, 10.0); //50\n   data_t second = d.reduce(first, first, 15.0, 5.0);\n   data_t c = d.norm(second, ts_1, ts_2);\n\n   d.clean(second);\n\n   BOOST_TEST( a == 10 );\n   BOOST_TEST( c == 30 );\n}\n", "meta": {"hexsha": "aa86c16dbb5be40c54533504970be536ea474318", "size": 638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distance/ManhattanTest.cpp", "max_stars_repo_name": "mihinsumaria/genex", "max_stars_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-28T07:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T07:49:24.000Z", "max_issues_repo_path": "test/distance/ManhattanTest.cpp", "max_issues_repo_name": "mihinsumaria/genex", "max_issues_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/distance/ManhattanTest.cpp", "max_forks_repo_name": "mihinsumaria/genex", "max_forks_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T20:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T20:25:42.000Z", "avg_line_length": 22.7857142857, "max_line_length": 72, "alphanum_fraction": 0.6567398119, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5971303041127226}}
{"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": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE snowlib\n\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_tools.hpp>\n#include <ostream>\n\nnamespace tt = boost::test_tools;\n\n#include \"../lib/conjugate_residual_solver.h\"\n#include \"../lib/SnowSolver.h\"\n#include \"../lib/LavaSolver.h\"\n\n\n// A[3x3]\nvoid A(std::vector<double> &Ax, std::vector<double> const &x) {\n    Ax[0] = 2 * x[0] + x[1] + x[2];\n    Ax[1] = x[0] + 2 * x[1] + x[2];\n    Ax[2] = x[0] + x[1] + 2 * x[2];\n}\n\n// B[3x3]\nvoid B(std::vector<glm::dvec3> &Ax, std::vector<glm::dvec3> const &x) {\n    Ax[0] = glm::dmat3(2, 1, 1, 1, 2, 1, 1, 1, 2) * x[0];\n}\n\ntemplate<typename T>\nstd::ostream &operator<<(std::ostream &os, std::vector<T> const &vector) {\n    for (auto const &vec3 : vector) {\n        os << vec3 << \", \";\n    }\n    return os;\n}\n\nBOOST_AUTO_TEST_SUITE(test_conjugate_gradient_method)\n\n    BOOST_AUTO_TEST_CASE(test1) {\n\n        // b\n        std::vector<double> b = {1, 1, 1};\n\n        // x - initial guess\n        std::vector<double> x = {0, 0, 0};\n\n        // Solve Ax = b\n        conjugateResidualSolver(A, x, b, 2000);\n\n        BOOST_TEST(x[0] == 0.25);\n        BOOST_TEST(x[1] == 0.25);\n        BOOST_TEST(x[2] == 0.25);\n\n    }\n\n    BOOST_AUTO_TEST_CASE(testb) {\n\n        // b\n        std::vector<glm::dvec3> b = {\n                {1, 1, 1}\n        };\n\n        // x - initial guess\n        std::vector<glm::dvec3> x = {\n                {0, 0, 0}\n        };\n\n        // Solve Ax = b\n        conjugateResidualSolver(B, x, b, 2000);\n\n        BOOST_TEST(x[0][0] == 0.25);\n        BOOST_TEST(x[0][1] == 0.25);\n        BOOST_TEST(x[0][2] == 0.25);\n\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\nBOOST_AUTO_TEST_SUITE(test_n)\n\n    BOOST_AUTO_TEST_CASE(n) {\n\n        auto n0 = SnowSolver::n(0);\n        auto n0p5 = SnowSolver::n(0.5);\n        auto n1 = SnowSolver::n(1);\n        auto n1p5 = SnowSolver::n(1.5);\n        auto n2 = SnowSolver::n(2);\n        auto n2p5 = SnowSolver::n(2.5);\n\n        std::cout << \"n0=\" << n0 << std::endl;\n        std::cout << \"n0p5=\" << n0p5 << std::endl;\n        std::cout << \"n1=\" << n1 << std::endl;\n        std::cout << \"n1p5=\" << n1p5 << std::endl;\n        std::cout << \"n2=\" << n2 << std::endl;\n        std::cout << \"n2p5=\" << n2p5 << std::endl;\n\n        BOOST_TEST(SnowSolver::n(-0.5) == n0p5);\n        BOOST_TEST(SnowSolver::n(-1) == n1);\n        BOOST_TEST(SnowSolver::n(-1.5) == n1p5);\n        BOOST_TEST(SnowSolver::n(-2) == n2);\n        BOOST_TEST(SnowSolver::n(-2.5) == n2p5);\n\n    }\n\n    BOOST_AUTO_TEST_CASE(del_n) {\n\n        auto n0 = SnowSolver::del_n(0);\n        auto n0p5 = SnowSolver::del_n(0.5);\n        auto n1 = SnowSolver::del_n(1);\n        auto n1p5 = SnowSolver::del_n(1.5);\n        auto n2 = SnowSolver::del_n(2);\n        auto n2p5 = SnowSolver::del_n(2.5);\n\n        std::cout << \"n0=\" << n0 << std::endl;\n        std::cout << \"n0p5=\" << n0p5 << std::endl;\n        std::cout << \"n1=\" << n1 << std::endl;\n        std::cout << \"n1p5=\" << n1p5 << std::endl;\n        std::cout << \"n2=\" << n2 << std::endl;\n        std::cout << \"n2p5=\" << n2p5 << std::endl;\n\n        BOOST_TEST(SnowSolver::del_n(-2) == 0);\n        BOOST_TEST(SnowSolver::del_n(-1.5) > 0);\n        BOOST_TEST(SnowSolver::del_n(-1) > 0);\n        BOOST_TEST(SnowSolver::del_n(-0.5) > 0);\n        BOOST_TEST(SnowSolver::del_n(0) == 0);\n        BOOST_TEST(SnowSolver::del_n(0.5) < 0);\n        BOOST_TEST(SnowSolver::del_n(1) < 0);\n        BOOST_TEST(SnowSolver::del_n(1.5) < 0);\n        BOOST_TEST(SnowSolver::del_n(2) == 0);\n\n        BOOST_TEST(SnowSolver::del_n(-0.5) == -n0p5);\n        BOOST_TEST(SnowSolver::del_n(-1) == -n1);\n        BOOST_TEST(SnowSolver::del_n(-1.5) == -n1p5);\n        BOOST_TEST(SnowSolver::del_n(-2) == -n2);\n        BOOST_TEST(SnowSolver::del_n(-2.5) == -n2p5);\n\n    }\n\n    BOOST_AUTO_TEST_CASE(tight_n) {\n\n        auto n0 = LavaSolver::tight_n(0);\n        auto n0p5 = LavaSolver::tight_n(0.5);\n        auto n1 = LavaSolver::tight_n(1);\n        auto n1p5 = LavaSolver::tight_n(1.5);\n        auto n2 = LavaSolver::tight_n(2);\n        auto n2p5 = LavaSolver::tight_n(2.5);\n\n        std::cout << \"n0=\" << n0 << std::endl;\n        std::cout << \"n0p5=\" << n0p5 << std::endl;\n        std::cout << \"n1=\" << n1 << std::endl;\n        std::cout << \"n1p5=\" << n1p5 << std::endl;\n        std::cout << \"n2=\" << n2 << std::endl;\n        std::cout << \"n2p5=\" << n2p5 << std::endl;\n\n        BOOST_TEST(LavaSolver::tight_n(-0.5) == n0p5);\n        BOOST_TEST(LavaSolver::tight_n(-1) == n1);\n        BOOST_TEST(LavaSolver::tight_n(-1.5) == n1p5);\n        BOOST_TEST(LavaSolver::tight_n(-2) == n2);\n        BOOST_TEST(LavaSolver::tight_n(-2.5) == n2p5);\n\n    }\n\n    BOOST_AUTO_TEST_CASE(tight_del_n) {\n\n        auto n0 = LavaSolver::tight_del_n(0);\n        auto n0p5 = LavaSolver::tight_del_n(0.5);\n        auto n1 = LavaSolver::tight_del_n(1);\n        auto n1p5 = LavaSolver::tight_del_n(1.5);\n        auto n2 = LavaSolver::tight_del_n(2);\n        auto n2p5 = LavaSolver::tight_del_n(2.5);\n\n        std::cout << \"n0=\" << n0 << std::endl;\n        std::cout << \"n0p5=\" << n0p5 << std::endl;\n        std::cout << \"n1=\" << n1 << std::endl;\n        std::cout << \"n1p5=\" << n1p5 << std::endl;\n        std::cout << \"n2=\" << n2 << std::endl;\n        std::cout << \"n2p5=\" << n2p5 << std::endl;\n\n        BOOST_TEST(LavaSolver::tight_del_n(-0.5) == -n0p5);\n        BOOST_TEST(LavaSolver::tight_del_n(-1) == -n1);\n        BOOST_TEST(LavaSolver::tight_del_n(-1.5) == -n1p5);\n        BOOST_TEST(LavaSolver::tight_del_n(-2) == -n2);\n        BOOST_TEST(LavaSolver::tight_del_n(-2.5) == -n2p5);\n\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE(test_temperature)\n\n    BOOST_AUTO_TEST_CASE(test_small_increments) {\n\n        LavaParticleNode node({}, 1);\n        node.temperature = 20;\n\n        while (node.temperature < 50) {\n            LavaSolver::applyTemperatureDifference(node, 1);\n            std::cout << node.temperature << \" \" << node.latentHeat << std::endl;\n        }\n\n    }\n\n    BOOST_AUTO_TEST_CASE(test_large_increments) {\n\n        LavaParticleNode node({}, 1);\n        node.temperature = 20;\n\n        while (node.temperature < 50) {\n            LavaSolver::applyTemperatureDifference(node, 50);\n            std::cout << node.temperature << \" \" << node.latentHeat << std::endl;\n        }\n\n    }\n\n    BOOST_AUTO_TEST_CASE(test_small_decrements) {\n\n        LavaParticleNode node({}, 1);\n        node.temperature = 50;\n\n        while (node.temperature > 20) {\n            LavaSolver::applyTemperatureDifference(node, -1);\n            std::cout << node.temperature << \" \" << node.latentHeat << std::endl;\n        }\n\n    }\n\n    BOOST_AUTO_TEST_CASE(test_large_decrements) {\n\n        LavaParticleNode node({}, 1);\n        node.temperature = 50;\n\n        while (node.temperature > 20) {\n            LavaSolver::applyTemperatureDifference(node, -50);\n            std::cout << node.temperature << \" \" << node.latentHeat << std::endl;\n        }\n\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "037189c81e472237051f57e5a84576485783039f", "size": 7012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/snowlib.cpp", "max_stars_repo_name": "sethlu/renderbox-snow", "max_stars_repo_head_hexsha": "17c4e956dd5fdad54125508c348b599b02197dff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-02-15T04:01:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-26T06:37:08.000Z", "max_issues_repo_path": "tests/snowlib.cpp", "max_issues_repo_name": "sethlu/renderbox-snow", "max_issues_repo_head_hexsha": "17c4e956dd5fdad54125508c348b599b02197dff", "max_issues_repo_licenses": ["MIT"], "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/snowlib.cpp", "max_forks_repo_name": "sethlu/renderbox-snow", "max_forks_repo_head_hexsha": "17c4e956dd5fdad54125508c348b599b02197dff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-30T20:40:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T14:38:43.000Z", "avg_line_length": 29.2166666667, "max_line_length": 81, "alphanum_fraction": 0.5436394752, "num_tokens": 2319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5971302989110864}}
{"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": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Triangulation_2.h>\n#include <CGAL/boost/graph/graph_traits_Triangulation_2.h>\n\n#include <CGAL/boost/graph/dijkstra_shortest_paths.h>\n#include <boost/graph/filtered_graph.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point;\n\ntypedef CGAL::Triangulation_2<K> Triangulation;\n\n// As we want to run Dijskra's shortest path algorithm we only\n// consider finite vertices and edges.\n\ntemplate <typename T>\nstruct Is_finite {\n\n  const T* t_;\n\n  Is_finite()\n    : t_(NULL)\n  {}\n\n  Is_finite(const T& t)\n    : t_(&t)\n  { }\n\n  template <typename VertexOrEdge>\n  bool operator()(const VertexOrEdge& voe) const {\n    return ! t_->is_infinite(voe);\n  }\n};\n\ntypedef Is_finite<Triangulation> Filter;\ntypedef boost::filtered_graph<Triangulation,Filter,Filter> Finite_triangulation;\ntypedef boost::graph_traits<Finite_triangulation>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<Finite_triangulation>::vertex_iterator vertex_iterator;\n\ntypedef std::map<vertex_descriptor,int> VertexIndexMap;\nVertexIndexMap vertex_id_map;\n\ntypedef boost::associative_property_map<VertexIndexMap> VertexIdPropertyMap;\nVertexIdPropertyMap vertex_index_pmap(vertex_id_map);\n\nint\nmain(int,char*[])\n{\n  Triangulation t;\n  Filter is_finite(t);\n  Finite_triangulation ft(t, is_finite, is_finite);\n\n  t.insert(Point(0,0));\n  t.insert(Point(1,0));\n  t.insert(Point(0.2,0.2));\n  t.insert(Point(0,1));\n  t.insert(Point(0,2));\n\n  vertex_iterator vit, ve;\n  // Associate indices to the vertices\n  int index = 0;\n  // boost::tie assigns the first and second element of the std::pair\n  // returned by boost::vertices to the variables vit and ve\n  for(boost::tie(vit,ve)=boost::vertices(ft); vit!=ve; ++vit ){\n    vertex_descriptor  vd = *vit;\n    vertex_id_map[vd]= index++;\n    }\n\n  // Dijkstra's shortest path needs property maps for the predecessor and distance\n  // We first declare a vector\n  std::vector<vertex_descriptor> predecessor(boost::num_vertices(ft));\n  // and then turn it into a property map\n  boost::iterator_property_map<std::vector<vertex_descriptor>::iterator,\n                               VertexIdPropertyMap>\n    predecessor_pmap(predecessor.begin(), vertex_index_pmap);\n\n  std::vector<double> distance(boost::num_vertices(ft));\n  boost::iterator_property_map<std::vector<double>::iterator,\n                               VertexIdPropertyMap>\n    distance_pmap(distance.begin(), vertex_index_pmap);\n\n  // start at an arbitrary vertex\n  vertex_descriptor source = *boost::vertices(ft).first;\n  std::cout << \"\\nStart dijkstra_shortest_paths at \" << source->point() <<\"\\n\";\n\n  boost::dijkstra_shortest_paths(ft, source,\n\t\t\t\t distance_map(distance_pmap)\n\t\t\t\t .predecessor_map(predecessor_pmap)\n\t\t\t\t .vertex_index_map(vertex_index_pmap));\n\n  for(boost::tie(vit,ve)=boost::vertices(ft); vit!=ve; ++vit ){\n    vertex_descriptor vd = *vit;\n    std::cout << vd->point() << \" [\" <<  vertex_id_map[vd] << \"] \";\n    std::cout << \" has distance = \"  << boost::get(distance_pmap,vd)\n\t      << \" and predecessor \";\n    vd =  boost::get(predecessor_pmap,vd);\n    std::cout << vd->point() << \" [\" <<  vertex_id_map[vd] << \"]\\n \";\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "d5dc03e08a5b50a9c13672d95e688c1ea43fea3e", "size": 3247, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/BGL/examples/BGL_triangulation_2/dijkstra.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/BGL/examples/BGL_triangulation_2/dijkstra.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/BGL/examples/BGL_triangulation_2/dijkstra.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": 31.8333333333, "max_line_length": 87, "alphanum_fraction": 0.7132737912, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5971022834502224}}
{"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": "#include <array>\n#include <iostream>\n#include <numeric>\n#include <string_view>\n\n#include <boost/range/irange.hpp>\n\n#include \"input.hpp\"\n\n// compile-time parsing of string_view\nstruct ParseStats {\n  int num_cols,\n      num_rows;\n};\n\nconstexpr auto NEWLINE = '\\n';\n\nconstexpr auto parse_stats(std::string_view input) {\n  auto stats = ParseStats{};\n\n  auto& num_cols = stats.num_cols;\n  auto& num_rows = stats.num_rows;\n\n  for(const auto c : input) {\n    num_cols += (c != NEWLINE);\n    num_rows += (c == NEWLINE);\n  }\n\n  ++num_rows;\n  num_cols /= num_rows;\n\n  return stats;\n}\n\nconstexpr auto DEFAULT_INPUT = puzzle_input;\nconstexpr auto DEFAULT_STEPS = 100;\nconstexpr auto PARSE_STATS = parse_stats(DEFAULT_INPUT);\n\n/*\n * This will create a \"ring\" buffer around the actual grid, allowing us to\n * bypass the need to treat first/last rows/columns and all four corners of the\n * actual grid as special cases.\n */\nconstexpr auto GRIDLEN = PARSE_STATS.num_cols + 2;\nconstexpr auto GRIDWIDTH = PARSE_STATS.num_rows + 2;\n\nconstexpr auto GRIDSIZE = (GRIDLEN * GRIDWIDTH);\n\nusing Grid = std::array<char, GRIDSIZE>;\n\nconst auto my_index = [] (auto row, auto col) {\n  return (row * GRIDLEN + col);\n};\n\nauto parse(std::string_view input) {\n\n  auto grid = Grid{};\n\n  for(const auto row : boost::irange(1, GRIDWIDTH-1)) {\n\n    for(const auto col : boost::irange(1, GRIDLEN-1)) {\n\n      if(input.front() == '#') {\n        grid[my_index(row, col)] = 1;\n      }\n\n      input.remove_prefix(1);\n    }\n    // skip newline\n    input.remove_prefix(1);\n  }\n\n  return grid;\n}\n\nauto num_lights_on(Grid grid, const unsigned steps) {\n\n  /*\n   * Each cell in the sums grid represents the sum of turned-on lights from\n   * grid[i-1] to grid[i+1]. The sum of three of these cells minus the current\n   * cell represents the sum of all turned-on lights in the neighborhood.\n   *\n   * Because we are only looking at the current cell in any iteration, we can\n   * overwrite the grid in-place.\n   */\n  auto sums = Grid{};\n\n  const auto turn_on_corners = [&grid, OTHERLEN = (2*GRIDLEN)] {\n    // top-left corner\n    grid[GRIDLEN+1] =\n    // top-right corner\n    grid[OTHERLEN-2] =\n    // bottom-left corner\n    grid[GRIDSIZE-OTHERLEN+1] =\n    // bottom-right corner\n    grid[GRIDSIZE-GRIDLEN-2] = 1;\n  };\n\n  turn_on_corners();\n\n  for(const auto step : boost::irange(steps)) {\n\n    for(const auto i : boost::irange(GRIDLEN, GRIDSIZE-GRIDLEN)) {\n      sums[i] = grid[i-1]\n              + grid[i]\n              + grid[i+1];\n    }\n\n    for(const auto row: boost::irange(1, (GRIDWIDTH - 1))) {\n\n      for(const auto col : boost::irange(1, (GRIDLEN - 1))) {\n\n        const auto pos = my_index(row, col);\n\n        auto& cell = grid[pos];\n\n        const auto sum = sums[pos]\n                       - cell\n                       + sums[pos+GRIDLEN]\n                       + sums[pos-GRIDLEN];\n\n        cell = (sum == 3) or (sum == 2 and cell == 1);\n\n      }\n    }\n    turn_on_corners();\n  }\n\n  return std::accumulate(grid.begin(), grid.end(), 0);\n}\n\nauto solution(std::string_view input, const unsigned steps) {\n\n  const auto& grid = parse(input);\n\n  const auto result = num_lights_on(grid, steps);\n\n  return result;\n}\n\nint main() {\n\n  std::cout << solution(DEFAULT_INPUT, DEFAULT_STEPS) << std::endl;\n\n}\n", "meta": {"hexsha": "ffe86eeb98b0609ea9e611d10a3ee521fa29f197", "size": 3259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 18 Part 2/main.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 18 Part 2/main.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 18 Part 2/main.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3219178082, "max_line_length": 79, "alphanum_fraction": 0.6268794109, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5971022678524572}}
{"text": "#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Geometry>\n\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/stitching.hpp>\n#include <opencv2/video.hpp>\n#include <opencv2/optflow.hpp>\n\n#include <opencv2/cudaoptflow.hpp>\n#include \"opencv2/cudaarithm.hpp\"\n\n#include <cstdio>\n#include <iostream>\n\n#include <sphericalsfm/so3.h>\n#include <sphericalsfm/plane_estimator.h>\n#include <sphericalsfm/preemptive_ransac.h>\n\n#include \"stereo_panorama_tools.h\"\n\nusing namespace sphericalsfm;\n\nnamespace stereopanotools {\n\n    static cv::Ptr<cv::cuda::BroxOpticalFlow> optflow = cv::cuda::BroxOpticalFlow::create(0.197f, 50.0f, 0.8f, 10, 150, 10);\n\n    static const double depth = 10; // depth of plane\n    static const double synth_radius = 0.5; // radius of circle of synthetic views\n    static const double synth_focal_factor = 1.2; // synthetic focal = factor * input focal\n\n    void _compute_flow( cv::Mat &prev, cv::Mat &next, cv::Mat &out, bool upsample = false )\n    {\n        cv::cuda::GpuMat d_frame0(prev);\n        cv::cuda::GpuMat d_frame1(next);\n\n        cv::cuda::GpuMat d_flow(d_frame0.size(), CV_32FC2), d_flowxy;\n        cv::cuda::GpuMat d_frame0f;\n        cv::cuda::GpuMat d_frame1f;\n\n        d_frame0.convertTo(d_frame0f, CV_32F, 1.0 / 255.0);\n        d_frame1.convertTo(d_frame1f, CV_32F, 1.0 / 255.0);\n\n        optflow->calc(d_frame0f, d_frame1f, d_flow);\n        \n        d_flow.download(out);\n\n        if ( upsample )\n        {\n            cv::Mat out2;\n            cv::resize(out, out2, cv::Size(0,0), 2, 2, cv::INTER_LINEAR);\n            out2 *= 2;\n            out = out2;\n        }\n    }\n\n    Eigen::Vector3d project(const Eigen::Vector3d &vec, const Eigen::Vector3d &up)\n    {\n      return vec - up * (vec.dot(up));\n    }\n\n    double signed_angle_between( const Eigen::Vector3d &a, const Eigen::Vector3d &b, const Eigen::Vector3d &up )\n    {\n        return atan2(a.cross(b).dot(up),a.dot(b));\n    }\n\n    bool get_synthetic_column_maps( \n                                    double focal, double centerx, double centery,\n                                    double theta, double phi,\n                                    const Keyframe &left, const Keyframe &right,\n                                    cv::Mat &xL, cv::Mat &xR )\n    {\n        Eigen::Vector3d synth_t(0,0,-synth_radius);\n        Eigen::Matrix3d synth_R = so3exp(Eigen::Vector3d(0,-theta,0));\n        Eigen::Vector3d synth_center = -synth_R.transpose() * synth_t;\n        double synth_focal = focal * synth_focal_factor;\n        \n        Eigen::Vector3d left_center = -left.R.transpose() * left.t;\n        Eigen::Vector3d right_center = -right.R.transpose() * right.t;\n\n        for ( int y = 0; y < xL.rows; y++ )\n        {\n          double col = tan(phi);\n\n          Eigen::Vector3d synth_x(col,(y-centery)/synth_focal,1);\n          Eigen::Vector3d synth_X = synth_x * depth;\n          Eigen::Vector3d world_X = synth_R.transpose() * (synth_X - synth_t);\n                \n          // find projection in left and right images\n          Eigen::Vector3d XL = left.R * world_X + left.t;\n          Eigen::Vector3d XR = right.R * world_X + right.t;\n          \n          if ( XL(2) <= 0 ) return false;\n          if ( XR(2) <= 0 ) return false;\n          \n          Eigen::Vector2d XL_proj(focal*XL(0)/XL(2)+centerx,focal*XL(1)/XL(2)+centery);\n          Eigen::Vector2d XR_proj(focal*XR(0)/XR(2)+centerx,focal*XR(1)/XR(2)+centery);\n\n          xL.at<cv::Vec2f>(y,0) = cv::Vec2f(XL_proj(0),XL_proj(1));\n          xR.at<cv::Vec2f>(y,0) = cv::Vec2f(XR_proj(0),XR_proj(1));\n        }\n        \n        return true;\n    }\n\n    bool synthesize_column_linear( double focal, double centerx, double centery,\n                                   double theta, double phi, double alpha,\n                                   Keyframe &left, Keyframe &right,\n                                   cv::Mat &left_image_float, cv::Mat &right_image_float,\n                                   cv::Mat synth_column )\n    {\n        const int height = synth_column.rows;\n        \n        cv::Mat xL(height,1,CV_32FC2);\n        cv::Mat xR(height,1,CV_32FC2);\n        \n        bool success = get_synthetic_column_maps( focal, centerx, centery, theta, phi, left, right, xL, xR );\n        if ( !success ) return false;\n        \n        // remap left and right views\n        cv::Mat I_L;\n        cv::Mat I_R;\n        cv::remap(left_image_float,I_L,xL,cv::noArray(),cv::INTER_LINEAR);\n        cv::remap(right_image_float,I_R,xR,cv::noArray(),cv::INTER_LINEAR);\n        \n        cv::Mat result;\n        cv::addWeighted(I_L,(1.0-alpha),I_R,alpha,0.,result);\n        result.convertTo(synth_column, CV_8UC3);\n\n        return true;\n    }\n\n    bool synthesize_column_flowbased( double focal, double centerx, double centery,\n                          double theta, double phi, double alpha,\n                          Keyframe &left, Keyframe &right,\n                          cv::Mat &left_image_float, cv::Mat &right_image_float,\n                          cv::Mat &forward_flow, cv::Mat &backward_flow,\n                          cv::Mat &synth_column )\n    {\n        const int width = 1;\n        const int height = synth_column.rows;\n        \n        cv::Mat xL(height,width,CV_32FC2);\n        cv::Mat xR(height,width,CV_32FC2);\n        \n        bool success = get_synthetic_column_maps( focal, centerx, centery, theta, phi, left, right, xL, xR);\n        if ( !success ) return false;\n        \n        /// compute plane-induced displacement\n        cv::Mat v_LR;\n        cv::Mat v_RL;\n        cv::subtract( xR, xL, v_LR );\n        cv::subtract( xL, xR, v_RL );\n\n        // look up flows\n        cv::Mat F_LR;\n        cv::Mat F_RL;\n        cv::remap(forward_flow, F_LR, xL, cv::noArray(), cv::INTER_LINEAR);\n        cv::remap(backward_flow, F_RL, xR, cv::noArray(), cv::INTER_LINEAR);\n        \n        // compute corrected flows\n        cv::Mat Fs_LR;\n        cv::Mat Fs_RL;\n        cv::subtract( v_LR, F_LR, Fs_LR );\n        cv::subtract( v_RL, F_RL, Fs_RL );\n\n        // compute maps for interpolation\n        cv::Mat xs_L;\n        cv::Mat xs_R;\n        \n        cv::addWeighted( xL, 1.0, Fs_LR, alpha, 0.0, xs_L );\n        cv::addWeighted( xR, 1.0, Fs_RL, 1.0-alpha, 0.0, xs_R );\n        \n        // remap left and right views\n        cv::Mat I_L;\n        cv::Mat I_R;\n        cv::remap(left_image_float,I_L,xs_L,cv::noArray(),cv::INTER_LINEAR);\n        cv::remap(right_image_float,I_R,xs_R,cv::noArray(),cv::INTER_LINEAR);\n        \n        // alpha blend\n        cv::Mat result;\n        cv::addWeighted(I_L,(1.0-alpha),I_R,alpha,0.,result);\n        result.convertTo(synth_column, CV_8UC3);\n        \n        return true;\n    }\n\n    void load_keyframes( const std::string & posespath, std::vector<Keyframe> &keyframes )\n    {\n        FILE *posesf = fopen(posespath.c_str(),\"r\");\n        while ( true )\n        {\n            int index;\n            double t[3];\n            double r[3];\n            \n            int nread = fscanf(posesf,\"%d %lf %lf %lf %lf %lf %lf\\n\",\n                               &index,\n                               t+0,t+1,t+2,\n                               r+0,r+1,r+2);\n            if ( nread != 7 ) break;\n            \n            Keyframe kf;\n            kf.index = index;\n            kf.t << t[0],t[1],t[2];\n            kf.r << r[0],r[1],r[2];\n            kf.R = so3exp(kf.r);\n            \n            keyframes.push_back(kf);\n        }\n        fclose(posesf);\n    }\n\n    void decompose_keyframe_rotations( std::vector<Keyframe> &keyframes )\n    {\n        for ( int i = 0; i < keyframes.size(); i++ )\n        {\n            Keyframe &kf = keyframes[i];\n            \n            Eigen::Vector3d up(0,1,0);\n            Eigen::Vector3d Rup = kf.R*up;\n            std::cout << \"Rup: \" << Rup.transpose() << \"\\n\";\n            double angle = acos(up.dot(Rup));\n            std::cout << \"angle: \" << angle*180/M_PI << \"\\n\";\n            \n            if ( fabs(angle) > 0 )\n            {\n                Eigen::Vector3d v = up.cross(Rup);\n                v /= v.norm();\n                kf.Rxz = so3exp(v*angle);\n            }\n            else\n            {\n                kf.Rxz = Eigen::Matrix3d::Identity();\n            }\n            kf.Ry = kf.Rxz.transpose()*kf.R;\n            \n            Eigen::Vector3d ry = so3ln(kf.Ry);\n            kf.theta = -ry(1);\n        }\n    }\n\n    double compute_theta( const Eigen::Vector3d &c, const Eigen::Vector3d &up )\n    {\n      Eigen::Vector3d cproj = c - up * c.dot(up);\n      Eigen::Vector3d x = Eigen::Vector3d(1,0,0);\n      Eigen::Vector3d xproj = x - up * (x.dot(up));\n      return atan2(xproj.cross(cproj).dot(up),xproj.dot(cproj))+M_PI;\n    }\n\n    void compute_thetas( std::vector<Keyframe> &keyframes )\n    {\n        Eigen::Vector3d up = Eigen::Vector3d(0,1,0);\n        for ( int i = 0; i < keyframes.size(); i++ )\n        {\n            Eigen::Vector3d c = -keyframes[i].R.transpose() * keyframes[i].t;\n            keyframes[i].theta = compute_theta( c, up );\n        }\n    }\n\n    Eigen::Matrix3d get_rotation( const Eigen::Vector3d &from, const Eigen::Vector3d &to )\n    {\n        Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\n        double angle = acos(from.dot(to));\n        if ( fabs(angle) > 0 )\n        {\n            Eigen::Vector3d v = from.cross(to);\n            v /= v.norm();\n            R = so3exp(v*angle);\n        }\n        return R;\n    }\n\n    void estimate_plane( std::vector<Keyframe> &keyframes )\n    {\n        RayPairList centers(keyframes.size());\n        for ( int i = 0; i < keyframes.size(); i++ )\n        {\n            Keyframe &kf = keyframes[i];\n            \n            // get camera center\n            Eigen::Vector3d c = -kf.R.transpose() * kf.t;\n            Ray ray;\n            ray.head(3) = c;\n            centers[i] = std::make_pair( ray, ray );\n        }\n        \n        std::vector<PlaneEstimator*> estimators(200);\n        for ( int i = 0; i < estimators.size(); i++ ) estimators[i] = new PlaneEstimator;\n        \n        PreemptiveRANSAC<RayPairList, PlaneEstimator> plane_ransac;\n        plane_ransac.inlier_threshold = 0.01;\n        \n        std::vector<bool> inliers;\n        PlaneEstimator *best_estimator = NULL;\n        int ninliers = plane_ransac.compute( centers.begin(), centers.end(), estimators, &best_estimator, inliers );\n        std::cout << ninliers << \"/\" << centers.size() << \" inliers\\n\";\n        std::cout << best_estimator->normal << \"\\n\";\n        Eigen::Vector3d up = best_estimator->normal;\n        if ( up(1) < 0 ) up = -up;\n        \n        // calculate rotation to correct up vector\n        Eigen::Matrix3d correction = get_rotation( up, Eigen::Vector3d(0,1,0) );\n        std::cout << \"correction rotation:\\n\" << correction << \"\\n\";\n        std::cout << \"corrected up vector:\\n\" << correction * up << \"\\n\";\n        \n        // c = -R.' * t\n        // newup = correction * up\n        // newc = correction * c = - correction * R.' * t = - (R * correction.') .' * t\n        \n        // rotate all cameras to correct up vector\n        for ( int i = 0; i < keyframes.size(); i++ )\n        {\n            Keyframe &kf = keyframes[i];\n            \n            kf.R = kf.R * correction.transpose();\n            kf.r = so3ln(kf.R);\n        }\n\n        // check if we should flip upside-down\n        int nflip = 0;\n        for ( int i = 0; i < keyframes.size(); i++ )\n        {\n            Keyframe &kf = keyframes[i];\n            if ( kf.R(1,1) < 0 ) nflip++;\n        }\n        \n        if ( nflip > keyframes.size() / 2 )\n        {\n            std::cout << \"FLIP\\n\";\n            Eigen::Matrix3d Rflip = Eigen::Matrix3d::Identity();\n            Rflip(1,1) = -1;\n            Rflip(2,2) = -1;\n            for ( int i = 0; i < keyframes.size(); i++ )\n            {\n                Keyframe &kf = keyframes[i];\n                kf.R = kf.R * Rflip;\n                kf.r = so3ln(kf.R);\n            }\n        }\n    }\n\n    cv::Mat convert_to_spherical(const Intrinsics &intrinsics, const cv::Mat &cylindrical )\n    {\n        const int height = cylindrical.cols/2;\n        double vertfov = 2. * atan2(cylindrical.rows,2.*intrinsics.focal);\n        \n        // do vertical remap first\n        // make lookup table for vertical remap\n        std::vector<double> lut(height);\n        \n        double minphi = -M_PI/2;\n        double maxphi = M_PI/2;\n        double phistep = (maxphi-minphi)/(height-1);\n        \n        for ( int phinum = 0; phinum < height; phinum++ )\n        {\n            double phi = minphi + phinum*phistep;\n            double H = tan(phi);\n            lut[phinum] = intrinsics.focal*H+intrinsics.centery;\n        }\n        \n        // now remap columns of cylindrical panorama\n        cv::Mat spherical(height,cylindrical.cols,CV_8UC3);\n        \n        for ( int y = 0; y < height; y++ )\n        {\n            if ( std::isinf(lut[y]) || std::isnan(lut[y]) ) continue;\n            if ( lut[y] < 0 || lut[y] >= cylindrical.rows ) continue;\n            cv::Mat patch;\n            cv::getRectSubPix(cylindrical,cv::Size(cylindrical.cols,1),cv::Point2f(cylindrical.cols/2.f,lut[y]),patch);\n            patch.copyTo(spherical.row(y));\n        }\n\n        // resize horizontally if necessary\n        cv::Mat spherical_resized;\n        if ( spherical.cols != 2*height )\n        {\n            cv::resize( spherical, spherical_resized, cv::Size(2*height,height) );\n        } else {\n            spherical_resized = spherical;\n        }\n        \n        return spherical_resized;\n    }\n\n    void make_stereo_panoramas( const Intrinsics &intrinsics, const std::string &videopath, const std::string &outputpath,\n        const int panowidth, const bool is_loop )\n    {\n        const int start_theta = 0;\n        const int end_theta = panowidth;\n        \n        std::string posespath = outputpath + \"/poses.txt\";\n        \n        std::vector<Keyframe> keyframes;\n        \n        std::cout << \"loading keyframes from \" << posespath << \"...\\n\";\n        load_keyframes( posespath, keyframes );\n        std::cout << \"loaded \" << keyframes.size() << \" keyframes\\n\";\n\n        std::cout << \"estimating plane...\\n\";\n        Eigen::Vector3d up(0,1,0);\n        estimate_plane( keyframes );\n\n        std::cout << \"decomposing rotations...\\n\";\n        decompose_keyframe_rotations( keyframes );\n\n        std::cout << \"computing thetas...\\n\";\n        compute_thetas( keyframes );\n\n        std::cout << \"keyframe poses: \\n\";\n        for ( int i = 0; i < keyframes.size(); i++ ) std::cout << i << \"\\t\" << keyframes[i].t.transpose() << \"\\t\" << so3ln(keyframes[i].R).transpose() << \"\\n\";\n\n        std::cout << \"thetas before: \\n\";\n        for ( int i = 0; i < keyframes.size(); i++ ) std::cout << i << \"\\t\" << keyframes[i].theta*180/M_PI << \"\\n\";\n        \n        // re-order keyframes if necessary to make thetas increase\n        std::cout << \"re-ordering...\\n\";\n        int npos = 0;\n        int nneg = 0;\n        for ( int i = 0; i < 10; i++ ) \n        {\n            if ( keyframes[1].theta < keyframes[0].theta ) nneg++;\n            else if ( keyframes[0].theta < keyframes[1].theta ) npos++;\n        }\n        bool reverse = ( nneg > npos );\n        \n        // remove end frames that overlap with beginning frames\n        if ( is_loop )\n        {\n            if ( reverse )\n            {\n                while ( keyframes.back().theta < keyframes[0].theta )\n                {\n                    keyframes.pop_back();\n                }\n            } else {\n                while ( keyframes.back().theta > keyframes[0].theta )\n                {\n                    keyframes.pop_back();\n                }\n            }\n        }\n        \n        std::cout << \"thetas after: \\n\";\n        for ( int i = 0; i < keyframes.size(); i++ ) std::cout << i << \"\\t\" << keyframes[i].theta*180/M_PI << \"\\n\";\n        \n        std::cout << \"loading images...\\n\";\n        cv::VideoCapture cap(videopath);\n        int video_index = -1;\n        for ( int i = 0; i < keyframes.size(); i++ )\n        {\n            while ( video_index < keyframes[i].index )\n            {\n                if ( !cap.read(keyframes[i].image) )\n                {\n                    std::cout << \"could not read all keyframe images from \" << videopath << \"\\n\";\n                    exit(1);\n                }\n                video_index++;\n            }\n        }\n\n        const int width = keyframes[0].image.cols;\n        const int height = keyframes[0].image.rows;\n        \n        const int nphi = 9;\n        const double min_phi = (-(nphi-1)/2.)*M_PI/180.;\n        const double max_phi = ((nphi-1)/2.)*M_PI/180.;\n        std::vector<double> phirange(nphi);\n        if ( nphi == 1 )\n        {\n          phirange[0] = 0;\n        } else {\n          for ( int i = 0; i < nphi; i++ ) phirange[i] = min_phi + i*(max_phi-min_phi)/(nphi-1);\n        }\n        \n        const double min_theta = -M_PI;\n        const double max_theta = M_PI;\n        const int ntheta = panowidth;\n        std::vector<double> thetarange(ntheta);\n        const double theta_step = (max_theta-min_theta)/(ntheta-1);\n        for ( int i = 0; i < ntheta; i++ ) thetarange[i] = min_theta + i*theta_step;\n        \n        std::cout << \"interpolating frames...\\n\";\n        \n        int last_leftnum = -1;\n        cv::Mat forward_flow;\n        cv::Mat backward_flow;\n        cv::Mat left_image;\n        cv::Mat right_image;\n        cv::Mat left_image_gray;\n        cv::Mat right_image_gray;\n        cv::Mat left_image_float;\n        cv::Mat right_image_float;\n        \n        std::vector<cv::Mat> panoramas(nphi);\n        for ( int phinum = 0; phinum < nphi; phinum++ )\n        {\n            panoramas[phinum] = cv::Mat(height,ntheta,CV_8UC3,cv::Scalar(0,0,0,0));\n        }\n        \n        // iterate through each keyframe pair\n        for ( int kfnum = 0; kfnum < keyframes.size(); kfnum++ )\n        {\n          if ( kfnum % 10 == 0 ) std::cout << kfnum+1 << \" / \" << keyframes.size() << \"\\n\";\n          if ( !is_loop && kfnum == keyframes.size()-1 ) break;\n\n          int leftnum = kfnum;\n          int rightnum = (kfnum+1)%keyframes.size();\n\n          Keyframe &left = keyframes[leftnum];\n          Keyframe &right = keyframes[rightnum];\n\n          // load images\n          left_image = left.image;\n          cv::cvtColor( left_image, left_image_gray, cv::COLOR_BGR2GRAY );\n          left_image.convertTo(left_image_float,CV_32FC3);\n          right_image = right.image;\n          right_image.convertTo(right_image_float,CV_32FC3);\n          cv::cvtColor( right_image, right_image_gray, cv::COLOR_BGR2GRAY );\n\n          // compute flow\n          _compute_flow( left_image_gray, right_image_gray, forward_flow );\n          _compute_flow( right_image_gray, left_image_gray, backward_flow );\n\n          // get left and right camera centers\n          Eigen::Vector3d C_L = -left.R.transpose() * left.t;\n          Eigen::Vector3d C_R = -right.R.transpose() * right.t;\n\n          bool found_one_theta = false;\n\n          // find theta / phi combinations which fall between these keyframes\n          for ( int thetanum = start_theta; thetanum < end_theta; thetanum++ )\n          {\n            double theta = thetarange[thetanum];\n            Eigen::Vector3d synth_t(0,0,-synth_radius);\n            Eigen::Vector3d synth_r(0,-theta,0);\n            Eigen::Matrix3d synth_R = so3exp(synth_r);\n            \n            // get synthetic camera center\n            Eigen::Vector3d C_D = -synth_R.transpose() * synth_t;\n\n            // project left and right camera centers into synth camera\n            Eigen::Vector3d r_L = C_L - C_D;\n            Eigen::Vector3d r_R = C_R - C_D;\n              \n            // project rays to circle\n            Eigen::Vector3d rs_L = project(r_L,up);\n            Eigen::Vector3d rs_R = project(r_R,up);\n            \n            for ( int phinum = 0; phinum < phirange.size(); phinum++ ) \n            {\n              double phi = phirange[phinum];\n\n              // get synthetic ray in synth camera coordinate frame\n              Eigen::Vector3d r_D(tan(phi),0,1);\n              // get synthetic ray in world coordinate frame\n              r_D = synth_R.transpose() * (r_D - synth_t);\n              \n              // project synthetic ray to circle\n              Eigen::Vector3d rs_D = project(r_D,up);\n              \n              double angle_LD = signed_angle_between(rs_L,rs_D,up);\n              double angle_RD = signed_angle_between(rs_R,rs_D,up);\n              double angle_LR = signed_angle_between(rs_L,rs_R,up);\n\n              // check that cameras lie on either side of synth ray\n              if ( ! ( angle_LD * angle_RD < 0 ) ) continue;\n              \n              // check that cameras are within front hemisphere\n              const double angle_thresh = M_PI/2;\n              if ( fabs(angle_LD) >= angle_thresh ) continue;\n              if ( fabs(angle_RD) >= angle_thresh ) continue;\n            \n              // calculate alpha\n              double alpha = fabs(angle_LD)/fabs(angle_LR);\n              //std::cout << alpha << \"\\n\";\n            \n              // synthesize column\n              cv::Mat synth_column(height,1,CV_8UC3);\n            \n              bool success = synthesize_column_flowbased( intrinsics.focal, intrinsics.centerx, intrinsics.centery, theta, phi, alpha, left, right, left_image_float, right_image_float, forward_flow, backward_flow, synth_column );\n              if ( !success ) continue;\n              found_one_theta = true;\n              std::cout << theta << \" \" << phi << \"\\n\";\n            \n              // store column in output panorama\n              int colout = thetanum;\n              int shift = round(phi/theta_step);\n              colout = (colout+shift)%ntheta;\n              if ( colout < 0 ) colout += ntheta;\n                \n              synth_column.copyTo(panoramas[phinum].col(colout));\n            }\n          }\n          \n        }\n        \n        std::vector<cv::Mat> spherical_panos(panoramas.size());\n        for ( int i = 0; i < panoramas.size(); i++ )\n        {\n            spherical_panos[i] = convert_to_spherical(intrinsics, panoramas[i]);\n        }\n        for ( int phinum = 0; phinum < nphi; phinum++ )\n        {\n            cv::imwrite(outputpath + \"/cylindrical\" + std::to_string(phinum) + \".png\", panoramas[phinum]);\n            cv::imwrite(outputpath + \"/spherical\" + std::to_string(phinum) + \".png\", spherical_panos[phinum]);\n        }\n        for ( int phinum = 0; phinum < nphi/2; phinum++ )\n        {\n            cv::Mat overunder;\n            cv::vconcat(spherical_panos[nphi-phinum-1],spherical_panos[phinum],overunder);\n            cv::imwrite(outputpath + \"/overunder\" + std::to_string(nphi-phinum-1) + std::to_string(phinum) + \".png\", overunder);\n            cv::imwrite(outputpath + \"/overunder\" + std::to_string(nphi-phinum-1) + std::to_string(phinum) + \".jpg\", overunder);\n        }\n    }\n}\n", "meta": {"hexsha": "be34fca6d784b2e0347fc366e98981419c41f40f", "size": 22855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/stereo_panorama_tools.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": "examples/stereo_panorama_tools.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": "examples/stereo_panorama_tools.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": 36.8035426731, "max_line_length": 229, "alphanum_fraction": 0.5233428134, "num_tokens": 6112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5971022678524572}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2021, 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#pragma once\n\n#include \"panther_types.hpp\"\n#include <Eigen/Dense>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Convex_hull_traits_3.h>\n#include <CGAL/convex_hull_3.h>\n#include <CGAL/Triangulation_3.h>\n#include <decomp_geometry/polyhedron.h>\n#include <decomp_geometry/polyhedron.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Convex_hull_traits_3<K> Traits;\ntypedef Traits::Polyhedron_3 CGAL_Polyhedron_3;\ntypedef K::Segment_3 Segment_3;\ntypedef K::Plane_3 Plane_3;\n// define point creator\ntypedef K::Point_3 Point_3;\ntypedef K::Vector_3 Vector_3;\ntypedef CGAL::Creator_uniform_3<double, Point_3> PointCreator;\n\ntypedef std::vector<CGAL_Polyhedron_3> ConvexHullsOfCurve;\ntypedef std::vector<ConvexHullsOfCurve> ConvexHullsOfCurves;\n\nConvexHullsOfCurves_Std vectorGCALPol2vectorStdEigen(ConvexHullsOfCurves& convexHulls);\n\nvec_E<Polyhedron<3>> vectorGCALPol2vectorJPSPol(ConvexHullsOfCurves& convex_hulls_of_curves);\n\nCGAL_Polyhedron_3 convexHullOfPoints(const std::vector<Point_3>& points);\n\nmt::Edges vectorGCALPol2edges(const ConvexHullsOfCurves& convexHulls);", "meta": {"hexsha": "d0a411c22513d64969e0f300fd31c0a9cb3f0345", "size": 1547, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "panther/include/cgal_utils.hpp", "max_stars_repo_name": "t-thanh/panther", "max_stars_repo_head_hexsha": "c7ecb04b7a6ad0e61ee0596252196305a7fd0878", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2021-03-12T03:08:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:43:14.000Z", "max_issues_repo_path": "panther/include/cgal_utils.hpp", "max_issues_repo_name": "NamDinhRobotics/panther", "max_issues_repo_head_hexsha": "385b9ac3775a8df7db17e69c6278f8fcab769507", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-03-15T05:22:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T08:54:12.000Z", "max_forks_repo_path": "panther/include/cgal_utils.hpp", "max_forks_repo_name": "NamDinhRobotics/panther", "max_forks_repo_head_hexsha": "385b9ac3775a8df7db17e69c6278f8fcab769507", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2021-03-14T06:18:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T09:43:12.000Z", "avg_line_length": 38.675, "max_line_length": 93, "alphanum_fraction": 0.7446670976, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.597097765058197}}
{"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": "/*!@file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Molassembler/Temple/constexpr/Numeric.h\"\n\n#include <iostream>\n\nusing namespace Scine::Molassembler;\n\nBOOST_AUTO_TEST_CASE(NumericAverageStdDev, *boost::unit_test::label(\"Temple\")) {\n  const std::vector<double> values {29, 30, 31, 32, 33};\n\n  BOOST_CHECK(Temple::average(values) == 31);\n  BOOST_CHECK(\n    std::fabs(Temple::stddev(values) - std::sqrt(2))\n    < 1e-10\n  );\n}\n", "meta": {"hexsha": "616af2d37f1f84a0394d9e847756176bdd01341d", "size": 611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Temple/Numeric.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "test/Temple/Numeric.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Temple/Numeric.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 25.4583333333, "max_line_length": 80, "alphanum_fraction": 0.7103109656, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5970977522323908}}
{"text": "#include \"vicon_odom/filter.h\"\n#include <Eigen/LU>  // For matrix inverse\n\nnamespace vicon_odom {\n\nvoid KalmanFilter::initialize(const State_t &state,\n                              const ProcessCov_t &initial_cov,\n                              const ProcessCov_t &process_noise,\n                              const MeasurementCov_t &meas_noise) {\n  x = state;\n  P = initial_cov;\n  Q = process_noise;\n  R = meas_noise;\n}\n\nvoid KalmanFilter::processUpdate(double dt) {\n  ProcessCov_t A = ProcessCov_t::Identity();\n  A.topRightCorner<3, 3>() = Eigen::Vector3d(dt, dt, dt).asDiagonal();\n\n  x = A * x;\n  P = A * P * A.transpose() + Q;\n}\n\nvoid KalmanFilter::measurementUpdate(const Measurement_t &meas, double dt) {\n  Eigen::Matrix<double, n_meas, n_states> H;\n  H.setZero();\n  H(0, 0) = 1;\n  H(1, 1) = 1;\n  H(2, 2) = 1;\n\n  const Eigen::Matrix<double, n_states, n_meas> K =\n      P * H.transpose() * (H * P * H.transpose() + R).inverse();\n  const Measurement_t inno = meas - H * x;\n  x += K * inno;\n  P = (ProcessCov_t::Identity() - K * H) * P;\n}\n\n}  // namespace vicon_odom\n", "meta": {"hexsha": "6a3a989fa158f4b6bd73f67c5ef09a63400c164b", "size": 1069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vicon_odom/src/filter.cpp", "max_stars_repo_name": "KumarRobotics/vicon", "max_stars_repo_head_hexsha": "5c7c1aad8e17c018e9fc7cc8d7b6f1d4ef74dc16", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2015-12-16T03:07:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T20:00:11.000Z", "max_issues_repo_path": "vicon_odom/src/filter.cpp", "max_issues_repo_name": "KumarRobotics/vicon", "max_issues_repo_head_hexsha": "5c7c1aad8e17c018e9fc7cc8d7b6f1d4ef74dc16", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-05-20T18:48:13.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-02T20:38:09.000Z", "max_forks_repo_path": "vicon_odom/src/filter.cpp", "max_forks_repo_name": "KumarRobotics/vicon", "max_forks_repo_head_hexsha": "5c7c1aad8e17c018e9fc7cc8d7b6f1d4ef74dc16", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2015-02-01T23:49:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T09:08:04.000Z", "avg_line_length": 27.4102564103, "max_line_length": 76, "alphanum_fraction": 0.5996258185, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5970019254719856}}
{"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": "/*\r\nRafael D\u00edaz Medina A01024592\r\nDavid Benjamin Ruiz A01020825\r\nhttps://www.boost.org/doc/libs/1_55_0/libs/graph/example/\r\nhttps://www.boost.org/doc/libs/1_55_0/libs/graph/example/dfs-example.cpp\r\nhttps://www.boost.org/doc/libs/1_55_0/libs/graph/example/kruskal-example.cpp\r\nhttps://www.boost.org/doc/libs/1_55_0/libs/graph/example/bfs-example.cpp\r\nhttps://www.boost.org/doc/libs/1_55_0/libs/graph/example/prim-example.cpp\r\nhttps://www.boost.org/doc/libs/1_55_0/libs/graph/example/dijkstra-example.cpp\r\n\r\nPara poder correr este programa en windows se necesitaron de muchos pasos pero como se \r\nconsiguio finalmente fue as\u00ed:\r\n1- Descargar dev-c++\r\n2- Descargar Boost\r\n3- Configurar las librer\u00edas de boost para que el compilador las pudiera leer automaticamente\r\n4- Ejecutar el programa\r\n\r\nTenemos contadores en cada uno de los algoritmos y tambi\u00e9n en las operaciones\r\nde inserci\u00f3n y delete\r\n\r\nComplejidad de crear Vertice O(1)\r\nComplejidad de borrar Vertice O(m+n)\r\nComplejidad de crear Aristas O(1)\r\nComplejidad de borrar Aristas O(1)\r\nComplejidad de DFS O(m+n) Este algoritmo utiliza una tecnica Branch and bound\r\nComplejidad de BFS O(m+n) Este algoritmo utiliza una tecnica Branch and bound\r\nComplejidad de Dijkstra O(n log n) Este algoritmo utiliza una tecnica Avida\r\nComplejidad de Prim O(n log n) Este algoritmo utiliza una tecnica Avida\r\nComplejidad de Kruskal O(n log n) Este algoritmo utiliza una tecnica Avida\r\nComplejidad de Floyd Warshall O(n^3) Este algoritmo utiliza una tecnica de programacion dinamica\r\n*/\r\n#include <iostream>\r\n#include <fstream>\r\n#include <stack>\r\n#include <map>\r\n#include <queue>\r\n#include <vector>\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <chrono>\r\n#include <string.h>\r\n#include <bits/stdc++.h>\r\n#include <ctype.h>\r\n#include <stdio.h>\r\n#include <cstdio>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include \"time.h\"\r\n#include <ctime> \r\n#include <string>\r\n#include <algorithm>\r\n#include <tuple>\r\n#include <iterator>\r\nusing namespace std;\r\nusing namespace boost;\r\nusing namespace std::chrono;\r\n#include <boost/graph/adjacency_list.hpp> \r\n#include <boost/graph/graph_traits.hpp> \r\n#include <boost/graph/graphviz.hpp> \r\n#include <boost/tuple/tuple.hpp> \r\n#include <boost/graph/breadth_first_search.hpp>\r\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\r\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\r\n#include <boost/graph/dijsktra_shortest_paths_no_color_map.hpp>\r\n#include <boost/graph/depth_first_search.hpp>\r\n#include <boost/graph/exterior_property.hpp>\r\n\r\n\r\ntypedef property<vertex_distance_t, int> Vdistance;\r\ntypedef property<edge_weight_t, int> EdgeWeight;\r\ntypedef adjacency_list <vecS, vecS, bidirectionalS, Vdistance, EdgeWeight> Grafo;\r\ntypedef property_map<Grafo, edge_weight_t>::type EdgeWeights;\r\ntypedef boost::graph_traits<Grafo>::vertex_descriptor vertex_t;\r\ntypedef graph_traits < Grafo >::edge_descriptor Edge;\r\ntypedef boost::exterior_vertex_property<Grafo, int> DistanceProperty;\r\ntypedef DistanceProperty::matrix_type DistanceMatrix;\r\ntypedef DistanceProperty::matrix_map_type DistanceMatrixMap;\r\n\r\nclass dfsVisitor : public boost::default_dfs_visitor{\r\npublic:\r\n\t\r\n\tvoid discover_vertex(vertex_t v, const Grafo& n) const{\r\n\t\tstd::cerr << v << \" \" ;\r\n\t\t\r\n\t\treturn;\r\n\t}\r\n};\r\n\r\nclass bfsVisitor : public boost::default_bfs_visitor{\r\npublic:\r\n\tvoid discover_vertex(vertex_t v, const Grafo& n) const{\r\n\t\tstd::cerr << v << \" \";\r\n\t\treturn;\r\n\t}\r\n};\r\n\t//Complejidad del Algoritmo: O(1)\r\n\tGrafo crearVertices(Grafo p,int vertex){\r\n\t\tvertex_t u;\r\n\t\tu= crear_vertice(p);\r\n\t\tname.push_back(\tstd::to_string(vertex));\r\n\t\tstd::cout << \"Se puso el vertice \"<< vertex << \"\\n\";\r\n\t\treturn p;\r\n\t}\r\n\r\n\t//Complejidad del Algoritmo: O(1)\r\n\tGrafo crearAristas(Grafo p, int sale, int entra, int peso){\r\n\t\tcrear_aristas(sale, entra, peso, p);\r\n\t\tstd::cout << \"Se puso la arista de \" << sale << \" a \" << entra << \"\\n\";\r\n\t\treturn p;\r\n\t}\r\n\r\n\t//Complejidad del Algoritmo: O(1)\r\n\tGrafo borrarArista(Grafo p, int sale, int entra){\r\n\t\tborrar_arista(sale, entra, p);\r\n\t\tstd::cout << \"Se removio la arista de \" << sale << \" a \" << entra << \"\\n\";\r\n\t\treturn p;\r\n\t}\r\n\r\n\t//Complejidad del Algoritmo: O(1)\r\n\tGrafo borrarVertice(Grafo p, int u){\r\n\t\tclear_vertex(u,p);\r\n\t\tborrar_vertice(u, p);\r\n\t\tstd::cout << \"Se ha removido el vertice \" << u; \r\n\t\treturn p;\r\n\t}\r\n\t//Complejidad del Algoritmo: O(M+N)\r\n\t//Este algoritmo utiliza una tecnica Branch and bound\r\n\tvoid DFS(Grafo p){\r\n\t\tdfsVisitor temp;\r\n\t\tstd::cout << \"DFS: \\n\";\r\n\t\tdepth_first_search(p, visitor(temp));\r\n\t}\r\n\t//Complejidad del Algoritmo: O(M+N)\r\n\t//Este algoritmo utiliza una tecnica Branch and bound\r\n\tvoid BFS(Grafo p, int inicio){\r\n\t\tbfsVisitor temp;\r\n\t\tstd::cout << \"BFS: \\n\";\r\n\t\tbreadth_first_search(p,inicio, visitor(temp));\r\n\t}\r\n\t//Complejidad del Algoritmo: O(N^2)\r\n\t//Este algoritmo utiliza una tecnica Avida\r\n\tvoid dijsktra(Grafo n){\r\n\t\tstd::vector<vertex_t> p(num_vertices(n));\r\n\t\tstd::vector<int> d(num_vertices(n));\r\n\t\tvertex_t s = vertex(1, n);\r\n\t\tproperty_map<Grafo, vertex_index_t>::type indexmap = get(vertex_index, n);\r\n\t\tproperty_map<Grafo, edge_weight_t>::type weightmap = get(edge_weight, n);\r\n\t\tdijsktra_shortest_paths(n, s, &p[0], &d[0], weightmap, indexmap,\r\n\t\tstd::less<int>(), closed_plus<int>(),(std::numeric_limits<int>::max)(), 0,default_dijsktra_visitor());\r\n\t\tgraph_traits <Grafo>::vertex_iterator vi, vend;\r\n\t\t\r\n\t\tfor (tie(vi, vend) = vertices(n); vi != vend; ++vi){\r\n\t\t\tstd::cout << \"distancia al vertice \" << name[*vi] << \" = \" << d[*vi] << \", \";\r\n\t\t\tstd::cout << \" con padre \" << name[p[*vi]] << std::\r\n\t\t\t\tendl;\r\n\t\t}\r\n\t}\r\n\t//Complejidad del Algoritmo: O(N Log(M))\r\n\t//Este algoritmo utiliza una tecnica Avido\r\n\tvoid prim(Grafo p){\r\n\t\tstd::vector<vertex_t> v(num_vertices(p));\r\n\t\tproperty_map<Grafo, vertex_index_t>::type indexmap = get(vertex_index, p);\r\n\t\tproperty_map<Grafo, vertex_distance_t>::type distance = get(vertex_distance, p);\r\n\t\tproperty_map<Grafo, edge_weight_t>::type weightmap = get(edge_weight, p);\r\n\t\tprim_minimum_spanning_tree(p, *vertices(p).first,&v[0],distance,weightmap,indexmap, default_dijsktra_visitor());\r\n\t\t\r\n\t\tfor (std::size_t i = 1; i != v.size(); ++i){\r\n\t\t\t\r\n\t\t\tif (v[i] != i){\r\n\t\t\tstd::cout << \"parent[\" << i << \"] = \" << v[i] << std::endl;\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tstd::cout << \"parent[\" << i << \"] = no hay padre\" << std::endl;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t//Complejidad del Algoritmo: O(N Log(N))\r\n\t//Este algoritmo utiliza una tecnica Avido\r\n\tvoid kruskal(Grafo p){\r\n\t\tproperty_map < Grafo, edge_weight_t >::type weight = get(edge_weight, p);\r\n\t\tstd::vector < Edge > spanning_tree;\r\n\t\tkruskal_minimum_spanning_tree(p, std::back_inserter(spanning_tree));\r\n\t\tstd::cout << \"Kruskal: \\n\";\r\n\t\tfor (std::vector < Edge >::iterator ei = spanning_tree.begin(); ei != spanning_tree.end(); ++ei) {\r\n\t\t\tstd::cout << source(*ei, p) << \" <--> \" << target(*ei, p)<< \" con peso \" << weight[*ei] << std::endl;\r\n\t\t}\r\n\t}\r\n\t//Complejidad del Algoritmo: O(N^3)\r\n\t//Este algoritmo utiliza una tecnica de programacion dinamica\r\n\tvoid floydWarshall(Grafo p){\r\n\t\tDistanceMatrix distancias(num_vertices(p));\r\n\t\tDistanceMatrixMap dm(distancias, p);\r\n\t\tproperty_map < Grafo, edge_weight_t >::type weight = get(edge_weight, p);\r\n\t\tfloyd_warshall_all_pairs_shortest_paths(p, dm,boost::weight_map(weight));\r\n\t\tstd::cout << \"\\n Floyd-Warshall AP-SP: \" << std::endl;\r\n\t\t\r\n\t\tfor (std::size_t i = 1; i < num_vertices(p); ++i) {\r\n\t\t\t\r\n\t\t\tfor (std::size_t j = 1; j < num_vertices(p); ++j) {\r\n\t\t\t\tstd::cout << \"del vertice \" << i  << \" al \" << j  << \" : \";\r\n\t\t\t\t\r\n\t\t\t\tif (distancias[i][j] == std::numeric_limits<int>::max()){\r\n\t\t\t\t\tstd::cout << \"X\" << std::endl;\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tstd::cout << distancias[i][j] << std::endl;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tstd::cout << std::endl;\r\n\t\t}\r\n\t}\r\n};\r\nclass GrafoC{\r\npublic:\r\n\tstd::vector<std::string> name = { \"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\",\"14\" };\r\npublic: \r\n\r\n\tGrafo crearGrafo(){\r\n\t\tstd::vector<int> vertices = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14 };\r\n\t\tGrafo n(vertices.size());\r\n\t\tstd::vector<int> pesos = { 8,8,8,7,4,7,9,4,6,2,3,1,2,6,3,3,2,4,10,6,8,6,2,9 };\r\n\r\n\t\tcrear_aristas(1,3,8,n);\r\n\t\tcrear_aristas(1, 4,8,n);\r\n\t\tcrear_aristas(3,5,8,n);\r\n\t\tcrear_aristas(3,2,7,n);\r\n\t\tcrear_aristas(3,10,4,n);\r\n\t\tcrear_aristas(2,5,7,n);\r\n\t\tcrear_aristas(5,6,9,n);\r\n\t\tcrear_aristas(6,13,4,n);\r\n\t\tcrear_aristas(13,14,6,n);\r\n\t\tcrear_aristas(14,13,2,n);\r\n\t\tcrear_aristas(4,7,3,n);\r\n\t\tcrear_aristas(4,5,1,n);\r\n\t\tcrear_aristas(4,8,2,n);\r\n\t\tcrear_aristas(7,4,6,n);\r\n\t\tcrear_aristas(8,7,3, n);\r\n\t\tcrear_aristas(8,9,3, n);\r\n\t\tcrear_aristas(9,10,2, n);\r\n\t\tcrear_aristas(9,12,4, n);\r\n\t\tcrear_aristas(10,3,10, n);\r\n\t\tcrear_aristas(10,6,6, n);\r\n\t\tcrear_aristas(12,11,8, n);\r\n\t\tcrear_aristas(11,12,6, n);\r\n\t\tcrear_aristas(12,9,2, n);\r\n\t\tcrear_aristas(12,14,9, n);\r\n\t\t\r\n\t\treturn n;\r\n\t}\r\n\r\nint main(){\r\n\thigh_resolution_clock::time_point t1;\r\n   \thigh_resolution_clock::time_point t2;\r\n   \tduration<double> tiempo;\r\n\t\r\n\tGrafoC test;\r\n\tGrafo n = test.crearGrafo();\r\n\tint s;\r\n\twhile (1){\r\n\tprintf(\"1.Crear vertice\\n2.Borrar vertice\\n3.Crear arista\\n4.Borrar arista\\n5.DFS\\n6.BFS\\n7.Prim y Kruskal\\n8.dijsktra y Floyd-Warshall\\n\");\r\n\tscanf(\"%d\", &s);\r\n\tif(s==1){\r\n\t\tprintf(\"Ingresa el numero\\n\");\r\n\t\tint num;\r\n\t\tscanf(\"%d\", &num);\r\n\t\tt1=high_resolution_clock::now();\r\n\t\ttest.crearVertices(n, num);\r\n\t\tt2=high_resolution_clock::now();\r\n\t\ttiempo = duration_cast<duration<double>>(t2-t1);\r\n        tiempo=tiempo*1000;\r\n        cout << tiempo.count() << \"milisegundos\" << endl;\r\n\r\n\t}\r\n\telse if(s==2){\r\n\t\tprintf(\"Ingresa el numero\\n\");\r\n\t\tint num;\r\n\t\tscanf(\"%d\", &num);\r\n\t\tt1=high_resolution_clock::now();\r\n\t\ttest.borrarVertice(n, num);\r\n\t\tt2=high_resolution_clock::now();\r\n\t\ttiempo = duration_cast<duration<double>>(t2-t1);\r\n        tiempo=tiempo*1000;\r\n        cout << tiempo.count() << \"milisegundos\" << endl;\r\n\t}\r\n\telse if(s==3){\r\n\t\tprintf(\"Los numeros que vamos a ingresar son 14, 15, 2\\n\");\r\n\t\tt1=high_resolution_clock::now();\r\n\t\ttest.crearAristas(n, 14, 15, 2);\r\n\t\tt2=high_resolution_clock::now();\r\n\t\ttiempo = duration_cast<duration<double>>(t2-t1);\r\n        tiempo=tiempo*1000;\r\n        cout << tiempo.count() << \"milisegundos\" << endl;\r\n\t}\r\n\telse if(s==4){\r\n\t\tprintf(\"Borraremos 10, 3\");\r\n\t\tt1=high_resolution_clock::now();\r\n\t\ttest.borrarArista(n, 10, 3);\r\n\t\tt2=high_resolution_clock::now();\r\n\t\ttiempo = duration_cast<duration<double>>(t2-t1);\r\n        tiempo=tiempo*1000;\r\n        cout << tiempo.count() << \"milisegundos\" << endl;\r\n\t}\r\n\telse if(s==5){\r\n\t\tprintf(\"Hacemos el corrido de DFS\");\r\n\t\tt1=high_resolution_clock::now();\r\n\t\ttest.DFS(n);\r\n\t\tt2=high_resolution_clock::now();\r\n\t\ttiempo = duration_cast<duration<double>>(t2-t1);\r\n        tiempo=tiempo*1000;\r\n        cout << tiempo.count() << \"milisegundos\" << endl;\r\n\t}\r\n\telse if(s==6){\r\n\t\tprintf(\"Hacemos el corrido de BFS\");\r\n\t\tt1=high_resolution_clock::now();\r\n\t\ttest.BFS(n,1);\r\n\t\tt2=high_resolution_clock::now();\r\n\t\ttiempo = duration_cast<duration<double>>(t2-t1);\r\n        tiempo=tiempo*1000;\r\n        cout << tiempo.count() << \"milisegundos\" << endl;\r\n\t}\r\n\telse if(s==7){\r\n\t\tprintf(\"Arbol de recubrimiento Minimo con Prim y Kruskal\");\r\n\t\tt1=high_resolution_clock::now();\r\n\t\ttest.prim(n);\r\n\t\tt2=high_resolution_clock::now();\r\n\t\ttiempo = duration_cast<duration<double>>(t2-t1);\r\n        tiempo=tiempo*1000;\r\n        cout << tiempo.count() << \"milisegundos\" << endl;\r\n\t\t//------------------------------------------------------\r\n\t\tt1=high_resolution_clock::now();\r\n\t\ttest.kruskal(n);\r\n\t\tt2=high_resolution_clock::now();\r\n\t\ttiempo = duration_cast<duration<double>>(t2-t1);\r\n        tiempo=tiempo*1000;\r\n        cout << tiempo.count() << \"milisegundos\" << endl;\r\n\t}\r\n\telse if(s==8){\r\n\t\tprintf(\"Ruta minima con dijsktra y Floyd-Warshall\");\r\n\t\tt1=high_resolution_clock::now();\r\n\t\ttest.dijsktra(n);\r\n\t\tt2=high_resolution_clock::now();\r\n\t\ttiempo = duration_cast<duration<double>>(t2-t1);\r\n        tiempo=tiempo*1000;\r\n        cout << tiempo.count() << \"milisegundos\" << endl;\r\n\t\t//-------------------------------------------------\r\n\t\tt1=high_resolution_clock::now();\r\n\t\ttest.FloydWarshall(n);\r\n\t\tt2=high_resolution_clock::now();\r\n\t\ttiempo = duration_cast<duration<double>>(t2-t1);\r\n        tiempo=tiempo*1000;\r\n        cout << tiempo.count() << \"milisegundos\" << endl;\r\n\r\n\t}\r\n\telse \r\n\tbreak;\r\n\t}\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "dd9b7497e85b64798b1f7286795583dba4fa3aa6", "size": 12213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Pratica2Final/AlgoritmosBoost.cpp", "max_stars_repo_name": "RafaelDM/Tarea-4", "max_stars_repo_head_hexsha": "85d5915cce9055245ee35367950b0ed147a634c6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Pratica2Final/AlgoritmosBoost.cpp", "max_issues_repo_name": "RafaelDM/Tarea-4", "max_issues_repo_head_hexsha": "85d5915cce9055245ee35367950b0ed147a634c6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pratica2Final/AlgoritmosBoost.cpp", "max_forks_repo_name": "RafaelDM/Tarea-4", "max_forks_repo_head_hexsha": "85d5915cce9055245ee35367950b0ed147a634c6", "max_forks_repo_licenses": ["Apache-2.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.0194986072, "max_line_length": 142, "alphanum_fraction": 0.6548759519, "num_tokens": 3755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5968930683744138}}
{"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": "#include <tiny_math_types.h>\n#include <tiny_vector_functions.h>\n\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(tiny_axis_angle);\n\nBOOST_AUTO_TEST_CASE(simple_test)\n{\n\n  typedef tiny::MathTypes<double>       math_types;\n\n  typedef math_types::real_type        T;\n  typedef math_types::vector3_type     V;\n  typedef math_types::quaternion_type  Q;\n\n  // Small positive angle\n  {\n    Q q;\n    T const phi = 0.01;\n    V const m = tiny::unit( V::make(1.0, 1.0, 1.0) );\n    q = Q::Ru( phi, m);\n\n    T theta;\n    V n;\n    tiny::get_axis_angle( q, n, theta );\n\n    BOOST_CHECK_CLOSE( phi, theta, 0.01 );\n    BOOST_CHECK_CLOSE( m(0), n(0), 0.01 );\n    BOOST_CHECK_CLOSE( m(1), n(1), 0.01 );\n    BOOST_CHECK_CLOSE( m(2), n(2), 0.01 );\n  }\n  // See what happens if axis is flipped\n  {\n    Q q;\n    T const phi = 0.01;\n    V const m = -tiny::unit( V::make(1.0, 1.0, 1.0) );\n    q = Q::Ru( phi, m);\n\n    T theta;\n    V n;\n    tiny::get_axis_angle( q, n, theta );\n\n    BOOST_CHECK_CLOSE( phi, theta, 0.01 );\n    BOOST_CHECK_CLOSE( m(0), n(0), 0.01 );\n    BOOST_CHECK_CLOSE( m(1), n(1), 0.01 );\n    BOOST_CHECK_CLOSE( m(2), n(2), 0.01 );\n  }\n  // Pick larger angle\n  {\n    Q q;\n    T const phi = 3.0;\n    V const m = tiny::unit( V::make(1.0, 1.0, 1.0) );\n    q = Q::Ru( phi, m);\n\n    T theta;\n    V n;\n    tiny::get_axis_angle( q, n, theta );\n\n    BOOST_CHECK_CLOSE( phi, theta, 0.01 );\n    BOOST_CHECK_CLOSE( m(0), n(0), 0.01 );\n    BOOST_CHECK_CLOSE( m(1), n(1), 0.01 );\n    BOOST_CHECK_CLOSE( m(2), n(2), 0.01 );\n  }\n  // Pick larger negative angle, the positive angle version representation should be returned!\n  {\n    Q q;\n    T const phi = -3.0;\n    V const m = tiny::unit( V::make(1.0, 1.0, 1.0) );\n    q = Q::Ru( phi, m);\n\n    T theta;\n    V n;\n    tiny::get_axis_angle( q, n, theta );\n\n    BOOST_CHECK_CLOSE( -phi, theta, 0.01 );\n    BOOST_CHECK_CLOSE( -m(0), n(0), 0.01 );\n    BOOST_CHECK_CLOSE( -m(1), n(1), 0.01 );\n    BOOST_CHECK_CLOSE( -m(2), n(2), 0.01 );\n  }\n  // Flip the axis\n  {\n    Q q;\n    T const phi = -3.0;\n    V const m = -tiny::unit( V::make(1.0, 1.0, 1.0) );\n    q = Q::Ru( phi, m);\n\n    T theta;\n    V n;\n    tiny::get_axis_angle( q, n, theta );\n\n    BOOST_CHECK_CLOSE( -phi, theta, 0.01 );\n    BOOST_CHECK_CLOSE( -m(0), n(0), 0.01 );\n    BOOST_CHECK_CLOSE( -m(1), n(1), 0.01 );\n    BOOST_CHECK_CLOSE( -m(2), n(2), 0.01 );\n  }\n  // Large positive angle\n  {\n    Q q;\n    T const phi = 6.0;\n    V const m = tiny::unit( V::make(1.0, 1.0, 1.0) );\n    q = Q::Ru( phi, m);\n\n    T theta;\n    V n;\n    tiny::get_axis_angle( q, n, theta );\n\n    BOOST_CHECK_CLOSE( phi, theta, 0.01 );\n    BOOST_CHECK_CLOSE( m(0), n(0), 0.01 );\n    BOOST_CHECK_CLOSE( m(1), n(1), 0.01 );\n    BOOST_CHECK_CLOSE( m(2), n(2), 0.01 );\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "764a39370bd23338091ea38dc8d1e80f97de8b15", "size": 2933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_axis_angle/tiny_axis_angle.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_axis_angle/tiny_axis_angle.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_axis_angle/tiny_axis_angle.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0409836066, "max_line_length": 94, "alphanum_fraction": 0.5744971019, "num_tokens": 1061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5968705076428883}}
{"text": "#include <cmath>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"drake/solvers/fbstab/fbstab_mpc.h\"\n#include \"drake/solvers/fbstab/test/ocp_generator.h\"\n\nnamespace drake {\nnamespace solvers {\nnamespace fbstab {\nnamespace test {\n\nusing VectorXd = Eigen::VectorXd;\n\nGTEST_TEST(FBstabMpc, DoubleIntegrator) {\n  // Get the problem data.\n  OcpGenerator ocp;\n  ocp.DoubleIntegrator(2);  // horizon length of 2\n  FBstabMpc::QPData data = ocp.GetFBstabInput();\n\n  // Set up the initial guess.\n  VectorXd z = VectorXd::Zero(ocp.nz());\n  VectorXd l = VectorXd::Zero(ocp.nl());\n  VectorXd v = VectorXd::Zero(ocp.nv());\n  VectorXd y = VectorXd::Zero(ocp.nv());\n  FBstabMpc::QPVariable x = {&z, &l, &v, &y};\n\n  // Call the solver.\n  Eigen::Vector4d size = ocp.ProblemSize();\n  FBstabMpc solver(size(0), size(1), size(2), size(3));\n\n  solver.UpdateOption(\"abs_tol\", 1e-6);\n  solver.SetDisplayLevel(FBstabAlgoMpc::Display::ITER);\n  SolverOut out = solver.Solve(data, &x);\n\n  ASSERT_EQ(out.eflag, ExitFlag::SUCCESS);\n  ASSERT_LE(out.residual, 1e-6);\n\n  VectorXd zopt(ocp.nz());\n  VectorXd lopt(ocp.nl());\n  VectorXd vopt(ocp.nv());\n\n  // These numbers were computed using MATLAB's quadprog command.\n  zopt << -5.31028204670497e-14, 5.02854354118183e-13, 0.311688311338095,\n      5.35637944798588e-13, 0.311688311339015, -0.0779220779990502,\n      0.311688311339667, 0.233766233340057, -0.103896103779874;\n\n  lopt << -5.24675324688535, -4.49350649223710, -3.55844155822323,\n      -0.935064934014372, -1.48051948022526, 0.233766233996585;\n\n  vopt << 1.06213597221667e-13, -1.41190425869539e-21, 0, 0, 0, 0,\n      -1.50393600622818e-21, -8.75144622575045e-10, 0, 0, 0, 0,\n      -8.75144611157041e-10, -6.56358459377444e-10, 0, 0, 0, 0;\n\n  for (int i = 0; i < ocp.nz(); i++) {\n    EXPECT_NEAR(z(i), zopt(i), 1e-8);\n  }\n\n  for (int i = 0; i < ocp.nl(); i++) {\n    EXPECT_NEAR(l(i), lopt(i), 1e-8);\n  }\n\n  for (int i = 0; i < ocp.nv(); i++) {\n    EXPECT_NEAR(v(i), vopt(i), 1e-8);\n  }\n}\n\nGTEST_TEST(FBstabMpc, DoubleIntegratorLongHorizon) {\n  // Get the problem data.\n  OcpGenerator ocp;\n  ocp.DoubleIntegrator(20);  // horizon length of 20\n  FBstabMpc::QPData data = ocp.GetFBstabInput();\n\n  // Set up the initial guess.\n  VectorXd z = VectorXd::Zero(ocp.nz());\n  VectorXd l = VectorXd::Zero(ocp.nl());\n  VectorXd v = VectorXd::Zero(ocp.nv());\n  VectorXd y = VectorXd::Zero(ocp.nv());\n  FBstabMpc::QPVariable x = {&z, &l, &v, &y};\n\n  // Call the solver.\n  Eigen::Vector4d size = ocp.ProblemSize();\n  FBstabMpc solver(size(0), size(1), size(2), size(3));\n\n  solver.UpdateOption(\"abs_tol\", 1e-6);\n  solver.SetDisplayLevel(FBstabAlgoMpc::Display::ITER);\n  SolverOut out = solver.Solve(data, &x);\n\n  ASSERT_EQ(out.eflag, ExitFlag::SUCCESS);\n  ASSERT_LE(out.residual, 1e-6);\n}\n\nGTEST_TEST(FBstabMpc, ServoMotor) {\n  // Get the problem data.\n  OcpGenerator ocp;\n  ocp.ServoMotor(25);  // horizon length of 25\n  FBstabMpc::QPData data = ocp.GetFBstabInput();\n\n  // Set up the initial guess.\n  VectorXd z = VectorXd::Zero(ocp.nz());\n  VectorXd l = VectorXd::Zero(ocp.nl());\n  VectorXd v = VectorXd::Zero(ocp.nv());\n  VectorXd y = VectorXd::Zero(ocp.nv());\n  FBstabMpc::QPVariable x = {&z, &l, &v, &y};\n\n  // Call the solver.\n  Eigen::Vector4d size = ocp.ProblemSize();\n  FBstabMpc solver(size(0), size(1), size(2), size(3));\n\n  solver.UpdateOption(\"abs_tol\", 1e-6);\n  solver.SetDisplayLevel(FBstabAlgoMpc::Display::ITER);\n  SolverOut out = solver.Solve(data, &x);\n\n  ASSERT_EQ(out.eflag, ExitFlag::SUCCESS);\n  ASSERT_LE(out.residual, 1e-6);\n}\n\nGTEST_TEST(FBstabMpc, SpacecraftRelativeMotion) {\n  // Get the problem data.\n  OcpGenerator ocp;\n  ocp.SpacecraftRelativeMotion(40);  // horizon length of 40\n  FBstabMpc::QPData data = ocp.GetFBstabInput();\n\n  // Set up the initial guess.\n  VectorXd z = VectorXd::Zero(ocp.nz());\n  VectorXd l = VectorXd::Zero(ocp.nl());\n  VectorXd v = VectorXd::Zero(ocp.nv());\n  VectorXd y = VectorXd::Zero(ocp.nv());\n  FBstabMpc::QPVariable x = {&z, &l, &v, &y};\n\n  // Call the solver.\n  Eigen::Vector4d size = ocp.ProblemSize();\n  FBstabMpc solver(size(0), size(1), size(2), size(3));\n\n  solver.UpdateOption(\"abs_tol\", 1e-6);\n  solver.SetDisplayLevel(FBstabAlgoMpc::Display::ITER);\n  SolverOut out = solver.Solve(data, &x);\n\n  ASSERT_EQ(out.eflag, ExitFlag::SUCCESS);\n  ASSERT_LE(out.residual, 1e-6);\n}\n\nGTEST_TEST(FBstabMpc, CopolymerizationReactor) {\n  // Get the problem data.\n  OcpGenerator ocp;\n  ocp.CopolymerizationReactor(80);  // horizon length of 80\n  FBstabMpc::QPData data = ocp.GetFBstabInput();\n\n  // Set up the initial guess.\n  VectorXd z = VectorXd::Zero(ocp.nz());\n  VectorXd l = VectorXd::Zero(ocp.nl());\n  VectorXd v = VectorXd::Zero(ocp.nv());\n  VectorXd y = VectorXd::Zero(ocp.nv());\n  FBstabMpc::QPVariable x = {&z, &l, &v, &y};\n\n  // Call the solver.\n  Eigen::Vector4d size = ocp.ProblemSize();\n  FBstabMpc solver(size(0), size(1), size(2), size(3));\n\n  solver.UpdateOption(\"abs_tol\", 1e-6);\n  solver.SetDisplayLevel(FBstabAlgoMpc::Display::ITER);\n  SolverOut out = solver.Solve(data, &x);\n\n  ASSERT_EQ(out.eflag, ExitFlag::SUCCESS);\n  ASSERT_LE(out.residual, 1e-6);\n}\n\n}  // namespace test\n}  // namespace fbstab\n}  // namespace solvers\n}  // namespace drake\n", "meta": {"hexsha": "92573092fe4582649d087b746e6493a10f87d4af", "size": 5215, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/fbstab/test/fbstab_mpc_unit_tests.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "solvers/fbstab/test/fbstab_mpc_unit_tests.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/fbstab/test/fbstab_mpc_unit_tests.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 29.9712643678, "max_line_length": 73, "alphanum_fraction": 0.6736337488, "num_tokens": 1853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.5968704752331223}}
{"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": "// Copyright (C) 2016-2018 T. Zachary Laine\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#include <boost/yap/expression.hpp>\r\n\r\n#include <boost/test/minimal.hpp>\r\n\r\n\r\ntemplate<typename T>\r\nusing term = boost::yap::terminal<boost::yap::expression, T>;\r\n\r\ntemplate<typename T>\r\nusing ref = boost::yap::expression_ref<boost::yap::expression, T>;\r\n\r\nnamespace yap = boost::yap;\r\nnamespace bh = boost::hana;\r\n\r\n\r\nnamespace user {\r\n\r\n    struct number\r\n    {\r\n        double value;\r\n    };\r\n\r\n    struct eval_xform\r\n    {\r\n        auto\r\n        operator()(yap::expr_tag<yap::expr_kind::terminal>, number const & n)\r\n        {\r\n            return n;\r\n        }\r\n\r\n        template<typename Expr>\r\n        decltype(auto) operator()(\r\n            yap::expression<yap::expr_kind::negate, bh::tuple<Expr>> const &\r\n                expr)\r\n        {\r\n            number const n = transform(yap::value(expr), *this);\r\n            return number{-n.value};\r\n        }\r\n\r\n        template<typename Expr1, typename Expr2>\r\n        decltype(auto) operator()(yap::expression<\r\n                                  yap::expr_kind::plus,\r\n                                  bh::tuple<Expr1, Expr2>> const & expr)\r\n        {\r\n            number const lhs = transform(yap::left(expr), *this);\r\n            number const rhs = transform(yap::right(expr), *this);\r\n            return number{lhs.value + rhs.value};\r\n        }\r\n    };\r\n}\r\n\r\ntemplate<typename Expr>\r\nauto make_ref(Expr && expr)\r\n{\r\n    using type = yap::detail::operand_type_t<yap::expression, Expr>;\r\n    return yap::detail::make_operand<type>{}(static_cast<Expr &&>(expr));\r\n}\r\n\r\nint test_main(int, char * [])\r\n{\r\n{\r\n    {\r\n        term<user::number> a{{1.0}};\r\n\r\n        {\r\n            user::number result = transform(a, user::eval_xform{});\r\n            BOOST_CHECK(result.value == 1);\r\n        }\r\n\r\n        {\r\n            user::number result = transform(make_ref(a), user::eval_xform{});\r\n            BOOST_CHECK(result.value == 1);\r\n        }\r\n\r\n        {\r\n            user::number result = transform(-a, user::eval_xform{});\r\n            BOOST_CHECK(result.value == -1);\r\n        }\r\n\r\n        {\r\n            auto expr = make_ref(a);\r\n            user::number result = transform(-expr, user::eval_xform{});\r\n            BOOST_CHECK(result.value == -1);\r\n        }\r\n\r\n        {\r\n            auto expr = -a;\r\n            user::number result = transform(expr, user::eval_xform{});\r\n            BOOST_CHECK(result.value == -1);\r\n        }\r\n\r\n        {\r\n            auto expr1 = make_ref(a);\r\n            auto expr2 = make_ref(expr1);\r\n            user::number result = transform(expr2, user::eval_xform{});\r\n            BOOST_CHECK(result.value == 1);\r\n        }\r\n\r\n        {\r\n            auto expr1 = -a;\r\n            auto expr2 = make_ref(expr1);\r\n            user::number result = transform(expr2, user::eval_xform{});\r\n            BOOST_CHECK(result.value == -1);\r\n        }\r\n\r\n        {\r\n            auto expr1 = make_ref(a);\r\n            auto expr2 = -expr1;\r\n            user::number result = transform(expr2, user::eval_xform{});\r\n            BOOST_CHECK(result.value == -1);\r\n        }\r\n\r\n        {\r\n            auto expr1 = a;\r\n            auto expr2 = make_ref(expr1);\r\n            auto expr3 = make_ref(expr2);\r\n            user::number result = transform(expr3, user::eval_xform{});\r\n            BOOST_CHECK(result.value == 1);\r\n        }\r\n\r\n        {\r\n            auto expr1 = -a;\r\n            auto expr2 = make_ref(expr1);\r\n            auto expr3 = make_ref(expr2);\r\n            user::number result = transform(expr3, user::eval_xform{});\r\n            BOOST_CHECK(result.value == -1);\r\n        }\r\n\r\n        {\r\n            auto expr1 = make_ref(a);\r\n            auto expr2 = -expr1;\r\n            auto expr3 = make_ref(expr2);\r\n            user::number result = transform(expr3, user::eval_xform{});\r\n            BOOST_CHECK(result.value == -1);\r\n        }\r\n\r\n        {\r\n            auto expr1 = make_ref(a);\r\n            auto expr2 = make_ref(expr1);\r\n            auto expr3 = -expr2;\r\n            user::number result = transform(expr3, user::eval_xform{});\r\n            BOOST_CHECK(result.value == -1);\r\n        }\r\n    }\r\n\r\n    {\r\n        user::number result =\r\n            transform(-term<user::number>{{1.0}}, user::eval_xform{});\r\n        BOOST_CHECK(result.value == -1);\r\n    }\r\n}\r\n\r\n{\r\n    term<user::number> a{{1.0}};\r\n    term<user::number> x{{41.0}};\r\n\r\n    {\r\n        user::number result = transform(a + x, user::eval_xform{});\r\n        BOOST_CHECK(result.value == 42);\r\n    }\r\n\r\n\r\n    {\r\n        user::number result =\r\n            transform(make_ref(a) + make_ref(x), user::eval_xform{});\r\n        BOOST_CHECK(result.value == 42);\r\n    }\r\n\r\n    {\r\n        user::number result = transform(make_ref(a) + x, user::eval_xform{});\r\n        BOOST_CHECK(result.value == 42);\r\n    }\r\n\r\n    {\r\n        user::number result = transform(a + make_ref(x), user::eval_xform{});\r\n        BOOST_CHECK(result.value == 42);\r\n    }\r\n\r\n    {\r\n        user::number result = transform(a + x, user::eval_xform{});\r\n        BOOST_CHECK(result.value == 42);\r\n    }\r\n\r\n\r\n    {\r\n        user::number result =\r\n            transform(-make_ref(a) + make_ref(x), user::eval_xform{});\r\n        BOOST_CHECK(result.value == 40);\r\n    }\r\n\r\n    {\r\n        user::number result = transform(-make_ref(a) + x, user::eval_xform{});\r\n        BOOST_CHECK(result.value == 40);\r\n    }\r\n\r\n    {\r\n        user::number result = transform(-a + make_ref(x), user::eval_xform{});\r\n        BOOST_CHECK(result.value == 40);\r\n    }\r\n\r\n    {\r\n        user::number result = transform(-a + x, user::eval_xform{});\r\n        BOOST_CHECK(result.value == 40);\r\n    }\r\n\r\n\r\n    {\r\n        user::number result =\r\n            transform(make_ref(a) + -make_ref(x), user::eval_xform{});\r\n        BOOST_CHECK(result.value == -40);\r\n    }\r\n\r\n    {\r\n        user::number result = transform(make_ref(a) + -x, user::eval_xform{});\r\n        BOOST_CHECK(result.value == -40);\r\n    }\r\n\r\n    {\r\n        user::number result = transform(a + -make_ref(x), user::eval_xform{});\r\n        BOOST_CHECK(result.value == -40);\r\n    }\r\n\r\n    {\r\n        user::number result = transform(a + -x, user::eval_xform{});\r\n        BOOST_CHECK(result.value == -40);\r\n    }\r\n\r\n\r\n    {\r\n        user::number result =\r\n            transform(-make_ref(a) + -make_ref(x), user::eval_xform{});\r\n        BOOST_CHECK(result.value == -42);\r\n    }\r\n\r\n    {\r\n        user::number result = transform(-make_ref(a) + -x, user::eval_xform{});\r\n        BOOST_CHECK(result.value == -42);\r\n    }\r\n\r\n    {\r\n        user::number result = transform(-a + -make_ref(x), user::eval_xform{});\r\n        BOOST_CHECK(result.value == -42);\r\n    }\r\n\r\n    {\r\n        user::number result = transform(-a + -x, user::eval_xform{});\r\n        BOOST_CHECK(result.value == -42);\r\n    }\r\n}\r\n\r\nreturn 0;\r\n}\r\n", "meta": {"hexsha": "8ae4cea3433fcd153dad9a6b0383bd514ca9d579", "size": 6952, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/yap/test/user_expression_transform_2.cpp", "max_stars_repo_name": "Talustus/boost_src", "max_stars_repo_head_hexsha": "ffe074de008f6e8c46ae1f431399cf932164287f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/yap/test/user_expression_transform_2.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "third_party/boost/libs/yap/test/user_expression_transform_2.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 26.9457364341, "max_line_length": 80, "alphanum_fraction": 0.5057537399, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.596862212859244}}
{"text": "// Boost.Geometry Index\r\n//\r\n// Quickbook Examples\r\n//\r\n// Copyright (c) 2011-2013 Adam Wulkiewicz, Lodz, Poland.\r\n//\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[rtree_value_index\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point.hpp>\r\n#include <boost/geometry/geometries/box.hpp>\r\n\r\n#include <boost/geometry/index/rtree.hpp>\r\n\r\n#include <cmath>\r\n#include <vector>\r\n#include <iostream>\r\n#include <boost/foreach.hpp>\r\n\r\nnamespace bg = boost::geometry;\r\nnamespace bgi = boost::geometry::index;\r\n\r\ntemplate <typename Container>\r\nclass my_indexable\r\n{\r\n    typedef typename Container::size_type size_t;\r\n    typedef typename Container::const_reference cref;\r\n    Container const& container;\r\n\r\npublic:\r\n    typedef cref result_type;\r\n    explicit my_indexable(Container const& c) : container(c) {}\r\n    result_type operator()(size_t i) const { return container[i]; }\r\n};\r\n\r\nint main()\r\n{\r\n    typedef bg::model::point<float, 2, bg::cs::cartesian> point;\r\n    typedef bg::model::box<point> box;\r\n    typedef std::vector<box>::size_type value;\r\n    typedef bgi::rstar<16, 4> parameters;\r\n    typedef my_indexable< std::vector<box> > indexable_getter;\r\n\r\n    // boxes\r\n    std::vector<box> boxes;\r\n\r\n    // create some boxes\r\n    for ( unsigned i = 0 ; i < 10 ; ++i )\r\n    {\r\n        // add a box\r\n        boxes.push_back(box(point(i+0.0f, i+0.0f), point(i+0.5f, i+0.5f)));\r\n    }\r\n\r\n    // display boxes\r\n    std::cout << \"generated boxes:\" << std::endl;\r\n    BOOST_FOREACH(box const& b, boxes)\r\n        std::cout << bg::wkt<box>(b) << std::endl;\r\n\r\n    // create the rtree\r\n    parameters params;\r\n    indexable_getter ind(boxes);\r\n    bgi::rtree<value, parameters, indexable_getter> rtree(params, ind);\r\n\r\n    // fill the spatial index\r\n    for ( size_t i = 0 ; i < boxes.size() ; ++i )\r\n        rtree.insert(i);\r\n\r\n    // find values intersecting some area defined by a box\r\n    box query_box(point(0, 0), point(5, 5));\r\n    std::vector<value> result_s;\r\n    rtree.query(bgi::intersects(query_box), std::back_inserter(result_s));\r\n\r\n    // find 5 nearest values to a point\r\n    std::vector<value> result_n;\r\n    rtree.query(bgi::nearest(point(0, 0), 5), std::back_inserter(result_n));\r\n\r\n    // note: in Boost.Geometry the WKT representation of a box is polygon\r\n\r\n    // display results\r\n    std::cout << \"spatial query box:\" << std::endl;\r\n    std::cout << bg::wkt<box>(query_box) << std::endl;\r\n    std::cout << \"spatial query result:\" << std::endl;\r\n    BOOST_FOREACH(value i, result_s)\r\n        std::cout << bg::wkt<box>(boxes[i]) << std::endl;\r\n\r\n    std::cout << \"knn query point:\" << std::endl;\r\n    std::cout << bg::wkt<point>(point(0, 0)) << std::endl;\r\n    std::cout << \"knn query result:\" << std::endl;\r\n    BOOST_FOREACH(value i, result_n)\r\n        std::cout << bg::wkt<box>(boxes[i]) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n", "meta": {"hexsha": "0e1b6cbae3e21580b1aa209a43cd450059b62f15", "size": 3015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/index/src/examples/rtree/value_index.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/doc/index/src/examples/rtree/value_index.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/doc/index/src/examples/rtree/value_index.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 30.15, "max_line_length": 80, "alphanum_fraction": 0.6291873964, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5968621967743319}}
{"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 \"SparseCMPC/SparseCMPC.h\"\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n\n\nvoid SparseCMPC::c2d(u32 trajIdx, u32 bBlockStartIdx, u32 block_count) {\n\n  Eigen::Matrix<double, 24, 24> AB, expmm;\n  AB.setZero();\n  AB.block(0,0,12,12) = _aMat[trajIdx];\n\n  for(u32 i = bBlockStartIdx; i < bBlockStartIdx + block_count; i++) {\n    BblockID id = _bBlockIds[i];\n    if(id.timestep != trajIdx) throw std::runtime_error(\"c2d timestep error\");\n    AB.block(0,12 + 3 * id.foot, 12, 3) = _bBlocks[i];\n  }\n\n  AB *= _dtTrajectory[trajIdx];\n\n  expmm = AB.exp();\n  _aMat[trajIdx] = expmm.block(0,0,12,12);\n\n  for(u32 i = bBlockStartIdx; i < bBlockStartIdx + block_count; i++) {\n    //BblockID id = _bBlockIds[i];\n    //_bBlocks[i] = expmm.block(0,12 + 3 * id.foot, 12, 3);\n    _bBlocks[i] *= _dtTrajectory[trajIdx];\n  }\n}\n", "meta": {"hexsha": "6013290528bd2098a16c4913a1d2fb610895c6c7", "size": 834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common/src/SparseCMPC/SparseCMPC_Math.cpp", "max_stars_repo_name": "zbwu/Cheetah-Software", "max_stars_repo_head_hexsha": "286ca1eac576c61df76c71979f4e8940537ee084", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-18T03:36:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T03:36:47.000Z", "max_issues_repo_path": "common/src/SparseCMPC/SparseCMPC_Math.cpp", "max_issues_repo_name": "zbwu/Cheetah-Software", "max_issues_repo_head_hexsha": "286ca1eac576c61df76c71979f4e8940537ee084", "max_issues_repo_licenses": ["MIT"], "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/src/SparseCMPC/SparseCMPC_Math.cpp", "max_forks_repo_name": "zbwu/Cheetah-Software", "max_forks_repo_head_hexsha": "286ca1eac576c61df76c71979f4e8940537ee084", "max_forks_repo_licenses": ["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.7586206897, "max_line_length": 78, "alphanum_fraction": 0.6558752998, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5967481205979922}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation, \n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n *  @file   testGaussianFactorGraphB.cpp\n *  @brief  Unit tests for Linear Factor Graph\n *  @author Christian Potthast\n **/\n\n#include <tests/smallExample.h>\n#include <gtsam/nonlinear/Symbol.h>\n#include <gtsam/linear/GaussianBayesNet.h>\n#include <gtsam/linear/GaussianSequentialSolver.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/inference/SymbolicFactorGraph.h>\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/base/Matrix.h>\n#include <gtsam/base/Testable.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/foreach.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/assign/std/list.hpp> // for operator +=\n#include <boost/assign/std/set.hpp> // for operator +=\n#include <boost/assign/std/vector.hpp> // for operator +=\nusing namespace boost::assign;\n\n#include <string.h>\n#include <iostream>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace example;\n\ndouble tol=1e-5;\n\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, equals ) {\n\n  Ordering ordering; ordering += X(1),X(2),L(1);\n  GaussianFactorGraph fg = createGaussianFactorGraph(ordering);\n  GaussianFactorGraph fg2 = createGaussianFactorGraph(ordering);\n  EXPECT(fg.equals(fg2));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, error ) {\n  Ordering ordering; ordering += X(1),X(2),L(1);\n  GaussianFactorGraph fg = createGaussianFactorGraph(ordering);\n  VectorValues cfg = createZeroDelta(ordering);\n\n  // note the error is the same as in testNonlinearFactorGraph as a\n  // zero delta config in the linear graph is equivalent to noisy in\n  // non-linear, which is really linear under the hood\n  double actual = fg.error(cfg);\n  DOUBLES_EQUAL( 5.625, actual, 1e-9 );\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, eliminateOne_x1 )\n{\n  Ordering ordering; ordering += X(1),L(1),X(2);\n  GaussianFactorGraph fg = createGaussianFactorGraph(ordering);\n\n  GaussianConditional::shared_ptr conditional;\n  GaussianFactorGraph remaining;\n  boost::tie(conditional,remaining) = fg.eliminateOne(0, EliminateQR);\n\n  // create expected Conditional Gaussian\n  Matrix I = 15*eye(2), R11 = I, S12 = -0.111111*I, S13 = -0.444444*I;\n  Vector d = Vector_(2, -0.133333, -0.0222222), sigma = ones(2);\n  GaussianConditional expected(ordering[X(1)],15*d,R11,ordering[L(1)],S12,ordering[X(2)],S13,sigma);\n\n  EXPECT(assert_equal(expected,*conditional,tol));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, eliminateOne_x2 )\n{\n  Ordering ordering; ordering += X(2),L(1),X(1);\n  GaussianFactorGraph fg = createGaussianFactorGraph(ordering);\n  GaussianConditional::shared_ptr actual = fg.eliminateOne(0, EliminateQR).first;\n\n  // create expected Conditional Gaussian\n  double sig = 0.0894427;\n  Matrix I = eye(2)/sig, R11 = I, S12 = -0.2*I, S13 = -0.8*I;\n  Vector d = Vector_(2, 0.2, -0.14)/sig, sigma = ones(2);\n  GaussianConditional expected(ordering[X(2)],d,R11,ordering[L(1)],S12,ordering[X(1)],S13,sigma);\n\n  EXPECT(assert_equal(expected,*actual,tol));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, eliminateOne_l1 )\n{\n  Ordering ordering; ordering += L(1),X(1),X(2);\n  GaussianFactorGraph fg = createGaussianFactorGraph(ordering);\n  GaussianConditional::shared_ptr actual = fg.eliminateOne(0, EliminateQR).first;\n\n  // create expected Conditional Gaussian\n  double sig = sqrt(2.0)/10.;\n  Matrix I = eye(2)/sig, R11 = I, S12 = -0.5*I, S13 = -0.5*I;\n  Vector d = Vector_(2, -0.1, 0.25)/sig, sigma = ones(2);\n  GaussianConditional expected(ordering[L(1)],d,R11,ordering[X(1)],S12,ordering[X(2)],S13,sigma);\n\n  EXPECT(assert_equal(expected,*actual,tol));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, eliminateOne_x1_fast )\n{\n  Ordering ordering; ordering += X(1),L(1),X(2);\n  GaussianFactorGraph fg = createGaussianFactorGraph(ordering);\n  GaussianConditional::shared_ptr conditional;\n  GaussianFactorGraph remaining;\n  boost::tie(conditional,remaining) = fg.eliminateOne(ordering[X(1)], EliminateQR);\n\n  // create expected Conditional Gaussian\n  Matrix I = 15*eye(2), R11 = I, S12 = -0.111111*I, S13 = -0.444444*I;\n  Vector d = Vector_(2, -0.133333, -0.0222222), sigma = ones(2);\n  GaussianConditional expected(ordering[X(1)],15*d,R11,ordering[L(1)],S12,ordering[X(2)],S13,sigma);\n\n  // Create expected remaining new factor\n  JacobianFactor expectedFactor(1, Matrix_(4,2,\n             4.714045207910318,                   0.,\n                             0.,   4.714045207910318,\n                             0.,                   0.,\n                             0.,                   0.),\n     2, Matrix_(4,2,\n           -2.357022603955159,                   0.,\n                            0.,  -2.357022603955159,\n            7.071067811865475,                   0.,\n                            0.,   7.071067811865475),\n     Vector_(4, -0.707106781186547, 0.942809041582063, 0.707106781186547, -1.414213562373094), noiseModel::Unit::Create(4));\n\n  EXPECT(assert_equal(expected,*conditional,tol));\n  EXPECT(assert_equal((const GaussianFactor&)expectedFactor,*remaining.back(),tol));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, eliminateOne_x2_fast )\n{\n  Ordering ordering; ordering += X(1),L(1),X(2);\n  GaussianFactorGraph fg = createGaussianFactorGraph(ordering);\n  GaussianConditional::shared_ptr actual = fg.eliminateOne(ordering[X(2)], EliminateQR).first;\n\n  // create expected Conditional Gaussian\n  double sig = 0.0894427;\n  Matrix I = eye(2)/sig, R11 = I, S12 = -0.2*I, S13 = -0.8*I;\n  Vector d = Vector_(2, 0.2, -0.14)/sig, sigma = ones(2);\n  GaussianConditional expected(ordering[X(2)],d,R11,ordering[X(1)],S13,ordering[L(1)],S12,sigma);\n\n  EXPECT(assert_equal(expected,*actual,tol));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, eliminateOne_l1_fast )\n{\n  Ordering ordering; ordering += X(1),L(1),X(2);\n  GaussianFactorGraph fg = createGaussianFactorGraph(ordering);\n  GaussianConditional::shared_ptr actual = fg.eliminateOne(ordering[L(1)], EliminateQR).first;\n\n  // create expected Conditional Gaussian\n  double sig = sqrt(2.0)/10.;\n  Matrix I = eye(2)/sig, R11 = I, S12 = -0.5*I, S13 = -0.5*I;\n  Vector d = Vector_(2, -0.1, 0.25)/sig, sigma = ones(2);\n  GaussianConditional expected(ordering[L(1)],d,R11,ordering[X(1)],S12,ordering[X(2)],S13,sigma);\n\n  EXPECT(assert_equal(expected,*actual,tol));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, eliminateAll )\n{\n  // create expected Chordal bayes Net\n  Matrix I = eye(2);\n\n  Ordering ordering;\n  ordering += X(2),L(1),X(1);\n\n  Vector d1 = Vector_(2, -0.1,-0.1);\n  GaussianBayesNet expected = simpleGaussian(ordering[X(1)],d1,0.1);\n\n  double sig1 = 0.149071;\n  Vector d2 = Vector_(2, 0.0, 0.2)/sig1, sigma2 = ones(2);\n  push_front(expected,ordering[L(1)],d2, I/sig1,ordering[X(1)], (-1)*I/sig1,sigma2);\n\n  double sig2 = 0.0894427;\n  Vector d3 = Vector_(2, 0.2, -0.14)/sig2, sigma3 = ones(2);\n  push_front(expected,ordering[X(2)],d3, I/sig2,ordering[L(1)], (-0.2)*I/sig2, ordering[X(1)], (-0.8)*I/sig2, sigma3);\n\n  // Check one ordering\n  GaussianFactorGraph fg1 = createGaussianFactorGraph(ordering);\n  GaussianBayesNet actual = *GaussianSequentialSolver(fg1).eliminate();\n  EXPECT(assert_equal(expected,actual,tol));\n\n  GaussianBayesNet actualQR = *GaussianSequentialSolver(fg1, true).eliminate();\n  EXPECT(assert_equal(expected,actualQR,tol));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, copying )\n{\n  // Create a graph\n  Ordering ordering; ordering += X(2),L(1),X(1);\n  GaussianFactorGraph actual = createGaussianFactorGraph(ordering);\n\n  // Copy the graph !\n  GaussianFactorGraph copy = actual;\n\n  // now eliminate the copy\n  GaussianBayesNet actual1 = *GaussianSequentialSolver(copy).eliminate();\n\n  // Create the same graph, but not by copying\n  GaussianFactorGraph expected = createGaussianFactorGraph(ordering);\n\n  // and check that original is still the same graph\n  EXPECT(assert_equal(expected,actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, CONSTRUCTOR_GaussianBayesNet )\n{\n  Ordering ord;\n  ord += X(2),L(1),X(1);\n  GaussianFactorGraph fg = createGaussianFactorGraph(ord);\n\n  // render with a given ordering\n  GaussianBayesNet CBN = *GaussianSequentialSolver(fg).eliminate();\n\n  // True GaussianFactorGraph\n  GaussianFactorGraph fg2(CBN);\n  GaussianBayesNet CBN2 = *GaussianSequentialSolver(fg2).eliminate();\n  EXPECT(assert_equal(CBN,CBN2));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, getOrdering)\n{\n  Ordering original; original += L(1),X(1),X(2);\n  FactorGraph<IndexFactor> symbolic(createGaussianFactorGraph(original));\n  Permutation perm(*inference::PermutationCOLAMD(VariableIndex(symbolic)));\n  Ordering actual = original; actual.permuteInPlace(perm);\n  Ordering expected; expected += L(1),X(2),X(1);\n  EXPECT(assert_equal(expected,actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, optimize_Cholesky )\n{\n  // create an ordering\n  Ordering ord; ord += X(2),L(1),X(1);\n\n  // create a graph\n  GaussianFactorGraph fg = createGaussianFactorGraph(ord);\n\n  // optimize the graph\n  VectorValues actual = *GaussianSequentialSolver(fg, false).optimize();\n\n  // verify\n  VectorValues expected = createCorrectDelta(ord);\n\n  EXPECT(assert_equal(expected,actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, optimize_QR )\n{\n  // create an ordering\n  Ordering ord; ord += X(2),L(1),X(1);\n\n  // create a graph\n  GaussianFactorGraph fg = createGaussianFactorGraph(ord);\n\n  // optimize the graph\n  VectorValues actual = *GaussianSequentialSolver(fg, true).optimize();\n\n  // verify\n  VectorValues expected = createCorrectDelta(ord);\n\n  EXPECT(assert_equal(expected,actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, combine)\n{\n  // create an ordering\n  Ordering ord; ord += X(2),L(1),X(1);\n\n  // create a test graph\n  GaussianFactorGraph fg1 = createGaussianFactorGraph(ord);\n\n  // create another factor graph\n  GaussianFactorGraph fg2 = createGaussianFactorGraph(ord);\n\n  // get sizes\n  size_t size1 = fg1.size();\n  size_t size2 = fg2.size();\n\n  // combine them\n  fg1.combine(fg2);\n\n  EXPECT(size1+size2 == fg1.size());\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, combine2)\n{\n  // create an ordering\n  Ordering ord; ord += X(2),L(1),X(1);\n\n  // create a test graph\n  GaussianFactorGraph fg1 = createGaussianFactorGraph(ord);\n\n  // create another factor graph\n  GaussianFactorGraph fg2 = createGaussianFactorGraph(ord);\n\n  // get sizes\n  size_t size1 = fg1.size();\n  size_t size2 = fg2.size();\n\n  // combine them\n  GaussianFactorGraph fg3 = GaussianFactorGraph::combine2(fg1, fg2);\n\n  EXPECT(size1+size2 == fg3.size());\n}\n\n/* ************************************************************************* */\n// print a vector of ints if needed for debugging\nvoid print(vector<int> v) {\n  for (size_t k = 0; k < v.size(); k++)\n    cout << v[k] << \" \";\n  cout << endl;\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, createSmoother)\n{\n  GaussianFactorGraph fg1 = createSmoother(2).first;\n  LONGS_EQUAL(3,fg1.size());\n  GaussianFactorGraph fg2 = createSmoother(3).first;\n  LONGS_EQUAL(5,fg2.size());\n}\n\n/* ************************************************************************* */\ndouble error(const VectorValues& x) {\n  // create an ordering\n  Ordering ord; ord += X(2),L(1),X(1);\n\n  GaussianFactorGraph fg = createGaussianFactorGraph(ord);\n  return fg.error(x);\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, multiplication )\n{\n  // create an ordering\n  Ordering ord; ord += X(2),L(1),X(1);\n\n  GaussianFactorGraph A = createGaussianFactorGraph(ord);\n  VectorValues x = createCorrectDelta(ord);\n  Errors actual = A * x;\n  Errors expected;\n  expected += Vector_(2,-1.0,-1.0);\n  expected += Vector_(2, 2.0,-1.0);\n  expected += Vector_(2, 0.0, 1.0);\n  expected += Vector_(2,-1.0, 1.5);\n  EXPECT(assert_equal(expected,actual));\n}\n\n/* ************************************************************************* */\n// Extra test on elimination prompted by Michael's email to Frank 1/4/2010\nTEST( GaussianFactorGraph, elimination )\n{\n  Ordering ord;\n  ord += X(1), X(2);\n  // Create Gaussian Factor Graph\n  GaussianFactorGraph fg;\n  Matrix Ap = eye(1), An = eye(1) * -1;\n  Vector b = Vector_(1, 0.0);\n  SharedDiagonal sigma = noiseModel::Isotropic::Sigma(1,2.0);\n  fg.add(ord[X(1)], An, ord[X(2)], Ap, b, sigma);\n  fg.add(ord[X(1)], Ap, b, sigma);\n  fg.add(ord[X(2)], Ap, b, sigma);\n\n  // Eliminate\n  GaussianBayesNet bayesNet = *GaussianSequentialSolver(fg).eliminate();\n\n  // Check sigma\n  EXPECT_DOUBLES_EQUAL(1.0,bayesNet[ord[X(2)]]->get_sigmas()(0),1e-5);\n\n  // Check matrix\n  Matrix R;Vector d;\n  boost::tie(R,d) = matrix(bayesNet);\n  Matrix expected = Matrix_(2,2,\n      0.707107,  -0.353553,\n      0.0,   0.612372);\n  Matrix expected2 = Matrix_(2,2,\n      0.707107,  -0.353553,\n      0.0,   -0.612372);\n  EXPECT(equal_with_abs_tol(expected, R, 1e-6) || equal_with_abs_tol(expected2, R, 1e-6));\n}\n\n /* ************************************************************************* */\n// Tests ported from ConstrainedGaussianFactorGraph\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, constrained_simple )\n{\n  // get a graph with a constraint in it\n  GaussianFactorGraph fg = createSimpleConstraintGraph();\n  EXPECT(hasConstraints(fg));\n\n\n  // eliminate and solve\n  VectorValues actual = *GaussianSequentialSolver(fg).optimize();\n\n  // verify\n  VectorValues expected = createSimpleConstraintValues();\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, constrained_single )\n{\n  // get a graph with a constraint in it\n  GaussianFactorGraph fg = createSingleConstraintGraph();\n  EXPECT(hasConstraints(fg));\n\n  // eliminate and solve\n  VectorValues actual = *GaussianSequentialSolver(fg).optimize();\n\n  // verify\n  VectorValues expected = createSingleConstraintValues();\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, constrained_multi1 )\n{\n  // get a graph with a constraint in it\n  GaussianFactorGraph fg = createMultiConstraintGraph();\n  EXPECT(hasConstraints(fg));\n\n  // eliminate and solve\n  VectorValues actual = *GaussianSequentialSolver(fg).optimize();\n\n  // verify\n  VectorValues expected = createMultiConstraintValues();\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\n\nstatic SharedDiagonal model = noiseModel::Isotropic::Sigma(2,1);\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, replace)\n{\n  Ordering ord; ord += X(1),X(2),X(3),X(4),X(5),X(6);\n  SharedDiagonal noise(noiseModel::Isotropic::Sigma(3, 1.0));\n\n  GaussianFactorGraph::sharedFactor f1(new JacobianFactor(\n      ord[X(1)], eye(3,3), ord[X(2)], eye(3,3), zero(3), noise));\n  GaussianFactorGraph::sharedFactor f2(new JacobianFactor(\n      ord[X(2)], eye(3,3), ord[X(3)], eye(3,3), zero(3), noise));\n  GaussianFactorGraph::sharedFactor f3(new JacobianFactor(\n      ord[X(3)], eye(3,3), ord[X(4)], eye(3,3), zero(3), noise));\n  GaussianFactorGraph::sharedFactor f4(new JacobianFactor(\n      ord[X(5)], eye(3,3), ord[X(6)], eye(3,3), zero(3), noise));\n\n  GaussianFactorGraph actual;\n  actual.push_back(f1);\n  actual.push_back(f2);\n  actual.push_back(f3);\n  actual.replace(0, f4);\n\n  GaussianFactorGraph expected;\n  expected.push_back(f4);\n  expected.push_back(f2);\n  expected.push_back(f3);\n\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, createSmoother2)\n{\n  using namespace example;\n  GaussianFactorGraph fg2;\n  Ordering ordering;\n  boost::tie(fg2,ordering) = createSmoother(3);\n  LONGS_EQUAL(5,fg2.size());\n\n  // eliminate\n  vector<Index> x3var; x3var.push_back(ordering[X(3)]);\n  vector<Index> x1var; x1var.push_back(ordering[X(1)]);\n  GaussianBayesNet p_x3 = *GaussianSequentialSolver(\n      *GaussianSequentialSolver(fg2).jointFactorGraph(x3var)).eliminate();\n  GaussianBayesNet p_x1 = *GaussianSequentialSolver(\n      *GaussianSequentialSolver(fg2).jointFactorGraph(x1var)).eliminate();\n  CHECK(assert_equal(*p_x1.back(),*p_x3.front())); // should be the same because of symmetry\n}\n\n/* ************************************************************************* */\nTEST(GaussianFactorGraph, hasConstraints)\n{\n  FactorGraph<GaussianFactor> fgc1 = createMultiConstraintGraph();\n  EXPECT(hasConstraints(fgc1));\n\n  FactorGraph<GaussianFactor> fgc2 = createSimpleConstraintGraph() ;\n  EXPECT(hasConstraints(fgc2));\n\n  Ordering ordering; ordering += X(1), X(2), L(1);\n  GaussianFactorGraph fg = createGaussianFactorGraph(ordering);\n  EXPECT(!hasConstraints(fg));\n}\n\n#include <gtsam/slam/ProjectionFactor.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/slam/RangeFactor.h>\n#include <gtsam/linear/GaussianMultifrontalSolver.h>\n\n/* ************************************************************************* */\nTEST( GaussianFactorGraph, conditional_sigma_failure) {\n  // This system derives from a failure case in DDF in which a Bayes Tree\n  // has non-unit sigmas for conditionals in the Bayes Tree, which\n  // should never happen by construction\n\n  // Reason for the failure: using Vector_() is dangerous as having a non-float gets set to zero, resulting in constraints\n  gtsam::Key xC1 = 0, l32 = 1, l41 = 2;\n\n  // noisemodels at nonlinear level\n  gtsam::SharedNoiseModel priorModel = noiseModel::Diagonal::Sigmas(Vector_(6, 0.05, 0.05, 3.0, 0.2, 0.2, 0.2));\n  gtsam::SharedNoiseModel measModel = noiseModel::Unit::Create(2);\n  gtsam::SharedNoiseModel elevationModel = noiseModel::Isotropic::Sigma(1, 3.0);\n\n  double fov = 60; // degrees\n  double imgW = 640; // pixels\n  double imgH = 480; // pixels\n  gtsam::Cal3_S2::shared_ptr K(new gtsam::Cal3_S2(fov, imgW, imgH));\n\n  typedef GenericProjectionFactor<Pose3, Point3> ProjectionFactor;\n\n  double relElevation = 6;\n\n  Values initValues;\n  initValues.insert(xC1,\n      Pose3(Rot3(\n          -1.,           0.0,  1.2246468e-16,\n          0.0,             1.,           0.0,\n          -1.2246468e-16,           0.0,            -1.),\n          Point3(0.511832102, 8.42819594, 5.76841725)));\n  initValues.insert(l32,  Point3(0.364081507, 6.89766221, -0.231582751) );\n  initValues.insert(l41,  Point3(1.61051523, 6.7373052, -0.231582751)   );\n\n  NonlinearFactorGraph factors;\n  factors.add(PriorFactor<Pose3>(xC1,\n      Pose3(Rot3(\n          -1.,           0.0,  1.2246468e-16,\n          0.0,             1.,           0.0,\n          -1.2246468e-16,           0.0,            -1),\n          Point3(0.511832102, 8.42819594, 5.76841725)), priorModel));\n  factors.add(ProjectionFactor(Point2(333.648615, 98.61535), measModel, xC1, l32, K));\n  factors.add(ProjectionFactor(Point2(218.508, 83.8022039), measModel, xC1, l41, K));\n  factors.add(RangeFactor<Pose3,Point3>(xC1, l32, relElevation, elevationModel));\n  factors.add(RangeFactor<Pose3,Point3>(xC1, l41, relElevation, elevationModel));\n\n  Ordering orderingC; orderingC += xC1, l32, l41;\n\n  // Check that sigmas are correct (i.e., unit)\n  GaussianFactorGraph lfg = *factors.linearize(initValues, orderingC);\n\n  GaussianMultifrontalSolver solver(lfg, false);\n  GaussianBayesTree actBT = *solver.eliminate();\n\n  // Check that all sigmas in an unconstrained bayes tree are set to one\n  BOOST_FOREACH(const GaussianBayesTree::sharedClique& clique, actBT.nodes()) {\n    GaussianConditional::shared_ptr conditional = clique->conditional();\n    size_t dim = conditional->dim();\n    EXPECT(assert_equal(gtsam::ones(dim), conditional->get_sigmas(), tol));\n  }\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "b8bea8c6ed360a8dedd58eeffc3ed8bcf5301dcb", "size": 21339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testGaussianFactorGraphB.cpp", "max_stars_repo_name": "malcolmreynolds/GTSAM", "max_stars_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-23T19:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-23T19:34:50.000Z", "max_issues_repo_path": "tests/testGaussianFactorGraphB.cpp", "max_issues_repo_name": "malcolmreynolds/GTSAM", "max_issues_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/testGaussianFactorGraphB.cpp", "max_forks_repo_name": "malcolmreynolds/GTSAM", "max_forks_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.565, "max_line_length": 124, "alphanum_fraction": 0.6103847416, "num_tokens": 5641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5967417802605312}}
{"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 * Title ---- intercom-party/LocationManager.hpp\n * Author --- Giacomo Trudu aka `Wicker25` - wicker25[at]gmail[dot]com\n *\n * Copyright (C) 2017 by Giacomo Trudu.\n * All rights reserved.\n */\n\n#ifndef __INTERCOM_PARTY_LOCATION_MANAGER_HPP__\n#define __INTERCOM_PARTY_LOCATION_MANAGER_HPP__\n\n#include <intercom-party.hpp>\n#include <intercom-party/Exception.hpp>\n#include <intercom-party/Location.hpp>\n\n#include <cmath>\n\n#include <boost/math/constants/constants.hpp>\n\nusing namespace boost;\n\nnamespace intercom { // Begin main namespace\n\n/*!\n * The location manager.\n */\nclass LocationManager\n{\n\npublic:\n\n    /*!\n     * The Earth radius in km.\n     */\n    static constexpr double EarthRadius = 6'371.0;\n\n    /*!\n     * Converts degrees in radians.\n     *\n     * @return The distance (km).\n     */\n    static double getRadians(double degrees);\n\n    /*!\n     * Returns the distance between two locations.\n     *\n     * @return The distance (km).\n     */\n    static double getDistance(const Location &first, const Location &second);\n};\n\n} // End of main namespace\n\n#endif /* __INTERCOM_PARTY_LOCATION_MANAGER_HPP__ */\n\n// Include inline methods\n#include <intercom-party/LocationManager-inl.hpp>", "meta": {"hexsha": "9f3cb0ab04cdc138aca3183639ab4d5e43f91e61", "size": 1191, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/intercom-party/LocationManager.hpp", "max_stars_repo_name": "Wicker25/intercom-party", "max_stars_repo_head_hexsha": "5b1610aa79f6242be0cd846533ba97bf6a97f304", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-03T19:52:30.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-03T19:52:30.000Z", "max_issues_repo_path": "include/intercom-party/LocationManager.hpp", "max_issues_repo_name": "Wicker25/intercom-party", "max_issues_repo_head_hexsha": "5b1610aa79f6242be0cd846533ba97bf6a97f304", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/intercom-party/LocationManager.hpp", "max_forks_repo_name": "Wicker25/intercom-party", "max_forks_repo_head_hexsha": "5b1610aa79f6242be0cd846533ba97bf6a97f304", "max_forks_repo_licenses": ["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.8947368421, "max_line_length": 77, "alphanum_fraction": 0.6935348447, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5966736332624303}}
{"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": "#include <frovedis.hpp>\n#include <frovedis/matrix/blas_wrapper.hpp>\n#include <frovedis/matrix/lapack_wrapper.hpp>\n\n\n#define BOOST_TEST_MODULE FrovedisTest\n#include <boost/test/unit_test.hpp>\n\nusing namespace frovedis;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( frovedis_test )\n{\n    int argc = 1;\n    char** argv = NULL;\n    use_frovedis use(argc, argv);\n\n    // creating a colmajor matrix local from file\n    colmajor_matrix_local<float> A (\n           make_rowmajor_matrix_local_load<float>(\"./sample_2x2\"));\n\n    colmajor_matrix_local<float> B (\n           make_rowmajor_matrix_local_load<float>(\"./sample_2x1\"));\n\n    std::vector<int> ipiv;   // empty ipiv array\n    getrf<float> (A,ipiv);   // A will be factorized and ipiv will contain pivoting info\n    getrs<float> (A,B,ipiv); // solving AX=B, B will be overwritten with result matrix X\n\n    // checking whether the above operations successfully taken place \n    B.to_rowmajor().save(\"./out_2x1\");\n    BOOST_CHECK (system(\"diff ./out_2x1 ./ref_2x1\") == 0);\n    system(\"rm -f ./out_2x1\");\n}\n\n", "meta": {"hexsha": "9ce1ad90ab13782e4d3173b90a8bc27effeb2808", "size": 1050, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix/test7.2-1/test.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "test/matrix/test7.2-1/test.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "test/matrix/test7.2-1/test.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 30.0, "max_line_length": 88, "alphanum_fraction": 0.7, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5966221670492793}}
{"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": "#pragma once\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <iomanip>\n#include <random>\n#include <vector>\n\nnamespace Robotics {\n    template <int N>\n    using ColumnVector = Eigen::Matrix<double, N, 1>;\n\n    template <int N>\n    using SquareMatrix = Eigen::Matrix<double, N, N>;\n\n    template <int N, int M>\n    using Matrix = Eigen::Matrix<double, N, M>;\n\n    double deg2rad(double deg)\n    {\n        return deg * 3.14 / 180.0;  // TODO: replace 3.14 with M_PI (cross-platform)\n    }\n\n    class NormalDistributionRandomGenerator {\n      public:\n        template <int Size>\n        ColumnVector<Size> GetColumnVector()\n        {\n            ColumnVector<Size> rand_vector;\n\n            for (auto i = 0; i < rand_vector.size(); i++) rand_vector(i) = distribution(generator);\n\n            return rand_vector;\n        }\n\n      private:\n        std::default_random_engine generator;\n        std::normal_distribution<double> distribution{0.0, 1.0};\n    };\n\n}  // namespace Robotics", "meta": {"hexsha": "250b68db78d3d7ba435dabe9307def3789fe560e", "size": 979, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/robotics/common.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/common.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/common.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": 23.8780487805, "max_line_length": 99, "alphanum_fraction": 0.6179775281, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5965799005056704}}
{"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 <Eigen/Dense>\n#include <iostream>\n\n#include \"ransac.h\"\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(){\n    Matrix3d sigma;\n    sigma << 0.2, 0, 0, 0, 0.3, 0, 0, 0, 0.5;\n    Vector3d X = Vector3d::Random(3,1);\n    Vector3d A = Vector3d::Random(3,1);\n    Vector3d B = Vector3d::Random(3,1);\n\n    cout << \"================\" << endl;\n\n    Ransac myRansac(100, 1e-4);\n    double dist = myRansac.mahalanobis_distance(X, sigma, A, B);\n    Matrix3Xd temp = MatrixXd::Random(3,100);\n    vector<Matrix3d> cov;\n    for(int i=0; i< 100; ++i){\n        cov.push_back(sigma);\n    }\n    Eigen::MatrixXd temp2 = myRansac.removeOutlierPoints(temp, cov);\n\n    return 0;\n}\n", "meta": {"hexsha": "dc19200ee16989e03175c2ae83c43a24befa29ce", "size": 672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_ransac.cpp", "max_stars_repo_name": "SubramanianKrish/roblineVO", "max_stars_repo_head_hexsha": "9c977c63cc02e8a3a9e42dfa8bae77198f5347f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-09T08:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T08:28:48.000Z", "max_issues_repo_path": "src/test_ransac.cpp", "max_issues_repo_name": "SubramanianKrish/roblineVO", "max_issues_repo_head_hexsha": "9c977c63cc02e8a3a9e42dfa8bae77198f5347f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-11T07:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-11T07:00:50.000Z", "max_forks_repo_path": "src/test_ransac.cpp", "max_forks_repo_name": "SubramanianKrish/roblineVO", "max_forks_repo_head_hexsha": "9c977c63cc02e8a3a9e42dfa8bae77198f5347f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T11:55:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-12T19:24:46.000Z", "avg_line_length": 23.1724137931, "max_line_length": 68, "alphanum_fraction": 0.6026785714, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5965195342409767}}
{"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": "/*    Copyright (c) 2010-2018, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      B. Romgens, \"Verified Interval Propagation\" (2011). MSc thesis,\n *          Delft University of Technology.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/unitConversions.h\"\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h\"\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/modifiedEquinoctialElementConversions.h\"\n#include \"Tudat/Basics/basicTypedefs.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Show the functionality of the unit tests.\nBOOST_AUTO_TEST_SUITE( test_orbital_element_conversions )\n\n//! Unit test for conversion Keplerian orbital elements to modified equinoctial elements.\nBOOST_AUTO_TEST_CASE( testConvertKeplerianToModifiedEquinoctialElements )\n{\n    using namespace orbital_element_conversions;\n    using namespace unit_conversions;\n    using mathematical_constants::PI;\n\n    // Setting fraction tolerance for correctness evaluation\n    double tolerance = 1.0E-14;\n\n    // Initializing default Keplerian orbit\n    Eigen::Vector6d keplerianElements = Eigen::VectorXd::Zero( 6 );\n    keplerianElements( semiMajorAxisIndex ) = 1.0e7;\n    keplerianElements( eccentricityIndex ) = 0.1;\n    keplerianElements( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n    bool avoidSingularity = false;\n    keplerianElements( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 350.0 );\n    keplerianElements( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 15.0 );\n    keplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 10.0 );\n    // Modified equinoctial element vector declaration\n    Eigen::Vector6d expectedModifiedEquinoctialElements\n            = Eigen::VectorXd::Zero( 6 );\n    Eigen::Vector6d computedModifiedEquinoctialElements\n            = Eigen::VectorXd::Zero( 6 );\n\n    // Case 1: Elliptical prograde orbit (default case).\n    {\n        // Default case, so no modification necessary.\n\n        // Expected modified equinoctial elements [m,-,-,-,-,rad].\n        // (Results obtained using code archive B. Romgens (2011)).\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 9900000.0;\n        expectedModifiedEquinoctialElements( fElementIndex ) = 0.09961946980917456;\n        expectedModifiedEquinoctialElements( gElementIndex ) = 0.008715574274765783;\n        expectedModifiedEquinoctialElements( hElementIndex ) = 0.4504186100082874;\n        expectedModifiedEquinoctialElements( kElementIndex ) = 0.1206893028076694;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex ) =\n                basic_mathematics::computeModulo( 6.544984694978736, 2.0 * PI );\n\n        // Compute modified equinoctial elements.\n        Eigen::Vector6d computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n    }\n\n    // Case 2: Hyperbolic retrograde orbit.\n    {\n        // Modify Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( semiMajorAxisIndex ) = -1.0e7;\n        keplerianElements( eccentricityIndex ) = 2.0;\n        keplerianElements( inclinationIndex ) = convertDegreesToRadians( 170.0 );\n        avoidSingularity = true;\n        keplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 10.0 );\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 3.0e7;\n        expectedModifiedEquinoctialElements( fElementIndex )\n                = 1.8126155740732999264851053135086;\n        expectedModifiedEquinoctialElements( gElementIndex )\n                = -0.84523652348139887237395697929546;\n        expectedModifiedEquinoctialElements( hElementIndex )\n                = 0.0845075596072044152327702959491; //Minor error?\n        expectedModifiedEquinoctialElements( kElementIndex )\n                = 0.02264373235107538825570191377426;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex )\n                = 6.0213859193804370403867331512857;\n\n        // Compute modified equinoctial elements.\n        Eigen::Vector6d computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n    }\n\n    // Case 3: Parabolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( semiMajorAxisIndex ) = 1.0e7;\n        keplerianElements( eccentricityIndex ) = 1.0;\n        keplerianElements( inclinationIndex ) = convertDegreesToRadians( 170.0 );\n        avoidSingularity = true;\n        keplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand)\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 1.0e7;\n        expectedModifiedEquinoctialElements( fElementIndex )\n                = 0.90630778703664996324255265675432;\n        expectedModifiedEquinoctialElements( gElementIndex )\n                = -0.42261826174069943618697848964773;\n        expectedModifiedEquinoctialElements( hElementIndex )\n                = 0.0845075596072044152327702959491;\n        expectedModifiedEquinoctialElements( kElementIndex )\n                = 0.02264373235107538825570191377426;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex )\n                = 2.5307274153917778865393516143085;\n\n        // Compute modified equinoctial elements.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n    }\n\n    // Case 4: Circular prograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( eccentricityIndex ) = 0.0;\n        keplerianElements( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n        avoidSingularity = false;\n\n        // Expected modified equinoctial elements [m,-,-,-,-,rad].\n        // (Results obtained using code archive B. Romgens (2011)).\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 10000000;\n        expectedModifiedEquinoctialElements( fElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( gElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( hElementIndex ) = 0.4504186100082874;\n        expectedModifiedEquinoctialElements( kElementIndex ) = 0.1206893028076694;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex ) =\n                basic_mathematics::computeModulo( 9.337511498169663, 2.0 * PI );\n\n        // Compute modified equinoctial elements.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n    }\n\n    // Case 5: 0 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( eccentricityIndex ) = 0.1;\n        keplerianElements( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n\n        // Expected modified equinoctial elements [m,-,-,-,-,rad].\n        // (Results obtained using code archive B. Romgens (2011)).\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 9900000;\n        expectedModifiedEquinoctialElements( fElementIndex ) = 0.09961946980917456;\n        expectedModifiedEquinoctialElements( gElementIndex ) = 0.008715574274765783;\n        expectedModifiedEquinoctialElements( hElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( kElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex ) =\n                basic_mathematics::computeModulo( 9.337511498169663, 2.0 * PI );\n\n        // Compute modified equinoctial elements.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed modified equinoctial elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElements,\n                                           computedModifiedEquinoctialElements, tolerance );\n    }\n\n    // Case 6: 180 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( inclinationIndex ) = PI; // = 180 deg\n        avoidSingularity = true;\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 9.9e6;\n        expectedModifiedEquinoctialElements( fElementIndex )\n                = 0.09063077870366499632425526567543;\n        expectedModifiedEquinoctialElements( gElementIndex )\n                = -0.04226182617406994361869784896477;\n        expectedModifiedEquinoctialElements( hElementIndex ) = 0.0;\n        expectedModifiedEquinoctialElements( kElementIndex ) = 0.0;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex )\n                = 2.5307274153917778865393516143085;\n\n        // Compute modified equinoctial elements.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this\n        Eigen::Vector6d vectorToAdd\n                = ( Eigen::Vector6d( ) << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ).finished( );\n        Eigen::Vector6d expectedModifiedEquinoctialElementsPlusOne =\n                expectedModifiedEquinoctialElements + vectorToAdd;\n        Eigen::Vector6d computedModifiedEquinoctialElementsPlusOne =\n                computedModifiedEquinoctialElements + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElementsPlusOne,\n                                           computedModifiedEquinoctialElementsPlusOne, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this\n        expectedModifiedEquinoctialElementsPlusOne =\n                expectedModifiedEquinoctialElements + vectorToAdd;\n        computedModifiedEquinoctialElementsPlusOne =\n                computedModifiedEquinoctialElements + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElementsPlusOne,\n                                           computedModifiedEquinoctialElementsPlusOne, tolerance );\n    }\n\n    // Case 7: 0 eccentricity and inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        keplerianElements( eccentricityIndex ) = 0.0;\n        keplerianElements( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n\n        // Expected modified equinoctial elements [m,-,-,-,-,rad].\n        // (Results obtained using code archive B. Romgens (2011)).\n        expectedModifiedEquinoctialElements( semiLatusRectumIndex ) = 10000000;\n        expectedModifiedEquinoctialElements( fElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( gElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( hElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( kElementIndex ) = 0;\n        expectedModifiedEquinoctialElements( trueLongitudeIndex ) =\n                basic_mathematics::computeModulo( 9.337511498169663, 2.0 * PI );\n\n        // Compute modified equinoctial elements.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements,\n                                                               avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this\n        Eigen::Vector6d vectorToAdd\n                = ( Eigen::Vector6d( ) << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ).finished( );\n        Eigen::Vector6d expectedModifiedEquinoctialElementsPlusOne =\n                expectedModifiedEquinoctialElements + vectorToAdd;\n        Eigen::Vector6d computedModifiedEquinoctialElementsPlusOne =\n                computedModifiedEquinoctialElements + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElementsPlusOne,\n                                           computedModifiedEquinoctialElementsPlusOne, tolerance );\n\n        // Compute modified equinoctial elements using direct function.\n        computedModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( keplerianElements );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this\n        expectedModifiedEquinoctialElementsPlusOne =\n                expectedModifiedEquinoctialElements + vectorToAdd;\n        computedModifiedEquinoctialElementsPlusOne =\n                computedModifiedEquinoctialElements + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedModifiedEquinoctialElementsPlusOne,\n                                           computedModifiedEquinoctialElementsPlusOne, tolerance );\n    }\n\n    // Case 8: 200 degree inclination orbit, test for error.\n    {\n        keplerianElements( inclinationIndex ) = convertDegreesToRadians( 200.0 );\n        bool isExceptionFound = false;\n\n        // Try to calculate retrogradeness\n        try\n        {\n            computedModifiedEquinoctialElements = convertKeplerianToModifiedEquinoctialElements\n                    ( keplerianElements, avoidSingularity );\n        }\n        // Catch the expected runtime error, and set the boolean flag to true.\n        catch ( std::runtime_error )\n        {\n            isExceptionFound = true;\n        }\n\n        // Check value of flag.\n        BOOST_CHECK( isExceptionFound );\n    }\n}\n\n//! Unit test for conversion modified equinoctial elements to Keplerian orbital elements\nBOOST_AUTO_TEST_CASE( testConvertModifiedEquinoctialToKeplerianElements )\n{\n    /* Used procedure:\n      Because the Kepler to modified equinoctial elements are verified, a subsequent conversion back\n      to Keplerian elements should yield the same outcome as the input Keplerian state. This\n      principle is used for verification.\n     */\n\n    using namespace orbital_element_conversions;\n    using namespace unit_conversions;\n    using mathematical_constants::PI;\n\n    // Setting fraction tolerance for correctness evaluation\n    double tolerance = 1.0E-14;\n\n    // Initializing default Keplerian orbit\n    Eigen::Vector6d expectedKeplerianElements = Eigen::VectorXd::Zero( 6 );\n    expectedKeplerianElements( semiMajorAxisIndex ) = 1.0e7;\n    expectedKeplerianElements( eccentricityIndex ) = 0.1;\n    expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n    bool avoidSingularity = false;\n    expectedKeplerianElements( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 350.0 );\n    expectedKeplerianElements( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 15.0 );\n    expectedKeplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n    // Declaring computed output vector.\n    Eigen::Vector6d computedKeplerianElements = Eigen::VectorXd::Zero( 6 );\n\n    // Case 1: Elliptical prograde orbit (default case).\n    {\n        // Default case, so no modification necessary.\n\n        // Convert to modified equinoctial elements and back.\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 2: Hyperbolic retrograde orbit.\n    {\n        // Modify Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( semiMajorAxisIndex ) = -1.0e7;\n        expectedKeplerianElements( eccentricityIndex ) = 2.0;\n        expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 160.0 );\n        avoidSingularity = true;\n        expectedKeplerianElements( trueAnomalyIndex )\n                = convertDegreesToRadians( 10.0 ); // 170 is above limit\n\n        // Convert to modified equinoctial elements and back.\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 3: Parabolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( semiMajorAxisIndex ) = 3.678e7;\n        expectedKeplerianElements( eccentricityIndex ) = 1.0;\n        expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 90.0 );\n        avoidSingularity = true;\n\n        // Convert to modified equinoctial elements and back.\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 4: Circular prograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( eccentricityIndex ) = 0.0;\n        expectedKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 70.0 );\n        avoidSingularity = false;\n        expectedKeplerianElements( argumentOfPeriapsisIndex ) = 0.0; // For e = 0, undefined.\n\n        // Convert to modified equinoctial elements and back.\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 5: 0 inclination orbit,\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( eccentricityIndex ) = 0.3;\n        expectedKeplerianElements( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n        expectedKeplerianElements( longitudeOfAscendingNodeIndex ) = 0.0; // Set to zero as for\n        // non-inclined orbit planes, this parameter is undefined\n\n        // Convert to modified equinoctial elements and back.\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 6: 180 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( semiMajorAxisIndex ) = 1.0e10;\n        expectedKeplerianElements( inclinationIndex ) = PI;\n        avoidSingularity = true;\n        expectedKeplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 240.0 );\n\n        // Convert to modified equinoctial elements and back.\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n\n    // Case 7: 0 eccentricity and inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        expectedKeplerianElements( eccentricityIndex ) = 0.0;\n        expectedKeplerianElements( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n\n        // Convert to modified equinoctial elements and back\n        computedKeplerianElements = convertModifiedEquinoctialToKeplerianElements(\n                    convertKeplerianToModifiedEquinoctialElements( expectedKeplerianElements,\n                                                                   avoidSingularity ),\n                    avoidSingularity );\n\n        // Check if computed Keplerian elements match the expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedKeplerianElements,\n                                           computedKeplerianElements, tolerance );\n    }\n}\n\n//! Unit test for conversion of Cartesian to modified equinoctial elements.\nBOOST_AUTO_TEST_CASE( testConvertCartesianElementsToModifiedEquinoctialElements )\n{\n    using namespace orbital_element_conversions;\n    using namespace unit_conversions;\n    using mathematical_constants::PI;\n\n    double tolerance = 1.0E-14;\n\n    Eigen::Vector6d testMEE = Eigen::VectorXd::Zero( 6 );\n    Eigen::Vector6d computedMEE = Eigen::VectorXd::Zero( 6 );\n    Eigen::Vector6d testCartesianElements = Eigen::VectorXd::Zero( 6 );\n\n    // Set default Keplerian elements [m,-,rad,rad,rad,rad].\n    Eigen::Vector6d testKepler = Eigen::VectorXd::Zero( 6 );\n    testKepler( semiMajorAxisIndex ) = 1.0e7;\n    testKepler( eccentricityIndex ) = 0.1;\n    testKepler( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n    bool avoidSingularity = false;\n    testKepler( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 350.0 );\n    testKepler( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 15.0 );\n    testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n    double gravitationalParameter = 398600.44e9; // Earth's, but any parameter would do.\n\n    // Case 1: Elliptical prograde orbit.\n    {\n        // Default, so no modification necessary\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand)\n        testMEE( semiLatusRectumIndex ) = 9.9e6;\n        testMEE( fElementIndex )\n                = 0.09961946980917455322950104024739;\n        testMEE( gElementIndex )\n                = 0.00871557427476581735580642708375;\n        testMEE( hElementIndex )\n                = 0.45041861000828740764931177254188;\n        testMEE( kElementIndex )\n                = 0.12068930280766941437578622043344;\n        testMEE( trueLongitudeIndex )\n                = 3.0543261909900767596164588448551;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Compare, because element 2 is quite small, tolerance is less stringent than usual.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( testMEE, computedMEE, 1.0E-13 );\n\n        // Convert to modified equinoctial elements using direct function.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Compare, because element 2 is quite small, tolerance is less stringent than usual.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( testMEE, computedMEE, 1.0E-13 );\n    }\n\n    // Case 2: Hyperbolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( semiMajorAxisIndex ) = -1.0e7;\n        testKepler( eccentricityIndex ) = 2.0;\n        testKepler( inclinationIndex ) = convertDegreesToRadians( 170.0 );\n        avoidSingularity = true;\n        testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 10.0 );\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand)\n        testMEE( semiLatusRectumIndex ) = 3.0e7;\n        testMEE( fElementIndex )\n                = 1.8126155740732999264851053135086;\n        testMEE( gElementIndex )\n                = -0.84523652348139887237395697929546;\n        testMEE( hElementIndex )\n                = 0.0845075596072044152327702959491;\n        testMEE( kElementIndex )\n                = 0.02264373235107538825570191377426;\n        testMEE( trueLongitudeIndex )\n                = 6.0213859193804370403867331512857;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( testMEE, computedMEE, tolerance );\n\n        // Convert to modified equinoctial elements using direct function.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( testMEE, computedMEE, tolerance );\n    }\n\n    // Case 3: Parabolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( semiMajorAxisIndex ) = 1.0e7;\n        testKepler( eccentricityIndex ) = 1.0;\n        avoidSingularity = true;\n        testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        testMEE( semiLatusRectumIndex ) = 1.0e7;\n        testMEE( fElementIndex )\n                = 0.90630778703664996324255265675432;\n        testMEE( gElementIndex )\n                = -0.42261826174069943618697848964773;\n        testMEE( hElementIndex )\n                = 0.0845075596072044152327702959491;\n        testMEE( kElementIndex )\n                = 0.02264373235107538825570191377426;\n        testMEE( trueLongitudeIndex )\n                = 2.5307274153917778865393516143085;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( testMEE, computedMEE, tolerance );\n\n        // Convert to modified equinoctial elements using direct function.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( testMEE, computedMEE, tolerance );\n    }\n\n    // Case 4: Circular prograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler ( eccentricityIndex ) = 0.0;\n        testKepler ( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n        avoidSingularity = false;\n        testKepler ( argumentOfPeriapsisIndex ) = 0.0; // e = 0, so actually undefined\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        testMEE ( semiLatusRectumIndex ) = 1.0e7;\n        testMEE ( fElementIndex ) = 0.0;\n        testMEE ( gElementIndex ) = 0.0;\n        testMEE ( hElementIndex )\n                = 0.45041861000828740764931177254188;\n        testMEE ( kElementIndex )\n                = 0.12068930280766941437578622043344;\n        testMEE ( trueLongitudeIndex )\n                = 3.2288591161895097173088279217039;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this\n        Eigen::Vector6d vectorToAdd\n                = ( Eigen::Vector6d( ) << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ).finished( );\n        Eigen::Vector6d computedMeePlusOne = computedMEE + vectorToAdd;\n        Eigen::Vector6d testMeePlusOne = testMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n\n        // Convert to modified equinoctial elements using direct function\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        computedMeePlusOne = computedMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n    }\n\n    // Case 5: 0 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler ( eccentricityIndex ) = 0.1;\n        testKepler ( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n        testKepler ( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 260.0 );\n        testKepler ( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 0.0 );\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        testMEE( semiLatusRectumIndex ) = 9.9e6;\n        testMEE( fElementIndex )\n                = -0.01736481776669303488517166267693;\n        testMEE( gElementIndex )\n                = -0.09848077530122080593667430245895;\n        testMEE( hElementIndex ) = 0.0;\n        testMEE( kElementIndex ) = 0.0;\n        testMEE( trueLongitudeIndex )\n                = 1.221730476396030703846583537942;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        Eigen::Vector6d vectorToAdd\n                = ( Eigen::Vector6d( ) << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ).finished( );\n        Eigen::Vector6d computedMeePlusOne = computedMEE + vectorToAdd;\n        Eigen::Vector6d testMeePlusOne = testMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n\n        // Convert to modified equinoctial elements using direct function.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        computedMeePlusOne = computedMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n    }\n\n    // Case 6: 180 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( eccentricityIndex ) = 0.1;\n        testKepler( inclinationIndex ) = PI; // = 180 deg\n        avoidSingularity = true;\n        testKepler( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 12.0 );\n        testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 190.0 );\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        testMEE ( semiLatusRectumIndex ) = 9.9e6;\n        testMEE ( fElementIndex )\n                = 0.09781476007338056379285667478696;\n        testMEE ( gElementIndex )\n                = 0.02079116908177593371017422844051;\n        testMEE ( hElementIndex )\n                = 0.0;\n        testMEE ( kElementIndex )\n                = 0.0;\n        testMEE ( trueLongitudeIndex )\n                = 3.525565089028545745385855352347;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        Eigen::Vector6d vectorToAdd\n                = ( Eigen::Vector6d( ) << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ).finished( );\n        Eigen::Vector6d computedMeePlusOne = computedMEE + vectorToAdd;\n        Eigen::Vector6d testMeePlusOne = testMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n\n        // Convert to modified equinoctial elements using direct function.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        computedMeePlusOne = computedMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n    }\n\n    // Case 7: 0 eccentricity and inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( eccentricityIndex ) = 0.0;\n        testKepler( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n\n        // Set expected modified equinoctial elements [m,-,-,-,-,rad]. (Results were calculated by\n        // hand).\n        testMEE ( semiLatusRectumIndex ) = 1.0e7; // Circular\n        testMEE ( fElementIndex ) = 0.0;\n        testMEE ( gElementIndex ) = 0.0;\n        testMEE ( hElementIndex ) = 0.0;\n        testMEE ( kElementIndex ) = 0.0;\n        testMEE ( trueLongitudeIndex )\n                = 3.525565089028545745385855352347;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        testCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                     gravitationalParameter );\n\n        // Convert to modified equinoctial elements.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter,\n                                                                     avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        Eigen::Vector6d vectorToAdd\n                = ( Eigen::Vector6d( ) << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ).finished( );\n        Eigen::Vector6d computedMeePlusOne = computedMEE + vectorToAdd;\n        Eigen::Vector6d testMeePlusOne = testMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n\n        // Convert to modified equinoctial elements using direct function.\n        computedMEE = convertCartesianToModifiedEquinoctialElements( testCartesianElements,\n                                                                     gravitationalParameter );\n\n        // Check if computed elements match the expected values.\n        // Because two elements are near-zero, a close fraction/percentage check will fail.\n        // Therefore, 1.0 is added to the elements to avoid this.\n        computedMeePlusOne = computedMEE + vectorToAdd;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( computedMeePlusOne, testMeePlusOne, tolerance );\n    }\n}\n\n//! Unit test for conversion of modified equinoctial elements to Cartesian.\nBOOST_AUTO_TEST_CASE( testConvertModifiedEquinoctialToCartesianElements )\n{\n    /* Used procedure:\n      The Cartesian expected outcome is computed from the verified Kepler to Cartesian conversion.\n      Subsequently, the Kepler state is converted to modified equinoctial elements and then\n      converted back to Cartesian elements. Outcomes are compared.\n     */\n\n    using namespace orbital_element_conversions;\n    using namespace unit_conversions;\n    using mathematical_constants::PI;\n\n    // Tolerance precision: two orders higher than machine due to three conversions being applied\n    // (accumulation of error) in order to save on manual labor.\n    double tolerance = 2.0E-14;\n\n    Eigen::Vector6d intermediateModifiedEquinoctialElements\n            = Eigen::VectorXd::Zero( 6 );\n    Eigen::Vector6d expectedCartesianElements = Eigen::VectorXd::Zero( 6 );\n    Eigen::Vector6d computedCartesianElements = Eigen::VectorXd::Zero( 6 );\n\n    // Set default Keplerian elements [m,-,rad,rad,rad,rad].\n    Eigen::Vector6d testKepler = Eigen::VectorXd::Zero( 6 );\n    testKepler( semiMajorAxisIndex ) = 1.0e7;\n    testKepler( eccentricityIndex ) = 0.1;\n    testKepler( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n    bool avoidSingularity = false;\n    testKepler( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 350.0 );\n    testKepler( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 15.0 );\n    testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n    double gravitationalParameter = 398600.44e9; // Earth's, but any parameter would do.\n\n    // Case 1: Elliptical prograde orbit.\n    {\n        // Default, so no modification necessary.\n\n        // Create expected Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then that to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElementsViaKeplerElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n    }\n\n    // Case 2: Hyperbolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( semiMajorAxisIndex ) = -1.0e7;\n        testKepler( eccentricityIndex ) = 2.0;\n        testKepler( inclinationIndex )\n                = convertDegreesToRadians( 170.0 ); // Between 90 and 180 is retrograde\n        avoidSingularity = true;\n        testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 10.0 );\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElementsViaKeplerElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Check if computed elements match the expected values.\n        // Because element z is ~10^16 smaller than the other elements, it is only checked whether\n        // its value is 'sufficiently' close to zero.\n        BOOST_CHECK_SMALL( expectedCartesianElements( 2 ), 1.0E-9 );\n        BOOST_CHECK_SMALL( computedCartesianElements( 2 ), 1.0E-9 );\n        expectedCartesianElements( 2 ) = 0.0;\n        computedCartesianElements( 2 ) = 0.0;\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n    }\n\n    // Case 3: Parabolic retrograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( semiMajorAxisIndex ) = 1.0e7;\n        testKepler( eccentricityIndex ) = 1.0;\n        avoidSingularity = true;\n        testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 170.0 );\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElementsViaKeplerElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n    }\n\n    // Case 4: Circular prograde orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler ( eccentricityIndex ) = 0.0;\n        testKepler ( inclinationIndex ) = convertDegreesToRadians( 50.0 );\n        avoidSingularity = false;\n        testKepler ( argumentOfPeriapsisIndex ) = 0.0; // e = 0, so actually undefined.\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElementsViaKeplerElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           1.0E-13 );\n\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           1.0E-13 );\n    }\n\n    // Case 5: 0 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler ( eccentricityIndex ) = 0.1;\n        testKepler ( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n        testKepler ( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 260.0 );\n        testKepler ( longitudeOfAscendingNodeIndex ) = convertDegreesToRadians( 0.0 );\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElementsViaKeplerElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n    }\n\n    // Case 6: 180 inclination orbit.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( eccentricityIndex ) = 0.1;\n        testKepler( inclinationIndex ) = PI; // = 180 deg\n        avoidSingularity = true;\n        testKepler( argumentOfPeriapsisIndex ) = convertDegreesToRadians( 12.0 );\n        testKepler( trueAnomalyIndex ) = convertDegreesToRadians( 190.0 );\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElementsViaKeplerElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n\n//        computedCartesianElements = convertModifiedEquinoctialToCartesianElements(\n//                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n//                    avoidSingularity );\n\n//        // Compare.\n//        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n//                                           tolerance );\n    }\n\n    // Case 7: 0 eccentricity and inclination.\n    {\n        // Set Keplerian elements [m,-,rad,rad,rad,rad].\n        testKepler( eccentricityIndex ) = 0.0;\n        testKepler( inclinationIndex ) = 0.0;\n        avoidSingularity = false;\n\n        // Create starting Cartesian vector through the verified Kepler to Cartesian routine.\n        expectedCartesianElements = convertKeplerianToCartesianElements( testKepler,\n                                                                         gravitationalParameter );\n\n        // Convert to modified equinoctial elements, then to Cartesian.\n        intermediateModifiedEquinoctialElements =\n                convertKeplerianToModifiedEquinoctialElements( testKepler, avoidSingularity );\n        computedCartesianElements = convertModifiedEquinoctialToCartesianElementsViaKeplerElements(\n                    intermediateModifiedEquinoctialElements, gravitationalParameter,\n                    avoidSingularity );\n\n        // Compare.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianElements, computedCartesianElements,\n                                           tolerance );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "6a53fb6cba7833bbe5fe228437cc615ec5c4be16", "size": 56931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestModifiedEquinoctialElementConversions.cpp", "max_stars_repo_name": "J-Westin/tudat", "max_stars_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestModifiedEquinoctialElementConversions.cpp", "max_issues_repo_name": "J-Westin/tudat", "max_issues_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestModifiedEquinoctialElementConversions.cpp", "max_forks_repo_name": "J-Westin/tudat", "max_forks_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.7859054416, "max_line_length": 100, "alphanum_fraction": 0.6512971843, "num_tokens": 12592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5965148218172394}}
{"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": "///////////////////////////////////////////////////////////////////\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#include <boost/config.hpp>\n#include <boost/multiprecision/number.hpp>\n#ifdef BOOST_MATH_USE_FLOAT128\n#include <boost/multiprecision/complex128.hpp>\n#endif\n#include <boost/math/fft/fftw_backend.hpp>\n\n#include <array>\n#include <complex>\n\n#include <boost/core/demangle.hpp>\n#include <iostream>\n\ntemplate<class Backend, int N >\nvoid test()\n{\n  using T = typename Backend::value_type;\n  std::cout << \"Testing: \" << boost::core::demangle(typeid(T).name()) << \"\\n\";\n  Backend P(N);    \n  alignas(1)  std::array<T,N> A;\n  alignas(16) std::array<T,N> B;\n  \n  P.forward(A.data(),A.data()+N,B.data());\n  P.backward(A.data(),A.data()+N,B.data());\n  \n  P.forward(A.data(),A.data()+N,A.data());\n  P.backward(A.data(),A.data()+N,A.data());\n  \n  P.forward(B.data(),B.data()+N,B.data());\n  P.backward(B.data(),B.data()+N,B.data());\n}\n\nint main()\n{\n  using boost::math::fft::fftw_dft;\n  test<fftw_dft<std::complex<float>>,      16 >();\n  test<fftw_dft<std::complex<double>>,     16 >();\n  test<fftw_dft<std::complex<long double>>,16 >();\n#ifdef BOOST_MATH_USE_FLOAT128\n  test<fftw_dft<boost::multiprecision::complex128>,16 >();\n#endif\n  return 0;\n}\n\n", "meta": {"hexsha": "f87d134a8b7451707a4220db7bc34a3f8c150096", "size": 1471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fft_alignment.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/fft_alignment.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/fft_alignment.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 27.7547169811, "max_line_length": 78, "alphanum_fraction": 0.6410605031, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5965147945411097}}
{"text": "#include \"summarize.h\"\n#include \"util.h\"\n\n#include <Eigen/Core>\n#include <cassert>\n\nvoid Summarize(\n    TClusters& clusters,\n    const TAgencyRating& agencyRating,\n    const std::map<std::string, std::unique_ptr<TFastTextEmbedder>>& embedders\n) {\n    for (auto& cluster : clusters) {\n        const TFastTextEmbedder& embedder = *embedders.at(cluster.GetLanguage());\n\n        Eigen::MatrixXf points(cluster.GetSize(), embedder.GetEmbeddingSize());\n        for (size_t i = 0; i < cluster.GetSize(); i++) {\n            const TDocument& doc = cluster.GetDocuments()[i];\n            fasttext::Vector embedding = embedder.GetSentenceEmbedding(doc);\n            Eigen::Map<Eigen::VectorXf, Eigen::Unaligned> eigenVector(embedding.data(), embedding.size());\n            points.row(i) = eigenVector / eigenVector.norm();\n        }\n        Eigen::MatrixXf docsCosine = points * points.transpose();\n\n        std::vector<double> weights;\n        weights.reserve(cluster.GetSize());\n        uint64_t freshestTimestamp = cluster.GetFreshestTimestamp();\n        for (size_t i = 0; i < cluster.GetSize(); ++i) {\n            const TDocument& doc = cluster.GetDocuments()[i];\n            double docRelevance = docsCosine.row(i).mean();\n            double timeMultiplier = Sigmoid(static_cast<double>(doc.FetchTime - freshestTimestamp) / 3600.0 + 12.0);\n            double agencyScore = agencyRating.ScoreUrl(doc.Url);\n            double weight = (agencyScore + docRelevance) * timeMultiplier;\n            weights.push_back(weight);\n        }\n        cluster.SortByWeights(weights);\n    }\n}\n", "meta": {"hexsha": "8e721dc248ea81d4f61db01b76499463224a2cd5", "size": 1572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/summarize.cpp", "max_stars_repo_name": "gangeleski/tgcontest", "max_stars_repo_head_hexsha": "3d8ab5ba140c9a6f928c40e97c917db9f9297321", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-02T21:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T21:17:39.000Z", "max_issues_repo_path": "src/summarize.cpp", "max_issues_repo_name": "gangeleski/tgcontest", "max_issues_repo_head_hexsha": "3d8ab5ba140c9a6f928c40e97c917db9f9297321", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/summarize.cpp", "max_forks_repo_name": "gangeleski/tgcontest", "max_forks_repo_head_hexsha": "3d8ab5ba140c9a6f928c40e97c917db9f9297321", "max_forks_repo_licenses": ["Apache-2.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.3684210526, "max_line_length": 116, "alphanum_fraction": 0.6424936387, "num_tokens": 364, "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 <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": "/**\n * @ file stableevaluationatapoint_main.cc\n * @ brief NPDE homework StableEvaluationAtAPoint\n * @ author Am\u00e9lie Loher\n * @ date 22.04.20\n * @ copyright Developed at SAM, ETH Zurich\n */\n\n#include <lf/assemble/assemble.h>\n#include <lf/io/io.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/refinement/mesh_hierarchy.h>\n\n#include <Eigen/Core>\n#include <fstream>\n#include <iostream>\n#include <string>\n\n#include \"stableevaluationatapoint.h\"\n\nusing namespace StableEvaluationAtAPoint;\n\nint main(int /*argc*/, const char ** /*argv*/) {\n  /* LOADING COARSE MESH */\n  // Load mesh into a Lehrfem++ Mesh object. See Example 2.7.1.11 in lecture\n  // document.\n  auto mesh_factory_init = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader_init(std::move(mesh_factory_init),\n                                 CURRENT_SOURCE_DIR \"/../meshes/square.msh\");\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = reader_init.mesh();\n  // Finite Element Space for lowest-order Lagrangian finite elements\n  std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  // Initial dofhandler as built along with the finite-element space\n  const lf::assemble::DofHandler &dofh = fe_space->LocGlobMap();\n  // Dimension of unconstrained finite-element space\n  lf::base::size_type N_dofs = dofh.NumDofs();\n\n  // EXACT SOLUTION AND CHOSEN POINT x INSIDE THE DOMAIN\n  // u(x) = log(|x + [1 0]|): harmonic inside the unit square\n  auto u = [](Eigen::Vector2d x) -> double {\n    Eigen::Vector2d one(1.0, 0.0);\n    return std::log((x + one).norm());\n  };\n  // Fixed evaluation point\n  Eigen::Vector2d x(0.3, 0.4);\n\n  // INITIALIZING ERROR ANALYSIS TOOLS AND OBJECTS\n  int N_meshes = 8;  // total number of meshes (coarse + refinement)\n  // Array for recording mesh widths\n  Eigen::VectorXd mesh_sizes{Eigen::VectorXd::Zero(N_meshes)};\n  mesh_sizes(0) = getMeshSize(mesh_p);\n  // Dimensions of (full) finite element spaces\n  Eigen::VectorXd dofs{Eigen::VectorXd::Zero(N_meshes)};\n  dofs(0) = N_dofs;\n\n  // Naive point evaluation\n  Eigen::VectorXd errors_Eval(N_meshes);\n  errors_Eval.setZero();\n// Subproblem (3-11.b)\n//====================\n// Your code goes here\n//====================\n\n  // Stable point evaluation\n  Eigen::VectorXd errors_stabEval(N_meshes);\n  errors_stabEval.setZero();\n  Eigen::VectorXd ux(N_meshes);\n  ux.setZero();\n\n/* CONVERGENCE ANALYSIS */\n// Subproblem (3-11.h)\n//====================\n// Your code goes here\n//====================\n\n  for (int k = 1; k < N_meshes; k++) {  // for each mesh refinement\n    // Load finer mesh\n    std::string idx = std::to_string(k);\n    auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n    lf::io::GmshReader reader(std::move(mesh_factory), CURRENT_SOURCE_DIR\n                                                           \"/../meshes/square\" +\n                                                           idx + \".msh\");\n    mesh_p = reader.mesh();\n    fe_space = std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n    const lf::assemble::DofHandler &dofh = fe_space->LocGlobMap();\n    lf::base::size_type N_dofs = dofh.NumDofs();\n\n    // Update objects info and evaluate error\n    mesh_sizes(k) = getMeshSize(mesh_p);\n    dofs(k) = N_dofs;\n    errors_Eval(k) = pointEval(mesh_p);\n\n    ux(k) = stab_pointEval(fe_space, u, x);\n    errors_stabEval(k) = std::abs(u(x) - ux(k));\n    std::cout << \"u(x)=\" << u(x) << \", ux=\" << ux(k) << std::endl;\n  }\n\n  // Computing rates of convergence\n  double ratesEval[N_meshes - 1];\n  double ratesStabEval[N_meshes - 1];\n  double log_denum;\n  for (int k = 0; k < N_meshes - 1; k++) {\n    log_denum = log(mesh_sizes[k] / mesh_sizes[k + 1]);\n    ratesEval[k] = log(errors_Eval[k] / errors_Eval[k + 1]) / log_denum;\n    ratesStabEval[k] =\n        log(errors_stabEval[k] / errors_stabEval[k + 1]) / log_denum;\n  }\n\n  std::cout << \"*********************************************************\"\n            << std::endl;\n  std::cout << \"       Errors for StableEvaluationAtAPoint\t\t\"\n            << std::endl;\n  std::cout << \"--------------------- ERRORS ---------------------------\"\n            << std::endl;\n  std::cout << \"mesh size\"\n            << \"\\t| pointEval\"\n            << \"\\t\\t| stab_pointEval\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  for (int i = 0; i < 5; i++) {\n    std::cout << mesh_sizes(i) << \"\\t\"\n              << \"\\t\" << errors_Eval(i) << \"\\t \\t\" << errors_stabEval(i)\n              << std::endl;\n  }\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n\n  std::cout << \"\\n\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  std::cout << \"      Convergence rates for NAIVE point evaluation       \"\n            << std::endl;\n  std::cout << \"--------------------- RESULTS ---------------------------\"\n            << std::endl;\n  std::cout << \"Iteration\"\n            << \"\\t| errors_Eval\"\n            << \"\\t\\t| rates\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  for (int k = 0; k < N_meshes; k++) {\n    std::cout << k << \"\\t\"\n              << \"\\t|\" << errors_Eval[k];\n    if (k > 0) {\n      std::cout << \"\\t\\t|\" << ratesEval[k - 1];\n    }\n    std::cout << \"\\n\";\n  }\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n\n  std::cout << \"\\n\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  std::cout << \"      Convergence rates for STABLE point evaluation       \"\n            << std::endl;\n  std::cout << \"--------------------- RESULTS ---------------------------\"\n            << std::endl;\n  std::cout << \"Iteration\"\n            << \"\\t| errors_stabEval\"\n            << \"\\t\\t| rates\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  for (int k = 0; k < N_meshes; k++) {\n    std::cout << k << \"\\t\"\n              << \"\\t|\" << errors_stabEval[k];\n    if (k > 0) {\n      std::cout << \"\\t\\t|\" << ratesStabEval[k - 1];\n    }\n    std::cout << \"\\n\";\n  }\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n\n  // Define output file format\n  const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision,\n                                         Eigen::DontAlignCols, \", \", \"\\n\");\n\n  std::ofstream file;\n  file.open(\"errors_Eval.csv\");\n  file << errors_Eval.format(CSVFormat);\n  file.close();\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/errors_Eval.csv\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "803b530d89293aaff74f5539b7c663124ba0b71c", "size": 6777, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/StableEvaluationAtAPoint/templates/stableevaluationatapoint_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/StableEvaluationAtAPoint/templates/stableevaluationatapoint_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/StableEvaluationAtAPoint/templates/stableevaluationatapoint_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": 36.2406417112, "max_line_length": 80, "alphanum_fraction": 0.5108455069, "num_tokens": 1813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.5964256512916908}}
{"text": "//-----------------------------------------------------------------------------\n// Examples and tests of the constant expression table library.\n//-----------------------------------------------------------------------------\n//\n// Copyright (c) 2013\n// Joshua Napoli <jnapoli@alum.mit.edu>\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#define BOOST_TEST_MODULE table_test\n#include <boost/test/unit_test.hpp>\n#include <table.hpp>\n\nstruct times_two\n{\n  constexpr std::size_t operator()( std::size_t x ) { return x*2; }\n};\n\nBOOST_AUTO_TEST_CASE( table_should_generate_values )\n{\n  constexpr table<std::size_t, 5> actual_array{ times_two{} };\n\n  std::array<std::size_t,5> expected_array{{0,2,4,6,8}};\n\n  BOOST_CHECK_EQUAL_COLLECTIONS\n    ( actual_array.begin(), actual_array.end()\n    , expected_array.begin(), expected_array.end()\n    );\n}\n\ntypedef table<std::size_t, 2> test_table_type;\nconstexpr test_table_type test_table{times_two()};\nstatic_assert( 0 == test_table[0], \"test_table[0] should be equal 0 (2*0)\" );\nstatic_assert( 2 == test_table[1], \"test_table[1] should be equal 2 (2*1)\" );\n\nstatic_assert( 2 == std::tuple_size<test_table_type>::value, \"test table should have tuple interface\" );\n\n\n// Can construct a constexpr table using a class with a ctor taking an index as an argument.\nstruct times_three_t\n{\n  constexpr times_three_t( std::size_t n ) : n_( 3*n ) {}\n\n  std::size_t n_;\n};\n\nconstexpr table<times_three_t,5> times_three;\nstatic_assert( times_three[3].n_ == 9, \"times_three[3] should be 9\" );\n", "meta": {"hexsha": "7e2c237765a3240e2e1aee364f25d3f6b07d67c6", "size": 1640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/table_test.cpp", "max_stars_repo_name": "joshuanapoli/table", "max_stars_repo_head_hexsha": "949c37101e8ff736c1b3cc8f32d61d482d26f90b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-09-05T08:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-26T21:43:23.000Z", "max_issues_repo_path": "test/table_test.cpp", "max_issues_repo_name": "joshuanapoli/table", "max_issues_repo_head_hexsha": "949c37101e8ff736c1b3cc8f32d61d482d26f90b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/table_test.cpp", "max_forks_repo_name": "joshuanapoli/table", "max_forks_repo_head_hexsha": "949c37101e8ff736c1b3cc8f32d61d482d26f90b", "max_forks_repo_licenses": ["BSL-1.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.1568627451, "max_line_length": 104, "alphanum_fraction": 0.6487804878, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.596425647614176}}
{"text": "#include <catch.hpp>\n\n#define BOOST_LOG_DYN_LINK 1\n#include <boost/log/trivial.hpp>\n\n#include \"../core_power.cpp\"\n\nTEST_CASE( \"UNIT TEST: growth functions {growth_factor, growth_rate, growth_change}\", \"[core_power]\" )\n{\n    BOOST_LOG_TRIVIAL(info) << \"growth functions {growth_factor, growth_rate, growth_change}\";\n\n    int argc = 1;\n    const char* const argv[1] = {\"test\"};\n    Sim_Param sim(argc, argv);\n    FTYPE_t D, D_to_a, f, Oma, OLa, dDda, factor;\n    for (FTYPE_t a =0; a <= 1.0; a += 0.1)\n    {\n        D = growth_factor(a, sim.cosmo);\n        f = growth_rate(a, sim.cosmo);\n        dDda = growth_change(a, sim.cosmo);\n        D_to_a = a ? D/a : dDda;\n        CHECK( dDda == Approx(D_to_a*f) );\n    }\n\n    CHECK(0.0 == growth_factor(0, sim.cosmo));\n    CHECK(1.0 == growth_factor(1, sim.cosmo));\n}", "meta": {"hexsha": "ed7d8ca0d05f798ca49ae2fe6960751b3e0a1451", "size": 808, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/tests/test_core_power.cpp", "max_stars_repo_name": "vrastil/Adhesion-Approximation", "max_stars_repo_head_hexsha": "02619dc5aae0627e4a2e87bc3577c75d4b1e42c2", "max_stars_repo_licenses": ["Apache-2.0"], "max_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/tests/test_core_power.cpp", "max_issues_repo_name": "vrastil/Adhesion-Approximation", "max_issues_repo_head_hexsha": "02619dc5aae0627e4a2e87bc3577c75d4b1e42c2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2017-06-27T07:34:02.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-17T07:36:21.000Z", "max_forks_repo_path": "src/core/tests/test_core_power.cpp", "max_forks_repo_name": "vrastil/Adhesion-Approximation", "max_forks_repo_head_hexsha": "02619dc5aae0627e4a2e87bc3577c75d4b1e42c2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-20T13:15:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-03T12:48:40.000Z", "avg_line_length": 29.9259259259, "max_line_length": 102, "alphanum_fraction": 0.6188118812, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276224, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5964038302118138}}
{"text": "#include <iostream>\n#include <cassert>\n#include <boost/graph/adjacency_matrix.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.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 std::tuple<int, int, int> RawEdgeWeight;\ntypedef boost::adjacency_matrix<boost::directedS, boost::no_property, boost::property<boost::edge_weight_t, long>> Graph;\n\nstruct MstEdge\n{\n  int cost, from, to;\n};\n\nvoid testcase()\n{\n  int n, root_i;\n  std::cin >> n >> root_i;\n  assert(n >= 3 && n <= 1e3 && root_i >= 1 && root_i <= n);\n  root_i--;\n\n  Graph G(n);\n  std::vector<std::vector<int>> edge_costs(n, std::vector<int>(n));\n  for (int i = 0; i < n; i++)\n  {\n    for (int j = i + 1; j < n; j++)\n    {\n      int cost;\n      std::cin >> cost;\n      assert(cost >= 1 && cost <= (1 << 20));\n\n      edge_costs.at(i).at(j) = cost;\n      edge_costs.at(j).at(i) = cost;\n\n      boost::add_edge(i, j, long(cost) << 20 | long(n - j) << 10 | long(n - i), G);\n      boost::add_edge(j, i, long(cost) << 20 | long(n - i) << 10 | long(n - j), G);\n    }\n  }\n\n  std::vector<Graph::vertex_descriptor> predecessors(n);\n  boost::prim_minimum_spanning_tree(G, predecessors.data(), boost::root_vertex(root_i));\n\n  auto weights = boost::get(boost::edge_weight, G);\n  int leia_cost = 0;\n  for (int i = 0; i < n; i++)\n  {\n    const Graph::vertex_descriptor p = predecessors.at(i);\n    if (int(p) == i)\n    {\n      DEBUG(3, \"same predecessor \" << i);\n      assert(i == root_i);\n      continue;\n    }\n\n    const int cost = edge_costs.at(p).at(i);\n    DEBUG(3, \"p \" << p << \" to i \" << i << \" costs \" << cost);\n    assert(cost >= 1 && cost <= (1 << 20));\n    leia_cost += cost;\n  }\n  DEBUG(2, \"leia_cost \" << leia_cost);\n\n  auto max_cost_between_endpoints = [root_i](const std::vector<std::pair<int, int>> &path_a, const std::vector<std::pair<int, int>> &path_b) {\n    auto it_a = path_a.rbegin(), it_b = path_b.rbegin();\n    while (it_a != path_a.rend() && it_b != path_b.rend() && it_a->first == it_b->first)\n    {\n      it_a++;\n      it_b++;\n    }\n    int max_cost = 0;\n    if (it_a != path_a.rend())\n    {\n      max_cost = std::max(max_cost, it_a->second);\n    }\n    if (it_b != path_b.rend())\n    {\n      max_cost = std::max(max_cost, it_b->second);\n    }\n    return max_cost;\n  };\n\n  std::vector<std::vector<std::pair<int, int>>> paths_to_root(n);\n  for (int i = 0; i < n; i++)\n  {\n    std::vector<std::pair<int, int>> &path = paths_to_root.at(i);\n    int j = i;\n    int max_cost = 0;\n    while (true)\n    {\n      const int p = predecessors.at(j);\n      if (p == j)\n      {\n        break;\n      }\n      const int cost = edge_costs.at(p).at(j);\n      max_cost = std::max(max_cost, cost);\n      path.push_back(std::make_pair(j, max_cost));\n      j = p;\n    }\n  }\n\n  int min_total_cost = std::numeric_limits<int>::max();\n  for (int from = 0; from < n; from++)\n  {\n    for (int to = from + 1; to < n; to++)\n    {\n      DEBUG(3, \"considering adding edge \" << from << \" \" << to);\n\n      if (int(predecessors.at(from)) == to || int(predecessors.at(to)) == from)\n      {\n        DEBUG(3, \"edge already in mst\");\n        continue;\n      }\n\n      const int added_cost = edge_costs.at(from).at(to);\n      const int removed_cost = max_cost_between_endpoints(paths_to_root.at(from), paths_to_root.at(to));\n      DEBUG(3, \"added_cost \" << added_cost << \" removed_cost \" << removed_cost);\n      assert(added_cost >= removed_cost);\n\n      const int this_total_cost = leia_cost - removed_cost + added_cost;\n      if (this_total_cost < min_total_cost)\n      {\n        min_total_cost = this_total_cost;\n        DEBUG(3, \"lowered min_total_cost \" << min_total_cost);\n      }\n    }\n  }\n\n  std::cout << min_total_cost << \"\\n\";\n}\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n\n  int t;\n  std::cin >> t;\n  for (int i = 0; i < t; i++)\n  {\n    testcase();\n    DEBUG(1, \"\");\n  }\n\n  return 0;\n}", "meta": {"hexsha": "53723baac3aa7add7ec313347d966dcdb026e716", "size": 3970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-11/return-of-the-jedi/src/main.cpp", "max_stars_repo_name": "tehwalris/algolab", "max_stars_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T08:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T08:21:32.000Z", "max_issues_repo_path": "week-11/return-of-the-jedi/src/main.cpp", "max_issues_repo_name": "tehwalris/algolab", "max_issues_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-11/return-of-the-jedi/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": 26.2913907285, "max_line_length": 142, "alphanum_fraction": 0.5614609572, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5964038158385933}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\nnamespace mp = boost::multiprecision;\r\n\r\nmp::cpp_int sum_of_digits(mp::cpp_int num) {\r\n\tmp::cpp_int sum = 0;\r\n\twhile(num) {\r\n\t\tsum += num % 10;\r\n\t\tnum /= 10;\r\n\t}\r\n\treturn sum;\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n\tcout << sum_of_digits(mp::pow((mp::cpp_int)2, 1000)) << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "d38a25e63087427921ba0cd16823edfaa209c099", "size": 385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/1-50/16/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/16/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/16/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": 20.2631578947, "max_line_length": 63, "alphanum_fraction": 0.6337662338, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770431, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5964038143760403}}
{"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": "#include <gtest/gtest.h>\n\n#include <Eigen/SparseCore>\n\n#include \"../transformationofgalerkinmatrices.h\"\n\nnamespace TransformationOfGalerkinMatrices::test {\n\nTEST(TransformationOfGalerkinMatrices, TestTransformation) {\n  std::cout << \"NPDE homework TransformationOfGalerkinMatrices: unit test\"\n            << std::endl;\n\n  // Create change of basis matrix S\n  typedef Eigen::SparseMatrix<double> SpMat;\n  std::vector<Eigen::Triplet<double>> S_triplets;\n\n  int N = 4;\n  SpMat S(2 * N, 2 * N);\n  for (int i = 0; i < N; i++) {\n    S_triplets.push_back(Eigen::Triplet<double>(i, i * 2, 1));\n    S_triplets.push_back(Eigen::Triplet<double>(i, i * 2 + 1, 1));\n    S_triplets.push_back(Eigen::Triplet<double>(N + i, i * 2, 1));\n    S_triplets.push_back(Eigen::Triplet<double>(N + i, i * 2 + 1, -1));\n  }\n  S.setFromTriplets(S_triplets.begin(), S_triplets.end());\n\n  SpMat sol_mat(2 * N, 2 * N);\n  SpMat A_mat(2 * N, 2 * N);\n  SpMat A_tilde_mat(2 * N, 2 * N);\n  std::vector<Eigen::Triplet<double>> A, A_tilde;\n\n  // Case 1 and 2\n  A.push_back(Eigen::Triplet<double>(2 * N - 1, 2 * N - 1, 1));  // i, j even\n  A.push_back(Eigen::Triplet<double>(3 - 1, 3 - 1, 5));          // i, j odd\n  A_mat.setFromTriplets(A.begin(), A.end());\n  A_tilde = TransformationOfGalerkinMatrices::transformCOOmatrix(A);\n  A_tilde_mat.setFromTriplets(A_tilde.begin(), A_tilde.end());\n  sol_mat = S * A_mat * S.transpose();\n\n  ASSERT_TRUE((sol_mat - A_tilde_mat).norm() == 0);\n\n  // Case 3\n  A.clear();\n  A_tilde.clear();\n  A.push_back(Eigen::Triplet<double>(2 * N - 1, 2 * N - 1, 1));\n  A.push_back(Eigen::Triplet<double>(4 - 1, 3 - 1, 5));  // i even, j odd\n  A_mat.setFromTriplets(A.begin(), A.end());\n  A_tilde = TransformationOfGalerkinMatrices::transformCOOmatrix(A);\n  A_tilde_mat.setFromTriplets(A_tilde.begin(), A_tilde.end());\n  sol_mat = S * A_mat * S.transpose();\n\n  ASSERT_TRUE((sol_mat - A_tilde_mat).norm() == 0);\n\n  // Case 4\n  A.clear();\n  A_tilde.clear();\n  A.push_back(Eigen::Triplet<double>(2 * N - 1, 2 * N - 1, 1));\n  A.push_back(Eigen::Triplet<double>(3 - 1, 4 - 1, 5));  // i odd, j even\n  A_mat.setFromTriplets(A.begin(), A.end());\n  A_tilde = TransformationOfGalerkinMatrices::transformCOOmatrix(A);\n  A_tilde_mat.setFromTriplets(A_tilde.begin(), A_tilde.end());\n  sol_mat = S * A_mat * S.transpose();\n\n  ASSERT_TRUE((sol_mat - A_tilde_mat).norm() == 0);\n}\n\n}  // namespace TransformationOfGalerkinMatrices::test\n", "meta": {"hexsha": "cc7b3af2b8fe26afb292aa34f248f21644943153", "size": 2406, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/TransformationOfGalerkinMatrices/templates/test/transformationofgalerkinmatrices_test.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/TransformationOfGalerkinMatrices/templates/test/transformationofgalerkinmatrices_test.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/TransformationOfGalerkinMatrices/templates/test/transformationofgalerkinmatrices_test.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3823529412, "max_line_length": 77, "alphanum_fraction": 0.6558603491, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481138, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.596308309951485}}
{"text": "#include <string>\n#include <sstream>\n#include <iostream>\n#include <map>\n#include <regex>\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\n#include \"../common.hpp\"\n\nusing namespace std;\n\nbool sum(const vector<int> & nums, int offset, int target) {\n    for (int x = offset; x < nums.size(); x++) {\n        for (int y = x + 1; y < nums.size(); y++) {\n            if ((nums[x] + nums[y]) == target) {\n                return true;\n            }\n        }\n    }\n    return false;\n}\n\nint range(const vector<int> & nums, int offset, int target) {\n    int smallest = INT_MAX;\n    int largest = 0;\n    int total = 0;\n    int i = offset;\n    while (total < target && i < nums.size()) {\n        total += nums[i];\n\n        smallest = min(smallest, nums[i]);\n        largest = max(largest, nums[i]);\n\n        i++;\n    }\n    if (total == target) {\n        return smallest + largest;\n    }\n    return 0;\n}\n\nint main() {\n    ifstream file (\"2020/9.txt\");\n    if (!file.is_open()) {\n        cout << \"Failed to open file: \" << strerror(errno) << endl;\n        return -1;\n    }\n\n    int answer1 = 0;\n    int answer2 = 0;\n\n    int preamble = 25;\n    vector<int> nums;\n\n    string line; \n    while (getline(file, line, '\\n')) {\n        boost::trim(line);\n\n        if (line == \"\") {\n            continue;\n        }\n\n        int i = stoi(line);\n\n        if (nums.size() > preamble) {\n            // Start checking\n            if (!sum(nums, nums.size() - preamble, i)) {\n                answer1 = i;\n                break;\n            }\n        }\n\n        nums.push_back(i);\n    }\n\n    cout << \"Answer 9.1: \" << answer1 << endl;\n\n    for (int x = 0; x < nums.size(); x++) {\n        answer2 = range(nums, x, answer1);\n        if (answer2) {\n            break;\n        }\n    }\n\n    cout << \"Answer 9.2: \" << answer2 << endl;\n\n    file.close();\n}", "meta": {"hexsha": "e3991c75e930b5e7d36cd1a1b1a44df4a5196b0b", "size": 1828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/9.cpp", "max_stars_repo_name": "bramp/aoc", "max_stars_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2020/9.cpp", "max_issues_repo_name": "bramp/aoc", "max_issues_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/9.cpp", "max_forks_repo_name": "bramp/aoc", "max_forks_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5393258427, "max_line_length": 67, "alphanum_fraction": 0.4797592998, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.5963082961347549}}
{"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\u00e4ckel.\n\n        21 200 primitive polynomials modulo two are provided in QuantLib.\n        J\u00e4ckel 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\u00e4ckel 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": "//==================================================================================================\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/*!\n  @ingroup group-constant\n  @defgroup constant-Log_2 Log_2 (function template)\n\n  Generates the constant \\f$\\log(2)\\f$\n\n  @headerref{<boost/simd/constant/log_2.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Log_2();\n      @endcode\n\n  2.  @code\n      template<typename T> T Log_2( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T that evaluates to \\f$\\log(2)\\f$.\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n   A value of type @c T that evaluates to ` T(0.6931471805599453094172321214581765680755001343602553)`.\n\n  @par Requirements\n  - **T** models IEEEValue\n**/\n\n#include <boost/simd/constant/scalar/log_2.hpp>\n#include <boost/simd/constant/simd/log_2.hpp>\n\n#endif\n", "meta": {"hexsha": "618a36a85fd45ac031b133935e1ab1d77c541bb0", "size": 1499, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/log_2.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/log_2.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/log_2.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 29.3921568627, "max_line_length": 103, "alphanum_fraction": 0.530353569, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.596180406706552}}
{"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": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"NNFuncs.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Core>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass NNLayer\n{\n  using MatrixXd = Eigen::MatrixXd;\n  using VectorXd = Eigen::VectorXd;\n  using Activation = NNActivations::Activation;\n  using LayerData = std::tuple<RealMatrixView, RealVectorView, index>;\n\npublic:\n  NNLayer(index inputSize, index outputSize, index actType)\n  {\n    using namespace Eigen;\n    mWeights = MatrixXd::Ones(inputSize, outputSize);\n    mBiases = VectorXd::Zero(outputSize);\n    mActType = actType;\n    mActivation = static_cast<Activation>(actType);\n  }\n\n  void init(Eigen::Ref<MatrixXd> weights, Eigen::Ref<VectorXd> biases,\n            index actType)\n  {\n    mWeights = weights;\n    mBiases = biases;\n    mActType = actType;\n    mActivation = static_cast<Activation>(actType);\n    initGrads();\n  }\n\n  void init()\n  {\n    double dev = std::sqrt(6.0 / (mWeights.rows() + mWeights.cols()));\n    mWeights = dev * MatrixXd::Random(mWeights.rows(), mWeights.cols()).array();\n    mBiases = VectorXd::Zero(mWeights.cols());\n    initGrads();\n  }\n\n  MatrixXd getWeights() const { return mWeights; }\n  VectorXd getBiases() const { return mBiases; }\n  index    getActType() const { return mActType; }\n\n  void initGrads()\n  {\n    mWeightsGrad = MatrixXd::Zero(mWeights.rows(), mWeights.cols());\n    mBiasesGrad = VectorXd::Zero(mWeights.cols());\n    mPrevWeightsUpdate = MatrixXd::Zero(mWeights.rows(), mWeights.cols());\n    mPrevBiasesUpdate = VectorXd::Zero(mWeights.cols());\n  }\n\n  index inputSize() const { return mWeights.rows(); }\n\n  index outputSize() const { return mWeights.cols(); }\n\n  void forward(Eigen::Ref<MatrixXd> in, Eigen::Ref<MatrixXd> out) const\n  {\n    mInput = in;\n    MatrixXd WT = mWeights.transpose();\n    MatrixXd IT = mInput.transpose();\n    MatrixXd Z = ((WT * IT).colwise() + mBiases).transpose();\n    mOutput = MatrixXd::Zero(out.rows(), out.cols());\n    NNActivations::activation()[mActivation](Z, mOutput);\n    out = mOutput;\n  }\n\n  void backward(Eigen::Ref<MatrixXd> outGrad, Eigen::Ref<MatrixXd> inGrad)\n  { // going backwards, so out is in\n    MatrixXd dAct = MatrixXd::Zero(mOutput.rows(), mOutput.cols());\n    NNActivations::derivative()[mActivation](mOutput, dAct);\n    MatrixXd actGrad = dAct.array() * outGrad.array();\n    double   norm = 1.0 / mInput.rows();\n    mWeightsGrad = norm * (mInput.transpose() * actGrad);\n    inGrad = actGrad * mWeights.transpose();\n    mBiasesGrad = actGrad.colwise().mean();\n  }\n\n  void update(double learningRate, double momentum)\n  {\n    MatrixXd wUpdate = (momentum * mPrevWeightsUpdate) +\n                       ((1 - momentum) * learningRate * mWeightsGrad);\n    VectorXd bUpdate = (momentum * mPrevBiasesUpdate) +\n                       ((1 - momentum) * learningRate * mBiasesGrad);\n    mWeights = mWeights - wUpdate;\n    mBiases = mBiases - bUpdate;\n    mPrevWeightsUpdate = wUpdate;\n    mPrevBiasesUpdate = bUpdate;\n  }\n\nprivate:\n  MatrixXd   mWeights;\n  VectorXd   mBiases;\n  index      mActType;\n  Activation mActivation;\n\n  MatrixXd mWeightsGrad;\n  VectorXd mBiasesGrad;\n\n  MatrixXd mPrevWeightsUpdate;\n  VectorXd mPrevBiasesUpdate;\n\n  mutable MatrixXd mInput;\n  mutable MatrixXd mOutput;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "caf8c5a3c3a8d3b4b52ba060e958fea3b560b68d", "size": 3687, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/NNLayer.hpp", "max_stars_repo_name": "jamesb93/flucoma-core", "max_stars_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/algorithms/util/NNLayer.hpp", "max_issues_repo_name": "jamesb93/flucoma-core", "max_issues_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/algorithms/util/NNLayer.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2213114754, "max_line_length": 80, "alphanum_fraction": 0.6859235151, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.596081275355641}}
{"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": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <utility> // std::pair, std::make_pair\n#include <cmath> // float comparison\n#include <limits>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"persistent_cohomology_multi_field\"\n#include <boost/test/unit_test.hpp>\n\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/reader_utils.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Persistent_cohomology.h>\n#include <gudhi/Persistent_cohomology/Multi_field.h>\n\nusing namespace Gudhi;\nusing namespace Gudhi::persistent_cohomology;\nusing namespace boost::unit_test;\n\ntypedef Simplex_tree<> typeST;\n\nstd::string test_persistence(int min_coefficient, int max_coefficient, double min_persistence) {\n  // file is copied in CMakeLists.txt\n  std::ifstream simplex_tree_stream;\n  simplex_tree_stream.open(\"simplex_tree_file_for_multi_field_unit_test.txt\");\n  typeST st;\n  simplex_tree_stream >> st;\n  simplex_tree_stream.close();\n\n  // Display the Simplex_tree\n  std::clog << \"The complex contains \" << st.num_simplices() << \" simplices\" << \" - dimension= \" << st.dimension()\n      << std::endl;\n\n  // Check\n  BOOST_CHECK(st.num_simplices() == 58);\n  BOOST_CHECK(st.dimension() == 3);\n\n  // Sort the simplices in the order of the filtration\n  st.initialize_filtration();\n\n  // Compute the persistence diagram of the complex\n  Persistent_cohomology<Simplex_tree<>, Multi_field> pcoh(st);\n\n  pcoh.init_coefficients(min_coefficient, max_coefficient); // initializes the coefficient field for homology\n  // Compute the persistent homology of the complex\n  pcoh.compute_persistent_cohomology(min_persistence); // Minimal lifetime of homology feature to be recorded.\n\n  std::ostringstream ossPers;\n  pcoh.output_diagram(ossPers);\n\n  std::string strPers = ossPers.str();\n  return strPers;\n}\n\nvoid test_persistence_with_coeff_field(int min_coefficient, int max_coefficient) {\n  // there are 2 discontinued ensembles \n  std::string value0(\"  0 0.25 inf\");\n  std::string value1(\"  1 0.4 inf\");\n  // And a big hole - cut in 2 pieces after 0.3\n  std::string value2(\"  0 0.2 0.3\");\n\n  // For dim <= 1 =>\n  std::string value3(\"  1 0.25 inf\");\n  std::string value4(\"  2 0.25 inf\");\n  std::string value5(\"  1 0.3 inf\");\n  std::string value6(\"  2 0.3 inf\");\n  std::string value7(\"  2 0.4 inf\");\n\n  std::clog << \"********************************************************************\" << std::endl;\n  std::clog << \"TEST OF PERSISTENT_COHOMOLOGY_MULTI_FIELD MIN_COEFF=\" << min_coefficient << \" MAX_COEFF=\" << max_coefficient << \" MIN_PERS=0\" << std::endl;\n\n  std::string str_persistence = test_persistence(min_coefficient, max_coefficient, 0.0);\n  std::clog << \"str_persistence=\" << str_persistence << std::endl;\n\n  BOOST_CHECK(str_persistence.find(value0) != std::string::npos); // Check found\n  BOOST_CHECK(str_persistence.find(value1) != std::string::npos); // Check found\n  BOOST_CHECK(str_persistence.find(value2) != std::string::npos); // Check found\n\n  if ((min_coefficient < 2) && (max_coefficient < 2)) {\n    BOOST_CHECK(str_persistence.find(value3) != std::string::npos); // Check found\n    BOOST_CHECK(str_persistence.find(value4) != std::string::npos); // Check found\n    BOOST_CHECK(str_persistence.find(value5) != std::string::npos); // Check found\n    BOOST_CHECK(str_persistence.find(value6) != std::string::npos); // Check found\n    BOOST_CHECK(str_persistence.find(value7) != std::string::npos); // Check found\n  } else {\n    BOOST_CHECK(str_persistence.find(value3) == std::string::npos); // Check not found\n    BOOST_CHECK(str_persistence.find(value4) == std::string::npos); // Check not found\n    BOOST_CHECK(str_persistence.find(value5) == std::string::npos); // Check not found\n    BOOST_CHECK(str_persistence.find(value6) == std::string::npos); // Check not found\n    BOOST_CHECK(str_persistence.find(value7) == std::string::npos); // Check not found\n  }\n\n}\n\nBOOST_AUTO_TEST_CASE(persistent_cohomology_multi_field_coeff_0_0) {\n  test_persistence_with_coeff_field(0, 0);\n}\n\nBOOST_AUTO_TEST_CASE(persistent_cohomology_multi_field_coeff_0_1) {\n  test_persistence_with_coeff_field(0, 1);\n}\n\nBOOST_AUTO_TEST_CASE(persistent_cohomology_multi_field_coeff_0_6) {\n  test_persistence_with_coeff_field(0, 6);\n}\n\nBOOST_AUTO_TEST_CASE(persistent_cohomology_multi_field_coeff_1_2) {\n  test_persistence_with_coeff_field(1, 2);\n}\n\nBOOST_AUTO_TEST_CASE(persistent_cohomology_multi_field_coeff_1_3) {\n  test_persistence_with_coeff_field(1, 3);\n}\n\nBOOST_AUTO_TEST_CASE(persistent_cohomology_multi_field_coeff_1_5) {\n  test_persistence_with_coeff_field(1, 5);\n}\n\nBOOST_AUTO_TEST_CASE(persistent_cohomology_multi_field_coeff_2_3) {\n  test_persistence_with_coeff_field(2, 3);\n}\n\nBOOST_AUTO_TEST_CASE(persistent_cohomology_multi_field_coeff_3_4) {\n  test_persistence_with_coeff_field(3, 4);\n}\n", "meta": {"hexsha": "c6c0bfaf25210a5e27d86eca2e74d98941b74e77", "size": 4796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Persistent_cohomology/test/persistent_cohomology_unit_test_multi_field.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T05:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T05:45:06.000Z", "max_issues_repo_path": "src/Persistent_cohomology/test/persistent_cohomology_unit_test_multi_field.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Persistent_cohomology/test/persistent_cohomology_unit_test_multi_field.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.46875, "max_line_length": 155, "alphanum_fraction": 0.7376980817, "num_tokens": 1317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5960173059660279}}
{"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// \u4ee5\u4e0b\u5185\u5bb9\u4e4b\u524d\u90fd\u5df2\u7ecf\u4ecb\u7ecd\u8fc7\u4e86\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/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// \u8fd9\u662f\u552f\u4e00\u4e00\u4e2a\u65b0\u7684\u3002\u6211\u4eec\u5c06\u9700\u8981\u4e00\u4e2a\u5b9a\u4e49\u5728GridTools\u547d\u540d\u7a7a\u95f4\u7684\u5e93\u51fd\u6570\uff0c\u7528\u6765\u8ba1\u7b97\u6700\u5c0f\u7684\u5355\u5143\u683c\u76f4\u5f84\u3002\n\n#include <deal.II/grid/grid_tools.h> \n\n// \u6700\u540e\u4e00\u6b65\u548c\u4ee5\u524d\u6240\u6709\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\nnamespace Step24 \n{ \n  using namespace dealii; \n// @sect3{The \"forward problem\" class template}  \n\n// \u4e3b\u7c7b\u7684\u7b2c\u4e00\u90e8\u5206\u4e0e step-23 \u4e2d\u7684\u5185\u5bb9\u5b8c\u5168\u4e00\u81f4\uff08\u9664\u4e86\u540d\u5b57\uff09\u3002\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// \u4e0b\u9762\u662f\u65b0\u7684\u5185\u5bb9\uff1a\u9996\u5148\uff0c\u6211\u4eec\u9700\u8981\u4ece\u5438\u6536\u8fb9\u754c\u6761\u4ef6\u51fa\u6765\u7684\u90a3\u4e2a\u8fb9\u754c\u8d28\u91cf\u77e9\u9635 $B$ \u3002\u540c\u6837\uff0c\u7531\u4e8e\u8fd9\u6b21\u6211\u4eec\u8003\u8651\u7684\u662f\u4e00\u4e2a\u73b0\u5b9e\u7684\u4ecb\u8d28\uff0c\u6211\u4eec\u5fc5\u987b\u6709\u4e00\u4e2a\u8861\u91cf\u6ce2\u901f\u7684\u6807\u51c6 $c_0$ \uff0c\u5b83\u5c06\u8fdb\u5165\u6240\u6709\u4e0e\u62c9\u666e\u62c9\u65af\u77e9\u9635\uff08\u6211\u4eec\u4ecd\u7136\u5b9a\u4e49\u4e3a $(\\nabla \\phi_i,\\nabla \\phi_j)$ \uff09\u6709\u5173\u7684\u516c\u5f0f\u3002\n\n    SparseMatrix<double> boundary_matrix; \n    const double         wave_speed; \n\n// \u6211\u4eec\u5fc5\u987b\u6ce8\u610f\u7684\u6700\u540e\u4e00\u4ef6\u4e8b\u662f\uff0c\u6211\u4eec\u60f3\u5728\u4e00\u5b9a\u6570\u91cf\u7684\u68c0\u6d4b\u5668\u4f4d\u7f6e\u8bc4\u4f30\u89e3\u51b3\u65b9\u6848\u3002\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u6570\u7ec4\u6765\u4fdd\u5b58\u8fd9\u4e9b\u4f4d\u7f6e\uff0c\u5728\u8fd9\u91cc\u58f0\u660e\u5e76\u5728\u6784\u9020\u51fd\u6570\u4e2d\u586b\u5145\u3002\n\n    std::vector<Point<dim>> detector_locations; \n  }; \n// @sect3{Equation data}  \n\n// \u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u6211\u4eec\u5fc5\u987b\u5b9a\u4e49\u6211\u4eec\u7684\u521d\u59cb\u503c\u3001\u8fb9\u754c\u6761\u4ef6\u548c\u53f3\u624b\u8fb9\u7684\u51fd\u6570\u3002\u8fd9\u6b21\u4e8b\u60c5\u6709\u70b9\u7b80\u5355\uff1a\u6211\u4eec\u8003\u8651\u7684\u662f\u4e00\u4e2a\u7531\u521d\u59cb\u6761\u4ef6\u9a71\u52a8\u7684\u95ee\u9898\uff0c\u6240\u4ee5\u6ca1\u6709\u53f3\u624b\u51fd\u6570\uff08\u5c3d\u7ba1\u4f60\u53ef\u4ee5\u5728 step-23 \u4e2d\u67e5\u627e\uff0c\u770b\u770b\u5982\u4f55\u505a\u5230\u8fd9\u4e00\u70b9\uff09\u3002\u5176\u6b21\uff0c\u6ca1\u6709\u8fb9\u754c\u6761\u4ef6\uff1a\u57df\u7684\u6574\u4e2a\u8fb9\u754c\u7531\u5438\u6536\u6027\u8fb9\u754c\u6761\u4ef6\u7ec4\u6210\u3002\u8fd9\u5c31\u53ea\u5269\u4e0b\u521d\u59cb\u6761\u4ef6\u4e86\uff0c\u8fd9\u91cc\u7684\u4e8b\u60c5\u4e5f\u5f88\u7b80\u5355\uff0c\u56e0\u4e3a\u5bf9\u4e8e\u8fd9\u4e2a\u7279\u6b8a\u7684\u5e94\u7528\uff0c\u53ea\u89c4\u5b9a\u4e86\u538b\u529b\u7684\u975e\u96f6\u521d\u59cb\u6761\u4ef6\uff0c\u800c\u6ca1\u6709\u89c4\u5b9a\u901f\u5ea6\u7684\u975e\u96f6\u521d\u59cb\u6761\u4ef6\uff08\u901f\u5ea6\u5728\u521d\u59cb\u65f6\u95f4\u4e3a\u96f6\uff09\u3002\n\n// \u6240\u4ee5\u8fd9\u5c31\u662f\u6211\u4eec\u6240\u9700\u8981\u7684\uff1a\u4e00\u4e2a\u6307\u5b9a\u538b\u529b\u521d\u59cb\u6761\u4ef6\u7684\u7c7b\u3002\u5728\u672c\u7a0b\u5e8f\u6240\u8003\u8651\u7684\u7269\u7406\u73af\u5883\u4e2d\uff0c\u8fd9\u4e9b\u662f\u5c0f\u7684\u5438\u6536\u5668\uff0c\u6211\u4eec\u5c06\u5176\u5efa\u6a21\u4e3a\u4e00\u7cfb\u5217\u7684\u5c0f\u5706\u5708\uff0c\u6211\u4eec\u5047\u8bbe\u538b\u529b\u76c8\u4f59\u4e3a1\uff0c\u800c\u5176\u4ed6\u5730\u65b9\u6ca1\u6709\u5438\u6536\uff0c\u56e0\u6b64\u6ca1\u6709\u538b\u529b\u76c8\u4f59\u3002\u6211\u4eec\u662f\u8fd9\u6837\u505a\u7684\uff08\u6ce8\u610f\uff0c\u5982\u679c\u6211\u4eec\u60f3\u628a\u8fd9\u4e2a\u7a0b\u5e8f\u6269\u5c55\u5230\u4e0d\u4ec5\u53ef\u4ee5\u7f16\u8bd1\uff0c\u800c\u4e14\u53ef\u4ee5\u8fd0\u884c\uff0c\u6211\u4eec\u5c06\u4e0d\u5f97\u4e0d\u7528\u4e09\u7ef4\u6e90\u7684\u4f4d\u7f6e\u6765\u521d\u59cb\u5316\u6e90\uff09\u3002\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// \u8ba9\u6211\u4eec\u518d\u4ece\u6784\u9020\u51fd\u6570\u5f00\u59cb\u3002\u8bbe\u7f6e\u6210\u5458\u53d8\u91cf\u662f\u5f88\u76f4\u63a5\u7684\u3002\u6211\u4eec\u4f7f\u7528\u77ff\u7269\u6cb9\u7684\u58f0\u6ce2\u901f\u5ea6\uff08\u5355\u4f4d\u4e3a\u6beb\u7c73/\u5fae\u79d2\uff0c\u662f\u5b9e\u9a8c\u6027\u751f\u7269\u533b\u5b66\u6210\u50cf\u4e2d\u7684\u5e38\u7528\u5355\u4f4d\uff09\uff0c\u56e0\u4e3a\u6211\u4eec\u60f3\u548c\u8f93\u51fa\u7684\u8bb8\u591a\u5b9e\u9a8c\u90fd\u662f\u5728\u8fd9\u91cc\u8fdb\u884c\u7684\u3002\u518d\u6b21\u4f7f\u7528Crank-Nicolson\u65b9\u6848\uff0c\u5373theta\u88ab\u8bbe\u5b9a\u4e3a0.5\u3002\u968f\u540e\u9009\u62e9\u65f6\u95f4\u6b65\u957f\u4ee5\u6ee1\u8db3 $k = \\frac hc$ \uff1a\u8fd9\u91cc\u6211\u4eec\u628a\u5b83\u521d\u59cb\u5316\u4e3a\u4e00\u4e2a\u65e0\u6548\u7684\u6570\u5b57\u3002\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// \u6784\u9020\u51fd\u6570\u4e2d\u7684\u7b2c\u4e8c\u4e2a\u4efb\u52a1\u662f\u521d\u59cb\u5316\u5b58\u653e\u68c0\u6d4b\u5668\u4f4d\u7f6e\u7684\u6570\u7ec4\u3002\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u7ed3\u679c\u4e0e\u5b9e\u9a8c\u8fdb\u884c\u4e86\u6bd4\u8f83\uff0c\u5176\u4e2d\u68c0\u6d4b\u5668\u95f4\u8ddd\u7684\u6b65\u957f\u4e3a2.25\u5ea6\uff0c\u5bf9\u5e94160\u4e2a\u68c0\u6d4b\u5668\u4f4d\u7f6e\u3002\u626b\u63cf\u5706\u7684\u534a\u5f84\u88ab\u9009\u4e3a\u4e2d\u5fc3\u548c\u8fb9\u754c\u4e4b\u95f4\u7684\u4e00\u534a\uff0c\u4ee5\u907f\u514d\u4e0d\u5b8c\u5584\u7684\u8fb9\u754c\u6761\u4ef6\u5e26\u6765\u7684\u5269\u4f59\u53cd\u5c04\u7834\u574f\u6211\u4eec\u7684\u6570\u503c\u7ed3\u679c\u3002\n\n// \u7136\u540e\u6309\u987a\u65f6\u9488\u987a\u5e8f\u8ba1\u7b97\u63a2\u6d4b\u5668\u7684\u4f4d\u7f6e\u3002\u8bf7\u6ce8\u610f\uff0c\u4e0b\u9762\u7684\u5185\u5bb9\u5f53\u7136\u53ea\u6709\u5728\u6211\u4eec\u4ee52D\u8ba1\u7b97\u65f6\u624d\u6709\u6548\uff0c\u6211\u4eec\u7528\u4e00\u4e2a\u65ad\u8a00\u6765\u4fdd\u62a4\u8fd9\u4e2a\u6761\u4ef6\u3002\u5982\u679c\u6211\u4eec\u4ee5\u540e\u60f3\u5728\u4e09\u7ef4\u4e2d\u8fd0\u884c\u540c\u6837\u7684\u7a0b\u5e8f\uff0c\u6211\u4eec\u5c06\u4e0d\u5f97\u4e0d\u5728\u8fd9\u91cc\u6dfb\u52a0\u4ee3\u7801\u6765\u521d\u59cb\u5316\u4e09\u7ef4\u4e2d\u7684\u63a2\u6d4b\u5668\u4f4d\u7f6e\u3002\u7531\u4e8e\u65ad\u8a00\u7684\u5b58\u5728\uff0c\u6211\u4eec\u4e0d\u53ef\u80fd\u5fd8\u8bb0\u8fd9\u6837\u505a\u3002\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// \u4e0b\u9762\u7684\u7cfb\u7edf\u51e0\u4e4e\u5c31\u662f\u6211\u4eec\u5728  step-23  \u4e2d\u5df2\u7ecf\u505a\u8fc7\u7684\uff0c\u4f46\u6709\u4e24\u4e2a\u91cd\u8981\u7684\u533a\u522b\u3002\u9996\u5148\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u539f\u70b9\u5468\u56f4\u521b\u5efa\u4e00\u4e2a\u534a\u5f84\u4e3a1\u7684\u5706\u5f62\uff08\u6216\u7403\u5f62\uff09\u7f51\u683c\u3002\u8fd9\u5e76\u4e0d\u65b0\u9c9c\uff1a\u6211\u4eec\u4e4b\u524d\u5728 step-6 \u548c step-10 \u4e2d\u5df2\u7ecf\u8fd9\u6837\u505a\u4e86\uff0c\u5728\u90a3\u91cc\u6211\u4eec\u8fd8\u89e3\u91ca\u4e86PolarManifold\u6216SphericalManifold\u5bf9\u8c61\u5982\u4f55\u5728\u7ec6\u5316\u5355\u5143\u65f6\u5c06\u65b0\u70b9\u653e\u5728\u540c\u5fc3\u5706\u4e0a\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u4e5f\u5c06\u4f7f\u7528\u5b83\u3002\n\n// \u6211\u4eec\u5fc5\u987b\u786e\u4fdd\u7684\u4e00\u70b9\u662f\uff0c\u65f6\u95f4\u6b65\u957f\u6ee1\u8db3  step-23  \u7684\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684 CFL \u6761\u4ef6\u3002\u5728\u90a3\u4e2a\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u901a\u8fc7\u8bbe\u7f6e\u4e00\u4e2a\u4e0e\u7f51\u683c\u5bbd\u5ea6\u76f8\u5339\u914d\u7684\u65f6\u95f4\u6b65\u957f\u6765\u786e\u4fdd\u8fd9\u4e00\u70b9\uff0c\u4f46\u662f\u8fd9\u5f88\u5bb9\u6613\u51fa\u9519\uff0c\u56e0\u4e3a\u5982\u679c\u6211\u4eec\u518d\u7ec6\u5316\u4e00\u6b21\u7f51\u683c\uff0c\u6211\u4eec\u4e5f\u5fc5\u987b\u786e\u4fdd\u65f6\u95f4\u6b65\u957f\u6709\u6240\u6539\u53d8\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u81ea\u52a8\u505a\u5230\u4e86\u8fd9\u4e00\u70b9\uff1a\u6211\u4eec\u5411\u4e00\u4e2a\u5e93\u51fd\u6570\u8be2\u95ee\u4efb\u4f55\u5355\u5143\u7684\u6700\u5c0f\u76f4\u5f84\u3002\u7136\u540e\u6211\u4eec\u8bbe\u7f6e $k=\\frac h{c_0}$  \u3002\u552f\u4e00\u7684\u95ee\u9898\u662f\uff1a $h$ \u5230\u5e95\u662f\u4ec0\u4e48\uff1f\u5173\u952e\u662f\uff0c\u5bf9\u4e8e\u6ce2\u6d6a\u65b9\u7a0b\u6765\u8bf4\uff0c\u8fd9\u4e2a\u95ee\u9898\u786e\u5b9e\u6ca1\u6709\u597d\u7684\u7406\u8bba\u3002\u4f17\u6240\u5468\u77e5\uff0c\u5bf9\u4e8e\u7531\u77e9\u5f62\u7ec4\u6210\u7684\u5747\u5300\u7ec6\u5316\u7f51\u683c\uff0c $h$ \u662f\u6700\u5c0f\u8fb9\u957f\u3002\u4f46\u5bf9\u4e8e\u4e00\u822c\u56db\u8fb9\u5f62\u7684\u7f51\u683c\uff0c\u786e\u5207\u7684\u5173\u7cfb\u4f3c\u4e4e\u662f\u672a\u77e5\u7684\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u4e0d\u77e5\u9053\u5355\u5143\u683c\u7684\u4ec0\u4e48\u5c5e\u6027\u4e0eCFL\u6761\u4ef6\u6709\u5173\u3002\u95ee\u9898\u662f\uff0cCFL\u6761\u4ef6\u6765\u81ea\u4e8e\u5bf9\u62c9\u666e\u62c9\u65af\u77e9\u9635\u6700\u5c0f\u7279\u5f81\u503c\u7684\u4e86\u89e3\uff0c\u800c\u8fd9\u53ea\u80fd\u5bf9\u7b80\u5355\u7ed3\u6784\u7684\u7f51\u683c\u8fdb\u884c\u5206\u6790\u8ba1\u7b97\u3002\n\n// \u8fd9\u4e00\u5207\u7684\u7ed3\u679c\u662f\uff0c\u6211\u4eec\u5e76\u4e0d\u5341\u5206\u786e\u5b9a\u6211\u4eec\u5e94\u8be5\u5bf9 $h$ \u91c7\u53d6\u4ec0\u4e48\u63aa\u65bd\u3002\u51fd\u6570 GridTools::minimal_cell_diameter \u8ba1\u7b97\u4e86\u6240\u6709\u5355\u5143\u7684\u6700\u5c0f\u76f4\u5f84\u3002\u5982\u679c\u5355\u5143\u683c\u90fd\u662f\u6b63\u65b9\u5f62\u6216\u7acb\u65b9\u4f53\uff0c\u90a3\u4e48\u6700\u5c0f\u8fb9\u957f\u5c31\u662f\u6700\u5c0f\u76f4\u5f84\u9664\u4ee5 <code>std::sqrt(dim)</code>  \u3002\u6211\u4eec\u7b80\u5355\u5730\u5c06\u6b64\u6982\u62ec\u4e3a\u975e\u5747\u5300\u7f51\u683c\u7684\u60c5\u51b5\uff0c\u6ca1\u6709\u7406\u8bba\u4e0a\u7684\u7406\u7531\u3002\n\n// \u552f\u4e00\u7684\u5176\u4ed6\u91cd\u5927\u53d8\u5316\u662f\u6211\u4eec\u9700\u8981\u5efa\u7acb\u8fb9\u754c\u8d28\u91cf\u77e9\u9635\u3002\u6211\u4eec\u5c06\u5728\u4e0b\u6587\u4e2d\u8fdb\u4e00\u6b65\u8bc4\u8bba\u8fd9\u4e2a\u95ee\u9898\u3002\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// \u5982\u524d\u6240\u8ff0\uff0c\u4e0e step-23 \u7684\u7b2c\u4e8c\u4e2a\u533a\u522b\u662f\uff0c\u6211\u4eec\u9700\u8981\u5efa\u7acb\u4ece\u5438\u6536\u6027\u8fb9\u754c\u6761\u4ef6\u4e2d\u751f\u957f\u51fa\u6765\u7684\u8fb9\u754c\u8d28\u91cf\u77e9\u9635\u3002\n\n// \u7b2c\u4e00\u4e2a\u89c2\u5bdf\u7ed3\u679c\u662f\uff0c\u8fd9\u4e2a\u77e9\u9635\u6bd4\u5e38\u89c4\u8d28\u91cf\u77e9\u9635\u8981\u7a00\u758f\u5f97\u591a\uff0c\u56e0\u4e3a\u6ca1\u6709\u4e00\u4e2a\u5177\u6709\u7eaf\u5185\u90e8\u652f\u6301\u7684\u5f62\u72b6\u51fd\u6570\u5bf9\u8fd9\u4e2a\u77e9\u9635\u6709\u8d21\u732e\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u53ef\u4ee5\u6839\u636e\u8fd9\u79cd\u60c5\u51b5\u4f18\u5316\u5b58\u50a8\u6a21\u5f0f\uff0c\u5efa\u7acb\u7b2c\u4e8c\u4e2a\u7a00\u758f\u6a21\u5f0f\uff0c\u53ea\u5305\u542b\u6211\u4eec\u9700\u8981\u7684\u975e\u96f6\u9879\u3002\u8fd9\u91cc\u6709\u4e00\u4e2a\u6743\u8861\uff1a\u9996\u5148\uff0c\u6211\u4eec\u5fc5\u987b\u8981\u6709\u7b2c\u4e8c\u4e2a\u7a00\u758f\u6a21\u5f0f\u5bf9\u8c61\uff0c\u6240\u4ee5\u8fd9\u9700\u8981\u82b1\u8d39\u5185\u5b58\u3002\u5176\u6b21\uff0c\u4e0e\u8be5\u7a00\u758f\u6027\u6a21\u5f0f\u76f8\u8fde\u7684\u77e9\u9635\u5c06\u66f4\u5c0f\uff0c\u56e0\u6b64\u9700\u8981\u66f4\u5c11\u7684\u5185\u5b58\uff1b\u7528\u5b83\u8fdb\u884c\u77e9\u9635-\u5411\u91cf\u4e58\u6cd5\u4e5f\u4f1a\u66f4\u5feb\u3002\u7136\u800c\uff0c\u6700\u540e\u4e00\u4e2a\u8bba\u70b9\u662f\u63d0\u793a\u89c4\u6a21\u7684\u8bba\u70b9\uff1a\u6211\u4eec\u4e3b\u8981\u611f\u5174\u8da3\u7684\u4e0d\u662f\u5355\u72ec\u5bf9\u8fb9\u754c\u77e9\u9635\u8fdb\u884c\u77e9\u9635-\u5411\u91cf\u8fd0\u7b97\uff08\u5c3d\u7ba1\u6211\u4eec\u9700\u8981\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u5bf9\u53f3\u4fa7\u5411\u91cf\u8fdb\u884c\u4e00\u6b21\u8fd0\u7b97\uff09\uff0c\u800c\u662f\u4e3b\u8981\u5e0c\u671b\u5c06\u5176\u4e0e\u4e24\u4e2a\u65b9\u7a0b\u4e2d\u7684\u7b2c\u4e00\u4e2a\u65b9\u7a0b\u4f7f\u7528\u7684\u5176\u4ed6\u77e9\u9635\u76f8\u52a0\uff0c\u56e0\u4e3a\u8fd9\u662fCG\u65b9\u6cd5\u6bcf\u4e2a\u8fed\u4ee3\u90fd\u8981\u4e0e\u4e4b\u76f8\u4e58\u7684\uff0c\u5373\u660e\u663e\u66f4\u9891\u7e41\u3002\u73b0\u5728\u7684\u60c5\u51b5\u662f\uff0c SparseMatrix::add \u7c7b\u5141\u8bb8\u5c06\u4e00\u4e2a\u77e9\u9635\u6dfb\u52a0\u5230\u53e6\u4e00\u4e2a\u77e9\u9635\u4e2d\uff0c\u4f46\u524d\u63d0\u662f\u5b83\u4eec\u4f7f\u7528\u76f8\u540c\u7684\u7a00\u758f\u6a21\u5f0f\uff08\u539f\u56e0\u662f\u6211\u4eec\u4e0d\u80fd\u5728\u7a00\u758f\u6a21\u5f0f\u521b\u5efa\u540e\u5411\u77e9\u9635\u6dfb\u52a0\u975e\u96f6\u6761\u76ee\uff0c\u6240\u4ee5\u6211\u4eec\u53ea\u662f\u8981\u6c42\u8fd9\u4e24\u4e2a\u77e9\u9635\u5177\u6709\u76f8\u540c\u7684\u7a00\u758f\u6a21\u5f0f\uff09\u3002\n\n// \u6240\u4ee5\uff0c\u6211\u4eec\u5c31\u7528\u8fd9\u4e2a\u65b9\u6cd5\u5427\u3002\n\n    boundary_matrix.reinit(sparsity_pattern); \n\n// \u7b2c\u4e8c\u4ef6\u8981\u505a\u7684\u4e8b\u662f\u5b9e\u9645\u5efa\u7acb\u77e9\u9635\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u9700\u8981\u5bf9\u5355\u5143\u683c\u7684\u9762\u8fdb\u884c\u79ef\u5206\uff0c\u6240\u4ee5\u9996\u5148\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u80fd\u5728 <code>dim-1</code> \u7ef4\u5bf9\u8c61\u4e0a\u5de5\u4f5c\u7684\u6b63\u4ea4\u5bf9\u8c61\u3002\u5176\u6b21\uff0cFEValues\u7684\u53d8\u4f53FEFaceValues\uff0c\u6b63\u5982\u5b83\u7684\u540d\u5b57\u6240\u6697\u793a\u7684\uff0c\u5b83\u53ef\u4ee5\u5728\u9762\u4e0a\u5de5\u4f5c\u3002\u6700\u540e\uff0c\u5176\u4ed6\u7684\u53d8\u91cf\u662f\u7ec4\u88c5\u673a\u5668\u7684\u4e00\u90e8\u5206\u3002\u6240\u6709\u8fd9\u4e9b\u6211\u4eec\u90fd\u653e\u5728\u5927\u62ec\u53f7\u91cc\uff0c\u4ee5\u4fbf\u5c06\u8fd9\u4e9b\u53d8\u91cf\u7684\u8303\u56f4\u9650\u5236\u5728\u6211\u4eec\u771f\u6b63\u9700\u8981\u5b83\u4eec\u7684\u5730\u65b9\u3002\n//\u7136\u540e\n//\u7ec4\u88c5\u77e9\u9635\u7684\u5b9e\u9645\u884c\u4e3a\u662f\u76f8\u5f53\u76f4\u63a5\u7684\uff1a\u6211\u4eec\u5728\u6240\u6709\u5355\u5143\u4e2d\u5faa\u73af\uff0c\u5728\u6bcf\u4e2a\u5355\u5143\u7684\u6240\u6709\u9762\u4e2d\u5faa\u73af\uff0c\u7136\u540e\u53ea\u5728\u7279\u5b9a\u7684\u9762\u4f4d\u4e8e\u57df\u7684\u8fb9\u754c\u65f6\u505a\u4e00\u4e9b\u4e8b\u60c5\u3002\u50cf\u8fd9\u6837\u3002\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// \u4e0b\u9762\u4e24\u4e2a\u51fd\u6570\uff0c\u89e3\u51b3\u538b\u529b\u548c\u901f\u5ea6\u53d8\u91cf\u7684\u7ebf\u6027\u7cfb\u7edf\uff0c\u51e0\u4e4e\u662f\u9010\u5b57\u9010\u53e5\u5730\u4ece step-23 \u4e2d\u63d0\u53d6\u7684\uff08\u9664\u4e86\u4e3b\u53d8\u91cf\u7684\u540d\u5b57\u4ece $u$ \u6539\u4e3a $p$ \uff09\u3002\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// \u8fd9\u91cc\u4e5f\u662f\u5982\u6b64\uff1a\u8be5\u51fd\u6570\u6765\u81ea  step-23  \u3002\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// \u8fd9\u4e2a\u505a\u5927\u90e8\u5206\u5de5\u4f5c\u7684\u51fd\u6570\u53c8\u548c step-23 \u4e2d\u7684\u5dee\u4e0d\u591a\uff0c\u5c3d\u7ba1\u6211\u4eec\u901a\u8fc7\u4f7f\u7528\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\u5411\u91cfG1\u548cG2\u4f7f\u4e8b\u60c5\u53d8\u5f97\u66f4\u52a0\u6e05\u6670\u3002\u4e0e\u7a0b\u5e8f\u7684\u6574\u4f53\u5185\u5b58\u6d88\u8017\u76f8\u6bd4\uff0c\u5f15\u5165\u51e0\u4e2a\u4e34\u65f6\u5411\u91cf\u5e76\u6ca1\u6709\u4ec0\u4e48\u574f\u5904\u3002\n\n// \u8fd9\u4e2a\u51fd\u6570\u552f\u4e00\u7684\u53d8\u5316\u662f\uff1a\u9996\u5148\uff0c\u6211\u4eec\u4e0d\u5fc5\u4e3a\u901f\u5ea6 $v$ \u9884\u6d4b\u521d\u59cb\u503c\uff0c\u56e0\u4e3a\u6211\u4eec\u77e5\u9053\u5b83\u662f\u96f6\u3002\u5176\u6b21\uff0c\u6211\u4eec\u5728\u6784\u9020\u51fd\u6570\u4e2d\u8ba1\u7b97\u7684\u68c0\u6d4b\u5668\u4f4d\u7f6e\u4e0a\u8bc4\u4f30\u89e3\u51b3\u65b9\u6848\u3002\u8fd9\u662f\u7528 VectorTools::point_value \u51fd\u6570\u5b8c\u6210\u7684\u3002\u7136\u540e\uff0c\u8fd9\u4e9b\u503c\u88ab\u5199\u5165\u6211\u4eec\u5728\u51fd\u6570\u5f00\u59cb\u65f6\u6253\u5f00\u7684\u4e00\u4e2a\u6587\u4ef6\u4e2d\u3002\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// \u5269\u4e0b\u7684\u5c31\u662f\u7a0b\u5e8f\u7684\u4e3b\u8981\u529f\u80fd\u4e86\u3002\u8fd9\u91cc\u6ca1\u6709\u4ec0\u4e48\u662f\u5728\u524d\u9762\u51e0\u4e2a\u7a0b\u5e8f\u4e2d\u6ca1\u6709\u5c55\u793a\u8fc7\u7684\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace 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": "#include <boost/simd/meta/prev_power_of_2.hpp>\n#include <boost/mpl/comparison.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/int.hpp>\n\nint main()\n{\n  using boost::mpl::int_;\n\n  typedef boost::simd::meta::prev_power_of_2_c<0    >::type  a0;\n  typedef boost::simd::meta::prev_power_of_2_c<9    >::type  a9;\n  typedef boost::simd::meta::prev_power_of_2_c<1055 >::type  a1055;\n\n  BOOST_MPL_ASSERT(( boost::mpl::equal_to<a0    , int_<0>     >::type ));\n  BOOST_MPL_ASSERT(( boost::mpl::equal_to<a9    , int_<8>     >::type ));\n  BOOST_MPL_ASSERT(( boost::mpl::equal_to<a1055 , int_<1024>  >::type ));\n}\n", "meta": {"hexsha": "ca27421e7ce31fdbc8c923251570501b91f59b11", "size": 608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/examples/meta/prev_power_of_2_c.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/sdk/examples/meta/prev_power_of_2_c.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/sdk/examples/meta/prev_power_of_2_c.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 33.7777777778, "max_line_length": 73, "alphanum_fraction": 0.6710526316, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5959827180457904}}
{"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 \u00a3100,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 \"cryptonote_config.h\"\n#include \"common/exp2.h\"\n#include \"int-util.h\"\n#include <vector>\n#include <boost/lexical_cast.hpp>\n\n#include \"service_node_rules.h\"\n\nnamespace service_nodes {\n\n\n\tuint64_t get_staking_requirement(cryptonote::network_type m_nettype, uint64_t height)\n\t{\n\t\tif (m_nettype != cryptonote::MAINNET)\n\t\t\treturn COIN * 100;\n\n\t\tuint64_t hardfork_height = m_nettype == cryptonote::MAINNET ? 106950 : 581 /* stagenet */;\n\t\tif (height < hardfork_height) height = hardfork_height;\n\n\t\tuint64_t height_adjusted = height - hardfork_height;\n\t\tuint64_t base = 0, variable = 0;\n\t\tif (height >= 352846)\n\t\t{\n\t\t\tbase = 70000 * COIN;\n\t\t\tvariable = (20000.0 * COIN) / triton::exp2(height_adjusted / 356446.0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbase = 10000 * COIN;\n\t\t\tvariable = (30000.0 * COIN) / triton::exp2(height_adjusted / 129600.0);\n\t\t}\n\n\t\tuint64_t result = base + variable;\n\t\treturn result;\n\t}\n\n\tuint64_t portions_to_amount(uint64_t portions, uint64_t staking_requirement)\n\t{\n\t\tuint64_t hi, lo, resulthi, resultlo;\n\t\tlo = mul128(staking_requirement, portions, &hi);\n\t\tdiv128_64(hi, lo, STAKING_PORTIONS, &resulthi, &resultlo);\n\t\treturn resultlo;\n\t}\n\n\tbool check_service_node_portions(const std::vector<uint64_t>& portions, const uint64_t min_portions)\n\t{\n\t\tuint64_t portions_left = STAKING_PORTIONS;\n\n\t\tfor (const auto portion : portions) {\n\t\t\tconst uint64_t min_portions = std::min(portions_left, min_portions);\n\t\t\tif (portion < min_portions || portion > portions_left) return false;\n\t\t\tportions_left -= portion;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tuint64_t get_portions_to_make_amount(uint64_t staking_requirement, uint64_t amount)\n\t{\n\t\tuint64_t lo, hi, resulthi, resultlo;\n\t\tlo = mul128(amount, STAKING_PORTIONS, &hi);\n\t\tif (lo > UINT64_MAX - (staking_requirement - 1))\n\t\t\thi++;\n\t\tlo += staking_requirement-1;\n\t\tdiv128_64(hi, lo, staking_requirement, &resulthi, &resultlo);\n\t\treturn resultlo;\n\t}\n\n\tstatic bool get_portions_from_percent(double cur_percent, uint64_t& portions) {\n\n\t\tif(cur_percent < 0.0 || cur_percent > 100.0) return false;\n\n\t\t// Fix for truncation issue when operator cut = 100 for a pool Service Node.\n\t\tif (cur_percent == 100.0)\n\t\t{\n\t\t\tportions = STAKING_PORTIONS;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tportions = (cur_percent / 100.0) * STAKING_PORTIONS;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool get_portions_from_percent_str(std::string cut_str, uint64_t& portions) {\n\n\t\tif(!cut_str.empty() && cut_str.back() == '%')\n\t\t{\n\t\tcut_str.pop_back();\n\t\t}\n\n\t\tdouble cut_percent;\n\t\ttry\n\t\t{\n\t\tcut_percent = boost::lexical_cast<double>(cut_str);\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\treturn false;\n\t\t}\n\n\t\treturn get_portions_from_percent(cut_percent, portions);\n\t}\n\n}\n", "meta": {"hexsha": "d52e4db8c126134940bc6b7a56d3f0285a6c4bde", "size": 2619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cryptonote_core/service_node_rules.cpp", "max_stars_repo_name": "kurohi/Equilibria", "max_stars_repo_head_hexsha": "3fff9d123ec83308e756ba6288f12ba016458bd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-01-04T08:46:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:51:10.000Z", "max_issues_repo_path": "src/cryptonote_core/service_node_rules.cpp", "max_issues_repo_name": "kurohi/Equilibria", "max_issues_repo_head_hexsha": "3fff9d123ec83308e756ba6288f12ba016458bd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T14:36:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T19:52:48.000Z", "max_forks_repo_path": "src/cryptonote_core/service_node_rules.cpp", "max_forks_repo_name": "kurohi/Equilibria", "max_forks_repo_head_hexsha": "3fff9d123ec83308e756ba6288f12ba016458bd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2019-12-04T08:26:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T18:21:01.000Z", "avg_line_length": 24.476635514, "max_line_length": 101, "alphanum_fraction": 0.7067583047, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.5959635588270896}}
{"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": "#ifndef __PICSAR_MULTIPHYSICS_SPECIAL_FUNCTIONS__\n#define __PICSAR_MULTIPHYSICS_SPECIAL_FUNCTIONS__\n\n//This .hpp file is an extremely thin wrapper around special functions\n//(Bessel functions for now) defined either in the STL (if C++17 is available)\n//or in Boost library as a fallback.\n\n//TODO: should we foresee a flag FORCE_USE_BOOST ?\n\n//Set build option for the Bessel functions.\n// 1) from STL (if C++ version > 14)\n// 2) from Boost library\n\n#include <limits>\n\n#if __cplusplus > 201402L\n    #define PXRMP_SPECFUNC_WITH_CXX17\n    #include <cmath>\n#else\n    #define PXRMP_SPECFUNC_WITH_BOOST\n    #include <boost/math/special_functions/bessel.hpp>\n#endif\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        //For the moment we need just modified Bessel functions of the\n        //second kind.\n        //Different combinations of argument types can be accepted\n        //(e.g. double + double or double + float).\n    #ifdef PXRMP_SPECFUNC_WITH_CXX17\n        template<typename _REAL_ARG1, typename _REAL_ARG2>\n        auto k_v(_REAL_ARG1 v, _REAL_ARG2 x);\n    #elif defined(PXRMP_SPECFUNC_WITH_BOOST)\n        template<typename _REAL_ARG1, typename _REAL_ARG2>\n        constexpr auto k_v(_REAL_ARG1 v, _REAL_ARG2 x)\n        -> decltype(boost::math::cyl_bessel_k(v, x));\n    #endif\n\n    }\n}\n\n\n//############################################### Implementation\n\n\n#ifdef PXRMP_SPECFUNC_WITH_CXX17\n\ntemplate<typename _REAL_ARG1, typename _REAL_ARG2>\nauto picsar::multi_physics::k_v(_REAL_ARG1 v, _REAL_ARG2 x)\n{\n    return std::cyl_bessel_k(v, x);\n}\n\n#elif defined(PXRMP_SPECFUNC_WITH_BOOST)\n\ntemplate<typename _REAL_ARG1, typename _REAL_ARG2>\nconstexpr auto picsar::multi_physics::k_v(_REAL_ARG1 v, _REAL_ARG2 x)\n->decltype(boost::math::cyl_bessel_k(v, x))\n{\n    return boost::math::cyl_bessel_k(v, x);;\n}\n\n#endif\n\n#endif //__PICSAR_MULTIPHYSICS_SPECIAL_FUNCTIONS__\n", "meta": {"hexsha": "eec1124d4c543b3d60bd8cb4d74538f76173ddf3", "size": 2013, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED/src/special_functions.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/special_functions.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/special_functions.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.9583333333, "max_line_length": 78, "alphanum_fraction": 0.7034277198, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5959635496069594}}
{"text": "// HEADER\n#include <path_follower/controller/robotcontroller_kinematic_SLP.h>\n\n// THIRD PARTY\n#include <visualization_msgs/MarkerArray.h>\n\n// PROJECT\n#include <path_follower/parameters/path_follower_parameters.h>\n#include <path_follower/utils/cubic_spline_interpolation.h>\n#include <cslibs_navigation_utilities/MathHelper.h>\n#include <path_follower/utils/pose_tracker.h>\n#include <path_follower/utils/visualizer.h>\n\n// SYSTEM\n#include <cmath>\n#include <deque>\n#include <boost/algorithm/clamp.hpp>\n\n\n#include <path_follower/factory/controller_factory.h>\n\nREGISTER_ROBOT_CONTROLLER(RobotController_Kinematic_SLP, kinematic_SLP, default_collision_avoider);\n\nusing namespace Eigen;\n\n\nRobotController_Kinematic_SLP::RobotController_Kinematic_SLP():\n    RobotController(),\n    cmd_(this),\n    vn_(0),\n    delta_(0),\n    Ts_(0.02),\n    ind_(0),\n    xe_(0),\n    ye_(0)\n{\n\n}\n\nvoid RobotController_Kinematic_SLP::stopMotion()\n{\n\n    cmd_.speed = 0;\n    cmd_.direction_angle = 0;\n    cmd_.rotation = 0;\n\n    MoveCommand mcmd = cmd_;\n    publishMoveCommand(mcmd);\n}\n\nvoid RobotController_Kinematic_SLP::initialize()\n{\n    RobotController::initialize();\n\n    //reset the index of the current point on the path\n    ind_ = 0;\n\n    // desired velocity\n    vn_ = std::min(PathFollowerParameters::getInstance()->max_velocity(), velocity_);\n    ROS_DEBUG_STREAM(\"velocity_: \" << velocity_ << \", vn: \" << vn_);\n}\n\nvoid RobotController_Kinematic_SLP::start()\n{\n\n}\n\nvoid RobotController_Kinematic_SLP::reset()\n{\n    RobotController::reset();\n}\n\nvoid RobotController_Kinematic_SLP::setPath(Path::Ptr path)\n{\n    RobotController::setPath(path);\n}\n\nRobotController::MoveCommandStatus RobotController_Kinematic_SLP::computeMoveCommand(MoveCommand *cmd)\n{\n    // omni drive can rotate.\n    *cmd = MoveCommand(true);\n\n    if(path_interpol.n() < 2) {\n        ROS_ERROR(\"[Line] path is too short (N = %d)\", (int) path_interpol.n());\n\n        stopMotion();\n        return MoveCommandStatus::REACHED_GOAL;\n    }\n\n\n    /// get the pose as pose(0) = x, pose(1) = y, pose(2) = theta\n    Eigen::Vector3d current_pose = pose_tracker_->getRobotPose();\n\n    double x_meas = current_pose[0];\n    double y_meas = current_pose[1];\n    double theta_meas = current_pose[2];\n    ///***///\n\n\n    RobotController::findOrthogonalProjection();\n\n    if(RobotController::isGoalReached(cmd)){\n       return RobotController::MoveCommandStatus::REACHED_GOAL;\n    }\n\n\n    ///Compute the control for the current point on the path\n\n    //robot direction angle in path coordinates\n    double theta_e = MathHelper::AngleDelta(path_interpol.theta_p(ind_), theta_meas);\n\n    //robot position vector module\n    double r = hypot(x_meas - path_interpol.p(ind_), y_meas - path_interpol.q(ind_));\n\n    //robot position vector angle in world coordinates\n    double theta_r = atan2(y_meas - path_interpol.q(ind_), x_meas - path_interpol.p(ind_));\n\n    //robot position vector angle in path coordinates\n    double delta_theta = MathHelper::AngleDelta(path_interpol.theta_p(ind_), theta_r);\n\n    //current robot position in path coordinates\n    xe_ = r * cos(delta_theta);\n    ye_ = r * sin(delta_theta);\n\n    ///***///\n\n\n    ///Check the driving direction, and set the complementary angle in path coordinates, if driving backwards\n\n    if (getDirSign() < 0.0) {\n        theta_e = MathHelper::NormalizeAngle(M_PI + theta_e);\n        ROS_WARN_THROTTLE(1, \"Driving backwards...\");\n    }\n\n    ///***///\n\n\n    ///Compute the delta_ and its derivative\n\n    double delta_old = delta_;\n\n    delta_ = MathHelper::AngleClamp(-getDirSign()*opt_.theta_a()*tanh(ye_));\n\n    double delta_prim = (delta_ - delta_old)/Ts_;\n    ///***///\n\n\n    ///Lyapunov-curvature speed control\n\n    //Lyapunov function as a measure of the path following error\n    double v = vn_;\n    double V1 = 0.5*(std::pow(xe_,2) + std::pow(ye_,2)) + (0.5/opt_.gamma())*std::pow((theta_e - delta_),2);\n\n    //use v/2 as the minimum speed, and allow larger values when the error is small\n    if (V1 >= opt_.epsilon()) v = 0.5*v;\n\n    else if (V1 < opt_.epsilon()) v = v/(1 + opt_.b()*std::abs(path_interpol.curvature(ind_)));\n\n    ///***///\n\n\n    ///Compute the next point on the path\n\n    double s_old = path_interpol.s_new();\n\n    //calculate the speed of the \"virtual vehicle\"\n    double s_prim_tmp = v * cos(theta_e) + opt_.k1() * xe_;\n    path_interpol.set_s_prim(s_prim_tmp > 0 ? s_prim_tmp : 0);\n\n    //approximate the first derivative and calculate the next point\n    double s_temp = Ts_*path_interpol.s_prim() + s_old;\n    path_interpol.set_s_new(s_temp > 0 ? s_temp : 0);\n\n    ///***///\n\n\n    ///Direction control\n\n    cmd_.direction_angle = 0;\n\n    //omega_m = theta_e_prim + curv*s_prim\n    double omega_m = delta_prim - opt_.gamma()*ye_*v*(sin(theta_e) - sin(delta_))\n            /(theta_e - delta_) - opt_.k2()*(theta_e - delta_) + path_interpol.curvature(ind_)*path_interpol.s_prim();\n\n\n    omega_m = boost::algorithm::clamp(omega_m, -opt_.max_angular_velocity(), opt_.max_angular_velocity());\n    cmd_.rotation = omega_m;\n\n    ///***///\n\n    ///Speed control\n\n    double exp_factor = RobotController::exponentialSpeedControl();\n    v = v * exp_factor;\n\n    cmd_.speed = getDirSign()*std::max((double)PathFollowerParameters::getInstance()->min_velocity(), fabs(v));\n\n    ///***///\n\n\n\n    ///plot the moving reference frame together with position vector and error components\n\n    if (visualizer_->MarrayhasSubscriber()) {\n        visualizer_->drawFrenetSerretFrame(getFixedFrame(), 0, current_pose, xe_, ye_, path_interpol.p(ind_),\n                                           path_interpol.q(ind_), path_interpol.theta_p(ind_));\n    }\n\n    ///***///\n\n\n    ///Compute the index of the new point\n\n    double s_diff = std::numeric_limits<double>::max();\n    uint old_ind = ind_;\n\n    for (unsigned int i = old_ind; i < path_interpol.n(); i++){\n\n        double s_diff_curr = std::abs(path_interpol.s_new() - path_interpol.s(i));\n\n        if(s_diff_curr < s_diff){\n\n            s_diff = s_diff_curr;\n            ind_ = i;\n\n        }\n\n    }\n\n    if(old_ind != ind_) {\n        path_->fireNextWaypointCallback();\n    }\n\n    ///***///\n\n\n    if (visualizer_->hasSubscriber()) {\n        visualizer_->drawSteeringArrow(pose_tracker_->getFixedFrameId(), 1, pose_tracker_->getRobotPoseMsg(), cmd_.direction_angle, 0.2, 1.0, 0.2);\n    }\n\n    ///***///\n\n    *cmd = cmd_;\n\n    return MoveCommandStatus::OKAY;\n}\n\nvoid RobotController_Kinematic_SLP::publishMoveCommand(const MoveCommand &cmd) const\n{\n    geometry_msgs::Twist msg;\n    msg.linear.x  = cmd.getVelocity();\n    msg.linear.y  = 0;\n    msg.angular.z = cmd.getRotationalVelocity();\n\n    cmd_pub_.publish(msg);\n}\n", "meta": {"hexsha": "f6b4d06d16ff3e4b1562eea93248684c60aca272", "size": 6652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "path_follower/src/controller/robotcontroller_kinematic_SLP.cpp", "max_stars_repo_name": "cyy1991/gerona", "max_stars_repo_head_hexsha": "1860158f082e3f5e0dd1418dcb9d2fa43a5aa191", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "path_follower/src/controller/robotcontroller_kinematic_SLP.cpp", "max_issues_repo_name": "cyy1991/gerona", "max_issues_repo_head_hexsha": "1860158f082e3f5e0dd1418dcb9d2fa43a5aa191", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_follower/src/controller/robotcontroller_kinematic_SLP.cpp", "max_forks_repo_name": "cyy1991/gerona", "max_forks_repo_head_hexsha": "1860158f082e3f5e0dd1418dcb9d2fa43a5aa191", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T02:24:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T02:24:17.000Z", "avg_line_length": 25.8832684825, "max_line_length": 147, "alphanum_fraction": 0.6686710764, "num_tokens": 1739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5959635487766579}}
{"text": "#include <crave/ConstrainedRandom.hpp>\n#include <vector>\n#include <boost/timer.hpp>\n\nusing crave::rand_obj;\nusing crave::randv;\nusing crave::inside;\n\nclass sudoku : public rand_obj {\npublic:\n  randv<short> field[9][9];\n\n\tsudoku(rand_obj* parent = 0) : rand_obj(parent) {\n    short numbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n\t\tfor (int i = 0; i < 9; i++)\n\t\t\tfor (int j = 0; j < 9; j++)\n        constraint( inside(field[i][j](), numbers) );\n\n\t\tfor (int i = 0; i < 9; i++)\n\t\t\tfor (int j = 0; j < 9; j++)\n\t\t\t\tfor (int k = j + 1; k < 9; k++)\n         \tconstraint( field[i][j]() != field[i][k]() );\n\n\t\tfor (int j = 0; j < 9; j++)\n\t\t\tfor (int i = 0; i < 9; i++)\n\t\t\t\tfor (int k = i + 1; k < 9; k++)\n         \tconstraint( field[i][j]() != field[k][j]() );\n\n\t\tfor (int i = 0; i < 9; i++)\n\t\t\tfor (int j = 0; j < 9; j++)\n\t\t\t\tconstraint\n          ( field[i][j]() != field[(i + 1) % 3 + i - (i % 3)][ j                       ]() )\n          ( field[i][j]() != field[(i + 2) % 3 + i - (i % 3)][ j                       ]() )\n\n          ( field[i][j]() != field[ i                       ][(j + 1) % 3 + j - (j % 3)]() )\n          ( field[i][j]() != field[(i + 1) % 3 + i - (i % 3)][(j + 1) % 3 + j - (j % 3)]() )\n          ( field[i][j]() != field[(i + 2) % 3 + i - (i % 3)][(j + 1) % 3 + j - (j % 3)]() )\n\n          ( field[i][j]() != field[ i                       ][(j + 2) % 3 + j - (j % 3)]() )\n          ( field[i][j]() != field[(i + 1) % 3 + i - (i % 3)][(j + 2) % 3 + j - (j % 3)]() )\n          ( field[i][j]() != field[(i + 2) % 3 + i - (i % 3)][(j + 2) % 3 + j - (j % 3)]() );\n\t}\n};\n\ntemplate <unsigned N, bool ToBeFailed>\nclass sudoku_container : public rand_obj {\n public:\n\tsudoku_container(rand_obj* parent = 0) : rand_obj(parent) {\n    for (unsigned i = 0; i < N; i++) {\n      list.push_back(new sudoku(this));\n      if (ToBeFailed)\n        constraint(x[i]() != x[i]());\n      else  \n        constraint(x[i]() == x[i]());\n    }\n\t}\n\t\n private:\t\n  std::vector<sudoku*> list;\n  randv<unsigned> x[N];\n};\n\nint main (int argc, char *argv[]) {\n  boost::timer timer;\n  crave::init(\"crave.cfg\");\n\tsudoku_container<9, true> sc;\n  sc.constraint.enable_multithreading();\n\tfor (int i = 0; i < 20; i++) {\n    std::cout << (sc.next() ? \"solved\" : \"failed\") << std::endl;\n\t}\n  std::cout << \"complete: \" << timer.elapsed() << std::endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "e6a280153620edbfefa664edf57f3a90ffdc7c45", "size": 2331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/sudoku_free_perf/main.cpp", "max_stars_repo_name": "hoangmle/crave-bundle-2015-07-22", "max_stars_repo_head_hexsha": "ffe89f3752887ca2fe12a327ba6c5b25bf23d98a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/sudoku_free_perf/main.cpp", "max_issues_repo_name": "hoangmle/crave-bundle-2015-07-22", "max_issues_repo_head_hexsha": "ffe89f3752887ca2fe12a327ba6c5b25bf23d98a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/sudoku_free_perf/main.cpp", "max_forks_repo_name": "hoangmle/crave-bundle-2015-07-22", "max_forks_repo_head_hexsha": "ffe89f3752887ca2fe12a327ba6c5b25bf23d98a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5, "max_line_length": 93, "alphanum_fraction": 0.4414414414, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5959635430785194}}
{"text": "/*\nHeaders for file \"anfis.cpp\".\n\nCopyright (c) 2021 Gabriele Gilardi\n*/\n\n#ifndef __ANFIS_H_\n#define __ANFIS_H_\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n/* Helper functions */\nArrayXd build_class_table(ArrayXd Y, double tol=1.e-5);\nArrayXi get_classes(ArrayXd Y, ArrayXd table, double tol=1.e-5);\n\n/* ANFIS class */\nclass AnfisType {\n\n    public:\n\n        // Data\n        int n_pf;                   // Number of premise MFs\n        int n_cf;                   // Number of consequent MFs\n        int n_var;                  // Number of variables\n        ArrayXd mu;                 // Premise parameters mu\n        ArrayXd s;                  // Premise parameters s\n        ArrayXd c;                  // Premise parameters c\n        ArrayXXd A;                 // Consequent parameters A\n\n        // Functions\n        AnfisType();\n        void init(ArrayXi MFs, int n_outputs);\n        double create_model(ArrayXd theta, ArrayXXd X, ArrayXXd Y);\n        double create_model(ArrayXd theta, ArrayXXd X, ArrayXi Yc);\n        ArrayXXd eval_data(ArrayXXd Xp);\n        ArrayXXd eval_data(ArrayXXd Xp, ArrayXd table);\n        void info();\n        ~AnfisType();\n    \n    private:\n\n        // Data\n        int n_outputs;              // Number of labels/classes\n        int n_inputs;               // Number of features/inputs\n        ArrayXi MFs;                   // Number of MFs in each feature/input\n        ArrayXXi combs;                // Combinations of premise MFs\n\n        // Functions\n        void build_combinations();\n        void build_param(ArrayXd theta);\n        ArrayXXd forward_steps(ArrayXXd X);\n        ArrayXXd f_activation(ArrayXXd z);\n        ArrayXXd logsig(ArrayXXd z);\n};\n\n#endif\n ", "meta": {"hexsha": "07bd7f9286419add1b6dd31ebec07bc9eb5e758d", "size": 1712, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code_Cpp_PSO/anfis.hpp", "max_stars_repo_name": "gabrielegilardi/ANFIS-metaheuristic", "max_stars_repo_head_hexsha": "28c9e3ed03720ebe56ca2e5aa08bff654084e9fc", "max_stars_repo_licenses": ["MIT"], "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_Cpp_PSO/anfis.hpp", "max_issues_repo_name": "gabrielegilardi/ANFIS-metaheuristic", "max_issues_repo_head_hexsha": "28c9e3ed03720ebe56ca2e5aa08bff654084e9fc", "max_issues_repo_licenses": ["MIT"], "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_Cpp_PSO/anfis.hpp", "max_forks_repo_name": "gabrielegilardi/ANFIS-metaheuristic", "max_forks_repo_head_hexsha": "28c9e3ed03720ebe56ca2e5aa08bff654084e9fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-26T10:03:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T10:03:44.000Z", "avg_line_length": 29.0169491525, "max_line_length": 77, "alphanum_fraction": 0.5695093458, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5959635400720704}}
{"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": "// Copyright (C) 2012  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n#include <dlib/clustering.h>\n\n#include \"tester.h\"\n\nnamespace  \n{\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    logger dlog(\"test.clustering\");\n\n// ----------------------------------------------------------------------------------------\n\n    void make_test_graph(\n        dlib::rand& rnd,\n        std::vector<sample_pair>& edges,\n        std::vector<unsigned long>& labels,\n        const int groups,\n        const int group_size,\n        const int noise_level,\n        const double missed_edges\n    )\n    {\n        labels.resize(groups*group_size);\n\n        for (unsigned long i = 0; i < labels.size(); ++i)\n        {\n            labels[i] = i/group_size;\n        }\n\n        edges.clear();\n        for (int i = 0; i < groups; ++i)\n        {\n            for (int j = 0; j < group_size; ++j)\n            {\n                for (int k = 0; k < group_size; ++k)\n                {\n                    if (j == k)\n                        continue;\n\n                    if (rnd.get_random_double() < missed_edges)\n                        continue;\n\n                    edges.push_back(sample_pair(j+group_size*i, k+group_size*i, 1));\n                }\n            }\n        }\n\n        for (int k = 0; k < groups*noise_level; ++k)\n        {\n            const int i = rnd.get_random_32bit_number()%labels.size();\n            const int j = rnd.get_random_32bit_number()%labels.size();\n            edges.push_back(sample_pair(i,j,1));\n        }\n\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void make_modularity_matrices (\n        const std::vector<sample_pair>& edges,\n        matrix<double>& A,\n        matrix<double>& P,\n        double& m\n    )\n    {\n        const unsigned long num_nodes = max_index_plus_one(edges);\n        A.set_size(num_nodes, num_nodes);\n        P.set_size(num_nodes, num_nodes);\n        A = 0;\n        P = 0;\n        std::vector<double> k(num_nodes,0);\n\n        for (unsigned long i = 0; i < edges.size(); ++i)\n        {\n            const unsigned long n1 = edges[i].index1();\n            const unsigned long n2 = edges[i].index2();\n            k[n1] += edges[i].distance();\n            if (n1 != n2)\n            {\n                k[n2] += edges[i].distance();\n                A(n2,n1) += edges[i].distance();\n            }\n\n            A(n1,n2) += edges[i].distance();\n        }\n\n        m = sum(A)/2;\n\n        for (long r = 0; r < P.nr(); ++r)\n        {\n            for (long c = 0; c < P.nc(); ++c)\n            {\n                P(r,c) = k[r]*k[c]/(2*m);\n            }\n        }\n\n    }\n\n    double compute_modularity_simple (\n        const std::vector<sample_pair>& edges,\n        std::vector<unsigned long> labels\n    )\n    {\n        double m;\n        matrix<double> A,P;\n        make_modularity_matrices(edges, A, P, m);\n        matrix<double> B = A - P;\n\n        double Q = 0;\n        for (long r = 0; r < B.nr(); ++r)\n        {\n            for (long c = 0; c < B.nc(); ++c)\n            {\n                if (labels[r] == labels[c])\n                {\n                    Q += B(r,c);\n                }\n            }\n        }\n        return 1.0/(2*m) * Q;\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_modularity(dlib::rand& rnd)\n    {\n        print_spinner();\n        std::vector<sample_pair> edges;\n        std::vector<ordered_sample_pair> oedges;\n        std::vector<unsigned long> labels;\n\n        make_test_graph(rnd, edges, labels, 10, 30, 3, 0.10);\n        if (rnd.get_random_double() < 0.5)\n            remove_duplicate_edges(edges);\n        convert_unordered_to_ordered(edges, oedges);\n\n\n        const double m1 = modularity(edges, labels);\n        const double m2 = compute_modularity_simple(edges, labels);\n        const double m3 = modularity(oedges, labels);\n\n        DLIB_TEST(std::abs(m1-m2) < 1e-12);\n        DLIB_TEST(std::abs(m2-m3) < 1e-12);\n        DLIB_TEST(std::abs(m3-m1) < 1e-12);\n    }\n\n    void test_newman_clustering(dlib::rand& rnd)\n    {\n        print_spinner();\n        std::vector<sample_pair> edges;\n        std::vector<unsigned long> labels;\n\n        make_test_graph(rnd, edges, labels, 5, 30, 3, 0.10);\n        if (rnd.get_random_double() < 0.5)\n            remove_duplicate_edges(edges);\n\n\n        std::vector<unsigned long> labels2;\n\n        unsigned long num_clusters = newman_cluster(edges, labels2);\n        DLIB_TEST(labels.size() == labels2.size());\n        DLIB_TEST(num_clusters == 5);\n\n        for (unsigned long i = 0; i < labels.size(); ++i)\n        {\n            for (unsigned long j = 0; j < labels.size(); ++j)\n            {\n                if (labels[i] == labels[j])\n                {\n                    DLIB_TEST(labels2[i] == labels2[j]);\n                }\n                else\n                {\n                    DLIB_TEST(labels2[i] != labels2[j]);\n                }\n            }\n        }\n    }\n\n    void test_chinese_whispers(dlib::rand& rnd)\n    {\n        print_spinner();\n        std::vector<sample_pair> edges;\n        std::vector<unsigned long> labels;\n\n        make_test_graph(rnd, edges, labels, 5, 30, 3, 0.10);\n        if (rnd.get_random_double() < 0.5)\n            remove_duplicate_edges(edges);\n\n\n        std::vector<unsigned long> labels2;\n\n        unsigned long num_clusters;\n        if (rnd.get_random_double() < 0.5)\n            num_clusters = chinese_whispers(edges, labels2, 200, rnd);\n        else\n            num_clusters = chinese_whispers(edges, labels2);\n\n        DLIB_TEST(labels.size() == labels2.size());\n        DLIB_TEST(num_clusters == 5);\n\n        for (unsigned long i = 0; i < labels.size(); ++i)\n        {\n            for (unsigned long j = 0; j < labels.size(); ++j)\n            {\n                if (labels[i] == labels[j])\n                {\n                    DLIB_TEST(labels2[i] == labels2[j]);\n                }\n                else\n                {\n                    DLIB_TEST(labels2[i] != labels2[j]);\n                }\n            }\n        }\n    }\n\n    void test_bottom_up_clustering()\n    {\n        std::vector<dpoint> pts;\n        pts.push_back(dpoint(0.0,0.0));\n        pts.push_back(dpoint(0.5,0.0));\n        pts.push_back(dpoint(0.5,0.5));\n        pts.push_back(dpoint(0.0,0.5));\n\n        pts.push_back(dpoint(3.0,3.0));\n        pts.push_back(dpoint(3.5,3.0));\n        pts.push_back(dpoint(3.5,3.5));\n        pts.push_back(dpoint(3.0,3.5));\n\n        pts.push_back(dpoint(7.0,7.0));\n        pts.push_back(dpoint(7.5,7.0));\n        pts.push_back(dpoint(7.5,7.5));\n        pts.push_back(dpoint(7.0,7.5));\n\n        matrix<double> dists(pts.size(), pts.size());\n        for (long r = 0; r < dists.nr(); ++r)\n            for (long c = 0; c < dists.nc(); ++c)\n                dists(r,c) = length(pts[r]-pts[c]);\n\n\n        matrix<unsigned long,0,1> truth(12);\n        truth = 0, 0, 0, 0,\n                1, 1, 1, 1,\n                2, 2, 2, 2;\n\n        std::vector<unsigned long> labels;\n        DLIB_TEST(bottom_up_cluster(dists, labels, 3) == 3);\n        DLIB_TEST(mat(labels) == truth);\n        DLIB_TEST(bottom_up_cluster(dists, labels, 1, 4.0) == 3);\n        DLIB_TEST(mat(labels) == truth);\n        DLIB_TEST(bottom_up_cluster(dists, labels, 1, 4.95) == 2);\n        truth = 0, 0, 0, 0,\n                0, 0, 0, 0,\n                1, 1, 1, 1;\n        DLIB_TEST(mat(labels) == truth);\n        DLIB_TEST(bottom_up_cluster(dists, labels, 1) == 1);\n        truth = 0, 0, 0, 0,\n                0, 0, 0, 0,\n                0, 0, 0, 0;\n        DLIB_TEST(mat(labels) == truth);\n\n        dists.set_size(0,0);\n        DLIB_TEST(bottom_up_cluster(dists, labels, 3) == 0);\n        DLIB_TEST(labels.size() == 0);\n        DLIB_TEST(bottom_up_cluster(dists, labels, 1) == 0);\n        DLIB_TEST(labels.size() == 0);\n\n        dists.set_size(1,1);\n        dists = 1;\n        DLIB_TEST(bottom_up_cluster(dists, labels, 3) == 1);\n        DLIB_TEST(labels.size() == 1);\n        DLIB_TEST(labels[0] == 0);\n        DLIB_TEST(bottom_up_cluster(dists, labels, 1) == 1);\n        DLIB_TEST(labels.size() == 1);\n        DLIB_TEST(labels[0] == 0);\n        DLIB_TEST(bottom_up_cluster(dists, labels, 1, 0) == 1);\n        DLIB_TEST(labels.size() == 1);\n        DLIB_TEST(labels[0] == 0);\n\n        dists.set_size(2,2);\n        dists = 1;\n        DLIB_TEST(bottom_up_cluster(dists, labels, 3) == 2);\n        DLIB_TEST(labels.size() == 2);\n        DLIB_TEST(labels[0] == 0);\n        DLIB_TEST(labels[1] == 1);\n        DLIB_TEST(bottom_up_cluster(dists, labels, 1) == 1);\n        DLIB_TEST(labels.size() == 2);\n        DLIB_TEST(labels[0] == 0);\n        DLIB_TEST(labels[1] == 0);\n        DLIB_TEST(bottom_up_cluster(dists, labels, 1, 1) == 1);\n        DLIB_TEST(labels.size() == 2);\n        DLIB_TEST(labels[0] == 0);\n        DLIB_TEST(labels[1] == 0);\n        DLIB_TEST(bottom_up_cluster(dists, labels, 1, 0.999) == 2);\n        DLIB_TEST(labels.size() == 2);\n        DLIB_TEST(labels[0] == 0);\n        DLIB_TEST(labels[1] == 1);\n    }\n\n    void test_segment_number_line()\n    {\n        dlib::rand rnd;\n\n\n        std::vector<double> x;\n        for (int i = 0; i < 5000; ++i)\n        {\n            x.push_back(rnd.get_double_in_range(-1.5, -1.01));\n            x.push_back(rnd.get_double_in_range(-0.99, -0.01));\n            x.push_back(rnd.get_double_in_range(0.01, 1));\n        }\n\n        auto r = segment_number_line(x,1);\n        std::sort(r.begin(), r.end());\n        DLIB_TEST(r.size() == 3);\n        DLIB_TEST(-1.5 <= r[0].lower && r[0].lower < r[0].upper && r[0].upper <= -1.01);\n        DLIB_TEST(-0.99 <= r[1].lower && r[1].lower < r[1].upper && r[1].upper <= -0.01);\n        DLIB_TEST(0.01 <= r[2].lower && r[2].lower < r[2].upper && r[2].upper <= 1);\n\n        x.clear();\n        for (int i = 0; i < 5000; ++i)\n        {\n            x.push_back(rnd.get_double_in_range(-2, 1));\n            x.push_back(rnd.get_double_in_range(-2, 1));\n            x.push_back(rnd.get_double_in_range(-2, 1));\n        }\n\n        r = segment_number_line(x,1);\n        DLIB_TEST(r.size() == 3);\n        r = segment_number_line(x,1.5);\n        DLIB_TEST(r.size() == 2);\n        r = segment_number_line(x,10.5);\n        DLIB_TEST(r.size() == 1);\n        DLIB_TEST(-2 <= r[0].lower && r[0].lower < r[0].upper && r[0].upper <= 1);\n    }\n\n    class test_clustering : public tester\n    {\n    public:\n        test_clustering (\n        ) :\n            tester (\"test_clustering\",\n                    \"Runs tests on the clustering routines.\")\n        {}\n\n        void perform_test (\n        )\n        {\n            test_bottom_up_clustering();\n            test_segment_number_line();\n\n            dlib::rand rnd;\n\n            std::vector<sample_pair> edges;\n            std::vector<unsigned long> labels;\n            DLIB_TEST(newman_cluster(edges, labels) == 0);\n            DLIB_TEST(chinese_whispers(edges, labels) == 0);\n\n            edges.push_back(sample_pair(0,1,1));\n            DLIB_TEST(newman_cluster(edges, labels) == 1);\n            DLIB_TEST(labels.size() == 2);\n            DLIB_TEST(chinese_whispers(edges, labels) == 1);\n            DLIB_TEST(labels.size() == 2);\n\n            edges.clear();\n            edges.push_back(sample_pair(0,0,1));\n            DLIB_TEST(newman_cluster(edges, labels) == 1);\n            DLIB_TEST(labels.size() == 1);\n            DLIB_TEST(chinese_whispers(edges, labels) == 1);\n            DLIB_TEST(labels.size() == 1);\n\n            edges.clear();\n            edges.push_back(sample_pair(1,1,1));\n            DLIB_TEST(newman_cluster(edges, labels) == 1);\n            DLIB_TEST(labels.size() == 2);\n            DLIB_TEST(chinese_whispers(edges, labels) == 2);\n            DLIB_TEST(labels.size() == 2);\n\n            edges.push_back(sample_pair(0,0,1));\n            DLIB_TEST(newman_cluster(edges, labels) == 2);\n            DLIB_TEST(labels.size() == 2);\n            DLIB_TEST(chinese_whispers(edges, labels) == 2);\n            DLIB_TEST(labels.size() == 2);\n\n\n            for (int i = 0; i < 10; ++i)\n                test_modularity(rnd);\n\n            for (int i = 0; i < 10; ++i)\n                test_newman_clustering(rnd);\n\n            for (int i = 0; i < 10; ++i)\n                test_chinese_whispers(rnd);\n\n\n        }\n    } a;\n\n\n\n}\n\n\n\n", "meta": {"hexsha": "a784c57c03240942460356934b7e1743b88bf7c9", "size": 12352, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/dlib/test/clustering.cpp", "max_stars_repo_name": "mohitjain4395/mosip", "max_stars_repo_head_hexsha": "20ee978dc539be42c8b79cd4b604fdf681e7b672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "dlib/test/clustering.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "dlib/test/clustering.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 30.0535279805, "max_line_length": 91, "alphanum_fraction": 0.4865608808, "num_tokens": 3365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.5957423851564576}}
{"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": "// Testing the do_equal function\n\n#include <CGAL/config.h>\n#ifndef CGAL_USE_CORE\n#include <iostream>\nint main()\n{\n  std::cout << \"Sorry, this example needs CORE ...\" << std::endl;\n  return 0;\n}\n\n#else\n\n#include <vector>\n#include <list>\n\n#include <boost/type_traits/is_same.hpp>\n\n#include <CGAL/Cartesian.h>\n#include <CGAL/Quotient.h>\n#include <CGAL/MP_Float.h>\n#include <CGAL/CORE_algebraic_number_traits.h>\n#include <CGAL/Arr_polyline_traits_2.h>\n#include <CGAL/Arr_conic_traits_2.h>\n#include <CGAL/tags.h>\n#include <CGAL/Arr_tags.h>\n\n////////////////////\n//conic traits\n////////////////////\ntypedef CGAL::CORE_algebraic_number_traits            Nt_traits;\ntypedef Nt_traits::Rational                           Rational;\ntypedef Nt_traits::Algebraic                          Algebraic;\ntypedef CGAL::Cartesian<Rational>                     Rat_kernel;\ntypedef Rat_kernel::Point_2                           Rat_point_2;\ntypedef Rat_kernel::Segment_2                         Rat_segment_2;\ntypedef Rat_kernel::Circle_2                          Rat_circle_2;\ntypedef CGAL::Cartesian<Algebraic>                    Alg_kernel;\ntypedef CGAL::Arr_conic_traits_2<Rat_kernel, Alg_kernel, Nt_traits>\n                                                      Conic_traits_2;\ntypedef Conic_traits_2::Point_2                       Conic_point_2;\ntypedef Conic_traits_2::Curve_2                       Conic_curve_2;\ntypedef Conic_traits_2::X_monotone_curve_2            Conic_x_monotone_curve_2;\ntypedef CGAL::Arr_polyline_traits_2<Conic_traits_2>   Polycurve_conic_traits_2;\ntypedef Polycurve_conic_traits_2::X_monotone_curve_2  Pc_x_monotone_curve_2;\ntypedef Polycurve_conic_traits_2::Point_2             Pc_point_2;\n\n// typedef CGAL::Arr_polyline_traits_2<\n//                CGAL::Arr_conic_traits_2<CGAL::Cartesian<BigRat>,\n//                CGAL::Cartesian<Expr>,\n//                CGAL::CORE_algebraic_number_traits>\n//              >::Point_2   test_point_2;\n\nvoid check_equal()\n{\n  bool are_equal;\n\n  Polycurve_conic_traits_2 traits;\n  Polycurve_conic_traits_2::Equal_2 equal = traits.equal_2_object();\n  Polycurve_conic_traits_2::Construct_x_monotone_curve_2\n    construct_x_monotone_curve_2 = traits.construct_x_monotone_curve_2_object();\n\n  //create some curves\n  Conic_point_2 ps1(Rational(1,4), 4);\n  Conic_point_2 pt1(2, Rational(1,2));\n  Conic_curve_2 c1(0, 0, 1, 0, 0, -1, CGAL::COUNTERCLOCKWISE, ps1, pt1);\n\n  Conic_point_2 ps2(Rational(1,4), 4);\n  Conic_point_2 pt2(2, Rational(1,2));\n  Conic_curve_2 c2(0, 0, 1, 0, 0, -1, CGAL::COUNTERCLOCKWISE, ps2, pt2);\n\n  Rat_point_2 ps3(Rational(1,4), 4);\n  Rat_point_2 pmid3(Rational(3,2), 2);\n  Rat_point_2 pt3(2, Rational(1,3));\n  Conic_curve_2 c3(ps3, pmid3, pt3);\n\n  Rat_point_2 ps4(1, 5);\n  Rat_point_2 pmid4(Rational(3,2), 3);\n  Rat_point_2 pt4(3, Rational(1,3));\n  Conic_curve_2 c4(ps4, pmid4, pt4);\n\n  // //make x_monotone\n  Polycurve_conic_traits_2::X_monotone_curve_2 xmc1 =\n    construct_x_monotone_curve_2(c1);\n  Polycurve_conic_traits_2::X_monotone_curve_2 xmc2 =\n    construct_x_monotone_curve_2(c2);\n  Polycurve_conic_traits_2::X_monotone_curve_2 xmc3 =\n    construct_x_monotone_curve_2(c3);\n  Polycurve_conic_traits_2::X_monotone_curve_2 xmc4 =\n    construct_x_monotone_curve_2(c4);\n\n  are_equal = equal(xmc1, xmc2);\n  std::cout << \"Two equal conic arcs are computed as:  \"\n            << ((are_equal) ? \"equal\" : \"Not equal\") << std::endl;\n\n  are_equal = equal(xmc3, xmc2);\n  std::cout << \"Two un-equal conic arcs are computed as:  \"\n            << ((are_equal) ? \"equal\" : \"Not equal\") << std::endl;\n\n  are_equal = equal(xmc3, xmc4);\n  std::cout << \"Two un-equal conic arcs are computed as:  \"\n            << ((are_equal) ? \"equal\" : \"Not equal\") << std::endl;\n }\n\n template <typename Traits>\n void check_intersect(typename Traits::X_monotone_curve_2& xcv1,\n                      typename Traits::X_monotone_curve_2& xcv2,\n                      const Traits& traits)\n {\n   typedef typename Traits::Multiplicity                Multiplicity;\n   typedef typename Traits::Point_2                     Point_2;\n   typedef typename Traits::X_monotone_curve_2          X_monotone_curve_2;\n   typedef std::pair<Multiplicity, Point_2>             Intersection_point;\n   typedef boost::variant<Intersection_point, X_monotone_curve_2>\n     Intersection_result;\n\n   std::vector<Intersection_result> intersection_points;\n   traits.intersect_2_object()(xcv1, xcv2,\n                               std::back_inserter(intersection_points));\n   std::cout<< \"Number of intersection Points: \" << intersection_points.size()\n            << std::endl;\n\n   //dynamic cast the cgal_objects\n   // std::vector< std::pair<Polycurve_conic_traits_2::Point_2,\n   //                        Polycurve_conic_traits_2::Multiplicity> > pm_vector;\n   // for(int i=0; i<intersection_points.size(); i++)\n   // {\n   //   std::pair<Polycurve_conic_traits_2::Point_2,\n   //             Polycurve_conic_traits_2::Multiplicity> pm =\n   //   CGAL::object_cast<std::pair<Polycurve_conic_traits_2::Point_2,\n   //                               Polycurve_conic_traits_2::Multiplicity> >\n   //                              (&(intersection_points[i]));\n   //   pm_vector.push_back(pm);\n   // }\n }\n\nvoid check_compare_end_points_xy_2()\n{\n  Polycurve_conic_traits_2 traits;\n  Polycurve_conic_traits_2::Construct_x_monotone_curve_2\n    construct_x_monotone_curve_2 = traits.construct_x_monotone_curve_2_object();\n  Polycurve_conic_traits_2::Compare_endpoints_xy_2 compare_endpoints_xy_2 =\n    traits.compare_endpoints_xy_2_object();\n\n  //create some curves\n  Conic_point_2 ps1(Rational(1,4), 4);\n  Conic_point_2 pt1(2, Rational(1,2));\n  Conic_curve_2 c1(0, 0, 1, 0, 0, -1, CGAL::COUNTERCLOCKWISE, ps1, pt1);\n\n  // Insert a parabolic arc that is supported by a parabola y = -x^2\n  // (or: x^2 + y = 0) and whose endpoints are (-sqrt(3), -3) ~ (-1.73, -3)\n  // and (sqrt(2), -2) ~ (1.41, -2). Notice that since the x-coordinates\n  // of the endpoints cannot be accurately represented, we specify them\n  // as the intersections of the parabola with the lines y = -3 and y = -2.\n  // Note that the arc is clockwise oriented.\n  Conic_curve_2\n    c2 = Conic_curve_2(1, 0, 0, 0, 1, 0,         // The parabola.\n                       CGAL::CLOCKWISE,\n                       Conic_point_2(-1.73, -3), // Approximation of the source.\n                       0, 0, 0, 0, 1, 3,         // The line: y = -3.\n                       Conic_point_2(1.41, -2),  // Approximation of the target.\n                       0, 0, 0, 0, 1, 2);        // The line: y = -2.\n  assert(c2.is_valid());\n\n  //make polyline x-monotone curves\n  Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc1 =\n    construct_x_monotone_curve_2(c1);\n  Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc2 =\n    construct_x_monotone_curve_2(c2);\n\n  CGAL::Comparison_result res = compare_endpoints_xy_2(polyline_xmc1);\n  std::cout << \"compare_end_points_xy_2 for counterclockwise curve: \"\n            << (res == CGAL::SMALLER ? \"SMALLER\":\n               (res == CGAL::LARGER ? \"LARGER\" : \"EQUAL\")) << std::endl;\n\n  res = compare_endpoints_xy_2(polyline_xmc2);\n  std::cout<< \"compare_end_points_xy_2 for clockwise curve: \"\n           << (res == CGAL::SMALLER ? \"SMALLER\":\n               (res == CGAL::LARGER ? \"LARGER\" : \"EQUAL\")) << std::endl;\n}\n\ntemplate <typename Curve_type>\nvoid check_split(Curve_type &xcv1, Curve_type &xcv2)\n{\n  Polycurve_conic_traits_2 traits;\n\n  //split x poly-curves\n\n  Conic_curve_2 c6(1,1,0,6,-26,162,CGAL::COUNTERCLOCKWISE,\n                   Conic_point_2(Algebraic(-7), Algebraic(13)),\n                   Conic_point_2(Algebraic(-3), Algebraic(9)));\n  Conic_curve_2 c7(1,0,0,0,-1,0,CGAL::COUNTERCLOCKWISE,\n                   Conic_point_2(Algebraic(-3), Algebraic(9)),\n                   Conic_point_2(Algebraic(0), Algebraic(0)));\n  Conic_curve_2 c8(0,1,0,-1,0,0, CGAL::COUNTERCLOCKWISE,\n                   Conic_point_2(Algebraic(0), Algebraic(0)),\n                   Conic_point_2(Algebraic(4), Algebraic(-2)));\n\n  Conic_x_monotone_curve_2 xc6(c6);\n  Conic_x_monotone_curve_2 xc7(c7);\n  Conic_x_monotone_curve_2 xc8(c8);\n  std::vector<Conic_x_monotone_curve_2> xmono_conic_curves_2;\n\n  xmono_conic_curves_2.push_back(xc6);\n  xmono_conic_curves_2.push_back(xc7);\n  Pc_x_monotone_curve_2 split_expected_1 =\n    traits.construct_x_monotone_curve_2_object()(xmono_conic_curves_2.begin(),\n                                                 xmono_conic_curves_2.end());\n\n  xmono_conic_curves_2.clear();\n  xmono_conic_curves_2.push_back(xc8);\n  Pc_x_monotone_curve_2 split_expected_2 =\n    traits.construct_x_monotone_curve_2_object()(xmono_conic_curves_2.begin(),\n                                                 xmono_conic_curves_2.end());\n\n\n  Polycurve_conic_traits_2::X_monotone_curve_2 split_curve_1, split_curve_2;\n  Polycurve_conic_traits_2::Point_2\n    point_of_split = Polycurve_conic_traits_2::Point_2(0,0);\n\n  //Split functor\n  traits.split_2_object()(xcv2, point_of_split, split_curve_1, split_curve_2);\n\n  bool split_1_chk = traits.equal_2_object()(split_curve_1, split_expected_1);\n  bool split_2_chk = traits.equal_2_object()(split_curve_2, split_expected_2);\n\n  if(split_1_chk && split_2_chk)\n    std::cout << \"Split is working fine\" << std::endl;\n  else\n    std::cout << \"Something is wrong with split\" << std::endl;\n}\n\nvoid check_is_vertical()\n{\n  Polycurve_conic_traits_2 traits;\n  Polycurve_conic_traits_2::Construct_x_monotone_curve_2\n    construct_x_monotone_curve_2 = traits.construct_x_monotone_curve_2_object();\n  Polycurve_conic_traits_2::Is_vertical_2 is_vertical =\n    traits.is_vertical_2_object();\n\n   //create a curve\n  Rat_point_2 ps1(1, 10);\n  Rat_point_2 pmid1(5, 4);\n  Rat_point_2 pt1(10, 1);\n  Conic_curve_2 c1(ps1, pmid1, pt1);\n\n  //make x-monotone curve\n  Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc1 =\n    construct_x_monotone_curve_2(c1);\n\n  bool result = is_vertical(polyline_xmc1);\n  std::cout << \"Is_verticle:: Expected first result is not vertivle: Computed: \"\n            << ((result)? \"vertical\" : \"not vertical\") << std::endl;\n}\n\n/*! */\ntemplate <typename stream>\nbool read_orientation(stream& is, CGAL::Orientation& orient)\n{\n  int i_orient;\n  is >> i_orient;\n  orient = (i_orient > 0) ? CGAL::COUNTERCLOCKWISE :\n    (i_orient < 0) ? CGAL::CLOCKWISE : CGAL::COLLINEAR;\n  return true;\n}\n\n/*! */\ntemplate <typename stream>\nbool read_app_point(stream& is, Conic_point_2& p)\n{\n  //waqar: original\n  double x, y;\n  is >> x >> y;\n  p = Conic_point_2(Algebraic(x), Algebraic(y));\n  return true;\n\n  //waqar: my modification\n  // long int rat_x_num, rat_x_den, rat_y_num, rat_y_den;\n  // is >> rat_x_num >> rat_x_den >> rat_y_num >> rat_y_den;\n\n  // Basic_number_type x(rat_x), y(rat_y);\n  // p = Conic_point_2(Rational(rat_x_num, rat_x_den),\n  //                   Rational(rat_y_num, rat_y_den));\n  // return true;\n}\n\n/*! */\ntemplate <typename stream>\nbool read_orientation_and_end_points(stream& is, CGAL::Orientation& orient,\n                                     Conic_point_2& source,\n                                     Conic_point_2& target)\n{\n  // Read the orientation.\n  if (!read_orientation(is, orient)) return false;\n\n  // Read the end points of the arc and create it.\n  if (!read_app_point(is, source)) return false;\n  if (!read_app_point(is, target)) return false;\n  return true;\n}\n\n/*! */\ntemplate <typename stream, typename Curve>\nbool read_general_arc(stream& is, Curve& cv)\n{\n  // Read a general conic, given by its coefficients <r,s,t,u,v,w>.\n  Rational r, s, t, u, v, w;                // The conic coefficients.\n  is >> r >> s >> t >> u >> v >> w;\n    // Read the orientation.\n  int i_orient = 0;\n  is >> i_orient;\n  CGAL::Orientation orient = (i_orient > 0) ? CGAL::COUNTERCLOCKWISE :\n    (i_orient < 0) ? CGAL::CLOCKWISE : CGAL::COLLINEAR;\n\n  // Read the approximated source, along with a general conic\n  // <r_1,s_1,t_1,u_1,v_1,w_1> whose intersection with <r,s,t,u,v,w>\n  // defines the source.\n  Conic_point_2 app_source;\n  if (!read_app_point(is, app_source)) return false;\n  Rational r1, s1, t1, u1, v1, w1;\n  is >> r1 >> s1 >> t1 >> u1 >> v1 >> w1;\n\n  // Read the approximated target, along with a general conic\n  // <r_2,s_2,t_2,u_2,v_2,w_2> whose intersection with <r,s,t,u,v,w>\n  // defines the target.\n  Conic_point_2 app_target;\n  if (!read_app_point(is, app_target)) return false;\n\n  Rational r2, s2, t2, u2, v2, w2;\n  is >> r2 >> s2 >> t2 >> u2 >> v2 >> w2;\n\n  std::cout << \"line is: \" << r << s << t << u << v << w << i_orient\n            << r1 << s1 << t1 << u1 << v1 << w1\n            << r2 << s2 << t2 << u2 << v2 << w2 << std::endl;\n\n  // Create the conic arc.\n  cv = Curve(r, s, t, u, v, w, orient,\n             app_source, r1, s1, t1, u1, v1, w1,\n             app_target, r2, s2, t2, u2, v2, w2);\n  return true;\n}\n\n/*! */\ntemplate <typename stream, typename Curve>\nbool read_general_conic(stream& is, Curve& cv)\n{\n  // Read a general conic, given by its coefficients <r,s,t,u,v,w>.\n  Rational r, s, t, u, v, w;\n  is >> r >> s >> t >> u >> v >> w;\n  // Create a full conic (should work only for ellipses).\n  cv = Curve(r, s, t, u, v, w);\n  return true;\n}\n\n// /*! */\ntemplate <typename stream, typename Curve>\nbool read_general_curve(stream& is, Curve& cv)\n{\n  Rational r, s, t, u, v, w;                // The conic coefficients.\n  // Read a general conic, given by its coefficients <r,s,t,u,v,w>.\n  is >> r >> s >> t >> u >> v >> w;\n  CGAL::Orientation orient;\n  Conic_point_2 source, target;\n  if (!read_orientation_and_end_points(is, orient, source, target))\n    return false;\n\n  // Create the conic (or circular) arc.\n  // std::cout << \"arc coefficients: \" << r << \" \" << s << \" \" << t << \" \"\n  //           << u << \" \" << v << \" \" << w << std::endl;\n  // std::cout << \"Read Points : \" << source.x() << \" \" << source.y() << \" \"\n  //           << target.x() << \" \" << target.y() << std::endl;\n  cv = Curve(r, s, t, u, v, w, orient, source, target);\n  return true;\n}\nstd::istream& skip_comments(std::istream& is, std::string& line)\n{\n  while (std::getline(is, line))\n    if (!line.empty() && (line[0] != '#')) break;\n  return is;\n}\n\nbool check_compare_y_at_x_2()\n{\n  Polycurve_conic_traits_2 traits;\n  Polycurve_conic_traits_2::Compare_y_at_x_2 cmp_y_at_x_2 =\n    traits.compare_y_at_x_2_object();\n  //polycurve constructors\n  Polycurve_conic_traits_2::Construct_x_monotone_curve_2\n    construct_x_mono_polycurve = traits.construct_x_monotone_curve_2_object();\n  Polycurve_conic_traits_2::Construct_curve_2  construct_polycurve =\n    traits.construct_curve_2_object();\n\n   //create a curve\n  Rat_point_2 ps1(1, 10);\n  Rat_point_2 pmid1(5, 4);\n  Rat_point_2 pt1(10, 1);\n  Conic_curve_2 c1(ps1, pmid1, pt1);\n\n   //create a curve\n  Rat_point_2 ps2(10, 1);\n  Rat_point_2 pmid2(15, 5);\n  Rat_point_2 pt2(20, 10);\n  Conic_curve_2 c2(ps2, pmid2, pt2);\n\n  Conic_curve_2 c3(1,0,0,0,-1,0,CGAL::COUNTERCLOCKWISE,\n                   Conic_point_2(Algebraic(0), Algebraic(0)),\n                   Conic_point_2(Algebraic(3), Algebraic(9)));\n  Conic_curve_2 c4(1,0,0,0,-1,0,CGAL::COUNTERCLOCKWISE,\n                   Conic_point_2(Algebraic(3), Algebraic(9)),\n                   Conic_point_2(Algebraic(5), Algebraic(25)));\n\n  std::vector<Conic_curve_2> conic_curves, conic_curves_2, Conic_curves_3;\n  conic_curves.push_back(c1);\n  conic_curves.push_back(c2);\n\n  //conic_curves_2.push_back(c3);\n  //conic_curves_2.push_back(c4);\n\n  Conic_x_monotone_curve_2 xc1(c1);\n  Conic_x_monotone_curve_2 xc2(c2);\n  Conic_x_monotone_curve_2 xc3(c3);\n  Conic_x_monotone_curve_2 xc4(c4);\n\n  std::vector<Conic_x_monotone_curve_2> xmono_conic_curves, xmono_conic_curves_2;\n  /* VERY IMPORTANT\n   * For efficiency reasons, we recommend users not to construct x-monotone\n   * conic arc directly, but rather use the Make_x_monotone_2 functor supplied\n   * by the conic-arc traits class to convert conic curves to x-monotone curves.\n   */\n  xmono_conic_curves.push_back(xc1);\n  xmono_conic_curves.push_back(xc2);\n  xmono_conic_curves_2.push_back(xc3);\n  xmono_conic_curves_2.push_back(xc4);\n\n  //construct x-monotone poly-curve\n  Polycurve_conic_traits_2::X_monotone_curve_2 conic_x_mono_polycurve =\n    construct_x_mono_polycurve(xmono_conic_curves.begin(),\n                               xmono_conic_curves.end());\n  Polycurve_conic_traits_2::X_monotone_curve_2 conic_x_mono_polycurve_2 =\n    construct_x_mono_polycurve(xmono_conic_curves_2.begin(),\n                               xmono_conic_curves_2.end());\n\n  //construct poly-curve\n  Polycurve_conic_traits_2::Curve_2 conic_polycurve =\n    construct_polycurve(conic_curves.begin(), conic_curves.end());\n  //Polycurve_conic_traits_2::Curve_2 conic_polycurve_2 =\n  //  construct_polycurve(conic_curves_2.begin(), conic_curves_2.end());\n\n  //make x-monotone curve\n  //Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc1 =\n  //  construct_x_monotone_curve_2(c1);\n\n  //create points\n  Polycurve_conic_traits_2::Point_2\n    point_above_line = Polycurve_conic_traits_2::Point_2(2,10),\n    point_below_line = Polycurve_conic_traits_2::Point_2(4,7),\n    point_on_line = Polycurve_conic_traits_2::Point_2(2,4);\n\n  CGAL::Comparison_result result;\n\n  result =  cmp_y_at_x_2(point_above_line, conic_x_mono_polycurve_2);\n  std::cout << \"Compare_y_at_x_2:: for point above the curve computed Answer is:  \"\n            << (result == CGAL::SMALLER ? \"Below\":\n               (result == CGAL::LARGER ? \"Above\" : \"On-line\")) << std::endl;\n\n  result =  cmp_y_at_x_2(point_below_line, conic_x_mono_polycurve_2);\n  std::cout << \"Compare_y_at_x_2:: for point below the curve computed Answer is:  \"\n            << (result == CGAL::SMALLER ? \"Below\":\n               (result == CGAL::LARGER ? \"Above\" : \"On-line\")) << std::endl;\n\n  result =  cmp_y_at_x_2(point_on_line, conic_x_mono_polycurve_2);\n  std::cout << \"Compare_y_at_x_2:: for point on the curve computed Answer is:  \"\n            << (result == CGAL::SMALLER ? \"Below\":\n               (result == CGAL::LARGER ? \"Above\" : \"On-line\")) << std::endl;\n\n  return true;\n}\n\nvoid check_are_mergable()\n{\n  Polycurve_conic_traits_2 traits;\n  Polycurve_conic_traits_2::Construct_x_monotone_curve_2\n    construct_x_monotone_curve_2 = traits.construct_x_monotone_curve_2_object();\n  Polycurve_conic_traits_2::Are_mergeable_2  are_mergeable_2 =\n    traits.are_mergeable_2_object();\n\n   //create a curve\n  Rat_point_2 ps1(1, 10);\n  Rat_point_2 pmid1(5, 4);\n  Rat_point_2 pt1(10, 1);\n  Conic_curve_2 c1(ps1, pmid1, pt1);\n\n  Rat_point_2 ps2(10, 1);\n  Rat_point_2 pmid2(15, 14);\n  Rat_point_2 pt2(20, 20);\n  Conic_curve_2 c2(ps2, pmid2, pt2);\n\n  Rat_point_2 ps3(Rational(1,4), 4);\n  Rat_point_2 pmid3(Rational(3,2), 2);\n  Rat_point_2 pt3(2, Rational(1,3));\n  Conic_curve_2 c3(ps3, pmid3, pt3);\n\n  //construct x-monotone curve(compatible with polyline class)\n   Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc1 =\n     construct_x_monotone_curve_2(c1);\n   Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc2 =\n     construct_x_monotone_curve_2(c2);\n   Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc3 =\n     construct_x_monotone_curve_2(c3);\n\n  bool result = are_mergeable_2(polyline_xmc1, polyline_xmc2);\n  std::cout << \"Are_mergable:: Mergable x-monotone polycurves are Computed as: \"\n            << ((result)? \"Mergable\" : \"Not-Mergable\") << std::endl;\n\n  result = are_mergeable_2(polyline_xmc1, polyline_xmc3);\n  std::cout << \"Are_mergable:: Non-Mergable x-monotone polycurves are Computed as: \"\n            << ((result)? \"Mergable\" : \"Not-Mergable\") << std::endl;\n}\n\nvoid check_merge_2()\n{\n  Polycurve_conic_traits_2 traits;\n  Polycurve_conic_traits_2::Construct_x_monotone_curve_2\n    construct_x_monotone_curve_2 = traits.construct_x_monotone_curve_2_object();\n  Polycurve_conic_traits_2::Merge_2  merge_2 = traits.merge_2_object();\n\n  //create a curve\n  Rat_point_2 ps1(1, 10);\n  Rat_point_2 pmid1(5, 4);\n  Rat_point_2 pt1(10, 1);\n  Conic_curve_2 c1(ps1, pmid1, pt1);\n\n  Rat_point_2 ps2(10, 1);\n  Rat_point_2 pmid2(15, 14);\n  Rat_point_2 pt2(20, 20);\n  Conic_curve_2 c2(ps2, pmid2, pt2);\n\n//construct x-monotone curve (compatible with polyline class)\n Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc1 =\n   construct_x_monotone_curve_2(c1);\n Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc2 =\n   construct_x_monotone_curve_2(c2);\n\n Polycurve_conic_traits_2::X_monotone_curve_2 merged_xmc;\n\n merge_2(polyline_xmc1, polyline_xmc2, merged_xmc);\n std::cout<< \"Merge_2:: Mergable x-monotone curves merged successfully\"\n          << std:: endl;\n}\n\nvoid check_construct_opposite()\n{\n  Polycurve_conic_traits_2 traits;\n  Polycurve_conic_traits_2::Construct_x_monotone_curve_2\n    construct_x_monotone_curve_2 = traits.construct_x_monotone_curve_2_object();\n  Polycurve_conic_traits_2::Construct_opposite_2 construct_opposite_2 =\n    traits.construct_opposite_2_object();\n\n  //create a curve\n  Rat_point_2 ps1(1, 10);\n  Rat_point_2 pmid1(5, 4);\n  Rat_point_2 pt1(10, 1);\n  Conic_curve_2     c1(ps1, pmid1, pt1);\n\n  //construct x-monotone curve (compatible with polyline class)\n Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc1 =\n   construct_x_monotone_curve_2(c1);\n Polycurve_conic_traits_2::X_monotone_curve_2 polyline_opposite_curve =\n   construct_opposite_2(polyline_xmc1);\n\n std::cout<< \"Construct_opposite_2:: Opposite curve created\";\n}\n\nvoid check_compare_y_at_x_right()\n{\n  Polycurve_conic_traits_2 traits;\n  Polycurve_conic_traits_2::Construct_x_monotone_curve_2\n    construct_x_monotone_curve_2 = traits.construct_x_monotone_curve_2_object();\n  Polycurve_conic_traits_2::Compare_y_at_x_right_2 cmp_y_at_x_right_2 =\n    traits.compare_y_at_x_right_2_object();\n\n  //create constructing curves\n  Rat_point_2 ps2(1, 10);\n  Rat_point_2 pmid2(5, 4);\n  Rat_point_2 pt2(10, 1);\n  Conic_curve_2 c1(ps2, pmid2, pt2);\n\n  Rat_point_2 ps3(10, 1);\n  Rat_point_2 pmid3(5, 4);\n  Rat_point_2 pt3(1, 10);\n  Conic_curve_2 c2(ps3, pmid3, pt3);\n\n  //construct x-monotone curve (compatible with polyline class)\n  Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc1 =\n    construct_x_monotone_curve_2(c1);\n  Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc2 =\n    construct_x_monotone_curve_2(c2);\n  Polycurve_conic_traits_2::Point_2 intersection_point =\n    Polycurve_conic_traits_2::Point_2(5,4);\n\n  CGAL::Comparison_result result;\n  result = cmp_y_at_x_right_2(polyline_xmc1, polyline_xmc2, intersection_point);\n  std::cout << \"Compare_y_at_x_right:: Expected Answer: equal, Computed answer:  \"\n            << (result == CGAL::SMALLER ? \"smaller\":\n               (result == CGAL::LARGER ? \"Larger\" : \"equal\")) << std::endl;\n}\n\nvoid check_compare_y_at_x_left()\n{\n  Polycurve_conic_traits_2 traits;\n  Polycurve_conic_traits_2::Construct_x_monotone_curve_2\n    construct_x_monotone_curve_2 = traits.construct_x_monotone_curve_2_object();\n  Polycurve_conic_traits_2::Compare_y_at_x_left_2 cmp_y_at_x_left_2 =\n    traits.compare_y_at_x_left_2_object();\n\n  //create constructing curves\n  Rat_point_2 ps2(1, 10);\n  Rat_point_2 pmid2(5, 4);\n  Rat_point_2 pt2(10, 1);\n  Conic_curve_2 c1(ps2, pmid2, pt2);\n\n  Rat_point_2 ps3(10, 1);\n  Rat_point_2 pmid3(5, 4);\n  Rat_point_2 pt3(1, 10);\n  Conic_curve_2 c2(ps3, pmid3, pt3);\n\n  //construct x-monotone curve(compatible with polyline class)\n  Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc1 =\n    construct_x_monotone_curve_2(c1);\n  Polycurve_conic_traits_2::X_monotone_curve_2 polyline_xmc2 =\n    construct_x_monotone_curve_2(c2);\n  Polycurve_conic_traits_2::Point_2 intersection_point =\n    Polycurve_conic_traits_2::Point_2(5,4);\n\n  CGAL::Comparison_result result;\n\n  result = cmp_y_at_x_left_2(polyline_xmc1, polyline_xmc2, intersection_point);\n  std::cout << \"Compare_y_at_x_left:: Expected Answer: equal, Computed answer:  \"\n            << (result == CGAL::SMALLER ? \"smaller\":\n               (result == CGAL::LARGER ? \"Larger\" : \"equal\")) << std::endl;\n}\n\ntemplate <typename GeometryTraits>\nvoid check_make_x_monotne_curve(const typename GeometryTraits::Curve_2& c1)\n{\n  typename GeometryTraits::Point_2                      Point_2;\n  typename GeometryTraits::X_monotone_curve_2           X_monotone_curve_2;\n  typedef boost::variant<Point_2, X_monotone_curve_2>   Make_x_monotone_result;\n  Polycurve_conic_traits_2 traits;\n  std::vector<Make_x_monotone_result> objs;\n  traits.make_x_monotone_2_object()(c1, std::back_inserter(objs));\n  std::cout << \"The polycurve is: \" << c1 << std::endl;\n  std::cout<< \"The poly curve have been split into \" << objs.size()\n           << \" polycurves\" << std::endl;\n\n  //const Pc_x_monotone_curve_2 *split_curve_1 =\n  //  CGAL::object_cast<Pc_x_monotone_curve_2> (&(objs[0]));\n  //const Pc_x_monotone_curve_2 *split_curve_2 =\n  //  CGAL::object_cast<Pc_x_monotone_curve_2> (&(objs[1]));\n\n  //std::cout << \"The split curve 1 is: \" << *split_curve_1 << std::endl;\n  //std::cout << \"The split curve 2 is: \" << *split_curve_2 << std::endl;\n}\n\ntemplate<typename Curve, typename Segment>\nvoid check_push_front(Curve base_curve, Segment curve_tobe_pushed)\n{\n  Polycurve_conic_traits_2 traits;\n\n  std::cout << \"Base curve: \" << base_curve << std::endl;\n  std::cout << \"push curve: \" << curve_tobe_pushed << std::endl;\n\n  traits.push_front_2_object()(base_curve, curve_tobe_pushed);\n  std::cout << \"result curve: \" << base_curve << std::endl;\n}\n\ntemplate<typename Curve, typename Segment>\nvoid check_push_back(Curve& base_curve, Segment curve_tobe_pushed)\n{\n  Polycurve_conic_traits_2 traits;\n\n  std::cout << \"Base curve: \" << base_curve << std::endl;\n  std::cout << \"push curve: \" << curve_tobe_pushed << std::endl;\n\n  traits.push_back_2_object()(base_curve, curve_tobe_pushed);\n\n  std::cout << \"result curve: \" << base_curve << std::endl;\n}\n\ntemplate<typename Segment>\nvoid check_compare_x_2(const Segment& seg1, const Segment& seg2)\n{\n  Polycurve_conic_traits_2 traits;\n  CGAL::Comparison_result result;\n\n  result = traits.compare_x_2_object()(seg1, CGAL::ARR_MIN_END, seg2,\n                                       CGAL::ARR_MIN_END);\n  std::cout << \"Compare_x_2:: Expected Answer: Larger, Computed answer:  \"\n            << (result == CGAL::SMALLER ? \"smaller\":\n               (result == CGAL::LARGER ? \"Larger\" : \"equal\")) << std::endl;\n\n  result = traits.compare_x_2_object()(seg1, CGAL::ARR_MIN_END, seg2,\n                                       CGAL::ARR_MAX_END);\n  std::cout << \"Compare_x_2:: Expected Answer: Equal, Computed answer:  \"\n            << (result == CGAL::SMALLER ? \"smaller\":\n               (result == CGAL::LARGER ? \"Larger\" : \"equal\")) << std::endl;\n}\n\ntemplate<typename Curve>\nvoid check_compare_points(Curve& cv)\n{\n  Polycurve_conic_traits_2 traits;\n  CGAL::Arr_parameter_space result =\n    traits.parameter_space_in_x_2_object()(cv, CGAL::ARR_MAX_END);\n}\n\ntemplate <typename curve>\nvoid check_trim(curve& xcv, int sx, int sy, int tx, int ty)\n{\n  Polycurve_conic_traits_2 traits;\n\n  // Conic_point_2 source(Algebraic(-16), Algebraic(-4));\n  // Conic_point_2 target(Algebraic(4), Algebraic(16));\n  Conic_point_2 source(sx, sy);\n  Conic_point_2 target(tx, ty);\n\n  Polycurve_conic_traits_2::Trim_2  trim_polycurve = traits.trim_2_object();\n  Pc_x_monotone_curve_2 trimmed_curve = trim_polycurve(xcv, source, target);\n\n  std::cout << \"polycurvecurve: \" << xcv << std::endl<<std::endl;\n  std::cout << \"Trimmed curve: \" << trimmed_curve << std::endl;\n\n}\n\nint main(int argc, char* argv[])\n{\n  Polycurve_conic_traits_2 traits;\n    //polycurve constructors\n  auto construct_x_mono_polycurve = traits.construct_x_monotone_curve_2_object();\n  auto construct_polycurve = traits.construct_curve_2_object();\n\n   //create a curve\n\n  Conic_curve_2 c3(1,0,0,0,-1,0,CGAL::COUNTERCLOCKWISE,\n                   Conic_point_2(Algebraic(0), Algebraic(0)),\n                   Conic_point_2(Algebraic(3), Algebraic(9)));\n  Conic_curve_2 c4(1,0,0,0,-1,0,CGAL::COUNTERCLOCKWISE,\n                   Conic_point_2(Algebraic(3), Algebraic(9)),\n                   Conic_point_2(Algebraic(5), Algebraic(25)));\n  Conic_curve_2 c5(0,1,0,1,0,0, CGAL::COUNTERCLOCKWISE,\n                   Conic_point_2(Algebraic(-25), Algebraic(-5)),\n                   Conic_point_2(Algebraic(0), Algebraic(0)));\n\n  Conic_curve_2 c6(1,1,0,6,-26,162,CGAL::COUNTERCLOCKWISE,\n                   Conic_point_2(Algebraic(-7), Algebraic(13)),\n                   Conic_point_2(Algebraic(-3), Algebraic(9)));\n  Conic_curve_2 c7(1,0,0,0,-1,0,CGAL::COUNTERCLOCKWISE,\n                   Conic_point_2(Algebraic(-3), Algebraic(9)),\n                   Conic_point_2(Algebraic(0), Algebraic(0)));\n  Conic_curve_2 c8(0,1,0,-1,0,0, CGAL::COUNTERCLOCKWISE,\n                   Conic_point_2(Algebraic(0), Algebraic(0)),\n                   Conic_point_2(Algebraic(4), Algebraic(-2)));\n\n  Conic_curve_2 c9(1,0,0,0,-1,0,CGAL::COUNTERCLOCKWISE,\n                   Conic_point_2(Algebraic(-5), Algebraic(25)),\n                   Conic_point_2(Algebraic(5), Algebraic(25)));\n  Conic_curve_2 c10(58, 72, -48, 0, 0, -360);\n\n  //This vector is used to store curves that will be used to create polycurve\n  std::vector<Conic_curve_2> conic_curves;\n  conic_curves.push_back(c9);\n\n  //construct poly-curve\n  Polycurve_conic_traits_2::Curve_2 conic_polycurve =\n    construct_polycurve(conic_curves.begin(), conic_curves.end());\n\n  Conic_curve_2 c11(0,1,0,-1,0,0,CGAL::COUNTERCLOCKWISE,\n                     Conic_point_2(Algebraic(25), Algebraic(-5)),\n                     Conic_point_2(Algebraic(0), Algebraic(0)));\n  Conic_curve_2 c12(1,0,0,0,-1,0,CGAL::COUNTERCLOCKWISE,\n                     Conic_point_2(Algebraic(0), Algebraic(0)),\n                     Conic_point_2(Algebraic(5), Algebraic(25)));\n  conic_curves.clear();\n  conic_curves.push_back(c11);\n  conic_curves.push_back(c12);\n\n  //construct poly-curve\n  Polycurve_conic_traits_2::Curve_2 conic_polycurve_2 =\n    construct_polycurve(conic_curves.begin(), conic_curves.end());\n\n  /* VERY IMPORTANT\n   * For efficiency reasons, we recommend users not to construct\n   * x-monotone conic arc directly, but rather use the Make_x_monotone_2\n   * functor supplied by the conic-arc traits class to convert conic curves\n   * to x-monotone curves.\n   */\n  Conic_x_monotone_curve_2 xc3(c3);\n  Conic_x_monotone_curve_2 xc4(c4);\n  Conic_x_monotone_curve_2 xc5(c5);\n  Conic_x_monotone_curve_2 xc6(c6);\n  Conic_x_monotone_curve_2 xc7(c7);\n  Conic_x_monotone_curve_2 xc8(c8);\n\n\n  //This vector is used to store curves that will be used to create\n  //X-monotone-polycurve\n  std::vector<Conic_x_monotone_curve_2> xmono_conic_curves_2;\n  xmono_conic_curves_2.push_back(xc5);\n  xmono_conic_curves_2.push_back(xc3);\n  xmono_conic_curves_2.push_back(xc4);\n\n\n  //construct x-monotone poly-curve\n  Pc_x_monotone_curve_2 conic_x_mono_polycurve_1 =\n    construct_x_mono_polycurve(xmono_conic_curves_2.begin(),\n                               xmono_conic_curves_2.end());\n\n  xmono_conic_curves_2.clear();\n  xmono_conic_curves_2.push_back(xc6);\n  xmono_conic_curves_2.push_back(xc7);\n  xmono_conic_curves_2.push_back(xc8);\n  //construct x-monotone poly-curve\n  Pc_x_monotone_curve_2 conic_x_mono_polycurve_2 =\n    construct_x_mono_polycurve(xmono_conic_curves_2.begin(),\n                               xmono_conic_curves_2.end());\n\n  xmono_conic_curves_2.clear();\n  xmono_conic_curves_2.push_back(xc5);\n\n  Pc_x_monotone_curve_2 x_polycurve_push =\n    construct_x_mono_polycurve(xmono_conic_curves_2.begin(),\n                               xmono_conic_curves_2.end());\n  Polycurve_conic_traits_2::X_monotone_subcurve_2 xcurve_push =\n    Polycurve_conic_traits_2::X_monotone_subcurve_2(c5);\n  //traits.construct_x_monotone_curve_2_object()(c5);\n\n  xmono_conic_curves_2.clear();\n  xmono_conic_curves_2.push_back(xc3);\n  xmono_conic_curves_2.push_back(xc4);\n  Pc_x_monotone_curve_2 base_curve =\n    construct_x_mono_polycurve(xmono_conic_curves_2.begin(),\n                               xmono_conic_curves_2.end());\n\n  //curves for push_back\n  Conic_curve_2 c13(1,1,0,-50,12,660,CGAL::COUNTERCLOCKWISE,\n                    Conic_point_2(Algebraic(25), Algebraic(-7)),\n                    Conic_point_2(Algebraic(25), Algebraic(-5)));\n  Conic_curve_2 c14(0,1,0,-1,0,0,CGAL::COUNTERCLOCKWISE,\n                    Conic_point_2(Algebraic(25), Algebraic(-5)),\n                    Conic_point_2(Algebraic(0), Algebraic(0)));\n  Conic_curve_2 c15(-1,0,0,0,1,0,CGAL::COUNTERCLOCKWISE,\n                    Conic_point_2(Algebraic(0), Algebraic(0)),\n                    Conic_point_2(Algebraic(5), Algebraic(25)));\n  conic_curves.clear();\n  conic_curves.push_back(c13);\n  conic_curves.push_back(c14);\n  Polycurve_conic_traits_2::Curve_2 base_curve_push_back =\n    construct_polycurve(conic_curves.begin(), conic_curves.end());\n\n  conic_curves.push_back(c15);\n  Polycurve_conic_traits_2::Curve_2 Expected_push_back_result =\n    construct_polycurve(conic_curves.begin(), conic_curves.end());\n\n  // //checking the orientattion consistency\n  // Conic_curve_2 c21(0,1,0,1,0,0,CGAL::CLOCKWISE,\n  //                  Conic_point_2(Algebraic(9), Algebraic(-3)),\n  //                  Conic_point_2(Algebraic(0), Algebraic(0)));\n  // Conic_curve_2 c20(1,0,0,0,-1,0,CGAL::COUNTERCLOCKWISE,\n  //                   Conic_point_2(Algebraic(0), Algebraic(0)),\n  //                   Conic_point_2(Algebraic(3), Algebraic(9)));\n  //  Conic_x_monotone_curve_2 xc20(c20);\n  //  Conic_x_monotone_curve_2 xc21(c21);\n  //  xmono_conic_curves_2.clear();\n  //  xmono_conic_curves_2.push_back(xc20);\n  // xmono_conic_curves_2.push_back(xc21);\n  // Pc_x_monotone_curve_2 eric_polycurve =\n  //   construct_x_mono_polycurve(xmono_conic_curves_2.begin(),\n  //                              xmono_conic_curves_2.end());\n  // std::cout << \"the polycurve is: \" << eric_polycurve << std::endl;\n\n  // std::cout<< std::endl;\n\n  //check_compare_x_2(xc3, xc5);\n\n  // check_equal();\n  // std::cout<< std::endl;\n\n   //check_intersect(conic_x_mono_polycurve_1, conic_x_mono_polycurve_2);\n   //std::cout<< std::endl;\n\n  // check_compare_end_points_xy_2();\n  // std::cout<< std::endl;\n\n  //check_split(conic_x_mono_polycurve_1, conic_x_mono_polycurve_2);\n  // std::cout<< std::endl;\n\n  //check_make_x_monotne_curve<Point_2, Curve_2>(conic_polycurve_2);\n   //std::cout<< std::endl;\n\n  // check_is_vertical();\n  // std::cout<< std::endl;\n\n  //check_compare_y_at_x_2();\n  //std::cout<< std::endl;\n\n  //adds the segment to the right.\n  //check_push_back(base_curve_push_back, c15);\n  //std::cout<< std::endl;\n\n  //adds the segment to the left.\n  //check_push_front(base_curve, xcurve_push);\n  //std::cout<< std::endl;\n\n  // check_are_mergable();\n  // std::cout<< std::endl;\n\n  // check_merge_2();\n  // std::cout<< std::endl;\n\n  // check_construct_opposite();\n  // std::cout<< std::endl;\n\n  // check_compare_y_at_x_right();\n  // std::cout<< std::endl;\n\n  // check_compare_y_at_x_left();\n  // std::cout<< std::endl;\n  //check_compare_points(conic_x_mono_polycurve_1);\n\n  //number of segments\n  //std::cout << \"Number of segments: \"\n  //          << traits.number_of_points_2_object()(base_curve_push_back)\n  //          << std::endl;\n\n  check_trim(conic_x_mono_polycurve_1, atoi(argv[1]), atoi(argv[2]),\n             atoi(argv[3]), atoi(argv[4]));\n  std::cout << std::endl;\n\n  //std::cout << (atoi(argv[1]) + atoi(argv[2])) << std::endl;\n  // Conic_traits_2 con_traits;\n  // Conic_curve_2 cc3(1,0,0,0,-1,0,CGAL::COUNTERCLOCKWISE,\n  //                   Conic_point_2(Algebraic(0), Algebraic(0)),\n  //                   Conic_point_2(Algebraic(3), Algebraic(9)));\n  // Conic_x_monotone_curve_2 xcc3(cc3);\n  // Conic_point_2       ps2(0, 0);\n  // Conic_point_2       pt2(3, 9);\n  // std::cout << \"conic curve is : \" << xcc3 << std::endl;\n  // Conic_x_monotone_curve_2 trimmed_curve =\n  //   con_traits.trim_2_object()(xc3, ps2, pt2);\n  // std::cout << \"trimmed conic curve is : \" << trimmed_curve << std::endl;\n\n  return 0;\n}\n\n#endif\n", "meta": {"hexsha": "84c33b4d9141b9d1659524713f6d31d6c8e673be", "size": 35820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Arrangement_on_surface_2/test/Arrangement_on_surface_2/test_conic_polycurve.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": "Arrangement_on_surface_2/test/Arrangement_on_surface_2/test_conic_polycurve.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": "Arrangement_on_surface_2/test/Arrangement_on_surface_2/test_conic_polycurve.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": 37.4686192469, "max_line_length": 84, "alphanum_fraction": 0.6806811837, "num_tokens": 11344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5957317739061484}}
{"text": "/*\nCopyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n\nNVIDIA CORPORATION and its licensors retain all intellectual property\nand proprietary rights in and to this software, related documentation\nand any modifications thereto. Any use, reproduction, disclosure or\ndistribution of this software and related documentation without an express\nlicense agreement from NVIDIA CORPORATION is strictly prohibited.\n*/\n#pragma once\n\n#include <Eigen/Eigen>\n\nnamespace isaac {\n\ntemplate <typename K, int N, int M>\nusing Matrix = Eigen::Matrix<K, N, M>;\ntemplate <typename K, int N>\nusing Vector = Eigen::Matrix<K, N, 1>;\n\ntemplate <typename K, int N>\nusing RowVector = Eigen::Matrix<K, 1, N>;\ntemplate <typename K, int N>\nusing ColVector = Eigen::Matrix<K, N, 1>;\n\ntemplate <typename K>\nusing VectorX = Vector<K, Eigen::Dynamic>;\nusing VectorXd = VectorX<double>;\nusing VectorXf = VectorX<float>;\nusing VectorXi = VectorX<int>;\nusing VectorXub = VectorX<uint8_t>;\n\nusing VectorXcf = Eigen::VectorXcf;\n\ntemplate <typename K>\nusing RowVectorX = RowVector<K, Eigen::Dynamic>;\nusing RowVectorXf = RowVectorX<float>;\n\ntemplate <typename K>\nusing ColVectorX = ColVector<K, Eigen::Dynamic>;\nusing ColVectorXf = ColVectorX<float>;\n\ntemplate <typename K>\nusing MatrixX = Matrix<K, Eigen::Dynamic, Eigen::Dynamic>;\nusing MatrixXd = MatrixX<double>;\nusing MatrixXf = MatrixX<float>;\nusing MatrixXi = MatrixX<int>;\n\nusing MatrixXcf = Eigen::MatrixXcf;\n\n#define DEFINE_MATRIX_TYPES(N)            \\\n  template <typename K>                   \\\n  using Matrix##N = Matrix<K, N, N>;      \\\n  using Matrix##N##d = Matrix##N<double>; \\\n  using Matrix##N##f = Matrix##N<float>;  \\\n  using Matrix##N##i = Matrix##N<int>;\n\nDEFINE_MATRIX_TYPES(2)\nDEFINE_MATRIX_TYPES(3)\nDEFINE_MATRIX_TYPES(4)\nDEFINE_MATRIX_TYPES(5)\nDEFINE_MATRIX_TYPES(6)\nDEFINE_MATRIX_TYPES(7)\nDEFINE_MATRIX_TYPES(8)\n\n#undef DEFINE_MATRIX_TYPES\n\n// Matrix types with fixed number of rows but dynamic number of columns.\n// Useful to store and efficiently manipulate sets of geometric entities, e.g. points and planes.\n// 2xN: 2D points in Euclidean coordinates\n// 3xN: 2D points in homogeneous coordinates or 3D points in Euclidean coordinates\n// 4xN: planes or 3D points in homogeneous coordinates\n#define DEFINE_FIXED_ROWS_MATRIX_TYPES(N) \\\n  template <typename K> using Matrix##N##X = Matrix<K, N, Eigen::Dynamic>; \\\n  using Matrix##N##Xd = Matrix##N##X<double>; \\\n  using Matrix##N##Xf = Matrix##N##X<float>; \\\n  using Matrix##N##Xi = Matrix##N##X<int>; \\\n\nDEFINE_FIXED_ROWS_MATRIX_TYPES(2)\nDEFINE_FIXED_ROWS_MATRIX_TYPES(3)\nDEFINE_FIXED_ROWS_MATRIX_TYPES(4)\nDEFINE_FIXED_ROWS_MATRIX_TYPES(5)\nDEFINE_FIXED_ROWS_MATRIX_TYPES(6)\nDEFINE_FIXED_ROWS_MATRIX_TYPES(7)\nDEFINE_FIXED_ROWS_MATRIX_TYPES(8)\n\n#undef DEFINE_FIXED_ROWS_MATRIX_TYPES\n\ntemplate <typename K>\nusing Matrix34 = Matrix<K, 3, 4>;\nusing Matrix34d = Matrix34<double>;\nusing Matrix34f = Matrix34<float>;\nusing Matrix34i = Matrix34<int>;\n\ntemplate <typename K>\nusing Matrix43 = Matrix<K, 4, 3>;\nusing Matrix43d = Matrix43<double>;\nusing Matrix43f = Matrix43<float>;\nusing Matrix43i = Matrix43<int>;\n\n#define DEFINE_VECTOR_TYPES(N)            \\\n  template <typename K>                   \\\n  using Vector##N = Vector<K, N>;         \\\n  using Vector##N##d = Vector##N<double>; \\\n  using Vector##N##f = Vector##N<float>;  \\\n  using Vector##N##i = Vector##N<int>;    \\\n  using Vector##N##ub = Vector##N<uint8_t>;\n\nDEFINE_VECTOR_TYPES(2)\nDEFINE_VECTOR_TYPES(3)\nDEFINE_VECTOR_TYPES(4)\nDEFINE_VECTOR_TYPES(5)\nDEFINE_VECTOR_TYPES(6)\nDEFINE_VECTOR_TYPES(7)\nDEFINE_VECTOR_TYPES(8)\n\n#undef DEFINE_VECTOR_TYPES\n\ntemplate <typename K>\nusing Quaternion = Eigen::Quaternion<K>;\nusing Quaterniond = Quaternion<double>;\nusing Quaternionf = Quaternion<float>;\n\n// Helper function to compute the sum of two quaternions\ntemplate <typename K>\nQuaternion<K> operator+(const Quaternion<K>& lhs, const Quaternion<K>& rhs) {\n  return Quaternion<K>(lhs.coeffs() + rhs.coeffs());\n}\n// Helper function to compute the difference of two quaternions\ntemplate <typename K>\nQuaternion<K> operator-(const Quaternion<K>& lhs, const Quaternion<K>& rhs) {\n  return Quaternion<K>(lhs.coeffs() - rhs.coeffs());\n}\n// Unary - operator for a quaternion\ntemplate <typename K>\nQuaternion<K> operator-(const Quaternion<K>& q) {\n  return Quaternion<K>(-q.coeffs());\n}\n\ntemplate <typename K>\nusing EigenImage = Eigen::Array<K, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\ntemplate <typename K>\nusing EigenImageMap = Eigen::Map<EigenImage<K>>;\ntemplate <typename K>\nusing EigenImageConstMap = Eigen::Map<const EigenImage<K>>;\n\n// A base helper for constructing Views of data as eigen matrix maps.\ntemplate <typename K, int Rows = Eigen::Dynamic, int Cols = Eigen::Dynamic, int MatrixOptions = 0,\n          int MapOptions = 0, int OuterStride = 0, int InnerStride = 0>\nusing EigenMatrixView = Eigen::Map<Eigen::Matrix<K, Rows, Cols, MatrixOptions>, MapOptions,\n                                   Eigen::Stride<OuterStride, InnerStride>>;\n\n// A base helper for constructing const Views of data as eigen matrix maps.\ntemplate <typename K, int Rows = Eigen::Dynamic, int Cols = Eigen::Dynamic, int MatrixOptions = 0,\n          int MapOptions = 0, int OuterStride = 0, int InnerStride = 0>\nusing EigenMatrixConstView = Eigen::Map<const Eigen::Matrix<K, Rows, Cols, MatrixOptions>,\n                                        MapOptions, Eigen::Stride<OuterStride, InnerStride>>;\n\n// A base helper for constructing Views of data as eigen vector maps.\ntemplate <typename K, int Rows = Eigen::Dynamic, int MapOptions = 0,\n          int OuterStride = 0, int InnerStride = 0>\nusing EigenVectorView = Eigen::Map<Eigen::Matrix<K, Rows, 1>, MapOptions,\n                                   Eigen::Stride<OuterStride, InnerStride>>;\n\n// A base helper for constructing const Views of data as eigen vector maps.\ntemplate <typename K, int Rows = Eigen::Dynamic,  int MapOptions = 0,\n          int OuterStride = 0, int InnerStride = 0>\nusing EigenVectorConstView = Eigen::Map<const Eigen::Matrix<K, Rows, 1>, MapOptions,\n                                        Eigen::Stride<OuterStride, InnerStride>>;\n\n// A base helper for constructing Views of data as eigen row vector maps.\ntemplate <typename K, int Cols = Eigen::Dynamic, int MapOptions = 0,\n          int OuterStride = 0, int InnerStride = 0>\nusing EigenRowVectorView = Eigen::Map<Eigen::Matrix<K, 1, Cols, Eigen::RowMajor>, MapOptions,\n                                      Eigen::Stride<OuterStride, InnerStride>>;\n\n// A base helper for constructing const Views of data as eigen row vector maps.\ntemplate <typename K, int Cols = Eigen::Dynamic, int MapOptions = 0,\n          int OuterStride = 0, int InnerStride = 0>\nusing EigenRowVectorConstView = Eigen::Map<const Eigen::Matrix<K, 1, Cols, Eigen::RowMajor>,\n                                           MapOptions, Eigen::Stride<OuterStride, InnerStride>>;\n\n// Creates a Vector from an initializer list\ntemplate <typename K, size_t N>\nVector<K, N> MakeVector(const K (&elements)[N]) {\n  Vector<K, N> result;\n  for (size_t i = 0; i < N; i++) {\n    result[i] = elements[i];\n  }\n  return result;\n}\n\n}  // namespace isaac\n", "meta": {"hexsha": "f5b189512a9e877fdf1aba6144420f8f81089923", "size": 7159, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "engine/engine/core/math/types.hpp", "max_stars_repo_name": "ddr95070/RMIsaac", "max_stars_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "engine/engine/core/math/types.hpp", "max_issues_repo_name": "ddr95070/RMIsaac", "max_issues_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "engine/engine/core/math/types.hpp", "max_forks_repo_name": "ddr95070/RMIsaac", "max_forks_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-28T16:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T16:37:51.000Z", "avg_line_length": 36.9020618557, "max_line_length": 98, "alphanum_fraction": 0.7075010476, "num_tokens": 1791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5957228433607952}}
{"text": "/*\n * This benchmark times the performance of B += sqr(A), where A and B\n * are complex<double> arrays.\n *\n * Note: need to use -mv8 for SPARC v8.\n */\n\n#include <blitz/array.h>\n#include <blitz/timer.h>\n\nBZ_USING_NAMESPACE(blitz)\n\n#include <blitz/vector.h>\n\ntypedef Array<complex<double>,1> CArray;\n\nvoid setup(Array<complex<double>,1>& A, Array<complex<double>,1>& B)\n{\n    int n = A.extent(firstDim);\n\n    for (int i=0; i < n; ++i)\n    {\n        double x=-10.+20./(n-1.0)*i;\n        A(i)=sin(x);\n        B(i)=sin(x);\n    }\n}\n\nvoid version1(CArray& A, CArray& B, int nIters)\n{\n    Timer timer;\n\n    // Array notation\n    setup(A, B);\n    timer.start();\n    for (int i=0; i < nIters; ++i)\n    {\n        B += A*A;\n    }\n    timer.stop();\n    cout << \"Time using array notation b += a*a: \" << timer.elapsedSeconds()\n         << endl;\n}\n\nvoid version2(CArray& A, CArray& B, int nIters)\n{\n    // Array notation, using sqr(a)\n    Timer timer;\n\n    setup(A,B);\n    timer.start();\n    for (int i=0; i < nIters; ++i)\n    {\n        B += sqr(A);\n    }\n    timer.stop();\n    cout << \"Time using array notation b += sqr(a): \" << timer.elapsedSeconds()\n         << endl;\n}\n\nvoid version2c(CArray& A, CArray& B)\n{\n    B += sqr(A);\n}\n\nvoid version2b(CArray& A, CArray& B, int nIters)\n{\n    // Array notation, using sqr(a)\n    Timer timer;\n\n    setup(A,B);\n    timer.start();\n    for (int i=0; i < nIters; ++i)\n    {\n        version2c(A,B);\n    }\n    timer.stop();\n    cout << \"Time using array notation b += sqr(a): \" << timer.elapsedSeconds()\n         << endl;\n}\n\nvoid version3(CArray& A, CArray& B, int nIters)\n{\n    Timer timer;\n\n    int N = A.extent(firstDim);\n\n    // Low-level implementation\n    setup(A,B);\n    timer.start();\n    for (int i=0; i < nIters; ++i)\n    {\n        for (int j=0; j < N; ++j)\n            B(j) += A(j) * A(j);\n    }\n    timer.stop();\n    cout << \"Time using low-level version: \" << timer.elapsedSeconds()\n         << endl;\n}\n\nvoid version4(CArray& A, CArray& B, int nIters)\n{\n    Timer timer;\n\n    struct cmplx {\n        double re, im;\n    };\n    cmplx* a = (cmplx*)A.data();\n    cmplx* b = (cmplx*)B.data();\n    setup(A,B);\n    int N = A.extent(firstDim);\n\n    timer.start();\n    for (int i=0; i < nIters; ++i)\n    {\n        for (int j=0; j < N; ++j)\n        {\n            double ar = a[j].re;\n            double ai = a[j].im;\n            b[j].re += ar*ar - ai*ai;\n            b[j].im += 2 * ar * ai;\n        }\n    }\n    timer.stop();\n    cout << \"Time using really low-level version: \" << timer.elapsedSeconds()\n         << endl;\n}\n           \nint run(int N, int nIters)\n{\n    Array<complex<double>,1> A(N), B(N);\n\n    version1(A,B,nIters);\n    version2(A,B,nIters);\n    version2b(A,B,nIters);\n    version3(A,B,nIters);\n    version4(A,B,nIters);\n\n    return 0;\n}\n\nint main()\n{\n    cout << \"In-cache:\" << endl;\n    run(256,39063);\n\n    cout << endl << \"Out-of-cache:\" << endl;\n    run(1000000,10);\n}\n\n", "meta": {"hexsha": "16526923a20d1fa53d54ae4ea375d8e3b5593d79", "size": 2917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/hao-he.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/hao-he.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/hao-he.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": 19.3178807947, "max_line_length": 79, "alphanum_fraction": 0.5169694892, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.5957167809239864}}
{"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 * Introduction to the header template.\n * For each function FUNC, the file name shall be FUNC.hpp in src/DeemaAlomair folder.\n * Every FUNC shall be replaced with implemented function name.\n * The type of a CFS with FLOAT is CFST<FLOAT>\n * The code shall follow c++17 standard.\n * Only the c++ standard libraries are allowed.\n * C-style code is highly not recommended.\n */\n\n#ifndef FSL_INTEGRAL_H\n#define FSL_INTEGRAL_H\n\n/*Other library inclusion is here*/\n#include <boost/math/quadrature/trapezoidal.hpp>\n/*\ntemplate<class F, class Real>\nReal trapezoidal(F f, Real a, Real b,\n                 Real tol = sqrt(std::numeric_limits<Real>::epsilon()),\n                 size_t max_refinements = 10,\n                 Real* error_estimate = nullptr,\n                 Real* L1 = nullptr);\n*/\n\nnamespace FSL{\ntemplate<class FLOAT, class FUNC>\nFLOAT Integral(FUNC f, FLOAT a, FLOAT b)\n{\n\tusing boost::math::quadrature::trapezoidal;\n\treturn trapezoidal<FUNC, FLOAT>(f, a, b);\n}\n}\n#endif\n\n/*\n * Type N in MIS shall be translated to size_t in C++. \n * This type is already introduced in CFSData.h\n */", "meta": {"hexsha": "dba80a751c89bfd6bd1ec59ddf81c74162b88001", "size": 1092, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Integral.hpp", "max_stars_repo_name": "caobo1994/FourierSeries", "max_stars_repo_head_hexsha": "e6b3cab9409aaaa8071adc82276dc22d82c0575c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Integral.hpp", "max_issues_repo_name": "caobo1994/FourierSeries", "max_issues_repo_head_hexsha": "e6b3cab9409aaaa8071adc82276dc22d82c0575c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-09-18T21:51:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T17:54:25.000Z", "max_forks_repo_path": "src/Integral.hpp", "max_forks_repo_name": "caobo1994/FourierSeries", "max_forks_repo_head_hexsha": "e6b3cab9409aaaa8071adc82276dc22d82c0575c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7368421053, "max_line_length": 86, "alphanum_fraction": 0.684981685, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.5957167729200087}}
{"text": "//qbr clang++ -std=c++11 test.cpp\n//qbr ./a.out --force-colour -b\n\n#include <iostream>\n\n#include \"pathfinding.hpp\"\n\n#define CATCH_CONFIG_MAIN\n#include <catch.hpp>\n#include <vector>\n#include <boost/utility.hpp>\nusing namespace pf;\n\nTEST_CASE( \"SimpleGraph\", \"[graph]\" ) {\n\n\t//the only requirement for a node is that it must implement '=='.\n\tstruct SimpleNode : boost::noncopyable{\n\t\t\n\t\tSimpleNode( char name ) : name(name) {}\n\n\t\tchar name;\n\t\tstd::vector<SimpleNode*>adjacentNodes;\n\n\t\t//you can define the == operator pretty much anyway you'd like\n\t\t//even comparing memory locations works\n\t\tbool operator==(const SimpleNode& rhs) const{\n\t\t\treturn ( this == &rhs );\n\t\t}\n\t};\n\n\tclass SimpleAdaptor : Adaptor<SimpleNode>\n\t{\n\tpublic:\n\t\tusing Adaptor::node_t;\n\t\t\n\t\tstd::vector<node_t*> getAdjacentNodes(const node_t& node){\n\t\t\treturn node.adjacentNodes;\n\t\t}\n\n\t\tunsigned heuristicDistanceBetweenAdjacentNodes(const node_t& a,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   const node_t& b){\n\t\t\treturn 1;\n\t\t}\n\t};\n\n\tSECTION( \"chain\" ) {\n\t\t//\n\t\t//  a--b--c\n\t\t//\t\n\t\tSimpleNode a('a');\n\t\tSimpleNode b('b');\n\t\tSimpleNode c('c');\n\n\t\ta.adjacentNodes.push_back( &b );\n\t\tb.adjacentNodes.push_back( &c );\n\n\t\tSearch<SimpleAdaptor> search( a, c );\n\t\tauto results = search.path();\n\t\tREQUIRE( results.size() == 3 );\n\t\tREQUIRE( results[0]->name == 'a' );\n\t\tREQUIRE( results[1]->name == 'b' );\n\t\tREQUIRE( results[2]->name == 'c' );\n\t}\n\t\n\tSECTION( \"3-node path vs. 2-node path\" ) {\n\t\t//\t  __u__\t\n\t\t//\t /\t   \\\n\t\t//\ts\t\te\n\t\t//\t \\d1_d2/\n\t\t//\n\t\tSimpleNode s('s');\n\t\tSimpleNode u('u');\n\t\tSimpleNode d1('d');\n\t\tSimpleNode d2('D');\n\t\tSimpleNode e('e');\n\t\t\n\t\ts.adjacentNodes.push_back( &u );\n\t\ts.adjacentNodes.push_back( &d1 );\n\t\n\t\td1.adjacentNodes.push_back( &d2 );\n\t\td2.adjacentNodes.push_back( &e );\n\t\t\n\t\tu.adjacentNodes.push_back( &e );\n\t\t\n\t\tSearch<SimpleAdaptor> search( s, e );\n\t\tauto results = search.path();\n\n\t\tREQUIRE( results.size() == 3 );\n\t\tREQUIRE( results[0]->name == 's' );\n\t\tREQUIRE( results[1]->name == 'u' );\n\t\tREQUIRE( results[2]->name == 'e' );\n\t}\n\n}\n\nTEST_CASE( \"Generating node's on the fly\", \"[graph]\" ) {\n\n\tusing namespace std;\n\n\t//std::pair is a perfectly fine node\n\t//it defines '=='.\n\ttypedef std::pair<int,int> MyNode;\n\n\tclass MyAdaptor : Adaptor<MyNode>\n\t{\n\tpublic:\n\t\tusing Adaptor::node_t;\n\t \tconst bool * grid;\n\t\t\n\t\tvector<unique_ptr<node_t> >garbageCollecter;\n\t\tMyAdaptor( const bool * grid ) : grid(grid){\n\t\t}\n\t\t\n\t\tbool validNode( int i, int j ){\n\t\t\tif( ( i >= 5 )||( i < 0 ) )\n\t\t\t\treturn false;\n\t\t\tif( ( j >= 5 )||( j < 0 ) )\n\t\t\t\treturn false;\n\t\t\treturn grid[i+j*5] == 0;\n\t\t}\n\t\t\t\n\t\tnode_t * makeNode( int i, int j ){\n\t\t\treturn new pair<int, int>( i, j);\n\t\t\tgarbageCollecter.push_back(\n\t\t\t\tunique_ptr<std::pair<int, int>>(\n\t\t\t\t\tnew pair<int, int>(i,j)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\treturn garbageCollecter[ garbageCollecter.size() - 1].get();\n\t\t}\n\n\t\tstd::vector<node_t*> getAdjacentNodes(const node_t& node){\n\t\t\t//std::cout << \"getAdjacentNodes(\"<<node.first<<','<<node.second<<\")\\n\";\n\t\t\tstd::vector<std::pair<int,int>*> returnVector;\n\t\t\tint i = node.first;\n\t\t\tint j = node.second;\n\t\t\tif( validNode( i-1, j ) )\n\t\t\t\treturnVector.push_back( makeNode( i-1, j ) );\n\t\t\tif( validNode( i+1, j ) )\n\t\t\t\treturnVector.push_back( makeNode( i+1, j ) );\n\t\t\tif( validNode( i, j-1 ) )\n\t\t\t\treturnVector.push_back( makeNode( i, j-1 ) );\n\t\t\tif( validNode( i, j+1 ) )\n\t\t\t\treturnVector.push_back( makeNode( i, j+1 ) );\n\t\t\treturn returnVector;\n\t\t}\n\n\t\tunsigned heuristicDistanceBetweenAdjacentNodes(const node_t& a,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   const node_t& b){\n\t\t\treturn abs(a.first - b.first + a.second - b.second);\n\t\t}\n\t};\n\n\tSECTION( \"open grid\" ) {\n\t\tconst bool grid[25] =\n\t\t\t\t{\t0,\t0,\t0,\t0,\t0,\n\t\t\t\t\t0,\t0,\t0,\t0,\t0,\n\t\t\t\t\t0,\t0,\t0,\t0,\t0,\n\t\t\t\t\t0,\t0,\t0,\t0,\t0,\n\t\t\t\t\t0,\t0,\t0,\t0,\t0 };\n\t\tSearch<MyAdaptor, const bool *> search(\n\t\t\tstd::pair<int,int>(0,0), std::pair<int,int>(4,4), grid );\n\t\tauto path = search.path();\n\t\tREQUIRE( path.size() == 9 );\n\t}\n\t\n\tSECTION( \"one path grid\" ) {\n\t\tconst bool grid[25] =\n\t\t\t\t{\t0,\t1,\t0,\t0,\t0,\n\t\t\t\t\t0,\t1,\t0,\t0,\t0,\n\t\t\t\t\t0,\t1,\t0,\t0,\t0,\n\t\t\t\t\t0,\t1,\t1,\t1,\t1,\n\t\t\t\t\t0,\t0,\t0,\t0,\t0 };\n\t\tSearch<MyAdaptor, const bool *> search(\n\t\t\tstd::pair<int,int>(0,0), std::pair<int,int>(4,4), grid );\n\t\tauto path = search.path();\n\t\tREQUIRE( path.size() == 9 );\n\t\tREQUIRE( path[4]->first ==0 );\n\t\tREQUIRE( path[4]->second==4 );\n\t}\n\n\tSECTION( \"better lower path grid\" ) {\n\t\tconst bool grid[25] =\n\t\t\t\t{\t0,\t0,\t0,\t0,\t0,\n\t\t\t\t\t0,\t1,\t1,\t1,\t0,\n\t\t\t\t\t0,\t1,\t0,\t0,\t0,\n\t\t\t\t\t0,\t1,\t0,\t1,\t1,\n\t\t\t\t\t0,\t0,\t0,\t0,\t0 };\n\t\tSearch<MyAdaptor, const bool *> search(\n\t\t\tstd::pair<int,int>(0,0), std::pair<int,int>(4,4), grid );\n\t\tauto path = search.path();\n\t\tREQUIRE( path.size() == 9 );\n\t\tREQUIRE( path[4]->first ==0 );\n\t\tREQUIRE( path[4]->second==4 );\n\t}\n\n\t\tSECTION( \"better upper path grid\" ) {\n\t\tconst bool grid[25] =\n\t\t\t\t{\t0,\t0,\t0,\t0,\t0,\n\t\t\t\t\t0,\t1,\t1,\t1,\t0,\n\t\t\t\t\t0,\t1,\t0,\t0,\t0,\n\t\t\t\t\t0,\t1,\t0,\t1,\t0,\n\t\t\t\t\t0,\t0,\t0,\t1,\t0 };\n\t\tSearch<MyAdaptor, const bool *> search(\n\t\t\tstd::pair<int,int>(0,0), std::pair<int,int>(4,4), grid );\n\t\tauto path = search.path();\n\t\tREQUIRE( path.size() == 9 );\n\t\tREQUIRE( path[4]->first ==4 );\n\t\tREQUIRE( path[4]->second==0 );\n\t}\n\n\n\n}\n\nTEST_CASE( \"spied on optimization check\", \"[graph]\" ) {\n\n\tusing namespace std;\n\n\t//std::pair is a perfectly fine node\n\t//it defines '=='.\n\ttypedef std::pair<int,int> MyNode;\n\n\tclass MyAdaptor : Adaptor<MyNode>\n\t{\n\tpublic:\n\t\tusing Adaptor::node_t;\n\t \tconst bool * grid;\n\t\t\n\t\tint &adjacentNodeAskCount;\n\t\t\t\n\t\tvector<unique_ptr<node_t> >garbageCollecter;\n\t\tMyAdaptor( const bool * grid, int &adjacentNodeAskCount ):\n\t\t\tgrid(grid),\n\t\t\tadjacentNodeAskCount( adjacentNodeAskCount ){\n\t\t}\n\t\t\n\t\tbool validNode( int i, int j ){\n\t\t\tif( ( i >= 5 )||( i < 0 ) )\n\t\t\t\treturn false;\n\t\t\tif( ( j >= 5 )||( j < 0 ) )\n\t\t\t\treturn false;\n\t\t\treturn grid[i+j*5] == 0;\n\t\t}\n\t\t\t\n\t\tnode_t * makeNode( int i, int j ){\n\t\t\treturn new pair<int, int>( i, j);\n\t\t\tgarbageCollecter.push_back(\n\t\t\t\tunique_ptr<std::pair<int, int>>(\n\t\t\t\t\tnew pair<int, int>(i,j)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\treturn garbageCollecter[ garbageCollecter.size() - 1].get();\n\t\t}\n\n\t\tstd::vector<node_t*> getAdjacentNodes(const node_t& node){\n\t\t\tadjacentNodeAskCount++;\n\t\t\tstd::vector<std::pair<int,int>*> returnVector;\n\t\t\tint i = node.first;\n\t\t\tint j = node.second;\n\t\t\tif( validNode( i-1, j ) )\n\t\t\t\treturnVector.push_back( makeNode( i-1, j ) );\n\t\t\tif( validNode( i+1, j ) )\n\t\t\t\treturnVector.push_back( makeNode( i+1, j ) );\n\t\t\tif( validNode( i, j-1 ) )\n\t\t\t\treturnVector.push_back( makeNode( i, j-1 ) );\n\t\t\tif( validNode( i, j+1 ) )\n\t\t\t\treturnVector.push_back( makeNode( i, j+1 ) );\n\t\t\treturn returnVector;\n\t\t}\n\n\t\tunsigned heuristicDistanceBetweenAdjacentNodes(const node_t& a,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   const node_t& b){\n\t\t\treturn abs(a.first - b.first + a.second - b.second);\n\t\t}\n\t};\n\n\tSECTION( \"open grid\" ) {\n\t\tconst bool grid[25] =\n\t\t\t\t{\t0,\t0,\t0,\t0,\t0,\n\t\t\t\t\t0,\t0,\t0,\t0,\t0,\n\t\t\t\t\t0,\t0,\t0,\t0,\t0,\n\t\t\t\t\t0,\t0,\t0,\t0,\t0,\n\t\t\t\t\t0,\t0,\t0,\t0,\t0 };\n\t\tint adjacentNodeAskCount = 0;\n\t\tSearch<MyAdaptor, const bool *, int& > search(\n\t\t\tstd::pair<int,int>(0,0),\n\t\t\tstd::pair<int,int>(4,4),\n\t\t\tgrid,\n\t\t\tadjacentNodeAskCount );\n\t\tauto path = search.path();\n\t\tREQUIRE( path.size() == 9 );\n\t\tREQUIRE( adjacentNodeAskCount == 8 );\n\t}\n\n\tSECTION( \"zigzag grid\" ) {\n\t\tconst bool grid[25] =\n\t\t\t\t{\t0,\t1,\t0,\t0,\t0,\n\t\t\t\t\t0,\t1,\t0,\t1,\t0,\n\t\t\t\t\t0,\t1,\t0,\t1,\t0,\n\t\t\t\t\t0,\t1,\t0,\t1,\t0,\n\t\t\t\t\t0,\t0,\t0,\t1,\t0 };\n\t\tint adjacentNodeAskCount = 0;\n\t\tSearch<MyAdaptor, const bool *, int& > search(\n\t\t\tstd::pair<int,int>(0,0),\n\t\t\tstd::pair<int,int>(4,4),\n\t\t\tgrid,\n\t\t\tadjacentNodeAskCount );\n\t\tauto path = search.path();\n\t\tREQUIRE( path.size() == 17 );\n\t\tREQUIRE( adjacentNodeAskCount == 16 );\n\t}\n\n\tSECTION( \"lowerpath better grid\" ) {\n\t\tconst bool grid[25] =\n\t\t\t\t{\t0,\t0,\t0,\t0,\t0,\n\t\t\t\t\t0,\t1,\t1,\t1,\t0,\n\t\t\t\t\t0,\t1,\t0,\t0,\t0,\n\t\t\t\t\t0,\t1,\t0,\t1,\t1,\n\t\t\t\t\t0,\t0,\t0,\t0,\t0 };\n\t\tint adjacentNodeAskCount = 0;\n\t\tSearch<MyAdaptor, const bool *, int& > search(\n\t\t\tstd::pair<int,int>(0,0),\n\t\t\tstd::pair<int,int>(4,4),\n\t\t\tgrid,\n\t\t\tadjacentNodeAskCount );\n\t\tauto path = search.path();\n\t\tREQUIRE( path.size() == 9 );\n\t\tREQUIRE( adjacentNodeAskCount == 8 );\n\t}\n\n\tSECTION( \"upper path better grid\" ) {\n\t\tconst bool grid[25] =\n\t\t\t\t{\t0,\t0,\t0,\t0,\t0,\n\t\t\t\t\t0,\t1,\t1,\t1,\t0,\n\t\t\t\t\t0,\t1,\t0,\t0,\t0,\n\t\t\t\t\t0,\t1,\t0,\t1,\t0,\n\t\t\t\t\t0,\t0,\t0,\t1,\t0 };\n\t\tint adjacentNodeAskCount = 0;\n\t\tSearch<MyAdaptor, const bool *, int& > search(\n\t\t\tstd::pair<int,int>(0,0),\n\t\t\tstd::pair<int,int>(4,4),\n\t\t\tgrid,\n\t\t\tadjacentNodeAskCount );\n\t\tauto path = search.path();\n\t\tREQUIRE( path.size() == 9 );\n\t\tREQUIRE( adjacentNodeAskCount == 8 );\n\t}\n\n\n\n}\n", "meta": {"hexsha": "dcf7504670442080bda59d7539f882ad6ce6130e", "size": 8415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test.cpp", "max_stars_repo_name": "coryknapp/pathfinding", "max_stars_repo_head_hexsha": "49ea5aa08d074b5705c0dfbff115ad4f665dbb54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-05T17:59:36.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-05T17:59:36.000Z", "max_issues_repo_path": "test.cpp", "max_issues_repo_name": "coryknapp/pathfinding", "max_issues_repo_head_hexsha": "49ea5aa08d074b5705c0dfbff115ad4f665dbb54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test.cpp", "max_forks_repo_name": "coryknapp/pathfinding", "max_forks_repo_head_hexsha": "49ea5aa08d074b5705c0dfbff115ad4f665dbb54", "max_forks_repo_licenses": ["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.8385269122, "max_line_length": 75, "alphanum_fraction": 0.5757575758, "num_tokens": 3064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.5957167727246062}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[make_3d_point\n//` Using make to construct a three dimensional point\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n\nint main()\n{\n    typedef boost::geometry::model::point<double, 3, boost::geometry::cs::cartesian> point_type;\n    point_type p = boost::geometry::make<point_type>(1, 2, 3);\n    std::cout << boost::geometry::dsv(p) << std::endl;\n    return 0;\n}\n\n//]\n\n\n//[make_3d_point_output\n/*`\nOutput:\n[pre\n(1, 2, 3)\n]\n*/\n//]\n", "meta": {"hexsha": "88349894b2d8e56ce2e03ea7d235ff84ef74b8ea", "size": 813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/make_3d_point.cpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/make_3d_point.cpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/make_3d_point.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.972972973, "max_line_length": 96, "alphanum_fraction": 0.7011070111, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.595673347089121}}
{"text": "//#####################################################################\n//  Copyright (c) 2011-2019 Nathan Mitchell, Eftychios Sifakis, Yutian Tao.\n//  This file is covered by the FreeBSD license. Please refer to the\n//  license.txt file for more information.\n//#####################################################################\n\n\n//#include <PhysBAM_Tools/Matrices/MATRIX_3X3.h>\n#include <iostream>\n#include <iomanip>\n#include <bitset> // for bitset\n#include <type_traits> // for is_same\n#include <stdexcept> // for logic error\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace{\n\n    namespace {\n        typedef union {\n            int i;\n            float f;\n        } floatConverter;\n\n        typedef union {\n            long long int i;\n            double f;\n        } doubleConverter;\n    }\n\n    template<class T>\n        void Print_Bdiff(const T C[9], const T C_reference[9], std::ostream& output);\n\n    template<>\n        void Print_Bdiff(const float C[9], const float C_reference[9], std::ostream& output)\n    {\n        floatConverter cvt;\n        floatConverter cvt_ref;\n        for (int i=0; i<9; i++) {\n            cvt.f = C[i];\n            cvt_ref.f = C_reference[i];\n                output << std::bitset<32>(cvt.i^cvt_ref.i)<<std::endl;\n        }\n    }\n\n    template<>\n        void Print_Bdiff(const double C[9], const double C_reference[9], std::ostream& output)\n    {\n        doubleConverter cvt;\n        doubleConverter cvt_ref;\n        for (int i=0; i<9; i++) {\n            cvt.f = C[i];\n            cvt_ref.f = C_reference[i];\n            output << std::bitset<64>(cvt.i^cvt_ref.i)<<std::endl;\n        }\n    }\n\ntemplate<class T_MATRIX>\n    void Print_Formatted(const T_MATRIX& A,std::ostream& output)\n{\n    for(int i=0;i<A.rows();i++){\n        for(int j=0;j<A.cols();j++){\n            output<<std::setw(12)<<A(i,j);\n            if(j<A.cols()-1) output<<\" \";}\n        output<<std::endl;}\n}\n}\n\ntemplate<class T>\nvoid Matrix_Times_Matrix_Reference(const T A[9], const T B[9], T C[9])\n{\n    Map<const Matrix<T,3,3>> mA=Map<const Matrix<T,3,3>>(A);\n    Map<const Matrix<T,3,3>> mB=Map<const Matrix<T,3,3>>(B);\n    Map<Matrix<T,3,3>> mC=Map<Matrix<T,3,3>>(C);\n\n    mC=mA*mB;\n}\n\ntemplate<class T>\nbool Matrix_Times_Matrix_Compare(const T C[9], const T C_reference[9])\n{\n    Map<const Matrix<T,3,3>> mC=Map<const Matrix<T,3,3>>(C);\n    Map<const Matrix<T,3,3>> mC_reference=Map<const Matrix<T,3,3>>(C_reference);\n\n    std::cout<<\"Computed matrix C :\"<<std::endl;Print_Formatted(mC,std::cout);\n    std::cout<<\"Reference matrix C :\"<<std::endl;Print_Formatted(mC_reference,std::cout);\n    std::cout<<\"Difference = \"<<(mC-mC_reference).norm()<<std::endl;\n    Print_Bdiff(C, C_reference, std::cout);\n    if( (mC-mC_reference).norm() < 0.00001 )\n        return true;\n    else\n        return false;\n}\n\ntemplate void Matrix_Times_Matrix_Reference(const float A[9], const float B[9], float C[9]);\ntemplate bool Matrix_Times_Matrix_Compare(const float C[9], const float C_reference[9]);\n\ntemplate void Matrix_Times_Matrix_Reference(const double A[9], const double B[9], double C[9]);\ntemplate bool Matrix_Times_Matrix_Compare(const double C[9], const double C_reference[9]);\n", "meta": {"hexsha": "6aa762a6855d1135017bbf7a9c79e52a0a2b7b21", "size": 3188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simd-numeric-kernels-new/References/Matrix_Times_Matrix/Matrix_Times_Matrix_Reference.cpp", "max_stars_repo_name": "uwgraphics/SkinFlaps", "max_stars_repo_head_hexsha": "28f66f768514347ff16a75b569aaa4274b73353a", "max_stars_repo_licenses": ["BSD-2-Clause", "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": "simd-numeric-kernels-new/References/Matrix_Times_Matrix/Matrix_Times_Matrix_Reference.cpp", "max_issues_repo_name": "uwgraphics/SkinFlaps", "max_issues_repo_head_hexsha": "28f66f768514347ff16a75b569aaa4274b73353a", "max_issues_repo_licenses": ["BSD-2-Clause", "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": "simd-numeric-kernels-new/References/Matrix_Times_Matrix/Matrix_Times_Matrix_Reference.cpp", "max_forks_repo_name": "uwgraphics/SkinFlaps", "max_forks_repo_head_hexsha": "28f66f768514347ff16a75b569aaa4274b73353a", "max_forks_repo_licenses": ["BSD-2-Clause", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5643564356, "max_line_length": 95, "alphanum_fraction": 0.5915934755, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5956733334600125}}
{"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": "#ifndef _BOOSTSPATIALINDEX_SHAPE\n#define _BOOSTSPATIALINDEX_SHAPE\n#include <memory>\n#include <string>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/box.hpp>\n\nenum ShapeType {bbox, circle, annulus, poly};\n\ntypedef boost::geometry::model::point<double, 2, boost::geometry::cs::geographic<boost::geometry::degree>> point;\ntypedef boost::geometry::model::box<point> box;\ntypedef boost::geometry::model::polygon<point, false, false> polygon;\n\nclass Shape {\n  protected:\n    std::string id;\n    ShapeType type;\n    box envelope; // the minimum bounding rectangle embedding the provided shape\n    box envelopeFromCircle(point const& p, double radius);\n    double getDistance(point const& origin, point const& p);\n\n    /*\n     * shape-specific storage objects\n     * (boxes do not need those as the envelope already describe these)\n     */\n    // - circle and annulus\n    point center;\n    double outerRadius;\n    //std::pair<double, double>\n\n    // annulus\n    double innerRadius;\n\n    // polygon\n    polygon polygonShape;\n\n  public:\n    // Registers a box shape\n    Shape(std::string id_, box const& b);\n\n    // Registers a circle shape. Radius must be in meters\n    Shape(std::string id_, point const& p, double radius);\n\n    // Registers an annulus shape. Radiuses must be in meters\n    Shape(std::string id_, point const& p, double outerRadius_, double innerRadius_);\n\n    // Registers a polygon shape\n    Shape(std::string id_, polygon const& p);\n\n    // getters\n    const char *getId();\n    box getEnvelope();\n\n    // others\n    bool covered(point const& p);\n};\n\n#endif\n", "meta": {"hexsha": "e568bae528c93d3918ef44d30ea58d2b2df944fa", "size": 1589, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/shape.hpp", "max_stars_repo_name": "aswinsreedhar/boost-geospatial-index", "max_stars_repo_head_hexsha": "1614a1715558adc2edd2bff2839f7a6084ffef1a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2016-10-26T09:12:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T22:45:44.000Z", "max_issues_repo_path": "src/shape.hpp", "max_issues_repo_name": "aswinsreedhar/boost-geospatial-index", "max_issues_repo_head_hexsha": "1614a1715558adc2edd2bff2839f7a6084ffef1a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-12-24T07:30:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T21:56:15.000Z", "max_forks_repo_path": "src/shape.hpp", "max_forks_repo_name": "aswinsreedhar/boost-geospatial-index", "max_forks_repo_head_hexsha": "1614a1715558adc2edd2bff2839f7a6084ffef1a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-12-24T07:30:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T14:55:22.000Z", "avg_line_length": 26.9322033898, "max_line_length": 113, "alphanum_fraction": 0.6928886092, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5956707623015514}}
{"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": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file TransformTests.cpp\n/// \\brief Unit tests for the implementation of the transformation matrix class.\n/// \\details Unit tests for the various Lie Group functions will test both\n/// special cases,\n///          and randomly generated cases.\n///\n/// \\author Sean Anderson\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <gtest/gtest.h>\n\n#include <math.h>\n#include <iomanip>\n#include <ios>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <lgmath/CommonMath.hpp>\n\n#include <lgmath/se3/Operations.hpp>\n#include <lgmath/se3/Transformation.hpp>\n#include <lgmath/so3/Operations.hpp>\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n///\n/// UNIT TESTS OF TRANSFORMATION MATRIX\n///\n/////////////////////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General test of transformation constructors\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, TransformationConstructors) {\n  // Generate random transform from most basic constructor\n  Eigen::Matrix<double, 3, 3> C_ba =\n      lgmath::so3::vec2rot(Eigen::Matrix<double, 3, 1>::Random());\n  Eigen::Matrix<double, 3, 1> r_ba_ina = Eigen::Matrix<double, 3, 1>::Random();\n  lgmath::se3::Transformation rand(C_ba, r_ba_ina);\n\n  // Transformation();\n  {\n    lgmath::se3::Transformation tmatrix;\n    Eigen::Matrix4d test = Eigen::Matrix4d::Identity();\n    std::cout << \"tmat: \" << tmatrix.matrix() << std::endl;\n    std::cout << \"test: \" << test << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(tmatrix.matrix(), test, 1e-6));\n  }\n\n  // Transformation(const Transformation& T);\n  {\n    lgmath::se3::Transformation test(rand);\n    std::cout << \"tmat: \" << rand.matrix() << std::endl;\n    std::cout << \"test: \" << test.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(rand.matrix(), test.matrix(), 1e-6));\n  }\n\n  // Transformation(const Eigen::Matrix4d& T);\n  {\n    lgmath::se3::Transformation test(rand.matrix());\n    std::cout << \"tmat: \" << rand.matrix() << std::endl;\n    std::cout << \"test: \" << test.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(rand.matrix(), test.matrix(), 1e-6));\n\n    // Test forced reprojection (ones to identity)\n    Eigen::Matrix4d proj_test = Eigen::Matrix4d::Identity();\n    proj_test.topRightCorner<3, 1>() = -r_ba_ina;\n    Eigen::Matrix3d notRotation = Eigen::Matrix3d::Ones();\n    Eigen::Matrix4d notTransform = Eigen::Matrix4d::Identity();\n    notTransform.topLeftCorner<3, 3>() = notRotation;\n    notTransform.topRightCorner<3, 1>() = -r_ba_ina;\n    lgmath::se3::Transformation test_bad(notTransform);  // force reproj\n    std::cout << \"cmat: \" << proj_test.matrix() << std::endl;\n    std::cout << \"test: \" << test_bad.matrix() << std::endl;\n    EXPECT_TRUE(\n        lgmath::common::nearEqual(proj_test.matrix(), test_bad.matrix(), 1e-6));\n  }\n\n  // Transformation& operator=(Transformation T);\n  {\n    lgmath::se3::Transformation test = rand;\n    std::cout << \"tmat: \" << rand.matrix() << std::endl;\n    std::cout << \"test: \" << test.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(rand.matrix(), test.matrix(), 1e-6));\n  }\n\n  // Transformation(const Eigen::Matrix<double,6,1>& vec, unsigned int numTerms\n  // = 0);\n  {\n    Eigen::Matrix<double, 6, 1> vec = Eigen::Matrix<double, 6, 1>::Random();\n    Eigen::Matrix4d tmat = lgmath::se3::vec2tran(vec);\n    lgmath::se3::Transformation testAnalytical(vec);\n    lgmath::se3::Transformation testNumerical(vec, 15);\n    std::cout << \"tmat: \" << tmat << std::endl;\n    std::cout << \"testAnalytical: \" << testAnalytical.matrix() << std::endl;\n    std::cout << \"testNumerical: \" << testNumerical.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(tmat, testAnalytical.matrix(), 1e-6));\n    EXPECT_TRUE(lgmath::common::nearEqual(tmat, testNumerical.matrix(), 1e-6));\n  }\n\n  // Transformation(const Eigen::VectorXd& vec);\n  {\n    Eigen::VectorXd vec = Eigen::Matrix<double, 6, 1>::Random();\n    Eigen::Matrix4d tmat = lgmath::se3::vec2tran(vec);\n    lgmath::se3::Transformation test(vec);\n    std::cout << \"tmat: \" << tmat << std::endl;\n    std::cout << \"test: \" << test.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(tmat, test.matrix(), 1e-6));\n  }\n\n  // Transformation(const Eigen::VectorXd& vec);\n  {\n    Eigen::VectorXd vec = Eigen::Matrix<double, 6, 1>::Random();\n    lgmath::se3::Transformation test(vec);\n\n    // Wrong size vector\n    Eigen::VectorXd badvec = Eigen::Matrix<double, 3, 1>::Random();\n    lgmath::se3::Transformation testFailure;\n    try {\n      testFailure = lgmath::se3::Transformation(badvec);\n    } catch (const std::invalid_argument& e) {\n      testFailure = test;\n    }\n    std::cout << \"tmat: \" << testFailure.matrix() << std::endl;\n    std::cout << \"test: \" << test.matrix() << std::endl;\n    EXPECT_TRUE(\n        lgmath::common::nearEqual(testFailure.matrix(), test.matrix(), 1e-6));\n  }\n\n  // Transformation(const Eigen::Matrix3d& C_ba,\n  //               const Eigen::Vector3d& r_ba_ina);\n  {\n    lgmath::se3::Transformation tmat(C_ba, r_ba_ina);\n    Eigen::Matrix4d test = Eigen::Matrix4d::Identity();\n    test.topLeftCorner<3, 3>() = C_ba;\n    test.topRightCorner<3, 1>() = -C_ba * r_ba_ina;\n    std::cout << \"tmat: \" << tmat.matrix() << std::endl;\n    std::cout << \"test: \" << test << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(tmat.matrix(), test, 1e-6));\n\n    // Test forced reprojection (ones to identity)\n    Eigen::Matrix4d proj_test = Eigen::Matrix4d::Identity();\n    proj_test.topRightCorner<3, 1>() = -Eigen::Matrix3d::Identity() * r_ba_ina;\n    Eigen::Matrix3d notRotation = Eigen::Matrix3d::Ones();\n    lgmath::se3::Transformation test_bad(notRotation,\n                                         r_ba_ina);  // forces reprojection\n    std::cout << \"cmat: \" << proj_test.matrix() << std::endl;\n    std::cout << \"test: \" << test_bad.matrix() << std::endl;\n    EXPECT_TRUE(\n        lgmath::common::nearEqual(proj_test.matrix(), test_bad.matrix(), 1e-6));\n  }\n\n  // Transformation(Transformation&&);\n  {\n    auto rand2 = rand;\n    lgmath::se3::Transformation test(std::move(rand));\n    rand = rand2;\n\n    std::cout << \"tmat: \" << test.matrix() << std::endl;\n    std::cout << \"test: \" << rand.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(test.matrix(), rand.matrix(), 1e-6));\n  }\n\n  // Transformation = Transformation&&;\n  {\n    lgmath::se3::Transformation test;\n    auto rand2 = rand;\n    test = std::move(rand);\n    rand = rand2;\n\n    std::cout << \"tmat: \" << test.matrix() << std::endl;\n    std::cout << \"test: \" << rand.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(test.matrix(), rand.matrix(), 1e-6));\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Test some get methods\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, TransformationGetMethods) {\n  // Generate random transform from most basic constructor\n  Eigen::Matrix<double, 3, 3> C_ba =\n      lgmath::so3::vec2rot(Eigen::Matrix<double, 3, 1>::Random());\n  Eigen::Matrix<double, 3, 1> r_ba_ina = Eigen::Matrix<double, 3, 1>::Random();\n  lgmath::se3::Transformation T_ba(C_ba, r_ba_ina);\n\n  // Construct simple eigen matrix from random rotation and translation\n  Eigen::Matrix4d test = Eigen::Matrix4d::Identity();\n  Eigen::Matrix<double, 3, 1> r_ab_inb = -C_ba * r_ba_ina;\n  test.topLeftCorner<3, 3>() = C_ba;\n  test.topRightCorner<3, 1>() = r_ab_inb;\n\n  // Test matrix()\n  std::cout << \"T_ba: \" << T_ba.matrix() << std::endl;\n  std::cout << \"test: \" << test << std::endl;\n  EXPECT_TRUE(lgmath::common::nearEqual(T_ba.matrix(), test, 1e-6));\n\n  // Test C_ba()\n  std::cout << \"T_ba: \" << T_ba.C_ba() << std::endl;\n  std::cout << \"C_ba: \" << C_ba << std::endl;\n  EXPECT_TRUE(lgmath::common::nearEqual(T_ba.C_ba(), C_ba, 1e-6));\n\n  // Test r_ba_ina()\n  std::cout << \"T_ba: \" << T_ba.r_ba_ina() << std::endl;\n  std::cout << \"r_ba_ina: \" << r_ba_ina << std::endl;\n  EXPECT_TRUE(lgmath::common::nearEqual(T_ba.r_ba_ina(), r_ba_ina, 1e-6));\n\n  // Test r_ab_inb()\n  std::cout << \"T_ba: \" << T_ba.r_ab_inb() << std::endl;\n  std::cout << \"r_ab_inb: \" << r_ab_inb << std::endl;\n  EXPECT_TRUE(lgmath::common::nearEqual(T_ba.r_ab_inb(), r_ab_inb, 1e-6));\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Test exponential map construction and logarithmic vec() method\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, TransformationToFromSE3Algebra) {\n  // Add vectors to be tested\n  std::vector<Eigen::Matrix<double, 6, 1> > trueVecs;\n  Eigen::Matrix<double, 6, 1> temp;\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 1.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 1.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 1.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, -lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, -lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, -lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  const unsigned numRand = 20;\n  for (unsigned i = 0; i < numRand; i++) {\n    trueVecs.push_back(Eigen::Matrix<double, 6, 1>::Random());\n  }\n\n  // Get number of tests\n  const unsigned numTests = trueVecs.size();\n\n  // Calc transformation matrices\n  std::vector<Eigen::Matrix4d> transMatrices;\n  for (unsigned i = 0; i < numTests; i++) {\n    transMatrices.push_back(lgmath::se3::vec2tran(trueVecs.at(i)));\n  }\n\n  // Calc transformations\n  std::vector<lgmath::se3::Transformation> transformations;\n  for (unsigned i = 0; i < numTests; i++) {\n    transformations.push_back(lgmath::se3::Transformation(trueVecs.at(i)));\n  }\n\n  // Compare matrices\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      std::cout << \"matr: \" << transMatrices.at(i) << std::endl;\n      std::cout << \"tran: \" << transformations.at(i).matrix() << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(\n          transMatrices.at(i), transformations.at(i).matrix(), 1e-6));\n    }\n  }\n\n  // Test logarithmic map\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      Eigen::Matrix<double, 6, 1> testVec = transformations.at(i).vec();\n      std::cout << \"true: \" << trueVecs.at(i) << std::endl;\n      std::cout << \"func: \" << testVec << std::endl;\n      EXPECT_TRUE(\n          lgmath::common::nearEqualLieAlg(trueVecs.at(i), testVec, 1e-6));\n    }\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Test inverse, adjoint and operatations\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, TransformationInverse) {\n  // Add vectors to be tested\n  std::vector<Eigen::Matrix<double, 6, 1> > trueVecs;\n  Eigen::Matrix<double, 6, 1> temp;\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 1.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 1.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 1.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, -lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, -lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, -lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  const unsigned numRand = 20;\n  for (unsigned i = 0; i < numRand; i++) {\n    trueVecs.push_back(Eigen::Matrix<double, 6, 1>::Random());\n  }\n\n  // Get number of tests\n  const unsigned numTests = trueVecs.size();\n\n  // Add vectors to be tested - random\n  std::vector<Eigen::Matrix<double, 4, 1> > landmarks;\n  for (unsigned i = 0; i < numTests; i++) {\n    landmarks.push_back(Eigen::Matrix<double, 4, 1>::Random());\n  }\n\n  // Calc transformation matrices\n  std::vector<Eigen::Matrix4d> transMatrices;\n  for (unsigned i = 0; i < numTests; i++) {\n    transMatrices.push_back(lgmath::se3::vec2tran(trueVecs.at(i)));\n  }\n\n  // Calc transformations\n  std::vector<lgmath::se3::Transformation> transformations;\n  for (unsigned i = 0; i < numTests; i++) {\n    transformations.push_back(lgmath::se3::Transformation(trueVecs.at(i)));\n  }\n\n  // Compare inverse to basic matrix inverse\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      std::cout << \"matr: \" << transMatrices.at(i).inverse() << std::endl;\n      std::cout << \"tran: \" << transformations.at(i).inverse().matrix()\n                << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(\n          transMatrices.at(i).inverse(),\n          transformations.at(i).inverse().matrix(), 1e-6));\n    }\n  }\n\n  // Test that product of inverse and self make identity\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      std::cout << \"T*Tinv: \"\n                << transformations.at(i).matrix() *\n                       transformations.at(i).inverse().matrix();\n      EXPECT_TRUE(lgmath::common::nearEqual(\n          transformations.at(i).matrix() *\n              transformations.at(i).inverse().matrix(),\n          Eigen::Matrix4d::Identity(), 1e-6));\n    }\n  }\n\n  // Test adjoint\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      std::cout << \"matr: \" << lgmath::se3::tranAd(transMatrices.at(i))\n                << std::endl;\n      std::cout << \"tran: \" << transformations.at(i).adjoint() << std::endl;\n      EXPECT_TRUE(\n          lgmath::common::nearEqual(lgmath::se3::tranAd(transMatrices.at(i)),\n                                    transformations.at(i).adjoint(), 1e-6));\n    }\n  }\n\n  // Test self-product\n  {\n    for (unsigned i = 0; i < numTests - 1; i++) {\n      lgmath::se3::Transformation test = transformations.at(i);\n      test *= transformations.at(i + 1);\n      Eigen::Matrix4d matrix = transMatrices.at(i) * transMatrices.at(i + 1);\n      std::cout << \"matr: \" << matrix << std::endl;\n      std::cout << \"tran: \" << test.matrix() << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(matrix, test.matrix(), 1e-6));\n    }\n  }\n\n  // Test product\n  {\n    for (unsigned i = 0; i < numTests - 1; i++) {\n      lgmath::se3::Transformation test =\n          transformations.at(i) * transformations.at(i + 1);\n      Eigen::Matrix4d matrix = transMatrices.at(i) * transMatrices.at(i + 1);\n      std::cout << \"matr: \" << matrix << std::endl;\n      std::cout << \"tran: \" << test.matrix() << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(matrix, test.matrix(), 1e-6));\n    }\n  }\n\n  // Test self product with inverse\n  {\n    for (unsigned i = 0; i < numTests - 1; i++) {\n      lgmath::se3::Transformation test = transformations.at(i);\n      test /= transformations.at(i + 1);\n      Eigen::Matrix4d matrix =\n          transMatrices.at(i) * transMatrices.at(i + 1).inverse();\n      std::cout << \"matr: \" << matrix << std::endl;\n      std::cout << \"tran: \" << test.matrix() << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(matrix, test.matrix(), 1e-6));\n    }\n  }\n\n  // Test product with inverse\n  {\n    for (unsigned i = 0; i < numTests - 1; i++) {\n      lgmath::se3::Transformation test =\n          transformations.at(i) / transformations.at(i + 1);\n      Eigen::Matrix4d matrix =\n          transMatrices.at(i) * transMatrices.at(i + 1).inverse();\n      std::cout << \"matr: \" << matrix << std::endl;\n      std::cout << \"tran: \" << test.matrix() << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(matrix, test.matrix(), 1e-6));\n    }\n  }\n\n  // Test product with landmark\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      Eigen::Matrix<double, 4, 1> mat = transMatrices.at(i) * landmarks.at(i);\n      Eigen::Matrix<double, 4, 1> test =\n          transformations.at(i) * landmarks.at(i);\n\n      std::cout << \"matr: \" << mat << std::endl;\n      std::cout << \"test: \" << test << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(mat, test, 1e-6));\n    }\n  }\n}\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "87261b01989756b72605f7837154d3fdb96748da", "size": 17459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TransformTests.cpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "tests/TransformTests.cpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "tests/TransformTests.cpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 38.5408388521, "max_line_length": 94, "alphanum_fraction": 0.5711667335, "num_tokens": 5426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.595639946343016}}
{"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// acvf.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_HPP_ER_2008_04\n#define BOOST_ACCUMULATORS_STATISTICS_ACVF_HPP_ER_2008_04\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/placeholders.hpp>\n\n#include <boost/call_traits.hpp>\n#include <boost/array.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/type_traits/add_const.hpp>\n\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/delay.hpp> // in accumulators_filter\n\nnamespace boost { namespace accumulators\n{\n\n\nnamespace impl\n{\n    ////////////////////////////////////////////////////////////////////////////\n    // acvf_impl (Autocovariance function)\n    //\n    template<typename T,typename I>\n    class acvf_impl\n      : public accumulator_base\n    {\n\t   typedef std::vector<T>                       acvs_type;\n       typedef delay_impl<T,I>                      delay_type;\n\t   typedef typename delay_type::result_type     input_type;\n    public:\n        typedef I discriminator_type;\n\n        typedef boost::iterator_range<\n            typename acvs_type::const_iterator\n        > result_type;\n\n        template<typename Args>\n        acvf_impl(Args const &args)\n        :acvs(\n            args[tag::delay<I>::cache_size|delay(args).size()],\n            static_cast<T>(0)\n        )\n        {\n        }\n\n        acvf_impl(const acvf_impl& that)\n        :acvs(that.acvs){}\n\n        acvf_impl& operator=(const acvf_impl& that){\n            if(&that!=this){\n                acvs = that.acvs;\n            } \n            return *this;\n        }\n\n        template<typename Args>\n        void operator ()(Args const &args)\n        {\n          input_type in = delay(args); //0,1,2,...,K\n          typedef typename input_type::const_iterator  in_iter_type;\n          typedef typename acvs_type::iterator         out_iter_type;\n          std::size_t in_sz = in.size();\n\n          BOOST_ASSERT((in_sz<acvs.size())||(in_sz==acvs.size()));\n          in_iter_type i = begin(in);\n          in_iter_type e = end(in);\n\n          T x0 = (*i);\n          std::size_t n = count(args);\n          std::size_t k = 0;\n\t\t  while((k<in_sz) && (n>1+k)){\n\t\t      BOOST_ASSERT(i<e);\n              T xk = (*i);\n              T div = (T) ((n-1)-k);\n              T sum_prod = acvs[k] * div;\n              T mean_val = mean(args);\n              sum_prod += (xk - mean_val) * (x0 - mean_val);\n              div = (T)(n-k);\n              acvs[k] = sum_prod / div;\n              ++i;\n              ++k;\n          }\n\t\t}\n\n        result_type result(dont_care) const\n        {\n          return boost::make_iterator_range(acvs.begin(),acvs.end());\n        }\n\n    private:\n\t   acvs_type   acvs;\n\n    };\n\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::acvf\n//\n\nnamespace tag\n{\n    template <typename I = default_delay_discriminator>\n    struct acvf\n      : depends_on<count, mean, delay<I> >\n    {\n        /// INTERNAL ONLY\n      typedef accumulators::impl::acvf_impl<mpl::_1,I> impl;\n\n    };\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::acvf\n//\n\nnamespace extract\n{\n//  extractor<tag::acvf<> > const acvf = {};\n//  //a non-default discriminator requires\n//  //struct my_other_delay {};\n//  //extractor<tag::delay<my_other_delay> > other_delay={};\n\n  template<typename I,typename AccumulatorSet>\n  typename\n    mpl::apply<AccumulatorSet,tag::acvf<I> >::type::result_type\n  acvf(AccumulatorSet const& acc){\n    typedef tag::acvf<I> the_tag;\n    return extract_result<the_tag>(acc);\n  }//typical call://acvf<default_delay_discriminator>(acc)\n\n//  TODO\n//  //overload\n//  template<typename AccumulatorSet>\n//  typename mpl::apply<AccumulatorSet,tag::acvf<> >::type::result_type\n//  acvf(AccumulatorSet const& acc){\n//    return acvf<default_delay_discriminator,AccumulatorSet>(acc);\n//  }\n// /../boost_1_35_0/boost/mpl/aux_/preprocessed/gcc/apply_wrap.hpp|39|error: no\n// class template named \u2018apply\u2019\n// in \u2018struct boost::accumulators::default_delay_discriminator\u2019|\n\n}\n\nusing extract::acvf;\n\n\n}} // namespace boost::accumulators\n\n#endif\n", "meta": {"hexsha": "ce6a9491a44b5d52e24283c63065d2d112c2c3e1", "size": 5167, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "autocovariance/boost/accumulators/statistics/acvf.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.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.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8670520231, "max_line_length": 80, "alphanum_fraction": 0.55854461, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5956367304418162}}
{"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). \ufffdLong lines on the spheroid.\ufffd Surv. Rev., XVI(125), 301\ufffd309.\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": "/* boost random/exponential_distribution.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: exponential_distribution.hpp,v 1.1 2007/02/12 18:25:54 irving Exp $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_EXPONENTIAL_DISTRIBUTION_HPP\n#define BOOST_RANDOM_EXPONENTIAL_DISTRIBUTION_HPP\n\n#include <cmath>\n#include <cassert>\n#include <iostream>\n#include <boost/limits.hpp>\n#include <boost/static_assert.hpp>\n\nnamespace boost {\n\n// exponential distribution: p(x) = lambda * exp(-lambda * x)\ntemplate<class RealType = double>\nclass exponential_distribution\n{\npublic:\n  typedef RealType input_type;\n  typedef RealType result_type;\n\n#if !defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS) && !(defined(BOOST_MSVC) && BOOST_MSVC <= 1300)\n  BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);\n#endif\n\n  explicit exponential_distribution(result_type lambda = result_type(1))\n    : _lambda(lambda) { assert(lambda > result_type(0)); }\n\n  // compiler-generated copy ctor and assignment operator are fine\n\n  result_type lambda() const { return _lambda; }\n\n  void reset() { }\n\n  template<class Engine>\n  result_type operator()(Engine& eng)\n  { \n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::log;\n#endif\n    return -result_type(1) / _lambda * log(result_type(1)-eng());\n  }\n\n#if !defined(BOOST_NO_OPERATORS_IN_NAMESPACE) && !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)\n  template<class CharT, class Traits>\n  friend std::basic_ostream<CharT,Traits>&\n  operator<<(std::basic_ostream<CharT,Traits>& os, const exponential_distribution& ed)\n  {\n    os << ed._lambda;\n    return os;\n  }\n\n  template<class CharT, class Traits>\n  friend std::basic_istream<CharT,Traits>&\n  operator>>(std::basic_istream<CharT,Traits>& is, exponential_distribution& ed)\n  {\n    is >> std::ws >> ed._lambda;\n    return is;\n  }\n#endif\n\nprivate:\n  result_type _lambda;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_EXPONENTIAL_DISTRIBUTION_HPP\n", "meta": {"hexsha": "cd4a5511d83422c73397696dc1d36792e4eb427d", "size": 2215, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/random/exponential_distribution.hpp", "max_stars_repo_name": "schinmayee/nimbus", "max_stars_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-07-03T19:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T02:53:56.000Z", "max_issues_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/random/exponential_distribution.hpp", "max_issues_repo_name": "schinmayee/nimbus", "max_issues_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/random/exponential_distribution.hpp", "max_forks_repo_name": "schinmayee/nimbus", "max_forks_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T02:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-31T00:12:01.000Z", "avg_line_length": 27.012195122, "max_line_length": 100, "alphanum_fraction": 0.7426636569, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5956367253241406}}
{"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": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <cmath>\n#include <cfloat>\n#include <cstdint>\n#include <limits>\n#include <type_traits>\n#include <boost/math/ccmath/remainder.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\n#if !defined(BOOST_MATH_NO_CONSTEXPR_DETECTION) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\ntemplate <typename T>\nconstexpr void test()\n{\n    // Error Handling\n    if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    {\n        static_assert(boost::math::ccmath::isnan(boost::math::ccmath::remainder(std::numeric_limits<T>::quiet_NaN(), T(1))), \"If x is NaN, NaN is returned\");\n        static_assert(boost::math::ccmath::isnan(boost::math::ccmath::remainder(T(1), std::numeric_limits<T>::quiet_NaN())), \"If y is NaN, NaN is returned\");\n    }\n\n    static_assert(boost::math::ccmath::isnan(boost::math::ccmath::remainder(std::numeric_limits<T>::infinity(), T(1))));\n    static_assert(boost::math::ccmath::isnan(boost::math::ccmath::remainder(-std::numeric_limits<T>::infinity(), T(1))));\n    static_assert(boost::math::ccmath::isnan(boost::math::ccmath::remainder(T(1), T(0))));\n    static_assert(boost::math::ccmath::isnan(boost::math::ccmath::remainder(T(1), T(-0))));\n\n    // Functionality\n    static_assert(boost::math::ccmath::remainder(T(6), T(2)) == T(0));\n    static_assert(boost::math::ccmath::remainder(T(3.0/2), T(1.0) == T(3.0/2)));\n    static_assert(boost::math::ccmath::remainder(T(7.0/3), T(2.0) == T(1.0/3)));\n    static_assert(boost::math::ccmath::remainder(T(-8.0/3), T(2.0) == T(-2.0/3)));\n    static_assert(boost::math::ccmath::remainder(T(-0), T(1)) == T(-0));\n    \n    // Not exact values but pulled from https://en.cppreference.com/w/cpp/numeric/math/remainder as general functionality tests so allow for some error\n    // std::is_floating_point_v excludes multi-precision types\n    if constexpr (std::is_floating_point_v<T>)\n    {\n        static_assert(boost::math::ccmath::abs(boost::math::ccmath::remainder(T(5.1l), T(3.0l)) - T(-0.9l)) < 2*std::numeric_limits<T>::epsilon());\n        static_assert(boost::math::ccmath::abs(boost::math::ccmath::remainder(T(-5.1l), T(3.0l)) - T(0.9l)) < 2*std::numeric_limits<T>::epsilon());\n        static_assert(boost::math::ccmath::abs(boost::math::ccmath::remainder(T(5.1l), T(-3.0l)) - T(-0.9l)) < 2*std::numeric_limits<T>::epsilon());\n        static_assert(boost::math::ccmath::abs(boost::math::ccmath::remainder(T(-5.1l), T(-3.0l)) - T(0.9l)) < 2*std::numeric_limits<T>::epsilon());\n    }\n\n    // Correct promoted types\n    if constexpr (!std::is_same_v<T, float>)\n    {\n        constexpr auto test_type = boost::math::ccmath::remainder(T(1), 1.0f);\n        static_assert(std::is_same_v<T, std::remove_cv_t<decltype(test_type)>>);\n    }\n    else\n    {\n        constexpr auto test_type = boost::math::ccmath::remainder(1.0f, 1);\n        static_assert(std::is_same_v<double, std::remove_cv_t<decltype(test_type)>>);\n    }\n}\n\nint main()\n{\n    test<float>();\n    test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test<long double>();\n    #endif\n    \n    #ifdef BOOST_HAS_FLOAT128\n    test<boost::multiprecision::float128>();\n    #endif\n\n    return 0;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif", "meta": {"hexsha": "ac5ebd981715521ceb37e6cd9217054b074c6e9e", "size": 3511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_remainder_test.cpp", "max_stars_repo_name": "cenit/math", "max_stars_repo_head_hexsha": "8e8f6ec4be96723b0ce9399bbc297b02a7da4fe1", "max_stars_repo_licenses": ["BSL-1.0"], "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/ccmath_remainder_test.cpp", "max_issues_repo_name": "cenit/math", "max_issues_repo_head_hexsha": "8e8f6ec4be96723b0ce9399bbc297b02a7da4fe1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/ccmath_remainder_test.cpp", "max_forks_repo_name": "cenit/math", "max_forks_repo_head_hexsha": "8e8f6ec4be96723b0ce9399bbc297b02a7da4fe1", "max_forks_repo_licenses": ["BSL-1.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.3058823529, "max_line_length": 157, "alphanum_fraction": 0.6684705212, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5956367199269879}}
{"text": "#include <limits>\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <rsvd/Constants.hpp>\n#include <rsvd/ErrorEstimators.hpp>\n#include <rsvd/RandomizedSvd.hpp>\n\nusing Eigen::Index;\n\ntemplate <typename T> struct RandomizedSvd : public ::testing::Test {\n  using MatrixType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\n  const Index numRows = 50;\n  const Index numCols = 25;\n  const Index rank = 5;\n  const unsigned int prngSeed = 777;\n};\n\nusing NumericalTypes = ::testing::Types<float, double, std::complex<float>, std::complex<double>>;\n\nTYPED_TEST_CASE(RandomizedSvd, NumericalTypes, );\n\nTYPED_TEST(RandomizedSvd, ExactRankApproximationNoConditioner) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  const MatrixType m = MatrixType::Random(TestFixture::numRows, TestFixture::rank) *\n                       MatrixType::Random(TestFixture::rank, TestFixture::numCols);\n\n  Eigen::JacobiSVD<MatrixType> svd(m, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  const MatrixType reconstructedSvd =\n      svd.matrixU() * svd.singularValues().asDiagonal() * svd.matrixV().adjoint();\n  const auto relErrSvd = Rsvd::relativeFrobeniusNormError(m, reconstructedSvd);\n\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n  Rsvd::RandomizedSvd<MatrixType, std::mt19937_64, Rsvd::NoConditioner> rsvd(randomEngine);\n  rsvd.compute(m, TestFixture::rank);\n  const MatrixType reconstructedRsvd =\n      rsvd.matrixU() * rsvd.singularValues().asDiagonal() * rsvd.matrixV().adjoint();\n  const auto relErrRsvd = Rsvd::relativeFrobeniusNormError(m, reconstructedRsvd);\n\n  ASSERT_LE(relErrRsvd, 1.15 * relErrSvd);\n}\n\nTYPED_TEST(RandomizedSvd, ExactRankApproximationLuConditioner) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  const MatrixType m = MatrixType::Random(TestFixture::numRows, TestFixture::rank) *\n                       MatrixType::Random(TestFixture::rank, TestFixture::numCols);\n\n  Eigen::JacobiSVD<MatrixType> svd(m, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  const MatrixType reconstructedSvd =\n      svd.matrixU() * svd.singularValues().asDiagonal() * svd.matrixV().adjoint();\n  const auto relErrSvd = Rsvd::relativeFrobeniusNormError(m, reconstructedSvd);\n\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n  Rsvd::RandomizedSvd<MatrixType, std::mt19937_64, Rsvd::LuConditioner> rsvd(randomEngine);\n  rsvd.compute(m, TestFixture::rank);\n  const MatrixType reconstructedRsvd =\n      rsvd.matrixU() * rsvd.singularValues().asDiagonal() * rsvd.matrixV().adjoint();\n  const auto relErrRsvd = Rsvd::relativeFrobeniusNormError(m, reconstructedRsvd);\n\n  ASSERT_LE(relErrRsvd, 1.05 * relErrSvd);\n}\n\nTYPED_TEST(RandomizedSvd, ExactRankApproximationMgsConditioner) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  const MatrixType m = MatrixType::Random(TestFixture::numRows, TestFixture::rank) *\n                       MatrixType::Random(TestFixture::rank, TestFixture::numCols);\n\n  Eigen::JacobiSVD<MatrixType> svd(m, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  const MatrixType reconstructedSvd =\n      svd.matrixU() * svd.singularValues().asDiagonal() * svd.matrixV().adjoint();\n  const auto relErrSvd = Rsvd::relativeFrobeniusNormError(m, reconstructedSvd);\n\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n  Rsvd::RandomizedSvd<MatrixType, std::mt19937_64, Rsvd::MgsConditioner> rsvd(randomEngine);\n  rsvd.compute(m, TestFixture::rank);\n  const MatrixType reconstructedRsvd =\n      rsvd.matrixU() * rsvd.singularValues().asDiagonal() * rsvd.matrixV().adjoint();\n  const auto relErrRsvd = Rsvd::relativeFrobeniusNormError(m, reconstructedRsvd);\n\n  ASSERT_LE(relErrRsvd, 1.30 * relErrSvd);\n}\n\nTYPED_TEST(RandomizedSvd, OversamplingMgsConditioner) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  const MatrixType m = MatrixType::Random(TestFixture::numRows, TestFixture::rank) *\n                       MatrixType::Random(TestFixture::rank, TestFixture::numCols);\n\n  Eigen::JacobiSVD<MatrixType> svd(m, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  const MatrixType reconstructedSvd =\n      svd.matrixU() * svd.singularValues().asDiagonal() * svd.matrixV().adjoint();\n  const auto relErrSvd = Rsvd::relativeFrobeniusNormError(m, reconstructedSvd);\n\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n  Rsvd::RandomizedSvd<MatrixType, std::mt19937_64, Rsvd::MgsConditioner> rsvd(randomEngine);\n  // Oversample (twice the rank)\n  rsvd.compute(m, TestFixture::rank, TestFixture::rank);\n  const MatrixType reconstructedRsvd =\n      rsvd.matrixU() * rsvd.singularValues().asDiagonal() * rsvd.matrixV().adjoint();\n  const auto relErrRsvd = Rsvd::relativeFrobeniusNormError(m, reconstructedRsvd);\n\n  ASSERT_LE(relErrRsvd, 1.30 * relErrSvd);\n}\n\nTYPED_TEST(RandomizedSvd, ExactRankApproximationQrConditioner) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n  const MatrixType m = MatrixType::Random(TestFixture::numRows, TestFixture::rank) *\n                       MatrixType::Random(TestFixture::rank, TestFixture::numCols);\n\n  Eigen::JacobiSVD<MatrixType> svd(m, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  const MatrixType reconstructedSvd =\n      svd.matrixU() * svd.singularValues().asDiagonal() * svd.matrixV().adjoint();\n  const auto relErrSvd = Rsvd::relativeFrobeniusNormError(m, reconstructedSvd);\n\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n  Rsvd::RandomizedSvd<MatrixType, std::mt19937_64, Rsvd::QrConditioner> rsvd(randomEngine);\n  rsvd.compute(m, TestFixture::rank);\n  const MatrixType reconstructedRsvd =\n      rsvd.matrixU() * rsvd.singularValues().asDiagonal() * rsvd.matrixV().adjoint();\n  const auto relErrRsvd = Rsvd::relativeFrobeniusNormError(m, reconstructedRsvd);\n\n  ASSERT_LE(relErrRsvd, 1.05 * relErrSvd);\n}\n", "meta": {"hexsha": "241d7b3aa9215759a0f3a5093f4b4c41cd03bf7b", "size": 6009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/RandomizedSvd.cpp", "max_stars_repo_name": "valerii-filev-picsart/rsvd", "max_stars_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/RandomizedSvd.cpp", "max_issues_repo_name": "valerii-filev-picsart/rsvd", "max_issues_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/RandomizedSvd.cpp", "max_forks_repo_name": "valerii-filev-picsart/rsvd", "max_forks_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9214285714, "max_line_length": 98, "alphanum_fraction": 0.7458811782, "num_tokens": 1782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5956085336704432}}
{"text": "//\n// Copyright 1997, University of Notre Dame.\n// Authors: Andrew Lumsdaine, Jeremy G. Siek\n//\n// This file is part of the Matrix Template Library\n//\n// You should have received a copy of the License Agreement for the\n// Matrix Template Library along with the software;  see the\n// file LICENSE.  If not, contact Office of Research, University of Notre\n// Dame, Notre Dame, IN  46556.\n//\n// Permission to modify the code and to distribute modified code is\n// granted, provided the text of this NOTICE is retained, a notice that\n// the code was modified is included with the above COPYRIGHT NOTICE and\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\n// file is distributed with the modified code.\n//\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n// By way of example, but not limitation, Licensor MAKES NO\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n// OR OTHER RIGHTS.\n//\n// $Id: symm_matvec_mult.cc 1749 2004-01-27 00:01:18Z gabrielt $\n//\n\n#include <mtl/dense1D.h>\n#include <mtl/mtl.h>\n#include <mtl/matrix.h>\n\n\n/*\n\n  Sample Output\n\n  A in full form:\n  4x4\n  [\n  [1,2,3,4],\n  [2,5,6,7],\n  [3,6,8,9],\n  [4,7,9,10]\n  ]\n  x:\n  [2,2,2,2,]\n  y:\n  [4000,5000,6000,7000,]\n  Ax + y:\n  [20,40,52,60,]\n  \n\n */\n\nusing namespace mtl;\n\n//begin\ntypedef matrix<double, symmetric<lower>, array< dense<> >, row_major>::type Matrix;\ntypedef dense1D<double> Vector;\n//end\n\nint\nmain()\n{\n  typedef Matrix::size_type sizeT;\n  sizeT i, j;\n  const sizeT N = 4;\n  //begin\n  Matrix A(N);\n  Vector x(N);\n  Vector y(N);\n  //end\n  //         1  2  3  4       2       4000\n  //\n  //     A = 2  5  6  7   x = 2   y = 5000\n  //\n  //         3  6  8  9       2       6000\n  //\n  //         4  7  9 10       2       7000\n\n  int c = 0;\n  for (i = 0; i < N; ++i)\n    for (j = i; j < N; ++j)\n      A(i,j) = ++c;\n\n  for (i = 0; i < N; ++i) {\n    x[i] = 2;\n    y[i] = (i + 4) * 1000;\n  }\n\n  std::cout << \"A in full form:\" << std::endl;\n  print_all_matrix(A);\n\n  std::cout << \"x:\" << std::endl;\n  print_vector(x);\n\n  std::cout << \"y:\" << std::endl;\n  print_vector(y);\n  //begin\n  mult(A, x, y);\n\n  std::cout << \"Ax + y:\" << std::endl;\n  print_vector(y);\n  //end\n  return 0;\n}\n", "meta": {"hexsha": "a2a5ea66dfd9d8bc29a517b9d4df8000c4551e68", "size": 2362, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/symm_matvec_mult.cc", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/symm_matvec_mult.cc", "max_issues_repo_name": "parasol-ppl/PPL_utils", "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/symm_matvec_mult.cc", "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0747663551, "max_line_length": 83, "alphanum_fraction": 0.6096528366, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.5956085290868094}}
{"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": "#ifndef MLT_MODELS_OPTIMIZABLE_LINEAR_MODEL_HPP\n#define MLT_MODELS_OPTIMIZABLE_LINEAR_MODEL_HPP\n\n#include <tuple>\n#include <type_traits>\n\n#include <Eigen/Core>\n\n#include \"../defs.hpp\"\n#include \"../utils/eigen.hpp\"\n#include \"../utils/linear_algebra.hpp\"\n\nnamespace mlt {\nnamespace models {\n\ttemplate <class LinearBase, class Loss, class Optimizer>\n\tclass OptimizableLinearModel : public LinearBase {\n\tpublic:\n\t\tSelf& fit(Features input, Target target, bool cold_start = true) {\n\t\t\tauto target_matrix = _to_target_matrix(target);\n\t\t\tauto init = _fitted && !cold_start ? coefficients() : (MatrixXd::Random(target_matrix.rows(), input.rows() + (fit_intercept() ? 1 : 0)) * 0.005).eval();\n\t\t\t_set_coefficients(_optimizer(*this, input, target_matrix, init, cold_start));\n\n\t\t\treturn _self();\n\t\t}\n\n\t\tauto loss(MatrixXdRef coeffs, Features input, MatrixXdRef target) const {\n\t\t\tauto l = _loss.loss(_apply_linear_transformation(input, coeffs), target);\n\t\t\tif (_fit_intercept) {\n\t\t\t\treturn l + _regularization * (coeffs.leftCols(coeffs.cols() - 1).array().pow(2).sum());\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn l + _regularization * (coeffs.array().pow(2).sum());\n\t\t\t}\n\t\t}\n\n\t\tauto gradient(MatrixXdRef coeffs, Features input, MatrixXdRef target) const {\n\t\t\tauto g = _loss.gradient(_apply_linear_transformation(input, coeffs), target);\n\n\t\t\tif (_fit_intercept) {\n\t\t\t\tauto full_g = MatrixXd::Zero(coeffs.rows(), coeffs.cols()).eval();\n\t\t\t\tfull_g.leftCols(coeffs.cols() - 1) = g * input.transpose() + _regularization * 2 * coeffs.leftCols(coeffs.cols() - 1);\n\t\t\t\tfull_g.rightCols<1>() = g.rowwise().sum();\n\t\t\t\treturn full_g;\n\t\t\t} else {\n\t\t\t\treturn (g * input.transpose() + _regularization * 2 * coeffs).eval();\n\t\t\t}\n\t\t}\n\n\t\tauto loss_and_gradient(MatrixXdRef coeffs, Features input, MatrixXdRef target) const {\n\t\t\tdouble l;\n\t\t\tMatrixXd g;\n\n\t\t\ttie(l, g) = _loss.loss_and_gradient(_apply_linear_transformation(input, coeffs), target);\n\t\t\tif (_fit_intercept) {\n\t\t\t\tauto full_g = MatrixXd::Zero(coeffs.rows(), coeffs.cols()).eval();\n\t\t\t\tfull_g.leftCols(coeffs.cols() - 1) = g * input.transpose() + _regularization * 2 * coeffs.leftCols(coeffs.cols() - 1);\n\t\t\t\tfull_g.rightCols<1>() = g.rowwise().sum();\n\t\t\t\treturn make_tuple(l + _regularization * (coeffs.leftCols(coeffs.cols() - 1).array().pow(2).sum()) , full_g);\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn make_tuple(l + _regularization * coeffs.array().pow(2).sum(), (g * input.transpose() + _regularization * 2 * coeffs).eval());\n\t\t\t}\n\t\t}\n\n\tprotected:\n\t\ttemplate <class L, class O, class = enable_if<is_same<decay_t<L>, Loss>::value && is_convertible<decay_t<O>, Optimizer>::value>>\n\t\texplicit OptimizableLinearModel(L&& loss, O&& optimizer, double regularization, bool fit_intercept) : LinearBase(fit_intercept), _loss(forward<L>(loss)), _optimizer(forward<O>(optimizer)), _regularization(regularization) {}\n\n\t\tLoss _loss;\n\t\tOptimizer _optimizer;\n\t\tdouble _regularization;\n\t};\n}\n}\n#endif\t", "meta": {"hexsha": "a61dc72ec0c3990d39bad2975d385bfe94ed5d6d", "size": 2893, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/models/optimizable_linear_model.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/optimizable_linear_model.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/optimizable_linear_model.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": 38.5733333333, "max_line_length": 225, "alphanum_fraction": 0.6978914622, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.5954413950754639}}
{"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": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#include \"catch.hpp\"\n\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n\n\n#include <Eigen/Core>\n\n#include \"bi_operators/CollocationIntegrator.hpp\"\n#include \"green/DerivativeTypes.hpp\"\n#include \"green/SphericalDiffuse.hpp\"\n#include \"green/dielectric_profile/OneLayerErf.hpp\"\n#include \"green/dielectric_profile/OneLayerTanh.hpp\"\n\nSCENARIO(\"Evaluation of the spherical diffuse Green's function and its derivatives\", \"[green][green_spherical_diffuse]\")\n{\n    GIVEN(\"A permittivity profile modelled by the hyperbolic tangent function\")\n    {\n        int maxL = 3;\n        // High dielectric constant inside\n        double eps1 = 80.0;\n        // Low dielectric constant outside\n        double eps2 = 2.0;\n        double sphereRadius = 100.0;\n        double width = 5.0;\n        // Evaluation inside the sphere\n        Eigen::Vector3d source1 = (Eigen::Vector3d() << 1.0, 0.0, 0.0).finished();\n        Eigen::Vector3d sourceNormal1 = source1;\n        sourceNormal1.normalize();\n        Eigen::Vector3d probe1 = (Eigen::Vector3d() << 2.0, 0.0, 0.0).finished();\n        Eigen::Vector3d probeNormal1 = probe1;\n        probeNormal1.normalize();\n        // Evaluation outside the sphere\n        Eigen::Vector3d source2 = (Eigen::Vector3d() << 150.0, 150.0, 150.0).finished();\n        Eigen::Vector3d sourceNormal2 = source2;\n        sourceNormal2.normalize();\n        Eigen::Vector3d probe2 = (Eigen::Vector3d() << 151.0, 150.0, 150.0).finished();\n        Eigen::Vector3d probeNormal2 = probe2;\n        probeNormal2.normalize();\n        WHEN(\"the spherical droplet is centered at the origin\")\n        {\n            Eigen::Vector3d sphereCenter = Eigen::Vector3d::Zero();\n            SphericalDiffuse<> gf(eps1, eps2, width, sphereRadius, sphereCenter, maxL);\n            THEN(\"the value of the Green's function inside the droplet is\")\n            {\n                double value = 0.012507311388168523;\n                double gf_value = gf.kernelS(source1, probe1);\n                INFO(\"ref_value = \" << std::setprecision(std::numeric_limits<long double>::digits10) << value);\n                INFO(\"gf_value  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_value);\n                REQUIRE(value == Approx(gf_value));\n            }\n            AND_THEN(\"the value of the Green's function outside the droplet is\")\n            {\n                double value = 0.50004567416494572;\n                double gf_value = gf.kernelS(source2, probe2);\n                INFO(\"ref_value = \" << std::setprecision(std::numeric_limits<long double>::digits10) << value);\n                INFO(\"gf_value  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_value);\n                REQUIRE(value == Approx(gf_value));\n            }\n            THEN(\"the value of the Green's function directional derivative wrt the probe point inside the droplet is\")\n            {\n                double derProbe = -0.012506305835640469;\n                double gf_derProbe = gf.derivativeProbe(probeNormal1, source1, probe1);\n                INFO(\"ref_derProbe = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derProbe);\n                INFO(\"gf_derProbe  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derProbe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the probe point outside the droplet is\")\n            {\n                double derProbe = -0.29005549287308696;\n                double gf_derProbe = gf.derivativeProbe(probeNormal2, source2, probe2);\n                INFO(\"ref_derProbe = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derProbe);\n                INFO(\"gf_derProbe  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derProbe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            THEN(\"the value of the Green's function directional derivative wrt the source point inside the droplet is\")\n            {\n                double derSource = 0.012498621932118328;\n                double gf_derSource = gf.derivativeSource(sourceNormal1, source1, probe1);\n                INFO(\"ref_derSource = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derSource);\n                INFO(\"gf_derSource  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derSource);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the source point outside the droplet is\")\n            {\n                double derSource = 0.28879776627577236;\n                double gf_derSource = gf.derivativeSource(sourceNormal2, source2, probe2);\n                INFO(\"ref_derSource = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derSource);\n                INFO(\"gf_derSource  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derSource);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n        }\n\n        AND_WHEN(\"the spherical droplet is centered away from the origin\")\n        {\n            Eigen::Vector3d sphereCenter = (Eigen::Vector3d() << 25.0, 0.0, 0.0).finished();\n            SphericalDiffuse<> gf(eps1, eps2, width, sphereRadius, sphereCenter, maxL);\n            THEN(\"the value of the Green's function inside the droplet is\")\n            {\n                double value = 0.0125233347669694017;\n                double gf_value = gf.kernelS(source1, probe1);\n                INFO(\"ref_value = \" << std::setprecision(std::numeric_limits<long double>::digits10) << value);\n                INFO(\"gf_value  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_value);\n                REQUIRE(value == Approx(gf_value));\n            }\n            AND_THEN(\"the value of the Green's function outside the droplet is\")\n            {\n                double value = 0.5000329900631173;\n                double gf_value = gf.kernelS(source2, probe2);\n                INFO(\"ref_value = \" << std::setprecision(std::numeric_limits<long double>::digits10) << value);\n                INFO(\"gf_value  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_value);\n                REQUIRE(value == Approx(gf_value));\n            }\n            THEN(\"the value of the Green's function directional derivative wrt the probe point inside the droplet is\")\n            {\n                double derProbe = -0.0125024363466751109;\n                double gf_derProbe = gf.derivativeProbe(probeNormal1, source1, probe1);\n                INFO(\"ref_derProbe = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derProbe);\n                INFO(\"gf_derProbe  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derProbe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the probe point outside the droplet is\")\n            {\n                double derProbe = -0.289999709125188243;\n                double gf_derProbe = gf.derivativeProbe(probeNormal2, source2, probe2);\n                INFO(\"ref_derProbe = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derProbe);\n                INFO(\"gf_derProbe  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derProbe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            THEN(\"the value of the Green's function directional derivative wrt the source point inside the droplet is\")\n            {\n                double derSource = 0.0124899030052444404;\n                double gf_derSource = gf.derivativeSource(sourceNormal1, source1, probe1);\n                INFO(\"ref_derSource = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derSource);\n                INFO(\"gf_derSource  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derSource);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the source point outside the droplet is\")\n            {\n                double derSource = 0.288657584958107449;\n                double gf_derSource = gf.derivativeSource(sourceNormal2, source2, probe2);\n                INFO(\"ref_derSource = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derSource);\n                INFO(\"gf_derSource  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derSource);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n        }\n    }\n\n    GIVEN(\"A permittivity profile modelled by the error function\")\n    {\n        int maxL = 3;\n        // High dielectric constant inside\n        double eps1 = 80.0;\n        // Low dielectric constant outside\n        double eps2 = 2.0;\n        double sphereRadius = 100.0;\n        double width = 5.0;\n        // Evaluation inside the sphere\n        Eigen::Vector3d source1 = (Eigen::Vector3d() << 1.0, 0.0, 0.0).finished();\n        Eigen::Vector3d sourceNormal1 = source1;\n        sourceNormal1.normalize();\n        Eigen::Vector3d probe1 = (Eigen::Vector3d() << 2.0, 0.0, 0.0).finished();\n        Eigen::Vector3d probeNormal1 = probe1;\n        probeNormal1.normalize();\n        // Evaluation outside the sphere\n        Eigen::Vector3d source2 = (Eigen::Vector3d() << 150.0, 150.0, 150.0).finished();\n        Eigen::Vector3d sourceNormal2 = source2;\n        sourceNormal2.normalize();\n        Eigen::Vector3d probe2 = (Eigen::Vector3d() << 151.0, 150.0, 150.0).finished();\n        Eigen::Vector3d probeNormal2 = probe2;\n        probeNormal2.normalize();\n        WHEN(\"the spherical droplet is centered at the origin\")\n        {\n            Eigen::Vector3d sphereCenter = Eigen::Vector3d::Zero();\n            SphericalDiffuse<CollocationIntegrator, OneLayerErf> gf(eps1, eps2, width, sphereRadius, sphereCenter, maxL);\n            THEN(\"the value of the Green's function inside the droplet is\")\n            {\n                double value = 0.012507311377769814;\n                double gf_value = gf.kernelS(source1, probe1);\n                INFO(\"ref_value = \" << std::setprecision(std::numeric_limits<long double>::digits10) << value);\n                INFO(\"gf_value  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_value);\n                REQUIRE(value == Approx(gf_value));\n            }\n            AND_THEN(\"the value of the Green's function outside the droplet is\")\n            {\n                double value = 0.49991229576650942;\n                double gf_value = gf.kernelS(source2, probe2);\n                INFO(\"ref_value = \" << std::setprecision(std::numeric_limits<long double>::digits10) << value);\n                INFO(\"gf_value  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_value);\n                REQUIRE(value == Approx(gf_value));\n            }\n            THEN(\"the value of the Green's function directional derivative wrt the probe point inside the droplet is\")\n            {\n                double derProbe = -0.012506340818360315;\n                double gf_derProbe = gf.derivativeProbe(probeNormal1, source1, probe1);\n                INFO(\"ref_derProbe = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derProbe);\n                INFO(\"gf_derProbe  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derProbe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the probe point outside the droplet is\")\n            {\n                double derProbe = -0.28997553534915177;\n                double gf_derProbe = gf.derivativeProbe(probeNormal2, source2, probe2);\n                INFO(\"ref_derProbe = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derProbe);\n                INFO(\"gf_derProbe  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derProbe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            THEN(\"the value of the Green's function directional derivative wrt the source point inside the droplet is\")\n            {\n                double derSource = 0.012498621813619368;\n                double gf_derSource = gf.derivativeSource(sourceNormal1, source1, probe1);\n                INFO(\"ref_derSource = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derSource);\n                INFO(\"gf_derSource  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derSource);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the source point outside the droplet is\")\n            {\n                double derSource = 0.28871292628573908;\n                double gf_derSource = gf.derivativeSource(sourceNormal2, source2, probe2);\n                INFO(\"ref_derSource = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derSource);\n                INFO(\"gf_derSource  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derSource);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n        }\n\n        AND_WHEN(\"the spherical droplet is centered away from the origin\")\n        {\n            Eigen::Vector3d sphereCenter = (Eigen::Vector3d() << 25.0, 0.0, 0.0).finished();\n            SphericalDiffuse<CollocationIntegrator, OneLayerErf> gf(eps1, eps2, width, sphereRadius, sphereCenter, maxL);\n            THEN(\"the value of the Green's function inside the droplet is\")\n            {\n                double value = 0.012523344896520634;\n                double gf_value = gf.kernelS(source1, probe1);\n                INFO(\"ref_value = \" << std::setprecision(std::numeric_limits<long double>::digits10) << value);\n                INFO(\"gf_value  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_value);\n                REQUIRE(value == Approx(gf_value));\n            }\n            AND_THEN(\"the value of the Green's function outside the droplet is\")\n            {\n                double value = 0.49989736527661349;\n                double gf_value = gf.kernelS(source2, probe2);\n                INFO(\"ref_value = \" << std::setprecision(std::numeric_limits<long double>::digits10) << value);\n                INFO(\"gf_value  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_value);\n                REQUIRE(value == Approx(gf_value));\n            }\n            THEN(\"the value of the Green's function directional derivative wrt the probe point inside the droplet is\")\n            {\n                double derProbe = -0.012502439280500169;\n                double gf_derProbe = gf.derivativeProbe(probeNormal1, source1, probe1);\n                INFO(\"ref_derProbe = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derProbe);\n                INFO(\"gf_derProbe  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derProbe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the probe point outside the droplet is\")\n            {\n                double derProbe = -0.28995345687399254;\n                double gf_derProbe = gf.derivativeProbe(probeNormal2, source2, probe2);\n                INFO(\"ref_derProbe = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derProbe);\n                INFO(\"gf_derProbe  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derProbe);\n                REQUIRE(derProbe == Approx(gf_derProbe));\n            }\n            THEN(\"the value of the Green's function directional derivative wrt the source point inside the droplet is\")\n            {\n                double derSource = 0.012489903372303254;\n                double gf_derSource = gf.derivativeSource(sourceNormal1, source1, probe1);\n                INFO(\"ref_derSource = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derSource);\n                INFO(\"gf_derSource  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derSource);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n            AND_THEN(\"the value of the Green's function directional derivative wrt the source point outside the droplet is\")\n            {\n                double derSource = 0.28869402146192158;\n                double gf_derSource = gf.derivativeSource(sourceNormal2, source2, probe2);\n                INFO(\"ref_derSource = \" << std::setprecision(std::numeric_limits<long double>::digits10) << derSource);\n                INFO(\"gf_derSource  = \" << std::setprecision(std::numeric_limits<long double>::digits10) << gf_derSource);\n                REQUIRE(derSource == Approx(gf_derSource));\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "75480331488e809cc9e250bd17c40a8ce29d392b", "size": 18374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/tests/green/green_spherical_diffuse.cpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/tests/green/green_spherical_diffuse.cpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/tests/green/green_spherical_diffuse.cpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.6558441558, "max_line_length": 124, "alphanum_fraction": 0.6122782192, "num_tokens": 4278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5954392049822338}}
{"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    // \u6bcf\u4e2a\u4f18\u5316\u53d8\u91cf\u7ef4\u5ea6\u4e3a3\uff0c\u8bef\u5dee\u503c\u7ef4\u5ea6\u4e3a1\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        //\u9876\u70b9\n        v->setId(curr_idx);\n        v->setEstimate(Eigen::Isometry3d::Identity());\n        optimizer.addVertex(v);\n        //\u8fb9\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    // \u6bcf\u4e2a\u4f18\u5316\u53d8\u91cf\u7ef4\u5ea6\u4e3a3\uff0c\u8bef\u5dee\u503c\u7ef4\u5ea6\u4e3a1\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        //\u9876\u70b9\n        v->setId(curr_idx);\n        v->setEstimate(Eigen::Isometry3d::Identity());\n        optimizer.addVertex(v);\n        //\u8fb9\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])//\ufffd\ufffd\u05b9\ufffd\ufffd0\ufffd\u0436\ufffd\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": "/* Copyright (c) 2014, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n#include <iostream>\n#include <sstream>\n#include <sys/time.h>\n//#include <random> // can only use with C++11\n#include <pcl/io/ply_io.h>\n#include <pcl/point_types.h>\n#include <pcl/common/transforms.h>\n\n#include <boost/program_options.hpp>\n#include <boost/random.hpp>\n\nnamespace po = boost::program_options;\nusing std::cout;\nusing std::endl;\n\n#include <jsCore/timer.hpp>\n\nfloat ToDeg(float rad) {\n  return rad*180./M_PI;\n}\nfloat ToRad(float deg) {\n  return deg/180.*M_PI;\n}\ndouble ToDeg(double rad) {\n  return rad*180./M_PI;\n}\ndouble ToRad(double deg) {\n  return deg/180.*M_PI;\n}\n\nint main (int argc, char** argv)\n{\n  // Declare the supported options.\n  po::options_description desc(\"Apply random transformation to input point cloud.\\n The affine transformation is sampled as: (1) sample random rotation axis (uniformly on the sphere) and use specified rotation magnitude to obtain rotation and (2) sample random rotation uniformly on the sphere with radius spcified in the translation argument.\\nAllowed options\");\n  desc.add_options()\n    (\"help,h\", \"produce help message\")\n    (\"input,i\", po::value<string>(),\"path to input point cloud\")\n    (\"output,o\", po::value<string>(),\"path to output transformed point cloud\")\n    (\"angle,a\", po::value<double>(),\"magnitude of rotation (deg)\")\n    (\"translation,t\", po::value<double>(),\"magnitude of translation (m)\")\n    ;\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);    \n\n  if (vm.count(\"help\")) {\n    cout << desc << \"\\n\";\n    return 1;\n  }\n\n  double angle = 10.; // In degree\n  double translation = 1.0;\n  string inputPath = \"./file.ply\";\n  string outputPath = \"./out.ply\";\n  if(vm.count(\"input\")) inputPath = vm[\"input\"].as<string>();\n  if(vm.count(\"output\")) outputPath = vm[\"output\"].as<string>();\n  if(vm.count(\"angle\")) angle = vm[\"angle\"].as<double>();\n  if(vm.count(\"translation\")) translation = vm[\"translation\"].as<double>();\n\n  std::stringstream ssOutPath;\n  std::stringstream ssTransformationFile;\n  ssOutPath << outputPath << \"_angle_\" << angle << \"_translation_\" <<\n    translation << \".ply\";\n  ssTransformationFile << outputPath << \"_angle_\" << angle <<\n    \"_translation_\" << translation << \"_TrueTransformation\" << \".csv\";\n\n  outputPath = ssOutPath.str();\n  std::string transformationOutputPath = ssTransformationFile.str();\n\n  // Load point cloud.\n  pcl::PointCloud<pcl::PointXYZRGBNormal> pcIn, pcOut;\n  pcl::PLYReader reader;\n  if (reader.read(inputPath, pcIn)) \n    std::cout << \"error reading \" << inputPath << std::endl;\n  else\n    std::cout << \"loaded pc from \" << inputPath << \": \" << pcIn.width << \"x\"\n      << pcIn.height << std::endl;\n\n  std::cout<< \" input pointcloud from \"<<inputPath<<std::endl;\n  std::cout<< \"  angular magnitude \"<< angle <<std::endl;\n  std::cout<< \"  translational magnitude \"<< translation <<std::endl;\n  std::cout<< \" output to \"<<outputPath<<std::endl;\n  std::cout<< \" sampled transformation to \" << transformationOutputPath << std::endl;\n\n  // Using boost here because C11 and CUDA seem to have troubles.\n  timeval tNow; \n  gettimeofday(&tNow, NULL);\n  boost::mt19937 gen(tNow.tv_usec);\n  boost::normal_distribution<> N(0,1);\n  // Sample axis of rotation:\n  Eigen::Vector3f axis(N(gen), N(gen), N(gen));\n  axis /= axis.norm();\n  // Construct rotation:\n  Eigen::AngleAxisf aa(ToRad(angle), axis);\n  Eigen::Quaternionf q(aa);\n  // Sample translation on sphere with radius translation:\n  Eigen::Vector3f t(N(gen), N(gen), N(gen));\n  t *= translation / t.norm();\n\n  Eigen::Affine3f T = Eigen::Affine3f::Identity();\n  T.translation() = t;\n  T.rotate(q);\n\n  std::cout << \"sampled random transformation:\\n\" \n    << T.matrix() << std::endl;\n\n  // Transform both points by T as well as surface normals by R\n  // manually since the standard transformPointCloud does not seem to\n  // touch the Surface normals.\n  pcOut = pcIn;\n  for (uint32_t i=0; i<pcOut.size(); ++i) {\n    Eigen::Map<Eigen::Vector3f> p(&(pcOut.at(i).x));\n    p = T.rotation() * p + T.translation();\n    Eigen::Map<Eigen::Vector3f> n(pcOut.at(i).normal);\n    n = T.rotation()*n;\n  }\n  \n  pcl::PLYWriter writer;\n  writer.write(outputPath, pcOut, false, false);\n\n  std::ofstream out(transformationOutputPath.c_str());\n  out << \"q_w q_x q_y q_z t_x t_y t_z\" << std::endl;\n  out << q.w() << \" \" << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" \n    << t(0) << \" \" << t(1) << \" \" << t(2);\n  out.close();\n}\n\n", "meta": {"hexsha": "542fe0c2626ce0338df82cd00a13c52c84130e6f", "size": 4542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/randomlyTransformPointClouds.cpp", "max_stars_repo_name": "jstraub/cudaPcl", "max_stars_repo_head_hexsha": "10b61d66f83c664942f1e7b6ee574246df8d8922", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 84.0, "max_stars_repo_stars_event_min_datetime": "2015-04-05T16:17:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T13:40:51.000Z", "max_issues_repo_path": "src/randomlyTransformPointClouds.cpp", "max_issues_repo_name": "jstraub/cudaPcl", "max_issues_repo_head_hexsha": "10b61d66f83c664942f1e7b6ee574246df8d8922", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T02:35:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-04T06:50:53.000Z", "max_forks_repo_path": "src/randomlyTransformPointClouds.cpp", "max_forks_repo_name": "jstraub/cudaPcl", "max_forks_repo_head_hexsha": "10b61d66f83c664942f1e7b6ee574246df8d8922", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-06-19T18:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-02T08:21:22.000Z", "avg_line_length": 34.6717557252, "max_line_length": 363, "alphanum_fraction": 0.6545574637, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5953874508932449}}
{"text": "#include <boost/tuple/tuple.hpp>\n#include <map>\n\n#include <boost/graph/adjacency_list.hpp>\n#include \"tdlib/TD_combinations.hpp\"\n#include \"tdlib/TD_misc.hpp\"\n\n#ifndef TD_STRUCT_VERTEX\n#define TD_STRUCT_VERTEX\n\nstruct Vertex{\n    unsigned int id;\n};\n\n#endif\n\ntypedef boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS, Vertex> TD_graph_t;\n\nstruct bag{\n    std::set<unsigned int> bag;\n};\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, bag> TD_tree_dec_t;\n\n\nvoid make_tdlib_graph(TD_graph_t &G, std::vector<unsigned int> &V, std::vector<unsigned int> &E){\n    unsigned int max = 0;\n    for(unsigned int i = 0; i < V.size(); i++)\n        max = (V[i]>max)? V[i] : max;\n\n    std::vector<TD_graph_t::vertex_descriptor> idxMap(max+1);\n\n    for(unsigned int i = 0; i < V.size(); i++){\n        idxMap[V[i]] = boost::add_vertex(G);\n        G[idxMap[V[i]]].id = V[i];\n    }\n\n    if(E.size() != 0){\n        for(unsigned int j = 0; j < E.size()-1; j++){\n            boost::add_edge(idxMap[E[j]], idxMap[E[j+1]], G);\n            j++;\n        }\n    }\n}\n\nvoid make_sage_decomp(TD_tree_dec_t &T, std::vector<std::vector<int> > &V_T, std::vector<unsigned int> &E_T){\n    std::map<boost::graph_traits<TD_tree_dec_t>::vertex_descriptor, unsigned int> vertex_map;\n    boost::graph_traits<TD_tree_dec_t>::vertex_iterator tIt, tEnd;\n    unsigned int id = 0;\n    \n    for(boost::tie(tIt, tEnd) = boost::vertices(T); tIt != tEnd; tIt++){\n        vertex_map.insert(std::pair<boost::graph_traits<TD_tree_dec_t>::vertex_descriptor, unsigned int>(*tIt, id++));\n        std::vector<int> bag;\n        for(std::set<unsigned int>::iterator sIt = T[*tIt].bag.begin(); sIt != T[*tIt].bag.end(); sIt++)\n            bag.push_back((int)*sIt);\n        V_T.push_back(bag);\n    }\n    \n    boost::graph_traits<TD_tree_dec_t>::edge_iterator eIt, eEnd;\n    for(boost::tie(eIt, eEnd) = boost::edges(T); eIt != eEnd; eIt++){\n        std::map<boost::graph_traits<TD_tree_dec_t>::vertex_descriptor, unsigned int>::iterator v, w;\n        v = vertex_map.find(boost::source(*eIt, T));\n        w = vertex_map.find(boost::target(*eIt, T));\n        E_T.push_back(v->second);\n        E_T.push_back(w->second);\n    }\n}\n\n\n/* EXACT TREE DECOMPOSITIONS */\n\nint sage_exact_decomposition(std::vector<unsigned int> &V_G, std::vector<unsigned int> &E_G, std::vector<std::vector<int> > &V_T, std::vector<unsigned int> &E_T, int lb){\n    TD_graph_t G;\n    make_tdlib_graph(G, V_G, E_G);\n\n    TD_tree_dec_t T;\n\n    treedec::exact_decomposition_cutset(G, T, lb);\n\n    treedec::make_small(T);\n\n    make_sage_decomp(T, V_T, E_T);\n\n    return treedec::get_width(T);\n}\n\n", "meta": {"hexsha": "ad1e3fb1f0385cbba54206601e70c07a04412b70", "size": 2643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sage/graphs/graph_decompositions/tdlib/sage_tdlib.cpp", "max_stars_repo_name": "bopopescu/sage", "max_stars_repo_head_hexsha": "2d495be78e0bdc7a0a635454290b27bb4f5f70f0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1742.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:32:52.000Z", "max_issues_repo_path": "src/sage/graphs/graph_decompositions/tdlib/sage_tdlib.cpp", "max_issues_repo_name": "Ivo-Maffei/sage", "max_issues_repo_head_hexsha": "467fbc70a08b552b3de33d9065204ee9cbfb02c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T19:17:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:59:30.000Z", "max_forks_repo_path": "src/sage/graphs/graph_decompositions/tdlib/sage_tdlib.cpp", "max_forks_repo_name": "dimpase/sage", "max_forks_repo_head_hexsha": "468f23815ade42a2192b0a9cd378de8fdc594dcd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 495.0, "max_forks_repo_forks_event_min_datetime": "2015-01-10T10:23:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:06:11.000Z", "avg_line_length": 30.3793103448, "max_line_length": 170, "alphanum_fraction": 0.6371547484, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5953874446813923}}
{"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": "#ifndef TIKPP_DETAIL_CONVERT_HPP\n#define TIKPP_DETAIL_CONVERT_HPP\n\n#include \"fmt/format.h\"\n#include <boost/lexical_cast/try_lexical_convert.hpp>\n\n#include <string>\n#include <type_traits>\n\nnamespace tikpp::detail {\n\ntemplate <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>\nauto integeral_pow(T base, T exp) -> T {\n    T result {1};\n\n    while (true) {\n        if (exp & 1) {\n            result *= base;\n        }\n\n        if (!(exp >>= 1)) {\n            break;\n        }\n\n        base *= base;\n    }\n\n    return result;\n}\n\ntemplate <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>\nstatic inline auto rparse_uint(const std::string &str, std::size_t pos) noexcept\n    -> T {\n    T    ret {};\n    char c;\n\n    for (std::size_t i {pos}; i > 0; --i) {\n        c = str[i - 1];\n\n        if (!std::isdigit(c)) {\n            break;\n        }\n\n        ret += integeral_pow<T>(10, pos - i) * (c - '0');\n    }\n\n    if constexpr (std::is_signed_v<T>) {\n        if (c == '-') {\n            ret = ~ret + 1;\n        }\n    }\n\n    return ret;\n}\n\ntemplate <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>\nstatic inline auto parse_uint(const std::string &str,\n                              std::size_t        pos = 0) noexcept -> T {\n    T    ret {};\n    char c;\n\n    std::size_t idx {pos};\n\n    while ((c = str[idx++])) {\n        if (!std::isdigit(c)) {\n            break;\n        }\n\n        ret = ret * 10 + (c - '0');\n    }\n\n    if constexpr (std::is_signed_v<T>) {\n        if (str[pos] == '-') {\n            ret = ~ret + 1;\n        }\n    }\n\n    return ret;\n}\n\ntemplate <typename T>\ninline auto convert(const std::string &str) -> std::decay_t<T> {\n    using type = std::decay_t<T>;\n\n    if constexpr (std::is_constructible_v<type, decltype(str)>) {\n        return T {str};\n    }\n\n    if constexpr (std::is_integral_v<type> && std::is_unsigned_v<type>) {\n        return parse_uint<type>(str);\n    }\n\n    type ret {};\n\n    if (!str.empty()) {\n        boost::conversion::try_lexical_convert(str, ret);\n    }\n\n    return ret;\n}\n\ntemplate <>\ninline auto convert<std::string>(const std::string &str) -> std::string {\n    return str;\n}\n\ntemplate <>\ninline auto convert<bool>(const std::string &str) -> bool {\n    return str == \"true\" || str == \"yes\";\n}\n\ntemplate <typename T>\ninline auto convert_back(const T &value) -> std::string {\n    using type = std::decay_t<T>;\n\n    if constexpr (std::is_same_v<type, std::string>) {\n        return value;\n    } else if constexpr (std::is_constructible_v<std::string, type>) {\n        return std::string {value};\n    }\n\n    return fmt::to_string(value);\n}\n\n} // namespace tikpp::detail\n\n#endif\n", "meta": {"hexsha": "c54ffd5383db64d03978c4a758c93c37e844aca5", "size": 2658, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/tikpp/detail/convert.hpp", "max_stars_repo_name": "aymanalqadhi/tikpp", "max_stars_repo_head_hexsha": "8e94abdc4ac8c85dd893780ad4256cdd6690a758", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-07T08:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T04:33:18.000Z", "max_issues_repo_path": "include/tikpp/detail/convert.hpp", "max_issues_repo_name": "xSHAD0Wx/tikpp", "max_issues_repo_head_hexsha": "8e94abdc4ac8c85dd893780ad4256cdd6690a758", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/tikpp/detail/convert.hpp", "max_forks_repo_name": "xSHAD0Wx/tikpp", "max_forks_repo_head_hexsha": "8e94abdc4ac8c85dd893780ad4256cdd6690a758", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-18T20:00:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T09:04:46.000Z", "avg_line_length": 20.765625, "max_line_length": 80, "alphanum_fraction": 0.5489089541, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940927, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5952115059394975}}
{"text": "//standard include\n#include <math.h>\n#include <iostream>\n#include <fstream>\n\n//#include <Eigen/Geometry>\n#include <cmath>\n\n//opencv include\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/core/core.hpp\"\n\n#ifndef UTILITIES\n#define UTILITIES\n\n#include \"objtype.hpp\"\nnamespace zv_utils {\n\nstd::pair<float, float> minOfDepthMat(const cv::Mat& img, const cv::Mat& mask, const cv::Rect& bound_rect, int range);\nfloat avgOfDepthMat(const cv::Mat& img, const cv::Mat& mask, const cv::Rect& bound_rect);\nvoid shrinkRect(cv::Rect &rect_in, float shrink_factor);\n\n//void printIsometry(const Eigen::Transform<double, 3, Eigen::Isometry> m);\ndouble slope_list(const std::vector<double>& x, const std::vector<double>& y);\nstd::pair<double,double> slopeOfMasked(ObjectType ot, const cv::Mat &depth, const cv::Mat &mask, cv::Point2f fov);\ndouble normalCFD(const std::pair<double, double> &meanAndStdev, double value);\n\n}\n\n#endif\n", "meta": {"hexsha": "698472530a04fe715210dbe46706adb91a0aa29a", "size": 922, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "common/Utilities.hpp", "max_stars_repo_name": "mattwalstra/2019RobotCode", "max_stars_repo_head_hexsha": "44f2543876b95428a68dc84820f931571244e49d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-15T16:37:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-15T16:39:31.000Z", "max_issues_repo_path": "common/Utilities.hpp", "max_issues_repo_name": "mattwalstra/2019RobotCode", "max_issues_repo_head_hexsha": "44f2543876b95428a68dc84820f931571244e49d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-30T00:06:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-29T17:02:18.000Z", "max_forks_repo_path": "common/Utilities.hpp", "max_forks_repo_name": "mattwalstra/2019RobotCode", "max_forks_repo_head_hexsha": "44f2543876b95428a68dc84820f931571244e49d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-29T01:13:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T21:53:06.000Z", "avg_line_length": 29.7419354839, "max_line_length": 118, "alphanum_fraction": 0.7429501085, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778823, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.595211491729976}}
{"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\u017dBENO NIJE ODR\u017dAVAN OD STRANE ADMINISTRATORA \n    ALGORITAM I RJE\u0160ENJE 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 \u2207xA\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 \u03c6 that is nonzero on the element E, we want to\n// solve the least square system A w = rhs, where:\n//     \u250f                                     \u2513\n//     \u2503 \u03c8_k(pi) ... 1 xi yi xi*yi xi^2 yi^2 \u2503\n// A = \u2503   \u250a        \u250a  \u250a  \u250a   \u250a    \u250a    \u250a    \u2503 \u220a \u211d^{#S x (#K+1+dim+dim*(dim+1)/2)}\n//     \u2503   \u250a        \u250a  \u250a  \u250a   \u250a    \u250a    \u250a    \u2503\n//     \u2517                                     \u251b\n//     \u250f                                 \u2513^\u22a4\n// w = \u2503 w_k ... a00 a10 a01 a11 a20 a02 \u2503   \u220a \u211d^{#K+1+dim+dim*(dim+1)/2}\n//     \u2517                                 \u251b\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^\u03b1*y^\u03b2 with \u03b1+\u03b2 <= 2 is in the span of the FEM bases {\u03c6_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: \u222b_\u03a9 \u0394u v = - \u222b_\u03a9 \u2207u\u00b7\u2207v   \u2200 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 {\u03c6_j}_j must be equal to Q(x,y).\n// In particular, for any \u03c6_j that is nonzero on the polyhedral element E, we must have:\n//\n//   \u222b_{\ud835\ude05 in \u03a9} \u0394Q(\ud835\ude05) \u03c6_j(\ud835\ude05) d\ud835\ude05  = - \u222b_{\ud835\ude05 \\in \u03a9} \u2207Q(\ud835\ude05)\u00b7\u2207\u03c6_j(\ud835\ude05) d\ud835\ude05     (1)\n//\n// Now, for each of the 5 non-constant monomials (9 in 3D), we need to compute\n// \u0394(x^\u03b1*y^\u03b2). For (\u03b1,\u03b2) \u220a {(1,0), (0,1), (1,1), (2,0), (0,2)}, this yields\n// the following equalities:\n//\n//     \u0394x  = 0      (2a)\n//     \u0394y  = 0      (2b)\n//     \u0394xy = 0      (2c)\n//     \u0394x\u00b2 = 1      (2d)\n//     \u0394y\u00b2 = 1      (2e)\n//\n// If we plug these back into (1), and split the integral between the polyhedral\n// element E and \u03a9\\E, we obtain the following constraints:\n//\n// \u222b_E \u2207Q\u00b7\u2207\u03c6_j + \u222b_E \u0394Q \u03c6_j = - \u222b_{\u03a9\\E} \u2207Q\u00b7\u2207\u03c6_j - \u222b_{\u03a9\\E} \u0394Q \u03c6_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 \u2202\u03a9. 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//     \u222b_E \u2207x(\u03c6_j) = c10                       (4a)\n//     \u222b_E \u2207y(\u03c6_j) = c01                       (4b)\n//     \u222b_E (y\u00b7\u2207x(\u03c6_j) + y\u00b7\u2207x(\u03c6_jj)) = c11      (4c)\n//     \u222b_E 2x\u00b7\u2207x(\u03c6_j) + \u222b_E 2 \u03c6_j = c20        (4d)\n//     \u222b_E 2y\u00b7\u2207y(\u03c6_j) + \u222b_E 2 \u03c6_j = c02        (4e)\n//\n// The next step is to express the basis \u03c6_j in terms of the harmonic kernels and\n// quadratic polynomials:\n//\n//     \u03c6_j(x,y) = \u03a3_k w_k \u03c8_k(x,y) + a00 + a10*x + a01*y + a11*x*y + a20*x\u00b2 + a02*y\u00b2\n//\n// The five equations in (4) become:\n//\n//\t\t\u03a3_j w_k \u222b\u2207x(\u03c8_k) = \u222b \u0394 q10  (\u03a3_j w_k (\u03c8_k) + a00) + \u03a3_j w_k \u222b\u2207q10 . \u2207(\u03c8_k + a00)\n//    \u03a3_j w_k \u222b\u2207x(\u03c8_k) + a10 |E| + a11 \u222by + a20 \u222b2x = c10\n//    \u03a3_j w_k \u222b\u2207y(\u03c8_k) + a01 |E| + a11 \u222bx + a02 \u222b2y = c01\n//    \u03a3_j w_k (\u222by\u00b7\u2207x(\u03c8_k) + \u222bx\u00b7\u2207y(\u03c8_k)) + a10 \u222by + a01 \u222bx + a11 (\u222bx\u00b2+\u222by\u00b2) + a20 2\u222bxy + a02 2\u222bxy = c11\n//    \u03a3_j w_k (2\u222bx\u00b7\u2207x(\u03c8_k) + 2\u03c8_k) + a10 4\u222bx + a01 2\u222by + a11 4\u222bxy + a20 6\u222bx\u00b2 + a02 2\u222by\u00b2 = c20\n//    \u03a3_j w_k (2\u222by\u00b7\u2207y(\u03c8_k) + 2\u03c8_k) + a10 2\u222bx + a01 4\u222by + a11 4\u222bxy + a20 2\u222bx\u00b2 + a02 6\u222by\u00b2 = c02\n//  \t\u03a3_j w_k (2\u222by\u00b7\u2207y(\u03c8_k) + 2\u03c8_k) = \u222b \u0394 q20  (\u03a3_j w_k (\u03c8_k) + a00) + \u03a3_j w_k \u222b\u2207q20 . \u2207(\u03c8_k + a00) = \u222b -2  (\u03a3_j w_k (\u03c8_k) + a00) + \u03a3_j w_k \u222b2x \u2207x(\u03c8_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//     \u250f                              \u2513             \u250f     \u2513\n//     \u2503 |E|         \u222by    2\u222bx        \u2503             \u2503 w_k \u2503\n//     \u2503                              \u2503             \u2503  \u250a  \u2503\n//     \u2503       |E|   \u222bx          2\u222by  \u2503             \u2503  \u250a  \u2503\n//     \u2503                              \u2503             \u2503  \u250a  \u2503\n// M = \u2503  \u222by   \u222bx  \u222bx\u00b2+\u222by\u00b2 2\u222bxy  2\u222bxy \u2503 = \\tilde{L} \u2503  \u250a  \u2503 + \\tilde{t}\n//     \u2503                              \u2503             \u2503  \u250a  \u2503\n//     \u2503 4\u222bx  2\u222by  4\u222bxy    6\u222bx\u00b2  2\u222by\u00b2 \u2503             \u2503  \u250a  \u2503\n//     \u2503                              \u2503             \u2503w_#K \u2503\n//     \u2503 2\u222bx  4\u222by  4\u222bxy    2\u222bx\u00b2  6\u222by\u00b2 \u2503             \u2503 a00 \u2503\n//     \u2517                              \u251b             \u2517     \u251b\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//     \u250f                  \u2513\n//     \u2503   1              \u2503\n//     \u2503       1          \u2503\n//     \u2503          \u00b7       \u2503\n// L = \u2503             \u00b7    \u2503 \u220a \u211d^{ (#K+1+dim+dim*(dim+1)/2) x (#K+1}) }\n//     \u2503                1 \u2503\n//     \u2503 M^{-1} \\tilde{L} \u2503\n//     \u2517                  \u251b\n//     \u250f                  \u2513\n//     \u2503        0         \u2503\n//     \u2503        \u250a         \u2503\n// t = \u2503        \u250a         \u2503 \u220a \u211d^{#K+1+dim+dim*(dim+1)/2}\n//     \u2503        0         \u2503\n//     \u2503 M^{-1} \\tilde{t} \u2503\n//     \u2517                  \u251b\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 = \u222b\u03c8_k\n\t// K_lin = \u222b\u2207x(\u03c8_k), \u222b\u2207y(\u03c8_k)\n\t// K_mix = \u222by\u00b7\u2207x(\u03c8_k), \u222bx\u00b7\u2207y(\u03c8_k)\n\t// K_sqr = \u222bx\u00b7\u2207x(\u03c8_k), \u222by\u00b7\u2207y(\u03c8_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// \u222b\u2207x(\u03c8_k)(p) = \u03a3_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 = \u222bx, \u222by\n\t// I_mix = \u222bxy\n\t// I_sqr = \u222bx\u00b2, \u222by\u00b2\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 = \u222b\u03c8_k\n\t// K_lin = \u222b\u2207x(\u03c8_k), \u222b\u2207y(\u03c8_k), \u222b\u2207z(\u03c8_k)\n\t// K_mix = \u222b(y\u00b7\u2207x(\u03c8_k)+x\u00b7\u2207y(\u03c8_k)), \u222b(z\u00b7\u2207y(\u03c8_k)+y\u00b7\u2207z(\u03c8_k)), \u222b(x\u00b7\u2207z(\u03c8_k)+z\u00b7\u2207x(\u03c8_k))\n\t// K_sqr = \u222bx\u00b7\u2207x(\u03c8_k), \u222by\u00b7\u2207y(\u03c8_k), \u222bz\u00b7\u2207z(\u03c8_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// \u222b\u2207x(\u03c8_k)(p) = \u03a3_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 = \u222bx, \u222by, \u222bz\n\t// I_sqr = \u222bx\u00b2, \u222by\u00b2, \u222bz\u00b2\n\t// I_mix = \u222bxy, \u222byz, \u222bzx\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": "\ufeff#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/convex_hull_3.h>\n#include <Eigen/Dense>\n#include <vtkPolyDataReader.h>\n#include <vtkPolyDataWriter.h>\n#include <vtkPolyData.h>\n#include <vtkCellArray.h>\n#include <vtkDoubleArray.h>\n#include <vtkSmartPointer.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_3 Point;\ntypedef CGAL::Surface_mesh<Point> Surface_mesh;\ntypedef Surface_mesh::Vertex_index Vertex;\ntypedef Surface_mesh::Edge_index Edge;\ntypedef Surface_mesh::Face_index Face;\ntypedef Surface_mesh::Halfedge_index Halfedge;\ntypedef Eigen::Vector3d Vector3d;\ntypedef Eigen::VectorXd VectorXd;\ntypedef Eigen::Matrix3d Matrix3d;\ntypedef Eigen::Matrix3Xd Matrix3Xd;\ntypedef Eigen::Map<Matrix3Xd> Map3Xd;\n\nint main(){\n    clock_t t1;\n    t1 = clock();\n    for(auto i=0; i < 10000; ++i){\n        vtkNew<vtkPolyDataReader> reader;\n        reader->SetFileName(\"Bad.vtk\");\n        reader->Update();\n        auto poly = reader->GetOutput();\n        auto N = poly->GetNumberOfPoints();\n        auto pts = static_cast<double_t*>(poly->GetPoints()->GetData()->GetVoidPointer(0));\n        Map3Xd points(pts,3,N);\n\n        // Project points to unit sphere\n        points.colwise().normalize();\n\n        // Reset the center of the sphere to origin by translating\n        Vector3d center = points.rowwise().mean();\n        points = points.colwise() - center;\n\n        std::vector<Point> spherePoints(N);\n        for( auto i=0; i < N; ++i){\n            spherePoints[i] = Point(points(0,i),points(1,i),points(2,i));\n        }\n\n        // Make a mesh object\n        Surface_mesh sm;\n\n        // Calculate the convex hull\n        CGAL::convex_hull_3(spherePoints.begin(),\n                            spherePoints.end(), sm);\n\n        // To extract the surface\n        // Write to a vtk file\n        vtkNew<vtkCellArray> triangles;\n        for( auto f : sm.faces() ){\n            triangles->InsertNextCell(3);\n\t    auto he = sm.halfedge( f );\n            for( auto j=0; j < 3; ++j){\n                triangles->InsertCellPoint( static_cast<size_t>(sm.target(he)) );\n\t\the = sm.next( he );\n            }\n        }\n        poly->SetPolys(triangles);\n        vtkNew<vtkPolyDataWriter> writer;\n        writer->SetFileName(\"CH_Mesh.vtk\");\n        writer->SetInputData(poly);\n        writer->Write();\n    }\n    float diff(static_cast<float>(clock()) - static_cast<float>(t1));\n    std::cout << \"Time elapsed : \" << diff / CLOCKS_PER_SEC\n              << \" seconds\" << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "f8b52620a5a5177bb5bc1df500858d07e4d7caad", "size": 2568, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "CPP/cgal3dCH.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/cgal3dCH.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/cgal3dCH.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": 32.9230769231, "max_line_length": 91, "alphanum_fraction": 0.6343457944, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5951276513187993}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n/// @brief      Tests periods.hpp\n///\n///\n/// @file\n/// @author     olivier\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/foreach.hpp>\n\n#include \"plato/math/matrix.hpp\"\n#include \"plato/misc/periods.hpp\"\n\nusing namespace boost;\nusing namespace unit_test;\n\nusing namespace plato::misc;\nusing namespace plato::math;\n\nvoid period_unit_test_func()\n{\n    typedef plato::misc::period<int> period_type;\n    \n    /// An empty period object\n    period_type period_1;\n    \n    /// A period object\n    period_type period_2(2,5);\n    \n    BOOST_CHECK_EQUAL(period_1.start(), 0);\n    BOOST_CHECK_EQUAL(period_1.stop() , 0);\n    BOOST_CHECK_EQUAL(period_1.span() , 0);\n    \n    BOOST_CHECK_EQUAL(period_2.start(), 2);\n    BOOST_CHECK_EQUAL(period_2.stop() , 5);\n    BOOST_CHECK_EQUAL(period_2.span() , 3);\n    \n    /// Copy constructing a new period object and checking operator==\n    period_type period_3(period_2);\n    BOOST_CHECK(period_2 == period_3);\n    \n    /// Check operator!=\n    BOOST_CHECK(period_type(2,5) != period_type(3,5));\n    BOOST_CHECK(period_type(2,5) != period_type(2,6));\n    \n    /// Check operator=\n    period_type period_4 = period_3;\n    BOOST_CHECK(period_3 == period_3);\n    \n    /// Check repr()\n    BOOST_CHECK_NO_THROW(period_1.repr());\n    \n    /// Checks a non-valid periods\n    BOOST_CHECK_THROW(period_type p(6,2), std::runtime_error);\n}\n\nvoid periods_unit_test_func()\n{\n    typedef periods<int> periods_type;\n    typedef periods_type::period_type period_type;\n    \n    /// An empty periods object\n    periods_type periods_1;\n    \n    /// A periods object with 10 periods with span 1, starting at 0\n    periods_type periods_2(10);\n    \n    /// A periods object with periods with span 1, starting at 5 and stopping at 15\n    periods_type periods_3(5,15);\n    \n    /// A periods object with periods of span 2, starting at 7 and stopping at 17\n    periods_type periods_4(7,17,2);\n    \n    /// A periods object with periods of span 2, starting at 7 and stopping at 16\n    periods_type periods_5(7,16,2);\n    \n    /// A periods object with periods of different spans\n    plato::math::vector<int> offsets(8);\n    offsets << 0, 7, 14, 30, 60, 90, 180, 365;\n    periods_type periods_6(offsets);\n    \n    /// Checking start, stop and size\n    BOOST_CHECK_EQUAL(periods_1.start(),      0);\n    BOOST_CHECK_EQUAL(periods_1.stop() ,      0);\n    BOOST_CHECK_EQUAL(periods_1.real_stop(),  0);\n    BOOST_CHECK_EQUAL(periods_1.size() ,      0u);\n    \n    BOOST_CHECK_EQUAL(periods_2.start(),      0);\n    BOOST_CHECK_EQUAL(periods_2.stop() ,     10);\n    BOOST_CHECK_EQUAL(periods_2.real_stop(), 10);\n    BOOST_CHECK_EQUAL(periods_2.size() ,     10u);\n    \n    BOOST_CHECK_EQUAL(periods_3.start(),      5);\n    BOOST_CHECK_EQUAL(periods_3.stop() ,     15);\n    BOOST_CHECK_EQUAL(periods_3.real_stop(), 15);\n    BOOST_CHECK_EQUAL(periods_3.size() ,     10u);\n    \n    BOOST_CHECK_EQUAL(periods_4.start(),      7);\n    BOOST_CHECK_EQUAL(periods_4.stop() ,     17);\n    BOOST_CHECK_EQUAL(periods_4.real_stop(), 17);\n    BOOST_CHECK_EQUAL(periods_4.size() ,      5u);\n    \n    BOOST_CHECK_EQUAL(periods_5.start(),      7);\n    BOOST_CHECK_EQUAL(periods_5.stop() ,     16);\n    BOOST_CHECK_EQUAL(periods_5.real_stop(), 17);\n    BOOST_CHECK_EQUAL(periods_5.size() ,     5u);\n    \n    BOOST_CHECK_EQUAL(periods_6.start(),      0);\n    BOOST_CHECK_EQUAL(periods_6.stop() ,    365);\n    BOOST_CHECK_EQUAL(periods_6.real_stop(),365);\n    BOOST_CHECK_EQUAL(periods_6.size() ,     7u);\n    \n    /// Checking operator==\n    BOOST_CHECK(periods_type(10) == periods_type(0,10));\n    BOOST_CHECK(periods_type(10) == periods_type(0,10,1));\n    \n    /// periods_4 and periods_5 have a different stop offsets, \n    /// but same real_stop offsets and since they produce the \n    /// same periods, they should be considered equal. Checking that...\n    BOOST_CHECK(periods_4 == periods_5);\n    \n    /// Check operator!=\n    BOOST_CHECK(periods_type(0,10,1) != periods_type(1,10,1));\n    BOOST_CHECK(periods_type(0,10,1) != periods_type(0,11,1));\n    BOOST_CHECK(periods_type(0,10,1) != periods_type(0,10,2));\n    \n    /// Check operator=\n    periods_type periods_7 = periods_6;\n    BOOST_CHECK(periods_6 == periods_7);\n    \n    /// Check repr()\n    BOOST_CHECK_NO_THROW(periods_7.repr());\n    \n    /// Check iteration\n    periods_type p(periods_7);\n    BOOST_CHECK(*(p.begin())              == period_type(  0,   7));\n    BOOST_CHECK(*(++p.begin())            == period_type(  7,  14));\n    BOOST_CHECK(*(++++p.begin())          == period_type( 14,  30));\n    BOOST_CHECK(*(++++++p.begin())        == period_type( 30,  60));\n    BOOST_CHECK(*(++++++++p.begin())      == period_type( 60,  90));\n    BOOST_CHECK(*(++++++++++p.begin())    == period_type( 90, 180));\n    BOOST_CHECK(*(++++++++++++p.begin())  == period_type(180, 365));\n    BOOST_CHECK(  ++++++++++++++p.begin() == p.end());\n    BOOST_CHECK(*(--p.end())              == period_type(180, 365));\n    BOOST_CHECK(*(----p.end())            == period_type( 90, 180));\n    BOOST_CHECK(*(------p.end())          == period_type( 60,  90));\n    BOOST_CHECK(*(--------p.end())        == period_type( 30,  60));\n    BOOST_CHECK(*(----------p.end())      == period_type( 14,  30));\n    BOOST_CHECK(*(------------p.end())    == period_type(  7,  14));\n    BOOST_CHECK(*(--------------p.end())  == period_type(  0,   7));\n        \n    /// Check random access\n    BOOST_CHECK(p.begin()                 == p.begin() + 0);\n    BOOST_CHECK(++p.begin()               == p.begin() + 1);\n    BOOST_CHECK(++++p.begin()             == p.begin() + 2);\n    BOOST_CHECK(++++++p.begin()           == p.begin() + 3);\n    BOOST_CHECK(++++++++p.begin()         == p.begin() + 4);\n    BOOST_CHECK(++++++++++p.begin()       == p.begin() + 5);\n    BOOST_CHECK(++++++++++++p.begin()     == p.begin() + 6);\n    BOOST_CHECK(++++++++++++++p.begin()   == p.begin() + 7);\n    BOOST_CHECK(p.begin()                 == p.end()   - 7);\n    BOOST_CHECK(++p.begin()               == p.end()   - 6);\n    BOOST_CHECK(++++p.begin()             == p.end()   - 5);\n    BOOST_CHECK(++++++p.begin()           == p.end()   - 4);\n    BOOST_CHECK(++++++++p.begin()         == p.end()   - 3);\n    BOOST_CHECK(++++++++++p.begin()       == p.end()   - 2);\n    BOOST_CHECK(++++++++++++p.begin()     == p.end()   - 1);\n    BOOST_CHECK(++++++++++++++p.begin()   == p.end()   - 0);\n    \n    /// Check BOOST_FOREACH\n    std::size_t count(0);\n    BOOST_FOREACH(period_type period, p)\n    {\n        BOOST_CHECK_EQUAL(period, period_type(\n                                      (*(p.begin() + count)).start()\n                                    , (*(p.begin() + count)).stop()\n                                  )\n                         );\n        ++count;\n    }\n    BOOST_CHECK_EQUAL(count, static_cast<std::size_t>(p.size()));\n    \n    /// Check some non-valid periods\n    BOOST_CHECK_THROW(periods_type p(0,10,-1), std::runtime_error);\n    BOOST_CHECK_THROW(periods_type p(10,0, 1), std::runtime_error);\n    BOOST_CHECK_THROW(periods_type p(10,0,-1), std::runtime_error);\n    plato::math::vector<int> o(8);\n    o << 0, 7, 14, 60, 30, 90, 180, 365;\n    BOOST_CHECK_THROW(periods_type p(o), std::runtime_error);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"plato::misc::periods test\");\n\n    test->add(BOOST_TEST_CASE(&period_unit_test_func));\n    test->add(BOOST_TEST_CASE(&periods_unit_test_func));\n\n\n    return test;\n}\n", "meta": {"hexsha": "572336add20d28090e71f2d714d394b37e9eef56", "size": 7679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/time_series/periods/test/test_periods.cpp", "max_stars_repo_name": "ericniebler/time_series", "max_stars_repo_head_hexsha": "4040119366cc21f25c7734bb355e4a647296a96d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T11:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T03:39:29.000Z", "max_issues_repo_path": "boost/time_series/periods/test/test_periods.cpp", "max_issues_repo_name": "ericniebler/time_series", "max_issues_repo_head_hexsha": "4040119366cc21f25c7734bb355e4a647296a96d", "max_issues_repo_licenses": ["BSL-1.0"], "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/time_series/periods/test/test_periods.cpp", "max_forks_repo_name": "ericniebler/time_series", "max_forks_repo_head_hexsha": "4040119366cc21f25c7734bb355e4a647296a96d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-05-09T02:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-02T13:39:29.000Z", "avg_line_length": 37.0966183575, "max_line_length": 83, "alphanum_fraction": 0.5696054174, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.5951024261180643}}
{"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": "//  (C) Copyright Matt Borland 2022.\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 \"math_unit_test.hpp\"\n#include <limits>\n#include <boost/math/special_functions/logaddexp.hpp>\n#include <boost/math/constants/constants.hpp>\n\ntemplate <typename Real>\nvoid test()\n{\n    using boost::math::logaddexp;\n    using std::log;\n    using std::exp;\n\n    constexpr Real nan_val = std::numeric_limits<Real>::quiet_NaN();\n    constexpr Real inf_val = std::numeric_limits<Real>::infinity();\n\n    // NAN\n    CHECK_NAN(logaddexp(nan_val, Real(1)));\n    CHECK_NAN(logaddexp(Real(1), nan_val));\n    CHECK_NAN(logaddexp(nan_val, nan_val));\n\n    // INF\n    CHECK_EQUAL(logaddexp(inf_val, Real(1)), inf_val);\n    CHECK_EQUAL(logaddexp(Real(1), inf_val), inf_val);\n    CHECK_EQUAL(logaddexp(inf_val, inf_val), inf_val);\n\n    // Equal values\n    constexpr Real ln2 = boost::math::constants::ln_two<Real>();\n    CHECK_ULP_CLOSE(Real(2) + ln2, logaddexp(Real(2), Real(2)), 1);\n    CHECK_ULP_CLOSE(Real(1e-50) + ln2, logaddexp(Real(1e-50), Real(1e-50)), 1);\n\n    // Spot check\n    // https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html\n    // Calculated at higher precision using wolfram alpha\n    Real x1 = 1e-50l;\n    Real x2 = 2.5e-50l;\n    Real spot1 = static_cast<Real>(exp(x1));\n    Real spot2 = static_cast<Real>(exp(x2));\n    Real spot12 = logaddexp(x1, x2);\n\n    CHECK_ULP_CLOSE(log(spot1 + spot2), spot12, 1);\n}\n\nint main (void)\n{\n    test<float>();\n    test<double>();\n    test<long double>();\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "d0793f27addc8c3a3be4a73bcdeb801bcd7af418", "size": 1666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/logaddexp_test.cpp", "max_stars_repo_name": "grlee77/math", "max_stars_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/logaddexp_test.cpp", "max_issues_repo_name": "grlee77/math", "max_issues_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/logaddexp_test.cpp", "max_forks_repo_name": "grlee77/math", "max_forks_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2909090909, "max_line_length": 79, "alphanum_fraction": 0.6764705882, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5950582484851362}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Polyhedron_3.h>\n\n#include <iostream>\n#include <list>\n\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\n\ntypedef CGAL::Simple_cartesian<double>                       Kernel;\ntypedef Kernel::Vector_3                                     Vector;\ntypedef Kernel::Point_3                                      Point;\ntypedef CGAL::Polyhedron_3<Kernel>                           Polyhedron;\n\ntypedef boost::graph_traits<Polyhedron>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<Polyhedron>::vertex_iterator   vertex_iterator;\ntypedef boost::graph_traits<Polyhedron>::edge_descriptor   edge_descriptor;\n\n// The BGL makes heavy use of indices associated to the vertices\n// We use a std::map to store the index\n\ntypedef std::map<vertex_descriptor,int> Vertex_index_map;\nVertex_index_map vertex_index_map;\n\n// A std::map is not a property map, because it is not lightweight\ntypedef boost::associative_property_map<Vertex_index_map> Vertex_index_pmap;\nVertex_index_pmap vertex_index_pmap(vertex_index_map);\n\nvoid\nkruskal(const Polyhedron& P)\n{\n  // associate indices to the vertices\n  vertex_iterator vb, ve;\n  int index = 0;\n  \n  // boost::tie assigns the first and second element of the std::pair\n  // returned by boost::vertices to the variables vb and ve\n  for(boost::tie(vb, ve)=vertices(P); vb!=ve; ++vb){\n    vertex_index_pmap[*vb]= index++;\n  }\n\n  \n  // We use the default edge weight which is the length of the edge\n  // This property map is defined in graph_traits_Polyhedron_3.h\n\n  // In the function call you can see a named parameter: vertex_index_map\n  std::list<edge_descriptor> mst;\n\n  boost::kruskal_minimum_spanning_tree(P, \n                                       std::back_inserter(mst), \n                                       boost::vertex_index_map(vertex_index_pmap));\n\n  std::cout << \"#VRML V2.0 utf8\\n\"\n    \"Shape {\\n\"\n    \"  appearance Appearance {\\n\"\n    \"    material Material { emissiveColor 1 0 0}}\\n\"\n    \"    geometry\\n\"\n    \"    IndexedLineSet {\\n\"\n    \"      coord Coordinate {\\n\"\n    \"        point [ \\n\";\n\n  for(boost::tie(vb, ve) = vertices(P); vb!=ve; ++vb){\n    std::cout <<  \"        \" << (*vb)->point() << \"\\n\";\n  }\n\n  std::cout << \"        ]\\n\"\n               \"     }\\n\"\n    \"      coordIndex [\\n\";\n\n  for(std::list<edge_descriptor>::iterator it = mst.begin(); it != mst.end(); ++it)\n  {\n    edge_descriptor e = *it ;\n    vertex_descriptor s = source(e,P);\n    vertex_descriptor t = target(e,P);\n    std::cout << \"      \" << vertex_index_pmap[s] << \", \" << vertex_index_pmap[t] <<  \", -1\\n\";\n  }\n\n  std::cout << \"]\\n\"\n    \"  }#IndexedLineSet\\n\"\n    \"}# Shape\\n\";\n}\n\n\nint main() {\n\n  Polyhedron P;\n  Point a(1,0,0);\n  Point b(0,1,0);\n  Point c(0,0,1);\n  Point d(0,0,0);\n\n  P.make_tetrahedron(a,b,c,d);\n\n  kruskal(P);\n\n  return 0;\n}\n", "meta": {"hexsha": "4d55340c4d5adcfd7754b50e44dce08fb2e1bdfd", "size": 2835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_polyhedron_3/kruskal.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_polyhedron_3/kruskal.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_polyhedron_3/kruskal.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 28.9285714286, "max_line_length": 95, "alphanum_fraction": 0.6215167549, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5950498103083945}}
{"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 * @author Eric Cousineau <eacousineau@gmail.com>, member of Dr. Aaron\n * Ames's AMBER Lab\n */\n#ifndef EIGEN_UTILITIES_TYPES_H\n    #define EIGEN_UTILITIES_TYPES_H\n\n#include <Eigen/Dense>\n\nnamespace Eigen\n{\n\ntypedef Matrix<double, 6, 1> Vector6d;\ntypedef Matrix<double, 6, 6> Matrix6d;\n\n}\n\n#endif // EIGEN_UTILITIES_TYPES_H\n", "meta": {"hexsha": "a63b6860ee20183093d46fe55cc991cf60839fcb", "size": 327, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "eigen_utilities/include/eigen_utilities/types.hpp", "max_stars_repo_name": "noelc-s/amber_developer_stack", "max_stars_repo_head_hexsha": "dda28b1b79f8df6eb56c41a0e1b5c1d167631176", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-18T04:36:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T04:36:22.000Z", "max_issues_repo_path": "eigen_utilities/include/eigen_utilities/types.hpp", "max_issues_repo_name": "noelc-s/amber_developer_stack", "max_issues_repo_head_hexsha": "dda28b1b79f8df6eb56c41a0e1b5c1d167631176", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen_utilities/include/eigen_utilities/types.hpp", "max_forks_repo_name": "noelc-s/amber_developer_stack", "max_forks_repo_head_hexsha": "dda28b1b79f8df6eb56c41a0e1b5c1d167631176", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-04T21:22:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T21:22:48.000Z", "avg_line_length": 17.2105263158, "max_line_length": 70, "alphanum_fraction": 0.7370030581, "num_tokens": 100, "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   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": "#include \"mkldnn.hpp\"\r\n#include \"bfloat16.hpp\"\r\n#include \"mkldnn_debug.h\"\r\n\r\n#include \"mkldnn.h\"\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <chrono>\r\n\r\n#include <mkl.h>\r\n#include <Eigen/Dense>\r\n\r\n//#define XBYAK_NO_OP_NAMES\r\n//#include <xbyak.h>\r\n\r\ntypedef mkldnn::impl::bfloat16_t bfloat16;\r\n\r\nvoid init_param(int m, int n, int k, float *A, float *B, float *C, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16, Eigen::MatrixXf& A_mat, Eigen::MatrixXf& B_mat, Eigen::MatrixXf& C_mat);\r\n\r\ndouble test_eigen_sgemm(Eigen::MatrixXf& A_mat, Eigen::MatrixXf& B_mat, Eigen::MatrixXf& C_mat, int m, int n, int k);\r\ndouble test_mkl_sgemm(float *A, float *B, float *C, int m, int n, int k);\r\ndouble test_mkl_sgemm_transB(float *A, float *B, float *C, int m, int n, int k);\r\ndouble test_mkldnn_sgemm(float *A, float *B, float *C, int m, int n, int k);\r\ndouble test_mkldnn_gemm_bf16bf16f32(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_mkldnn_gemm_bf16bf16f32_transB(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_mkldnn_gemm_bf16bf16f32_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_mkldnn_gemm_bf16bf16f32_transB_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_mkldnn_gemm_bf16bf16f32_omp_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_mkldnn_gemm_bf16bf16f32_transB_omp_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_mkldnn_cvt_float_to_bfloat16(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\ndouble test_mkldnn_omp_cvt_float_to_bfloat16(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\n//double test_jit_cvt_float_to_bfloat16(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16);\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n    printf(\"./gemmbench m n k\\nargc = %d\\n\", argc);\r\n    for(int ndx = 0; ndx != argc; ++ndx)\r\n        printf(\"argv[%d] --> %s\\n\", ndx, argv[ndx]);\r\n\r\n    int m = atoi(argv[1]);\r\n    int n = atoi(argv[2]);\r\n    int k = atoi(argv[3]);\r\n\r\n    bfloat16 *A_bf16 = new bfloat16[m*k];\r\n    bfloat16 *B_bf16 = new bfloat16[k*n];\r\n    bfloat16 *C_bf16 = new bfloat16[m*n];\r\n\r\n    float *A = new float[m*k];\r\n    float *B = new float[k*n];\r\n    float *C = new float[m*n];\r\n\r\n    Eigen::MatrixXf A_mat(m, k);\r\n    Eigen::MatrixXf B_mat(k, n);\r\n    Eigen::MatrixXf C_mat(m, n);\r\n\r\n    init_param(m, n, k, A, B, C, A_bf16, B_bf16, C_bf16, A_mat, B_mat, C_mat);\r\n    std::cout << \"\\nstarting...\" << std::endl;\r\n\r\n    double t_eigen_sgemm  = test_eigen_sgemm(A_mat, B_mat, C_mat, m, n, k);\r\n\r\n    double t_mkl_sgemm    = test_mkl_sgemm(A, B, C, m, n, k);\r\n    double t_mkl_sgemm_tB = test_mkl_sgemm_transB(A, B, C, m, n, k);\r\n\r\n    double t_mkldnn_sgemm = test_mkldnn_sgemm(A, B, C, m, n, k);\r\n    double t_mkldnn_gemm_bf16 = test_mkldnn_gemm_bf16bf16f32(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_mkldnn_gemm_bf16_tB = test_mkldnn_gemm_bf16bf16f32_transB(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_mkldnn_gemm_bf16_cvt = test_mkldnn_gemm_bf16bf16f32_cvt(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_mkldnn_gemm_bf16_tB_cvt = test_mkldnn_gemm_bf16bf16f32_transB_cvt(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_mkldnn_gemm_bf16_omp_cvt = test_mkldnn_gemm_bf16bf16f32_omp_cvt(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_mkldnn_gemm_bf16_tB_omp_cvt = test_mkldnn_gemm_bf16bf16f32_transB_omp_cvt(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_mkldnn_cvt     = test_mkldnn_cvt_float_to_bfloat16(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    double t_mkldnn_omp_cvt = test_mkldnn_omp_cvt_float_to_bfloat16(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n    //double t_mkldnn_jit_cvt = test_jit_cvt_float_to_bfloat16(A, B, C, m, n, k, A_bf16, B_bf16, C_bf16);\r\n\r\n    printf(\"\\n>> omp num_procs: %d\\n\", omp_get_num_procs());\r\n    printf(\"eigen gemm: \\t%.6f\\n\", t_eigen_sgemm);\r\n    printf(\"mkl sgemm: \\t%.6f ms --> baseline\\n\", t_mkl_sgemm);\r\n    printf(\"mkl sgemm+transB:            \\t%.6f \\t+%.3fX\\n\", t_mkl_sgemm_tB,                t_mkl_sgemm/t_mkl_sgemm_tB);\r\n    printf(\"mkldnn sgemm:                \\t%.6f \\t+%.3fX\\n\", t_mkldnn_sgemm,                t_mkl_sgemm/t_mkldnn_sgemm);\r\n    printf(\"mkldnn bgemm:                \\t%.6f \\t+%.3fX\\n\", t_mkldnn_gemm_bf16,            t_mkl_sgemm/t_mkldnn_gemm_bf16);\r\n    printf(\"mkldnn bgemm+transB:         \\t%.6f \\t+%.3fX\\n\", t_mkldnn_gemm_bf16_tB,         t_mkl_sgemm/t_mkldnn_gemm_bf16_tB);\r\n    printf(\"mkldnn bgemm+cvt:            \\t%.6f \\t+%.3fX\\n\", t_mkldnn_gemm_bf16_cvt,        t_mkl_sgemm/t_mkldnn_gemm_bf16_cvt);\r\n    printf(\"mkldnn bgemm+transB+cvt:     \\t%.6f \\t+%.3fX\\n\", t_mkldnn_gemm_bf16_tB_cvt,     t_mkl_sgemm/t_mkldnn_gemm_bf16_tB_cvt);\r\n    printf(\"mkldnn bgemm+omp_cvt:        \\t%.6f \\t+%.3fX\\n\", t_mkldnn_gemm_bf16_omp_cvt,    t_mkl_sgemm/t_mkldnn_gemm_bf16_omp_cvt);\r\n    printf(\"mkldnn bgemm+transB+omp_cvt: \\t%.6f \\t+%.3fX\\n\", t_mkldnn_gemm_bf16_tB_omp_cvt, t_mkl_sgemm/t_mkldnn_gemm_bf16_tB_omp_cvt);\r\n    printf(\"mkldnn cvt:     \\t%.6f \\tt/bgemm:   %.3f%\\n\", t_mkldnn_cvt,     t_mkldnn_cvt/t_mkldnn_gemm_bf16*100);\r\n    printf(\"mkldnn omp_cvt: \\t%.6f \\tt/bgemm:   %.3f%\\n\", t_mkldnn_omp_cvt, t_mkldnn_omp_cvt/t_mkldnn_gemm_bf16*100);\r\n    //printf(\"mkldnn jit_cvt: \\t%.6f \\tt/bgemm:   %.3f%\\n\", t_mkldnn_jit_cvt, t_mkldnn_jit_cvt/t_mkldnn_gemm_bf16*100);\r\n\r\n    delete[] A_bf16;\r\n    delete[] B_bf16;\r\n    delete[] C_bf16;\r\n\r\n    delete[] A;\r\n    delete[] B;\r\n    delete[] C;\r\n\r\n    return 0;\r\n}\r\n\r\n\r\nvoid init_param(int m, int n, int k, float *A, float *B, float *C, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16, Eigen::MatrixXf& A_mat, Eigen::MatrixXf& B_mat, Eigen::MatrixXf& C_mat)\r\n{\r\n    for (int i = 0; i < m; ++i) {\r\n        for (int j = 0; j < k; ++j) {\r\n            A_bf16[i*k+j] = (bfloat16)1.1;\r\n            A[i*k+j] = 1.1;\r\n            A_mat.row(i).col(j) << 1.1;\r\n        }\r\n    }\r\n\r\n    for (int i = 0; i < k; ++i) {\r\n        for (int j = 0; j < n; ++j) {\r\n            B_bf16[i*n+j] = (bfloat16)1.1;\r\n            B[i*n+j] = 1.1;\r\n            B_mat.row(i).col(j) << 1.1;\r\n        }\r\n    }\r\n\r\n    for (int i = 0; i < m; ++i) {\r\n        for (int j = 0; j < n; ++j) {\r\n            C_bf16[i*n+j] = (bfloat16)1.1;\r\n            C[i*n+j] = 1.1;\r\n            C_mat.row(i).col(j) << 1.1;\r\n        }\r\n    }\r\n}\r\n\r\ndouble test_eigen_sgemm(Eigen::MatrixXf& A_mat, Eigen::MatrixXf& B_mat, Eigen::MatrixXf& C_mat, int m, int n, int k)\r\n{\r\n    C_mat = A_mat * B_mat;\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        C_mat = A_mat * B_mat;\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C_mat(0, 0) << \",\" << C_mat(m-1, n-1) << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkl_sgemm(float *A, float *B, float *C, int m, int n, int k)\r\n{\r\n    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0, A, k, B, n, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0, A, k, B, n, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkl_sgemm_transB(float *A, float *B, float *C, int m, int n, int k)\r\n{\r\n    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, m, n, k, 1.0, A, k, B, k, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, m, n, k, 1.0, A, k, B, k, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkldnn_sgemm(float *A, float *B, float *C, int m, int n, int k)\r\n{\r\n    mkldnn_sgemm('N', 'N', m, n, k, 1.0, A, k, B, n, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        mkldnn_sgemm('N', 'N', m, n, k, 1.0, A, k, B, n, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkldnn_gemm_bf16bf16f32(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    mkldnn_gemm_bf16bf16f32('N', 'N', m, n, k, 1.0, A_bf16, k, B_bf16, n, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        mkldnn_gemm_bf16bf16f32('N', 'N', m, n, k, 1.0, A_bf16, k, B_bf16, n, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkldnn_gemm_bf16bf16f32_transB(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    mkldnn_gemm_bf16bf16f32('N', 'T', m, n, k, 1.0, A_bf16, k, B_bf16, k, 0.0, C, n);\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        mkldnn_gemm_bf16bf16f32('N', 'T', m, n, k, 1.0, A_bf16, k, B_bf16, k, 0.0, C, n);\r\n    }\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkldnn_gemm_bf16bf16f32_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    mkldnn::impl::cvt_float_to_bfloat16(A_bf16, A, m*k);\r\n    mkldnn_gemm_bf16bf16f32('N', 'N', m, n, k, 1.0, A_bf16, k, B_bf16, n, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        mkldnn::impl::cvt_float_to_bfloat16(A_bf16, A, m*k);\r\n        mkldnn_gemm_bf16bf16f32('N', 'N', m, n, k, 1.0, A_bf16, k, B_bf16, n, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkldnn_gemm_bf16bf16f32_transB_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n\r\n    mkldnn::impl::cvt_float_to_bfloat16(A_bf16, A, m*k);\r\n    mkldnn_gemm_bf16bf16f32('N', 'T', m, n, k, 1.0, A_bf16, k, B_bf16, k, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        mkldnn::impl::cvt_float_to_bfloat16(A_bf16, A, m*k);\r\n        mkldnn_gemm_bf16bf16f32('N', 'T', m, n, k, 1.0, A_bf16, k, B_bf16, k, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkldnn_gemm_bf16bf16f32_omp_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    #pragma omp parallel for num_threads(omp_get_num_procs())\r\n    for (int i = 0; i < m; ++i)\r\n        mkldnn::impl::cvt_float_to_bfloat16(A_bf16+i*k, A+i*k, k);\r\n    mkldnn_gemm_bf16bf16f32('N', 'N', m, n, k, 1.0, A_bf16, k, B_bf16, n, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        #pragma omp parallel for num_threads(omp_get_num_procs())\r\n        for (int i = 0; i < m; ++i)\r\n            mkldnn::impl::cvt_float_to_bfloat16(A_bf16+i*k, A+i*k, k);\r\n\tmkldnn_gemm_bf16bf16f32('N', 'N', m, n, k, 1.0, A_bf16, k, B_bf16, n, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkldnn_gemm_bf16bf16f32_transB_omp_cvt(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    #pragma omp parallel for num_threads(omp_get_num_procs())\r\n    for (int i = 0; i < m; ++i)\r\n        mkldnn::impl::cvt_float_to_bfloat16(A_bf16+i*k, A+i*k, k);\r\n    mkldnn_gemm_bf16bf16f32('N', 'T', m, n, k, 1.0, A_bf16, k, B_bf16, k, 0.0, C, n);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        #pragma omp parallel for num_threads(omp_get_num_procs())\r\n        for (int i = 0; i < m; ++i)\r\n            mkldnn::impl::cvt_float_to_bfloat16(A_bf16+i*k, A+i*k, k);\r\n\tmkldnn_gemm_bf16bf16f32('N', 'T', m, n, k, 1.0, A_bf16, k, B_bf16, k, 0.0, C, n);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkldnn_cvt_float_to_bfloat16(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    mkldnn::impl::cvt_float_to_bfloat16(A_bf16, A, m*k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        mkldnn::impl::cvt_float_to_bfloat16(A_bf16, A, m*k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n\r\ndouble test_mkldnn_omp_cvt_float_to_bfloat16(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    #pragma omp parallel for num_threads(omp_get_num_procs())\r\n    for (int i = 0; i < m; ++i)\r\n        mkldnn::impl::cvt_float_to_bfloat16(A_bf16+i*k, A+i*k, k);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        #pragma omp parallel for num_threads(omp_get_num_procs())\r\n        for (int i = 0; i < m; ++i)\r\n            mkldnn::impl::cvt_float_to_bfloat16(A_bf16+i*k, A+i*k, k);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n/*\r\nstruct Code : Xbyak::CodeGenerator {\r\n    const Xbyak::Reg64& src;\r\n    const Xbyak::Reg64& dst;\r\n    const Xbyak::Reg32& loop;\r\n    Code()\r\n        : src(rsi)\r\n        , dst(rdi)\r\n        , loop(edx)\r\n    {\r\n        Xbyak::Label l0;\r\n        L(l0);\r\n\r\n        vcvtneps2bf16(ymm0, zword[src]);\r\n        vmovups(yword[dst], ymm0);\r\n        add(src, 64);\r\n        add(dst, 32);\r\n\r\n        dec(loop);\r\n        jg(l0, T_NEAR);\r\n\r\n        mov(eax, loop);\r\n        ret();\r\n    }\r\n};\r\n\r\ndouble test_jit_cvt_float_to_bfloat16(float *A, float *B, float *C, int m, int n, int k, bfloat16 *A_bf16, bfloat16 *B_bf16, bfloat16 *C_bf16)\r\n{\r\n    Code c;\r\n    int (*f)(void*, void*, int) = c.getCode<int (*)(void*, void*, int)>();\r\n    int num = m*k/16;\r\n    int ret = f(A_bf16, A, num);\r\n\r\n    auto tag_1 = std::chrono::high_resolution_clock::now();\r\n    for (int i = 0; i < 1000; ++i) {\r\n        f(A_bf16, A, num);\r\n    }\r\n\r\n    auto tag_2 = std::chrono::high_resolution_clock::now();\r\n    auto tag_diff = std::chrono::duration<double>(tag_2 - tag_1).count();\r\n    std::cout << \"result: \" << C[0] << \",\" << C[m*n-1] << std::endl;\r\n\r\n    return tag_diff;\r\n}\r\n*/\r\n", "meta": {"hexsha": "a021d4927eb9268b133257df64606762a3fed0fb", "size": 16707, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tools/gemm_bench/gemmbench.cc", "max_stars_repo_name": "yao-matrix/mProto", "max_stars_repo_head_hexsha": "e5fecce2693056ac53f7d34d00801829ea1094c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T04:55:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-18T06:56:10.000Z", "max_issues_repo_path": "tools/gemm_bench/gemmbench.cc", "max_issues_repo_name": "yao-matrix/mProto", "max_issues_repo_head_hexsha": "e5fecce2693056ac53f7d34d00801829ea1094c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/gemm_bench/gemmbench.cc", "max_forks_repo_name": "yao-matrix/mProto", "max_forks_repo_head_hexsha": "e5fecce2693056ac53f7d34d00801829ea1094c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-27T01:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T05:32:04.000Z", "avg_line_length": 43.3948051948, "max_line_length": 194, "alphanum_fraction": 0.6059136889, "num_tokens": 6582, "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": "///////////////////////////////////////////////////////////////////////////////\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": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"Envelope.hpp\"\n#include \"../util/ButterworthHPFilter.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/SlideUDFilter.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass EnvelopeSegmentation\n{\n\n  using ArrayXd = Eigen::ArrayXd;\n\npublic:\n  void init(double floor, double hiPassFreq)\n  {\n    // mFastSlide.init(floor);\n    // mSlowSlide.init(floor);\n    mEnvelope.init(floor,hiPassFreq); \n    mDebounceCount = 1;\n    // initFilters(hiPassFreq);\n    // mHiPassFreq = hiPassFreq;\n    mPrevValue = 0;\n    mState = false;\n    // mInitialized = true;\n  }\n\n  double processSample(const double in, double onThreshold, double offThreshold,\n                       double floor, index fastRampUpTime, index slowRampUpTime,\n                       index fastRampDownTime, index slowRampDownTime,\n                       double hiPassFreq, index debounce)\n  {\n    // using namespace std;\n    // assert(mInitialized);\n    // mFastSlide.updateCoeffs(fastRampUpTime, fastRampDownTime);\n    // mSlowSlide.updateCoeffs(slowRampUpTime, slowRampDownTime);\n    // double filtered = in;\n    // if (hiPassFreq != mHiPassFreq)\n    // {\n    //   initFilters(hiPassFreq);\n    //   mHiPassFreq = hiPassFreq;\n    // }\n    // if (mHiPassFreq > 0){\n    //   filtered = mHiPass2.processSample(mHiPass1.processSample(in));\n    // }\n    // double rectified = abs(filtered);\n    // double dB = 20 * log10(rectified);\n    // double clipped = max(dB, floor);\n    // double fast = mFastSlide.processSample(clipped);\n    // double slow = mSlowSlide.processSample(clipped);\n    // double value = fast - slow;\n\n\n    double value =\n        mEnvelope.processSample(in, floor, fastRampUpTime, slowRampUpTime,\n                                fastRampDownTime, slowRampDownTime, hiPassFreq);\n    double detected = 0;\n\n    if (!mState && value > onThreshold && mPrevValue < onThreshold &&\n        mDebounceCount == 0)\n    {\n      detected = 1.0;\n      mDebounceCount = debounce;\n      mState = true;\n    }\n    else\n    {\n      if (mDebounceCount > 0) mDebounceCount--;\n    }\n    if (mState && value < offThreshold) { mState = false; }\n    mPrevValue = value;\n    return detected;\n  }\n\n  bool initialized() { return mEnvelope.initialized(); }\n\nprivate:\n//  void initFilters(double cutoff)\n//  {\n//    mHiPass1.init(cutoff);\n//    mHiPass2.init(cutoff);\n//  }\n  \n  Envelope mEnvelope; \n  // double mHiPassFreq{0};\n  index  mDebounceCount{1};\n  double mPrevValue{0};\n  // bool   mInitialized{false};\n  bool   mState{false};\n\n  // ButterworthHPFilter mHiPass1;\n  // ButterworthHPFilter mHiPass2;\n  // SlideUDFilter       mFastSlide;\n  // SlideUDFilter       mSlowSlide;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "296c6bae18b35d945f3e8805ef3ccf521254f2f3", "size": 3227, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/EnvelopeSegmentation.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/EnvelopeSegmentation.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/EnvelopeSegmentation.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3070175439, "max_line_length": 80, "alphanum_fraction": 0.6603656647, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5948158811165136}}
{"text": "#include <algorithm>\n#include <cinttypes>\n#include <iostream>\n#include <vector>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n\n#include \"benchmark.h\"\n#include \"bitmap.h\"\n#include \"builder.h\"\n#include \"command_line.h\"\n#include \"graph.h\"\n#include \"pvector.h\"\n#include \"timer.h\"\n\nusing namespace std;\n\nint Stoer_Wagner(const WGraph &g)\n{\n    Timer t;\n    typedef boost::property<boost::edge_weight_t, int> EdgeWeightProp;\n    typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, EdgeWeightProp> Graph;\n    Graph conn(g.num_nodes());\n    for (auto i : g.vertices())\n        for(auto j : g.out_neigh(i))\n        {\n            if(i < j.v)\n                boost::add_edge(i, j.v, j.w, conn);\n        }\n    \n    auto weights = get(boost::edge_weight, conn);\n    t.Start();\n    int res = boost::stoer_wagner_min_cut(conn, weights);\n    t.Stop();\n    cout << g.num_nodes() << \", \" << g.num_edges() << \", \"<<  t.Seconds() << \", \" << res << \"\\n\";\n    return res;\n}\n\nvoid DummyPrint(const WGraph &g, size_t min_cut_value)\n{\n    cout << \"min cut value: \" << min_cut_value << endl;\n}\n\nbool DummyVerifier(const WGraph &g, size_t test_min)\n{\n    return true;\n}\n\nint main(int argc, char *argv[])\n{\n    CLApp cli(argc, argv, \"stoer_wagner\");\n    if (!cli.ParseArgs())\n        return -1;\n    WeightedBuilder b(cli);\n    WGraph g = b.MakeGraph();\n    BenchmarkKernel(cli, g, Stoer_Wagner,DummyPrint, DummyVerifier);\n    return 0;\n}", "meta": {"hexsha": "6fd7fc19a6a94f3a3dd38d39bfdd66e8bf6b5227", "size": 1545, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/stoer_wagner.cc", "max_stars_repo_name": "trinhhe/BA", "max_stars_repo_head_hexsha": "32db7cc8aec3f24d0ef9657d9a99d8217a3731f3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stoer_wagner.cc", "max_issues_repo_name": "trinhhe/BA", "max_issues_repo_head_hexsha": "32db7cc8aec3f24d0ef9657d9a99d8217a3731f3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stoer_wagner.cc", "max_forks_repo_name": "trinhhe/BA", "max_forks_repo_head_hexsha": "32db7cc8aec3f24d0ef9657d9a99d8217a3731f3", "max_forks_repo_licenses": ["BSD-3-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.186440678, "max_line_length": 122, "alphanum_fraction": 0.6427184466, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5948158640550179}}
{"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": "/* ----------------------------------------------------------------------------\n\n * QuadricSLAM Copyright 2020, ARC Centre of Excellence for Robotic Vision, Queensland University of Technology (QUT)\n * Brisbane, QLD 4000\n * All Rights Reserved\n * Authors: Lachlan Nicholson, et al. (see THANKS for the full author list)\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file ConstrainedDualQuadric.cpp\n * @date Apr 14, 2020\n * @author Lachlan Nicholson\n * @brief a constrained dual quadric \n */\n\n#include <quadricslam/geometry/AlignedBox2.h>\n#include <quadricslam/geometry/ConstrainedDualQuadric.h>\n#include <quadricslam/geometry/QuadricCamera.h>\n#include <quadricslam/base/Utilities.h>\n\n#include <Eigen/Eigenvalues>\n#include <iostream>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/* ************************************************************************* */\nConstrainedDualQuadric::ConstrainedDualQuadric() {\n  pose_ = Pose3();\n  radii_ = Vector3(1,1,1);\n}\n\n/* ************************************************************************* */\nConstrainedDualQuadric::ConstrainedDualQuadric(const Matrix44& dQ) {\n  *this = ConstrainedDualQuadric::constrain(dQ);\n}\n\n/* ************************************************************************* */\nConstrainedDualQuadric ConstrainedDualQuadric::constrain(const Matrix4& dual_quadric) {\n\n  // normalize if required\n  Matrix4 normalized_dual_quadric(dual_quadric);\n  if (dual_quadric(3,3) != 1.0) {\n    normalized_dual_quadric = dual_quadric/dual_quadric(3,3);\n  }\n\n  // extract translation\n  Point3 translation(normalized_dual_quadric.block(0,3,3,1));\n\n  // calculate the point quadric matrix\n  Matrix4 point_quadric = normalized_dual_quadric.inverse();\n  Matrix4 normalized_point_quadric = point_quadric;\n  if (point_quadric(3,3) != 1.0) {\n    normalized_point_quadric = point_quadric/point_quadric(3,3);\n  }\n\n  // extract shape\n  auto lambdaa = normalized_point_quadric.block(0,0,3,3).eigenvalues();\n  Vector3 shape = Eigen::sqrt(\n    -1.0*normalized_point_quadric.determinant() \\\n    / normalized_point_quadric.block(0,0,3,3).determinant() \\\n    *  1.0/lambdaa.array()  ).abs();\n\n  // extract rotation \n  Eigen::EigenSolver<Eigen::Matrix<double,3,3>> s(normalized_point_quadric.block(0,0,3,3));\n  Matrix3 rotation_matrix = s.eigenvectors().real();\n\n  // ensure rotation is right-handed\n  if (!(fabs(1.0-rotation_matrix.determinant()) < 1e-8)) {\n    rotation_matrix *= -1.0 * Matrix3::Identity();\n  }\n  Rot3 rotation(rotation_matrix);\n\n  return ConstrainedDualQuadric(rotation, translation, shape);\n}\n\n/* ************************************************************************* */\nMatrix44 ConstrainedDualQuadric::matrix(OptionalJacobian<16,9> dQ_dq) const {\n  Matrix44 Z = pose_.matrix();\n  Matrix44 Qc = (Vector4() << (radii_).array().pow(2), -1.0).finished().asDiagonal();\n  Matrix44 Q = Z * Qc * Z.transpose(); \n\n  if (dQ_dq) {\n\n    Eigen::Matrix<double, 16,6> dZ_dx;\n    utils::matrix(pose_, dZ_dx); // NOTE: this will recalculate pose.matrix\n    Eigen::Matrix<double, 16,9> dZ_dq = Matrix::Zero(16,9);\n    dZ_dq.block(0,0,16,6) = dZ_dx;\n\n    Eigen::Matrix<double, 16,9> dQc_dq = Matrix::Zero(16,9);\n    dQc_dq(0,6) = 2.0 * radii_(0);\n    dQc_dq(5,7) = 2.0 * radii_(1);\n    dQc_dq(10,8) = 2.0 * radii_(2);\n    \n    using utils::kron;\n    static Matrix4 I44 = Matrix::Identity(4,4);\n    static Eigen::Matrix<double, 16,16> T44 = utils::TVEC(4,4);\n    *dQ_dq = kron(I44, Z*Qc) * T44 * dZ_dq  +  kron(Z, I44) * (kron(I44, Z)*dQc_dq + kron(Qc, I44)*dZ_dq);\n  }\n  return Q;\n}\n\n/* ************************************************************************* */\nMatrix44 ConstrainedDualQuadric::normalizedMatrix(void) const {\n  Matrix44 Q = this->matrix();\n  return Q/Q(3,3);\n}\n\n/* ************************************************************************* */\n// TODO: vectorize\nAlignedBox3 ConstrainedDualQuadric::bounds() const {\n  Matrix44 dE = this->matrix();\n  double x_min = (dE(0,3) + std::sqrt(dE(0,3) * dE(0,3) - (dE(0,0) * dE(3,3)))) / dE(3,3);\n  double y_min = (dE(1,3) + std::sqrt(dE(1,3) * dE(1,3) - (dE(1,1) * dE(3,3)))) / dE(3,3);\n  double z_min = (dE(2,3) + std::sqrt(dE(2,3) * dE(2,3) - (dE(2,2) * dE(3,3)))) / dE(3,3);\n  double x_max = (dE(0,3) - std::sqrt(dE(0,3) * dE(0,3) - (dE(0,0) * dE(3,3)))) / dE(3,3);\n  double y_max = (dE(1,3) - std::sqrt(dE(1,3) * dE(1,3) - (dE(1,1) * dE(3,3)))) / dE(3,3);\n  double z_max = (dE(2,3) - std::sqrt(dE(2,3) * dE(2,3) - (dE(2,2) * dE(3,3)))) / dE(3,3);\n  return AlignedBox3((Vector6() << x_min, y_min, z_min, x_max, y_max, z_max).finished());\n}\n\n/* ************************************************************************* */\nbool ConstrainedDualQuadric::isBehind(const Pose3& cameraPose) const {\n  Pose3 rpose = cameraPose.between(this->pose());\n  if (rpose.z() < 0.0) { return true;}\n  return false;\n}\n\n/* ************************************************************************* */\nbool ConstrainedDualQuadric::contains(const Pose3& cameraPose) const {\n  Vector4 cameraPoint = (Vector4() << cameraPose.translation().vector(), 1.0).finished();\n  double pointError = cameraPoint.transpose() * this->matrix().inverse() * cameraPoint;\n  if (pointError <= 0.0) { return true;}\n  return false;\n}\n\n/* ************************************************************************* */\nConstrainedDualQuadric ConstrainedDualQuadric::Retract(const Vector9& v) {\n  Pose3 pose = Pose3::Retract(v.head<6>());\n  Vector3 radii = v.tail<3>();\n  return ConstrainedDualQuadric(pose, radii);\n}\n\n/* ************************************************************************* */\nVector9 ConstrainedDualQuadric::LocalCoordinates(const ConstrainedDualQuadric& q) {\n  Vector9 v = Vector9::Zero();\n  v.head<6>() = Pose3::LocalCoordinates(q.pose_);\n  v.tail<3>() = q.radii_;\n  return v;\n}\n\n/* ************************************************************************* */\nConstrainedDualQuadric ConstrainedDualQuadric::retract(const Vector9& v) const {\n  Pose3 pose = pose_.retract(v.head<6>());\n  Vector3 radii = radii_ + v.tail<3>();\n  return ConstrainedDualQuadric(pose, radii);\n}\n\n/* ************************************************************************* */\nVector9 ConstrainedDualQuadric::localCoordinates(const ConstrainedDualQuadric& other) const {\n  Vector9 v = Vector9::Zero();\n  v.head<6>() = pose_.localCoordinates(other.pose_);\n  v.tail<3>() = other.radii_ - radii_;\n  return v;\n}\n\n/* ************************************************************************* */\nvoid ConstrainedDualQuadric::print(const std::string& s) const {\n  cout << s;\n  cout << this->matrix() << endl;\n}\n\n/* ************************************************************************* */\nbool ConstrainedDualQuadric::equals(const ConstrainedDualQuadric& other, double tol) const {\n  return this->normalizedMatrix().isApprox(other.normalizedMatrix(), tol);\n}\n\n/* ************************************************************************* */\nvoid ConstrainedDualQuadric::addToValues(Values &v, const Key& k) { v.insert(k,*this);}\n\n/* ************************************************************************* */\nConstrainedDualQuadric ConstrainedDualQuadric::getFromValues(const Values &v, const Key& k) { return v.at<ConstrainedDualQuadric>(k);}\n\n} // namespace gtsam", "meta": {"hexsha": "44ef1c2d142e861d7b70c346331bbea74305a334", "size": 7294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "quadricslam/geometry/ConstrainedDualQuadric.cpp", "max_stars_repo_name": "moshanATucsd/quadricslam", "max_stars_repo_head_hexsha": "68222c44d50dab6166a63848c22c087b81fdbe55", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quadricslam/geometry/ConstrainedDualQuadric.cpp", "max_issues_repo_name": "moshanATucsd/quadricslam", "max_issues_repo_head_hexsha": "68222c44d50dab6166a63848c22c087b81fdbe55", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-29T22:03:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-29T22:03:16.000Z", "max_forks_repo_path": "quadricslam/geometry/ConstrainedDualQuadric.cpp", "max_forks_repo_name": "moshanATucsd/quadricslam", "max_forks_repo_head_hexsha": "68222c44d50dab6166a63848c22c087b81fdbe55", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-12T09:53:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-12T09:53:55.000Z", "avg_line_length": 39.0053475936, "max_line_length": 134, "alphanum_fraction": 0.5534686043, "num_tokens": 2041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5947427227553314}}
{"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 <CGAL/Simple_cartesian.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n\n#include <boost/config.hpp>\n#include <boost/version.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include <CGAL/IO/WKT.h>\n\n//typedef CGAL::Simple_cartesian<CGAL::Gmpq> Kernel;\ntypedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;\n\nint main(int argc, char* argv[])\n{\n  typedef CGAL::Point_2<Kernel> Point;\n  typedef std::vector<Point>  MultiPoint;\n\n  std::ifstream is((argc>1)?argv[1]:\"data/multipoint.wkt\");\n  MultiPoint mp;\n  CGAL::read_multi_point_WKT(is, mp);\n  for(const Point& p : mp)\n  {\n    std::cout<<p<<std::endl;\n  }\n  is.close();\n  return 0;\n}\n#else\nint main()\n{\n  return 0;\n}\n#endif\n", "meta": {"hexsha": "ce6020f4e23418870374682049a29452781e8a8f", "size": 800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Stream_support/examples/Stream_support/Point_WKT.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": "Stream_support/examples/Stream_support/Point_WKT.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": "Stream_support/examples/Stream_support/Point_WKT.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": 21.0526315789, "max_line_length": 75, "alphanum_fraction": 0.70875, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5947427116224193}}
{"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": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2020, 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 <gtest/gtest.h>\n#include <mrpt/math/wrap2pi.h>\n#include <mrpt/poses/SO_SE_average.h>\n#include <Eigen/Dense>\n\nusing namespace mrpt;\nusing namespace mrpt::poses;\nusing namespace mrpt::math;\nusing namespace std;\n\nvoid run_test_so2_avrg(\n\tconst double* angs, const size_t N, const double ang_correct_avr)\n{\n\tSO_average<2> so_avr;\n\tfor (size_t i = 0; i < N; i++) so_avr.append(angs[i]);\n\tconst double calc_avr = so_avr.get_average();\n\tEXPECT_NEAR(mrpt::math::wrapToPi(ang_correct_avr - calc_avr), .0, 1e-6);\n}\n\nTEST(SE2_SE3_avrg, SO2_average)\n{\n\t// Simple tests:\n\t{\n\t\tconst double angs[] = {.1};\n\t\tconst double ang_correct_avr = .1;\n\t\trun_test_so2_avrg(\n\t\t\tangs, sizeof(angs) / sizeof(angs[0]), ang_correct_avr);\n\t}\n\t{\n\t\tconst double angs[] = {.0, M_PI};\n\t\tconst double ang_correct_avr = .5 * M_PI;\n\t\trun_test_so2_avrg(\n\t\t\tangs, sizeof(angs) / sizeof(angs[0]), ang_correct_avr);\n\t}\n\t{\n\t\tconst double angs[] = {-0.75 * M_PI, 0.75 * M_PI};\n\t\tconst double ang_correct_avr = 1.0 * M_PI;\n\t\trun_test_so2_avrg(\n\t\t\tangs, sizeof(angs) / sizeof(angs[0]), ang_correct_avr);\n\t}\n\t{\n\t\tconst double angs[] = {-0.75 * M_PI, 0.75 * M_PI, 0.3 * M_PI};\n\t\t// const double angs_w[] = {1.0, 1.0, 0.1 };\n\t\tconst double ang_correct_avr = 2.3668403111754515;\n\t\trun_test_so2_avrg(\n\t\t\tangs, sizeof(angs) / sizeof(angs[0]), ang_correct_avr);\n\t}\n\t// Test launching an exception when there is no data:\n\t{\n\t\tconst double dummy[] = {0.};\n\t\ttry\n\t\t{\n\t\t\trun_test_so2_avrg(dummy, 0, 0);\n\t\t\tGTEST_FAIL()\n\t\t\t\t<< \"An exception should have been raised before this point!!\";\n\t\t}\n\t\tcatch (std::exception&)\n\t\t{\n\t\t\t// This error is expected, it's OK.\n\t\t}\n\t}\n}\n\nvoid run_test_so3_avrg(\n\tconst double* angs, const size_t N,\n\tconst mrpt::math::CMatrixDouble33& correct_avr)\n{\n\tSO_average<3> so_avr;\n\tfor (size_t i = 0; i < N; i++)\n\t{\n\t\tmrpt::poses::CPose3D rot(\n\t\t\t0, 0, 0, angs[3 * i + 0], angs[3 * i + 1], angs[3 * i + 2]);\n\t\tso_avr.append(rot.getRotationMatrix());\n\t}\n\tconst auto calc_avr = so_avr.get_average();\n\tEXPECT_NEAR((correct_avr - calc_avr).array().abs().sum(), .0, 1e-5);\n}\n\nTEST(SE2_SE3_avrg, SO3_average)\n{\n\t// Simple tests:\n\t{\n\t\tconst double angs[] = {.0, .0, .0};\n\t\tconst auto correct_avr =\n\t\t\tmrpt::poses::CPose3D(0, 0, 0, 0, 0, 0).getRotationMatrix();\n\t\trun_test_so3_avrg(\n\t\t\tangs, sizeof(angs) / (3 * sizeof(angs[0])), correct_avr);\n\t}\n\t{\n\t\tconst double angs[] = {-.75 * M_PI, .0, .0, .75 * M_PI, .0, .0};\n\t\tconst auto correct_avr =\n\t\t\tmrpt::poses::CPose3D(0, 0, 0, M_PI, 0, 0).getRotationMatrix();\n\t\trun_test_so3_avrg(\n\t\t\tangs, sizeof(angs) / (3 * sizeof(angs[0])), correct_avr);\n\t}\n\t{\n\t\tconst double angs[] = {.0, -0.2, .0, .0, 0.2, .0};\n\t\tconst auto correct_avr =\n\t\t\tmrpt::poses::CPose3D(0, 0, 0, 0, 0, 0).getRotationMatrix();\n\t\trun_test_so3_avrg(\n\t\t\tangs, sizeof(angs) / (3 * sizeof(angs[0])), correct_avr);\n\t}\n\t{\n\t\tconst double angs[] = {.0, .0, .3, .0, .0, -.3};\n\t\tconst auto correct_avr =\n\t\t\tmrpt::poses::CPose3D(0, 0, 0, 0, 0, 0).getRotationMatrix();\n\t\trun_test_so3_avrg(\n\t\t\tangs, sizeof(angs) / (3 * sizeof(angs[0])), correct_avr);\n\t}\n}\n", "meta": {"hexsha": "db0951fc331d6113dfe78f835d67d1cf2d211886", "size": 3652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/poses/src/SO_SE_average_unittest.cpp", "max_stars_repo_name": "swt2c/mrpt", "max_stars_repo_head_hexsha": "9b4fd246530ff94bb93f5703e61844c6f67aa0b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/poses/src/SO_SE_average_unittest.cpp", "max_issues_repo_name": "swt2c/mrpt", "max_issues_repo_head_hexsha": "9b4fd246530ff94bb93f5703e61844c6f67aa0b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/poses/src/SO_SE_average_unittest.cpp", "max_forks_repo_name": "swt2c/mrpt", "max_forks_repo_head_hexsha": "9b4fd246530ff94bb93f5703e61844c6f67aa0b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-30T14:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T14:06:37.000Z", "avg_line_length": 30.4333333333, "max_line_length": 80, "alphanum_fraction": 0.5843373494, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931457, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5946196794247922}}
{"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": "/** \n \\file random.cpp\n \\brief Random generation.\n \n \\author              Soproni Peter\n \\author              soproni@tmit.bme.hu\n \\date                2012 april\n*/\n\n#include \"random.h\"\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <ctime>\n#include <math.h>\n#include <iostream>\n\ndouble BRandom::GetNextUniformDouble(double _upperbound, double _lowerbound)\n{\n\tif  (_upperbound < _lowerbound)\n\t{\n\t\tdouble temp = _lowerbound;\n\t\t_lowerbound = _upperbound;\n\t\t_upperbound = temp;\n\t}\n\tdouble ret = generator();\n\tret *=_upperbound-_lowerbound;\n\tret +=_lowerbound;\n\treturn ret;\n}\n\ndouble BRandom::GetNextEponencialDouble(double _lambda)\n{\n\tif (_lambda > 0)\n\t\treturn -1*log(GetNextUniformDouble())*_lambda;\n\n\treturn log(GetNextUniformDouble())*_lambda;\n}\n\nint BRandom::GetNextUniformInt(int _upperbound , int _lowerbound)\n{\n\tif (_upperbound < _lowerbound)\n\t{\n\t\tint temp = _lowerbound;\n\t\t_lowerbound = _upperbound;\n\t\t_upperbound = temp;\n\t}\n\tint ret = (int)GetNextUniformDouble(_upperbound+1,_lowerbound);\n\tif (ret > _upperbound)\n\t\tret = _lowerbound;\n\tif (ret < _lowerbound)\n\t\tret = _upperbound;\n\treturn ret;\n}\n\nBRandom::BRandom() : generator(boost::minstd_rand(), boost::uniform_real<>(0,1))\n{\n}\n\nBRandom::BRandom(int seed) : generator(boost::minstd_rand(((seed == 0) ? -1 : seed)), boost::uniform_real<>(0,1))\n{\n}\n\n// To generate a solution for generating and deleting Randoms without memory leak\nvoid BRandom::atExit()\n{\n\tif (rand == NULL)\n\t\treturn;\n\n\tdelete rand;\n\trand = NULL;\n}\n\nBRandom* BRandom::instance()\n{\n\tif (rand == NULL)\n\t{\n\t\tstd::atexit(atExit);\n\t\tif (timeBasedSeed)\n\t\t\trand = new BRandom(time(NULL));\n\t\telse\n\t\t\trand = new BRandom();\n\t}\n\treturn rand;\n}\n\nBRandom* BRandom::rand = NULL;\nbool BRandom::timeBasedSeed = false;\n", "meta": {"hexsha": "8874a6b70975cd62392bb336a6c8a9d18be469cd", "size": 1742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "random.cpp", "max_stars_repo_name": "peterbabarczi/mwldsim", "max_stars_repo_head_hexsha": "cc9698ce410248cf5b448151b4d5ef8f719807c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "random.cpp", "max_issues_repo_name": "peterbabarczi/mwldsim", "max_issues_repo_head_hexsha": "cc9698ce410248cf5b448151b4d5ef8f719807c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "random.cpp", "max_forks_repo_name": "peterbabarczi/mwldsim", "max_forks_repo_head_hexsha": "cc9698ce410248cf5b448151b4d5ef8f719807c4", "max_forks_repo_licenses": ["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.0229885057, "max_line_length": 113, "alphanum_fraction": 0.6888633754, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5944886546959521}}
{"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": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix4d m = Vector4d(1,2,3,4).asDiagonal();\ncout << \"Here is the matrix m:\" << endl << m << endl;\ncout << \"Here is m.fixed<2, 2>(2, 2):\" << endl << m.block<2, 2>(2, 2) << endl;\nm.block<2, 2>(2, 0) = m.block<2, 2>(2, 2);\ncout << \"Now the matrix m is:\" << endl << m << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "913e8c6e96f491657a41b843786bd0e9cb10107e", "size": 425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_fixedBlock_int_int.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_fixedBlock_int_int.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_fixedBlock_int_int.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6111111111, "max_line_length": 78, "alphanum_fraction": 0.5858823529, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.5944886429795}}
{"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": "#include <boost/optional/optional_io.hpp>\n#include <catch.hpp>\n\n#include \"tests/netcode/launch.hh\"\n\n#include \"netcode/detail/invert_matrix.hh\"\n#include \"netcode/detail/square_matrix.hh\"\n\n/*------------------------------------------------------------------------------------------------*/\n\nusing namespace ntc;\n\n/*------------------------------------------------------------------------------------------------*/\n\nnamespace /* unnamed */{\n\n// Use jerasure implementation as a reference. Slighty modified to use our galois_field.\nint\njerasure_invert_matrix( detail::square_matrix& mat, detail::square_matrix& inv\n                      , detail::galois_field& gf)\n{\n  // Types are changed from int to unsigned int to avoid warnings.\n  unsigned int i, j, k, x, rs2;\n  unsigned int row_start, tmp, inverse;\n  unsigned int cols = static_cast<unsigned int>(mat.dimension());\n  unsigned int rows = cols;\n\n  k = 0;\n  for (i = 0; i < rows; i++) {\n    for (j = 0; j < cols; j++) {\n      inv[k] = (i == j) ? 1 : 0;\n      k++;\n    }\n  }\n\n  /* First -- convert into upper triangular  */\n  for (i = 0u; i < cols; i++) {\n    row_start = cols * i;\n\n    /* Swap rows if we ave a zero i,i element.  If we can't swap, then the\n     matrix was not invertible  */\n\n    if (mat[row_start+i] == 0) {\n      for (j = i+1; j < rows && mat[cols*j+i] == 0; j++) ;\n      if (j == rows) return -1;\n      rs2 = j*cols;\n      for (k = 0; k < cols; k++) {\n        tmp = mat[row_start+k];\n        mat[row_start+k] = mat[rs2+k];\n        mat[rs2+k] = tmp;\n        tmp = inv[row_start+k];\n        inv[row_start+k] = inv[rs2+k];\n        inv[rs2+k] = tmp;\n      }\n    }\n\n    /* Multiply the row by 1/element i,i  */\n    tmp = mat[row_start+i];\n    if (tmp != 1) {\n//      inverse = galois_single_divide(1, tmp, w);\n      inverse = gf.invert(tmp);\n      for (j = 0; j < cols; j++) {\n//        mat[row_start+j] = galois_single_multiply(mat[row_start+j], inverse, w);\n        mat[row_start+j] = gf.multiply(mat[row_start+j], inverse);\n//        inv[row_start+j] = galois_single_multiply(inv[row_start+j], inverse, w);\n        inv[row_start+j] = gf.multiply(inv[row_start+j], inverse);\n      }\n    }\n\n    /* Now for each j>i, add A_ji*Ai to Aj  */\n    k = row_start+i;\n    for (j = i+1; j != cols; j++) {\n      k += cols;\n      if (mat[k] != 0) {\n        if (mat[k] == 1) {\n          rs2 = cols*j;\n          for (x = 0; x < cols; x++) {\n            mat[rs2+x] ^= mat[row_start+x];\n            inv[rs2+x] ^= inv[row_start+x];\n          }\n        } else {\n          tmp = mat[k];\n          rs2 = cols*j;\n          for (x = 0; x < cols; x++) {\n//            mat[rs2+x] ^= galois_single_multiply(tmp, mat[row_start+x], w);\n            mat[rs2+x] ^= gf.multiply(tmp, mat[row_start+x]);\n//            inv[rs2+x] ^= galois_single_multiply(tmp, inv[row_start+x], w);\n            inv[rs2+x] ^= gf.multiply(tmp, inv[row_start+x]);\n          }\n        }\n      }\n    }\n  }\n\n  /* Now the matrix is upper triangular.  Start at the top and multiply down  */\n\n//  for (i = rows-1; i >= 0; i--) {\n  for (i = rows-1; ; i--) {\n    row_start = i*cols;\n    for (j = 0; j < i; j++) {\n      rs2 = j*cols;\n      if (mat[rs2+i] != 0) {\n        tmp = mat[rs2+i];\n        mat[rs2+i] = 0;\n        for (k = 0; k < cols; k++) {\n//          inv[rs2+k] ^= galois_single_multiply(tmp, inv[row_start+k], w);\n          inv[rs2+k] ^= gf.multiply(tmp, inv[row_start+k]);\n        }\n      }\n    }\n    if (i == 0) // Added test .\n    {\n      break;\n    }\n  }\n  return 0;\n}\n\n} // namespace unnamed\n\n/*------------------------------------------------------------------------------------------------*/\n\nTEST_CASE(\"Compare with jerasure matrix inversion\")\n{\n  launch([](std::uint8_t gf_size)\n  {\n    detail::galois_field gf{gf_size};\n\n    detail::square_matrix m0{3};\n    std::uint32_t k = 0u;\n    for (auto i = 0ul; i < 3; ++i)\n    {\n      for (auto j = 0ul; j < 3; ++j, ++k)\n      {\n        m0(i, j) = k;\n      }\n    }\n    auto m1 = m0;\n\n    detail::square_matrix inv0{3};\n    detail::square_matrix inv1{3};\n\n    // Matrix is invertible.\n    REQUIRE(jerasure_invert_matrix(m0, inv0, gf) == 0);\n    REQUIRE(not detail::invert(gf, m1, inv1));\n\n    // The result is the same as jerasure's.\n    for (auto i = 0ul; i < 3 * 3; ++i)\n    {\n      REQUIRE(inv0[i] == inv1[i]);\n    }\n  });\n}\n\n/*------------------------------------------------------------------------------------------------*/\n\nTEST_CASE(\"Non-invertible matrix\")\n{\n  /// @todo Find non invertible matrix for other GF sizes.\n  detail::galois_field gf{8};\n\n  detail::square_matrix m0{3};\n  std::uint32_t k = 0u;\n  for (auto i = 0u; i < 3; ++i)\n  {\n    for (auto j = 0u; j < 3; ++j, ++k)\n    {\n      m0[k] = (k+i) * 2;\n    }\n  }\n  auto m1 = m0;\n\n  detail::square_matrix inv0{3};\n  detail::square_matrix inv1{3};\n\n  REQUIRE(jerasure_invert_matrix(m0, inv0, gf) == -1);\n  REQUIRE(detail::invert(gf, m1, inv1));\n}\n\n/*------------------------------------------------------------------------------------------------*/\n\nTEST_CASE(\"Matrix is correctly inverted\")\n{\n  launch([&](std::uint8_t gf_size)\n  {\n    detail::galois_field gf{gf_size};\n\n    detail::square_matrix m{3};\n    std::uint32_t k = 0u;\n    for (auto i = 0ul; i < 3; ++i)\n    {\n      for (auto j = 0ul; j < 3; ++j, ++k)\n      {\n        m(i, j) = k;\n      }\n    }\n\n    // Inverted matrix is destroyed, we need a copy.\n    auto copy = m;\n\n    detail::square_matrix inv{3};\n\n    // Matrix is invertible.\n    REQUIRE(not detail::invert(gf, copy, inv));\n\n    // Multiply m and inv\n    detail::square_matrix identity{3};\n    for (auto i = 0ul; i < identity.dimension(); ++i)\n    {\n      for (auto j = 0ul; j < identity.dimension(); ++j, ++k)\n      {\n        identity(i, j) = [&]\n        {\n          std::uint32_t tmp = 0;\n          for (k = 0ul; k < identity.dimension(); ++k)\n          {\n            tmp ^= gf.multiply(m(i, k), inv(k, j));\n          }\n          return tmp;\n        }();\n      }\n    }\n\n    // Check that M * M^-1 = Id\n    for (auto i = 0ul; i < identity.dimension(); ++i)\n    {\n      for (auto j = 0ul; j < identity.dimension(); ++j)\n      {\n        REQUIRE(identity(i,j) == (i == j ? 1 : 0));\n      }\n    }\n  });\n}\n\n/*------------------------------------------------------------------------------------------------*/\n", "meta": {"hexsha": "45434cb5fc5d9977ce5f523c87c16145d9e0f103", "size": 6253, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/netcode/detail/test_invert_matrix.cc", "max_stars_repo_name": "ahamez/netcode", "max_stars_repo_head_hexsha": "aee7eeca8081831574dfb82edf3450ee03be36a1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-10-11T12:12:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T09:54:05.000Z", "max_issues_repo_path": "tests/netcode/detail/test_invert_matrix.cc", "max_issues_repo_name": "ahamez/netcode", "max_issues_repo_head_hexsha": "aee7eeca8081831574dfb82edf3450ee03be36a1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-13T17:31:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T17:32:16.000Z", "max_forks_repo_path": "tests/netcode/detail/test_invert_matrix.cc", "max_forks_repo_name": "ahamez/netcode", "max_forks_repo_head_hexsha": "aee7eeca8081831574dfb82edf3450ee03be36a1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-25T21:26:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-20T21:31:38.000Z", "avg_line_length": 26.4957627119, "max_line_length": 100, "alphanum_fraction": 0.4660163122, "num_tokens": 1831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5943676365456947}}
{"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": "/* test_binomial_distribution.cpp\n *\n * Copyright Steven Watanabe 2010\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * $Id$\n *\n */\n\n#include <boost/random/binomial_distribution.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::binomial_distribution<>\n#define BOOST_RANDOM_ARG1 t\n#define BOOST_RANDOM_ARG2 p\n#define BOOST_RANDOM_ARG1_DEFAULT 1\n#define BOOST_RANDOM_ARG2_DEFAULT 0.5\n#define BOOST_RANDOM_ARG1_VALUE 10\n#define BOOST_RANDOM_ARG2_VALUE 0.25\n\n#define BOOST_RANDOM_DIST0_MIN 0\n#define BOOST_RANDOM_DIST0_MAX 1\n#define BOOST_RANDOM_DIST1_MIN 0\n#define BOOST_RANDOM_DIST1_MAX 10\n#define BOOST_RANDOM_DIST2_MIN 0\n#define BOOST_RANDOM_DIST2_MAX 10\n\n#define BOOST_RANDOM_TEST1_PARAMS\n#define BOOST_RANDOM_TEST1_MIN 0\n#define BOOST_RANDOM_TEST1_MAX 1\n\n#define BOOST_RANDOM_TEST2_PARAMS (10, 0.25)\n#define BOOST_RANDOM_TEST2_MIN 0\n#define BOOST_RANDOM_TEST2_MAX 10\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "47e80d6920af691f25726771a3c632fbcbbb05c2", "size": 1021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_binomial_distribution.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/random/test/test_binomial_distribution.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/random/test/test_binomial_distribution.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 26.8684210526, "max_line_length": 72, "alphanum_fraction": 0.8266405485, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5943461023632549}}
{"text": "/**\n * @file feedforward_network_test.cpp\n * @author Marcus Edel\n * @author Palash Ahuja\n *\n * Tests the feed forward network.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/loss_functions/mean_squared_error.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n\n#include <ensmallen.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n#include \"serialization.hpp\"\n#include \"custom_layer.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(FeedForwardNetworkTest);\n\n/**\n * Train and evaluate a vanilla network with the specified structure.\n */\ntemplate<typename MatType = arma::mat>\nvoid BuildVanillaNetwork(MatType& trainData,\n                         MatType& trainLabels,\n                         MatType& testData,\n                         MatType& testLabels,\n                         const size_t outputSize,\n                         const size_t hiddenLayerSize,\n                         const size_t maxEpochs,\n                         const double classificationErrorThreshold)\n{\n  /*\n   * Construct a feed forward network with trainData.n_rows input nodes,\n   * hiddenLayerSize hidden nodes and trainLabels.n_rows output nodes. The\n   * network structure looks like:\n   *\n   *  Input         Hidden        Output\n   *  Layer         Layer         Layer\n   * +-----+       +-----+       +-----+\n   * |     |       |     |       |     |\n   * |     +------>|     +------>|     |\n   * |     |     +>|     |     +>|     |\n   * +-----+     | +--+--+     | +-----+\n   *             |             |\n   *  Bias       |  Bias       |\n   *  Layer      |  Layer      |\n   * +-----+     | +-----+     |\n   * |     |     | |     |     |\n   * |     +-----+ |     +-----+\n   * |     |       |     |\n   * +-----+       +-----+\n   */\n\n  FFN<NegativeLogLikelihood<> > model;\n  model.Add<Linear<> >(trainData.n_rows, hiddenLayerSize);\n  model.Add<SigmoidLayer<> >();\n  model.Add<Linear<> >(hiddenLayerSize, outputSize);\n  model.Add<LogSoftMax<> >();\n\n  // RMSProp opt(0.01, 32, 0.88, 1e-8, maxEpochs * trainData.n_cols, -1);\n  ens::RMSProp opt(0.01, 32, 0.88, 1e-8, maxEpochs * trainData.n_cols, -1);\n  model.Train(trainData, trainLabels, opt);\n\n  MatType predictionTemp;\n  model.Predict(testData, predictionTemp);\n  MatType prediction = arma::zeros<MatType>(1, predictionTemp.n_cols);\n\n  for (size_t i = 0; i < predictionTemp.n_cols; ++i)\n  {\n    prediction(i) = arma::as_scalar(arma::find(\n        arma::max(predictionTemp.col(i)) == predictionTemp.col(i), 1)) + 1;\n  }\n\n  size_t error = 0;\n  for (size_t i = 0; i < testData.n_cols; i++)\n  {\n    if (int(arma::as_scalar(prediction.col(i))) ==\n        int(arma::as_scalar(testLabels.col(i))))\n    {\n      error++;\n    }\n  }\n\n  double classificationError = 1 - double(error) / testData.n_cols;\n  BOOST_REQUIRE_LE(classificationError, classificationErrorThreshold);\n}\n\n/**\n * Train the vanilla network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(VanillaNetworkTest)\n{\n  // Load the dataset.\n  arma::mat trainData;\n  data::Load(\"thyroid_train.csv\", trainData, true);\n\n  arma::mat trainLabels = trainData.row(trainData.n_rows - 1);\n  trainData.shed_row(trainData.n_rows - 1);\n\n  arma::mat testData;\n  data::Load(\"thyroid_test.csv\", testData, true);\n\n  arma::mat testLabels = testData.row(testData.n_rows - 1);\n  testData.shed_row(testData.n_rows - 1);\n\n  // Vanilla neural net with logistic activation function.\n  // Because 92 percent of the patients are not hyperthyroid the neural\n  // network must be significant better than 92%.\n  BuildVanillaNetwork<>\n      (trainData, trainLabels, testData, testLabels, 3, 8, 10, 0.1);\n\n  arma::mat dataset;\n  dataset.load(\"mnist_first250_training_4s_and_9s.arm\");\n\n  // Normalize each point since these are images.\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    dataset.col(i) /= norm(dataset.col(i), 2);\n\n  arma::mat labels = arma::zeros(1, dataset.n_cols);\n  labels.submat(0, labels.n_cols / 2, 0, labels.n_cols - 1).fill(1);\n  labels += 1;\n\n  // Vanilla neural net with logistic activation function.\n  BuildVanillaNetwork<>\n      (dataset, labels, dataset, labels, 2, 10, 10, 0.2);\n}\n\nBOOST_AUTO_TEST_CASE(ForwardBackwardTest)\n{\n  arma::mat dataset;\n  dataset.load(\"mnist_first250_training_4s_and_9s.arm\");\n\n  // Normalize each point since these are images.\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    dataset.col(i) /= norm(dataset.col(i), 2);\n\n  arma::mat labels = arma::zeros(1, dataset.n_cols);\n  labels.submat(0, labels.n_cols / 2, 0, labels.n_cols - 1).fill(1);\n  labels += 1;\n\n  FFN<NegativeLogLikelihood<> > model;\n  model.Add<Linear<> >(dataset.n_rows, 50);\n  model.Add<SigmoidLayer<> >();\n  model.Add<Linear<> >(50, 10);\n  model.Add<LogSoftMax<> >();\n\n  ens::VanillaUpdate opt;\n  model.ResetParameters();\n  opt.Initialize(model.Parameters().n_rows, model.Parameters().n_cols);\n  double stepSize = 0.01;\n  size_t batchSize = 10;\n\n  size_t iteration = 0;\n  bool converged = false;\n  while (iteration < 100)\n  {\n    arma::running_stat<double> error;\n    size_t batchStart = 0;\n    while (batchStart < dataset.n_cols)\n    {\n      size_t batchEnd = std::min(batchStart + batchSize,\n          (size_t) dataset.n_cols);\n      arma::mat currentData = dataset.cols(batchStart, batchEnd - 1);\n      arma::mat currentLabels = labels.cols(batchStart, batchEnd - 1);\n      arma::mat currentResuls;\n      model.Forward(currentData, currentResuls);\n      arma::mat gradients;\n      model.Backward(currentLabels, gradients);\n      opt.Update(model.Parameters(), stepSize, gradients);\n      batchStart = batchEnd;\n\n      arma::mat prediction = arma::zeros<arma::mat>(1, currentResuls.n_cols);\n\n      for (size_t i = 0; i < currentResuls.n_cols; ++i)\n      {\n        prediction(i) = arma::as_scalar(arma::find(\n            arma::max(currentResuls.col(i)) == currentResuls.col(i), 1)) + 1;\n      }\n\n      size_t correct = 0;\n      for (size_t i = 0; i < currentLabels.n_cols; i++)\n      {\n        if (int(arma::as_scalar(prediction.col(i))) ==\n            int(arma::as_scalar(currentLabels.col(i))))\n        {\n          correct++;\n        }\n      }\n\n      error(1 - (double) correct / batchSize);\n    }\n    Log::Debug << \"Current training error: \" << error.mean() << std::endl;\n    iteration++;\n    if (error.mean() < 0.05)\n    {\n      converged = true;\n      break;\n    }\n  }\n\n  BOOST_REQUIRE(converged);\n}\n\n/**\n * Train and evaluate a Dropout network with the specified structure.\n */\ntemplate<typename MatType = arma::mat>\nvoid BuildDropoutNetwork(MatType& trainData,\n                         MatType& trainLabels,\n                         MatType& testData,\n                         MatType& testLabels,\n                         const size_t outputSize,\n                         const size_t hiddenLayerSize,\n                         const size_t maxEpochs,\n                         const double classificationErrorThreshold)\n{\n  /*\n   * Construct a feed forward network with trainData.n_rows input nodes,\n   * hiddenLayerSize hidden nodes and trainLabels.n_rows output nodes. The\n   * network structure looks like:\n   *\n   *  Input         Hidden        Dropout      Output\n   *  Layer         Layer         Layer        Layer\n   * +-----+       +-----+       +-----+       +-----+\n   * |     |       |     |       |     |       |     |\n   * |     +------>|     +------>|     +------>|     |\n   * |     |     +>|     |       |     |       |     |\n   * +-----+     | +--+--+       +-----+       +-----+\n   *             |\n   *  Bias       |\n   *  Layer      |\n   * +-----+     |\n   * |     |     |\n   * |     +-----+\n   * |     |\n   * +-----+\n   */\n\n  FFN<NegativeLogLikelihood<> > model;\n  model.Add<Linear<> >(trainData.n_rows, hiddenLayerSize);\n  model.Add<SigmoidLayer<> >();\n  model.Add<Dropout<> >();\n  model.Add<Linear<> >(hiddenLayerSize, outputSize);\n  model.Add<LogSoftMax<> >();\n\n  ens::RMSProp opt(0.01, 32, 0.88, 1e-8, maxEpochs * trainData.n_cols, -1);\n\n  model.Train(trainData, trainLabels, opt);\n\n  MatType predictionTemp;\n  model.Predict(testData, predictionTemp);\n  MatType prediction = arma::zeros<MatType>(1, predictionTemp.n_cols);\n\n  for (size_t i = 0; i < predictionTemp.n_cols; ++i)\n  {\n    prediction(i) = arma::as_scalar(arma::find(\n        arma::max(predictionTemp.col(i)) == predictionTemp.col(i), 1)) + 1;\n  }\n\n  size_t error = 0;\n  for (size_t i = 0; i < testData.n_cols; i++)\n  {\n    if (int(arma::as_scalar(prediction.col(i))) ==\n        int(arma::as_scalar(testLabels.col(i))))\n    {\n      error++;\n    }\n  }\n\n  double classificationError = 1 - double(error) / testData.n_cols;\n  BOOST_REQUIRE_LE(classificationError, classificationErrorThreshold);\n}\n\n/**\n * Train the dropout network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(DropoutNetworkTest)\n{\n  // Load the dataset.\n  arma::mat trainData;\n  data::Load(\"thyroid_train.csv\", trainData, true);\n\n  arma::mat trainLabels = trainData.row(trainData.n_rows - 1);\n  trainData.shed_row(trainData.n_rows - 1);\n\n  arma::mat testData;\n  data::Load(\"thyroid_test.csv\", testData, true);\n\n  arma::mat testLabels = testData.row(testData.n_rows - 1);\n  testData.shed_row(testData.n_rows - 1);\n\n  // Vanilla neural net with logistic activation function.\n  // Because 92 percent of the patients are not hyperthyroid the neural\n  // network must be significant better than 92%.\n  BuildDropoutNetwork<>\n      (trainData, trainLabels, testData, testLabels, 3, 8, 10, 0.1);\n\n  arma::mat dataset;\n  dataset.load(\"mnist_first250_training_4s_and_9s.arm\");\n\n  // Normalize each point since these are images.\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    dataset.col(i) /= norm(dataset.col(i), 2);\n\n  arma::mat labels = arma::zeros(1, dataset.n_cols);\n  labels.submat(0, labels.n_cols / 2, 0, labels.n_cols - 1).fill(1);\n  labels += 1;\n\n  // Vanilla neural net with logistic activation function.\n  BuildDropoutNetwork<>\n      (dataset, labels, dataset, labels, 2, 10, 10, 0.2);\n}\n\n/**\n * Train and evaluate a DropConnect network(with a baselayer) with the\n * specified structure.\n */\ntemplate<typename MatType = arma::mat>\nvoid BuildDropConnectNetwork(MatType& trainData,\n                             MatType& trainLabels,\n                             MatType& testData,\n                             MatType& testLabels,\n                             const size_t outputSize,\n                             const size_t hiddenLayerSize,\n                             const size_t maxEpochs,\n                             const double classificationErrorThreshold)\n{\n /*\n  *  Construct a feed forward network with trainData.n_rows input nodes,\n  *  hiddenLayerSize hidden nodes and trainLabels.n_rows output nodes. The\n  *  network struct that looks like:\n  *\n  *  Input         Hidden     DropConnect     Output\n  *  Layer         Layer         Layer        Layer\n  * +-----+       +-----+       +-----+       +-----+\n  * |     |       |     |       |     |       |     |\n  * |     +------>|     +------>|     +------>|     |\n  * |     |     +>|     |       |     |       |     |\n  * +-----+     | +--+--+       +-----+       +-----+\n  *             |\n  *  Bias       |\n  *  Layer      |\n  * +-----+     |\n  * |     |     |\n  * |     +-----+\n  * |     |\n  * +-----+\n  *\n  *\n  */\n\n  FFN<NegativeLogLikelihood<> > model;\n  model.Add<Linear<> >(trainData.n_rows, hiddenLayerSize);\n  model.Add<SigmoidLayer<> >();\n  model.Add<DropConnect<> >(hiddenLayerSize, outputSize);\n  model.Add<LogSoftMax<> >();\n\n  ens::RMSProp opt(0.01, 32, 0.88, 1e-8, maxEpochs * trainData.n_cols, -1);\n\n  model.Train(trainData, trainLabels, opt);\n\n  MatType predictionTemp;\n  model.Predict(testData, predictionTemp);\n  MatType prediction = arma::zeros<MatType>(1, predictionTemp.n_cols);\n\n  for (size_t i = 0; i < predictionTemp.n_cols; ++i)\n  {\n    prediction(i) = arma::as_scalar(arma::find(\n        arma::max(predictionTemp.col(i)) == predictionTemp.col(i), 1)) + 1;\n  }\n\n  size_t error = 0;\n  for (size_t i = 0; i < testData.n_cols; i++)\n  {\n    if (int(arma::as_scalar(prediction.col(i))) ==\n        int(arma::as_scalar(testLabels.col(i))))\n    {\n      error++;\n    }\n  }\n\n  double classificationError = 1 - double(error) / testData.n_cols;\n  BOOST_REQUIRE_LE(classificationError, classificationErrorThreshold);\n}\n\n/**\n * Train the dropconnect network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(DropConnectNetworkTest)\n{\n  // Load the dataset.\n  arma::mat trainData;\n  data::Load(\"thyroid_train.csv\", trainData, true);\n\n  arma::mat trainLabels = trainData.row(trainData.n_rows - 1);\n  trainData.shed_row(trainData.n_rows - 1);\n\n  arma::mat testData;\n  data::Load(\"thyroid_test.csv\", testData, true);\n\n  arma::mat testLabels = testData.row(testData.n_rows - 1);\n  testData.shed_row(testData.n_rows - 1);\n\n  // Vanilla neural net with logistic activation function.\n  // Because 92 percent of the patients are not hyperthyroid the neural\n  // network must be significant better than 92%.\n  BuildDropConnectNetwork<>\n      (trainData, trainLabels, testData, testLabels, 3, 8, 10, 0.1);\n\n  arma::mat dataset;\n  dataset.load(\"mnist_first250_training_4s_and_9s.arm\");\n\n  // Normalize each point since these are images.\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    dataset.col(i) /= norm(dataset.col(i), 2);\n\n  arma::mat labels = arma::zeros(1, dataset.n_cols);\n  labels.submat(0, labels.n_cols / 2, 0, labels.n_cols - 1).fill(1);\n  labels += 1;\n\n  // Vanilla neural net with logistic activation function.\n  BuildDropConnectNetwork<>\n      (dataset, labels, dataset, labels, 2, 10, 10, 0.2);\n}\n\n/**\n * Test miscellaneous things of FFN,\n * e.g. copy/move constructor, assignment operator.\n */\nBOOST_AUTO_TEST_CASE(FFNMiscTest)\n{\n  FFN<MeanSquaredError<>> model;\n  model.Add<Linear<>>(2, 3);\n  model.Add<ReLULayer<>>();\n\n  auto copiedModel(model);\n  copiedModel = model;\n  auto movedModel(std::move(model));\n  movedModel = std::move(copiedModel);\n}\n\n/**\n * Test that serialization works ok.\n */\nBOOST_AUTO_TEST_CASE(SerializationTest)\n{\n  // Load the dataset.\n  arma::mat trainData;\n  data::Load(\"thyroid_train.csv\", trainData, true);\n\n  arma::mat trainLabels = trainData.row(trainData.n_rows - 1);\n  trainData.shed_row(trainData.n_rows - 1);\n\n  arma::mat testData;\n  data::Load(\"thyroid_test.csv\", testData, true);\n\n  arma::mat testLabels = testData.row(testData.n_rows - 1);\n  testData.shed_row(testData.n_rows - 1);\n\n  // Vanilla neural net with logistic activation function.\n  // Because 92 percent of the patients are not hyperthyroid the neural\n  // network must be significant better than 92%.\n  FFN<NegativeLogLikelihood<> > model;\n  model.Add<Linear<> >(trainData.n_rows, 8);\n  model.Add<SigmoidLayer<> >();\n  model.Add<Dropout<> >();\n  model.Add<Linear<> >(8, 3);\n  model.Add<LogSoftMax<> >();\n\n  ens::RMSProp opt(0.01, 32, 0.88, 1e-8, trainData.n_cols /* 1 epoch */, -1);\n\n  model.Train(trainData, trainLabels, opt);\n\n  FFN<NegativeLogLikelihood<>> xmlModel, textModel, binaryModel;\n  xmlModel.Add<Linear<>>(10, 10); // Layer that will get removed.\n\n  // Serialize into other models.\n  SerializeObjectAll(model, xmlModel, textModel, binaryModel);\n\n  arma::mat predictions, xmlPredictions, textPredictions, binaryPredictions;\n  model.Predict(testData, predictions);\n  xmlModel.Predict(testData, xmlPredictions);\n  textModel.Predict(testData, textPredictions);\n  textModel.Predict(testData, binaryPredictions);\n\n  CheckMatrices(predictions, xmlPredictions, textPredictions,\n      binaryPredictions);\n}\n\n/**\n * Test if the custom layers work. The target is to see if the code compiles\n * when the Train and Prediction are called.\n */\nBOOST_AUTO_TEST_CASE(CustomLayerTest)\n{\n  // Load the dataset.\n  arma::mat trainData;\n  data::Load(\"thyroid_train.csv\", trainData, true);\n\n  arma::mat trainLabels = trainData.row(trainData.n_rows - 1);\n  trainData.shed_row(trainData.n_rows - 1);\n\n  arma::mat testData;\n  data::Load(\"thyroid_test.csv\", testData, true);\n\n  arma::mat testLabels = testData.row(testData.n_rows - 1);\n  testData.shed_row(testData.n_rows - 1);\n\n  FFN<NegativeLogLikelihood<>, RandomInitialization, CustomLayer<> > model;\n  model.Add<Linear<> >(trainData.n_rows, 8);\n  model.Add<CustomLayer<> >();\n  model.Add<Linear<> >(8, 3);\n  model.Add<LogSoftMax<> >();\n\n  ens::RMSProp opt(0.01, 32, 0.88, 1e-8, 15, -1);\n  model.Train(trainData, trainLabels, opt);\n\n  arma::mat predictionTemp;\n  model.Predict(testData, predictionTemp);\n  arma::mat prediction = arma::zeros<arma::mat>(1, predictionTemp.n_cols);\n}\n\n/**\n * Test the overload of Forward function which allows partial forward pass.\n */\nBOOST_AUTO_TEST_CASE(PartialForwardTest)\n{\n  FFN<NegativeLogLikelihood<>, RandomInitialization> model;\n  model.Add<Linear<> >(5, 10);\n\n  // Add a new Add<> module which adds a constant term to the input.\n  Add<>* addModule = new Add<>(10);\n  model.Add(addModule);\n\n  LinearNoBias<>* linearNoBiasModule = new LinearNoBias<>(10, 10);\n  model.Add(linearNoBiasModule);\n\n  model.Add<Linear<> >(10, 10);\n\n  model.ResetParameters();\n  // Set the parameters of the Add<> module to a matrix of ones.\n  addModule->Parameters() = arma::ones(10, 1);\n  // Set the parameters of the LinearNoBias<> module to a matrix of ones.\n  linearNoBiasModule->Parameters() = arma::ones(10, 10);\n\n  arma::mat input = arma::ones(10, 1);\n  arma::mat output;\n\n  // Forward pass only through the Add module.\n  model.Forward(input,\n                output,\n                1 /* Index of the Add module */,\n                1 /* Index of the Add module */);\n\n  // As we only forward pass through Add module, input and output should\n  // differ by a matrix of ones.\n  CheckMatrices(input, output - 1);\n\n  // Forward pass only through the Add module and the LinearNoBias module.\n  model.Forward(input,\n                output,\n                1 /* Index of the Add module */,\n                2 /* Index of the LinearNoBias module */);\n\n  // As we only forward pass through Add module followed by the LinearNoBias\n  // module, output should be a matrix of 20s.(output = weight * input)\n  CheckMatrices(output, arma::ones(10, 1) * 20);\n}\n\n/**\n * Test that FFN::Train() returns finite objective value.\n */\nBOOST_AUTO_TEST_CASE(FFNTrainReturnObjective)\n{\n  // Load the dataset.\n  arma::mat trainData;\n  data::Load(\"thyroid_train.csv\", trainData, true);\n\n  arma::mat trainLabels = trainData.row(trainData.n_rows - 1);\n  trainData.shed_row(trainData.n_rows - 1);\n\n  arma::mat testData;\n  data::Load(\"thyroid_test.csv\", testData, true);\n\n  arma::mat testLabels = testData.row(testData.n_rows - 1);\n  testData.shed_row(testData.n_rows - 1);\n\n  // Vanilla neural net with logistic activation function.\n  // Because 92 percent of the patients are not hyperthyroid the neural\n  // network must be significantly better than 92%.\n  FFN<NegativeLogLikelihood<> > model;\n  model.Add<Linear<> >(trainData.n_rows, 8);\n  model.Add<SigmoidLayer<> >();\n  model.Add<Dropout<> >();\n  model.Add<Linear<> >(8, 3);\n  model.Add<LogSoftMax<> >();\n\n  ens::RMSProp opt(0.01, 32, 0.88, 1e-8, trainData.n_cols /* 1 epoch */, -1);\n\n  double objVal = model.Train(trainData, trainLabels, opt);\n\n  BOOST_REQUIRE_EQUAL(std::isfinite(objVal), true);\n}\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "1055ff3c0849d9961d8220759b21f8083d367ff2", "size": 19422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/feedforward_network_test.cpp", "max_stars_repo_name": "yashMustak/mlpack", "max_stars_repo_head_hexsha": "354938177a718b58685d2d1f5eda3591d61ad3bc", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-12T20:10:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-12T20:10:39.000Z", "max_issues_repo_path": "src/mlpack/tests/feedforward_network_test.cpp", "max_issues_repo_name": "yashMustak/mlpack", "max_issues_repo_head_hexsha": "354938177a718b58685d2d1f5eda3591d61ad3bc", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/feedforward_network_test.cpp", "max_forks_repo_name": "yashMustak/mlpack", "max_forks_repo_head_hexsha": "354938177a718b58685d2d1f5eda3591d61ad3bc", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4781199352, "max_line_length": 78, "alphanum_fraction": 0.624343528, "num_tokens": 5292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5943460916969205}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n\n#include \"camera.hpp\"\n\nusing std::cout;\nusing std::endl;\nusing std::max;\nusing std::min;\nusing std::ifstream;\nusing std::ofstream;\n\nusing namespace Eigen;\nusing namespace SnowSimulator;\n\nvoid Camera::configure(double nearClip, double farClip, double hFov,\n                       double vFov, size_t screenW, size_t screenH) {\n  this->screenW = screenW;\n  this->screenH = screenH;\n\n  this->nearClip = nearClip;\n  this->farClip = farClip;\n\n  this->hFov = hFov;\n  this->vFov = vFov;\n\n  double ar1 = tan(radians(hFov) / 2) / tan(radians(vFov) / 2);\n  ar = static_cast<double>(screenW) / screenH;\n\n  if (ar1 < ar) {\n    // hFov is too small\n    hFov = 2 * degrees(atan(tan(radians(vFov) / 2) * ar));\n  } else if (ar1 > ar) {\n    // vFov is too small\n    vFov = 2 * degrees(atan(tan(radians(hFov) / 2) / ar));\n  }\n\n  screenDist = ((double)screenH) / (2.0 * tan(radians(vFov) / 2));\n}\n\nvoid Camera::place(const Vector3d &targetPos, const double phi,\n                   const double theta, const double r, const double minR,\n                   const double maxR) {\n  double r_ = min(max(r, minR), maxR);\n  double phi_ = (sin(phi) == 0) ? (phi + EPS_F) : phi;\n\n  this->targetPos = targetPos;\n  this->phi = phi_;\n  this->theta = theta;\n  this->r = r_;\n  this->minR = minR;\n  this->maxR = maxR;\n\n  compute_position();\n}\n\nvoid Camera::copy_placement(const Camera &other) {\n  pos = other.pos;\n  targetPos = other.targetPos;\n  phi = other.phi;\n  theta = other.theta;\n  minR = other.minR;\n  maxR = other.maxR;\n  c2w = other.c2w;\n}\n\nvoid Camera::set_screen_size(const size_t screenW, const size_t screenH) {\n  this->screenW = screenW;\n  this->screenH = screenH;\n\n  ar = 1.0 * screenW / screenH;\n  hFov = 2 * degrees(atan(((double)screenW) / (2 * screenDist)));\n  vFov = 2 * degrees(atan(((double)screenH) / (2 * screenDist)));\n}\n\nvoid Camera::move_by(const double dx, const double dy, const double d) {\n  const double scaleFactor = d / screenDist;\n  const Vector3d &displacement =\n      c2w.col(0) * (dx * scaleFactor) + c2w.col(1) * (dy * scaleFactor);\n\n  pos += displacement;\n  targetPos += displacement;\n}\n\nvoid Camera::move_forward(const double dist) {\n  double newR = min(max(r - dist, minR), maxR);\n  pos = targetPos + ((pos - targetPos) * (newR / r));\n  r = newR;\n}\n\nvoid Camera::rotate_by(const double dPhi, const double dTheta) {\n  phi = clamp(phi + dPhi, 0.0, (double)PI);\n  theta += dTheta;\n  compute_position();\n}\n\nvoid Camera::compute_position() {\n  double sinPhi = sin(phi);\n  if (sinPhi == 0) {\n    phi += EPS_F;\n    sinPhi = sin(phi);\n  }\n  const Vector3d dirToCamera(r * sinPhi * sin(theta), r * cos(phi),\n                             r * sinPhi * cos(theta));\n  pos = targetPos + dirToCamera;\n\n  Vector3d upVec(0, sinPhi > 0 ? 1 : -1, 0);\n  Vector3d screenXDir = upVec.cross(dirToCamera);\n\n  screenXDir.normalize();\n  Vector3d screenYDir = dirToCamera.cross(screenXDir);\n  screenYDir.normalize();\n\n  c2w.col(0) = screenXDir;\n  c2w.col(1) = screenYDir;\n\n  // camera's view direction is the opposite of of dirToCamera, so directly\n  // using dirToCamera as column 2 of the matrix takes [0 0 -1] to the world\n  // space view direction\n  c2w.col(2) = dirToCamera.normalized();\n}\n\n// void Camera::dump_settings(string filename) {\n//   ofstream file(filename);\n//   file << hFov << \" \" << vFov << \" \" << ar << \" \" << nearClip << \" \" <<\n//   farClip\n//        << endl;\n//   for (int i = 0; i < 3; ++i)\n//     file << pos[i] << \" \";\n//   for (int i = 0; i < 3; ++i)\n//     file << targetPos[i] << \" \";\n//   file << endl;\n//   file << phi << \" \" << theta << \" \" << r << \" \" << minR << \" \" << maxR <<\n//   endl; for (int i = 0; i < 9; ++i)\n//     file << c2w(i / 3, i % 3) << \" \";\n//   file << endl;\n//   file << screenW << \" \" << screenH << \" \" << screenDist << endl;\n//   cout << \"[Camera] Dumped settings to \" << filename << endl;\n// }\n//\n// void Camera::load_settings(string filename) {\n//   ifstream file(filename);\n//\n//   file >> hFov >> vFov >> ar >> nearClip >> farClip;\n//   for (int i = 0; i < 3; ++i)\n//     file >> pos[i];\n//   for (int i = 0; i < 3; ++i)\n//     file >> targetPos[i];\n//   file >> phi >> theta >> r >> minR >> maxR;\n//   for (int i = 0; i < 9; ++i)\n//     file >> c2w(i / 3, i % 3);\n//   file >> screenW >> screenH >> screenDist;\n//   cout << \"[Camera] Loaded settings from \" << filename << endl;\n// }\n", "meta": {"hexsha": "5dd062c5540d3222b4d7f5f0d7c9b40cc6cb5e9a", "size": 4432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/camera.cpp", "max_stars_repo_name": "kvchen/snowsim", "max_stars_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/camera.cpp", "max_issues_repo_name": "kvchen/snowsim", "max_issues_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-14T16:38:11.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-14T16:38:11.000Z", "max_forks_repo_path": "src/camera.cpp", "max_forks_repo_name": "kvchen/snowsim", "max_forks_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_forks_repo_licenses": ["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.0506329114, "max_line_length": 77, "alphanum_fraction": 0.589801444, "num_tokens": 1431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5943163137122823}}
{"text": "#include \"ros_package_template/Algorithm.hpp\"\n\n// gtest\n#include <gtest/gtest.h>\n\n// STD\n#include <vector>\n\n#include <Eigen/Core>\n\nusing namespace ros_package_template;\n\nTEST(Algorithm, getWithoutSet\n) {\nAlgorithm algorithm;\nconst double average = algorithm.getAverage();\nEXPECT_EQ(0.0, average);\n}\n\nTEST(Algorithm, singleDataPoint\n) {\nconst double inputData = 100.0 * (double) rand() / RAND_MAX;\nAlgorithm algorithm;\nalgorithm.\naddData(inputData);\nconst double average = algorithm.getAverage();\nEXPECT_NEAR(inputData, average,\n1e-10);\n}\n\nTEST(Algorithm, singleDataVector\n) {\nconst double inputValue = 100.0 * (double) rand() / RAND_MAX;\nAlgorithm algorithm;\nEigen::VectorXd inputData;\ninputData.resize(2);\ninputData << inputValue, 3 *\ninputValue;\nalgorithm.\naddData(inputData);\nconst double average = algorithm.getAverage();\nEXPECT_NEAR(2 * inputValue, average, 1e-10);\n}\n\nTEST(Algorithm, multipleDataPoints\n) {\nsize_t nMeasurements = 100;\nstd::vector<double> inputData(nMeasurements);\ndouble sum = 0.0;\nfor (\nauto &data\n: inputData) {\ndata = 100.0 * (double) rand() / RAND_MAX;\nsum +=\ndata;\n}\n\nAlgorithm algorithm;\nfor (\nconst auto data\n: inputData) {\nalgorithm.\naddData(data);\n}\nconst double average = algorithm.getAverage();\nEXPECT_NEAR(sum\n/ nMeasurements, average, 1e-10);\n}\n", "meta": {"hexsha": "f9011d6088e8a9021a5ab0ab6279b38937a89a4d", "size": 1281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/AlgorithmTest.cpp", "max_stars_repo_name": "BlackRu1/hero_chassis_controller", "max_stars_repo_head_hexsha": "b51ab5fac4645331456c6b74f34cf67e6e55cfc3", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/AlgorithmTest.cpp", "max_issues_repo_name": "BlackRu1/hero_chassis_controller", "max_issues_repo_head_hexsha": "b51ab5fac4645331456c6b74f34cf67e6e55cfc3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/AlgorithmTest.cpp", "max_forks_repo_name": "BlackRu1/hero_chassis_controller", "max_forks_repo_head_hexsha": "b51ab5fac4645331456c6b74f34cf67e6e55cfc3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-05T03:20:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T08:39:52.000Z", "avg_line_length": 18.5652173913, "max_line_length": 61, "alphanum_fraction": 0.743950039, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5943163103461842}}
{"text": "/**\n * @file convolution_test.cpp\n * @author Marcus Edel\n *\n * Tests for various convolution strategies.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/pooling_rules/max_pooling.hpp>\n#include <mlpack/methods/ann/pooling_rules/mean_pooling.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(PoolingTest);\n\n/**\n * Test the max pooling rule.\n */\nBOOST_AUTO_TEST_CASE(MaxPoolingTest)\n{\n  // The data was generated by magic(6) in MATLAB.\n  arma::mat input, output;\n  input << 35 << 1 << 6 << 26 << 19 << 24 << arma::endr\n        << 3 << 32 << 7 << 21 << 23 << 25 << arma::endr\n        << 31 << 9 << 2 << 22 << 27 << 20 << arma::endr\n        << 8 << 28 << 33 << 17 << 10 << 15 << arma::endr\n        << 30 << 5 << 34 << 12 << 14 << 16 << arma::endr\n        << 4 << 36 << 29 << 13 << 18 << 11;\n\n  // Expected output of the generated 6 x 6 matrix.\n  const double poolingOutput = 36;\n\n  MaxPooling poolingRule;\n\n  // Test the pooling function.\n  BOOST_REQUIRE_EQUAL(poolingRule.Pooling(input), poolingOutput);\n\n  // Test the unpooling function.\n  poolingRule.Unpooling(input, input.max(), output);\n  BOOST_REQUIRE_EQUAL(arma::accu(output), input.max());\n}\n\n/**\n * Test the mean pooling rule.\n */\nBOOST_AUTO_TEST_CASE(MeanPoolingTest)\n{\n  // The data was generated by magic(6) in MATLAB.\n  arma::mat input, output;\n  input << 35 << 1 << 6 << 26 << 19 << 24 << arma::endr\n        << 3 << 32 << 7 << 21 << 23 << 25 << arma::endr\n        << 31 << 9 << 2 << 22 << 27 << 20 << arma::endr\n        << 8 << 28 << 33 << 17 << 10 << 15 << arma::endr\n        << 30 << 5 << 34 << 12 << 14 << 16 << arma::endr\n        << 4 << 36 << 29 << 13 << 18 << 11;\n\n  // Expected output of the generated 6 x 6 matrix.\n  const double poolingOutput = 18.5;\n\n  MeanPooling poolingRule;\n\n  // Test the pooling function.\n  BOOST_REQUIRE_EQUAL(poolingRule.Pooling(input), poolingOutput);\n\n  // Test the unpooling function.\n  poolingRule.Unpooling(input, input.max(), output);\n  bool b = arma::all(arma::vectorise(output) == (input.max() / input.n_elem));\n  BOOST_REQUIRE_EQUAL(b, true);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b85f3e85c98faf2f02bf358edba4250e6257d393", "size": 2202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/pooling_rules_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:20.000Z", "max_issues_repo_path": "src/mlpack/tests/pooling_rules_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/pooling_rules_test.cpp", "max_forks_repo_name": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9736842105, "max_line_length": 78, "alphanum_fraction": 0.6171662125, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5943162990929842}}
{"text": "#include \"derivative_damping.hpp\"\n#include \"laplacian.hpp\"\n\n#include <string>\n#include <armadillo>\n#include <yaml-cpp/yaml.h>\n\nDerivativeDamping::DerivativeDamping(const std::string &filenm):\n  Regularization(filenm)\n{\n  YAML::Node config = YAML::LoadFile(filenm);\n  output_file_ = config[\"file_deriv\"].as<std::string>();\n\n  this->load();\n  laplacian_ = laplacian2d(umodel_-rmodel_, ni1_, ni2_, nk1_, nk2_);\n}\n\n\nvoid DerivativeDamping::save()\n{\n  Regularization::save(output_file_);\n}\n\n\nvoid DerivativeDamping::cal_fitness()\n{\n  fitness_ = arma::accu(arma::square(laplacian_));\n}\n\n\nvoid DerivativeDamping::cal_gradient()\n{\n  gradient_ = 2 * laplacian2d(laplacian_, ni1_, ni2_, nk1_, nk2_);\n\n}\n", "meta": {"hexsha": "1c599f9d5c1dd90b7a51cfe8d195a7dc3cddd069", "size": 693, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/derivative_damping.cc", "max_stars_repo_name": "panlei7/regularization", "max_stars_repo_head_hexsha": "a417e844bfcc841e35f8075918837cc99a276bfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/derivative_damping.cc", "max_issues_repo_name": "panlei7/regularization", "max_issues_repo_head_hexsha": "a417e844bfcc841e35f8075918837cc99a276bfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/derivative_damping.cc", "max_forks_repo_name": "panlei7/regularization", "max_forks_repo_head_hexsha": "a417e844bfcc841e35f8075918837cc99a276bfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.25, "max_line_length": 68, "alphanum_fraction": 0.7243867244, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5942999995726801}}
{"text": "#include <iostream>\n#include <cmath>\n#include <string>\n\n#include \"timer.h\"\n#include \"matrix.h\"\n\n#if defined(AMATRIX_COMPARE_WITH_EIGEN)\n#include \"Eigen/Dense\"\n#endif\n\n#if defined(AMATRIX_COMPARE_WITH_UBLAS)\n#include <boost/numeric/ublas/matrix.hpp>\n#endif\n\n#define AMATRIX_MEASURE_ABC_OPERATION(name, operation)                   \\\n    void name() {                                                        \\\n        TMatrixType A(TSize1, TSize2);                                   \\\n        TMatrixType B(TSize1, TSize2);                                   \\\n        initialize(A);                                                   \\\n        initialize(B);                                                   \\\n        Timer timer;                                                     \\\n        for (std::size_t i_repeat = 0; i_repeat < mRepeat; i_repeat++) { \\\n            operation                                                    \\\n        }                                                                \\\n        auto elapsed = timer.elapsed().count();                          \\\n        std::cout << \"\\t\\t\" << elapsed;                                  \\\n    }\n\n#define AMATRIX_MEASURE_ABCD_OPERATION(name, operation)                   \\\n    void name() {                                                         \\\n        TMatrixType A(TSize1, TSize2);                                    \\\n        TMatrixType B(TSize1, TSize2);                                    \\\n        initialize(A);                                                    \\\n        initializeInverse(B);                                             \\\n        initializeInverse(D);                                             \\\n        Timer timer;                                                      \\\n        for (std::size_t i_repeat = 0; i_repeat < mRepeat / (2 * TSize2); \\\n             i_repeat++) {                                                \\\n            operation                                                     \\\n        }                                                                 \\\n        auto elapsed = timer.elapsed().count();                           \\\n        std::cout << \"\\t\\t\" << elapsed;                                   \\\n    }\n\ntemplate <typename TMatrixType, std::size_t TSize1, std::size_t TSize2>\nclass ComparisonColumn {\n   protected:\n    static constexpr std::size_t mRepeat =\n        static_cast<std::size_t>(1e8 / (TSize1 * TSize2));\n\n    TMatrixType C;\n    TMatrixType D;\n    std::string mColumnName;\n\n    void initialize(TMatrixType& TheMatrix) {\n        for (std::size_t i = 0; i < TSize1; i++)\n            for (std::size_t j = 0; j < TSize2; j++)\n                TheMatrix(i, j) = j + 1.00;\n    }\n\n    void initializeInverse(TMatrixType& TheMatrix) {\n        for (std::size_t i = 0; i < TSize1; i++)\n            for (std::size_t j = 0; j < TSize2; j++)\n                TheMatrix(i, j) = 1.00 / (i + 1);\n    }\n\n   public:\n    ComparisonColumn() = delete;\n\n    ComparisonColumn(std::string ColumnName) \n        : C(TSize1, TSize2),\n          D(TSize1, TSize2), mColumnName(ColumnName) {\n        initialize(C);\n    }\n    std::string const& GetColumnName() { return mColumnName; }\n    TMatrixType& GetResult() { return C; }\n\n    template <typename TMatrixType2>\n    bool CheckResult(TMatrixType2 const& Reference) {\n        constexpr double tolerance = 1e-12;\n        for (std::size_t i = 0; i < TSize1; i++)\n            for (std::size_t j = 0; j < TSize2; j++)\n                if (std::abs(C(i, j) - Reference(i, j)) > tolerance) {\n                    std::cout << \" \" << C(i, j) << \" != \" << Reference(i, j);\n                    return false;\n                }\n\n        return true;\n    }\n\n    AMATRIX_MEASURE_ABC_OPERATION(MeasureSumTime,C.noalias() = A + B; B.noalias() = C;)\n\n    AMATRIX_MEASURE_ABCD_OPERATION(MeasureMultTime,C.noalias() = D * A; D.noalias() = B;)\n\n    AMATRIX_MEASURE_ABCD_OPERATION(MeasureABAMultTime, C.noalias() = A * TMatrixType(D * A); D.noalias() = B;)\n\n    AMATRIX_MEASURE_ABCD_OPERATION(MeasureATransposeBAMultTime,C.noalias() = A.transpose() * TMatrixType(D * A); D.noalias() = B;)\n\n};\n\n\n#if defined(AMATRIX_COMPARE_WITH_UBLAS)\nusing namespace boost::numeric::ublas;\ntemplate <typename TMatrixType, std::size_t TSize1,\n    std::size_t TSize2>\n\nclass UblasComparisonColumn\n    : public ComparisonColumn<TMatrixType, TSize1, TSize2> {\n    void initialize(TMatrixType& TheMatrix) {\n        for (std::size_t i = 0; i < TSize1; i++)\n            for (std::size_t j = 0; j < TSize2; j++)\n                TheMatrix(i, j) = j + 1.00;\n    }\n\n    void initializeInverse(TMatrixType& TheMatrix) {\n        for (std::size_t i = 0; i < TSize1; i++)\n            for (std::size_t j = 0; j < TSize2; j++)\n                TheMatrix(i, j) = 1.00 / (i + 1);\n    }\n   public:\n    using BaseType =\n        ComparisonColumn<TMatrixType, TSize1, TSize2>;\n\n    using BaseType::mRepeat;\n\n    using BaseType::C;\n    using BaseType::D;\n\n\n    UblasComparisonColumn(std::string ColumnName)\n        : ComparisonColumn<TMatrixType, TSize1, TSize2>(\n              ColumnName) {}\n\n\n    AMATRIX_MEASURE_ABC_OPERATION(MeasureSumTime, noalias(BaseType::C) =  A + B; noalias(B) = BaseType::C;)\n    AMATRIX_MEASURE_ABCD_OPERATION(MeasureMultTime,noalias(BaseType::C) = prod(BaseType::D, A); noalias(BaseType::D) = B;)\n    AMATRIX_MEASURE_ABCD_OPERATION(MeasureABAMultTime, noalias(BaseType::C) = prod(A, TMatrixType(prod(BaseType::D, A))); noalias(BaseType::D) = B;)\n    AMATRIX_MEASURE_ABCD_OPERATION(MeasureATransposeBAMultTime, noalias(BaseType::C) = prod(trans(A), TMatrixType(prod(BaseType::D, A)));noalias(BaseType::D) = B;)\n\n};\n#endif\n\ntemplate <typename TMatrixType, std::size_t TSize1,\n    std::size_t TSize2>\nclass EmptyComparisonColumn\n    : public ComparisonColumn<TMatrixType, TSize1, TSize2> {\n   public:\n    EmptyComparisonColumn(std::string ColumnName)\n        : ComparisonColumn<TMatrixType, TSize1, TSize2>(\"\") {}\n    void MeasureSumTime() { std::cout << \"\\t\\t\"; }\n    void MeasureMultTime() { std::cout << \"\\t\\t\"; }\n    void MeasureABAMultTime() { std::cout << \"\\t\\t\"; }\n    void MeasureATransposeBAMultTime() { std::cout << \"\\t\\t\"; }\n\n    template <typename TMatrixType2>\n    bool CheckResult(TMatrixType2 const& Reference) {\n        return true;\n    }\n};\n\n#define RUN_BENCHMARK(name, function)                          \\\n    std::cout << name;                                         \\\n    mAMatrixColumn.function();                                 \\\n    mEigenColumn.function();                                   \\\n    if (!mEigenColumn.CheckResult(mAMatrixColumn.GetResult())) \\\n        std::cout << \"(Failed!)\";                              \\\n    mUblasColumn.function();                                   \\\n    if (!mUblasColumn.CheckResult(mAMatrixColumn.GetResult())) \\\n        std::cout << \"(Failed!)\";                              \\\n    std::cout << std::endl;\n\ntemplate <std::size_t TSize1, std::size_t TSize2>\nclass BenchmarkMatrix {\n    ComparisonColumn<AMatrix::Matrix<double, TSize1, TSize2>,\n        TSize1, TSize2>\n        mAMatrixColumn;\n#if defined(AMATRIX_COMPARE_WITH_EIGEN)\n    ComparisonColumn<Eigen::Matrix<double, TSize1, TSize2>,\n        TSize1, TSize2>\n        mEigenColumn;\n#else\n    EmptyComparisonColumn<\n        AMatrix::Matrix<double, TSize1, TSize2>, TSize1,\n        TSize2>\n        mEigenColumn;\n#endif\n#if defined(AMATRIX_COMPARE_WITH_UBLAS)\n    UblasComparisonColumn<boost::numeric::ublas::bounded_matrix<double,\n                              TSize1, TSize2>,\n        TSize1, TSize2>\n        mUblasColumn;\n#else\n    EmptyComparisonColumn<\n        AMatrix::Matrix<double, TSize1, TSize2>, TSize1,\n        TSize2>\n        mUblasColumn;\n#endif\n   public:\n    BenchmarkMatrix()\n        : mAMatrixColumn(\"AMatrix\"),\n          mEigenColumn(\"Eigen\"),\n          mUblasColumn(\"Ublas\") {\n        std::cout << \"Benchmark[\" << TSize1 << \",\" << TSize2\n                  << \"]\";\n        std::cout << \"\\t\\t\" << mAMatrixColumn.GetColumnName();\n        std::cout << \"\\t\\t\" << mEigenColumn.GetColumnName();\n        std::cout << \"\\t\\t\" << mUblasColumn.GetColumnName();\n        std::cout << std::endl;\n    }\n\n    ~BenchmarkMatrix() = default;\n    void Run() {\n        RUN_BENCHMARK(\"C = A + B\", MeasureSumTime)\n        RUN_BENCHMARK(\"C = A * B\", MeasureMultTime)\n        RUN_BENCHMARK(\"C = A * B * A\", MeasureABAMultTime)\n        RUN_BENCHMARK(\"C = A^T * B * A\", MeasureATransposeBAMultTime)\n\n        std::cout << std::endl;\n    }\n};\n\ntemplate <std::size_t TSize1, std::size_t TSize2>\nclass BenchmarkDynamicMatrix {\n    ComparisonColumn<AMatrix::Matrix<double, 0, 0>, TSize1,\n        TSize2>\n        mAMatrixColumn;\n#if defined(AMATRIX_COMPARE_WITH_EIGEN)\n    ComparisonColumn<\n        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>, TSize1,\n        TSize2>\n        mEigenColumn;\n#else\n    EmptyComparisonColumn<\n        AMatrix::Matrix<double, TSize1, TSize2>, TSize1,\n        TSize2>\n        mEigenColumn;\n#endif\n#if defined(AMATRIX_COMPARE_WITH_UBLAS)\n    UblasComparisonColumn<boost::numeric::ublas::matrix<double>,\n        TSize1, TSize2>\n        mUblasColumn;\n#else\n    EmptyComparisonColumn<\n        AMatrix::Matrix<double, TSize1, TSize2>, TSize1,\n        TSize2>\n        mUblasColumn;\n#endif\n   public:\n    BenchmarkDynamicMatrix()\n        : mAMatrixColumn(\"AMatrix\"),\n          mEigenColumn(\"Eigen\"),\n          mUblasColumn(\"Ublas\") {\n        std::cout << \"Benchmark[\" << TSize1 << \",\" << TSize2\n                  << \"]\";\n        std::cout << \"\\t\\t\" << mAMatrixColumn.GetColumnName();\n        std::cout << \"\\t\\t\" << mEigenColumn.GetColumnName();\n        std::cout << \"\\t\\t\" << mUblasColumn.GetColumnName();\n        std::cout << std::endl;\n    }\n\n    ~BenchmarkDynamicMatrix() = default;\n    void Run() {\n        RUN_BENCHMARK(\"C = A + B\", MeasureSumTime)\n        RUN_BENCHMARK(\"C = A * B\", MeasureMultTime)\n        RUN_BENCHMARK(\"C = A * B * A\", MeasureABAMultTime)\n        RUN_BENCHMARK(\"C = A^T * B * A\", MeasureATransposeBAMultTime)\n\n        std::cout << std::endl;\n    }\n};\n\nint main() {\n    BenchmarkMatrix<3, 3> benchmark_3_3;\n    benchmark_3_3.Run();\n\n    BenchmarkMatrix<4, 4> benchmark_4_4;\n    benchmark_4_4.Run();\n\n    BenchmarkMatrix<6, 6> benchmark_6_6;\n    benchmark_6_6.Run();\n\n    BenchmarkMatrix<12, 12> benchmark_12_12;\n    benchmark_12_12.Run();\n\n    BenchmarkMatrix<16, 16> benchmark_16_16;\n    benchmark_16_16.Run();\n\n    BenchmarkDynamicMatrix<3, 3> dynamic_bechmark_3_3;\n    dynamic_bechmark_3_3.Run();\n\n    BenchmarkDynamicMatrix<4, 4> dynamic_benchmark_4_4;\n    dynamic_benchmark_4_4.Run();\n\n    BenchmarkDynamicMatrix<6, 6> dynamic_benchmark_6_6;\n    dynamic_benchmark_6_6.Run();\n\n    BenchmarkDynamicMatrix<12, 12> dynamic_benchmark_12_12;\n    dynamic_benchmark_12_12.Run();\n\n    BenchmarkDynamicMatrix<16, 16> dynamic_benchmark_16_16;\n    dynamic_benchmark_16_16.Run();\n\n    return 0;\n}\n", "meta": {"hexsha": "91d4af80269c94c9c4d83c7ecaea10152cff2ab5", "size": 10874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/benchmark_matrix.cpp", "max_stars_repo_name": "oberbichler/AMatrix", "max_stars_repo_head_hexsha": "e4db9ea0ee7269601389fac24542f91d79eb4679", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2017-10-31T17:22:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T21:16:41.000Z", "max_issues_repo_path": "benchmarks/benchmark_matrix.cpp", "max_issues_repo_name": "oberbichler/AMatrix", "max_issues_repo_head_hexsha": "e4db9ea0ee7269601389fac24542f91d79eb4679", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-10-28T07:27:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-24T16:38:15.000Z", "max_forks_repo_path": "benchmarks/benchmark_matrix.cpp", "max_forks_repo_name": "oberbichler/AMatrix", "max_forks_repo_head_hexsha": "e4db9ea0ee7269601389fac24542f91d79eb4679", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-04-22T18:12:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-16T10:39:41.000Z", "avg_line_length": 35.5359477124, "max_line_length": 163, "alphanum_fraction": 0.5463490896, "num_tokens": 2789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5942876894791538}}
{"text": "#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Arr_segment_traits_2.h>\n#include <CGAL/Arr_polyline_traits_2.h>\n#include <CGAL/Arrangement_2.h>\n\n#include <boost/iterator/function_output_iterator.hpp>\n\n#include <array>\n#include <cassert>\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;\ntypedef CGAL::Arr_segment_traits_2<Kernel>                Segment_traits_2;\ntypedef CGAL::Arr_polyline_traits_2<Segment_traits_2>     Geom_traits_2;\n\ntypedef Geom_traits_2::Point_2                            Point_2;\ntypedef Geom_traits_2::Segment_2                          Segment_2;\ntypedef Geom_traits_2::Curve_2                            Polyline_2;\ntypedef CGAL::Arrangement_2<Geom_traits_2>                Arrangement_2;\ntypedef Geom_traits_2::X_monotone_curve_2                 X_monotone_polyline;\ntypedef Geom_traits_2::X_monotone_subcurve_2              X_monotone_subcurve;\n\nstruct Test_functor\n{\n  const X_monotone_polyline* reference;\n\n  Test_functor (const X_monotone_polyline& reference)\n    : reference (&reference) { }\n\n  void operator() (const CGAL::Object& obj) const\n  {\n     const X_monotone_polyline* poly\n      = CGAL::object_cast<X_monotone_polyline>(&obj);\n     assert(poly != nullptr); //  Intersection is not a polyline\n\n    typename X_monotone_polyline::Point_const_iterator\n      itref = reference->points_begin(),\n      itpoly = poly->points_begin();\n\n    for (; itref != reference->points_end()\n           && itpoly != poly->points_end();\n         ++ itref, ++ itpoly)\n      assert(*itref == *itpoly);\n  }\n};\n\nvoid test (const X_monotone_polyline& a, const X_monotone_polyline& b,\n           const X_monotone_polyline& reference)\n{\n  Geom_traits_2 traits;\n  Geom_traits_2::Intersect_2 intersect_2 =\n    traits.intersect_2_object();\n\n  std::cerr << \" * Polyline A = \" << a << std::endl\n            << \" * Polyline B = \" << b << std::endl;\n\n  intersect_2\n    (a, b, boost::make_function_output_iterator (Test_functor(reference)));\n}\n\nint main()\n{\n  Geom_traits_2 traits;\n  Arrangement_2 arr(&traits);\n\n  Geom_traits_2::Construct_x_monotone_curve_2 x_mono_polyline_construct =\n    traits.construct_x_monotone_curve_2_object();\n\n  std::array<Segment_2, 2> r2l\n    = { Segment_2(Point_2(1, 0), Point_2(0, 1)),\n        Segment_2(Point_2(0, 1), Point_2(-1, 0)) };\n\n  std::array<Segment_2, 2> l2r\n    = { Segment_2(Point_2(-1, 0), Point_2(0, 1)),\n        Segment_2(Point_2(0, 1), Point_2(1, 0)), };\n\n  X_monotone_polyline p0l2r\n    = x_mono_polyline_construct (l2r.begin(), l2r.end());\n  X_monotone_polyline p1l2r\n    = x_mono_polyline_construct (l2r.begin(), l2r.end());\n  X_monotone_polyline p0r2l\n    = x_mono_polyline_construct (r2l.begin(), r2l.end());\n  X_monotone_polyline p1r2l\n    = x_mono_polyline_construct (r2l.begin(), r2l.end());\n\n  std::cerr << \"Testing intersection left-to-right / left-to-right\" << std::endl;\n  test (p0l2r, p1l2r, p0l2r);\n  std::cerr << \"Testing intersection left-to-right / right-to-left\" << std::endl;\n  test (p0l2r, p1r2l, p0l2r);\n  std::cerr << \"Testing intersection right-to-left / left-to-right\" << std::endl;\n  test (p0r2l, p1l2r, p0l2r);\n  std::cerr << \"Testing intersection right-to-left / right-to-left\" << std::endl;\n  test (p0r2l, p1r2l, p0r2l);\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "2c0a68510c79628b0489c69efbe510cf85e287d0", "size": 3277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Arrangement_on_surface_2/test/Arrangement_on_surface_2/test_polycurve_intersection.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": "Arrangement_on_surface_2/test/Arrangement_on_surface_2/test_polycurve_intersection.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Arrangement_on_surface_2/test/Arrangement_on_surface_2/test_polycurve_intersection.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1354166667, "max_line_length": 81, "alphanum_fraction": 0.6847726579, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5942876840942252}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/mldivide.hpp\n *\n * \\brief Matrix left division.\n *\n * Inspired by the \\c mldivide MATLAB function.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2012, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_MLDIVIDE_HPP\n#define BOOST_NUMERIC_UBLASX_MLDIVIDE_HPP\n\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublasx/operation/lu.hpp>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\ntemplate<typename AMatrixT,\n         typename BVectorT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<AMatrixT>::size_type mldivide_inplace(matrix_expression<AMatrixT> const& A,\n                                                             vector_container<BVectorT>& b)\n{\n    return lu_solve_inplace(A, b);\n}\n\ntemplate<typename AMatrixT,\n         typename BVectorT,\n         typename XVectorT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<AMatrixT>::size_type mldivide(matrix_expression<AMatrixT> const& A,\n                                                     vector_expression<BVectorT> const& b,\n                                                     vector_container<XVectorT>& x)\n{\n    return lu_solve(A, b, x());\n}\n\ntemplate<typename AMatrixT,\n         typename BMatrixT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<AMatrixT>::size_type mldivide_inplace(matrix_expression<AMatrixT> const& A,\n                                                             matrix_container<BMatrixT>& B)\n{\n    return lu_solve_inplace(A, B);\n}\n\ntemplate<typename AMatrixT,\n         typename BMatrixT,\n         typename XMatrixT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<AMatrixT>::size_type mldivide(matrix_expression<AMatrixT> const& A,\n                                                     matrix_expression<BMatrixT> const& B,\n                                                     matrix_container<XMatrixT>& X)\n{\n    return lu_solve(A, B, X());\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n#endif // BOOST_NUMERIC_UBLASX_MLDIVIDE_HPP\n", "meta": {"hexsha": "82337af60da656a30d146ad82c077277d2a8e6e4", "size": 2353, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/mldivide.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/mldivide.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/mldivide.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": 30.1666666667, "max_line_length": 98, "alphanum_fraction": 0.6472588185, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5942876840942252}}
{"text": "#ifndef ASLAM_SCALAR_EXPRESSION_HPP\n#define ASLAM_SCALAR_EXPRESSION_HPP\n\n#include <Eigen/Core>\n#include <boost/shared_ptr.hpp>\n#include <aslam/backend/JacobianContainer.hpp>\n#include <aslam/backend/Differential.hpp>\n#include <set>\n\nnamespace aslam {\n  namespace backend {\n\n    using std::sqrt;\n    using std::log;\n    using std::exp;\n\n    class ExpressionNodeVisitor;\n    class ScalarExpressionNode;\n    \n    class ScalarExpression\n    {\n    public:\n      enum { Dimension = 1 };\n      typedef double Value;\n      typedef double value_t;\n      typedef ScalarExpressionNode node_t;\n\n      explicit ScalarExpression(double value);\n      ScalarExpression(const char * name, double value);\n      ScalarExpression(ScalarExpressionNode * designVariable);\n      ScalarExpression(boost::shared_ptr<ScalarExpressionNode> designVariable);\n      ~ScalarExpression();\n      \n      double toScalar() const;\n      double toValue() const { return toScalar(); }\n      double evaluate() const { return toScalar(); }\n\n      void evaluateJacobians(JacobianContainer & outJacobians) const;\n      void evaluateJacobians(JacobianContainer & outJacobians, const Eigen::MatrixXd & applyChainRule) const;\n      void getDesignVariables(DesignVariable::set_t & designVariables) const;\n\n      boost::shared_ptr<ScalarExpressionNode> root() const { return _root; }\n      bool isEmpty() const { return false; }  //TODO feature: support empty scalar expression\n\n      ScalarExpression operator+(const ScalarExpression & s) const;\n      ScalarExpression operator-(const ScalarExpression & s) const;\n      ScalarExpression operator*(const ScalarExpression & s) const;\n      ScalarExpression operator/(const ScalarExpression & s) const;\n      ScalarExpression operator+(double s) const;\n      ScalarExpression operator-(double s) const;\n      ScalarExpression operator-() const;\n      ScalarExpression operator*(double s) const;\n      ScalarExpression operator/(double s) const;\n      bool operator < (const ScalarExpression & s) const { return this->toValue() < s.toValue(); }\n      bool operator > (const ScalarExpression & s) const { return this->toValue() > s.toValue(); }\n      bool operator <= (const ScalarExpression & s) const { return this->toValue() <= s.toValue(); }\n      bool operator >= (const ScalarExpression & s) const { return this->toValue() >= s.toValue(); }\n      bool operator == (const ScalarExpression & s) const { return this->toValue() == s.toValue(); }\n      bool operator != (const ScalarExpression & s) const { return this->toValue() != s.toValue(); }\n      bool operator < (const double s) const { return this->toValue() < s; }\n      bool operator > (const double s) const { return this->toValue() > s; }\n      bool operator <= (const double s) const { return this->toValue() <= s; }\n      bool operator >= (const double s) const { return this->toValue() >= s; }\n      bool operator == (const double s) const { return this->toValue() == s; }\n      bool operator != (const double s) const { return this->toValue() != s; }\n\n      void accept(ExpressionNodeVisitor& visitor) const;\n    private:\n      /// \\todo make the default constructor private.\n      ScalarExpression();\n\n      boost::shared_ptr<ScalarExpressionNode> _root;\n\n      friend class EuclideanExpression;\n\n    };\n    \n    std::ostream& operator<<(std::ostream& os, const ScalarExpression& e);\n\n    ScalarExpression sqrt(const ScalarExpression& e);\n    ScalarExpression log(const ScalarExpression& e);\n    ScalarExpression exp(const ScalarExpression& e);\n    ScalarExpression atan(const ScalarExpression& e);\n    ScalarExpression tanh(const ScalarExpression& e);\n    ScalarExpression atan2(const ScalarExpression& e0, const ScalarExpression& e1);\n    ScalarExpression sin(const ScalarExpression& e);\n    ScalarExpression cos(const ScalarExpression& e);\n    ScalarExpression acos(const ScalarExpression& e);\n    ScalarExpression acosSquared(const ScalarExpression& e);\n    ScalarExpression inverseSigmoid(const ScalarExpression& e, const double height, const double scale, const double shift);\n    ScalarExpression powerExpression(const ScalarExpression& e, const int k);\n    ScalarExpression piecewiseExpression(const ScalarExpression& e1, const ScalarExpression& e2, std::function<bool()> useFirst);\n    inline ScalarExpression operator / (const double num, const ScalarExpression& den) {\n      return ScalarExpression(num) / den;\n    }\n\n  } // namespace backend\n} // namespace aslam\n\n\n#endif /* ASLAM_SCALAR_EXPRESSION_HPP */\n", "meta": {"hexsha": "c34282e9c37f9815e8e4e70d8a209e215a586b55", "size": 4485, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "aslam_backend_expressions/include/aslam/backend/ScalarExpression.hpp", "max_stars_repo_name": "ethz-asl/aslam_optimizer", "max_stars_repo_head_hexsha": "8e9dd18f9f0d8af461e88e108a3beda2003daf11", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2017-04-26T13:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T01:52:22.000Z", "max_issues_repo_path": "aslam_backend_expressions/include/aslam/backend/ScalarExpression.hpp", "max_issues_repo_name": "ethz-asl/aslam_optimizer", "max_issues_repo_head_hexsha": "8e9dd18f9f0d8af461e88e108a3beda2003daf11", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:02:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-12T06:07:22.000Z", "max_forks_repo_path": "aslam_backend_expressions/include/aslam/backend/ScalarExpression.hpp", "max_forks_repo_name": "ethz-asl/aslam_optimizer", "max_forks_repo_head_hexsha": "8e9dd18f9f0d8af461e88e108a3beda2003daf11", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-06-28T04:17:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T04:58:36.000Z", "avg_line_length": 43.9705882353, "max_line_length": 129, "alphanum_fraction": 0.7070234114, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5942876787092964}}
{"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#define BOOST_TEST_MODULE test_recurrences\n\n#include <boost/config.hpp>\n\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/math/tools/recurrence.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n//#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/math/concepts/real_concept.hpp>\n\n#ifdef BOOST_MSVC\n#pragma warning(disable:4127)\n#endif\n\ntemplate <class T>\nstruct bessel_jy_recurrence\n{\n   bessel_jy_recurrence(T v, T z) : v(v), z(z) {}\n   boost::math::tuple<T, T, T> operator()(int k)const\n   {\n      return boost::math::tuple<T, T, T>(T(1), -2 * (v + k) / z, T(1));\n   }\n\n   T v, z;\n};\n\ntemplate <class T>\nstruct bessel_ik_recurrence\n{\n   bessel_ik_recurrence(T v, T z) : v(v), z(z) {}\n   boost::math::tuple<T, T, T> operator()(int k)const\n   {\n      return boost::math::tuple<T, T, T>(T(1), -2 * (v + k) / z, T(-1));\n   }\n\n   T v, z;\n};\n\n\ntemplate <class T>\nvoid test_spots(T, const char* name)\n{\n   std::cout << \"Running tests for type \" << name << std::endl;\n   T tol = boost::math::tools::epsilon<T>() * 5;\n   if ((std::numeric_limits<T>::digits > 53) || (std::numeric_limits<T>::digits == 0))\n      tol *= 5;\n   //\n   // Test forward recurrence on Y_v(x):\n   //\n   {\n      T v = 22.25;\n      T x = 4.125;\n      bessel_jy_recurrence<T> coef(v, x);\n      T prev;\n      T first = boost::math::cyl_neumann(v - 1, x);\n      T second = boost::math::cyl_neumann(v, x);\n      T sixth = boost::math::tools::apply_recurrence_relation_forward(coef, 6, first, second, (long long*)0, &prev);\n      T expected1 = boost::math::cyl_neumann(v + 6, x);\n      T expected2 = boost::math::cyl_neumann(v + 5, x);\n      BOOST_CHECK_CLOSE_FRACTION(sixth, expected1, tol);\n      BOOST_CHECK_CLOSE_FRACTION(prev, expected2, tol);\n\n      boost::math::tools::forward_recurrence_iterator< bessel_jy_recurrence<T> > it(coef, first, second);\n      for (unsigned i = 0; i < 15; ++i)\n      {\n         expected1 = boost::math::cyl_neumann(v + i, x);\n         T found = *it;\n         BOOST_CHECK_CLOSE_FRACTION(found, expected1, tol);\n         ++it;\n      }\n\n      if (std::numeric_limits<T>::max_exponent > 300)\n      {\n         //\n         // This calculates the ratio Y_v(x)/Y_v+1(x) from the recurrence relations\n         // which are only transiently stable since Y_v is not minimal as v->-INF\n         // but only as v->0.  We have to be sure that v is sufficiently large that\n         // convergence is complete before we reach the origin.\n         //\n         v = 102.75;\n         boost::uintmax_t max_iter = 200;\n         T ratio = boost::math::tools::function_ratio_from_forwards_recurrence(bessel_jy_recurrence<T>(v, x), boost::math::tools::epsilon<T>(), max_iter);\n         first = boost::math::cyl_neumann(v, x);\n         second = boost::math::cyl_neumann(v + 1, x);\n         BOOST_CHECK_CLOSE_FRACTION(ratio, first / second, tol);\n\n         boost::math::tools::forward_recurrence_iterator< bessel_jy_recurrence<T> > it2(bessel_jy_recurrence<T>(v, x), boost::math::cyl_neumann(v, x));\n         for (unsigned i = 0; i < 15; ++i)\n         {\n            expected1 = boost::math::cyl_neumann(v + i, x);\n            T found = *it2;\n            BOOST_CHECK_CLOSE_FRACTION(found, expected1, tol);\n            ++it2;\n         }\n      }\n\n   }\n   //\n   // Test backward recurrence on J_v(x):\n   //\n   {\n      if ((std::numeric_limits<T>::digits > 53) || !std::numeric_limits<T>::is_specialized)\n         tol *= 5;\n\n      T v = 22.25;\n      T x = 4.125;\n      bessel_jy_recurrence<T> coef(v, x);\n      T prev;\n      T first = boost::math::cyl_bessel_j(v + 1, x);\n      T second = boost::math::cyl_bessel_j(v, x);\n      T sixth = boost::math::tools::apply_recurrence_relation_backward(coef, 6, first, second, (long long*)0, &prev);\n      T expected1 = boost::math::cyl_bessel_j(v - 6, x);\n      T expected2 = boost::math::cyl_bessel_j(v - 5, x);\n      BOOST_CHECK_CLOSE_FRACTION(sixth, expected1, tol);\n      BOOST_CHECK_CLOSE_FRACTION(prev, expected2, tol);\n\n      boost::math::tools::backward_recurrence_iterator< bessel_jy_recurrence<T> > it(coef, first, second);\n      for (unsigned i = 0; i < 15; ++i)\n      {\n         expected1 = boost::math::cyl_bessel_j(v - i, x);\n         T found = *it;\n         BOOST_CHECK_CLOSE_FRACTION(found, expected1, tol);\n         ++it;\n      }\n\n      boost::uintmax_t max_iter = 200;\n      T ratio = boost::math::tools::function_ratio_from_backwards_recurrence(bessel_jy_recurrence<T>(v, x), boost::math::tools::epsilon<T>(), max_iter);\n      first = boost::math::cyl_bessel_j(v, x);\n      second = boost::math::cyl_bessel_j(v - 1, x);\n      BOOST_CHECK_CLOSE_FRACTION(ratio, first / second, tol);\n\n      boost::math::tools::backward_recurrence_iterator< bessel_jy_recurrence<T> > it2(bessel_jy_recurrence<T>(v, x), boost::math::cyl_bessel_j(v, x));\n      //boost::math::tools::backward_recurrence_iterator< bessel_jy_recurrence<T> > it3(bessel_jy_recurrence<T>(v, x), boost::math::cyl_neumann(v+1, x), boost::math::cyl_neumann(v, x));\n      for (unsigned i = 0; i < 15; ++i)\n      {\n         expected1 = boost::math::cyl_bessel_j(v - i, x);\n         T found = *it2;\n         BOOST_CHECK_CLOSE_FRACTION(found, expected1, tol);\n         ++it2;\n      }\n\n   }\n}\n\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n   BOOST_MATH_CONTROL_FP;\n#if !defined(TEST) || TEST == 1\n   test_spots(0.0F, \"float\");\n   test_spots(0.0, \"double\");\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_spots(0.0L, \"long double\");\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\n   test_spots(boost::math::concepts::real_concept(0.1), \"real_concept\");\n#endif\n#endif\n#endif\n#if !defined(TEST) || TEST == 2 || TEST == 3\n   test_spots(boost::multiprecision::cpp_bin_float_quad(), \"cpp_bin_float_quad\");\n#endif\n}\n\n#else\n\nint main() { return 0; }\n\n#endif\n", "meta": {"hexsha": "eb85b3b6c1d0894c5295a4f7c4910ea64724bdd9", "size": 6124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_recurrence.cpp", "max_stars_repo_name": "anarthal/boost-unix-mirror", "max_stars_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-15T13:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T13:07:07.000Z", "max_issues_repo_path": "libs/math/test/test_recurrence.cpp", "max_issues_repo_name": "anarthal/boost-unix-mirror", "max_issues_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/test/test_recurrence.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-06T08:30:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T08:30:20.000Z", "avg_line_length": 34.5988700565, "max_line_length": 185, "alphanum_fraction": 0.6319399086, "num_tokens": 1833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5942536307561106}}
{"text": "#define BZ_DISABLE_KCC_COPY_PROPAGATION_KLUDGE\n\n#include <blitz/tinyvec-et.h>\n\nusing namespace blitz;\n\ntypedef TinyVector<double,3> vec;\n\ninline void reflect(vec& reflection, const vec& incident, \n    const vec& surfaceNormal)\n{\n    // The surface normal must be unit length to use this equation.\n\n    reflection = incident - 2 * dot(incident,surfaceNormal) * surfaceNormal;\n}\n\ntemplate<typename T>\nvoid optimizationSink(T&);\n\nvoid foo(TinyVector<double,3>& x)\n{\n    TinyVector<double,3> y, z;\n\n    y =  1.00,  0.40, -1.00;\n    z =  0.31,  0.20,  0.93;\n\n    reflect(x, y, z);\n}\n\n", "meta": {"hexsha": "811bf8f759e45a83fbc3b33e4de63dbc07198ae1", "size": 579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/tiny2.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/tiny2.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/tiny2.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": 19.3, "max_line_length": 76, "alphanum_fraction": 0.6839378238, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5942536098388498}}
{"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": "#define BOOST_TEST_MODULE \"test_flexible_local_dihedral_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/forcefield/FLP/FlexibleLocalDihedralPotential.hpp>\n#include <mjolnir/math/constants.hpp>\n\nBOOST_AUTO_TEST_CASE(FlexibleLocalDihedral_double)\n{\n    using real_type = double;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-6;\n    constexpr real_type   pi = mjolnir::math::constants<real_type>::pi();\n\n    const real_type k  = 1.0;\n    const std::array<real_type, 7> term{{\n        2.2056, 0.2183, -0.0795, 0.0451, -0.3169, 0.0165, -0.1375\n    }};\n\n    mjolnir::FlexibleLocalDihedralPotential<real_type> flpd(k, term);\n\n    const real_type x_min = -pi;\n    const real_type x_max =  pi;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + dx * i;\n        const real_type pot1 = flpd.potential(x + h);\n        const real_type pot2 = flpd.potential(x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = flpd.derivative(x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(1e-5));\n        BOOST_TEST(flpd.potential (x) == flpd.potential (x + 2 * pi),\n                   boost::test_tools::tolerance(h));\n        BOOST_TEST(flpd.derivative(x) == flpd.derivative(x + 2 * pi),\n                   boost::test_tools::tolerance(h));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(FlexibleLocalDihedral_float)\n{\n    using real_type = float;\n    constexpr std::size_t N   = 100;\n    constexpr real_type   h   = 1e-3;\n    constexpr real_type   tol = 5e-2;\n    constexpr real_type   pi = mjolnir::math::constants<real_type>::pi();\n\n    const real_type k  = 1.0;\n    const std::array<real_type, 7> term{{\n        2.2056, 0.2183, -0.0795, 0.0451, -0.3169, 0.0165, -0.1375\n    }};\n\n    mjolnir::FlexibleLocalDihedralPotential<real_type> flpd(k, term);\n\n    const real_type x_min = -pi;\n    const real_type x_max =  pi;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + dx * i;\n        const real_type pot1 = flpd.potential(x + h);\n        const real_type pot2 = flpd.potential(x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = flpd.derivative(x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(tol));\n        BOOST_TEST(flpd.potential (x) == flpd.potential (x + 2 * pi),\n                   boost::test_tools::tolerance(tol));\n        BOOST_TEST(flpd.derivative(x) == flpd.derivative(x + 2 * pi),\n                   boost::test_tools::tolerance(tol));\n    }\n}\n", "meta": {"hexsha": "a70f9bc9bd03377f5ba7ee0dfe505436da14cf76", "size": 2719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_flp_dihedral_potential.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/core/test_flp_dihedral_potential.cpp", "max_issues_repo_name": "yutakasi634/Mjolnir", "max_issues_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T11:41:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T10:01:38.000Z", "max_forks_repo_path": "test/core/test_flp_dihedral_potential.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9875, "max_line_length": 73, "alphanum_fraction": 0.6248620816, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5942468332500913}}
{"text": "#include \"transform.h\"\n\n#include <Eigen/Dense>\n#include \"math/rotation.h\"\n#include \"utilities/error.h\"\n\nnamespace cpt {\n\nTransform::Transform() {\n    reset();\n}\n\nvoid Transform::reset() {\n    _scale.setOnes();\n    _rotation.setIdentity();\n    _translation.setZero();\n}\n\nvoid Transform::set_translation(const Eigen::Vector3f& trans) {\n    _translation = trans;\n}\n\nvoid Transform::set_rotation(const Eigen::Matrix3f& rot) {\n    // Check to make sure we have a valid rotation.\n    CHECK_AND_THROW_ERROR(std::abs(rot.determinant() - 1.f) < 1e-6, \"Invalid rotation matrix [Determinant:\" <<  rot.determinant() << \"].\");\n    _rotation = rot;\n}\n\nvoid Transform::set_scale(const Eigen::Vector3f& scale) {\n    _scale = scale;\n}\n\nEigen::Vector3f Transform::operator*(const Eigen::Vector3f& other) const {\n    return (_rotation * _scale.cwiseProduct(other));\n}\n\nEigen::Vector3f Transform::homogeneous_mult(const Eigen::Vector3f& other) const {\n    return (*this * other + _translation);\n}\n\nEigen::Vector3f Transform::rotate(const Eigen::Vector3f& other) const {\n    return (_rotation * other);\n}\n\nTransform& Transform::operator*=(const Transform& other) {\n    // Assume that we have\n    // T_1 R_1 S_1 for one transform and T_2 R_2 S_2 for the other transform.\n    // The new transform would thus have a translation of T_1 + R_1 S_1 T_2\n    // Its rotation/scale would be a combined R_1 S_1 R_2 S_2. We can extract\n    // the new scale by taking the magnitude of the colums and the rotation\n    // matrix are just the normalized columns.\n    _translation += (*this * other._translation);\n\n    Eigen::Matrix3f newRotScaleMat = _rotation * _scale.asDiagonal() * other._rotation * other._scale.asDiagonal();\n    decompose_scale_rotation(newRotScaleMat, _rotation, _scale);\n    return *this;\n}\n\nTransform Transform::operator*(const Transform& other) const {\n    Transform xform = *this;\n    xform *= other;\n    return xform;\n}\n\nTransform Transform::from_transform_matrix(const Eigen::Matrix4f& matrix) {\n    Transform xform;\n    xform.set_translation(matrix.block(0, 3, 3, 1));\n\n    Eigen::Matrix3f rot;\n    Eigen::Vector3f scale;\n    decompose_scale_rotation(matrix.block(0,0,3,3), rot, scale);    \n\n    xform.set_scale(scale);\n    xform.set_rotation(rot);\n    return xform;\n}\n\nTransform Transform::inverse() const {\n    Eigen::Matrix4f mat = to_matrix();\n    Eigen::Matrix4f new_mat = mat;\n    new_mat.block(0,0,3,3) = mat.block(0,0,3,3).inverse();\n    new_mat.block(0,3,3,1) = -new_mat.block(0,0,3,3) * mat.block(0,3,3, 1);\n    return Transform::from_transform_matrix(new_mat);\n}\n\nEigen::Matrix4f Transform::to_matrix() const {\n    Eigen::Matrix4f matrix;\n    matrix.setIdentity();\n    matrix.block(0,0,3,3) = _rotation * _scale.asDiagonal();\n    matrix.block(0,3,3,1) = _translation;\n    return matrix;\n}\n\n}\n", "meta": {"hexsha": "4be6b7525db32d3ad956cc0e487d98b436dd03ef", "size": 2796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/math/transform.cpp", "max_stars_repo_name": "b3h47pte/cuda-path-tracing", "max_stars_repo_head_hexsha": "b874b86f15b4aca18ecd40e9eb962996298f5fa8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/math/transform.cpp", "max_issues_repo_name": "b3h47pte/cuda-path-tracing", "max_issues_repo_head_hexsha": "b874b86f15b4aca18ecd40e9eb962996298f5fa8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/math/transform.cpp", "max_forks_repo_name": "b3h47pte/cuda-path-tracing", "max_forks_repo_head_hexsha": "b874b86f15b4aca18ecd40e9eb962996298f5fa8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4315789474, "max_line_length": 139, "alphanum_fraction": 0.6927753934, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5941479482986802}}
{"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": "#include \"matrix.hpp\"\n#include \"generator_options.hpp\"\n#include <ctime>\n#include <cstdlib>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\ntemplate<typename MatrixType>\nvoid populate(MatrixType& matrix, const std::size_t bandwidth, const double density, const bool symmetric)\n{\n  const double weight = 1e15;\n  assert(matrix.size1() == matrix.size2());\n\n  // Place random values with appropriate bandwidth\n  for(std::size_t row=0; row<matrix.size1(); ++row)\n  {\n    for(std::size_t col=std::max(static_cast<std::size_t>(0), row-bandwidth); col<std::min(matrix.size2(), row+bandwidth+1); ++col)\n    {\n      if (drand48 () < density)\n      {\n        const double value = drand48() * weight;\n        matrix(row, col) += value;\n\n        if (symmetric)\n          matrix(col, row) += value;\n      }\n    }\n  }\n\n  // Make diagonally dominant\n  for (typename MatrixType::iterator1 rowIter = matrix.begin1(); rowIter != matrix.end1(); ++rowIter) \n  {\n    const typename MatrixType::value_type weight = 1e1;  // arbitrary value to increase the sum by to make strictly dominant\n    typename MatrixType::value_type absSum;\n    for(typename MatrixType::iterator2 colIter(rowIter.begin()); colIter != rowIter.end(); ++colIter)\n    {\n      if (colIter.index1() != colIter.index2())\n        absSum += std::fabs(*colIter);\n    }\n    matrix(rowIter.index1(), rowIter.index1()) = absSum + weight;\n  }\n}\n\nint main(int argc, char* argv[])\n{\n  GeneratorOptions options;\n  options.processOptions(argc, argv);\n  srand48(time(NULL));\n\n  const unsigned size = options.getSize();\n  const bool symmetric = options.getSymmetric();\n\n  boost::numeric::ublas::mapped_matrix<double> matrix(size, size);\n\n  populate(matrix, size/4, 4.0/size, symmetric);\n  \n  CCSMatrix<double> csrMatrix(matrix, symmetric);\n  std::cout << \"Generating \" << (symmetric ? \"a symmetric\" : \"an unsymmetric\") << \" matrix of size \" << size << \".\" << std::endl;\n  std::cout << \"Number of non-zeros in generated matrix: \" << csrMatrix.nnz() << \".\" << std::endl;\n\n  csrMatrix.writeToFile(options.getOutputFile());\n}\n", "meta": {"hexsha": "01e0b223782d6fff68448457bc8b476bd5a95417", "size": 2149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matrix-generator/generator.cpp", "max_stars_repo_name": "FrancisRussell/desola", "max_stars_repo_head_hexsha": "a469428466e4849c7c0e2009a0c50b89184cae01", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T10:46:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T11:53:50.000Z", "max_issues_repo_path": "matrix-generator/generator.cpp", "max_issues_repo_name": "FrancisRussell/desola", "max_issues_repo_head_hexsha": "a469428466e4849c7c0e2009a0c50b89184cae01", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix-generator/generator.cpp", "max_forks_repo_name": "FrancisRussell/desola", "max_forks_repo_head_hexsha": "a469428466e4849c7c0e2009a0c50b89184cae01", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5606060606, "max_line_length": 131, "alphanum_fraction": 0.6682177757, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5941479374874361}}
{"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": "/**\n * @file symplectictimesteppingwaves_test.cc\n * @brief NPDE homework \"SymplecticTimesteppingWaves\" code\n * @author Am\u00e9lie Loher\n * @date 09.04.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include \"../symplectictimesteppingwaves.h\"\n#include \"../symplectictimesteppingwaves_assemble.h\"\n#include \"../symplectictimesteppingwaves_ode.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseLU>\n\n#include <utility>\n\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/uscalfe/uscalfe.h>\n\nnamespace SymplecticTimesteppingWaves::test {\n\nTEST(SymplecticTimesteppingWaves, sympTimesteppingHarmonicOscillatorODE) {\n  unsigned int m = 10;\n\n  Eigen::Vector2d sol = sympTimesteppingHarmonicOscillatorODE(m);\n\n  Eigen::Vector2d ref_sol;\n  ref_sol << 0.000675997, 1;\n\n  double tol = 1.0e-4;\n  ASSERT_NEAR((sol - ref_sol).lpNorm<Eigen::Infinity>(), 0.0, tol);\n}\n\nTEST(SymplecticTimesteppingWaves, assembleGalerkinMatrix) {\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  const lf::io::GmshReader reader(\n      std::move(mesh_factory), CURRENT_SOURCE_DIR \"/../../meshes/simple.msh\");\n  auto mesh_p = reader.mesh();\n\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto one = [](Eigen::Vector2d x) -> double { return 1.0; };\n\n  Eigen::SparseMatrix<double> galMat =\n      assembleGalerkinMatrix(fe_space, one, one, one);\n\n  Eigen::MatrixXd sol(galMat);\n\n  Eigen::MatrixXd ref_sol(5, 5);\n  ref_sol << 1.75, 0.1875, 0, 0.1875, -0.958333, 0.1875, 1.75, 0.1875, 0,\n      -0.958333, 0, 0.1875, 1.75, 0.1875, -0.958333, 0.1875, 0, 0.1875, 1.75,\n      -0.958333, -0.958333, -0.958333, -0.958333, -0.958333, 4.16667;\n\n  double tol = 1.0e-4;\n  ASSERT_NEAR((sol - ref_sol).lpNorm<Eigen::Infinity>(), 0.0, tol);\n}\n\nTEST(SymplecticTimesteppingWaves, computeEnergies) {\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  const lf::io::GmshReader reader(\n      std::move(mesh_factory), CURRENT_SOURCE_DIR \"/../../meshes/simple.msh\");\n  auto mesh_p = reader.mesh();\n\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto c = [](Eigen::Vector2d x) -> double { return 1.0 + x.dot(x); };\n\n  SympTimestepWaveEq stepper(fe_space, c);\n\n  Eigen::VectorXd p = Eigen::VectorXd::Ones(5);\n  Eigen::VectorXd q = 2 * Eigen::VectorXd::Ones(5);\n\n  double sol = stepper.computeEnergies(p, q);\n\n  double ref_sol = 3.83333;\n\n  double tol = 1.0e-4;\n  ASSERT_NEAR((sol - ref_sol), 0.0, tol);\n}\n\nTEST(SymplecticTimesteppingWaves, solvewave) {\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  const lf::io::GmshReader reader(\n      std::move(mesh_factory), CURRENT_SOURCE_DIR \"/../../meshes/simple.msh\");\n  auto mesh_p = reader.mesh();\n\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  auto c = [](Eigen::Vector2d x) -> double { return 1.0 + x.dot(x); };\n\n  Eigen::VectorXd u0 = Eigen::VectorXd::Ones(5);\n  Eigen::VectorXd v0 = 2 * Eigen::VectorXd::Ones(5);\n\n  double T = 1.0;\n  unsigned int m = 10;\n\n  std::pair<Eigen::VectorXd, Eigen::VectorXd> sol =\n      solvewave(fe_space, c, u0, v0, T, m);\n\n  Eigen::VectorXd ref_sol_first(5);\n  ref_sol_first << 2.01346, 1.76133, 1.53227, 1.76133, 1.77866;\n\n  Eigen::VectorXd ref_sol_second(11);\n  ref_sol_second << 2.83333, 2.83333, 2.83334, 2.83336, 2.83338, 2.8334,\n      2.83342, 2.83346, 2.8335, 2.83355, 2.83359;\n\n  double tol = 1.0e-4;\n  ASSERT_NEAR((sol.first - ref_sol_first).lpNorm<Eigen::Infinity>(), 0.0, tol);\n  ASSERT_NEAR((sol.second - ref_sol_second).lpNorm<Eigen::Infinity>(), 0.0,\n              tol);\n}\n\n} /* namespace SymplecticTimesteppingWaves::test */\n", "meta": {"hexsha": "b7f7d0cab4b7af7087b8281bb711b5c89fa5765b", "size": 3725, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/SymplecticTimesteppingWaves/templates/test/symplectictimesteppingwaves_test.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/SymplecticTimesteppingWaves/templates/test/symplectictimesteppingwaves_test.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/SymplecticTimesteppingWaves/templates/test/symplectictimesteppingwaves_test.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7851239669, "max_line_length": 79, "alphanum_fraction": 0.6845637584, "num_tokens": 1300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.5941055266772116}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <ridgelet/construction/ridgelet_functions.hpp>\n\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n  unsigned int N = 100;\n  Eigen::VectorXd vec(N);\n  Eigen::VectorXd ty(N);\n\n  vec.setLinSpaced(N, -2, 2);\n\n  TransitionFunction t;\n\n  std::transform(vec.data(), vec.data() + vec.size(), ty.data(), t);\n  cout << \"Transfer function:\"\n       << \"\\n\";\n  cout << \"x: \" << vec.array().transpose() << endl;\n  cout << \"y: \" << ty.array().transpose() << endl;\n\n  PsiSpherical1<> psi_spherical;\n\n  Eigen::VectorXd ws(N);\n  std::transform(vec.data(), vec.data() + vec.size(), ws.data(), psi_spherical);\n\n  cout << \"Spherical: \"\n       << \"\\n\";\n  cout << \"y\" << ws.array().transpose() << \"\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "e3130af7816d869f7dac2119c36b1226b7e3f94f", "size": 753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main_ridgelet_functions.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_ridgelet_functions.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_ridgelet_functions.cpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 22.1470588235, "max_line_length": 80, "alphanum_fraction": 0.6002656042, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5940962631220504}}
{"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": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nclass Network {\n  public:\n    Network(vector<int> &sizes, vector<VectorXd> &training_inputs, vector<VectorXd> &training_outputs,\n       vector<VectorXd> &test_inputs, vector<int> &test_labels,\n       int mini_batch_size, double learning_rate);\n    void feedforward(VectorXd &a);\n    void backpropagate(VectorXd &y);\n    void stochastic_gradient_descent(int epochs);\n    double evaluate();\n    int save_weights_and_biases(string filepath);\n  private:\n    void update_mini_batch(vector<int> &indices, int batch_num); /* helper for ``stochastic_gradient_descent``. */\n    VectorXd sigmoid_prime(int &layer_num); /* helper for ``backpropogate``. */\n    VectorXd relu_prime(int &layer_num); /* helper for ``backpropogate``. */\n    VectorXd cost_derivative(VectorXd &y); /* helper for ``backpropogate``. */\n    int num_layers_; /* Number of layers in the network (including input and output layers). */\n    vector<int> sizes_; /* Vector containing the sizes of each layer. ``sizes_.size() == num_layers``. */\n    vector<VectorXd> biases_; /* Bias vectors for each layer. \n                               * 0th index contains a dummy vector since there is no bias for the input layer. */\n    vector<MatrixXd> weights_; /* Weight vectors for each layer except the input. \n                                * 0th index contains a dummy matrix since there is no weight for the input layer. */\n    vector<VectorXd> as_; /* Stores the activations of each layer to avoid repeated computation. */\n    vector<VectorXd> zs_; /* Stores the z-vectors of each layer to avoid repeated computation. */\n    vector<VectorXd> nabla_b_; /* Stores the derivatives of the cost function with respect to the baises. */\n    vector<MatrixXd> nabla_w_; /* Stores the derivatives of the cost function with respect to the weights. */\n    vector<VectorXd> training_inputs_;\n    vector<VectorXd> training_outputs_;\n    vector<VectorXd> test_inputs_;\n    vector<int> test_labels_;\n    int mini_batch_size_;\n    double learning_rate_;\n};\n\n", "meta": {"hexsha": "48baa4fb86996695adb21a08aaa69012b3be732e", "size": 2143, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/network.hpp", "max_stars_repo_name": "oojiang/Neural-Net-From-Scratch", "max_stars_repo_head_hexsha": "555847dee624c8f16ca6dd46b84e1114bdc0b4e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/network.hpp", "max_issues_repo_name": "oojiang/Neural-Net-From-Scratch", "max_issues_repo_head_hexsha": "555847dee624c8f16ca6dd46b84e1114bdc0b4e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/network.hpp", "max_forks_repo_name": "oojiang/Neural-Net-From-Scratch", "max_forks_repo_head_hexsha": "555847dee624c8f16ca6dd46b84e1114bdc0b4e3", "max_forks_repo_licenses": ["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.8372093023, "max_line_length": 116, "alphanum_fraction": 0.7050863276, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5940704667812301}}
{"text": "#include <math_lib/plane.h>\n#include <math_lib/projection.h>\n\n#include <boost/qvm/vec_operations.hpp>\n\n#include <gtest/gtest.h>\n\nusing namespace pagoda;\n\nTEST(Plane, when_using_default_constructor_should_construct_the_xy_plane)\n{\n\tPlane<float> p;\n\tEXPECT_EQ(p.GetDistanceToOrigin(), 0.0f);\n\tEXPECT_TRUE(p.GetNormal() == (Vec3F{0, 0, 1}));\n}\n\nTEST(Plane, when_constructing_with_normal_and_distance_should_set_the_normal_and_distance_values)\n{\n\tPlane<float> p(Vec3F{1, 2, 3}, 4);\n\tEXPECT_EQ(p.GetDistanceToOrigin(), 4.0f);\n\tEXPECT_TRUE(p.GetNormal() == (Vec3F{1, 2, 3}));\n}\n\nTEST(Plane, when_constructing_from_point_and_normal_should_construct_the_plane_correctly)\n{\n\tauto p = Plane<float>::FromPointAndNormal(Vec3F{1, 0, 0}, Vec3F{0, 1, 0});\n\tEXPECT_EQ(p.GetDistanceToOrigin(), 0.0f);\n\tEXPECT_TRUE(p.GetNormal() == (Vec3F{0, 1, 0}));\n}\n\nTEST(Plane, when_constructing_from_three_points_should_construct_the_plane_correctly)\n{\n\tauto p = Plane<float>::FromPoints(Vec3F{1, 0.5, 0}, Vec3F{0, 0.5, 0}, Vec3F{0, 0.5, 1});\n\tEXPECT_EQ(p.GetDistanceToOrigin(), 0.5f);\n\tEXPECT_TRUE(p.GetNormal() == (Vec3F{0, 1, 0}));\n}\n\nTEST(Plane, when_constructing_from_a_point_and_two_vectors_should_construct_the_plane_correctly)\n{\n\tauto p = Plane<float>::FromPointAndVectors(Vec3F{1, 1, 1}, Vec3F{1, 0, 0}, Vec3F{0, 1, 0});\n\tEXPECT_EQ(p.GetDistanceToOrigin(), 1.0f);\n\tEXPECT_TRUE(p.GetNormal() == (Vec3F{0, 0, 1}));\n}\n\nTEST(Plane, when_getting_vectors_contained_in_the_plane_should_get_vectors_orthogonal_to_the_normal)\n{\n\tPlane<float> p(Vec3F{1, 2, 3}, 4);\n\tEXPECT_EQ(boost::qvm::dot(p.GetVector(), (Vec3F{1, 2, 3})), 0.0f);\n\tEXPECT_EQ(boost::qvm::dot(p.GetVector2(), (Vec3F{1, 2, 3})), 0.0f);\n}\n\nTEST(Plane, when_getting_points_contained_in_the_plane_should_have_zero_distance_to_the_plane)\n{\n\tPlane<float> plane(Vec3F{0, 0, 1}, 4);\n\tauto p1 = plane.GetPoint();\n\tauto p2 = plane.GetPoint2();\n\n\tEXPECT_TRUE(projection(p1, plane) == p1);\n\tEXPECT_TRUE(projection(p2, plane) == p2);\n}\n\nTEST(Plane, when_a_getting_the_side_of_the_plane_a_point_is_in_should_return_the_right_value)\n{\n\tPlane<float> plane = Plane<float>::FromPointAndNormal(Vec3F{0, 0, 0}, Vec3F{1, 0, 0});\n\n\tEXPECT_EQ(plane.GetPlaneSide((Vec3F{1, 0, 0})), Plane<float>::PlaneSide::Front);\n\tEXPECT_EQ(plane.GetPlaneSide((Vec3F{0, 0, 0})), Plane<float>::PlaneSide::Contained);\n\tEXPECT_EQ(plane.GetPlaneSide((Vec3F{-1, 0, 0})), Plane<float>::PlaneSide::Back);\n}\n", "meta": {"hexsha": "8d34a5eb11e614f437b84033531677212c73c822", "size": 2398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit_tests/math_lib/plane.cpp", "max_stars_repo_name": "diegoarjz/selector", "max_stars_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T17:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-12T14:37:27.000Z", "max_issues_repo_path": "tests/unit_tests/math_lib/plane.cpp", "max_issues_repo_name": "diegoarjz/selector", "max_issues_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47.0, "max_issues_repo_issues_event_min_datetime": "2019-05-27T15:24:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T17:54:54.000Z", "max_forks_repo_path": "tests/unit_tests/math_lib/plane.cpp", "max_forks_repo_name": "diegoarjz/selector", "max_forks_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2571428571, "max_line_length": 100, "alphanum_fraction": 0.7376980817, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5940704644735743}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <cmath>\n#include <gmp.h>\n#include <limits>\n#include <mpfr.h>\n\n#include \"runtime/header.h\"\n\nextern \"C\" {\nfloating *hook_FLOAT_ceil(floating *);\nfloating *hook_FLOAT_floor(floating *);\nfloating *hook_FLOAT_trunc(floating *);\nfloating *hook_FLOAT_round(floating *, mpz_t, mpz_t);\nmpz_ptr hook_FLOAT_float2int(floating *);\nfloating *hook_FLOAT_int2float(mpz_t, mpz_t, mpz_t);\nfloating *hook_FLOAT_sin(floating *);\nfloating *hook_FLOAT_cos(floating *);\nfloating *hook_FLOAT_tan(floating *);\nfloating *hook_FLOAT_sec(floating *);\nfloating *hook_FLOAT_csc(floating *);\nfloating *hook_FLOAT_cot(floating *);\nfloating *hook_FLOAT_asin(floating *);\nfloating *hook_FLOAT_acos(floating *);\nfloating *hook_FLOAT_atan(floating *);\nfloating *hook_FLOAT_atan2(floating *, floating *);\nmpz_ptr hook_FLOAT_precision(floating *);\nmpz_ptr hook_FLOAT_exponentBits(floating *);\nmpz_ptr hook_FLOAT_exponent(floating *);\nbool hook_FLOAT_isNaN(floating *);\nfloating *hook_FLOAT_maxValue(mpz_t, mpz_t);\nfloating *hook_FLOAT_minValue(mpz_t, mpz_t);\nbool hook_FLOAT_gt(floating *, floating *);\nbool hook_FLOAT_ge(floating *, floating *);\nbool hook_FLOAT_lt(floating *, floating *);\nbool hook_FLOAT_le(floating *, floating *);\nbool hook_FLOAT_eq(floating *, floating *);\nbool hook_FLOAT_ne(floating *, floating *);\nfloating *hook_FLOAT_abs(floating *);\nfloating *hook_FLOAT_neg(floating *);\nfloating *hook_FLOAT_min(floating *, floating *);\nfloating *hook_FLOAT_max(floating *, floating *);\nfloating *hook_FLOAT_add(floating *, floating *);\nfloating *hook_FLOAT_sub(floating *, floating *);\nfloating *hook_FLOAT_mul(floating *, floating *);\nfloating *hook_FLOAT_div(floating *, floating *);\nfloating *hook_FLOAT_rem(floating *, floating *);\nfloating *hook_FLOAT_pow(floating *, floating *);\nfloating *hook_FLOAT_root(floating *, mpz_t);\nfloating *hook_FLOAT_log(floating *);\nfloating *hook_FLOAT_exp(floating *);\nfloating *hook_FLOAT_rat2float(mpz_t, mpz_t, mpz_t, mpz_t);\nbool hook_FLOAT_sign(floating *);\n\nfloating *move_float(floating *i) {\n  floating *result = (floating *)malloc(sizeof(floating));\n  *result = *i;\n  return result;\n}\n}\n\nstatic void set_float(floating *a, unsigned prec, unsigned exp, double val) {\n  mpfr_init2(a->f, prec);\n  a->exp = exp;\n  mpfr_set_d(a->f, val, MPFR_RNDN);\n}\n\nBOOST_AUTO_TEST_SUITE(FloatTest)\n\nBOOST_AUTO_TEST_CASE(ceil) {\n  floating a[1];\n  floating *result;\n  set_float(a, 24, 8, 10.5);\n  result = hook_FLOAT_ceil(a);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 11.0), 0);\n}\n\nBOOST_AUTO_TEST_CASE(floor) {\n  floating a[1];\n  floating *result;\n  set_float(a, 24, 8, 10.5);\n  result = hook_FLOAT_floor(a);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 10.0), 0);\n}\n\nBOOST_AUTO_TEST_CASE(trunc) {\n  floating a[1];\n  floating *result;\n\n  set_float(a, 24, 8, 145.23);\n  result = hook_FLOAT_trunc(a);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 145.0), 0);\n\n  set_float(a, 53, 11, -0.5345);\n  result = hook_FLOAT_trunc(a);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 0.0), 0);\n\n  set_float(a, 24, 8, -2342.99);\n  result = hook_FLOAT_trunc(a);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, -2342.0), 0);\n\n  set_float(a, 53, 11, 54.34);\n  result = hook_FLOAT_trunc(a);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 54.0), 0);\n}\n\nBOOST_AUTO_TEST_CASE(round) {\n  floating a[1];\n  floating *result;\n  mpz_t b, c;\n  mpz_init_set_ui(b, 2);\n  mpz_init_set_ui(c, 8);\n  set_float(a, 53, 11, 10.5);\n  result = hook_FLOAT_round(a, b, c);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 12.0), 0);\n  set_float(a, 53, 11, 9.5);\n  result = hook_FLOAT_round(a, b, c);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 8.0), 0);\n  set_float(a, 53, 11, 10.5);\n  mpz_set_ui(b, 24);\n  result = hook_FLOAT_round(a, b, c);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 10.5), 0);\n  set_float(a, 53, 11, 9.5);\n  result = hook_FLOAT_round(a, b, c);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 9.5), 0);\n}\n\nBOOST_AUTO_TEST_CASE(float2int) {\n  floating a[1];\n  mpz_ptr result;\n  set_float(a, 53, 11, 10.5);\n  result = hook_FLOAT_float2int(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 10), 0);\n  set_float(a, 53, 11, 9.5);\n  result = hook_FLOAT_float2int(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 10), 0);\n}\n\nBOOST_AUTO_TEST_CASE(int2float) {\n  mpz_t a, b, c;\n  floating *result;\n  mpz_init_set_ui(a, 9);\n  mpz_init_set_ui(b, 2);\n  mpz_init_set_ui(c, 8);\n  result = hook_FLOAT_int2float(a, b, c);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 8.0), 0);\n  mpz_set_ui(a, 11);\n  result = hook_FLOAT_int2float(a, b, c);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 12.0), 0);\n  mpz_set_ui(a, 10);\n  result = hook_FLOAT_int2float(a, b, c);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 8.0), 0);\n  mpz_set_ui(b, 24);\n  result = hook_FLOAT_int2float(a, b, c);\n  BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, 10.0), 0);\n}\n\nBOOST_AUTO_TEST_CASE(trig) {\n  floating a[1];\n  floating *result;\n  set_float(a, 53, 11, M_PI_4);\n  result = hook_FLOAT_sin(a);\n  double e = 0.000000000000001;\n  BOOST_CHECK_CLOSE_FRACTION(mpfr_get_d(result->f, MPFR_RNDN), sin(M_PI_4), e);\n  result = hook_FLOAT_cos(a);\n  BOOST_CHECK_CLOSE_FRACTION(mpfr_get_d(result->f, MPFR_RNDN), cos(M_PI_4), e);\n  result = hook_FLOAT_tan(a);\n  BOOST_CHECK_CLOSE_FRACTION(mpfr_get_d(result->f, MPFR_RNDN), 1.0, e);\n  result = hook_FLOAT_sec(a);\n  BOOST_CHECK_CLOSE_FRACTION(\n      mpfr_get_d(result->f, MPFR_RNDN), 1.0 / cos(M_PI_4), e);\n  result = hook_FLOAT_csc(a);\n  BOOST_CHECK_CLOSE_FRACTION(\n      mpfr_get_d(result->f, MPFR_RNDN), 1.0 / sin(M_PI_4), e);\n  result = hook_FLOAT_cot(a);\n  BOOST_CHECK_CLOSE_FRACTION(mpfr_get_d(result->f, MPFR_RNDN), 1.0, e);\n  set_float(a, 53, 11, 0.0);\n  result = hook_FLOAT_asin(a);\n  BOOST_CHECK_CLOSE_FRACTION(mpfr_get_d(result->f, MPFR_RNDN), 0.0, e);\n  result = hook_FLOAT_acos(a);\n  BOOST_CHECK_CLOSE_FRACTION(mpfr_get_d(result->f, MPFR_RNDN), M_PI_2, e);\n  result = hook_FLOAT_atan(a);\n  BOOST_CHECK_CLOSE_FRACTION(mpfr_get_d(result->f, MPFR_RNDN), 0, e);\n  set_float(a, 53, 11, 1.0);\n  result = hook_FLOAT_asin(a);\n  BOOST_CHECK_CLOSE_FRACTION(mpfr_get_d(result->f, MPFR_RNDN), M_PI_2, e);\n  result = hook_FLOAT_acos(a);\n  BOOST_CHECK_CLOSE_FRACTION(mpfr_get_d(result->f, MPFR_RNDN), 0, e);\n  result = hook_FLOAT_atan(a);\n  BOOST_CHECK_CLOSE_FRACTION(mpfr_get_d(result->f, MPFR_RNDN), M_PI_4, e);\n  floating b[1];\n  set_float(b, 53, 11, 0.0);\n  result = hook_FLOAT_atan2(a, b);\n  BOOST_CHECK_CLOSE_FRACTION(mpfr_get_d(result->f, MPFR_RNDN), M_PI_2, e);\n  set_float(a, 53, 11, -1.0);\n  result = hook_FLOAT_atan2(a, b);\n  BOOST_CHECK_CLOSE_FRACTION(mpfr_get_d(result->f, MPFR_RNDN), -M_PI_2, e);\n}\n\nBOOST_AUTO_TEST_CASE(precision) {\n  floating a[1];\n  mpz_ptr result;\n  set_float(a, 2, 8, 0.0);\n  result = hook_FLOAT_precision(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 2), 0);\n  set_float(a, 24, 8, 0.0);\n  result = hook_FLOAT_precision(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 24), 0);\n}\n\nBOOST_AUTO_TEST_CASE(exponentBits) {\n  floating a[1];\n  mpz_ptr result;\n  set_float(a, 24, 8, 0.0);\n  result = hook_FLOAT_exponentBits(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 8), 0);\n  set_float(a, 53, 11, 0.0);\n  result = hook_FLOAT_exponentBits(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 11), 0);\n}\n\nBOOST_AUTO_TEST_CASE(exponent) {\n  floating a[1];\n  mpz_ptr result;\n  set_float(a, 24, 8, 0.0);\n  result = hook_FLOAT_exponent(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, -127), 0);\n  set_float(a, 24, 8, -0.0);\n  result = hook_FLOAT_exponent(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, -127), 0);\n  set_float(a, 24, 8, 1.0 / 0.0);\n  result = hook_FLOAT_exponent(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, 128), 0);\n  set_float(a, 24, 8, 0.0 / 0.0);\n  result = hook_FLOAT_exponent(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, 128), 0);\n  set_float(a, 24, 8, 4.0);\n  result = hook_FLOAT_exponent(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, 2), 0);\n  set_float(a, 24, 8, std::numeric_limits<float>::min());\n  result = hook_FLOAT_exponent(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, -126), 0);\n  set_float(a, 24, 8, std::numeric_limits<float>::denorm_min());\n  result = hook_FLOAT_exponent(a);\n  BOOST_CHECK_EQUAL(mpz_cmp_si(result, -127), 0);\n}\n\nBOOST_AUTO_TEST_CASE(isNaN) {\n  floating a[1];\n  set_float(a, 24, 8, 0.0);\n  BOOST_CHECK(!hook_FLOAT_isNaN(a));\n  set_float(a, 24, 8, -0.0);\n  BOOST_CHECK(!hook_FLOAT_isNaN(a));\n  set_float(a, 24, 8, 1.0 / 0.0);\n  BOOST_CHECK(!hook_FLOAT_isNaN(a));\n  set_float(a, 24, 8, 0.0 / 0.0);\n  BOOST_CHECK(hook_FLOAT_isNaN(a));\n}\n\nBOOST_AUTO_TEST_CASE(maxValue) {\n  mpz_t a, b;\n  mpz_init_set_ui(a, 24);\n  mpz_init_set_ui(b, 8);\n  floating *result;\n  result = hook_FLOAT_maxValue(a, b);\n  BOOST_CHECK_EQUAL(\n      mpfr_cmp_d(result->f, std::numeric_limits<float>::max()), 0);\n  mpz_init_set_ui(a, 53);\n  mpz_init_set_ui(b, 11);\n  result = hook_FLOAT_maxValue(a, b);\n  BOOST_CHECK_EQUAL(\n      mpfr_cmp_d(result->f, std::numeric_limits<double>::max()), 0);\n}\n\nBOOST_AUTO_TEST_CASE(minValue) {\n  mpz_t a, b;\n  mpz_init_set_ui(a, 24);\n  mpz_init_set_ui(b, 8);\n  floating *result;\n  result = hook_FLOAT_minValue(a, b);\n  BOOST_CHECK_EQUAL(\n      mpfr_cmp_d(result->f, std::numeric_limits<float>::denorm_min()), 0);\n  mpz_init_set_ui(a, 53);\n  mpz_init_set_ui(b, 11);\n  result = hook_FLOAT_minValue(a, b);\n  BOOST_CHECK_EQUAL(\n      mpfr_cmp_d(result->f, std::numeric_limits<double>::denorm_min()), 0);\n}\n\nBOOST_AUTO_TEST_CASE(lt) {\n  floating arr[6], nan[1];\n  set_float(arr, 24, 8, -1.0 / 0.0);\n  set_float(arr + 1, 24, 8, -1.0);\n  set_float(arr + 2, 24, 8, -0.0);\n  set_float(arr + 3, 24, 8, 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, 1.0 / 0.0);\n  set_float(nan, 24, 8, 0.0 / 0.0);\n  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {\n    for (int j = 0; j < sizeof(arr) / sizeof(arr[0]); j++) {\n      bool result = hook_FLOAT_lt(arr + i, arr + j);\n      if ((i == 2 && j == 3) || (i == 3 && j == 2)) {\n        BOOST_CHECK(!result);\n      } else if (i < j) {\n        BOOST_CHECK(result);\n      } else {\n        BOOST_CHECK(!result);\n      }\n    }\n  }\n  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {\n    BOOST_CHECK(!hook_FLOAT_lt(arr + i, nan));\n    BOOST_CHECK(!hook_FLOAT_lt(nan, arr + i));\n  }\n  BOOST_CHECK(!hook_FLOAT_lt(nan, nan));\n}\n\nBOOST_AUTO_TEST_CASE(le) {\n  floating arr[6], nan[1];\n  set_float(arr, 24, 8, -1.0 / 0.0);\n  set_float(arr + 1, 24, 8, -1.0);\n  set_float(arr + 2, 24, 8, -0.0);\n  set_float(arr + 3, 24, 8, 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, 1.0 / 0.0);\n  set_float(nan, 24, 8, 0.0 / 0.0);\n  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {\n    for (int j = 0; j < sizeof(arr) / sizeof(arr[0]); j++) {\n      bool result = hook_FLOAT_le(arr + i, arr + j);\n      if ((i == 2 && j == 3) || (i == 3 && j == 2)) {\n        BOOST_CHECK(result);\n      } else if (i <= j) {\n        BOOST_CHECK(result);\n      } else {\n        BOOST_CHECK(!result);\n      }\n    }\n  }\n  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {\n    BOOST_CHECK(!hook_FLOAT_le(arr + i, nan));\n    BOOST_CHECK(!hook_FLOAT_le(nan, arr + i));\n  }\n  BOOST_CHECK(!hook_FLOAT_le(nan, nan));\n}\n\nBOOST_AUTO_TEST_CASE(gt) {\n  floating arr[6], nan[1];\n  set_float(arr, 24, 8, -1.0 / 0.0);\n  set_float(arr + 1, 24, 8, -1.0);\n  set_float(arr + 2, 24, 8, -0.0);\n  set_float(arr + 3, 24, 8, 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, 1.0 / 0.0);\n  set_float(nan, 24, 8, 0.0 / 0.0);\n  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {\n    for (int j = 0; j < sizeof(arr) / sizeof(arr[0]); j++) {\n      bool result = hook_FLOAT_gt(arr + i, arr + j);\n      if ((i == 2 && j == 3) || (i == 3 && j == 2)) {\n        BOOST_CHECK(!result);\n      } else if (i > j) {\n        BOOST_CHECK(result);\n      } else {\n        BOOST_CHECK(!result);\n      }\n    }\n  }\n  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {\n    BOOST_CHECK(!hook_FLOAT_gt(arr + i, nan));\n    BOOST_CHECK(!hook_FLOAT_gt(nan, arr + i));\n  }\n  BOOST_CHECK(!hook_FLOAT_gt(nan, nan));\n}\n\nBOOST_AUTO_TEST_CASE(ge) {\n  floating arr[6], nan[1];\n  set_float(arr, 24, 8, -1.0 / 0.0);\n  set_float(arr + 1, 24, 8, -1.0);\n  set_float(arr + 2, 24, 8, -0.0);\n  set_float(arr + 3, 24, 8, 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, 1.0 / 0.0);\n  set_float(nan, 24, 8, 0.0 / 0.0);\n  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {\n    for (int j = 0; j < sizeof(arr) / sizeof(arr[0]); j++) {\n      bool result = hook_FLOAT_ge(arr + i, arr + j);\n      if ((i == 2 && j == 3) || (i == 3 && j == 2)) {\n        BOOST_CHECK(result);\n      } else if (i >= j) {\n        BOOST_CHECK(result);\n      } else {\n        BOOST_CHECK(!result);\n      }\n    }\n  }\n  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {\n    BOOST_CHECK(!hook_FLOAT_ge(arr + i, nan));\n    BOOST_CHECK(!hook_FLOAT_ge(nan, arr + i));\n  }\n  BOOST_CHECK(!hook_FLOAT_ge(nan, nan));\n}\n\nBOOST_AUTO_TEST_CASE(eq) {\n  floating arr[6], nan[1];\n  set_float(arr, 24, 8, -1.0 / 0.0);\n  set_float(arr + 1, 24, 8, -1.0);\n  set_float(arr + 2, 24, 8, -0.0);\n  set_float(arr + 3, 24, 8, 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, 1.0 / 0.0);\n  set_float(nan, 24, 8, 0.0 / 0.0);\n  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {\n    for (int j = 0; j < sizeof(arr) / sizeof(arr[0]); j++) {\n      bool result = hook_FLOAT_eq(arr + i, arr + j);\n      if ((i == 2 && j == 3) || (i == 3 && j == 2)) {\n        BOOST_CHECK(result);\n      } else if (i == j) {\n        BOOST_CHECK(result);\n      } else {\n        BOOST_CHECK(!result);\n      }\n    }\n  }\n  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {\n    BOOST_CHECK(!hook_FLOAT_eq(arr + i, nan));\n    BOOST_CHECK(!hook_FLOAT_eq(nan, arr + i));\n  }\n  BOOST_CHECK(!hook_FLOAT_eq(nan, nan));\n}\n\nBOOST_AUTO_TEST_CASE(ne) {\n  floating arr[6], nan[1];\n  set_float(arr, 24, 8, -1.0 / 0.0);\n  set_float(arr + 1, 24, 8, -1.0);\n  set_float(arr + 2, 24, 8, -0.0);\n  set_float(arr + 3, 24, 8, 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, 1.0 / 0.0);\n  set_float(nan, 24, 8, 0.0 / 0.0);\n  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {\n    for (int j = 0; j < sizeof(arr) / sizeof(arr[0]); j++) {\n      bool result = hook_FLOAT_ne(arr + i, arr + j);\n      if ((i == 2 && j == 3) || (i == 3 && j == 2)) {\n        BOOST_CHECK(!result);\n      } else if (i != j) {\n        BOOST_CHECK(result);\n      } else {\n        BOOST_CHECK(!result);\n      }\n    }\n  }\n  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {\n    BOOST_CHECK(hook_FLOAT_ne(arr + i, nan));\n    BOOST_CHECK(hook_FLOAT_ne(nan, arr + i));\n  }\n  BOOST_CHECK(hook_FLOAT_ne(nan, nan));\n}\n\nBOOST_AUTO_TEST_CASE(abs) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    floating *result = hook_FLOAT_abs(arr + i);\n    float f = fabsf(ref[i]);\n    if (f != f) {\n      BOOST_CHECK(mpfr_nan_p(result->f));\n    } else {\n      BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(log) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    floating *result = hook_FLOAT_log(arr + i);\n    float f = logf(ref[i]);\n    if (f != f) {\n      BOOST_CHECK(mpfr_nan_p(result->f));\n    } else {\n      BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(exp) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    floating *result = hook_FLOAT_exp(arr + i);\n    float f = expf(ref[i]);\n    if (f != f) {\n      BOOST_CHECK(mpfr_nan_p(result->f));\n    } else {\n      BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(neg) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    floating *result = hook_FLOAT_neg(arr + i);\n    float f = -ref[i];\n    if (f != f) {\n      BOOST_CHECK(mpfr_nan_p(result->f));\n    } else {\n      BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(min) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    for (int j = 0; j < sizeof(ref) / sizeof(ref[0]); j++) {\n      floating *result = hook_FLOAT_min(arr + i, arr + j);\n      float f = fminf(ref[i], ref[j]);\n      if (f != f) {\n        BOOST_CHECK(mpfr_nan_p(result->f));\n      } else {\n        BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(max) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    for (int j = 0; j < sizeof(ref) / sizeof(ref[0]); j++) {\n      floating *result = hook_FLOAT_max(arr + i, arr + j);\n      float f = fmaxf(ref[i], ref[j]);\n      if (f != f) {\n        BOOST_CHECK(mpfr_nan_p(result->f));\n      } else {\n        BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(add) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    for (int j = 0; j < sizeof(ref) / sizeof(ref[0]); j++) {\n      floating *result = hook_FLOAT_add(arr + i, arr + j);\n      float f = ref[i] + ref[j];\n      if (f != f) {\n        BOOST_CHECK(mpfr_nan_p(result->f));\n      } else {\n        BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(sub) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    for (int j = 0; j < sizeof(ref) / sizeof(ref[0]); j++) {\n      floating *result = hook_FLOAT_sub(arr + i, arr + j);\n      float f = ref[i] - ref[j];\n      if (f != f) {\n        BOOST_CHECK(mpfr_nan_p(result->f));\n      } else {\n        BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(mul) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    for (int j = 0; j < sizeof(ref) / sizeof(ref[0]); j++) {\n      floating *result = hook_FLOAT_mul(arr + i, arr + j);\n      float f = ref[i] * ref[j];\n      if (f != f) {\n        BOOST_CHECK(mpfr_nan_p(result->f));\n      } else {\n        BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(div) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    for (int j = 0; j < sizeof(ref) / sizeof(ref[0]); j++) {\n      floating *result = hook_FLOAT_div(arr + i, arr + j);\n      float f = ref[i] / ref[j];\n      if (f != f) {\n        BOOST_CHECK(mpfr_nan_p(result->f));\n      } else {\n        BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(rem) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    for (int j = 0; j < sizeof(ref) / sizeof(ref[0]); j++) {\n      floating *result = hook_FLOAT_rem(arr + i, arr + j);\n      float f = fmodf(ref[i], ref[j]);\n      if (f != f) {\n        BOOST_CHECK(mpfr_nan_p(result->f));\n      } else {\n        BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(pow) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    for (int j = 0; j < sizeof(ref) / sizeof(ref[0]); j++) {\n      floating *result = hook_FLOAT_pow(arr + i, arr + j);\n      float f = powf(ref[i], ref[j]);\n      if (f != f) {\n        BOOST_CHECK(mpfr_nan_p(result->f));\n      } else {\n        BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(root) {\n  floating arr[9];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  float ref[9];\n  ref[0] = 0.0f;\n  ref[1] = -0.0f;\n  ref[2] = 1.0f / 0.0f;\n  ref[3] = -1.0f / 0.0f;\n  ref[4] = 1.0f;\n  ref[5] = -1.0f;\n  ref[6] = 3.0f;\n  ref[7] = 0.5f;\n  ref[8] = 0.0f / 0.0f;\n  mpz_t k;\n  mpz_init_set_ui(k, 2);\n  for (int i = 0; i < sizeof(ref) / sizeof(ref[0]); i++) {\n    floating *result = hook_FLOAT_root(arr + i, k);\n    float f = sqrt(ref[i]);\n    if (f != f) {\n      BOOST_CHECK(mpfr_nan_p(result->f));\n    } else {\n      BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, f), 0);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(sign) {\n  floating arr[10];\n  set_float(arr + 0, 24, 8, 0.0);\n  set_float(arr + 1, 24, 8, -0.0);\n  set_float(arr + 2, 24, 8, 1.0 / 0.0);\n  set_float(arr + 3, 24, 8, -1.0 / 0.0);\n  set_float(arr + 4, 24, 8, 1.0);\n  set_float(arr + 5, 24, 8, -1.0);\n  set_float(arr + 6, 24, 8, 3.0);\n  set_float(arr + 7, 24, 8, 0.5);\n  set_float(arr + 8, 24, 8, 0.0 / 0.0);\n  BOOST_CHECK(!hook_FLOAT_sign(arr + 0));\n  BOOST_CHECK(hook_FLOAT_sign(arr + 1));\n  BOOST_CHECK(!hook_FLOAT_sign(arr + 2));\n  BOOST_CHECK(hook_FLOAT_sign(arr + 3));\n  BOOST_CHECK(!hook_FLOAT_sign(arr + 4));\n  BOOST_CHECK(hook_FLOAT_sign(arr + 5));\n  BOOST_CHECK(!hook_FLOAT_sign(arr + 6));\n  BOOST_CHECK(!hook_FLOAT_sign(arr + 7));\n  BOOST_CHECK(!hook_FLOAT_sign(arr + 8));\n}\n\nBOOST_AUTO_TEST_CASE(rat2float) {\n  mpz_t num, den, prec, exp;\n  mpz_init_set_ui(num, 1);\n  mpz_init_set_ui(den, 3);\n  mpz_init_set_ui(prec, 53);\n  mpz_init_set_ui(exp, 11);\n  floating *result = hook_FLOAT_rat2float(num, den, prec, exp);\n  mpfr_t ref;\n  mpfr_init2(ref, 53);\n  mpfr_set_d(ref, 0.33333333333333333333333333333333333, MPFR_RNDN);\n  BOOST_CHECK_EQUAL(mpfr_cmp(ref, result->f), 0);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "9dbbf9d5c3092c85a999e1f8b9defde7e789f924", "size": 27507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/runtime-arithmetic/floattest.cpp", "max_stars_repo_name": "Tarnyko/llvm-backend", "max_stars_repo_head_hexsha": "96a81b5909f925d286ceb64def3ff9b4bcc5a97e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2018-08-01T16:45:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T07:37:50.000Z", "max_issues_repo_path": "unittests/runtime-arithmetic/floattest.cpp", "max_issues_repo_name": "Tarnyko/llvm-backend", "max_issues_repo_head_hexsha": "96a81b5909f925d286ceb64def3ff9b4bcc5a97e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 165.0, "max_issues_repo_issues_event_min_datetime": "2018-07-26T19:55:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T16:39:32.000Z", "max_forks_repo_path": "unittests/runtime-arithmetic/floattest.cpp", "max_forks_repo_name": "runtimeverification/llvm-backend", "max_forks_repo_head_hexsha": "8243ca9e201f9be793b57ddfb54cc77043a14dd4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-08-18T06:00:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T00:19:46.000Z", "avg_line_length": 29.6731391586, "max_line_length": 79, "alphanum_fraction": 0.5831970044, "num_tokens": 11315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5940704583375498}}
{"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": "//\n// Created by Amir Masoud Abdol on 2020-07-28\n//\n\n#include \"HackingProbabilityStrategy.h\"\n\n#include <boost/math/special_functions/relative_difference.hpp>\n\nusing namespace sam;\nusing boost::math::relative_difference;\n\nHackingProbabilityStrategy::~HackingProbabilityStrategy(){\n    // Pure destructors\n};\n\nstd::unique_ptr<HackingProbabilityStrategy>\nHackingProbabilityStrategy::build(json &config) {\n\n  auto params = config.get<FrankenbachStrategy::Parameters>();\n  return std::make_unique<FrankenbachStrategy>(params);\n}\n\nfloat FrankenbachStrategy::estimate(Experiment *experiment) {\n\n  /// @todo replace this with boost comparison\n  if ((params.base_hp - 0.) < 0.00001) {\n    return 0.0;\n  }\n\n  // We have something in the middle now, so, we are calculating based on the\n  // p-value we check for significance, if sig, then we return 0. else, then we\n  // assign a value\n\n  bool is_any_non_sig{false};\n  for (int i{experiment->setup.nd()}, d{0}; i < experiment->setup.ng();\n       ++i, ++d %= experiment->setup.nd()) {\n    is_any_non_sig |= !experiment->dvs_[i].sig_;\n  }\n\n  if (!is_any_non_sig) {\n    return 0.0;\n  }\n\n  // I have a feeling this is a very inefficient implementation\n  int d = experiment->setup.nd();\n  int g = experiment->setup.ng();\n\n  arma::Row<float> dangers(g - d);\n\n  dangers.imbue([&, i = d]() mutable {\n    return this->border(experiment->dvs_[i++].effect_sei);\n  });\n\n  probabilities.resize(g - d);\n  probabilities.imbue([&, i = d]() mutable {\n    if (experiment->dvs_[i].effect_ > dangers[i - 1]) {\n\n      float d_sig = experiment->dvs_[i].effect_sei * 1.959964;\n      arma::Row<float> danger_breaks =\n          arma::linspace<arma::Row<float>>(dangers[i - 1], d_sig, 11);\n\n      // If the hacking probability is 1, then everything in this range is\n      // going to be hacked, a.k.a, hp = 1; Update: I think I had this wrong\n      // previously, where I assign the probability to everything, while it\n      // should only be assigned to those studies that are passing the effect\n      // test in the first place\n      if ((params.base_hp - 1.) < 0.00001) {\n        return static_cast<float>(1);\n      }\n\n      return arma::as_scalar(hp_range.at(\n          arma::max(find(danger_breaks < experiment->dvs_[i++].effect_))));\n    }\n    // else\n    return static_cast<float>(0);\n  });\n\n  spdlog::trace(\"Chance of hacking: {}\", arma::max(probabilities));\n\n  // @todo Remember that you should consider some option here. At the moment,\n  // I'm returning the maximum of all probabilities, but that's not necessarily\n  // the best things to do, also, it works just fine in Frankenbach simulation\n  // because they have only one one outcome anyway\n  return arma::max(probabilities);\n}\n", "meta": {"hexsha": "74d8f789fa8fbe144b983224d2d1310f2c3dc95c", "size": 2706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HackingProbabilityStrategy.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/HackingProbabilityStrategy.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/HackingProbabilityStrategy.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": 31.4651162791, "max_line_length": 79, "alphanum_fraction": 0.6740576497, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5938885917418284}}
{"text": "#define CATCH_CONFIG_MAIN\n#include <catch/catch.hpp>\n\n#include <ctime>\n\n#include <complex>\n#include <iostream>\n\n#include <Eigen/Core>\n\n#include <fftw3/shared_plan.hpp>\n\nusing Index         = Eigen::Index;\nusing Real          = double;\nusing Complex       = std::complex<Real>;\nusing RealVector    = Eigen::VectorXd;\nusing ComplexVector = Eigen::VectorXcd;\nusing RealMatrix    = Eigen::MatrixXd;\nusing ComplexMatrix = Eigen::MatrixXcd;\n\nusing FFT  = fftw3::FFT<Real>;\nusing IFFT = fftw3::IFFT<Real>;\n\nstatic const double eps = 1.0e-14;\n\nvoid test_complex_fft_many_1d(Index n, Index howmany)\n{\n    INFO(\"1D complex-to-complex FFT (n = \" << n << \", howmany = \" << howmany\n                                           << ')');\n\n    ComplexMatrix f1(n, howmany);\n    ComplexMatrix re_f1(n, howmany);\n    ComplexMatrix g1(n, howmany);\n\n    RealMatrix f2(n, howmany);\n    RealMatrix re_f2(n, howmany);\n    ComplexMatrix g2(n / 2 + 1, howmany);\n\n    int n_       = static_cast<int>(n);\n    int howmany_ = static_cast<int>(howmany);\n\n    // Complex-to-complex\n    auto plan_fft  = FFT::make_plan(n_, howmany_, f1.data(), g1.data());\n    auto plan_ifft = IFFT::make_plan(n_, howmany_, f1.data(), g1.data());\n\n    f1.setRandom();\n    FFT::run(plan_fft, f1.data(), g1.data());\n    IFFT::run(plan_ifft, g1.data(), re_f1.data());\n    re_f1 /= Real(n);\n\n    for (Index i = 0; i < howmany; ++i)\n    {\n        const Real residual = (f1.col(i) - re_f1.col(i)).norm();\n        CHECK(residual == Approx(0.0).margin(n * eps));\n    }\n}\n\nvoid test_real_fft_many_1d(Index n, Index howmany)\n{\n    INFO(\"1D real-to-complex FFT (n = \" << n << \", howmany = \" << howmany\n                                        << ')');\n\n    RealMatrix f2(n, howmany);\n    RealMatrix re_f2(n, howmany);\n    ComplexMatrix g2(n / 2 + 1, howmany);\n\n    RealVector residuals(howmany);\n\n    int n_       = static_cast<int>(n);\n    int howmany_ = static_cast<int>(howmany);\n\n    // Real-to-complex transform\n    auto plan_fft_r2c  = FFT::make_plan(n_, howmany_, f2.data(), g2.data());\n    auto plan_ifft_r2c = IFFT::make_plan(n_, howmany_, g2.data(), re_f2.data());\n\n    f2.setRandom();\n    FFT::run(plan_fft_r2c, f2.data(), g2.data());\n    IFFT::run(plan_ifft_r2c, g2.data(), re_f2.data());\n    re_f2 /= Real(n);\n\n    for (Index i = 0; i < howmany; ++i)\n    {\n        const Real residual = (f2.col(i) - re_f2.col(i)).norm();\n        CHECK(residual == Approx(0.0).margin(n * eps));\n    }\n}\n\nTEST_CASE(\"Test thread-safe FFTW3 wrapper for multiple 1D FFT\")\n{\n    std::srand(static_cast<unsigned>(std::time(0)));\n    SECTION(\"Complex-to-complex FFT\")\n    {\n        test_complex_fft_many_1d(100, 20);\n        test_complex_fft_many_1d(1000, 10);\n        test_complex_fft_many_1d(10000, 5);\n        test_complex_fft_many_1d(100000, 2);\n        test_complex_fft_many_1d(1000000, 1);\n    }\n\n    SECTION(\"Real-to-complex FFT\")\n    {\n        test_real_fft_many_1d(100, 20);\n        test_real_fft_many_1d(1000, 10);\n        test_real_fft_many_1d(10000, 5);\n        test_real_fft_many_1d(100000, 2);\n        test_real_fft_many_1d(1000000, 1);\n    }\n}\n", "meta": {"hexsha": "676649a35933edd710580942d2d88e67214e39cc", "size": 3085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fftw3/shared_plan.cpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "test/fftw3/shared_plan.cpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "test/fftw3/shared_plan.cpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3027522936, "max_line_length": 80, "alphanum_fraction": 0.6084278768, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5938885911439615}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::exponential::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_EXPONENTIAL_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_EXPONENTIAL_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#include <string>\n#include <boost/math/distributions/exponential.hpp>\n#include <boost/math/policies/policy.hpp> \n\nnamespace boost{\nnamespace math{\n\n    template<typename T,typename P>\n    T\n    log_unnormalized_pdf(\n        const boost::math::exponential_distribution<T,P>& d,\n        const T& x\n    ){\n\n        typedef std::string str_;\n        BOOST_MATH_STD_USING // for ADL of std functions\n        static const char* function = \n            (str_(\"log_unnormalized_pdf(\")+ \n            \"const exponential_distribution<%1%>&,%1%)\").c_str();\n\n        T lambda = d.lambda();\n        T result;\n\n        if(0 == boost::math::detail::verify_lambda(\n            function, lambda, &result, P()))\n            return result;\n        if(0 == boost::math::detail::verify_exp_x(\n            function, x, &result, P()))\n            return result;\n        result = (-lambda * x);\n        return result;\n    }\n\n}// math\n}// boost\n\n#endif\n", "meta": {"hexsha": "0f804de1077a0632ca8ab9ad6e9df3d2ff7620fc", "size": 1772, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/exponential/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/exponential/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/exponential/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": 36.9166666667, "max_line_length": 97, "alphanum_fraction": 0.5428893905, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5938885814415369}}
{"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": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2020 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"alpha_kernel_d\"\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <CGAL/Epick_d.h>\n#include <CGAL/Epeck_d.h>\n#include <CGAL/NT_converter.h>\n\n#include <iostream>\n#include <vector>\n#include <utility>  // for std::pair\n\n#include <gudhi/Alpha_complex/Alpha_kernel_d.h>\n#include <gudhi/Unitary_tests_utils.h>\n\n// Use dynamic_dimension_tag for the user to be able to set dimension\ntypedef CGAL::Epeck_d< CGAL::Dynamic_dimension_tag > Exact_kernel_d;\n// Use static dimension_tag for the user not to be able to set dimension\ntypedef CGAL::Epeck_d< CGAL::Dimension_tag<4> > Exact_kernel_s;\n// Use dynamic_dimension_tag for the user to be able to set dimension\ntypedef CGAL::Epick_d< CGAL::Dynamic_dimension_tag > Inexact_kernel_d;\n// Use static dimension_tag for the user not to be able to set dimension\ntypedef CGAL::Epick_d< CGAL::Dimension_tag<4> > Inexact_kernel_s;\n// The triangulation uses the default instantiation of the TriangulationDataStructure template parameter\n\ntypedef boost::mpl::list<Exact_kernel_d, Exact_kernel_s, Inexact_kernel_d, Inexact_kernel_s> list_of_kernel_variants;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_kernel_d_dimension, TestedKernel, list_of_kernel_variants) {\n  // Test for a point (weighted or not) in 4d, that the dimension is 4.\n\n  Gudhi::alpha_complex::Alpha_kernel_d<TestedKernel, false> kernel;\n  std::vector<double> p0 {0., 1., 2., 3.};\n  typename TestedKernel::Point_d p0_d(p0.begin(), p0.end());\n\n  std::clog << \"Dimension is \" << kernel.get_dimension(p0_d) << std::endl;\n  BOOST_CHECK(kernel.get_dimension(p0_d) == 4);\n\n  Gudhi::alpha_complex::Alpha_kernel_d<TestedKernel, true> w_kernel;\n  typename TestedKernel::Weighted_point_d w_p0_d(p0_d, 10.);\n\n  std::clog << \"Dimension is \" << w_kernel.get_dimension(w_p0_d) << std::endl;\n  BOOST_CHECK(w_kernel.get_dimension(w_p0_d) == 4);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_kernel_d_sphere, TestedKernel, list_of_kernel_variants) {\n  // Test with 5 points on a 3-sphere, that get_sphere returns the same center and squared radius\n  // for dD unweighted and for dD weighted with all weights at 0.\n\n  using Unweighted_kernel = Gudhi::alpha_complex::Alpha_kernel_d<TestedKernel, false>;\n  // Sphere: (x-1)\u00b2 + (y-1)\u00b2 + z\u00b2 + t\u00b2 = 1\n  // At least 5 points for a 3-sphere\n  std::vector<double> p0 {1., 0., 0., 0.};\n  std::vector<double> p1 {0., 1., 0., 0.};\n  std::vector<double> p2 {1., 1., 1., 0.};\n  std::vector<double> p3 {1., 1., 0., 1.};\n  std::vector<double> p4 {1., 1., -1., 0.};\n\n  using Point_d = typename Unweighted_kernel::Point_d;\n  std::vector<Point_d> unw_pts;\n  unw_pts.emplace_back(p0.begin(), p0.end());\n  unw_pts.emplace_back(p1.begin(), p1.end());\n  unw_pts.emplace_back(p2.begin(), p2.end());\n  unw_pts.emplace_back(p3.begin(), p3.end());\n  unw_pts.emplace_back(p4.begin(), p4.end());\n\n  Unweighted_kernel kernel;\n  auto unw_sphere = kernel.get_sphere(unw_pts.cbegin(), unw_pts.cend());\n\n  std::clog << \"Center is \" << unw_sphere.first << \" - squared radius is \" << unw_sphere.second << std::endl;\n\n  using Weighted_kernel = Gudhi::alpha_complex::Alpha_kernel_d<TestedKernel, true>;\n\n  using Weighted_point_d = typename Weighted_kernel::Weighted_point_d;\n  using Bare_point_d = typename Weighted_kernel::Bare_point_d;\n  std::vector<Weighted_point_d> w_pts;\n  w_pts.emplace_back(Bare_point_d(p0.begin(), p0.end()), 0.);\n  w_pts.emplace_back(Bare_point_d(p1.begin(), p1.end()), 0.);\n  w_pts.emplace_back(Bare_point_d(p2.begin(), p2.end()), 0.);\n  w_pts.emplace_back(Bare_point_d(p3.begin(), p3.end()), 0.);\n  w_pts.emplace_back(Bare_point_d(p4.begin(), p4.end()), 0.);\n\n  Weighted_kernel w_kernel;\n  auto w_sphere = w_kernel.get_sphere(w_pts.cbegin(), w_pts.cend());\n\n  std::clog << \"Center is \" << w_sphere.point() << \" - squared radius is \" << w_sphere.weight() << std::endl;\n\n  CGAL::NT_converter<typename Weighted_kernel::FT, double> cast_to_double;\n  // The results shall be the same with weights = 0.\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(cast_to_double(unw_sphere.second), cast_to_double(w_sphere.weight()));\n  BOOST_CHECK(unw_sphere.first == w_sphere.point());\n\n  auto unw_sq_rd = kernel.get_squared_radius(unw_pts.cbegin(), unw_pts.cend());\n  std::clog << \"Squared radius is \" << unw_sq_rd << std::endl;\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(cast_to_double(unw_sphere.second), cast_to_double(unw_sq_rd));\n  auto w_sq_rd = w_kernel.get_squared_radius(w_pts.cbegin(), w_pts.cend());\n  std::clog << \"Squared radius is \" << w_sq_rd << std::endl;\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(cast_to_double(w_sphere.weight()), cast_to_double(w_sq_rd));\n}\n", "meta": {"hexsha": "6da4c08450a107be78cda9f7b96f4b1419b2d75c", "size": 4970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Alpha_complex/test/Alpha_kernel_d_unit_test.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Alpha_complex/test/Alpha_kernel_d_unit_test.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Alpha_complex/test/Alpha_kernel_d_unit_test.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 45.1818181818, "max_line_length": 117, "alphanum_fraction": 0.7307847082, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5938885756935245}}
{"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": "#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include \"../include/core/pardiso.hpp\"\n\nusing namespace std;\n\n\nTEST(Pardiso, unsymmSolver)\n{\n    // CSR sparse matrix\n    int sizeA = 8;\n    int rowPtrA[9] = { 0, 4, 7, 9, 11, 12, 15, 17, 20 };\n    int colIdA[20] = { 0,    2,       5, 6,\n                          1, 2,    4,\n                             2,             7,\n                                   3,       6,\n                          1,\n                             2,       5,    7,\n                          1,             6,\n                             2,          6, 7 };\n    double dataA[20] = { 7.0,      1.0,           2.0, 7.0,\n                             -4.0, 8.0,      2.0,\n                                   1.0,                     5.0,\n                                        7.0,           9.0,\n                             -4.0,\n                                   7.0,           3.0,      8.0,\n                              1.0,                    11.0,\n                                  -3.0,                2.0, 5.0 };\n\n    // create an Eigen Sparse matrix from rowPtrA, colIdA, dataA\n    Eigen::SparseMatrix<double> matA(sizeA, sizeA);\n    matA.reserve(20);\n    for (int i=0; i<sizeA; i++) {\n        for (int j=rowPtrA[i]; j<rowPtrA[i+1]; j++) {\n            matA.insert(i,colIdA[j]) = dataA[j];\n        }\n    }\n    matA.makeCompressed();\n\n    // rhs\n    Eigen::VectorXd b(sizeA);\n    //b = Eigen::VectorXd::Constant(sizeA, 1);\n    b = Eigen::VectorXd::Random(sizeA);\n\n    // solve with Eigen\n    Eigen::VectorXd true_x(sizeA);\n    Eigen::SparseLU sparselu(matA);\n    true_x = sparselu.solve(b);\n\n    // solve with Pardiso\n    int mtype = 11;\n    Eigen::VectorXd x(sizeA);\n    PardisoSolver pardisoSolver(mtype);\n    pardisoSolver.initialize(sizeA, rowPtrA, colIdA, dataA);\n    pardisoSolver.factorize();\n    pardisoSolver.solve(b.data(), x.data());\n    pardisoSolver.finalize();\n\n    double TOL = 1E-8;\n    ASSERT_LE((true_x - x).norm(), TOL);\n}\n", "meta": {"hexsha": "9054678ac09e3ef8228f826efa9ad5bedd84c588", "size": 2003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_pardiso.cpp", "max_stars_repo_name": "pratyuksh/FEMWave", "max_stars_repo_head_hexsha": "9ed0fbe0981d712ce3e531500381589b034fb9f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T13:06:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T13:06:38.000Z", "max_issues_repo_path": "tests/test_pardiso.cpp", "max_issues_repo_name": "pratyuksh/FEMWave", "max_issues_repo_head_hexsha": "9ed0fbe0981d712ce3e531500381589b034fb9f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_pardiso.cpp", "max_forks_repo_name": "pratyuksh/FEMWave", "max_forks_repo_head_hexsha": "9ed0fbe0981d712ce3e531500381589b034fb9f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-05T13:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T13:06:39.000Z", "avg_line_length": 30.8153846154, "max_line_length": 66, "alphanum_fraction": 0.4098851722, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481138, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.5938783532923478}}
{"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": "// Copyright (c) 2018-2021 FRC Team 3512. All Rights Reserved.\n\n#pragma once\n\n#include <Eigen/Core>\n#include <frc/controller/LinearQuadraticRegulator.h>\n#include <frc/estimator/KalmanFilter.h>\n#include <frc/logging/CSVLogFile.h>\n#include <frc/system/LinearSystem.h>\n#include <frc/system/plant/DCMotor.h>\n#include <frc/system/plant/LinearSystemId.h>\n#include <frc/trajectory/TrapezoidProfile.h>\n#include <units/length.h>\n#include <units/velocity.h>\n\n#include \"Constants.hpp\"\n\nnamespace frc3512 {\n\nclass ElevatorController {\npublic:\n    // State tolerances in meters and meters/sec respectively.\n    static constexpr double kPositionTolerance = 0.05;\n    static constexpr double kVelocityTolerance = 2.0;\n\n    ElevatorController();\n\n    ElevatorController(const ElevatorController&) = delete;\n    ElevatorController& operator=(const ElevatorController&) = delete;\n\n    void Enable();\n    void Disable();\n    bool IsEnabled() const;\n\n    void SetScoringIndex();\n    void SetClimbingIndex();\n\n    void SetGoal(double goal);\n\n    /**\n     * Sets the references.\n     *\n     * @param position Position of the carriage in meters.\n     * @param velocity Velocity of the carriage in meters per second.\n     */\n    void SetReferences(units::meter_t position,\n                       units::meters_per_second_t velocity);\n\n    bool AtReferences() const;\n\n    bool AtGoal() const;\n\n    /**\n     * Sets the current encoder measurement.\n     *\n     * @param measuredPosition Position of the carriage in meters.\n     */\n    void SetMeasuredPosition(double measuredPosition);\n\n    /**\n     * Returns the control loop calculated voltage.\n     */\n    double ControllerVoltage() const;\n\n    /**\n     * Returns the estimated position.\n     */\n    double EstimatedPosition() const;\n\n    /**\n     * Returns the estimated velocity.\n     */\n    double EstimatedVelocity() const;\n\n    /**\n     * Returns the error between the position reference and the position\n     * estimate.\n     */\n    double PositionError() const;\n\n    /**\n     * Returns the error between the velocity reference and the velocity\n     * estimate.\n     */\n    double VelocityError() const;\n\n    /**\n     * Returns the current position reference set by the profile.\n     */\n    double PositionReference();\n\n    /**\n     * Returns the current velocity reference set by the profile.\n     */\n    double VelocityReference();\n\n    /**\n     * Executes the control loop for a cycle.\n     */\n    void Update();\n\n    /**\n     * Resets any internal state.\n     */\n    void Reset();\n\nprivate:\n    // The current sensor measurement.\n    Eigen::Matrix<double, 1, 1> m_y;\n    frc::TrapezoidProfile<units::meters>::State m_goal;\n\n    frc::TrapezoidProfile<units::meters>::Constraints scoringConstraints{\n        Constants::Elevator::kMaxV, Constants::Elevator::kMaxA};\n    frc::TrapezoidProfile<units::meters>::Constraints climbingConstraints{\n        Constants::Elevator::kClimbMaxV, Constants::Elevator::kClimbMaxA};\n    frc::TrapezoidProfile<units::meters>::Constraints m_activeConstraints =\n        scoringConstraints;\n\n    frc::TrapezoidProfile<units::meters>::State m_profiledReference;\n\n    frc::LinearSystem<2, 1, 1> m_scorePlant = [=] {\n        constexpr auto motor = frc::DCMotor::NEO();\n\n        // Carriage mass\n        constexpr auto m = 9.785262_kg;\n\n        // Radius of pulley\n        constexpr auto r = 0.0181864_m;\n\n        // Gear ratio\n        constexpr double G = 8.0;\n\n        return frc::LinearSystemId::ElevatorSystem(motor, m, r, G);\n    }();\n\n    frc::LinearSystem<2, 1, 1> m_climbPlant = [=] {\n        auto motor = frc::DCMotor::NEO();\n\n        // Carriage mass\n        constexpr auto m = 8.381376_kg;\n\n        // Radius of pulley\n        constexpr auto r = 0.0181864_m;\n\n        // Gear ratio\n        constexpr double G = 12.5;\n\n        return frc::LinearSystemId::ElevatorSystem(motor, m, r, G);\n    }();\n\n    frc::LinearQuadraticRegulator<2, 1> m_scoreController{\n        m_scorePlant, {0.3, 3.0}, {12.0}, Constants::kDt};\n    frc::LinearQuadraticRegulator<2, 1> m_climbController{\n        m_climbPlant, {0.3, 3.0}, {12.0}, Constants::kDt};\n\n    frc::KalmanFilter<2, 1, 1> m_scoreObserver{\n        m_scorePlant, {0.05, 100.0}, {0.0001}, Constants::kDt};\n    frc::KalmanFilter<2, 1, 1> m_climbObserver{\n        m_climbPlant, {0.05, 100.0}, {0.0001}, Constants::kDt};\n\n    bool m_isEnabled = false;\n    bool m_climbing = false;\n\n    Eigen::Matrix<double, 2, 1> m_nextR;\n    Eigen::Matrix<double, 1, 1> m_u;\n\n    bool m_atReferences = false;\n\n    frc::CSVLogFile elevatorLogger{\"Elevator\",   \"EstPos (m)\",  \"EstVel (m/s)\",\n                                   \"RefPos (m)\", \"Voltage (V)\", \"RefVel (m/s)\"};\n};\n\n}  // namespace frc3512\n", "meta": {"hexsha": "85d07355f369135b9395f3c597e291764cb184dc", "size": 4689, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/main/include/controllers/ElevatorController.hpp", "max_stars_repo_name": "frc3512/Robot-2019", "max_stars_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-05T01:06:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T15:18:49.000Z", "max_issues_repo_path": "src/main/include/controllers/ElevatorController.hpp", "max_issues_repo_name": "frc3512/Robot-2019", "max_issues_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main/include/controllers/ElevatorController.hpp", "max_forks_repo_name": "frc3512/Robot-2019", "max_forks_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T16:21:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-14T16:21:42.000Z", "avg_line_length": 26.9482758621, "max_line_length": 80, "alphanum_fraction": 0.6427809768, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5938403523381105}}
{"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 <gtest/gtest.h>\n\n#include \"scheme/numeric/euler_angles.hh\"\n\n#include <Eigen/Geometry>\n\n#include <random>\n#include <boost/lexical_cast.hpp>\n#include <boost/format.hpp>\n\n#include \"scheme/util/Timer.hh\"\n\nnamespace scheme { namespace numeric { namespace test {\n\nusing std::cout;\nusing std::endl;\n\nTEST(euler_angles,test){\n\tusing namespace Eigen;\n\tstd::mt19937 rng((unsigned int)time(0));\n\tstd::normal_distribution<> gauss;\n\tstd::uniform_real_distribution<> uniform;\n\n\tfor(int i = 0; i < 10000; ++i){\n\t\tQuaterniond q( fabs(gauss(rng)), gauss(rng), gauss(rng), gauss(rng) );\n\t\tq.normalize();\n\t\tMatrix3d m = q.matrix();\n\t\tVector3d euler;\n\t\teuler_angles(m,euler);\n\t\t// cout << euler.transpose() << endl;\n\t\t// cout << m << endl;\n\t\t// cout << endl;\n\t\tMatrix3d m2;\n\t\tfrom_euler_angles(euler,m2);\n\t\tdouble thresh = 0.0000001;\n\t\tif( euler[2] < 0.000001 || euler[2] > M_PI-0.000001 ) thresh = 0.0002;\n\t\tif( !m2.isApprox(m,thresh) ){\n\t\t\tcout << euler << endl;\n\t\t\tcout << m << endl;\n\t\t\tcout << m2 << endl;\n\t\t}\n\t\tASSERT_TRUE( m2.isApprox(m,thresh) );\n\n\t}\n}\n\nTEST( euler_angles, performance ){\n\tusing namespace Eigen;\n\tstd::mt19937 rng((unsigned int)time(0));\n\tstd::normal_distribution<> gauss;\n\tstd::uniform_real_distribution<> uniform;\n\n\tint NSAMP = 1*1000*1000;\n\n\tstd::vector<Matrix3d> samp(NSAMP);\n\tstd::vector<Vector3d> euler(NSAMP);\n\n\tfor(int i = 0; i < NSAMP; ++i){\n\t\tQuaterniond q( fabs(gauss(rng)), gauss(rng), gauss(rng), gauss(rng) );\n\t\tq.normalize();\n\t\tMatrix3d m = q.matrix();\n\t\tsamp[i] = m;\n\t}\n\n\tutil::Timer<> t;\n\tfor(int i = 0; i < NSAMP; ++i){\n\t\teuler_angles(samp[i],euler[i]);\n\t}\n\tcout << \"rate \" << NSAMP/(double)t.elapsed() << endl;\n\n\n\n\tfor(int i = 0; i < NSAMP; ++i){\n\t\t// cout << euler.transpose() << endl;\n\t\t// cout << m << endl;\n\t\t// cout << endl;\n\t\tMatrix3d m2;\n\t\tfrom_euler_angles(euler[i],m2);\n\t\tdouble thresh = 0.0000001;\n\t\tif( euler[i][2] < 0.000001 || euler[i][2] > M_PI-0.000001 ) thresh = 0.0002;\n\t\tif( !m2.isApprox(samp[i],thresh) ){\n\t\t\tcout << euler[i] << endl;\n\t\t\tcout << samp[i] << endl;\n\t\t\tcout << m2 << endl;\n\t\t}\n\t\tASSERT_TRUE( m2.isApprox(samp[i],thresh) );\n\n\t}\n}\n\n\n\n}}}\n\n", "meta": {"hexsha": "806a63a4fa7abdba5677e3634b4e3a41f5b61be8", "size": 2101, "ext": "cc", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/numeric/euler_angles.gtest.cc", "max_stars_repo_name": "YaoYinYing/rifdock", "max_stars_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:16:08.000Z", "max_issues_repo_path": "schemelib/scheme/numeric/euler_angles.gtest.cc", "max_issues_repo_name": "YaoYinYing/rifdock", "max_issues_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-30T17:45:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:44.000Z", "max_forks_repo_path": "schemelib/scheme/numeric/euler_angles.gtest.cc", "max_forks_repo_name": "YaoYinYing/rifdock", "max_forks_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:56:17.000Z", "avg_line_length": 22.1157894737, "max_line_length": 78, "alphanum_fraction": 0.6268443598, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5936715290863728}}
{"text": "#include \"compi.hpp\"\n\n#include <complex>\n\n#include <boost/math/quadrature/tanh_sinh.hpp>\n\n#include \"integration_routines_template.hpp\"\n#include \"IntegrandFunctionWrapper.hpp\"\n\nextern \"C\" {\n    #include \"integration_routines.h\"\n}\n\nstruct TanhSinhParameters: public RoutineParametersBase {\n    Real x_min;\n    Real x_max;\n\n    TanhSinhParameters(PyObject* routine_args, PyObject* routine_kwargs){\n        constexpr auto keywords = generate_keyword_list<IntegralRange::finite>();\n\n        if(!PyArg_ParseTupleAndKeywords(routine_args,routine_kwargs,\"Odd|OO$pId\",const_cast<char**>(keywords.data()),\n                &integrand,&x_min,&x_max,\n                &args,&kw,\n                &full_output, &max_levels,&tolerance)){\n            throw could_not_parse_arguments(\"Unable to parse python arguments to C variables\");\n        }\n    }\n\n    struct result_type:public RoutineParametersBase::result_type {\n        size_t levels;\n    };\n};\n\nTanhSinhParameters::result_type run_integration_routine(const compi_internal::IntegrandFunctionWrapper& f,const TanhSinhParameters& parameters){\n    auto integrator = boost::math::quadrature::tanh_sinh<Real>(static_cast<size_t>(parameters.max_levels));\n    TanhSinhParameters::result_type result;\n\n    result.result =  integrator.integrate(f,parameters.x_min,parameters.x_max,parameters.tolerance,&(result.err),&(result.l1),&(result.levels));\n\n    return result;\n}\n\n\nextern \"C\" PyObject* tanh_sinh(PyObject* self, PyObject* args, PyObject* kwargs){\n    return integration_routine<TanhSinhParameters>(args,kwargs);\n}\n", "meta": {"hexsha": "7c7a3f1c8faa417d99dbf5db0abbd175c7c845ea", "size": 1551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/tanh_sinh.cpp", "max_stars_repo_name": "CGJackson/Compi", "max_stars_repo_head_hexsha": "9fe2a316e9dbe54b01ee274417a07a13f4f990b0", "max_stars_repo_licenses": ["MIT"], "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/tanh_sinh.cpp", "max_issues_repo_name": "CGJackson/Compi", "max_issues_repo_head_hexsha": "9fe2a316e9dbe54b01ee274417a07a13f4f990b0", "max_issues_repo_licenses": ["MIT"], "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/tanh_sinh.cpp", "max_forks_repo_name": "CGJackson/Compi", "max_forks_repo_head_hexsha": "9fe2a316e9dbe54b01ee274417a07a13f4f990b0", "max_forks_repo_licenses": ["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.0, "max_line_length": 144, "alphanum_fraction": 0.7285622179, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5936546363227142}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"spectral/macroscopic_quantities.hpp\"\n#include \"spectral/polar_to_nodal.hpp\"\n#include \"spectral/quadrature/qhermitew.hpp\"\n\nusing namespace boltzmann;\n\nTEST(spectral, mqEval)\n{\n  typedef SpectralBasisFactoryKS::basis_type basis_t;\n\n  double PI = boost::math::constants::pi<double>();\n\n  basis_t basis;\n  int K = 30;\n  SpectralBasisFactoryKS::create(basis, K);\n\n  Polar2Nodal<> p2n(basis);\n\n  MQEval mq(basis);\n\n  QHermiteW quad(1.0, K);\n\n  double o = 0.1;\n  auto f = [PI, o](double x, double y) {\n    double cx = (x - o);\n    double cy = (y - o);\n    return 1. / 2 / PI * std::exp(-cx * cx / 2 - cy * cy / 2);\n  };\n\n  Eigen::MatrixXd Nd(K, K);\n\n  for (int i = 0; i < K; ++i) {\n    double xi = quad.pts(i);\n    double wi = quad.wts(i);\n    for (int j = 0; j < K; ++j) {\n      double xj = quad.pts(j);\n      double wj = quad.wts(j);\n      Nd(i, j) = f(xi, xj) * std::sqrt(wi * wj);\n    }\n  }\n\n  Eigen::VectorXd v(basis.size());\n\n  p2n.to_polar(v, Nd);\n\n  auto evaluator = mq.evaluator();\n  evaluator(v);\n  const double tol = 1e-12;\n\n  EXPECT_TRUE(std::abs(evaluator.m - 1.0) < tol) << evaluator.m;\n  EXPECT_TRUE(std::abs(evaluator.v[0] - o) < tol) << evaluator.v[0];\n  EXPECT_TRUE(std::abs(evaluator.v[1] - o) < tol) << evaluator.v[1];\n\n  // std::cout << v << \"\\n\";\n}\n", "meta": {"hexsha": "9c68eb7776bb8f41e51b7055a3b5181ec9bb4332", "size": 1419, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gtest/gtest_mq_eval.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "test/gtest/gtest_mq_eval.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/gtest/gtest_mq_eval.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": 23.262295082, "max_line_length": 68, "alphanum_fraction": 0.613812544, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5936546338820364}}
{"text": "//  Copyright (c) 2015 Boost.Test team\r\n//  Distributed under the Boost Software License, Version 1.0.\r\n//  (See accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  See http://www.boost.org/libs/test for the library home page.\r\n\r\n//[example_code\r\n#define BOOST_TEST_MODULE tolerance_01\r\n#include <boost/test/included/unit_test.hpp>\r\nnamespace utf = boost::unit_test;\r\n\r\nBOOST_AUTO_TEST_CASE(test1, * utf::tolerance(0.00001))\r\n{\r\n  double x = 10.0000000;\r\n  double y = 10.0000001;\r\n  double z = 10.001;\r\n  BOOST_TEST(x == y); // irrelevant difference\r\n  BOOST_TEST(x == z); // relevant difference\r\n}\r\n//]", "meta": {"hexsha": "7deb3e241c0081268ff3f278de5cfbb78ab9c5ad", "size": 646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/test/doc/examples/tolerance_01.run-fail.cpp", "max_stars_repo_name": "fineshift/boost", "max_stars_repo_head_hexsha": "67469225b1d640f8d0cdcec25b099d212c6bfa41", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/test/doc/examples/tolerance_01.run-fail.cpp", "max_issues_repo_name": "fineshift/boost", "max_issues_repo_head_hexsha": "67469225b1d640f8d0cdcec25b099d212c6bfa41", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/test/doc/examples/tolerance_01.run-fail.cpp", "max_forks_repo_name": "fineshift/boost", "max_forks_repo_head_hexsha": "67469225b1d640f8d0cdcec25b099d212c6bfa41", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7619047619, "max_line_length": 66, "alphanum_fraction": 0.6965944272, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.593654629426313}}
{"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": "#include <gtest/gtest.h>\n\n#include \"scheme/numeric/bcc_lattice.hh\"\n#include \"scheme/io/dump_pdb_atom.hh\"\n#include \"scheme/util/Timer.hh\"\n#include <fstream>\n#include <random>\n#include <boost/foreach.hpp>\n#include <iterator>     // std::back_inserter\n#include <boost/format.hpp>\n#include <sparsehash/dense_hash_set>\n\n#include <Eigen/Geometry>\n\nnamespace scheme { namespace numeric { namespace test {\n\nusing std::cout;\nusing std::endl;\n\n// TEST(TEMPORARY,gm_20140905){\n// \tint NSAMP = 1000000;\n// \tstd::mt19937 r((unsigned int)time(0));\n// \tstd::uniform_real_distribution<> u;\n// \tEigen::Matrix<double,6,6> dis; dis.fill(0);\n// \tfor(int idata = 1; idata <= 6; ++idata ){\n// \t\tfor(int irep  = 1; irep <= idata; ++irep ){\n// \t\t\tint totbin = 16<<(idata-1)*2;\n// \t\t\tint nbins = std::pow( totbin, 1.0/irep );\n// \t\t\tcout << idata << \" \" << irep << \" \" << totbin << \" \" << std::pow(nbins,irep) << endl;\n// \t\t\tfor(int iter = 0; iter < NSAMP; ++iter){\n// \t\t\t\tutil::SimpleArray<6,double> samp(0.5);\n// \t\t\t\tfor(int i=0; i<idata; ++i) samp[i] = u(r);\n// \t\t\t\tutil::SimpleArray<6,double> rep(0.5);\n// \t\t\t\tfor(int i=0; i<irep; ++i){\n// \t\t\t\t\trep[i] = ((int)(samp[i]*nbins)+u(r))/nbins;\n// \t\t\t\t}\n// \t\t\t\t// cout << idata << \" \" << irep << \" \" << samp << endl;\n// \t\t\t\t// cout << idata << \" \" << irep << \" \" << rep << endl;\n// \t\t\t\t// cout << endl;\n// \t\t\t\t// std::exit(-1);\n// \t\t\t\tdis(irep-1,idata-1) += (samp-rep).norm();\n// \t\t\t}\n// \t\t}\n// \t}\n// \tdis = dis / (double)NSAMP * 100;\n// \tcout << dis << endl;\n// }\n\nTEST(bcc_lattice,centers_map){\n\ttypedef util::SimpleArray<3,double> V;\n\ttypedef util::SimpleArray<3,uint64_t> I;\n\n\t// {\n\t// \tBCC<3,double> bcc(I(2,2,2),V(0,0,0),V(1,1,1));\n\t// \tfor(int i = 0; i < bcc.size(); ++i)\n\t// \t\tcout << i << \"\\t\" << bcc[i] << endl;\n\n\t// }\n\n\tBCC<3,double> bcc(I(3,5,7),V(0,0,0),V(6,10,14));\n\n\t// std::ofstream out(\"test.pdb\");\n\tfor(size_t i = 0; i < bcc.size(); i+=2){\n\t\tASSERT_EQ( i, bcc[bcc[i]] );\n\t\t// printf(\"%6lu %10.6f %10.6f %10.6f\\n\",i,bcc[i][0],bcc[i][1],bcc[i][2]);\n\t\t// io::dump_pdb_atom(out,i,bcc[i]*3.0);\n\t\t// cout << i << \" \" << bcc[i] << endl;\n\t}\n\t// out.close();\n\n}\n\n\t// double const R3approx = 0.558099;\n\t// double const R4approx = 0.701687;\n\t// double const R5approx = 0.742306;\n\t// double const R6approx = 0.845359;\n\t// double const R7approx = 0.882879;\ntemplate<int N, class F, class S>\nF\ntest_bcc_performance(\n\tsize_t NSAMP,\n\tS const Nside,\n\tF const Width\n){\n\ttypedef util::SimpleArray<N,F> V;\n\ttypedef util::SimpleArray<N,S> I;\n\tstd::mt19937 rng((unsigned int)time(0));\n\tstd::uniform_real_distribution<> runif;\n\tBCC<N,F,S> bcc(I(Nside),V(-Width/2),V(Width/2));\n\n\tstd::vector<V> samples(NSAMP);\n\tfor(int i = 0; i < NSAMP; ++i)\n\t\tfor(int j = 0; j < N; ++j)\n\t\t\t// samples[i][j] = runif(rng)*9.4+0.3;\n\t\t\tsamples[i][j] = runif(rng)*9.0-4.5;\t\t\t\n\n\tstd::vector<size_t> indices(NSAMP);\n\tutil::Timer<> lookup_time;\n\tfor(int i = 0; i < NSAMP; ++i)\n\t\tindices[i] = bcc[samples[i]];\n\tcout << \"BCC DIM \" << N << \" lookup rate: \" << (double)NSAMP / lookup_time.elapsed() << \" sec / \";\n\n\tstd::vector<V> centers(NSAMP);\n\tutil::Timer<> getval_time;\n\tfor(int i = 0; i < NSAMP; ++i)\n\t\tcenters[i] = bcc[indices[i]];\n\tcout << \" getval rate: \" << (double)NSAMP / getval_time.elapsed() << \" sec\" << endl;\n\n\n\tF maxdiff = 0;\n\tfor(int i = 0; i < NSAMP; ++i)\n\t\tmaxdiff = std::max( maxdiff, (samples[i]-centers[i]).squaredNorm() );\n\n\tmaxdiff = sqrt(maxdiff);\n\tF frac = bcc.width_[0] * sqrt(N)/2.0 / maxdiff;\n\tF improvement = 1.0; for(int i = 0; i < N; ++i) improvement *= frac;\n\tcout << \"     improvement over cubic: \" << improvement / 2.0 << \" cov: \" << maxdiff / Width * Nside\n\t     << \" vs. \" << sqrt(N)/2.0 << endl; // 2 x num samp as cubic\n\n\treturn maxdiff;\n}\n\nTEST(bcc_lattice,performance){\n\tsize_t NITER = 50*1000;\n\t#ifdef SCHEME_BENCHMARK\n\tNITER *= 50;\n\t#endif\n\tsize_t Nside = 100;\n\tdouble Width = 10.0;\n\tdouble const R3test = test_bcc_performance<3,double,uint64_t>( NITER, Nside, Width );\n\t                      test_bcc_performance<4,double,uint64_t>( NITER, Nside, Width );\n\t                      test_bcc_performance<5,double,uint64_t>( NITER, Nside, Width );\n\t                      test_bcc_performance<6,double,uint64_t>( NITER, Nside, Width );\n\t                      test_bcc_performance<7,double,uint64_t>( NITER, Nside, Width );\n\tdouble const R3 = std::pow(2.0,-5.0/3.0)*sqrt(5) / std::pow(2.0,1.0/3.0) * Width / Nside;\n\tASSERT_LE( R3test     , R3 );\n\tASSERT_GT( R3test*1.1 , R3 );\t\n}\n\n\ntemplate<int N, class F, class S>\nF\ntest_bcc_inradius(){\n\ttypedef util::SimpleArray<N,F> V;\n\ttypedef util::SimpleArray<N,S> I;\n\tstd::mt19937 rng((unsigned int)time(0));\n\tstd::uniform_real_distribution<> runif;\n\tstd::normal_distribution<> rnorm;\t\n\tS const Nside = 5;\n\tBCC<N,F,S> bcc(I(5),V(-(F)Nside/2.0),V((F)Nside/2.0));\n\tBOOST_VERIFY( bcc[bcc[V(0.0)]] == V(0.0) );\n\tBOOST_VERIFY( bcc.width_ == V(1.0) );\n\tS const i0 = bcc[V(0)];\n\n\tdouble const RNapprox[5] = { 0.558099, 0.701687, 0.742306, 0.845359, 0.882879 };\n\tdouble const Rapprox = RNapprox[N-3];\n\n\tint NSAMP = 50*1000;\n\n\tdouble min_inrad = Rapprox;\n\tfor(int i = 0; i < NSAMP; ++i){\n\t\tV samp;\n\t\tfor(int j = 0; j < N; ++j) samp[j] = rnorm(rng);\n\t\tsamp.normalize();\n\t\tdouble const radius = runif(rng)*min_inrad*0.1 + 0.9*min_inrad;\n\t\tsamp *= radius;\n\t\tif( bcc[samp] != i0 ){\n\t\t\tmin_inrad = radius;\n\t\t}\n\n\t}\n\treturn min_inrad;\n}\n\nTEST(bcc_lattice,inradius){\n\tASSERT_NEAR( (test_bcc_inradius<3,double,uint64_t>()), 0.433015, 0.03 );\n\tASSERT_NEAR( (test_bcc_inradius<4,double,uint64_t>()), 0.500000, 0.03 );\n\tASSERT_NEAR( (test_bcc_inradius<5,double,uint64_t>()), 0.500000, 0.03 );\n\tASSERT_NEAR( (test_bcc_inradius<6,double,uint64_t>()), 0.500000, 0.03 );\n\tASSERT_NEAR( (test_bcc_inradius<7,double,uint64_t>()), 0.500000, 0.03 );\n}\n\ntemplate<int N, class F, class S> \nF \ntest_bcc_neighbors( size_t NSAMP ){\n\ttypedef util::SimpleArray<N,F> V;\n\ttypedef util::SimpleArray<N,S> I;\n\tstd::mt19937 rng((unsigned int)time(0));\n\tstd::uniform_real_distribution<> runif;\n\tstd::normal_distribution<> rnorm;\t\n\tS const Nside = 5;\n\tBCC<N,F,S> bcc(I(5),V(-(F)Nside/2.0),V((F)Nside/2.0));\n\tBOOST_VERIFY( bcc[bcc[V(0.0)]] == V(0.0) );\n\tBOOST_VERIFY( bcc.width_ == V(1.0) );\n\tS const i0 = bcc[V(0)];\n\tstd::vector<size_t> nbrs,nbrs_we;\t\t\n\tbcc.neighbors( i0, std::back_inserter(nbrs   ), false );\n\tbcc.neighbors( i0, std::back_inserter(nbrs_we), true );\t\t\n\n\tCubic<N,F,S> cubic(I(5),V(-(F)Nside/2.0),V((F)Nside/2.0));\n\tBOOST_VERIFY( cubic[cubic[V(0.0)]] == V(0.0) );\n\tBOOST_VERIFY( cubic.width_ == V(1.0) );\n\tS const i0cubic = cubic[V(0)];\n\tstd::vector<size_t> nbrs_cubic;\t\t\n\tcubic.neighbors( i0cubic, std::back_inserter(nbrs_cubic) );\n\n\t/////////////////////////////////////////////////////\n\t// test neighbor coverage\n\t///////////////////////////////////////////////////////////////\n\n\tF maxrad_99 = 0;\n\t// F const RNapprox[5] = { 0.558099, 0.701687, 0.742306, 0.845359, 0.882879 };\n\t// F const Rapprox = RNapprox[N-3];\n\tF inrad = 0.5;\n\tif(N==3) inrad = 0.433015;\n\t// F const radius = 1.9*inrad;\n\tfor(F radius = 0; radius < 3.0*inrad; radius += inrad/10.0){\n\t// F radius = 2.1*inrad; {\n\n\t\tint sum_in_nbrs=0, sum_in_nbrs_we=0;\n\t\tfor(int i = 0; i < NSAMP; ++i){\n\n\t\t\t// pick random point in i0 cell\n\t\t\tV cen; for(int j = 0; j < N; ++j) cen[j] = (runif(rng)-0.5)*2.0*inrad;\n\t\t\tif( bcc[cen] != i0 ){ --i; continue; }\n\n\t\t\tV samp;\n\t\t\tfor(int j = 0; j < N; ++j) samp[j] = rnorm(rng);\n\t\t\tsamp *= (radius/samp.norm());\n\t\t\tS index = bcc[samp+cen];\n\t\t\t// if( index == i0 ){ --i; continue; }\n\t\t\tif( std::find( nbrs_we.begin(), nbrs_we.end(), index ) != nbrs_we.end() ){\n\t\t\t\t++sum_in_nbrs_we;\n\t\t\t\tif( std::find( nbrs.begin(), nbrs.end(), index ) != nbrs.end() ){\n\t\t\t\t\t++sum_in_nbrs;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif( (F)sum_in_nbrs_we/NSAMP > 0.99 ) maxrad_99 = radius;\n\n\t\t// uncomment for print report\n\t\tif( fabs( radius - 2.0*inrad ) > 0.001 ) continue;\n\t\tint sum_in_nbrs_cubic=0;\n\t\tfor(int i = 0; i < NSAMP; ++i){\n\t\t\t// pick random point in i0 cell\n\t\t\tV cen; for(int j = 0; j < N; ++j) cen[j] = (runif(rng)-0.5);\n\t\t\tBOOST_VERIFY( cubic[cen] == i0cubic );\n\n\t\t\tV samp;\n\t\t\tfor(int j = 0; j < N; ++j) samp[j] = rnorm(rng);\n\t\t\tsamp *= (radius/inrad*0.5/samp.norm());\n\t\t\tS index = cubic[samp+cen];\n\t\t\t// if( index == i0 ){ --i; continue; }\n\t\t\tif( std::find( nbrs_cubic.begin(), nbrs_cubic.end(), index ) != nbrs_cubic.end() ){\n\t\t\t\t++sum_in_nbrs_cubic;\n\t\t\t}\n\t\t}\n\t\tprintf(\"%i %7.3f %9.7f %9.7f %9.7f\\n\",\n\t\t\tN,\n\t\t\tradius/inrad,\n\t\t\t(F)sum_in_nbrs/NSAMP,\n\t\t\t(F)sum_in_nbrs_we/NSAMP,\n\t\t\t(F)sum_in_nbrs_cubic/NSAMP\t\t\t\n\t\t);\n\n\t}\n\n\t// ///////////////////////////////////////////////////////////////////\n\t// // // dump neighbors\n\t// //////////////////////////////////////////////////////////////////\n\t// if(N != 3) return;\n\t// #define LAT bcc\n\t// std::ofstream out_bcc(\"bcc.pdb\");\n\t// for(int i = 0; i < LAT.size(); ++i) io::dump_pdb_atom(out_bcc,i,LAT[i]*10.0);\n\t// out_bcc.close();\n\t// for(int i = 0; i < LAT.size(); ++i){\n\t// \tstd::vector<size_t> nbrs;\n\t// \tLAT.neighbors( i, std::back_inserter(nbrs), true );\n\t// \t// BOOST_FOREACH(size_t nbr, nbrs) cout << nbr << \" \" << LAT[nbr] << endl;\n\t// \tstd::string s = boost::str(boost::format(\"%4i\") % i);\n\t// \tstd::ofstream out(\"test_\"+s+\".pdb\");\n\t// \tBOOST_FOREACH(size_t nbr, nbrs) io::dump_pdb_atom(out,nbr,LAT[nbr]*10.0);\n\t// \tout.close();\n\t// }\n\n\treturn maxrad_99;\n}\n\nTEST(bcc_lattice,neighbors){\n\tsize_t NITER = 1000;\n\t#ifdef SCHEME_BENCHMARK\n\tNITER *= 50;\n\t#endif\n\t// for(int i = 3; i < 8; ++i){\n\t// \tint nc = std::pow(3,i);\n\t// \tint nbccFC = 1+2*i+std::pow(2,i);\n\t// \tint nbccFCE = nbccFC + i*(i-1)/2 * 4;\n\t// \tcout << \"Nnbrs: \" << i <<\" cubic \"<< nc << \" bccFC \" << nbccFC << \" bccFCE \" << nbccFCE << endl;\n\t// }\n\t// Nnbrs: 3 cubic   27 bccFC  15 bccFCE  27\n\t// Nnbrs: 4 cubic   81 bccFC  25 bccFCE  49\n\t// Nnbrs: 5 cubic  243 bccFC  43 bccFCE  83\n\t// Nnbrs: 6 cubic  729 bccFC  77 bccFCE 137\n\t// Nnbrs: 7 cubic 2187 bccFC 143 bccFCE 227\n\tdouble v1 = test_bcc_neighbors<3,double,uint64_t>(NITER);\n\tdouble v2 = test_bcc_neighbors<4,double,uint64_t>(NITER);\n\tdouble v3 = test_bcc_neighbors<5,double,uint64_t>(NITER);\n\tdouble v4 = test_bcc_neighbors<6,double,uint64_t>(NITER);\n\tdouble v5 = test_bcc_neighbors<7,double,uint64_t>(NITER);\n\tEXPECT_LE( 0.73, v1 ); // these are total approximations\n\tEXPECT_LE( 0.69, v2 ); // these are total approximations\n\tEXPECT_LE( 0.64, v3 ); // these are total approximations\n\tEXPECT_LE( 0.57, v4 ); // these are total approximations\n\tEXPECT_LE( 0.51, v5 ); // these are total approximations\n\t// cout << test_bcc_neighbors<3,double,size_t>(1000000) << endl; // 0.779427\n\t// cout << test_bcc_neighbors<4,double,size_t>(1000000) << endl; // 0.75\n\t// cout << test_bcc_neighbors<5,double,size_t>(1000000) << endl; // 0.7\n\t// cout << test_bcc_neighbors<6,double,size_t>(1000000) << endl; // 0.65\n\t// cout << test_bcc_neighbors<7,double,size_t>(1000000) << endl; // 0.6\n}\n\n// TEST(bcc_lattice,coverage_transform_7d){\n// \tusing namespace Eigen;\n// \ttypedef Transform<double,3,AffineCompact> Xform;\n// \ttypedef util::SimpleArray<7,double> V;\n// \ttypedef util::SimpleArray<7,size_t> I;\n// \ttypedef Matrix<double,7,1> Vector7d;\n// \tstd::mt19937 mt((unsigned int)time(0));\n// \tstd::normal_distribution<> rnorm;\n// \tsize_t Nside = 64;\n// \tV bounds = V(1.5,1.5,1.5,1.5,10,10,10);\n// \tBCC<7,double> bcc(I(Nside),-bounds,bounds);\n\n// \tMatrix<double,3,6> pts0;\n// \tpts0 <<  1, 0, 0,-2, 0, 0,\n// \t         0, 1, 0, 0,-1, 0,\n// \t         0, 0, 1, 0, 0,-1;\n// \tpts0.colwise() -= pts0.rowwise().sum()/pts0.cols();\n\n// \tXform X( AngleAxisd(2,Vector3d(1,2,3)) );\n\n// \t// cout << pts0 << endl;\n// \t// cout << X*pts0 << endl;\n\n// \tint const NSAMP = 3;\n// \tfor(int i = 0; i < NSAMP; ++i){\n// \t\tVector4d quat( rnorm(mt), rnorm(mt), rnorm(mt), rnorm(mt) ); quat.normalize();\n// \t\tVector3d trans( rnorm(mt), rnorm(mt), rnorm(mt) );\n// \t\tVector7d samp;\n// \t\tsamp.block(0,0,4,1) = quat;\n// \t\tsamp.block(4,0,3,1) = trans;\n// \t\t// cout << samp.transpose() << endl;\n// \t\tV tmp = bcc[ bcc[ samp ] ];\n// \t\tVector7d cen;\n// \t\tfor(int i = 0; i < 7; ++i) cen[i] = tmp[i];\n\n// \t\tcout << samp.transpose() << endl;\n// \t\tcout << cen.transpose() << endl;\n// \t\tcout << endl;\n\n// // \tstd::vector<size_t> indices(NSAMP);\n// // \tutil::Timer<> lookup_time;\n// // \tfor(int i = 0; i < NSAMP; ++i)\n// // \t\tindices[i] = bcc[samples[i]];\n// // \tcout << N << \" lookup: \" << (double)NSAMP / lookup_time.elapsed() << \" sec\" << endl;\n\n// // \tstd::vector<V> centers(NSAMP);\n// // \tutil::Timer<> getval_time;\n// // \tfor(int i = 0; i < NSAMP; ++i)\n// // \t\tcenters[i] = bcc[indices[i]];\n\n// \t}\n\n\n// }\n\n\n\ntemplate<int N, class F, class S> \nF \ntest_bcc_children( size_t NSAMP ){\n\ttypedef util::SimpleArray<N,F> V;\n\ttypedef util::SimpleArray<N,S> I;\n\tstd::mt19937 rng((unsigned int)time(0));\n\tstd::uniform_real_distribution<> runif;\n\tstd::normal_distribution<> rnorm;\t\n\tS const Nside = 5;\n\tBCC<N,F,S> bcc_parent(I(5),V(-(F)Nside),V((F)Nside));\n\tBCC<N,F,S> bcc(I(5),V(-(F)Nside/2.0),V((F)Nside/2.0));\n\tBOOST_VERIFY( bcc[bcc[V(0.0)]] == V(0.0) );\n\tBOOST_VERIFY( bcc.width_ == V(1.0) );\n\tS const i0 = bcc[V(0)];\n\tstd::vector<size_t> nbrs,nbrs_we;\t\t\n\tbcc.neighbors( i0, std::back_inserter(nbrs   ), false );\n\tbcc.neighbors( i0, std::back_inserter(nbrs_we), true );\t\t\n\n\t/////////////////////////////////////////////////////\n\t// test neighbor coverage\n\t///////////////////////////////////////////////////////////////\n\n\t// F const RNapprox[5] = { 0.558099, 0.701687, 0.742306, 0.845359, 0.882879 };\n\t// F const Rapprox = RNapprox[N-3];\n\tF inrad = 0.5;\n\tif(N==3) inrad = 0.433015;\n\n\tint sum_in_nbrs=0, sum_in_nbrs_we=0;\n\tfor(int i = 0; i < NSAMP; ++i){\n\n\t\t// pick random point in i0 parent cell\n\t\tV samp; for(int j = 0; j < N; ++j)\n\t\t\tsamp[j] = (runif(rng)-0.5)*4.0*inrad;\n\t\tif( bcc_parent[samp] != i0 ){ --i; continue; }\n\n\t\tS index = bcc[samp];\n\t\t// if( index == i0 ){ --i; continue; }\n\t\tif( std::find( nbrs_we.begin(), nbrs_we.end(), index ) != nbrs_we.end() ){\n\t\t\t++sum_in_nbrs_we;\n\t\t\tif( std::find( nbrs.begin(), nbrs.end(), index ) != nbrs.end() ){\n\t\t\t\t++sum_in_nbrs;\n\t\t\t}\n\t\t}\n\t}\n\n\t//int nc = std::pow(3,N);\n\tint nbccFC = 1+2*N+std::pow(2,N);\n\tint nbccFCE = nbccFC + N*(N-1)/2 * 4;\n\tprintf(\"BCC child coverage: %i %3i %9.7f   %3i %9.7f\\n\",\n\t\tN, \n\t\tnbccFC, (F)sum_in_nbrs/NSAMP,\n\t\tnbccFCE, (F)sum_in_nbrs_we/NSAMP\n\t);\n\treturn 0;\n}\n\nTEST(bcc_lattice,children){\n\tint NITER = 5*1000;\n\t#ifdef SCHEME_BENCHMARK\n\tNITER *= 30;\n\t#endif\n\n\tcout << \"BCC               DIM Nfc   frac_fc  Nfce  frac_fce\" << std::endl;\n\ttest_bcc_children<3,double,uint64_t>( NITER );\n\ttest_bcc_children<4,double,uint64_t>( NITER );\n\ttest_bcc_children<5,double,uint64_t>( NITER );\n\ttest_bcc_children<6,double,uint64_t>( NITER );\n\ttest_bcc_children<7,double,uint64_t>( NITER );\n}\n\n\n}}}\n\n", "meta": {"hexsha": "8325a9383972c50f49f6802bef8863259bd945c7", "size": 14569, "ext": "cc", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/numeric/bcc_lattice.gtest.cc", "max_stars_repo_name": "YaoYinYing/rifdock", "max_stars_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:16:08.000Z", "max_issues_repo_path": "schemelib/scheme/numeric/bcc_lattice.gtest.cc", "max_issues_repo_name": "YaoYinYing/rifdock", "max_issues_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-30T17:45:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:44.000Z", "max_forks_repo_path": "schemelib/scheme/numeric/bcc_lattice.gtest.cc", "max_forks_repo_name": "YaoYinYing/rifdock", "max_forks_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:56:17.000Z", "avg_line_length": 32.232300885, "max_line_length": 101, "alphanum_fraction": 0.5845974329, "num_tokens": 5396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.5935206076856465}}
{"text": "// Copyright \u00a9 2016-2021 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n\n#pragma once\n\n#include <Eigen/Dense>\n\nnamespace vinecopulib {\n\nnamespace tools_interpolation {\n//! A class for cubic spline interpolation of bivariate copulas\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{\npublic:\n  InterpolationGrid() {}\n\n  InterpolationGrid(const Eigen::VectorXd& grid_points,\n                    const Eigen::MatrixXd& values,\n                    int norm_times = 3);\n\n  Eigen::MatrixXd get_values() const;\n\n  void set_values(const Eigen::MatrixXd& values, int norm_times = 3);\n\n  void flip();\n\n  void normalize_margins(int times);\n\n  Eigen::VectorXd interpolate(const Eigen::MatrixXd& x);\n\n  Eigen::VectorXd integrate_1d(const Eigen::MatrixXd& u, size_t cond_var);\n\n  Eigen::VectorXd integrate_2d(const Eigen::MatrixXd& u);\n\nprivate:\n  Eigen::Matrix<ptrdiff_t, 1, 2> get_indices(double x0, double x1);\n  double bilinear_interpolation(double z11,\n                                double z12,\n                                double z21,\n                                double z22,\n                                double x1,\n                                double x2,\n                                double y1,\n                                double y2,\n                                double x,\n                                double y);\n  double int_on_grid(const double& upr,\n                     const Eigen::VectorXd& vals,\n                     const Eigen::VectorXd& grid);\n\n  Eigen::VectorXd grid_points_;\n  Eigen::MatrixXd values_;\n};\n}\n}\n\n#include <vinecopulib/misc/implementation/tools_interpolation.ipp>\n", "meta": {"hexsha": "21d472b09415452b20574a4bbac0a3946388b545", "size": 1946, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/vinecopulib/misc/tools_interpolation.hpp", "max_stars_repo_name": "tvatter/vinecoplib", "max_stars_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-05-05T13:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T23:40:01.000Z", "max_issues_repo_path": "include/vinecopulib/misc/tools_interpolation.hpp", "max_issues_repo_name": "vinecopulib/vinecopulib", "max_issues_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 264.0, "max_issues_repo_issues_event_min_datetime": "2017-03-28T10:07:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T10:04:39.000Z", "max_forks_repo_path": "include/vinecopulib/misc/tools_interpolation.hpp", "max_forks_repo_name": "tvatter/vinecoplib", "max_forks_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-04-24T13:54:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T16:56:17.000Z", "avg_line_length": 30.40625, "max_line_length": 79, "alphanum_fraction": 0.6135662898, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5935206034018101}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <scorum/utils/fraction.hpp>\n\n#include <scorum/protocol/asset.hpp>\n\n#include \"defines.hpp\"\n\n#include <limits>\n\nnamespace fraction_tests {\nusing namespace scorum;\nusing namespace scorum::protocol;\n\nBOOST_AUTO_TEST_SUITE(fraction_tests)\n\nBOOST_AUTO_TEST_CASE(fraction_creation_check)\n{\n    BOOST_CHECK_THROW(utils::make_fraction(ASSET_SP(10).amount, 0);, fc::assert_exception);\n\n    {\n        auto f = utils::make_fraction(1, 2);\n        BOOST_CHECK_EQUAL(f.numerator, 1);\n        BOOST_CHECK_EQUAL(f.denominator, 2);\n    }\n    {\n        auto f = utils::make_fraction(ASSET_SP(10).amount, 2);\n        BOOST_CHECK_EQUAL(f.numerator, 10);\n        BOOST_CHECK_EQUAL(f.denominator, 2);\n    }\n    {\n        auto f = utils::make_fraction(1, ASSET_SP(10).amount);\n        BOOST_CHECK_EQUAL(f.numerator, 1);\n        BOOST_CHECK_EQUAL(f.denominator, 10);\n    }\n    {\n        auto f = utils::make_fraction(ASSET_SP(10).amount, ASSET_SCR(20).amount);\n        BOOST_CHECK_EQUAL(f.numerator, 10);\n        BOOST_CHECK_EQUAL(f.denominator, 20);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(multiply_by_fractional_negative_check)\n{\n    // negative value\n    BOOST_CHECK_THROW(utils::multiply_by_fractional(-10, 1, 2), fc::assert_exception);\n    BOOST_CHECK_THROW(utils::multiply_by_fractional(10, -1, 2), fc::assert_exception);\n    BOOST_CHECK_THROW(utils::multiply_by_fractional(10, 1, -2), fc::assert_exception);\n    BOOST_CHECK_THROW(utils::multiply_by_fractional(-10, -1, -2), fc::assert_exception);\n    // zero denominator\n    BOOST_CHECK_THROW(utils::multiply_by_fractional(10, 1, 0), fc::assert_exception);\n}\n\nBOOST_AUTO_TEST_CASE(multiply_by_fractional_positive_check)\n{\n    // claculate half off int32 max\n    BOOST_CHECK_EQUAL(utils::multiply_by_fractional(std::numeric_limits<int32_t>::max(), 50, 100),\n                      std::numeric_limits<int32_t>::max() / 2);\n\n    // claculate half off int64 max\n    BOOST_CHECK_EQUAL(utils::multiply_by_fractional(std::numeric_limits<int64_t>::max(), 50, 100),\n                      std::numeric_limits<int64_t>::max() / 2);\n\n    // claculate half off asset_symbol_type max\n    BOOST_CHECK_EQUAL(utils::multiply_by_fractional(std::numeric_limits<asset_symbol_type>::max(), 50, 100),\n                      std::numeric_limits<asset_symbol_type>::max() / 2);\n}\n\nBOOST_AUTO_TEST_CASE(asset_with_fractional_operations_check)\n{\n    // calculate 20 % of 100 SP\n    {\n        auto value = ASSET_SP(100e+9);\n        value *= utils::make_fraction(20, 100);\n        BOOST_CHECK_EQUAL(value, ASSET_SP(20e+9));\n    }\n\n    // calculate 20 % of 100 SP\n    {\n        auto value = ASSET_SP(100e+9) * utils::make_fraction(20, 100);\n        BOOST_CHECK_EQUAL(value, ASSET_SP(20e+9));\n    }\n\n    // calculate 20 % of maximum SP\n    {\n        auto value = asset::maximum(SP_SYMBOL) * utils::make_fraction(20, 100);\n        BOOST_CHECK_EQUAL(value, asset::maximum(SP_SYMBOL) / 5);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(fraction_simplify_check)\n{\n    BOOST_CHECK(utils::make_fraction(20'000, 100'000).simplify() == utils::make_fraction(1, 5));\n\n    BOOST_CHECK(utils::make_fraction(8, 12).simplify() == utils::make_fraction(2, 3));\n    BOOST_CHECK(utils::make_fraction(-8, 12).simplify() == utils::make_fraction(-2, 3));\n    BOOST_CHECK(utils::make_fraction(8, -12).simplify() == utils::make_fraction(2, -3));\n    BOOST_CHECK(utils::make_fraction(-8, -12).simplify() == utils::make_fraction(-2, -3));\n\n    BOOST_CHECK(utils::make_fraction(2, 3).simplify() == utils::make_fraction(2, 3));\n    BOOST_CHECK(utils::make_fraction(-2, 3).simplify() == utils::make_fraction(-2, 3));\n    BOOST_CHECK(utils::make_fraction(2, -3).simplify() == utils::make_fraction(2, -3));\n    BOOST_CHECK(utils::make_fraction(-2, -3).simplify() == utils::make_fraction(-2, -3));\n}\n\nBOOST_AUTO_TEST_CASE(fraction_invert_check)\n{\n    BOOST_CHECK(utils::make_fraction(2, 3).invert() == utils::make_fraction(1, 3));\n\n    BOOST_CHECK(utils::make_fraction(12, 20).invert() == utils::make_fraction(8, 20));\n\n    BOOST_CHECK(utils::make_fraction(-2, 20).invert() == utils::make_fraction(22, 20));\n\n    BOOST_CHECK(utils::make_fraction(-12, -20).invert() == utils::make_fraction(8, 20));\n}\n\nBOOST_AUTO_TEST_CASE(fraction_coup_check)\n{\n    BOOST_CHECK(utils::make_fraction(2, 3).coup() == utils::make_fraction(3, 2));\n\n    BOOST_CHECK_THROW(utils::make_fraction(0, 2).coup(), fc::assert_exception);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n}\n", "meta": {"hexsha": "1fdc6676a337eff2b2732fd7e453bad344584e5d", "size": 4432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/utests/fraction_tests.cpp", "max_stars_repo_name": "scorum/scorum", "max_stars_repo_head_hexsha": "1da00651f2fa14bcf8292da34e1cbee06250ae78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-10-28T22:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T02:20:48.000Z", "max_issues_repo_path": "tests/utests/fraction_tests.cpp", "max_issues_repo_name": "Scorum/Scorum", "max_issues_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2017-11-25T09:06:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T09:17:22.000Z", "max_forks_repo_path": "tests/utests/fraction_tests.cpp", "max_forks_repo_name": "Scorum/Scorum", "max_forks_repo_head_hexsha": "fb4aa0b0960119b97828865d7a5b4d0409af7876", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T19:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T10:50:42.000Z", "avg_line_length": 35.1746031746, "max_line_length": 108, "alphanum_fraction": 0.6856949458, "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.59352060178924}}
{"text": "#include <Eigen/Core>\n#include <ceres/ceres.h>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n\n#include <ceres-error-terms/parameterization/pose-param-jpl.h>\n#include <ceres-error-terms/position-error-term.h>\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\nclass PosegraphErrorTerms : public ::testing::Test {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n protected:\n  virtual void SetUp() {\n    prior_position_ << 1, 2, 3;\n    prior_orientation_.coeffs() << sqrt(2) / 2, 0, 0, sqrt(2) / 2;\n\n    current_pose_ << prior_orientation_.coeffs(), prior_position_;\n\n    covariance_matrix_.setIdentity();\n  }\n\n  void addResidual();\n  void solve();\n\n  ceres::Problem problem_;\n  ceres::Solver::Summary summary_;\n\n  Eigen::Vector3d prior_position_;\n  Eigen::Quaterniond prior_orientation_;\n\n  Eigen::Matrix<double, 7, 1> current_pose_;\n  Eigen::Matrix<double, 3, 3> covariance_matrix_;\n};\n\nvoid PosegraphErrorTerms::addResidual() {\n  ceres::CostFunction* cost_function = new ceres_error_terms::PositionErrorTerm(\n      prior_position_, covariance_matrix_);\n\n  problem_.AddResidualBlock(cost_function, NULL, current_pose_.data());\n  ceres::LocalParameterization* pose_parameterization =\n      new ceres_error_terms::JplPoseParameterization;\n  problem_.SetParameterization(current_pose_.data(), pose_parameterization);\n}\n\nvoid PosegraphErrorTerms::solve() {\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_SCHUR;\n  options.minimizer_progress_to_stdout = false;\n  options.parameter_tolerance = 1e-20;\n  options.gradient_tolerance = 1e-20;\n  options.function_tolerance = 1e-20;\n  options.max_num_iterations = 1e3;\n  ceres::Solve(options, &problem_, &summary_);\n\n  LOG(INFO) << summary_.BriefReport() << std::endl;\n  LOG(INFO) << summary_.message << std::endl;\n}\n\nTEST_F(PosegraphErrorTerms, TestPositionPriorErrorTermZeroCost) {\n  addResidual();\n  solve();\n\n  EXPECT_EQ(summary_.initial_cost, 0.0);\n  EXPECT_EQ(summary_.final_cost, 0.0);\n  EXPECT_EQ(summary_.iterations.size(), 1u);\n}\n\nTEST_F(PosegraphErrorTerms, TestPositionPriorErrorTermPositionOptimization) {\n  current_pose_.tail(3) << 4, 7, 4;\n  addResidual();\n  solve();\n\n  EXPECT_NEAR_EIGEN(current_pose_.tail(3), prior_position_, 1e-10);\n  EXPECT_LT(summary_.final_cost, 1e-10);\n}\n\nTEST_F(PosegraphErrorTerms, TestPositionPriorErrorTermPositionOptimization2) {\n  current_pose_.tail(3) << 2.484e8, -1.264e9, -8.4567e24;\n  addResidual();\n  solve();\n\n  EXPECT_NEAR_EIGEN(current_pose_.tail(3), prior_position_, 1e-10);\n  EXPECT_LT(summary_.final_cost, 1e-10);\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "4fec4d9c4db2d321e5a1c87fcb3824ad9d7828ae", "size": 2621, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/ceres-error-terms/test/test_position_error_term.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "algorithms/ceres-error-terms/test/test_position_error_term.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "algorithms/ceres-error-terms/test/test_position_error_term.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": 29.1222222222, "max_line_length": 80, "alphanum_fraction": 0.7535291873, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5935205908027122}}
{"text": "#define BOOST_TEST_MODULE \"test_vector\"\n\n#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST\n#include <boost/test/unit_test.hpp>\n#else\n#define BOOST_TEST_NO_LIB\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mill/math/Vector.hpp>\n\n#include <random>\nconstexpr static unsigned int seed = 32479327;\nconstexpr static std::size_t N = 10000;\n\nBOOST_AUTO_TEST_CASE(add_vector_3d)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(-1.0, 1.0);\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const mill::Vector<double, 3> lhs(uni(mt), uni(mt), uni(mt));\n        const mill::Vector<double, 3> rhs(uni(mt), uni(mt), uni(mt));\n\n        mill::Vector<double, 3> vec = lhs + rhs;\n        BOOST_CHECK_EQUAL(vec[0], lhs[0] + rhs[0]);\n        BOOST_CHECK_EQUAL(vec[1], lhs[1] + rhs[1]);\n        BOOST_CHECK_EQUAL(vec[2], lhs[2] + rhs[2]);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(sub_vector_3d)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(-1.0, 1.0);\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const mill::Vector<double, 3> lhs(uni(mt), uni(mt), uni(mt));\n        const mill::Vector<double, 3> rhs(uni(mt), uni(mt), uni(mt));\n\n        mill::Vector<double, 3> vec = lhs - rhs;\n        BOOST_CHECK_EQUAL(vec[0], lhs[0] - rhs[0]);\n        BOOST_CHECK_EQUAL(vec[1], lhs[1] - rhs[1]);\n        BOOST_CHECK_EQUAL(vec[2], lhs[2] - rhs[2]);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(mul_vector_3d)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(-1.0, 1.0);\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const mill::Vector<double, 3> lhs(uni(mt), uni(mt), uni(mt));\n        const double scl = uni(mt);\n\n        mill::Vector<double, 3> vec = lhs * scl;\n        BOOST_CHECK_EQUAL(vec[0], lhs[0] * scl);\n        BOOST_CHECK_EQUAL(vec[1], lhs[1] * scl);\n        BOOST_CHECK_EQUAL(vec[2], lhs[2] * scl);\n    }\n}\n", "meta": {"hexsha": "fdc7b072d8ac7e302a40225c6d79a6b50d5cb6e9", "size": 1938, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math/test_vector.cpp", "max_stars_repo_name": "ToruNiina/Coffee-mill", "max_stars_repo_head_hexsha": "343a6b89f7bc4645d596809aac9009db1c5ec0d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-12-11T07:26:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T07:33:37.000Z", "max_issues_repo_path": "tests/math/test_vector.cpp", "max_issues_repo_name": "ToruNiina/Coffee-mill", "max_issues_repo_head_hexsha": "343a6b89f7bc4645d596809aac9009db1c5ec0d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/math/test_vector.cpp", "max_forks_repo_name": "ToruNiina/Coffee-mill", "max_forks_repo_head_hexsha": "343a6b89f7bc4645d596809aac9009db1c5ec0d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7619047619, "max_line_length": 69, "alphanum_fraction": 0.6341589267, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.593499992671432}}
{"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": "/*\n * Advent of Code 2016\n * Day 3 (part 1)\n *\n * Command: clang++ --std=c++14 -I/usr/local/include -L/usr/local/lib day03a.cpp\n *\n */\n\n#include <cmath>\n#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <boost/foreach.hpp>\n#include <boost/tokenizer.hpp>\n\nconst int MAX_LINE_LENGTH = 2000;\n\nclass Triangle {\n\tpublic:\n\t\tTriangle(int, int, int);\n\t\tTriangle(std::string, std::string, std::string);\n\t\tint a;\n\t\tint b;\n\t\tint c;\n\t\tbool valid();\n};\n\nTriangle::Triangle(int a, int b, int c) {\n\tthis->a = a;\n\tthis->b = b;\n\tthis->c = c;\n}\n\nTriangle::Triangle(std::string a, std::string b, std::string c) {\n\tthis->a = atoi(a.c_str());\n\tthis->b = atoi(b.c_str());\n\tthis->c = atoi(c.c_str());\n}\n\nbool Triangle::valid() {\n\treturn ((this->a + this->b > this->c) && (this->a + this->c > this->b) && (this->b + this->c > this->a));\n}\n\nvoid split(const std::string &s, char delim, std::vector<std::string> &elems) {\n\tstd::stringstream ss;\n\tss.str(s);\n\tstd::string item;\n\twhile (std::getline(ss, item, delim)) {\n\t\telems.push_back(item);\n\t}\n}\n\nstd::vector<std::string> split(const std::string &s, char delim) {\n\tstd::vector<std::string> elems;\n\tsplit(s, delim, elems);\n\treturn elems;\n}\n\nint main(void) {\n\t// Open the input file\n\tstd::ifstream fin(\"input03.txt\");\n\tif (!fin) {\n\t\tstd::cerr << \"Error reading input file input03.txt\" << std::endl;\n\t\treturn -1;\n\t}\n\n\tstd::vector<Triangle> candidates;\n\n\t// Read the input\n\tstd::vector<std::string> input;\n\tchar cInput[MAX_LINE_LENGTH];\n\twhile (fin.getline(cInput, MAX_LINE_LENGTH)) {\n\t\tusing namespace std;\n\t\tusing namespace boost;\n\n\t\tvector<string> bits;\n\t\tstring input(cInput);\n\t\ttokenizer<> tokenizer(input);\n\n\t\tfor (auto token : tokenizer) {\n\t\t\tbits.push_back(token);\n\t\t}\n\n\t\tTriangle t(bits.at(0), bits.at(1), bits.at(2));\n\t\tcandidates.push_back(t);\n\t}\n\tfin.close();\n\n\t// Solve the problem\n\tint triangles = 0; int other = 0;\n\tfor (auto t : candidates) {\n\t\tif (t.valid()) {\n\t\t\ttriangles++;\n\t\t} else {\n\t\t\tother++;\n\t\t}\n\t}\n\n\tstd::cout << \"Triangles: \" << triangles << std::endl << \"Non-triangles: \" << other << std::endl;\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "911d6a7516c48a634d44181848be3a4b26c0bd1c", "size": 2150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "advent2016/day03a.cpp", "max_stars_repo_name": "rnelson/adventofcode", "max_stars_repo_head_hexsha": "d15a360f7e3e6f306bede3f1c4252be4088b8cc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-12-03T13:20:10.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-03T13:20:10.000Z", "max_issues_repo_path": "advent2016/day03a.cpp", "max_issues_repo_name": "rnelson/adventofcode", "max_issues_repo_head_hexsha": "d15a360f7e3e6f306bede3f1c4252be4088b8cc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-13T11:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-13T11:59:33.000Z", "max_forks_repo_path": "advent2016/day03a.cpp", "max_forks_repo_name": "rnelson/adventofcode", "max_forks_repo_head_hexsha": "d15a360f7e3e6f306bede3f1c4252be4088b8cc7", "max_forks_repo_licenses": ["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.9074074074, "max_line_length": 106, "alphanum_fraction": 0.6306976744, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5934692408480476}}
{"text": "/*\n * Copyright 2014-2019, CNRS\n * Copyright 2018-2019, INRIA\n */\n\n#ifndef __eigenpy_geometry_conversion_hpp__\n#define __eigenpy_geometry_conversion_hpp__\n\n#include \"eigenpy/fwd.hpp\"\n#include <Eigen/Geometry>\n\nnamespace eigenpy\n{\n  \n  namespace bp = boost::python;\n \n  template<typename Scalar,int Options=0>\n  struct EulerAnglesConvertor\n  {\n    \n    typedef typename Eigen::Matrix<Scalar,3,1,Options> Vector3;\n    typedef typename Eigen::Matrix<Scalar,3,3,Options> Matrix3;\n    typedef typename Vector3::Index Index;\n    \n    typedef typename Eigen::AngleAxis<Scalar> AngleAxis;\n    \n    static void expose()\n    {\n      bp::def(\"toEulerAngles\",&EulerAnglesConvertor::toEulerAngles,\n              bp::args(\"mat (dim 3x3)\",\"a0\",\"a1\",\"a2\"),\n              \"It returns the Euler-angles of the rotation matrix mat using the convention defined by the triplet (a0,a1,a2).\");\n      \n      bp::def(\"fromEulerAngles\",&EulerAnglesConvertor::fromEulerAngles,\n              bp::args(\"ea (vector of Euler angles)\",\"a0\",\"a1\",\"a2\"),\n              \"It returns the rotation matrix associated to the Euler angles using the convention defined by the triplet (a0,a1,a2).\");\n    }\n    \n    static Vector3 toEulerAngles(const Matrix3 & mat,\n                                 Index a0,\n                                 Index a1,\n                                 Index a2)\n    {\n      return mat.eulerAngles(a0,a1,a2);\n    }\n    \n    static Matrix3 fromEulerAngles(const Vector3 & ea,\n                                   Index a0,\n                                   Index a1,\n                                   Index a2)\n    {\n      Matrix3 mat;\n      mat = AngleAxis(ea[0], Vector3::Unit(a0))\n      * AngleAxis(ea[1], Vector3::Unit(a1))\n      * AngleAxis(ea[2], Vector3::Unit(a2));\n      return mat;\n    }\n  };\n  \n  \n} // namespace eigenpy\n\n#endif // define __eigenpy_geometry_conversion_hpp__\n", "meta": {"hexsha": "de6f79882586f4bc6ffcbe0a80e0e7e68cebd21d", "size": 1870, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/eigenpy/geometry-conversion.hpp", "max_stars_repo_name": "cmastalli/eigenpy", "max_stars_repo_head_hexsha": "aef2a9aa3be42d85275fbe654eb621e289b02017", "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/eigenpy/geometry-conversion.hpp", "max_issues_repo_name": "cmastalli/eigenpy", "max_issues_repo_head_hexsha": "aef2a9aa3be42d85275fbe654eb621e289b02017", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/eigenpy/geometry-conversion.hpp", "max_forks_repo_name": "cmastalli/eigenpy", "max_forks_repo_head_hexsha": "aef2a9aa3be42d85275fbe654eb621e289b02017", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6825396825, "max_line_length": 135, "alphanum_fraction": 0.5898395722, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5934692291382369}}
{"text": "#pragma once\n#include \"IntegerInterval.hpp\"\n#include \"Misc.hpp\"\n#include \"VectorHelpers.hpp\"\n#include \"detail/MultisetsDetail.hpp\"\n#include <boost/iterator/iterator_facade.hpp>\n\nnamespace discreture\n{\n\n/**\n *@brief Multisets is a container to iterate over all subsets of a multiset.\n *\n *For example, let's suppose you have the multiset {0,0,0,1,1,2,2,2,2,3,3,5}.\n *First, we encode this as [3,2,4,2,0,1], meaning we take three 0's, two 1's,\n *etc. Then, the set of submultisets of this can be encoded as lists of length 6\n *where the first element is less than 3, the second less than 2, the third less\n *than 4, and so on. So for example, [1,0,0,2,0,1], representing {0,3,3,5}, is\n *in multisets([3,2,4,2,0,1])\n *\n *# Example usage:\n *\n *\tmultisets X({1,0,3,1});\n *\tfor (auto&& x : X)\n *\t\tstd::cout << x << \" \";\n *\n *Prints out:\n *\n *\t[ 0 0 0 0 ]\n *\t[ 1 0 0 0 ]\n *\t[ 0 0 1 0 ]\n *\t[ 1 0 1 0 ]\n *\t[ 0 0 2 0 ]\n *\t[ 1 0 2 0 ]\n *\t[ 0 0 3 0 ]\n *\t[ 1 0 3 0 ]\n *\t[ 0 0 0 1 ]\n *\t[ 1 0 0 1 ]\n *\t[ 0 0 1 1 ]\n *\t[ 1 0 1 1 ]\n *\t[ 0 0 2 1 ]\n *\t[ 1 0 2 1 ]\n *\t[ 0 0 3 1 ]\n *\t[ 1 0 3 1 ]\n *\n */\n\ntemplate <class IntType = int, class RAContainerInt = std::vector<IntType>>\nclass Multisets\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 multiset = value_type;\n    using difference_type = std::ptrdiff_t;\n    using size_type = difference_type;\n    class iterator;\n    using const_iterator = iterator;\n    class reverse_iterator;\n    using const_reverse_iterator = reverse_iterator;\n\npublic:\n    explicit Multisets(const multiset& set) : total_(set), size_(1)\n    {\n        for (auto x : set)\n        {\n            size_ *= (x + 1);\n        }\n    }\n\n    explicit Multisets(IntType size, IntType n = 1)\n        : total_(size, n), size_(std::pow(n + 1, size))\n    {}\n\n    size_type size() const { return size_; }\n\n    iterator begin() const { return iterator(total_); }\n\n    const iterator end() const\n    {\n        return iterator::make_invalid_with_id(size());\n    }\n\n    reverse_iterator rbegin() const { return reverse_iterator(total_); }\n\n    const reverse_iterator rend() const\n    {\n        return reverse_iterator::make_invalid_with_id(size());\n    }\n\n    //////////////////////////////\n    /// @brief Random Access Capabilities for multiset\n    /// @param m assumes 0 <= m < size(). Undefined behaviour otherwise\n    //////////////////////////////\n    multiset operator[](size_type m) const\n    {\n        assert(m >= 0 && m < size());\n        multiset sub(total_.size());\n        construct_multiset(sub, total_, m);\n        return sub;\n    }\n\n    //////////////////////////////\n    /// @brief Opposite operator to operator[]\n    /// @param sub given a multiset, what would it's index be?\n    //////////////////////////////\n    size_type get_index(const multiset& sub) const\n    {\n        assert(sub.size() == total_.size());\n        size_type coeff = 1;\n        size_type result = 0;\n        for (size_t i = 0; i < total_.size(); ++i)\n        {\n            result += coeff*sub[i];\n            coeff *= (total_[i] + 1);\n        }\n        return result;\n    }\n\n    class iterator\n        : public boost::iterator_facade<iterator, const multiset&, boost::random_access_traversal_tag>\n    {\n\n    public:\n        iterator() = default;\n\n        explicit iterator(const multiset& total)\n            : ID_(0), n_(total.size()), submulti_(total.size(), 0), total_(&total)\n        {}\n\n        size_type ID() const { return ID_; }\n\n        static const iterator make_invalid_with_id(size_type id)\n        {\n            return iterator(id);\n        }\n\n    private:\n        explicit iterator(size_type id) : ID_(id) {}\n\n        void increment()\n        {\n            ++ID_;\n            next_multiset(submulti_, *total_, n_);\n        }\n\n        void decrement()\n        {\n            --ID_;\n            prev_multiset(submulti_, *total_, n_);\n        }\n\n        const multiset& dereference() const { return submulti_; }\n\n        // It only makes sense to compare iterators from the SAME multiset.\n        bool equal(const iterator& it) const { return ID_ == it.ID_; }\n\n        void advance(difference_type m)\n        {\n            ID_ += m;\n            construct_multiset(submulti_, *total_, ID_);\n        }\n\n        difference_type distance_to(const iterator& it) const\n        {\n            return static_cast<difference_type>(it.ID()) - ID();\n        }\n\n    private:\n        size_type ID_{0};\n        size_type n_{0};\n        multiset submulti_{};\n        multiset const* total_{nullptr};\n\n        friend class boost::iterator_core_access;\n    };\n\n    class reverse_iterator\n        : public boost::iterator_facade<reverse_iterator,\n                                        const multiset&,\n                                        boost::random_access_traversal_tag>\n    {\n    public:\n        reverse_iterator() = default;\n\n        explicit reverse_iterator(const multiset& total)\n            : ID_(0), n_(total.size()), submulti_(total), total_(&total)\n        {}\n\n        size_type ID() const { return ID_; }\n\n        static const reverse_iterator make_invalid_with_id(size_type id)\n        {\n            return reverse_iterator(id);\n        }\n\n    private:\n        explicit reverse_iterator(size_type id) : ID_(id) {}\n\n        // prefix\n        void increment()\n        {\n            ++ID_;\n            prev_multiset(submulti_, *total_, n_);\n        }\n\n        void decrement()\n        {\n            --ID_;\n            next_multiset(submulti_, *total_, n_);\n        }\n\n        void advance(difference_type m)\n        {\n            size_type s = 1;\n            for (auto x : *total_)\n                s *= (x + 1);\n            ID_ += m;\n            construct_multiset(submulti_, *total_, s - ID_ - 1);\n        }\n\n        const multiset& dereference() const { return submulti_; }\n\n        // It only makes sense to compare iterators from the SAME multiset.\n        bool equal(const reverse_iterator& it) const { return ID_ == it.ID_; }\n\n        difference_type distance_to(const reverse_iterator& other) const\n        {\n            return static_cast<difference_type>(other.ID()) - ID();\n        }\n\n    private:\n        size_type ID_{0};\n        size_type n_{0}; // must have n_ = submulti_.size() = total_->size()\n        multiset submulti_{};\n        multiset const* total_{nullptr};\n\n        friend class boost::iterator_core_access;\n    };\n\n    template <class Func>\n    void for_each(Func f) const\n    {\n        switch (total_.size())\n        {\n            // clang-format off\n        case 0: detail::for_each_multiset<multiset,0>::apply(total_,f); break;\n        case 1: detail::for_each_multiset<multiset,1>::apply(total_,f); break;\n        case 2: detail::for_each_multiset<multiset,2>::apply(total_,f); break;\n        case 3: detail::for_each_multiset<multiset,3>::apply(total_,f); break;\n        case 4: detail::for_each_multiset<multiset,4>::apply(total_,f); break;\n        case 5: detail::for_each_multiset<multiset,5>::apply(total_,f); break;\n        case 6: detail::for_each_multiset<multiset,6>::apply(total_,f); break;\n        case 7: detail::for_each_multiset<multiset,7>::apply(total_,f); break;\n        case 8: detail::for_each_multiset<multiset,8>::apply(total_,f); break;\n        case 9: detail::for_each_multiset<multiset,9>::apply(total_,f); break;\n        case 10: detail::for_each_multiset<multiset,10>::apply(total_,f); break;\n        case 11: detail::for_each_multiset<multiset,11>::apply(total_,f); break;\n        case 12: detail::for_each_multiset<multiset,12>::apply(total_,f); break;\n        case 13: detail::for_each_multiset<multiset,13>::apply(total_,f); break;\n        case 14: detail::for_each_multiset<multiset,14>::apply(total_,f); break;\n        case 15: detail::for_each_multiset<multiset,15>::apply(total_,f); break;\n        case 16: detail::for_each_multiset<multiset,16>::apply(total_,f); break;\n        case 17: detail::for_each_multiset<multiset,17>::apply(total_,f); break;\n        case 18: detail::for_each_multiset<multiset,18>::apply(total_,f); break;\n        case 19: detail::for_each_multiset<multiset,19>::apply(total_,f); break;\n        case 20: detail::for_each_multiset<multiset,20>::apply(total_,f); break;\n            // clang-format on\n\n        default:\n            for (auto& x : (*this))\n            {\n                f(x);\n            }\n\n            break;\n        }\n    }\n\n    static void next_multiset(multiset& sub, const multiset& total)\n    {\n        next_multiset(sub, total, total.size());\n    }\n\n    static void next_multiset(multiset& sub, const multiset& total, size_type n)\n    {\n        assert(n == sub.size());\n        assert(n == total.size());\n        for (auto i : NN(n))\n        {\n            if (can_increment(i, sub, total))\n            {\n                ++sub[i];\n\n                return;\n            }\n            sub[i] = 0;\n        }\n    }\n\n    static void prev_multiset(multiset& sub, const multiset& total, size_t n)\n    {\n        assert(n == sub.size());\n        assert(n == total.size());\n\n        for (auto i : NN(n))\n        {\n            if (sub[i] != 0)\n            {\n                --sub[i];\n                return;\n            }\n            sub[i] = total[i];\n        }\n    }\n\n    static void construct_multiset(multiset& sub,\n                                   const multiset& total,\n                                   size_type m)\n    {\n        assert(sub.size() == total.size());\n        size_type n = total.size();\n        if (n == 0)\n            return;\n        for (auto&& s : sub)\n            s = 0;\n        std::vector<size_type> coeffs(n);\n        coeffs[0] = 1;\n        for (auto i : II(1, n))\n        {\n            coeffs[i] = coeffs[i - 1]*(total[i - 1] + 1);\n        }\n\n        for (difference_type i = n - 1; i >= 0; --i)\n        {\n            size_type w = coeffs[i];\n            auto t = big_integer_interval(total[i] + 1)\n                       .partition_point(\n                         [m, w](size_type a) { return a*w <= m; }) -\n              1;\n            sub[i] = t;\n            m -= w*t;\n            if (m <= 0)\n                break;\n        }\n    }\n\nprivate:\n    multiset total_;\n    size_type size_;\n\n    static bool can_increment(size_t index,\n                              const multiset& sub,\n                              const multiset& total)\n    {\n        return sub[index] < total[index];\n    }\n};\n\nusing boost::container::static_vector;\n\nusing multisets = Multisets<int>;\nusing multisets_stack = Multisets<int, static_vector<int, 48>>;\n\n} // namespace discreture\n", "meta": {"hexsha": "379f515c95ecfb6ba0a8581e89c7e1c59f2dc942", "size": 10714, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Discreture/Multisets.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/Multisets.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/Multisets.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": 29.0352303523, "max_line_length": 102, "alphanum_fraction": 0.5458278887, "num_tokens": 2777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.59345581135926}}
{"text": "// (C) Copyright 2007-2009 Andrew Sutton\r\n//\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0 (See accompanying file\r\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <iostream>\r\n\r\n#include <boost/graph/undirected_graph.hpp>\r\n#include <boost/graph/directed_graph.hpp>\r\n#include <boost/graph/exterior_property.hpp>\r\n#include <boost/graph/clustering_coefficient.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\n\r\n// number of vertices in the graph\r\nstatic const unsigned N = 5;\r\n\r\ntemplate <typename Graph>\r\nstruct vertex_vector\r\n{\r\n    typedef graph_traits<Graph> traits;\r\n    typedef vector<typename traits::vertex_descriptor> type;\r\n};\r\n\r\ntemplate <typename Graph>\r\nvoid build_graph(Graph& g, typename vertex_vector<Graph>::type& v)\r\n{\r\n    // add vertices\r\n    for(size_t i = 0; i < N; ++i) {\r\n        v[i] = add_vertex(g);\r\n    }\r\n\r\n    // add edges\r\n    add_edge(v[0], v[1], g);\r\n    add_edge(v[1], v[2], g);\r\n    add_edge(v[2], v[0], g);\r\n    add_edge(v[3], v[4], g);\r\n    add_edge(v[4], v[0], g);\r\n}\r\n\r\ntemplate <typename Graph>\r\nvoid test_undirected()\r\n{\r\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n\r\n    typedef exterior_vertex_property<Graph, double> ClusteringProperty;\r\n    typedef typename ClusteringProperty::container_type ClusteringContainer;\r\n    typedef typename ClusteringProperty::map_type ClusteringMap;\r\n\r\n    Graph g;\r\n    vector<Vertex> v(N);\r\n    build_graph(g, v);\r\n\r\n    ClusteringContainer cc(num_vertices(g));\r\n    ClusteringMap cm(cc, g);\r\n\r\n    BOOST_ASSERT(num_paths_through_vertex(g, v[0]) == 3);\r\n    BOOST_ASSERT(num_paths_through_vertex(g, v[1]) == 1);\r\n    BOOST_ASSERT(num_paths_through_vertex(g, v[2]) == 1);\r\n    BOOST_ASSERT(num_paths_through_vertex(g, v[3]) == 0);\r\n    BOOST_ASSERT(num_paths_through_vertex(g, v[4]) == 1);\r\n\r\n    BOOST_ASSERT(num_triangles_on_vertex(g, v[0]) == 1);\r\n    BOOST_ASSERT(num_triangles_on_vertex(g, v[1]) == 1);\r\n    BOOST_ASSERT(num_triangles_on_vertex(g, v[2]) == 1);\r\n    BOOST_ASSERT(num_triangles_on_vertex(g, v[3]) == 0);\r\n    BOOST_ASSERT(num_triangles_on_vertex(g, v[4]) == 0);\r\n\r\n    // TODO: Need a FP approximation to assert here.\r\n    // BOOST_ASSERT(clustering_coefficient(g, v[0]) == double(1)/3);\r\n    BOOST_ASSERT(clustering_coefficient(g, v[1]) == 1);\r\n    BOOST_ASSERT(clustering_coefficient(g, v[2]) == 1);\r\n    BOOST_ASSERT(clustering_coefficient(g, v[3]) == 0);\r\n    BOOST_ASSERT(clustering_coefficient(g, v[4]) == 0);\r\n\r\n    all_clustering_coefficients(g, cm);\r\n\r\n    // TODO: Need a FP approximation to assert here.\r\n    // BOOST_ASSERT(cm[v[0]] == double(1)/3);\r\n    BOOST_ASSERT(cm[v[1]] == 1);\r\n    BOOST_ASSERT(cm[v[2]] == 1);\r\n    BOOST_ASSERT(cm[v[3]] == 0);\r\n    BOOST_ASSERT(cm[v[4]] == 0);\r\n\r\n    // I would have used check_close, but apparently, that requires\r\n    // me to link this against a library - which I don't really want\r\n    // to do. Basically, this makes sure that that coefficient is\r\n    // within some tolerance (like 1/10 million).\r\n    double coef = mean_clustering_coefficient(g, cm);\r\n    BOOST_ASSERT((coef - (7.0f / 15.0f)) < 1e-7f);\r\n}\r\n\r\nint\r\nmain(int, char *[])\r\n{\r\n    typedef undirected_graph<> Graph;\r\n    // typedef directed_graph<> Digraph;\r\n\r\n    // TODO: write a test for directed clustering coefficient.\r\n\r\n    test_undirected<Graph>();\r\n    // test<Digraph>();\r\n}\r\n", "meta": {"hexsha": "9c1ff9e0093c77e75791efa35413f7a6203a5f40", "size": 3405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/graph/test/clustering_coefficient.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/graph/test/clustering_coefficient.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/graph/test/clustering_coefficient.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 32.1226415094, "max_line_length": 77, "alphanum_fraction": 0.6619676946, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.5934558071761482}}
{"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/LU>\n\n#include <iostream>\n#include <iomanip>\n\ntemplate <class Matrix>\nclass ImpedanceMap {\npublic:\n    ImpedanceMap(double R_, double W_) : R(R_), W(W_) {\n        // TODO: build and factorize A0 into lu\n    };\n    \n    double operator()(double Rx) {\n        // TODO: compute the impedance from voltages and resistance\n    };\nprivate:\n    Eigen::PartialPivLU< Matrix > lu; //< Store lu decomposition of a for efficiency\n    double R, W; //< Resistance R and source voltage W\n    Matrix rhs; //< Store rhs vector prescribing sink and source voltages\n};\n\nint main(void) {\n    ImpedanceMap<Eigen::MatrixXd> IM = ImpedanceMap<Eigen::MatrixXd>(1, 1);\n    \n    std::cout << std::setw(30) << \"Impedance [Ohm]\" << std::setw(30) << \"R_x [Ohm]\" << std::endl;\n    for(auto Rx = 1; Rx <= 1024; Rx *= 2) {\n        std::cout << std::setw(30) << IM(Rx)        << std::setw(30) << \" \" << Rx << std::endl;\n    }\n    \n}\n", "meta": {"hexsha": "e2c39b9c784bc25a8481627215cb2ac5a0fcf78d", "size": 939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/solutions/solution_3/impedancemap.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/solutions/solution_3/impedancemap.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/solutions/solution_3/impedancemap.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.34375, "max_line_length": 97, "alphanum_fraction": 0.6027689031, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5934336375244742}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE linalg_test\n\n// Standard includes\n#include <iostream>\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/tools/eigenio_matrixmarket.h\"\n#include \"votca/tools/linalg.h\"\n\nusing namespace votca::tools;\n\nBOOST_AUTO_TEST_SUITE(linalg_test)\n\nBOOST_AUTO_TEST_CASE(linalg_constrained_qrsolve_test) {\n\n  Eigen::VectorXd b = Eigen::VectorXd::Zero(3);\n  b(0) = 11;\n  b(1) = -3;\n  b(2) = 8;\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(3, 3);\n  A(0, 0) = 1;\n  A(0, 1) = 1;\n  A(0, 2) = 1;\n  A(1, 0) = 1;\n  A(1, 1) = -1;\n  A(2, 1) = 1;\n  A(2, 2) = 1;\n\n  Eigen::MatrixXd B = Eigen::MatrixXd::Zero(1, 3);\n  B(0, 1) = -1;\n  B(0, 2) = 3;\n  Eigen::VectorXd x = linalg_constrained_qrsolve(A, b, B);\n  Eigen::VectorXd x_ref = Eigen::VectorXd::Zero(3);\n  x_ref(0) = 3;\n  x_ref(1) = 6;\n  x_ref(2) = 2;\n\n  bool equal = x_ref.isApprox(x, 1e-7);\n\n  if (!equal) {\n    std::cout << \"result\" << std::endl;\n    std::cout << x << std::endl;\n    std::cout << \"ref\" << std::endl;\n    std::cout << x_ref << std::endl;\n  }\n  BOOST_CHECK_EQUAL(equal, true);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "55920b7e9ba50845a24e26c81e60a133702af51c", "size": 1795, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tools/src/tests/test_linalg.cc", "max_stars_repo_name": "ipelupessy/votca", "max_stars_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/src/tests/test_linalg.cc", "max_issues_repo_name": "ipelupessy/votca", "max_issues_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/src/tests/test_linalg.cc", "max_forks_repo_name": "ipelupessy/votca", "max_forks_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_forks_repo_licenses": ["Apache-2.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.9305555556, "max_line_length": 75, "alphanum_fraction": 0.6623955432, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5934094367452376}}
{"text": "/**\n * @file fastmks_test.cpp\n * @author Ryan Curtin\n *\n * Ensure that fast max-kernel search is correct.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/fastmks/fastmks.hpp>\n#include <mlpack/core/kernels/linear_kernel.hpp>\n#include <mlpack/core/kernels/polynomial_kernel.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::tree;\nusing namespace mlpack::fastmks;\nusing namespace mlpack::kernel;\nusing namespace mlpack::metric;\n\nBOOST_AUTO_TEST_SUITE(FastMKSTest);\n\n/**\n * Compare single-tree and naive.\n */\nBOOST_AUTO_TEST_CASE(SingleTreeVsNaive)\n{\n  // First create a random dataset.\n  arma::mat data;\n  data.randn(5, 1000);\n  LinearKernel lk;\n\n  // Now run FastMKS naively.\n  FastMKS<LinearKernel> naive(data, lk, false, true);\n\n  arma::Mat<size_t> naiveIndices;\n  arma::mat naiveProducts;\n  naive.Search(10, naiveIndices, naiveProducts);\n\n  // Now run it in single-tree mode.\n  FastMKS<LinearKernel> single(data, lk, true);\n\n  arma::Mat<size_t> singleIndices;\n  arma::mat singleProducts;\n  single.Search(10, singleIndices, singleProducts);\n\n  // Compare the results.\n  for (size_t q = 0; q < singleIndices.n_cols; ++q)\n  {\n    for (size_t r = 0; r < singleIndices.n_rows; ++r)\n    {\n      BOOST_REQUIRE_EQUAL(singleIndices(r, q), naiveIndices(r, q));\n      BOOST_REQUIRE_CLOSE(singleProducts(r, q), naiveProducts(r, q), 1e-5);\n    }\n  }\n}\n\n/**\n * Compare dual-tree and naive.\n */\nBOOST_AUTO_TEST_CASE(DualTreeVsNaive)\n{\n  // First create a random dataset.\n  arma::mat data;\n  data.randn(10, 5000);\n  LinearKernel lk;\n\n  // Now run FastMKS naively.\n  FastMKS<LinearKernel> naive(data, lk, false, true);\n\n  arma::Mat<size_t> naiveIndices;\n  arma::mat naiveProducts;\n  naive.Search(10, naiveIndices, naiveProducts);\n\n  // Now run it in dual-tree mode.\n  FastMKS<LinearKernel> tree(data, lk);\n\n  arma::Mat<size_t> treeIndices;\n  arma::mat treeProducts;\n  tree.Search(10, treeIndices, treeProducts);\n\n  for (size_t q = 0; q < treeIndices.n_cols; ++q)\n  {\n    for (size_t r = 0; r < treeIndices.n_rows; ++r)\n    {\n      BOOST_REQUIRE_EQUAL(treeIndices(r, q), naiveIndices(r, q));\n      BOOST_REQUIRE_CLOSE(treeProducts(r, q), naiveProducts(r, q), 1e-5);\n    }\n  }\n}\n\n/**\n * Compare dual-tree and single-tree on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(DualTreeVsSingleTree)\n{\n  // First create a random dataset.\n  arma::mat data;\n  data.randu(8, 5000);\n  PolynomialKernel pk(5.0, 2.5);\n\n  FastMKS<PolynomialKernel> single(data, pk, true);\n\n  arma::Mat<size_t> singleIndices;\n  arma::mat singleProducts;\n  single.Search(10, singleIndices, singleProducts);\n\n  // Now run it in dual-tree mode.\n  FastMKS<PolynomialKernel> tree(data, pk);\n\n  arma::Mat<size_t> treeIndices;\n  arma::mat treeProducts;\n  tree.Search(10, treeIndices, treeProducts);\n\n  for (size_t q = 0; q < treeIndices.n_cols; ++q)\n  {\n    for (size_t r = 0; r < treeIndices.n_rows; ++r)\n    {\n      BOOST_REQUIRE_EQUAL(treeIndices(r, q), singleIndices(r, q));\n      BOOST_REQUIRE_CLOSE(treeProducts(r, q), singleProducts(r, q), 1e-5);\n    }\n  }\n}\n\n/**\n * Test sparse FastMKS (how useful is this, I'm not sure).\n */\nBOOST_AUTO_TEST_CASE(SparseFastMKSTest)\n{\n  // First create a random sparse dataset.\n  arma::sp_mat dataset;\n  dataset.sprandu(10, 100, 0.3);\n\n  FastMKS<LinearKernel, arma::sp_mat> sparsemks(dataset);\n\n  arma::mat denseset(dataset);\n  FastMKS<LinearKernel> densemks(denseset);\n\n  // Store the results in these.\n  arma::Mat<size_t> sparseIndices, denseIndices;\n  arma::mat sparseKernels, denseKernels; \n\n  // Do the searches.\n  sparsemks.Search(3, sparseIndices, sparseKernels);\n  densemks.Search(3, denseIndices, denseKernels);\n\n  // Make sure the results are the same.\n  for (size_t i = 0; i < sparseIndices.n_cols; ++i)\n  {\n    for (size_t j = 0; j < sparseIndices.n_rows; ++j)\n    {\n      if (std::abs(sparseKernels(j, i)) > 1e-15)\n        BOOST_REQUIRE_CLOSE(sparseKernels(j, i), denseKernels(j, i), 1e-5);\n      else\n        BOOST_REQUIRE_SMALL(denseKernels(j, i), 1e-15);\n      BOOST_REQUIRE_EQUAL(sparseIndices(j, i), denseIndices(j, i));\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SparsePolynomialFastMKSTest)\n{\n  // Do it again with the polynomial kernel, just to be sure.\n  arma::sp_mat dataset;\n  dataset.sprandu(10, 100, 0.3);\n  arma::mat denseset(dataset);\n\n  PolynomialKernel pk(3);\n\n  for (size_t i = 0; i < 100; ++i)\n    for (size_t j = 0; j < 100; ++j)\n      if (std::abs(pk.Evaluate(dataset.col(i), dataset.col(j))) < 1e-10)\n        BOOST_REQUIRE_SMALL(pk.Evaluate(denseset.col(i), denseset.col(j)), 1e-10);\n      else\n        BOOST_REQUIRE_CLOSE(pk.Evaluate(dataset.col(i), dataset.col(j)),\n                            pk.Evaluate(denseset.col(i), denseset.col(j)),\n                            1e-5);\n\n  FastMKS<PolynomialKernel, arma::sp_mat> sparsepoly(dataset);\n  FastMKS<PolynomialKernel> densepoly(denseset);\n\n  // Store the results in these.\n  arma::Mat<size_t> sparseIndices, denseIndices;\n  arma::mat sparseKernels, denseKernels; \n\n  // Do the searches.\n  sparsepoly.Search(3, sparseIndices, sparseKernels);\n  densepoly.Search(3, denseIndices, denseKernels);\n\n  // Make sure the results are the same.\n  for (size_t i = 0; i < sparseIndices.n_cols; ++i)\n  {\n    for (size_t j = 0; j < sparseIndices.n_rows; ++j)\n    {\n      if (std::abs(sparseKernels(j, i)) > 1e-15)\n        BOOST_REQUIRE_CLOSE(sparseKernels(j, i), denseKernels(j, i), 1e-5);\n      else\n        BOOST_REQUIRE_SMALL(denseKernels(j, i), 1e-15);\n      BOOST_REQUIRE_EQUAL(sparseIndices(j, i), denseIndices(j, i));\n    }\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "3a55d84d9f4fe9ef1c8d05d4d871230b6e122c56", "size": 5602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/fastmks_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/fastmks_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/fastmks_test.cpp", "max_forks_repo_name": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1941747573, "max_line_length": 82, "alphanum_fraction": 0.6795787219, "num_tokens": 1644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5934094269033063}}
{"text": "/*! \\file\n    \\brief Demonstration of some simple 2D plot features.\n    \\details Uses some simple math functions to generate curves.\n    This demonstrates plotting some simple math functions with most of the 2-D defaults,\n    just changing a few typical details.\n    The detailed output shows the plot settings for each plot.\n    See default_2d_plot.cpp for using \\b all defaults.\n    See also demo_2d_plot.cpp for use of some of the very many options.\n*/\n\n// demo_2d_simple.cpp\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 2007, 2008, 2012, 2018, 2021\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/svg_plot/svg_2d_plot.hpp> // For plot package.\n  using boost::svg::svg_2d_plot;\n\n#include <boost/svg_plot/show_2d_settings.hpp>\n// Only needed for showing which settings in use.\n// Use this when the plot doesn't look as you want it to be.\n\n#include <boost/quan/unc_init.hpp>  // for setUncDefaults\n\n#include <iostream>\n  using std::cout;\n  using std::endl;\n  using std::boolalpha;\n#include <map>\n  using std::map;\n#include <cmath>\n  using std::sqrt;\n#include <string>\n  using std::string;\n\n// using namespace boost::svg;\n// may be *very convenient* if using any SVG named colors,\n// to avoid writing\n  using boost::svg::red;\n  using boost::svg::yellow;\n  using boost::svg::orange;\n  using boost::svg::blue;\n  // for every color used.\n  \n  // and other enum options used:\n  using boost::svg::square;\n  using boost::svg::circlet;\n\n// Some example of 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  std::cout << \"Demonstration of a simple 2D plot showing data points with markers and with lines joining points.\" << std::endl;\n  using boost::quan::setUncDefaults;\n  try\n  {\n    // Some containers for (sorted) sample data.\n    map<double, double> data1;\n    map<double, double> data2;\n    map<double, double> data3;\n\n    for(double i = -5; i <= 10.; i += 1.)\n    { // Several data points for each function.\n      data1[i] = f(i);\n      data2[i] = g(i);\n      data3[i] = h(i);\n      // List if desired:\n      // cout << i << ' '<< data1[i] << ' ' << data2[i] << ' '<< data3[i] << endl;\n    }\n\n    setUncDefaults(std::cout);  // Set the uncertain class defaults.\n    svg_2d_plot my_plot; // Class to hold the plot settings.\n    // Uses most defaults, but scale settings are usually sensible.\n\n    // Add the data series to the plot:\n    my_plot.title(\"demo_2d_simple\");\n    cout << \" my_plot.title() \" << my_plot.title() << endl;\n    my_plot.x_label(\"X-axis\").y_label(\"Y-axis\"); // Note chaining, the easy way to add lots of options.\n\n    std::string s = my_plot.title(); \n\n    my_plot.plot(data1, \"Sqrt(x)\").fill_color(red);\n    my_plot.plot(data2, \"-2 + x^2\").fill_color(orange).size(5);\n    my_plot.plot(data3, \"-1 + 2x\").fill_color(yellow).bezier_on(true).line_color(blue).shape(square);\n    cout << \" my_plot.title() \" << my_plot.title() << endl;\n\n    my_plot.write(\"./demo_2d_simple.svg\");\n    cout << \" my_plot.title() \" << my_plot.title() << endl;\n\n    show_2d_plot_settings(my_plot);\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n  \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n\n/*\n\nOutput:\n\nDemonstration of a simple 2D plot showing data points with markers and with lines joining points.\nmy_plot.title() demo_2d_simple\nmy_plot.title() demo_2d_simple\nfont size 12\nx value_font_space 24\nx left-right border_margin = 24\nplot_left before margin 30\nplot_left after margin 54\nplot_right before margin 498\nplot_right after margin 474\n\ny value_font_space 24\ny top-botton border_margin = 24\nplot_top before margin 54\nplot_top after margin 54\nplot_bottom before margin 474\nplot_bottom after margin 474\nmy_plot.title()\n\n\nSVG 2-D plot settings\n(default units pixels)========================\naxes_on true\nbackground_border_width 2\nbackground_border_color RGB(255,255,0)\nbackground_color RGB(255,255,255)\nimage_border_margin() 3\nimage_border_width() 2\ncoord_precision 3\ncopyright_date\ncopyright_holder\ndescription\ndocument_title \"\"\nimage x_size 500\nimage y_size 400\nimage_filename\nlegend_on false\nlegend_place 2\nlegend_top_left -1, -1, legend_bottom_right -1, -1\nlegend_background_color blank\nlegend_border_color RGB(255,255,0)\nlegend_color blank\nlegend_title \"\"\nlegend_title_font_size 14\nlegend_font_weight\nlegend_width 0\nlegend_lines true\nlimit points stroke color RGB(119,136,153)\nlimit points fill color RGB(250,235,215)\nlicense_on false\nlicense_reproduction permits\nlicense_distribution permits\nlicense_attribution requires\nlicense_commercialuse permits\nplot_background_color RGB(255,255,255)\nplot_border_color RGB(119,136,153)\nplot_border_width 2\nplot_window_on true\nplot_window_x 84.2, 474\nplot_window_x_left 84.2\nplot_window_x_right 474\nplot_window_y 71, 323\nplot_window_y_top 71\nplot_window_y_bottom 323\ntitle_on true\ntitle \"\"\ntitle_color blank\ntitle_font_alignment 2\ntitle_font_decoration\ntitle_font_family Lucida Sans Unicode\ntitle_font_rotation 0\ntitle_font_size 18\ntitle_font_stretch\ntitle_font_style\ntitle_font_weight\nx_values_on false\nx_values_font_size 12\nx_values_font_family Lucida Sans Unicode\nx_values_precision 3\nx_values_ioflags 200 iosFormatFlags (0x200) dec.\ny_values_precision 3\ny_values_font_size() 3\ny_values_ioflags 200 iosFormatFlags (0x200) dec.\ny_values_color blank\ny_values_font_family() Lucida Sans Unicode\ny_values_font_size() 12\nx_max 10\nx_min -10\nx_autoscale false\ny_autoscale false\nxy_autoscale false\nx_autoscale_check_limits true\nx_axis_on true\nx_axis_color() RGB(0,0,0)\nx_axis_label_color blank\nx_values_color blank\nx_axis_width 1\nx_label_on true\nx_label \"X-axis\"\nx_label_color blank\nx_label_font_family Lucida Sans Unicode\nx_label_font_size 14\nx_label_units\nx_label_units_on false\nx_major_labels_side left\nx_major_label_rotation 0\nx_major_grid_color RGB(200,220,255)\nx_major_grid_on false\nx_major_grid_width 1\nx_major_interval 2\nx_major_tick 2\nx_major_tick_color RGB(0,0,0)\nx_major_tick_length 5\nx_major_tick_width 2\nx_minor_interval 0\nx_minor_tick_color RGB(0,0,0)\nx_minor_tick_length 2\nx_minor_tick_width 1\nx_minor_grid_on false\nx_minor_grid_color RGB(200,220,255)\nx_minor_grid_width 0.5\nx_range() -10, 10\nx_num_minor_ticks 4\nx_ticks_down_on true\nx_ticks_up_on false\nx_ticks_on_window_or_axis bottom\ny_axis_position y_axis_position intersects X-axis (X range includes zero)\nx_axis_position x_axis_position intersects Y axis (Y range includes zero)\nx_plusminus_on false\nx_plusminus_color blank\nx_df_on false\nx_df_color RGB(0,0,0)\nx_prefix\nx_separator\nx_suffix\nxy_values_on false\ny_label_on \"true\"\ny_label_axis Y-axis\ny_axis_color RGB(0,0,0)\ny_axis_label_color blank\ny_axis_on true\naxes_on true\ny_axis_value_color RGB(0,0,0)\ny_axis_width 1\ny_label Y-axis\ny_label_color blank\ny_label_font_family Lucida Sans Unicode\ny_label_font_size 14\ny_label_on true\ny_label_units\ny_label_units_on false\ny_label_width 0\ny_major_grid_on false\ny_major_grid_color RGB(200,220,255)\ny_major_grid_width 1\ny_major_interval 2\ny_major_labels_side bottom\ny_major_label_rotation 0\ny_major_tick_color RGB(0,0,0)\ny_major_tick_length  5\ny_major_tick_width  2\ny_minor_grid_on false\ny_minor_grid_color  RGB(200,220,255)\ny_minor_grid_width 0.5\ny_minor_interval 0\ny_minor_tick_color RGB(0,0,0)\ny_minor_tick_length 2\ny_minor_tick_width 1\ny_range() -10, 10\ny_num_minor_ticks\ny_ticks_left_on true\ny_ticks_right_on false\ny_ticks_on_window_or_axis left\ny_max 10\ny_min -10\ny_values_on false\ny_plusminus_on false\ny_plusminus_color blank\nx_addlimits_on false\nx_addlimits_color RGB(0,0,0)\ny_df_on false\ny_df_color RGB(0,0,0)\ny_prefix \"\"\ny_separator \"\"\ny_suffix \"\"\nconfidence alpha 0.05\ndata lines width 2\nPress any key to continue . . .\n\n\n\n*/\n", "meta": {"hexsha": "d792682a52ea9a15994d27aa1df271c458e65d71", "size": 7900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_2d_simple.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_2d_simple.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_2d_simple.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 25.0, "max_line_length": 128, "alphanum_fraction": 0.766835443, "num_tokens": 2260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.5934094239628188}}
{"text": "#define BOOST_TEST_MODULE party\n\n#include <chrono>\n#include <iostream>\n#include <set>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"party.hpp\"\n\n\nusing clock_type = std::chrono::system_clock;\nusing namespace party;\n\n\nBOOST_AUTO_TEST_SUITE(functional_tests)\n\n\n// functions should work for any movable element type\n// including non-comparable and non-copyable types\n\nstruct element {\n\telement(element&& other) = default;\n\telement& operator = (element&& other) = default;\n\telement(size_t value = 0) : value(value) {}\n\toperator int () const {return value;}\n\tsize_t value;\n};\n\n\nBOOST_AUTO_TEST_CASE(seventh_bell_number) {\n\tstd::cout << \"Constructing unordered partitions\" << std::endl;\n\tstd::vector<size_t> elements {1,2,3,4,5,6,7};\n\n\tsize_t counter = 0;\n\n\t// set up generation for elements on non-copyable type\n\tauto root = first_set_partition<element>(elements);\n\tauto start = clock_type::now();\n\tfor(bool is_valid(1); is_valid; is_valid = next_unordered_partition(root)) {\n//\t\tstd::cout << counter << \":\\t\" << root << std::endl;\n\t\t++counter;\n\t}\n\n\tstd::cout << counter << \" partitions generated\" << std::endl;\n\tBOOST_CHECK_EQUAL(counter, 877);\n\n\troot = last_set_partition<element>(elements);\n\n\tfor(bool is_valid(1); is_valid; is_valid = prev_unordered_partition(root)) {\n//\t\tstd::cout << counter << \":\\t\" << root << std::endl;\n\t\t--counter;\n\t}\n\n\tstd::cout << counter << \" partitions left after reverse\" << std::endl;\n\tBOOST_CHECK_EQUAL(counter, 0);\n\n\tauto finish = clock_type::now();\n\tauto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count();\n\tstd::cout << elapsed << \" milliseconds elapsed\" << std::endl;\n}\n\n\nBOOST_AUTO_TEST_CASE(fifth_ordered_bell_number) {\n\tstd::cout << \"Constructing ordered paritions\" << std::endl;\n\tstd::vector<size_t> elements {1,2,3,4,5};\n\n\tauto start = clock_type::now();\n\tsize_t counter = 0;\n\n\t// set up generation for elements on non-copyable type\n\tauto root = first_set_partition<element>(elements);\n\tfor(bool is_valid(1); is_valid; is_valid = next_ordered_partition(root)) {\n//\t\tstd::cout << ++counter << \":\\t\" << root << std::endl;\n\t\t++counter;\n\t}\n\n\tstd::cout << counter << \" partitions constructed\" << std::endl;\n\tBOOST_CHECK_EQUAL(counter, 541);\n\n\troot = last_set_partition<element>(elements);\n\tfor(bool is_valid(1); is_valid; is_valid = prev_ordered_partition(root)) {\n//\t\tstd::cout << --counter << \":\\t\" << root << std::endl;\n\t\t--counter;\n\t}\n\n\tstd::cout << counter << \" partitions left after reverse\" << std::endl;\n\tBOOST_CHECK_EQUAL(counter, 0);\n\n\tauto finish = clock_type::now();\n\tauto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count();\n\tstd::cout << elapsed << \" milliseconds elapsed\" << std::endl;\n}\n\n\nBOOST_AUTO_TEST_CASE(Ono_and_Nakano_extension) {\n\tstd::vector<size_t> elements {1,2,3,4,5,6};\n\tstd::vector<extension<size_t>> exhaustive, forward, reverse;\n\tstd::set<std::pair<size_t, size_t>> relation {\n\t\t{1,2}, {1,4}, {2,4}, {3,5}, {3,6}, {5,6}\n\t};\n\n\t// find extensions with exhaustive search\n\tauto use_exhaustive_search = [&] () {\n\t\textension<size_t> root;\n\t\troot.elements = elements;\n\t\troot.index.resize(elements.size());\n\t\tstd::iota(root.index.begin(), root.index.end(), 0);\n\t\twhile (true) {\n\n\t\t\tauto e_begin = root.elements.begin(), e_end = root.elements.end();\n\t\t\tauto r_iter = relation.begin(), r_end = relation.end();\n\t\t\tfor(; r_iter != r_end; ++r_iter) {\n\n\t\t\t\t// find positions of the elements spesified by the relation\n\t\t\t\tsize_t source = std::distance(e_begin, std::find(e_begin, e_end, r_iter->first));\n\t\t\t\tsize_t target = std::distance(e_begin, std::find(e_begin, e_end, r_iter->second));\n\n\t\t\t\t// check relation requirements\n\t\t\t\tif (source > target) break;\n\t\t\t}\n\n\t\t\tif (r_iter == r_end) exhaustive.emplace_back(root);\n\t\t\tif (!std::next_permutation(root.index.begin(), root.index.end())) break;\n\t\t\tfor(size_t i = 0; i < root.index.size(); ++i) {\n\t\t\t\troot.elements[i] = elements[root.index[i]];\n\t\t\t}\n\t\t}\n\t};\n\n\t// find extensions with forward enumeration algorithm\n\tauto use_forward_enumeration = [&] () {\n\t\tauto ps = make_poset<size_t>(elements, relation);\n\t\tauto root = first_poset_extension(ps);\n\n\t\tdo forward.push_back(root);\n\t\twhile (next_poset_extension(root, ps));\n\t};\n\n\t// find extensions with reverse enumeration algorithm\n\tauto use_reverse_enumeration = [&] () {\n\t\tauto ps = make_poset<size_t>(elements, relation);\n\t\tauto root = last_poset_extension(ps);\n\n\t\tdo reverse.push_back(root);\n\t\twhile (prev_poset_extension(root, ps));\n\t};\n\n\tuse_exhaustive_search();\n\tuse_forward_enumeration();\n\tuse_reverse_enumeration();\n\n\tstd::cout << \"exhaustive search : \" << exhaustive.size() << std::endl;\n\tstd::cout << \"forward enumeration : \" << forward.size() << std::endl;\n\tstd::cout << \"reverse enumeration : \" << reverse.size() << std::endl;\n\n\tBOOST_CHECK(exhaustive.size() == forward.size());\n\tBOOST_CHECK(exhaustive.size() == reverse.size());\n\n//\tstd::reverse(forward.begin(), forward.end());\n//\tBOOST_CHECK(forward == reverse);\n}\n\n\nBOOST_AUTO_TEST_CASE(opartition_example_by_Ono_and_Nakano) {\n\tstd::vector<size_t> elements {1,2,3,4,5,6};\n\tstd::vector<partition<size_t>> exhaustive, forward, reverse;\n\tstd::set<std::pair<size_t, size_t>> relation {\n\t\t{1,2}, {1,4}, {2,4}, {3,5}, {3,6}, {5,6}\n\t};\n\n\t// find partitions using exhaustive search\n\tauto use_exhaustive_search = [&] () {\n\t\tauto root = first_set_partition<size_t>(elements);\t\t\n\t\twhile (true) {\n\n\t\t\tauto e_begin = root.elements.begin(), e_end = root.elements.end();\n\t\t\tauto r_iter = relation.begin(), r_end = relation.end();\n\t\t\tfor(; r_iter != r_end; ++r_iter) {\n\n\t\t\t\t// find positions of the elements spesified by the relation\n\t\t\t\tsize_t source = std::distance(e_begin, std::find(e_begin, e_end, r_iter->first));\n\t\t\t\tsize_t target = std::distance(e_begin, std::find(e_begin, e_end, r_iter->second));\n\n\t\t\t\t// check relation requirements\n\t\t\t\tif (source > target) break;\n\n\t\t\t\t// items should belong to different segments\n\t\t\t\tauto s_begin = root.segments.begin();\n\t\t\t\tauto s_min = s_begin + std::min(source, target);\n\t\t\t\tauto s_max = s_begin + std::max(source, target);\n\t\t\t\twhile (s_max != s_min && !*s_max) --s_max;\n\t\t\t\tif (s_max == s_min) break;\n\t\t\t}\n\n\t\t\tif (r_iter == r_end) exhaustive.emplace_back(root);\n\t\t\tif (!next_ordered_partition(root)) break;\n\t\t}\n\t};\n\n\t// find partitions with forward enumeration algorithm\n\tauto use_forward_enumeration = [&] () {\n\t\tauto ps = make_poset<size_t>(elements, relation);\n\t\tauto root = first_poset_partition(ps);\n\n\t\tdo forward.push_back(root);\n\t\twhile (next_poset_partition(root, ps));\n\t};\n\n\t// find partitions with reverse enumeration algorithm\n\tauto use_reverse_enumeration = [&] () {\n\t\tauto ps = make_poset<size_t>(elements, relation);\n\t\tauto root = last_poset_partition(ps);\n\n\t\tdo reverse.push_back(root);\n\t\twhile (prev_poset_partition(root, ps));\n\t};\n\n\tuse_exhaustive_search();\n\tuse_forward_enumeration();\n\tuse_reverse_enumeration();\n\n\tstd::cout << \"exhaustive search : \" << exhaustive.size() << std::endl;\n\tstd::cout << \"forward enumeration : \" << forward.size() << std::endl;\n\tstd::cout << \"reverse enumeration : \" << reverse.size() << std::endl;\n\n\tBOOST_CHECK(exhaustive.size() == forward.size());\n\tBOOST_CHECK(exhaustive.size() == reverse.size());\n\n//\tstd::reverse(forward.begin(), forward.end());\n//\tBOOST_CHECK(forward == reverse);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "eba243579e0346e39c449d4711c42f1eeb1d87b1", "size": 7291, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utest.cpp", "max_stars_repo_name": "eugene-che/party", "max_stars_repo_head_hexsha": "b8967bbb9b9d6e51d90806f8d89eb6c0c843f451", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utest.cpp", "max_issues_repo_name": "eugene-che/party", "max_issues_repo_head_hexsha": "b8967bbb9b9d6e51d90806f8d89eb6c0c843f451", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utest.cpp", "max_forks_repo_name": "eugene-che/party", "max_forks_repo_head_hexsha": "b8967bbb9b9d6e51d90806f8d89eb6c0c843f451", "max_forks_repo_licenses": ["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.8940677966, "max_line_length": 94, "alphanum_fraction": 0.6845425868, "num_tokens": 1908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189134878876, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5934094223905282}}
{"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": "//          Copyright Carl Philipp Reh 2009 - 2015.\n//          Copyright Philipp Middendorf 2009 - 2015.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#ifndef FCPPT_ALGORITHM_LEVENSHTEIN_HPP_INCLUDED\n#define FCPPT_ALGORITHM_LEVENSHTEIN_HPP_INCLUDED\n\n#include <fcppt/literal.hpp>\n#include <fcppt/cast/to_signed.hpp>\n#include <fcppt/cast/to_unsigned.hpp>\n#include <fcppt/container/grid/object.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/range/empty.hpp>\n#include <boost/range/size.hpp>\n#include <boost/range/size_type.hpp>\n#include <boost/range/value_type.hpp>\n#include <algorithm>\n#include <fcppt/config/external_end.hpp>\n\n\nnamespace fcppt\n{\nnamespace algorithm\n{\n\n/**\n\\brief Calculates the Levenshtein distance\n\\ingroup fcpptalgorithm\n\\details\nSee http://en.wikipedia.org/wiki/Levenshtein_distance for an explanation of the algorithm.\n\\pre\n<ul>\n<li><code>Range::size_type</code> and <code>Range::value_type</code> exist</li>\n<li><code>bool Range::empty() const</code> exists</li>\n<li><code>size_type Range::size() const</code> exists</li>\n<li><code>Range::operator[]</code> exists</li>\n<li><code>Range::value_type</code> has to have an <code>operator==</code></li>\n</ul>\n\n\\note\nThe code is taken quite literally from:\nhttp://www.merriampark.com/ldcpp.htm\n*/\ntemplate<typename Range>\ntypename\nboost::range_size<Range>::type\nlevenshtein(\n\tRange const &source,\n\tRange const &target)\n{\n\ttypedef typename\n\tboost::range_size<Range>::type\n\tsize_type;\n\n\ttypedef typename\n\tboost::range_difference<Range>::type\n\tdifference_type;\n\n\ttypedef typename\n\tboost::range_value<Range>::type\n\telement_type;\n\n\tsize_type const\n\t\tn =\n\t\t\tboost::size(\n\t\t\t\tsource),\n\t\tm =\n\t\t\tboost::size(\n\t\t\t\ttarget);\n\n\tif(boost::empty(source))\n\t\treturn m;\n\n\tif(boost::empty(target))\n\t\treturn n;\n\n\ttypedef\n\tfcppt::container::grid::object\n\t<\n\t\tsize_type,\n\t\t2\n\t>\n\tgrid;\n\n\ttypedef typename\n\tgrid::dim\n\tdim;\n\n\ttypedef typename\n\tgrid::pos\n\tpos;\n\n\tgrid matrix(\n\t\tdim(\n\t\t\tn + 1,\n\t\t\tm + 1\n\t\t),\n\t\tfcppt::literal<\n\t\t\tsize_type\n\t\t>(\n\t\t\t0\n\t\t)\n\t);\n\n\t// Step 2\n\n\tfor (size_type i = 0; i <= n; i++)\n\t\tmatrix[pos(i,0u)] = i;\n\n\tfor (size_type j = 0; j <= m; j++)\n\t\tmatrix[pos(0u,j)] = j;\n\n\tfor (difference_type i = 1; i <= fcppt::cast::to_signed(n); i++)\n\t{\n\t\telement_type const &s_i =\n\t\t\t*(boost::begin(\n\t\t\t\tsource) +\n\t\t\ti-1);\n\n\t\tfor (difference_type j = 1; j <= fcppt::cast::to_signed(m); j++)\n\t\t{\n\t\t\telement_type const &t_j =\n\t\t\t\t*(boost::begin(\n\t\t\t\t\ttarget) +\n\t\t\t\tj-1);\n\n\t\t\tsize_type const cost(\n\t\t\t\ts_i == t_j\n\t\t\t\t?\n\t\t\t\t\t0u\n\t\t\t\t:\n\t\t\t\t\t1u\n\t\t\t);\n\n\t\t\t// Step 6\n\n\t\t\tsize_type const\n\t\t\t\tabove =\n\t\t\t\t\tmatrix[\n\t\t\t\t\t\tpos(\n\t\t\t\t\t\t\tfcppt::cast::to_unsigned(\n\t\t\t\t\t\t\t\ti-1),\n\t\t\t\t\t\t\tfcppt::cast::to_unsigned(\n\t\t\t\t\t\t\t\tj))],\n\t\t\t\tleft =\n\t\t\t\t\tmatrix[\n\t\t\t\t\t\tpos(\n\t\t\t\t\t\t\tfcppt::cast::to_unsigned(\n\t\t\t\t\t\t\t\ti),\n\t\t\t\t\t\t\tfcppt::cast::to_unsigned(\n\t\t\t\t\t\t\t\tj-1))],\n\t\t\t\tdiag =\n\t\t\t\t\tmatrix[\n\t\t\t\t\t\tpos(\n\t\t\t\t\t\t\tfcppt::cast::to_unsigned(\n\t\t\t\t\t\t\t\ti-1),\n\t\t\t\t\t\t\tfcppt::cast::to_unsigned(\n\t\t\t\t\t\t\t\tj-1))];\n\n\t\t\tsize_type cell =\n\t\t\t\t::std::min(\n\t\t\t\t\tabove + 1u,\n\t\t\t\t\t::std::min(\n\t\t\t\t\t\tleft + 1u,\n\t\t\t\t\t\tdiag + cost));\n\n\t\t\t// Step 6A: Cover transposition, in addition to deletion,\n\t\t\t// insertion and substitution. This step is taken from:\n\t\t\t// Berghel, Hal ; Roach, David : \"An Extension of Ukkonen's\n\t\t\t// Enhanced Dynamic Programming ASM Algorithm\"\n\t\t\t// (http://www.acm.org/~hlb/publications/asm/asm.html)\n\t\t\tif(i>fcppt::literal<difference_type>(2) && j>fcppt::literal<difference_type>(2))\n\t\t\t{\n\t\t\t\tsize_type trans =\n\t\t\t\t\tmatrix[\n\t\t\t\t\t\tpos(\n\t\t\t\t\t\t\tfcppt::cast::to_unsigned(\n\t\t\t\t\t\t\t\ti-2),\n\t\t\t\t\t\t\tfcppt::cast::to_unsigned(\n\t\t\t\t\t\t\t\tj-2))\n\t\t\t\t\t] +\n\t\t\t\t\t\t1u;\n\n\t\t\t\tif(*(boost::begin(source) + i-2) != t_j)\n\t\t\t\t\ttrans++;\n\n\t\t\t\tif(s_i != *(boost::begin(target) + j-2))\n\t\t\t\t\ttrans++;\n\n\t\t\t\tif(cell>trans)\n\t\t\t\t\tcell = trans;\n\t\t\t}\n\n\t\t\tmatrix[\n\t\t\t\tpos(\n\t\t\t\t\tfcppt::cast::to_unsigned(\n\t\t\t\t\t\ti),\n\t\t\t\t\tfcppt::cast::to_unsigned(\n\t\t\t\t\t\tj))] =\n\t\t\t\tcell;\n\t\t}\n\t}\n\n\treturn\n\t\tmatrix[\n\t\t\tpos(\n\t\t\t\tn,\n\t\t\t\tm\n\t\t\t)\n\t\t];\n}\n\n}\n}\n\n#endif\n", "meta": {"hexsha": "4b4805d096845db57f5b407f23e577b019d885c8", "size": 4058, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fcppt/algorithm/levenshtein.hpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/fcppt/algorithm/levenshtein.hpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/fcppt/algorithm/levenshtein.hpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.4454545455, "max_line_length": 90, "alphanum_fraction": 0.6168063085, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.5933021171261826}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#define NT2_UNIT_MODULE \"nt2 polynom toolbox - polyfit/scalar Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of polynom components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n/// created  by jt the 06/03/2011\n///\n#include <nt2/include/functions/polyfit.hpp>\n#include <nt2/include/functions/polyval.hpp>\n#include <nt2/include/functions/isulpequal.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/memory/buffer.hpp>\n#include <nt2/include/constants/real.hpp>\n#include <nt2/table.hpp>\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/include/functions/complexify.hpp>\n\n#include <boost/array.hpp>\n\nNT2_TEST_CASE_TPL ( polyfit_real__1_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::polyfit;\n  using nt2::tag::polyfit_;\n  typedef std::complex<T> cT;\n  nt2::table<cT> x =  nt2::complexify(nt2::_(T(1), T(3)));\n  nt2::table<cT> p =  nt2::complexify(nt2::_(T(1), T(3)));\n  nt2::table<cT> y =  nt2::polyval(p, x);\n  NT2_DISPLAY(y);\n  NT2_DISPLAY(x);\n  NT2_DISPLAY(p);\n  NT2_DISPLAY(nt2::polyfit(x, y));\n  nt2::table<cT> p1 =nt2::polyfit(x, y);\n  NT2_DISPLAY(p1);\n  NT2_DISPLAY(nt2::polyval(p1, x));\n  NT2_DISPLAY(y);\n  NT2_TEST(nt2::isulpequal(nt2::polyval(p1, x), y, 0.5));\n\n  NT2_DISPLAY(polyfit(x, y, 2));\n  nt2::table<cT> p2 =polyfit(x, y, 2);\n  NT2_DISPLAY(p2);\n  NT2_DISPLAY(nt2::polyval(p2, x));\n  NT2_DISPLAY(y);\n  NT2_TEST(nt2::isulpequal(nt2::polyval(p2, x), y, 0.5));\n\n  nt2::table<cT> r;\n  T df, normr;\n  nt2::table<cT> mu;\n  nt2::tie(p, r, df, normr, mu) = nt2::polyfit(x, y);\n  NT2_DISPLAY(p);\n  NT2_DISPLAY(r);\n  NT2_DISPLAY(df);\n  NT2_DISPLAY(normr);\n  NT2_DISPLAY(mu);\n  NT2_DISPLAY(polyval(p, (x-mu(1))/mu(2)));\n  NT2_DISPLAY(y);\n  NT2_TEST(nt2::isulpequal(nt2::polyval(p, (x-mu(1))/mu(2)), y, T(5.0)));\n\n\n\n  //////////////////////////////////////////////////////\n  // TODO This does not work s being a structure defined in polyfit.hpp\n  //   nt2::polyfit_infos<T> s;\n  //   nt2::tie(p, s) = polyfit(x, y);\n  //   NT2_DISPLAY(p);\n  //   NT2_DISPLAY(s.r);\n  //   NT2_DISPLAY(s.df);\n  //    NT2_DISPLAY(s.normr);\n  //////////////////////////////////////////////////////\n\n} // end of test for floating_\n\n\nNT2_TEST_CASE_TPL ( polyfit_real__4_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::polyfit;\n  using nt2::tag::polyfit_;\n  typedef std::complex<T> cT;\n  cT a [] = {0.0, 1.0, 2.0, 3.0,  4.0,  5.0};\n  cT b [] = {0.0, 0.8, 0.9, 0.1, -0.8, -1.0};\n  cT c [] = {0.087037037037037245923, -0.81349206349206493183, 1.6931216931216956922, -0.039682539682541172199 };\n  nt2::table<cT> x(nt2::of_size(1,6));\n  nt2::table<cT> y(nt2::of_size(1,6));\n  nt2::table<cT> zz(nt2::of_size(1,4)); //, c+0, c+4); DOESS NOT WORK TODO\n\n for(int i=0; i < 6; ++i)\n   {\n     x(i+1) = cT(a[i]);\n     y(i+1) = cT(b[i]);\n   }\n for(int i=0; i < 4; ++i)\n   {\n     zz(i+1) = cT(c[i]);\n   }\n\n  NT2_DISPLAY(x);\n  NT2_DISPLAY(y);\n  nt2::table<cT> z = polyfit(x, y, 3);\n  NT2_DISPLAY(z);\n  NT2_TEST_ULP_EQUAL(z, zz, 500);\n} // end of test for floating_\n\n", "meta": {"hexsha": "a6a3594e981a99d017545530db9c47867dce11cd", "size": 3652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/polynom/unit/scalar/polyfit.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/type/complex/polynom/unit/scalar/polyfit.cpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/type/complex/polynom/unit/scalar/polyfit.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7565217391, "max_line_length": 113, "alphanum_fraction": 0.5594194962, "num_tokens": 1224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.5933021132360652}}
{"text": "// 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// test_weibull.cpp\r\n\r\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\r\n#include <boost/test/test_exec_monitor.hpp> // Boost.Test\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\n#include <boost/math/distributions/weibull.hpp>\r\n    using boost::math::weibull_distribution;\r\n#include <boost/math/tools/test.hpp> \r\n\r\n#include <iostream>\r\n   using std::cout;\r\n   using std::endl;\r\n   using std::setprecision;\r\n#include <limits>\r\n  using std::numeric_limits;\r\n\r\ntemplate <class RealType>\r\nvoid check_weibull(RealType shape, RealType scale, RealType x, RealType p, RealType q, RealType tol)\r\n{\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         weibull_distribution<RealType>(shape, scale),       // distribution.\r\n         x),                                            // random variable.\r\n         p,                                             // probability.\r\n         tol);                                          // %tolerance.\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         complement(\r\n            weibull_distribution<RealType>(shape, scale),    // distribution.\r\n            x)),                                        // random variable.\r\n         q,                                             // probability complement.\r\n         tol);                                          // %tolerance.\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::quantile(\r\n         weibull_distribution<RealType>(shape, scale),       // distribution.\r\n         p),                                            // probability.\r\n         x,                                             // random variable.\r\n         tol);                                          // %tolerance.\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::quantile(\r\n         complement(\r\n            weibull_distribution<RealType>(shape, scale),    // distribution.\r\n            q)),                                        // probability complement.\r\n         x,                                             // random variable.\r\n         tol);                                          // %tolerance.\r\n}\r\n\r\ntemplate <class RealType>\r\nvoid test_spots(RealType)\r\n{\r\n   // Basic sanity checks\r\n   //\r\n   // These test values were generated for the normal distribution\r\n   // using the online calculator at \r\n   // http://espse.ed.psu.edu/edpsych/faculty/rhale/hale/507Mat/statlets/free/pdist.htm\r\n   //\r\n   // Tolerance is just over 5 decimal digits expressed as a persentage:\r\n   // that's the limit of the test data.\r\n   RealType tolerance = 2e-5f * 100;  \r\n   cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \" %\" << endl;\r\n\r\n   using std::exp;\r\n\r\n   check_weibull(\r\n      static_cast<RealType>(0.25),     // shape\r\n      static_cast<RealType>(0.5),     // scale\r\n      static_cast<RealType>(0.1),     // x\r\n      static_cast<RealType>(0.487646),   // p\r\n      static_cast<RealType>(1-0.487646),   // q\r\n      tolerance);\r\n   check_weibull(\r\n      static_cast<RealType>(0.25),     // shape\r\n      static_cast<RealType>(0.5),     // scale\r\n      static_cast<RealType>(0.5),     // x\r\n      static_cast<RealType>(1-0.367879),   // p\r\n      static_cast<RealType>(0.367879),   // q\r\n      tolerance);\r\n   check_weibull(\r\n      static_cast<RealType>(0.25),     // shape\r\n      static_cast<RealType>(0.5),     // scale\r\n      static_cast<RealType>(1),     // x\r\n      static_cast<RealType>(1-0.304463),   // p\r\n      static_cast<RealType>(0.304463),   // q\r\n      tolerance);\r\n   check_weibull(\r\n      static_cast<RealType>(0.25),     // shape\r\n      static_cast<RealType>(0.5),     // scale\r\n      static_cast<RealType>(2),     // x\r\n      static_cast<RealType>(1-0.243117),   // p\r\n      static_cast<RealType>(0.243117),   // q\r\n      tolerance);\r\n   check_weibull(\r\n      static_cast<RealType>(0.25),     // shape\r\n      static_cast<RealType>(0.5),     // scale\r\n      static_cast<RealType>(5),     // x\r\n      static_cast<RealType>(1-0.168929),   // p\r\n      static_cast<RealType>(0.168929),   // q\r\n      tolerance);\r\n\r\n   check_weibull(\r\n      static_cast<RealType>(0.5),     // shape\r\n      static_cast<RealType>(2),     // scale\r\n      static_cast<RealType>(0.1),     // x\r\n      static_cast<RealType>(0.200371),   // p\r\n      static_cast<RealType>(1-0.200371),   // q\r\n      tolerance);\r\n   check_weibull(\r\n      static_cast<RealType>(0.5),     // shape\r\n      static_cast<RealType>(2),     // scale\r\n      static_cast<RealType>(0.5),     // x\r\n      static_cast<RealType>(0.393469),   // p\r\n      static_cast<RealType>(1-0.393469),   // q\r\n      tolerance);\r\n   check_weibull(\r\n      static_cast<RealType>(0.5),     // shape\r\n      static_cast<RealType>(2),     // scale\r\n      static_cast<RealType>(1),     // x\r\n      static_cast<RealType>(1-0.493069),   // p\r\n      static_cast<RealType>(0.493069),   // q\r\n      tolerance);\r\n   check_weibull(\r\n      static_cast<RealType>(0.5),     // shape\r\n      static_cast<RealType>(2),     // scale\r\n      static_cast<RealType>(2),     // x\r\n      static_cast<RealType>(1-0.367879),   // p\r\n      static_cast<RealType>(0.367879),   // q\r\n      tolerance);\r\n   check_weibull(\r\n      static_cast<RealType>(0.5),     // shape\r\n      static_cast<RealType>(2),     // scale\r\n      static_cast<RealType>(5),     // x\r\n      static_cast<RealType>(1-0.205741),   // p\r\n      static_cast<RealType>(0.205741),   // q\r\n      tolerance);\r\n\r\n   check_weibull(\r\n      static_cast<RealType>(2),     // shape\r\n      static_cast<RealType>(0.25),     // scale\r\n      static_cast<RealType>(0.1),     // x\r\n      static_cast<RealType>(0.147856),   // p\r\n      static_cast<RealType>(1-0.147856),   // q\r\n      tolerance);\r\n   check_weibull(\r\n      static_cast<RealType>(2),     // shape\r\n      static_cast<RealType>(0.25),     // scale\r\n      static_cast<RealType>(0.5),     // x\r\n      static_cast<RealType>(1-0.018316),   // p\r\n      static_cast<RealType>(0.018316),   // q\r\n      tolerance);\r\n\r\n   /*\r\n   This test value came from \r\n   http://espse.ed.psu.edu/edpsych/faculty/rhale/hale/507Mat/statlets/free/pdist.htm\r\n   but appears to be grossly incorrect: certainly it does not agree with the values\r\n   I get from pushing numbers into a calculator (0.0001249921878255106610615995196123).   \r\n   Strangely other test values generated for the same shape and scale parameters do look OK.\r\n   check_weibull(\r\n      static_cast<RealType>(3),     // shape\r\n      static_cast<RealType>(2),     // scale\r\n      static_cast<RealType>(0.1),     // x\r\n      static_cast<RealType>(1.25E-40),   // p\r\n      static_cast<RealType>(1-1.25E-40),   // q\r\n      tolerance);\r\n      */\r\n   check_weibull(\r\n      static_cast<RealType>(3),     // shape\r\n      static_cast<RealType>(2),     // scale\r\n      static_cast<RealType>(0.5),     // x\r\n      static_cast<RealType>(0.015504),   // p\r\n      static_cast<RealType>(1-0.015504),   // q\r\n      tolerance * 10); // few digits in test value\r\n   check_weibull(\r\n      static_cast<RealType>(3),     // shape\r\n      static_cast<RealType>(2),     // scale\r\n      static_cast<RealType>(1),     // x\r\n      static_cast<RealType>(0.117503),   // p\r\n      static_cast<RealType>(1-0.117503),   // q\r\n      tolerance);\r\n   check_weibull(\r\n      static_cast<RealType>(3),     // shape\r\n      static_cast<RealType>(2),     // scale\r\n      static_cast<RealType>(2),     // x\r\n      static_cast<RealType>(1-0.367879),   // p\r\n      static_cast<RealType>(0.367879),   // q\r\n      tolerance);\r\n\r\n   //\r\n   // Tests for PDF\r\n   //\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(weibull_distribution<RealType>(0.25, 0.5), static_cast<RealType>(0.1)), \r\n      static_cast<RealType>(0.856579), \r\n      tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(weibull_distribution<RealType>(0.25, 0.5), static_cast<RealType>(0.5)), \r\n      static_cast<RealType>(0.183940), \r\n      tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(weibull_distribution<RealType>(0.25, 0.5), static_cast<RealType>(5)), \r\n      static_cast<RealType>(0.015020), \r\n      tolerance * 10); // fewer digits in test value\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(weibull_distribution<RealType>(0.5, 2), static_cast<RealType>(0.1)), \r\n      static_cast<RealType>(0.894013), \r\n      tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(weibull_distribution<RealType>(0.5, 2), static_cast<RealType>(0.5)), \r\n      static_cast<RealType>(0.303265), \r\n      tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(weibull_distribution<RealType>(0.5, 2), static_cast<RealType>(1)), \r\n      static_cast<RealType>(0.174326), \r\n      tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(weibull_distribution<RealType>(2, 0.25), static_cast<RealType>(0.1)), \r\n      static_cast<RealType>(2.726860), \r\n      tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(weibull_distribution<RealType>(2, 0.25), static_cast<RealType>(0.5)), \r\n      static_cast<RealType>(0.293050), \r\n      tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(weibull_distribution<RealType>(3, 2), static_cast<RealType>(1)), \r\n      static_cast<RealType>(0.330936), \r\n      tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(weibull_distribution<RealType>(3, 2), static_cast<RealType>(2)), \r\n      static_cast<RealType>(0.551819), \r\n      tolerance);\r\n\r\n   //\r\n   // These test values were obtained using the formulas at \r\n   // http://en.wikipedia.org/wiki/Weibull_distribution\r\n   // which are subtly different to (though mathematically\r\n   // the same as) the ones on the Mathworld site\r\n   // http://mathworld.wolfram.com/WeibullDistribution.html\r\n   // which are the ones used in the implementation.\r\n   // The assumption is that if both computation methods\r\n   // agree then the implementation is probably correct...\r\n   // What's not clear is which method is more accurate.\r\n   //\r\n   tolerance = (std::max)(\r\n      boost::math::tools::epsilon<RealType>(),\r\n      static_cast<RealType>(boost::math::tools::epsilon<double>())) * 5 * 100; // 5 eps as a percentage\r\n   cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \" %\" << endl;\r\n   weibull_distribution<RealType> dist(2, 3);\r\n   RealType x = static_cast<RealType>(0.125);\r\n\r\n   BOOST_MATH_STD_USING // ADL of std lib math functions\r\n\r\n   // mean:\r\n   BOOST_CHECK_CLOSE(\r\n      mean(dist)\r\n      , dist.scale() * boost::math::tgamma(1 + 1 / dist.shape()), tolerance);\r\n   // variance:\r\n   BOOST_CHECK_CLOSE(\r\n      variance(dist)\r\n      , dist.scale() * dist.scale() * boost::math::tgamma(1 + 2 / dist.shape()) - mean(dist) * mean(dist), tolerance);\r\n   // std deviation:\r\n   BOOST_CHECK_CLOSE(\r\n    standard_deviation(dist)\r\n    , sqrt(variance(dist)), tolerance);\r\n   // hazard:\r\n   BOOST_CHECK_CLOSE(\r\n    hazard(dist, x)\r\n    , pdf(dist, x) / cdf(complement(dist, x)), tolerance);\r\n   // cumulative hazard:\r\n   BOOST_CHECK_CLOSE(\r\n    chf(dist, x)\r\n    , -log(cdf(complement(dist, x))), tolerance);\r\n   // coefficient_of_variation:\r\n   BOOST_CHECK_CLOSE(\r\n    coefficient_of_variation(dist)\r\n    , standard_deviation(dist) / mean(dist), tolerance);\r\n   // mode:\r\n   BOOST_CHECK_CLOSE(\r\n    mode(dist)\r\n    , dist.scale() * pow((dist.shape() - 1) / dist.shape(), 1/dist.shape()), tolerance);\r\n   // median:\r\n   BOOST_CHECK_CLOSE(\r\n    median(dist)\r\n    , dist.scale() * pow(log(static_cast<RealType>(2)), 1 / dist.shape()), tolerance);\r\n   // skewness:\r\n   BOOST_CHECK_CLOSE(\r\n    skewness(dist), \r\n    (boost::math::tgamma(1 + 3/dist.shape()) * pow(dist.scale(), RealType(3)) - 3 * mean(dist) * variance(dist) - pow(mean(dist), RealType(3))) / pow(standard_deviation(dist), RealType(3)), \r\n    tolerance * 100);\r\n   // kertosis:\r\n   BOOST_CHECK_CLOSE(\r\n    kurtosis(dist)\r\n    , kurtosis_excess(dist) + 3, tolerance);\r\n   // kertosis excess:\r\n   BOOST_CHECK_CLOSE(\r\n    kurtosis_excess(dist), \r\n    (pow(dist.scale(), RealType(4)) * boost::math::tgamma(1 + 4/dist.shape()) \r\n         - 3 * variance(dist) * variance(dist) \r\n         - 4 * skewness(dist) * variance(dist) * standard_deviation(dist) * mean(dist)\r\n         - 6 * variance(dist) * mean(dist) * mean(dist) \r\n         - pow(mean(dist), RealType(4))) / (variance(dist) * variance(dist)), \r\n    tolerance * 1000);\r\n\r\n   //\r\n   // Special cases:\r\n   //\r\n   BOOST_CHECK(pdf(dist, 0) == 0);\r\n   BOOST_CHECK(cdf(dist, 0) == 0);\r\n   BOOST_CHECK(cdf(complement(dist, 0)) == 1);\r\n   BOOST_CHECK(quantile(dist, 0) == 0);\r\n   BOOST_CHECK(quantile(complement(dist, 1)) == 0);\r\n\r\n   //\r\n   // Error checks:\r\n   //\r\n   BOOST_CHECK_THROW(weibull_distribution<RealType>(0, -1), std::domain_error);\r\n   BOOST_CHECK_THROW(weibull_distribution<RealType>(-1, 1), std::domain_error);\r\n   BOOST_CHECK_THROW(pdf(dist, -1), std::domain_error);\r\n   BOOST_CHECK_THROW(cdf(dist, -1), std::domain_error);\r\n   BOOST_CHECK_THROW(cdf(complement(dist, -1)), std::domain_error);\r\n   BOOST_CHECK_THROW(quantile(dist, 1), std::overflow_error);\r\n   BOOST_CHECK_THROW(quantile(complement(dist, 0)), std::overflow_error);\r\n\r\n} // template <class RealType>void test_spots(RealType)\r\n\r\nint test_main(int, char* [])\r\n{\r\n\r\n  // Check that can construct weibull distribution using the two convenience methods:\r\n  using namespace boost::math;\r\n  weibull myw1(2); // Using typedef\r\n   weibull_distribution<> myw2(2); // Using default RealType double.\r\n\r\n    // Basic sanity-check spot values.\r\n   // (Parameter value, arbitrarily zero, only communicates the floating point type).\r\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %\r\n  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n  test_spots(0.0L); // Test long double.\r\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x0582))\r\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\r\n#endif\r\n#else\r\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\r\n      \"either because the long double overloads of the usual math functions are \"\r\n      \"not available at all, or because they are too inaccurate for these tests \"\r\n      \"to pass.</note>\" << std::cout;\r\n#endif\r\n\r\n   return 0;\r\n} // int test_main(int, char* [])\r\n\r\n/*\r\n\r\nOutput:\r\n\r\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\test_weibull.exe\"\r\nRunning 1 test case...\r\nTolerance for type float is 0.002 %\r\nTolerance for type float is 5.96046e-005 %\r\nTolerance for type double is 0.002 %\r\nTolerance for type double is 1.11022e-013 %\r\nTolerance for type long double is 0.002 %\r\nTolerance for type long double is 1.11022e-013 %\r\nTolerance for type class boost::math::concepts::real_concept is 0.002 %\r\nTolerance for type class boost::math::concepts::real_concept is 1.11022e-013 %\r\n*** No errors detected\r\n\r\n*/\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "4b0fe9ad8f9450749ca5088386f396cde8aa77ff", "size": 14906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_weibull.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/math/test/test_weibull.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/test/test_weibull.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1233595801, "max_line_length": 191, "alphanum_fraction": 0.6000939219, "num_tokens": 3981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.59330209664958}}
{"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": "#include <Eigen/Dense>\n\n#include \"benchmark.hpp\"\n\nint main() {\n  // Array - Blas\n  for (size_t k = 10; k < 1000; k+=10) {\n    size_t m = k;\n    double *A = create_random_sq_matrix(m);\n    double *B = create_random_sq_matrix(m);\n    double *C = (double *) malloc(sizeof(double) * m * m);\n\n    sleep(0.1);\n    Eigen::MatrixXd A_;\n    Eigen::MatrixXd B_;\n    Eigen::MatrixXd C_;\n    A_.resize(m, m);\n    B_.resize(m, m);\n    C_.resize(m, m);\n\n    size_t index = 0;\n    for (size_t i = 0; i < m; i++) {\n      for (size_t j = 0; j < m; j++) {\n        A_(i, j) = A[index];\n        B_(i, j) = B[index];\n        index++;\n      }\n    }\n\n    struct timespec t = tic();\n    C_ = A_ * B_;\n    printf(\"matrix_size: %ld\\teigen matmul: %fs\\n\", m, toc(&t));\n\n    free(A);\n    free(B);\n    free(C);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "ec43a3a4a5c24ff1ae06f0f81549fe13aa60fe99", "size": 801, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "proto/lib/benchmarks/bench_matmul-eigen.cpp", "max_stars_repo_name": "daoran/proto", "max_stars_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-08-27T21:37:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T12:25:04.000Z", "max_issues_repo_path": "proto/lib/benchmarks/bench_matmul-eigen.cpp", "max_issues_repo_name": "daoran/proto", "max_issues_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-21T01:08:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T01:10:10.000Z", "max_forks_repo_path": "proto/lib/benchmarks/bench_matmul-eigen.cpp", "max_forks_repo_name": "daoran/proto", "max_forks_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T05:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-22T03:19:44.000Z", "avg_line_length": 19.5365853659, "max_line_length": 64, "alphanum_fraction": 0.5081148564, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5932492863891122}}
{"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": "//\n// \tCopyright (c) 2018  Cem Bassoy, cem.bassoy@gmail.com\n// \tCopyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n#include <boost/test/unit_test.hpp>\n#include <boost/numeric/ublas/tensor/extents.hpp>\n\nBOOST_AUTO_TEST_SUITE ( test_extents_dynamic )\n\n\nstruct fixture\n{\n  using extents = boost::numeric::ublas::extents<>;\n\n//  static inline auto n     = extents{};\n  static inline auto n1    = extents{1};\n  static inline auto n2    = extents{2};\n  static inline auto n11   = extents{1,1};\n  static inline auto n12   = extents{1,2};\n  static inline auto n21   = extents{2,1};\n  static inline auto n22   = extents{2,2};\n  static inline auto n32   = extents{3,2};\n  static inline auto n111  = extents{1,1,1};\n  static inline auto n211  = extents{2,1,1};\n  static inline auto n121  = extents{1,2,1};\n  static inline auto n112  = extents{1,1,2};\n  static inline auto n123  = extents{1,2,3};\n  static inline auto n321  = extents{3,2,1};\n  static inline auto n213  = extents{2,1,3};\n  static inline auto n432  = extents{4,3,2};\n};\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_empty,\n                        fixture,\n                        *boost::unit_test::label(\"dynamic_extents\") *boost::unit_test::label(\"empty\"))\n{\n  namespace ublas = boost::numeric::ublas;\n\n//  BOOST_CHECK( ublas::empty(n   ));\n  BOOST_CHECK(!ublas::empty(n1  ));\n  BOOST_CHECK(!ublas::empty(n2  ));\n  BOOST_CHECK(!ublas::empty(n11 ));\n  BOOST_CHECK(!ublas::empty(n12 ));\n  BOOST_CHECK(!ublas::empty(n21 ));\n  BOOST_CHECK(!ublas::empty(n22 ));\n  BOOST_CHECK(!ublas::empty(n32 ));\n  BOOST_CHECK(!ublas::empty(n111));\n  BOOST_CHECK(!ublas::empty(n211));\n  BOOST_CHECK(!ublas::empty(n121));\n  BOOST_CHECK(!ublas::empty(n112));\n  BOOST_CHECK(!ublas::empty(n123));\n  BOOST_CHECK(!ublas::empty(n321));\n  BOOST_CHECK(!ublas::empty(n213));\n  BOOST_CHECK(!ublas::empty(n432));\n\n  BOOST_CHECK_THROW( extents({1,1,0}), std::invalid_argument);\n  BOOST_CHECK_THROW( extents({1,0})  , std::invalid_argument);\n  BOOST_CHECK_THROW( extents({0}  )  , std::invalid_argument);\n  BOOST_CHECK_THROW( extents({0,1})  , std::invalid_argument);\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_size,\n                        fixture,\n                        *boost::unit_test::label(\"dynamic_extents\") *boost::unit_test::label(\"size\"))\n{\n  namespace ublas = boost::numeric::ublas;\n\n\n//  BOOST_CHECK_EQUAL(ublas::size(n   ),0);\n  BOOST_CHECK_EQUAL(ublas::size(n1  ),1);\n  BOOST_CHECK_EQUAL(ublas::size(n2  ),1);\n  BOOST_CHECK_EQUAL(ublas::size(n11 ),2);\n  BOOST_CHECK_EQUAL(ublas::size(n12 ),2);\n  BOOST_CHECK_EQUAL(ublas::size(n21 ),2);\n  BOOST_CHECK_EQUAL(ublas::size(n22 ),2);\n  BOOST_CHECK_EQUAL(ublas::size(n32 ),2);\n  BOOST_CHECK_EQUAL(ublas::size(n111),3);\n  BOOST_CHECK_EQUAL(ublas::size(n211),3);\n  BOOST_CHECK_EQUAL(ublas::size(n121),3);\n  BOOST_CHECK_EQUAL(ublas::size(n112),3);\n  BOOST_CHECK_EQUAL(ublas::size(n123),3);\n  BOOST_CHECK_EQUAL(ublas::size(n321),3);\n  BOOST_CHECK_EQUAL(ublas::size(n213),3);\n  BOOST_CHECK_EQUAL(ublas::size(n432),3);\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_at_read,\n                       fixture,\n                       *boost::unit_test::label(\"dynamic_extents\") *boost::unit_test::label(\"at_read\"))\n{\n  BOOST_CHECK_EQUAL(n1  .at(0),1);\n  BOOST_CHECK_EQUAL(n2  .at(0),2);\n\n  BOOST_CHECK_EQUAL(n11 .at(0),1);\n  BOOST_CHECK_EQUAL(n11 .at(1),1);\n\n  BOOST_CHECK_EQUAL(n12 .at(0),1);\n  BOOST_CHECK_EQUAL(n12 .at(1),2);\n\n  BOOST_CHECK_EQUAL(n21 .at(0),2);\n  BOOST_CHECK_EQUAL(n21 .at(1),1);\n\n  BOOST_CHECK_EQUAL(n22 .at(0),2);\n  BOOST_CHECK_EQUAL(n22 .at(1),2);\n\n  BOOST_CHECK_EQUAL(n32 .at(0),3);\n  BOOST_CHECK_EQUAL(n32 .at(1),2);\n\n  BOOST_CHECK_EQUAL(n432.at(0),4);\n  BOOST_CHECK_EQUAL(n432.at(1),3);\n  BOOST_CHECK_EQUAL(n432.at(2),2);\n\n\n//  BOOST_CHECK_THROW( (void)n  .at(0), std::out_of_range);\n  BOOST_CHECK_THROW( (void)n32.at(2), std::out_of_range);\n  BOOST_CHECK_THROW( (void)n32.at(5), std::out_of_range);\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_at_write,\n                        fixture,\n                        *boost::unit_test::label(\"dynamic_extents\") *boost::unit_test::label(\"at_write\"))\n{\n  auto n3 = extents{1};\n  n3 = extents{3};\n  BOOST_CHECK_EQUAL(n3.at(0),3);\n\n  auto n34 = extents{1,1};\n  n34 = extents{3,4};\n  BOOST_CHECK_EQUAL(n34.at(0),3);\n  BOOST_CHECK_EQUAL(n34.at(1),4);\n\n\n  auto n345 = extents{1,1,1};\n  n345 = extents{3,4,5};\n  BOOST_CHECK_EQUAL(n345.at(0),3);\n  BOOST_CHECK_EQUAL(n345.at(1),4);\n  BOOST_CHECK_EQUAL(n345.at(2),5);\n\n\n  auto n5432 = extents{1,1,1,1};\n  n5432 = extents{5,4,3,2};\n  BOOST_CHECK_EQUAL(n5432.at(0),5);\n  BOOST_CHECK_EQUAL(n5432.at(1),4);\n  BOOST_CHECK_EQUAL(n5432.at(2),3);\n  BOOST_CHECK_EQUAL(n5432.at(3),2);\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_operator_access_read,\n                        fixture,\n                        *boost::unit_test::label(\"dynamic_extents\") *boost::unit_test::label(\"operator_access_read\"))\n{\n  BOOST_CHECK_EQUAL(n1  [0],1);\n  BOOST_CHECK_EQUAL(n2  [0],2);\n\n  BOOST_CHECK_EQUAL(n11 [0],1);\n  BOOST_CHECK_EQUAL(n11 [1],1);\n\n  BOOST_CHECK_EQUAL(n12 [0],1);\n  BOOST_CHECK_EQUAL(n12 [1],2);\n\n  BOOST_CHECK_EQUAL(n21 [0],2);\n  BOOST_CHECK_EQUAL(n21 [1],1);\n\n  BOOST_CHECK_EQUAL(n22 [0],2);\n  BOOST_CHECK_EQUAL(n22 [1],2);\n\n  BOOST_CHECK_EQUAL(n32 [0],3);\n  BOOST_CHECK_EQUAL(n32 [1],2);\n\n  BOOST_CHECK_EQUAL(n432[0],4);\n  BOOST_CHECK_EQUAL(n432[1],3);\n  BOOST_CHECK_EQUAL(n432[2],2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "fe4761b88164cecddc32150d55a3bde4e414a61e", "size": 5692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_extents_dynamic.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_extents_dynamic.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_extents_dynamic.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 29.8010471204, "max_line_length": 117, "alphanum_fraction": 0.6732255798, "num_tokens": 1756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5931868897893804}}
{"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 << \"\u4e00\u5171\u627e\u5230\u4e86\" << matches.size() << \"\u7ec4\u5339\u914d\u70b9\" << endl;\n\n\n  Mat d1 = imread(f3, CV_LOAD_IMAGE_UNCHANGED);\n  Mat K = (Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n  vector<Point3f> pts_3d;\n  vector<Point2f> pts_2d;\n  for (DMatch m:matches) {\n    ushort d = d1.ptr<unsigned short>(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)];\n    if (d == 0)   // bad depth\n      continue;\n    float dd = d / 5000.0;\n    Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n    pts_3d.push_back(Point3f(p1.x * dd, p1.y * dd, dd));\n    pts_2d.push_back(keypoints_2[m.trainIdx].pt);\n  }\n\n  cout << \"3d-2d pairs: \" << pts_3d.size() << endl;\n\n  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n  Mat r, t;\n  solvePnP(pts_3d, pts_2d, K, Mat(), r, t, false);\n  Mat R;\n  cv::Rodrigues(r, R);\n  chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n  chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"solve pnp in opencv cost time: \" << time_used.count() << \" seconds.\" << endl;\n\n  cout << \"R=\" << endl << R << endl;\n  cout << \"t=\" << endl << t << endl;\n\n\n  VecVector3d pts_3d_eigen;\n  VecVector2d pts_2d_eigen;\n  for (size_t i = 0; i < pts_3d.size(); ++i) {\n    pts_3d_eigen.push_back(Eigen::Vector3d(pts_3d[i].x, pts_3d[i].y, pts_3d[i].z));\n    pts_2d_eigen.push_back(Eigen::Vector2d(pts_2d[i].x, pts_2d[i].y));\n  }\n  Eigen::Matrix3d K_eigen;\n  K_eigen << 520.9, 0, 325.1,\n             0, 521.0, 249.7,\n             0, 0, 1;\n\n  // Ceres\n  cout << \"Custom Ceres\" << endl;\n  Sophus::SE3d pose_ceres;\n  pose_refinement_ceres(pts_3d_eigen, pts_2d_eigen, K_eigen, pose_ceres);\n  Eigen::Vector3d t_ceres = pose_ceres.translation();\n  Eigen::Matrix3d R_ceres = pose_ceres.so3().unit_quaternion().toRotationMatrix();\n  cout << \"R_ceres = \" << endl << R_ceres << endl;\n  cout << \"t_ceres = \" << endl << t_ceres << endl;\n\n  return 0;\n}\n\n", "meta": {"hexsha": "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// Created by \u53f6\u74a8\u94ed on 2022/4/2.\n//\n#include \"cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/BinarySearch.hpp\"\n#include \"gtest/gtest.h\"\n#include <algorithm>\n#include <boost/log/trivial.hpp>\n#include <numeric>\n#include <vector>\nnamespace cn::edu::SUSTech::YeCanming::Algs::DivideAndConquer {\n    namespace ThisPackage = cn::edu::SUSTech::YeCanming::Algs::DivideAndConquer;\n    TEST(GTestBinarySearch, UsedToFindElement){\n        std::vector<int> a(10);\n        std::iota(a.begin(), a.end(), 0); //0,1,2,...,9\n      // binary_search_for_last_satisfies\n        auto result = ThisPackage::binary_search_for_last_satisfies(a.begin(), a.end(), [](const int& a){\n            return a<=5;\n        });\n        EXPECT_EQ(*result, 5);\n        auto resultC = ThisPackage::binary_search_for_last_satisfies(a.cbegin(), a.cend(), [](const int& a){\n            return a<=5;\n        });\n        EXPECT_EQ(*resultC, 5);\n        // binary_search_for_first_satisfies\n        result = ThisPackage::binary_search_for_first_satisfies(a.begin(), a.end(), [](const int& a){\n            return a>=5;\n        });\n        EXPECT_EQ(*result, 5);\n        resultC = ThisPackage::binary_search_for_first_satisfies(a.cbegin(), a.cend(), [](const int& a){\n            return a>=5;\n        });\n        EXPECT_EQ(*resultC, 5);\n    }\n    TEST(GTestBinarySearch, WhenSatifactionSequenceAreAllZero){\n        std::vector<int> a(10);\n        std::fill(a.begin(), a.end(), 10);\n        // binary_search_for_last_satisfies\n        auto result = ThisPackage::binary_search_for_last_satisfies(a.begin(), a.end(), [](const int& a){\n            return a>11;\n        });\n        EXPECT_EQ(result, a.end());\n        auto resultC = ThisPackage::binary_search_for_last_satisfies(a.cbegin(), a.cend(), [](const int& a){\n            return a>11;\n        });\n        EXPECT_EQ(result, a.cend());\n        // binary_search_for_first_satisfies\n        result = ThisPackage::binary_search_for_first_satisfies(a.begin(), a.end(), [](const int& a){\n            return a>11;\n        });\n        EXPECT_EQ(result, a.end());\n        resultC = ThisPackage::binary_search_for_first_satisfies(a.cbegin(), a.cend(), [](const int& a){\n            return a>11;\n        });\n        EXPECT_EQ(result, a.cend());\n    }\n}\nint main(int argc, char* argv[]){\n    testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}", "meta": {"hexsha": "e1c24fd41f46996908ecdc97eb8fb6277ee7f581", "size": 2355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/GTestBinarySearch.cpp", "max_stars_repo_name": "2catycm/P_Algorithm_Design_and_Analysis_cpp", "max_stars_repo_head_hexsha": "d1678d4db6f59a11215a8c790c2852bf9ad852dd", "max_stars_repo_licenses": ["MulanPSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/cpp/cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/GTestBinarySearch.cpp", "max_issues_repo_name": "2catycm/P_Algorithm_Design_and_Analysis_cpp", "max_issues_repo_head_hexsha": "d1678d4db6f59a11215a8c790c2852bf9ad852dd", "max_issues_repo_licenses": ["MulanPSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/cpp/cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/GTestBinarySearch.cpp", "max_forks_repo_name": "2catycm/P_Algorithm_Design_and_Analysis_cpp", "max_forks_repo_head_hexsha": "d1678d4db6f59a11215a8c790c2852bf9ad852dd", "max_forks_repo_licenses": ["MulanPSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.25, "max_line_length": 108, "alphanum_fraction": 0.6076433121, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.5931868798974294}}
{"text": "/**\n * Authors:\n * \t\tAndr\u00e9 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": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n    This is an example illustrating the use of the kernel ridge regression \n    object from the dlib C++ Library.\n\n    This example will train on data from the sinc function.\n\n*/\n\n#include <iostream>\n#include <vector>\n\n#include <dlib/svm.h>\n\nusing namespace std;\nusing namespace dlib;\n\n// Here is the sinc function we will be trying to learn with kernel ridge regression \ndouble sinc(double x)\n{\n    if (x == 0)\n        return 1;\n    return sin(x)/x;\n}\n\nint main()\n{\n    // Here we declare that our samples will be 1 dimensional column vectors.  \n    typedef matrix<double,1,1> sample_type;\n\n    // Now sample some points from the sinc() function\n    sample_type m;\n    std::vector<sample_type> samples;\n    std::vector<double> labels;\n    for (double x = -10; x <= 4; x += 1)\n    {\n        m(0) = x;\n        samples.push_back(m);\n        labels.push_back(sinc(x));\n    }\n\n    // Now we are making a typedef for the kind of kernel we want to use.  I picked the\n    // radial basis kernel because it only has one parameter and generally gives good\n    // results without much fiddling.\n    typedef radial_basis_kernel<sample_type> kernel_type;\n\n    // Here we declare an instance of the krr_trainer object.  This is the\n    // object that we will later use to do the training.\n    krr_trainer<kernel_type> trainer;\n\n    // Here we set the kernel we want to use for training.   The radial_basis_kernel \n    // has a parameter called gamma that we need to determine.  As a rule of thumb, a good \n    // gamma to try is 1.0/(mean squared distance between your sample points).  So \n    // below we are using a similar value computed from at most 2000 randomly selected\n    // samples.\n    const double gamma = 3.0/compute_mean_squared_distance(randomly_subsample(samples, 2000));\n    cout << \"using gamma of \" << gamma << endl;\n    trainer.set_kernel(kernel_type(gamma));\n\n    // now train a function based on our sample points\n    decision_function<kernel_type> test = trainer.train(samples, labels);\n\n    // now we output the value of the sinc function for a few test points as well as the \n    // value predicted by our regression.\n    m(0) = 2.5; cout << sinc(m(0)) << \"   \" << test(m) << endl;\n    m(0) = 0.1; cout << sinc(m(0)) << \"   \" << test(m) << endl;\n    m(0) = -4;  cout << sinc(m(0)) << \"   \" << test(m) << endl;\n    m(0) = 5.0; cout << sinc(m(0)) << \"   \" << test(m) << endl;\n\n    // The output is as follows:\n    //using gamma of 0.075\n    //    0.239389   0.239389\n    //    0.998334   0.998362\n    //    -0.189201   -0.189254\n    //    -0.191785   -0.186618\n\n    // The first column is the true value of the sinc function and the second\n    // column is the output from the krr estimate.  \n\n\n    // Note that the krr_trainer has the ability to tell us the leave-one-out predictions\n    // for each sample.  \n    std::vector<double> loo_values;\n    trainer.train(samples, labels, loo_values);\n    cout << \"mean squared LOO error: \" << mean_squared_error(labels,loo_values) << endl;\n    cout << \"R^2 LOO value:          \" << r_squared(labels,loo_values) << endl;\n    // Which outputs the following:\n    // mean squared LOO error: 8.29575e-07\n    // R^2 LOO value:          0.999995\n\n\n\n\n\n    // Another thing that is worth knowing is that just about everything in dlib is serializable.\n    // So for example, you can save the test object to disk and recall it later like so:\n    ofstream fout(\"saved_function.dat\",ios::binary);\n    serialize(test,fout);\n    fout.close();\n\n    // now lets open that file back up and load the function object it contains\n    ifstream fin(\"saved_function.dat\",ios::binary);\n    deserialize(test, fin);\n\n\n}\n\n\n", "meta": {"hexsha": "4b182f9850226754cc51808dca09a40c646c6082", "size": 3744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DynamicGestures/dlib-18.5/examples/krr_regression_ex.cpp", "max_stars_repo_name": "uiuyuty/vsfh", "max_stars_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2015-03-02T09:30:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T07:07:57.000Z", "max_issues_repo_path": "DynamicGestures/dlib-18.5/examples/krr_regression_ex.cpp", "max_issues_repo_name": "uiuyuty/vsfh", "max_issues_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-04-01T21:28:24.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-30T21:39:28.000Z", "max_forks_repo_path": "DynamicGestures/dlib-18.5/examples/krr_regression_ex.cpp", "max_forks_repo_name": "uiuyuty/vsfh", "max_forks_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-03-02T18:48:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T06:44:08.000Z", "avg_line_length": 34.3486238532, "max_line_length": 97, "alphanum_fraction": 0.6535790598, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.5930972249999802}}
{"text": "/**\n * @file expfittedupwind.cc\n * @brief NPDE homework ExpFittedUpwind\n * @author Am\u00e9lie Loher, Philippe Peter\n * @date 07.01.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"expfittedupwind.h\"\n\n#include <lf/base/base.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n\n#include <Eigen/Core>\n#include <cmath>\n#include <memory>\n#include <vector>\n\nnamespace ExpFittedUpwind {\n\n/**\n * @brief Computes the Bernoulli function B(tau)\n **/\ndouble Bernoulli(double tau) {\n  //====================\n  // Your code goes here\n  //====================\n  return tau;\n}\n\n/**\n * @brief computes the quantities \\beta(e) for all the edges e of a mesh\n * @param mesh_p underlying mesh\n * @param mu vector of nodal values of a potential Psi\n * @return  Mesh Data set containing the quantities \\beta(e)\n */\nstd::shared_ptr<lf::mesh::utils::CodimMeshDataSet<double>> CompBeta(\n    std::shared_ptr<const lf::mesh::Mesh> mesh_p, const Eigen::VectorXd& mu) {\n  // data set over all edges of the mesh.\n  auto beta_p = lf::mesh::utils::make_CodimMeshDataSet(mesh_p, 1, 1.0);\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return beta_p;\n}\n\n/**\n * @brief actual computation of the element matrix\n * @param cell reference to the triangle for which the matrix is evaluated\n * @return 3x3 dense matrix containg the element matrix\n */\nEigen::Matrix3d ExpFittedEMP::Eval(const lf::mesh::Entity& cell) {\n  LF_VERIFY_MSG(cell.RefEl() == lf::base::RefEl::kTria(),\n                \"Only 2D triangles are supported.\");\n\n  // Evaluate the element matrix A_K\n  Eigen::Matrix3d AK = laplace_provider_.Eval(cell).block<3, 3>(0, 0);\n\n  Eigen::Matrix3d result;\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return std::move(result);\n}\n\n/**\n * @brief returns the quanties beta(e) for  the\n * three edges e_0, e_1 and e_2 of a triangle.\n * @param cell reference to the triangle for which the quantities are needed\n * @return vector  [beta(e_0),beta(e_1),beta(e_2)]'\n **/\nEigen::Vector3d ExpFittedEMP::beta_loc(const lf::mesh::Entity& cell) {\n  Eigen::Vector3d b;\n  auto edges = cell.SubEntities(1);\n  for (int i = 0; i < 3; ++i) {\n    b(i) = (*beta_)(*(edges[i]));\n  }\n  return b;\n}\n\n/** @brief returns the nodal values of the potential Psi for the\n * three vertices a_1, a_2 and a_3 of a triangle\n * @param cell reference to the triangle for which the quantities are needed\n * @return vector [Psi(a_1), Psi(a_2), Psi(a_3)]'\n **/\nEigen::Vector3d ExpFittedEMP::mu_loc(const lf::mesh::Entity& cell) {\n  Eigen::Vector3d m;\n  auto mesh_p = fe_space_->Mesh();\n  auto vertices = cell.SubEntities(2);\n  for (int i = 0; i < 3; ++i) {\n    int index = mesh_p->Index(*(vertices[i]));\n    m(i) = mu_(index);\n  }\n  return m;\n}\n\n} /* namespace ExpFittedUpwind */\n", "meta": {"hexsha": "a4f111a1b8f6008ea5f8c7136cf4dc9907325dfd", "size": 2789, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ExpFittedUpwind/templates/expfittedupwind.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ExpFittedUpwind/templates/expfittedupwind.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ExpFittedUpwind/templates/expfittedupwind.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 27.0776699029, "max_line_length": 78, "alphanum_fraction": 0.643958408, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.5930972202792715}}
{"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 * @file\n * @ingroup tests\n * @brief  Test with embedded error estimation on a domain with reentrant corner.\n * \n * Testprogram for Kaskade: tests wether the error between calculated and exact solution behaves as expected. \n * This test was built by using the embedded error estimation example (2D) and changing the domain. \n * \n * Test uses direct solver or IterateType::CG with preconditioner PrecondType::ICC, PrecondType::ICC0 or PrecondType::BOOMERAMG. \n * Uses ContinuousLagrangeMapper.\n * \n * Since the exact solution is not known, the solution, that is obtained by the finest refinement, is taken for error calculation.\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/norms.hh\"\n// #include \"fem/hierarchicspace.hh\"\n#include \"fem/lagrangespace.hh\"\n#include \"linalg/trivialpreconditioner.hh\"\n#include \"linalg/direct.hh\"\n#include \"linalg/iccprecond.hh\"\n#include \"linalg/icc0precond.hh\"\n#include \"linalg/hyprecond.hh\"       // BoomerAMG\n#include \"linalg/cg.hh\"\n#include \"utilities/enums.hh\"\n#include \"utilities/kaskopt.hh\"\n\nusing namespace Kaskade;\n#include \"reentrantCorner.hh\"\n\nint main(int argc, char *argv[])\n{\n  using namespace boost::fusion;\n\n  int verbosityOpt = 0;\n  bool dump = false; \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<VariableDescription<0,1,0> >;\n  using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;\n  using Functional = ReentrantCornerFunctional<double,VariableSet>;\n  constexpr int nvars = Functional::AnsatzVars::noOfVariables;\n  constexpr int neq = Functional::TestVars::noOfVariables;\n  using Assembler = VariationalFunctionalAssembler<LinearizationAt<Functional> >;\n  using Rhs = Assembler::TestVariableSet::CoefficientVectorRepresentation<>::type;\n  using CoefficientVectors = VariableSet::CoefficientVectorRepresentation<0,neq>::type;\n  using LinearSpace = VariableSet::CoefficientVectorRepresentation<0,neq>::type;\n\n  std::unique_ptr<boost::property_tree::ptree> pt = getKaskadeOptions(argc, argv, verbosityOpt, dump);\n\n  std::cout << \"Start heat program using embedded error estimation on a domain with reentrant corner (einspringender Ecke)\" << std::endl;\n\n  int  refinements = 2;\n  int verbosity   = getParameter(pt, \"verbosity\", 1);\n  // if true, then the test result will be written in a file\n  bool result = getParameter(pt, \"result\",0);\n\n  constexpr int orderLength = 5;\n  constexpr int maxRefSteps = 45;\n  //ansatz orders to be tested\n  int order[orderLength] = {1,2,3,4,5};\n  //error values for corresponding ansatz order\n  //double errors[orderLength] = {3.4e-4,1.3e-4,6.0e-6,9.0e-7,1.5e-7};\n  double errors[orderLength] = {1.4e-3,3.1e-4,4.2e-05,5.0e-05,6.7e-05};\n  // former values for error limits\n  //double errors[orderLength] = {1e-3,3e-4,2e-5,3e-6,1.5e-7};\n  // values for order of convergence for corresponding ansatz order\n  double conOrder[orderLength] = {0.7,0.9,1.2,1.4,1.47};\n  \n  double atol = 1e-7;\n  double rtol = 1e-7;\n  \n  bool valid = true;\n  std::stringstream message(\"Test succeeded\", std::stringstream::out);\n  \n  DirectType directType;\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  std::string solverTypeI = getParameter(pt, \"solver.type\", empty);\n  std::string solverTypeII;\n  s += solverTypeI;\n  direct = getParameter(pt, s, 0);\n\n  std::string directSolver = getParameter(pt, \"solver.direct\", empty);\n  s = \"names.direct.\" + directSolver;\n  directType = static_cast<DirectType>(getParameter(pt, s, 2));\n\n  // Remark: in this example only PrecondType::NONE,PrecondType::JACOBI, PrecondType::ICC, PrecondType::ICC0, PrecondType::BOOMERAMG are used.\n  std::string preconditioner = getParameter(pt, \"solver.preconditioner\", empty);\n  s = \"names.preconditioner.\" + preconditioner;\n  precondType = static_cast<PrecondType>(getParameter(pt, s, 0));\n\n  property = MatrixProperties::SYMMETRIC;\n  if(verbosity > 0) {\n    std::cout << \"discretization is symmetric\" << std::endl;\n  }\n  \n  if ( (directType == DirectType::MUMPS)||(directType == DirectType::PARDISO) || (precondType == PrecondType::ICC) )\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  //iterate over the ansatz orders\n  for(int i = 0;i < orderLength && valid;i++) {\n    if(verbosity > 0) {\n      std::cout << \"original mesh shall be refined : \" << refinements << \" times\" << std::endl;\n      std::cout << \"discretization order         : \" << order[i] << std::endl;\n      std::cout << \"output level (verbosity)     : \" << verbosity << std::endl;\n    }\n\n    //   two-dimensional space: dim=2\n    Dune::GridFactory<Grid> factory;\n\n    // create Grid on a domain with reentrant corner\n    // vertex coordinates v[0], v[1]\n    Dune::FieldVector<double,dim> v;  \n    v[0]=0; v[1]=0; factory.insertVertex(v);\n    v[0]=0.5; v[1]=0; factory.insertVertex(v);\n    v[0]=1; v[1]=0; factory.insertVertex(v);\n    v[0]=1; v[1]=0.499; factory.insertVertex(v);\n    v[0]=0.5; v[1]=0.5; factory.insertVertex(v);\n    v[0]=1; v[1]=0.501; factory.insertVertex(v);\n    v[0]=1; v[1]=1; factory.insertVertex(v);\n    v[0]=0.5; v[1]=1; factory.insertVertex(v);\n    v[0]=0; v[1]=1; factory.insertVertex(v);\n    v[0]=0; v[1]=0.5; factory.insertVertex(v);\n    // triangle defined by 3 vertex indices\n    std::vector<unsigned int> vid(3);\n    Dune::GeometryType gt(Dune::GeometryType::simplex,2);\n    vid[0]=0; vid[1]=1; vid[2]=9; factory.insertElement(gt,vid);\n    vid[0]=1; vid[1]=4; vid[2]=9; factory.insertElement(gt,vid);\n    vid[0]=1; vid[1]=3; vid[2]=4; factory.insertElement(gt,vid);\n    vid[0]=1; vid[1]=2; vid[2]=3; factory.insertElement(gt,vid);\n    vid[0]=5; vid[1]=6; vid[2]=7; factory.insertElement(gt,vid);\n    vid[0]=4; vid[1]=5; vid[2]=7; factory.insertElement(gt,vid);\n    vid[0]=4; vid[1]=7; vid[2]=9; factory.insertElement(gt,vid);\n    vid[0]=7; vid[1]=8; vid[2]=9; factory.insertElement(gt,vid);\n    std::unique_ptr<Grid> grid( factory.createGrid() ) ;\n    // the coarse grid will be refined \n    grid->globalRefine(refinements);\n    // some information on the refined mesh\n    if(verbosity > 0) {\n      std::cout << std::endl;\n      std::cout << \"Grid: \" << grid->size(0) << \" triangles, \" << std::endl;\n      std::cout << \"      \" << grid->size(1) << \" edges, \" << std::endl;\n      std::cout << \"      \" << grid->size(2) << \" points\" << std::endl << std::endl;\n    }\n      \n    // a gridmanager is constructed \n    // as connector between geometric and algebraic information\n    GridManager<Grid> gridManager(std::move(grid));  \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[i]);\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    Functional F;\n    \n    if(verbosity > 0) {\n      std::cout << \"no of variables = \" << nvars << std::endl;\n      std::cout << \"no of equations = \" << neq   << std::endl;\n    }\n    \n    //construct Galerkin representation\n    Assembler assembler(gridManager,spaces);\n    \n    // keep the solutions of different refinements\n    std::vector<VariableSet::VariableSet> xx;\n    xx.reserve(maxRefSteps);\n    for(int i=0;i<maxRefSteps;i++) {\n      xx.push_back(VariableSet::VariableSet(variableSet));\n    }\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    tol[0] = std::make_pair(atol,rtol); \n    if(verbosity > 0) {\n      std::cout << std::endl << \"Accuracy: atol = \" << atol << \",  rtol = \" << rtol << std::endl;\n    }\n\n    bool accurate = true;\n    int refSteps = -1;\n\n    //keep degrees of freedom\n    std::vector<double> dofs;\n    dofs.reserve(maxRefSteps);\n    \n    do {\n      refSteps++;\n      if(refSteps >= maxRefSteps || size > 2e5) \n      {\n        refSteps--;\n        std::cout << \"maxRefSteps = \" << maxRefSteps << \",  size = \" << size << std::endl;\n        break;\n      }\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>0) std::cout << \"assemble: \" << (double)assembTimer.elapsed().user/1e9 << \"s\\n\";\n\n      if (direct)\n      {\n        solverTypeII = directSolver;\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>0) std::cout << \"direct solve: \" << (double)(directTimer.elapsed().user)/1e9 << \"s\\n\";\n      }\n      else\n      {\n        solverTypeII = \"CG, \" + preconditioner;\n        int iteSteps = getParameter(pt, \"solver.iteMax\", 1000);\n        double iteEps = getParameter(pt, \"solver.iteEps\", 1.0e-10);\n        //if ( verbosity>0) std::cout << \"iterative solver: steps = \" << iteSteps << \n        //   \", eps = \" << iteEps << std::endl;\n        boost::timer::cpu_timer iteTimer;\n        Dune::InverseOperatorResult res;\n        const DefaultDualPairing<LinearSpace,LinearSpace> defaultScalarProduct{};\n        StrakosTichyPTerminationCriterion<double> termination(iteEps,iteSteps);\n        int lookAhead = getParameter(pt, \"solver.lookAhead\", 3);\n        termination.setLookAhead(lookAhead);\n        \n        switch (precondType)\n        {\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::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::BOOMERAMG:\n          default:\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            //Dune::LoopSolver<LinearSpace> cg(A,BoomerAMGPrecon,iteEps,iteSteps,verbosity);\n            CG<LinearSpace,LinearSpace> cg(A,BoomerAMGPrecon,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      // VariableSet::VariableSet xx may be used beyond the do...while loop  \n      xx[refSteps].data = x.data;\n      dofs.push_back(size);\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 = variableSet.degreesOfFreedom(0,1);\n      if ( verbosity>0) std::cout << \"new mesh: nnz = \" << nnz << \", dof = \" << size << std::endl;\n            \n    }  while (!accurate); \n    \n    //calculate and keep errors\n    if ( refSteps < 3 ) {\n      message << \"Test failed: refSteps = \" << refSteps << \" is too small\" ;\n      break;}\n    else {\n      \n      std::vector<double> ress(refSteps-2);\n      for(int i = 0; i < refSteps-2;i++) {\n        L2Norm l2;\n        xx[i] -= xx[refSteps];\n        ress[i] = l2( boost::fusion::at_c<0>(xx[i].data) );\n      }\n      \n      if(verbosity > 0) {\n        std::cout << \"error = \" << ress.back() << std::endl;\n      }\n  \n      if(verbosity > 0) {\n      std::cout << \"error in l2norm: \" << ress.back() << \"  has to be smaller than  \" \n                << errors[i] << std::endl;\n      }\n      \n      // query whether error is low enough\n      if(ress.back() > errors[i]) {\n        valid = false;\n        message << \"Test failed: The error was too high at the test with ansatz functions of order \" \n                << order[i] << \".\";\n        message << \"\\n             err = \" << ress.back() << \", threshold = \" << errors[i] << \".\";\n      }\n      \n      // calculate order of convergence by linear regression\n      double a11=0, a12=0, a22=ress.size(), b1=0,b2=0;\n      for(int j=0;j<ress.size();j++) {\n        dofs[j] = std::log(dofs[j]);\n        ress[j] = std::log(ress[j]);\n        a11 += dofs[j]*dofs[j];\n        a12 += dofs[j];\n        b1 += dofs[j]*ress[j];\n        b2 += ress[j];\n      }\n      double det = 1.0/(a11*a22-a12*a12);\n      double convOrd = det*(a22*b1-a12*b2);\n      double logc = det*(a11*b2-a12*b1);\n      convOrd = -convOrd;\n      if(verbosity > 0) {\n        std::cout << \"error = c*(1/N)^p with\" << std::endl;\n        std::cout << \"p = \" << convOrd << std::endl;\n        std::cout << \"log(c) = \" << logc << std::endl;\n      }\n      if(convOrd < conOrder[i]) {\n        valid = false;\n        message << \"Test failed: The order of convergence was too low at the test with ansatz functions of order \" << order[i] << \".\";\n      }\n    }\n  }\n  \n  std::cout << \"End test program\" << std::endl;\n  std::cout << message.str() << std::endl;\n  if(result) {\n    std::string description = \"Test with embedded error estimation, einspringende Ecke. Used \" \n                              + solverTypeI + \" solver \" + solverTypeII + \":\";\n    std::ofstream outfile(\"../testResult.txt\", std::ofstream::out | std::ofstream::app);\n    outfile << description << std::endl << message.str() << std::endl << std::endl;\n    outfile.close();\n  }\n}\n", "meta": {"hexsha": "8a77e92f697968868b6a12dfcc6826804c9a01ab", "size": 17180, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tests/reentrantCorner/reentrantCorner.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/tests/reentrantCorner/reentrantCorner.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/tests/reentrantCorner/reentrantCorner.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": 42.315270936, "max_line_length": 142, "alphanum_fraction": 0.6137369034, "num_tokens": 4909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.5930972173168055}}
{"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": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_basic_types.h>\n#include <OpenTissue/collision/gjk/gjk.h>\n#include <OpenTissue/core/geometry/geometry_obb.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n#include <cmath>\n\nusing namespace OpenTissue;\n\nBOOST_AUTO_TEST_SUITE(opentissue_collision_gjk);\n\nBOOST_AUTO_TEST_CASE(face_aligned_separated_boxes)\n{\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  typedef math_types::vector3_type                         vector3_type;\n  typedef math_types::quaternion_type                      quaternion_type;\n  typedef math_types::coordsys_type                        coordsys_type;\n  typedef math_types::real_type                            real_type;\n\n  vector3_type p_a;                   \n  vector3_type p_b;                   \n  real_type tol = 0.01;\n  OpenTissue::gjk::obsolete::detail::GJK<vector3_type > gjk;          ///< GJK collision detection Algorithm.\n  OpenTissue::geometry::OBB<math_types> A;\n  OpenTissue::geometry::OBB<math_types> B;\n\n  A.init(1.0,1.0,1.0);\n  B.init(1.0,1.0,1.0);\n\n  vector3_type vector_px = vector3_type( 1.0, 0.0, 0.0);\n  vector3_type vector_mx = vector3_type(-1.0, 0.0, 0.0);\n  vector3_type vector_py = vector3_type( 0.0, 1.0, 0.0);\n  vector3_type vector_my = vector3_type( 0.0,-1.0, 0.0);\n  vector3_type vector_pz = vector3_type( 0.0, 0.0, 1.0);\n  vector3_type vector_mz = vector3_type( 0.0, 0.0,-1.0);\n\n  coordsys_type  Awcs = coordsys_type( vector_mx, quaternion_type());   \n  coordsys_type  Bwcs = coordsys_type( vector_px, quaternion_type());      \n  A.place(Awcs);\n  B.place(Bwcs);\n  gjk.get_closest_points(A,B,p_a,p_b);\n  real_type distance = length( p_a - p_b);\n  BOOST_CHECK_CLOSE(distance, 1.0, tol);\n  BOOST_CHECK( !gjk.is_intersecting(A,B,vector_px) );\n  BOOST_CHECK( !gjk.get_common_point(A,B,vector_px,p_a,p_b) );\n\n  vector_px = vector3_type( 1.0, 0.0, 0.0);\n  vector_mx = vector3_type(-1.0, 0.0, 0.0);\n  vector_py = vector3_type( 0.0, 1.0, 0.0);\n  vector_my = vector3_type( 0.0,-1.0, 0.0);\n  vector_pz = vector3_type( 0.0, 0.0, 1.0);\n  vector_mz = vector3_type( 0.0, 0.0,-1.0);\n  Awcs = coordsys_type( vector_px, quaternion_type());   \n  Bwcs = coordsys_type( vector_mx, quaternion_type());      \n  A.place(Awcs);\n  B.place(Bwcs);\n  gjk.get_closest_points(A,B,p_a,p_b);\n  distance = length( p_a - p_b);\n  BOOST_CHECK_CLOSE(distance, 1.0, tol);\n  BOOST_CHECK( !gjk.is_intersecting(A,B,vector_px) );\n  BOOST_CHECK( !gjk.get_common_point(A,B,vector_px,p_a,p_b) );\n\n  vector_px = vector3_type( 1.0, 0.0, 0.0);\n  vector_mx = vector3_type(-1.0, 0.0, 0.0);\n  vector_py = vector3_type( 0.0, 1.0, 0.0);\n  vector_my = vector3_type( 0.0,-1.0, 0.0);\n  vector_pz = vector3_type( 0.0, 0.0, 1.0);\n  vector_mz = vector3_type( 0.0, 0.0,-1.0);\n  Awcs = coordsys_type( vector_py, quaternion_type());   \n  Bwcs = coordsys_type( vector_my, quaternion_type());      \n  A.place(Awcs);\n  B.place(Bwcs);\n  gjk.get_closest_points(A,B,p_a,p_b);\n  distance = length( p_a - p_b);\n  BOOST_CHECK_CLOSE(distance, 1.0, tol);\n  BOOST_CHECK( !gjk.is_intersecting(A,B,vector_px) );\n  BOOST_CHECK( !gjk.get_common_point(A,B,vector_px,p_a,p_b) );\n\n  vector_px = vector3_type( 1.0, 0.0, 0.0);\n  vector_mx = vector3_type(-1.0, 0.0, 0.0);\n  vector_py = vector3_type( 0.0, 1.0, 0.0);\n  vector_my = vector3_type( 0.0,-1.0, 0.0);\n  vector_pz = vector3_type( 0.0, 0.0, 1.0);\n  vector_mz = vector3_type( 0.0, 0.0,-1.0);\n  Awcs = coordsys_type( vector_my, quaternion_type());   \n  Bwcs = coordsys_type( vector_py, quaternion_type());      \n  A.place(Awcs);\n  B.place(Bwcs);\n  gjk.get_closest_points(A,B,p_a,p_b);\n  distance = length( p_a - p_b);\n  BOOST_CHECK_CLOSE(distance, 1.0, tol);\n  BOOST_CHECK( !gjk.is_intersecting(A,B,vector_px) );\n  BOOST_CHECK( !gjk.get_common_point(A,B,vector_px,p_a,p_b) );\n\n  vector_px = vector3_type( 1.0, 0.0, 0.0);\n  vector_mx = vector3_type(-1.0, 0.0, 0.0);\n  vector_py = vector3_type( 0.0, 1.0, 0.0);\n  vector_my = vector3_type( 0.0,-1.0, 0.0);\n  vector_pz = vector3_type( 0.0, 0.0, 1.0);\n  vector_mz = vector3_type( 0.0, 0.0,-1.0);\n  Awcs = coordsys_type( vector_pz, quaternion_type());   \n  Bwcs = coordsys_type( vector_mz, quaternion_type());      \n  A.place(Awcs);\n  B.place(Bwcs);\n  gjk.get_closest_points(A,B,p_a,p_b);\n  distance = length( p_a - p_b);\n  BOOST_CHECK_CLOSE(distance, 1.0, tol);\n  BOOST_CHECK( !gjk.is_intersecting(A,B,vector_px) );\n  BOOST_CHECK( !gjk.get_common_point(A,B,vector_px,p_a,p_b) );\n\n  vector_px = vector3_type( 1.0, 0.0, 0.0);\n  vector_mx = vector3_type(-1.0, 0.0, 0.0);\n  vector_py = vector3_type( 0.0, 1.0, 0.0);\n  vector_my = vector3_type( 0.0,-1.0, 0.0);\n  vector_pz = vector3_type( 0.0, 0.0, 1.0);\n  vector_mz = vector3_type( 0.0, 0.0,-1.0);\n  Awcs = coordsys_type( vector_mz, quaternion_type());   \n  Bwcs = coordsys_type( vector_pz, quaternion_type());      \n  A.place(Awcs);\n  B.place(Bwcs);\n  gjk.get_closest_points(A,B,p_a,p_b);\n  distance = length( p_a - p_b);\n  BOOST_CHECK_CLOSE(distance, 1.0, tol);\n  BOOST_CHECK( !gjk.is_intersecting(A,B,vector_px) );\n  BOOST_CHECK( !gjk.get_common_point(A,B,vector_px,p_a,p_b) );\n}\n\nBOOST_AUTO_TEST_CASE(non_aligned_cases)\n{\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  typedef math_types::vector3_type                         vector3_type;\n  typedef math_types::quaternion_type                      quaternion_type;\n  typedef math_types::coordsys_type                        coordsys_type;\n  typedef math_types::real_type                            real_type;\n\n  vector3_type p_a;                   \n  vector3_type p_b;                   \n  real_type tol = 0.01;\n  OpenTissue::gjk::obsolete::detail::GJK<vector3_type > gjk;          ///< GJK collision detection Algorithm.\n  OpenTissue::geometry::OBB<math_types> A;\n  OpenTissue::geometry::OBB<math_types> B;\n\n  A.init(1.0,1.0,1.0);\n  B.init(1.0,1.0,1.0);\n\n  real_type sqrt_half = std::sqrt(0.5);\n  real_type test_distance = 1.0 - (sqrt_half - 0.5);\n\n  quaternion_type q;\n  q.Rz( math_types::value_traits::pi()/4.0 );\n\n  vector3_type vector_px = vector3_type( 1.0, 0.0, 0.0);\n  vector3_type vector_mx = vector3_type(-1.0, 0.0, 0.0);\n  coordsys_type  Awcs = coordsys_type( vector_mx, quaternion_type());   \n  coordsys_type  Bwcs = coordsys_type( vector_px, q);      \n  A.place(Awcs);\n  B.place(Bwcs);\n  gjk.get_closest_points(A,B,p_a,p_b);\n  real_type distance = length( p_a - p_b);\n  BOOST_CHECK_CLOSE(distance, test_distance, tol);\n  BOOST_CHECK( !gjk.is_intersecting(A,B,vector_px) );\n  BOOST_CHECK( !gjk.get_common_point(A,B,vector_px,p_a,p_b) );\n\n  vector_px = vector3_type( 1.0, 0.0, 0.0);\n  vector_mx = vector3_type(-1.0, 0.0, 0.0);\n  Awcs = coordsys_type( vector_mx, quaternion_type());   \n  Bwcs = coordsys_type( vector3_type( 1.0,0.1,0.1), q);      \n  A.place(Awcs);\n  B.place(Bwcs);\n  gjk.get_closest_points(A,B,p_a,p_b);\n  distance = length( p_a - p_b);\n  BOOST_CHECK_CLOSE(distance, test_distance, tol);\n  BOOST_CHECK( !gjk.is_intersecting(A,B,vector_px) );\n  BOOST_CHECK( !gjk.get_common_point(A,B,vector_px,p_a,p_b) );\n\n  vector_px = vector3_type( 1.0, 0.0, 0.0);\n  vector_mx = vector3_type(-1.0, 0.0, 0.0);\n  Awcs = coordsys_type( vector3_type(-1.0,0.0,0.5), quaternion_type());   \n  Bwcs = coordsys_type( vector_px, q);      \n  A.place(Awcs);\n  B.place(Bwcs);\n  gjk.get_closest_points(A,B,p_a,p_b);\n  distance = length( p_a - p_b);\n  BOOST_CHECK_CLOSE(distance, test_distance, tol);\n  BOOST_CHECK( !gjk.is_intersecting(A,B,vector_px) );\n  BOOST_CHECK( !gjk.get_common_point(A,B,vector_px,p_a,p_b) );\n\n  vector_px = vector3_type( 1.0, 0.0, 0.0);\n  vector_mx = vector3_type(-1.0, 0.0, 0.0);\n  Awcs = coordsys_type( vector3_type(-1.0,0.0,-0.5), quaternion_type());   \n  Bwcs = coordsys_type( vector3_type( 1.0,0.0,0.5), quaternion_type());      \n  A.place(Awcs);\n  B.place(Bwcs);\n  gjk.get_closest_points(A,B,p_a,p_b);\n  distance = length( p_a - p_b);\n  BOOST_CHECK_CLOSE(distance, 1.0, tol);\n  BOOST_CHECK( !gjk.is_intersecting(A,B,vector_px) );\n  BOOST_CHECK( !gjk.get_common_point(A,B,vector_px,p_a,p_b) );\n}\n\nBOOST_AUTO_TEST_CASE(penetrating_cases)\n{\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  typedef math_types::vector3_type                         vector3_type;\n  typedef math_types::quaternion_type                      quaternion_type;\n  typedef math_types::coordsys_type                        coordsys_type;\n  typedef math_types::real_type                            real_type;\n\n  vector3_type p_a;                   \n  vector3_type p_b;                   \n\n  OpenTissue::gjk::obsolete::detail::GJK<vector3_type > gjk;          ///< GJK collision detection Algorithm.\n  OpenTissue::geometry::OBB<math_types> A;\n  OpenTissue::geometry::OBB<math_types> B;\n\n  A.init(1.0,1.0,1.0);\n  B.init(1.0,1.0,1.0);\n\n  vector3_type vector_px = vector3_type( 1.0, 0.0, 0.0);\n  coordsys_type  Awcs = coordsys_type( vector3_type( 0.0,0.0,0.0), quaternion_type());   \n  coordsys_type  Bwcs = coordsys_type( vector3_type( 0.25,0.25,0.25), quaternion_type());      \n  A.place(Awcs);\n  B.place(Bwcs);\n  gjk.get_closest_points(A,B,p_a,p_b);\n  real_type distance = length( p_a - p_b);\n  BOOST_CHECK(fabs(distance) < 10e-7);\n  BOOST_CHECK( gjk.is_intersecting(A,B,vector_px) );\n  BOOST_CHECK( gjk.get_common_point(A,B,vector_px,p_a,p_b) );\n\n  B.init(0.9,0.9,0.9);\n\n  vector_px = vector3_type( 1.0, 0.0, 0.0);\n  Awcs = coordsys_type( vector3_type( 0.0,0.0,0.0), quaternion_type());   \n  Bwcs = coordsys_type( vector3_type( 0.0,0.0,0.0), quaternion_type());      \n  A.place(Awcs);\n  B.place(Bwcs);\n\n  gjk.get_closest_points(A,B,p_a,p_b);\n  distance = length( p_a - p_b);\n  BOOST_CHECK(fabs(distance) < 10e-7);\n  BOOST_CHECK( gjk.is_intersecting(A,B,vector_px) );\n  BOOST_CHECK( gjk.get_common_point(A,B,vector_px,p_a,p_b) );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "a491af156d932d8a4a41782ea9d6b9fc66e8936d", "size": 10206, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/collision/gjk/old_gjk/src/unit_gjk.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/collision/gjk/old_gjk/src/unit_gjk.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/collision/gjk/old_gjk/src/unit_gjk.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 39.4054054054, "max_line_length": 109, "alphanum_fraction": 0.6742112483, "num_tokens": 3423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5930383418510082}}
{"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 * 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#pragma once\n\n#include \"mader_types.hpp\"\n#include <Eigen/Dense>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Convex_hull_traits_3.h>\n#include <decomp_geometry/polyhedron.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Convex_hull_traits_3<K> Traits;\ntypedef Traits::Polyhedron_3 CGAL_Polyhedron_3;\ntypedef K::Segment_3 Segment_3;\ntypedef K::Plane_3 Plane_3;\n// define point creator\ntypedef K::Point_3 Point_3;\ntypedef K::Vector_3 Vector_3;\ntypedef CGAL::Creator_uniform_3<double, Point_3> PointCreator;\n\ntypedef std::vector<CGAL_Polyhedron_3> ConvexHullsOfCurve;\ntypedef std::vector<ConvexHullsOfCurve> ConvexHullsOfCurves;\n\nnamespace cu  // cgal utils\n{\nstruct Plane_equation\n{\n  template <class Facet>\n  typename Facet::Plane_3 operator()(Facet& f)\n  {\n    typename Facet::Halfedge_handle h = f.halfedge();\n    typedef typename Facet::Plane_3 Plane;\n    return Plane(h->vertex()->point(), h->next()->vertex()->point(), h->next()->next()->vertex()->point());\n  }\n};\n\nmt::ConvexHullsOfCurves_Std vectorGCALPol2vectorStdEigen(ConvexHullsOfCurves& convexHulls);\n\nvec_E<Polyhedron<3>> vectorGCALPol2vectorJPSPol(ConvexHullsOfCurves& convex_hulls_of_curves);\n\nCGAL_Polyhedron_3 convexHullOfPoints(const std::vector<Point_3>& points);\n\nmt::Edges vectorGCALPol2edges(const ConvexHullsOfCurves& convexHulls);\n}  // namespace cu", "meta": {"hexsha": "9cd381207d53c6556b6e519191c397546473386c", "size": 1805, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mader/include/cgal_utils.hpp", "max_stars_repo_name": "shubham-shahh/mader", "max_stars_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 222.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T01:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:46:02.000Z", "max_issues_repo_path": "mader/include/cgal_utils.hpp", "max_issues_repo_name": "shubham-shahh/mader", "max_issues_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-02-18T15:19:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T14:19:54.000Z", "max_forks_repo_path": "mader/include/cgal_utils.hpp", "max_forks_repo_name": "shubham-shahh/mader", "max_forks_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T01:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T22:46:04.000Z", "avg_line_length": 35.3921568627, "max_line_length": 107, "alphanum_fraction": 0.71966759, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5930383325776282}}
{"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": "// Copyright Andr\u00e1s Vukics 2006\u20132020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#include \"MathExtensions.h\"\n\n#include <boost/math/special_functions/factorials.hpp>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_sf.h>\n\n#include <stdexcept>\n\nnamespace mathutils {\n  \nconst double PI(M_PI);\nconst double SQRTPI(M_SQRTPI);\nconst double EULER(M_E);\n\nint sign(double x) {return GSL_SIGN(x);}\nint fcmp(double x, double y, double eps) {return gsl_fcmp(x,y,eps);}\n\ndouble sqr(double x) {return gsl_pow_2(x);}\n\ndouble sqrAbs(dcomp x) {return sqr(real(x))+sqr(imag(x));} // saves the sqrt\n\ndouble fact(unsigned n)\n{\n  if (n>GSL_SF_FACT_NMAX) throw std::out_of_range(\"Factorial of\"+std::to_string(n));\n  return gsl_sf_fact(n);\n}\n\ndouble choose(unsigned n, unsigned m)\n{\n  return gsl_sf_choose(n,m);\n}\n\ndcomp coherentElement(unsigned long n, dcomp alpha)\n{\n  using namespace boost::math;\n  return n ? n<max_factorial<double>::value ? pow(alpha,n)/sqrt(factorial<double>(n)) \n                                            : pow(2*n*PI,-.25)*pow(alpha/sqrt(n/EULER),n)\n           : 1.;\n}\n\n\n} // mathutils\n", "meta": {"hexsha": "4031cade7dd43dc0f7928f2a315c8e7797347300", "size": 1166, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDutils/MathExtensions.cc", "max_stars_repo_name": "bartoszek/cppqed", "max_stars_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CPPQEDutils/MathExtensions.cc", "max_issues_repo_name": "bartoszek/cppqed", "max_issues_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CPPQEDutils/MathExtensions.cc", "max_forks_repo_name": "bartoszek/cppqed", "max_forks_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_forks_repo_licenses": ["BSL-1.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.347826087, "max_line_length": 132, "alphanum_fraction": 0.6886792453, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5929677497967286}}
{"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": "#include <tiny_math_types.h>\n#include <tiny_type_traits.h>\n#include <tiny_quaternion.h>\n#include <tiny_quaternion_functions.h>\n#include <tiny_matrix_functions.h>\n#include <tiny_euler_angles.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n\ntypedef tiny::MathTypes<double>  MT;\ntypedef MT::quaternion_type      Q;\ntypedef MT::matrix3x3_type       M;\ntypedef MT::real_type            T;\ntypedef MT::value_traits         VT;\n\n\nvoid do_zyz_test( T const & phi_in, T const & psi_in, T const & theta_in)\n{\n  Q Q_in;\n  Q Q_out;\n  Q identity = Q::identity();\n  Q Qz1;\n  Q Qy;\n  Q Qz2;\n\n  T const too_small = 10e-7;\n\n  T phi_out   = 0.0;\n  T psi_out   = 0.0;\n  T theta_out = 0.0;\n\n  Qz1 = Q::Rz(theta_in);\n  Qy = Q::Ry(psi_in);\n  Qz2 = Q::Rz(phi_in);\n\n  Q_in = tiny::prod( Qz2 , tiny::prod( Qy , Qz1) );\n\n  tiny::ZYZ_euler_angles(Q_in,phi_out,psi_out,theta_out);\n\n  if(psi_in > 0.0)\n  {\n    // we only want to do this if we are not in a gimbal lock\n    Qz1 = Q::Rz(theta_out);\n    Qy = Q::Ry(psi_out);\n    Qz2 = Q::Rz(phi_out);\n    Q_out = tiny::prod( Qz2 , tiny::prod( Qy , Qz1) );\n    identity = tiny::prod( tiny::conj(Q_out), Q_in );\n\n    T const s = fabs( fabs(identity.real())  - 1.0 );\n    T const v0 = fabs(identity.imag()(0));\n    T const v1 = fabs(identity.imag()(1));\n    T const v2 = fabs(identity.imag()(2));\n\n    BOOST_CHECK( s < too_small);\n    BOOST_CHECK( v0 < too_small);\n    BOOST_CHECK( v1 < too_small);\n    BOOST_CHECK( v2 < too_small);\n\n    T const dphi = fabs(phi_in - phi_out);\n    T const dpsi = fabs(psi_in - psi_out);\n    T const dtheta = fabs(theta_in - theta_out);\n    BOOST_CHECK( dphi < too_small);\n    BOOST_CHECK( dpsi < too_small);\n    BOOST_CHECK( dtheta < too_small);\n  }\n  else\n  {\n    // In gimbal lock phi and theta behaves strangely\n    BOOST_CHECK_CLOSE( 0.0, theta_out, 0.01);\n    double const dpsi = fabs(psi_out);\n    BOOST_CHECK( dpsi < too_small);\n\n    T new_phi = phi_in + theta_in;\n    T const pi     = 3.1415926535897932384626433832795;\n    T const two_pi = 2.0*pi;\n    while(new_phi>pi) new_phi -= two_pi;\n    while(new_phi<-pi) new_phi += two_pi;\n\n    T const dphi = fabs(new_phi - phi_out);\n    BOOST_CHECK( dphi < too_small);\n  }\n}\n\n\nvoid SAFE_CHECK_CLOSE( double const & l, double const & r, double const tol  )\n{\n  using std::fabs;\n\n  double const ALMOST_ZERO = 10e-10;\n\n  if( fabs(l) < ALMOST_ZERO || fabs(r) < ALMOST_ZERO )\n    BOOST_CHECK( fabs(l-r) < ALMOST_ZERO );\n  else\n    BOOST_CHECK_CLOSE(l, r, tol);\n}\n\n\nvoid do_xyz_test( T const & alpha_in, T const & beta_in, T const & gamma_in)\n{\n  // Q Qx   = Q::Rx(alpha_in);\n  // Q Qy   = Q::Ry(beta_in);\n  // Q Qz   = Q::Rz(gamma_in);\n  // Q Q_in = tiny::prod( Qz, tiny::prod( Qy , Qx) );\n  // M R_in = tiny::make(Q_in);\n\n  M const Rx_in = M::Rx(alpha_in);\n  M const Ry_in = M::Ry(beta_in);\n  M const Rz_in = M::Rz(gamma_in);\n  M const R_in  = Rz_in * Ry_in * Rx_in;\n\n  double alpha_out = 0.0;\n  double beta_out  = 0.0;\n  double gamma_out = 0.0;\n\n  tiny::XYZ_euler_angles(R_in, alpha_out, beta_out, gamma_out);\n\n  M const Rx_out = M::Rx(alpha_out);\n  M const Ry_out = M::Ry(beta_out);\n  M const Rz_out = M::Rz(gamma_out);\n  M const R_out  = Rz_out * Ry_out * Rx_out;\n\n  {\n    SAFE_CHECK_CLOSE(R_in(0,0), R_out(0,0), 0.1);\n    SAFE_CHECK_CLOSE(R_in(0,1), R_out(0,1), 0.1);\n    SAFE_CHECK_CLOSE(R_in(0,2), R_out(0,2), 0.1);\n    SAFE_CHECK_CLOSE(R_in(1,0), R_out(1,0), 0.1);\n    SAFE_CHECK_CLOSE(R_in(1,1), R_out(1,1), 0.1);\n    SAFE_CHECK_CLOSE(R_in(1,2), R_out(1,2), 0.1);\n    SAFE_CHECK_CLOSE(R_in(2,0), R_out(2,0), 0.1);\n    SAFE_CHECK_CLOSE(R_in(2,1), R_out(2,1), 0.1);\n    SAFE_CHECK_CLOSE(R_in(2,2), R_out(2,2), 0.1);\n  }\n\n}\n\n\nBOOST_AUTO_TEST_SUITE(tiny_euler_angles);\n\nBOOST_AUTO_TEST_CASE(ZYZ)\n{\n  size_t N = 15;\n\n  double const pi     = 3.1415926535897932384626433832795;\n  double const two_pi = 2.0*pi;\n  double const delta = (two_pi)/(N-1);\n\n  double phi = -pi+delta;\n  for(;phi<pi;)\n  {\n    double psi = 0.0;\n    for(;psi<pi;)\n    {\n      double theta = -pi+delta;\n      for(;theta<pi;)\n      {\n        do_zyz_test( phi, psi, theta );\n        theta += delta;\n      }\n      psi += delta;\n    }\n    phi += delta;\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(XYZ)\n{\n  double const pi     = VT::pi();\n  unsigned int N      = 40;\n  double const dpi    = 2.0*pi/(N-1);\n\n  for (unsigned int i = 0; i < N;++i)\n  {\n    for (unsigned int j = 0; j < N;++j)\n    {\n      for (unsigned int k = 0; k < N;++k)\n      {\n        double const alpha = -pi + i*dpi;\n        double const beta  = (-pi + j*dpi)/2.0;\n        double const gamma = -pi + k*dpi;\n\n        do_xyz_test( alpha, beta, gamma );\n      }\n    }\n  }\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "95f8d2e04bca87b808b1e0461dbf0fa0fde8308c", "size": 4776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_euler_angles/tiny_euler_angles.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_euler_angles/tiny_euler_angles.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_euler_angles/tiny_euler_angles.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4923076923, "max_line_length": 78, "alphanum_fraction": 0.6141122278, "num_tokens": 1631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5929451986464612}}
{"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": "#include <boost/simd/algorithm.hpp>\n#include <boost/simd/pack.hpp>\n\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/memory/allocator.hpp>\n\n#include <chrono>\n#include <cstdlib>\n#include <iostream>\n#include <limits>\n#include <vector>\n\nnamespace bs = boost::simd;\nusing pack_t = bs::pack<float>;\n\n//! [neural-rec]\nstruct activation_function_rec\n{\n  template <typename T>\n  BOOST_FORCEINLINE T operator()(T const& a)\n  {\n    return bs::rec(T(1) + bs::exp(a));\n  }\n};\n//! [neural-rec]\n\n//! [neural-struct]\nstruct activation_function\n{\n  template <typename T>\n  BOOST_FORCEINLINE T operator()(T const& a)\n  {\n    return T(1) / (T(1) + bs::exp(a));\n  }\n};\n//! [neural-struct]\n\nint main(int argc, char** argv)\n{\n  using T  = float;\n  int size = std::atoi(argv[1]);\n  std::vector<T, bs::allocator<T>> activations(size);\n  std::vector<T, bs::allocator<T>> results(size);\n\n  std::generate(activations.begin(), activations.end(),\n                []() { return (T)std::rand() / std::numeric_limits<int>::max(); });\n\n  auto t0 = std::chrono::high_resolution_clock::now();\n  //! [neural-scalar]\n  std::transform(activations.data(), activations.data() + activations.size(), results.data(),\n                 [](T const& a) { return T(1) / (T(1) + std::exp(a)); });\n  //! [neural-scalar]\n  auto t1 = std::chrono::high_resolution_clock::now();\n  std::cout << \"Scalar std::exp time: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count() << std::endl;\n\n  t0 = std::chrono::high_resolution_clock::now();\n  //! [neural-scalar-bs]\n  std::transform(activations.data(), activations.data() + activations.size(), results.data(),\n                 [](T const& a) { return T(1) / (T(1) + bs::exp(a)); });\n  //! [neural-scalar-bs]\n  t1 = std::chrono::high_resolution_clock::now();\n  std::cout << \"Scalar bs::exp time: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count() << std::endl;\n\n  t0 = std::chrono::high_resolution_clock::now();\n  //! [neural-transform]\n  bs::transform(activations.data(), activations.data() + activations.size(), results.data(),\n                activation_function{});\n  //! [neural-transform]\n  t1 = std::chrono::high_resolution_clock::now();\n  std::cout << \"SIMD time: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count() << std::endl;\n\n  t0 = std::chrono::high_resolution_clock::now();\n\n  //! [neural-transform-rec]\n  bs::transform(activations.data(), activations.data() + activations.size(), results.data(),\n                activation_function{});\n  //! [neural-transform-rec]\n  t1 = std::chrono::high_resolution_clock::now();\n  std::cout << \"SIMD rec time: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count() << std::endl;\n}\n", "meta": {"hexsha": "064829b296a05ee99bc8ec801e40971c72b2b2ff", "size": 2853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/neural_net.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/neural_net.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/neural_net.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": 32.7931034483, "max_line_length": 99, "alphanum_fraction": 0.6277602524, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5929236556701275}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/module/bessel.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n#include <eve/detail/diff_div.hpp>\n\nEVE_TEST_TYPES( \"Check return types of sph_bessel_y1\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  TTS_EXPR_IS(eve::sph_bessel_y1(T(0)), T);\n  TTS_EXPR_IS(eve::sph_bessel_y1(v_t(0)), v_t);\n};\n\n EVE_TEST( \"Check behavior of sph_bessel_y1 on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.0, 5.5),\n                              eve::test::randoms(5.5, 9.5),\n                              eve::test::randoms(9.5, 60.0))\n         )\n   <typename T>(T const& a0, T const& a1, T const& a2)\n{\n  using v_t = eve::element_type_t<T>;\n  auto eve__sph_bessel_y1 =  [](auto x) { return eve::sph_bessel_y1(x); };\n  auto std__sph_bessel_y1 =  [](auto x)->v_t { return boost::math::sph_neumann(1u, double(x)); };\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__sph_bessel_y1(eve::inf(eve::as<v_t>())), eve::zero(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_y1(eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_y1(eve::inf(eve::as< T>())),  eve::zero(eve::as< T>()), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_y1(eve::nan(eve::as< T>())), eve::nan(eve::as< T>()), 0);\n  }\n  TTS_ULP_EQUAL(eve__sph_bessel_y1(v_t(500)), std__sph_bessel_y1(v_t(500)), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1(v_t(10)), std__sph_bessel_y1(v_t(10))  , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1(v_t(5)),  std__sph_bessel_y1(v_t(5))   , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1(v_t(2)),  std__sph_bessel_y1(v_t(2))   , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1(v_t(1.5)),std__sph_bessel_y1(v_t(1.5)) , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1(v_t(0.5)),std__sph_bessel_y1(v_t(0.5)) , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1(v_t(1)),  std__sph_bessel_y1(v_t(1))   , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1(v_t(0)),  eve::minf(eve::as<v_t>()), 0.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_y1( T(500)),  T(std__sph_bessel_y1(v_t(500)) ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1( T(10)) ,  T(std__sph_bessel_y1( v_t(10)) ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1( T(5))  ,  T(std__sph_bessel_y1( v_t(5))  ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1( T(2))  ,  T(std__sph_bessel_y1( v_t(2))  ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1( T(1.5)),  T(std__sph_bessel_y1( v_t(1.5))), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1( T(0.5)),  T(std__sph_bessel_y1( v_t(0.5))), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1( T(1))  ,  T(std__sph_bessel_y1( v_t(1))  ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1( T(0))  , eve::minf(eve::as< T>()), 0.0);\n\n\n  TTS_ULP_EQUAL(eve__sph_bessel_y1(a0), map(std__sph_bessel_y1, a0), 130.0); //BMI2 ??\n  TTS_ULP_EQUAL(eve__sph_bessel_y1(a1), map(std__sph_bessel_y1, a1), 20.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y1(a2), map(std__sph_bessel_y1, a2), 20.0);\n\n};\n\nEVE_TEST( \"Check behavior of diff(sph_bessel_y1) on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(1.0, 10.0))\n        )\n  <typename T>(T a0 )\n{\n  auto eve__diff_bessel_y1 =  [](auto x) { return eve::diff(eve::sph_bessel_y1)(x); };\n  auto df = [](auto x){return eve::detail::centered_diffdiv(eve::sph_bessel_y1, x); };\n\n  TTS_RELATIVE_EQUAL(eve__diff_bessel_y1(a0),   df(a0), 2.0e-2);\n};\n", "meta": {"hexsha": "387b5bb3a007796fc0471f384c94d5b1f409a38e", "size": 3785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/bessel/sph_bessel_y1.cpp", "max_stars_repo_name": "clayne/eve", "max_stars_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/bessel/sph_bessel_y1.cpp", "max_issues_repo_name": "clayne/eve", "max_issues_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/bessel/sph_bessel_y1.cpp", "max_forks_repo_name": "clayne/eve", "max_forks_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.9113924051, "max_line_length": 100, "alphanum_fraction": 0.6311756935, "num_tokens": 1488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5929236555296946}}
{"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_STD_HPP_INCLUDED\n#define NDHIST_STATS_STD_HPP_INCLUDED 1\n\n#include <cmath>\n\n#include <boost/python.hpp>\n\n#include <ndhist/ndhist.hpp>\n#include <ndhist/stats/var.hpp>\n\nnamespace ndhist {\nnamespace stats {\n\nnamespace detail {\n\ntemplate <typename AxisValueType, typename WeightValueType>\ndouble\ncalc_axis_std_impl(\n    ndhist const & h\n  , intptr_t const axis\n)\n{\n    return std::sqrt(calc_axis_var_impl<AxisValueType, WeightValueType>(h, axis));\n}\n\n}// namespace detail\n\nnamespace py {\n\n/**\n * @brief Calculates the standard deviation (std) along the given axis of the\n *     given ndhist object. As in statistics, the standard deviation is defined\n *     as :math:`\\sqrt{V[x]}`, where :math:`V[x]` is the variance.\n *     This function generates a projection along the given axis and then\n *     calculates the standard deviation.\n *     If None is given as axis, the standard deviation for all individual axes\n *     of the ndhist object will be calculated and returned as a tuple.\n *     But if the dimensionality of the ndhist object is 1, a scalar value is\n *     returned.\n *\n * @note This function is only defined for ndhist objects with POD axis values\n *     AND POD weight values.\n */\nboost::python::object\nstd(\n    ndhist const & h\n  , boost::python::object const & axis = boost::python::object()\n);\n\n}// namespace py\n\n}// namespace stats\n}// namespace ndhist\n\n#endif // !NDHIST_STATS_STD_HPP_INCLUDED\n", "meta": {"hexsha": "49c3e8d3b330fd7b2e3280d74fdd60cfb6fd3019", "size": 1629, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ndhist/stats/std.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/std.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/std.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.3134328358, "max_line_length": 82, "alphanum_fraction": 0.7084100675, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.592861677851772}}
{"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": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n\n#include <OpenTissue/core/math/math_random.h>\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/optimization/optimization_compute_index_reordering.h>\n#include <OpenTissue/core/math/optimization/optimization_make_mbd_bounds.h>\n#include <OpenTissue/core/math/optimization/non_smooth_newton/optimization_compute_jacobian.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_non_smooth_newton_compute_full_jacobian);\n\nBOOST_AUTO_TEST_CASE(test_case)\n{\n  typedef ublas::vector<size_t>   idx_vector_type;\n  typedef ublas::vector<double>   vector_type;\n  typedef ublas::compressed_matrix<double>   matrix_type;\n  typedef OpenTissue::math::ValueTraits<double> value_traits;\n  typedef double real_type;\n  typedef size_t size_type;\n\n  matrix_type A;\n  vector_type mu,lo,hi;\n  A.resize(10,10,false);\n  mu.resize(10,false);\n  lo.resize(10,false);\n  hi.resize(10,false);\n\n  OpenTissue::math::Random<double> value(0.0,1.0);\n  for(size_t i=0;i<A.size1();++i)\n  {\n    mu(i) = value();\n    lo(i) = value_traits::zero();\n    hi(i) = value_traits::infinity();\n    for(size_t j=0;j<A.size2();++j)\n      A(i,j) = value();\n  }\n\n  idx_vector_type bitmask;\n\n  bitmask.resize(10,false);\n\n  static size_t const in_lower  = 1;\n  static size_t const in_upper  = 2;\n  static size_t const in_active = 4;\n\n  bitmask(0) = in_upper;   // pi = inf\n  bitmask(1) = in_lower;   // pi = 0\n  bitmask(2) = in_active;  // pi = 0\n  bitmask(3) = in_lower;   // pi = inf\n  bitmask(4) = in_active;  // pi = 3\n  bitmask(5) = in_upper;   // pi = 3\n  bitmask(6) = in_active;  // pi = inf\n  bitmask(7) = in_upper;   // pi = 6\n  bitmask(8) = in_lower;   // pi = 6\n  bitmask(9) = in_active;  // pi = inf\n\n  idx_vector_type old2new;\n  idx_vector_type new2old;\n\n  OpenTissue::math::optimization::compute_index_reordering( bitmask, old2new, new2old );\n\n  idx_vector_type pi;\n  pi.resize(10,false);\n  size_type nodep = OpenTissue::math::detail::highest<size_t>();\n  pi(0) = nodep;\n  pi(1) = 0;\n  pi(2) = 0;\n  pi(3) = nodep;\n  pi(4) = 3;\n  pi(5) = 3;\n  pi(6) = nodep;\n  pi(7) = 6;\n  pi(8) = 6;\n  pi(9) = nodep;\n\n  matrix_type J;\n  OpenTissue::math::optimization::detail::compute_jacobian( \n      A\n    , OpenTissue::math::optimization::make_lower_mbd_bounds( pi, mu, lo )\n    , OpenTissue::math::optimization::make_upper_mbd_bounds( pi, mu, hi )\n    , bitmask        \n    , J\n    );\n\n  double tol = 0.01;\n\n  // upper      pi = inf\n  BOOST_CHECK_CLOSE( double( J(0,0) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(0,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(0,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(0,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(0,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(0,5) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(0,6) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(0,7) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(0,8) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(0,9) ), double( 0.0 ), tol );\n\n  // lower      pi = 0\n  BOOST_CHECK_CLOSE( double( J(1,0) ), double( mu(1) ), tol );\n  BOOST_CHECK_CLOSE( double( J(1,1) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(1,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(1,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(1,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(1,5) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(1,6) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(1,7) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(1,8) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(1,9) ), double( 0.0 ), tol );\n\n  // active     pi = 0\n  BOOST_CHECK_CLOSE( double( J(2,0) ), double( A(2,0) ), tol );\n  BOOST_CHECK_CLOSE( double( J(2,1) ), double( A(2,1) ), tol );\n  BOOST_CHECK_CLOSE( double( J(2,2) ), double( A(2,2) ), tol );\n  BOOST_CHECK_CLOSE( double( J(2,3) ), double( A(2,3) ), tol );\n  BOOST_CHECK_CLOSE( double( J(2,4) ), double( A(2,4) ), tol );\n  BOOST_CHECK_CLOSE( double( J(2,5) ), double( A(2,5) ), tol );\n  BOOST_CHECK_CLOSE( double( J(2,6) ), double( A(2,6) ), tol );\n  BOOST_CHECK_CLOSE( double( J(2,7) ), double( A(2,7) ), tol );\n  BOOST_CHECK_CLOSE( double( J(2,8) ), double( A(2,8) ), tol );\n  BOOST_CHECK_CLOSE( double( J(2,9) ), double( A(2,9) ), tol );\n\n  // lower      pi = inf\n  BOOST_CHECK_CLOSE( double( J(3,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(3,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(3,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(3,3) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(3,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(3,5) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(3,6) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(3,7) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(3,8) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(3,9) ), double( 0.0 ), tol );\n\n  // active     pi = 3\n  BOOST_CHECK_CLOSE( double( J(4,0) ), double( A(4,0) ), tol );\n  BOOST_CHECK_CLOSE( double( J(4,1) ), double( A(4,1) ), tol );\n  BOOST_CHECK_CLOSE( double( J(4,2) ), double( A(4,2) ), tol );\n  BOOST_CHECK_CLOSE( double( J(4,3) ), double( A(4,3) ), tol );\n  BOOST_CHECK_CLOSE( double( J(4,4) ), double( A(4,4) ), tol );\n  BOOST_CHECK_CLOSE( double( J(4,5) ), double( A(4,5) ), tol );\n  BOOST_CHECK_CLOSE( double( J(4,6) ), double( A(4,6) ), tol );\n  BOOST_CHECK_CLOSE( double( J(4,7) ), double( A(4,7) ), tol );\n  BOOST_CHECK_CLOSE( double( J(4,8) ), double( A(4,8) ), tol );\n  BOOST_CHECK_CLOSE( double( J(4,9) ), double( A(4,9) ), tol );\n\n  // upper      pi = 3\n  BOOST_CHECK_CLOSE( double( J(5,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(5,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(5,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(5,3) ), double( -mu(5) ), tol );\n  BOOST_CHECK_CLOSE( double( J(5,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(5,5) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(5,6) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(5,7) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(5,8) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(5,9) ), double( 0.0 ), tol );\n\n  // active     pi = inf\n  BOOST_CHECK_CLOSE( double( J(6,0) ), double( A(6,0) ), tol );\n  BOOST_CHECK_CLOSE( double( J(6,1) ), double( A(6,1) ), tol );\n  BOOST_CHECK_CLOSE( double( J(6,2) ), double( A(6,2) ), tol );\n  BOOST_CHECK_CLOSE( double( J(6,3) ), double( A(6,3) ), tol );\n  BOOST_CHECK_CLOSE( double( J(6,4) ), double( A(6,4) ), tol );\n  BOOST_CHECK_CLOSE( double( J(6,5) ), double( A(6,5) ), tol );\n  BOOST_CHECK_CLOSE( double( J(6,6) ), double( A(6,6) ), tol );\n  BOOST_CHECK_CLOSE( double( J(6,7) ), double( A(6,7) ), tol );\n  BOOST_CHECK_CLOSE( double( J(6,8) ), double( A(6,8) ), tol );\n  BOOST_CHECK_CLOSE( double( J(6,9) ), double( A(6,9) ), tol );\n\n  // upper      pi = 6\n  BOOST_CHECK_CLOSE( double( J(7,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(7,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(7,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(7,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(7,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(7,5) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(7,6) ), double( -mu(7) ), tol );\n  BOOST_CHECK_CLOSE( double( J(7,7) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(7,8) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(7,9) ), double( 0.0 ), tol );\n\n  // lower      pi = 6\n  BOOST_CHECK_CLOSE( double( J(8,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(8,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(8,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(8,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(8,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(8,5) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(8,6) ), double( mu(8) ), tol );\n  BOOST_CHECK_CLOSE( double( J(8,7) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(8,8) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( J(8,9) ), double( 0.0 ), tol );\n\n  // active     pi = inf\n  BOOST_CHECK_CLOSE( double( J(9,0) ), double( A(9,0) ), tol );\n  BOOST_CHECK_CLOSE( double( J(9,1) ), double( A(9,1) ), tol );\n  BOOST_CHECK_CLOSE( double( J(9,2) ), double( A(9,2) ), tol );\n  BOOST_CHECK_CLOSE( double( J(9,3) ), double( A(9,3) ), tol );\n  BOOST_CHECK_CLOSE( double( J(9,4) ), double( A(9,4) ), tol );\n  BOOST_CHECK_CLOSE( double( J(9,5) ), double( A(9,5) ), tol );\n  BOOST_CHECK_CLOSE( double( J(9,6) ), double( A(9,6) ), tol );\n  BOOST_CHECK_CLOSE( double( J(9,7) ), double( A(9,7) ), tol );\n  BOOST_CHECK_CLOSE( double( J(9,8) ), double( A(9,8) ), tol );\n  BOOST_CHECK_CLOSE( double( J(9,9) ), double( A(9,9) ), tol );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "6c3f260ca348dba17187137739eed749c90f82ac", "size": 9394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/compute_jacobian/src/unit_compute_jacobian.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/compute_jacobian/src/unit_compute_jacobian.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/compute_jacobian/src/unit_compute_jacobian.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 42.3153153153, "max_line_length": 94, "alphanum_fraction": 0.6259314456, "num_tokens": 3345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.592861674572742}}
{"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": "// Boost.Geometry\r\n// Unit Test\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#include \"test_formula.hpp\"\r\n#include \"inverse_cases.hpp\"\r\n\r\n#include <boost/geometry/formulas/vincenty_inverse.hpp>\r\n#include <boost/geometry/formulas/thomas_inverse.hpp>\r\n#include <boost/geometry/formulas/andoyer_inverse.hpp>\r\n\r\ntemplate <typename Result>\r\nvoid check_inverse(Result const& result, expected_result const& expected, expected_result const& reference, double reference_error)\r\n{\r\n    check_one(result.distance, expected.distance, reference.distance, reference_error);\r\n    check_one(result.azimuth, expected.azimuth, reference.azimuth, reference_error, true);\r\n    check_one(result.reverse_azimuth, expected.reverse_azimuth, reference.reverse_azimuth, reference_error, true);\r\n    check_one(result.reduced_length, expected.reduced_length, reference.reduced_length, reference_error);\r\n    check_one(result.geodesic_scale, expected.geodesic_scale, reference.geodesic_scale, reference_error);\r\n}\r\n\r\nvoid test_all(expected_results const& results)\r\n{\r\n    double const d2r = bg::math::d2r<double>();\r\n    double const r2d = bg::math::r2d<double>();\r\n\r\n    double lon1r = results.p1.lon * d2r;\r\n    double lat1r = results.p1.lat * d2r;\r\n    double lon2r = results.p2.lon * d2r;\r\n    double lat2r = results.p2.lat * d2r;\r\n\r\n    // WGS84\r\n    bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);\r\n\r\n    bg::formula::result_inverse<double> result_v, result_t, result_a;\r\n\r\n    typedef bg::formula::vincenty_inverse<double, true, true, true, true, true> vi_t;\r\n    result_v = vi_t::apply(lon1r, lat1r, lon2r, lat2r, spheroid);\r\n    result_v.azimuth *= r2d;\r\n    result_v.reverse_azimuth *= r2d;\r\n    check_inverse(result_v, results.vincenty, results.reference, 0.0000001);\r\n\r\n    typedef bg::formula::thomas_inverse<double, true, true, true, true, true> th_t;\r\n    result_t = th_t::apply(lon1r, lat1r, lon2r, lat2r, spheroid);\r\n    result_t.azimuth *= r2d;\r\n    result_t.reverse_azimuth *= r2d;\r\n    check_inverse(result_t, results.thomas, results.reference, 0.00001);\r\n\r\n    typedef bg::formula::andoyer_inverse<double, true, true, true, true, true> an_t;\r\n    result_a = an_t::apply(lon1r, lat1r, lon2r, lat2r, spheroid);\r\n    result_a.azimuth *= r2d;\r\n    result_a.reverse_azimuth *= r2d;\r\n    check_inverse(result_a, results.andoyer, results.reference, 0.001);\r\n}\r\n\r\nint test_main(int, char*[])\r\n{\r\n    for (size_t i = 0; i < expected_size; ++i)\r\n    {\r\n        test_all(expected[i]);\r\n    }\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "4b75609b1ce880fe25c9e7b0993faa8d95502547", "size": 2792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/formulas/inverse.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/geometry/test/formulas/inverse.cpp", "max_issues_repo_name": "lijgame/boost", "max_issues_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/geometry/test/formulas/inverse.cpp", "max_forks_repo_name": "lijgame/boost", "max_forks_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_forks_repo_licenses": ["BSL-1.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.7777777778, "max_line_length": 132, "alphanum_fraction": 0.7141833811, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5928412126977447}}
{"text": "//\n// Copyright 2019 Miral Shah <miralshah2211@gmail.com>\n// Copyright 2019 Mateusz Loskot <mateusz at loskot dot net>\n// Copyright 2021 Pranam Lashkari <plashkari628@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <vector>\n#include <iostream>\n#include <boost/gil/image_processing/kernel.hpp>\n#include <boost/gil/image_processing/convolve.hpp>\n#include <boost/gil/extension/io/png.hpp>\n\n#include <boost/gil/extension/io/jpeg.hpp>\n\nusing namespace boost::gil;\nusing namespace std;\n\n// Convolves the image with a 2d kernel.\n\n// Note that the kernel can be fixed or resizable:\n// kernel_2d_fixed<float, N> k(elements, centre_y, centre_x) produces a fixed kernel\n// kernel_2d<float> k(elements, size, centre_y, centre_x) produces a resizable kernel\n// The size of the kernel matrix is deduced as the square root of the number of the elements (9 elements yield a 3x3 matrix)\n\n// See also:\n// convolution.cpp - Convolution with 2d kernels\n\n\nint main()\n{\n    gray8_image_t img;\n    read_image(\"src_view.png\", img, png_tag{});\n    gray8_image_t img_out(img.dimensions()), img_out1(img.dimensions());\n\n    std::vector<float> v(9, 1.0f / 9.0f);\n    detail::kernel_2d<float> kernel(v.begin(), v.size(), 1, 1);\n    detail::convolve_2d(view(img), kernel, view(img_out1));\n\n    write_view(\"out-convolve2d.png\", view(img_out1), png_tag{});\n\n    std::vector<float> v1(3, 1.0f / 3.0f);\n    kernel_1d<float> kernel1(v1.begin(), v1.size(), 1);\n\n    detail::convolve_1d<gray32f_pixel_t>(const_view(img), kernel1, view(img_out), boundary_option::extend_zero);\n    write_view(\"out-convolve_option_extend_zero.png\", view(img_out), png_tag{});\n\n    if (equal_pixels(view(img_out1), view(img_out)))\n      cout << \"convolve_option_extend_zero\" << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "caa61c55e5650224de51e0fb004e9483168ec621", "size": 1908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/convolve2d.cpp", "max_stars_repo_name": "Paul92/gil", "max_stars_repo_head_hexsha": "da0655fb66dd161a643e1ca0ed51937548465d18", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/convolve2d.cpp", "max_issues_repo_name": "Paul92/gil", "max_issues_repo_head_hexsha": "da0655fb66dd161a643e1ca0ed51937548465d18", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/convolve2d.cpp", "max_forks_repo_name": "Paul92/gil", "max_forks_repo_head_hexsha": "da0655fb66dd161a643e1ca0ed51937548465d18", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6909090909, "max_line_length": 124, "alphanum_fraction": 0.7232704403, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.5928412007812162}}
{"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": "#include \"exception.hh\"\n#include \"network.hh\"\n#include \"timer.hh\"\n\n#include <Eigen/Dense>\n#include <iostream>\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 = 64;\n// epsilon for computation of numerical gradients\nconstexpr double grad_epsilon = 1e-5;\n// max allowable absolute difference in numerical and backprop gradients\nconstexpr double compare_epsilon = 1e-5;\n// max allowable percentage difference in numerical and backprop gradients\nconstexpr double percentage_error_epsilon = 1e-3;\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  srand( 0 );\n\n  /* construct neural network on heap */\n  auto nn = make_unique<Network<double, batch_size, input_size, 64, 64, 64, 64, 64, 64, 64, 64, 1>>();\n  nn->initializeWeightsRandomly();\n\n  srand( 10 );\n  /* initialize inputs */\n  Matrix<double, batch_size, input_size> input = Matrix<double, batch_size, input_size>::Random();\n\n  /* forward prop */\n  nn->apply( input );\n\n  /* back prop */\n  nn->computeDeltas();\n  nn->evaluateGradients( input );\n\n  /* compare back prop results with numerical gradients */\n  bool errorsOverThreshold = false;\n  double maxDiff = 0.0;\n  double maxPercentageError = 0.0;\n  unsigned int numLayers = nn->getNumLayers();\n  for ( unsigned int layerNum = 0; layerNum < numLayers; layerNum++ ) {\n    unsigned int numParams = nn->getNumParams( layerNum );\n    for ( unsigned int paramNum = 0; paramNum < numParams; paramNum++ ) {\n      double formulaGradient = nn->getEvaluatedGradient( layerNum, paramNum );\n      double numericalGradient = nn->calculateNumericalGradient( input, layerNum, paramNum, grad_epsilon );\n      double diff = abs( formulaGradient - numericalGradient );\n      double percentageError = diff / max( abs( formulaGradient ), abs( numericalGradient ) );\n      maxDiff = max( diff, maxDiff );\n      maxPercentageError = max( percentageError, maxPercentageError );\n      if ( ( diff > compare_epsilon ) and ( percentageError > percentage_error_epsilon ) ) {\n        errorsOverThreshold = true;\n        cout << \"Error in Layer \" << layerNum << \", Param \" << paramNum << endl;\n        cout << formulaGradient << \" \" << numericalGradient << endl;\n        cout << \"diff: \" << diff << \", %diff: \" << percentageError << endl;\n        cout << endl;\n      }\n    }\n  }\n  cout << endl;\n  cout << \"Params: grad_epsilon \" << grad_epsilon << \", compare_epsilon \" << compare_epsilon\n       << \", percentage_error_epsilon \" << percentage_error_epsilon << endl;\n  cout << \"maxDiff: \" << maxDiff << endl << \"maxPercentageError: \" << maxPercentageError << endl << endl;\n  if ( errorsOverThreshold ) {\n    throw runtime_error( \"test failure\" );\n  }\n}\n\nint main()\n{\n  try {\n    program_body();\n    return EXIT_SUCCESS;\n  } catch ( const exception& e ) {\n    cerr << e.what() << \"\\n\";\n    return EXIT_FAILURE;\n  }\n}\n", "meta": {"hexsha": "84a41830daf70329497e2143ab5d422e5ce98675", "size": 3145, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/formulagradienttest2.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/tests/formulagradienttest2.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/tests/formulagradienttest2.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": 34.5604395604, "max_line_length": 107, "alphanum_fraction": 0.6775834658, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604134, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5927984363770087}}
{"text": "/*\n * This file is part of MXE. See LICENSE.md for licensing information.\n *\n * This code was originally found on:\n *   https://eigen.tuxfamily.org/dox/GettingStarted.html\n */\n\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\n\nint main()\n{\n    MatrixXd m(2,2);\n    m(0,0) = 3;\n    m(1,0) = 2.5;\n    m(0,1) = -1;\n    m(1,1) = m(1,0) + m(0,1);\n    return 0;\n}\n", "meta": {"hexsha": "436bf1a2cf51bc7588fced47c4a9685a00695228", "size": 356, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen-test.cpp", "max_stars_repo_name": "swigger/mxe", "max_stars_repo_head_hexsha": "bee76ee63ec361a379b58c1d51214c36dc5e3a78", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 864.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T10:31:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:54:29.000Z", "max_issues_repo_path": "src/eigen-test.cpp", "max_issues_repo_name": "swigger/mxe", "max_issues_repo_head_hexsha": "bee76ee63ec361a379b58c1d51214c36dc5e3a78", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 1942.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T08:18:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T08:04:19.000Z", "max_forks_repo_path": "src/eigen-test.cpp", "max_forks_repo_name": "swigger/mxe", "max_forks_repo_head_hexsha": "bee76ee63ec361a379b58c1d51214c36dc5e3a78", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 526.0, "max_forks_repo_forks_event_min_datetime": "2015-01-04T05:39:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T20:23:12.000Z", "avg_line_length": 16.9523809524, "max_line_length": 70, "alphanum_fraction": 0.5814606742, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.5927984255169622}}
{"text": "//\n// Copyright (c) 2016-2019 CNRS, INRIA\n//\n\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n#include \"pinocchio/algorithm/finite-differences.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nusing namespace pinocchio;\nusing namespace Eigen;\n\ntemplate<bool local>\nData::Matrix6x finiteDiffJacobian(const Model & model, Data & data, const Eigen::VectorXd & q, const Model::JointIndex joint_id)\n{\n  Data::Matrix6x res(6,model.nv); res.setZero();\n  VectorXd q_integrate (model.nq);\n  VectorXd v_integrate (model.nv); v_integrate.setZero();\n  \n  forwardKinematics(model,data,q);\n  const SE3 oMi_ref = data.oMi[joint_id];\n  \n  const VectorXd fd_increment = finiteDifferenceIncrement(model);\n \n  double eps = 1e-8;\n  for(int k=0; k<model.nv; ++k)\n  {\n    // Integrate along kth direction\n    eps = fd_increment[k];\n    v_integrate[k] = eps;\n    q_integrate = integrate(model,q,v_integrate);\n    \n    forwardKinematics(model,data,q_integrate);\n    const SE3 & oMi = data.oMi[joint_id];\n    \n    if (local)\n      res.col(k) = log6(oMi_ref.inverse()*oMi).toVector();\n    else\n      res.col(k) = oMi_ref.act(log6(oMi_ref.inverse()*oMi)).toVector();\n    \n    res.col(k) /= eps;\n    \n    v_integrate[k] = 0.;\n  }\n  \n  return res;\n}\n\ntemplate<typename Matrix>\nvoid filterValue(MatrixBase<Matrix> & mat, typename Matrix::Scalar value)\n{\n  for(int k = 0; k < mat.size(); ++k)\n    mat.derived().data()[k] =  math::fabs(mat.derived().data()[k]) <= value?0:mat.derived().data()[k];\n}\n\nstruct FiniteDiffJoint\n{\n  template<typename JointModel>\n  static void init (JointModelBase<JointModel> & /*jmodel*/) {}\n  \n  template<typename JointModel>\n  void operator()(JointModelBase<JointModel> & jmodel) const\n  {\n    typedef typename JointModel::ConfigVector_t CV;\n    typedef typename JointModel::TangentVector_t TV;\n    typedef typename LieGroup<JointModel>::type LieGroupType;\n    \n    init(jmodel); jmodel.setIndexes(0,0,0);\n    typename JointModel::JointDataDerived jdata = jmodel.createData();\n    CV q; LieGroupType().random(q);\n    jmodel.calc(jdata,q);\n    SE3 M_ref(jdata.M);\n    \n    CV q_int(jmodel.nq());\n    TV v(jmodel.nv()); v.setZero();\n    double eps = 1e-4;\n    \n    Eigen::Matrix<double,6,JointModel::NV> S(6,jmodel.nv()), S_ref(jdata.S.matrix());\n    \n    eps = jmodel.finiteDifferenceIncrement();\n    for(int k=0;k<jmodel.nv();++k)\n    {\n      v[k] = eps;\n      q_int = LieGroupType().integrate(q,v);\n      jmodel.calc(jdata,q_int);\n      SE3 M_int = jdata.M;\n      \n      S.col(k) = log6(M_ref.inverse()*M_int).toVector();\n      S.col(k) /= eps;\n      \n      v[k] = 0.;\n    }\n    \n    BOOST_CHECK(S.isApprox(S_ref,eps*1e1));\n    std::cout << \"name: \" << jmodel.classname() << std::endl;\n    std::cout << \"S_ref:\\n\" << S_ref << std::endl;\n    std::cout << \"S:\\n\" << S << std::endl;\n  }\n};\n\ntemplate<>\nvoid FiniteDiffJoint::init<JointModelRevoluteUnaligned>(JointModelBase<JointModelRevoluteUnaligned> & jmodel)\n{\n  jmodel.derived().axis.setRandom(); jmodel.derived().axis.normalize();\n}\n\ntemplate<>\nvoid FiniteDiffJoint::init<JointModelPrismaticUnaligned>(JointModelBase<JointModelPrismaticUnaligned> & jmodel)\n{\n  jmodel.derived().axis.setRandom(); jmodel.derived().axis.normalize();\n}\n\ntemplate<>\nvoid FiniteDiffJoint::init<JointModelComposite>(JointModelBase<JointModelComposite> & jmodel)\n{\n  jmodel.derived().addJoint(JointModelRX());\n  jmodel.derived().addJoint(JointModelRZ());\n}\n\ntemplate<>\nvoid FiniteDiffJoint::operator()< JointModelComposite > (JointModelBase<JointModelComposite> & ) const\n{\n  // DO NOT CHECK BECAUSE IT IS NOT WORKINK YET - TODO\n//  typedef typename JointModel::ConfigVector_t CV;\n//  typedef typename JointModel::TangentVector_t TV;\n//\n//  pinocchio::JointModelComposite jmodel((pinocchio::JointModelRX())/*, (pinocchio::JointModelRY())*/);\n//  jmodel.setIndexes(0,0,0);\n//\n//  pinocchio::JointModelComposite::JointDataDerived jdata = jmodel.createData();\n//\n//  CV q = jmodel.random();\n//  jmodel.calc(jdata,q);\n//  SE3 M_ref(jdata.M);\n//\n//  CV q_int;\n//  TV v(Eigen::VectorXd::Random(jmodel.nv())); v.setZero();\n//  double eps = 1e-4;\n//\n//  assert(q.size() == jmodel.nq()&& \"nq false\");\n//  assert(v.size() == jmodel.nv()&& \"nv false\");\n//  Eigen::MatrixXd S(6,jmodel.nv()), S_ref(ConstraintXd(jdata.S).matrix());\n//\n//  eps = jmodel.finiteDifferenceIncrement();\n//  for(int k=0;k<jmodel.nv();++k)\n//  {\n//    v[k] = eps;\n//    q_int = jmodel.integrate(q,v);\n//    jmodel.calc(jdata,q_int);\n//    SE3 M_int = jdata.M;\n//\n//    S.col(k) = log6(M_ref.inverse()*M_int).toVector();\n//    S.col(k) /= eps;\n//\n//    v[k] = 0.;\n//  }\n//\n//  std::cout << \"S\\n\" << S << std::endl;\n//  std::cout << \"S_ref\\n\" << S_ref << std::endl;\n  // BOOST_CHECK(S.isApprox(S_ref,eps*1e1)); //@TODO Uncomment to test once JointComposite maths are ok\n}\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE(increment)\n{\n  typedef double Scalar;\n  \n  Model model;\n  buildModels::humanoidRandom(model);\n  \n  VectorXd fd_increment(model.nv);\n  fd_increment = finiteDifferenceIncrement(model);\n  \n  for(int k=0; k<model.nv; ++k)\n  {\n    BOOST_CHECK(fd_increment[k] > Eigen::NumTraits<Scalar>::epsilon());\n    BOOST_CHECK(fd_increment[k] < 1e-3);\n  }\n}\n\nBOOST_AUTO_TEST_CASE (test_S_finit_diff)\n{\n  boost::mpl::for_each<JointModelVariant::types>(FiniteDiffJoint());\n}\n\nBOOST_AUTO_TEST_CASE (test_jacobian_vs_finit_diff)\n{\n  pinocchio::Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  pinocchio::Data data(model);\n  \n  const VectorXd fd_increment = finiteDifferenceIncrement(model);\n\n  VectorXd q = VectorXd::Ones(model.nq);\n  q.segment<4>(3).normalize();\n  computeJointJacobians(model,data,q);\n\n  Model::Index idx = model.existJointName(\"rarm2\")?model.getJointId(\"rarm2\"):(Model::Index)(model.njoints-1);\n  Data::Matrix6x Jrh(6,model.nv); Jrh.fill(0);\n  \n  getJointJacobian(model,data,idx,WORLD,Jrh);\n  Data::Matrix6x Jrh_finite_diff = finiteDiffJacobian<false>(model,data,q,idx);\n  BOOST_CHECK(Jrh_finite_diff.isApprox(Jrh,fd_increment.maxCoeff()*1e1));\n  \n  getJointJacobian(model,data,idx,LOCAL,Jrh);\n  Jrh_finite_diff = finiteDiffJacobian<true>(model,data,q,idx);\n  BOOST_CHECK(Jrh_finite_diff.isApprox(Jrh,fd_increment.maxCoeff()*1e1));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "54d1d83813b68e8fc1c41f0e58a6d1cd730370e9", "size": 6458, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/finite-differences.cpp", "max_stars_repo_name": "matthieuvigne/pinocchio", "max_stars_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "unittest/finite-differences.cpp", "max_issues_repo_name": "matthieuvigne/pinocchio", "max_issues_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/finite-differences.cpp", "max_forks_repo_name": "matthieuvigne/pinocchio", "max_forks_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 29.623853211, "max_line_length": 128, "alphanum_fraction": 0.6824094147, "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511432905479, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5927984222968494}}
{"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": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/FFT.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/PeakDetection.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass YINFFT\n{\n\npublic:\n  void processFrame(const RealVectorView& input, RealVectorView output,\n                    double minFreq, double maxFreq, double sampleRate)\n  {\n    using namespace Eigen;\n    PeakDetection pd;\n    ArrayXd       mag = _impl::asEigen<Array>(input);\n    ArrayXd       squareMag = mag.square();\n    index         nBins = mag.size();\n    FFT           fft(2 * (mag.size() - 1));\n    double        squareMagSum = 2 * squareMag.sum();\n    ArrayXd       squareMagSym(2 * (nBins - 1));\n    squareMagSym << squareMag[0], squareMag.segment(1, nBins - 1),\n        squareMag.segment(1, nBins - 2).reverse();\n    ArrayXcd squareMagFFT = fft.process(squareMagSym);\n    ArrayXd  yin = squareMagSum - squareMagFFT.real();\n    if (maxFreq == 0) maxFreq = 1;\n    if (minFreq == 0) minFreq = 1;\n    yin(0) = 1;\n    double tmpSum = 0;\n    for (index i = 1; i < nBins; i++)\n    {\n      tmpSum += yin(i);\n      yin(i) *= i / tmpSum;\n    }\n    double pitch = 0;\n    double pitchConfidence = 0;\n    if (tmpSum > 0)\n    {\n      ArrayXd yinFlip = -yin;\n      // segment from max to min freq\n      index minBin = std::lrint(sampleRate / maxFreq);\n      index maxBin = std::lrint(sampleRate / minFreq);\n      if (minBin > yinFlip.size() - 1) minBin = yinFlip.size() - 1;\n      if (maxBin > yinFlip.size() - minBin - 1)\n        maxBin = yinFlip.size() - minBin - 1;\n      if (maxBin > minBin)\n      {\n        yinFlip = yinFlip.segment(minBin, maxBin - minBin);\n\n        auto vec = pd.process(yinFlip, 1, yinFlip.minCoeff());\n        if (vec.size() > 0)\n        {\n          pitch = sampleRate / (minBin + vec[0].first);\n          pitchConfidence = std::max(1. + vec[0].second, 0.);\n        }\n      }\n    }\n    output(0) = pitch;\n    output(1) = pitchConfidence;\n  }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "c05327c53baad92b321dab13af283f6d9cf778d5", "size": 2479, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/YINFFT.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/algorithms/public/YINFFT.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-15T10:39:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T13:19:22.000Z", "max_forks_repo_path": "include/algorithms/public/YINFFT.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9875, "max_line_length": 74, "alphanum_fraction": 0.617587737, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5926723563679211}}
{"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": "/* boost-supplement random/discrete_distribution.hpp header file\n *\n * Copyright (C) 2008 Kenta Murata.\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * $Id: discrete_distribution.hpp 5906 2008-01-30 15:09:35Z mrkn $\n * \n */\n\n#ifndef BOOST_SUPPLEMENT_ZIPF_DISTRIBUTION_HPP\n#define BOOST_SUPPLEMENT_ZIPF_DISTRIBUTION_HPP 1\n\n#include <boost/random/discrete_distribution.hpp>\n\n#include <cmath>\n\nnamespace boost { namespace random {\n\n// Zipf-Mandelbrot distribution\n//\n// Let N, q, and s be num, shift, and exp, respectively.  The\n// probability distribution is P(k) = (k + q)^{-s} / H_{N,q,s} where k\n// = 1, 2, ..., N, and H_{N,q,s} is generalized harmonic number, that\n// is H_{N,q,s} = \\sum_{i=1}^N (i+q)^{-s}.\n//\n// http://en.wikipedia.org/wiki/Zipf-Mandelbrot_law.\ntemplate<class IntType = long, class RealType = double>\nclass zipf_distribution\n{\npublic:\n  typedef RealType input_type;\n  typedef IntType result_type;\n\n#if !defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS) && !(defined(BOOST_MSVC) && BOOST_MSVC <= 1300)\n  BOOST_STATIC_ASSERT(std::numeric_limits<IntType>::is_integer);\n  BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);\n#endif\n\nprivate:\n  result_type num_;\n  input_type shift_;\n  input_type exp_;\n\n  typedef discrete_distribution<IntType, RealType> dist_type;\n  dist_type dist_;\n\n  dist_type make_dist(result_type num, input_type shift, input_type exp)\n    {\n      std::vector<input_type> buffer(num);\n      for (result_type k = 1; k <= num; ++k)\n        buffer[k-1] = std::pow(k + shift, -exp);\n      return dist_type(buffer.begin(), buffer.end());\n    }\n\npublic:\n  zipf_distribution(result_type num, input_type shift, input_type exp)\n    : num_(num), shift_(shift), exp_(exp),\n      dist_(make_dist(num, shift, exp))\n    {}\n\n  result_type num() const { return num_; }\n\n  input_type shift() const { return shift_; }\n\n  input_type exponent() const { return exp_; }\n\n  template<class Engine>\n  result_type operator()(Engine& eng) { return dist_(eng); }\n  \n  RealType pmf(IntType i) { return dist_.probabilities().at(i); }\n};\n\n} }\n\n#endif // BOOST_SUPPLEMENT_ZIPF_DISTRIBUTION_HPP\n", "meta": {"hexsha": "587037e5cf7e3e4aabaa681eea335d81562b1fd3", "size": 2225, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/zipf_distribution.hpp", "max_stars_repo_name": "manuhalo/PLACeS", "max_stars_repo_head_hexsha": "1574a34a2a98468e72d072cc9d1f2b32fcee38f2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/zipf_distribution.hpp", "max_issues_repo_name": "manuhalo/PLACeS", "max_issues_repo_head_hexsha": "1574a34a2a98468e72d072cc9d1f2b32fcee38f2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-04-24T10:10:51.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-18T08:32:16.000Z", "max_forks_repo_path": "src/zipf_distribution.hpp", "max_forks_repo_name": "manuhalo/PLACeS", "max_forks_repo_head_hexsha": "1574a34a2a98468e72d072cc9d1f2b32fcee38f2", "max_forks_repo_licenses": ["Apache-2.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.5256410256, "max_line_length": 100, "alphanum_fraction": 0.7101123596, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5926716726075072}}
{"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 *      Izzo, D. and Vinko, T. ACT - Informatics - GTOP Database, ESA Advanced Concept Team, last\n *          accessed on 2012-01-12. http://www.esa.int/gsp/ACT/inf/op/globopt.htm.\n *      Musegaas, P. Gravity Assist calculation Verification.xlsx, last accessed: 3 December 2012,\n *          http://tudat.tudelft.nl/projects/tudat/wiki/Unit_tests, 2012.\n *\n *    Notes\n *      Three main functions are tested in these unit tests.\n *        Regarding the deltaV calculation gravity assist method:\n *          There is a complicated if-statement in this method. Hence many unit test are performed\n *          to test the functionality. Also various limit cases failed previously, hence many tests\n *          for this are also included:\n *              Case 1: required bending angle > maximum bending angle:\n *                  Two tests were written. In the first one no velocity effect is needed. This\n *                  test has a low accuracy, which should be replaced one day (it still relies on\n *                  hand calculator calculations done in 2011). In the second one a combination of\n *                  bending-effect deltaV and velocity-effect deltaV is calculated. This test has\n *                  been calculated using Tudat, and was verified using Excel.\n *                  Could definitely be improved.\n *              Case 2: no assist is required:\n *                  One test was written.\n *              Case 3: velocity effect deltaV only, using eccentricity iteration scheme:\n *                  Four tests were written. The first one calculates a case from Cassini-1 of GTOP\n *                  with high precision. The other three test limit cases: low incoming, high\n *                  outgoing velocity; high incoming, low outgoing velocity; low incoming, low\n *                  outgoing velocity. These tests were calculated using Tudat, but verified in\n *                  Excel to be exactly correct.\n *              Case 4: velocity effect deltaV only, using pericenter radius iteration scheme:\n *                  The same four tests as for case 3 were used.\n *        Regarding the unpowered gravity assist propagator:\n *          One test was written, based on GTOP. This should be a satisfactory test.\n *        Regarding the powered gravity assist propagator:\n *          Two tests were written. The first one is similar to the unpowered gravity assist\n *          propagator. The second one is reverse engineered from the Cassini-1 test, similar to\n *          the one in the deltaV calculation test.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <cmath>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/unitConversions.h\"\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/Astrodynamics/MissionSegments/gravityAssist.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Test of gravity assist code.\nBOOST_AUTO_TEST_SUITE( test_gravity_assist )\n\n//! Test bending angle Delta-V computation.\nBOOST_AUTO_TEST_CASE( testBendingAngleDeltaV )\n{\n    // Tolerance, determined primarily by the accuracy of the hand calculations for this test case.\n    const double velocityTolerance = 0.0002;\n\n    // In the first test case, the incoming and outgoing inertial velocities are defined such that\n    // the hyperbolic excess velocities are equal. In that way, a delta-V is only needed to rotate\n    // the velocity vector, which has been calculated by hand.\n    // Expected delta-V for a powered swing-by around Mars.\n    const double expectedDeltaV = 3.652e3;\n\n    // Define swingby body gravitational parameter.\n    const double marsGravitationalParameter = 4.2828018915e13;\n\n    // Define Sun gravitational parameter.\n    const double gravitationalParameterSun = 1.32712440018e20;\n\n    // Define planet-Sun distance.\n    const double distanceMarsToSun = unit_conversions::\n            convertAstronomicalUnitsToMeters( 1.5 );\n\n    // Define smallest periapsis distance factor.\n    const double marsSmallestPeriapsisDistance = 3656248.0;\n\n    // Define planet heliocentric velocity vector. The orbit is considered to be circular.\n    const Eigen::Vector3d marsVelocity( 0.0,\n                                        std::sqrt( gravitationalParameterSun / distanceMarsToSun ),\n                                        0.0 );\n\n    // Define satellite incoming vector.\n    using mathematical_constants::PI;\n    const Eigen::Vector3d incomingVelocity( -25.0e3 * std::sin( PI / 6.0 ),\n                                            25.0e3 * std::cos( PI / 6.0 ),\n                                            0.0 );\n\n    // Define satellite outgoing vector.\n    const Eigen::Vector3d outgoingVelocity( incomingVelocity( 0 ),\n                                            2.0 * marsVelocity( 1 ) - incomingVelocity( 1 ),\n                                            0.0 );\n\n    // Perform the gravity assist.\n    const double deltaV = mission_segments::gravityAssist( marsGravitationalParameter,\n                                                           marsVelocity, incomingVelocity,\n                                                           outgoingVelocity,\n                                                           marsSmallestPeriapsisDistance );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( deltaV, expectedDeltaV, velocityTolerance );\n}\n\n//! Test case for both bending angle and velocity effect delta V.\nBOOST_AUTO_TEST_CASE( testBendingAngleAndVelocityEffectDeltaVPericenter )\n{\n    // Tolerance.\n    const double tolerance = 1e-12;\n\n    // Expected deltaV cost, as obtained from this code, verified in Excel (Musegaas, 2012).\n    const double expectedDeltaV = 183.8481861944;\n\n    // Define swingby body gravitational parameter.\n    const double venusGravitationalParameter = 3.24860e14;\n\n    // Define smallest periapsis distance factor.\n    const double venusSmallestPeriapsisDistance = 6351800.0;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d venusVelocity( 35000.0, 0.0 , 0.0 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 36000.0 , 0.0 , 0.0 );\n\n    // Define heliocentric satellite outgoing vector.\n    const Eigen::Vector3d outgoingVelocity( 34500.0, 0.0, 0.0 );\n\n    // Perform the gravity assist.\n    const double deltaV = mission_segments::gravityAssist( venusGravitationalParameter,\n                                                           venusVelocity,incomingVelocity,\n                                                           outgoingVelocity,\n                                                           venusSmallestPeriapsisDistance );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( deltaV, expectedDeltaV, tolerance );\n}\n\n//! Test case in which no assist is required.\nBOOST_AUTO_TEST_CASE( testNoDeltaVRequired )\n{\n    // Tolerance.\n    const double tolerance = std::numeric_limits< double >::epsilon( );\n\n    // Expected deltaV cost, as obtained from this code, verified in Excel (Musegaas, 2012).\n    const double expectedDeltaV = 0.0;\n\n    // Define swingby body gravitational parameter.\n    const double venusGravitationalParameter = 3.24860e14;\n\n    // Define smallest periapsis distance factor.\n    const double venusSmallestPeriapsisDistance = 6351800.0;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d venusVelocity( 35000.0, 0.0 , 0.0 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 36000.0 , 0.0 , 0.0 );\n\n    // Define heliocentric satellite outgoing vector.\n    const Eigen::Vector3d outgoingVelocity( 35000.0, 1000.0, 0.0 );\n\n    // Perform the gravity assist.\n    const double deltaV = mission_segments::gravityAssist( venusGravitationalParameter,\n                                                           venusVelocity,incomingVelocity,\n                                                           outgoingVelocity,\n                                                           venusSmallestPeriapsisDistance );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( deltaV, expectedDeltaV, tolerance );\n}\n\n//! Test velocity effect Delta-V computation using the eccentricity iteration scheme.\nBOOST_AUTO_TEST_CASE( testVelocityEffectDeltaVEccentricity )\n{\n    // Tolerance. Benchmark obtained directly from the GTOP code, based on the first swing-by for\n    // the ideal Cassini-1 trajectory. Values were obtained with a 15-digit accuracy from GTOP,\n    // resulting in an accuracy of 6e-14 in the final results.\n    const double tolerance = 1.0e-13;\n\n    // Expected deltaV cost, as obtained from GTOP code.\n    const double expectedDeltaV = 1090.64622870007;\n\n    // Define swingby body gravitational parameter.\n    const double venusGravitationalParameter = 3.24860e14;\n\n    // Define smallest periapsis distance factor.\n    const double venusSmallestPeriapsisDistance = 6351800.0;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d venusVelocity( 32851.224953746, -11618.7310059974, -2055.04615890989 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 34216.4827530912, -15170.1440677825,\n                                            395.792122152361 );\n\n    // Define heliocentric satellite outgoing vector.\n    const Eigen::Vector3d outgoingVelocity( 37954.2431376052, -14093.0467234774,\n                                            -5753.53728279429 );\n\n    // Set flag to use iteration scheme on eccentricity.\n    const bool useEccentricity = true;\n\n    // Perform the gravity assist.\n    const double deltaV = mission_segments::gravityAssist( venusGravitationalParameter,\n                                                           venusVelocity,incomingVelocity,\n                                                           outgoingVelocity,\n                                                           venusSmallestPeriapsisDistance,\n                                                           useEccentricity );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( deltaV, expectedDeltaV, tolerance );\n}\n\n//! Test limit case for deltaV computation with low incoming velocity with eccentricity iteration.\nBOOST_AUTO_TEST_CASE( testLimitCaseDeltaVLowIncomingVelocityEccentricity )\n{\n    // Tolerance.\n    const double tolerance = 1.0e-11;\n\n    // Expected deltaV cost, as obtained from this code, verified in Excel (Musegaas, 2012).\n    const double expectedDeltaV = 966.37867363;\n\n    // Define swingby body gravitational parameter.\n    const double venusGravitationalParameter = 3.24860e14;\n\n    // Define smallest periapsis distance factor.\n    const double venusSmallestPeriapsisDistance = 6351800.0;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d venusVelocity( 35000.0, 0.0 , 0.0 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 35000.01, 0.0, 0.0 );\n\n    // Define heliocentric satellite outgoing vector.\n    const Eigen::Vector3d outgoingVelocity( 35000.0 , 1000.0 , 0.0 );\n\n    // Set flag to use iteration scheme on eccentricity.\n    const bool useEccentricity = true;\n\n    // Perform the gravity assist.\n    const double deltaV = mission_segments::gravityAssist( venusGravitationalParameter,\n                                                           venusVelocity,incomingVelocity,\n                                                           outgoingVelocity,\n                                                           venusSmallestPeriapsisDistance,\n                                                           useEccentricity );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( deltaV, expectedDeltaV, tolerance );\n}\n\n//! Test limit case for deltaV computation with low outgoing velocity with eccentricity iteration.\nBOOST_AUTO_TEST_CASE( testLimitCaseDeltaVLowOutgoingVelocityEccentricity )\n{\n    // Tolerance.\n    const double tolerance = 1.0e-11;\n\n    // Expected deltaV cost, as obtained from this code, verified in Excel (Musegaas, 2012).\n    const double expectedDeltaV = 966.37867363;\n\n    // Define swingby body gravitational parameter.\n    const double venusGravitationalParameter = 3.24860e14;\n\n    // Define smallest periapsis distance factor.\n    const double venusSmallestPeriapsisDistance = 6351800.0;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d venusVelocity( 35000.0, 0.0 , 0.0 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 35000.0 , 1000.0 , 0.0 );\n\n    // Define heliocentric satellite outgoing vector.\n    const Eigen::Vector3d outgoingVelocity( 35000.01, 0.0, 0.0 );\n\n    // Set flag to use iteration scheme on eccentricity.\n    const bool useEccentricity = true;\n\n    // Perform the gravity assist.\n    const double deltaV = mission_segments::gravityAssist( venusGravitationalParameter,\n                                                           venusVelocity, incomingVelocity,\n                                                           outgoingVelocity,\n                                                           venusSmallestPeriapsisDistance,\n                                                           useEccentricity );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( deltaV, expectedDeltaV, tolerance );\n}\n\n//! Test limit case for deltaV computation with low velocities with eccentricity iteration.\nBOOST_AUTO_TEST_CASE( testLimitCaseDeltaVLowVelocitiesEccentricity )\n{\n    // Tolerance.\n    const double tolerance = 1.0e-9;\n\n    // Expected deltaV cost, as obtained from this code, verified in Excel (Musegaas, 2012).\n    const double expectedDeltaV = 0.004260780473;\n\n    // Define swingby body gravitational parameter.\n    const double venusGravitationalParameter = 3.24860e14;\n\n    // Define smallest periapsis distance factor.\n    const double venusSmallestPeriapsisDistance = 6351800.0;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d venusVelocity( 35000.0, 0.0 , 0.0 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 35000.0 , 0.02 , 0.0 );\n\n    // Define heliocentric satellite outgoing vector.\n    const Eigen::Vector3d outgoingVelocity( 35000.01, 0.0, 0.0 );\n\n    // Set flag to use iteration scheme on eccentricity.\n    const bool useEccentricity = true;\n\n    // Perform the gravity assist.\n    const double deltaV = mission_segments::gravityAssist( venusGravitationalParameter,\n                                                           venusVelocity,incomingVelocity,\n                                                           outgoingVelocity,\n                                                           venusSmallestPeriapsisDistance,\n                                                           useEccentricity );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( deltaV, expectedDeltaV, tolerance );\n}\n\n//! Test velocity effect Delta-V computation using the pericenter iteration scheme.\nBOOST_AUTO_TEST_CASE( testVelocityEffectDeltaVPericenter )\n{\n    // Tolerance. Benchmark obtained directly from the GTOP code, based on the first swing-by for\n    // the ideal Cassini-1 trajectory. Values were obtained with a 15-digit accuracy from GTOP,\n    // resulting in an accuracy of 6e-14 in the final results.\n    const double tolerance = 1.0e-13;\n\n    // Expected deltaV cost, as obtained from GTOP code.\n    const double expectedDeltaV = 1090.64622870007;\n\n    // Define swingby body gravitational parameter.\n    const double venusGravitationalParameter = 3.24860e14;\n\n    // Define smallest periapsis distance factor.\n    const double venusSmallestPeriapsisDistance = 6351800.0;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d venusVelocity( 32851.224953746, -11618.7310059974, -2055.04615890989 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 34216.4827530912, -15170.1440677825,\n                                            395.792122152361 );\n\n    // Define heliocentric satellite outgoing vector.\n    const Eigen::Vector3d outgoingVelocity( 37954.2431376052, -14093.0467234774,\n                                            -5753.53728279429 );\n\n    // Set flag to use iteration scheme on pericenter.\n    const bool useEccentricity = false;\n\n    // Perform the gravity assist.\n    const double deltaV = mission_segments::gravityAssist( venusGravitationalParameter,\n                                                           venusVelocity,incomingVelocity,\n                                                           outgoingVelocity,\n                                                           venusSmallestPeriapsisDistance,\n                                                           useEccentricity );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( deltaV, expectedDeltaV, tolerance );\n}\n\n//! Test limit case for deltaV computation with low incoming velocity with pericenter iteration.\nBOOST_AUTO_TEST_CASE( testLimitCaseDeltaVLowIncomingVelocityPericenter )\n{\n    // Tolerance.\n    const double tolerance = 1.0e-11;\n\n    // Expected deltaV cost, as obtained from this code, verified in Excel (Musegaas, 2012).\n    const double expectedDeltaV = 966.37867363;\n\n    // Define swingby body gravitational parameter.\n    const double venusGravitationalParameter = 3.24860e14;\n\n    // Define smallest periapsis distance factor.\n    const double venusSmallestPeriapsisDistance = 6351800.0;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d venusVelocity( 35000.0, 0.0 , 0.0 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 35000.01, 0.0, 0.0 );\n\n    // Define heliocentric satellite outgoing vector.\n    const Eigen::Vector3d outgoingVelocity( 35000.0 , 1000.0 , 0.0 );\n\n    // Set flag to use iteration scheme on eccentricity.\n    const bool useEccentricity = false;\n\n    // Perform the gravity assist.\n    const double deltaV = mission_segments::gravityAssist( venusGravitationalParameter,\n                                                           venusVelocity,incomingVelocity,\n                                                           outgoingVelocity,\n                                                           venusSmallestPeriapsisDistance,\n                                                           useEccentricity );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( deltaV, expectedDeltaV, tolerance );\n}\n\n//! Test limit case for deltaV computation with low outgoing velocity with pericenter iteration.\nBOOST_AUTO_TEST_CASE( testLimitCaseDeltaVLowOutgoingVelocityPericenter )\n{\n    // Tolerance.\n    const double tolerance = 1.0e-11;\n\n    // Expected deltaV cost, as obtained from this code, verified in Excel (Musegaas, 2012).\n    const double expectedDeltaV = 966.37867363;\n\n    // Define swingby body gravitational parameter.\n    const double venusGravitationalParameter = 3.24860e14;\n\n    // Define smallest periapsis distance factor.\n    const double venusSmallestPeriapsisDistance = 6351800.0;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d venusVelocity( 35000.0, 0.0 , 0.0 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 35000.0 , 1000.0 , 0.0 );\n\n    // Define heliocentric satellite outgoing vector.\n    const Eigen::Vector3d outgoingVelocity( 35000.01, 0.0, 0.0 );\n\n    // Set flag to use iteration scheme on pericenter.\n    const bool useEccentricity = false;\n\n    // Perform the gravity assist.\n    const double deltaV = mission_segments::gravityAssist( venusGravitationalParameter,\n                                                           venusVelocity,incomingVelocity,\n                                                           outgoingVelocity,\n                                                           venusSmallestPeriapsisDistance,\n                                                           useEccentricity );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( deltaV, expectedDeltaV, tolerance );\n}\n\n//! Test limit case for deltaV computation with low velocities with pericenter iteration.\nBOOST_AUTO_TEST_CASE( testLimitCaseDeltaVLowVelocitiesPericenter )\n{\n    // Tolerance.\n    const double tolerance = 1.0e-9;\n\n    // Expected deltaV cost, as obtained from this code, verified in Excel (Musegaas, 2012).\n    const double expectedDeltaV = 0.004260780473;\n\n    // Define swingby body gravitational parameter.\n    const double venusGravitationalParameter = 3.24860e14;\n\n    // Define smallest periapsis distance factor.\n    const double venusSmallestPeriapsisDistance = 6351800.0;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d venusVelocity( 35000.0, 0.0 , 0.0 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 35000.0 , 0.02 , 0.0 );\n\n    // Define heliocentric satellite outgoing vector.\n    const Eigen::Vector3d outgoingVelocity( 35000.01, 0.0, 0.0 );\n\n    // Set flag to use iteration scheme on pericenter.\n    const bool useEccentricity = false;\n\n    // Perform the gravity assist.\n    const double deltaV = mission_segments::gravityAssist( venusGravitationalParameter,\n                                                           venusVelocity,incomingVelocity,\n                                                           outgoingVelocity,\n                                                           venusSmallestPeriapsisDistance,\n                                                           useEccentricity );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( deltaV, expectedDeltaV, tolerance );\n}\n\n//! Test unpowered gravity assist propagation.\nBOOST_AUTO_TEST_CASE( testUnpoweredGravityAssistPropagation )\n{\n    // Tolerance. Benchmark obtained directly from the GTOP code, based on the first swing-by for\n    // the ideal Messenger trajectory. Values were obtained with a 15-digit accuracy from GTOP,\n    // resulting in an accuracy of 2e-14 in the final results.\n    const double tolerance = 1.0e-13;\n\n    // Expected deltaV cost, as obtained from GTOP code.\n    const Eigen::Vector3d expectedOutgoingVelocity( 12868.5248737923, -22821.444560174,\n                                                    -775.698475033994 );\n\n    // Define swingby body gravitational parameter.\n    const double earthGravitationalParameter = 3.9860119e14;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d earthVelocity( 15025.522196446, -25544.3782752036, 0.0 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 17969.3166254716, -23543.691593914, 6.38384671663496 );\n\n    // Define rotation angle.\n    const double rotationAngle = 1.35077257078;\n\n    // Define pericenter radius.\n    const double pericenterRadius = 1.80629232251 * 6378000.0;\n\n    // Perform the gravity assist.\n    const Eigen::Vector3d outgoingVelocity = mission_segments::gravityAssist(\n                                                    earthGravitationalParameter, earthVelocity,\n                                                    incomingVelocity, rotationAngle,\n                                                    pericenterRadius );\n\n    // Test if the computed outgoing velocity corresponds to the expected velocity within the\n    // specified tolerance.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedOutgoingVelocity, outgoingVelocity, tolerance );\n}\n\n//! Test powered gravity assist propagation function for unpowered gravity assist.\nBOOST_AUTO_TEST_CASE( testPoweredGravityAssistPropagationForUnpoweredGravityAssist )\n{\n    // Tolerance. Benchmark obtained directly from the GTOP code, based on the first swing-by for\n    // the ideal Messenger trajectory. Values were obtained with a 15-digit accuracy from GTOP,\n    // resulting in an accuracy of 2e-14 in the final results.\n    const double tolerance = 1.0e-13;\n\n    // Expected deltaV cost, as obtained from GTOP code.\n    const Eigen::Vector3d expectedOutgoingVelocity( 12868.5248737923, -22821.444560174,\n                                                    -775.698475033994 );\n\n    // Define swingby body gravitational parameter.\n    const double earthGravitationalParameter = 3.9860119e14;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d earthVelocity( 15025.522196446, -25544.3782752036, 0.0 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 17969.3166254716, -23543.691593914, 6.38384671663496 );\n\n    // Define rotation angle.\n    const double rotationAngle = 1.35077257078;\n\n    // Define pericenter radius.\n    const double pericenterRadius = 1.80629232251 * 6378000.0;\n\n    // Define deltaV.\n    const double deltaV = 0.0;\n\n    // Perform the gravity assist.\n    const Eigen::Vector3d outgoingVelocity = mission_segments::gravityAssist(\n                                                    earthGravitationalParameter, earthVelocity,\n                                                    incomingVelocity, rotationAngle,\n                                                    pericenterRadius, deltaV );\n\n    // Test if the computed outgoing velocity corresponds to the expected velocity within the\n    // specified tolerance.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedOutgoingVelocity, outgoingVelocity, tolerance );\n}\n\n//! Test powered gravity assist propagation function for reverse engineered test case.\nBOOST_AUTO_TEST_CASE( testPoweredGravityAssistPropagationReverseEngineered )\n{\n    // Tolerance. Benchmark obtained by reverse engineering the GTOP code, based on the first\n    // swing-by for the ideal Cassini-1 trajectory. Values were obtained with a 15-digit accuracy\n    // from GTOP, resulting in an accuracy of 1e-14 in the final results.\n    const double tolerance = 1.0e-14;\n\n    // Expected deltaV cost, as obtained from GTOP code.\n    const Eigen::Vector3d expectedOutgoingVelocity( 37954.2431376052, -14093.0467234774,\n                                                    -5753.53728279429 );\n\n    // Define swingby body gravitational parameter.\n    const double venusGravitationalParameter = 3.24860e14;\n\n    // Define heliocentric planet velocity vector.\n    const Eigen::Vector3d venusVelocity( 32851.224953746, -11618.7310059974, -2055.04615890989 );\n\n    // Define heliocentric satellite incoming vector.\n    const Eigen::Vector3d incomingVelocity( 34216.4827530912, -15170.1440677825,\n                                            395.792122152361 );\n\n    // Define rotation angle.\n    const double rotationAngle = -2.0291949514117;\n\n    // Define pericenter radius.\n    const double pericenterRadius = 6351801.04541467;\n\n    // Define deltaV.\n    const double deltaV = 1090.64622870007;\n\n    // Perform the gravity assist.\n    const Eigen::Vector3d outgoingVelocity = mission_segments::gravityAssist(\n                                                    venusGravitationalParameter, venusVelocity,\n                                                    incomingVelocity, rotationAngle,\n                                                    pericenterRadius, deltaV );\n\n    // Test if the computed outgoing velocity corresponds to the expected velocity within the\n    // specified tolerance.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedOutgoingVelocity, outgoingVelocity, tolerance );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "431f9002fda87ef411eac60dc0d19bb1e8bc4a1d", "size": 28984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/MissionSegments/UnitTests/unitTestGravityAssist.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/MissionSegments/UnitTests/unitTestGravityAssist.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/MissionSegments/UnitTests/unitTestGravityAssist.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.572327044, "max_line_length": 99, "alphanum_fraction": 0.6540505106, "num_tokens": 6451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5926716589184576}}
{"text": "// test CPU direct R solver\n\n#include <minisam/3rdparty/Catch2/catch.hpp>\n#include <minisam/utils/testAssertions.h>\n\n#include <minisam/linear/Covariance.h>\n#include <minisam/linear/SquareRootCholesky.h>\n\n#include <Eigen/LU> // rank\n\nusing namespace minisam;\n\n// exmaple systems\nEigen::SparseMatrix<double> H1(2,2), H2(2,2), H3(2,2), H;\nEigen::MatrixXd Hinv1(2,2), Hinv2(2,2), Hinv3(2,2), Hinv;\nconst int A_row = 40, A_col = 20;\n\n/* ************************************************************************** */\nTEST_CASE(\"Covariance_prep_static_values\", \"[linear]\") {\n\n  Eigen::SparseMatrix<double> A1(2,2), A2(2,2), A3(3,2);\n\n  // sys 1, identity\n  A1.insert(0,0) = 1.0;\n  A1.insert(1,1) = 1.0;\n  A1.makeCompressed();\n  H1 = A1.transpose() * A1;\n  Hinv1 = Eigen::MatrixXd::Identity(2, 2);\n\n  // sys 2, well-cond, use matlab get ground truth\n  A2.insert(0,0) = 3.2;\n  A2.insert(0,1) = 4.5;\n  A2.insert(1,0) = -1.9;\n  A2.insert(1,1) = 7.6;\n  A2.makeCompressed();\n  H2 = A2.transpose() * A2;\n  Hinv2 <<  7.220227298789961e-02,  3.702206024247995e-05,\n            3.702206024247995e-05,  1.281888835895923e-02;\n\n  // sys 3, over-cond, use matlab get ground truth\n  A3.insert(0,0) = 3.2;\n  A3.insert(0,1) = 4.5;\n  A3.insert(1,0) = -1.9;\n  A3.insert(1,1) = 7.6;\n  A3.insert(2,0) = 5.5;\n  A3.insert(2,1) = 3.4;\n  A3.makeCompressed();\n  H3 = A3.transpose() * A3;\n  Hinv3 <<  2.486783565761668e-02,  -5.180683413767191e-03,\n            -5.180683413767191e-03, 1.224373732835655e-02;\n\n  // use random A to generate test, to test whether R'R - ordering.permute(A'A) = 0\n  Eigen::MatrixXd A_dense;\n  int A_rank;\n  do {\n    A_dense = Eigen::MatrixXd::Random(A_row, A_col);\n    Eigen::FullPivLU<Eigen::MatrixXd> lu_decomp(A_dense);\n    A_rank = lu_decomp.rank();\n  } while (A_rank < A_col); // make sure full rank\n\n  Eigen::MatrixXd H_dense = A_dense.transpose() * A_dense;\n  H = H_dense.sparseView();\n  Hinv = H_dense.inverse();\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"Covariance_ground_truth\", \"[linear]\") {\n  // get ground truth from matlab\n  SquareRootSolverCholesky sqrsolver(OrderingMethod::NONE);\n  Eigen::SparseMatrix<double> L;\n  Eigen::MatrixXd Hinv_act; \n  std::vector<int> full_indices = {0, 1};\n\n  sqrsolver.initialize(H1);\n  sqrsolver.solveL(H1, L);\n  Covariance c1(L);\n  Hinv_act = c1.marginalCovariance(full_indices);\n  CHECK(assert_equal(Hinv1, Hinv_act));\n\n  sqrsolver.initialize(H2);\n  sqrsolver.solveL(H2, L);\n  Covariance c2(L);\n  Hinv_act = c2.marginalCovariance(full_indices);\n  CHECK(assert_equal(Hinv2, Hinv_act));\n\n  sqrsolver.initialize(H3);\n  sqrsolver.solveL(H3, L);\n  Covariance c3(L);\n  Hinv_act = c3.marginalCovariance(full_indices);\n  CHECK(assert_equal(Hinv3, Hinv_act));\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"Covariance_random\", \"[linear]\") {\n  // get ground truth from matlab\n  SquareRootSolverCholesky sqrsolver(OrderingMethod::NONE);\n  Eigen::SparseMatrix<double> L;\n  Eigen::MatrixXd Hinv_act, Hinv_partial;\n  std::vector<int> full_indices;\n\n  sqrsolver.initialize(H);\n  sqrsolver.solveL(H, L);\n  Covariance c(L);\n\n  // block index\n  full_indices = {5, 6, 7, 8};\n  Hinv_act = c.marginalCovariance(full_indices);\n  Hinv_partial = Hinv.block(5, 5, 4, 4);\n  CHECK(assert_equal(Hinv_partial, Hinv_act));\n\n  // full index\n  full_indices.clear();\n  for (int i = 0; i < A_col; i++) full_indices.push_back(i);\n  Hinv_act = c.marginalCovariance(full_indices);\n  CHECK(assert_equal(Hinv, Hinv_act));\n}", "meta": {"hexsha": "f130ec1b95b22bab9009afde7020b2c1509fde72", "size": 3528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testCovariance.cpp", "max_stars_repo_name": "versatran01/minisam", "max_stars_repo_head_hexsha": "b3840d2629551fdfa287df8aac2e7956873d2b0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 338.0, "max_stars_repo_stars_event_min_datetime": "2019-09-03T10:44:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:12:08.000Z", "max_issues_repo_path": "tests/testCovariance.cpp", "max_issues_repo_name": "bhsphd/minisam", "max_issues_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2019-09-26T09:00:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T06:04:02.000Z", "max_forks_repo_path": "tests/testCovariance.cpp", "max_forks_repo_name": "bhsphd/minisam", "max_forks_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 87.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T05:17:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T09:47:23.000Z", "avg_line_length": 30.4137931034, "max_line_length": 83, "alphanum_fraction": 0.6346371882, "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.5926716565525185}}
{"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": "#include \"matrixIO.hpp\"\n#include <Eigen/Dense>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace matrixIO {\n\nvoid saveData(const string &fileName, const MatrixXd &matrix)\n{\n  // see https://eigen.tuxfamily.org/dox/structEigen_1_1IOFormat.html\n  const static IOFormat CSVFormat(FullPrecision, DontAlignCols, \", \", \"\\n\");\n\n  ofstream file(fileName);\n  if (file.is_open()) {\n    file << matrix.format(CSVFormat);\n    file.close();\n  }\n}\n\nMatrixXd openData(const string &fileToOpen, const int matrixSize)\n{\n  ifstream matrixDataFile(fileToOpen);\n\n  // one row of the matrix as a string with comma-separated values\n  string matrixRowString;\n\n  // a single matrix entry as a string\n  string matrixEntry;\n\n  // matrix entries row by row\n  vector<double> matrixEntries;\n\n  int matrixRowNumber = 0;\n  int matrixColNumber = 0;\n\n  // read matrixDataFile row by row\n  while (getline(matrixDataFile, matrixRowString)) {\n    // convert matrixRowString to a stream\n    stringstream matrixRowStringStream(matrixRowString);\n\n    // read matrixRowStringStream entry by entry\n    while (getline(matrixRowStringStream, matrixEntry, ',')) {\n      matrixEntries.push_back(stod(matrixEntry));\n      ++matrixColNumber;\n    }\n    if (matrixColNumber != matrixSize) {\n      throw std::runtime_error(\"The matrix stored in \\\"\" + fileToOpen +\n                               \"\\\" has \" + std::to_string(matrixColNumber) +\n                               \" columns, while the specified matrix size is \" +\n                               std::to_string(matrixSize));\n    }\n    matrixColNumber = 0;\n    ++matrixRowNumber;\n  }\n\n  if (matrixRowNumber != matrixSize) {\n    throw std::runtime_error(\"The matrix stored in \\\"\" + fileToOpen +\n                             \"\\\" has \" + std::to_string(matrixRowNumber) +\n                             \" rows, while the specified matrix size is \" +\n                             std::to_string(matrixSize));\n  }\n\n  // convert std vector into Eigen matrix and return the matrix\n  return Map<Matrix<double, Dynamic, Dynamic, RowMajor>>(\n      matrixEntries.data(), matrixRowNumber,\n      matrixEntries.size() / matrixRowNumber);\n}\n\n} // namespace matrixIO\n", "meta": {"hexsha": "1a2cd03265fc372c746fdf1c0339997202a5ff44", "size": 2218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/matrixIO.cpp", "max_stars_repo_name": "kimkroener/testing-boost-exercise", "max_stars_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrixIO.cpp", "max_issues_repo_name": "kimkroener/testing-boost-exercise", "max_issues_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2022-01-29T01:07:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T16:49:23.000Z", "max_forks_repo_path": "src/matrixIO.cpp", "max_forks_repo_name": "kimkroener/testing-boost-exercise", "max_forks_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-01T16:22:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T16:22:19.000Z", "avg_line_length": 29.972972973, "max_line_length": 80, "alphanum_fraction": 0.6532912534, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.5926354395755931}}
{"text": "// Copyright (C) 2019 David Harmon and Artificial Necessity\n// This code distributed under zlib, see LICENSE.txt for terms.\n\n#pragma once\n\n#include <Eigen/Core>\n\n\ntemplate<typename Scalar, int K>\nclass kDOP {\npublic:\n    using VectorK  = Eigen::Matrix<Scalar, K/2, 1>;\n    using MatrixK3 = Eigen::Matrix<Scalar, K/2, 3>;\n\n    kDOP() { setEmpty(); }\n\n    void setEmpty() {\n        min_ = VectorK::Constant(std::numeric_limits<Scalar>::max());\n        max_ = VectorK::Constant(std::numeric_limits<Scalar>::min());\n    }\n\n    template<typename Derived>\n    kDOP& extendK(const Eigen::MatrixBase<Derived>& vals) {\n        min_ = min_.cwiseMin(vals);\n        max_ = max_.cwiseMax(vals);\n        return *this;\n    }\n\n    template<typename Derived>\n    kDOP& extend(const Eigen::MatrixBase<Derived>& p) {\n        VectorK p_proj = project(p);\n        min_ = min_.cwiseMin(p_proj);\n        max_ = max_.cwiseMax(p_proj);\n        return *this;\n    }\n\n    kDOP& extend(const kDOP& b) {\n        min_ = min_.cwiseMin(b.min_);\n        max_ = max_.cwiseMax(b.max_);\n        return *this;\n    }\n\n    template<typename Derived>\n    bool contains(const Eigen::MatrixBase<Derived>& p) const {\n        VectorK p_proj = project(p);\n        return (min_.array() <= p_proj.array()).all() &&\n               (p_proj.array() <= max_.array()).all();\n    }\n\n    bool intersects(const kDOP& b) const {\n        return (min_.array() <= (b.max)().array()).all() &&\n                ((b.min)().array() <= max_.array()).all();\n    }\n\n    template<typename Derived>\n    VectorK project(const Eigen::MatrixBase<Derived>& p) const {\n        return Eigen::Map<const MatrixK3>(dirs.data()) * p;\n    }\n\n    const VectorK& min() const { return min_; }\n    const VectorK& max() const { return max_; }\n\nprotected:\n    VectorK min_;\n    VectorK max_;\n\n    static constexpr std::array<Scalar, 39> dirs = {\n            1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0,\n            0, 1, 0, 1, -1, 1, -1, 1, 0, 1, -1, 0, 1,\n            0, 0, 1, 1, 1, -1, -1, 0, 1, 1, 0, -1, -1 };\n};\n\nusing kDOP26d = kDOP<double, 26>;\n\n", "meta": {"hexsha": "a2d88843b8d8cc46c316abefd4fa0b48207c3e3b", "size": 2060, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kdop.hpp", "max_stars_repo_name": "liuwei792966953/stitch", "max_stars_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-23T05:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-23T05:20:09.000Z", "max_issues_repo_path": "include/kdop.hpp", "max_issues_repo_name": "liuwei792966953/stitch", "max_issues_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/kdop.hpp", "max_forks_repo_name": "liuwei792966953/stitch", "max_forks_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4666666667, "max_line_length": 69, "alphanum_fraction": 0.5718446602, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5926354314942922}}
{"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": "#include <fstream>\n#include \"sys.h\"\n#include \"math/Mat.h\"\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace nla3d;\nusing namespace nla3d::math;\n\nconst double eps = 0.000001;\nuint16 tn = 100;\nchar* dir;\n\ntemplate<typename M1, typename M2>\nbool eigen_compare(const Eigen::MatrixBase<M1>& ref, const Eigen::MatrixBase<M2>& res, double eps = 0.001) {\n  assert(ref.rows() == res.rows());\n  assert(ref.cols() == res.cols());\n  for (uint16 i = 0; i < ref.rows(); i++) {\n    for (uint16 j = 0; j < ref.cols(); j++) {\n      if (fabs(ref(i,j) - res(i,j)) > eps) {\n        LOG(ERROR) << \"Matrices are different\";\n        exit(1);\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\nbool test_matBVprod () {\n\tstd::ifstream in;\n\tconst uint16 _N = 24;\n\tconst uint16 _M = 9;\n\tchar filename[100];\n\tMat<_N,_M> B;\n\tVec<_M> V;\n\tVec<_N> Rf;\n\tVec<_N> R;\n\n  Eigen::MatrixXd e_B;\n  Eigen::VectorXd e_V;\n  Eigen::VectorXd e_R;\n\n  sprintf_s(filename,100,\"%s/matBVprod_%02d%02d\",dir,_N,_M);\n  in.open(filename);\n\tfor (uint16 gg = 1; gg <= tn; gg++) {\n\t\tB.zero();\n\t\tV.zero();\n\t\tR.zero();\n\t\tRf.zero();\n\n\t\tB.simple_read(in);\n\t\tV.simple_read(in);\n\t\tRf.simple_read(in);\n\n\t\tmatBVprod(B, V, 1.0, R);\n\n    e_B = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > (B.ptr(), _N, _M);\n    e_V = Eigen::Map<Eigen::VectorXd> (V.ptr(), _M, 1);\n\n    e_R = e_B*e_V;\n\n\t\tif (!R.compare(Rf, eps)) {\n\t\t\tLOG(ERROR) << \"test_matBVprod: n = \" << gg;\n      exit(1);\n\t\t}\n    eigen_compare(Eigen::Map<Eigen::MatrixXd> (Rf.ptr(),_N,1),e_R);\n\t\tDLOG(DEBUG) << \"test_matBVprod: case \" << gg << \" checked successfuly!\";\n\t}\n  in.close();\n\treturn true;\n}\n\nbool test_matBTVprod () {\n\tstd::ifstream in;\n\tconst uint16 _N = 24;\n\tconst uint16 _M = 9;\n\tchar filename[100];\n\tMat<_N,_M> B;\n\tVec<_N> V;\n\tVec<_M> Rf;\n\tVec<_M> R;\n\n  Eigen::MatrixXd e_B;\n  Eigen::VectorXd e_V;\n  Eigen::VectorXd e_R;\n\n  sprintf_s(filename,100, \"%s/matBTVprod_%02d%02d\", dir, _N, _M);\n  in.open(filename);\n\tfor (uint16 gg = 1; gg <= tn; gg++) {\n\t\tB.zero();\n\t\tV.zero();\n\t\tR.zero();\n\t\tRf.zero();\n\n\t\tB.simple_read(in);\n\t\tV.simple_read(in);\n\t\tRf.simple_read(in);\n\n\t\tmatBTVprod(B, V, 1.0, R);\n\n    e_B = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > (B.ptr(), _N, _M);\n    e_V = Eigen::Map<Eigen::VectorXd> (V.ptr(), _N, 1);\n\n    e_R = e_B.transpose()*e_V;\n\n\t\tif (!R.compare(Rf, eps)) {\n\t\t\tLOG(ERROR) << \"test_matBTVprod: n = \" << gg;\n      exit(1);\n\t\t}\n    eigen_compare(Eigen::Map<Eigen::MatrixXd > (Rf.ptr(),_M,1), e_R);\n\t\tDLOG(DEBUG) << \"test_matBTVprod: case \" << gg << \" checked successfuly!\";\n\t}\n  in.close();\n\treturn true;\n}\n\nbool test_matABprod () {\n  std::ifstream in;\n\tconst uint16 _N = 24;\n\tconst uint16 _M = 9;\n\tconst uint16 _M2= 12;\n\tchar filename[100];\n\tMat<_N,_M>  A;\n\tMat<_M,_M2> B;\n\tMat<_N,_M2> R;\n\tMat<_N,_M2> Rf;\n  Eigen::MatrixXd e_A, e_B, e_R;\n  sprintf_s(filename,100, \"%s/matABprod_%02d%02d%02d\", dir, _N, _M, _M2);\n  in.open(filename);\n\tfor (uint16 gg = 1; gg <= tn; gg++) {\n\t\tA.zero();\n\t\tB.zero();\n\t\tR.zero();\n\t\tRf.zero();\n\n\t\tA.simple_read(in);\n\t\tB.simple_read(in);\n\t\tRf.simple_read(in);\n\n\t\tmatABprod(A, B, 1.0, R);\n\n    e_A = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > (A.ptr(), _N, _M);\n    e_B = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > (B.ptr(), _M, _M2);\n    e_R = e_A * e_B;\n\t\tif (!R.compare(Rf, eps)) {\n\t\t\tLOG(ERROR) << \"test_matABprod: n = \" << gg;\n      exit(1);\n\t\t}\n    eigen_compare(Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > (Rf.ptr(),_N, _M2),\n       e_R);\n\t\tDLOG(DEBUG) << \"test_matABprod: case \" << gg << \" checked successfuly!\";\n\t}\n  in.close();\n\treturn true;\n}\n\nbool test_matATBprod () {\n  std::ifstream in;\n\tconst uint16 _M = 24;\n\tconst uint16 _N = 9;\n\tconst uint16 _N2= 12;\n\tchar filename[100];\n\tMat<_M,_N>  A;\n\tMat<_M,_N2> B;\n\tMat<_N,_N2> R;\n\tMat<_N,_N2> Rf;\n\n  Eigen::MatrixXd e_A, e_B, e_R;\n  sprintf_s(filename,100, \"%s/matATBprod_%02d%02d%02d\", dir, _M, _N, _N2);\n  in.open(filename);\n\tfor (uint16 gg = 1; gg <= tn; gg++) {\n\t\tA.zero();\n\t\tB.zero();\n\t\tR.zero();\n\t\tRf.zero();\n\n\t\tA.simple_read(in);\n\t\tB.simple_read(in);\n\t\tRf.simple_read(in);\n\n\t\tmatATBprod(A, B, 1.0, R);\n\n\n    e_A = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > (A.ptr(), _M, _N);\n    e_B = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > (B.ptr(), _M, _N2);\n    e_R = e_A.transpose() * e_B;\n\t\tif (!R.compare(Rf, eps)) {\n\t\t\tLOG(ERROR) << \"test_matATBprod: n = \" << gg;\n      exit(1);\n\t\t}\n    eigen_compare(Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > (Rf.ptr(),_N, _N2),\n       e_R);\n\t\tDLOG(DEBUG) << \"test_matATBprod: case \" << gg << \" checked successfuly!\";\n\t}\n  in.close();\n\treturn true;\n}\n\nbool test_matBTDBprod () {\n  std::ifstream in;\n\tconst uint16 _M = 24;\n\tconst uint16 _N = 9;\n\tchar filename[100];\n\tMat<_M,_N>  B;\n\tMatSym<_M> D;\n\tMatSym<_N> R;\n\tMatSym<_N> Rf;\n  Eigen::MatrixXd e_D, e_B, e_R;\n  sprintf_s(filename,100, \"%s/matBTDBprod_%02d%02d\", dir, _M, _N);\n  in.open(filename);\n\tfor (uint16 gg = 1; gg <= tn; gg++) {\n\t\tD.zero();\n\t\tB.zero();\n\t\tR.zero();\n\t\tRf.zero();\n\n\t\tB.simple_read(in);\n\t\tD.simple_read(in);\n\t\tRf.simple_read(in);\n\n\t\tmatBTDBprod(B, D, 1.0, R);\n\n\n    e_D.resize(_M,_M);\n    uint16 c = 0;\n    for (uint16 i = 0; i < _M; i++) {\n      for (uint16 j = i; j < _M; j++) {\n        e_D(i,j) = D.data[c];\n        c++;\n      }\n    }\n    //cout << \"e_D = \" << endl << e_D << endl;\n    //Eigen::MatrixXd tmp = e_D.selfadjointView<Eigen::Upper>();\n    //cout << \"e_D.symmetric_view = \" << endl << tmp;\n    e_B = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > (B.ptr(), _M, _N);\n    e_R = e_B.transpose() *  e_D.selfadjointView<Eigen::Upper>() * e_B;\n    Eigen::MatrixXd e_Rf(_N, _N);\n    c = 0;\n    for (uint16 i = 0; i < _N; i++) {\n      for (uint16 j = i; j < _N; j++) {\n        e_Rf(i,j) = Rf.data[c];\n        c++;\n      }\n    }\n    e_Rf = e_Rf.selfadjointView<Eigen::Upper>();\n    cout << \"e_Rf.rows = \" << e_Rf.rows() << \",e_Rf.cols = \" << e_Rf.cols() << endl;\n    cout << \"e_R.rows = \" << e_R.rows() << \",e_R.cols = \" << e_R.cols() << endl;\n    eigen_compare(e_Rf, e_R);\n\t\tif (!R.compare(Rf, eps)) {\n\t\t\tLOG(ERROR) << \"test_matBTDBprod: n = \" << gg;\n      exit(1);\n\t\t}\n\t\tDLOG(DEBUG) << \"test_matBTDBprod: case \" << gg << \" checked successfuly!\";\n\t}\n  in.close();\n\treturn true;\n}\n\nint main (int argc, char* argv[]) {\n  char* tmp = getCmdOption(argv, argv + argc, \"-dir\");\n  if (tmp) {\n    dir = tmp;\n  } else {\n    LOG(FATAL) << \"You shoud provide directory with test data\";\n  }\n\n  tmp = getCmdOption(argv, argv + argc, \"-num\");\n  if (tmp) {\n    tn = atoi(tmp);\n  }\n\ttest_matBVprod();\n\ttest_matBTVprod();\n\ttest_matABprod();\n\ttest_matATBprod();\n\ttest_matBTDBprod();\n}\n", "meta": {"hexsha": "85f4446335699d550b7ff77953312dac2f989c21", "size": 6869, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/eigen_mat_prod_test.cpp", "max_stars_repo_name": "pinkieli/nla3d", "max_stars_repo_head_hexsha": "7c7d0d63e69608c624924e60a70598e1e363d5cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T16:19:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T10:50:11.000Z", "max_issues_repo_path": "test/eigen_mat_prod_test.cpp", "max_issues_repo_name": "pinkieli/nla3d", "max_issues_repo_head_hexsha": "7c7d0d63e69608c624924e60a70598e1e363d5cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T11:42:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T06:11:12.000Z", "max_forks_repo_path": "test/eigen_mat_prod_test.cpp", "max_forks_repo_name": "pinkieli/nla3d", "max_forks_repo_head_hexsha": "7c7d0d63e69608c624924e60a70598e1e363d5cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-03-28T11:31:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-29T16:35:04.000Z", "avg_line_length": 24.7086330935, "max_line_length": 121, "alphanum_fraction": 0.5848012811, "num_tokens": 2416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236824, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5925710443383161}}
{"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 * @file solvecauchyproblem.cc\n * @brief NPDE exam problem summer 2019 \"CLEmpiricFlux\" code\n * @author Oliver Rietmann\n * @date 19.07.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"solvecauchyproblem.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n\n#include \"uniformcubicspline.h\"\n\nnamespace CLEmpiricFlux {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector2d findSupport(const UniformCubicSpline &f,\n                            Eigen::Vector2d initsupp, double t) {\n  Eigen::Vector2d result;\n  //====================\n  // Your code goes here\n  //====================\n  return result;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\ntemplate <typename FUNCTOR>\nEigen::VectorXd semiDiscreteRhs(const Eigen::VectorXd &mu0, double h,\n                                FUNCTOR &&numFlux) {\n  int m = mu0.size();\n  Eigen::VectorXd mu1(m);\n  //====================\n  // Your code goes here\n  //====================\n  return mu1;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\ntemplate <typename FUNCTOR>\nEigen::VectorXd RalstonODESolver(FUNCTOR &&rhs, Eigen::VectorXd mu0, double tau,\n                                 int n) {\n  //====================\n  // Your code goes here\n  //====================\n  return mu0;\n}\n/* SAM_LISTING_END_3 */\n\n/* SAM_LISTING_BEGIN_4 */\nEigen::VectorXd solveCauchyProblem(const UniformCubicSpline &f,\n                                   const Eigen::VectorXd &mu0, double h,\n                                   double T) {\n  Eigen::VectorXd muT(mu0.size());\n  //====================\n  // Your code goes here\n  //====================\n  return muT;\n}\n/* SAM_LISTING_END_4 */\n\n}  // namespace CLEmpiricFlux\n", "meta": {"hexsha": "2591e816d98158a3247b1ec261ead19e0d4f8d3e", "size": 1638, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/CLEmpiricFlux/templates/solvecauchyproblem.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/CLEmpiricFlux/templates/solvecauchyproblem.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/CLEmpiricFlux/templates/solvecauchyproblem.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": 24.8181818182, "max_line_length": 80, "alphanum_fraction": 0.5634920635, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.5925075668068217}}
{"text": "#include <Eigen/Dense>\n\nEigen::VectorXd  get_transition_probs_byind(Eigen::VectorXi rhovec_inds, double krnl, int ind_current){\n  int nrhos = rhovec_inds.rows();\n  Eigen::VectorXd  prop_prob(nrhos);\n  for(int i=0; i<nrhos; i++){ prop_prob(i) = exp(-krnl*pow((double)rhovec_inds(i)-(double)ind_current,2.0)); }\n  prop_prob(ind_current) = 0.0;\n  double sumInv = 1.0 / prop_prob.sum();\n  prop_prob = sumInv * prop_prob;\n  return prop_prob;\n}\n", "meta": {"hexsha": "131bc983fd407919f800edf65644ed9a6f47a7ad", "size": 439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fifa_gp/sampleMHfuncs.cpp", "max_stars_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_stars_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fifa_gp/sampleMHfuncs.cpp", "max_issues_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_issues_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fifa_gp/sampleMHfuncs.cpp", "max_forks_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_forks_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5833333333, "max_line_length": 110, "alphanum_fraction": 0.7129840547, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.5925075628704635}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestNormalDistribution\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/algorithm/count_if.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/random/default_random_engine.hpp>\n#include <boost/compute/random/normal_distribution.hpp>\n#include <boost/compute/lambda.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\n#include \"context_setup.hpp\"\n\ntemplate <class Stats, class T>\nboost::accumulators::accumulator_set<T, Stats>\naccumulate_statistics(const boost::compute::vector<T> &vector,\n                      boost::compute::command_queue &queue)\n{\n    // copy vector to the host\n    std::vector<T, mi_stl_allocator<T>> host_vector(vector.size());\n    boost::compute::copy(\n        vector.begin(), vector.end(), host_vector.begin(), queue);\n\n    // compute desired statistics and return accumulator object\n    return std::for_each(\n        host_vector.begin(),\n        host_vector.end(),\n        boost::accumulators::accumulator_set<T, Stats>());\n}\n\nBOOST_AUTO_TEST_CASE(normal_distribution_doctest)\n{\n    using boost::compute::lambda::_1;\n\n    boost::compute::vector<float> vec(10, context);\n\n    //! [generate]\n    // initialize the default random engine\n    boost::compute::default_random_engine engine(queue);\n\n    // setup the normal distribution to produce floats centered at 5\n    boost::compute::normal_distribution<float> distribution(5.0f, 1.0f);\n\n    // generate the random values and store them to 'vec'\n    distribution.generate(vec.begin(), vec.end(), engine, queue);\n    //! [generate]\n}\n\nBOOST_AUTO_TEST_CASE(normal_distribution_statistics)\n{\n    // generate normally distributed random numbers\n    const size_t n = 10000;\n    boost::compute::vector<float> vec(n, context);\n    boost::compute::default_random_engine engine(queue);\n    boost::compute::normal_distribution<float> distribution(10.0f, 2.0f);\n    distribution.generate(vec.begin(), vec.end(), engine, queue);\n\n    // compute mean and standard deviation\n    using namespace boost::accumulators;\n    accumulator_set<float, stats<tag::variance>> acc =\n        accumulate_statistics<stats<tag::variance>>(vec, queue);\n\n    // check mean and standard deviation are what we expect\n    BOOST_CHECK_CLOSE(mean(acc), 10.f, 0.5f);\n    BOOST_CHECK_CLOSE(std::sqrt(variance(acc)), 2.f, 0.5f);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d144c4a945e56fd36a2d3c8dcb6c004528a59194", "size": 3033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "compute/test/test_normal_distribution.cpp", "max_stars_repo_name": "atksh/mimalloc-lgb", "max_stars_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "compute/test/test_normal_distribution.cpp", "max_issues_repo_name": "atksh/mimalloc-lgb", "max_issues_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute/test/test_normal_distribution.cpp", "max_forks_repo_name": "atksh/mimalloc-lgb", "max_forks_repo_head_hexsha": "add692a5ef9a91cad0bc78fa18a051d43a8c930e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1071428571, "max_line_length": 79, "alphanum_fraction": 0.6917243653, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5925075542331285}}
{"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 \"types.h\"\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <Eigen/Geometry>\n#include <iostream>\n\nusing namespace sdrsac;\nnamespace py = pybind11;\n\nPYBIND11_MODULE(_kabsch, m) {\n    m.def(\"kabsch\", [](const Matrix3X& model, const Matrix3X& target) -> std::pair<Matrix3, Vector3> {\n        const auto res = Eigen::umeyama(model, target, false);\n        return std::make_pair(res.block<3, 3>(0, 0), res.col(3).head<3>());\n    });\n\n#ifdef VERSION_INFO\n    m.attr(\"__version__\") = VERSION_INFO;\n#else\n    m.attr(\"__version__\") = \"dev\";\n#endif\n}", "meta": {"hexsha": "e0c0969d79cf9023c98dd67dd65c284f5f426e39", "size": 567, "ext": "cc", "lang": "C++", "max_stars_repo_path": "sdrsac/cc/kabsch_py.cc", "max_stars_repo_name": "neka-nat/sdrsac", "max_stars_repo_head_hexsha": "84f07799c3c08960a4e1b7b62ca01aaffb8da3bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-11-07T01:08:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-30T05:57:23.000Z", "max_issues_repo_path": "sdrsac/cc/kabsch_py.cc", "max_issues_repo_name": "jtpils/sdrsac-1", "max_issues_repo_head_hexsha": "23aafd532239c587a7e148ddc62d3e2398aacc6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-09T12:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-11T08:22:12.000Z", "max_forks_repo_path": "sdrsac/cc/kabsch_py.cc", "max_forks_repo_name": "jtpils/sdrsac-1", "max_forks_repo_head_hexsha": "23aafd532239c587a7e148ddc62d3e2398aacc6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-07T01:54:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-17T00:17:35.000Z", "avg_line_length": 27.0, "max_line_length": 102, "alphanum_fraction": 0.6666666667, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5924797563198498}}
{"text": "\ufeff#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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// With contributions from Cornelius Steinhardt\n\n#ifndef MTL_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\u2013344. 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": "#include \"dynet/saxe-init.h\"\n#include \"dynet/tensor.h\"\n#include \"dynet/tensor-eigen.h\"\n#include \"dynet/globals.h\"\n\n#include <random>\n#include <cstring>\n\n#include <Eigen/SVD>\n\nusing namespace std;\n\nnamespace dynet {\n\nvoid orthonormal_random(unsigned dd, float g, Tensor& x) {\n  Tensor t;\n  t.d = Dim({dd, dd});\n  t.v = new float[dd * dd];\n  normal_distribution<float> distribution(0, 0.01);\n  auto b = [&] () {return distribution(*rndeng);};\n  generate(t.v, t.v + dd*dd, b);\n  Eigen::JacobiSVD<Eigen::MatrixXf> svd(mat(t), Eigen::ComputeFullU);\n  mat(x) = svd.matrixU();\n  delete[] t.v;\n}\n\n}\n\n", "meta": {"hexsha": "c10b03340959e31b498915378adf29241476e537", "size": 592, "ext": "cc", "lang": "C++", "max_stars_repo_path": "dynet/saxe-init.cc", "max_stars_repo_name": "ruyimarone/dynet", "max_stars_repo_head_hexsha": "67bace3fb1d79327ada53b248e497c894819760d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3307.0, "max_stars_repo_stars_event_min_datetime": "2016-10-08T15:51:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:40:44.000Z", "max_issues_repo_path": "dynet/saxe-init.cc", "max_issues_repo_name": "ruyimarone/dynet", "max_issues_repo_head_hexsha": "67bace3fb1d79327ada53b248e497c894819760d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1348.0, "max_issues_repo_issues_event_min_datetime": "2016-10-08T14:36:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T15:19:27.000Z", "max_forks_repo_path": "dynet/saxe-init.cc", "max_forks_repo_name": "ruyimarone/dynet", "max_forks_repo_head_hexsha": "67bace3fb1d79327ada53b248e497c894819760d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 741.0, "max_forks_repo_forks_event_min_datetime": "2016-10-09T04:44:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T22:29:02.000Z", "avg_line_length": 20.4137931034, "max_line_length": 69, "alphanum_fraction": 0.660472973, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436727, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5923813968781636}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <math/prim/mat/prob/vector_rng_test_helper.hpp>\n#include <limits>\n#include <vector>\n\nclass BetaProportionTestRig : public VectorRealRNGTestRig {\n public:\n  BetaProportionTestRig()\n      : VectorRealRNGTestRig(10000, 10, {0.3, 0.4, 0.5, 0.6, 0.7}, {1, 2, 3},\n                             {-2.5, -1.7, -0.1, 0.0}, {-3, -2, -1, 0},\n                             {0.35, 0.5, 0.9, 1.7, 2.1, 4.1}, {1, 2, 3, 4},\n                             {-2.7, -1.5, -0.5, 0.0}, {-3, -2, -1, 0}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& mu, const T2& kappa, const T3&,\n                        T_rng& rng) const {\n    return stan::math::beta_proportion_rng(mu, kappa, rng);\n  }\n\n  std::vector<double> generate_quantiles(double mu, double kappa,\n                                         double) const {\n    // transform from location and precision parameterization\n    // into shape1 (alpha) and shape2 (beta) parameterization\n    double alpha = mu * kappa;\n    double beta = kappa - alpha;\n    std::vector<double> quantiles;\n    double K = stan::math::round(2 * std::pow(N_, 0.4));\n    boost::math::beta_distribution<> dist(alpha, beta);\n\n    for (int i = 1; i < K; ++i) {\n      double frac = i / K;\n      quantiles.push_back(quantile(dist, frac));\n    }\n    quantiles.push_back(std::numeric_limits<double>::max());\n\n    return quantiles;\n  }\n};\n\nTEST(ProbDistributionsBetaProportion, errorCheck) {\n  check_dist_throws_real_first_argument(BetaProportionTestRig());\n}\n\nTEST(ProbDistributionsBetaProportion, distributionTest) {\n  check_quantiles_real_first_argument(BetaProportionTestRig());\n}\n", "meta": {"hexsha": "7070b82bed04d25856cb9c19c7f9966db4c874c9", "size": 1788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/mat/prob/beta_proportion_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/prim/mat/prob/beta_proportion_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/prim/mat/prob/beta_proportion_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.76, "max_line_length": 77, "alphanum_fraction": 0.6230425056, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5923738202493446}}
{"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": "#pragma once\r\n#ifndef NN_HPP\r\n#define NN_HPP\r\n\r\n#define EIGEN_NO_DEBUG\r\n\r\n// c++ libraries\r\n#include <iosfwd>\r\n// eigen\r\n#include <Eigen/Dense>\r\n// ann - math\r\n#include \"src/math/random.hpp\"\r\n// ann - mem\r\n#include \"src/mem/serialize.hpp\"\r\n// ann - typedef\r\n#include \"src/util/typedef.hpp\"\r\n\r\nnamespace NN{\r\n\t\r\n//***********************************************************************\r\n// COMPILER DIRECTIVES\r\n//***********************************************************************\r\n\r\n#ifndef NN_PRINT_FUNC\r\n#define NN_PRINT_FUNC 0\r\n#endif\r\n\r\n#ifndef NN_PRINT_STATUS\r\n#define NN_PRINT_STATUS 0\r\n#endif\r\n\r\n#ifndef NN_PRINT_DATA\r\n#define NN_PRINT_DATA 0\r\n#endif\r\n\r\n//***********************************************************************\r\n// FORWARD DECLARATIONS\r\n//***********************************************************************\r\n\r\nclass ANN;\r\nclass ANNInit;\r\nclass Cost;\r\nclass DOutDVal;\r\nclass DOutDP;\r\nclass D2OutDPDVal;\r\n\r\n//***********************************************************************\r\n// INITIALIZATION METHOD\r\n//***********************************************************************\r\n\r\nclass Init{\r\npublic:\r\n\t//enum\r\n\tenum Type{\r\n\t\tUNKNOWN=0,\r\n\t\tRAND=1,\r\n\t\tXAVIER=2,\r\n\t\tHE=3,\r\n\t\tMEAN=4\r\n\t};\r\n\t//constructor\r\n\tInit():t_(Type::UNKNOWN){}\r\n\tInit(Type t):t_(t){}\r\n\t//operators\r\n\toperator Type()const{return t_;}\r\n\t//member functions\r\n\tstatic Init read(const char* str);\r\n\tstatic const char* name(const Init& init);\r\nprivate:\r\n\tType t_;\r\n\t//prevent automatic conversion for other built-in types\r\n\t//template<typename T> operator T() const;\r\n};\r\nstd::ostream& operator<<(std::ostream& out, const Init& init);\r\n\r\n//***********************************************************************\r\n// TRANSFER FUNCTIONS \r\n//***********************************************************************\r\n\r\nclass Transfer{\r\npublic:\r\n\t//type\r\n\tenum Type{\r\n\t\tUNKNOWN=0,\r\n\t\tLINEAR=1,\r\n\t\tSIGMOID=2,\r\n\t\tTANH=3,\r\n\t\tISRU=4,\r\n\t\tARCTAN=5,\r\n\t\tSOFTSIGN=6,\r\n\t\tRELU=7,\r\n\t\tSOFTPLUS=8,\r\n\t\tELU=9,\r\n\t\tGELU=10,\r\n\t\tSWISH=11,\r\n\t\tMISH=12,\r\n\t\tTANHRE=13\r\n\t};\r\n\t//constructor\r\n\tTransfer():t_(Type::UNKNOWN){}\r\n\tTransfer(Type t):t_(t){}\r\n\t//operators\r\n\toperator Type()const{return t_;}\r\n\t//member functions\r\n\tstatic Transfer read(const char* str);\r\n\tstatic const char* name(const Transfer& tf);\r\n\t//function\r\n\tstatic void tf_lin(VecXd& f, VecXd& d);\r\n\tstatic void tf_sigmoid(VecXd& f, VecXd& d);\r\n\tstatic void tf_tanh(VecXd& f, VecXd& d);\r\n\tstatic void tf_isru(VecXd& f, VecXd& d);\r\n\tstatic void tf_arctan(VecXd& f, VecXd& d);\r\n\tstatic void tf_softsign(VecXd& f, VecXd& d);\r\n\tstatic void tf_relu(VecXd& f, VecXd& d);\r\n\tstatic void tf_softplus(VecXd& f, VecXd& d);\r\n\tstatic void tf_elu(VecXd& f, VecXd& d);\r\n\tstatic void tf_gelu(VecXd& f, VecXd& d);\r\n\tstatic void tf_swish(VecXd& f, VecXd& d);\r\n\tstatic void tf_mish(VecXd& f, VecXd& d);\r\n\tstatic void tf_tanhre(VecXd& f, VecXd& d);\r\nprivate:\r\n\tType t_;\r\n\t//prevent automatic conversion for other built-in types\r\n\t//template<typename T> operator T() const;\r\n};\r\nstd::ostream& operator<<(std::ostream& out, const Transfer& tf);\r\n\r\n//***********************************************************************\r\n// ANN\r\n//***********************************************************************\r\n\r\n/*\r\nDEFINITIONS:\r\n\tensemble - total set of all data (e.g. training \"ensemble\")\r\n\telement - single datum from ensemble\r\n\tc - \"c\" donotes the cost function, e.g. the gradient of the cost function w.r.t. the value of a node is dc/da\r\n\tz - \"z\" is the input to each node, e.g. the gradient of a node w.r.t. to its input is da/dz\r\n\ta - \"a\" is the value of a node, e.g. the gradient of a node w.r.t. to its input is da/dz\r\n\to - \"o\" is the output of the network (i.e. out_), e.g. the gradient of the output w.r.t. the input is do/di\r\n\ti - \"i\" is the input of the network (i.e. in_), e.g. the gradient of the output w.r.t. the input is do/di\r\nPRIVATE:\r\n\tVecXd in_ - raw input data for a single element of the ensemble (e.g. training set)\r\n\tVecXd inw_ - weight used to scale the input data\r\n\tVecXd inb_ - bias used to shift the input data\r\n\tVecXd out_ - raw output data given a single input element\r\n\tVecXd outw_ - weight used to scale the output data\r\n\tVecXd outb_ - bias used to shift the output data\r\n\tint nlayer_ - \r\n\t\ttotal number of hidden layers\r\n\t\tbest thought of as the number of \"connections\" between layers\r\n\t\tnlayer_ must be greater than zero for an initialized network\r\n\t\tthis is true even for a network with zero \"hidden\" layers\r\n\t\tan uninitialized network has nlayer_ = 0\r\n\t\tif we have just the input and output: nlayer_ = 1\r\n\t\t\tone set of weights,biases connecting input/output\r\n\t\tif we have one hidden layer: nlayer_ = 2\r\n\t\t\ttwo sets of weights,biases connecting input/layer0/output\r\n\t\tif we have two hidden layers: nlayer_ = 3\r\n\t\t\tthree sets of weights,biases connecting input/layer0/layer1/output\r\n\t\tet cetera\r\n\tstd::vector<VecXd> node_ - \r\n\t\tall nodes, including the input, output, and hidden layers\r\n\t\tthe raw input and output (in_,out_) are separate from \"node_\"\r\n\t\tthis is because the raw input/output may be shifted/scaled before being used\r\n\t\tthus, while in_/out_ are the \"raw\" input/output,\r\n\t\tthe front/back of \"node_\" can be thought of the \"scaled\" input/output\r\n\t\tnote that scaling is not necessary, but made optional with the use of in_/out_\r\n\t\thas a size of \"nlayer_+1\", as there are \"nlayer_\" connections between \"nlayer_+1\" nodes\r\n\tstd::vector<VecXd> bias_ - \r\n\t\tthe bias of each layer, best thought of as the bias \"between\" layers n,n+1\r\n\t\tbias_[n] must have the size node_[n+1] - we add this bias when going from node_[n] to node_[n+1]\r\n\t\thas a size of \"nlayer_\", as there are \"nlayer_\" connections between \"nlayer_+1\" nodes\r\n\tstd::vector<MatXd> edge_ -\r\n\t\tthe weights of each layer, best though of as transforming from layers n to n+1\r\n\t\tedge_[n] must have the size (node_[n+1],node_[n]) - matrix multiplying (node_[n]) to get (node_[n+1])\r\n\t\thas a size of \"nlayer_\", as there are \"nlayer_\" connections between \"nlayer_+1\" nodes\r\n\tstd::vector<VecXd> dadz_ - \r\n\t\tthe gradient of the value of a node (a) w.r.t. the input of the node (z) - da/dz\r\n\t\tpractically, the gradient of the transfer function of each layer\r\n\t\tbest thought of as the gradient associated with function transferring \"between\" layers n,n+1\r\n\t\tthus, dadz_[n] must have the size node_[n+1]\r\n\t\thas a size of \"nlayer_\", as there are \"nlayer_\" connections between \"nlayer_+1\" nodes\r\n\ttf_ -\r\n\t\tthe type of the transfer function\r\n\t\tnote the transfer function for the last layer is always linear\r\n\ttfp_ - \r\n\t\t(Transfer Function, Function Derivative, Vector)\r\n\t\tthe transfer function for each layer, operates on entire vector at once\r\n\t\tcomputes both function and derivative simultaneously\r\n*/\r\nclass ANN{\r\nprivate:\r\n\t//typedefs\r\n\t\ttypedef void (*TFP)(VecXd&,VecXd&);\r\n\t//layers\r\n\t\tint nlayer_;//number of layers (weights,biases)\r\n\t//transfer functions\r\n\t\tTransfer tf_;//transfer function type\r\n\t\tstd::vector<TFP> tfp_;//transfer function - input for indexed layer (nlayer_)\r\n\t//input/output\r\n\t\tVecXd in_;//input layer\r\n\t\tVecXd out_;//output layer\r\n\t\tVecXd inw_,inb_;//input weight, bias\r\n\t\tVecXd outw_,outb_;//output weight, bias\r\n\t//gradients - nodes\r\n\t\tstd::vector<VecXd> dadz_;//node derivative - not including input layer (nlayer_)\r\n\t//node weights and biases\r\n\t\tstd::vector<VecXd> node_;//nodes (nlayer_+1)\r\n\t\tstd::vector<VecXd> bias_;//bias (nlayer_)\r\n\t\tstd::vector<MatXd> edge_;//edges (nlayer_)\r\npublic:\r\n\t//==== constructors/destructors ====\r\n\tANN(){defaults();}\r\n\t~ANN(){}\r\n\t\r\n\t//==== operators ====\r\n\tfriend std::ostream& operator<<(std::ostream& out, const ANN& n);\r\n\tfriend FILE* operator<<(FILE* out, const ANN& n);\r\n\tfriend VecXd& operator>>(const ANN& nn, VecXd& v);\r\n\tfriend ANN& operator<<(ANN& nn, const VecXd& v);\r\n\t\r\n\t//==== access ====\r\n\t//network dimensions\r\n\t\tint nlayer()const{return nlayer_;}\r\n\t//nodes\r\n\t\tVecXd& in(){return in_;}\r\n\t\tconst VecXd& in()const{return in_;}\r\n\t\tVecXd& out(){return out_;}\r\n\t\tconst VecXd& out()const{return out_;}\r\n\t\tVecXd& node(int n){return node_[n];}\r\n\t\tconst VecXd& node(int n)const{return node_[n];}\r\n\t\tint nNodes(int n)const{return node_[n].size();}\r\n\t//scaling\r\n\t\tVecXd& inw(){return inw_;}\r\n\t\tconst VecXd& inw()const{return inw_;}\r\n\t\tVecXd& inb(){return inb_;}\r\n\t\tconst VecXd& inb()const{return inb_;}\r\n\t\tVecXd& outw(){return outw_;}\r\n\t\tconst VecXd& outw()const{return outw_;}\r\n\t\tVecXd& outb(){return outb_;}\r\n\t\tconst VecXd& outb()const{return outb_;}\r\n\t//bias\r\n\t\tVecXd& bias(int l){return bias_[l];}\r\n\t\tconst VecXd& bias(int l)const{return bias_[l];}\r\n\t//edge\r\n\t\tMatXd& edge(int l){return edge_[l];}\r\n\t\tconst MatXd& edge(int l)const{return edge_[l];}\r\n\t//size\r\n\t\tint nIn()const{return in_.size();}\r\n\t\tint nOut()const{return out_.size();}\r\n\t//gradients - nodes\r\n\t\tVecXd& dadz(int n){return dadz_[n];}\r\n\t\tconst VecXd& dadz(int n)const{return dadz_[n];}\r\n\t//transfer functions\r\n\t\tTransfer& tf(){return tf_;}\r\n\t\tconst Transfer& tf()const{return tf_;}\r\n\t\tTFP tfp(int l){return tfp_[l];}\r\n\t\tconst TFP tfp(int l)const{return tfp_[l];}\r\n\t\t\r\n\t//==== member functions ====\r\n\t//clearing/initialization\r\n\t\tvoid defaults();\r\n\t\tvoid clear();\r\n\t//info\r\n\t\tint size()const;\r\n\t\tint nBias()const;\r\n\t\tint nWeight()const;\r\n\t//resizing\r\n\t\tvoid resize(const ANNInit& init, int nInput, int nOutput);\r\n\t\tvoid resize(const ANNInit& init, int nInput, const std::vector<int>& nNodes, int nOutput);\r\n\t\tvoid resize(const ANNInit& init, const std::vector<int>& nNodes);\r\n\t//error\r\n\t\tdouble error_lambda()const;\r\n\t\tVecXd& grad_lambda(VecXd& grad)const;\r\n\t//execution\r\n\t\tconst VecXd& execute();\r\n\t\tconst VecXd& execute(const VecXd& in){in_=in;return execute();}\r\n\t\t\r\n\t//==== static functions ====\r\n\tstatic void write(FILE* writer, const ANN& nn);\r\n\tstatic void write(const char*, const ANN& nn);\r\n\tstatic void read(FILE* writer, ANN& nn);\r\n\tstatic void read(const char*, ANN& nn);\r\n};\r\n\r\nbool operator==(const ANN& n1, const ANN& n2);\r\ninline bool operator!=(const ANN& n1, const ANN& n2){return !(n1==n2);}\r\n\r\n//***********************************************************************\r\n// ANNInit\r\n//***********************************************************************\r\n\r\nclass ANNInit{\r\nprivate:\r\n\tdouble bInit_;//initial value - bias\r\n\tdouble wInit_;//initial value - weight\r\n\tdouble sigma_;//distribution size parameter\r\n\trng::dist::Name dist_;//distribution type\r\n\tInit init_;//initialization scheme\r\n\tint seed_;//random seed\t\r\npublic:\r\n\t//==== constructors/destructors ====\r\n\tANNInit(){defaults();}\r\n\t~ANNInit(){}\r\n\t\r\n\t//==== operators ====\r\n\tfriend std::ostream& operator<<(std::ostream& out, const ANNInit& init);\r\n\t\r\n\t//==== access ====\r\n\tdouble& bInit(){return bInit_;}\r\n\tconst double& bInit()const{return bInit_;}\r\n\tdouble& wInit(){return wInit_;}\r\n\tconst double& wInit()const{return wInit_;}\r\n\tdouble& sigma(){return sigma_;}\r\n\tconst double& sigma()const{return sigma_;}\r\n\trng::dist::Name& dist(){return dist_;}\r\n\tconst rng::dist::Name& dist()const{return dist_;}\r\n\tInit& init(){return init_;}\r\n\tconst Init& init()const{return init_;}\r\n\tint& seed(){return seed_;}\r\n\tconst int& seed()const{return seed_;}\r\n\t\r\n\t//==== member functions ====\r\n\tvoid defaults();\r\n\tvoid clear(){defaults();}\r\n};\r\n\r\n//***********************************************************************\r\n// Cost\r\n//***********************************************************************\r\n\r\n/*\r\ndcdz_ - \r\n\tthe gradient of the cost function (c) w.r.t. the node inputs (z) - dc/dz\r\n*/\r\nclass Cost{\r\nprivate:\r\n\tstd::vector<VecXd> dcdz_;//derivative of cost function w.r.t. node inputs (nlayer_)\r\n\tVecXd grad_;//gradient of the cost function with respect to each parameter (bias + weight)\r\npublic:\r\n\t//==== constructors/destructors ====\r\n\tCost(){}\r\n\tCost(const ANN& nn){resize(nn);}\r\n\t~Cost(){}\r\n\t\r\n\t//==== access ====\r\n\tstd::vector<VecXd>& dcdz(){return dcdz_;}\r\n\tconst std::vector<VecXd>& dcdz()const{return dcdz_;}\r\n\tVecXd& grad(){return grad_;}\r\n\tconst VecXd& grad()const{return grad_;}\r\n\t\r\n\t//==== member functions ====\r\n\tvoid clear();\r\n\tvoid resize(const ANN& nn);\r\n\tconst VecXd& grad(const ANN& nn, const VecXd& dcdo);\r\n};\r\n\r\n//***********************************************************************\r\n// DOutDVal\r\n//***********************************************************************\r\n\r\n/*\r\ndoda_ -\r\n\tthe derivative of the output (o) w.r.t. the value of all nodes (a)\r\n\thas a size of \"nlayer_+1\" as we need to compute the gradient w.r.t. all nodes\r\n\tthus, doda_[n] must of the size node_[n]\r\n\tthis includes the hidden layers as well as the input/ouput layers\r\n\tnote these are the scaled inputs/outputs\r\ndodi_ -\r\n\tthe derivative of the output w.r.t. the raw input\r\n\tthis is the first element of doda_ multiplied by the input scaling\r\n*/\r\nclass DOutDVal{\r\nprivate:\r\n\tMatXd dodi_;//derivative of out_ w.r.t. to in_ (out_.size() x in_.size())\r\n\tstd::vector<MatXd> doda_;//derivative of out_ w.r.t. to the value \"a\" of all nodes (nlayer_+1)\r\npublic:\r\n\t//==== constructors/destructors ====\r\n\tDOutDVal(){}\r\n\tDOutDVal(const ANN& nn){resize(nn);}\r\n\t~DOutDVal(){}\r\n\t\r\n\t//==== access ====\r\n\tMatXd& dodi(){return dodi_;}\r\n\tconst MatXd& dodi()const{return dodi_;}\r\n\tMatXd& doda(int n){return doda_[n];}\r\n\tconst MatXd& doda(int n)const{return doda_[n];}\r\n\tstd::vector<MatXd>& doda(){return doda_;}\r\n\tconst std::vector<MatXd>& doda()const{return doda_;}\r\n\t\r\n\t//==== member functions ====\r\n\tvoid clear();\r\n\tvoid resize(const ANN& nn);\r\n\tvoid grad(const ANN& nn);\r\n};\r\n\r\n//***********************************************************************\r\n// DOutDP\r\n//***********************************************************************\r\n\r\nclass DOutDP{\r\nprivate:\r\n\tstd::vector<MatXd> dodz_;//derivative of output w.r.t. node inputs (nlayer_)\r\n\tstd::vector<std::vector<VecXd> > dodb_;//derivative of output w.r.t. biases\r\n\tstd::vector<std::vector<MatXd> > dodw_;//derivative of output w.r.t. weights\r\npublic:\r\n\t//==== constructors/destructors ====\r\n\tDOutDP(){}\r\n\tDOutDP(const ANN& nn){resize(nn);}\r\n\t~DOutDP(){}\r\n\t\r\n\t//==== access ====\r\n\tMatXd& dodz(int n){return dodz_[n];}\r\n\tconst MatXd& dodz(int n)const{return dodz_[n];}\r\n\tstd::vector<MatXd>& dodz(){return dodz_;}\r\n\tconst std::vector<MatXd>& dodz()const{return dodz_;}\r\n\tMatXd& dodb(int n){return dodz_[n];}\r\n\tconst MatXd& dodb(int n)const{return dodz_[n];}\r\n\tstd::vector<std::vector<VecXd> >& dodb(){return dodb_;}\r\n\tconst std::vector<std::vector<VecXd> >& dodb()const{return dodb_;}\r\n\tstd::vector<std::vector<MatXd> >& dodw(){return dodw_;}\r\n\tconst std::vector<std::vector<MatXd> >& dodw()const{return dodw_;}\r\n\t\r\n\t//==== member functions ====\r\n\tvoid clear();\r\n\tvoid resize(const ANN& nn);\r\n\tvoid grad(const ANN& nn);\r\n};\r\n\r\n//***********************************************************************\r\n// D2OutDPDVal\r\n//***********************************************************************\r\n\r\nclass D2OutDPDVal{\r\nprivate:\r\n\tANN nnc_;\r\n\tDOutDVal dOutDVal_;\r\n\tstd::vector<MatXd> d2odpda_;\r\n\tMatXd pt1_,pt2_;\r\npublic:\r\n\t//==== constructors/destructors ====\r\n\tD2OutDPDVal(){}\r\n\tD2OutDPDVal(const ANN& nn){resize(nn);}\r\n\t~D2OutDPDVal(){}\r\n\t\r\n\t//==== access ====\r\n\tstd::vector<MatXd>& d2odpda(){return d2odpda_;}\r\n\tconst std::vector<MatXd>& d2odpda()const{return d2odpda_;}\r\n\tMatXd& d2odpda(int i){return d2odpda_[i];}\r\n\tconst MatXd& d2odpda(int i)const{return d2odpda_[i];}\r\n\t\r\n\t//==== member functions ====\r\n\tvoid clear();\r\n\tvoid resize(const ANN& nn);\r\n\tvoid grad(const ANN& nn);\r\n};\r\n\r\n}\r\n\r\n//**********************************************\r\n// serialization\r\n//**********************************************\r\n\r\nnamespace serialize{\r\n\t\r\n\t//**********************************************\r\n\t// byte measures\r\n\t//**********************************************\r\n\t\r\n\ttemplate <> int nbytes(const NN::ANNInit& obj);\r\n\ttemplate <> int nbytes(const NN::ANN& obj);\r\n\t\r\n\t//**********************************************\r\n\t// packing\r\n\t//**********************************************\r\n\t\r\n\ttemplate <> int pack(const NN::ANNInit& obj, char* arr);\r\n\ttemplate <> int pack(const NN::ANN& obj, char* arr);\r\n\t\r\n\t//**********************************************\r\n\t// unpacking\r\n\t//**********************************************\r\n\t\r\n\ttemplate <> int unpack(NN::ANNInit& obj, const char* arr);\r\n\ttemplate <> int unpack(NN::ANN& obj, const char* arr);\r\n\t\r\n}\r\n\r\n#endif", "meta": {"hexsha": "87d67c4efd29381275f82da45a8fe6aaff88c7be", "size": 16192, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ml/nn.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/ml/nn.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/ml/nn.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": 33.1124744376, "max_line_length": 111, "alphanum_fraction": 0.5919589921, "num_tokens": 4291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5923737976859795}}
{"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    /* \u56fa\u5b9a\u7b2c\u4e00\u4e2a\u9876\u70b9\uff0c\u5728gtsam\u4e2d\u76f8\u5f53\u4e8e\u6dfb\u52a0\u4e00\u4e2a\u5148\u9a8c\u56e0\u5b50 */\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    // \u5f00\u59cb\u56e0\u5b50\u56fe\u4f18\u5316\uff0c\u914d\u7f6e\u4f18\u5316\u9009\u9879\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": "/*\r\r\n// Parameters.h defines Parameters of the hardware/Simulator which are not direct part of MSCKF Algorithm\r\r\n*/\r\r\n#ifndef PARAMETERS_H\r\r\n#define PARAMETERS_H\r\r\n\r\r\n#include <Eigen/Core>\r\r\n#include <opencv2/core/core.hpp>\r\r\n\r\r\nstruct noiseParameters\r\r\n{\r\r\n\t// define noise params\t-> noiseParams\r\r\n\r\r\n\tdouble u_var_prime;\r\r\n\tdouble v_var_prime;\r\r\n\t/*\r\r\n\tdouble sigma_gc;\t\t\t\t\t//rot vel var\r\r\n\tdouble sigma_ac;\t\t\t\t\t//lin accel var\r\r\n\tdouble sigma_wgc;\t\t\t\t//gyro bias change var\r\r\n\tdouble sigma_wac;\t\t\t\t//accel bias change var\r\r\n\t*/\r\r\n\tEigen::Vector3d var_gc;\r\r\n\tEigen::Vector3d var_ac;\r\r\n\tEigen::Vector3d var_wgc;\r\r\n\tEigen::Vector3d var_wac;\r\r\n\r\r\n\r\r\n\tEigen::Vector3d aBias;\r\r\n\tEigen::Vector3d gBias;\r\r\n\r\r\n\tEigen::Vector3d aScale;\r\r\n\tEigen::Vector3d gScale;\r\r\n\r\r\n\tnoiseParameters& operator=(const noiseParameters& old){\r\r\n\t\tu_var_prime = old.u_var_prime;\r\r\n\t\tv_var_prime = old.v_var_prime;\r\r\n\t\tvar_ac = old.var_ac;\r\r\n\t\tvar_gc = old.var_gc;\r\r\n\t\tvar_wgc = old.var_wgc;\r\r\n\t\tvar_wac = old.var_wac;\r\r\n\t\treturn *this;\r\r\n\t};\r\r\n};\r\r\n\r\r\nstruct msckfParameters\r\r\n{\r\r\n\t// define msckf params\t-> msckfParams\r\r\n\r\r\n\tint minTrackLength;\t\t\t\t// Set to inf to dead-reckon only\r\r\n\tint maxTrackLength;\t\t\t\t// Set to inf to wait for features to go out of view\r\r\n\tdouble maxGNCostNorm;\t\t\t// Set to inf to allow any triangulation, no matter how bad\r\r\n\tdouble minRCOND;\r\r\n\tbool doNullSpaceTrick;\r\r\n\tbool doQRdecomp;\r\r\n\tdouble fDistanceMin ;\r\r\n    double fDistanceMax ;\r\r\n};\r\r\n\r\r\nstruct cameraParameters\r\r\n{\r\r\n\t// define camera params\t-> camera\r\r\n\r\r\n\tunsigned int width;\r\r\n\tunsigned int height;\r\r\n\r\r\n\tdouble c_u;\t\t\t\t\t\t// Principal point [u pixels] \r\r\n\tdouble c_v;\t\t\t\t\t\t// Principal point [v pixels]\r\r\n\tdouble f_u;\t\t\t\t\t\t// Focal length [u pixels]\r\r\n\tdouble f_v;\t\t\t\t\t\t// Focal length [v pixels]\r\r\n\t\r\r\n\tdouble w;\r\r\n\r\r\n\tdouble Wc0;\r\r\n\tdouble Wc1;\r\r\n\tdouble Wc2;\r\r\n\r\r\n\tdouble Tc0;\r\r\n\tdouble Tc1;\r\r\n\tdouble Tc2;\r\r\n\r\r\n\tEigen::Matrix3d R_C_B;\r\r\n\tEigen::Vector3d Bp_c0;\r\r\n\tcv::Mat  distortCoeff;\r\r\n\r\r\n\tcameraParameters &operator=(const cameraParameters &old){\r\r\n\t\tc_u = old.c_u;\r\r\n\t\tc_v = old.c_v;\r\r\n\t\tf_u = old.f_u;\r\r\n\t\tf_v = old.f_v;\r\r\n\t\tw = old.w;\r\r\n\t\tR_C_B = old.R_C_B;\r\r\n\t\tBp_c0 = old.Bp_c0;\r\r\n\t\tWc0 = old.Wc0;\r\r\n\t\tWc1 = old.Wc1;\r\r\n\t\tWc2 = old.Wc2;\r\r\n\t\tTc0 = old.Tc0;\r\r\n\t\tTc1 = old.Tc1;\r\r\n\t\tTc2 = old.Tc2;\r\r\n\t\treturn *this;\r\r\n\t};\r\r\n\r\r\n};\r\r\n\r\r\nstruct IMUCalibrationParameters\r\r\n{\r\r\n\t// define IMU Calibration params -> \r\r\n\r\r\n\tEigen::Matrix3d Ta;\r\r\n\tEigen::Matrix3d Tg;\r\r\n\tEigen::Matrix3d Ts;\r\r\n};\r\r\n\r\r\n#endif", "meta": {"hexsha": "40ec5ed0042c8b639c20ef52af1c380c2d941e27", "size": 2475, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rovio/Parameters.hpp", "max_stars_repo_name": "YJCITA/rovio_noros", "max_stars_repo_head_hexsha": "89d80c5696afd0dff72650216fcb145d276abcd4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2017-04-26T02:54:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T19:12:52.000Z", "max_issues_repo_path": "include/rovio/Parameters.hpp", "max_issues_repo_name": "YJCITA/rovio_noros", "max_issues_repo_head_hexsha": "89d80c5696afd0dff72650216fcb145d276abcd4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-02-16T17:13:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-24T07:42:25.000Z", "max_forks_repo_path": "include/rovio/Parameters.hpp", "max_forks_repo_name": "YJCITA/rovio_noros", "max_forks_repo_head_hexsha": "89d80c5696afd0dff72650216fcb145d276abcd4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-05-17T13:47:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T06:09:20.000Z", "avg_line_length": 21.9026548673, "max_line_length": 107, "alphanum_fraction": 0.6331313131, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5922430002185495}}
{"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": "/*\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/GaussianMixture.h>\n#include <BayesFilters/AdditiveMeasurementModel.h>\n#include <BayesFilters/sigma_point.h>\n#include <BayesFilters/utils.h>\n\n#include <Eigen/Dense>\n\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace bfl;\n\n\nclass SimulatedMeasurement : public AdditiveMeasurementModel\n{\npublic:\n    SimulatedMeasurement(const Ref<VectorXd>& measurement, const Ref<VectorXd>& predicted_measurement) :\n        measurement_(measurement), predicted_measurement_(predicted_measurement)\n    { }\n\n\n    bool freeze(const Data& data) override\n    {\n        return true;\n    }\n\n\n    std::pair<bool, Data> measure(const Data& data = Data()) const override\n    {\n        MatrixXd measurement(measurement_.size(), 1);\n        measurement.col(0) = measurement_;\n        return std::make_pair(true, measurement);\n    }\n\n\n    std::pair<bool, Data> predictedMeasure(const Ref<const MatrixXd>& cur_states) const override\n    {\n        MatrixXd predicted = MatrixXd::Zero(measurement_.size(), cur_states.cols());\n        predicted.colwise() += predicted_measurement_;\n        return std::make_pair(true, predicted);\n    }\n\n\n    std::pair<bool, Data> innovation(const Data& predicted_measurements, const Data& measurements) const override\n    {\n        MatrixXd innovation = -(any::any_cast<MatrixXd>(predicted_measurements).colwise() - any::any_cast<MatrixXd>(measurements).col(0));\n\n        return std::make_pair(true, std::move(innovation));\n    }\n\n\n    std::pair<bool, MatrixXd> getNoiseCovarianceMatrix() const\n    {\n        VectorXd covariance(measurement_.size());\n        for (std::size_t i = 0; i < measurement_.size(); i++)\n            covariance(i) = 0.1 * (i + 1);\n\n        MatrixXd covariance_matrix = covariance.asDiagonal();\n\n        return std::make_pair(true, covariance_matrix);\n    }\n\n\n    std::pair<std::size_t, std::size_t> getOutputSize() const override\n    {\n        return std::pair<std::size_t, std::size_t>(measurement_.size(), 0);\n    }\n\nprivate:\n    VectorXd measurement_;\n\n    VectorXd predicted_measurement_;\n};\n\n\nint main()\n{\n    std::cout << \"[Test] \" << std::endl;\n    {\n        std::cout << \"Constructing a simulated scenario...\" << std::endl;\n\n        // Unscented Transform parameters\n        double alpha = 1.0;\n        double beta = 2.0;\n        double kappa = 0.0;\n        sigma_point::UTWeight ut_weight(3, alpha, beta, kappa);\n\n        // Predicted state\n        Gaussian predicted_state(3);\n        Matrix3d covariance;\n        covariance << 0.01, 0.0,  0.0,\n                      0.0,  0.01, 0.0,\n                      0.0,  0.0,  0.01;\n        predicted_state.mean() = Vector3d::Zero();\n        predicted_state.covariance() = covariance;\n\n        // Measurement model\n        VectorXd measurement(6);\n        measurement(0) = 1.05;\n        measurement(1) = -0.05;\n        measurement(2) = 0.05;\n        measurement(3) = 0.95;\n        measurement(4) = 1.1;\n        measurement(5) = 0.8;\n\n        VectorXd predicted(6);\n        predicted(0) = 1.0;\n        predicted(1) = 0.0;\n        predicted(2) = 0.0;\n        predicted(3) = 1.0;\n        predicted(4) = 1.0;\n        predicted(5) = 1.0;\n\n        SimulatedMeasurement measurement_model(measurement, predicted);\n\n        // Propagate belief\n        GaussianMixture predicted_measurement(1, 6);\n        MatrixXd cross_covariance;\n        std::tie(std::ignore, predicted_measurement, cross_covariance) = sigma_point::unscented_transform(predicted_state, ut_weight, measurement_model);\n\n        // Extract mean and predicted measurement covariance\n        VectorXd my = predicted_measurement.mean(0);\n        MatrixXd Py = predicted_measurement.covariance(0);\n\n        std::cout << \"done.\" << std::endl;\n\n        // Evaluate likelihood using standard Gaussian\n        VectorXd likelihood_0 = utils::multivariate_gaussian_density(measurement, my, Py);\n\n        std::cout << \"Evaluated likelihood using standard Gaussian evaluation is \" << likelihood_0(0) << std::endl;\n\n        // Evaluate likelihood using Gaussian having covariance in the form S = UV + R with R block diagonal\n\n        // Evaluate the predicted measurement covariance using the form Py = YY^{T} + R with U = Y, V = Y^{T}\n        MatrixXd input_sigma_points = sigma_point::sigma_point(predicted_state, ut_weight.c);\n\n        bfl::Data prediction;\n        std::tie(std::ignore, prediction) = measurement_model.predictedMeasure(input_sigma_points);\n        MatrixXd propagated_sigma_points = bfl::any::any_cast<MatrixXd&&>(std::move(prediction));\n\n        MatrixXd sqrt_ut_weight = ut_weight.covariance.array().sqrt().matrix().asDiagonal();\n        MatrixXd Y = propagated_sigma_points.colwise() - my;\n        Y *= sqrt_ut_weight;\n\n        MatrixXd R_full;\n        std::tie(std::ignore, R_full) = measurement_model.getNoiseCovarianceMatrix();\n\n        // Compose the R matrix with adjacent diagonal blocks, as required by the method\n        // utils::multivariate_gaussian_UVR()\n        MatrixXd R(2, 6);\n        for (std::size_t i = 0; i < R_full.cols() / 2; i++)\n            R.block<2, 2>(0, 2 * i) = R_full.block<2, 2>(2 * i, 2 * i);\n\n        VectorXd likelihood_1 = utils::multivariate_gaussian_density_UVR(measurement, my, Y, Y.transpose(), R);\n        std::cout << \"Evaluated likelihood using Gaussian with UVR factorized covariance matrix is \" << likelihood_1(0) << std::endl;\n\n        if (!(std::abs(likelihood_0(0) - likelihood_1(0)) < 0.00001))\n        {\n            std::cerr << \"Evaluation of likelihood using Gaussian with UVR factorized covariance matrix failed.\"\n                      << \"Should be \" << likelihood_0(0) << \", is \" << likelihood_1(0) << std::endl;\n            return EXIT_FAILURE;\n        }\n    }\n\n    std::cout << \"done.\" << std::endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "fa942f2c601ff63904979233b973f1574c18668d", "size": 6015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_Gaussian_Density_UVR/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_Gaussian_Density_UVR/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_Gaussian_Density_UVR/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": 33.9830508475, "max_line_length": 153, "alphanum_fraction": 0.6415627598, "num_tokens": 1493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5921878076347747}}
{"text": "#include <Eigen/Dense>\n\n#include <openbr/plugins/openbr_internal.h>\n#include <openbr/core/eigenutils.h>\n\nnamespace br\n{\n\n/*!\n * \\ingroup transforms\n * \\brief Designed for use after eye detection + Stasm, this will\n * revert the detected landmarks to the original coordinate space\n * before affine alignment to the stasm mean shape. The storeAffine\n * parameter must be set to true when calling AffineTransform before this.\n * \\author Brendan Klare \\cite bklare\n */\nclass RevertAffineTransform : public UntrainableTransform\n{\n    Q_OBJECT\n\nprivate:\n\n    void project(const Template &src, Template &dst) const\n    {\n        QList<float> paramList = src.file.getList<float>(\"affineParameters\");\n        Eigen::MatrixXf points = EigenUtils::pointsToMatrix(src.file.points(), true);\n        Eigen::MatrixXf affine = Eigen::MatrixXf::Zero(3, 3);\n        for (int i = 0, cnt = 0; i < 2; i++)\n            for (int j = 0; j < 3; j++, cnt++)\n                affine(i, j) = paramList[cnt];\n        affine(2, 2) = 1;\n        affine = affine.inverse();\n        Eigen::MatrixXf affineInv = affine.block(0, 0, 2, 3);\n        Eigen::MatrixXf pointsT = points.transpose();\n        points =  affineInv * pointsT;\n        dst = src;\n        dst.file.clearPoints();\n        dst.file.setPoints(EigenUtils::matrixToPoints(points.transpose()));\n    }\n};\n\nBR_REGISTER(Transform, RevertAffineTransform)\n\n} // namespace br\n\n#include \"imgproc/revertaffine.moc\"\n", "meta": {"hexsha": "868fa3b1b72f72f8648ea8dd5be2becd28daea54", "size": 1434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbr/plugins/imgproc/revertaffine.cpp", "max_stars_repo_name": "kassemitani/openbr", "max_stars_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1883.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:33:37.000Z", "max_issues_repo_path": "openbr/plugins/imgproc/revertaffine.cpp", "max_issues_repo_name": "kassemitani/openbr", "max_issues_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 272.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T09:53:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T08:04:33.000Z", "max_forks_repo_path": "openbr/plugins/imgproc/revertaffine.cpp", "max_forks_repo_name": "kassemitani/openbr", "max_forks_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 718.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T18:51:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T08:10:53.000Z", "avg_line_length": 30.5106382979, "max_line_length": 85, "alphanum_fraction": 0.660390516, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5921878060594198}}
{"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/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n\n**/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_HPP_INCLUDED\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-functions\n    @defgroup group-arithmetic Arithmetic functions\n\n    Those functions provides scalar and SIMD algorithms for classical arithmetic operators and\n    functions provided by the C and C++ standard library. Other functions like, in particular,\n    provision for saturated operations are also provided.\n\n  **/\n\n  /*!\n    @ingroup group-callable\n    @defgroup group-callable-arithmetic Arithmetic Callable Objects\n    Callable objects version of @ref group-arithmetic\n\n    Their specific semantic limitations are similar to those of their function\n    equivalents as described in the @ref group-arithmetic section.\n  **/\n} }\n\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/abss.hpp>\n#include <boost/simd/function/adds.hpp>\n#include <boost/simd/function/angle.hpp>\n#include <boost/simd/function/arg.hpp>\n#include <boost/simd/function/average.hpp>\n#include <boost/simd/function/ceil.hpp>\n#include <boost/simd/function/conj.hpp>\n#include <boost/simd/function/correct_fma.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/decs.hpp>\n#include <boost/simd/function/dist.hpp>\n#include <boost/simd/function/dists.hpp>\n#include <boost/simd/function/div.hpp>\n#include <boost/simd/function/divs.hpp>\n#include <boost/simd/function/drem.hpp>\n#include <boost/simd/function/extract.hpp>\n#include <boost/simd/function/fabs.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/fmod.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/idiv.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/incs.hpp>\n#include <boost/simd/function/iround2even.hpp>\n#include <boost/simd/function/iround.hpp>\n#include <boost/simd/function/itrunc.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/minusone.hpp>\n#include <boost/simd/function/mod.hpp>\n#include <boost/simd/function/modulo.hpp>\n#include <boost/simd/function/modulus.hpp>\n#include <boost/simd/function/muls.hpp>\n#include <boost/simd/function/neg.hpp>\n#include <boost/simd/function/negs.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/function/oneplus.hpp>\n#include <boost/simd/function/rdivide.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/remainder.hpp>\n#include <boost/simd/function/remfix.hpp>\n#include <boost/simd/function/rem.hpp>\n#include <boost/simd/function/remquo.hpp>\n#include <boost/simd/function/remround.hpp>\n#include <boost/simd/function/rint.hpp>\n#include <boost/simd/function/round2even.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/sqrs.hpp>\n#include <boost/simd/function/sqrt1pm1.hpp>\n#include <boost/simd/function/sqrt.hpp>\n#include <boost/simd/function/subs.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/toints.hpp>\n#include <boost/simd/function/touint.hpp>\n#include <boost/simd/function/touints.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": "ecc35ce3bc097abb07782756d60ea326f5785a20", "size": 4414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arithmetic.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/arithmetic.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/arithmetic.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.406779661, "max_line_length": 100, "alphanum_fraction": 0.7415043045, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303236047049, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.5921761569917321}}
{"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": "#pragma once\n\n////////////////////////////////////////////////////////////////////////////////\n#include <polysolve/LinearSolver.hpp>\n\n#include <nlohmann/json.hpp>\nusing json = nlohmann::json;\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <memory>\n////////////////////////////////////////////////////////////////////////////////\n\nnamespace polysolve\n{\n\n    ///\n    /// @brief         { Solve a linear system Ax = b with Dirichlet boundary\n    ///                conditions. For each Dirichlet node i, we want to ensure that\n    ///                x[i] = b[i]. The implementation follows\n    ///                http://www.math.colostate.edu/~bangerth/videos.676.21.65.html\n    ///\n    ///                For memory efficiency, this function updates in place the\n    ///                matrix of the linear system. We also return the modified rhs\n    ///                to the user }\n    ///\n    /// @param[in]     solver           { Linear solver class to use for solving the\n    ///                                 system }\n    /// @param[in,out] A                { Matrix of the linear system without\n    ///                                 boundary conditions. Output: modified\n    ///                                 matrix. }\n    /// @param[in,out] b                { Right-hand side of the linear system.\n    ///                                 Output: modified rhs for the equivalent\n    ///                                 system. }\n    /// @param[in]     dirichlet_nodes  { List of ids of Dirichlet nodes }\n    /// @param[in,out] x                { Unknown vector }\n    ///\n    Eigen::Vector4d dirichlet_solve(LinearSolver &solver, StiffnessMatrix &A,\n                                    Eigen::VectorXd &b, const std::vector<int> &dirichlet_nodes, Eigen::VectorXd &x,\n                                    const int precond_num,\n                                    const std::string &save_path = \"\", bool compute_spectrum = false,\n                                    const bool remove_zero_cols = false,\n                                    const bool skip_last_cols = false);\n\n    void prefactorize(LinearSolver &solver, StiffnessMatrix &A,\n                                 const std::vector<int> &dirichlet_nodes, const int precond_num,\n                                 const std::string &save_path = \"\");\n\n    void dirichlet_solve_prefactorized(LinearSolver &solver, const StiffnessMatrix &A, Eigen::VectorXd &f,\n                                                  const std::vector<int> &dirichlet_nodes, Eigen::VectorXd &u);\n\n} // namespace polysolve\n", "meta": {"hexsha": "8e5d93650f0ec73293b1197b592c122c5dd82ebf", "size": 2570, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/FEMSolver.hpp", "max_stars_repo_name": "Huangzizhou/polysolve", "max_stars_repo_head_hexsha": "f6a48102ace2fb2e943e2c3694b096ac04996a1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T12:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:32:10.000Z", "max_issues_repo_path": "src/FEMSolver.hpp", "max_issues_repo_name": "Huangzizhou/polysolve", "max_issues_repo_head_hexsha": "f6a48102ace2fb2e943e2c3694b096ac04996a1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-05-30T19:29:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T19:13:13.000Z", "max_forks_repo_path": "src/FEMSolver.hpp", "max_forks_repo_name": "Huangzizhou/polysolve", "max_forks_repo_head_hexsha": "f6a48102ace2fb2e943e2c3694b096ac04996a1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-07-07T14:13:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T19:03:01.000Z", "avg_line_length": 48.4905660377, "max_line_length": 116, "alphanum_fraction": 0.479766537, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.5920661153561279}}
{"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": "#include <boost/test/unit_test.hpp>\n\n#include \"combinatoire.h\"\n\nBOOST_AUTO_TEST_SUITE(test_combinatoire)\n\n    BOOST_AUTO_TEST_CASE(coefficient_binomial) {\n        BOOST_CHECK_EQUAL(35, combinatoire::coefficient_binomial(7, 3));\n        BOOST_CHECK_EQUAL(70, combinatoire::coefficient_binomial(8, 4));\n        BOOST_CHECK_EQUAL(1, combinatoire::coefficient_binomial(40, 0));\n    }\n\n    BOOST_AUTO_TEST_CASE(catalan) {\n        BOOST_CHECK_EQUAL(1, combinatoire::catalan(0));\n        BOOST_CHECK_EQUAL(1, combinatoire::catalan(1));\n        BOOST_CHECK_EQUAL(16796, combinatoire::catalan<unsigned long long>(10));\n    }\n\n    BOOST_AUTO_TEST_CASE(factorielle) {\n        BOOST_CHECK_EQUAL(120, combinatoire::factorielle(5));\n        BOOST_CHECK_EQUAL(720, combinatoire::factorielle(6));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4ea5e537ab34ad79e1b8d40afa5f34d5740a8362", "size": 816, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/combinatoire.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "tests/combinatoire.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/combinatoire.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.64, "max_line_length": 80, "alphanum_fraction": 0.7242647059, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5919668325867918}}
{"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/LinearModel.h>\n\n#include <cmath>\n#include <iostream>\n#include <utility>\n\n#include <Eigen/Cholesky>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nLinearModel::LinearModel\n(\n    const LinearMatrixComponent& linear_matrix_component,\n    const Ref<const MatrixXd>& noise_covariance_matrix,\n    const unsigned int seed\n) :\n    LTIMeasurementModel(MatrixXd::Zero(linear_matrix_component.second.size(), linear_matrix_component.first), noise_covariance_matrix),\n    generator_(std::mt19937_64(seed)),\n    distribution_(std::normal_distribution<double>(0.0, 1.0)),\n    gauss_rnd_sample_([&] { return (distribution_)(generator_); })\n{\n    for (std::size_t i = 0; i < linear_matrix_component.second.size(); ++i)\n    {\n        const std::size_t& component_index = linear_matrix_component.second[i];\n\n        if (component_index < linear_matrix_component.first)\n            H_(i, component_index) = 1.0;\n        else\n            throw std::runtime_error(std::string(\"ERROR::LINEARMODEL::CTOR\\nERROR:\\n\\tIndex component out of bound.\\nLOG:\\n\\tProvided: \") + std::to_string(component_index) + \". Index bound: \" + std::to_string(linear_matrix_component.first) + \".\");\n    }\n\n    LDLT<MatrixXd> chol_ldlt(R_);\n    sqrt_R_ = (chol_ldlt.transpositionsP() * MatrixXd::Identity(R_.rows(), R_.cols())).transpose() * chol_ldlt.matrixL() * chol_ldlt.vectorD().real().cwiseSqrt().asDiagonal();\n}\n\n\nLinearModel::LinearModel(const LinearMatrixComponent& linear_matrix_component, const Ref<const MatrixXd>& noise_covariance_matrix) :\n    LinearModel(linear_matrix_component, noise_covariance_matrix, 1)\n{ }\n\n\nstd::pair<bool, MatrixXd> LinearModel::getNoiseSample(const int num) const\n{\n    MatrixXd rand_vectors(2, num);\n    for (int i = 0; i < rand_vectors.size(); i++)\n        *(rand_vectors.data() + i) = gauss_rnd_sample_();\n\n    MatrixXd noise_sample = sqrt_R_ * rand_vectors;\n\n    return std::make_pair(true, std::move(noise_sample));\n}\n\n\nstd::pair<bool, MatrixXd> LinearModel::getNoiseCovarianceMatrix() const\n{\n    return std::make_pair(true, R_);\n}\n\n\nEigen::MatrixXd LinearModel::getMeasurementMatrix() const\n{\n    return H_;\n}\n", "meta": {"hexsha": "a0124db1ad80f51937b57733296b003692c83707", "size": 2353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesFilters/src/LinearModel.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/LinearModel.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/LinearModel.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.2328767123, "max_line_length": 247, "alphanum_fraction": 0.7186570336, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5919668266288474}}
{"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": "#include <vector>\n#include <Eigen/Dense>\n\n# pragma once\n\nusing std::vector; using std::string;\n\ntypedef Eigen::MatrixXd matrix;\n\nint atom(int ao_index, int orbitals_per_atom);\n\nint orb_index(int ao_index, int orbitals_per_atom);\n\nmatrix calculate_fock_matrix(matrix hamiltonian_matrix, matrix interaction_matrix, matrix density_matrix, int orbitals_per_atom, double dipole);\n", "meta": {"hexsha": "26b3dddaab9f422587944335e4402b3ba64ef4f6", "size": 375, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "shared_lib/fock_matrix.hpp", "max_stars_repo_name": "Abdul-Zamani/qm_2019_sss_1", "max_stars_repo_head_hexsha": "fd665cccd90d8cf68cb97c8738cd32fb7981fe54", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_lib/fock_matrix.hpp", "max_issues_repo_name": "Abdul-Zamani/qm_2019_sss_1", "max_issues_repo_head_hexsha": "fd665cccd90d8cf68cb97c8738cd32fb7981fe54", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-24T01:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-24T01:45:23.000Z", "max_forks_repo_path": "shared_lib/fock_matrix.hpp", "max_forks_repo_name": "MolSSI-Education/qm_2019_sss_1", "max_forks_repo_head_hexsha": "c1b3c1d66dd32e47edc5214bc32c5e996a03db26", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-07-23T20:16:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-31T17:47:46.000Z", "avg_line_length": 25.0, "max_line_length": 144, "alphanum_fraction": 0.8053333333, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430394931457, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5919668224332005}}
{"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": "#include <cmath>\n\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n\n#include <BingoCpp/explicit_regression.h>\n\n#include \"test_fixtures.h\"\n\nusing namespace bingo;\n\nnamespace {\n\nclass TestExplicitRegression : public testing::Test {\n public:\n  ExplicitTrainingData* training_data_;\n  testutils::SumEquation sum_equation_;\n\n  void SetUp() {\n    training_data_ = init_sample_training_data();\n    sum_equation_ = testutils::init_sum_equation();\n  }\n\n  void TearDown() {\n    delete training_data_;\n  }\n\n private:\n  ExplicitTrainingData* init_sample_training_data() {\n    const int num_points = 50;\n    const int num_data_per_feature = 10;\n    const int num_feature = 50 / num_data_per_feature;\n    Eigen::ArrayXXd x = Eigen::ArrayXd::LinSpaced(num_points, 0, 0.98);\n    x = x.reshaped(num_feature, num_data_per_feature);\n    x.transposeInPlace();\n    Eigen::Array<double, 10, 1> y = Eigen::ArrayXd::LinSpaced(10, 0.2, 4.7);\n    return new ExplicitTrainingData(x, y);\n  }\n};\n\nTEST_F(TestExplicitRegression, EvaluateIndividualFitness) {\n  ExplicitRegression regressor(training_data_);\n  double fitness = regressor.EvaluateIndividualFitness(sum_equation_);\n  ASSERT_TRUE(fitness < 1e-10);\n}\n\nTEST_F(TestExplicitRegression, EvaluateIndividualFitnessWithNaN) {\n  training_data_->x(0, 0) = std::numeric_limits<double>::quiet_NaN();\n  ExplicitRegression regressor(training_data_);\n  double fitness = regressor.EvaluateIndividualFitness(sum_equation_);\n  ASSERT_TRUE(std::isnan(fitness));\n}\n\nTEST_F(TestExplicitRegression, GetSubsetOfTrainingData) {\n  Eigen::ArrayXXd data_input = Eigen::ArrayXd::LinSpaced(5, 0, 4);\n  ExplicitTrainingData* training_data = new ExplicitTrainingData(data_input, data_input);\n  ExplicitTrainingData* subset_training_data = training_data->GetItem(std::vector<int>{0, 2, 3});\n\n  Eigen::ArrayXXd expected_subset(3, 1);\n  expected_subset << 0, 2, 3;\n  ASSERT_TRUE(subset_training_data->x.isApprox(expected_subset));\n  ASSERT_TRUE(subset_training_data->y.isApprox(expected_subset));\n  delete training_data,\n  delete subset_training_data;\n}\n\nTEST_F(TestExplicitRegression, CorrectTrainingDataSize) {\n  for (int size : std::vector<int> {2, 5, 50}) {\n    Eigen::ArrayXXd data_input = Eigen::ArrayXd::LinSpaced(size, 0, 10);\n    ExplicitTrainingData* training_data = new ExplicitTrainingData(data_input, data_input);\n    ASSERT_EQ(training_data->Size(), size);\n    delete training_data;\n  }\n}\n} // namespace ", "meta": {"hexsha": "fd8cd545d6bb4d94d265e27bf1785e3f252298b6", "size": 2414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/explicit_regression_tests.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": "tests/explicit_regression_tests.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": "tests/explicit_regression_tests.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": 32.1866666667, "max_line_length": 97, "alphanum_fraction": 0.7543496272, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159727, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5918780359554568}}
{"text": "//test_duration_mc_var.cpp\n\n//test Treasury portfolio VaR through MC simulation\n\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <vector>\n\n#include<memory>\n\n#include <Eigen/Dense>\nusing namespace Eigen;\nusing namespace std;\n\n#include \"compute_returns_eigen.h\"\n#include \"compute_var.h\"\n#include \"path.h\"\n#include \"ptf_var.h\"\n#include \"rng.h\"\n#include \"portfolio.h\"\n\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 US Treasury Zero-Coupon Yield Curve\n    // daily series obtained from US Federal Reserve Data Releases\n\t//https://www.quandl.com\n\n\tstd::fstream file(\"/home/mrnoname/Documents/VaR/data/TermStructureData.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] = 1. - std::stod(tmp)/100.;              \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    //-------------------------------------------------------------------------\n    // Compute Monte Carlo VaR\n\n\t// Simulate yield chge through brute force Monte-Carlo\n\n\tPath1x1 process;\n\n\tstd::vector<Path1x1> processes(7);\n\n\tfor(size_t i = 0;i < 7;++i) processes[i] = Path1x1();\n\n\tHistoricalVaR var1;\n\n    // Portfolio with 7 durations across the yield curve\n\n\tdouble a = double(1./7.);\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\t_ptf.push_back(std::make_pair(0,shared_ptr<Instrument> (new FI(.960/100.)))); //1 yr\n\t_ptf.push_back(std::make_pair(1,shared_ptr<Instrument> (new FI(1.918/100.)))); //2 yrs\n\t_ptf.push_back(std::make_pair(2,shared_ptr<Instrument> (new FI(2.913/100.)))); //3 yrs\n\t_ptf.push_back(std::make_pair(4,shared_ptr<Instrument> (new FI(4.704/100.)))); //5 yrs\n\t_ptf.push_back(std::make_pair(6,shared_ptr<Instrument> (new FI(6.406/100.)))); // 7 yrs\n\t_ptf.push_back(std::make_pair(9,shared_ptr<Instrument> (new FI(8.874/100.)))); // 10  yrs\n\t_ptf.push_back(std::make_pair(29,shared_ptr<Instrument> (new FI(19.592/100.)))); // 30 yrs\n\n    /*\n    http://online.wsj.com/mdc/public/page/2_3022-bondmkt.html\n\n    The Bond Market: Ryan Indexes\n    Tuesday, December 20, 2016\n\n    1 yr Treasury .960\n    2 yr Treasury 1.918\n    3 yr Treasury 2.913\n    5 yr Treasury 4.704\n    7 yr Treasury 6.406\n    10 yr Treasury 8.874\n    30 yr Treasury 19.592\n    */\n\n\tshared_ptr<Portfolio> ptf(new Portfolio(_ptf, weights, cr, true, 1.e+07));\n\n\trng _rng;\n\n    //ptf value at risk\n\n\tVaRPtfMCCompute<HistoricalVaR, Path1x1> VaRMonteCarlo(ptf,var1, processes, _rng);\n\n\tcout << \"Monte Carlo VaR: \" << VaRMonteCarlo.computeVaR() << endl;\n\n\t//simulate portfolio rtn instead instead of component\n\n\tVaRMonteCarloCompute<Portfolio, HistoricalVaR, Path1x1> VaRMonteCarlo1(ptf,var1, process, _rng);\n\n\tcout << \"Monte Carlo VaR - ptf rtn: \" << VaRMonteCarlo1.computeVaR() << endl;\n\n\n    return 0;\n\n    } catch (const std::exception& e) { // caught by reference to base\n        std::cout << \" a standard exception was caught, with message '\"\n                  << e.what() << \"'\\n\";\n    }\n\n}\n\n", "meta": {"hexsha": "22be4b3013917eb1b636601160ab274b2809c064", "size": 5089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cpptests/test_duration_mc_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_duration_mc_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_duration_mc_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": 26.7842105263, "max_line_length": 103, "alphanum_fraction": 0.622519159, "num_tokens": 1541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.591832699588635}}
{"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": "#include \"LineSegment.h\"\n\n#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>\n\n__BEGIN_LIBRARIES_DISABLE_WARNINGS\n#include <boost/integer/common_factor.hpp>\n__END_LIBRARIES_DISABLE_WARNINGS\n\nnamespace AdventOfCode\n{\nnamespace Year2021\n{\nnamespace Day05\n{\n\nLineSegment::LineSegment(Vector2D start, Vector2D end)\n    : m_start{std::move(start)}\n    , m_end{std::move(end)}\n{\n\n}\n\nbool LineSegment::isAxisParallel() const\n{\n    return m_start.x() == m_end.x() || m_start.y() == m_end.y();\n}\n\nstd::vector<Vector2D> LineSegment::getCoveredPoints() const\n{\n    const Vector2D differenceVector = m_end - m_start;\n    const Vector2D differenceVectorAbs = differenceVector.cwiseAbs();\n\n    const int numStepsFromStartToEnd = boost::integer::gcd(differenceVectorAbs[0], differenceVectorAbs[1]);\n\n    const Vector2D stepVector = differenceVector / numStepsFromStartToEnd;\n\n    std::vector<Vector2D> coveredPoints;\n    for (Vector2D innerPointVector = m_start; ; innerPointVector += stepVector)\n    {\n        coveredPoints.push_back(innerPointVector);\n\n        if (innerPointVector == m_end)\n        {\n            break;\n        }\n    }\n\n    return coveredPoints;\n}\n\n}\n}\n}\n", "meta": {"hexsha": "30c35673309a1daea5a11faeb0a4469c192bc58c", "size": 1169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AdventOfCode2021/Day05-HydrothermalVenture/LineSegment.cpp", "max_stars_repo_name": "dbartok/advent-of-code-cpp", "max_stars_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AdventOfCode2021/Day05-HydrothermalVenture/LineSegment.cpp", "max_issues_repo_name": "dbartok/advent-of-code-cpp", "max_issues_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AdventOfCode2021/Day05-HydrothermalVenture/LineSegment.cpp", "max_forks_repo_name": "dbartok/advent-of-code-cpp", "max_forks_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6481481481, "max_line_length": 107, "alphanum_fraction": 0.7194183062, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5918158261482831}}
{"text": "// big_posit.cpp: Functionality tests for big posits\n//\n// Copyright (C) 2017-2019 Stillwater Supercomputing, Inc.\n//\n// This file is part of the universal numbers project, which is released under an MIT Open Source license.\n\n#include \"common.hpp\"\n\n#include <boost/multiprecision/cpp_bin_float.hpp>\n// enable posit arithmetic exceptions\n#define POSIT_THROW_ARITHMETIC_EXCEPTION 1\n// to capture all the possible bits, use \n#define POSIT_ROUNDING_ERROR_FREE_IO_FORMAT 1\n#include <posit>\n#include \"../test_helpers.hpp\"\n#include \"../posit_test_helpers.hpp\"\n\n/*\nexperiments with big posits\n*/\n\n// Sample the conversion space around 1 when number of fraction bits\n// of a big posit is bigger than the number of bits in the input representation\ntemplate<typename Ty>\nvoid Sample(Ty value) {\n\tusing namespace std;\n\tusing namespace sw::unum;\n\n\tcout << typeid(value).name() << endl;\n\tcout << posit<54, 3>(value) << \" \" << double(posit<54, 3>(value)) << endl;\n\tcout << posit<56, 3>(value) << \" \" << double(posit<56, 3>(value)) << endl;\n\tcout << posit<58, 3>(value) << \" \" << double(posit<58, 3>(value)) << endl;\n\tcout << posit<60, 3>(value) << \" \" << double(posit<60, 3>(value)) << endl;\n\tcout << posit<62, 3>(value) << \" \" << double(posit<62, 3>(value)) << endl;\n\tcout << posit<64, 3>(value) << \" \" << double(posit<64, 3>(value)) << endl;\n\tcout << posit<66, 3>(value) << \" \" << double(posit<66, 3>(value)) << endl;\n\tcout << posit<67, 3>(value) << \" \" << double(posit<67, 3>(value)) << endl;\n\tcout << posit<68, 3>(value) << \" \" << double(posit<68, 3>(value)) << endl;\n\tcout << posit<69, 3>(value) << \" \" << double(posit<69, 3>(value)) << endl;\n\tcout << posit<70, 3>(value) << \" \" << double(posit<70, 3>(value)) << endl;\n\tcout << posit<71, 3>(value) << \" \" << double(posit<71, 3>(value)) << endl;\n\tcout << posit<72, 3>(value) << \" \" << double(posit<72, 3>(value)) << endl;\n\tcout << posit<80, 3>(value) << \" \" << double(posit<80, 3>(value)) << endl;\n}\n\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace sw::unum;\n\n\tconst size_t RND_TEST_CASES = 1000;\n\n\tconst size_t nbits = 128;\n\tconst size_t es = 4;\n\n\tint nrOfFailedTestCases = 0;\n\tbool bReportIndividualTestCases = false;\n\tstd::string tag = \" big posit conversion experiments\";\n\n\tposit<80, 3> p;\n\tp = 1ull;\n\tp = 2ull;\n\n\tSample(1);\n\tSample(2);\n\tSample(1ull);\n\tSample(2ull);\n\tSample(1.0f);\n\n\treturn (nrOfFailedTestCases > 0 ? 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": "f07f4fa751b7c52d5fd9bdfd9353e15e7e7e3455", "size": 3273, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/posit/big_posits.cpp", "max_stars_repo_name": "shikharvashistha/hpr-blas", "max_stars_repo_head_hexsha": "73f109d45701fc3816af0a1ecd42f11d494a6f97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-02-13T10:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T20:30:58.000Z", "max_issues_repo_path": "tests/posit/big_posits.cpp", "max_issues_repo_name": "jamesquinlan/hpr-blas", "max_issues_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-20T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T11:19:32.000Z", "max_forks_repo_path": "tests/posit/big_posits.cpp", "max_forks_repo_name": "jamesquinlan/hpr-blas", "max_forks_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T21:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T05:35:35.000Z", "avg_line_length": 34.4526315789, "max_line_length": 125, "alphanum_fraction": 0.6578062939, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5917672786036895}}
{"text": "// (C) Copyright Andrew Sutton 2007\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0 (See accompanying file\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\n\n//[code_clustering_coefficient\n#include <iostream>\n#include <iomanip>\n\n#include <boost/graph/undirected_graph.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/graph/clustering_coefficient.hpp>\n#include \"helper.hpp\"\n\nusing namespace std;\nusing namespace boost;\n\n// The Actor type stores the name of each vertex in the graph.\nstruct Actor\n{\n    string name;\n};\n\n// Declare the graph type and its vertex and edge types.\ntypedef undirected_graph< Actor > Graph;\ntypedef graph_traits< Graph >::vertex_descriptor Vertex;\ntypedef graph_traits< Graph >::edge_descriptor Edge;\n\n// The name map provides an abstract accessor for the names of\n// each vertex. This is used during graph creation.\ntypedef property_map< Graph, string Actor::* >::type NameMap;\n\n// The clustering property, container, and map define the containment\n// and abstract accessor for the clustering coefficients of vertices.\ntypedef exterior_vertex_property< Graph, float > ClusteringProperty;\ntypedef ClusteringProperty::container_type ClusteringContainer;\ntypedef ClusteringProperty::map_type ClusteringMap;\n\nint main(int argc, char* argv[])\n{\n    // Create the graph and a name map that provides access to\n    // then actor names.\n    Graph g;\n    NameMap nm(get(&Actor::name, g));\n\n    // Read the graph from standard input.\n    read_graph(g, nm, cin);\n\n    // Compute the clustering coefficients of each vertex in the graph\n    // and the mean clustering coefficient which is returned from the\n    // computation.\n    ClusteringContainer coefs(num_vertices(g));\n    ClusteringMap cm(coefs, g);\n    float cc = all_clustering_coefficients(g, cm);\n\n    // Print the clustering coefficient of each vertex.\n    graph_traits< Graph >::vertex_iterator i, end;\n    for (boost::tie(i, end) = vertices(g); i != end; ++i)\n    {\n        cout << setw(12) << setiosflags(ios::left) << g[*i].name << get(cm, *i)\n             << endl;\n    }\n    cout << \"mean clustering coefficient: \" << cc << endl;\n\n    return 0;\n}\n//]\n", "meta": {"hexsha": "cb2ef39bff03f1f07f2f37e81421914388ff0711", "size": 2208, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/clustering_coefficient.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/clustering_coefficient.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/graph/example/clustering_coefficient.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": 32.0, "max_line_length": 79, "alphanum_fraction": 0.7201086957, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5917672640085234}}
{"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": "#include <igl/opengl/gl.h>\r\n#include <igl/arap.h>\r\n#include <igl/biharmonic_coordinates.h>\r\n#include <igl/cat.h>\r\n#include <igl/cotmatrix.h>\r\n#include <igl/massmatrix.h>\r\n#include <igl/matrix_to_list.h>\r\n#include <igl/parula.h>\r\n#include <igl/point_mesh_squared_distance.h>\r\n#include <igl/readDMAT.h>\r\n#include <igl/readMESH.h>\r\n#include <igl/remove_unreferenced.h>\r\n#include <igl/slice.h>\r\n#include <igl/writeDMAT.h>\r\n#include <igl/opengl/glfw/Viewer.h>\r\n#include <Eigen/Sparse>\r\n#include <iostream>\r\n#include <queue>\r\n\r\n#include \"tutorial_shared_path.h\"\r\n\r\nstruct Mesh\r\n{\r\n  Eigen::MatrixXd V,U;\r\n  Eigen::MatrixXi T,F;\r\n} low,high,scene;\r\n\r\nEigen::MatrixXd W;\r\nigl::ARAPData arap_data;\r\n\r\nint main(int argc, char * argv[])\r\n{\r\n  using namespace Eigen;\r\n  using namespace std;\r\n  using namespace igl;\r\n  if(!readMESH(TUTORIAL_SHARED_PATH \"/octopus-low.mesh\",low.V,low.T,low.F))\r\n  {\r\n    cout<<\"failed to load mesh\"<<endl;\r\n  }\r\n  if(!readMESH(TUTORIAL_SHARED_PATH \"/octopus-high.mesh\",high.V,high.T,high.F))\r\n  {\r\n    cout<<\"failed to load mesh\"<<endl;\r\n  }\r\n\r\n  // Precomputation\r\n  {\r\n    Eigen::VectorXi b;\r\n    {\r\n      Eigen::VectorXi J = Eigen::VectorXi::LinSpaced(high.V.rows(),0,high.V.rows()-1);\r\n      Eigen::VectorXd sqrD;\r\n      Eigen::MatrixXd _2;\r\n      cout<<\"Finding closest points...\"<<endl;\r\n      igl::point_mesh_squared_distance(low.V,high.V,J,sqrD,b,_2);\r\n      assert(sqrD.minCoeff() < 1e-7 && \"low.V should exist in high.V\");\r\n    }\r\n    // force perfect positioning, rather have popping in low-res than high-res.\r\n    // The correct/elaborate thing to do is express original low.V in terms of\r\n    // linear interpolation (or extrapolation) via elements in (high.V,high.F)\r\n    igl::slice(high.V,b,1,low.V);\r\n    // list of points --> list of singleton lists\r\n    std::vector<std::vector<int> > S;\r\n    igl::matrix_to_list(b,S);\r\n    cout<<\"Computing weights for \"<<b.size()<<\r\n      \" handles at \"<<high.V.rows()<<\" vertices...\"<<endl;\r\n    // Technically k should equal 3 for smooth interpolation in 3d, but 2 is\r\n    // faster and looks OK\r\n    const int k = 2;\r\n    igl::biharmonic_coordinates(high.V,high.T,S,k,W);\r\n    cout<<\"Reindexing...\"<<endl;\r\n    // Throw away interior tet-vertices, keep weights and indices of boundary\r\n    VectorXi I,J;\r\n    igl::remove_unreferenced(high.V.rows(),high.F,I,J);\r\n    for_each(high.F.data(),high.F.data()+high.F.size(),[&I](int & a){a=I(a);});\r\n    for_each(b.data(),b.data()+b.size(),[&I](int & a){a=I(a);});\r\n    igl::slice(MatrixXd(high.V),J,1,high.V);\r\n    igl::slice(MatrixXd(W),J,1,W);\r\n  }\r\n\r\n  // Resize low res (high res will also be resized by affine precision of W)\r\n  low.V.rowwise() -= low.V.colwise().mean();\r\n  low.V /= (low.V.maxCoeff()-low.V.minCoeff());\r\n  low.V.rowwise() += RowVector3d(0,1,0);\r\n  low.U = low.V;\r\n  high.U = high.V;\r\n\r\n  arap_data.with_dynamics = true;\r\n  arap_data.max_iter = 10;\r\n  arap_data.energy = ARAP_ENERGY_TYPE_DEFAULT;\r\n  arap_data.h = 0.01;\r\n  arap_data.ym = 0.001;\r\n  if(!arap_precomputation(low.V,low.T,3,VectorXi(),arap_data))\r\n  {\r\n    cerr<<\"arap_precomputation failed.\"<<endl;\r\n    return EXIT_FAILURE;\r\n  }\r\n  // Constant gravitational force\r\n  Eigen::SparseMatrix<double> M;\r\n  igl::massmatrix(low.V,low.T,igl::MASSMATRIX_TYPE_DEFAULT,M);\r\n  const size_t n = low.V.rows();\r\n  arap_data.f_ext =  M * RowVector3d(0,-9.8,0).replicate(n,1);\r\n  // Random initial velocities to wiggle things\r\n  arap_data.vel = MatrixXd::Random(n,3);\r\n  \r\n  igl::opengl::glfw::Viewer viewer;\r\n  // Create one huge mesh containing both meshes\r\n  igl::cat(1,low.U,high.U,scene.U);\r\n  igl::cat(1,low.F,MatrixXi(high.F.array()+low.V.rows()),scene.F);\r\n  // Color each mesh\r\n  viewer.data().set_mesh(scene.U,scene.F);\r\n  MatrixXd C(scene.F.rows(),3);\r\n  C<<\r\n    RowVector3d(0.8,0.5,0.2).replicate(low.F.rows(),1),\r\n    RowVector3d(0.3,0.4,1.0).replicate(high.F.rows(),1);\r\n  viewer.data().set_colors(C);\r\n\r\n  viewer.callback_key_pressed = \r\n    [&](igl::opengl::glfw::Viewer & viewer,unsigned int key,int mods)->bool\r\n  {\r\n    switch(key)\r\n    {\r\n      default: \r\n        return false;\r\n      case ' ':\r\n        viewer.core.is_animating = !viewer.core.is_animating;\r\n        return true;\r\n      case 'r':\r\n        low.U = low.V;\r\n        return true;\r\n    }\r\n  };\r\n  viewer.callback_pre_draw = [&](igl::opengl::glfw::Viewer & viewer)->bool\r\n  {\r\n    glEnable(GL_CULL_FACE);\r\n    if(viewer.core.is_animating)\r\n    {\r\n      arap_solve(MatrixXd(0,3),arap_data,low.U);\r\n      for(int v = 0;v<low.U.rows();v++)\r\n      {\r\n        // collide with y=0 plane\r\n        const int y = 1;\r\n        if(low.U(v,y) < 0)\r\n        {\r\n          low.U(v,y) = -low.U(v,y);\r\n          // ~ coefficient of restitution\r\n          const double cr = 1.1;\r\n          arap_data.vel(v,y) = - arap_data.vel(v,y) / cr;\r\n        }\r\n      }\r\n\r\n      scene.U.block(0,0,low.U.rows(),low.U.cols()) = low.U;\r\n      high.U = W * (low.U.rowwise() + RowVector3d(1,0,0));\r\n      scene.U.block(low.U.rows(),0,high.U.rows(),high.U.cols()) = high.U;\r\n\r\n      viewer.data().set_vertices(scene.U);\r\n      viewer.data().compute_normals();\r\n    }\r\n    return false;\r\n  };\r\n  viewer.data().show_lines = false;\r\n  viewer.core.is_animating = true;\r\n  viewer.core.animation_max_fps = 30.;\r\n  viewer.data().set_face_based(true);\r\n  cout<<R\"(\r\n[space] to toggle animation\r\n'r'     to reset positions \r\n      )\";\r\n  viewer.core.rotation_type = \r\n    igl::opengl::ViewerCore::ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP;\r\n  viewer.launch();\r\n}\r\n", "meta": {"hexsha": "0953efb68c078fcc41e0c7285c9b6d513e1a031f", "size": 5487, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/tutorial/407_BiharmonicCoordinates/main.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/tutorial/407_BiharmonicCoordinates/main.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/tutorial/407_BiharmonicCoordinates/main.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 32.0877192982, "max_line_length": 87, "alphanum_fraction": 0.6181884454, "num_tokens": 1609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5917524401770442}}
{"text": "//\n// Copyright (c) 2020 INRIA\n//\n\n#include \"pinocchio/math/multiprecision-mpfr.hpp\"\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n#include <iostream>\n\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/center-of-mass.hpp\"\n#include \"pinocchio/algorithm/centroidal.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/math/multiprecision.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_basic)\n{\n  using namespace boost::multiprecision;\n\n  // Operations at fixed precision and full numeric_limits support:\n  mpfr_float_100 b = 2;\n  std::cout << std::numeric_limits<mpfr_float_100>::digits << std::endl;\n  std::cout << std::numeric_limits<mpfr_float_100>::digits10 << std::endl;\n  // We can use any C++ std lib function, lets print all the digits as well:\n  std::cout << std::setprecision(\n                   std::numeric_limits<mpfr_float_100>::max_digits10)\n            << log(b)\n            << 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\n  // large numbers here (4.0238726007709377354370243e+2564):\n  std::cout << boost::math::tgamma(mpfr_float_100(1000)) << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(test_sincos)\n{\n  using namespace boost::multiprecision;\n  typedef mpfr_float_100 heap_float_100;\n  typedef number<mpfr_float_backend<100, allocate_stack> > stack_float_100;\n  {\n    heap_float_100 x;\n    heap_float_100 s;\n    heap_float_100 c;\n    x = 100;\n    pinocchio::SINCOS(x, &s, &c);\n    BOOST_CHECK(s == sin(x));\n    BOOST_CHECK(c == cos(x));\n  }\n  {\n    stack_float_100 x;\n    stack_float_100 s;\n    stack_float_100 c;\n    x = 100;\n    pinocchio::SINCOS(x, &s, &c);\n    BOOST_CHECK(s == sin(x));\n    BOOST_CHECK(c == cos(x));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_cast)\n{\n  typedef boost::multiprecision::mpfr_float_100 float_100;\n\n  // Test Scalar cast\n  double initial_value = boost::math::constants::pi<double>();\n  float_100 value_100(initial_value);\n  double value_cast = value_100.convert_to<double>();\n  BOOST_CHECK(initial_value == value_cast);\n\n  typedef Eigen::Matrix<float_100, Eigen::Dynamic, 1> VectorFloat100;\n  static const Eigen::DenseIndex dim = 100;\n  Eigen::VectorXd initial_vec = Eigen::VectorXd::Random(dim);\n  VectorFloat100 vec_float_100 = initial_vec.cast<float_100>();\n  Eigen::VectorXd vec = vec_float_100.cast<double>();\n\n  BOOST_CHECK(vec == initial_vec);\n}\n\n#define BOOST_CHECK_IS_APPROX(double_field, multires_field, Scalar) \\\n  BOOST_CHECK(double_field.isApprox(multires_field.cast<Scalar>()))\n\nBOOST_AUTO_TEST_CASE(test_mutliprecision)\n{\n  using namespace pinocchio;\n\n  Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  Data data(model);\n\n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n\n  typedef boost::multiprecision::mpfr_float_100 float_100;\n  typedef ModelTpl<float_100> ModelMulti;\n  typedef DataTpl<float_100> DataMulti;\n\n  ModelMulti model_multi = model.cast<float_100>();\n  DataMulti data_multi(model_multi);\n\n  ModelMulti::ConfigVectorType q_multi = randomConfiguration(model_multi);\n  ModelMulti::TangentVectorType v_multi =\n      ModelMulti::TangentVectorType::Random(model_multi.nv);\n  ModelMulti::TangentVectorType a_multi =\n      ModelMulti::TangentVectorType::Random(model_multi.nv);\n  ModelMulti::TangentVectorType tau_multi =\n      ModelMulti::TangentVectorType::Random(model_multi.nv);\n\n  //  Model::ConfigVectorType q = randomConfiguration(model);\n  //  Model::TangentVectorType v = Model::TangentVectorType::Random(model.nv);\n  //  Model::TangentVectorType a = Model::TangentVectorType::Random(model.nv);\n  //  Model::TangentVectorType tau = Model::TangentVectorType::Random(model.nv);\n\n  Model::ConfigVectorType q = q_multi.cast<double>();\n  Model::TangentVectorType v = v_multi.cast<double>();\n  Model::TangentVectorType a = a_multi.cast<double>();\n  Model::TangentVectorType tau = tau_multi.cast<double>();\n\n  forwardKinematics(model_multi, data_multi, q_multi, v_multi, a_multi);\n  forwardKinematics(model, data, q, v, a);\n\n  for (JointIndex joint_id = 1; joint_id < (JointIndex)model.njoints;\n       ++joint_id)\n  {\n    BOOST_CHECK_IS_APPROX(data.oMi[joint_id], data_multi.oMi[joint_id], double);\n    BOOST_CHECK_IS_APPROX(data.v[joint_id], data_multi.v[joint_id], double);\n    BOOST_CHECK_IS_APPROX(data.a[joint_id], data_multi.a[joint_id], double);\n  }\n\n  // Jacobians\n  computeJointJacobians(model_multi, data_multi, q_multi);\n  computeJointJacobians(model, data, q);\n\n  BOOST_CHECK_IS_APPROX(data.J, data_multi.J, double);\n\n  // Inverse Dynamics\n  rnea(model_multi, data_multi, q_multi, v_multi, a_multi);\n  rnea(model, data, q, v, a);\n\n  BOOST_CHECK_IS_APPROX(data.tau, data_multi.tau, double);\n\n  // Forward Dynamics\n  aba(model_multi, data_multi, q_multi, v_multi, tau_multi);\n  aba(model, data, q, v, tau);\n\n  BOOST_CHECK_IS_APPROX(data.ddq, data_multi.ddq, double);\n\n  // Mass matrix\n  crba(model_multi, data_multi, q_multi);\n  data_multi.M.triangularView<Eigen::StrictlyLower>() =\n      data_multi.M.transpose().triangularView<Eigen::StrictlyLower>();\n\n  crba(model, data, q);\n  data.M.triangularView<Eigen::StrictlyLower>() =\n      data.M.transpose().triangularView<Eigen::StrictlyLower>();\n\n  BOOST_CHECK_IS_APPROX(data.M, data_multi.M, double);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "9ca2c2c336cc808eb5a22ca5f013a100c5613523", "size": 5887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/multiprecision-mpfr.cpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 716.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T16:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:26:58.000Z", "max_issues_repo_path": "unittest/multiprecision-mpfr.cpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1130.0, "max_issues_repo_issues_event_min_datetime": "2015-02-21T17:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:06:22.000Z", "max_forks_repo_path": "unittest/multiprecision-mpfr.cpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 34.226744186, "max_line_length": 80, "alphanum_fraction": 0.7307626975, "num_tokens": 1571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5917524372863389}}
{"text": "#ifndef IEOMPP_CONSTANTS_HPP_\n#define IEOMPP_CONSTANTS_HPP_\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ieompp\n{\n    template <typename Float>\n    struct Pi {\n        static const Float value;\n    };\n\n    template <typename Float>\n    struct HalfPi {\n        static const Float value;\n    };\n\n    template <typename Float>\n    struct TwoPi {\n        static const Float value;\n    };\n\n\n    template <typename Float>\n    const Float Pi<Float>::value = boost::math::constants::pi<Float>();\n\n    template <typename Float>\n    const Float HalfPi<Float>::value = boost::math::constants::half_pi<Float>();\n\n    template <typename Float>\n    const Float TwoPi<Float>::value = boost::math::constants::two_pi<Float>();\n} // namespace ieompp\n\n#endif\n", "meta": {"hexsha": "09d324e83eeaea487c121f0f9f8548da4148a79b", "size": 753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ieompp/constants.hpp", "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": "include/ieompp/constants.hpp", "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": "include/ieompp/constants.hpp", "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": 21.5142857143, "max_line_length": 80, "alphanum_fraction": 0.6679946879, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5917524274718895}}
{"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": "//\n// Copyright (c) 2019 INRIA\n//\n\n#include <pinocchio/math/quaternion.hpp>\n#include <pinocchio/spatial/se3.hpp>\n\n#include <boost/variant.hpp> // to avoid C99 warnings\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_assignQuaternion)\n{\n  using namespace pinocchio;\n  const int max_tests = 1e5;\n  for(int k = 0; k < max_tests; ++k)\n  {\n    const SE3 M(SE3::Random());\n    SE3::Quaternion quat_ref(M.rotation());\n    \n    SE3::Quaternion quat;\n    quaternion::assignQuaternion(quat,M.rotation());\n    \n    BOOST_CHECK(quat.coeffs().isApprox(quat_ref.coeffs()));\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "dc5d65ad9beeb5a3f78cad17cba0f09d803cb0f5", "size": 690, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/quaternion.cpp", "max_stars_repo_name": "yDMhaven/pinocchio", "max_stars_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T07:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T07:23:34.000Z", "max_issues_repo_path": "unittest/quaternion.cpp", "max_issues_repo_name": "longwoo/pinocchio", "max_issues_repo_head_hexsha": "66bb1bc08669497a0da3d303841e88f68b7434bb", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/quaternion.cpp", "max_forks_repo_name": "longwoo/pinocchio", "max_forks_repo_head_hexsha": "66bb1bc08669497a0da3d303841e88f68b7434bb", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-25T13:34:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T13:34:37.000Z", "avg_line_length": 20.9090909091, "max_line_length": 59, "alphanum_fraction": 0.7101449275, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.5917474410092555}}
{"text": "/*! \\file\tgeometry.hpp\n *  \\brief\tDeclarations for geometry-related calculations.\n*/\n\n#ifndef THERMALVIS_GEOMETRY_H\n#define THERMALVIS_GEOMETRY_H\n\n#ifdef _USE_EIGEN_\n\n#include \"core/tools.hpp\"\n\n#include \"core/general_resources.hpp\"\n#include \"core/ros_resources.hpp\"\n\n#include <opencv2/core.hpp>\n\n#ifdef _USE_OPENCV_VIZ_\n#include <opencv2/viz.hpp>\n#endif\n\n#include <Eigen/Geometry>\n\ntypedef Eigen::Matrix<float, 3, 3, Eigen::RowMajor> Matrix3frm;\ntypedef Eigen::Quaternion<double>   QuaternionDbl;\ntypedef Eigen::Quaternion<double>   Quaterniond;\ntypedef Eigen::Matrix<double, 4, 1, Eigen::DontAlign> Vector4d;\n\n//#include <math.h>\n\n// FLAGS for geometric distance measurement (F & H assessment)\n#define SAMPSON_DISTANCE\t\t\t0\n#define ALGEBRAIC_DISTANCE\t\t\t1\n#define EPIPOLAR_DISTANCE\t\t\t2\n#define LOURAKIS_DISTANCE\t\t\t3\n\n#define DEFAULT_ASSIGN_MODE\t\t\t0\n#define MAPPER_ASSIGN_MODE\t\t\t1\n\n#define MAX_TIME_GAP_FOR_INTERP\t\t\t\t\t0.5\n\n#define MAX_RVIZ_DISPLACEMENT \t\t\t\t\t1000\n\n#define CLUSTER_MEAN_MODE\t\t\t1\n#define DEFAULT_MEAN_MODE\t\t\t0\n\nvoid assignPose(geometry_msgs::PoseStamped& pPose, cv::Mat& C, int idx, ros::Time timestamp, int mode = DEFAULT_ASSIGN_MODE);\nvoid convertPoseFormat(const geometry_msgs::Pose& pose, cv::Mat& t, Eigen::Quaternion<double>& Q);\nvoid convertPoseFormat(const cv::Mat& t, const Eigen::Quaternion<double>& Q, geometry_msgs::Pose& pose);\nvoid convertAndShiftPoseFormat(const geometry_msgs::Pose& pose, cv::Mat& t, Eigen::Quaternion<double>& Q);\nvoid convertAndShiftPoseFormat(const cv::Mat& t, const Eigen::Quaternion<double>& Q, geometry_msgs::Pose& pose);\n\n/// \\brief \t\tConverts translation vector from OpenCV to Eigen format\nvoid convertTvecToEigenvec(const cv::Mat& T_src, Eigen::Vector3f& T_dst);\n\n/// \\brief \t\tConverts rotation matrix from OpenCV to Eigen format\nvoid convertRmatTo3frm(const cv::Mat& R_src, Matrix3frm& R_dst);\n\n/// \\brief \t\tConverts translation vector from Eigen to OpenCV format\nvoid convertEigenvecToTvec(const Eigen::Vector3f& T_src, cv::Mat& T_dst);\n\n#ifdef _USE_OPENCV_VIZ_\n/// \\brief \t\tConverts from 4x4 OpenCV matrix to 3x4 Affine representation\nvoid convertMatToAffine(const cv::Mat mat, cv::Affine3f& affine);\n#endif\n\n/// \\brief \t\tFinds centroid of 3D cloud\ncv::Point3d findCentroid(vector<cv::Point3d>& cloud);\n\n/// \\brief \t\tFinds the length of the diagonal from extreme corners of minimum enclosing prism (perpendicular do X,Y,Z axes)\ndouble findPrismDiagonal(vector<cv::Point3d>& cloud);\n\n/// \\brief \t\tConverts rotation matrix from Eigen to OpenCV format\nvoid convert3frmToRmat(const Matrix3frm& R_src, cv::Mat& R_dst);\n\n/// \\brief \t\tSplits OpenCV transformation matrix into rotation matrix and translation vector\nvoid decomposeTransform(const cv::Mat& c, cv::Mat& R, cv::Mat& t);\n\n/// \\brief\t\tFind the average point position of the dominant cluster\nbool findClusterMean(const vector<cv::Point3d>& estimatedLocations, cv::Point3d& pt3d, int mode = DEFAULT_MEAN_MODE, int minEstimates = 3, double maxStandardDev = 0.1);\n\n/// \\brief \t\tPossible duplicate of 'composeTransform'\nvoid findP1Matrix(cv::Mat& P1, const cv::Mat& R, const cv::Mat& t);\n\n/// \\brief \t\tCombines OpenCV rotation matrix and translation vector into a transformation matrix\nvoid composeTransform(const cv::Mat& R, const cv::Mat& t, cv::Mat& c);\n\n/// \\brief \t\tConverts OpenCV rotation matrix to Eigen quaternion \nvoid matrixToQuaternion(const cv::Mat& mat, Eigen::Quaternion<double>& quat);\n\n/// \\brief \t\tConverts Eigen quaternion to OpenCV rotation matrix\nvoid quaternionToMatrix(const Eigen::Quaternion<double>& quat, cv::Mat& mat, bool handedness = false);\n\n/// \\brief \t\tTransform a 3D point cloud according to a different coordinate system convention\nvoid transformPoints(std::vector<cv::Point3d>& pts, unsigned int option = 0);\n\n/// \\brief \t\tTransform a 3D point cloud according to a different coordinate system convention\nvoid transformPoints(std::vector<cv::Point3d>& pts, int *options);\n\n/// \\brief \t\tGet minimum number of projections required to achieve the specified number of pairs\nint minProjections(int pairs);\n\n/// \\brief \t\tGet maximum possible number of pairs able to be achieved with specified number of projections\nint possiblePairs(int projections);\n\n/// \\brief \t\tConvert from OpenCV 4x4 transformation matrix to 3x4 projection matrix\nvoid transformationToProjection(const cv::Mat& trans, cv::Mat& proj);\n\n/// \\brief \t\tConvert from OpenCV 3x4 projection matrix to 4x4 transformation matrix\nvoid projectionToTransformation(const cv::Mat& proj, cv::Mat& trans);\n\n/// \\brief \t\tExtract OpenCV 3x3 rotation matrix from OpenCV 3x4 projection matrix\nvoid projectionToRotation(const cv::Mat& src, cv::Mat& dst);\n\n/// \\brief \t\tConvert OpenCV 3x3 rotation matrix to OpenCV 3x4 projection matrix\nvoid rotationToProjection(const cv::Mat& src, cv::Mat& dst);\n\n/// \\brief \t\tExtract just the 3 translation magnitudes (X,Y,Z) between two poses\nvoid getTranslationBetweenCameras(cv::Mat& C1, cv::Mat& C2, double *translations);\n\n/// \\brief \t\tSet the 3x4 pose matrix to the equivalent of the identity pose\nvoid initializeP0(cv::Mat& P);\n\n/// \\brief \t\tGet the W and Z matrices, which are useful for some geometric operations\nvoid getWandZ(cv::Mat& W, cv::Mat& Winv, cv::Mat& Z);\n\n/// \\brief \t\tShift a 3D point according to a provided transformation\nvoid transfer3dPoint(const cv::Point3d& src, cv::Point3d& dst, const cv::Mat& C);\n\n/// \\brief \t\tShift a set of 3D points according to a provided transformation\nvoid transfer3DPoints(const std::vector<cv::Point3d>& src, std::vector<cv::Point3d>& dst, const cv::Mat& C);\n\n/// \\brief \t\tDetermine rotation relative to identity in degrees\ndouble getRotationInDegrees(const cv::Mat& R);\n\n/// \\brief \t\tGet magnitude of translation vector\ndouble getDistanceInUnits(const cv::Mat& t);\n\n/// \\brief \t\tGet angle difference between two quaternions\ndouble getQuaternionAngle(const Eigen::Quaterniond& q1, const Eigen::Quaterniond& q2);\n\n/// \\brief \t\tConvert 3D point from OpenCV point format to matrix format\nvoid convertPoint3dToMat(const cv::Point3d& src, cv::Mat& dst);\n\n/// \\brief \t\tCreate default quaternion\nQuaterniond defaultQuaternion();\n\n/// \\brief \t\tConverts OpenCV projection matrix to Eigen projection matrix\nvoid convertProjectionMatCVToEigen(const cv::Mat& mat, Eigen::Matrix< double, 3, 4 >& m);\n\n/// \\brief \t\tConverts Eigen projection matrix to OpenCV projection matrix \nvoid convertProjectionMatEigenToCV(const Eigen::Matrix< double, 3, 4 >& m, cv::Mat& mat);\n\n/// \\brief \t\tCalculate the dot product between two vectors\ndouble dotProduct(const cv::Mat& vec1, const cv::Mat& vec2);\n\n/// \\brief \t\tCalculate the dot product between two quaternions\ndouble dotProduct(const Quaterniond& q1, const Quaterniond& q2);\n\n/// \\brief \t\tConvert from Eigen vector to OpenCV matrix \nvoid convertVec4dToMat(const Vector4d& vec4, cv::Mat& mat);\n\n// Can't find where these are actually implemented!\n/*\nvoid compileTransform(cv::Mat& c, const cv::Mat& R, const cv::Mat& t);\nvoid combineTransforms(cv::Mat& CN, const cv::Mat& C0, const cv::Mat& C1);\nvoid decomposeTransform(const cv::Mat& c, cv::Mat& R, cv::Mat& t);\n*/\n\nbool interpolatePose(const geometry_msgs::Pose& pose1, ros::Time time1, const geometry_msgs::Pose& pose2, ros::Time time2, geometry_msgs::Pose& finalPose, ros::Time time3);\nvoid shiftPose(const geometry_msgs::Pose& pose_src, geometry_msgs::Pose& pose_dst, cv::Mat transformation);\n\n#endif // THERMALVIS_GEOMETRY_H\n\n#endif // _USE_EIGEN_", "meta": {"hexsha": "5ad90512ca1b6ae29cecb28d6c62228a74b23cb8", "size": 7404, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/slam/geometry.hpp", "max_stars_repo_name": "ida-zrt/thermalvis", "max_stars_repo_head_hexsha": "36a6ba0d12ab91097435630586e3eb760130582c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 109.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T23:30:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T03:24:36.000Z", "max_issues_repo_path": "include/slam/geometry.hpp", "max_issues_repo_name": "adaniy/thermalvis", "max_issues_repo_head_hexsha": "782f71b5fbde033d226d11b8d0c994fc83d10d98", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-02-19T05:46:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-02T14:00:49.000Z", "max_forks_repo_path": "include/slam/geometry.hpp", "max_forks_repo_name": "adaniy/thermalvis", "max_forks_repo_head_hexsha": "782f71b5fbde033d226d11b8d0c994fc83d10d98", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-05T11:51:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T06:36:57.000Z", "avg_line_length": 42.5517241379, "max_line_length": 172, "alphanum_fraction": 0.7567531064, "num_tokens": 1968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5917474410092554}}
{"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": "\n#include \"plan.h\"\n\n#include \"../Util.h\"\n#include \"../log.h\"\n#include \"../simulator/constants.h\"\n#include \"../simulator/graphics.h\"\n\n#include <iostream>\n#include <queue>\n#include <set>\n\n#include <Eigen/Core>\n\nconstexpr double EPSILON = 1.2; // heuristic weight for weighted A*\n\nusing namespace NavSim;\n\n// TODO implement goal orientations?\ndouble heuristic(int x, int y, const point_t& goal) {\n\tdouble dx = goal(0) - x * PLAN_RESOLUTION;\n\tdouble dy = goal(1) - y * PLAN_RESOLUTION;\n\treturn sqrt(dx * dx + dy * dy);\n}\n\nstruct Node {\n\tint x;\n\tint y;\n\tint theta;\t\t // allows values 0..7; gives angle in increments of pi/4\n\tdouble acc_cost; // accumulated cost\n\tdouble heuristic_to_goal;\n\tint acc_steps; // for knowing how long (in discrete steps) the plan will be\n\tstruct Node* parent;\n\t// action: the action taken to reach this node from the parent node\n\t// Tracking this makes it easier to construct the plan later.\n\taction_t action;\n\n\t// Note: In the robot frame, starting pose is always (0,0,0).\n\tNode(Node* p, action_t& a, const point_t& goal)\n\t\t: x(0), y(0), theta(0), acc_cost(0.), heuristic_to_goal(0.), acc_steps(0), parent(p),\n\t\t  action(a) {\n\t\tif (p != nullptr) {\n\t\t\tacc_steps = p->acc_steps + 1;\n\t\t\tbool moving_forward = action(1) > 0.0;\n\t\t\tdouble step_cost = moving_forward ? action(1) : RADIAN_COST * fabs(action(0));\n\t\t\tacc_cost = p->acc_cost + step_cost;\n\t\t\tif (moving_forward) {\n\t\t\t\ttheta = p->theta;\n\t\t\t\tint dx(0), dy(0);\n\t\t\t\tif (theta >= 1 && theta <= 3)\n\t\t\t\t\tdy = 1;\n\t\t\t\tif (theta >= 3 && theta <= 5)\n\t\t\t\t\tdx = -1;\n\t\t\t\tif (theta >= 5 && theta <= 7)\n\t\t\t\t\tdy = -1;\n\t\t\t\tif (theta == 7 || theta <= 1)\n\t\t\t\t\tdx = 1;\n\t\t\t\tx = p->x + dx;\n\t\t\t\ty = p->y + dy;\n\t\t\t} else {\n\t\t\t\tx = p->x;\n\t\t\t\ty = p->y;\n\t\t\t\ttheta = (p->theta + ((action(0) > 0.0) ? 1 : 7)) % 8;\n\t\t\t}\n\t\t}\n\t\theuristic_to_goal = heuristic(x, y, goal);\n\t}\n};\n\nstd::ostream& operator<<(std::ostream& out, const Node& n) {\n\tout << \"(\" << n.x << \" \" << n.y << \" \" << n.theta << \") \";\n\treturn out;\n}\n\nclass NodeEqualityCompare {\npublic:\n\tbool operator()(const Node* lhs, const Node* rhs) const {\n\t\tbool res = lhs->x < rhs->x || (lhs->x == rhs->x && lhs->y < rhs->y) ||\n\t\t\t\t   (lhs->x == rhs->x && lhs->y == rhs->y && lhs->theta < rhs->theta);\n\t\treturn res;\n\t}\n};\n\nclass NodeCompare {\npublic:\n\tbool operator()(const Node* lhs, const Node* rhs) {\n\t\treturn (lhs->acc_cost + EPSILON * (lhs->heuristic_to_goal)) >\n\t\t\t   (rhs->acc_cost + EPSILON * (rhs->heuristic_to_goal));\n\t}\n};\n\nusing pqueue_t = std::priority_queue<Node*, std::vector<Node*>, NodeCompare>;\nusing set_t = std::set<Node*, NodeEqualityCompare>;\nusing collides_predicate_t = std::function<bool(double x, double y, double radius)>;\n\nbool is_valid(const Node* n, const collides_predicate_t& collides) {\n\t// To get away from obstacles, turning is always allowed.\n\tif (n->action(1) == 0.0)\n\t\treturn true;\n\tdouble x = n->x * PLAN_RESOLUTION;\n\tdouble y = n->y * PLAN_RESOLUTION;\n\treturn !collides(x, y, SAFE_RADIUS);\n}\n\nplan_t getPlan(const collides_predicate_t& collides, const point_t& goal, double goal_radius) {\n\tutil::ScopedTimer timer;\n\tlog(LOG_DEBUG, \"Planning... \");\n\taction_t action = action_t::Zero();\n\tstd::vector<Node*> allocated_nodes;\n\tNode* start = new Node(nullptr, action, goal);\n\tallocated_nodes.push_back(start);\n\tpqueue_t fringe; // If you haven't guessed, we'll be using A*\n\tset_t visited_set;\n\tfringe.push(start);\n\tvisited_set.insert(start);\n\tNode* n = start;\n\tplan_t valid_actions(3, 2);\n\tvalid_actions << 0., 0., M_PI / 4, 0., -M_PI / 4, 0.;\n\tint counter = 0;\n\tbool success = false;\n\twhile (fringe.size() > 0) {\n\t\tif (counter++ > MAX_ITERS) {\n\t\t\tbreak;\n\t\t}\n\t\tn = fringe.top();\n\t\tfringe.pop();\n\t\tif (n->heuristic_to_goal < goal_radius) {\n\t\t\tsuccess = true;\n\t\t\tbreak;\n\t\t} else {\n\t\t\tdouble forward_dist =\n\t\t\t\t(n->theta % 2 == 1) ? PLAN_RESOLUTION * 1.414 : PLAN_RESOLUTION;\n\t\t\tvalid_actions(0, 1) = forward_dist;\n\t\t\tfor (int i = 0; i < valid_actions.rows(); i++) {\n\t\t\t\taction = valid_actions.row(i);\n\t\t\t\tNode* next = new Node(n, action, goal);\n\t\t\t\tallocated_nodes.push_back(next);\n\t\t\t\tif (is_valid(next, collides) && visited_set.count(next) == 0) {\n\t\t\t\t\tvisited_set.insert(next);\n\t\t\t\t\tfringe.push(next);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (success == false)\n\t\tn = start;\n\n\tplan_t plan(n->acc_steps, 2);\n\tfor (int i = n->acc_steps - 1; i >= 0; i--) {\n\t\tplan.row(i) = n->action;\n\t\tn = n->parent;\n\t}\n\n\tstd::chrono::milliseconds endTime = std::chrono::duration_cast<std::chrono::milliseconds>(\n\t\tstd::chrono::system_clock::now().time_since_epoch());\n\n\tlog(LOG_DEBUG, \"finished in %d iterations (%d visited nodes), Time: %dms\\n\", counter,\n\t\tallocated_nodes.size(), timer.elapsedTime().count() / 1000);\n\tfor (Node* p : allocated_nodes) {\n\t\tfree(p);\n\t}\n\n\treturn plan;\n}\n\n// Goal given in robot frame\nplan_t getPlan(const points_t& lidar_hits, const point_t& goal, double goal_radius) {\n\tcollides_predicate_t collidesPredicate = [&](double x, double y, double radius) {\n\t\tpose_t p = {x, y, 0};\n\t\ttransform_t trf = toTransform(p);\n\t\treturn collides(trf, lidar_hits, SAFE_RADIUS);\n\t};\n\treturn getPlan(collidesPredicate, goal, goal_radius);\n}\n\ndouble planCostFromIndex(plan_t& plan, int idx) {\n\tdouble cost = 0;\n\tfor (int i = idx; i < plan.rows(); i++) {\n\t\taction_t action = plan.row(i);\n\t\tcost += fabs(action(1)) + RADIAN_COST * fabs(action(0));\n\t}\n\treturn cost;\n}\n", "meta": {"hexsha": "5ea5b565770cf1468a1f62134cb3bef3d536aa02", "size": 5277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/planning/plan.cpp", "max_stars_repo_name": "huskyroboticsteam/PY2020", "max_stars_repo_head_hexsha": "cd6368d85866204dbdca6aefacac69059e780aa2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-10-03T01:17:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-25T02:38:32.000Z", "max_issues_repo_path": "src/planning/plan.cpp", "max_issues_repo_name": "huskyroboticsteam/PY2020", "max_issues_repo_head_hexsha": "cd6368d85866204dbdca6aefacac69059e780aa2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2019-10-03T02:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-05T03:11:55.000Z", "max_forks_repo_path": "src/planning/plan.cpp", "max_forks_repo_name": "huskyroboticsteam/PY2020", "max_forks_repo_head_hexsha": "cd6368d85866204dbdca6aefacac69059e780aa2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-20T04:09:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T22:25:20.000Z", "avg_line_length": 28.6793478261, "max_line_length": 95, "alphanum_fraction": 0.6380519234, "num_tokens": 1585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5915626181544946}}
{"text": "/*\n Copyright (C) 2020 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file qle/termstructures/spreadedsmilesection2.hpp\n    \\brief smile section with linear interpolated vol spreads\n    \\ingroup termstructures\n*/\n\n#pragma once\n\n#include <ql/math/interpolation.hpp>\n#include <ql/quote.hpp>\n#include <ql/termstructures/volatility/smilesection.hpp>\n\n#include <boost/shared_ptr.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\n\nclass SpreadedSmileSection2 : public SmileSection {\npublic:\n    SpreadedSmileSection2(const boost::shared_ptr<SmileSection>& base, const std::vector<Real>& volSpreads,\n                          const std::vector<Real>& strikes, const bool strikesRelativeToAtm = false,\n                          const Real atmLevel = Null<Real>());\n    Rate minStrike() const;\n    Rate maxStrike() const;\n    Rate atmLevel() const;\n\nprotected:\n    Volatility volatilityImpl(Rate strike) const;\n\nprivate:\n    boost::shared_ptr<SmileSection> base_;\n    std::vector<Real> volSpreads_;\n    std::vector<Real> strikes_;\n    bool strikesRelativeToAtm_;\n    Real atmLevel_;\n    Interpolation volSpreadInterpolation_;\n};\n\n} // namespace QuantExt\n", "meta": {"hexsha": "8cb785f9fecbd13abe0caf753d680837121e1ec9", "size": 1833, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/spreadedsmilesection2.hpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/termstructures/spreadedsmilesection2.hpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/termstructures/spreadedsmilesection2.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": 32.1578947368, "max_line_length": 107, "alphanum_fraction": 0.746863066, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5915445209569602}}
{"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": "/**\n * @file radauthreetimestepping_main.cc\n * @brief NPDE homework RadauThreeTimestepping\n * @author Erick Schulz\n * @date 08/04/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"radauthreetimestepping.h\"\n#include \"radauthreetimesteppingode.h\"\n\n#include <iostream>\n#include <memory>\n\n#include <Eigen/Core>\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\nusing namespace RadauThreeTimestepping;\n\nint main(int /*argc*/, char ** /*argv*/) {\n  /* Solving the ODE problem */\n  // This function prints to the terminal the convergence rates and average rate\n  // of a convergence study performed for the ODE (d/dt)y = -y.\n  testConvergenceTwoStageRadauLinScalODE();\n\n  /* Solving the parabolic heat equation */\n  // Create a Lehrfem++ square tensor product mesh\n  lf::mesh::hybrid2d::TPTriagMeshBuilder builder(\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2));\n  // Set mesh parameters following the Builder pattern\n  // Domain is the unit square\n  builder.setBottomLeftCorner(Eigen::Vector2d{-1.0, -1.0})\n      .setTopRightCorner(Eigen::Vector2d{1, 1})\n      .setNumXCells(50)\n      .setNumYCells(50);\n  auto mesh_p = builder.Build();\n\n  /* SAM_LISTING_BEGIN_1 */\n#if SOLUTION\n  // Generate the linear lagrange FE data\n  // Finite element space\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  // Obtain local->global index mapping for current finite element space\n  const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n  // Dimension of finite element space\n  const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n\n  // Solve heat evolution with zero initial and boundary conditions\n  double final_time = 1.0;\n  unsigned int m = 50;\n  Eigen::VectorXd discrete_heat_solution =\n      solveHeatEvolution(dofh, m, final_time);\n  LF_ASSERT_MSG(\n      discrete_heat_solution.size() == N_dofs,\n      \"Size of discrete solution and dimension of FE space mismatch.\");\n\n  // Output results to vtk file\n  lf::io::VtkWriter vtk_writer(\n      mesh_p, CURRENT_BINARY_DIR \"/discrete_heat_solution.vtk\");\n  // Write nodal data taking the values of the discrete solution at the vertices\n  auto nodal_data = lf::mesh::utils::make_CodimMeshDataSet<double>(mesh_p, 2);\n  for (int global_idx = 0; global_idx < N_dofs; global_idx++) {\n    nodal_data->operator()(dofh.Entity(global_idx)) =\n        discrete_heat_solution[global_idx];\n  };\n  vtk_writer.WritePointData(\"discrete_heat_solution\", *nodal_data);\n  /* SAM_LISTING_END_1 */\n  std::cout << \"\\n The discrete_heat_solution was written to:\" << std::endl;\n  std::cout << \">> discrete_heat_solution.vtk\\n\" << std::endl;\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n\n  return 0;\n}\n", "meta": {"hexsha": "b799c9ad4f214ca71656760c99473bae63ee3833", "size": 2834, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/RadauThreeTimestepping/mastersolution/radauthreetimestepping_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": "developers/RadauThreeTimestepping/mastersolution/radauthreetimestepping_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": "developers/RadauThreeTimestepping/mastersolution/radauthreetimestepping_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": 33.7380952381, "max_line_length": 80, "alphanum_fraction": 0.7071277347, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.5914844069822042}}
{"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": "///////////////////////////////////////////////////////////////////////////////\n// vector_space::example::difference.cpp                                     //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#include <vector>\n#include <algorithm>\n#include <functional>\n#include <iterator>\n#include <boost/bind.hpp>\n#include <boost/range.hpp>\n#include <boost/assert.hpp>\n#include <boost/foreach.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/math/tools/precision.hpp>\n#include <boost/vector_space/data/lazy_difference.hpp>\n\nvoid example_difference(std::ostream& out){\n    std::cout << \"-> example_difference : \";\n    using namespace boost;\n    namespace vs = statistics::detail::vector_space;\n    typedef double                          val_;\n    typedef std::vector<val_>               vec_;\n    typedef vs::lazy_difference<vec_,vec_>  range_diff_;\n\n    const val_ eps = math::tools::epsilon<val_>();\n    const val_ delta = eps * static_cast<val_>(2);\n\n    vec_ vec;\n    {\n        using namespace assign;\n        vec += 0.0, 1.1, 2.2, 3.3;\n    }\n    vec_ vec1(vec);\n    std::transform(\n        boost::begin(vec),\n        boost::end(vec),\n        begin(vec1),\n        boost::bind<val_>(\n            std::minus<val_>(),\n            _1,\n            delta\n        )\n    );\n\n    range_diff_ range_diff(vec,vec1);\n    vec_ copy_diff(size(vec));\n    std::copy(\n        const_begin(range_diff),\n        const_end(range_diff),\n        begin(copy_diff)\n    );\n\n   BOOST_FOREACH(const val_& z, copy_diff){\n        BOOST_ASSERT(fabs(z-delta)<eps);\n    }\n\n    out << \"<- \" << std::endl;\n}\n", "meta": {"hexsha": "f97d1d21e54d6075089758eda0f63236686c17b0", "size": 1941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vector_space/libs/vector_space/example/difference.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": "vector_space/libs/vector_space/example/difference.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": "vector_space/libs/vector_space/example/difference.cpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3064516129, "max_line_length": 79, "alphanum_fraction": 0.513137558, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5914494712165136}}
{"text": "#ifndef ALM_HERMITE_CURVE_VEC_H\n#define ALM_HERMITE_CURVE_VEC_H\n\n#include <Eigen/Dense>\n#include <avatar_locomanipulation/helpers/hermite_curve.hpp>\n\nclass HermiteCurveVec{\npublic:\n\tHermiteCurveVec();\n\tHermiteCurveVec(const Eigen::VectorXd & start_pos, const Eigen::VectorXd & start_vel, \n\t\t\t\t   const Eigen::VectorXd & end_pos, const Eigen::VectorXd & end_vel);\n\t~HermiteCurveVec();\n\tEigen::VectorXd evaluate(const double & s_in);\n\tEigen::VectorXd evaluateFirstDerivative(const double & s_in);\n\tEigen::VectorXd evaluateSecondDerivative(const double & s_in);\n\nprivate:\n\tEigen::VectorXd p1;\n\tEigen::VectorXd v1;\n\tEigen::VectorXd p2;\n\tEigen::VectorXd v2;\n\n\tstd::vector<HermiteCurve> curves;\n \tEigen::VectorXd output;\n};\n\n#endif", "meta": {"hexsha": "a8ad8f8e9206f91e10db6c2c6f6648f34a6e2575", "size": 725, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/avatar_locomanipulation/helpers/hermite_curve_vec.hpp", "max_stars_repo_name": "stevenjj/icra2020locomanipulation", "max_stars_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-01-06T11:43:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T22:59:09.000Z", "max_issues_repo_path": "include/avatar_locomanipulation/helpers/hermite_curve_vec.hpp", "max_issues_repo_name": "stevenjj/icra2020locomanipulation", "max_issues_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/avatar_locomanipulation/helpers/hermite_curve_vec.hpp", "max_forks_repo_name": "stevenjj/icra2020locomanipulation", "max_forks_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T16:08:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T11:13:49.000Z", "avg_line_length": 26.8518518519, "max_line_length": 87, "alphanum_fraction": 0.7724137931, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5914494662004155}}
{"text": "// -*- C++ -*-\n\n#include <mtl/matrix.h>\n#include <mtl/mtl.h>\n#include <mtl/utils.h> \n\nusing namespace mtl;\n\ntypedef matrix< double, rectangle<>, dense<>, column_major>::type MATRIX; \n\n\nint\nmain (int , char *[])\n{\n  MATRIX A(3, 5), B(5, 3);\n  for (int j = 0; j < 5; ++j)\n    for (int i = 0; i < 3; ++i)\n      A(i,j) = i * 5 + j;\n\n  transpose(A, B);\n  print_all_matrix(A);\n  print_all_matrix(B);\n  exit (0);\n}\n", "meta": {"hexsha": "aa194250c55b26c33388068d14a47f395ab03cf2", "size": 408, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/transpose.cc", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/transpose.cc", "max_issues_repo_name": "parasol-ppl/PPL_utils", "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/transpose.cc", "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.32, "max_line_length": 74, "alphanum_fraction": 0.5490196078, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5914494622771713}}
{"text": "/**\n * test eigensystem calculation\n * @author Tobias Weber <tweber@ill.fr>\n * @date 25-jul-20\n * @license GPLv3, see 'LICENSE' file\n *\n * g++ -std=c++20 -DUSE_LAPACK -I.. -I/usr/include/lapacke -Iext/lapacke/include -Lext/lapacke/lib -o eig eig.cpp -llapacke\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021  Tobias WEBER (Institut Laue-Langevin (ILL),\n *                          Grenoble, France).\n * Copyright (C) 2015-2017  Tobias WEBER (Technische Universitaet Muenchen\n *                          (TUM), Garching, Germany).\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n * ----------------------------------------------------------------------------\n */\n\n#define BOOST_TEST_MODULE Eigenvector Test\n#include <boost/test/included/unit_test.hpp>\nnamespace test = boost::unit_test;\nnamespace testtools = boost::test_tools;\n\n#include <iostream>\n#include <vector>\n#include <random>\n\n#include \"libs/maths.h\"\n\n\n// LinearAlgebra.eigen([-1.5 0.01 0.02; -0.04 1.0 0.03; -2.05 0.06 0.5])\n\nusing t_types = std::tuple<double, float>;\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_eig, t_real, t_types)\n{\n\tusing namespace tl2_ops;\n\n\tusing t_cplx = std::complex<t_real>;\n\tusing t_vec = tl2::vec<t_real, std::vector>;\n\tusing t_mat = tl2::mat<t_real, std::vector>;\n\tusing t_vec_cplx = tl2::vec<t_cplx, std::vector>;\n\tusing t_mat_cplx = tl2::mat<t_cplx, std::vector>;\n\n\tt_real eps = 1e-4;\n\tstd::size_t dim = 3;\n\n\tstd::mt19937 rndgen{tl2::epoch<unsigned int>()};\n\tstd::uniform_real_distribution<t_real> rnddist{-100, 100};\n\n\t// real version\n\t{\n\t\tstd::cout << \"--------------------------------------------------------------------------------\" << std::endl;\n\t\tauto mat = tl2::zero<t_mat>(dim,dim);\n\t\tfor(std::size_t i=0; i<dim; ++i)\n\t\t\tfor(std::size_t j=0; j<dim; ++j)\n\t\t\t\tmat(i,j) = rnddist(rndgen);\n\t\tstd::cout << mat << std::endl;\n\n\t\tbool sym = 0;\n\t\tauto [ok, evals_re, evals_im, evecs_re, evecs_im] =\n\t\t\ttl2_la::eigenvec<t_mat, t_vec, t_real>(mat, false, sym, true);\n\t\tstd::cout << \"ok = \" << std::boolalpha << ok << \"\\n\" << std::endl;\n\n\t\tfor(std::size_t i=0; i<evals_re.size(); ++i)\n\t\t\tstd::cout << \"Re(eval) \" << i+1 << \": \" << evals_re[i] << std::endl;\n\t\tfor(std::size_t i=0; i<evals_im.size(); ++i)\n\t\t\tstd::cout << \"Im(eval) \" << i+1 << \": \" << evals_im[i] << std::endl;\n\t\tstd::cout << std::endl;\n\n\t\tfor(std::size_t i=0; i<evecs_re.size(); ++i)\n\t\t\tstd::cout << \"Re(evec) \" << i+1 << \": \" << evecs_re[i] << std::endl;\n\t\tstd::cout << std::endl;\n\t\tfor(std::size_t i=0; i<evecs_im.size(); ++i)\n\t\t\tstd::cout << \"Im(evec) \" << i+1 << \": \" << evecs_im[i] << std::endl;\n\t\tstd::cout << std::endl;\n\n\t\tBOOST_TEST(ok);\n\n\n\t\tt_mat_cplx mat_cplx = tl2::zero<t_mat_cplx>(dim, dim);\n\t\tfor(std::size_t i=0; i<dim; ++i)\n\t\t\tfor(std::size_t j=0; j<dim; ++j)\n\t\t\t\tmat_cplx(i,j) = mat(i,j);\n\n\t\tfor(std::size_t i=0; i<dim; ++i)\n\t\t{\n\t\t\tt_cplx eval = t_cplx{evals_re[i], evals_im[i]};\n\t\t\tt_vec_cplx evec = tl2::zero<t_vec_cplx>(dim);\n\n\t\t\tfor(std::size_t j=0; j<dim; ++j)\n\t\t\t\tevec[j] = t_cplx{evecs_re[i][j], evecs_im[i][j]};\n\n\t\t\tt_vec_cplx tstvec1 = mat_cplx * evec;\n\t\t\tt_vec_cplx tstvec2 = eval * evec;\n\t\t\tbool is_equal = tl2::equals<t_vec_cplx>(tstvec1, tstvec2, eps);\n\t\t\tstd::cout << tstvec1 << \" == \" << tstvec2 << \": \" << std::boolalpha << is_equal << std::endl;\n\t\t\tBOOST_TEST(is_equal);\n\t\t}\n\n\t\tstd::cout << \"--------------------------------------------------------------------------------\\n\" << std::endl;\n\t}\n\n\n\t// real version, symmetric\n\t{\n\t\tstd::cout << \"--------------------------------------------------------------------------------\" << std::endl;\n\t\tauto mat = tl2::zero<t_mat>(dim,dim);\n\t\tfor(std::size_t i=0; i<dim; ++i)\n\t\t\tfor(std::size_t j=i; j<dim; ++j)\n\t\t\t\tmat(j,i) = mat(i,j) = rnddist(rndgen);\n\t\tstd::cout << mat << std::endl;\n\n\t\tbool sym = 1;\n\t\tauto [ok, evals_re, evals_im, evecs_re, evecs_im] =\n\t\t\ttl2_la::eigenvec<t_mat, t_vec, t_real>(mat, false, sym, true);\n\t\tstd::cout << \"ok = \" << std::boolalpha << ok << \"\\n\" << std::endl;\n\n\t\tfor(std::size_t i=0; i<evals_re.size(); ++i)\n\t\t\tstd::cout << \"Re(eval) \" << i+1 << \": \" << evals_re[i] << std::endl;\n\t\tfor(std::size_t i=0; i<evals_im.size(); ++i)\n\t\t\tstd::cout << \"Im(eval) \" << i+1 << \": \" << evals_im[i] << std::endl;\n\t\tstd::cout << std::endl;\n\n\t\tfor(std::size_t i=0; i<evecs_re.size(); ++i)\n\t\t\tstd::cout << \"Re(evec) \" << i+1 << \": \" << evecs_re[i] << std::endl;\n\t\tstd::cout << std::endl;\n\t\tfor(std::size_t i=0; i<evecs_im.size(); ++i)\n\t\t\tstd::cout << \"Im(evec) \" << i+1 << \": \" << evecs_im[i] << std::endl;\n\t\tstd::cout << std::endl;\n\n\t\tBOOST_TEST(ok);\n\n\n\t\tt_mat_cplx mat_cplx = tl2::zero<t_mat_cplx>(dim, dim);\n\t\tfor(std::size_t i=0; i<dim; ++i)\n\t\t\tfor(std::size_t j=0; j<dim; ++j)\n\t\t\t\tmat_cplx(i,j) = mat(i,j);\n\n\t\tfor(std::size_t i=0; i<dim; ++i)\n\t\t{\n\t\t\tt_cplx eval = t_cplx{evals_re[i], evals_im[i]};\n\t\t\tt_vec_cplx evec = tl2::zero<t_vec_cplx>(dim);\n\n\t\t\tfor(std::size_t j=0; j<dim; ++j)\n\t\t\t\tevec[j] = t_cplx{evecs_re[i][j], evecs_im[i][j]};\n\n\t\t\tt_vec_cplx tstvec1 = mat_cplx * evec;\n\t\t\tt_vec_cplx tstvec2 = eval * evec;\n\t\t\tbool is_equal = tl2::equals<t_vec_cplx>(tstvec1, tstvec2, eps);\n\t\t\tstd::cout << tstvec1 << \" == \" << tstvec2 << \": \" << std::boolalpha << is_equal << std::endl;\n\t\t\tBOOST_TEST(is_equal);\n\t\t}\n\n\t\tstd::cout << \"--------------------------------------------------------------------------------\\n\" << std::endl;\n\t}\n\n\n\t// complex version\n\t{\n\t\tstd::cout << \"--------------------------------------------------------------------------------\" << std::endl;\n\n\t\tauto mat = tl2::zero<t_mat_cplx>(dim, dim);\n\t\tfor(std::size_t i=0; i<dim; ++i)\n\t\t\tfor(std::size_t j=0; j<dim; ++j)\n\t\t\t\tmat(i,j) = rnddist(rndgen) + rnddist(rndgen)*t_cplx{0, 1};\n\t\tstd::cout << mat << std::endl;\n\n\t\tbool herm = 0;\n\t\tauto [ok, evals, evecs] =\n\t\t\ttl2_la::eigenvec<t_mat_cplx, t_vec_cplx, t_cplx>(mat, false, herm, true);\n\t\tstd::cout << \"ok = \" << std::boolalpha << ok << \"\\n\" << std::endl;\n\n\t\tfor(std::size_t i=0; i<evecs.size(); ++i)\n\t\t\tstd::cout << \"eval \" << i+1 << \": \" << evals[i] << std::endl;\n\t\tstd::cout << std::endl;\n\t\tfor(std::size_t i=0; i<evecs.size(); ++i)\n\t\t\tstd::cout << \"evec \" << i+1 << \": \" << evecs[i] << std::endl;\n\t\tstd::cout << std::endl;\n\n\t\tBOOST_TEST(ok);\n\t\tfor(std::size_t i=0; i<dim; ++i)\n\t\t{\n\t\t\tt_vec_cplx tstvec1 = mat*evecs[i];\n\t\t\tt_vec_cplx tstvec2 = evals[i]*evecs[i];\n\t\t\tbool is_equal = tl2::equals<t_vec_cplx>(tstvec1, tstvec2, eps);\n\t\t\tstd::cout << tstvec1 << \" == \" << tstvec2 << \": \" << std::boolalpha << is_equal << std::endl;\n\t\t\tBOOST_TEST(is_equal);\n\t\t}\n\n\t\tstd::cout << \"--------------------------------------------------------------------------------\\n\" << std::endl;\n\t}\n\n\n\t// complex version, hermitian\n\t{\n\t\tstd::cout << \"--------------------------------------------------------------------------------\" << std::endl;\n\n\t\tauto mat = tl2::zero<t_mat_cplx>(dim, dim);\n\t\tfor(std::size_t i=0; i<dim; ++i)\n\t\t{\n\t\t\tfor(std::size_t j=i+1; j<dim; ++j)\n\t\t\t{\n\t\t\t\tmat(i,j) = rnddist(rndgen) + rnddist(rndgen)*t_cplx{0, 1};\n\t\t\t\tmat(j,i) = std::conj(mat(i,j));\n\t\t\t}\n\t\t}\n\t\tfor(std::size_t i=0; i<dim; ++i)\n\t\t\tmat(i,i) = rnddist(rndgen);\n\t\tstd::cout << mat << std::endl;\n\n\t\tbool herm = 1;\n\t\tauto [ok, evals, evecs] =\n\t\t\ttl2_la::eigenvec<t_mat_cplx, t_vec_cplx, t_cplx>(mat, false, herm, true);\n\t\tstd::cout << \"ok = \" << std::boolalpha << ok << \"\\n\" << std::endl;\n\n\t\tfor(std::size_t i=0; i<evecs.size(); ++i)\n\t\t\tstd::cout << \"eval \" << i+1 << \": \" << evals[i] << std::endl;\n\t\tstd::cout << std::endl;\n\t\tfor(std::size_t i=0; i<evecs.size(); ++i)\n\t\t\tstd::cout << \"evec \" << i+1 << \": \" << evecs[i] << std::endl;\n\t\tstd::cout << std::endl;\n\n\t\tBOOST_TEST(ok);\n\t\tfor(std::size_t i=0; i<dim; ++i)\n\t\t{\n\t\t\tt_vec_cplx tstvec1 = mat*evecs[i];\n\t\t\tt_vec_cplx tstvec2 = evals[i]*evecs[i];\n\t\t\tbool is_equal = tl2::equals<t_vec_cplx>(tstvec1, tstvec2, eps);\n\t\t\tstd::cout << tstvec1 << \" == \" << tstvec2 << \": \" << std::boolalpha << is_equal << std::endl;\n\t\t\tBOOST_TEST(is_equal);\n\t\t}\n\n\t\tstd::cout << \"--------------------------------------------------------------------------------\\n\" << std::endl;\n\t}\n}\n", "meta": {"hexsha": "fd4054af70ceb6ebd1255ccee4f87983c4cbee03", "size": 8551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/eig.cpp", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittests/eig.cpp", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/eig.cpp", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 34.6194331984, "max_line_length": 123, "alphanum_fraction": 0.5350251433, "num_tokens": 2836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5914494428574597}}
{"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(), \"\u00b7\", strlen(\"\u00b7\")) == 0) {\n\t\t\tCParserPP::Pos pos = p.GetPos();\n\t\t\tpos.ptr += strlen(\"\u00b7\");\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(), \"\u00ba\", strlen(\"\u00ba\")) == 0) { \n\t\t\tCParserPP::Pos pos = p.GetPos();\n\t\t\tpos.ptr += strlen(\"\u00ba\");\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": "#include <boost/mpl/plus.hpp>\n#include <boost/mpl/int.hpp>\n#include <functional>\n#include <cassert>\n\nusing namespace boost::mpl;\n\n/**\n * metafunction class\n */\nstruct plus_mf {\n    template <class T1, class T2> \n        struct apply {\n            typedef typename plus<T1, T2>::type type;\n        };\n\n    /* metafunction forward */\n    //template <class T1, class T2>\n    //    struct apply: plus<T1, T2> { };\n};\n\n/**\n * function object(functor)\n */\n//struct plus_f {\n//    int operator () (int x, int y) {\n//        return x + y;\n//    }\n//};\nstruct plus_f: std::plus<int> {};\n\n/**\n */\ntemplate <int lhs, int rhs>\nstruct plus_ff {\n    int operator() () {\n        return lhs + rhs;\n    }\n};\n\n/**\n */\ntemplate <int lhs, int rhs>\nstruct plus_fff {\n    const static int value = lhs + rhs;\n};\n\nint main()\n{\n    static_assert((plus<int_<1>, int_<2>>::value == int_<3>::value), \"metafunction\");\n    static_assert((plus_mf::apply<int_<1>, int_<2>>::type::value == int_<3>::value), \"metafunction-class\");\n    assert((plus_f()(1, 2) == 3));\n    assert((plus_ff<1, 2>()() == 3));\n    static_assert((plus_fff<1, 2>::value == 3), \"metafunction2\");\n    return 0;\n}\n", "meta": {"hexsha": "f32fff0a65abd11a7259c183cb3a257c1804cc51", "size": 1152, "ext": "cc", "lang": "C++", "max_stars_repo_path": "chapter3/metafunction-class.cc", "max_stars_repo_name": "HelloCodeMing/TMP", "max_stars_repo_head_hexsha": "49573215d1c88eadda8273499b31c3b184a64d0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-02T03:03:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-02T03:03:43.000Z", "max_issues_repo_path": "chapter3/metafunction-class.cc", "max_issues_repo_name": "HelloCodeMing/TMP", "max_issues_repo_head_hexsha": "49573215d1c88eadda8273499b31c3b184a64d0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter3/metafunction-class.cc", "max_forks_repo_name": "HelloCodeMing/TMP", "max_forks_repo_head_hexsha": "49573215d1c88eadda8273499b31c3b184a64d0f", "max_forks_repo_licenses": ["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.2105263158, "max_line_length": 107, "alphanum_fraction": 0.5720486111, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5914078199476556}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <vector>\n#include \"perf_test.hpp\"\n#include \"types.hpp\"\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> MatrixXd;\ntypedef Eigen::SelfAdjointEigenSolver<MatrixXd> EVD;\n\nvoid run_evd(EVD&& evd, const MatrixXd& m, unsigned int flags) { evd.compute(m, flags); }\n\nusing EVDTolType = decltype(&run_evd);\n\ndouble base_cost(size_t n) {\n    // https://eigen.tuxfamily.org/dox/classEigen_1_1SelfAdjointEigenSolver.html#adf397f6bce9f93c4b0139a47e261fc24\n    return 9 * n * n * n;\n}\n\nstd::vector<EVDTolType> tol_based_versions = {run_evd};\nstd::vector<std::string> tol_based_names = {\"evd_eigen\"};\n\nint main() {\n    std::ios_base::sync_with_stdio(false);  // disable synchronization between C and C++ standard streams\n    std::cin.tie(NULL);                     // untie cin from cout\n\n    size_t n;\n    std::cin >> n;\n    std::cout << \"Performance benchmark on array of size \" << n << \" by \" << n << std::endl;\n\n    MatrixXd A(n, n);\n    EVD evd;\n\n    for (size_t i = 0; i < n; ++i) {\n        for (size_t j = 0; j < n; j++) {\n            std::cin >> A(i, j);\n        }\n    }\n\n    std::vector<double> costs = {base_cost(n)};\n    run_all(tol_based_versions, tol_based_names, costs, evd, A, Eigen::ComputeEigenvectors);\n}\n", "meta": {"hexsha": "fdc00145cef99018ae0a930a0c0373ecb006682e", "size": 1343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perf/evd/eigen/evd_perf.cpp", "max_stars_repo_name": "ktrianta/jacobi-svd-evd", "max_stars_repo_head_hexsha": "8162562c631c3d1541e23b1fa38ec7600a5032af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-09T14:22:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T05:40:44.000Z", "max_issues_repo_path": "perf/evd/eigen/evd_perf.cpp", "max_issues_repo_name": "ktrianta/jacobi-svd-evd", "max_issues_repo_head_hexsha": "8162562c631c3d1541e23b1fa38ec7600a5032af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-03-17T14:02:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-12T13:15:19.000Z", "max_forks_repo_path": "perf/evd/eigen/evd_perf.cpp", "max_forks_repo_name": "ktrianta/jacobi-svd-evd", "max_forks_repo_head_hexsha": "8162562c631c3d1541e23b1fa38ec7600a5032af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-03-09T14:22:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T19:36:42.000Z", "avg_line_length": 29.8444444444, "max_line_length": 114, "alphanum_fraction": 0.6552494415, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.591407814371906}}
{"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": "////////////////////////////////////////////////////////////////////////////////\n\n/** To enforce matrix output from root process only */\n// #define ROOT_OUTPUT\n\n/** To enforce matrix generation for local->local */\n// #define LOCAL\n\n/** To denote whether rowwise sketching is attempted (columnwise otherwise) */\n#define ROWWISE\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n#include <boost/mpi.hpp>\n#include <elemental.hpp>\n#include <skylark.hpp>\n#include <iostream>\n\n\n/** Aliases */\n\ntypedef elem::Matrix<double>     dense_matrix_t;\n\ntypedef elem::DistMatrix<double> dist_dense_matrix_t;\ntypedef elem::DistMatrix<double, elem::VC, elem::STAR>\ndist_VC_STAR_dense_matrix_t;\ntypedef elem::DistMatrix<double, elem::VR, elem::STAR>\ndist_VR_STAR_dense_matrix_t;\ntypedef elem::DistMatrix<double, elem::STAR, elem::VC>\ndist_STAR_VC_dense_matrix_t;\ntypedef elem::DistMatrix<double, elem::STAR, elem::VR>\ndist_STAR_VR_dense_matrix_t;\n\ntypedef elem::DistMatrix<double, elem::CIRC, elem::CIRC>\ndist_CIRC_CIRC_dense_matrix_t;\n\ntypedef elem::DistMatrix<double, elem::STAR, elem::STAR>\ndist_STAR_STAR_dense_matrix_t;\n\n\n/* Set the following 2 typedefs for various matrix-type tests */\ntypedef dist_dense_matrix_t input_matrix_t;\ntypedef dist_dense_matrix_t output_matrix_t;\n\ntypedef skylark::sketch::JLT_t<input_matrix_t, output_matrix_t>\nsketch_transform_t;\n\n\nint main(int argc, char* argv[]) {\n\n    /** Initialize MPI  */\n    boost::mpi::environment env(argc, argv);\n    boost::mpi::communicator world;\n\n    /** Initialize Elemental */\n    elem::Initialize (argc, argv);\n\n    MPI_Comm mpi_world(world);\n    elem::Grid grid(mpi_world);\n\n    /** Example parameters */\n    int height      = 20;\n    int width       = 10;\n    int sketch_size = 5;\n\n    /** Define input matrix A */\n\n#ifdef LOCAL\n    input_matrix_t A;\n    elem::Uniform(A, height, width);\n#else\n    dist_CIRC_CIRC_dense_matrix_t A_CIRC_CIRC(grid);\n    input_matrix_t A(grid);\n    elem::Uniform(A_CIRC_CIRC, height, width);\n    A = A_CIRC_CIRC;\n#endif\n\n    /** Initialize context */\n    skylark::base::context_t context(0);\n\n#ifdef ROWWISE\n\n    /** Sketch transform (rowwise)*/\n    int size = width;\n    /** Distributed matrix computation */\n    output_matrix_t sketched_A(height, sketch_size);\n    sketch_transform_t sketch_transform(size, sketch_size, context);\n    sketch_transform.apply(A, sketched_A, skylark::sketch::rowwise_tag());\n\n#else\n\n    /** Sketch transform (columnwise)*/\n    int size = height;\n    /** Distributed matrix computation */\n    output_matrix_t sketched_A(sketch_size, width);\n    sketch_transform_t sketch_transform(size, sketch_size, context);\n    sketch_transform.apply(A, sketched_A, skylark::sketch::columnwise_tag());\n\n#endif\n\n#ifdef ROOT_OUTPUT\n    if (world.rank() == 0) {\n#endif\n        elem::Print(sketched_A, \"sketched_A\");\n#ifdef ROOT_OUTPUT\n    }\n#endif\n    elem::Finalize();\n    return 0;\n}\n", "meta": {"hexsha": "b7e6e5eda3990fb35dfce80a66dbea0bd1eaaa96", "size": 2916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/hp_dense.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/hp_dense.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/hp_dense.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": 26.0357142857, "max_line_length": 80, "alphanum_fraction": 0.676611797, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.5913818289918704}}
{"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": "#include <Eigen/Dense>\n#include <aslam/cameras/Triangulation.hpp>\n\nnamespace aslam {\nnamespace cameras {\n\nvoid triangulate(const Eigen::Vector3d& point1, const Eigen::Vector3d& ray1, const Eigen::Vector3d& point2,\n                 const Eigen::Vector3d& ray2, Eigen::Vector3d& outTriangulatedPoint, double& outGap, double& outS1,\n                 double& outS2) {\n    Eigen::Vector3d t12 = point2 - point1;\n\n    Eigen::Vector2d b;\n    b[0] = t12.dot(ray1);\n    b[1] = t12.dot(ray2);\n    Eigen::Matrix2d A;\n    A(0, 0) = ray1.dot(ray1);\n    A(1, 0) = ray1.dot(ray2);\n    A(0, 1) = -A(1, 0);\n    A(1, 1) = -ray2.dot(ray2);\n    Eigen::Vector2d lambda = A.inverse() * b;\n    Eigen::Vector3d xm = point1 + lambda[0] * ray1;\n    Eigen::Vector3d xn = point2 + lambda[1] * ray2;\n    t12 = (xm - xn);\n\n    outGap = t12.norm();\n    outTriangulatedPoint = xn + 0.5 * t12;\n    outS1 = lambda[0];\n    outS2 = lambda[1];\n}\n\n}  // namespace cameras\n}  // namespace aslam\n", "meta": {"hexsha": "5dd1936420880f54647d3918e10a9be8b32781d4", "size": 956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_cv/aslam_cameras/src/Triangulation.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_cv/aslam_cameras/src/Triangulation.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_cv/aslam_cameras/src/Triangulation.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": 28.9696969697, "max_line_length": 115, "alphanum_fraction": 0.6035564854, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5913164328312073}}
{"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 <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <test/unit/math/rev/scal/fun/nan_util.hpp>\n#include <test/unit/math/rev/scal/util.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\nTEST(AgradRev, lgamma) {\n  AVAR a = 3.0;\n  AVAR f = lgamma(a);\n  EXPECT_FLOAT_EQ(lgamma(3.0), f.val());\n\n  AVEC x = createAVEC(a);\n  VEC grad_f;\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(boost::math::digamma(3.0), grad_f[0]);\n}\n\nstruct lgamma_fun {\n  template <typename T0>\n  inline T0 operator()(const T0& arg1) const {\n    return lgamma(arg1);\n  }\n};\n\nTEST(AgradRev, lgamma_NaN) {\n  lgamma_fun lgamma_;\n  test_nan(lgamma_, false, true);\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  AVAR a = 3.0;\n  test::check_varis_on_stack(stan::math::lgamma(a));\n}\n", "meta": {"hexsha": "e4734cb7fd4a0176ae2e9dd25825ca04e08f464d", "size": 757, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/scal/fun/lgamma_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T14:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T14:57:41.000Z", "max_issues_repo_path": "test/unit/math/rev/scal/fun/lgamma_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-23T19:58:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T12:03:41.000Z", "max_forks_repo_path": "test/unit/math/rev/scal/fun/lgamma_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2647058824, "max_line_length": 56, "alphanum_fraction": 0.6908850727, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5913076574882707}}
{"text": "// Copyright John Maddock 2006.\n// Copyright Paul A. Bristow 2007, 2009\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifdef _MSC_VER\n# pragma warning (disable : 4996) // POSIX name for this item is deprecated\n# pragma warning (disable : 4224) // nonstandard extension used : formal parameter 'arg' was previously defined as a type\n# pragma warning (disable : 4180) // qualifier applied to function type has no meaning; ignored\n#endif\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/test/test_exec_monitor.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/tools/stats.hpp>\n#include <boost/math/tools/test.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/array.hpp>\n#include \"functor.hpp\"\n\n#include \"test_beta_hooks.hpp\"\n#include \"handle_test_result.hpp\"\n\n#undef small // VC++ #defines small char !!!!!!\n\n#ifndef SC_\n#define SC_(x) static_cast<T>(BOOST_JOIN(x, L))\n#endif\n\ntemplate <class T>\nvoid do_test_beta(const T& data, const char* type_name, const char* test_name)\n{\n   typedef typename T::value_type row_type;\n   typedef typename row_type::value_type value_type;\n\n   typedef value_type (*pg)(value_type, value_type);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::beta<value_type, value_type>;\n#else\n   pg funcp = boost::math::beta;\n#endif\n\n   boost::math::tools::test_result<value_type> result;\n\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n\n   //\n   // test beta against data:\n   //\n   result = boost::math::tools::test(\n      data, \n      bind_func(funcp, 0, 1), \n      extract_result(2));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::beta\", test_name);\n#ifdef TEST_OTHER\n   if(::boost::is_floating_point<value_type>::value){\n      funcp = other::beta;\n      result = boost::math::tools::test(\n         data, \n         bind_func(funcp, 0, 1), \n         extract_result(2));\n      print_test_result(result, data[result.worst()], result.worst(), type_name, \"other::beta\");\n   }\n#endif\n   std::cout << std::endl;\n}\ntemplate <class T>\nvoid test_beta(T, const char* name)\n{\n   //\n   // The actual test data is rather verbose, so it's in a separate file\n   //\n   // The contents are as follows, each row of data contains\n   // three items, input value a, input value b and beta(a, b):\n   // \n#  include \"beta_small_data.ipp\"\n\n   do_test_beta(beta_small_data, name, \"Beta Function: Small Values\");\n\n#  include \"beta_med_data.ipp\"\n\n   do_test_beta(beta_med_data, name, \"Beta Function: Medium Values\");\n\n#  include \"beta_exp_data.ipp\"\n\n   do_test_beta(beta_exp_data, name, \"Beta Function: Divergent Values\");\n}\n\ntemplate <class T>\nvoid test_spots(T)\n{\n   //\n   // Basic sanity checks, tolerance is 20 epsilon expressed as a percentage:\n   //\n   T tolerance = boost::math::tools::epsilon<T>() * 20 * 100;\n   T small = boost::math::tools::epsilon<T>() / 1024;\n   BOOST_CHECK_CLOSE(::boost::math::beta(static_cast<T>(1), static_cast<T>(1)), static_cast<T>(1), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::beta(static_cast<T>(1), static_cast<T>(4)), static_cast<T>(0.25), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::beta(static_cast<T>(4), static_cast<T>(1)), static_cast<T>(0.25), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::beta(small, static_cast<T>(4)), 1/small, tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::beta(static_cast<T>(4), small), 1/small, tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::beta(static_cast<T>(4), static_cast<T>(20)), static_cast<T>(0.00002823263692828910220214568040654997176736L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::beta(static_cast<T>(0.0125L), static_cast<T>(0.000023L)), static_cast<T>(43558.24045647538375006349016083320744662L), tolerance);\n}\n\n", "meta": {"hexsha": "8d70005592c138327ac87338be124ed756fabc57", "size": 4103, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_beta.hpp", "max_stars_repo_name": "AishwaryaDoosa/Boost1.49", "max_stars_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/math/test/test_beta.hpp", "max_issues_repo_name": "AishwaryaDoosa/Boost1.49", "max_issues_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/test/test_beta.hpp", "max_forks_repo_name": "AishwaryaDoosa/Boost1.49", "max_forks_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3, "max_line_length": 165, "alphanum_fraction": 0.6955885937, "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.5913076548122863}}
{"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// \u50cf\u7d20\u5750\u6807\u8f6c\u76f8\u673a\u5f52\u4e00\u5316\u5750\u6807\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    //-- \u8bfb\u53d6\u56fe\u50cf\n    Mat img_1 = imread ( argv[1], CV_LOAD_IMAGE_COLOR );\n    Mat img_2 = imread ( argv[2], CV_LOAD_IMAGE_COLOR );\n\n    vector<KeyPoint> keypoints_1, keypoints_2;\n    vector<DMatch> matches;\n    find_feature_matches ( img_1, img_2, keypoints_1, keypoints_2, matches );\n    cout<<\"\u4e00\u5171\u627e\u5230\u4e86\"<<matches.size() <<\"\u7ec4\u5339\u914d\u70b9\"<<endl;\n\n    // \u5efa\u7acb3D\u70b9\n    Mat depth1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED );       // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n    Mat depth2 = imread ( argv[4], CV_LOAD_IMAGE_UNCHANGED );       // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n    Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n    vector<Point3f> 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    //-- \u521d\u59cb\u5316\n    Mat descriptors_1, descriptors_2;\n    // used in OpenCV3 \n    Ptr<FeatureDetector> detector = ORB::create();\n    Ptr<DescriptorExtractor> descriptor = ORB::create();\n    // use this if you are in OpenCV2 \n    // Ptr<FeatureDetector> detector = FeatureDetector::create ( \"ORB\" );\n    // Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( \"ORB\" );\n    Ptr<DescriptorMatcher> matcher  = DescriptorMatcher::create(\"BruteForce-Hamming\");\n    //-- \u7b2c\u4e00\u6b65:\u68c0\u6d4b Oriented FAST \u89d2\u70b9\u4f4d\u7f6e\n    detector->detect ( img_1,keypoints_1 );\n    detector->detect ( img_2,keypoints_2 );\n\n    //-- \u7b2c\u4e8c\u6b65:\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97 BRIEF \u63cf\u8ff0\u5b50\n    descriptor->compute ( img_1, keypoints_1, descriptors_1 );\n    descriptor->compute ( img_2, keypoints_2, descriptors_2 );\n\n    //-- \u7b2c\u4e09\u6b65:\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n    vector<DMatch> match;\n   // BFMatcher matcher ( NORM_HAMMING );\n    matcher->match ( descriptors_1, descriptors_2, match );\n\n    //-- \u7b2c\u56db\u6b65:\u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n    double min_dist=10000, max_dist=0;\n\n    //\u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        double dist = match[i].distance;\n        if ( dist < min_dist ) min_dist = dist;\n        if ( dist > max_dist ) max_dist = dist;\n    }\n\n    printf ( \"-- Max dist : %f \\n\", max_dist );\n    printf ( \"-- Min dist : %f \\n\", min_dist );\n\n    //\u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        if ( match[i].distance <= max ( 2*min_dist, 30.0 ) )\n        {\n            matches.push_back ( match[i] );\n        }\n    }\n}\n\nPoint2d pixel2cam ( const Point2d& p, const Mat& K )\n{\n    return Point2d\n           (\n               ( p.x - K.at<double> ( 0,2 ) ) / K.at<double> ( 0,0 ),\n               ( p.y - K.at<double> ( 1,2 ) ) / K.at<double> ( 1,1 )\n           );\n}\n\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    // \u521d\u59cb\u5316g2o\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose\u7ef4\u5ea6\u4e3a 6, landmark \u7ef4\u5ea6\u4e3a 3\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverEigen<Block::PoseMatrixType>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    Block* solver_ptr = new Block( linearSolver );      // \u77e9\u9635\u5757\u6c42\u89e3\u5668\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": "#include <iostream>\n#include <boost_random.hpp>\n\nint main()\n{\n  //uni_int_dist_type dist1(1,6); // created a uniform integer distribution from [1,6]\n  uni_real_dist_type uni_real_dist(0,1); // created a uniform real distribution from [0,1) \n  uni_var_gen_real_type random_unif_real(gen,uni_real_dist); // binding the random generator with \"uni_real_dist\" distribution\n\n  for(int i=0; i<100; i++){\n    std::cout << \" \" << random_unif_real();\n    std::cout << std::endl;\n  }  \n\n  return 0;\n}\n\n", "meta": {"hexsha": "f0d0f25728691416d1f5a2f2e22dc7c4b01794c6", "size": 491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/boost_random_test.cpp", "max_stars_repo_name": "anupgp/astron", "max_stars_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/old/src/old/boost_random_test.cpp", "max_issues_repo_name": "anupgp/astron", "max_issues_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/old/src/old/boost_random_test.cpp", "max_forks_repo_name": "anupgp/astron", "max_forks_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2777777778, "max_line_length": 126, "alphanum_fraction": 0.6965376782, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5912643826941884}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\n\ntemplate <typename Matrix>\nvoid test(Matrix& A, const char* name)\n{\n    typedef typename mtl::Collection<Matrix>::value_type   value_type;\n    \n    value_type array[][3]= {{1., 2., 3.}, {4., 5., 6.}, {7., 8., 9.}};\n    A= array;\n\n    cout << \"\\n\" << name << \"\\n\" << \"A =\\n\" << A;\n\n    int indices[]= {1, 2, 0};\n    mtl::mat::traits::permutation<>::type P= mtl::mat::permutation(indices);\n    cout << \"\\nP =\\n\" << P;    \n\n    Matrix A2( P * A );\n    cout << \"\\nP * A =\\n\" << A2;\n\n    MTL_THROW_IF(A2[1][2] != value_type(9.), mtl::runtime_error(\"Wrong value after row permutation!\"));\n\n    Matrix A3( A2 * trans(P) );\n    cout << \"\\nA2 * trans(P) =\\n\" << A3;\n\n    MTL_THROW_IF(A3[1][2] != value_type(7.), mtl::runtime_error(\"Wrong value after column permutation!\"));\n}\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n    \n    dense2D<double>                                      dr;\n    dense2D<double, mat::parameters<col_major> >      dc;\n    morton_dense<double, recursion::morton_z_mask>       mzd;\n    morton_dense<double, recursion::doppled_2_row_mask>  d2r;\n    compressed2D<double>                                 cr;\n    compressed2D<double, mat::parameters<col_major> > cc;\n\n    dense2D<complex<double> >                            drc;\n    compressed2D<complex<double> >                       crc;\n\n    test(dr, \"Dense row major\");\n    test(dc, \"Dense column major\");\n    test(mzd, \"Morton Z-order\");\n    test(d2r, \"Hybrid 2 row-major\");\n    test(cr, \"Compressed row major\");\n    test(cc, \"Compressed column major\");\n    test(drc, \"Dense row major complex\");\n    test(crc, \"Compressed row major complex\");\n\n\t\n    return 0;\n}\n", "meta": {"hexsha": "af4ec4138eb1aa679c7015bd9e0679b1a5eaaece", "size": 2163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/permutation_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/permutation_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/permutation_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.0416666667, "max_line_length": 106, "alphanum_fraction": 0.5908460472, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.5912536506526338}}
{"text": "#include \"cpu/image_proc.h\"\r\n\r\n#include <Eigen/Dense>\r\n#include <map>\r\n#include <string>\r\n#include <cmath>\r\n\r\nnamespace helper {\r\n\r\n    bool in_bounds(Eigen::Vector2f p, int h, int w) {\r\n        return p.x() >= 0.0 && p.x() < w && p.y() >= 0.0 && p.y() < h;\r\n    }\r\n\r\n    bool valid_flow_at(const Eigen::Vector2f& p, int h, int w, py::array_t<float>& flow_image, Eigen::Vector2f& flow) {\r\n        if (!in_bounds(p, h, w)) {\r\n            return false;\r\n        }\r\n\r\n        flow.x() = *flow_image.data(p.y(), p.x(), 0);\r\n        flow.y() = *flow_image.data(p.y(), p.x(), 1);\r\n\r\n        if (!flow.allFinite()) {\r\n            return false;\r\n        }\r\n\r\n        return true;\r\n    }\r\n}\r\n\r\nnamespace image_proc {\r\n\r\n    using Vec2f = Eigen::Vector2f;\r\n    \r\n    template <class V, class L = std::less<std::string>, \r\n              class A = Eigen::aligned_allocator<std::pair<const std::string, V>>>\r\n    using aligned_dict = std::map<std::string, V, L, A>;\r\n\r\n    py::array_t<float> compute_augmented_flow_from_rotation(py::array_t<float>& flow_image_rot_sa2so, \r\n                                              py::array_t<float>& flow_image_so2to, \r\n                                              py::array_t<float>& flow_image_rot_to2ta,\r\n                                              const int h, const int w) {\r\n        // TODO: change to runtime asserts\r\n        // assert(flow_image_rot_sa2so.ndim() == 3);\r\n        // assert(flow_image_rot_sa2so.shape(0) == 2);\r\n        // assert(flow_image_rot_sa2so.shape(1) == h);\r\n        // assert(flow_image_rot_sa2so.shape(2) == w);\r\n\r\n        // assert(flow_image_so2to.ndim() == 3);\r\n        // assert(flow_image_so2to.shape(0) == 2);\r\n        // assert(flow_image_so2to.shape(1) == h);\r\n        // assert(flow_image_so2to.shape(2) == w);\r\n\r\n        // assert(flow_image_rot_to2ta.ndim() == 3);\r\n        // assert(flow_image_rot_to2ta.shape(0) == 2);\r\n        // assert(flow_image_rot_to2ta.shape(1) == h);\r\n        // assert(flow_image_rot_to2ta.shape(2) == w);\r\n\r\n        // allocate memory for output array\r\n        py::array_t<float> flow_image_rot_sa2ta = py::array_t<float>(flow_image_rot_sa2so.request().size);\r\n\r\n        // reshape array to match input shape\r\n        flow_image_rot_sa2ta.resize({h, w, 2});\r\n\r\n        for (int y = 0; y < h; y++) {\r\n            for (int x = 0; x < w; x++) {\r\n\r\n                // update output flow image\r\n                *flow_image_rot_sa2ta.mutable_data(y, x, 0) = - std::numeric_limits<float>::infinity();\r\n                *flow_image_rot_sa2ta.mutable_data(y, x, 1) = - std::numeric_limits<float>::infinity();\r\n\r\n                Vec2f p_sa(x, y);\r\n\r\n                /////////////////////////////////////////////////////////////////////////////////\r\n                // 1. SOURCE AUGMENTED TO SOURCE ORIGINAL\r\n                /////////////////////////////////////////////////////////////////////////////////\r\n\r\n                // flow from source augmented to source original\r\n                Vec2f flow_sa2so(*flow_image_rot_sa2so.data(y, x, 0), *flow_image_rot_sa2so.data(y, x, 1));\r\n                \r\n                // flow_sa2so should be dense and w/o any invalid value\r\n                if (!flow_sa2so.allFinite()) {\r\n                    throw \"flow_sa2so sould be dense and w/o any invalid values!\";\r\n                }\r\n\r\n                // compute warped location on source original (so we're going from source augmented to source original)\r\n                Vec2f p_so = p_sa + flow_sa2so;\r\n\r\n                // init flow_sa2ta with the first contribution, i.e, flow_sa2so\r\n                Vec2f flow_sa2ta = flow_sa2so;\r\n\r\n                /////////////////////////////////////////////////////////////////////////////////\r\n                // 2. SOURCE ORIGINAL TO TARGET ORIGINAL\r\n                /////////////////////////////////////////////////////////////////////////////////\r\n                int u0 = std::floor(p_so.x());\r\n                int u1 = u0 + 1;\r\n                int v0 = std::floor(p_so.y());\r\n                int v1 = v0 + 1;\r\n\r\n                Vec2f p00(u0, v0);\r\n                Vec2f p01(u0, v1);\r\n                Vec2f p10(u1, v0);\r\n                Vec2f p11(u1, v1);\r\n\r\n                aligned_dict<Vec2f> valid_coords;\r\n                aligned_dict<Vec2f> valid_flows;\r\n\r\n                Vec2f flow_00_so2to;\r\n                if (helper::valid_flow_at(p00, h, w, flow_image_so2to, flow_00_so2to)) {\r\n                    valid_coords[\"p00\"] = p00;\r\n                    valid_flows[\"p00\"]  = flow_00_so2to;\r\n                }\r\n\r\n                Vec2f flow_01_so2to;\r\n                if (helper::valid_flow_at(p01, h, w, flow_image_so2to, flow_01_so2to)) {\r\n                    valid_coords[\"p01\"] = p01;\r\n                    valid_flows[\"p01\"]  = flow_01_so2to;\r\n                }\r\n\r\n                Vec2f flow_10_so2to;\r\n                if (helper::valid_flow_at(p10, h, w, flow_image_so2to, flow_10_so2to)) {\r\n                    valid_coords[\"p10\"] = p10;\r\n                    valid_flows[\"p10\"]  = flow_10_so2to;\r\n                }\r\n\r\n                Vec2f flow_11_so2to;\r\n                if (helper::valid_flow_at(p11, h, w, flow_image_so2to, flow_11_so2to)) {\r\n                    valid_coords[\"p11\"] = p11;\r\n                    valid_flows[\"p11\"]  = flow_11_so2to;\r\n                }\r\n\r\n                // Depending on how many valid flows we have, do bilinear interpolation or nearest neighbor:\r\n                Vec2f flow_so2to;\r\n\r\n                if (valid_coords.size() == 0) {\r\n                    continue;\r\n                } else if (valid_coords.size() == 4) {\r\n                    // Bilinear interpolation\r\n                    float du = p_so.x() - u0;\r\n                    float dv = p_so.y() - v0;\r\n\r\n                    float w00 = (1 - du) * (1 - dv);\r\n                    float w01 = (1 - du) * dv;\r\n                    float w10 = du * (1 - dv);\r\n                    float w11 = du * dv;\r\n\r\n                    flow_so2to = w00 * valid_flows[\"p00\"] + \r\n                                 w01 * valid_flows[\"p01\"] + \r\n                                 w10 * valid_flows[\"p10\"] + \r\n                                 w11 * valid_flows[\"p11\"];                    \r\n                } else {\r\n                    // Nearest Neighbor\r\n                    std::string nn = \"None\";\r\n                    float min_dist = std::numeric_limits<float>::max();\r\n\r\n                    for (const auto& valid_coord : valid_coords) {\r\n                        const std::string k = valid_coord.first;\r\n                        const Vec2f& p = valid_coord.second;\r\n\r\n                        float dist = (p_so - p).norm();\r\n                        if (dist < min_dist) {\r\n                            min_dist = dist;\r\n                            nn = k;\r\n                        }\r\n                    }\r\n                    \r\n                    if (nn == \"None\") {\r\n                        throw std::runtime_error(\"Neighrest Neighbor 'nn' was not assigned...\");\r\n                    }\r\n\r\n                    flow_so2to = valid_flows[nn];\r\n                }\r\n\r\n                // compute warped location on target original (so we're going from source original to target original)\r\n                Vec2f p_to = p_so + flow_so2to;\r\n\r\n                // add flow_so2to to flow_sa2ta\r\n                flow_sa2ta += flow_so2to;\r\n\r\n                /////////////////////////////////////////////////////////////////////////////////\r\n                // 3. TARGET ORIGINAL TO TARGET AUGMENTED\r\n                /////////////////////////////////////////////////////////////////////////////////\r\n                u0 = std::floor(p_to.x());\r\n                u1 = u0 + 1;\r\n                v0 = std::floor(p_to.y());\r\n                v1 = v0 + 1;\r\n\r\n                p00 = Vec2f(u0, v0);\r\n                p01 = Vec2f(u0, v1);\r\n                p10 = Vec2f(u1, v0);\r\n                p11 = Vec2f(u1, v1);\r\n\r\n                valid_coords.clear();\r\n                valid_flows.clear();\r\n\r\n                Vec2f flow_00_to2ta;\r\n                if (helper::valid_flow_at(p00, h, w, flow_image_rot_to2ta, flow_00_to2ta)) {\r\n                    valid_coords[\"p00\"] = p00;\r\n                    valid_flows[\"p00\"]  = flow_00_to2ta;\r\n                }\r\n\r\n                Vec2f flow_01_to2ta;\r\n                if (helper::valid_flow_at(p01, h, w, flow_image_rot_to2ta, flow_01_to2ta)) {\r\n                    valid_coords[\"p01\"] = p01;\r\n                    valid_flows[\"p01\"]  = flow_01_to2ta;\r\n                }\r\n\r\n                Vec2f flow_10_to2ta;\r\n                if (helper::valid_flow_at(p10, h, w, flow_image_rot_to2ta, flow_10_to2ta)) {\r\n                    valid_coords[\"p10\"] = p10;\r\n                    valid_flows[\"p10\"]  = flow_10_to2ta;\r\n                }\r\n\r\n                Vec2f flow_11_to2ta;\r\n                if (helper::valid_flow_at(p11, h, w, flow_image_rot_to2ta, flow_11_to2ta)) {\r\n                    valid_coords[\"p11\"] = p11;\r\n                    valid_flows[\"p11\"]  = flow_11_to2ta;\r\n                }\r\n\r\n                // Depending on how many valid flows we have, do bilinear interpolation or nearest neighbor:\r\n                Vec2f flow_to2ta;\r\n\r\n                if (valid_coords.size() == 0) {\r\n                    continue;\r\n                } else if (valid_coords.size() == 4) {\r\n                    // Bilinear interpolation\r\n                    float du = p_to.x() - u0;\r\n                    float dv = p_to.y() - v0;\r\n\r\n                    float w00 = (1 - du) * (1 - dv);\r\n                    float w01 = (1 - du) * dv;\r\n                    float w10 = du * (1 - dv);\r\n                    float w11 = du * dv;\r\n\r\n                    flow_to2ta = w00 * valid_flows[\"p00\"] + \r\n                                 w01 * valid_flows[\"p01\"] + \r\n                                 w10 * valid_flows[\"p10\"] + \r\n                                 w11 * valid_flows[\"p11\"];                    \r\n                } else {\r\n                    // Nearest Neighbor\r\n                    std::string nn = \"None\";\r\n                    float min_dist = std::numeric_limits<float>::max();\r\n\r\n                    for (const auto& valid_coord : valid_coords) {\r\n                        const std::string k = valid_coord.first;\r\n                        const Vec2f& p = valid_coord.second;\r\n\r\n                        float dist = (p_to - p).norm();\r\n                        if (dist < min_dist) {\r\n                            min_dist = dist;\r\n                            nn = k;\r\n                        }\r\n                    }\r\n                    \r\n                    if (nn == \"None\") {\r\n                        throw std::runtime_error(\"Neighrest Neighbor 'nn' was not assigned...\");\r\n                    }\r\n\r\n                    flow_to2ta = valid_flows[nn];\r\n                }\r\n\r\n                // add flow_to2ta to flow_sa2ta\r\n                flow_sa2ta += flow_to2ta;\r\n\r\n                // update output flow image\r\n                *flow_image_rot_sa2ta.mutable_data(y, x, 0) = flow_sa2ta.x();\r\n                *flow_image_rot_sa2ta.mutable_data(y, x, 1) = flow_sa2ta.y();\r\n            }\r\n        }\r\n\r\n        return flow_image_rot_sa2ta;\r\n    }\r\n\r\n    int count_tp1(py::array_t<bool> &p, py::array_t<bool> &gt) {\r\n        assert(p.ndim() == 2);\r\n        assert(gt.ndim() == 2);\r\n        const int n_batch = p.shape(0);\r\n        const int dimz = p.shape(1);\r\n\r\n        auto& ptr = p;\r\n        int counter = 0;\r\n        for (int i = 0; i < n_batch; i++) \r\n            for (int z = 0 ; z < dimz ; z++)\r\n                if (*gt.data(i, z)) {\r\n                    counter += CHECK1();\r\n                }\r\n        return counter;\r\n    }\r\n\r\n    int count_tp2(py::array_t<bool> &p, py::array_t<bool> &gt) {\r\n        assert(p.ndim() == 4);\r\n        assert(gt.ndim() == 4);\r\n        const int n_batch = p.shape(0);\r\n        assert(p.shape(1) == 1);\r\n        const int height = p.shape(2);\r\n        const int width = p.shape(3);\r\n\r\n        auto& ptr = p;\r\n        int counter = 0;\r\n        for (int i = 0; i < n_batch; i++) \r\n            for (int y = 0; y <  height; y++)\r\n                for (int x = 0; x < width; x++) {\r\n                    if (*gt.data(i, 0, y, x)) {\r\n                        counter += CHECK2();\r\n                    }\r\n                }\r\n        return counter;\r\n    }\r\n\r\n    int count_tp3(py::array_t<bool> &p, py::array_t<bool> &gt) {\r\n        assert(p.ndim() == 5);\r\n        assert(gt.ndim() == 5);\r\n        const int n_batch = p.shape(0);\r\n        assert(p.shape(1) == 1);\r\n        const int dimz = p.shape(2);\r\n        const int dimy = p.shape(3);\r\n        const int dimx = p.shape(4);\r\n\r\n        auto& ptr = p;\r\n        int counter = 0;\r\n        for (int i = 0; i < n_batch; i++) \r\n            for (int z = 0 ; z < dimz ; z++)\r\n                for (int y = 0; y <  dimy; y++)\r\n                    for (int x = 0; x < dimx; x++) {\r\n                        if (*gt.data(i, 0, z, y, x)) {\r\n                            counter += CHECK3();\r\n                            //printf(\"i %d x %d y %d z %d in %d\\n\", i, x, y, z, res);\r\n                        }\r\n                    }\r\n        return counter;\r\n    }\r\n\r\n    void extend3(py::array_t<bool> &in, py::array_t<bool> &out) {\r\n        assert(in.ndim() == 5);\r\n        assert(out.ndim() == 5);\r\n        int n_batch = in.shape(0);\r\n        assert(in.shape(1) == 1);\r\n        int dimz = in.shape(2);\r\n        int dimy = in.shape(3);\r\n        int dimx = in.shape(4);\r\n\r\n        auto& ptr = in;\r\n        for (int i = 0; i < n_batch; i++) \r\n            for (int z = 1 ; z < dimz - 1; z++)\r\n                for (int y = 1; y <  dimy - 1; y++)\r\n                    for (int x = 1; x < dimx - 1; x++) {\r\n                        *out.mutable_data(i, 0, z, y, x) = CHECK3();\r\n                    }\r\n    }\r\n\r\n    void backproject_depth_ushort(py::array_t<unsigned short>& in, py::array_t<float>& out, float fx, float fy, float cx, float cy, float normalizer) {\r\n        assert(in.ndim() == 2);\r\n        assert(out.ndim() == 3);\r\n\r\n        int width = in.shape(1);\r\n        int height = in.shape(0);\r\n        assert(out.shape(0) == 3);\r\n        assert(out.shape(1) == height);\r\n        assert(out.shape(2) == width);\r\n        \r\n        for (int y = 0; y < height; y++) {\r\n            for (int x = 0; x < width; x++) {\r\n                float depth = float(*in.data(y, x)) / normalizer;\r\n\r\n                if (depth > 0) {\r\n                    float pos_x = depth * (x - cx) / fx;\r\n                    float pos_y = depth * (y - cy) / fy;\r\n                    float pos_z = depth;\r\n\r\n                    *out.mutable_data(0, y, x) = pos_x;\r\n                    *out.mutable_data(1, y, x) = pos_y;\r\n                    *out.mutable_data(2, y, x) = pos_z;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    void backproject_depth_float(py::array_t<float>& in, py::array_t<float>& out, float fx, float fy, float cx, float cy) {\r\n        assert(in.ndim() == 2);\r\n        assert(out.ndim() == 3);\r\n\r\n        int width = in.shape(1);\r\n        int height = in.shape(0);\r\n        assert(out.shape(0) == 3);\r\n        assert(out.shape(1) == height);\r\n        assert(out.shape(2) == width);\r\n        \r\n        for (int y = 0; y < height; y++) {\r\n            for (int x = 0; x < width; x++) {\r\n                float depth = *in.data(y, x);\r\n\r\n                if (depth > 0) {\r\n                    float pos_x = depth * (x - cx) / fx;\r\n                    float pos_y = depth * (y - cy) / fy;\r\n                    float pos_z = depth;\r\n\r\n                    *out.mutable_data(0, y, x) = pos_x;\r\n                    *out.mutable_data(1, y, x) = pos_y;\r\n                    *out.mutable_data(2, y, x) = pos_z;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    void compute_mesh_from_depth(\r\n        const py::array_t<float>& pointImage, float maxTriangleEdgeDistance, \r\n        py::array_t<float>& vertexPositions, py::array_t<int>& vertexPixels, py::array_t<int>& faceIndices\r\n    ) {\r\n        int width = pointImage.shape(2);\r\n        int height = pointImage.shape(1);\r\n\r\n        // Compute valid pixel vertices and faces.\r\n        // We also need to compute the pixel -> vertex index mapping for \r\n        // computation of faces.\r\n        // We connect neighboring pixels on the square into two triangles.\r\n        // We only select valid triangles, i.e. with all valid vertices and\r\n        // not too far apart.\r\n        // Important: The triangle orientation is set such that the normals\r\n        // point towards the camera.\r\n        std::vector<Eigen::Vector3f> vertices;\r\n        std::vector<Eigen::Vector3i> faces;\r\n        std::vector<Eigen::Vector2i> pixels;\r\n\r\n        int vertexIdx = 0;\r\n        std::vector<int> mapPixelToVertexIdx(width * height, -1);\r\n\r\n        for (int y = 0; y < height - 1; y++) {\r\n            for (int x = 0; x < width - 1; x++) {\r\n                Eigen::Vector3f obs00(*pointImage.data(0, y, x), *pointImage.data(1, y, x), *pointImage.data(2, y, x));\r\n                Eigen::Vector3f obs01(*pointImage.data(0, y + 1, x), *pointImage.data(1, y + 1, x), *pointImage.data(2, y + 1, x));\r\n                Eigen::Vector3f obs10(*pointImage.data(0, y, x + 1), *pointImage.data(1, y, x + 1), *pointImage.data(2, y, x + 1));\r\n                Eigen::Vector3f obs11(*pointImage.data(0, y + 1, x + 1), *pointImage.data(1, y + 1, x + 1), *pointImage.data(2, y + 1, x + 1));\r\n\r\n                int idx00 = y * width + x;\r\n                int idx01 = (y + 1) * width + x;\r\n                int idx10 = y * width + (x + 1);\r\n                int idx11 = (y + 1) * width + (x + 1);\r\n\r\n                bool valid00 = obs00.z() > 0;\r\n                bool valid01 = obs01.z() > 0;\r\n                bool valid10 = obs10.z() > 0;\r\n                bool valid11 = obs11.z() > 0;\r\n\r\n                if (valid00 && valid01 && valid10) {\r\n                    float d0 = (obs00 - obs01).norm();\r\n                    float d1 = (obs00 - obs10).norm();\r\n                    float d2 = (obs01 - obs10).norm();\r\n                    \r\n                    if (d0 <= maxTriangleEdgeDistance && d1 <= maxTriangleEdgeDistance && d2 <= maxTriangleEdgeDistance) {\r\n                        int vIdx0 = mapPixelToVertexIdx[idx00];\r\n                        int vIdx1 = mapPixelToVertexIdx[idx01];\r\n                        int vIdx2 = mapPixelToVertexIdx[idx10];\r\n\r\n                        if (vIdx0 == -1) {\r\n                            vIdx0 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx00] = vertexIdx;\r\n                            vertices.push_back(obs00);\r\n                            pixels.push_back(Eigen::Vector2i(x, y));\r\n\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx1 == -1) {\r\n                            vIdx1 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx01] = vertexIdx;\r\n                            vertices.push_back(obs01);\r\n                            pixels.push_back(Eigen::Vector2i(x, y+1));\r\n\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx2 == -1) {\r\n                            vIdx2 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx10] = vertexIdx;\r\n                            vertices.push_back(obs10);\r\n                            pixels.push_back(Eigen::Vector2i(x+1, y));\r\n                            vertexIdx++;\r\n                        }\r\n\r\n                        faces.push_back(Eigen::Vector3i(vIdx0, vIdx1, vIdx2));\r\n                    }\r\n                }\r\n\r\n                if (valid01 && valid10 && valid11) {\r\n                    float d0 = (obs10 - obs01).norm();\r\n                    float d1 = (obs10 - obs11).norm();\r\n                    float d2 = (obs01 - obs11).norm();\r\n\r\n                    if (d0 <= maxTriangleEdgeDistance && d1 <= maxTriangleEdgeDistance && d2 <= maxTriangleEdgeDistance) {\r\n                        int vIdx0 = mapPixelToVertexIdx[idx11];\r\n                        int vIdx1 = mapPixelToVertexIdx[idx10];\r\n                        int vIdx2 = mapPixelToVertexIdx[idx01];\r\n\r\n                        if (vIdx0 == -1) {\r\n                            vIdx0 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx11] = vertexIdx;\r\n                            vertices.push_back(obs11);\r\n                            pixels.push_back(Eigen::Vector2i(x+1, y + 1));\r\n\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx1 == -1) {\r\n                            vIdx1 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx10] = vertexIdx;\r\n                            vertices.push_back(obs10);\r\n                            pixels.push_back(Eigen::Vector2i(x+1, y));\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx2 == -1) {\r\n                            vIdx2 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx01] = vertexIdx;\r\n                            vertices.push_back(obs01);\r\n                            pixels.push_back(Eigen::Vector2i(x, y+1));\r\n                            vertexIdx++;\r\n                        }\r\n\r\n                        faces.push_back(Eigen::Vector3i(vIdx0, vIdx1, vIdx2));\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        // Convert to numpy array.\r\n        int nVertices = vertices.size();\r\n        int nFaces = faces.size();\r\n\r\n        if (nVertices > 0 && nFaces > 0) {\r\n            // Reference check should be set to false otherwise there is a runtime\r\n            // error. Check why that is the case.\r\n            vertexPositions.resize({ nVertices, 3 }, false);\r\n            vertexPixels.resize({ nVertices, 2 }, false);\r\n            faceIndices.resize({ nFaces, 3 }, false);\r\n\r\n            for (int i = 0; i < nVertices; i++) {\r\n                *vertexPositions.mutable_data(i, 0) = vertices[i].x();\r\n                *vertexPositions.mutable_data(i, 1) = vertices[i].y();\r\n                *vertexPositions.mutable_data(i, 2) = vertices[i].z();\r\n\r\n                *vertexPixels.mutable_data(i, 0) = pixels[i].x();\r\n                *vertexPixels.mutable_data(i, 1) = pixels[i].y();\r\n            }\r\n            \r\n            for (int i = 0; i < nFaces; i++) {\r\n                *faceIndices.mutable_data(i, 0) = faces[i].x();\r\n                *faceIndices.mutable_data(i, 1) = faces[i].y();\r\n                *faceIndices.mutable_data(i, 2) = faces[i].z();\r\n            }\r\n        }\r\n    }\r\n\r\n    void compute_mesh_from_depth_and_color(\r\n        const py::array_t<float>& pointImage, const py::array_t<int>& colorImage, float maxTriangleEdgeDistance, \r\n        py::array_t<float>& vertexPositions, py::array_t<int>& vertexColors, py::array_t<int>& faceIndices\r\n    ) {\r\n        int width = pointImage.shape(2);\r\n        int height = pointImage.shape(1);\r\n\r\n        // Compute valid pixel vertices and faces.\r\n        // We also need to compute the pixel -> vertex index mapping for \r\n        // computation of faces.\r\n        // We connect neighboring pixels on the square into two triangles.\r\n        // We only select valid triangles, i.e. with all valid vertices and\r\n        // not too far apart.\r\n        // Important: The triangle orientation is set such that the normals\r\n        // point towards the camera.\r\n        std::vector<Eigen::Vector3f> vertices;\r\n        std::vector<Eigen::Vector3i> colors;\r\n        std::vector<Eigen::Vector3i> faces;\r\n\r\n        int vertexIdx = 0;\r\n        std::vector<int> mapPixelToVertexIdx(width * height, -1);\r\n\r\n        for (int y = 0; y < height - 1; y++) {\r\n            for (int x = 0; x < width - 1; x++) {\r\n                Eigen::Vector3f obs00(*pointImage.data(0, y, x), *pointImage.data(1, y, x), *pointImage.data(2, y, x));\r\n                Eigen::Vector3f obs01(*pointImage.data(0, y + 1, x), *pointImage.data(1, y + 1, x), *pointImage.data(2, y + 1, x));\r\n                Eigen::Vector3f obs10(*pointImage.data(0, y, x + 1), *pointImage.data(1, y, x + 1), *pointImage.data(2, y, x + 1));\r\n                Eigen::Vector3f obs11(*pointImage.data(0, y + 1, x + 1), *pointImage.data(1, y + 1, x + 1), *pointImage.data(2, y + 1, x + 1));\r\n\r\n                Eigen::Vector3i color00(*colorImage.data(0, y, x), *colorImage.data(1, y, x), *colorImage.data(2, y, x));\r\n                Eigen::Vector3i color01(*colorImage.data(0, y + 1, x), *colorImage.data(1, y + 1, x), *colorImage.data(2, y + 1, x));\r\n                Eigen::Vector3i color10(*colorImage.data(0, y, x + 1), *colorImage.data(1, y, x + 1), *colorImage.data(2, y, x + 1));\r\n                Eigen::Vector3i color11(*colorImage.data(0, y + 1, x + 1), *colorImage.data(1, y + 1, x + 1), *colorImage.data(2, y + 1, x + 1));\r\n\r\n                int idx00 = y * width + x;\r\n                int idx01 = (y + 1) * width + x;\r\n                int idx10 = y * width + (x + 1);\r\n                int idx11 = (y + 1) * width + (x + 1);\r\n\r\n                bool valid00 = obs00.z() > 0;\r\n                bool valid01 = obs01.z() > 0;\r\n                bool valid10 = obs10.z() > 0;\r\n                bool valid11 = obs11.z() > 0;\r\n\r\n                if (valid00 && valid01 && valid10) {\r\n                    float d0 = (obs00 - obs01).norm();\r\n                    float d1 = (obs00 - obs10).norm();\r\n                    float d2 = (obs01 - obs10).norm();\r\n                    \r\n                    if (d0 <= maxTriangleEdgeDistance && d1 <= maxTriangleEdgeDistance && d2 <= maxTriangleEdgeDistance) {\r\n                        int vIdx0 = mapPixelToVertexIdx[idx00];\r\n                        int vIdx1 = mapPixelToVertexIdx[idx01];\r\n                        int vIdx2 = mapPixelToVertexIdx[idx10];\r\n\r\n                        if (vIdx0 == -1) {\r\n                            vIdx0 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx00] = vertexIdx;\r\n                            vertices.push_back(obs00);\r\n                            colors.push_back(color00);\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx1 == -1) {\r\n                            vIdx1 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx01] = vertexIdx;\r\n                            vertices.push_back(obs01);\r\n                            colors.push_back(color01);\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx2 == -1) {\r\n                            vIdx2 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx10] = vertexIdx;\r\n                            vertices.push_back(obs10);\r\n                            colors.push_back(color10);\r\n                            vertexIdx++;\r\n                        }\r\n\r\n                        faces.push_back(Eigen::Vector3i(vIdx0, vIdx1, vIdx2));\r\n                    }\r\n                }\r\n\r\n                if (valid01 && valid10 && valid11) {\r\n                    float d0 = (obs10 - obs01).norm();\r\n                    float d1 = (obs10 - obs11).norm();\r\n                    float d2 = (obs01 - obs11).norm();\r\n\r\n                    if (d0 <= maxTriangleEdgeDistance && d1 <= maxTriangleEdgeDistance && d2 <= maxTriangleEdgeDistance) {\r\n                        int vIdx0 = mapPixelToVertexIdx[idx11];\r\n                        int vIdx1 = mapPixelToVertexIdx[idx10];\r\n                        int vIdx2 = mapPixelToVertexIdx[idx01];\r\n\r\n                        if (vIdx0 == -1) {\r\n                            vIdx0 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx11] = vertexIdx;\r\n                            vertices.push_back(obs11);\r\n                            colors.push_back(color11);\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx1 == -1) {\r\n                            vIdx1 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx10] = vertexIdx;\r\n                            vertices.push_back(obs10);\r\n                            colors.push_back(color10);\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx2 == -1) {\r\n                            vIdx2 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx01] = vertexIdx;\r\n                            vertices.push_back(obs01);\r\n                            colors.push_back(color01);\r\n                            vertexIdx++;\r\n                        }\r\n\r\n                        faces.push_back(Eigen::Vector3i(vIdx0, vIdx1, vIdx2));\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        // Convert to numpy array.\r\n        int nVertices = vertices.size();\r\n        int nFaces = faces.size();\r\n\r\n        if (nVertices > 0 && nFaces > 0) {\r\n            // Reference check should be set to false otherwise there is a runtime\r\n            // error. Check why that is the case.\r\n            vertexPositions.resize({ nVertices, 3 }, false);\r\n            vertexColors.resize({ nVertices, 3 }, false);\r\n            faceIndices.resize({ nFaces, 3 }, false);\r\n\r\n            for (int i = 0; i < nVertices; i++) {\r\n                *vertexPositions.mutable_data(i, 0) = vertices[i].x();\r\n                *vertexPositions.mutable_data(i, 1) = vertices[i].y();\r\n                *vertexPositions.mutable_data(i, 2) = vertices[i].z();\r\n\r\n                *vertexColors.mutable_data(i, 0) = colors[i].x();\r\n                *vertexColors.mutable_data(i, 1) = colors[i].y();\r\n                *vertexColors.mutable_data(i, 2) = colors[i].z();\r\n            }\r\n            \r\n            for (int i = 0; i < nFaces; i++) {\r\n                *faceIndices.mutable_data(i, 0) = faces[i].x();\r\n                *faceIndices.mutable_data(i, 1) = faces[i].y();\r\n                *faceIndices.mutable_data(i, 2) = faces[i].z();\r\n            }\r\n        }\r\n    }\r\n\r\n    void compute_mesh_from_depth_and_flow(\r\n        const py::array_t<float>& pointImage, const py::array_t<float>& flowImage, float maxTriangleEdgeDistance, \r\n        py::array_t<float>& vertexPositions, py::array_t<float>& vertexFlows, py::array_t<int>& vertexPixels, py::array_t<int>& faceIndices\r\n    ) {\r\n        int width = pointImage.shape(2);\r\n        int height = pointImage.shape(1);\r\n\r\n        // Compute valid pixel vertices and faces.\r\n        // We also need to compute the pixel -> vertex index mapping for \r\n        // computation of faces.\r\n        // We connect neighboring pixels on the square into two triangles.\r\n        // We only select valid triangles, i.e. with all valid vertices and\r\n        // not too far apart.\r\n        // Important: The triangle orientation is set such that the normals\r\n        // point towards the camera.\r\n        std::vector<Eigen::Vector3f> vertices;\r\n        std::vector<Eigen::Vector3f> flows;\r\n        std::vector<Eigen::Vector2i> pixels;\r\n        std::vector<Eigen::Vector3i> faces;\r\n\r\n        int vertexIdx = 0;\r\n        std::vector<int> mapPixelToVertexIdx(width * height, -1);\r\n\r\n        for (int y = 0; y < height - 1; y++) {\r\n            for (int x = 0; x < width - 1; x++) {\r\n                Eigen::Vector3f obs00(*pointImage.data(0, y, x), *pointImage.data(1, y, x), *pointImage.data(2, y, x));\r\n                Eigen::Vector3f obs01(*pointImage.data(0, y + 1, x), *pointImage.data(1, y + 1, x), *pointImage.data(2, y + 1, x));\r\n                Eigen::Vector3f obs10(*pointImage.data(0, y, x + 1), *pointImage.data(1, y, x + 1), *pointImage.data(2, y, x + 1));\r\n                Eigen::Vector3f obs11(*pointImage.data(0, y + 1, x + 1), *pointImage.data(1, y + 1, x + 1), *pointImage.data(2, y + 1, x + 1));\r\n\r\n                Eigen::Vector3f flow00(*flowImage.data(0, y, x), *flowImage.data(1, y, x), *flowImage.data(2, y, x));\r\n                Eigen::Vector3f flow01(*flowImage.data(0, y + 1, x), *flowImage.data(1, y + 1, x), *flowImage.data(2, y + 1, x));\r\n                Eigen::Vector3f flow10(*flowImage.data(0, y, x + 1), *flowImage.data(1, y, x + 1), *flowImage.data(2, y, x + 1));\r\n                Eigen::Vector3f flow11(*flowImage.data(0, y + 1, x + 1), *flowImage.data(1, y + 1, x + 1), *flowImage.data(2, y + 1, x + 1));\r\n\r\n                int idx00 = y * width + x;\r\n                int idx01 = (y + 1) * width + x;\r\n                int idx10 = y * width + (x + 1);\r\n                int idx11 = (y + 1) * width + (x + 1);\r\n\r\n                bool valid00 = obs00.z() > 0 && std::isfinite(flow00.x()) && std::isfinite(flow00.y()) && std::isfinite(flow00.z());\r\n                bool valid01 = obs01.z() > 0 && std::isfinite(flow01.x()) && std::isfinite(flow01.y()) && std::isfinite(flow01.z());\r\n                bool valid10 = obs10.z() > 0 && std::isfinite(flow10.x()) && std::isfinite(flow10.y()) && std::isfinite(flow10.z());\r\n                bool valid11 = obs11.z() > 0 && std::isfinite(flow11.x()) && std::isfinite(flow11.y()) && std::isfinite(flow11.z());\r\n\r\n                if (valid00 && valid01 && valid10) {\r\n                    float d0 = (obs00 - obs01).norm();\r\n                    float d1 = (obs00 - obs10).norm();\r\n                    float d2 = (obs01 - obs10).norm();\r\n                    \r\n                    if (d0 <= maxTriangleEdgeDistance && d1 <= maxTriangleEdgeDistance && d2 <= maxTriangleEdgeDistance) {\r\n                        int vIdx0 = mapPixelToVertexIdx[idx00];\r\n                        int vIdx1 = mapPixelToVertexIdx[idx01];\r\n                        int vIdx2 = mapPixelToVertexIdx[idx10];\r\n\r\n                        if (vIdx0 == -1) {\r\n                            vIdx0 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx00] = vertexIdx;\r\n                            vertices.push_back(obs00);\r\n                            flows.push_back(flow00);\r\n                            pixels.push_back(Eigen::Vector2i(x, y));\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx1 == -1) {\r\n                            vIdx1 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx01] = vertexIdx;\r\n                            vertices.push_back(obs01);\r\n                            flows.push_back(flow01);\r\n                            pixels.push_back(Eigen::Vector2i(x, y + 1));\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx2 == -1) {\r\n                            vIdx2 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx10] = vertexIdx;\r\n                            vertices.push_back(obs10);\r\n                            flows.push_back(flow10);\r\n                            pixels.push_back(Eigen::Vector2i(x + 1, y));\r\n                            vertexIdx++;\r\n                        }\r\n\r\n                        faces.push_back(Eigen::Vector3i(vIdx0, vIdx1, vIdx2));\r\n                    }\r\n                }\r\n\r\n                if (valid01 && valid10 && valid11) {\r\n                    float d0 = (obs10 - obs01).norm();\r\n                    float d1 = (obs10 - obs11).norm();\r\n                    float d2 = (obs01 - obs11).norm();\r\n\r\n                    if (d0 <= maxTriangleEdgeDistance && d1 <= maxTriangleEdgeDistance && d2 <= maxTriangleEdgeDistance) {\r\n                        int vIdx0 = mapPixelToVertexIdx[idx11];\r\n                        int vIdx1 = mapPixelToVertexIdx[idx10];\r\n                        int vIdx2 = mapPixelToVertexIdx[idx01];\r\n\r\n                        if (vIdx0 == -1) {\r\n                            vIdx0 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx11] = vertexIdx;\r\n                            vertices.push_back(obs11);\r\n                            flows.push_back(flow11);\r\n                            pixels.push_back(Eigen::Vector2i(x + 1, y + 1));\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx1 == -1) {\r\n                            vIdx1 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx10] = vertexIdx;\r\n                            vertices.push_back(obs10);\r\n                            flows.push_back(flow10);\r\n                            pixels.push_back(Eigen::Vector2i(x + 1, y));\r\n                            vertexIdx++;\r\n                        }\r\n                        if (vIdx2 == -1) {\r\n                            vIdx2 = vertexIdx;\r\n                            mapPixelToVertexIdx[idx01] = vertexIdx;\r\n                            vertices.push_back(obs01);\r\n                            flows.push_back(flow01);\r\n                            pixels.push_back(Eigen::Vector2i(x, y + 1));\r\n                            vertexIdx++;\r\n                        }\r\n\r\n                        faces.push_back(Eigen::Vector3i(vIdx0, vIdx1, vIdx2));\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        // Convert to numpy array.\r\n        int nVertices = vertices.size();\r\n        int nFaces = faces.size();\r\n\r\n        if (nVertices > 0 && nFaces > 0) {\r\n            // Reference check should be set to false otherwise there is a runtime\r\n            // error. Check why that is the case.\r\n            vertexPositions.resize({ nVertices, 3 }, false);\r\n            vertexFlows.resize({ nVertices, 3 }, false);\r\n            vertexPixels.resize({ nVertices, 2 }, false);\r\n            faceIndices.resize({ nFaces, 3 }, false);\r\n\r\n            for (int i = 0; i < nVertices; i++) {\r\n                *vertexPositions.mutable_data(i, 0) = vertices[i].x();\r\n                *vertexPositions.mutable_data(i, 1) = vertices[i].y();\r\n                *vertexPositions.mutable_data(i, 2) = vertices[i].z();\r\n\r\n                *vertexFlows.mutable_data(i, 0) = flows[i].x();\r\n                *vertexFlows.mutable_data(i, 1) = flows[i].y();\r\n                *vertexFlows.mutable_data(i, 2) = flows[i].z();\r\n\r\n                *vertexPixels.mutable_data(i, 0) = pixels[i].x();\r\n                *vertexPixels.mutable_data(i, 1) = pixels[i].y();\r\n            }\r\n            \r\n            for (int i = 0; i < nFaces; i++) {\r\n                *faceIndices.mutable_data(i, 0) = faces[i].x();\r\n                *faceIndices.mutable_data(i, 1) = faces[i].y();\r\n                *faceIndices.mutable_data(i, 2) = faces[i].z();\r\n            }\r\n        }\r\n    }\r\n\r\n    void filter_depth(py::array_t<unsigned short>& in, py::array_t<unsigned short>& out, int radius) {\r\n        assert(in.ndim() == 2);\r\n        assert(out.ndim() == 2);\r\n        \r\n        unsigned kernelSize = 2 * radius + 1;\r\n        unsigned windowSize = kernelSize * kernelSize;\r\n\r\n        int width = in.shape(1);\r\n        int height = in.shape(0);\r\n        assert(out.shape(0) == height);\r\n        assert(out.shape(1) == width);\r\n\r\n        // #pragma omp parallel for\r\n        for (int y = 0; y < height; y++) {\r\n            for (int x = 0; x < width; x++) {\r\n                // Get all values in the median window.\r\n                int xMin = std::max(x - radius, 0);\r\n                int xMax = std::min(x + radius, int(width) - 1);\r\n                int yMin = std::max(y - radius, 0);\r\n                int yMax = std::min(y + radius, int(height) - 1);\r\n\r\n                std::vector<unsigned short> windowValues;\r\n                windowValues.reserve(windowSize);\r\n\r\n                for (int yNear = yMin; yNear <= yMax; yNear++) {\r\n                    for (int xNear = xMin; xNear <= xMax; xNear++) {\r\n                        unsigned short depth = *in.data(yNear, xNear);\r\n                        if (depth > 0) {\r\n                            windowValues.push_back(depth);\r\n                        }\r\n                    }\r\n                }\r\n\r\n                // Sort the values and pick the median as the middle element.\r\n                unsigned nElements = windowValues.size();\r\n                std::sort(windowValues.begin(), windowValues.end());\r\n\r\n                unsigned middleIdx = std::floor(nElements / 2);\r\n                unsigned short median = windowValues[middleIdx];\r\n\r\n                // Write out the median value.\r\n                *out.mutable_data(y, x) = median;\r\n            }\r\n        }\r\n    }\r\n\r\n    py::array_t<float> warp_flow(const py::array_t<float>& image, const py::array_t<float>& flow, const py::array_t<float>& mask) {\r\n        // We assume:\r\n        //      image shape (3, h, w)\r\n        //      flow shape  (2, h, w)\r\n        //      mask shape  (2, h, w)\r\n\r\n        int width = image.shape(2);\r\n        int height = image.shape(1);\r\n\r\n        py::array_t<float> imageWarped = py::array_t<float>({3, height, width});\r\n        py::array_t<float> weightsWarped = py::array_t<float>({1, height, width});\r\n\r\n        // Initialize to zero.\r\n        for (int v = 0; v < height; v++) {\r\n            for (int u = 0; u < width; u++) {\r\n                *imageWarped.mutable_data(0, v, u) = 0.0;\r\n                *imageWarped.mutable_data(1, v, u) = 0.0;\r\n                *imageWarped.mutable_data(2, v, u) = 0.0;\r\n                *weightsWarped.mutable_data(0, v, u) = 0.0;\r\n            }\r\n        }\r\n\r\n        // Compute image values and interpolation weights.\r\n        for (int v = 0; v < height; v++) {\r\n            for (int u = 0; u < width; u++) {\r\n                // Check if pixel is inside the mask.\r\n                if (*mask.data(0, v, u) <= 0 || *mask.data(1, v, u) <= 0) continue;\r\n\r\n                // Compute the warped pixel.\r\n                float u_warped = u + *flow.data(0, v, u);\r\n                float v_warped = v + *flow.data(1, v, u);\r\n\r\n                int u0 = std::floor(u_warped);\r\n                int u1 = u0 + 1;\r\n                int v0 = std::floor(v_warped);\r\n                int v1 = v0 + 1;\r\n\r\n                if (u0 < 0 || u1 >= width || v0 < 0 || v1 >= height) continue;\r\n\r\n                // Interpolate the color contributions.\r\n                float du = u_warped - u0;\r\n                float dv = v_warped - v0;\r\n                \r\n                float w00 = (1 - du)*(1 - dv);\r\n                float w01 = (1 - du)*dv;\r\n                float w10 = du*(1 - dv);\r\n                float w11 = du*dv;\r\n\r\n                float c0 = *image.data(0, v, u); \r\n                float c1 = *image.data(1, v, u); \r\n                float c2 = *image.data(2, v, u); \r\n\r\n                *imageWarped.mutable_data(0, v0, u0) += w00 * c0;\r\n                *imageWarped.mutable_data(1, v0, u0) += w00 * c1;\r\n                *imageWarped.mutable_data(2, v0, u0) += w00 * c2;\r\n                *imageWarped.mutable_data(0, v1, u0) += w01 * c0;\r\n                *imageWarped.mutable_data(1, v1, u0) += w01 * c1;\r\n                *imageWarped.mutable_data(2, v1, u0) += w01 * c2;\r\n                *imageWarped.mutable_data(0, v0, u1) += w10 * c0;\r\n                *imageWarped.mutable_data(1, v0, u1) += w10 * c1;\r\n                *imageWarped.mutable_data(2, v0, u1) += w10 * c2;\r\n                *imageWarped.mutable_data(0, v1, u1) += w11 * c0;\r\n                *imageWarped.mutable_data(1, v1, u1) += w11 * c1;\r\n                *imageWarped.mutable_data(2, v1, u1) += w11 * c2;\r\n                \r\n                *weightsWarped.mutable_data(0, v0, u0) += w00;\r\n                *weightsWarped.mutable_data(0, v1, u0) += w01;\r\n                *weightsWarped.mutable_data(0, v0, u1) += w10;\r\n                *weightsWarped.mutable_data(0, v1, u1) += w11;\r\n            }\r\n        }\r\n\r\n        // Normalize image.\r\n        for (int v = 0; v < height; v++) {\r\n            for (int u = 0; u < width; u++) {\r\n                float w = *weightsWarped.data(0, v, u);\r\n                if (w > 0) {\r\n                    *imageWarped.mutable_data(0, v, u) /= w;\r\n                    *imageWarped.mutable_data(1, v, u) /= w;\r\n                    *imageWarped.mutable_data(2, v, u) /= w;\r\n                }\r\n                else {\r\n                    *imageWarped.mutable_data(0, v, u) = 1.0;\r\n                    *imageWarped.mutable_data(1, v, u) = 1.0;\r\n                    *imageWarped.mutable_data(2, v, u) = 1.0;\r\n                }\r\n            }\r\n        }\r\n\r\n        return imageWarped;\r\n    }\r\n\r\n    py::array_t<float> warp_rigid(\r\n        const py::array_t<float>& rgbd, \r\n        const py::array_t<float>& rotation, \r\n        const py::array_t<float>& translation, \r\n        float fx, float fy, float cx, float cy\r\n    ) { \r\n        // We assume:\r\n        //      rgbd shape (6, h, w)\r\n        //      rotation shape  (9)\r\n        //      translation shape  (2)\r\n\r\n        int width = rgbd.shape(2);\r\n        int height = rgbd.shape(1);\r\n\r\n        float r00 = *rotation.data(0);\r\n        float r01 = *rotation.data(1);\r\n        float r02 = *rotation.data(2);\r\n        float r10 = *rotation.data(3);\r\n        float r11 = *rotation.data(4);\r\n        float r12 = *rotation.data(5);\r\n        float r20 = *rotation.data(6);\r\n        float r21 = *rotation.data(7);\r\n        float r22 = *rotation.data(8);\r\n        float t0 = *translation.data(0);\r\n        float t1 = *translation.data(1);\r\n        float t2 = *translation.data(2);\r\n\r\n        py::array_t<float> imageWarped = py::array_t<float>({3, height, width});\r\n        py::array_t<float> weightsWarped = py::array_t<float>({1, height, width});\r\n\r\n        // Initialize to zero.\r\n        for (int v = 0; v < height; v++) {\r\n            for (int u = 0; u < width; u++) {\r\n                *imageWarped.mutable_data(0, v, u) = 0.0;\r\n                *imageWarped.mutable_data(1, v, u) = 0.0;\r\n                *imageWarped.mutable_data(2, v, u) = 0.0;\r\n                *weightsWarped.mutable_data(0, v, u) = 0.0;\r\n            }\r\n        }\r\n\r\n        // Compute image values and interpolation weights.\r\n        for (int v = 0; v < height; v++) {\r\n            for (int u = 0; u < width; u++) {\r\n                // Compute the warped pixel.\r\n                float x = *rgbd.data(3, v, u);\r\n                float y = *rgbd.data(4, v, u);\r\n                float z = *rgbd.data(5, v, u);\r\n                if (z <= 0) continue;\r\n\r\n                float x_def = r00 * x + r01 * y + r02 * z + t0;\r\n                float y_def = r10 * x + r11 * y + r12 * z + t1;\r\n                float z_def = r20 * x + r21 * y + r22 * z + t2;\r\n                if (z_def <= 0) continue;\r\n\r\n                float u_warped = fx * x_def / z_def + cx;\r\n                float v_warped = fy * y_def / z_def + cy;\r\n\r\n                int u0 = std::floor(u_warped);\r\n                int u1 = u0 + 1;\r\n                int v0 = std::floor(v_warped);\r\n                int v1 = v0 + 1;\r\n\r\n                if (u0 < 0 || u1 >= width || v0 < 0 || v1 >= height) continue;\r\n\r\n                // Interpolate the color contributions.\r\n                float du = u_warped - u0;\r\n                float dv = v_warped - v0;\r\n                \r\n                float w00 = (1 - du)*(1 - dv);\r\n                float w01 = (1 - du)*dv;\r\n                float w10 = du*(1 - dv);\r\n                float w11 = du*dv;\r\n\r\n                float c0 = *rgbd.data(0, v, u); \r\n                float c1 = *rgbd.data(1, v, u); \r\n                float c2 = *rgbd.data(2, v, u); \r\n\r\n                *imageWarped.mutable_data(0, v0, u0) += w00 * c0;\r\n                *imageWarped.mutable_data(1, v0, u0) += w00 * c1;\r\n                *imageWarped.mutable_data(2, v0, u0) += w00 * c2;\r\n                *imageWarped.mutable_data(0, v1, u0) += w01 * c0;\r\n                *imageWarped.mutable_data(1, v1, u0) += w01 * c1;\r\n                *imageWarped.mutable_data(2, v1, u0) += w01 * c2;\r\n                *imageWarped.mutable_data(0, v0, u1) += w10 * c0;\r\n                *imageWarped.mutable_data(1, v0, u1) += w10 * c1;\r\n                *imageWarped.mutable_data(2, v0, u1) += w10 * c2;\r\n                *imageWarped.mutable_data(0, v1, u1) += w11 * c0;\r\n                *imageWarped.mutable_data(1, v1, u1) += w11 * c1;\r\n                *imageWarped.mutable_data(2, v1, u1) += w11 * c2;\r\n                \r\n                *weightsWarped.mutable_data(0, v0, u0) += w00;\r\n                *weightsWarped.mutable_data(0, v1, u0) += w01;\r\n                *weightsWarped.mutable_data(0, v0, u1) += w10;\r\n                *weightsWarped.mutable_data(0, v1, u1) += w11;\r\n            }\r\n        }\r\n\r\n        // Normalize image.\r\n        for (int v = 0; v < height; v++) {\r\n            for (int u = 0; u < width; u++) {\r\n                float w = *weightsWarped.data(0, v, u);\r\n                if (w > 0) {\r\n                    *imageWarped.mutable_data(0, v, u) /= w;\r\n                    *imageWarped.mutable_data(1, v, u) /= w;\r\n                    *imageWarped.mutable_data(2, v, u) /= w;\r\n                }\r\n                else {\r\n                    *imageWarped.mutable_data(0, v, u) = 1.0;\r\n                    *imageWarped.mutable_data(1, v, u) = 1.0;\r\n                    *imageWarped.mutable_data(2, v, u) = 1.0;\r\n                }\r\n            }\r\n        }\r\n\r\n        return imageWarped;\r\n    }\r\n\r\n    py::array_t<float> warp_3d(const py::array_t<float>& rgbd, const py::array_t<float>& points, const py::array_t<int>& pointValidity, float fx, float fy, float cx, float cy) {\r\n        // We assume:\r\n        //      image shape             (6, h, w)\r\n        //      points shape            (3, h, w)\r\n        //      pointValidity shape     (h, w)\r\n\r\n        int width = rgbd.shape(2);\r\n        int height = rgbd.shape(1);\r\n\r\n        py::array_t<float> imageWarped = py::array_t<float>({3, height, width});\r\n        py::array_t<float> weightsWarped = py::array_t<float>({1, height, width});\r\n\r\n        // Initialize to zero.\r\n        for (int v = 0; v < height; v++) {\r\n            for (int u = 0; u < width; u++) {\r\n                *imageWarped.mutable_data(0, v, u) = 0.0;\r\n                *imageWarped.mutable_data(1, v, u) = 0.0;\r\n                *imageWarped.mutable_data(2, v, u) = 0.0;\r\n                *weightsWarped.mutable_data(0, v, u) = 0.0;\r\n            }\r\n        }\r\n\r\n        // Compute image values and interpolation weights.\r\n        for (int v = 0; v < height; v++) {\r\n            for (int u = 0; u < width; u++) {\r\n                // Compute the warped pixel.\r\n                if (*pointValidity.data(v, u) <= 0) continue;\r\n\r\n                float z = *rgbd.data(5, v, u);\r\n                if (z <= 0) continue;\r\n\r\n                float x_def = *points.data(0, v, u);\r\n                float y_def = *points.data(1, v, u);\r\n                float z_def = *points.data(2, v, u);\r\n                if (z_def <= 0) continue;\r\n\r\n                float u_warped = fx * x_def / z_def + cx;\r\n                float v_warped = fy * y_def / z_def + cy;\r\n\r\n                int u0 = std::floor(u_warped);\r\n                int u1 = u0 + 1;\r\n                int v0 = std::floor(v_warped);\r\n                int v1 = v0 + 1;\r\n\r\n                if (u0 < 0 || u1 >= width || v0 < 0 || v1 >= height) continue;\r\n\r\n                // Interpolate the color contributions.\r\n                float du = u_warped - u0;\r\n                float dv = v_warped - v0;\r\n                \r\n                float w00 = (1 - du)*(1 - dv);\r\n                float w01 = (1 - du)*dv;\r\n                float w10 = du*(1 - dv);\r\n                float w11 = du*dv;\r\n\r\n                float c0 = *rgbd.data(0, v, u); \r\n                float c1 = *rgbd.data(1, v, u); \r\n                float c2 = *rgbd.data(2, v, u); \r\n\r\n                *imageWarped.mutable_data(0, v0, u0) += w00 * c0;\r\n                *imageWarped.mutable_data(1, v0, u0) += w00 * c1;\r\n                *imageWarped.mutable_data(2, v0, u0) += w00 * c2;\r\n                *imageWarped.mutable_data(0, v1, u0) += w01 * c0;\r\n                *imageWarped.mutable_data(1, v1, u0) += w01 * c1;\r\n                *imageWarped.mutable_data(2, v1, u0) += w01 * c2;\r\n                *imageWarped.mutable_data(0, v0, u1) += w10 * c0;\r\n                *imageWarped.mutable_data(1, v0, u1) += w10 * c1;\r\n                *imageWarped.mutable_data(2, v0, u1) += w10 * c2;\r\n                *imageWarped.mutable_data(0, v1, u1) += w11 * c0;\r\n                *imageWarped.mutable_data(1, v1, u1) += w11 * c1;\r\n                *imageWarped.mutable_data(2, v1, u1) += w11 * c2;\r\n                \r\n                *weightsWarped.mutable_data(0, v0, u0) += w00;\r\n                *weightsWarped.mutable_data(0, v1, u0) += w01;\r\n                *weightsWarped.mutable_data(0, v0, u1) += w10;\r\n                *weightsWarped.mutable_data(0, v1, u1) += w11;\r\n            }\r\n        }\r\n\r\n        // Normalize image.\r\n        for (int v = 0; v < height; v++) {\r\n            for (int u = 0; u < width; u++) {\r\n                float w = *weightsWarped.data(0, v, u);\r\n                if (w > 0) {\r\n                    *imageWarped.mutable_data(0, v, u) /= w;\r\n                    *imageWarped.mutable_data(1, v, u) /= w;\r\n                    *imageWarped.mutable_data(2, v, u) /= w;\r\n                }\r\n                else {\r\n                    *imageWarped.mutable_data(0, v, u) = 1.0;\r\n                    *imageWarped.mutable_data(1, v, u) = 1.0;\r\n                    *imageWarped.mutable_data(2, v, u) = 1.0;\r\n                }\r\n            }\r\n        }\r\n\r\n        return imageWarped;\r\n    }\r\n\r\n} //namespace image_proc", "meta": {"hexsha": "fdbe8e3f3ee8e03d4f14aa3a155055e4479c8b18", "size": 52926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "csrc/cpu/image_proc.cpp", "max_stars_repo_name": "shubhMaheshwari/NeuralTracking", "max_stars_repo_head_hexsha": "c47c2e0b0f1a654e3e53fabaa898b3b8a2649381", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-18T07:11:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T07:11:18.000Z", "max_issues_repo_path": "csrc/cpu/image_proc.cpp", "max_issues_repo_name": "shubhMaheshwari/NeuralTracking", "max_issues_repo_head_hexsha": "c47c2e0b0f1a654e3e53fabaa898b3b8a2649381", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2022-03-08T07:00:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T07:07:29.000Z", "max_forks_repo_path": "csrc/cpu/image_proc.cpp", "max_forks_repo_name": "shubhMaheshwari/NeuralTracking", "max_forks_repo_head_hexsha": "c47c2e0b0f1a654e3e53fabaa898b3b8a2649381", "max_forks_repo_licenses": ["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.8492129246, "max_line_length": 178, "alphanum_fraction": 0.4360238824, "num_tokens": 13197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.591179650948877}}
{"text": "#include \"HybridBot.cpp\"\n#include \"SweepBot.cpp\"\n#include <kilosim/World.h>\n#include <kilosim/Viewer.h>\n#include <kilosim/ConfigParser.h>\n#include <kilosim/Logger.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n#include <unistd.h>\n\n// using Eigen::MatrixXd;\n\n// AGGREGATORS\n\nstd::vector<double> network_eigenvals(std::vector<Kilosim::Robot *> &robots)\n{\n    // Get the eigenvalues of the Laplacian of the robot network/communication graph for this:\n    // https://en.wikipedia.org/wiki/Algebraic_connectivity\n\n    // L = D - A\n    // D is the diagonal matrix of the degree matrix\n    // A is the adjacency matrix of the robot network\n    // L_{i,j} = ...\n    // deg(v_i) if v_i == v_j\n    // -1       if v_i != v_j and v_i is connected to v_j\n    // 0        otherwise\n\n    // Get the IDs of all robots\n    std::vector<int> robot_ids(robots.size());\n    for (int i = 0; i < robots.size(); i++)\n    {\n        robot_ids[i] = robots[i]->id;\n    }\n    // Initialize a 2D matrix with the number of robots\n    Eigen::MatrixXd connectivity_matrix = Eigen::MatrixXd::Zero(robots.size(), robots.size());\n    for (int i = 0; i < robots.size(); i++)\n    {\n        // From each robot, get a list of the neighbors it has heard from on this tick\n        Kilosim::BaseBot *bot = (Kilosim::BaseBot *)robots[i];\n        std::vector<int> neighbor_ids = bot->get_neighbors();\n        // Convert the map to a vector, sorted by neighbor ID (include self as 1!)\n        // All neighbors not heard from are 0; all neighbors heard from are 1\n        // std::vector<int> network_row(robots.size(), 0);\n        for (int j = 0; j < neighbor_ids.size(); j++)\n        {\n            // Find the index of the neighbor in the list of robot IDs\n            // (row order must match column order)\n            auto iter = std::find(robot_ids.begin(), robot_ids.end(), neighbor_ids[j]);\n            int neighbor_id_ind = iter - robot_ids.begin();\n            connectivity_matrix(i, neighbor_id_ind) = -1;\n        }\n        connectivity_matrix(i, i) = bot->neighbor_count;\n    }\n    // Compute the eigenvalues of the matrix\n    Eigen::VectorXcd eivals = connectivity_matrix.eigenvalues();\n    // // Convert the eigenvalues to an std::vector for returning\n    // Convert all eigenvalues to real numbers. Those with an imaginary part are converted to nan\n    std::vector<double> ei_real(eivals.size());\n    for (int i = 0; i < ei_real.size(); i++)\n    {\n        if (eivals[i].imag() == 0)\n        {\n            ei_real[i] = eivals[i].real();\n        }\n        else\n        {\n            ei_real[i] = std::nan(\"\");\n        }\n    }\n    return ei_real;\n}\n\nstd::vector<double> decision_states(std::vector<Kilosim::Robot *> &robots)\n{\n    // Get the current state of the robots' decisions. (undecided, self decided, all decided)\n    // This is represented by the robot's m_state\n    std::vector<double> decision_states(robots.size());\n    for (auto i = 0ul; i < robots.size(); i++)\n    {\n        Kilosim::BaseBot *bot = (Kilosim::BaseBot *)robots[i];\n        decision_states[i] = bot->get_state();\n    }\n    return decision_states;\n}\n\nstd::vector<double> has_decided_count(std::vector<Kilosim::Robot *> &robots)\n{\n    // Count how many robots have made a decision (ie, found value <= threshold)\n    double decided_count = 0;\n    for (auto i = 0ul; i < robots.size(); i++)\n    {\n        Kilosim::BaseBot *bot = (Kilosim::BaseBot *)robots[i];\n        if (bot->has_decided())\n        {\n            decided_count++;\n        }\n    }\n    return std::vector<double>{decided_count};\n}\n\nstd::vector<double> neighbor_count(std::vector<Kilosim::Robot *> &robots)\n{\n    // Get the number of neighbors each robot has heard from on this tick\n    std::vector<double> neighbor_count(robots.size());\n    for (auto i = 0ul; i < robots.size(); i++)\n    {\n        Kilosim::BaseBot *bot = (Kilosim::BaseBot *)robots[i];\n        neighbor_count[i] = bot->neighbor_count;\n    }\n    return neighbor_count;\n}\n\nstd::vector<double> robot_coverage(std::vector<Kilosim::Robot *> &robots)\n{\n    // Get the total number of cells covered by each robot.\n    // This includes the number of cells covered by the robot's sensors, not where the robot walked.\n    // It also doesn't account for duplicates (ie, if a robot is in a cell twice, it will only count once).\n    std::vector<double> coverage(robots.size());\n    int i = 0;\n    for (auto &robot : robots)\n    {\n        Kilosim::BaseBot *bot = (Kilosim::BaseBot *)robot;\n        coverage[i] = bot->map_coverage_count();\n        i++;\n    }\n    return coverage;\n}\n\nstd::vector<double> robot_distance(std::vector<Kilosim::Robot *> &robots)\n{\n    // Get the distance each robot has traveled.\n    // This is the number of cells the robot has walked, not the number of cells covered by the robot's sensors.\n    std::vector<double> distances(robots.size());\n    for (auto i = 0ul; i < robots.size(); i++)\n    {\n        Kilosim::BaseBot *bb = (Kilosim::BaseBot *)robots[i];\n        distances[i] = bb->map_visited_count();\n    }\n    return distances;\n}\n\nstd::vector<double> collective_coverage(std::vector<Kilosim::Robot *> &robots)\n{\n    // Add up how much of the map the robots have observed (over all robots).\n    // This is very time-intensive -- AT LEAST O(nwh) (n=num_robots, w=width, h=height)\n    // Probably most useful to only call at the end to check how much was covered\n    std::vector<std::vector<int>> collective_map;\n    for (auto i = 0ul; i < robots.size(); i++)\n    {\n        Kilosim::BaseBot *bb = (Kilosim::BaseBot *)robots[i];\n        std::vector<std::vector<int>> map = bb->get_map();\n        // On the first go, resize the map to match the robot's map and fill with 0\n        if (i == 0)\n        {\n            collective_map.resize(map.size(), std::vector<int>(map[0].size(), 0));\n            // m_map.resize(m_arena_grid_height, std::vector<int>(m_arena_grid_width, -1))\n        }\n        // Add the robot's map to the collective map\n        for (auto j = 0ul; j < map.size(); j++)\n        {\n            for (auto k = 0ul; k < map[j].size(); k++)\n            {\n                if (map[j][k] != -1)\n                {\n                    // Only add 1 if the cell was observed\n                    collective_map[j][k] += std::min(1, map[j][k]);\n                    collective_map[j][k] = 1;\n                }\n            }\n        }\n    }\n    // Add up the collective map to get the total number of cells covered\n    double total_coverage = 0;\n    for (auto j = 0ul; j < collective_map.size(); j++)\n    {\n        for (auto k = 0ul; k < collective_map[j].size(); k++)\n        {\n            total_coverage += collective_map[j][k];\n        }\n    }\n    return std::vector<double>{total_coverage};\n}\n\n// -------------------------------------------------------------------------------------------------\n\nbool all_robots_home(std::vector<Kilosim::HybridBot *> robots)\n{\n    for (auto robot : robots)\n    {\n        if (!robot->is_home())\n        {\n            // At least one robot is not home (ie finished)\n            return false;\n        }\n    }\n    return true;\n}\n\n// Check if all of the robots in the world are finished\n// (either they all found the source and returned home, or the time limit expired)\nbool is_finished(Kilosim::World &world, std::vector<Kilosim::HybridBot *> robots, std::string end_condition, int end_val)\n{\n    if (end_condition == \"time\")\n    {\n        // Either time is up OR all of the robots are home (done)\n        return (world.get_time() * world.get_tick_rate() >= end_val) || all_robots_home(robots);\n    }\n    else if (end_condition == \"value\")\n    {\n        return all_robots_home(robots);\n    }\n    else if (end_condition == \"first_find\")\n    {\n        for (auto robot : robots)\n        {\n            // Robot is finished if it found a target below threshold\n            if (robot->is_finished())\n            {\n                return true;\n            }\n        }\n        // There are no robots finished\n        return false;\n    }\n    // Else no robots that *didn't* meet the end condition\n    return true;\n}\n\nbool all_robots_home(std::vector<Kilosim::SweepBot *> &robots)\n{\n    // Check if all robots have returned to the origin\n    for (auto robot : robots)\n    {\n        if (!robot->is_home())\n        {\n            // At least one robot is not home (ie finished)\n            return false;\n        }\n    }\n    return true;\n}\n\nbool is_finished(Kilosim::World &world, std::vector<Kilosim::SweepBot *> robots, std::string end_condition, int end_val)\n{\n    // HACKY: This is just a copy of the HybridBot version\n    if (end_condition == \"time\")\n    {\n        return world.get_time() * world.get_tick_rate() >= end_val || all_robots_home(robots);\n    }\n    else if (end_condition == \"value\")\n    {\n        return all_robots_home(robots);\n    }\n    // Else no robots that *didn't* meet the end condition\n    return true;\n}\n\nvoid print_pos_vec(std::vector<Pos> pos_vec)\n{\n    for (auto pos : pos_vec)\n    {\n        std::cout << pos.x << \", \" << pos.y << std::endl;\n    }\n}\n\nstd::vector<std::vector<Pos>> compute_sweep_paths(int arena_width, int arena_height, int num_robots)\n{\n    // Compute the predetermined sweep paths for the robots to follow\n    std::vector<std::vector<Pos>> paths;\n    for (int i = 0; i < num_robots; i++)\n    {\n        Pos start_pos = {0, 0};\n        int x_max = arena_width - i * 3 - 1;\n        int x_min = num_robots * 3 - i * 3 - 2;\n        int y_move_r = (num_robots * 3 - i * 3) * 2 - 3;\n        int y_move_l = (i * 3) * 2 + 3;\n        int x = 0;\n        int y = i * 3 + 1;\n        std::vector<Pos> path = {start_pos};\n\n        // Start by going from the origin to the starting position along the left side\n        // To get everyone lined up takes a fixed time dependent on the number of robots\n        // Then subtract off the number of ticks it takes for a robot to get to its OWN start pos.\n        // time_to_lineup = num_robots * 3 - 1  # Should be -2, but we're accounting for origin @ t=0\n        int next_y = start_pos.y;\n        int next_x = start_pos.x;\n        while (path.back() != Pos({x, y}))\n        {\n            if (x > next_x)\n            {\n                next_x += 1;\n            }\n            next_y += 1;\n            path.push_back({next_x, next_y});\n        }\n\n        // Go until hitting the bottom\n        while (path.back().y < arena_height)\n        {\n            // x right\n            if ((y >= arena_height - y_move_r && arena_height / num_robots % 2 == 1) || num_robots >= arena_width / 3)\n            {\n                // Last row-set of an odd number or multiples of number of robots\n                for (int x_ = 0; x_ < arena_width - 1; x_++)\n                {\n                    path.push_back({x_, y});\n                }\n                break;\n            }\n            else\n            {\n                for (int x_ = x + 1; x_ < x_max; x_++)\n                {\n                    path.push_back({x_, y});\n                }\n                x = x_max - 1;\n                // down (right)\n                for (int y_ = y + 1; y_ < y_move_r + y; y_++)\n                {\n                    path.push_back({x, y_});\n                }\n                y = y + y_move_r;\n                // x left\n                for (int x_ = x_max - 1; x_ > x_min - 1; x_--)\n                {\n                    path.push_back({x_, y});\n                }\n                x = x_min;\n                // down (left)\n                for (int y_ = y + 1; y_ < y_move_l + y; y_++)\n                {\n                    path.push_back({x, y_});\n                }\n                y = y + y_move_l;\n                // ... repeat\n            }\n        }\n        // Filter out points outside of the arena\n        path.erase(std::remove_if(path.begin(), path.end(), [&](Pos p)\n                                  { return p.x < 0 || p.x >= arena_width || p.y < 0 || p.y >= arena_height; }),\n                   path.end());\n        std::reverse(path.begin(), path.end());\n        paths.push_back(path);\n    }\n    return paths;\n}\n\nvoid hybrid_sim(Kilosim::World &world, Kilosim::Logger &logger, Kilosim::ConfigParser &config)\n{\n\n    int num_robots = config.get(\"num_robots\");\n    std::string end_condition = config.get(\"end_condition\");\n    int end_val;\n    try\n    {\n        end_val = config.get(\"end_val\");\n    }\n    catch (std::invalid_argument &e)\n    {\n        if (end_condition == \"value\")\n        {\n            end_val = config.get(\"end_condition_params\").at(\"value\").at(\"end_val\");\n        }\n        else if (end_condition == \"time\")\n        {\n            end_val = config.get(\"end_condition_params\").at(\"time\").at(\"end_val\");\n        }\n        logger.log_param(\"end_val\", end_val);\n    }\n    int target_val = config.get(\"target_val\");\n\n    unsigned long int max_duration = config.get(\"max_trial_duration\");\n\n    // This accounts for possibility of different ways of doing weights\n    double pso_self_weight;\n    double pso_group_weight;\n    try\n    {\n        // Try to use the same weight for own/others' observations\n        pso_self_weight = config.get(\"pso_weights\");\n        pso_group_weight = config.get(\"pso_weights\");\n    }\n    catch (std::exception &e)\n    {\n        // Use different weights for own/others' observations\n        pso_self_weight = config.get(\"pso_self_weight\");\n        pso_group_weight = config.get(\"pso_group_weight\");\n    }\n\n    std::vector<Kilosim::HybridBot *> robots(num_robots);\n    for (int n = 0; n < num_robots; n++)\n    {\n        robots[n] = new Kilosim::HybridBot();\n        world.add_robot(robots[n]);\n        robots[n]->robot_init(0, 0, 0);\n        robots[n]->max_speed = config.get(\"max_speed\");\n        // PSO/GD hybrid pre-decision movement\n        robots[n]->pso_step_interval = config.get(\"pso_step_interval\");\n        robots[n]->is_pso_step_interval_constant = config.get(\"is_pso_step_interval_constant\", true);\n        robots[n]->pso_self_weight = pso_self_weight;\n        robots[n]->pso_group_weight = pso_group_weight;\n        // This is only used with the old init method. It's left here for legacy reasons.\n        // (Now, robots, start by going to a random initial position)\n        robots[n]->start_interval = (int)config.get(\"pso_step_interval\") * 3;\n        robots[n]->pso_inertia = config.get(\"pso_inertia\");\n        robots[n]->gradient_weight = config.get(\"gradient_weight\");\n        // comm_range is used by comm_criteria to determine communication range\n        // In config, comm_range is in grid cells (as dimension)\n        robots[n]->comm_range = (int)config.get(\"comm_range\") * 10;\n        robots[n]->num_neighbors = num_robots - 1;\n        robots[n]->rx_table_timeout = config.get(\"rx_table_timeout\");\n        // End conditions\n        robots[n]->end_condition = end_condition;\n        robots[n]->end_val = end_val;\n        robots[n]->target_val = target_val;\n        // Post-decision movement options\n        robots[n]->post_decision_movement = config.get(\"post_decision_movement\");\n        // Boids parameters\n        robots[n]->lj_a = config.get(\"lj_a\");\n        robots[n]->lj_b = config.get(\"lj_b\");\n        robots[n]->lj_epsilon = config.get(\"lj_epsilon\");\n        robots[n]->lj_gamma = config.get(\"lj_gamma\");\n        robots[n]->boids_step_interval = config.get(\"boids_step_interval\");\n    }\n\n    logger.add_aggregator(\"num_neighbors\", neighbor_count);\n    logger.add_aggregator(\"network_eigenvals\", network_eigenvals);\n    logger.add_aggregator(\"decision_states\", decision_states);\n    logger.add_aggregator(\"has_decided_count\", has_decided_count);\n\n    Kilosim::Viewer viewer(world, 1080);\n    // viewer.set_show_network(true);\n    // viewer.set_show_tags(true);\n\n    sleep(2);\n    while (!is_finished(world, robots, end_condition, end_val) &&\n           world.get_tick() < max_duration)\n    {\n        viewer.draw();\n        world.step();\n        if (world.get_tick() % 20 == 0)\n        {\n            logger.log_state();\n        }\n        usleep(10000);\n    }\n}\n\nvoid sweep_sim(Kilosim::World &world, Kilosim::Logger &logger, Kilosim::ConfigParser &config)\n{\n    // Kilosim::Viewer viewer(world, 1200);\n    // viewer.set_show_network(true);\n    // viewer.set_show_tags(true);\n\n    int num_robots = config.get(\"num_robots\");\n    std::string end_condition = config.get(\"end_condition\");\n    int end_val;\n    try\n    {\n        end_val = config.get(\"end_val\");\n    }\n    catch (std::invalid_argument &e)\n    {\n        // Try getting it from sub-config instead\n        end_val = config.get(\"end_condition_params\").at(end_condition).at(\"end_val\");\n        logger.log_param(\"end_val\", end_val);\n    }\n    unsigned long int max_duration = config.get(\"max_trial_duration\");\n\n    std::vector<std::vector<Pos>> sweep_paths =\n        compute_sweep_paths(config.get(\"world_grid_width\"),\n                            config.get(\"world_grid_height\"),\n                            config.get(\"num_robots\"));\n    int max_path_len = 0;\n    for (auto path : sweep_paths)\n    {\n        if (path.size() > max_path_len)\n        {\n            max_path_len = path.size();\n        }\n    }\n\n    std::vector<Kilosim::SweepBot *> robots(num_robots);\n    for (int n = 0; n < num_robots; n++)\n    {\n        std::vector<Pos> this_path = sweep_paths[n];\n\n        Pos start_pos = this_path.back();\n        this_path.pop_back();\n        robots[n] = new Kilosim::SweepBot();\n        world.add_robot(robots[n]);\n        robots[n]->robot_init(start_pos.x, start_pos.y, 0);\n        robots[n]->end_condition = end_condition;\n        robots[n]->end_val = end_val;\n        robots[n]->set_path_external(this_path);\n        robots[n]->max_path_len = max_path_len;\n        // In config, comm_range is in grid cells (as dimension)\n        robots[n]->comm_range = (int)config.get(\"comm_range\") * 10;\n    }\n\n    logger.add_aggregator(\"decision_states\", decision_states);\n\n    // sleep(2);\n    while (!is_finished(world, robots, end_condition, end_val) &&\n           world.get_tick() < max_duration)\n    {\n        // viewer.draw();\n        world.step();\n        if (world.get_tick() % 20 == 0)\n        {\n            logger.log_state();\n        }\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    // Get config file name\n    std::vector<std::string> args(argv, argv + argc);\n    if (args.size() < 2)\n    {\n        std::cout << \"ERROR: You must provide a config file name\" << std::endl;\n        exit(1);\n    }\n    Kilosim::ConfigParser config(args[1]);\n\n    // Get configuration values\n    const int start_trial = config.get(\"start_trial\");\n    const int num_trials = config.get(\"num_trials\");\n    const std::string img_dir = config.get(\"img_dir\");\n    const int env_octaves = config.get(\"env_octaves\");\n    const int world_grid_width = (int)config.get(\"world_grid_width\");\n    const int world_grid_height = (int)config.get(\"world_grid_height\");\n    const int world_width = world_grid_width * 10;\n    const int world_height = world_grid_height * 10;\n    const std::string movement_type = config.get(\"movement_type\");\n\n    for (auto trial = start_trial; trial < start_trial + num_trials; trial++)\n    {\n        std::string trial_str = std::to_string(trial);\n        trial_str.insert(trial_str.begin(), 3 - trial_str.size(), '0');\n        const std::string img_filename = img_dir + \"/\" + trial_str +\n                                         \"_oct=\" + std::to_string(env_octaves) + \".png\";\n        // const std::string img_filename = img_dir + \"/img_oct=\" + std::to_string(env_octaves) +\n        //                                  \"_\" + trial_str + \".png\";\n        // std::cout << img_filename << std::endl;\n\n        // Create 3m x 3m world (no background image, for now)\n        Kilosim::World world(\n            world_width, world_height, img_filename // World image\n        );\n\n        // Leaving this out keeps the default communication rate of every 3 ticks\n        // Hopefully this will speed everything up without damaging results\n        // world.set_comm_rate(1);\n        world.set_comm_rate(2);\n\n        // Create log file\n        std::string log_filename = (std::string)config.get(\"log_dir\") + \"data.h5\";\n        // False = don't overwrite logs\n        Kilosim::Logger logger(world, log_filename, trial, false);\n        // Kilosim::Logger logger(world, log_filename, trial, false);\n        // False = don't warn about config parameters that can't be saved\n        logger.log_config(config, false);\n\n        // Run the right simulation\n        std::cout << \"Starting trial \" << trial << \" (\" << config.get(\"log_dir\") << \")\" << std::endl;\n        if (movement_type == \"hybrid\")\n        {\n            hybrid_sim(world, logger, config);\n        }\n        else if (movement_type == \"sweep\")\n        {\n            sweep_sim(world, logger, config);\n        }\n\n        // These are things that are only logged once, at the end of the experiment!\n        logger.add_aggregator(\"robot_distance\", robot_distance);\n        logger.add_aggregator(\"robot_coverage\", robot_coverage);\n        logger.add_aggregator(\"collective_coverage\", collective_coverage);\n        logger.log_state();\n\n        std::cout << \"Finished trial \" << trial << \"\\tt=\" << world.get_time() * world.get_tick_rate() << std::endl;\n    }\n\n    printf(\"Finished\\n\");\n\n    return 0;\n}", "meta": {"hexsha": "290ae4522e56c9985939e7f62e1ca26856154b81", "size": 21127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "jtebert/kilosim-gridbots-decisions", "max_stars_repo_head_hexsha": "ba8c00ca823e000bff4bcdc9e3bb7ba90f424501", "max_stars_repo_licenses": ["MIT"], "max_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": "jtebert/kilosim-gridbots-decisions", "max_issues_repo_head_hexsha": "ba8c00ca823e000bff4bcdc9e3bb7ba90f424501", "max_issues_repo_licenses": ["MIT"], "max_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": "jtebert/kilosim-gridbots-decisions", "max_forks_repo_head_hexsha": "ba8c00ca823e000bff4bcdc9e3bb7ba90f424501", "max_forks_repo_licenses": ["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.7478849408, "max_line_length": 121, "alphanum_fraction": 0.5776967861, "num_tokens": 5268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5911796457652431}}
{"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": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE HeapTest\n/*\n* @author : Ionesio Junior\n*/\n\n#include <boost/test/unit_test.hpp>\n#include \"../BinaryHeap.hpp\"\n#include <cstdlib>\n#include <iostream>\n#include <time.h>\n#include <vector>\n\n\nstruct setUp{\n\tBinaryHeap<int> *heap = new BinaryHeap<int>(10);\n\tint empty[0] = {};\n\tint even[10] = {9,8,7,6,5,4,3,2,1,0};\n\tint odd[9] = {9,8,7,6,5,4,3,2,1};\n\tint repeated[9] = {8,5,8,5,9,5,7,8,5};\n\t\n\tint equal[5] = {5,5,5,5,5};\n\t\n\tint repeatedOrdered[9] = {5,5,5,5,7,8,8,8,9};\n\tint evenOrdered[10] = {0,1,2,3,4,5,6,7,8,9};\n\tint oddOrdered[9] = {1,2,3,4,5,6,7,8,9};\n};\n\nBOOST_FIXTURE_TEST_SUITE(HeapTest,setUp)\nBOOST_AUTO_TEST_CASE(testInit){\n\tBOOST_CHECK(true == heap->isEmpty());\n\tBOOST_CHECK(false == heap->isFull());\n\tBOOST_CHECK(NULL == heap->rootElement());\n\tBOOST_CHECK(0 == heap->size());\n}\n\nBOOST_AUTO_TEST_CASE(testIsEmpty){\n\tBOOST_CHECK(true == heap->isEmpty());\n\theap->insert(10);\n\tBOOST_CHECK(false == heap->isEmpty());\n\theap->extractRoot();\n\tBOOST_CHECK(true == heap->isEmpty());\n}\n\nBOOST_AUTO_TEST_CASE(testSize){\n\tBOOST_CHECK(0 == heap->size());\n\tfor(int i = 0 ; i < 5;i++){\n\t\theap->insert(i);\n\t\tBOOST_CHECK(i + 1 == heap->size());\n\t}\n\tBOOST_CHECK(5 == heap->size());\n\tfor(int i = 10; i < 20 ;i = i + 2){\n\t\theap->insert(i);\n\t}\n\tBOOST_CHECK(10 == heap->size());\n\t\n\tfor(int i = 0 ; i < 5;i++){\n\t\theap->extractRoot();\n\t}\n\t\n\tBOOST_CHECK(5 == heap->size());\n}\n\n\nBOOST_AUTO_TEST_CASE(testInsert){\n\tBOOST_CHECK(0 == heap->size());\n\t\n\t//Test insert repeated elements\n\theap->insert(5);\n\tBOOST_CHECK(1 == heap->size());\n\theap->insert(5);\n\tBOOST_CHECK(2 == heap->size());\n\t\n\theap->extractRoot();\n\theap->extractRoot();\n\tBOOST_CHECK(0 == heap->size());\n\n\t//Test responsive array\n\tfor(int i = 0 ; i < 10;i++){\n\t\theap->insert(i);\n\t\tBOOST_CHECK(i == *heap->rootElement());\n\t}\n\tBOOST_CHECK(true == heap->isFull());\n\theap->insert(10);\n\tBOOST_CHECK(false == heap->isFull());\n\tBOOST_CHECK(11 == heap->size());\n}\n\nBOOST_AUTO_TEST_CASE(testExtractRoot){\n\tBOOST_CHECK(0 == heap->size());\n\tBOOST_CHECK(true == heap->isEmpty());\n\t\n\tfor(int i = 0; i < 100;i++){\n\t\theap->insert(i);\n\t}\n\t\n\tBOOST_CHECK(100 == heap->size());\n\tBOOST_CHECK(false == heap->isEmpty());\n\tBOOST_CHECK(99 == *heap->rootElement());\n\n\tfor(int i = 99; i >= 0;i--){\n\t\tBOOST_CHECK(i == heap->extractRoot());\n\t}\n\t\n\tBOOST_CHECK(0 == heap->size());\n\tBOOST_CHECK(true == heap->isEmpty());\n\t\n\tfor(int i = 0 ; i < 10;i++){\n\t\tif(i < 5){\n\t\t\theap->insert(10);\n\t\t}else{\n\t\t\theap->insert(20);\n\t\t}\n\t}\n\t\n\tBOOST_CHECK(10 == heap->size());\n\t\n\tfor(int i = 0 ; i < 10;i++){\n\t\tif(i < 5){\n\t\t\tBOOST_CHECK(20 == heap->extractRoot());\n\t\t}else{\n\t\t\tBOOST_CHECK(10 == heap->extractRoot());\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(testRootElement){\n\tBOOST_CHECK(true == heap->isEmpty());\n\theap->insert(100);\n\tfor(int i = 0 ; i < 10;i++){\n\t\tBOOST_CHECK(100 == *heap->rootElement());\n\t}\n\t\n\tBOOST_CHECK(1 == heap->size());\n\t\n\tfor(int i = 0 ; i < 10;i++){\n\t\theap->insert(i);\n\t\tBOOST_CHECK(100 == *heap->rootElement());\n\t}\n\t\n\tfor(int i = 0 ; i <= 10;i++){\n\t\tBOOST_CHECK(*heap->rootElement() == heap->extractRoot());\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(testHeapSort){\n\t//Test Even Array\n\tArray<int> result = heap->heapSort(even,10);\n\tfor(int i = 0 ; i < result.size;i++){\n\t\tBOOST_CHECK(evenOrdered[i] == result[i]);\n\t}\n\t\n\t\n\t//Test Odd Array\n\tresult = heap->heapSort(odd,9);\n\tfor(int i = 0 ; i < result.size;i++){\n\t\tBOOST_CHECK(oddOrdered[i] == result[i]);\n\t}\n\t\n\t\n\t//Test Empty array\n\tresult = heap->heapSort(empty,0);\n\tfor(int i = 0; i < result.size;i++){\n\t\tBOOST_CHECK(empty[i] == result[i]);\n\t}\n\t\n\t//Test Repeated Array\n\tresult = heap->heapSort(repeated,9);\n\tfor(int i = 0 ; i < result.size;i++){\n\t\tBOOST_CHECK(repeatedOrdered[i] == result[i]);\n\t}\n\n\t//Test equal array\n\tresult = heap->heapSort(equal,5);\n\tfor(int i = 0 ; i < result.size;i++){\n\t\tBOOST_CHECK(equal[i] == result[i]);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(testBuildHeap){\n\t\n\t//Test even array\n\tBOOST_CHECK(0 == heap->size());\n\tBOOST_CHECK(true == heap->isEmpty());\n\theap->buildHeap(even,10);\n\tBOOST_CHECK(10 == heap->size());\n\tBOOST_CHECK(false == heap->isEmpty());\n\tfor(int i = 9 ; i >= 0;i--){\n\t\tBOOST_CHECK(i == heap->extractRoot());\n\t}\n\n\t//Test odd array\n        BOOST_CHECK(0 == heap->size());\n        BOOST_CHECK(true == heap->isEmpty());\n        heap->buildHeap(odd,9);\n        BOOST_CHECK(9 == heap->size());\n        BOOST_CHECK(false == heap->isEmpty());\n        for(int i = 9 ; i > 0;i--){\n                BOOST_CHECK(i == heap->extractRoot());\n        }\n\t\n\t//Test empty array\t\n        BOOST_CHECK(0 == heap->size());\n        BOOST_CHECK(true == heap->isEmpty());\n        heap->buildHeap(empty,0);\n        BOOST_CHECK(0 == heap->size());\n        BOOST_CHECK(true == heap->isEmpty());\n        \n\t//Test equal array\n        BOOST_CHECK(0 == heap->size());\n        BOOST_CHECK(true == heap->isEmpty());\n        heap->buildHeap(equal,5);\n        BOOST_CHECK(5 == heap->size());\n        BOOST_CHECK(false == heap->isEmpty());\n        for(int i = 5 ; i > 0;i--){\n                BOOST_CHECK(5 == heap->extractRoot());\n        }\n\n\t//Test repeated array\n\tint reverseRepeated[9] = {9,8,8,8,7,5,5,5,5};\n        BOOST_CHECK(0 == heap->size());\n        BOOST_CHECK(true == heap->isEmpty());\n        heap->buildHeap(repeated,9);\n        BOOST_CHECK(9 == heap->size());\n        BOOST_CHECK(false == heap->isEmpty());\n        for(int i = 0 ; i < 9;i++){\n\t\tBOOST_CHECK(reverseRepeated[i] == heap->extractRoot());\n        }\n}\n\nBOOST_AUTO_TEST_CASE(testException){\n\tBOOST_CHECK_THROW(heap->extractRoot(),HeapUnderflowException);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6042cfb2741bb9d5300016d81413a233d3ef2c21", "size": 5551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Data Structures/Heap/C++/Test/test.cpp", "max_stars_repo_name": "Julian-Mentasti/codezilla", "max_stars_repo_head_hexsha": "ca157d75628f68ab01d589267f26d17751a87e86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 147.0, "max_stars_repo_stars_event_min_datetime": "2018-02-27T03:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T18:25:33.000Z", "max_issues_repo_path": "Data Structures/Heap/C++/Test/test.cpp", "max_issues_repo_name": "Julian-Mentasti/codezilla", "max_issues_repo_head_hexsha": "ca157d75628f68ab01d589267f26d17751a87e86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 273.0, "max_issues_repo_issues_event_min_datetime": "2018-02-26T18:40:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-31T10:37:44.000Z", "max_forks_repo_path": "Data Structures/Heap/C++/Test/test.cpp", "max_forks_repo_name": "Julian-Mentasti/codezilla", "max_forks_repo_head_hexsha": "ca157d75628f68ab01d589267f26d17751a87e86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 234.0, "max_forks_repo_forks_event_min_datetime": "2018-02-27T03:27:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T08:44:22.000Z", "avg_line_length": 23.4219409283, "max_line_length": 63, "alphanum_fraction": 0.5979102864, "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.5910742209136535}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/KWeightingFilter.hpp\"\n#include \"../util/TruePeak.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass Loudness\n{\n\npublic:\n  Loudness(index maxSize) : mTP(maxSize) {}\n\n  void init(index size, double sampleRate)\n  {\n    mFilter.init(sampleRate);\n    mTP.init(size, sampleRate);\n    mSize = size;\n    mInitialized = true;\n  }\n\n  void processFrame(const RealVectorView& input, RealVectorView output,\n                    bool weighting, bool truePeak)\n  {\n    using namespace Eigen;\n    using namespace std;\n    assert(mInitialized);\n    assert(output.size() == 2);\n    assert(input.size() == mSize);\n    ArrayXd in = _impl::asEigen<Array>(input);\n    ArrayXd filtered(mSize);\n    for (index i = 0; i < mSize; i++)\n      filtered(i) = weighting ? mFilter.processSample(in(i)) : in(i);\n    double loudness = -0.691 + 10 * log10(filtered.square().mean() + epsilon);\n    double peak = truePeak ? mTP.processFrame(input) : in.abs().maxCoeff();\n    peak = 20 * log10(peak + epsilon);\n    output(0) = loudness;\n    output(1) = peak;\n  }\n\nprivate:\n  TruePeak         mTP;\n  KWeightingFilter mFilter;\n  index            mSize{1024};\n  bool             mInitialized{false};\n};\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "b9cf9367cf7bafb915ae6653f3895ecd62a7e48d", "size": 1845, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/Loudness.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/public/Loudness.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/public/Loudness.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 27.5373134328, "max_line_length": 78, "alphanum_fraction": 0.6791327913, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5910583001164305}}
{"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": "\n#include <NTL/ZZ_pXFactoring.h>\n#include <NTL/ZZ_pEXFactoring.h>\n\nNTL_CLIENT\n\nint main()\n{\n   ZZ_p::init(to_ZZ(17));\n\n   ZZ_pX P;\n   BuildIrred(P, 10);\n\n   ZZ_pE::init(P);\n\n   ZZ_pEX f, g, h;\n\n   random(f, 20);\n   SetCoeff(f, 20);\n\n   random(h, 20);\n\n   g = MinPolyMod(h, f);\n\n   if (deg(g) < 0) Error(\"bad ZZ_pEXTest (1)\");\n   if (CompMod(g, h, f) != 0)\n      Error(\"bad ZZ_pEXTest (2)\");\n\n\n   \n   vec_pair_ZZ_pEX_long v;\n\n   long i;\n   for (i = 0; i < 5; i++) {\n      long n = RandomBnd(20)+1;\n      cerr << n << \" \";\n\n      random(f, n);\n      SetCoeff(f, n);\n\n      v = CanZass(f);\n\n      g = mul(v);\n      if (f != g) cerr << \"oops1\\n\";\n\n      long i;\n      for (i = 0; i < v.length(); i++)\n         if (!DetIrredTest(v[i].a))\n            Error(\"bad ZZ_pEXTest (3)\");\n\n\n   }\n\n   cerr << \"\\n\";\n\n   cerr << \"ZZ_pEXTest OK\\n\";\n}\n", "meta": {"hexsha": "3cd5497d1b690110d15d34ff34c5d428a0716a66", "size": 832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/tests/ZZ_pEXTest.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RUNETag/WinNTL/tests/ZZ_pEXTest.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/tests/ZZ_pEXTest.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.3448275862, "max_line_length": 47, "alphanum_fraction": 0.4807692308, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5910582904953093}}
{"text": "#include \"../Boost_Float.hxx\"\n\n#include <El.hpp>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <vector>\n\n// Rescaled Laguerre\nstd::vector<Boost_Float> sample_points(const size_t &num_points)\n{\n  std::vector<Boost_Float> result;\n  result.reserve(num_points);\n\n  Boost_Float rho_crossing(3 - 2 * sqrt(Boost_Float(2))),\n    constant(-boost::math::constants::pi_sqr<Boost_Float>()\n                    / (64 * num_points * log(rho_crossing)));\n\n  for(size_t k = 0; k < num_points; ++k)\n    {\n      result.push_back((-1 + 4 * k) * (-1 + 4 * k) * constant);\n    }\n  return result;\n}\n", "meta": {"hexsha": "349204d59a5ea7b82afb02f4032a9fda50ccab84", "size": 587, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/sdp_read/sample_points.cxx", "max_stars_repo_name": "ChrisPattison/sdpb", "max_stars_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T15:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T07:45:01.000Z", "max_issues_repo_path": "src/sdp_read/sample_points.cxx", "max_issues_repo_name": "ChrisPattison/sdpb", "max_issues_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58.0, "max_issues_repo_issues_event_min_datetime": "2015-02-27T10:03:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T04:21:42.000Z", "max_forks_repo_path": "src/sdp_read/sample_points.cxx", "max_forks_repo_name": "ChrisPattison/sdpb", "max_forks_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T11:11:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:59:42.000Z", "avg_line_length": 23.48, "max_line_length": 64, "alphanum_fraction": 0.6422487223, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593496, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5910582893039011}}
{"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": "#include <catch2/catch.hpp>\n\n#include <Eigen/Dense>\n\n#include <cannon/physics/euler_integrator.hpp>\n#include <cannon/log/registry.hpp>\n\nusing namespace Eigen;\n\nusing namespace cannon::physics;\nusing namespace cannon::log;\n\nvoid linear_system(const VectorXd& x, VectorXd& dxdt, double /*t*/) {\n  static MatrixXd A(2, 2);\n  A << -1.0, 0.0,\n       0.0, -1.0;\n\n  dxdt = A * x;\n}\n\nTEST_CASE(\"EulerIntegrator\", \"[physics]\") {\n  auto e = make_euler_integrator(linear_system, 2, 0.01);\n  VectorXd s(2);\n  s << 1.0, 0.0;\n  e.set_state(s);\n\n  for (int i = 0; i < 1000; i++) {\n    e.step();\n    log_info(\"State is now\", e.get_state(), \"at time\", e.get_time());\n  }\n\n  REQUIRE(e.get_state().norm() < 0.001);\n}\n", "meta": {"hexsha": "31e8d9fe6de4633390a4546aac4598d18b0d92c7", "size": 698, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cannon/physics/euler_integrator.test.cpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/physics/euler_integrator.test.cpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/physics/euler_integrator.test.cpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5294117647, "max_line_length": 69, "alphanum_fraction": 0.6332378223, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5909716499422535}}
{"text": "/**\n* @file distance.cpp\n* @author Shivam Akhauri (Driver),Toyas Dhake (Navigator) \n* @date 19 October 2019\n* @copyright 2019 Toyas Dhake, Shivam Akhauri\n* @brief This is a class for depth perception module based on image from single \n* camera. \n*/\n\n#include <dlib/opencv.h>\n#include <dlib/image_processing/frontal_face_detector.h>\n#include <dlib/image_processing/render_face_detections.h>\n#include <dlib/image_processing.h>\n#include <dlib/gui_widgets.h>\n#include <dlib/image_io.h>\n#include <iostream>\n#include <distance.hpp>\n#include <face.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n/**\n* @brief Function to calculate focal length of camera from a \n* reference iamge.\n* @return Focal length of camera calculated\n*/\ndouble CalculateDistance::calculateFocalLength() {\n    // constructor call for the dlib face detector\n    dlib::frontal_face_detector detector = dlib::get_frontal_face_detector();\n    dlib::matrix<dlib::bgr_pixel>  referenceImg;\n    // load the refernce image\n    dlib::load_image(referenceImg, \"../app/reference.jpg\");\n    // Detect faces\n    std::vector<dlib::rectangle> faces = detector(referenceImg);\n    // find the width of the detected face in pixels\n    double refWidth = 0;\n    for (auto&& face : faces) {\n        refWidth = face.r - face.l;\n    }\n    // calculate the focal length from the refernce frame\n    double focalLength = (refWidth * knownDistance) / knownWidth;\n    return focalLength;\n}\n\n/**\n* @brief Constructor to set the width of human face and find focal length from reference image.\n* @params _width Width of head\n* @params _focalLength Focal length of camera\n*/\nCalculateDistance::CalculateDistance() {\n    focalLength = calculateFocalLength();\n}\n\n/**\n* @brief This is the function which computes the distance of each human from the camera\n* @params image Image captured by camera, dlib face detector object\n* @return vector of Distances for each face in the frame\n*/\nstd::vector<Face> CalculateDistance::getDistance(cv::Mat image,\n                                    dlib::frontal_face_detector detector) {\n    std::vector<Face> facesWithDistance;\n    dlib::cv_image<dlib::bgr_pixel> cimg(image);\n    std::vector<dlib::rectangle> faces = detector(cimg);\n    // for each detected face calculate the distance\n    for (auto&& face : faces) {\n        // calculate width for each face\n        double width = face.r - face.l;\n        // calculate the distance for each face\n        realTimeDistance = calDist(width, focalLength);\n        Face faceWithDistance(face.l, face.t, face.r, face.b, realTimeDistance);\n        // append the distance of each face in a vecor\n        facesWithDistance.emplace_back(faceWithDistance);\n    }\n    return facesWithDistance;\n}\n\n/**\n* @brief This function contains the formula for distance calculation\n* @params width of the detected face, focalLength of the camera\n* @return double value of the calculated distance\n*/\ndouble CalculateDistance::calDist(double width, double focalLength) {\n    // formula for distance calculation\n    double distInches = (focalLength*knownWidth) / width;\n    // convert inches measurement to meters\n    double distMetres = distInches * 0.0254;\n    return distMetres;\n}\n\n", "meta": {"hexsha": "a92576b455a78acb369fd05d55f14ed130437393", "size": 3175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/distance.cpp", "max_stars_repo_name": "shivamakhauri04/midterm_project", "max_stars_repo_head_hexsha": "4d062d90cb459d035fa9453aa837463b1e72f5a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/distance.cpp", "max_issues_repo_name": "shivamakhauri04/midterm_project", "max_issues_repo_head_hexsha": "4d062d90cb459d035fa9453aa837463b1e72f5a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-10-19T06:55:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-21T15:08:33.000Z", "max_forks_repo_path": "app/distance.cpp", "max_forks_repo_name": "shivamakhauri04/midterm_project", "max_forks_repo_head_hexsha": "4d062d90cb459d035fa9453aa837463b1e72f5a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-19T02:12:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T02:12:38.000Z", "avg_line_length": 35.6741573034, "max_line_length": 95, "alphanum_fraction": 0.7165354331, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5909716499422534}}
{"text": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// With contributions from Cornelius Steinhardt\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/mtl/operation/secular.hpp>\n#include <boost/numeric/mtl/operation/sort.hpp>\n\nusing namespace std;\n\n\nint main(int , char**)\n{\n    using namespace mtl;\n    typedef dense_vector<double>  Vector;\n    Vector                    lambda(2, 0.0), z(2), d(2);\n    z[0]=1; z[1]=1;\n    d[0]=-5; d[1]=-1;\n   \n    //lambda= mtl::secular_f<Vector>(lambda, z, d, 5.0).f(3.0);\n\n    mtl::vec::secular_f<Vector>   ss(z, d, 5.0);\n    std::cout<<\"lambda  =\" << ss.f(3.0) <<\"\\n\";\n    std::cout<<\"lambda  =\" << ss.f(0.0) <<\"\\n\";\n    std::cout<<\"lambda  =\" << ss.f(-3.0) <<\"\\n\";\n    std::cout<<\"lambda  =\" << ss.f(13.0) <<\"\\n\";\n    std::cout<<\"lambda  =\" << ss.f(113.0) <<\"\\n\";\n\n    std::cout<<\"lambda  =\" << ss.grad_f(13.0) <<\"\\n\";\n    std::cout<<\"lambda  =\" << ss.grad_f(113.0) <<\"\\n\";\n    std::cout<<\"roots  =\" << secular(z, d, 5.0) <<\"\\n\";\n    //std::cout<<\"lambda  =\" << lambda <<\"\\n\";\n\n    Vector x(5, 0.0);\n    for(int i = 0; i < 5; i++)\n\tx[i]=5-i;\n    x[1]=1;\n    std::cout<< \"\\n x=\" << x << \"\\n\";\n    sort(x);\n    std::cout<< \"x=\" << x << \"\\n\";\n    MTL_THROW_IF(x[0] != 1.0, mtl::runtime_error(\"Error in sorting.\"));\n\n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "e611f333d5885a342cb06ea534844ce315be37af", "size": 1692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/secular_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/secular_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/secular_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 28.6779661017, "max_line_length": 94, "alphanum_fraction": 0.5602836879, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083132, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5909378127209023}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"../math/math.h\"\n\nUSING_NAMESPACE(sway)\n\nBOOST_AUTO_TEST_SUITE(TVector4TestSuite)\n\n/*!\n\u00a0* \u0423\u0431\u0435\u0436\u0434\u0430\u0435\u043c\u0441\u044f, \u0447\u0442\u043e \u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u043e\u0440 \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e \u043f\u0440\u0438\u0432\u043e\u0434\u0438\u0442 \u0432\u0441\u0435 \u043a\u043e\u043c\u043f\u043e\u043d\u0435\u043d\u0442\u044b \u043a \u043d\u0443\u043b\u044e.\n */\nBOOST_AUTO_TEST_CASE(TVector4TestCase_DefaultConstructor) {\n\tconst math::TVector4<s32> vec4;\n\n\tBOOST_CHECK_EQUAL(vec4.getX(), 0);\n\tBOOST_CHECK_EQUAL(vec4.getY(), 0);\n\tBOOST_CHECK_EQUAL(vec4.getZ(), 0);\n\tBOOST_CHECK_EQUAL(vec4.getW(), 0);\n}\n\n/*!\n\u00a0* \u0423\u0431\u0435\u0436\u0434\u0430\u0435\u043c\u0441\u044f, \u0447\u0442\u043e \u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u043e\u0440 \u0443\u0441\u0442\u0430\u043d\u0430\u0432\u043b\u0438\u0432\u0430\u0435\u0442 \u0432\u0441\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043a\u043e\u043c\u043f\u043e\u043d\u0435\u043d\u0442\u043e\u0432 \u0432 \u0442\u0435, \n * \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0431\u044b\u043b\u0438 \u0437\u0430\u0434\u0430\u043d\u044b.\n */\nBOOST_AUTO_TEST_CASE(TVector4TestCase_ComponentConstructor) {\n\tconst s32 x = 1, y = 2, z = 3, w = 4;\n\tconst math::TVector4<s32> vec4(x, y, z, w);\n\n\tBOOST_CHECK_EQUAL(vec4.getX(), x);\n\tBOOST_CHECK_EQUAL(vec4.getY(), y);\n\tBOOST_CHECK_EQUAL(vec4.getZ(), z);\n\tBOOST_CHECK_EQUAL(vec4.getW(), w);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "b9206fd5f0f97c6a992e26f330de4f8fbb101c30", "size": 884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/vector4.tests.cpp", "max_stars_repo_name": "timcogames/Sway.Framework", "max_stars_repo_head_hexsha": "e59c3ddaaafd849fa683e8d99ec0cd297c3806dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/vector4.tests.cpp", "max_issues_repo_name": "timcogames/Sway.Framework", "max_issues_repo_head_hexsha": "e59c3ddaaafd849fa683e8d99ec0cd297c3806dc", "max_issues_repo_licenses": ["MIT"], "max_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/vector4.tests.cpp", "max_forks_repo_name": "timcogames/Sway.Framework", "max_forks_repo_head_hexsha": "e59c3ddaaafd849fa683e8d99ec0cd297c3806dc", "max_forks_repo_licenses": ["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.2571428571, "max_line_length": 76, "alphanum_fraction": 0.7398190045, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.5908436469901055}}
{"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 * Copyright 2020, Massachusetts Institute of Technology,\n * Cambridge, MA 02139\n * All Rights Reserved\n * Authors: Jingnan Shi, et al. (see THANKS for the full author list)\n * See LICENSE for the license information\n */\n\n#include \"gtest/gtest.h\"\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <chrono>\n\n#include <Eigen/Eigenvalues>\n\n#include \"teaser/registration.h\"\n#include \"test_utils.h\"\n\nTEST(TLSTest, TLSEstimate) {\n  teaser::ScalarTLSEstimator tls;\n  // No outlier\n  {\n    Eigen::RowVectorXd measurements(5);\n    measurements << 0.5, 1, 0.6, 0.7, 1.2;\n    Eigen::RowVectorXd ranges(5);\n    ranges << 0.9, 0.9, 0.4, 0.5, 0.4;\n\n    double ref_estimate = 0.8383;\n    Eigen::Matrix<bool, 1, 5> ref_inliers;\n    ref_inliers << true, true, true, true, true;\n\n    double estimate_output;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> inliers_output;\n    inliers_output.resize(1, ref_inliers.cols());\n    tls.estimate(measurements, ranges, &estimate_output, &inliers_output);\n    EXPECT_NEAR(estimate_output, ref_estimate, 0.001); // TODO tolerance seems quite large\n\n    for (size_t i = 0; i < 5; ++i) {\n      EXPECT_EQ(inliers_output(i), ref_inliers(i));\n    }\n  }\n  // One outlier\n  {\n    Eigen::RowVectorXd measurements(6);\n    measurements << 0.5, 1, 0.6, 0.7, 1.2, 10;\n    Eigen::RowVectorXd ranges(6);\n    ranges << 0.9, 0.9, 0.4, 0.5, 0.4, 0.5;\n\n    double ref_estimate = 0.8383;\n    Eigen::Matrix<bool, 1, 6> ref_inliers;\n    ref_inliers << true, true, true, true, true, false;\n\n    double estimate_output;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> inliers_output;\n    inliers_output.resize(1, ref_inliers.cols());\n    tls.estimate(measurements, ranges, &estimate_output, &inliers_output);\n    EXPECT_NEAR(estimate_output, ref_estimate, 0.001);\n\n    for (size_t i = 0; i < 6; ++i) {\n      EXPECT_EQ(inliers_output(i), ref_inliers(i));\n    }\n  }\n  // Three (out of six) outliers\n  {\n    Eigen::RowVectorXd measurements(6);\n    measurements << 0.5, 1, 0.6, 20, 16, 10;\n    Eigen::RowVectorXd ranges(6);\n    ranges << 0.9, 0.9, 0.4, 0.5, 0.4, 0.5;\n\n    double ref_estimate = 0.6425;\n    Eigen::Matrix<bool, 1, 6> ref_inliers;\n    ref_inliers << true, true, true, false, false, false;\n\n    double estimate_output;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> inliers_output;\n    inliers_output.resize(1, ref_inliers.cols());\n    tls.estimate(measurements, ranges, &estimate_output, &inliers_output);\n    EXPECT_NEAR(estimate_output, ref_estimate, 0.001);\n\n    for (size_t i = 0; i < 6; ++i) {\n      EXPECT_EQ(inliers_output(i), ref_inliers(i));\n    }\n  }\n}\n\nTEST(TLSTest, TLSEstimateTiled) {\n  teaser::ScalarTLSEstimator tls;\n  const int scale = 64;\n  // No outlier\n  {\n    Eigen::RowVectorXd measurements(5);\n    measurements << 0.5, 1, 0.6, 0.7, 1.2;\n    Eigen::RowVectorXd ranges(5);\n    ranges << 0.9, 0.9, 0.4, 0.5, 0.4;\n\n    double ref_estimate = 0.8383;\n    Eigen::Matrix<bool, 1, 5> ref_inliers;\n    ref_inliers << true, true, true, true, true;\n\n    double estimate_output;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> inliers_output;\n    inliers_output.resize(1, ranges.cols());\n    tls.estimate_tiled(measurements, ranges, scale, &estimate_output, &inliers_output);\n    EXPECT_NEAR(estimate_output, ref_estimate, 0.001); // TODO tolerance seems quite large\n\n    for (size_t i = 0; i < 5; ++i) {\n      EXPECT_EQ(inliers_output(i), ref_inliers(i));\n    }\n  }\n  // One outlier\n  {\n    Eigen::RowVectorXd measurements(6);\n    measurements << 0.5, 1, 0.6, 0.7, 1.2, 10;\n    Eigen::RowVectorXd ranges(6);\n    ranges << 0.9, 0.9, 0.4, 0.5, 0.4, 0.5;\n\n    double ref_estimate = 0.8383;\n    Eigen::Matrix<bool, 1, 6> ref_inliers;\n    ref_inliers << true, true, true, true, true, false;\n\n    double estimate_output;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> inliers_output;\n    inliers_output.resize(1, ranges.cols());\n    tls.estimate_tiled(measurements, ranges, scale, &estimate_output, &inliers_output);\n    EXPECT_NEAR(estimate_output, ref_estimate, 0.001);\n\n    for (size_t i = 0; i < 6; ++i) {\n      EXPECT_EQ(inliers_output(i), ref_inliers(i));\n    }\n  }\n  // Three (out of six) outliers\n  {\n    Eigen::RowVectorXd measurements(6);\n    measurements << 0.5, 1, 0.6, 20, 16, 10;\n    Eigen::RowVectorXd ranges(6);\n    ranges << 0.9, 0.9, 0.4, 0.5, 0.4, 0.5;\n\n    double ref_estimate = 0.6425;\n    Eigen::Matrix<bool, 1, 6> ref_inliers;\n    ref_inliers << true, true, true, false, false, false;\n\n    double estimate_output;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> inliers_output;\n    inliers_output.resize(1, ranges.cols());\n    tls.estimate_tiled(measurements, ranges, scale, &estimate_output, &inliers_output);\n    EXPECT_NEAR(estimate_output, ref_estimate, 0.001);\n\n    for (size_t i = 0; i < 6; ++i) {\n      EXPECT_EQ(inliers_output(i), ref_inliers(i));\n    }\n  }\n}\n", "meta": {"hexsha": "d0c5e9e3c19610205dbbf358f584013d3fc02248", "size": 4799, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/teaser/tls-test.cc", "max_stars_repo_name": "plusk01/TEASER-plusplus", "max_stars_repo_head_hexsha": "0d497521d261b3fa35c4ca29eb86ba7cf9558f9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 962.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T19:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:28:49.000Z", "max_issues_repo_path": "test/teaser/tls-test.cc", "max_issues_repo_name": "plusk01/TEASER-plusplus", "max_issues_repo_head_hexsha": "0d497521d261b3fa35c4ca29eb86ba7cf9558f9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2020-01-24T15:11:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T02:28:52.000Z", "max_forks_repo_path": "test/teaser/tls-test.cc", "max_forks_repo_name": "plusk01/TEASER-plusplus", "max_forks_repo_head_hexsha": "0d497521d261b3fa35c4ca29eb86ba7cf9558f9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 234.0, "max_forks_repo_forks_event_min_datetime": "2020-01-21T12:28:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:41:31.000Z", "avg_line_length": 30.9612903226, "max_line_length": 90, "alphanum_fraction": 0.6536778496, "num_tokens": 1571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5908430776062087}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Siargey Kachanovich\n *\n *    Copyright (C) 2019 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"freudenthal_triangulation\"\n#include <boost/test/unit_test.hpp>\n\n#include <gudhi/Unitary_tests_utils.h>\n#include <gudhi/Freudenthal_triangulation.h>\n#include <gudhi/Coxeter_triangulation.h>\n\nBOOST_AUTO_TEST_CASE(freudenthal_triangulation) {\n  // Point location check\n  typedef std::vector<double> Point;\n  typedef Gudhi::coxeter_triangulation::Freudenthal_triangulation<> FK_triangulation;\n  typedef typename FK_triangulation::Simplex_handle Simplex_handle;\n  typedef typename FK_triangulation::Vertex_handle Vertex_handle;\n  typedef typename Simplex_handle::OrderedSetPartition Ordered_set_partition;\n  typedef typename Ordered_set_partition::value_type Part;\n\n  FK_triangulation tr(3);\n\n  // Point location check\n  {\n    Point point({3, -1, 0});\n    Simplex_handle s = tr.locate_point(point);\n    BOOST_CHECK(s.vertex() == Vertex_handle({3, -1, 0}));\n    BOOST_CHECK(s.partition() == Ordered_set_partition({Part({0, 1, 2, 3})}));\n  }\n\n  {\n    Point point({3.5, -1.5, 0.5});\n    Simplex_handle s = tr.locate_point(point);\n    BOOST_CHECK(s.vertex() == Vertex_handle({3, -2, 0}));\n    BOOST_CHECK(s.partition() == Ordered_set_partition({Part({0, 1, 2}), Part({3})}));\n  }\n\n  {\n    Point point({3.5, -1.8, 0.5});\n    Simplex_handle s = tr.locate_point(point);\n    BOOST_CHECK(s.vertex() == Vertex_handle({3, -2, 0}));\n    BOOST_CHECK(s.partition() == Ordered_set_partition({Part({0, 2}), Part({1}), Part({3})}));\n  }\n\n  {\n    Point point({3.5, -1.8, 0.3});\n    Simplex_handle s = tr.locate_point(point);\n    BOOST_CHECK(s.vertex() == Vertex_handle({3, -2, 0}));\n    BOOST_CHECK(s.partition() == Ordered_set_partition({Part({0}), Part({2}), Part({1}), Part({3})}));\n  }\n\n  // Dimension check\n  BOOST_CHECK(tr.dimension() == 3);\n  // Matrix check\n  Eigen::MatrixXd default_matrix = Eigen::MatrixXd::Identity(3, 3);\n  BOOST_CHECK(tr.matrix() == default_matrix);\n  // Vector check\n  Eigen::MatrixXd default_offset = Eigen::VectorXd::Zero(3);\n  BOOST_CHECK(tr.offset() == default_offset);\n\n  // Barycenter check\n  Point point({3.5, -1.8, 0.3});\n  Simplex_handle s = tr.locate_point(point);\n  Eigen::Vector3d barycenter_cart = Eigen::Vector3d::Zero();\n  for (auto v : s.vertex_range())\n    for (std::size_t i = 0; i < v.size(); i++) barycenter_cart(i) += v[i];\n  barycenter_cart /= 4.;  // simplex is three-dimensional\n  Eigen::Vector3d barycenter = tr.barycenter(s);\n  for (std::size_t i = 0; (long int)i < barycenter.size(); i++)\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(barycenter(i), barycenter_cart(i), 1e-7);\n\n  // Barycenter check for twice the scale\n  s = tr.locate_point(point, 2);\n  barycenter_cart = Eigen::Vector3d::Zero();\n  for (auto v : s.vertex_range())\n    for (std::size_t i = 0; i < v.size(); i++) barycenter_cart(i) += v[i];\n  barycenter_cart /= 3.;  // simplex is now a two-dimensional face\n  barycenter_cart /= 2.;  // scale\n  barycenter = tr.barycenter(s, 2);\n  for (std::size_t i = 0; (long int)i < barycenter.size(); i++)\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(barycenter(i), barycenter_cart(i), 1e-7);\n\n  // Matrix and offset change check\n  Eigen::MatrixXd new_matrix(3, 3);\n  new_matrix << 1, 0, 0, -1, 1, 0, -1, 0, 1;\n  Eigen::Vector3d new_offset(1.5, 1, 0.5);\n  tr.change_matrix(new_matrix);\n  tr.change_offset(new_offset);\n\n  BOOST_CHECK(tr.matrix() == new_matrix);\n  BOOST_CHECK(tr.offset() == new_offset);\n}\n\n#ifdef GUDHI_DEBUG\nBOOST_AUTO_TEST_CASE(freudenthal_triangulation_exceptions_in_debug_mode) {\n  // Point location check\n  typedef Gudhi::coxeter_triangulation::Freudenthal_triangulation<> FK_triangulation;\n\n  BOOST_CHECK_THROW (FK_triangulation tr(3, Eigen::MatrixXd::Identity(3, 3), Eigen::VectorXd::Zero(4)),\n                     std::invalid_argument);\n\n  FK_triangulation tr(3);\n  // Point of dimension 4\n  std::vector<double> point({3.5, -1.8, 0.3, 4.1});\n  BOOST_CHECK_THROW (tr.locate_point(point), std::invalid_argument);\n}\n#endif\n", "meta": {"hexsha": "2cf8f00e40dd07b7191358e2af2160f7951d4369", "size": 4279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Coxeter_triangulation/test/freud_triang_test.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T05:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T05:45:06.000Z", "max_issues_repo_path": "src/Coxeter_triangulation/test/freud_triang_test.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Coxeter_triangulation/test/freud_triang_test.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2086956522, "max_line_length": 103, "alphanum_fraction": 0.6861416219, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5908205113492301}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"euclidean_simple_witness_complex\"\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <CGAL/Epick_d.h>\n\n#include <gudhi/Simplex_tree.h>\n\n#include <gudhi/Witness_complex.h>\n#include <gudhi/Euclidean_witness_complex.h>\n#include <gudhi/Strong_witness_complex.h>\n#include <gudhi/Euclidean_strong_witness_complex.h>\n\n#include <gudhi/Kd_tree_search.h>\n\n#include <iostream>\n#include <ctime>\n#include <vector>\n\ntypedef Gudhi::Simplex_tree<> Simplex_tree;\ntypedef typename Simplex_tree::Vertex_handle Vertex_handle;\ntypedef std::vector< Vertex_handle > typeVectorVertex;\ntypedef CGAL::Epick_d<CGAL::Dynamic_dimension_tag> Kernel;\ntypedef typename Kernel::FT FT;\ntypedef typename Kernel::Point_d Point_d;\ntypedef Gudhi::witness_complex::Euclidean_witness_complex<Kernel> EuclideanWitnessComplex;\ntypedef Gudhi::witness_complex::Euclidean_strong_witness_complex<Kernel> EuclideanStrongWitnessComplex;\n\ntypedef std::vector<Point_d> Point_range;\ntypedef Gudhi::spatial_searching::Kd_tree_search<Kernel, Point_range> Kd_tree;\ntypedef Kd_tree::INS_range Nearest_landmark_range;\ntypedef std::vector<Nearest_landmark_range> Nearest_landmark_table;\ntypedef Gudhi::witness_complex::Witness_complex<Nearest_landmark_table> WitnessComplex;\ntypedef Gudhi::witness_complex::Strong_witness_complex<Nearest_landmark_table> StrongWitnessComplex;\n\n\n/* All landmarks and witnesses are taken on the grid in the following manner.\n   LWLWL\n   WW.WW\n   L...L\n   WW.WW\n   LWLWL\n\n   Witness complex consists of 8 vertices, 12 edges and 4 triangles\n */\n\nBOOST_AUTO_TEST_CASE(simple_witness_complex) {\n  Simplex_tree complex, relaxed_complex, strong_relaxed_complex, strong_relaxed_complex2;\n  Simplex_tree complex_ne, relaxed_complex_ne, strong_relaxed_complex_ne, strong_relaxed_complex2_ne;\n\n  Point_range witnesses, landmarks;\n\n  landmarks.push_back(Point_d(std::vector<FT>{-2,-2}));\n  landmarks.push_back(Point_d(std::vector<FT>{-2, 0}));\n  landmarks.push_back(Point_d(std::vector<FT>{-2, 2}));\n  landmarks.push_back(Point_d(std::vector<FT>{ 0,-2}));\n  landmarks.push_back(Point_d(std::vector<FT>{ 0, 2}));\n  landmarks.push_back(Point_d(std::vector<FT>{ 2,-2}));\n  landmarks.push_back(Point_d(std::vector<FT>{ 2, 0}));\n  landmarks.push_back(Point_d(std::vector<FT>{ 2, 2}));\n  witnesses.push_back(Point_d(std::vector<FT>{-2,-1}));\n  witnesses.push_back(Point_d(std::vector<FT>{-2, 1}));\n  witnesses.push_back(Point_d(std::vector<FT>{-1,-2}));\n  witnesses.push_back(Point_d(std::vector<FT>{-1,-1}));\n  witnesses.push_back(Point_d(std::vector<FT>{-1, 1}));\n  witnesses.push_back(Point_d(std::vector<FT>{-1, 2}));\n  witnesses.push_back(Point_d(std::vector<FT>{ 1,-2}));\n  witnesses.push_back(Point_d(std::vector<FT>{ 1,-1}));\n  witnesses.push_back(Point_d(std::vector<FT>{ 1, 1}));\n  witnesses.push_back(Point_d(std::vector<FT>{ 1, 2}));\n  witnesses.push_back(Point_d(std::vector<FT>{ 2,-1}));\n  witnesses.push_back(Point_d(std::vector<FT>{ 2, 1}));\n\n  Kd_tree landmark_tree(landmarks);\n  Nearest_landmark_table nearest_landmark_table;\n  for (auto w: witnesses)\n    nearest_landmark_table.push_back(landmark_tree.incremental_nearest_neighbors(w));\n\n  // Weak witness complex: Euclidean version\n  EuclideanWitnessComplex eucl_witness_complex(landmarks,\n                                               witnesses);\n  eucl_witness_complex.create_complex(complex, 0);\n\n  std::cout << \"complex.num_simplices() = \" << complex.num_simplices() << std::endl;\n  BOOST_CHECK(complex.num_simplices() == 24);\n\n  eucl_witness_complex.create_complex(relaxed_complex, 8.01);\n\n  std::cout << \"relaxed_complex.num_simplices() = \" << relaxed_complex.num_simplices() << std::endl;\n  BOOST_CHECK(relaxed_complex.num_simplices() == 239);\n  // The corner simplex {0,2,5,7} and its cofaces are missing.\n\n  // Weak witness complex: non-Euclidean version\n  WitnessComplex witness_complex(nearest_landmark_table);\n  witness_complex.create_complex(complex_ne, 0);\n\n  std::cout << \"complex.num_simplices() = \" << complex_ne.num_simplices() << std::endl;\n  BOOST_CHECK(complex_ne.num_simplices() == 24);\n\n  witness_complex.create_complex(relaxed_complex_ne, 8.01);\n\n  std::cout << \"relaxed_complex.num_simplices() = \" << relaxed_complex_ne.num_simplices() << std::endl;\n  BOOST_CHECK(relaxed_complex_ne.num_simplices() == 239);\n\n\n  // Strong complex : Euclidean version\n  EuclideanStrongWitnessComplex eucl_strong_witness_complex(landmarks,\n                                                            witnesses);\n\n  eucl_strong_witness_complex.create_complex(strong_relaxed_complex, 9.1);\n  eucl_strong_witness_complex.create_complex(strong_relaxed_complex2, 9.1, 2);\n\n  std::cout << \"strong_relaxed_complex.num_simplices() = \" << strong_relaxed_complex.num_simplices() << std::endl;\n  BOOST_CHECK(strong_relaxed_complex.num_simplices() == 239);\n\n  std::cout << \"strong_relaxed_complex2.num_simplices() = \" << strong_relaxed_complex2.num_simplices() << std::endl;\n  BOOST_CHECK(strong_relaxed_complex2.num_simplices() == 92);\n\n\n  // Strong complex : non-Euclidean version\n  StrongWitnessComplex strong_witness_complex(nearest_landmark_table);\n\n  strong_witness_complex.create_complex(strong_relaxed_complex_ne, 9.1);\n  strong_witness_complex.create_complex(strong_relaxed_complex2_ne, 9.1, 2);\n\n  std::cout << \"strong_relaxed_complex.num_simplices() = \" << strong_relaxed_complex_ne.num_simplices() << std::endl;\n  BOOST_CHECK(strong_relaxed_complex_ne.num_simplices() == 239);\n\n  std::cout << \"strong_relaxed_complex2.num_simplices() = \" << strong_relaxed_complex2_ne.num_simplices() << std::endl;\n  BOOST_CHECK(strong_relaxed_complex2_ne.num_simplices() == 92);\n\n\n  // 8 vertices, 28 edges, 56 triangles\n}\n", "meta": {"hexsha": "4f718203486cb95f4e50802dda30838717ac6701", "size": 5721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Witness_complex/test/test_euclidean_simple_witness_complex.cpp", "max_stars_repo_name": "jmarino/gudhi-devel", "max_stars_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-27T03:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T21:14:14.000Z", "max_issues_repo_path": "src/Witness_complex/test/test_euclidean_simple_witness_complex.cpp", "max_issues_repo_name": "jmarino/gudhi-devel", "max_issues_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-25T16:03:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T07:36:21.000Z", "max_forks_repo_path": "src/Witness_complex/test/test_euclidean_simple_witness_complex.cpp", "max_forks_repo_name": "jmarino/gudhi-devel", "max_forks_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-06T12:36:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-25T14:53:13.000Z", "avg_line_length": 42.0661764706, "max_line_length": 119, "alphanum_fraction": 0.7573850725, "num_tokens": 1536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5908205001325657}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <random>\n\nusing namespace Eigen;\n\nint main() {\n  std::default_random_engine generator;\n  std::poisson_distribution<int> distribution(4.1);\n  auto poisson = [&] () {return distribution(generator);};\n\n  RowVectorXi v = RowVectorXi::NullaryExpr(10, poisson );\n  std::cout << v << \"\\n\";\n}\n", "meta": {"hexsha": "33744c051662f76299e223305b1aa912d45d4fa2", "size": 336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/special_examples/random_cpp11.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/special_examples/random_cpp11.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/special_examples/random_cpp11.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": 22.4, "max_line_length": 58, "alphanum_fraction": 0.693452381, "num_tokens": 87, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5908204988257814}}
{"text": "// Boost.Geometry\r\n// Unit Test\r\n\r\n// Copyright (c) 2016-2017 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#include \"test_formula.hpp\"\r\n#include \"intersection_cases.hpp\"\r\n\r\n#include <boost/geometry/formulas/andoyer_inverse.hpp>\r\n#include <boost/geometry/formulas/geographic.hpp>\r\n#include <boost/geometry/formulas/gnomonic_intersection.hpp>\r\n#include <boost/geometry/formulas/sjoberg_intersection.hpp>\r\n#include <boost/geometry/formulas/thomas_direct.hpp>\r\n#include <boost/geometry/formulas/thomas_inverse.hpp>\r\n#include <boost/geometry/formulas/vincenty_direct.hpp>\r\n#include <boost/geometry/formulas/vincenty_inverse.hpp>\r\n\r\n#include <boost/geometry/srs/spheroid.hpp>\r\n\r\nvoid check_result(expected_result const& result, expected_result const& expected,\r\n                  expected_result const& reference, double reference_error,\r\n                  bool check_reference_only)\r\n{\r\n    //BOOST_CHECK_MESSAGE((false), \"(\" << result.lon << \" \" << result.lat << \") vs (\" << expected.lon << \" \" << expected.lat << \")\");\r\n    check_one(result.lon, expected.lon, reference.lon, reference_error, false, check_reference_only);\r\n    check_one(result.lat, expected.lat, reference.lat, reference_error, false, check_reference_only);\r\n}\r\n\r\nvoid test_formulas(expected_results const& results, bool check_reference_only)\r\n{\r\n    // reference result\r\n    if (results.sjoberg_vincenty.lon == ND)\r\n    {\r\n        return;\r\n    }\r\n\r\n    double const d2r = bg::math::d2r<double>();\r\n    double const r2d = bg::math::r2d<double>();\r\n\r\n    double lona1r = results.p1.lon * d2r;\r\n    double lata1r = results.p1.lat * d2r;\r\n    double lona2r = results.p2.lon * d2r;\r\n    double lata2r = results.p2.lat * d2r;\r\n    double lonb1r = results.q1.lon * d2r;\r\n    double latb1r = results.q1.lat * d2r;\r\n    double lonb2r = results.q2.lon * d2r;\r\n    double latb2r = results.q2.lat * d2r;\r\n\r\n    expected_result result;\r\n\r\n    // WGS84\r\n    bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);\r\n\r\n    if (results.gnomonic_vincenty.lon != ND)\r\n    {\r\n        bg::formula::gnomonic_intersection<double, bg::formula::vincenty_inverse, bg::formula::vincenty_direct>\r\n            ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid);\r\n        result.lon *= r2d;\r\n        result.lat *= r2d;\r\n        check_result(result, results.gnomonic_vincenty, results.sjoberg_vincenty, 0.00000001, check_reference_only);\r\n    }\r\n\r\n    if (results.gnomonic_thomas.lon != ND)\r\n    {\r\n        bg::formula::gnomonic_intersection<double, bg::formula::thomas_inverse, bg::formula::thomas_direct>\r\n            ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid);\r\n        result.lon *= r2d;\r\n        result.lat *= r2d;\r\n        check_result(result, results.gnomonic_thomas, results.sjoberg_vincenty, 0.0000001, check_reference_only);\r\n    }\r\n\r\n    if (results.sjoberg_vincenty.lon != ND)\r\n    {\r\n        bg::formula::sjoberg_intersection<double, bg::formula::vincenty_inverse, 4>\r\n            ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid);\r\n        result.lon *= r2d;\r\n        result.lat *= r2d;\r\n        check_result(result, results.sjoberg_vincenty, results.sjoberg_vincenty, 0.00000001, check_reference_only);\r\n    }\r\n\r\n    if (results.sjoberg_thomas.lon != ND)\r\n    {\r\n        bg::formula::sjoberg_intersection<double, bg::formula::thomas_inverse, 2>\r\n            ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid);\r\n        result.lon *= r2d;\r\n        result.lat *= r2d;\r\n        check_result(result, results.sjoberg_thomas, results.sjoberg_vincenty, 0.0000001, check_reference_only);\r\n    }\r\n\r\n    if (results.sjoberg_andoyer.lon != ND)\r\n    {\r\n        bg::formula::sjoberg_intersection<double, bg::formula::andoyer_inverse, 1>\r\n            ::apply(lona1r, lata1r, lona2r, lata2r, lonb1r, latb1r, lonb2r, latb2r, result.lon, result.lat, spheroid);\r\n        result.lon *= r2d;\r\n        result.lat *= r2d;\r\n        check_result(result, results.sjoberg_andoyer, results.sjoberg_vincenty, 0.0001, check_reference_only);\r\n    }\r\n\r\n    if (results.great_elliptic.lon != ND)\r\n    {\r\n        typedef bg::model::point<double, 2, bg::cs::geographic<bg::degree> > point_geo;\r\n        typedef bg::model::point<double, 3, bg::cs::cartesian> point_3d;\r\n        point_geo a1(results.p1.lon, results.p1.lat);\r\n        point_geo a2(results.p2.lon, results.p2.lat);\r\n        point_geo b1(results.q1.lon, results.q1.lat);\r\n        point_geo b2(results.q2.lon, results.q2.lat);\r\n        point_3d a1v = bg::formula::geo_to_cart3d<point_3d>(a1, spheroid);\r\n        point_3d a2v = bg::formula::geo_to_cart3d<point_3d>(a2, spheroid);\r\n        point_3d b1v = bg::formula::geo_to_cart3d<point_3d>(b1, spheroid);\r\n        point_3d b2v = bg::formula::geo_to_cart3d<point_3d>(b2, spheroid);\r\n        point_3d resv(0, 0, 0);\r\n        point_geo res(0, 0);\r\n        bg::formula::great_elliptic_intersection(a1v, a2v, b1v, b2v, resv, spheroid);\r\n        res = bg::formula::cart3d_to_geo<point_geo>(resv, spheroid);\r\n        result.lon = bg::get<0>(res);\r\n        result.lat = bg::get<1>(res);\r\n        check_result(result, results.great_elliptic, results.sjoberg_vincenty, 0.01, check_reference_only);\r\n    }\r\n}\r\n\r\nvoid test_4_input_combinations(expected_results const& results, bool check_reference_only)\r\n{\r\n    test_formulas(results, check_reference_only);\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_GEO_INTERSECTION_TEST_SIMILAR\r\n    {\r\n        expected_results results_alt = results;\r\n        std::swap(results_alt.p1, results_alt.p2);\r\n        test_formulas(results_alt, true);\r\n    }\r\n    {\r\n        expected_results results_alt = results;\r\n        std::swap(results_alt.q1, results_alt.q2);\r\n        test_formulas(results_alt, true);\r\n    }\r\n    {\r\n        expected_results results_alt = results;\r\n        std::swap(results_alt.p1, results_alt.p2);\r\n        std::swap(results_alt.q1, results_alt.q2);\r\n        test_formulas(results_alt, true);\r\n    }\r\n#endif\r\n}\r\n\r\nvoid test_all(expected_results const& results)\r\n{\r\n    test_4_input_combinations(results, false);\r\n\r\n#ifdef BOOST_GEOMETRY_TEST_GEO_INTERSECTION_TEST_SIMILAR\r\n    expected_results results_alt = results;\r\n    results_alt.p1.lat *= -1;\r\n    results_alt.p2.lat *= -1;\r\n    results_alt.q1.lat *= -1;\r\n    results_alt.q2.lat *= -1;\r\n    results_alt.gnomonic_vincenty.lat *= -1;\r\n    results_alt.gnomonic_thomas.lat *= -1;\r\n    results_alt.sjoberg_vincenty.lat *= -1;\r\n    results_alt.sjoberg_thomas.lat *= -1;\r\n    results_alt.sjoberg_andoyer.lat *= -1;\r\n    results_alt.great_elliptic.lat *= -1;\r\n    test_4_input_combinations(results_alt, true);\r\n#endif\r\n}\r\n\r\nint test_main(int, char*[])\r\n{\r\n    for (size_t i = 0; i < expected_size; ++i)\r\n    {\r\n        test_all(expected[i]);\r\n    }\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "3b5ebd385bb7b7e6513b1cd178a958ebeb5eda6c", "size": 7169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/formulas/intersection.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/formulas/intersection.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/formulas/intersection.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8277777778, "max_line_length": 134, "alphanum_fraction": 0.6673176175, "num_tokens": 2090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5908204876091164}}
{"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 <boost/test/unit_test.hpp>\n#include <vector>\n#include <numeric>\n#include <limits>\n#include <set>\n#include <math.h>\n\n\n\nusing namespace std;\n\nint FindMid( vector<int>& A )\n{\n    if ( A.size() == 0 ) \n        return -1;\n\n    long long rsum = std::accumulate( A.begin()+1, A.end(), 0 );\n    long long lsum = 0;\n\n    if( lsum == rsum ) \n        return 0;\n\n    for( size_t i=1; i<A.size(); ++i )\n    {\n        lsum += A[i-1];\n        rsum -= A[i];\n\n        if ( rsum == lsum ) \n            return i;\n    }\n\n    return -1;\n}\n\n\nBOOST_AUTO_TEST_CASE( TestCodilityDemo )\n{\n    {\n        int A[] = { 1, -2, 1 };\n        BOOST_CHECK_EQUAL( 1, FindMid( vector<int>( A, A+3 ) ) );\n    }\n\n    {\n        int A[] = { 1, 2, -2, 1, 1 };\n        BOOST_CHECK_EQUAL( 3, FindMid( vector<int>( A, A+(sizeof(A)/sizeof(A[0])) ) ) );\n    }\n}\n\n\nint ClosestAscender( int A[], int length, int k )\n{\n    if( k < 0 || k >= length ) \n        return -1;\n\n    vector<int> as;\n    for( int i=0; i<length; ++i )\n    {\n        if( i == k ) continue;\n\n        if( A[i] > A[k] ) \n            as.push_back( i );\n    }\n\n    int min = numeric_limits<int>::max();\n    int minIndex = -1;\n    for( int j = 0; j < (int)as.size(); ++j) \n    {\n        int dist = abs( as[j]-k );\n        if( dist < min ) \n        {\n            min = dist;\n            minIndex = as[j];\n        }\n    }\n\n    return minIndex;\n}\n\nBOOST_AUTO_TEST_CASE( TestClosestAscender )\n{\n    {\n        int A[] = { 1, 2, 3, 4, 5 };\n        BOOST_CHECK_EQUAL( 3, ClosestAscender( A, sizeof(A)/sizeof(A[0]), 2 ) );\n    }\n\n    {\n        int A[] = { 1, 5, 3, 4, 4 };\n        BOOST_CHECK_EQUAL( 1, ClosestAscender( A, sizeof(A)/sizeof(A[0]), 4 ) );\n    }\n}\n\n\nlong long Fib( int N )\n{\n    if( N >= 2 ) \n    {\n        return Fib( N-1 ) + Fib( N -2 );\n    }\n    \n    return N;\n}\n\nlong long FibImp( int N )\n{\n    long long a = 0;\n    long long b = 1;\n    long long t;\n\n    for( int i = 0; i<N; ++i )\n    {\n        t = a;\n        a = b;\n        b = b + t;\n    }\n    return a;\n}\n\nint power_fib( int N, int M )\n{\n    return FibImp( pow( (double)N, (double)M ) ) % 10000103;\n}\n\n\n\nBOOST_AUTO_TEST_CASE( TestPowerFib )\n{\n    BOOST_CHECK_EQUAL( 21, power_fib( 2, 3 ) );\n}\n\n\nint FirstCoveringPrefix( int A[], int length )\n{   \n    if ( length == 0 ) \n        return -1;\n\n    set<int> keys;\n    int prefix = -1;\n\n    for( int i = 0; i<length; ++i )\n    {\n        pair<set<int>::iterator,bool> ret = keys.insert ( A[i] );\n        if( ret.second == true )\n        {\n            prefix = i;\n        }\n    }\n\n    return prefix;\n}\n\nBOOST_AUTO_TEST_CASE( TestFirstCoveringPrefix )\n{\n    {\n        int A[] = { 1, 5, 3, 4, 4 };\n        BOOST_CHECK_EQUAL( 3, FirstCoveringPrefix( A, sizeof(A)/sizeof(A[0]) ) );\n    }\n\n    {\n        int A[] = { 1 };\n        BOOST_CHECK_EQUAL( 0, FirstCoveringPrefix( A, sizeof(A)/sizeof(A[0]) ) );\n    }    \n\n    {\n        int A[] = { 1, 1, 1, 1, 1 };\n        BOOST_CHECK_EQUAL( 0, FirstCoveringPrefix( A, sizeof(A)/sizeof(A[0]) ) );\n    }    \n\n    {\n        int A[] = { 1 };\n        BOOST_CHECK_EQUAL( -1, FirstCoveringPrefix( A, 0 ) );\n    }  \n\n    {\n        int A[] = { 1,2,3,4,5 };\n        BOOST_CHECK_EQUAL( 4, FirstCoveringPrefix( A, sizeof(A)/sizeof(A[0]) ) );\n    }  \n\n}\n\n", "meta": {"hexsha": "4880ab30f7d3cf6a8f52cabca54d0dba0e6f29b4", "size": 3213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CodingSkill/CPPCoding/TestCodilityDemo.cpp", "max_stars_repo_name": "SungwooNam/ProgrammingStudy", "max_stars_repo_head_hexsha": "3c2fe6096fea29547f05ff29bbde14a48c4afa9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-22T04:58:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-22T04:58:15.000Z", "max_issues_repo_path": "src/CodingSkill/CPPCoding/TestCodilityDemo.cpp", "max_issues_repo_name": "SungwooNam/ProgrammingStudy", "max_issues_repo_head_hexsha": "3c2fe6096fea29547f05ff29bbde14a48c4afa9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-21T16:02:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-21T16:02:41.000Z", "max_forks_repo_path": "src/CodingSkill/CPPCoding/TestCodilityDemo.cpp", "max_forks_repo_name": "SungwooNam/ProgrammingStudy", "max_forks_repo_head_hexsha": "3c2fe6096fea29547f05ff29bbde14a48c4afa9b", "max_forks_repo_licenses": ["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.85, "max_line_length": 88, "alphanum_fraction": 0.4684095861, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5907973818946971}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2014 Roshan <thisisroshansmail@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestUniformIntDistribution\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/algorithm/count_if.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/random/default_random_engine.hpp>\n#include <boost/compute/random/uniform_int_distribution.hpp>\n#include <boost/compute/lambda.hpp>\n\n#include \"context_setup.hpp\"\n\nnamespace compute=boost::compute;\n\nBOOST_AUTO_TEST_CASE(uniform_int_distribution_doctest)\n{\n    using boost::compute::uint_;\n    using boost::compute::lambda::_1;\n\n    boost::compute::vector<uint_> vec(128, context);\n\n//! [generate]\n// initialize the default random engine\nboost::compute::default_random_engine engine(queue);\n\n// setup the uniform distribution to produce integers 0 and 1\nboost::compute::uniform_int_distribution<uint_> distribution(0, 1);\n\n// generate the random values and store them to 'vec'\ndistribution.generate(vec.begin(), vec.end(), engine, queue);\n//! [generate]\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::count_if(\n            vec.begin(), vec.end(), _1 > 1, queue\n        ),\n        size_t(0)\n    );\n}\n\nBOOST_AUTO_TEST_CASE(issue159) {\n    using boost::compute::lambda::_1;\n\n    boost::compute::vector<int> input(10, context);\n\n    // generate random numbers between 1 and 10\n    compute::default_random_engine rng(queue);\n    compute::uniform_int_distribution<int> d(1, 10);\n    d.generate(input.begin(), input.end(), rng, queue);\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::count_if(\n            input.begin(), input.end(), _1 > 10, queue\n        ),\n        size_t(0)\n    );\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::count_if(\n            input.begin(), input.end(), _1 < 1, queue\n        ),\n        size_t(0)\n    );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "fdb267b3da3e3284c29f7ef2736c4b464e6f0fa7", "size": 2285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_uniform_int_distribution.cpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "test/test_uniform_int_distribution.cpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_uniform_int_distribution.cpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2948717949, "max_line_length": 79, "alphanum_fraction": 0.6507658643, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.590797381894697}}
{"text": "#include \"visual_utility/TransformEstimator-Inl.h\"\n\n#include <gtest/gtest.h>\n#include <boost/scoped_ptr.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include \"cv_utils/DisplayImages.h\"\n\nusing namespace cv;\nusing namespace std;\nusing namespace boost;\n\nnamespace visual_utility {\n\nclass EstimateAffineTransformTest : public ::testing::Test {\n\n protected:\n  Mat_<double> image;\n  scoped_ptr<AffineTransformEstimator> estimator;\n  \n  virtual void SetUp() {\n    estimator.reset(new AffineTransformEstimator(100, 1e-6, 1.0));\n\n    // Create a simple image\n    image = Mat::zeros(20, 30, CV_64F);\n    \n    for (int i = 3; i < 14; i++) {\n      image.at<double>(Point((i+10)/2, i)) += i/20.0;\n    }\n\n    for (int i = 9; i < 18; i++) {\n      image.at<double>(Point(i, 6)) = 0.6;\n    }\n  }\n\n  void ExpectMatrixNear(const Mat& a, const Mat& b, double error=1e-5) {\n    ASSERT_EQ(a.rows, b.rows);\n    ASSERT_EQ(a.cols, b.cols);\n\n    for (int i = 0; i < a.rows; i++) {\n      for (int j = 0; j < b.cols; j++) {\n        EXPECT_NEAR(a.at<double>(Point(j,i)), b.at<double>(Point(j,i)), error);\n      }\n    }\n  }\n\n  Mat CreateWarpedImage(const Mat_<double>& src, const Mat& M) {\n    return estimator->ApplyTransform(src, M, geo::BORDER_CONSTANT, 0.0);\n  }\n\n};\n\nTEST_F(EstimateAffineTransformTest, SmallRotation) {\n  double angle = 1.0;\n  Mat desiredTransform = Mat::zeros(2,3,CV_64F);\n  desiredTransform.at<double>(Point(0,0)) = cos(angle * M_PI / 180.0);\n  desiredTransform.at<double>(Point(0,1)) = -sin(angle * M_PI /180.0);\n  desiredTransform.at<double>(Point(1,0)) = sin(angle * M_PI / 180.0);\n  desiredTransform.at<double>(Point(1,1)) = cos(angle * M_PI / 180.0);\n\n  Mat warpedImage = CreateWarpedImage(image, desiredTransform);\n\n  Mat foundTransform = estimator->EstimateTransform(image, warpedImage);         \n  ExpectMatrixNear(desiredTransform, foundTransform);\n}\n\nTEST_F(EstimateAffineTransformTest, SmallTranslation) {\n  Mat_<double> desiredTransform = Mat::eye(2,3,CV_64F);\n  desiredTransform(0,2) = 2;\n  desiredTransform(1,2) = -2;\n\n  Mat warpedImage = CreateWarpedImage(image, desiredTransform);\n\n  Mat foundTransform = estimator->EstimateTransform(image, warpedImage);         \n  ExpectMatrixNear(desiredTransform, foundTransform);\n}\n\nTEST_F(EstimateAffineTransformTest, TranslationWithRescaling) {\n  Mat_<double> desiredTransform = Mat::eye(2,3,CV_64F);\n  desiredTransform(0,2) = 2;\n  desiredTransform(1,2) = -2;\n\n  Mat warpedImage = CreateWarpedImage(image, desiredTransform);\n\n  estimator.reset(new AffineTransformEstimator(100, 1e-6, 2.0));\n  Mat foundTransform = estimator->EstimateTransform(image, warpedImage);         \n  ExpectMatrixNear(desiredTransform, foundTransform);\n}\n\nTEST_F(EstimateAffineTransformTest, ImageWithRescaling) {\n  // Do a small rotation on an image that is resized\n  double angle = 8.0;\n  Mat_<double> desiredTransform = Mat::zeros(2,3,CV_64F);\n  desiredTransform(0,0) = cos(angle * M_PI / 180.0);\n  desiredTransform(0,1) = -sin(angle * M_PI /180.0);\n  desiredTransform(1,0) = sin(angle * M_PI / 180.0);\n  desiredTransform(1,1) = cos(angle * M_PI / 180.0);\n  \n  Mat biggerImage;\n  resize(image, biggerImage, Size(), 2.0, 2.0, INTER_CUBIC);\n\n  Mat warpedImage = CreateWarpedImage(biggerImage, desiredTransform);\n\n  Mat foundTransform = estimator->EstimateTransform(biggerImage, warpedImage);         \n  ExpectMatrixNear(desiredTransform, foundTransform);\n}\n\n\nTEST_F(EstimateAffineTransformTest, TestIdentityTransform) {\n  Mat desiredTransform = Mat::eye(2,3,CV_64F);\n\n  Mat warpedImage = CreateWarpedImage(image, desiredTransform);\n\n  Mat foundTransform = estimator->EstimateTransform(image, warpedImage);\n                                                \n  ExpectMatrixNear(desiredTransform, foundTransform);\n  ExpectMatrixNear(warpedImage, image);\n}\n\nTEST_F(EstimateAffineTransformTest, TestNoTransform) {\n\n  Mat warpedImage = image.clone();\n\n  Mat foundTransform = estimator->EstimateTransform(image, warpedImage);\n\n  ExpectMatrixNear(Mat::eye(2,3,CV_64F), foundTransform);\n}\n\n// mdesnoyer: disable the test because OpenCV isn't throwing a normal\n// exception, it's killing the program.\nTEST_F(EstimateAffineTransformTest, DISABLED_SrcNotGreyscale) {\n  Mat colorImage;\n\n  cvtColor(image, colorImage, CV_GRAY2BGR);\n\n  EXPECT_THROW(estimator->EstimateTransform(colorImage, image), cv::Exception);\n}\n\n// mdesnoyer: disable the test because OpenCV isn't throwing a normal\n// exception, it's killing the program.\nTEST_F(EstimateAffineTransformTest, DISABLED_DestNotGreyscale) {\n  Mat colorImage;\n\n  cvtColor(image, colorImage, CV_GRAY2BGR);\n\n  EXPECT_THROW(estimator->EstimateTransform(image, colorImage), cv::Exception);\n}\n\nTEST_F(EstimateAffineTransformTest, ReadDataTest) {\n  Mat img1 = imread(\"test/testFishFrame1.png\", -1);\n  Mat img2 = imread(\"test/testFishFrame2.png\", -1);\n\n  Mat img1Float;\n  Mat img2Float;\n  img1.convertTo(img1Float, CV_64F, 1./255);\n  img2.convertTo(img2Float, CV_64F, 1./255);\n\n  estimator.reset(new AffineTransformEstimator(50, 1e-8, 4.0));\n\n  Mat M = estimator->EstimateTransform(img1Float, img2Float);\n  ASSERT_EQ(M.rows, 2);\n  ASSERT_EQ(M.cols, 3);\n}\n\nTEST_F(EstimateAffineTransformTest, RealImageRotateAndTranslate) {\n  // Rotate\n  double angle = 0.5;\n  Mat_<double> desiredTransform = Mat::zeros(2,3,CV_64F);\n  desiredTransform(0,0) = cos(angle * M_PI / 180.0);\n  desiredTransform(0,1) = -sin(angle * M_PI /180.0);\n  desiredTransform(1,0) = sin(angle * M_PI / 180.0);\n  desiredTransform(1,1) = cos(angle * M_PI / 180.0);\n\n  // Zoom\n  desiredTransform(0,0) *= 1.02;\n  desiredTransform(1,1) *= 1.05;\n  \n  // Shift\n  desiredTransform(0,2) = 1;\n  desiredTransform(1,2) = -2;\n\n  estimator.reset(new AffineTransformEstimator(100, 1e-8, 4.0));\n\n  Mat img1 = imread(\"test/hima_set22_404.bmp\", 0);\n  Mat img1Float;\n  img1.convertTo(img1Float, CV_64F, 1./255);\n\n  Mat warpedImage = CreateWarpedImage(img1Float, desiredTransform);\n\n  Mat foundTransform = estimator->EstimateTransform(img1Float, warpedImage);\n\n  ExpectMatrixNear(desiredTransform, foundTransform);\n\n  cv_utils::DisplayNormalizedImage(img1, \"img1\");\n  cv_utils::DisplayNormalizedImage(warpedImage, \"img2\");\n  cv_utils::DisplayNormalizedImage(abs(warpedImage - CreateWarpedImage(img1Float,\n                                                                       foundTransform)),\n                                   \"diff\");\n  cv_utils::DisplayNormalizedImage(CreateWarpedImage(img1Float,\n                                                     foundTransform),\n                                   \"warped\");\n  cv_utils::ShowWindowsUntilKeyPress();\n}\n\n}; // namespace\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "e01f454341a1a004138fd0e371fe78d82471b616", "size": 6676, "ext": "cc", "lang": "C++", "max_stars_repo_path": "visual_utility/test/TransformEstimatorTest.cc", "max_stars_repo_name": "MRSD2018/reefbot-1", "max_stars_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "visual_utility/test/TransformEstimatorTest.cc", "max_issues_repo_name": "MRSD2018/reefbot-1", "max_issues_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "visual_utility/test/TransformEstimatorTest.cc", "max_forks_repo_name": "MRSD2018/reefbot-1", "max_forks_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7904761905, "max_line_length": 88, "alphanum_fraction": 0.6941282205, "num_tokens": 1872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5907973798518323}}
{"text": "#include <utility>\n\n//\n// Created by lei on 4/21/19.\n//\n\n#include \"topography.hpp\"\n\n#include <algorithm>\n#include <fmt/format.h>\n#include <armadillo>\n\n\nTopography::Topography(const arma::vec &x,\n                       const arma::vec &fev, int nk):\n                       x_(x), topo_(nk, x.size()) {\n    if (not x.is_sorted()) {\n        fmt::print(\"{}\\n\", \"input vector is not a sorted one.\");\n        exit(-1);\n    }\n    int nx = x.size();\n    int nk2 = 2*nk;\n    for (auto i=0; i<nx; ++i) {\n        int ind_beg;\n        if (i < nk) {\n            ind_beg = 0;\n        } else if (i >= nx-nk) {\n            ind_beg = nx - 1 - nk2;\n        } else {\n            ind_beg = i - nk;\n        }\n        arma::vec x_slice = x.subvec(ind_beg, ind_beg+nk2);\n        x_slice = arma::abs(x_slice -x[i]);\n        arma::uvec ind_sort = arma::sort_index(x_slice);\n        for (auto j=0; j<nk; ++j) {\n            int ind_global = ind_sort(j+1) + ind_beg;\n            double f_diff = fev(ind_global) - fev(i);\n            int sign = (f_diff > 0 )  - (f_diff < 0);\n            topo_(j, i) = sign * ind_global;\n        }\n    }\n}\n\n\nstd::vector<double> Topography::minimize_pool() const {\n    std::vector<double> min_pool;\n    for (auto i=0U; i<x_.size(); ++i) {\n        if (arma::all(topo_.col(i) > 0)) {\n            min_pool.push_back(x_(i));\n        }\n    }\n    return min_pool;\n}\n", "meta": {"hexsha": "8cd1da39ac7fe98e1f6c59bc59cdb9281ba684c7", "size": 1363, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/topography.cc", "max_stars_repo_name": "pan3rock/tgo1d-cxx", "max_stars_repo_head_hexsha": "9553b48279c918e0f19ca3a22538caf1a2eff296", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/topography.cc", "max_issues_repo_name": "pan3rock/tgo1d-cxx", "max_issues_repo_head_hexsha": "9553b48279c918e0f19ca3a22538caf1a2eff296", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/topography.cc", "max_forks_repo_name": "pan3rock/tgo1d-cxx", "max_forks_repo_head_hexsha": "9553b48279c918e0f19ca3a22538caf1a2eff296", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2407407407, "max_line_length": 64, "alphanum_fraction": 0.4893617021, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5907444848052859}}
{"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": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm trigonometry tan\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/data_customization_point/scalar.h\"\n#include \"fern/algorithm/trigonometry/tan.h\"\n\n\nnamespace fa = fern::algorithm;\n\n\ntemplate<\n    class Value>\nusing OutOfDomainPolicy = fa::tan::OutOfDomainPolicy<Value>;\n\n\nBOOST_AUTO_TEST_CASE(out_of_domain_policy)\n{\n    {\n        OutOfDomainPolicy<double> policy;\n        BOOST_CHECK(policy.within_domain(5));\n        BOOST_CHECK(policy.within_domain(-5));\n        BOOST_CHECK(policy.within_domain(0));\n\n        BOOST_CHECK(!policy.within_domain(fern::infinity<double>()));\n        BOOST_CHECK(!policy.within_domain(-fern::infinity<double>()));\n\n        BOOST_CHECK(!policy.within_domain(1.0 * fern::half_pi<double>()));\n        BOOST_CHECK( policy.within_domain(2.0 * fern::half_pi<double>()));\n        BOOST_CHECK(!policy.within_domain(3.0 * fern::half_pi<double>()));\n\n        BOOST_CHECK(!policy.within_domain(-1.0 * fern::half_pi<double>()));\n        BOOST_CHECK( policy.within_domain(-2.0 * fern::half_pi<double>()));\n        BOOST_CHECK(!policy.within_domain(-3.0 * fern::half_pi<double>()));\n    }\n}\n\n\ntemplate<\n    class Value,\n    class Result>\nvoid verify_zero(\n    Value const& value)\n{\n    fa::SequentialExecutionPolicy sequential;\n\n    Result result_we_want{0};\n    Result result_we_get;\n    fa::trigonometry::tan(sequential, value, result_we_get);\n    BOOST_CHECK_CLOSE(1.0 + result_we_get, 1.0 + result_we_want, 1e-10);\n}\n\n\ntemplate<\n    class Value,\n    class Result>\nvoid verify_value(\n    Value const& value,\n    Result const& result_we_want)\n{\n    fa::SequentialExecutionPolicy sequential;\n\n    Result result_we_get;\n    fa::trigonometry::tan(sequential, value, result_we_get);\n\n    // TODO mingw 32 bit / gcc 4.8.2 requires us to use 4e-3. Other compilers\n    //      allow the use of 1e-10.\n    //      Check compiler and version and restore original epsilon.\n    BOOST_CHECK_CLOSE(result_we_get, result_we_want, 4e-3);\n}\n\n\nBOOST_AUTO_TEST_CASE(algorithm)\n{\n    verify_zero<double, double>(0.0);\n    verify_zero<double, double>(-0.0);\n\n    verify_zero<double, double>(1.0 * fern::pi<double>());\n    verify_zero<double, double>(2.0 * fern::pi<double>());\n    verify_zero<double, double>(-1.0 * fern::pi<double>());\n    verify_zero<double, double>(-2.0 * fern::pi<double>());\n\n    verify_value<double, double>(fern::half_pi<double>(),\n        std::tan(fern::half_pi<double>()));\n    verify_value<double, double>(-fern::half_pi<double>(),\n        std::tan(-fern::half_pi<double>()));\n}\n", "meta": {"hexsha": "7399b5f52a5d7d300e54e8abecb096655e740523", "size": 3015, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/trigonometry/test/tan_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/trigonometry/test/tan_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/trigonometry/test/tan_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0744680851, "max_line_length": 80, "alphanum_fraction": 0.6500829187, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5905619151872609}}
{"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) \u00b7 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": "//============================================================================\n//\n// This file is part of the Thea toolkit.\n//\n// This software is distributed under the BSD license, as detailed in the\n// accompanying LICENSE.txt file. Portions are derived from other works:\n// their respective licenses and copyright information are reproduced in\n// LICENSE.txt and/or in the relevant source files.\n//\n// Author: Siddhartha Chaudhuri\n// First version: 2009\n//\n//============================================================================\n\n#ifndef __Thea_Algorithms_StdLinearSolver_hpp__\n#define __Thea_Algorithms_StdLinearSolver_hpp__\n\n#include \"../Common.hpp\"\n#include \"../Array.hpp\"\n#include \"../MatVec.hpp\"\n#include \"../SparseMatVec.hpp\"\n#include \"ILinearSolver.hpp\"\n#include \"NNLS/nnls.h\"\n#include <Eigen/QR>\n#include <Eigen/SVD>\n\nnamespace Thea {\nnamespace Algorithms {\n\n// Forward declarations\nnamespace StdLinearSolverInternal { class StdLinearSolverImpl; }\n\n/**\n * Solve dense and sparse linear systems of the form Ax = b for x. This class implements the ILinearSolver interface to provide a\n * variety of built-in algorithms. Other solvers may be provided by plugins implementing the ILinearSolver interface.\n */\nclass THEA_API StdLinearSolver : public virtual ILinearSolver, public NamedObject\n{\n  public:\n    THEA_DECL_SMART_POINTERS(StdLinearSolver)\n\n    /** The constraints to be imposed on the solution (enum class). */\n    struct THEA_API Constraint\n    {\n      /** Supported values. */\n      enum Value\n      {\n        UNCONSTRAINED,  ///< The solution is not constrained.\n        NON_NEGATIVE    ///< The solution must have non-negative elements only.\n      };\n\n      THEA_ENUM_CLASS_BODY(Constraint)\n\n      THEA_ENUM_CLASS_STRINGS_BEGIN(Constraint)\n        THEA_ENUM_CLASS_STRING(UNCONSTRAINED,  \"unconstrained\")\n        THEA_ENUM_CLASS_STRING(NON_NEGATIVE,   \"non-negative\")\n      THEA_ENUM_CLASS_STRINGS_END(Constraint)\n    };\n\n    /** Solution methods (enum class). */\n    struct THEA_API Method\n    {\n      /** Supported values. */\n      enum Value\n      {\n        DEFAULT,                             ///< Automatically pick a solution method.\n\n        // Dense solvers\n        HOUSEHOLDER_QR,                      ///< Eigen's HouseholderQR solver.\n        COL_PIV_HOUSEHOLDER_QR,              ///< Eigen's ColPivHouseholderQR solver.\n        FULL_PIV_HOUSEHOLDER_QR,             ///< Eigen's FullPivHouseholderQR solver.\n        COMPLETE_ORTHOGONAL_DECOMPOSITION,   ///< Eigen's CompleteOrthogonalDecomposition solver.\n        BDCSVD,                              ///< Eigen's BDCSVD solver.\n        NNLS,                                ///< NNLS non-negative least squares solver.\n\n        // Sparse solvers\n        SIMPLICIALT_LLT,                     ///< Eigen's SimplicialLLT solver.\n        SIMPLICIALT_LDLT,                    ///< Eigen's SimplicialLDLT solver.\n        SPARSE_LU,                           ///< Eigen's SparseLU solver.\n        SPARSE_QR,                           ///< Eigen's SparseQR solver.\n        CONJUGATE_GRADIENT,                  ///< Eigen's ConjugateGradient solver.\n        LEAST_SQUARES_CONJUGATE_GRADIENT,    ///< Eigen's LeastSquaresConjugateGradient solver.\n        BICGSTAB,                            ///< Eigen's BiCGSTAB solver.\n      };\n\n      THEA_ENUM_CLASS_BODY(Method)\n\n      THEA_ENUM_CLASS_STRINGS_BEGIN(Method)\n        THEA_ENUM_CLASS_STRING(DEFAULT,                            \"default\")\n\n        THEA_ENUM_CLASS_STRING(HOUSEHOLDER_QR,                     \"HouseholderQR\")\n        THEA_ENUM_CLASS_STRING(COL_PIV_HOUSEHOLDER_QR,             \"ColPivHouseholderQR\")\n        THEA_ENUM_CLASS_STRING(FULL_PIV_HOUSEHOLDER_QR,            \"FullPivHouseholderQR\")\n        THEA_ENUM_CLASS_STRING(COMPLETE_ORTHOGONAL_DECOMPOSITION,  \"CompleteOrthogonalDecomposition\")\n        THEA_ENUM_CLASS_STRING(BDCSVD,                             \"BDSVD\")\n        THEA_ENUM_CLASS_STRING(NNLS,                               \"NNLS\")\n\n        THEA_ENUM_CLASS_STRING(SIMPLICIALT_LLT,                    \"SimplicialLLT\")\n        THEA_ENUM_CLASS_STRING(SIMPLICIALT_LDLT,                   \"SimplicialLDLT\")\n        THEA_ENUM_CLASS_STRING(SPARSE_LU,                          \"SparseLU\")\n        THEA_ENUM_CLASS_STRING(SPARSE_QR,                          \"SparseQR\")\n        THEA_ENUM_CLASS_STRING(CONJUGATE_GRADIENT,                 \"ConjugateGradient\")\n        THEA_ENUM_CLASS_STRING(LEAST_SQUARES_CONJUGATE_GRADIENT,   \"LeastSquaresConjugateGradient\")\n        THEA_ENUM_CLASS_STRING(BICGSTAB,                           \"BiCGSTAB\")\n      THEA_ENUM_CLASS_STRINGS_END(Method)\n    };\n\n    /** Constructor. */\n    StdLinearSolver(Method method_ = Method::DEFAULT, Constraint constraint_ = Constraint::UNCONSTRAINED);\n\n    /** Destructor. */\n    ~StdLinearSolver();\n\n    /** Get the solution method. */\n    Method getMethod() const;\n\n    /** Get the solution constraint. */\n    Constraint getConstraint() const;\n\n    /* Get the solution tolerance/threshold. A negative number implies the default tolerance. */\n    double getTolerance() const;\n\n    /* Get the maximum number of solver iterations, if the solver is iterative. */\n    intx maxIterations() const;\n\n    /** Set the solution method. */\n    void setMethod(Method method_);\n\n    /** Set the solution constraint. */\n    void setConstraint(Constraint constraint_);\n\n    /* Set the solution tolerance/threshold. */\n    void setTolerance(float64 tol);\n\n    /* Get the maximum number of solver iterations, if the solver is iterative. A negative number implies the default value. */\n    void setMaxIterations(intx max_iters_);\n\n    /** Solve the linear system Ax = b for a dense double-precision matrix A. */\n    bool solve(Eigen::Ref< MatrixXd > const & a, double const * b, IOptions const * options = nullptr);\n\n    /** Solve the linear system Ax = b for a sparse double-precision matrix A. */\n    bool solve(Eigen::Ref< SparseMatrix<double> > const & a, double const * b, IOptions const * options = nullptr);\n\n    // Functions from ILinearSolver\n    int8 THEA_ICALL solve(IMatrix<float64> const * a, float64 const * b, IOptions const * options = nullptr);\n    int64 THEA_ICALL dims() const;\n    int8 THEA_ICALL hasSolution() const;\n    float64 const * THEA_ICALL getSolution() const;\n    int8 THEA_ICALL getSquaredError(float64 * err) const;\n\n  private:\n    StdLinearSolverInternal::StdLinearSolverImpl * impl;  ///< Contains base function implementations using PIMPL idiom.\n\n}; // class StdLinearSolver\n\n} // namespace Algorithms\n} // namespace Thea\n\n#endif\n", "meta": {"hexsha": "43a1bd28d385ed0a69be6ee2f649b5bab163c577", "size": 6560, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/Source/Algorithms/StdLinearSolver.hpp", "max_stars_repo_name": "christinazavou/Thea", "max_stars_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T17:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:34.000Z", "max_issues_repo_path": "Code/Source/Algorithms/StdLinearSolver.hpp", "max_issues_repo_name": "christinazavou/Thea", "max_issues_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-22T16:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-22T16:47:04.000Z", "max_forks_repo_path": "Code/Source/Algorithms/StdLinearSolver.hpp", "max_forks_repo_name": "christinazavou/Thea", "max_forks_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-10-17T20:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T09:56:27.000Z", "avg_line_length": 41.0, "max_line_length": 129, "alphanum_fraction": 0.6384146341, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5903968819048163}}
{"text": "extern \"C\"  {\n        #include \"postgres.h\"\n        #include \"catalog/pg_type.h\"\n        #include \"fmgr.h\"\n}\n#include \"random.h\"\n#include \"../array.h\"\n\n#include <boost/random.hpp>\n\ntemplate<class D> static Datum _gen_rand(PG_FUNCTION_ARGS, D& dist, int dim_arr_idx = 0) {\n  typedef typename D::result_type T;\n  ArrayType* arr = PG_GETARG_ARRAYTYPE_P_COPY(dim_arr_idx);\n\n  if (ARR_NDIM(arr) == 0 ) {\n     PG_RETURN_POINTER(construct_empty_array(oid_type<double>()));\n  } else if (ARR_NDIM(arr) != 1 ) {\n     elog(ERROR, \"GEN_RAND: Size specification can only be 1-dimension array\");\n     PG_RETURN_NULL();\n  } else if (ARR_DIMS(arr)[0] >= 4 ) {\n     elog(ERROR, \"GEN_RAND: Maximum of 4 dimensions in array generation.\");\n     PG_RETURN_NULL();\n  }\n\n  //compute number of dimensions\n  ArrDims rd = extract_shape(arr);\n  Datum* r = (Datum*)palloc(rd.n * sizeof(Datum));\n  for (size_t i = 0; i < rd.n; ++i ) {\n     r[i] = _ret<T>(dist(rgen));\n  }\n\n  ArrayType* res = construct_md_array(r,\n                                      NULL,\n                                      rd.ndims,\n                                      rd.dims,\n                                      rd.lbs,\n                                      oid_type<T>(),\n                                      sizeof(T),\n                                      true,\n                                      oid_align<T>());\n  PG_RETURN_POINTER(res);\n}\n\n#define RAND_FUNCTION(NAME) \\\n\textern \"C\" { PG_FUNCTION_INFO_V1(NAME); Datum NAME(PG_FUNCTION_ARGS); } \\\n        Datum NAME(PG_FUNCTION_ARGS)\n\nRAND_FUNCTION(gen_rand) {\n  std::uniform_real_distribution<double> dist{0.0, 1.0};\n  return _gen_rand(fcinfo, dist);\n}\n\n\nRAND_FUNCTION(gen_randn) {\n  //for soem reason can't determine \"std' variant is producing warnings.\n  std::normal_distribution<double> dist{0.0, 1.0};\n  return _gen_rand(fcinfo, dist);\n}\n\n\nRAND_FUNCTION(gen_randint) {\n  long low = get_param<long>(fcinfo, 0);\n  long high = get_param<long>(fcinfo, 1);\n  if (high <= low ){\n     elog(ERROR, \"GEN_RANDINT: Cannot have high bound lower then low bound\");\n     PG_RETURN_NULL();\n  } else {\n     std::uniform_int_distribution<> dist(low, high);\n     return _gen_rand(fcinfo, dist, 2);\n  }\n}\n\nRAND_FUNCTION(gen_beta) {\n  float alpha = get_param<double>(fcinfo, 0);\n  float beta  = get_param<double>(fcinfo, 1);\n  if (alpha < 0 || beta < 0){\n     elog(ERROR, \"BETA: Can't have negative alpha/beta parameters\");\n     PG_RETURN_NULL();\n  } else {\n     boost::random::beta_distribution<double> dist(alpha, beta);\n     return _gen_rand(fcinfo, dist, 2);\n  }\n}\n\nRAND_FUNCTION(gen_binomial) {\n  int t = get_param<int>(fcinfo, 0);\n  float p  = get_param<double>(fcinfo, 1);\n  if (t < 0 || p < 0 || p > 1){\n     elog(ERROR, \"BINOMIAL: Input parameters outside of range\");\n     PG_RETURN_NULL();\n  } else {\n     boost::random::binomial_distribution<int> dist(t,p);\n     return _gen_rand(fcinfo, dist, 2);\n  }\n}\n\n", "meta": {"hexsha": "196db737195161bf46a105856bbd7370a3031d23", "size": 2908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/random/distribution.cpp", "max_stars_repo_name": "tarkmeper/numpgsql", "max_stars_repo_head_hexsha": "a5098af9b7c4d88564092c0a4809029aab9f614f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-08T15:25:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-07T16:31:55.000Z", "max_issues_repo_path": "src/random/distribution.cpp", "max_issues_repo_name": "tarkmeper/numpgsql", "max_issues_repo_head_hexsha": "a5098af9b7c4d88564092c0a4809029aab9f614f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/random/distribution.cpp", "max_forks_repo_name": "tarkmeper/numpgsql", "max_forks_repo_head_hexsha": "a5098af9b7c4d88564092c0a4809029aab9f614f", "max_forks_repo_licenses": ["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.9793814433, "max_line_length": 90, "alphanum_fraction": 0.5900962861, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5903968819048163}}
{"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": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#define NT2_UNIT_MODULE \"nt2 optimize toolbox - quadl\"\n\n#include <iostream>\n#include <nt2/include/functions/quadl.hpp>\n#include <nt2/toolbox/optimization/output.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/bind.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/rowvect.hpp>\n#include <nt2/include/functions/exp.hpp>\n#include <nt2/include/functions/expm1.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/include/functions/globalsum.hpp>\n#include <nt2/include/functions/globalmax.hpp>\n#include <nt2/include/functions/dist.hpp>\n#include <nt2/include/functions/ones.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/sqrteps.hpp>\n#include <nt2/table.hpp>\nstruct f\n{\n  template < class X > inline\n  X operator()(const X & x ) const\n  {\n    return x;\n  }\n};\n\n\nNT2_TEST_CASE_TPL( quadl_functor, NT2_REAL_TYPES )\n{\n  using nt2::quadl;\n  using nt2::options;\n  using nt2::optimization::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n  tab_t x = nt2::_(T(0), T(5));\n  NT2_DISPLAY(x);\n  BOOST_AUTO_TPL(res, quadl<T>(f(), x));\n   std::cout << \"Integrals:\" << res.integrals << \") = \" << res.errors\n             << \" after \" << res.eval_count <<  \" evaluations\\n\";\n\n   NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::dist(res.integrals, nt2::sqr(x)*nt2::Half<T>())), nt2::Sqrteps<T>());\n\n\n}\n\nNT2_TEST_CASE_TPL( quadl_tag, NT2_REAL_TYPES )\n{\n  using nt2::quadl;\n  using nt2::options;\n  using nt2::integration::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n  tab_t x = nt2::_(T(0), T(5));\n  NT2_DISPLAY(x);\n  //output<tab_t,T>\n  BOOST_AUTO_TPL(res, quadl<T>(nt2::functor<nt2::tag::exp_>(), x));\n  std::cout << \"Integrals: \" << res.integrals << \" with \" << res.errors\n            << \" after \" << res.eval_count <<  \" evaluations\\n\";\n\n  NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::dist(res.integrals, nt2::expm1(x))), nt2::Sqrteps<T>());\n\n\n}\nNT2_TEST_CASE_TPL( quadl_tag_reverse, NT2_REAL_TYPES )\n{\n  using nt2::quadl;\n  using nt2::options;\n  using nt2::integration::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n  tab_t x = nt2::_(T(5), T(-1), T(0));\n  NT2_DISPLAY(x);\n  //output<tab_t,T>\n  BOOST_AUTO_TPL(res, quadl<T>(nt2::functor<nt2::tag::exp_>(), x));\n  std::cout << \"Integrals: \" << res.integrals << \" with \" << res.errors\n            << \" after \" << res.eval_count <<  \" evaluations\\n\";\n\n  NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::dist(res.integrals, nt2::exp(x)-nt2::exp(T(5)))), nt2::Sqrteps<T>());\n\n\n}\n\nNT2_TEST_CASE_TPL( quadl_2, NT2_REAL_TYPES )\n{\n  using nt2::quadl;\n  using nt2::options;\n  using nt2::integration::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n  tab_t x = nt2::_(T(0), T(5), T(5));\n  NT2_DISPLAY(x);\n\n  BOOST_AUTO_TPL(res, quadl<T>(nt2::functor<nt2::tag::exp_>(), T(0), T(5)));\n  std::cout << \"Integrals: \" << res.integrals << \" with \" << res.errors\n            << \" after \" << res.eval_count <<  \" evaluations\\n\";\n\n  NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::dist(res.integrals, expm1(x))), nt2::Sqrteps<T>());\n\n\n}\n\n", "meta": {"hexsha": "6f6fafd65eade0b310ac20b3437b7801db1ba5e3", "size": 3881, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/integration/unit/scalar/quadl.cpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/integration/unit/scalar/quadl.cpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/integration/unit/scalar/quadl.cpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1709401709, "max_line_length": 114, "alphanum_fraction": 0.6361762432, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5902366543435336}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file TransformationWithCovariance.hpp\n/// \\brief Header file for a transformation matrix class with associated covariance.\n/// \\details Light weight transformation class with added covariance propagation, intended to\n///          be fast, and not to provide unnecessary functionality, but still much slower than\n///          the base Transformation class due to extra matrix multiplications associated with\n///          covariance propagation.  Only use this class if you need covariance.\n///\n/// \\author Kai van Es\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n///\n/// A note on EIGEN_MAKE_ALIGNED_OPERATOR_NEW (Sean Anderson, as of May 23, 2013)\n/// (also see http://eigen.tuxfamily.org/dox-devel/group__TopicStructHavingEigenMembers.html)\n///\n/// Fortunately, Eigen::Matrix3d and Eigen::Vector3d are NOT 16-byte vectorizable,\n/// therefore this class should not require alignment, and can be used normally in STL.\n///\n/// To inform others of the issue, classes that include *fixed-size vectorizable Eigen types*,\n/// see http://eigen.tuxfamily.org/dox-devel/group__TopicFixedSizeVectorizable.html,\n/// must include the above macro! Furthermore, special considerations must be taken if\n/// you want to use them in STL containers, such as std::vector or std::map.\n/// The macro overloads the dynamic \"new\" operator so that it generates\n/// 16-byte-aligned pointers, this MUST be in the public section of the header!\n///\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef LGMATH_TRANSFORMATIONWITHCOVARIANCE_HPP\n#define LGMATH_TRANSFORMATIONWITHCOVARIANCE_HPP\n\n#include <lgmath/se3/Transformation.hpp>\n#include <Eigen/Core>\n\nnamespace lgmath {\nnamespace se3 {\n\nclass TransformationWithCovariance: public Transformation\n{\n public:\n  // Eigen::Matrix<double,6,6> is 16-byte vectorizable\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Default constructor\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(bool initCovarianceToZero = false);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Copy constructor.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(const TransformationWithCovariance&) = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Move constructor.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(TransformationWithCovariance&& T) = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Copy constructor from basic Transformation\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(const Transformation& T, bool initCovarianceToZero = false);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Move constructor from basic Transformation\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(Transformation&& T, bool initCovarianceToZero = false);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Copy constructor from basic Transformation, with covariance\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(const Transformation& T,\n                               const Eigen::Matrix<double,6,6>& covariance);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(const Eigen::Matrix4d& T);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor with covariance\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(const Eigen::Matrix4d& T,\n                               const Eigen::Matrix<double,6,6>& covariance);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor. The transformation will be T_ba = [C_ba, -C_ba*r_ba_ina; 0 0 0 1]\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(const Eigen::Matrix3d& C_ba, const Eigen::Vector3d& r_ba_ina);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor with covariance. The transformation will be\n  /// T_ba = [C_ba, -C_ba*r_ba_ina; 0 0 0 1]\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(const Eigen::Matrix3d& C_ba, const Eigen::Vector3d& r_ba_ina,\n                               const Eigen::Matrix<double,6,6>& covariance);\n\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor. The transformation will be T_ba = vec2tran(xi_ab)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(const Eigen::Matrix<double,6,1>& xi_ab,\n                               unsigned int numTerms = 0);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor with covariance. The transformation will be T_ba = vec2tran(xi_ab)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(const Eigen::Matrix<double,6,1>& xi_ab,\n                               const Eigen::Matrix<double,6,6>& covariance,\n                               unsigned int numTerms = 0);\n\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor. The transformation will be T_ba = vec2tran(xi_ab), xi_ab must be 6x1\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(const Eigen::VectorXd& xi_ab);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor. The transformation will be T_ba = vec2tran(xi_ab), xi_ab must be 6x1\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance(const Eigen::VectorXd& xi_ab,\n                               const Eigen::Matrix<double,6,6>& covariance);\n\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Destructor. Default implementation.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  ~TransformationWithCovariance() = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Copy assignment operator.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance& operator=(const TransformationWithCovariance&) = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Move assignment operator.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance& operator=(TransformationWithCovariance&& T) = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Copy assignment operator from basic Transform.\n  /// \\details This assignment resets the covariance to the uninitialized state.  You must\n  ///          manually call setZeroCovariance() or setCovariance(const Eigen::Matrix6d&)\n  ///          before querying it with the public method cov(), or an exception will be\n  ///          thrown.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual TransformationWithCovariance& operator=(const Transformation& T);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Move assignment operator from basic Transform.\n  /// \\details This assignment resets the covariance to the uninitialized state.  You must\n  ///          manually call setZeroCovariance() or setCovariance(const Eigen::Matrix6d&)\n  ///          before querying it with the public method cov(), or an exception will be\n  ///          thrown.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  virtual TransformationWithCovariance& operator=(Transformation&& T);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Gets the underlying covariance matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  const Eigen::Matrix<double,6,6>& cov() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Returns whether or not a covariance has been set. If it is unset, then querying it\n  ///        with the public method cov() will throw an exception.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  bool covarianceSet() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Sets the underlying rotation matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  void setCovariance(const Eigen::Matrix<double,6,6>& covariance);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Sets the underlying rotation matrix to the 6x6 zero matrix (perfect certainty)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  void setZeroCovariance();\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get the inverse matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance inverse() const;\n\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief In-place right-hand side multiply T_rhs.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance& operator*=(const TransformationWithCovariance& T_rhs);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief In-place right-hand side multiply basic (certain) T_rhs\n  ///\n  /// Note: Assumes that the Transformation matrix has perfect certainty\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance& operator*=(const Transformation& T_rhs);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief In-place right-hand side multiply this matrix by the inverse of T_rhs\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance& operator/=(const TransformationWithCovariance& T_rhs);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief In-place right-hand side multiply this matrix by\n  ///        the inverse of a basic (certain) T_rhs\n  ///\n  /// Note: Assumes that the Transformation matrix has perfect certainty\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  TransformationWithCovariance& operator/=(const Transformation& T_rhs);\n\n private:\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// Covariance\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::Matrix<double,6,6> covariance_;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// Covariance flag.  Set to true when the covariance is manually set or initialized.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  bool covarianceSet_;\n};\n\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Multiplication of TransformWithCovariance by TransformWithCovariance\n//////////////////////////////////////////////////////////////////////////////////////////////\nTransformationWithCovariance operator*(TransformationWithCovariance T_lhs,\n                                       const TransformationWithCovariance& T_rhs);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Multiplication of TransformWithCovariance by Transform\n///\n/// Note: Assumes that the Transformation matrix has perfect certainty\n//////////////////////////////////////////////////////////////////////////////////////////////\nTransformationWithCovariance operator*(TransformationWithCovariance T_lhs,\n                                       const Transformation& T_rhs);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Multiplication of Transform by TransformWithCovariance\n///\n/// Note: Assumes that the Transformation matrix has perfect certainty\n//////////////////////////////////////////////////////////////////////////////////////////////\nTransformationWithCovariance operator*(const Transformation& T_lhs,\n                                       const TransformationWithCovariance& T_rhs);\n\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Multiplication of TransformWithCovariance by inverse TransformWithCovariance\n//////////////////////////////////////////////////////////////////////////////////////////////\nTransformationWithCovariance operator/(TransformationWithCovariance T_lhs,\n                                       const TransformationWithCovariance& T_rhs);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Multiplication of TransformWithCovariance by inverse Transform\n///\n/// Note: Assumes that the Transformation matrix has perfect certainty\n//////////////////////////////////////////////////////////////////////////////////////////////\nTransformationWithCovariance operator/(TransformationWithCovariance T_lhs,\n                                       const Transformation& T_rhs);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Multiplication of Transform by inverse TransformWithCovariance\n///\n/// Note: Assumes that the Transformation matrix has perfect certainty\n//////////////////////////////////////////////////////////////////////////////////////////////\nTransformationWithCovariance operator/(const Transformation& T_lhs,\n                                       const TransformationWithCovariance& T_rhs);\n\n} // se3\n} // lgmath\n\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief print transformation\n//////////////////////////////////////////////////////////////////////////////////////////////\nstd::ostream& operator<<(std::ostream& out, const lgmath::se3::TransformationWithCovariance& T);\n\n\n#endif //LGMATH_TRANSFORMATIONWITHCOVARIANCE_HPP\n\n\n", "meta": {"hexsha": "3baf2929161a0b1aaa0f878ced71b25cdd0ba857", "size": 16398, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lgmath/se3/TransformationWithCovariance.hpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "include/lgmath/se3/TransformationWithCovariance.hpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "include/lgmath/se3/TransformationWithCovariance.hpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 58.1489361702, "max_line_length": 96, "alphanum_fraction": 0.3940724479, "num_tokens": 2303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5902366497200346}}
{"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// \u6b63\u5982\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c\u672c\u7a0b\u5e8f\u57fa\u672c\u4e0a\u53ea\u662f  step-4  \u7684\u4e00\u4e2a\u5c0f\u4fee\u6539\u7248\u672c\u3002\u56e0\u6b64\uff0c\u4ee5\u4e0b\u5927\u90e8\u5206\u7684include\u6587\u4ef6\u90fd\u662f\u5728\u90a3\u91cc\u4f7f\u7528\u7684\uff0c\u6216\u8005\u81f3\u5c11\u662f\u5728\u4ee5\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u5df2\u7ecf\u4f7f\u7528\u7684\u3002\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\u7528\u4e8e\u8bbe\u7f6e\u6bcf\u4e2a  PETScWrappers::MPI::Vector:  \u7684\u5927\u5c0f\u3002\n#include <deal.II/base/index_set.h> \n\n// PETSc\u51fa\u73b0\u5728\u8fd9\u91cc\u662f\u56e0\u4e3aSLEPc\u4f9d\u8d56\u4e8e\u8fd9\u4e2a\u5e93\u3002\n\n#include <deal.II/lac/petsc_sparse_matrix.h> \n#include <deal.II/lac/petsc_vector.h> \n\n// \u7136\u540e\u6211\u4eec\u9700\u8981\u5b9e\u9645\u5bfc\u5165SLEPc\u63d0\u4f9b\u7684\u6c42\u89e3\u5668\u63a5\u53e3\u3002\n\n#include <deal.II/lac/slepc_solver.h> \n\n// \u6211\u4eec\u8fd8\u9700\u8981\u4e00\u4e9b\u6807\u51c6\u7684C++\u3002\n\n#include <fstream> \n#include <iostream> \n\n// \u6700\u540e\uff0c\u548c\u4ee5\u524d\u7684\u7a0b\u5e8f\u4e00\u6837\uff0c\u6211\u4eec\u5c06\u6240\u6709\u7684deal.II\u7c7b\u548c\u51fd\u6570\u540d\u5bfc\u5165\u5230\u672c\u7a0b\u5e8f\u4e2d\u6240\u6709\u7684\u540d\u5b57\u7a7a\u95f4\u4e2d\u3002\n\nnamespace Step36 \n{ \n  using namespace dealii; \n// @sect3{The <code>EigenvalueProblem</code> class template}  \n\n// \u4e0b\u9762\u662f\u4e3b\u7c7b\u6a21\u677f\u7684\u7c7b\u58f0\u660e\u3002\u5b83\u770b\u8d77\u6765\u548c\u5728  step-4  \u4e2d\u5df2\u7ecf\u5c55\u793a\u8fc7\u7684\u5dee\u4e0d\u591a\u4e86\u3002\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// \u6709\u4e86\u8fd9\u4e9b\u4f8b\u5916\u60c5\u51b5\u3002\u5bf9\u4e8e\u6211\u4eec\u7684\u7279\u5f81\u503c\u95ee\u9898\uff0c\u6211\u4eec\u65e2\u9700\u8981\u5de6\u624b\u8fb9\u7684\u521a\u5ea6\u77e9\u9635\uff0c\u4e5f\u9700\u8981\u53f3\u624b\u8fb9\u7684\u8d28\u91cf\u77e9\u9635\u3002\u6211\u4eec\u8fd8\u9700\u8981\u7684\u4e0d\u4ec5\u4ec5\u662f\u4e00\u4e2a\u89e3\u51fd\u6570\uff0c\u800c\u662f\u4e00\u6574\u5957\u6211\u4eec\u60f3\u8981\u8ba1\u7b97\u7684\u7279\u5f81\u51fd\u6570\uff0c\u4ee5\u53ca\u76f8\u5e94\u7684\u7279\u5f81\u503c\u3002\n\n    PETScWrappers::SparseMatrix             stiffness_matrix, mass_matrix; \n    std::vector<PETScWrappers::MPI::Vector> eigenfunctions; \n    std::vector<double>                     eigenvalues; \n\n// \u7136\u540e\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u5bf9\u8c61\u6765\u5b58\u50a8\u51e0\u4e2a\u8fd0\u884c\u65f6\u53c2\u6570\uff0c\u6211\u4eec\u5c06\u5728\u8f93\u5165\u6587\u4ef6\u4e2d\u6307\u5b9a\u3002\n\n    ParameterHandler parameters; \n\n// \u6700\u540e\uff0c\u6211\u4eec\u5c06\u6709\u4e00\u4e2a\u5bf9\u8c61\uff0c\u5305\u542b\u5bf9\u6211\u4eec\u81ea\u7531\u5ea6\u7684 \"\u7ea6\u675f\"\u3002\u5982\u679c\u6211\u4eec\u6709\u81ea\u9002\u5e94\u7ec6\u5316\u7684\u7f51\u683c\uff08\u76ee\u524d\u7684\u7a0b\u5e8f\u4e2d\u6ca1\u6709\uff09\uff0c\u8fd9\u53ef\u80fd\u5305\u62ec\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u3002\u8fd9\u91cc\uff0c\u6211\u4eec\u5c06\u5b58\u50a8\u8fb9\u754c\u8282\u70b9\u7684\u7ea6\u675f  $U_i=0$  \u3002\n\n    AffineConstraints<double> constraints; \n  }; \n// @sect3{Implementation of the <code>EigenvalueProblem</code> class}  \n// @sect4{EigenvalueProblem::EigenvalueProblem}  \n\n// \u9996\u5148\u662f\u6784\u9020\u51fd\u6570\u3002\u4e3b\u8981\u7684\u65b0\u90e8\u5206\u662f\u5904\u7406\u8fd0\u884c\u65f6\u7684\u8f93\u5165\u53c2\u6570\u3002\u6211\u4eec\u9700\u8981\u9996\u5148\u58f0\u660e\u5b83\u4eec\u7684\u5b58\u5728\uff0c\u7136\u540e\u4ece\u8f93\u5165\u6587\u4ef6\u4e2d\u8bfb\u53d6\u5b83\u4eec\u7684\u503c\uff0c\u8be5\u6587\u4ef6\u7684\u540d\u79f0\u88ab\u6307\u5b9a\u4e3a\u8be5\u51fd\u6570\u7684\u53c2\u6570\u3002\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\u7814\u7a76\u4e3a\u4ec0\u4e48\u83b7\u5f97\u6b63\u786e\u7684\u7279\u5f81\u503c\u9000\u5316\u6240\u9700\u7684\u6700\u5c0f\u7ec6\u5316\u6b65\u9aa4\u6570\u4e3a6\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// \u4e0b\u4e00\u4e2a\u51fd\u6570\u5728\u57df $[-1,1]^d$ \u4e0a\u521b\u5efa\u4e00\u4e2a\u7f51\u683c\uff0c\u6839\u636e\u8f93\u5165\u6587\u4ef6\u7684\u8981\u6c42\u5bf9\u5176\u8fdb\u884c\u591a\u6b21\u7ec6\u5316\uff0c\u7136\u540e\u7ed9\u5b83\u9644\u52a0\u4e00\u4e2aDoFHandler\uff0c\u5c06\u77e9\u9635\u548c\u5411\u91cf\u521d\u59cb\u5316\u4e3a\u6b63\u786e\u7684\u5927\u5c0f\u3002\u6211\u4eec\u8fd8\u5efa\u7acb\u4e86\u5bf9\u5e94\u4e8e\u8fb9\u754c\u503c\u7684\u7ea6\u675f  $u|_{\\partial\\Omega}=0$  \u3002\n\n// \u5bf9\u4e8e\u77e9\u9635\uff0c\u6211\u4eec\u4f7f\u7528PETSc\u5305\u88c5\u5668\u3002\u8fd9\u4e9b\u5305\u88c5\u5668\u80fd\u591f\u5728\u975e\u96f6\u6761\u76ee\u88ab\u6dfb\u52a0\u65f6\u5206\u914d\u5fc5\u8981\u7684\u5185\u5b58\u3002\u8fd9\u770b\u8d77\u6765\u6548\u7387\u5f88\u4f4e\uff1a\u6211\u4eec\u53ef\u4ee5\u5148\u8ba1\u7b97\u7a00\u758f\u6a21\u5f0f\uff0c\u7528\u5b83\u6765\u521d\u59cb\u5316\u77e9\u9635\uff0c\u7136\u540e\u5728\u6211\u4eec\u63d2\u5165\u6761\u76ee\u65f6\uff0c\u6211\u4eec\u53ef\u4ee5\u786e\u5b9a\u6211\u4eec\u4e0d\u9700\u8981\u91cd\u65b0\u5206\u914d\u5185\u5b58\u548c\u91ca\u653e\u4e4b\u524d\u4f7f\u7528\u7684\u5185\u5b58\u3002\u4e00\u79cd\u65b9\u6cd5\u662f\u4f7f\u7528\u8fd9\u6837\u7684\u4ee3\u7801\u3002\u7528\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//  \u4ee3\u66ff\u4e0b\u9762\u4e24\u4e2a <code>reinit()</code> \u7684\u521a\u5ea6\u548c\u8d28\u91cf\u77e9\u9635\u7684\u8c03\u7528\u3002\n\n// \u4e0d\u5e78\u7684\u662f\uff0c\u8fd9\u5e76\u4e0d\u5b8c\u5168\u53ef\u884c\u3002\u4e0a\u9762\u7684\u4ee3\u7801\u53ef\u80fd\u4f1a\u5bfc\u81f4\u5728\u975e\u96f6\u6a21\u5f0f\u4e0b\u7684\u4e00\u4e9b\u6761\u76ee\uff0c\u6211\u4eec\u53ea\u5199\u96f6\u6761\u76ee\uff1b\u6700\u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c\u5bf9\u4e8e\u90a3\u4e9b\u5c5e\u4e8e\u8fb9\u754c\u8282\u70b9\u7684\u884c\u548c\u5217\u7684\u975e\u5bf9\u89d2\u7ebf\u6761\u76ee\uff0c\u8fd9\u4e00\u70b9\u662f\u6210\u7acb\u7684\u3002\u8fd9\u4e0d\u5e94\u8be5\u662f\u4e00\u4e2a\u95ee\u9898\uff0c\u4f46\u662f\u4e0d\u7ba1\u4ec0\u4e48\u539f\u56e0\uff0cPETSc\u7684ILU\u9884\u5904\u7406\u7a0b\u5e8f\uff08\u6211\u4eec\u7528\u6765\u89e3\u51b3\u7279\u5f81\u503c\u6c42\u89e3\u5668\u4e2d\u7684\u7ebf\u6027\u7cfb\u7edf\uff09\u4e0d\u559c\u6b22\u8fd9\u4e9b\u989d\u5916\u7684\u6761\u76ee\uff0c\u5e76\u4ee5\u9519\u8bef\u4fe1\u606f\u4e2d\u6b62\u3002\n\n// \u5728\u6ca1\u6709\u4efb\u4f55\u660e\u663e\u7684\u65b9\u6cd5\u6765\u907f\u514d\u8fd9\u79cd\u60c5\u51b5\u7684\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u5e72\u8106\u9009\u62e9\u7b2c\u4e8c\u79cd\u6700\u597d\u7684\u65b9\u6cd5\uff0c\u5373\u8ba9PETSc\u5728\u5fc5\u8981\u65f6\u5206\u914d\u5185\u5b58\u3002\u4e5f\u5c31\u662f\u8bf4\uff0c\u7531\u4e8e\u8fd9\u4e0d\u662f\u4e00\u4e2a\u65f6\u95f4\u4e0a\u7684\u5173\u952e\u90e8\u5206\uff0c\u8fd9\u6574\u4e2a\u4e8b\u4ef6\u5c31\u4e0d\u518d\u91cd\u8981\u4e86\u3002\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// \u4e0b\u4e00\u6b65\u662f\u5904\u7406\u7279\u5f81\u8c31\u7684\u95ee\u9898\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u8f93\u51fa\u662f\u7279\u5f81\u503c\u548c\u7279\u5f81\u51fd\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u7279\u5f81\u51fd\u6570\u548c\u7279\u5f81\u503c\u5217\u8868\u7684\u5927\u5c0f\u8bbe\u7f6e\u4e3a\u4e0e\u6211\u4eec\u5728\u8f93\u5165\u6587\u4ef6\u4e2d\u8981\u6c42\u7684\u4e00\u6837\u5927\u3002\u5f53\u4f7f\u7528 PETScWrappers::MPI::Vector, \u65f6\uff0cVector\u662f\u4f7f\u7528IndexSet\u521d\u59cb\u5316\u7684\u3002IndexSet\u4e0d\u4ec5\u7528\u4e8e\u8c03\u6574 PETScWrappers::MPI::Vector \u7684\u5927\u5c0f\uff0c\u800c\u4e14\u8fd8\u5c06 PETScWrappers::MPI::Vector \u4e2d\u7684\u4e00\u4e2a\u7d22\u5f15\u4e0e\u4e00\u4e2a\u81ea\u7531\u5ea6\u8054\u7cfb\u8d77\u6765\uff08\u66f4\u8be6\u7ec6\u7684\u89e3\u91ca\u89c1 step-40 \uff09\u3002\u51fd\u6570complete_index_set()\u521b\u5efa\u4e86\u4e00\u4e2aIndexSet\uff0c\u6bcf\u4e2a\u6709\u6548\u7684\u7d22\u5f15\u90fd\u662f\u8fd9\u4e2a\u96c6\u5408\u7684\u4e00\u90e8\u5206\u3002\u8bf7\u6ce8\u610f\uff0c\u8fd9\u4e2a\u7a0b\u5e8f\u53ea\u80fd\u6309\u987a\u5e8f\u8fd0\u884c\uff0c\u5982\u679c\u5e76\u884c\u4f7f\u7528\uff0c\u5c06\u629b\u51fa\u4e00\u4e2a\u5f02\u5e38\u3002\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// \u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u4ece\u5c40\u90e8\u8d21\u732e $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)$ \u548c $M^K_{ij} = \\int_K \\varphi_i(\\mathbf x)\\varphi_j(\\mathbf x)$ \u4e2d\u5206\u522b\u7ec4\u5408\u51fa\u5168\u5c40\u521a\u5ea6\u548c\u8d28\u91cf\u77e9\u9635\u3002\u5982\u679c\u4f60\u770b\u8fc7\u4ee5\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\uff0c\u8fd9\u4e2a\u51fd\u6570\u5e94\u8be5\u4f1a\u5f88\u719f\u6089\u3002\u552f\u4e00\u65b0\u7684\u4e1c\u897f\u662f\u4f7f\u7528\u6211\u4eec\u4ece\u8f93\u5165\u6587\u4ef6\u4e2d\u5f97\u5230\u7684\u8868\u8fbe\u5f0f\uff0c\u8bbe\u7f6e\u4e00\u4e2a\u63cf\u8ff0\u52bf $V(\\mathbf x)$ \u7684\u5bf9\u8c61\u3002\u7136\u540e\u6211\u4eec\u9700\u8981\u5728\u6bcf\u4e2a\u5355\u5143\u7684\u6b63\u4ea4\u70b9\u4e0a\u8bc4\u4f30\u8fd9\u4e2a\u5bf9\u8c61\u3002\u5982\u679c\u4f60\u89c1\u8fc7\u5982\u4f55\u8bc4\u4f30\u51fd\u6570\u5bf9\u8c61\uff08\u4f8b\u5982\uff0c\u89c1 step-5 \u4e2d\u7684\u7cfb\u6570\uff09\uff0c\u8fd9\u91cc\u7684\u4ee3\u7801\u4e5f\u4f1a\u663e\u5f97\u76f8\u5f53\u719f\u6089\u3002\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// \u73b0\u5728\u6211\u4eec\u6709\u4e86\u672c\u5730\u77e9\u9635\u7684\u8d21\u732e\uff0c\u6211\u4eec\u628a\u5b83\u4eec\u8f6c\u79fb\u5230\u5168\u5c40\u5bf9\u8c61\u4e2d\uff0c\u5e76\u5904\u7406\u597d\u96f6\u8fb9\u754c\u7ea6\u675f\u3002\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// \u5728\u51fd\u6570\u7684\u6700\u540e\uff0c\u6211\u4eec\u544a\u8bc9PETSc\uff0c\u77e9\u9635\u73b0\u5728\u5df2\u7ecf\u5b8c\u5168\u7ec4\u88c5\u597d\u4e86\uff0c\u7a00\u758f\u77e9\u9635\u8868\u793a\u6cd5\u73b0\u5728\u53ef\u4ee5\u88ab\u538b\u7f29\u4e86\uff0c\u56e0\u4e3a\u4e0d\u4f1a\u518d\u6dfb\u52a0\u4efb\u4f55\u6761\u76ee\u3002\n\n    stiffness_matrix.compress(VectorOperation::add); \n    mass_matrix.compress(VectorOperation::add); \n\n// \u5728\u79bb\u5f00\u51fd\u6570\u4e4b\u524d\uff0c\u6211\u4eec\u8ba1\u7b97\u865a\u5047\u7684\u7279\u5f81\u503c\uff0c\u8fd9\u4e9b\u7279\u5f81\u503c\u662f\u7531\u96f6Dirichlet\u7ea6\u675f\u5f15\u5165\u5230\u7cfb\u7edf\u4e2d\u7684\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u4f7f\u7528Dirichlet\u8fb9\u754c\u6761\u4ef6\uff0c\u52a0\u4e0a\u4f4d\u4e8e\u57df\u7684\u8fb9\u754c\u7684\u81ea\u7531\u5ea6\u4ecd\u7136\u662f\u6211\u4eec\u6240\u6c42\u89e3\u7684\u7ebf\u6027\u7cfb\u7edf\u7684\u4e00\u90e8\u5206\uff0c\u5f15\u5165\u4e86\u4e00\u4e9b\u865a\u5047\u7684\u7279\u5f81\u503c\u3002\u4e0b\u9762\uff0c\u6211\u4eec\u8f93\u51fa\u5b83\u4eec\u6240\u5904\u7684\u533a\u95f4\uff0c\u4ee5\u786e\u4fdd\u6211\u4eec\u5728\u8ba1\u7b97\u4e2d\u51fa\u73b0\u65f6\u53ef\u4ee5\u5ffd\u7565\u5b83\u4eec\u3002\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// \u8fd9\u662f\u8be5\u7a0b\u5e8f\u7684\u5173\u952e\u65b0\u529f\u80fd\u3002\u73b0\u5728\u7cfb\u7edf\u5df2\u7ecf\u8bbe\u7f6e\u597d\u4e86\uff0c\u73b0\u5728\u662f\u5b9e\u9645\u89e3\u51b3\u95ee\u9898\u7684\u597d\u65f6\u673a\uff1a\u548c\u5176\u4ed6\u4f8b\u5b50\u4e00\u6837\uff0c\u8fd9\u662f\u4f7f\u7528 \"\u89e3\u51b3 \"\u7a0b\u5e8f\u6765\u5b8c\u6210\u7684\u3002\u4ece\u672c\u8d28\u4e0a\u8bb2\uff0c\u5b83\u7684\u5de5\u4f5c\u539f\u7406\u4e0e\u5176\u4ed6\u7a0b\u5e8f\u4e00\u6837\uff1a\u4f60\u8bbe\u7f6e\u4e00\u4e2aSolverControl\u5bf9\u8c61\uff0c\u63cf\u8ff0\u6211\u4eec\u8981\u89e3\u51b3\u7684\u7ebf\u6027\u7cfb\u7edf\u7684\u7cbe\u5ea6\uff0c\u7136\u540e\u6211\u4eec\u9009\u62e9\u6211\u4eec\u60f3\u8981\u7684\u89e3\u7b97\u5668\u7c7b\u578b\u3002\u8fd9\u91cc\u6211\u4eec\u9009\u62e9\u4e86SLEPc\u7684Krylov-Schur\u6c42\u89e3\u5668\uff0c\u5bf9\u4e8e\u8fd9\u7c7b\u95ee\u9898\u6765\u8bf4\uff0c\u8fd9\u662f\u4e00\u4e2a\u76f8\u5f53\u5feb\u901f\u548c\u5f3a\u5927\u7684\u9009\u62e9\u3002\n\n  template <int dim> \n  unsigned int EigenvalueProblem<dim>::solve() \n  { \n\n// \u6211\u4eec\u4ece\u8fd9\u91cc\u5f00\u59cb\uff0c\u5c31\u50cf\u6211\u4eec\u901a\u5e38\u505a\u7684\u90a3\u6837\uff0c\u6307\u5b9a\u6211\u4eec\u60f3\u8981\u7684\u6536\u655b\u63a7\u5236\u3002\n\n    SolverControl                    solver_control(dof_handler.n_dofs(), 1e-9); \n    SLEPcWrappers::SolverKrylovSchur eigensolver(solver_control); \n\n// \u5728\u6211\u4eec\u5b9e\u9645\u6c42\u89e3\u7279\u5f81\u51fd\u6570\u548c-\u503c\u4e4b\u524d\uff0c\u6211\u4eec\u8fd8\u5fc5\u987b\u9009\u62e9\u54ea\u4e00\u7ec4\u7279\u5f81\u503c\u6765\u6c42\u89e3\u3002\u8ba9\u6211\u4eec\u9009\u62e9\u90a3\u4e9b\u5b9e\u90e8\u6700\u5c0f\u7684\u7279\u5f81\u503c\u548c\u76f8\u5e94\u7684\u7279\u5f81\u51fd\u6570\uff08\u4e8b\u5b9e\u4e0a\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u89e3\u51b3\u7684\u95ee\u9898\u662f\u5bf9\u79f0\u7684\uff0c\u6240\u4ee5\u7279\u5f81\u503c\u662f\u7eaf\u5b9e\u90e8\u7684\uff09\u3002\u4e4b\u540e\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u771f\u6b63\u8ba9SLEPc\u505a\u5b83\u7684\u5de5\u4f5c\u4e86\u3002\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// \u4e0a\u8ff0\u8c03\u7528\u7684\u8f93\u51fa\u662f\u4e00\u7ec4\u5411\u91cf\u548c\u6570\u503c\u3002\u5728\u7279\u5f81\u503c\u95ee\u9898\u4e2d\uff0c\u7279\u5f81\u51fd\u6570\u53ea\u786e\u5b9a\u5230\u4e00\u4e2a\u5e38\u6570\uff0c\u8fd9\u4e2a\u5e38\u6570\u53ef\u4ee5\u5f88\u968f\u610f\u5730\u56fa\u5b9a\u3002\u7531\u4e8e\u5bf9\u7279\u5f81\u503c\u95ee\u9898\u7684\u539f\u70b9\u4e00\u65e0\u6240\u77e5\uff0cSLEPc\u9664\u4e86\u5c06\u7279\u5f81\u5411\u91cf\u5f52\u4e00\u5230 $l_2$ \uff08\u5411\u91cf\uff09\u51c6\u5219\u5916\uff0c\u6ca1\u6709\u5176\u4ed6\u9009\u62e9\u3002\u4e0d\u5e78\u7684\u662f\uff0c\u8fd9\u4e2a\u89c4\u8303\u4e0e\u6211\u4eec\u4ece\u7279\u5f81\u51fd\u6570\u89d2\u5ea6\u53ef\u80fd\u611f\u5174\u8da3\u7684\u4efb\u4f55\u89c4\u8303\u6ca1\u6709\u4ec0\u4e48\u5173\u7cfb\uff1a $L_2(\\Omega)$ \u89c4\u8303\uff0c\u6216\u8005\u4e5f\u8bb8\u662f $L_\\infty(\\Omega)$ \u89c4\u8303\u3002\n\n//\u8ba9\u6211\u4eec\u9009\u62e9\u540e\u8005\uff0c\u91cd\u65b0\u5212\u5206\u7279\u5f81\u51fd\u6570\u7684\u5c3a\u5ea6\uff0c\u4f7f\u5176\u5177\u6709 $\\|\\phi_i(\\mathbf x)\\|_{L^\\infty(\\Omega)}=1$ \u800c\u4e0d\u662f $\\|\\Phi\\|_{l_2}=1$ \uff08\u5176\u4e2d $\\phi_i$ \u662f $i$ \u7b2c\u4e09\u4e2a\u7279\u5f81<i>function</i>\uff0c $\\Phi_i$ \u662f\u76f8\u5e94\u7684\u7ed3\u70b9\u503c\u77e2\u91cf\uff09\u3002\u5bf9\u4e8e\u8fd9\u91cc\u9009\u62e9\u7684 $Q_1$ \u5143\u7d20\uff0c\u6211\u4eec\u77e5\u9053\u51fd\u6570 $\\phi_i(\\mathbf x)$ \u7684\u6700\u5927\u503c\u662f\u5728\u5176\u4e2d\u4e00\u4e2a\u8282\u70b9\u8fbe\u5230\u7684\uff0c\u6240\u4ee5 $\\max_{\\mathbf x}\\phi_i(\\mathbf x)=\\max_j (\\Phi_i)_j$ \uff0c\u4f7f\u5f97\u5728 $L_\\infty$ \u51c6\u5219\u4e0b\u7684\u5f52\u4e00\u5316\u662f\u5fae\u4e0d\u8db3\u9053\u7684\u3002\u8bf7\u6ce8\u610f\uff0c\u5982\u679c\u6211\u4eec\u9009\u62e9 $Q_k$ \u5143\u7d20\u4e0e $k>1$ \uff0c\u8fd9\u5c31\u4e0d\u5bb9\u6613\u4e86\uff1a\u5728\u90a3\u91cc\uff0c\u4e00\u4e2a\u51fd\u6570\u7684\u6700\u5927\u503c\u4e0d\u4e00\u5b9a\u8981\u5728\u4e00\u4e2a\u8282\u70b9\u4e0a\u8fbe\u5230\uff0c\u6240\u4ee5 $\\max_{\\mathbf x}\\phi_i(\\mathbf x)\\ge\\max_j (\\Phi_i)_j$ \uff08\u5c3d\u7ba1\u5e73\u7b49\u901a\u5e38\u51e0\u4e4e\u662f\u771f\u7684\uff09\u3002\n\n    for (unsigned int i = 0; i < eigenfunctions.size(); ++i) \n      eigenfunctions[i] /= eigenfunctions[i].linfty_norm(); \n\n// \u6700\u540e\u8fd4\u56de\u6536\u655b\u6240\u9700\u7684\u8fed\u4ee3\u6b21\u6570\u3002\n\n    return solver_control.last_step(); \n  } \n// @sect4{EigenvalueProblem::output_results}  \n\n// \u8fd9\u662f\u672c\u7a0b\u5e8f\u7684\u6700\u540e\u4e00\u4e2a\u91cd\u8981\u529f\u80fd\u3002\u5b83\u4f7f\u7528DataOut\u7c7b\u6765\u751f\u6210\u7279\u5f81\u51fd\u6570\u7684\u56fe\u5f62\u8f93\u51fa\uff0c\u4ee5\u4fbf\u4ee5\u540e\u8fdb\u884c\u53ef\u89c6\u5316\u3002\u5b83\u7684\u5de5\u4f5c\u539f\u7406\u4e0e\u5176\u4ed6\u8bb8\u591a\u6559\u7a0b\u4e2d\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\n\n// \u6574\u4e2a\u51fd\u6570\u7684\u96c6\u5408\u88ab\u8f93\u51fa\u4e3a\u4e00\u4e2a\u5355\u4e00\u7684VTK\u6587\u4ef6\u3002\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// \u552f\u4e00\u503c\u5f97\u8ba8\u8bba\u7684\u53ef\u80fd\u662f\uff0c\u7531\u4e8e\u52bf\u5728\u8f93\u5165\u6587\u4ef6\u4e2d\u88ab\u6307\u5b9a\u4e3a\u51fd\u6570\u8868\u8fbe\u5f0f\uff0c\u56e0\u6b64\u6700\u597d\u80fd\u5c06\u5176\u4e0e\u7279\u5f81\u51fd\u6570\u4e00\u8d77\u4ee5\u56fe\u5f62\u5f62\u5f0f\u8868\u793a\u3002\u5b9e\u73b0\u8fd9\u4e00\u76ee\u7684\u7684\u8fc7\u7a0b\u76f8\u5bf9\u7b80\u5355\uff1a\u6211\u4eec\u5efa\u7acb\u4e00\u4e2a\u4ee3\u8868 $V(\\mathbf x)$ \u7684\u5bf9\u8c61\uff0c\u7136\u540e\u5c06\u8fd9\u4e2a\u8fde\u7eed\u51fd\u6570\u63d2\u503c\u5230\u6709\u9650\u5143\u7a7a\u95f4\u3002\u6211\u4eec\u8fd8\u5c06\u7ed3\u679c\u9644\u52a0\u5230DataOut\u5bf9\u8c61\u4e0a\uff0c\u4ee5\u4fbf\u8fdb\u884c\u53ef\u89c6\u5316\u3002\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// \u8fd9\u662f\u4e00\u4e2a\u5bf9\u4e00\u5207\u90fd\u6709\u9876\u5c42\u63a7\u5236\u7684\u51fd\u6570\u3002\u5b83\u51e0\u4e4e\u4e0e  step-4  \u4e2d\u7684\u5185\u5bb9\u5b8c\u5168\u76f8\u540c\u3002\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// \u8fd9\u4e2a\u7a0b\u5e8f\u53ea\u80fd\u5728\u4e32\u884c\u4e2d\u8fd0\u884c\u3002\u5426\u5219\uff0c\u5c06\u629b\u51fa\u4e00\u4e2a\u5f02\u5e38\u3002\n\n      AssertThrow(Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD) == 1, \n                  ExcMessage( \n                    \"This program can only be run in serial, use ./step-36\")); \n\n      EigenvalueProblem<2> problem(\"step-36.prm\"); \n      problem.run(); \n    } \n\n// \u5728\u8fd9\u671f\u95f4\uff0c\u6211\u4eec\u4e00\u76f4\u5728\u6ce8\u610f\u662f\u5426\u6709\u4efb\u4f55\u5f02\u5e38\u5e94\u8be5\u88ab\u751f\u6210\u3002\u5982\u679c\u662f\u8fd9\u6837\u7684\u8bdd\uff0c\u6211\u4eec\u5c31\u4f1a\u60ca\u614c\u5931\u63aa...\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// \u5982\u679c\u6ca1\u6709\u629b\u51fa\u5f02\u5e38\uff0c\u6211\u4eec\u5c31\u544a\u8bc9\u7a0b\u5e8f\u4e0d\u8981\u518d\u80e1\u95f9\u4e86\uff0c\u4e56\u4e56\u5730\u9000\u51fa\u3002\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//\u6761\u4ef6\u304c\u6e80\u305f\u3055\u308c\u3066\u3044\u306a\u3044\u3068\u304d\u306b\u5206\u5c90\u4ee5\u5916\u306e\u547d\u4ee4\u306b\u5230\u9054\u3057\u305f\u3089\u30b9\u30ad\u30c3\u30d7\u3059\u308b\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": "#ifndef SSMPACK_MODEL_LINEAR_GAUSSIAN_HPP\n#define SSMPACK_MODEL_LINEAR_GAUSSIAN_HPP\n\n#include <armadillo>\n\nnamespace ssmkit {\nnamespace map {\n\nstruct LinearGaussian {\n  using TParameter = std::tuple<arma::vec, arma::mat>;\n  using TConditionVAR = arma::vec;\n  \n  LinearGaussian(arma::mat trans, arma::mat cov) : transfer{trans},\n  covariance{cov} {}\n// should not be overloaded, should not be template\n  TParameter operator()(const TConditionVAR &x) const {\n    return std::make_tuple(transfer * x, covariance);\n  }\n\n  arma::mat transfer;\n  arma::mat covariance;\n};\n\n} // namespace map\n} // namespace ssmkit\n\n#endif //SSMPACK_MODEL_LINEAR_GAUSSIAN_HPP\n", "meta": {"hexsha": "7e1e425156eff185de4ebbc6be98151dff7610ed", "size": 651, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ssmkit/map/linear_gaussian.hpp", "max_stars_repo_name": "vahid-bastani/ssmpack", "max_stars_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-08T09:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-10T06:46:55.000Z", "max_issues_repo_path": "src/ssmkit/map/linear_gaussian.hpp", "max_issues_repo_name": "vahidbas/ssmkit", "max_issues_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ssmkit/map/linear_gaussian.hpp", "max_forks_repo_name": "vahidbas/ssmkit", "max_forks_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:46:08.000Z", "avg_line_length": 23.25, "max_line_length": 67, "alphanum_fraction": 0.7403993856, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5901502208026017}}
{"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": "//\n// Copyright \u00a9 2019 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include \"LogSoftmax.hpp\"\n\n#include <TensorUtils.hpp>\n\n#include <cmath>\n\n#include <boost/assert.hpp>\n#include <boost/core/ignore_unused.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n\nnamespace\n{\n\ninline bool ValidateAxis(int axis, unsigned int numDimensions)\n{\n    const int sNumDimensions = boost::numeric_cast<int>(numDimensions);\n    return axis < sNumDimensions && axis >= -sNumDimensions;\n}\n\n} // anonymous namespace\n\nnamespace armnn\n{\n\nvoid LogSoftmax(Decoder<float>& input,\n                Encoder<float>& output,\n                const TensorInfo& inputInfo,\n                const LogSoftmaxDescriptor& descriptor)\n{\n    const unsigned int numDimensions = inputInfo.GetNumDimensions();\n\n    bool axisIsValid = ValidateAxis(descriptor.m_Axis, numDimensions);\n    BOOST_ASSERT_MSG(axisIsValid,\n        \"Axis index is not in range [-numDimensions, numDimensions).\");\n    boost::ignore_unused(axisIsValid);\n\n    unsigned int uAxis = descriptor.m_Axis < 0  ?\n        numDimensions - boost::numeric_cast<unsigned int>(std::abs(descriptor.m_Axis)) :\n        boost::numeric_cast<unsigned int>(descriptor.m_Axis);\n\n    const TensorShape& inputShape = inputInfo.GetShape();\n    const unsigned int outerSize  = armnnUtils::GetNumElementsBetween(inputShape, 0, uAxis);\n    const unsigned int axisSize   = inputShape[uAxis];\n    const unsigned int innerSize  = armnnUtils::GetNumElementsBetween(inputShape,\n                                                                      uAxis + 1,\n                                                                      inputShape.GetNumDimensions());\n\n    for (unsigned int outer = 0; outer < outerSize; ++outer)\n    {\n        for (unsigned int inner = 0; inner < innerSize; ++inner)\n        {\n            // Find max\n            input[outer * axisSize * innerSize + inner];\n            float maxValue = input.Get();\n            for (unsigned int i = 1u; i < axisSize; ++i)\n            {\n                input[(outer * axisSize + i) * innerSize + inner];\n                maxValue = std::max(maxValue, input.Get());\n            }\n\n            // Compute sum\n            float sum = 0.0f;\n            for (unsigned int i = 0u; i < axisSize; ++i)\n            {\n                input[(outer * axisSize + i) * innerSize + inner];\n                sum += std::exp((input.Get() - maxValue) * descriptor.m_Beta);\n            }\n\n            // Compute log sum\n            const float logSum = std::log(sum);\n\n            // Compute result\n            for (unsigned int i = 0u; i < axisSize; ++i)\n            {\n                const unsigned int index = (outer * axisSize + i) * innerSize + inner;\n\n                input [index];\n                output[index];\n\n                output.Set((input.Get() - maxValue) * descriptor.m_Beta - logSum);\n            }\n        }\n    }\n}\n\n} // namespace armnn\n", "meta": {"hexsha": "3fa3dc0d8c0f8e218115e4c363cb0b0e27498b0d", "size": 2914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backends/reference/workloads/LogSoftmax.cpp", "max_stars_repo_name": "vivint-smarthome/armnn", "max_stars_repo_head_hexsha": "6b1bf1a40bebf4cc108d39f8b8e0c29bdfc51ce1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/backends/reference/workloads/LogSoftmax.cpp", "max_issues_repo_name": "vivint-smarthome/armnn", "max_issues_repo_head_hexsha": "6b1bf1a40bebf4cc108d39f8b8e0c29bdfc51ce1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/backends/reference/workloads/LogSoftmax.cpp", "max_forks_repo_name": "vivint-smarthome/armnn", "max_forks_repo_head_hexsha": "6b1bf1a40bebf4cc108d39f8b8e0c29bdfc51ce1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6739130435, "max_line_length": 101, "alphanum_fraction": 0.571379547, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095495, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5901502154547615}}
{"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": "#define BOOST_TEST_MODULE test_lemon\n\n#include <iostream>\n#include <boost/test/unit_test.hpp>\n\n#include <lemon/adaptors.h>\n#include <lemon/bellman_ford.h>\n\n#define private public\n#include \"graph.h\"\n#include \"flowgraph.h\"\n#include \"residualgraph.h\"\n\n\nusing namespace dpct;\n\nBOOST_AUTO_TEST_CASE(pure_lemon)\n{\n    typedef lemon::ListDigraph LGraph;\n    typedef LGraph::Node Node;\n    typedef LGraph::Arc Arc;\n    typedef LGraph::ArcMap<double> DistMap;\n    LGraph g;\n    DistMap dist(g);\n\n    Node s = g.addNode();\n    Node t = g.addNode();\n\n    Node n_1_1 = g.addNode();\n    Node n_1_2 = g.addNode();\n    Node n_2_1 = g.addNode();\n    Node n_2_2 = g.addNode();\n    Node n_2_3 = g.addNode();\n\n    Node d_1_1 = g.addNode();\n    Node d_1_2 = g.addNode();\n\n    Arc app1 = g.addArc(s, n_1_1);\n    dist[app1] = 0.0;\n    Arc app2 = g.addArc(s, n_1_2);\n    dist[app2] = 0.0;\n\n    Arc div1 = g.addArc(s, d_1_1);\n    dist[div1] = -4.0;\n    Arc div2 = g.addArc(s, d_1_2);\n    dist[div2] = -4.0;\n\n    Arc move1 = g.addArc(n_1_1, n_2_1);\n    dist[move1] = -4.0;\n    Arc move2 = g.addArc(n_1_1, n_2_2);\n    dist[move2] = -3.0;\n    Arc move3 = g.addArc(n_1_2, n_2_2);\n    dist[move3] = -1.0;\n    Arc move4 = g.addArc(n_1_2, n_2_3);\n    dist[move4] = -4.0;\n\n    Arc child1 = g.addArc(d_1_1, n_2_1);\n    dist[child1] = -4.0;\n    Arc child2 = g.addArc(d_1_1, n_2_2);\n    dist[child2] = -3.0;\n    Arc child3 = g.addArc(d_1_2, n_2_2);\n    dist[child3] = -1.0;\n    Arc child4 = g.addArc(d_1_2, n_2_3);\n    dist[child4] = -4.0;\n\n    Arc dis1 = g.addArc(n_2_1, t);\n    dist[dis1] = -2.0;\n    Arc dis2 = g.addArc(n_2_2, t);\n    dist[dis2] = -2.0;\n    Arc dis3 = g.addArc(n_2_3, t);\n    dist[dis3] = -4.0;\n\n    // graph adapter to hide the two division arcs\n    LGraph::ArcMap<bool> divisionArcEnabledMap(g);\n    for(LGraph::ArcIt a(g); a != lemon::INVALID; ++a)\n        divisionArcEnabledMap[a] = true;\n    divisionArcEnabledMap[div1] = false;\n    divisionArcEnabledMap[div2] = false;\n\n    typedef lemon::FilterArcs<LGraph> FilteredLGraph;\n    FilteredLGraph filteredG(g, divisionArcEnabledMap);\n\n    // ------------------------------------------------\n    // find shortest path\n    typedef lemon::BellmanFord<FilteredLGraph, DistMap> BellmanFord;\n    BellmanFord bf(filteredG, dist);\n    bf.init();\n    bf.addSource(s);\n\n    if(bf.checkedStart())\n    {\n        std::cout << \"\\n******************************\\n[BellmanFord]: found shortest path at distance \" << bf.dist(t) << std::endl;\n        \n        std::cout << \"Found path is: \";\n        for(Node v = t; v != s; v=bf.predNode(v)) \n        {\n            std::cout << filteredG.id(v) << \"=\" << g.id(v) << \" <- \";\n        }\n        std::cout << filteredG.id(s) << \"=\" << g.id(s) << std::endl;\n    }\n\n    // ------------------------------------------------\n    // build up capacities and residual graph\n    LGraph::ArcMap<int> capacities(g);\n    LGraph::ArcMap<int> flowMap(g);\n    for(LGraph::ArcIt a(g); a != lemon::INVALID; ++a)\n    {\n        capacities[a] = 1;\n        flowMap[a] = 0;\n    }\n\n    for(Arc a = bf.predArc(t); a != lemon::INVALID; a=bf.predArc(g.source(a)))\n    {\n        std::cout << \"setting arc \" << \"(\" << g.id(g.source(a)) << \", \" << g.id(g.target(a)) << \") to contain 1 flow\" << std::endl;\n        flowMap[a] = 1;\n    }\n\n    // update filtered graph to contain the appropriate division now!\n    divisionArcEnabledMap[div2] = true;\n    divisionArcEnabledMap[child4] = false; // cannot use the same child as parent path\n    filteredG = FilteredLGraph(g, divisionArcEnabledMap);\n\n    typedef lemon::ResidualDigraph< FilteredLGraph, LGraph::ArcMap<int>, LGraph::ArcMap<int> > ResidualGraph;\n    typedef ResidualGraph::ArcMap<double> ResidualDistMap;\n\n    // ------------------------------------------------\n    // find shortest path in residual graph and augment flow\n    {\n        ResidualGraph residualG(filteredG, capacities, flowMap);\n        ResidualDistMap residualDist(residualG);\n        for(ResidualGraph::ArcIt a(residualG); a != lemon::INVALID; ++a)\n        {\n            if(residualG.forward(a))\n            {\n                residualDist[a] = dist[lemon::findArc(g, residualG.source(a), residualG.target(a))];\n            }\n            else\n            {\n                residualDist[a] = -1.0 * dist[lemon::findArc(g, residualG.target(a), residualG.source(a))];\n            }\n        }\n\n        std::cout << \"Residual Graph has edges: \" << std::endl;\n        for(ResidualGraph::ArcIt a(residualG); a != lemon::INVALID; ++a)\n        {\n            std::cout << \"(\" << residualG.id(residualG.source(a)) << \", \" << residualG.id(residualG.target(a)) << \") \" \n            << (residualG.forward(a)?\"forward\":\"backward\") \n            << \" cost: \" << residualDist[a]\n            << std::endl;\n        }\n\n        typedef lemon::BellmanFord<ResidualGraph, ResidualDistMap> ResidualBellmanFord;\n        ResidualBellmanFord rbf(residualG, residualDist);\n        rbf.init();\n        rbf.addSource(s);\n\n        if(rbf.checkedStart())\n        {\n            std::cout << \"\\n******************************\\n[ResidualBellmanFord]: found shortest path at distance \" << rbf.dist(t) << std::endl;\n            \n            std::cout << \"Found path is: \";\n            for(Node v = t; v != s; v=rbf.predNode(v)) \n            {\n                std::cout << residualG.id(v) << \"=\" << g.id(v) << \" <- \";\n            }\n            std::cout << residualG.id(s) << \"=\" << g.id(s) << std::endl;\n\n            for(ResidualGraph::Arc a = rbf.predArc(t); a != lemon::INVALID; a=rbf.predArc(residualG.source(a)))\n            {\n                int delta = (residualG.forward(a) ? 1 : -1);\n                flowMap[a] += delta;\n                std::cout << \"setting arc \" << \"(\" << g.id(g.source(a)) << \", \" << g.id(g.target(a))\n                        << \"), delta: \" << delta \n                        << \" new flow: \" << flowMap[a]\n                        << (residualG.forward(a) ? \" forward\" : \" backward\")\n                        << std::endl;\n            }\n        }\n        else\n        {\n            std::cout << \"\\n******************************\\n[ResidualBellmanFord]: found negative weight directed cycle!\" << std::endl;\n            lemon::Path<ResidualGraph> path = rbf.negativeCycle();\n            for(lemon::Path<ResidualGraph>::ArcIt it(path); it != lemon::INVALID; ++it)\n            {\n                std::cout << \"(\" << residualG.id(residualG.source(it)) << \"=\" << g.id(residualG.source(it)) << \", \" << residualG.id(residualG.target(it)) << \"=\" << g.id(residualG.target(it)) << \") \";\n            }\n            std::cout << std::endl;\n        }\n\n        // found path that used division 2 of node 3, so disallow \"unusing\" the parent of the division before the division\n        divisionArcEnabledMap[div2] = true;\n        divisionArcEnabledMap[app2] = false;\n        filteredG = FilteredLGraph(g, divisionArcEnabledMap);\n    }\n    // ------------------------------------------------\n    // again, update flow, should find path s,n_1_1,n_2_1,t (= 0,2,4,1)\n    {\n        ResidualGraph residualG(filteredG, capacities, flowMap);\n        ResidualDistMap residualDist(residualG);\n        for(ResidualGraph::ArcIt a(residualG); a != lemon::INVALID; ++a)\n        {\n            if(residualG.forward(a))\n            {\n                residualDist[a] = dist[lemon::findArc(g, residualG.source(a), residualG.target(a))];\n            }\n            else\n            {\n                residualDist[a] = -1.0 * dist[lemon::findArc(g, residualG.target(a), residualG.source(a))];\n            }\n        }\n\n        std::cout << \"Residual Graph has edges: \" << std::endl;\n        for(ResidualGraph::ArcIt a(residualG); a != lemon::INVALID; ++a)\n        {\n            std::cout << \"(\" << residualG.id(residualG.source(a)) << \", \" << residualG.id(residualG.target(a)) << \") \" \n            << (residualG.forward(a)?\"forward\":\"backward\") \n            << \" cost: \" << residualDist[a]\n            << std::endl;\n        }\n\n        typedef lemon::BellmanFord<ResidualGraph, ResidualDistMap> ResidualBellmanFord;\n        ResidualBellmanFord rbf(residualG, residualDist);\n        rbf.init();\n        rbf.addSource(s);\n\n        if(rbf.checkedStart())\n        {\n            std::cout << \"\\n******************************\\n[ResidualBellmanFord]: found shortest path at distance \" << rbf.dist(t) << std::endl;\n            \n            std::cout << \"Found path is: \";\n            for(Node v = t; v != s; v=rbf.predNode(v)) \n            {\n                std::cout << residualG.id(v) << \"=\" << g.id(v) << \" <- \";\n            }\n            std::cout << residualG.id(s) << \"=\" << g.id(s) << std::endl;\n\n            for(ResidualGraph::Arc a = rbf.predArc(t); a != lemon::INVALID; a=rbf.predArc(residualG.source(a)))\n            {\n                int delta = (residualG.forward(a) ? 1 : -1);\n                flowMap[a] += delta;\n                std::cout << \"setting arc \" << \"(\" << g.id(g.source(a)) << \", \" << g.id(g.target(a))\n                        << \"), delta: \" << delta \n                        << \" new flow: \" << flowMap[a]\n                        << (residualG.forward(a) ? \" forward\" : \" backward\")\n                        << std::endl;\n            }\n        }\n        else\n        {\n            std::cout << \"\\n******************************\\n[ResidualBellmanFord]: found negative weight directed cycle!\" << std::endl;\n            lemon::Path<ResidualGraph> path = rbf.negativeCycle();\n            for(lemon::Path<ResidualGraph>::ArcIt it(path); it != lemon::INVALID; ++it)\n            {\n                std::cout << \"(\" << residualG.id(residualG.source(it)) << \"=\" << g.id(residualG.source(it)) << \", \" << residualG.id(residualG.target(it)) << \"=\" << g.id(residualG.target(it)) << \") \";\n            }\n            std::cout << std::endl;\n        }\n\n        // found path that now enables division 1\n        divisionArcEnabledMap[div1] = true;\n        divisionArcEnabledMap[child1] = false;\n        filteredG = FilteredLGraph(g, divisionArcEnabledMap);\n    }\n\n    // ------------------------------------------------\n    // again, update flow, should find cycle s, d_1_1, n_2_2, d_1_2, s\n    {\n        ResidualGraph residualG(filteredG, capacities, flowMap);\n        ResidualDistMap residualDist(residualG);\n        for(ResidualGraph::ArcIt a(residualG); a != lemon::INVALID; ++a)\n        {\n            if(residualG.forward(a))\n            {\n                residualDist[a] = dist[lemon::findArc(g, residualG.source(a), residualG.target(a))];\n            }\n            else\n            {\n                residualDist[a] = -1.0 * dist[lemon::findArc(g, residualG.target(a), residualG.source(a))];\n            }\n        }\n\n        std::cout << \"Residual Graph has edges: \" << std::endl;\n        for(ResidualGraph::ArcIt a(residualG); a != lemon::INVALID; ++a)\n        {\n            std::cout << \"(\" << residualG.id(residualG.source(a)) << \", \" << residualG.id(residualG.target(a)) << \") \" \n            << (residualG.forward(a)?\"forward\":\"backward\") \n            << \" cost: \" << residualDist[a]\n            << std::endl;\n        }\n\n        typedef lemon::BellmanFord<ResidualGraph, ResidualDistMap> ResidualBellmanFord;\n        ResidualBellmanFord rbf(residualG, residualDist);\n        rbf.init();\n        rbf.addSource(s);\n\n        if(rbf.checkedStart())\n        {\n            if(!rbf.reached(t))\n            {\n                std::cout << \">>>>>> Finished!\" << std::endl;\n                return;\n            }\n\n            std::cout << \"\\n******************************\\n[ResidualBellmanFord]: found shortest path at distance \" << rbf.dist(t) << std::endl;\n            \n            std::cout << \"Found path is: \";\n            for(Node v = t; v != s; v=rbf.predNode(v)) \n            {\n                std::cout << residualG.id(v) << \"=\" << g.id(v) << \" <- \";\n            }\n            std::cout << residualG.id(s) << \"=\" << g.id(s) << std::endl;\n\n            for(ResidualGraph::Arc a = rbf.predArc(t); a != lemon::INVALID; a=rbf.predArc(residualG.source(a)))\n            {\n                int delta = (residualG.forward(a) ? 1 : -1);\n                flowMap[a] += delta;\n                std::cout << \"setting arc \" << \"(\" << g.id(g.source(a)) << \", \" << g.id(g.target(a))\n                        << \"), delta: \" << delta \n                        << \" new flow: \" << flowMap[a]\n                        << (residualG.forward(a) ? \" forward\" : \" backward\")\n                        << std::endl;\n            }\n        }\n        else\n        {\n            std::cout << \"\\n******************************\\n[ResidualBellmanFord]: found negative weight directed cycle!\" << std::endl;\n            lemon::Path<ResidualGraph> path = rbf.negativeCycle();\n            for(lemon::Path<ResidualGraph>::ArcIt it(path); it != lemon::INVALID; ++it)\n            {\n                int delta = (residualG.forward(it) ? 1 : -1);\n                flowMap[lemon::findArc(g, residualG.target(it), residualG.source(it))] += delta;\n                std::cout << \"(\" << residualG.id(residualG.source(it)) << \"=\" << g.id(residualG.source(it)) << \", \" << residualG.id(residualG.target(it)) << \"=\" << g.id(residualG.target(it)) \n                        << \"), delta: \" << delta \n                        << \" new flow: \" << flowMap[lemon::findArc(g, residualG.target(it), residualG.source(it))]\n                        << (residualG.forward(it) ? \" forward\" : \" backward\")\n                        << std::endl;\n            }\n        }\n\n        // flow has been redirected to use cheaper path\n        // but we still have to re-enable the move from\n        divisionArcEnabledMap[app2] = true;\n        filteredG = FilteredLGraph(g, divisionArcEnabledMap);\n    }\n\n    // ------------------------------------------------\n    // again, but there shouldn't be any paths left\n    {\n        ResidualGraph residualG(filteredG, capacities, flowMap);\n        ResidualDistMap residualDist(residualG);\n        for(ResidualGraph::ArcIt a(residualG); a != lemon::INVALID; ++a)\n        {\n            if(residualG.forward(a))\n            {\n                residualDist[a] = dist[lemon::findArc(g, residualG.source(a), residualG.target(a))];\n            }\n            else\n            {\n                residualDist[a] = -1.0 * dist[lemon::findArc(g, residualG.target(a), residualG.source(a))];\n            }\n        }\n\n        std::cout << \"Residual Graph has edges: \" << std::endl;\n        for(ResidualGraph::ArcIt a(residualG); a != lemon::INVALID; ++a)\n        {\n            std::cout << \"(\" << residualG.id(residualG.source(a)) << \", \" << residualG.id(residualG.target(a)) << \") \" \n            << (residualG.forward(a)?\"forward\":\"backward\") \n            << \" cost: \" << residualDist[a]\n            << std::endl;\n        }\n\n        typedef lemon::BellmanFord<ResidualGraph, ResidualDistMap> ResidualBellmanFord;\n        ResidualBellmanFord rbf(residualG, residualDist);\n        rbf.init();\n        rbf.addSource(s);\n\n        if(rbf.checkedStart())\n        {\n            if(!rbf.reached(t))\n            {\n                std::cout << \">>>>>> Finished!\" << std::endl;\n                return;\n            }\n\n            std::cout << \"\\n******************************\\n[ResidualBellmanFord]: found shortest path at distance \" << rbf.dist(t) << std::endl;\n            \n            std::cout << \"Found path is: \";\n            for(Node v = t; v != s; v=rbf.predNode(v)) \n            {\n                std::cout << residualG.id(v) << \"=\" << g.id(v) << \" <- \";\n            }\n            std::cout << residualG.id(s) << \"=\" << g.id(s) << std::endl;\n\n            for(ResidualGraph::Arc a = rbf.predArc(t); a != lemon::INVALID; a=rbf.predArc(residualG.source(a)))\n            {\n                int delta = (residualG.forward(a) ? 1 : -1);\n                flowMap[a] += delta;\n                std::cout << \"setting arc \" << \"(\" << g.id(g.source(a)) << \", \" << g.id(g.target(a))\n                        << \"), delta: \" << delta \n                        << \" new flow: \" << flowMap[a]\n                        << (residualG.forward(a) ? \" forward\" : \" backward\")\n                        << std::endl;\n            }\n        }\n        else\n        {\n            std::cout << \"\\n******************************\\n[ResidualBellmanFord]: found negative weight directed cycle!\" << std::endl;\n            lemon::Path<ResidualGraph> path = rbf.negativeCycle();\n            for(lemon::Path<ResidualGraph>::ArcIt it(path); it != lemon::INVALID; ++it)\n            {\n                int delta = (residualG.forward(it) ? 1 : -1);\n                std::cout << \"(\" << residualG.id(residualG.source(it)) << \"=\" << g.id(residualG.source(it)) << \", \" << residualG.id(residualG.target(it)) << \"=\" << g.id(residualG.target(it)) << \") \";\n                flowMap[lemon::findArc(g, residualG.source(it), residualG.target(it))] += delta;\n            }\n            std::cout << std::endl;\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE( flowgraph_simple )\n{\n    FlowGraph g;\n    typedef FlowGraph::FullNode Node;\n    typedef FlowGraph::Arc Arc;\n\n    Node n_1_1 = g.addNode({0.0});\n    Node n_1_2 = g.addNode({0.0});\n    Node n_1_3 = g.addNode({0.0});\n    Node n_2_1 = g.addNode({0.0});\n    Node n_2_2 = g.addNode({0.0});\n    Node n_2_3 = g.addNode({0.0});\n\n    FlowGraph::Node s = g.getSource();\n    FlowGraph::Node t = g.getTarget();\n\n    Arc app1 = g.addArc(s, n_1_1.u, {0.0});\n    Arc app2 = g.addArc(s, n_1_2.u, {0.0});\n    Arc app3 = g.addArc(s, n_2_1.u, {10.0});\n    Arc app4 = g.addArc(s, n_2_2.u, {10.0});\n    Arc app5 = g.addArc(s, n_2_3.u, {10.0});\n    Arc app6 = g.addArc(s, n_1_3.u, {0.0});\n\n    Arc move1 = g.addArc(n_1_1, n_2_1, {-4.0});\n    Arc move2 = g.addArc(n_1_1, n_2_2, {-3.0});\n    Arc move3 = g.addArc(n_1_2, n_2_2, {-1.0});\n    Arc move4 = g.addArc(n_1_2, n_2_3, {-4.0});\n    Arc move5 = g.addArc(n_1_3, n_2_3, {2.0});\n\n    Arc dis1 = g.addArc(n_2_1.v, t, {-2.0});\n    Arc dis2 = g.addArc(n_2_2.v, t, {-2.0});\n    Arc dis3 = g.addArc(n_2_3.v, t, {-4.0});\n    Arc dis4 = g.addArc(n_1_1.v, t, {10.0});\n    Arc dis5 = g.addArc(n_1_2.v, t, {10.0});\n    Arc dis6 = g.addArc(n_1_3.v, t, {-1.0});\n\n    Arc div1 = g.allowMitosis(n_1_1, {-4.0});\n    Arc div2 = g.allowMitosis(n_1_2, {-4.0});\n\n    g.maxFlowMinCostTracking();\n\n    BOOST_CHECK_EQUAL(g.getFlowMap()[app1], 1);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[app2], 1);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[app3], 0);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[app4], 0);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[app5], 0);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[app6], 1);\n\n    BOOST_CHECK_EQUAL(g.getFlowMap()[dis1], 1);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[dis2], 1);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[dis3], 1);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[dis4], 0);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[dis5], 0);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[dis6], 1);\n\n    BOOST_CHECK_EQUAL(g.getFlowMap()[div1], 1);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[div2], 0);\n\n    BOOST_CHECK_EQUAL(g.getFlowMap()[move1], 1);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[move2], 1);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[move3], 0);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[move4], 1);\n    BOOST_CHECK_EQUAL(g.getFlowMap()[move5], 0);\n}\n\n/*\nThe following test cannot work as long as we use the alternative way of checking for tokens on a path\n\nBOOST_AUTO_TEST_CASE( tokenizedbellmanford_have_tokens )\n{\n    FlowGraph g;\n    typedef FlowGraph::FullNode Node;\n    typedef FlowGraph::Arc Arc;\n\n    Node n_1_1 = g.addNode({0.0});\n    Node n_2_1 = g.addNode({0.0});\n    Node n_2_2 = g.addNode({0.0});\n\n    FlowGraph::Node s = g.getSource();\n    FlowGraph::Node t = g.getTarget();\n\n    Arc app1 = g.addArc(s, n_1_1.u, {0.0});\n    \n    Arc move1 = g.addArc(n_1_1, n_2_1, {-4.0});\n    Arc move2 = g.addArc(n_1_1, n_2_2, {-3.0});\n    \n    Arc dis1 = g.addArc(n_2_1.v, t, {-2.0});\n    Arc dis2 = g.addArc(n_2_2.v, t, {-2.0});\n    \n    const FlowGraph::Graph& baseGraph = g.getGraph();\n    ResidualGraph rg(baseGraph);\n\n    // only enable forward arcs, we just want a simple scenario to check whether token collection works\n    for(FlowGraph::Graph::ArcIt a(baseGraph); a != lemon::INVALID; ++a)\n    {\n        rg.updateArc(a, ResidualGraph::Forward, g.getArcCost(a, 0), 1);\n    }\n\n    size_t tokenId = 12;\n    rg.addProvidedToken(app1, ResidualGraph::Forward, tokenId);\n    rg.addForbiddenToken(move1, ResidualGraph::Forward, tokenId);\n\n    ResidualGraph::ShortestPathResult sp = rg.findShortestPath(s, t);\n    BOOST_CHECK(sp.second < 0); // check that we found an augmenting path\n    g.printPath(sp.first);\n    \n    // make sure we did not go along forbidden move1 arc\n    for(auto arcFlowPair : sp.first)\n    {\n        BOOST_CHECK(arcFlowPair.first != move1);\n    }\n\n    // try again, this time without forbidding the provided token\n    rg.removeForbiddenToken(move1, ResidualGraph::Forward, tokenId);\n    sp = rg.findShortestPath(s, t);\n    BOOST_CHECK(sp.second < 0); // check that we found an augmenting path\n    g.printPath(sp.first);\n    \n    // make sure we did not go along move2 arc, because move1 is cheaper now\n    for(auto arcFlowPair : sp.first)\n    {\n        BOOST_CHECK(arcFlowPair.first != move2);\n    }\n}\n*/", "meta": {"hexsha": "d6e8675ed99b6df57b59e5313bfdad6f03442fb0", "size": 21046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_lemon.cpp", "max_stars_repo_name": "ilastik/dpct", "max_stars_repo_head_hexsha": "59f553d917ef257c3e4c230752979263db7a57e1", "max_stars_repo_licenses": ["MIT"], "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_lemon.cpp", "max_issues_repo_name": "ilastik/dpct", "max_issues_repo_head_hexsha": "59f553d917ef257c3e4c230752979263db7a57e1", "max_issues_repo_licenses": ["MIT"], "max_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_lemon.cpp", "max_forks_repo_name": "ilastik/dpct", "max_forks_repo_head_hexsha": "59f553d917ef257c3e4c230752979263db7a57e1", "max_forks_repo_licenses": ["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.6875, "max_line_length": 199, "alphanum_fraction": 0.5212867053, "num_tokens": 5902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5901502047598848}}
{"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": "#include <Eigen/Dense>\n#include <iostream>\n#include \"string_aligner.h\"\n\nint main(int argc, char* argv[]) {\n    if (argc != 3) {\n        std::cerr << \"Error: two strings expected as arguments\" << std::endl;\n        std::exit(1);\n    }\n    std::string str1(argv[1]);\n    std::string str2(argv[2]);\n    Matrix_t scoring_matrix(4, 4);\n    const std::string alphabet(\"ACGT\");\n    scoring_matrix <<  2, -1,  1, -1,\n                      -1,  2, -1,  1,\n                       1, -1,  2, -1,\n                      -1,  1, -1,  2;\n    const int gap_socre {-2};\n    StringAligner aligner(alphabet, scoring_matrix, gap_socre);\n    auto [aligned1, aligned2] = aligner.align(str1, str2);\n    std::cout << aligned1 << \"\\n\"\n              << aligned2 << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "b268e01fcbb6125adab1af51d3bbb181533287f4", "size": 766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Eigen/StringAlignment/main.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/StringAlignment/main.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/StringAlignment/main.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": 30.64, "max_line_length": 77, "alphanum_fraction": 0.5248041775, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5901208780162192}}
{"text": "#include <Eigen/Sparse>\n#include <iostream>\n\nint main()\n{\n\tEigen::SparseVector<double> vec(10);\n\tvec.insert(2) = 23;\n\tvec.insert(5) = 13.5;\n\tstd::cout << vec << std::endl;\n\n\tEigen::SparseMatrix<double> mat(10, 10);\n\tmat.insert(2, 4) = 2.4;\n\tmat.insert(5, 1) = 3.53;\n\tstd::cout << mat << std::endl;\n\n}", "meta": {"hexsha": "ac9c2f569a16fde1c707441bac8501ea36b893b4", "size": 300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/analysis/testSparse.cpp", "max_stars_repo_name": "TING2938/Gmx2020PostAnalysis", "max_stars_repo_head_hexsha": "0859383946c05c7424adb1ffa72fd2f8066ce850", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-23T15:02:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T16:32:09.000Z", "max_issues_repo_path": "src/analysis/testSparse.cpp", "max_issues_repo_name": "jianghuili/Gmx2020PostAnalysis", "max_issues_repo_head_hexsha": "0859383946c05c7424adb1ffa72fd2f8066ce850", "max_issues_repo_licenses": ["MIT"], "max_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/testSparse.cpp", "max_forks_repo_name": "jianghuili/Gmx2020PostAnalysis", "max_forks_repo_head_hexsha": "0859383946c05c7424adb1ffa72fd2f8066ce850", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-23T15:01:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T15:01:49.000Z", "avg_line_length": 18.75, "max_line_length": 41, "alphanum_fraction": 0.6133333333, "num_tokens": 108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.590098273085321}}
{"text": "\n#include <gtest/gtest.h>\n#include \"../util/util.h\"\n#include <Eigen/Core>\n#include <string>\n#include <algorithm>\n\n#ifndef _MSC_VER\nextern \"C\" {\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#include <csim/update_ops.h>\n#include <csim/init_ops.h>\n}\n#else\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#include <csim/update_ops.h>\n#include <csim/init_ops.h>\n#endif\n#include <csim/update_ops_cpp.hpp>\n\n\nTEST(UpdateTest, SingleQubitPauliTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tUINT target, pauli;\n\n\tEigen::MatrixXcd Identity(2, 2);\n\tIdentity << 1, 0, 0, 1;\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\t/* single qubit Pauli gate */\n\t\ttarget = rand_int(n);\n\t\tpauli = rand_int(4);\n\t\tsingle_qubit_Pauli_gate(target, pauli, state, dim);\n\t\ttest_state = get_expanded_eigen_matrix_with_identity(target, get_eigen_matrix_single_Pauli(pauli), n) * test_state;\n\t\tstate_equal(state, test_state, dim, \"single Pauli gate\");\n\t}\n\trelease_quantum_state(state);\n}\n\nTEST(UpdateTest, SingleQubitPauliRotationTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tUINT target, pauli;\n\tdouble angle;\n\n\tEigen::MatrixXcd Identity(2, 2);\n\tIdentity << 1, 0, 0, 1;\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\ttarget = rand_int(n);\n\t\tpauli = rand_int(3) + 1;\n\t\tangle = rand_real();\n\t\tsingle_qubit_Pauli_rotation_gate(target, pauli, angle, state, dim);\n\t\ttest_state = get_expanded_eigen_matrix_with_identity(target, cos(angle / 2)*Identity + 1.i * sin(angle / 2) * get_eigen_matrix_single_Pauli(pauli), n) * test_state;\n\t\tstate_equal(state, test_state, dim, \"single rotation Pauli gate\");\n\t}\n\trelease_quantum_state(state);\n}\n\nTEST(UpdateTest, MultiQubitPauliTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tUINT pauli;\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\t// multi pauli whole\n\t\tstd::vector<UINT> pauli_whole, pauli_partial, pauli_partial_index;\n\t\tstd::vector<std::pair<UINT, UINT>> pauli_partial_pair;\n\n\t\tpauli_whole.resize(n);\n\t\tfor (UINT i = 0; i < n; ++i) {\n\t\t\tpauli_whole[i] = rand_int(4);\n\t\t}\n\t\tmulti_qubit_Pauli_gate_whole_list(pauli_whole.data(), n, state, dim);\n\t\ttest_state = get_eigen_matrix_full_qubit_pauli(pauli_whole) * test_state;\n\t\tstate_equal(state, test_state, dim, \"multi Pauli whole gate\");\n\n\t\t// multi pauli partial\n\t\tpauli_partial.clear();\n\t\tpauli_partial_index.clear();\n\t\tpauli_partial_pair.clear();\n\t\tfor (UINT i = 0; i < n; ++i) {\n\t\t\tpauli = rand_int(4);\n\t\t\tpauli_whole[i] = pauli;\n\t\t\tif (pauli != 0) {\n\t\t\t\tpauli_partial_pair.push_back(std::make_pair(i, pauli));\n\t\t\t}\n\t\t}\n\t\tstd::random_shuffle(pauli_partial_pair.begin(), pauli_partial_pair.end());\n\t\tfor (auto val : pauli_partial_pair) {\n\t\t\tpauli_partial_index.push_back(val.first);\n\t\t\tpauli_partial.push_back(val.second);\n\t\t}\n\t\tmulti_qubit_Pauli_gate_partial_list(pauli_partial_index.data(), pauli_partial.data(), (UINT)pauli_partial.size(), state, dim);\n\t\ttest_state = get_eigen_matrix_full_qubit_pauli(pauli_whole) * test_state;\n\t\tstate_equal(state, test_state, dim, \"multi Pauli partial gate\");\n\t}\n\trelease_quantum_state(state);\n}\n\nTEST(UpdateTest, MultiQubitPauliRotationTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tUINT pauli;\n\tdouble angle;\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\tEigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\n\t\tstd::vector<UINT> pauli_whole, pauli_partial, pauli_partial_index;\n\t\tstd::vector<std::pair<UINT, UINT>> pauli_partial_pair;\n\n\t\t// multi pauli rotation whole\n\t\tpauli_whole.resize(n);\n\t\tfor (UINT i = 0; i < n; ++i) {\n\t\t\tpauli_whole[i] = rand_int(4);\n\t\t}\n\t\tangle = rand_real();\n\t\tmulti_qubit_Pauli_rotation_gate_whole_list(pauli_whole.data(), n, angle, state, dim);\n\t\ttest_state = (cos(angle / 2)*whole_I + 1.i * sin(angle / 2)* get_eigen_matrix_full_qubit_pauli(pauli_whole)) * test_state;\n\t\tstate_equal(state, test_state, dim, \"multi Pauli rotation whole gate\");\n\n\t\t// multi pauli rotation partial\n\t\tpauli_partial.clear();\n\t\tpauli_partial_index.clear();\n\t\tpauli_partial_pair.clear();\n\t\tfor (UINT i = 0; i < n; ++i) {\n\t\t\tpauli = rand_int(4);\n\t\t\tpauli_whole[i] = pauli;\n\t\t\tif (pauli != 0) {\n\t\t\t\tpauli_partial_pair.push_back(std::make_pair(i, pauli));\n\t\t\t}\n\t\t}\n\t\tstd::random_shuffle(pauli_partial_pair.begin(), pauli_partial_pair.end());\n\t\tfor (auto val : pauli_partial_pair) {\n\t\t\tpauli_partial_index.push_back(val.first);\n\t\t\tpauli_partial.push_back(val.second);\n\t\t}\n\t\tangle = rand_real();\n\t\tmulti_qubit_Pauli_rotation_gate_partial_list(pauli_partial_index.data(), pauli_partial.data(), (UINT)pauli_partial.size(), angle, state, dim);\n\t\ttest_state = (cos(angle / 2)*whole_I + 1.i * sin(angle / 2)* get_eigen_matrix_full_qubit_pauli(pauli_whole)) * test_state;\n\t\tstate_equal(state, test_state, dim, \"multi Pauli rotation partial gate\");\n\t}\n\trelease_quantum_state(state);\n}\n", "meta": {"hexsha": "d556bfbdbf24cc05e4e434386530209baa12babe", "size": 5710, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/csim/test_update_pauli.cpp", "max_stars_repo_name": "kamakiri01/qulacs", "max_stars_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 260.0, "max_stars_repo_stars_event_min_datetime": "2018-10-13T15:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T11:03:58.000Z", "max_issues_repo_path": "test/csim/test_update_pauli.cpp", "max_issues_repo_name": "kamakiri01/qulacs", "max_issues_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 182.0, "max_issues_repo_issues_event_min_datetime": "2018-10-14T02:29:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:23:18.000Z", "max_forks_repo_path": "test/csim/test_update_pauli.cpp", "max_forks_repo_name": "kamakiri01/qulacs", "max_forks_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 88.0, "max_forks_repo_forks_event_min_datetime": "2018-10-10T03:46:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T21:56:05.000Z", "avg_line_length": 32.0786516854, "max_line_length": 166, "alphanum_fraction": 0.7133099825, "num_tokens": 1771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5900973921506985}}
{"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": "/* test_triangle.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/triangle_distribution.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/math/distributions/triangular.hpp>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::triangle_distribution<>\r\n#define BOOST_RANDOM_DISTRIBUTION_NAME lognormal\r\n#define BOOST_MATH_DISTRIBUTION boost::math::triangular\r\n#define BOOST_RANDOM_ARG1_TYPE double\r\n#define BOOST_RANDOM_ARG1_NAME b\r\n#define BOOST_RANDOM_ARG1_DEFAULT 0.5\r\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(0.0001, 0.9999)\r\n#define BOOST_RANDOM_DISTRIBUTION_INIT (0.0, b, 1.0)\r\n#define BOOST_MATH_DISTRIBUTION_INIT (0.0, b, 1.0)\r\n\r\n#include \"test_real_distribution.ipp\"\r\n", "meta": {"hexsha": "fdc2f5df55d12843389a1c2d3a4e9973b95063b4", "size": 912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_triangle.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/random/test/test_triangle.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/random/test/test_triangle.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": 33.7777777778, "max_line_length": 80, "alphanum_fraction": 0.7763157895, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5900973866600919}}
{"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": "\n//#define BOOST_NUMERIC_BINDINGS_LAPACK_2\n\n#include <cstddef>\n#include <iostream>\n#include <algorithm> \n#include <complex>\n#include <boost/numeric/bindings/lapack/gesdd.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/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::cout;\nusing std::endl; \n\ntypedef double real_t; \ntypedef std::complex<real_t> cmplx_t; \ntypedef ublas::matrix<cmplx_t, ublas::column_major> m_t;\ntypedef ublas::vector<cmplx_t> v_t;\ntypedef ublas::matrix<real_t, ublas::column_major> rm_t;\ntypedef ublas::vector<real_t> rv_t;\n\nint main() {\n\n  cout << endl; \n\n  size_t m = 1, n = 3;   \n  size_t minmn = m < n ? m : n; \n  m_t a (m, n);  \n  a(0,0) = cmplx_t (2, -1);\n  a(0,1) = cmplx_t (1, 1);\n  a(0,2) = cmplx_t (-2, 0);\n\n  m_t a2 (a); // for part 2\n  m_t a3 (a); // for part 3\n\n  print_m (a, \"A\"); \n  cout << endl; \n\n  rv_t s (minmn); // singular values are real \n  m_t u (m, m);\n  m_t vt (n, n);\n\n  size_t lw; \n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_2\n  lw = lapack::gesdd_work ('O', 'N', a); \n  cout << \"opt N lw: \" << lw << endl; \n  lw = lapack::gesdd_work ('O', 'A', a); \n  cout << \"opt A lw: \" << lw << endl; \n  lw = lapack::gesdd_work ('O', 'S', a); \n  cout << \"opt S lw: \" << lw << endl; \n  lw = lapack::gesdd_work ('O', 'O', a); \n  cout << \"opt O lw: \" << lw << endl; \n#endif \n  lw = lapack::gesdd_work ('M', 'A', a); \n  cout << \"min lw: \" << lw << endl << endl; \n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_2\n  lw = lapack::gesdd_work ('O', 'A', a); \n#endif \n\n  std::vector<cmplx_t> w (lw); \n\n  size_t lrw = lapack::gesdd_rwork ('A', a);\n  cout << \"lrw: \" << lrw << endl << endl; \n  std::vector<real_t> rw (lrw);\n\n  size_t liw = lapack::gesdd_iwork (a);\n  cout << \"liw: \" << liw << endl << endl; \n  std::vector<int> iw (liw);\n\n  lapack::gesdd ('A', a, s, u, vt, w, rw, iw);\n\n  print_v (s, \"s\"); \n  cout << endl; \n  print_m (u, \"U\"); \n  cout << endl; \n  print_m (vt, \"V^T\"); \n  cout << endl; \n\n  rm_t sm (m, n); \n  for (size_t i = 0; i < s.size(); ++i) \n    sm (i,i) = s (i); \n  print_m (sm, \"S\"); \n  cout << endl;\n\n  a = ublas::prod (u, m_t (ublas::prod (sm, vt))); \n  print_m (a, \"A == U S V^T\"); \n  cout << endl; \n\n  // part 2 \n\n  cout << endl << \"part 2\" << endl << endl; \n \n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_2\n  lapack::gesdd ('A', a2, s, u, vt);  \n#else\n  lapack::gesdd ('M', 'A', a2, s, u, vt);  \n#endif\n\n  print_v (s, \"s\"); \n  cout << endl; \n  print_m (u, \"U\"); \n  cout << endl; \n  print_m (vt, \"V^T\"); \n  cout << endl; \n\n  for (size_t i = 0; i < s.size(); ++i) \n    sm (i,i) = s (i); \n  print_m (sm, \"S\"); \n  cout << endl;\n\n  a2 = ublas::prod (u, m_t (ublas::prod (sm, vt))); \n  print_m (a2, \"A == U S V^T\"); \n  cout << endl;\n\n  // part 3\n\n  cout << endl << \"part 3\" << endl << endl;\n \n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_2\n  cout << \"opt lw: \" << lapack::gesdd_work ('O', 'N', a3) << endl << endl; \n  lapack::gesdd (a3, s);\n#else \n  cout << \"min lw: \" << lapack::gesdd_work ('M', 'N', a3) << endl << endl; \n  lapack::gesdd ('M', 'N', a3, s, u, vt);\n#endif \n\n  print_v (s, \"singular value only\"); \n  cout << endl; \n\n  cout << endl; \n}\n\n", "meta": {"hexsha": "d52e721653eed7aab7ac29e76ca0278982d2969a", "size": 3294, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libs/numeric/bindings/lapack/test/ublas_gesdd2.cc", "max_stars_repo_name": "inducer/boost-numeric-bindings", "max_stars_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "libs/numeric/bindings/lapack/test/ublas_gesdd2.cc", "max_issues_repo_name": "inducer/boost-numeric-bindings", "max_issues_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/bindings/lapack/test/ublas_gesdd2.cc", "max_forks_repo_name": "inducer/boost-numeric-bindings", "max_forks_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 23.3617021277, "max_line_length": 75, "alphanum_fraction": 0.5655737705, "num_tokens": 1264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5900886361089115}}
{"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": "///////////////////////////////////////////////////////////////////////////////\n//                                                                           //\n//                          *** w90.hpp ***                                  //\n//                                                                           //\n// class to manage methods relating to wannier90 hamiltonian                 //\n// templatized over dimension of the mesh                                    //\n//                                                                           //\n// created November 27, 2017                                                 //\n// copyright Christopher N. Singh Binghamton University Physics              //\n//                                                                           //\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef W90_hpp\n#define W90_hpp\n\n#include <cassert>\n#include <Eigen/Dense>\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <vector>\n\nclass W90\n{\npublic:\n\tW90(std::string hr_file) {\n\t\t\n\t\tstd::ifstream file(hr_file);\n\t\tassert(file.is_open());\n\n\t\tstd::string line;\n\t\tdouble data;\n\t\tstd::vector<double> v;\n\n\t\twhile (std::getline(file, line)) {\n\t\t\tstd::stringstream input(line);\n\t\t\tfor (int i = 0; i < 7; ++i) {\n\t\t\t\tinput >> data;\n\t\t\t\tv.push_back(data);\n\t\t\t}\n\t\t}\n\n\t\thr = Eigen::Map<Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, \n\t\t   Eigen::RowMajor> >(&v[0], v.size()/7, 7);\n\t}\n\n\tEigen::MatrixXcd fft(const Eigen::Vector3d& k) {\n\n\t\tint dimension = hr.col(3).maxCoeff();\n\t\tEigen::MatrixXcd h = Eigen::MatrixXcd::Zero(dimension, dimension);\n\n\t\tfor (int nn = 0; nn < hr.rows(); ++nn) {\n\t\t\th((int)hr(nn, 3)-1, (int)hr(nn, 4)-1) += tij(nn, k);\n\t\t}\n\n\t\treturn h;\n\t}\n\nprivate:\n\tEigen::ArrayXXd hr;\n\t\n\tinline std::complex<double> tij(int nn, const Eigen::Vector3d& k) {\n\t\t\n\t\tstd::complex<double> i(0, 1);\n\t\tstd::complex<double> hopping(hr(nn, 5), hr(nn, 6));\n\t\tstd::complex<double> phase;\n\n\t\tphase = exp(i * (k(0)*hr(nn, 0) + k(1)*hr(nn,1) + k(2)*hr(nn, 2)));\n\n\t\treturn hopping * phase;\t\n\t}\n};\n\n\n#endif /* W90_hpp */\n", "meta": {"hexsha": "b761b09423bc90558052ff61a816d43ab569e0b3", "size": 2109, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/W90.hpp", "max_stars_repo_name": "csingh5/TBkit", "max_stars_repo_head_hexsha": "3b6c51a5f7f1efd1ef102872eeea5f2c25ef2244", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/W90.hpp", "max_issues_repo_name": "csingh5/TBkit", "max_issues_repo_head_hexsha": "3b6c51a5f7f1efd1ef102872eeea5f2c25ef2244", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/W90.hpp", "max_forks_repo_name": "csingh5/TBkit", "max_forks_repo_head_hexsha": "3b6c51a5f7f1efd1ef102872eeea5f2c25ef2244", "max_forks_repo_licenses": ["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.75, "max_line_length": 79, "alphanum_fraction": 0.4295874822, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5900788336217712}}
{"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": "/*\n * Copyright 2019 Denis Yaroshevskiy\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 \"algo/factoriadic_representation.h\"\n\n#include <algorithm>\n#include <array>\n#include <numeric>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"test/catch.h\"\n\nnamespace algo {\nnamespace {\n\nusing big_int = boost::multiprecision::cpp_int;\n\nstruct FailCompilation {};\n\ntemplate <size_t N>\nconstexpr bool test_factoriadic(int value, std::array<int, N> expected) {\n  if (compute_factoriadic_representation_length(value) != N) {\n    throw FailCompilation{};\n  }\n  std::array<int, N> actual = {};\n  to_factoriadic_representation(value, actual.begin());\n\n  // non-constexpr array still\n  for (size_t i = 0; i < N; ++i) {\n    if (actual[i] != expected[i]) return false;\n  }\n\n  return value ==\n         from_factoriadic_representation<int>(expected.begin(), expected.end());\n}\n\ntemplate <typename N>\nvoid test_factoriadic_runtime(N n) {\n  std::vector<int> representation(compute_factoriadic_representation_length(n));\n  to_factoriadic_representation(n, representation.begin());\n  N actual = from_factoriadic_representation<N>(representation.begin(),\n                                                representation.end());\n  REQUIRE(n == actual);\n}\n\nTEST_CASE(\"algorithm.to_from_factoriadic_representation.builtin\",\n          \"[algorithm]\") {\n  // Specific examples\n  {\n    static_assert(test_factoriadic(0, std::array{0}));\n    static_assert(test_factoriadic(1, std::array{0, 1}));\n\n    static_assert(test_factoriadic(2, std::array{0, 0, 1}));\n    static_assert(test_factoriadic(3, std::array{0, 1, 1}));\n    static_assert(test_factoriadic(4, std::array{0, 0, 2}));\n    static_assert(test_factoriadic(5, std::array{0, 1, 2}));\n\n    static_assert(test_factoriadic(6, std::array{0, 0, 0, 1}));\n\n    static_assert(test_factoriadic(349, std::array{0, 1, 0, 2, 4, 2}));\n  }\n\n  {\n    for (int i = 0; i < 1000; ++i) {\n      test_factoriadic_runtime(i);\n    }\n  }\n}\n\nTEST_CASE(\"algorithm.to_factoriadic_representation.cpp_int\", \"[algorithm]\") {\n  {\n    big_int x{6};\n    std::ptrdiff_t lenght_default =\n        compute_factoriadic_representation_length(x);\n    int length_int = compute_factoriadic_representation_length<int>(x);\n    short length_short =\n        compute_factoriadic_representation_length<short, int>(x);\n    REQUIRE(lenght_default == 4);\n    REQUIRE(length_int == 4);\n    REQUIRE(length_short == 4);\n  }\n  {\n    auto factorial = [](int x) {\n      big_int res(1);\n      for (int i = 1; i < x; ++i) {\n        res *= i;\n      }\n      return res;\n    };\n\n    for (int i = 100; i < 200; ++i) test_factoriadic_runtime(factorial(i));\n  }\n}\n\n}  // namespace\n}  // namespace algo\n", "meta": {"hexsha": "07c2c956f4b81fe64b83ec5cb7c62373351f8686", "size": 3186, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/test/algo/factoriadic_representation.t.cc", "max_stars_repo_name": "maxpev/algorithm_dumpster", "max_stars_repo_head_hexsha": "e68c7da1b1d278fefe2617ce19e4278ac623d286", "max_stars_repo_licenses": ["Apache-2.0"], "max_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/algo/factoriadic_representation.t.cc", "max_issues_repo_name": "maxpev/algorithm_dumpster", "max_issues_repo_head_hexsha": "e68c7da1b1d278fefe2617ce19e4278ac623d286", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/algo/factoriadic_representation.t.cc", "max_forks_repo_name": "maxpev/algorithm_dumpster", "max_forks_repo_head_hexsha": "e68c7da1b1d278fefe2617ce19e4278ac623d286", "max_forks_repo_licenses": ["Apache-2.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.7027027027, "max_line_length": 80, "alphanum_fraction": 0.6757689893, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.590008752151284}}
{"text": "/*\n * @file\n * @author University of Warwick\n * @version 1.0\n *\n * @section LICENSE\n *\n * @section DESCRIPTION\n *\n * Tests for the Statistics kernels of the utility operations\n */\n\n#define BOOST_TEST_MODULE StatisticsKernels\n#include <boost/test/unit_test.hpp>\n#include <boost/test/output_test_stream.hpp>\n\n#include <stdexcept>\n\n#include \"StatisticsKernels.h\"\n\nusing namespace cupcfd::utility::kernels;\n\n// === sum ===\n\n// Test 1: Test sum of arbitrary values, integer\nBOOST_AUTO_TEST_CASE(sum_test1)\n{\n\tint data[10] = {5, 6, 1, 7, 2, 61, 51, 32, 13, 1041};\n\tint sumCmp = 1219;\n\tint result;\n\n\tresult = sum(data, 10);\n\n\tBOOST_CHECK_EQUAL(result, sumCmp);\n}\n\n// Test 2: Test sum of arbitrary values, doubles\nBOOST_AUTO_TEST_CASE(sum_test2)\n{\n\tdouble data[10] = {434.2, 213.1, 52.2, 14.1, 0.000434, 2315.2, 413.2, 754.52, 5267.2, 173543.2};\n\tdouble sumCmp = 183006.920434;\n\tdouble result;\n\n\tresult = sum(data, 10);\n\n\tBOOST_CHECK_EQUAL(result, sumCmp);\n}\n\n// === mean ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(mean_test1)\n{\n\n}\n\n// === median ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(median_test1)\n{\n\n}\n\n// === mode ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(mode_test1)\n{\n\n}\n\n// === stDev ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(stDev_test1)\n{\n\n}\n\n// === count ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(count_test1)\n{\n\n}\n", "meta": {"hexsha": "4469a2c4e00ac327912aef152ae6d233ba55cb96", "size": 1289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/utility/implementation/component/StatisticsKernelTests.cpp", "max_stars_repo_name": "thorbenlouw/CUP-CFD", "max_stars_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T10:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T14:43:19.000Z", "max_issues_repo_path": "tests/utility/implementation/component/StatisticsKernelTests.cpp", "max_issues_repo_name": "thorbenlouw/CUP-CFD", "max_issues_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T15:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T14:27:28.000Z", "max_forks_repo_path": "tests/utility/implementation/component/StatisticsKernelTests.cpp", "max_forks_repo_name": "thorbenlouw/CUP-CFD", "max_forks_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T15:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T15:24:24.000Z", "avg_line_length": 15.5301204819, "max_line_length": 97, "alphanum_fraction": 0.6726144298, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5900087473681047}}
{"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// Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE fft_evaluation_domain_test\n\n#include <boost/test/unit_test.hpp>\n\n#include <memory>\n#include <vector>\n#include <cstdint>\n\n#include <nil/crypto3/algebra/fields/bls12/base_field.hpp>\n#include <nil/crypto3/algebra/fields/bls12/scalar_field.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/bls12.hpp>\n\n#include <nil/crypto3/algebra/fields/mnt4/scalar_field.hpp>\n#include <nil/crypto3/algebra/fields/mnt4/base_field.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/mnt4.hpp>\n\n#include <nil/crypto3/algebra/fields/mnt6/scalar_field.hpp>\n#include <nil/crypto3/algebra/fields/mnt6/base_field.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/mnt6.hpp>\n\n#include <nil/crypto3/math/coset.hpp>\n#include <nil/crypto3/math/domains/arithmetic_sequence_domain.hpp>\n#include <nil/crypto3/math/domains/basic_radix2_domain.hpp>\n#include <nil/crypto3/math/domains/extended_radix2_domain.hpp>\n#include <nil/crypto3/math/domains/geometric_sequence_domain.hpp>\n#include <nil/crypto3/math/domains/step_radix2_domain.hpp>\n\n#include <nil/crypto3/math/algorithms/make_evaluation_domain.hpp>\n\n#include <nil/crypto3/math/polynomial/evaluate.hpp>\n\n#include <typeinfo>\n\nusing namespace nil::crypto3::algebra;\nusing namespace nil::crypto3::math;\n\n/**\n * Note: Templatized type referenced with FieldType (instead of canonical FieldType)\n * https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#typed-tests\n */\n\ntemplate<typename FieldType>\nvoid test_fft() {\n    typedef typename FieldType::value_type value_type;\n\n    const std::size_t m = 4;\n    std::vector<value_type> f = {2, 5, 3, 8};\n\n    std::shared_ptr<evaluation_domain<FieldType>> domain;\n\n    domain = make_evaluation_domain<FieldType>(m);\n\n    std::vector<value_type> a(f);\n\n    domain->fft(a);\n\n    std::vector<value_type> idx(m);\n\n    for (std::size_t i = 0; i < m; i++) {\n        idx[i] = domain->get_domain_element(i);\n    }\n\n    std::cout << \"FFT: key = \" << typeid(*domain).name() << std::endl;\n    for (std::size_t i = 0; i < m; i++) {\n        value_type e = evaluate_polynomial(f, idx[i], m);\n        std::cout << \"idx[\" << i << \"] = \" << idx[i].data << std::endl;\n        std::cout << \"e = \" << e.data << std::endl;\n        BOOST_CHECK_EQUAL(e.data, a[i].data);\n    }\n    std::cout << \"is_basic_radix2_domain = \" << detail::is_basic_radix2_domain<FieldType>(m) << std::endl;\n    std::cout << \"is_extended_radix2_domain = \" << detail::is_extended_radix2_domain<FieldType>(m) << std::endl;\n    std::cout << \"is_step_radix2_domain = \" << detail::is_step_radix2_domain<FieldType>(m) << std::endl;\n    std::cout << \"is_geometric_sequence_domain = \" << detail::is_geometric_sequence_domain<FieldType>(m) << std::endl;\n    std::cout << \"is_arithmetic_sequence_domain = \" << detail::is_arithmetic_sequence_domain<FieldType>(m) << std::endl;\n}\n\ntemplate<typename FieldType>\nvoid test_inverse_fft_of_fft() {\n    typedef typename FieldType::value_type value_type;\n    const std::size_t m = 4;\n    std::vector<value_type> f = {2, 5, 3, 8};\n\n    std::shared_ptr<evaluation_domain<FieldType>> domain;\n\n    domain = make_evaluation_domain<FieldType>(m);\n\n    std::vector<value_type> a(f);\n    domain->fft(a);\n    domain->inverse_fft(a);\n\n    std::cout << \"inverse FFT of FFT: key = \" << typeid(*domain).name() << std::endl;\n    for (std::size_t i = 0; i < m; i++) {\n        std::cout << \"a[\" << i << \"] = \" << a[i].data << std::endl;\n        BOOST_CHECK_EQUAL(f[i].data, a[i].data);\n    }\n}\n\ntemplate<typename FieldType>\nvoid test_inverse_coset_ftt_of_coset_fft() {\n    typedef typename FieldType::value_type value_type;\n    const std::size_t m = 4;\n    std::vector<value_type> f = {2, 5, 3, 8};\n\n    value_type coset = value_type(fields::arithmetic_params<FieldType>::multiplicative_generator);\n\n    std::shared_ptr<evaluation_domain<FieldType>> domain;\n\n    domain = make_evaluation_domain<FieldType>(m);\n\n    std::vector<value_type> a(f);\n    multiply_by_coset(a, coset);\n    domain->fft(a);\n    domain->inverse_fft(a);\n    multiply_by_coset(a, coset.inversed());\n\n    for (std::size_t i = 0; i < m; i++) {\n        BOOST_CHECK_EQUAL(f[i].data, a[i].data);\n    }\n}\n\ntemplate<typename FieldType>\nvoid test_lagrange_coefficients() {\n    typedef typename FieldType::value_type value_type;\n\n    const std::size_t m = 8;\n    value_type t = value_type(10);\n\n    std::shared_ptr<evaluation_domain<FieldType>> domain;\n\n    domain = make_evaluation_domain<FieldType>(m);\n\n    std::vector<value_type> a;\n    a = domain->evaluate_all_lagrange_polynomials(t);\n\n    std::cout << \"LagrangeCoefficients: key = \" << typeid(*domain).name() << std::endl;\n    std::vector<value_type> d(m);\n    for (std::size_t i = 0; i < m; i++) {\n        d[i] = domain->get_domain_element(i);\n        std::cout << \"d[\" << i << \"] = \" << d[i].data << std::endl;\n    }\n\n    for (std::size_t i = 0; i < m; i++) {\n        value_type e = evaluate_lagrange_polynomial(d, t, m, i);\n        BOOST_CHECK_EQUAL(e.data, a[i].data);\n        std::cout << \"e = \" << e.data << std::endl;\n    }\n}\n\ntemplate<typename FieldType>\nvoid test_compute_z() {\n    typedef typename FieldType::value_type value_type;\n\n    const std::size_t m = 8;\n    value_type t = value_type(10);\n\n    std::shared_ptr<evaluation_domain<FieldType>> domain;\n    domain = make_evaluation_domain<FieldType>(m);\n\n    value_type a;\n    a = domain->compute_vanishing_polynomial(t);\n\n    value_type Z = value_type::one();\n    std::cout << \"ComputeZ: key = \" << typeid(*domain).name() << std::endl;\n    for (std::size_t i = 0; i < m; i++) {\n        Z *= (t - domain->get_domain_element(i));\n        std::cout << \"Z = \" << Z.data << std::endl;\n    }\n\n    BOOST_CHECK_EQUAL(Z.data, a.data);\n}\n\nBOOST_AUTO_TEST_SUITE(fft_evaluation_domain_test_suite)\n\nBOOST_AUTO_TEST_CASE(fft) {\n    test_fft<fields::bls12<381>>();\n    test_fft<fields::mnt4<298>>();\n}\n\nBOOST_AUTO_TEST_CASE(inverse_fft_to_fft) {\n    test_inverse_fft_of_fft<fields::bls12<381>>();\n    test_inverse_fft_of_fft<fields::mnt4<298>>();\n}\n\nBOOST_AUTO_TEST_CASE(inverse_coset_ftt_to_coset_fft) {\n    test_inverse_coset_ftt_of_coset_fft<fields::bls12<381>>();\n    test_inverse_coset_ftt_of_coset_fft<fields::mnt4<298>>();\n}\n\nBOOST_AUTO_TEST_CASE(lagrange_coefficients) {\n    test_lagrange_coefficients<fields::bls12<381>>();\n    test_lagrange_coefficients<fields::mnt4<298>>();\n}\n\nBOOST_AUTO_TEST_CASE(compute_z) {\n    test_compute_z<fields::bls12<381>>();\n    test_compute_z<fields::mnt4<298>>();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e095a09936f60e24d1695abb525dccb1417fb2f4", "size": 7895, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/evaluation_domain.cpp", "max_stars_repo_name": "NilFoundation/fft", "max_stars_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/evaluation_domain.cpp", "max_issues_repo_name": "NilFoundation/fft", "max_issues_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-12-19T23:19:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T20:10:27.000Z", "max_forks_repo_path": "test/evaluation_domain.cpp", "max_forks_repo_name": "NilFoundation/crypto3-math", "max_forks_repo_head_hexsha": "9351ff8c0f1a75022457e82475b0eba2447ceecc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0888888889, "max_line_length": 120, "alphanum_fraction": 0.6813172894, "num_tokens": 2080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.590008737801746}}
{"text": "//\n// Copyright (c) 2018 CNRS\n//\n\n#include \"pinocchio/fwd.hpp\"\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/rnea-derivatives.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/aba-derivatives.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_rnea_derivatives)\n{\n  using CppAD::AD;\n  using CppAD::NearEqual;\n  \n  typedef double Scalar;\n  typedef AD<Scalar> ADScalar;\n  \n  typedef pinocchio::ModelTpl<Scalar> Model;\n  typedef Model::Data Data;\n\n  typedef pinocchio::ModelTpl<ADScalar> ADModel;\n  typedef ADModel::Data ADData;\n  \n  Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  Data data(model);\n  \n  ADModel ad_model = model.cast<ADScalar>();\n  ADData ad_data(ad_model);\n  \n  // Sample random configuration\n  typedef Model::ConfigVectorType CongigVectorType;\n  typedef Model::TangentVectorType TangentVectorType;\n  CongigVectorType q(model.nq);\n  q = pinocchio::randomConfiguration(model);\n\n  TangentVectorType v(TangentVectorType::Random(model.nv));\n  TangentVectorType a(TangentVectorType::Random(model.nv));\n  \n  Eigen::MatrixXd rnea_partial_dq(model.nv,model.nv); rnea_partial_dq.setZero();\n  Eigen::MatrixXd rnea_partial_dv(model.nv,model.nv); rnea_partial_dv.setZero();\n  Eigen::MatrixXd rnea_partial_da(model.nv,model.nv); rnea_partial_da.setZero();\n  \n  pinocchio::computeRNEADerivatives(model,data,q,v,a,\n                              rnea_partial_dq,\n                              rnea_partial_dv,\n                              rnea_partial_da);\n  \n  rnea_partial_da.triangularView<Eigen::StrictlyLower>()\n  = rnea_partial_da.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  typedef ADModel::ConfigVectorType ADCongigVectorType;\n  typedef ADModel::TangentVectorType ADTangentVectorType;\n  \n  ADCongigVectorType ad_q = q.cast<ADScalar>();\n  ADTangentVectorType ad_dq = ADTangentVectorType::Zero(model.nv);\n  ADTangentVectorType ad_v = v.cast<ADScalar>();\n  ADTangentVectorType ad_a = a.cast<ADScalar>();\n  \n  typedef Eigen::Matrix<ADScalar,Eigen::Dynamic,1> VectorXAD;\n  pinocchio::crba(model,data,q);\n  data.M.triangularView<Eigen::StrictlyLower>()\n  = data.M.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  Data::TangentVectorType tau = pinocchio::rnea(model,data,q,v,a);\n  \n  // dtau_dq\n  {\n    CppAD::Independent(ad_dq);\n    ADCongigVectorType ad_q_plus = pinocchio::integrate(ad_model,ad_q,ad_dq);\n    pinocchio::rnea(ad_model,ad_data,ad_q_plus,ad_v,ad_a);\n    \n    VectorXAD Y(model.nv);\n    Eigen::Map<ADData::TangentVectorType>(Y.data(),model.nv,1) = ad_data.tau;\n    \n    CppAD::ADFun<Scalar> ad_fun(ad_dq,Y);\n    \n    CPPAD_TESTVECTOR(Scalar) x((size_t)model.nv);\n    Eigen::Map<Data::TangentVectorType>(x.data(),model.nv,1).setZero();\n    \n    CPPAD_TESTVECTOR(Scalar) tau = ad_fun.Forward(0,x);\n    BOOST_CHECK(Eigen::Map<Data::TangentVectorType>(tau.data(),model.nv,1).isApprox(data.tau));\n    \n    CPPAD_TESTVECTOR(Scalar) dtau_dq = ad_fun.Jacobian(x);\n    Data::MatrixXs dtau_dq_mat = Eigen::Map<EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::MatrixXs)>(dtau_dq.data(),model.nv,model.nv);\n    BOOST_CHECK(dtau_dq_mat.isApprox(rnea_partial_dq));\n  }\n  \n  // dtau_dv\n  {\n    CppAD::Independent(ad_v);\n    pinocchio::rnea(ad_model,ad_data,ad_q,ad_v,ad_a);\n\n    VectorXAD Y(model.nv);\n    Eigen::Map<ADData::TangentVectorType>(Y.data(),model.nv,1) = ad_data.tau;\n\n    CppAD::ADFun<Scalar> ad_fun(ad_v,Y);\n\n    CPPAD_TESTVECTOR(Scalar) x((size_t)model.nv);\n    Eigen::Map<Data::TangentVectorType>(x.data(),model.nv,1) = v;\n\n    CPPAD_TESTVECTOR(Scalar) tau = ad_fun.Forward(0,x);\n    BOOST_CHECK(Eigen::Map<Data::TangentVectorType>(tau.data(),model.nv,1).isApprox(data.tau));\n\n    CPPAD_TESTVECTOR(Scalar) dtau_dv = ad_fun.Jacobian(x);\n    Data::MatrixXs dtau_dv_mat = Eigen::Map<EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::MatrixXs)>(dtau_dv.data(),model.nv,model.nv);\n    BOOST_CHECK(dtau_dv_mat.isApprox(rnea_partial_dv));\n  }\n  \n  // dtau_da\n  {\n    CppAD::Independent(ad_a);\n    pinocchio::rnea(ad_model,ad_data,ad_q,ad_v,ad_a);\n    \n    VectorXAD Y(model.nv);\n    Eigen::Map<ADData::TangentVectorType>(Y.data(),model.nv,1) = ad_data.tau;\n    \n    CppAD::ADFun<Scalar> ad_fun(ad_a,Y);\n    \n    CPPAD_TESTVECTOR(Scalar) x((size_t)model.nv);\n    Eigen::Map<Data::TangentVectorType>(x.data(),model.nv,1) = a;\n    \n    CPPAD_TESTVECTOR(Scalar) tau = ad_fun.Forward(0,x);\n    BOOST_CHECK(Eigen::Map<Data::TangentVectorType>(tau.data(),model.nv,1).isApprox(data.tau));\n    \n    CPPAD_TESTVECTOR(Scalar) dtau_da = ad_fun.Jacobian(x);\n    Data::MatrixXs dtau_da_mat = Eigen::Map<EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::MatrixXs)>(dtau_da.data(),model.nv,model.nv);\n    BOOST_CHECK(dtau_da_mat.isApprox(rnea_partial_da));\n    BOOST_CHECK(dtau_da_mat.isApprox(data.M));\n  }\n  \n}\n\nBOOST_AUTO_TEST_CASE(test_aba_derivatives)\n{\n  using CppAD::AD;\n  using CppAD::NearEqual;\n  \n  typedef double Scalar;\n  typedef AD<Scalar> ADScalar;\n  \n  typedef pinocchio::ModelTpl<Scalar> Model;\n  typedef Model::Data Data;\n  \n  typedef pinocchio::ModelTpl<ADScalar> ADModel;\n  typedef ADModel::Data ADData;\n  \n  Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  Data data(model);\n  \n  ADModel ad_model = model.cast<ADScalar>();\n  ADData ad_data(ad_model);\n  \n  // Sample random configuration\n  typedef Model::ConfigVectorType CongigVectorType;\n  typedef Model::TangentVectorType TangentVectorType;\n  CongigVectorType q(model.nq);\n  q = pinocchio::randomConfiguration(model);\n  \n  TangentVectorType v(TangentVectorType::Random(model.nv));\n  TangentVectorType tau(TangentVectorType::Random(model.nv));\n  \n  Eigen::MatrixXd aba_partial_dq(model.nv,model.nv); aba_partial_dq.setZero();\n  Eigen::MatrixXd aba_partial_dv(model.nv,model.nv); aba_partial_dv.setZero();\n  Eigen::MatrixXd aba_partial_dtau(model.nv,model.nv); aba_partial_dtau.setZero();\n  \n  pinocchio::computeABADerivatives(model,data,q,v,tau,\n                             aba_partial_dq,\n                             aba_partial_dv,\n                             aba_partial_dtau);\n  \n  aba_partial_dtau.triangularView<Eigen::StrictlyLower>()\n  = aba_partial_dtau.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  typedef ADModel::ConfigVectorType ADCongigVectorType;\n  typedef ADModel::TangentVectorType ADTangentVectorType;\n  \n  ADCongigVectorType ad_q = q.cast<ADScalar>();\n  ADTangentVectorType ad_dq = ADTangentVectorType::Zero(model.nv);\n  ADTangentVectorType ad_v = v.cast<ADScalar>();\n  ADTangentVectorType ad_tau = tau.cast<ADScalar>();\n  \n  typedef Eigen::Matrix<ADScalar,Eigen::Dynamic,1> VectorXAD;\n  pinocchio::computeMinverse(model,data,q);\n  data.Minv.triangularView<Eigen::StrictlyLower>()\n  = data.Minv.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  Data::TangentVectorType ddq = pinocchio::aba(model,data,q,v,tau);\n  \n  // dddq_dq\n  {\n    CppAD::Independent(ad_dq);\n    ADCongigVectorType ad_q_plus = pinocchio::integrate(ad_model,ad_q,ad_dq);\n    pinocchio::aba(ad_model,ad_data,ad_q_plus,ad_v,ad_tau);\n    \n    VectorXAD Y(model.nv);\n    Eigen::Map<ADData::TangentVectorType>(Y.data(),model.nv,1) = ad_data.ddq;\n    \n    CppAD::ADFun<Scalar> ad_fun(ad_dq,Y);\n    \n    CPPAD_TESTVECTOR(Scalar) x((size_t)model.nv);\n    Eigen::Map<Data::TangentVectorType>(x.data(),model.nv,1).setZero();\n    \n    CPPAD_TESTVECTOR(Scalar) ddq = ad_fun.Forward(0,x);\n    BOOST_CHECK(Eigen::Map<Data::TangentVectorType>(ddq.data(),model.nv,1).isApprox(data.ddq));\n    \n    CPPAD_TESTVECTOR(Scalar) ddq_dq = ad_fun.Jacobian(x);\n    Data::MatrixXs ddq_dq_mat = Eigen::Map<EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::MatrixXs)>(ddq_dq.data(),model.nv,model.nv);\n    BOOST_CHECK(ddq_dq_mat.isApprox(aba_partial_dq));\n  }\n  \n  // dddq_dv\n  {\n    CppAD::Independent(ad_v);\n    pinocchio::aba(ad_model,ad_data,ad_q,ad_v,ad_tau);\n    \n    VectorXAD Y(model.nv);\n    Eigen::Map<ADData::TangentVectorType>(Y.data(),model.nv,1) = ad_data.ddq;\n    \n    CppAD::ADFun<Scalar> ad_fun(ad_v,Y);\n    \n    CPPAD_TESTVECTOR(Scalar) x((size_t)model.nv);\n    Eigen::Map<Data::TangentVectorType>(x.data(),model.nv,1) = v;\n    \n    CPPAD_TESTVECTOR(Scalar) ddq = ad_fun.Forward(0,x);\n    BOOST_CHECK(Eigen::Map<Data::TangentVectorType>(ddq.data(),model.nv,1).isApprox(data.ddq));\n    \n    CPPAD_TESTVECTOR(Scalar) ddq_dv = ad_fun.Jacobian(x);\n    Data::MatrixXs ddq_dv_mat = Eigen::Map<EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::MatrixXs)>(ddq_dv.data(),model.nv,model.nv);\n    BOOST_CHECK(ddq_dv_mat.isApprox(aba_partial_dv));\n  }\n  \n  // dddq_da\n  {\n    CppAD::Independent(ad_tau);\n    pinocchio::aba(ad_model,ad_data,ad_q,ad_v,ad_tau);\n    \n    VectorXAD Y(model.nv);\n    Eigen::Map<ADData::TangentVectorType>(Y.data(),model.nv,1) = ad_data.ddq;\n    \n    CppAD::ADFun<Scalar> ad_fun(ad_tau,Y);\n    \n    CPPAD_TESTVECTOR(Scalar) x((size_t)model.nv);\n    Eigen::Map<Data::TangentVectorType>(x.data(),model.nv,1) = tau;\n    \n    CPPAD_TESTVECTOR(Scalar) ddq = ad_fun.Forward(0,x);\n    BOOST_CHECK(Eigen::Map<Data::TangentVectorType>(ddq.data(),model.nv,1).isApprox(data.ddq));\n    \n    CPPAD_TESTVECTOR(Scalar) ddq_dtau = ad_fun.Jacobian(x);\n    Data::MatrixXs ddq_dtau_mat = Eigen::Map<EIGEN_PLAIN_ROW_MAJOR_TYPE(Data::MatrixXs)>(ddq_dtau.data(),model.nv,model.nv);\n    BOOST_CHECK(ddq_dtau_mat.isApprox(aba_partial_dtau));\n    BOOST_CHECK(ddq_dtau_mat.isApprox(data.Minv));\n  }\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "79b79c8661bbf2c4cb1250c1ab47cac08bb5f69f", "size": 9925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/cppad-algo-derivatives.cpp", "max_stars_repo_name": "matthieuvigne/pinocchio", "max_stars_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "unittest/cppad-algo-derivatives.cpp", "max_issues_repo_name": "matthieuvigne/pinocchio", "max_issues_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/cppad-algo-derivatives.cpp", "max_forks_repo_name": "matthieuvigne/pinocchio", "max_forks_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 35.4464285714, "max_line_length": 124, "alphanum_fraction": 0.715768262, "num_tokens": 2995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5900087378017459}}
{"text": "#ifndef __DYSKTRA__\n#define __DYSKTRA__\n\n#include <Eigen/Dense>\n#include \"proximals.hpp\"\n\nnamespace proxopp {\n\t\n//  Dykstra's algorithm to compute projections on intersection of convex sets\n//  P. L. Combettes and J.-C. Pesquet, \"Proximal splitting methods in signal processing\"\n\nclass DykstraProjection \n{\n\tpublic:\n\t\tDykstraProjection(proximalOperator *pF, proximalOperator *pG, \n\t\t\t\tint n_iterations=10) :\n\t\t\tpF(pF), pG(pG), n_iterations(n_iterations) {}\n\t\t// Provided the convex F and G are \"simple\", convergence \n\t\t// should be fast. \n\n\t\t~DykstraProjection() {}\n\n\t\tEigen::VectorXf project(Eigen::VectorXf& x0)\n\t\t{\n\t\t\tEigen::VectorXf x,y,p,q; \n\n\t\t\tx = x0;\n\t\t\tp = q = Eigen::VectorXf::Zeros(x0.rows()); \t\n\n\t\t\tfor(int k=0; k < n_iterations;k++) \n\t\t\t{\n\t\t\t\ty = (*pF)(x+p); \n\t\t\t\tp = x + p - y;\n\t\t\t\tx = (*pG)(y+q);\n\t\t\t\tq = y + q - x; \n\t\t\t}\n\n\t\t\treturn x;\n\t\t}\n\tprivate:\n\t\tproximalOperator *pF, *pG; \n\t\tint n_itierations;\n};\n} // namespace proxopp \n\n#endif \n", "meta": {"hexsha": "8285c3be3952fe335af270c4e31151bc2d3fe2d1", "size": 952, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dykstra.hpp", "max_stars_repo_name": "jopago/proxopp", "max_stars_repo_head_hexsha": "4eef17219f99591850bfbca26da2a4baf7e7268b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-17T21:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-17T21:20:15.000Z", "max_issues_repo_path": "include/dykstra.hpp", "max_issues_repo_name": "Meloignon/proxopp", "max_issues_repo_head_hexsha": "e18d334ac714517b2bf166b12993495b0593bc39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dykstra.hpp", "max_forks_repo_name": "Meloignon/proxopp", "max_forks_repo_head_hexsha": "e18d334ac714517b2bf166b12993495b0593bc39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T21:04:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-11T21:04:38.000Z", "avg_line_length": 20.2553191489, "max_line_length": 88, "alphanum_fraction": 0.637605042, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5899554494485525}}
{"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": "//  (C) Copyright Eric Niebler 2005.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/accumulators/accumulators.hpp>\r\n#include <boost/accumulators/statistics/stats.hpp>\r\n#include <boost/accumulators/statistics/moment.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace unit_test;\r\nusing namespace accumulators;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// test_stat\r\n//\r\nvoid test_stat()\r\n{\r\n    accumulator_set<int, stats<tag::moment<2> > > acc1;\r\n\r\n    acc1(2); //    4\r\n    acc1(4); //   16\r\n    acc1(5); // + 25\r\n             // = 45 / 3 = 15\r\n\r\n    BOOST_CHECK_CLOSE(15., accumulators::moment<2>(acc1), 1e-5);\r\n\r\n    accumulator_set<int, stats<tag::moment<5> > > acc2;\r\n\r\n    acc2(2); //     32\r\n    acc2(3); //    243\r\n    acc2(4); //   1024\r\n    acc2(5); // + 3125\r\n             // = 4424 / 4 = 1106\r\n\r\n    BOOST_CHECK_CLOSE(1106., accumulators::moment<5>(acc2), 1e-5);\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// init_unit_test_suite\r\n//\r\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n    test_suite *test = BOOST_TEST_SUITE(\"moment test\");\r\n\r\n    test->add(BOOST_TEST_CASE(&test_stat));\r\n\r\n    return test;\r\n}\r\n\r\n", "meta": {"hexsha": "ba53e185cff68439b2392bbedeeaf53586d31827", "size": 1477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/accumulators/test/moment.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/accumulators/test/moment.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/accumulators/test/moment.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 27.8679245283, "max_line_length": 80, "alphanum_fraction": 0.5646580907, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.589938352910949}}
{"text": "#include <vector>\n#include <iostream>\n#include <unordered_map>\n#include <Eigen/Eigen>\n#include <fstream>\n#include <cstdio>\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n\n#include \"orcvio/obj/ObjectState.h\"\n\nusing namespace boost::filesystem;\n\nnamespace orcvio \n{\n\nEigen::MatrixX3d transform_mean_keypoints_to_global(const Eigen::MatrixX3d& object_keypoints_mean_shape, const Eigen::Matrix4d& object_pose)\n{\n\n    // get the number of keypoints for this object class \n    const int kps_num = object_keypoints_mean_shape.rows();\n\n    Eigen::MatrixX3d object_keypoints_shape_global_frame;\n    object_keypoints_shape_global_frame = Eigen::MatrixXd::Zero(kps_num, 3);\n\n    Eigen::Matrix3d wRq = object_pose.block(0, 0, 3, 3);\n    Eigen::Vector3d wPq = object_pose.block(0, 3, 3, 1);\n\n    // std::cout << \"wRq \" << wRq << std::endl;\n    // std::cout << \"wPq \" << wPq.transpose() << std::endl;\n\n    for (int i = 0; i < kps_num; ++i)\n    {\n        // std::cout << \"keypoint position in object frame \" << object_keypoints_mean_shape.row(i) << std::endl;\n        Eigen::Vector3d keypoint_global_frame = wRq * object_keypoints_mean_shape.row(i).transpose() + wPq;\n        // std::cout << \"keypoint position in global frame \" << keypoint_global_frame.transpose() << std::endl;\n        object_keypoints_shape_global_frame.row(i) = keypoint_global_frame.transpose();\n    }\n\n    return object_keypoints_shape_global_frame;\n\n}\n\nvoid save_object_state_to_file(const ObjectState & object_state, const std::vector<double>& timestamps, \n    std::string filepath_format)\n{\n    boost::format boost_filepath_format(filepath_format);\n    if (!boost::filesystem::is_directory(filepath_format))\n        return;\n\n    std::ofstream file((boost_filepath_format % object_state.object_id).str());\n\n    // std::cout << \"debug file \" << file.is_open() << std::endl;\n\n    if (file.is_open())\n    {\n        file << \"object id:\\n\" << object_state.object_id << '\\n';\n        file << \"object class:\\n\" << object_state.object_class << '\\n';\n        file << \"wTq:\\n\" << object_state.object_pose << '\\n';\n        file << \"keypoints in global frame:\\n\" << object_state.object_keypoints_shape_global_frame << '\\n';\n        file << \"ellipsoid shape:\\n\" << object_state.ellipsoid_shape << '\\n';\n        file << \"observation timestamps:\\n\";\n        for (const auto& time: timestamps)\n        {\n            file << time << \" \";\n        }\n    }\n    // else\n    //     std::cout << \"cannot open file\" << std::endl;\n\n}\n\n}\n", "meta": {"hexsha": "baf70d35c70b842a96c797dd603116f7aa878a6c", "size": 2485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/orcvio/obj/ObjectState.cpp", "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": "src/orcvio/obj/ObjectState.cpp", "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": "src/orcvio/obj/ObjectState.cpp", "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": 33.5810810811, "max_line_length": 140, "alphanum_fraction": 0.660362173, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5899383476809713}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#define NT2_UNIT_MODULE \"nt2 complex toolbox - cot/scalar Mode\"\n\n//////////////////////////////////////////////////////////////////////////////\n// unit test behavior of cot  components in scalar mode\n//////////////////////////////////////////////////////////////////////////////\n/// created by jt the 08/12/2010\n///\n#include <nt2/include/functions/cot.hpp>\n#include <nt2/include/functions/rec.hpp>\n#include <nt2/include/functions/tan.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/meta/as_floating.hpp>\n#include <nt2/sdk/meta/as_signed.hpp>\n#include <nt2/sdk/meta/upgrade.hpp>\n#include <nt2/sdk/meta/downgrade.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n#include <boost/type_traits/common_type.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/memory/buffer.hpp>\n#include <nt2/constant/constant.hpp>\n#include <complex>\n\n\nNT2_TEST_CASE_TPL ( cot_real__1_0,  NT2_REAL_TYPES)\n{\n\n  using nt2::cot;\n  using nt2::tag::cot_;\n  typedef std::complex<T> cT;\n  typedef typename nt2::meta::as_integer<T>::type iT;\n  typedef typename nt2::meta::call<cot_(cT)>::type r_t;\n  typedef typename nt2::meta::scalar_of<r_t>::type ssr_t;\n  typedef typename nt2::meta::upgrade<T>::type u_t;\n  typedef typename nt2:: meta::as_complex<T>::type wished_r_t;\n\n\n  // return type conformity test\n  NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) );\n  std::cout << std::endl;\n  double ulpd;\n  ulpd=0.0;\n\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(nt2::cot(cT(nt2::Inf<T>())), cT(nt2::Nan<T>()), 1);\n  NT2_TEST_ULP_EQUAL(nt2::cot(cT(nt2::Minf<T>())), cT(nt2::Nan<T>()), 1);\n  NT2_TEST_ULP_EQUAL(nt2::cot(cT(1, 1)),nt2::rec(nt2::tan(cT(1.0, 1.0))), 1);\n  NT2_TEST_ULP_EQUAL(nt2::cot(cT(1, 10)),nt2::rec(nt2::tan(cT(1.0, 10.0))), 1);\n  NT2_TEST_ULP_EQUAL(nt2::cot(cT(10, 1)),nt2::rec(nt2::tan(cT(10.0, 1.0))), 1);\n  NT2_TEST_ULP_EQUAL(nt2::cot(cT(10, 10)),nt2::rec(nt2::tan(cT(10.0, 10.0))), 1);\n  NT2_TEST_ULP_EQUAL(nt2::cot(cT(0, 1)),nt2::rec(nt2::tan(cT(0.0, 1.0))), 1);\n  NT2_TEST_ULP_EQUAL(nt2::cot(cT(0, 10)),nt2::rec(nt2::tan(cT(0.0, 10.0))), 1);\n  NT2_TEST_ULP_EQUAL(nt2::cot(cT(10, 0)),nt2::rec(nt2::tan(cT(10.0, 0.0))), 1);\n } // end of test for floating_\n\n", "meta": {"hexsha": "935e66547ef0431208de8aeb179453b0d88485ad", "size": 2838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/trigonometric/unit/scalar/cot.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/type/complex/trigonometric/unit/scalar/cot.cpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/type/complex/trigonometric/unit/scalar/cot.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7352941176, "max_line_length": 81, "alphanum_fraction": 0.6025369979, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.5898454959324698}}
{"text": "/*\nCopyright 2014 Rogier van Dalen.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** \\file\nTest max_semiring.hpp.\n*/\n\n#define BOOST_TEST_MODULE test_max_semiring\n#include \"utility/test/boost_unit_test.hpp\"\n\n#include \"math/max_semiring.hpp\"\n\n#include <boost/mpl/assert.hpp>\n\n#include \"range/std/container.hpp\"\n\n#include \"math/check/check_magma.hpp\"\n#include \"math/check/check_hash.hpp\"\n\nBOOST_AUTO_TEST_SUITE (test_suite_max_semiring)\n\ntemplate <class Type> void check_max_semiring_for() {\n    typedef math::max_semiring <Type> semiring;\n\n    {\n        semiring five (5);\n        semiring three (3);\n        semiring zero (0);\n        semiring zero2;\n\n        BOOST_CHECK (zero == zero2);\n\n        BOOST_CHECK_EQUAL ((five * three).value(), 15);\n        BOOST_CHECK_EQUAL ((five + three), five);\n        BOOST_CHECK_EQUAL (math::choose (five, three), five);\n\n        BOOST_CHECK (three < five);\n        BOOST_CHECK (zero < five);\n        BOOST_CHECK (zero < three);\n    }\n\n    static_assert (math::has <math::callable::times (\n        semiring, semiring)>::value, \"\");\n    static_assert (math::has <math::callable::plus (\n        semiring, semiring)>::value, \"\");\n    static_assert (math::has <math::callable::choose (\n        semiring, semiring)>::value, \"\");\n\n    static_assert (math::is::associative <math::callable::times (\n        semiring, semiring)>::value, \"\");\n    static_assert (math::is::commutative <math::callable::times (\n        semiring, semiring)>::value, \"\");\n    static_assert (!math::is::idempotent <math::callable::times (\n        semiring, semiring)>::value, \"\");\n\n    static_assert (math::is::path_operation <math::callable::plus (\n        semiring, semiring)>::value, \"\");\n    static_assert (math::is::path_operation <math::callable::choose (\n        semiring, semiring)>::value, \"\");\n\n    std::vector <semiring> examples;\n    examples.push_back (semiring (0));\n    examples.push_back (semiring (3));\n    examples.push_back (semiring (5));\n    examples.push_back (semiring (17));\n\n    BOOST_CHECK (semiring (3) == semiring (3));\n\n    math::check_equal_on (examples);\n    math::check_hash (examples);\n\n    math::check_semiring <semiring, math::either> (\n        math::times, math::plus, examples);\n    math::check_semiring <semiring, math::either> (\n        math::times, math::choose, examples);\n}\n\nBOOST_AUTO_TEST_CASE (test_max_semiring_complete) {\n    check_max_semiring_for <int>();\n    check_max_semiring_for <float>();\n    check_max_semiring_for <double>();\n}\n\n// Test whether floating-point numbers and integers are treated correctly when\n// they should behave differently.\nBOOST_AUTO_TEST_CASE (test_max_semiring_float) {\n    // non_member, divide, and invert available for floating-point numbers.\n    static_assert (math::has <\n        math::callable::non_member <math::max_semiring <double>>()>::value, \"\");\n    static_assert (math::has <\n        math::callable::invert <math::callable::times> (\n            math::max_semiring <double>)>::value, \"\");\n    static_assert (math::has <math::callable::divide<> (\n            math::max_semiring <double>, math::max_semiring <double>)>::value,\n        \"\");\n\n    // times and divide are approximate for floating-point numbers; plus is not.\n    static_assert (!math::is::approximate <math::callable::plus (\n        math::max_semiring <double>, math::max_semiring <double>)>::value, \"\");\n    static_assert (math::is::approximate <math::callable::times (\n        math::max_semiring <double>, math::max_semiring <double>)>::value, \"\");\n    static_assert (math::is::approximate <math::callable::divide<> (\n        math::max_semiring <double>, math::max_semiring <double>)>::value, \"\");\n\n    // But not for integers.\n    static_assert (!math::has <\n        math::callable::non_member <math::max_semiring <int>>()>::value, \"\");\n    static_assert (!math::has <math::callable::invert <math::callable::times> (\n            math::max_semiring <int>)>::value, \"\");\n    static_assert (!math::has <math::callable::divide<> (\n            math::max_semiring <int>, math::max_semiring <int>)>::value, \"\");\n\n    static_assert (!math::is::approximate <math::callable::plus (\n        math::max_semiring <int>, math::max_semiring <int>)>::value, \"\");\n    static_assert (!math::is::approximate <math::callable::times (\n        math::max_semiring <int>, math::max_semiring <int>)>::value, \"\");\n    static_assert (!math::is::approximate <math::callable::divide<> (\n        math::max_semiring <int>, math::max_semiring <int>)>::value, \"\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "1ecfc877cc5c257598115352624eafa0715e68b4", "size": 5004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/test-max_semiring.cpp", "max_stars_repo_name": "rogiervd/math", "max_stars_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/test-max_semiring.cpp", "max_issues_repo_name": "rogiervd/math", "max_issues_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/test-max_semiring.cpp", "max_forks_repo_name": "rogiervd/math", "max_forks_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0666666667, "max_line_length": 80, "alphanum_fraction": 0.6648681055, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5898454914699067}}
{"text": "/**\n * Simulate: Particles from Form+Code in Art, Design, and Architecture\n * implemented in C++ by Patrick Tierney (patrick.l.tierney@gmail.com || http://ptierney.com)\n *\n * Requires Cinder 0.8.2 available at http://libcinder.org\n *\n * Project files are located at https://github.com/hlp/form-and-code\n *\n * For more information about Form+Code visit http://formandcode.com\n */\n\n#include <boost/date_time.hpp>\n\n#include \"cinder/app/AppBasic.h\"\n#include \"cinder/Rand.h\"\n#include \"cinder/CinderMath.h\"\n\nclass Particle;\n\nclass Simulate_Particles : public ci::app::AppBasic {\npublic:\n    void prepareSettings(Settings* settings);\n    void setup();\n    void draw();\n\nprivate:\n    std::vector<Particle> particles;\n    bool saving;\n};\n\nclass Particle {\npublic:\n    Particle(ci::Vec2f l) {\n        counter = 0;\n\n        float randmin = -M_PI / 2.0f;\n        float randmax = 0;\n\n        float r = ci::Rand::randFloat(0, M_PI * 2.0f);\n        float x = ci::math<float>::cos(r);\n        float y = ci::math<float>::sin(r);\n        acc = ci::Vec2f(x / 250.0f, y / 250.0f);\n\n        float q = ci::Rand::randFloat(0, 1);\n        r = ci::Rand::randFloat(randmin, randmax);\n        x = ci::math<float>::cos(r) * q;\n        y = ci::math<float>::sin(r) * q;\n        vel = ci::Vec2f(x, y);\n        loc = l;\n\n        counter = 0;\n        hist.resize(1000);\n    }\n\n    void update() {\n        vel += acc;\n        loc += vel;\n        // save location every 10 frames\n        if (ci::app::getElapsedFrames() % 10 == 0) {\n            hist[counter] = (loc);  \n            counter++;\n        }\n    }\n\n    void drawArrowHead(ci::Vec2f v, ci::Vec2f loc, float scale) {\n        ci::gl::pushMatrices();\n        float arrowsize = 4;\n        // Translate to location to render vector\n        ci::gl::translate(ci::Vec2f(loc.x, loc.y));\n\n        // Rotate to the vector heading\n        ci::Quatf q(0.0f, 0.0f, ci::math<float>::atan2(v.normalized().y, v.normalized().x));\n        ci::gl::rotate(q);\n\n        // Calculate length of vector & scale it to be bigger or smaller if necessary\n        float len = v.length()*scale;\n        arrowsize = ci::lmap<float>(len, 0, 10, 0, 1) * arrowsize;\n\n        // Draw point\n        glColor4f(0.0f, 0.0f, 0.0f, 100.0f/255.0f);\n        ci::gl::drawLine(ci::Vec2f(0,0),ci::Vec2f(len-arrowsize,0));\n        glBegin(GL_TRIANGLES);\n        glVertex2f(len,0);\n        glVertex2f(len-arrowsize,+arrowsize/2);\n        glVertex2f(len-arrowsize,-arrowsize/2);\n        glEnd();\n\n        ci::gl::popMatrices();\n    }\n\n    void draw() {\n        float c = 100.0f/255.0f;\n        glColor4f(c, c, c, 50.0f/255.0f);\n\n        drawArrowHead(vel,loc,10);\n\n        // draw history path\n        glColor4f(0.0f, 0.0f, 0.0f, 100.0f/255.0f);\n        glBegin(GL_LINE_STRIP);\n        for (int i = 0; i < counter; i++) {\n            glVertex2f(hist[i].x, hist[i].y);\n        }\n\n        if (!hist.empty()) glVertex2f(loc.x, loc.y);\n        \n        glEnd();\n    }\n\nprivate:\n    ci::Vec2f loc;\n    ci::Vec2f vel;\n    ci::Vec2f acc;\n\n    std::vector<ci::Vec2f> hist;\n    int counter;\n};\n\nvoid Simulate_Particles::prepareSettings(Settings* settings) {\n    settings->setWindowSize(1024, 768);\n}\n\nvoid Simulate_Particles::setup() {\n    glEnable(GL_LINE_SMOOTH);\n    ci::gl::enableAlphaBlending();\n\n    for (int i = 0; i < 1000; i++) {\n        particles.push_back(Particle(ci::Vec2f(100, getWindowHeight()-100)));\n    }\n}\n\nvoid Simulate_Particles::draw() {\n    ci::gl::setMatricesWindow(getWindowSize());\n    ci::gl::clear(ci::Color::white());\n\n    for (std::vector<Particle>::iterator it = particles.begin(); \n        it != particles.end(); ++it) {\n        it->update();\n        it->draw();\n    }\n}\n\n\nCINDER_APP_BASIC(Simulate_Particles, ci::app::RendererGl)\n", "meta": {"hexsha": "5b8bbfef7933a0cd9ac6810ecf0d4a97867a2874", "size": 3730, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reference/contributions/Cinder/Simulate_Particles/src/Simulate_Particles.cpp", "max_stars_repo_name": "TakafumiOyama/FormCodePractice", "max_stars_repo_head_hexsha": "80421242631114071e7d50fd2231122c04b37b92", "max_stars_repo_licenses": ["MIT"], "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/contributions/Cinder/Simulate_Particles/src/Simulate_Particles.cpp", "max_issues_repo_name": "TakafumiOyama/FormCodePractice", "max_issues_repo_head_hexsha": "80421242631114071e7d50fd2231122c04b37b92", "max_issues_repo_licenses": ["MIT"], "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/contributions/Cinder/Simulate_Particles/src/Simulate_Particles.cpp", "max_forks_repo_name": "TakafumiOyama/FormCodePractice", "max_forks_repo_head_hexsha": "80421242631114071e7d50fd2231122c04b37b92", "max_forks_repo_licenses": ["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.9027777778, "max_line_length": 93, "alphanum_fraction": 0.573458445, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5898398507421129}}
{"text": "#ifndef _POW_HPP\n#define _POW_HPP\n\n#include \"discrete_sequence.hpp\"\n\n#include <boost/hana/integral_constant.hpp>\n#include <cstdlib>\n\ntemplate<long long N, typename T>\nauto power(T x) {\n    if constexpr (N == 0) {\n        return T{1};\n    } else {\n        return x * power<N-1>(x);\n    }\n};\n\ntemplate <long long N, typename UnderlyingSequence>\nstruct pow_expr\n{\n    constexpr explicit pow_expr(UnderlyingSequence const& seq) : seq{seq} {};\n\n    constexpr unsigned operator()(size_t index) const {\n        return power<N>(seq(index));\n    }\n\n    UnderlyingSequence const& seq;\n};\n\ntemplate <typename Sequence, long long N>\nconstexpr auto operator^(Sequence const& seq, boost::hana::integral_constant<long long, N>)\n{\n    return pow_expr<N, Sequence>{seq};\n}\n\n#endif //_POW_HPP\n", "meta": {"hexsha": "da0ed85e603e63744f26109a2ba86e56852a7a0c", "size": 775, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "4_manual_expression_templates/pow2.hpp", "max_stars_repo_name": "rgrover/yap-demos", "max_stars_repo_head_hexsha": "d4e100f9fb835bea2a6505f2ed9b8e87ee1ee928", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4_manual_expression_templates/pow2.hpp", "max_issues_repo_name": "rgrover/yap-demos", "max_issues_repo_head_hexsha": "d4e100f9fb835bea2a6505f2ed9b8e87ee1ee928", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4_manual_expression_templates/pow2.hpp", "max_forks_repo_name": "rgrover/yap-demos", "max_forks_repo_head_hexsha": "d4e100f9fb835bea2a6505f2ed9b8e87ee1ee928", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9459459459, "max_line_length": 91, "alphanum_fraction": 0.68, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5898398445706865}}
{"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 \"../DynAutoDiff/DynAutoDiff.hpp\"\n#include <algorithm>\n#include <boost/test/tools/old/interface.hpp>\n#include <eigen3/Eigen/Core>\n#include <iostream>\n#include <vector>\n\n#define BOOST_TEST_MODULE ArithMetic_Test\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#define TL 1e-10\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace DynAutoDiff;\n\nBOOST_AUTO_TEST_SUITE(test)\nBOOST_AUTO_TEST_CASE(multi_branch_test) {\n    auto x1=psca(2.0),x2=psca(3.0),x3=psca(4.0),x4=psca(5.0);\n\tauto y1=x1*x2+x3;\n\tauto y2=y1*x4+y1;\n\n\tGraphManager<> m1(y2);\n\tm1.run();\n\tBOOST_CHECK_CLOSE(y2->v(), 60.0, 1e-5);\n\tBOOST_CHECK_CLOSE(x1->g(), 18.0, 1e-5);\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "14fd1c4a724826ba6472a1d0c8b56d31c8e35885", "size": 732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tmp_test.cpp", "max_stars_repo_name": "kilasuelika/DynAutoDiff", "max_stars_repo_head_hexsha": "1da36182e93f4893201389c5841941500586e3ea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-26T06:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T06:13:56.000Z", "max_issues_repo_path": "test/tmp_test.cpp", "max_issues_repo_name": "kilasuelika/DynAutoDiff", "max_issues_repo_head_hexsha": "1da36182e93f4893201389c5841941500586e3ea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/tmp_test.cpp", "max_forks_repo_name": "kilasuelika/DynAutoDiff", "max_forks_repo_head_hexsha": "1da36182e93f4893201389c5841941500586e3ea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2413793103, "max_line_length": 61, "alphanum_fraction": 0.7513661202, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5896858860851171}}
{"text": "#include<CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include<CGAL/create_straight_skeleton_2.h>\n#include<CGAL/draw_straight_skeleton_2.h>\n#include \"print.h\"\n#include<CGAL/Polygon_2.h>\n\n#include <boost/shared_ptr.hpp>\n\n#include <cassert>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel         K;\n\ntypedef K::Point_2                                                  Point;\ntypedef CGAL::Polygon_2<K>                                          Polygon_2;\ntypedef CGAL::Straight_skeleton_2<K>                                Ss;\n\ntypedef boost::shared_ptr<Ss>                                       SsPtr;\n\nint main()\n{\n  Polygon_2 poly;\n\n  poly.push_back(Point(     0,     0));\n  poly.push_back(Point(  2000,  8000));\n  poly.push_back(Point( 10000, 10000));\n  poly.push_back(Point(  2000, 12000));\n  poly.push_back(Point(     0, 20000));\n  poly.push_back(Point( -2000, 12000));\n  poly.push_back(Point(-10000, 10000));\n  poly.push_back(Point( -2000,  8000));\n\n  assert(poly.is_simple());\n  assert(poly.is_counterclockwise_oriented());\n\n  SsPtr iss = CGAL::create_interior_straight_skeleton_2(poly.vertices_begin(), poly.vertices_end());\n\n  print_straight_skeleton(*iss);\n  draw(*iss);\n\n  assert(iss->size_of_vertices() == 9);\n  assert(iss->size_of_halfedges() == 32);\n  assert(iss->size_of_faces() == 8);\n  assert(iss->is_valid());\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "d552e1241a4a9309ead28bd80b70a65c27d2ba44", "size": 1376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Straight_skeleton_2/test/Straight_skeleton_2/issue4533.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/test/Straight_skeleton_2/issue4533.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/test/Straight_skeleton_2/issue4533.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.6666666667, "max_line_length": 100, "alphanum_fraction": 0.6409883721, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5896858768066208}}
{"text": "#ifndef SOAR_H_\n#define SOAR_H_\n\n#include <Eigen/Dense>\n#include <vector>\n\nclass Soar {\npublic:\n  Soar(const Eigen::Ref<const Eigen::MatrixXd> &matA,\n       const Eigen::Ref<const Eigen::MatrixXd> &matB);\n\n  Eigen::MatrixXd compute(int n);\n\nprivate:\n  const int ndim_;\n  Eigen::MatrixXd matA_, matB_;\n  Eigen::VectorXd u_;\n\n  const double tol_ = 1.0e-10;\n};\n\n#endif", "meta": {"hexsha": "44fcdfef95548c6a744ebf709e525c575718be76", "size": 365, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/soar.hpp", "max_stars_repo_name": "pan3rock/QuadEigsSOAR", "max_stars_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/soar.hpp", "max_issues_repo_name": "pan3rock/QuadEigsSOAR", "max_issues_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/soar.hpp", "max_forks_repo_name": "pan3rock/QuadEigsSOAR", "max_forks_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5909090909, "max_line_length": 54, "alphanum_fraction": 0.6904109589, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5896717824446156}}
{"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": "// Copyright (C) 2012  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <dlib/optimization.h>\n#include <dlib/svm.h>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <vector>\n\n#include \"tester.h\"\n\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    logger dlog(\"test.oca\");\n\n// ----------------------------------------------------------------------------------------\n\n    class test_oca : public tester\n    {\n\n    public:\n        test_oca (\n        ) :\n            tester (\"test_oca\",\n                    \"Runs tests on the oca component.\")\n        {\n        }\n\n        void perform_test(\n        )\n        {\n            print_spinner();\n\n            typedef matrix<double,0,1> w_type;\n            w_type w;\n\n            decision_function<linear_kernel<w_type> > df;\n            svm_c_linear_trainer<linear_kernel<w_type> > trainer;\n            trainer.set_c_class1(2);\n            trainer.set_c_class1(3);\n            trainer.set_learns_nonnegative_weights(true);\n            trainer.set_epsilon(1e-12);\n\n            std::vector<w_type> x;\n            w_type temp(2);\n            temp = -1, 1;\n            x.push_back(temp);\n            temp = 1, -1;\n            x.push_back(temp);\n\n            std::vector<double> y;\n            y.push_back(+1);\n            y.push_back(-1);\n\n            w_type true_w(3);\n\n            oca solver;\n\n            // test the version without a non-negativity constraint on w.\n            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 0);\n            dlog << LINFO << trans(w);\n            true_w = -0.5, 0.5, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            w_type prior = true_w;\n            solver(make_oca_problem_c_svm<w_type>(20.0, 30.0, mat(x), mat(y), false, 1e-12, 40), w, prior);\n            dlog << LINFO << trans(w);\n            true_w = -0.5, 0.5, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            prior = 0,0,0;\n            solver(make_oca_problem_c_svm<w_type>(20.0, 30.0, mat(x), mat(y), false, 1e-12, 40), w, prior);\n            dlog << LINFO << trans(w);\n            true_w = -0.5, 0.5, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            prior = -1,1,0;\n            solver(make_oca_problem_c_svm<w_type>(20.0, 30.0, mat(x), mat(y), false, 1e-12, 40), w, prior);\n            dlog << LINFO << trans(w);\n            true_w = -1.0, 1.0, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            prior = -0.2,0.2,0;\n            solver(make_oca_problem_c_svm<w_type>(20.0, 30.0, mat(x), mat(y), false, 1e-12, 40), w, prior);\n            dlog << LINFO << trans(w);\n            true_w = -0.5, 0.5, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            prior = -10.2,-1,0;\n            solver(make_oca_problem_c_svm<w_type>(20.0, 30.0, mat(x), mat(y), false, 1e-12, 40), w, prior);\n            dlog << LINFO << trans(w);\n            true_w = -10.2, -1.0, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            print_spinner();\n\n            // test the version with a non-negativity constraint on w.\n            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 9999);\n            dlog << LINFO << trans(w);\n            true_w = 0, 1, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            df = trainer.train(x,y);\n            w = join_cols(df.basis_vectors(0), uniform_matrix<double>(1,1,-df.b));\n            true_w = 0, 1, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n\n            print_spinner();\n\n            // test the version with a non-negativity constraint on w.\n            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 2);\n            dlog << LINFO << trans(w);\n            true_w = 0, 1, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            print_spinner();\n\n\n            // test the version with a non-negativity constraint on w.\n            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 1);\n            dlog << LINFO << trans(w);\n            true_w = 0, 1, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            print_spinner();\n\n\n            // switching the labels should change which w weight goes negative.\n            y.clear();\n            y.push_back(-1);\n            y.push_back(+1);\n\n\n            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 0);\n            dlog << LINFO << trans(w);\n            true_w = 0.5, -0.5, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            print_spinner();\n\n            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 1);\n            dlog << LINFO << trans(w);\n            true_w = 0.5, -0.5, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            print_spinner();\n\n            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 2);\n            dlog << LINFO << trans(w);\n            true_w = 1, 0, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            print_spinner();\n\n            solver(make_oca_problem_c_svm<w_type>(2.0, 3.0, mat(x), mat(y), false, 1e-12, 40), w, 5);\n            dlog << LINFO << trans(w);\n            true_w = 1, 0, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n            df = trainer.train(x,y);\n            w = join_cols(df.basis_vectors(0), uniform_matrix<double>(1,1,-df.b));\n            true_w = 1, 0, 0;\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n\n\n            x.clear();\n            y.clear();\n            temp = -2, 2;\n            x.push_back(temp);\n            temp = 0, -0;\n            x.push_back(temp);\n\n            y.push_back(+1);\n            y.push_back(-1);\n\n            trainer.set_c(10);\n            df = trainer.train(x,y);\n            w = join_cols(df.basis_vectors(0), uniform_matrix<double>(1,1,-df.b));\n            true_w = 0, 1, -1;\n            dlog << LINFO << \"w: \" << trans(w);\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n\n            x.clear();\n            y.clear();\n            temp = -2, 2;\n            x.push_back(temp);\n            temp = 0, -0;\n            x.push_back(temp);\n\n            y.push_back(-1);\n            y.push_back(+1);\n\n            trainer.set_c(10);\n            df = trainer.train(x,y);\n            w = join_cols(df.basis_vectors(0), uniform_matrix<double>(1,1,-df.b));\n            true_w = 1, 0, 1;\n            dlog << LINFO << \"w: \" << trans(w);\n            dlog << LINFO << \"error: \"<< max(abs(w-true_w));\n            DLIB_TEST(max(abs(w-true_w)) < 1e-10);\n\n        }\n\n    } a;\n\n}\n\n\n\n", "meta": {"hexsha": "ce0c5cbefff84453bd4699462eaccd3d2337cfe7", "size": 7744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "itomp_cio_planner/dlib/dlib/test/oca.cpp", "max_stars_repo_name": "Chpark/itomp", "max_stars_repo_head_hexsha": "a11713a14a0b65ede54ab3b1cee2c0060b386d0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T14:46:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-06T02:57:19.000Z", "max_issues_repo_path": "itomp_cio_planner/dlib/dlib/test/oca.cpp", "max_issues_repo_name": "Chpark/itomp", "max_issues_repo_head_hexsha": "a11713a14a0b65ede54ab3b1cee2c0060b386d0e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-12-16T14:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-19T05:49:51.000Z", "max_forks_repo_path": "itomp_cio_planner/dlib/dlib/test/oca.cpp", "max_forks_repo_name": "Chpark/itomp", "max_forks_repo_head_hexsha": "a11713a14a0b65ede54ab3b1cee2c0060b386d0e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T04:45:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T04:28:53.000Z", "avg_line_length": 32.6751054852, "max_line_length": 107, "alphanum_fraction": 0.477660124, "num_tokens": 2330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5896717714919137}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n    This is an example illustrating the use of the multilayer perceptron \n    from the dlib C++ Library.  \n\n    This example creates a simple set of data to train on and shows\n    you how to train a mlp object on that data.\n\n\n    The data used in this example will be 2 dimensional data and will\n    come from a distribution where points with a distance less than 10\n    from the origin are labeled 1 and all other points are labeled\n    as 0.\n        \n*/\n\n\n#include <iostream>\n#include <dlib/mlp.h>\n\nusing namespace std;\nusing namespace dlib;\n\n\n\n\n#if defined(BUILD_MONOLITHIC)\n#define main(cnt, arr)      dlib_mlp_ex_main(cnt, arr)\n#endif\n\nint main(int argc, const char** argv)\n{\n    // The mlp takes column vectors as input and gives column vectors as output.  The dlib::matrix\n    // object is used to represent the column vectors. So the first thing we do here is declare \n    // a convenient typedef for the matrix object we will be using.\n\n    // This typedef declares a matrix with 2 rows and 1 column.  It will be the\n    // object that contains each of our 2 dimensional samples.   (Note that if you wanted \n    // more than 2 features in this vector you can simply change the 2 to something else)\n    typedef matrix<double, 2, 1> sample_type;\n\n\n    // make an instance of a sample matrix so we can use it below\n    sample_type sample;\n\n    // Create a multi-layer perceptron network.   This network has 2 nodes on the input layer \n    // (which means it takes column vectors of length 2 as input) and 5 nodes in the first \n    // hidden layer.  Note that the other 4 variables in the mlp's constructor are left at\n    // their default values.  \n    mlp::kernel_1a_c net(2,5);\n\n    // Now let's put some data into our sample and train on it.  We do this\n    // by looping over 41*41 points and labeling them according to their\n    // distance from the origin.\n    for (int i = 0; i < 1000; ++i)\n    {\n        for (int r = -20; r <= 20; ++r)\n        {\n            for (int c = -20; c <= 20; ++c)\n            {\n                sample(0) = r;\n                sample(1) = c;\n\n                // if this point is less than 10 from the origin\n                if (sqrt((double)r*r + c*c) <= 10)\n                    net.train(sample,1);\n                else\n                    net.train(sample,0);\n            }\n        }\n    }\n\n    // Now we have trained our mlp.  Let's see how well it did.  \n    // Note that if you run this program multiple times you will get different results. This\n    // is because the mlp network is randomly initialized.\n\n    // each of these statements prints out the output of the network given a particular sample.\n\n    sample(0) = 3.123;\n    sample(1) = 4;\n    cout << \"This sample should be close to 1 and it is classified as a \" << net(sample) << endl;\n\n    sample(0) = 13.123;\n    sample(1) = 9.3545;\n    cout << \"This sample should be close to 0 and it is classified as a \" << net(sample) << endl;\n\n    sample(0) = 13.123;\n    sample(1) = 0;\n    cout << \"This sample should be close to 0 and it is classified as a \" << net(sample) << endl;\n}\n\n", "meta": {"hexsha": "2417f57ebd2c0b279cbd5441b0807f9b48e6d6e3", "size": 3175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mlp_ex.cpp", "max_stars_repo_name": "GerHobbelt/dlib", "max_stars_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/mlp_ex.cpp", "max_issues_repo_name": "GerHobbelt/dlib", "max_issues_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/mlp_ex.cpp", "max_forks_repo_name": "GerHobbelt/dlib", "max_forks_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1397849462, "max_line_length": 98, "alphanum_fraction": 0.6359055118, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.589671766321501}}
{"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\u00e9 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": "/* Boost example/horner.cpp\r\n * example of unprotecting rounding for a whole function computation\r\n *\r\n * Copyright 2002-2003 Guillaume Melquiond\r\n *\r\n * Distributed under the Boost Software License, Version 1.0.\r\n * (See accompanying file LICENSE_1_0.txt or\r\n * copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#include <boost/numeric/interval.hpp>\r\n#include <iostream>\r\n\r\n// I is an interval class, the polynom is a simple array\r\ntemplate<class I>\r\nI horner(const I& x, const I p[], int n) {\r\n\r\n  // initialize and restore the rounding mode\r\n  typename I::traits_type::rounding rnd;\r\n\r\n  // define the unprotected version of the interval type\r\n  typedef typename boost::numeric::interval_lib::unprotect<I>::type R;\r\n\r\n  const R& a = x;\r\n  R y = p[n - 1];\r\n  for(int i = n - 2; i >= 0; i--) {\r\n    y = y * a + (const R&)(p[i]);\r\n  }\r\n  return y;\r\n\r\n  // restore the rounding mode with the destruction of rnd\r\n}\r\n\r\ntemplate<class T, class Policies>\r\nstd::ostream &operator<<(std::ostream &os,\r\n                         const boost::numeric::interval<T, Policies> &x) {\r\n  os << \"[\" << x.lower() << \", \" << x.upper() << \"]\";\r\n  return os;\r\n}\r\n\r\nint main() {\r\n  typedef boost::numeric::interval<double> I;\r\n  I p[3] = { -1.0, 0, 1.0 };\r\n  I x = 1.0;\r\n  std::cout << horner(x, p, 3) << std::endl;\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "a1da94b3ae5d8e526b85dd12d6f8f6ac98ff46f5", "size": 1316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/interval/examples/horner.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/numeric/interval/examples/horner.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/numeric/interval/examples/horner.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 27.4166666667, "max_line_length": 75, "alphanum_fraction": 0.6124620061, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5896255789896035}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n\nTEST(MathFunctions, int_step_double) {\n  using stan::math::int_step;\n  EXPECT_EQ(0U, int_step(-1.0));\n  EXPECT_EQ(0U, int_step(0.0));\n  EXPECT_EQ(1U, int_step(0.00000000001));\n  EXPECT_EQ(1U, int_step(100.0));\n}\n\nTEST(MathFunctions, int_step_int) {\n  using stan::math::int_step;\n\n  EXPECT_EQ(0U, int_step(static_cast<int>(-1)));\n  EXPECT_EQ(0U, int_step(static_cast<int>(0)));\n  EXPECT_EQ(1U, int_step(static_cast<int>(100)));\n}\n\nTEST(MathFunctions, int_step_inf) {\n  using stan::math::int_step;\n\n  EXPECT_EQ(1U, int_step(std::numeric_limits<double>::infinity()));\n  EXPECT_EQ(0U, int_step(-std::numeric_limits<double>::infinity()));\n}\n\nTEST(MathFunctions, int_step_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_EQ(0U, stan::math::int_step(nan));\n}\n", "meta": {"hexsha": "8819292366e44f036d14a14085328548dddd16c0", "size": 911, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/int_step_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/prim/scal/fun/int_step_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/prim/scal/fun/int_step_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7941176471, "max_line_length": 68, "alphanum_fraction": 0.7200878156, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.5896255789896034}}
{"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": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp> \n\nusing namespace std;\nusing namespace boost;\ntypedef boost::adjacency_list<listS, vecS, bidirectionalS> Graph;\ntypedef Graph::vertex_descriptor Vertex;\ntypedef Graph::vertex_iterator VertexI;\ntypedef Graph::in_edge_iterator inEdgeI;\ntypedef Graph::out_edge_iterator outEdgeI;\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, g); add_edge(u, w, g); add_edge(u, x, g);\n  cout << \"Number of edges: \" << num_edges(g) << \"\\n\";\n  cout << \"Number of vertices: \" << num_vertices(g) << \"\\n\";\n  VertexI vertexIt, vertexEnd;\n  inEdgeI inedgeIt, inedgeEnd;\n  outEdgeI outedgeIt, outedgeEnd;\n  tie(vertexIt, vertexEnd) = vertices(g);\n  for (; vertexIt != vertexEnd; ++vertexIt) {\n    cout << \"incoming edges for \" << *vertexIt << \": \";\n    tie(inedgeIt, inedgeEnd) = in_edges(*vertexIt, g); \n    for(; inedgeIt != inedgeEnd; ++inedgeIt) { \n      cout << *inedgeIt << \" \"; \n    }\n    cout << \"; in degree: \" << in_degree(*vertexIt, g) << \"\\n\"; \n    cout << \"outgoing edges for \" << *vertexIt << \": \";\n    tie(outedgeIt, outedgeEnd) = out_edges(*vertexIt, g);\n    for(; outedgeIt != outedgeEnd; ++outedgeIt) { \n      cout << *outedgeIt << \" \"; \n    }\n    cout << \"; out degree: \" << out_degree(*vertexIt, g) << \"\\n\"; \n  }\n  return 0; \n}\n", "meta": {"hexsha": "4d23d7f0a44d3ed7e2b390e8e09244896bfa77e2", "size": 1391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "practice/graph2.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/graph2.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/graph2.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": 33.9268292683, "max_line_length": 66, "alphanum_fraction": 0.6326383896, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.5896255511385934}}
{"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": "#include <boost/multiprecision/cpp_dec_float.hpp>\n//#include <cmath>\n#include <iostream>\n\nconst int PRECISION = 10000;\ntypedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<PRECISION>> arbFloat;\n\nenum returnID {success = 0, precisionExceeded = 1};\n\nint main(){\n\tarbFloat k = 6, \n\t\tthreeK = pow(3, k), \n\t\ttwoK = pow(2, k), \n\t\tfloorK;\n\tbool isSolution = false;\n\n\tfor(; !isSolution; ++k){\n\t\tthreeK *= 3, twoK *= 2, floorK = floor(threeK / twoK);\n\t\tisSolution = threeK - twoK * floorK > twoK - floorK - 2;\n\t}\n\n\tif(threeK - twoK * floorK <= twoK - floorK - 2){\n\t\tstd::cout << \"Solution at k = \" << k << \"\\n\";\n\t\treturn returnID::success;\n\t} else {\n\t\tstd::cout << \"Error: Precision exceeded at k = \" << k << \" with \" << PRECISION << \" digits\\n\";\n\t\treturn returnID::precisionExceeded;\n\t}\n}\n", "meta": {"hexsha": "9c395b9ba2de6476bbbd78fa8d8d9602e4bd4ca8", "size": 803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Unsolved-inequality/Unsolved-inequality.cpp", "max_stars_repo_name": "esote/mathematical-functions", "max_stars_repo_head_hexsha": "0bdf761583a49b6479a82d7e0668744d9bb75dad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Unsolved-inequality/Unsolved-inequality.cpp", "max_issues_repo_name": "esote/mathematical-functions", "max_issues_repo_head_hexsha": "0bdf761583a49b6479a82d7e0668744d9bb75dad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Unsolved-inequality/Unsolved-inequality.cpp", "max_forks_repo_name": "esote/mathematical-functions", "max_forks_repo_head_hexsha": "0bdf761583a49b6479a82d7e0668744d9bb75dad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7666666667, "max_line_length": 96, "alphanum_fraction": 0.6400996264, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5894361525527883}}
{"text": "#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include \"nn.cpp\"\n\nint main(){\n    auto s = std::vector <int> {2,5,3};\n    auto a = NeuralNetwork(s); // NN with 2,5,3 layers. 2 inputs, 3 outputs\n\n    auto inp = Eigen::MatrixXd::Random(2,1); // Supply random input\n    auto ans = a.predict(inp);\n    std::cout<< ans << std::endl;\n    \n    return 0;\n}", "meta": {"hexsha": "92d7e64b48efe48236afdcf977d4e9f9cb4dd127", "size": 362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NeuralNetworks/main.cpp", "max_stars_repo_name": "adityapande-1995/CPP_Projects", "max_stars_repo_head_hexsha": "4546c504fbbdb2ea25c6a8d7073448b565538701", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NeuralNetworks/main.cpp", "max_issues_repo_name": "adityapande-1995/CPP_Projects", "max_issues_repo_head_hexsha": "4546c504fbbdb2ea25c6a8d7073448b565538701", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NeuralNetworks/main.cpp", "max_forks_repo_name": "adityapande-1995/CPP_Projects", "max_forks_repo_head_hexsha": "4546c504fbbdb2ea25c6a8d7073448b565538701", "max_forks_repo_licenses": ["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.1333333333, "max_line_length": 75, "alphanum_fraction": 0.6077348066, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5894361401788366}}
{"text": "#include \"Sorter.h\"\r\n#include <algorithm>\r\n#include <boost/dynamic_bitset.hpp>\r\n#include <bitset>\r\n#include <stack>\r\n#include <vector>\r\n\r\nvoid Sorter::Shuffle(int *vals, int n)\r\n{\r\n\tfor (int ii = 0; ii < n; ++ii)\r\n\t\tSwap(vals + ii, vals + (rand() % n));\r\n}\r\n\r\nvoid Sorter::Bubble(int *vals, int n)\r\n{\r\n\tfor (; n > 1; --n)\r\n\t\tfor (int ii = 1; ii < n; ++ii)\r\n\t\t\tif (vals[ii - 1] > vals[ii])\r\n\t\t\t\tSwap(vals + ii - 1, vals + ii);\r\n}\r\n\r\nvoid Sorter::Cocktail(int *vals, int n)\r\n{\r\n\tint lo = 0, hi = n - 1;\r\n\twhile (hi - lo > 1)\r\n\t{\r\n\t\tfor(int ii = lo; ii < hi; ++ii)\r\n\t\t\tif (vals[ii] > vals[ii + 1])\r\n\t\t\t\tSwap(vals + ii, vals + ii + 1);\r\n\t\t--hi;\r\n\t\tfor (int ii = hi; ii > lo; --ii)\r\n\t\t\tif (vals[ii] < vals[ii - 1])\r\n\t\t\t\tSwap(vals + ii, vals + ii - 1);\r\n\t\t++lo;\r\n\t}\r\n}\r\n\r\nvoid Sorter::Gnome(int *vals, int n)\r\n{\r\n\tint ii = 1;\r\n\twhile (ii < n)\r\n\t{\r\n\t\tif (ii == 0)\r\n\t\t\t++ii;\r\n\t\tif (vals[ii] < vals[ii - 1])\r\n\t\t{\r\n\t\t\tSwap(vals + ii, vals + ii - 1);\r\n\t\t\t--ii;\r\n\t\t}\r\n\t\telse\r\n\t\t\t++ii;\r\n\r\n\t}\r\n}\r\n\r\nvoid Sorter::OddEven(int *vals, int n)\r\n{\r\n\tbool sorted = false;\r\n\twhile (!sorted)\r\n\t{\r\n\t\tsorted = true;\r\n\t\tSwapper(sorted, vals, n, 1);\r\n\t\tSwapper(sorted, vals, n, 0);\r\n\t}\r\n}\r\n\r\nvoid Sorter::Comb(int *vals, int n)\r\n{\r\n\tint gap = n >> 1;\r\n\tbool sorted = false;\r\n\twhile (!sorted || gap != 1)\r\n\t{\r\n\t\tsorted = true;\r\n\t\tgap = gap == 1 ? 1 : gap >> 1;\r\n\t\tfor (int ii = 0; ii + gap < n; ++ii)\r\n\t\t{\r\n\t\t\tif (vals[ii] > vals[ii + gap])\r\n\t\t\t{\r\n\t\t\t\tSwap(vals + ii, vals + ii + gap);\r\n\t\t\t\tsorted = false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Sorter::Selection(int *vals, int n)\r\n{\r\n\tfor (int min = 0, base = 0; base < n; min = ++base)\r\n\t{\r\n\t\tfor (int ii = min + 1; ii < n; ++ii)\r\n\t\t\tif (vals[ii] < vals[min])\r\n\t\t\t\tmin = ii;\r\n\t\tSwap(vals + base, vals + min);\r\n\t}\r\n}\r\n\r\nvoid Sorter::Pancake(int *vals, int n)\r\n{\r\n\tfor (int top = n - 1, max = 0; top > 1; --top, max = 0)\r\n\t{\r\n\t\tfor (int ii = 0; ii <= top; ++ii)\r\n\t\t\tif (vals[max] < vals[ii])\r\n\t\t\t\tmax = ii;\r\n\t\tif (max != top)\r\n\t\t{\r\n\t\t\tFlip(vals, max);\r\n\t\t\tFlip(vals, top);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Sorter::Insertion(int *vals, int n)\r\n{\r\n\tfor (int ii = 1; ii < n; ++ii)\r\n\t{\r\n\t\tint in = BinarySearch(vals, vals[ii], 0, ii - 1);\r\n\t\tfor (int jj = ii - 1; jj >= in && vals[jj] != vals[jj + 1]; --jj)\r\n\t\t\tSwap(vals + jj, vals + jj + 1);\r\n\t}\r\n}\r\n\r\nvoid Sorter::Shell(int *vals, int n)\r\n{\r\n\tfor (int gap = n >> 1; gap > 0; gap >>= 1)\r\n\t{\r\n\t\tfor (int ii = gap; ii < n; ++ii)\r\n\t\t{\r\n\t\t\tint trace, min = vals[ii];\r\n\t\t\tfor (trace = ii; trace >= gap && vals[trace - gap] > min; trace -= gap)\r\n\t\t\t\tvals[trace] = vals[trace - gap];\r\n\t\t\tvals[trace] = min;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Sorter::Merge(int *vals, int lo, int hi)\r\n{\r\n\tif (lo < hi)\r\n\t{\r\n\t\tint mid = lo + ((hi - lo) >> 1);\r\n\t\tMerge(vals, lo, mid);\r\n\t\tMerge(vals, mid + 1, hi);\r\n\t\tMerger(vals, lo, mid, hi);\r\n\t}\r\n}\r\n\r\nvoid Sorter::ItMerge(int *vals, int n)\r\n{\r\n\tfor (int size = 1; size < n; size >>= 1)\r\n\t{\r\n\t\tfor (int left = 0; left < n; left += size >> 1)\r\n\t\t{\r\n\t\t\tint mid = std::min(left + size - 1, n - 1);\r\n\t\t\tint right = std::min(left + (size >> 1) - 1, n - 1);\r\n\t\t\tMerger(vals, left, mid, right);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Sorter::Quick(int *vals, int lo, int hi)\r\n{\r\n\tif (lo < hi)\r\n\t{\r\n\t\tint p = Partition(vals, lo, hi);\r\n\t\tQuick(vals, lo, p - 1);\r\n\t\tQuick(vals, p + 1, hi);\r\n\t}\r\n}\r\n\r\nvoid Sorter::ItQuick(int *vals, int n)\r\n{\r\n\tstd::stack<int> stack;\r\n\tstack.push(0);\r\n\tstack.push(n - 1);\r\n\twhile (!stack.empty())\r\n\t{\r\n\t\tint hi = stack.top();\r\n\t\tstack.pop();\r\n\t\tint lo = stack.top();\r\n\t\tstack.pop();\r\n\t\tint p = Partition(vals, lo, hi);\r\n\t\tif (p - 1 > lo)\r\n\t\t{\r\n\t\t\tstack.push(lo);\r\n\t\t\tstack.push(p - 1);\r\n\t\t}\r\n\t\tif (p + 1 < hi)\r\n\t\t{\r\n\t\t\tstack.push(p + 1);\r\n\t\t\tstack.push(hi);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Sorter::TQuick(int *vals, int lo, int hi)\r\n{\r\n\tif (lo < hi)\r\n\t{\r\n\t\tint left, right;\r\n\t\tTPartition(vals, lo, hi, left, right);\r\n\t\tTQuick(vals, lo, left);\r\n\t\tTQuick(vals, right, hi);\r\n\t}\r\n}\r\n\r\nvoid Sorter::Pigeonhole(int *vals, int n)\r\n{\r\n\tint min = *std::min_element(vals, vals + n), max = *std::max_element(vals, vals + n);\r\n\tstd::vector<std::vector<int>> holes(max - min - 1);\r\n\tfor (int ii = 0; ii < n; ++ii)\r\n\t\tholes[ii - min].push_back(vals[ii]);\r\n\tint in = 0;\r\n\tfor (std::vector<int> hole : holes)\r\n\t\tfor (int val : hole)\r\n\t\t\tvals[in++] = val;\r\n}\r\n\r\nvoid Sorter::Bucket(int *vals, int n, int b)\r\n{\r\n\tint max = *std::max_element(vals, vals + n);\r\n\tstd::vector<std::vector<int>> buckets(b);\r\n\tfor (int ii = 0; ii < n; ++ii)\r\n\t\tbuckets[b * vals[ii] / max].push_back(vals[ii]);\r\n\tfor (std::vector<int> bucket : buckets)\r\n\t\tInsertion(&bucket[0], bucket.size()); // maybe make recursive, find base case.\r\n\tint in = 0;\r\n\tfor (std::vector<int> bucket : buckets)\r\n\t\tfor (int val : bucket)\r\n\t\t\tvals[in++] = val;\r\n}\r\n\r\nvoid Sorter::Counting(int *vals, int n)\r\n{\r\n\tint min = *std::min_element(vals, vals + n), max = *std::max_element(vals, vals + n);\r\n\tstd::vector<int> count(max - min + 1), sorted(n);\r\n\tfor (int ii = 0; ii < n; ++ii)\r\n\t\t++count[vals[ii] - min];\r\n\tfor (int ii = n - 1; ii >= 0; --ii)\r\n\t{\r\n\t\tsorted[count[vals[ii] - min] - 1] = vals[ii];\r\n\t\t--count[vals[ii] - min];\r\n\t}\r\n\tfor (int ii = 0; ii < n; ++ii)\r\n\t\tvals[ii] = sorted[ii];\r\n}\r\n\r\nvoid Sorter::Radix(int *vals, int n, int b)\r\n{\r\n\tint runs = 0, d = 1, max = *std::max_element(vals, vals + n);\r\n\twhile (max > 0)\r\n\t{\r\n\t\tmax /= b;\r\n\t\t++runs;\r\n\t}\r\n\tstd::vector<std::vector<int>> digits(b);\r\n\twhile (runs-- > 0)\r\n\t{\r\n\t\tfor (int ii = 0; ii < n; ++ii)\r\n\t\t\tdigits[vals[ii] / d % b].push_back(vals[ii]);\r\n\t\td *= b;\r\n\t\tint in = 0;\r\n\t\tfor (std::vector<int> digit : digits)\r\n\t\t{\r\n\t\t\tfor (int val : digit)\r\n\t\t\t\tvals[in++] = val;\r\n\t\t\tdigit.resize(0);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Sorter::Gravity(int *vals, int n)\r\n{\r\n\tint max = *std::max_element(vals, vals + n);\r\n\tstd::vector<boost::dynamic_bitset<>> abacus(n, boost::dynamic_bitset<>(max));\r\n\tfor (int ii = 0; ii < n; ++ii)\r\n\t{\r\n\t\tabacus[ii].flip();\r\n\t\tabacus[ii] >>= max - vals[ii];\r\n\t}\r\n\tfor (int jj = 0, sum = 0; jj < max; ++jj, sum = 0)\r\n\t{\r\n\t\tfor (int ii = 0; ii < n; ++ii)\r\n\t\t{\r\n\t\t\tsum += abacus[ii].test(jj) ? 1 : 0;\r\n\t\t\tabacus[ii].set(jj, 0);\r\n\t\t}\r\n\t\tfor (int ii = n - 1; ii >= n - sum; --ii)\r\n\t\t\tabacus[ii].set(jj, 1);\r\n\t}\r\n\tfor (int ii = 0; ii < n; ++ii)\r\n\t\tvals[ii] = abacus[ii].count();\r\n}\r\n\r\nvoid Sorter::Swap(int *a, int *b)\r\n{\r\n\tint tmp = *a;\r\n\t*a = *b;\r\n\t*b = tmp;\r\n}\r\n\r\nvoid Sorter::Swapper(bool &sorted, int *vals, int n, int parity)\r\n{\r\n\tfor (int ii = parity; ii < n - 2; ii += 2)\r\n\t{\r\n\t\tif (vals[ii] > vals[ii + 1])\r\n\t\t{\r\n\t\t\tSwap(vals + ii, vals + ii + 1);\r\n\t\t\tsorted = false;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Sorter::Flip(int *vals, int n)\r\n{\r\n\tint lo = 0, hi = n;\r\n\twhile (lo < hi)\r\n\t\tSwap(vals + lo++, vals + hi--);\r\n}\r\n\r\nint Sorter::BinarySearch(int *vals, int key, int lo, int hi)\r\n{\r\n\tint mid;\r\n\twhile (lo <= hi)\r\n\t{\r\n\t\tmid = lo + ((hi - lo) >> 1);\r\n\t\tif (vals[mid] == key)\r\n\t\t\treturn mid + 1;\r\n\t\tif (vals[mid] < key)\r\n\t\t\tlo = mid + 1;\r\n\t\telse\r\n\t\t\thi = mid - 1;\r\n\t}\r\n\treturn vals[mid] < key ? mid + 1 : mid;\r\n}\r\n\r\nvoid Sorter::Merger(int *vals, int lo, int mid, int hi)\r\n{\r\n\tint left = lo, right = mid + 1, tmp = 0;\r\n\tstd::vector<int> aux(hi - lo + 1);\r\n\twhile (left <= mid && right <= hi)\r\n\t{\r\n\t\tif (vals[left] < vals[right])\r\n\t\t\taux[tmp++] = vals[left++];\r\n\t\telse\r\n\t\t\taux[tmp++] = vals[right++];\r\n\t}\r\n\twhile (left <= mid)\r\n\t\taux[tmp++] = vals[left++];\r\n\tfor (int ii = 0; ii < tmp; ++ii)\r\n\t\tvals[ii + lo] = aux[ii];\r\n}\r\n\r\nint Sorter::Partition(int *vals, int lo, int hi)\r\n{\r\n\tint ii = lo, p = vals[lo];\r\n\tfor (int jj = ii + 1; jj <= hi; ++jj)\r\n\t{\r\n\t\tif (vals[jj] < p)\r\n\t\t\tSwap(vals + (++ii), vals + jj);\r\n\t\tSwap(vals + (++ii), vals + lo);\r\n\t}\r\n\treturn ii;\r\n}\r\n\r\nvoid Sorter::TPartition(int *vals, int lo, int hi, int &left, int &right)\r\n{\r\n\tint ii = lo, p = vals[lo];\r\n\twhile (ii <= hi)\r\n\t{\r\n\t\tif (vals[ii] < p)\r\n\t\t\tSwap(vals + (lo++), vals + (ii++));\r\n\t\telse if (vals[ii] == p)\r\n\t\t\t++ii;\r\n\t\telse\r\n\t\t\tSwap(vals + ii, vals + (hi--));\r\n\t}\r\n\tleft = lo - 1;\r\n\tright = hi + 1;\r\n}\r\n", "meta": {"hexsha": "fb3ce1a67d2e2c0850e7b4316d9f72fa05754007", "size": 7820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/Sorter.cpp", "max_stars_repo_name": "zecuse/Sorting", "max_stars_repo_head_hexsha": "bb8d878423efcf9132bf1b8a8ff948060998a212", "max_stars_repo_licenses": ["MIT"], "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++/Sorter.cpp", "max_issues_repo_name": "zecuse/Sorting", "max_issues_repo_head_hexsha": "bb8d878423efcf9132bf1b8a8ff948060998a212", "max_issues_repo_licenses": ["MIT"], "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++/Sorter.cpp", "max_forks_repo_name": "zecuse/Sorting", "max_forks_repo_head_hexsha": "bb8d878423efcf9132bf1b8a8ff948060998a212", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-01T16:41:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T16:41:34.000Z", "avg_line_length": 20.5789473684, "max_line_length": 87, "alphanum_fraction": 0.502173913, "num_tokens": 2832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5894109821401929}}
{"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) 2015 Carnegie Mellon University, Daniel Maturana <dimatura@cmu.edu>\n *\n * For License information please see the LICENSE file in the root directory.\n *\n */\n\n\n#ifndef FIXEDGRID3_HPP_6KPVVRZF\n#define FIXEDGRID3_HPP_6KPVVRZF\n\n#include <math.h>\n#include <stdint.h>\n\n#include <vector>\n\n#include <boost/shared_ptr.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <ros/console.h>\n\n#include <pcl_util/point_types.hpp>\n#include <geom_cast/geom_cast.hpp>\n\n#include \"scrollgrid/grid_types.hpp\"\n#include \"scrollgrid/box.hpp\"\n\nnamespace ca\n{\n\ntemplate<class Scalar>\nclass FixedGrid3 {\npublic:\n  typedef Scalar ScalarType; // TODO what is my convention for this?\n  typedef Eigen::Matrix<Scalar, 3, 1> Vec3;\n  typedef Eigen::Matrix<Scalar, 3, Eigen::Dynamic> Mat3;\n\n  typedef boost::shared_ptr<FixedGrid3> Ptr;\n  typedef boost::shared_ptr<const FixedGrid3> ConstPtr;\n\npublic:\n  FixedGrid3() :\n      box_(),\n      origin_(0, 0, 0),\n      min_world_corner_ijk_(0, 0, 0),\n      dimension_(0, 0, 0),\n      num_cells_(0),\n      strides_(0, 0, 0),\n      resolution_(0)\n  { }\n\n  /**\n   * @param center: center of the grid in global frame\n   * @param dimension: number of grid cells along each coordinate\n   * @param resolution: size of each grid cell side. they are cubic.\n   * Default assumes \"ZYX\" layout, i.e. z changes fastest.\n   */\n  FixedGrid3(const Vec3& center,\n             const Vec3Ix& dimension,\n             Scalar resolution,\n             bool x_fastest=false) :\n      box_(center-(dimension.cast<Scalar>()*resolution)/2,\n           center+(dimension.cast<Scalar>()*resolution)/2),\n      origin_(center-box_.radius()),\n      dimension_(dimension),\n      num_cells_(dimension.prod()),\n      resolution_(resolution)\n  {\n    if (x_fastest) {\n      strides_ = Vec3Ix(1, dimension[0], dimension.head<2>().prod());\n    } else {\n      strides_ = Vec3Ix(dimension.tail<2>().prod(), dimension[2], 1);\n    }\n    this->calc_min_corner_ijk();\n\n  }\n\n  virtual ~FixedGrid3() { }\n\n  FixedGrid3(const FixedGrid3& other) :\n      box_(other.box_),\n      origin_(other.origin_),\n      min_world_corner_ijk_(other.min_world_corner_ijk_),\n      dimension_(other.dimension_),\n      num_cells_(other.num_cells_),\n      strides_(other.strides_),\n      resolution_(other.resolution_)\n\n  {\n  }\n\n  FixedGrid3& operator=(const FixedGrid3& other) {\n    if (this==&other) { return *this; }\n    box_ = other.box_;\n    origin_ = other.origin_;\n    min_world_corner_ijk_ = other.min_world_corner_ijk_;\n    dimension_ = other.dimension_;\n    num_cells_ = other.num_cells_;\n    strides_ = other.strides_;\n    resolution_ = other.resolution_;\n    return *this;\n  }\n\npublic:\n\n  /**\n   * see ctor for params\n   */\n  void reset(const Vec3& center,\n             const Vec3Ix& dimension,\n             Scalar resolution,\n             bool x_fastest=false) {\n    box_.set_center(center);\n    box_.set_radius((dimension.template cast<Scalar>()*resolution)/2);\n    origin_ = center - box_.radius();\n    dimension_ = dimension;\n    num_cells_ = dimension.prod();\n    if (x_fastest) {\n      strides_ = Vec3Ix(1, dimension[0], dimension.head<2>().prod());\n    } else {\n      strides_ = Vec3Ix(dimension.tail<2>().prod(), dimension[2], 1);\n    }\n    resolution_ = resolution;\n  }\n\n\n  /**\n   * Is pt inside 3D box containing grid?\n   * @param pt point in same frame as center (probably world_view)\n   */\n  bool is_inside_box(const Vec3& pt) const {\n    return box_.contains(pt);\n  }\n\n  /**\n   */\n  Eigen::VectorXi multiple_is_inside_box(const Eigen::Matrix<Scalar, 3, Eigen::Dynamic>& pts) {\n    Eigen::VectorXi out(pts.cols());\n    for (int i=0; i < pts.cols(); ++i) {\n      const Eigen::Matrix<Scalar, 3, 1>& pt(pts.col(i));\n      int inside = box_.contains(pt);\n      out[i] = inside;\n    }\n    return out;\n  }\n\n  bool is_inside_box(Scalar x, Scalar y, Scalar z) const {\n    return box_.contains(Vec3(x, y, z));\n  }\n\n  template<class PointT>\n  bool is_inside_box(const PointT& pt) const {\n    return box_.contains(ca::point_cast<Eigen::Vector3d>(pt));\n  }\n\n  /**\n   * is i, j, k inside the grid limits?\n   */\n  bool is_inside_grid(const Vec3Ix& grid_ix) const {\n    return ((grid_ix.array() >= 0).all() &&\n            (grid_ix.array() < dimension_.array()).all());\n  }\n\n  bool is_inside_grid(grid_ix_t i, grid_ix_t j, grid_ix_t k) const {\n    return this->is_inside_grid(Vec3Ix(i, j, k));\n  }\n\n  /**\n   * Given position in world coordinates, return ijk grid coordinates.\n   * Note: does not check if point is inside grid.\n   */\n  Vec3Ix world_to_grid(const Vec3& xyz) const {\n    Vec3 tmp = ((xyz - origin_).array() - 0.5*resolution_)/resolution_;\n    //return tmp.cast<grid_ix_t>();\n    return Vec3Ix(round(tmp.x()), round(tmp.y()), round(tmp.z()));\n  }\n\n  Vec3Ix world_to_grid(Scalar x, Scalar y, Scalar z) const {\n    return this->world_to_grid(Vec3(x, y, z));\n  }\n\n  /**\n   * Given ijk grid coordinates resurn xyz world coordinates.\n   * xyz is center of corresponding voxel.\n   */\n  Vec3 grid_to_world(const Vec3Ix& grid_ix) const {\n    Vec3 w((grid_ix.cast<Scalar>()*resolution_ + origin_).array() + 0.5*resolution_);\n    return w;\n  }\n\n  Vec3 grid_to_world(grid_ix_t i, grid_ix_t j, grid_ix_t k) const {\n    return this->grid_to_world(Vec3Ix(i, j, k));\n  }\n\n  Mat3 multiple_grid_to_world(const Mat3Ix& grid_indices) {\n\n    Mat3 out( 3, grid_indices.cols() );\n    for (int ix=0; ix < grid_indices.cols(); ++ix) {\n      Vec3Ix gix(grid_indices.col(ix));\n      out.col(ix) = this->grid_to_world( gix );\n    }\n    return out;\n\n  }\n\n  /**\n   * given grid ijk coordinate, return linear memory index.\n   */\n  mem_ix_t grid_to_mem(grid_ix_t i, grid_ix_t j, grid_ix_t k) const {\n    return this->grid_to_mem(Vec3Ix(i, j, k));\n  }\n\n  mem_ix_t grid_to_mem(const Vec3Ix& grid_ix) const {\n    return strides_.dot(grid_ix);\n  }\n\n  MemIxVector multiple_grid_to_mem(const Mat3Ix& grid_indices) {\n    MemIxVector out( grid_indices.cols() );\n    for (int ix=0; ix < grid_indices.cols(); ++ix) {\n      Vec3Ix gix(grid_indices.col(ix));\n      out[ix] = this->grid_to_mem( gix );\n    }\n    return out;\n  }\n\n  /**\n   * given linear memory index, return ijk coordinate.\n   */\n  Vec3Ix mem_to_grid(mem_ix_t mem_ix) const {\n    grid_ix_t i = mem_ix/strides_[0];\n    mem_ix -= i*strides_[0];\n    grid_ix_t j = mem_ix/strides_[1];\n    mem_ix -= j*strides_[1];\n    grid_ix_t k = mem_ix;\n\n    return Vec3Ix(i, j, k);\n  }\n\n  /**\n   * pack into grid_ix_t as [int16, int16, int16, 0]\n   * note grid_ix_it is a signed 64-bit type\n   * this gives range of [-32768, 32768] for each coordinate\n   * so if voxel is 5cm, [-1638.4 m, 1638.4 m] relative to initial center.\n   * this is useful as a unique hash.\n   * this is better than mem_ix because mem_ix is ambiguous for absolute ijk.\n   * if we use linear mem_ix as a hash,\n   * then because of scrolling there may be collisions, and mem_ix become\n   * invalidated once the corresponding voxel scrolls out.\n   */\n  hash_ix_t grid_to_hash(const Vec3Ix& grid_ix) const {\n    // grid2 should be all positive\n    Vec3Ix grid2(grid_ix - min_world_corner_ijk_);\n\n    hash_ix_t hi = static_cast<hash_ix_t>(grid2[0]);\n    hash_ix_t hj = static_cast<hash_ix_t>(grid2[1]);\n    hash_ix_t hk = static_cast<hash_ix_t>(grid2[2]);\n    hash_ix_t h = (hi << 48) | (hj << 32) | (hk << 16);\n    return h;\n  }\n\n  Vec3Ix hash_to_grid(hash_ix_t hix) const {\n    hash_ix_t hi = (hix & 0xffff000000000000) >> 48;\n    hash_ix_t hj = (hix & 0x0000ffff00000000) >> 32;\n    hash_ix_t hk = (hix & 0x00000000ffff0000) >> 16;\n    Vec3Ix grid_ix(hi, hj, hk);\n    grid_ix += min_world_corner_ijk_;\n    return grid_ix;\n  }\n\n  Mat3Ix multiple_hash_to_grid(const HashIxVector& hindices) const {\n    Mat3Ix out( 3, hindices.rows() );\n    for (size_t i=0; i < hindices.rows(); ++i) {\n      Vec3Ix gix = this->hash_to_grid(hindices[i]);\n      out.col(i) = gix;\n    }\n    return out;\n  }\n\n  /**\n   * Like the above but does not offset by origin.\n   * In the fixed case we assume the min ijk for origin is 0,0,0.\n   */\n  hash_ix_t local_grid_to_hash(const Vec3Ix& grid_ix) const {\n    // TODO assumes grid_ix is inside box.\n    hash_ix_t hi = static_cast<hash_ix_t>(grid_ix[0]);\n    hash_ix_t hj = static_cast<hash_ix_t>(grid_ix[1]);\n    hash_ix_t hk = static_cast<hash_ix_t>(grid_ix[2]);\n    hash_ix_t h = (hi << 48) | (hj << 32) | (hk << 16);\n    return h;\n  }\n\n  Vec3Ix hash_to_local_grid(hash_ix_t hix) const {\n    hash_ix_t hi = (hix & 0xffff000000000000) >> 48;\n    hash_ix_t hj = (hix & 0x0000ffff00000000) >> 32;\n    hash_ix_t hk = (hix & 0x00000000ffff0000) >> 16;\n    Vec3Ix grid_ix(hi, hj, hk);\n    return grid_ix;\n  }\n\n  Mat3Ix multiple_local_hash_to_grid(const HashIxVector& hindices) const {\n    Mat3Ix out( 3, hindices.rows() );\n    for (size_t i=0; i < hindices.rows(); ++i) {\n      Vec3Ix gix = this->local_hash_to_grid(hindices[i]);\n      out.col(i) = gix;\n    }\n    return out;\n  }\n\n public:\n  const ca::scrollgrid::Box<Scalar, 3>& box() const { return box_; }\n  grid_ix_t dim_i() const { return dimension_[0]; }\n  grid_ix_t dim_j() const { return dimension_[1]; }\n  grid_ix_t dim_k() const { return dimension_[2]; }\n  // this is the case because of the way origin is set at construction.\n  // TODO should we allow arbitrary origins?\n  grid_ix_t first_i() const { return 0; }\n  grid_ix_t first_j() const { return 0; }\n  grid_ix_t first_k() const { return 0; }\n  grid_ix_t last_i() const { return dimension_[0]; }\n  grid_ix_t last_j() const { return dimension_[1]; }\n  grid_ix_t last_k() const { return dimension_[2]; }\n  const Vec3Ix& dimension() const { return dimension_; }\n  const Vec3& radius() const { return box_.radius(); }\n  const Vec3& origin() const { return origin_; }\n  Vec3 min_pt() const { return box_.min_pt(); }\n  Vec3 max_pt() const { return box_.max_pt(); }\n  const Vec3& center() const { return box_.center(); }\n  Scalar resolution() const { return resolution_; }\n\n  // basically equivalent to scroll_offset = (0, 0, 0)\n  grid_ix_t num_cells() const { return num_cells_; }\n\n private:\n  void calc_min_corner_ijk() {\n    // set the \"minimum possible\" ijk, assuming the grid\n    // won't stray \"too far\" from the initial position.\n    // too far == more than 2^15 grid cells.\n    // so if you voxel resolution is 1 cm, 327.68 m.\n    Scalar m = -static_cast<Scalar>(std::numeric_limits<uint16_t>::max()/2)*resolution_;\n    Vec3 m3(m, m, m);\n    //std::cerr << \"m3 = \" << m3.transpose() << std::endl;\n    m3 += box_.center();\n    //std::cerr << \"m3pcenter = \" << m3.transpose() << std::endl;\n    min_world_corner_ijk_ = this->world_to_grid(m3);\n    //std::cerr << \"min_world_corner_ijk_ = \" << min_world_corner_ijk_.transpose() << std::endl;\n  }\n\n\n private:\n  // 3d box enclosing grid. In whatever coordinates were given (probably\n  // world_view)\n  ca::scrollgrid::Box<Scalar, 3> box_;\n\n  // static origin of the grid coordinate system.\n  // it's center - box.radius\n  Vec3 origin_;\n\n  // minimum world corner in ijk. used for hash\n  Vec3Ix min_world_corner_ijk_;\n\n  // number of grid cells along each axis\n  Vec3Ix dimension_;\n\n  // number of cells\n  grid_ix_t num_cells_;\n\n  // grid strides to translate from linear to 3D layout.\n  // C-ordering, ie x slowest, z fastest.\n  Vec3Ix strides_;\n\n  // size of grid cells\n  Scalar resolution_;\n\n};\n\ntypedef FixedGrid3<double> FixedGrid3d;\ntypedef FixedGrid3<float> FixedGrid3f;\n\n} /* ca */\n\n#endif /* end of include guard: FIXEDGRID3_HPP_6KPVVRZF */\n", "meta": {"hexsha": "1a9c688cc36e25ada3d986f356dc6515e56cdd5f", "size": 11390, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/scrollgrid/fixedgrid3.hpp", "max_stars_repo_name": "castacks/scrollgrid", "max_stars_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-07-20T23:04:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T08:03:10.000Z", "max_issues_repo_path": "include/scrollgrid/fixedgrid3.hpp", "max_issues_repo_name": "castacks/scrollgrid", "max_issues_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/scrollgrid/fixedgrid3.hpp", "max_forks_repo_name": "castacks/scrollgrid", "max_forks_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T16:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T01:39:22.000Z", "avg_line_length": 29.6614583333, "max_line_length": 96, "alphanum_fraction": 0.6548726953, "num_tokens": 3318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5893284378793742}}
{"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 <iostream>\n#include <Eigen/Dense>\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n\nusing namespace Eigen;\nnamespace py = pybind11;\n\nusing RowMatrixXf = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\nEigen::MatrixXf multMatrix(MatrixXf matriz)\n{\n     MatrixXf c;\n     c = 2*matriz;\n     std::cout << \"2*matriz =\\n\" << c << std::endl;\n\n     return c;\n}\n\nvoid multMatrix_Ref(Eigen::Ref<MatrixXf> matriz)\n{\n     matriz = 2*matriz;\n     std::cout << \"2*matriz =\\n\" << matriz << std::endl;\n}\n\nvoid multRowMatrix_Ref(Eigen::Ref<RowMatrixXf> matriz)\n{\n     matriz = 2*matriz;\n     std::cout << \"2*matriz =\\n\" << matriz << std::endl;\n}\n\nEigen::MatrixXf multMatrixByMatrix_Ref(Eigen::Ref<MatrixXf> matriz1, Eigen::Ref<MatrixXf> matriz2)\n{\n\n     MatrixXf mult = matriz1 * matriz2.transpose();\n     //std::cout << \"matriz1*matriz2 =\\n\" << mult << std::endl;\n     return mult;\n}\n\nPYBIND11_MODULE(demo, m) {\n     m.doc() = \"pybind11 example plugin\"; // optional module docstring\n     m.def(\"multMatrix\", &multMatrix, \"Funcion con un argumento\",\n          py::arg(\"m\"));\n     m.def(\"multMatrixRef\", &multMatrix_Ref, \"Funcion con un argumento pasado por referencia\",\n          py::arg(\"m\"));\n     m.def(\"multRowMatrixRef\", &multRowMatrix_Ref, \"Funcion con un argumento pasado por referencia con rowMajor\",\n          py::arg(\"m\"));\n     m.def(\"multMatrixByMatrix_Ref\", &multMatrixByMatrix_Ref, \"Funcion con 2 argumento pasado por referencia\",\n          py::arg(\"matriz1\"), py::arg(\"matriz2\"));\n}\n", "meta": {"hexsha": "09bd02a3e7e0c017f9e8199eb42dbf996537731f", "size": 1524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo.cpp", "max_stars_repo_name": "argos-uach/eigen-demo", "max_stars_repo_head_hexsha": "f2caea9e324c25d5b4e9ad60494053d8dec90f1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demo.cpp", "max_issues_repo_name": "argos-uach/eigen-demo", "max_issues_repo_head_hexsha": "f2caea9e324c25d5b4e9ad60494053d8dec90f1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo.cpp", "max_forks_repo_name": "argos-uach/eigen-demo", "max_forks_repo_head_hexsha": "f2caea9e324c25d5b4e9ad60494053d8dec90f1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8823529412, "max_line_length": 113, "alphanum_fraction": 0.6535433071, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5892963289543283}}
{"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": "/**\n * @file sparse_coding_test.cpp\n *\n * Test for Sparse Coding\n */\n\n// Note: We don't use BOOST_REQUIRE_CLOSE in the code below because we need\n// to use FPC_WEAK, and it's not at all intuitive how to do that.\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/sparse_coding/sparse_coding.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::regression;\nusing namespace mlpack::sparse_coding;\n\nBOOST_AUTO_TEST_SUITE(SparseCodingTest);\n\nvoid SCVerifyCorrectness(vec beta, vec errCorr, double lambda)\n{\n  const double tol = 1e-12;\n  size_t nDims = beta.n_elem;\n  for(size_t j = 0; j < nDims; j++)\n  {\n    if (beta(j) == 0)\n    {\n      // Make sure that errCorr(j) <= lambda.\n      BOOST_REQUIRE_SMALL(std::max(fabs(errCorr(j)) - lambda, 0.0), tol);\n    }\n    else if (beta(j) < 0)\n    {\n      // Make sure that errCorr(j) == lambda.\n      BOOST_REQUIRE_SMALL(errCorr(j) - lambda, tol);\n    }\n    else // beta(j) > 0.\n    {\n      // Make sure that errCorr(j) == -lambda.\n      BOOST_REQUIRE_SMALL(errCorr(j) + lambda, tol);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SparseCodingTestCodingStepLasso)\n{\n  double lambda1 = 0.1;\n  uword nAtoms = 25;\n\n  mat X;\n  X.load(\"mnist_first250_training_4s_and_9s.arm\");\n  uword nPoints = X.n_cols;\n\n  // Normalize each point since these are images.\n  for (uword i = 0; i < nPoints; ++i) {\n    X.col(i) /= norm(X.col(i), 2);\n  }\n\n  SparseCoding<> sc(X, nAtoms, lambda1);\n  sc.OptimizeCode();\n\n  mat D = sc.Dictionary();\n  mat Z = sc.Codes();\n\n  for (uword i = 0; i < nPoints; ++i)\n  {\n    vec errCorr = trans(D) * (D * Z.unsafe_col(i) - X.unsafe_col(i));\n    SCVerifyCorrectness(Z.unsafe_col(i), errCorr, lambda1);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SparseCodingTestCodingStepElasticNet)\n{\n  double lambda1 = 0.1;\n  double lambda2 = 0.2;\n  uword nAtoms = 25;\n\n  mat X;\n  X.load(\"mnist_first250_training_4s_and_9s.arm\");\n  uword nPoints = X.n_cols;\n\n  // Normalize each point since these are images.\n  for (uword i = 0; i < nPoints; ++i)\n    X.col(i) /= norm(X.col(i), 2);\n\n  SparseCoding<> sc(X, nAtoms, lambda1, lambda2);\n  sc.OptimizeCode();\n\n  mat D = sc.Dictionary();\n  mat Z = sc.Codes();\n\n  for(uword i = 0; i < nPoints; ++i)\n  {\n    vec errCorr =\n      (trans(D) * D + lambda2 * eye(nAtoms, nAtoms)) * Z.unsafe_col(i)\n      - trans(D) * X.unsafe_col(i);\n\n    SCVerifyCorrectness(Z.unsafe_col(i), errCorr, lambda1);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SparseCodingTestDictionaryStep)\n{\n  const double tol = 1e-6;\n\n  double lambda1 = 0.1;\n  uword nAtoms = 25;\n\n  mat X;\n  X.load(\"mnist_first250_training_4s_and_9s.arm\");\n  uword nPoints = X.n_cols;\n\n  // Normalize each point since these are images.\n  for (uword i = 0; i < nPoints; ++i)\n    X.col(i) /= norm(X.col(i), 2);\n\n  SparseCoding<> sc(X, nAtoms, lambda1);\n  sc.OptimizeCode();\n\n  mat D = sc.Dictionary();\n  mat Z = sc.Codes();\n\n  uvec adjacencies = find(Z);\n  double normGradient = sc.OptimizeDictionary(adjacencies, 1e-15);\n\n  BOOST_REQUIRE_SMALL(normGradient, tol);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "0bd179f71ff2dfc99dba5e2d2dfc826460202221", "size": 3081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/sparse_coding_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/sparse_coding_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/sparse_coding_test.cpp", "max_forks_repo_name": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1654135338, "max_line_length": 75, "alphanum_fraction": 0.6556312885, "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.5892963136233619}}
{"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": "#include <iostream>\n#include <vector>\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/operation.hpp>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n\nvoid ConstructBernoulliMatrix(int M, int N, unsigned seed, boost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> &P);\n\nvoid CompressBernoulli(std::vector<double> x, double * y, int M, unsigned seed);\n", "meta": {"hexsha": "e27ebd515fb007f386f1fa4f5134328920437d00", "size": 578, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "swinzip-v2.0/src/Sampling/Sampling_Matrix.hpp", "max_stars_repo_name": "msalloum80/SWinzip", "max_stars_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-17T07:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T07:58:23.000Z", "max_issues_repo_path": "swinzip-v2.5/src/Sampling/Sampling_Matrix.hpp", "max_issues_repo_name": "msalloum80/SWinzip", "max_issues_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swinzip-v2.5/src/Sampling/Sampling_Matrix.hpp", "max_forks_repo_name": "msalloum80/SWinzip", "max_forks_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-05T20:18:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T20:18:25.000Z", "avg_line_length": 36.125, "max_line_length": 138, "alphanum_fraction": 0.7750865052, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.5892899827588338}}
{"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": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/text.hpp>\n#include <fcppt/io/cerr.hpp>\n#include <fcppt/math/box/comparison.hpp>\n#include <fcppt/math/box/extend_bounding_box.hpp>\n#include <fcppt/math/box/object_impl.hpp>\n#include <fcppt/math/box/output.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_box_extend_bounding_box_vector\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::box::object<\n\t\tint,\n\t\t2\n\t>\n\tbox_type;\n\n\tbox_type b(\n\t\tbox_type::vector(\n\t\t\t1,\n\t\t\t1\n\t\t),\n\t\tbox_type::dim(\n\t\t\t0,\n\t\t\t0\n\t\t)\n\t);\n\n\tfcppt::io::cerr()\n\t\t<< FCPPT_TEXT(\"Original box: \")\n\t\t<< b\n\t\t<< FCPPT_TEXT('\\n');\n\n\tb =\n\t\tfcppt::math::box::extend_bounding_box(\n\t\t\tb,\n\t\t\tbox_type::vector(\n\t\t\t\t3,\n\t\t\t\t4\n\t\t\t)\n\t\t);\n\n\tfcppt::io::cerr()\n\t\t<< FCPPT_TEXT(\"Added (3,4), now: \")\n\t\t<< b\n\t\t<< FCPPT_TEXT('\\n');\n\n\tBOOST_CHECK_EQUAL(\n\t\tb,\n\t\tbox_type(\n\t\t\tbox_type::vector(\n\t\t\t\t1,\n\t\t\t\t1\n\t\t\t),\n\t\t\tbox_type::dim(\n\t\t\t\t2,\n\t\t\t\t3\n\t\t\t)\n\t\t)\n\t);\n\n\tb =\n\t\tfcppt::math::box::extend_bounding_box(\n\t\t\tb,\n\t\t\tbox_type::vector(\n\t\t\t\t0,0\n\t\t\t)\n\t\t);\n\n\tfcppt::io::cerr()\n\t\t<< FCPPT_TEXT(\"Added (0,0), now: \")\n\t\t<< b\n\t\t<< FCPPT_TEXT('\\n');\n\n\t// The tests are incremental, so require is...required here\n\tBOOST_REQUIRE_EQUAL(\n\t\tb,\n\t\tbox_type(\n\t\t\tbox_type::vector(\n\t\t\t\t0,\n\t\t\t\t0\n\t\t\t),\n\t\t\tbox_type::dim(\n\t\t\t\t3,\n\t\t\t\t4\n\t\t\t)\n\t\t)\n\t);\n\n\t// This point is inside the bounding box -> nothing should change\n\tb =\n\t\tfcppt::math::box::extend_bounding_box(\n\t\t\tb,\n\t\t\tbox_type::vector(\n\t\t\t\t1,\n\t\t\t\t1\n\t\t\t)\n\t\t);\n\n\tfcppt::io::cerr()\n\t\t<< FCPPT_TEXT(\"Added (1,1), now: \")\n\t\t<< b\n\t\t<< FCPPT_TEXT('\\n');\n\n\tBOOST_REQUIRE_EQUAL(\n\t\tb,\n\t\tbox_type(\n\t\t\tbox_type::vector(\n\t\t\t\t0,\n\t\t\t\t0\n\t\t\t),\n\t\t\tbox_type::dim(\n\t\t\t\t3,\n\t\t\t\t4\n\t\t\t)\n\t\t)\n\t);\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_box_extend_bounding_box_box\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::box::object<\n\t\tint,\n\t\t2\n\t>\n\tbox_type;\n\n\tbox_type const box1(\n\t\tbox_type::vector(\n\t\t\t1,\n\t\t\t2\n\t\t),\n\t\tbox_type::dim(\n\t\t\t2,\n\t\t\t3\n\t\t)\n\t);\n\n\tbox_type const box2(\n\t\tbox_type::vector(\n\t\t\t0,\n\t\t\t1\n\t\t),\n\t\tbox_type::dim(\n\t\t\t2,\n\t\t\t1\n\t\t)\n\t);\n\n\tbox_type const expected(\n\t\tbox_type::vector(\n\t\t\t0,\n\t\t\t1\n\t\t),\n\t\tbox_type::dim(\n\t\t\t3,\n\t\t\t4\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::box::extend_bounding_box(\n\t\t\tbox1,\n\t\t\tbox2\n\t\t),\n\t\texpected\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::box::extend_bounding_box(\n\t\t\tbox2,\n\t\t\tbox1\n\t\t),\n\t\texpected\n\t);\n}\n", "meta": {"hexsha": "247ed335e6f339007b8f9d91e237e5e44a13db49", "size": 2839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/box/extend.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/box/extend.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/box/extend.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.9166666667, "max_line_length": 66, "alphanum_fraction": 0.6209933075, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.5892899824652028}}
{"text": "/*\n    tests/eigen.cpp -- automatic conversion of Eigen types\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"pybind11_tests.h\"\n#include <pybind11/eigen.h>\n#include <Eigen/Cholesky>\n\nEigen::VectorXf double_col(const Eigen::VectorXf& x)\n{ return 2.0f * x; }\n\nEigen::RowVectorXf double_row(const Eigen::RowVectorXf& x)\n{ return 2.0f * x; }\n\nEigen::MatrixXf double_mat_cm(const Eigen::MatrixXf& x)\n{ return 2.0f * x; }\n\n// Different ways of passing via Eigen::Ref; the first and second are the Eigen-recommended\nEigen::MatrixXd cholesky1(Eigen::Ref<Eigen::MatrixXd> &x) { return x.llt().matrixL(); }\nEigen::MatrixXd cholesky2(const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.llt().matrixL(); }\nEigen::MatrixXd cholesky3(const Eigen::Ref<Eigen::MatrixXd> &x) { return x.llt().matrixL(); }\nEigen::MatrixXd cholesky4(Eigen::Ref<const Eigen::MatrixXd> &x) { return x.llt().matrixL(); }\nEigen::MatrixXd cholesky5(Eigen::Ref<Eigen::MatrixXd> x) { return x.llt().matrixL(); }\nEigen::MatrixXd cholesky6(Eigen::Ref<const Eigen::MatrixXd> x) { return x.llt().matrixL(); }\n\ntypedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXfRowMajor;\nMatrixXfRowMajor double_mat_rm(const MatrixXfRowMajor& x)\n{ return 2.0f * x; }\n\ntest_initializer eigen([](py::module &m) {\n    typedef Eigen::Matrix<float, 5, 6, Eigen::RowMajor> FixedMatrixR;\n    typedef Eigen::Matrix<float, 5, 6> FixedMatrixC;\n    typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> DenseMatrixR;\n    typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> DenseMatrixC;\n    typedef Eigen::SparseMatrix<float, Eigen::RowMajor> SparseMatrixR;\n    typedef Eigen::SparseMatrix<float> SparseMatrixC;\n\n    m.attr(\"have_eigen\") = py::cast(true);\n\n    // Non-symmetric matrix with zero elements\n    Eigen::MatrixXf mat(5, 6);\n    mat << 0, 3, 0, 0, 0, 11, 22, 0, 0, 0, 17, 11, 7, 5, 0, 1, 0, 11, 0,\n        0, 0, 0, 0, 11, 0, 0, 14, 0, 8, 11;\n\n    m.def(\"double_col\", &double_col);\n    m.def(\"double_row\", &double_row);\n    m.def(\"double_mat_cm\", &double_mat_cm);\n    m.def(\"double_mat_rm\", &double_mat_rm);\n    m.def(\"cholesky1\", &cholesky1);\n    m.def(\"cholesky2\", &cholesky2);\n    m.def(\"cholesky3\", &cholesky3);\n    m.def(\"cholesky4\", &cholesky4);\n    m.def(\"cholesky5\", &cholesky5);\n    m.def(\"cholesky6\", &cholesky6);\n\n    // Returns diagonals: a vector-like object with an inner stride != 1\n    m.def(\"diagonal\", [](const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.diagonal(); });\n    m.def(\"diagonal_1\", [](const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.diagonal<1>(); });\n    m.def(\"diagonal_n\", [](const Eigen::Ref<const Eigen::MatrixXd> &x, int index) { return x.diagonal(index); });\n\n    // Return a block of a matrix (gives non-standard strides)\n    m.def(\"block\", [](const Eigen::Ref<const Eigen::MatrixXd> &x, int start_row, int start_col, int block_rows, int block_cols) {\n        return x.block(start_row, start_col, block_rows, block_cols);\n    });\n\n    // Returns a DiagonalMatrix with diagonal (1,2,3,...)\n    m.def(\"incr_diag\", [](int k) {\n        Eigen::DiagonalMatrix<int, Eigen::Dynamic> m(k);\n        for (int i = 0; i < k; i++) m.diagonal()[i] = i+1;\n        return m;\n    });\n\n    // Returns a SelfAdjointView referencing the lower triangle of m\n    m.def(\"symmetric_lower\", [](const Eigen::MatrixXi &m) {\n            return m.selfadjointView<Eigen::Lower>();\n    });\n    // Returns a SelfAdjointView referencing the lower triangle of m\n    m.def(\"symmetric_upper\", [](const Eigen::MatrixXi &m) {\n            return m.selfadjointView<Eigen::Upper>();\n    });\n\n    m.def(\"fixed_r\", [mat]() -> FixedMatrixR {\n        return FixedMatrixR(mat);\n    });\n\n    m.def(\"fixed_c\", [mat]() -> FixedMatrixC {\n        return FixedMatrixC(mat);\n    });\n\n    m.def(\"fixed_passthrough_r\", [](const FixedMatrixR &m) -> FixedMatrixR {\n        return m;\n    });\n\n    m.def(\"fixed_passthrough_c\", [](const FixedMatrixC &m) -> FixedMatrixC {\n        return m;\n    });\n\n    m.def(\"dense_r\", [mat]() -> DenseMatrixR {\n        return DenseMatrixR(mat);\n    });\n\n    m.def(\"dense_c\", [mat]() -> DenseMatrixC {\n        return DenseMatrixC(mat);\n    });\n\n    m.def(\"dense_passthrough_r\", [](const DenseMatrixR &m) -> DenseMatrixR {\n        return m;\n    });\n\n    m.def(\"dense_passthrough_c\", [](const DenseMatrixC &m) -> DenseMatrixC {\n        return m;\n    });\n\n    m.def(\"sparse_r\", [mat]() -> SparseMatrixR {\n        return Eigen::SparseView<Eigen::MatrixXf>(mat);\n    });\n\n    m.def(\"sparse_c\", [mat]() -> SparseMatrixC {\n        return Eigen::SparseView<Eigen::MatrixXf>(mat);\n    });\n\n    m.def(\"sparse_passthrough_r\", [](const SparseMatrixR &m) -> SparseMatrixR {\n        return m;\n    });\n\n    m.def(\"sparse_passthrough_c\", [](const SparseMatrixC &m) -> SparseMatrixC {\n        return m;\n    });\n});\n", "meta": {"hexsha": "a9cb9f21c704931e67a6e4e8c96883e7619805ec", "size": 4981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/instant-meshes/instant-meshes-dust3d/ext/nanogui/ext/pybind11/tests/test_eigen.cpp", "max_stars_repo_name": "MelvinG24/dust3d", "max_stars_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "thirdparty/instant-meshes/instant-meshes-dust3d/ext/nanogui/ext/pybind11/tests/test_eigen.cpp", "max_issues_repo_name": "MelvinG24/dust3d", "max_issues_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "thirdparty/instant-meshes/instant-meshes-dust3d/ext/nanogui/ext/pybind11/tests/test_eigen.cpp", "max_forks_repo_name": "MelvinG24/dust3d", "max_forks_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 36.8962962963, "max_line_length": 129, "alphanum_fraction": 0.6408351737, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.7718435083355188, "lm_q1q2_score": 0.589289978311455}}
{"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 \u25c0---v4---(cotan2)\n                                   \u25e5 \u25e4         /\n                                  /   \\       /\n                                 v2    v5    v3\n                                /       \\   /\n                               /         \\ \u25e3\n                        (cotan1)----v1---\u25b6c_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                                   \u25e5\n                                  /  \\\n                                 v2   \\\n                                /      \\\n                               /        \\\n                        (cotan)----v1---\u25b6 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": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <test/unit/math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdGammaP, gamma_p) {\n  using boost::math::gamma_p;\n  using stan::math::fvar;\n  using stan::math::gamma_p;\n\n  fvar<double> x(0.5);\n  x.d_ = 1.0;\n  fvar<double> y(1.0);\n  y.d_ = 1.0;\n\n  fvar<double> a = gamma_p(x, y);\n  EXPECT_FLOAT_EQ(gamma_p(0.5, 1.0), a.val_);\n  EXPECT_FLOAT_EQ(-0.18228334, a.d_);\n\n  double z = 1.0;\n  double w = 0.5;\n\n  a = gamma_p(x, z);\n  EXPECT_FLOAT_EQ(gamma_p(0.5, 1.0), a.val_);\n  EXPECT_FLOAT_EQ(-0.389837, a.d_);\n\n  a = gamma_p(w, y);\n  EXPECT_FLOAT_EQ(gamma_p(0.5, 1.0), a.val_);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5, 1.0), a.d_);\n\n  EXPECT_THROW(gamma_p(-x, y), std::domain_error);\n  EXPECT_THROW(gamma_p(x, -y), std::domain_error);\n}\n\nTEST(AgradFwdGammaP, FvarFvarDouble) {\n  using boost::math::gamma_p;\n  using stan::math::fvar;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<double> > a = gamma_p(x, y);\n\n  EXPECT_FLOAT_EQ(gamma_p(0.5, 1.0), a.val_.val_);\n  EXPECT_FLOAT_EQ(-0.38983709, a.val_.d_);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5, 1.0), a.d_.val_);\n  EXPECT_FLOAT_EQ(0.40753385, a.d_.d_);\n}\n\nstruct gamma_p_fun {\n  template <typename T0, typename T1>\n  inline typename boost::math::tools::promote_args<T0, T1>::type operator()(\n      const T0 arg1, const T1 arg2) const {\n    return gamma_p(arg1, arg2);\n  }\n};\n\nTEST(AgradFwdGammaP, nan) {\n  gamma_p_fun gamma_p_;\n  test_nan_fwd(gamma_p_, 3.0, 5.0, false);\n}\n", "meta": {"hexsha": "d691779acceae47cf7b2ed4df9ac6a9aee200606", "size": 1708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/fwd/scal/fun/gamma_p_test.cpp", "max_stars_repo_name": "danluu/math", "max_stars_repo_head_hexsha": "a293807aadc0f0d57fa56fec70251ac70f1bd8c4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/math/fwd/scal/fun/gamma_p_test.cpp", "max_issues_repo_name": "danluu/math", "max_issues_repo_head_hexsha": "a293807aadc0f0d57fa56fec70251ac70f1bd8c4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/fwd/scal/fun/gamma_p_test.cpp", "max_forks_repo_name": "danluu/math", "max_forks_repo_head_hexsha": "a293807aadc0f0d57fa56fec70251ac70f1bd8c4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1176470588, "max_line_length": 76, "alphanum_fraction": 0.6692037471, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.589223366838716}}
{"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\u00e9lie 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": "// Copyright (C) 2009  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <dlib/matrix.h>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <vector>\n#include \"../stl_checked.h\"\n#include \"../array.h\"\n#include \"../rand.h\"\n#include <dlib/string.h>\n\n#include \"tester.h\"\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    logger dlog(\"test.matrix_eig\");\n\n    dlib::rand rnd;\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename type>\n    const matrix<type> randm(long r, long c)\n    {\n        matrix<type> m(r,c);\n        for (long row = 0; row < m.nr(); ++row)\n        {\n            for (long col = 0; col < m.nc(); ++col)\n            {\n                m(row,col) = static_cast<type>(rnd.get_random_double()); \n            }\n        }\n\n        return m;\n    }\n\n    template <typename type, long NR, long NC>\n    const matrix<type,NR,NC> randm()\n    {\n        matrix<type,NR,NC> m;\n        for (long row = 0; row < m.nr(); ++row)\n        {\n            for (long col = 0; col < m.nc(); ++col)\n            {\n                m(row,col) = static_cast<type>(rnd.get_random_double()); \n            }\n        }\n\n        return m;\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename matrix_type, typename U>\n    void test_eigenvalue_impl ( const matrix_type& m,  const eigenvalue_decomposition<U>& test )\n    {\n        typedef typename matrix_type::type type;\n        const type eps = 10*max(abs(m))*sqrt(std::numeric_limits<type>::epsilon());\n        dlog << LDEBUG << \"test_eigenvalue():  \" << m.nr() << \" x \" << m.nc() << \"  eps: \" << eps;\n        print_spinner();\n\n\n        DLIB_TEST(test.dim() == m.nr());\n\n        // make sure all the various ways of asking for the eigenvalues are actually returning a\n        // consistent set of eigenvalues.\n        DLIB_TEST(equal(real(test.get_eigenvalues()), test.get_real_eigenvalues(), eps)); \n        DLIB_TEST(equal(imag(test.get_eigenvalues()), test.get_imag_eigenvalues(), eps)); \n        DLIB_TEST(equal(real(diag(test.get_d())), test.get_real_eigenvalues(), eps)); \n        DLIB_TEST(equal(imag(diag(test.get_d())), test.get_imag_eigenvalues(), eps)); \n\n        matrix<type> eig1 ( real_eigenvalues(m));\n        matrix<type> eig2 ( test.get_real_eigenvalues());\n        sort(&eig1(0), &eig1(0) + eig1.size());\n        sort(&eig2(0), &eig2(0) + eig2.size());\n        DLIB_TEST(max(abs(eig1 - eig2)) < eps);\n\n        const matrix<type> V = test.get_pseudo_v();\n        const matrix<type> D = test.get_pseudo_d();\n        const matrix<complex<type> > CV = test.get_v();\n        const matrix<complex<type> > CD = test.get_d();\n        const matrix<complex<type> > CM = complex_matrix(m, uniform_matrix<type>(m.nr(),m.nc(),0));\n\n        DLIB_TEST(V.nr() == test.dim());\n        DLIB_TEST(V.nc() == test.dim());\n        DLIB_TEST(D.nr() == test.dim());\n        DLIB_TEST(D.nc() == test.dim());\n\n        // CD is a diagonal matrix\n        DLIB_TEST(diagm(diag(CD)) == CD);\n\n        // verify that these things are actually eigenvalues and eigenvectors of m\n        DLIB_TEST_MSG(max(abs(m*V - V*D)) < eps, max(abs(m*V - V*D)) << \"   \" << eps);\n        DLIB_TEST(max(norm(CM*CV - CV*CD)) < eps);\n\n        // if m is a symmetric matrix\n        if (max(abs(m-trans(m))) < 1e-5)\n        {\n            dlog << LTRACE << \"m is symmetric\";\n            // there aren't any imaginary eigenvalues \n            DLIB_TEST(max(abs(test.get_imag_eigenvalues())) < eps); \n            DLIB_TEST(diagm(diag(D)) == D);\n\n            // only check the determinant against the eigenvalues for small matrices\n            // because for huge ones the determinant might be so big it overflows a floating point number.\n            if (m.nr() < 50) \n            {\n                const type mdet = det(m);\n                DLIB_TEST_MSG(std::abs(prod(test.get_real_eigenvalues()) - mdet) < std::abs(mdet)*sqrt(std::numeric_limits<type>::epsilon()),\n                              std::abs(prod(test.get_real_eigenvalues()) - mdet) <<\"    eps: \" << std::abs(mdet)*sqrt(std::numeric_limits<type>::epsilon())\n                              << \"  mdet: \"<< mdet << \"   prod(eig): \" << prod(test.get_real_eigenvalues())\n                );\n            }\n\n            // V is orthogonal\n            DLIB_TEST(equal(V*trans(V), identity_matrix<type>(test.dim()), eps));\n            DLIB_TEST(equal(m , V*D*trans(V), eps));\n        }\n        else\n        {\n            dlog << LTRACE << \"m is NOT symmetric\";\n            DLIB_TEST_MSG(equal(m , V*D*inv(V), eps), max(abs(m - V*D*inv(V))));\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename matrix_type>\n    void test_eigenvalue ( const matrix_type& m )\n    {\n        typedef typename matrix_type::type type;\n        typedef typename matrix_type::mem_manager_type MM;\n        matrix<type,matrix_type::NR, matrix_type::NC, MM, row_major_layout> mr(m); \n        matrix<type,matrix_type::NR, matrix_type::NC, MM, column_major_layout> mc(m); \n\n        {\n        eigenvalue_decomposition<matrix_type> test(mr);\n        test_eigenvalue_impl(mr, test);\n\n        eigenvalue_decomposition<matrix_type> test_symm(make_symmetric(mr));\n        test_eigenvalue_impl(make_symmetric(mr), test_symm);\n        }\n\n        {\n        eigenvalue_decomposition<matrix_type> test(mc);\n        test_eigenvalue_impl(mc, test);\n\n        eigenvalue_decomposition<matrix_type> test_symm(make_symmetric(mc));\n        test_eigenvalue_impl(make_symmetric(mc), test_symm);\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void matrix_test_double()\n    {\n\n        test_eigenvalue(10*randm<double>(1,1));\n        test_eigenvalue(10*randm<double>(2,2));\n        test_eigenvalue(10*randm<double>(3,3));\n        test_eigenvalue(10*randm<double>(4,4));\n        test_eigenvalue(10*randm<double>(15,15));\n        test_eigenvalue(10*randm<double>(150,150));\n\n        test_eigenvalue(10*randm<double,1,1>());\n        test_eigenvalue(10*randm<double,2,2>());\n        test_eigenvalue(10*randm<double,3,3>());\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void matrix_test_float()\n    {\n\n        test_eigenvalue(10*randm<float>(1,1));\n        test_eigenvalue(10*randm<float>(2,2));\n        test_eigenvalue(10*randm<float>(3,3));\n        test_eigenvalue(10*randm<float>(4,4));\n        test_eigenvalue(10*randm<float>(15,15));\n        test_eigenvalue(10*randm<float>(50,50));\n\n        test_eigenvalue(10*randm<float,1,1>());\n        test_eigenvalue(10*randm<float,2,2>());\n        test_eigenvalue(10*randm<float,3,3>());\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    class matrix_tester : public tester\n    {\n    public:\n        matrix_tester (\n        ) :\n            tester (\"test_matrix_eig\",\n                    \"Runs tests on the matrix eigen decomp component.\")\n        {\n            //rnd.set_seed(cast_to_string(time(0)));\n        }\n\n        void perform_test (\n        )\n        {\n            dlog << LINFO << \"seed string: \" << rnd.get_seed();\n\n            dlog << LINFO << \"begin testing with double\";\n            matrix_test_double();\n            dlog << LINFO << \"begin testing with float\";\n            matrix_test_float();\n        }\n    } a;\n\n}\n\n\n\n", "meta": {"hexsha": "c86f90f7b31773e8c57cdfc0e892e7570d16f2f4", "size": 7604, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/dlib/test/matrix_eig.cpp", "max_stars_repo_name": "markovchainz/cppagent", "max_stars_repo_head_hexsha": "97314ec43786a90697ca7fda15db13f2973aee3e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 51.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T06:50:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T21:00:13.000Z", "max_issues_repo_path": "lib/dlib/test/matrix_eig.cpp", "max_issues_repo_name": "markovchainz/cppagent", "max_issues_repo_head_hexsha": "97314ec43786a90697ca7fda15db13f2973aee3e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-05-03T00:28:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-30T12:32:16.000Z", "max_forks_repo_path": "lib/dlib/test/matrix_eig.cpp", "max_forks_repo_name": "markovchainz/cppagent", "max_forks_repo_head_hexsha": "97314ec43786a90697ca7fda15db13f2973aee3e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-03-02T18:48:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T06:44:08.000Z", "avg_line_length": 33.7955555556, "max_line_length": 155, "alphanum_fraction": 0.5273540242, "num_tokens": 1871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.5892233540855406}}
{"text": "#pragma once\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n#include <boost/geometry/geometries/register/segment.hpp>\n#include <boost/optional.hpp>\n#include <vector>\n\nnamespace sssp {\n\nstruct rgb {\n    rgb() : r(0.0), g(0.0), b(0.0) {}\n    rgb(double r, double g, double b) : r(r), g(g), b(b) {}\n    double r;\n    double g;\n    double b;\n};\n\nstruct vec2 {\n    vec2() : x(0.0), y(0.0) {}\n    vec2(double x, double y) : x(x), y(y) {}\n    double x;\n    double y;\n};\n\ninline bool operator==(const vec2& a, const vec2& b) {\n    return a.x == b.x && a.y == b.y;\n}\n\ninline bool operator!=(const vec2& a, const vec2& b) {\n    return !(a == b);\n}\n\ninline vec2 operator+(const vec2& a, const vec2& b) {\n    return vec2(a.x + b.x, a.y + b.y);\n}\n\ninline vec2 operator-(const vec2& a, const vec2& b) {\n    return vec2(a.x - b.x, a.y - b.y);\n}\n\ninline vec2 normalize(const vec2& v) {\n    double f = std::sqrt(v.x * v.x + v.y * v.y);\n    return vec2(v.x / f, v.y / f);\n}\n\nstruct line {\n    line(const vec2& start, const vec2& end) : start(start), end(end) {}\n    vec2 start;\n    vec2 end;\n};\n\ndouble distance(const vec2& a, const vec2& b);\nbool intersects(const line& a, const line& b);\n\n} // namespace sssp\n\nBOOST_GEOMETRY_REGISTER_POINT_2D(sssp::vec2, double, boost::geometry::cs::cartesian, x, y)\nBOOST_GEOMETRY_REGISTER_SEGMENT(sssp::line, sssp::vec2, start, end)\n", "meta": {"hexsha": "8c28c6cd17ebb47863e40b417379039755fddc72", "size": 1392, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math.hpp", "max_stars_repo_name": "kaini/sssp-simulation", "max_stars_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_stars_repo_licenses": ["MIT"], "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": "kaini/sssp-simulation", "max_issues_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_issues_repo_licenses": ["MIT"], "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": "kaini/sssp-simulation", "max_forks_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_forks_repo_licenses": ["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.593220339, "max_line_length": 90, "alphanum_fraction": 0.6185344828, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.5892233409411732}}
{"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// \u524d\u9762\u7684\u51e0\u4e2ainclude\u6587\u4ef6\u5df2\u7ecf\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u4f7f\u7528\u8fc7\u4e86\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u8fd9\u91cc\u4e0d\u518d\u89e3\u91ca\u5b83\u4eec\u7684\u542b\u4e49\u3002\u8be5\u7a0b\u5e8f\u7684\u4e3b\u8981\u7ed3\u6784\u4e0e\u4f8b\u5982 step-4 \u7684\u7ed3\u6784\u975e\u5e38\u76f8\u4f3c\uff0c\u56e0\u6b64\u6211\u4eec\u5305\u542b\u4e86\u8bb8\u591a\u76f8\u540c\u7684\u5934\u6587\u4ef6\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n\n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/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// \u6700\u6709\u8da3\u7684\u4e24\u4e2a\u5934\u6587\u4ef6\u5c06\u662f\u8fd9\u4e24\u4e2a\u3002\n\n#include <deal.II/fe/fe_interface_values.h> \n#include <deal.II/meshworker/mesh_loop.h> \n\n// \u5176\u4e2d\u7b2c\u4e00\u4e2a\u6587\u4ef6\u8d1f\u8d23\u63d0\u4f9bFEInterfaceValues\u7c7b\uff0c\u8be5\u7c7b\u53ef\u7528\u4e8e\u8bc4\u4f30\u5355\u5143\u95f4\u754c\u9762\u7684\u5f62\u72b6\u51fd\u6570\uff08\u6216\u5176\u68af\u5ea6\uff09\u7684\u8df3\u8dc3\u6216\u5e73\u5747\u503c\u7b49\u6570\u91cf\u3002\u8fd9\u4e2a\u7c7b\u5728\u8bc4\u4f30C0IP\u516c\u5f0f\u4e2d\u51fa\u73b0\u7684\u60e9\u7f5a\u9879\u65f6\u5c06\u76f8\u5f53\u6709\u7528\u3002\n\n#include <fstream> \n#include <iostream> \n#include <cmath> \n\nnamespace Step47 \n{ \n  using namespace dealii; \n\n// \u5728\u4e0b\u9762\u7684\u547d\u540d\u7a7a\u95f4\u4e2d\uff0c\u8ba9\u6211\u4eec\u5b9a\u4e49\u7cbe\u786e\u89e3\uff0c\u6211\u4eec\u5c06\u4e0e\u6570\u503c\u8ba1\u7b97\u7684\u89e3\u8fdb\u884c\u6bd4\u8f83\u3002\u5b83\u7684\u5f62\u5f0f\u662f $u(x,y) = \\sin(\\pi x) \\sin(\\pi y)$ \uff08\u53ea\u5b9e\u73b0\u4e862d\u7684\u60c5\u51b5\uff09\uff0c\u8be5\u547d\u540d\u7a7a\u95f4\u8fd8\u5305\u542b\u4e00\u4e2a\u5bf9\u5e94\u4e8e\u4ea7\u751f\u8be5\u89e3\u7684\u53f3\u624b\u8fb9\u7684\u7c7b\u3002\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// \u4ee5\u4e0b\u662f\u672c\u6559\u7a0b\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u3002\u5b83\u5177\u6709\u8bb8\u591a\u5176\u4ed6\u6559\u7a0b\u7a0b\u5e8f\u7684\u7ed3\u6784\uff0c\u5176\u5185\u5bb9\u548c\u540e\u9762\u7684\u6784\u9020\u51fd\u6570\u5e94\u8be5\u6ca1\u6709\u4ec0\u4e48\u7279\u522b\u4ee4\u4eba\u60ca\u8bb6\u7684\u5730\u65b9\u3002\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// \u63a5\u4e0b\u6765\u662f\u521b\u5efa\u521d\u59cb\u7f51\u683c\uff08\u4e00\u6b21\u7cbe\u70bc\u7684\u5355\u5143\u683c\uff09\u548c\u8bbe\u7f6e\u6bcf\u4e2a\u7f51\u683c\u7684\u7ea6\u675f\u3001\u5411\u91cf\u548c\u77e9\u9635\u7684\u51fd\u6570\u3002\u540c\u6837\uff0c\u8fd9\u4e24\u4e2a\u51fd\u6570\u4e0e\u4e4b\u524d\u7684\u8bb8\u591a\u6559\u7a0b\u7a0b\u5e8f\u57fa\u672c\u6ca1\u6709\u53d8\u5316\u3002\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// \u4e0b\u9762\u7684\u51e0\u6bb5\u4ee3\u7801\u66f4\u6709\u610f\u601d\u3002\u5b83\u4eec\u90fd\u4e0e\u7ebf\u6027\u7cfb\u7edf\u7684\u7ec4\u88c5\u6709\u5173\u3002\u867d\u7136\u7ec4\u88c5\u5355\u5143\u683c\u5185\u90e8\u9879\u7684\u96be\u5ea6\u4e0d\u5927--\u8fd9\u5728\u672c\u8d28\u4e0a\u5c31\u50cf\u7ec4\u88c5\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u7684\u76f8\u5e94\u9879\u4e00\u6837\uff0c\u4f60\u5df2\u7ecf\u5728 step-4 \u6216 step-6 \u4e2d\u770b\u5230\u4e86\u8fd9\u662f\u5982\u4f55\u5de5\u4f5c\u7684\uff0c\u4f8b\u5982\uff0c\u56f0\u96be\u5728\u4e8e\u516c\u5f0f\u4e2d\u7684\u60e9\u7f5a\u9879\u3002\u8fd9\u9700\u8981\u5728\u5355\u5143\u683c\u7684\u754c\u9762\u4e0a\u5bf9\u5f62\u72b6\u51fd\u6570\u7684\u68af\u5ea6\u8fdb\u884c\u8bc4\u4f30\u3002\u56e0\u6b64\uff0c\u81f3\u5c11\u9700\u8981\u4f7f\u7528\u4e24\u4e2aFEFaceValues\u5bf9\u8c61\uff0c\u4f46\u5982\u679c\u5176\u4e2d\u4e00\u4e2a\u9762\u662f\u81ea\u9002\u5e94\u7ec6\u5316\u7684\uff0c\u90a3\u4e48\u5b9e\u9645\u4e0a\u9700\u8981\u4e00\u4e2aFEFaceValues\u548c\u4e00\u4e2aFESubfaceValues\u5bf9\u8c61\uff1b\u6211\u4eec\u8fd8\u9700\u8981\u8ddf\u8e2a\u54ea\u4e9b\u5f62\u72b6\u51fd\u6570\u5728\u54ea\u91cc\uff0c\u6700\u540e\u6211\u4eec\u9700\u8981\u786e\u4fdd\u6bcf\u4e2a\u9762\u53ea\u88ab\u8bbf\u95ee\u4e00\u6b21\u3002\u6240\u6709\u8fd9\u4e9b\u5bf9\u4e8e\u6211\u4eec\u771f\u6b63\u60f3\u8981\u5b9e\u73b0\u7684\u903b\u8f91\uff08\u5373\u53cc\u7ebf\u6027\u5f62\u5f0f\u4e2d\u7684\u60e9\u7f5a\u9879\uff09\u6765\u8bf4\u90fd\u662f\u4e00\u7b14\u4e0d\u5c0f\u7684\u5f00\u9500\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5c06\u4f7f\u7528FEInterfaceValues\u7c7b--\u8fd9\u662fdeal.II\u4e2d\u7684\u4e00\u4e2a\u8f85\u52a9\u7c7b\uff0c\u5b83\u5141\u8bb8\u6211\u4eec\u62bd\u8c61\u51fa\u4e24\u4e2aFEFaceValues\u6216FESubfaceValues\u5bf9\u8c61\uff0c\u76f4\u63a5\u8bbf\u95ee\u6211\u4eec\u771f\u6b63\u5173\u5fc3\u7684\u4e1c\u897f\uff1a\u8df3\u8dc3\u3001\u5e73\u5747\u7b49\u3002\n\n// \u4f46\u8fd9\u8fd8\u6ca1\u6709\u89e3\u51b3\u6211\u4eec\u7684\u95ee\u9898\uff0c\u5373\u5f53\u6211\u4eec\u5728\u6240\u6709\u5355\u5143\u683c\u548c\u5b83\u4eec\u7684\u6240\u6709\u9762\u4e2d\u5faa\u73af\u65f6\uff0c\u5fc5\u987b\u8ddf\u8e2a\u6211\u4eec\u5df2\u7ecf\u8bbf\u95ee\u8fc7\u54ea\u4e9b\u9762\u3002\u4e3a\u4e86\u4f7f\u8fd9\u4e2a\u8fc7\u7a0b\u66f4\u7b80\u5355\uff0c\u6211\u4eec\u4f7f\u7528\u4e86 MeshWorker::mesh_loop() \u51fd\u6570\uff0c\u5b83\u4e3a\u8fd9\u4e2a\u4efb\u52a1\u63d0\u4f9b\u4e86\u4e00\u4e2a\u7b80\u5355\u7684\u63a5\u53e3\uff1a\u57fa\u4e8eWorkStream\u547d\u540d\u7a7a\u95f4\u6587\u6863\u4e2d\u6982\u8ff0\u7684\u60f3\u6cd5\uff0c MeshWorker::mesh_loop() \u9700\u8981\u4e09\u4e2a\u51fd\u6570\u5bf9\u5355\u5143\u3001\u5185\u90e8\u9762\u548c\u8fb9\u754c\u9762\u8fdb\u884c\u5de5\u4f5c\u3002\u8fd9\u4e9b\u51fd\u6570\u5728\u6293\u53d6\u5bf9\u8c61\u4e0a\u5de5\u4f5c\uff0c\u4ee5\u83b7\u5f97\u4e2d\u95f4\u7ed3\u679c\uff0c\u7136\u540e\u5c06\u5176\u8ba1\u7b97\u7ed3\u679c\u590d\u5236\u5230\u590d\u5236\u6570\u636e\u5bf9\u8c61\u4e2d\uff0c\u7531\u4e00\u4e2a\u590d\u5236\u5668\u51fd\u6570\u5c06\u5176\u590d\u5236\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u4fa7\u5bf9\u8c61\u4e2d\u3002\n\n// \u7136\u540e\uff0c\u4e0b\u9762\u7684\u7ed3\u6784\u63d0\u4f9b\u4e86\u8fd9\u79cd\u65b9\u6cd5\u6240\u9700\u7684\u4ece\u5934\u5f00\u59cb\u548c\u590d\u5236\u5bf9\u8c61\u3002\u4f60\u53ef\u4ee5\u67e5\u9605WorkStream\u547d\u540d\u7a7a\u95f4\u4ee5\u53ca @ref threads \"\u591a\u5904\u7406\u5668\u5e76\u884c\u8ba1\u7b97 \"\u6a21\u5757\uff0c\u4e86\u89e3\u66f4\u591a\u5173\u4e8e\u5b83\u4eec\u901a\u5e38\u5982\u4f55\u5de5\u4f5c\u7684\u4fe1\u606f\u3002\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// \u66f4\u6709\u8da3\u7684\u90e8\u5206\u662f\u6211\u4eec\u5b9e\u9645\u7ec4\u88c5\u7ebf\u6027\u7cfb\u7edf\u7684\u5730\u65b9\u3002\u4ece\u6839\u672c\u4e0a\u8bf4\uff0c\u8fd9\u4e2a\u51fd\u6570\u6709\u4e94\u4e2a\u90e8\u5206\u3002\n\n// - `cell_worker`\u03bb\u51fd\u6570\u7684\u5b9a\u4e49\uff0c\u8fd9\u662f\u4e00\u4e2a\u5b9a\u4e49\u5728`assemble_system()`\u51fd\u6570\u4e2d\u7684\u5c0f\u51fd\u6570\uff0c\u5b83\u5c06\u8d1f\u8d23\u8ba1\u7b97\u5355\u4e2a\u5355\u5143\u4e0a\u7684\u5c40\u90e8\u79ef\u5206\u3002\u5b83\u5c06\u5728`ScratchData`\u7c7b\u7684\u526f\u672c\u4e0a\u5de5\u4f5c\uff0c\u5e76\u5c06\u5176\u7ed3\u679c\u653e\u5165\u76f8\u5e94\u7684`CopyData`\u5bf9\u8c61\u3002\n\n// - `face_worker` lambda\u51fd\u6570\u7684\u5b9a\u4e49\uff0c\u5b83\u5c06\u5bf9\u5355\u5143\u683c\u4e4b\u95f4\u7684\u754c\u9762\u4e0a\u7684\u6240\u6709\u9879\u8fdb\u884c\u79ef\u5206\u3002\n\n// - \u5b9a\u4e49\u4e86`boundary_worker`\u51fd\u6570\uff0c\u5bf9\u4f4d\u4e8e\u57df\u7684\u8fb9\u754c\u4e0a\u7684\u5355\u5143\u9762\u505a\u540c\u6837\u7684\u5de5\u4f5c\u3002\n\n// - `copier`\u51fd\u6570\u7684\u5b9a\u4e49\uff0c\u8be5\u51fd\u6570\u8d1f\u8d23\u5c06\u524d\u9762\u4e09\u4e2a\u51fd\u6570\u4e2d\u7684\u6240\u6709\u6570\u636e\u590d\u5236\u5230\u5355\u4e2a\u5355\u5143\u7684\u590d\u5236\u5bf9\u8c61\u4e2d\uff0c\u5e76\u590d\u5236\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u4fa7\u3002\n\n// \u7b2c\u4e94\u90e8\u5206\u662f\u6211\u4eec\u628a\u6240\u6709\u8fd9\u4e9b\u90fd\u96c6\u4e2d\u5728\u4e00\u8d77\u3002\n\n// \u8ba9\u6211\u4eec\u8f6e\u6d41\u6d4f\u89c8\u4e00\u4e0b\u8fd9\u4e9b\u7ec4\u88c5\u6240\u9700\u7684\u6bcf\u4e00\u5757\u3002\n\n  template <int dim> \n  void BiharmonicProblem<dim>::assemble_system() \n  { \n    using Iterator = typename DoFHandler<dim>::active_cell_iterator; \n\n// \u7b2c\u4e00\u90e8\u5206\u662f`cell_worker'\uff0c\u5b83\u5728\u7ec6\u80de\u5185\u90e8\u8fdb\u884c\u7ec4\u88c5\u3002\u5b83\u662f\u4e00\u4e2a\uff08lambda\uff09\u51fd\u6570\uff0c\u4ee5\u4e00\u4e2a\u5355\u5143\u683c\uff08\u8f93\u5165\uff09\u3001\u4e00\u4e2a\u6293\u53d6\u5bf9\u8c61\u548c\u4e00\u4e2a\u590d\u5236\u5bf9\u8c61\uff08\u8f93\u51fa\uff09\u4e3a\u53c2\u6570\u3002\u5b83\u770b\u8d77\u6765\u50cf\u8bb8\u591a\u5176\u4ed6\u6559\u7a0b\u7a0b\u5e8f\u7684\u88c5\u914d\u51fd\u6570\uff0c\u6216\u8005\u81f3\u5c11\u662f\u6240\u6709\u5355\u5143\u683c\u7684\u5faa\u73af\u4e3b\u4f53\u3002\n\n// \u6211\u4eec\u5728\u8fd9\u91cc\u6574\u5408\u7684\u6761\u6b3e\u662f\u5355\u5143\u683c\u5bf9\u5168\u5c40\u77e9\u9635\u7684\u8d21\u732e\n// @f{align*}{\n//     A^K_{ij} = \\int_K \\nabla^2\\varphi_i(x) : \\nabla^2\\varphi_j(x) dx\n//  @f} \uff0c\n//  \u4ee5\u53ca\u5bf9\u53f3\u4fa7\u5411\u91cf\u7684\u8d21\u732e\n//  @f{align*}{\n//     f^K_i = \\int_K \\varphi_i(x) f(x) dx\n//  @f}\n\n// \u6211\u4eec\u4f7f\u7528\u4e0e\u7ec4\u88c5 step-22 \u76f8\u540c\u7684\u6280\u672f\u6765\u52a0\u901f\u8be5\u51fd\u6570\u3002\u6211\u4eec\u4e0d\u5728\u6700\u91cc\u9762\u7684\u5faa\u73af\u4e2d\u8c03\u7528`fe_values.shape_hessian(i, qpoint)`\uff0c\u800c\u662f\u521b\u5efa\u4e00\u4e2a\u53d8\u91cf`hessian_i`\uff0c\u5728\u5faa\u73af\u4e2d\u5bf9`i`\u8fdb\u884c\u4e00\u6b21\u8bc4\u4f30\uff0c\u5728\u5faa\u73af\u4e2d\u5bf9`j`\u91cd\u65b0\u4f7f\u7528\u5982\u6b64\u8bc4\u4f30\u7684\u503c\u3002\u4e3a\u4e86\u5bf9\u79f0\uff0c\u6211\u4eec\u5bf9\u53d8\u91cf`hessian_j`\u4e5f\u505a\u4e86\u540c\u6837\u7684\u5904\u7406\uff0c\u5c3d\u7ba1\u5b83\u786e\u5b9e\u53ea\u7528\u4e86\u4e00\u6b21\uff0c\u800c\u4e14\u6211\u4eec\u53ef\u4ee5\u5728\u8ba1\u7b97\u4e24\u4e2a\u9879\u4e4b\u95f4\u6807\u91cf\u4e58\u79ef\u7684\u6307\u4ee4\u4e2d\u7559\u4e0b\u5bf9`fe_values.shape_hessian(j,qpoint)`\u7684\u8c03\u7528\u3002\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// \u4e0b\u4e00\u4e2a\u6784\u5efa\u6a21\u5757\u662f\u5728\u7f51\u683c\u7684\u6bcf\u4e2a\u5185\u90e8\u9762\u7ec4\u88c5\u60e9\u7f5a\u9879\u3002\u6b63\u5982 MeshWorker::mesh_loop(), \u6587\u6863\u4e2d\u6240\u63cf\u8ff0\u7684\uff0c\u8fd9\u4e2a\u51fd\u6570\u63a5\u6536\u5230\u7684\u53c2\u6570\u8868\u793a\u4e00\u4e2a\u5355\u5143\u548c\u5b83\u7684\u76f8\u90bb\u5355\u5143\uff0c\u4ee5\u53ca\uff08\u5bf9\u4e8e\u8fd9\u4e24\u4e2a\u5355\u5143\u4e2d\u7684\u6bcf\u4e00\u4e2a\uff09\u6211\u4eec\u5fc5\u987b\u6574\u5408\u7684\u9762\uff08\u4ee5\u53ca\u6f5c\u5728\u7684\u5b50\u9762\uff09\u3002\u540c\u6837\u5730\uff0c\u6211\u4eec\u4e5f\u5f97\u5230\u4e86\u4e00\u4e2a\u4ece\u5934\u5f00\u59cb\u7684\u5bf9\u8c61\uff0c\u4ee5\u53ca\u4e00\u4e2a\u7528\u4e8e\u653e\u7f6e\u7ed3\u679c\u7684\u62f7\u8d1d\u5bf9\u8c61\u3002\n\n// \u8fd9\u4e2a\u51fd\u6570\u672c\u8eab\u6709\u4e09\u4e2a\u90e8\u5206\u3002\u5728\u9876\u90e8\uff0c\u6211\u4eec\u521d\u59cb\u5316FEInterfaceValues\u5bf9\u8c61\uff0c\u5e76\u521b\u5efa\u4e00\u4e2a\u65b0\u7684 `CopyData::FaceData` \u5bf9\u8c61\u6765\u5b58\u50a8\u6211\u4eec\u7684\u8f93\u5165\u3002\u8fd9\u5c06\u88ab\u63a8\u5230`copy_data.face_data`\u53d8\u91cf\u7684\u672b\u5c3e\u3002\u6211\u4eec\u9700\u8981\u8fd9\u6837\u505a\uff0c\u56e0\u4e3a\u6211\u4eec\u5bf9\u4e00\u4e2a\u7ed9\u5b9a\u5355\u5143\u8fdb\u884c\u79ef\u5206\u7684\u9762\uff08\u6216\u5b50\u9762\uff09\u7684\u6570\u91cf\u56e0\u5355\u5143\u800c\u5f02\uff0c\u800c\u4e14\u8fd9\u4e9b\u77e9\u9635\u7684\u5927\u5c0f\u4e5f\u4e0d\u540c\uff0c\u53d6\u51b3\u4e8e\u9762\u6216\u5b50\u9762\u76f8\u90bb\u7684\u81ea\u7531\u5ea6\u3002\u6b63\u5982 MeshWorker::mesh_loop(), \u6587\u6863\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u6bcf\u6b21\u8bbf\u95ee\u4e00\u4e2a\u65b0\u7684\u5355\u5143\u65f6\uff0c\u590d\u5236\u5bf9\u8c61\u90fd\u4f1a\u88ab\u91cd\u7f6e\uff0c\u6240\u4ee5\u6211\u4eec\u63a8\u5230`copy_data.face_data()`\u672b\u5c3e\u7684\u5185\u5bb9\u5b9e\u9645\u4e0a\u5c31\u662f\u540e\u6765\u7684`copier`\u51fd\u6570\u5728\u590d\u5236\u6bcf\u4e2a\u5355\u5143\u7684\u8d21\u732e\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u4fa7\u5bf9\u8c61\u65f6\u6240\u80fd\u770b\u5230\u7684\u3002\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// \u7b2c\u4e8c\u90e8\u5206\u6d89\u53ca\u5230\u786e\u5b9a\u60e9\u7f5a\u53c2\u6570\u5e94\u8be5\u662f\u4ec0\u4e48\u3002\u901a\u8fc7\u89c2\u5bdf\u53cc\u7ebf\u6027\u5f62\u5f0f\u4e2d\u5404\u79cd\u9879\u7684\u5355\u4f4d\uff0c\u5f88\u660e\u663e\uff0c\u60e9\u7f5a\u5fc5\u987b\u5177\u6709 $\\frac{\\gamma}{h_K}$ \u7684\u5f62\u5f0f\uff08\u5373\uff0c\u8d85\u8fc7\u957f\u5ea6\u5c3a\u5ea6\u7684\u4e00\u4e2a\uff09\uff0c\u4f46\u5982\u4f55\u9009\u62e9\u65e0\u7ef4\u6570 $\\gamma$ \u5e76\u4e0d\u662f\u5148\u9a8c\u7684\u3002\u4ece\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u7684\u4e0d\u8fde\u7eedGalerkin\u7406\u8bba\u6765\u770b\uff0c\u4eba\u4eec\u53ef\u80fd\u731c\u60f3\u6b63\u786e\u7684\u9009\u62e9\u662f $\\gamma=p(p+1)$ \u662f\u6b63\u786e\u7684\u9009\u62e9\uff0c\u5176\u4e2d $p$ \u662f\u6240\u7528\u6709\u9650\u5143\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u3002\u6211\u4eec\u5c06\u5728\u672c\u7a0b\u5e8f\u7684\u7ed3\u679c\u90e8\u5206\u66f4\u8be6\u7ec6\u5730\u8ba8\u8bba\u8fd9\u4e2a\u9009\u62e9\u3002\n\n// \u5728\u4e0a\u9762\u7684\u516c\u5f0f\u4e2d\uff0c $h_K$  \u662f\u5355\u5143\u683c  $K$  \u7684\u5927\u5c0f\u3002\u4f46\u8fd9\u4e5f\u4e0d\u662f\u5f88\u7b80\u5355\u7684\u4e8b\u60c5\u3002\u5982\u679c\u4f7f\u7528\u9ad8\u5ea6\u62c9\u4f38\u7684\u5355\u5143\u683c\uff0c\u90a3\u4e48\u4e00\u4e2a\u66f4\u590d\u6742\u7684\u7406\u8bba\u8bf4\uff0c $h$ \u5e94\u8be5\u88ab\u5355\u5143\u683c $K$ \u7684\u76f4\u5f84\u53d6\u4ee3\uff0c\u8be5\u76f4\u5f84\u662f\u6709\u5173\u8fb9\u7f18\u65b9\u5411\u7684\u6cd5\u7ebf\u3002 \u4e8b\u5b9e\u8bc1\u660e\uff0c\u5728deal.II\u4e2d\u6709\u4e00\u4e2a\u51fd\u6570\u7528\u4e8e\u6b64\u3002\u5176\u6b21\uff0c\u5f53\u4ece\u4e00\u4e2a\u9762\u7684\u4e24\u4e2a\u4e0d\u540c\u4fa7\u9762\u770b\u65f6\uff0c $h_K$ \u53ef\u80fd\u662f\u4e0d\u540c\u7684\u3002\n\n// \u4e3a\u4e86\u5b89\u5168\u8d77\u89c1\uff0c\u6211\u4eec\u53d6\u8fd9\u4e24\u4e2a\u503c\u7684\u6700\u5927\u503c\u3002\u6211\u4eec\u5c06\u6ce8\u610f\u5230\uff0c\u5982\u679c\u4f7f\u7528\u81ea\u9002\u5e94\u7f51\u683c\u7ec6\u5316\u6240\u4ea7\u751f\u7684\u60ac\u7a7a\u8282\u70b9\uff0c\u6709\u53ef\u80fd\u9700\u8981\u8fdb\u4e00\u6b65\u8c03\u6574\u8fd9\u4e00\u8ba1\u7b97\u65b9\u6cd5\u3002\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// \u6700\u540e\uff0c\u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u6211\u4eec\u5728\u6b63\u4ea4\u70b9\u548c\u6307\u6570`i`\u548c`j`\u4e0a\u5faa\u73af\uff0c\u628a\u8fd9\u4e2a\u9762\u6216\u5b50\u9762\u7684\u8d21\u732e\u52a0\u8d77\u6765\u3002\u7136\u540e\u5c06\u8fd9\u4e9b\u6570\u636e\u5b58\u50a8\u5728\u4e0a\u9762\u521b\u5efa\u7684`copy_data.face_data`\u5bf9\u8c61\u4e2d\u3002\u81f3\u4e8e\u5355\u5143\u683c\u5de5\u4f5c\u8005\uff0c\u5982\u679c\u53ef\u80fd\u7684\u8bdd\uff0c\u6211\u4eec\u5c06\u5e73\u5747\u6570\u548c\u8df3\u8dc3\u7684\u8bc4\u4f30\u4ece\u5faa\u73af\u4e2d\u62c9\u51fa\u6765\uff0c\u5f15\u5165\u5c40\u90e8\u53d8\u91cf\u6765\u5b58\u50a8\u8fd9\u4e9b\u7ed3\u679c\u3002\u7136\u540e\u7ec4\u4ef6\u53ea\u9700\u8981\u5728\u6700\u91cc\u9762\u7684\u5faa\u73af\u4e2d\u4f7f\u7528\u8fd9\u4e9b\u5c40\u90e8\u53d8\u91cf\u3002\u5173\u4e8e\u8fd9\u6bb5\u4ee3\u7801\u5b9e\u73b0\u7684\u5177\u4f53\u516c\u5f0f\uff0c\u56de\u987e\u4e00\u4e0b\uff0c\u53cc\u7ebf\u6027\u5f62\u5f0f\u7684\u63a5\u53e3\u9879\u5982\u4e0b\u3002\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// \u7b2c\u4e09\u5757\u662f\u5bf9\u5904\u4e8e\u8fb9\u754c\u7684\u9762\u505a\u540c\u6837\u7684\u88c5\u914d\u3002\u5f53\u7136\uff0c\u60f3\u6cd5\u548c\u4e0a\u9762\u4e00\u6837\uff0c\u552f\u4e00\u4e0d\u540c\u7684\u662f\uff0c\u73b0\u5728\u6709\u60e9\u7f5a\u6761\u6b3e\u4e5f\u8fdb\u5165\u4e86\u53f3\u624b\u8fb9\u3002\n\n// \u548c\u4ee5\u524d\u4e00\u6837\uff0c\u8fd9\u4e2a\u51fd\u6570\u7684\u7b2c\u4e00\u90e8\u5206\u53ea\u662f\u8bbe\u7f6e\u4e86\u4e00\u4e9b\u8f85\u52a9\u5bf9\u8c61\u3002\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// \u4ece\u6b63\u9762\u770b\uff0c\u7531\u4e8e\u6211\u4eec\u73b0\u5728\u53ea\u5904\u7406\u4e0e\u9762\u76f8\u90bb\u7684\u4e00\u4e2a\u5355\u5143\uff08\u56e0\u4e3a\u6211\u4eec\u5728\u8fb9\u754c\u4e0a\uff09\uff0c\u60e9\u7f5a\u56e0\u5b50 $\\gamma$ \u7684\u8ba1\u7b97\u5927\u5927\u7b80\u5316\u4e86\u3002\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// \u7b2c\u4e09\u5757\u662f\u672f\u8bed\u7684\u7ec4\u5408\u3002\u7531\u4e8e\u8fd9\u4e9b\u6761\u6b3e\u5305\u542b\u4e86\u77e9\u9635\u7684\u6761\u6b3e\u548c\u53f3\u624b\u8fb9\u7684\u6761\u6b3e\uff0c\u6240\u4ee5\u73b0\u5728\u7a0d\u5fae\u6709\u4e9b\u9ebb\u70e6\u3002\u524d\u8005\u4e0e\u4e0a\u9762\u6240\u8bf4\u7684\u5185\u90e8\u9762\u5b8c\u5168\u76f8\u540c\uff0c\u5982\u679c\u6211\u4eec\u53ea\u662f\u9002\u5f53\u5730\u5b9a\u4e49\u4e86\u8df3\u8dc3\u548c\u5e73\u5747\uff08\u8fd9\u5c31\u662fFEInterfaceValues\u7c7b\u6240\u505a\u7684\uff09\u3002\u540e\u8005\u9700\u8981\u6211\u4eec\u8bc4\u4f30\u8fb9\u754c\u6761\u4ef6 $j(\\mathbf x)$ \uff0c\u5728\u5f53\u524d\u60c5\u51b5\u4e0b\uff08\u6211\u4eec\u77e5\u9053\u786e\u5207\u7684\u89e3\u51b3\u65b9\u6848\uff09\uff0c\u6211\u4eec\u4ece $j(\\mathbf x) = \\frac{\\partial u(\\mathbf x)}{\\partial {\\mathbf n}}$ \u4e2d\u8ba1\u7b97\u51fa\u6765\u3002\u7136\u540e\uff0c\u8981\u6dfb\u52a0\u5230\u53f3\u4fa7\u5411\u91cf\u7684\u9879\u662f  $\\frac{\\gamma}{h_e}\\int_e \\jump{\\frac{\\partial v_h}{\\partial \\mathbf n}} j \\ ds$  \u3002\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// \u7b2c\u56db\u90e8\u5206\u662f\u4e00\u4e2a\u5c0f\u51fd\u6570\uff0c\u5b83\u5c06\u4e0a\u9762\u7684\u5355\u5143\u683c\u3001\u5185\u90e8\u548c\u8fb9\u754c\u9762\u88c5\u914d\u7a0b\u5e8f\u4ea7\u751f\u7684\u6570\u636e\u590d\u5236\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u624b\u5411\u91cf\u4e2d\u3002\u8fd9\u91cc\u771f\u7684\u6ca1\u6709\u4ec0\u4e48\u53ef\u505a\u7684\u3002\u6211\u4eec\u5206\u914d\u5355\u5143\u683c\u77e9\u9635\u548c\u53f3\u4fa7\u8d21\u732e\uff0c\u5c31\u50cf\u6211\u4eec\u5728\u5176\u4ed6\u51e0\u4e4e\u6240\u6709\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u7ea6\u675f\u5bf9\u8c61\u90a3\u6837\u3002\u7136\u540e\uff0c\u6211\u4eec\u8fd8\u5fc5\u987b\u5bf9\u9762\u77e9\u9635\u7684\u8d21\u732e\u505a\u540c\u6837\u7684\u5904\u7406\uff0c\u8fd9\u4e9b\u8d21\u732e\u5df2\u7ecf\u83b7\u5f97\u4e86\u9762\uff08\u5185\u90e8\u548c\u8fb9\u754c\uff09\u7684\u5185\u5bb9\uff0c\u5e76\u4e14`\u9762_\u5de5\u4f5c`\u548c`\u8fb9\u754c_\u5de5\u4f5c`\u5df2\u7ecf\u6dfb\u52a0\u5230`copy_data.face_data`\u9635\u5217\u4e2d\u3002\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// \u5728\u8bbe\u7f6e\u4e86\u6240\u6709\u8fd9\u4e9b\u4e4b\u540e\uff0c\u5269\u4e0b\u7684\u5c31\u662f\u521b\u5efa\u4e00\u4e2a\u4ece\u5934\u5f00\u59cb\u548c\u590d\u5236\u6570\u636e\u7684\u5bf9\u8c61\uff0c\u5e76\u8c03\u7528 MeshWorker::mesh_loop() \u51fd\u6570\uff0c\u7136\u540e\u904d\u5386\u6240\u6709\u7684\u5355\u5143\u683c\u548c\u9762\uff0c\u8c03\u7528\u5b83\u4eec\u5404\u81ea\u7684\u5de5\u4f5c\u5668\uff0c\u7136\u540e\u662f\u590d\u5236\u5668\u51fd\u6570\uff0c\u5c06\u4e1c\u897f\u653e\u5165\u5168\u5c40\u77e9\u9635\u548c\u53f3\u4fa7\u3002\u4f5c\u4e3a\u4e00\u4e2a\u989d\u5916\u7684\u597d\u5904\uff0c MeshWorker::mesh_loop() \u4ee5\u5e76\u884c\u65b9\u5f0f\u5b8c\u6210\u6240\u6709\u8fd9\u4e9b\u5de5\u4f5c\uff0c\u4f7f\u7528\u4f60\u7684\u673a\u5668\u6070\u597d\u6709\u591a\u5c11\u4e2a\u5904\u7406\u5668\u6838\u5fc3\u3002\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// \u5230\u6b64\u4e3a\u6b62\uff0c\u8282\u76ee\u57fa\u672c\u4e0a\u7ed3\u675f\u4e86\u3002\u5176\u4f59\u7684\u51fd\u6570\u5e76\u4e0d\u592a\u6709\u8da3\u6216\u65b0\u9896\u3002\u7b2c\u4e00\u4e2a\u51fd\u6570\u53ea\u662f\u7528\u4e00\u4e2a\u76f4\u63a5\u6c42\u89e3\u5668\u6765\u6c42\u89e3\u7ebf\u6027\u7cfb\u7edf\uff08\u4e5f\u89c1 step-29  \uff09\u3002\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// \u4e0b\u4e00\u4e2a\u51fd\u6570\u8bc4\u4f30\u4e86\u8ba1\u7b97\u51fa\u7684\u89e3\u548c\u7cbe\u786e\u89e3\u4e4b\u95f4\u7684\u8bef\u5dee\uff08\u5728\u8fd9\u91cc\u662f\u5df2\u77e5\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u9009\u62e9\u4e86\u53f3\u624b\u8fb9\u548c\u8fb9\u754c\u503c\u7684\u65b9\u5f0f\uff0c\u6240\u4ee5\u6211\u4eec\u77e5\u9053\u76f8\u5e94\u7684\u89e3\uff09\u3002\u5728\u4e0b\u9762\u7684\u524d\u4e24\u4e2a\u4ee3\u7801\u5757\u4e2d\uff0c\u6211\u4eec\u8ba1\u7b97\u4e86 $L_2$ \u51c6\u5219\u548c $H^1$ \u534a\u51c6\u5219\u4e0b\u7684\u8bef\u5dee\u3002\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// \u73b0\u5728\u4e5f\u8ba1\u7b97\u4e00\u4e0b $H^2$ \u534a\u6b63\u6001\u8bef\u5dee\u7684\u8fd1\u4f3c\u503c\u3002\u5b9e\u9645\u7684 $H^2$ \u534a\u89c4\u8303\u8981\u6c42\u6211\u4eec\u5bf9\u89e3\u51b3\u65b9\u6848 $u_h$ \u7684\u4e8c\u9636\u5bfc\u6570\u8fdb\u884c\u79ef\u5206\uff0c\u4f46\u662f\u8003\u8651\u5230\u6211\u4eec\u4f7f\u7528\u7684\u62c9\u683c\u6717\u65e5\u5f62\u72b6\u51fd\u6570\uff0c $u_h$ \u5f53\u7136\u5728\u5355\u5143\u95f4\u7684\u754c\u9762\u4e0a\u6709\u7ed3\u70b9\uff0c\u56e0\u6b64\u4e8c\u9636\u5bfc\u6570\u5728\u754c\u9762\u662f\u5947\u5f02\u7684\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5b9e\u9645\u4e0a\u53ea\u5bf9\u5355\u5143\u7684\u5185\u90e8\u8fdb\u884c\u79ef\u5206\uff0c\u800c\u5ffd\u7565\u4e86\u754c\u9762\u7684\u8d21\u732e\u3002\u8fd9\u4e0d\u662f*\u7b49\u540c\u4e8e\u95ee\u9898\u7684\u80fd\u91cf\u51c6\u5219\uff0c\u4f46\u662f\u4ecd\u7136\u53ef\u4ee5\u8ba9\u6211\u4eec\u4e86\u89e3\u8bef\u5dee\u6536\u655b\u7684\u901f\u5ea6\u3002\n\n// \u6211\u4eec\u6ce8\u610f\u5230\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u5b9a\u4e49\u4e00\u4e2a\u7b49\u540c\u4e8e\u80fd\u91cf\u51c6\u5219\u7684\u51c6\u5219\u6765\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u3002\u8fd9\u5c06\u6d89\u53ca\u5230\u4e0d\u4ec5\u8981\u50cf\u6211\u4eec\u4e0b\u9762\u505a\u7684\u90a3\u6837\u5c06\u7ec6\u80de\u5185\u90e8\u7684\u79ef\u5206\u76f8\u52a0\uff0c\u800c\u4e14\u8fd8\u8981\u4e3a $u_h$ \u7684\u5bfc\u6570\u5728\u754c\u9762\u4e0a\u7684\u8df3\u8dc3\u6dfb\u52a0\u60e9\u7f5a\u9879\uff0c\u5e76\u5bf9\u8fd9\u4e24\u79cd\u9879\u8fdb\u884c\u9002\u5f53\u7684\u7f29\u653e\u3002\u6211\u4eec\u5c06\u628a\u8fd9\u4e2a\u95ee\u9898\u7559\u7ed9\u4ee5\u540e\u7684\u5de5\u4f5c\u3002\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// \u540c\u6837\u65e0\u8da3\u7684\u662f\u751f\u6210\u56fe\u5f62\u8f93\u51fa\u7684\u51fd\u6570\u3002\u5b83\u770b\u8d77\u6765\u548c  step-6  \u4e2d\u7684\u4e00\u6a21\u4e00\u6837\uff0c\u6bd4\u5982\u8bf4\u3002\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()`\u51fd\u6570\u7684\u60c5\u51b5\u4e5f\u662f\u5982\u6b64\u3002\u5c31\u50cf\u5728\u4ee5\u524d\u7684\u7a0b\u5e8f\u4e2d\u4e00\u6837\u3002\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// \u6700\u540e\u662f \"main() \"\u51fd\u6570\u3002\u540c\u6837\uff0c\u8fd9\u91cc\u6ca1\u6709\u4ec0\u4e48\u53ef\u770b\u7684\u3002\u5b83\u770b\u8d77\u6765\u548c\u4ee5\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u7684\u4e00\u6837\u3002\u6709\u4e00\u4e2a\u53d8\u91cf\uff0c\u53ef\u4ee5\u9009\u62e9\u6211\u4eec\u8981\u7528\u6765\u89e3\u65b9\u7a0b\u7684\u5143\u7d20\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u3002\u56e0\u4e3a\u6211\u4eec\u4f7f\u7528\u7684C0IP\u516c\u5f0f\u8981\u6c42\u5143\u7d20\u7684\u5ea6\u6570\u81f3\u5c11\u4e3a2\uff0c\u6240\u4ee5\u6211\u4eec\u7528\u4e00\u4e2a\u65ad\u8a00\u6765\u68c0\u67e5\uff0c\u65e0\u8bba\u4e3a\u591a\u9879\u5f0f\u5ea6\u6570\u8bbe\u7f6e\u4ec0\u4e48\u90fd\u662f\u6709\u610f\u4e49\u7684\u3002\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": "#ifndef H_MPC_DESIRED_TRAJECTORY_MANAGER\n#define H_MPC_DESIRED_TRAJECTORY_MANAGER\n\n\n#include <Utils/Math/cubicfit_one_dim.hpp>\n#include <Utils/Math/linearfit_one_dim.hpp>\n#include <Eigen/Dense>\n#include <vector>\n#include <cmath>\n\n// A container that holds the state trajectory within the time horizon bounded by time_start and time_end\n\n#define STATE_TRAJECTORY_WITHIN_HORIZON_POSITION 0\n#define STATE_TRAJECTORY_WITHIN_HORIZON_VELOCITY 1\n#define STATE_TRAJECTORY_WITHIN_HORIZON_ACCELERATION 2\n\n#define STATE_TRAJECTORY_WITHIN_HORIZON_CUBIC_FIT 2\n#define STATE_TRAJECTORY_WITHIN_HORIZON_LINEAR_FIT 0\n\n\nclass StateTrajectoryWithinHorizon{\npublic:\n    // for a given state [x, xdot], the size of dimension_in is equal to the dimension of x.\n    StateTrajectoryWithinHorizon(const int dimension_in);\n    ~StateTrajectoryWithinHorizon();\n\n    // init_boundary is the state [x, xdot] at the start time\n    // end_boundary is the state [x, xdot] at the end boundary\n    void setParams(const Eigen::VectorXd init_boundary, \n                   const Eigen::VectorXd end_boundary,\n                   const double time_start, double const time_end);\n\n    Eigen::VectorXd getVal(const int index, const double time,\n                           int fit_type = STATE_TRAJECTORY_WITHIN_HORIZON_CUBIC_FIT);    \n\n    Eigen::VectorXd getPos(const double time, const int fit_type = STATE_TRAJECTORY_WITHIN_HORIZON_CUBIC_FIT);\n    Eigen::VectorXd getVel(const double time, const int fit_type = STATE_TRAJECTORY_WITHIN_HORIZON_CUBIC_FIT);\n    Eigen::VectorXd getAcc(const double time, const int fit_type = STATE_TRAJECTORY_WITHIN_HORIZON_CUBIC_FIT);\n\nprivate:\n    int dimension;\n    // A vector of a polynomial cubic fit for the state within the horizon \n    std::vector<CubicFit_OneDimension> x_cubic;\n    // A vector of a linear fit for the state within the horizon \n    std::vector<LinearFit_OneDimension> x_linear;\n};\n\nclass InputTrajectoryWithinHorizon{\npublic:\n    // for a given state [x, xdot], the size of dimension_in is equal to the dimension of x.\n    InputTrajectoryWithinHorizon(const int dimension_in);\n    ~InputTrajectoryWithinHorizon();\n\n    // init_boundary is the input u at the start time\n    // end_boundary is the input u at the end boundary\n    void setParams(const Eigen::VectorXd init_boundary, \n                   const Eigen::VectorXd end_boundary,\n                   const double time_start, double const time_end);\n\n    Eigen::VectorXd getVal(const double time);\n\n\nprivate:\n    int dimension;\n    // A vector of a linear fit for the input within the horizon \n    std::vector<LinearFit_OneDimension> u_linear;\n};\n\n\nclass MPCDesiredTrajectoryManager{\npublic: \n    MPCDesiredTrajectoryManager(const int state_size_in, const int horizon_in, const double dt_in);\n    MPCDesiredTrajectoryManager(const int input_size_in, const int state_size_in, const int horizon_in, const double dt_in);\n    ~MPCDesiredTrajectoryManager();\n\n    // Accepts a concatenated state vector which lists the knot points of the state over the horizon\n    // Assumes that the state has the form X = [x, \\dot{x}]\n    // For CMPC, the state has the form X = [x, \\dot{x}, g] where g is the gravitational constant. \n    //    this class automatically handles the CMPC case due to the implementation.\n\n    // Therefore, X_pred = [X_1, X_2, ..., X_horizon].\n\n    // Warning. It's important that X_pred has the right dimension\n    // double t_start_in, starting time of the reference trajectory\n\n    // Eigen::VectorXd X_start = [x_start, \\dot{x}_start]; // starting state of the system\n    void setStateKnotPoints(const double t_start_in,\n                            const Eigen::VectorXd & X_start,\n                            const Eigen::VectorXd & X_pred); \n\n    // U_sequence = [U_0, U_1, ... U_{horizon-1}]\n    // set the input knot points with U_0 the input that should be taken now.\n    void setInputKnotPoints(const double t_start_in,\n                            const Eigen::VectorXd & U_sequence); \n\n\n    // Simultaenously sets input and state knotpoints\n    void setStateAndInputKnotPoints(const double t_start_in,\n                                    const Eigen::VectorXd & X_start,\n                                    const Eigen::VectorXd & X_pred,\n                                    const Eigen::VectorXd & U_sequence); \n\n\n    // int horizon: number of time steps\n    void setHorizon(const int horizon_in);\n    // double dt: time interval between knot points. Usually equal to the MPC dt\n    void setDt(const double dt_in);\n\n    // outputs the state value at the specified time\n    // x_out = [x_cubic(t), \\dot{x}_cubic(t)]\n    \n    // time_in is clamped between (t_start and t_start + horizon*dt_internal)\n    void getState(const double time_in, Eigen::VectorXd & x_out); \n\n    // time_in is clamped between (t_start and t_start + horizon*dt_internal)\n    void getInput(const double time_in, Eigen::VectorXd & u_out); \n\n    // Returns the input state vector\n    Eigen::VectorXd getXStartVector();\n    // Returns the input state knot points\n    Eigen::VectorXd getXpredVector();\n    // Returns the global start time of the trajectories\n    double getStartTime();\n\n    // Returns the input sequence\n    Eigen::VectorXd getUSequence();\n\n    // Returns the knot points that are after this time.\n    Eigen::VectorXd getTruncatedXpredVector(const double time);\n\n    // Returns a vector of knotpoints, equal to the horizon, spaced by dt_internal excluding the input time\n    Eigen::VectorXd getInterpolatedXpredVector(const double time);\n\n    // helper function which gives the index to use for the piecewise cubic function\n    int getHorizonIndex(const double time);\n\n    Eigen::VectorXd getPos(const double time);\n    Eigen::VectorXd getVel(const double time);\n    Eigen::VectorXd getAcc(const double time);\n\n    void setLinearInterpolate(bool val);\n    void setCubicInterpolate(bool val);\n    void setLinearInterpolateFirstStatetoNext(bool val);\n\nprivate:\n    double t_start; // global start time of the trajectories\n    double dt_internal;\n\n    int input_size;\n    int state_size;\n    int dim;\n    int horizon;\n\n    // option:\n    bool linear_interpolate_states;\n\n    // store initial start value\n    Eigen::VectorXd X_start_internal; \n    // vector containing the knot points\n    Eigen::VectorXd X_pred_internal; \n\n    // vector containing all the polynomial fits from t_start to t_start + horizon*dt\n    std::vector< StateTrajectoryWithinHorizon > x_trajectory;\n\n    // vector containing the input knot points\n    Eigen::VectorXd U_sequence_internal; \n    std::vector< InputTrajectoryWithinHorizon > u_trajectory;\n\n\n};\n\nnamespace mpc_trajectory_manager_test{\n    // Function which tests this object\n    void test_object();\n}\n\n#endif", "meta": {"hexsha": "a049a07c119af5613b6f0b55f5d9c45ac29e6096", "size": 6720, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PnC/MPC/MPCDesiredTrajectoryManager.hpp", "max_stars_repo_name": "stevenjj/PnC", "max_stars_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T22:36:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T22:36:54.000Z", "max_issues_repo_path": "PnC/MPC/MPCDesiredTrajectoryManager.hpp", "max_issues_repo_name": "stevenjj/PnC", "max_issues_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PnC/MPC/MPCDesiredTrajectoryManager.hpp", "max_forks_repo_name": "stevenjj/PnC", "max_forks_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9661016949, "max_line_length": 124, "alphanum_fraction": 0.7151785714, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5891707635758892}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra. Eigen itself is part of the KDE project.\r\n//\r\n// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>\r\n//\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#define EIGEN2_SUPPORT_STAGE15_RESOLVE_API_CONFLICTS_WARN\r\n\r\n#include \"main.h\"\r\n#include <Eigen/Geometry>\r\n#include <Eigen/LU>\r\n#include <Eigen/SVD>\r\n\r\ntemplate<typename Scalar> void geometry(void)\r\n{\r\n  /* this test covers the following files:\r\n     Cross.h Quaternion.h, Transform.cpp\r\n  */\r\n\r\n  typedef Matrix<Scalar,2,2> Matrix2;\r\n  typedef Matrix<Scalar,3,3> Matrix3;\r\n  typedef Matrix<Scalar,4,4> Matrix4;\r\n  typedef Matrix<Scalar,2,1> Vector2;\r\n  typedef Matrix<Scalar,3,1> Vector3;\r\n  typedef Matrix<Scalar,4,1> Vector4;\r\n  typedef eigen2_Quaternion<Scalar> Quaternionx;\r\n  typedef eigen2_AngleAxis<Scalar> AngleAxisx;\r\n  typedef eigen2_Transform<Scalar,2> Transform2;\r\n  typedef eigen2_Transform<Scalar,3> Transform3;\r\n  typedef eigen2_Scaling<Scalar,2> Scaling2;\r\n  typedef eigen2_Scaling<Scalar,3> Scaling3;\r\n  typedef eigen2_Translation<Scalar,2> Translation2;\r\n  typedef eigen2_Translation<Scalar,3> Translation3;\r\n\r\n  Scalar largeEps = test_precision<Scalar>();\r\n  if (ei_is_same_type<Scalar,float>::ret)\r\n    largeEps = 1e-2f;\r\n\r\n  Vector3 v0 = Vector3::Random(),\r\n    v1 = Vector3::Random(),\r\n    v2 = Vector3::Random();\r\n  Vector2 u0 = Vector2::Random();\r\n  Matrix3 matrot1;\r\n\r\n  Scalar a = ei_random<Scalar>(-Scalar(M_PI), Scalar(M_PI));\r\n\r\n  // cross product\r\n  VERIFY_IS_MUCH_SMALLER_THAN(v1.cross(v2).eigen2_dot(v1), Scalar(1));\r\n  Matrix3 m;\r\n  m << v0.normalized(),\r\n      (v0.cross(v1)).normalized(),\r\n      (v0.cross(v1).cross(v0)).normalized();\r\n  VERIFY(m.isUnitary());\r\n\r\n  // Quaternion: Identity(), setIdentity();\r\n  Quaternionx q1, q2;\r\n  q2.setIdentity();\r\n  VERIFY_IS_APPROX(Quaternionx(Quaternionx::Identity()).coeffs(), q2.coeffs());\r\n  q1.coeffs().setRandom();\r\n  VERIFY_IS_APPROX(q1.coeffs(), (q1*q2).coeffs());\r\n\r\n  // unitOrthogonal\r\n  VERIFY_IS_MUCH_SMALLER_THAN(u0.unitOrthogonal().eigen2_dot(u0), Scalar(1));\r\n  VERIFY_IS_MUCH_SMALLER_THAN(v0.unitOrthogonal().eigen2_dot(v0), Scalar(1));\r\n  VERIFY_IS_APPROX(u0.unitOrthogonal().norm(), Scalar(1));\r\n  VERIFY_IS_APPROX(v0.unitOrthogonal().norm(), Scalar(1));\r\n\r\n\r\n  VERIFY_IS_APPROX(v0, AngleAxisx(a, v0.normalized()) * v0);\r\n  VERIFY_IS_APPROX(-v0, AngleAxisx(Scalar(M_PI), v0.unitOrthogonal()) * v0);\r\n  VERIFY_IS_APPROX(ei_cos(a)*v0.squaredNorm(), v0.eigen2_dot(AngleAxisx(a, v0.unitOrthogonal()) * v0));\r\n  m = AngleAxisx(a, v0.normalized()).toRotationMatrix().adjoint();\r\n  VERIFY_IS_APPROX(Matrix3::Identity(), m * AngleAxisx(a, v0.normalized()));\r\n  VERIFY_IS_APPROX(Matrix3::Identity(), AngleAxisx(a, v0.normalized()) * m);\r\n\r\n  q1 = AngleAxisx(a, v0.normalized());\r\n  q2 = AngleAxisx(a, v1.normalized());\r\n\r\n  // angular distance\r\n  Scalar refangle = ei_abs(AngleAxisx(q1.inverse()*q2).angle());\r\n  if (refangle>Scalar(M_PI))\r\n    refangle = Scalar(2)*Scalar(M_PI) - refangle;\r\n  \r\n  if((q1.coeffs()-q2.coeffs()).norm() > 10*largeEps)\r\n  {\r\n    VERIFY(ei_isApprox(q1.angularDistance(q2), refangle, largeEps));\r\n  }\r\n\r\n  // rotation matrix conversion\r\n  VERIFY_IS_APPROX(q1 * v2, q1.toRotationMatrix() * v2);\r\n  VERIFY_IS_APPROX(q1 * q2 * v2,\r\n    q1.toRotationMatrix() * q2.toRotationMatrix() * v2);\r\n\r\n  VERIFY( (q2*q1).isApprox(q1*q2, largeEps) || !(q2 * q1 * v2).isApprox(\r\n    q1.toRotationMatrix() * q2.toRotationMatrix() * v2));\r\n\r\n  q2 = q1.toRotationMatrix();\r\n  VERIFY_IS_APPROX(q1*v1,q2*v1);\r\n\r\n  matrot1 = AngleAxisx(Scalar(0.1), Vector3::UnitX())\r\n          * AngleAxisx(Scalar(0.2), Vector3::UnitY())\r\n          * AngleAxisx(Scalar(0.3), Vector3::UnitZ());\r\n  VERIFY_IS_APPROX(matrot1 * v1,\r\n       AngleAxisx(Scalar(0.1), Vector3(1,0,0)).toRotationMatrix()\r\n    * (AngleAxisx(Scalar(0.2), Vector3(0,1,0)).toRotationMatrix()\r\n    * (AngleAxisx(Scalar(0.3), Vector3(0,0,1)).toRotationMatrix() * v1)));\r\n\r\n  // angle-axis conversion\r\n  AngleAxisx aa = q1;\r\n  VERIFY_IS_APPROX(q1 * v1, Quaternionx(aa) * v1);\r\n  VERIFY_IS_NOT_APPROX(q1 * v1, Quaternionx(AngleAxisx(aa.angle()*2,aa.axis())) * v1);\r\n\r\n  // from two vector creation\r\n  VERIFY_IS_APPROX(v2.normalized(),(q2.setFromTwoVectors(v1,v2)*v1).normalized());\r\n  VERIFY_IS_APPROX(v2.normalized(),(q2.setFromTwoVectors(v1,v2)*v1).normalized());\r\n\r\n  // inverse and conjugate\r\n  VERIFY_IS_APPROX(q1 * (q1.inverse() * v1), v1);\r\n  VERIFY_IS_APPROX(q1 * (q1.conjugate() * v1), v1);\r\n\r\n  // AngleAxis\r\n  VERIFY_IS_APPROX(AngleAxisx(a,v1.normalized()).toRotationMatrix(),\r\n    Quaternionx(AngleAxisx(a,v1.normalized())).toRotationMatrix());\r\n\r\n  AngleAxisx aa1;\r\n  m = q1.toRotationMatrix();\r\n  aa1 = m;\r\n  VERIFY_IS_APPROX(AngleAxisx(m).toRotationMatrix(),\r\n    Quaternionx(m).toRotationMatrix());\r\n\r\n  // Transform\r\n  // TODO complete the tests !\r\n  a = 0;\r\n  while (ei_abs(a)<Scalar(0.1))\r\n    a = ei_random<Scalar>(-Scalar(0.4)*Scalar(M_PI), Scalar(0.4)*Scalar(M_PI));\r\n  q1 = AngleAxisx(a, v0.normalized());\r\n  Transform3 t0, t1, t2;\r\n  // first test setIdentity() and Identity()\r\n  t0.setIdentity();\r\n  VERIFY_IS_APPROX(t0.matrix(), Transform3::MatrixType::Identity());\r\n  t0.matrix().setZero();\r\n  t0 = Transform3::Identity();\r\n  VERIFY_IS_APPROX(t0.matrix(), Transform3::MatrixType::Identity());\r\n\r\n  t0.linear() = q1.toRotationMatrix();\r\n  t1.setIdentity();\r\n  t1.linear() = q1.toRotationMatrix();\r\n\r\n  v0 << 50, 2, 1;//= ei_random_matrix<Vector3>().cwiseProduct(Vector3(10,2,0.5));\r\n  t0.scale(v0);\r\n  t1.prescale(v0);\r\n\r\n  VERIFY_IS_APPROX( (t0 * Vector3(1,0,0)).norm(), v0.x());\r\n  //VERIFY(!ei_isApprox((t1 * Vector3(1,0,0)).norm(), v0.x()));\r\n\r\n  t0.setIdentity();\r\n  t1.setIdentity();\r\n  v1 << 1, 2, 3;\r\n  t0.linear() = q1.toRotationMatrix();\r\n  t0.pretranslate(v0);\r\n  t0.scale(v1);\r\n  t1.linear() = q1.conjugate().toRotationMatrix();\r\n  t1.prescale(v1.cwise().inverse());\r\n  t1.translate(-v0);\r\n\r\n  VERIFY((t0.matrix() * t1.matrix()).isIdentity(test_precision<Scalar>()));\r\n\r\n  t1.fromPositionOrientationScale(v0, q1, v1);\r\n  VERIFY_IS_APPROX(t1.matrix(), t0.matrix());\r\n  VERIFY_IS_APPROX(t1*v1, t0*v1);\r\n\r\n  t0.setIdentity(); t0.scale(v0).rotate(q1.toRotationMatrix());\r\n  t1.setIdentity(); t1.scale(v0).rotate(q1);\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n\r\n  t0.setIdentity(); t0.scale(v0).rotate(AngleAxisx(q1));\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n\r\n  VERIFY_IS_APPROX(t0.scale(a).matrix(), t1.scale(Vector3::Constant(a)).matrix());\r\n  VERIFY_IS_APPROX(t0.prescale(a).matrix(), t1.prescale(Vector3::Constant(a)).matrix());\r\n\r\n  // More transform constructors, operator=, operator*=\r\n\r\n  Matrix3 mat3 = Matrix3::Random();\r\n  Matrix4 mat4;\r\n  mat4 << mat3 , Vector3::Zero() , Vector4::Zero().transpose();\r\n  Transform3 tmat3(mat3), tmat4(mat4);\r\n  tmat4.matrix()(3,3) = Scalar(1);\r\n  VERIFY_IS_APPROX(tmat3.matrix(), tmat4.matrix());\r\n\r\n  Scalar a3 = ei_random<Scalar>(-Scalar(M_PI), Scalar(M_PI));\r\n  Vector3 v3 = Vector3::Random().normalized();\r\n  AngleAxisx aa3(a3, v3);\r\n  Transform3 t3(aa3);\r\n  Transform3 t4;\r\n  t4 = aa3;\r\n  VERIFY_IS_APPROX(t3.matrix(), t4.matrix());\r\n  t4.rotate(AngleAxisx(-a3,v3));\r\n  VERIFY_IS_APPROX(t4.matrix(), Matrix4::Identity());\r\n  t4 *= aa3;\r\n  VERIFY_IS_APPROX(t3.matrix(), t4.matrix());\r\n\r\n  v3 = Vector3::Random();\r\n  Translation3 tv3(v3);\r\n  Transform3 t5(tv3);\r\n  t4 = tv3;\r\n  VERIFY_IS_APPROX(t5.matrix(), t4.matrix());\r\n  t4.translate(-v3);\r\n  VERIFY_IS_APPROX(t4.matrix(), Matrix4::Identity());\r\n  t4 *= tv3;\r\n  VERIFY_IS_APPROX(t5.matrix(), t4.matrix());\r\n\r\n  Scaling3 sv3(v3);\r\n  Transform3 t6(sv3);\r\n  t4 = sv3;\r\n  VERIFY_IS_APPROX(t6.matrix(), t4.matrix());\r\n  t4.scale(v3.cwise().inverse());\r\n  VERIFY_IS_APPROX(t4.matrix(), Matrix4::Identity());\r\n  t4 *= sv3;\r\n  VERIFY_IS_APPROX(t6.matrix(), t4.matrix());\r\n\r\n  // matrix * transform\r\n  VERIFY_IS_APPROX(Transform3(t3.matrix()*t4).matrix(), Transform3(t3*t4).matrix());\r\n\r\n  // chained Transform product\r\n  VERIFY_IS_APPROX(((t3*t4)*t5).matrix(), (t3*(t4*t5)).matrix());\r\n\r\n  // check that Transform product doesn't have aliasing problems\r\n  t5 = t4;\r\n  t5 = t5*t5;\r\n  VERIFY_IS_APPROX(t5, t4*t4);\r\n\r\n  // 2D transformation\r\n  Transform2 t20, t21;\r\n  Vector2 v20 = Vector2::Random();\r\n  Vector2 v21 = Vector2::Random();\r\n  for (int k=0; k<2; ++k)\r\n    if (ei_abs(v21[k])<Scalar(1e-3)) v21[k] = Scalar(1e-3);\r\n  t21.setIdentity();\r\n  t21.linear() = Rotation2D<Scalar>(a).toRotationMatrix();\r\n  VERIFY_IS_APPROX(t20.fromPositionOrientationScale(v20,a,v21).matrix(),\r\n    t21.pretranslate(v20).scale(v21).matrix());\r\n\r\n  t21.setIdentity();\r\n  t21.linear() = Rotation2D<Scalar>(-a).toRotationMatrix();\r\n  VERIFY( (t20.fromPositionOrientationScale(v20,a,v21)\r\n        * (t21.prescale(v21.cwise().inverse()).translate(-v20))).matrix().isIdentity(test_precision<Scalar>()) );\r\n\r\n  // Transform - new API\r\n  // 3D\r\n  t0.setIdentity();\r\n  t0.rotate(q1).scale(v0).translate(v0);\r\n  // mat * scaling and mat * translation\r\n  t1 = (Matrix3(q1) * Scaling3(v0)) * Translation3(v0);\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n  // mat * transformation and scaling * translation\r\n  t1 = Matrix3(q1) * (Scaling3(v0) * Translation3(v0));\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n\r\n  t0.setIdentity();\r\n  t0.prerotate(q1).prescale(v0).pretranslate(v0);\r\n  // translation * scaling and transformation * mat\r\n  t1 = (Translation3(v0) * Scaling3(v0)) * Matrix3(q1);\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n  // scaling * mat and translation * mat\r\n  t1 = Translation3(v0) * (Scaling3(v0) * Matrix3(q1));\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n\r\n  t0.setIdentity();\r\n  t0.scale(v0).translate(v0).rotate(q1);\r\n  // translation * mat and scaling * transformation\r\n  t1 = Scaling3(v0) * (Translation3(v0) * Matrix3(q1));\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n  // transformation * scaling\r\n  t0.scale(v0);\r\n  t1 = t1 * Scaling3(v0);\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n  // transformation * translation\r\n  t0.translate(v0);\r\n  t1 = t1 * Translation3(v0);\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n  // translation * transformation\r\n  t0.pretranslate(v0);\r\n  t1 = Translation3(v0) * t1;\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n\r\n  // transform * quaternion\r\n  t0.rotate(q1);\r\n  t1 = t1 * q1;\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n\r\n  // translation * quaternion\r\n  t0.translate(v1).rotate(q1);\r\n  t1 = t1 * (Translation3(v1) * q1);\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n\r\n  // scaling * quaternion\r\n  t0.scale(v1).rotate(q1);\r\n  t1 = t1 * (Scaling3(v1) * q1);\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n\r\n  // quaternion * transform\r\n  t0.prerotate(q1);\r\n  t1 = q1 * t1;\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n\r\n  // quaternion * translation\r\n  t0.rotate(q1).translate(v1);\r\n  t1 = t1 * (q1 * Translation3(v1));\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n\r\n  // quaternion * scaling\r\n  t0.rotate(q1).scale(v1);\r\n  t1 = t1 * (q1 * Scaling3(v1));\r\n  VERIFY_IS_APPROX(t0.matrix(), t1.matrix());\r\n\r\n  // translation * vector\r\n  t0.setIdentity();\r\n  t0.translate(v0);\r\n  VERIFY_IS_APPROX(t0 * v1, Translation3(v0) * v1);\r\n\r\n  // scaling * vector\r\n  t0.setIdentity();\r\n  t0.scale(v0);\r\n  VERIFY_IS_APPROX(t0 * v1, Scaling3(v0) * v1);\r\n\r\n  // test transform inversion\r\n  t0.setIdentity();\r\n  t0.translate(v0);\r\n  t0.linear().setRandom();\r\n  VERIFY_IS_APPROX(t0.inverse(Affine), t0.matrix().inverse());\r\n  t0.setIdentity();\r\n  t0.translate(v0).rotate(q1);\r\n  VERIFY_IS_APPROX(t0.inverse(Isometry), t0.matrix().inverse());\r\n\r\n  // test extract rotation and scaling\r\n  t0.setIdentity();\r\n  t0.translate(v0).rotate(q1).scale(v1);\r\n  VERIFY_IS_APPROX(t0.rotation() * v1, Matrix3(q1) * v1);\r\n\r\n  Matrix3 mat_rotation, mat_scaling;\r\n  t0.setIdentity();\r\n  t0.translate(v0).rotate(q1).scale(v1);\r\n  t0.computeRotationScaling(&mat_rotation, &mat_scaling);\r\n  VERIFY_IS_APPROX(t0.linear(), mat_rotation * mat_scaling);\r\n  VERIFY_IS_APPROX(mat_rotation*mat_rotation.adjoint(), Matrix3::Identity());\r\n  VERIFY_IS_APPROX(mat_rotation.determinant(), Scalar(1));\r\n  t0.computeScalingRotation(&mat_scaling, &mat_rotation);\r\n  VERIFY_IS_APPROX(t0.linear(), mat_scaling * mat_rotation);\r\n  VERIFY_IS_APPROX(mat_rotation*mat_rotation.adjoint(), Matrix3::Identity());\r\n  VERIFY_IS_APPROX(mat_rotation.determinant(), Scalar(1));\r\n\r\n  // test casting\r\n  eigen2_Transform<float,3> t1f = t1.template cast<float>();\r\n  VERIFY_IS_APPROX(t1f.template cast<Scalar>(),t1);\r\n  eigen2_Transform<double,3> t1d = t1.template cast<double>();\r\n  VERIFY_IS_APPROX(t1d.template cast<Scalar>(),t1);\r\n\r\n  Translation3 tr1(v0);\r\n  eigen2_Translation<float,3> tr1f = tr1.template cast<float>();\r\n  VERIFY_IS_APPROX(tr1f.template cast<Scalar>(),tr1);\r\n  eigen2_Translation<double,3> tr1d = tr1.template cast<double>();\r\n  VERIFY_IS_APPROX(tr1d.template cast<Scalar>(),tr1);\r\n\r\n  Scaling3 sc1(v0);\r\n  eigen2_Scaling<float,3> sc1f = sc1.template cast<float>();\r\n  VERIFY_IS_APPROX(sc1f.template cast<Scalar>(),sc1);\r\n  eigen2_Scaling<double,3> sc1d = sc1.template cast<double>();\r\n  VERIFY_IS_APPROX(sc1d.template cast<Scalar>(),sc1);\r\n\r\n  eigen2_Quaternion<float> q1f = q1.template cast<float>();\r\n  VERIFY_IS_APPROX(q1f.template cast<Scalar>(),q1);\r\n  eigen2_Quaternion<double> q1d = q1.template cast<double>();\r\n  VERIFY_IS_APPROX(q1d.template cast<Scalar>(),q1);\r\n\r\n  eigen2_AngleAxis<float> aa1f = aa1.template cast<float>();\r\n  VERIFY_IS_APPROX(aa1f.template cast<Scalar>(),aa1);\r\n  eigen2_AngleAxis<double> aa1d = aa1.template cast<double>();\r\n  VERIFY_IS_APPROX(aa1d.template cast<Scalar>(),aa1);\r\n\r\n  eigen2_Rotation2D<Scalar> r2d1(ei_random<Scalar>());\r\n  eigen2_Rotation2D<float> r2d1f = r2d1.template cast<float>();\r\n  VERIFY_IS_APPROX(r2d1f.template cast<Scalar>(),r2d1);\r\n  eigen2_Rotation2D<double> r2d1d = r2d1.template cast<double>();\r\n  VERIFY_IS_APPROX(r2d1d.template cast<Scalar>(),r2d1);\r\n\r\n  m = q1;\r\n//   m.col(1) = Vector3(0,ei_random<Scalar>(),ei_random<Scalar>()).normalized();\r\n//   m.col(0) = Vector3(-1,0,0).normalized();\r\n//   m.col(2) = m.col(0).cross(m.col(1));\r\n  #define VERIFY_EULER(I,J,K, X,Y,Z) { \\\r\n    Vector3 ea = m.eulerAngles(I,J,K); \\\r\n    Matrix3 m1 = Matrix3(AngleAxisx(ea[0], Vector3::Unit##X()) * AngleAxisx(ea[1], Vector3::Unit##Y()) * AngleAxisx(ea[2], Vector3::Unit##Z())); \\\r\n    VERIFY_IS_APPROX(m, m1); \\\r\n    VERIFY_IS_APPROX(m,  Matrix3(AngleAxisx(ea[0], Vector3::Unit##X()) * AngleAxisx(ea[1], Vector3::Unit##Y()) * AngleAxisx(ea[2], Vector3::Unit##Z()))); \\\r\n  }\r\n  VERIFY_EULER(0,1,2, X,Y,Z);\r\n  VERIFY_EULER(0,1,0, X,Y,X);\r\n  VERIFY_EULER(0,2,1, X,Z,Y);\r\n  VERIFY_EULER(0,2,0, X,Z,X);\r\n\r\n  VERIFY_EULER(1,2,0, Y,Z,X);\r\n  VERIFY_EULER(1,2,1, Y,Z,Y);\r\n  VERIFY_EULER(1,0,2, Y,X,Z);\r\n  VERIFY_EULER(1,0,1, Y,X,Y);\r\n\r\n  VERIFY_EULER(2,0,1, Z,X,Y);\r\n  VERIFY_EULER(2,0,2, Z,X,Z);\r\n  VERIFY_EULER(2,1,0, Z,Y,X);\r\n  VERIFY_EULER(2,1,2, Z,Y,Z);\r\n\r\n  // colwise/rowwise cross product\r\n  mat3.setRandom();\r\n  Vector3 vec3 = Vector3::Random();\r\n  Matrix3 mcross;\r\n  int i = ei_random<int>(0,2);\r\n  mcross = mat3.colwise().cross(vec3);\r\n  VERIFY_IS_APPROX(mcross.col(i), mat3.col(i).cross(vec3));\r\n  mcross = mat3.rowwise().cross(vec3);\r\n  VERIFY_IS_APPROX(mcross.row(i), mat3.row(i).cross(vec3));\r\n\r\n\r\n}\r\n\r\nvoid test_eigen2_geometry_with_eigen2_prefix()\r\n{\r\n  std::cout << \"eigen2 support: \" << EIGEN2_SUPPORT_STAGE << std::endl;\r\n  for(int i = 0; i < g_repeat; i++) {\r\n    CALL_SUBTEST_1( geometry<float>() );\r\n    CALL_SUBTEST_2( geometry<double>() );\r\n  }\r\n}\r\n", "meta": {"hexsha": "4fc9432e58ec5a720d1cc3b8f16ba6e87b3034f3", "size": 15637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/eigen3.2.10/test/eigen2/eigen2_geometry_with_eigen2_prefix.cpp", "max_stars_repo_name": "rgijsen/opengl_tmp_poc", "max_stars_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thirdparty/eigen3.2.10/test/eigen2/eigen2_geometry_with_eigen2_prefix.cpp", "max_issues_repo_name": "rgijsen/opengl_tmp_poc", "max_issues_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty/eigen3.2.10/test/eigen2/eigen2_geometry_with_eigen2_prefix.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": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8646788991, "max_line_length": 156, "alphanum_fraction": 0.6658566221, "num_tokens": 4858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5891707536936803}}
{"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": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2015 Benoit Steiner <benoit.steiner.goog@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"main.h\"\n\n#include <Eigen/CXX11/Tensor>\n\nstruct Generator1D {\n  Generator1D() { }\n\n  float operator()(const array<Eigen::DenseIndex, 1>& coordinates) const {\n    return coordinates[0];\n  }\n};\n\ntemplate <int DataLayout>\nstatic void test_1D()\n{\n  Tensor<float, 1> vec(6);\n  Tensor<float, 1> result = vec.generate(Generator1D());\n\n  for (int i = 0; i < 6; ++i) {\n    VERIFY_IS_EQUAL(result(i), i);\n  }\n}\n\n\nstruct Generator2D {\n  Generator2D() { }\n\n  float operator()(const array<Eigen::DenseIndex, 2>& coordinates) const {\n    return 3 * coordinates[0] + 11 * coordinates[1];\n  }\n};\n\ntemplate <int DataLayout>\nstatic void test_2D()\n{\n  Tensor<float, 2> matrix(5, 7);\n  Tensor<float, 2> result = matrix.generate(Generator2D());\n\n  for (int i = 0; i < 5; ++i) {\n    for (int j = 0; j < 5; ++j) {\n      VERIFY_IS_EQUAL(result(i, j), 3*i + 11*j);\n    }\n  }\n}\n\n\ntemplate <int DataLayout>\nstatic void test_gaussian()\n{\n  int rows = 32;\n  int cols = 48;\n  array<float, 2> means;\n  means[0] = rows / 2.0f;\n  means[1] = cols / 2.0f;\n  array<float, 2> std_devs;\n  std_devs[0] = 3.14f;\n  std_devs[1] = 2.7f;\n  internal::GaussianGenerator<float, Eigen::DenseIndex, 2> gaussian_gen(means, std_devs);\n\n  Tensor<float, 2> matrix(rows, cols);\n  Tensor<float, 2> result = matrix.generate(gaussian_gen);\n\n  for (int i = 0; i < rows; ++i) {\n    for (int j = 0; j < cols; ++j) {\n      float g_rows = powf(rows/2.0f - i, 2) / (3.14f * 3.14f) * 0.5f;\n      float g_cols = powf(cols/2.0f - j, 2) / (2.7f * 2.7f) * 0.5f;\n      float gaussian = expf(-g_rows - g_cols);\n      VERIFY_IS_EQUAL(result(i, j), gaussian);\n    }\n  }\n}\n\n\nvoid test_cxx11_tensor_generator()\n{\n  CALL_SUBTEST(test_1D<ColMajor>());\n  CALL_SUBTEST(test_1D<RowMajor>());\n  CALL_SUBTEST(test_2D<ColMajor>());\n  CALL_SUBTEST(test_2D<RowMajor>());\n  CALL_SUBTEST(test_gaussian<ColMajor>());\n  CALL_SUBTEST(test_gaussian<RowMajor>());\n}\n", "meta": {"hexsha": "dcb928714b1d66c2d0220705e01840ab8c730046", "size": 2250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/unsupported/test/cxx11_tensor_generator.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/unsupported/test/cxx11_tensor_generator.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1057.0, "max_issues_repo_issues_event_min_datetime": "2015-04-27T04:27:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:14:59.000Z", "max_forks_repo_path": "src/Eigen-3.3/unsupported/test/cxx11_tensor_generator.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 24.4565217391, "max_line_length": 89, "alphanum_fraction": 0.6413333333, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.5890334510871114}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/list.hpp>\n\n#include <ORUtils/SE3Pose.h>\n\n#include <orx/geometry/DualQuaternion.h>\n#include <orx/geometry/GeometryUtil.h>\n\n#include \"HelperFunctions.h\"\n\nusing namespace ORUtils;\nusing namespace orx;\n\n//#################### TESTS ####################\n\ntypedef boost::mpl::list<double,float> TS;\n\nBOOST_AUTO_TEST_SUITE(test_DualQuaternion)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_apply, T, TS)\n{\n  const T TOL = static_cast<T>(1e-4);\n\n  DualQuaternion<T> rot = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,1), -T(M_PI_2));\n  DualQuaternion<T> trans = DualQuaternion<T>::from_translation(Vector3<T>(1,2,3));\n  DualQuaternion<T> dq = trans * rot;\n\n  check_close(dq.apply(Vector3<T>(1,0,0)), Vector3<T>(1,1,3), TOL);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_from_point, T, TS)\n{\n  DualQuaternion<T> dq = DualQuaternion<T>::from_point(Vector3<T>(3,4,5));\n  BOOST_CHECK(DualQuaternion<T>::close(dq.conjugate(), DualQuaternion<T>(DualNumber<T>(1,0), DualNumber<T>(0,-3), DualNumber<T>(0,-4), DualNumber<T>(0,-5))));\n  BOOST_CHECK(DualNumber<T>::close(dq.norm(), DualNumber<T>(1,0)));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_from_rotation, T, TS)\n{\n  Vector3<T> axis(0,1,0);\n  DualQuaternion<T> dq = DualQuaternion<T>::from_rotation(axis, T(M_PI_4));\n\n  BOOST_CHECK_SMALL(length(dq.get_rotation() - axis * T(M_PI_4)), T(1e-4));\n  BOOST_CHECK(DualQuaternion<T>::close(dq.get_rotation_part(), dq));\n  BOOST_CHECK_SMALL(length(dq.get_translation()), T(1e-4));\n\n  Vector3<T> v(1,0,0);\n  Vector3<T> w1 = dq.apply(v);\n\n  SE3Pose pose(0, 0, 0, 0, static_cast<float>(M_PI_4), 0);\n  Vector3f r = GeometryUtil::to_rotation_vector(pose.GetR());\n  Vector3<T> w2 = DualQuaternion<T>::from_rotation(r).apply(v);\n\n  BOOST_CHECK_SMALL(length(w2 - w1), T(1e-4));\n\n  DualQuaternion<T> expected = DualQuaternion<T>(T(0.707107), T(0), T(0), T(0.707107));\n\n  dq = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,1), T(M_PI_2));\n  BOOST_CHECK(DualQuaternion<T>::close(dq, expected));\n\n  dq = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,-1), -T(M_PI_2));\n  BOOST_CHECK(DualQuaternion<T>::close(dq, expected));\n\n  dq = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,2), T(M_PI_2));\n  BOOST_CHECK(DualQuaternion<T>::close(dq, expected));\n\n  expected = DualQuaternion<T>(T(0.707107), T(0), T(0), -T(0.707107));\n\n  dq = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,1), -T(M_PI_2));\n  BOOST_CHECK(DualQuaternion<T>::close(dq, expected));\n\n  dq = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,-1), T(M_PI_2));\n  BOOST_CHECK(DualQuaternion<T>::close(dq, expected));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_from_se3, T, TS)\n{\n  DualQuaternion<T> rot = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,1), T(M_PI_2));\n  DualQuaternion<T> trans = DualQuaternion<T>::from_translation(Vector3<T>(3,4,5));\n  Vector3<T> v(1,0,0);\n\n  BOOST_CHECK(DualQuaternion<T>::close(rot, DualQuaternion<T>(DualNumber<T>(0.707107f,0), DualNumber<T>(0,0), DualNumber<T>(0,0), DualNumber<T>(0.707107f,0))));\n  BOOST_CHECK(DualQuaternion<T>::close(trans, DualQuaternion<T>(DualNumber<T>(1,0), DualNumber<T>(0,1.5f), DualNumber<T>(0,2), DualNumber<T>(0,2.5f))));\n  BOOST_CHECK(DualQuaternion<T>::close(trans * rot, DualQuaternion<T>(DualNumber<T>(0.707107f,-1.76777f), DualNumber<T>(0,2.47487f), DualNumber<T>(0,0.353553f), DualNumber<T>(0.707107f,1.76777f))));\n  BOOST_CHECK_SMALL(length(rot.apply(v) - Vector3<T>(0,1,0)), T(1e-4));\n  BOOST_CHECK_SMALL(length(trans.apply(v) - Vector3<T>(4,4,5)), T(1e-4));\n  BOOST_CHECK_SMALL(length((trans * rot).apply(v) - Vector3<T>(3,5,5)), T(1e-4));\n  BOOST_CHECK_SMALL(length((rot * trans).apply(v) - Vector3<T>(-4,4,5)), T(1e-4));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_from_translation, T, TS)\n{\n  Vector3<T> v(1,2,3), t(3,4,5);\n  DualQuaternion<T> dq = DualQuaternion<T>::from_translation(t);\n  BOOST_CHECK_SMALL(length(dq.apply(v) - (v + t)), T(1e-4));\n  BOOST_CHECK_SMALL(length(dq.get_rotation()), T(1e-4));\n  BOOST_CHECK(DualQuaternion<T>::close(dq.get_rotation_part(), DualQuaternion<T>::identity()));\n  BOOST_CHECK_SMALL(length(dq.get_translation() - t), T(1e-4));\n  BOOST_CHECK(DualQuaternion<T>::close(dq.get_translation_part(), dq));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_blend, T, TS)\n{\n  DualQuaternion<T> p = DualQuaternion<T>::from_translation(Vector3<T>(2,3,4));\n  DualQuaternion<T> q = DualQuaternion<T>::from_translation(Vector3<T>(3,4,4)) * DualQuaternion<T>::from_rotation(Vector3<T>(0,0,1), T(M_PI_2));\n  Vector3<T> v(1,0,0);\n\n  std::vector<DualQuaternion<T> > dqs;\n  dqs.push_back(p);\n  dqs.push_back(q);\n\n  std::vector<T> weights(2);\n\n  weights[0] = 1.0f, weights[1] = 0.0f;\n  BOOST_CHECK_SMALL(length(DualQuaternion<T>::linear_blend(&dqs[0], &weights[0], static_cast<int>(dqs.size())).apply(v) - Vector3<T>(3,3,4)), T(1e-4));\n\n  weights[0] = 0.5f, weights[1] = 0.5f;\n  BOOST_CHECK_SMALL(length(DualQuaternion<T>::linear_blend(&dqs[0], &weights[0], static_cast<int>(dqs.size())).apply(v) - Vector3<T>(3.41421f,4,4)), T(1e-4));\n\n  weights[0] = 0.0f, weights[1] = 1.0f;\n  BOOST_CHECK_SMALL(length(DualQuaternion<T>::linear_blend(&dqs[0], &weights[0], static_cast<int>(dqs.size())).apply(v) - Vector3<T>(3,5,4)), T(1e-4));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_pow, T, TS)\n{\n  DualQuaternion<T> rot = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,1), T(M_PI_2));\n  DualQuaternion<T> tripleRot = rot.pow(3);\n  Vector3<T> v(1,0,0);\n  BOOST_CHECK_SMALL(length(tripleRot.apply(v) - Vector3<T>(0,-1,0)), T(1e-4));\n\n  DualQuaternion<T> trans = DualQuaternion<T>::from_translation(Vector3<T>(3,4,5));\n  DualQuaternion<T> tr = trans * rot;\n  BOOST_CHECK_SMALL(length(tr.pow(3).apply(v) - (tr * tr * tr).apply(v)), T(1e-4));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_sclerp, T, TS)\n{\n  DualQuaternion<T> p = DualQuaternion<T>::from_translation(Vector3<T>(2,3,4));\n  DualQuaternion<T> q = DualQuaternion<T>::from_translation(Vector3<T>(3,4,4)) * DualQuaternion<T>::from_rotation(Vector3<T>(0,0,1), T(M_PI_2));\n  BOOST_CHECK(DualQuaternion<T>::close(p, DualQuaternion<T>(DualNumber<T>(1,0), DualNumber<T>(0,1), DualNumber<T>(0,1.5f), DualNumber<T>(0,2))));\n  BOOST_CHECK(DualQuaternion<T>::close(q, DualQuaternion<T>(DualNumber<T>(0.707107f,-1.41421f), DualNumber<T>(0,2.47487f), DualNumber<T>(0,0.353553f), DualNumber<T>(0.707107f,1.41421f))));\n\n  Vector3<T> v(1,0,0);\n  BOOST_CHECK_SMALL(length(DualQuaternion<T>::sclerp(p, q, 0.0).apply(v) - Vector3<T>(3,3,4)), T(1e-4));\n  BOOST_CHECK_SMALL(length(DualQuaternion<T>::sclerp(p, q, 0.5).apply(v) - Vector3<T>(3.41421f,4,4)), T(1e-4));\n  BOOST_CHECK_SMALL(length(DualQuaternion<T>::sclerp(p, q, 1.0).apply(v) - Vector3<T>(3,5,4)), T(1e-4));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_screw, T, TS)\n{\n  DualQuaternion<T> rot = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,1), T(M_PI_2));\n  DualQuaternion<T> trans = DualQuaternion<T>::from_translation(Vector3<T>(3,4,5));\n  DualQuaternion<T> tr = trans * rot;\n  BOOST_CHECK(DualQuaternion<T>::close(DualQuaternion<T>::from_screw(tr.to_screw()), tr));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0c350d29ec975c915435f5bd7f0214b7e191c6d0", "size": 7052, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/orx/test_DualQuaternion.cpp", "max_stars_repo_name": "torrvision/spaint", "max_stars_repo_head_hexsha": "9cac8100323ea42fe439f66407b832b88f72d2fd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 197.0, "max_stars_repo_stars_event_min_datetime": "2015-10-01T07:23:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:02:31.000Z", "max_issues_repo_path": "tests/unit/orx/test_DualQuaternion.cpp", "max_issues_repo_name": "torrvision/spaint", "max_issues_repo_head_hexsha": "9cac8100323ea42fe439f66407b832b88f72d2fd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2016-03-26T13:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T09:13:49.000Z", "max_forks_repo_path": "tests/unit/orx/test_DualQuaternion.cpp", "max_forks_repo_name": "torrvision/spaint", "max_forks_repo_head_hexsha": "9cac8100323ea42fe439f66407b832b88f72d2fd", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2015-10-03T07:14:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T08:58:18.000Z", "avg_line_length": 44.075, "max_line_length": 198, "alphanum_fraction": 0.6956891662, "num_tokens": 2321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.588964316151932}}
{"text": "#include \"conex/block_triangular_operations.h\"\n#include \"conex/supernodal_solver.h\"\n\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\nnamespace conex {\n\nusing Eigen::MatrixXd;\nusing T = TriangularMatrixOperations;\nusing B = BlockTriangularOperations;\n\nint GetMax(const std::vector<Clique>& cliques) {\n  int max = cliques.at(0).at(0);\n  for (const auto& c : cliques) {\n    for (const auto ci : c) {\n      if (ci > max) {\n        max = ci;\n      }\n    }\n  }\n  return max;\n}\n\nvoid DoCholeskyTest(const std::vector<Clique>& cliques) {\n  auto mat = GetFillInPattern(GetMax(cliques) + 1, cliques);\n  for (auto& sn : mat.supernodes) {\n    sn.diagonal().array() += 100;\n  }\n\n  Eigen::MatrixXd x = T::ToDense(mat);\n  Eigen::LLT<MatrixXd> llt(x);\n  MatrixXd L = llt.matrixL();\n  EXPECT_TRUE(llt.info() == Eigen::Success);\n\n  B::BlockCholeskyInPlace(&mat.workspace_);\n  MatrixXd error = T::ToDense(mat) - L;\n  error = error.triangularView<Eigen::Lower>();\n  EXPECT_NEAR(error.norm(), 0, 1e-12);\n}\n\nTEST(LowerTri, Cholesky) {\n  DoCholeskyTest({{0, 1, 2}, {2}});\n  DoCholeskyTest({{0, 1, 2, 4, 7}, {3, 4}, {5, 6, 7}});\n  DoCholeskyTest({{0, 1, 5}, {1, 2, 5}, {3, 4, 5}});\n  DoCholeskyTest({{0, 1, 2}, {1, 2, 3}, {3, 4, 2}});\n  DoCholeskyTest({{0, 1}, {2, 4}, {3, 4}, {5, 6, 7}, {7, 8, 9, 10}});\n}\n\nvoid DoInverseTest(const std::vector<Clique>& cliques) {\n  auto mat = GetFillInPattern(GetMax(cliques) + 1, cliques);\n  for (auto& sn : mat.supernodes) {\n    sn.diagonal().array() += 10;\n  }\n\n  Eigen::MatrixXd L = T::ToDense(mat).triangularView<Eigen::Lower>();\n  Eigen::VectorXd b;\n  b.setLinSpaced(L.rows(), -1, 1);\n\n  Eigen::VectorXd y2 = b;\n  B::ApplyBlockInverseInPlace(mat.workspace_, &y2);\n  EXPECT_NEAR((L * y2 - b).norm(), 0, 1e-12);\n}\n\nTEST(LowerTri, InverseTest) {\n  DoInverseTest({{0, 1, 2, 3}, {3, 4, 5}});\n  DoInverseTest({{0, 1, 2, 3}});\n  DoInverseTest({{0, 1, 2, 3}, {3, 4}, {4, 5, 6}});\n}\n\nvoid DoInverseOfTransposeTest(const std::vector<Clique>& cliques) {\n  auto mat = GetFillInPattern(GetMax(cliques) + 1, cliques);\n  for (auto& sn : mat.supernodes) {\n    sn.diagonal().array() += 10;\n  }\n\n  Eigen::MatrixXd L = T::ToDense(mat).triangularView<Eigen::Lower>();\n  Eigen::VectorXd b;\n  b.setLinSpaced(L.rows(), -1, 1);\n\n  Eigen::VectorXd y2 = b;\n  B::ApplyBlockInverseOfTransposeInPlace(mat.workspace_, &y2);\n  EXPECT_NEAR((L.transpose() * y2 - b).norm(), 0, 1e-12);\n}\n\nTEST(LowerTri, InverseOfTranspose) {\n  DoInverseOfTransposeTest({{0, 1, 2, 5}, {3, 4, 5}});\n  DoInverseOfTransposeTest({{0, 1, 2, 5}, {3, 4, 5}, {5, 6}});\n  DoInverseOfTransposeTest({{0, 1, 2, 3}});\n}\n\nMatrixXd Submatrix(const MatrixXd& T, const Clique& c) {\n  MatrixXd y(c.size(), c.size());\n  int i = 0;\n  for (auto ci : c) {\n    int j = 0;\n    for (auto cj : c) {\n      y(i, j) = T(ci, cj);\n      j++;\n    }\n    i++;\n  }\n  return y;\n}\n\nvoid DoLDLTTest(bool diagonal, const std::vector<Clique>& cliques) {\n  auto mat = GetFillInPattern(GetMax(cliques) + 1, cliques);\n\n  // Set to identity.\n  for (auto& sn : mat.workspace_.diagonal) {\n    if (diagonal) {\n      sn.setZero();\n    }\n    int n = sn.diagonal().size();\n    for (int i = 0; i < n; i++) {\n      sn.diagonal()(i) = -101 + i * 100;\n    }\n  }\n\n  if (diagonal) {\n    for (auto& sn : mat.workspace_.off_diagonal) {\n      sn.setZero();\n    }\n  }\n\n  Eigen::MatrixXd X = T::ToDense(mat).selfadjointView<Eigen::Lower>();\n\n  std::vector<Eigen::LDLT<Eigen::Ref<MatrixXd>>> factorization;\n  B::BlockLDLTInPlace(&mat.workspace_, &factorization);\n\n  Eigen::VectorXd z = Eigen::VectorXd::Random(X.cols());\n  z.setConstant(0);\n  z(1) = 1;\n\n  Eigen::VectorXd y = X * z;\n  // X = M D M ^T z = y\n  // z = inv(M^{T}) (MD)^{-1} y\n  B::ApplyBlockInverseOfMD(mat.workspace_, factorization, &y);\n  B::ApplyBlockInverseOfMTranspose(mat.workspace_, factorization, &y);\n  EXPECT_NEAR((z - y).norm(), 0, 1e-12);\n}\n\nTEST(LowerTri, LDLT) {\n  bool diagonal = true;\n  DoLDLTTest(diagonal, {{0, 1}});\n  DoLDLTTest(diagonal, {{0, 1, 2}, {2}});\n  DoLDLTTest(diagonal, {{0, 1, 2, 4, 7}, {3, 4}, {5, 6, 7}});\n  DoLDLTTest(diagonal, {{0, 1, 5}, {1, 2, 5}, {3, 4, 5}});\n  DoLDLTTest(diagonal, {{0, 1, 2}, {1, 2, 3}, {3, 4, 2}});\n  DoLDLTTest(diagonal, {{0, 1}, {2, 4}, {3, 4}, {5, 6, 7}, {7, 8, 9, 10}});\n\n  diagonal = false;\n  DoLDLTTest(diagonal, {{0, 1, 2}, {2}});\n  DoLDLTTest(diagonal, {{0, 1, 2, 4, 7}, {3, 4}, {5, 6, 7}});\n  DoLDLTTest(diagonal, {{0, 1, 5}, {1, 2, 5}, {3, 4, 5}});\n  DoLDLTTest(diagonal, {{0, 1, 2}, {1, 2, 3}, {3, 4, 2}});\n  DoLDLTTest(diagonal, {{0, 1}, {2, 4}, {3, 4}, {5, 6, 7}, {7, 8, 9, 10}});\n}\n\n}  // namespace conex\n", "meta": {"hexsha": "f4490f54fdff8a72d17c11ebf5c85c4cf3e6aae3", "size": 4545, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/test/block_triangular_operations_test.cc", "max_stars_repo_name": "ToyotaResearchInstitute/conex", "max_stars_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T08:02:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T21:53:22.000Z", "max_issues_repo_path": "conex/test/block_triangular_operations_test.cc", "max_issues_repo_name": "ToyotaResearchInstitute/conex", "max_issues_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/test/block_triangular_operations_test.cc", "max_forks_repo_name": "ToyotaResearchInstitute/conex", "max_forks_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T16:02:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T11:25:46.000Z", "avg_line_length": 28.2298136646, "max_line_length": 75, "alphanum_fraction": 0.5889988999, "num_tokens": 1773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5888722354086411}}
{"text": "//\r\n// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n\r\n#include <OpenTissue/core/math/math_basic_types.h>\r\n#include <OpenTissue/collision/gjk/gjk_signed_distance_to_vertex_edge_voronoi_plane.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <OpenTissue/utility/utility_push_boost_filter.h>\r\n#include <boost/test/auto_unit_test.hpp>\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\r\n\r\n#include <cmath>\r\n\r\nusing namespace OpenTissue;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_collision_gjk_signed_distance_to_vertex_edge_vp);\r\n\r\nBOOST_AUTO_TEST_CASE(case_by_case_test)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n  typedef math_types::vector3_type                         vector3_type;\r\n  typedef math_types::real_type                            real_type;\r\n\r\n\r\n  vector3_type a = vector3_type(1.0, 0.0, 0.0);\r\n  vector3_type b = vector3_type(0.0, 0.0, 0.0);\r\n\r\n  // First we use a test point that does not lie on the line\r\n\r\n  // Front side of A voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 2.0, 1.0,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_vertex_edge_voronoi_plane(p, a, b);\r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n  }\r\n  // Back side of A voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.0, 1.0,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_vertex_edge_voronoi_plane(p, a, b);\r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n  }\r\n  // In A voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 1.0, 1.0,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_vertex_edge_voronoi_plane(p, a, b);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n\r\n  // Front side of B voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( -1.0, 1.0,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_vertex_edge_voronoi_plane(p, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n  }\r\n  // Back side of B voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 1.0, 1.0,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_vertex_edge_voronoi_plane(p, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n  }\r\n  // In B voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.0, 1.0,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_vertex_edge_voronoi_plane(p, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n\r\n  // Second we use a test point that lies on the line\r\n\r\n  // Front side of A voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 2.0, 0.0,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_vertex_edge_voronoi_plane(p, a, b);\r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n  }\r\n  // Back side of A voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.0, 0.0,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_vertex_edge_voronoi_plane(p, a, b);\r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n  }\r\n  // In A voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 1.0, 0.0,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_vertex_edge_voronoi_plane(p, a, b);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n\r\n  // Front side of B voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( -1.0, 0.0,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_vertex_edge_voronoi_plane(p, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n  }\r\n  // Back side of B voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 1.0, 0.0,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_vertex_edge_voronoi_plane(p, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n  }\r\n  // In B voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.0, 0.0,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_vertex_edge_voronoi_plane(p, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "eb3269819072d349460f0e433bac955216d910c0", "size": 4507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/collision/gjk/sign_dist2vert_edge_vp/src/unit_sign_dist2vert_edge_vp.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/collision/gjk/sign_dist2vert_edge_vp/src/unit_sign_dist2vert_edge_vp.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/collision/gjk/sign_dist2vert_edge_vp/src/unit_sign_dist2vert_edge_vp.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 34.9379844961, "max_line_length": 93, "alphanum_fraction": 0.6682937653, "num_tokens": 1486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5888722307416602}}
{"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/* \u904a\u811a\u306e\u6642\u9593 */\n\tconst float period = 0.30;\n\t/* \u76ee\u6a19\u8db3\u4e0a\u3052\u9ad8\u3055 */\n\tconst float h = 0.060;\n\t/* \u30b5\u30f3\u30d7\u30ea\u30f3\u30b0\u30bf\u30a4\u30e0 */\n\tconst float dt = 0.01; \n\t\n\t/* \u8db3\u5148\u8ecc\u9053 */\n\tMatrix<float,2,1> p(Matrix<float,2,1>::Zero());\n\t/* \u76ee\u6a19\u8db3\u5148\u63a5\u5730\u4f4d\u7f6e */\n\tMatrix<float,2,1> p_goal(Matrix<float,2,1>::Zero());\n\t/* \u521d\u671f\u8db3\u5148\u4f4d\u7f6e */\n\tMatrix<float,2,1> p_start(Matrix<float,2,1>::Zero());\n\n\t/* 3\u6b21\u88dc\u9593\u306e\u305f\u3081\u306e\u4fc2\u6570 */\n\tMatrix<float,2,4> A(Matrix<float,2,4>::Zero());\n\n\t/* \u76ee\u6a19\u8db3\u5148\u63a5\u5730\u5730\u70b9 */\n\tp_goal << atof(argv[1]), atof(argv[2]); \n\t/* \u521d\u671f\u306e\u8db3\u5148\u4f4d\u7f6e */\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\u65b9\u5411\u306e\u904a\u811a\u8ecc\u9053\u751f\u6210(\u30b5\u30a4\u30af\u30ed\u30a4\u30c9\u66f2\u7dda) */\n\t\tfloat z_swing = h*0.5*(1-cos(2*pi/static_cast<int>(period/dt)*(t/dt)));\n\n\t\t/* \u6642\u523bt\u306ex, y\u65b9\u5411\u306e\u904a\u811a\u8ecc\u9053\u751f\u6210 */\n\t\tp = A * Vector4f(1, t, t*t, t*t*t);\n\t\t\n\t\t/* \u30d5\u30a1\u30a4\u30eb\u66f8\u304d\u8fbc\u307f */\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\n *\n * @copyright\n * SPDX-License-Identifier: Apache-2.0\n *\n * @test @b eigen_gemm_cdouble_dynamic_square\n * @parblock\n * This piece of code aims to stress test the exec (in particular FMA)\n * by repetitively solving general matrix matrix multiplication.  The\n * multiplication function is from the 3rd party library Eigen.  A\n * pair of random matrices are generated as inputs and then multiplied\n * using Eigen's gemm. The multiplication result is compared against a\n * golden result that is computed during init.  This particular\n * version of the test goes for double precision, complex numbers\n * input matrices.  Although the test should run fine on a single\n * thread, it is only expected to catch defects if run on at least 2\n * cores.\n *\n * @note This test requires at least 2 threads to run.\n * @endparblock\n */\n\n#include <sandstone.h>\n\n#include <Eigen/Core>\nusing namespace Eigen;\n\n#define M_DIM 221 // weird dim on purpose\n\ntypedef Matrix < std::complex < double >, Dynamic, Dynamic > Mat;\n\nnamespace {\nstruct eigen_test_data {\n    Mat lhs;\n    Mat rhs;\n    Mat prod;\n};\n}\n\n#define CAST(_x) static_cast<struct eigen_test_data *>(_x)\n\nstatic int eigen_gemm_cdouble_dynamic_square_init(struct test *test) {\n    test->data = new(eigen_test_data);\n    try {\n        CAST(test->data)->lhs = Mat::Random(M_DIM, M_DIM);\n        CAST(test->data)->rhs = Mat::Random(M_DIM, M_DIM);\n        CAST(test->data)->prod = CAST(test->data)->lhs * CAST(test->data)->rhs;\n    } catch (...) {\n        report_fail_msg(\"Exception on Eigen code, most probably OOM\");\n    }\n    return EXIT_SUCCESS;\n}\n\nstatic int eigen_gemm_cdouble_dynamic_square_run(struct test *test, int cpu) {\n    //int i=0;\n    do {\n        //++i;\n        auto testdata = CAST(test->data);\n        Mat x;\n        x = testdata->lhs * testdata->rhs;\n\n        memcmp_or_fail(reinterpret_cast<double *>(x.data()),\n                       reinterpret_cast<double *>(testdata->prod.data()), 2 * M_DIM * M_DIM);\n    } while (test_time_condition(test));\n    //log_info(\"Num iters = %i\\n\", i);\n    return EXIT_SUCCESS;\n}\n\nstatic int eigen_gemm_cdouble_dynamic_square_finish(struct test *test) {\n    delete(CAST(test->data));\n    return EXIT_SUCCESS;\n}\n\nDECLARE_TEST(eigen_gemm_cdouble_dynamic_square, \"Eigen GEMM payload (cplx double, dynamic, square)\")\n  .groups = DECLARE_TEST_GROUPS(&group_math),\n  .test_init = eigen_gemm_cdouble_dynamic_square_init,\n  .test_run = eigen_gemm_cdouble_dynamic_square_run,\n  .test_cleanup = eigen_gemm_cdouble_dynamic_square_finish,\n  .fracture_loop_count = 5,\n  .quality_level = TEST_QUALITY_PROD,\nEND_DECLARE_TEST\n", "meta": {"hexsha": "ede71ea9c6b06bf908ba7f20bd5b05e42da164ee", "size": 2612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/eigen_gemm/gemm_cdouble_dynamic_square.cpp", "max_stars_repo_name": "jposwiata/opendcdiag", "max_stars_repo_head_hexsha": "4ce25562ebaca238150ffd7e8ceea9de4daf0992", "max_stars_repo_licenses": ["Apache-2.0"], "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/eigen_gemm/gemm_cdouble_dynamic_square.cpp", "max_issues_repo_name": "jposwiata/opendcdiag", "max_issues_repo_head_hexsha": "4ce25562ebaca238150ffd7e8ceea9de4daf0992", "max_issues_repo_licenses": ["Apache-2.0"], "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/eigen_gemm/gemm_cdouble_dynamic_square.cpp", "max_forks_repo_name": "jposwiata/opendcdiag", "max_forks_repo_head_hexsha": "4ce25562ebaca238150ffd7e8ceea9de4daf0992", "max_forks_repo_licenses": ["Apache-2.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.4698795181, "max_line_length": 100, "alphanum_fraction": 0.7009954058, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639065, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5888193633543206}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2020 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"zero_weighted_alpha_complex\"\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <CGAL/Epeck_d.h>\n\n#include <vector>\n#include <random>\n#include <cmath> // for std::fabs\n\n#include <gudhi/Alpha_complex.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Unitary_tests_utils.h>\n\nusing list_of_exact_kernel_variants = boost::mpl::list<CGAL::Epeck_d< CGAL::Dynamic_dimension_tag >,\n                                                       CGAL::Epeck_d< CGAL::Dimension_tag<4> >\n                                                       > ;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(Zero_weighted_alpha_complex, Kernel, list_of_exact_kernel_variants) {\n  // Check that in exact mode for static dimension 4 the code for dD unweighted and for dD weighted with all weights\n  // 0 give exactly the same simplex tree (simplices and filtration values).\n\n  // Random points construction\n  using Point_d = typename Kernel::Point_d;\n  std::vector<Point_d> points;\n  std::uniform_real_distribution<double> rd_pts(-10., 10.);\n  std::random_device rand_dev;\n  std::mt19937 rand_engine(rand_dev());\n  for (int idx = 0; idx < 20; idx++) {\n    std::vector<double> point {rd_pts(rand_engine), rd_pts(rand_engine), rd_pts(rand_engine), rd_pts(rand_engine)};\n    points.emplace_back(point.begin(), point.end());\n  }\n  \n  // Alpha complex from points\n  Gudhi::alpha_complex::Alpha_complex<Kernel, false> alpha_complex_from_points(points);\n  Gudhi::Simplex_tree<> simplex;\n  Gudhi::Simplex_tree<>::Filtration_value infty = std::numeric_limits<Gudhi::Simplex_tree<>::Filtration_value>::infinity();\n  BOOST_CHECK(alpha_complex_from_points.create_complex(simplex, infty, true));\n  std::clog << \"Iterator on alpha complex simplices in the filtration order, with [filtration value]:\"\n            << std::endl;\n  for (auto f_simplex : simplex.filtration_simplex_range()) {\n    std::clog << \"   ( \";\n    for (auto vertex : simplex.simplex_vertex_range(f_simplex)) {\n      std::clog << vertex << \" \";\n    }\n    std::clog << \") -> \" << \"[\" << simplex.filtration(f_simplex) << \"] \" << std::endl;\n  }\n\n  // Alpha complex from zero weighted points\n  std::vector<typename Kernel::FT> weights(20, 0.);\n  Gudhi::alpha_complex::Alpha_complex<Kernel, true> alpha_complex_from_zero_weighted_points(points, weights);\n  Gudhi::Simplex_tree<> zw_simplex;\n  BOOST_CHECK(alpha_complex_from_zero_weighted_points.create_complex(zw_simplex, infty, true));\n\n  std::clog << \"Iterator on zero weighted alpha complex simplices in the filtration order, with [filtration value]:\"\n            << std::endl;\n  for (auto f_simplex : zw_simplex.filtration_simplex_range()) {\n    std::clog << \"   ( \";\n    for (auto vertex : zw_simplex.simplex_vertex_range(f_simplex)) {\n      std::clog << vertex << \" \";\n    }\n    std::clog << \") -> \" << \"[\" << zw_simplex.filtration(f_simplex) << \"] \" << std::endl;\n  }\n\n  BOOST_CHECK(zw_simplex == simplex);\n}", "meta": {"hexsha": "b7df07c7a22dbc0c543dc3dbfbead7a3893b00f1", "size": 3302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Alpha_complex/test/Zero_weighted_alpha_complex_unit_test.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Alpha_complex/test/Zero_weighted_alpha_complex_unit_test.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Alpha_complex/test/Zero_weighted_alpha_complex_unit_test.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 42.8831168831, "max_line_length": 123, "alphanum_fraction": 0.683827983, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5888107640401783}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n\n#include <iostream>\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE mf test\n#include <boost/test/unit_test.hpp>\n\n#include <mmf/mfPrior.hpp>\n#include <mmf/mf.hpp>\n\nBOOST_AUTO_TEST_CASE(mf_test)\n{\n  boost::mt19937 rndGen(1);\n  double nu = 4;\n  MatrixXd Delta = MatrixXd::Identity(2,2);\n  Delta *= pow(5.0*M_PI/180.,2)*nu;\n  IW<double> iw0(Delta,nu,&rndGen);\n  std::vector<shared_ptr<BaseMeasure<double> > >thetas;\n  for(uint32_t k=0; k<6; ++k)\n    thetas.push_back(shared_ptr<IwTangent<double> >(\n          new IwTangent<double>(iw0,&rndGen)));\n  VectorXd alpha = VectorXd::Ones(6);\n  Dir<Cat<double>, double> dir(alpha,&rndGen);\n  DirMM<double> dirMM(dir,thetas);\n  MfPrior<double> mfPrior(dirMM,10);\n\n  MatrixXd Sigma = MatrixXd::Identity(2,2);\n  Sigma *= pow(1.0*M_PI/180.,2);\n  uint32_t N = 100;\n  MatrixXd x(3,N*6);\n  MatrixXd R(3,3);\n  double theta = 30.*M_PI/180.;\n  R<<cos(theta), -sin(theta), 0.,\n     sin(theta),cos(theta) ,0.,\n     0,0,1.;\n  cout<<R<<endl;\n  cout<<\" ..................... \"<<endl;\n  for(uint32_t k=0; k<6; ++k)\n  {\n    NormalSphere<double> g(R*mfPrior.M().col(k),Sigma,&rndGen);\n    for(uint32_t i =0; i< N; ++i)\n      x.col(i+N*k) = g.sample(); \n  }\n  VectorXu z = VectorXu::Zero(N*6);\n  MF<double> mf = mfPrior.posteriorSample(x,z,0);\n\n  mf.print();\n\n  for(uint32_t i =0; i< N*6; i+=N)\n  {\n    cout<<mf.logPdf(x.col(i))<<endl;\n  }\n  MF<double> mf2(mf);\n  mf2.print();\n};\n", "meta": {"hexsha": "361a19b30e1955cf56ca220eacf567f0cb9138d6", "size": 1536, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/mf.cpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "test/mf.cpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/mf.cpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 26.4827586207, "max_line_length": 64, "alphanum_fraction": 0.6276041667, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.588810752908752}}
{"text": "// Array DAXPY benchmark\n\n#include <blitz/benchext.h>\n#include <blitz/array.h>\n#include <blitz/vector2.h>\n#include <random/uniform.h>\n\nBZ_NAMESPACE(blitz)\nextern void sink();\nBZ_NAMESPACE_END\n\nBZ_USING_NAMESPACE(blitz)\n\n#ifdef BZ_FORTRAN_SYMBOLS_WITH_TRAILING_UNDERSCORES\n  #define arrdaxpyf arrdaxpyf_\n#elif defined(BZ_FORTRAN_SYMBOLS_WITH_DOUBLE_TRAILING_UNDERSCORES)\n  #define arrdaxpyf arrdaxpyf__\n#endif\n\nextern \"C\" {\n    void arrdaxpyf(double* A, double* B, int& N, double& a);\n}\n\nvoid arrdaxpyFortran77Version(BenchmarkExt<int>& bench);\nvoid arrdaxpyBlitzVersion(BenchmarkExt<int>& bench);\n\nint main()\n{\n    BenchmarkExt<int> bench(\"Array DAXPY\", 2);\n\n    const int numSizes = 8;\n\n    bench.setNumParameters(numSizes);\n    bench.setDependentVariable(\"flops\");\n\n    Vector<int> parameters(numSizes);\n    Vector<long> iters(numSizes);\n    Vector<double> flops(numSizes);\n\n    parameters = pow(2.,tensor::i);\n    cout << parameters;\n    iters = 100*16*32*8*8*8/pow3(parameters);\n    cout << iters;\n    flops = pow3(parameters) * 2 * 2;\n    cout << flops;\n\n    bench.setParameterVector(parameters);\n    bench.setParameterDescription(\"3D Array size\");\n    bench.setIterations(iters);\n    bench.setOpsPerIteration(flops);\n\n    bench.beginBenchmarking();\n    arrdaxpyBlitzVersion(bench);\n    arrdaxpyFortran77Version(bench);\n    bench.endBenchmarking();\n\n    bench.saveMatlabGraph(\"arrdaxpy.m\");\n\n    return 0;\n}\n\nvoid initializeRandomDouble(double* data, int numElements)\n{\n  ranlib::Uniform<double> rnd;\n\n    for (int i=0; i < numElements; ++i)\n        data[i] = rnd.random();\n}\n\nvoid arrdaxpyBlitzVersion(BenchmarkExt<int>& bench)\n{\n    bench.beginImplementation(\"Blitz++\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Blitz++: N = \" << N << endl;\n        cout.flush();\n\n        long iters = bench.getIterations();\n\n        Array<double,3> A(N,N,N), B(N,N,N);\n        initializeRandomDouble(A.data(), N*N*N);\n        initializeRandomDouble(B.data(), N*N*N);\n        TinyVector<int,2> size = N-2;\n        double a = 0.34928313;\n        double b = - a; \n\n        bench.start();\n        for (long i=0; i < iters; ++i)\n        {\n            A += a * B;\n            A += b * B;\n\t    sink();\n        }\n        bench.stop();\n\n        bench.startOverhead();\n        for (long i=0; i < iters; ++i) {\n            sink();\n\t}\n        bench.stopOverhead();\n    }\n\n    bench.endImplementation();\n}\n\nvoid arrdaxpyFortran77Version(BenchmarkExt<int>& bench)\n{\n    bench.beginImplementation(\"Fortran 77\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Fortran 77: N = \" << N << endl;\n        cout.flush();\n\n        int iters = (int)bench.getIterations();\n\n        size_t arraySize = size_t(N) * size_t(N) * N;\n       \n        double* A = new double[arraySize];\n        double* B = new double[arraySize];\n\n        initializeRandomDouble(A, arraySize);\n        initializeRandomDouble(B, arraySize);\n\n        double a = 0.34928313;\n\n        for (long i=0; i < iters; ++i)\n        {\n\t  arrdaxpyf(A,B,N,a);\n\t  sink();\n        }\n        bench.stop();\n\n        bench.startOverhead();\n        for (long i=0; i < iters; ++i) {\n            sink();\n\t}\n        bench.stopOverhead();\n\n        delete [] A;\n        delete [] B;\n    }\n\n    bench.endImplementation();\n}\n", "meta": {"hexsha": "3cb6dfed4455dd5f3e9f5f07c21a713713860722", "size": 3373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/arrdaxpy.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/arrdaxpy.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/arrdaxpy.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3377483444, "max_line_length": 66, "alphanum_fraction": 0.6059887341, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5888107407453562}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nThis class is created for using the extended hull-white model with\nterm structure of volatility.\n\nCreated by Jihoon Lee, 20150127\n\n*/\n\n/*! \\file hullwhitevolatility.hpp\n\t\\brief HullWhite functions\n*/\n\n#ifndef quantlib_hullwhitevolatility_hpp\n#define quantlib_hullwhitevolatility_hpp\n\n#include <ql/time/date.hpp>\n#include <ql/math/matrix.hpp>\n#include <ql/time/daycounter.hpp>\n#include <ql/models/parameter.hpp>\n#include <ql/termstructures/interpolatedcurve.hpp>\n#include <ql/math/interpolations/linearinterpolation.hpp>\n#include <boost/function.hpp>\n\n#include <ql/types.hpp>\n\nnamespace QuantLib {\n\n\tclass HullWhiteVolatility {\n\t public:\n\t\t HullWhiteVolatility();\n\n\t\t HullWhiteVolatility(\n\t\t\t Date referenceDate,\n\t\t\t DayCounter dc,\n\t\t\t std::vector<Volatility>& vols,\n\t\t\t std::vector<Date>& volDates);\t\t \n\n\t\t boost::function<Real (Time)> vol() const;\n\n\t\t Real sigma() const { return sigma_(0.0); }\n\n\t private:\n\n\t\t Date referencedate_;\n\t\t DayCounter daycounter_;\n\n\t\t std::vector<Date> volstructure_;\n\t\t std::vector<Time> volperiods_;\t\t \n\n\t\t Parameter sigma_;\n\t};\n\n}\n\n#endif", "meta": {"hexsha": "ae50e6e9565ce41f368eb9b08cbff9438d5bd88b", "size": 1154, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/termstructures/volatility/hullwhitevolatility.hpp", "max_stars_repo_name": "quantosaurosProject/quantLib", "max_stars_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/termstructures/volatility/hullwhitevolatility.hpp", "max_issues_repo_name": "quantosaurosProject/quantLib", "max_issues_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/termstructures/volatility/hullwhitevolatility.hpp", "max_forks_repo_name": "quantosaurosProject/quantLib", "max_forks_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-29T05:44:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:44:27.000Z", "avg_line_length": 20.2456140351, "max_line_length": 79, "alphanum_fraction": 0.7218370884, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5888107356956275}}
{"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": "#include <Eigen/Dense>\n#include <tf/transform_listener.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Point.h>\n#include <nav_msgs/OccupancyGrid.h>\n#include <nav_msgs/MapMetaData.h>\n\nconst float EPS = 1e-2;\n// Convert int data[] to Eigen::MatrixXd\nvoid grid_to_matrix(const nav_msgs::OccupancyGrid msg, Eigen::MatrixXd &map){\n  for(int i=0; i<msg.data.size(); ++i){\n    map(i/msg.info.width,i%msg.info.height) = msg.data[i];\n  }\n}\n// Get indices of grid from position\n// Return false if out of range\nbool pose_to_idx(nav_msgs::MapMetaData info, double target_x, double target_y, int& idx_x, int& idx_y){\n  geometry_msgs::Pose origin = info.origin;\n  float resolution = info.resolution;\n  int map_width = info.width, map_height = info.height;\n  idx_x = floor((target_x - origin.position.x + EPS)/resolution);\n  idx_y = floor((target_y - origin.position.y + EPS)/resolution);\n  if(idx_x<0 or idx_x>=map_height or idx_y<0 or idx_y>=map_height) return false;\n  return true;\n}\n// Convert indices of grid to position with type PoseStamped\ngeometry_msgs::PoseStamped indice_to_pose(nav_msgs::MapMetaData info, int x, int y){\n  geometry_msgs::Pose origin = info.origin;\n  float resolution = info.resolution;\n  geometry_msgs::PoseStamped res;\n  res.pose.position.x = origin.position.x+resolution*y;\n  res.pose.position.y = origin.position.y+resolution*x; // Have to change xy order\n  res.pose.orientation.w = 1.0;\n  return res;\n}\n// Convert indices of grid to position with type Point\ngeometry_msgs::Point indice_to_point(nav_msgs::MapMetaData info, int x, int y){\n  geometry_msgs::Pose origin = info.origin;\n  float resolution = info.resolution;\n  geometry_msgs::Point res;\n  res.x = origin.position.x+resolution*y;\n  res.y = origin.position.y+resolution*x; // Have to change xy order\n  return res;\n}\n// Convert frame of pose with given transform\nvoid convertFrame(tf::Transform mat, geometry_msgs::PoseStamped &ps){\n  tf::Vector3 pos(ps.pose.position.x, ps.pose.position.y, 0), res = mat*pos;\n  ps.pose.position.x = res.getX(); ps.pose.position.y = res.getY();\n}\n// Convert frame of pose with given transform\nvoid convertFrame(tf::Transform mat, geometry_msgs::Pose &ps){\n  tf::Vector3 pos(ps.position.x, ps.position.y, 0), res = mat*pos;\n  ps.position.x = res.getX(); ps.position.y = res.getY();\n}\n// Overloading for input point\nvoid convertFrame(tf::Transform mat, geometry_msgs::Point &p){\n  tf::Vector3 pos(p.x, p.y, 0), res = mat*pos;\n  p.x = res.getX(); p.y = res.getY();\n}\n", "meta": {"hexsha": "6bd40ef625018dd7c1e07d121d23e785cd700d77", "size": 2491, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/path_planning/src/helper.hpp", "max_stars_repo_name": "championway/asv_ros", "max_stars_repo_head_hexsha": "4ded50c48077e1e63586cd32be2354633c163975", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/path_planning/src/helper.hpp", "max_issues_repo_name": "championway/asv_ros", "max_issues_repo_head_hexsha": "4ded50c48077e1e63586cd32be2354633c163975", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/path_planning/src/helper.hpp", "max_forks_repo_name": "championway/asv_ros", "max_forks_repo_head_hexsha": "4ded50c48077e1e63586cd32be2354633c163975", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-08T20:05:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T20:05:02.000Z", "avg_line_length": 41.5166666667, "max_line_length": 103, "alphanum_fraction": 0.7278201525, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5887406978908934}}
{"text": "#ifndef RADARMODELROS_H\n#define RADARMODELROS_H\n\n//ROS MSGS\n#include \"nav_msgs/OccupancyGrid.h\"\n#include \"std_msgs/Header.h\"\n#include \"nav_msgs/MapMetaData.h\"\n\n//GRIDMAP\n#include <grid_map_ros/grid_map_ros.hpp>\n#include <grid_map_core/iterators/GridMapIterator.hpp>\n#include <grid_map_cv/grid_map_cv.hpp>\n#include <grid_map_core/GridMap.hpp>\n\n#include <Eigen/Eigen> // AFTER GRIDMAP!\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/Splines>\n\n// Math\n#include <algorithm>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <math.h>\n#include <vector>\n\n// other\n#include <iomanip>\n#include <string>\n\n// OpenCV\n#include <cv_bridge/cv_bridge.h>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\nusing namespace std;\nusing namespace grid_map;\nusing namespace std::placeholders;\nusing Eigen::MatrixXf;\n\n// constants ..................................................................\n// We mostly use UPM frog 3D.\nconst double TAG_LOSSES = -4.8;\n\n// 20 * log10 ( c / (4*pi) )\nconst double LOSS_CONSTANT = 147.55;\n// 4*pi/c\nconst double PHASE_CONSTANT = 4.192e-8;\nconst double C = 299792458.0;\n\n// This comes from the manufacturer. Azimut\n// gain list entries start at -180 degrees to 180 in steps of 15.\nconst double ANTENNA_LOSSES_LIST[25] = {\n    -22.6, -25.2, -25,   -20.2, -17.6, -15.6, -14,  -11.2, -7.8,\n    -5.2,  -2.4,  -0.6,  0,     -0.6,  -2.4,  -5.2, -8.8,  -12.2,\n    -16.4, -19.2, -20.8, -24.4, -28.2, -24,   -22.6};\nconst double ANTENNA_ANGLES_LIST[25] = {\n    -180.0, -165.0, -150.0, -135.0, -120.0, -105.0, -90.0, -75.0, -60.0,\n    -45.0,  -30.0,  -15.0,  0.0,    15.0,   30.0,   45.0,  60.0,  75.0,\n    90.0,   105.0,  120.0,  135.0,  150.0,  165.0,  180.0};\n\n// M6e RFID reader Specs\n// Minimum required power to identify a tag. Also depends on other factors, but\n// this value is a guide\nconst double SENSITIVITY = -115; // dB\n\n// Max transmitted power may be limited by the Region regulations\n// see Power Requirements  in M6e Hardware Guide\nconst double MIN_TX_POWER = -25;  // dB\nconst double MAX_TX_POWER = 0;    // dB\nconst double STEP_TX_POWER = 0.5; // dB\n\n// These freqs ARE limited depending on the region regulations\n// see Regional Frequency Quantization in M6e Hardware Guide\nconst double STEP_FREQ = 25e3;   // Hertzs\nconst double MIN_FREQ_A = 865e6; // Hertzs\nconst double MAX_FREQ_A = 869e6; // Hertzs\nconst double MIN_FREQ_B = 902e6; // Hertzs\nconst double MAX_FREQ_B = 928e6; // Hertzs\n\n// most likely we will use EU or NA regions....\nconst double MIN_FREQ_EU = 865.6e6; // Hertzs\nconst double MAX_FREQ_EU = 867.6e6; // Hertzs\nconst double STEP_FREQ_EU = 100e3;  // Hertzs\n\nconst double MIN_FREQ_NA = 902e6;  // Hertzs\nconst double MAX_FREQ_NA = 928e6;  // Hertzs\nconst double STEP_FREQ_NA = 250e3; // Hertzs\n\n//  ..................................................................\n\n/**\n * @brief The spline is used to interpolate antenna gain values,\n * as we only have the graph\n */\nclass SplineFunction {\n\npublic:\n  SplineFunction();\n\n  /**\n   * @brief Construct a new Spline Function Interpolation for antenna gain\n   *\n   * @param x_vec reference azimuth angle (deg) points\n   * @param y_vec reference gain (db) points\n   */\n  SplineFunction(Eigen::VectorXd const &x_vec, Eigen::VectorXd const &y_vec);\n\n  /**\n   * @brief Interpolate gain from angle\n   *\n   * @param x azimuth angle (rads)\n   * @return double interpolated gain (dB)\n   */\n  double interpRad(double x) const;\n  float interpRadf(float x) const;\n\n  /**\n   * @brief Interpolate gain from angle\n   *\n   * @param x azimuth angle (degs)\n   * @return double interpolated gain (dB)\n   */\n  double interpDeg(double x) const;\n\nprivate:\n  double scaled_value(double x) const;\n\n  Eigen::RowVectorXd scaled_values(Eigen::VectorXd const &x_vec) const;\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\nclass RadarModelROS {\n\npublic:\n  int _Ncol; // number of rows of reference and rfid belief maps (cells)\n  int _Nrow; // number of cols of reference and rfid belief maps (cells)\n  float _free_space_val; // max value stored in reference map, used as free\n                         // space marker\n  double _resolution;    // Reference AND belief map resolution (m./cell)\n\n  // we only model here gaussian noise\n  double _sigma_power; // noise factor\n  double _sigma_phase; // noise factor\n\n  GridMap _rfid_belief_maps; // Prob. beliefs. One layer per tag. Also, one\n                             // layer with reference map, mostly for tag layout\n                             // representation.\n  GridMap _tmp_rfid_c_map;\n\n  std::vector<std::pair<double, double>>  _tags_coords; // tag locations in reference map coords (m.)\n  int _numTags;     // rfid tags to consider\n\n  SplineFunction _antenna_gains; // model for antenna power gain depending on\n                                 // the angle (dB.)    \n  // gains cache for hopefully faster access.\n  std::vector<float> _antenaGainVector; \n\n  bool _output_prediction = false;\n  float gainValue(int x);\n  \n  RadarModelROS(const nav_msgs::OccupancyGrid& nav_map, const double sigma_power, const double sigma_phase, const double resolution, bool output_prediction );\n  void initRefMap(const nav_msgs::OccupancyGrid& nav_map);\n\n  void loadBelief(const std::string imageURI);\n\n  void saveBelief(const std::string imageURI);\n\n  /**\n   * @brief Construct a new Radar Model object\n   *        It is based upon the link budget equation. See D. M. Dobkin, \u201cThe RF\n   * in RFID: Passive UHF RFID in Practice\u201d, Elsevier, 2007\n   * @param resolution   reference map and rfid belief map images resolution in\n   * m./cell\n   * @param sigma_power  noise std in log model\n   * @param sigma_phase  noise std in phase\n   * @param txtPower     transmitted power (dB)\n   * @param freqs        frequencies used in transmission\n   * @param tags_coords  tag positions in map coordinates\n   * @param imageFileURI reference map file\n   *   TODO We will use a fixed antenna model, Gaussian noise model and will\n   * assume tags are isotropic. This may need to be revisited ...\n   */\n  RadarModelROS(const double resolution, const double sigma_power,\n             const double sigma_phase, \n             const std::vector<std::pair<double, double>> tags_coords,\n             const std::string imageFileURI);\n\n  RadarModelROS();\n\n  /**\n   * @brief Print scenario map with tags\n   *\n   * @param fileURI\n   */\n  void PrintRefMapWithTags(std::string fileURI);\n\n  double received_power_friis_with_obstacles(double antenna_x, double antenna_y,\n                                             double antenna_h, double tag_x,\n                                             double tag_y, double tag_h,\n                                             double freq, double txtPower,\n                                             SplineFunction antennaGainsModel);\n\n  double received_power_friis_with_obstacles(double antenna_x, double antenna_y,\n                                             double antenna_h, double tag_x,\n                                             double tag_y, double tag_h,\n                                             double freq, double txtPower);\n  /**\n   * @brief Plots a power distribution\n   *\n   * @param fileURI save file location\n   * @param f_i frequency to consider in the propagation model\n   */\n  void PrintRecPower(std::string fileURI, double f_i, double txtPower);\n\n  /**\n   * @brief Plots a probability distribution, conditioned to a received power\n   *\n   * @param fileURI save file location\n   * @param rxPw received power\n   * @param f_i frequency to consider in the propagation model\n   */\n  void PrintPowProb(std::string fileURI, double rxPw, double f_i, double txtPower);\n\n  void PrintPhase(std::string fileURI, double f_i);\n  void PrintPhaseProb(std::string fileURI, double phi, double f_i);\n  void PrintBothProb(std::string fileURI, double rxPw, double phi, double f_i, double txtPower);\n\n  void PrintMap(std::string savePath);\n  void initRefMap(const std::string imageURI);\n  void getImage(std::string layerName, std::string fileURI);\n  void addTagID(std::string tagID, int i);\n  /**\n   * @brief Get layer name corresponding to given frequency (Hz.)\n   *\n   * @param freq_i\n   * @return std::string\n   */\n  std::string getLayerName(double freq_i);\n  /////////////////////\n  /**\n   * returns a range vector FROM start TO stop (included) in step increments\n   * @param  start min Value in vector\n   * @param  stop  max Value in vector\n   * @param  step  increment\n   * @return       range vector\n   */\n  std::vector<double> range(double start, double stop, double step);\n\n  /**\n   * returns MT_242025NRHK antenna losses in a plane\n   * @param  angleRad spheric coordinate within the plane (radians)\n   * @return          dB losses\n   */\n  double antennaPlaneLoss(double angleRad);\n\n  /**\n   * my Sign function...\n   * @param  x\n   * @return   sign of x\n   */\n  float sign(float x);\n\n  /**\n   * Returns Spherical coordinates\n   * @param x          cartesian coordinate x (m.)\n   * @param y          cartesian coordinate y (m.)\n   * @param r          spheric coordinate r (m.)\n   * @param phi        relative azimut [0,2pi) (angle between XY projection and\n   * X) (radians)\n   */\n  void getSphericCoords(double x, double y, double &r, double &phi);\n\n  /**\n   * Received signal estimated phase difference with pi ambiguity\n   * @param  tag_x       Tag x coord (m.) with respect to antenna\n   * @param  tag_y       Tag y coord (m.) with respect to antenna\n   * @param  freq        Transmission frequency (Hertzs)\n   * @return      phase difference (radians)\n   */\n  double phaseDifference(double tag_x, double tag_y, double freq);\n\n  Eigen::MatrixXf getFriisMat(double x_m, double y_m, double orientation_deg,\n                              double freq, double txtPower);\n  Eigen::MatrixXf getFriisMatFast(double x_m, double y_m,\n                                  double orientation_deg, double freq, double txtPower);\n\n  Eigen::MatrixXf getPhaseMat(double x_m, double y_m, double orientation_deg,\n                              double freq);\n  Eigen::MatrixXf getProbCond(Eigen::MatrixXf X_mat, double x, double sig);\n  /**\n   * @param  x             x coord (m.) in map coords of the center\n   * @param  y             y coord (m.) in map coords of the center\n   * @param  orientation   orientation (rad.) in map coords of the center\n   * @param  tag_i         tag we want to read\n   */\n  double getTotalWeight(double x, double y, double orientation, int tag_i);\n\n  double getTotalWeight(double x, double y, double orientation, double size_x,\n                        double size_y, int tag_i);\n\n  double getTotalWeight(grid_map::SubmapIterator iterator, int tag_i);\n\n  double getTotalWeight(grid_map::PolygonIterator iterator, int tag_i);\n  double getTotalWeight(int tag_i);\n\n  void addMeasurement(double x, double y, double orientation, double rxPower,\n                      double phase, double freq, int i, double txtPower);\n  \n  std::string getPowLayerName(double freq_i);\n\n  std::string getPhaseLayerName(double freq_i);\n\n  std::string getTagLayerName(int tag_num);\n\n  /**\n   * Get received power from an OMNIDIRECTIONAL tag,\n   * given its relative position to antenna.\n   * We assume antenna at 0,0,0, facing X coordinate.\n   * See http://www.antenna-theory.com/basics/friis.php\n   * Sensitivity is -85 dBm / -115 dB\n   *\n   * @param  tag_r       Tag r coord (m.) with respect to antenna\n   * @param  tag_h       Tag h coord (rad.) with respect to antenna\n   * @param  freq        Transmission frequency (Hertzs)\n   * @param  txtPower    Transmitted power (dB)\n   * @param antennaGainsModel   Antena Gain model\n   * @return             Received power (dB)\n   */\n  double received_power_friis_polar(double tag_r, double tag_h, double freq,\n                                    double txtPower,\n                                    SplineFunction antennaGainsModel);\n\n  void getImageDebug(GridMap *gm, std::string layerName, std::string fileURI);\n  Eigen::MatrixXf getPowProbCond(double rxPw, double f_i, double txtPower);\n  Eigen::MatrixXf getPhaseProbCond(double ph_i, double f_i);\n  Eigen::MatrixXf getProbCond(std::string layer_i, double x, double sig);\n\n  void saveProbMapDebug(std::string savePATH, int tag_num, int step,\n                        double robot_x, double robot_y, double robot_head);\n  void createTempProbLayer(Eigen::MatrixXf prob_mat, double x_m, double y_m,\n                           double orientation_deg);\n  cv::Mat rfidBeliefToCVImg(std::string layer_i);\n  void getImage(GridMap *gm, std::string layerName, std::string fileURI);\n  Position getRelPoint(Position glob_point, double x_m, double y_m,\n                       double orientation_rad);\n  Eigen::MatrixXf getIntervProb(std::string layer_i, double x, double sigm);\n  void fillFriisMat(Eigen::MatrixXf *rxPw_mat, Eigen::MatrixXf *delay_mat,\n                    double freq_i, double offset);\n\n  void overlayRobotPose(GridMap *gm, double robot_x, double robot_y, double robot_head,\n                        cv::Mat &image);\n  void overlayRobotPose(double robot_x, double robot_y, double robot_head,\n                        cv::Mat &image);\n                        \n  void overlayRobotPoseT(double robot_x, double robot_y, double robot_head,\n                         cv::Mat &image);\n  void rotatePoints(cv::Point *points, int npts, int cxi, int cyi, double ang);\n  void clearObstacles(cv::Mat &image);\n\n  Eigen::MatrixXf getProbCondG(std::string layer_i, double x, double sig);\n  Eigen::MatrixXf getProbCondLogN(std::string layer_i, double x, double sig);\n\n  void PrintProb(std::string fileURI, Eigen::MatrixXf *prob_mat, double sX,\n                 double sY, double res);\n  void saveProbMaps(std::string savePath);\n\n  grid_map::Position fromPoint(cv::Point cvp);\n  grid_map::Polygon getActiveMapEdges(double robot_x, double robot_y,\n                                      double robot_head);\n\n  void PrintProb(std::string fileURI, Eigen::MatrixXf *prob_mat);\n\n  std::pair<int, std::pair<int, int>> findTagFromBeliefMap(int num_tag);\n\n  void normalizeRFIDLayer(std::string layerName);\n  void clearObstacleCellsRFIDLayer(std::string layerName);\n  void addTagLayer(int tagNum);\n\n\n  double getNormalizingFactorBayesRFIDActiveArea(double x_m, double y_m,\n                                                 double orientation_rad,\n                                                 string tagLayerName);\n  Eigen::MatrixXf getNegProb(std::string layer_i, double sensitivity,\n                             double sigm);\n\n  void debugInfo();\n  void debugInfo(GridMap *gm, std::string mapName,std::string baseLayer);\n\n  cv::Point getPoint(double x, double y);\n  cv::Point getPoint(  GridMap* gm, double x_m, double y_m);\n\n  void overlayActiveMapEdges(double robot_x, double robot_y, double robot_head,\n                             cv::Mat image);\n  void overlayMapEdges(cv::Mat image);\n\n  /**\n   * Calculate the KL-divergence between posterior and prior distribution over\n   * tags position\n   *\n   * @param x: x-coord (m.) of the center\n   * @param y: y-coord (m.) of the center\n   * @param orientation: orientation (rad.) in map coords of the center\n   * @param size_x: size-x of the active area\n   * @param size_y: size-y of the active area\n   * @param tag_i: id of the tag emitting the signal\n   */\n  double getTotalKL(double x, double y, double orientation, double size_x,\n                    double size_y, int tag_i);\n  /**\n   * Calculate the KL-divergence between posterior and prior distribution over\n   * tags position\n   *\n   * @param x: x-coord (m.) of the center\n   * @param y: y-coord (m.) of the center\n   * @param orientation: orientation (rad.) in map coords of the center\n   * @param iterator: iterator over a submap\n   * @param tag_i: id of the tag emitting the signal\n   */\n  double getTotalKL(double x, double y, double orientation,\n                    grid_map::SubmapIterator iterator, int tag_i);\n  /**\n   * Calculate the entropy of the tag position over the map\n   *\n   * @param x: x-coord (m.) of the center\n   * @param y: y-coord (m.) of the center\n   * @param orientation: orientation (rad.) in map coords of the center\n   * @param size_x: size-x of the active area\n   * @param size_y: size-y of the active area\n   * @param tag_i: id of the tag emitting the signal\n   */\n  double getTotalEntropy(double x, double y, double orientation, double size_x,\n                         double size_y, int tag_i);\n  /**\n   * Calculate the entropy of the tag position over the map\n   *\n   * @param x: x-coord (m.) of the center\n   * @param y: y-coord (m.) of the center\n   * @param orientation: orientation (rad.) in map coords of the center\n   * @param iterator: iterator over a submap\n   * @param tag_i: id of the tag emitting the signal\n   */\n  double getTotalEntropy(double x, double y, double orientation,\n                         grid_map::SubmapIterator iterator, int tag_i);\n  /**\n   * Calculate the entropy of the tag position over the map\n   *\n   * @param target: the robot pose\n   * @param maxX: distance from one focal distance to the further edge\n   * @param minX: distance from one focal distance to the clostest edge\n   * @param tag_i: id of the tag emitting the signal\n   */\n  double getTotalEntropyEllipse(double x, double y, double h_rad, double maxX, double minX,\n                                int tag_i);\n  /**\n   * Calculate the entropy of the tag position over the map\n   *\n   * @param target: the robot pose\n   * @param iterator: iterator over an ellipse\n   * @param tag_i: id of the tag emitting the signal\n   */\n  double getTotalEntropyEllipse(grid_map::EllipseIterator iterator,\n                                int tag_i);\n\n  void printEllipse(double x, double y, double orient_rad, double maxX, double minX);\n\n  void addTmpMeasurementRFIDCriterion(double x, double y, double orientation,\n                                      double rxPower, double phase, double freq,\n                                      int i, double len_update);\n  Eigen::MatrixXf getPowProbCondRFIDCriterion(double rxPw, double f_i);\n  Eigen::MatrixXf getNegProbRFIDCriterion(double sensitivity, double sigm);\n  void createTempProbLayerRFIDCriterion(Eigen::MatrixXf prob_mat, double x_m,\n                                        double y_m, double orientation_deg,\n                                        double len_update);\n  grid_map::Polygon getSubMapEdges(double robot_x, double robot_y,\n                                   double robot_head, double len);\n  // Position getSubMapRelPoint(Position glob_point, double x_m, double  y_m,\n  // double orientation_rad, double len);\n\n  template <typename Scalar>\n  void 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\n  template <typename Scalar>\n  void 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\n  void addLossesTillEdgeLine(grid_map::Index edge_index_start,\n                             grid_map::Index edge_index_end,\n                             grid_map::Index antenna_index);\n  bool useFast = true;\n  Eigen::MatrixXf getFriisMatSlow(double x_m, double y_m,\n                                  double orientation_deg, double freq, double txtPower);\n  Eigen::MatrixXf getPhaseProbCond(double ph_i, double x_m, double y_m,\n                                   double orientation_deg, double f_i);\n  Eigen::MatrixXf getPowProbCond(double rxPw, double x_m, double y_m,\n                                 double orientation_deg, double f_i, double txtPower);\n\n  void PrintRecPower(std::string fileURI, double x_m, double y_m,\n                     double orientation_deg, double f_i, double txtPower);\n  void PrintPhase(std::string fileURI, double x_m, double y_m,\n                  double orientation_deg, double f_i);\n  void PrintPowProb(std::string fileURI, double rxPw, double x_m, double y_m,\n                    double orientation_deg, double f_i, double txtPower);\n  void PrintPhaseProb(std::string fileURI, double phi, double x_m, double y_m,\n                      double orientation_deg, double f_i);\n  void PrintBothProb(std::string fileURI, double rxPw, double phi, double x_m,\n                     double y_m, double orientation_deg, double f_i, double txtPower);\n  cv::Mat layerToImage(GridMap *gm, std::string layerName);\n\n  Eigen::MatrixXf getFakeMeasurement(double x_m, double y_m, double orientation_deg,\n                                double rxPower, double phase, double freq,\n                                double txtPower);\n}; // end class\n\n#endif", "meta": {"hexsha": "6dd9df4eaee75711895806ba23ae6cb2cbff7b1b", "size": 20837, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rfid_grid_map/include/RadarModelROS.hpp", "max_stars_repo_name": "LCAS/RFID", "max_stars_repo_head_hexsha": "4841d03a97cbd41ddeab5b40cddc06a3d05d32b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rfid_grid_map/include/RadarModelROS.hpp", "max_issues_repo_name": "LCAS/RFID", "max_issues_repo_head_hexsha": "4841d03a97cbd41ddeab5b40cddc06a3d05d32b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rfid_grid_map/include/RadarModelROS.hpp", "max_forks_repo_name": "LCAS/RFID", "max_forks_repo_head_hexsha": "4841d03a97cbd41ddeab5b40cddc06a3d05d32b9", "max_forks_repo_licenses": ["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.3150943396, "max_line_length": 158, "alphanum_fraction": 0.6475020396, "num_tokens": 5276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5887406978908933}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/box/center.hpp>\n#include <fcppt/math/box/comparison.hpp>\n#include <fcppt/math/box/object_impl.hpp>\n#include <fcppt/math/vector/comparison.hpp>\n#include <fcppt/math/vector/output.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tbox_center\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef fcppt::math::box::object<\n\t\tint,\n\t\t3\n\t> box_type;\n\n\tbox_type const b(\n\t\tbox_type::vector(10,12,14),\n\t\tbox_type::dim(24,26,4)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::box::center(\n\t\t\tb\n\t\t),\n\t\tbox_type::vector(22,25,16)\n\t);\n}\n", "meta": {"hexsha": "bad891557515ee5a61093094765ff0a96ee5f446", "size": 1049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/box/center.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/box/center.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/box/center.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8043478261, "max_line_length": 61, "alphanum_fraction": 0.7378455672, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5887406951878243}}
{"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": "/**\n * @file nystroem_method_test.cpp\n * @author Ryan Curtin\n *\n * Test the NystroemMethod class and ensure that the reconstructed kernel matrix\n * errors are comparable with those in the literature.\n */\n#include <mlpack/core.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\n#include <mlpack/methods/nystroem_method/ordered_selection.hpp>\n#include <mlpack/methods/nystroem_method/random_selection.hpp>\n#include <mlpack/methods/nystroem_method/kmeans_selection.hpp>\n#include <mlpack/methods/nystroem_method/nystroem_method.hpp>\n\nusing namespace mlpack;\nusing namespace mlpack::kernel;\n\nBOOST_AUTO_TEST_SUITE(NystroemMethodTest);\n\n/**\n * Make sure that if the rank is the same and we do a full-rank approximation,\n * the result is virtually identical (a little bit of tolerance for floating\n * point error).\n */\nBOOST_AUTO_TEST_CASE(FullRankTest)\n{\n  // Run several trials.\n  for (size_t trial = 0; trial < 5; ++trial)\n  {\n    arma::mat data;\n    data.randu(5, trial * 200);\n\n    GaussianKernel gk;\n    NystroemMethod<GaussianKernel, OrderedSelection> nm(data, gk, trial * 200);\n\n    arma::mat g;\n    nm.Apply(g);\n\n    // Construct exact kernel matrix.\n    arma::mat kernel(trial * 200, trial * 200);\n    for (size_t i = 0; i < trial * 200; ++i)\n      for (size_t j = 0; j < trial * 200; ++j)\n        kernel(i, j) = gk.Evaluate(data.col(i), data.col(j));\n\n    // Reconstruct approximation.\n    arma::mat approximation = g * g.t();\n\n    // Check closeness.\n    for (size_t i = 0; i < trial * 200; ++i)\n    {\n      for (size_t j = 0; j < trial * 200; ++j)\n      {\n        if (kernel(i, j) < 1e-5)\n          BOOST_REQUIRE_SMALL(approximation(i, j), 1e-4);\n        else\n          BOOST_REQUIRE_CLOSE(kernel(i, j), approximation(i, j), 1e-5);\n      }\n    }\n  }\n}\n\n/**\n * Can we accurately represent a rank-10 matrix?\n */\nBOOST_AUTO_TEST_CASE(Rank10Test)\n{\n  arma::mat data;\n  data.randu(500, 500); // Just so it's square.\n\n  // Use SVD and only keep the first ten singular vectors.\n  arma::mat U;\n  arma::vec s;\n  arma::mat V;\n  arma::svd(U, s, V, data);\n\n  // Don't set completely to 0; the hope is that K is still positive definite.\n  s.subvec(0, 9) += 1.0; // Make sure the first 10 singular vectors are large.\n  s.subvec(10, s.n_elem - 1).fill(1e-6);\n  arma::mat dataMod = U * arma::diagmat(s) * V.t();\n\n  // Add some noise.\n  dataMod += 1e-5 * arma::randu<arma::mat>(dataMod.n_rows, dataMod.n_cols);\n\n  // Calculate the true kernel matrix.\n  LinearKernel lk;\n  arma::mat kernel = dataMod.t() * dataMod;\n\n  // Now use the linear kernel to get a Nystroem approximation; try this several\n  // times.\n  double normalizedFroAverage = 0.0;\n  for (size_t trial = 0; trial < 20; ++trial)\n  {\n    LinearKernel lk;\n    NystroemMethod<LinearKernel, RandomSelection> nm(dataMod, lk, 10);\n\n    arma::mat g;\n    nm.Apply(g);\n\n    arma::mat approximation = g * g.t();\n\n    // Check the normalized Frobenius norm.\n    const double normalizedFro = arma::norm(kernel - approximation, \"fro\") /\n        arma::norm(kernel, \"fro\");\n\n    normalizedFroAverage += normalizedFro;\n  }\n\n  normalizedFroAverage /= 20;\n  BOOST_REQUIRE_SMALL(normalizedFroAverage, 1e-3);\n}\n\n/**\n * Can we reproduce the results in Zhang, Tsang, and Kwok (2008)?\n * They provide the following test points (approximately) in their experiments\n * in Section 4.1, for the german dataset:\n *\n *  rank = 0.02n; approximation error: ~27\n *  rank = 0.04n; approximation error: ~15\n *  rank = 0.06n; approximation error: ~10\n *  rank = 0.08n; approximation error: ~7\n *  rank = 0.10n; approximation error: ~3\n */\nBOOST_AUTO_TEST_CASE(GermanTest)\n{\n  // Load the dataset.\n  arma::mat dataset;\n  data::Load(\"german.csv\", dataset, true);\n\n  // These are our tolerance bounds.\n  double results[5] = { 32.0, 20.0, 15.0, 12.0, 9.0 };\n\n  // The bandwidth of the kernel is selected to be the half the average\n  // distance between each point and the mean of the dataset.  This isn't\n  // _exactly_ what the paper says, but I've modified what it said because our\n  // formulation of what the Gaussian kernel is is different.\n  GaussianKernel gk(16.461);\n\n  // Calculate the true kernel matrix.\n  arma::mat kernel(dataset.n_cols, dataset.n_cols);\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    for (size_t j = 0; j < dataset.n_cols; ++j)\n      kernel(i, j) = gk.Evaluate(dataset.col(i), dataset.col(j));\n\n  for (size_t trial = 0; trial < 5; ++trial)\n  {\n    // We will repeat each trial 20 times.\n    double avgError = 0.0;\n    for (size_t z = 0; z < 20; ++z)\n    {\n      NystroemMethod<GaussianKernel, KMeansSelection<> > nm(dataset, gk,\n          size_t((double((trial + 1) * 2) / 100.0) * dataset.n_cols));\n      arma::mat g;\n      nm.Apply(g);\n\n      // Reconstruct kernel matrix.\n      arma::mat approximation = g * g.t();\n\n      const double error = arma::norm(kernel - approximation, \"fro\");\n      if (error != error)\n      {\n        // Sometimes K' is singular.  Unlucky.\n        --z;\n        continue;\n      }\n      else\n      {\n        Log::Debug << \"Trial \" << trial << \": error \" << error << \".\\n\";\n        avgError += arma::norm(kernel - approximation, \"fro\");\n      }\n    }\n\n    avgError /= 20;\n\n    // Ensure that this is within tolerance, which is at least as good as the\n    // paper's results (plus a little bit for noise).\n    BOOST_REQUIRE_SMALL(avgError, results[trial]);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "241d9716b58fd29cf2f90195a42027de21647a8b", "size": 5382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/nystroem_method_test.cpp", "max_stars_repo_name": "jmlevin7878/mlpack2", "max_stars_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:16.000Z", "max_issues_repo_path": "src/mlpack/tests/nystroem_method_test.cpp", "max_issues_repo_name": "jmlevin7878/mlpack2", "max_issues_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/nystroem_method_test.cpp", "max_forks_repo_name": "jmlevin7878/mlpack2", "max_forks_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.25, "max_line_length": 80, "alphanum_fraction": 0.6452991453, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5887257205867379}}
{"text": "//------------------------------------------------------------------------------\n/// \\file ContinuationMonad_tests.cpp\n/// \\author Ernest Yeung\n//------------------------------------------------------------------------------\n//#include \"Categories/Monads/ContinuationMonad.h\"\n\n#define BOOST_THREAD_PROVIDES_FUTURE\n#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION\n\n#include \"Categories/Monads/ContinuationMonad.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n#include <future>\n#include <optional>\n#include <string>\n#include <utility>\n\nusing Categories::Monads::ContinuationMonad::AsLambdas::eval;\nusing Categories::Monads::ContinuationMonad::AsLambdas::return_;\nusing Categories::Monads::ContinuationMonad::AsLambdas::runContinuation;\nusing Categories::Monads::ContinuationMonad::apply_endomorphism;\nusing Categories::Monads::ContinuationMonad::evaluate;\nusing Categories::Monads::ContinuationMonad::unit;\n\nusing namespace Categories::Monads::ContinuationMonad;\n\nBOOST_AUTO_TEST_SUITE(Categories)\nBOOST_AUTO_TEST_SUITE(Monads)\nBOOST_AUTO_TEST_SUITE(ContinuationMonad_tests)\n\n// Test morphisms.\n\nstd::optional<std::string> user_full_name(const std::string name)\n{\n  if (name.empty() || name == \"None\")\n  {\n    return {};\n  }\n  else\n  {\n    return std::make_optional(\"Username: \" + name);\n  }\n}\n\nstd::optional<std::string> to_html(const std::string name)\n{\n  if (name.empty() || name == \"NA\")\n  {\n    return {};\n  }\n  else\n  {\n    return std::make_optional(\"http://\" + name);\n  }\n}\n\nstd::pair<bool, std::string> h(const std::optional<std::string> text)\n{\n  if (!text)\n  {\n    return std::make_pair(false, \"\");\n  }\n  if (text.value() == \"What you want.\")\n  {\n    return std::make_pair(true, text.value());\n  }\n  else\n  {\n    return std::make_pair(false, text.value());\n  }\n}\n\ntemplate <int Divisor>\nstd::pair<bool, int> integer_division(const int input)\n{\n  if (Divisor == 0)\n  {\n    return std::make_pair(false, input);\n  }\n  else\n  {\n    return std::make_pair(true, input / Divisor);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE(Endomorphisms)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ApplyEndomorphismAppliesInternalHomToInput)\n{\n  {\n    const auto result = apply_endomorphism(user_full_name, \"Sainte-Foy\");\n    BOOST_TEST(result.value() == \"Username: Sainte-Foy\");\n  }\n  {\n    const auto result = apply_endomorphism(to_html, \"Sainte-Foy\");\n    BOOST_TEST(result.value() == \"http://Sainte-Foy\");\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(RunContinuationAppliesInternalHomToInput)\n{\n  {\n    const auto result = runContinuation(user_full_name, \"Sainte-Foy\");\n    BOOST_TEST(result.value() == \"Username: Sainte-Foy\");\n  }\n  {\n    const auto result = runContinuation(to_html, \"Sainte-Foy\");\n    BOOST_TEST(result.value() == \"http://Sainte-Foy\");\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Endomorphisms\n\nBOOST_AUTO_TEST_SUITE(Return)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(TestMorphismsWork)\n{\n  {\n    auto result = user_full_name(\"Sainte-Foy\");\n    BOOST_TEST(result.value() == \"Username: Sainte-Foy\");\n  }\n  {\n    const auto result1 = integer_division<2>(5);\n    BOOST_TEST(result1.first);\n    BOOST_TEST(result1.second == 2);    \n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ReturnReturnsEndomorphismObject)\n{\n  auto returned_unit = return_(\"Sainte-Foy\");\n  {\n    const auto result = returned_unit(user_full_name);\n    BOOST_TEST(result.value() == \"Username: Sainte-Foy\");\n  }\n  {\n    const auto result = returned_unit(to_html);\n    BOOST_TEST(result.value() == \"http://Sainte-Foy\");\n  }\n  auto returned_unit1 = return_(10);\n  {\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Return\n\n// cf. https://github.com/dbrattli/OSlash/blob/master/tests/test_cont.py\n\nBOOST_AUTO_TEST_SUITE(UnitComponent)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(\n  UnitComponentReturnsInternalHomMappingInternalHomToReturnType)\n{\n  auto returned_endomorphism = unit<std::string>(\"Helene Desportes\");\n  {\n    const auto result = returned_endomorphism(user_full_name);\n    BOOST_TEST(result.value() == \"Username: Helene Desportes\");\n  }\n  {\n    const auto result = returned_endomorphism(to_html);\n    BOOST_TEST(result.value() == \"http://Helene Desportes\");\n  }\n}\n\n// cf. https://github.com/dbrattli/OSlash/blob/master/tests/test_cont.py\n// The following reproduces the unit tests in the referenced link.\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(UnitComponentDelaysComputation)\n{\n  auto test_internal_hom = [](const int value)\n  {\n    return std::to_string(value);\n  };\n  {\n    auto addition = [](const auto x, const auto y)\n    {\n      return unit(x + y);\n    };\n    auto square = [](const auto x)\n    {\n      return unit(x * x);\n    };\n    // Results is of type [[X, Y], Y]\n    auto delay_addition = addition(25, 9);\n    auto delay_square = square(5);\n\n    const auto addition_result = delay_addition(test_internal_hom);\n    const auto square_result = delay_square(test_internal_hom);\n\n    BOOST_TEST_REQUIRE(addition_result == \"34\");\n    BOOST_TEST_REQUIRE(square_result == \"25\");\n    BOOST_TEST(addition(25, 9)(evaluate<int>) == 34);\n    {\n      auto create_add_x = [](const int x)\n      {\n        return [x](const auto y)\n        {\n          return (x + y);\n        };\n      };\n      auto add_6 = create_add_x(6);\n      auto add_7 = create_add_x(7);\n\n      BOOST_TEST(delay_square(add_6) == 31);\n      BOOST_TEST(delay_square(add_7) == 32);\n      BOOST_TEST(square(5)(add_6) == 31);\n      BOOST_TEST(square(5)(add_7) == 32);\n\n      auto intermediate = square(5)(\n        [addition](const int xx)\n        {\n          return addition(xx, 8);\n        });\n\n      BOOST_TEST_REQUIRE(intermediate(evaluate<int>) == 33);\n\n      auto intermediate_f = [square, addition](const int x, const int y)\n      {\n        return square(x)(\n          [addition, y](const int xx)\n          {\n            return addition(xx, y);\n          });\n      };\n\n      auto intermediate_f_result = intermediate_f(3, 6)(evaluate<int>);\n      BOOST_TEST(intermediate_f_result == 15);\n\n      auto pythagoras_formula = [addition, square](const int x, const int y)\n      {\n        return square(x)(\n          [addition, square, y](const int xx)\n          {\n            return square(y)(\n              [addition, xx](const int yy)\n              {\n                return addition(xx, yy);\n              });\n          });\n      };\n      BOOST_TEST(pythagoras_formula(5, 6)(evaluate<int>) == 61);\n      BOOST_TEST(pythagoras_formula(4, 4)(evaluate<int>) == 32);\n    }\n  }\n  {\n    auto addition = [](const auto x, const auto y)\n    {\n      return return_(x + y);\n    };\n    auto square = [](const auto x)\n    {\n      return return_(x * x);\n    };\n    auto delay_addition = addition(25, 9);\n    auto delay_square = square(5);\n\n    const auto addition_result = delay_addition(test_internal_hom);\n    const auto square_result = delay_square(test_internal_hom);\n\n    BOOST_TEST_REQUIRE(addition_result == \"34\");\n    BOOST_TEST_REQUIRE(square_result == \"25\");\n\n    {\n      auto pythagoras_formula = [addition, square](const int x, const int y)\n      {\n        return square(x)(\n          [addition, square, y](const int xx)\n          {\n            return square(y)(\n              [addition, xx](const int yy)\n              {\n                return addition(xx, yy);\n              });\n          });\n      };\n      BOOST_TEST(pythagoras_formula(5, 6)(evaluate<int>) == 61);\n      BOOST_TEST(pythagoras_formula(4, 4)(evaluate<int>) == 32);\n    }\n  }\n}\n\nint pair_add(const std::pair<int, int> inputs)\n{\n  return inputs.first + inputs.second;\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(UnitComponentTreatsFunctionsAsFirstClassValues)\n{\n  {\n    auto pair_addition = unit(pair_add);\n    BOOST_TEST_REQUIRE(pair_addition(eval)(std::make_pair<int, int>(40, 2)));\n    BOOST_TEST(unit(pair_add)(eval)(std::make_pair<int, int>(40, 2)));\n  }\n  {\n    auto pair_addition = return_(pair_add);\n    BOOST_TEST_REQUIRE(pair_addition(eval)(std::make_pair<int, int>(40, 2)));\n    BOOST_TEST(return_(pair_add)(eval)(std::make_pair<int, int>(40, 2)));    \n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SimpleUnitComponentExamples)\n{\n  auto morphism_c = [](const auto x) -> std::string\n  {\n    return \"Done: \" + std::to_string(x);\n  };\n  {\n    auto f = [](const auto x)\n    {\n      return unit(std::pow(x, 3));\n    };\n    auto g = [](const auto x)\n    {\n      return unit(x - 2);\n    };\n    auto h = [f, g](const auto x)\n    {\n      return (x == 5) ? f(x) : g(x);\n    };\n    auto do_c = unit(4.0)(h);\n    BOOST_TEST_REQUIRE(do_c(evaluate<float>) == 2.0);\n    BOOST_TEST(do_c(morphism_c) == \"Done: 2.000000\");\n  }\n  {\n    auto f = [](const auto x)\n    {\n      return return_(std::pow(x, 3));\n    };\n    auto g = [](const auto x)\n    {\n      return return_(x - 2);\n    };\n    auto h = [f, g](const auto x)\n    {\n      return (x == 5) ? f(x) : g(x);\n    };\n    auto do_c = return_(4.0)(h);\n    BOOST_TEST_REQUIRE(do_c(evaluate<float>) == 2.0);\n    BOOST_TEST(do_c(morphism_c) == \"Done: 2.000000\");\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // UnitComponent\n\nBOOST_AUTO_TEST_SUITE(Bind)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(BindAsLambdas)\n{\n  auto composed_fg = AsLambdas::bind(to_html, user_full_name);\n//  composed_fg(h);\n\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Bind\n\n\nBOOST_AUTO_TEST_SUITE_END() // ContinuationMonad_tests\nBOOST_AUTO_TEST_SUITE_END() // Monads\nBOOST_AUTO_TEST_SUITE_END() // Categories", "meta": {"hexsha": "76ef7d2767e8375b1cbbce063b19c19437f41a2a", "size": 10575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Categories/Monads/ContinuationMonad_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Categories/Monads/ContinuationMonad_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Categories/Monads/ContinuationMonad_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9761904762, "max_line_length": 80, "alphanum_fraction": 0.5422222222, "num_tokens": 2396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.5887257153221085}}
{"text": "#pragma once\n#include \"Optimizer.hpp\"\n\n#include <Eigen/Dense>\n#include <array>\n#include <cmath>\n#include <nlohmann/json.hpp>\n\nnamespace yavque\n{\nclass SGD : public Optimizer\n{\npublic:\n\tstatic constexpr std::array<double, 3> DEFAULT_PARAMS = {0.01, 0.0, 1e-4};\n\nprivate:\n\tconst double alpha_;\n\tconst double p_;\n\tconst double min_alpha_;\n\tint t_ = 0;\n\npublic:\n\texplicit SGD(double alpha = DEFAULT_PARAMS[0], double p = DEFAULT_PARAMS[1],\n\t             double min_alpha = DEFAULT_PARAMS[2])\n\t\t: alpha_{alpha}, p_{p}, min_alpha_{min_alpha}\n\t{\n\t}\n\n\texplicit SGD(const nlohmann::json& params)\n\t\t: alpha_{params.value(\"alpha\", DEFAULT_PARAMS[0])}, p_{params.value(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"p\", DEFAULT_PARAMS[1])},\n\t\t  min_alpha_{params.value(\"min_alpha\", DEFAULT_PARAMS[2])}\n\t{\n\t}\n\n\t[[nodiscard]] nlohmann::json desc() const override\n\t{\n\t\treturn nlohmann::json{{\"name\", \"SGD\"},\n\t\t                      {\"alhpa\", alpha_},\n\t\t                      {\"p\", p_},\n\t\t                      {\"min_alpha\", min_alpha_}};\n\t}\n\n\tEigen::VectorXd getUpdate(const Eigen::VectorXd& v) override\n\t{\n\t\tusing std::pow;\n\t\t++t_;\n\t\tdouble eta = std::max((alpha_ / pow(t_, p_)), min_alpha_);\n\t\treturn -eta * v;\n\t}\n};\n} // namespace yavque\n", "meta": {"hexsha": "3693557c5821fd4f124fa81b5b47b862af48680d", "size": 1197, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/yavque/Optimizers/SGD.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/SGD.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/SGD.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": 22.5849056604, "max_line_length": 77, "alphanum_fraction": 0.6232247285, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5886503167008128}}
{"text": "/*\n * Copyright 2016 Erik Crevel\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"ArithmeticEncoder.hpp\"\n#include \"ArithmeticDecoder.hpp\"\n\n#include \"catch.hpp\"\n\n#include <random>\n#include <boost/iostreams/stream.hpp>\n\n#include \"UniformEncodingDistribution.hpp\"\n#include \"NormalEncodingDistribution.hpp\"\n#include \"LaplaceEncodingDistribution.hpp\"\n\n\n// This tests the boundries between values\nvoid testDistribution(EncodingDistribution& _encodeDist, std::pair<int, int> _encodeRange)\n{\n\tfor(int v = _encodeRange.first; v < _encodeRange.second; ++v)\n\t{\n\t\tstd::pair<ArithmeticEncoder::Range, ArithmeticEncoder::Range>\n\t\t\trange = _encodeDist.getRange(v);\n\n\t\tstd::pair<int, std::pair<ArithmeticEncoder::Range, ArithmeticEncoder::Range>>\n\t\t\tv2_ = _encodeDist.getValue(range.first);\n\n\t\tif(range.second - range.first > 0)\n\t\t{\n\t\t\tCHECK( v == (int)v2_.first );\n\t\t\tCHECK( range.first == v2_.second.first );\n\t\t\tCHECK( range.second == v2_.second.second );\n\n\t\t\tv2_ = _encodeDist.getValue(range.second-1);\n\n\t\t\tCHECK( v == (int)v2_.first );\n\t\t\tCHECK( range.first == v2_.second.first );\n\t\t\tCHECK( range.second == v2_.second.second );\n\t\t}\n\t}\n}\n\nvoid testEncoding(int _seed)\n{\n\tstd::default_random_engine generator;\n\tgenerator.seed(_seed);\n\tstd::uniform_int_distribution<int> distribution(0,255);\n\n\tNormalEncodingDistribution encodeDist({0, 256}, distribution(generator), distribution(generator)+100);\n\n\ttestDistribution(encodeDist, {0, 256});\n\n\tstd::vector<char> encodedData(1000);\n\n\tboost::iostreams::stream<boost::iostreams::basic_array_sink<char>>\n\t\toutDataStream(encodedData.data(),encodedData.size());\n\tauto streamStart = outDataStream.tellp();\n\n\tArithmeticEncoder encoder(outDataStream);\n\n\tstd::vector<unsigned char> values(100);\n\tfor(auto& v : values)\n\t\tv = distribution(generator);\n\n\tfor(auto v : values)\n\t\tencodeDist.encode(encoder, v);\n\tencoder.close();\n\n\tstd::size_t writeSize = outDataStream.tellp() - streamStart;\n\n\toutDataStream.close();\n\n\tboost::iostreams::stream<boost::iostreams::basic_array_source<char>>\n\t\tinDataStream(encodedData.data(),encodedData.size());\n\tstreamStart = inDataStream.tellg();\n\n\tArithmeticDecoder decoder(inDataStream);\n\tdecoder.open();\n\n\tfor(auto& v : values)\n\t{\n\t\tunsigned char decodedV = encodeDist.decode(decoder);\n\n\t\tREQUIRE( static_cast<int>(decodedV) == static_cast<int>(v) );\n\t}\n\n\tstd::size_t readSize = inDataStream.tellg() - streamStart;\n\tREQUIRE( readSize == writeSize );\n}\n\nTEST_CASE( \"Test normal distribution\", \"[normal_distribution]\" )\n{\n\tstd::pair<int, int> encodeRange{0, 256};\n\n\tNormalEncodingDistribution encodeDist(encodeRange, 100, 100);\n\n\ttestDistribution(encodeDist, encodeRange);\n}\n\nTEST_CASE( \"Test laplace distribution\", \"[laplace_distribution]\" )\n{\n\tstd::pair<int, int> encodeRange{0, 256};\n\n\tLaplaceEncodingDistribution encodeDist(encodeRange, 70.239466369334451, 1.2228440911461289);\n\n\ttestDistribution(encodeDist, encodeRange);\n}\n\nTEST_CASE( \"Test arithmetic encoding and decoding\", \"[arithmetic_encoding_decoding]\" )\n{\n\tfor(int seed = 0; seed < 1000; ++seed)\n\t\ttestEncoding(seed);\n}\n", "meta": {"hexsha": "d13e7f07f167ed7fd4614e80f157ad9421a542e5", "size": 3556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_ArithmeticEncoder.cpp", "max_stars_repo_name": "nimble0/rsic", "max_stars_repo_head_hexsha": "e94f2e226fa68e7495c7423f1845b01edff6b2fe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_ArithmeticEncoder.cpp", "max_issues_repo_name": "nimble0/rsic", "max_issues_repo_head_hexsha": "e94f2e226fa68e7495c7423f1845b01edff6b2fe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_ArithmeticEncoder.cpp", "max_forks_repo_name": "nimble0/rsic", "max_forks_repo_head_hexsha": "e94f2e226fa68e7495c7423f1845b01edff6b2fe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 103, "alphanum_fraction": 0.7387514061, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5886503164270852}}
{"text": "#include \"benchmarks_general.h\"\nusing benchmarks_general::println;\nusing benchmarks_general::rtimeit;\nusing benchmarks_general::unused;\n\n#include <Eigen/Core>\n\ntemplate<typename T, size_t M, size_t K, size_t N>\nT single_test() {\n    using namespace Eigen;\n    Matrix<T,M,K,RowMajor> a; a.setConstant(3);\n    Matrix<T,K,N,RowMajor> b; b.setConstant(4);\n    Matrix<T,M,N,RowMajor> c = a*b;\n\n    Matrix<T,M,N,RowMajor> tmp; tmp.setConstant(0);\n    benchmarks_general::matmul_ref<M,K,N>(a,b,tmp);\n    return std::abs(tmp.array().sum() - c.array().sum());\n}\n\ntemplate<typename T, size_t M, size_t K, size_t N>\nvoid run_single_test() {\n    T value = single_test<T,M,K,N>();\n    benchmarks_general::EXIT_ASSERT(std::abs(value) < 1e-10, \"TEST FAILED\");\n}\n\ntemplate<typename T>\nvoid run_tests() {\n    TEST_RUN_MATMUL_BENCHMARK(run_single_test, T)\n}\n\n\ntemplate<typename T, size_t M, size_t K, size_t N>\nvoid single_benchmark() {\n    using namespace Eigen;\n    Matrix<T,M,K,RowMajor> a; a.setConstant(3);\n    Matrix<T,K,N,RowMajor> b; b.setConstant(4);\n    Matrix<T,M,N,RowMajor> c = a*b;\n    unused(c);\n}\n\ntemplate<typename T, size_t M, size_t K, size_t N>\nvoid run_single_benchmark() {\n\n    double elapsed_time = rtimeit(static_cast<void (*)()>(&single_benchmark<T,M,K,N>));\n    double max_gflops = 2.0 * M * N * K / (elapsed_time * 1.0e9);\n    println(\"(M, N, K):\", M, N, K, \"GFLOPS:\", max_gflops, \"minimum runtime:\", elapsed_time,'\\n');\n}\n\n\ntemplate<typename T>\nvoid run_benchmarks() {\n    TEST_RUN_MATMUL_BENCHMARK(run_single_benchmark, T)\n}\n\n\n\n\n\n\nint main() {\n\n#ifdef RUN_SINGLE\n    println(\"Running eigen benchmark: single precision\\n\");\n    run_tests<float>();\n    run_benchmarks<float>();\n#else\n    println(\"Running eigen benchmark: double precision\\n\");\n    run_tests<double>();\n    run_benchmarks<double>();\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "ddd654ab5e12a525929e34bc989079d964c700f7", "size": 1832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/external/benchmark_matmul/benchmark_eigen.cpp", "max_stars_repo_name": "mablanchard/Fastor", "max_stars_repo_head_hexsha": "f5ca2f608bdfee34833d5008a93a3f82ce42ddef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 424.0, "max_stars_repo_stars_event_min_datetime": "2017-05-15T14:34:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:58:22.000Z", "max_issues_repo_path": "benchmark/external/benchmark_matmul/benchmark_eigen.cpp", "max_issues_repo_name": "manodeep/Fastor", "max_issues_repo_head_hexsha": "aefce47955dd118f04e7b36bf5dbb2d86997ff8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 150.0, "max_issues_repo_issues_event_min_datetime": "2016-12-23T10:08:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T03:53:45.000Z", "max_forks_repo_path": "benchmark/external/benchmark_matmul/benchmark_eigen.cpp", "max_forks_repo_name": "manodeep/Fastor", "max_forks_repo_head_hexsha": "aefce47955dd118f04e7b36bf5dbb2d86997ff8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2017-09-20T19:47:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T21:12:49.000Z", "avg_line_length": 24.7567567568, "max_line_length": 97, "alphanum_fraction": 0.6790393013, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5886503106036055}}
{"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            \u0420\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u043f\u043e\u0440\u044f\u0434\u043a\u043e\u0432\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u0432\u044b\u0431\u043e\u0440\u043a\u0438 \u0438\u0437 \u0441\u0442\u0430\u043d\u0434\u0430\u0440\u0442\u043d\u043e\u0433\u043e \u043d\u0435\u043f\u0440\u0435\u0440\u044b\u0432\u043d\u043e\u0433\u043e \u0440\u0430\u0432\u043d\u043e\u043c\u0435\u0440\u043d\u043e\u0433\u043e\n            \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f.\n\n        \\details\n            \"urd\" \u043e\u0437\u043d\u0430\u0447\u0430\u0435\u0442 \"uniform random distribution\".\n            https://ru.wikipedia.org/wiki/\u041f\u043e\u0440\u044f\u0434\u043a\u043e\u0432\u0430\u044f_\u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0430#\u041f\u0440\u0438\u043c\u0435\u0440\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                \u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u0441 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0430\u043c\u0438\n\n            \\param n\n                \u0420\u0430\u0437\u043c\u0435\u0440 \u0432\u044b\u0431\u043e\u0440\u043a\u0438.\n            \\param k\n                \u041d\u043e\u043c\u0435\u0440 \u043f\u043e\u0440\u044f\u0434\u043a\u043e\u0432\u043e\u0439 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0438.\n            \\param a\n                \u041c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0440\u0430\u0432\u043d\u043e\u043c\u0435\u0440\u043d\u043e\u0433\u043e \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f.\n            \\param b\n                \u041c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0440\u0430\u0432\u043d\u043e\u043c\u0435\u0440\u043d\u043e\u0433\u043e \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f.\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": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Barycentric_coordinates_2/Mean_value_coordinates_2.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n\ntemplate<typename Kernel>\nvoid test_mv_special_points() {\n\n  using FT      = typename Kernel::FT;\n  using Point_2 = typename Kernel::Point_2;\n\n  const std::vector<Point_2> vertices = {\n    Point_2(0, 0),\n    Point_2(1, 1),\n    Point_2(FT(7) / FT(4), FT(1) / FT(2)),\n    Point_2(FT(7) / FT(4), FT(5) / FT(2)),\n    Point_2(1, 2),\n    Point_2(0, 3),\n    Point_2(FT(1) / FT(2), FT(3) / FT(2))\n  };\n\n  const Point_2 queries[11] = {\n    Point_2(FT(1) + (FT(1) / FT(std::pow(10.0, 300.0))), FT(2) - (FT(1) / FT(std::pow(10.0, 300.0)))),\n    Point_2(FT(1) + (FT(1) / FT(std::pow(10.0, 300.0))), FT(1) + (FT(1) / FT(std::pow(10.0, 300.0)))),\n    Point_2(1, FT(3) / FT(2)),\n    Point_2(FT(5) / FT(4), FT(5) / FT(4)),\n    Point_2(FT(5) / FT(4), FT(7) / FT(4)),\n    Point_2(FT(3) / FT(2), FT(3) / FT(2)),\n\n    Point_2(FT(7) / FT(4) - (FT(1) / FT(std::pow(10.0, 300.0))), FT(7) / FT(4) - (FT(1) / FT(std::pow(10.0, 300.0)))),\n    Point_2(FT(7) / FT(4) - (FT(1) / FT(std::pow(10.0, 300.0))), FT(5) / FT(4) + (FT(1) / FT(std::pow(10.0, 300.0)))),\n\n    Point_2(FT(3) / FT(4) - (FT(1) / FT(std::pow(10.0, 300.0))), FT(3) / FT(4) + (FT(1) / FT(std::pow(10.0, 300.0)))),\n    Point_2(FT(3) / FT(4) - (FT(1) / FT(std::pow(10.0, 300.0))), FT(9) / FT(4) - (FT(1) / FT(std::pow(10.0, 300.0)))),\n    Point_2(FT(1) / FT(2) + (FT(1) / FT(std::pow(10.0, 300.0))), FT(3) / FT(2))\n  };\n\n  std::size_t count = 0;\n  const FT epsilon = FT(1) / FT(1000000000000000);\n\n  std::vector<FT> coordinates;\n  for (std::size_t i = 0; i < 11; ++i) {\n    CGAL::Barycentric_coordinates::mean_value_coordinates_2(\n      vertices, queries[i], std::back_inserter(coordinates));\n\n    assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 0])));\n    assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 0])));\n\n    assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 1])));\n    assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 1])));\n\n    assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 2])));\n    assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 2])));\n\n    assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 3])));\n    assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 3])));\n\n    assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 4])));\n    assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 4])));\n\n    assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 5])));\n    assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 5])));\n\n    assert(!boost::math::isnan(CGAL::to_double(coordinates[count + 6])));\n    assert(!boost::math::isinf(CGAL::to_double(coordinates[count + 6])));\n\n    const FT coordinate_sum =\n      coordinates[count + 0] +\n      coordinates[count + 1] +\n      coordinates[count + 2] +\n      coordinates[count + 3] +\n      coordinates[count + 4] +\n      coordinates[count + 5] +\n      coordinates[count + 6] ;\n    const Point_2 linear_combination(\n      vertices[0].x() * coordinates[count + 0] +\n      vertices[1].x() * coordinates[count + 1] +\n      vertices[2].x() * coordinates[count + 2] +\n      vertices[3].x() * coordinates[count + 3] +\n      vertices[4].x() * coordinates[count + 4] +\n      vertices[5].x() * coordinates[count + 5] +\n      vertices[6].x() * coordinates[count + 6] ,\n      vertices[0].y() * coordinates[count + 0] +\n      vertices[1].y() * coordinates[count + 1] +\n      vertices[2].y() * coordinates[count + 2] +\n      vertices[3].y() * coordinates[count + 3] +\n      vertices[4].y() * coordinates[count + 4] +\n      vertices[5].y() * coordinates[count + 5] +\n      vertices[6].y() * coordinates[count + 6] );\n    const Point_2 difference(\n      linear_combination.x() - queries[i].x(),\n      linear_combination.y() - queries[i].y());\n    assert(\n      CGAL::abs(coordinate_sum - FT(1)) < epsilon &&\n      CGAL::abs(difference.x()) < epsilon &&\n      CGAL::abs(difference.y()) < epsilon );\n    count += 7;\n  }\n}\n\nint main() {\n\n  test_mv_special_points< CGAL::Simple_cartesian<double> >();\n  test_mv_special_points< CGAL::Exact_predicates_inexact_constructions_kernel >();\n\n  std::cout << \"test_mv_special_points: PASSED\" << std::endl;\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "f47e49745e7f320fa29f9c076d293777fd6289c2", "size": 4419, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Barycentric_coordinates_2/test/Barycentric_coordinates_2/test_mv_special_points.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Barycentric_coordinates_2/test/Barycentric_coordinates_2/test_mv_special_points.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Barycentric_coordinates_2/test/Barycentric_coordinates_2/test_mv_special_points.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": 40.5412844037, "max_line_length": 118, "alphanum_fraction": 0.6005883684, "num_tokens": 1528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5886133572884541}}
{"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\"\u8bf4\u660e\uff1a\u672c\u8230\u81ea\u4e0a\u4e00\u6b21\u6240\u5728\u4f4d\u7f6e\u7684\u79fb\u52a8\u65b9\u5411 = \u4ece\u4e0a\u4e00\u4e2a\u89c2\u6d4b\u70b9\u6307\u5411\u5f53\u524d\u4f4d\u7f6e\u7684\u7edd\u5bf9\u65b9\u4f4d\uff0c\u53ef\u5728\u6d77\u56fe\u4e2d\u5bf9\u4e24\u4e2a\u89c2\u6d4b\u70b9\u8fde\u7ebf\u83b7\u5f97\u3002v0.3\u7248\u672c\u52a0\u5165\u8bef\u5dee\u5206\u5e03\u8ba1\u7b97\uff0c\u5bf9\u89c2\u6d4b\u5230\u7684\u65b9\u4f4d\u89d2\u65bd\u52a0-0.5\u52300.5\u5ea6\u8303\u56f4\u5185\u7684\u968f\u673a\u8bef\u5dee\uff0c\u5e76\u8fdb\u884c1000\u6b21\u5faa\u73af\u8ba1\u7b97\u8bef\u5dee\u5206\u5e03\u6982\u7387\u3002\" << endl;\r\n    std::wcout << endl;\r\n\r\n    std::wcout << L\"\u65f6\u95f4\u70b9time t1 = 0 (sec)\" << endl;\r\n\r\n    std::wcout << L\"\u672c\u8230\u822a\u5411 (deg): \";\r\n    std::cin >> own_ship_hdg;\r\n    std::wcout << endl;\r\n\r\n    std::wcout << L\"\u654c\u8230\u76f8\u5bf9\u65b9\u4f4d\u89d2 (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\"\u672c\u8230\u81ea\u4e0a\u4e00\u6b21\u6240\u5728\u4f4d\u7f6e\u7684\u79fb\u52a8\u65b9\u5411 = 0 (deg)\" << endl;\r\n    std::wcout << L\"\u672c\u8230\u8ddd\u4e0a\u4e00\u6b21\u6240\u5728\u4f4d\u7f6e\u7684\u76f4\u7ebf\u8ddd\u79bb = 0 (meter)\" << endl;\r\n\r\n    std::wcout << L\"*******************************\" << endl;\r\n\r\n    std::wcout << L\"\u65f6\u95f4\u70b9time t2 (sec): \";\r\n    std::cin >> recording_time[1];\r\n    std::wcout << endl;\r\n\r\n    std::wcout << L\"\u672c\u8230\u822a\u5411 (deg): \";\r\n    std::cin >> own_ship_hdg;\r\n    std::wcout << endl;\r\n\r\n    std::wcout << L\"\u654c\u8230\u76f8\u5bf9\u65b9\u4f4d\u89d2 (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\"\u672c\u8230\u81ea\u4e0a\u4e00\u6b21\u6240\u5728\u4f4d\u7f6e\u7684\u79fb\u52a8\u65b9\u5411 (deg): \";\r\n    std::cin >> last_travel_direction;\r\n    std::wcout << endl;\r\n\r\n    std::wcout << L\"\u672c\u8230\u8ddd\u4e0a\u4e00\u6b21\u6240\u5728\u4f4d\u7f6e\u7684\u76f4\u7ebf\u8ddd\u79bb (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\"\u65f6\u95f4\u70b9time t\" << j + 1 << L\" (sec): \";\r\n        std::cin >> recording_time[j];\r\n        std::wcout << endl;\r\n\r\n        std::wcout << L\"\u672c\u8230\u822a\u5411 (deg): \";\r\n        std::cin >> own_ship_hdg;\r\n        std::wcout << endl;\r\n\r\n        std::wcout << L\"\u654c\u8230\u76f8\u5bf9\u65b9\u4f4d\u89d2 (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\"\u672c\u8230\u81ea\u4e0a\u4e00\u6b21\u6240\u5728\u4f4d\u7f6e\u7684\u79fb\u52a8\u65b9\u5411 (deg): \";\r\n        std::cin >> last_travel_direction;\r\n        std::wcout << endl;\r\n\r\n        std::wcout << L\"\u672c\u8230\u8ddd\u4e0a\u4e00\u6b21\u6240\u5728\u4f4d\u7f6e\u7684\u76f4\u7ebf\u8ddd\u79bb (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\"\u654c\u8230\u822a\u5411target 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\"\u654c\u8230\u822a\u5411target true course: \" << starting_point(2) << L\"deg, \u901f\u5ea6speed: \" << optimize_spd * ms_to_kts << L\"knots, \u8ddd\u79bbdistance: \" << 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\"\u822a\u5411\u8bef\u5dee\u5206\u5e03\u4f4d\u4e8e5\u5ea6\u4ee5\u5185\u7684\u6982\u7387probability of target course error within 5deg: \" << error_prob_5deg << \" %\" << endl;\r\n            std::wcout << L\"\u822a\u5411\u8bef\u5dee\u5206\u5e03\u4f4d\u4e8e10\u5ea6\u4ee5\u5185\u7684\u6982\u7387probability of target course error within 10deg: \" << error_prob_10deg << \" %\" << endl;\r\n            std::wcout << L\"\u822a\u5411\u8bef\u5dee\u5206\u5e03\u4f4d\u4e8e20\u5ea6\u4ee5\u5185\u7684\u6982\u7387probability 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\"\u4f4d\u7f6e\u8bef\u5dee\u5206\u5e03\u4f4d\u4e8e75\u7c73\u4ee5\u5185\u7684\u6982\u7387probability of target positional error within 75m: \" << error_prob_75m << \" %\" << endl;\r\n                std::wcout << L\"\u4f4d\u7f6e\u8bef\u5dee\u5206\u5e03\u4f4d\u4e8e150\u7c73\u4ee5\u5185\u7684\u6982\u7387probability of target positional error within 150m: \" << error_prob_150m << \" %\" << endl;\r\n                std::wcout << L\"\u4f4d\u7f6e\u8bef\u5dee\u5206\u5e03\u4f4d\u4e8e300\u7c73\u4ee5\u5185\u7684\u6982\u7387probability of target positional error within 300m: \" << error_prob_300m << \" %\" << endl;\r\n                std::wcout << endl;\r\n                std::wcout << \"\u901f\u5ea6\u8bef\u5dee\u5206\u5e03\u4f4d\u4e8e0.5\u8282\u4ee5\u5185\u7684\u6982\u7387probability of target speed error within 0.5kts: \" << error_prob_05kts << \" %\" << endl;\r\n                std::wcout << \"\u901f\u5ea6\u8bef\u5dee\u5206\u5e03\u4f4d\u4e8e1\u8282\u4ee5\u5185\u7684\u6982\u7387probability of target speed error within 1kts: \" << error_prob_1kts << \" %\" << endl;\r\n                std::wcout << \"\u901f\u5ea6\u8bef\u5dee\u5206\u5e03\u4f4d\u4e8e2\u8282\u4ee5\u5185\u7684\u6982\u7387probability 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\"\u65e0\u89e3\uff01\" << 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": "/* test_exponential_distribution.cpp\n *\n * Copyright Steven Watanabe 2011\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * $Id$\n *\n */\n\n#include <boost/random/exponential_distribution.hpp>\n\n#include <limits>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::exponential_distribution<>\n#define BOOST_RANDOM_ARG1 lambda\n#define BOOST_RANDOM_ARG1_DEFAULT 1.0\n#define BOOST_RANDOM_ARG1_VALUE 7.5\n\n#define BOOST_RANDOM_DIST0_MIN 0\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\n#define BOOST_RANDOM_DIST1_MIN 0\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\n\n#define BOOST_RANDOM_TEST1_PARAMS\n#define BOOST_RANDOM_TEST1_MIN 0.0\n\n#define BOOST_RANDOM_TEST2_PARAMS (1000.0)\n#define BOOST_RANDOM_TEST2_MIN 0.0\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "169aab5faf3180f3bb19fb9131f5f9215190d1a3", "size": 901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_exponential_distribution.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/random/test/test_exponential_distribution.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/random/test/test_exponential_distribution.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 27.303030303, "max_line_length": 75, "alphanum_fraction": 0.8057713651, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.588606867754642}}
{"text": "/*\n * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE symmetric_matrix_test\n#include <boost/test/unit_test.hpp>\n#include <votca/xtp/symmetric_matrix.h>\n#include <iostream>\n\nusing namespace votca::xtp;\n\nBOOST_AUTO_TEST_SUITE(symmetric_matrix_test)\n\nBOOST_AUTO_TEST_CASE(Constructor_test) {\n  int dim=3;\nEigen::MatrixXd test=Eigen::MatrixXd::Random(dim,dim);\n Eigen::MatrixXd trans=test.transpose();\ntest+=trans;\nSymmetric_Matrix sym=Symmetric_Matrix(test);\n\n\nEigen::MatrixXd back=Eigen::MatrixXd::Zero(dim,dim);  \n\nsym.AddtoEigenMatrix(back);\n\nbool check_matrices=back.isApprox(test,0.000001);\nif(!check_matrices){\n   std::cout<<sym<<std::endl;\n  std::cout<<test<<std::endl;\n  std::cout<<back<<std::endl;\n}\nBOOST_CHECK_EQUAL(check_matrices, 1);\n}\n\nBOOST_AUTO_TEST_CASE(Add_test) {\n  \n   int dim=3;\nEigen::MatrixXd test=Eigen::MatrixXd::Random(dim,dim);\n Eigen::MatrixXd trans=test.transpose();\ntest+=trans;\nSymmetric_Matrix sym=Symmetric_Matrix(test);\n\nEigen::MatrixXd rand=Eigen::MatrixXd::Random(dim,dim);\n\nEigen::MatrixXd result=rand+2*test;\n\nsym.AddtoEigenMatrix(rand,2.0);\n\nbool check_matrices2=rand.isApprox(result,0.000001);\nif(!check_matrices2){\n  std::cout<<test<<std::endl;\n  std::cout<<sym<<std::endl;\n  std::cout<<rand<<std::endl;\n  std::cout<<result<<std::endl;\n}\nBOOST_CHECK_EQUAL(check_matrices2, 1);\n\n\n}\n\nBOOST_AUTO_TEST_CASE(FullMatrix_test) {\n  \nint dim=3;\nEigen::MatrixXd test=Eigen::MatrixXd::Random(dim,dim);\n Eigen::MatrixXd trans=test.transpose();\ntest+=trans;\nSymmetric_Matrix sym=Symmetric_Matrix(test);\nEigen::MatrixXd result=sym.FullMatrix();\nbool check_matrices=test.isApprox(result,0.000001);\n\nBOOST_CHECK_EQUAL(check_matrices, 1);\n}\n\n\nBOOST_AUTO_TEST_CASE(TraceofProd_test) {\n  \n   int dim=3;\nEigen::MatrixXd test=Eigen::MatrixXd::Random(dim,dim);\n Eigen::MatrixXd trans=test.transpose();\ntest+=trans;\nSymmetric_Matrix sym1=Symmetric_Matrix(test);\n\nEigen::MatrixXd test2=Eigen::MatrixXd::Random(dim,dim);\n Eigen::MatrixXd trans2=test2.transpose();\ntest2+=trans2;\nSymmetric_Matrix sym2=Symmetric_Matrix(test2);\n\ndouble ref=test2.cwiseProduct(test).sum();\ndouble result=sym1.TraceofProd(sym2);\n\nbool check=std::abs(ref-result)<1e-7;\nif(!check){\n  std::cout<<\"Ref: \"<<ref<<\" Sym: \"<<result<<std::endl;\n}\n\nBOOST_CHECK_EQUAL(check, 1);\n\n\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d1d56bfcc757298892c92520dcaf857874f131f1", "size": 2889, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_symmetric_matrix.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/test_symmetric_matrix.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_symmetric_matrix.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9051724138, "max_line_length": 75, "alphanum_fraction": 0.7507788162, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5885720295325227}}
{"text": "/* -------------------------------------------------------------------------\n *   A Modular Optimization framework for Localization and mApping  (MOLA)\n * Copyright (C) 2018-2021 University of Almeria\n * See LICENSE for license information.\n * ------------------------------------------------------------------------- */\n\n/**\n * @file   test-mp2p_error_terms_jacobians.cpp\n * @brief  Unit tests for Jacobians of error terms\n * @author Francisco Jose Ma\u00f1as Alvarez, Jose Luis Blanco Claraco\n * @date   Apr 10, 2020\n */\n\n#include <mp2p_icp/errorTerms.h>\n#include <mrpt/core/exceptions.h>\n#include <mrpt/math/num_jacobian.h>  // finite difference method\n#include <mrpt/poses/CPose3D.h>\n#include <mrpt/poses/Lie/SE.h>\n#include <mrpt/random.h>\n\n#include <Eigen/Dense>\n#include <iostream>  // cerr\n\nusing namespace mrpt;  // for the \"_deg\" suffix\nusing namespace mrpt::math;\nusing namespace mrpt::poses;\n\nauto& rnd = mrpt::random::getRandomGenerator();\n\nstatic double normald(const double sigma)\n{\n    return rnd.drawGaussian1D_normalized() * sigma;\n}\nstatic float normalf(const float sigma)\n{\n    return rnd.drawGaussian1D_normalized() * sigma;\n}\n\n// ===========================================================================\n//  Test: error_point2point\n// ===========================================================================\n\nstatic void test_Jacob_error_point2point()\n{\n    const CPose3D p = CPose3D(\n        // x y z\n        normald(10), normald(10), normald(10),\n        // Yaw pitch roll\n        rnd.drawUniform(-M_PI, M_PI), rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5),\n        rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5));\n\n    mrpt::tfest::TMatchingPair pair;\n    pair.global = {normalf(20), normalf(20), normalf(20)};\n    pair.local  = {normalf(20), normalf(20), normalf(20)};\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 3, 12> J1;\n    // const mrpt::math::CVectorFixed<double, 3> error = // (Ignored here)\n    mp2p_icp::error_point2point(pair, p, J1);\n\n    // (12x6 Jacobian)\n    const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);\n\n    const mrpt::math::CMatrixFixed<double, 3, 6> jacob(J1 * dDexpe_de);\n\n    // Numerical Jacobian:\n    CMatrixDouble numJacob;\n    {\n        CVectorFixedDouble<6> x_mean;\n        x_mean.setZero();\n\n        CVectorFixedDouble<6> x_incrs;\n        x_incrs.fill(1e-6);\n        mrpt::math::estimateJacobian(\n            x_mean,\n            /* Error function to evaluate */\n            std::function<void(\n                const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                CVectorFixedDouble<3>& err)>(\n                /* Lambda, capturing the pair data */\n                [pair](\n                    const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                    CVectorFixedDouble<3>& err) {\n                    // SE(3) pose increment on the manifold:\n                    const CPose3D incr         = Lie::SE<3>::exp(eps);\n                    const CPose3D D_expEpsilon = D + incr;\n                    err = mp2p_icp::error_point2point(pair, D_expEpsilon);\n                }),\n            x_incrs, p, numJacob);\n    }\n\n    if ((numJacob.asEigen() - jacob.asEigen()).array().abs().maxCoeff() > 1e-5)\n    {\n        std::cerr << \"numJacob:\\n\"\n                  << numJacob.asEigen() << \"\\njacob:\\n\"\n                  << jacob.asEigen() << \"\\nDiff:\\n\"\n                  << (numJacob - jacob) << \"\\nJ1:\\n\"\n                  << J1.asEigen() << \"\\n\";\n        THROW_EXCEPTION(\"Jacobian mismatch, see above.\");\n    }\n}\n\n// ===========================================================================\n//  Test: error_point2line\n// ===========================================================================\n\nstatic void test_Jacob_error_point2line()\n{\n    const CPose3D p = CPose3D(\n        // x y z\n        normald(10), normald(10), normald(10),\n        // Yaw pitch roll\n        rnd.drawUniform(-M_PI, M_PI), rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5),\n        rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5));\n\n    mp2p_icp::point_line_pair_t pair;\n\n    pair.ln_global.pBase.x = normalf(20);\n    pair.ln_global.pBase.y = normalf(20);\n    pair.ln_global.pBase.z = normalf(20);\n    pair.ln_global.director =\n        mrpt::math::TPoint3D(normald(1), normald(1), normald(1)).unitarize();\n\n    pair.pt_local.x = normalf(10);\n    pair.pt_local.y = normalf(10);\n    pair.pt_local.z = normalf(10);\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 3, 12> J1;\n\n    mp2p_icp::error_point2line(pair, p, J1);\n\n    // (12x6 Jacobian)\n    const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);\n\n    const mrpt::math::CMatrixFixed<double, 3, 6> jacob(J1 * dDexpe_de);\n\n    // Numerical Jacobian:\n    CMatrixDouble numJacob;\n    {\n        CVectorFixedDouble<6> x_mean;\n        x_mean.setZero();\n\n        CVectorFixedDouble<6> x_incrs;\n        x_incrs.fill(1e-5);\n        mrpt::math::estimateJacobian(\n            x_mean,\n            /* Error function to evaluate */\n            std::function<void(\n                const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                CVectorFixedDouble<3>& err)>(\n                /* Lambda, capturing the pair data */\n                [pair](\n                    const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                    CVectorFixedDouble<3>& err) {\n                    // SE(3) pose increment on the manifold:\n                    const CPose3D incr         = Lie::SE<3>::exp(eps);\n                    const CPose3D D_expEpsilon = D + incr;\n                    err = mp2p_icp::error_point2line(pair, D_expEpsilon);\n                }),\n            x_incrs, p, numJacob);\n    }\n\n    if ((numJacob.asEigen() - jacob.asEigen()).array().abs().maxCoeff() > 1e-5)\n    {\n        std::cerr << \"relativePose: \" << p\n                  << \"\\n\"\n                     \"numJacob:\"\n                  << numJacob.asEigen()\n                  << \"\\n\"\n                     \"jacob   :\"\n                  << jacob.asEigen()\n                  << \"\\n\"\n                     \"diff    :\"\n                  << (numJacob - jacob)\n                  << \"\\n\"\n                     \"J1      :\"\n                  << J1.asEigen() << \"\\n\";\n        THROW_EXCEPTION(\"Jacobian mismatch, see above.\");\n    }\n}\n\n// ===========================================================================\n//  Test: error_point2plane\n// ===========================================================================\n\nstatic void test_Jacob_error_point2plane()\n{\n    const CPose3D p = CPose3D(\n        // x y z\n        normald(10), normald(10), normald(10),\n        // Yaw pitch roll\n        rnd.drawUniform(-M_PI, M_PI), rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5),\n        rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5));\n\n    mp2p_icp::point_plane_pair_t pair;\n\n    pair.pl_global.centroid.x     = normalf(20);\n    pair.pl_global.centroid.y     = normalf(20);\n    pair.pl_global.centroid.z     = normalf(20);\n    pair.pl_global.plane.coefs[0] = normald(20);\n    pair.pl_global.plane.coefs[1] = normald(20);\n    pair.pl_global.plane.coefs[2] = normald(20);\n\n    pair.pt_local.x = normalf(10);\n    pair.pt_local.y = normalf(10);\n    pair.pt_local.z = normalf(10);\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 3, 12> J1;\n\n    mp2p_icp::error_point2plane(pair, p, J1);\n\n    // (12x6 Jacobian)\n    const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);\n\n    const mrpt::math::CMatrixFixed<double, 3, 6> jacob(J1 * dDexpe_de);\n\n    // Numerical Jacobian:\n    CMatrixDouble numJacob;\n    {\n        CVectorFixedDouble<6> x_mean;\n        x_mean.setZero();\n\n        CVectorFixedDouble<6> x_incrs;\n        x_incrs.fill(1e-6);\n        mrpt::math::estimateJacobian(\n            x_mean,\n            /* Error function to evaluate */\n            std::function<void(\n                const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                CVectorFixedDouble<3>& err)>(\n                /* Lambda, capturing the pair data */\n                [pair](\n                    const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                    CVectorFixedDouble<3>& err) {\n                    // SE(3) pose increment on the manifold:\n                    const CPose3D incr         = Lie::SE<3>::exp(eps);\n                    const CPose3D D_expEpsilon = D + incr;\n                    err = mp2p_icp::error_point2plane(pair, D_expEpsilon);\n                }),\n            x_incrs, p, numJacob);\n    }\n\n    if ((numJacob.asEigen() - jacob.asEigen()).array().abs().maxCoeff() > 1e-5)\n    {\n        std::cerr << \"numJacob:\\n\"\n                  << numJacob.asEigen() << \"\\njacob:\\n\"\n                  << jacob.asEigen() << \"\\nDiff:\\n\"\n                  << (numJacob - jacob) << \"\\nJ1:\\n\"\n                  << J1.asEigen() << \"\\n\";\n        THROW_EXCEPTION(\"Jacobian mismatch, see above.\");\n    }\n}\n\n// ===========================================================================\n//  Test: error_line2line\n// ===========================================================================\n\nstatic void test_Jacob_error_line2line()\n{\n    const CPose3D p = CPose3D(\n        // x y z\n        normald(10), normald(10), normald(10),\n        // Yaw pitch roll\n        rnd.drawUniform(-M_PI, M_PI), rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5),\n        rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5));\n\n    mp2p_icp::matched_line_t pair;\n\n    pair.ln_global.pBase.x     = normalf(10);\n    pair.ln_global.pBase.y     = normalf(10);\n    pair.ln_global.pBase.z     = normalf(10);\n    pair.ln_global.director[0] = normald(10);\n    pair.ln_global.director[1] = normald(10);\n    pair.ln_global.director[2] = normald(10);\n\n    pair.ln_local.pBase.x     = normalf(10);\n    pair.ln_local.pBase.y     = normalf(10);\n    pair.ln_local.pBase.z     = normalf(10);\n    pair.ln_local.director[0] = normald(10);\n    pair.ln_local.director[1] = normald(10);\n    pair.ln_local.director[2] = normald(10);\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 4, 12> J1;\n\n    mp2p_icp::error_line2line(pair, p, J1);\n\n    // (12x6 Jacobian)\n    const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);\n\n    const mrpt::math::CMatrixFixed<double, 4, 6> jacob(J1 * dDexpe_de);\n\n    // Numerical Jacobian:\n    CMatrixDouble numJacob;\n    {\n        CVectorFixedDouble<6> x_mean;\n        x_mean.setZero();\n\n        CVectorFixedDouble<6> x_incrs;\n        x_incrs.fill(1e-6);\n        mrpt::math::estimateJacobian(\n            x_mean,\n            /* Error function to evaluate */\n            std::function<void(\n                const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                CVectorFixedDouble<4>& err)>(\n                /* Lambda, capturing the pair data */\n                [pair](\n                    const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                    CVectorFixedDouble<4>& err) {\n                    // SE(3) pose increment on the manifold:\n                    const CPose3D incr         = Lie::SE<3>::exp(eps);\n                    const CPose3D D_expEpsilon = D + incr;\n                    err = mp2p_icp::error_line2line(pair, D_expEpsilon);\n                }),\n            x_incrs, p, numJacob);\n    }\n\n    if ((numJacob.asEigen() - jacob.asEigen()).array().abs().maxCoeff() > 1e-5)\n    {\n        std::cerr << \"numJacob:\\n\"\n                  << numJacob.asEigen() << \"\\njacob:\\n\"\n                  << jacob.asEigen() << \"\\nDiff:\\n\"\n                  << (numJacob - jacob) << \"\\nJ1:\\n\"\n                  << J1.asEigen() << \"\\n\";\n        THROW_EXCEPTION(\"Jacobian mismatch, see above.\");\n    }\n}\n\n// ===========================================================================\n//  Test: error_plane2plane\n// ===========================================================================\n\nstatic void test_Jacob_error_plane2plane()\n{\n    const CPose3D p = CPose3D(\n        // x y z\n        normald(10), normald(10), normald(10),\n        // Yaw pitch roll\n        rnd.drawUniform(-M_PI, M_PI), rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5),\n        rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5));\n\n    mp2p_icp::matched_plane_t pair;\n\n    pair.p_global.centroid.x     = normalf(20);\n    pair.p_global.centroid.y     = normalf(20);\n    pair.p_global.centroid.z     = normalf(20);\n    pair.p_global.plane.coefs[0] = normald(20);\n    pair.p_global.plane.coefs[1] = normald(20);\n    pair.p_global.plane.coefs[2] = normald(20);\n\n    pair.p_local.centroid.x     = normalf(10);\n    pair.p_local.centroid.y     = normalf(10);\n    pair.p_local.centroid.z     = normalf(10);\n    pair.p_local.plane.coefs[0] = normald(10);\n    pair.p_local.plane.coefs[1] = normald(10);\n    pair.p_local.plane.coefs[2] = normald(10);\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 3, 12> J1;\n\n    mp2p_icp::error_plane2plane(pair, p, J1);\n\n    // (12x6 Jacobian)\n    const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);\n\n    const mrpt::math::CMatrixFixed<double, 3, 6> jacob(J1 * dDexpe_de);\n\n    // Numerical Jacobian:\n    CMatrixDouble numJacob;\n    {\n        CVectorFixedDouble<6> x_mean;\n        x_mean.setZero();\n\n        CVectorFixedDouble<6> x_incrs;\n        x_incrs.fill(1e-6);\n        mrpt::math::estimateJacobian(\n            x_mean,\n            /* Error function to evaluate */\n            std::function<void(\n                const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                CVectorFixedDouble<3>& err)>(\n                /* Lambda, capturing the pair data */\n                [pair](\n                    const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                    CVectorFixedDouble<3>& err) {\n                    // SE(3) pose increment on the manifold:\n                    const CPose3D incr         = Lie::SE<3>::exp(eps);\n                    const CPose3D D_expEpsilon = D + incr;\n                    err = mp2p_icp::error_plane2plane(pair, D_expEpsilon);\n                }),\n            x_incrs, p, numJacob);\n    }\n\n    if ((numJacob.asEigen() - jacob.asEigen()).array().abs().maxCoeff() > 1e-5)\n    {\n        std::cerr << \"numJacob:\\n\"\n                  << numJacob.asEigen() << \"\\njacob:\\n\"\n                  << jacob.asEigen() << \"\\nDiff:\\n\"\n                  << (numJacob - jacob) << \"\\nJ1:\\n\"\n                  << J1.asEigen() << \"\\n\";\n        THROW_EXCEPTION(\"Jacobian mismatch, see above.\");\n    }\n}\n\n// ===========================================================================\n//  Test: error_line2line\n// ===========================================================================\n\nstatic void test_error_line2line()\n{\n    const CPose3D p = CPose3D(\n        // x y z\n        1, 0.5, 0.1,\n        // Yaw pitch roll\n        0, 0, 0);\n\n    mp2p_icp::matched_line_t pair;\n\n    pair.ln_global.pBase.x     = 0;\n    pair.ln_global.pBase.y     = 1;\n    pair.ln_global.pBase.z     = -4;\n    pair.ln_global.director[0] = 0.4364;\n    pair.ln_global.director[1] = 0.8729;\n    pair.ln_global.director[2] = -0.2182;\n\n    pair.ln_local.pBase.x     = 2;\n    pair.ln_local.pBase.y     = 1;\n    pair.ln_local.pBase.z     = -0.5;\n    pair.ln_local.director[0] = 0.2357;\n    pair.ln_local.director[1] = 0.2357;\n    pair.ln_local.director[2] = 0.9428;\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 4, 12> J1;\n\n    mrpt::math::CVectorFixedDouble<4> ref_error;\n    ref_error[0] = 0.0517;\n    ref_error[1] = 0.2007;\n    ref_error[2] = 0.6372;\n    ref_error[3] = -1.1610;\n\n#if 0\n    mrpt::math::CVectorFixedDouble<4> error =\n        mp2p_icp::error_line2line(pair, p, J1);\n\n    std::cout << \"\\nResultado: \\n\"\n              << error << \"\\nRecta A:\\n\"\n              << pair.ln_global << \"\\nRecta B:\\n\"\n              << pair.ln_local << \"\\n\";\n#endif\n\n    // (12x6 Jacobian)\n    const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);\n\n    const mrpt::math::CMatrixFixed<double, 4, 6> jacob(J1 * dDexpe_de);\n\n    // Numerical Jacobian:\n    CMatrixDouble numJacob;\n    {\n        CVectorFixedDouble<6> x_mean;\n        x_mean.setZero();\n\n        CVectorFixedDouble<6> x_incrs;\n        x_incrs.fill(1e-6);\n        mrpt::math::estimateJacobian(\n            x_mean,\n            /* Error function to evaluate */\n            std::function<void(\n                const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                CVectorFixedDouble<4>& err)>(\n                /* Lambda, capturing the pair data */\n                [pair](\n                    const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                    CVectorFixedDouble<4>& err) {\n                    // SE(3) pose increment on the manifold:\n                    const CPose3D incr         = Lie::SE<3>::exp(eps);\n                    const CPose3D D_expEpsilon = D + incr;\n                    err = mp2p_icp::error_line2line(pair, D_expEpsilon);\n                }),\n            x_incrs, p, numJacob);\n    }\n#if 0\n    std::cout << \"numJacob:\\n\"\n              << numJacob.asEigen() << \"\\njacob:\\n\"\n              << jacob.asEigen() << \"\\nDiff:\\n\"\n              << (numJacob - jacob) << \"\\nJ1:\\n\"\n              << J1.asEigen() << \"\\ndDexp_de:\\n\"\n              << dDexpe_de.asEigen() << \"\\n\";\n#endif\n}\n\nstatic void test_against_ground_truth_error_point2line()\n{\n    const CPose3D p = CPose3D::Identity();\n\n    mp2p_icp::point_line_pair_t pair;\n\n    pair.ln_global.pBase.x  = 10;\n    pair.ln_global.pBase.y  = 11;\n    pair.ln_global.pBase.z  = 12;\n    pair.ln_global.director = mrpt::math::TPoint3D(0, 0, 1).unitarize();\n\n    pair.pt_local.x = 10;\n    pair.pt_local.y = 11;\n    pair.pt_local.z = -1.0;\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 3, 12> J1;\n\n    CVectorFixedDouble<3> err = mp2p_icp::error_point2line(pair, p, J1);\n    ASSERT_NEAR_(err[0], 0.0, 1e-6);\n}\n\nint main([[maybe_unused]] int argc, [[maybe_unused]] char** argv)\n{\n    try\n    {\n        // test Jacobians:\n        // ----------------------------------------------\n        rnd.randomize(1234);  // for reproducible tests\n\n        // Run for many different random conditions:\n        for (int i = 0; i < 1000; i++)\n        {\n            test_Jacob_error_point2point();\n            test_Jacob_error_point2line();\n            test_Jacob_error_point2plane();\n            test_Jacob_error_plane2plane();\n            // TODO: Fix this one:\n            // test_Jacob_error_line2line();\n\n            test_error_line2line();\n        }\n\n        // Test for known fixed conditions:\n        // ----------------------------------------------\n        test_against_ground_truth_error_point2line();\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << mrpt::exception_to_str(e) << \"\\n\";\n        return 1;\n    }\n}\n", "meta": {"hexsha": "02beab4d2f471e87ee1b1fde64d43fcc6177f83f", "size": 18539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test-mp2p_error_terms_jacobians.cpp", "max_stars_repo_name": "MOLAorg/mp2_icp", "max_stars_repo_head_hexsha": "e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-07T08:10:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-07T15:01:02.000Z", "max_issues_repo_path": "tests/test-mp2p_error_terms_jacobians.cpp", "max_issues_repo_name": "MOLAorg/mp2_icp", "max_issues_repo_head_hexsha": "e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test-mp2p_error_terms_jacobians.cpp", "max_forks_repo_name": "MOLAorg/mp2_icp", "max_forks_repo_head_hexsha": "e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb", "max_forks_repo_licenses": ["BSD-3-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.8302919708, "max_line_length": 79, "alphanum_fraction": 0.5169642376, "num_tokens": 5202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199673867852, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5884532141972307}}
{"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": "/* Boost check_gmp.cpp test file\n\n Copyright 2009 Karsten Ahnert\n Copyright 2009 Mario Mulansky\n\n This file tests the odeint library with the gmp arbitrary precision types\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#define BOOST_TEST_MODULE odeint_gmp\n\n#include <iostream>\n\n#include <gmpxx.h>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/array.hpp>\n\n#include <boost/mpl/vector.hpp>\n\n#include <boost/numeric/odeint.hpp>\n//#include <boost/numeric/odeint/algebra/vector_space_algebra.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\n\nnamespace mpl = boost::mpl;\n\nconst int precision = 1024;\n\ntypedef mpf_class value_type;\ntypedef mpf_class state_type;\n\n//provide min, max and pow functions for mpf types - required for controlled steppers\nvalue_type min( const value_type a , const value_type b )\n{\n    if( a<b ) return a;\n    else return b;\n}\nvalue_type max( const value_type a , const value_type b )\n{\n    if( a>b ) return a;\n    else return b;\n}\nvalue_type pow( const value_type a , const value_type b )\n{\n    // do calculation in double precision\n    return value_type( std::pow( a.get_d() , b.get_d() ) );\n}\n\n\n//provide vector_space reduce:\n\nnamespace boost { namespace numeric { namespace odeint {\n\ntemplate<>\nstruct vector_space_reduce< state_type >\n{\n  template< class Op >\n  state_type operator()( state_type x , Op op , state_type init ) const\n  {\n      init = op( init , x );\n      return init;\n  }\n};\n\n} } }\n\n\nvoid constant_system( const state_type &x , state_type &dxdt , value_type t )\n{\n    dxdt = value_type( 1.0 , precision );\n}\n\n\n/* check runge kutta stepers */\ntypedef mpl::vector<\n    euler< state_type , value_type , state_type , value_type , vector_space_algebra > ,\n    modified_midpoint< state_type , value_type , state_type , value_type , vector_space_algebra > ,\n    runge_kutta4< state_type , value_type , state_type , value_type , vector_space_algebra > ,\n    runge_kutta4_classic< state_type , value_type , state_type , value_type , vector_space_algebra > ,\n    runge_kutta_cash_karp54_classic< state_type , value_type , state_type , value_type , vector_space_algebra > ,\n    runge_kutta_cash_karp54< state_type , value_type , state_type , value_type , vector_space_algebra > ,\n    runge_kutta_dopri5< state_type , value_type , state_type , value_type , vector_space_algebra > ,\n    runge_kutta_fehlberg78< state_type , value_type , state_type , value_type , vector_space_algebra >\n    > stepper_types;\n\n\ntemplate< class Stepper >\nstruct perform_runge_kutta_test {\n\n    void operator()( void )\n    {\n        /* We have to specify the desired precision in advance! */\n        mpf_set_default_prec( precision );\n\n        mpf_t eps_ , unity;\n        mpf_init( eps_ ); mpf_init( unity );\n        mpf_set_d( unity , 1.0 );\n        mpf_div_2exp( eps_ , unity , precision-1 ); // 2^(-precision+1) : smallest number that can be represented with used precision\n        value_type eps( eps_ );\n\n        Stepper stepper;\n        state_type x;\n        x = 0.0;\n\n        stepper.do_step( constant_system , x , 0.0 , 0.1 );\n\n        BOOST_MESSAGE( eps );\n        BOOST_CHECK_MESSAGE( abs( x - value_type( 0.1 , precision ) ) < eps , x - 0.1 );\n    }\n};\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( runge_kutta_stepper_test , Stepper , stepper_types )\n{\n    perform_runge_kutta_test< Stepper > tester;\n    tester();\n}\n\n\n/* check controlled steppers */\ntypedef mpl::vector<\n    controlled_runge_kutta< runge_kutta_cash_karp54_classic< state_type , value_type , state_type , value_type , vector_space_algebra > > ,\n    controlled_runge_kutta< runge_kutta_dopri5< state_type , value_type , state_type , value_type , vector_space_algebra > > , \n    controlled_runge_kutta< runge_kutta_fehlberg78< state_type , value_type , state_type , value_type , vector_space_algebra > > ,\n    bulirsch_stoer< state_type , value_type , state_type , value_type , vector_space_algebra >\n    > controlled_stepper_types;\n\n\ntemplate< class Stepper >\nstruct perform_controlled_test {\n\n    void operator()( void )\n    {\n        mpf_set_default_prec( precision );\n\n        mpf_t eps_ , unity;\n        mpf_init( eps_ ); mpf_init( unity );\n        mpf_set_d( unity , 1.0 );\n        mpf_div_2exp( eps_ , unity , precision-1 ); // 2^(-precision+1) : smallest number that can be represented with used precision\n        value_type eps( eps_ );\n\n        Stepper stepper;\n        state_type x;\n        x = 0.0;\n\n        value_type t(0.0);\n        value_type dt(0.1);\n\n        stepper.try_step( constant_system , x , t , dt );\n\n        BOOST_MESSAGE( eps );\n        BOOST_CHECK_MESSAGE( abs( x - value_type( 0.1 , precision ) ) < eps , x - 0.1 );\n    }\n};\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( controlled_stepper_test , Stepper , controlled_stepper_types )\n{\n    perform_controlled_test< Stepper > tester;\n    tester();\n}\n", "meta": {"hexsha": "ce469c7f5e8646a3fe7dbf532f177e7f746585cf", "size": 4931, "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/test_external/gmp/check_gmp.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/test_external/gmp/check_gmp.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/test_external/gmp/check_gmp.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": 29.7048192771, "max_line_length": 139, "alphanum_fraction": 0.6980328534, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5884532056541218}}
{"text": "#ifndef TURBOTRACK_HPP\n#define TURBOTRACK_HPP\n\n#include <Eigen/Dense>\n\nnamespace turbotrack {\n\nenum class TrackballType {\n\t// chen_et_al, not implemented yet\n\tshoemake,\n\tholroyd\n};\n\n// See equation 33 in Henriksen et al.\nEigen::Vector3f shoemake_projection(Eigen::Vector2f const &mouse, float radius);\n\n// See equation 46 in Henriksen et al.\nEigen::Vector3f holroyd_projection(Eigen::Vector2f const &mouse, float radius);\n\nEigen::Quaternionf mouse_move(Eigen::Vector2f const &old_pos,\n                              Eigen::Vector2f const &new_pos,\n                              float radius = 1.0,\n                              TrackballType type = TrackballType::holroyd);\n\n} // namespace turbotrack\n\n#endif // TURBOTRACK_HPP\n", "meta": {"hexsha": "bbe8c0f63b10dacc6d93acf09a10a50834e7f84a", "size": 726, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/turbotrack.hpp", "max_stars_repo_name": "manuel5975p/turbotrack", "max_stars_repo_head_hexsha": "20599abe932888e873f978a6ce8ae35c21f8d3fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/turbotrack.hpp", "max_issues_repo_name": "manuel5975p/turbotrack", "max_issues_repo_head_hexsha": "20599abe932888e873f978a6ce8ae35c21f8d3fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/turbotrack.hpp", "max_forks_repo_name": "manuel5975p/turbotrack", "max_forks_repo_head_hexsha": "20599abe932888e873f978a6ce8ae35c21f8d3fc", "max_forks_repo_licenses": ["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.9285714286, "max_line_length": 80, "alphanum_fraction": 0.6763085399, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5884532018730936}}
{"text": "#include <stan/math/prim.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <limits>\n\nstan::math::vector_d get_simplex_Phi(double lambda,\n                                     const stan::math::vector_d& c) {\n  using stan::math::Phi;\n  int K = c.size() + 1;\n  stan::math::vector_d theta(K);\n  theta(0) = 1.0 - Phi(lambda - c(0));\n  for (int k = 1; k < (K - 1); ++k)\n    theta(k) = Phi(lambda - c(k - 1)) - Phi(lambda - c(k));\n  // - 0.0\n  theta(K - 1) = Phi(lambda - c(K - 2));\n  return theta;\n}\n\nTEST(ProbDistributions, ordered_probit_stability) {\n  using stan::math::is_inf;\n  using stan::math::ordered_probit_log;\n\n  Eigen::VectorXd c(3);\n  c << -0.3, 0.1, 1.2;\n\n  EXPECT_FALSE(is_inf(ordered_probit_log(1, 10, c)));\n  EXPECT_FALSE(is_inf(ordered_probit_log(2, 10, c)));\n  EXPECT_NE(ordered_probit_log(4, 10, c), 0);\n\n  EXPECT_NE(ordered_probit_log(1, -38, c), 0);\n  EXPECT_FALSE(is_inf(ordered_probit_log(2, -38, c)));\n  EXPECT_FALSE(is_inf(ordered_probit_log(4, -38, c)));\n}\n\nTEST(ProbDistributions, ordered_probit_vals) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n\n  using stan::math::ordered_probit_log;\n  using stan::math::Phi;\n\n  int K = 5;\n  Matrix<double, Dynamic, 1> c(K - 1);\n  c << -1.7, -0.3, 1.2, 2.6;\n  double lambda = 1.1;\n\n  stan::math::vector_d theta = get_simplex_Phi(lambda, c);\n\n  double sum = 0.0;\n  for (int k = 0; k < theta.size(); ++k)\n    sum += theta(k);\n  EXPECT_FLOAT_EQ(1.0, sum);\n\n  for (int k = 0; k < K; ++k)\n    EXPECT_FLOAT_EQ(log(theta(k)), ordered_probit_log(k + 1, lambda, c));\n\n  EXPECT_THROW(ordered_probit_log(0, lambda, c), std::domain_error);\n  EXPECT_THROW(ordered_probit_log(6, lambda, c), std::domain_error);\n}\n\nTEST(ProbDistributions, ordered_probit_vals_2) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n\n  using stan::math::ordered_probit_log;\n  using stan::math::Phi;\n\n  int K = 3;\n  Matrix<double, Dynamic, 1> c(K - 1);\n  c << -0.2, 4;\n  double lambda = -0.9;\n\n  stan::math::vector_d theta = get_simplex_Phi(lambda, c);\n\n  double sum = 0.0;\n  for (int k = 0; k < theta.size(); ++k)\n    sum += theta(k);\n  EXPECT_FLOAT_EQ(1.0, sum);\n\n  for (int k = 0; k < K; ++k)\n    EXPECT_FLOAT_EQ(log(theta(k)), ordered_probit_log(k + 1, lambda, c));\n\n  EXPECT_THROW(ordered_probit_log(0, lambda, c), std::domain_error);\n  EXPECT_THROW(ordered_probit_log(4, lambda, c), std::domain_error);\n}\n\nTEST(ProbDistributions, ordered_probit) {\n  using stan::math::ordered_probit_log;\n  int K = 4;\n  Eigen::Matrix<double, Eigen::Dynamic, 1> c(K - 1);\n  c << -0.3, 0.1, 1.2;\n  double lambda = 0.5;\n  EXPECT_THROW(ordered_probit_log(-1, lambda, c), std::domain_error);\n  EXPECT_THROW(ordered_probit_log(0, lambda, c), std::domain_error);\n  EXPECT_THROW(ordered_probit_log(5, lambda, c), std::domain_error);\n  for (int k = 1; k <= K; ++k)\n    EXPECT_NO_THROW(ordered_probit_log(k, lambda, c));\n\n  // init size zero\n  Eigen::Matrix<double, Eigen::Dynamic, 1> c_zero;\n  EXPECT_EQ(0, c_zero.size());\n  EXPECT_THROW(ordered_probit_log(1, lambda, c_zero), std::invalid_argument);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> c_neg(1);\n  c_neg << -13.7;\n  EXPECT_NO_THROW(ordered_probit_log(1, lambda, c_neg));\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> c_unord(3);\n  c_unord << 1.0, 0.4, 2.0;\n  EXPECT_THROW(ordered_probit_log(1, lambda, c_unord), std::domain_error);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> c_unord_2(3);\n  c_unord_2 << 1.0, 2.0, 0.4;\n  EXPECT_THROW(ordered_probit_log(1, lambda, c_unord_2), std::domain_error);\n\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  double inf = std::numeric_limits<double>::infinity();\n\n  EXPECT_THROW(ordered_probit_log(1, nan, c), std::domain_error);\n  EXPECT_THROW(ordered_probit_log(1, inf, c), std::domain_error);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> cbad(2);\n  cbad << 0.2, inf;\n  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad), std::domain_error);\n  cbad[1] = nan;\n  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad), std::domain_error);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> cbad1(1);\n  cbad1 << inf;\n  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad1), std::domain_error);\n  cbad1[0] = nan;\n  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad1), std::domain_error);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> cbad3(3);\n  cbad3 << 0.5, inf, 1.0;\n  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad3), std::domain_error);\n  cbad3[1] = nan;\n  EXPECT_THROW(ordered_probit_log(1, 1.0, cbad3), std::domain_error);\n}\n\nTEST(ProbDistributionOrderedProbit, error_check) {\n  boost::random::mt19937 rng;\n  double inf = std::numeric_limits<double>::infinity();\n  Eigen::VectorXd c(4);\n  c << -2, 2.0, 5, 10;\n  EXPECT_NO_THROW(stan::math::ordered_probit_rng(4.0, c, rng));\n\n  EXPECT_THROW(\n      stan::math::ordered_probit_rng(stan::math::positive_infinity(), c, rng),\n      std::domain_error);\n  c << -inf, 2.0, -5, inf;\n  EXPECT_THROW(stan::math::ordered_probit_rng(4.0, c, rng), std::domain_error);\n}\n\nTEST(ProbDistributionOrderedProbit, chiSquareGoodnessFitTest) {\n  using stan::math::Phi;\n  boost::random::mt19937 rng;\n  int N = 10000;\n  double eta = 1.0;\n  Eigen::VectorXd theta(3);\n  theta << -0.4, 4.0, 6.2;\n  Eigen::VectorXd prob(4);\n  prob(0) = 1 - Phi(eta - theta(0));\n  prob(1) = Phi(eta - theta(0)) - Phi(eta - theta(1));\n  prob(2) = Phi(eta - theta(1)) - Phi(eta - theta(2));\n  prob(3) = Phi(eta - theta(2));\n  int K = prob.rows();\n  boost::math::chi_squared mydist(K - 1);\n\n  Eigen::VectorXd loc(prob.rows());\n  for (int i = 0; i < prob.rows(); i++)\n    loc(i) = 0;\n\n  for (int i = 0; i < prob.rows(); i++) {\n    for (int j = i; j < prob.rows(); j++)\n      loc(j) += prob(i);\n  }\n\n  int count = 0;\n  int bin[K];\n  double expect[K];\n  for (int i = 0; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N * prob(i);\n  }\n\n  while (count < N) {\n    int a = stan::math::ordered_probit_rng(eta, theta, rng);\n    bin[a - 1]++;\n    count++;\n  }\n\n  double chi = 0;\n\n  for (int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n", "meta": {"hexsha": "0e5d82d5af6f7f9bcad4be30cff476c5e3db6ad4", "size": 6078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/ordered_probit_test.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "test/unit/math/prim/prob/ordered_probit_test.cpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/prim/prob/ordered_probit_test.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 30.39, "max_line_length": 79, "alphanum_fraction": 0.6437973017, "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5884531961776882}}
{"text": "#ifndef CONCEPTS_DIMENSIONS_GROUP_HPP_INCLUDED\n#define CONCEPTS_DIMENSIONS_GROUP_HPP_INCLUDED\n\n#include <limits>\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/zero.hpp>\n#include <boost/hana/plus.hpp>\n#include <boost/hana/less.hpp>\n\n#include <gem/fwd/dimensions.hpp>\n\nnamespace boost::hana {\n\ntemplate<typename T>\nstatic constexpr\nauto safe_sub(const T & v1, const T & v2)\n{\n    return v1 >= v2 ? v1 - v2 : 0;\n}\n\ngem::concepts::detail::DimensionPair {T1, cv1, max1, min1, T2, cv2, max2, min2}\nstruct minus_impl<gem::Dimension<T1, cv1, max1, min1>,\n                  gem::Dimension<T2, cv2, max2, min2>>\n{\nprivate:\n    using ctype = typename boost::hana::common<T1, T2>::type;\n\npublic:\n    static constexpr auto\n    apply(const gem::Dimension<T1, cv1, max1, min1>& d1,\n          const gem::Dimension<T2, cv2, max2, min2>& d2)\n    {\n        BOOST_HANA_RUNTIME_CHECK_MSG(d1.value() >= d2.value(),\n                                     \"Dimension underflow...\");\n        return gem::Dimension<ctype, safe_sub<ctype>(cv1, cv2),\n                                     safe_sub<ctype>(max1, min2),\n                                     safe_sub<ctype>(min1, max2)> {d1.value() -\n                                                                   d2.value()};\n    }\n};\n\ntemplate<typename T1, T1 cv1, typename T2, T2 cv2>\nstruct minus_impl<gem::Dimension<T1, cv1, cv1, cv1>,\n                  gem::Dimension<T2, cv2, cv2, cv2>>\n{\nprivate:\n    using ctype = typename boost::hana::common<T1, T2>::type;\n\npublic:\n    static constexpr auto\n    apply(const gem::Dimension<T1, cv1, cv1, cv1> &,\n          const gem::Dimension<T2, cv2, cv2, cv2> &)\n    {\n        constexpr auto c = integral_c<ctype, cv1>;\n        constexpr auto m = integral_c<ctype, cv2>;\n        BOOST_HANA_CONSTANT_CHECK_MSG(c >= m, \"Dimension underflow...\");\n        constexpr ctype s = static_cast<ctype>(cv1) -\n                            static_cast<ctype>(cv2);\n        return gem::Dimension<ctype, s, s, s> {};\n    }\n};\n\n}  // namespace boost::hana\n\nnamespace gem {\n\ntemplate <typename T1, T1 cv1, T1 cv_max1, T1 cv_min1,\n          typename T2, T2 cv2, T2 cv_max2, T2 cv_min2>\nconstexpr inline auto\noperator-(const gem::Dimension<T1, cv1, cv_max1, cv_min1> & d1,\n          const gem::Dimension<T2, cv2, cv_max2, cv_min2> & d2)\n{\n    return boost::hana::minus(d1, d2);\n}\n\n}  // namespace gem\n\n#endif  // !CONCEPTS_DIMENSIONS_GROUP_HPP_INCLUDED\n", "meta": {"hexsha": "e33a003b8fe1655c93bdaabe839ab5e959a26018", "size": 2407, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gem/concept/dimensions_group.hpp", "max_stars_repo_name": "RomainBrault/Gem", "max_stars_repo_head_hexsha": "0eff3cb034a0faaca894316b72f4b005e72e0f5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/gem/concept/dimensions_group.hpp", "max_issues_repo_name": "RomainBrault/Gem", "max_issues_repo_head_hexsha": "0eff3cb034a0faaca894316b72f4b005e72e0f5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gem/concept/dimensions_group.hpp", "max_forks_repo_name": "RomainBrault/Gem", "max_forks_repo_head_hexsha": "0eff3cb034a0faaca894316b72f4b005e72e0f5d", "max_forks_repo_licenses": ["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.0875, "max_line_length": 79, "alphanum_fraction": 0.6015787287, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5884531923727965}}
{"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": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nMatrixXf A(2,2), B(3,2);\nB << 2, 0,  0, 3, 1, 1;\nA << 2, 0, 0, -2;\nA = (B * A).cwiseAbs();\ncout << A;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "6da6a3c9d7d10bef1265ff2157df97a297b48878", "size": 635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_TopicAliasing_mult4.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_TopicAliasing_mult4.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_TopicAliasing_mult4.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8965517241, "max_line_length": 224, "alphanum_fraction": 0.6519685039, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5883898960443358}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n    This is an example illustrating the use of the RVM regression object \n    from the dlib C++ Library.\n\n    This example will train on data from the sinc function.\n\n*/\n\n#include <iostream>\n#include <vector>\n\n#include <dlib/svm.h>\n\nusing namespace std;\nusing namespace dlib;\n\n// Here is the sinc function we will be trying to learn with rvm regression \ndouble sinc(double x)\n{\n    if (x == 0)\n        return 1;\n    return sin(x)/x;\n}\n\nint main()\n{\n    // Here we declare that our samples will be 1 dimensional column vectors.  \n    typedef matrix<double,1,1> sample_type;\n\n    // Now sample some points from the sinc() function\n    sample_type m;\n    std::vector<sample_type> samples;\n    std::vector<double> labels;\n    for (double x = -10; x <= 4; x += 1)\n    {\n        m(0) = x;\n        samples.push_back(m);\n        labels.push_back(sinc(x));\n    }\n\n    // Now we are making a typedef for the kind of kernel we want to use.  I picked the\n    // radial basis kernel because it only has one parameter and generally gives good\n    // results without much fiddling.\n    typedef radial_basis_kernel<sample_type> kernel_type;\n\n    // Here we declare an instance of the rvm_regression_trainer object.  This is the\n    // object that we will later use to do the training.\n    rvm_regression_trainer<kernel_type> trainer;\n\n    // Here we set the kernel we want to use for training.   The radial_basis_kernel \n    // has a parameter called gamma that we need to determine.  As a rule of thumb, a good \n    // gamma to try is 1.0/(mean squared distance between your sample points).  So \n    // below we are using a similar value.   Note also that using an inappropriately large\n    // gamma will cause the RVM training algorithm to run extremely slowly.  What\n    // \"large\" means is relative to how spread out your data is.  So it is important\n    // to use a rule like this as a starting point for determining the gamma value\n    // if you want to use the RVM.  It is also probably a good idea to normalize your\n    // samples as shown in the rvm_ex.cpp example program.\n    const double gamma = 2.0/compute_mean_squared_distance(samples);\n    cout << \"using gamma of \" << gamma << endl;\n    trainer.set_kernel(kernel_type(gamma));\n\n    // One thing you can do to reduce the RVM training time is to make its\n    // stopping epsilon bigger.  However, this might make the outputs less\n    // reliable.  But sometimes it works out well.  0.001 is the default.\n    trainer.set_epsilon(0.001);\n\n    // now train a function based on our sample points\n    decision_function<kernel_type> test = trainer.train(samples, labels);\n\n    // now we output the value of the sinc function for a few test points as well as the \n    // value predicted by our regression.\n    m(0) = 2.5; cout << sinc(m(0)) << \"   \" << test(m) << endl;\n    m(0) = 0.1; cout << sinc(m(0)) << \"   \" << test(m) << endl;\n    m(0) = -4;  cout << sinc(m(0)) << \"   \" << test(m) << endl;\n    m(0) = 5.0; cout << sinc(m(0)) << \"   \" << test(m) << endl;\n\n    // The output is as follows:\n    //using gamma of 0.05\n    //0.239389   0.240989\n    //0.998334   0.999538\n    //-0.189201   -0.188453\n    //-0.191785   -0.226516\n\n\n    // The first column is the true value of the sinc function and the second\n    // column is the output from the rvm estimate.  \n\n\n\n    // Another thing that is worth knowing is that just about everything in dlib is serializable.\n    // So for example, you can save the test object to disk and recall it later like so:\n    ofstream fout(\"saved_function.dat\",ios::binary);\n    serialize(test,fout);\n    fout.close();\n\n    // now lets open that file back up and load the function object it contains\n    ifstream fin(\"saved_function.dat\",ios::binary);\n    deserialize(test, fin);\n\n\n}\n\n\n", "meta": {"hexsha": "0ff6e85f18990908432d097035cae2a013e5d088", "size": 3854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DynamicGestures/dlib-18.5/examples/rvm_regression_ex.cpp", "max_stars_repo_name": "uiuyuty/vsfh", "max_stars_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2015-03-02T09:30:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T07:07:57.000Z", "max_issues_repo_path": "DynamicGestures/dlib-18.5/examples/rvm_regression_ex.cpp", "max_issues_repo_name": "uiuyuty/vsfh", "max_issues_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-04-01T21:28:24.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-30T21:39:28.000Z", "max_forks_repo_path": "DynamicGestures/dlib-18.5/examples/rvm_regression_ex.cpp", "max_forks_repo_name": "uiuyuty/vsfh", "max_forks_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-03-02T18:48:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T06:44:08.000Z", "avg_line_length": 36.358490566, "max_line_length": 97, "alphanum_fraction": 0.6676180592, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.5883898949741757}}
{"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": "//\n// Created by Hamza El-Kebir on 5/9/21.\n//\n\n#ifndef LODESTAR_ALGEBRAICRICCATIEQUATION_HPP\n#define LODESTAR_ALGEBRAICRICCATIEQUATION_HPP\n\n#include \"Lodestar/systems/StateSpace.hpp\"\n#include <Eigen/Eigenvalues>\n\nnamespace ls {\n    namespace synthesis {\n        class AlgebraicRiccatiEquation {\n        public:\n            static Eigen::MatrixXd\n            solveDARE(const Eigen::MatrixXd &A, const Eigen::MatrixXd &B, const Eigen::MatrixXd &Q,\n                      const Eigen::MatrixXd &R);\n\n            static Eigen::MatrixXd\n            solveDARE(const systems::StateSpace<> &sys, const Eigen::MatrixXd &Q, const Eigen::MatrixXd &R);\n        };\n    }\n}\n\n#endif //LODESTAR_ALGEBRAICRICCATIEQUATION_HPP\n", "meta": {"hexsha": "adf93d6ca2fe5ee6c4979ff6b28752a30fb4938c", "size": 707, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/synthesis/AlgebraicRiccatiEquation.hpp", "max_stars_repo_name": "helkebir/Lodestar", "max_stars_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T14:08:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T22:15:31.000Z", "max_issues_repo_path": "Lodestar/synthesis/AlgebraicRiccatiEquation.hpp", "max_issues_repo_name": "helkebir/Lodestar", "max_issues_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T15:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T17:43:20.000Z", "max_forks_repo_path": "Lodestar/synthesis/AlgebraicRiccatiEquation.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": 27.1923076923, "max_line_length": 108, "alphanum_fraction": 0.6676096181, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5883188180286492}}
{"text": "// Depth filling based on the paper\n//  \"Colorization Using Optimization\" by A. Levin, D. Lischinski, Y. Weiss\n// Author: Max Schwarz <max.schwarz@uni-bonn.de>\n//  based on an implementation by Benedikt Waldvogel\n\n#include <depth_filler/depth_filler.h>\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/LU>\n\n#ifdef EIGEN_UMFPACK_SUPPORT\n#include <Eigen/UmfPackSupport>\n#endif\n\n#ifdef KLU_SUPPORT\n#include \"eigen_klu.h\"\n#endif\n\n#include <unsupported/Eigen/SparseExtra>\n\n#include <chrono>\n\nnamespace depth_filler\n{\n\nconstexpr bool DUMP_MATRICES = false;\nconstexpr bool PROFILE_SOLVING = true;\n\ntypedef decltype(std::chrono::high_resolution_clock::now()) Time;\n\n// Choose best available solver\n#ifdef KLU_SUPPORT\n// KLU can only solve in double precision\ntypedef double SolveType;\n#elif defined(EIGEN_UMFPACK_SUPPORT)\n#warning Using slower UMFPACK solver. Install KLU for faster solving.\n// UMFPACK can only solve in double precision\ntypedef double SolveType;\n#else\n#warning Using very slow built-in Eigen BiCGSTAB solver. Install KLU!\ntypedef float SolveType;\n#endif\n\nnamespace\n{\n\tclass ScopeTimer\n\t{\n\tpublic:\n\t\texplicit ScopeTimer(const std::string& name)\n\t\t: m_name(name)\n\t\t{\n\t\t\tif(PROFILE_SOLVING)\n\t\t\t\tm_start = std::chrono::high_resolution_clock::now();\n\t\t}\n\n\t\t~ScopeTimer()\n\t\t{\n\t\t\tif(PROFILE_SOLVING)\n\t\t\t{\n\t\t\t\tTime stop = std::chrono::high_resolution_clock::now();\n\t\t\t\tstd::cout << m_name << \" took \" << std::chrono::duration_cast<std::chrono::milliseconds>(stop - m_start).count() << \"ms\\n\";\n\t\t\t}\n\t\t}\n\tprivate:\n\t\tstd::string m_name;\n\t\tTime m_start;\n\t};\n}\n\nclass DepthFillerPrivate\n{\npublic:\n\tvoid solve();\n\n\tint rows;\n\tint cols;\n\n\tcv::Mat_<uint8_t> mask;\n\tcv::Mat_<float> depth;\n\tcv::Mat_<cv::Vec3b> rgb;\n\tunsigned int numUnknown;\n\n\tcv::Mat_<int> mapImgToIdx;\n\n\tstd::vector<int> outerIndices;\n\tstd::vector<int> innerIndices;\n\tstd::vector<SolveType> values;\n\n\tEigen::Matrix<SolveType, Eigen::Dynamic, 1> b;\n\tEigen::Matrix<SolveType, Eigen::Dynamic, 1> newDepth;\n\n#if defined(KLU_SUPPORT)\n\tEigen::KLU<Eigen::MappedSparseMatrix<SolveType, Eigen::RowMajor>> solver;\n#elif defined(EIGEN_UMFPACK_SUPPORT)\n\tEigen::UmfPackLU<Eigen::SparseMatrix<SolveType>> solver;\n#else\n\tEigen::BiCGSTAB<Eigen::MappedSparseMatrix<SolveType, Eigen::RowMajor>> solver;\n#endif\n\n\tDepthFiller::ColorDistance distance = DepthFiller::CD_GRAYSCALE;\n\tbool normalizeWithVariance = true;\n\tfloat distExponent = 1.2f;\n\tfloat distScale = 1.0f;\n};\n\n\nvoid DepthFillerPrivate::solve()\n{\n\tconst int winRad = 1;\n\tconst int winPixel = (2 * winRad + 1)*(2 * winRad + 1);\n\n\touterIndices.clear();\n\tinnerIndices.clear();\n\tvalues.clear();\n\n\tconst int GUESS_NONZERO = 9 * numUnknown;\n\touterIndices.reserve(numUnknown);\n\tinnerIndices.reserve(GUESS_NONZERO);\n\tvalues.reserve(GUESS_NONZERO);\n\n\tEigen::VectorXi cols(winPixel);\n\tEigen::VectorXf winDepth(winPixel);\n\tEigen::VectorXf gvals = Eigen::VectorXf::Zero(winPixel);\n\tstd::vector<Eigen::Vector3f> rgbWin(winPixel);\n\n\tb.resize(numUnknown);\n\tb.setZero();\n\n\tmapImgToIdx = cv::Mat_<int>(depth.rows, depth.cols);\n\t{\n\t\tunsigned int idx = 0;\n\t\tfor(int y = 0; y < depth.rows; ++y)\n\t\t{\n\t\t\tfloat* ptr = depth[y];\n\t\t\tint* idxPtr = mapImgToIdx[y];\n\n\t\t\tfor(int x = 0; x < depth.cols; ++x)\n\t\t\t{\n\t\t\t\tif(ptr[x] < 0 && (!mask.rows || mask(y,x)))\n\t\t\t\t\tidxPtr[x] = idx++;\n\t\t\t\telse\n\t\t\t\t\tidxPtr[x] = -1;\n\t\t\t}\n\t\t}\n\t}\n\n\t{\n\t\tScopeTimer timer(\"formulate system matrix\");\n\n\t\tcv::Mat_<uint8_t> gray;\n\t\tcv::cvtColor(rgb, gray, CV_BGR2GRAY);\n\n\t\tint absIdx = 0;\n\n\t\tfor(int y = 0; y < depth.rows; ++y)\n\t\t{\n\t\t\tfor(int x = 0; x < depth.cols; ++x)\n\t\t\t{\n\t\t\t\t// For pixels r without depth, we need to put the equation\n\t\t\t\t//  U(r) - sum(w_rs * U(s)) = 0\n\t\t\t\t// into matrix form (sum over neighborhood of r).\n\t\t\t\t// For pixels r with depth, we have\n\t\t\t\t//  U(r) = depth.\n\n\t\t\t\tif(depth(y,x) >= 0 || (mask.rows && !mask(y,x)))\n\t\t\t\t\tcontinue; // this pixel is known\n\n\t\t\t\touterIndices.push_back(innerIndices.size());\n\n\t\t\t\tint nWin = 0;\n\n\t\t\t\tfor(int wy = std::max(0, y - winRad); wy < std::min(y + winRad + 1, depth.rows); ++wy)\n\t\t\t\t{\n\t\t\t\t\tfor(int wx = std::max(0, x - winRad); wx < std::min(x + winRad + 1, depth.cols); ++wx)\n\t\t\t\t\t{\n#if REDUCED_NEIGHBORHOOD\n\t\t\t\t\t\tif(std::abs(wx-x) == 1 && std::abs(wy-y) == 1)\n\t\t\t\t\t\t\tcontinue;\n#endif\n\n\t\t\t\t\t\tif(wx == x && wy == y)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tcols[nWin] = mapImgToIdx(wy, wx);\n\t\t\t\t\t\tgvals[nWin] = gray(wy, wx);\n\t\t\t\t\t\twinDepth[nWin] = depth(wy,wx);\n\n\t\t\t\t\t\tauto& color = rgb.at<cv::Vec3b>(y,x);\n\t\t\t\t\t\trgbWin[nWin] = Eigen::Vector3f((float)color[0] / 255, (float)color[1]/255, (float)color[2]/255);\n\n\t\t\t\t\t\tnWin++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// center pixel\n\t\t\t\tfloat curVal = gray(y, x);\n\t\t\t\tgvals[nWin] = curVal;\n\n\t\t\t\tauto& color = rgb.at<cv::Vec3b>(y,x);\n\t\t\t\tauto ownColor = Eigen::Vector3f((float)color[0] / 255, (float)color[1]/255, (float)color[2]/255);\n\n\t\t\t\t// Calculate variance\n\t\t\t\tfloat mean = gvals.mean();\n\t\t\t\tEigen::VectorXf dev = gvals - Eigen::VectorXf::Constant(gvals.rows(), mean);\n\t\t\t\tfloat c_var = (dev.array()*dev.array()).mean();\n\n\t\t\t\tfloat csig = normalizeWithVariance ? std::max(c_var, 0.0000002f) : 1.0f;\n\n\t\t\t\tEigen::ArrayXf tmp(nWin);\n\t\t\t\tif(distance == DepthFiller::CD_GRAYSCALE)\n\t\t\t\t{\n\t\t\t\t\ttmp = gvals.head(nWin).array() - curVal;\n\t\t\t\t\ttmp = (tmp * tmp).pow(distExponent);\n\t\t\t\t}\n\t\t\t\telse if(distance == DepthFiller::CD_RGB)\n\t\t\t\t{\n\t\t\t\t\t// RGB distance\n\t\t\t\t\tfor(int i = 0; i < nWin; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\ttmp[i] = std::pow((ownColor - rgbWin[i]).squaredNorm(), distExponent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttmp *= distScale;\n\n\t\t\t\tgvals.head(nWin) = (- tmp / csig).exp().matrix();\n\n\t\t\t\tfloat s = gvals.head(nWin).sum();\n\t\t\t\tif(s > 0)\n\t\t\t\t{\n\t\t\t\t\tgvals.head(nWin) /= s;\n\t\t\t\t}\n\n\t\t\t\tbool self = false;\n\t\t\t\tfor(int i = 0; i < nWin; ++i)\n\t\t\t\t{\n\t\t\t\t\tif(!self && cols[i] > absIdx)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Now the self-reference U(r) (along the diagonal).\n\t\t\t\t\t\tinnerIndices.push_back(absIdx);\n\t\t\t\t\t\tvalues.push_back(1.0);\n\t\t\t\t\t\tself = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(cols[i] >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t// relation to other unknown pixel...\n\t\t\t\t\t\tinnerIndices.push_back(cols[i]);\n\t\t\t\t\t\tvalues.push_back(-gvals[i]);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// relation to fixed pixel => put on rhs\n\t\t\t\t\t\tb[absIdx] += gvals[i] * winDepth[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(!self)\n\t\t\t\t{\n\t\t\t\t\tinnerIndices.push_back(absIdx);\n\t\t\t\t\tvalues.push_back(1.0);\n\t\t\t\t}\n\n\t\t\t\tabsIdx++;\n\t\t\t}\n\t\t}\n\t}\n\n\touterIndices.push_back(innerIndices.size());\n\n\t// Create Eigen matrix from A\n\tEigen::MappedSparseMatrix<SolveType, Eigen::RowMajor> A(\n\t\tnumUnknown, numUnknown,\n\t\tvalues.size(),\n\t\touterIndices.data(), innerIndices.data(),\n\t\tvalues.data()\n\t);\n\t{\n\t\tScopeTimer timer(\"sparse matrix\");\n\n\t\t// Check CSR format\n\t\tif(outerIndices.size() != numUnknown+1)\n\t\t\tthrow std::runtime_error(\"outer indices has invalid size\");\n\n\t\tprintf(\"numUnknown: %u, non-zero: %lu\\n\", numUnknown, values.size());\n\n\t\tfor(unsigned int i = 0; i < numUnknown; ++i)\n\t\t{\n\t\t\tint rowStart = outerIndices[i];\n\t\t\tint nextRowStart = outerIndices[i+1];\n\n\t\t\tif(rowStart > nextRowStart)\n\t\t\t\tthrow std::runtime_error(\"outer indices are non-monotonic\");\n\n\t\t\tif(rowStart >= (int)values.size() || rowStart < 0)\n\t\t\t\tthrow std::runtime_error(\"invalid start idx\");\n\n\t\t\tif(nextRowStart > (int)values.size() || nextRowStart < 0)\n\t\t\t\tthrow std::runtime_error(\"invalid end idx\");\n\n\t\t\tint lastOne = -1;\n\t\t\tfor(int j = rowStart; j < nextRowStart; ++j)\n\t\t\t{\n\t\t\t\tint col = innerIndices[j];\n\t\t\t\tif(col < 0 || col >= (int)numUnknown)\n\t\t\t\t\tthrow std::runtime_error(\"invalid inner index\");\n\n\t\t\t\tif(col <= lastOne)\n\t\t\t\t\tthrow std::runtime_error(\"non-monotonic inner index\");\n\n\t\t\t\tlastOne = col;\n\t\t\t}\n\t\t}\n\n\t\tif(DUMP_MATRICES)\n\t\t{\n\t\t\tEigen::saveMarket(A, \"/tmp/filler_A.mtx\");\n\t\t\tEigen::saveMarketVector(b, \"/tmp/filler_A_b.mtx\");\n\n\t\t\t// Dump upper left corner of matrix as image\n\t\t\tconst int IMG_SIZE = std::min<int>(5000, A.rows());\n\t\t\tcv::Mat_<uint8_t> vis(IMG_SIZE, IMG_SIZE, 255);\n\t\t\tEigen::MatrixXf reduced(IMG_SIZE, IMG_SIZE);\n\t\t\treduced.fill(0);\n\n\t\t\tfor (int k=0; k<A.outerSize(); ++k)\n\t\t\t{\n\t\t\t\tfor (Eigen::MappedSparseMatrix<SolveType, Eigen::RowMajor>::InnerIterator it(A,k); it; ++it)\n\t\t\t\t{\n\t\t\t\t\tif(it.row() < 0 || it.col() < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tfprintf(stderr, \"Invalid idx!\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif(it.row() < IMG_SIZE && it.col() < IMG_SIZE)\n\t\t\t\t\t{\n\t\t\t\t\t\tvis(it.row(), it.col()) = 0;\n\t\t\t\t\t\treduced(it.row(), it.col()) = it.value();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcv::imwrite(\"/tmp/filler_A.png\", vis);\n\n\t\t\tEigen::MatrixXf inverse = reduced.inverse();\n\t\t\tcv::Mat_<uint8_t> inverseVis(IMG_SIZE, IMG_SIZE);\n\t\t\tfor(int i = 0; i < IMG_SIZE; ++i)\n\t\t\t{\n\t\t\t\tfor(int j = 0; j < IMG_SIZE; ++j)\n\t\t\t\t{\n\t\t\t\t\tinverseVis(i,j) = (std::abs(inverse(i,j)) > 1e-6) ? 0 : 255;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcv::imwrite(\"/tmp/filler_Ainv.png\", inverseVis);\n\t\t}\n\t}\n\n\t{\n\t\tScopeTimer timer(\"solving\");\n\n#if KLU_SUPPORT\n// \t\tif(sameStructure)\n// \t\t\tsolver.refactorize(A);\n// \t\telse\n\t\t\tsolver.compute(A);\n#else\n\t\tsolver.compute(Eigen::SparseMatrix<SolveType>(A));\n#endif\n\t\tif(solver.info() != Eigen::Success)\n\t\t{\n\t\t\tfprintf(stderr, \"Failed to solve system!\\n\");\n\t\t}\n\t\tnewDepth = solver.solve(b);\n\t}\n}\n\n\n\nDepthFiller::DepthFiller()\n : m_d(new DepthFillerPrivate)\n{\n}\n\nDepthFiller::~DepthFiller()\n{\n}\n\nvoid DepthFiller::setColorDistance(ColorDistance dist)\n{\n\tm_d->distance = dist;\n}\n\nvoid DepthFiller::setNormalizeWithVariance(bool on)\n{\n\tm_d->normalizeWithVariance = on;\n}\n\nvoid DepthFiller::setDistanceExponent(float exp)\n{\n\tm_d->distExponent = exp;\n}\n\nvoid DepthFiller::setDistanceScale(float scale)\n{\n\tm_d->distScale = scale;\n}\n\ncv::Mat DepthFiller::fillDepth(const cv::Mat& input, const cv::Mat& rgb, bool sameStructure, const cv::Mat_<uint8_t>& mask)\n{\n\tm_d->rows = input.rows;\n\tm_d->cols = input.cols;\n\n\t// Normalize depth image to [0, 1]\n\tm_d->depth = cv::Mat_<float>(input.size());\n\tfloat oldMin = std::numeric_limits<float>::infinity();\n\tfloat oldMax = -std::numeric_limits<float>::infinity();\n\n\tm_d->numUnknown = 0;\n\n\t{\n\t\tScopeTimer timer(\"normalize depth image\");\n\n\t\tfor(int y = 0; y < input.rows; ++y)\n\t\t{\n\t\t\tfor(int x = 0; x < input.cols; ++x)\n\t\t\t{\n\t\t\t\tfloat ival = input.at<float>(y,x);\n\t\t\t\tif(!std::isfinite(ival) || ival == 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\toldMin = std::min<float>(oldMin, ival);\n\t\t\t\toldMax = std::max<float>(oldMax, ival);\n\t\t\t}\n\t\t}\n\n\t\tfor(int y = 0; y < input.rows; ++y)\n\t\t{\n\t\t\tfor(int x = 0; x < input.cols; ++x)\n\t\t\t{\n\t\t\t\tfloat ival = input.at<float>(y,x);\n\t\t\t\tif(!std::isfinite(ival) || ival == 0)\n\t\t\t\t{\n\t\t\t\t\tm_d->depth(y,x) = -1;\n\n\t\t\t\t\tif(!mask.rows || mask(y,x))\n\t\t\t\t\t\tm_d->numUnknown++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tm_d->depth(y,x) = ((float)(ival - oldMin)) / (oldMax - oldMin);\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"depth: %d by %d, numUnknown: %u\\n\", m_d->depth.cols, m_d->depth.rows, m_d->numUnknown);\n\n\tm_d->rgb = rgb;\n\tm_d->mask = mask;\n\n\tm_d->solve();\n\n\tcv::Mat_<float> ret(input.size());\n\tint idx = 0;\n\tfor(int y = 0; y < ret.rows; ++y)\n\t{\n\t\tfor(int x = 0; x < ret.cols; ++x)\n\t\t{\n\t\t\tfloat ival = input.at<float>(y,x);\n\t\t\tif(std::isfinite(ival) || (mask.rows && !mask(y,x)))\n\t\t\t\tret(y,x) = ival;\n\t\t\telse\n\t\t\t{\n\t\t\t\tret(y,x) = oldMin + (oldMax - oldMin) * m_d->newDepth[idx];\n\t\t\t\tidx++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ret;\n}\n\nvoid DepthFiller::erodeDepth(const cv::Mat_<float>& input, cv::Mat_<float>& output, int kernelSize)\n{\n\tcv::Mat_<uint8_t> valid(input.rows, input.cols);\n\tfor(int y = 0; y < input.rows; ++y)\n\t{\n\t\tfor(int x = 0; x < input.cols; ++x)\n\t\t{\n\t\t\tvalid(y,x) = std::isfinite(input(y,x));\n\t\t}\n\t}\n\n\tcv::Mat_<uint8_t> erodedValid;\n\tcv::Mat kernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(2*kernelSize+1, 2*kernelSize+1), cv::Point(kernelSize, kernelSize));\n\tcv::erode(valid, erodedValid, kernel);\n\n\tfor(int y = 0; y < valid.rows; ++y)\n\t{\n\t\tfor(int x = 0; x < valid.cols; ++x)\n\t\t{\n\t\t\tif(!erodedValid(y,x))\n\t\t\t\toutput(y,x) = NAN;\n\t\t}\n\t}\n}\n\ncv::Mat_<float> DepthFiller::prefill(const cv::Mat_<float>& input)\n{\n\tcv::Mat_<float> ret;\n\tinput.copyTo(ret);\n\n\tEigen::Matrix<float, 9, 1> values;\n\tcv::Mat_<bool> valid(3,3);\n\n\tfor(int y = 1; y < input.rows-1; ++y)\n\t{\n\t\tfor(int x = 1; x < input.cols-1; ++x)\n\t\t{\n\t\t\tif(std::isfinite(input(y,x)))\n\t\t\t{\n\t\t\t\tret(y,x) = input(y,x);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tvalid = false;\n\n\t\t\tint numValid = 0;\n\n\t\t\tfor(int dy = -1; dy <= 1; ++dy)\n\t\t\t{\n\t\t\t\tfor(int dx = -1; dx <= 1; ++dx)\n\t\t\t\t{\n\t\t\t\t\tif(std::isfinite(input(y+dy,x+dx)))\n\t\t\t\t\t{\n\t\t\t\t\t\tvalid[dy+1][dx+1] = true;\n\n\t\t\t\t\t\tvalues[numValid] = input(y+dy,x+dx);\n\t\t\t\t\t\tnumValid++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool corners[4] = {\n\t\t\t\tvalid[0][0] || valid[0][1] || valid[1][0],\n\t\t\t\tvalid[2][0] || valid[1][0] || valid[2][1],\n\t\t\t\tvalid[0][2] || valid[1][2] || valid[0][1],\n\t\t\t\tvalid[2][2] || valid[1][2] || valid[2][1]\n\t\t\t};\n\n\t\t\tif(corners[0] && corners[1] && corners[2] && corners[3]\n\t\t\t\t&& values.head(numValid).maxCoeff() - values.head(numValid).minCoeff() < 0.05)\n\t\t\t{\n\t\t\t\tret(y,x) = values.head(numValid).mean();\n\t\t\t}\n\t\t\telse\n\t\t\t\tret(y,x) = NAN;\n\t\t}\n\t}\n\n\treturn ret;\n}\n\nvoid DepthFiller::dumpSystem(const std::string& prefix)\n{\n\tEigen::MappedSparseMatrix<SolveType, Eigen::RowMajor> A(\n\t\tm_d->numUnknown, m_d->numUnknown,\n\t\tm_d->values.size(),\n\t\tm_d->outerIndices.data(), m_d->innerIndices.data(),\n\t\tm_d->values.data()\n\t);\n\n\tEigen::saveMarket(A, prefix + \".mtx\");\n\tEigen::saveMarketVector(m_d->b, prefix + \"_b.mtx\");\n}\n\n}\n", "meta": {"hexsha": "01ae1865124dad3e8e08d427500713a4fe330cde", "size": 13043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depth_filler/src/depth_filler.cpp", "max_stars_repo_name": "warehouse-picking-automation-challenges/nimbro_picking", "max_stars_repo_head_hexsha": "857eee602beea9eebee45bbb67fce423b28f9db6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2017-11-02T03:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T19:40:15.000Z", "max_issues_repo_path": "depth_filler/src/depth_filler.cpp", "max_issues_repo_name": "warehouse-picking-automation-challenges/nimbro_picking", "max_issues_repo_head_hexsha": "857eee602beea9eebee45bbb67fce423b28f9db6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "depth_filler/src/depth_filler.cpp", "max_forks_repo_name": "warehouse-picking-automation-challenges/nimbro_picking", "max_forks_repo_head_hexsha": "857eee602beea9eebee45bbb67fce423b28f9db6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-16T02:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T14:06:35.000Z", "avg_line_length": 22.7229965157, "max_line_length": 140, "alphanum_fraction": 0.6143525263, "num_tokens": 4236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460027, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5882897745751727}}
{"text": "/*!\n * Copyright (C) tkornuta, IBM Corporation 2015-2019\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file Matrix.hpp\n * \\brief \n * \\author tkornut\n * \\date Mar 7, 2016\n */\n\n#ifndef SRC_TYPES_MATRIX_HPP_\n#define SRC_TYPES_MATRIX_HPP_\n\n#include <Eigen/Dense>\n#include <random>\n#include <memory> // std::shared_ptr\n\n#include <boost/serialization/serialization.hpp>\n// include this header to serialize vectors\n#include <boost/serialization/vector.hpp>\n// include this header to serialize arrays\n#include <boost/serialization/array.hpp>\n#include <boost/serialization/version.hpp>\n\n// Forward declaration of class boost::serialization::access\nnamespace boost {\nnamespace serialization {\nclass access;\n}//: serialization\n}//: access\n\nnamespace mic {\nnamespace types {\n\n// Forward declaration of a class Tensor.\ntemplate<typename T>\nclass Tensor;\n\n// Forward declaration of a class Vector.\n//template<typename T>\n//class Vector;\n\n/*!\n * \\brief Template-typed Matrix of dynamic size.\n * Uses OpenBLAS if found by CMAKE - overloaded, specializations of * operator for types: float, double.\n *\n * \\tparam T Template parameter denoting elementary type of data used (int, float, double etc.)\n * \\date Mar 7, 2016\n * \\author tkornuta\n */\ntemplate<typename T>\nclass Matrix : public Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> {\npublic:\n\n\t/*!\n\t * Constructor. Calls default Eigen::MatrixXf constructor.\n\t */\n\tEIGEN_STRONG_INLINE\n\tMatrix() :\n\t\tEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>() {\n\t}\n\n\t/*!\n\t * Constructor. Calls default Eigen::MatrixXf constructor.\n\t * @param Rows_ Number of rows.\n\t * @param Cols_ Number of columns.\n\t */\n\tEIGEN_STRONG_INLINE\n\tMatrix(int Rows_, int Cols_) :\n\t\tEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>(Rows_, Cols_) {\n\t\tthis->setZero();\n\t}\n\n\t/*!\n\t * Copying constructor on the basis of a vector. Sets dimensions to rows = size(), cols = 1.\n\t * @param vector_ Vector\n\t */\n\tEIGEN_STRONG_INLINE\n\tMatrix(const Eigen::Matrix<T, Eigen::Dynamic, 1>& vector_) :\n\t\tEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>(vector_.size(), 1)\n\t{\n\t\t// Copy the whole vector block.\n\t\tmemcpy(this->data(), vector_.data(), vector_.size() * sizeof(T));\n\t}\n\n\t/*!\n\t * Copying constructor on the basis of another matrix.\n\t * @param matrix_ Matrix to be copied.\n\t */\n\tEIGEN_STRONG_INLINE\n\tMatrix(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& matrix_) :\n\t\tEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>(matrix_.rows(), matrix_.cols())\n\t{\n\t\t// Copy the whole vector block.\n\t\tmemcpy(this->data(), matrix_.data(), matrix_.size() * sizeof(T));\n\t}\n\n\t/*!\n\t * Copying constructor on the basis of a tensor. Copies dimensions and data.\n\t * Note: tensor must be 2D.\n\t * @param tensor_ Tensor\n\t */\n\tEIGEN_STRONG_INLINE\n\tMatrix(mic::types::Tensor<T>& tensor_) :\n\t\tEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>(tensor_.dim(1), tensor_.dim(0))\n\t{\n\t\t// Tensor must be 2D!\n\t\tassert(tensor_.dims().size() == 2);\n\t\t// Copy the whole block.\n\t\tmemcpy(this->data(), tensor_.data(), tensor_.size() * sizeof(T));\n\t}\n\n\t/*\n\t * Overloaded assignment operator - calls base operator.\n\t * @param mat_ Input matrix\n\t * @return An exact copy of the input matrix.\n\t */\n/*\tEIGEN_STRONG_INLINE\n\tconst Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& operator =(const mic::types::Matrix<T>& mat_) {\n\t\t// Using base EIGEN operator =\n\t\treturn Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::operator=(mat_);\n\t}*/\n\n\n/*\tEIGEN_STRONG_INLINE\n\tconst Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& operator =(const Eigen::Matrix<T, Eigen::Dynamic, 1>& vector_) {\n\t\t// Using base EIGEN operator =\n\t\treturn Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::operator=(vector_);\n\t}*/\n\n\t/*!\n\t * Overloaded assignment operator - calls base operator.\n\t * @param mat_ Input matrix\n\t * @return An exact copy of the input matrix.\n\t */\n\tEIGEN_STRONG_INLINE\n\tEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& operator =(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& mat_) {\n\t\t// Using base EIGEN operator =\n\t\tEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::operator=(mat_);\n\t\treturn *this;\n\t}\n\n\n\t/*!\n\t * Overloaded multiplication operator.\n\t * @param mat_ Input matrix\n\t * @return Resulting matrix - multiplication of this and input mat_.\n\t */\n\tEIGEN_STRONG_INLINE\n\tEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> operator *(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& mat_) {\n\t\t// Calling base EIGEN operator *\n\t\t//printf(\"Calling base EIGEN operator *\\n\");\n\t\treturn Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::operator*(mat_);\n\t}\n\n\n\t/*!\n\t * Sets values of all element to the value given as parameter.\n\t * @param value_ The value to be set.\n\t */\n\tvoid setValue(T value_) {\n\t\t// Get access to data.\n\t\tT* data_ptr = this->data();\n\n#pragma omp parallel for\n\t\tfor (size_t i = 0; i < (size_t) (this->rows() * this->cols()); i++)\n\t\t\tdata_ptr[i] = value_;\n\t}\n\n\t/*!\n\t * Enumerates - sets values of elements to their indices.\n\t */\n\tvoid enumerate() {\n\t\t// Get access to data.\n\t\tT* data_ptr = this->data();\n\n#pragma omp parallel for\n\t\tfor (size_t i = 0; i < (size_t)this->size(); i++)\n\t\t\tdata_ptr[i] = i;\n\t}\n\n\t/*!\n\t * Set values of all matrix elements to random with a normal distribution.\n\t * @param mean Mean\n\t * @param stddev Variance\n\t */\n\tvoid randn(T mean = 0, T stddev = 1) {\n\n\t\t// Initialize random number generator with normal distribution.\n\t\tstd::random_device rd;\n\t\tstd::mt19937 mt(rd());\n\t\tstd::normal_distribution<T> dist(mean, stddev);\n\n\t\t// Get access to data.\n\t\tT* data_ptr = this->data();\n\n#pragma omp parallel for\n\t\tfor (size_t i = 0; i < (size_t) (this->rows() * this->cols()); i++) {\n\t\t\tdata_ptr[i] = (T)dist(mt);\n\t\t}\n\t}\n\n\t/*!\n\t * Set values of all matrix elements to random numbers from range <min, max> - uniform distribution.\n\t * @param min Min value.\n\t * @param max Max value.\n\t * @return Random real value.\n\t */\n\tvoid rand(T min = 0, T max = 1) {\n\n\t\t// Initialize random number generator with normal distribution.\n\t\tstd::random_device rd;\n\t\tstd::mt19937 mt(rd());\n\t\tstd::uniform_real_distribution<T> dist(min, max);\n\n\t\t// Get access to data.\n\t\tT* data_ptr = this->data();\n\n#pragma omp parallel for\n\t\tfor (size_t i = 0; i < (size_t) (this->rows() * this->cols()); i++) {\n\t\t\tdata_ptr[i] = (T)dist(rd);\n\t\t}\n\t}\n\n\n\t/*!\n\t * Applies elementwise function to all matrix elements.\n\t * @param func Function to be applied.\n\t */\n\tvoid elementwiseFunction(T (*func)(T)) {\n\n\t\t// Get access to data.\n\t\tT* data_ptr = this->data();\n\n\t\t// Apply function to all elements.\n#pragma omp parallel for\n\t\tfor (size_t i = 0; i < (size_t) (this->rows() * this->cols()); i++) {\n\t\t\tdata_ptr[i] = (*func)(data_ptr[i]);\n\t\t} //: for i\n\t}\n\n\t/*!\n\t * Applies elementwise function to all matrix elements passing scalar as function argument.\n\t * @param func Function to be applied.\n\t * @param scalar_ Scalar passed to function as argument.\n\t */\n\tvoid elementwiseFunctionScalar(T (*func)(T, T), T scalar_) {\n\n\t\t// Get access to data.\n\t\tT* data_ptr = this->data();\n\n\t\t// Apply function to all elements.\n#pragma omp parallel for\n\t\tfor (size_t i = 0; i < (size_t) (this->rows() * this->cols()); i++) {\n\t\t\tdata_ptr[i] = (*func)(data_ptr[i], scalar_);\n\t\t} //: for i\n\t}\n\n\t/*!\n\t * Applies elementwise function to all matrix elements and uses additional Matrix mat_ data as function parameter.\n\t * @param func Function to be applied.\n\t * @param mat_ Matrix passed to function as argument.\n\t */\n\tvoid elementwiseFunctionMatrix(T (*func)(T, T), Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> & mat_) {\n\n\t\t// Check dimensions.\n\t\tif ((this->rows() != mat_.rows()) || (this->cols() != mat_.cols()))\n\t\t\tprintf(\"elementwiseFunctionMatrix: dimensions mismatch!\\n\");\n\n\t\t// Get access to data.\n\t\tT* data_ptr = this->data();\n\t\tT* m_data_ptr = mat_.data();\n\n\t\t// Apply function to all elements.\n#pragma omp parallel for\n\t\tfor (size_t i = 0; i < (size_t) (this->rows() * this->cols()); i++) {\n\t\t\tdata_ptr[i] = (*func)(data_ptr[i], m_data_ptr[i]);\n\t\t}//: for i\n\n\t}\n\n\t/*!\n\t * Applies function to all matrix elements and uses additional vector data as function parameter - columnwise.\n\t * @param func Used function\n\t * @param v_ Vector passed to function\n\t */\n\tvoid matrixColumnVectorFunction(T (*func)(T, T),\n\t\t\tEigen::Matrix<T, Eigen::Dynamic, 1>& v_) {\n\n\t\tif (this->rows() != v_.cols())\n\t\t\tprintf(\"matrixColumnVectorFunction: dimensions mismatch\\n\");\n\n\t\t// Get access to data.\n\t\t//float* data_ptr = data();\n\t\t//int rows = this->rows();\n\t\t//int cols = this->cols();\n\t\t//float* vector_data_ptr = v_.data();\n\n#pragma omp parallel for\n\t\tfor (size_t x = 0; x < (size_t)this->cols(); x++) {\n\t\t\tfor (size_t y = 0; y < (size_t)this->rows(); y++) {\n\t\t\t\t//data_ptr[x + y*cols] = (*func)(data_ptr[x + y*cols], vector_data_ptr[x]);\n\t\t\t\t(*this)(y, x) = (*func)((*this)(y, x), v_(y));\n\t\t\t}//: for y\n\t\t}//: for x\n\t}\n\n\t/*!\n\t * Applies function to all matrix elements and uses additional vector data as function parameter - rowwise.\n\t * @param func Used function\n\t * @param v_ Vector passed to function\n\t */\n\tvoid matrixRowVectorFunction(T (*func)(T, T), Eigen::Matrix<T, Eigen::Dynamic, 1>& v_) {\n\n\t\tif (this->cols() != v_.cols())\n\t\t\tprintf(\"matrixRowVectorFunction: dimensions mismatch\\n\");\n\n\t\t// Get access to data.\n\t\t/*float* data_ptr = data();\n\t\t int rows = this->rows();\n\t\t int cols = this->cols();\n\t\t float* vector_data_ptr = v_.data();*/\n\n#pragma omp parallel for\n\t\tfor (size_t x = 0; x < (size_t)this->cols(); x++) {\n\t\t\tfor (size_t y = 0; y < (size_t)this->rows(); y++) {\n\t\t\t\t//h(y,x) += c(x);\n\t\t\t\t//(*this)(y,x) += v_(x);\n\t\t\t\t(*this)(y, x) = (*func)((*this)(y, x), v_(x));\n\t\t\t\t//data_ptr[x + y*cols] = (*func)(data_ptr[x + y*cols], vector_data_ptr[y]);\n\t\t\t}//: for y\n\t\t}//: for x\n\t}\n\n\n\t/*!\n\t * Sets the consecutive columns to be equal to given vector.\n\t * @param in Input vector, that will be \"cloned\".\n\t */\n\tvoid repeatVector(Eigen::Matrix<T, Eigen::Dynamic, 1> &in) {\n#pragma omp parallel for\n\t\tfor (size_t x = 0; x < (size_t)this->cols(); x++) {\n\t\t\tfor (size_t y = 0; y < (size_t)this->rows(); y++) {\n\n\t\t\t\t(*this)(y, x) = in(y);\n\t\t\t}//: y\n\t\t}//: x\n\t}\n\n\t/*!\n\t * Returns a vector of indices indicating maximal elements in consecutive matrix columns (colwise).\n\t * @return Vector of indices.\n\t */\n\tEigen::Matrix<T, Eigen::Dynamic, 1> colwiseReturnMaxIndices() {\n\n\t\tEigen::Matrix<T, Eigen::Dynamic, 1> indices((*this).cols());\n\n\t\tfor (size_t i = 0; i < (size_t)(*this).cols(); i++) {\n\n\t\t\tT current_max_val;\n\t\t\tT index;\n\n\t\t\tfor (size_t j = 0; j < (size_t)(*this).rows(); j++) {\n\n\t\t\t\tif (j == 0 || (*this)(j, i) > current_max_val) {\n\n\t\t\t\t\tindex = j;\n\t\t\t\t\tcurrent_max_val = (*this)(j, i);\n\t\t\t\t}\n\n\t\t\t\tindices(i) = index;\n\n\t\t\t}\n\t\t}\n\n\t\treturn indices;\n\t}\n\n\t/*!\n\t * Calculates the cross entropy as measure of how accurate given matrix (treated as prediction) fits to the desired (target) matrix.\n\t * @param targets_ Desired results (targets) in the form of a matrix of answers.\n\t * @return\n\t */\n\tT calculateCrossEntropy(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& targets_) {\n\n\t\tT ce = 0.0;\n\t\tEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> error(this->rows(), this->cols());\n\n\t\t//check what has happened and get information content for that event\n\t\terror.array() = - (this->unaryExpr(std::ptr_fun(::logf)).array() * targets_.array());\n\n\t\t// Sum the errors.\n\t\tce = error.sum();\n\n\t\treturn ce;\n\t}\n\n\t/****************** ARMADILLO COMPATIBILITY *********************************/\n\n\t/*!\n\t * Set zeros.\n\t */\n\tvoid zeros (){\n\t\tthis->setZero();\n\t}\n\n    T& operator [](int idx) {\n        return this->data()[idx];\n    }\n\n    T operator [](int idx) const {\n        return this->data()[idx];\n    }\n\nprivate:\n\n\t// Friend class - required for using boost serialization.\n    friend class boost::serialization::access;\n\n    /*!\n     * Serialization save - saves the matrix object to archive.\n     * @param ar Used archive.\n     * @param version Version of the matrix class.\n     */\n\ttemplate<class Archive>\n\tvoid save(Archive & ar, const unsigned int version) const {\n    \tsize_t rows, cols;\n    \trows = this->rows();\n    \tcols = this->cols();\n\t\tar & rows;\n\t\tar & cols;\n        // Save elements.\n        size_t elements = (size_t)(this->rows() * this->cols());\n\t\tT* data_ptr = (T*)this->data();\n        ar & boost::serialization::make_array<T>(data_ptr, elements);\n     }\n\n    /*!\n     * Serialization load - loads the matrix object to archive.\n     * @param ar Used archive.\n     * @param version Version of the matrix class.\n     */\n     template<class Archive>\n     void load(Archive & ar, const unsigned int version) {\n    \tsize_t rows, cols;\n\t\tar & rows;\n\t\tar & cols;\n\t\t// Allocate memory - resize.\n\t\tthis->resize(rows, cols);\n\t\t// Load elements\n        size_t elements = (size_t)(this->rows() * this->cols());\n\t\tT* data_ptr = this->data();\n\t\tar & boost::serialization::make_array<T>(data_ptr, elements);\n     }\n\n     // The serialization must be splited as load requires to allocate the memory.\n     BOOST_SERIALIZATION_SPLIT_MEMBER()\n\n};\n\n\n/*!\n * \\brief Typedef for a shared pointer to template-typed dynamic matrices.\n * \\author tkornuta\n */\ntemplate<typename T>\nusing MatrixPtr = typename std::shared_ptr< mic::types::Matrix<T> >;\n\n}//: namespace types\n}//: namespace mic\n\n\n\n// Just in the case that something important will change in the matrix class - set version.\nBOOST_CLASS_VERSION(mic::types::Matrix<bool>, 1)\nBOOST_CLASS_VERSION(mic::types::Matrix<short>, 1)\nBOOST_CLASS_VERSION(mic::types::Matrix<int>, 1)\nBOOST_CLASS_VERSION(mic::types::Matrix<long>, 1)\nBOOST_CLASS_VERSION(mic::types::Matrix<float>, 1)\nBOOST_CLASS_VERSION(mic::types::Matrix<double>, 1)\n\n#endif /* SRC_TYPES_MATRIX_HPP_ */\n", "meta": {"hexsha": "99518cec49351126c1919df5fc199b34824fc91f", "size": 14069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/types/Matrix.hpp", "max_stars_repo_name": "kant/mi-algorithms", "max_stars_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/types/Matrix.hpp", "max_issues_repo_name": "kant/mi-algorithms", "max_issues_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/types/Matrix.hpp", "max_forks_repo_name": "kant/mi-algorithms", "max_forks_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-30T09:51:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T09:51:14.000Z", "avg_line_length": 28.4222222222, "max_line_length": 133, "alphanum_fraction": 0.6517876182, "num_tokens": 3901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370423, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5882646194211668}}
{"text": "#include \"gaussianXd.h\"\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n\nusing namespace Eigen;\n\nint main(){\n    VectorXd mean(2, 1);\n    mean << 2,\n            17;\n    MatrixXd covariance(2, 2);\n    covariance << 10.0, 0,\n                0.0, 4.0;\n    filters::MultivariateGaussian dist(mean, covariance);\n\n    sciplot::Vec x = sciplot::linspace(-10, 15, 0.2);\n    sciplot::Vec y = sciplot::linspace(5, 25, 0.2);\n    std::vector<double> z;\n    for(auto x_: x){\n        for(auto y_: y){\n            VectorXd vec(2, 1);\n            vec << x_,\n                   y_;\n\n            double z_ = dist.probability(vec);\n            z.push_back(z_);\n        }\n    }\n    for(auto val: z){\n        std::cout << val << std::endl;\n    }\n}", "meta": {"hexsha": "f23c006b458a5c8eef361a7c5d8007fca298f91d", "size": 739, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_3.cpp", "max_stars_repo_name": "SuhrudhSarathy/filters", "max_stars_repo_head_hexsha": "25b025a97e1edcf31a0195cb956c41f6d82e7764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_3.cpp", "max_issues_repo_name": "SuhrudhSarathy/filters", "max_issues_repo_head_hexsha": "25b025a97e1edcf31a0195cb956c41f6d82e7764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_3.cpp", "max_forks_repo_name": "SuhrudhSarathy/filters", "max_forks_repo_head_hexsha": "25b025a97e1edcf31a0195cb956c41f6d82e7764", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3939393939, "max_line_length": 57, "alphanum_fraction": 0.5115020298, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5882490706208678}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/function/ellint_rf.hpp>\n#include <boost/math/special_functions/ellint_rf.hpp>\n#include <eve/wide.hpp>\n\n\nTTS_CASE_TPL(\"Check eve::ellint_rf behavior\", EVE_TYPE)\n{\n  using elt_t = eve::element_type_t<T>;\n  TTS_ULP_EQUAL(eve::ellint_rf(T(0.2), T(0.4), T(0)),  T(boost::math::ellint_rf(elt_t(0.2), elt_t(0.4), elt_t(0))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rf(T(1.5), T(1), T(7)),T(boost::math::ellint_rf(elt_t(1.5), elt_t(1), elt_t(7))), 1.0);\n  TTS_ULP_EQUAL(eve::ellint_rf(T(2), T(0), T(7)),  T(boost::math::ellint_rf(elt_t(2), elt_t(0), elt_t(7))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rf(T(0), T(5), T(7)),  T(boost::math::ellint_rf(elt_t(0), elt_t(5), elt_t(7))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rf(T(2), T(5), T(7)),  T(boost::math::ellint_rf(elt_t(2), elt_t(5), elt_t(7))),   1.0);\n                                                                        }\n", "meta": {"hexsha": "12b955b1ebe7fecfed90a332df2d12abead48a05", "size": 1197, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/elliptic/ellint_rf/regular/ellint_rf.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/elliptic/ellint_rf/regular/ellint_rf.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/elliptic/ellint_rf/regular/ellint_rf.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.4090909091, "max_line_length": 123, "alphanum_fraction": 0.5054302423, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5882490584232924}}
{"text": "\n\n#include \"bio/math.h\"\n#include \"bio/iterator.h\"\nUSING_BIO_NS\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/parameterized_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/assign/list_of.hpp>\nusing namespace boost;\nusing namespace boost::assign;\nusing boost::unit_test::test_suite;\n\n#include <iostream>\nusing namespace std;\n\n#include <gsl/gsl_sf_exp.h>\n\n\n//#define VERBOSE_CHECKING\n\n\n\n\ntypedef vector< unsigned > obs_vec_t;\n\nconst std::vector< double > alpha(4, 1.0);\nconst vector< obs_vec_t > obs_vec = list_of< vector< unsigned > >\n\t(list_of< unsigned > (0) (0) (0) (0))\n\t(list_of< unsigned > (0) (1) (1) (0))\n\t(list_of< unsigned > (0) (2) (0) (0))\n\t(list_of< unsigned > (1) (1) (1) (1))\n\t(list_of< unsigned > (4) (4) (4) (4))\n\t(list_of< unsigned > (0) (0) (0) (4))\n\t(list_of< unsigned > (0) (0) (0) (8))\n\t(list_of< unsigned > (1) (1) (1) (13))\n\t(list_of< unsigned > (100) (97) (103) (101))\n\t;\n\nconst vector< unsigned > total_vec = list_of< unsigned >\n\t(1)\n\t(2)\n\t(3)\n\t(10)\n\t(30)\n\t;\n\nvoid\ncheck_calc_ln_gamma_factor_total(const unsigned total)\n{\n\tcout << \"******* check_calc_ln_gamma_factor(): total = \" << total << \"\\n\";\n\n\tobs_vec_t obs(4);\n\n\tdouble uniform = 0.0;\n\tdouble dirichlet = 0.0;\n\n\tfor (obs[0] = 0; obs[0] != total + 1; ++obs[0])\n\t{\n\t\tfor (obs[1] = 0; obs[0] + obs[1] != total + 1; ++obs[1])\n\t\t{\n\t\t\tfor (obs[2] = 0; obs[0] + obs[1] + obs[2] != total + 1; ++obs[2])\n\t\t\t{\n\t\t\t\tobs[3] = total - obs[0] - obs[1] - obs[2];\n\n\t\t\t\tBOOST_ASSERT(unsigned(std::accumulate(obs.begin(), obs.end(), 0)) == total);\n\n\t\t\t\tconst double ln_uniform = calc_multinomial_ln_likelihood_uniform_dist(obs.begin(), obs.end());\n\t\t\t\tdouble p = 0.25;\n\t\t\t\tBOOST_CHECK_CLOSE(\n\t\t\t\t\tln_uniform,\n\t\t\t\t\tcalc_multinomial_ln_likelihood(obs.begin(), obs.end(), single_value_iterator< double >( p )),\n\t\t\t\t\t0.001);\n\n\t\t\t\tuniform += BIO_GSL_EXP(ln_uniform);\n\t\t\t\tdirichlet += BIO_GSL_EXP(calc_multinomial_ln_likelihood_dirichlet_prior(obs.begin(), obs.end(), alpha.begin()));\n\t\t\t}\n\t\t}\n\t}\n\n\tBOOST_CHECK_CLOSE(uniform, 1.0, 0.001);\n\tBOOST_CHECK_CLOSE(dirichlet, 1.0, 0.001);\n}\n\nvoid\ncheck_calc_ln_gamma_factor(const obs_vec_t & obs)\n{\n\tcout << \"******* check_calc_ln_gamma_factor()\" << endl;\n\n\tboost::io::ios_base_all_saver ias(cout);\n\n\n\n\tconst double n_choose = gsl_sf_exp(calc_ln_n_choose(obs.begin(), obs.end()));\n\tconst double uniform_ll = calc_multinomial_ln_likelihood_uniform_dist(obs.begin(), obs.end());\n\tconst double dirichlet_ll = calc_multinomial_ln_likelihood_dirichlet_prior(obs.begin(), obs.end(), alpha.begin());\n\n\tcout.setf(ios::left, ios::adjustfield);\n\tcout.setf(ios::fixed, ios::floatfield);\n\n#ifdef VERBOSE_CHECKING\n\tcopy(obs.begin(), obs.end(), ostream_iterator< unsigned >(cout , \",\"));\n\tcout\n\t\t<< \" \" << setw(6) << uniform_ll\n\t\t<< \" \" << setw(6) << dirichlet_ll\n\t\t<< \" \" << setw(6) << uniform_ll - dirichlet_ll\n\t\t<< \"\\n\";\n#endif\n\n}\n\n\n\nvoid\nregister_math_tests(boost::unit_test::test_suite * test)\n{\n\ttest->add( BOOST_PARAM_TEST_CASE( &check_calc_ln_gamma_factor, obs_vec.begin(), obs_vec.end() ), 0);\n\ttest->add( BOOST_PARAM_TEST_CASE( &check_calc_ln_gamma_factor_total, total_vec.begin(), total_vec.end() ), 0);\n}\n", "meta": {"hexsha": "b3a386ac95581a1867b38e4e68841cc6cd715d52", "size": 3144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/test/check_math.cpp", "max_stars_repo_name": "JohnReid/biopsy", "max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_stars_repo_licenses": ["MIT"], "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++/test/check_math.cpp", "max_issues_repo_name": "JohnReid/biopsy", "max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_issues_repo_licenses": ["MIT"], "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++/test/check_math.cpp", "max_forks_repo_name": "JohnReid/biopsy", "max_forks_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_forks_repo_licenses": ["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.9834710744, "max_line_length": 116, "alphanum_fraction": 0.6618956743, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5882138318023117}}
{"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": "// Copyright Andr\u00e1s Vukics 2006\u20132020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#include <MathExtensions.h>\n#include <Pars.h>\n\n#include <boost/math/special_functions/factorials.hpp>\n\nusing namespace std;\nusing namespace boost::math;\nusing namespace cppqedutils;\n\nint main(int argc, char* argv[])\n{\n  parameters::Table p;\n  dcomp         & alpha=p.add(\"alpha\",\"\",dcomp(-1,2));\n  unsigned long & max  =p.add(\"max\"  ,\"\",200ul      );\n  \n  update(p,argc,argv,\"--\");\n  \n  cerr<<max_factorial<double>::value<<\" \"<<max_factorial<long double>::value<<endl;\n  for (unsigned long n=1; n<max; ++n) {\n    const dcomp\n      straight(n<max_factorial<double>::value ? pow(alpha,n)/sqrt(factorial<double>(n)) : dcomp()),\n      stirling(n ? pow(2*n*PI,-.25)*pow(alpha/sqrt(n/EULER),n) : dcomp(1.));\n    cout<<n<<\" \"<<straight.real()<<\" \"<<straight.imag()<<\" \"<<stirling.real()<<\" \"<<stirling.imag()<<\" \"<<abs((straight-stirling)/(straight+stirling))<<endl;\n  }\n}\n", "meta": {"hexsha": "b835dc5dc12bb1e6b2ba998f9e00255b56727894", "size": 999, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDcore/examples/CoherentElementTest.cc", "max_stars_repo_name": "vukics/cppqed", "max_stars_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T14:00:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T15:12:11.000Z", "max_issues_repo_path": "CPPQEDcore/examples/CoherentElementTest.cc", "max_issues_repo_name": "vukics/cppqed", "max_issues_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-04-14T11:18:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T20:11:23.000Z", "max_forks_repo_path": "CPPQEDcore/examples/CoherentElementTest.cc", "max_forks_repo_name": "vukics/cppqed", "max_forks_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T10:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T18:29:01.000Z", "avg_line_length": 37.0, "max_line_length": 157, "alphanum_fraction": 0.6516516517, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5881705523500936}}
{"text": "#pragma once\n\n#include \"types.hh\"\n\n#include <Eigen/Dense>\n\nnamespace sonder {\n\nEigen::AngleAxisf vector3f_to_angleaxis(const Eigen::Vector3f &vec);\n\n// Construct a rotation between two vectors (Non-unique)\n//\n//\nEigen::Quaternionf create_rotation_to(const Eigen::Vector3f &from, const Eigen::Vector3f &to);\n\n// Construct a rotation into a frame defined by two vectors\n//\n//\nEigen::Quaternionf rotation_from_xy(const Eigen::Vector3f &frame_x, const Eigen::Vector3f &frame_y);\n\nEigen::Vector3f any_perpendicular(const Eigen::Vector3f &direction);\n}", "meta": {"hexsha": "b8e8fc6b321e90b5ece9891c336f4a5feb3f3bd7", "size": 546, "ext": "hh", "lang": "C++", "max_stars_repo_path": "sonder/src/geometry/geometry.hh", "max_stars_repo_name": "jpanikulam/sonder", "max_stars_repo_head_hexsha": "ff3eece5f6a31d3bb2573d0e3e6dd5dafec7ffda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-24T07:52:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T07:52:39.000Z", "max_issues_repo_path": "sonder/src/geometry/geometry.hh", "max_issues_repo_name": "jpanikulam/sonder", "max_issues_repo_head_hexsha": "ff3eece5f6a31d3bb2573d0e3e6dd5dafec7ffda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sonder/src/geometry/geometry.hh", "max_forks_repo_name": "jpanikulam/sonder", "max_forks_repo_head_hexsha": "ff3eece5f6a31d3bb2573d0e3e6dd5dafec7ffda", "max_forks_repo_licenses": ["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.8181818182, "max_line_length": 100, "alphanum_fraction": 0.7673992674, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.5881480240715216}}
{"text": "\n/*\n * Copyright 2015 Christoph Jud (christoph.jud@unibas.ch)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <iostream>\n#include <memory>\n#include <ctime>\n#include <cmath>\n\n#include <boost/random.hpp>\n\n#include \"GaussianProcess.h\"\n#include \"Kernel.h\"\n\nusing namespace gpr;\n\ntypedef double ScalarType;\ntypedef Kernel<ScalarType>  KernelType;\ntypedef std::shared_ptr<KernelType> KernelTypePointer;\ntypedef GaussianProcess<ScalarType> GaussianProcessType;\ntypedef std::shared_ptr<GaussianProcessType> GaussianProcessTypePointer;\n\ntypedef typename GaussianProcessType::VectorType VectorType;\ntypedef typename GaussianProcessType::MatrixType MatrixType;\n\nvoid Test1(){\n    /*\n     * Test 1: derivative test of kernels\n     */\n    std::cout << \"Test 1.1: gaussian kernel derivative... \" << std::flush;\n\n    VectorType x = VectorType::Zero(2);\n    x(0) = 0.1; x(1) = 0.5;\n\n    VectorType y = VectorType::Zero(2);\n    y(0) = -0.1; y(1) = 0.8;\n\n\n    // typedefs\n    typedef GaussianKernel<ScalarType>    GaussianKernelType;\n    typedef std::shared_ptr<GaussianKernelType>                 GaussianKernelTypePointer;\n\n    double h = 0.001;\n    VectorType err = VectorType::Zero(2);\n    unsigned counter = 0;\n    for(double sigma=0.1; sigma<10; sigma+=0.4){\n        for(double scale=0.1; scale<3; scale+=0.8){\n            // analytical derivative\n            GaussianKernelTypePointer gk(new GaussianKernelType(sigma, scale));\n            VectorType D = gk->GetDerivative(x,y);\n\n            // scale central difference\n            GaussianKernelTypePointer gk1_scale(new GaussianKernelType(sigma, scale+h/2));\n            GaussianKernelTypePointer gk2_scale(new GaussianKernelType(sigma, scale-h/2));\n            double cd_scale = (*gk1_scale)(x,y) - (*gk2_scale)(x,y);\n            cd_scale/=h;\n\n            // sigma central difference\n            GaussianKernelTypePointer gk1_sigma(new GaussianKernelType(sigma+h/2, scale));\n            GaussianKernelTypePointer gk2_sigma(new GaussianKernelType(sigma-h/2, scale));\n            double cd_sigma = (*gk1_sigma)(x,y) - (*gk2_sigma)(x,y);\n            cd_sigma/=h;\n\n            err[0] += std::fabs(cd_sigma-D[0]);\n            err[1] += std::fabs(cd_scale-D[1]);\n\n            counter++;\n        }\n    }\n\n\n    if(err[0]/counter < 1e-5 && err[1]/counter < 1e-12){\n        std::cout << \"\\t[passed].\" << std::endl;\n    }\n    else{\n        std::stringstream ss; ss<<\"(sigma) \" << err[0]/counter << \" and (scale) \" << err[1]/counter; throw ss.str();\n    }\n    return;\n\n\n}\n\nvoid Test1_2(){\n    /*\n     * Test 1.2: derivative test of kernels\n     */\n    std::cout << \"Test 1.2: gaussian kernel derivative with exponentiated parameters... \" << std::flush;\n\n    VectorType x = VectorType::Zero(2);\n    x(0) = 0.1; x(1) = 0.5;\n\n    VectorType y = VectorType::Zero(2);\n    y(0) = -0.1; y(1) = 0.8;\n\n\n    // typedefs\n    typedef GaussianExpKernel<ScalarType>           GaussianExpKernelType;\n    typedef std::shared_ptr<GaussianExpKernelType>  GaussianExpKernelTypePointer;\n\n    double h = 0.001;\n    VectorType err = VectorType::Zero(2);\n    unsigned counter = 0;\n    for(double sigma=0.1; sigma<10; sigma+=0.4){\n        for(double scale=0.1; scale<3; scale+=0.8){\n            // analytical derivative\n            GaussianExpKernelTypePointer gk(new GaussianExpKernelType(sigma, scale));\n            VectorType D = gk->GetDerivative(x,y);\n\n            // scale central difference\n            GaussianExpKernelTypePointer gk1_scale(new GaussianExpKernelType(sigma, scale+h/2));\n            GaussianExpKernelTypePointer gk2_scale(new GaussianExpKernelType(sigma, scale-h/2));\n            double cd_scale = (*gk1_scale)(x,y) - (*gk2_scale)(x,y);\n            cd_scale/=h;\n\n            // sigma central difference\n            GaussianExpKernelTypePointer gk1_sigma(new GaussianExpKernelType(sigma+h/2, scale));\n            GaussianExpKernelTypePointer gk2_sigma(new GaussianExpKernelType(sigma-h/2, scale));\n            double cd_sigma = (*gk1_sigma)(x,y) - (*gk2_sigma)(x,y);\n            cd_sigma/=h;\n\n            err[0] += std::fabs(cd_sigma-D[0]);\n            err[1] += std::fabs(cd_scale-D[1]);\n\n            counter++;\n        }\n    }\n\n    if(err[0]/counter < 1e-6 && err[1]/counter < 1e-3){\n        std::cout << \"\\t[passed].\" << std::endl;\n    }\n    else{\n        std::stringstream ss; ss<<\"(sigma) \" << err[0]/counter << \" and (scale) \" << err[1]/counter; throw ss.str();\n    }\n    return;\n}\n\nvoid Test2(){\n    /*\n     * Test 2: derivative test of kernels\n     */\n    std::cout << \"Test 2: white kernel derivative... \" << std::flush;\n\n    VectorType x = VectorType::Zero(2);\n    x(0) = 0.1; x(1) = 0.5;\n\n    VectorType y = VectorType::Zero(2);\n    y(0) = -0.1; y(1) = 0.8;\n\n\n    // typedefs\n    typedef WhiteKernel<ScalarType>              KernelType;\n    typedef std::shared_ptr<KernelType>          KernelTypePointer;\n\n    double h = 0.1;\n    VectorType err1 = VectorType::Zero(1);\n    VectorType err2 = VectorType::Zero(1);\n    unsigned counter = 0;\n\n    for(double scale=0.1; scale<3; scale+=0.8){\n        // analytical derivative\n        KernelTypePointer k(new KernelType(scale));\n        VectorType D1 = k->GetDerivative(x,y);\n        VectorType D2 = k->GetDerivative(x,x);\n\n        // scale central difference\n        KernelTypePointer k1_scale(new KernelType(scale+h/2));\n        KernelTypePointer k2_scale(new KernelType(scale-h/2));\n        double cd_scale1 = (*k1_scale)(x,y) - (*k2_scale)(x,y);\n        cd_scale1/=h;\n        double cd_scale2 = (*k1_scale)(x,x) - (*k2_scale)(x,x);\n        cd_scale2/=h;\n\n        err1[0] += std::fabs(cd_scale1-D1[0]);\n        err2[0] += std::fabs(cd_scale2-D2[0]);\n        counter++;\n    }\n\n    if(err1[0]/counter == 0 && err2[0]/counter < 1e-13){\n        std::cout << \"\\t[passed].\" << std::endl;\n    }\n    else{\n        std::stringstream ss; ss<<\"scale 1: \" << err1[0]/counter << \", scale 2: \"<<err2[0]/counter; throw ss.str();\n    }\n}\n\nvoid Test3(){\n    /*\n     * Test 3: derivative test of kernels\n     */\n    std::cout << \"Test 3: rational quadratic kernel derivative... \" << std::flush;\n\n    VectorType x = VectorType::Zero(2);\n    x(0) = 0.1; x(1) = 0.5;\n\n    VectorType y = VectorType::Zero(2);\n    y(0) = -0.1; y(1) = 0.8;\n\n\n    // typedefs\n    typedef RationalQuadraticKernel<ScalarType>              KernelType;\n    typedef std::shared_ptr<KernelType>          KernelTypePointer;\n\n    double h = 0.01;\n    VectorType err = VectorType::Zero(3);\n    unsigned counter = 0;\n\n    for(double scale=0.1; scale<3; scale+=0.8){\n        for(double sigma=0.2; sigma<10; sigma+=0.6){\n            for(double alpha=0.1; alpha<6; alpha+=0.6){\n                // analytical derivative\n                KernelTypePointer k(new KernelType(scale, sigma, alpha));\n                VectorType D = k->GetDerivative(x,y);\n\n                // scale central difference\n                KernelTypePointer k1_scale(new KernelType(scale+h/2, sigma, alpha));\n                KernelTypePointer k2_scale(new KernelType(scale-h/2, sigma, alpha));\n                double cd_scale = (*k1_scale)(x,y) - (*k2_scale)(x,y);\n                cd_scale/=h;\n\n                // sigma central difference\n                KernelTypePointer k1_sigma(new KernelType(scale, sigma+h/2, alpha));\n                KernelTypePointer k2_sigma(new KernelType(scale, sigma-h/2, alpha));\n                double cd_sigma = (*k1_sigma)(x,y) - (*k2_sigma)(x,y);\n                cd_sigma/=h;\n\n                // alpha central difference\n                KernelTypePointer k1_alpha(new KernelType(scale, sigma, alpha+h/2));\n                KernelTypePointer k2_alpha(new KernelType(scale, sigma, alpha-h/2));\n                double cd_alpha = (*k1_alpha)(x,y) - (*k2_alpha)(x,y);\n                cd_alpha/=h;\n\n                err[0] += std::fabs(cd_scale-D[0]);\n                err[1] += std::fabs(cd_sigma-D[1]);\n                err[2] += std::fabs(cd_alpha-D[2]);\n                counter++;\n            }\n        }\n    }\n\n    // sigma and alpha are not that stable with central difference\n\n    if(err[0]/counter < 1e-13 && err[1]/counter < 0.001 && err[2]/counter < 1e-4){\n        std::cout << \"\\t\\t[passed].\" << std::endl;\n    }\n    else{\n        std::stringstream ss; ss<<\"scale: \" << err[0]/counter << \", sigma: \"<<err[1]/counter << \", alpha: \"<<err[2]/counter; throw ss.str();\n    }\n}\n\nvoid Test4(){\n    /*\n     * Test 4: derivative test of kernels\n     */\n    std::cout << \"Test 4: periodic kernel derivative... \" << std::flush;\n\n    VectorType x = VectorType::Zero(2);\n    x(0) = 0.1; x(1) = 0.5;\n\n    VectorType y = VectorType::Zero(2);\n    y(0) = -0.1; y(1) = 0.8;\n\n\n    // typedefs\n    typedef PeriodicKernel<ScalarType>              KernelType;\n    typedef std::shared_ptr<KernelType>          KernelTypePointer;\n\n    double h = 0.01;\n    VectorType err = VectorType::Zero(3);\n    unsigned counter = 0;\n\n    for(double scale=0.1; scale<3; scale+=0.8){\n        for(double b=0.1; b<5*M_PI; b+=0.3){\n            for(double sigma=0.1; sigma<4; sigma+=0.1){\n                // analytical derivative\n                KernelTypePointer k(new KernelType(scale, b, sigma));\n                VectorType D = k->GetDerivative(x,y);\n\n                // scale central difference\n                KernelTypePointer k1_scale(new KernelType(scale+h/2, b, sigma));\n                KernelTypePointer k2_scale(new KernelType(scale-h/2, b, sigma));\n                double cd_scale = (*k1_scale)(x,y) - (*k2_scale)(x,y);\n                cd_scale/=h;\n\n                // sigma central difference\n                KernelTypePointer k1_b(new KernelType(scale, b+h/2, sigma));\n                KernelTypePointer k2_b(new KernelType(scale, b-h/2, sigma));\n                double cd_b = (*k1_b)(x,y) - (*k2_b)(x,y);\n                cd_b/=h;\n\n                // alpha central difference\n                KernelTypePointer k1_sigma(new KernelType(scale, b, sigma+h/2));\n                KernelTypePointer k2_sigma(new KernelType(scale, b, sigma-h/2));\n                double cd_sigma = (*k1_sigma)(x,y) - (*k2_sigma)(x,y);\n                cd_sigma/=h;\n\n                err[0] += std::fabs(cd_scale-D[0]);\n                err[1] += std::fabs(cd_b-D[1]);\n                err[2] += std::fabs(cd_sigma-D[2]);\n                counter++;\n            }\n        }\n    }\n\n    if(err[0]/counter < 1e-13 && err[1]/counter < 1e-5 && err[2]/counter < 0.001){\n        std::cout << \"\\t[passed].\" << std::endl;\n    }\n    else{\n        std::stringstream ss; ss<<\"scale: \"<<err[0]/counter << \", b: \"<<err[1]/counter << \", sigma: \"<<err[2]/counter; throw ss.str();\n    }\n}\n\nvoid Test5(){\n    /*\n     * Test 5: derivative test of kernels\n     */\n    std::cout << \"Test 5: sum of gaussian and periodic kernel derivative... \" << std::flush;\n\n    VectorType x = VectorType::Zero(2);\n    x(0) = 0.1; x(1) = 0.5;\n\n    VectorType y = VectorType::Zero(2);\n    y(0) = -0.1; y(1) = 0.8;\n\n\n    // typedefs\n    typedef SumKernel<ScalarType>                ProductKernelType;\n    typedef std::shared_ptr<ProductKernelType>       ProductKernelTypePointer;\n    typedef GaussianKernel<ScalarType>           GaussianKernelType;\n    typedef std::shared_ptr<GaussianKernelType>  GaussianKernelTypePointer;\n    typedef PeriodicKernel<ScalarType>           PeriodicKernelType;\n    typedef std::shared_ptr<PeriodicKernelType>  PeriodicKernelTypePointer;\n\n    double h = 0.01;\n    VectorType err = VectorType::Zero(5);\n    unsigned counter = 0;\n\n    for(double gscale=0.1; gscale<5; gscale+=0.8){\n        for(double gsigma=0.1; gsigma<6; gsigma+=0.4){\n            for(double pscale=0.1; pscale<4; pscale+=0.8){\n                for(double b=0.1; b<5*M_PI; b+=0.4){\n                    for(double psigma=0.2; psigma<6; psigma+=0.3){\n\n                        // analytical derivative\n                        GaussianKernelTypePointer gk(new GaussianKernelType(gsigma, gscale));\n                        PeriodicKernelTypePointer pk(new PeriodicKernelType(pscale, b, psigma));\n                        ProductKernelTypePointer k(new ProductKernelType(gk,pk));\n                        VectorType D = k->GetDerivative(x,y);\n\n                        // gaussian scale central difference\n                        GaussianKernelTypePointer gk1_gscale(new GaussianKernelType(gsigma, gscale+h/2));\n                        GaussianKernelTypePointer gk2_gscale(new GaussianKernelType(gsigma, gscale-h/2));\n                        ProductKernelTypePointer k1_gscale(new ProductKernelType(gk1_gscale, pk));\n                        ProductKernelTypePointer k2_gscale(new ProductKernelType(gk2_gscale, pk));\n                        double cd_gscale = (*k1_gscale)(x,y) - (*k2_gscale)(x,y);\n                        cd_gscale/=h;\n\n                        // gaussian scale central difference\n                        GaussianKernelTypePointer gk1_gsigma(new GaussianKernelType(gsigma+h/2, gscale));\n                        GaussianKernelTypePointer gk2_gsigma(new GaussianKernelType(gsigma-h/2, gscale));\n                        ProductKernelTypePointer k1_gsigma(new ProductKernelType(gk1_gsigma, pk));\n                        ProductKernelTypePointer k2_gsigma(new ProductKernelType(gk2_gsigma, pk));\n                        double cd_gsigma = (*k1_gsigma)(x,y) - (*k2_gsigma)(x,y);\n                        cd_gsigma/=h;\n\n                        // periodic scale central difference\n                        PeriodicKernelTypePointer pk1_pscale(new PeriodicKernelType(pscale+h/2, b, psigma));\n                        PeriodicKernelTypePointer pk2_pscale(new PeriodicKernelType(pscale-h/2, b, psigma));\n                        ProductKernelTypePointer k1_pscale(new ProductKernelType(gk, pk1_pscale));\n                        ProductKernelTypePointer k2_pscale(new ProductKernelType(gk, pk2_pscale));\n                        double cd_pscale = (*k1_pscale)(x,y) - (*k2_pscale)(x,y);\n                        cd_pscale/=h;\n\n                        // periodic period length central difference\n                        PeriodicKernelTypePointer pk1_pb(new PeriodicKernelType(pscale, b+h/2, psigma));\n                        PeriodicKernelTypePointer pk2_pb(new PeriodicKernelType(pscale, b-h/2, psigma));\n                        ProductKernelTypePointer k1_pb(new ProductKernelType(gk, pk1_pb));\n                        ProductKernelTypePointer k2_pb(new ProductKernelType(gk, pk2_pb));\n                        double cd_pb = (*k1_pb)(x,y) - (*k2_pb)(x,y);\n                        cd_pb/=h;\n\n                        // periodic sigma central difference\n                        PeriodicKernelTypePointer pk1_psigma(new PeriodicKernelType(pscale, b, psigma+h/2));\n                        PeriodicKernelTypePointer pk2_psigma(new PeriodicKernelType(pscale, b, psigma-h/2));\n                        ProductKernelTypePointer k1_psigma(new ProductKernelType(gk, pk1_psigma));\n                        ProductKernelTypePointer k2_psigma(new ProductKernelType(gk, pk2_psigma));\n                        double cd_psigma = (*k1_psigma)(x,y) - (*k2_psigma)(x,y);\n                        cd_psigma/=h;\n\n\n\n                        err[0] += std::fabs(cd_gsigma-D[0]);\n                        err[1] += std::fabs(cd_gscale-D[1]);\n                        err[2] += std::fabs(cd_pscale-D[2]);\n                        err[3] += std::fabs(cd_pb-D[3]);\n                        err[4] += std::fabs(cd_psigma-D[4]);\n                        counter++;\n                    }\n                }\n            }\n        }\n    }\n\n    if(err[0]/counter < 0.005 &&\n            err[1]/counter < 1e-11 &&\n            err[2]/counter < 1e-11 &&\n            err[3]/counter < 1e-6 &&\n            err[4]/counter < 1e-4){\n        std::cout << \"\\t[passed].\" << std::endl;\n    }\n    else{\n        std::stringstream ss; ss<<\"gsigma: \"<<err[0]/counter << \", gscale: \"<<err[1]/counter;\n        ss<<\", pscale: \" << err[2]/counter << \", pb: \" << err[3]/counter << \", psigma: \" << err[4]/counter;\n        throw ss.str();\n    }\n}\n\nvoid Test6(){\n    /*\n     * Test 6: derivative test of kernels\n     */\n    std::cout << \"Test 6: product of gaussian and periodic kernel derivative... \" << std::flush;\n\n    VectorType x = VectorType::Zero(2);\n    x(0) = 0.1; x(1) = 0.5;\n\n    VectorType y = VectorType::Zero(2);\n    y(0) = -0.1; y(1) = 0.8;\n\n\n    // typedefs\n    typedef ProductKernel<ScalarType>            ProductKernelType;\n    typedef std::shared_ptr<ProductKernelType>   ProductKernelTypePointer;\n    typedef GaussianKernel<ScalarType>           GaussianKernelType;\n    typedef std::shared_ptr<GaussianKernelType>  GaussianKernelTypePointer;\n    typedef PeriodicKernel<ScalarType>           PeriodicKernelType;\n    typedef std::shared_ptr<PeriodicKernelType>  PeriodicKernelTypePointer;\n\n    double h = 0.01;\n    VectorType err = VectorType::Zero(5);\n    unsigned counter = 0;\n\n    for(double gscale=0.4; gscale<4; gscale+=0.8){\n        for(double gsigma=0.1; gsigma<5; gsigma+=0.4){\n            for(double pscale=0.1; pscale<4; pscale+=0.8){\n                for(double b=0.1; b<4*M_PI; b+=0.4){\n                    for(double psigma=0.4; psigma<5; psigma+=0.3){\n\n                        // analytical derivative\n                        GaussianKernelTypePointer gk(new GaussianKernelType(gsigma, gscale));\n                        PeriodicKernelTypePointer pk(new PeriodicKernelType(pscale, b, psigma));\n                        ProductKernelTypePointer k(new ProductKernelType(gk,pk));\n                        VectorType D = k->GetDerivative(x,y);\n\n                        // gaussian scale central difference\n                        GaussianKernelTypePointer gk1_gscale(new GaussianKernelType(gsigma, gscale+h/2));\n                        GaussianKernelTypePointer gk2_gscale(new GaussianKernelType(gsigma, gscale-h/2));\n                        ProductKernelTypePointer k1_gscale(new ProductKernelType(gk1_gscale, pk));\n                        ProductKernelTypePointer k2_gscale(new ProductKernelType(gk2_gscale, pk));\n                        double cd_gscale = (*k1_gscale)(x,y) - (*k2_gscale)(x,y);\n                        cd_gscale/=h;\n\n                        // gaussian scale central difference\n                        GaussianKernelTypePointer gk1_gsigma(new GaussianKernelType(gsigma+h/2, gscale));\n                        GaussianKernelTypePointer gk2_gsigma(new GaussianKernelType(gsigma-h/2, gscale));\n                        ProductKernelTypePointer k1_gsigma(new ProductKernelType(gk1_gsigma, pk));\n                        ProductKernelTypePointer k2_gsigma(new ProductKernelType(gk2_gsigma, pk));\n                        double cd_gsigma = (*k1_gsigma)(x,y) - (*k2_gsigma)(x,y);\n                        cd_gsigma/=h;\n\n                        // periodic scale central difference\n                        PeriodicKernelTypePointer pk1_pscale(new PeriodicKernelType(pscale+h/2, b, psigma));\n                        PeriodicKernelTypePointer pk2_pscale(new PeriodicKernelType(pscale-h/2, b, psigma));\n                        ProductKernelTypePointer k1_pscale(new ProductKernelType(gk, pk1_pscale));\n                        ProductKernelTypePointer k2_pscale(new ProductKernelType(gk, pk2_pscale));\n                        double cd_pscale = (*k1_pscale)(x,y) - (*k2_pscale)(x,y);\n                        cd_pscale/=h;\n\n                        // periodic period length central difference\n                        PeriodicKernelTypePointer pk1_pb(new PeriodicKernelType(pscale, b+h/2, psigma));\n                        PeriodicKernelTypePointer pk2_pb(new PeriodicKernelType(pscale, b-h/2, psigma));\n                        ProductKernelTypePointer k1_pb(new ProductKernelType(gk, pk1_pb));\n                        ProductKernelTypePointer k2_pb(new ProductKernelType(gk, pk2_pb));\n                        double cd_pb = (*k1_pb)(x,y) - (*k2_pb)(x,y);\n                        cd_pb/=h;\n\n                        // periodic sigma central difference\n                        PeriodicKernelTypePointer pk1_psigma(new PeriodicKernelType(pscale, b, psigma+h/2));\n                        PeriodicKernelTypePointer pk2_psigma(new PeriodicKernelType(pscale, b, psigma-h/2));\n                        ProductKernelTypePointer k1_psigma(new ProductKernelType(gk, pk1_psigma));\n                        ProductKernelTypePointer k2_psigma(new ProductKernelType(gk, pk2_psigma));\n                        double cd_psigma = (*k1_psigma)(x,y) - (*k2_psigma)(x,y);\n                        cd_psigma/=h;\n\n\n\n                        err[0] += std::fabs(cd_gsigma-D[0]);\n                        err[1] += std::fabs(cd_gscale-D[1]);\n                        err[2] += std::fabs(cd_pscale-D[2]);\n                        err[3] += std::fabs(cd_pb-D[3]);\n                        err[4] += std::fabs(cd_psigma-D[4]);\n                        counter++;\n                    }\n                }\n            }\n        }\n    }\n\n    if(err[0]/counter < 0.009 &&\n            err[1]/counter < 1e-11 &&\n            err[2]/counter < 1e-11 &&\n            err[3]/counter < 1e-5 &&\n            err[4]/counter < 0.001){\n        std::cout << \"\\t[passed].\" << std::endl;\n    }\n    else{\n        std::stringstream ss; ss<<\"gsigma: \"<<err[0]/counter << \", gscale: \"<<err[1]/counter;\n        ss<<\", pscale: \" << err[2]/counter << \", pb: \" << err[3]/counter << \", psigma: \" << err[4]/counter;\n        throw ss.str();\n    }\n}\n\nint main (int argc, char *argv[]){\n    std::cout << \"Product kernel test: \" << std::endl;\n    try{\n        Test1();\n        Test1_2();\n        Test2();\n        Test3();\n        Test4();\n        Test5();\n        Test6();\n    }\n    catch(std::string& s){\n        std::cout << \"[failed] Error: \" << s << std::endl;\n        return -1;\n    }\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "806d8812e2fe4cd9f5dffc53d282082a64727aa1", "size": 22141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/KernelDerivativeTest.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/KernelDerivativeTest.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/KernelDerivativeTest.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": 39.821942446, "max_line_length": 140, "alphanum_fraction": 0.5632988573, "num_tokens": 5758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.58814801617055}}
{"text": "#ifndef MATH_UTILITY\n#define MATH_UTILITY\n\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <optional>\n#include <type_traits>\n\nnamespace math {\nnamespace utility {\n\n/**\n * @brief \u9069\u5207\u306b2\u03c0\u306e\u500d\u6570\u3092\u52a0\u3048\u308b\u3053\u3068\u3067\u89d2\u5ea6\u3092[-\u03c0, \u03c0]\u306e\u7bc4\u56f2\u306b\u30e9\u30c3\u30d7\u3059\u308b\n *\n * @param  x  \u30e9\u30c3\u30d7\u5bfe\u8c61\u306e\u89d2\u5ea6\n * @retval w  \u30e9\u30c3\u30d7\u5f8c\u306e\u89d2\u5ea6\n */\ntemplate <typename Float> constexpr inline Float wrap_pi(Float x) {\n  static_assert(std::is_floating_point_v<Float>,\n                \"only makes sence for floating point types.\");\n  namespace bmc = boost::math::constants;\n  constexpr Float y = x + bmc::pi<Float>();\n  constexpr Float z =\n      y - std::floor(y * bmc::half_pi<Float>()) * bmc::two_pi<Float>();\n  constexpr Float w = z - bmc::pi<Float>();\n  return w;\n}\n\n} // namespace utility\n} // namespace math\n\n#endif\n", "meta": {"hexsha": "ab26f6a02a56f06c3e0bf0f0a0676f1d857b41d3", "size": 759, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/math/utility.hpp", "max_stars_repo_name": "mnrn/game-memo", "max_stars_repo_head_hexsha": "8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/utility.hpp", "max_issues_repo_name": "mnrn/game-memo", "max_issues_repo_head_hexsha": "8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/utility.hpp", "max_forks_repo_name": "mnrn/game-memo", "max_forks_repo_head_hexsha": "8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0, "max_line_length": 71, "alphanum_fraction": 0.6785243742, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5880633682198849}}
{"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": "\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE davidson_test\n\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include <Eigen/Eigenvalues>\n#include <chrono>\n\n#include \"../src/DavidsonSolver.hpp\"\n#include \"../src/DavidsonOperator.hpp\"\n#include \"../src/MatrixFreeOperator.hpp\"\n\n// intiialize a full matrix \nEigen::MatrixXd init_matrix(int N, double eps, bool diag)\n{\n    Eigen::MatrixXd matrix;\n    matrix =  eps * Eigen::MatrixXd::Random(N,N);\n    Eigen::MatrixXd tmat = matrix.transpose();\n    matrix = matrix + tmat; \n\n    for (int i = 0; i<N; i++) {\n        if(diag)    matrix(i,i) = static_cast<double> (i+1);   \n        else        matrix(i,i) =  static_cast<double> (1. + (std::rand() %1000 ) / 10.);\n    }\n    return matrix;\n}\n\n// test to derived the matrix free operator class\nclass TestOperator : public MatrixFreeOperator\n{\n    public : \n    TestOperator(int n) {_size = n;}\n    Eigen::VectorXd col(int index) const;\n};\n\n//  get a col of the operator\nEigen::VectorXd TestOperator::col(int index) const\n{\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) = static_cast<double> (j+1); \n        }\n        else{\n            col_out(j) = 0.01 / std::pow( static_cast<double>(j-index),2) ;\n        }\n    }\n    return col_out;\n}\n\n//BOOST_AUTO_TEST_SUITE(davidson_test)\n\nBOOST_AUTO_TEST_CASE(davidson_full_matrix) {\n\n    int size = 1000;\n    int neigen = 10;\n    double eps = 0.01;\n    Eigen::MatrixXd A = init_matrix(size,eps,false);\n\n    DavidsonSolver DS;\n    DS.solve(A,neigen);\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n\n    auto lambda = DS.eigenvalues();\n    auto lambda_ref = es.eigenvalues().head(neigen);\n    bool check_eigenvalues = lambda.isApprox(lambda_ref,1E-6);\n    \n    BOOST_CHECK_EQUAL(check_eigenvalues,1);\n\n}\n\n\nBOOST_AUTO_TEST_CASE(olsen_full_matrix) {\n\n    int size = 1000;\n    int neigen = 10;\n    double eps = 0.01;\n    Eigen::MatrixXd A = init_matrix(size,eps,false);\n\n    DavidsonSolver DS;\n    DS.set_correction(\"OLSEN\");\n    DS.solve(A,neigen);\n\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n\n    auto lambda = DS.eigenvalues();\n    auto lambda_ref = es.eigenvalues().head(neigen);\n    bool check_eigenvalues = lambda.isApprox(lambda_ref,1E-6);\n    \n    BOOST_CHECK_EQUAL(check_eigenvalues,1);\n\n}\n\nBOOST_AUTO_TEST_CASE(jacobi_full_matrix) {\n\n    int size = 50;\n    int neigen = 2;\n    double eps = 0.01;\n    Eigen::MatrixXd A = init_matrix(size,eps,false);\n\n    DavidsonSolver DS;\n    DS.set_correction(\"JACOBI\");\n    DS.set_jacobi_linsolve(\"CG\");\n    DS.solve(A,neigen);\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n\n    auto lambda = DS.eigenvalues();\n    auto lambda_ref = es.eigenvalues().head(neigen);\n    bool check_eigenvalues = lambda.isApprox(lambda_ref,1E-6);\n    \n    BOOST_CHECK_EQUAL(check_eigenvalues,1);\n\n}\n\n\nBOOST_AUTO_TEST_CASE(davidson_matrix_free) {\n\n    int size = 1000;\n    int neigen = 10;\n\n    TestOperator Aop(size);\n    DavidsonSolver DS;\n    DS.solve(Aop,neigen);\n\n    Eigen::MatrixXd A = Aop.get_full_mat();\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n\n    auto lambda = DS.eigenvalues();\n    auto lambda_ref = es.eigenvalues().head(neigen);\n    bool check_eigenvalues = lambda.isApprox(lambda_ref,1E-6);\n    \n    BOOST_CHECK_EQUAL(check_eigenvalues,1);\n\n}\n\n\nBOOST_AUTO_TEST_CASE(olsen_matrix_free) {\n\n    int size = 1000;\n    int neigen = 10;\n    \n\n    TestOperator Aop(size);\n    DavidsonSolver DS;\n    DS.set_correction(\"OLSEN\");\n    DS.solve(Aop,neigen);\n\n    Eigen::MatrixXd A = Aop.get_full_mat();\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n\n    auto lambda = DS.eigenvalues();\n    auto lambda_ref = es.eigenvalues().head(neigen);\n    bool check_eigenvalues = lambda.isApprox(lambda_ref,1E-6);\n    \n    BOOST_CHECK_EQUAL(check_eigenvalues,1);\n\n}\n\nBOOST_AUTO_TEST_CASE(jacobi_matrix_free) {\n\n    int size = 50;\n    int neigen = 2;\n    \n\n    TestOperator Aop(size);\n    DavidsonSolver DS;\n    DS.set_correction(\"JACOBI\");\n    DS.set_jacobi_linsolve(\"CG\");\n    DS.solve(Aop,neigen);\n\n    Eigen::MatrixXd A = Aop.get_full_mat();\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);\n\n    auto lambda = DS.eigenvalues();\n    auto lambda_ref = es.eigenvalues().head(neigen);\n    bool check_eigenvalues = lambda.isApprox(lambda_ref,1E-6);\n    \n    BOOST_CHECK_EQUAL(check_eigenvalues,1);\n\n}\n\n//BOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "d8057c6b686f4bdc558d39fb66271d74835b531d", "size": 4531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_davidson.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": "test/test_davidson.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": "test/test_davidson.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": 24.1010638298, "max_line_length": 89, "alphanum_fraction": 0.6667402339, "num_tokens": 1247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.682573734412324, "lm_q1q2_score": 0.588063343243715}}
{"text": "#ifndef FUNCTIONS_HPP\n#define FUNCTIONS_HPP\n\n#include <iostream>\n#include <vector>\n#define _USE_MATH_DEFINES\n#include <math.h>      \n#include <array>\n#include <random>\n\n#include <Eigen/Dense>\n#include \"particle.hpp\"\n#include \"constants.hpp\"\n\nusing namespace Eigen;\n\nMatrixXd CalcInput(const float &time);\n\nstd::array<MatrixXd,2> Observation(MatrixXd &x_true, MatrixXd &xd, const MatrixXd &u, const MatrixXd &RFID);\n\nMatrixXd MotionModel(const MatrixXd &x, const MatrixXd &u);\n\ndouble Pi2Pi(const double &angle);\n\n#endif // FUNCTIONS_HPP", "meta": {"hexsha": "2f225d5fdfb98b4665a788b50a5e87058fde6874", "size": 536, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/functions.hpp", "max_stars_repo_name": "dskart/ROBO_fast_slam", "max_stars_repo_head_hexsha": "cde36b06288981b189baa463719bb2605ab28794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-19T21:36:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T14:20:26.000Z", "max_issues_repo_path": "inc/functions.hpp", "max_issues_repo_name": "dskart/ROBO_fast_slam", "max_issues_repo_head_hexsha": "cde36b06288981b189baa463719bb2605ab28794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/functions.hpp", "max_forks_repo_name": "dskart/ROBO_fast_slam", "max_forks_repo_head_hexsha": "cde36b06288981b189baa463719bb2605ab28794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.44, "max_line_length": 108, "alphanum_fraction": 0.7555970149, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5880439187561045}}
{"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": "/* \n * File:   FCLayer.hpp\n * Author: heshan\n *\n * Created on June 7, 2018, 8:46 PM\n */\n\n#ifndef FCLAYER_HPP\n#define FCLAYER_HPP\n\n#include <iostream>\n#include <Eigen>\n#include \"Activation.hpp\"\n\nclass FCLayer {\npublic:\n    FCLayer();\n    /**\n     * Constructor\n     * \n     * @param dimensions: dimensions of the input matrix (depth, height, width)\n     * @param outputs: no of outputs\n     */\n    FCLayer(std::tuple<int, int, int> dimensions, int outputs);\n    /**\n     * \n     * @param orig\n     */\n    FCLayer(const FCLayer& orig);\n    /**\n     * \n     */\n    virtual ~FCLayer();\n    /**\n     * Initialize weight matrix and bias values\n     * \n     * @return 0\n     */\n    int initMat();\n    /**\n     * \n     * @param input: input matrix \n     * @return \n     */\n    Eigen::MatrixXd * forward(Eigen::MatrixXd * input);\n    /**\n     * Return the dimension of the layer output\n     * \n     * @return a tuple\n     */\n    std::tuple<int, int, int> getOutputDims();\nprivate:\npublic:\n    int height, width, depth,outputs;\n    Eigen::MatrixXd ** weights;\n    Eigen::MatrixXd bias;\n    Eigen::MatrixXd * output; // outputs before activation\n    Eigen::MatrixXd * activatedOut;\n    \n    \n};\n\n#endif /* FCLAYER_HPP */\n\n", "meta": {"hexsha": "e602fb73e79ef1cd972ce446a367d99dd1794b64", "size": 1211, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ProfilingModule/Profilers/LSTMCNnet/CNNet/FCLayer.hpp", "max_stars_repo_name": "pasindubawantha/sherlock-framework", "max_stars_repo_head_hexsha": "92d64fbc86256a61c6b00b7ca9eb0a17634c7446", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ProfilingModule/Profilers/LSTMCNnet/CNNet/FCLayer.hpp", "max_issues_repo_name": "pasindubawantha/sherlock-framework", "max_issues_repo_head_hexsha": "92d64fbc86256a61c6b00b7ca9eb0a17634c7446", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ProfilingModule/Profilers/LSTMCNnet/CNNet/FCLayer.hpp", "max_forks_repo_name": "pasindubawantha/sherlock-framework", "max_forks_repo_head_hexsha": "92d64fbc86256a61c6b00b7ca9eb0a17634c7446", "max_forks_repo_licenses": ["Apache-2.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.6307692308, "max_line_length": 79, "alphanum_fraction": 0.5681255161, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5879061888945052}}
{"text": "// inverse_gamma_distribution_example.cpp\n\n// Copyright Paul A. Bristow 2010.\n// Copyright Thomas Mang 2010.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Example 1 of using inverse gamma\n#include <boost/math/distributions/inverse_gamma.hpp>\nusing boost::math::inverse_gamma_distribution;  //  inverse_gamma_distribution.\nusing boost::math::inverse_gamma;\n\n#include <boost/math/special_functions/gamma.hpp>\nusing boost::math::tgamma; // Used for naive pdf as a comparison.\n\n#include <boost/math/distributions/gamma.hpp>\nusing boost::math::inverse_gamma_distribution;\n\n#include <iostream>\nusing std::cout;    using std::endl;\n#include <iomanip>\nusing std::setprecision;\n#include <cmath>\nusing std::sqrt;\n\nint main()\n{\n\n  cout << \"Example using Inverse Gamma distribution. \" << endl;\n  // TODO - awaiting a real example using Bayesian statistics.\n\n#ifdef BOOST_NO_NUMERIC_LIMITS_LOWEST\n  int max_digits10 = 2 + (boost::math::policies::digits<double, boost::math::policies::policy<> >() * 30103UL) / 100000UL;\n  cout << \"BOOST_NO_NUMERIC_LIMITS_LOWEST is defined\" << endl;\n#else\n  int max_digits10 = std::numeric_limits<double>::max_digits10;\n#endif\n  cout << \"Show all potentially significant decimal digits std::numeric_limits<double>::max_digits10 = \"\n    << max_digits10 << endl;\n  cout.precision(max_digits10); //\n\n  double shape = 1.;\n  double scale = 1.;\n  double x = 0.5;\n  // Construction using default RealType double, and default shape and scale..\n  inverse_gamma_distribution<> my_inverse_gamma(shape, scale); // (alpha, beta)\n\n  cout << \"my_inverse_gamma.shape() = \" << my_inverse_gamma.shape()\n    << \", scale = \"<< my_inverse_gamma.scale() << endl;\n  cout << \"x = \" << x << \", pdf = \" << pdf(my_inverse_gamma, x)\n    << \", cdf = \" << cdf(my_inverse_gamma, x) << endl;\n\n  // Construct using  typedef and default shape and scale parameters.\n  inverse_gamma my_ig;\n\n  inverse_gamma my_ig23(2, 3);\n  cout << \"my_inverse_gamma.shape() = \" << my_ig23.shape()\n    << \", scale = \"<< my_ig23.scale() << endl;\n  cout << \"x = \" << x << \", pdf = \" << pdf(my_ig23, x)\n    << \", cdf = \" << cdf(my_ig23, x) << endl;\n\n  // Example of providing an 'out of domain' or 'bad' parameter,\n  // here a shape < 1, for which mean is not defined.\n  // Try block is essential to catch the exception message.\n  // (Uses the default policy which is to throw on all errors).\n  try\n  {\n    inverse_gamma if051(0.5, 1);\n    //inverse_gamma if051(0.5, 1);\n    cout << \"mean(if051) = \" << mean(if051) << endl;\n  }\n  catch(const std::exception& e)\n  { // Always useful to include try & catch blocks because default policies\n    // are to throw exceptions on arguments that cause errors like underflow, overflow.\n    // Lacking try & catch blocks, the program will abort without a message below,\n    // which may give some helpful clues as to the cause of the exception.\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\n  }\n\n  return 0;\n}  // int main()\n\n/*\n\nOutput is:\n  Example using Inverse Gamma distribution.\n  std::numeric_limits<double>::max_digits10 = 17\n  my_inverse_gamma.shape() = 1, scale = 1\n  x = 0.5, pdf = 0.54134113294645081, cdf = 0.1353352832366127\n  my_inverse_gamma.shape() = 2, scale = 3\n  x = 0.5, pdf = 0.17847015671997774, cdf = 0.017351265236664509\n\n  Message from thrown exception was:\n     Error in function boost::math::mean(const inverse_gamma_distribution<double>&): Shape parameter is 0.5, but for a defined mean it must be > 1\n\n\n*/\n\n\n", "meta": {"hexsha": "147c8084cbddc9a4bfd19406cce0f56012a38718", "size": 3639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/example/inverse_gamma_distribution_example.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T23:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T17:41:27.000Z", "max_issues_repo_path": "boost/libs/math/example/inverse_gamma_distribution_example.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "boost/libs/math/example/inverse_gamma_distribution_example.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T01:56:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T09:02:49.000Z", "avg_line_length": 34.9903846154, "max_line_length": 146, "alphanum_fraction": 0.6897499313, "num_tokens": 989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.5879061859110939}}
{"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\u2013205\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": "#include \"../voxelizer.h\"\n#include \"../volume.h\"\n#include \"../traversal.h\"\n\n\n#include <gp_Pln.hxx>\n#include <Bnd_Box.hxx>\n#include <BRepBndLib.hxx>\n#include <BRepBuilderAPI_MakeFace.hxx>\n#include <BRepMesh_IncrementalMesh.hxx>\n\n#include <Eigen/Dense>\n\n#include <gtest/gtest.h>\n\nTEST(NormalEstimation, EigenPCA) {\n\tstatic Eigen::Vector3f Z(0, 0, 1);\n\tEigen::MatrixXf points(10, 3);\n\tpoints.setRandom();\n\tpoints.col(2).setZero();\n\n\tEigen::MatrixXf centered = points.rowwise() - points.colwise().mean();\n\tEigen::MatrixXf cov = centered.adjoint() * centered;\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXf> eig(cov);\n\t\n\tASSERT_FLOAT_EQ(std::abs(eig.eigenvectors().col(0).dot(Z)), 1.);\n}\n\n\nTEST(NormalEstimation, OCC) {\n\tgp_Pln p(1, 2, 3, 4);\n\tauto face = BRepBuilderAPI_MakeFace(p, -1, 1, -1, 1).Face();\n\tBRepMesh_IncrementalMesh(face, 0.1);\n\n\tauto surf = BRep_Tool::Surface(face);\n\tauto dir = Handle_Geom_Plane::DownCast(surf)->Position().Direction();\n\n\tEigen::Vector3f norm(dir.X(), dir.Y(), dir.Z());\n\tstd::cout << \"Face normal \" << norm << std::endl;\n\t\n\tBnd_Box B;\n\tBRepBndLib::AddClose(face, B);\n\t\n\tdouble d = 0.01;\n\tdouble x0, y0, z0, x1, y1, z1;\n\tB.Get(x0, y0, z0, x1, y1, z1);\n\t\n\tauto storage = new chunked_voxel_storage<bit_t>(\n\t\tx0 - d, \n\t\ty0 - d, \n\t\tz0 - d, d, \n\t\t(x1 - x0) / d + 2, \n\t\t(y1 - y0) / d + 2, \n\t\t(z1 - z0) / d + 2, \n\t\t64);\n\tauto vox = voxelizer(face, storage);\n\tvox.Convert();\t\n\n\tstd::cout << \"count \" << storage->count() << std::endl;\n\n\tauto it = storage->begin();\n\tstd::advance(it, storage->count() / 2);\n\n\tstd::cout << \"center \" << (*it).format() << std::endl;\n\n\tint i = 2;\n\n\tvisitor<26> vis;\n\tvis.max_depth = 0.1 * i / d;\n\n\tstd::cout << \"md \" << (0.1 * i) << std::endl;\n\n\tstd::vector<float> coords;\n\n\tauto selection = storage->empty_copy();\n\n\tvis([&coords, &selection](const tagged_index& pos) {\n\t\tif (pos.which == tagged_index::VOXEL) {\n\t\t\tcoords.push_back(pos.pos.get(0));\n\t\t\tcoords.push_back(pos.pos.get(1));\n\t\t\tcoords.push_back(pos.pos.get(2));\n\t\t\tselection->Set(pos.pos);\n\t\t}\n\t\telse {\n\t\t\tthrow std::runtime_error(\"Unexpected\");\n\t\t}\n\t}, storage, *it);\n\n\t/*{\n\t\tstd::ofstream ofs(\"m2.obj\");\n\t\t((chunked_voxel_storage<bit_t>*)selection)->obj_export(ofs);\n\t}\n\n\tstorage->boolean_subtraction_inplace(selection);\n\n\t{\n\t\tstd::ofstream ofs(\"m1.obj\");\n\t\tstorage->obj_export(ofs);\n\t}*/\n\n\tstd::cout << \"neighbours \" << (coords.size() / 3) << std::endl;\n\n\tEigen::MatrixXf points = Eigen::Map<Eigen::MatrixXf>(coords.data(), 3, coords.size() / 3).transpose();\n\n\tEigen::MatrixXf centered = points.rowwise() - points.colwise().mean();\n\tEigen::MatrixXf cov = centered.adjoint() * centered;\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXf> eig(cov);\n\n\tauto estimated = eig.eigenvectors().col(0);\n\n\tstd::cout << estimated << std::endl;\n\n\tauto angle = std::acos(estimated.dot(norm));\n\tif (angle > M_PI / 2) {\n\t\tangle = M_PI - angle;\n\t}\n\tauto angle_degrees = angle / M_PI * 180.;\n\n\tstd::cout << \"angle \" << angle_degrees << \"d\" << std::endl;\n\n\tASSERT_LT(angle_degrees, 1.);\n}", "meta": {"hexsha": "0c01e82e2bea110d5f241f0efb4735054375921f", "size": 2979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_pca.cpp", "max_stars_repo_name": "luzpaz/voxelization_toolkit", "max_stars_repo_head_hexsha": "a166bb02880886e50e9bab02fd46367a572edfb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-06-04T13:37:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T23:23:59.000Z", "max_issues_repo_path": "tests/test_pca.cpp", "max_issues_repo_name": "luzpaz/voxelization_toolkit", "max_issues_repo_head_hexsha": "a166bb02880886e50e9bab02fd46367a572edfb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-09-07T12:04:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T15:03:29.000Z", "max_forks_repo_path": "tests/test_pca.cpp", "max_forks_repo_name": "luzpaz/voxelization_toolkit", "max_forks_repo_head_hexsha": "a166bb02880886e50e9bab02fd46367a572edfb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-05-25T11:44:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:36:28.000Z", "avg_line_length": 24.4180327869, "max_line_length": 103, "alphanum_fraction": 0.6404833837, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5878142872471623}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[register_ring\r\n//` Show the use of the macro BOOST_GEOMETRY_REGISTER_RING\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/register/ring.hpp>\r\n\r\ntypedef boost::geometry::model::d2::point_xy<double> point_2d;\r\n\r\nBOOST_GEOMETRY_REGISTER_RING(std::vector<point_2d>) /*< The magic: adapt vector to Boost.Geometry Ring Concept >*/\r\n\r\nint main()\r\n{\r\n    // Normal usage of std::\r\n    std::vector<point_2d> ring;\r\n    ring.push_back(point_2d(1, 1));\r\n    ring.push_back(point_2d(2, 2));\r\n    ring.push_back(point_2d(2, 1));\r\n    \r\n    \r\n    // Usage of Boost.Geometry\r\n    boost::geometry::correct(ring);\r\n    std::cout << \"Area: \"  << boost::geometry::area(ring) << std::endl;\r\n    std::cout << \"WKT: \"  << boost::geometry::wkt(ring) << std::endl;\r\n    \r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[register_ring_output\r\n/*`\r\nOutput:\r\n[pre\r\nArea: 0.5\r\nWKT: POLYGON((1 1,2 2,2 1,1 1))\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "3716463400e9ff9ee81659f02b6615d629c4ecdb", "size": 1317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/geometries/register/ring.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/geometry/doc/src/examples/geometries/register/ring.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/geometry/doc/src/examples/geometries/register/ring.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3269230769, "max_line_length": 115, "alphanum_fraction": 0.6583143508, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.5878036448325146}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2014 MetaScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_IEEE_FUNCTIONS_SCALAR_ULPDIST_HPP_INCLUDED\n#define BOOST_SIMD_IEEE_FUNCTIONS_SCALAR_ULPDIST_HPP_INCLUDED\n#include <boost/simd/ieee/functions/ulpdist.hpp>\n#include <boost/simd/include/constants/eps.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/functions/scalar/abs.hpp>\n#include <boost/simd/include/functions/scalar/tofloat.hpp>\n#include <boost/simd/include/functions/scalar/ldexp.hpp>\n#include <boost/simd/include/functions/scalar/frexp.hpp>\n#include <boost/simd/include/functions/scalar/max.hpp>\n#include <boost/simd/include/functions/scalar/dist.hpp>\n#include <boost/simd/include/functions/scalar/subs.hpp>\n#include <boost/simd/include/functions/scalar/is_nan.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( ulpdist_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< int_<A0> >)\n                                      (scalar_< int_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return (a0>a1) ? subs(a0,a1) : subs(a1,a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( ulpdist_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< uint_<A0> >)\n                                      (scalar_< uint_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return dist(a0,a1);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( ulpdist_, tag::cpu_\n                                    , (A0)\n                                    , (scalar_< floating_<A0> >)\n                                      (scalar_< floating_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename dispatch::meta::as_integer<A0>::type itype;\n\n      if (a0 == a1)               return Zero<A0>();\n      if (is_nan(a0)&&is_nan(a1)) return Zero<A0>();\n\n      itype e1, e2;\n\n      A0 m1 = boost::simd::frexp(a0, e1);\n      A0 m2 = boost::simd::frexp(a1, e2);\n\n      itype expo = -boost::simd::max(e1, e2);\n\n      A0 e = (e1 == e2) ? boost::simd::abs(m1-m2)\n                            :   boost::simd::abs( boost::simd::ldexp(a0, expo)\n                                                - boost::simd::ldexp(a1, expo)\n                                                );\n      return e/Eps<A0>();\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "1f8b83fbd9996c08370938c3e964eff50be36de7", "size": 3207, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/ieee/functions/scalar/ulpdist.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/ieee/functions/scalar/ulpdist.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/ieee/functions/scalar/ulpdist.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 36.4431818182, "max_line_length": 80, "alphanum_fraction": 0.5144995323, "num_tokens": 742, "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": "/**\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": "#pragma once\n\n#include \"Common.hh\"\n\n#include <ACG/Math/VectorT.hh>\n\n#include <Eigen/Dense>\n\nnamespace betri\n{\n\nclass Fitting\n{\npublic:\n\n\t// list of available solvers\n\tenum Solver\n\t{\n\t\tnormal_equation,\n\t\tqr_decomposition,\n\t\tadaptive\n\t};\n\n\tusing EigenMatT = Eigen::MatrixXd;\n\tusing EigenVectorT = Eigen::VectorXd;\n\n\tusing Vertices = std::vector<VertexHandle>;\n\n\n\texplicit Fitting(BezierTMesh &mesh) :\n\t\tm_mesh(mesh), m_degree(1), m_solver(Solver::normal_equation) {}\n\n\tvoid degree(size_t degree) { m_degree = degree; }\n\tsize_t degree() const { return m_degree; }\n\n\tvoid solver(Solver solver) { m_solver = solver; }\n\tSolver solver() const { return m_solver; }\n\n\tvirtual bool solve() = 0;\n\n\tvirtual void prepare() = 0;\n\tvirtual void cleanup() = 0;\n\nprotected:\n\n\tstatic Scalar calcCoeffs(Vec2 uv, int i, int j, size_t degree)\n\t{\n\t\tassert(std::islessequal(uv[0], 1.0));\n\t\tassert(std::islessequal(uv[1], 1.0));\n\t\treturn eval(i, j, uv, degree);\n\t}\n\n\tstatic bool solveSystem(\n\t\tEigenMatT &A,\n\t\tEigenVectorT &rhs,\n\t\tEigenVectorT &result,\n\t\tSolver solver=normal_equation\n\t) {\n\t\tEigen::ComputationInfo info;\n\n\t\tif (solver == adaptive) {\n\t\t\tsolver = std::max(A.rows(), A.cols()) > 100 ? qr_decomposition : normal_equation;\n\t\t}\n\n\t\t// solve system with specified solver\n\t\tswitch (solver) {\n\t\t\tcase normal_equation:\n\t\t\t{\n\t\t\t\tauto solver = (A.transpose() * A).ldlt();\n\t\t\t\tresult = solver.solve(A.transpose() * rhs);\n\t\t\t\tinfo = solver.info();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase qr_decomposition:\n\t\t\t{\n\t\t\t\tauto solver = A.colPivHouseholderQr();\n\t\t\t\tresult = solver.solve(rhs);\n\t\t\t\tinfo = solver.info();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (info != Eigen::Success) {\n\t\t\tstd::cerr << __FUNCTION__ << \": solver failed! (\" << info << \")\\n\";\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t///////////////////////////////////////////////////////////\n\t// member variables\n\t///////////////////////////////////////////////////////////\n\n\tBezierTMesh &m_mesh;\n\tsize_t m_degree;\n\tSolver m_solver;\n};\n\n} // namespace betri\n", "meta": {"hexsha": "dd544ae0faa5b8c3f15858f1b8c960b3fd802b74", "size": 1965, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Plugin-BezierTriangleAlgorithms/common/Fitting.hh", "max_stars_repo_name": "ArielMant0/betri", "max_stars_repo_head_hexsha": "d231e07ff8cb92d26766545c4f5d6b7350300df4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Plugin-BezierTriangleAlgorithms/common/Fitting.hh", "max_issues_repo_name": "ArielMant0/betri", "max_issues_repo_head_hexsha": "d231e07ff8cb92d26766545c4f5d6b7350300df4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugin-BezierTriangleAlgorithms/common/Fitting.hh", "max_forks_repo_name": "ArielMant0/betri", "max_forks_repo_head_hexsha": "d231e07ff8cb92d26766545c4f5d6b7350300df4", "max_forks_repo_licenses": ["BSD-3-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.4554455446, "max_line_length": 84, "alphanum_fraction": 0.617302799, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480666, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5877552245377924}}
{"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": "\n#include <gtest/gtest.h>\n#include \"../util/util.h\"\n#include <Eigen/Core>\n#include <string>\n#include <algorithm>\n\n#ifndef _MSC_VER\nextern \"C\" {\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#include <csim/update_ops.h>\n}\n#else\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#include <csim/update_ops.h>\n#endif\n\n\n\nTEST(UpdateTest, SingleQubitGateTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    Eigen::MatrixXcd X(2, 2), Y(2, 2), Z(2, 2), H(2, 2), S(2, 2), T(2, 2), sqrtX(2, 2), sqrtY(2, 2);\n    X << 0, 1, 1, 0;\n    Y << 0, -1.i, 1.i, 0;\n    Z << 1, 0, 0, -1;\n    H << 1, 1, 1, -1; H /= sqrt(2.);\n    S << 1, 0, 0, 1.i;\n    T << 1, 0, 0, (1. + 1.i) / sqrt(2.);\n    sqrtX << 0.5 + 0.5i, 0.5 - 0.5i, 0.5 - 0.5i, 0.5 + 0.5i;\n    sqrtY << 0.5 + 0.5i, -0.5 - 0.5i, 0.5 + 0.5i, 0.5 + 0.5i;\n\n    UINT target;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n    typedef std::tuple<std::function<void(UINT, CTYPE*, ITYPE)>, Eigen::MatrixXcd, std::string> testset;\n    std::vector<testset> test_list;\n    test_list.push_back(std::make_tuple(X_gate, X, \"X\"));\n    test_list.push_back(std::make_tuple(Y_gate, Y, \"Y\"));\n    test_list.push_back(std::make_tuple(Z_gate, Z, \"Z\"));\n    test_list.push_back(std::make_tuple(S_gate, S, \"S\"));\n    test_list.push_back(std::make_tuple(Sdag_gate, S.adjoint(), \"Sdag\"));\n    test_list.push_back(std::make_tuple(T_gate, T, \"T\"));\n    test_list.push_back(std::make_tuple(Tdag_gate, T.adjoint(), \"Tdag\"));\n    test_list.push_back(std::make_tuple(sqrtX_gate, sqrtX, \"sqrtX\"));\n    test_list.push_back(std::make_tuple(sqrtXdag_gate, sqrtX.adjoint(), \"sqrtXdag\"));\n    test_list.push_back(std::make_tuple(sqrtY_gate, sqrtY, \"sqrtY\"));\n    test_list.push_back(std::make_tuple(sqrtYdag_gate, sqrtY.adjoint(), \"sqrtYdag\"));\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        for (auto tup : test_list) {\n            target = rand_int(n);\n            auto func = std::get<0>(tup);\n            auto mat = std::get<1>(tup);\n            auto name = std::get<2>(tup);\n            func(target, state, dim);\n            test_state = get_expanded_eigen_matrix_with_identity(target, mat, n) * test_state;\n            state_equal(state, test_state, dim, name);\n        }\n    }\n    release_quantum_state(state);\n}\n\n\nTEST(UpdateTest, ProjectionAndNormalizeTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n    const double eps = 1e-14;\n\n    Eigen::MatrixXcd P0(2, 2), P1(2, 2);\n    P0 << 1, 0, 0, 0;\n    P1 << 0, 0, 0, 1;\n\n    UINT target;\n    double prob;\n\n    auto state = allocate_quantum_state(dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        initialize_Haar_random_state(state, dim);\n        Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n        for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n        // Z-projection operators \n        target = rand_int(n);\n        if (rep % 2 == 0) {\n            prob = M0_prob(target, state, dim);\n            EXPECT_GT(prob, 1e-10);\n            P0_gate(target, state, dim);\n            ASSERT_NEAR(state_norm(state, dim), prob, eps);\n            normalize(prob, state, dim);\n\n            test_state = get_expanded_eigen_matrix_with_identity(target, P0, n)*test_state;\n            ASSERT_NEAR(test_state.squaredNorm(), prob, eps);\n            test_state.normalize();\n            state_equal(state, test_state, dim, \"P0 gate\");\n        }\n        else {\n            prob = M1_prob(target, state, dim);\n            EXPECT_GT(prob, 1e-10);\n            P1_gate(target, state, dim);\n            ASSERT_NEAR(state_norm(state, dim), prob, eps);\n            normalize(prob, state, dim);\n\n            test_state = get_expanded_eigen_matrix_with_identity(target, P1, n)*test_state;\n            ASSERT_NEAR(test_state.squaredNorm(), prob, eps);\n            test_state.normalize();\n            state_equal(state, test_state, dim, \"P1 gate\");\n        }\n    }\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, SingleQubitRotationGateTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    Eigen::MatrixXcd Identity(2,2),X(2, 2), Y(2, 2), Z(2, 2);\n    Identity << 1, 0, 0, 1;\n    X << 0, 1, 1, 0;\n    Y << 0, -1.i, 1.i, 0;\n    Z << 1, 0, 0, -1;\n\n    UINT target;\n    double angle;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n    typedef std::tuple<std::function<void(UINT, double, CTYPE*, ITYPE)>, Eigen::MatrixXcd, std::string> testset;\n    std::vector<testset> test_list;\n    test_list.push_back(std::make_tuple(RX_gate, X, \"Xrot\"));\n    test_list.push_back(std::make_tuple(RY_gate, Y, \"Yrot\"));\n    test_list.push_back(std::make_tuple(RZ_gate, Z, \"Zrot\"));\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        for (auto tup : test_list) {\n            target = rand_int(n);\n            angle = rand_real();\n            auto func = std::get<0>(tup);\n            auto mat = std::get<1>(tup);\n            auto name = std::get<2>(tup);\n            func(target, angle, state, dim);\n            test_state = get_expanded_eigen_matrix_with_identity(target, cos(angle/2)*Identity + 1.i*sin(angle/2)*mat, n) * test_state;\n            state_equal(state, test_state, dim, name);\n        }\n    }\n    release_quantum_state(state);\n}\n\n\nTEST(UpdateTest, TwoQubitGateTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    std::vector<UINT> index_list;\n    for (UINT i = 0; i < n; ++i) index_list.push_back(i);\n\n    UINT target,control;\n    \n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n    typedef std::tuple<\n        std::function<void(UINT, UINT, CTYPE*, ITYPE)>, \n        std::function<Eigen::MatrixXcd(UINT,UINT,UINT)>, \n        std::string> testset;\n    std::vector<testset> test_list;\n    test_list.push_back(std::make_tuple(CNOT_gate, get_eigen_matrix_full_qubit_CNOT, \"CNOT\"));\n    test_list.push_back(std::make_tuple(CZ_gate, get_eigen_matrix_full_qubit_CZ, \"CZ\"));\n    test_list.push_back(std::make_tuple(SWAP_gate, get_eigen_matrix_full_qubit_SWAP, \"SWAP\"));\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        for (auto tup : test_list) {\n            std::random_shuffle(index_list.begin(), index_list.end());\n            target = index_list[0];\n            control = index_list[1];\n            ASSERT_NE(target, control);\n            auto func = std::get<0>(tup);\n            auto mat_func = std::get<1>(tup);\n            auto name = std::get<2>(tup);\n\n            func(control, target, state, dim);\n            test_state = mat_func(control,target,n) * test_state;\n            state_equal(state, test_state, dim, name);\n        }\n    }\n    release_quantum_state(state);\n}\n\n\nTEST(UpdateTest, SingleQubitPauliTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    UINT target, pauli;\n    double angle;\n\n    Eigen::MatrixXcd Identity(2, 2);\n    Identity << 1, 0, 0, 1;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        /* single qubit Pauli gate */\n        target = rand_int(n);\n        pauli = rand_int(4);\n        single_qubit_Pauli_gate(target, pauli, state, dim);\n        test_state = get_expanded_eigen_matrix_with_identity(target, get_eigen_matrix_single_Pauli(pauli), n) * test_state;\n        state_equal(state, test_state, dim, \"single Pauli gate\");\n\n        target = rand_int(n);\n        pauli = rand_int(4);\n        angle = rand_real();\n        single_qubit_Pauli_rotation_gate(target, pauli, angle, state, dim);\n        test_state = get_expanded_eigen_matrix_with_identity(target, cos(angle/2)*Identity + 1.i * sin(angle/2) * get_eigen_matrix_single_Pauli(pauli), n) * test_state;\n        state_equal(state, test_state, dim, \"single rotation Pauli gate\");\n    }\n    release_quantum_state(state);\n}\n\n\n\nTEST(UpdateTest, MultiQubitPauliTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    UINT pauli;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        // multi pauli whole\n        std::vector<UINT> pauli_whole, pauli_partial, pauli_partial_index;\n        std::vector<std::pair<UINT, UINT>> pauli_partial_pair;\n\n        pauli_whole.resize(n);\n        for (UINT i = 0; i < n; ++i) {\n            pauli_whole[i] = rand_int(4);\n        }\n        multi_qubit_Pauli_gate_whole_list(pauli_whole.data(), n, state, dim);\n        test_state = get_eigen_matrix_full_qubit_pauli(pauli_whole) * test_state;\n        state_equal(state, test_state, dim, \"multi Pauli whole gate\");\n\n        // multi pauli partial\n        pauli_partial.clear();\n        pauli_partial_index.clear();\n        pauli_partial_pair.clear();\n        for (UINT i = 0; i < n; ++i) {\n            pauli = rand_int(4);\n            pauli_whole[i] = pauli;\n            if (pauli != 0) {\n                pauli_partial_pair.push_back(std::make_pair(i, pauli));\n            }\n        }\n        std::random_shuffle(pauli_partial_pair.begin(), pauli_partial_pair.end());\n        for (auto val : pauli_partial_pair) {\n            pauli_partial_index.push_back(val.first);\n            pauli_partial.push_back(val.second);\n        }\n        multi_qubit_Pauli_gate_partial_list(pauli_partial_index.data(), pauli_partial.data(), (UINT)pauli_partial.size(), state, dim);\n        test_state = get_eigen_matrix_full_qubit_pauli(pauli_whole) * test_state;\n        state_equal(state, test_state, dim, \"multi Pauli partial gate\");\n    }\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, MultiQubitPauliRotationTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    UINT pauli;\n    double angle;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n\n        std::vector<UINT> pauli_whole, pauli_partial, pauli_partial_index;\n        std::vector<std::pair<UINT, UINT>> pauli_partial_pair;\n\n        // multi pauli rotation whole\n        pauli_whole.resize(n);\n        for (UINT i = 0; i < n; ++i) {\n            pauli_whole[i] = rand_int(4);\n        }\n        angle = rand_real();\n        multi_qubit_Pauli_rotation_gate_whole_list(pauli_whole.data(), n, angle, state, dim);\n        test_state = (cos(angle/2)*whole_I + 1.i * sin(angle/2)* get_eigen_matrix_full_qubit_pauli(pauli_whole)) * test_state;\n        state_equal(state, test_state, dim, \"multi Pauli rotation whole gate\");\n\n        // multi pauli rotation partial\n        pauli_partial.clear();\n        pauli_partial_index.clear();\n        pauli_partial_pair.clear();\n        for (UINT i = 0; i < n; ++i) {\n            pauli = rand_int(4);\n            pauli_whole[i] = pauli;\n            if (pauli != 0) {\n                pauli_partial_pair.push_back(std::make_pair(i, pauli));\n            }\n        }\n        std::random_shuffle(pauli_partial_pair.begin(), pauli_partial_pair.end());\n        for (auto val : pauli_partial_pair) {\n            pauli_partial_index.push_back(val.first);\n            pauli_partial.push_back(val.second);\n        }\n        angle = rand_real();\n        multi_qubit_Pauli_rotation_gate_partial_list(pauli_partial_index.data(), pauli_partial.data(), (UINT)pauli_partial.size(), angle, state, dim);\n        test_state = (cos(angle/2)*whole_I + 1.i * sin(angle/2)* get_eigen_matrix_full_qubit_pauli(pauli_whole)) * test_state;\n        state_equal(state, test_state, dim, \"multi Pauli rotation partial gate\");\n    }\n    release_quantum_state(state);\n}\n\n\n\n\nTEST(UpdateTest, SingleDenseMatrixTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U;\n\n    UINT target;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        // single qubit dense matrix gate\n        // NOTE: Eigen uses column major by default. To use raw-data of eigen matrix, we need to specify RowMajor.\n        target = rand_int(n);\n        U = get_eigen_matrix_random_single_qubit_unitary();\n        single_qubit_dense_matrix_gate(target, (CTYPE*)U.data(), state, dim);\n        test_state = get_expanded_eigen_matrix_with_identity(target, U, n) * test_state;\n        state_equal(state, test_state, dim, \"single dense gate\");\n    }\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, SingleDiagonalMatrixTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    Eigen::MatrixXcd Identity(2, 2),Z(2, 2);\n    Identity << 1, 0, 0, 1;\n    Z << 1, 0, 0, -1;\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U;\n\n    UINT target;\n    double icoef, zcoef, norm;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        // single qubit diagonal matrix gate\n        target = rand_int(n);\n        icoef = rand_real(); zcoef = rand_real();\n        norm = sqrt(icoef * icoef + zcoef * zcoef);\n        icoef /= norm; zcoef /= norm;\n        U = icoef * Identity + 1.i*zcoef * Z;\n        Eigen::VectorXcd diag = U.diagonal();\n        single_qubit_diagonal_matrix_gate(target, (CTYPE*)diag.data(), state, dim);\n        test_state = get_expanded_eigen_matrix_with_identity(target, U, n) * test_state;\n        state_equal(state, test_state, dim, \"single diagonal gate\");\n    }\n    release_quantum_state(state);\n}\n\n\n\nTEST(UpdateTest, SinglePhaseMatrixTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U;\n\n    UINT target;\n    double angle;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        // single qubit phase matrix gate\n        target = rand_int(n);\n        angle = rand_real();\n        U << 1, 0, 0, cos(angle) + 1.i*sin(angle);\n        single_qubit_phase_gate(target, cos(angle) + 1.i*sin(angle), state, dim);\n        test_state = get_expanded_eigen_matrix_with_identity(target, U, n) * test_state;\n        state_equal(state, test_state, dim, \"single phase gate\");\n    }\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, SingleQubitControlSingleQubitDenseMatrixTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    Eigen::MatrixXcd P0(2, 2), P1(2, 2);\n    P0 << 1, 0, 0, 0;\n    P1 << 0, 0, 0, 1;\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U;\n\n    UINT target,control;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        // single qubit control-1 single qubit gate\n        target = rand_int(n);\n        control = rand_int(n - 1);\n        if (control >= target) control++;\n        U = get_eigen_matrix_random_single_qubit_unitary();\n        single_qubit_control_single_qubit_dense_matrix_gate(control, 1, target, (CTYPE*)U.data(), state, dim);\n        test_state = (get_expanded_eigen_matrix_with_identity(control, P0, n) + get_expanded_eigen_matrix_with_identity(control, P1, n)*get_expanded_eigen_matrix_with_identity(target, U, n)) * test_state;\n        state_equal(state, test_state, dim, \"single qubit control sinlge qubit dense gate\");\n\n        // single qubit control-0 single qubit gate\n        target = rand_int(n);\n        control = rand_int(n - 1);\n        if (control >= target) control++;\n        U = get_eigen_matrix_random_single_qubit_unitary();\n        single_qubit_control_single_qubit_dense_matrix_gate(control, 0, target, (CTYPE*)U.data(), state, dim);\n        test_state = (get_expanded_eigen_matrix_with_identity(control, P1, n) + get_expanded_eigen_matrix_with_identity(control, P0, n)*get_expanded_eigen_matrix_with_identity(target, U, n)) * test_state;\n        state_equal(state, test_state, dim, \"single qubit control sinlge qubit dense gate\");\n    }\n    release_quantum_state(state);\n}\n\n\n\nTEST(UpdateTest, TwoQubitControlSingleQubitDenseMatrixTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    std::vector<UINT> index_list;\n    for (UINT i = 0; i < n; ++i) index_list.push_back(i);\n\n    Eigen::MatrixXcd P0(2, 2), P1(2, 2);\n    P0 << 1, 0, 0, 0;\n    P1 << 0, 0, 0, 1;\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U;\n\n    UINT target;\n    UINT controls[2];\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        // two qubit control-10 single qubit gate\n        std::random_shuffle(index_list.begin(), index_list.end());\n        target = index_list[0];\n        controls[0] = index_list[1];\n        controls[1] = index_list[2];\n\n        U = get_eigen_matrix_random_single_qubit_unitary();\n        UINT mvalues[2] = { 1,0 };\n        multi_qubit_control_single_qubit_dense_matrix_gate(controls, mvalues, 2, target, (CTYPE*)U.data(), state, dim);\n        test_state = (\n            get_expanded_eigen_matrix_with_identity(controls[0], P0, n)*get_expanded_eigen_matrix_with_identity(controls[1], P0, n) +\n            get_expanded_eigen_matrix_with_identity(controls[0], P0, n)*get_expanded_eigen_matrix_with_identity(controls[1], P1, n) +\n            get_expanded_eigen_matrix_with_identity(controls[0], P1, n)*get_expanded_eigen_matrix_with_identity(controls[1], P0, n)*get_expanded_eigen_matrix_with_identity(target, U, n) +\n            get_expanded_eigen_matrix_with_identity(controls[0], P1, n)*get_expanded_eigen_matrix_with_identity(controls[1], P1, n)\n            ) * test_state;\n        state_equal(state, test_state, dim, \"two qubit control sinlge qubit dense gate\");\n\n    }\n    release_quantum_state(state);\n}\n\n\nTEST(UpdateTest, TwoQubitDenseMatrixTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    std::vector<UINT> index_list;\n    for (UINT i = 0; i < n; ++i) index_list.push_back(i);\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U,U2;\n    Eigen::Matrix<std::complex<double>, 4,4, Eigen::RowMajor> Umerge;\n\n    UINT targets[2];\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n\n        // two qubit dense matrix gate\n        U = get_eigen_matrix_random_single_qubit_unitary();\n        U2 = get_eigen_matrix_random_single_qubit_unitary();\n\n        std::random_shuffle(index_list.begin(), index_list.end());\n\n        targets[0] = index_list[0];\n        targets[1] = index_list[1];\n        Umerge = kronecker_product(U2, U);\n        // the below two lines are equivalent to the above two line\n        //UINT targets_rev[2] = { targets[1], targets[0] };\n        //Umerge = kronecker_product(U, U2);\n        test_state = get_expanded_eigen_matrix_with_identity(targets[1], U2, n) * get_expanded_eigen_matrix_with_identity(targets[0], U, n) * test_state;\n        multi_qubit_dense_matrix_gate(targets, 2, (CTYPE*)Umerge.data(), state, dim);\n        state_equal(state, test_state, dim, \"two-qubit separable dense gate\");\n    }\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, TwoQubitDenseMatrixTest2) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tstd::vector<UINT> index_list;\n\tfor (UINT i = 0; i < n; ++i) index_list.push_back(i);\n\n\tEigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U, U2;\n\tEigen::Matrix<std::complex<double>, 4, 4, Eigen::RowMajor> Umerge;\n\n\tUINT targets[2];\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\tEigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\n\t\t// two qubit dense matrix gate\n\t\tU = get_eigen_matrix_random_single_qubit_unitary();\n\t\tU2 = get_eigen_matrix_random_single_qubit_unitary();\n\n\t\tstd::random_shuffle(index_list.begin(), index_list.end());\n\n\t\ttargets[0] = index_list[0];\n\t\ttargets[1] = index_list[1];\n\t\tUmerge = kronecker_product(U2, U);\n\t\t// the below two lines are equivalent to the above two line\n\t\t//UINT targets_rev[2] = { targets[1], targets[0] };\n\t\t//Umerge = kronecker_product(U, U2);\n\t\ttest_state = get_expanded_eigen_matrix_with_identity(targets[1], U2, n) * get_expanded_eigen_matrix_with_identity(targets[0], U, n) * test_state;\n\t\ttwo_qubit_dense_matrix_gate(targets[0], targets[1], (CTYPE*)Umerge.data(), state, dim);\n\t\tstate_equal(state, test_state, dim, \"two-qubit separable dense gate\");\n\t}\n\trelease_quantum_state(state);\n}\n\n\n\nTEST(UpdateTest, SingleQubitControlTwoQubitDenseMatrixTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    std::vector<UINT> index_list;\n    for (UINT i = 0; i < n; ++i) index_list.push_back(i);\n\n    Eigen::MatrixXcd P0(2, 2), P1(2, 2);\n    P0 << 1, 0, 0, 0;\n    P1 << 0, 0, 0, 1;\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U, U2;\n    Eigen::Matrix<std::complex<double>, 4, 4, Eigen::RowMajor> Umerge;\n\n    UINT targets[2], control;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        // single qubit 1-controlled qubit dense matrix gate\n        U = get_eigen_matrix_random_single_qubit_unitary();\n        U2 = get_eigen_matrix_random_single_qubit_unitary();\n        std::random_shuffle(index_list.begin(), index_list.end());\n        targets[0] = index_list[0];\n        targets[1] = index_list[1];\n        control = index_list[2];\n\n        Umerge = kronecker_product(U2, U);\n        test_state = (get_expanded_eigen_matrix_with_identity(control, P0, n) + get_expanded_eigen_matrix_with_identity(control, P1, n)*get_expanded_eigen_matrix_with_identity(targets[1], U2, n) * get_expanded_eigen_matrix_with_identity(targets[0], U, n)) * test_state;\n        single_qubit_control_multi_qubit_dense_matrix_gate(control, 1, targets, 2, (CTYPE*)Umerge.data(), state, dim);\n        state_equal(state, test_state, dim, \"single qubit control two-qubit separable dense gate\");\n    }\n    release_quantum_state(state);\n}\n\n\n\nTEST(UpdateTest, TwoQubitControlTwoQubitDenseMatrixTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    std::vector<UINT> index_list;\n    for (UINT i = 0; i < n; ++i) index_list.push_back(i);\n\n    Eigen::MatrixXcd P0(2, 2), P1(2, 2);\n    P0 << 1, 0, 0, 0;\n    P1 << 0, 0, 0, 1;\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U, U2;\n    Eigen::Matrix<std::complex<double>, 4, 4, Eigen::RowMajor> Umerge;\n\n    UINT targets[2], controls[2],mvalues[2];\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n\n        // two qubit control-11 two qubit gate\n        U = get_eigen_matrix_random_single_qubit_unitary();\n        U2 = get_eigen_matrix_random_single_qubit_unitary();\n        std::random_shuffle(index_list.begin(), index_list.end());\n        targets[0] = index_list[0];\n        targets[1] = index_list[1];\n        controls[0] = index_list[2];\n        controls[1] = index_list[3];\n\n        mvalues[0] = 1; mvalues[1] = 1;\n        Umerge = kronecker_product(U2, U);\n        multi_qubit_control_multi_qubit_dense_matrix_gate(controls, mvalues, 2, targets, 2, (CTYPE*)Umerge.data(), state, dim);\n        test_state = (\n            get_expanded_eigen_matrix_with_identity(controls[0], P0, n)*get_expanded_eigen_matrix_with_identity(controls[1], P0, n) +\n            get_expanded_eigen_matrix_with_identity(controls[0], P0, n)*get_expanded_eigen_matrix_with_identity(controls[1], P1, n) +\n            get_expanded_eigen_matrix_with_identity(controls[0], P1, n)*get_expanded_eigen_matrix_with_identity(controls[1], P0, n) +\n            get_expanded_eigen_matrix_with_identity(controls[0], P1, n)*get_expanded_eigen_matrix_with_identity(controls[1], P1, n)*get_expanded_eigen_matrix_with_identity(targets[0], U, n)*get_expanded_eigen_matrix_with_identity(targets[1], U2, n)\n            ) * test_state;\n        state_equal(state, test_state, dim, \"two qubit control two qubit dense gate\");\n    }\n    release_quantum_state(state);\n}\n", "meta": {"hexsha": "dcefd75b4f89139237701a288f06431c959d8b13", "size": 27034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/csim/test_update.cpp", "max_stars_repo_name": "puyokw/qulacs", "max_stars_repo_head_hexsha": "cc22285695a35c2393972798bc9c3f4e04771055", "max_stars_repo_licenses": ["MIT"], "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/csim/test_update.cpp", "max_issues_repo_name": "puyokw/qulacs", "max_issues_repo_head_hexsha": "cc22285695a35c2393972798bc9c3f4e04771055", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-12-13T12:40:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-13T17:47:06.000Z", "max_forks_repo_path": "test/csim/test_update.cpp", "max_forks_repo_name": "puyokw/qulacs", "max_forks_repo_head_hexsha": "cc22285695a35c2393972798bc9c3f4e04771055", "max_forks_repo_licenses": ["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.2917847025, "max_line_length": 269, "alphanum_fraction": 0.6444847229, "num_tokens": 7910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5876698486206484}}
{"text": "#include <boost/math/constants/constants.hpp>\n\n#include <TMath.h>\n\n#include \"IbdInteraction.hh\"\n#include \"IbdZeroOrder.hh\"\n#include \"PDGVariables.hh\"\n\n#include <iostream>\n\nconstexpr double pi = boost::math::constants::pi<double>();\n\nIbdZeroOrder::IbdZeroOrder()\n{\n  transformation_(\"Enu\")\n    .input(\"Ee\")\n    .output(\"Enu\")\n    .func(&IbdZeroOrder::calcEnu);\n  transformation_(\"xsec\")\n    .input(\"Ee\")\n    .output(\"xsec\")\n    .func(&IbdZeroOrder::calcXsec);\n}\n\nIbdZeroOrder::IbdZeroOrder(bool useEnu): IbdZeroOrder() {\n    this->useEnu = useEnu;\n}\n\nvoid IbdZeroOrder::calcEnu(FunctionArgs fargs) {\n  fargs.rets[0].x = fargs.args[0].x + m_DeltaNP;\n}\n\nvoid IbdZeroOrder::calcXsec(FunctionArgs fargs) {\n  Eigen::ArrayXd Ee;\n  if (this->useEnu) {\n      Ee = fargs.args[0].x - m_DeltaNP;\n  } else {\n      Ee = fargs.args[0].x;\n  }\n\n  const double MeV2J = 1.E6 * TMath::Qe();\n  const double J2MeV = 1./MeV2J;\n\n  const double MeV2cm = pow(TMath::Hbar()*TMath::C()*J2MeV, 2) * 1.E4;\n\n  Eigen::ArrayXd pe = (Ee.square() - m_pdg->ElectronMass*m_pdg->ElectronMass).sqrt();\n/* Sanity check to null all possible nans */\n  std::transform(pe.data(), pe.data() + pe.size(), pe.data(),\n                [](double x){return (!std::isnan(x) ? x : 0.);});\n  auto coeff = 2.*pi*pi /\n    (std::pow(m_pdg->ElectronMass, 5) * PhaseFactor * m_pdg->NeutronLifeTime/(1.E-6*TMath::Hbar()/TMath::Qe()));\n  fargs.rets[0].x = MeV2cm * coeff*Ee*pe;\n}\n", "meta": {"hexsha": "7068ddf3b76b055d7eb53a42924a8a1b78d7daae", "size": 1419, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/neutrino/IbdZeroOrder.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/neutrino/IbdZeroOrder.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/neutrino/IbdZeroOrder.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2777777778, "max_line_length": 112, "alphanum_fraction": 0.6420014094, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253257, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5876698428818902}}
{"text": "/*\n** EPITECH PROJECT, 2017\n** ECS Engine\n** File description:\n** Thomas Arbona\n*/\n#pragma once\n\n#include <vector>\n#include <irrlicht/irrlicht.h>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include \"../core/Scene.hpp\"\n\nnamespace engine {\n\n    struct TransformComponent;\n    struct HitboxComponent;\n    struct PhysicsComponent;\n    class Entity;\n\n    using Point = boost::geometry::model::d2::point_xy<float>;\n    using Polygon = boost::geometry::model::polygon<Point>;\n    using Segment = boost::geometry::model::referring_segment<const Point>;\n\n    using Vec2D = irr::core::vector2d<float>;\n\n    struct Segment3D {\n        irr::core::vector3df p1;\n        irr::core::vector3df p2;\n    };\n\n\n    struct Manifold {\n        bool isCollide = false;\n        bool hasError = false;\n        Vec2D normal{0.f, 0.f};\n    };\n\n\tclass GeometryHelper {\n\tpublic:\n        static std::vector<Segment> getCombinedSegments(Polygon const& p1, Polygon const& p2);\n        static bool segmentsAreCollinear(Segment const& s1, Segment const& s2);\n        static void transformHitbox(HitboxComponent& hitbox, TransformComponent const& transform);\n        static Manifold polygonCollide(Entity const& entity, Entity const& entity2, float rebound, int call = 0);\n        static Manifold polygonCollideChilds(Entity const& entity, Entity const& entity2, float rebound);\n        static bool simplePolygonCollide(Entity const& entity, Entity const& entity2);\n        static Point mergeSegmentsIntoVector(std::vector<Segment> const& segments);\n        static bool AABBCollide(HitboxComponent const& h1, HitboxComponent const& h2);\n\t\tstatic Entity createBlastPolygon(Scene& scene, float x, float y, float radius);\n\n        static const float epsilon;\n\n\tprivate:\n        GeometryHelper() = default;\n        ~GeometryHelper() = default;\n\t};\n}\n", "meta": {"hexsha": "f8ae3ede3b3dd52f0a269e0712a532cacb962605", "size": 1896, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/engine/helpers/GeometryHelper.hpp", "max_stars_repo_name": "arthurchaloin/indie", "max_stars_repo_head_hexsha": "84fa7f0864c54e4b35620235ca4e852d7b85fffd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/engine/helpers/GeometryHelper.hpp", "max_issues_repo_name": "arthurchaloin/indie", "max_issues_repo_head_hexsha": "84fa7f0864c54e4b35620235ca4e852d7b85fffd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/engine/helpers/GeometryHelper.hpp", "max_forks_repo_name": "arthurchaloin/indie", "max_forks_repo_head_hexsha": "84fa7f0864c54e4b35620235ca4e852d7b85fffd", "max_forks_repo_licenses": ["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.6, "max_line_length": 113, "alphanum_fraction": 0.6993670886, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5876698269935696}}
{"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//! [remainders]\n#include <boost/simd/arithmetic.hpp>\n#include <boost/simd/pack.hpp>\n#include <iostream>\n\nnamespace bs =  boost::simd;\nusing pack_ft =  bs::pack <float, 8>;\n\nint main()\n{\n  pack_ft p = {-4, -3, -2, -1, 1, 2, 3, 4};\n  pack_ft q = { 5,  2,  3,  2, 2, 3, 2, 5};\n  std::cout << \" p = \" << p << std::endl\n            << \" q = \" << q << std::endl\n            <<  \" -> bs::rem(bs::ceil,      p, q) = \" << bs::rem(bs::ceil,      p, q) << std::endl\n            <<  \" -> bs::rem(bs::floor,     p, q) = \" << bs::rem(bs::floor,     p, q) << std::endl\n            <<  \" -> bs::rem(bs::fix,       p, q) = \" << bs::rem(bs::fix,       p, q) << std::endl\n            <<  \" -> bs::rem(bs::round,     p, q) = \" << bs::rem(bs::round,     p, q) << std::endl\n            <<  \" -> bs::rem(bs::nearbyint, p, q) = \" << bs::rem(bs::nearbyint, p, q) << std::endl;\n  return 0;\n}\n//! [remainders]\n", "meta": {"hexsha": "97a89e583ee9e625216f9d53fe1ac7ec5d3ee2a7", "size": 1265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/arithmetic/remainders.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/remainders.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/remainders.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": 40.8064516129, "max_line_length": 100, "alphanum_fraction": 0.4055335968, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.587641766899899}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <test/unit/math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdGammaP, gamma_p){\n  using stan::math::fvar;\n  using stan::math::gamma_p;\n  using boost::math::gamma_p;\n\n  fvar<double> x(0.5);\n  x.d_ = 1.0;\n  fvar<double> y (1.0);\n  y.d_ = 1.0;\n\n  fvar<double> a = gamma_p(x,y);\n  EXPECT_FLOAT_EQ(gamma_p(0.5,1.0), a.val_);\n  EXPECT_FLOAT_EQ(-0.18228334, a.d_);\n\n  double z = 1.0;\n  double w = 0.5;\n\n  a = gamma_p(x,z);\n  EXPECT_FLOAT_EQ(gamma_p(0.5,1.0), a.val_);\n  EXPECT_FLOAT_EQ(-0.389837, a.d_);\n\n  a = gamma_p(w,y);\n  EXPECT_FLOAT_EQ(gamma_p(0.5,1.0), a.val_);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), a.d_);\n\n  EXPECT_THROW(gamma_p(-x,y), std::domain_error);\n  EXPECT_THROW(gamma_p(x,-y), std::domain_error);\n}\n\nTEST(AgradFwdGammaP, FvarFvarDouble) {\n  using stan::math::fvar;\n  using boost::math::gamma_p;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<double> > a = gamma_p(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_p(0.5,1.0), a.val_.val_);\n  EXPECT_FLOAT_EQ(-0.38983709, a.val_.d_);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_);\n  EXPECT_FLOAT_EQ(0.40753385, a.d_.d_);\n}\n\n\nstruct gamma_p_fun {\n  template <typename T0, typename T1>\n  inline \n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return gamma_p(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdGammaP, nan) {\n  gamma_p_fun gamma_p_;\n  test_nan_fwd(gamma_p_,3.0,5.0,false);\n}\n", "meta": {"hexsha": "9eb367807f0fcc08f79aac4803bcb4c9706ca01b", "size": 1703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/gamma_p_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/gamma_p_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/gamma_p_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.985915493, "max_line_length": 71, "alphanum_fraction": 0.6711685261, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5875044518052882}}
{"text": "//    boost asinh.hpp header file\n\n//  (C) Copyright Eric Ford & Hubert Holin 2001.\n//  (C) Copyright John Maddock 2008.\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 updates, documentation, and revision history.\n\n#ifndef BOOST_ASINH_HPP\n#define BOOST_ASINH_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n\n#include <boost/config/no_tr1/cmath.hpp>\n#include <boost/config.hpp>\n#include <boost/math/tools/precision.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/special_functions/sqrt1pm1.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n\n// This is the inverse of the hyperbolic sine function.\n\nnamespace boost\n{\n    namespace math\n    {\n       namespace detail{\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, class Policy>\n        inline T    asinh_imp(const T x, const Policy& pol)\n        {\n            BOOST_MATH_STD_USING\n            \n            if        (x >= tools::forth_root_epsilon<T>())\n            {\n               if        (x > 1 / tools::root_epsilon<T>())\n                {\n                    // http://functions.wolfram.com/ElementaryFunctions/ArcSinh/06/01/06/01/0001/\n                    // approximation by laurent series in 1/x at 0+ order from -1 to 1\n                    return log(x * 2) + 1/ (4 * x * x);\n                }\n                else if(x < 0.5f)\n                {\n                   // As below, but rearranged to preserve digits:\n                   return boost::math::log1p(x + boost::math::sqrt1pm1(x * x, pol), pol);\n                }\n                else\n                {\n                    // http://functions.wolfram.com/ElementaryFunctions/ArcSinh/02/\n                    return( log( x + sqrt(x*x+1) ) );\n                }\n            }\n            else if    (x <= -tools::forth_root_epsilon<T>())\n            {\n                return(-asinh(-x));\n            }\n            else\n            {\n                // http://functions.wolfram.com/ElementaryFunctions/ArcSinh/06/01/03/01/0001/\n                // approximation by taylor series in x at 0 up to order 2\n                T    result = x;\n                \n                if    (abs(x) >= tools::root_epsilon<T>())\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        template<typename T>\n        inline typename tools::promote_args<T>::type asinh(T x)\n        {\n           return boost::math::asinh(x, policies::policy<>());\n        }\n        template<typename T, typename Policy>\n        inline typename tools::promote_args<T>::type asinh(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            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           return policies::checked_narrowing_cast<result_type, forwarding_policy>(\n              detail::asinh_imp(static_cast<value_type>(x), forwarding_policy()),\n              \"boost::math::asinh<%1%>(%1%)\");\n        }\n\n    }\n}\n\n#endif /* BOOST_ASINH_HPP */\n\n", "meta": {"hexsha": "14289688b42a576abeba7201ea060c663b34171b", "size": 3942, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/math/special_functions/asinh.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/asinh.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-11-22T13:14:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T00:56:51.000Z", "max_forks_repo_path": "boost/boost/math/special_functions/asinh.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": 33.6923076923, "max_line_length": 97, "alphanum_fraction": 0.5322171487, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.587504439028937}}
{"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 *  .file test/oglplus/angle.cpp\n *  .brief Test case for Angle class and related functionality.\n *\n *  .author Matus Chochlik\n *\n *  Copyright 2011-2019 Matus Chochlik. Distributed under the Boost\n *  Software License, Version 1.0. (See accompanying file\n *  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE OGLPLUS_Angle\n#include <boost/test/unit_test.hpp>\n\n#include <oglplus/gl.hpp>\n#include <oglplus/math/angle.hpp>\n\nBOOST_AUTO_TEST_SUITE(Angle)\n\nBOOST_AUTO_TEST_CASE(Angle_default_construction) {\n    oglplus::Angle<float> af;\n    oglplus::Angle<double> ad;\n}\n\nBOOST_AUTO_TEST_CASE(Angle_construction) {\n    using Anglef = oglplus::Angle<float>;\n    Anglef a1 = Anglef::Degrees(90);\n    Anglef a2 = Anglef::Radians(oglplus::math::HalfPi());\n    Anglef a3 = oglplus::Degrees(90);\n    Anglef a4 = oglplus::Radians(oglplus::math::HalfPi());\n    Anglef a5 = oglplus::RightAngles(1.0f);\n    Anglef a6 = oglplus::FullCircles(1.0f);\n    Anglef a7 = a6;\n}\n\nBOOST_AUTO_TEST_CASE(Angle_value) {\n    using Anglef = oglplus::Angle<float>;\n\n    Anglef a1 = Anglef::Radians(oglplus::math::HalfPi());\n    Anglef a2 = Anglef::Radians(oglplus::math::Pi());\n    Anglef a3 = Anglef::Radians(oglplus::math::TwoPi());\n\n    BOOST_CHECK_EQUAL(a1.ValueInDegrees(), 90);\n    BOOST_CHECK_EQUAL(a2.ValueInDegrees(), 180);\n    BOOST_CHECK_EQUAL(a3.ValueInDegrees(), 360);\n    BOOST_CHECK_EQUAL(a1.Value(), float(oglplus::math::HalfPi()));\n    BOOST_CHECK_EQUAL(a2.Value(), float(oglplus::math::Pi()));\n    BOOST_CHECK_EQUAL(a3.Value(), float(oglplus::math::TwoPi()));\n\n    Anglef a4 = oglplus::RightAngles(1.0f);\n    Anglef a5 = oglplus::FullCircles(1.0f);\n\n    BOOST_CHECK_EQUAL(a1.ValueInDegrees(), a4.ValueInDegrees());\n    BOOST_CHECK_EQUAL(a3.ValueInDegrees(), a5.ValueInDegrees());\n}\n\nBOOST_AUTO_TEST_CASE(Angle_cmp) {\n    using Anglef = oglplus::Angle<float>;\n\n    Anglef a1 = Anglef::Radians(oglplus::math::HalfPi());\n    Anglef a2 = Anglef::Radians(oglplus::math::TwoPi());\n\n    Anglef a3 = oglplus::RightAngles(1.0f);\n    Anglef a4 = oglplus::FullCircles(1.0f);\n\n    BOOST_CHECK(a1 == a1);\n    BOOST_CHECK(a2 == a2);\n\n    BOOST_CHECK(a1 != a2);\n    BOOST_CHECK(a3 != a4);\n\n    BOOST_CHECK(a1 == a3);\n    BOOST_CHECK(a2 == a4);\n}\n\nBOOST_AUTO_TEST_CASE(Angle_addition) {\n    using Angled = oglplus::Angle<double>;\n\n    Angled a0;\n    Angled a1 = Angled::Radians(oglplus::math::HalfPi());\n    Angled a2 = Angled::Radians(oglplus::math::Pi());\n    Angled a3 = Angled::Radians(oglplus::math::TwoPi());\n\n    BOOST_CHECK((a0 + a0) == a0);\n    BOOST_CHECK((a0 + a1) == a1);\n    BOOST_CHECK((a1 + a1) == a2);\n    BOOST_CHECK((a2 + a2) == a3);\n    BOOST_CHECK((a1 + a2 + a1) == a3);\n    BOOST_CHECK((a1 + a1 + a1 + a1) == a3);\n}\n\nBOOST_AUTO_TEST_CASE(Angle_subtraction) {\n    using Angled = oglplus::Angle<double>;\n\n    Angled a0;\n    Angled a1 = Angled::Radians(oglplus::math::HalfPi());\n    Angled a2 = Angled::Radians(oglplus::math::Pi());\n    Angled a3 = Angled::Radians(oglplus::math::TwoPi());\n\n    BOOST_CHECK((a0 - a0) == a0);\n    BOOST_CHECK((a1 - a1) == a0);\n    BOOST_CHECK((a1 - a0) == a1);\n    BOOST_CHECK((a0 - a1) == -a1);\n    BOOST_CHECK((a2 - a1) == a1);\n    BOOST_CHECK((-a1 + a2) == a1);\n    BOOST_CHECK((a3 - a2 - a1) == a1);\n    BOOST_CHECK((a3 - a2 - a1 - a1) == a0);\n    BOOST_CHECK((-a1 - a2 + a3) == a1);\n    BOOST_CHECK((-a1 - a1 - a1 - a1) == -a3);\n    BOOST_CHECK(-(-a1 - a1 - a2) == a3);\n}\n\nBOOST_AUTO_TEST_CASE(Angle_multiplication) {\n    using Angled = oglplus::Angle<double>;\n\n    Angled a0;\n    Angled a1 = Angled::Radians(oglplus::math::HalfPi());\n    Angled a2 = Angled::Radians(oglplus::math::Pi());\n    Angled a3 = Angled::Radians(oglplus::math::TwoPi());\n\n    BOOST_CHECK((2 * a0) == a0);\n    BOOST_CHECK((0 * a1) == a0);\n    BOOST_CHECK((2 * a1) == a2);\n    BOOST_CHECK((2 * a2) == a3);\n    BOOST_CHECK(a1 == (a2 * 0.5));\n    BOOST_CHECK((4 * a1) == (2 * a2));\n    BOOST_CHECK((2.1 * a1) == (a1 * 2.1));\n    BOOST_CHECK((3.0 * a1) == (a2 * 1.5));\n    BOOST_CHECK((2.4 * a1) == (a2 * 1.2));\n    BOOST_CHECK((4.4 * a1) == (a3 * 1.1));\n    BOOST_CHECK((oglplus::math::TwoPi() * a1) == (a2 * oglplus::math::Pi()));\n}\n\nBOOST_AUTO_TEST_CASE(Angle_division) {\n    using Angled = oglplus::Angle<double>;\n\n    Angled a0;\n    Angled a1 = Angled::Radians(oglplus::math::HalfPi());\n    Angled a2 = Angled::Radians(oglplus::math::Pi());\n    Angled a3 = Angled::Radians(oglplus::math::TwoPi());\n\n    BOOST_CHECK(a0 == (a0 / 2));\n    BOOST_CHECK(a1 == (a2 / 2));\n    BOOST_CHECK(a2 == (a3 / 2));\n    BOOST_CHECK(a1 == (a3 / 4));\n    BOOST_CHECK((a1 / 3) == (a2 / 6));\n    BOOST_CHECK((a1 / 3) == (a3 / 12));\n    BOOST_CHECK((a1 / oglplus::math::Pi()) == (a2 / oglplus::math::TwoPi()));\n}\n\nBOOST_AUTO_TEST_CASE(Angle_arithmetic) {\n    using Angled = oglplus::Angle<double>;\n\n    Angled a0;\n    Angled a1 = Angled::Radians(oglplus::math::HalfPi());\n    Angled a2 = Angled::Radians(oglplus::math::Pi());\n    Angled a3 = Angled::Radians(oglplus::math::TwoPi());\n\n    BOOST_CHECK((a1 + a1 + a1) == (3.0 * a2) / 2.0);\n    BOOST_CHECK((a1 + a0) == (a1 - a0));\n    BOOST_CHECK(2.0 * (-a1 - a2 + a3) == a3 / 2.0);\n    BOOST_CHECK((9 * a1 - 4 * a2) * 3.0 + a1 == a3);\n}\n\nBOOST_AUTO_TEST_CASE(Angle_sin_cos) {\n    using Angled = oglplus::Angle<double>;\n\n    Angled a0;\n    Angled a1 = Angled::Radians(oglplus::math::HalfPi());\n    Angled a2 = Angled::Radians(oglplus::math::Pi());\n    Angled a3 = Angled::Radians(oglplus::math::TwoPi());\n    double eps = 1e-9;\n\n    BOOST_CHECK_EQUAL(Sin(a0), 0.0);\n    BOOST_CHECK_EQUAL(Cos(a0), 1.0);\n\n    BOOST_CHECK_CLOSE(Sin(a1), 1.0, eps);\n    BOOST_CHECK_CLOSE(Sin(a2) + 1.0, 1.0, eps);\n    BOOST_CHECK_CLOSE(Sin(a2) + 1.0, Sin(a0) + 1.0, eps);\n    BOOST_CHECK_CLOSE(Sin(a2 + a1), -1.0, eps);\n\n    BOOST_CHECK_CLOSE(Cos(a1) + 1.0, 1.0, eps);\n    BOOST_CHECK_CLOSE(Cos(a2), -1.0, eps);\n    BOOST_CHECK_CLOSE(Cos(a2 + a1) + 1.0, 1.0, eps);\n\n    BOOST_CHECK_CLOSE(Sin(a1), Sin(100000 * a3 + a1), eps);\n    BOOST_CHECK_CLOSE(Cos(a0), Cos(100000 * a3 + a0), eps);\n\n    BOOST_CHECK(Sin(a2 + a1) == Sin(a3 - a1));\n    BOOST_CHECK(Cos(a2 + a1) == Cos(a3 - a1));\n}\n\nBOOST_AUTO_TEST_CASE(Angle_sin_cos_2) {\n    using Angled = oglplus::Angle<double>;\n    Angled a3 = Angled::Radians(oglplus::math::TwoPi());\n\n    double eps = 1e-8;\n    double d = 1.6181;\n\n    for(unsigned i = 0; i != 1000; ++i) {\n        Angled a = Angled::Radians(i * i * d);\n        BOOST_CHECK_CLOSE(Sin(a) + 2.0, Sin(a + a3 * i) + 2.0, eps);\n        BOOST_CHECK_CLOSE(Cos(a) + 2.0, Cos(a + a3 * i) + 2.0, eps);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Angle_tan) {\n    using Angled = oglplus::Angle<double>;\n\n    double eps = 1e-9;\n    double d = 1.6181;\n\n    for(unsigned i = 0; i != 1000; ++i) {\n        Angled a = Angled::Radians(i * i * d);\n        BOOST_CHECK_CLOSE(Sin(a) / Cos(a) + 2.0, Tan(a) + 2.0, eps);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Angle_arc) {\n    using oglplus::ArcCos;\n    using oglplus::ArcSin;\n\n    using Angled = oglplus::Angle<double>;\n\n    double eps = 2;\n\n    for(unsigned i = 1; i != 1000; ++i) {\n        Angled a = Angled::Radians(oglplus::math::HalfPi() / i);\n        BOOST_CHECK_CLOSE(a.Value(), ArcSin(Sin(a)).Value(), eps);\n        BOOST_CHECK_CLOSE(a.Value(), ArcCos(Cos(a)).Value(), eps);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f12ff264aa1288f30c24a4a5d5462344edca5572", "size": 7313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/oglplus/angle.cpp", "max_stars_repo_name": "matus-chochlik/oglplus", "max_stars_repo_head_hexsha": "76dd964e590967ff13ddff8945e9dcf355e0c952", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 364.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T09:38:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:32:00.000Z", "max_issues_repo_path": "test/oglplus/angle.cpp", "max_issues_repo_name": "matus-chochlik/oglplus", "max_issues_repo_head_hexsha": "76dd964e590967ff13ddff8945e9dcf355e0c952", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 55.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T16:42:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-09T04:21:41.000Z", "max_forks_repo_path": "test/oglplus/angle.cpp", "max_forks_repo_name": "matus-chochlik/oglplus", "max_forks_repo_head_hexsha": "76dd964e590967ff13ddff8945e9dcf355e0c952", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 57.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T18:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T05:32:04.000Z", "avg_line_length": 31.1191489362, "max_line_length": 77, "alphanum_fraction": 0.6141118556, "num_tokens": 2531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5874968545054576}}
{"text": "#define BOOST_TEST_NO_LIB\n#include <boost/test/auto_unit_test.hpp>\n\n#include \"coconut/pulp/math/Vector.hpp\"\n\nusing namespace coconut;\nusing namespace coconut::pulp;\nusing namespace coconut::pulp::math;\n\nnamespace /* anonymous */ {\n\nBOOST_AUTO_TEST_SUITE(PulpTestSuite);\nBOOST_AUTO_TEST_SUITE(PulpMathTestSuite);\nBOOST_AUTO_TEST_SUITE(PulpMathVectorTestSuite);\n\nBOOST_AUTO_TEST_CASE(VectorConstructionAndElementAccessWorks) {\n\tconst auto oneTwoThreeFour = Vec4(1.0f, 2.0f, 3.0f, 4.0f);\n\tauto oneTwoThenThree = Vector<int, 2>{ 1, 2 };\n\n\tBOOST_CHECK_EQUAL(oneTwoThreeFour.x(), 1.0f);\n\tBOOST_CHECK_EQUAL(oneTwoThreeFour.y(), 2.0f);\n\tBOOST_CHECK_EQUAL(oneTwoThreeFour.z(), 3.0f);\n\tBOOST_CHECK_EQUAL(oneTwoThreeFour.w(), 4.0f);\n\n\tBOOST_CHECK_EQUAL(oneTwoThenThree.x(), 1);\n\tBOOST_CHECK_EQUAL(oneTwoThenThree.y(), 2);\n\toneTwoThenThree.y() = 4;\n\tBOOST_CHECK_EQUAL(oneTwoThenThree.y(), 4);\n}\n\nBOOST_AUTO_TEST_CASE(DefaultConstructorYieldsZeros) {\n\tconst auto zero = Vec2();\n\tBOOST_CHECK_EQUAL(zero, Vec2(0.0f, 0.0f));\n}\n\nBOOST_AUTO_TEST_CASE(HigherDimensionVectorsAreConstructibleFromLower) {\n\tconst auto oneTwoThree = Vector<std::int32_t, 3>(1, 2, 3);\n\tconst auto oneTwoThreeFour = Vector<std::int32_t, 4>(oneTwoThree, 4);\n\tconst auto oneTwoThreeFourFive = Vector<std::int64_t, 5>(oneTwoThree, 4, 5);\n\n\tconst auto expected1234 = Vector<std::int32_t, 4>(1, 2, 3, 4);\n\tconst auto expected12345 = Vector<std::int64_t, 5>(1, 2, 3, 4, 5);\n\n\tBOOST_CHECK_EQUAL(oneTwoThreeFour, expected1234);\n\tBOOST_CHECK_EQUAL(oneTwoThreeFourFive, expected12345);\n}\n\nBOOST_AUTO_TEST_CASE(VectorsAreEqualityComparable) {\n\tconst auto iOne = Vector<int, 1>(1);\n\tconst auto iOne2 = Vector<int, 1>(1);\n\tconst auto iTwo = Vector<int, 1>(2);\n\n\tBOOST_CHECK_EQUAL(iOne, iOne2);\n\tBOOST_CHECK_NE(iOne, iTwo);\n\n\tconst auto fOneTwo = Vec2(1.0f, 2.0f);\n\tconst auto fOneAlmostTwo = Vec2(1.0f, 2.0f - 0.0000001f);\n\tconst auto fOneNotTwo = Vec2(1.0f, 2.0f - 0.001f);\n\n\tBOOST_CHECK_EQUAL(fOneTwo, fOneAlmostTwo);\n\tBOOST_CHECK_NE(fOneTwo, fOneNotTwo);\n}\n\nBOOST_AUTO_TEST_CASE(VectorsAreAdditive) {\n\tauto lhs = Vec3(1.0f, 1.0f, 1.0f);\n\tconst auto rhs = Vec3(0.0f, 1.0f, 2.0f);\n\tconst auto sum = Vec3(1.0f, 2.0f, 3.0f);\n\n\tBOOST_CHECK_EQUAL(lhs + rhs, sum);\n\n\tlhs += rhs;\n\tBOOST_CHECK_EQUAL(lhs, sum);\n\n\tlhs -= rhs;\n\tBOOST_CHECK_EQUAL(lhs, sum - rhs);\n}\n\nBOOST_AUTO_TEST_CASE(VectorsAreNegatable) {\n\tauto vector = Vec2(4.5f, 6.7f);\n\tauto negated = Vec2(-4.5f, -6.7f);\n\t\n\tBOOST_CHECK_EQUAL(-vector, negated);\n}\n\nBOOST_AUTO_TEST_CASE(VectorsAreScalarMultiplicative) {\n\tauto vector = Vec2(0.5f, 1.0f);\n\tconst auto product = Vec2(1.0f, 2.0f);\n\n\tBOOST_CHECK_EQUAL(vector * 2, product);\n\n\tvector *= 2.0f;\n\tBOOST_CHECK_EQUAL(vector, product);\n\n\tvector /= 2.0f;\n\tBOOST_CHECK_EQUAL(vector, product / 2.0f);\n}\n\nBOOST_AUTO_TEST_CASE(DotProducesDotProduct) {\n\tconst auto lhs = Vec2(1.0f, 25.0f);\n\tconst auto rhs = Vec2(0.5f, 0.1f);\n\n\tBOOST_CHECK_EQUAL(dot(lhs, rhs), 3.0f);\n}\n\nBOOST_AUTO_TEST_CASE(CrossProducesCrossProduct) {\n\tauto lhs = Vec3(0.123f, 4.5f, -3.14f);\n\tconst auto rhs = Vec3(0.0f, -0.1f, 5.001f);\n\tconst auto product = Vec3(22.1905f, -0.615123f, -0.0123f);\n\n\tBOOST_CHECK_EQUAL(cross(lhs, rhs), product);\n}\n\nBOOST_AUTO_TEST_CASE(LengthReturnsVectorLength) {\n\tconst auto vec = Vec2(3.12f, 0.14f);\n\n\tBOOST_CHECK_CLOSE(vec.length(), 3.12313944613f, 0.01f);\n\tBOOST_CHECK_CLOSE(vec.lengthSq(), 9.754f, 0.01f);\n}\n\nBOOST_AUTO_TEST_CASE(NormalisedReturnsNormalised) {\n\tauto vec = Vec2(3.12f, 0.14f);\n\tconst auto normalised = Vec2(0.998994778f, 0.044826688f);\n\n\tBOOST_CHECK_EQUAL(vec.normalised(), normalised);\n\t\n\tvec.normalise();\n\tBOOST_CHECK_EQUAL(vec, normalised);\n\n\tBOOST_CHECK_CLOSE(vec.lengthSq(), 1.0f, 0.01f);\n}\n\nBOOST_AUTO_TEST_SUITE_END(/* PulpMathVectorTestSuite */);\nBOOST_AUTO_TEST_SUITE_END(/* PulpMathTestSuite */);\nBOOST_AUTO_TEST_SUITE_END(/* PulpTestSuite */);\n\n} // namespace anonymous\n", "meta": {"hexsha": "e3e013bea42ad554ee4447742f84fd8cf71dc1d9", "size": 3846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "coconut-pulp-math/src/test/c++/coconut/pulp/math/Vector.cpp", "max_stars_repo_name": "mikosz/coconut", "max_stars_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T12:01:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T12:01:54.000Z", "max_issues_repo_path": "coconut-pulp-math/src/test/c++/coconut/pulp/math/Vector.cpp", "max_issues_repo_name": "mikosz/coconut", "max_issues_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coconut-pulp-math/src/test/c++/coconut/pulp/math/Vector.cpp", "max_forks_repo_name": "mikosz/coconut", "max_forks_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0729927007, "max_line_length": 77, "alphanum_fraction": 0.7392095684, "num_tokens": 1275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5874968398352313}}
{"text": "\n// solving A * X = B\n// using driver function gesv()\n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <cstddef>\n#include <iostream>\n#include <boost/numeric/bindings/atlas/cblas.hpp>\n#include <boost/numeric/bindings/atlas/clapack.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\n#ifndef F_ROW_MAJOR\ntypedef ublas::matrix<double, ublas::column_major> m_t;\n#else\ntypedef ublas::matrix<double, ublas::row_major> m_t;\n#endif\n\nint main() {\n\n  cout << endl; \n\n  size_t n = 5;   \n  m_t a (n, n);   // system matrix \n\n  size_t nrhs = 2; \n  m_t x (n, nrhs), bb (n, nrhs);  \n  // b -- right-hand side matrix, see below \n\n  init_symm (a); \n  //     [n   n-1 n-2  ... 1]\n  //     [n-1 n   n-1  ... 2]\n  // a = [n-2 n-1 n    ... 3]\n  //     [        ...       ]\n  //     [1   2   ...  n-1 n]\n\n  m_t const aa (a); // copy of a, because a is `lost' after gesv()\n\n  ublas::matrix_column<m_t> xc0 (x, 0), xc1 (x, 1); \n  atlas::set (1., xc0);\n  atlas::set (2., xc1);\n  atlas::gemm (a, x, bb);  // bb = a x, so we know the result ;o) \n\n  print_m (a, \"A\"); \n  cout << endl; \n  print_m (bb, \"B\"); \n  cout << endl; \n\n  // see leading comments for `gesv()' in clapack.hpp\n#ifndef F_ROW_MAJOR\n  m_t b (bb); \n#else \n  m_t b (ublas::trans (bb)); \n#endif \n  print_m (b, \"B for gesv()\"); \n  cout << endl; \n\n  atlas::gesv (a, b);  // solving the system, b contains x \n\n#ifndef F_ROW_MAJOR\n  print_m (b, \"X\");\n  cout << endl; \n  atlas::gemm (aa, b, x); \n#else\n  print_m (b, \"X^T\"); \n  cout << endl; \n  atlas::gemm (CblasNoTrans, CblasTrans, 1.0, aa, b, 0.0, x); \n#endif \n  print_m (x, \"B = A X\"); \n\n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "dc326dff0ef554d4c0ebc4587d4b3bcbcfd8add3", "size": 1880, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_gesv2.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_gesv2.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_gesv2.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 22.1176470588, "max_line_length": 66, "alphanum_fraction": 0.5973404255, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.58749683817672}}
{"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": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/math/square_root.hpp\"\n#include \"common/equality.hpp\"\n\nBOOST_AUTO_TEST_SUITE(TestSquareRoot)\n\nBOOST_AUTO_TEST_CASE(test_sqroot_rough)\n{\n    BOOST_CHECK(-1 == SquareRoot::RoughSR(-1));\n    BOOST_CHECK(-1 == SquareRoot::RoughSR(0));\n    BOOST_CHECK(1 == SquareRoot::RoughSR(1));\n    BOOST_CHECK(1 == SquareRoot::RoughSR(2));\n    BOOST_CHECK(2 == SquareRoot::RoughSR(3));\n    BOOST_CHECK(2 == SquareRoot::RoughSR(4));\n    BOOST_CHECK(4 == SquareRoot::RoughSR(15));\n    BOOST_CHECK(16 == SquareRoot::RoughSR(257));\n    BOOST_CHECK(256 == SquareRoot::RoughSR(125348));\n}\n\nBOOST_AUTO_TEST_CASE(test_sqroot_babylonial)\n{\n    const double epsilon = 0.0001;\n    BOOST_CHECK(equalDoubles(0.0, SquareRoot::BabylonialSR(-1, epsilon), epsilon));\n    BOOST_CHECK(equalDoubles(0.0, SquareRoot::BabylonialSR(0, epsilon), epsilon));\n    BOOST_CHECK(equalDoubles(1.0, SquareRoot::BabylonialSR(1, epsilon), epsilon));\n    BOOST_CHECK(equalDoubles(1.4142, SquareRoot::BabylonialSR(2, epsilon), epsilon));\n    BOOST_CHECK(equalDoubles(1.7320, SquareRoot::BabylonialSR(3, epsilon), epsilon));\n    BOOST_CHECK(equalDoubles(2.0, SquareRoot::BabylonialSR(4, epsilon), epsilon));\n    BOOST_CHECK(equalDoubles(3.8729, SquareRoot::BabylonialSR(15, epsilon), epsilon));\n    BOOST_CHECK(equalDoubles(16.0312, SquareRoot::BabylonialSR(257, epsilon), epsilon));\n    BOOST_CHECK(equalDoubles(354.0451, SquareRoot::BabylonialSR(125348, epsilon), epsilon));\n}\n\nBOOST_AUTO_TEST_CASE(test_sqroot_with_rounding)\n{\n    SquareRoot::Solution solution;\n    BOOST_CHECK(0 == solution.mySqrt(0));\n    BOOST_CHECK(1 == solution.mySqrt(1));\n    BOOST_CHECK(1 == solution.mySqrt(2));\n    BOOST_CHECK(1 == solution.mySqrt(3));\n    BOOST_CHECK(2 == solution.mySqrt(4));\n    BOOST_CHECK(3 == solution.mySqrt(15));\n    BOOST_CHECK(16 == solution.mySqrt(257));\n    BOOST_CHECK(354 == solution.mySqrt(125348));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e25a19efce186daaf93a61d86014d3a24e0721a4", "size": 1945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/math/test_square_root.cpp", "max_stars_repo_name": "iamantony/CppNotes", "max_stars_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T14:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T09:51:43.000Z", "max_issues_repo_path": "test/algorithms/math/test_square_root.cpp", "max_issues_repo_name": "iamantony/CppNotes", "max_issues_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T07:38:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-02T11:00:58.000Z", "max_forks_repo_path": "test/algorithms/math/test_square_root.cpp", "max_forks_repo_name": "iamantony/CppNotes", "max_forks_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-11T14:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T08:53:50.000Z", "avg_line_length": 40.5208333333, "max_line_length": 92, "alphanum_fraction": 0.7259640103, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5874968336799075}}
{"text": "#include <catch.hpp>\n#include <UnitConvert.hpp>\n\n#include <boost/units/systems/si.hpp>\n#include <boost/units/systems/cgs.hpp>\n\nTEST_CASE(\"UnitRegistry Example\")\n{\n\nusing namespace UnitConvert;\nUnitRegistry ureg;\n\n// add base units to the registry\nureg.addUnit(\"m = [L]\");\nureg.addUnit(\"kg = [M]\");\nureg.addUnit(\"s = [T]\");\nureg.addUnit(\"K = [THETA]\");\nureg.addUnit(\"mol = [N]\");\n\n// add some derived units to the registry\nureg.addUnit(\"100 cm = 1 m\");\nureg.addUnit(\"1 in = 2.54 cm\");\nureg.addUnit(\"1 ft = 12 in\");\nureg.addUnit(\"1 J = 1 kg*m^2*s^-2\");\nureg.addUnit(\"1 W = 1 J/s\");\nureg.addUnit(\"1 cal = 4.184 J\");\n\nQuantity<double> q = ureg.makeQuantity<double>(200, \"cm\");\n\n// q.value() returns the numerical value of the quantity\nCHECK(q.value() == Approx(200));\nCHECK(q.to(\"m\").value() == Approx(2));\n// millimeter was not defined, but we can use SI-prefixed versions of any unit in the registry\nCHECK(q.to(\"mm\").value() == Approx(2000));\n// converting to a unit with different dimensions will throw an error\nCHECK_THROWS(q.to(ureg.getUnit(\"s\")));\n\n\n\n\n// quantities  can be assigned to new dimensions\nq = ureg.makeQuantity<double>(0.25, \"s\");\nCHECK(q.value() == Approx(0.25));\nCHECK(q.to(\"ms\").value() == Approx(250));\n// conversions have to match the quantities current dimensions.\nCHECK_THROWS(q.to(ureg.getUnit(\"m\")));\n\n\n\nq = ureg.makeQuantity<double>(100, \"cal\");\nCHECK(q.value() == Approx(100));\nCHECK(q.to(\"J\").value() == Approx(100 * 4.184));\n// again, we can use SI prefixes\nCHECK(q.to(\"mJ\").value() == Approx(100 * 4.184*1000));\n// we can convert to arbitrary combinations of defined dimensions\nCHECK(q.to(\"kg*m^2*s^-2\").value() == Approx(100 * 4.184));\nCHECK(q.to(\"kg*m^2*ms^-2\").value() == Approx(100 * 4.184 / 1000 / 1000));\nCHECK(q.to(\"W*s\").value() == Approx(100 * 4.184));\nCHECK(q.to(\"kW*s\").value() == Approx(100 * 4.184/1000));\n\nCHECK_THROWS(q.to(\"m\"));\n\n\n\n// The unit registry can create Boost.Units quantities.\n// So we can easily convert to a unit in one of the Boost.Unit\n// systems and then create a Boost.Unit quantity.\nq = ureg.makeQuantity<double>(100, \"ft\");\nboost::units::quantity<boost::units::si::length> L = q.to<boost::units::si::length>();\nCHECK(boost::units::quantity_cast<double>(L) == Approx(30.48));\n\n}\n\n\nTEST_CASE(\"BoostUnitRegisty Example\")\n{\n  using namespace UnitConvert;\nBoostUnitRegistry<boost::units::si::system> ureg;\n\nQuantity<double> q;\n\n// all SI base units and their prefixed versions\n// are automatically defined.\n\nq = ureg.makeQuantity<double>( 24, \"cm\" );\nCHECK( q.to(\"m\").value() == Approx(0.24) );\n\n// mass\nq = ureg.makeQuantity<double>( 24, \"kg\" );\nCHECK( q.to(\"kg\").value() == Approx(24) );\n//CHECK( q.to(\"g\").value() == Approx(24000) ); // 'g' does not exist yet\nCHECK( q.to(\"mkg\").value() == Approx(24000) );\n\n// time\nq = ureg.makeQuantity<double>( 24, \"ms\" );\nCHECK( q.to(\"ms\").value() == Approx(24) );\nCHECK( q.to(\"s\").value() == Approx(0.024) );\nCHECK( q.to_base_units().value() == Approx(0.024) );\n\n// electrical current\nq = ureg.makeQuantity<double>( 24, \"A\" );\nCHECK( q.to(\"mA\").value() == Approx(24000) );\n\n// temperature\nq = ureg.makeQuantity<double>( 24, \"K\" );\nCHECK( q.to(\"mK\").value() == Approx(24000) );\n\n// amount\nq = ureg.makeQuantity<double>( 24, \"mol\" );\nCHECK( q.to(\"mmol\").value() == Approx(24000) );\n\n// luminous intensity\nq = ureg.makeQuantity<double>( 24, \"cd\" );\nCHECK( q.to(\"mcd\").value() == Approx(24000) );\n\n\n\n// now add some non-base units\n// we can add boost unit directly.\n// however, the unit will be added using whatever it string-ify's to\nureg.addUnit( boost::units::cgs::mass() );\n// or we can define the units with a string\nureg.addUnit( \"N = kg m / s^2\" );\nureg.addUnit( \"J = N m\" );\nureg.addUnit( \"W = J s\" );\n\nq = ureg.makeQuantity<double>( 24, \"kg\" );\nCHECK( q.to(\"kg\").value() == Approx(24) );\nCHECK( q.to(\"g\").value() == Approx(24000) ); // 'g' exists now\n\n\nq = ureg.makeQuantity<double>( 24, \"kJ\" );\nCHECK( q.to(\"mJ\").value() == Approx(24000000) );\nCHECK( q.to_base_units().value() == Approx(24000) );\n\nq = ureg.makeQuantity<double>( 24, \"mW\" );\nCHECK( q.to(\"kW\").value() == Approx(0.000024) );\n\n\n}\n", "meta": {"hexsha": "28d64adbfc78c60e2ffde9ee2cb3a6e64da9c143", "size": 4099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/CatchTests/Usage.cpp", "max_stars_repo_name": "CD3/UnitConvert", "max_stars_repo_head_hexsha": "06530130a952ac67bd3d88b2b7791a147c69db64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-22T11:01:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-22T11:01:10.000Z", "max_issues_repo_path": "testing/CatchTests/Usage.cpp", "max_issues_repo_name": "CD3/UnitConvert", "max_issues_repo_head_hexsha": "06530130a952ac67bd3d88b2b7791a147c69db64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-13T15:12:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T22:32:23.000Z", "max_forks_repo_path": "testing/CatchTests/Usage.cpp", "max_forks_repo_name": "CD3/UnitConvert", "max_forks_repo_head_hexsha": "06530130a952ac67bd3d88b2b7791a147c69db64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0709219858, "max_line_length": 94, "alphanum_fraction": 0.6464991461, "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5874920769998565}}
{"text": "#include \"CRTP/Categories/Sets/PosetElement.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <type_traits>\n\nusing CRTP::Categories::Sets::Posets::BoostPartiallyOrderedElement;\nusing CRTP::Categories::Sets::Posets::PartiallyOrderedSetElement;\n\nBOOST_AUTO_TEST_SUITE(CRTP)\nBOOST_AUTO_TEST_SUITE(Categories)\nBOOST_AUTO_TEST_SUITE(Sets)\n\nBOOST_AUTO_TEST_SUITE(PosetElement_tests)\n\nBOOST_AUTO_TEST_SUITE(BoostPartiallyOrderedElement_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(Reflexivity)\n{\n  {\n    //BoostPartiallyOrderedElement<unsigned int> a {97};\n    //BoostPartiallyOrderedElement<unsigned int> b {97};\n\n    //BOOST_TEST((a <= b));\n  }\n  BOOST_TEST(true);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // BoostPartiallyOrderedElement_tests\n\nBOOST_AUTO_TEST_SUITE(PartiallyOrderedSetElement_tests)\n\ntemplate <typename T, typename = std::enable_if_t<std::is_integral<T>::value>>\nclass PartiallyOrderedNaturalNumber :\n  PartiallyOrderedSetElement<PartiallyOrderedNaturalNumber<T>>\n{\n  public:\n\n    PartiallyOrderedNaturalNumber():\n      data_{static_cast<T>(0)}\n    {}\n\n    PartiallyOrderedNaturalNumber(const T n):\n      data_{n}\n    {}\n\n    bool operator<=(const PartiallyOrderedNaturalNumber& rhs) const\n    {\n      return this->data_ <= rhs.data_;\n    }\n\n    /*\n    friend bool operator<=(\n      const PartiallyOrderedNaturalNumber& lhs,\n      const PartiallyOrderedNaturalNumber& rhs)\n    {\n      return lhs.data_ <= rhs.data_\n    }\n    */\n\n  private:\n\n    T data_;\n};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(Reflexivity)\n{\n  PartiallyOrderedNaturalNumber<unsigned int> a {97};\n  PartiallyOrderedNaturalNumber<unsigned int> b {97};\n\n  BOOST_TEST((a <= b));\n  BOOST_TEST((a <= a));\n  BOOST_TEST((b <= b));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // PartiallyOrderedSetElement_tests\n\nBOOST_AUTO_TEST_SUITE_END() // PosetElement_tests\nBOOST_AUTO_TEST_SUITE_END() // Sets\nBOOST_AUTO_TEST_SUITE_END() // Categories\nBOOST_AUTO_TEST_SUITE_END() // CRTP", "meta": {"hexsha": "2d3a6b888c6dbce47ed7197ce8ee6dbe2467ffc1", "size": 2216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Manifolds/Source/UnitTests/CRTP/Categories/Sets/PosetElement_tests.cpp", "max_stars_repo_name": "ernestyalumni/mathphysics", "max_stars_repo_head_hexsha": "24ad9436bcb4860462cd10fe592e93ebd0ade0e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T14:24:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:19:23.000Z", "max_issues_repo_path": "Manifolds/Source/UnitTests/CRTP/Categories/Sets/PosetElement_tests.cpp", "max_issues_repo_name": "ernestyalumni/mathphysics", "max_issues_repo_head_hexsha": "24ad9436bcb4860462cd10fe592e93ebd0ade0e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-09-29T09:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T03:12:29.000Z", "max_forks_repo_path": "Manifolds/Source/UnitTests/CRTP/Categories/Sets/PosetElement_tests.cpp", "max_forks_repo_name": "ernestyalumni/mathphysics", "max_forks_repo_head_hexsha": "24ad9436bcb4860462cd10fe592e93ebd0ade0e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2018-01-21T05:33:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T20:15:13.000Z", "avg_line_length": 26.380952381, "max_line_length": 80, "alphanum_fraction": 0.6398916968, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.5874920670450938}}
{"text": "#include \"AsteroidMap.h\"\n\n#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>\n\n__BEGIN_LIBRARIES_DISABLE_WARNINGS\n#include <boost/integer/common_factor.hpp>\n#include <boost/math/constants/constants.hpp>\n__END_LIBRARIES_DISABLE_WARNINGS\n\n\nnamespace\n{\nconst int SOME_NUMBER_LARGER_THAN_GRID_SIZE = 10000;\n}\n\nnamespace AdventOfCode\n{\nnamespace Year2019\n{\nnamespace Day10\n{\n\nAsteroidMap::AsteroidMap(CoordinatesSet asteroidCoordinatesSet)\n    : m_asteroidCoordinatesSet{std::move(asteroidCoordinatesSet)}\n    , m_laserVector{-1, -SOME_NUMBER_LARGER_THAN_GRID_SIZE}\n{\n    m_locatorPosition = determineLocatorPosition();\n    m_asteroidCoordinatesSet.erase(m_locatorPosition);\n}\n\nunsigned AsteroidMap::getMaxNumAsteroidsDetected() const\n{\n    return getNumAsteroidsDetected(m_locatorPosition);\n}\n\nstd::vector<Coordinates> AsteroidMap::vaporize()\n{\n    while (!m_asteroidCoordinatesSet.empty())\n    {\n        vaporizeNextAsteroid();\n    }\n\n    return m_vaporizationOrder;\n}\n\nCoordinates AsteroidMap::determineLocatorPosition() const\n{\n    return *std::max_element(m_asteroidCoordinatesSet.cbegin(), m_asteroidCoordinatesSet.cend(), [this](const auto& lhs, const auto& rhs)\n                             {\n                                 return this->getNumAsteroidsDetected(lhs) < this->getNumAsteroidsDetected(rhs);\n                             });\n}\n\nunsigned AsteroidMap::getNumAsteroidsDetected(const Coordinates& stationPos) const\n{\n    unsigned numAsteroidsDetected = 0;\n\n    for (const auto& asteroidCoordinates : m_asteroidCoordinatesSet)\n    {\n        if (asteroidCoordinates == stationPos)\n        {\n            continue;\n        }\n\n        if (isThereDirectLineOfSight(stationPos, asteroidCoordinates))\n        {\n            ++numAsteroidsDetected;\n        }\n    }\n\n    return numAsteroidsDetected;\n}\n\nbool AsteroidMap::isThereDirectLineOfSight(const Coordinates& fromCoordinates, const Coordinates& toCoordinates) const\n{\n    Vector2D fromVector{fromCoordinates.first, fromCoordinates.second};\n    Vector2D toVector{toCoordinates.first, toCoordinates.second};\n\n    Vector2D differenceVector = toVector - fromVector;\n    Vector2D differenceVectorAbs = differenceVector.cwiseAbs();\n\n    int gcd = boost::integer::gcd(differenceVectorAbs[0], differenceVectorAbs[1]);\n\n    Vector2D differenceBetweenTwoMidpointsVector = differenceVector / gcd;\n\n    for (Vector2D midpointVector = fromVector + differenceBetweenTwoMidpointsVector; midpointVector != toVector; midpointVector += differenceBetweenTwoMidpointsVector)\n    {\n        Coordinates midpointCoordinates{midpointVector[0], midpointVector[1]};\n        if (m_asteroidCoordinatesSet.find(midpointCoordinates) != m_asteroidCoordinatesSet.cend())\n        {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nvoid AsteroidMap::vaporizeNextAsteroid()\n{\n    Coordinates nextAsteroidToVaporize = findNextAsteroidToVaporize();\n    Vector2D nextAsteroidToVaporizeVector{nextAsteroidToVaporize.first, nextAsteroidToVaporize.second};\n\n    Vector2D locatorVector{m_locatorPosition.first, m_locatorPosition.second};\n\n    m_laserVector = nextAsteroidToVaporizeVector - locatorVector;\n\n    m_vaporizationOrder.push_back(nextAsteroidToVaporize);\n    m_asteroidCoordinatesSet.erase(nextAsteroidToVaporize);\n}\n\nCoordinates AsteroidMap::findNextAsteroidToVaporize() const\n{\n    Coordinates closestAsteroid;\n    double minAngle = std::numeric_limits<double>::max();\n\n    for (const auto& asteroidCoordinates : m_asteroidCoordinatesSet)\n    {\n        double angle = getLaserAngleToAsteroid(asteroidCoordinates);\n\n        // The laser has to spin to some non-zero degree, so zero degrees\n        // actually means that  a full revolution has to be made\n        if (angle == 0)\n        {\n            angle = 2 * boost::math::constants::pi<double>();\n        }\n\n        if (angle <= minAngle && isThereDirectLineOfSight(m_locatorPosition, asteroidCoordinates))\n        {\n            minAngle = angle;\n            closestAsteroid = asteroidCoordinates;\n        }\n    }\n\n    return closestAsteroid;\n}\n\ndouble AsteroidMap::getLaserAngleToAsteroid(const Coordinates& asteroidCoordinates) const\n{\n    Vector2D fromVector{m_laserVector};\n\n    Vector2D asteroidVector{asteroidCoordinates.first, asteroidCoordinates.second};\n    Vector2D locatorVector{m_locatorPosition.first, m_locatorPosition.second};\n\n    Vector2D toVector{asteroidVector - locatorVector};\n\n    double angle = std::atan2(toVector[1], toVector[0]) - std::atan2(fromVector[1], fromVector[0]);\n\n    double pi = boost::math::constants::pi<double>();\n    if (angle < 0)\n    {\n        angle += 2 * pi;\n    }\n\n    // We are looking for negative angles, so we need to multiply the angle by -1.\n    // And we are in a mirrored coordinate sytem, so we need to multiply it by -1 again.\n    // These two operations simplified just mean that we can return the angle as is.\n    return angle;\n}\n\n}\n}\n}\n", "meta": {"hexsha": "8a2b686b1083fe4f7ae78739462c1ef1b3a2c98c", "size": 4899, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AdventOfCode2019/Day10-MonitoringStation/AsteroidMap.cpp", "max_stars_repo_name": "dbartok/advent-of-code-cpp", "max_stars_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AdventOfCode2019/Day10-MonitoringStation/AsteroidMap.cpp", "max_issues_repo_name": "dbartok/advent-of-code-cpp", "max_issues_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AdventOfCode2019/Day10-MonitoringStation/AsteroidMap.cpp", "max_forks_repo_name": "dbartok/advent-of-code-cpp", "max_forks_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0552147239, "max_line_length": 167, "alphanum_fraction": 0.7221882017, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5874704392772448}}
{"text": "/*\n * Copyright 2020 \u00a9 Centre Interdisciplinaire de d\u00e9veloppement en Cartographie des Oc\u00e9ans (CIDCO), Tous droits r\u00e9serv\u00e9s\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": "#ifndef ABC\n#define ABC\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n\nnamespace ublas = boost::numeric::ublas;\n\nnamespace ABC\n{\n   template<typename T>\n   using Func=std::function<T(ublas::vector<T>)>;\n   std::random_device seed_gen;\n   std::mt19937 engine(seed_gen());\n   std::uniform_real_distribution<double> rand_double(-1, 1);\n   template<typename T>\n   std::uniform_real_distribution<T> rand_init(-1, 1);\n\n   template<typename T>\n   void init(ublas::vector<T> &x)\n   {\n      for (int i = 0; i < x.size(); i++)\n      {\n         x[i] = rand_init<T>(engine);\n      }\n   }\n   template<typename T>\n   bool update(int const i, std::vector<ublas::vector<T>> &x, std::vector<int> &cnt, ublas::vector<double> &v, Func<T> f)\n   {\n      int dimension = x[i].size();\n      int population = x.size();\n      std::uniform_int_distribution<int> rand_dim(0, dimension-1);\n      std::uniform_int_distribution<int> rand_pop(0, population-1);\n      int j = rand_dim(engine);\n      int k = rand_pop(engine);\n      double phi = rand_double(engine);\n      ublas::vector<T> x_i = ublas::vector<T>(x[i]);\n      x_i[j] -= phi*(x_i[j] - x[k][j]);\n      double v_new = f(x_i);\n      cnt[i]++;\n      if(v_new <= v[i])\n      {\n         x[i] = x_i;\n         v[i] = v_new;\n         return true;\n      }\n      return false;\n   }\n   template<typename T>\n   void update_random(int const max_visit, std::vector<ublas::vector<T>> &x, std::vector<int> &cnt, ublas::vector<double> &v, Func<T> f)\n   {\n      int dimension = x[0].size();\n      int population = x.size();\n      for(int i = 0; i < population; i++)\n      {\n         if(cnt[i] < max_visit) continue;\n         ublas::vector<T> x_i(dimension);\n         init(x_i);\n         double v_new = f(x_i);\n         cnt[i] = 1;\n         if(v_new <= v[i])\n         {\n            x[i] = x_i;\n            v[i] = v_new;\n         }\n      }\n   }\n   template<typename T>\n   double minimize(int const dimension, int const num_population, int const max_visit, int const max_step, Func<T> f)\n   {\n      std::vector<ublas::vector<T>> x(num_population);\n      std::vector<int> intervals(num_population);\n      std::vector<int> cnt(num_population);\n      ublas::vector<double> one(num_population);\n      ublas::vector<double> v(num_population);\n      ublas::vector<double> p(num_population);\n      std::uniform_int_distribution<int> rand_dim(0, dimension-1);\n      double best_obj = 1 << 20;\n      ublas::vector<T> best_x(dimension);      \n\n      for (int i = 0; i < num_population; i++)\n      {\n         x[i].resize(dimension);\n         init(x[i]);\n         v[i] = f(x[i]);\n         intervals[i] = i;\n         one[i] = 1.0;\n      }\n      for(int step = 0; step < max_step; step++)\n      {\n         int i = rand_dim(engine);\n         update<T>(i, x, cnt, v, f);\n         auto m = std::min_element(v.begin(), v.end());\n         if(*m < 0)\n         {\n            ublas::vector<double> w = v - ublas::vector<double>(num_population, *m);\n            p = w / ublas::sum(w);\n         }\n         else\n         {\n            p = v / ublas::sum(v);\n         }\n         p = one - p;\n         p /= ublas::sum(p);\n         std::piecewise_constant_distribution<> dist(intervals.begin(), intervals.end(), p.begin());\n         i = static_cast<int>(dist(engine));\n         update<T>(i, x, cnt, v, f);\n         update_random<T>(max_visit, x, cnt, v, f);\n\n         auto iter =  std::min_element(v.begin(), v.end());\n         int idx = std::distance(v.begin(), iter);\n         if(best_obj >= *iter)\n         {\n            best_obj = *iter;\n            best_x = x[idx];\n         }\n      }\n      return best_obj;\n   }\n   \n};\n#endif // ABC", "meta": {"hexsha": "4f99b0ce8b27021fffe17eb190c18713b1ff4fc4", "size": 3673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/ABC.cpp", "max_stars_repo_name": "yamamura-k/MetaHeuristics", "max_stars_repo_head_hexsha": "abc6da4c0d9886260425124dfcee2a92b833446f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T04:28:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T04:28:18.000Z", "max_issues_repo_path": "cpp/ABC.cpp", "max_issues_repo_name": "yamamura-k/MetaHeuristics", "max_issues_repo_head_hexsha": "abc6da4c0d9886260425124dfcee2a92b833446f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-07-01T01:13:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T14:26:46.000Z", "max_forks_repo_path": "cpp/ABC.cpp", "max_forks_repo_name": "yamamura-k/MetaHeuristics", "max_forks_repo_head_hexsha": "abc6da4c0d9886260425124dfcee2a92b833446f", "max_forks_repo_licenses": ["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.8617886179, "max_line_length": 136, "alphanum_fraction": 0.538524367, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5873158273995488}}
{"text": "#include \"catch.hpp\"\n\n#include <boost/units/systems/si.hpp>\n\n#include <UnitConvert.hpp>\nusing namespace UnitConvert;\n\n/**\n * This file is used for development. As new classes are created,\n * small tests are written here so that we can try to compile and use\n * them.\n */\n\nTEST_CASE(\"Dimension Devel\", \"[devel]\")\n{\n  BaseDimension<Dimension::Name::Length>            L;\n  BaseDimension<Dimension::Name::Mass>              M;\n  BaseDimension<Dimension::Name::Time>              T;\n  BaseDimension<Dimension::Name::ElectricalCurrent> I;\n  BaseDimension<Dimension::Name::Temperature>       THETA;\n  BaseDimension<Dimension::Name::Amount>            N;\n  BaseDimension<Dimension::Name::LuminousIntensity> J;\n\n  Dimension V = L / T;\n  Dimension E = M * V * V;\n  Dimension P = E / T;\n\n  BaseDimension<Dimension::Name::Length> Length;\n\n  CHECK(P[Dimension::Name::Length] == 2);\n  CHECK(P[Dimension::Name::Mass] == 1);\n  CHECK(P[Dimension::Name::Time] == -3);\n  CHECK(P[Dimension::Name::ElectricalCurrent] == 0);\n  CHECK(P[Dimension::Name::Temperature] == 0);\n  CHECK(P[Dimension::Name::Amount] == 0);\n  CHECK(P[Dimension::Name::LuminousIntensity] == 0);\n\n  CHECK(L == Length);\n  CHECK(M != Length);\n  CHECK(M != L);\n  CHECK(E != P);\n  CHECK(E == P * T);\n}\n\nTEST_CASE(\"Unit Devel\", \"[devel]\")\n{\n  BaseUnit<Dimension::Name::Length>      meter;\n  BaseUnit<Dimension::Name::Mass>        kilogram;\n  BaseUnit<Dimension::Name::Time>        second;\n  BaseUnit<Dimension::Name::Temperature> kelvin;\n\n  Unit gram = kilogram / 1000;\n\n  Unit centimeter = meter / 100;\n  Unit inch       = 2.54 * centimeter;\n  Unit foot       = 12 * inch;\n\n  Unit joule = kilogram * meter * meter / second / second;\n\n  Unit celsius    = kelvin - 273.15;\n  Unit fahrenheit = (5. / 9) * celsius + 32;\n\n  Unit unit = celsius;\n\n  CHECK(meter.scale() == 1);\n  CHECK(meter.offset() == 0);\n  CHECK(kilogram.scale() == 1);\n  CHECK(kilogram.offset() == 0);\n  CHECK(second.scale() == 1);\n  CHECK(second.offset() == 0);\n  CHECK(kelvin.scale() == 1);\n  CHECK(kelvin.offset() == 0);\n\n  CHECK(gram.scale() == Approx(0.001));\n  CHECK(gram.offset() == 0);\n\n  CHECK(centimeter.scale() == Approx(0.01));\n  CHECK(centimeter.offset() == 0);\n  CHECK(inch.scale() == Approx(0.0254));\n  CHECK(inch.offset() == 0);\n  CHECK(foot.scale() == Approx(12 * 0.0254));\n  CHECK(foot.offset() == 0);\n\n  CHECK(joule.scale() == Approx(1));\n  CHECK(joule.offset() == Approx(0));\n\n  CHECK(celsius.scale() == Approx(1));\n  CHECK(celsius.offset() == Approx(-273.15));\n\n  CHECK(fahrenheit.scale() == Approx(5. / 9));\n  CHECK(fahrenheit.offset() == Approx(32 - (9. / 5) * 273.15));\n\n  CHECK(unit.offset() == Approx(-273.15));\n  unit += 100;\n  CHECK(unit.offset() == Approx(-173.15));\n  unit += 100;\n  CHECK(unit.offset() == Approx(-73.15));\n  unit -= 50;\n  CHECK(unit.offset() == Approx(-123.15));\n\n  SECTION(\"Quantity Devel\", \"[devel]\")\n  {\n    Quantity<double> distance(100, foot);\n\n    CHECK(distance.to(meter).value() == Approx(30.48));\n    CHECK_THROWS(distance.to(second));\n\n    Quantity<double> temperature(37, celsius);\n\n    CHECK(temperature.to(kelvin).value() == Approx(273.15 + 37));\n    CHECK(temperature.to(fahrenheit).value() == Approx(98.6));\n  }\n}\n\nTEST_CASE(\"UnitRegistry Devel\", \"[devel]\")\n{\n  UnitRegistry ureg;\n\n  ureg.addBaseUnit<Dimension::Name::Length>(\"m\");\n  ureg.addBaseUnit<Dimension::Name::Mass>(\"kg\");\n  ureg.addBaseUnit<Dimension::Name::Time>(\"s\");\n  ureg.addBaseUnit<Dimension::Name::Temperature>(\"K\");\n  ureg.addBaseUnit<Dimension::Name::Amount>(\"mol\");\n\n  ureg.addUnit(\"100 cm = 1 m\");\n  ureg.addUnit(\"1 in = 2.54 cm\");\n  ureg.addUnit(\"1 ft = 12 in\");\n  ureg.addUnit(\"1 J = 1 kg*m^2*s^-2\");\n  ureg.addUnit(\"1 W = 1 J/s\");\n  ureg.addUnit(\"1 cal = 4.184 J\");\n\n  Unit u = BaseUnit<Dimension::Name::Dimensionless>();\n  Quantity<double> q = ureg.makeQuantity<double>(200, \"cm\");\n\n  u = ureg.getUnit(\"m\");\n  CHECK(u.scale() == Approx(1));\n  u = ureg.getUnit(\"cm\");\n  CHECK(u.scale() == Approx(0.01));\n  CHECK_THROWS(ureg.getUnit(\"mm\"));\n  u = ureg.getUnit(\"mm\",true);\n  CHECK(u.scale() == Approx(0.001));\n  u = ureg.getUnit(\"millim\",true);\n  CHECK(u.scale() == Approx(0.001));\n\n  CHECK(q.value() == Approx(200));\n  // getUnit returns a unit that is in the registry\n  CHECK(q.to(ureg.getUnit(\"m\")).value() == Approx(2));\n  CHECK_THROWS(q.to(ureg.getUnit(\"s\")));\n\n  q = ureg.makeQuantity<double>(0.25, \"s\");\n  CHECK(q.value() == Approx(0.25));\n  // makeUnit can create a unit from the registry,\n  // including SI prefixed versions of the units in the registry\n  CHECK(q.to(ureg.makeUnit(\"ms\")).value() == Approx(250));\n  CHECK_THROWS(q.to(ureg.getUnit(\"m\")));\n\n  q = ureg.makeQuantity<double>(100, \"cal\");\n  CHECK(q.value() == Approx(100));\n  // the Quantity class can convert to a unit string\n  // if it was created by a UnitRegistry\n  CHECK(q.to(\"J\").value() == Approx(100 * 4.184));\n\n  // string based conversion can convert to SI prefixed version of any unit\n  // in the registry, even if they are not explicitly put in the registry,\n  CHECK(q.to(\"mJ\").value() == Approx(100 * 4.184 * 1000));\n\n  // string based conversion can also convert to derived unit representations\n  // that contain SI prefixed versions of units in the registry\n  CHECK(q.to(\"kg*km^2/ms^2\").value() == Approx(100 * 4.184 / 1e12));\n  CHECK(q.to(\"kg*m*km/ms/s\").value() == Approx(100 * 4.184 / 1e6));\n  CHECK(q.to(\"mW*s\").value() == Approx(100 * 4.184 * 1000));\n  CHECK(q.to(\"mW*cs\").value() == Approx(100 * 4.184 * 1000 * 100));\n\n  CHECK_THROWS(q.to(\"m\"));\n\n  SECTION(\"Converting to Boost.Units quantity\")\n  {\n    Quantity<double> distance = ureg.makeQuantity<double>(100, \"ft\");\n    boost::units::quantity<boost::units::si::length> L =\n        distance.to<boost::units::si::length>();\n    CHECK(boost::units::quantity_cast<double>(L) == Approx(30.48));\n  }\n\n\n}\n\nTEST_CASE(\"BoostUnitRegistry Devel\", \"[devel]\")\n{\n  BoostUnitRegistry<boost::units::si::system> ureg;\n\n  // base units are automatically loaded into the\n  // registry.\n\n  ureg.addUnit(\"100 cm = 1 m\");\n  ureg.addUnit(\"1 in = 2.54 cm\");\n  ureg.addUnit(\"1 ft = 12 in\");\n  ureg.addUnit(\"1 J = 1 kg*m^2*s^-2\");\n  ureg.addUnit(\"1 W = 1 J/s\");\n  ureg.addUnit(\"1 cal = 4.184 J\");\n\n  Quantity<double> q = ureg.makeQuantity<double>(200, \"cm\");\n\n  CHECK(q.value() == Approx(200));\n  // getUnit returns a unit that is in the registry\n  CHECK(q.to(ureg.getUnit(\"m\")).value() == Approx(2));\n  CHECK_THROWS(q.to(ureg.getUnit(\"s\")));\n\n  q = ureg.makeQuantity<double>(0.25, \"s\");\n  CHECK(q.value() == Approx(0.25));\n  // makeUnit can create a unit from the registry,\n  // including SI prefixed versions of the units in the registry\n  CHECK(q.to(ureg.makeUnit(\"ms\")).value() == Approx(250));\n  CHECK_THROWS(q.to(ureg.getUnit(\"m\")));\n\n  q = ureg.makeQuantity<double>(100, \"cal\");\n  CHECK(q.value() == Approx(100));\n  // the Quantity class can convert to a unit string\n  // if it was created by a UnitRegistry\n  CHECK(q.to(\"J\").value() == Approx(100 * 4.184));\n\n  // string based conversion can convert to SI prefixed version of any unit\n  // in the registry, even if they are not explicitly put in the registry,\n  CHECK(q.to(\"mJ\").value() == Approx(100 * 4.184 * 1000));\n\n  // string based conversion can also convert to derived unit representations\n  // that contain SI prefixed versions of units in the registry\n  CHECK(q.to(\"kg*km^2/ms^2\").value() == Approx(100 * 4.184 / 1e12));\n  CHECK(q.to(\"kg*m*km/ms/s\").value() == Approx(100 * 4.184 / 1e6));\n  CHECK(q.to(\"mW*s\").value() == Approx(100 * 4.184 * 1000));\n  CHECK(q.to(\"mW*cs\").value() == Approx(100 * 4.184 * 1000 * 100));\n\n  CHECK_THROWS(q.to(\"m\"));\n\n  SECTION(\"Converting to Boost.Units quantity\")\n  {\n    Quantity<double> distance = ureg.makeQuantity<double>(100, \"ft\");\n    boost::units::quantity<boost::units::si::length> L =\n        distance.to<boost::units::si::length>();\n    CHECK(boost::units::quantity_cast<double>(L) == Approx(30.48));\n  }\n}\n", "meta": {"hexsha": "e72f900840824928b27be355cbdc91f83e38cacb", "size": 7878, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/CatchTests/Devel.cpp", "max_stars_repo_name": "CD3/UnitConvert", "max_stars_repo_head_hexsha": "06530130a952ac67bd3d88b2b7791a147c69db64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-22T11:01:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-22T11:01:10.000Z", "max_issues_repo_path": "testing/CatchTests/Devel.cpp", "max_issues_repo_name": "CD3/UnitConvert", "max_issues_repo_head_hexsha": "06530130a952ac67bd3d88b2b7791a147c69db64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-13T15:12:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T22:32:23.000Z", "max_forks_repo_path": "testing/CatchTests/Devel.cpp", "max_forks_repo_name": "CD3/UnitConvert", "max_forks_repo_head_hexsha": "06530130a952ac67bd3d88b2b7791a147c69db64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5537190083, "max_line_length": 77, "alphanum_fraction": 0.6335364306, "num_tokens": 2391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5872558622526226}}
{"text": "/**\n * @file random_test.cpp\n * @author Konstantin Sidorov\n *\n * Tests for generators of random numbers from math:: namespace.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/core/math/random.hpp>\n#include <mlpack/core/dists/discrete_distribution.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace math;\n\nBOOST_AUTO_TEST_SUITE(RandomTest);\n\n// Test for RandInt() sampler from discrete uniform distribution.\nBOOST_AUTO_TEST_CASE(DiscreteUniformRandomTest)\n{\n  std::vector<std::pair<int, int>> ranges =\n  {\n    std::make_pair(0, 1),\n    std::make_pair(0, 2),\n    std::make_pair(-6, -2),\n    std::make_pair(-3, 4),\n    std::make_pair(13, 37)\n  };\n  const size_t iterations = 10000;\n  for (std::pair<int, int> range : ranges)\n  {\n    int lo = range.first, hiExclusive = range.second;\n    std::vector<int> count(hiExclusive - lo, 0);\n    for (size_t iter = 0; iter < iterations; ++iter)\n    {\n      count[RandInt(lo, hiExclusive) - lo]++;\n    }\n    for (size_t i = 0; i < count.size(); ++i)\n    {\n      BOOST_REQUIRE_SMALL(\n        1.0 / (hiExclusive - lo) - count[i] * 1.0 / iterations, 0.15);\n    }\n  }\n\n  // Here we also test RandInt(hiExclusive) overload.\n  for (std::pair<int, int> range : ranges)\n  {\n    int lo = range.first, hiExclusive = range.second;\n    if (lo != 0) continue;\n    std::vector<int> count(hiExclusive - lo, 0);\n    for (size_t iter = 0; iter < iterations; ++iter)\n    {\n      count[RandInt(lo, hiExclusive) - lo]++;\n    }\n\n    for (size_t i = 0; i < count.size(); ++i)\n    {\n      BOOST_REQUIRE_SMALL(\n          1.0 / (hiExclusive - lo) - count[i] * 1.0 / iterations, 0.15);\n    }\n  }\n}\n\n// Test for RandInt() sampler from discrete (possibly nonuniform) distribution.\nBOOST_AUTO_TEST_CASE(WeightedRandomTest)\n{\n  std::vector<std::vector<double>> weights = {\n    {1},\n    {0, 0, 1, 0, 0},\n    {1, 0, 0},\n    {0, 0, 1},\n    {0.25, 0.25, 0.5},\n    {0.9, 0.05, 0.05},\n    {0.5, 0.1, 0.1, 0.1, 0.1, 0.1}\n  };\n  const size_t iterations = 50000;\n  for (std::vector<double> weightSet : weights)\n  {\n    mlpack::distribution::DiscreteDistribution d(1);\n    d.Probabilities(0) =  arma::vec(weightSet);\n    std::vector<int> count(weightSet.size(), 0);\n    for (size_t iter = 0; iter < iterations; ++iter)\n    {\n      count[d.Random()(0)]++;\n    }\n\n    for (size_t i = 0; i < weightSet.size(); ++i)\n    {\n      BOOST_REQUIRE_SMALL(weightSet[i] - count[i] * 1.0 / iterations, 0.15);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "179ef6f73736616d9805537c236af84cb38ed442", "size": 2780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/random_test.cpp", "max_stars_repo_name": "RMaron/mlpack", "max_stars_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-21T23:30:34.000Z", "max_issues_repo_path": "src/mlpack/tests/random_test.cpp", "max_issues_repo_name": "RMaron/mlpack", "max_issues_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-01-23T18:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T13:58:34.000Z", "max_forks_repo_path": "src/mlpack/tests/random_test.cpp", "max_forks_repo_name": "RMaron/mlpack", "max_forks_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-20T00:54:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-16T05:34:32.000Z", "avg_line_length": 27.5247524752, "max_line_length": 79, "alphanum_fraction": 0.6248201439, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.587255851377332}}
{"text": "/**\n * MIT License\n *\n * Copyright (c) 2020 Sean Crutchlow\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * @file kf_test.cpp\n * @brief Unit tests using Google Test framework to validate class\n *  implementation.\n * @author Sean Crutchlow <sean.GH1231@gmail.com>\n * @version 1.0\n */\n\n/// System\n#include <gtest/gtest.h>\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <vector>\n\n\n/// Library\n#include <Eigen/Dense>\n\n/// Project\n#include \"kalman_filter/kf.h\"\n#include \"kalman_filter/ekf.h\"\n#include \"kalman_filter/ukf.h\"\n#include \"kalman_filter/utils.h\"\n\nnamespace kalman_filter {\nclass KfTest : public ::testing::Test {\n protected:\n  /// Pointer for Kalman Filter object\n  std::shared_ptr<KF> kf_ptr;\n  /// Pointers for Eigen Matrices\n  Eigen::MatrixXd *kf_H_lidar_ptr;\n  Eigen::MatrixXd *kf_H_radar_ptr;\n  Eigen::MatrixXd *kf_R_lidar_ptr;\n  Eigen::MatrixXd *kf_R_radar_ptr;\n  Eigen::MatrixXd *kf_Q_ptr;\n\n  /// Pointer for Extended Kalman Filter object\n  std::shared_ptr<EKF> ekf_ptr;\n  /// Pointers for Eigen Matrices\n  Eigen::MatrixXd *ekf_H_lidar_ptr;\n  Eigen::MatrixXd *ekf_H_radar_ptr;\n  Eigen::MatrixXd *ekf_R_lidar_ptr;\n  Eigen::MatrixXd *ekf_R_radar_ptr;\n  Eigen::MatrixXd *ekf_Q_ptr;\n\n  /// File names for input data\n  std::string f_lidar_radar;\n\n  /// Generic structure for sensor measurements\n  struct Measurement {\n    std::string type;\n    std::vector<double> data;\n    double gt_x, gt_y, gt_vx, gt_vy;\n    int64_t timestamp;\n  };\n\n  virtual void SetUp() {\n    /// Files containing measurement data\n    f_lidar_radar = \"lidar_and_radar.csv\";\n\n    /// state vector - x\n    Eigen::VectorXd kf_x(4);\n    // covariance matrix - P\n    Eigen::MatrixXd kf_P(4, 4);\n    /// measurement matrix - H\n    kf_H_lidar_ptr = new Eigen::MatrixXd(2, 4);\n    kf_H_radar_ptr = new Eigen::MatrixXd(2, 4);\n    /// measurement covariance matrix - R\n    kf_R_lidar_ptr = new Eigen::MatrixXd(2, 2);\n    kf_R_radar_ptr = new Eigen::MatrixXd(2, 2);\n    /// state noise covariance matrix - Q\n    kf_Q_ptr = new Eigen::MatrixXd(4, 4);\n    /// control vector - u\n    Eigen::VectorXd kf_u(4);\n\n    /// Initialize Kalman Filter Variables\n    InitKfVars(&kf_x,\n               &kf_P,\n               kf_H_lidar_ptr,\n               kf_H_radar_ptr,\n               kf_R_lidar_ptr,\n               kf_R_radar_ptr,\n               kf_Q_ptr,\n               &kf_u);\n\n    /// Create Kalman Filter Object\n    kf_ptr = std::make_shared<KF>(kf_x, kf_P, kf_u);\n\n    /// state vector - x\n    Eigen::VectorXd ekf_x(6);\n    // covariance matrix - P\n    Eigen::MatrixXd ekf_P(6, 6);\n    /// measurement matrix - H\n    ekf_H_lidar_ptr = new Eigen::MatrixXd(2, 6);\n    ekf_H_radar_ptr = new Eigen::MatrixXd(2, 6);\n    /// measurement covariance matrix - R\n    ekf_R_lidar_ptr = new Eigen::MatrixXd(2, 2);\n    ekf_R_radar_ptr = new Eigen::MatrixXd(2, 2);\n    /// state noise covariance matrix - Q\n    ekf_Q_ptr = new Eigen::MatrixXd(6, 6);\n    /// control vector - u\n    Eigen::VectorXd ekf_u(6);\n\n    /// Initialize Kalman Filter Variables\n    InitEkfVars(&ekf_x,\n               &ekf_P,\n               ekf_H_lidar_ptr,\n               ekf_H_radar_ptr,\n               ekf_R_lidar_ptr,\n               ekf_R_radar_ptr,\n               ekf_Q_ptr,\n               &ekf_u);\n\n    /// Create Extended Kalman Filter Object\n    ekf_ptr = std::make_shared<EKF>(ekf_x, ekf_P, ekf_u);\n  }\n\n  virtual void TearDown() {\n    delete kf_H_lidar_ptr;\n    delete kf_H_radar_ptr;\n    delete kf_R_lidar_ptr;\n    delete kf_R_radar_ptr;\n    delete kf_Q_ptr;\n\n    delete ekf_H_lidar_ptr;\n    delete ekf_H_radar_ptr;\n    delete ekf_R_lidar_ptr;\n    delete ekf_R_radar_ptr;\n    delete ekf_Q_ptr;\n  }\n\n  /**\n   * @brief      Initializes the Kalman Filter variables.\n   *\n   * @param      _x        State vector\n   * @param      _P        The covariance matrix\n   * @param      _lidar_H  The lidar measurment matrix\n   * @param      _radar_H  The radar measurment matrix\n   * @param      _lidar_R  The lidar measurment noise matrix\n   * @param      _radar_R  The radar measurment noise matrix\n   * @param      _Q        The state covariance matrix\n   * @param      _u        The control vector\n   */\n  void InitKfVars(KF::vec_t *_x,\n                  KF::mat_t *_P,\n                  KF::mat_t *_lidar_H,\n                  KF::mat_t *_radar_H,\n                  KF::mat_t *_lidar_R,\n                  KF::mat_t *_radar_R,\n                  KF::mat_t *_Q,\n                  KF::vec_t *_u) {\n    *_x << 0.0,  /// x\n           0.0,  /// y\n           0.0,  /// vx\n           0.0;  /// vy\n\n    *_P << 0.1, 0.0,  0.0,  0.0,  /// x\n           0.0, 0.1,  0.0,  0.0,  /// y\n           0.0, 0.0, 10.0,  0.0,  /// vx\n           0.0, 0.0,  0.0, 10.0;  /// vy\n\n    *_lidar_H << 1.0, 0.0, 0.0, 0.0,  /// x\n                 0.0, 1.0, 0.0, 0.0;  /// y\n\n    *_radar_H << 1.0, 0.0, 0.0, 0.0,  /// x\n                 0.0, 1.0, 0.0, 0.0;  /// y\n\n    *_lidar_R << 0.0225, 0.0,     /// x\n                 0.0,    0.0225;  /// y\n\n    *_radar_R << 0.09, 0.0,       /// x\n                 0.0,  0.0009;    /// y\n\n    *_Q << 0.1, 0.0, 0.0, 0.0,  /// x\n           0.0, 0.1, 0.0, 0.0,  /// y\n           0.0, 0.0, 0.1, 0.0,  /// vx\n           0.0, 0.0, 0.0, 0.1;  /// vy\n\n    *_u << 0.0,  /// x\n           0.0,  /// y\n           0.0,  /// vx\n           0.0;  /// vy\n  }\n\n  /**\n   * @brief      Initializes the Extended Kalman Filter variables.\n   *\n   * @param      _x        State vector\n   * @param      _P        The covariance matrix\n   * @param      _lidar_H  The lidar measurment matrix\n   * @param      _radar_H  The radar measurment matrix\n   * @param      _lidar_R  The lidar measurment noise matrix\n   * @param      _radar_R  The radar measurment noise matrix\n   * @param      _Q        The state covariance matrix\n   * @param      _u        The control vector\n   */\n  void InitEkfVars(KF::vec_t *_x,\n                   KF::mat_t *_P,\n                   KF::mat_t *_lidar_H,\n                   KF::mat_t *_radar_H,\n                   KF::mat_t *_lidar_R,\n                   KF::mat_t *_radar_R,\n                   KF::mat_t *_Q,\n                   KF::vec_t *_u) {\n    *_x << 0.0,  /// x\n           0.0,  /// y\n           0.0,  /// vx\n           0.0,  /// vy\n           0.0,  /// ax\n           0.0;  /// ay\n\n    *_P << 0.1, 0.0,  0.0,   0.0,   0.0,   0.0,  /// x\n           0.0, 0.1,  0.0,   0.0,   0.0,   0.0,  /// y\n           0.0, 0.0, 10.0,   0.0,   0.0,   0.0,  /// vx\n           0.0, 0.0,  0.0,  10.0,   0.0,   0.0,  /// vy\n           0.0, 0.0,  0.0,   0.0, 100.0,   0.0,  /// ax\n           0.0, 0.0,  0.0,   0.0,   0.0, 100.0;  /// ay\n\n    *_lidar_H << 1.0, 0.0, 0.0, 0.0, 0.0, 0.0,  /// x\n                 0.0, 1.0, 0.0, 0.0, 0.0, 0.0;  /// y\n\n    *_radar_H << 1.0, 0.0, 0.0, 0.0, 0.0, 0.0,  /// x\n                 0.0, 1.0, 0.0, 0.0, 0.0, 0.0;  /// y\n\n    *_lidar_R << 0.0225, 0.0,     /// x\n                 0.0,    0.0225;  /// y\n\n    *_radar_R << 0.09, 0.0,       /// x\n                 0.0,  0.0009;    /// y\n\n    *_Q << 0.1, 0.0, 0.0, 0.0, 0.0, 0.0,   /// x\n           0.0, 0.1, 0.0, 0.0, 0.0, 0.0,   /// y\n           0.0, 0.0, 0.1, 0.0, 0.0, 0.0,   /// vx\n           0.0, 0.0, 0.0, 0.1, 0.0, 0.0,  /// vy\n           0.0, 0.0, 0.0, 0.0, 0.1, 0.0,   /// ax\n           0.0, 0.0, 0.0, 0.0, 0.0, 0.1;   /// ay\n\n    *_u << 0.0,  /// x\n           0.0,  /// y\n           0.0,  /// vx\n           0.0,  /// vy\n           0.0,  /// ax\n           0.0;  /// ay\n  }\n\n  /**\n   * @brief      Parses file with sensor measurements.\n   *\n   * @param[in]  _file  The file\n   *\n   * @return     Vector of sensor measurements.\n   */\n  std::vector<Measurement> Parse(const std::string& _file) {\n    /// Store parsed measurements\n    std::vector<Measurement> measurements;\n    /// Parsed line\n    std::string line;\n    /// File handle for measurements\n    std::ifstream f(_file);\n\n    /// If file can be opened\n    if (f.is_open()) {\n      /// While there is a line to be retrieved from file handle\n      while (getline(f, line)) {\n        /// Convert string to stringstream\n        std::stringstream stream(line);\n        /// Define type for storing string without delimeters\n        std::vector<std::string> delim_line;\n        /// While there are no errors in stringstream\n        while (stream.good()) {\n          /// Remove delimeter and store data\n          std::string substr;\n          getline(stream, substr, ',');\n          delim_line.push_back(substr);\n        }\n          Measurement measurement;\n          /// If measurement is lidar, parse directly, otherwise,\n          // measurement is radar, convert from polar to Cartesian & parse\n          if (delim_line[0].compare(\"L\") == 0) {\n            measurement.type      = \"Lidar\";\n\n            measurement.data.push_back(std::stod(delim_line[1]));  /// x\n            measurement.data.push_back(std::stod(delim_line[2]));  /// y\n\n            measurement.timestamp = std::stoll(delim_line[3]);\n            measurement.gt_x      = std::stod(delim_line[4]);\n            measurement.gt_y      = std::stod(delim_line[5]);\n            measurement.gt_vx     = std::stod(delim_line[6]);\n            measurement.gt_vy     = std::stod(delim_line[7]);\n          } else {\n            double rho       = std::stod(delim_line[1]);\n            double phi       = std::stod(delim_line[2]);\n            double rho_dot   = std::stod(delim_line[3]);\n\n            /**\n             * This is now a converted measurement Kalman Filter - Jacobian \n             * and Symbolic Differentiation can be used in other applications\n             * to linearize the measurement error. For this test, the main\n             * focus is library.\n             */\n            coord2D_t radar_cartesian = Polar2Cartesian(rho, phi);\n\n            measurement.type      = \"Radar\";\n\n            measurement.data.push_back(std::get<0>(radar_cartesian));\n            measurement.data.push_back(std::get<1>(radar_cartesian));\n\n            measurement.timestamp = std::stoll(delim_line[4]);\n            measurement.gt_x      = std::stod(delim_line[5]);\n            measurement.gt_y      = std::stod(delim_line[6]);\n            measurement.gt_vx     = std::stod(delim_line[7]);\n            measurement.gt_vy     = std::stod(delim_line[8]);\n          }\n          measurements.push_back(measurement);\n      }\n      f.close();\n    }\n\n    return measurements;\n  }\n\n  /**\n   * @brief      Processes the measurements'\n   *\n   * @param[in]  _z         The measurement vector\n   * @param[in]  _H_lidar   The lidar measurement matrix\n   * @param[in]  _H_radar   The radar measurement matrix\n   * @param[in]  _R_lidar   The lidar measurment noise matrix\n   * @param[in]  _R_radar   The radar measurment noise matrix\n   * @param[in]  _Q         The state covariance matrix\n   * @param      _estimate  The estimated states\n   * @param      _actual    The actual states (ground truth)\n   * @param[in]  padding    The padding\n   *\n   * @return     The final state vector.\n   */\n  Eigen::VectorXd Process(const std::vector<Measurement>& _z,\n                          const Eigen::MatrixXd* _H_lidar,\n                          const Eigen::MatrixXd* _H_radar,\n                          const Eigen::MatrixXd* _R_lidar,\n                          const Eigen::MatrixXd* _R_radar,\n                          const Eigen::MatrixXd* _Q,\n                          std::vector<Eigen::VectorXd>* _estimate,\n                          std::vector<Eigen::VectorXd>* _actual,\n                          size_t padding = 0) {\n    for (int i = 0; i < _z.size(); i++) {\n      /// Define measurment vector based on raw measurement data\n      Eigen::VectorXd measurement(\n        Eigen::Map<const Eigen::VectorXd>(\n          _z[i].data.data(), _z[i].data.size()));\n\n      /// Have Kalman Filter complete a single iteration (Update & Predict)\n      if (_z[i].type.compare(\"Lidar\") == 0) {\n        kf_ptr->Update(measurement,\n                       *_H_lidar,\n                       *_R_lidar);\n      } else {\n        kf_ptr->Update(measurement,\n                       *_H_radar,\n                       *_R_radar);\n      }\n      kf_ptr->Predict(*_Q, _z[i].timestamp);\n\n      /// Populate estimated & actual states if needed for RMSE calcuation\n      if (_estimate != nullptr) {\n        _estimate->push_back(kf_ptr->GetState());\n      }\n      if (_actual != nullptr) {\n        Eigen::VectorXd ground_truth(4);\n        ground_truth << _z[i].gt_x,\n                        _z[i].gt_y,\n                        _z[i].gt_vx,\n                        _z[i].gt_vy;\n        /// Added padding to state vector since data set in this\n        /// test is 4-dimensional\n        if (padding > 0) {\n            Eigen::VectorXd ground_truth_padded(4 + padding);\n            Eigen::VectorXd padded = Eigen::VectorXd::Zero(padding);\n            ground_truth_padded << ground_truth,\n                                   padded;\n\n          _actual->push_back(ground_truth_padded);\n        } else {\n          _actual->push_back(ground_truth);\n        }\n      }\n    }\n    /// Return final state\n    return kf_ptr->GetState();\n  }\n};\n\n\nTEST_F(KfTest, CMKF_RMSE) {\n  /// Vectors to hold data used in RMSE calculation\n  std::vector<Eigen::VectorXd> estimated_states;\n  std::vector<Eigen::VectorXd> actual_states;\n\n  /// Parse CSV to extract sensor measurements\n  std::vector<Measurement> measurements = Parse(f_lidar_radar);\n\n  /// Process measurements to estimate final state\n  Eigen::VectorXd curr_state = Process(measurements,\n                                       kf_H_lidar_ptr,\n                                       kf_H_radar_ptr,\n                                       kf_R_lidar_ptr,\n                                       kf_R_radar_ptr,\n                                       kf_Q_ptr,\n                                       &estimated_states,\n                                       &actual_states);\n  /// Define allowable RMSE\n  Eigen::VectorXd allowable_rmse(4);\n  allowable_rmse << 1.0,\n                    1.0,\n                    10.0,\n                    10.0;\n\n  /// Calculate RMSE for estimated & actual state vectors\n  Eigen::VectorXd calculated_rmse = CalcRMSE(estimated_states, actual_states);\n\n  /// Check that calculated RMSE is less than allowable\n  bool result = !(calculated_rmse.array() > allowable_rmse.array()).any();\n\n  /// RMSE for state vector\n  std::cerr << \"\\nCMKF RMSE:\\n\" << calculated_rmse << std::endl;\n\n  EXPECT_TRUE(result);\n}\n\nTEST_F(KfTest, CMKF_FinalPose) {\n  /// Parse CSV to extract sensor measurements\n  std::vector<Measurement> measurements = Parse(f_lidar_radar);\n\n  /// Extract expected state from final ground truth measurement\n  Eigen::VectorXd expected_state(4);\n  Measurement final_state = measurements[measurements.size() - 1];\n  expected_state << final_state.gt_x,\n                    final_state.gt_y,\n                    final_state.gt_vx,\n                    final_state.gt_vy;\n\n  /// Process measurements to estimate final state\n  Eigen::VectorXd curr_state = Process(measurements,\n                                       kf_H_lidar_ptr,\n                                       kf_H_radar_ptr,\n                                       kf_R_lidar_ptr,\n                                       kf_R_radar_ptr,\n                                       kf_Q_ptr,\n                                       nullptr,\n                                       nullptr);\n\n  /// Print out states as reference\n  std::cerr << \"\\nCMKF curr_state:\\n\" << curr_state << std::endl;\n  std::cerr << \"\\nCMKF expected_state:\\n\" << expected_state << std::endl;\n\n  EXPECT_TRUE(curr_state.isApprox(expected_state));\n}\n\nTEST_F(KfTest, CMEKF_RMSE) {\n  /// Vectors to hold data used in RMSE calculation\n  std::vector<Eigen::VectorXd> estimated_states;\n  std::vector<Eigen::VectorXd> actual_states;\n\n  /// Parse CSV to extract sensor measurements\n  std::vector<Measurement> measurements = Parse(f_lidar_radar);\n\n  /// Set pointer to derived class\n  kf_ptr = ekf_ptr;\n\n  /// Process measurements to estimate final state\n  Eigen::VectorXd curr_state = Process(measurements,\n                                       ekf_H_lidar_ptr,\n                                       ekf_H_radar_ptr,\n                                       ekf_R_lidar_ptr,\n                                       ekf_R_radar_ptr,\n                                       ekf_Q_ptr,\n                                       &estimated_states,\n                                       &actual_states,\n                                       2);\n  /// Define allowable RMSE\n  Eigen::VectorXd allowable_rmse(6);\n  allowable_rmse << 1.0,\n                    1.0,\n                    10.0,\n                    10.0,\n                    100.0,\n                    100.0;\n\n  /// Calculate RMSE for estimated & actual state vectors\n  Eigen::VectorXd calculated_rmse = CalcRMSE(estimated_states, actual_states);\n\n  /// Check that calculated RMSE is less than allowable\n  bool result = !(calculated_rmse.array() > allowable_rmse.array()).any();\n\n  /// RMSE for state vector\n  std::cerr << \"\\nCMEKF RMSE:\\n\" << calculated_rmse << std::endl;\n\n  EXPECT_TRUE(result);\n}\n\nTEST_F(KfTest, CMEKF_FinalPose) {\n  /// Parse CSV to extract sensor measurements\n  std::vector<Measurement> measurements = Parse(f_lidar_radar);\n\n  /// Extract expected state from final ground truth measurement\n  Eigen::VectorXd expected_state(6);\n  Measurement final_state = measurements[measurements.size() - 1];\n  expected_state << final_state.gt_x,\n                    final_state.gt_y,\n                    final_state.gt_vx,\n                    final_state.gt_vy,\n                    0.0,\n                    0.0;\n\n  /// Set pointer to derived class\n  kf_ptr = ekf_ptr;\n\n  /// Process measurements to estimate final state\n  Eigen::VectorXd curr_state = Process(measurements,\n                                       ekf_H_lidar_ptr,\n                                       ekf_H_radar_ptr,\n                                       ekf_R_lidar_ptr,\n                                       ekf_R_radar_ptr,\n                                       ekf_Q_ptr,\n                                       nullptr,\n                                       nullptr,\n                                       2);\n\n  /// Print out states as reference\n  std::cerr << \"\\nCMEKF curr_state:\\n\" << curr_state << std::endl;\n  std::cerr << \"\\nCMEKF expected_state:\\n\" << expected_state << std::endl;\n\n  EXPECT_TRUE(curr_state.isApprox(expected_state));\n}\n}   //  namespace kalman_filter\n\n\nint main(int argc, char **argv) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "0c6ac3cdd270895ae3e0613e2bead58d43374aa4", "size": 19555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/kf_test.cpp", "max_stars_repo_name": "scr123/kalman_filter", "max_stars_repo_head_hexsha": "e282aef98d0ce0b4ec3e1307b292b35315468ccd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-25T18:44:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-25T18:44:17.000Z", "max_issues_repo_path": "test/kf_test.cpp", "max_issues_repo_name": "scr123/kalman_filter", "max_issues_repo_head_hexsha": "e282aef98d0ce0b4ec3e1307b292b35315468ccd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/kf_test.cpp", "max_forks_repo_name": "scr123/kalman_filter", "max_forks_repo_head_hexsha": "e282aef98d0ce0b4ec3e1307b292b35315468ccd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2469352014, "max_line_length": 81, "alphanum_fraction": 0.5412937868, "num_tokens": 5430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5872083085730622}}
{"text": "\ufeff#include \"stdafx.h\"\n#include \"VectorProcessor.h\"\n#include <algorithm>\n#include <numeric>\n#include <functional>\n#include <boost/range/algorithm/transform.hpp>\n#include <boost/phoenix.hpp>\n\nusing namespace std;\nusing namespace std::placeholders;\nusing namespace boost::phoenix::placeholders;\nusing namespace boost::phoenix;\nusing boost::transform;\n\nvoid ProcessVector(std::vector<double> & numbers)\n{\n\tauto IsPositive = [](double number){return number > 0; };\n\n\tsize_t numberOfPositives = 0;\n\n\t// \u0444\u0443\u043d\u043a\u0446\u0438\u044f, \u0441\u0443\u043c\u043c\u0438\u0440\u0443\u044e\u0449\u0430\u044f \u0442\u043e\u043b\u044c\u043a\u043e \u043f\u043e\u043b\u043e\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0435 \u0447\u0438\u0441\u043b\u0430 \u0441 \u043f\u043e\u0434\u0441\u0447\u0435\u0442\u043e\u043c \u0438\u0445 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430\n\tauto addIfPositive = [&numberOfPositives](double acc, double current) {\n\t\tif (current > 0.0)\n\t\t{\n\t\t\t++numberOfPositives;\n\t\t\treturn acc + current;\n\t\t}\n\t\treturn acc;\n\t};\n\n\tauto sumOfPositives = accumulate(numbers.begin(), numbers.end(), 0.0, addIfPositive);\n\n\tdouble avg = (numberOfPositives > 0) ? sumOfPositives / numberOfPositives : 0.0;\n\n\t// TODO: \u0418\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0439 \u0441\u0438\u043b\u0443 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u0430 std::transform, \u041b\u044e\u043a, \u0432\u043c\u0435\u0441\u0442\u043e \u044d\u0442\u043e\u0433\u043e \u0446\u0438\u043a\u043b\u0430\n\tboost::transform(numbers, numbers.begin(), arg1 + avg);\n\t/*\n\tauto addAvg = bind(plus<double>(), _1, avg);\n\ttransform(numbers, numbers.begin(), addAvg);\n\t*/\n\t/*transform(numbers, numbers.begin(), bind(plus<double>(), _1, avg));*/\n\n\t/*transform(numbers.begin(), numbers.end(), numbers.begin(), bind(plus<double>(), _1, avg));*/\n\t/*\n\ttransform(numbers.begin(), numbers.end(), numbers.begin(), [&avg](double current){\n\t\treturn current + avg;\n\t});\n\t*/\n\t/*\n\tfor (auto &number : numbers)\n\t{\n\t\tnumber += avg;\n\t}*/\n}", "meta": {"hexsha": "c7a4dad731d8be2eea7f9a96dc7e618b5ce79fcc", "size": 1494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lab2/task1/VectorProcessor.cpp", "max_stars_repo_name": "alexey-malov/ips-oop2015", "max_stars_repo_head_hexsha": "fd47a03213b9387eef5f1664725557b41a2ffd1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab2/task1/VectorProcessor.cpp", "max_issues_repo_name": "alexey-malov/ips-oop2015", "max_issues_repo_head_hexsha": "fd47a03213b9387eef5f1664725557b41a2ffd1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab2/task1/VectorProcessor.cpp", "max_forks_repo_name": "alexey-malov/ips-oop2015", "max_forks_repo_head_hexsha": "fd47a03213b9387eef5f1664725557b41a2ffd1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6666666667, "max_line_length": 95, "alphanum_fraction": 0.7001338688, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.5872059556137218}}
{"text": "//  Copyright John Maddock 2009.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include \"required_defines.hpp\"\n\n#include \"performance_measure.hpp\"\n\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/math/special_functions/expm1.hpp>\n#include <boost/array.hpp>\n\n#define T double\n#  include \"../test/log1p_expm1_data.ipp\"\n\ntemplate <std::size_t N>\ndouble log1p_evaluate2(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::log1p(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(log1p_test, \"log1p\")\n{\n   double result = log1p_evaluate2(log1p_expm1_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(log1p_expm1_data)) / sizeof(log1p_expm1_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble expm1_evaluate2(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::expm1(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(expm1_test, \"expm1\")\n{\n   double result = expm1_evaluate2(log1p_expm1_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(log1p_expm1_data)) / sizeof(log1p_expm1_data[0]));\n}\n\n#ifdef TEST_DCDFLIB\n#include <dcdflib.h>\n\ntemplate <std::size_t N>\ndouble log1p_evaluate2_dcd(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n   {\n      double t = data[i][0];\n      result += ::alnrel(&t);\n   }\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(log1p_test_dcd, \"log1p-dcd\")\n{\n   double result = log1p_evaluate2_dcd(log1p_expm1_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(log1p_expm1_data)) / sizeof(log1p_expm1_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble expm1_evaluate2_dcd(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n   {\n      double t = data[i][0];\n      result += ::dexpm1(&t);\n   }\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(expm1_test_dcd, \"expm1-dcd\")\n{\n   double result = expm1_evaluate2_dcd(log1p_expm1_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(log1p_expm1_data)) / sizeof(log1p_expm1_data[0]));\n}\n\n#endif\n\n#ifdef TEST_GSL\n\n#include <gsl/gsl_sf.h>\n\ntemplate <std::size_t N>\ndouble log1p_evaluate_gsl(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += gsl_sf_log_1plusx(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(log1p_test, \"log1p-gsl\")\n{\n   double result = log1p_evaluate_gsl(log1p_expm1_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(log1p_expm1_data)) / sizeof(log1p_expm1_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble expm1_evaluate_gsl(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += gsl_sf_expm1(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(expm1_test, \"expm1-gsl\")\n{\n   double result = expm1_evaluate_gsl(log1p_expm1_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(log1p_expm1_data)) / sizeof(log1p_expm1_data[0]));\n}\n\n#endif\n\n#ifdef TEST_CEPHES\n\nextern \"C\" double expm1(double);\nextern \"C\" double log1p(double);\n\ntemplate <std::size_t N>\ndouble log1p_evaluate_cephes(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += ::log1p(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(log1p_test, \"log1p-cephes\")\n{\n   double result = log1p_evaluate_cephes(log1p_expm1_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(log1p_expm1_data)) / sizeof(log1p_expm1_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble expm1_evaluate_cephes(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += ::expm1(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(expm1_test, \"expm1-cephes\")\n{\n   double result = expm1_evaluate_cephes(log1p_expm1_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(log1p_expm1_data)) / sizeof(log1p_expm1_data[0]));\n}\n\n#endif\n\n", "meta": {"hexsha": "43ac89134d9e57cffcc879d0ed158f7567e4caee", "size": 4340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/performance/test_expm1_log1p.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": "2015-01-08T08:33:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-12T06:14:54.000Z", "max_issues_repo_path": "boost/libs/math/performance/test_expm1_log1p.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "boost/libs/math/performance/test_expm1_log1p.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": 23.4594594595, "max_line_length": 77, "alphanum_fraction": 0.6894009217, "num_tokens": 1368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5871877006263636}}
{"text": "#define BOOST_TEST_MODULE lue framework core math\n#include <hpx/config.hpp>\n#include <boost/test/unit_test.hpp>\n#include \"lue/framework/core/math.hpp\"\n\n\nnamespace detail {\n\ntemplate<\n    typename Input,\n    typename Output>\nauto check_equal = [](\n        Input const from_min,\n        Input const from_max,\n        Output const to_min,\n        Output const to_max,\n        Input const value_to_map,\n        Output const result_we_want)\n    {\n        BOOST_TEST_INFO(\"With value \" << value_to_map);\n        BOOST_CHECK_EQUAL(\n            lue::map_to_range(\n                from_min, from_max, to_min, to_max, value_to_map),\n            result_we_want);\n    };\n\n}  // namespace detail\n\n\n#define DEFINE_CHECK_EQUAL() \\\n    auto check_equal = [=]( \\\n            Input const value_to_map, \\\n            Output const result_we_want) \\\n        { \\\n            detail::check_equal<Input, Output>( \\\n                    from_min, from_max, to_min, to_max, value_to_map, \\\n                    result_we_want); \\\n        };\n\n\nBOOST_AUTO_TEST_CASE(map_indices)\n{\n    using Input = std::size_t;\n    using Output = std::size_t;\n\n    // Equal input and output ranges\n    {\n        Input from_min = 0;\n        Input from_max = 10;\n        Output to_min = 0;\n        Output to_max = 10;\n\n        DEFINE_CHECK_EQUAL()\n\n        check_equal(0, 0);\n        check_equal(1, 1);\n        check_equal(2, 2);\n        check_equal(3, 3);\n        check_equal(4, 4);\n        check_equal(5, 5);\n        check_equal(6, 6);\n        check_equal(7, 7);\n        check_equal(8, 8);\n        check_equal(9, 9);\n        check_equal(10, 10);\n    }\n\n    // Smaller input range than output range\n    {\n        Input from_min = 0;\n        Input from_max = 4;\n        Output to_min = 0;\n        Output to_max = 9;\n\n        DEFINE_CHECK_EQUAL()\n\n        check_equal(0, 0);\n        check_equal(1, 2);\n        check_equal(2, 4);\n        check_equal(3, 6);\n        check_equal(4, 8);\n    }\n\n    // Larger input range than output range\n    {\n        Input from_min = 0;\n        Input from_max = 9;\n        Output to_min = 0;\n        Output to_max = 4;\n\n        DEFINE_CHECK_EQUAL()\n\n        check_equal(0, 0);\n        check_equal(1, 0);\n        check_equal(2, 1);\n        check_equal(3, 1);\n        check_equal(4, 2);\n        check_equal(5, 2);\n        check_equal(6, 3);\n        check_equal(7, 3);\n        check_equal(8, 4);\n        check_equal(9, 4);\n    }\n\n    // Input range with single element\n    {\n        Input from_min = 0;\n        Input from_max = 0;\n        Output to_min = 0;\n        Output to_max = 4;\n\n        DEFINE_CHECK_EQUAL()\n\n        check_equal(0, 0);\n    }\n\n    // Output range with single element\n    {\n        Input from_min = 0;\n        Input from_max = 9;\n        Output to_min = 0;\n        Output to_max = 0;\n\n        DEFINE_CHECK_EQUAL()\n\n        check_equal(0, 0);\n        check_equal(5, 0);\n        check_equal(9, 0);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(map_to_range_case_1)\n{\n    using Input = std::size_t;\n    using Output = std::size_t;\n\n    // 100 partitions \u2192 3 localities\n    Input from_min = 0;\n    Input from_max = 99;\n    Output to_min = 0;\n    Output to_max = 2;\n\n    DEFINE_CHECK_EQUAL()\n\n    //  0 - 33: 0 (\u2192 34)\n    // 33 - 66: 1 (\u2192 33)\n    // 66 - 99: 2 (\u2192 33)\n    check_equal( 0, 0);\n    check_equal(33, 0);\n    check_equal(34, 1);\n    check_equal(66, 1);\n    check_equal(67, 2);\n    check_equal(99, 2);\n}\n\n#undef DEFINE_CHECK_EQUAL\n", "meta": {"hexsha": "a0e6d24711a3d8cf7f78abd1890f8caf6e3c628e", "size": 3422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/framework/core/test/math_test.cpp", "max_stars_repo_name": "computationalgeography/lue", "max_stars_repo_head_hexsha": "71993169bae67a9863d7bd7646d207405dc6f767", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-26T22:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T10:28:48.000Z", "max_issues_repo_path": "source/framework/core/test/math_test.cpp", "max_issues_repo_name": "pcraster/lue", "max_issues_repo_head_hexsha": "e64c18f78a8b6d8a602b7578a2572e9740969202", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 262.0, "max_issues_repo_issues_event_min_datetime": "2016-08-11T10:12:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-13T18:09:16.000Z", "max_forks_repo_path": "source/framework/core/test/math_test.cpp", "max_forks_repo_name": "computationalgeography/lue", "max_forks_repo_head_hexsha": "71993169bae67a9863d7bd7646d207405dc6f767", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T09:49:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T09:49:41.000Z", "avg_line_length": 21.6582278481, "max_line_length": 71, "alphanum_fraction": 0.5479251899, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5871877006263636}}
{"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.\u00c5^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*\u00c5^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*\u00c5^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": "#include <glm/models/links/logc.hpp>\n\n#include <armadillo>\n\nusing namespace arma;\n\nlogc_link::logc_link()\n    : glm_link::glm_link( \"logc\" )\n{\n}\n\nvec\nlogc_link::init_beta(const mat &X, const vec &y) const\n{\n    vec mu = (y + 0.5) / 2.0;\n    vec eta = log( 1 - mu );\n    \n    return pinv( X ) * eta;\n}\n\nvec\nlogc_link::mu(const arma::vec &eta) const\n{\n    return 1.0 - exp( eta );\n}\n\nvec\nlogc_link::eta(const arma::vec &mu) const\n{\n    return log( 1 - mu );\n}\n\nvec\nlogc_link::mu_eta(const arma::vec &mu) const\n{\n    return -1 / ( 1.0 - mu );\n}\n", "meta": {"hexsha": "71acdc389455646b0ed7ef32e36e40c92ff1ad3f", "size": 542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/glm/models/links/logc.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/logc.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/logc.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": 14.2631578947, "max_line_length": 54, "alphanum_fraction": 0.594095941, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.587183997319532}}
{"text": "#include \"MeshTriangle.h\"\n#include \"triangle_triangle_intersection.h\"\n#include \"find_all_intersecting_pairs_using_AABBTrees.h\"\n#include \"Object.h\"\n#include \"AABBTree.h\"\n#include \"warnings.h\"\n#include \"tictoc.h\"\n#include \"visualize_aabbtree.h\"\n#include <igl/read_triangle_mesh.h>\n#include <Eigen/Core>\n#include <iostream>\n#include <iomanip> // std::setw\n#include <memory> // std::shared_ptr\n\nint main(int argc, char * argv[])\n{\n  /////////////////////////////////////////////////////////////////////////////\n  // TRIANGLE MESH INTERSECTION DETECTION\n  /////////////////////////////////////////////////////////////////////////////\n  std::cout<<\"# Triangle Mesh Intersection Detection\"<<std::endl;\n  // Read in a triangle mesh\n  Eigen::MatrixXd VA;\n  Eigen::MatrixXi FA;\n  igl::read_triangle_mesh(argc>1?argv[1]:\"../data/knight.obj\",VA,FA);\n  std::cout<<\"  |VA| \"<<VA.rows()<<\"  \"<<std::endl;\n  std::cout<<\"  |FA| \"<<FA.rows()<<\"  \"<<std::endl<<std::endl;\n  Eigen::MatrixXd VB;\n  Eigen::MatrixXi FB;\n  igl::read_triangle_mesh(argc>2?argv[2]:\"../data/cheburashka.obj\",VB,FB);\n  std::cout<<\"  |VB| \"<<VB.rows()<<\"  \"<<std::endl;\n  std::cout<<\"  |FB| \"<<FB.rows()<<\"  \"<<std::endl<<std::endl;\n\n  tic(); // Start the clock!\n  std::vector<std::pair<int, int> > bf_pairs;\n  // Brute force\n  for(int fa = 0;fa<FA.rows();fa++)\n  {\n    for(int fb = 0;fb<FB.rows();fb++)\n    {\n      if(triangle_triangle_intersection(\n          VA.row(FA(fa,0)),\n          VA.row(FA(fa,1)),\n          VA.row(FA(fa,2)),\n          VB.row(FB(fb,0)),\n          VB.row(FB(fb,1)),\n          VB.row(FB(fb,2))))\n      {\n        bf_pairs.emplace_back(fa,fb);\n      }\n    }\n  }\n  std::cout<<\"  | Method      | Time in seconds |\"<<std::endl;\n  std::cout<<\"  |:------------|----------------:|\"<<std::endl;\n  std::cout<<\"  | brute force | \" << FLOAT15 << toc() << \" |\"<<std::endl;\n  \n  // Build trees for each\n  tic();\n  std::vector<std::pair<int, int> > tree_pairs;\n  const auto triangle_tree = [](\n      const Eigen::MatrixXd & V,\n      const Eigen::MatrixXi & F)->std::shared_ptr<AABBTree>\n  {\n    // Because we use shared_ptrs it's OK that this list is destroyed\n    std::vector<std::shared_ptr<Object> > triangles;\n    triangles.reserve(F.rows());\n    // Create a box for each triangle\n    for(int f = 0;f<F.rows();f++)\n    {\n      triangles.emplace_back( std::make_shared<MeshTriangle>(V,F,f) );\n    }\n    return std::make_shared<AABBTree>(triangles);\n  };\n  std::shared_ptr<AABBTree> rootA = triangle_tree(VA,FA);\n  std::shared_ptr<AABBTree> rootB = triangle_tree(VB,FB);\n  std::cout<<\"  | build trees | \" << FLOAT15 << toc() << \" |\"<<std::endl;\n\n  tic();\n  std::vector<std::pair<std::shared_ptr<Object>,std::shared_ptr<Object> > >\n    leaf_pairs;\n  // Broad phase\n  find_all_intersecting_pairs_using_AABBTrees(rootA,rootB,leaf_pairs);\n  for(const auto & pair : leaf_pairs)\n  {\n    std::shared_ptr<MeshTriangle> triangleA =\n      std::static_pointer_cast<MeshTriangle>(pair.first);\n    std::shared_ptr<MeshTriangle> triangleB =\n      std::static_pointer_cast<MeshTriangle>(pair.second);\n    const int fa = triangleA->f;\n    const int fb = triangleB->f;\n    // Narrow phase\n    if(triangle_triangle_intersection(\n        VA.row(FA(fa,0)),\n        VA.row(FA(fa,1)),\n        VA.row(FA(fa,2)),\n        VB.row(FB(fb,0)),\n        VB.row(FB(fb,1)),\n        VB.row(FB(fb,2))))\n    {\n      tree_pairs.emplace_back(fa,fb);\n    }\n  }\n  std::cout<<\"  | use trees   | \" << FLOAT15 << toc() << \" |\"<<std::endl;\n  std::cout<<std::endl;\n\n  // See if lists match\n  diff_and_warn(  bf_pairs,\"brute force\",tree_pairs,\"tree\");\n  diff_and_warn(tree_pairs,\"tree\",       bf_pairs,  \"brute force\");\n\n  visualize_aabbtree(VA,FA,VB,FB,leaf_pairs);\n}\n", "meta": {"hexsha": "a1ccd223600f0e913622e463977f92d793e8dae9", "size": 3688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "intersections.cpp", "max_stars_repo_name": "ericpko/computer-graphics-bounding-volume-hierarchy", "max_stars_repo_head_hexsha": "9f4781ab2308ebf57d4ac89e1d37e51c311a17f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "intersections.cpp", "max_issues_repo_name": "ericpko/computer-graphics-bounding-volume-hierarchy", "max_issues_repo_head_hexsha": "9f4781ab2308ebf57d4ac89e1d37e51c311a17f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intersections.cpp", "max_forks_repo_name": "ericpko/computer-graphics-bounding-volume-hierarchy", "max_forks_repo_head_hexsha": "9f4781ab2308ebf57d4ac89e1d37e51c311a17f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2252252252, "max_line_length": 79, "alphanum_fraction": 0.5810737527, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.5871802699309788}}
{"text": "\r\n#pragma once\r\n\r\n#include <array>\r\n#include <Eigen/Core>\r\n\r\n#include <Discregrid/common.hpp>\r\n\r\nnamespace Discregrid\r\n{\r\n\r\nenum class NearestEntity\r\n{\r\n\tVN0, VN1, VN2, EN0, EN1, EN2, FN\r\n};\r\n\r\nReal point_triangle_sqdistance(Vector3r const& point, \r\n\tstd::array<Vector3r const*, 3> const& triangle,\r\n\tVector3r* nearest_point = nullptr,\r\n\tNearestEntity* ne = nullptr);\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "75fc6813da373704776071349e6e3437072128f3", "size": 376, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "discregrid/src/geometry/point_triangle_distance.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/src/geometry/point_triangle_distance.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/src/geometry/point_triangle_distance.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": 15.6666666667, "max_line_length": 55, "alphanum_fraction": 0.6835106383, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802158996553, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.5871802535713396}}
{"text": "#include <glm/models/links/odds.hpp>\n\n#include <armadillo>\n\nusing namespace arma;\n\nodds_link::odds_link()\n    : glm_link::glm_link( \"odds\" )\n{\n}\n\nvec\nodds_link::init_beta(const mat &X, const vec &y) const\n{\n    vec mu = (y + 0.5) / 2.0;\n    vec eta = mu / ( 1.0 - mu );\n    \n    /* Sometimes the initialization behaves badly for the odds-additive\n     * scale by taking a too large step in the first iteration. Always\n     * shrink the initial betas some to address this.\n    */\n    return pinv( X ) * eta / 4.0;\n}\n\nvec\nodds_link::mu(const arma::vec &eta) const\n{\n    return eta / ( 1 + eta );\n}\n\nvec\nodds_link::eta(const arma::vec &mu) const\n{\n    return mu / ( 1 - mu );\n}\n\nvec\nodds_link::mu_eta(const arma::vec &mu) const\n{\n    return 1 / ( (mu - 1) % (mu - 1) );\n}\n", "meta": {"hexsha": "b4f4a61a4e7402b954cecae65ed1276a4fda4cf9", "size": 769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/glm/models/links/odds.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/odds.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/odds.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": 18.3095238095, "max_line_length": 71, "alphanum_fraction": 0.6098829649, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5871768313813589}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE COMPUTE\n\n#include <boost/test/unit_test.hpp>\n\n#include \"api/umo.hpp\"\n\n#include <cmath>\n#include <stdexcept>\n#include <vector>\n\n#define STRINGIFY(x) #x\n#define TOSTRING(x) STRINGIFY(x)\n\nusing namespace umo;\n\nconst double eps = 0.1;\n\nBOOST_AUTO_TEST_CASE(Square1) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    minimize(x*x + (-2)*x + 1);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 1, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Square2) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    minimize( (x + (-1)) * (x + (-1)) );\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 1, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Square3) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    minimize(x*x + 2*x + 1);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), -1, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Square4) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    minimize( (x + 1) * (x + 1) );\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), -1, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(LowerBound) {\n    Model model;\n    FloatExpression x = model.floatVar(2.0, umo::inf());\n    minimize(x*x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 2.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(UpperBound) {\n    Model model;\n    FloatExpression x = model.floatVar(-umo::inf(), -2.0);\n    minimize(x*x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), -2.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(FixedVar) {\n    Model model;\n    FloatExpression x = model.floatVar(2.0, 2.0);\n    minimize(x*x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 2.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Exp) {\n    Model model;\n    FloatExpression x = model.floatVar();\n    minimize(umo::exp(x) + (-1)*x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Log) {\n    Model model;\n    FloatExpression x = model.floatVar(1.0e-5, 1.0e5);\n    maximize(umo::log(x) + (-1)*x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 1, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Cos1) {\n    Model model;\n    FloatExpression x = model.floatVar(0, 1);\n    minimize(umo::cos(x));\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 1, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Cos2) {\n    Model model;\n    FloatExpression x = model.floatVar(0, 1);\n    maximize(umo::cos(x));\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Sin1) {\n    Model model;\n    FloatExpression x = model.floatVar(0, 1);\n    minimize(umo::sin(x));\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Sin2) {\n    Model model;\n    FloatExpression x = model.floatVar(0, 1);\n    maximize(umo::sin(x));\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 1, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Tan1) {\n    Model model;\n    FloatExpression x = model.floatVar(0, 1);\n    minimize(umo::tan(x));\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Tan2) {\n    Model model;\n    FloatExpression x = model.floatVar(0, 1);\n    maximize(umo::tan(x));\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x.getValue(), 1, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Bool1) {\n    Model model;\n    BoolExpression x = model.boolVar();\n    minimize(x*x + (-1.6)*x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK(x.getValue());\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Bool2) {\n    Model model;\n    BoolExpression x1 = model.boolVar();\n    BoolExpression x2 = model.boolVar();\n    BoolExpression x3 = model.boolVar();\n    BoolExpression x4 = model.boolVar();\n    maximize(x1 - x2 + x3 - x4);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK(x1.getValue());\n    BOOST_CHECK(!x2.getValue());\n    BOOST_CHECK(x3.getValue());\n    BOOST_CHECK(!x4.getValue());\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Int1) {\n    Model model;\n    IntExpression x = model.intVar();\n    minimize(x*x + (-3.8)*x);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_EQUAL(x.getValue(), 2);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Bounds1) {\n    Model model;\n    BoolExpression b1 = model.boolVar();\n    BoolExpression b2 = model.boolVar();\n    IntExpression i1 = model.intVar(-9, 9);\n    IntExpression i2 = model.intVar(-8, 8);\n    IntExpression i3 = model.intVar(-7, 7);\n    IntExpression i4 = model.intVar(-6, 6);\n    FloatExpression f1 = model.floatVar(-5, 5);\n    FloatExpression f2 = model.floatVar(-4, 4);\n    FloatExpression f3 = model.floatVar(-3, 3);\n    FloatExpression f4 = model.floatVar(-2, 2);\n    maximize(i1 + i2 + i3 + i4 + f1 + f2 + f3 + f4 + b1 + b2);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_EQUAL(i1.getValue(), 9);\n    BOOST_CHECK_EQUAL(i2.getValue(), 8);\n    BOOST_CHECK_EQUAL(i3.getValue(), 7);\n    BOOST_CHECK_EQUAL(i4.getValue(), 6);\n    BOOST_CHECK_CLOSE(f1.getValue(), 5.0, eps);\n    BOOST_CHECK_CLOSE(f2.getValue(), 4.0, eps);\n    BOOST_CHECK_CLOSE(f3.getValue(), 3.0, eps);\n    BOOST_CHECK_CLOSE(f4.getValue(), 2.0, eps);\n    BOOST_CHECK(b1.getValue());\n    BOOST_CHECK(b2.getValue());\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Bounds2) {\n    Model model;\n    BoolExpression b1 = model.boolVar();\n    BoolExpression b2 = model.boolVar();\n    IntExpression i1 = model.intVar(-9, 9);\n    IntExpression i2 = model.intVar(-8, 8);\n    IntExpression i3 = model.intVar(-7, 7);\n    IntExpression i4 = model.intVar(-6, 6);\n    FloatExpression f1 = model.floatVar(-5, 5);\n    FloatExpression f2 = model.floatVar(-4, 4);\n    FloatExpression f3 = model.floatVar(-3, 3);\n    FloatExpression f4 = model.floatVar(-2, 2);\n    maximize(i1 + i2 - i3 - i4 + f1 + f2 - f3 - f4 + b1 - b2);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_EQUAL(i1.getValue(), 9);\n    BOOST_CHECK_EQUAL(i2.getValue(), 8);\n    BOOST_CHECK_EQUAL(i3.getValue(), -7);\n    BOOST_CHECK_EQUAL(i4.getValue(), -6);\n    BOOST_CHECK_CLOSE(f1.getValue(), 5.0, eps);\n    BOOST_CHECK_CLOSE(f2.getValue(), 4.0, eps);\n    BOOST_CHECK_CLOSE(f3.getValue(), -3.0, eps);\n    BOOST_CHECK_CLOSE(f4.getValue(), -2.0, eps);\n    BOOST_CHECK(b1.getValue());\n    BOOST_CHECK(!b2.getValue());\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Bounds3) {\n    Model model;\n    BoolExpression b1 = model.boolVar();\n    BoolExpression b2 = model.boolVar();\n    IntExpression i1 = model.intVar(-9, 9);\n    IntExpression i2 = model.intVar(-8, 8);\n    IntExpression i3 = model.intVar(-7, 7);\n    IntExpression i4 = model.intVar(-6, 6);\n    FloatExpression f1 = model.floatVar(-5, 5);\n    FloatExpression f2 = model.floatVar(-4, 4);\n    FloatExpression f3 = model.floatVar(-3, 3);\n    FloatExpression f4 = model.floatVar(-2, 2);\n    minimize(i1 + i2 + i3 + i4 + f1 + f2 + f3 + f4 + b1 + b2);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_EQUAL(i1.getValue(), -9);\n    BOOST_CHECK_EQUAL(i2.getValue(), -8);\n    BOOST_CHECK_EQUAL(i3.getValue(), -7);\n    BOOST_CHECK_EQUAL(i4.getValue(), -6);\n    BOOST_CHECK_CLOSE(f1.getValue(), -5.0, eps);\n    BOOST_CHECK_CLOSE(f2.getValue(), -4.0, eps);\n    BOOST_CHECK_CLOSE(f3.getValue(), -3.0, eps);\n    BOOST_CHECK_CLOSE(f4.getValue(), -2.0, eps);\n    BOOST_CHECK(!b1.getValue());\n    BOOST_CHECK(!b2.getValue());\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Mixed1) {\n    Model model;\n    BoolExpression x1 = model.boolVar();\n    IntExpression x2 = model.intVar(0, 10);\n    FloatExpression x3 = model.floatVar(0, 20);\n    maximize(x1 + x2 + x3);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK(x1.getValue());\n    BOOST_CHECK_EQUAL(x2.getValue(), 10);\n    BOOST_CHECK_CLOSE(x3.getValue(), 20, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Mixed2) {\n    Model model;\n    FloatExpression x1 = model.floatVar(0, 20);\n    IntExpression x2 = model.intVar(0, 10);\n    BoolExpression x3 = model.boolVar();\n    maximize(x1 + x2 + x3);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x1.getValue(), 20, eps);\n    BOOST_CHECK_EQUAL(x2.getValue(), 10);\n    BOOST_CHECK(x3.getValue());\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Mixed3) {\n    Model model;\n    FloatExpression x1 = model.floatVar(0, 20);\n    IntExpression x2 = model.intVar(0, 10);\n    BoolExpression x3 = model.boolVar();\n    FloatExpression x4 = model.floatVar(-5, 40);\n    IntExpression x5 = model.intVar(-10, 30);\n    BoolExpression x6 = model.boolVar();\n    maximize(x1 + x2 + x3 - x4 - x5 -x6);\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x1.getValue(), 20, eps);\n    BOOST_CHECK_EQUAL(x2.getValue(), 10);\n    BOOST_CHECK(x3.getValue());\n    BOOST_CHECK_CLOSE(x4.getValue(), -5, eps);\n    BOOST_CHECK_EQUAL(x5.getValue(), -10);\n    BOOST_CHECK(!x6.getValue());\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Empty) {\n    Model model;\n    BoolExpression x1 = model.boolVar();\n    IntExpression x2 = model.intVar();\n    FloatExpression x3 = model.floatVar();\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Linear1) {\n    Model model;\n    FloatExpression x1 = model.floatVar(0.0, umo::unbounded());\n    FloatExpression x2 = model.floatVar(0.0, umo::unbounded());\n    maximize(x1);\n    linearConstraint(umo::unbounded(), 1.0, {x1, x2});\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x1.getValue(), 1.0, eps);\n    BOOST_CHECK_CLOSE(x2.getValue(), 0.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Linear2) {\n    Model model;\n    FloatExpression x1 = model.floatVar(0.0, umo::unbounded());\n    FloatExpression x2 = model.floatVar(0.0, umo::unbounded());\n    maximize(x2);\n    linearConstraint(umo::unbounded(), 1.0, {x1, x2});\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x1.getValue(), 0.0, eps);\n    BOOST_CHECK_CLOSE(x2.getValue(), 1.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Linear3) {\n    Model model;\n    FloatExpression x1 = model.floatVar(umo::unbounded(), 1.0);\n    FloatExpression x2 = model.floatVar(umo::unbounded(), 1.0);\n    maximize(x2);\n    linearConstraint(umo::unbounded(), 1.0, {x1, x2});\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x1.getValue(), 0.0, eps);\n    BOOST_CHECK_CLOSE(x2.getValue(), 1.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Linear4) {\n    Model model;\n    FloatExpression x1 = model.floatVar(umo::unbounded(), 1.0);\n    FloatExpression x2 = model.floatVar(umo::unbounded(), 1.0);\n    maximize(x1 + x2);\n    linearConstraint(umo::unbounded(), 1.0, {x1, x2}, {1.0, 2.0});\n    linearConstraint(umo::unbounded(), 1.0, {x1, x2}, {2.0, 1.0});\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x1.getValue(), 1.0/3.0, eps);\n    BOOST_CHECK_CLOSE(x2.getValue(), 1.0/3.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n\nBOOST_AUTO_TEST_CASE(Linear5) {\n    Model model;\n    FloatExpression x1 = model.floatVar();\n    FloatExpression x2 = model.floatVar();\n    maximize(x2);\n    linearConstraint(umo::unbounded(), 1.0, {x1, x2});\n    linearConstraint(umo::unbounded(), 0.0, {x1}, {-1.0});\n    linearConstraint(umo::unbounded(), 0.0, {x2}, {-1.0});\n    model.setSolver(TOSTRING(SOLVER_PARAM));\n    model.solve();\n    BOOST_CHECK_CLOSE(x1.getValue(), 0.0, eps);\n    BOOST_CHECK_CLOSE(x2.getValue(), 1.0, eps);\n    BOOST_CHECK_EQUAL(model.getStatus(), Status::Optimal);\n}\n", "meta": {"hexsha": "4d6fb860b44cf35ab199caec098ba9cb28184c05", "size": 13568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/solve_minlp.cpp", "max_stars_repo_name": "Coloquinte/umo", "max_stars_repo_head_hexsha": "1f39c316d6584bbed22913aabaa4bfb5ee02d72b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T20:56:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T20:56:25.000Z", "max_issues_repo_path": "test/solve_minlp.cpp", "max_issues_repo_name": "Coloquinte/umo", "max_issues_repo_head_hexsha": "1f39c316d6584bbed22913aabaa4bfb5ee02d72b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/solve_minlp.cpp", "max_forks_repo_name": "Coloquinte/umo", "max_forks_repo_head_hexsha": "1f39c316d6584bbed22913aabaa4bfb5ee02d72b", "max_forks_repo_licenses": ["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.7729468599, "max_line_length": 66, "alphanum_fraction": 0.6713590802, "num_tokens": 3800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5871768076439168}}
{"text": "#include <ctime>\n#include <iostream>\n#include <limits>\n#include <iomanip>\nusing namespace std;\n\n#define BOOST_TEST_MAIN\n// #define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE TestMisc\n#include <boost/test/unit_test.hpp>\n\n//#include <boost/chrono/system_clocks.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/random.hpp>\n\n#include <fftscarf.h>\n\nint g_nb_tests = 100000;\n\nBOOST_AUTO_TEST_CASE( test_ispow2 )\n{\n    // Test power of 2 up to 2^30\n    int p=2;\n    for(int l=1; l<30; ++l, p*=2)\n        BOOST_CHECK(fftscarf::isPow2(p));\n\n    // Test non-power of 2\n    boost::random::mt19937 rng((const uint32_t)std::time(0));\n    boost::random::uniform_int_distribution<int> intrnd(1,std::numeric_limits<int>::max());\n    for(int n=0; n<g_nb_tests; ++n){\n        p = intrnd(rng);\n        while(p%2) p /= 2; // Remove potential powers of 2\n        if(p>1)\n            BOOST_CHECK(!fftscarf::isPow2(p)); // The reminder should be non-power of 2^a\n    }\n}\n\nBOOST_AUTO_TEST_CASE( test_ispow235 )\n{\n    // Test power of 2^a * 3^b * 5^c\n    boost::random::mt19937 rng((const uint32_t)std::time(0));\n    boost::random::uniform_int_distribution<int> powsrnd(1,30);\n    int p;\n    for(int n=0; n<g_nb_tests; ++n){\n        p = std::pow(2, powsrnd(rng)) * std::pow(3, powsrnd(rng)) * std::pow(5, powsrnd(rng));\n        BOOST_CHECK(fftscarf::isPow235(p));\n    }\n\n    // Test non-power of 2^a * 3^b * 5^c\n    boost::random::uniform_int_distribution<int> intrnd(1,std::numeric_limits<int>::max());\n    for(int n=0; n<g_nb_tests; ++n){\n        p = intrnd(rng);\n        while(p%2==0) p /= 2; // Remove potential powers of 2\n        while(p%3==0) p /= 3; // Remove potential powers of 3\n        while(p%5==0) p /= 5; // Remove potential powers of 5\n        if(p>1)\n            BOOST_CHECK(!fftscarf::isPow235(p)); // The reminder should be non-power of 2^a * 3^b * 5^c\n    }\n}\n\n// Test wrapq -----------------------------------------------------------------\n\ntemplate<typename FloatType>\ninline FloatType refwrap(FloatType value){\n    return std::arg(std::complex<FloatType>(std::cos(value),std::sin(value)));\n}\n\ntemplate<typename ValueType>\nvoid check_wrap(ValueType value){\n    long double err = refwrap(value) - fftscarf::wrapq(value);\n    if(!(std::abs(err)<100*fftscarf::eps<ValueType>())){\n        std::cout << std::setprecision(std::numeric_limits<ValueType>::digits10+2);\n        std::cout << \"value=\" << value << \" refwrap=\" << refwrap(value) << \" wrap=\" << fftscarf::wrapq(value) << \" err=\" << err << \" eps=\" << fftscarf::eps<ValueType>() << std::endl;\n    }\n    BOOST_CHECK(std::abs(err)<100*fftscarf::eps<ValueType>());\n}\n\ntemplate<typename ValueType>\nvoid check_multi_wrap(){\n\n    std::cout << \"Test fftscarf::wrapq for type size: \" << sizeof(ValueType) << std::endl;\n\n    boost::mt19937 rnd_engine((uint32_t)std::time(0));\n    boost::random::uniform_real_distribution<ValueType> phirnd(0.0, 2*fftscarf::pi); // For random phase\n\n    check_wrap<ValueType>(0.0);\n    check_wrap<ValueType>(fftscarf::pi/2);\n    check_wrap<ValueType>(fftscarf::pi);\n    check_wrap<ValueType>(-fftscarf::pi/2);\n    check_wrap<ValueType>(-fftscarf::pi);\n    check_wrap<ValueType>(2*fftscarf::pi);\n    for(int N=-16; N<=16; ++N)\n        check_wrap<ValueType>(phirnd(rnd_engine) + N*2*fftscarf::pi);\n\n\n    // Check speed\n    int Nmax = 1000000;\n    volatile ValueType res = 0.0; // volatile to avoid simplification because res is not used\n    boost::posix_time::ptime tstart;\n    boost::posix_time::ptime tend;\n\n    tstart = boost::posix_time::microsec_clock::local_time();\n    for(int N=-Nmax; N<=Nmax; ++N)\n        res = fftscarf::wrap(phirnd(rnd_engine) + N*2*fftscarf::pi);\n    tend  = boost::posix_time::microsec_clock::local_time();\n    long double dur_wrap = (tend-tstart).total_milliseconds();\n    std::cout << \"wrap time:\" << dur_wrap << \"ms\" << std::endl;\n\n    tstart = boost::posix_time::microsec_clock::local_time();\n    for(int N=-Nmax; N<=Nmax; ++N)\n        res = fftscarf::wrapq(phirnd(rnd_engine) + N*2*fftscarf::pi);\n    tend  = boost::posix_time::microsec_clock::local_time();\n    long double dur_wrapq = (tend-tstart).total_milliseconds();\n    std::cout << \"wrapq time:\" << dur_wrapq << \"ms\" << std::endl;\n\n    long double acc = dur_wrap/dur_wrapq;\n    std::cout << \"speed up ratio:\" << acc << std::endl;\n    BOOST_CHECK(acc>2.0); // Should be at least twice faster\n}\n\nBOOST_AUTO_TEST_CASE( test_wrap_single )\n{\n    check_multi_wrap<float>();\n}\nBOOST_AUTO_TEST_CASE( test_wrap_double )\n{\n    check_multi_wrap<double>();\n}\nBOOST_AUTO_TEST_CASE( test_wrap_long_double )\n{\n    check_multi_wrap<long double>();\n}\n", "meta": {"hexsha": "fcdc3a23d98080a148c975066617814ccf43b2c0", "size": 4623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_misc.cpp", "max_stars_repo_name": "entn-at/gillesdegottex_fttscarf", "max_stars_repo_head_hexsha": "91251689107f53e21bf3dc4c5afae066a0bc48d7", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_misc.cpp", "max_issues_repo_name": "entn-at/gillesdegottex_fttscarf", "max_issues_repo_head_hexsha": "91251689107f53e21bf3dc4c5afae066a0bc48d7", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_misc.cpp", "max_forks_repo_name": "entn-at/gillesdegottex_fttscarf", "max_forks_repo_head_hexsha": "91251689107f53e21bf3dc4c5afae066a0bc48d7", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7593984962, "max_line_length": 182, "alphanum_fraction": 0.640709496, "num_tokens": 1376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.5871671033699226}}
{"text": "/*\n * sum.hpp\n *\n *  Created on: Apr 15, 2019\n *      Author: Gregory Kramida\n *   Copyright: 2019 Gregory Kramida\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n//libraries\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n\nnamespace math{\n\ntemplate<typename Scalar, typename NestedContainer>\nvoid cwise_nested_sum(Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& summed,\n\t\tconst Eigen::Matrix<NestedContainer, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& field);\n\ntemplate<typename Scalar, typename NestedContainer>\nvoid cwise_nested_sum(Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& summed,\n\t\tconst Eigen::Tensor<NestedContainer, 3, Eigen::ColMajor>& field);\n\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>\ncwise_square(const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& field);\n\ntemplate<typename Scalar>\nEigen::Tensor<Scalar, 3, Eigen::ColMajor>\ncwise_square(const Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& field);\n\ntemplate<typename Scalar>\ninline\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>\ncwise_abs(const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& field){\n\treturn field.array().abs();\n}\n\ntemplate<typename Scalar>\ninline\nEigen::Tensor<Scalar, 3, Eigen::ColMajor>\ncwise_abs(const Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& field){\n\treturn field.abs();\n}\n\n}  // namespace math\n", "meta": {"hexsha": "12b3fe22c8655b6f24cb429fc493a5337c8fd43e", "size": 2003, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/cwise_unary.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_unary.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_unary.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": 32.8360655738, "max_line_length": 101, "alphanum_fraction": 0.7428856715, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5871670939575414}}
{"text": "#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n#include <autoppl/mcmc/hmc/hamiltonian.hpp>\n\nnamespace ppl {\nnamespace mcmc {\n\nstruct hamiltonian_fixture : ::testing::Test\n{\nprotected:\n};\n\n////////////////////////////////////////////////////////////\n// hamiltonian TESTS\n////////////////////////////////////////////////////////////\n\nTEST_F(hamiltonian_fixture, hamiltonian_sanity)\n{\n    double potential = -3.41;\n    Eigen::VectorXd momentum(5);\n    momentum.setZero();\n    momentum += Eigen::VectorXd::LinSpaced(momentum.size(), 1, momentum.size());\n    double kinetic = -0.5 * momentum.squaredNorm();\n    double actual = hamiltonian(potential, kinetic);\n    double expected = -3.41 - 0.5 * 55;\n    EXPECT_DOUBLE_EQ(actual, expected);\n}\n\n} // namespace mcmc\n} // namespace ppl\n", "meta": {"hexsha": "ae5f1a1417b1138d23bd024b06c00d09e3814350", "size": 778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/mcmc/hmc/hamiltonian_unittest.cpp", "max_stars_repo_name": "JamesYang007/autoppl", "max_stars_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-04-12T19:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T19:05:38.000Z", "max_issues_repo_path": "test/mcmc/hmc/hamiltonian_unittest.cpp", "max_issues_repo_name": "JamesYang007/autoppl", "max_issues_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-04-26T14:55:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T19:21:50.000Z", "max_forks_repo_path": "test/mcmc/hmc/hamiltonian_unittest.cpp", "max_forks_repo_name": "JamesYang007/autoppl", "max_forks_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T04:45:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:28:42.000Z", "avg_line_length": 25.0967741935, "max_line_length": 80, "alphanum_fraction": 0.588688946, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5871670707681577}}
{"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": "// Copyright (C) 2017-2018 Vicente J. Botet Escriba\n//\n//  Distributed under the Boost Software License, Version 1.0. (See accompanying\n//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n// Based on https://github.com/akrzemi1/explicit/blob/master/test/test_explicit.cpp\n\n// <experimental/numerics/v1/numbers/double_wide_types.hpp>\n\n//#define JASEL_CONFIG_CONTRACT_LEVEL_MASK 0x111\n#define JASEL_CONFIG_CONTRACT_VIOLATION_THROWS_V 1\n\n#include <iostream>\n#include <experimental/numerics/v1/numbers/overflow_detection_arithmetic.hpp>\n#include <string>\n\n#include <boost/detail/lightweight_test.hpp>\n\nnamespace stdex = std::experimental;\nnamespace nmx = std::experimental::numerics;\n\n#if __cplusplus >= 201402L\n\nstatic_assert(nmx::overflow_cvt<short>(1) == std::make_pair(false, short(1)), \"error\");\nstatic_assert(nmx::overflow_cvt<short>(100000) == std::make_pair(true, short(0)), \"error\");\nstatic_assert(nmx::check_overflow_cvt<short>(100000) == true, \"error\");\nstatic_assert(nmx::overflow_add(2,2) == std::make_pair(false, 4), \"error\");\nstatic_assert(nmx::overflow_sub(2,2) == std::make_pair(false, 0), \"error\");\nstatic_assert(nmx::overflow_mul(2,2) == std::make_pair(false, 4), \"error\");\nstatic_assert(nmx::overflow_div(2,2) == std::make_pair(false, 1), \"error\");\n\n#endif\n\nint main()\n{\n    {\n        int i=0;\n        short s;\n        BOOST_TEST_EQ(false, nmx::overflow_cvt(&s, i));\n        BOOST_TEST_EQ(s, 0);\n    }\n    {\n        int i=100000;\n        short s;\n        BOOST_TEST_EQ(true, nmx::overflow_cvt(&s, i));\n    }\n    {\n        int i=1;\n        int r;\n        BOOST_TEST_EQ(false, nmx::overflow_neg(&r, i));\n        BOOST_TEST_EQ(r, -1);\n    }\n    {\n        signed char i=-128;\n        signed char r;\n        BOOST_TEST_EQ(true, nmx::overflow_neg(&r, i));\n    }\n    {\n        unsigned r;\n        unsigned x = 1;\n        BOOST_TEST_EQ(false, nmx::overflow_lsh(&r, x, 2));\n        BOOST_TEST_EQ(r, 4);\n    }\n    {\n        unsigned r;\n        unsigned x = 1;\n        BOOST_TEST_EQ(true, nmx::overflow_lsh(&r, x, -1));\n    }\n    {\n        unsigned r;\n        unsigned x = 1;\n        BOOST_TEST_EQ(true, nmx::overflow_lsh(&r, x, std::numeric_limits<unsigned>::digits));\n    }\n    {\n        unsigned r;\n        unsigned x = 1;\n        unsigned y = 1;\n        BOOST_TEST_EQ(false, nmx::overflow_add(&r, x, y));\n        BOOST_TEST_EQ(r, 2);\n    }\n    {\n        unsigned char r;\n        unsigned char x = 128;\n        unsigned char y = 128;\n        BOOST_TEST_EQ(true, nmx::overflow_add(&r, x, y));\n    }\n    {\n        std::uint64_t r;\n        BOOST_TEST_EQ(true, nmx::overflow_add(&r, std::numeric_limits<std::uint64_t>::max(), std::uint64_t(1)));\n    }\n    {\n        signed char r;\n        signed char x = -64;\n        signed char y = -65;\n        BOOST_TEST_EQ(true, nmx::overflow_add(&r, x, y));\n    }\n    {\n        unsigned r;\n        unsigned x = 1;\n        unsigned y = 1;\n        BOOST_TEST_EQ(false, nmx::overflow_sub(&r, x, y));\n        BOOST_TEST_EQ(r, 0);\n    }\n    {\n        unsigned char r;\n        unsigned char x = 1;\n        unsigned char y = 2;\n        BOOST_TEST_EQ(true, nmx::overflow_sub(&r, x, y));\n    }\n    {\n        signed char r;\n        signed char x = -64;\n        signed char y = 65;\n        BOOST_TEST_EQ(true, nmx::overflow_sub(&r, x, y));\n    }\n    {\n        unsigned r;\n        unsigned x = 2;\n        unsigned y = 3;\n        BOOST_TEST_EQ(false, nmx::overflow_mul(&r, x, y));\n        BOOST_TEST_EQ(r, 6);\n    }\n    {\n        unsigned char r;\n        unsigned char x = 2;\n        unsigned char y = 128;\n        BOOST_TEST_EQ(true, nmx::overflow_mul(&r, x, y));\n    }\n    {\n        signed char r;\n        signed char x = -65;\n        signed char y = 2;\n        BOOST_TEST_EQ(true, nmx::overflow_mul(&r, x, y));\n    }\n    {\n        unsigned r;\n        unsigned x = 4;\n        unsigned y = 2;\n        BOOST_TEST_EQ(false, nmx::overflow_div(&r, x, y));\n        BOOST_TEST_EQ(r, 2);\n    }\n    {\n        unsigned char r;\n        unsigned char x = 2;\n        unsigned char y = 0;\n        BOOST_TEST_EQ(true, nmx::overflow_div(&r, x, y));\n    }\n    {\n        unsigned char r;\n        unsigned char x = 2;\n        unsigned char y = 0;\n        BOOST_TEST_EQ(true, nmx::overflow_div(&r, x, y));\n    }\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "01d1705b6993d3c0bafc31a0d03fca78a55eccf7", "size": 4283, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/numerics/numbers/overflow_detection_arithmetic_pass.cpp", "max_stars_repo_name": "jwakely/std-make", "max_stars_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 105.0, "max_stars_repo_stars_event_min_datetime": "2015-01-24T13:26:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T15:36:53.000Z", "max_issues_repo_path": "test/numerics/numbers/overflow_detection_arithmetic_pass.cpp", "max_issues_repo_name": "jwakely/std-make", "max_issues_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2015-09-04T06:57:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T18:01:44.000Z", "max_forks_repo_path": "test/numerics/numbers/overflow_detection_arithmetic_pass.cpp", "max_forks_repo_name": "jwakely/std-make", "max_forks_repo_head_hexsha": "f09d052983ace70cf371bb8ddf78d4f00330bccd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2015-01-27T11:09:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T02:23:30.000Z", "avg_line_length": 27.6322580645, "max_line_length": 112, "alphanum_fraction": 0.5731963577, "num_tokens": 1236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5870706328744042}}
{"text": "/**\n * Metrics class definition\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n\nnamespace DeepLearningFramework {\n/**\n * Metrics class\n *\n * accuracy: count of good predictions / number of predictions\n */\nclass Metrics {\npublic:\n  Metrics() = delete;\n  ~Metrics() = delete;\n\n  /**\n   * accuracy static method\n   *\n   * accuracy: count of good predictions / number of predictions\n   *\n   * @param[out] accuracy accuracy in range [0.f, 1.f]\n   * @param[in] labels one-hot encoded labels in format [N, 2]\n   * @param[in] features prediction in format [N, 2]\n   */\n  static void accuracy(float &accuracy, const Eigen::MatrixXf &labels,\n                       const Eigen::MatrixXf &features);\n};\n}; // namespace DeepLearningFramework\n", "meta": {"hexsha": "7bff725a96e391c3ca71213c7be5e0f111a74481", "size": 725, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Metrics/Metrics.hpp", "max_stars_repo_name": "Apiquet/DeepLearningFrameworkFromScratchCpp", "max_stars_repo_head_hexsha": "63a6cd57f8f50e75ac7eb9bd5d7ea79ed5253c71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Metrics/Metrics.hpp", "max_issues_repo_name": "Apiquet/DeepLearningFrameworkFromScratchCpp", "max_issues_repo_head_hexsha": "63a6cd57f8f50e75ac7eb9bd5d7ea79ed5253c71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Metrics/Metrics.hpp", "max_forks_repo_name": "Apiquet/DeepLearningFrameworkFromScratchCpp", "max_forks_repo_head_hexsha": "63a6cd57f8f50e75ac7eb9bd5d7ea79ed5253c71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9696969697, "max_line_length": 70, "alphanum_fraction": 0.6565517241, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5870706218851046}}
{"text": "#define BOOST_TEST_MODULE literals\n#include <boost/test/included/unit_test.hpp>\n#include \"exprtest.hpp\"\n\nusing namespace boost::math::constants;\n\nEXPRTEST(literal1, \"1.234\"  ,  1.234)\nEXPRTEST(literal2, \"4.2e2\"  ,  420)\nEXPRTEST(literal3, \"5e-01\"  ,  0.5)\nEXPRTEST(literal4, \"-3\"     , -3)\nEXPRTEST(literal5, \"pi\"     ,  pi<double>())\nEXPRTEST(literal6, \"epsilon\",  std::numeric_limits<double>::epsilon())\nEXPRTEST(literal7, \"phi\"    ,  phi<double>())\nEXPRTEST(literal8, \"e\"      ,  e<double>())\n", "meta": {"hexsha": "a5e23e0045e914db939ff344809472744fafd7af", "size": 496, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/literals.cpp", "max_stars_repo_name": "hmenke/boost_matheval", "max_stars_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-01-26T01:58:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:49:05.000Z", "max_issues_repo_path": "tests/literals.cpp", "max_issues_repo_name": "hmenke/boost_matheval", "max_issues_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T04:32:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T06:53:42.000Z", "max_forks_repo_path": "tests/literals.cpp", "max_forks_repo_name": "hmenke/boost_matheval", "max_forks_repo_head_hexsha": "013f28cb001b30a3d9d47758cf1a9e6456d5356e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-11-07T07:09:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T03:03:03.000Z", "avg_line_length": 33.0666666667, "max_line_length": 70, "alphanum_fraction": 0.6754032258, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5870366796621366}}
{"text": "/**\n*cpp file of assignment 4 Unit-Test\n*Authors Alexey Titov and Shir Bentabou\n*Version 1.0\n**/\n//libraries\n#include <boost/test/minimal.hpp>\n#include \"CircularInt.hpp\"\nusing namespace std;\n//main \nint test_main( int, char *[ ] ) // note the name! \n{\n    CircularInt hour {1, 12};\n    CircularInt tmp=hour;\n    //before operator\n    BOOST_CHECK( hour.getPos()==1);\n    //operator '+='\n    hour += 4;  \n    BOOST_CHECK(hour.getPos()==5);\n    //operators '+=' and '++'\n    (hour+=2)++;\n    BOOST_CHECK(hour.getPos()==8);\n    //operator '+='\n    hour += 18;\n    BOOST_REQUIRE(hour.getPos()==2);\n    //operator '-'\n    -hour;\n    BOOST_REQUIRE(hour.getPos()==10);\n    //operators '=' and int '+' CircularInt\n    hour= 1-hour;\n    BOOST_REQUIRE(hour.getPos()==3);            //BOOST_REQUIRE(hour.getPos()==11);\n    //operator CircularInt '+' CircularInt\n    tmp=hour+hour; \n    if( tmp.getPos()== 3 )\n         BOOST_FAIL( \"Ouch...\" ); \n\t// cout << hour+hour << endl;                // 10 (11 hours after 11)\n    hour += 8;\n    //operator '*='\n    hour *= 2; \n    if (!(hour.getPos()== 10))\n        BOOST_FAIL( \"Ouch...\" );\n    //operator '/'\n    tmp=hour/2;\n    if (!(tmp.getPos()==5 || tmp.getPos()==11))  // TWO OPTIONS: 11 (since 11*2=10) or 5 (since 5*2=10 too).\n        BOOST_FAIL( \"Ouch...\" );\t\n\treturn 0;                                    // #returns error code \n}\n", "meta": {"hexsha": "85b750052d4ea32f1248672eb869a3d5816af7d2", "size": 1369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Test/Mytest.cpp", "max_stars_repo_name": "cppSA/Assignment4", "max_stars_repo_head_hexsha": "df5f4c4864da060423037cf3d20598c9ab497f6d", "max_stars_repo_licenses": ["MIT"], "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/Mytest.cpp", "max_issues_repo_name": "cppSA/Assignment4", "max_issues_repo_head_hexsha": "df5f4c4864da060423037cf3d20598c9ab497f6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test/Mytest.cpp", "max_forks_repo_name": "cppSA/Assignment4", "max_forks_repo_head_hexsha": "df5f4c4864da060423037cf3d20598c9ab497f6d", "max_forks_repo_licenses": ["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.5208333333, "max_line_length": 108, "alphanum_fraction": 0.5405405405, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5869749407265199}}
{"text": "/* Copyright 2017 The sfcpp Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n\n\n\n#pragma once\n\n#include <sfc/CurveSpecification.hpp>\n\n#include <Eigen/Dense>\n\n#include <cstddef>\n#include <memory>\n#include <vector>\n\nnamespace sfcpp {\nnamespace sfc {\n\n/**\n * This class provides a simpler means to specify curves that are based on\n * k^d-trees. An object of this class can be converted to a CurveSpecification\n * object.\n */\nstruct KDCurveSpecification {\n  // Number of cubes per dimension in the subdivision step\n  size_t k;\n  // Number of dimensions\n  size_t d;\n  // A lookup table representing the child state function S^c\n  std::vector<std::vector<size_t>> grammar;\n\n  // A vector providing the order of subcubes for each state (subcubes are\n  // enumerated\n  // row-major), for example, in the 3D Hilbert curve, childOrdering[0] might be\n  // {0, 1, 3, 2, 6, 7, 5, 4}.\n  std::vector<std::vector<size_t>> childOrdering;\n\n  KDCurveSpecification(size_t k, size_t d, size_t numGrammarElements);\n\n  // KDCurveSpecification(size_t k, size_t d, std::initializer_list<std::string>\n  // stringGrammar);\n\n  /**\n   * Returns a global model of the specified curve.\n   */\n  std::shared_ptr<CurveSpecification> getCurveSpecification() const;\n\n  /**\n   * Returns a local model of the specified curve. Only works for curves where\n   * this is possible!\n   */\n  std::shared_ptr<CurveSpecification> getLocalCurveSpecification() const;\n\n  static Eigen::MatrixXd generateUnitCube(size_t dim);\n\n  /**\n   * @param k number of cubes per \"row\", must be odd and >= 3.\n   */\n  static std::shared_ptr<KDCurveSpecification> getPeanoCurveSpecification(\n      size_t d, size_t k = 3);\n\n  static std::shared_ptr<KDCurveSpecification> getHilbertCurveSpecification(\n      size_t d);\n\n  /**\n   * @param k number of cubes per \"row\", can be anything >= 2.\n   * A big value of k can be used to emulate row-major layout.\n   */\n  static std::shared_ptr<KDCurveSpecification> getMortonCurveSpecification(\n      size_t d, size_t k = 2);\n};\n\n} /* namespace sfc */\n} /* namespace sfcpp */\n", "meta": {"hexsha": "058d4c77afc9a115793fd821e862572cee7a028f", "size": 2634, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sfc/KDCurveSpecification.hpp", "max_stars_repo_name": "dholzmueller/sfcpp", "max_stars_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-10-20T07:53:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T15:54:54.000Z", "max_issues_repo_path": "src/sfc/KDCurveSpecification.hpp", "max_issues_repo_name": "dholzmueller/sfcpp", "max_issues_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sfc/KDCurveSpecification.hpp", "max_forks_repo_name": "dholzmueller/sfcpp", "max_forks_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-10-20T20:02:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-02T12:47:53.000Z", "avg_line_length": 30.275862069, "max_line_length": 80, "alphanum_fraction": 0.7031131359, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.586974924366086}}
{"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 <iostream>\n#include <NTL/ZZ>\n#include <NTL/ZZ_p>\n#include <NTL/ZZ_px>\n#include <sum.h>\n\nusing namespace NTL;\n\nEC::EC(ZZ a, ZZ b, ZZ p)\n{\n\tZZ_p::init(p);\n}\n\nPoint EC::sum(Point p1, Point p2)\n{\n\tZZ_p u = p2.y - p1.y;\n        ZZ_p uu = u * u;\t\n      \tZZ_p v = p2.x - p1.x;\n      \tZZ_p vv = v * v;\n\tZZ_p vvv = v * vv;\n\tZZ_p R = vv * p1.x;\n\tZZ_p A = uu - vvv - 2*R;\n      \tZZ_p x3 = v * A;\n      \tZZ_p y3 = u * (R - A) - vvv * p1.y;\n      \tZZ_p Z3 = vvv;\n\treturn EC:Point{x3, y3, z3};\n}\n\nstruct EC::Point{\n\tZZ_p x, y, z;\n};\n", "meta": {"hexsha": "e49616de87b87976c789632baed3ac4646d2f161", "size": 528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2.12.2/EC/ECSUM/sum.cpp", "max_stars_repo_name": "mahzoun/programs", "max_stars_repo_head_hexsha": "39fbd730d635ed49a0af2d16dd486eba1db2f295", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2.12.2/EC/ECSUM/sum.cpp", "max_issues_repo_name": "mahzoun/programs", "max_issues_repo_head_hexsha": "39fbd730d635ed49a0af2d16dd486eba1db2f295", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2.12.2/EC/ECSUM/sum.cpp", "max_forks_repo_name": "mahzoun/programs", "max_forks_repo_head_hexsha": "39fbd730d635ed49a0af2d16dd486eba1db2f295", "max_forks_repo_licenses": ["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.5, "max_line_length": 42, "alphanum_fraction": 0.5132575758, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.5868926620779671}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/function/heuman_lambda.hpp>\n#include <boost/math/special_functions/heuman_lambda.hpp>\n#include <eve/function/next.hpp>\n#include <eve/function/prev.hpp>\n#include <eve/function/is_denormal.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/minlog.hpp>\n#include <eve/platform.hpp>\n\n#include <cmath>\n\nTTS_CASE_TPL(\"Check eve::heuman_lambda return type\", EVE_TYPE)\n{\n  TTS_EXPR_IS(eve::heuman_lambda(T(0), T(0)), T);\n}\n\n\nTTS_CASE_TPL(\"Check eve::heuman_lambda behavior two parameter\", EVE_TYPE)\n{\n  using v_t = eve::element_type_t<T>;\n  using eve::as;\n  if constexpr( eve::platform::supports_invalids )\n  {\n   TTS_IEEE_EQUAL(eve::heuman_lambda(eve::pio_4(as<T>()), eve::nan(eve::as<T>())) , eve::nan(eve::as<T>()) );\n   TTS_ULP_EQUAL(eve::heuman_lambda(eve::pio_2(as<T>()), T(1)) , eve::one(eve::as<T>()), 0.5);\n   TTS_ULP_EQUAL(eve::heuman_lambda(eve::pio_2(as<T>()), T(-1)), eve::one(eve::as<T>()), 0.5);\n  }\n\n  TTS_ULP_EQUAL( eve::heuman_lambda(eve::pio_2(as<T>()), T( 0.)),  eve::one(eve::as<T>()), 0.5);\n  TTS_ULP_EQUAL( eve::heuman_lambda(eve::pio_2(as<T>()), T( 0.5)), eve::one(eve::as<T>()), 4);\n  TTS_ULP_EQUAL( eve::heuman_lambda(eve::pio_2(as<T>()), T( 0.9)), eve::one(eve::as<T>()), 4.55);\n\n  TTS_ULP_EQUAL( eve::heuman_lambda(eve::pio_4(as<T>()), T( 0.)),  T(boost::math::heuman_lambda(v_t(0)  , eve::pio_4(as<v_t>()))), 1.0);\n  TTS_ULP_EQUAL( eve::heuman_lambda(eve::pio_4(as<T>()), T( 0.5)), T(boost::math::heuman_lambda(v_t(0.5), eve::pio_4(as<v_t>()))), 2.0);\n  TTS_ULP_EQUAL( eve::heuman_lambda(eve::pio_4(as<T>()), T( 0.9)), T(boost::math::heuman_lambda(v_t(0.9), eve::pio_4(as<v_t>()))), 1.5);\n\n}\n", "meta": {"hexsha": "96c495523dfc8558bb74426f352abd4a899ce65f", "size": 2019, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/elliptic/heuman_lambda/regular/heuman_lambda.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/elliptic/heuman_lambda/regular/heuman_lambda.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/elliptic/heuman_lambda/regular/heuman_lambda.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9574468085, "max_line_length": 136, "alphanum_fraction": 0.5963348192, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925404, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5867953222800003}}
{"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": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n//\r\n// Copyright (c) 2010 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n\r\n#include <algorithms/test_equals.hpp>\r\n\r\n#include <boost/geometry/multi/algorithms/area.hpp>\r\n#include <boost/geometry/multi/algorithms/equals.hpp>\r\n\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/multi/geometries/multi_polygon.hpp>\r\n\r\n#include <boost/geometry/domains/gis/io/wkt/read_wkt_multi.hpp>\r\n\r\n\r\n\r\ntemplate <typename P>\r\nvoid test_all()\r\n{\r\n    std::string case1 = \"MULTIPOLYGON(((0 0,0 7,4 2,2 0,0 0)))\";\r\n    std::string case1_p     = \"POLYGON((0 0,0 7,4 2,2 0,0 0))\";\r\n\r\n    typedef bg::model::polygon<P> polygon;\r\n    typedef bg::model::multi_polygon<polygon> mp;\r\n    test_geometry<mp, mp>(\"c1\", case1, case1, true);\r\n\r\n    test_geometry<mp, mp>(\"c2\",\r\n            \"MULTIPOLYGON(((0 0,0 7.01,4 2,2 0,0 0)))\",\r\n            case1, false);\r\n\r\n    // Different order == equal\r\n    test_geometry<mp, mp>(\"c3\",\r\n            \"MULTIPOLYGON(((0 0,0 7,4 2,2 0,0 0)),((10 10,10 12,12 10,10 10)))\",\r\n            \"MULTIPOLYGON(((10 10,10 12,12 10,10 10)),((0 0,0 7,4 2,2 0,0 0)))\",\r\n            true);\r\n\r\n    // check different types\r\n    test_geometry<polygon, mp>(\"c1_p_mp\", case1_p, case1, true);\r\n    test_geometry<mp, polygon>(\"c1_mp_p\", case1, case1_p, true);\r\n\r\n}\r\n\r\nint test_main( int , char* [] )\r\n{\r\n    test_all<bg::model::d2::point_xy<double> >();\r\n\r\n#ifdef HAVE_TTMATH\r\n    test_all<bg::model::d2::point_xy<ttmath_big> >();\r\n#endif\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "c86c96c43c9868cc19447e8669d02fab29679f74", "size": 1770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/multi/algorithms/multi_equals.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/geometry/test/multi/algorithms/multi_equals.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/geometry/test/multi/algorithms/multi_equals.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5172413793, "max_line_length": 81, "alphanum_fraction": 0.6367231638, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5867953144909013}}
{"text": "// (C) Copyright Andrew Sutton 2007\r\n//\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0 (See accompanying file\r\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[closeness_centrality_example\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\n#include <boost/graph/undirected_graph.hpp>\r\n#include <boost/graph/exterior_property.hpp>\r\n#include <boost/graph/floyd_warshall_shortest.hpp>\r\n#include <boost/graph/closeness_centrality.hpp>\r\n#include <boost/graph/property_maps/constant_property_map.hpp>\r\n#include \"helper.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\n\r\n// The Actor type stores the name of each vertex in the graph.\r\nstruct Actor\r\n{\r\n    string name;\r\n};\r\n\r\n// Declare the graph type and its vertex and edge types.\r\ntypedef undirected_graph<Actor> Graph;\r\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\r\ntypedef graph_traits<Graph>::edge_descriptor Edge;\r\n\r\n// The name map provides an abstract accessor for the names of\r\n// each vertex. This is used during graph creation.\r\ntypedef property_map<Graph, string Actor::*>::type NameMap;\r\n\r\n// Declare a matrix type and its corresponding property map that\r\n// will contain the distances between each pair of vertices.\r\ntypedef exterior_vertex_property<Graph, int> DistanceProperty;\r\ntypedef DistanceProperty::matrix_type DistanceMatrix;\r\ntypedef DistanceProperty::matrix_map_type DistanceMatrixMap;\r\n\r\n// Declare the weight map so that each edge returns the same value.\r\ntypedef constant_property_map<Edge, int> WeightMap;\r\n\r\n// Declare a container and its corresponding property map that\r\n// will contain the resulting closeness centralities of each\r\n// vertex in the graph.\r\ntypedef boost::exterior_vertex_property<Graph, float> ClosenessProperty;\r\ntypedef ClosenessProperty::container_type ClosenessContainer;\r\ntypedef ClosenessProperty::map_type ClosenessMap;\r\n\r\nint\r\nmain(int argc, char *argv[])\r\n{\r\n    // Create the graph and a property map that provides access to[\r\n    // tha actor names.\r\n    Graph g;\r\n    NameMap nm(get(&Actor::name, g));\r\n\r\n    // Read the graph from standard input.\r\n    read_graph(g, nm, cin);\r\n\r\n    // Compute the distances between all pairs of vertices using\r\n    // the Floyd-Warshall algorithm. Note that the weight map is\r\n    // created so that every edge has a weight of 1.\r\n    DistanceMatrix distances(num_vertices(g));\r\n    DistanceMatrixMap dm(distances, g);\r\n    WeightMap wm(1);\r\n    floyd_warshall_all_pairs_shortest_paths(g, dm, weight_map(wm));\r\n\r\n    // Compute the closeness centrality for graph.\r\n    ClosenessContainer cents(num_vertices(g));\r\n    ClosenessMap cm(cents, g);\r\n    all_closeness_centralities(g, dm, cm);\r\n\r\n    // Print the closeness centrality of each vertex.\r\n    graph_traits<Graph>::vertex_iterator i, end;\r\n    for(tie(i, end) = vertices(g); i != end; ++i) {\r\n        cout << setw(12) << setiosflags(ios::left)\r\n             << g[*i].name << get(cm, *i) << endl;\r\n    }\r\n\r\n    return 0;\r\n}\r\n//]\r\n", "meta": {"hexsha": "eb173cd760bbfb707d0dca136ea7f70c86abc11d", "size": 3001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/closeness_centrality.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/graph/example/closeness_centrality.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/graph/example/closeness_centrality.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 34.8953488372, "max_line_length": 73, "alphanum_fraction": 0.7257580806, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5867953024157889}}
{"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// statistics::survival::data::example::data.cpp                             //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#include <vector>\n#include <ostream>\n#include <fstream>\n#include <stdexcept>\n#include <string> //needed?\n#include <algorithm>\n#include <iterator>\n#include <boost/tuple/tuple.hpp>\n#include <boost/range.hpp>\n#include <boost/assert.hpp>\n#include <boost/foreach.hpp> \n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/iterator/range_cycle.hpp>\n#include <boost/statistics/survival/data/include.hpp>\n#include <libs/statistics/survival/data/example/data.h>\n\nvoid example_data(std::ostream& out){\n    out << \"-> example_data : \";\n    \n    // Steps shown in this example:\n    //\n    // Records creation\n    // Events creation\n    // I/O\n    // Statistics\n    \n    using namespace boost;\n    using namespace statistics;\n    namespace surv = statistics::survival;\n\n    // [ Types ]\n    typedef unsigned val_; // do not modify\n    typedef std::vector<val_> vals_;\n\n    // Records\n    typedef surv::data::record<val_> record_;\n    typedef std::vector<record_> records_;\n    typedef range_iterator<records_>::type it_record_;\n\n    // Events\n    typedef surv::data::event<val_> event_;\n    typedef std::vector<event_> events_;\n    typedef range_iterator<events_>::type it_event_;\n\n    // I/O\n    typedef boost::archive::text_oarchive oa_;\n    typedef boost::archive::text_iarchive ia_;\n\n    // Covariates\n    typedef val_                                    x_;\n    typedef vals_                                   r_x_;\n    typedef range_cycle<>                           range_cycle_;\n    typedef range_cycle_::apply<r_x_>::type         x_cycle_;\n\n    // Statistics\n    typedef surv::data::mean_event<val_>            me_;\n    typedef std::vector<me_>                        mes_;\n    typedef surv::data::mean_events_by_covariate<val_,x_> mes_by_x_;\n\n    // [ Constants ]\n    const unsigned n_record = 4; \n    const val_ entry_bound = n_record - 1;\n    const val_ fail_time = 2;\n\n    // [ Records ]\n    records_ records;\n    events_ events;\n    for(val_ i = 0; i<n_record; i++){\n        val_ entry_t = i;\n        record_ record(entry_t,fail_time);\n        records.push_back(record);\n    }\n\n    out << \" records : \";\n    for(val_ i = 0; i<n_record; i++){\n        out << records[i] << ' ';\n    }\n\n    // [ Events ]\n    \n    surv::data::events(\n        begin(records),\n        end(records),\n        entry_bound,\n        std::back_inserter(events)\n    );\n    \n    // Analysis for n_record = 4 and entry_bound = 3;\n    //      e       ft      dt     ft<=dt  min(ft,dt)\n    //      0       2       3       1       2\n    //      1       2       2       1       2\n    //      2       2       1       0       1\n    //      3       2       0       NA      NA\n\n    BOOST_ASSERT(size(events) == entry_bound);\n    out << \" events : \";\n    BOOST_FOREACH(const event_& e,events){\n        out << e << ' ';\n    }\n\n    // [ I/O ]\n    const char* path = \"./serialized_events\";\n    \n    {\n        // Save events\n        std::ofstream ofs(path);\n        oa_ oa(ofs);\n        BOOST_FOREACH(const event_& e,events){\n            oa << e;\n            ofs.flush();\n        }\n    }\n    val_ n = size(events);\n    events_ events2;\n    {\n        // Recover events\n        event_ tmp;\n        std::ifstream ifs(path);\n        if(ifs.good()){\n            ia_ ia(ifs);\n            val_ j = 0;\n            //while(true){ //TODO\n            while(j<n){\n                ia >> tmp;\n                events2.push_back(tmp);\n                // TODO \n                //if (ifs.eof()) break; \n                //if (ifs.fail()){\n                //    throw std::runtime_error(\"error reading\");\n                //}\n                ++j;\n            }\n        }else{\n            std::string str = \"error opening : \";\n            str.append( path );\n            throw std::runtime_error(str);\n        }\n    }\n    BOOST_ASSERT(n == size(events2));\n    for(val_ i = 0; i<n; i++){\n        BOOST_ASSERT(events[i] == events2[i]);\n    }\n\n    // [ Statistics ]\n    // Assume the records were generated conditional on the following\n    // covariates:\n    r_x_ r_x;\n    {\n        using namespace boost::assign;\n        r_x += 1, 2;\n    }\n    x_cycle_ x_cycle = range_cycle_::make(r_x,0,n_record);\n    out << \"size(x_cycle) = \" << size(x_cycle) << std::endl;\n    BOOST_ASSERT( size(x_cycle)>=size(events) );\n    // Resize x_cycle to a size that matches that of events\n    x_cycle.advance_end(\n        - (size(x_cycle) - size(events))\n    );\n    BOOST_ASSERT( size(x_cycle)==size(events) );\n\n    mes_by_x_ mes_by_x(r_x);\n    mes_by_x(\n        boost::begin(x_cycle),\n        boost::end(x_cycle),\n        boost::begin(events)\n    );\n\n    mes_ mes;\n    mes_by_x.tails(std::back_inserter(mes));\n    \n    // Analysis for n_record = 4 and entry_bound = 3;\n    //      x       ft<=dt  min(ft,dt)  \n    //      1       1       2\n    //      2       1       2\n    //      1       0       1\n    // -------------------------------\n    //      1       1/2=0   3/2 = 1         // Remember, val_ = unsigned,\n    //      2       1       2               // not a float\n    \n    out << \"mean_events : \";\n    std::copy(\n        boost::begin( mes ),\n        boost::end( mes ),\n        std::ostream_iterator<me_>(out,\" \")\n    );\n\n    vals_ flat_mes;\n    surv::data::vectorize_events(\n        boost::begin( mes ),\n        boost::end( mes ),\n        std::back_inserter( flat_mes )\n    );\n\n    out << \"flattened mean_events : \";\n    std::copy(\n        boost::begin( flat_mes ),\n        boost::end( flat_mes ),\n        std::ostream_iterator<val_>(out,\" \")\n    );\n\n//    // Dont try this here because val_ = unsigned, but you get the idea\n//    surv::data::logit_log(\n//        boost::begin(flat_mes),\n//        boost::end(flat_mes),\n//        std::back_inserter(flat_mes),\n//        0.01,\n//        0.01\n//    );\n    out << \"<-\" << std::endl;\n}\n\n\n", "meta": {"hexsha": "5d7e77f72cc0e49aea004d8e0cf0af047d60bdef", "size": 6402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "survival_data copy/libs/statistics/survival/data/example/data.cpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "survival_data copy/libs/statistics/survival/data/example/data.cpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "survival_data copy/libs/statistics/survival/data/example/data.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": 28.8378378378, "max_line_length": 79, "alphanum_fraction": 0.4971883786, "num_tokens": 1584, "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": "/*!\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": "/**\n * @file test_Mesh.cc\n * @brief Unitest module for the bunny_mesh/Mesh.h file.\n * @version 1.0\n * @date 2019-02-10\n * \n * @copyright Copyright (c) 2019 Pedro Henrique S. Perrusi\n * \n */\n#include \"gtest/gtest.h\"\n\n#include \"bunny_mesh/data_io.h\"\n#include \"bunny_mesh/Mesh.h\"\n\n#include <Eigen/Dense>\n#include <math.h>\n#include <iostream>\n\nusing namespace bunny_mesh;\n\n// eigen default value for a very small number\nconst double precision = Eigen::NumTraits<double>::dummy_precision();\n    \n\nTEST(Mesh, SingleFaceNormal)\n{\n    // defines simple vertices matrix\n    bunny_dataIO::Point3DMatrixType vertices(3,3);\n    vertices << 0.0, 0.0, 0.0, // (x=0,y=0,z=0)\n                1.0, 0.0, 0.0, // (x=1,y=0,z=0)\n                0.0, 1.0, 0.0; // (x=0,y=1,z=0)\n\n    // denines a single face\n    bunny_dataIO::IndexMatrixType faces(1, 3);\n    faces << 0, 1, 2;\n\n    // Create a triangle mesh\n    TriangleMesh singleFaceMesh(vertices, faces);\n    singleFaceMesh.ComputeNormals();\n\n    // define expected output:\n    bunny_dataIO::Point3DMatrixType expectedFaceNormals(1,3);\n    expectedFaceNormals << 0.0, 0.0, 1.0;\n\n    bunny_dataIO::Point3DMatrixType expectedVerticeNormals(3,3);\n    expectedVerticeNormals << 0.0, 0.0, 1.0,\n                              0.0, 0.0, 1.0,\n                              0.0, 0.0, 1.0;\n\n    // test them...\n    // size assertions:\n    ASSERT_EQ(faces.rows(), singleFaceMesh.getFaceNormals().rows());\n    ASSERT_EQ(vertices.rows(), singleFaceMesh.getVerticeNormals().rows());\n    // norm assertions:\n    ASSERT_TRUE(expectedFaceNormals.isApprox(singleFaceMesh.getFaceNormals()));\n    ASSERT_TRUE(expectedVerticeNormals.isApprox(singleFaceMesh.getVerticeNormals()));\n}\n\nTEST(Mesh, SingleFaceNormalized)\n{\n    // defines simple vertices matrix\n    bunny_dataIO::Point3DMatrixType vertices(3,3);\n    vertices << 0.0, 0.0, 0.0,  // (x=0,y=0,z=0)\n                10.0, 0.0, 0.0, // (x=10,y=0,z=0)\n                0.0, 10.0, 0.0; // (x=0,y=10,z=0)\n\n    // denines a single face\n    bunny_dataIO::IndexMatrixType faces(1, 3);\n    faces << 0, 1, 2;\n\n    // Create a triangle mesh\n    TriangleMesh singleFaceMesh(vertices, faces);\n    singleFaceMesh.ComputeNormals();\n\n    // define expected output:\n    bunny_dataIO::Point3DMatrixType expectedFaceNormals(1,3);\n    expectedFaceNormals << 0.0, 0.0, 1.0;\n\n    bunny_dataIO::Point3DMatrixType expectedVerticeNormals(3,3);\n    expectedVerticeNormals << 0.0, 0.0, 1.0,\n                              0.0, 0.0, 1.0,\n                              0.0, 0.0, 1.0;\n\n    // test them...\n    // size assertions:\n    ASSERT_EQ(faces.rows(), singleFaceMesh.getFaceNormals().rows());\n    ASSERT_EQ(vertices.rows(), singleFaceMesh.getVerticeNormals().rows());\n    // norm assertions:\n    ASSERT_TRUE(expectedFaceNormals.isApprox(singleFaceMesh.getFaceNormals()));\n    ASSERT_TRUE(expectedVerticeNormals.isApprox(singleFaceMesh.getVerticeNormals()));\n}\n\nTEST(MESH, ObjectAngle)\n{\n    // Simple object:\n    bunny_dataIO::Point3DMatrixType vertices(3,3);\n    vertices << 0.0, 0.0, 0.0, // (x=0,y=0,z=0)\n                1.0, 0.0, 0.0, // (x=1,y=0,z=0)\n                0.0, 1.0, 0.0; // (x=0,y=1,z=0)\n\n    // denines a single face\n    bunny_dataIO::IndexMatrixType faces(1, 3);\n    faces << 0, 1, 2;\n\n    // Add a orientation:\n    bunny_dataIO::Point3DType orientation;\n    orientation << 0.0, 1.0, 0.0;\n\n    // expected angle\n    double angle = M_PI_2;\n\n    // create Mesh\n    TriangleMesh singleFaceMesh(vertices, faces);\n    // set orientation\n    singleFaceMesh.setOrientation(orientation);\n\n    // eigen default value for a very small number\n    const double precision = Eigen::NumTraits<double>::dummy_precision();\n\n    ASSERT_TRUE(abs(singleFaceMesh.objectAngle() - M_PI_2) < precision);\n}\n\nTEST(MESH, ObjectAngleNormalized)\n{\n    // Simple object:\n    bunny_dataIO::Point3DMatrixType vertices(3,3);\n    vertices << 0.0, 0.0, 0.0, // (x=0,y=0,z=0)\n                1.0, 0.0, 0.0, // (x=1,y=0,z=0)\n                0.0, 1.0, 0.0; // (x=0,y=1,z=0)\n\n    // denines a single face\n    bunny_dataIO::IndexMatrixType faces(1, 3);\n    faces << 0, 1, 2;\n\n    // Add a orientation:\n    bunny_dataIO::Point3DType orientation;\n    orientation << 0.0, 10.0, 0.0;\n\n    // expected angle\n    double angle = M_PI_2;\n\n    // create Mesh\n    TriangleMesh singleFaceMesh(vertices, faces);\n    // set orientation\n    singleFaceMesh.setOrientation(orientation);\n\n    // eigen default value for a very small number\n    const double precision = Eigen::NumTraits<double>::dummy_precision();\n\n    ASSERT_TRUE(abs(singleFaceMesh.objectAngle() - M_PI_2) < precision);\n}\n\nTEST(MESH, RotationAxis_orientationY)\n{\n    // Simple object:\n    bunny_dataIO::Point3DMatrixType vertices(3,3);\n    vertices << 0.0, 0.0, 0.0, // (x=0,y=0,z=0)\n                1.0, 0.0, 0.0, // (x=1,y=0,z=0)\n                0.0, 1.0, 0.0; // (x=0,y=1,z=0)\n\n    // denines a single face\n    bunny_dataIO::IndexMatrixType faces(1, 3);\n    faces << 0, 1, 2;\n\n    // Add a orientation:\n    bunny_dataIO::Point3DType orientation;\n    orientation << 0.0, 1.0, 0.0;\n\n    // create Mesh\n    TriangleMesh singleFaceMesh(vertices, faces);\n    // set orientation\n    singleFaceMesh.setOrientation(orientation);\n\n    // expected result\n    bunny_dataIO::Point3DType expected;\n    expected << -1, 0, 0;\n\n    ASSERT_TRUE(expected.isApprox(singleFaceMesh.RotationAxis()));\n}\n\nTEST(MESH, RotationAxis_orientationX)\n{\n    // Simple object:\n    bunny_dataIO::Point3DMatrixType vertices(3,3);\n    vertices << 0.0, 0.0, 0.0, // (x=0,y=0,z=0)\n                1.0, 0.0, 0.0, // (x=1,y=0,z=0)\n                0.0, 1.0, 0.0; // (x=0,y=1,z=0)\n\n    // denines a single face\n    bunny_dataIO::IndexMatrixType faces(1, 3);\n    faces << 0, 1, 2;\n\n    // Add a orientation:\n    bunny_dataIO::Point3DType orientation;\n    orientation << 1.0, 0.0, 0.0;\n\n    // create Mesh\n    TriangleMesh singleFaceMesh(vertices, faces);\n    // set orientation\n    singleFaceMesh.setOrientation(orientation);\n\n    // expected result\n    bunny_dataIO::Point3DType expected;\n    expected << 0, 1, 0;\n\n    ASSERT_TRUE(expected.isApprox(singleFaceMesh.RotationAxis()));\n}\n\nTEST(MESH, RotationAxisNormalized)\n{\n    // Simple object:\n    bunny_dataIO::Point3DMatrixType vertices(3,3);\n    vertices << 0.0, 0.0, 0.0, // (x=0,y=0,z=0)\n                1.0, 0.0, 0.0, // (x=1,y=0,z=0)\n                0.0, 1.0, 0.0; // (x=0,y=1,z=0)\n\n    // denines a single face\n    bunny_dataIO::IndexMatrixType faces(1, 3);\n    faces << 0, 1, 2;\n\n    // Add a orientation:\n    bunny_dataIO::Point3DType orientation;\n    orientation << 0.0, 10.0, 0.0;\n\n    // create Mesh\n    TriangleMesh singleFaceMesh(vertices, faces);\n    // set orientation\n    singleFaceMesh.setOrientation(orientation);\n\n    // expected result\n    bunny_dataIO::Point3DType expected;\n    expected << -1, 0, 0;\n\n    ASSERT_TRUE(expected.isApprox(singleFaceMesh.RotationAxis()));\n}\n\nTEST(MESH, matchObjectOrientationX)\n{\n    // Simple object:\n    bunny_dataIO::Point3DMatrixType vertices(3,3);\n    vertices << 0.0, 0.0, 0.0, // (x=0,y=0,z=0)\n                1.0, 0.0, 0.0, // (x=1,y=0,z=0)\n                0.0, 1.0, 0.0; // (x=0,y=1,z=0)\n\n    // denines a single face\n    bunny_dataIO::IndexMatrixType faces(1, 3);\n    faces << 0, 1, 2;\n\n    // Add a orientation:\n    bunny_dataIO::Point3DType orientation;\n    orientation << 1.0, 0.0, 0.0;\n\n    // create Mesh\n    TriangleMesh singleFaceMesh(vertices, faces);\n    // set orientation\n    singleFaceMesh.setOrientation(orientation);\n\n    // array to transform\n    bunny_dataIO::Point3DType verticeX, verticeY, verticeZ;\n    verticeX << 1, 0, 0;\n    verticeY << 0, 1, 0;\n    verticeZ << 0, 0, 1;\n\n    // expected result\n    bunny_dataIO::Point3DType expectedX, expectedY, expectedZ;\n    expectedX << 0, 0, -1;\n    expectedY << 0, 1, 0;\n    expectedZ << 1, 0, 0;\n\n    ASSERT_TRUE(expectedX.isApprox(singleFaceMesh.matchObjectOrientation(verticeX)));\n    ASSERT_TRUE(expectedY.isApprox(singleFaceMesh.matchObjectOrientation(verticeY)));\n    ASSERT_TRUE(expectedZ.isApprox(singleFaceMesh.matchObjectOrientation(verticeZ)));\n}\n\nTEST(MESH, matchObjectOrientationY)\n{\n    // Simple object:\n    bunny_dataIO::Point3DMatrixType vertices(3,3);\n    vertices << 0.0, 0.0, 0.0, // (x=0,y=0,z=0)\n                1.0, 0.0, 0.0, // (x=1,y=0,z=0)\n                0.0, 1.0, 0.0; // (x=0,y=1,z=0)\n\n    // denines a single face\n    bunny_dataIO::IndexMatrixType faces(1, 3);\n    faces << 0, 1, 2;\n\n    // Add a orientation:\n    bunny_dataIO::Point3DType orientation;\n    orientation << 0.0, 1.0, 0.0;\n\n    // create Mesh\n    TriangleMesh singleFaceMesh(vertices, faces);\n    // set orientation\n    singleFaceMesh.setOrientation(orientation);\n\n    // array to transform\n    bunny_dataIO::Point3DType verticeX, verticeY, verticeZ;\n    verticeX << 1, 0, 0;\n    verticeY << 0, 1, 0;\n    verticeZ << 0, 0, 1;\n\n    // expected result\n    bunny_dataIO::Point3DType expectedX, expectedY, expectedZ;\n    expectedX << 1, 0, 0;\n    expectedY << 0, 0, -1;\n    expectedZ << 0, 1, 0;\n\n    ASSERT_TRUE(expectedX.isApprox(singleFaceMesh.matchObjectOrientation(verticeX)));\n    ASSERT_TRUE(expectedY.isApprox(singleFaceMesh.matchObjectOrientation(verticeY)));\n    ASSERT_TRUE(expectedZ.isApprox(singleFaceMesh.matchObjectOrientation(verticeZ)));\n}\n\nTEST(Mesh, verticesIntoWorld)\n{\n    // defines simple vertices matrix\n    bunny_dataIO::Point3DMatrixType vertices(3,3);\n    vertices << 0.0, 0.0, 0.0, // (x=0,y=0,z=0)\n                1.0, 0.0, 0.0, // (x=1,y=0,z=0)\n                0.0, 1.0, 0.0; // (x=0,y=1,z=0)\n\n    // denines a single face\n    bunny_dataIO::IndexMatrixType faces(1, 3);\n    faces << 0, 1, 2;\n\n    // Create a triangle mesh\n    TriangleMesh singleFaceMesh(vertices, faces);\n\n    // define a non-standard orientation to the object\n    bunny_dataIO::Point3DType orientation;\n    orientation << 1.0, 0.0, 0.0;\n    singleFaceMesh.setOrientation(orientation);\n\n    // define expected output:\n    bunny_dataIO::Point3DMatrixType expectedVertices(3,3);\n    expectedVertices << 0.0, 0.0, 0.0,\n                        0.0, 0.0, -1.0,\n                        0.0, 1.0, 0.0;\n\n    bunny_dataIO::printArray(singleFaceMesh.getVerticesIntoWorld());\n\n    ASSERT_TRUE(expectedVertices.isApprox(singleFaceMesh.getVerticesIntoWorld()));\n}\n\n// TEST(Mesh, NonDefaultOrientationNormals)\n// {\n//     // defines simple vertices matrix\n//     bunny_dataIO::Point3DMatrixType vertices(3,3);\n//     vertices << 0.0, 0.0, 0.0, // (x=0,y=0,z=0)\n//                 1.0, 0.0, 0.0, // (x=1,y=0,z=0)\n//                 0.0, 1.0, 0.0; // (x=0,y=1,z=0)\n\n//     // denines a single face\n//     bunny_dataIO::IndexMatrixType faces(1, 3);\n//     faces << 0, 1, 2;\n\n//     // Create a triangle mesh\n//     TriangleMesh singleFaceMesh(vertices, faces);\n\n//     // define a non-standard orientation to the object\n//     bunny_dataIO::Point3DType orientation;\n//     orientation << 0, 1, 0;\n//     singleFaceMesh.setOrientation(orientation);\n//     // compute normals\n//     singleFaceMesh.ComputeNormals();\n\n//     // define expected output:\n//     bunny_dataIO::Point3DMatrixType expectedFaceNormals(1,3);\n//     expectedFaceNormals << 0.0, 1.0, 0.0;\n\n//     bunny_dataIO::Point3DMatrixType expectedVerticeNormals(3,3);\n//     expectedVerticeNormals << 1.0, 0.0, 0.0,\n//                               1.0, 0.0, 0.0,\n//                               1.0, 0.0, 0.0;\n\n//     bunny_dataIO::printArray(singleFaceMesh.getFaceNormals());\n\n//     bunny_dataIO::printArray(singleFaceMesh.getVerticeNormals());\n\n//     // test them...\n//     // size assertions:\n//     ASSERT_EQ(faces.rows(), singleFaceMesh.getFaceNormals().rows());\n//     ASSERT_EQ(vertices.rows(), singleFaceMesh.getVerticeNormals().rows());\n//     // norm assertions:\n//     ASSERT_TRUE(expectedFaceNormals.isApprox(singleFaceMesh.getFaceNormals()));\n//     ASSERT_TRUE(expectedVerticeNormals.isApprox(singleFaceMesh.getVerticeNormals()));\n// }", "meta": {"hexsha": "d322032be767a3f0b57df924f402157c9ded0a16", "size": 11889, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test_Mesh.cc", "max_stars_repo_name": "pedroperrusi/bunny_mesh_normals", "max_stars_repo_head_hexsha": "2fc828667cc0cb07fed36e5b7b5618545e100cfe", "max_stars_repo_licenses": ["MIT"], "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_Mesh.cc", "max_issues_repo_name": "pedroperrusi/bunny_mesh_normals", "max_issues_repo_head_hexsha": "2fc828667cc0cb07fed36e5b7b5618545e100cfe", "max_issues_repo_licenses": ["MIT"], "max_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_Mesh.cc", "max_forks_repo_name": "pedroperrusi/bunny_mesh_normals", "max_forks_repo_head_hexsha": "2fc828667cc0cb07fed36e5b7b5618545e100cfe", "max_forks_repo_licenses": ["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.8005181347, "max_line_length": 88, "alphanum_fraction": 0.6252838759, "num_tokens": 3815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5866814691357913}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <fstream>\n\n#include <boost/algorithm/string.hpp>\n#include <numeric>\n\ntypedef unsigned long long nombre;\n\nENREGISTRER_PROBLEME(22, \"Names scores\") {\n    // Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing \n    // over five-thousand first names, begin by sorting it into alphabetical order. \n    // Then working out the alphabetical value for each name, multiply this value by its alphabetical \n    // position in the list to obtain a name score.\n    // \n    // For example, when the list is sorted into alphabetical order, COLIN, which is worth \n    // 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a \n    // score of 938 \u00d7 53 = 49714.\n    // \n    // What is the total of all the name scores in the file?    \n    std::ifstream ifs(\"data/p022_names.txt\");\n    std::string entree;\n    ifs >> entree;\n    std::vector<std::string> names;\n    boost::split(names, entree, boost::is_any_of(\",\"));\n    std::sort(names.begin(), names.end());\n    nombre compteur = 0;\n    nombre resultat = 0;\n    for (const auto &name: names) {\n        nombre score = std::accumulate(name.begin(), name.end(), 0ULL, [](const nombre &n, char c) {\n            if (c != '\"')\n                return n + 1 + static_cast<nombre>(c - 'A');\n            return n;\n        });\n        resultat += (++compteur * score);\n    }\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "7a22da2bc2f487072000e8a88ee677b03cf4fff5", "size": 1459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme022.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme022.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme0xx/probleme022.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.475, "max_line_length": 102, "alphanum_fraction": 0.6230294722, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5866814594054461}}
{"text": "// Copyright Paul A. Bristow 2013\n// Copyright John Maddock 2013\n// Copyright Christopher Kormanyos\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// Examples of std::numeric_limits usage as snippets for multiprecision documentation at multiprecision.qbk.\n\n// Includes text as Quickbook comments.\n\n#include <boost/assert.hpp>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/nonfinite_num_facets.hpp>\n\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/math/tools/precision.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp> // is decimal.\n#include <boost/multiprecision/cpp_bin_float.hpp> // is binary.\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp> // Boost.Test\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <sstream>\n#include <limits> // numeric_limits\n#include <iomanip>\n#include <locale>\n\n// static long double const log10Two = 0.30102999566398119521373889472449L; // log10(2.)\n// It is more portable useful to use a Boost macro\n// See https://www.boost.org/doc/libs/release/libs/config/doc/html/boost_config/boost_macro_reference.html\nstatic constexpr long double log10Two = 0.30102999566398119521373889472449L;\n// which expands to static constexpr on standard C++11 and up, but static const on earlier versions.\n\n  /*`By default, output would only show the standard 6 decimal digits,\n so set precision to show all 50 significant digits, including any trailing zeros.\n This is generally useful to show the implicit precision of the type of the value.\n*/\n\n\n\n\ntemplate <typename T>\nint max_digits10()\n{\n   int significand_digits = std::numeric_limits<T>::digits;\n  // constexpr int significand_digits = std::numeric_limits<T>::digits;\n   return static_cast<int>(ceil(1 + significand_digits * log10Two));\n} // template <typename T> int max_digits10()\n\n// Used to test max_digits10<>() function below.\n\nBOOST_AUTO_TEST_CASE(test_numeric_limits_snips)\n{\n#if !(defined(CI_SUPPRESS_KNOWN_ISSUES) && defined(BOOST_MSVC) && (BOOST_MSVC == 1600))\n  try\n  {\n\n// Example of portable way to get `std::numeric_limits<T>::max_digits10`.\n//[max_digits10_1\n\n/*`For example, to be portable (including obselete platforms) for type `T` where `T` may be:\n `float`, `double`, `long double`, `128-bit quad type`, `cpp_bin_float_50` ...\n*/\n\n  typedef float T;\n\n  std::cout.precision(std::numeric_limits<T>::max_digits10);\n  std::cout.precision(std::numeric_limits<T>::digits10);\n  std::cout.setf(std::ios_base::showpoint); // Append any trailing zeros,\n  // or more memorably\n  std::cout << std::showpoint << std::endl; //\n\n  std::cout << \"std::cout.precision(max_digits10) = \" << std::cout.precision() << std::endl; // 9\n\n  double x = 1.2345678901234567889;\n\n  std::cout << \"x = \" << x << std::endl; //\n\n/*`which should output:\n\n  std::cout.precision(max_digits10) = 9\n  x = 1.23456789\n*/\n\n//] [/max_digits10_1]\n\n  {\n//[max_digits10_2\n\n  double write = 2./3; // Any arbitrary value that cannot be represented exactly.\n  double read = 0;\n  std::stringstream s;\n  s.precision(std::numeric_limits<double>::digits10); // or `float64_t` for 64-bit IEE754 double.\n  s << write;\n  s >> read;\n  if(read != write)\n  {\n    std::cout <<  std::setprecision(std::numeric_limits<double>::digits10)\n      << read << \" != \" << write << std::endl;\n  }\n\n//] [/max_digits10_2]\n  // 0.666666666666667 != 0.666666666666667\n  }\n\n  {\n//[max_digits10_3\n\n  double pi = boost::math::double_constants::pi;\n  std::cout.precision(std::numeric_limits<double>::max_digits10);\n  std::cout << pi << std::endl; // 3.1415926535897931\n\n//] [/max_digits10_3]\n  }\n  {\n//[max_digits10_4\n/*`and similarly for a much higher precision type:\n*/\n\n  using namespace boost::multiprecision;\n\n  typedef number<cpp_dec_float<50> > cpp_dec_float_50; // 50 decimal digits.\n\n  // or using boost::multiprecision::cpp_dec_float_50;\n\n  cpp_dec_float_50 pi = boost::math::constants::pi<cpp_dec_float_50>();\n  std::cout.precision(std::numeric_limits<cpp_dec_float_50>::max_digits10);\n  std::cout << pi << std::endl;\n  // 3.141592653589793238462643383279502884197169399375105820974944592307816406\n//] [/max_digits10_4]\n  }\n\n  {\n//[max_digits10_5\n\n  for (int i = 2; i < 15; i++)\n  {\n    std::cout << std::setw(std::numeric_limits<int>::max_digits10)\n      << boost::math::factorial<double>(i)  << std::endl;\n  }\n\n//] [/max_digits10_5]\n  }\n\n  }\n  catch(const std::exception& ex)\n  {\n    std::cout << \"Caught Exception \" << ex.what() << std::endl;\n  }\n\n  {\n//[max_digits10_6\n\n  typedef double T;\n\n  bool denorm = std::numeric_limits<T>::denorm_min() < (std::numeric_limits<T>::min)();\n  BOOST_MP_ASSERT(denorm);\n\n//] [/max_digits10_6]\n  }\n\n  {\n    unsigned char c = 255;\n    std::cout << \"char c = \" << (int)c << std::endl;\n  }\n\n  {\n//[digits10_1\n    std::cout\n      << std::setw(std::numeric_limits<short>::digits10 +1 +1) // digits10+1, and +1 for sign.\n      << std::showpos << (std::numeric_limits<short>::max)() // +32767\n      << std::endl\n      << std::setw(std::numeric_limits<short>::digits10 +1 +1)\n      << (std::numeric_limits<short>::min)() << std::endl;   // -32767\n//] [/digits10_1]\n  }\n\n  {\n//[digits10_2\n    std::cout\n      << std::setw(std::numeric_limits<unsigned short>::digits10 +1 +1) // digits10+1, and +1 for sign.\n      << std::showpos << (std::numeric_limits<unsigned short>::max)() //  65535\n      << std::endl\n      << std::setw(std::numeric_limits<unsigned short>::digits10 +1 +1) // digits10+1, and +1 for sign.\n      << (std::numeric_limits<unsigned short>::min)() << std::endl;   //      0\n//] [/digits10_2]\n  }\n\n  std::cout <<std::noshowpos << std::endl;\n\n  {\n//[digits10_3\n  std::cout.precision(std::numeric_limits<double>::max_digits10);\n  double d =  1e15;\n  double dp1 = d+1;\n  std::cout << d << \"\\n\" << dp1 << std::endl;\n  // 1000000000000000\n  // 1000000000000001\n  std::cout <<  dp1 - d << std::endl; // 1\n//] [/digits10_3]\n  }\n\n  {\n//[digits10_4\n  std::cout.precision(std::numeric_limits<double>::max_digits10);\n  double d =  1e16;\n  double dp1 = d+1;\n  std::cout << d << \"\\n\" << dp1 << std::endl;\n  // 10000000000000000\n  // 10000000000000000\n    std::cout << dp1 - d << std::endl; // 0 !!!\n//] [/digits10_4]\n  }\n\n  {\n//[epsilon_1\n  std::cout.precision(std::numeric_limits<double>::max_digits10);\n  double d = 1.;\n  double eps = std::numeric_limits<double>::epsilon();\n  double dpeps = d+eps;\n  std::cout << std::showpoint // Ensure all trailing zeros are shown.\n    << d << \"\\n\"           // 1.0000000000000000\n    << dpeps << std::endl; // 2.2204460492503131e-016\n  std::cout << dpeps - d   // 1.0000000000000002\n    << std::endl;\n//] [epsilon_1]\n  }\n\n  {\n//[epsilon_2\n  double one = 1.;\n  double nad = boost::math::float_next(one);\n  std::cout << nad << \"\\n\"  //  1.0000000000000002\n    << nad - one // 2.2204460492503131e-016\n    << std::endl;\n//] [epsilon_2]\n  }\n  {\n//[epsilon_3\n  std::cout.precision(std::numeric_limits<double>::max_digits10);\n  double d = 1.;\n  double eps = std::numeric_limits<double>::epsilon();\n  double dpeps = d + eps/2;\n\n  std::cout << std::showpoint // Ensure all trailing zeros are shown.\n    << dpeps << \"\\n\"       // 1.0000000000000000\n    << eps/2 << std::endl; // 1.1102230246251565e-016\n  std::cout << dpeps - d   // 0.00000000000000000\n    << std::endl;\n//] [epsilon_3]\n  }\n\n  {\n    typedef double RealType;\n//[epsilon_4\n/*`A tolerance might be defined using this version of epsilon thus:\n*/\n    RealType tolerance = boost::math::tools::epsilon<RealType>() * 2;\n//] [epsilon_4]\n    (void)tolerance; // warning suppression\n  }\n\n  {\n    bool b =\n//[digits10_5\n    -(std::numeric_limits<double>::max)() == std::numeric_limits<double>::lowest();\n//] [/digits10_5]\n    (void)b;  // warning suppression\n  }\n\n  {\n//[denorm_min_1\n  std::cout.precision(std::numeric_limits<double>::max_digits10);\n  if (std::numeric_limits<double>::has_denorm == std::denorm_present)\n  {\n    double d = std::numeric_limits<double>::denorm_min();\n\n      std::cout << d << std::endl; //  4.9406564584124654e-324\n\n      int exponent;\n\n      double significand = frexp(d, &exponent);\n      std::cout << \"exponent = \" << std::hex << exponent << std::endl; //  fffffbcf\n      std::cout << \"significand = \" << std::hex << significand << std::endl; // 0.50000000000000000\n  }\n  else\n  {\n    std::cout << \"No denormalization. \" << std::endl;\n  }\n//] [denorm_min_1]\n  }\n\n  {\n//[round_error_1\n    double round_err = std::numeric_limits<double>::epsilon() // 2.2204460492503131e-016\n                     * std::numeric_limits<double>::round_error(); // 1/2\n    std::cout << round_err << std::endl; // 1.1102230246251565e-016\n//] [/round_error_1]\n  }\n\n  {\n    typedef double T;\n//[tolerance_1\n/*`For example, if we want a tolerance that might suit about 9 arithmetical operations,\nsay sqrt(9) = 3,  we could define:\n*/\n\n    T tolerance =  3 * std::numeric_limits<T>::epsilon();\n\n/*`This is very widely used in Boost.Math testing\nwith Boost.Test's macro `BOOST_CHECK_CLOSE_FRACTION`\n*/\n\n    T expected = 1.0;\n    T calculated = 1.0 + std::numeric_limits<T>::epsilon();\n\n    BOOST_CHECK_CLOSE_FRACTION(expected, calculated, tolerance);\n\n//] [/tolerance_1]\n  }\n\n#if !(defined(CI_SUPPRESS_KNOWN_ISSUES) && defined(__GNUC__) && defined(_WIN32))\n  {\n//[tolerance_2\n\n  using boost::multiprecision::number;\n  using boost::multiprecision::cpp_dec_float;\n  using boost::multiprecision::et_off;\n\n  typedef number<cpp_dec_float<50>, et_off > cpp_dec_float_50; // 50 decimal digits.\n/*`[note that Boost.Test does not yet allow floating-point comparisons with expression templates on,\nso the default expression template parameter has been replaced by `et_off`.]\n*/\n\n  cpp_dec_float_50 tolerance =  3 * std::numeric_limits<cpp_dec_float_50>::epsilon();\n  cpp_dec_float_50 expected = boost::math::constants::two_pi<cpp_dec_float_50>();\n  cpp_dec_float_50 calculated = 2 * boost::math::constants::pi<cpp_dec_float_50>();\n\n  BOOST_CHECK_CLOSE_FRACTION(expected, calculated, tolerance);\n\n//] [/tolerance_2]\n  }\n\n  {\n//[tolerance_3\n\n  using boost::multiprecision::cpp_bin_float_quad;\n\n  cpp_bin_float_quad tolerance =  3 * std::numeric_limits<cpp_bin_float_quad>::epsilon();\n  cpp_bin_float_quad expected = boost::math::constants::two_pi<cpp_bin_float_quad>();\n  cpp_bin_float_quad calculated = 2 * boost::math::constants::pi<cpp_bin_float_quad>();\n\n  BOOST_CHECK_CLOSE_FRACTION(expected, calculated, tolerance);\n\n//] [/tolerance_3]\n  }\n\n  {\n//[tolerance_4\n\n  using boost::multiprecision::cpp_bin_float_oct;\n\n  cpp_bin_float_oct tolerance =  3 * std::numeric_limits<cpp_bin_float_oct>::epsilon();\n  cpp_bin_float_oct expected = boost::math::constants::two_pi<cpp_bin_float_oct>();\n  cpp_bin_float_oct calculated = 2 * boost::math::constants::pi<cpp_bin_float_oct>();\n\n  BOOST_CHECK_CLOSE_FRACTION(expected, calculated, tolerance);\n\n//] [/tolerance_4]\n  }\n\n  {\n//[nan_1]\n\n/*`NaN can be used with binary multiprecision types like `cpp_bin_float_quad`:\n*/\n  using boost::multiprecision::cpp_bin_float_quad;\n\n  if (std::numeric_limits<cpp_bin_float_quad>::has_quiet_NaN == true)\n  {\n    cpp_bin_float_quad NaN =  std::numeric_limits<cpp_bin_float_quad>::quiet_NaN();\n    std::cout << \"cpp_bin_float_quad NaN is \"  << NaN << std::endl; //   cpp_bin_float_quad NaN is nan\n\n    cpp_bin_float_quad expected = NaN;\n    cpp_bin_float_quad calculated = 2 * NaN;\n    // Comparisons of NaN's always fail:\n    bool b = expected == calculated;\n    std::cout << b << std::endl;\n    BOOST_CHECK_NE(expected, expected);\n    BOOST_CHECK_NE(expected, calculated);\n  }\n  else\n  {\n    std::cout << \"Type \" << typeid(cpp_bin_float_quad).name() << \" does not have NaNs!\" << std::endl;\n  }\n\n//]  [/nan_1]\n  }\n\n  {\n//[facet_1]\n\n/*`\nSee [@boost:/libs/math/example/nonfinite_facet_sstream.cpp]\nand we also need\n\n  #include <boost/math/special_functions/nonfinite_num_facets.hpp>\n\nThen we can equally well use a multiprecision type cpp_bin_float_quad:\n\n*/\n  using boost::multiprecision::cpp_bin_float_quad;\n\n  typedef cpp_bin_float_quad T;\n\n  using boost::math::nonfinite_num_put;\n  using boost::math::nonfinite_num_get;\n  {\n    std::locale old_locale;\n    std::locale tmp_locale(old_locale, new nonfinite_num_put<char>);\n    std::locale new_locale(tmp_locale, new nonfinite_num_get<char>);\n    std::stringstream ss;\n    ss.imbue(new_locale);\n    T inf = std::numeric_limits<T>::infinity();\n    ss << inf; // Write out.\n   BOOST_MP_ASSERT(ss.str() == \"inf\");\n    T r;\n    ss >> r; // Read back in.\n    BOOST_MP_ASSERT(inf == r); // Confirms that the floating-point values really are identical.\n    std::cout << \"infinity output was \" << ss.str() << std::endl;\n    std::cout << \"infinity input was \" << r << std::endl;\n  }\n\n/*`\n``\n  infinity output was inf\n  infinity input was inf\n``\nSimilarly we can do the same with NaN (except that we cannot use `assert` (because any comparisons with NaN always return false).\n*/\n  {\n    std::locale old_locale;\n    std::locale tmp_locale(old_locale, new nonfinite_num_put<char>);\n    std::locale new_locale(tmp_locale, new nonfinite_num_get<char>);\n    std::stringstream ss;\n    ss.imbue(new_locale);\n    T n;\n    T NaN = std::numeric_limits<T>::quiet_NaN();\n    ss << NaN; // Write out.\n    BOOST_MP_ASSERT(ss.str() == \"nan\");\n    std::cout << \"NaN output was \" << ss.str() << std::endl;\n    ss >> n; // Read back in.\n    std::cout << \"NaN input was \" << n << std::endl;\n  }\n/*`\n``\n  NaN output was nan\n  NaN input was nan\n``\n*/\n//]  [/facet_1]\n  }\n\n#endif\n#endif\n} // BOOST_AUTO_TEST_CASE(test_numeric_limits_snips)\n\n", "meta": {"hexsha": "4f4d06cad443c510d1d7ac7d4b795053f8e51fdb", "size": 13722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/numeric_limits_snips.cpp", "max_stars_repo_name": "mariospr/multiprecision", "max_stars_repo_head_hexsha": "4720edda9e3058ba68be8ae6c29342536b9ce142", "max_stars_repo_licenses": ["BSL-1.0"], "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/numeric_limits_snips.cpp", "max_issues_repo_name": "mariospr/multiprecision", "max_issues_repo_head_hexsha": "4720edda9e3058ba68be8ae6c29342536b9ce142", "max_issues_repo_licenses": ["BSL-1.0"], "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/numeric_limits_snips.cpp", "max_forks_repo_name": "mariospr/multiprecision", "max_forks_repo_head_hexsha": "4720edda9e3058ba68be8ae6c29342536b9ce142", "max_forks_repo_licenses": ["BSL-1.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.7672955975, "max_line_length": 129, "alphanum_fraction": 0.6735898557, "num_tokens": 3984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.586571369643982}}
{"text": "/***************************************************************************\n* Copyright (c) Johan Mabille, Sylvain Corlay and Wolf Vollprecht          *\n* Copyright (c) QuantStack                                                 *\n*                                                                          *\n* Distributed under the terms of the BSD 3-Clause License.                 *\n*                                                                          *\n* The full license is in the file LICENSE, distributed with this software. *\n****************************************************************************/\n\n#include <benchmark/benchmark.h>\n\n#ifdef HAS_XTENSOR\n#include \"xtensor/xnoalias.hpp\"\n#include \"xtensor/xio.hpp\"\n#include \"xtensor/xrandom.hpp\"\n#include \"xtensor/xfixed.hpp\"\n#include \"xtensor/xarray.hpp\"\n#endif\n\n#ifdef HAS_EIGEN\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#endif\n\n#ifdef HAS_XTENSOR\ntemplate <std::size_t N, std::size_t M>\nvoid Add2dFixed_XTensor(benchmark::State& state)\n{\n    using namespace xt;\n\n    xtensor_fixed<double, xshape<N, M>> a = random::rand<double>({N, M});\n    xtensor_fixed<double, xshape<N, M>> b = random::rand<double>({N, M});\n\n    for (auto _ : state)\n    {\n        xtensor_fixed<double, xshape<N, M>> res;\n        xt::noalias(res) = a + b;\n        benchmark::DoNotOptimize(res.data());\n    }\n}\nBENCHMARK_TEMPLATE(Add2dFixed_XTensor, 3, 3);\nBENCHMARK_TEMPLATE(Add2dFixed_XTensor, 8, 8);\nBENCHMARK_TEMPLATE(Add2dFixed_XTensor, 64, 64);\nBENCHMARK_TEMPLATE(Add2dFixed_XTensor, 512, 512);\n#endif\n\n#ifdef HAS_EIGEN\ntemplate <std::size_t N, std::size_t M>\nvoid Add2dFixed_Eigen(benchmark::State& state)\n{\n    using namespace Eigen;\n    Matrix<double, N, M> a = Matrix<double, N, N>::Random(N, M);\n    Matrix<double, N, M> b = Matrix<double, N, N>::Random(N, M);\n\n    for (auto _ : state)\n    {\n        Matrix<double, N, M> res;\n        res.noalias() = a + b;\n        benchmark::DoNotOptimize(res.data());\n    }\n}\nBENCHMARK_TEMPLATE(Add2dFixed_Eigen, 3, 3);\nBENCHMARK_TEMPLATE(Add2dFixed_Eigen, 8, 8);\nBENCHMARK_TEMPLATE(Add2dFixed_Eigen, 64, 64);\n#endif\n", "meta": {"hexsha": "bd76b644b53b8ae5f0977b1a1b543f28824c6a2c", "size": 2104, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/benchmark_fixed.hpp", "max_stars_repo_name": "breznak/xtensor-benchmark", "max_stars_repo_head_hexsha": "1a4afb5ca75a4119c09a4063975c5bc5aa1d8e66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-02-26T01:27:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-03T09:16:32.000Z", "max_issues_repo_path": "src/benchmark_fixed.hpp", "max_issues_repo_name": "breznak/xtensor-benchmark", "max_issues_repo_head_hexsha": "1a4afb5ca75a4119c09a4063975c5bc5aa1d8e66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T07:02:10.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-16T23:06:50.000Z", "max_forks_repo_path": "src/benchmark_fixed.hpp", "max_forks_repo_name": "breznak/xtensor-benchmark", "max_forks_repo_head_hexsha": "1a4afb5ca75a4119c09a4063975c5bc5aa1d8e66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T08:08:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-30T13:59:03.000Z", "avg_line_length": 31.8787878788, "max_line_length": 77, "alphanum_fraction": 0.5670152091, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5865713615207766}}
{"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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cstdlib>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\nvoid test_dynam_vector()\n{\n    std::cout<<\"\\n---test: operations for vectors of dynam. size---\";\n\t\n    typedef mtl::dense_vector<double> vector;\n    vector v1(10,5.), v2(10,0.), v3(10);\n\t\n    v1[7]=3.;\n\t\n    v2[2]=2.;\n    std::cout<<\"\\nv1=\"<<v1;\n    std::cout<<\"\\nv2=\"<<v2;\n\n    v3= v1 + 5. * v2 - dot(v1,v2) * v2;\n    std::cout << \"\\nv3=v1+5.*v2-mtl::dot(v1,v2)*v2=\" << v3;\n    v3/= 5.;\n    std::cout << \"\\nv3/=5. is \" << v3;\n    std::cout << \"\\nv3 has size=\" << size(v3);\n}\n\nvoid test_stat_vector()\n{\n    std::cout<<\"\\n---test: operations for vectors of fixed size---\";\n    typedef mtl::vec::parameters<mtl::tag::col_major, mtl::vec::fixed::dimension<10> > dimension;\n    typedef mtl::dense_vector<double, dimension> vector;\n    vector v1, v2, v3;\n    v1=5.;\n    v1[7]=3.;\n    v2=0.;\n    v2[2]=2.;\n    std::cout<<\"\\nv1=\"<<v1;\n    std::cout<<\"\\nv2=\"<<v2;\n    v3=v1+5.*v2-mtl::dot(v1,v2)*v2;\n    std::cout<<\"\\nv3=v1+5.*v2-mtl::dot(v1,v2)*v2=\"<<v3;\n    v3/=5.;\n    std::cout<<\"\\nv3/=5. is \"<<v3;\n    std::cout << \"\\nv3 has size=\" << mtl::static_size<vector>::value;\n}\n\nvoid test_stat_matrix()\n{\n    std::cout<<\"\\n---test: operations for matrices of stat. size---\";\n    typedef mtl::mat::parameters<mtl::tag::row_major, mtl::index::c_index, mtl::fixed::dimensions<3, 3> > matrix_parameters;\n    typedef mtl::dense2D<double, matrix_parameters>  matrix_type;\n\t\n    matrix_type A, B, C;\n\t\n    mtl::mat::diagonal_setup(A, 2. );\n\t\n    B=5.;\n    mtl::mat::inserter<matrix_type> ins(B);\n    ins[1][0]<<2.;\n\t\n    B(0,1)=3.;\n\t\n    std::cout<<\"\\nA=\"<<A;\n    std::cout<<\"\\nB=\"<<B;\n    std::cout<<\"\\nmatrices A,B,C have size=(\"<<mtl::static_num_rows<matrix_type>::value<<\",\"<<mtl::static_num_cols<matrix_type>::value<<\")\";\n    std::cout<<\"\\nmatrix B has one-norm =\"<<mtl::one_norm(B);\n\t\n    invert_diagonal(A);\n    std::cout<<\"\\ninverto of diagonal matrix A is=\"<<A;\n\n    C=A+B;\t\n    B += A;\n    C = 5.*B -A;\n    C=A*B;\n    mtl::dense_vector<mtl::Collection<matrix_type>::value_type> eigenvalues;\n    eigenvalues= eigenvalue_symmetric(A);\n    std::cout<<\"\\nmatrix A has trace =\"<<trace(A);\n}\n\n\n\nvoid test_dynam_matrix()\n{\n    std::cout<<\"\\n---test: operations for matrices of dynam. size---\";\n    typedef mtl::dense2D<double>  MATRIX;\n\t\n    MATRIX A(3,3),B(3,3),C(3,3);\n\t\n    mtl::mat::diagonal_setup(A, 2. );\n\t\n    B=5.;\n    mtl::mat::inserter<MATRIX> ins(B);\n    ins[1][0]<<2.;\n\t\n    B(0,1)=3.;\n\t\n    std::cout<<\"\\nA=\"<<A;\n    std::cout<<\"\\nB=\"<<B;\n    std::cout<<\"\\nMatrix A has size=(\"<<A.num_rows()<<\",\"<<A.num_cols()<<\")\";\n    std::cout<<\"\\nmatrix B has one-norm =\"<<mtl::one_norm(B);\n\t\n    invert_diagonal(A);\n    std::cout<<\"\\ninvert of diagonal matrix A is=\"<<A;\n\n    C=A+B;\n    B += A; \n    C = 5.*B -A;\n    C=A*B;                         \n    mtl::dense_vector<mtl::Collection<MATRIX>::value_type > eigenvalues;\n    eigenvalues=eigenvalue_symmetric(A);\n}\n\n\nvoid test_compressed_matrix()\n{\n\n    std::cout<<\"\\n---test: operations for compressed matrices ---\";\n    typedef mtl::compressed2D<double>  MATRIX;\n\t\n    MATRIX A(3,3),B(3,3),C(3,3);\n\t\n    mtl::mat::diagonal_setup(A, 2. );\n\t\n    {\n\tmtl::mat::inserter<MATRIX> ins(B);\n\tins[1][0]<<2.;\n\tins[0][1]<<3.;\n    }\n\t\n    std::cout<<\"\\nA=\"<<A;\n    std::cout<<\"\\nB=\"<<B;\n    std::cout<<\"\\nMatrix A has size=(\"<<A.num_rows()<<\",\"<<A.num_cols()<<\")\";\n    std::cout<<\"\\nmatrix B has one-norm =\"<<mtl::one_norm(B);\n\t\n    invert_diagonal(A);\n    std::cout<<\"\\ninverto of diagonal matrix A is=\"<<A;\n\t\n    C=A+B;\n    std::cout<<\"\\nC=A+B=\"<<C;\n\t \n    B += A;\n    std::cout<<\"\\nB+=A; B=\"<<B;\n\t \n    C = 5.*B -A;\n    std::cout<<\"\\nC = 5.*B -A=\"<<C;\n\t \n    C=A*B;\n    std::cout<<\"\\nC = A*B=\"<<C;\n\t \n    mtl::dense_vector<mtl::Collection<MATRIX>::value_type > eigenvalues;\n    eigenvalues= eigenvalue_symmetric(A);\n}\n\n\nvoid test_dynam_vector_and_matrix()\n{\n\n    std::cout<<\"\\n---test: operations for vectors and matrices of dynam. size---\";\n\t\n    typedef mtl::dense_vector<double> vector;\n    vector v1(10,5.), v2(10,0.), v3(10);\n    v1[7]=3.;\n\t\n    typedef mtl::dense2D<double> matrix;\n    matrix A(10,10);\n    A=10.;\n\n    v2+=A*v1;\n    v3=A*v2;\n}\n\n\n\nvoid test_stat_vector_and_matrix()\n{\n    std::cout<<\"\\n---test: operations for vectors and matrices of fixed size---\";\n\t\n    typedef mtl::vec::parameters<mtl::tag::col_major, mtl::vec::fixed::dimension<3> > dimension;\n    // typedef mtl::parameters<mtl::tag::col_major, mtl::fixed::dimension<10> > dimension;\n    typedef mtl::vec::dense_vector<double, dimension> vector;\n    vector v1,v2,v3;\n    v1=2.; v2=0.;\n\t\t\n    typedef mtl::mat::parameters<mtl::tag::row_major, mtl::index::c_index, mtl::fixed::dimensions<3, 3> > matrix_parameters;\n    typedef mtl::dense2D<double, matrix_parameters>  matrix;\n\n    matrix A;\n    A=10.;\n    v2+=A*v1;                            \n    v3=A*v2;                    \n}\n\n\nvoid test_compressed_matrix_and_vector()\n{\n\n    std::cout<<\"\\n---test: operations for vectors and compressed matrices ---\";\n\t\n    typedef mtl::compressed2D<double>  matrix;\n    matrix A(10,10);\n\t\n    mtl::mat::diagonal_setup(A, 10. );\n\t\n    typedef mtl::vec::parameters<mtl::tag::col_major, mtl::vec::fixed::dimension<10> > dimension;\n    typedef mtl::vec::dense_vector<double, dimension> vector;\n    vector v1,v2,v3;\n    v1=2.;v2=0.;\n    std::cout<<\"\\nA=\"<<A;\n    std::cout<<\"\\nv1=\"<<v1;\n    std::cout<<\"\\nv2=\"<<v2;\n    v2+=A*v1;\n    std::cout<<\"\\nv2+=A*v1; v2=\"<<v2;      \n\t\n    v3=A*v2;\n    std::cout<<\"\\nv3=A*v2=\"<<v3;\n}\n\nvoid test_solver()\n{\n    std::cout<<\"\\n---test: solver CG with iLU on compresed matrix ---\";\n    using namespace mtl;\n    using namespace itl;\n    const int size=5, N=size*size;\n\n\t\n    typedef compressed2D<double> MATRIX;\n    MATRIX A(N,N);\n    mat::laplacian_setup(A,size,size);\n\t\n    typedef dense_vector<double> vector; \n    vector x(N,1.),b(N);\n    b=A*x; x=0.;\n    std::cout<<\"\\nA=\"<<A;\n    std::cout<<\"\\nb=\"<<b;\n\n    pc::ilu_0<MATRIX>  Precond(A);\n    noisy_iteration<double> iter(b, 500, 1.e-6);\n    cg(A, x, b, Precond, iter);\n    if(iter.error_code()!=0) {\n\tstd::cout<<\"\\nInterpolation matrix:\\n\"<<A;\n\tstd::cerr<<\"\\nERROR: unsolvable system, error code=\"<<iter.error_code(); exit(EXIT_FAILURE);\n    }\n    std::cout<<\"\\nFor compressed matrix A=\"<<A;\n    std::cout<<\"\\nCG solver with iLU, b=\"<<b;\n}\n\nint main()\n{\n    test_dynam_vector();\n    test_dynam_matrix();\n    test_stat_vector();\n    test_stat_matrix();\n    test_dynam_matrix();\n    test_compressed_matrix();\n    test_dynam_vector_and_matrix();\n    test_stat_vector_and_matrix();\n    test_compressed_matrix_and_vector();\n    test_solver();\n    std::cout << \"\\nNo errors detected.\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "38aa4f8183309c5e373ca6bf7b196971e3f028e0", "size": 7135, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/ams_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/ams_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/ams_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": 26.1355311355, "max_line_length": 140, "alphanum_fraction": 0.5882270498, "num_tokens": 2323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658109754052, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5865258748613397}}
{"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_GENERIC_SQRT1PM1_HPP_INCLUDED\n#define NT2_EXPONENTIAL_FUNCTIONS_GENERIC_SQRT1PM1_HPP_INCLUDED\n\n#include <nt2/exponential/functions/sqrt1pm1.hpp>\n#include <nt2/include/functions/simd/tofloat.hpp>\n#include <nt2/include/functions/simd/sqrt.hpp>\n#include <nt2/include/functions/simd/oneplus.hpp>\n#include <nt2/include/functions/simd/minusone.hpp>\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/is_less.hpp>\n#include <nt2/include/functions/simd/tofloat.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/divides.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sqrt1pm1_, tag::cpu_\n                            , (A0)\n                            , (generic_< arithmetic_<A0> >)\n                            )\n  {\n    typedef typename boost::dispatch::meta::as_floating<A0>::type result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      return nt2::minusone(nt2::sqrt(oneplus(nt2::tofloat(a0))));\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sqrt1pm1_, tag::cpu_\n                            , (A0)\n                            , (generic_< floating_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      A0 tmp =  nt2::sqrt(oneplus(a0));\n      return  nt2::if_else(lt(nt2::abs(a0),  nt2::Half<A0>()),\n                           a0/ nt2::oneplus(tmp),\n                           nt2::minusone(tmp));\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "376978ac00f025bb7fd40bf56112382e1dc2d5e2", "size": 2097, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/generic/sqrt1pm1.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/exponential/include/nt2/exponential/functions/generic/sqrt1pm1.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/exponential/include/nt2/exponential/functions/generic/sqrt1pm1.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7894736842, "max_line_length": 80, "alphanum_fraction": 0.5751072961, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5865258651683216}}
{"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": "#include \"solver.hpp\"\n#include <Eigen/Dense>\n#ifdef SPECTRAL_VERBOSE\n#\tinclude <iostream>\n#endif\n\nnamespace graphseg { namespace detail {\n\nstd::vector<EigenComponent> solver_eigen(const Eigen::MatrixXf& A, unsigned int num_ev)\n{\n\t// solve eigensystem\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXf> solver;\n\tsolver.compute(A);\n#ifdef SPECTRAL_VERBOSE\n\tstd::cout << \"DEBUG: solver_eigen_dense_gev says \" << solver.info() << std::endl;\n#endif\n\t// collect eigenvectors and eigenvalues\n\tstd::vector<EigenComponent> solution(std::min<std::size_t>(A.rows(), num_ev));\n\tfor(unsigned int i=0; i<solution.size(); i++) {\n\t\tsolution[i].eigenvalue = solver.eigenvalues()[i];\n#ifdef SPECTRAL_VERBOSE\n\t\tstd::cout << \"DEBUG:\\teigenvalue #\" << i << \"=\" << solution[i].eigenvalue << std::endl;\n#endif\n\t\tsolution[i].eigenvector = solver.eigenvectors().col(i);\n\t}\n\treturn solution;\n}\n\n}}\n", "meta": {"hexsha": "717da4a033f21db67af0123811a6c2153c287891", "size": 869, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp_graphseg/spectral/eigen.cpp", "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/eigen.cpp", "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/eigen.cpp", "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": 28.9666666667, "max_line_length": 89, "alphanum_fraction": 0.7169159954, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782092, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5865067926919897}}
{"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": "//\n// Copyright (c) 2015-2018 CNRS\n//\n\n#include \"pinocchio/spatial/fwd.hpp\"\n#include \"pinocchio/spatial/se3.hpp\"\n#include \"pinocchio/multibody/visitor.hpp\"\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/centroidal.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/cholesky.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/center-of-mass.hpp\"\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/parsers/urdf.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <iostream>\n\n#include \"pinocchio/utils/timer.hpp\"\n\n#include <Eigen/StdVector>\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::VectorXd)\n\nint main(int argc, const char ** argv)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  PinocchioTicToc timer(PinocchioTicToc::US);\n  #ifdef NDEBUG\n  const int NBT = 1000*100;\n  #else\n    const int NBT = 1;\n    std::cout << \"(the time score in debug mode is not relevant) \" << std::endl;\n  #endif\n    \n  pinocchio::Model model;\n\n  std::string filename = PINOCCHIO_SOURCE_DIR\"/models/simple_humanoid.urdf\";\n  if(argc>1) filename = argv[1];\n  \n  bool with_ff = true;\n  if(argc>2)\n  {\n    const std::string ff_option = argv[2];\n    if(ff_option == \"-no-ff\")\n      with_ff = false;\n  }\n  \n  if( filename == \"HS\") \n    pinocchio::buildModels::humanoidRandom(model,true);\n  else\n    if(with_ff)\n      pinocchio::urdf::buildModel(filename,JointModelFreeFlyer(),model);\n    else\n      pinocchio::urdf::buildModel(filename,model);\n  std::cout << \"nq = \" << model.nq << std::endl;\n  \n  \n\n  pinocchio::Data data(model);\n  VectorXd q = VectorXd::Random(model.nq);\n  VectorXd qdot = VectorXd::Random(model.nv);\n  VectorXd qddot = VectorXd::Random(model.nv);\n\n  std::vector<VectorXd> qs     (NBT);\n  std::vector<VectorXd> qdots  (NBT);\n  std::vector<VectorXd> qddots (NBT);\n  for(size_t i=0;i<NBT;++i)\n    {\n      qs[i]     = Eigen::VectorXd::Random(model.nq);\n      qs[i].segment<4>(3) /= qs[i].segment<4>(3).norm();\n      qdots[i]  = Eigen::VectorXd::Random(model.nv);\n      qddots[i] = Eigen::VectorXd::Random(model.nv);\n    }\n\n \n  timer.tic();\n  SMOOTH(NBT)\n    {\n      rnea(model,data,qs[_smooth],qdots[_smooth],qddots[_smooth]);\n    }\n  std::cout << \"RNEA = \\t\\t\"; timer.toc(std::cout,NBT);\n\n  timer.tic();\n  SMOOTH(NBT)\n  {\n    nonLinearEffects(model,data,qs[_smooth],qdots[_smooth]);\n  }\n  std::cout << \"NLE = \\t\\t\"; timer.toc(std::cout,NBT);\n\n  timer.tic();\n  SMOOTH(NBT)\n  {\n    rnea(model,data,qs[_smooth],qdots[_smooth],Eigen::VectorXd::Zero(model.nv));\n  }\n  std::cout << \"NLE via RNEA = \\t\\t\"; timer.toc(std::cout,NBT);\n \n  timer.tic();\n  SMOOTH(NBT)\n    {\n      crba(model,data,qs[_smooth]);\n    }\n  std::cout << \"CRBA = \\t\\t\"; timer.toc(std::cout,NBT);\n  \n  timer.tic();\n  SMOOTH(NBT)\n  {\n    crbaMinimal(model,data,qs[_smooth]);\n  }\n  std::cout << \"CRBA minimal = \\t\\t\"; timer.toc(std::cout,NBT);\n\n  timer.tic();\n  SMOOTH(NBT)\n  {\n    computeAllTerms(model,data,qs[_smooth],qdots[_smooth]);\n  }\n  std::cout << \"computeAllTerms = \\t\\t\"; timer.toc(std::cout,NBT);\n  \n  double total = 0;\n  SMOOTH(NBT)\n    {\n      crba(model,data,qs[_smooth]);\n      timer.tic();\n      cholesky::decompose(model,data);\n      total += timer.toc(timer.DEFAULT_UNIT);\n    }\n  std::cout << \"Branch Induced Sparsity Cholesky = \\t\" << (total/NBT)\n\t    << \" \" << timer.unitName(timer.DEFAULT_UNIT) <<std::endl;\n  \n  total = 0;\n  Eigen::LDLT<Eigen::MatrixXd> Mldlt(data.M);\n  SMOOTH(NBT)\n  {\n    crba(model,data,qs[_smooth]);\n    data.M.triangularView<Eigen::StrictlyLower>()\n    = data.M.transpose().triangularView<Eigen::StrictlyLower>();\n    timer.tic();\n    Mldlt.compute(data.M);\n    total += timer.toc(timer.DEFAULT_UNIT);\n  }\n  std::cout << \"Dense Eigen Cholesky = \\t\" << (total/NBT)\n  << \" \" << timer.unitName(timer.DEFAULT_UNIT) <<std::endl;\n \n  timer.tic();\n  SMOOTH(NBT)\n    {\n      computeJointJacobians(model,data,qs[_smooth]);\n    }\n  std::cout << \"Jacobian = \\t\"; timer.toc(std::cout,NBT);\n  \n  timer.tic();\n  SMOOTH(NBT)\n  {\n    computeJointJacobiansTimeVariation(model,data,qs[_smooth],qdots[_smooth]);\n  }\n  std::cout << \"Jacobian Time Variation = \\t\"; timer.toc(std::cout,NBT);\n\n  timer.tic();\n  SMOOTH(NBT)\n    {\n      jacobianCenterOfMass(model,data,qs[_smooth],true);\n    }\n  std::cout << \"COM+Jcom = \\t\"; timer.toc(std::cout,NBT);\n  \n  timer.tic();\n  SMOOTH(NBT)\n  {\n    centerOfMass(model,data,qs[_smooth], qdots[_smooth], qddots[_smooth], true);\n  }\n  std::cout << \"COM+vCOM+aCOM = \\t\"; timer.toc(std::cout,NBT);\n\n  timer.tic();\n  SMOOTH(NBT)\n  {\n    forwardKinematics(model,data,qs[_smooth]);\n  }\n  std::cout << \"Zero Order Kinematics = \\t\"; timer.toc(std::cout,NBT);\n\n\n  timer.tic();\n  SMOOTH(NBT)\n  {\n    forwardKinematics(model,data,qs[_smooth],qdots[_smooth]);\n  }\n  std::cout << \"First Order Kinematics = \\t\"; timer.toc(std::cout,NBT);\n  \n  timer.tic();\n  SMOOTH(NBT)\n  {\n    forwardKinematics(model,data,qs[_smooth],qdots[_smooth], qddots[_smooth]);\n  }\n  std::cout << \"Second Order Kinematics = \\t\"; timer.toc(std::cout,NBT);\n  \n  timer.tic();\n  SMOOTH(NBT)\n  {\n    ccrba(model,data,qs[_smooth],qdots[_smooth]);\n  }\n  std::cout << \"CCRBA = \\t\"; timer.toc(std::cout,NBT);\n  \n  timer.tic();\n  SMOOTH(NBT)\n  {\n    aba(model,data,qs[_smooth],qdots[_smooth], qddots[_smooth]);\n  }\n  std::cout << \"ABA = \\t\"; timer.toc(std::cout,NBT);\n  \n  timer.tic();\n  SMOOTH(NBT)\n  {\n    emptyForwardPass(model,data);\n  }\n  std::cout << \"Empty Forward Pass = \\t\"; timer.toc(std::cout,NBT);\n  \n  timer.tic();\n  SMOOTH(NBT)\n  {\n    computeCoriolisMatrix(model,data,qs[_smooth],qdots[_smooth]);\n  }\n  std::cout << \"Coriolis Matrix = \\t\"; timer.toc(std::cout,NBT);\n  \n  timer.tic();\n  SMOOTH(NBT)\n  {\n    computeMinverse(model,data,qs[_smooth]);\n  }\n  std::cout << \"Minv = \\t\"; timer.toc(std::cout,NBT);\n\n  std::cout << \"--\" << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "43fcc1633bb7b8d4a2b3baa09c67c769e681fe70", "size": 6016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/timings.cpp", "max_stars_repo_name": "matthieuvigne/pinocchio", "max_stars_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "benchmark/timings.cpp", "max_issues_repo_name": "matthieuvigne/pinocchio", "max_issues_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark/timings.cpp", "max_forks_repo_name": "matthieuvigne/pinocchio", "max_forks_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 25.2773109244, "max_line_length": 80, "alphanum_fraction": 0.6377992021, "num_tokens": 1921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5864804659758177}}
{"text": "#include <path_follower/supervisor/distancetopathsupervisor.h>\n#include <path_msgs/FollowPathResult.h>\n#include <paths.h>\n#include <cslibs_navigation_utilities/Line2d.h>\n#include <Eigen/Core>\n\nusing namespace Eigen;\n\nnamespace {\n//! Module name, that is used for ros console output\nconst std::string MODULE = \"s_disttopath\";\n}\n\nDistanceToPathSupervisor::DistanceToPathSupervisor(double max_distance_to_path):\n    max_dist_(max_distance_to_path),\n    visualizer_(Visualizer::getInstance())\n{}\n\nvoid DistanceToPathSupervisor::supervise(Supervisor::State &state, Supervisor::Result *out)\n{\n    double dist = calculateDistanceToCurrentPathSegment(state);\n    ROS_DEBUG_NAMED(MODULE, \"Distance to current path segment: %g m\", dist);\n    if (dist > max_dist_) {\n        //parent_.say(\"abort: too far away!\"); //TODO: give supervisors access to say().\n\n        ROS_WARN_NAMED(MODULE, \"Moved too far away from the path (%g m, limit: %g m). Abort.\",\n                 dist, max_dist_);\n\n        out->can_continue = false;\n        out->status = path_msgs::FollowPathResult::RESULT_STATUS_PATH_LOST;\n    }\n}\n\ndouble DistanceToPathSupervisor::calculateDistanceToCurrentPathSegment(const Supervisor::State &state)\n{\n    /* Calculate line from last way point to current way point (which should be the line the robot is driving on)\n     * and calculate the distance of the robot to this line.\n     */\n\n    // Get previous waypoint\n    // If the current waypoint is the first in this sub path (i.e. index == 0), use the next\n    // instead. (I am not absolutly sure if this a good behaviour, so observe this via debug-output).\n    int wp1_idx = 0;\n    if (state.path->getWaypointIndex() > 0) {\n        wp1_idx = state.path->getWaypointIndex() - 1;\n    } else {\n        // if wp_idx == 0, use the segment from 0th to 1st waypoint.\n        wp1_idx = 1;\n\n        ROS_DEBUG_NAMED(MODULE, \"Toggle waypoints as wp_idx == 0 in calculateDistanceToCurrentPathSegment() (%s, line %d)\", __FILE__, __LINE__);\n    }\n\n    geometry_msgs::Pose wp1 = state.path->getWaypoint(wp1_idx);\n    geometry_msgs::Pose wp2 = state.path->getCurrentWaypoint();\n\n    // line from last waypoint to current one.\n    Line2d segment_line(Vector2d(wp1.position.x, wp1.position.y), Vector2d(wp2.position.x, wp2.position.y));\n\n    ///// visualize start and end point of the current segment (for debugging)\n    visualizer_->drawMark(24, wp1.position, \"segment_marker\", 0, 1, 1);\n    visualizer_->drawMark(25, wp2.position, \"segment_marker\", 1, 0, 1);\n    /////\n\n    // get distance of robot (slam_pose_) to segment_line.\n    return segment_line.GetDistance(state.robot_pose.head<2>());\n}\n", "meta": {"hexsha": "ee3e7caac201e597185b4b46effc8ba0b5095d9e", "size": 2633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "path_follower/src/supervisor/distancetopathsupervisor.cpp", "max_stars_repo_name": "sunarditay/gerona", "max_stars_repo_head_hexsha": "7ca6bb169571d498c4a2d627faddc8cbe590d2c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 296.0, "max_stars_repo_stars_event_min_datetime": "2017-06-19T07:06:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T01:27:44.000Z", "max_issues_repo_path": "path_follower/src/supervisor/distancetopathsupervisor.cpp", "max_issues_repo_name": "sunarditay/gerona", "max_issues_repo_head_hexsha": "7ca6bb169571d498c4a2d627faddc8cbe590d2c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T08:49:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T22:18:28.000Z", "max_forks_repo_path": "path_follower/src/supervisor/distancetopathsupervisor.cpp", "max_forks_repo_name": "sunarditay/gerona", "max_forks_repo_head_hexsha": "7ca6bb169571d498c4a2d627faddc8cbe590d2c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117.0, "max_forks_repo_forks_event_min_datetime": "2017-05-30T10:50:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T01:27:23.000Z", "avg_line_length": 39.2985074627, "max_line_length": 144, "alphanum_fraction": 0.7037599696, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.5864804544267347}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/matrix/adjugate.hpp>\n#include <fcppt/math/matrix/comparison.hpp>\n#include <fcppt/math/matrix/object_impl.hpp>\n#include <fcppt/math/matrix/output.hpp>\n#include <fcppt/math/matrix/row.hpp>\n#include <fcppt/math/matrix/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <ostream>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_matrix_adjugate\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tint,\n\t\t3,\n\t\t3\n\t>\n\tmatrix_type;\n\n\tmatrix_type const t(\n\t\tfcppt::math::matrix::row(\n\t\t\t-3, 2, -5\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t-1, 0, -2\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t3, -4, 1\n\t\t)\n\t);\n\n\tmatrix_type const result(\n\t\tfcppt::math::matrix::adjugate(\n\t\t\tt\n\t\t)\n\t);\n\n\tstd::cout\n\t\t<< result\n\t\t<< '\\n';\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult,\n\t\tmatrix_type(\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t-8,18,-4\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t-5,12,-1\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t4,-6,2\n\t\t\t)\n\t\t)\n\t);\n}\n", "meta": {"hexsha": "cfc79c8e560a0406a761286670e87071c1235777", "size": 1452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/matrix/adjugate.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/matrix/adjugate.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/matrix/adjugate.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8571428571, "max_line_length": 61, "alphanum_fraction": 0.6811294766, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5864804496721591}}
{"text": "#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n#include \"simple_cycles.hpp\"\n#include <boost/test/unit_test.hpp>\n\nusing namespace bglex;\n\nBOOST_AUTO_TEST_CASE(test1) {\n  typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS>\n      Graph;\n  Graph G(6);\n  boost::add_edge(0, 1, G);\n  boost::add_edge(1, 2, G);\n  boost::add_edge(2, 3, G);\n  boost::add_edge(3, 1, G);\n  boost::add_edge(2, 4, G);\n  boost::add_edge(4, 5, G);\n  boost::add_edge(5, 3, G);\n\n  vector<vector<int>> reference = {{1, 2, 4, 5, 3}, {1, 2, 3}};\n\n  vector<vector<Graph::vertex_descriptor>> cycles;\n  cycles = bglex::simple_cycles<Graph>(G);\n\n  BOOST_CHECK_EQUAL(cycles.size(), reference.size());\n  for (auto n = 0; n < cycles.size(); n++) {\n    BOOST_CHECK_EQUAL(cycles[n].size(), reference[n].size());\n    for (auto m = 0; m < cycles[n].size(); m++) {\n      BOOST_CHECK_EQUAL(cycles[n][m], reference[n][m]);\n    }\n  }\n}", "meta": {"hexsha": "ad007752902fb5e0bd0e0ccc2cd0ec7108d1f10e", "size": 910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_test/simple_cycles.cpp", "max_stars_repo_name": "herenvarno/bglex", "max_stars_repo_head_hexsha": "a08f9be87bc332dd03a59a40f733d10ac9730457", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_test/simple_cycles.cpp", "max_issues_repo_name": "herenvarno/bglex", "max_issues_repo_head_hexsha": "a08f9be87bc332dd03a59a40f733d10ac9730457", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_test/simple_cycles.cpp", "max_forks_repo_name": "herenvarno/bglex", "max_forks_repo_head_hexsha": "a08f9be87bc332dd03a59a40f733d10ac9730457", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4375, "max_line_length": 75, "alphanum_fraction": 0.643956044, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143953, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5864804455922942}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, fma_double) {\n  using stan::math::fma;\n  EXPECT_FLOAT_EQ(1.0, fma(3.0, 2.0, -5));\n  EXPECT_FLOAT_EQ(0.0, fma(2.0, 3.0, -6));\n  EXPECT_FLOAT_EQ(46.9, fma(4.5, 2.0, 37.9));\n}\n\nTEST(MathFunctions, fma_int) {\n  using stan::math::fma;\n  EXPECT_FLOAT_EQ(11.0, fma(int(3),int(2),int(5)));\n}\n\nTEST(MathFunctions, fma_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::fma(nan, 3.0, 2.7));\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::fma(3.0, nan, 1.5));\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::fma(2, -8.2, nan));\n}\n", "meta": {"hexsha": "198ed5e27a2e43797869d0e77cfe2f0bb8181165", "size": 783, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/fma.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/test/unit/math/prim/scal/fun/fma.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/test/unit/math/prim/scal/fun/fma.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.1153846154, "max_line_length": 56, "alphanum_fraction": 0.6360153257, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.5864804360831434}}
{"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// Copyright (c) 2015-2018 Benjamin Buch\n//\n// https://github.com/bebuch/mitrax\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n//-----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE mitrax operator\n#include <boost/test/unit_test.hpp>\n\n#include <mitrax/operator.hpp>\n#include <mitrax/compare.hpp>\n\n\nusing boost::typeindex::type_id;\nusing boost::typeindex::type_id_runtime;\nusing namespace mitrax;\nusing namespace mitrax::literals;\n\n\ntemplate < typename T >\nauto rt_id(T&& v){\n\treturn type_id_runtime(static_cast< T&& >(v));\n}\n\ntemplate < typename T >\nauto const id = type_id< T >();\n\n\nconstexpr auto ref1 = make_matrix< int >(3_DS, {\n\t{0, 1, 2},\n\t{3, 4, 5},\n\t{6, 7, 8}\n});\n\nconstexpr auto ref2 = make_matrix< int >(3_DS, {\n\t{0, 2, 4},\n\t{6, 8, 10},\n\t{12, 14, 16}\n});\n\nconstexpr auto ref3 = make_matrix< int >(3_DS, {\n\t{0, 3, 6},\n\t{9, 12, 15},\n\t{18, 21, 24}\n});\n\nconstexpr auto ref1_mod3 = make_matrix< int >(3_DS, {\n\t{0, 1, 2},\n\t{0, 1, 2},\n\t{0, 1, 2}\n});\n\nconstexpr auto ref1_square = make_matrix< int >(3_DS, {\n\t{0, 1, 4},\n\t{9, 16, 25},\n\t{36, 49, 64}\n});\n\nconstexpr auto ref1_element_plus1 = make_matrix< int >(3_DS, {\n\t{1, 2, 3},\n\t{4, 5, 6},\n\t{7, 8, 9}\n});\n\nconstexpr auto ref1_element_minus1 = make_matrix< int >(3_DS, {\n\t{-1, 0, 1},\n\t{2, 3, 4},\n\t{5, 6, 7}\n});\n\nconstexpr auto ref_all1 = make_matrix< int >(3_DS, {\n\t{1, 1, 1},\n\t{1, 1, 1},\n\t{1, 1, 1}\n});\n\nconstexpr auto ref_all3 = make_matrix< int >(3_DS, {\n\t{3, 3, 3},\n\t{3, 3, 3},\n\t{3, 3, 3}\n});\n\nconstexpr auto ref_all9 = make_matrix< int >(3_DS, {\n\t{9, 9, 9},\n\t{9, 9, 9},\n\t{9, 9, 9}\n});\n\nconstexpr auto ref_mod = make_matrix< int >(3_DS, {\n\t{2, 3, 4},\n\t{5, 6, 7},\n\t{8, 9, 10}\n});\n\nconstexpr auto ref_all9_mod_res = make_matrix< int >(3_DS, {\n\t{1, 0, 1},\n\t{4, 3, 2},\n\t{1, 0, 9}\n});\n\n\n// TODO: also check non compile time versions\n// TODO: also check non square versions\n\n\nBOOST_AUTO_TEST_SUITE(suite_operator)\n\n\nBOOST_AUTO_TEST_CASE(test_element_plus_assign){\n\tauto m = ref1;\n\n\telement_plus_assign(m, 1);\n\tauto eq = m == ref1_element_plus1;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_element_minus_assign){\n\tauto m = ref1;\n\n\telement_minus_assign(m, 1);\n\tauto eq = m == ref1_element_minus1;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_multiplies_assign){\n\tauto m = ref1;\n\n\tm *= 3;\n\tauto eq = m == ref3;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_divides_assign){\n\tauto m = ref3;\n\n\tm /= 3;\n\tauto eq = m == ref1;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_modulus_assign){\n\tauto m = ref1;\n\n\tm %= 3;\n\tauto eq = m == ref1_mod3;\n\tBOOST_TEST(eq);\n}\n\n\nBOOST_AUTO_TEST_CASE(test_plus_assign){\n\tauto m = ref1;\n\n\tm += ref1;\n\tauto eq = m == ref2;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_minus_assign){\n\tauto m = ref2;\n\n\tm -= ref1;\n\tauto eq = m == ref1;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_element_multiplies_assign){\n\tauto m = ref1;\n\n\telement_multiplies_assign(m, ref1);\n\tauto eq = m == ref1_square;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_element_divides_assign){\n\tauto m = ref1_element_plus1;\n\n\telement_divides_assign(m, ref1_element_plus1);\n\tauto eq = m == ref_all1;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_element_modulus_assign){\n\tauto m = ref_all9;\n\n\telement_modulus_assign(m, ref_mod);\n\tauto eq = m == ref_all9_mod_res;\n\tBOOST_TEST(eq);\n}\n\n\nBOOST_AUTO_TEST_CASE(test_element_plus){\n\tauto m = ref1;\n\n\tauto res = element_plus(m, 1);\n\tauto eq = res == ref1_element_plus1;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_element_minus){\n\tauto m = ref1;\n\n\tauto res = element_minus(m, 1);\n\tauto eq = res == ref1_element_minus1;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_multiplies){\n\tauto m = ref1;\n\n\tauto res1 = m * 3;\n\tauto res2 = 3 * m;\n\tauto eq1 = res1 == ref3;\n\tauto eq2 = res2 == ref3;\n\tBOOST_TEST(eq1);\n\tBOOST_TEST(eq2);\n}\n\nBOOST_AUTO_TEST_CASE(test_divides){\n\tauto m = ref3;\n\n\tauto res = m / 3;\n\tauto eq = res == ref1;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_modulus){\n\tauto m = ref1;\n\n\tauto res = m % 3;\n\tauto eq = res == ref1_mod3;\n\tBOOST_TEST(eq);\n}\n\n\nBOOST_AUTO_TEST_CASE(test_plus){\n\tauto m = ref1;\n\n\tauto res = m + ref1;\n\tauto eq = res == ref2;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_minus){\n\tauto m = ref2;\n\n\tauto res = m - ref1;\n\tauto eq = res == ref1;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_element_multiplies){\n\tauto m = ref1;\n\n\tauto res = element_multiplies(m, ref1);\n\tauto eq = res == ref1_square;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_element_divides){\n\tauto m = ref1_element_plus1;\n\n\tauto res = element_divides(m, ref1_element_plus1);\n\tauto eq = res == ref_all1;\n\tBOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(test_element_modulus){\n\tauto m = ref_all9;\n\n\tauto res = element_modulus(m, ref_mod);\n\tauto eq = res == ref_all9_mod_res;\n\tBOOST_TEST(eq);\n}\n\n\nBOOST_AUTO_TEST_CASE(test_matrix_multiplies){\n\tauto m = ref_all1 * ref_all1;\n\n\tauto eq = m == ref_all3;\n\tBOOST_TEST(eq);\n}\n\n\nBOOST_AUTO_TEST_CASE(test_transpose){\n\tconstexpr auto m_cc = make_matrix< int >(2_CS, 3_RS, {\n\t\t{1, 2},\n\t\t{3, 4},\n\t\t{5, 6}\n\t});\n\n\tauto m_CD = make_matrix< int >(2_CS, 3_RD, {\n\t\t{1, 2},\n\t\t{3, 4},\n\t\t{5, 6}\n\t});\n\n\tauto m_dc = make_matrix< int >(2_CD, 3_RS, {\n\t\t{1, 2},\n\t\t{3, 4},\n\t\t{5, 6}\n\t});\n\n\tauto m_DD = make_matrix< int >(2_CD, 3_RD, {\n\t\t{1, 2},\n\t\t{3, 4},\n\t\t{5, 6}\n\t});\n\n\t/*constexpr*/ auto trans_cc = transpose(m_cc); //TODO:need constexpr lambda\n\tauto trans_CD = transpose(m_CD);\n\tauto trans_dc = transpose(m_dc);\n\tauto trans_DD = transpose(m_DD);\n\n\tauto check1 = [](auto const& m){\n\t\treturn\n\t\t\tm.cols() == 3_CS &&\n\t\t\tm.rows() == 2_RS &&\n\t\t\tm(0_c, 0_r) == 1 &&\n\t\t\tm(1_c, 0_r) == 3 &&\n\t\t\tm(2_c, 0_r) == 5 &&\n\t\t\tm(0_c, 1_r) == 2 &&\n\t\t\tm(1_c, 1_r) == 4 &&\n\t\t\tm(2_c, 1_r) == 6;\n\t};\n\n\tauto check2 = [](auto const& m){\n\t\treturn\n\t\t\tm.cols() == 2_CS &&\n\t\t\tm.rows() == 3_RS &&\n\t\t\tm(0_c, 0_r) == 1 &&\n\t\t\tm(1_c, 0_r) == 2 &&\n\t\t\tm(0_c, 1_r) == 3 &&\n\t\t\tm(1_c, 1_r) == 4 &&\n\t\t\tm(0_c, 2_r) == 5 &&\n\t\t\tm(1_c, 2_r) == 6;\n\t};\n\n\tBOOST_TEST(check1(trans_cc));\n\tBOOST_TEST(check1(trans_CD));\n\tBOOST_TEST(check1(trans_dc));\n\tBOOST_TEST(check1(trans_DD));\n\n\tBOOST_TEST((rt_id(trans_cc) == id< std_matrix< int, 3_C, 2_R > >));\n\tBOOST_TEST((rt_id(trans_CD) == id< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(trans_dc) == id< std_matrix< int, 3_C, 0_R > >));\n\tBOOST_TEST((rt_id(trans_DD) == id< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check2(transpose(trans_cc)));\n\tBOOST_TEST(check2(transpose(trans_CD)));\n\tBOOST_TEST(check2(transpose(trans_dc)));\n\tBOOST_TEST(check2(transpose(trans_DD)));\n}\n\nBOOST_AUTO_TEST_CASE(test_unary_plus){\n\tauto m = ref1_element_minus1;\n\n\tauto n = +m;\n\n\tBOOST_TEST((\n\t\t\tn.cols() == 3_CS &&\n\t\t\tn.rows() == 3_RS &&\n\t\t\tn(0_c, 0_r) == -1 &&\n\t\t\tn(1_c, 0_r) == 0 &&\n\t\t\tn(2_c, 0_r) == 1 &&\n\t\t\tn(0_c, 1_r) == 2 &&\n\t\t\tn(1_c, 1_r) == 3 &&\n\t\t\tn(2_c, 1_r) == 4 &&\n\t\t\tn(0_c, 2_r) == 5 &&\n\t\t\tn(1_c, 2_r) == 6 &&\n\t\t\tn(2_c, 2_r) == 7\n\t));\n}\n\nBOOST_AUTO_TEST_CASE(test_unary_minus){\n\tauto m = ref1_element_minus1;\n\n\tauto n = -m;\n\n\tBOOST_TEST((\n\t\t\tn.cols() == 3_CS &&\n\t\t\tn.rows() == 3_RS &&\n\t\t\tn(0_c, 0_r) == 1 &&\n\t\t\tn(1_c, 0_r) == 0 &&\n\t\t\tn(2_c, 0_r) == -1 &&\n\t\t\tn(0_c, 1_r) == -2 &&\n\t\t\tn(1_c, 1_r) == -3 &&\n\t\t\tn(2_c, 1_r) == -4 &&\n\t\t\tn(0_c, 2_r) == -5 &&\n\t\t\tn(1_c, 2_r) == -6 &&\n\t\t\tn(2_c, 2_r) == -7\n\t));\n}\n\nBOOST_AUTO_TEST_CASE(test_abs){\n\tauto m = ref1_element_minus1;\n\n\tauto n = abs(m);\n\n\tBOOST_TEST((\n\t\t\tn.cols() == 3_CS &&\n\t\t\tn.rows() == 3_RS &&\n\t\t\tn(0_c, 0_r) == 1 &&\n\t\t\tn(1_c, 0_r) == 0 &&\n\t\t\tn(2_c, 0_r) == 1 &&\n\t\t\tn(0_c, 1_r) == 2 &&\n\t\t\tn(1_c, 1_r) == 3 &&\n\t\t\tn(2_c, 1_r) == 4 &&\n\t\t\tn(0_c, 2_r) == 5 &&\n\t\t\tn(1_c, 2_r) == 6 &&\n\t\t\tn(2_c, 2_r) == 7\n\t));\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "bef1cb59a2ed04be3acd1e9098ceea4372fb11bb", "size": 7739, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/operator.cpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/operator.cpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/operator.cpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.514354067, "max_line_length": 79, "alphanum_fraction": 0.608218116, "num_tokens": 2721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.5862824507842266}}
{"text": "// #define BOOST_TEST_DYN_LINK\n// #define BOOST_TEST_MODULE Suites\n// #include <boost/test/unit_test.hpp>\n\n#include<iostream>\n#include \"basis.hpp\"\n#include \"operators.hpp\"\n#include\"numerics.hpp\"\n#include\"diag.hpp\"\n#include \"files.hpp\"\n// using namespace boost::unit_test;\n// using boost::unit_test_framework::test_suite;\n// using namespace Many_Body;\n// BOOST_AUTO_TEST_SUITE(timeevesting)\n// BOOST_AUTO_TEST_CASE(timeev)\nusing namespace Many_Body;\nusing namespace Eigen;\n  template <typename Matrix>\n    double diag_with_lancz(Eigen::VectorXcd& initialState, const Matrix& ham, const Matrix& obs, size_t lanczosDim)\n  { double sum=0;\n\n    Eigen::VectorXcd initialState2=initialState;\n    Eigen::MatrixXcd Q(ham.rows(), lanczosDim);\n    Many_Body::TriDiagMat tri=Many_Body::Lanczos(ham, initialState2, lanczosDim, Q);\n    Eigen::MatrixXd S(Q.cols(), Q.cols());\n              Eigen::VectorXd eigenVals(Q.cols());\n    Many_Body::diag(tri, S, eigenVals);\n   Eigen::MatrixXcd S2=S.cast<std::complex<double>>();  \n   VectorXcd initialStateTemp(Q.cols());\n    initialStateTemp= (S2.row(0).transpose());\n   //  // initialStateTemp= S2*initialStateTemp;\n   //  // initialState= Q*initialStateTemp;\n   //  assert(std::abs(initialState.norm() -1.) < Many_Body::err);\n     Eigen::MatrixXcd obs2=S.adjoint()*Q.adjoint()*obs*Q*S;\n    for (size_t i = 0; i < lanczosDim; ++i)\n      {\n\t\n      std::complex<double> c=std::abs(initialStateTemp(i))*std::abs(initialStateTemp(i))*obs2(i, i);\n    \t sum+=real(c);\n    }\n    return sum;\n    \n  }\nint main()\n{\n\n    size_t numberOfSteps=5;\n   const size_t L=8;\n   ElectronBasis<L> e(4);\n   size_t D=700;\n   //std::cout << e << std::endl;\n   Eigen::MatrixXcd AA = Eigen::MatrixXcd::Random(D, D);\n   \t Eigen::MatrixXcd H = AA + AA.adjoint();\n   //  Operators::Mat H= Operators::NumberOperator(e)+Operators::EKinOperator(e);\n   // Eigen::VectorXcd inistate(e.D);\n  \n   // inistate.setZero();\n   // inistate[0]=1;\n\t Eigen::VectorXcd inistate=Eigen::VectorXcd::Random(D);\n\t inistate=inistate/inistate.norm();\n   Eigen::VectorXd eigenVals(D);\n   Eigen::MatrixXcd BB = Eigen::MatrixXcd::Random(D, D);\n   \t Eigen::MatrixXcd O = BB + BB.adjoint();\n   // Operators::Mat O(e.dim, e.dim);\n   //  O.setZero();\n   //  O.coeffRef(1, 1)=0.5;\n   //  O.coeffRef(2, 2)=0.5;\n    \n    // HAmiltonian =H\n   Eigen::MatrixXcd HH=Eigen::MatrixXcd(H);\n   // Eigen::MatrixXd HH2=Eigen::MatrixXd(H);\n\n   \n   \n   \n   Many_Body::diag(HH, eigenVals);\nEigen::VectorXcd newIn=inistate;\nEigen::VectorXcd newIn2=inistate;\n  double evalL=diag_with_lancz(newIn2, H, O, 20);\n double evalN=0;\n  MatrixXcd M=HH.adjoint()*O*HH;\n  newIn=HH.adjoint()*newIn;\n  for(size_t i=0; i<D; i++)\n   {\n\n        std::complex<double> c=M(i, i)*std::abs(newIn(i))*std::abs(newIn2(i));\n        evalN+=real(c);\n   }\n   std::cout<< evalN << \"  \" << evalL << \"  \" << D <<std::endl;\n  return 0;\n}\n\n\n//BOOST_AUTO_TEST_SUITE_END()\n// EOF\n", "meta": {"hexsha": "1801f0a977889c504dd47359409aac1ad50079e5", "size": 2899, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testdir/exvalcompare.cpp", "max_stars_repo_name": "jansendavid/many-body-lib", "max_stars_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testdir/exvalcompare.cpp", "max_issues_repo_name": "jansendavid/many-body-lib", "max_issues_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testdir/exvalcompare.cpp", "max_forks_repo_name": "jansendavid/many-body-lib", "max_forks_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1979166667, "max_line_length": 115, "alphanum_fraction": 0.6522938944, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5862197182820098}}
{"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": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// Written by Cornelius Steinhardt\n\n#include <cmath>\n\n// #include <boost/test/minimal.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\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\n\nint main(int, char**)\n{\n\n\n\n  const int N = 2; // Original from Jan had 2000\n  const int Niter = 5000;\n  using itl::pc::identity; using itl::pc::ilu_0; using itl::pc::ic_0; using itl::pc::diagonal;\n  //typedef mtl::dense2D<double> matrix_type;\n  //typedef compressed2D<std::complex<double>mat::parameters<tag::col_major> > matrix_type;\n  typedef mtl::compressed2D<double> matrix_type;\n  matrix_type                   A(N, N);\n  laplacian_setup(A, N, N);\n  mtl::dense_vector<double> b(N*N, 1), x(N*N),r(N*N);\n  identity<matrix_type>         Ident(A);\n  //ic_0<matrix_type>             ic(A);\n  //ilu_0<matrix_type>            ilu(A);\n  //diagonal<matrix_type>         diag(A);\n\n  //test1(A,0.194);\n  std::cout << \"A has \" << A.nnz() << \" non-zero entries\" << std::endl;\n  std::cout << \"A =\\n\"  << A << \" \\n\";\n\n  std::cout << \"Non- preconditioned bicgstab  Won't convergence (for large examples)!\" << std::endl;\n  x= 2.0;\n  itl::basic_iteration<double> iter_0(b, Niter, 1.e-8);\n\n  bicgstab(A, x, b, Ident, iter_0);\n  r= A*x-b;\n\n  std::cout << \"START GMRES  Won't convergence (for large examples)!\" << std::endl;\n  std::cout << \"\\n Non-preconditioned gmres(1)\" << std::endl;\n  x= 5.0;\n  itl::basic_iteration<double> iter_1(b, 1, 1.e-8);\n  gmres(A, x, b, Ident, Ident, iter_1, 1);\n  r= A*x-b;\n  if (two_norm(r) > 0.00005) throw \"gmres doesn't converge\";\n\n  std::cout << \"\\n Non-preconditioned gmres(2) (doesn't converge even for the test)\" << std::endl;\n  x= 2.0;\n  itl::basic_iteration<double> iter_2(b, 8, 1.e-8);\n  gmres(A, x, b, Ident, Ident, iter_2, 2);\n  r= A*x-b;\n  // if (two_norm(r) > 0.00005) throw \"gmres(2) doesn't converge\";\n  if (two_norm(r) > 0.00005) std::cout << \"GMRES(2) didn't converge after 8 titerations.\\n\";\n\n#if 1\n  std::cout << \"\\n Non-preconditioned gmres(4)\" << std::endl;\n  x= 2.5;\n  itl::basic_iteration<double> iter_4(b, 16, 1.e-8);\n  gmres(A, x, b, Ident, Ident,  iter_4, 4);\n  r= A*x-b;\n  // if (two_norm(r) > 0.000001) throw \"gmres(4) doesn't converge even with more iterations and restarts\";\n  if (two_norm(r) > 0.00005) std::cout << \"GMRES(4) didn't converge after 16 titerations.\\n\";\n\n  std::cout << \"\\n Non-preconditioned gmres(4) more iterations \" << std::endl;\n  x= 2.5;\n  itl::basic_iteration<double> iter_5(b, 32, 1.e-8);\n  gmres(A, x, b, Ident, Ident,  iter_5, 4);\n  r= A*x-b;\n  // if (two_norm(r) > 0.00005) throw \"gmres(4) doesn't converge\";\n\n  std::cout << \"\\n Non-preconditioned gmres(8)\" << std::endl;\n  x= 2.5;\n  itl::basic_iteration<double> iter_8(b, 8, 1.e-8);\n  gmres(A, x, b, Ident, Ident, iter_8, 8);\n  r= A*x-b;\n  if (two_norm(r) > 0.00005) throw \"gmres(8) doesn't converge\";\n\n  std::cout << \"\\n Non-preconditioned gmres(16)\" << std::endl;\n  x= 2.5;\n  itl::basic_iteration<double> iter_16(b, 32, 1.e-8);\n  gmres(A, x, b, Ident, Ident, iter_16, 16);\n  r= A*x-b;\n  if (two_norm(r) > 0.00005) throw \"gmres(16) doesn't converge\";\n\n  std::cout << \"\\n Non-preconditioned gmres(32)\" << std::endl;\n  x= 2.5;\n  itl::basic_iteration<double> iter_32(b, 32, 1.e-8);\n  gmres(A, x, b, Ident, Ident, iter_32, 32);\n  r= A*x-b;\n  if (two_norm(r) > 0.00005) throw \"gmres(32) doesn't converge\";\n#endif\n\n  test1(A,0.194);\n  std::cout << \"A has \" << A.nnz() << \" non-zero entries\" << std::endl;\n  std::cout << \"A =\\n\"  << A << \" \\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "30c43e3e0643434709c7417b5bf55ddf966eeaa4", "size": 4292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/gmres_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_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_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 31.3284671533, "max_line_length": 106, "alphanum_fraction": 0.6104380242, "num_tokens": 1542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5861544922304325}}
{"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 * Copyright (C) 2019 by AutoSense Organization. All rights reserved.\n * Gary Chan <chenshj35@mail2.sysu.edu.cn>\n */\n\n#ifndef COMMON_INCLUDE_COMMON_BOUNDING_BOX_HPP_\n#define COMMON_INCLUDE_COMMON_BOUNDING_BOX_HPP_\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include <boost/geometry/geometries/adapted/c_array.hpp>\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\n\n\n#include \"common/common.hpp\"\n#include \"common/types/object.hpp\"\n\nnamespace autosense {\nnamespace common {\nnamespace bbox {\n/*\n *                           |x\n *(x_max,y_max) ---width-----|\n *      |                    |\n *      |                  length\n *      |                    |\n *  y<-----------------(x_min,y_min)\n */\ntypedef struct {\n    double x_max;  // left-top corner\n    double y_max;\n    double x_min;  // right-bottom corner\n    double y_min;\n} BoundingBox;\n\n// Orientation Bounding Box\ntypedef struct {\n    BoundingBox box;\n    double yaw_rad;\n} OBB2;\n\n// Orientation Bounding Box\ntypedef struct {\n    double gc_x, gc_y, gc_z;\n    double yaw_rad;\n    double h, w, l;\n} GroundBox;\n\ntypedef boost::geometry::model::polygon<\n    boost::geometry::model::d2::point_xy<double>>\n    Polygon;\n\n/**\n * @brief Object's 3D OBB to 2D ground box\n * @param object\n * @param gbox\n */\nstatic void toGroundBox(ObjectConstPtr object, GroundBox* gbox) {\n    gbox->gc_x = object->ground_center(0);\n    gbox->gc_y = object->ground_center(1);\n    gbox->gc_z = object->ground_center(2);\n    gbox->yaw_rad = object->yaw_rad;\n    gbox->h = object->height;\n    gbox->w = object->width;\n    gbox->l = object->length;\n}\n\nstatic void toGroundBox(const Eigen::Vector3f& center,\n                        const Eigen::Vector3f& size,\n                        const double& yaw,\n                        GroundBox* gbox) {\n    gbox->gc_x = center(0);\n    gbox->gc_y = center(1);\n    gbox->gc_z = center(2);\n    gbox->yaw_rad = yaw;\n    gbox->h = size(0);\n    gbox->w = size(1);\n    gbox->l = size(2);\n}\n\n/**\n * @brief Intersection-over-Union\n */\nstatic double bbIoU(const BoundingBox& box1, const BoundingBox& box2) {\n    double box1_length = box1.x_max - box1.x_min;\n    double box1_width = box1.y_max - box1.y_min;\n    double area1 = box1_length * box1_width;\n\n    double box2_length = box2.x_max - box2.x_min;\n    double box2_width = box2.y_max - box2.y_min;\n    double area2 = box2_length * box2_width;\n\n    if (box1.x_min > box2.x_max) {\n        return 0.0;\n    }\n    if (box1.y_min > box2.y_max) {\n        return 0.0;\n    }\n    if (box1.x_max < box2.x_min) {\n        return 0.0;\n    }\n    if (box1.y_max < box2.y_min) {\n        return 0.0;\n    }\n    double inter_x =\n        std::min(box1.x_max, box2.x_max) - std::max(box1.x_min, box2.x_min);\n    double inter_y =\n        std::min(box1.x_max, box2.x_max) - std::max(box1.x_min, box2.x_min);\n    double intersection = inter_x * inter_y;\n    return intersection / (area1 + area2 - intersection);\n}\n\n/*\n * @brief compute polygon of an oriented bounding box\n * @note Apollo's Object Coordinate\n *          |x\n *      C   |   D-----------\n *          |              |\n *  y---------------     length\n *          |              |\n *      B   |   A-----------\n */\ntemplate <typename T>\nPolygon toPolygon(const T& g) {\n    using boost::numeric::ublas::matrix;\n    matrix<double> mref(2, 2);\n    mref(0, 0) = cos(g.yaw_rad);\n    mref(0, 1) = -sin(g.yaw_rad);\n    mref(1, 0) = sin(g.yaw_rad);\n    mref(1, 1) = cos(g.yaw_rad);\n\n    matrix<double> corners(2, 4);\n    // -------------(l/2,w/2)(l/2,-w/2)(-l/2,-w/2)(-l/2,w/2)\n    double data[] = {g.l / 2, g.l / 2,  -g.l / 2, -g.l / 2,\n                     g.w / 2, -g.w / 2, -g.w / 2, g.w / 2};\n    std::copy(data, data + 8, corners.data().begin());\n    matrix<double> gc = boost::numeric::ublas::prod(mref, corners);\n\n    for (int i = 0; i < 4; ++i) {\n        gc(0, i) += g.gc_x;\n        gc(1, i) += g.gc_y;\n    }\n\n    double points[][2] = {{gc(0, 0), gc(1, 0)},\n                          {gc(0, 1), gc(1, 1)},\n                          {gc(0, 2), gc(1, 2)},\n                          {gc(0, 3), gc(1, 3)},\n                          {gc(0, 0), gc(1, 0)}};\n    Polygon poly;\n    boost::geometry::append(poly, points);\n    return poly;\n}\n\n/**\n * @brief Intersection-over-Union\n */\nstatic double groundBoxIoU(const GroundBox& box1, const GroundBox& box2) {\n    Polygon gp = toPolygon(box1);\n    Polygon dp = toPolygon(box2);\n\n    std::vector<Polygon> in, un;\n    boost::geometry::intersection(gp, dp, in);\n    boost::geometry::union_(gp, dp, un);\n\n    double inter_area = in.empty() ? 0. : boost::geometry::area(in.front());\n    double union_area = boost::geometry::area(un.front());\n\n    double o = 0.;\n    // union\n    o = inter_area / union_area;\n    // bbox_a\n    // o = inter_area / area(dp);\n    // bbox_b\n    // o = inter_area / area(gp);\n    return o;\n}\n\nstatic bool groundBoxInside(const GroundBox& box1, const GroundBox& box2) {\n    Polygon gp = toPolygon(box1);\n    Polygon dp = toPolygon(box2);\n\n    std::vector<Polygon> in;\n    boost::geometry::intersection(gp, dp, in);\n    if (in.empty()) {\n        return false;\n    } else {\n        double inter_area = boost::geometry::area(in.front());\n        double box1_area = boost::geometry::area(gp);\n        return abs(box1_area - inter_area) < EPSILON;\n    }\n}\n\n/**\n * @brief check box1 is overlapping with box2\n *  true: box1 is inside box2 or box2 is inside box1\n *  true: IoU between box1 and box2 > threshold_IoU\n * @param box1\n * @param box2\n * @param threshold_IoU\n * @return\n */\nstatic bool groundBoxOverlap(const GroundBox& box1,\n                             const GroundBox& box2,\n                             double threshold_IoU) {\n    if (groundBoxInside(box1, box2) || groundBoxInside(box2, box1)) {\n        return true;\n    }\n\n    if (groundBoxIoU(box1, box2) > threshold_IoU) {\n        return true;\n    }\n\n    return false;\n}\n\n/**\n * @brief predict object size and ground center based on object cloud and\n * previous direction\n * @tparam PointT\n * @param cloud\n * @param direction\n * @param size\n * @param center\n */\ntemplate <typename PointCloudPtrT>\nvoid computeBboxSizeCenter(PointCloudPtrT cloud,\n                           const Eigen::Vector3d& direction,\n                           Eigen::Vector3d* size,\n                           Eigen::Vector3d* center) {\n    Eigen::Vector3d dir(direction[0], direction[1], 0);\n    dir.normalize();\n    Eigen::Vector3d ortho_dir(-dir[1], dir[0], 0.0);\n\n    Eigen::Vector3d z_dir(dir.cross(ortho_dir));\n\n    Eigen::Vector3d min_pt(DBL_MAX, DBL_MAX, DBL_MAX);\n    Eigen::Vector3d max_pt(-DBL_MAX, -DBL_MAX, -DBL_MAX);\n    Eigen::Vector3d loc_pt;\n    for (size_t i = 0u; i < cloud->size(); ++i) {\n        Eigen::Vector3d pt = Eigen::Vector3d(\n            cloud->points[i].x, cloud->points[i].y, cloud->points[i].z);\n        loc_pt[0] = pt.dot(dir);\n        loc_pt[1] = pt.dot(ortho_dir);\n        loc_pt[2] = pt.dot(z_dir);\n        for (size_t j = 0u; j < 3; ++j) {\n            min_pt[j] = std::min(min_pt[j], loc_pt[j]);\n            max_pt[j] = std::max(max_pt[j], loc_pt[j]);\n        }\n    }\n\n    *size = max_pt - min_pt;\n    *center = dir * ((max_pt[0] + min_pt[0]) * 0.5) +\n              ortho_dir * ((max_pt[1] + min_pt[1]) * 0.5) + z_dir * min_pt[2];\n}\n\n}  // namespace bbox\n}  // namespace common\n}  // namespace autosense\n\n#endif  // COMMON_INCLUDE_COMMON_BOUNDING_BOX_HPP_\n", "meta": {"hexsha": "f63bf7e76bd4c5c9b314b2cd4b61d5c0a457c165", "size": 7548, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "LetsGo/ThirdParty/ObjectBuilder/Includes/common/bounding_box.hpp", "max_stars_repo_name": "wis1906/letsgo-ar-space-generation", "max_stars_repo_head_hexsha": "02d888a44bb9eb112f308356ab42720529349338", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LetsGo/ThirdParty/ObjectBuilder/Includes/common/bounding_box.hpp", "max_issues_repo_name": "wis1906/letsgo-ar-space-generation", "max_issues_repo_head_hexsha": "02d888a44bb9eb112f308356ab42720529349338", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LetsGo/ThirdParty/ObjectBuilder/Includes/common/bounding_box.hpp", "max_forks_repo_name": "wis1906/letsgo-ar-space-generation", "max_forks_repo_head_hexsha": "02d888a44bb9eb112f308356ab42720529349338", "max_forks_repo_licenses": ["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.9555555556, "max_line_length": 78, "alphanum_fraction": 0.5751192369, "num_tokens": 2241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359878, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5860916741197951}}
{"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": "// Copyright (c) 2015 Pierre MOULON.\r\n\r\n// This Source Code Form is subject to the terms of the Mozilla Public\r\n// License, v. 2.0. If a copy of the MPL was not distributed with this\r\n// file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#ifndef I23DSFM_GEOMETRY_HALF_SPACE_HPP_\r\n#define I23DSFM_GEOMETRY_HALF_SPACE_HPP_\r\n\r\n#include \"i23dSFM/linearProgramming/linearProgrammingOSI_X.hpp\"\r\n#include <Eigen/Geometry>\r\n#include <Eigen/StdVector>\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::Hyperplane<double,3>)\n\r\nnamespace i23dSFM {\r\nnamespace geometry {\r\nnamespace halfPlane {\r\n\r\n/// Define the Half_plane equation (abcd coefficients)\r\ntypedef Eigen::Hyperplane<double,3> Half_plane;\r\n/// Define a collection of Half_plane\r\ntypedef std::vector<Half_plane> Half_planes;\r\n\r\n// Define a plane passing through the points (p, q, r).\r\n// The plane is oriented such that p, q and r are oriented in a positive sense (that is counterclockwise).\r\nstatic Half_plane Half_plane_p(const Vec3 & p, const Vec3 & q, const Vec3 & r)\r\n{\r\n  const Vec3 abc = (p-r).cross(q-r);\r\n  const double d = - abc.dot(r);\r\n  Half_plane hp;\r\n  hp.coeffs() << abc(0),abc(1),abc(2),d;\r\n  return hp;\r\n}\r\n\r\n// [1] Paper: Finding the intersection of n half-spaces in time O(n log n).\r\n// Author: F.P. Preparata, D.E. Muller\r\n// Published in: Theoretical Computer Science, Volume 8, Issue 1, Pages 45-55\r\n// Year: 1979\r\n// More: ISSN 0304-3975, http://dx.doi.org/10.1016/0304-3975(79)90055-0.\r\n\r\n\r\n/// Return true if the half_planes define a not empty volume (an intersection exists)\r\nstatic bool isNotEmpty(const Half_planes & hplanes)\r\n{\r\n  // Check if it exists a point on all positive side of the half plane thanks to a Linear Program formulation [1].\r\n  // => If a point exists: there is a common subspace defined and so intersections.\r\n  // The LP formulation consists in set the Half_plane as constraint and check if a point can fit the equations.\r\n\r\n  using namespace i23dSFM;\r\n  using namespace i23dSFM::linearProgramming;\r\n\r\n  LP_Constraints cstraint;\r\n  {\r\n    cstraint._nbParams = 3; // {X,Y,Z}\r\n    cstraint._vec_bounds.resize(cstraint._nbParams);\r\n    std::fill(cstraint._vec_bounds.begin(),cstraint._vec_bounds.end(),\r\n      std::make_pair((double)-1e+30, (double)1e+30)); // [X,Y,Z] => -inf, +inf\r\n    cstraint._bminimize = true;\r\n\r\n    // Configure constraints\r\n    const size_t nbConstraints = hplanes.size();\r\n    cstraint._constraintMat = Mat(nbConstraints,3);\r\n    cstraint._vec_sign.resize(nbConstraints);\r\n    cstraint._Cst_objective = Vec(nbConstraints);\r\n\r\n    // Fill the constrains (half-space equations)\r\n    for (unsigned char i= 0; i < hplanes.size(); ++i)\r\n    {\r\n      const Vec & half_plane_coeff = hplanes[i].coeffs();\r\n      // add the half plane equation to the system\r\n      cstraint._constraintMat.row(i) =\r\n        Vec3(half_plane_coeff(0),\r\n          half_plane_coeff(1),\r\n          half_plane_coeff(2));\r\n      cstraint._vec_sign[i] = LP_Constraints::LP_GREATER_OR_EQUAL;\r\n      cstraint._Cst_objective(i) = - half_plane_coeff(3);\r\n    }\r\n  }\r\n\r\n  // Solve in order to see if a point exists within the half spaces positive side?\r\n  OSI_CLP_SolverWrapper solver(cstraint._nbParams);\r\n  solver.setup(cstraint);\r\n  const bool bIntersect = solver.solve(); // Status of the solver tell if there is an intersection or not\r\n  return bIntersect;\r\n}\r\n\r\n} // namespace geometry\r\n} // namespace i23dSFM\r\n} // namespace halfPlane\r\n\r\n#endif // I23DSFM_GEOMETRY_HALF_SPACE_HPP_\r\n", "meta": {"hexsha": "54f0a1eb7016d7082f69c86efc78789fcadc62c1", "size": 3478, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "i23dSFM/geometry/half_space_intersection.hpp", "max_stars_repo_name": "zyxrrr/GraphSfM", "max_stars_repo_head_hexsha": "1af22ec17950ffc8a5c737a6a46f4465c40aa470", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "i23dSFM/geometry/half_space_intersection.hpp", "max_issues_repo_name": "zyxrrr/GraphSfM", "max_issues_repo_head_hexsha": "1af22ec17950ffc8a5c737a6a46f4465c40aa470", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "i23dSFM/geometry/half_space_intersection.hpp", "max_forks_repo_name": "zyxrrr/GraphSfM", "max_forks_repo_head_hexsha": "1af22ec17950ffc8a5c737a6a46f4465c40aa470", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-18T09:49:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-18T09:49:32.000Z", "avg_line_length": 37.8043478261, "max_line_length": 115, "alphanum_fraction": 0.7032777458, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5859645020576641}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\n#include \"../../../../util/Maybe.hh\"\n\n#include \"../../../Bounds.hh\"\n#include \"../linesegment2.hh\"\n\nnamespace bold\n{\n  class Line;\n\n  struct LineSegment2i : public LineSegment2<int>\n  {\n  public:\n    LineSegment2i(Eigen::Matrix<int, 2, 1> const& p1, Eigen::Matrix<int, 2, 1> const& p2)\n    : LineSegment2<int>::LineSegment2(p1, p2)\n    {}\n\n    LineSegment2i(int x1, int y1, int x2, int y2)\n    : LineSegment2<int>::LineSegment2(Point(x1, y1), Point(x2, y2))\n    {}\n\n    using LineSegment2<int>::LineSegment2;\n    using LineSegment2<int>::operator=;\n\n    double gradient() const;\n\n    double yIntersection() const;\n\n    /** Returns the angle of this line to the +ve x-azis, in the range [-pi, pi] */\n    double angle() const;\n\n    Maybe<LineSegment2i> cropTo(Bounds2i const& bounds) const;\n  };\n}\n", "meta": {"hexsha": "fbd6266820f03619eaf4e0643c33ce85b072af64", "size": 832, "ext": "hh", "lang": "C++", "max_stars_repo_path": "geometry/LineSegment/LineSegment2/LineSegment2i/linesegment2i.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geometry/LineSegment/LineSegment2/LineSegment2i/linesegment2i.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry/LineSegment/LineSegment2/LineSegment2i/linesegment2i.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8947368421, "max_line_length": 89, "alphanum_fraction": 0.6418269231, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7341195210831258, "lm_q1q2_score": 0.585964502057664}}
{"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 \"difference_of_squares.h\"\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(squares_of_sums)\n{\n    BOOST_REQUIRE_EQUAL(225, squares::square_of_sums(5));\n    BOOST_REQUIRE_EQUAL(3025, squares::square_of_sums(10));\n    BOOST_REQUIRE_EQUAL(25502500, squares::square_of_sums(100));\n}\n\nBOOST_AUTO_TEST_CASE(sum_of_squares)\n{\n    BOOST_REQUIRE_EQUAL(55, squares::sum_of_squares(5));\n    BOOST_REQUIRE_EQUAL(385, squares::sum_of_squares(10));\n    BOOST_REQUIRE_EQUAL(338350, squares::sum_of_squares(100));\n}\n\nBOOST_AUTO_TEST_CASE(up_to_5)\n{\n    BOOST_REQUIRE_EQUAL(225, squares::square_of_sums(5));\n    BOOST_REQUIRE_EQUAL(55, squares::sum_of_squares(5));\n    BOOST_REQUIRE_EQUAL(170, squares::difference(5));\n}\n\nBOOST_AUTO_TEST_CASE(up_to_10)\n{\n    BOOST_REQUIRE_EQUAL(3025, squares::square_of_sums(10));\n    BOOST_REQUIRE_EQUAL(385, squares::sum_of_squares(10));\n    BOOST_REQUIRE_EQUAL(2640, squares::difference(10));\n}\n\nBOOST_AUTO_TEST_CASE(up_to_100)\n{\n    BOOST_REQUIRE_EQUAL(25502500, squares::square_of_sums(100));\n    BOOST_REQUIRE_EQUAL(338350, squares::sum_of_squares(100));\n    BOOST_REQUIRE_EQUAL(25164150, squares::difference(100));\n}\n#if defined(EXERCISM_RUN_ALL_TESTS)\n#endif\n", "meta": {"hexsha": "66dc326d1d83f9e81483c1dcd7432e1d2318c9ad", "size": 1226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "difference-of-squares/difference_of_squares_test.cpp", "max_stars_repo_name": "mapa17/Exercism-cpp", "max_stars_repo_head_hexsha": "6f61c33dbe96c1e580d5b98bfc36ca2f59adea60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "difference-of-squares/difference_of_squares_test.cpp", "max_issues_repo_name": "mapa17/Exercism-cpp", "max_issues_repo_head_hexsha": "6f61c33dbe96c1e580d5b98bfc36ca2f59adea60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "difference-of-squares/difference_of_squares_test.cpp", "max_forks_repo_name": "mapa17/Exercism-cpp", "max_forks_repo_head_hexsha": "6f61c33dbe96c1e580d5b98bfc36ca2f59adea60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9024390244, "max_line_length": 64, "alphanum_fraction": 0.7765089723, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.798186787341014, "lm_q1q2_score": 0.5859644974145658}}
{"text": "/***************************************************************************\n/* Javier Juan Albarracin - jajuaal1@ibime.upv.es                         */\n/* Universidad Politecnica de Valencia, Spain                             */\n/*                                                                        */\n/* Copyright (C) 2018 Javier Juan Albarracin                              */\n/*                                                                        */\n/***************************************************************************\n* Eigen <-> CImg data type conversions                                     *\n***************************************************************************/\n\n#ifndef EIGENCIMG_HPP\n#define EIGENCIMG_HPP\n\n#define cimg_display 0\n#include <CImg.h>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n#include <stdexcept>\n\n#define __STR_FUNCNAME__  std::string(__FUNCTION__)\n\nusing namespace cimg_library;\nusing namespace Eigen;\n\nclass EigenCImg\n{\npublic:\n    template <typename T>\n    static Matrix<T, Dynamic, Dynamic> toEigen(const CImg<T> &image);\n    template <typename T>\n    static Matrix<T, Dynamic, Dynamic> toEigen(const CImg<T> &image, const CImg<bool> &mask);\n    template <class Derived>\n    static CImg<typename Derived::Scalar> toCImg(const DenseBase<Derived> &data, const CImg<bool> &mask);\n    template<typename T, int Dimensions>\n    static CImg<T> toCImg(const Tensor<T, Dimensions> &data, const CImg<bool> &mask);\n};\n\n\ntemplate <typename T>\nMatrix<T, Dynamic, Dynamic> EigenCImg::toEigen(const CImg<T> &image)\n{\n    int i = 0;\n    Matrix<T, Dynamic, Dynamic> data(image.width() * image.height() * image.depth(), image.spectrum());\n    for (int x = 0; x < image.width(); ++x)\n    {\n        for (int y = 0; y < image.height(); ++y)\n        {\n            for (int z = 0; z < image.depth(); ++z)\n            {\n                for (int c = 0; c < image.spectrum(); ++c)\n                    data(i, c) = (T) image(x, y, z, c);\n                ++i;\n            }\n        }\n    }\n    return data;\n}\n\ntemplate <typename T>\nMatrix<T, Dynamic, Dynamic> EigenCImg::toEigen(const CImg<T> &image, const CImg<bool> &mask)\n{\n    if (image.height() != mask.height() || image.width() != mask.width() || image.depth() != mask.depth())\n    {\n        std::stringstream s;\n        s << \"In function \" << __STR_FUNCNAME__ << \" ==> Image and mask dimensions must agree.\" << std::endl;\n        throw std::runtime_error(s.str());\n    }\n    \n    int i = 0;\n    Matrix<T, Dynamic, Dynamic> data(mask.size(), image.spectrum());\n    for (int x = 0; x < image.width(); ++x)\n    {\n        for (int y = 0; y < image.height(); ++y)\n        {\n            for (int z = 0; z < image.depth(); ++z)\n            {\n                if (!mask(x, y, z))\n                    continue;\n                \n                for (int c = 0; c < image.spectrum(); ++c)\n                    data(i, c) = (T) image(x, y, z, c);\n                ++i;\n            }\n        }\n    }\n    data.conservativeResize(i, data.cols());\n    return data;\n}\n\ntemplate <class Derived>\nCImg<typename Derived::Scalar> EigenCImg::toCImg(const DenseBase<Derived> &data, const CImg<bool> &mask)\n{\n    if (mask.sum() != data.rows())\n    {\n        std::stringstream s;\n        s << \"In function \" << __STR_FUNCNAME__ << \" ==> Number of positive mask elements must agree with data rows.\" << std::endl;\n        throw std::runtime_error(s.str());\n    }\n    \n    int i = 0;\n    CImg<typename Derived::Scalar> image(mask.width(), mask.height(), mask.depth(), data.cols());\n    for (int x = 0; x < image.width(); ++x)\n    {\n        for (int y = 0; y < image.height(); ++y)\n        {\n            for (int z = 0; z < image.depth(); ++z)\n            {\n                if (!mask(x, y, z))\n                {\n                    for (int c = 0; c < data.cols(); ++c)\n                        image(x, y, z, c) = (typename Derived::Scalar) 0;\n                }\n                else\n                {\n                    for (int c = 0; c < data.cols(); ++c)\n                        image(x, y, z, c) = (typename Derived::Scalar) data(i, c);\n                    ++i;\n                }\n            }\n        }\n    }\n    return image;\n}\n\ntemplate<typename T, int Dimensions>\nCImg<T> EigenCImg::toCImg(const Tensor<T, Dimensions> &data, const CImg<bool> &mask)\n{\n    if (mask.sum() != (int) data.dimension(0))\n    {\n        std::stringstream s;\n        s << \"In function \" << __STR_FUNCNAME__ << \" ==> Number of positive mask elements must agree with data rows.\" << std::endl;\n        throw std::runtime_error(s.str());\n    }\n    \n    const int K = data.dimension(Dimensions - 1);\n    \n    typename Eigen::Tensor<T, Dimensions-2>::Dimensions dims;\n    for (int i = 0; i < Dimensions - 2; ++i)\n        dims[i] = i + 1;\n    \n    Eigen::Tensor<T, 2> dataReduced = data.sum(dims);\n    \n    int i = 0;\n    CImg<T> image(mask.width(), mask.height(), mask.depth(), K);\n    for (int x = 0; x < image.width(); ++x)\n    {\n        for (int y = 0; y < image.height(); ++y)\n        {\n            for (int z = 0; z < image.depth(); ++z)\n            {\n                if (!mask(x, y, z))\n                {\n                    for (int c = 0; c < K; ++c)\n                        image(x, y, z, c) = (T) 0;\n                }\n                else\n                {\n                    for (int c = 0; c < K; ++c)\n                        image(x, y, z, c) = (T) dataReduced(i, c);\n                    ++i;\n                }\n            }\n        }\n    }\n    return image;\n}\n\n#endif", "meta": {"hexsha": "2e8a0f050bf102a82f884f557d453cd2cd1ef19c", "size": 5529, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "EigenCImg.hpp", "max_stars_repo_name": "javierjuan/tools", "max_stars_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EigenCImg.hpp", "max_issues_repo_name": "javierjuan/tools", "max_issues_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EigenCImg.hpp", "max_forks_repo_name": "javierjuan/tools", "max_forks_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_forks_repo_licenses": ["Apache-2.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.9107142857, "max_line_length": 131, "alphanum_fraction": 0.4546934346, "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5859493612601627}}
{"text": "#include <Eigen/Dense>\n#include <stdio.h>\n#include <math.h>\n#include <omp.h>\n#include \"mvnormal.h\"\nextern \"C\" {\n#include <sparse.h>\n}\n\nextern \"C\" void dsyrk_(char *uplo, char *trans, int *m, int *n, double *alpha, double a[],\n            int *lda, double *beta, double c[], int *ldc);\n\nusing namespace Eigen;\n\nvoid hello(double* x, double* y, int n, int k) {\n  //cblas_dsyrk(CblasColMajor, CblasLower, CblasTrans, n, k, 1.0, x, k, 0.0, y, n);\n  char lower  = 'L';\n  char trans  = 'T';\n  double one  = 1.0;\n  double zero = 0.0;\n  dsyrk_(&lower, &trans, &n, &k, &one, x, &k, &zero, y, &n);\n}\n\nvoid eigenQR(double* x, int nrow, int ncol) {\n  MatrixXd X = Map<MatrixXd>(x, nrow, ncol);\n  HouseholderQR<MatrixXd> qr(X);\n  MatrixXd Q = qr.householderQ();\n  printf(\"Q(0,0) = %f\\n\", Q(0,0));\n}\n\nMatrixXd getx() {\n  init_bmrng(100099102);\n  MatrixXd x(1000,10);\n  bmrandn(x);\n  return x;\n}\n\n/** x is [n x k] matrix\n *  y is [n x n] matrix\n *  x and y are column-ordered\n *  computes y = x * x'\n *  (storing only lower triangular part)\n */\nvoid hello2(double* x, double* y, int n, int k) {\n  if (n >= 256) {\n    // probably broken\n    //cblas_dsyrk(CblasColMajor, CblasLower, CblasNoTrans, n, k, 1.0, x, k, 0.0, y, n);\n    char lower  = 'L';\n    char trans  = 'N';\n    double one  = 1.0;\n    double zero = 0.0;\n    dsyrk_(&lower, &trans, &n, &k, &one, x, &n, &zero, y, &n);\n    return;\n  }\n  int nthreads = -1;\n#pragma omp parallel\n  {\n#pragma omp single\n    {\n      nthreads = omp_get_num_threads();\n    }\n  }\n  std::vector<MatrixXd> Ys;\n  Ys.resize(nthreads, MatrixXd(n, n));\n\n#pragma omp parallel\n  {\n    const int ithread  = omp_get_thread_num();\n    int rows_per_thread = (int) 8 * ceil(k / 8.0 / nthreads);\n    int row_start = rows_per_thread * ithread;\n    int row_end   = rows_per_thread * (ithread + 1);\n    if (row_end > k) {\n      row_end = k;\n    }\n    double* xi = & x[ row_start * n ];\n    int nrows  = row_end - row_start;\n    MatrixXd X = Map<MatrixXd>(xi, n, nrows);\n    MatrixXd & Y = Ys[ithread];\n    Y.triangularView<Eigen::Lower>() = X * X.transpose();\n  }\n  for (int i = 0; i < n; i++) {\n    for (int j = i; j < n; j++) {\n      double tmp = 0;\n      for (int k = 0; k < nthreads; k++) {\n        tmp += Ys[k](j, i);\n      }\n      y[i*n + j] = tmp;\n    }\n  }\n}\n\nvoid At_mul_A_eig(Eigen::MatrixXd & A, Eigen::MatrixXd & C) {\n  const int n = A.cols();\n  if (n != C.rows()) { printf(\"A.cols() must equal C.rows().\"); exit(1); }\n  if (C.rows() != C.cols()) { printf(\"C.rows() must equal C.cols().\"); exit(1); }\n  C.triangularView<Eigen::Lower>() = A.transpose() * A;\n}\n", "meta": {"hexsha": "73b0221782899411d163c6f0664d48d26b583807", "size": 2575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/macau-cpp/hello.cpp", "max_stars_repo_name": "edebrouwer/macau", "max_stars_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2016-02-27T22:18:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:17:39.000Z", "max_issues_repo_path": "lib/macau-cpp/hello.cpp", "max_issues_repo_name": "edebrouwer/macau", "max_issues_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-05-23T14:14:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T08:12:40.000Z", "max_forks_repo_path": "lib/macau-cpp/hello.cpp", "max_forks_repo_name": "edebrouwer/macau", "max_forks_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T12:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T15:05:59.000Z", "avg_line_length": 26.2755102041, "max_line_length": 90, "alphanum_fraction": 0.5677669903, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6926419958239133, "lm_q1q2_score": 0.58593526889027}}
{"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 << \"\u4e00\u5171\u627e\u5230\u4e86\" << matches.size() << \"\u7ec4\u5339\u914d\u70b9\" << endl;\n\n\n  Mat d1 = imread(f3, CV_LOAD_IMAGE_UNCHANGED);\n  Mat K = (Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n  vector<Point3f> pts_3d;\n  vector<Point2f> pts_2d;\n  for (DMatch m:matches) {\n    ushort d = d1.ptr<unsigned short>(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)];\n    if (d == 0)   // bad depth\n      continue;\n    float dd = d / 5000.0;\n    Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n    pts_3d.push_back(Point3f(p1.x * dd, p1.y * dd, dd));\n    pts_2d.push_back(keypoints_2[m.trainIdx].pt);\n  }\n\n  cout << \"3d-2d pairs: \" << pts_3d.size() << endl;\n\n  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n  Mat r, t;\n  solvePnP(pts_3d, pts_2d, K, Mat(), r, t, false);\n  Mat R;\n  cv::Rodrigues(r, R);\n  chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n  chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"solve pnp in opencv cost time: \" << time_used.count() << \" seconds.\" << endl;\n\n  cout << \"R=\" << endl << R << endl;\n  cout << \"t=\" << endl << t << endl;\n\n\n\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": "#ifndef CORE_QUAT_HPP\n#define CORE_QUAT_HPP\n\n#include <core/real.hpp>\n\n#include <Eigen/Geometry>\n\n// a unit quaternion\ntemplate<class U>\nclass quaternion : public Eigen::Quaternion<U, Eigen::DontAlign> {\n  using base = typename quaternion::Quaternion;\npublic:\n\n  using base::Quaternion::Quaternion;\n\n  \n  quaternion() {\n    base::setIdentity();\n  }\n\n\n  static constexpr U epsilon = std::numeric_limits<U>::epsilon();\n\n  \n  static quaternion exp(const vector<3, U>& omega) {\n    const U theta = omega.norm();\n\n    quaternion res;\n\n    if(theta < epsilon) {\n      res.vec() = omega;\n      res.normalize();\n    } else {\n      const U half_theta = theta / 2;\n      res.w() = std::cos(half_theta);\n      res.vec() = (std::sin(half_theta) / theta) * omega;\n    }\n    \n    return res;\n  }\n\n\n  vector<3, U> log() const {\n    quaternion q;\n\n    if(this->w() < 0) {\n      q = - *this;\n    } else {\n      q = *this;\n    }\n\n    const U half_theta = std::acos( std::min(q.w(), 1.0) );\n\n    if(half_theta < epsilon) {\n      return (q / q.w()).vec();\n    } else {\n      const U theta = 2 * theta;\n      return q.vec() * ( theta / std::sin(half_theta));\n    }\n    \n  }\n\n};\n\n\nusing quat = quaternion<real>;\n\n\n#endif\n", "meta": {"hexsha": "81da5e89bc9ccd2a4bd63cf64938ef6d9256692b", "size": 1199, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pouf/core/quat.hpp", "max_stars_repo_name": "maxime-tournier/cpp", "max_stars_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pouf/core/quat.hpp", "max_issues_repo_name": "maxime-tournier/cpp", "max_issues_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pouf/core/quat.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.1285714286, "max_line_length": 66, "alphanum_fraction": 0.5738115096, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5859120696484396}}
{"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": "// Copyright Stephan T. Lavavej, http://nuwen.net .\n// Distributed under the Boost Software License, Version 1.0.\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://boost.org/LICENSE_1_0.txt .\n\n#ifndef PHAM_FIBONACCI_HH\n#define PHAM_FIBONACCI_HH\n\n#include \"compiler.hh\"\n\n#ifdef NUWEN_PLATFORM_MSVC\n    #pragma once\n#endif\n\n#include \"static_assert_private.hh\"\n#include \"typedef.hh\"\n#include \"vector.hh\"\n\n#include \"external_begin.hh\"\n    #include <stdexcept>\n    #include <vector>\n    #include <boost/type_traits.hpp>\n#include \"external_end.hh\"\n\nnamespace nuwen {\n    template <typename C> vuc_t fibonacci_encode(const C& c);\n    template <typename T> std::vector<T> fibonacci_decode(const vuc_t& v);\n}\n\nnamespace pham {\n    template <typename T> const std::vector<T>& fib_seq() {\n        PHAM_STATIC_ASSERT((\n               boost::is_same<T, nuwen::uc_t >::value\n            || boost::is_same<T, nuwen::us_t >::value\n            || boost::is_same<T, nuwen::ul_t >::value\n            || boost::is_same<T, nuwen::ull_t>::value));\n\n        static std::vector<T> s_fib;\n\n        if (s_fib.empty()) {\n            for (T a = 0, b = 1, c = 1; c >= b; a = b, b = c, c = static_cast<T>(a + b)) {\n                s_fib.push_back(c);\n            }\n        }\n\n        return s_fib;\n    }\n\n    template <typename T> void fib_encode(const std::vector<T>& fib, nuwen::pack::packed_bits& pb, T n) {\n        if (n == 0) {\n            throw std::logic_error(\"LOGIC ERROR: pham::fib_encode() - Cannot encode a zero.\");\n        }\n\n        nuwen::db_t d(1, 1);\n\n        typename std::vector<T>::const_iterator j = fib.end() - 1;\n\n        while (*j > n) {\n            --j;\n        }\n\n        while (true) {\n            if (n >= *j) {\n                n = static_cast<T>(n - *j);\n                d.push_front(1);\n            } else {\n                d.push_front(0);\n            }\n\n            if (j == fib.begin()) {\n                break;\n            } else {\n                --j;\n            }\n        }\n\n        for (nuwen::db_ci_t i = d.begin(); i != d.end(); ++i) {\n            pb.push_back(*i);\n        }\n    }\n}\n\ntemplate <typename C> nuwen::vuc_t nuwen::fibonacci_encode(const C& c) {\n    typedef typename C::value_type T;\n\n    const std::vector<T>& fib = pham::fib_seq<T>();\n    pack::packed_bits pb;\n\n    for (typename C::const_iterator i = c.begin(); i != c.end(); ++i) {\n        pham::fib_encode(fib, pb, *i);\n    }\n\n    return pb.vuc();\n}\n\ntemplate <typename T> std::vector<T> nuwen::fibonacci_decode(const vuc_t& v) {\n    const std::vector<T>& fib = pham::fib_seq<T>();\n\n    std::vector<T> ret;\n    T n = 0;\n    typename std::vector<T>::const_iterator j = fib.begin();\n\n    for (ull_t i = 0; i < v.size() * 8; ++i) {\n        if (n != 0 && bit_from_vuc(v, i - 1) == 1 && bit_from_vuc(v, i) == 1) {\n            ret.push_back(n);\n            n = 0;\n            j = fib.begin();\n        } else if (j == fib.end()) {\n            throw std::runtime_error(\"RUNTIME ERROR: nuwen::fibonacci_decode() - Codeword contains too many bits.\");\n        } else if (bit_from_vuc(v, i) == 1) {\n            const T t = static_cast<T>(n + *j);\n\n            if (t < n) {\n                throw std::runtime_error(\"RUNTIME ERROR: nuwen::fibonacci_decode() - Codeword overflows T.\");\n            }\n\n            n = t;\n            ++j;\n        } else {\n            ++j;\n        }\n    }\n\n    if (n != 0) {\n        throw std::runtime_error(\"RUNTIME ERROR: nuwen::fibonacci_decode() - Padding contains ones.\");\n    }\n\n    if (j - fib.begin() > 7) {\n        throw std::runtime_error(\"RUNTIME ERROR: nuwen::fibonacci_decode() - Padding contains too many zeros.\");\n    }\n\n    return ret;\n}\n\n#endif // Idempotency\n", "meta": {"hexsha": "8d606b3227dff9ebed288be2cb0d65dead5d6e88", "size": 3682, "ext": "hh", "lang": "C++", "max_stars_repo_path": "fibonacci.hh", "max_stars_repo_name": "nurettin/libnuwen", "max_stars_repo_head_hexsha": "5b3012d9e75552c372a4d09b218b7af04a928e68", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-09-17T10:33:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T10:03:42.000Z", "max_issues_repo_path": "fibonacci.hh", "max_issues_repo_name": "nurettin/libnuwen", "max_issues_repo_head_hexsha": "5b3012d9e75552c372a4d09b218b7af04a928e68", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fibonacci.hh", "max_forks_repo_name": "nurettin/libnuwen", "max_forks_repo_head_hexsha": "5b3012d9e75552c372a4d09b218b7af04a928e68", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-05T04:31:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-05T04:31:22.000Z", "avg_line_length": 27.0735294118, "max_line_length": 116, "alphanum_fraction": 0.5285171103, "num_tokens": 1034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571774, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5858899082918572}}
{"text": "// Algolab BGL Tutorial 2 (Max flow, by taubnert@ethz.ch)\n// Flow example demonstrating how to use push_relabel_max_flow using a custom edge adder\n// to manage the interior graph properties required for flow algorithms\n#include <iostream>\n\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\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// 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 n, m;\n  cin >> n; cin >> m;\n  graph G(n + m);\n  edge_adder adder(G);\n  \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  for(int i = 0; i < m; i++) {\n    adder.add_edge(v_source, i, 1); // from, to, capacity\n    int a, b, c;\n    cin >> a; cin >> b; cin >> c;\n    if(c == 1) {\n      adder.add_edge(i, m + a, 1); // from, to, capacity  \n    } else if(c == 2) {\n      adder.add_edge(i, m + b, 1); // from, to, capacity\n    } else {\n      adder.add_edge(i, m + a, 1); // from, to, capacity\n      adder.add_edge(i, m + b, 1); // from, to, capacity\n    }\n  }\n\n  int sum_s = 0;\n  for(int i = 0; i < n; i++) {\n    int si; cin >> si;\n    adder.add_edge(m + i, v_sink, si);\n    sum_s += si;\n  }\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  \n  if(flow == sum_s && flow == m) {\n    std::cout << \"yes\" << \"\\n\";\n  } else {\n    std::cout << \"no\" << \"\\n\";\n  }\n}\n\nint main() {\n  std::ios_base::sync_with_stdio(false); // Always!\n  int t; cin >> t;\n  while(t--) make_it_flow();\n  return 0;\n}\n", "meta": {"hexsha": "1d483868140d689df95a82b3f672c5d0400b08bb", "size": 2832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week07-coin_tossing/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-coin_tossing/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-coin_tossing/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.1276595745, "max_line_length": 93, "alphanum_fraction": 0.6475988701, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5858898948222275}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MTL_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": "#include \"intersection.hpp\"\n\n#include <Eigen/Geometry>\n\n#include <igl/predicates/predicates.h>\n#include <ipc/friction/closest_point.hpp>\n\n#include <utils/is_zero.hpp>\n\nnamespace ipc::rigid {\n\nbool is_point_along_edge(\n    const VectorMax3I& p, const VectorMax3I& e0, const VectorMax3I& e1)\n{\n    VectorMax3I e = e1 - e0;\n\n    Interval alpha = point_edge_closest_point(p, e0, e1);\n    // Check this in case empty intervals are not allowed\n    if (!overlap(alpha, Interval(0, 1))) {\n        return false;\n    }\n    Interval valid_alpha = boost::numeric::intersect(alpha, Interval(0, 1));\n\n    // Check the distance to the closest point is small\n    VectorMax3I edge_to_point = e0 + valid_alpha * e - p;\n\n    return is_zero(edge_to_point);\n}\n\nbool are_edges_intersecting(\n    const Vector3I& ea0,\n    const Vector3I& ea1,\n    const Vector3I& eb0,\n    const Vector3I& eb1)\n{\n    // Check if the origin is withing the 3D difference of edge points\n    // WARNING: This is a very converative estimate.\n    Vector3I ea_alpha = (ea1 - ea0) * Interval(0, 1) + ea0;\n    Vector3I eb_alpha = (eb1 - eb0) * Interval(0, 1) + eb0;\n    return is_zero(Vector3I(ea_alpha - eb_alpha));\n}\n\ninline bool are_points_on_same_side_of_edge(\n    const Vector3I& p1,\n    const Vector3I& p2,\n    const Vector3I& a,\n    const Vector3I& b)\n{\n    Vector3I cp1 = (b - a).cross(p1 - a);\n    Vector3I cp2 = (b - a).cross(p2 - a);\n    return cp1.dot(cp2).upper() >= 0;\n}\n\nbool is_point_inside_triangle(\n    const Vector3I& point,\n    const Vector3I& triangle_vertex0,\n    const Vector3I& triangle_vertex1,\n    const Vector3I& triangle_vertex2)\n{\n    return are_points_on_same_side_of_edge(\n               point, triangle_vertex0, triangle_vertex1, triangle_vertex2)\n        && are_points_on_same_side_of_edge(\n               point, triangle_vertex1, triangle_vertex0, triangle_vertex2)\n        && are_points_on_same_side_of_edge(\n               point, triangle_vertex2, triangle_vertex0, triangle_vertex1);\n}\n\n} // namespace ipc::rigid\n", "meta": {"hexsha": "b540c783c098ef49de59fe593f102ab647f4f4f1", "size": 1999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/intersection.cpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "src/geometry/intersection.cpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "src/geometry/intersection.cpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 28.9710144928, "max_line_length": 76, "alphanum_fraction": 0.6868434217, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5858755623375843}}
{"text": "// Copyright (C) 2004 Jeremy Siek <jsiek@cs.indiana.edu>\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/transitive_closure.hpp>\n#include <iostream>\nusing namespace std;\n\nusing namespace boost;\ntypedef adjacency_list<> graph_t;\n\nint main(int argc, char* argv[])\n{\n    graph_t g(5), g_TC;\n\n    add_edge(0, 2, g);\n    add_edge(1, 0, g);\n    add_edge(1, 2, g);\n    add_edge(1, 4, g);\n    add_edge(3, 0, g);\n    add_edge(3, 2, g);\n    add_edge(4, 2, g);\n    add_edge(4, 3, g);\n\n    transitive_closure(g, g_TC);\n\n    cout << \"original graph: 0->2, 1->0, 1->2, 1->4, 3->0, 3->2, 4->2, 4->3\"\n         << endl;\n    cout << \"transitive closure: \";\n    graph_t::edge_iterator i, iend;\n    for (boost::tie(i, iend) = edges(g_TC); i != iend; ++i)\n    {\n        cout << source(*i, g_TC) << \"->\" << target(*i, g_TC) << \" \";\n    }\n    cout << endl;\n}\n", "meta": {"hexsha": "8b71279187d5cf698ca6a7df18694f26ef35f6d4", "size": 1054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/test/transitive_closure_test2.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/graph/test/transitive_closure_test2.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/test/transitive_closure_test2.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": 27.0256410256, "max_line_length": 76, "alphanum_fraction": 0.6091081594, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5858755621226984}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestAccumulate\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/algorithm/accumulate.hpp>\n#include <boost/compute/algorithm/iota.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/iterator/counting_iterator.hpp>\n\n#include \"context_setup.hpp\"\n\nBOOST_AUTO_TEST_CASE(sum_int)\n{\n    int data[] = { 2, 4, 6, 8 };\n    boost::compute::vector<int> vector(data, data + 4, queue);\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(vector.begin(), vector.end(), 0, queue),\n        20\n    );\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(vector.begin(), vector.end(), -10, queue),\n        10\n    );\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(vector.begin(), vector.end(), 5, queue),\n        25\n    );\n}\n\nBOOST_AUTO_TEST_CASE(product_int)\n{\n    int data[] = { 2, 4, 6, 8 };\n    boost::compute::vector<int> vector(data, data + 4);\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(\n            vector.begin(), vector.end(), 1, boost::compute::multiplies<int>()),\n        384\n    );\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(\n            vector.begin(), vector.end(), -1, boost::compute::multiplies<int>()),\n        -384\n    );\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(\n            vector.begin(), vector.end(), 2, boost::compute::multiplies<int>()),\n        768\n    );\n}\n\nBOOST_AUTO_TEST_CASE(quotient_int)\n{\n    int data[] = { 2, 8, 16 };\n    boost::compute::vector<int> vector(data, data + 3, queue);\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(\n            vector.begin(),\n            vector.end(),\n            1024,\n            boost::compute::divides<int>(),\n            queue\n        ),\n        4\n    );\n}\n\nBOOST_AUTO_TEST_CASE(sum_counting_iterator)\n{\n    // sum 0 -> 9\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(\n            boost::compute::make_counting_iterator(0),\n            boost::compute::make_counting_iterator(10),\n            0,\n            boost::compute::plus<int>(),\n            queue\n        ),\n        45\n    );\n\n    // sum 0 -> 9 + 7\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(\n            boost::compute::make_counting_iterator(0),\n            boost::compute::make_counting_iterator(10),\n            7,\n            boost::compute::plus<int>(),\n            queue\n        ),\n        52\n    );\n\n    // sum 15 -> 24\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(\n            boost::compute::make_counting_iterator(15),\n            boost::compute::make_counting_iterator(25),\n            0,\n            boost::compute::plus<int>(),\n            queue\n        ),\n        195\n    );\n\n    // sum -5 -> 10\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(\n            boost::compute::make_counting_iterator(-5),\n            boost::compute::make_counting_iterator(10),\n            0,\n            boost::compute::plus<int>(),\n            queue\n        ),\n        30\n    );\n\n    // sum -5 -> 10 - 2\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(\n            boost::compute::make_counting_iterator(-5),\n            boost::compute::make_counting_iterator(10),\n            -2,\n            boost::compute::plus<int>(),\n            queue\n        ),\n        28\n    );\n}\n\nBOOST_AUTO_TEST_CASE(sum_iota)\n{\n    // size 0\n    boost::compute::vector<int> vector(0, context);\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(vector.begin(), vector.end(), 0, queue),\n        0\n    );\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(vector.begin(), vector.end(), 4, queue),\n        4\n    );\n\n    // size 50\n    vector.resize(50);\n    boost::compute::iota(vector.begin(), vector.end(), 0, queue);\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(vector.begin(), vector.end(), 0, queue),\n        1225\n    );\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(vector.begin(), vector.end(), 11, queue),\n        1236\n    );\n\n    // size 1000\n    vector.resize(1000);\n    boost::compute::iota(vector.begin(), vector.end(), 0, queue);\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(vector.begin(), vector.end(), 0, queue),\n        499500\n    );\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(vector.begin(), vector.end(), -45, queue),\n        499455\n    );\n\n    // size 1025\n    vector.resize(1025);\n    boost::compute::iota(vector.begin(), vector.end(), 0, queue);\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(vector.begin(), vector.end(), 0, queue),\n        524800\n    );\n\n    BOOST_CHECK_EQUAL(\n        boost::compute::accumulate(vector.begin(), vector.end(), 2, queue),\n        524802\n    );\n}\n\nBOOST_AUTO_TEST_CASE(min_and_max)\n{\n    using boost::compute::int2_;\n\n    int data[] = { 5, 3, 1, 6, 4, 2 };\n    boost::compute::vector<int> vector(data, data + 6, queue);\n\n    BOOST_COMPUTE_FUNCTION(int2_, min_and_max, (int2_ accumulator, const int value),\n    {\n        return (int2)(min(accumulator.x, value), max(accumulator.y, value));\n    });\n\n    int2_ result = boost::compute::accumulate(\n        vector.begin(), vector.end(), int2_(100, -100), min_and_max, queue\n    );\n    BOOST_CHECK_EQUAL(result[0], 1);\n    BOOST_CHECK_EQUAL(result[1], 6);\n}\n\nBOOST_AUTO_TEST_CASE(min_max)\n{\n    float data[] = { 1.2f, 5.5f, 0.1f, 9.6f, 4.2f, 6.7f, 9.0f, 3.4f };\n    boost::compute::vector<float> vec(data, data + 8, queue);\n\n    using ::boost::compute::min;\n    using ::boost::compute::max;\n\n    float min_value = boost::compute::accumulate(\n        vec.begin(), vec.end(), std::numeric_limits<float>::max(), min<float>(), queue\n    );\n    BOOST_CHECK_EQUAL(min_value, 0.1f);\n\n    float max_value = boost::compute::accumulate(\n        vec.begin(), vec.end(), std::numeric_limits<float>::min(), max<float>(), queue\n    );\n    BOOST_CHECK_EQUAL(max_value, 9.6f);\n\n    // find min with init less than any value in the array\n    min_value = boost::compute::accumulate(\n        vec.begin(), vec.end(), -1.f, min<float>(), queue\n    );\n    BOOST_CHECK_EQUAL(min_value, -1.f);\n\n    // find max with init greater than any value in the array\n    max_value = boost::compute::accumulate(\n        vec.begin(), vec.end(), 10.f, max<float>(), queue\n    );\n    BOOST_CHECK_EQUAL(max_value, 10.f);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0ecfedda60bcd69fdfa55ecdfdd457e49c4a7517", "size": 6765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_accumulate.cpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-31T17:12:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T17:12:33.000Z", "max_issues_repo_path": "test/test_accumulate.cpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_accumulate.cpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7391304348, "max_line_length": 86, "alphanum_fraction": 0.5735402809, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.585821511767612}}
{"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": "/*****************************************************************************\n * \n * File:    sssp_gold.cpp\n * Author:  Alex Stivala\n * Created: February 2011\n *\n * $Id: sssp_gold.cpp 668 2011-09-08 04:40:08Z astivala $\n *\n * Get single-source shortest path on CPU for verification.\n * Uses Dijkstra's algorithm from the Boost Graph Library.\n * (Based on the example/dijkstra-example.cpp code from Boost Graph Library\n * manual\n *  http://www.boost.org/doc/libs/1_38_0/libs/graph/doc/dijkstra_shortest_paths.html)\n *\n ****************************************************************************/\n\n#include <assert.h>\n\n#include <cutil_inline.h>      /* CUDA SDK */\n\n#include <boost/config.hpp>\n#include <iostream>\n#include <fstream>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\n#include \"sssp_gold.h\"\n\nusing namespace boost;\n\n/*\n * sssp_gold() -  use Dijkstra's algorithim on CPU (using Boost Graph Library)\n *                to solve single-source shortest path problem for checking.\n *\n * Parameters:\n *     adjlist - adjacnecy list (array of (node1,node2,cost) structs)\n *     num_nodes  - number of nodes \n *     num_arcs - number of edges (entries in adjlist)\n *     source - source node \n *     distances (OUT) - array of shortest costs from source to each node\n *     predecessors (OUT) - predecessor node on minimum spanning tree for\n *                          each node.\n * Return value:\n *     time spent running dijkstra_shortest_paths() in milliseconds\n */\ndouble sssp_gold(adjlist_entry_t adjlist[], long num_nodes, long num_arcs,\n               long source,\n               double distances[], long predecessors[])\n{\n  unsigned int hTimer;\n  typedef adjacency_list < listS, vecS, directedS,\n    no_property, property < edge_weight_t, double > > graph_t;\n  typedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;\n  typedef graph_traits < graph_t >::edge_descriptor edge_descriptor;\n  typedef std::pair<long, long> Edge;\n\n  Edge *edge_array = new Edge[num_arcs];\n  double *weights = new double[num_arcs];\n  for (long i = 0; i < num_arcs; i++)\n  {\n    edge_array[i] =  Edge(adjlist[i].from, adjlist[i].to);\n    weights[i] = adjlist[i].cost;\n  }\n\n  \n  graph_t g(edge_array, edge_array + num_arcs, weights, num_nodes);\n  property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);\n\n  std::vector<vertex_descriptor> p(num_vertices(g));\n  std::vector<double> d(num_vertices(g));\n  vertex_descriptor s = vertex(source, g);\n\n  cutilCheckError( cutCreateTimer(&hTimer) );\n  cutilCheckError( cutResetTimer(hTimer) );\n  cutilCheckError( cutStartTimer(hTimer) );\n\n  dijkstra_shortest_paths(g, s, predecessor_map(&p[0]).distance_map(&d[0]));\n\n  cutilCheckError( cutStopTimer(hTimer) );\n  double runtime = cutGetTimerValue(hTimer);\n\n  graph_traits < graph_t >::vertex_iterator vi, vend;\n  long i = 0;\n  for (tie(vi, vend) = vertices(g); vi != vend; ++vi)\n  {\n    assert(i < num_nodes);\n    distances[i] = d[*vi];\n    predecessors[i] = p[*vi];\n    i++;\n  }\n\n  delete[] edge_array;\n  delete[] weights;\n\n  return runtime;\n}\n", "meta": {"hexsha": "4f373c449a7c27a0ba82c21990b612d27bff9787", "size": 3141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trunk/cuda_sssp_double/sssp_gold.cpp", "max_stars_repo_name": "stivalaa/traffic_assignment", "max_stars_repo_head_hexsha": "45378558af73feeaf9e6491612c93dba042cb5ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-10T16:18:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T04:52:37.000Z", "max_issues_repo_path": "trunk/cuda_sssp_double/sssp_gold.cpp", "max_issues_repo_name": "stivalaa/traffic_assignment", "max_issues_repo_head_hexsha": "45378558af73feeaf9e6491612c93dba042cb5ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trunk/cuda_sssp_double/sssp_gold.cpp", "max_forks_repo_name": "stivalaa/traffic_assignment", "max_forks_repo_head_hexsha": "45378558af73feeaf9e6491612c93dba042cb5ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-02T10:59:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T10:59:51.000Z", "avg_line_length": 31.7272727273, "max_line_length": 85, "alphanum_fraction": 0.6542502388, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5858214890382741}}
{"text": "#include <armadillo>\n#include <cassert>\n#include <cstdio>\n#include <iostream>\n\nvoid alter(arma::vec &vref) {\n\n    vref *= -4.0;\n\n    return;\n}\n\nint main() {\n\n    // arma::arma_rng::set_seed_random();\n    arma::arma_rng::set_seed(5489);\n\n    size_t lr = 4;\n    size_t lc = 3;\n\n    arma::mat Am(lr, lc, arma::fill::randn);\n\n    Am.print(\"Am\");\n\n    arma::vec ones(lr, arma::fill::ones);\n    Am.col(2) = ones;\n\n    Am.print(\"Am\");\n\n    arma::vec wrapper(Am.colptr(2), lr, false, false);\n    wrapper *= -4.0;\n\n    Am.print(\"Am\");\n\n    alter(wrapper);\n\n    Am.print(\"Am\");\n\n    return 0;\n\n}\n", "meta": {"hexsha": "844ad4c184862c01bfa1b698b97dd1f14a5aeba9", "size": 586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/armadillo/arma_test_wrap.cpp", "max_stars_repo_name": "berquist/eg", "max_stars_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/armadillo/arma_test_wrap.cpp", "max_issues_repo_name": "berquist/eg", "max_issues_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/armadillo/arma_test_wrap.cpp", "max_forks_repo_name": "berquist/eg", "max_forks_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.9523809524, "max_line_length": 54, "alphanum_fraction": 0.5563139932, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.585821487499636}}
{"text": "#ifndef IMAGEDISTANCE_HPP\n#define IMAGEDISTANCE_HPP\n\n#include <Eigen/Core>\n#include <array>\n#include <functional>\n\nnamespace imagedistance\n{\n    using Histogram = Eigen::VectorXd;\n\n    class HistogramManager\n    {\n    public:\n        HistogramManager(const Eigen::MatrixXd&                                        r_channel,\n                         const Eigen::MatrixXd&                                        g_channel,\n                         const Eigen::MatrixXd&                                        b_channel,\n                         const std::function<Eigen::Vector3d(const Eigen::Vector3d&)>& rgb_to_hsl_converter,\n                         const int                                                     num_bins = 30);\n\n        std::array<Histogram, 3> m_rgb_histograms;\n        std::array<Histogram, 3> m_hsl_histograms;\n        Histogram                m_intensity_histogram;\n        std::array<Histogram, 2> m_edge_histograms;\n\n        double m_size;\n        double m_aspect;\n    };\n\n    // This function returns a 38-dimensional vector, calculated based on Kapoor et al.'s paper [2014]\n    Eigen::VectorXd CalcDistances(const HistogramManager& a, const HistogramManager& b);\n\n    double CalcL2Distance(const Histogram& a, const Histogram& b);\n    double CalcSmoothedL2Distance(const Histogram& a, const Histogram& b);\n    double CalcSymmetricKlDivergenceDistance(const Histogram& a, const Histogram& b);\n    double CalcEntropyDistance(const Histogram& a, const Histogram& b);\n} // namespace imagedistance\n\n#endif /* IMAGEDISTANCE_HPP */\n", "meta": {"hexsha": "066aaeb6329fca90aa256ba38b31787dc5754370", "size": 1554, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/imagedistance.hpp", "max_stars_repo_name": "yuki-koyama/image-distance-calculator", "max_stars_repo_head_hexsha": "d65bd23c35a850f307dcbfcf7296596fde568d79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-09T21:51:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-09T21:51:13.000Z", "max_issues_repo_path": "include/imagedistance.hpp", "max_issues_repo_name": "yuki-koyama/image-distance-calculator", "max_issues_repo_head_hexsha": "d65bd23c35a850f307dcbfcf7296596fde568d79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/imagedistance.hpp", "max_forks_repo_name": "yuki-koyama/image-distance-calculator", "max_forks_repo_head_hexsha": "d65bd23c35a850f307dcbfcf7296596fde568d79", "max_forks_repo_licenses": ["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.85, "max_line_length": 108, "alphanum_fraction": 0.5984555985, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5857966281096494}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <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": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE SinogramCreatorTest\n#include <boost/test/unit_test.hpp>\n\n#include \"SinogramCreatorTools.h\"\n\nBOOST_AUTO_TEST_SUITE(FirstSuite)\n\nBOOST_AUTO_TEST_CASE(roundToNearesMultiplicity_test)\n{\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.0f, 1.f), 0u);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.4f, 1.f), 0u);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.5f, 1.f), 1u);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(30.f, 1.f), 30u);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.00f, 0.01f), 0u);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.01f, 0.01f), 1u);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::roundToNearesMultiplicity(0.02f, 0.01f), 2u);\n}\n\nBOOST_AUTO_TEST_CASE(test_angle_middle)\n{\n  for (int i = 0; i < 180; i++) {\n    float x = std::cos(i / M_PI);\n    float y = std::sin(i / M_PI);\n    BOOST_REQUIRE_EQUAL(SinogramCreatorTools::calculateAngle(x, y, -x, -y), i);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_angle)\n{\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::calculateAngle(0.f, 0.f, 0.f, 0.f), 0);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::calculateAngle(0.f, 0.f, -1.f, 0.f), 0);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::calculateAngle(-1.f, 0.f, 1.f, 0.f), 0);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::calculateAngle(1.f, 0.f, -1.f, 0.f), 0);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::calculateAngle(0.f, 1.f, 0.f, -1.f), 90);\n  BOOST_REQUIRE_EQUAL(SinogramCreatorTools::calculateAngle(0.f, -1.f, 0.f, 1.f), 90);\n}\n\nBOOST_AUTO_TEST_CASE(test_distance)\n{\n  const float EPSILON = 0.00001f;\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateDistance(0.f, 0.f, 0.f, 0.f), 0, EPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateDistance(0.f, 0.f, -1.f, 0.f), -0, EPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateDistance(0.f, 0.f, 1.f, 0.f), 0, EPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateDistance(1.f, 1.f, -1.f, 1.f), 1, EPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateDistance(-1.f, 1.f, 1.f, 1.f), 1, EPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateDistance(0.f, 1.f, 1.f, 0.f), std::sqrt(0.5f), EPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateDistance(1.f, 0.f, 0.f, 1.f), std::sqrt(0.5f), EPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateDistance(-1.f, 0.f, 1.f, 0.f), 0, EPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateDistance(1.f, 0.f, -1.f, 0.f), 0, EPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateDistance(0.f, 1.f, 0.f, -1.f), 0, EPSILON);\n  BOOST_REQUIRE_CLOSE(SinogramCreatorTools::calculateDistance(0.f, -1.f, 0.f, 1.f), 0, EPSILON);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e1c8b60d46005140e24b6e66c945cd472e520ac7", "size": 2833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ImageReconstruction/SinogramCreatorToolsTest.cpp", "max_stars_repo_name": "nenprio/j-pet-framework-examples", "max_stars_repo_head_hexsha": "b76e8c289e91932a2e7bf30b19ab6fcaaa8d2d1e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ImageReconstruction/SinogramCreatorToolsTest.cpp", "max_issues_repo_name": "nenprio/j-pet-framework-examples", "max_issues_repo_head_hexsha": "b76e8c289e91932a2e7bf30b19ab6fcaaa8d2d1e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-15T12:47:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-15T12:47:16.000Z", "max_forks_repo_path": "ImageReconstruction/SinogramCreatorToolsTest.cpp", "max_forks_repo_name": "nenprio/j-pet-framework-examples", "max_forks_repo_head_hexsha": "b76e8c289e91932a2e7bf30b19ab6fcaaa8d2d1e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.5892857143, "max_line_length": 109, "alphanum_fraction": 0.7585598306, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414786, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5857439224621589}}
{"text": "/**\n * @file upwindquadrature_main.cc\n * @brief NPDE homework template main\n * @author Philippe Peter\n * @date June 2020\n * @copyright Developed at SAM, ETH Zurich\n */\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/fe/fe.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <cmath>\n#include <memory>\n\n#include \"../../../lecturecodes/ConvectionDiffusion/convection_emp.h\"\n#include \"upwindquadrature.h\"\n\nint main() {\n  // PARAMETERS\n  // mesh specification (number of cells in both sides of the tensor-product\n  // triangular mesh)\n  int M = 49;\n\n  // coefficient functions:\n  // Dirichlet functor\n  const auto g = [](const Eigen::Vector2d &x) {\n    return x(1) == 0 ? 0.5 - std::abs(x(0) - 0.5) : 0.0;\n  };\n  lf::mesh::utils::MeshFunctionGlobal mf_g{g};\n\n  // velocity field\n  const auto v = [](const Eigen::Vector2d &x) {\n    return (Eigen::Vector2d() << -x(1), x(0)).finished();\n  };\n\n  // diffusion coefficient\n  const double eps = 1e-4;\n  lf::mesh::utils::MeshFunctionConstant mf_eps{eps};\n\n  // MESH CONSTRUCTION\n  // construct a triangular tensor product mesh on the unit square\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(M)\n      .setNumYCells(M);\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = builder.Build();\n\n  // DOF HANDLER & FINITE ELEMENT SPACE\n  // Construct dofhanlder for linear finite elements on the 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  // PREPARING DATA TO IMPOSE DIRICHLET CONDITIONS\n  // Obtain specification for shape functions on edges\n  const lf::fe::ScalarReferenceFiniteElement<double> *rsf_edge_p =\n      fe_space->ShapeFunctionLayout(lf::base::RefEl::kSegment());\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  // Fetch flags and values for degrees of freedom located on Dirichlet\n  // boundary.\n  auto ess_bdc_flags_values{\n      lf::fe::InitEssentialConditionFromFunction(*fe_space, bd_flags, mf_g)};\n\n  //============================================================================\n  // SOLVE LAPLACIAN WITH NON-HOMOGENEOUS DIRICHLET BC (STANDARD: UNSTABLE)\n  //============================================================================\n  // Matrix in triplet format holding Galerkin matrix, zero initially.\n  lf::assemble::COOMatrix<double> A(dofh.NumDofs(), dofh.NumDofs());\n\n  // ASSEMBLE GALERKIN MATRIX\n  // First the part corresponding to the laplacian\n  lf::uscalfe::ReactionDiffusionElementMatrixProvider laplacian_provider(\n      fe_space, mf_eps, lf::mesh::utils::MeshFunctionConstant(0.0));\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, laplacian_provider, A);\n\n  // Next part corresponding to the convection term:\n  ConvectionDiffusion::ConvectionElementMatrixProvider convection_provider(v);\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, convection_provider, A);\n\n  // RIGHT-HAND SIDE VECTOR\n  Eigen::VectorXd phi(dofh.NumDofs());\n  phi.setZero();\n\n  // IMPOSE DIRICHLET CONDITIONS:\n  // Eliminate Dirichlet dofs from linear system\n  lf::assemble::FixFlaggedSolutionComponents<double>(\n      [&ess_bdc_flags_values](lf::uscalfe::glb_idx_t gdof_idx) {\n        return ess_bdc_flags_values[gdof_idx];\n      },\n      A, phi);\n\n  // SOLVE LINEAR SYSTEM\n  Eigen::SparseMatrix 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 finite element solution\n  lf::fe::MeshFunctionFE mf_sol(fe_space, sol_vec);\n  // construct vtk writer\n  lf::io::VtkWriter vtk_writer(\n      mesh_p, CURRENT_BINARY_DIR \"/upwind_quadrature_solution_unstable.vtk\");\n  // output data\n  vtk_writer.WritePointData(\"upwind_quadrature_solution_unstable\", mf_sol);\n\n  //============================================================================\n  // SOLVE LAPLACIAN WITH NON-HOMOGENEOUS DIRICHLET BC (UPWIND: STABLE)\n  //============================================================================\n  // Matrix in triplet format holding Galerkin matrix, zero initially.\n  lf::assemble::COOMatrix<double> A_stable(dofh.NumDofs(), dofh.NumDofs());\n\n  // ASSEMBLE GALERKIN MATRIX\n  // First the part corresponding to the laplacian, computed using standard\n  // Galerkin approach\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, laplacian_provider,\n                                      A_stable);\n\n  // Next part corresponding to the convection term, computed using upwind\n  // quadrature:\n  UpwindQuadrature::UpwindConvectionElementMatrixProvider\n      convection_provider_stable(v, UpwindQuadrature::initializeMasses(mesh_p));\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, convection_provider_stable,\n                                      A_stable);\n\n  // RIGHT-HAND SIDE VECTOR\n  Eigen::VectorXd phi_stable(dofh.NumDofs());\n  phi_stable.setZero();\n\n  // IMPOSE DIRICHLET CONDITIONS:\n  // Eliminate Dirichlet dofs from linear system\n  lf::assemble::FixFlaggedSolutionComponents<double>(\n      [&ess_bdc_flags_values](lf::uscalfe::glb_idx_t gdof_idx) {\n        return ess_bdc_flags_values[gdof_idx];\n      },\n      A_stable, phi_stable);\n\n  // SOLVE LINEAR SYSTEM\n  Eigen::SparseMatrix A_stable_crs = A_stable.makeSparse();\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver_stable;\n  solver_stable.compute(A_stable_crs);\n  Eigen::VectorXd sol_vec_stable = solver_stable.solve(phi_stable);\n\n  // OUTPUT RESULTS TO VTK FILe\n  // construct mesh function representing finite element solution\n  lf::fe::MeshFunctionFE mf_sol_stable(fe_space, sol_vec_stable);\n  // construct vtk writer\n  lf::io::VtkWriter vtk_writer_stable(\n      mesh_p, CURRENT_BINARY_DIR \"/upwind_quadrature_solution_stable.vtk\");\n  // output data\n  vtk_writer_stable.WritePointData(\"upwind_quadrature_solution_stable\",\n                                   mf_sol_stable);\n\n  return 0;\n}\n", "meta": {"hexsha": "048afd296075db6076fba93e027e16fcbe06eab7", "size": 6494, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/UpwindQuadrature/templates/upwindquadrature_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": "homeworks/UpwindQuadrature/templates/upwindquadrature_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": "homeworks/UpwindQuadrature/templates/upwindquadrature_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": 37.9766081871, "max_line_length": 80, "alphanum_fraction": 0.6854019095, "num_tokens": 1726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5857439090602387}}
{"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\u00e9n wavefunction including the r^2 Jacobian expands to\n  // three exponential terms:  exp(-2*a*r) + exp(-2*b*r) - 2*exp(-(a+b)*r).\n  // This does not have a closed-form inverse CDF, however we can easily sample\n  // exponential numbers from the term that falls off the slowest, i.e.\n  // exp(-2*min(a,b)*r).  In the ctor initializer list the \"a\" parameter is\n  // always set to the minimum, so we should sample from exp(-2*a*r).\n  double r, prob;\n  do {\n    // Sample a uniform random number, u = exp(-2*a*r).\n    auto u = random::canonical<double>();\n    // Invert to find the actual radius.\n    r = -std::log(u) / (2*a_);\n    // The acceptance probability is now the radial wavefunction over the\n    // envelope function, both evaluated at the proposal radius r.\n    // Conveniently, the envelope evaluated at r is just the uniform random\n    // number u.\n    prob = std::pow(std::exp(-a_*r) - std::exp(-b_*r), 2) / u;\n  } while (prob < random::canonical<double>());\n\n  // Now sample spherical rotation angles.\n  auto cos_theta = random::cos_theta<double>();\n  auto phi = random::phi<double>();\n\n  // And compute the 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": "#ifndef PYTHONIC_INCLUDE_NUMPY_LOG2_HPP\n#define PYTHONIC_INCLUDE_NUMPY_LOG2_HPP\n\n#include \"pythonic/include/utils/functor.hpp\"\n#include \"pythonic/include/types/ndarray.hpp\"\n#include \"pythonic/include/utils/numpy_traits.hpp\"\n#include <boost/simd/function/log2.hpp>\n\nPYTHONIC_NS_BEGIN\n\nnamespace numpy\n{\n  namespace wrapper\n  {\n    template <class T>\n    std::complex<T> log2(std::complex<T> const &val)\n    {\n      return std::log(val) / std::log(2);\n    }\n    template <class T>\n    auto log2(T const &val) -> decltype(boost::simd::log2(val))\n    {\n      return boost::simd::log2(val);\n    }\n  }\n#define NUMPY_NARY_FUNC_NAME log2\n#define NUMPY_NARY_FUNC_SYM wrapper::log2\n#include \"pythonic/include/types/numpy_nary_expr.hpp\"\n}\nPYTHONIC_NS_END\n\n#endif\n", "meta": {"hexsha": "efedde019cd5a233194482804f1c5e33cbdb27e4", "size": 752, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pythran/pythonic/include/numpy/log2.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-24T00:33:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-24T00:33:03.000Z", "max_issues_repo_path": "pythran/pythonic/include/numpy/log2.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pythran/pythonic/include/numpy/log2.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7878787879, "max_line_length": 63, "alphanum_fraction": 0.7260638298, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5857409922302155}}
{"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": "//  Copyright John Maddock 2007.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include \"required_defines.hpp\"\r\n#include \"performance_measure.hpp\"\r\n\r\n#include <boost/math/special_functions/cbrt.hpp>\r\n\r\ndouble cbrt_test()\r\n{\r\n   double result = 0;\r\n   double val = 1e-100;\r\n   for(int i = 0; i < 1000; ++i)\r\n   {\r\n      val *= 1.5;\r\n      result += boost::math::cbrt(val);\r\n   }\r\n   return result;\r\n}\r\n\r\nBOOST_MATH_PERFORMANCE_TEST(cbrt_test, \"cbrt\")\r\n{\r\n   double result = cbrt_test();\r\n\r\n   consume_result(result);\r\n   set_call_count(1000);\r\n}\r\n\r\ndouble cbrt_pow_test()\r\n{\r\n   double result = 0;\r\n   double val = 1e-100;\r\n   for(int i = 0; i < 1000; ++i)\r\n   {\r\n      val *= 1.5;\r\n      result += std::pow(val, 0.33333333333333333333333333333333);\r\n   }\r\n   return result;\r\n}\r\n\r\nBOOST_MATH_PERFORMANCE_TEST(cbrt_pow_test, \"cbrt-pow\")\r\n{\r\n   double result = cbrt_pow_test();\r\n\r\n   consume_result(result);\r\n   set_call_count(1000);\r\n}\r\n\r\n#ifdef TEST_CEPHES\r\n\r\nextern \"C\" double cbrt(double);\r\n\r\ndouble cbrt_cephes_test()\r\n{\r\n   double result = 0;\r\n   double val = 1e-100;\r\n   for(int i = 0; i < 1000; ++i)\r\n   {\r\n      val *= 1.5;\r\n      result += ::cbrt(val);\r\n   }\r\n   return result;\r\n}\r\n\r\nBOOST_MATH_PERFORMANCE_TEST(cbrt_test, \"cbrt-cephes\")\r\n{\r\n   double result = cbrt_cephes_test();\r\n\r\n   consume_result(result);\r\n   set_call_count(1000);\r\n}\r\n\r\n#endif\r\n\r\n#if defined(__GNUC__) && (__GNUC__ >= 4)\r\n\r\n#include <math.h>\r\n\r\ndouble cbrt_c99_test()\r\n{\r\n   double result = 0;\r\n   double val = 1e-100;\r\n   for(int i = 0; i < 1000; ++i)\r\n   {\r\n      val *= 1.5;\r\n      result += ::cbrt(val);\r\n   }\r\n   return result;\r\n}\r\n\r\nBOOST_MATH_PERFORMANCE_TEST(cbrt_c99_test, \"cbrt-c99\")\r\n{\r\n   double result = cbrt_c99_test();\r\n\r\n   consume_result(result);\r\n   set_call_count(1000);\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "3317ff01ab9b9b41f91aa845817dc5492a084741", "size": 1935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/performance/test_cbrt.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/math/performance/test_cbrt.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/math/performance/test_cbrt.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": 18.9705882353, "max_line_length": 69, "alphanum_fraction": 0.6118863049, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5857094686159123}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#include \"catch.hpp\"\n\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <iostream>\n\n\n#include <Eigen/Core>\n#include <boost/math/special_functions/erf.hpp>\n\n#include \"green/dielectric_profile/OneLayerTanh.hpp\"\n#include \"green/dielectric_profile/OneLayerErf.hpp\"\n\ndouble tanh_value(double point, double e1, double e2, double w, double c);\ndouble tanh_deriv(double point, double e1, double e2, double w, double c);\n\ndouble erf_value(double point, double e1, double e2, double w, double c);\ndouble erf_deriv(double point, double e1, double e2, double w, double c);\n\ndouble distribution(double fMin, double fMax);\n\nSCENARIO(\"Diffuse permittivity single layers\", \"[dielectric_profile][one_layer]\")\n{\n    GIVEN(\"The parameters for a one-layer diffuse permittivity profile\")\n    {\n        std::srand(std::time(0));\n        double eps1 = 78.39;\n        double eps2 = 1.0;\n        double center = 50.0;\n        double width = 10.0;\n\n        /*! \\class OneLayerTanh\n         *  \\test \\b TanhOneLayerTest tests the evaluation of the one layer hyperbolic tangent profile against the analytic value\n         */\n        WHEN(\"the sigmoidal profile is modelled by the hyperbolic tangent function\")\n        {\n            OneLayerTanh diffuse(eps1, eps2, width, center);\n            double value = 0.0, deriv = 0.0;\n            double point = distribution(0.0, 100.0);\n            pcm::tie(value, deriv) = diffuse(point);\n            THEN(\"the value of the profile at a random point is\")\n            {\n                double analytic = tanh_value(point, eps1, eps2, width, center);\n                INFO(\" The evaluation point is: \" << point);\n                REQUIRE(value == Approx(analytic));\n            }\n            AND_THEN(\"the value of the first derivative at a random point is\")\n            {\n                double analyticDeriv = tanh_deriv(point, eps1, eps2, width, center);\n                INFO(\" The evaluation point is: \" << point);\n                REQUIRE(deriv == Approx(analyticDeriv));\n            }\n        }\n\n        /*! \\class OneLayerErf\n         *  \\test \\b TanhOneLayerTest tests the evaluation of the one layer hyperbolic tangent profile against the analytic value\n         */\n        WHEN(\"the sigmoidal profile is modelled by the error function\")\n        {\n            OneLayerErf diffuse(eps1, eps2, width, center);\n            double value = 0.0, deriv = 0.0;\n            double point = distribution(0.0, 100.0);\n            pcm::tie(value, deriv) = diffuse(point);\n            THEN(\"the value of the profile at a random point is\")\n            {\n                double analytic = erf_value(point, eps1, eps2, width, center);\n                INFO(\" The evaluation point is: \" << point);\n                REQUIRE(value == Approx(analytic));\n            }\n            AND_THEN(\"the value of the first derivative at a random point is\")\n            {\n                double analyticDeriv = erf_deriv(point, eps1, eps2, width, center);\n                INFO(\" The evaluation point is: \" << point);\n                REQUIRE(deriv == Approx(analyticDeriv));\n            }\n        }\n    }\n}\n\ndouble tanh_value(double point, double e1, double e2, double w, double c)\n{\n    w /= 6.0;\n    double epsPlus = (e1 + e2) / 2.0;\n    double epsMinus = (e2 - e1) / 2.0;\n    double tanh_r = std::tanh((point - c) / w);\n    return (epsPlus + epsMinus * tanh_r);\n}\ndouble tanh_deriv(double point, double e1, double e2, double w, double c)\n{\n    w /= 6.0;\n    double factor = (e2 - e1) / (2.0 * w);\n    double tanh_r = std::tanh((point - c) / w);\n    return (factor * (1 - std::pow(tanh_r, 2)));\n}\n\ndouble erf_value(double point, double e1, double e2, double w, double c)\n{\n    w /= 6.0;\n    double epsPlus = (e1 + e2) / 2.0;\n    double epsMinus = (e2 - e1) / 2.0;\n    double val = boost::math::erf((point - c) / w);\n    return (epsPlus + epsMinus * val);\n}\ndouble erf_deriv(double point, double e1, double e2, double w, double c)\n{\n    w /= 6.0;\n    double factor = (e2 - e1) / (w * std::sqrt(M_PI));\n    double t = (point - c) / w;\n    double val = std::exp(-std::pow(t, 2));\n    return (factor * val);\n}\n\ndouble distribution(double fMin, double fMax)\n{\n    double f = (double)std::rand() / RAND_MAX;\n    return fMin + f * (fMax - fMin);\n}\n", "meta": {"hexsha": "4acb4a96e22dc0746fd60fae245d465968ef10c0", "size": 5352, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/tests/dielectric_profile/one_layer.cpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/tests/dielectric_profile/one_layer.cpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/tests/dielectric_profile/one_layer.cpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1666666667, "max_line_length": 129, "alphanum_fraction": 0.6132286996, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5857094681967278}}
{"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 * @file semimprk.cc\n * @brief NPDE homework SemImpRK code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"semimprk.h\"\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"../../../lecturecodes/helperfiles/polyfit.h\"\n\nnamespace SemImpRK {\n\n/* SAM_LISTING_BEGIN_0 */\ndouble CvgRosenbrock() {\n  double cvgRate = 0.0;\n  // Use polyfit to estimate the rate of convergence\n  // for SolveRosenbrock.\n  //====================\n  // Your code goes here\n  // explore the order of method 7.4.2 empirically by applying it to the IVP for the limit cycle \n  // use uniform timesteps for size h=2^(-k), k= 4,...,10, and compute a reference solution yref with \n  // timestep size h =2^(-12). Monitor the maximal error on the temporal mesh \n  // max||yj-yref(tj)||2 and use it to estimate a rate of algebraic convergence by means of linear regression. \n\n  Eigen::Matrix2d R; \n  R << 0.0, -1.0, 1.0, 0.0; \n  int lambda =1; \n  auto f [R,lambda](Eigen::VectorXd y) -> Eigen::VectorXd{\n\n    return R*y+lambda*(1-y.squaredNorm())*y; \n  }\n\n  auto df [R, lambda](Eigen::VectorXd y) {\n    Eigen::Matrix2d J; \n    J << lambda*(1-y.squaredNorm())-2*lambda*y(0)*y(0), -1-2*lambda*y(0)*y(1), 1-2*lambda*y(0)*y(1), lambda*(1-y.squaredNorm())-2*lambda*y(0)**2; \n    return J; \n  }\n\n  int M_ref = std::pow(2,12); \n  std::vector<Eigen::VectorXd> res_ref = SolveRosenbrock(f, df, y0, M_ref, T); \n\n  Eigen::ArrayXd K= Eigen::ArrayXd::linspace(7,4,10); \n\n  Eigen::ArrayXd Error(K.size()); \n  Eigen::ArrayXd M(K.size()); \n\n  for (int i=0; i<K.size(); i++){\n    M[i] = std::pow(2,K[i]); \n    std::vector<Eigen::VectorXd> res = SolveRosenbrock(f,df, y0, M[i], T); \n    \n    double maxerr =0; \n\n    for(int j=0; j<res.size(); j++){\n      maxerr = std::max(maxerr, (res[j]-res_ref[j*M_ref/M[i]].norm()); \n    }\n    Error[i] = maxerr; \n  }\n\n\n  SolveRosenbrock(Func &&f, Jac &&df, const Eigen::VectorXd &y0, unsigned int M, double T)\n\n  //====================\n  return cvgRate;\n}\n/* SAM_LISTING_END_0 */\n\n}  // namespace SemImpRK\n", "meta": {"hexsha": "3ea2ec1cdc6d3b9b9ac9c4f8cea6ecaed60a08a9", "size": 2128, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/SemImpRK/mysolution/semimprk.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/SemImpRK/mysolution/semimprk.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/SemImpRK/mysolution/semimprk.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": 27.6363636364, "max_line_length": 146, "alphanum_fraction": 0.6217105263, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.5855652665536364}}
{"text": "// Copyright (C) 2010  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <dlib/optimization.h>\n#include \"optimization_test_functions.h\"\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <vector>\n#include \"../rand.h\"\n\n#include \"tester.h\"\n\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n    using namespace dlib::test_functions;\n\n    logger dlog(\"test.trust_region\");\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename T>\n    struct neg_rosen_model\n    {\n        typedef matrix<T,0,1> column_vector;\n        typedef matrix<T,0,0> general_matrix;\n\n        T operator() ( column_vector x) const\n        {\n            return -static_cast<T>(rosen<T>(x));\n        }\n\n        void get_derivative_and_hessian (\n            const column_vector& x,\n            column_vector& d,\n            general_matrix& h\n        ) const \n        {\n            d = -matrix_cast<T>(rosen_derivative<T>(x));\n            h = -matrix_cast<T>(rosen_hessian<T>(x));\n        }\n\n    };\n\n// ----------------------------------------------------------------------------------------\n\n    dlib::rand rnd;\n\n    template <typename T>\n    void test_with_rosen()\n    {\n        print_spinner();\n\n        matrix<T,2,1> ans;\n        ans = 1,1;\n\n        matrix<T,2,1> p = 100*matrix_cast<T>(randm(2,1,rnd)) - 50;\n\n        T obj = find_min_trust_region(objective_delta_stop_strategy(1e-12, 100), rosen_function_model<T>(), p);\n\n        DLIB_TEST_MSG(std::abs(obj) < 1e-10, \"obj: \" << obj);\n        DLIB_TEST_MSG(length(p-ans) < 1e-5, \"length(p): \" << length(p-ans));\n\n        matrix<T,0,1> p2 = 100*matrix_cast<T>(randm(2,1,rnd)) - 50;\n        obj = find_max_trust_region(objective_delta_stop_strategy(1e-12, 100), neg_rosen_model<T>(), p2);\n\n        DLIB_TEST_MSG(std::abs(obj) < 1e-10, \"obj: \" << obj);\n        DLIB_TEST_MSG(length(p-ans) < 1e-5, \"length(p): \" << length(p-ans));\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_trust_region_sub_problem()\n    {\n        dlog << LINFO << \"subproblem test 1\";\n        {\n            matrix<double,2,2> B;\n            B = 1, 0,\n                0, 1;\n\n            matrix<double,2,1> g, p, ans;\n            g = 0;\n\n            ans = 0;\n\n            solve_trust_region_subproblem(B,g,1,p, 0.001, 10);\n\n            DLIB_TEST(length(p-ans) < 1e-10);\n            solve_trust_region_subproblem(B,g,1,p, 0.001, 1);\n            DLIB_TEST(length(p-ans) < 1e-10);\n        }\n\n        dlog << LINFO << \"subproblem test 2\";\n        {\n            matrix<double,2,2> B;\n            B = 1, 0,\n                0, 1;\n\n            B *= 0.1;\n\n            matrix<double,2,1> g, p, ans;\n            g = 1;\n\n            ans = -g / length(g);\n\n            solve_trust_region_subproblem(B,g,1,p, 1e-6, 20);\n\n            DLIB_TEST(length(p-ans) < 1e-4);\n        }\n\n        dlog << LINFO << \"subproblem test 3\";\n        {\n            matrix<double,2,2> B;\n            B = 0, 0,\n                0, 0;\n\n            matrix<double,2,1> g, p, ans;\n            g = 1;\n\n            ans = -g / length(g);\n\n            solve_trust_region_subproblem(B,g,1,p, 1e-6, 20);\n\n            dlog << LINFO << \"ans: \" << trans(ans);\n            dlog << LINFO << \"p: \" << trans(p);\n            DLIB_TEST(length(p-ans) < 1e-4);\n        }\n        return;\n\n        dlog << LINFO << \"subproblem test 4\";\n        {\n            matrix<double,2,2> B;\n            B = 2, 0,\n                0, -1;\n\n\n            matrix<double,2,1> g, p, ans;\n            g = 0;\n\n            ans = 0, -1;\n\n            solve_trust_region_subproblem(B,g,1,p, 1e-6, 20);\n\n            DLIB_TEST(length(p-ans) < 1e-4);\n        }\n\n\n        dlog << LINFO << \"subproblem test 5\";\n        {\n            matrix<double,2,2> B;\n            B = 2, 0,\n                0, -1;\n\n\n            matrix<double,2,1> g, p, ans;\n            g = 0, 1;\n\n            ans = 0, -1;\n\n            solve_trust_region_subproblem(B,g,1,p, 1e-6, 20);\n\n            DLIB_TEST(length(p-ans) < 1e-4);\n        }\n\n        dlog << LINFO << \"subproblem test 6\";\n        for (int i = 0; i < 10; ++i)\n        {\n            matrix<double,10,10> B;\n\n            B = randm(10,10, rnd);\n\n            B = 0.01*B*trans(B);\n\n\n            matrix<double,10,1> g, p, ans;\n            g = 1;\n\n            solve_trust_region_subproblem(B,g,1,p, 1e-6, 20);\n\n            DLIB_TEST(std::abs(length(p) - 1) < 1e-4);\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_problems()\n    {\n        print_spinner();\n        {\n            matrix<double,4,1> ch;\n\n            ch = brown_start();\n\n            find_min_trust_region(objective_delta_stop_strategy(1e-7, 80),\n                                  brown_function_model(),\n                                  ch);\n\n            dlog << LINFO << \"brown obj: \" << brown(ch);\n            dlog << LINFO << \"brown der: \" << length(brown_derivative(ch));\n            dlog << LINFO << \"brown error: \" << length(ch - brown_solution());\n\n            DLIB_TEST(length(ch - brown_solution()) < 1e-5);\n\n        }\n        print_spinner();\n        {\n            matrix<double,2,1> ch;\n\n            ch = rosen_start<double>();\n\n            find_min_trust_region(objective_delta_stop_strategy(1e-7, 80),\n                                  rosen_function_model<double>(),\n                                  ch);\n\n            dlog << LINFO << \"rosen obj: \" << rosen(ch);\n            dlog << LINFO << \"rosen der: \" << length(rosen_derivative(ch));\n            dlog << LINFO << \"rosen error: \" << length(ch - rosen_solution<double>());\n\n            DLIB_TEST(length(ch - rosen_solution<double>()) < 1e-5);\n        }\n\n        print_spinner();\n        {\n            matrix<double,0,1> ch;\n\n            ch = chebyquad_start(2);\n\n            find_min_trust_region(objective_delta_stop_strategy(1e-7, 80),\n                                  chebyquad_function_model(),\n                                  ch);\n\n            dlog << LINFO << \"chebyquad 2 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"chebyquad 2 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"chebyquad 2 error: \" << length(ch - chebyquad_solution(2));\n\n            DLIB_TEST(length(ch - chebyquad_solution(2)) < 1e-5);\n\n        }\n        print_spinner();\n        {\n            matrix<double,0,1> ch;\n\n            ch = chebyquad_start(4);\n\n            find_min_trust_region(objective_delta_stop_strategy(1e-7, 80),\n                                  chebyquad_function_model(),\n                                  ch);\n\n            dlog << LINFO << \"chebyquad 4 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"chebyquad 4 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"chebyquad 4 error: \" << length(ch - chebyquad_solution(4));\n\n            DLIB_TEST(length(ch - chebyquad_solution(4)) < 1e-5);\n        }\n        print_spinner();\n        {\n            matrix<double,0,1> ch;\n\n            ch = chebyquad_start(6);\n\n            find_min_trust_region(objective_delta_stop_strategy(1e-12, 80),\n                                  chebyquad_function_model(),\n                                  ch);\n\n            dlog << LINFO << \"chebyquad 6 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"chebyquad 6 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"chebyquad 6 error: \" << length(ch - chebyquad_solution(6));\n\n            DLIB_TEST(length(ch - chebyquad_solution(6)) < 1e-5);\n\n        }\n        print_spinner();\n        {\n            matrix<double,0,1> ch;\n\n            ch = chebyquad_start(8);\n\n            find_min_trust_region(objective_delta_stop_strategy(1e-10, 80),\n                                  chebyquad_function_model(),\n                                  ch);\n\n            dlog << LINFO << \"chebyquad 8 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"chebyquad 8 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"chebyquad 8 error: \" << length(ch - chebyquad_solution(8));\n\n            DLIB_TEST(length(ch - chebyquad_solution(8)) < 1e-5);\n        }\n\n    }\n\n\n\n    class optimization_tester : public tester\n    {\n    public:\n        optimization_tester (\n        ) :\n            tester (\"test_trust_region\",\n                    \"Runs tests on the trust region optimization component.\")\n        {}\n\n        void perform_test (\n        )\n        {\n            dlog << LINFO << \"test with rosen<float>\";\n            for (int i = 0; i < 50; ++i)\n                test_with_rosen<float>();\n\n            dlog << LINFO << \"test with rosen<double>\";\n            for (int i = 0; i < 50; ++i)\n                test_with_rosen<double>();\n\n\n            test_trust_region_sub_problem();\n\n            test_problems();\n        }\n    } a;\n\n}\n\n\n", "meta": {"hexsha": "aa2775b9c950da21a570390abeca930cff5964b9", "size": 8958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/trust_region.cpp", "max_stars_repo_name": "yatonon/dlib-face", "max_stars_repo_head_hexsha": "0230c1034ee65d0846d007e6145bfe73ca0d6321", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "dlib/test/trust_region.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "dlib/test/trust_region.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 27.1454545455, "max_line_length": 111, "alphanum_fraction": 0.4642777406, "num_tokens": 2347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.5855652605092657}}
{"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        // \u6b8b\u5dee\u662f\u4e09\u7ef4\u7684,\u53d8\u91cf\u5206\u522b\u662f\u601d\u7ef4\u548c\u4e09\u7ef4\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": "/**\n * @author Alessandro Bianco\n */\n\n/**\n * @addtogroup DFNs\n * @{\n */\n\n#include \"LeastSquaresMinimization.hpp\"\n\n#include <Errors/Assert.hpp>\n#include <Macros/YamlcppMacros.hpp>\n\n#include <opencv2/calib3d.hpp>\n#include <Eigen/Geometry>\n\n#include <stdlib.h>\n#include <fstream>\n\nusing namespace PoseWrapper;\nusing namespace MatrixWrapper;\nusing namespace CorrespondenceMap3DWrapper;\nusing namespace Helpers;\nusing namespace BaseTypesWrapper;\n\nnamespace CDFF\n{\nnamespace DFN\n{\nnamespace Transform3DEstimation\n{\n\nLeastSquaresMinimization::LeastSquaresMinimization()\n{\n        parameters = DEFAULT_PARAMETERS;\n\n\tparametersHelper.AddParameter<float>(\"GeneralParameters\", \"MaximumAllowedError\", parameters.maximumAllowedError, DEFAULT_PARAMETERS.maximumAllowedError);\n\n\tconfigurationFilePath = \"\";\n\tSetPosition(emptyPose, 0, 0, 0);\n\tSetOrientation(emptyPose, 0, 0, 0, 0);\n}\n\nLeastSquaresMinimization::~LeastSquaresMinimization()\n{\n}\n\nvoid LeastSquaresMinimization::configure()\n{\n\tparametersHelper.ReadFile(configurationFilePath);\n\tValidateParameters();\n}\n\nvoid LeastSquaresMinimization::process()\n{\n\tint numberOfCorrespondences = GetNumberOfCorrespondenceMaps(inMatches);\n\tClear(outTransforms);\n\tfor(int mapIndex = 0; mapIndex < numberOfCorrespondences; mapIndex++)\n\t\t{\n\t\tconst CorrespondenceMap3D& map = GetCorrespondenceMap(inMatches, mapIndex);\n\n\t\tcv::Mat coefficientMatrix, valueMatrix;\n\t\tbool success = CreateLinearSystem(map, coefficientMatrix, valueMatrix);\n\n\t\tcv::Mat transformMatrix;\n\t\tif (success)\n\t\t\t{\n\t\t\ttransformMatrix = SolveLinearSystem(coefficientMatrix, valueMatrix, outError);\n\t\t\t}\n\n\t\tif (!success || outError > parameters.maximumAllowedError)\n\t\t\t{\n\t\t\tif (numberOfCorrespondences == 1)\n\t\t\t\t{\n\t\t\t\toutSuccess = false;\n\t\t\t\treturn;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tAddPose(outTransforms, emptyPose);\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tAddTransformOutput(transformMatrix);\n\t\t\t}\n\t\t}\n\toutSuccess = true;\n}\n\nbool LeastSquaresMinimization::CreateLinearSystem(const CorrespondenceMap3D& map, cv::Mat& coefficientMatrix, cv::Mat& valueMatrix)\n\t{\n\tconst float EPSILON = 0.00001;\n\tconst int NUMBER_OF_DEGREES_OF_FREEDOM = 6;\n\tconst int NUMBER_OF_VARIABLES = 12;\n\n\tcoefficientMatrix = cv::Mat();\n\tvalueMatrix = cv::Mat();\n\tfor(int correspondenceIndex = 0; correspondenceIndex < GetNumberOfCorrespondences(map); correspondenceIndex++)\n\t\t{\n\t\tPoint3D source = GetSource(map, correspondenceIndex);\n\t\tPoint3D sink = GetSink(map, correspondenceIndex);\n\t\n\t\tif (source.x != source.x || source.y != source.y || source.z != source.z || sink.x != sink.x || sink.y != sink.y || sink.z != sink.z)\n\t\t\t{\n\t\t\tcontinue;\n\t\t\t}\n\n\t\tcv::Mat coefficientMatrixPart = ( cv::Mat_<float>(3, 12) << \n\t\t\tsource.x, source.y, source.z, 1,    0, 0, 0, 0,    0, 0, 0, 0,\n\t\t\t0, 0, 0, 0,   source.x, source.y, source.z, 1,     0, 0, 0, 0,\n\t\t\t0, 0, 0, 0,   0, 0, 0, 0,     source.x, source.y, source.z, 1 );\n\t\tcv::Mat valueMatrixPart = ( cv::Mat_<float>(3, 1) << sink.x, sink.y, sink.z);\n\t\t\n\t\tif (coefficientMatrix.rows == 0)\n\t\t\t{\n\t\t\tcoefficientMatrix = coefficientMatrixPart;\n\t\t\tvalueMatrix = valueMatrixPart;\n\t\t\t}\t\t\n\t\telse\n\t\t\t{\n\t\t\tcv::Mat matrixList[2] = {coefficientMatrix, coefficientMatrixPart};\n\t\t\tcv::vconcat(matrixList, 2, coefficientMatrix);\n\t\t\tmatrixList[0] = valueMatrix;\n\t\t\tmatrixList[1] = valueMatrixPart;\n\t\t\tcv::vconcat(matrixList, 2, valueMatrix);\n\t\t\t}\n\t\t}\n\n\tif ( coefficientMatrix.rows < NUMBER_OF_VARIABLES )\n\t\t{\n\t\treturn false;\n\t\t}\n\n\tcv::Mat singulaValueMatrix;\n\tcv::SVD::compute(coefficientMatrix, singulaValueMatrix);\n\tint rank = cv::countNonZero( singulaValueMatrix > EPSILON );\n\treturn ( rank >= NUMBER_OF_DEGREES_OF_FREEDOM );\n\t}\n\ncv::Mat LeastSquaresMinimization::SolveLinearSystem(cv::Mat coefficientMatrix, cv::Mat valueMatrix, float& error)\n\t{\n\tcv::Mat pseudoInverse;\n\tcv::invert(coefficientMatrix, pseudoInverse, cv::DECOMP_SVD);\n\tcv::Mat transformMatrix = pseudoInverse * valueMatrix;\n\n\tcv::Mat errorMatrix = coefficientMatrix * transformMatrix - valueMatrix;\n\terror = cv::norm(errorMatrix);\n\treturn transformMatrix;\n\t}\n\nvoid LeastSquaresMinimization::AddTransformOutput(cv::Mat transformMatrix)\n\t{\n\tcv::Mat rotationMatrix = (cv::Mat_<float>(3, 3) << \n\t\ttransformMatrix.at<float>(0), transformMatrix.at<float>(1), transformMatrix.at<float>(2),\n\t\ttransformMatrix.at<float>(4), transformMatrix.at<float>(5), transformMatrix.at<float>(6),\n\t\ttransformMatrix.at<float>(8), transformMatrix.at<float>(9), transformMatrix.at<float>(10) );\n\tcv::Mat translationVector = (cv::Mat_<float>(3,1) << transformMatrix.at<float>(3), transformMatrix.at<float>(7), transformMatrix.at<float>(11));\n\t\n\tcv::Mat position = - rotationMatrix.inv() * translationVector;\n\n\tPose3D pose;\n\tSetPosition(pose, position.at<float>(0, 0), position.at<float>(1, 0), position.at<float>(2, 0) );\n\n\tfloat qw = std::sqrt(1.00 + rotationMatrix.at<float>(0,0) + rotationMatrix.at<float>(1,1) + rotationMatrix.at<float>(2,2)) / 2;\n\tfloat qx = (rotationMatrix.at<float>(2,1) - rotationMatrix.at<float>(1,2)) / ( 4 * qw );\n\tfloat qy = (rotationMatrix.at<float>(0,2) - rotationMatrix.at<float>(2,0)) / ( 4 * qw );\n\tfloat qz = (rotationMatrix.at<float>(1,0) - rotationMatrix.at<float>(0,1)) / ( 4 * qw );\n\tSetOrientation(pose, qx, qy, qz, qw);\n\n\tAddPose(outTransforms, pose);\n\t}\n\nconst LeastSquaresMinimization::LeastSquaresMinimizationOptionsSet LeastSquaresMinimization::DEFAULT_PARAMETERS =\n{\n\t/*.maximumAllowedError =*/ 0.001\n};\n\nvoid LeastSquaresMinimization::ValidateParameters()\n{\n\tASSERT(parameters.maximumAllowedError > 0, \"LeastSquaresMinimization Configuration Error: maximumAllowedError has to be positive\");\n}\n\nvoid LeastSquaresMinimization::ValidateInputs(const CorrespondenceMap3D& map)\n{\n\t\n}\n\n}\n}\n}\n\n/** @} */\n", "meta": {"hexsha": "b6f43cea7aa31f4d272db1a230c2fbf07a00e8ad", "size": 5650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DFNs/Transform3DEstimation/LeastSquaresMinimization.cpp", "max_stars_repo_name": "H2020-InFuse/cdff", "max_stars_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T15:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T07:39:01.000Z", "max_issues_repo_path": "DFNs/Transform3DEstimation/LeastSquaresMinimization.cpp", "max_issues_repo_name": "H2020-InFuse/cdff", "max_issues_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DFNs/Transform3DEstimation/LeastSquaresMinimization.cpp", "max_forks_repo_name": "H2020-InFuse/cdff", "max_forks_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-06T12:09:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T12:09:05.000Z", "avg_line_length": 28.9743589744, "max_line_length": 154, "alphanum_fraction": 0.7201769912, "num_tokens": 1563, "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": "// Example 2: Matrices and vectors\n// source:\n// http://eigen.tuxfamily.org/dox/GettingStarted.html#title0\n// Compile: g++ -I /usr/include/eigen3/ eigen_ex2.cpp -o eigen_ex2\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(void)\n{\n    MatrixXd m = MatrixXd::Random(3,3);\n    m = (m + MatrixXd::Constant(3, 3, 1.2)) * 50;\n    cout << \"m = \" << '\\n' << m << '\\n';\n    VectorXd v(3);\n    v << 1, 2, 3;\n    cout << \"m * v = \" << '\\n' << m * v << '\\n';\n    return 0;\n}\n", "meta": {"hexsha": "33fda8f3b0e8e6a7ddba6b9a5d41e7544e8a2756", "size": 513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen_practice/eigen_ex2.cpp", "max_stars_repo_name": "RobinCPC/ros_tutorials", "max_stars_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Eigen_practice/eigen_ex2.cpp", "max_issues_repo_name": "RobinCPC/ros_tutorials", "max_issues_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Eigen_practice/eigen_ex2.cpp", "max_forks_repo_name": "RobinCPC/ros_tutorials", "max_forks_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T06:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-29T06:32:54.000Z", "avg_line_length": 24.4285714286, "max_line_length": 66, "alphanum_fraction": 0.5730994152, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5851743316364825}}
{"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": "#include <iostream>\n#include <string>\n#include <numeric>\n#include <algorithm>\n#include <vector>\n#include <array>\n#include <boost/algorithm/string.hpp>\n\nstd::vector<std::vector<int>> generateAll(int limit, const std::vector<std::vector<int>>& input, bool find = false);\n\n// This are the values provided in the quiz input. This solution is not very flexible, but\n// get's the problem solved\nstd::array<std::array<int, 5>, 4> properties = {{{4, -2,  0, 0, 5},\n\t\t\t\t\t\t {0,  5, -1, 0, 8},\n\t\t\t\t\t\t {-1, 0,  5, 0, 6},\n\t\t\t\t\t\t {0,  0, -2, 2, 1}}};\n\nint main (int argc, char** argv) {\n  std::string line;\n\n  int limit = 100;\n  int elements = 4;\n  std::vector<std::vector<int>> v;\n  for(int i = 0 ; i < elements - 1; ++i) {\n    v = generateAll(limit, v); \n  }\n  // For the last generation iteration we just want to print out the max value\n  generateAll(limit, v, true);\n}\n\nstd::vector<std::vector<int>> generateAll(int limit, const std::vector<std::vector<int>>& input,\n\t\t\t\t\t  bool find) {\n  std::vector<std::vector<int>> output;\n\n  // The input vector is empty, fill it please\n  if (input.size() == 0) {\n    for(int i = 0 ; i <= limit ; ++i) {\n      output.push_back({i});\n    }\n    return std::move(output);\n  }\n  \n  int max = 0;\n  for(auto& v : input) {\n    for(int i = 0 ; i <= limit ; ++i) {\n      auto vCopy = v;\n      vCopy.push_back(i);\n\n      // Do not add options that add up to more than the limit otherwise\n      // memory explodes. In fact memory explodes with more than 3 different\n      // elements. This is why we use \"find\" hack, to not store in memory\n      // the vector with the 4 elements.\n      if(std::accumulate(vCopy.begin(), vCopy.end(), 0) <= limit) {\n\tif(find) {\n\t  int total = 1;\n\t  for(int i = 0 ; i < 4 ; ++i) {\n\t    int propTotal = 0;\n\t    for(int j = 0 ; j < vCopy.size() ; ++ j) {\n\t      propTotal += (vCopy[j] * properties[j][i]);\n\t    }\n\t    total *= (propTotal > 0) ? propTotal : 0;\n\t  }\n\t  max = std::max(total, max);\n\t} else {\n\t  output.push_back(std::move(vCopy));\n\t}\n      } else {\n\tbreak;\n      }\n    }    \n  }\n  if(find)\n    std::cout << \"Max Total \" << max << std::endl;\n  return std::move(output);\n}\n", "meta": {"hexsha": "10628671d3921c4f4c5f85f215ede430241ae5eb", "size": 2132, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "15/15.cpp", "max_stars_repo_name": "julitopower/AdventOfCode2015", "max_stars_repo_head_hexsha": "42577266d7d38b60bc8f5800c9c5f9a49705a728", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "15/15.cpp", "max_issues_repo_name": "julitopower/AdventOfCode2015", "max_issues_repo_head_hexsha": "42577266d7d38b60bc8f5800c9c5f9a49705a728", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "15/15.cpp", "max_forks_repo_name": "julitopower/AdventOfCode2015", "max_forks_repo_head_hexsha": "42577266d7d38b60bc8f5800c9c5f9a49705a728", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0526315789, "max_line_length": 116, "alphanum_fraction": 0.5783302064, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5851384059659048}}
{"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": "#ifndef STACK_HH\n#define STACK_HH\n\n// Stack classes\n//\n// These are the low-level classes that implement feed-forward and\n// recurrent neural networks. All the Eigen-dependant code in this\n// library should live in this file.\n//\n// To keep the Eigen code out of the high-level interface, the STL ->\n// Eigen ``preprocessor'' classes are also defined here.\n//\n// The ordering of classes is as follows:\n//  - Feed-forward Stack class\n//  - Feed-forward Layer classes\n//  - RecurrentStack class\n//  - Recurrent layers\n//  - Activation functions\n//  - Various utility functions\n\n\n#include \"Exceptions.hh\"\n#include \"NNLayerConfig.hh\"\n\n#include <Eigen/Dense>\n\n#include <vector>\n#include <functional>\n\nnamespace lwt {\n\n  using Eigen::VectorXd;\n  using Eigen::MatrixXd;\n\n  class ILayer;\n  class IRecurrentLayer;\n\n\n  // ______________________________________________________________________\n  // Feed forward Stack class\n\n  class Stack\n  {\n  public:\n    // constructor for dummy net\n    Stack();\n    // constructor for real net\n    Stack(size_t n_inputs, const std::vector<LayerConfig>& layers,\n          size_t skip_layers = 0);\n    ~Stack();\n\n    // make non-copyable for now\n    Stack(Stack&) = delete;\n    Stack& operator=(Stack&) = delete;\n\n    VectorXd compute(VectorXd) const;\n    size_t n_outputs() const;\n\n  private:\n    // returns the size of the next layer\n    size_t add_layers(size_t n_inputs, const LayerConfig&);\n    size_t add_dense_layers(size_t n_inputs, const LayerConfig&);\n    size_t add_normalization_layers(size_t n_inputs, const LayerConfig&);\n    size_t add_highway_layers(size_t n_inputs, const LayerConfig&);\n    size_t add_maxout_layers(size_t n_inputs, const LayerConfig&);\n    std::vector<ILayer*> m_layers;\n    size_t m_n_outputs;\n  };\n\n  // _______________________________________________________________________\n  // Feed-forward layers\n\n  class ILayer\n  {\n  public:\n    virtual ~ILayer() {}\n    virtual VectorXd compute(const VectorXd&) const = 0;\n  };\n\n  class DummyLayer: public ILayer\n  {\n  public:\n    virtual VectorXd compute(const VectorXd&) const;\n  };\n\n  class UnaryActivationLayer: public ILayer\n  {\n  public:\n    UnaryActivationLayer(Activation);\n    virtual VectorXd compute(const VectorXd&) const;\n  private:\n    std::function<double(double)> m_func;\n  };\n\n  class SoftmaxLayer: public ILayer\n  {\n  public:\n    virtual VectorXd compute(const VectorXd&) const;\n  };\n\n  class BiasLayer: public ILayer\n  {\n  public:\n    BiasLayer(const VectorXd& bias);\n    BiasLayer(const std::vector<double>& bias);\n    virtual VectorXd compute(const VectorXd&) const;\n  private:\n    VectorXd m_bias;\n  };\n\n  class MatrixLayer: public ILayer\n  {\n  public:\n    MatrixLayer(const MatrixXd& matrix);\n    virtual VectorXd compute(const VectorXd&) const;\n  private:\n    MatrixXd m_matrix;\n  };\n\n  class MaxoutLayer: public ILayer\n  {\n  public:\n    typedef std::pair<MatrixXd, VectorXd> InitUnit;\n    MaxoutLayer(const std::vector<InitUnit>& maxout_tensor);\n    virtual VectorXd compute(const VectorXd&) const;\n  private:\n    std::vector<MatrixXd> m_matrices;\n    MatrixXd m_bias;\n  };\n\n\n  /// Normalization layer ///\n  /// https://arxiv.org/abs/1502.03167 ///\n  class NormalizationLayer : public ILayer\n  {\n\n  public:\n    NormalizationLayer(const VectorXd& W,const VectorXd& b);\n    virtual VectorXd compute(const VectorXd&) const;\n\n  private:\n    VectorXd _W;\n    VectorXd _b;\n\n  };\n\n  //http://arxiv.org/pdf/1505.00387v2.pdf\n  class HighwayLayer: public ILayer\n  {\n  public:\n    HighwayLayer(const MatrixXd& W,\n                 const VectorXd& b,\n                 const MatrixXd& W_carry,\n                 const VectorXd& b_carry,\n                 Activation activation);\n    virtual VectorXd compute(const VectorXd&) const;\n  private:\n    MatrixXd m_w_t;\n    VectorXd m_b_t;\n    MatrixXd m_w_c;\n    VectorXd m_b_c;\n    std::function<double(double)> m_act;\n  };\n\n  // ______________________________________________________________________\n  // Recurrent Stack\n\n  class RecurrentStack\n  {\n  public:\n    RecurrentStack(size_t n_inputs, const std::vector<LayerConfig>& layers);\n    ~RecurrentStack();\n    RecurrentStack(RecurrentStack&) = delete;\n    RecurrentStack& operator=(RecurrentStack&) = delete;\n    VectorXd reduce(MatrixXd inputs) const;\n    size_t n_outputs() const;\n  private:\n    std::vector<IRecurrentLayer*> m_layers;\n    size_t add_lstm_layers(size_t n_inputs, const LayerConfig&);\n    size_t add_gru_layers(size_t n_inputs, const LayerConfig&);\n    size_t add_embedding_layers(size_t n_inputs, const LayerConfig&);\n    Stack* m_stack;\n  };\n\n\n  // __________________________________________________________________\n  // Recurrent layers\n\n  class IRecurrentLayer\n  {\n  public:\n    virtual ~IRecurrentLayer() {}\n    virtual MatrixXd scan( const MatrixXd&) const = 0;\n  };\n\n  class EmbeddingLayer : public IRecurrentLayer\n  {\n  public:\n    EmbeddingLayer(int var_row_index, MatrixXd W);\n    virtual ~EmbeddingLayer() {};\n    virtual MatrixXd scan( const MatrixXd&) const;\n\n  private:\n    int m_var_row_index;\n    MatrixXd m_W;\n  };\n\n  /// long short term memory ///\n  struct LSTMState;\n  class LSTMLayer : public IRecurrentLayer\n  {\n  public:\n    LSTMLayer(Activation activation, Activation inner_activation,\n              MatrixXd W_i, MatrixXd U_i, VectorXd b_i,\n              MatrixXd W_f, MatrixXd U_f, VectorXd b_f,\n              MatrixXd W_o, MatrixXd U_o, VectorXd b_o,\n              MatrixXd W_c, MatrixXd U_c, VectorXd b_c);\n\n    virtual ~LSTMLayer() {};\n    virtual MatrixXd scan( const MatrixXd&) const;\n    void step( const VectorXd& input, LSTMState& ) const;\n\n  private:\n    std::function<double(double)> m_activation_fun;\n    std::function<double(double)> m_inner_activation_fun;\n\n    MatrixXd m_W_i;\n    MatrixXd m_U_i;\n    VectorXd m_b_i;\n\n    MatrixXd m_W_f;\n    MatrixXd m_U_f;\n    VectorXd m_b_f;\n\n    MatrixXd m_W_o;\n    MatrixXd m_U_o;\n    VectorXd m_b_o;\n\n    MatrixXd m_W_c;\n    MatrixXd m_U_c;\n    VectorXd m_b_c;\n\n    int m_n_outputs;\n  };\n\n  /// gated recurrent unit ///\n  struct GRUState;\n  class GRULayer : public IRecurrentLayer\n  {\n  public:\n    GRULayer(Activation activation, Activation inner_activation,\n             MatrixXd W_z, MatrixXd U_z, VectorXd b_z,\n             MatrixXd W_r, MatrixXd U_r, VectorXd b_r,\n             MatrixXd W_h, MatrixXd U_h, VectorXd b_h);\n\n    virtual ~GRULayer() {};\n    virtual MatrixXd scan( const MatrixXd&) const;\n    void step( const VectorXd& input, GRUState& ) const;\n\n  private:\n    std::function<double(double)> m_activation_fun;\n    std::function<double(double)> m_inner_activation_fun;\n\n    MatrixXd m_W_z;\n    MatrixXd m_U_z;\n    VectorXd m_b_z;\n\n    MatrixXd m_W_r;\n    MatrixXd m_U_r;\n    VectorXd m_b_r;\n\n    MatrixXd m_W_h;\n    MatrixXd m_U_h;\n    VectorXd m_b_h;\n\n    int m_n_outputs;\n  };\n\n  // ______________________________________________________________________\n  // Activation functions\n\n  // note that others are supported but are too simple to\n  // require a special function\n  double nn_sigmoid( double x );\n  double nn_hard_sigmoid( double x );\n  double nn_tanh( double x );\n  double nn_relu( double x );\n  std::function<double(double)> get_activation(lwt::Activation);\n\n  // WARNING: you own this pointer! Only call when assigning to member data!\n  ILayer* get_raw_activation_layer(Activation);\n\n  // ______________________________________________________________________\n  // utility functions\n\n  // functions to build up basic units from vectors\n  MatrixXd build_matrix(const std::vector<double>& weights, size_t n_inputs);\n  VectorXd build_vector(const std::vector<double>& bias);\n\n  // consistency checks\n  void throw_if_not_maxout(const LayerConfig& layer);\n  void throw_if_not_dense(const LayerConfig& layer);\n  void throw_if_not_normalization(const LayerConfig& layer);\n\n  // LSTM component for convenience in some layers\n  struct DenseComponents\n  {\n    Eigen::MatrixXd W;\n    Eigen::MatrixXd U;\n    Eigen::VectorXd b;\n  };\n  DenseComponents get_component(const lwt::LayerConfig& layer, size_t n_in);\n\n\n}\n\n#endif // STACK_HH\n", "meta": {"hexsha": "02cd681a291a8e85b032fb1a1b0435c7ecd36dbe", "size": 8053, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/lwtnn/Stack.hh", "max_stars_repo_name": "mickypaganini/lwtnn", "max_stars_repo_head_hexsha": "7032e70aeb7d21e2074830f87d37696b407cf519", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T00:31:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T00:31:00.000Z", "max_issues_repo_path": "include/lwtnn/Stack.hh", "max_issues_repo_name": "mickypaganini/lwtnn", "max_issues_repo_head_hexsha": "7032e70aeb7d21e2074830f87d37696b407cf519", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-05-09T07:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-09T08:25:10.000Z", "max_forks_repo_path": "include/lwtnn/Stack.hh", "max_forks_repo_name": "mickypaganini/lwtnn", "max_forks_repo_head_hexsha": "7032e70aeb7d21e2074830f87d37696b407cf519", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3238993711, "max_line_length": 77, "alphanum_fraction": 0.7032161927, "num_tokens": 1970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5851383955421408}}
{"text": "//\n//  Copyright Toon Knapen, Karl Meerbergen\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include \"../../blas/test/random.hpp\"\n\n#include <boost/numeric/bindings/lapack/steqr.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <algorithm>\n#include <limits>\n#include <iostream>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\n\ntemplate <typename T>\nint do_value_type() {\n   const int n = 10 ;\n\n   typedef typename boost::numeric::bindings::traits::type_traits<T>::real_type real_type ;\n   typedef std::complex< real_type >                                            complex_type ;\n\n   typedef ublas::matrix<T, ublas::column_major> matrix_type ;\n   typedef ublas::vector<T>                      vector_type ;\n   real_type safety_factor (1.5);\n\n   // Set matrix\n   matrix_type z( n, n );\n   vector_type d( n ), e ( n - 1 ) ;\n\n   std::fill( d.begin(), d.end(), 2.0 ) ;\n   std::fill( e.begin(), e.end(), -1.0 ) ;\n\n   // Compute eigendecomposition.\n   lapack::steqr( 'I', d, e, z ) ;\n\n   for ( int i=0; i<d.size(); ++i) {\n     T sum( 0.0 ) ;\n     for (int j=0; j<d.size(); ++j) {\n       sum += z(i,j)*z(i,j) * d(j) ;\n     }\n     if (std::abs( sum - 2.0 ) > safety_factor*10 * std::numeric_limits<T>::epsilon() ) return 1 ;\n\n     if (i>0) {\n       sum = 0.0 ;\n       for (int j=0; j<d.size(); ++j) {\n         sum += z(i-1,j)*z(i,j) * d(j) ;\n       }\n       if (std::abs( sum + 1.0 ) > safety_factor*10 * std::numeric_limits<T>::epsilon() ) return 1 ;\n     }\n   }\n\n   return 0 ;\n} // do_value_type()\n\n\n\nint main() {\n   // Run tests for different value_types\n   std::cout << \"float\\n\" ;\n   if (do_value_type<float>()) return 255;\n   std::cout << \"double\\n\" ;\n   if (do_value_type<double>()) return 255;\n\n   std::cout << \"Regression test succeeded\\n\" ;\n   return 0;\n}\n\n", "meta": {"hexsha": "4443b2d4835567f3d2aef5e81512d1a37a4a56c7", "size": 2043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_steqr.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_steqr.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_steqr.cpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5324675325, "max_line_length": 100, "alphanum_fraction": 0.5937347039, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5851302742938268}}
{"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": "#ifndef WZP_EIGEN_MATRIX_HPP_\n#define WZP_EIGEN_MATRIX_HPP_\n\n/**\n * This is just a wapper for eigen matrix(DYNAMIC)\n */\n#include <cassert>\n\n#include <Eigen/Dense>\n\n\nnamespace wzp\n{\n\ntemplate<typename Dtype>\nclass EMatrix {\nprivate:\n    // the alias for inner use of raw eigen matrix\n    template<typename F>\n    using RawMatrix = Eigen::Matrix<F, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n    // define the index type\n    typedef Eigen::Index Index;\n\npublic:\n    /**\n     * Constructors\n     */\n    // default contructor\n    EMatrix() : m_mat() {}\n\n    // construct by size\n    EMatrix(Index m) : m_mat(m, m) { InitByValue(0); }\n\n    // construct by two size\n    EMatrix(Index m, Index n, Dtype init_val = 0) : m_mat(m, n) {InitByValue(init_val); }\n\n    // construct by raw point\n    EMatrix(Index m, Index n, Dtype* raw_data_ptr) {\n        m_mat = std::move(Eigen::Map<RawMatrix<Dtype>>(raw_data_ptr, m, n));\n    }\n\n    // construct by datas\n    EMatrix(RawMatrix<Dtype>&& raw_mat) : m_mat(std::move(raw_mat)) {}\n    EMatrix(const RawMatrix<Dtype>& raw_mat) : m_mat(raw_mat) {}\n\n    // move construct\n    EMatrix(EMatrix<Dtype>&& other) : m_mat(std::move(other.m_mat)) { }\n\n    // move operator\n    EMatrix<Dtype>& operator= (EMatrix<Dtype>&& other) {\n        assert(this != &other);\n        m_mat = std::move(other.m_mat);\n        return *this;\n    }\n\n    // copy constructor\n    EMatrix(const EMatrix<Dtype>&) = default;\n    EMatrix<Dtype>& operator= (const EMatrix<Dtype>&) = default;\n\n    // get the raw matrix\n    inline RawMatrix<Dtype>& get_raw_mat() { return m_mat; }\n    inline const RawMatrix<Dtype>& get_raw_mat() const { return m_mat; }\n\n    /**\n     * reshape functions\n     */\n    inline void reshape(Index m, Index n) {\n        if(m == m_mat.rows() && n == m_mat.cols()) return;\n        m_mat.resize(m, n);\n    }\n\n    /**\n     * transpose and adjoint\n     */\n    // transpose\n    EMatrix<Dtype> transpose() const {\n        auto tmp = m_mat.transpose();\n        return EMatrix<Dtype>(std::move(tmp));\n    }\n\n    // adjoint\n    EMatrix<Dtype> adjoint() const {\n        auto tmp = m_mat.adjoint();\n        return EMatrix<Dtype>(std::move(tmp));\n    }\n\n    /**\n     * operations by contant value\n     */\n    // scalar product\n    EMatrix<Dtype> operator* (Dtype val) const {\n        auto tmp = m_mat * val;\n        return EMatrix<Dtype>(std::move(tmp));\n    }\n\n    EMatrix<Dtype>& operator*= (Dtype val) {\n        m_mat *= val;\n        return *this;\n    }\n\n    // scalar +\n    EMatrix<Dtype> operator+ (Dtype val) const {\n        auto tmp = m_mat + val;\n        return EMatrix<Dtype>(std::move(tmp));\n    }\n\n    EMatrix<Dtype>& operator+= (Dtype val) {\n        m_mat += val;\n        return *this;\n    }\n\n    // scalar -\n    EMatrix<Dtype> operator- (Dtype val) const {\n        auto tmp = m_mat - val;\n        return EMatrix<Dtype>(std::move(tmp));\n    }\n\n    EMatrix<Dtype>& operator-= (Dtype val) {\n        m_mat -= val;\n        return *this;\n    }\n\n    // matrix dot product\n    EMatrix<Dtype> operator* (const EMatrix<Dtype>& other) const {\n        auto tmp = m_mat * other.get_raw_mat();\n        return EMatrix<Dtype>(std::move(tmp));\n    }\n\n    // matrix add function\n    EMatrix<Dtype> operator+ (const EMatrix<Dtype>& other) const {\n        if(other.rows() == 1) {\n            assert(other.cols() == cols());\n            EMatrix<Dtype> tmp_mat(*this);\n            for(Index i = 0; i < rows(); ++i) {\n                for(Index j = 0; j < cols(); ++j) {\n                    tmp_mat.at(i, j) += other(0, j);\n                }\n            }\n            return tmp_mat;\n        } else if(other.cols() == 1) {\n            assert(other.rows() == rows());\n            EMatrix<Dtype> tmp_mat(*this);\n            for(Index j = 0; j < cols(); ++j) {\n                for(Index i = 0; i < rows(); ++i) {\n                    tmp_mat.at(i, j) += other(i, 0);\n                }\n            }\n            return tmp_mat;\n        } else {\n            auto tmp = m_mat + other.get_raw_mat();\n            return EMatrix<Dtype>(std::move(tmp));\n        }\n    }\n\n    EMatrix<Dtype>& operator+= (const EMatrix<Dtype>& other) {\n        if(other.rows() == 1) {\n            assert(other.cols() == cols());\n            for(Index i = 0; i < rows(); ++i) {\n                for(Index j = 0; j < cols(); ++j) {\n                    at(i, j) += other(0, j);\n                }\n            }\n        } else if(other.cols() == 1) {\n            assert(other.rows() == rows());\n            EMatrix<Dtype> tmp_mat(*this);\n            for(Index j = 0; j < cols(); ++j) {\n                for(Index i = 0; i < rows(); ++i) {\n                    at(i, j) += other(i, 0);\n                }\n            }\n        } else {\n            m_mat += other.get_raw_mat();\n        }\n        return *this;\n    }\n\n    /**\n     * Block\n     */\n    EMatrix<Dtype> block(Index i, Index j, Index h, Index w) const {\n        auto tmp = m_mat.block(i, j, h, w);\n        return EMatrix<Dtype>(std::move(tmp));\n    }\n\n    EMatrix<Dtype> row(Index i) const {\n        auto tmp = m_mat.row(i);\n        return EMatrix<Dtype>(std::move(tmp));\n    }\n\n    EMatrix<Dtype> col(Index j) const {\n        auto tmp = m_mat.col(j);\n        return EMatrix<Dtype>(std::move(tmp));\n    }\n\n    void mutable_row(Index i, const EMatrix<Dtype>& row_vec) {\n        m_mat.row(i) = row_vec.get_raw_mat();\n    }\n\n    void mutable_col(Index j, const EMatrix<Dtype>& col_vec) {\n        m_mat.col(j) = col_vec.get_raw_mat();\n    }\n\n    /**\n     * Getters\n     */\n    inline bool empty() const { return m_mat.rows() == 0; }\n    inline Index rows() const { return m_mat.rows(); }\n    inline Index cols() const { return m_mat.cols(); }\n    inline Dtype at(Index i, Index j) const { return m_mat(i, j); }\n    inline Dtype& at(Index i, Index j) { return m_mat(i, j); }\n    inline Dtype operator() (Index i, Index j) const { return at(i, j); }\n    inline Dtype& operator() (Index i, Index j) { return at(i, j); }\n    inline Dtype at(Index i) const { return m_mat(i); }\n    inline Dtype& at(Index i) { return m_mat(i); }\n    inline Dtype operator() (Index i) const { return at(i); }\n    inline Dtype& operator() (Index i) { return at(i); }\n\n    /**\n     * some simple function\n     */\n    inline Dtype sum() const { return m_mat.sum(); }\n    inline Dtype prod() const { return m_mat.prod(); }\n    inline Dtype min() const { return m_mat.minCoeff(); }\n    inline Dtype max() const { return m_mat.maxCoeff(); }\n    inline Dtype trace() const { return m_mat.trace(); }\n\n    /**\n     * the print functions\n     */\n    inline friend std::ostream& operator<<(std::ostream &os, const EMatrix<Dtype>& e) {\n        os << e.m_mat;\n        return os;\n    }\n\nprivate:\n    //the contranier of matrix datas\n    RawMatrix<Dtype> m_mat;\n\nprivate:\n\n    void InitByValue(Dtype val) {\n        Index length = m_mat.rows() * m_mat.cols();\n        for(Index i = 0; i < length; ++i) {\n            m_mat(i) = val;\n        }\n    }\n\npublic:\n    // the function to apply element wise operation\n    template<typename Fun, typename... Args>\n    void element_apply(Index i, Index j, Index p, Index q, Fun&& fun, Args&&... args) {\n        assert(i >= 0 && j >= 0 && i + p < rows() && j + q < cols());\n        for(Index ii = i; ii < i + p; ++ii) {\n            for(Index jj = j; jj < j + q; ++jj) {\n                m_mat(ii, jj) = fun(std::forward<Args>(args)...);\n            }\n        }\n    }\n\n};\n\n\n} //wzp\n\n\n#endif /*WZP_EIGEN_MATRIX_HPP_*/", "meta": {"hexsha": "feac128da8d7f4707a75ad872dc38ab159e0d167", "size": 7439, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdparty/wzp_cpp_lib/container/ematrix.hpp", "max_stars_repo_name": "wzppengpeng/LittleConv", "max_stars_repo_head_hexsha": "12aab4cfbbe965fa8b4053bb464db1165cc4ec31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2017-10-25T07:48:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:18:11.000Z", "max_issues_repo_path": "3rdparty/wzp_cpp_lib/container/ematrix.hpp", "max_issues_repo_name": "wzppengpeng/LittleConv", "max_issues_repo_head_hexsha": "12aab4cfbbe965fa8b4053bb464db1165cc4ec31", "max_issues_repo_licenses": ["MIT"], "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/wzp_cpp_lib/container/ematrix.hpp", "max_forks_repo_name": "wzppengpeng/LittleConv", "max_forks_repo_head_hexsha": "12aab4cfbbe965fa8b4053bb464db1165cc4ec31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-02-06T10:01:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T09:26:40.000Z", "avg_line_length": 27.861423221, "max_line_length": 89, "alphanum_fraction": 0.5324640409, "num_tokens": 2013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5850525879758675}}
{"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 <cmath>\n#include <memory>\n#include <utility>\n\n#include <Eigen/Core>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n\n#include <geometric-vision/linear-triangulation.h>\n#include <maplab-common/pose_types.h>\n#include <maplab-common/quaternion-math.h>\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\nusing namespace geometric_vision;  // NOLINT\n\nclass GeometricVisionTwoViewTriangulationTest\n    : public ::testing::TestWithParam<std::pair<double, double> > {};  // NOLINT\n\nTEST_P(GeometricVisionTwoViewTriangulationTest, ParallelOpticalAxes) {\n  LinearTriangulation triangulator;\n\n  pose::Transformation camera0(\n      pose::Position3D(0, 0, 0), pose::Quaternion(1, 0, 0, 0));\n  pose::Transformation camera1(\n      pose::Position3D(1, 0, 0), pose::Quaternion(1, 0, 0, 0));\n\n  std::pair<double, double> measurements = GetParam();\n  Eigen::Vector2d measurement0(measurements.first, 0);\n  Eigen::Vector2d measurement1(measurements.second, 0);\n\n  Eigen::Vector3d triangulated_point;\n  EXPECT_TRUE(\n      triangulator.triangulateFromNormalizedTwoViews(\n          measurement0, camera0, measurement1, camera1, &triangulated_point));\n\n  // Calculation of expected result.\n  const double b = camera0.getPosition()(0) - camera1.getPosition()(0);\n  const double f = 1;\n  const double Z = (b * f) / (measurement0(0) - measurement1(0));\n  const double X = measurement0(0) * Z / f;\n  const double Y = measurement0(1) * Z / f;\n  Eigen::Vector3d expected_result(X, Y, Z);\n\n  EXPECT_NEAR_EIGEN(expected_result, triangulated_point, 1e-15);\n}\n\nINSTANTIATE_TEST_CASE_P(\n    GeometricVision, GeometricVisionTwoViewTriangulationTest,\n    ::testing::Values(\n        std::pair<double, double>(0.1, -0.1),\n        std::pair<double, double>(0.2, -0.2),\n        std::pair<double, double>(0.1, -0.2),\n        std::pair<double, double>(0.05, -0.4),\n        std::pair<double, double>(0.3, 0.0)));\n\nstruct TriangulationParams {\n  TriangulationParams(\n      double camera1_rotation_y, double camera1_x, double camera1_y,\n      double camera1_z, double G_p_fi_x, double G_p_fi_y, double G_p_fi_z)\n      : camera1_rotation_Y_(camera1_rotation_y),\n        camera1_position_(camera1_x, camera1_y, camera1_z),\n        G_p_fi_(G_p_fi_x, G_p_fi_y, G_p_fi_z) {}\n\n  double camera1_rotation_Y_;\n  Eigen::Vector3d camera1_position_;\n  Eigen::Vector3d G_p_fi_;\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\nclass GeometricVisionRotatedTwoViewParamTest\n    : public ::testing::TestWithParam<TriangulationParams> {\n protected:\n  Eigen::Vector2d reprojectPoint(\n      const pose::Transformation& transform, const Eigen::Vector3d& G_p_fi) {\n    const Eigen::Quaterniond& G_q_C =\n        transform.getRotation().toImplementation();\n    Eigen::Matrix3d G_R_C = G_q_C.toRotationMatrix();\n\n    // TODO(dymczykm) Investigate why the transformation need to be\n    // inverted here\n    //    const Eigen::Vector3d C_p_fi = C_R_G\n    //        * (G_p_fi - transform.getPosition().toImplementation());\n    const Eigen::Vector3d C_p_fi = G_R_C * G_p_fi + transform.getPosition();\n\n    return C_p_fi.hnormalized().head<2>();\n  }\n\n  pose::Quaternion getQuaternionFromYRotation(double rotation) {\n    // Invert quaternion to get passive rotation.\n    return pose::Quaternion(cos(rotation / 2), 0.0, -sin(rotation / 2), 0.0);\n  }\n};\n\nINSTANTIATE_TEST_CASE_P(\n    GeometricVision, GeometricVisionRotatedTwoViewParamTest,\n    ::testing::Values(\n        TriangulationParams(0, 3, 0, 0, 1.5, 0, 5),\n        TriangulationParams(0, 1, 0.05, 0, 0.5, 0.1, 5),\n        TriangulationParams(0, 1.2, 0, 0.1, 0.64, 0, 3.2),\n        TriangulationParams(-0.4, 1, 0.1, -0.3, 0.64, 0.05, 5.1),\n        TriangulationParams(-M_PI / 2, 1, 0.0, 1.0, 0, 0, 1)));\n\nTEST_P(\n    GeometricVisionRotatedTwoViewParamTest, TwoViewTriangulationOneCamRotated) {\n  LinearTriangulation triangulator;\n  TriangulationParams params = GetParam();\n\n  pose::Transformation camera0(\n      pose::Position3D(0, 0, 0), pose::Quaternion(1, 0, 0, 0));\n  pose::Transformation camera1(\n      pose::Position3D(params.camera1_position_),\n      getQuaternionFromYRotation(params.camera1_rotation_Y_));\n\n  Eigen::Vector2d measurement0 = this->reprojectPoint(camera0, params.G_p_fi_);\n  Eigen::Vector2d measurement1 = this->reprojectPoint(camera1, params.G_p_fi_);\n\n  Eigen::Vector3d triangulated_point, triangulated_point_homog;\n  EXPECT_TRUE(\n      triangulator.triangulateFromNormalizedTwoViews(\n          measurement0, camera0, measurement1, camera1, &triangulated_point));\n  EXPECT_TRUE(\n      triangulator.triangulateFromNormalizedTwoViewsHomogeneous(\n          measurement0, camera0, measurement1, camera1,\n          &triangulated_point_homog));\n  EXPECT_NEAR_EIGEN(params.G_p_fi_, triangulated_point, 1e-12);\n  EXPECT_NEAR_EIGEN(triangulated_point, triangulated_point_homog, 1e-12);\n}\n\nTEST(GeometricVision, TwoViewTriangulationParallelRays) {\n  LinearTriangulation triangulator;\n  pose::Transformation camera0(\n      pose::Position3D(0, 0, 0), pose::Quaternion(1, 0, 0, 0));\n  pose::Transformation camera1(\n      pose::Position3D(1, 0, 0), pose::Quaternion(1, 0, 0, 0));\n\n  Eigen::Vector2d measurement0(0, 0);\n  Eigen::Vector2d measurement1(0, 0);\n\n  Eigen::Vector3d triangulated_point;\n  EXPECT_FALSE(\n      triangulator.triangulateFromNormalizedTwoViews(\n          measurement0, camera0, measurement1, camera1, &triangulated_point));\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "1b63007910b96c06d698c4351d9231884bafc163", "size": 5420, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/geometric-vision-algorithms/test/test_two_view_triangulation.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "algorithms/geometric-vision-algorithms/test/test_two_view_triangulation.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "algorithms/geometric-vision-algorithms/test/test_two_view_triangulation.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": 36.6216216216, "max_line_length": 80, "alphanum_fraction": 0.7193726937, "num_tokens": 1616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5850236131151968}}
{"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": "/*\n * test_STDP.cpp\n *\n *  Created on: 2019-4-18\n *      Author: fasiondog\n */\n\n#ifdef TEST_ALL_IN_ONE\n    #include <boost/test/unit_test.hpp>\n#else\n    #define BOOST_TEST_MODULE test_hikyuu_indicator_suite\n    #include <boost/test/unit_test.hpp>\n#endif\n\n#include <fstream>\n#include <hikyuu/StockManager.h>\n#include <hikyuu/indicator/crt/KDATA.h>\n#include <hikyuu/indicator/crt/STDP.h>\n#include <hikyuu/indicator/crt/PRICELIST.h>\n\nusing namespace hku;\n\n/**\n * @defgroup test_indicator_STDP test_indicator_STDP\n * @ingroup test_hikyuu_indicator_suite\n * @{\n */\n\n/** @par \u68c0\u6d4b\u70b9 */\nBOOST_AUTO_TEST_CASE( test_STDP ) {\n    /** @arg n > 1 \u7684\u6b63\u5e38\u60c5\u51b5 */\n    PriceList d;\n    for (size_t i = 0; i < 15; ++i) {\n        d.push_back(i+1);\n    }\n    d[5] = 4.0;\n    d[7] = 4.0;\n    d[11] = 6.0;\n\n    Indicator ind = PRICELIST(d);\n    Indicator dev = STDP(ind, 10);\n    BOOST_CHECK(dev.name() == \"STDP\");\n    BOOST_CHECK(dev.size() == 15);\n    BOOST_CHECK(dev[8] == Null<price_t>());\n    BOOST_CHECK(std::fabs(dev[9] - 2.77308) < 0.00001 );\n    BOOST_CHECK(std::fabs(dev[10] - 2.98161) < 0.00001 );\n    BOOST_CHECK(std::fabs(dev[11] - 2.68514) < 0.00001 );\n    BOOST_CHECK(std::fabs(dev[12] - 3.1) < 0.00001 );\n    BOOST_CHECK(std::fabs(dev[13] - 3.46554) < 0.00001 );\n    BOOST_CHECK(std::fabs(dev[14] - 3.79605) < 0.00001 );\n\n    /** @arg n = 1\u65f6 */\n    dev = STDP(ind, 1);\n    BOOST_CHECK(dev.name() == \"STDP\");\n    BOOST_CHECK(dev.size() == 15);\n    for (size_t i = 0; i < dev.size(); ++i) {\n        BOOST_CHECK(dev[i] == Null<price_t>());\n    }\n\n    /** @arg operator() */\n    Indicator expect = STDP(ind, 10);\n    dev = STDP(10);\n    Indicator result = dev(ind);\n    BOOST_CHECK(result.size() == expect.size());\n    for (size_t i = 0; i < expect.size(); ++i) {\n        BOOST_CHECK(result[i] == expect[i]);\n    }\n}\n\n\n//-----------------------------------------------------------------------------\n// test export\n//-----------------------------------------------------------------------------\n#if HKU_SUPPORT_SERIALIZATION\n\n/** @par \u68c0\u6d4b\u70b9 */\nBOOST_AUTO_TEST_CASE( test_STDP_export ) {\n    StockManager& sm = StockManager::instance();\n    string filename(sm.tmpdir());\n    filename += \"/STDP.xml\";\n\n    Stock stock = sm.getStock(\"sh000001\");\n    KData kdata = stock.getKData(KQuery(-20));\n    Indicator ma1 = STDP(CLOSE(kdata), 10);\n    {\n        std::ofstream ofs(filename);\n        boost::archive::xml_oarchive oa(ofs);\n        oa << BOOST_SERIALIZATION_NVP(ma1);\n    }\n\n    Indicator ma2;\n    {\n        std::ifstream ifs(filename);\n        boost::archive::xml_iarchive ia(ifs);\n        ia >> BOOST_SERIALIZATION_NVP(ma2);\n    }\n\n    BOOST_CHECK(ma2.name() == \"STDP\");\n    BOOST_CHECK(ma1.size() == ma2.size());\n    BOOST_CHECK(ma1.discard() == ma2.discard());\n    BOOST_CHECK(ma1.getResultNumber() == ma2.getResultNumber());\n    for (size_t i = 0; i < ma1.size(); ++i) {\n        BOOST_CHECK_CLOSE(ma1[i], ma2[i], 0.00001);\n    }\n}\n#endif /* #if HKU_SUPPORT_SERIALIZATION */\n\n/** @} */\n\n\n", "meta": {"hexsha": "33615aac76c267b178f92b87a37d2a39f19d249e", "size": 2971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_STDP.cpp", "max_stars_repo_name": "allen9mu/hikyuu", "max_stars_repo_head_hexsha": "bed68183029e5a653e3e0ad53510036605e1d610", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-12T23:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-12T23:48:13.000Z", "max_issues_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_STDP.cpp", "max_issues_repo_name": "allen9mu/hikyuu", "max_issues_repo_head_hexsha": "bed68183029e5a653e3e0ad53510036605e1d610", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_STDP.cpp", "max_forks_repo_name": "allen9mu/hikyuu", "max_forks_repo_head_hexsha": "bed68183029e5a653e3e0ad53510036605e1d610", "max_forks_repo_licenses": ["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.7657657658, "max_line_length": 79, "alphanum_fraction": 0.5674856951, "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5849124162896764}}
{"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": "#define BOOST_TEST_MODULE classic hamiltonian\n#define BOOST_TEST_DYN_LINK\n#include <cmath>\n#include <random>\n#include <functional>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/test/unit_test.hpp>\n#include <mpp/chains/mcmc_chain.hpp>\n#include <mpp/hamiltonian/classic_hamiltonian.hpp>\n#include <mpp/dists/multivariate_normal.hpp>\n\ntemplate<typename real_scalar_type>\nvoid test_classic_hamiltonian(std::string const & chn_file_name) {\n    using namespace mpp::hamiltonian;\n    using namespace mpp::chains;\n    using namespace mpp::dists;\n    using namespace boost::numeric::ublas;\n\n    typedef diag_multivar_normal<real_scalar_type> diag_multivar_normal_type;\n    typedef hmc_sampler<real_scalar_type> hmc_sampler_type;\n    typedef vector<real_scalar_type> real_vector_type;\n    typedef std::normal_distribution<real_scalar_type> normal_distribution_type;\n    typedef std::mt19937 rng_type;\n    typedef mcmc_chain<real_scalar_type> chain_type;\n    typedef typename hmc_sampler_type::log_post_func_type log_post_func_type;\n    typedef typename hmc_sampler_type::grad_log_post_func_type grad_log_post_func_type;\n\n    size_t const num_dims(10);\n    real_vector_type mean(num_dims);\n    real_vector_type var(num_dims);\n    for(size_t i=0;i<num_dims;++i) {\n        mean(i) = real_scalar_type(0);\n        var(i) = real_scalar_type(1);\n    }\n    diag_multivar_normal_type dmn(mean,var);\n    using std::placeholders::_1;\n    log_post_func_type log_posterior\n        = std::bind (&diag_multivar_normal_type::log_posterior,&dmn,_1);\n\n    grad_log_post_func_type grad_log_posterior\n        = std::bind (&diag_multivar_normal_type::grad_log_posterior,&dmn,_1);\n    size_t const max_num_steps(10);\n    real_scalar_type const max_eps(1);\n    real_vector_type inv_mass_mat(num_dims);\n    for(size_t i=0;i<num_dims;++i) {\n        inv_mass_mat(i) = real_scalar_type(1);\n    }\n\n    hmc_sampler_type hmc_spr(\n        log_posterior,\n        grad_log_posterior,\n        num_dims,\n        max_num_steps,\n        max_eps,\n        inv_mass_mat\n    );\n\n    size_t const num_samples(100);\n    rng_type rng;\n    normal_distribution_type nrm_dist;\n    real_vector_type q_0(num_dims);\n    for(size_t i=0;i<num_dims;++i) {\n        q_0(i) = nrm_dist(rng);\n    }\n    chain_type chn = hmc_spr.run_sampler(num_samples,q_0);\n    chn.write_samples_to_csv(chn_file_name);\n\n}\n\nBOOST_AUTO_TEST_CASE(classic_hamiltonian) {\n    test_classic_hamiltonian<float>(std::string(\"float.chain\"));\n    test_classic_hamiltonian<double>(std::string(\"double.chain\"));\n    test_classic_hamiltonian<long double>(std::string(\"long-double.chain\"));\n}\n", "meta": {"hexsha": "7d5b7efac6ee2eb35ad141130af8f466d8b97915", "size": 2605, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/hamiltonian/classic_hamiltonian.cpp", "max_stars_repo_name": "tbs1980/mpp", "max_stars_repo_head_hexsha": "5a704b48d5ab2386588c71987a7616a276380a99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/hamiltonian/classic_hamiltonian.cpp", "max_issues_repo_name": "tbs1980/mpp", "max_issues_repo_head_hexsha": "5a704b48d5ab2386588c71987a7616a276380a99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/hamiltonian/classic_hamiltonian.cpp", "max_forks_repo_name": "tbs1980/mpp", "max_forks_repo_head_hexsha": "5a704b48d5ab2386588c71987a7616a276380a99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7333333333, "max_line_length": 87, "alphanum_fraction": 0.7408829175, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.584898658167381}}
{"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": "//------------------------------------------------------------------------------\n// \\file Algorithms_tests.cpp\n//------------------------------------------------------------------------------\n\n#include <boost/test/unit_test.hpp>\n\n#include <algorithm> // std::transform\n#include <array>\n#include <cctype> // std::toupper\n#include <cstdio> // std::printf\n#include <cstdlib> // std::atoi\n#include <iostream>\n#include <list>\n#include <numeric>\n#include <optional>\n#include <string>\n#include <vector>\n\nBOOST_AUTO_TEST_SUITE(Cpp)\nBOOST_AUTO_TEST_SUITE(Algorithms)\nBOOST_AUTO_TEST_SUITE(Algorithms_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(StdForEachPrintsEachValue)\n{\n\t{\n\t\tconstexpr std::size_t N {100};\n\n\t\t// Initializer list doesn't work to make std::list have size of N.\n\t\tstd::list<std::size_t> range_list (N);\n\t\tstd::iota(range_list.begin(), range_list.end(), 0);\n\n\t\tstd::size_t counter {0};\t\t\n\t\tfor (const auto& l_i : range_list)\n\t\t{\n\t\t\tBOOST_TEST_REQUIRE(l_i == counter);\n\t\t\tcounter++;\n\t\t}\n\t\tBOOST_TEST_REQUIRE(counter == N);\n\t\tBOOST_TEST_REQUIRE(range_list.size() == N);\n\n\t\t// Initializer list just initializes to 2 values if done like this:\n\t\t// {N, '0'} or this {{N, '0'}}\n\t\tstd::vector<unsigned char> test_values (N, '0');\n\t\tBOOST_TEST_REQUIRE(test_values.size() == N);\n\n\t\tstd::transform(\n\t\t\trange_list.begin(),\n\t\t\trange_list.end(),\n\t\t\ttest_values.begin(),\n\t\t\t[](const auto& l_i) -> unsigned char\n\t\t\t{\n\t\t\t\treturn 'a' + l_i;\n\t\t\t});\n\t\t\n\t  std::for_each(\n\t  \trange_list.begin(),\n\t    range_list.end(),\n\t    [&test_values](const auto& index)\n\t    {\n\t      std::printf(\"%01x \", test_values[index]);\n\t    });\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Algorithms_tests\nBOOST_AUTO_TEST_SUITE_END() // Algorithms\nBOOST_AUTO_TEST_SUITE_END() // Cpp\n\n", "meta": {"hexsha": "8fa703e0c0306a6d14157265febd80fba2914aca", "size": 1889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Cpp/Std/Algorithm/Algorithms_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Cpp/Std/Algorithm/Algorithms_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Cpp/Std/Algorithm/Algorithms_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6056338028, "max_line_length": 80, "alphanum_fraction": 0.5622022234, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5847446010137116}}
{"text": "/*\n *  vector_map_view_test_2.cpp\n *  MTL\n *\n *\tTest rscaled_view and divide_by_view\n *\n *  Created by Hui Li (huil@Princeton.EDU)\n *\n */\n\n\n#include <iostream>\n#include <cmath>\n#include <complex>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/vector/map_view.hpp>\n#include <boost/numeric/mtl/operation/print.hpp>\n#include <boost/numeric/mtl/operation/set_to_zero.hpp>\n#include <boost/numeric/mtl/operation/conj.hpp>\n#include <boost/numeric/mtl/operation/rscale.hpp>\n#include <boost/numeric/mtl/operation/divide_by.hpp>\n\n#if 0\n#include <boost/numeric/mtl/operation/hermitian.hpp>\n#endif\n\n\nusing std::cout;  using std::complex;\n\ntypedef complex<double> ct;\n\ndouble value(double)\n{\n    return 7.0;\n}\n\ncomplex<double> value(complex<double>)\n{\n    return ct(7.0, 1.0);\n}\n\n// rscaled value\ndouble rsvalue(double)\n{\n    return 14.0;\n}\n\nct rsvalue(ct)\n{\n    return ct(14.0, 2.0);\n}\n\n// complex rscaled value\nct crsvalue(double)\n{\n    return ct(0.0, 7.0);\n}\n\nct crsvalue(ct)\n{\n    return ct(-1.0, 7.0);\n}\n\n\ntemplate <typename Vector>\nvoid test(Vector& vector, const char* name)\n{\n    set_to_zero(vector);\n    typename Vector::value_type ref(0);\n\t\n#if 1\t\n    vector[2]= value(ref);\n    vector[4]= value(ref) + 1.0;\n    vector[5]= value(ref) + 2.0;\n\t\n#else // When sparse vectors are used there should be an inserter class for vectors too\n    {\n\t\tinserter<Vector>  ins(vector);\n\t\tins(2) << value(ref);\n\t\tins(4) << value(ref) + 1.0;\n\t\tins(5) << value(ref) + 2.0;\n    }\n#endif\n\t\n    cout << \"\\n\\n\" << name << \"\\n\";\n    cout << \"Original vector:\\n\" << vector << \"\\n\";\n\t\n\t// test rscaled_view\n    mtl::vec::rscaled_view<Vector,double>  rscaled_vector(vector,2.0);\n    cout << \"vector right scaled with 2.0\\n\" << rscaled_vector << \"\\n\";\n    MTL_THROW_IF(rscaled_vector(2) != rsvalue(ref), mtl::runtime_error(\"right scaling wrong\"));\n    \n    mtl::vec::rscaled_view<Vector,ct>  crscaled_vector(vector,ct(0.0, 1.0));\n    cout << \"vector right scaled with i (complex(0, 1))\\n\" << crscaled_vector << \"\\n\";\n    MTL_THROW_IF(crscaled_vector(2) != crsvalue(ref), mtl::runtime_error(\"complex right scaling wrong\"));\n\t\n    cout << \"vector right scaled with 2.0 (free function)\\n\" << rscale(vector,2.0) << \"\\n\";\n    MTL_THROW_IF(rscale(vector,2.0)(2) != rsvalue(ref), mtl::runtime_error(\"right scaling wrong\"));\n\t\n    cout << \"vector right scaled with i (complex(0, 1)) (free function)\\n\" << rscale(vector,ct(0.0, 1.0)) << \"\\n\";\n    MTL_THROW_IF(rscale(vector,ct(0.0, 1.0))(2) != crsvalue(ref), mtl::runtime_error(\"complex right scaling wrong\"));\n\t\n\t// test divide_by_view\n    mtl::vec::divide_by_view<Vector,double>  div_vector(vector,0.5);\n    cout << \"vector divide by 0.5\\n\" << div_vector << \"\\n\";\n    MTL_THROW_IF(div_vector(2) != rsvalue(ref), mtl::runtime_error(\"divide_by wrong\"));\n    \n    mtl::vec::divide_by_view<Vector,ct>  cdiv_vector(vector,ct(0.0, -1.0));\n    cout << \"vector divide by -i (complex(0, -1))\\n\" << cdiv_vector << \"\\n\";\n    MTL_THROW_IF(cdiv_vector(2) != crsvalue(ref), mtl::runtime_error(\"complex divide_by wrong\"));\n\t\n    cout << \"vector divide by 0.5 (free function)\\n\" << divide_by(vector,0.5) << \"\\n\";\n    MTL_THROW_IF(divide_by(vector,0.5)(2) != rsvalue(ref), mtl::runtime_error(\"divide_by wrong\"));\n\t\n    cout << \"vector divide by -i (complex(0, -1)) (free function)\\n\" << divide_by(vector,ct(0.0, -1.0)) << \"\\n\";\n    MTL_THROW_IF(divide_by(vector,ct(0.0, -1.0))(2) != crsvalue(ref), mtl::runtime_error(\"complex divide_by wrong\"));\n\t\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    unsigned size= 7; \n    if (argc > 1) size= atoi(argv[1]); \n\t\n    mtl::dense_vector<double>                                 dv(size);\n    mtl::dense_vector<complex<double> >                       drc(size);\n\t\n    test(dv, \"Dense double vector\");\n    test(drc, \"Dense complex vector\");\n\t\n    return 0;\n}\n", "meta": {"hexsha": "41f151669f5fcf2b0ac71a797a64e4c105511a35", "size": 3823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/vector_map_view_2_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/vector_map_view_2_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/vector_map_view_2_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 28.3185185185, "max_line_length": 117, "alphanum_fraction": 0.6413811143, "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.5847445967426769}}
{"text": "// -*- mode: C++ -*-\n/**\n   Dietrich Bollmann, Kamakura, 2015/01/01\n   \n   FEM-test.h\n\n   Unit tests for class: FEM\n   \n   Copyright (c) 2015 Dietrich Bollmann\n   \n   This software may be modified and distributed under the terms\n   of the MIT license.  See the LICENSE file for details.\n*/\n\n#define BOOST_TEST_DYN_LINK\n#ifdef STAND_ALONE\n#   define BOOST_TEST_MODULE Main\n#endif\n\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>\n\n#include \"Spring.h\"\n\n#include \"FEM.h\"\n\nnamespace nsl {\n\nBOOST_AUTO_TEST_SUITE(TestSuite_FEM)\n\n/**\n   Add node.\n*/ \nvoid addNode(FEM &fem, std::vector<double> node)\n{\n  // Add node\n  int id = node[0];\n  fem.addNode(id);\n\n  for (size_t i = 1; i < node.size() - 1; i += 2)\n    {\n      // Add displacement, when given\n      if (node[i] == 'd')\n\t{\n\t  double displacement = node[i+1];\n\t  fem.addDisplacement(id, displacement);\n\t}\n      \n      // Add force, when given\n      if (node[i] == 'f')\n\t{\n\t  double force = node[i+1];\n\t  fem.addForce(id, force);\n\t}\n    }\n}\n\t\t    \n/**\n  Add spring.\n */\nvoid addSpring(FEM &fem, std::vector<double> spring)\n{\n  // Unpack spring data\n  int id = spring[0];\n  int node1 = spring[1];\n  int node2 = spring[2];\n  double springConstant = spring[3];\n\n  // Add spring\n  fem.addSpring(id, node1, node2, springConstant);\n}\n\n/**\n   Test stiffness matrix.\n */\nvoid testStiffnessMatrix(std::vector<std::vector<double> > nodes, \n\t\t\t std::vector<std::vector<double> > springs, \n\t\t\t std::vector<std::vector<double> > stiffnessMatrix)\n{\n  FEM fem;\n \n  // Assemble model\n  for (auto node : nodes) addNode(fem, node);\n  for (auto spring : springs) addSpring(fem, spring);\n\n  // Solve model\n  fem.solve();\n\n  DMatrix expectedStiffnessMatrix(stiffnessMatrix);\n  DMatrix calculatedStiffnessMatrix = fem.getGlobalStiffnessMatrix();\n\n  double distance = euclideanDistance(expectedStiffnessMatrix, calculatedStiffnessMatrix);\n  bool testResult = distance < 1e-20;\n      \n  BOOST_CHECK( testResult );\n        \n  if (!testResult)\n    std::cout \n      << \">>> Stiffness matrix:\" << std::endl << std::endl\n      << \"expected:\"   << std::endl << expectedStiffnessMatrix << std::endl\n      << \"calculated:\" << std::endl << calculatedStiffnessMatrix << std::endl\n      << \"euclidian distance: \" << distance << std::endl\n      ;\n}\n  \nBOOST_AUTO_TEST_CASE(Test_stiffnessMatrix) \n{\n  // Test case 1\n  // \n  // Taken from the book \n  // \"A First Course in the Finite element Method, third edition\"\n  // by Daryl L. Logan,\n  // Example 2.1, page 40.\n  // \n  testStiffnessMatrix(// Nodes:\n\t\t      // node id ['d', <displacement>] ['f', <force>]\n\t\t      {{1, 'd', 0},\n\t\t       {2, 'd', 0},\n\t\t       {3},\n\t\t       {4, 'f', 5000}\n\t\t      },\n\t\t      // Springs:\n\t\t      // spring id  node1 node2  spring constant\n\t\t      {{1,  1, 3,  1000},\n\t\t       {2,  3, 4,  2000},\n\t\t       {3,  4, 2,  3000}\n\t\t      },\n\t\t      // Stiffness matrix:\n\t\t      {{ 1000,     0, -1000,     0},\n\t\t       {    0,  3000,     0, -3000},\n\t\t       {-1000,     0,  3000, -2000},\n\t\t       {    0, -3000, -2000,  5000},\n\t\t      }\n\t\t      );\n  \n  // Test case 2\n  // \n  // Taken from the book \n  // \"A First Course in the Finite element Method, third edition\"\n  // by Daryl L. Logan,\n  // Example 2.2, page 43.\n  // \n  testStiffnessMatrix(// Nodes:\n\t\t      // node id ['d', <displacement>] ['f', <force>]\n\t\t      {{1, 'd', 0},\n\t\t       {2},\n\t\t       {3},\n\t\t       {4},\n\t\t       {5, 'd', 0.02}\n\t\t      },\n\t\t      // Springs:\n\t\t      // spring id  node1 node2  spring constant\n\t\t      {{1,  1, 2,  200},\n\t\t       {2,  2, 3,  200},\n\t\t       {3,  3, 4,  200},\n\t\t       {4,  4, 5,  200}\n\t\t      },\n\t\t      // Stiffness matrix:\n\t\t      {{ 200, -200,    0,    0,    0},\n\t\t       {-200,  400, -200,    0,    0},\n\t\t       {   0, -200,  400, -200,    0},\n\t\t       {   0,    0, -200,  400, -200},\n\t\t       {   0,    0,    0, -200,  200},\n\t\t      }\n\t\t      );\n\n  // Test case 3  \n  // \n  // Taken from the book \n  // \"A First Course in the Finite element Method, third edition\"\n  // by Daryl L. Logan,\n  // Example 2.3, page 46.\n  // \n  testStiffnessMatrix(// Nodes:\n\t\t      // node id ['d', <displacement>] ['f', <force>]\n\t\t      {{1, 'd', 0},\n           \t       {2},\n           \t       {3, 'd', 0},\n           \t       {4, 'd', 0}\n           \t      },\n\t\t      // Springs:\n\t\t      // spring id  node1 node2  spring constant\n           \t      {{1,  1, 2,  1},\n           \t       {2,  2, 3,  2},\n           \t       {3,  2, 4,  3}\n           \t      },\n\t\t      // Stiffness matrix:\n\t\t      {{ 1,    -1,  0,  0},\n\t\t       {-1, 1+2+3, -2, -3},\n\t\t       { 0,    -2,  2,  0},\n\t\t       { 0,    -3,  0,  3}\n\t\t      }\n\t\t      );\n\n  // Test case 4\n  // \n  // Taken from the book \n  // \"A First Course in the Finite element Method, third edition\"\n  // by Daryl L. Logan,\n  // Example 2.4, page 54.\n  // \n  testStiffnessMatrix(// Nodes:\n\t\t      // node id ['d', <displacement>] ['f', <force>]\n\t\t      {{1, 'd', 0},\n\t\t       {2, 'f', 1000}\n           \t      },\n\t\t      // Springs:\n\t\t      // spring id  node1 node2  spring constant\n           \t      {{1,  1, 2,  500}\n           \t      },\n\t\t      // Stiffness matrix:\n\t\t      {{ 500, -500},\n\t\t       {-500,  500}\n\t\t      }\n\t\t      );\n}\n\n/**\n   Test case.\n */\nvoid testCase(std::vector<std::vector<double> > nodes, \n\t      std::vector<std::vector<double> > springs, \n\t      std::vector<std::vector<double> > displacements,\n\t      std::vector<std::vector<double> > forces,\n\t      std::vector<std::vector<double> > localForces)\n{\n  FEM fem;\n \n  // Assemble model\n  for (auto node : nodes) addNode(fem, node);\n  for (auto spring : springs) addSpring(fem, spring);\n\n  // Solve model\n  fem.solve();\n\n  // Check displacements\n  for (auto displacementData : displacements)\n    {\n      int node = displacementData[0];\n      double expectedDisplacement = displacementData[1];\n      double displacement = fem.getGlobalDisplacement(node);\n\n      bool testResult = (expectedDisplacement == displacement);\n\n      BOOST_CHECK( testResult );\n        \n      if (!testResult)\n\tstd::cout \n\t  << \">>> Displacement at node \" << node << \": \"\n\t  << \"expected: \" << expectedDisplacement << \", \"\n\t  << \"calculated: \" << displacement << std::endl\n\t  ;\n    }\n\n  // Check forces\n  for (auto forceData : forces)\n    {\n      int node = forceData[0];\n      double expectedForce = forceData[1];\n      double force = fem.getGlobalForce(node);\n\n      bool testResult = abs(expectedForce - force) < 1e-12;\n\n      BOOST_CHECK( testResult );\n        \n      if (!testResult)\n\tstd::cout \n\t  << \">>> Force at node \" << node << \": \"\n\t  << \"expected: \" << expectedForce << \", \"\n\t  << \"calculated: \" << force << std::endl\n\t  ;\n    }\n\n  // Check localForces\n  for (auto localForceData : localForces)\n    {\n      int node = localForceData[0];\n      DVector expectedLocalForces({localForceData[1], localForceData[2]});\n      DVector localForces = fem.getLocalForces(node);\n\n      double distance = euclideanDistance(expectedLocalForces, localForces);\n      bool testResult = distance < 1e-12;\n      \n      BOOST_CHECK( testResult );\n        \n      if (!testResult)\n      \tstd::cout \n      \t  << \">>> Local forces at node \" << node << \": \"\n      \t  << \"expected: \" << expectedLocalForces << \", \"\n      \t  << \"calculated: \" << localForces << \"  \"\n      \t  << \"(euclidian distance: \" << distance << \")\" << std::endl\n      \t  ;\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Test_testCases)\n{\n  // Test case 1\n  // \n  // Taken from the book \n  // \"A First Course in the Finite element Method, third edition\"\n  // by Daryl L. Logan,\n  // Example 2.1, page 40.\n  // \n  testCase(// Nodes:\n  \t   // node id ['d', <displacement>] ['f', <force>]\n\t   {{1, 'd', 0},\n\t    {2, 'd', 0},\n\t    {3},\n\t    {4, 'f', 5000}\n  \t   },\n  \t   // Springs:\n  \t   // spring id  node1 node2  spring constant\n  \t   {{1,  1, 3,  1000},\n            {2,  3, 4,  2000},\n  \t    {3,  4, 2,  3000}\n  \t   },\n\t   // Displacements:\n\t   // node id  displacement\n\t   {{1, 0},\n\t    {2, 0},\n\t    {3, 10.0 / 11.0},\n\t    {4, 15.0 / 11.0}\n\t   },\n\t   // Forces:\n\t   // node id  force\n\t   {{1, -10000.0 / 11},\n\t    {2, -45000.0 / 11},\n\t    {3,      0.0},\n\t    {4,  55000.0 / 11}\n\t   },\n\t   // Local forces:\n\t   // spring id  local force node1, node2\n\t   {{1, -10000.0 / 11,  10000.0 / 11},\n\t    {2, -10000.0 / 11,  10000.0 / 11},\n\t    {3,  45000.0 / 11, -45000.0 / 11}\n\t   }\n  \t   );\n  \n  // Test case 2\n  // \n  // Taken from the book \n  // \"A First Course in the Finite element Method, third edition\"\n  // by Daryl L. Logan,\n  // Example 2.2, page 43.\n  // \n  testCase(// Nodes:\n\t   // node id ['d', <displacement>] ['f', <force>]\n\t   {{1, 'd', 0},\n\t    {2},\n\t    {3},\n\t    {4},\n\t    {5, 'd', 0.02}\n\t   },\n\t   // Springs:\n\t   // spring id  node1 node2  spring constant\n\t   {{1,  1, 2,  200},\n\t    {2,  2, 3,  200},\n\t    {3,  3, 4,  200},\n\t    {4,  4, 5,  200}\n\t   },\n\t   // Displacements:\n\t   // node id  displacement\n\t   {{1, 0},\n\t    {2, 0.005},\n\t    {3, 0.01},\n\t    {4, 0.015},\n\t    {5, 0.02}\n\t   },\n\t   // Forces:\n\t   // node id  force\n\t   {{1, -1},\n\t    {2,  0},\n\t    {3,  0},\n\t    {4,  0},\n\t    {5,  1}\n\t   },\n\t   // Local forces:\n\t   // spring id  local force node1, node2\n\t   {{1, -1, 1},\n\t    {2, -1, 1},\n\t    {3, -1, 1},\n\t    {4, -1 ,1}\n\t   }\n  \t   );\n  \n  // Test case 3\n  // \n  // Taken from the book \n  // \"A First Course in the Finite element Method, third edition\"\n  // by Daryl L. Logan,\n  // Example 2.3, page 46.\n  // \n  testCase(// Nodes:\n\t   // node id ['d', <displacement>] ['f', <force>]\n\t   {{1, 'd', 0},\n\t    {2, 'f', 6}, // Force: P = 6\n\t    {3, 'd', 0},\n\t    {4, 'd', 0}\n\t   },\n\t   // Springs:\n\t   // spring id  node1 node2  spring constant\n\t   {{1,  1, 2,  1}, // Spring constant:  k1 = 1\n\t    {2,  2, 3,  2}, // Spring constant:  k2 = 2\n\t    {3,  2, 4,  3}  // Spring constant:  k3 = 3\n\t   },\n\t   // Displacements:\n\t   // node id  displacement\n\t   {{1, 0},\n\t    {2, 1}, // P / (k1 + k2 + k3) = 6 / (1 + 2 + 3) = 1\n\t    {3, 0},\n\t    {4, 0}\n\t   },\n\t   // Forces:\n\t   // node id  force\n\t   // d2 = P / (k1 + k2 + k3) = 6 / (1 + 2 + 3) = 1\n\t   {{1, -1}, // F1 = -k1 * d2 = -k1 = -1\n\t    {2,  6}, // F2 = P = 6\n\t    {3, -2}, // F3 = -k2 * d2 = -k2 = -2\n\t    {4, -3}  // F4 = -k3 * d2 = -k3 = -3\n\t   },\n\t   // Local forces:\n\t   // spring id  local force node1, node2\n\t   // d2 = P / (k1 + k2 + k3) = 6 / (1 + 2 + 3) = 1\n\t   {{1, -1,  1}, // k1 * d1 + -k1 * d2 = 1 * 0 + -1 * 1 = -1\n\t    {2,  2, -2}, // k2 * d2 + -k2 * d3 = 2 * 1 + -2 * 0 =  2\n\t    {3,  3, -3}  // k3 * d2 + -k3 * d4 = 3 * 1 + -3 * 0 =  3\n\t   }\n  \t   );\n  \n  // Test case 4\n  // \n  // Taken from the book \n  // \"A First Course in the Finite element Method, third edition\"\n  // by Daryl L. Logan,\n  // Example 2.4, page 54.\n  // \n  testCase(// Nodes:\n\t   // node id ['d', <displacement>] ['f', <force>]\n\t   {{1, 'd', 0},\n\t    {2, 'f', 1000}\n\t   },\n\t   // Springs:\n\t   // spring id  node1 node2  spring constant\n\t   {{1,  1, 2,  500}\n\t   },\n\t   // Displacements:\n\t   // node id  displacement\n\t   {{1, 0},\n\t    {2, 2}\n\t   },\n\t   // Forces:\n\t   // node id  force\n\t   {{1, -1000},\n\t    {2,  1000}\n\t   },\n\t   // Local forces:\n\t   // spring id  local force node1, node2\n\t   {{1, -1000, 1000}\n\t   }\n  \t   );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n} // namespace nsl\n\n/* fin */\n\n", "meta": {"hexsha": "3f5ed4c1b36aa8607936a6f112149a93e30befa1", "size": 11160, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/FEM-test.cpp", "max_stars_repo_name": "newskylabs/nslfem-spring1d", "max_stars_repo_head_hexsha": "40dfb1c52dc62134ed12e49ab1147362c49312ce", "max_stars_repo_licenses": ["MIT"], "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/FEM-test.cpp", "max_issues_repo_name": "newskylabs/nslfem-spring1d", "max_issues_repo_head_hexsha": "40dfb1c52dc62134ed12e49ab1147362c49312ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/FEM-test.cpp", "max_forks_repo_name": "newskylabs/nslfem-spring1d", "max_forks_repo_head_hexsha": "40dfb1c52dc62134ed12e49ab1147362c49312ce", "max_forks_repo_licenses": ["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.6942675159, "max_line_length": 90, "alphanum_fraction": 0.4834229391, "num_tokens": 3886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.5846908144325672}}
{"text": "/*\n  boost_random.hpp : Random number class implimentaion header using BOOST functions\n\n  Copyright (C) 2015 Anup Gopalakrishna Pillai, Suhita Nadkarni Lab, IISER, Pune <anupgpillai@gmail.com>\n  Copyright (C) 2015 Pranav Kulkarni, Collins Assisi Lab, IISER, Pune <pranavcode@gmail.com>\n\n  This program is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with this program.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef BOOST_RANDOM_HPP_INCLUDED\n#define BOOST_RANDOM_HPP_INCLUDED\n\n#include <iostream>\n#include <ctime>\n#include <sys/types.h>\n#include <unistd.h>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/generator_iterator.hpp>\n\ntypedef boost::random::mt19937 base_generator_type;\ntypedef boost::random::uniform_int_distribution<> uni_int_dist_type;\ntypedef boost::random::uniform_real_distribution<> uni_real_dist_type;\ntypedef boost::random::normal_distribution<double> norm_dist_type;\n\ntypedef boost::random::variate_generator<base_generator_type&, uni_int_dist_type> uni_int_var_gen_type;\ntypedef boost::random::variate_generator<base_generator_type&, uni_real_dist_type> uni_real_var_gen_type;\ntypedef boost::random::variate_generator<base_generator_type&, norm_dist_type> norm_var_gen_type;\n\nclass boost_rng\n{\n private:\n  long long seed;\n  base_generator_type gen;\n  uni_int_dist_type uni_int_dist;\n  uni_real_dist_type uni_real_dist;\n  norm_dist_type norm_dist;\n  \n  uni_int_var_gen_type rand_uni_int;\n  norm_var_gen_type rand_norm;\n public:\n  boost_rng(long long seed_ = std::time(0) + (long long) getpid()):\n      seed(seed_), gen(seed), uni_int_dist(0,1), rand_uni_int(gen,uni_int_dist),\n      norm_dist(0.0,1.0),rand_norm(gen,norm_dist) {};\n  int uni_int(void);\n  double norm_double(void);\n};\n\n// generates uniform distribution (int)\nint boost_rng::uni_int(void)\n{\n  return (rand_uni_int());\n}\n\n// generates normal distribution ( double )\ndouble boost_rng::norm_double(void)\n{\n  return (rand_norm());\n}\n\n#endif\t// BOOST_RANDOM_HPP_INCLUDED\n", "meta": {"hexsha": "14c5021c0c7238d7595365fc34ee99484564f4c1", "size": 2730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/boost_random.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/boost_random.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/boost_random.hpp", "max_forks_repo_name": "anupgp/astron", "max_forks_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0, "max_line_length": 105, "alphanum_fraction": 0.7871794872, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.5846908075731172}}
{"text": "// test_inverse_chi_squared.cpp\n\n// Copyright Paul A. Bristow 2010.\n// Copyright John Maddock 2010.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifdef _MSC_VER\n#  pragma warning (disable : 4310) // cast truncates constant value.\n#endif\n\n// http://www.wolframalpha.com/input/?i=inverse+chisquare+distribution\n\n#include <boost/math/tools/test.hpp>\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\nusing ::boost::math::concepts::real_concept;\n\n//#include <boost/math/tools/test.hpp>\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp> // for test_main\n#include <boost/test/floating_point_comparison.hpp> // for BOOST_CHECK_CLOSE_FRACTION\n#include \"test_out_of_range.hpp\"\n\n#include <boost/math/distributions/inverse_chi_squared.hpp> // for inverse_chisquared_distribution\nusing boost::math::inverse_chi_squared_distribution;\nusing boost::math::cdf;\nusing boost::math::pdf;\n\n// Use Inverse Gamma distribution to check their relationship:\n// inverse_chi_squared<>(v) == inverse_gamma<>(v / 2., 0.5)\n#include <boost/math/distributions/inverse_gamma.hpp> // for inverse_gamma_distribution\nusing boost::math::inverse_gamma_distribution;\nusing boost::math::inverse_gamma;\n//  using  ::boost::math::cdf;\n//  using  ::boost::math::pdf;\n\n#include <boost/math/special_functions/gamma.hpp> \nusing boost::math::tgamma; // for naive pdf.\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n#include <limits>\nusing std::numeric_limits; // for epsilon.\n\ntemplate <class RealType>\nRealType naive_pdf(RealType df, RealType scale, RealType x)\n{ // Formula from Wikipedia\n   using namespace std; // For ADL of std functions.\n   using boost::math::tgamma;\n   RealType result = pow(scale * df/2, df/2) * exp(-df * scale/(2 * x));\n   result /= tgamma(df/2) * pow(x, 1 + df/2);\n   return result;\n}\n\n// Test using a spot value from some other reference source,\n// in this case test values from output from R provided by Thomas Mang,\n// and Wolfram Mathematica by Mark Coleman.\n\ntemplate <class RealType>\nvoid test_spot(\n     RealType degrees_of_freedom, // degrees_of_freedom,\n     RealType scale, // scale,\n     RealType x, // random variate x,\n     RealType pd, // expected pdf,\n     RealType P, // expected CDF,\n     RealType Q, // expected complement of CDF,\n     RealType tol) // test tolerance.\n{\n   boost::math::inverse_chi_squared_distribution<RealType> dist(degrees_of_freedom, scale);\n\n   BOOST_CHECK_CLOSE_FRACTION\n      ( // Compare to expected PDF.\n      pdf(dist, x), // calculated.\n      pd, // expected\n      tol);\n\n   BOOST_CHECK_CLOSE_FRACTION( // Compare to naive pdf formula (probably less accurate).\n      pdf(dist, x), naive_pdf(dist.degrees_of_freedom(), dist.scale(), x), tol);\n\n   BOOST_CHECK_CLOSE_FRACTION( // Compare to expected CDF.\n      cdf(dist, x), P, tol);\n\n   if((P < 0.999) && (Q < 0.999))\n   {  // We can only check this if P is not too close to 1,\n      // so that we can guarantee Q is accurate:\n      BOOST_CHECK_CLOSE_FRACTION(\n        cdf(complement(dist, x)), Q, tol); // 1 - cdf\n      BOOST_CHECK_CLOSE_FRACTION(\n        quantile(dist, P), x, tol); // quantile(cdf) = x\n      BOOST_CHECK_CLOSE_FRACTION(\n        quantile(complement(dist, Q)), x, tol); // quantile(complement(1 - cdf)) = x\n   }\n} // test_spot\n\ntemplate <class RealType> // Any floating-point type RealType.\nvoid test_spots(RealType)\n{\n  // Basic sanity checks, some test data is to six decimal places only,\n  // so set tolerance to 0.000001 (expressed as a percentage = 0.0001%).\n\n  RealType tolerance = 0.000001f;\n  cout << \"Tolerance = \" << tolerance * 100 << \"%.\" << endl;\n\n// This test values from output from geoR (17 decimal digits) guided by Thomas Mang.\n  test_spot(static_cast<RealType>(2), static_cast<RealType>(1./2.),\n    // degrees_of_freedom, default scale = 1/df.\n  static_cast<RealType>(1.L), // x.\n  static_cast<RealType>(0.30326532985631671L), // pdf.\n  static_cast<RealType>(0.60653065971263365L), // cdf.\n  static_cast<RealType>(1 - 0.606530659712633657L), // cdf complement.\n  tolerance  // tol\n  );\n\n// Tests from Mark Coleman & Georgi Boshnakov using Wolfram Mathematica.\n  test_spot(static_cast<RealType>(10), static_cast<RealType>(0.1L), // degrees_of_freedom, scale\n  static_cast<RealType>(0.2), // x\n  static_cast<RealType>(1.6700235722635659824529759616528281217001163943570L), // pdf\n  static_cast<RealType>(0.89117801891415124234834646836872197623907651175353L), // cdf\n  static_cast<RealType>(1 - 0.89117801891415127L), // cdf complement\n  tolerance  // tol\n  );\n\n  test_spot(static_cast<RealType>(10), static_cast<RealType>(0.1L), // degrees_of_freedom, scale\n  static_cast<RealType>(0.5), // x\n  static_cast<RealType>(0.03065662009762021L), // pdf\n  static_cast<RealType>(0.99634015317265628765454354418728984933240514654437L), // cdf\n  static_cast<RealType>(1 - 0.99634015317265628765454354418728984933240514654437L), // cdf complement\n  tolerance  // tol\n  );\n\n\n  test_spot(static_cast<RealType>(10), static_cast<RealType>(2), // degrees_of_freedom, scale\n  static_cast<RealType>(0.5), // x\n  static_cast<RealType>(0.00054964096598361569L), // pdf\n  static_cast<RealType>(0.000016944743930067383903707995865261004246785511612700L), // cdf\n  static_cast<RealType>(1 - 0.000016944743930067383903707995865261004246785511612700L), // cdf complement\n  tolerance  // tol\n  );\n  \n  // Check some bad parameters to the distribution cause expected exception to be thrown.\n#ifndef BOOST_NO_EXCEPTIONS\n  BOOST_MATH_CHECK_THROW(boost::math::inverse_chi_squared_distribution<RealType> ichsqbad1(-1), std::domain_error); // negative degrees_of_freedom.\n  BOOST_MATH_CHECK_THROW(boost::math::inverse_chi_squared_distribution<RealType> ichsqbad2(1, -1), std::domain_error); // negative scale.\n  BOOST_MATH_CHECK_THROW(boost::math::inverse_chi_squared_distribution<RealType> ichsqbad3(-1, -1), std::domain_error); // negative scale and degrees_of_freedom.\n#else\n  BOOST_MATH_CHECK_THROW(boost::math::inverse_chi_squared_distribution<RealType>(-1), std::domain_error); // negative degrees_of_freedom.\n  BOOST_MATH_CHECK_THROW(boost::math::inverse_chi_squared_distribution<RealType>(1, -1), std::domain_error); // negative scale.\n  BOOST_MATH_CHECK_THROW(boost::math::inverse_chi_squared_distribution<RealType>(-1, -1), std::domain_error); // negative scale and degrees_of_freedom.\n#endif\n  check_out_of_range<boost::math::inverse_chi_squared_distribution<RealType> >(1, 1);\n\n  inverse_chi_squared_distribution<RealType> ichsq;\n\n  if(std::numeric_limits<RealType>::has_infinity)\n  {\n    BOOST_MATH_CHECK_THROW(pdf(ichsq, +std::numeric_limits<RealType>::infinity()), std::domain_error); // x = + infinity, pdf = 0\n    BOOST_MATH_CHECK_THROW(pdf(ichsq, -std::numeric_limits<RealType>::infinity()),  std::domain_error); // x = - infinity, pdf = 0\n    BOOST_MATH_CHECK_THROW(cdf(ichsq, +std::numeric_limits<RealType>::infinity()),std::domain_error ); // x = + infinity, cdf = 1\n    BOOST_MATH_CHECK_THROW(cdf(ichsq, -std::numeric_limits<RealType>::infinity()), std::domain_error); // x = - infinity, cdf = 0\n    BOOST_MATH_CHECK_THROW(cdf(complement(ichsq, +std::numeric_limits<RealType>::infinity())), std::domain_error); // x = + infinity, c cdf = 0\n    BOOST_MATH_CHECK_THROW(cdf(complement(ichsq, -std::numeric_limits<RealType>::infinity())), std::domain_error); // x = - infinity, c cdf = 1\n#ifndef BOOST_NO_EXCEPTIONS\n    BOOST_MATH_CHECK_THROW(boost::math::inverse_chi_squared_distribution<RealType> nbad1(std::numeric_limits<RealType>::infinity(), static_cast<RealType>(1)), std::domain_error); // +infinite mean\n    BOOST_MATH_CHECK_THROW(boost::math::inverse_chi_squared_distribution<RealType> nbad1(-std::numeric_limits<RealType>::infinity(),  static_cast<RealType>(1)), std::domain_error); // -infinite mean\n    BOOST_MATH_CHECK_THROW(boost::math::inverse_chi_squared_distribution<RealType> nbad1(static_cast<RealType>(0), std::numeric_limits<RealType>::infinity()), std::domain_error); // infinite sd\n#else\n    BOOST_MATH_CHECK_THROW(boost::math::inverse_chi_squared_distribution<RealType>(std::numeric_limits<RealType>::infinity(), static_cast<RealType>(1)), std::domain_error); // +infinite mean\n    BOOST_MATH_CHECK_THROW(boost::math::inverse_chi_squared_distribution<RealType>(-std::numeric_limits<RealType>::infinity(),  static_cast<RealType>(1)), std::domain_error); // -infinite mean\n    BOOST_MATH_CHECK_THROW(boost::math::inverse_chi_squared_distribution<RealType>(static_cast<RealType>(0), std::numeric_limits<RealType>::infinity()), std::domain_error); // infinite sd\n#endif\n  }\n\n  if (std::numeric_limits<RealType>::has_quiet_NaN)\n  { // If no longer allow x or p to be NaN, then these tests should throw.\n    BOOST_MATH_CHECK_THROW(pdf(ichsq, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // x = NaN\n    BOOST_MATH_CHECK_THROW(cdf(ichsq, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // x = NaN\n    BOOST_MATH_CHECK_THROW(cdf(complement(ichsq, +std::numeric_limits<RealType>::quiet_NaN())), std::domain_error); // x = + infinity\n    BOOST_MATH_CHECK_THROW(quantile(ichsq, std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // p = + quiet_NaN\n    BOOST_MATH_CHECK_THROW(quantile(complement(ichsq, std::numeric_limits<RealType>::quiet_NaN())), std::domain_error); // p = + quiet_NaN\n  }\n    // Spot check for pdf using 'naive pdf' function\n  for(RealType x = 0.5; x < 5; x += 0.5)\n  {\n    BOOST_CHECK_CLOSE_FRACTION(\n      pdf(inverse_chi_squared_distribution<RealType>(5, 6), x),\n      naive_pdf(RealType(5), RealType(6), x),\n      tolerance);\n  }   // Spot checks for parameters:\n\n  RealType tol_2eps = boost::math::tools::epsilon<RealType>() * 2; // 2 eps as a fraction.\n  inverse_chi_squared_distribution<RealType> dist51(5, 1);\n  inverse_chi_squared_distribution<RealType> dist52(5, 2);\n  inverse_chi_squared_distribution<RealType> dist31(3, 1);\n  inverse_chi_squared_distribution<RealType> dist111(11, 1);\n  // 11 mean 0.10000000000000001, variance  0.0011111111111111111, sd 0.033333333333333333\n\n  using namespace std; // ADL of std names.\n  using namespace boost::math;\n  \n  inverse_chi_squared_distribution<RealType> dist10(10);\n  //  mean, variance etc\n  BOOST_CHECK_CLOSE_FRACTION(mean(dist10), static_cast<RealType>(0.125), tol_2eps);\n  BOOST_CHECK_CLOSE_FRACTION(variance(dist10), static_cast<RealType>(0.0052083333333333333333333333333333333333333333333333L), tol_2eps);\n  BOOST_CHECK_CLOSE_FRACTION(mode(dist10), static_cast<RealType>(0.08333333333333333333333333333333333333333333333L), tol_2eps);\n  BOOST_CHECK_CLOSE_FRACTION(median(dist10), static_cast<RealType>(0.10704554778227709530244586234274024205738435512468L), tol_2eps);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(dist10, median(dist10)), static_cast<RealType>(0.5L), 4 * tol_2eps);\n  BOOST_CHECK_CLOSE_FRACTION(skewness(dist10), static_cast<RealType>(3.4641016151377545870548926830117447338856105076208L), tol_2eps);\n  BOOST_CHECK_CLOSE_FRACTION(kurtosis(dist10), static_cast<RealType>(45), tol_2eps);\n  BOOST_CHECK_CLOSE_FRACTION(kurtosis_excess(dist10), static_cast<RealType>(45-3), tol_2eps);\n\n  tol_2eps = boost::math::tools::epsilon<RealType>() * 2; // 2 eps as a percentage.\n\n  // Special and limit cases:\n\n  RealType mx = (std::numeric_limits<RealType>::max)();\n  RealType mi = (std::numeric_limits<RealType>::min)();\n\n  BOOST_CHECK_EQUAL(\n  pdf(inverse_chi_squared_distribution<RealType>(1),\n    static_cast<RealType>(mx)), // max()\n    static_cast<RealType>(0)\n    );\n\n  BOOST_CHECK_EQUAL(\n  pdf(inverse_chi_squared_distribution<RealType>(1),\n    static_cast<RealType>(mi)), // min()\n    static_cast<RealType>(0)\n    );\n\n  BOOST_CHECK_EQUAL(\n    pdf(inverse_chi_squared_distribution<RealType>(1), static_cast<RealType>(0)), static_cast<RealType>(0));\n  BOOST_CHECK_EQUAL(\n    pdf(inverse_chi_squared_distribution<RealType>(3), static_cast<RealType>(0))\n    , static_cast<RealType>(0.0f));\n  BOOST_CHECK_EQUAL(\n    cdf(inverse_chi_squared_distribution<RealType>(1), static_cast<RealType>(0))\n    , static_cast<RealType>(0.0f));\n  BOOST_CHECK_EQUAL(\n    cdf(inverse_chi_squared_distribution<RealType>(2), static_cast<RealType>(0))\n    , static_cast<RealType>(0.0f));\n  BOOST_CHECK_EQUAL(\n    cdf(inverse_chi_squared_distribution<RealType>(3L), static_cast<RealType>(0L))\n    , static_cast<RealType>(0));\n  BOOST_CHECK_EQUAL(\n    cdf(complement(inverse_chi_squared_distribution<RealType>(1), static_cast<RealType>(0)))\n    , static_cast<RealType>(1));\n  BOOST_CHECK_EQUAL(\n    cdf(complement(inverse_chi_squared_distribution<RealType>(2), static_cast<RealType>(0)))\n    , static_cast<RealType>(1));\n  BOOST_CHECK_EQUAL(\n    cdf(complement(inverse_chi_squared_distribution<RealType>(3), static_cast<RealType>(0)))\n    , static_cast<RealType>(1));\n\n  BOOST_MATH_CHECK_THROW(\n    pdf(\n    inverse_chi_squared_distribution<RealType>(static_cast<RealType>(-1)), // degrees_of_freedom negative.\n    static_cast<RealType>(1)), std::domain_error\n    );\n  BOOST_MATH_CHECK_THROW(\n    pdf(\n    inverse_chi_squared_distribution<RealType>(static_cast<RealType>(8)),\n    static_cast<RealType>(-1)), std::domain_error\n    );\n  BOOST_MATH_CHECK_THROW(\n    cdf(\n    inverse_chi_squared_distribution<RealType>(static_cast<RealType>(-1)),\n    static_cast<RealType>(1)), std::domain_error\n    );\n  BOOST_MATH_CHECK_THROW(\n    cdf(\n    inverse_chi_squared_distribution<RealType>(static_cast<RealType>(8)),\n    static_cast<RealType>(-1)), std::domain_error\n    );\n  BOOST_MATH_CHECK_THROW(\n    cdf(complement(\n    inverse_chi_squared_distribution<RealType>(static_cast<RealType>(-1)),\n    static_cast<RealType>(1))), std::domain_error\n    );\n  BOOST_MATH_CHECK_THROW(\n    cdf(complement(\n    inverse_chi_squared_distribution<RealType>(static_cast<RealType>(8)),\n    static_cast<RealType>(-1))), std::domain_error\n    );\n  BOOST_MATH_CHECK_THROW(\n    quantile(\n    inverse_chi_squared_distribution<RealType>(static_cast<RealType>(-1)),\n    static_cast<RealType>(0.5)), std::domain_error\n    );\n  BOOST_MATH_CHECK_THROW(\n    quantile(\n    inverse_chi_squared_distribution<RealType>(static_cast<RealType>(8)),\n    static_cast<RealType>(-1)), std::domain_error\n    );\n  BOOST_MATH_CHECK_THROW(\n    quantile(\n    inverse_chi_squared_distribution<RealType>(static_cast<RealType>(8)),\n    static_cast<RealType>(1.1)), std::domain_error\n    );\n  BOOST_MATH_CHECK_THROW(\n    quantile(complement(\n    inverse_chi_squared_distribution<RealType>(static_cast<RealType>(-1)),\n    static_cast<RealType>(0.5))), std::domain_error\n    );\n  BOOST_MATH_CHECK_THROW(\n    quantile(complement(\n    inverse_chi_squared_distribution<RealType>(static_cast<RealType>(8)),\n    static_cast<RealType>(-1))), std::domain_error\n    );\n  BOOST_MATH_CHECK_THROW(\n    quantile(complement(\n    inverse_chi_squared_distribution<RealType>(static_cast<RealType>(8)),\n    static_cast<RealType>(1.1))), std::domain_error\n    );\n} // template <class RealType>void test_spots(RealType)\n\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n  BOOST_MATH_CONTROL_FP;\n\n  double tol_few_eps = numeric_limits<double>::epsilon() * 4;\n  \n  // Check that can generate inverse_chi_squared distribution using the two convenience methods:\n  // inverse_chi_squared_distribution; // with default parameters, degrees_of_freedom = 1, scale - 1\n  using boost::math::inverse_chi_squared;\n   \n  // Some constructor tests using default double.\n  double tol4eps = boost::math::tools::epsilon<double>() * 4; // 4 eps as a fraction.\n\n  inverse_chi_squared ichsqdef; // Using typedef and both default parameters.\n\n  BOOST_CHECK_EQUAL(ichsqdef.degrees_of_freedom(), 1.); // df == 1\n  BOOST_CHECK_EQUAL(ichsqdef.scale(), 1); // scale == 1./df\n  BOOST_CHECK_CLOSE_FRACTION(pdf(ichsqdef, 1), 0.24197072451914330, tol4eps);\n  BOOST_CHECK_CLOSE_FRACTION(pdf(ichsqdef, 9), 0.013977156581221969, tol4eps);\n  \n  inverse_chi_squared_distribution<double> ichisq102(10., 2); // Both parameters specified.\n  BOOST_CHECK_EQUAL(ichisq102.degrees_of_freedom(), 10.); // Check both parameters stored OK.\n  BOOST_CHECK_EQUAL(ichisq102.scale(), 2.); // Check both parameters stored OK.\n\n  inverse_chi_squared_distribution<double> ichisq10(10.); // Only df parameter specified (unscaled).\n  BOOST_CHECK_EQUAL(ichisq10.degrees_of_freedom(), 10.); // Check  parameter stored.\n  BOOST_CHECK_EQUAL(ichisq10.scale(), 0.1); // Check default scale = 1/df = 1/10 = 0.1\n  BOOST_CHECK_CLOSE_FRACTION(pdf(ichisq10, 1),  0.00078975346316749169, tol4eps);\n  BOOST_CHECK_CLOSE_FRACTION(pdf(ichisq10, 10), 0.0000000012385799798186384, tol4eps);\n\n  BOOST_CHECK_CLOSE_FRACTION(mode(ichisq10), 0.0833333333333333333333333333333333333333, tol4eps);\n  // nu * xi / nu + 2 = 10 * 0.1 / (10 + 2) = 1/12 =  0.0833333...\n  // mode is not defined in Mathematica.\n  // See Discussion section http://en.wikipedia.org/wiki/Talk:Scaled-inverse-chi-square_distribution\n  // for origin of this formula.\n\n  inverse_chi_squared_distribution<double> ichisq5(5.); // // Only df parameter specified.\n  BOOST_CHECK_EQUAL(ichisq5.degrees_of_freedom(), 5.); // check  parameter stored.\n  BOOST_CHECK_EQUAL(ichisq5.scale(), 1./5.); // check default is 1/df\n  BOOST_CHECK_CLOSE_FRACTION(pdf(ichisq5, 0.2), 3.0510380337346841, tol4eps);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(ichisq5, 0.5), 0.84914503608460956, tol4eps);\n  BOOST_CHECK_CLOSE_FRACTION(cdf(complement(ichisq5, 0.5)), 1 - 0.84914503608460956, tol4eps);\n\n  BOOST_CHECK_CLOSE_FRACTION(quantile(ichisq5, 0.84914503608460956), 0.5, tol4eps*100);\n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(ichisq5, 1. - 0.84914503608460956)), 0.5, tol4eps*100);\n\n  // Check mean, etc spot values.\n  inverse_chi_squared_distribution<double> ichisq81(8., 1.); // degrees_of_freedom = 5, scale = 1\n  BOOST_CHECK_CLOSE_FRACTION(mean(ichisq81),1.33333333333333333333333333333333333333333, tol4eps);\n  BOOST_CHECK_CLOSE_FRACTION(variance(ichisq81), 0.888888888888888888888888888888888888888888888, tol4eps);\n  BOOST_CHECK_CLOSE_FRACTION(skewness(ichisq81), 2 * std::sqrt(8.), tol4eps);\n  inverse_chi_squared_distribution<double> ichisq21(2., 1.);\n  BOOST_CHECK_CLOSE_FRACTION(mode(ichisq21), 0.5, tol4eps);\n  BOOST_CHECK_CLOSE_FRACTION(median(ichisq21), 1.4426950408889634, tol4eps);\n\n  inverse_chi_squared ichsq4(4.); // Using typedef and degrees_of_freedom parameter (and default scale = 1/df).\n  BOOST_CHECK_EQUAL(ichsq4.degrees_of_freedom(), 4.); // df == 4.\n  BOOST_CHECK_EQUAL(ichsq4.scale(), 0.25); // scale  == 1 /df == 1/4.\n\n  inverse_chi_squared ichsq32(3, 2);\n  BOOST_CHECK_EQUAL(ichsq32.degrees_of_freedom(), 3.); // df == 3.\n  BOOST_CHECK_EQUAL(ichsq32.scale(), 2); // scale  == 2\n  \n  inverse_chi_squared ichsq11(1, 1); // Using explicit degrees_of_freedom parameter, and default scale = 1).\n  BOOST_CHECK_CLOSE_FRACTION(mode(ichsq11), 0.3333333333333333333333333333333333333333, tol4eps);\n  // (1 * 1)/ (1 + 2) = 1/3 using Wikipedia nu * xi /(nu + 2)\n  BOOST_CHECK_EQUAL(ichsq11.degrees_of_freedom(), 1.); // df == 1 (default).\n  BOOST_CHECK_EQUAL(ichsq11.scale(), 1.); // scale == 1.\n  /*\n  // Used to find some 'exact' values for testing mean, variance ...\n  // First with scale fixed at unity (Wikipedia definition 1)\n  cout << \"df      scale            mean            variance              sd              median\" << endl;\n  for (int degrees_of_freedom = 8; degrees_of_freedom < 30; degrees_of_freedom++)\n  {\n    inverse_chi_squared ichisq(degrees_of_freedom, 1);\n    cout.precision(17);\n    cout << degrees_of_freedom << \"    \"  << 1 << \"  \" << mean(ichisq) << ' ' \n      << variance(ichisq) << ' ' << standard_deviation(ichisq)\n      << ' ' << median(ichisq) << endl;\n  }\n\n  // Default scale = 1 / df\n  cout << \"|\\n\" << \"df           scale          mean            variance              sd              median\" << endl;\n  for (int degrees_of_freedom = 8; degrees_of_freedom < 30; degrees_of_freedom++)\n  {\n    inverse_chi_squared ichisq(degrees_of_freedom);\n    cout.precision(17);\n    cout << degrees_of_freedom << \"    \"  << 1./degrees_of_freedom << \"  \" << mean(ichisq) << ' ' \n      << variance(ichisq) << ' ' << standard_deviation(ichisq)\n      << ' ' << median(ichisq) << endl;\n  }\n  */\n  inverse_chi_squared_distribution<> ichisq14(14, 1); // Using default RealType double.\n  BOOST_CHECK_CLOSE_FRACTION(mean(ichisq14), 1.166666666666666666666666666666666666666666666, tol4eps);\n  BOOST_CHECK_CLOSE_FRACTION(variance(ichisq14), 0.272222222222222222222222222222222222222222222, tol4eps);\n\n  inverse_chi_squared_distribution<> ichisq121(12); // Using default RealType double.\n  BOOST_CHECK_CLOSE_FRACTION(mean(ichisq121),  0.1, tol4eps);\n  BOOST_CHECK_CLOSE_FRACTION(variance(ichisq121), 0.0025, tol4eps);\n  BOOST_CHECK_CLOSE_FRACTION(standard_deviation(ichisq121), 0.05, tol4eps);\n\n  // and \"using boost::math::inverse_chi_squared_distribution;\".\n  inverse_chi_squared_distribution<> ichsq23(2., 3.); // Using default RealType double.\n  BOOST_CHECK_EQUAL(ichsq23.degrees_of_freedom(), 2.); //\n  BOOST_CHECK_EQUAL(ichsq23.scale(), 3.); //\n  BOOST_MATH_CHECK_THROW(mean(ichsq23), std::domain_error); // Degrees of freedom (nu) must be > 2\n  BOOST_MATH_CHECK_THROW(variance(ichsq23), std::domain_error); // Degrees of freedom (nu) must be > 4\n  BOOST_MATH_CHECK_THROW(skewness(ichsq23), std::domain_error); // Degrees of freedom (nu) must be > 6\n  BOOST_MATH_CHECK_THROW(kurtosis_excess(ichsq23), std::domain_error); // Degrees of freedom (nu) must be > 8\n\n  { // Check relationship between inverse gamma and inverse chi_squared distributions.\n  using boost::math::inverse_gamma_distribution;\n\n  double df = 2.;\n  double scale = 1.;\n  double alpha = df/2; // aka inv_gamma shape\n  double beta = scale /2; // inv_gamma scale.\n \n  inverse_gamma_distribution<> ig(alpha, beta); \n\n  inverse_chi_squared_distribution<> ichsq(df, 1./df); // == default scale.\n  BOOST_CHECK_EQUAL(pdf(ichsq, 0), 0); // Special case of zero x.\n\n  double x = 0.5;\n  BOOST_CHECK_EQUAL(pdf(ig, x), pdf(ichsq, x)); // inv_gamma compared to inv_chisq\n  BOOST_CHECK_EQUAL(cdf(ichsq, 0), 0); // Special case of zero.\n  BOOST_CHECK_EQUAL(cdf(ig, x), cdf(ichsq, x)); // invgamma == invchisq\n\n  // Test pdf by comparing using naive_pdf with relation to inverse gamma distribution\n  // wikipedia http://en.wikipedia.org/wiki/Scaled-inverse-chi-square_distribution related distributions.\n  // So if naive_pdf is correct, inverse_chi_squared_distribution should agree.\n  df = 1.; scale = 1.;\n  BOOST_CHECK_CLOSE_FRACTION(naive_pdf(df, scale, x), pdf(ichsq11, x), tol_few_eps);\n\n  //inverse_gamma_distribution<> igd(df/2, (df * scale)/2); \n  inverse_gamma_distribution<> igd11(df/2, df * scale/2);\n  BOOST_CHECK_CLOSE_FRACTION(naive_pdf(df, scale, x), pdf(igd11, x), tol_few_eps);\n  BOOST_CHECK_CLOSE_FRACTION(naive_pdf(df, scale, x), pdf(ichsq11, x), tol_few_eps);\n\n  df = 2; scale = 1;\n  inverse_gamma_distribution<> igd21(df/2, df * scale/2);\n  inverse_chi_squared_distribution<> ichsq21(df, scale);\n  BOOST_CHECK_CLOSE_FRACTION(naive_pdf(df, scale, x), pdf(igd21, x), tol_few_eps); // 0.54134113294645081 OK \n  BOOST_CHECK_CLOSE_FRACTION(naive_pdf(df, scale, x), pdf(ichsq21, x), tol_few_eps); \n\n  df = 2; scale = 2;\n  inverse_gamma_distribution<> igd22(df/2, df * scale/2);\n  inverse_chi_squared_distribution<> ichsq22(df, scale);\n  BOOST_CHECK_CLOSE_FRACTION(naive_pdf(df, scale, x), pdf(igd22, x), tol_few_eps);\n  BOOST_CHECK_CLOSE_FRACTION(naive_pdf(df, scale, x), pdf(ichsq22, x), tol_few_eps);\n  }\n\n  // Check using float.\n  inverse_chi_squared_distribution<float> igf23(1.f, 2.f); // Using explicit RealType float.\n  BOOST_CHECK_EQUAL(igf23.degrees_of_freedom(), 1.f); //\n  BOOST_CHECK_EQUAL(igf23.scale(), 2.f); //\n  \n  // Check throws from bad parameters.\n  inverse_chi_squared ig051(0.5, 1.); // degrees_of_freedom < 1, so wrong for mean.\n  BOOST_MATH_CHECK_THROW(mean(ig051), std::domain_error);\n  inverse_chi_squared ig191(1.9999, 1.); // degrees_of_freedom < 2, so wrong for variance.\n  BOOST_MATH_CHECK_THROW(variance(ig191), std::domain_error);\n  inverse_chi_squared ig291(2.9999, 1.); // degrees_of_freedom < 3, so wrong for skewness.\n  BOOST_MATH_CHECK_THROW(skewness(ig291), std::domain_error);\n  inverse_chi_squared ig391(3.9999, 1.); // degrees_of_freedom < 1, so wrong for kurtosis and kurtosis_excess.\n  BOOST_MATH_CHECK_THROW(kurtosis(ig391), std::domain_error);\n  BOOST_MATH_CHECK_THROW(kurtosis_excess(ig391), std::domain_error);\n  \n  inverse_chi_squared ig102(10, 2); // Wolfram.com/ page 2, quantile = 2.96859.\n  //http://reference.wolfram.com/mathematica/ref/InverseChiSquareDistribution.html\n  BOOST_CHECK_CLOSE_FRACTION(quantile(ig102, 0.75), 2.96859, 0.000001); \n  BOOST_CHECK_CLOSE_FRACTION(cdf(ig102, 2.96859), 0.75 , 0.000001); \n  BOOST_CHECK_CLOSE_FRACTION(cdf(complement(ig102, 2.96859)), 1 - 0.75 , 0.00001); \n  BOOST_CHECK_CLOSE_FRACTION(quantile(complement(ig102, 1 - 0.75)), 2.96859, 0.000001); \n \n  // Basic sanity-check spot values.\n  // (Parameter value, arbitrarily zero, only communicates the floating point type).\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %\n  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n  test_spots(0.0L); // Test long double.\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x0582))\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\n#endif\n#else\n  std::cout << \"<note>The long double tests have been disabled on this platform \"\n    \"either because the long double overloads of the usual math functions are \"\n    \"not available at all, or because they are too inaccurate for these tests \"\n    \"to pass.</note>\" << std::endl;\n#endif\n\n /*    */\n  \n} // BOOST_AUTO_TEST_CASE( test_main )\n\n/*\n\nOutput:\n\n\n\n\n*/\n\n\n\n", "meta": {"hexsha": "8b18c2d5a6492c3bc06e4fe1b1132ebb67080478", "size": 25799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/test/test_inverse_chi_squared_distribution.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/test/test_inverse_chi_squared_distribution.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/test/test_inverse_chi_squared_distribution.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": 48.954459203, "max_line_length": 198, "alphanum_fraction": 0.7350284895, "num_tokens": 7421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.5846908066672959}}
{"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": "// linpack_unchained.cpp: system solver benchmark with exact solution\n// This program completes the design goal of LINPACK, that is,\n// create an idealized problem where both the input values and the correct answer \n// are expressible in the numerical vocabulary of the computing environment.\n//\n// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.\n//\n// This file is part of the HPRBLAS project, which is released under an MIT Open Source license.\n#pragma warning(disable : 4996)\n#include \"common.hpp\"\n\n#include <iostream>\n#include <typeinfo>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\n// if you need to configure the posit number system, do it before including <hprblas>\n#include <hprblas>\n// matrix generators\n#include <generators/matrix_generators.hpp>\n\nusing namespace std;\nusing namespace sw::universal;\n\n#define BACKEND_MTL 0\n#define BACKEND_EIGEN 1\n\n#if defined(BACKEND_MTL)\n#if ARITHMETIC_POSIT\nusing Tensor = mtl::Tensor<  posit<nbits, es> >;\n#elif ARITHMETIC_INT8\nusing Tensor = mtl::Tensor< uint8_t >;\n#elif ARITHMETIC_FP16\nusing Tensor = mtl::Tensor< fp16 >;\n#endif\n#elif defined(BACKEND_EIGEN)\n#if ARITHMETIC_POSIT\nusing Tensor = Eigen::Tensor<  posit<nbits, es> >;\n#elif ARITHMETIC_INT8\nusing Tensor = Eigen::Tensor< uint8_t >;\n#elif ARITHMETIC_FP16\nusing Tensor = Eigen::Tensor< fp16 >;\n#endif\n#endif\n\nint main(int argc, char** argv)\ntry {\n\tconst size_t nbits = 32;\n\tconst size_t es = 2;\n\n\n\t{\n\t\tusing Scalar = posit<nbits, es>;\n\t\tusing Vector = mtl::dense_vector< Scalar >;\n\t\tusing Matrix = mtl::dense2D< Scalar >;\n\n\t\tconstexpr size_t N = 100;\n\t\tMatrix A(N, N);\n\t\tVector r(N), rtilde(N);\n\t\tVector x(N, 1.0), b(N);\n\t\t// generate a uniform random matrix\n\t\t//sw::hprblas::uniform_rand_sorted(A);\n\t\tsw::hprblas::uniform_rand(A, -100.0, 100.0);\n\n#define MANUAL 0\n#if MANUAL\n\t\tb = A * x;\n\t\tx = --posit<nbits, es>(1); /// 1 - eps\n\t\tr = b - A * x;\n\t\trtilde = r;\n\t\tScalar rho = sw::hprblas::fused_dot<Vector, nbits, es>(rtilde, r);\n\t\tcout << \"rho: \" << double(rho) << endl;\n\t\tsw::hprblas::printVector(cout, \"r: \", r);\n\n#else\n\t\t// Create an ILU(0) preconditioner\n\t\t//itl::pc::ilu_0<Matrix>    P(A);   // <-- this does a LU decomposition with pivoting\n\t\titl::pc::identity<Matrix>\tP(A);\n\n\t\t// Set b such that x == 1 is solution; start with x == 0\n\t\tb = A * x; x = 0;\n\n\t\t// Termination criterion: r < 1e-6 * b or N iterations\n\t\titl::noisy_iteration<Scalar>       iter(b, 500, 1.e-6);\n\n\t\ttry {\n\t\t\t// Solve Ax == b with left preconditioner P\n\t\t\titl::bicgstab(A, x, b, P, iter);\n\t\t}\n\t\tcatch (const std::runtime_error& e) {\n\t\t\tcerr << \"caught solver exception: \" << e.what() << endl;\n\t\t}\n\t\tcatch (...) {\n\t\t\tcerr << \"caught unknown exception using bicgstab\" << endl;\n\t\t}\n\n\t\treturn 0;\n\n#endif\n\n\t\tif (b != x) {\n\t\t\ttypedef typename mtl::Collection<Matrix>::size_type     size_type;\n\t\t\tposit<nbits, es> p, one(1);\n\t\t\tfor (size_type r = 0; r < num_rows(A); ++r) {\n\t\t\t\tsw::universal::quire<nbits, es> q, qt;\n\t\t\t\tfor (size_type c = 0; c < num_cols(A); ++c) {\n\t\t\t\t\tp = A[r][c];\n\t\t\t\t\tq += quire_mul(one, p);\n\t\t\t\t\tqt.reset();\n\t\t\t\t\tqt += quire_mul(one, p);\n\t\t\t\t\tcout << qt << endl;\n\t\t\t\t}\n\t\t\t\tcout << q << endl;\n\n\t\t\t\tconvert(q.to_value(), p);\n\t\t\t\tqt.reset();\n\t\t\t\tqt += quire_mul(posit<nbits, es>(1.0), p);\n\t\t\t\tcout << qt << endl << endl;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tcout << \"Solution vector:\\n\" << x << endl;\n\t\t}\n\t}\n\n\treturn 0;\n\n\t{\n\t\tusing Matrix = mtl::dense2D<float>;\n\t\tusing Vector = mtl::dense_vector<float>;\n\t\tMatrix  A(4, 4), L(4, 4), U(4, 4), LU(4, 4);\n\t\tVector\tx(4), b(4), xx(4);\n\t\tdouble \tc = 1.0;\n\n\t\tsw::hprblas::uniform_rand(A);  // uniform random with values between [0,1]\n\t\tLU = A;\n\t\tlu(LU);\n\t\tcout << A << endl;\n\t\tcout << LU << endl;\n\t}\n\t\n\n\tint nrOfFailedTestCases = 0;\n\treturn nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS;\n}\ncatch (char const* msg) {\n\tstd::cerr << \"caught ad hoc exception: \" << msg << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_arithmetic_exception& err) {\n\tstd::cerr << \"caught posit_arithmetic_exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_internal_exception& err) {\n\tstd::cerr << \"caught posit_internal_exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const quire_exception& err) {\n\tstd::cerr << \"caught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const mtl::domain_error& err) {\n\tstd::cerr << \"caught linear algebra domain exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const itl::search_space_exhaustion& err) {\n\tstd::cerr << \"caught iterative solver domain exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const std::runtime_error& err) {\n\tstd::cerr << \"caught runtime_error: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tstd::cerr << \"caught unknown exception\" << std::endl;\n\treturn EXIT_FAILURE;\n}\n", "meta": {"hexsha": "904bf884a2b88a64496b6d4effbaf60c2943ad0c", "size": 4843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/blas/linpack_unchained.cpp", "max_stars_repo_name": "shikharvashistha/hpr-blas", "max_stars_repo_head_hexsha": "73f109d45701fc3816af0a1ecd42f11d494a6f97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-02-13T10:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T20:30:58.000Z", "max_issues_repo_path": "applications/blas/linpack_unchained.cpp", "max_issues_repo_name": "jamesquinlan/hpr-blas", "max_issues_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-20T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T11:19:32.000Z", "max_forks_repo_path": "applications/blas/linpack_unchained.cpp", "max_forks_repo_name": "jamesquinlan/hpr-blas", "max_forks_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T21:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T05:35:35.000Z", "avg_line_length": 27.0558659218, "max_line_length": 96, "alphanum_fraction": 0.6504232913, "num_tokens": 1511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5846877999093137}}
{"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": "#ifndef MATHTOOLBOX_CLASSICAL_MDS_HPP\n#define MATHTOOLBOX_CLASSICAL_MDS_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\nnamespace mathtoolbox\n{\n    /// \\brief Compute low-dimensional embedding by using classical multi-dimensional scaling (MDS)\n    ///\n    /// \\param D Distance (dissimilarity) matrix\n    ///\n    /// \\param target_dim Target dimensionality\n    ///\n    /// \\return Coordinate matrix whose i-th column corresponds to the embedded coordinates of the i-th entry\n    Eigen::MatrixXd ComputeClassicalMds(const Eigen::MatrixXd& D, const unsigned taregt_dim);\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_CLASSICAL_MDS_HPP\n", "meta": {"hexsha": "7aa23aa206ed96c63586b97c66ce797ae8e192a2", "size": 646, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/classical-mds.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/classical-mds.hpp", "max_issues_repo_name": "yuki-koyama/mathtoolbox", "max_issues_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "include/mathtoolbox/classical-mds.hpp", "max_forks_repo_name": "yuki-koyama/mathtoolbox", "max_forks_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 32.3, "max_line_length": 109, "alphanum_fraction": 0.7523219814, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645723, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.5846445283748061}}
{"text": "//####### Test module for utilites ####################################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"utilites\"\n\n//Will automatically define a main for this test\n #define BOOST_TEST_DYN_LINK\n\n //Include Boost unit tests library & library for floating point comparison\n #include <boost/test/unit_test.hpp>\n #include <boost/test/floating_point_comparison.hpp>\n\n//Units choice. Not relevant here, but avoids compile-time warning\n#define PXRMP_USE_SI_UNITS\n\n#include \"utilities.hpp\"\n\nusing namespace picsar::multi_physics;\n\n// ------------- Tests --------------\n\n// ------------- Tests --------------\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-10;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-4;\n\n//Templated tolerance\ntemplate <typename T>\nT tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\n//Test generate_lin_spaced_vec generic\ntemplate<typename _WHATEVER>\nvoid test_generate_lin_spaced_vec(_WHATEVER min, _WHATEVER max, size_t size)\n{\n    std::vector<_WHATEVER> vv =\n        generate_lin_spaced_vec<_WHATEVER>(min, max, size);\n\n    BOOST_CHECK_EQUAL(vv.size(), size);\n    BOOST_CHECK_EQUAL(vv.front(), min);\n    BOOST_CHECK_EQUAL(vv.back(), max);\n\n    _WHATEVER expdiff =(max-min)/(size-1) ;\n\n    for(size_t i = 1; i < vv.size(); ++i){\n        _WHATEVER diff = vv[i]-vv[i-1];\n        BOOST_CHECK_SMALL((diff-expdiff)/expdiff, tolerance<_WHATEVER>());\n    }\n}\n\n\n//Test generate_lin_spaced_vec generic with double precision\nBOOST_AUTO_TEST_CASE( test_generate_lin_spaced_vec_double_1 )\n{\n    test_generate_lin_spaced_vec<double>(-73, 112, 500);\n}\n\n//Test generate_lin_spaced_vec generic with single precision\nBOOST_AUTO_TEST_CASE( test_generate_lin_spaced_vec_single_1 )\n{\n    test_generate_lin_spaced_vec<float>(-73, 112, 500);\n}\n\n\n//Test generate_log_spaced_vec generic\ntemplate<typename _WHATEVER>\nvoid test_generate_log_spaced_vec(_WHATEVER min, _WHATEVER max, size_t size)\n{\n    std::vector<_WHATEVER> vv =\n        generate_log_spaced_vec<_WHATEVER>(min, max, size);\n\n    BOOST_CHECK_EQUAL(vv.size(), size);\n    BOOST_CHECK_EQUAL(vv.front(), min);\n    BOOST_CHECK_EQUAL(vv.back(), max);\n\n    _WHATEVER mul = pow(max/min, static_cast<_WHATEVER>(1.0/(size-1)));\n\n    for(size_t i = 1; i < vv.size(); ++i){\n        _WHATEVER ratio = vv[i]/vv[i-1];\n        BOOST_CHECK_SMALL((ratio-mul)/mul, tolerance<_WHATEVER>());\n    }\n}\n\n\n//Test generate_log_spaced_vec generic with double precision\nBOOST_AUTO_TEST_CASE( test_generate_log_spaced_vec_double_1 )\n{\n    test_generate_log_spaced_vec<double>(0.01, 100.0, 200);\n}\n\n//Test generate_log_spaced_vec generic with single precision\nBOOST_AUTO_TEST_CASE( test_generate_log_spaced_vec_single_1 )\n{\n    test_generate_log_spaced_vec<float>(0.01, 100.0, 200);\n}\n", "meta": {"hexsha": "a5668912f309d1e455be3ce2e9b53f079e4d5551", "size": 2877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED_tests/test_utilities.cpp", "max_stars_repo_name": "thaisacs/PICSAR", "max_stars_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multi_physics/QED_tests/test_utilities.cpp", "max_issues_repo_name": "thaisacs/PICSAR", "max_issues_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multi_physics/QED_tests/test_utilities.cpp", "max_forks_repo_name": "thaisacs/PICSAR", "max_forks_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6634615385, "max_line_length": 76, "alphanum_fraction": 0.7142857143, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.5846445257447541}}
{"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// Created by tkhamvilai on 7/16/19.\n//\n\n#ifndef DIST_MILP_MATHHELPERFUNCTIONS_HPP\n#define DIST_MILP_MATHHELPERFUNCTIONS_HPP\n\n#include <vector>\n#include <algorithm>\n#include <Eigen/Dense>\n\nbool MathHelperFunctions_isSubset(std::vector<int> arr1, std::vector<int> arr2);\nint MathHelperFunctions_norm_of_difference(int i, int j, Eigen::MatrixXi mat);\nint MathHelperFunctions_Intersection(std::vector<int> arr1, std::vector<int> arr2);\n\n#endif //DIST_MILP_MATHHELPERFUNCTIONS_HPP\n", "meta": {"hexsha": "5f2c6477637874cdf5d7d8c92ed322521c64e501", "size": 480, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/MathHelperFunctions.hpp", "max_stars_repo_name": "Hakiwen/dist-milp", "max_stars_repo_head_hexsha": "9d876ef5c0c160b0b6057c24bb13b97f8edd7ea4", "max_stars_repo_licenses": ["MIT"], "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/MathHelperFunctions.hpp", "max_issues_repo_name": "Hakiwen/dist-milp", "max_issues_repo_head_hexsha": "9d876ef5c0c160b0b6057c24bb13b97f8edd7ea4", "max_issues_repo_licenses": ["MIT"], "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/MathHelperFunctions.hpp", "max_forks_repo_name": "Hakiwen/dist-milp", "max_forks_repo_head_hexsha": "9d876ef5c0c160b0b6057c24bb13b97f8edd7ea4", "max_forks_repo_licenses": ["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.2352941176, "max_line_length": 83, "alphanum_fraction": 0.8, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.5845392653055362}}
{"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": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdTgamma, Fvar) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::tgamma;\n\n  fvar<double> x(0.5, 1.0);\n  fvar<double> a = tgamma(x);\n  EXPECT_FLOAT_EQ(tgamma(0.5), a.val_);\n  EXPECT_FLOAT_EQ(tgamma(0.5) * digamma(0.5), a.d_);\n}\n\nstruct tgamma_fun {\n  template <typename T0>\n  inline T0 operator()(const T0& arg1) const {\n    return tgamma(arg1);\n  }\n};\n\nTEST(AgradFwdTgamma, tgamma_NaN_0) {\n  tgamma_fun tgamma_;\n  test_nan_fwd(tgamma_, false);\n}\n", "meta": {"hexsha": "cae7a6cd683ded6821d63555057159d9844c1b70", "size": 690, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/fwd/scal/fun/tgamma_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/fwd/scal/fun/tgamma_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/fwd/scal/fun/tgamma_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7931034483, "max_line_length": 52, "alphanum_fraction": 0.7057971014, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5845089441150095}}
{"text": "#ifndef _TEST_FIXTURES_H_\n#define _TEST_FIXTURES_H_\n#include <iostream> \n#include <iomanip> \n#include <vector>\n#include <cmath>\n//#include \"mxn_indexer.hpp\"\n#include <boost/static_assert.hpp>\n#include \"boost/multi_array.hpp\"\n\n//http://www.boost.org/doc/libs/1_55_0/libs/multi_array/doc/user.html\n//http://stackoverflow.com/questions/2168082/how-to-rewrite-array-from-row-order-to-column-order\n#include \"image_stack_utils.h\"\n#include \"test_algorithms.hpp\"\n\nnamespace anyfold {\n\ntemplate <unsigned short KernelDimSize = 3, \n\t  unsigned ImageDimSize = 8\n\t  >\nstruct convolutionFixture3D\n{\n\n  \n  const unsigned    image_size_   ;\n  std::vector<int>  image_shape_                             ;\n  std::vector<int>  padded_image_shape_                             ;\n\n  image_stack       image_                           ;\n  image_stack       padded_image_                           ;\n  image_stack       padded_one_                           ;\n  image_stack       padded_output_                           ;\n\n  image_stack       image_folded_by_horizontal_             ;\n  image_stack       image_folded_by_vertical_               ;\n  image_stack       image_folded_by_depth_                  ;\n  image_stack       image_folded_by_all1_                   ;\n\n  image_stack       padded_image_folded_by_horizontal_             ;\n  image_stack       padded_image_folded_by_vertical_               ;\n  image_stack       padded_image_folded_by_depth_                  ;\n  image_stack       padded_image_folded_by_all1_                   ;\n\n  const unsigned    kernel_size_  ;\n  std::vector<int>  kernel_dims_                            ;\n  std::vector<int>  asymm_kernel_dims_                            ;\n\n  image_stack       trivial_kernel_                         ;\n  image_stack       identity_kernel_                        ;\n  image_stack       vertical_kernel_                        ;\n  image_stack       horizontal_kernel_                        ;\n  image_stack       depth_kernel_                           ;\n  image_stack       all1_kernel_                           ;\n\n  \n  BOOST_STATIC_ASSERT(KernelDimSize % 2 != 0);\n\npublic:\n  \n  convolutionFixture3D():\n    image_size_                             ((unsigned)std::pow(ImageDimSize,3)),\n    image_shape_                             (3,ImageDimSize),\n    padded_image_shape_                             (3,ImageDimSize+2*(KernelDimSize/2)),\n    image_                           (boost::extents[ImageDimSize][ImageDimSize][ImageDimSize]),\n    padded_image_                           (boost::extents[ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)]),\n    padded_one_                           (boost::extents[ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)]),\n    padded_output_                           (boost::extents[ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)]),\n    image_folded_by_horizontal_             (boost::extents[ImageDimSize][ImageDimSize][ImageDimSize]),\n    image_folded_by_vertical_               (boost::extents[ImageDimSize][ImageDimSize][ImageDimSize]),\n    image_folded_by_depth_                  (boost::extents[ImageDimSize][ImageDimSize][ImageDimSize]),\n    image_folded_by_all1_                   (boost::extents[ImageDimSize][ImageDimSize][ImageDimSize]),\n    padded_image_folded_by_horizontal_             (boost::extents[ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)]),\n    padded_image_folded_by_vertical_               (boost::extents[ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)]),\n    padded_image_folded_by_depth_                  (boost::extents[ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)]),\n    padded_image_folded_by_all1_                   (boost::extents[ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)][ImageDimSize+2*(KernelDimSize/2)]),\n    kernel_size_                            ((unsigned)std::pow(KernelDimSize,3)),\n    kernel_dims_                            (3,KernelDimSize),\n    asymm_kernel_dims_                            (3,KernelDimSize),\n    trivial_kernel_                         (boost::extents[KernelDimSize][KernelDimSize][KernelDimSize]),\n    identity_kernel_                        (boost::extents[KernelDimSize][KernelDimSize][KernelDimSize]),\n    vertical_kernel_                        (boost::extents[KernelDimSize][KernelDimSize][KernelDimSize]),\n    horizontal_kernel_                        (boost::extents[KernelDimSize][KernelDimSize][KernelDimSize]),\n    depth_kernel_                           (boost::extents[KernelDimSize][KernelDimSize][KernelDimSize]),\n    all1_kernel_                           (boost::extents[KernelDimSize][KernelDimSize][KernelDimSize])\n  {\n    \n    //FILL KERNELS\n    const unsigned halfKernel  = KernelDimSize/2u;\n        \n    std::fill(trivial_kernel_.data()       ,trivial_kernel_.data()       +  kernel_size_                           ,0.f);\n    std::fill(identity_kernel_.data()      ,identity_kernel_.data()      +  kernel_size_                           ,0.f);\n    std::fill(vertical_kernel_.data()      ,vertical_kernel_.data()      +  kernel_size_                           ,0.f);\n    std::fill(depth_kernel_.data()         ,depth_kernel_.data()         +  kernel_size_                           ,0.f);\n    std::fill(all1_kernel_.data()         ,all1_kernel_.data()         +  kernel_size_                           ,1.f);\n    std::fill(horizontal_kernel_.data()      ,horizontal_kernel_.data()      +  kernel_size_                           ,0.f);\n\n\n    identity_kernel_[KernelDimSize/2][KernelDimSize/2][KernelDimSize/2]=1.; \n\n    for(unsigned int index = 0;index<KernelDimSize;++index){\n      horizontal_kernel_[index][halfKernel][halfKernel] = float(index+1);\n      vertical_kernel_[halfKernel][index][halfKernel] = float(index+1);\n      depth_kernel_   [halfKernel][halfKernel][index] = float(index+1);\n    }\n    \n    //FILL IMAGES\n    unsigned padded_image_axis = ImageDimSize+2*halfKernel;\n    unsigned padded_image_size = std::pow(padded_image_axis,3);\n    std::fill(padded_image_.data(),  padded_image_.data()  +  padded_image_size,  0.f  );\n    std::fill(padded_one_.data(),  padded_one_.data()  +  padded_image_size,  0.f  );\n    std::fill(padded_output_.data(),  padded_output_.data()  +  padded_image_size,  0.f  );\n    std::fill(padded_image_folded_by_horizontal_.data(),  padded_image_folded_by_horizontal_.data()  +  padded_image_size,  0.f  );\n    std::fill(padded_image_folded_by_vertical_.data(),  padded_image_folded_by_vertical_.data()  +  padded_image_size,  0.f  );\n    std::fill(padded_image_folded_by_depth_.data(),  padded_image_folded_by_depth_.data()  +  padded_image_size,  0.f  );\n    std::fill(padded_image_folded_by_all1_.data(),  padded_image_folded_by_all1_.data()  +  padded_image_size,  0.f  );\n\n    padded_one_[padded_image_axis/2][padded_image_axis/2][padded_image_axis/2] = 1.f;\n\n    for (unsigned pixel = 0; pixel < image_.num_elements(); ++pixel)\n      image_.data()[pixel] = float(pixel);\n\t\n      \n\n    //PADD THE IMAGE FOR CONVOLUTION\n    range axis_subrange = range(halfKernel,halfKernel+ImageDimSize);\n    image_stack_view padded_image_original = padded_image_[ boost::indices[axis_subrange][axis_subrange][axis_subrange] ];\n    padded_image_original = image_;\n    \n    padded_image_folded_by_horizontal_  = padded_image_;\n    padded_image_folded_by_vertical_    = padded_image_;\n    padded_image_folded_by_depth_       = padded_image_;\n    padded_image_folded_by_all1_        = padded_image_;\n\n    //PREPARE ASYMM IMAGES\n    std::vector<unsigned> symm_offsets(3);\n    std::fill(symm_offsets.begin(), symm_offsets.end(), halfKernel);\n\n    //CONVOLVE\n    convolve(padded_image_, horizontal_kernel_, padded_image_folded_by_horizontal_, symm_offsets);\n    convolve(padded_image_, vertical_kernel_, padded_image_folded_by_vertical_, symm_offsets);\n    convolve(padded_image_, depth_kernel_, padded_image_folded_by_depth_, symm_offsets);\n    convolve(padded_image_, all1_kernel_, padded_image_folded_by_all1_, symm_offsets);\n    \n    //EXTRACT NON-PADDED CONTENT FROM CONVOLVED IMAGE STACKS\n    image_folded_by_horizontal_  = padded_image_folded_by_horizontal_[ boost::indices[axis_subrange][axis_subrange][axis_subrange] ];\n    image_folded_by_vertical_    = padded_image_folded_by_vertical_[ boost::indices[axis_subrange][axis_subrange][axis_subrange] ];\n    image_folded_by_depth_       = padded_image_folded_by_depth_[ boost::indices[axis_subrange][axis_subrange][axis_subrange] ];\n    image_folded_by_all1_        = padded_image_folded_by_all1_[ boost::indices[axis_subrange][axis_subrange][axis_subrange] ];\n\n  }\n  \n   virtual ~convolutionFixture3D()  { \n    \n  };\n    \n  static const unsigned image_axis_size = ImageDimSize;\n  static const unsigned kernel_axis_size = KernelDimSize;\n\n};\n\ntypedef convolutionFixture3D<> default_3D_fixture;\n\n\n}\n\n#endif\n", "meta": {"hexsha": "58c4cd4b4f96646eaf05b7860339bccb3fd323dc", "size": 9107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/test_fixtures.hpp", "max_stars_repo_name": "abred/anyfold", "max_stars_repo_head_hexsha": "0db49fa611001836cf4ee9408b681dfcd9aeccbf", "max_stars_repo_licenses": ["MIT"], "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_fixtures.hpp", "max_issues_repo_name": "abred/anyfold", "max_issues_repo_head_hexsha": "0db49fa611001836cf4ee9408b681dfcd9aeccbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_fixtures.hpp", "max_forks_repo_name": "abred/anyfold", "max_forks_repo_head_hexsha": "0db49fa611001836cf4ee9408b681dfcd9aeccbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.5329341317, "max_line_length": 170, "alphanum_fraction": 0.6464258263, "num_tokens": 2233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.584508938587308}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2020 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <nil/crypto3/multiprecision/mpfr.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include \"test.hpp\"\n\nusing namespace nil::crypto3::multiprecision;\n\nint main() {\n    mpfr_float_50 half = 0.5;\n    mpfr_float_50 under_half = boost::math::float_prior(half);\n    BOOST_CHECK_NE(half, under_half);\n    int e1, e2;\n    mpfr_float_50 norm1, norm2;\n    norm1 = frexp(half, &e1);\n    norm2 = frexp(under_half, &e2);\n    BOOST_CHECK_EQUAL(norm1, half);\n    BOOST_CHECK_EQUAL(e1, 0);\n    BOOST_CHECK_GT(1, norm2);\n    BOOST_CHECK_LE(0.5, norm2);\n    BOOST_CHECK_EQUAL(e2, -1);\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "ab1aa5ddb214084559a6e57ad2c6f14a704267f3", "size": 887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/multiprecision/test/git_issue_265.cpp", "max_stars_repo_name": "idealatom/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "libs/multiprecision/test/git_issue_265.cpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/multiprecision/test/git_issue_265.cpp", "max_forks_repo_name": "Curryrasul/knapsack-snark", "max_forks_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:53:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:53:21.000Z", "avg_line_length": 32.8518518519, "max_line_length": 79, "alphanum_fraction": 0.6448703495, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5845089334060799}}
{"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": "#include \"sv/util/math.h\"\n\n#include <Eigen/Geometry>\n\nnamespace sv {\n\nvoid MakeRightHanded(Eigen::Vector3d& eigvals, Eigen::Matrix3d& eigvecs) {\n  auto hand = eigvecs.col(0).cross(eigvecs.col(1)).dot(eigvecs.col(2));\n  if (hand < 0) {\n    eigvecs.col(0).swap(eigvecs.col(1));\n    eigvals.row(0).swap(eigvals.row(1));\n  }\n}\n\n}  // namespace sv\n", "meta": {"hexsha": "19b2bdbc084092ec157647b45cafeca37eae5af1", "size": 343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sv/util/math.cpp", "max_stars_repo_name": "iandouglas96/llol", "max_stars_repo_head_hexsha": "028fe73d4f4f9214b4534cbedb9b53dff039e84f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T02:03:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:11:52.000Z", "max_issues_repo_path": "sv/util/math.cpp", "max_issues_repo_name": "iandouglas96/llol", "max_issues_repo_head_hexsha": "028fe73d4f4f9214b4534cbedb9b53dff039e84f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-01-14T15:22:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T20:07:44.000Z", "max_forks_repo_path": "sv/util/math.cpp", "max_forks_repo_name": "iandouglas96/llol", "max_forks_repo_head_hexsha": "028fe73d4f4f9214b4534cbedb9b53dff039e84f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2022-03-17T06:13:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T09:15:58.000Z", "avg_line_length": 21.4375, "max_line_length": 74, "alphanum_fraction": 0.6618075802, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.5844198564931108}}
{"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\u2081 - t\u2082|\u2082\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 \u03b8\n  // 1 - cos \u03b8 = 3/2 - tr(R)/2 \u2208 [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#include <NTL/ZZ_pXFactoring.h>\n\nNTL_CLIENT\n\n\nlong compare(const ZZ_pX& a, const ZZ_pX& b)\n{\n   if (deg(a) < deg(b))\n      return 0;\n\n   if (deg(a) > deg(b))\n      return 1;\n\n   long n = a.rep.length();\n   long i;\n\n   for (i = 0; i < n; i++) {\n      if (rep(a.rep[i]) < rep(b.rep[i])) return 0;\n      if (rep(a.rep[i]) > rep(b.rep[i])) return 1;\n   }\n\n   return 0;\n}\n\nvoid sort(vec_pair_ZZ_pX_long& v)\n{\n   long n = v.length();\n   long i, j;\n\n   for (i = 0; i < n-1; i++)\n      for (j = 0; j < n-1-i; j++)\n         if (compare(v[j].a, v[j+1].a)) {\n            swap(v[j].a, v[j+1].a);\n            swap(v[j].b, v[j+1].b);\n         }\n}\n\n\nint main()\n{\n   ZZ p;\n   cin >> p;\n   ZZ_p::init(p);\n   ZZ_pX f;\n   cin >> f;\n\n   vec_pair_ZZ_pX_long factors;\n\n   double t = GetTime();\n   berlekamp(factors, f, 1);\n   t = GetTime()-t;\n   cerr << \"total time: \" << t << \"\\n\";\n\n   ZZ_pX ff;\n\n   mul(ff, factors);\n   if (f != ff)\n      Error(\"Incorrect factorization!!\");\n\n   sort(factors);\n\n   cerr << \"factorization pattern:\";\n   long i;\n\n   for (i = 0; i < factors.length(); i++) {\n      cerr << \" \";\n      long k = factors[i].b;\n      if (k > 1)\n         cerr << k << \"*\";\n      cerr << deg(factors[i].a);\n   }\n\n   cerr << \"\\n\";\n\n\n\n   cout << factors << \"\\n\";\n\n   return 0;\n}\n", "meta": {"hexsha": "13474e79f7020e8111043f7755058962a6d148f0", "size": 1264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/tests/BerlekampTest.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RUNETag/WinNTL/tests/BerlekampTest.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/tests/BerlekampTest.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.4146341463, "max_line_length": 50, "alphanum_fraction": 0.4612341772, "num_tokens": 446, "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// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file linear_programming_test.cpp\n * @brief\n * @author Piotr Godlewski\n * @version 1.0\n * @date 2014-04-07\n */\n\n#include \"test_utils/logger.hpp\"\n\n#include \"paal/lp/glp.hpp\"\n#include \"paal/utils/floating.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/mpl/list.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <unordered_map>\n#include <vector>\n\nusing namespace paal;\n\nusing lp_types = boost::mpl::list<lp::glp>;\n\ntemplate <typename LP>\nvoid log_solution(lp::problem_type status, const LP &lp_instance) {\n    if (status == lp::OPTIMAL) {\n        LOGLN(\"Optimal solution cost: \" << lp_instance.get_obj_value());\n        for (auto column : lp_instance.get_columns()) {\n            boost::ignore_unused_variable_warning(column);\n            LOGLN(lp_instance.get_col_name(column)\n                  << \" = \" << lp_instance.get_col_value(column));\n        }\n    } else {\n        LOGLN(\"Optimal solution not found\");\n    }\n}\n\nBOOST_AUTO_TEST_SUITE(linear_programming_test)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(linear_programming_example, LP, lp_types) {\n    // sample problem\n    LP lp_instance;\n\n    lp_instance.set_optimization_type(lp::MAXIMIZE);\n    auto X = lp_instance.add_column(500, 0, lp::lp_traits::PLUS_INF, \"x\");\n    auto Y = lp_instance.add_column(300, 0, lp::lp_traits::PLUS_INF, \"y\");\n\n    auto expr = X + Y;\n    lp_instance.add_row(expr >= 7);\n    auto row = lp_instance.add_row(expr <= 10);\n    lp_instance.add_row(15 <= 200 * X + 100 * Y <= 1200);\n\n    // solve it\n    auto status = lp_instance.solve_simplex();\n    log_solution(status, lp_instance);\n\n    // add new row\n    expr += Y;\n    lp_instance.add_row(expr == 12);\n\n    // resolve it\n    status = lp_instance.resolve_simplex(lp::DUAL);\n    log_solution(status, lp_instance);\n\n    // delete row\n    lp_instance.delete_row(row);\n\n    // resolve it\n    status = lp_instance.resolve_simplex();\n    log_solution(status, lp_instance);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(linear_programming_expressions, LP, lp_types) {\n    LP lp_instance;\n\n    lp_instance.set_optimization_type(lp::MAXIMIZE);\n    auto X = lp_instance.add_column(500);\n    auto Y = lp_instance.add_column(300);\n    auto Z = lp_instance.add_column(150);\n    auto T = lp_instance.add_column(200);\n\n    auto expr1 = X + Y + 2 * T;\n    expr1 -= Y;\n    auto expr2 = 2 * expr1 - 3 * Z;\n    expr1 += Y * 0.5;\n    expr2 += T;\n    auto expr3 = expr2 * 0.1 - (Y * 0.3 + 2 * X) * 0.5 + 1 * expr1;\n\n    auto row1 = lp_instance.add_row(expr1 >= 7);\n    auto row2 = lp_instance.add_row(expr1 <= 10);\n    auto row3 = lp_instance.add_row(expr2 == 8.5);\n    auto row4 = lp_instance.add_row(-10 <= expr3 <= 20);\n\n    expr1 = lp::linear_expression();\n    expr1 += X;\n    expr1 -= T * 1;\n    expr1 = expr1 + Z;\n    expr1 = T + expr1;\n\n    auto row5 = lp_instance.add_row(expr1 <= 100);\n\n    auto U = lp_instance.add_column(-50);\n\n    auto expr4 =\n        -U + U + 0.2 * (X * 7 + (U + X) * 3) + U + 2 * U + 5 * X + (T - T) * 11;\n\n    auto row6 = lp_instance.add_row(expr4 >= 3);\n\n    lp_instance.set_row_expression(\n        row2, lp_instance.get_row_expression(row2) + 5 * U);\n    lp_instance.set_row_expression(\n        row3, lp_instance.get_row_expression(row3) - 2 * U);\n\n    // solve it\n    lp_instance.solve_simplex();\n\n    std::vector<lp::col_id> columns = { X, Y, Z, T, U };\n    std::vector<lp::row_id> rows = { row1, row2, row3, row4, row5, row6 };\n    std::vector<std::vector<double>> coefs = {\n        { 1, 0.5, 0, 2, 0 }, { 1, 0.5, 0, 2, 5 }, { 2, 0, -3, 5, -2 },\n        { 0.2, 0.35, -0.3, 2.5, 0 }, { 1, 0, 1, 0, 0 }, { 7, 0, 0, 0, 3.6 },\n    };\n    std::vector<int> row_degrees = { 3, 4, 4, 4, 2, 2 };\n    std::vector<int> col_degrees = { 6, 3, 3, 4, 3 };\n    const double MAX = lp::lp_traits::PLUS_INF;\n    const double MIN = lp::lp_traits::MINUS_INF;\n    std::vector<double> lower_bounds = { 7, MIN, 8.5, -10, MIN, 3 };\n    std::vector<double> upper_bounds = { MAX, 10, 8.5, 20, 100, MAX };\n\n    for (int row_num : paal::irange(rows.size())) {\n        auto expr = lp_instance.get_row_expression(rows[row_num]);\n        for (int col_num : paal::irange(columns.size())) {\n            BOOST_CHECK_SMALL(expr.get_coefficient(columns[col_num]) -\n                                  coefs[row_num][col_num],\n                              std::numeric_limits<double>::epsilon());\n        }\n        if (lower_bounds[row_num] == MIN) {\n            BOOST_CHECK(lp_instance.get_row_lower_bound(rows[row_num]) ==\n                        lower_bounds[row_num]);\n        } else {\n            BOOST_CHECK_SMALL(lp_instance.get_row_lower_bound(rows[row_num]) -\n                                  lower_bounds[row_num],\n                              std::numeric_limits<double>::epsilon());\n        }\n        if (upper_bounds[row_num] == MAX) {\n            BOOST_CHECK(lp_instance.get_row_upper_bound(rows[row_num]) ==\n                        upper_bounds[row_num]);\n        } else {\n            BOOST_CHECK_SMALL(lp_instance.get_row_upper_bound(rows[row_num]) -\n                                  upper_bounds[row_num],\n                              std::numeric_limits<double>::epsilon());\n        }\n        BOOST_CHECK_EQUAL(lp_instance.get_row_degree(rows[row_num]),\n                          row_degrees[row_num]);\n    }\n\n    for (int col_num : paal::irange(columns.size())) {\n        BOOST_CHECK_EQUAL(lp_instance.get_col_degree(columns[col_num]),\n                          col_degrees[col_num]);\n    }\n}\n\ntemplate <typename LP>\nvoid run_single_solve_test(lp::simplex_type solve_type,\n                           lp::simplex_type resolve_type) {\n    LP lp(\"test instance\", lp::MAXIMIZE);\n    auto X = lp.add_column(500, 0, lp::lp_traits::PLUS_INF, \"x\");\n    auto Y = lp.add_column(300, 0, lp::lp_traits::PLUS_INF, \"y\");\n    lp.add_row(10 >= X + Y >= 7);\n    lp.add_row(200 * X + 100 * Y <= 1200);\n\n    auto status = lp.solve_simplex(solve_type);\n    BOOST_CHECK_EQUAL(status, lp::OPTIMAL);\n    BOOST_CHECK_SMALL(lp.get_obj_value() - 3400,\n                      std::numeric_limits<double>::epsilon());\n    BOOST_CHECK_SMALL(lp.get_col_value(X) - 2,\n                      4 * std::numeric_limits<double>::epsilon());\n    BOOST_CHECK_SMALL(lp.get_col_value(Y) - 8,\n                      10 * std::numeric_limits<double>::epsilon());\n\n    lp.add_row(12 >= X + 2 * Y);\n\n    status = lp.resolve_simplex(resolve_type);\n    BOOST_CHECK_EQUAL(status, lp::OPTIMAL);\n    BOOST_CHECK_SMALL(lp.get_obj_value() - 3200,\n                      std::numeric_limits<double>::epsilon());\n    BOOST_CHECK_SMALL(lp.get_col_value(X) - 4,\n                      std::numeric_limits<double>::epsilon());\n    BOOST_CHECK_SMALL(lp.get_col_value(Y) - 4,\n                      std::numeric_limits<double>::epsilon());\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(linear_programming_solve, LP, lp_types) {\n    run_single_solve_test<LP>(lp::PRIMAL, lp::PRIMAL);\n    run_single_solve_test<LP>(lp::PRIMAL, lp::DUAL);\n    run_single_solve_test<LP>(lp::DUAL, lp::PRIMAL);\n    run_single_solve_test<LP>(lp::DUAL, lp::DUAL);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(linear_programming_methods, LP, lp_types) {\n    LP lp(\"test instance\", lp::MAXIMIZE);\n    // add rows and colums\n    auto X = lp.add_column(12, -9, 2.5, \"x\");\n    auto Y = lp.add_column(33, 5, lp::lp_traits::PLUS_INF, \"y\");\n    auto row1 = lp.add_row(X + 3.5 * Y, \"row1\");\n    auto row2 = lp.add_row(0 >= (Y + 2 * X) * 0.1, \"row2\");\n    auto row3 = lp.add_row(1 <= 0.04 * X + 23.7 * Y, \"row3\");\n    auto row4 = lp.add_row(-1 <= Y + 0.2 * X <= 11.2, \"row4\");\n\n    BOOST_CHECK_EQUAL(lp.columns_number(), 2);\n    std::unordered_map<lp::col_id, std::string> columns(\n        { { X, \"x\" }, { Y, \"y\" } });\n    for (auto col : lp.get_columns()) {\n        BOOST_CHECK(columns.find(col) != columns.end());\n        BOOST_CHECK_EQUAL(lp.get_col_name(col), columns.find(col)->second);\n        BOOST_CHECK_EQUAL(lp.get_col_degree(col), 4);\n        BOOST_CHECK_EQUAL(boost::distance(lp.get_rows_in_column(col)), 4);\n    }\n\n    BOOST_CHECK_EQUAL(lp.rows_number(), 4);\n    std::unordered_map<lp::row_id, std::string> rows(\n        { { row1, \"row1\" }, { row2, \"row2\" }, { row3, \"row3\" },\n          { row4, \"row4\" } });\n    for (auto row : lp.get_rows()) {\n        BOOST_CHECK(rows.find(row) != rows.end());\n        BOOST_CHECK_EQUAL(lp.get_row_name(row), rows.find(row)->second);\n        BOOST_CHECK_EQUAL(lp.get_row_degree(row), 2);\n        BOOST_CHECK_EQUAL(lp.get_row_expression(row).non_zeros(), 2);\n    }\n\n    // delete some rows and colums\n    lp.delete_row(row2);\n    BOOST_CHECK_EQUAL(lp.rows_number(), 3);\n\n    lp.delete_col(X);\n    BOOST_CHECK_EQUAL(lp.columns_number(), 1);\n\n    lp.delete_row(row3);\n    BOOST_CHECK_EQUAL(lp.rows_number(), 2);\n\n    columns = std::unordered_map<lp::col_id, std::string>({ { Y, \"y\" } });\n    for (auto col : lp.get_columns()) {\n        BOOST_CHECK(columns.find(col) != columns.end());\n        BOOST_CHECK_EQUAL(lp.get_col_name(col), columns.find(col)->second);\n        BOOST_CHECK_EQUAL(lp.get_col_degree(col), 2);\n        BOOST_CHECK_EQUAL(boost::distance(lp.get_rows_in_column(col)), 2);\n    }\n\n    rows = std::unordered_map<lp::row_id, std::string>(\n        { { row1, \"row1\" }, { row4, \"row4\" } });\n    for (auto row : lp.get_rows()) {\n        BOOST_CHECK(rows.find(row) != rows.end());\n        BOOST_CHECK_EQUAL(lp.get_row_name(row), rows.find(row)->second);\n        BOOST_CHECK_EQUAL(lp.get_row_degree(row), 1);\n        BOOST_CHECK_EQUAL(lp.get_row_expression(row).non_zeros(), 1);\n    }\n\n    // set new bounds and costs\n    lp.set_row_lower_bound(row1, 7);\n    lp.set_row_upper_bound(row1, 10);\n    lp.set_row_lower_bound(row4, lp::lp_traits::MINUS_INF);\n    lp.set_row_upper_bound(row4, 12);\n\n    lp.set_col_lower_bound(Y, 0);\n    lp.set_col_upper_bound(Y, lp::lp_traits::PLUS_INF);\n    lp.set_col_cost(Y, 30);\n\n    // add new column\n    auto Z = lp.add_column(50, 0, lp::lp_traits::PLUS_INF, \"z\");\n\n    // set row linear expressions\n    lp.set_row_expression(row1, Y + Z);\n    lp.set_row_expression(row4, 2 * Z + Y);\n\n    // solve\n    auto status = lp.solve_simplex(lp::PRIMAL);\n    BOOST_CHECK_EQUAL(status, lp::OPTIMAL);\n    BOOST_CHECK_SMALL(lp.get_obj_value() - 340,\n                      std::numeric_limits<double>::epsilon());\n    BOOST_CHECK_SMALL(lp.get_row_sum(row1) - 10,\n                      std::numeric_limits<double>::epsilon());\n    BOOST_CHECK_SMALL(lp.get_row_sum(row4) - 12,\n                      std::numeric_limits<double>::epsilon());\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(linear_programming_zeros, LP, lp_types) {\n    LP lp(\"test instance\", lp::MAXIMIZE);\n    auto X = lp.add_column();\n    auto Y = lp.add_column();\n    auto Z = lp.add_column();\n    auto expr = 1e-8 * X + Y;\n    BOOST_CHECK_EQUAL(expr.non_zeros(), 2);\n    expr += 0 * Z;\n    BOOST_CHECK_EQUAL(expr.non_zeros(), 2);\n    expr *= 1e-8;\n    BOOST_CHECK_EQUAL(expr.non_zeros(), 1);\n\n    expr = (1e-8 * X + Y) / 1e8;\n    BOOST_CHECK_EQUAL(expr.non_zeros(), 1);\n\n    expr = X + Y - Y;\n    BOOST_CHECK_EQUAL(expr.non_zeros(), 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "8746a65cc2fca3cc1fb349af5ca696b9c5823034", "size": 11366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/linear_programming/lp/linear_programming_test.cpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/linear_programming/lp/linear_programming_test.cpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/linear_programming/lp/linear_programming_test.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 36.0825396825, "max_line_length": 80, "alphanum_fraction": 0.6032025339, "num_tokens": 3141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.584396571142109}}
{"text": "#include \"Plane.h\"\n#include \"Ray.h\"\n#include \"Intersection.h\"\n\n#include <Eigen/Dense>\n\nstd::unique_ptr<Intersection> Plane::intersect(const Ray& ray) {\n    auto p = ray.p;\n    auto d = ray.d;\n\n    if (n.dot(d) > 0.0f) {\n        return nullptr;\n    } else {\n        auto a = this->p;\n        float t = (a-p).dot(n) / d.dot(n);\n        return std::unique_ptr<Intersection>(new Intersection(this, n, t));\n    }\n}\n", "meta": {"hexsha": "bbf6d9feaf80b3cfbe034b17cc8219f63daa7bd7", "size": 410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Plane.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/Plane.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/Plane.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": 21.5789473684, "max_line_length": 75, "alphanum_fraction": 0.5731707317, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5843965656724871}}
{"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// \ufffd\ufffd\ufffd\u0734\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\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": "/* Copyright (c) 2016, the Cap authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#define BOOST_TEST_MODULE ResistorCapacitorCircuit\n\n#include \"main.cc\"\n\n#include <cap/resistor_capacitor.h>\n#include <boost/test/unit_test.hpp>\n#include <boost/foreach.hpp>\n#include <boost/format.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <string>\n#include <tuple>\n#include <cmath>\n#include <iostream>\n\n// This file contains the following tests:\n//  - Series RC constant voltage\n//  - Series RC constant current\n//  - Series RC constant power\n//  - Series RC constant load\n//  - Parallel RC constant current\n//  - Parallel RC constant voltage\n//  - Parallel RC constant power\n//  - Parallel RC constant load\n\ndouble const R_SERIES = 55.0e-3;\ndouble const R_PARALLEL = 2.5e6;\ndouble const C = 3.0;\ndouble const TOLERANCE = 1.0e-8; // in percentage units\ndouble const I = 0.006;\ndouble const U = 2.1;\ndouble const P = 0.0017;\n\nboost::property_tree::ptree initialize_database()\n{\n  boost::property_tree::ptree database;\n  database.put(\"series_resistance\", R_SERIES);\n  database.put(\"parallel_resistance\", R_PARALLEL);\n  database.put(\"capacitance\", C);\n  return database;\n}\n\nvoid set_voltage(cap::SeriesRC &rc, double voltage)\n{\n  rc.U_C = voltage;\n  rc.U = rc.U_C;\n  rc.I = 0.0;\n}\n\nvoid set_current(cap::SeriesRC &rc, double current)\n{\n  rc.I = current;\n  rc.U = rc.U_C + rc.R * rc.I;\n}\n\nvoid set_voltage(cap::ParallelRC &rc, double voltage)\n{\n  rc.U = voltage;\n  rc.U_C = rc.R_parallel / (rc.R_series + rc.R_parallel) * rc.U;\n  rc.I = rc.U / (rc.R_series + rc.R_parallel);\n}\n\nvoid set_current(cap::ParallelRC &rc, double current)\n{\n  rc.I = current;\n  rc.U = rc.R_series * rc.I + rc.U_C;\n}\n\nBOOST_AUTO_TEST_CASE(test_series_rc_constant_voltage)\n{\n  double const TAU = R_SERIES * C;\n  double const DELTA_T = 0.1 * TAU;\n  std::vector<double> time;\n  for (double t = 0.0; t <= 5.0 * TAU; t += DELTA_T)\n    time.push_back(t);\n\n  cap::SeriesRC rc(initialize_database(), boost::mpi::communicator());\n\n  // CHARGE\n  BOOST_FOREACH (double const &t, time)\n  {\n    BOOST_CHECK_CLOSE(rc.U_C, U * (1.0 - std::exp(-t / TAU)), TOLERANCE);\n    rc.evolve_one_time_step_constant_voltage(DELTA_T, U);\n  }\n\n  // DISCHARGE\n  set_voltage(rc, U);\n  BOOST_FOREACH (double const &t, time)\n  {\n    BOOST_CHECK_CLOSE(rc.U_C, U * std::exp(-t / TAU), TOLERANCE);\n    rc.evolve_one_time_step_constant_voltage(DELTA_T, 0.0);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_series_rc_constant_current)\n{\n  double const TAU = R_SERIES * C;\n  double const DELTA_T = 0.1 * TAU;\n\n  std::vector<double> time;\n  for (double t = 0.0; t <= 5.0 * TAU; t += DELTA_T)\n    time.push_back(t);\n\n  cap::SeriesRC rc(initialize_database(), boost::mpi::communicator());\n\n  // CHARGE\n  set_voltage(rc, 0.0);\n  set_current(rc, I);\n  BOOST_FOREACH (double const &t, time)\n  {\n    BOOST_CHECK_CLOSE(rc.U, I * (R_SERIES + t / C), TOLERANCE);\n    rc.evolve_one_time_step_constant_current(DELTA_T, I);\n  }\n\n  // DISCHARGE\n  set_voltage(rc, U);\n  set_current(rc, -I);\n  BOOST_FOREACH (double const &t, time)\n  {\n    BOOST_CHECK_CLOSE(rc.U, U - I * (R_SERIES + t / C), TOLERANCE);\n    rc.evolve_one_time_step_constant_current(DELTA_T, -I);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_series_rc_constant_power)\n{\n  double const TAU = R_SERIES * C;\n  double const DELTA_T = 0.1 * TAU;\n\n  std::vector<double> time;\n  for (double t = 0.0; t <= 5.0 * TAU; t += DELTA_T)\n    time.push_back(t);\n\n  cap::SeriesRC rc_newton(initialize_database(), boost::mpi::communicator());\n  cap::SeriesRC rc_fixed_point(initialize_database(),\n                               boost::mpi::communicator());\n\n  // CHARGE\n  set_current(rc_newton, 0.0);\n  set_voltage(rc_newton, U);\n  set_current(rc_fixed_point, 0.0);\n  set_voltage(rc_fixed_point, U);\n\n  BOOST_FOREACH (double const &t, time)\n  {\n    std::ignore = t;\n    BOOST_CHECK_CLOSE(rc_newton.U, rc_fixed_point.U, TOLERANCE);\n    BOOST_CHECK_CLOSE(rc_newton.I, rc_fixed_point.I, TOLERANCE);\n    BOOST_CHECK_CLOSE(rc_newton.U_C, rc_fixed_point.U_C, TOLERANCE);\n    rc_newton.evolve_one_time_step_constant_power(DELTA_T, P, \"NEWTON\");\n    rc_fixed_point.evolve_one_time_step_constant_power(DELTA_T, P,\n                                                       \"FIXED_POINT\");\n  }\n\n  BOOST_CHECK_THROW(rc_newton.evolve_one_time_step_constant_power(\n                        DELTA_T, P, \"INVALID_ROOT_FINDING_METHOD\"),\n                    std::runtime_error);\n\n  // DISCHARGE\n  set_current(rc_newton, 0.0);\n  set_voltage(rc_newton, U);\n  set_current(rc_fixed_point, 0.0);\n  set_voltage(rc_fixed_point, U);\n  BOOST_FOREACH (double const &t, time)\n  {\n    std::ignore = t;\n    BOOST_CHECK_CLOSE(rc_newton.U, rc_fixed_point.U, TOLERANCE);\n    BOOST_CHECK_CLOSE(rc_newton.I, rc_fixed_point.I, TOLERANCE);\n    BOOST_CHECK_CLOSE(rc_newton.U_C, rc_fixed_point.U_C, TOLERANCE);\n    rc_newton.evolve_one_time_step_constant_power(DELTA_T, -P, \"NEWTON\");\n    rc_fixed_point.evolve_one_time_step_constant_power(DELTA_T, -P,\n                                                       \"FIXED_POINT\");\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_series_rc_constant_load)\n{\n  double const TAU = R_SERIES * C;\n  double const DELTA_T = 0.1 * TAU;\n  double const R_LOAD = 5.0 * R_SERIES;\n\n  std::vector<double> time;\n  for (double t = 0.0; t <= 5.0 * TAU; t += DELTA_T)\n    time.push_back(t);\n\n  cap::SeriesRC rc(initialize_database(), boost::mpi::communicator());\n\n  // DISCHARGE\n  set_voltage(rc, U);\n  BOOST_FOREACH (double const &t, time)\n  {\n    BOOST_CHECK_CLOSE(\n        rc.U, U * std::exp(-t / ((R_SERIES + R_LOAD) * C)) *\n                  (1.0 - ((t > 0.0) ? R_SERIES / (R_SERIES + R_LOAD) : 0.0)),\n        TOLERANCE);\n    rc.evolve_one_time_step_constant_load(DELTA_T, R_LOAD);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_parallel_rc_constant_current)\n{\n  double const TAU = R_PARALLEL * C;\n  double const DELTA_T = 0.1 * TAU;\n  std::vector<double> time;\n  for (double t = 0.0; t <= 5.0 * TAU; t += 0.1 * TAU)\n    time.push_back(t);\n\n  cap::ParallelRC rc(initialize_database(), boost::mpi::communicator());\n  rc.R_series = 0.0;\n\n  // CHARGE\n  set_voltage(rc, 0.0);\n  set_current(rc, I);\n  BOOST_FOREACH (double const &t, time)\n  {\n    BOOST_CHECK_CLOSE(rc.U_C,\n                      R_PARALLEL * I * (1.0 - std::exp(-t / (R_PARALLEL * C))),\n                      TOLERANCE);\n    rc.evolve_one_time_step_constant_current(DELTA_T, I);\n  }\n\n  // RELAXATION\n  set_voltage(rc, U);\n  set_current(rc, 0.0);\n  BOOST_FOREACH (double const &t, time)\n  {\n    BOOST_CHECK_CLOSE(rc.U_C, U * std::exp(-t / (R_PARALLEL * C)), TOLERANCE);\n    rc.evolve_one_time_step_constant_current(DELTA_T, 0.0);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_parallel_rc_constant_voltage)\n{\n  double const TAU = R_SERIES * C;\n  double const DELTA_T = 0.1 * TAU;\n\n  std::vector<double> time;\n  for (double t = 0.0; t <= 5.0 * TAU; t += DELTA_T)\n    time.push_back(t);\n\n  cap::ParallelRC rc(initialize_database(), boost::mpi::communicator());\n\n  // CHARGE\n  set_voltage(rc, 0.0);\n  BOOST_FOREACH (double const &t, time)\n  {\n    BOOST_CHECK_CLOSE(rc.U_C,\n                      U * R_PARALLEL / (R_SERIES + R_PARALLEL) *\n                          (1.0 - std::exp(-t / ((R_SERIES * R_PARALLEL) /\n                                                (R_SERIES + R_PARALLEL) * C))),\n                      TOLERANCE);\n    rc.evolve_one_time_step_constant_voltage(DELTA_T, U);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_parallel_rc_constant_power)\n{\n  double const TAU = R_SERIES * C;\n  double const DELTA_T = 0.1 * TAU;\n\n  std::vector<double> time;\n  for (double t = 0.0; t <= 5.0 * TAU; t += DELTA_T)\n    time.push_back(t);\n\n  cap::SeriesRC rc_newton(initialize_database(), boost::mpi::communicator());\n  cap::SeriesRC rc_fixed_point(initialize_database(),\n                               boost::mpi::communicator());\n\n  // CHARGE\n  set_current(rc_newton, 0.0);\n  set_voltage(rc_newton, U);\n  set_current(rc_fixed_point, 0.0);\n  set_voltage(rc_fixed_point, U);\n\n  BOOST_FOREACH (double const &t, time)\n  {\n    std::ignore = t;\n    BOOST_CHECK_CLOSE(rc_newton.U, rc_fixed_point.U, TOLERANCE);\n    BOOST_CHECK_CLOSE(rc_newton.I, rc_fixed_point.I, TOLERANCE);\n    BOOST_CHECK_CLOSE(rc_newton.U_C, rc_fixed_point.U_C, TOLERANCE);\n    rc_newton.evolve_one_time_step_constant_power(DELTA_T, P, \"NEWTON\");\n    rc_fixed_point.evolve_one_time_step_constant_power(DELTA_T, P,\n                                                       \"FIXED_POINT\");\n  }\n\n  BOOST_CHECK_THROW(rc_newton.evolve_one_time_step_constant_power(\n                        DELTA_T, P, \"INVALID_ROOT_FINDING_METHOD\"),\n                    std::runtime_error);\n\n  // DISCHARGE\n  set_current(rc_newton, 0.0);\n  set_voltage(rc_newton, U);\n  set_current(rc_fixed_point, 0.0);\n  set_voltage(rc_fixed_point, U);\n\n  BOOST_FOREACH (double const &t, time)\n  {\n    std::ignore = t;\n    BOOST_CHECK_CLOSE(rc_newton.U, rc_fixed_point.U, TOLERANCE);\n    BOOST_CHECK_CLOSE(rc_newton.I, rc_fixed_point.I, TOLERANCE);\n    BOOST_CHECK_CLOSE(rc_newton.U_C, rc_fixed_point.U_C, TOLERANCE);\n    rc_newton.evolve_one_time_step_constant_power(DELTA_T, -P, \"NEWTON\");\n    rc_fixed_point.evolve_one_time_step_constant_power(DELTA_T, -P,\n                                                       \"FIXED_POINT\");\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_parallel_rc_constant_load)\n{\n  double const TAU = R_PARALLEL * C;\n  double const DELTA_T = 0.1 * TAU;\n  double const R_LOAD = 5.0 * R_SERIES;\n  std::vector<double> time;\n  for (double t = 0.0; t <= 5.0 * TAU; t += 0.1 * TAU)\n    time.push_back(t);\n\n  cap::ParallelRC rc(initialize_database(), boost::mpi::communicator());\n  rc.R_series = 0.0;\n\n  // DISCHARGE\n  set_voltage(rc, U);\n  BOOST_FOREACH (double const &t, time)\n  {\n    BOOST_CHECK_CLOSE(\n        rc.U,\n        U * std::exp(-t * (1.0 + (R_SERIES + R_LOAD) / R_PARALLEL) /\n                     ((R_SERIES + R_LOAD) * C)) *\n            (1.0 - ((t > 0.0)\n                        ? R_SERIES * (1.0 + (R_SERIES + R_LOAD) / R_PARALLEL) /\n                              (R_SERIES + R_LOAD)\n                        : 0.0)),\n        TOLERANCE);\n    rc.evolve_one_time_step_constant_load(DELTA_T, R_LOAD);\n  }\n}\n", "meta": {"hexsha": "7dae06a09082debc2ff8eed2a473979954f59f82", "size": 10245, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/test/test_resistor_capacitor_circuit.cc", "max_stars_repo_name": "iiscsahoo/EnergyData", "max_stars_repo_head_hexsha": "6230145b5df6b126eab11aea58a5cfaa11ad5ba1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2016-05-15T11:42:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T19:33:04.000Z", "max_issues_repo_path": "cpp/test/test_resistor_capacitor_circuit.cc", "max_issues_repo_name": "iiscsahoo/EnergyData", "max_issues_repo_head_hexsha": "6230145b5df6b126eab11aea58a5cfaa11ad5ba1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 198.0, "max_issues_repo_issues_event_min_datetime": "2016-01-27T16:46:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-11T06:31:37.000Z", "max_forks_repo_path": "cpp/test/test_resistor_capacitor_circuit.cc", "max_forks_repo_name": "iiscsahoo/EnergyData", "max_forks_repo_head_hexsha": "6230145b5df6b126eab11aea58a5cfaa11ad5ba1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-01-27T15:17:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T02:06:50.000Z", "avg_line_length": 29.9561403509, "max_line_length": 79, "alphanum_fraction": 0.6507564666, "num_tokens": 2993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5842155632626831}}
{"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": "#include \"muan/control/pose.h\"\n#include <Eigen/Geometry>\n\nnamespace muan {\nnamespace control {\n\nEigen::Vector2d Projection(Eigen::Vector2d a, Eigen::Vector2d direction) {\n  return a.dot(direction) * direction.dot(direction) * direction;\n}\n\nEigen::Vector2d FromMagDirection(double magnitude, double direction) {\n  return magnitude *\n         (Eigen::Vector2d() << ::std::cos(direction), ::std::sin(direction))\n             .finished();\n}\n\nPose::Pose(Eigen::Vector3d values) : values_(values) {}\n\nPose::Pose(Eigen::Vector2d pos, double theta) {\n  values_.block<2, 1>(0, 0) = pos;\n  values_(2) = remainder(theta, 2 * M_PI);\n}\n\nPose Pose::operator+(const Pose &other) const {\n  Eigen::Vector3d new_values = values_ + other.values_;\n\n  // Wrap the heading into [-pi, pi]\n  new_values(2) = remainder(new_values(2), 2 * M_PI);\n\n  return Pose(new_values);\n}\n\nPose Pose::TranslateBy(const Eigen::Vector2d &delta) const {\n  Eigen::Vector3d new_values = values_;\n  new_values.block<2, 1>(0, 0) += delta;\n  return Pose(new_values);\n}\n\nPose Pose::RotateBy(double theta) const {\n  Eigen::Vector3d new_values = values_;\n  new_values.block<2, 1>(0, 0) =\n      Eigen::Rotation2D<double>(theta) * new_values.block<2, 1>(0, 0);\n\n  // Wrap the heading into [-pi, pi]\n  new_values(2) = remainder(new_values(2) + theta, 2 * M_PI);\n\n  return Pose(new_values);\n}\n\nPose Pose::operator-(const Pose &other) const {\n  Eigen::Vector3d new_values = values_ - other.values_;\n\n  // Wrap the heading into [-pi, pi]\n  new_values(2) = remainder(new_values(2), 2 * M_PI);\n  return Pose(new_values);\n}\n\nPose Pose::Compose(const Pose &other) const {\n  return other.RotateBy(heading()).TranslateBy(translational());\n}\n\nPose Pose::Interpolate(Pose other, double frac) const {\n  if (frac <= 0) {\n    return Pose(Get());\n  } else if (frac >= 1) {\n    return Pose(other.Get());\n  }\n  Pose delta = Pose((other.translational() - translational()) * frac,\n                    remainder((other.heading() - heading()) * frac, 2 * M_PI));\n  Pose result = Compose(delta);\n\n  return result;\n}\n\nPoseWithCurvature::PoseWithCurvature(Pose pose, double curvature)\n    : pose_(pose), curvature_(curvature) {}\n\nPoseWithCurvature PoseWithCurvature::operator+(\n    const PoseWithCurvature &other) const {\n  return PoseWithCurvature(pose_ + other.pose_, curvature_);\n}\n\nPoseWithCurvature PoseWithCurvature::operator-(\n    const PoseWithCurvature &other) const {\n  return PoseWithCurvature(pose_ - other.pose_, curvature_);\n}\n\nPoseWithCurvature PoseWithCurvature::TranslateBy(\n    const Eigen::Vector2d &delta) const {\n  Eigen::Vector2d new_values = pose_.translational() + delta;\n  return PoseWithCurvature(Pose(new_values, pose_.heading()), curvature_);\n}\n\nPoseWithCurvature PoseWithCurvature::Interpolate(PoseWithCurvature other,\n                                                 double frac) const {\n  return PoseWithCurvature(\n      pose_.Interpolate(other.pose(), frac),\n      curvature_ + ((other.curvature() - curvature_) * frac));\n}\n\n}  // namespace control\n}  // namespace muan\n", "meta": {"hexsha": "26de51ffd1edd9d41e5dc4341247aae0ee826902", "size": 3025, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "muan/control/pose.cpp", "max_stars_repo_name": "hansonl02/frc-robot-code", "max_stars_repo_head_hexsha": "4b120c917a7709df9f010c9089a87c320bab3a16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2017-01-22T04:38:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T00:04:37.000Z", "max_issues_repo_path": "muan/control/pose.cpp", "max_issues_repo_name": "hansonl02/frc-robot-code", "max_issues_repo_head_hexsha": "4b120c917a7709df9f010c9089a87c320bab3a16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-06-28T05:34:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-16T15:46:22.000Z", "max_forks_repo_path": "muan/control/pose.cpp", "max_forks_repo_name": "hansonl02/frc-robot-code", "max_forks_repo_head_hexsha": "4b120c917a7709df9f010c9089a87c320bab3a16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-05-12T15:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T12:49:38.000Z", "avg_line_length": 29.3689320388, "max_line_length": 79, "alphanum_fraction": 0.6839669421, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5841815240321466}}
{"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": "#include <boost/graph/adjacency_list.hpp>\nusing namespace boost;\n\ntypedef property<edge_weight_t, int> EdgeWeightProperty;\ntypedef boost::adjacency_list < listS, vecS, undirectedS, no_property, EdgeWeightProperty> mygraph;\n\nint main()\n{\nmygraph g;\nadd_edge (0, 1, 8, g);\nadd_edge (0, 3, 18, g);\nadd_edge (1, 2, 20, g);\nadd_edge (2, 3, 2, g);\nadd_edge (3, 1, 1, g);\nadd_edge (1, 3, 7, g);\n}\n", "meta": {"hexsha": "d2253959086517ffffc92c403da785005a543daf", "size": 390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "6Creating_a_weighted_directed_graph.cpp", "max_stars_repo_name": "mohsenuss91/BGL_workshop", "max_stars_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T18:40:32.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-12T18:40:32.000Z", "max_issues_repo_path": "6Creating_a_weighted_directed_graph.cpp", "max_issues_repo_name": "mohsenuss91/IBM_BGL", "max_issues_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6Creating_a_weighted_directed_graph.cpp", "max_forks_repo_name": "mohsenuss91/IBM_BGL", "max_forks_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9411764706, "max_line_length": 99, "alphanum_fraction": 0.7, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5841397850350192}}
{"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": "#pragma once\r\n\r\n#include <Eigen/Core>\r\n\r\nnamespace Discregrid\r\n{\r\n\r\nclass BoundingSphere\r\n{\r\n\r\npublic:\r\n\r\n\tBoundingSphere() : m_x(Eigen::Vector3d::Zero()), m_r(0.0) {}\r\n\tBoundingSphere(Eigen::Vector3d const& x, double r) : m_x(x), m_r(r) {}\r\n\r\n\tEigen::Vector3d const& x() const { return m_x; }\r\n\tEigen::Vector3d& x() { return m_x; }\r\n\r\n\tdouble r() const { return m_r; }\r\n\tdouble& r() { return m_r; }\r\n\r\n\tbool overlaps(BoundingSphere const& other) const \r\n\t{ \r\n\t\tdouble 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\tbool contains(BoundingSphere const& other) const\r\n\t{\r\n\t\tdouble rr = r() - other.r();\r\n\t\treturn (x() - other.x()).squaredNorm() < rr * rr;\r\n\t}\r\n\r\n\tbool contains(Eigen::Vector3d 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\tEigen::Vector3d m_x;\r\n\tdouble m_r;\r\n};\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "d43594bd1bd4c380a852142ad2d011b8644c64cd", "size": 871, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "discregrid/include/Discregrid/acceleration/bounding_sphere.hpp", "max_stars_repo_name": "Borges3D/Discregrid", "max_stars_repo_head_hexsha": "f16a29afebf7a7f43139d5832bbfc7124c5d98db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "discregrid/include/Discregrid/acceleration/bounding_sphere.hpp", "max_issues_repo_name": "Borges3D/Discregrid", "max_issues_repo_head_hexsha": "f16a29afebf7a7f43139d5832bbfc7124c5d98db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "discregrid/include/Discregrid/acceleration/bounding_sphere.hpp", "max_forks_repo_name": "Borges3D/Discregrid", "max_forks_repo_head_hexsha": "f16a29afebf7a7f43139d5832bbfc7124c5d98db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:58:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T13:58:55.000Z", "avg_line_length": 18.5319148936, "max_line_length": 72, "alphanum_fraction": 0.6050516648, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5841218965021922}}
{"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/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/function/erf_inv.hpp>\n#include <boost/math/special_functions/erf.hpp>\n#include <eve/function/is_negative.hpp>\n#include <eve/function/is_positive.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/platform.hpp>\n#include <cmath>\n\nTTS_CASE_TPL(\"Check eve::erf_inv return type\", EVE_TYPE)\n{\n  TTS_EXPR_IS(eve::erf_inv(T(0)), T);\n}\n\nTTS_CASE_TPL(\"Check eve::erf_inv behavior\", EVE_TYPE)\n{\n  auto eve__erf_inv =  [](auto x) { return eve::erf_inv(x); };\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_IEEE_EQUAL(eve__erf_inv(eve::nan(eve::as<T>()))  , eve::nan(eve::as<T>()) );\n    TTS_IEEE_EQUAL(eve__erf_inv(eve::inf(eve::as<T>()))  , eve::nan(eve::as<T>()) );\n    TTS_IEEE_EQUAL(eve__erf_inv(eve::minf(eve::as<T>())) , eve::nan(eve::as<T>()) );\n  }\n\n  TTS_ULP_EQUAL(eve__erf_inv(T(35)), eve::nan(eve::as<T>()), 0.5);\n  TTS_ULP_EQUAL(eve__erf_inv(T(-35)), eve::nan(eve::as<T>()), 0.5);\n\n  TTS_IEEE_EQUAL(eve__erf_inv(T( 0 )),T(0)  );\n  TTS_IEEE_EQUAL(eve__erf_inv(T(-0.)), T(0) );\n  TTS_ULP_EQUAL(eve__erf_inv(T( 0.1 )), T( boost::math::erf_inv(0.1)), 0.5 );\n  TTS_ULP_EQUAL(eve__erf_inv(T( 0.2 )), T( boost::math::erf_inv(0.2)), 0.5 );\n  TTS_ULP_EQUAL(eve__erf_inv(T( 0.3 )), T( boost::math::erf_inv(0.3)), 0.5 );\n  TTS_ULP_EQUAL(eve__erf_inv(T( 0.5 )), T( boost::math::erf_inv(0.5)),  1 );\n  TTS_ULP_EQUAL(eve__erf_inv(T( 0.15)), T( boost::math::erf_inv(0.15)), 0.5 );\n  TTS_ULP_EQUAL(eve__erf_inv(T( 0.75)), T( boost::math::erf_inv(0.75)), 0.5 );\n  TTS_ULP_EQUAL(eve__erf_inv(T(- 0.1 )), T( boost::math::erf_inv(-0.1)), 0.5 );\n  TTS_ULP_EQUAL(eve__erf_inv(T( -0.2 )), T( boost::math::erf_inv(-0.2)), 0.5 );\n  TTS_ULP_EQUAL(eve__erf_inv(T( -0.3 )), T( boost::math::erf_inv(-0.3)), 0.5 );\n  TTS_ULP_EQUAL(eve__erf_inv(T( -0.5 )), T( boost::math::erf_inv(-0.5)),  1 );\n  TTS_ULP_EQUAL(eve__erf_inv(T( -0.15)), T( boost::math::erf_inv(-0.15)), 0.5 );\n  TTS_ULP_EQUAL(eve__erf_inv(T( -0.75)), T( boost::math::erf_inv(-0.75)), 0.5 );\n}\n", "meta": {"hexsha": "e1997209c63d7ae8ef19c6ec0b4f7f74a2ba0027", "size": 2343, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/special/erf_inv/regular/erf_inv.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/special/erf_inv/regular/erf_inv.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/special/erf_inv/regular/erf_inv.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0576923077, "max_line_length": 100, "alphanum_fraction": 0.5970977379, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5841218948856718}}
{"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": "#include <gtest/gtest.h>\n\n#include \"manif/Bundle.h\"\n#include \"manif/Rn.h\"\n#include \"manif/SO2.h\"\n#include \"manif/SO3.h\"\n#include \"manif/SE2.h\"\n#include \"manif/SE3.h\"\n\n#include \"../common_tester.h\"\n\n#include <Eigen/StdVector>\n\n#include <array>\n\nusing namespace manif;\n\nusing GroupA = Bundle<double, R2, SO3, R1>;\n\n\nTEST(Bundle, StaticSizes)\n{\n  static_assert(GroupA::BundleSize == 3, \"Size error\");\n  static_assert(GroupA::Dim == 6, \"Dimension error\");\n  static_assert(GroupA::DoF == 6, \"Dimension error\");\n  static_assert(GroupA::RepSize == 7, \"Dimension error\");\n\n  static_assert(GroupA::DoF == R2d::DoF + SO3d::DoF + R1d::DoF, \"Dimension error\");\n  static_assert(GroupA::RepSize == R2d::RepSize + SO3d::RepSize + R1d::RepSize, \"Dimension error\");\n  static_assert(GroupA::Dim == R2d::Dim + SO3d::Dim + R1d::Dim, \"Dimension error\");\n\n  static_assert(\n    GroupA::Vector::RowsAtCompileTime ==\n    R2d::Vector::RowsAtCompileTime + SO3d::Vector::RowsAtCompileTime +\n    R1d::Vector::RowsAtCompileTime, \"Dimension error\");\n\n  static_assert(\n    GroupA::Transformation::RowsAtCompileTime ==\n    R2d::Transformation::RowsAtCompileTime + SO3d::Transformation::RowsAtCompileTime +\n    R1d::Transformation::RowsAtCompileTime, \"Dimension error\");\n\n  static_assert(\n    GroupA::Transformation::ColsAtCompileTime ==\n    R2d::Transformation::ColsAtCompileTime + SO3d::Transformation::ColsAtCompileTime +\n    R1d::Transformation::ColsAtCompileTime, \"Dimension error\");\n\n  static_assert(\n    GroupA::Tangent::Dim == R2d::Tangent::Dim + SO3d::Tangent::Dim + R1d::Tangent::Dim,\n    \"Dimension error\");\n  static_assert(\n    GroupA::Tangent::DoF == R2d::Tangent::DoF + SO3d::Tangent::DoF + R1d::Tangent::DoF,\n    \"Dimension error\");\n  static_assert(\n    GroupA::Tangent::RepSize ==\n    R2d::Tangent::RepSize + SO3d::Tangent::RepSize + R1d::Tangent::RepSize, \"Dimension error\");\n\n  static_assert(\n    GroupA::Tangent::LieAlg::RowsAtCompileTime ==\n    R2d::Tangent::LieAlg::RowsAtCompileTime + SO3d::Tangent::LieAlg::RowsAtCompileTime +\n    R1d::Tangent::LieAlg::RowsAtCompileTime, \"Dimension error\");\n\n  static_assert(\n    GroupA::Tangent::LieAlg::ColsAtCompileTime ==\n    R2d::Tangent::LieAlg::ColsAtCompileTime + SO3d::Tangent::LieAlg::ColsAtCompileTime +\n    R1d::Tangent::LieAlg::ColsAtCompileTime, \"Dimension error\");\n\n  static_assert(\n    GroupA::Jacobian::RowsAtCompileTime ==\n    R2d::Jacobian::RowsAtCompileTime + SO3d::Jacobian::RowsAtCompileTime +\n    R1d::Jacobian::RowsAtCompileTime, \"Dimension error\");\n\n  static_assert(\n    GroupA::Jacobian::ColsAtCompileTime ==\n    R2d::Jacobian::ColsAtCompileTime + SO3d::Jacobian::ColsAtCompileTime +\n    R1d::Jacobian::ColsAtCompileTime, \"Dimension error\");\n\n  static_assert(\n    GroupA::Tangent::Jacobian::RowsAtCompileTime ==\n    R2d::Tangent::Jacobian::RowsAtCompileTime + SO3d::Tangent::Jacobian::RowsAtCompileTime +\n    R1d::Tangent::Jacobian::RowsAtCompileTime, \"Dimension error\");\n\n  static_assert(\n    GroupA::Tangent::Jacobian::ColsAtCompileTime ==\n    R2d::Tangent::Jacobian::ColsAtCompileTime + SO3d::Tangent::Jacobian::ColsAtCompileTime +\n    R1d::Tangent::Jacobian::ColsAtCompileTime, \"Dimension error\");\n}\n\n\nTEST(Bundle, Interface)\n{\n  GroupA G = GroupA::Random();\n\n  auto Glog = G.log();\n  EXPECT_EIGEN_NEAR(Glog.element<0>().coeffs(), G.element<0>().log().coeffs());\n  EXPECT_EIGEN_NEAR(Glog.element<1>().coeffs(), G.element<1>().log().coeffs());\n  EXPECT_EIGEN_NEAR(Glog.element<2>().coeffs(), G.element<2>().log().coeffs());\n\n  auto Ginv = G.inverse();\n  EXPECT_EIGEN_NEAR(G.element<0>().inverse().coeffs(), Ginv.element<0>().coeffs());\n  EXPECT_EIGEN_NEAR(G.element<1>().inverse().coeffs(), Ginv.element<1>().coeffs());\n  EXPECT_EIGEN_NEAR(G.element<2>().inverse().coeffs(), Ginv.element<2>().coeffs());\n\n  auto G_Ginv = G.compose(Ginv);\n  EXPECT_EIGEN_NEAR(G_Ginv.element<0>().inverse().coeffs(), R2d::Identity().coeffs());\n  EXPECT_EIGEN_NEAR(G_Ginv.element<1>().inverse().coeffs(), SO3d::Identity().coeffs());\n  EXPECT_EIGEN_NEAR(G_Ginv.element<2>().inverse().coeffs(), R1d::Identity().coeffs());\n\n  typename GroupA::Vector vec;\n\n  auto adj = G.adj();\n  Eigen::Matrix2d adj0 = adj.block<2, 2>(0, 0);\n  EXPECT_EIGEN_NEAR(adj0, G.element<0>().adj());\n  Eigen::Matrix3d adj1 = adj.block<3, 3>(2, 2);\n  EXPECT_EIGEN_NEAR(adj1, G.element<1>().adj());\n  Eigen::Matrix<double, 1, 1> adj2 = adj.block<1, 1>(5, 5);\n  EXPECT_EIGEN_NEAR(adj2, G.element<2>().adj());\n}\n\n\nTEST(Bundle, Map)\n{\n  std::array<double, GroupA::RepSize> data;\n\n  Eigen::Map<GroupA> map(data.data());\n  map = GroupA::Random();\n\n  GroupA::DataType datatype = Eigen::Map<GroupA::DataType>(data.data());\n  GroupA copy(datatype);\n\n  auto diff = (map.inverse() * copy).log().coeffs();\n\n  EXPECT_EIGEN_NEAR(diff, GroupA::Tangent::DataType::Zero());\n}\n\n\nTEST(BundleTangent, Interface)\n{\n  typename GroupA::Tangent tangent = GroupA::Tangent::Random();\n  auto exp = tangent.exp();\n\n  EXPECT_EIGEN_NEAR(exp.element<0>().coeffs(), tangent.element<0>().exp().coeffs());\n  EXPECT_EIGEN_NEAR(exp.element<1>().coeffs(), tangent.element<1>().exp().coeffs());\n  EXPECT_EIGEN_NEAR(exp.element<2>().coeffs(), tangent.element<2>().exp().coeffs());\n}\n\n\nTEST(BundleTangent, Jacobians)\n{\n  auto tangent = GroupA::Random().log();\n\n  {\n    auto jac = tangent.rjac();\n    Eigen::Matrix2d jac0 = jac.block<2, 2>(0, 0);\n    Eigen::Matrix3d jac1 = jac.block<3, 3>(2, 2);\n    Eigen::Matrix<double, 1, 1> jac2 = jac.block<1, 1>(5, 5);\n\n    EXPECT_EIGEN_NEAR(jac0, tangent.element<0>().rjac());\n    EXPECT_EIGEN_NEAR(jac1, tangent.element<1>().rjac());\n    EXPECT_EIGEN_NEAR(jac2, tangent.element<2>().rjac());\n  }\n\n  {\n    auto jac = tangent.ljac();\n    Eigen::Matrix2d jac0 = jac.block<2, 2>(0, 0);\n    Eigen::Matrix3d jac1 = jac.block<3, 3>(2, 2);\n    Eigen::Matrix<double, 1, 1> jac2 = jac.block<1, 1>(5, 5);\n\n    EXPECT_EIGEN_NEAR(jac0, tangent.element<0>().ljac());\n    EXPECT_EIGEN_NEAR(jac1, tangent.element<1>().ljac());\n    EXPECT_EIGEN_NEAR(jac2, tangent.element<2>().ljac());\n  }\n\n  {\n    auto jac = tangent.rjacinv();\n    Eigen::Matrix2d jac0 = jac.block<2, 2>(0, 0);\n    Eigen::Matrix3d jac1 = jac.block<3, 3>(2, 2);\n    Eigen::Matrix<double, 1, 1> jac2 = jac.block<1, 1>(5, 5);\n\n    EXPECT_EIGEN_NEAR(jac0, tangent.element<0>().rjacinv());\n    EXPECT_EIGEN_NEAR(jac1, tangent.element<1>().rjacinv());\n    EXPECT_EIGEN_NEAR(jac2, tangent.element<2>().rjacinv());\n  }\n\n  {\n    auto jac = tangent.ljacinv();\n    Eigen::Matrix2d jac0 = jac.block<2, 2>(0, 0);\n    Eigen::Matrix3d jac1 = jac.block<3, 3>(2, 2);\n    Eigen::Matrix<double, 1, 1> jac2 = jac.block<1, 1>(5, 5);\n\n    EXPECT_EIGEN_NEAR(jac0, tangent.element<0>().ljacinv());\n    EXPECT_EIGEN_NEAR(jac1, tangent.element<1>().ljacinv());\n    EXPECT_EIGEN_NEAR(jac2, tangent.element<2>().ljacinv());\n  }\n\n  {\n    auto jac = tangent.smallAdj();\n    Eigen::Matrix2d jac0 = jac.block<2, 2>(0, 0);\n    Eigen::Matrix3d jac1 = jac.block<3, 3>(2, 2);\n    Eigen::Matrix<double, 1, 1> jac2 = jac.block<1, 1>(5, 5);\n\n    EXPECT_EIGEN_NEAR(jac0, tangent.element<0>().smallAdj());\n    EXPECT_EIGEN_NEAR(jac1, tangent.element<1>().smallAdj());\n    EXPECT_EIGEN_NEAR(jac2, tangent.element<2>().smallAdj());\n  }\n}\n\nMANIF_TEST(GroupA);\nMANIF_TEST_MAP(GroupA);\nMANIF_TEST_JACOBIANS(GroupA);\n\nusing GroupB1 = Bundle<double, R3>;\nusing GroupB2 = Bundle<double, SO2>;\nusing GroupB3 = Bundle<double, SE2>;\nusing GroupB4 = Bundle<double, SO3>;\nusing GroupB5 = Bundle<double, SE3>;\n\nusing GroupC = Bundle<double, R2, SO2, SE2, SO3, SE3>;\nusing GroupD = Bundle<double, SE2, R7, SO3, R2, R2>;\n\nMANIF_TEST(GroupB1);\nMANIF_TEST(GroupB2);\nMANIF_TEST(GroupB3);\nMANIF_TEST(GroupB4);\nMANIF_TEST(GroupB5);\nMANIF_TEST(GroupC);\nMANIF_TEST(GroupD);\n\nMANIF_TEST_MAP(GroupB1);\nMANIF_TEST_MAP(GroupB2);\nMANIF_TEST_MAP(GroupB3);\nMANIF_TEST_MAP(GroupB4);\nMANIF_TEST_MAP(GroupB5);\nMANIF_TEST_MAP(GroupC);\nMANIF_TEST_MAP(GroupD);\n\nMANIF_TEST_JACOBIANS(GroupB1);\nMANIF_TEST_JACOBIANS(GroupB2);\nMANIF_TEST_JACOBIANS(GroupB3);\nMANIF_TEST_JACOBIANS(GroupB4);\nMANIF_TEST_JACOBIANS(GroupB5);\nMANIF_TEST_JACOBIANS(GroupC);\nMANIF_TEST_JACOBIANS(GroupD);\n\n\nint main(int argc, char ** argv)\n{\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "e13d6c01bb0d719e90412d076a1c63fdead9ddb9", "size": 8160, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/bundle/gtest_bundle.cpp", "max_stars_repo_name": "pettni/manif", "max_stars_repo_head_hexsha": "81e9498af69417e4b2ed463d2bcf4b57007c1ca8", "max_stars_repo_licenses": ["MIT"], "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/bundle/gtest_bundle.cpp", "max_issues_repo_name": "pettni/manif", "max_issues_repo_head_hexsha": "81e9498af69417e4b2ed463d2bcf4b57007c1ca8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/bundle/gtest_bundle.cpp", "max_forks_repo_name": "pettni/manif", "max_forks_repo_head_hexsha": "81e9498af69417e4b2ed463d2bcf4b57007c1ca8", "max_forks_repo_licenses": ["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.64, "max_line_length": 99, "alphanum_fraction": 0.6887254902, "num_tokens": 2635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5841081597353271}}
{"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": "#include \"drake/systems/sensors/camera_info.h\"\n\n#include <limits>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n\nnamespace drake {\nnamespace systems {\nnamespace sensors {\nnamespace {\n// This is because there is a precision difference between Ubuntu and Mac.\nconst double kTolerance = 1e-12;\n\nconst int kWidth = 640;\nconst int kHeight = 480;\nconst double kFx = 554.25625842204079;  // In pixels.\nconst double kFy = 579.41125496954282;  // In pixels.\nconst double kCx = kWidth * 0.5 - 0.5;\nconst double kCy = kHeight * 0.5 - 0.5;\nconst double kVerticalFov = 0.78539816339744828;  // 45.0 degrees.\n\nvoid Verify(const Eigen::Matrix3d& expected, const CameraInfo& dut) {\n  EXPECT_EQ(kWidth, dut.width());\n  EXPECT_EQ(kHeight, dut.height());\n  EXPECT_NEAR(expected(0, 0), dut.focal_x(), kTolerance);\n  EXPECT_NEAR(expected(1, 1), dut.focal_y(), kTolerance);\n  EXPECT_NEAR(expected(0, 2), dut.center_x(), kTolerance);\n  EXPECT_NEAR(expected(1, 2), dut.center_y(), kTolerance);\n  EXPECT_TRUE(CompareMatrices(expected, dut.intrinsic_matrix(), kTolerance));\n}\n\nGTEST_TEST(TestCameraInfo, ConstructionTest) {\n  const Eigen::Matrix3d expected(\n      (Eigen::Matrix3d() << kFx, 0., kCx, 0., kFy, kCy, 0., 0., 1.).finished());\n\n  {\n    SCOPED_TRACE(\"Spelled out\");\n    CameraInfo dut(kWidth, kHeight, kFx, kFy, kCx, kCy);\n    Verify(expected, dut);\n  }\n  {\n    SCOPED_TRACE(\"Matrix\");\n    CameraInfo dut(kWidth, kHeight, expected);\n    Verify(expected, dut);\n  }\n}\n\n// The focal lengths become identical with this constructor.\nGTEST_TEST(TestCameraInfo, ConstructionWithFovTest) {\n  const Eigen::Matrix3d expected(\n      (Eigen::Matrix3d() << kFy, 0., kCx, 0., kFy, kCy, 0., 0., 1.).finished());\n\n  CameraInfo dut(kWidth, kHeight, kVerticalFov);\n  Verify(expected, dut);\n}\n\n// Confirms that the reported field of view (in radians) is the same as is\n// given.\nGTEST_TEST(TestCameraInfo, FieldOfView) {\n  // Pick some arbitrary angle that isn't a \"nice\" angle.\n  const double fov_y = M_PI / 7;\n  const double kEps = std::numeric_limits<double>::epsilon();\n\n  {\n    // Square camera: fields of view are equal in x- and y-directions.\n    CameraInfo camera(100, 100, fov_y);\n    EXPECT_NEAR(camera.fov_y(), fov_y, kEps);\n    EXPECT_NEAR(camera.fov_x(), fov_y, kEps);\n  }\n\n  {\n    // Rectangular camera: has an identical *focal lengths* in the x- and y-\n    // directions. But the rectangular image leads to different fields of view.\n    const int w = 100;\n    const int h = 200;\n    CameraInfo camera{w, h, fov_y};\n    const double fov_x = 2 * atan(w * tan(fov_y / 2) / h);\n    EXPECT_NEAR(camera.fov_y(), fov_y, kEps);\n    EXPECT_NEAR(camera.fov_x(), fov_x, kEps);\n  }\n}\n\n}  // namespace\n}  // namespace sensors\n}  // namespace systems\n}  // namespace drake\n", "meta": {"hexsha": "1829817aeebb885f92e62831715199e5f8c04036", "size": 2806, "ext": "cc", "lang": "C++", "max_stars_repo_path": "systems/sensors/test/camera_info_test.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "systems/sensors/test/camera_info_test.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "systems/sensors/test/camera_info_test.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 31.1777777778, "max_line_length": 80, "alphanum_fraction": 0.6899501069, "num_tokens": 840, "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": "/*\nCopyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n\nNVIDIA CORPORATION and its licensors retain all intellectual property\nand proprietary rights in and to this software, related documentation\nand any modifications thereto. Any use, reproduction, disclosure or\ndistribution of this software and related documentation without an express\nlicense agreement from NVIDIA CORPORATION is strictly prohibited.\n*/\n\n#include \"packages/pnp/gems/pnp.hpp\"\n#include \"engine/core/logger.hpp\"\n#include \"packages/pnp/gems/tests/simu.hpp\"\n\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <sstream>\n\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n\n// Global number of repetitions for some randomized tests.\nconstexpr int kRepeatTests = 100;\n\n// Test equivalence of two poses (a and b) are similar within tolerance parameters.\nvoid TestPoseEquivalence(const isaac::Pose3d& a, const isaac::Pose3d& b, double max_distance = 1e-9,\n                         double max_angle_degrees = 1e-9) {\n  // Calculate difference in orientation.\n  isaac::SO3d delta_rot = a.rotation.inverse() * b.rotation;\n  double angle = std::fmod(isaac::RadToDeg(std::abs(delta_rot.angle())), 360.0);\n  angle = std::min(angle, 360.0 - angle);\n\n  // Calculate difference in position.\n  // Convert world origin in camera frame to camera position in world frame. This can make\n  // a significant difference in case of a moving camera far away from world origin.\n  isaac::Vector3d position1 = -a.rotation.matrix().transpose() * a.translation;\n  isaac::Vector3d position2 = -b.rotation.matrix().transpose() * b.translation;\n\n  ASSERT_LT((position1 - position2).norm(), max_distance);\n  ASSERT_LT(angle, max_angle_degrees);\n}\n\n// Test EPnP pose estimation with random camera poses and 3D points on a FRONTO-PARALLEL plane.\n// Noise-free 2D-3D point matches, no outliers.\nTEST(PnpTest, EpnpFrontoPlanarTest) {\n  SCOPED_TRACE(\"EpnpFrontoPlanarTest\");\n\n  // Repeat the test with different random poses and points.\n  for (int i = 0; i < kRepeatTests; i++) {\n    // Generate a camera with fixed intrinsics and random pose.\n    const int width = 1280;\n    const int height = 720;\n    const double focal = 700.0;\n    isaac::pnp::Camera camera = isaac::pnp::GenerateRandomCamera(width, height, focal);\n    const double focal_u = camera.calib_matrix(0, 0);\n    const double focal_v = camera.calib_matrix(1, 1);\n    const double principal_u = camera.calib_matrix(0, 2);\n    const double principal_v = camera.calib_matrix(1, 2);\n\n    // Construct isaac::Pose3d object from the generated camera pose.\n    // This is the known ground-truth pose to compare to the output of pose estimation.\n    isaac::Vector3d gt_angle_axis = isaac::pnp::AngleAxisFromMatrix(camera.rotation_matrix);\n    isaac::Pose3d gt_pose{isaac::SO3d::FromAngleAxis(gt_angle_axis.norm(), gt_angle_axis),\n                          -camera.rotation_matrix * camera.position};\n\n    // Point generation parameters.\n    const double depth = 5.0;  // Plane depth in meters\n    const double angle = 0.0;  // Plane inclination angle in degrees (0 is fronto-parallel).\n\n    // Output of point generation and pose estimation.\n    isaac::Matrix3Xd points3;\n    isaac::Matrix2Xd points2;\n    isaac::Vector4d plane;\n    isaac::Pose3d pose;\n\n    // Test EPnP camera pose estimation from 6 points on a fronto-parallel plane.\n    isaac::pnp::GenerateFovPointsPlanar(6, camera, depth, angle, 0, &points3, &points2, &plane);\n    ASSERT_EQ(isaac::pnp::ComputeCameraPoseEpnp(points3, points2, focal_u, focal_v, principal_u,\n                                                principal_v, &pose),\n              isaac::pnp::Status::kSuccess);\n    TestPoseEquivalence(pose, gt_pose);\n\n    // Same test with many points.\n    isaac::pnp::GenerateFovPointsPlanar(50, camera, depth, angle, 0, &points3, &points2, &plane);\n    ASSERT_EQ(isaac::pnp::ComputeCameraPoseEpnp(points3, points2, focal_u, focal_v, principal_u,\n                                                principal_v, &pose),\n              isaac::pnp::Status::kSuccess);\n    TestPoseEquivalence(pose, gt_pose);\n  }\n}\n\n// Test EPnP pose estimation with random camera poses and 3D points on a SLANTED plane.\n// Noise-free 2D-3D point matches, no outliers.\nTEST(PnpTest, EpnpSlantedPlanarTest) {\n  SCOPED_TRACE(\"EpnpSlantedPlanarTest\");\n\n  // Repeat the test with different random poses and points.\n  for (int i = 0; i < kRepeatTests; i++) {\n    // Generate a camera with fixed intrinsics and random pose.\n    const int width = 1280;\n    const int height = 720;\n    const double focal = 700.0;\n    isaac::pnp::Camera camera = isaac::pnp::GenerateRandomCamera(width, height, focal);\n    const double focal_u = camera.calib_matrix(0, 0);\n    const double focal_v = camera.calib_matrix(1, 1);\n    const double principal_u = camera.calib_matrix(0, 2);\n    const double principal_v = camera.calib_matrix(1, 2);\n\n    // Construct isaac::Pose3d object from the generated camera pose.\n    // This is the known ground-truth pose to compare to the output of pose estimation.\n    isaac::Vector3d gt_angle_axis = isaac::pnp::AngleAxisFromMatrix(camera.rotation_matrix);\n    isaac::Pose3d gt_pose{isaac::SO3d::FromAngleAxis(gt_angle_axis.norm(), gt_angle_axis),\n                          -camera.rotation_matrix * camera.position};\n\n    // Point generation parameters.\n    const double depth = 10.0;  // Plane depth in meters\n    const double angle = 30.0;  // Plane inclination angle in degrees (0 is fronto-parallel).\n\n    // Output of point generation and pose estimation.\n    isaac::Matrix3Xd points3;\n    isaac::Matrix2Xd points2;\n    isaac::Vector4d plane;\n    isaac::Pose3d pose;\n\n    // Test EPnP camera pose estimation from 6 points on a slanted plane.\n    GenerateFovPointsPlanar(6, camera, depth, angle, 0, &points3, &points2, &plane);\n    ASSERT_EQ(isaac::pnp::ComputeCameraPoseEpnp(points3, points2, focal_u, focal_v, principal_u,\n                                                principal_v, &pose),\n              isaac::pnp::Status::kSuccess);\n    TestPoseEquivalence(pose, gt_pose);\n\n    // Same test with many points.\n    GenerateFovPointsPlanar(50, camera, depth, angle, 0, &points3, &points2, &plane);\n    ASSERT_EQ(isaac::pnp::ComputeCameraPoseEpnp(points3, points2, focal_u, focal_v, principal_u,\n                                                principal_v, &pose),\n              isaac::pnp::Status::kSuccess);\n    TestPoseEquivalence(pose, gt_pose);\n  }\n}\n\n// Test EPnP pose estimation with random camera poses and 3D points within a depth range.\n// Noise-free 2D-3D point matches, no outliers.\nTEST(PnpTest, EpnpNonPlanarTest) {\n  SCOPED_TRACE(\"EpnpNonPlanarTest\");\n\n  // Repeat the test with different random poses and points.\n  for (int i = 0; i < kRepeatTests; i++) {\n    // Generate a camera with fixed intrinsics and random pose.\n    const int width = 1280;\n    const int height = 720;\n    const double focal = 700.0;\n    isaac::pnp::Camera camera = isaac::pnp::GenerateRandomCamera(width, height, focal);\n    const double focal_u = camera.calib_matrix(0, 0);\n    const double focal_v = camera.calib_matrix(1, 1);\n    const double principal_u = camera.calib_matrix(0, 2);\n    const double principal_v = camera.calib_matrix(1, 2);\n\n    // Construct isaac::Pose3d object from the generated camera pose.\n    // This is the known ground-truth pose to compare to the output of pose estimation.\n    isaac::Vector3d gt_angle_axis = isaac::pnp::AngleAxisFromMatrix(camera.rotation_matrix);\n    isaac::Pose3d gt_pose{isaac::SO3d::FromAngleAxis(gt_angle_axis.norm(), gt_angle_axis),\n                          -camera.rotation_matrix * camera.position};\n\n    // Point generation parameters.\n    const double near = 2.0;\n    const double far = 100.0;\n\n    // Output of point generation and pose estimation.\n    isaac::Matrix3Xd points3;\n    isaac::Matrix2Xd points2;\n    isaac::Vector4d plane;\n    isaac::Pose3d pose;\n\n    // Test EPnP pose estimation from 6 points between the near and far planes.\n    GenerateFovPoints(6, camera, near, far, &points3, &points2);\n    ASSERT_EQ(isaac::pnp::ComputeCameraPoseEpnp(points3, points2, focal_u, focal_v, principal_u,\n                                                principal_v, &pose),\n              isaac::pnp::Status::kSuccess);\n    TestPoseEquivalence(pose, gt_pose);\n\n    // Same test with many points.\n    GenerateFovPoints(50, camera, near, far, &points3, &points2);\n    ASSERT_EQ(isaac::pnp::ComputeCameraPoseEpnp(points3, points2, focal_u, focal_v, principal_u,\n                                                principal_v, &pose),\n              isaac::pnp::Status::kSuccess);\n    TestPoseEquivalence(pose, gt_pose);\n  }\n}\n\n// Print table of the necessary number of RANSAC experiments for different outlier ratios (columns)\n// and different sample sizes (in table rows).\nvoid PrintRansacTable(double success_rate = 0.99) {\n  // Outlier ratios and sample sizes to sweep over.\n  std::vector<double> outlier_ratios{0.05, 0.10, 0.20, 0.25, 0.30, 0.40, 0.50};\n  std::vector<int> sample_sizes{2, 3, 4, 5, 6, 7, 8};\n\n  // Print table header.\n  std::stringstream ss;\n  const int cell_width = 4;\n  ss << \"    \";\n  for (double outlier_ratio : outlier_ratios) {\n    ss << std::setw(cell_width) << 100.0 * outlier_ratio << \"%\";\n  }\n  LOG_INFO(\"\\t%s\", ss.str().c_str());\n\n  // Print table body row by row.\n  for (int sample_size : sample_sizes) {\n    ss.str(\"\");\n    ss.clear();\n    ss << sample_size << \"-pt\";\n    for (double outlier_ratio : outlier_ratios) {\n      ss << \" \" << std::setw(cell_width);\n      ss << isaac::pnp::EvaluateRansacFormula(success_rate, outlier_ratio, sample_size);\n    }\n    LOG_INFO(\"\\t%s\", ss.str().c_str());\n  }\n}\n\n// Test if isaac::pnp::EvaluateRansacFormula() returns the values given in a textbook.\nTEST(PnpTest, RansacFormulaTest) {\n  // Print the RANSAC table for information.\n  PrintRansacTable(0.99);\n\n  // Reference values are taken from the book of Hartley & Zisserman, 3rd ed., p. 119, Table 4.3\n  std::vector<double> outlier_ratio{0.05, 0.10, 0.20, 0.25, 0.30, 0.40, 0.50};\n  std::vector<int> sample_size{2, 3, 4, 5, 6, 7, 8};\n  Eigen::MatrixXi num_experiments(sample_size.size(), outlier_ratio.size());\n  num_experiments << 2, 3, 5, 6, 7, 11, 17, 3, 4, 7, 9, 11, 19, 35, 3, 5, 9, 13, 17, 34, 72, 4, 6,\n      12, 17, 26, 57, 146, 4, 7, 16, 24, 37, 97, 293, 4, 8, 20, 33, 54, 163, 588, 5, 9, 26, 44, 78,\n      272, 1177;\n\n  // Compare the output of EvaluateRansacFormula() to the reference values.\n  for (size_t i = 0; i < sample_size.size(); i++) {\n    for (size_t j = 0; j < outlier_ratio.size(); j++) {\n      EXPECT_EQ(isaac::pnp::EvaluateRansacFormula(0.99, outlier_ratio[j], sample_size[i]),\n                num_experiments(i, j));\n    }\n  }\n}\n\n// Test RANSAC-EPnP pose estimation on a many random synthetic datasets contaminated with outliers.\n// In each each test run:\n// (1) Generate a camera with a random pose.\n// (2) Generate a fixed number of 2D/3D point match inliers and add a fixed percentage of outliers.\n// (3) Run RANSAC-EPnP.\n// (4) Test the result and collect statistics.\nTEST(PnpTest, EpnpRansacTest) {\n  SCOPED_TRACE(\"EpnpRansacTest\");\n\n  // Fixed number of inliers and outliers.\n  const double outlier_ratio = 0.3;\n  const unsigned num_inliers = 20;\n  const unsigned num_outliers = round(outlier_ratio / (1.0 - outlier_ratio) * num_inliers);\n\n  // RANSAC parameters.\n  const unsigned ransac_rounds = 40;\n  const double ransac_threshold = 1e-3;\n  const unsigned max_top_poses = 5;\n  unsigned rand_seed = 0;\n  std::random_device rnd;\n\n  // Collect outlier ratio statistics over many runs for reporting.\n  double min_outlier_ratio = 1.0;\n  double max_outlier_ratio = 0;\n  // unsigned max_hypotheses_found = 0;\n\n  // Run RANSAC on many different random datasets,\n  // each with a random camera pose and 2D/3D matches.\n  const unsigned num_runs = 100;\n  unsigned num_poses_found = 0;  // Total number of successful pose estimations across all runs.\n  for (unsigned i = 0; i < num_runs; i++) {\n    // Generate a camera with fixed intrinsics and random pose.\n    const int width = 1280;\n    const int height = 720;\n    const double focal = 700.0;\n    isaac::pnp::Camera camera = isaac::pnp::GenerateRandomCamera(width, height, focal);\n    const double focal_u = camera.calib_matrix(0, 0);\n    const double focal_v = camera.calib_matrix(1, 1);\n    const double principal_u = camera.calib_matrix(0, 2);\n    const double principal_v = camera.calib_matrix(1, 2);\n\n    // Construct isaac::Pose3d object from the generated camera pose.\n    // This is the known ground-truth pose to compare to the output of pose estimation.\n    isaac::Vector3d gt_angle_axis = isaac::pnp::AngleAxisFromMatrix(camera.rotation_matrix);\n    isaac::Pose3d gt_pose{isaac::SO3d::FromAngleAxis(gt_angle_axis.norm(), gt_angle_axis),\n                          -camera.rotation_matrix * camera.position};\n\n    // Generate inlier 2D-3D matches without noise.\n    // 3D points are within camera FoV between near and far planes.\n    const double near = 2.0;\n    const double far = 6.0;\n    isaac::Matrix3Xd points3;\n    isaac::Matrix2Xd points2;\n    isaac::pnp::GenerateFovPoints(num_inliers, camera, near, far, &points3, &points2);\n\n    // Generate outlier 2D-3D matches\n    isaac::pnp::InsertOutliers(num_outliers, camera, 30.0, &points3, &points2);\n\n    // Calculate reprojection error for every single point match.\n    isaac::VectorXd errs =\n        isaac::pnp::ColwiseNorms(points2 - ProjectPoints(camera, points3, true, true));\n\n    // Separate inliers from outliers based on reprojection error.\n    // Because generated outliers have 1.0 chance to be outliers, but that is not guarantee.\n    std::vector<bool> is_inlier(errs.size());\n    for (unsigned k = 0; k < errs.size(); k++) {\n      is_inlier[k] = (errs(k) <= ransac_threshold);\n    }\n    unsigned num_actual_outliers = (errs.array() > ransac_threshold).count();\n    double ratio = double(num_actual_outliers) / points3.cols();\n    if (ratio < min_outlier_ratio) {\n      min_outlier_ratio = ratio;\n    }\n    if (ratio > max_outlier_ratio) {\n      max_outlier_ratio = ratio;\n    }\n\n    // Run RANSAC-EPnP camera pose estimation on the current synthetic dataset.\n    rand_seed = rnd();\n    auto top_hypotheses = isaac::pnp::ComputeCameraPoseEpnpRansac(\n        points3, points2, focal_u, focal_v, principal_u, principal_v, ransac_rounds,\n        ransac_threshold, max_top_poses, rand_seed);\n\n    // Count successful pose estimations accross runs.\n    if (top_hypotheses.size()) {\n      num_poses_found++;\n    }\n\n    // Test if the output list of top hypotheses does not exceed the prescribed capacity.\n    ASSERT_LE(top_hypotheses.size(), max_top_poses);\n\n    // Check each output pose hypothesis individually.\n    for (const auto& hyp : top_hypotheses) {\n      // There should be at least 6 inliers for any accepted pose hypothesis.\n      ASSERT_GE(hyp.inliers.size(), 6);\n\n      // Inliers are perfect (zero reprojection error),\n      // so hypothesis score must be equal to the number of inliers up to numerical precision.\n      EXPECT_NEAR(hyp.score, hyp.inliers.size(), 1e-3);\n\n      // Make sure estimated pose matches the ground truth pose.\n      TestPoseEquivalence(hyp.pose, gt_pose);\n    }\n  }\n\n  // Print statistics.\n  unsigned min_successful_runs = 0.9 * num_runs;\n  LOG_INFO(\"Ransac: %.2f%% outliers, %d rounds\", 100.0 * min_outlier_ratio, ransac_rounds);\n  LOG_INFO(\"Ransac: no result in %d test runs, correct pose in %d of %d cases (%d required)\",\n           num_runs - num_poses_found, num_poses_found, num_runs, min_successful_runs);\n\n  // Require a high percentage of test runs to succeed.\n  // Do not require all test runs to succeed because RANSAC is a randomized algorithm,\n  // finding the solution is not guaranteed but should has a high chance.\n  EXPECT_GE(num_poses_found, min_successful_runs);\n}\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "ffcadb410972078dc2742a9dd4993a262ac6d6ae", "size": 15908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/packages/pnp/gems/tests/pnp_test.cpp", "max_stars_repo_name": "ddr95070/RMIsaac", "max_stars_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdk/packages/pnp/gems/tests/pnp_test.cpp", "max_issues_repo_name": "ddr95070/RMIsaac", "max_issues_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/packages/pnp/gems/tests/pnp_test.cpp", "max_forks_repo_name": "ddr95070/RMIsaac", "max_forks_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-28T16:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T16:37:51.000Z", "avg_line_length": 43.8236914601, "max_line_length": 100, "alphanum_fraction": 0.6879557455, "num_tokens": 4368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5839788273237824}}
{"text": "#include <blitz/array.h>\n#include <blitz/numinquire.h> // for huge()\n\nusing 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    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_ = static_cast<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    // 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", "meta": {"hexsha": "1767bb4e8f7c7b0fa20ca0a1e91d2fcd583ce525", "size": 1119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/doc/examples/fixed-class.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/fixed-class.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/fixed-class.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9661016949, "max_line_length": 72, "alphanum_fraction": 0.5773011618, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478254, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5839788253465936}}
{"text": "/**************************************************************************\n * Copyright (c) 2017-2019 by the mfmg authors                            *\n * All rights reserved.                                                   *\n *                                                                        *\n * This file is part of the mfmg library. mfmg is distributed under a BSD *\n * 3-clause license. For the licensing terms see the LICENSE file in the  *\n * top-level directory                                                    *\n *                                                                        *\n * SPDX-License-Identifier: BSD-3-Clause                                  *\n *************************************************************************/\n\n#ifndef MFMG_LANCZOS_SIMPLEOP_TEMPLATE_HPP\n#define MFMG_LANCZOS_SIMPLEOP_TEMPLATE_HPP\n\n#include <deal.II/lac/la_parallel_vector.h>\n\n#include <cassert>\n\n#include \"lanczos_simpleop.hpp\"\n\nnamespace mfmg\n{\n// This will be a diagonal matrix; specify the diag entries here\n#ifdef __CUDACC__\n__host__ __device__\n#endif\n    double\n    diag_value(size_t i, size_t multiplicity)\n{\n  return 1 + i / multiplicity;\n}\n\n#ifdef __CUDACC__\n__global__ void vmult_kernel(double *y, double const *x, unsigned int dim,\n                             unsigned int multiplicity)\n{\n  int i = threadIdx.x + blockDim.x * blockIdx.x;\n  if (i < dim)\n  {\n    y[i] = diag_value(i, multiplicity) * x[i];\n  }\n}\n#endif\n\n/// \\brief Simple test operator: constructor\ntemplate <typename VectorType>\nSimpleOperator<VectorType>::SimpleOperator(size_t dim, size_t multiplicity)\n    : _dim(dim), _multiplicity(multiplicity)\n{\n  assert(multiplicity > 0);\n}\n\ntemplate <typename VectorType>\nstd::vector<double> SimpleOperator<VectorType>::get_evals() const\n{\n  std::vector<double> evals(_dim);\n  for (size_t i = 0; i < _dim; i++)\n    evals[i] = diag_value(i, _multiplicity);\n\n  return evals;\n}\n\n/// \\brief Simple test operator: apply operator to a vector\ntemplate <typename VectorType>\nvoid SimpleOperator<VectorType>::vmult(VectorType &y, VectorType const &x) const\n{\n  ASSERT(x.size() == _dim, \"\");\n  ASSERT(y.size() == _dim, \"\");\n\n  for (size_t i = 0; i < _dim; ++i)\n    y[i] = diag_value(i, _multiplicity) * x[i];\n}\n\n#ifdef __CUDACC__\ntemplate <>\nvoid SimpleOperator<dealii::LinearAlgebra::distributed::Vector<\n    double, dealii::MemorySpace::CUDA>>::\n    vmult(dealii::LinearAlgebra::distributed::Vector<\n              double, dealii::MemorySpace::CUDA> &y,\n          dealii::LinearAlgebra::distributed::Vector<\n              double, dealii::MemorySpace::CUDA> const &x) const\n{\n  // CUDA does not like size_t. I think that size_t on the device is 32 bits\n  // while it 64 bits on the host and thus, dim and multiplicity in the kernel\n  // are garbage\n  unsigned int d = _dim;\n  unsigned int m = _multiplicity;\n  int n_blocks = 1 + _dim / 512;\n  vmult_kernel<<<n_blocks, 512>>>(y.get_values(), x.get_values(), d, m);\n}\n#endif\n\n} // namespace mfmg\n\n#endif\n", "meta": {"hexsha": "20918a85a65447dcde3b2e5edcef8d919c9c328d", "size": 2977, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/lanczos_simpleop.templates.hpp", "max_stars_repo_name": "Rombur/mfmg", "max_stars_repo_head_hexsha": "b7c66dfb58bc880b04f52ce22b454047f82d69ea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-11-03T15:13:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T19:33:10.000Z", "max_issues_repo_path": "tests/lanczos_simpleop.templates.hpp", "max_issues_repo_name": "Rombur/mfmg", "max_issues_repo_head_hexsha": "b7c66dfb58bc880b04f52ce22b454047f82d69ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 199.0, "max_issues_repo_issues_event_min_datetime": "2017-11-03T13:33:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-07T22:46:18.000Z", "max_forks_repo_path": "tests/lanczos_simpleop.templates.hpp", "max_forks_repo_name": "Rombur/mfmg", "max_forks_repo_head_hexsha": "b7c66dfb58bc880b04f52ce22b454047f82d69ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-11-03T12:44:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-16T05:51:23.000Z", "avg_line_length": 31.0104166667, "max_line_length": 80, "alphanum_fraction": 0.5858246557, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.5839788245126335}}
{"text": "/* \n * File:   ConvolutionLayer.hpp\n * Author: heshan\n *\n * Created on June 6, 2018, 6:26 PM\n */\n\n#ifndef CONVOLUTIONLAYER_HPP\n#define CONVOLUTIONLAYER_HPP\n\n#include <Eigen>\n#include <iostream>\n#include \"Activation.hpp\"\n#include <string>\n\nclass ConvolutionLayer {\npublic:\n    ConvolutionLayer();\n    /**\n     * Constructor\n     * \n     * @param dimensions: dimensions of the input matrix (depth, height, width)\n     * @param filterSize: size of the filter N, (N x N) \n     * @param stride: displacement units of the filter\n     * @param noOfFilters: no of filters\n     * @param padding\n     */\n    ConvolutionLayer(std::tuple<int, int, int> dimensions, int filterSize, int stride, int noOfFilters, int padding);\n    /**\n     * \n     * @param orig\n     */\n    ConvolutionLayer(const ConvolutionLayer& orig);\n    /**\n     */\n    virtual ~ConvolutionLayer();\n    /**\n     * Initialize weight matrices and the bias values for the convolutional layer\n     * \n     * @return 0\n     */\n    int initMat();\n    /**\n     * Apply the convolution operation to the image using the generated filters\n     * \n     * @param input: input image or matrix\n     * @return an array of convoluted images (array size = no of filters)\n     */\n    Eigen::MatrixXd * convolute(Eigen::MatrixXd * input);\n    /**\n     * Return the dimension of the layer output\n     * \n     * @return a tuple\n     */\n    std::tuple<int, int, int> getOutputDims();\n    \nprivate:\n    int height, width, padding = 0;\n    \npublic:\n    int stride, filterSize;\n    int depth, noOfFilters;\n    int outHeight, outWidth;\n    double * bias;\n    Eigen::MatrixXd ** filters;\n    Eigen::MatrixXd * output;\n    Eigen::MatrixXd * activatedOut;\n    \n};\n\n#endif /* CONVOLUTIONLAYER_HPP */\n\n", "meta": {"hexsha": "34ef4295aa820922431461254dd46a22eb07b50f", "size": 1728, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ProfilingModule/Profilers/LSTMCNnet/CNNet/ConvolutionLayer.hpp", "max_stars_repo_name": "pasindubawantha/sherlock-framework", "max_stars_repo_head_hexsha": "92d64fbc86256a61c6b00b7ca9eb0a17634c7446", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ProfilingModule/Profilers/LSTMCNnet/CNNet/ConvolutionLayer.hpp", "max_issues_repo_name": "pasindubawantha/sherlock-framework", "max_issues_repo_head_hexsha": "92d64fbc86256a61c6b00b7ca9eb0a17634c7446", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ProfilingModule/Profilers/LSTMCNnet/CNNet/ConvolutionLayer.hpp", "max_forks_repo_name": "pasindubawantha/sherlock-framework", "max_forks_repo_head_hexsha": "92d64fbc86256a61c6b00b7ca9eb0a17634c7446", "max_forks_repo_licenses": ["Apache-2.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.6712328767, "max_line_length": 117, "alphanum_fraction": 0.6278935185, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.5839788225354453}}
{"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/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/module/bessel.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n#include <eve/detail/diff_div.hpp>\n\nEVE_TEST_TYPES( \"Check return types of sph_bessel_j1\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  TTS_EXPR_IS(eve::sph_bessel_j1(T(0)), T);\n  TTS_EXPR_IS(eve::sph_bessel_j1(v_t(0)), v_t);\n};\n\n EVE_TEST( \"Check behavior of sph_bessel_j1 on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.0, 5.5),\n                              eve::test::randoms(5.5, 9.5),\n                              eve::test::randoms(9.5, 60.0))\n         )\n   <typename T>(T const& a0, T const& a1, T const& a2)\n{\n  using v_t = eve::element_type_t<T>;\n  auto eve__sph_bessel_j1 =  [](auto x) { return eve::sph_bessel_j1(x); };\n  auto std__sph_bessel_j1 =  [](auto x)->v_t { return boost::math::sph_bessel(double(1), double(x)); };\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__sph_bessel_j1(eve::inf(eve::as<v_t>())), eve::zero(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_j1(eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_j1(eve::inf(eve::as< T>())),  eve::zero(eve::as< T>()), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_j1(eve::nan(eve::as< T>())), eve::nan(eve::as< T>()), 0);\n  }\n  TTS_ULP_EQUAL(eve__sph_bessel_j1(v_t(500)), std__sph_bessel_j1(v_t(500)), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1(v_t(10)), std__sph_bessel_j1(v_t(10))  , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1(v_t(5)),  std__sph_bessel_j1(v_t(5))   , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1(v_t(2)),  std__sph_bessel_j1(v_t(2))   , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1(v_t(1.5)),std__sph_bessel_j1(v_t(1.5)) , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1(v_t(0.5)),std__sph_bessel_j1(v_t(0.5)) , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1(v_t(1)),  std__sph_bessel_j1(v_t(1))   , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1(v_t(0)),  eve::zero(eve::as<v_t>()), 0.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_j1( T(500)),  T(std__sph_bessel_j1(v_t(500)) ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1( T(10)) ,  T(std__sph_bessel_j1( v_t(10)) ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1( T(5))  ,  T(std__sph_bessel_j1( v_t(5))  ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1( T(2))  ,  T(std__sph_bessel_j1( v_t(2))  ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1( T(1.5)),  T(std__sph_bessel_j1( v_t(1.5))), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1( T(0.5)),  T(std__sph_bessel_j1( v_t(0.5))), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1( T(1))  ,  T(std__sph_bessel_j1( v_t(1))  ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1( T(0))  , eve::zero(eve::as< T>()), 0.0);\n\n\n  TTS_ULP_EQUAL(eve__sph_bessel_j1(a0), map(std__sph_bessel_j1, a0), 40.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1(a1), map(std__sph_bessel_j1, a1), 40.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j1(a2), map(std__sph_bessel_j1, a2), 40.0);\n\n};\n\n\nEVE_TEST( \"Check behavior of diff(sph_bessel_j1) on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(1.0, 10.0))\n        )\n  <typename T>(T a0 )\n{\n  auto eve__diff_bessel_j1 =  [](auto x) { return eve::diff(eve::sph_bessel_j1)(x); };\n  auto df = [](auto x){return eve::detail::centered_diffdiv(eve::sph_bessel_j1, x); };\n\n  TTS_RELATIVE_EQUAL(eve__diff_bessel_j1(a0),   df(a0), 2.0e-2);\n};\n", "meta": {"hexsha": "0a9fd0e50c95e47161f489830165f59ef42bb018", "size": 3781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/bessel/sph_bessel_j1.cpp", "max_stars_repo_name": "clayne/eve", "max_stars_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/bessel/sph_bessel_j1.cpp", "max_issues_repo_name": "clayne/eve", "max_issues_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/bessel/sph_bessel_j1.cpp", "max_forks_repo_name": "clayne/eve", "max_forks_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.2625, "max_line_length": 103, "alphanum_fraction": 0.6315789474, "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5839544377656786}}
{"text": "/**\n * @file lmnn_test.cpp\n * @author Marcus Edel\n * @author Ryan Curtin\n * @author Manish Kumar\n *\n * Unit tests for Large Margin Nearest Neighbors and related code (including\n * the constraints class).\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/core/metrics/lmetric.hpp>\n#include <mlpack/methods/lmnn/lmnn.hpp>\n#include <mlpack/core/optimizers/lbfgs/lbfgs.hpp>\n#include <mlpack/methods/neighbor_search/neighbor_search.hpp>\n#include <mlpack/core/optimizers/bigbatch_sgd/bigbatch_sgd.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::metric;\nusing namespace mlpack::lmnn;\nusing namespace mlpack::optimization;\n\n\nBOOST_AUTO_TEST_SUITE(LMNNTest);\n\n//\n// Tests for the Constraints.\n//\n\n/**\n * The target neighbors function should be correct.\n * point.\n */\nBOOST_AUTO_TEST_CASE(LMNNTargetNeighborsTest)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset        = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  Constraints<> constraint(dataset, labels, 1);\n\n  // Calculate norm of datapoints.\n  arma::vec norm(dataset.n_cols);\n  for (size_t i = 0; i < dataset.n_cols; i++)\n  {\n    norm(i) = arma::norm(dataset.col(i));\n  }\n\n  //! Store target neighbors of data points.\n  arma::Mat<size_t> targetNeighbors =\n      arma::Mat<size_t>(1, dataset.n_cols, arma::fill::zeros);\n\n  constraint.TargetNeighbors(targetNeighbors, dataset, labels, norm);\n\n  BOOST_REQUIRE_EQUAL(targetNeighbors(0, 0), 1);\n  BOOST_REQUIRE_EQUAL(targetNeighbors(0, 1), 0);\n  BOOST_REQUIRE_EQUAL(targetNeighbors(0, 2), 1);\n  BOOST_REQUIRE_EQUAL(targetNeighbors(0, 3), 4);\n  BOOST_REQUIRE_EQUAL(targetNeighbors(0, 4), 3);\n  BOOST_REQUIRE_EQUAL(targetNeighbors(0, 5), 4);\n}\n\n/**\n * The impostors function should be correct.\n */\nBOOST_AUTO_TEST_CASE(LMNNImpostorsTest)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset        = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  Constraints<> constraint(dataset, labels, 1);\n\n  // Calculate norm of datapoints.\n  arma::vec norm(dataset.n_cols);\n  for (size_t i = 0; i < dataset.n_cols; i++)\n  {\n    norm(i) = arma::norm(dataset.col(i));\n  }\n\n  //! Store impostors of data points.\n  arma::Mat<size_t> impostors =\n      arma::Mat<size_t>(1, dataset.n_cols, arma::fill::zeros);\n\n  constraint.Impostors(impostors, dataset, labels, norm);\n\n  BOOST_REQUIRE_EQUAL(impostors(0, 0), 3);\n  BOOST_REQUIRE_EQUAL(impostors(0, 1), 4);\n  BOOST_REQUIRE_EQUAL(impostors(0, 2), 5);\n  BOOST_REQUIRE_EQUAL(impostors(0, 3), 0);\n  BOOST_REQUIRE_EQUAL(impostors(0, 4), 1);\n  BOOST_REQUIRE_EQUAL(impostors(0, 5), 2);\n}\n\n//\n// Tests for the LMNNFunction\n//\n\n/**\n * The LMNN function should return the identity matrix as its initial\n * point.\n */\nBOOST_AUTO_TEST_CASE(LMNNInitialPointTest)\n{\n  // Cheap fake dataset.\n  arma::mat dataset = arma::randu(5, 5);\n  arma::Row<size_t> labels = \"0 1 1 0 0\";\n\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.5, 1);\n\n  // Verify the initial point is the identity matrix.\n  arma::mat initialPoint = lmnnfn.GetInitialPoint();\n  for (int row = 0; row < 5; row++)\n  {\n    for (int col = 0; col < 5; col++)\n    {\n      if (row == col)\n        BOOST_REQUIRE_CLOSE(initialPoint(row, col), 1.0, 1e-5);\n      else\n        BOOST_REQUIRE_SMALL(initialPoint(row, col), 1e-5);\n    }\n  }\n}\n\n/***\n * Ensure non-seprable objective function is right.\n */\nBOOST_AUTO_TEST_CASE(LMNNInitialEvaluationTest)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset        = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.6, 1);\n\n  double objective = lmnnfn.Evaluate(arma::eye<arma::mat>(2, 2));\n\n  // Result calculated by hand.\n  BOOST_REQUIRE_CLOSE(objective, 9.456, 1e-5);\n}\n\n/**\n * Ensure non-seprable gradient function is right.\n */\nBOOST_AUTO_TEST_CASE(LMNNInitialGradientTest)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset        = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.6, 1);\n\n  arma::mat gradient;\n  arma::mat coordinates = arma::eye<arma::mat>(2, 2);\n  lmnnfn.Gradient(coordinates, gradient);\n\n  // Result calculated by hand.\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.288, 1e-5);\n  BOOST_REQUIRE_SMALL(gradient(1, 0), 1e-5);\n  BOOST_REQUIRE_SMALL(gradient(0, 1), 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 12.0, 1e-5);\n}\n\n/***\n * Ensure non-seprable EvaluateWithGradient function is right.\n */\nBOOST_AUTO_TEST_CASE(LMNNInitialEvaluateWithGradientTest)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset        = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.6, 1);\n\n  arma::mat gradient;\n  arma::mat coordinates = arma::eye<arma::mat>(2, 2);\n  double objective = lmnnfn.EvaluateWithGradient(coordinates, gradient);\n\n  // Result calculated by hand.\n  BOOST_REQUIRE_CLOSE(objective, 9.456, 1e-5);\n  // Check Gradient\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.288, 1e-5);\n  BOOST_REQUIRE_SMALL(gradient(1, 0), 1e-5);\n  BOOST_REQUIRE_SMALL(gradient(0, 1), 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 12.0, 1e-5);\n}\n\n/**\n * Ensure the separable objective function is right.\n */\nBOOST_AUTO_TEST_CASE(LMNNSeparableObjectiveTest)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset        = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.6, 1);\n\n  // Result calculated by hand.\n  arma::mat coordinates = arma::eye<arma::mat>(2, 2);\n  BOOST_REQUIRE_CLOSE(lmnnfn.Evaluate(coordinates, 0, 1), 1.576, 1e-5);\n  BOOST_REQUIRE_CLOSE(lmnnfn.Evaluate(coordinates, 1, 1), 1.576, 1e-5);\n  BOOST_REQUIRE_CLOSE(lmnnfn.Evaluate(coordinates, 2, 1), 1.576, 1e-5);\n  BOOST_REQUIRE_CLOSE(lmnnfn.Evaluate(coordinates, 3, 1), 1.576, 1e-5);\n  BOOST_REQUIRE_CLOSE(lmnnfn.Evaluate(coordinates, 4, 1), 1.576, 1e-5);\n  BOOST_REQUIRE_CLOSE(lmnnfn.Evaluate(coordinates, 5, 1), 1.576, 1e-5);\n}\n\n/**\n * Ensure the separable gradient is right.\n */\nBOOST_AUTO_TEST_CASE(LMNNSeparableGradientTest)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset           = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.6, 1);\n\n  arma::mat coordinates = arma::eye<arma::mat>(2, 2);\n  arma::mat gradient(2, 2);\n\n  lmnnfn.Gradient(coordinates, 0, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.048, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 2.0, 1e-5);\n\n  lmnnfn.Gradient(coordinates, 1, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.048, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 2.0, 1e-5);\n\n  lmnnfn.Gradient(coordinates, 2, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.048, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 2.0, 1e-5);\n\n  lmnnfn.Gradient(coordinates, 3, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.048, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 2.0, 1e-5);\n\n  lmnnfn.Gradient(coordinates, 4, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.048, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 2.0, 1e-5);\n\n  lmnnfn.Gradient(coordinates, 5, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.048, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 2.0, 1e-5);\n}\n\n/**\n * Ensure the separable EvaluateWithGradient function is right.\n */\nBOOST_AUTO_TEST_CASE(LMNNSeparableEvaluateWithGradientTest)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset           = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.6, 1);\n\n  arma::mat coordinates = arma::eye<arma::mat>(2, 2);\n  arma::mat gradient(2, 2);\n\n  double objective = lmnnfn.EvaluateWithGradient(coordinates, 0, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(objective, 1.576, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.048, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 2.0, 1e-5);\n\n  objective = lmnnfn.EvaluateWithGradient(coordinates, 1, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(objective, 1.576, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.048, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 2.0, 1e-5);\n\n  objective = lmnnfn.EvaluateWithGradient(coordinates, 2, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(objective, 1.576, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.048, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 2.0, 1e-5);\n\n  objective = lmnnfn.EvaluateWithGradient(coordinates, 3, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(objective, 1.576, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.048, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 2.0, 1e-5);\n\n  objective = lmnnfn.EvaluateWithGradient(coordinates, 4, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(objective, 1.576, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.048, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 2.0, 1e-5);\n\n  objective = lmnnfn.EvaluateWithGradient(coordinates, 5, gradient, 1);\n\n  BOOST_REQUIRE_CLOSE(objective, 1.576, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(gradient(0, 0), -0.048, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(0, 1), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 0), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1, 1), 2.0, 1e-5);\n}\n\n// Check that final objective value using SGD optimizer is optimal.\nBOOST_AUTO_TEST_CASE(LMNNSGDSimpleDatasetTest)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset        = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  LMNN<> lmnn(dataset, labels, 1);\n\n  arma::mat outputMatrix;\n  lmnn.LearnDistance(outputMatrix);\n\n  // Ensure that the objective function is better now.\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.6, 1);\n\n  double initObj = lmnnfn.Evaluate(arma::eye<arma::mat>(2, 2));\n  double finalObj = lmnnfn.Evaluate(outputMatrix);\n\n  // finalObj must be less than initObj.\n  BOOST_REQUIRE_LT(finalObj, initObj);\n}\n\n// Check that final objective value using L-BFGS optimizer is optimal.\nBOOST_AUTO_TEST_CASE(LMNNLBFGSSimpleDatasetTest)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset        = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  LMNN<SquaredEuclideanDistance, L_BFGS> lmnn(dataset, labels, 1);\n\n  arma::mat outputMatrix;\n  lmnn.LearnDistance(outputMatrix);\n\n  // Ensure that the objective function is better now.\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.6, 1);\n\n  double initObj = lmnnfn.Evaluate(arma::eye<arma::mat>(2, 2));\n  double finalObj = lmnnfn.Evaluate(outputMatrix);\n\n  // finalObj must be less than initObj.\n  BOOST_REQUIRE_LT(finalObj, initObj);\n}\n\ndouble KnnAccuracy(const arma::mat& dataset,\n                   const arma::Row<size_t>& labels,\n                   const size_t k)\n{\n  arma::Row<size_t> uniqueLabels = arma::unique(labels);\n\n  arma::Mat<size_t> neighbors;\n  arma::mat distances;\n\n  neighbor::KNN knn;\n\n  knn.Train(dataset);\n  knn.Search(k, neighbors, distances);\n\n  // Keep count.\n  size_t count = 0.0;\n\n  for (size_t i = 0; i < dataset.n_cols; i++)\n  {\n    arma::vec Map;\n    Map.zeros(uniqueLabels.n_cols);\n\n    for (size_t j = 0; j < k; j++)\n      Map(labels(neighbors(j, i))) +=\n          1 / std::pow(distances(j, i) + 1, 2);\n\n    size_t index = arma::conv_to<size_t>::from(arma::find(Map\n        == arma::max(Map)));\n\n    // Increase count if labels match.\n    if (index == labels(i))\n        count++;\n  }\n\n  // return accuracy.\n  return ((double) count / dataset.n_cols) * 100;\n}\n\n// Check that final accuracy is greater than initial accuracy on\n// simple dataset.\nBOOST_AUTO_TEST_CASE(LMNNAccuracyTest)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset        = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  // Taking k = 3 as the case of k = 1 can be easily observed.\n  double initAccuracy = KnnAccuracy(dataset, labels, 3);\n\n  LMNN<> lmnn(dataset, labels, 2);\n\n  arma::mat outputMatrix;\n  lmnn.LearnDistance(outputMatrix);\n\n  double finalAccuracy = KnnAccuracy(outputMatrix * dataset, labels, 3);\n\n  // finalObj must be less than initObj.\n  BOOST_REQUIRE_LT(initAccuracy, finalAccuracy);\n\n  // Since this is a very simple dataset final accuracy should be around 100%.\n  BOOST_REQUIRE_CLOSE(finalAccuracy, 100.0, 1e-5);\n}\n\n// Check that accuracy while learning square distance matrix is the same as when\n// we are learning low rank matrix.  I'm ok if this passes only once out of\n// three tries.\nBOOST_AUTO_TEST_CASE(LMNNLowRankAccuracyLBFGSTest)\n{\n  bool success = false;\n  for (size_t trial = 0; trial < 3; ++trial)\n  {\n    arma::mat dataPart1;\n    dataPart1.randn(5, 50);\n\n    arma::Row<size_t> labelsPart1(50);\n    labelsPart1.fill(0);\n\n    arma::mat dataPart2;\n    dataPart2.randn(5, 50);\n\n    arma::Row<size_t> labelsPart2(50);\n    labelsPart2.fill(1);\n\n    // Generate ordering.\n    arma::uvec ordering = arma::shuffle(arma::linspace<arma::uvec>(0, 99, 100));\n\n    // Generate datasets.\n    arma::mat dataset = join_rows(dataPart1, dataPart2);\n    dataset = dataset.cols(ordering);\n\n    // Generate labels.\n    arma::Row<size_t> labels = join_rows(labelsPart1, labelsPart2);\n    labels = labels.cols(ordering);\n\n    LMNN<SquaredEuclideanDistance, L_BFGS> lmnn(dataset, labels, 1);\n\n    // Learn a square matrix.\n    arma::mat outputMatrix;\n    lmnn.LearnDistance(outputMatrix);\n\n    double acc1 = KnnAccuracy(outputMatrix * dataset, labels, 1);\n\n    // Learn a low rank matrix.\n    outputMatrix = arma::randu(4, 5);\n    lmnn.LearnDistance(outputMatrix);\n\n    double acc2 = KnnAccuracy(outputMatrix * dataset, labels, 1);\n\n    // We keep the tolerance very high.  We need to ensure the accuracy drop\n    // isn't any more than 10%.\n    success = ((acc1 - acc2) <= 10.0);\n    if (success)\n      break;\n  }\n\n  BOOST_REQUIRE_EQUAL(success, true);\n}\n\n// Check that accuracy while learning square distance matrix is the same as when\n// we are learning low rank matrix.  I'm ok if this passes only once out of\n// three tries.\nBOOST_AUTO_TEST_CASE(LMNNLowRankAccuracyTest)\n{\n  bool success = false;\n  for (size_t trial = 0; trial < 3; ++trial)\n  {\n    arma::mat dataPart1;\n    dataPart1.randn(5, 50);\n\n    arma::Row<size_t> labelsPart1(50);\n    labelsPart1.fill(0);\n\n    arma::mat dataPart2;\n    dataPart2.randn(5, 50);\n\n    arma::Row<size_t> labelsPart2(50);\n    labelsPart2.fill(1);\n\n    // Generate ordering.\n    arma::uvec ordering = arma::shuffle(arma::linspace<arma::uvec>(0, 99, 100));\n\n    // Generate datasets.\n    arma::mat dataset = join_rows(dataPart1, dataPart2);\n    dataset = dataset.cols(ordering);\n\n    // Generate labels.\n    arma::Row<size_t> labels = join_rows(labelsPart1, labelsPart2);\n    labels = labels.cols(ordering);\n\n    LMNN<> lmnn(dataset, labels, 1);\n\n    // Learn a square matrix.\n    arma::mat outputMatrix;\n    lmnn.LearnDistance(outputMatrix);\n\n    double acc1 = KnnAccuracy(outputMatrix * dataset, labels, 1);\n\n    // Learn a low rank matrix.\n    outputMatrix = arma::randu(4, 5);\n    lmnn.LearnDistance(outputMatrix);\n\n    double acc2 = KnnAccuracy(outputMatrix * dataset, labels, 1);\n\n    // We keep the tolerance very high.  We need to ensure the accuracy drop\n    // isn't any more than 10%.\n    success = ((acc1 - acc2) <= 10.0);\n    if (success)\n      break;\n  }\n\n  BOOST_REQUIRE_EQUAL(success, true);\n}\n\n// Check that accuracy while learning square distance matrix is the same as when\n// we are learning low rank matrix.  I'm ok if this passes only once out of\n// five tries, since BBSGD seems to have a harder time converging.\n/*\nBOOST_AUTO_TEST_CASE(LMNNLowRankAccuracyBBSGDTest)\n{\n  bool success = false;\n  for (size_t trial = 0; trial < 5; ++trial)\n  {\n    arma::mat dataPart1;\n    dataPart1.randn(5, 50);\n\n    arma::Row<size_t> labelsPart1(50);\n    labelsPart1.fill(0);\n\n    arma::mat dataPart2;\n    dataPart2.randn(5, 50);\n\n    arma::Row<size_t> labelsPart2(50);\n    labelsPart2.fill(1);\n\n    // Generate ordering.\n    arma::uvec ordering = arma::shuffle(arma::linspace<arma::uvec>(0, 99, 100));\n\n    // Generate datasets.\n    arma::mat dataset = join_rows(dataPart1, dataPart2);\n    dataset = dataset.cols(ordering);\n\n    // Generate labels.\n    arma::Row<size_t> labels = join_rows(labelsPart1, labelsPart2);\n    labels = labels.cols(ordering);\n\n    LMNN<SquaredEuclideanDistance, BigBatchSGD<>> lmnn(dataset, labels, 1);\n\n    // Learn a square matrix.\n    arma::mat outputMatrix;\n    lmnn.LearnDistance(outputMatrix);\n\n    double acc1 = KnnAccuracy(outputMatrix * dataset, labels, 1);\n\n    // Learn a low rank matrix.\n    outputMatrix = arma::randu(4, 5);\n    lmnn.LearnDistance(outputMatrix);\n\n    double acc2 = KnnAccuracy(outputMatrix * dataset, labels, 1);\n    if (acc2 < 5)\n      std::cout << \"super fail\\n\" << outputMatrix << std::endl;\n\n    // We keep the tolerance very high.  We need to ensure the accuracy drop\n    // isn't any more than 10%.\n    success = ((acc1 - acc2) <= 10.0);\n    if (success)\n      break;\n  }\n\n  BOOST_REQUIRE_EQUAL(success, true);\n}\n*/\n\n// Comprehensive gradient tests by Marcus Edel & Ryan Curtin.\n\n// Simple numerical gradient checker.\ntemplate<class FunctionType>\ndouble CheckGradient(FunctionType& function,\n                     arma::mat& coordinates,\n                     const double eps = 1e-7)\n{\n  // Get gradients for the current parameters.\n  arma::mat orgGradient, gradient, estGradient;\n  function.Gradient(coordinates, orgGradient);\n\n  estGradient = arma::zeros(orgGradient.n_rows, orgGradient.n_cols);\n\n  // Compute numeric approximations to gradient.\n  for (size_t i = 0; i < orgGradient.n_elem; ++i)\n  {\n    double tmp = coordinates(i);\n\n    // Perturb parameter with a positive constant and get costs.\n    coordinates(i) += eps;\n    double costPlus = function.Evaluate(coordinates);\n\n    // Perturb parameter with a negative constant and get costs.\n    coordinates(i) -= (2 * eps);\n    double costMinus = function.Evaluate(coordinates);\n\n    // Restore the parameter value.\n    coordinates(i) = tmp;\n\n    // Compute numerical gradients using the costs calculated above.\n    estGradient(i) = (costPlus - costMinus) / (2 * eps);\n  }\n\n  // Estimate error of gradient.\n  return arma::norm(orgGradient - estGradient) /\n      arma::norm(orgGradient + estGradient);\n}\n\nBOOST_AUTO_TEST_CASE(LMNNFunctionGradientTest)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset        = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.6, 1);\n\n  // 10 trials with random positions.\n  for (size_t i = 0; i < 10; ++i)\n  {\n    arma::mat coordinates(2, 2, arma::fill::randn);\n    CheckGradient(lmnnfn, coordinates);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(LMNNFunctionGradientTest2)\n{\n  // Useful but simple dataset with six points and two classes.\n  arma::mat dataset        = \"-0.1 -0.1 -0.1  0.1  0.1  0.1;\"\n                             \" 1.0  0.0 -1.0  1.0  0.0 -1.0 \";\n  arma::Row<size_t> labels = \" 0    0    0    1    1    1   \";\n\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.6, 1);\n\n  // 10 trials with random positions.\n  for (size_t i = 0; i < 10; ++i)\n  {\n    arma::mat coordinates(2, 2, arma::fill::randu);\n    CheckGradient(lmnnfn, coordinates);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(LMNNFunctionGradientTest3)\n{\n  arma::mat dataset;\n  arma::Row<size_t> labels;\n  data::Load(\"iris.csv\", dataset);\n  data::Load(\"iris_labels.txt\", labels);\n\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.6, 1);\n\n  // 10 trials with random positions.\n  for (size_t i = 0; i < 10; ++i)\n  {\n    arma::mat coordinates(dataset.n_rows, dataset.n_rows, arma::fill::randn);\n    CheckGradient(lmnnfn, coordinates);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(LMNNFunctionGradientTest4)\n{\n  arma::mat dataset;\n  arma::Row<size_t> labels;\n  data::Load(\"iris.csv\", dataset);\n  data::Load(\"iris_labels.txt\", labels);\n\n  LMNNFunction<> lmnnfn(dataset, labels, 1, 0.6, 1);\n\n  // 10 trials with random positions.\n  for (size_t i = 0; i < 10; ++i)\n  {\n    arma::mat coordinates(dataset.n_rows, dataset.n_rows, arma::fill::randu);\n    CheckGradient(lmnnfn, coordinates);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "288257ae8d26d76e182026ed7e8f7601d5d94c69", "size": 22747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/lmnn_test.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/lmnn_test.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/lmnn_test.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8643147897, "max_line_length": 80, "alphanum_fraction": 0.6528773025, "num_tokens": 7425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5839544340183817}}
{"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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\ntemplate <typename Matrix>\ninline void strided_laplacian_setup(Matrix& A, unsigned m, unsigned n)\n{\n    A.change_dim(2*m*n, 2*m*n);\n    set_to_zero(A);\n    mtl::mat::inserter<Matrix>      ins(A, 5);\n\n    for (unsigned i= 0; i < m; i++)\n\tfor (unsigned j= 0; j < n; j++) {\n\t    typename mtl::Collection<Matrix>::value_type four(4.0), minus_one(-1.0);\n\t    unsigned row= 2 * (i * n + j);\n\t    ins(row, row) << four;\n\t    if (j < n-1) ins(row, row+2) << minus_one;\n\t    if (i < m-1) ins(row, row+2*n) << minus_one;\n\t    if (j > 0) ins(row, row-2) << minus_one;\n\t    if (i > 0) ins(row, row-2*n) << minus_one;\n\t}\n    for (unsigned i= 1; i < num_rows(A); i+= 2)\n\tins(i, i) << 2;\n} \n\n\nint main()\n{\n    using mtl::srange; using mtl::imax;\n    // For a more realistic example set sz to 1000 or larger\n    const int size = 3, N = 2 * size * size; \n\n    typedef mtl::compressed2D<double>  matrix_type;\n    typedef itl::pc::ic_0<matrix_type> ic_type;\n\n\n    mtl::compressed2D<double>          A;\n    strided_laplacian_setup(A, size, size);\n    mtl::io::tout << \"A (merged diagonal and Laplace) is\\n\" << A << '\\n';\n\n    mtl::dense_vector<bool> tags= make_tag_vector(N, srange(0, imax, 2));\n    itl::pc::sub_matrix_pc<ic_type, matrix_type> P(tags, A);\n\n    mtl::dense_vector<double>          x(N, 1.0), b(N);\n    \n    b = A * x;\n    x= 0;\n\n    itl::cyclic_iteration<double> iter(b, N, 1.e-6, 0.0, 3);\n    cg(A, x, b, P, iter);\n     \n    // Test if adjoint works\n    x= 0;\n    itl::cyclic_iteration<double> iter2(b, N, 1.e-6, 0.0, 3);\n    bicg(A, x, b, P, iter2);\n\n    return 0;\n}\n", "meta": {"hexsha": "5c70306e9f5b759d433c3382dc8d66dc22d47eb1", "size": 2084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/sub_matrix_pc_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/itl/test/sub_matrix_pc_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/itl/test/sub_matrix_pc_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 29.7714285714, "max_line_length": 94, "alphanum_fraction": 0.603646833, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5839544214806544}}
{"text": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/gamma.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <simd_test.hpp>\n\nnamespace bs = boost::simd;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid limit_test(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  STF_ULP_EQUAL (bs::gamma(p_t(1))            , p_t(1), 0.5);\n  STF_IEEE_EQUAL(bs::gamma(p_t(0))            , p_t(bs::Inf<T>())        );\n  STF_IEEE_EQUAL(bs::gamma(p_t(bs::Inf<T>())) , bs::Inf<p_t>());\n  STF_IEEE_EQUAL(bs::gamma(p_t(bs::Minf<T>())), p_t(bs::Nan<T>())        );\n}\n\nSTF_CASE_TPL(\"Check gamma limit cases\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n  limit_test<T, N>($);\n  limit_test<T, N/2>($);\n  limit_test<T, N*2>($);\n}\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], b[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : -T(i);\n    b[i] = bs::gamma(a1[i]) ;\n  }\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n\n  STF_ULP_EQUAL(bs::gamma(aa1), bb, 0.5);\n}\n\nSTF_CASE_TPL(\"Check gamma on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n   test<T, N>($);\n   test<T, N/2>($);\n   test<T, N*2>($);\n}\n", "meta": {"hexsha": "b8a61f60d63293c63935ae3be6d64d06a778e38f", "size": 1712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/gamma.cpp", "max_stars_repo_name": "timblechmann/boost.simd", "max_stars_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "test/function/simd/gamma.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/simd/gamma.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 28.0655737705, "max_line_length": 100, "alphanum_fraction": 0.5344626168, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5839544051956299}}
{"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": "//  Copyright (c) 2015 Boost.Test team\n//  Distributed under the Boost Software License, Version 1.0.\n//  (See accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n\n//  See http://www.boost.org/libs/test for the library home page.\n\n//[example_code\n#define BOOST_TEST_MODULE tolerance_04\n#include <boost/test/included/unit_test.hpp>\n#include <boost/rational.hpp>\nnamespace utf = boost::unit_test;\nnamespace tt = boost::test_tools;\n\nnamespace boost { namespace math { namespace fpc {\n\n  template <typename I>\n  struct tolerance_based< rational<I> > : boost::true_type{};\n  \n} } }\n\ntypedef boost::rational<int> ratio;\n\nBOOST_AUTO_TEST_CASE(test1, * utf::tolerance(ratio(1, 1000)))\n{\n  ratio x (1002, 100); // 10.02\n  ratio y (1001, 100); // 10.01\n  ratio z (1000, 100); // 10.00\n  \n  BOOST_TEST(x == y);  // irrelevant diff by default\n  BOOST_TEST(x == y, tt::tolerance(ratio(1, 2000)));\n  \n  BOOST_TEST(x != z);  // relevant diff by default\n  BOOST_TEST(x != z, tt::tolerance(ratio(2, 1000)));\n}\n//]\n", "meta": {"hexsha": "a8008c622e38baf866a74efc1e360af850fff103", "size": 1032, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/boost_1_71_0/libs/test/doc/examples/tolerance_04.run-fail.cpp", "max_stars_repo_name": "anonymouscode1/djxperf", "max_stars_repo_head_hexsha": "b6073a761753aa7a6247f2618977ca3a2633e78a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "thirdparty/boost_1_71_0/libs/test/doc/examples/tolerance_04.run-fail.cpp", "max_issues_repo_name": "anonymouscode1/djxperf", "max_issues_repo_head_hexsha": "b6073a761753aa7a6247f2618977ca3a2633e78a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T01:39:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:18:40.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/test/doc/examples/tolerance_04.run-fail.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 27.8918918919, "max_line_length": 65, "alphanum_fraction": 0.6879844961, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5839029834684734}}
{"text": "#define BOOST_TEST_DYN_LINK\n#include <Eigen/Dense>\n#include <boost/test/unit_test.hpp>\n#include \"matrixIO.hpp\"\n\nstruct matrixIOFixture {\n  matrixIOFixture()\n  {\n    A = Eigen::MatrixXd(3, 3);\n    A << 1, 2, 3,\n        4, 5, 6,\n        7, 8, 9;\n  }\n\n  Eigen::MatrixXd A;\n  int             matrix_size                = 3;\n  std::string     valid_matrix_file          = \"../data/matrix_valid.csv\";\n  std::string     invalid_format_matrix_file = \"../data/matrix_invalid_format.csv\";\n  std::string     invalid_cols_matrix_file   = \"../data/matrix_invalid_cols.csv\";\n  std::string     invalid_rows_matrix_file   = \"../data/matrix_invalid_rows.csv\";\n};\n\nBOOST_FIXTURE_TEST_SUITE(matrixIOTests, matrixIOFixture)\n\nBOOST_AUTO_TEST_CASE(open_valid_data)\n{\n  Eigen::MatrixXd read = matrixIO::openData(valid_matrix_file, matrix_size);\n  BOOST_TEST(read == A);\n}\n\nBOOST_AUTO_TEST_CASE(open_invalid_format_data)\n{\n  BOOST_REQUIRE_THROW(matrixIO::openData(invalid_format_matrix_file, matrix_size), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(open_invalid_rows_data)\n{\n  BOOST_REQUIRE_THROW(matrixIO::openData(invalid_rows_matrix_file, matrix_size), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(open_invalid_cols_data)\n{\n  BOOST_REQUIRE_THROW(matrixIO::openData(invalid_cols_matrix_file, matrix_size), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4ba74decfb428fe869c33ed0f221f80c970b3566", "size": 1338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/matrixIOTest.cpp", "max_stars_repo_name": "qwach/testing-boost-exercise", "max_stars_repo_head_hexsha": "2c6e0337b59b1d0371b9aa2eebda6422d7215bc8", "max_stars_repo_licenses": ["MIT"], "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/matrixIOTest.cpp", "max_issues_repo_name": "qwach/testing-boost-exercise", "max_issues_repo_head_hexsha": "2c6e0337b59b1d0371b9aa2eebda6422d7215bc8", "max_issues_repo_licenses": ["MIT"], "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/matrixIOTest.cpp", "max_forks_repo_name": "qwach/testing-boost-exercise", "max_forks_repo_head_hexsha": "2c6e0337b59b1d0371b9aa2eebda6422d7215bc8", "max_forks_repo_licenses": ["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.4680851064, "max_line_length": 103, "alphanum_fraction": 0.7331838565, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5839029782920013}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// monomials_horner::example::monomials.cpp                                  //\n//                                                                           //\n//  (C) Copyright 2009 Erwann Rogard                                         //\n//  Use, modification and distribution are subject to the                    //\n//  Boost Software License, Version 1.0. (See accompanying file              //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#include <algorithm>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/range.hpp>\n#include <boost/monomials_horner/monomials.hpp>\n#include <libs/monomials_horner/example/monomials.h>\n\nvoid example_monomials(std::ostream& out){\n    out << \"-> example_monomials\" << std::endl;\n\n    using namespace boost;\n    using namespace monomials_horner;\n\n    typedef std::vector<double> vars_type;\n    typedef monomials<vars_type> monoms_type;\n\n    unsigned max_d = 5;\n    unsigned max_p = 5;    vars_type vars;\n    {\n        using namespace boost::assign; \n        vars += 0.0,1.0,2.0,3.0,4.0;\n    }\n\n    for(unsigned d = 1; d<max_d; d++){\n        out << \" -> d=\" << d << std::endl;\n        vars_type::iterator e = boost::begin(vars);\n        std::advance(e,d);\n        vars_type sub;\n        copy(boost::begin(vars),e,back_inserter(sub));\n        BOOST_ASSERT(boost::size(sub)-d==0);\n\n        for(unsigned int p = 1; p<max_p; p++){\n            out << \"  ->p=\" << p << std::endl;\n            //out << boost::math::binomial_coefficient<double>(p+d,d)\n            //<< std::endl;\n\n            monoms_type monoms;\n\n            monoms(sub,p);\n            copy(\n                boost::begin(monoms()),\n                boost::end(monoms()),\n                std::ostream_iterator<double>(out,\" \")\n            );\n            out << \"  <-\" << std::endl;\n        }\n            out << \" <-\" << std::endl;\n    }\n    out << \"<-\" << std::endl;\n}\n", "meta": {"hexsha": "564a79f0bb31e34667dd1a7f4b515061861daa5a", "size": 2118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "monomials_horner/libs/monomials_horner/example/monomials.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": "monomials_horner/libs/monomials_horner/example/monomials.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": "monomials_horner/libs/monomials_horner/example/monomials.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": 35.8983050847, "max_line_length": 79, "alphanum_fraction": 0.4754485364, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5839029782920013}}
{"text": "/* \n * File:   geometry.hpp\n * Copyright (C) 2014  K M Masum Habib <masum.habib@gmail.com>\n *\n * Created on February 3, 2014, 1:45 PM\n */\n\n#ifndef GEOMETRY_HPP\n#define\tGEOMETRY_HPP\n\n#include \"utils/std.hpp\"\n#include \"utils/Printable.hpp\"\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/ring.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/index/rtree.hpp>\n#include <boost/geometry/strategies/cartesian/point_in_poly_franklin.hpp>\n\n#include <vector>\n#include <algorithm>\n\nnamespace maths{\nnamespace geometry{\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\nusing namespace utils::stds;\nusing utils::Printable;\n\ntypedef bg::model::point<double, 2, bg::cs::cartesian> point;\ntypedef bg::model::box<point> box;\ntypedef bg::model::ring<point> ring;\ntypedef bg::model::polygon<point, false, false> polygon; // ccw, open polygon\ntypedef polygon::ring_type polyring;\ntypedef bg::strategy::within::franklin<point, point, double> stwithin;\n\n/*\n * Simple Quadrilateral\n */\nstruct SimpleQuadrilateral: public Printable{\n    point lb;\n    point rb;\n    point rt;\n    point lt;\n\n    SimpleQuadrilateral(const point &lb, const point &rb, const point &rt, \n    const point &lt, const string &prefix = \"\"):Printable(\" \" + prefix), \n        lb(lb), rb(rb), rt(rt), lt(lt){\n        \n        // Commented out since it is buggy\n        // correct();\n    }    \n    \n    // sort the points.\n    // @TODO: Does not alway work. Fix bug. \n    void correct(){\n        using std::sort;\n        using std::vector;\n        vector<point> p;\n        p.push_back(lb);\n        p.push_back(rb);\n        p.push_back(rt);\n        p.push_back(lt);\n        \n        sort(p.begin(), p.end(), OnRight());\n        \n        if (p[0].get<1>() < p[1].get<1>()){\n            lb = p[0];\n            lt = p[1];\n        }else{\n            lb = p[1];\n            lt = p[0];            \n        }\n        \n        if (p[2].get<1>() < p[3].get<1>()){\n            rb = p[2];\n            rt = p[3];\n        }else{\n            rb = p[3];\n            rt = p[2];            \n        }        \n    }\n    \n    \n    \n    virtual string toString() const{\n        stringstream out;\n        out.precision(3);\n        out << \"(\" << lb.get<0>() << \" \" << lb.get<1>() << \", \"\n                   << rb.get<0>() << \" \" << rb.get<1>() << \", \"\n                   << rt.get<0>() << \" \" << rt.get<1>() << \", \"\n                   << lt.get<0>() << \" \" << lt.get<1>() << \")\";\n        return out.str();\n    }\n    \nprotected:\n    struct OnRight{\n        bool operator()(const point &p1, const point &p2){\n            return (p1.get<0>() < p2.get<0>());\n        }\n    };\n};\n\ntypedef SimpleQuadrilateral squadrilateral;\ntypedef SimpleQuadrilateral quadrilateral;\n\n\n}\n}\n#endif\t/* GEOMETRY_HPP */\n\n", "meta": {"hexsha": "598773b79ce0ff385ebe5ebebda0e19b53baf3c0", "size": 2875, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/maths/geometry.hpp", "max_stars_repo_name": "mirzaelahi/quest", "max_stars_repo_head_hexsha": "c433175802014386c2b1bf3c8932cd66b0d37c8e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-04-04T20:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T02:08:22.000Z", "max_issues_repo_path": "lib/include/maths/geometry.hpp", "max_issues_repo_name": "mirzaelahi/quest", "max_issues_repo_head_hexsha": "c433175802014386c2b1bf3c8932cd66b0d37c8e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2016-10-06T03:00:24.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-30T06:43:32.000Z", "max_forks_repo_path": "lib/include/maths/geometry.hpp", "max_forks_repo_name": "mirzaelahi/quest", "max_forks_repo_head_hexsha": "c433175802014386c2b1bf3c8932cd66b0d37c8e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-03T04:09:25.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-03T04:09:25.000Z", "avg_line_length": 25.0, "max_line_length": 77, "alphanum_fraction": 0.5460869565, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430353105599, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5839029643003528}}
{"text": "// Filename: dot_example.cpp (part of MTL4)\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    typedef std::complex<double>  cdouble;\n    dense_vector<cdouble>         v(10000), x(10, cdouble(3, 2));\n    dense_vector<double>          w(10000);\n\n    for (unsigned i= 0; i < size(v); i++)\n\tv[i]= cdouble(i+1, 10000-i), w[i]= 2 * i + 2;\n\n    std::cout << \"dot(v, w) is \" << dot(v, w)<< \"\\n\";\n    \n    std::cout << \"dot<6>(v, w) is \" <<  dot<6>(v, w)<< \"\\n\";\n\n    std::cout << \"dot_real<6>(v, w) is \" <<  dot_real<6>(v, w)<< \"\\n\";\n    \n    std::cout << \"conj(x) is \" <<  mtl::conj(x)<< \"\\n\"; // ADL doesn't work here in g++ 4.4\n\n    return 0;\n}\n\n", "meta": {"hexsha": "c8f1c3a35ccd1c61053f03a45f3761091628fa76", "size": 704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/dot_example.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/dot_example.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/dot_example.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 25.1428571429, "max_line_length": 91, "alphanum_fraction": 0.5184659091, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5839029627625847}}
{"text": "/*=================================================================================\n *\t                    Copyleft! 2018 William Yu\n *          Some rights reserved\uff1aCC(creativecommons.org)BY-NC-SA\n *                      Copyleft! 2018 William Yu\n *      \u7248\u6743\u90e8\u5206\u6240\u6709\uff0c\u9075\u5faaCC(creativecommons.org)BY-NC-SA\u534f\u8bae\u6388\u6743\u65b9\u5f0f\u4f7f\u7528\n *\n * Filename                : \n * Description             : \n * Reference               : \n * Programmer(s)           : William Yu, windmillyucong@163.com\n * Company                 : HUST, DMET\u56fd\u5bb6\u91cd\u70b9\u5b9e\u9a8c\u5ba4FOCUS\u56e2\u961f\n * Modification History\t   : ver1.0, 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// \u50cf\u7d20\u5750\u6807\u8f6c\u76f8\u673a\u5f52\u4e00\u5316\u5750\u6807\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    //-- \u5185\u53c2\u77e9\u9635 \n    //--\u8c03\u53c2\uff1a\u76f8\u673a\u5185\u53c2--\n    //        | fx,  0, cx, | cx\u4e3b\u70b9\u504f\u79fb\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    //-- \u8bfb\u53d6\u56fe\u50cf\n    Mat img_1 = imread ( argv[1], CV_LOAD_IMAGE_COLOR );\n    Mat img_2 = imread ( argv[2], CV_LOAD_IMAGE_COLOR );\n\n    vector<KeyPoint> keypoints_1, keypoints_2;\n    vector<DMatch> matches;\n    find_feature_matches ( img_1, img_2, keypoints_1, keypoints_2, matches );\n    cout<<\"\u4e00\u5171\u627e\u5230\u4e86\"<<matches.size() <<\"\u7ec4\u5339\u914d\u70b9\"<<endl;\n\n    // \u5efa\u7acb3D\u70b9\n    Mat depth1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED );       // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n    Mat depth2 = imread ( argv[4], CV_LOAD_IMAGE_UNCHANGED );       // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\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 //\u6df1\u5ea6\u503c\u4e3a0\uff0c\u65e0\u6cd5\u4f7f\u7528\n            continue;\n        Point2d p1 = pixel2cam ( keypoints_1[m.queryIdx].pt, K );//\u662f\u6d4b\u8bd5\u56fe\u50cf\u7684\u7279\u5f81\u70b9\u63cf\u8ff0\u5b50\uff08descriptor\uff09\u7684\u4e0b\u6807\uff0c\u540c\u65f6\u4e5f\u662f\u63cf\u8ff0\u7b26\u5bf9\u5e94\u7279\u5f81\u70b9\uff08keypoint)\u7684\u4e0b\u6807\u3002\n        Point2d p2 = pixel2cam ( keypoints_2[m.trainIdx].pt, K );//\u662f\u6837\u672c\u56fe\u50cf\u7684\u7279\u5f81\u70b9\u63cf\u8ff0\u5b50\u7684\u4e0b\u6807\uff0c\u540c\u6837\u4e5f\u662f\u76f8\u5e94\u7684\u7279\u5f81\u70b9\u7684\u4e0b\u6807\u3002\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 \u70b9\u5bf9: \"<<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    * \u5219\u6709pts2 = R_inv*pts1 - R_inv*t\n    * \u5bf9\u5e94pts2 = R`*pts1 + t`\n    * \u5373\u9006\u8fd0\u52a8R` = R_inv\n    *        t` = - R_inv*t\n    * Notice:\u65cb\u8f6c\u77e9\u9635R\u4e3a\u6b63\u4ea4\u77e9\u9635\uff0c\n    * \u6240\u6709\u53c8\u6709 R^(-1) = R^T\uff0c\u9006\u7b49\u4e8e\u8f6c\u7f6e\n    --------------------------------------------------------------*/\n    cout<<\"\u9006\u8fd0\u52a8R\uff1aR` = R_inv = \"<<R.t() <<endl;   //Mat.t()\u4e3a\u77e9\u9635\u6c42\u8f6c\u7f6e\n    //cout<<\"\u9006\u8fd0\u52a8R\uff1aR` = R_inv = \"<<R.inv() <<endl;  //Mat.inv()\u4e3a\u77e9\u9635\u6c42\u9006 \n    cout<<\"\u9006\u8fd0\u52a8t\uff1at` = - R_inv*t = \"<<-R.t() *t <<endl;\n\n    cout<<\"---------------------------------------------\"<<endl;\n    //--\u6821\u9a8c5\u7ec4 p1 = R*p2 + t  \u548c  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 \u7279\u5f81\u70b9\u5339\u914d\u4e0e\u7b5b\u9009\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    //-- \u521d\u59cb\u5316\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]:\u68c0\u6d4b Oriented FAST \u89d2\u70b9\u4f4d\u7f6e\n    detector->detect ( img_1,keypoints_1 );\n    detector->detect ( img_2,keypoints_2 );\n\n    //--[2]:\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97 BRIEF \u63cf\u8ff0\u5b50\n    descriptor->compute ( img_1, keypoints_1, descriptors_1 );\n    descriptor->compute ( img_2, keypoints_2, descriptors_2 );\n    \n    //\u7ed8\u5236\u7279\u5f81\u70b9\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\u7279\u5f81\u70b9\u6570\"<<keypoints_1.size() <<endl;//500\u4e2a\u7279\u5f81\u70b9\n    cout<<\"Img2\u7279\u5f81\u70b9\u6570\"<<keypoints_2.size() <<endl;\n    \n    //--[3]:\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n    vector<DMatch> matches;\n    //BFMatcher matcher ( NORM_HAMMING );\n    matcher->match ( descriptors_1, descriptors_2, matches );\n    cout<<\"\u521d\u6b65\u5339\u914d\"<<matches.size() <<\"\u5bf9\u5339\u914d\u70b9\"<<endl; //500\u5bf9\u5339\u914d\n\n    //--[4]:\u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n    //--\u7b5b\u9009\u8981\u6c42\uff1a1.\u786e\u4fdd\u90fd\u662f\u6b63\u786e\u5339\u914d\uff0c\u5220\u53bb\u9519\u8bef\u5339\u914d\n    //          2.\u786e\u4fdd\u6b63\u786e\u5339\u914d\u7684\u524d\u63d0\u4e0b\uff0c\u4fdd\u8bc1\u70b9\u5bf9\u6570\u8db3\u591f\u591a\n\n    //--\u8c03\u53c2\uff1a\u7b5b\u9009\u9608\u503c--\n    double min_dist=10000, max_dist=0;\n    //\u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        double dist = matches[i].distance;\n        if ( dist < min_dist ) min_dist = dist;//\u6700\u77ed\u8ddd\u79bb\uff0c\u6700\u76f8\u4f3c\n        if ( dist > max_dist ) max_dist = dist;//\u6700\u957f\u8ddd\u79bb\uff0c\u6700\u4e0d\u76f8\u4f3c\n    }\n    printf ( \"-- Max dist : %f \\n\", max_dist );\n    printf ( \"-- Min dist : %f \\n\", min_dist );\n\n    //--\u8c03\u53c2\uff1a\u7b5b\u9009\u9608\u503c--\n    //\u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\n    //\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        if ( matches[i].distance <= max ( 2*min_dist, 30.0 ) )\n        {\n            good_matches.push_back ( matches[i] );\n        }\n    }\n\n    //--TODO\uff1a\u8c03\u53c2\uff1a\u9010\u70b9\u68c0\u67e5--\n\n\n    //--[5]:\u7ed8\u5236\u5339\u914d\u7ed3\u679c\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 \u50cf\u7d20\u5750\u6807\u8f6c\u76f8\u673a\u5f52\u4e00\u5316\u5750\u6807\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   \u6c42\u89e3R\u3001t\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": "/*\n * Copyright (c) 2018 Jonas Deyson\n *\n * This software is released under the MIT License.\n *\n * You should have received a copy of the MIT License\n * along with this program. If not, see <https://opensource.org/licenses/MIT>\n */\n\n#include \"SceneReader.h\"\n#include \"exprtk.hpp\"\n#include <QTextStream>\n#include <QDebug>\n#include <QFile>\n#include <tuple>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nusing ExpSymbolTable = exprtk::symbol_table<float>;\nusing ExpExpression = exprtk::expression<float>;\nusing ExpParser = exprtk::parser<float>;\nusing ExpSymbol = ExpParser::dependent_entity_collector::symbol_t;\nusing ExpError = exprtk::parser_error::type;\nusing ExpPtr = std::unique_ptr<ExpExpression>;\n\n\n//=====================================================================\n//                        AUXILIARY FUNCTIONS\n//=====================================================================\nnamespace\n{\n\nvoid extractInfo(const std::string infoStr, int& width, int& height, int& spp)\n{\n    ExpSymbolTable symbol_table;\n    float w = 0.f, h = 0.f;\n    float spp_f = 0.f;\n    symbol_table.add_variable(\"width\", w);\n    symbol_table.add_variable(\"height\", h);\n    symbol_table.add_variable(\"spp\", spp_f);\n\n    ExpExpression expression;\n    expression.register_symbol_table(symbol_table);\n\n    ExpParser parser;\n\n    if (!parser.compile(infoStr, expression))\n    {\n        printf(\"Error: %s\\tExpression: %s\\n\",\n               parser.error().c_str(),\n               infoStr.c_str());\n\n        for (std::size_t i = 0; i < parser.error_count(); ++i)\n        {\n            ExpError error = parser.get_error(i);\n            printf(\"Error: %02d Position: %02d Type: [%s] Msg: %s Expr: %s\\n\",\n                   static_cast<int>(i),\n                   static_cast<int>(error.token.position),\n                   exprtk::parser_error::to_str(error.mode).c_str(),\n                   error.diagnostic.c_str(),\n                   infoStr.c_str());\n        }\n\n        fflush(stdout);\n    }\n\n    expression.value();\n    width = std::round(w);\n    height = std::round(h);\n    spp = std::round(spp_f);\n}\n\nstd::tuple< std::unique_ptr<ExpExpression>,\n            std::vector<RandomParameter>,\n            std::vector<Feature> >\ncompileExpression(const std::string expStr, int width, int height, int spp, float* params, float* features)\n{\n    ExpSymbolTable symbol_table;\n    symbol_table.add_constants();\n\n    symbol_table.add_constant(\"width\", width);\n    symbol_table.add_constant(\"height\", height);\n    symbol_table.add_constant(\"spp\", spp);\n\n    symbol_table.add_variable(\"IMAGE_X\", params[0]);\n    symbol_table.add_variable(\"IMAGE_Y\", params[1]);\n    symbol_table.add_variable(\"LENS_U\", params[2]);\n    symbol_table.add_variable(\"LENS_V\", params[3]);\n    symbol_table.add_variable(\"TIME\", params[4]);\n    symbol_table.add_variable(\"LIGHT_X\", params[5]);\n    symbol_table.add_variable(\"LIGHT_Y\", params[6]);\n\n    symbol_table.add_variable(\"COLOR_R\", features[COLOR_R]);\n    symbol_table.add_variable(\"COLOR_G\", features[COLOR_G]);\n    symbol_table.add_variable(\"COLOR_B\", features[COLOR_B]);\n    symbol_table.add_variable(\"DEPTH\", features[DEPTH]);\n    symbol_table.add_variable(\"DIRECT_LIGHT_R\", features[DIRECT_LIGHT_R]);\n    symbol_table.add_variable(\"DIRECT_LIGHT_G\", features[DIRECT_LIGHT_G]);\n    symbol_table.add_variable(\"DIRECT_LIGHT_B\", features[DIRECT_LIGHT_B]);\n    symbol_table.add_variable(\"WORLD_X\", features[WORLD_X]);\n    symbol_table.add_variable(\"WORLD_Y\", features[WORLD_Y]);\n    symbol_table.add_variable(\"WORLD_Z\", features[WORLD_Z]);\n    symbol_table.add_variable(\"NORMAL_X\", features[NORMAL_X]);\n    symbol_table.add_variable(\"NORMAL_Y\", features[NORMAL_Y]);\n    symbol_table.add_variable(\"NORMAL_Z\", features[NORMAL_Z]);\n    symbol_table.add_variable(\"TEXTURE_COLOR_R\", features[TEXTURE_COLOR_R]);\n    symbol_table.add_variable(\"TEXTURE_COLOR_G\", features[TEXTURE_COLOR_G]);\n    symbol_table.add_variable(\"TEXTURE_COLOR_B\", features[TEXTURE_COLOR_B]);\n    symbol_table.add_variable(\"WORLD_X_1\", features[WORLD_X_1]);\n    symbol_table.add_variable(\"WORLD_Y_1\", features[WORLD_Y_1]);\n    symbol_table.add_variable(\"WORLD_Z_1\", features[WORLD_Z_1]);\n    symbol_table.add_variable(\"NORMAL_X_1\", features[NORMAL_X_1]);\n    symbol_table.add_variable(\"NORMAL_Y_1\", features[NORMAL_Y_1]);\n    symbol_table.add_variable(\"NORMAL_Z_1\", features[NORMAL_Z_1]);\n    symbol_table.add_variable(\"TEXTURE_COLOR_R_1\", features[TEXTURE_COLOR_R_1]);\n    symbol_table.add_variable(\"TEXTURE_COLOR_G_1\", features[TEXTURE_COLOR_G_1]);\n    symbol_table.add_variable(\"TEXTURE_COLOR_B_1\", features[TEXTURE_COLOR_B_1]);\n    symbol_table.add_variable(\"WORLD_X_NS\", features[WORLD_X_NS]);\n    symbol_table.add_variable(\"WORLD_Y_NS\", features[WORLD_Y_NS]);\n    symbol_table.add_variable(\"WORLD_Z_NS\", features[WORLD_Z_NS]);\n    symbol_table.add_variable(\"NORMAL_X_NS\", features[NORMAL_X_NS]);\n    symbol_table.add_variable(\"NORMAL_Y_NS\", features[NORMAL_Y_NS]);\n    symbol_table.add_variable(\"NORMAL_Z_NS\", features[NORMAL_Z_NS]);\n    symbol_table.add_variable(\"TEXTURE_COLOR_R_NS\", features[TEXTURE_COLOR_R_NS]);\n    symbol_table.add_variable(\"TEXTURE_COLOR_G_NS\", features[TEXTURE_COLOR_G_NS]);\n    symbol_table.add_variable(\"TEXTURE_COLOR_B_NS\", features[TEXTURE_COLOR_B_NS]);\n\n    std::unique_ptr<ExpExpression> expression(new ExpExpression);\n    expression->register_symbol_table(symbol_table);\n\n    ExpParser parser;\n    parser.dec().collect_variables() = true;\n    parser.dec().collect_assignments() = true;\n\n    if (!parser.compile(expStr, *expression))\n    {\n        printf(\"Error: %s\\tExpression: %s\\n\",\n               parser.error().c_str(),\n               expStr.c_str());\n\n        for (std::size_t i = 0; i < parser.error_count(); ++i)\n        {\n            ExpError error = parser.get_error(i);\n            printf(\"Error: %02d Position: %02d Type: [%s] Msg: %s Expr: %s\\n\",\n                   static_cast<int>(i),\n                   static_cast<int>(error.token.position),\n                   exprtk::parser_error::to_str(error.mode).c_str(),\n                   error.diagnostic.c_str(),\n                   expStr.c_str());\n        }\n\n        fflush(stdout);\n    }\n\n    // Find list of used variables\n    std::deque<ExpSymbol> symbol_list;\n    parser.dec().symbols(symbol_list);\n    auto newEnd = std::remove_if(symbol_list.begin(), symbol_list.end(),\n        [](ExpSymbol& symbol)\n        { return symbol.second != ExpParser::e_st_variable; }\n    );\n    symbol_list.erase(newEnd, symbol_list.end());\n    // Create list of used random parameters from the list of used variables\n    std::vector<RandomParameter> usedParameters;\n    for (std::size_t i = 0; i < symbol_list.size(); ++i)\n    {\n        const ExpSymbol& symbol = symbol_list[i];\n        RandomParameter p;\n        if(stringToRandomParameter(boost::to_upper_copy(symbol.first), &p))\n            usedParameters.push_back(p);\n    }\n\n    // Find list of variables assigned to\n    symbol_list = std::deque<ExpSymbol>();\n    parser.dec().assignment_symbols(symbol_list);\n    // Create list of used features from the list of variables assigned to\n    std::vector<Feature> usedFeatures;\n    for (std::size_t i = 0; i < symbol_list.size(); ++i)\n    {\n        const ExpSymbol& symbol = symbol_list[i];\n        Feature f;\n        if(stringToFeature(boost::to_upper_copy(symbol.first), &f))\n            usedFeatures.push_back(f);\n    }\n\n    return std::make_tuple(std::move(expression), usedParameters, usedFeatures);\n}\n\n}\n\n\n\n//=====================================================================\n//                            SCENE\n//=====================================================================\nScene::Scene(int w, int h, int spp, ExpPtr exp, const std::vector<RandomParameter>& parameters, const std::vector<Feature>& features):\n    width(w),\n    height(h),\n    spp(spp),\n    randomParameters(parameters),\n    features(features),\n    exp(std::move(exp))\n{}\n\nvoid Scene::evaluate()\n{\n    exp->value();\n}\n\nScene::~Scene() = default;\n\n\n\n//=====================================================================\n//                            READ SCENE\n//=====================================================================\nstd::unique_ptr<Scene> readScene(const QString& filename, float* params, float* features)\n{\n    QString info;\n    QString exp;\n\n    QString all;\n    QFile file(filename);\n    if(file.open(QIODevice::ReadOnly | QIODevice::Text))\n    {\n        QTextStream stream(&file);\n        all = stream.readAll();\n\n        QStringList sections = all.split(\"#\");\n        if(sections.size() != 2)\n        {\n            qDebug() << \"Scene file should contain two sections separated by a #.\";\n            return nullptr;\n        }\n\n        info = sections.at(0);\n        exp = sections.at(1);\n    }\n    else\n    {\n        qDebug() << \"Couldn't open file \" << filename;\n        qDebug() << file.errorString();\n        return nullptr;\n    }\n\n    int w = 0, h = 0, spp = 0;\n    extractInfo(info.toStdString(), w, h, spp);\n\n    ExpPtr expPtr;\n    std::vector<RandomParameter> usedParameters;\n    std::vector<Feature> usedFeatures;\n    std::tie(expPtr, usedParameters, usedFeatures) = compileExpression(exp.toStdString(), w, h, spp, params, features);\n    std::unique_ptr<Scene> scene(new Scene(w, h, spp, std::move(expPtr), usedParameters, usedFeatures));\n\n    return scene;\n}\n", "meta": {"hexsha": "7fe0a4423a90c5686fa23d935f5fa5949f1341e0", "size": 9339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SceneReader.cpp", "max_stars_repo_name": "fbksd/proceduralrender", "max_stars_repo_head_hexsha": "635aee89c0e9b22c9f48f876bc1aaa1a2cb88733", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SceneReader.cpp", "max_issues_repo_name": "fbksd/proceduralrender", "max_issues_repo_head_hexsha": "635aee89c0e9b22c9f48f876bc1aaa1a2cb88733", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SceneReader.cpp", "max_forks_repo_name": "fbksd/proceduralrender", "max_forks_repo_head_hexsha": "635aee89c0e9b22c9f48f876bc1aaa1a2cb88733", "max_forks_repo_licenses": ["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.3385214008, "max_line_length": 134, "alphanum_fraction": 0.6330442232, "num_tokens": 2135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.583882319445651}}
{"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": "#ifndef Area_hpp\n#define Area_hpp\n\n#include <shapes/Circle.hpp>\n#include <shapes/Rectangle.hpp>\n\n#include <boost/math/constants/constants.hpp>\nnamespace bmc = boost::math::constants;\n\nfloat\narea( Rectangle const & r )\n{\n  return r.width * r.height;\n}\n\nfloat\narea( Circle const & c )\n{\n  return bmc::pi<float>() * c.radius * c.radius;\n}\n\n#endif // Area_hpp\n", "meta": {"hexsha": "fbe3f6398fd83221ddee8a876834489f58de4df1", "size": 356, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/shapes/Area.hpp", "max_stars_repo_name": "cesiumsolutions/dynamic_generic_visitor", "max_stars_repo_head_hexsha": "da8fe928bf77270e1a64beae0051bfadba7ea256", "max_stars_repo_licenses": ["MIT"], "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/shapes/Area.hpp", "max_issues_repo_name": "cesiumsolutions/dynamic_generic_visitor", "max_issues_repo_head_hexsha": "da8fe928bf77270e1a64beae0051bfadba7ea256", "max_issues_repo_licenses": ["MIT"], "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/shapes/Area.hpp", "max_forks_repo_name": "cesiumsolutions/dynamic_generic_visitor", "max_forks_repo_head_hexsha": "da8fe928bf77270e1a64beae0051bfadba7ea256", "max_forks_repo_licenses": ["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.4782608696, "max_line_length": 48, "alphanum_fraction": 0.6994382022, "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6791786991753931, "lm_q1q2_score": 0.583865307799565}}
{"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){//\u65b0\u3057\u3044\u30af\u30e9\u30b9\u30bf\n\t\teval_new = densityMultiNormal(*d,c);\n\t}else{//\u65e2\u5b58\u306e\u30af\u30e9\u30b9\u30bf\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//\u3069\u306e\u30af\u30e9\u30b9\u30bf\u306b\u6a19\u672c\u304c\u5e7e\u3064\u304b\u308b\u6570\u3048\u308b\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//\u6700\u521d\u306e\u30af\u30e9\u30b9\u30bf\u3092\u4f5c\u308b\u3002\u5e73\u5747\u5024\u306f1\u8ef8\u3054\u3068\u306b\u30ac\u30a6\u30b9\u5206\u5e03\u304b\u3089\u30b5\u30f3\u30d7\u30ea\u30f3\u30b0\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": "//\n// Created by yue on 29.11.19.\n//\n\n#include <iostream>\n#include <time.h>\n#include <opencv2/opencv.hpp>\n#include <opencv2/ximgproc.hpp>\n#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\nint main()\n{\n    Mat myImage = imread(\"../../images/piece01_1200x900.jpg\");\n    Mat myImageGrey;\n    cvtColor(myImage, myImageGrey, CV_BGR2GRAY);\n    Mat dst_blur, dst_blur_median, dst_filter2d, dst_laplacian, dst_sobel, dst_diffusion;\n    blur(myImageGrey, dst_blur, Size(5, 5));\n    medianBlur(myImageGrey, dst_blur_median, 5);\n    Laplacian(myImageGrey, dst_laplacian, -1, 3);\n    Sobel(myImageGrey, dst_sobel, -1, 1, 0, 3);\n    ximgproc::anisotropicDiffusion(myImage, dst_diffusion, 0.15, 100, 10);\n\n    Matrix<char, 3, 3> m;\n    m << 0, 1, 0, 1, -4, 1, 0, 1, 0; // Laplacian filter\n    m << -1, -1, -1, -1, 9, -1, -1, -1, -1; // Laplacian filter\n    m << -1, -2, -1, 0, 0, 0, 1, 2, 1; // Sobel filter x_dir\n//    m.fill(1.0/9);\n    Mat kernel;\n    eigen2cv(m, kernel);\n    cout << typeToString(kernel.type());\n    filter2D(myImageGrey, dst_filter2d, -1, kernel);\n\n    imshow(\"myImageGrey\", myImageGrey);\n//    imshow(\"dst_blur\", dst_blur);\n//    imshow(\"dst_blur_median\", dst_blur_median);\n    imshow(\"dst_laplacian\", dst_laplacian);\n    imshow(\"dst_sobel\", dst_sobel);\n    imshow(\"dst_filter2d\", dst_filter2d);\n    imshow(\"dst_diffusion\", dst_diffusion);\n    waitKey(0);\n    return 0;\n}", "meta": {"hexsha": "68b3016f05b931088e8ae6b5f2dd38bc8e7fa82a", "size": 1453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/filters.cpp", "max_stars_repo_name": "dbddqy/DPI", "max_stars_repo_head_hexsha": "9fa05335902a7404cbc197653e476706ed724ae1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/filters.cpp", "max_issues_repo_name": "dbddqy/DPI", "max_issues_repo_head_hexsha": "9fa05335902a7404cbc197653e476706ed724ae1", "max_issues_repo_licenses": ["MIT"], "max_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.cpp", "max_forks_repo_name": "dbddqy/DPI", "max_forks_repo_head_hexsha": "9fa05335902a7404cbc197653e476706ed724ae1", "max_forks_repo_licenses": ["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.914893617, "max_line_length": 89, "alphanum_fraction": 0.6551961459, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5838652980318572}}
{"text": "#include <armadillo>\n#include <json/json.h>\n\n#include \"ema/Ema.h\"\n\n#include \"settings.h\"\n\nint main(int argc, char* argv[]) {\n\n  Settings settings(argc, argv);\n\n  Ema ema;\n  ema.read().from(settings.input);\n\n  const EmaInfo& info = ema.info();\n\n  arma::vec mean = arma::zeros(3);\n  const int pointAmount = settings.coils.size() * ema.info().sample_amount();\n\n\n  for(const std::string& currentCoil: settings.coils) {\n\n    for(int i = 0; i < info.sample_amount(); ++i) {\n\n      mean += ema.coil(currentCoil).access().position(i);\n\n    }\n\n  }\n\n  mean /= pointAmount;\n\n  Json::Value root(Json::objectValue);\n\n  root[\"x\"] = mean(0);\n  root[\"y\"] = mean(1);\n  root[\"z\"] = mean(2);\n\n  std::ofstream outFile(settings.output);\n\n  outFile << root << std::endl;\n\n  outFile.close();\n\n  return 0;\n\n}\n", "meta": {"hexsha": "d7ada2306a8cab8e5dfb23bcb41ca35c8a488288", "size": 785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ema-tools/ema-coils-compute-mean/src/bin/main.cpp", "max_stars_repo_name": "ahewer/mri-shape-tools", "max_stars_repo_head_hexsha": "4268499948f1330b983ffcdb43df62e38ca45079", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ema-tools/ema-coils-compute-mean/src/bin/main.cpp", "max_issues_repo_name": "ahewer/mri-shape-tools", "max_issues_repo_head_hexsha": "4268499948f1330b983ffcdb43df62e38ca45079", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-29T09:43:01.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-29T09:50:05.000Z", "max_forks_repo_path": "ema-tools/ema-coils-compute-mean/src/bin/main.cpp", "max_forks_repo_name": "ahewer/mri-shape-tools", "max_forks_repo_head_hexsha": "4268499948f1330b983ffcdb43df62e38ca45079", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-05-17T11:56:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T09:12:24.000Z", "avg_line_length": 16.3541666667, "max_line_length": 77, "alphanum_fraction": 0.6178343949, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5837776857885105}}
{"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": "// test_inverse_gamma.cpp\r\n\r\n// Copyright Paul A. Bristow 2010.\r\n// Copyright John Maddock 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#ifdef _MSC_VER\r\n#  pragma warning (disable : 4224) // nonstandard extension used : formal parameter 'type' was previously defined as a type\r\n// in Boost.test and lexical_cast\r\n#  pragma warning (disable : 4310) // cast truncates constant value\r\n#endif\r\n\r\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\r\nusing ::boost::math::concepts::real_concept;\r\n\r\n//#include <boost/math/tools/test.hpp>\r\n#include <boost/test/test_exec_monitor.hpp> // for test_main\r\n#include <boost/test/floating_point_comparison.hpp> // for BOOST_CHECK_CLOSE_FRACTION\r\n#include \"test_out_of_range.hpp\"\r\n\r\n#include <boost/math/distributions/inverse_gamma.hpp> // for inverse_gamma_distribution\r\nusing boost::math::inverse_gamma_distribution;\r\nusing  ::boost::math::inverse_gamma;\r\n//  using  ::boost::math::cdf;\r\n//  using  ::boost::math::pdf;\r\n\r\n#include <boost/math/special_functions/gamma.hpp> \r\nusing boost::math::tgamma; // for naive pdf.\r\n\r\n#include <iostream>\r\nusing std::cout;\r\nusing std::endl;\r\n#include <limits>\r\nusing std::numeric_limits;\r\n\r\ntemplate <class RealType>\r\nRealType naive_pdf(RealType shape, RealType scale, RealType x)\r\n{ // Formula from Wikipedia\r\n   using namespace std; // For ADL of std functions.\r\n   using boost::math::tgamma;\r\n   RealType result = (pow(scale, shape) * pow(x, (-shape -1)) * exp(-scale/x) ) / tgamma(shape);\r\n   return result;\r\n}\r\n\r\n// Test using a spot value from some other reference source,\r\n// in this case test values from output from R provided by Thomas Mang.\r\n\r\ntemplate <class RealType>\r\nvoid test_spot(\r\n     RealType shape, // shape,\r\n     RealType scale, // scale,\r\n     RealType x, // random variate x,\r\n     RealType pd, // expected pdf,\r\n     RealType P, // expected CDF,\r\n     RealType Q, // expected complement of CDF,\r\n     RealType tol) // test tolerance.\r\n{\r\n   boost::math::inverse_gamma_distribution<RealType> dist(shape, scale);\r\n\r\n   BOOST_CHECK_CLOSE_FRACTION\r\n      ( // Compare to expected PDF.\r\n      pdf(dist, x), // calculated.\r\n      pd, // expected\r\n      tol);\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION( // Compare to naive formula (might be less accurate).\r\n      pdf(dist, x), naive_pdf(dist.shape(), dist.scale(), x), tol);\r\n\r\n   BOOST_CHECK_CLOSE_FRACTION( // Compare to expected CDF.\r\n      cdf(dist, x), P, tol);\r\n\r\n   if((P < 0.999) && (Q < 0.999))\r\n   {  // We can only check this if P is not too close to 1,\r\n      // so that we can guarantee Q is accurate:\r\n      BOOST_CHECK_CLOSE_FRACTION(\r\n        cdf(complement(dist, x)), Q, tol);\r\n      BOOST_CHECK_CLOSE_FRACTION(\r\n        quantile(dist, P), x, tol); // quantile(pdf) = x\r\n      BOOST_CHECK_CLOSE_FRACTION(\r\n        quantile(complement(dist, Q)), x, tol);\r\n   }\r\n} // test_spot\r\n\r\n// Test using a spot value from some other reference source.\r\n\r\ntemplate <class RealType> // Any floating-point type RealType.\r\nvoid test_spots(RealType)\r\n{\r\n  // Basic sanity checks, test data is to six decimal places only\r\n  // so set tolerance to 0.000001 expressed as a percentage = 0.0001%.\r\n\r\n  RealType tolerance = 0.000001f; // as fraction.\r\n  cout << \"Tolerance = \" << tolerance * 100 << \"%.\" << endl;\r\n\r\n// This test values from output from R provided by Thomas Mang.\r\n  test_spot(static_cast<RealType>(2), static_cast<RealType>(1), // shape, scale\r\n  static_cast<RealType>(2.L), // x\r\n  static_cast<RealType>(0.075816332464079136L), // pdf\r\n  static_cast<RealType>(0.90979598956895047L), // cdf\r\n  static_cast<RealType>(1 - 0.90979598956895047L), // cdf complement\r\n  tolerance  // tol\r\n  );\r\n\r\n  test_spot(static_cast<RealType>(1.593), static_cast<RealType>( 0.5), // shape, scale\r\n  static_cast<RealType>( 0.5), // x\r\n  static_cast<RealType>(0.82415241749687074L), // pdf\r\n  static_cast<RealType>(0.60648042700409865L), // cdf\r\n  static_cast<RealType>(1 - 0.60648042700409865L), // cdf complement\r\n  tolerance  // tol\r\n  );\r\n\r\n  test_spot(static_cast<RealType>(13.319), static_cast<RealType>(0.5), // shape, scale\r\n  static_cast<RealType>(0.5), // x\r\n  static_cast<RealType>(0.00000000068343206235379223), // pdf\r\n  static_cast<RealType>(0.99999999997242739L), // cdf\r\n  static_cast<RealType>(1 - 0.99999999997242739L), // cdf complement\r\n  tolerance  // tol\r\n  );\r\n\r\n  test_spot(static_cast<RealType>(1.593), static_cast<RealType>(1), // shape, scale\r\n  static_cast<RealType>(1.977), // x\r\n  static_cast<RealType>(0.11535946773398653L), // pdf\r\n  static_cast<RealType>(0.82449794420341549L), // cdf\r\n  static_cast<RealType>(1 - 0.82449794420341549L), // cdf complement\r\n  tolerance  // tol\r\n  );\r\n  \r\n  test_spot(static_cast<RealType>(6.666), static_cast<RealType>(1.411), // shape, scale\r\n  static_cast<RealType>(5), // x\r\n  static_cast<RealType>(0.000000084415758206386872), // pdf\r\n  static_cast<RealType>(0.99999993427280998L), // cdf\r\n  static_cast<RealType>(1 - 0.99999993427280998L), // cdf complement\r\n  tolerance  // tol\r\n  );\r\n\r\n  // Check some bad parameters to the distribution,\r\n  BOOST_CHECK_THROW(boost::math::inverse_gamma_distribution<RealType> igbad1(-1, 0), std::domain_error); // negative shape.\r\n  BOOST_CHECK_THROW(boost::math::inverse_gamma_distribution<RealType> igbad2(0, -1), std::domain_error); // negative scale.\r\n  BOOST_CHECK_THROW(boost::math::inverse_gamma_distribution<RealType> igbad2(-1, -1), std::domain_error); // negative scale and shape.\r\n\r\n  inverse_gamma_distribution<RealType> ig21(2, 1);\r\n\r\n  if(std::numeric_limits<RealType>::has_infinity)\r\n  {\r\n    BOOST_CHECK_THROW(pdf(ig21, +std::numeric_limits<RealType>::infinity()), std::domain_error); // x = + infinity, pdf = 0\r\n    BOOST_CHECK_THROW(pdf(ig21, -std::numeric_limits<RealType>::infinity()),  std::domain_error); // x = - infinity, pdf = 0\r\n    BOOST_CHECK_THROW(cdf(ig21, +std::numeric_limits<RealType>::infinity()),std::domain_error ); // x = + infinity, cdf = 1\r\n    BOOST_CHECK_THROW(cdf(ig21, -std::numeric_limits<RealType>::infinity()), std::domain_error); // x = - infinity, cdf = 0\r\n    BOOST_CHECK_THROW(cdf(complement(ig21, +std::numeric_limits<RealType>::infinity())), std::domain_error); // x = + infinity, c cdf = 0\r\n    BOOST_CHECK_THROW(cdf(complement(ig21, -std::numeric_limits<RealType>::infinity())), std::domain_error); // x = - infinity, c cdf = 1\r\n    BOOST_CHECK_THROW(boost::math::inverse_gamma_distribution<RealType> nbad1(std::numeric_limits<RealType>::infinity(), static_cast<RealType>(1)), std::domain_error); // +infinite mean\r\n    BOOST_CHECK_THROW(boost::math::inverse_gamma_distribution<RealType> nbad1(-std::numeric_limits<RealType>::infinity(),  static_cast<RealType>(1)), std::domain_error); // -infinite mean\r\n    BOOST_CHECK_THROW(boost::math::inverse_gamma_distribution<RealType> nbad1(static_cast<RealType>(0), std::numeric_limits<RealType>::infinity()), std::domain_error); // infinite sd\r\n  }\r\n\r\n  if (std::numeric_limits<RealType>::has_quiet_NaN)\r\n  {\r\n    // No longer allow x to be NaN, then these tests should throw.\r\n    BOOST_CHECK_THROW(pdf(ig21, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // x = NaN\r\n    BOOST_CHECK_THROW(cdf(ig21, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // x = NaN\r\n    BOOST_CHECK_THROW(cdf(complement(ig21, +std::numeric_limits<RealType>::quiet_NaN())), std::domain_error); // x = + infinity\r\n    BOOST_CHECK_THROW(quantile(ig21, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // p = + infinity\r\n    BOOST_CHECK_THROW(quantile(complement(ig21, +std::numeric_limits<RealType>::quiet_NaN())), std::domain_error); // p = + infinity\r\n  }\r\n    // Spot check for pdf using 'naive pdf' function\r\n  for(RealType x = 0.5; x < 5; x += 0.5)\r\n  {\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n      pdf(inverse_gamma_distribution<RealType>(5, 6), x),\r\n      naive_pdf(RealType(5), RealType(6), x),\r\n      tolerance);\r\n  }   // Spot checks for parameters:\r\n\r\n  RealType tol_few_eps = boost::math::tools::epsilon<RealType>() * 5; // 5 eps as a fraction.\r\n  inverse_gamma_distribution<RealType> dist51(5, 1);\r\n  inverse_gamma_distribution<RealType> dist52(5, 2);\r\n  inverse_gamma_distribution<RealType> dist31(3, 1);\r\n  inverse_gamma_distribution<RealType> dist111(11, 1);\r\n  // 11 mean 0.10000000000000001, variance  0.0011111111111111111, sd 0.033333333333333333\r\n\r\n  RealType x = static_cast<RealType>(0.125);\r\n  using namespace std; // ADL of std names.\r\n  using namespace boost::math;\r\n\r\n  //  mean, variance etc\r\n  BOOST_CHECK_CLOSE_FRACTION(mean(dist52), static_cast<RealType>(0.5), tol_few_eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(mean(dist111), static_cast<RealType>(0.1L), tol_few_eps);\r\n  inverse_gamma_distribution<RealType> igamma41(static_cast<RealType>(4.), static_cast<RealType>(1.) );\r\n  BOOST_CHECK_CLOSE_FRACTION(mean(igamma41), static_cast<RealType>(0.3333333333333333333333333333333333333333333333333333333L), tol_few_eps);\r\n  // variance:\r\n  BOOST_CHECK_CLOSE_FRACTION(variance(dist51), static_cast<RealType>(0.0208333333333333333333333333333333333333333333333333L), tol_few_eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(variance(dist31), static_cast<RealType>(0.25), tol_few_eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(variance(dist111), static_cast<RealType>(0.001111111111111111111111111111111111111111111111111L), tol_few_eps);\r\n  // std deviation:\r\n  BOOST_CHECK_CLOSE_FRACTION(standard_deviation(dist31), static_cast<RealType>(0.5), tol_few_eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(standard_deviation(dist111), static_cast<RealType>(0.0333333333333333333333333333333333333333333333333L), tol_few_eps);\r\n  // hazard:\r\n  BOOST_CHECK_CLOSE_FRACTION(hazard(dist51, x), pdf(dist51, x) / cdf(complement(dist51, x)), tol_few_eps);\r\n //  cumulative hazard:\r\n  BOOST_CHECK_CLOSE_FRACTION(chf(dist51, x), -log(cdf(complement(dist51, x))), tol_few_eps);\r\n  // coefficient_of_variation:\r\n  BOOST_CHECK_CLOSE_FRACTION(coefficient_of_variation(dist51), standard_deviation(dist51) / mean(dist51), tol_few_eps);\r\n  // mode:\r\n  BOOST_CHECK_CLOSE_FRACTION(mode(dist51), static_cast<RealType>(0.166666666666666666666666666666666666666666666666666L), tol_few_eps);\r\n  // median\r\n  //BOOST_CHECK_CLOSE_FRACTION(median(dist52), static_cast<RealType>(0), tol_few_eps);\r\n  // Useful to have an exact median?  Failing that use a loop back test.\r\n   BOOST_CHECK_CLOSE_FRACTION(cdf(dist111, median(dist111)), 0.5, tol_few_eps);\r\n  // skewness:\r\n  BOOST_CHECK_CLOSE_FRACTION(skewness(dist111), static_cast<RealType>(1.5), tol_few_eps);\r\n   //kurtosis:\r\n  BOOST_CHECK_CLOSE_FRACTION(kurtosis(dist51), static_cast<RealType>(42 + 3), tol_few_eps);\r\n  // kurtosis excess:\r\n  BOOST_CHECK_CLOSE_FRACTION(kurtosis_excess(dist51), static_cast<RealType>(42), tol_few_eps);\r\n\r\n  tol_few_eps = boost::math::tools::epsilon<RealType>() * 3; // 3 eps as a percentage.\r\n\r\n  // Special and limit cases:\r\n\r\n  if(std::numeric_limits<RealType>::is_specialized)\r\n  {\r\n    RealType mx = (std::numeric_limits<RealType>::max)();\r\n    RealType mi = (std::numeric_limits<RealType>::min)();\r\n\r\n     BOOST_CHECK_EQUAL(\r\n     pdf(inverse_gamma_distribution<RealType>(1),\r\n       static_cast<RealType>(mx)), // max()\r\n       static_cast<RealType>(0)\r\n       );\r\n\r\n     BOOST_CHECK_EQUAL(\r\n     pdf(inverse_gamma_distribution<RealType>(1),\r\n       static_cast<RealType>(mi)), // min()\r\n       static_cast<RealType>(0)\r\n       );\r\n\r\n  }\r\n\r\n  BOOST_CHECK_EQUAL(\r\n    pdf(inverse_gamma_distribution<RealType>(1), static_cast<RealType>(0)), static_cast<RealType>(0));\r\n  BOOST_CHECK_EQUAL(\r\n    pdf(inverse_gamma_distribution<RealType>(3), static_cast<RealType>(0))\r\n    , static_cast<RealType>(0.0f));\r\n  BOOST_CHECK_EQUAL(\r\n    cdf(inverse_gamma_distribution<RealType>(1), static_cast<RealType>(0))\r\n    , static_cast<RealType>(0.0f));\r\n  BOOST_CHECK_EQUAL(\r\n    cdf(inverse_gamma_distribution<RealType>(2), static_cast<RealType>(0))\r\n    , static_cast<RealType>(0.0f));\r\n  BOOST_CHECK_EQUAL(\r\n    cdf(inverse_gamma_distribution<RealType>(3), static_cast<RealType>(0))\r\n    , static_cast<RealType>(0.0f));\r\n  BOOST_CHECK_EQUAL(\r\n    cdf(complement(inverse_gamma_distribution<RealType>(1), static_cast<RealType>(0)))\r\n    , static_cast<RealType>(1));\r\n  BOOST_CHECK_EQUAL(\r\n    cdf(complement(inverse_gamma_distribution<RealType>(2), static_cast<RealType>(0)))\r\n    , static_cast<RealType>(1));\r\n  BOOST_CHECK_EQUAL(\r\n    cdf(complement(inverse_gamma_distribution<RealType>(3), static_cast<RealType>(0)))\r\n    , static_cast<RealType>(1));\r\n\r\n  BOOST_CHECK_THROW(\r\n    pdf(\r\n    inverse_gamma_distribution<RealType>(static_cast<RealType>(-1)), // shape negative.\r\n    static_cast<RealType>(1)), std::domain_error\r\n    );\r\n  BOOST_CHECK_THROW(\r\n    pdf(\r\n    inverse_gamma_distribution<RealType>(static_cast<RealType>(8)),\r\n    static_cast<RealType>(-1)), std::domain_error\r\n    );\r\n  BOOST_CHECK_THROW(\r\n    cdf(\r\n    inverse_gamma_distribution<RealType>(static_cast<RealType>(-1)),\r\n    static_cast<RealType>(1)), std::domain_error\r\n    );\r\n  BOOST_CHECK_THROW(\r\n    cdf(\r\n    inverse_gamma_distribution<RealType>(static_cast<RealType>(8)),\r\n    static_cast<RealType>(-1)), std::domain_error\r\n    );\r\n  BOOST_CHECK_THROW(\r\n    cdf(complement(\r\n    inverse_gamma_distribution<RealType>(static_cast<RealType>(-1)),\r\n    static_cast<RealType>(1))), std::domain_error\r\n    );\r\n  BOOST_CHECK_THROW(\r\n    cdf(complement(\r\n    inverse_gamma_distribution<RealType>(static_cast<RealType>(8)),\r\n    static_cast<RealType>(-1))), std::domain_error\r\n    );\r\n  BOOST_CHECK_THROW(\r\n    quantile(\r\n    inverse_gamma_distribution<RealType>(static_cast<RealType>(-1)),\r\n    static_cast<RealType>(0.5)), std::domain_error\r\n    );\r\n  BOOST_CHECK_THROW(\r\n    quantile(\r\n    inverse_gamma_distribution<RealType>(static_cast<RealType>(8)),\r\n    static_cast<RealType>(-1)), std::domain_error\r\n    );\r\n  BOOST_CHECK_THROW(\r\n    quantile(\r\n    inverse_gamma_distribution<RealType>(static_cast<RealType>(8)),\r\n    static_cast<RealType>(1.1)), std::domain_error\r\n    );\r\n  BOOST_CHECK_THROW(\r\n    quantile(complement(\r\n    inverse_gamma_distribution<RealType>(static_cast<RealType>(-1)),\r\n    static_cast<RealType>(0.5))), std::domain_error\r\n    );\r\n  BOOST_CHECK_THROW(\r\n    quantile(complement(\r\n    inverse_gamma_distribution<RealType>(static_cast<RealType>(8)),\r\n    static_cast<RealType>(-1))), std::domain_error\r\n    );\r\n  BOOST_CHECK_THROW(\r\n    quantile(complement(\r\n    inverse_gamma_distribution<RealType>(static_cast<RealType>(8)),\r\n    static_cast<RealType>(1.1))), std::domain_error\r\n    );\r\n   check_out_of_range<inverse_gamma_distribution<RealType> >(1, 1);\r\n} // template <class RealType>void test_spots(RealType)\r\n\r\nint test_main(int, char* [])\r\n{\r\n  BOOST_MATH_CONTROL_FP;\r\n\r\n  // Check that can generate inverse_gamma distribution using the two convenience methods:\r\n  // inverse_gamma_distribution; // with default parameters, shape = 1, scale - 1\r\n  using boost::math::inverse_gamma;\r\n  inverse_gamma ig2(2.); // Using typedef and shape parameter (and default scale = 1).\r\n  BOOST_CHECK_EQUAL(ig2.shape(), 2.); // scale  == 2.\r\n  BOOST_CHECK_EQUAL(ig2.scale(), 1.); // scale  == 1 (default).\r\n  inverse_gamma ig; // Using typedef, type double and default values, shape = 1 and scale = 1\r\n  // check default is (1, 1)\r\n  BOOST_CHECK_EQUAL(ig.shape(), 1.); // shape == 1\r\n  BOOST_CHECK_EQUAL(ig.scale(), 1.); // scale  == 1\r\n  BOOST_CHECK_EQUAL(mode(ig), 0.5); // mode = 1/2\r\n\r\n  // Used to find some 'exact' values for testing mean, variance ...\r\n //for (int shape = 4; shape < 30; shape++)\r\n // {\r\n //   inverse_gamma ig(shape, 1);\r\n //   cout.precision(17);\r\n //   cout << shape << ' ' << mean(ig) << ' ' << variance(ig) << ' ' << standard_deviation(ig)\r\n //     << ' ' << median(ig) << endl;\r\n // }\r\n\r\n  // and \"using boost::math::inverse_gamma_distribution;\".\r\n  inverse_gamma_distribution<> ig23(2., 3.); // Using default RealType double.\r\n  BOOST_CHECK_EQUAL(ig23.shape(), 2.); //\r\n  BOOST_CHECK_EQUAL(ig23.scale(), 3.); //\r\n\r\n  inverse_gamma_distribution<float> igf23(1.f, 2.f); // Using explicit RealType float.\r\n  BOOST_CHECK_EQUAL(igf23.shape(), 1.f); //\r\n  BOOST_CHECK_EQUAL(igf23.scale(), 2.f); //\r\n  // Some tests using default double.\r\n  double tol5eps = boost::math::tools::epsilon<double>() * 5; // 5 eps as a fraction.\r\n  inverse_gamma_distribution<double> ig102(10., 2.); //\r\n  BOOST_CHECK_EQUAL(ig102.shape(), 10.); //\r\n  BOOST_CHECK_EQUAL(ig102.scale(), 2.); //\r\n  // formatC(SuppDists::dinvGauss(10, 1, 0.5), digits=17)[1] \"0.0011774669940754754\"\r\n  BOOST_CHECK_CLOSE_FRACTION(pdf(ig102, 0.5), 0.1058495335284024, tol5eps);\r\n  // formatC(SuppDists::pinvGauss(10, 1, 0.5), digits=17) [1] \"0.99681494462166653\"\r\n  BOOST_CHECK_CLOSE_FRACTION(cdf(ig102, 0.5), 0.99186775720306608, tol5eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(quantile(ig102, 0.05), 0.12734622346137681, tol5eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(quantile(ig102, 0.5), 0.20685272858879727, tol5eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(quantile(ig102, 0.95),  0.36863602680851204, tol5eps);\r\n  // Check mean, etc spot values.\r\n  inverse_gamma_distribution<double> ig51(5., 1.); // shape = 5, scale = 1\r\n  BOOST_CHECK_CLOSE_FRACTION(mean(ig51), 0.25, tol5eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(variance(ig51), 0.0208333333333333333333333333333333333333333, tol5eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(skewness(ig51), 2 * std::sqrt(3.), tol5eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(kurtosis_excess(ig51), 42, tol5eps);\r\n  // mode and median\r\n  inverse_gamma_distribution<double> ig21(1., 2.);\r\n  BOOST_CHECK_CLOSE_FRACTION(mode(ig21), 1, tol5eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(median(ig21), 2.8853900817779268, tol5eps);\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(quantile(ig21, 0.5), 2.8853900817779268, tol5eps);\r\n  BOOST_CHECK_CLOSE_FRACTION(cdf(ig21, median(ig21)), 0.5, tol5eps);\r\n\r\n    // Check throws from bad parameters.\r\n  inverse_gamma ig051(0.5, 1.); // shape < 1, so wrong for mean.\r\n  BOOST_CHECK_THROW(mean(ig051), std::domain_error);\r\n  inverse_gamma ig191(1.9999, 1.); // shape < 2, so wrong for variance.\r\n  BOOST_CHECK_THROW(variance(ig191), std::domain_error);\r\n  inverse_gamma ig291(2.9999, 1.); // shape < 3, so wrong for skewness.\r\n  BOOST_CHECK_THROW(skewness(ig291), std::domain_error);\r\n  inverse_gamma ig391(3.9999, 1.); // shape < 1, so wrong for kurtosis and kurtosis_excess.\r\n  BOOST_CHECK_THROW(kurtosis(ig391), std::domain_error);\r\n  BOOST_CHECK_THROW(kurtosis_excess(ig391), std::domain_error);\r\n\r\n  // Basic sanity-check spot values.\r\n  // (Parameter value, arbitrarily zero, only communicates the floating point type).\r\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %\r\n  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n  test_spots(0.0L); // Test long double.\r\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\r\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\r\n#endif\r\n#else\r\n  std::cout << \"<note>The long double tests have been disabled on this platform \"\r\n    \"either because the long double overloads of the usual math functions are \"\r\n    \"not available at all, or because they are too inaccurate for these tests \"\r\n    \"to pass.</note>\" << std::cout;\r\n#endif\r\n  return 0;\r\n} // int test_main(int, char* [])\r\n\r\n/*\r\n\r\nOutput:\r\n\r\n------ Build started: Project: test_inverse_gamma_distribution, Configuration: Release Win32 ------\r\n  test_inverse_gamma_distribution.cpp\r\n  Generating code\r\n  Finished generating code\r\n  test_inverse_gamma_distribution.vcxproj -> J:\\Cpp\\MathToolkit\\test\\Math_test\\Release\\test_inverse_gamma_distribution.exe\r\n  Running 1 test case...\r\n  Tolerance = 0.0001%.\r\n  Tolerance = 0.0001%.\r\n  Tolerance = 0.0001%.\r\n  Tolerance = 0.0001%.\r\n\r\n  *** No errors detected\r\n========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========\r\n\r\n\r\n*/\r\n\r\n\r\n\r\n", "meta": {"hexsha": "80c4c85da1e1c715163c2950ff6bd7fe7deebb23", "size": 19950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_inverse_gamma_distribution.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/math/test/test_inverse_gamma_distribution.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/math/test/test_inverse_gamma_distribution.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 45.2380952381, "max_line_length": 188, "alphanum_fraction": 0.705112782, "num_tokens": 5589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.5836162268730205}}
{"text": "#include <algorithm>\n#include <iostream>\n\n#include <boost/format.hpp>\n#include <gtest/gtest.h>\n\n#include <sort.hpp>\n\nstatic void print(my::container &v) {\n    for (auto &i : v) {\n        std::cout << i << \" \";\n    }\n    std::cout << std::endl;\n}\n\nclass sort_test : public ::testing::Test {\n  public:\n    void test(std::function<void(my::container::iterator,\n                                 my::container::iterator)> &&func) {\n        for (auto &v : datas) {\n            print(v);\n            func(v.begin(), v.end());\n            print(v);\n            EXPECT_TRUE(std::is_sorted(v.begin(), v.end()));\n        }\n    }\n\n  protected:\n    void SetUp() override {\n        datas = {{3, 2, 1, 5, 4}, {0, 0, 0}, {0, 1, 2}, {2, 0, 0}, {1, 2, 1}};\n    }\n    std::vector<std::vector<int>> datas;\n};\n\nTEST_F(sort_test, insert_sort) { test(my::insert_sort::sort); }\nTEST_F(sort_test, merge_sort) { test(my::merge_sort::sort); }\nTEST_F(sort_test, heap_sort) { test(my::heap_sort::sort); }\nTEST_F(sort_test, quick_sort) { test(my::quick_sort::sort); }\n", "meta": {"hexsha": "4cea1ecf1c03a1ddc7b8490aed2d1794cd205328", "size": 1038, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/sort.cc", "max_stars_repo_name": "yydcnjjw/my-algorithm", "max_stars_repo_head_hexsha": "ca10befe988ae448eeda7452900fb01d2712d359", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/sort.cc", "max_issues_repo_name": "yydcnjjw/my-algorithm", "max_issues_repo_head_hexsha": "ca10befe988ae448eeda7452900fb01d2712d359", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/sort.cc", "max_forks_repo_name": "yydcnjjw/my-algorithm", "max_forks_repo_head_hexsha": "ca10befe988ae448eeda7452900fb01d2712d359", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6153846154, "max_line_length": 78, "alphanum_fraction": 0.549132948, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.5836162231388672}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2015.\r\n// Modifications copyright (c) 2015 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//[relation\r\n//` Shows how to calculate the spatial relation between a point and a polygon\r\n\r\n#include <iostream>\r\n#include <string>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n/*<-*/ #include \"create_svg_two.hpp\" /*->*/\r\n\r\nint main()\r\n{\r\n    typedef boost::geometry::model::d2::point_xy<double> point_type;\r\n    typedef boost::geometry::model::polygon<point_type> polygon_type;\r\n\r\n    polygon_type poly;\r\n    boost::geometry::read_wkt(\r\n        \"POLYGON((2 1.3,2.4 1.7,2.8 1.8,3.4 1.2,3.7 1.6,3.4 2,4.1 3,5.3 2.6,5.4 1.2,4.9 0.8,2.9 0.7,2 1.3)\"\r\n            \"(4.0 2.0, 4.2 1.4, 4.8 1.9, 4.4 2.2, 4.0 2.0))\", poly);\r\n\r\n    point_type p(4, 1);\r\n\r\n    boost::geometry::de9im::matrix matrix = boost::geometry::relation(p, poly);\r\n    std::string code = matrix.str();\r\n\r\n    std::cout << \"relation: \" << code << std::endl;\r\n    /*<-*/ create_svg(\"relation.svg\", poly, p); /*->*/\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n//[relation_output\r\n/*`\r\nOutput:\r\n[pre\r\nrelation: 0FFFFF212\r\n\r\n[$img/algorithms/within.png]\r\n]\r\n\r\n*/\r\n//]\r\n", "meta": {"hexsha": "0308bef396f7871e0f5f231c17b046f4eff0d96b", "size": 1635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/algorithms/relation.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/algorithms/relation.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/algorithms/relation.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 27.7118644068, "max_line_length": 108, "alphanum_fraction": 0.6458715596, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7853085859124003, "lm_q1q2_score": 0.5836162179388021}}
{"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": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/gamma.hpp>\n#include <math/rev/scal/fun/nan_util.hpp>\n#include <math/rev/scal/util.hpp>\n\nTEST(AgradRev, gamma_q_var_var) {\n  AVAR a = 0.5;\n  AVAR b = 1.0;\n  AVAR f = gamma_q(a, b);\n  EXPECT_FLOAT_EQ(boost::math::gamma_q(0.5, 1.0), f.val());\n\n  AVEC x = createAVEC(a, b);\n  VEC g;\n  f.grad(x, g);\n  EXPECT_FLOAT_EQ(0.38983709, g[0]);\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5, 1.0), g[1]);\n\n  a = -0.5;\n  EXPECT_THROW(gamma_q(a, b), std::domain_error);\n\n  b = -1.0;\n  EXPECT_THROW(gamma_q(a, b), std::domain_error);\n}\nTEST(AgradRevGammaQ, infLoopInVersion2_0_1_var_var) {\n  AVAR a = 8.01006;\n  AVAR b = 2.47579e+215;\n  AVEC x = createAVEC(a, b);\n\n  AVAR f = gamma_q(a, b);\n  VEC g;\n  f.grad(x, g);\n  EXPECT_FLOAT_EQ(0, g[0]);\n}\nTEST(AgradRevGammaQ, infLoopInVersion2_0_1_var_double) {\n  AVAR a = 8.01006;\n  double b = 2.47579e+215;\n  AVEC x = createAVEC(a);\n\n  AVAR f = gamma_q(a, b);\n  VEC g;\n  f.grad(x, g);\n  EXPECT_FLOAT_EQ(0, g[0]);\n}\nTEST(AgradRev, gamma_q_double_var) {\n  double a = 0.5;\n  AVAR b = 1.0;\n  AVAR f = gamma_q(a, b);\n  EXPECT_FLOAT_EQ(boost::math::gamma_q(0.5, 1.0), f.val());\n\n  AVEC x = createAVEC(b);\n  VEC g;\n  f.grad(x, g);\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5, 1.0), g[0]);\n\n  a = -0.5;\n  EXPECT_THROW(gamma_q(a, b), std::domain_error);\n\n  b = -1.0;\n  EXPECT_THROW(gamma_q(a, b), std::domain_error);\n}\nTEST(AgradRev, gamma_q_var_double) {\n  AVAR a = 0.5;\n  double b = 1.0;\n  AVAR f = gamma_q(a, b);\n  EXPECT_FLOAT_EQ(boost::math::gamma_q(0.5, 1.0), f.val());\n\n  AVEC x = createAVEC(a);\n  VEC g;\n  f.grad(x, g);\n  EXPECT_FLOAT_EQ(0.38983709, g[0]);\n\n  a = -0.5;\n  EXPECT_THROW(gamma_q(a, b), std::domain_error);\n\n  b = -1.0;\n  EXPECT_THROW(gamma_q(a, b), std::domain_error);\n}\n\nnamespace {\nstruct gamma_q_fun {\n  template <typename T0, typename T1>\n  inline typename stan::return_type<T0, T1>::type operator()(\n      const T0& arg1, const T1& arg2) const {\n    return gamma_q(arg1, arg2);\n  }\n};\n}  // namespace\n\nTEST(AgradRev, gamma_q_nan) {\n  gamma_q_fun gamma_q_;\n  test_nan(gamma_q_, 3.0, 5.0, false, true);\n}\n\nTEST(AgradRev, check_varis_on_stack_24) {\n  AVAR a = 0.5;\n  AVAR b = 1.0;\n  test::check_varis_on_stack(stan::math::gamma_q(a, b));\n  test::check_varis_on_stack(stan::math::gamma_q(a, 1.0));\n  test::check_varis_on_stack(stan::math::gamma_q(0.5, b));\n}\n", "meta": {"hexsha": "0bcd08685b1e6fa2d54637731fc411c623d51cb1", "size": 2418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/rev/scal/fun/gamma_q_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/rev/scal/fun/gamma_q_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/rev/scal/fun/gamma_q_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7058823529, "max_line_length": 68, "alphanum_fraction": 0.6484698098, "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5835212865386218}}
{"text": "#include <iostream>\n\n#include <boost/graph/grid_graph.hpp>\n\n#include \"NearestNeighbor/metric_space_search.hpp\"\n\nint main(int argc, char *argv[])\n{\n  typedef boost::grid_graph<2> GraphType;\n\n  //const unsigned int dimension = 5;\n  const unsigned int gridDimension = 300;\n  boost::array<std::size_t, 2> lengths = { { gridDimension, gridDimension } };\n  GraphType graph(lengths);\n\n  typedef boost::graph_traits<GraphType>::vertex_descriptor VertexDescriptor;\n\n  VertexDescriptor v = { { 0, 1 } };\n\n  const unsigned int descriptorDimension = 100;\n  typedef boost::hypercube_topology<descriptorDimension, boost::minstd_rand> TopologyType;\n  TopologyType myTopology;\n  typedef TopologyType::point_type PointType;\n\n  std::vector<PointType> vertexData(gridDimension * gridDimension);\n\n  // This is an \"exterior property\" of the grid_graph\n  typedef boost::property_map<GraphType, boost::vertex_index_t>::const_type IndexMapType;\n\n  IndexMapType indexMap(get(boost::vertex_index, graph));\n\n  typedef boost::iterator_property_map<std::vector<PointType>::iterator, IndexMapType> MapType;\n  MapType myMap(vertexData.begin(), indexMap);\n\n  // Add vertices to the graph and corresponding points increasing integer points to the tree.\n  // The experiment here is to query the nearest neighbor of a point like (5.2, 5.2, 5.1, 5.3, 5.2, 5.1)\n  // and ensure we get back (5,5,5,5,5,5)\n  unsigned int counter = 0;\n//   for(unsigned int vertexId = 0; vertexId < num_vertices(graph); ++vertexId)\n//   {\n//     PointType p;\n//     for(unsigned int dim = 0; dim < descriptorDimension; ++dim)\n//       {\n//       p[dim] = vertexId;\n//       }\n//     boost::put(myMap, v, p);\n//   };\n  typedef typename boost::graph_traits<GraphType>::vertex_iterator VertexIter;\n  VertexIter ui,ui_end; tie(ui,ui_end) = vertices(graph);\n  for(VertexIter iter = ui; iter != ui_end; ++iter)\n    {\n    PointType p;\n    for(unsigned int dim = 0; dim < descriptorDimension; ++dim)\n      {\n      p[dim] = counter;\n      }\n    counter++;\n    boost::put(myMap, *iter, p);\n    }\n\n  // Prefer to initialize the DVP-tree with a filled graph, this way,\n  // the entire DVP-tree will be initialized at once (gets best results).\n  typedef dvp_tree<VertexDescriptor, TopologyType, MapType> TreeType;\n  TreeType tree(graph, myTopology, myMap);\n\n  multi_dvp_tree_search<GraphType, TreeType> nearestNeighborFinder;\n  nearestNeighborFinder.graph_tree_map[&graph] = &tree;\n\n  PointType queryPoint;\n  for(unsigned int dim = 0; dim < descriptorDimension; ++dim)\n    {\n    queryPoint[dim] = 5.2;\n    }\n\n  VertexDescriptor nearestNeighbor = nearestNeighborFinder(queryPoint, graph, myTopology, myMap);\n  std::cout << \"nearestNeighbor[0]: \" << nearestNeighbor[0] << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "d161ff9e1f19afc171b46d354a2b132716345297", "size": 2726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NearestNeighbor/Tests/TestDVPTreeGridGraph.cpp", "max_stars_repo_name": "jingtangliao/ff", "max_stars_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T07:59:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T18:11:46.000Z", "max_issues_repo_path": "NearestNeighbor/Tests/TestDVPTreeGridGraph.cpp", "max_issues_repo_name": "jingtangliao/ff", "max_issues_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-24T09:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-24T14:45:46.000Z", "max_forks_repo_path": "NearestNeighbor/Tests/TestDVPTreeGridGraph.cpp", "max_forks_repo_name": "jingtangliao/ff", "max_forks_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-01-11T15:10:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:02:10.000Z", "avg_line_length": 34.075, "max_line_length": 104, "alphanum_fraction": 0.7050623624, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.5834959422299867}}
{"text": "#include <Eigen/Dense>\n#include <cstdlib>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid program_body()\n{\n  Matrix<double, 2, 1> input;\n  input << 9, 2;\n\n  Matrix<double, 3, 2> layer1;\n  layer1 << 1, 2, 3, 4, 5, 6;\n\n  auto output = layer1 * input;\n\n  Matrix<double, 3, 1> expected_output;\n  expected_output << 13, 35, 57;\n\n  if ( output != expected_output ) {\n    throw runtime_error( \"test failure\" );\n  }\n}\n\nint main()\n{\n  try {\n    program_body();\n    return EXIT_SUCCESS;\n  } catch ( const exception& e ) {\n    cerr << e.what() << \"\\n\";\n    return EXIT_FAILURE;\n  }\n}\n", "meta": {"hexsha": "a584fed8095bbe68ce9e9f4b19b1a48646ede627", "size": 596, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/eigentest1.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/tests/eigentest1.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/tests/eigentest1.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": 16.5555555556, "max_line_length": 42, "alphanum_fraction": 0.6157718121, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.583495941745483}}
{"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": "#ifndef TEST_UNIT_MATH_PRIM_SCAL_PROB_HPP\n#define TEST_UNIT_MATH_PRIM_SCAL_PROB_HPP\n\n#include <boost/math/distributions.hpp>\n#include <algorithm>\n#include <vector>\n\n/**\n * Uses a chi-squared test to assert that a vector of observed counts\n * is consistent with a vector of expected counts. Useful for testing RNGs.\n */\nvoid assert_chi_squared(const std::vector<int>& counts,\n                        const std::vector<double>& expected, double tolerance) {\n  int bins = counts.size();\n  EXPECT_EQ(bins, expected.size());\n\n  double chi = 0;\n  for (int i = 0; i < bins; ++i) {\n    double discrepancy = expected[i] - counts[i];\n    chi += discrepancy * discrepancy / expected[i];\n  }\n  boost::math::chi_squared dist(bins - 1);\n  double chi_threshold = quantile(complement(dist, tolerance));\n\n  EXPECT_TRUE(chi < chi_threshold);\n}\n\n/**\n * From a collection of samples and a list of quantiles, assumed ordered,\n * assert that the samples resemble draws from a distribution with those\n * quantiles, using a chi_squared goodness of fit test.\n */\nvoid assert_matches_quantiles(const std::vector<double>& samples,\n                              const std::vector<double>& quantiles,\n                              double tolerance) {\n  int N = samples.size();\n  std::vector<double> mysamples = samples;\n  std::sort(mysamples.begin(), mysamples.end());\n\n  int K = quantiles.size();\n  double expected_count = static_cast<double>(N) / K;\n\n  std::vector<double> expected;\n  for (int i = 0; i < K; i++) {\n    expected.push_back(expected_count);\n  }\n\n  std::vector<int> counts(K);\n  size_t current_index = 0;\n  for (int i = 0; i < N; ++i) {\n    while (mysamples[i] >= quantiles[current_index]) {\n      ++current_index;\n      EXPECT_TRUE(current_index < quantiles.size());\n    }\n    ++counts[current_index];\n  }\n  assert_chi_squared(counts, expected, tolerance);\n}\n#endif\n", "meta": {"hexsha": "11f1c505657e19b36e11ae5fc463870d27301b96", "size": 1853, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/prob/util.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/math/prim/scal/prob/util.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/prim/scal/prob/util.hpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8833333333, "max_line_length": 80, "alphanum_fraction": 0.6686454398, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.583480801475227}}
{"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// \u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u6211\u4eec\u4ece\u5305\u62ec\u4e00\u4e9b\u8457\u540d\u7684\u6587\u4ef6\u5f00\u59cb\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/utilities.h> \n#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// \u4e3a\u4e86\u5728\u7f51\u683c\u4e4b\u95f4\u4f20\u8f93\u89e3\u51b3\u65b9\u6848\uff0c\u5305\u62ec\u8fd9\u4e2a\u6587\u4ef6\u3002\n\n#include <deal.II/numerics/solution_transfer.h> \n\n// \u8fd9\u4e2a\u6587\u4ef6\u5305\u62ecUMFPACK\uff1a\u76f4\u63a5\u6c42\u89e3\u5668\u3002\n\n#include <deal.II/lac/sparse_direct.h> \n\n// \u8fd8\u6709\u4e00\u4e2aILU\u9884\u5904\u7406\u7a0b\u5e8f\u3002\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// \u8be5\u7c7b\u7ba1\u7406\u4ecb\u7ecd\u4e2d\u63cf\u8ff0\u7684\u77e9\u9635\u548c\u5411\u91cf\uff1a\u7279\u522b\u662f\uff0c\u6211\u4eec\u4e3a\u5f53\u524d\u7684\u89e3\u51b3\u65b9\u6848\u3001\u5f53\u524d\u7684\u725b\u987f\u66f4\u65b0\u548c\u76f4\u7ebf\u641c\u7d22\u66f4\u65b0\u5b58\u50a8\u4e86\u4e00\u4e2aBlockVector\u3002 \u6211\u4eec\u8fd8\u5b58\u50a8\u4e86\u4e24\u4e2aAffineConstraints\u5bf9\u8c61\uff1a\u4e00\u4e2a\u662f\u5f3a\u5236\u6267\u884cDirichlet\u8fb9\u754c\u6761\u4ef6\u7684\u5bf9\u8c61\uff0c\u53e6\u4e00\u4e2a\u662f\u5c06\u6240\u6709\u8fb9\u754c\u503c\u8bbe\u4e3a0\u7684\u5bf9\u8c61\u3002\u7b2c\u4e00\u4e2a\u7ea6\u675f\u89e3\u5411\u91cf\uff0c\u7b2c\u4e8c\u4e2a\u7ea6\u675f\u66f4\u65b0\uff08\u4e5f\u5c31\u662f\u8bf4\uff0c\u6211\u4eec\u4ece\u4e0d\u66f4\u65b0\u8fb9\u754c\u503c\uff0c\u6240\u4ee5\u6211\u4eec\u5f3a\u5236\u76f8\u5173\u7684\u66f4\u65b0\u5411\u91cf\u503c\u4e3a\u96f6\uff09\u3002\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// \u5728\u8fd9\u4e2a\u95ee\u9898\u4e2d\uff0c\u6211\u4eec\u8bbe\u5b9a\u6cbf\u7a7a\u8154\u4e0a\u8868\u9762\u7684\u901f\u5ea6\u4e3a1\uff0c\u5176\u4ed6\u4e09\u9762\u5899\u7684\u901f\u5ea6\u4e3a0\u3002\u53f3\u8fb9\u7684\u51fd\u6570\u4e3a\u96f6\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u672c\u6559\u7a0b\u4e2d\u4e0d\u9700\u8981\u8bbe\u7f6e\u53f3\u8fb9\u7684\u51fd\u6570\u3002\u8fb9\u754c\u51fd\u6570\u7684\u5206\u91cf\u6570\u4e3a  <code>dim+1</code>  \u3002\u6211\u4eec\u6700\u7ec8\u5c06\u4f7f\u7528 VectorTools::interpolate_boundary_values \u6765\u8bbe\u7f6e\u8fb9\u754c\u503c\uff0c\u8fd9\u5c31\u8981\u6c42\u8fb9\u754c\u503c\u51fd\u6570\u7684\u5206\u91cf\u6570\u4e0e\u89e3\u76f8\u540c\uff0c\u5373\u4f7f\u6ca1\u6709\u5168\u90e8\u4f7f\u7528\u3002\u6362\u4e2a\u8bf4\u6cd5\uff1a\u4e3a\u4e86\u8ba9\u8fd9\u4e2a\u51fd\u6570\u9ad8\u5174\uff0c\u6211\u4eec\u4e3a\u538b\u529b\u5b9a\u4e49\u4e86\u8fb9\u754c\u503c\uff0c\u5c3d\u7ba1\u6211\u4eec\u5b9e\u9645\u4e0a\u6c38\u8fdc\u4e0d\u4f1a\u7528\u5230\u5b83\u4eec\u3002\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// \u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0cKrylov\u8fed\u4ee3\u65b9\u6cd5\u4e2d\u7684\u9884\u5904\u7406\u5668\u662f\u4f5c\u4e3a\u4e00\u4e2a\u77e9\u9635-\u5411\u91cf\u4e58\u79ef\u7b97\u5b50\u5b9e\u73b0\u7684\u3002\u5728\u5b9e\u8df5\u4e2d\uff0c\u8212\u5c14\u8865\u7801\u9884\u5904\u7406\u5668\u88ab\u5206\u89e3\u4e3a\u4e09\u4e2a\u77e9\u9635\u7684\u4e58\u79ef\uff08\u5982\u7b2c\u4e00\u8282\u6240\u8ff0\uff09\u3002\u7b2c\u4e00\u4e2a\u56e0\u7d20\u4e2d\u7684 $\\tilde{A}^{-1}$ \u6d89\u53ca\u5230\u5bf9\u7ebf\u6027\u7cfb\u7edf $\\tilde{A}x=b$ \u7684\u6c42\u89e3\u3002\u5728\u8fd9\u91cc\uff0c\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u6211\u4eec\u901a\u8fc7\u4e00\u4e2a\u76f4\u63a5\u6c42\u89e3\u5668\u6765\u89e3\u51b3\u8fd9\u4e2a\u7cfb\u7edf\u3002\u7b2c\u4e8c\u4e2a\u56e0\u7d20\u4e2d\u6d89\u53ca\u7684\u8ba1\u7b97\u662f\u4e00\u4e2a\u7b80\u5355\u7684\u77e9\u9635-\u5411\u91cf\u4e58\u6cd5\u3002\u8212\u5c14\u8865\u7801 $\\tilde{S}$ \u53ef\u4ee5\u88ab\u538b\u529b\u8d28\u91cf\u77e9\u9635\u5f88\u597d\u5730\u8fd1\u4f3c\uff0c\u5176\u9006\u503c\u53ef\u4ee5\u901a\u8fc7\u4e0d\u7cbe\u786e\u6c42\u89e3\u5668\u5f97\u5230\u3002\u56e0\u4e3a\u538b\u529b\u8d28\u91cf\u77e9\u9635\u662f\u5bf9\u79f0\u548c\u6b63\u5b9a\u7684\uff0c\u6211\u4eec\u53ef\u4ee5\u7528CG\u6765\u89e3\u51b3\u76f8\u5e94\u7684\u7ebf\u6027\u7cfb\u7edf\u3002\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// \u6211\u4eec\u53ef\u4ee5\u6ce8\u610f\u5230\uff0c\u5de6\u4e0a\u89d2\u7684\u77e9\u9635\u9006\u7684\u521d\u59cb\u5316\u662f\u5728\u6784\u9020\u51fd\u6570\u4e2d\u5b8c\u6210\u7684\u3002\u5982\u679c\u662f\u8fd9\u6837\uff0c\u90a3\u4e48\u9884\u5904\u7406\u7a0b\u5e8f\u7684\u6bcf\u4e00\u6b21\u5e94\u7528\u5c31\u4e0d\u518d\u9700\u8981\u8ba1\u7b97\u77e9\u9635\u56e0\u5b50\u4e86\u3002\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// \u8be5\u7c7b\u7684\u6784\u9020\u51fd\u6570\u770b\u8d77\u6765\u4e0e  step-22  \u4e2d\u7684\u6784\u9020\u51fd\u6570\u975e\u5e38\u76f8\u4f3c\u3002\u552f\u4e00\u7684\u533a\u522b\u662f\u7c98\u5ea6\u548c\u589e\u5f3a\u7684\u62c9\u683c\u6717\u65e5\u7cfb\u6570  <code>gamma</code>  \u3002\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// \u8fd9\u4e2a\u51fd\u6570\u521d\u59cb\u5316DoFHandler\uff0c\u5217\u4e3e\u5f53\u524d\u7f51\u683c\u4e0a\u7684\u81ea\u7531\u5ea6\u548c\u7ea6\u675f\u3002\n\n  template <int dim> \n  void StationaryNavierStokes<dim>::setup_dofs() \n  { \n    system_matrix.clear(); \n    pressure_mass_matrix.clear(); \n\n// \u7b2c\u4e00\u6b65\u662f\u5c06DoFs\u4e0e\u7ed9\u5b9a\u7684\u7f51\u683c\u8054\u7cfb\u8d77\u6765\u3002\n\n    dof_handler.distribute_dofs(fe); \n\n// \u6211\u4eec\u5bf9\u7ec4\u4ef6\u91cd\u65b0\u7f16\u53f7\uff0c\u4f7f\u6240\u6709\u7684\u901f\u5ea6DoF\u5728\u538b\u529bDoF\u4e4b\u524d\uff0c\u4ee5\u4fbf\u80fd\u591f\u5c06\u89e3\u5411\u91cf\u5206\u6210\u4e24\u4e2a\u5757\uff0c\u5728\u5757\u9884\u5904\u7406\u7a0b\u5e8f\u4e2d\u5206\u522b\u8bbf\u95ee\u3002\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// \u5728\u725b\u987f\u65b9\u6848\u4e2d\uff0c\u6211\u4eec\u9996\u5148\u5c06\u8fb9\u754c\u6761\u4ef6\u5e94\u7528\u4e8e\u4ece\u521d\u59cb\u6b65\u9aa4\u5f97\u5230\u7684\u89e3\u3002\u4e3a\u4e86\u786e\u4fdd\u8fb9\u754c\u6761\u4ef6\u5728\u725b\u987f\u8fed\u4ee3\u8fc7\u7a0b\u4e2d\u4fdd\u6301\u6ee1\u8db3\uff0c\u5728\u66f4\u65b0\u65f6\u4f7f\u7528\u96f6\u8fb9\u754c\u6761\u4ef6  $\\delta u^k$  \u3002\u56e0\u6b64\u6211\u4eec\u8bbe\u7f6e\u4e86\u4e24\u4e2a\u4e0d\u540c\u7684\u7ea6\u675f\u5bf9\u8c61\u3002\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// \u5728\u6bcf\u4e2a\u7f51\u683c\u4e0a\uff0cSparsityPattern\u548c\u7ebf\u6027\u7cfb\u7edf\u7684\u5927\u5c0f\u662f\u4e0d\u540c\u7684\u3002\u8fd9\u4e2a\u51fd\u6570\u5728\u7f51\u683c\u7ec6\u5316\u540e\u521d\u59cb\u5316\u5b83\u4eec\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u5efa\u7acb\u4e86\u6211\u4eec\u76ee\u524d\u5de5\u4f5c\u7684\u7cfb\u7edf\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u3002 @p initial_step \u53c2\u6570\u7528\u4e8e\u786e\u5b9a\u6211\u4eec\u5e94\u7528\u54ea\u4e00\u7ec4\u7ea6\u675f\uff08\u521d\u59cb\u6b65\u9aa4\u4e3a\u975e\u96f6\uff0c\u5176\u4ed6\u4e3a\u96f6\uff09\u3002 @p assemble_matrix \u53c2\u6570\u5206\u522b\u51b3\u5b9a\u4e86\u662f\u7ec4\u88c5\u6574\u4e2a\u7cfb\u7edf\u8fd8\u662f\u53ea\u7ec4\u88c5\u53f3\u624b\u8fb9\u7684\u5411\u91cf\u3002\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// \u5bf9\u4e8e\u7ebf\u6027\u5316\u7cfb\u7edf\uff0c\u6211\u4eec\u4e3a\u5f53\u524d\u901f\u5ea6\u548c\u68af\u5ea6\u4ee5\u53ca\u5f53\u524d\u538b\u529b\u521b\u5efa\u4e34\u65f6\u5b58\u50a8\u3002\u5728\u5b9e\u8df5\u4e2d\uff0c\u5b83\u4eec\u90fd\u662f\u901a\u8fc7\u6b63\u4ea4\u70b9\u7684\u5f62\u72b6\u51fd\u6570\u83b7\u5f97\u7684\u3002\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//\u88c5\u914d\u7c7b\u4f3c\u4e8e  step-22  \u3002\u4e00\u4e2a\u4ee5gamma\u4e3a\u7cfb\u6570\u7684\u9644\u52a0\u9879\u662f\u589e\u5f3a\u62c9\u683c\u6717\u65e5\uff08AL\uff09\uff0c\u5b83\u662f\u901a\u8fc7grad-div\u7a33\u5b9a\u5316\u7ec4\u88c5\u7684\u3002 \u6b63\u5982\u6211\u4eec\u5728\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u7cfb\u7edf\u77e9\u9635\u7684\u53f3\u4e0b\u5757\u5e94\u8be5\u4e3a\u96f6\u3002\u7531\u4e8e\u538b\u529b\u8d28\u91cf\u77e9\u9635\u662f\u5728\u521b\u5efa\u9884\u5904\u7406\u7a0b\u5e8f\u65f6\u4f7f\u7528\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u8fd9\u91cc\u7ec4\u88c5\u5b83\uff0c\u7136\u540e\u5728\u6700\u540e\u628a\u5b83\u79fb\u5230\u4e00\u4e2a\u5355\u72ec\u7684SparseMatrix\u4e2d\uff08\u4e0e step-22 \u76f8\u540c\uff09\u3002\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// \u6700\u540e\u6211\u4eec\u628a\u538b\u529b\u8d28\u91cf\u77e9\u9635\u79fb\u5230\u4e00\u4e2a\u5355\u72ec\u7684\u77e9\u9635\u4e2d\u3002\n\n        pressure_mass_matrix.reinit(sparsity_pattern.block(1, 1)); \n        pressure_mass_matrix.copy_from(system_matrix.block(1, 1)); \n\n// \u6ce8\u610f\uff0c\u5c06\u8fd9\u4e2a\u538b\u529b\u5757\u8bbe\u7f6e\u4e3a\u96f6\u5e76\u4e0d\u7b49\u540c\u4e8e\u4e0d\u5728\u8fd9\u4e2a\u5757\u4e2d\u88c5\u914d\u4efb\u4f55\u4e1c\u897f\uff0c\u56e0\u4e3a\u8fd9\u91cc\u7684\u64cd\u4f5c\u5c06\uff08\u9519\u8bef\u5730\uff09\u5220\u9664\u4ece\u538b\u529b\u4f5c\u7528\u529b\u7684\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u4e2d\u8fdb\u6765\u7684\u5bf9\u89d2\u7ebf\u6761\u76ee\u3002\u8fd9\u610f\u5473\u7740\uff0c\u6211\u4eec\u7684\u6574\u4e2a\u7cfb\u7edf\u77e9\u9635\u5c06\u6709\u5b8c\u5168\u4e3a\u96f6\u7684\u884c\u3002\u5e78\u8fd0\u7684\u662f\uff0cFGMRES\u5904\u7406\u8fd9\u4e9b\u884c\u6ca1\u6709\u4efb\u4f55\u95ee\u9898\u3002\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// \u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u4f7f\u7528FGMRES\u548c\u7a0b\u5e8f\u5f00\u59cb\u65f6\u5b9a\u4e49\u7684\u5757\u72b6\u9884\u5904\u7406\u7a0b\u5e8f\u6765\u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u3002\u6211\u4eec\u5728\u8fd9\u4e00\u6b65\u5f97\u5230\u7684\u662f\u89e3\u5411\u91cf\u3002\u5982\u679c\u8fd9\u662f\u521d\u59cb\u6b65\u9aa4\uff0c\u89e3\u5411\u91cf\u4e3a\u6211\u4eec\u63d0\u4f9b\u4e86\u7eb3\u7ef4\u5c14-\u65af\u6258\u514b\u65af\u65b9\u7a0b\u7684\u521d\u59cb\u731c\u6d4b\u3002\u5bf9\u4e8e\u521d\u59cb\u6b65\u9aa4\uff0c\u975e\u96f6\u7ea6\u675f\u88ab\u5e94\u7528\uff0c\u4ee5\u786e\u4fdd\u8fb9\u754c\u6761\u4ef6\u5f97\u5230\u6ee1\u8db3\u3002\u5728\u4e0b\u9762\u7684\u6b65\u9aa4\u4e2d\uff0c\u6211\u4eec\u5c06\u6c42\u89e3\u725b\u987f\u66f4\u65b0\uff0c\u6240\u4ee5\u4f7f\u7528\u96f6\u7ea6\u675f\u3002\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// \u5728\u7c97\u7565\u7684\u7f51\u683c\u4e0a\u627e\u5230\u4e00\u4e2a\u597d\u7684\u521d\u59cb\u731c\u6d4b\u540e\uff0c\u6211\u4eec\u5e0c\u671b\u901a\u8fc7\u7ec6\u5316\u7f51\u683c\u6765\u51cf\u5c11\u8bef\u5dee\u3002\u8fd9\u91cc\u6211\u4eec\u505a\u4e86\u7c7b\u4f3c\u4e8e step-15 \u7684\u81ea\u9002\u5e94\u7ec6\u5316\uff0c\u53ea\u662f\u6211\u4eec\u53ea\u4f7f\u7528\u4e86\u901f\u5ea6\u4e0a\u7684Kelly\u4f30\u8ba1\u5668\u3002\u6211\u4eec\u8fd8\u9700\u8981\u4f7f\u7528SolutionTransfer\u7c7b\u5c06\u5f53\u524d\u7684\u89e3\u8f6c\u79fb\u5230\u4e0b\u4e00\u4e2a\u7f51\u683c\u3002\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// \u9996\u5148\uff0cDoFHandler\u88ab\u8bbe\u7f6e\uff0c\u7ea6\u675f\u88ab\u751f\u6210\u3002\u7136\u540e\u6211\u4eec\u521b\u5efa\u4e00\u4e2a\u4e34\u65f6\u7684BlockVector  <code>tmp</code>  \uff0c\u5176\u5927\u5c0f\u4e0e\u65b0\u7f51\u683c\u4e0a\u7684\u89e3\u51b3\u65b9\u6848\u4e00\u81f4\u3002\n\n    setup_dofs(); \n\n    BlockVector<double> tmp(dofs_per_block); \n\n// \u5c06\u89e3\u51b3\u65b9\u6848\u4ece\u7c97\u7f51\u683c\u8f6c\u79fb\u5230\u7ec6\u7f51\u683c\uff0c\u5e76\u5bf9\u65b0\u8f6c\u79fb\u7684\u89e3\u51b3\u65b9\u6848\u5e94\u7528\u8fb9\u754c\u503c\u7ea6\u675f\u3002\u6ce8\u610f\uff0cpresent_solution\u4ecd\u7136\u662f\u5bf9\u5e94\u4e8e\u65e7\u7f51\u683c\u7684\u4e00\u4e2a\u5411\u91cf\u3002\n\n    solution_transfer.interpolate(present_solution, tmp); \n    nonzero_constraints.distribute(tmp); \n\n// \u6700\u540e\u8bbe\u7f6e\u77e9\u9635\u548c\u5411\u91cf\uff0c\u5e76\u5c06present_solution\u8bbe\u7f6e\u4e3a\u63d2\u503c\u540e\u7684\u6570\u636e\u3002\n\n    initialize_system(); \n    present_solution = tmp; \n  } \n// @sect4{StationaryNavierStokes<dim>::newton_iteration}  \n\n// \u8fd9\u4e2a\u51fd\u6570\u5b9e\u73b0\u4e86\u725b\u987f\u8fed\u4ee3\uff0c\u7ed9\u5b9a\u4e86\u516c\u5dee\u3001\u6700\u5927\u8fed\u4ee3\u6b21\u6570\u548c\u8981\u505a\u7684\u7f51\u683c\u7ec6\u5316\u6b21\u6570\u3002\n\n// \u53c2\u6570 <code>is_initial_step</code> \u544a\u8bc9\u6211\u4eec\u662f\u5426\u9700\u8981 <code>setup_system</code> \uff0c\u4ee5\u53ca\u5e94\u8be5\u88c5\u914d\u54ea\u4e00\u90e8\u5206\uff0c\u7cfb\u7edf\u77e9\u9635\u6216\u53f3\u624b\u8fb9\u7684\u77e2\u91cf\u3002\u5982\u679c\u6211\u4eec\u505a\u76f4\u7ebf\u641c\u7d22\uff0c\u5728\u6700\u540e\u4e00\u6b21\u8fed\u4ee3\u4e2d\u68c0\u67e5\u6b8b\u5dee\u51c6\u5219\u65f6\uff0c\u53f3\u624b\u8fb9\u5df2\u7ecf\u88ab\u7ec4\u88c5\u8d77\u6765\u4e86\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u53ea\u9700\u8981\u5728\u5f53\u524d\u8fed\u4ee3\u4e2d\u88c5\u914d\u7cfb\u7edf\u77e9\u9635\u3002\u6700\u540e\u4e00\u4e2a\u53c2\u6570 <code>output_result</code> \u51b3\u5b9a\u4e86\u662f\u5426\u5e94\u8be5\u4ea7\u751f\u56fe\u5f62\u8f93\u51fa\u3002\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// \u4e3a\u4e86\u786e\u4fdd\u6211\u4eec\u7684\u89e3\u51b3\u65b9\u6848\u8d8a\u6765\u8d8a\u63a5\u8fd1\u7cbe\u786e\u7684\u89e3\u51b3\u65b9\u6848\uff0c\u6211\u4eec\u8ba9\u89e3\u51b3\u65b9\u6848\u7528\u6743\u91cd <code>alpha</code> \u66f4\u65b0\uff0c\u4f7f\u65b0\u7684\u6b8b\u5dee\u5c0f\u4e8e\u4e0a\u4e00\u6b65\u7684\u6b8b\u5dee\uff0c\u8fd9\u662f\u5728\u4e0b\u9762\u7684\u5faa\u73af\u4e2d\u5b8c\u6210\u3002\u8fd9\u4e0e  step-15  \u4e2d\u4f7f\u7528\u7684\u7ebf\u641c\u7d22\u7b97\u6cd5\u76f8\u540c\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u5c06\u901a\u8fc7\u4f7f\u7528\u5ef6\u7eed\u6cd5\u4e3a\u6211\u4eec\u63d0\u4f9b\u4e00\u4e2a\u521d\u59cb\u731c\u6d4b\uff0c\u6b63\u5982\u6211\u4eec\u5728\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u90a3\u6837\u3002\u96f7\u8bfa\u6570\u88ab\u9010\u7ea7\u589e\u52a0 step- \uff0c\u76f4\u5230\u6211\u4eec\u8fbe\u5230\u76ee\u6807\u503c\u3002\u901a\u8fc7\u5b9e\u9a8c\uff0c\u65af\u6258\u514b\u65af\u7684\u89e3\u8db3\u4ee5\u6210\u4e3a\u96f7\u8bfa\u6570\u4e3a1000\u7684NSE\u7684\u521d\u59cb\u731c\u6d4b\uff0c\u6240\u4ee5\u6211\u4eec\u4ece\u8fd9\u91cc\u5f00\u59cb\u3002 \u4e3a\u4e86\u786e\u4fdd\u524d\u4e00\u4e2a\u95ee\u9898\u7684\u89e3\u51b3\u65b9\u6848\u4e0e\u4e0b\u4e00\u4e2a\u95ee\u9898\u8db3\u591f\u63a5\u8fd1\uff0c\u6b65\u957f\u5fc5\u987b\u8db3\u591f\u5c0f\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u4e0e step-22 \u4e2d\u7684\u51fd\u6570\u76f8\u540c\uff0c\u53ea\u662f\u6211\u4eec\u4e3a\u8f93\u51fa\u6587\u4ef6\u9009\u62e9\u4e86\u4e00\u4e2a\u540c\u65f6\u5305\u542b\u96f7\u8bfa\u6570\uff08\u5373\u5f53\u524d\u73af\u5883\u4e0b\u7684\u7c98\u5ea6\u7684\u5012\u6570\uff09\u7684\u540d\u79f0\u3002\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// \u5728\u6211\u4eec\u7684\u6d4b\u8bd5\u6848\u4f8b\u4e2d\uff0c\u6211\u4eec\u4e0d\u77e5\u9053\u5206\u6790\u89e3\u3002\u8be5\u51fd\u6570\u8f93\u51fa\u6cbf $x=0.5$ \u548c $0 \\leq y \\leq 1$ \u7684\u901f\u5ea6\u5206\u91cf\uff0c\u4ee5\u4fbf\u4e0e\u6587\u732e\u4e2d\u7684\u6570\u636e\u8fdb\u884c\u6bd4\u8f83\u3002\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// \u8fd9\u662f\u672c\u7a0b\u5e8f\u7684\u6700\u540e\u4e00\u6b65\u3002\u5728\u8fd9\u4e00\u90e8\u5206\uff0c\u6211\u4eec\u5206\u522b\u751f\u6210\u7f51\u683c\u548c\u8fd0\u884c\u5176\u4ed6\u51fd\u6570\u3002\u6700\u5927\u7ec6\u5316\u5ea6\u53ef\u4ee5\u901a\u8fc7\u53c2\u6570\u6765\u8bbe\u7f6e\u3002\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// \u5982\u679c\u7c98\u5ea6\u5c0f\u4e8e $1/1000$ \uff0c\u6211\u4eec\u5fc5\u987b\u9996\u5148\u901a\u8fc7\u5ef6\u7eed\u6cd5\u641c\u7d22\u521d\u59cb\u731c\u6d4b\u3002\u6211\u4eec\u5e94\u8be5\u6ce8\u610f\u7684\u662f\uff0c\u641c\u7d22\u603b\u662f\u5728\u521d\u59cb\u7f51\u683c\u4e0a\u8fdb\u884c\u7684\uff0c\u4e5f\u5c31\u662f\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u7684 $8 \\times 8$ \u7f51\u683c\u3002\u4e4b\u540e\uff0c\u6211\u4eec\u53ea\u9700\u505a\u4e0e\u7c98\u5ea6\u5927\u4e8e $1/1000$ \u65f6\u76f8\u540c\u7684\u5de5\u4f5c\uff1a\u8fd0\u884c\u725b\u987f\u8fed\u4ee3\uff0c\u7ec6\u5316\u7f51\u683c\uff0c\u8f6c\u79fb\u89e3\u51b3\u65b9\u6848\uff0c\u5e76\u91cd\u590d\u3002\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// \u5f53\u7c98\u5ea6\u5927\u4e8e1/1000\u65f6\uff0c\u65af\u6258\u514b\u65af\u65b9\u7a0b\u7684\u89e3\u4f5c\u4e3a\u521d\u59cb\u731c\u6d4b\u5df2\u7ecf\u8db3\u591f\u597d\u3002\u5982\u679c\u662f\u8fd9\u6837\uff0c\u6211\u4eec\u5c31\u4e0d\u9700\u8981\u7528\u5ef6\u7eed\u6cd5\u6765\u641c\u7d22\u521d\u59cb\u731c\u6d4b\u4e86\u3002\u725b\u987f\u8fed\u4ee3\u53ef\u4ee5\u76f4\u63a5\u5f00\u59cb\u3002\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": "#include \"geometrycentral/surface/manifold_surface_mesh.h\"\n#include \"geometrycentral/utilities/mesh_data.h\"\n#include \"geometrycentral/surface/edge_length_geometry.h\"\n#include \"geometrycentral/surface/heat_method_distance.h\"\n#include <Eigen/Core>\n#include <stdio.h>\n#include <iostream>\n#include <math.h>\n\nusing namespace geometrycentral;\nusing namespace geometrycentral::surface;\n\nextern \"C\" {\n\n  int main(){\n    // create quad with two triangles in CCW order\n    //\n    //   0--3\n    //   | /|\n    //   |/ |\n    //   1--2\n    //\n\n    const size_t F = 2;\n    Eigen::MatrixX3i faces(F, 3);\n    faces << 0, 1, 3,\n             1, 2, 3;\n    \n    Eigen::MatrixX3d edges(F, 3);\n    edges << 1, M_SQRT2, 1,\n             1, 1, M_SQRT2;\n\n    std::cout << \"Faces:\\n\" << faces << \"\\n\";\n    std::cout << \"Edges:\\n\" << edges << \"\\n\";\n\n    // create surface mesh\n    std::unique_ptr<ManifoldSurfaceMesh> mesh;\n    mesh.reset(new ManifoldSurfaceMesh(faces));\n    mesh->compress();\n    mesh->printStatistics();\n\n    // create geometry data\n    EdgeData<double> edgeLengths(*mesh);\n    for(size_t i = 0; i < faces.rows(); ++i){\n      Face f = mesh->face(i);\n      Halfedge he = f.halfedge(); edgeLengths[he.edge()] = edges(i, 0);\n      he = he.next(); edgeLengths[he.edge()] = edges(i, 1);\n      he = he.next(); edgeLengths[he.edge()] = edges(i, 2);\n    }\n    std::cout << \"Edges:\\n\" << edgeLengths.raw() << \"\\n\";\n    for(Edge e : mesh->edges()){\n      printf(\"Edge #%zu = %g\\n\", e.getIndex(), edgeLengths[e]);\n    }\n    std::unique_ptr<EdgeLengthGeometry> geometry;\n    geometry.reset(new EdgeLengthGeometry(*mesh, edgeLengths));\n\n    std::cout << \"Precomputation\\n\";\n\n    // create heat method distance solver (precomputation happens here)\n    std::unique_ptr<HeatMethodDistanceSolver> heatSolver;\n    heatSolver.reset(new HeatMethodDistanceSolver(*geometry));\n\n    std::cout << \"Solve\\n\";\n\n    // solve for distance from first vertex\n    const Vertex v = mesh->vertex(0);\n    VertexData<double> distToSource = heatSolver->computeDistance(v);\n    std::cout << \"Distances:\\n\" << distToSource.raw() << \"\\n\";\n\n    return 0;\n  }\n\n}", "meta": {"hexsha": "18bf17788c9d717110895d50864e2ca3671c55c4", "size": 2111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geodesic-dist/test.cpp", "max_stars_repo_name": "xionluhnis/knitsketching", "max_stars_repo_head_hexsha": "3e13670caa911b6d5e3c9c036c0ee15184e7d138", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-08-16T05:19:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T17:46:12.000Z", "max_issues_repo_path": "libs/geodesic-dist/test.cpp", "max_issues_repo_name": "xionluhnis/knitsketching", "max_issues_repo_head_hexsha": "3e13670caa911b6d5e3c9c036c0ee15184e7d138", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-08-25T07:11:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T09:16:05.000Z", "max_forks_repo_path": "libs/geodesic-dist/test.cpp", "max_forks_repo_name": "xionluhnis/knitsketching", "max_forks_repo_head_hexsha": "3e13670caa911b6d5e3c9c036c0ee15184e7d138", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-12T11:49:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T07:51:53.000Z", "avg_line_length": 28.9178082192, "max_line_length": 71, "alphanum_fraction": 0.6191378494, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5834494963385931}}
{"text": "#include <tdp/testing/testing.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <tdp/manifold/SO3.h>\n#include <tdp/manifold/rotation.h>\n#include <tdp/manifold/SO3.h>\n#include <tdp/eigen/dense.h>\n\nusing namespace tdp;\n\nTEST(SO3, deriv) {\n  float eps = 1e-3;\n\n  for (size_t i=0; i<100; ++i) {\n    Eigen::Vector3f p_c = Eigen::Vector3f::Random();\n    tdp::SO3f T_wc = tdp::SO3f::Random();\n    for (size_t j=0; j<3; ++j) {\n      Eigen::Matrix<float,3,1> delta = Eigen::Matrix<float,3,1>::Zero();\n      delta(j) = eps;\n      tdp::SO3f T_wcDelta = T_wc.Exp(delta);\n      Eigen::Vector3f diffGt = T_wcDelta*p_c - T_wc*p_c ; \n      Eigen::Matrix<float,3,3> J = -T_wc.matrix()*tdp::SO3f::invVee(p_c);\n      Eigen::Vector3f diffJ = J*delta;\n      std::cout << j << \": \" << (diffGt-diffJ).norm() << std::endl;\n//        << \";\\t\" << diffGt.transpose() << \" \" << diffJ.transpose() << std::endl;\n    }\n  }\n}\n\nTEST(SO3, derivofInverse) {\n  float eps = 1e-3;\n\n  for (size_t i=0; i<100; ++i) {\n    Eigen::Vector3f p_w = Eigen::Vector3f::Random();\n    tdp::SO3f T_wc = tdp::SO3f::Random();\n    for (size_t j=0; j<3; ++j) {\n      Eigen::Matrix<float,3,1> delta = Eigen::Matrix<float,3,1>::Zero();\n      delta(j) = eps;\n      tdp::SO3f T_wcDelta = T_wc.Exp(delta);\n      Eigen::Vector3f diffGt = T_wcDelta.Inverse()*p_w- T_wc.Inverse()*p_w; \n      Eigen::Matrix<float,3,3> J = tdp::SO3f::invVee(T_wc.Inverse()*p_w);\n      Eigen::Vector3f diffJ = J*delta;\n      std::cout << j << \": \" << (diffGt-diffJ).norm() \n        << \";\\t\" << diffGt.transpose() << \" \" << diffJ.transpose() << std::endl;\n    }\n  }\n}\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "885241caf28349ce75b3a0337ae65ccf9a1624fe", "size": 1693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/SO3derivs.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/SO3derivs.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/SO3derivs.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.9433962264, "max_line_length": 82, "alphanum_fraction": 0.5841701122, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5834494868371249}}
{"text": "//\n//  cal_BTDB.hpp\n//  hybrid_fem_bie\n//\n//  Created by Max on 2/6/18.\n//\n//\n\n#ifndef cal_BTDB_hpp\n#define cal_BTDB_hpp\n\n#include <stdio.h>\n#include <Eigen/Eigen>\nusing namespace Eigen;\nvoid cal_BTDB (MatrixXd coord,double E, double nu,MatrixXd &B_T_D_B);\n\n\n#endif /* cal_BTDB_hpp */\n", "meta": {"hexsha": "3f4efddc51731bdca51cdf2d15295d79a975b092", "size": 285, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fem/cal_BTDB.hpp", "max_stars_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_stars_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "src/fem/cal_BTDB.hpp", "max_issues_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_issues_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fem/cal_BTDB.hpp", "max_forks_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_forks_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 15.0, "max_line_length": 69, "alphanum_fraction": 0.701754386, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633915959134572, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5834494829735096}}
{"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": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n\n#include <OpenTissue/core/math/optimization/optimization_make_constant_bounds.h>\n#include <OpenTissue/core/math/optimization/optimization_project.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\ntemplate<typename bound_function>\ninline void test_projection( bound_function const & lower, bound_function const & upper, ublas::vector<double> const & x)\n{\n  double tol =0.01;\n  {\n    ublas::vector<double>  y;\n    y = x;\n    OpenTissue::math::optimization::project(x,lower,upper,y);\n    BOOST_CHECK_CLOSE( y(0) , 1.0 , tol );\n    BOOST_CHECK_CLOSE( y(1) , -2.0 , tol );\n    BOOST_CHECK_CLOSE( y(2) , 3.0 , tol );\n    BOOST_CHECK_CLOSE( y(3) , -4.0 , tol );\n    BOOST_CHECK_CLOSE( y(4) , 5.0 , tol );\n    BOOST_CHECK_CLOSE( y(5) , -6.0 , tol );\n    BOOST_CHECK_CLOSE( y(6) , 7.0 , tol );\n    BOOST_CHECK_CLOSE( y(7) , -8.0 , tol );\n    BOOST_CHECK_CLOSE( y(8) , 9.0 , tol );\n    BOOST_CHECK_CLOSE( y(9) , -10.0 , tol );\n  }\n  {\n    ublas::vector<double>  y;\n    y = x;\n\n    OpenTissue::math::optimization::project(y,lower,upper);\n\n    BOOST_CHECK_CLOSE( y(0) , 1.0 , tol );\n    BOOST_CHECK_CLOSE( y(1) , -2.0 , tol );\n    BOOST_CHECK_CLOSE( y(2) , 3.0 , tol );\n    BOOST_CHECK_CLOSE( y(3) , -4.0 , tol );\n    BOOST_CHECK_CLOSE( y(4) , 5.0 , tol );\n    BOOST_CHECK_CLOSE( y(5) , -6.0 , tol );\n    BOOST_CHECK_CLOSE( y(6) , 7.0 , tol );\n    BOOST_CHECK_CLOSE( y(7) , -8.0 , tol );\n    BOOST_CHECK_CLOSE( y(8) , 9.0 , tol );\n    BOOST_CHECK_CLOSE( y(9) , -10.0 , tol );\n  }\n  {\n    ublas::vector<double>  y;\n    y = x;\n    OpenTissue::math::optimization::Projection<double, bound_function> P(lower,upper);\n    P(x,y);\n    BOOST_CHECK_CLOSE( y(0) , 1.0 , tol );\n    BOOST_CHECK_CLOSE( y(1) , -2.0 , tol );\n    BOOST_CHECK_CLOSE( y(2) , 3.0 , tol );\n    BOOST_CHECK_CLOSE( y(3) , -4.0 , tol );\n    BOOST_CHECK_CLOSE( y(4) , 5.0 , tol );\n    BOOST_CHECK_CLOSE( y(5) , -6.0 , tol );\n    BOOST_CHECK_CLOSE( y(6) , 7.0 , tol );\n    BOOST_CHECK_CLOSE( y(7) , -8.0 , tol );\n    BOOST_CHECK_CLOSE( y(8) , 9.0 , tol );\n    BOOST_CHECK_CLOSE( y(9) , -10.0 , tol );\n  }\n  {\n    ublas::vector<double>  y;\n    y = x;\n    OpenTissue::math::optimization::Projection<double, bound_function> P(lower,upper);\n    P(y);\n    BOOST_CHECK_CLOSE( y(0) , 1.0 , tol );\n    BOOST_CHECK_CLOSE( y(1) , -2.0 , tol );\n    BOOST_CHECK_CLOSE( y(2) , 3.0 , tol );\n    BOOST_CHECK_CLOSE( y(3) , -4.0 , tol );\n    BOOST_CHECK_CLOSE( y(4) , 5.0 , tol );\n    BOOST_CHECK_CLOSE( y(5) , -6.0 , tol );\n    BOOST_CHECK_CLOSE( y(6) , 7.0 , tol );\n    BOOST_CHECK_CLOSE( y(7) , -8.0 , tol );\n    BOOST_CHECK_CLOSE( y(8) , 9.0 , tol );\n    BOOST_CHECK_CLOSE( y(9) , -10.0 , tol );\n  }\n  {\n    ublas::vector<double>  y;\n    y = x;\n    OpenTissue::math::optimization::NoProjection<double> P;\n    P(x,y);\n    BOOST_CHECK_CLOSE( y(0) , x(0) , tol );\n    BOOST_CHECK_CLOSE( y(1) , x(1) , tol );\n    BOOST_CHECK_CLOSE( y(2) , x(2) , tol );\n    BOOST_CHECK_CLOSE( y(3) , x(3) , tol );\n    BOOST_CHECK_CLOSE( y(4) , x(4) , tol );\n    BOOST_CHECK_CLOSE( y(5) , x(5) , tol );\n    BOOST_CHECK_CLOSE( y(6) , x(6) , tol );\n    BOOST_CHECK_CLOSE( y(7) , x(7) , tol );\n    BOOST_CHECK_CLOSE( y(8) , x(8) , tol );\n    BOOST_CHECK_CLOSE( y(9) , x(9) , tol );\n  }\n  {\n    ublas::vector<double>  y;\n    y = x;\n    OpenTissue::math::optimization::NoProjection<double> P;\n    P(y);\n    BOOST_CHECK_CLOSE( y(0) , x(0) , tol );\n    BOOST_CHECK_CLOSE( y(1) , x(1) , tol );\n    BOOST_CHECK_CLOSE( y(2) , x(2) , tol );\n    BOOST_CHECK_CLOSE( y(3) , x(3) , tol );\n    BOOST_CHECK_CLOSE( y(4) , x(4) , tol );\n    BOOST_CHECK_CLOSE( y(5) , x(5) , tol );\n    BOOST_CHECK_CLOSE( y(6) , x(6) , tol );\n    BOOST_CHECK_CLOSE( y(7) , x(7) , tol );\n    BOOST_CHECK_CLOSE( y(8) , x(8) , tol );\n    BOOST_CHECK_CLOSE( y(9) , x(9) , tol );\n  }\n}\n\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_projection);\n\nBOOST_AUTO_TEST_CASE(test_case)\n{\n  ublas::vector<double> lower;\n  ublas::vector<double> upper;\n  ublas::vector<double> x;\n\n  lower.resize(10,false);\n  upper.resize(10,false);\n  x.resize(10,false);\n\n  upper(0) = 1.0;\n  upper(1) = 2.0;\n  upper(2) = 3.0;\n  upper(3) = 4.0;\n  upper(4) = 5.0;\n  upper(5) = 6.0;\n  upper(6) = 7.0;\n  upper(7) = 8.0;\n  upper(8) = 9.0;\n  upper(9) = 10.0;\n\n  lower = -upper;\n\n  x(0) =  2.0;\n  x(1) = -3.0;\n  x(2) =  4.0;\n  x(3) = -5.0;\n  x(4) =  6.0;\n  x(5) = -7.0;\n  x(6) =  8.0;\n  x(7) = -9.0;\n  x(8) =  10.0;\n  x(9) = -11.0;\n\n  test_projection( \n    OpenTissue::math::optimization::make_constant_bounds( lower )\n    , OpenTissue::math::optimization::make_constant_bounds( upper )\n    , x\n    );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "1f5d5138ae006e4c97d4bca5ee9495bb8c358450", "size": 5083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/projection/src/unit_projection.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/projection/src/unit_projection.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/projection/src/unit_projection.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 30.255952381, "max_line_length": 121, "alphanum_fraction": 0.6049577021, "num_tokens": 1805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5832368914479045}}
{"text": "#include <AES.h>\r\n#include <NTL/ZZ.h>\r\n#include <RSA.h>\r\n#include <UI.h>\r\n#include <iostream>\r\nusing namespace std;\r\nusing namespace NTL;\r\nvoid saveRSAKey(int bits) {\r\n\tui::printTitle(\"  \u751f\u6210RSA\u5bc6\u94a5  \");\r\n\r\n\tcout << endl << \"\u751f\u6210\u5bc6\u94a5\u4e2d\u2026\u2026\" << endl;\r\n\tRSA::privateKey priK;\r\n\tRSA::publicKey pubK;\r\n\tRSA::makeKey(priK, pubK, bits);\r\n\r\n\tcout << endl;\r\n\tcout << \"private key:\" << endl << endl;\r\n\tcout << \"p=\" << priK.p << endl << endl;\r\n\tcout << \"q=\" << priK.q << endl << endl;\r\n\tcout << \"d=\" << priK.d << endl << endl;\r\n\tcout << endl;\r\n\tcout << \"public key:\" << endl << endl;\r\n\tcout << \"n=\" << pubK.n << endl << endl;\r\n\tcout << \"e=\" << pubK.e << endl << endl;\r\n\tcout << endl;\r\n\tui::pause(\"\\n\u4efb\u610f\u952e\u7ee7\u7eed\u2026\u2026\");\r\n\tui::OptionC opt[] = {{'1', \"\u4fdd\u5b58\u5230\u6587\u4ef6\"}, {'0', \"\u4e0d\u4fdd\u5b58\"}, ui::END_OPTC};\r\n\tui::showOptionC(opt);\r\n\tint choice = ui::inputOptionC(opt);\r\n\tif (opt[choice].c == '1') {\r\n\t\tstring priFile = \"rsa.pri\", pubFile = \"rsa.pub\";\r\n\t\tcout << \"\u8bf7\u8f93\u5165\u79c1\u94a5\u6587\u4ef6\u6587\u4ef6\u540d\uff08\u9ed8\u8ba4 rsa.pri \uff09\uff1a\" << endl;\r\n\t\tui::getLine(priFile, \"rsa.pri\");\r\n\t\tcout << \"\u8bf7\u8f93\u5165\u516c\u94a5\u6587\u4ef6\u6587\u4ef6\u540d\uff08\u9ed8\u8ba4 rsa.pub \uff09\uff1a\" << endl;\r\n\t\tui::getLine(pubFile, \"rsa.pub\");\r\n\t\tRSA::savePublicKey(pubK, pubFile);\r\n\t\tRSA::savePrivateKey(priK, priFile);\r\n\t}\r\n\treturn;\r\n}\r\n\r\nvoid makeRSAKey() {\r\n\tui::printTitle(\"  \u9009\u62e9\u751f\u6210\u5bc6\u94a5\u4f4d\u6570  \");\r\n\tui::OptionC const opt[] = {\r\n\t\t{'1', \"512\"}, {'2', \"1024\"}, {'0', \"\u79bb\u5f00\"}, ui::END_OPTC};\r\n\tui::showOptionC(opt);\r\n\tint choice = ui::inputOptionC(opt);\r\n\tif (opt[choice].c == '0')\r\n\t\treturn;\r\n\r\n\tint m;\r\n\tif (opt[choice].c == '1')\r\n\t\tm = 512;\r\n\tif (opt[choice].c == '2')\r\n\t\tm = 1024;\r\n\tsaveRSAKey(m);\r\n\treturn;\r\n}\r\nvoid title() {\r\n\tui::OptionC const opt[] = {{'1', \"\u751f\u6210RSA\u5bc6\u94a5\"}, {'2', \"\u6587\u4ef6\u52a0\u5bc6\"},\r\n\t\t\t\t\t\t\t   {'3', \"\u6587\u4ef6\u89e3\u5bc6\"},\r\n\t\t\t\t\t\t\t   {'0', \"\u79bb\u5f00\"},\t\t ui::END_OPTC};\r\n\twhile (1) {\r\n\t\tui::printTitle(\"  AES\u52a0\u5bc6\u5de5\u5177  \");\r\n\t\tui::showOptionC(opt);\r\n\t\tint choice = ui::inputOptionC(opt);\r\n\t\tif (opt[choice].c == '0')\r\n\t\t\tbreak;\r\n\t\tif (opt[choice].c == '1')\r\n\t\t\tmakeRSAKey();\r\n\t\tif (opt[choice].c == '2')\r\n\t\t\tAES::encipher();\r\n\t\tif (opt[choice].c == '3')\r\n\t\t\tAES::decipher();\r\n\t}\r\n\treturn;\r\n}\r\n\r\nint main() {\r\n\tui::setcoder(\"utf-8\");\r\n\ttitle();\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "9a51913b2b4b23dff9e158854e6ae30e6a2385b1", "size": 2060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "EUye9IM/Block_cipher", "max_stars_repo_head_hexsha": "6527330ceb6d92ca3f9a7069a449bca850de329d", "max_stars_repo_licenses": ["MIT"], "max_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": "EUye9IM/Block_cipher", "max_issues_repo_head_hexsha": "6527330ceb6d92ca3f9a7069a449bca850de329d", "max_issues_repo_licenses": ["MIT"], "max_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": "EUye9IM/Block_cipher", "max_forks_repo_head_hexsha": "6527330ceb6d92ca3f9a7069a449bca850de329d", "max_forks_repo_licenses": ["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.5238095238, "max_line_length": 67, "alphanum_fraction": 0.5310679612, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.5832368899711626}}
{"text": "#include \"sco/optimizers.hpp\"\n#include \"sco/solver_interface.hpp\"\n#include \"sco/expr_op_overloads.hpp\"\n#include \"sco/modeling_utils.hpp\"\n#include \"sco/sco_common.hpp\"\n#include \"utils/logging.hpp\"\n#include <cmath>\n#include <boost/assign/list_of.hpp>\n#include <boost/format.hpp>\n#include <iostream>\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n#include <sstream>\n#include \"utils/stl_to_string.hpp\"\nusing namespace util;\nusing namespace std;\nusing namespace boost::assign;\nusing namespace sco;\nusing namespace Eigen;\n\n\n\nvoid setupProblem(OptProbPtr& probptr, size_t nvars) {\n  probptr.reset(new OptProb());\n  vector<string> var_names;\n  for (size_t i=0; i < nvars; ++i) {\n    var_names.push_back( (boost::format(\"x_%i\")%i).str() );\n  }\n  probptr->createVariables(var_names);\n}\n\n\nvoid expectAllNear(const DblVec& x, const DblVec& y, double abstol) {\n  EXPECT_EQ(x.size(), y.size());\n  stringstream ss;\n  LOG_INFO(\"checking %s ?= %s\", CSTR(x), CSTR(y));\n  for (size_t i=0; i < x.size(); ++i) EXPECT_NEAR(x[i], y[i], abstol);\n}\n\ndouble f_QuadraticSeparable(const VectorXd& x) {\n  return x(0)*x(0) + sq(x(1) - 1) + sq(x(2)-2);\n}\nTEST(SQP, QuadraticSeparable)  {\n  // if the problem is exactly a QP, it should be solved in one iteration\n  OptProbPtr prob;\n  setupProblem(prob, 3);\n  prob->addCost(CostPtr(new CostFromFunc(ScalarOfVector::construct(&f_QuadraticSeparable), prob->getVars(), \"f\")));\n  BasicTrustRegionSQP solver(prob);\n  solver.trust_box_size_ = 100;\n  vector<double> x = list_of(3)(4)(5);\n  solver.initialize(x);\n  OptStatus status = solver.optimize();\n  ASSERT_EQ(status, OPT_CONVERGED);\n  expectAllNear(solver.x(), list_of(0)(1)(2), 1e-3);\n  // todo: checks on number of iterations and function evaluates\n}\ndouble f_QuadraticNonseparable(const VectorXd& x) {\n  return sq(x(0) - x(1) + 3*x(2)) + sq(x(0)-1) + sq(x(2) - 2);\n}\nTEST(SQP, QuadraticNonseparable)  {\n  OptProbPtr prob;\n  setupProblem(prob, 3);\n  prob->addCost(CostPtr(new CostFromFunc(ScalarOfVector::construct(&f_QuadraticNonseparable), prob->getVars(), \"f\",  true)));\n  BasicTrustRegionSQP solver(prob);\n  solver.trust_box_size_ = 100;\n  solver.min_trust_box_size_ = 1e-5;\n  solver.min_approx_improve_ = 1e-6;\n  vector<double> x = list_of(3)(4)(5);\n  solver.initialize(x);\n  OptStatus status = solver.optimize();\n  ASSERT_EQ(status, OPT_CONVERGED);\n  expectAllNear(solver.x(), list_of(1)(7)(2), .01);\n  // todo: checks on number of iterations and function evaluates\n}\n\n\nvoid testProblem(ScalarOfVectorPtr f, VectorOfVectorPtr g, ConstraintType cnt_type,\n  const DblVec& init, const DblVec& sol) {\n    OptProbPtr prob;\n    size_t n = init.size();\n    assert (sol.size() == n);\n    setupProblem(prob, n);\n    prob->addCost(CostPtr(new CostFromFunc(f, prob->getVars(), \"f\", true)));\n    prob->addConstraint(ConstraintPtr(new ConstraintFromFunc(g, prob->getVars(), VectorXd(), cnt_type,\"g\")));\n    BasicTrustRegionSQP solver(prob);\n    solver.max_iter_ = 1000;\n    solver.min_trust_box_size_ = 1e-5;\n    solver.min_approx_improve_ = 1e-10;\n    solver.merit_error_coeff_ = 1;\n    \n    solver.initialize(init);\n    OptStatus status = solver.optimize();\n    EXPECT_EQ(status, OPT_CONVERGED);\n    expectAllNear(solver.x(), sol, .01);\n}\n// http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf\n\ndouble f_TP1(const VectorXd& x) {\n  return 1*sq(x(1)-sq(x(0))) + sq(1-x(0));\n}\nVectorXd g_TP1(const VectorXd& x) {\n  VectorXd out(1);\n  out(0) = -1.5 - x(1);\n  return out;\n}\ndouble f_TP2(const VectorXd& x) {\n  return 100*sq(x(1)-sq(x(0))) + sq(1-x(0));\n}\nVectorXd g_TP2(const VectorXd& x) {\n  VectorXd out(1);\n  out(0) = -1.5 - x(1);\n  return out;\n}\ndouble f_TP3(const VectorXd& x) {\n  return (x(1) + 1e-5 * sq(x(1)-x(0)));\n}\nVectorXd g_TP3(const VectorXd& x) {\n  VectorXd out(1);\n  out(0) = 0 - x(1);\n  return out;\n}\ndouble f_TP6(const VectorXd& x) {\n  return sq(1-x(0));\n}\nVectorXd g_TP6(const VectorXd& x) {\n  VectorXd out(1);\n  out(0) = 10*(x(1)-sq(x(0)));\n  return out;\n}\ndouble f_TP7(const VectorXd& x) {\n  return log(1+sq(x(0))) - x(1);\n}\nVectorXd g_TP7(const VectorXd& x) {\n  VectorXd out(1);\n  out(0) = sq(1+sq(x(0))) + sq(x(1)) - 4;\n  return out;\n}\n\nTEST(SQP, TP1) {\n  testProblem(ScalarOfVector::construct(&f_TP1), VectorOfVector::construct(&g_TP1), INEQ, list_of(-2)(1), list_of(1)(1));\n}\nTEST(SQP, TP3) {\n  testProblem(ScalarOfVector::construct(&f_TP3), VectorOfVector::construct(&g_TP3), INEQ, list_of(10)(1), list_of(0)(0));\n}\nTEST(SQP, TP6) {\n  testProblem(ScalarOfVector::construct(&f_TP6), VectorOfVector::construct(&g_TP6), EQ, list_of(10)(1), list_of(1)(1));\n}\nTEST(SQP, TP7) {\n  testProblem(ScalarOfVector::construct(&f_TP7), VectorOfVector::construct(&g_TP7), EQ, list_of(2)(2), list_of(0.)(sqrtf(3.)));\n}\n", "meta": {"hexsha": "43a573599dc4697dcaf690578900a19f2c49d73a", "size": 4687, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sco/test/small-problems-unit.cpp", "max_stars_repo_name": "HARPLab/trajopt", "max_stars_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 250.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T04:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T15:52:54.000Z", "max_issues_repo_path": "src/sco/test/small-problems-unit.cpp", "max_issues_repo_name": "HARPLab/trajopt", "max_issues_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-08-19T13:14:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T08:08:26.000Z", "max_forks_repo_path": "src/sco/test/small-problems-unit.cpp", "max_forks_repo_name": "HARPLab/trajopt", "max_forks_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 118.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T11:44:00.000Z", "avg_line_length": 31.0397350993, "max_line_length": 127, "alphanum_fraction": 0.6820994239, "num_tokens": 1536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.5832368899711626}}
{"text": "#include <iostream>\n#include <pcl/console/parse.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/sample_consensus/ransac.h>\n#include <pcl/sample_consensus/sac_model_plane.h>\n#include <pcl/sample_consensus/sac_model_sphere.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <boost/thread/thread.hpp>\n\nboost::shared_ptr<pcl::visualization::PCLVisualizer>\nsimpleVis(pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud) {\n    // --------------------------------------------\n    // -----Open 3D viewer and add point cloud-----\n    // --------------------------------------------\n    boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer(\n        new pcl::visualization::PCLVisualizer(\"3D Viewer\"));\n    viewer->setBackgroundColor(0, 0, 0);\n    viewer->addPointCloud<pcl::PointXYZ>(cloud, \"sample cloud\");\n    viewer->setPointCloudRenderingProperties(\n        pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, \"sample cloud\");\n    // viewer->addCoordinateSystem (1.0);\n    viewer->initCameraParameters();\n    return (viewer);\n}\n\nint main(int argc, char **argv) {\n    // initialize PointClouds\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(\n        new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::PointCloud<pcl::PointXYZ>::Ptr final(\n        new pcl::PointCloud<pcl::PointXYZ>);\n\n    // populate our PointCloud with points\n    cloud->width = 500;\n    cloud->height = 1;\n    cloud->is_dense = false;\n    cloud->points.resize(cloud->width * cloud->height);\n    for (size_t i = 0; i < cloud->points.size(); ++i) {\n        if (pcl::console::find_argument(argc, argv, \"-s\") >= 0 ||\n            pcl::console::find_argument(argc, argv, \"-sf\") >= 0) {\n            cloud->points[i].x = 1024 * rand() / (RAND_MAX + 1.0);\n            cloud->points[i].y = 1024 * rand() / (RAND_MAX + 1.0);\n            if (i % 5 == 0)\n                cloud->points[i].z = 1024 * rand() / (RAND_MAX + 1.0);\n            else if (i % 2 == 0)\n                cloud->points[i].z =\n                    sqrt(1 - (cloud->points[i].x * cloud->points[i].x) -\n                         (cloud->points[i].y * cloud->points[i].y));\n            else\n                cloud->points[i].z =\n                    -sqrt(1 - (cloud->points[i].x * cloud->points[i].x) -\n                          (cloud->points[i].y * cloud->points[i].y));\n        } else {\n            cloud->points[i].x = 1024 * rand() / (RAND_MAX + 1.0);\n            cloud->points[i].y = 1024 * rand() / (RAND_MAX + 1.0);\n            if (i % 2 == 0)\n                cloud->points[i].z = 1024 * rand() / (RAND_MAX + 1.0);\n            else\n                cloud->points[i].z =\n                    -1 * (cloud->points[i].x + cloud->points[i].y);\n        }\n    }\n\n    std::vector<int> inliers;\n\n    // created RandomSampleConsensus object and compute the appropriated model\n    pcl::SampleConsensusModelSphere<pcl::PointXYZ>::Ptr model_s(\n        new pcl::SampleConsensusModelSphere<pcl::PointXYZ>(cloud));\n    pcl::SampleConsensusModelPlane<pcl::PointXYZ>::Ptr model_p(\n        new pcl::SampleConsensusModelPlane<pcl::PointXYZ>(cloud));\n    if (pcl::console::find_argument(argc, argv, \"-f\") >= 0) {\n        pcl::RandomSampleConsensus<pcl::PointXYZ> ransac(model_p);\n        ransac.setDistanceThreshold(.01);\n        ransac.computeModel();\n        ransac.getInliers(inliers);\n    } else if (pcl::console::find_argument(argc, argv, \"-sf\") >= 0) {\n        pcl::RandomSampleConsensus<pcl::PointXYZ> ransac(model_s);\n        ransac.setDistanceThreshold(.01);\n        ransac.computeModel();\n        ransac.getInliers(inliers);\n    }\n\n    // copies all inliers of the model computed to another PointCloud\n    pcl::copyPointCloud<pcl::PointXYZ>(*cloud, inliers, *final);\n\n    // creates the visualization object and adds either our orignial cloud or\n    // all of the inliers depending on the command line arguments specified.\n    boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;\n    if (pcl::console::find_argument(argc, argv, \"-f\") >= 0 ||\n        pcl::console::find_argument(argc, argv, \"-sf\") >= 0)\n        viewer = simpleVis(final);\n    else\n        viewer = simpleVis(cloud);\n    while (!viewer->wasStopped()) {\n        viewer->spinOnce(100);\n        boost::this_thread::sleep(boost::posix_time::microseconds(100000));\n    }\n    return 0;\n}\n", "meta": {"hexsha": "a72adbceb433092e481f9734d1e558e3ee0e4330", "size": 4329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/tutorials/content/sources/random_sample_consensus/random_sample_consensus.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": "doc/tutorials/content/sources/random_sample_consensus/random_sample_consensus.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": "doc/tutorials/content/sources/random_sample_consensus/random_sample_consensus.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": 42.4411764706, "max_line_length": 78, "alphanum_fraction": 0.5920535921, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.5832368879781985}}
{"text": "#include <ros/ros.h>\n#include <pcl_ros/point_cloud.h>\n#include <pcl_msgs/ModelCoefficients.h>\n#include <visualization_msgs/Marker.h>\n\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/common/transforms.h>\n\n#include <tf/transform_broadcaster.h>\n#include <tf_conversions/tf_eigen.h>\n#include <Eigen/Dense>\n\nros::Publisher obst_cluster_pub;\nros::Publisher model_pub;\nbool visualize = true;\n\ntf::Transform ros_tf;   // Transform to publish\n\nvoid pointCloudCallback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr& msg)\n{\n    // Create the segmentation object\n    pcl::SACSegmentation<pcl::PointXYZ> seg;\n    seg.setOptimizeCoefficients (true);\n    seg.setModelType (pcl::SACMODEL_PLANE);\n    seg.setMethodType (pcl::SAC_RANSAC);\n    seg.setDistanceThreshold (0.1);\n    seg.setInputCloud (msg);\n\n    // Coefficients of plane equation ax + by + cz + d = 0\n    pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients);\n    // Indices of points in the plane\n    pcl::PointIndices::Ptr inliers (new pcl::PointIndices);\n    seg.segment (*inliers, *coefficients);\n\n    // Output error if the plane found is less than 1/3 of the point cloud\n    if (inliers->indices.size() < msg->points.size()/3.0)\n        PCL_ERROR (\"Could not estimate a planar model for the given dataset.\\n\");\n    else\n    {\n        float a = coefficients->values[0];\n        float b = coefficients->values[1];\n        float c = coefficients->values[2];\n        float d = coefficients->values[3];\n        if (visualize)\n        {\n            // Publish plane visualization\n            visualization_msgs::Marker plane_points;\n            plane_points.type = visualization_msgs::Marker::SPHERE_LIST;\n            plane_points.header.frame_id = \"/stereo_camera\";\n            plane_points.header.stamp = ros::Time::now();\n            plane_points.id = 0;\n            plane_points.color.r = 0.0f;\n            plane_points.color.g = 1.0f;\n            plane_points.color.b = 0.0f;\n            plane_points.color.a = 1.0;\n            plane_points.scale.x = 0.02;\n            plane_points.scale.y = 0.02;\n            plane_points.scale.z = 0.02;\n            plane_points.action = visualization_msgs::Marker::ADD;\n\n            for(float x = -5; x < 5; x += 0.05)\n            {\n                for(float y = 0; y < 5; y += 0.05)\n                {\n                    float z = (-a*x - b*y - d)/c;\n                    geometry_msgs::Point p;\n                    p.x = x;\n                    p.y = y;\n                    p.z = z;\n                    plane_points.points.push_back(p);\n                }\n            }\n\n            obst_cluster_pub.publish(plane_points);\n        }\n\n        // Publish coefficients\n        pcl_msgs::ModelCoefficients ros_coeff;\n        pcl_conversions::fromPCL(*coefficients, ros_coeff);\n        model_pub.publish(ros_coeff);\n\n        // Calculate angle between the point-cloud ground plane and the world xy plane\n        Eigen::Matrix<double, 1, 3> pcl_plane_normal, world_xy_normal, rotation_vector;\n        pcl_plane_normal[0] = a;\n        pcl_plane_normal[1] = b;\n        pcl_plane_normal[2] = c;\n        world_xy_normal[0] = 0.0;\n        world_xy_normal[1] = 0.0;\n        world_xy_normal[2] = 1.0;\n\n        rotation_vector = (pcl_plane_normal.cross(world_xy_normal)).normalized();\n        double theta = acos(pcl_plane_normal.dot(world_xy_normal)/sqrt(a*a + b*b + c*c));\n\n        // Use the angle to create an affine transform\n        Eigen::Affine3d tf_ground_plane = Eigen::Affine3d::Identity();\n        tf_ground_plane.rotate(Eigen::AngleAxisd(theta, rotation_vector));\n\n        // Apply the affine transform to the ground plane to determine translation\n        Eigen::Vector4d original, transformed;\n        original[0] = a*d;\n        original[1] = b*d;\n        original[2] = c*d;\n        original[3] = 1.0;\n        transformed = tf_ground_plane * original;\n        tf_ground_plane.translation() << transformed[0], transformed[1], transformed[2];\n\n        // Convert Eigen Affine transform to a ROS transform\n        tf::transformEigenToTF(tf_ground_plane, ros_tf);\n    }\n\n    // Publish ROS transform\n    static tf::TransformBroadcaster transform_br;\n    transform_br.sendTransform(tf::StampedTransform(ros_tf, ros::Time::now(), \"world\", \"stereo_camera\"));\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"ground_plane\");\n    ros::NodeHandle n;\n\n    ros::param::get(\"~visualize\", visualize);\n\n    ros::Subscriber sub = n.subscribe<pcl::PointCloud<pcl::PointXYZ> >(\"/points2\", 1, pointCloudCallback);\n    model_pub = n.advertise<pcl_msgs::ModelCoefficients> (\"ground_plane/model_coefficients\", 1);\n    if(visualize)\n        obst_cluster_pub = n.advertise<visualization_msgs::Marker> (\"ground_plane/visual_markers\", 1);\n\n    ros::spin();\n\n    return 0;\n}\n", "meta": {"hexsha": "7c290bfd6292135bc04271295b1b6164c0585422", "size": 4778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ground_plane.cpp", "max_stars_repo_name": "lazim2142/carrt_goggles", "max_stars_repo_head_hexsha": "863d2a07329c353655433a589342e9a8706b186e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-07T03:39:57.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-07T03:39:57.000Z", "max_issues_repo_path": "src/ground_plane.cpp", "max_issues_repo_name": "lazim2142/carrt_goggles", "max_issues_repo_head_hexsha": "863d2a07329c353655433a589342e9a8706b186e", "max_issues_repo_licenses": ["MIT"], "max_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_plane.cpp", "max_forks_repo_name": "lazim2142/carrt_goggles", "max_forks_repo_head_hexsha": "863d2a07329c353655433a589342e9a8706b186e", "max_forks_repo_licenses": ["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.196969697, "max_line_length": 106, "alphanum_fraction": 0.6268313102, "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5832368850247156}}
{"text": "#pragma once\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n\n#include <eigen_conversions/eigen_msg.h>\n#include <Eigen/StdVector>\n#include <Eigen/SVD>\n\n#include <boost/foreach.hpp>\n\n#include <opencv2/opencv.hpp>\n\n#include <image_geometry/pinhole_camera_model.h>\n#include <image_transport/image_transport.h>\n#include <sensor_msgs/image_encodings.h>\n#include <ros/ros.h>\n\n// #define SEGMENTATION_DEBUG\n\nnamespace nav {\n\n/// UTILS\n\ntemplate <typename _Matrix_Type_>\nbool pseudoInverse(\n    const _Matrix_Type_ &a, _Matrix_Type_ &result,\n    double epsilon =\n        std::numeric_limits<typename _Matrix_Type_::Scalar>::epsilon());\n\ntypedef std::vector<cv::Point> Contour;\n\n// Compute the centroid of an OpenCV contour (Not templated)\ncv::Point contour_centroid(Contour &contour);\n\n// Used as a comparison function for std::sort(), sorting in order of decreasing\n// perimeters\n// returns true if the contourArea(c1) > contourArea(c2)\nbool larger_contour(const Contour &c1, const Contour &c2);\n\n// Filter a histogram of type cv::MatND generated by cv::calcHist using a\n// gaussian kernel\ncv::MatND smooth_histogram(const cv::MatND &histogram,\n                           size_t filter_kernel_size = 3, float sigma = 1.0);\n\n// Generate a one-dimensional gaussian kernel given a kernel size and it's\n// standard deviation\n// (sigma)\nstd::vector<float> generate_gaussian_kernel_1D(size_t kernel_size = 3,\n                                               float sigma = 1.0);\n\n// Finds positive local maxima greater than (global maximum * thresh_multiplier)\nstd::vector<cv::Point> find_local_maxima(const cv::MatND &histogram,\n                                         float thresh_multiplier);\n\n// Finds negative local minima less than (global minimum * thresh_multiplier)\nstd::vector<cv::Point> find_local_minima(const cv::MatND &histogram,\n                                         float thresh_multiplier);\n\n// Selects the mode of a multi-modal distribution closest to a given target\n// value\nunsigned int select_hist_mode(std::vector<cv::Point> &histogram_modes,\n                              unsigned int target);\n\n// Takes in a grayscale image and segments out a semi-homogenous foreground\n// object with pixel intensities close to <target>. Tuning of last three \n// parameters may imrove results but default values should work well in \n// most cases.\nvoid statistical_image_segmentation(const cv::Mat &src, cv::Mat &dest,\n                                    cv::Mat &debug_img, const int hist_size,\n                                    const float **ranges, const int target,\n                                    std::string image_name = \"Unnamed Image\",\n                                    bool ret_dbg_img = false,\n                                    const float sigma = 1.5,\n                                    const float low_thresh_gain = 0.5,\n                                    const float high_thresh_gain = 0.5);\n\ncv::Mat triangulate_Linear_LS(cv::Mat mat_P_l, cv::Mat mat_P_r,\n                              cv::Mat undistorted_l, cv::Mat undistorted_r);\n\nEigen::Vector3d kanatani_triangulation(const cv::Point2d &pt1,\n                                       const cv::Point2d &pt2,\n                                       const Eigen::Matrix3d &essential,\n                                       const Eigen::Matrix3d &R);\n\nEigen::Vector3d lindstrom_triangulation(const cv::Point2d &pt1,\n                                        const cv::Point2d &pt2,\n                                        const Eigen::Matrix3d &essential,\n                                        const Eigen::Matrix3d &R);\n\nstruct ImageWithCameraInfo {\n  /**\n          Packages corresponding  sensor_msgs::ImageConstPtr and\n     sensor_msgs::CameraInfoConstPtr\n     info_msg\n          into one object. Containers of these objects can be sorted by their\n     image_time attribute\n  */\npublic:\n  ImageWithCameraInfo() {}\n  ImageWithCameraInfo(sensor_msgs::ImageConstPtr _image_msg_ptr,\n                      sensor_msgs::CameraInfoConstPtr _info_msg_ptr);\n  sensor_msgs::ImageConstPtr image_msg_ptr;\n  sensor_msgs::CameraInfoConstPtr info_msg_ptr;\n  ros::Time image_time;\n  bool operator<(const ImageWithCameraInfo &right) const {\n    return this->image_time < right.image_time;\n  }\n};\n\nclass FrameHistory {\n  /**\n          Object that subscribes itself to an image topic and stores up to a\n     user defined\n          number of ImageWithCameraInfo objects. The frame history can then be\n     retrieved\n          in whole or just a portion.\n  */\npublic:\n  FrameHistory(std::string img_topic, unsigned int hist_size);\n  ~FrameHistory();\n  void image_callback(const sensor_msgs::ImageConstPtr &image_msg,\n                      const sensor_msgs::CameraInfoConstPtr &info_msg);\n  std::vector<ImageWithCameraInfo>\n  get_frame_history(unsigned int frames_requested);\n  int frames_available();\n\n  const std::string topic_name;\n  const size_t history_size;\n\nprivate:\n  ros::NodeHandle nh;\n  image_transport::CameraSubscriber _image_sub;\n  image_transport::ImageTransport _image_transport;\n  std::vector<ImageWithCameraInfo> _frame_history_ring_buffer;\n  size_t frame_count;\n};\n\n/// Param Helpers\n\nstruct Range {\n  cv::Scalar lower;\n  cv::Scalar upper;\n};\n\nvoid range_from_param(std::string &param_root, Range &range);\n\nvoid inParamRange(cv::Mat &src, Range &range, cv::Mat &dest);\n\n/// Templated pseudoinverse function implementation\ntemplate <typename _Matrix_Type_>\nbool pseudoInverse(\n    const _Matrix_Type_ &a, _Matrix_Type_ &result,\n    double epsilon =\n        std::numeric_limits<typename _Matrix_Type_::Scalar>::epsilon()) {\n  if (a.rows() < a.cols())\n    return false;\n\n  Eigen::JacobiSVD<_Matrix_Type_> svd = a.jacobiSvd();\n\n  typename _Matrix_Type_::Scalar tolerance =\n      epsilon * std::max(a.cols(), a.rows()) *\n      svd.singularValues().array().abs().maxCoeff();\n\n  result = svd.matrixV() *\n           _Matrix_Type_(\n               _Matrix_Type_((svd.singularValues().array().abs() > tolerance)\n                                 .select(svd.singularValues().array().inverse(),\n                                         0)).diagonal()) *\n           svd.matrixU().adjoint();\n}\n} // namespace sub\n", "meta": {"hexsha": "f666948163c395833ada81124c09317175d05744", "size": 6253, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "perception/navigator_vision/include/navigator_vision_lib/cv_tools.hpp", "max_stars_repo_name": "saltyan007/kill_test", "max_stars_repo_head_hexsha": "a641dd74bae38122c3a044ef11cd445042d85e2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "perception/navigator_vision/include/navigator_vision_lib/cv_tools.hpp", "max_issues_repo_name": "saltyan007/kill_test", "max_issues_repo_head_hexsha": "a641dd74bae38122c3a044ef11cd445042d85e2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perception/navigator_vision/include/navigator_vision_lib/cv_tools.hpp", "max_forks_repo_name": "saltyan007/kill_test", "max_forks_repo_head_hexsha": "a641dd74bae38122c3a044ef11cd445042d85e2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-29T12:24:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T12:24:15.000Z", "avg_line_length": 35.1292134831, "max_line_length": 80, "alphanum_fraction": 0.6473692628, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5832368835479737}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2016 Oracle and/or its affiliates.\r\n// Contributed and/or modified by Vissarion Fisikopoulos, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <algorithms/test_length.hpp>\r\n#include <algorithms/length/linestring_cases.hpp>\r\n\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/adapted/std_pair_as_segment.hpp>\r\n\r\n#include <test_geometries/all_custom_linestring.hpp>\r\n#include <test_geometries/wrapped_boost_array.hpp>\r\n\r\ntemplate <typename P>\r\nvoid test_all_default() //test the default strategy\r\n{\r\n    double const pi = boost::math::constants::pi<double>();\r\n\r\n    for(std::size_t i = 0; i < 2; ++i)\r\n    {\r\n        test_geometry<bg::model::linestring<P> >(Ls_data_sph[i], 2 * pi);\r\n    }\r\n    // Geometries with length zero\r\n    test_geometry<P>(\"POINT(0 0)\", 0);\r\n    test_geometry<bg::model::polygon<P> >(\"POLYGON((0 0,0 1,1 1,1 0,0 0))\", 0);\r\n}\r\n\r\ntemplate <typename P>\r\nvoid test_all_haversine(double const mean_radius)\r\n{\r\n    double const pi = boost::math::constants::pi<double>();\r\n    bg::strategy::distance::haversine<float> haversine_strategy(mean_radius);\r\n\r\n    for(std::size_t i = 0; i < 2; ++i)\r\n    {\r\n        test_geometry<bg::model::linestring<P> >(Ls_data_sph[i],\r\n                                                 2 * pi * mean_radius,\r\n                                                 haversine_strategy);\r\n    }\r\n    // Geometries with length zero\r\n    test_geometry<P>(\"POINT(0 0)\", 0, haversine_strategy);\r\n    test_geometry<bg::model::polygon<P> >(\"POLYGON((0 0,0 1,1 1,1 0,0 0))\",\r\n                                          0, haversine_strategy);\r\n}\r\n\r\ntemplate <typename P>\r\nvoid test_empty_input()\r\n{\r\n    test_empty_input(bg::model::linestring<P>());\r\n    test_empty_input(bg::model::multi_linestring<P>());\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n    //Earth radius estimation in Km\r\n    //(see https://en.wikipedia.org/wiki/Earth_radius)\r\n    double const mean_radius = 6371.0;\r\n\r\n    test_all_default<bg::model::d2::point_xy<int,\r\n            bg::cs::spherical_equatorial<bg::degree> > >();\r\n    test_all_default<bg::model::d2::point_xy<float,\r\n            bg::cs::spherical_equatorial<bg::degree> > >();\r\n    test_all_default<bg::model::d2::point_xy<double,\r\n            bg::cs::spherical_equatorial<bg::degree> > >();\r\n\r\n    test_all_haversine<bg::model::d2::point_xy<int,\r\n        bg::cs::spherical_equatorial<bg::degree> > >(mean_radius);\r\n    test_all_haversine<bg::model::d2::point_xy<float,\r\n        bg::cs::spherical_equatorial<bg::degree> > >(mean_radius);\r\n    test_all_haversine<bg::model::d2::point_xy<double,\r\n        bg::cs::spherical_equatorial<bg::degree> > >(mean_radius);\r\n\r\n#if defined(HAVE_TTMATH)\r\n    test_all<bg::model::d2::point_xy<ttmath_big> >();\r\n#endif\r\n\r\n    //test_empty_input<bg::model::d2::point_xy<int> >();\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "f56da1cd73483e3afea409a990dce44a34454879", "size": 3147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/length/length_sph.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/length/length_sph.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/length/length_sph.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": 35.7613636364, "max_line_length": 80, "alphanum_fraction": 0.639656816, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.58323688155501}}
{"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": "// 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 <gtest/gtest.h>\n\n#include <Eigen/Sparse>\n\n#include \"smooth/optim.hpp\"\n#include \"smooth/so3.hpp\"\n\ntemplate<int N, int M>\nvoid run_leastsquares_test(bool zero_d, bool sing)\n{\n  // static\n  for (auto i = 0u; i != 10; ++i) {\n    Eigen::Matrix<double, M, N> J;\n    Eigen::Matrix<double, M, 1> r;\n    Eigen::Matrix<double, N, 1> d;\n\n    J.setRandom();\n    if (sing) {\n      J.col(N / 2).setZero();\n      J.row(M / 2).setZero();\n    }\n\n    d.setRandom();\n    d = (d + Eigen::Matrix<double, N, 1>::Ones()).cwiseMax(0);\n    if (zero_d) { d.setZero(); }\n\n    r.setRandom();\n\n    // solve static\n    Eigen::ColPivHouseholderQR<decltype(J)> J_qr(J);\n    auto a1 = smooth::detail::solve_ls<N, M>(J_qr, d, r);\n\n    // solve dynamic\n    Eigen::Matrix<double, -1, -1> Jd = J;\n    Eigen::Matrix<double, -1, 1> rd  = r;\n    Eigen::Matrix<double, -1, 1> dd  = d;\n    Eigen::ColPivHouseholderQR<decltype(Jd)> Jd_qr(Jd);\n    auto a2 = smooth::detail::solve_ls<-1, -1>(Jd_qr, dd, rd);\n\n    // solve sparse\n    Eigen::SparseMatrix<double> Jsp;\n    Jsp = J.sparseView();\n    Eigen::SparseQR<decltype(Jsp), Eigen::COLAMDOrdering<int>> Jsp_qr(Jsp);\n    auto a3 = smooth::detail::solve_ls<-1, -1>(Jsp_qr, dd, rd);\n\n    // solve for precise solution\n    Eigen::Matrix<double, N + M, N> lhs;\n    lhs.template topLeftCorner<M, N>()    = J;\n    lhs.template bottomLeftCorner<N, N>() = d.asDiagonal();\n\n    Eigen::Matrix<double, N + M, 1> rhs;\n    rhs.template head<M>() = -r;\n    rhs.template tail<N>().setZero();\n    Eigen::Matrix<double, N, 1> a_verif = lhs.fullPivHouseholderQr().solve(rhs);\n\n    // verify that all methods gave the same result\n    ASSERT_TRUE(a1.isApprox(a_verif));\n    ASSERT_TRUE(a2.isApprox(a_verif));\n    ASSERT_TRUE(a3.isApprox(a_verif));\n  }\n}\n\nTEST(Optimization, LeastSquares)\n{\n  run_leastsquares_test<1, 1>(false, false);\n  run_leastsquares_test<5, 1>(false, false);\n  run_leastsquares_test<5, 10>(false, false);\n  run_leastsquares_test<8, 16>(false, false);\n\n  run_leastsquares_test<1, 1>(false, true);\n  run_leastsquares_test<5, 1>(false, true);\n  run_leastsquares_test<5, 10>(false, true);\n  run_leastsquares_test<8, 16>(false, true);\n\n  run_leastsquares_test<1, 1>(true, false);\n  run_leastsquares_test<5, 10>(true, false);\n  run_leastsquares_test<8, 16>(true, false);\n\n  run_leastsquares_test<5, 10>(true, true);\n  run_leastsquares_test<8, 16>(true, true);\n}\n\nTEST(Optimization, LmPar)\n{\n  constexpr int M = 4, N = 4;\n  Eigen::Matrix<double, M, N> J;\n  Eigen::Matrix<double, M, 1> r;\n  Eigen::Matrix<double, N, 1> d;\n\n  double Delta = 1;\n\n  for (auto i = 0u; i != 10; ++i) {\n    J.setRandom();\n\n    d.setRandom();\n    d = d + Eigen::Matrix<double, N, 1>::Ones();\n\n    r.setRandom();\n\n    // solve static\n    auto [par1, x] = smooth::detail::lmpar<4, 4>(J, d, r, Delta);\n\n    // solve dynamic\n    Eigen::MatrixXd Jd = J;\n    Eigen::VectorXd rd = r;\n    Eigen::VectorXd dd = d;\n    auto [par2, xd]    = smooth::detail::lmpar<-1, -1>(Jd, dd, rd, Delta);\n\n    // solve sparse1\n    Eigen::SparseMatrix<double> Jsp;\n    Jsp               = J.sparseView();\n    auto [par3, xsp1] = smooth::detail::lmpar<-1, -1>(Jsp, dd, rd, Delta);\n\n    // solve sparse2\n    auto [par4, xsp2] = smooth::detail::lmpar_sparse(Jsp, dd, rd, Delta);\n\n    // check equality of static and dynamic\n    ASSERT_NEAR(par1, par2, 1e-10);\n    ASSERT_NEAR(par1, par3, 1e-10);\n    ASSERT_NEAR(par1, par4, 1e-10);\n    ASSERT_TRUE(x.isApprox(xd));\n    ASSERT_TRUE(x.isApprox(xsp1));\n    ASSERT_TRUE(x.isApprox(xsp2));\n\n    // check that x solves resulting problem\n    Eigen::ColPivHouseholderQR<decltype(J)> J_qr(J);\n    auto x_test = smooth::detail::solve_ls<N, N>(J_qr, sqrt(par1) * d, r);\n    ASSERT_TRUE(x_test.isApprox(x));\n\n    // check that parameter satisfies conditions\n    bool cond1 = (par1 == 0) && (d.asDiagonal() * x).norm() <= 1.1 * Delta;\n    bool cond2 = (par1 > 0) && std::abs((d.asDiagonal() * x).norm() - Delta) <= 0.1 * Delta;\n    ASSERT_TRUE(cond1 || cond2);\n  }\n}\n\nTEST(Optimization, LmParSmall)\n{\n  constexpr int M = 4, N = 4;\n  Eigen::Matrix<double, M, N> J;\n  Eigen::Matrix<double, M, 1> r;\n  Eigen::Matrix<double, N, 1> d;\n\n  double Delta = 0.1;\n  for (auto i = 0u; i != 10; ++i) {\n    J.setRandom();\n\n    d.setRandom();\n    d = d + Eigen::Matrix<double, N, 1>::Ones();\n\n    r.setRandom();\n\n    // solve static\n    auto [par1, x] = smooth::detail::lmpar<4, 4>(J, d, r, Delta);\n\n    // solve dynamic\n    Eigen::MatrixXd Jd = J;\n    Eigen::VectorXd rd = r;\n    Eigen::VectorXd dd = d;\n    auto [par2, xd]    = smooth::detail::lmpar<-1, -1>(Jd, dd, rd, Delta);\n\n    // solve sparse\n    Eigen::SparseMatrix<double> Jsp;\n    Jsp               = J.sparseView();\n    auto [par3, xsp1] = smooth::detail::lmpar<-1, -1>(Jsp, dd, rd, Delta);\n\n    // solve sparse2\n    auto [par4, xsp2] = smooth::detail::lmpar_sparse(Jsp, dd, rd, Delta);\n\n    // check equality of static and dynamic\n    ASSERT_NEAR(par1, par2, 1e-10);\n    ASSERT_NEAR(par1, par3, 1e-10);\n    ASSERT_NEAR(par1, par4, 1e-10);\n    ASSERT_TRUE(x.isApprox(xd));\n    ASSERT_TRUE(x.isApprox(xsp1));\n    ASSERT_TRUE(x.isApprox(xsp2));\n\n    // check that x solves resulting problem\n    Eigen::ColPivHouseholderQR<decltype(J)> J_qr(J);\n    auto x_test = smooth::detail::solve_ls<N, N>(J_qr, sqrt(par1) * d, r);\n    ASSERT_TRUE(x_test.isApprox(x));\n\n    // check that parameter satisfies conditions\n    bool cond1 = (par1 == 0) && (d.asDiagonal() * x).norm() <= 1.1 * Delta;\n    bool cond2 = (par1 > 0) && std::abs((d.asDiagonal() * x).norm() - Delta) <= 0.1 * Delta;\n    ASSERT_TRUE(cond1 || cond2);\n  }\n}\n\nTEST(Optimization, LmParSing)\n{\n  constexpr int M = 4, N = 4;\n  Eigen::Matrix<double, M, N> J;\n  Eigen::Matrix<double, M, 1> r;\n  Eigen::Matrix<double, N, 1> d;\n\n  double Delta = 1;\n  for (auto i = 0u; i != 10; ++i) {\n    J.setRandom();\n    J.col(3).setZero();\n\n    d.setRandom();\n    d = d + Eigen::Matrix<double, N, 1>::Ones();\n\n    r.setRandom();\n\n    // solve QR\n    auto [par1, x] = smooth::detail::lmpar<4, 4>(J, d, r, Delta);\n\n    // solve dynamic\n    Eigen::MatrixXd Jd = J;\n    Eigen::VectorXd rd = r;\n    Eigen::VectorXd dd = d;\n    auto [par2, xd]    = smooth::detail::lmpar<-1, -1>(Jd, dd, rd, Delta);\n\n    // solve sparse1\n    Eigen::SparseMatrix<double> Jsp;\n    Jsp               = J.sparseView();\n    auto [par3, xsp1] = smooth::detail::lmpar<-1, -1>(Jsp, dd, rd, Delta);\n\n    // solve sparse2\n    auto [par4, xsp2] = smooth::detail::lmpar_sparse(Jsp, dd, rd, Delta);\n\n    // check equality of static and dynamic\n    ASSERT_NEAR(par1, par2, 1e-10);\n    ASSERT_NEAR(par1, par3, 1e-10);\n    ASSERT_TRUE(x.isApprox(xd));\n    ASSERT_TRUE(x.isApprox(xsp1));\n\n    // check that x solves resulting problem\n    Eigen::ColPivHouseholderQR<decltype(J)> J_qr(J);\n    auto x_test = smooth::detail::solve_ls<N, N>(J_qr, sqrt(par1) * d, r);\n\n    ASSERT_TRUE(x_test.isApprox(x));\n\n    // check that parameter satisfies conditions\n    bool cond1 = (par1 == 0) && (d.asDiagonal() * x).norm() <= 1.1 * Delta;\n    bool cond2 = (par1 > 0) && std::abs((d.asDiagonal() * x).norm() - Delta) <= 0.1 * Delta;\n    ASSERT_TRUE(cond1 || cond2);\n\n    // don't expect sparse2 to be equal\n    // check that parameter satisfies conditions\n    bool cond3 = (par4 == 0) && (d.asDiagonal() * xsp2).norm() <= 1.1 * Delta;\n    bool cond4 = (par4 > 0) && std::abs((d.asDiagonal() * xsp2).norm() - Delta) <= 0.1 * Delta;\n    ASSERT_TRUE(cond3 || cond4);\n  }\n}\n\nTEST(NLS, MultipleArgsStatic)\n{\n  smooth::SO3d g1, g2;\n  g1.setRandom();\n  g2.setRandom();\n\n  auto f = [](auto v1, auto v2) {\n    Eigen::Vector3d diff = (v1 - v2) - Eigen::Vector3d::Ones();\n    Eigen::Matrix<double, 9, 1> ret;\n    ret << v1.log(), v2.log(), diff;\n    return ret;\n  };\n\n  smooth::MinimizeOptions opts;\n  opts.ftol    = 1e-12;\n  opts.ptol    = 1e-12;\n  opts.verbose = true;\n\n  smooth::minimize(f, smooth::wrt(g1, g2), opts);\n\n  ASSERT_TRUE(g1.inverse().isApprox(g2, 1e-6));\n}\n\nTEST(NLS, MultipleArgsDynamic)\n{\n  smooth::SO3d g1, g2;\n  g1.setRandom();\n  g2.setRandom();\n\n  auto f = [](auto v1, auto v2) -> Eigen::VectorXd {\n    Eigen::VectorXd diff = (v1 - v2) - Eigen::Vector3d::Ones();\n    Eigen::Matrix<double, 9, 1> ret;\n    ret << v1.log(), v2.log(), diff;\n    return ret;\n  };\n\n  smooth::MinimizeOptions opts;\n  opts.ftol    = 1e-12;\n  opts.ptol    = 1e-12;\n  opts.verbose = true;\n\n  smooth::minimize(f, smooth::wrt(g1, g2), opts);\n\n  ASSERT_TRUE(g1.inverse().isApprox(g2, 1e-6));\n}\n\nTEST(NLS, MixedArgs)\n{\n  smooth::SO3d g0, g1;\n  Eigen::VectorXd v(3);\n  g0.setRandom();\n  g1.setRandom();\n  v.setRandom();\n\n  auto f = [&](auto var_g, auto var_vec) -> Eigen::VectorXd {\n    Eigen::Matrix<double, -1, 1> ret(6);\n    ret << (var_g + var_vec.template head<3>()) - g0, var_vec - Eigen::Vector3d::Ones();\n    return ret;\n  };\n\n  smooth::minimize(f, smooth::wrt(g1, v));\n\n  auto g1_plus_v = g1 + v.head<3>();\n  ASSERT_TRUE(g1_plus_v.isApprox(g0, 1e-6));\n  ASSERT_TRUE(v.isApprox(Eigen::Vector3d::Ones(), 1e-6));\n}\n\nstruct AnalyticSparseFunctor\n{\n  template<typename T>\n  Eigen::VectorX<T>\n  operator()(const smooth::SO3<T> & g1, const smooth::SO3<T> & g2, const smooth::SO3<T> & g3)\n  {\n    Eigen::VectorX<T> f(9);\n    f.template segment<3>(0) = g1.log();\n    f.template segment<3>(3) = (g3 - g2) - d23;\n    f.template segment<3>(6) = (g1 - g3) - d31;\n    return f;\n  }\n\n  Eigen::SparseMatrix<double>\n  jacobian(const smooth::SO3d & g1, const smooth::SO3d & g2, const smooth::SO3d & g3) const\n  {\n    const Eigen::Matrix3d dr_f1_g1 = smooth::SO3d::dr_expinv(g1.log());\n\n    const Eigen::Matrix3d dr_f2_g3 = smooth::SO3d::dr_expinv(g3 - g2);\n    const Eigen::Matrix3d dr_f2_g2 = -smooth::SO3d::dl_expinv(g3 - g2);\n\n    const Eigen::Matrix3d dr_f3_g1 = smooth::SO3d::dr_expinv(g1 - g3);\n    const Eigen::Matrix3d dr_f3_g3 = -smooth::SO3d::dl_expinv(g1 - g3);\n\n    Eigen::SparseMatrix<double> dr_f;\n    dr_f.resize(9, 9);\n    for (int i = 0; i != 3; ++i) {\n      for (int j = 0; j != 3; ++j) {\n        dr_f.insert(i, j) = dr_f1_g1(i, j);\n\n        dr_f.insert(3 + i, 3 + j) = dr_f2_g2(i, j);\n        dr_f.insert(3 + i, 6 + j) = dr_f2_g3(i, j);\n\n        dr_f.insert(6 + i, 6 + j) = dr_f3_g3(i, j);\n        dr_f.insert(6 + i, 0 + j) = dr_f3_g1(i, j);\n      }\n    }\n    dr_f.makeCompressed();\n\n    return dr_f;\n  }\n\n  Eigen::Vector3d d23, d31;\n};\n\nTEST(NLS, AnalyticSparse)\n{\n  auto f = AnalyticSparseFunctor{Eigen::Vector3d::Random(), Eigen::Vector3d::Random()};\n\n  smooth::SO3d g1, g2, g3;\n  g1.setRandom();\n  g2.setRandom();\n  g3.setRandom();\n\n  auto g1c = g1;\n  auto g2c = g2;\n  auto g3c = g3;\n\n  // solve with analytic diff\n  smooth::minimize<smooth::diff::Type::Analytic>(f, smooth::wrt(g1, g2, g3));\n\n  // solve with default autodiff\n  smooth::minimize<smooth::diff::Type::Default>(f, smooth::wrt(g1c, g2c, g3c));\n\n  ASSERT_TRUE(g1.isApprox(g1c, 1e-5));\n  ASSERT_TRUE(g2.isApprox(g2c, 1e-5));\n  ASSERT_TRUE(g3.isApprox(g3c, 1e-5));\n}\n", "meta": {"hexsha": "105ebe6f02a52eb914ed0ca526d8052690478461", "size": 12100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_nls.cpp", "max_stars_repo_name": "pettni/smooth", "max_stars_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T21:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T13:26:44.000Z", "max_issues_repo_path": "tests/test_nls.cpp", "max_issues_repo_name": "pettni/lie", "max_issues_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2021-07-07T21:13:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T04:40:37.000Z", "max_forks_repo_path": "tests/test_nls.cpp", "max_forks_repo_name": "pettni/lie", "max_forks_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T07:16:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T14:29:44.000Z", "avg_line_length": 29.5843520782, "max_line_length": 95, "alphanum_fraction": 0.6208264463, "num_tokens": 4079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.5832368771247842}}
{"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 * Author: Dominic Liao-McPherson \n * Contact: dliaomcp@umich.edu\n * \n * This file is part of the static-linalg library.\n * Copyright (C) 2018-2019 University of Michigan.\n * \n * This software is distributed under the BSD-3-Clause license. \n * You should have received a LICENSE file along with this program. \n * If not see: <https://opensource.org/licenses/BSD-3-Clause>\n */\n\n#include \"StaticMatrix.h\"\n#include \"TestingUtils.h\"\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace testutils;\n\n// TODO: Overhaul for its google test based\nint main(){\n\n\t// test assignment *************************************\n\tdouble *a1 = new double[9];\n\tdouble d1[] = {0.5,2,3};\n\tStaticMatrix A(a1,3,3);\n\tStaticMatrix d(d1,3,1);\n\tA.rand();\n\tA(2,2) = 100;\n\tA.tril();\n\n\t// test reshaping and slicing *************************************\n\n\tcout << \"A:\\n\";\n\tcout << A << endl;\n\tStaticMatrix Acol = A.col(0);\n\tcout << \"First column of A:\\n\" << Acol << endl;\n\tStaticMatrix Arow = A.row(0);\n\tcout << \"First row of A:\\n\" << Arow << endl;\n\tStaticMatrix ARE = A.getreshape(1,9);\n\tcout << \"reshape(A, [1,9]) is:\\n\" << ARE << endl;\n\tArow(2) = 4;\n\tAcol(1) = 6;\n\tcout << \"After A(0,2) = 4, A(1,0) = 6 and column mods\\n\" << A << endl;\n\n\tA.ColScale(d);\n\tcout << \"After column scaling\\n\" << A << endl;\n\tA.RowScale(d);\n\tcout << \"After row scaling\\n\" << A << endl;\n\tMatrixXd A1(3,3);\n\tCopyEig(A,A1);\n\n\t// axpy *************************************\n\tdouble *b1 = new double[3];\n\tStaticMatrix x(b1,3);\n\tx.rand();\n\n\tdouble *b2 = new double[3];\n\tStaticMatrix y(b2,3);\n\ty.rand();\n\n\tdouble a = -1.0;\n\t\n\tMatrixXd x1(3,1);\n\tCopyEig(x,x1);\n\n\tMatrixXd y1(3,1);\n\tCopyEig(y,y1);\n\n\ty1 = y1 + a*x1;\n\ty.axpy(x,a);\n\tcout << \"Testing y <- a*x + y, Error: \\n\";\n\tcout << DiffNorm(y,y1) << endl << endl;\n\t\n\n\t// gemv *************************************\n\tdouble b = 1;\n\t// not transposed\n\tA.rand();\n\tCopyEig(A,A1);\n\tx.rand();\n\tCopyEig(x,x1);\n\ty.rand();\n\tCopyEig(y,y1);\n\n\tcout << \"Testing y <- a*A*x + b*y, Error: \\n\";\n\ty1 = a*A1*x1 + b*y1;\n\ty.gemv(A,x,a,b);\n\n\tcout << DiffNorm(y,y1) << \"\\n\\n\";\n\n\t// transposed\n\tcout << \"Testing y <- a*A'*x + b*y, Error: \\n\";\n\tdouble *a2 = new double[6];\n\tStaticMatrix B(a2,2,3);\n\tB.rand();\n\tMatrixXd B1(2,3);\n\tCopyEig(B,B1);\n\n\tdouble *b3 = new double[2];\n\tStaticMatrix z(b3,2);\n\tz.rand(); \n\ty.rand();\n\tCopyEig(y,y1);\n\n\tMatrixXd z1(2,1);\n\tCopyEig(z,z1);\n\n\ty1 = a*(B1.transpose())*z1 + b*y1;\n\ty.gemv(B,z,a,0.0,true);\n\tcout << DiffNorm(y,y1) << \"\\n\\n\";\n\n\t// test dot and norms *************************************\n\tz1 = x1.transpose()*y1;\n\tcout << \"Testing dot(x,y), error is: \";\n\tcout << abs(StaticMatrix::dot(x,y) - z1(0)) << \"\\n\\n\";\n\n\tcout << \"Testing 2 norm, error is :\";\n\tcout << B.norm() - B1.norm() << \"\\n\\n\";\n\tcout << \"Testing 1 norm: \";\n\tcout << B.asum() << \"\\n\\n\";\n\n\t// free memory\n\tdelete[] a1;\n\tdelete[] a2;\n\tdelete[] b1;\n\tdelete[] b2;\n\tdelete[] b3;\n\t\n\t// gemm *************************************\n\n\ta1 = new double[9];\n\tb1 = new double[6];\n\tdouble* c1 = new double[6];\n\tA.map(a1,3,3);\n\tB.map(b1,3,2);\n\tStaticMatrix C(c1,3,2);\n\n\tMatrixXd AA(3,3);\n\tMatrixXd BB(3,2);\n\tMatrixXd CC(3,2);\n\n\tA.rand();\n\tB.rand();\n\tC.rand();\n\tCopyEig(C,CC);\n\tCopyEig(A,AA);\n\tCopyEig(B,BB);\n\n\tcout << \"Testing C = aAB+bC, error:\";\n\tC.gemm(A,B,a,b);\n\tCC = a*AA*BB + b*CC;\n\tcout << DiffNorm(C,CC) << \"\\n\\n\";\n\n\t// transA\n\tcout << \"Testing C = a A'B + bC, error:\";\n\tC.gemm(A,B,a,b,true);\n\tCC = a*(AA.transpose())*BB + b*CC;\n\tcout << DiffNorm(C,CC) << \"\\n\\n\";\n\t\n\n\t// trans B\n\tdelete[] a1;\n\tdelete[] b1;\n\ta1 = new double[3];\n\tb1 = new double[2];\n\tA.map(a1,3,1);\n\tB.map(b1,2,1);\n\tA.rand();\n\tB.rand();\n\tAA.resize(3,1);\n\tBB.resize(2,1);\n\tCopyEig(C,CC);\n\tCopyEig(A,AA);\n\tCopyEig(B,BB);\n\n\tCC = a*AA*(BB.transpose()) + b*CC;\n\tC.gemm(A,B,a,b,false,true);\n\n\tcout << \"Testing C = a AB' + bC, Error: \" << DiffNorm(C,CC) << \"\\n\\n\";\n\t\n\tdelete[] a1;\n\tdelete[] b1;\n\n\t// trans A,B\n\ta1 = new double[6];\n\tb1 = new double[4];\n\tA.map(a1,2,3);\n\tB.map(b1,2,2);\n\tA.rand();\n\tB.rand();\n\n\tAA.resize(2,3);\n\tBB.resize(2,2);\n\tCopyEig(C,CC);\n\tCopyEig(A,AA);\n\tCopyEig(B,BB);\n\tCC = a*(AA.transpose())*(BB.transpose()) + b*CC;\n\tC.gemm(A,B,a,b,true,true);\n\n\tcout << \"Testing C = a A'B' + bC, Error: \" << DiffNorm(C,CC) << \"\\n\\n\";\n\n\tdelete[] a1;\n\tdelete[] b1;\n\tdelete[] c1;\n\n\t// Symmetric products *************************************\n\n\ta1 = new double[10];\n\tb1 = new double[5];\n\tc1 = new double[4];\n\n\tA.map(a1,5,2);\n\tC.map(c1,2,2);\n\tA.rand();\n\tAA.resize(5,2);\n\tCC.resize(2,2);\n\n\n\tCopyEig(C,CC);\n\tCopyEig(A,AA);\n\t\n\n\tCC = (AA.transpose())*AA + CC;\n\tC.gram(A);\n\tcout << \"Testing C = A'*A, Error: \" << DiffNorm(C,CC) << \"\\n\\n\";\n\n\n\tB.map(b1,5,1);\n\tB.rand();\n\tBB.resize(5,5);\n\tBB.fill(0);\n\tfor(int i = 0; i< 5;i++)\n\t\tBB(i,i) = B(i);\n\n\tCC = (AA.transpose())*BB*AA + CC;\n\tC.gram(A,B);\n\tcout << \"Testing C = A'*diag(B)*A + C, Error: \" << DiffNorm(C,CC) << \"\\n\\n\";\n\n\tdelete[] a1;\n\tdelete[] b1;\n\n\t// Cholesky factorization *************************************\n\tdouble lmem[] = {3.8966,2.1881,1.1965,2.1551,\n    2.1881,2.9966,0.6827,1.8861,\n    1.1965,    0.6827,    1.7590,    0.5348,\n    2.1551,    1.8861,    0.5348,    3.0955};\n\n    A.map(lmem,4,4);\n    Map<MatrixXd> AL(lmem,4,4);\n    LLT<MatrixXd> LLTA(AL);\n    A.llt();\n    MatrixXd L = LLTA.matrixLLT();\n\n    cout << \"Testing Cholesky Factorizaton, Error: \";\n    cout << DiffNorm(A,L) << endl;\n    for(int j = 0;j<4;j++)\n    \tfor(int i = 0;i< j;i++)\n    \t\tL(i,j) = 0.0;\n\n\t// Back solves *************************************\n\n    double b4[] = {0.6541,    0.6892,    0.7482,    0.4505,\n    0.0838,    0.2290,    0.9133,    0.1524,\n    0.8258,    0.5383,    0.9961,    0.0782};\n    B.map(b4,4,3);\n    MatrixXd BE(3,4);\n    BE << 0.6541,    0.6892,    0.7482,    0.4505,\n    0.0838,    0.2290,    0.9133,    0.1524,\n    0.8258,    0.5383,    0.9961,    0.0782;\n    BE.transposeInPlace();\n\n    //*************************************\n    cout << \"Testing B <- inv(L)*B, A = LL' \\n\";\n   \n    BE = (L.inverse())*BE;\n    B.LeftCholApply(A);\n    cout << \"Error: \" << DiffNorm(B,BE) << endl << endl;\n\n    //*************************************\n    cout << \"Testing B <- inv(L)'*B, A = LL' \\n\";\n\n    B.LeftCholApply(A,true);\n    BE = ((L.inverse()).transpose())*BE;\n\n    cout << \"Error : \" << DiffNorm(B,BE) << endl << endl;\n\n    // *************************************\n\n    B.reshape(3,4);\n    BE.resize(3,4);\n\n    cout << \"Testing B <- B*inv(L) \\n\";\n    B.RightCholApply(A);\n    BE = BE*(L.inverse());\n\n    cout << \"Error : \" << DiffNorm(B,BE) << endl << endl;\n\n\n    // *************************************\n    cout << \"Testing B <- B*inv(L)' \\n\";\n\n    B.RightCholApply(A,true);\n    BE = BE*((L.inverse()).transpose());\n\n    cout << \"Error : \" << DiffNorm(B,BE) << endl << endl;\n\n\n\n\n\n\treturn 0;\n}\n\n\n\n", "meta": {"hexsha": "dd6ef0b0aaf1718703f4f1e7fda1f759f22dee7e", "size": 6708, "ext": "cc", "lang": "C++", "max_stars_repo_path": "StaticMatrixTest.cc", "max_stars_repo_name": "dliaomcp/static-linalg", "max_stars_repo_head_hexsha": "7091f691934dabbdc6ed83721732587b15359efd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "StaticMatrixTest.cc", "max_issues_repo_name": "dliaomcp/static-linalg", "max_issues_repo_head_hexsha": "7091f691934dabbdc6ed83721732587b15359efd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StaticMatrixTest.cc", "max_forks_repo_name": "dliaomcp/static-linalg", "max_forks_repo_head_hexsha": "7091f691934dabbdc6ed83721732587b15359efd", "max_forks_repo_licenses": ["BSD-3-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.0943396226, "max_line_length": 77, "alphanum_fraction": 0.5065593321, "num_tokens": 2414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.5832368687086324}}
{"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": "#pragma once\n\n#include \"definitions.hpp\"\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <initializer_list>\n\ninline RowVector vector_from_sequence(std::initializer_list<Real> seq)\n{\n    RowVector vec(seq.size());\n    for (auto it = seq.begin(); it != seq.end(); ++it)\n    {\n        vec[std::distance(seq.begin(), it)] = *it;\n    }\n    return vec;\n}\n\ntemplate <typename T>\ninline Real squaredNorm(const T& vec)\n{\n    assert(vec.rows() == 1);\n    return square(vec.array()).sum();\n}\ntemplate <typename T>\ninline Real norm(const T& vec)\n{\n    return std::sqrt(squaredNorm(vec));\n}\n", "meta": {"hexsha": "aaf262b69d0a36568c657ed6c6b66a591ab09a0f", "size": 580, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qflow/vector.hpp", "max_stars_repo_name": "johanere/qflow", "max_stars_repo_head_hexsha": "5453cd5c3230ad7f082adf9ec1aea63ab0a4312a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-07-24T21:46:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T18:18:24.000Z", "max_issues_repo_path": "qflow/vector.hpp", "max_issues_repo_name": "johanere/qflow", "max_issues_repo_head_hexsha": "5453cd5c3230ad7f082adf9ec1aea63ab0a4312a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2019-02-19T10:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-18T09:42:13.000Z", "max_forks_repo_path": "qflow/vector.hpp", "max_forks_repo_name": "bsamseth/FYS4411", "max_forks_repo_head_hexsha": "72b879e7978364498c48fc855b5df676c205f211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-04T15:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T16:37:38.000Z", "avg_line_length": 19.3333333333, "max_line_length": 70, "alphanum_fraction": 0.6482758621, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5832170331220327}}
{"text": "#ifndef _UBLAS_\n#define _UBLAS_\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#endif\n\n#ifndef _MY_UBLAS_\n#define _MY_UBLAS_\n\nusing namespace boost::numeric::ublas;\nusing namespace boost::numeric;\n\ntemplate <class T>\nunsigned int argmin(ublas::vector<T> v)\n{ /* v\u306e\u6700\u5c0f\u8981\u7d20\u306e\u6dfb\u5b57\u3092\u8fd4\u3059 */\n  if(v.empty()){ return -1; /* \u30a8\u30e9\u30fc */    \n  }else{\n    unsigned int argmin = 0;\n    T minval = v[argmin];\n    for(unsigned int i = 0; i < v.size(); ++i){\n      if(v[i] < minval){\n\targmin = i; minval = v[i];\n      }\n    }\n    return argmin;\n  }\n}\n\ntemplate <class T>\nunsigned int argmin2 (ublas::vector<T> v)\n{ /* v\u306e2\u756a\u76ee\u306b\u5c0f\u3055\u3044\u8981\u7d20\u306e\u6dfb\u5b57\u3092\u8fd4\u3059 */\n  if(v.size() < 2){ return -1; /* \u30a8\u30e9\u30fc */\n  }else{\n    unsigned int argmin1, argmin2;\n    T min1, min2;\n    if(v[0] <= v[1]){          \n      min1 = v[0]; argmin1 = 0;\n      min2 = v[1]; argmin2 = 1;\n    }else{           \n      min1 = v[1]; argmin1 = 1;\n      min2 = v[0]; argmin2 = 0;\n    }\n    for(unsigned int i = 2; i < v.size(); ++i){\n      if(v[i] <= min1){       /* \u6700\u5c0f\u5024\u304c\u767a\u898b\u3055\u308c\u305f */\n\tmin2 = min1; argmin2 = argmin1;       \n\tmin1 = v[i]; argmin1 = i;\n      }else if(v[i] <= min2){ /* \u6e96\u6700\u5c0f\u5024\u304c\u767a\u898b\u3055\u308c\u305f */\n\tmin2 = v[i]; argmin2 = i;\n      }\n    }\n    return argmin2;\n  }\n}\n\ntemplate <class T>\nunsigned int argmax(ublas::vector<T> v){\n  if(v.empty()){ return -1; /* \u30a8\u30e9\u30fc */    \n  }else{\n    unsigned int argmax = 0; T maxval = v[argmax];\n    for(unsigned int i = 0; i < v.size(); ++i){\n      if(v[i] > maxval){\n\targmax = i; maxval = v[i];\n      }\n    }\n    return argmax;\n  }\n}\n\ntemplate <class T>\ninline T min(ublas::vector<T> v){\n  if(v.empty()){ return -1; /* \u30a8\u30e9\u30fc */    \n  }else{\n    T minval = v[0];\n    for(unsigned int i = 0; i < v.size(); ++i){\n      if(v.at(i) < minval){\t\n\tminval = v.at(i);\n      }\n    }\n    return minval;\n  }\n}\n\ntemplate <class T>\ninline T min2(ublas::vector<T> v){\n  /* vector v\u306e\u8981\u7d20\u30672\u756a\u76ee\u306b\u5c0f\u3055\u3044\u8981\u7d20\u3092\u898b\u3064\u3051\u308b */\n  if(v.size() < 2){ return -1; /* \u30a8\u30e9\u30fc */\n  }else{\n    T min1 = v[0], min2 = v[1];\n    if(min1 > min2){ /* swap \u3059\u308b */\n      T temp = min1; min1 = min2; min2 = temp;\n    }\n    for(unsigned int i = 2; i < v.size(); ++i){\n      if(v[i] <= min1){       /* \u6700\u5c0f\u5024\u304c\u767a\u898b\u3055\u308c\u305f */\n\tmin2 = min1; min1 = v[i];\t\n      }else if(v[i] <= min2){ /* \u6e96\u6700\u5c0f\u5024\u304c\u767a\u898b\u3055\u308c\u305f */\n\tmin2 = v[i];\n      }\n    }\n    return min2;\n  }\n}\n\n#if 0\nublas::vector<double> map /* \u30d9\u30af\u30c8\u30eb\u306b\u95a2\u3059\u308bmap */\n(ublas::vector<double> source, function<double(double)> func)\n{\n  ublas::vector<double> result(source.size());\n  for (unsigned int i = 0; i < source.size(); ++i){\n    result[i]= func(source[i]);\n  }\n  return result;\n}\n\nublas::matrix<double> map /* \u884c\u5217\u306b\u95a2\u3059\u308bmap */\n(ublas::matrix<double> source,\n function<ublas::vector<double>(ublas::vector<double>)> func)\n{\n  ublas::matrix<double> result(source.size1(), source.size2());\n  for (unsigned int i = 0; i < source.size1(); ++i){\n    row(result, i)= func(row(source,i));\n  }\n  return result;\n}\n\nint maptest()\n{\n  ublas::vector<double> vec(5, 0);\n  vec[0] = 0.0;\n  vec[1] = 1.1;\n  vec[2] = -2.4;\n  vec[3] = 3.5;\n  vec[4] = 4.6;\n\n  cout << vec << endl;\n  \n  cout <<  map(vec, [](double x){ return x + 1.0; }) << endl;\n  return 0;\n}\n#endif\n\n\n\n#endif\n", "meta": {"hexsha": "328ac2e7bc784b36cbca75f8b1b77a38df4a2f55", "size": 3188, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "program/my_ublas.hpp", "max_stars_repo_name": "yk-tanigawa/201503_clustering", "max_stars_repo_head_hexsha": "43a11e707c08f1576e5765824c74330b6730e7e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "program/my_ublas.hpp", "max_issues_repo_name": "yk-tanigawa/201503_clustering", "max_issues_repo_head_hexsha": "43a11e707c08f1576e5765824c74330b6730e7e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-26T16:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-26T16:53:14.000Z", "max_forks_repo_path": "program/my_ublas.hpp", "max_forks_repo_name": "yk-tanigawa/201503_clustering", "max_forks_repo_head_hexsha": "43a11e707c08f1576e5765824c74330b6730e7e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5405405405, "max_line_length": 63, "alphanum_fraction": 0.5479924718, "num_tokens": 1186, "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": "//  (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": "#ifndef KEY_GENERATOR_HPP\n#define KEY_GENERATOR_HPP\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <ctime>\n#include <iostream>\n#include <random>\n#include <stdexcept>\n\n#include \"big_int_type.hpp\"\n#include \"euclidean.hpp\"\n#include \"primality.hpp\"\n\ntypedef struct key {\n  big_int d_e;\n  big_int n;\n} Key;\n\ntypedef struct key_pair {\n  Key pub_key;\n  Key priv_key;\n} Key_pair;\n\n/*\n * Gera os valores de p, q, n, Phi(n), e, d.\n * @returns Um par de chaves, contendo uma chave p\u00fablica e uma chave privada.\n */\nKey_pair generate_keys(unsigned max_bits, bool print = false);\n\n#endif", "meta": {"hexsha": "15d41cbe561ae5c0695bd76a588bc5756a5712ec", "size": 580, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/key_generator.hpp", "max_stars_repo_name": "paulora2405/cal-tf", "max_stars_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/key_generator.hpp", "max_issues_repo_name": "paulora2405/cal-tf", "max_issues_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/key_generator.hpp", "max_forks_repo_name": "paulora2405/cal-tf", "max_forks_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3333333333, "max_line_length": 77, "alphanum_fraction": 0.7310344828, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5832064700656189}}
{"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\u81ea\u5e26\u7684\u4e0eeigen\u7c7b\u578b\u8f6c\u6362api\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// \u6839\u636e\u540d\u5b57\u52a8\u6001\u6784\u5efa\u76f8\u5e94\u7684\u5339\u914d\u5668\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// \u6c42\u89e3PnP,\u6c42\u89e3\u51fa\u4e24\u5e27\u56fe\u50cf\u4e4b\u95f4\u7684\u4f4d\u59ff\u53d8\u6362\u5173\u7cfb\nvoid AlignImage:: alignTwoFrames(Frame::Ptr ref_frame, Frame::Ptr curr_frame)\n{\n\tis_good_align_ = true;\n\t\n\t// \u6e05\u7a7a\u4e4b\u524d\u7684\u5339\u914d\u6570\u636e,\u9632\u6b62\u4e0d\u540c\u5e27\u5bf9\u4e4b\u95f4\u7684\u6570\u636e\u7d2f\u79ef\n\tmatches_.clear();\n\tgood_matches_.clear();\n\t\n\t// \u5339\u914d\u4e24\u5e27\u7684\u63cf\u8ff0\u5b50\n\tmatcher_->match(ref_frame->descrip_, curr_frame->descrip_, matches_);\n\tcout << \"find total \" << matches_.size() << \" matches\" << endl;\n\t\n\t// \u6839\u636e\u8ddd\u79bb,\u7b5b\u9009\u597d\u7684\u5339\u914d\n\t// \u5bfb\u627e\u6700\u5c0f\u8ddd\u79bb\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// \u7b5b\u9009\n\tif (min_dist < 10 ) min_dist = 10;\t\t// \u9632\u6b62\u56e0\u4e3amin_dist\u7b49\u4e8e0\u800c\u627e\u4e0d\u5230good_match\u7684\u60c5\u51b5\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// \u7b2c\u4e00\u5e27\u4e2d\u7684\u4e09\u7ef4\u70b9\n\tvector<cv::Point3f> points_obj;\n\t// \u7b2c\u4e8c\u5e27\u4e2d\u7684\u56fe\u50cf\u70b9\n\tvector<cv::Point2f> points_img;\n\t\n\t// \u83b7\u5f97\u5bf9\u5e94\u7684\u4e09\u7ef4\u70b9\u548c\u50cf\u7d20\u70b9\u5750\u6807\n\tfor (cv::DMatch m : good_matches_) {\n\t\t// \u83b7\u53d6\u7b2c\u4e00\u5e27\u56fe\u50cf\u4e2d\u70b9\u7684\u50cf\u7d20\u5750\u6807\u548c\u6df1\u5ea6\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// \u5f97\u5230\u7b2c\u4e00\u5e27\u56fe\u50cf\u4e2d\u7a7a\u95f4\u70b9\u5750\u6807\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// \u5f97\u5230\u4e0e\u4e4b\u5bf9\u5e94\u7684\u7b2c\u4e8c\u5e27\u56fe\u50cf\u4e2d\u50cf\u7d20\u70b9\u5750\u6807\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// \u68c0\u67e5\u6709\u6548\u7684\u76ee\u6807\u70b9\u7684\u6570\u91cf,\u5c0f\u4e8e4\u5219\u4f1a\u5f15\u53d1opencv\u5f02\u5e38,\u9700\u8981\u653e\u5f03\u8be5\u5e27\n\tif (points_obj.size() < 4) {\n\t\tis_good_align_ = false;\n\t\treturn;\n\t}\n\t\n\t// \u6c42\u89e3PnP\u95ee\u9898,\u540c\u65f6\u4f7f\u7528RANSAC\u53bb\u9664outlier\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\u51fd\u6570\u8f93\u51fa\u7684\u662f\u4e09\u7ef4\u70b9\u5750\u6807\u7cfb(\u6a21\u578b\u5750\u6807\u7cfb)\u5230\u4e8c\u7ef4\u70b9\u5750\u6807\u7cfb(\u76f8\u673a\u5750\u6807\u7cfb)\u7684\u53d8\u6362\u5173\u7cfb\n\t// \u5728\u8fd9\u91cc,\u5c31\u662ffram1\u5750\u6807\u7cfb\u4e2d\u7684\u70b9\u5de6\u4e58\u5f97\u5230\u7684\u53d8\u6362\u5173\u7cfb,\u53ef\u4ee5\u53d8\u6362\u5230curr_frame\u5750\u6807\u7cfb\u4e2d\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// \u753b\u51fainliers\u5339\u914d \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// \u8ba1\u7b97\u5f53\u524d\u5e27\u5230\u4e16\u754c\u5750\u6807\u7684\u53d8\u6362\n\t/******************************************************************\n\t * \u6ce8\u610f,\u8fd9\u4e2a\u5730\u65b9\u4e4b\u6240\u4ee5\u662f\u53f3\u4e58 T_r2c_ \u7684\u9006,\u662f\u56e0\u4e3a\u4ece\u5f53\u524d\u5e27\u5750\u6807\u7cfb\u53d8\u5230\u4e16\u754c\u5750\u6807\u7cfb\u7684\n\t * \u8fc7\u7a0b\u7b49\u4ef7\u4e8e\u5148\u53d8\u5230\u524d\u4e00\u5e27\u7684\u5750\u6807\u7cfb,\u518d\u53d8\u5230\u524d\u524d\u5e27\u7684\u5750\u6807\u7cfb,\u4ee5\u6b64\u7c7b\u63a8,\u7528\u516c\u5f0f\u8868\u793a\n\t * \u5c31\u662fPw=Tw1^-1 * T12^-1 * T23^-1 * ...* Tn-1n^-1 * Pn,\u56e0\u6b64\u76f8\u5e94\u7684\u53d8\u6362\u77e9\u9635\u5c31\u662f\n\t * \u4ece\u7b2c\u4e00\u5e27\u5230\u4e16\u754c\u5750\u6807\u7cfb\u7684\u53d8\u6362\u5f00\u59cb\u4e0d\u65ad\u7684\u53f3\u4e58\u53c2\u8003\u5e27\u5230\u5f53\u524d\u5e27\u53d8\u6362\u7684\u9006\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 \u53ea\u7528\u4e8e\u663e\u793a,\u8c03\u8bd5\u65f6\u770b\u56fe\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// \u6e05\u7a7a\u4e4b\u524d\u7684\u5339\u914d\u6570\u636e,\u9632\u6b62\u6570\u636e\u7d2f\u79ef\n\tmatches_.clear();\n\tgood_matches_.clear();\n\tmatch_2dkp_index_.clear();\n\t\n\t// \u6839\u636e\u5047\u8bbe\u7684\u5f53\u524d\u5e27\u4f4d\u59ff,\u5bf9\u5730\u56fe\u70b9\u8fdb\u884c\u6295\u5f71,\u7b5b\u9009\u53ef\u80fd\u4f1a\u51fa\u73b0\u5728\u5f53\u524d\u5e27\u4e2d\u7684\u5730\u56fe\u70b9\u4f5c\u4e3a\u5339\u914d\u5019\u9009\u70b9\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// \u5982\u679c\u5730\u56fe\u70b9\u53ef\u80fd\u51fa\u73b0\u5728\u5f53\u524d\u5e27\u4e2d,\u5219\u5c06\u5176\u4f5c\u4e3a\u5019\u9009\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// \u5339\u914d\u5019\u9009\u7684\u5730\u56fe\u70b9\u548c\u5f53\u524d\u5e27\u7684\u7279\u5f81\u70b9\n\tmatcher_->match(map_descriptor, curr_frame->descrip_, matches_);\n\tcout << \"find total \" << matches_.size() << \" matches\" << endl;\n\t\n\t// \u6839\u636e\u8ddd\u79bb,\u7b5b\u9009\u597d\u7684\u5339\u914d\n\t// \u5bfb\u627e\u6700\u5c0f\u8ddd\u79bb\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// \u7b5b\u9009\n\tif (min_dist < 10.0 ) min_dist = 10.0;\t\t// \u9632\u6b62\u56e0\u4e3amin_dist\u7b49\u4e8e0\u800c\u627e\u4e0d\u5230good_match\u7684\u60c5\u51b5\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// \u83b7\u5f97\u5bf9\u5e94\u7684\u4e09\u7ef4\u70b9\u548c\u50cf\u7d20\u70b9\u5750\u6807\n\tfor (cv::DMatch m : good_matches_) {\n\t\t// 3D\u70b9\n\t\tcv::Point3f pt_world = (candidate_map_points[m.queryIdx])->getPositionCV();\n\t\tpoints_world.push_back(pt_world);\n\t\t// \u5f97\u5230\u4e0e\u4e4b\u5bf9\u5e94\u7684\u7b2c\u4e8c\u5e27\u56fe\u50cf\u4e2d\u50cf\u7d20\u70b9\u5750\u6807\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// \u68c0\u67e5\u6709\u6548\u7684\u76ee\u6807\u70b9\u7684\u6570\u91cf,\u5c0f\u4e8e4\u5219\u4f1a\u5f15\u53d1opencv\u5f02\u5e38,\u9700\u8981\u653e\u5f03\u8be5\u5e27\n\tif (points_world.size() < 4) {\n\t\tis_good_align_ = false;\n\t\treturn;\n\t}\n\t\n\t// \u6c42\u89e3PnP\u95ee\u9898,\u540c\u65f6\u4f7f\u7528RANSAC\u53bb\u9664outlier\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\u51fd\u6570\u8f93\u51fa\u7684\u662f\u4e09\u7ef4\u70b9\u5750\u6807\u7cfb(\u6a21\u578b\u5750\u6807\u7cfb)\u5230\u4e8c\u7ef4\u70b9\u5750\u6807\u7cfb(\u76f8\u673a\u5750\u6807\u7cfb)\u7684\u53d8\u6362\u5173\u7cfb\n\t// \u5728\u8fd9\u91cc,\u5c31\u662f\u4e16\u754c\u5750\u6807\u7cfb\u4e2d\u7684\u70b9\u5de6\u4e58\u5f97\u5230\u7684\u53d8\u6362\u5173\u7cfb,\u53ef\u4ee5\u53d8\u6362\u5230curr_frame\u5750\u6807\u7cfb\u4e2d\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// \u8ba1\u7b97\u5f53\u524d\u5e27\u5230\u4e16\u754c\u5750\u6807\u7684\u53d8\u6362\n\t/*\n\t * \u56e0\u4e3a\u6b64\u65f6T_r2c_\u8868\u793a\u7684\u662f\u4e16\u754c\u5230\u5e27\u7684\u53d8\u6362\n\t */\n\tcurr_frame->T_c2w_ = T_r2c_.inverse();\n\t\n\t// \u6839\u636e\u6c42\u5f97\u7684\u5f53\u524d\u5e27\u7684\u51c6\u786e\u4f4d\u59ff,\u5bf9\u5730\u56fe\u70b9\u7684\u76f8\u5173\u53d8\u91cf\u8fdb\u884c\u66f4\u65b0\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// \u7b26\u5408\u51e0\u4f55\u5173\u7cfb\u7684\u5730\u56fe\u70b9,\u5176\u88ab\u5339\u914d\u7684\u6b21\u6570\u52a01\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// \u4f7f\u7528g2o\u5bf9\u6c42\u89e3\u51fa\u6765\u7684\u53d8\u6362\u5173\u7cfb\u8fdb\u884c\u4f18\u5316\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// \u4f7f\u7528PnP\u8f93\u51fa\u6784\u5efa\u5f85\u4f18\u5316\u7684SE3\u53d8\u91cf\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 << \"\u4f18\u5316\u524d\u7684T_r2c_:\" << endl <<  T_r2c_no_opt.matrix() << endl;\n\t\n\t// \u6dfb\u52a0\u5f85\u4f18\u5316\u8282\u70b9\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// \u6dfb\u52a0\u8fb9,\u6bcf\u4e00\u6761\u8fb9\u8868\u793a\u4e00\u6b21\u4e09\u7ef4\u70b9\u5230\u56fe\u50cf\u70b9\u7684\u6295\u5f71\u6d4b\u91cf,\u80fd\u8ba1\u7b97\u5230\u4e00\u4e2a\u8bef\u5dee\n\tfor (int i = 0; i < inliers.rows; i++) {\n\t\tint index = inliers.at<int>(i,0);\t// \u7b2ci\u4e2a\u5185\u70b9\u5728\u539f\u6765\u7684\u70b9\u5217\u8868\u4e2d\u7684\u7d22\u5f15\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// \u4fe1\u606f\u77e9\u9635\u662f\u534f\u65b9\u5dee\u77e9\u9635\u7684\u9006,\u8868\u793a\u7684\u662f\u5bf9\u8bef\u5dee\u5411\u91cf\u4e2d\u4e0d\u540c\u5206\u91cf\u7684\u91cd\u89c6\u7a0b\u5ea6(\u6743\u91cd),\u6700\u7b80\u5355\u7684\u5373\u8bbe\u7f6e\u4e3a\u5355\u4f4d\u9635\n\t\toptimizer.addEdge( edge );\n\t}\n\t// \u542f\u52a8\u4f18\u5316\n\toptimizer.initializeOptimization();\n\toptimizer.optimize(10);\n\t\n\t// \u8f6c\u5b58\u4f18\u5316\u540e\u7684\u53d8\u91cf\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// \u6784\u9020Eigen\u53d8\u6362\u5173\u7cfb\n// \tT_.pretranslate (t_ );\n\tcout << \"\u4f18\u5316\u540e\u7684T_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": "//  (C) Copyright Matt Borland and Nick Thompson 2022.\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 \"math_unit_test.hpp\"\n#include <cmath>\n#include <vector>\n#include <boost/math/special_functions/logsumexp.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/random_vector.hpp>\n\ntemplate <typename Real>\nvoid test()\n{\n    using boost::math::logsumexp;\n    using std::log;\n    using std::exp;\n\n    // Spot check 2 values\n    // Also validate that 2 values does not attempt to instantiate the iterator version\n    // https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html\n    // Calculated at higher precision using wolfram alpha\n    Real x1 = 1e-50l;\n    Real x2 = 2.5e-50l;\n    Real spot1 = static_cast<Real>(exp(x1));\n    Real spot2 = static_cast<Real>(exp(x2));\n    Real spot12 = logsumexp(x1, x2);\n    CHECK_ULP_CLOSE(log(spot1 + spot2), spot12, 1);\n\n    // Spot check 3 values and compare result of each different interface\n    Real x3 = 5e-50l;\n    Real spot3 = static_cast<Real>(exp(x3));\n    std::vector<Real> x_vals {x1, x2, x3};\n\n    Real spot123 = logsumexp(x1, x2, x3);\n    Real spot123_container = logsumexp(x_vals);\n    Real spot123_iter = logsumexp(x_vals.begin(), x_vals.end());\n\n    CHECK_EQUAL(spot123, spot123_container);\n    CHECK_EQUAL(spot123_container, spot123_iter);\n    CHECK_ULP_CLOSE(log(spot1 + spot2 + spot3), spot123, 1);\n\n    // Spot check 4 values with repeated largest value\n    Real x4 = x3;\n    Real spot4 = spot3;\n    Real spot1234 = logsumexp(x1, x2, x3, x4);\n    x_vals.emplace_back(x4);\n    Real spot1234_container = logsumexp(x_vals);\n\n    CHECK_EQUAL(spot1234, spot1234_container);\n    CHECK_ULP_CLOSE(log(spot1 + spot2 + spot3 + spot4), spot1234, 1);\n\n    // Check with a value of vastly different order of magnitude\n    Real x5 = 1.0l;\n    Real spot5 = static_cast<Real>(exp(x5));\n    x_vals.emplace_back(x5);\n    Real spot12345 = logsumexp(x_vals);\n    CHECK_ULP_CLOSE(log(spot1 + spot2 + spot3 + spot4 + spot5), spot12345, 1);\n}\n\n// The naive method of computation should overflow:\ntemplate<typename Real>\nvoid test_overflow() \n{\n    using boost::math::logsumexp;\n    using std::exp;\n    using std::log;\n\n    Real x = ((std::numeric_limits<Real>::max)()/2);\n\n    Real naive_result = log(exp(x) + exp(x));\n    CHECK_EQUAL(std::isfinite(naive_result), false);\n\n    Real result = logsumexp(x, x);\n    CHECK_EQUAL(std::isfinite(result), true);\n    CHECK_ULP_CLOSE(result, x + boost::math::constants::ln_two<Real>(), 1);\n}\n\ntemplate <typename Real>\nvoid test_random()\n{\n    using std::exp;\n    using std::log;\n    using boost::math::logsumexp;\n    using boost::math::generate_random_vector;\n    \n    std::vector<Real> test_values = generate_random_vector(128, 0, Real(1e-50l), Real(1e-40l));\n    Real naive_exp_sum = 0;\n\n    for(const auto& val : test_values)\n    {\n        naive_exp_sum += exp(val);\n    }\n\n    CHECK_ULP_CLOSE(log(naive_exp_sum), logsumexp(test_values), 1);\n}\n\nint main (void)\n{\n    test<float>();\n    test<double>();\n    test<long double>();\n\n    test_overflow<float>();\n    test_overflow<double>();\n    test_overflow<long double>();\n\n    test_random<float>();\n    test_random<double>();\n    test_random<long double>();\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "78cc768ff5708f09a625a7feff1f4cc0ccf3ebce", "size": 3390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/logsumexp_test.cpp", "max_stars_repo_name": "grlee77/math", "max_stars_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/logsumexp_test.cpp", "max_issues_repo_name": "grlee77/math", "max_issues_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/logsumexp_test.cpp", "max_forks_repo_name": "grlee77/math", "max_forks_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7368421053, "max_line_length": 95, "alphanum_fraction": 0.6781710914, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5830837805812049}}
{"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 <iostream>\r\n#include <Eigen/Dense>\r\n#include \"igmn.h\"\r\n\r\nusing Eigen::MatrixXd;\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\tstd::cout << Statistic::chi2inv(12, 2) <<std::endl;\r\n\r\n    vector<double> range (2);\r\n\trange[0] = range[1] = 2;\r\n\r\n    liac::IGMN loigmn(range, 0.1, 0.3);\r\n\r\n    int num = 63;\r\n\tMatrixXd m(2, num);\r\n\tint i = 0;\r\n\r\n\tfor (float x = 0; x <= 2 * Constants::PI && i < num; x += 0.1f)\r\n\t{\r\n\t\tm(0, i) = x;\r\n\t\tm(1, i++) = std::sin(x);\r\n\t}\r\n\r\n    loigmn.train(m);\r\n\r\n\tfor (int j = 0; j < i; j++)\r\n\t{\r\n\t\tMatrixXd input = m.block(0, j, 1, 1);\r\n\t\tMatrixXd res = loigmn.recall(input);\r\n\r\n\t\tcout << \"Input: \" << input  << \" Real: \" << m(1, j) << \" Recall: \" << res << endl;\r\n\t}\r\n\r\n\tsystem(\"PAUSE\");\r\n}\r\n", "meta": {"hexsha": "5b53854711d4398e3e49d0f890ab55fc4517d940", "size": 721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "IGMN-C/Main.cpp", "max_stars_repo_name": "jchambyd/FIGMN-C-", "max_stars_repo_head_hexsha": "7f28c6007b5100cfd17a2b40615feb771858c1c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-01-21T17:22:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-22T20:18:24.000Z", "max_issues_repo_path": "IGMN-C/Main.cpp", "max_issues_repo_name": "jchambyd/FIGMN-C", "max_issues_repo_head_hexsha": "7f28c6007b5100cfd17a2b40615feb771858c1c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IGMN-C/Main.cpp", "max_forks_repo_name": "jchambyd/FIGMN-C", "max_forks_repo_head_hexsha": "7f28c6007b5100cfd17a2b40615feb771858c1c9", "max_forks_repo_licenses": ["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.025, "max_line_length": 85, "alphanum_fraction": 0.5034674064, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.583048995983957}}
{"text": "#ifndef CORE_ALGEBRA_UTIL_HPP\n#define CORE_ALGEBRA_UTIL_HPP\n#include <vector>\n#include <NTL/ZZ.h>\nnamespace algebra {\nNTL::ZZ _InvMod(NTL::ZZ a, NTL::ZZ p);\nNTL::ZZ apply_crt(const std::vector<NTL::ZZ> &alphas, const std::vector<NTL::ZZ> &primes, const bool negate);\n}\n#endif // CORE_ALGEBRA_UTIL_HPP\n", "meta": {"hexsha": "d56a28b223fefb2258fac223afc311e9d94f4d4f", "size": 301, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/include/core/algebra/util.hpp", "max_stars_repo_name": "fionser/CODA", "max_stars_repo_head_hexsha": "db234a1e9761d379fb96ae17eef3b77254f8781c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-24T19:28:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-05T04:40:47.000Z", "max_issues_repo_path": "core/include/core/algebra/util.hpp", "max_issues_repo_name": "fionser/CODA", "max_issues_repo_head_hexsha": "db234a1e9761d379fb96ae17eef3b77254f8781c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-15T03:41:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-24T09:06:15.000Z", "max_forks_repo_path": "core/include/core/algebra/util.hpp", "max_forks_repo_name": "fionser/CODA", "max_forks_repo_head_hexsha": "db234a1e9761d379fb96ae17eef3b77254f8781c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-05-14T10:12:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-07T03:50:56.000Z", "avg_line_length": 30.1, "max_line_length": 109, "alphanum_fraction": 0.7475083056, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5830372540443253}}
{"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": "\n// solving A * X = B\n// using driver function gesv()\n// with ublas::vector<> as RHS\n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n//#define BOOST_NUMERIC_BINDINGS_NO_SANITY_CHECK\n//#define BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n\n#include <cstddef>\n#include <iostream>\n#include <boost/numeric/bindings/atlas/cblas.hpp>\n#include <boost/numeric/bindings/atlas/clapack.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector2.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/ublas/io.hpp> \n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\ntypedef ublas::matrix<double, ublas::column_major> m_t;\ntypedef ublas::vector<double> v_t; \n\nint main() {\n\n  cout << endl; \n  size_t n = 3;\n\n  m_t a (n, n);   // system matrix \n  a(0,0) = 1.; a(0,1) = 1.; a(0,2) = 1.;\n  a(1,0) = 2.; a(1,1) = 3.; a(1,2) = 1.;\n  a(2,0) = 1.; a(2,1) = -1.; a(2,2) = -1.;\n\n  v_t b (n);  // right-hand side vector\n  b(0) = 4.; b(1) = 9.; b(2) = -2.; \n\n  cout << \"A: \" << a << endl; \n  cout << \"B: \" << b << endl; \n\n  atlas::lu_solve (a, b);  \n  cout << \"X: \" << b << endl; \n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "026d23fc7050f50c0af60c38bd5cbe6138ae4618", "size": 1257, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_gesv4.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_gesv4.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_gesv4.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 24.1730769231, "max_line_length": 58, "alphanum_fraction": 0.6435958632, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262968, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5829485704895222}}
{"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": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n    This is an example that shows some reasonable ways you can perform\n    model selection with the dlib C++ Library.  \n\n    It will create a simple set of data and then show you how to use \n    the cross validation and optimization routines to determine good model \n    parameters for the purpose of training an svm to classify the sample data.\n\n    The data used in this example will be 2 dimensional data and will\n    come from a distribution where points with a distance less than 10\n    from the origin are labeled +1 and all other points are labeled\n    as -1.\n        \n\n    As an side, you should probably read the svm_ex.cpp and matrix_ex.cpp example \n    programs before you read this one.\n*/\n\n\n#include <iostream>\n#include <dlib/svm.h>\n\nusing namespace std;\nusing namespace dlib;\n\n// The svm functions use column vectors to contain a lot of the data on which they \n// operate. So the first thing we do here is declare a convenient typedef.  \n\n// This typedef declares a matrix with 2 rows and 1 column.  It will be the\n// object that contains each of our 2 dimensional samples.   \ntypedef matrix<double, 2, 1> sample_type;\n\n// This is a typedef for the type of kernel we are going to use in this example.\n// In this case I have selected the radial basis kernel that can operate on our\n// 2D sample_type objects\ntypedef radial_basis_kernel<sample_type> kernel_type;\n\n\n\n\nclass cross_validation_objective\n{\n    /*!\n        WHAT THIS OBJECT REPRESENTS\n            This object is a simple function object that takes a set of model\n            parameters and returns a number indicating how \"good\" they are.  It\n            does this by performing 10 fold cross validation on our dataset\n            and reporting the accuracy.\n\n            See below in main() for how this object gets used. \n    !*/\npublic:\n\n    cross_validation_objective (\n        const std::vector<sample_type>& samples_,\n        const std::vector<double>& labels_\n    ) : samples(samples_), labels(labels_) {}\n\n    double operator() (\n        const matrix<double>& params\n    ) const\n    {\n        // Pull out the two SVM model parameters.  Note that, in this case,\n        // I have setup the parameter search to operate in log scale so we have\n        // to remember to call exp() to put the parameters back into a normal scale.\n        const double gamma = exp(params(0));\n        const double nu    = exp(params(1));\n\n        // Make an SVM trainer and tell it what the parameters are supposed to be.\n        svm_nu_trainer<kernel_type> trainer;\n        trainer.set_kernel(kernel_type(gamma));\n        trainer.set_nu(nu);\n\n        // Finally, perform 10-fold cross validation and then print and return the results.\n        matrix<double> result = cross_validate_trainer(trainer, samples, labels, 10);\n        cout << \"gamma: \" << setw(11) << gamma << \"  nu: \" << setw(11) << nu <<  \"  cross validation accuracy: \" << result;\n\n        // Here I'm just summing the accuracy on each class.  However, you could do something else.  \n        // For example, your application might require a 90% accuracy on class +1 and so you could\n        // heavily penalize results that didn't obtain the desired accuracy.  Or similarly, you \n        // might use the roc_c1_trainer() function to adjust the trainer output so that it always\n        // obtained roughly a 90% accuracy on class +1.  In that case returning the sum of the two\n        // class accuracies might be appropriate.  \n        return sum(result);\n    }\n\n    const std::vector<sample_type>& samples;\n    const std::vector<double>& labels;\n\n};\n\n\nint main()\n{\n    try\n    {\n\n        // Now we make objects to contain our samples and their respective labels.\n        std::vector<sample_type> samples;\n        std::vector<double> labels;\n\n        // Now lets put some data into our samples and labels objects.  We do this\n        // by looping over a bunch of points and labeling them according to their\n        // distance from the origin.\n        for (double r = -20; r <= 20; r += 0.8)\n        {\n            for (double c = -20; c <= 20; c += 0.8)\n            {\n                sample_type samp;\n                samp(0) = r;\n                samp(1) = c;\n                samples.push_back(samp);\n\n                // if this point is less than 10 from the origin\n                if (sqrt(r*r + c*c) <= 10)\n                    labels.push_back(+1);\n                else\n                    labels.push_back(-1);\n\n            }\n        }\n\n        cout << \"Generated \" << samples.size() << \" points\" << endl;\n\n\n        // Here we normalize all the samples by subtracting their mean and dividing by their standard deviation.\n        // This is generally a good idea since it often heads off numerical stability problems and also \n        // prevents one large feature from smothering others.  Doing this doesn't matter much in this example\n        // so I'm just doing this here so you can see an easy way to accomplish this with \n        // the library.  \n        vector_normalizer<sample_type> normalizer;\n        // let the normalizer learn the mean and standard deviation of the samples\n        normalizer.train(samples);\n        // now normalize each sample\n        for (unsigned long i = 0; i < samples.size(); ++i)\n            samples[i] = normalizer(samples[i]); \n\n\n        // Now that we have some data we want to train on it.  However, there are two parameters to the \n        // training.  These are the nu and gamma parameters.  Our choice for these parameters will \n        // influence how good the resulting decision function is.  To test how good a particular choice \n        // of these parameters is we can use the cross_validate_trainer() function to perform n-fold cross\n        // validation on our training data.  However, there is a problem with the way we have sampled \n        // our distribution above.  The problem is that there is a definite ordering to the samples.  \n        // That is, the first half of the samples look like they are from a different distribution \n        // than the second half.  This would screw up the cross validation process but we can \n        // fix it by randomizing the order of the samples with the following function call.\n        randomize_samples(samples, labels);\n\n\n        // The nu parameter has a maximum value that is dependent on the ratio of the +1 to -1 \n        // labels in the training data.  This function finds that value.  The 0.999 is here because\n        // the maximum allowable nu is strictly less than the value returned by maximum_nu().  So\n        // rather than dealing with that below we can just back away from it a little bit here and then\n        // not worry about it.\n        const double max_nu = 0.999*maximum_nu(labels);\n\n\n\n        // The first kind of model selection we will do is a simple grid search.  That is, below we just\n        // generate a fixed grid of points (each point represents one possible setting of the model parameters)\n        // and test each via cross validation.\n\n        // This code generates a 4x4 grid of logarithmically spaced points.  The result is a matrix\n        // with 2 rows and 16 columns where each column represents one of our points. \n        matrix<double> params = cartesian_product(logspace(log10(5.0), log10(1e-5), 4),  // gamma parameter\n                                                  logspace(log10(max_nu), log10(1e-5), 4) // nu parameter\n                                                  );\n        // As an aside, if you wanted to do a grid search over points of dimensionality more than two\n        // you would just nest calls to cartesian_product().  You can also use linspace() to generate \n        // linearly spaced points if that is more appropriate for the parameters you are working with.   \n\n\n        // Next we loop over all the points we generated and check how good each is.\n        cout << \"Doing a grid search\" << endl;\n        matrix<double> best_result(2,1);\n        best_result = 0;\n        double best_gamma = 0.1, best_nu;\n        for (long col = 0; col < params.nc(); ++col)\n        {\n            // pull out the current set of model parameters\n            const double gamma = params(0, col);\n            const double nu    = params(1, col);\n\n            // setup a training object using our current parameters\n            svm_nu_trainer<kernel_type> trainer;\n            trainer.set_kernel(kernel_type(gamma));\n            trainer.set_nu(nu);\n\n            // Finally, do 10 fold cross validation and then check if the results are the best we have seen so far.\n            matrix<double> result = cross_validate_trainer(trainer, samples, labels, 10);\n            cout << \"gamma: \" << setw(11) << gamma << \"  nu: \" << setw(11) << nu <<  \"  cross validation accuracy: \" << result;\n\n            // save the best results\n            if (sum(result) > sum(best_result))\n            {\n                best_result = result;\n                best_gamma = gamma;\n                best_nu = nu;\n            }\n        }\n\n        cout << \"\\n best result of grid search: \" << sum(best_result) << endl;\n        cout << \" best gamma: \" << best_gamma << \"   best nu: \" << best_nu << endl;\n\n\n\n        // Grid search is a very simple brute force method.  Below we try out the BOBYQA algorithm.\n        // It is a routine that performs optimization of a function in the absence of derivatives.  \n\n        cout << \"\\n\\n Try the BOBYQA algorithm\" << endl;\n\n        // We need to supply a starting point for the optimization.  Here we are using the best\n        // result of the grid search.  Generally, you want to try and give a reasonable starting\n        // point due to the possibility of the optimization getting stuck in a local maxima.  \n        params.set_size(2,1);\n        params = best_gamma, // initial gamma\n                 best_nu;    // initial nu\n\n        // We also need to supply lower and upper bounds for the search.  \n        matrix<double> lower_bound(2,1), upper_bound(2,1);\n        lower_bound = 1e-7,   // smallest allowed gamma\n                      1e-7;   // smallest allowed nu\n        upper_bound = 100,    // largest allowed gamma\n                      max_nu; // largest allowed nu\n\n\n        // For the gamma and nu SVM parameters it is generally a good idea to search\n        // in log space.  So I'm just converting them into log space here before\n        // we start the optimization.\n        params = log(params);\n        lower_bound = log(lower_bound);\n        upper_bound = log(upper_bound);\n\n        // Finally, ask BOBYQA to look for the best set of parameters.  Note that we are using the\n        // cross validation function object defined at the top of the file.\n        double best_score = find_max_bobyqa(\n            cross_validation_objective(samples, labels), // Function to maximize\n            params,                                      // starting point\n            params.size()*2 + 1,                         // See BOBYQA docs, generally size*2+1 is a good setting for this\n            lower_bound,                                 // lower bound \n            upper_bound,                                 // upper bound\n            min(upper_bound-lower_bound)/10,             // search radius\n            0.01,                                        // desired accuracy\n            100                                          // max number of allowable calls to cross_validation_objective()\n            );\n\n        // Don't forget to convert back from log scale to normal scale\n        params = exp(params);\n\n        cout << \" best result of BOBYQA: \" << best_score << endl;\n        cout << \" best gamma: \" << params(0) << \"   best nu: \" << params(1) << endl;\n\n        // Also note that the find_max_bobyqa() function only works for optimization problems\n        // with 2 variables or more.  If you only have a single variable then you should use\n        // the find_max_single_variable() function.\n\n    }\n    catch (exception& e)\n    {\n        cout << e.what() << endl;\n    }\n}\n\n", "meta": {"hexsha": "11e6a274870eaf4b7dde0ddfeacfb0f230b79cc6", "size": 12107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DynamicGestures/dlib-18.5/examples/model_selection_ex.cpp", "max_stars_repo_name": "uiuyuty/vsfh", "max_stars_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2015-03-02T09:30:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T07:07:57.000Z", "max_issues_repo_path": "DynamicGestures/dlib-18.5/examples/model_selection_ex.cpp", "max_issues_repo_name": "uiuyuty/vsfh", "max_issues_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-04-01T21:28:24.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-30T21:39:28.000Z", "max_forks_repo_path": "DynamicGestures/dlib-18.5/examples/model_selection_ex.cpp", "max_forks_repo_name": "uiuyuty/vsfh", "max_forks_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-03-02T18:48:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T06:44:08.000Z", "avg_line_length": 45.3445692884, "max_line_length": 127, "alphanum_fraction": 0.6186503676, "num_tokens": 2671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.582947835240729}}
{"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 BOOST_TEST_MODULE test_leg\n\n\n#include <boost/test/unit_test.hpp>\n#include \"Leg/FixedLeg.h\"\n#include <Leg/ZeroCurve/ZeroCouponCurve.h>\n#include <../Tir/Tir.h>\n\nnamespace utf = boost::unit_test;\n\n\nBOOST_AUTO_TEST_SUITE(leg_test_suite)\n\n    BOOST_AUTO_TEST_CASE(fixed_day_fraction, * utf::tolerance(0.0000001)) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const double notional = 100;\n        const double rate = 5.0/100;\n        std::vector<boost::gregorian::date> referenceDates {};\n        referenceDates.push_back(boost::gregorian::from_string(\"2016-4-01\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2016-10-03\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2017-04-03\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2017-10-02\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2018-04-02\"));\n\n        Actual_360 actualCalc = Actual_360();\n\n        ZeroCouponCurve zeroCouponCurve {};\n\n        FixedLeg myLeg {notional, rate, referenceDates, actualCalc, zeroCouponCurve};\n        std::vector<double> calculated_values = myLeg.getDayCountFractionVector();\n\n        double myDoubles[] = {0.513888888, 0.505555555, 0.505555555, 0.505555555 };\n        std::vector<double> expected_values (myDoubles, myDoubles + sizeof(myDoubles) / sizeof(double) );\n\n\n        //BOOST_TEST_MESSAGE(\" - Calculated Value: \" << calculated_values);\n        //BOOST_TEST_MESSAGE(\" - Expected Value: \" << expected_values);\n        BOOST_TEST(calculated_values == expected_values,  boost::test_tools::per_element());\n    }\n\n    BOOST_AUTO_TEST_CASE(fixed_cash_flows, * utf::tolerance(0.0001)) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const double notional = 100;\n        const double rate = 5.0/100;\n        std::vector<boost::gregorian::date> referenceDates {};\n        referenceDates.push_back(boost::gregorian::from_string(\"2016-04-01\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2016-10-03\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2017-04-03\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2017-10-02\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2018-04-02\"));\n\n        Actual_360 actualCalc = Actual_360();\n\n        ZeroCouponCurve zeroCouponCurve {};\n\n        FixedLeg myLeg {notional, rate, referenceDates, actualCalc, zeroCouponCurve};\n\n        double myDoubles[] = {0.51388888888, 0.505555555555, 0.505555555555, 0.505555555555 };\n        std::vector<double> dayCountFractionVector (myDoubles, myDoubles + sizeof(myDoubles) / sizeof(double) );\n\n        std::vector<double> calculated_values = myLeg.getLegCashFlows(dayCountFractionVector);\n\n        double myResults[] = {2.569444, 2.527777, 2.527777, 2.527777};\n        std::vector<double> expected_values (myResults, myResults + sizeof(myResults) / sizeof(double) );\n\n        //BOOST_TEST_MESSAGE(\" - Calculated Value: \" << calculated_values);\n        //BOOST_TEST_MESSAGE(\" - Expected Value: \" << expected_values);\n        BOOST_TEST(calculated_values == expected_values,  boost::test_tools::per_element());\n    }\n\n    BOOST_AUTO_TEST_CASE(actual_count) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const double notional = 100;\n        const double rate = 5.0/100;\n        std::vector<boost::gregorian::date> referenceDates {};\n        referenceDates.push_back(boost::gregorian::from_string(\"2016-04-01\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2016-10-03\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2017-04-03\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2017-10-02\"));\n        referenceDates.push_back(boost::gregorian::from_string(\"2018-04-02\"));\n\n        Actual_360 actualCalc = Actual_360();\n        ZeroCouponCurve zeroCouponCurve {};\n        Tir tir = Tir(notional, rate, referenceDates, actualCalc);\n\n        //Tir tir = Tir();\n\n        double expected_values = 6.76;\n\n        double calculated_values = tir.Get_Tir(6.76, 0.2);\n\n        BOOST_TEST_MESSAGE(\" - Calculated Value: \" << calculated_values);\n        BOOST_TEST_MESSAGE(\" - Expected Value: \" << expected_values);\n        BOOST_TEST_MESSAGE(\" - Diff \" << calculated_values - expected_values);\n        BOOST_TEST(expected_values == calculated_values, boost::test_tools::tolerance(1e-15));\n    }\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d0223e120256e720e7eae5a360b1243a7229c95e", "size": 4473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "assignment1/src/Leg/tests/test.cpp", "max_stars_repo_name": "paulochang/frontoffice-assignment1", "max_stars_repo_head_hexsha": "574c62dedfc0a5c060924a38d51b80aaca48ff23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-04-24T14:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-24T14:51:39.000Z", "max_issues_repo_path": "assignment1/src/Leg/tests/test.cpp", "max_issues_repo_name": "paulochang/frontoffice-assignment1", "max_issues_repo_head_hexsha": "574c62dedfc0a5c060924a38d51b80aaca48ff23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment1/src/Leg/tests/test.cpp", "max_forks_repo_name": "paulochang/frontoffice-assignment1", "max_forks_repo_head_hexsha": "574c62dedfc0a5c060924a38d51b80aaca48ff23", "max_forks_repo_licenses": ["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.0096153846, "max_line_length": 112, "alphanum_fraction": 0.6892465907, "num_tokens": 1108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5829478240071734}}
{"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": "#include <ros/ros.h>\n#include <nav_msgs/Odometry.h>\n#include <vicon/Subject.h>\n#include <vicon_odom/filter.h>\n#include <Eigen/Geometry>\n#include <tf2_ros/transform_broadcaster.h>\n\nstatic ros::Publisher odom_pub;\nstatic KalmanFilter kf;\nstatic nav_msgs::Odometry odom_msg;\nstatic tf2_ros::TransformBroadcaster* tfb;\n\nstatic std::string fixed_frame_id;\nstatic std::string base_frame_id;\n\nstatic void vicon_callback(const vicon::Subject::ConstPtr &msg)\n{\n  static ros::Time t_last_proc = msg->header.stamp;\n\n  double dt = (msg->header.stamp - t_last_proc).toSec();\n  t_last_proc = msg->header.stamp;\n\n  // Kalman filter for getting translational velocity from position measurements\n  kf.processUpdate(dt);\n  const KalmanFilter::Measurement_t meas(msg->position.x, msg->position.y, msg->position.z);\n  if(!msg->occluded)\n  {\n    static ros::Time t_last_meas = msg->header.stamp;\n    double meas_dt = (msg->header.stamp - t_last_meas).toSec();\n    t_last_meas = msg->header.stamp;\n    kf.measurementUpdate(meas, meas_dt);\n  }\n\n  const KalmanFilter::State_t state = kf.getState();\n  const KalmanFilter::ProcessCov_t proc_noise = kf.getProcessNoise();\n\n  odom_msg.header.seq = msg->header.seq;\n  odom_msg.header.stamp = msg->header.stamp;\n  odom_msg.header.frame_id = fixed_frame_id;\n  odom_msg.child_frame_id = base_frame_id;\n  odom_msg.pose.pose.position.x = state(0);\n  odom_msg.pose.pose.position.y = state(1);\n  odom_msg.pose.pose.position.z = state(2);\n  odom_msg.twist.twist.linear.x = state(3);\n  odom_msg.twist.twist.linear.y = state(4);\n  odom_msg.twist.twist.linear.z = state(5);\n  for(int i = 0; i < 3; i++)\n  {\n    for(int j = 0; j < 3; j++)\n    {\n      odom_msg.pose.covariance[6*i+j] = proc_noise(i,j);\n      odom_msg.twist.covariance[6*i+j] = proc_noise(3+i, 3+j);\n    }\n  }\n\n  odom_msg.pose.pose.orientation.x = msg->orientation.x;\n  odom_msg.pose.pose.orientation.y = msg->orientation.y;\n  odom_msg.pose.pose.orientation.z = msg->orientation.z;\n  odom_msg.pose.pose.orientation.w = msg->orientation.w;\n\n  // Single step differentitation for angular velocity\n  static Eigen::Matrix3d R_prev(Eigen::Matrix3d::Identity());\n  Eigen::Matrix3d R(Eigen::Quaterniond(msg->orientation.w, msg->orientation.x, msg->orientation.y, msg->orientation.z));\n  if(dt > 1e-6)\n  {\n    Eigen::Matrix3d R_dot = (R - R_prev)/dt;\n    Eigen::Matrix3d w_hat = R_dot * R.transpose();\n\n    odom_msg.twist.twist.angular.x = w_hat(2, 1);\n    odom_msg.twist.twist.angular.y = w_hat(0, 2);\n    odom_msg.twist.twist.angular.z = w_hat(1, 0);\n  }\n  R_prev = R;\n\n  odom_pub.publish(odom_msg);\n\n  geometry_msgs::TransformStamped ts;\n  ts.transform.translation.x = odom_msg.pose.pose.position.x;\n  ts.transform.translation.y = odom_msg.pose.pose.position.y;\n  ts.transform.translation.z = odom_msg.pose.pose.position.z;\n  ts.transform.rotation.x = odom_msg.pose.pose.orientation.x;\n  ts.transform.rotation.y = odom_msg.pose.pose.orientation.y;\n  ts.transform.rotation.z = odom_msg.pose.pose.orientation.z;\n  ts.transform.rotation.w = odom_msg.pose.pose.orientation.w;\n  ts.header = odom_msg.header;\n  ts.child_frame_id = odom_msg.child_frame_id;\n  tfb->sendTransform(ts);\n}\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"vicon_odom\");\n\n  ros::NodeHandle n(\"~\");\n\n  tfb = new tf2_ros::TransformBroadcaster();\n\n  if (!n.hasParam(\"frame_id/fixed\"))\n  {\n    ROS_ERROR(\"vicon_odom: failed to find param 'frame_id/fixed'\");\n    return EXIT_FAILURE;\n  }\n  n.getParam(\"frame_id/fixed\", fixed_frame_id);\n\n  if (!n.hasParam(\"frame_id/base\"))\n  {\n    ROS_ERROR(\"vicon_odom: failed to find param 'frame_id/fixed'\");\n    return EXIT_FAILURE;\n  }\n  n.getParam(\"frame_id/base\", base_frame_id);\n\n  double max_accel;\n  n.param(\"max_accel\", max_accel, 5.0);\n\n  double dt, vicon_fps;\n  n.param(\"vicon_fps\", vicon_fps, 100.0);\n  ROS_ASSERT(vicon_fps > 0.0);\n  dt = 1/vicon_fps;\n\n  KalmanFilter::State_t proc_noise_diag;\n  proc_noise_diag(0) = 0.5*max_accel*dt*dt;\n  proc_noise_diag(1) = 0.5*max_accel*dt*dt;\n  proc_noise_diag(2) = 0.5*max_accel*dt*dt;\n  proc_noise_diag(3) = max_accel*dt;\n  proc_noise_diag(4) = max_accel*dt;\n  proc_noise_diag(5) = max_accel*dt;\n  proc_noise_diag = proc_noise_diag.array().square();\n  KalmanFilter::Measurement_t meas_noise_diag;\n  meas_noise_diag(0) = 1e-4;\n  meas_noise_diag(1) = 1e-4;\n  meas_noise_diag(2) = 1e-4;\n  meas_noise_diag = meas_noise_diag.array().square();\n  kf.initialize(KalmanFilter::State_t::Zero(),\n                0.01*KalmanFilter::ProcessCov_t::Identity(),\n                proc_noise_diag.asDiagonal(),\n                meas_noise_diag.asDiagonal());\n\n  ros::Subscriber vicon_sub = n.subscribe(\"vicon\", 10, &vicon_callback,\n                                          ros::TransportHints().tcpNoDelay());\n\n  odom_pub = n.advertise<nav_msgs::Odometry>(\"odom\", 10);\n\n  ros::spin();\n\n  return 0;\n}\n", "meta": {"hexsha": "55db163816bb8d378fb475a612e1ec8e0f697821", "size": 4814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vicon_odom/src/vicon_odom.cpp", "max_stars_repo_name": "zheng-rong/vicon_mocap", "max_stars_repo_head_hexsha": "43baabf440cfebc00dc48532c939b46683ffebe3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vicon_odom/src/vicon_odom.cpp", "max_issues_repo_name": "zheng-rong/vicon_mocap", "max_issues_repo_head_hexsha": "43baabf440cfebc00dc48532c939b46683ffebe3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vicon_odom/src/vicon_odom.cpp", "max_forks_repo_name": "zheng-rong/vicon_mocap", "max_forks_repo_head_hexsha": "43baabf440cfebc00dc48532c939b46683ffebe3", "max_forks_repo_licenses": ["BSD-3-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.7482993197, "max_line_length": 120, "alphanum_fraction": 0.7008724553, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.58293560963201}}
{"text": "/*!\n  \\file gpp_linear_algebra_test.cpp\n  \\rst\n  Routines to test the functions in gpp_linear_algebra.cpp and gpp_linear_algebra-inl.hpp.\n\n  This includes a battery of tests that verify that all of our linear algebra subroutines are working correctly.  These tests\n  fall into a few categories:\n\n  1. manually verifying a general function (e.g., GeneralMatrixVectorMultiply) and then using that to\n     verify special cases (e.g., Triangular and Symmetric multiply).\n  2. asserting properties of the underlying matrices or operators: e.g., Q*Q^T = I for Q known to be orthogonal, or X*X^-1 = I, etc.\n  3. checking correctness against simple, hand-verified cases\n  4. checking results against analytically known (usually norm-wise) error bounds, taking conditioning into account over\n     well- and ill-conditioned inputs\n\n  These tests live in the functions called through RunLinearAlgebraTests().\n\n  This file also has implementations various Build.*() functions, which provide interesting inputs for the linear algebra\n  testing.  These include various random matrices (random, symmetric, SPD), interesting \"standard\" matrix examples\n  (prolate, moler, orthogonal symmetric) as well as some matrices with interesting properties resulting from things like\n  Householder Reflections.  We also have some utilites for data manipulation (e.g., extracting the lower triangle) as well as\n  routines to manipulate condition number (e.g., adding diagonal dominance).\n\\endrst*/\n\n#include \"gpp_linear_algebra_test.hpp\"\n\n#include <cmath>\n#include <cstdlib>\n\n#include <algorithm>\n#include <limits>\n#include <vector>\n\n#include <boost/random/uniform_real.hpp>  // NOLINT(build/include_order)\n\n#include \"gpp_common.hpp\"\n#include \"gpp_covariance.hpp\"\n#include \"gpp_exception.hpp\"\n#include \"gpp_linear_algebra.hpp\"\n#include \"gpp_linear_algebra-inl.hpp\"\n#include \"gpp_logging.hpp\"\n#include \"gpp_random.hpp\"\n#include \"gpp_test_utils.hpp\"\n\nnamespace optimal_learning {\n\nvoid BuildIdentityMatrix(int size_m, double * restrict matrix) noexcept {\n  std::fill(matrix, matrix + size_m*size_m, 0.0);\n  for (int i = 0; i < size_m; ++i) {\n    matrix[0] = 1.0;\n    matrix += size_m+1;  // puts us exactly on the next diagonal entry\n  }\n}\n\n/*!\\rst\n  ``A_{i,j} = { 2 * \\alpha                                 if i == j``\n  ``          { \\sin(2 * \\pi * \\alpha * k)/ (\\pi * k)      otherwise``\n  where ``k = |i - j|``\n\\endrst*/\nvoid BuildProlateMatrix(double alpha, int size, double * restrict prolate_matrix) noexcept {\n  for (int j = 0; j < size; ++j) {\n    for (int i = 0; i < size; ++i) {\n      if (i == j) {\n        prolate_matrix[j*size + i] = 2.0 * alpha;\n      } else {\n        int k = std::abs(i-j);\n        double angle = 2.0 * kPi * alpha * static_cast<double>(k);\n        prolate_matrix[j*size + i] = std::sin(angle)/(kPi * static_cast<double>(k));\n      }\n    }\n  }\n}\n\n/*!\\rst\n  ``A_{ij} = { i * alpha^2 + 1.0               if i == j``\n  ``         { min(i, j) * alpha^2 + alpha     otherwise``\n\\endrst*/\nvoid BuildMolerMatrix(double alpha, int size, double * restrict moler_matrix) noexcept {\n  for (int j = 0; j < size; ++j) {\n    for (int i = 0; i < size; ++i) {\n      if (i == j) {\n        moler_matrix[j*size + i] = i * alpha * alpha + 1.0;\n      } else {\n        moler_matrix[j*size + i] = std::min(i, j) * alpha * alpha + alpha;\n      }\n    }\n  }\n}\n\n/*!\\rst\n  Builds a matrix ``Q`` s.t. ``Q * Q^T = I``, ``Q = Q^T``, and ``\\|Q*x\\| = \\|x\\|``.  In particular, ``Q` is (real) orthogonal\n  AND symmetric.  This is not the only ``Q`` with the given properties.  ``Q`` is not SPD.\n\n  This is the eigenvector matrix for a n-point second-difference matrix (e.g., discrete hessian).\n\\endrst*/\nvoid BuildOrthogonalSymmetricMatrix(int size, double * restrict orthog_symm_matrix) noexcept {\n  for (int j = 0; j < size; ++j) {\n    for (int i = 0; i < size; ++i) {\n      // angle = 2.0 * (i+1) * (j+1) * kPi / static_cast<double>(2*size +1);\n      // orthog_symm_matrix[j*size + i] = 2.0 * std::sin(angle) / std::sqrt(static_cast<double>(2*size + 1));\n      double angle = (i+1) * (j+1) * kPi / static_cast<double>(size+1);\n      orthog_symm_matrix[j*size + i] = std::sqrt(2.0/static_cast<double>(size+1)) * std::sin(angle);\n    }\n  }\n}\n\n/*!\\rst\n  Randomly generates half (diagonal and one triangle) of a matrix and copies those values into the other half.\n  The result is not guaranteed to have any special properties (e.g., SPD) beyond symmetry.\n\\endrst*/\nvoid BuildRandomSymmetricMatrix(int size, double left_bound, double right_bound, UniformRandomGenerator * uniform_generator, double * restrict symmetric_matrix) noexcept {\n  boost::uniform_real<double> uniform_double(left_bound, right_bound);\n  for (int j = 0; j < size; ++j) {\n    for (int i = 0; i < size; ++i) {\n      double temp = uniform_double(uniform_generator->engine);\n      symmetric_matrix[j*size + i] = temp;\n      symmetric_matrix[i*size + j] = temp;\n    }\n  }\n}\n\n/*!\\rst\n  Randomly generates a lower triangular matrix, zeroing the upper triangle.\n\\endrst*/\nvoid BuildRandomLowerTriangularMatrix(int size, UniformRandomGenerator * uniform_generator, double * restrict lower_triangular_matrix) noexcept {\n  boost::uniform_real<double> uniform_double_unit_interval(0.0, 1.0);\n\n  for (int i = 0; i < size; ++i) {\n    for (int j = 0; j < i; ++j) {\n      lower_triangular_matrix[i*size + j] = 0.0;\n    }\n    for (int j = i; j < size; ++j) {\n      double temp = uniform_double_unit_interval(uniform_generator->engine);\n      lower_triangular_matrix[i*size + j] = temp;\n    }\n  }\n}\n\n/*!\\rst\n  A matrix ``A`` is SPD if and only if it can be cholesky-factored: ``L * L^T = A``.\n  Generate ``L`` randomly and form ``A``.\n\\endrst*/\nvoid BuildRandomSPDMatrix(int size, UniformRandomGenerator * uniform_generator, double * restrict spd_matrix) noexcept {\n  std::vector<double> lower_triangular_matrix(size*size);\n  std::vector<double> upper_triangular_matrix(size*size);\n  BuildRandomLowerTriangularMatrix(size, uniform_generator, lower_triangular_matrix.data());\n  MatrixTranspose(lower_triangular_matrix.data(), size, size, upper_triangular_matrix.data());\n\n  GeneralMatrixMatrixMultiply(lower_triangular_matrix.data(), 'N', upper_triangular_matrix.data(), 1.0, 0.0, size, size, size, spd_matrix);\n}\n\n/*!\\rst\n  The matrix ``F`` (householder) as a function of ``x`` (vector) where:\n  ``F = I - 2 * v*v^T``,\n  where ``v = w / ||w||_2``,\n  and   ``w = sign(x[0]) * \\|x\\|_2 * e_0 + x``  (``e_0`` is the cartesian unit vector, ``[1; zeros(n-1,1)]``)\n\\endrst*/\nvoid BuildHouseholderReflectorMatrix(double const * restrict vector, int size, double * restrict householder) noexcept {\n  double norm_of_vector = VectorNorm(vector, size);\n\n  std::vector<double> v(vector, vector+size);\n  v[0] += std::copysign(norm_of_vector, vector[0]);\n\n  double norm_of_v = VectorNorm(v.data(), size);\n  VectorScale(size, 1.0/norm_of_v, v.data());\n\n  BuildIdentityMatrix(size, householder);\n  for (int i = 0; i < size; ++i) {\n    for (int j = 0; j < size; ++j) {\n      householder[i*size + j] -= 2.0*v[i]*v[j];\n    }\n  }\n}\n\nvoid BuildRandomVector(int size, double left_bound, double right_bound, UniformRandomGenerator * uniform_generator, double * restrict vector) noexcept {\n  boost::uniform_real<double> uniform_double(left_bound, right_bound);\n  for (int i = 0; i < size; ++i) {\n    vector[i] = uniform_double(uniform_generator->engine);\n  }\n}\n\nbool CheckMatrixIsSymmetric(double const * restrict matrix, int size, double tolerance) noexcept {\n  bool symmetric_flag = true;\n  for (int j = 0; j < size; ++j) {\n    for (int i = 0; i < size; ++i) {\n      if (CheckDoubleWithinRelative(matrix[j*size +i], matrix[i*size + j], tolerance) == false) {\n        symmetric_flag = false;\n        return symmetric_flag;\n      }\n    }\n  }\n\n  return symmetric_flag;\n}\n\nnamespace {\n\n/*!\\rst\n  Adds ``scale*eye(size)`` to the result of BuildRandomSPDMatrix.\n\n  Adding positive numbers to the diagonal will significantly improve conditioning (thus turning\n  any ill-conditioned example matrix in this file into a well-conditioned one).\n\\endrst*/\nOL_NONNULL_POINTERS void ModifyMatrixDiagonal(int size, double scale, double * restrict spd_matrix) noexcept {\n  for (int i = 0; i < size; ++i) {\n    spd_matrix[0] += scale;\n    spd_matrix += size + 1;  // puts us exactly on the next diagonal entry\n  }\n}\n\nOL_NONNULL_POINTERS void ExtractLowerTriangularPart(double const * restrict matrix, int size, double * restrict lower_triangular_matrix) noexcept {\n  std::fill(lower_triangular_matrix, lower_triangular_matrix + size*size, 0.0);\n  for (int i = 0; i < size; ++i) {\n    for (int j = i; j < size; ++j) {\n      lower_triangular_matrix[i*size + j] = matrix[i*size + j];\n    }\n  }\n}\n\n/*!\\rst\n  Check Cholesky factorization.\n  Uses:\n\n  1. Some simple test cases with whole-number results.\n  2. Generate random SPD matrices. Factor them. Check that the factorization is close to the original matrix.\n\n  \\return\n    number of invalid entries in the factorizations\n\\endrst*/\nOL_WARN_UNUSED_RESULT int TestCholesky() {\n  int total_errors = 0;\n\n  // simple hand-spun tests with small integer inputs/outputs so that\n  // floating point error is non-existent\n  {  // hide scope\n    static const int kSize1 = 4;\n    static const int kSize2 = 3;\n    double matrix_A[kSize1*kSize1] =\n        {81.0, 27.0, 0.0, 90.0,\n         27.0, 13.0, 8.0, 44.0,\n         0.0, 8.0, 52.0, 40.0,\n         90.0, 44.0, 40.0, 217.0\n        };\n    double cholesky_A_exact[kSize1*kSize1] =\n        {9.0, 3.0, 0.0, 10.0,\n         0.0, 2.0, 4.0, 7.0,\n         0.0, 0.0, 6.0, 2.0,\n         0.0, 0.0, 0.0, 8.0\n        };\n    double cholesky_A_computed[kSize1*kSize1];\n\n    double matrix_B[kSize2*kSize2] =\n        {25.0, 15.0, -5.0,\n         15.0, 18.0, 0.0,\n         -5.0, 0.0, 11.0\n        };\n    double cholesky_B_exact[kSize2*kSize2] =\n        {5.0, 3.0, -1.0,\n         0.0, 3.0, 1.0,\n         0.0, 0.0, 3.0\n        };\n    double cholesky_B_computed[kSize2*kSize2];\n\n    std::copy(matrix_A, matrix_A + kSize1*kSize1, cholesky_A_computed);\n    if (ComputeCholeskyFactorL(kSize1, cholesky_A_computed) != 0) {\n      ++total_errors;\n    }\n    ZeroUpperTriangle(kSize1, cholesky_A_computed);\n\n    std::copy(matrix_B, matrix_B + kSize2*kSize2, cholesky_B_computed);\n    if (ComputeCholeskyFactorL(kSize2, cholesky_B_computed) != 0) {\n      ++total_errors;\n    }\n    ZeroUpperTriangle(kSize2, cholesky_B_computed);\n\n    for (int i = 0; i < kSize1*kSize1; ++i) {\n      if (!CheckDoubleWithinRelative(cholesky_A_computed[i], cholesky_A_exact[i], 0.0)) {\n        ++total_errors;\n      }\n    }\n\n    for (int i = 0; i < kSize2*kSize2; ++i) {\n      if (!CheckDoubleWithinRelative(cholesky_B_computed[i], cholesky_B_exact[i], 0.0)) {\n        ++total_errors;\n      }\n    }\n  }\n\n  const int num_tests = 3;\n  const int sizes[num_tests] = {5, 11, 20};\n\n  UniformRandomGenerator uniform_generator(34187);\n  // in each iteration, we form a random SPD matrix, A.\n  // we then Cholesky factor it: L * L^T = A.\n  // then we compare the product L * L^T to A and ensure that the deviation is small.\n  for (int i = 0; i < num_tests; ++i) {\n    std::vector<double> spd_matrix(sizes[i]*sizes[i]);\n    std::vector<double> cholesky_factor(sizes[i]*sizes[i]);\n    std::vector<double> cholesky_factor_T(sizes[i]*sizes[i]);\n    std::vector<double> product_matrix(sizes[i]*sizes[i]);\n\n    // this can be badly conditioned but we don't care\n    BuildRandomSPDMatrix(sizes[i], &uniform_generator, spd_matrix.data());\n\n    std::copy(spd_matrix.begin(), spd_matrix.end(), cholesky_factor.begin());\n    if (ComputeCholeskyFactorL(sizes[i], cholesky_factor.data()) != 0) {\n      ++total_errors;\n    }\n    ZeroUpperTriangle(sizes[i], cholesky_factor.data());\n    MatrixTranspose(cholesky_factor.data(), sizes[i], sizes[i], cholesky_factor_T.data());\n\n    // check L * L^T\n    GeneralMatrixMatrixMultiply(cholesky_factor.data(), 'N', cholesky_factor_T.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], product_matrix.data());\n\n    // backward stability of cholesky guarantees us the following:\n    // L * L^T = A + \\delta A, with ||\\delta A||/||A|| = O(\\epsilon_{machine})\n    for (int j = 0; j < sizes[i]*sizes[i]; ++j) {\n      if (!CheckDoubleWithinRelative(product_matrix[j], spd_matrix[j], 3*std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    // and again this time doing U^T * U\n    GeneralMatrixMatrixMultiply(cholesky_factor_T.data(), 'T', cholesky_factor_T.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], product_matrix.data());\n\n    // backward stability of cholesky guarantees us the following:\n    // L * L^T = A + \\delta A, with ||\\delta A||/||A|| = O(\\epsilon_{machine})\n    for (int j = 0; j < sizes[i]*sizes[i]; ++j) {\n      if (!CheckDoubleWithinRelative(product_matrix[j], spd_matrix[j], 3*std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n  }\n\n  return total_errors;\n}\n\n/*!\\rst\n  Test that SPDMatrixInverse and CholeskyFactorLMatrixVectorSolve are  working correctly\n  against some especially bad named matrices and some random inputs.\n  Outline:\n\n  1. Construct matrices, ``A``\n  2. Select a solution, ``x``, randomly.\n  3. Construct RHS by doing ``A*x``.\n  4. Solve ``Ax = b`` using backsolve and direct-inverse; check the size of ``\\|b - Ax\\|``.\n\n  \\return\n    number of test cases where the solver error is too large\n\\endrst*/\nOL_WARN_UNUSED_RESULT int TestSPDLinearSolvers() {\n  int total_errors = 0;\n\n  // simple/small case where numerical factors are not present.\n  // taken from: http://en.wikipedia.org/wiki/Cholesky_decomposition#Example\n  {\n    constexpr int size = 3;\n    std::vector<double> matrix =\n        {  4.0,   12.0, -16.0,\n          12.0,   37.0, -43.0,\n         -16.0,  -43.0,  98.0};\n\n    const std::vector<double> cholesky_factor_L_truth =\n        { 2.0, 6.0, -8.0,\n          0.0, 1.0, 5.0,\n          0.0, 0.0, 3.0};\n    std::vector<double> rhs = {-20.0, -43.0, 192.0};\n    std::vector<double> solution_truth = {1.0, 2.0, 3.0};\n\n    int local_errors = 0;\n    // check factorization is correct; only check lower-triangle\n    if (ComputeCholeskyFactorL(size, matrix.data()) != 0) {\n      ++total_errors;\n    }\n    for (int i = 0; i < size; ++i) {\n      for (int j = 0; j < size; ++j) {\n        if (j >= i) {\n          if (!CheckDoubleWithinRelative(matrix[i*size + j], cholesky_factor_L_truth[i*size + j], 0.0)) {\n            ++local_errors;\n          }\n        }\n      }\n    }\n\n    // check the solve is correct\n    CholeskyFactorLMatrixVectorSolve(matrix.data(), size, rhs.data());\n    for (int i = 0; i < size; ++i) {\n      if (!CheckDoubleWithinRelative(rhs[i], solution_truth[i], 0.0)) {\n        ++local_errors;\n      }\n    }\n\n    total_errors += local_errors;\n  }\n\n  const int num_tests = 10;\n  const int num_test_sizes = 3;\n  const int sizes[num_test_sizes] = {5, 11, 20};\n\n  // following tolerances are based on numerical experiments and/or computations\n  // of the matrix condition numbers (in MATLAB)\n  const double tolerance_backsolve_max_list[3][num_test_sizes] =\n      { {10*std::numeric_limits<double>::epsilon(), 100*std::numeric_limits<double>::epsilon(), 100*std::numeric_limits<double>::epsilon()},       // prolate\n        {100*std::numeric_limits<double>::epsilon(), 1.0e4*std::numeric_limits<double>::epsilon(), 1.0e6*std::numeric_limits<double>::epsilon()},  // moler\n        {50*std::numeric_limits<double>::epsilon(), 1.0e3*std::numeric_limits<double>::epsilon(), 5.0e4*std::numeric_limits<double>::epsilon()}    // random\n      };\n  const double tolerance_inverse_max_list[3][num_test_sizes] =\n      { {1.0e-13, 1.0e-9, 1.0e-2},  // prolate\n        {5.0e-13, 2.0e-8, 1.0e1},   // moler\n        {7.0e-10, 7.0e-6, 1.0e2}    // random\n      };\n\n  UniformRandomGenerator uniform_generator(34187);\n  // In each iteration, we form some an ill-conditioned SPD matrix.  We are using\n  // prolate, moler, and random matrices.\n  // Then we compute L * L^T = A.\n  // We want to test solutions of A * x = b using two methods:\n  //   1) Inverse: using L, we form A^-1 explicitly (ILL-CONDITIONED!)\n  //   2) Backsolve: we never form A^-1, but instead backsolve L and L^T against b.\n  // The resulting residual norms, ||b - A*x||_2 are computed; we check that\n  // backsolve is accurate and inverse is affected strongly by conditioning.\n  for (int j = 0; j < num_tests; ++j) {\n    for (int i = 0; i < num_test_sizes; ++i) {\n      std::vector<double> matrix(sizes[i]*sizes[i]);\n      std::vector<double> inverse_matrix(sizes[i]*sizes[i]);\n      std::vector<double> cholesky_factor(sizes[i]*sizes[i]);\n      std::vector<double> rhs(sizes[i]);\n      std::vector<double> solution(2*sizes[i]);\n\n      double tolerance_backsolve_max;\n      double tolerance_inverse_max;\n      switch (j) {\n        case 0: {\n          BuildProlateMatrix(kProlateDefaultParameter, sizes[i], matrix.data());\n          tolerance_backsolve_max = tolerance_backsolve_max_list[0][i];\n          tolerance_inverse_max = tolerance_inverse_max_list[0][i];\n          break;\n        }\n        case 1: {\n          BuildMolerMatrix(-1.66666666666, sizes[i], matrix.data());\n          tolerance_backsolve_max = tolerance_backsolve_max_list[1][i];\n          tolerance_inverse_max = tolerance_inverse_max_list[1][i];\n          break;\n        }\n        default: {\n          if (j <= 1 || j > num_tests) {\n            OL_THROW_EXCEPTION(BoundsException<int>, \"Invalid switch option.\", j, 2, num_tests);\n          } else {\n            BuildRandomSPDMatrix(sizes[i], &uniform_generator, matrix.data());\n            tolerance_backsolve_max = tolerance_backsolve_max_list[2][i];\n            tolerance_inverse_max = tolerance_inverse_max_list[2][i];\n            break;\n          }\n        }\n      }\n      // cholesky-factor A, form A^-1\n      std::copy(matrix.begin(), matrix.end(), cholesky_factor.begin());\n      if (ComputeCholeskyFactorL(sizes[i], cholesky_factor.data()) != 0) {\n        ++total_errors;\n      }\n      SPDMatrixInverse(cholesky_factor.data(), sizes[i], inverse_matrix.data());\n\n      // set b = A*random_vector.  This way we know the solution explicitly.\n      // this also allows us to ignore ||A|| in our computations when we\n      // normalize the RHS.\n      BuildRandomVector(sizes[i], 0.0, 1.0, &uniform_generator, solution.data());\n      SymmetricMatrixVectorMultiply(matrix.data(), solution.data(), sizes[i], rhs.data());\n\n      // re-scale the RHS so that its norm can be ignored in later computations\n      double rhs_norm = VectorNorm(rhs.data(), sizes[i]);\n      VectorScale(sizes[i], 1.0/rhs_norm, rhs.data());\n      std::copy(rhs.begin(), rhs.end(), solution.begin());\n\n      // Solve L * L^T * x1 = b (backsolve) and compute x2 = A^-1 * b\n      CholeskyFactorLMatrixVectorSolve(cholesky_factor.data(), sizes[i], solution.data());\n      SymmetricMatrixVectorMultiply(inverse_matrix.data(), rhs.data(), sizes[i], solution.data() + sizes[i]);\n\n      double norm_residual_via_backsolve = ResidualNorm(matrix.data(), solution.data(), rhs.data(), sizes[i]);\n      double norm_residual_via_inverse = ResidualNorm(matrix.data(), solution.data() + sizes[i], rhs.data(), sizes[i]);\n\n      if (norm_residual_via_backsolve > tolerance_backsolve_max) {\n        ++total_errors;\n        OL_ERROR_PRINTF(\"experiment %d, size[%d] = %d, norm_backsolve = %.18E > %.18E = tol\\n\", j, i, sizes[i],\n               norm_residual_via_backsolve, tolerance_backsolve_max);\n      }\n\n      if (norm_residual_via_inverse > tolerance_inverse_max) {\n        ++total_errors;\n        OL_ERROR_PRINTF(\"experiment %d, size[%d] = %d, norm_inverse = %.18E > %.18E = tol\\n\", j, i, sizes[i],\n               norm_residual_via_inverse, tolerance_inverse_max);\n      }\n    }\n  }\n\n  return total_errors;\n}\n\n/*!\\rst\n  Test that ``A * x`` and ``A^T * x`` work, where ``A`` is a matrix and ``x`` is a vector.\n  Outline:\n\n  1. Check different input size combinations and no/transpose setups on small hand-checked problems.\n  2. Exploit special property of Householder matrices: perform ``Ax`` and verify that the output has\n     the property (see implementation).\n\n  \\return\n    number of cases where matrix-vector multiply failed\n\\endrst*/\nOL_WARN_UNUSED_RESULT int TestGeneralMatrixVectorMultiply() noexcept {\n  int total_errors = 0;\n\n  // simple, hand-checked problems that are be minimally affected by floating point errors\n  {  // hide scope\n    static const int kSize_m = 3;  // rows\n    static const int kSize_n = 5;  // cols\n\n    double matrix_A[kSize_m*kSize_n] =\n        {-7.4, 0.1, 9.1,  // first COLUMN of A (col-major storage)\n         1.5, -8.8, -0.3,\n         -2.9, 6.4, -9.7,\n         -9.1, -6.6, 3.1,\n         4.6, 3.0, -1.0\n        };\n    double matrix_A_T[kSize_n*kSize_m];\n    const double test_vector1[kSize_n] = {1.3, -3.8, 4.2, 2.1, 0.2};\n    const double test_vector2[kSize_n] = {0.5, -2.0, -0.2, -3.1, 1.9};\n    const double result_vector1[kSize_m] = {-45.689999999999998, 47.190000000000005, -21.460000000000001};\n    const double result_vector2[kSize_m] = {30.829999999999998, 42.530000000000001, -4.420000000000002};\n    double product_vector1[kSize_m];\n\n    const double test_vector3[kSize_m] = {-3.2, 0.4, 1.3};\n    const double test_vector4[kSize_m] = {2.8, -4.2, 3.5};\n    const double result_vector3[kSize_n] = {35.550000000000004, -8.710000000000001, -0.770000000000000, 30.510000000000002, -14.820000000000000};\n    const double result_vector4[kSize_n] = {10.709999999999999, 40.110000000000014, -68.949999999999989, 13.090000000000002, -3.220000000000002};\n    double product_vector2[kSize_n];\n\n    MatrixTranspose(matrix_A, kSize_m, kSize_n, matrix_A_T);\n\n    // using A as base\n    GeneralMatrixVectorMultiply(matrix_A, 'N', test_vector1, 1.0, 0.0, kSize_m, kSize_n, kSize_m, product_vector1);\n    for (int i = 0; i < kSize_m; ++i) {\n      if (!CheckDoubleWithinRelative(product_vector1[i], result_vector1[i], std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    GeneralMatrixVectorMultiply(matrix_A, 'N', test_vector2, 1.0, 0.0, kSize_m, kSize_n, kSize_m, product_vector1);\n    for (int i = 0; i < kSize_m; ++i) {\n      if (!CheckDoubleWithinRelative(product_vector1[i], result_vector2[i], std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    GeneralMatrixVectorMultiply(matrix_A_T, 'N', test_vector3, 1.0, 0.0, kSize_n, kSize_m, kSize_n, product_vector2);\n    for (int i = 0; i < kSize_n; ++i) {\n      if (!CheckDoubleWithinRelative(product_vector2[i], result_vector3[i], 5*std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    GeneralMatrixVectorMultiply(matrix_A_T, 'N', test_vector4, 1.0, 0.0, kSize_n, kSize_m, kSize_n, product_vector2);\n    for (int i = 0; i < kSize_n; ++i) {\n      if (!CheckDoubleWithinRelative(product_vector2[i], result_vector4[i], 5*std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    // now with A^T as base\n    GeneralMatrixVectorMultiply(matrix_A_T, 'T', test_vector1, 1.0, 0.0, kSize_n, kSize_m, kSize_n, product_vector1);\n    for (int i = 0; i < kSize_m; ++i) {\n      if (!CheckDoubleWithinRelative(product_vector1[i], result_vector1[i], std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    GeneralMatrixVectorMultiply(matrix_A_T, 'T', test_vector2, 1.0, 0.0, kSize_n, kSize_m, kSize_n, product_vector1);\n    for (int i = 0; i < kSize_m; ++i) {\n      if (!CheckDoubleWithinRelative(product_vector1[i], result_vector2[i], std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    GeneralMatrixVectorMultiply(matrix_A, 'T', test_vector3, 1.0, 0.0, kSize_m, kSize_n, kSize_m, product_vector2);\n    for (int i = 0; i < kSize_n; ++i) {\n      if (!CheckDoubleWithinRelative(product_vector2[i], result_vector3[i], 5*std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    GeneralMatrixVectorMultiply(matrix_A, 'T', test_vector4, 1.0, 0.0, kSize_m, kSize_n, kSize_m, product_vector2);\n    for (int i = 0; i < kSize_n; ++i) {\n      if (!CheckDoubleWithinRelative(product_vector2[i], result_vector4[i], 5*std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n  }\n\n  const int num_tests = 3;\n  const int sizes[num_tests] = {5, 11, 20};\n\n  UniformRandomGenerator uniform_generator(34187);\n  // Here we check the performance of matrix-vector multiply using a very well-conditioned matrix\n  // with a very unique property.  F(x), the householder reflector for a vector x, has the following property:\n  // F * x = [||x||_2, zeros(n-1,1)]  (for an arbitrary vector, ||F*y|| = ||y|| always)\n  // Additionally, F is orthogonal so cond(F) = 1 and our results should be computable very accurately.\n  for (int i = 0; i < num_tests; ++i) {\n    std::vector<double> house_matrix(sizes[i]*sizes[i]);\n    std::vector<double> vector(sizes[i]);\n    std::vector<double> reflected_vector(sizes[i]);\n\n    BuildRandomVector(sizes[i], -1.0, 1.0, &uniform_generator, vector.data());\n    BuildHouseholderReflectorMatrix(vector.data(), sizes[i], house_matrix.data());\n    GeneralMatrixVectorMultiply(house_matrix.data(), 'N', vector.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], reflected_vector.data());\n\n    double vector_norm = VectorNorm(vector.data(), sizes[i]);\n\n    if (!CheckDoubleWithinRelative(std::fabs(reflected_vector[0]), vector_norm, 5*std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n    for (int j = 1; j < sizes[i]; ++j) {\n      if (!CheckDoubleWithin(reflected_vector[j], 0.0, 5*std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    // reflector is symmetric, so test T version too\n    GeneralMatrixVectorMultiply(house_matrix.data(), 'T', vector.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], reflected_vector.data());\n\n    vector_norm = VectorNorm(vector.data(), sizes[i]);\n\n    if (!CheckDoubleWithinRelative(std::fabs(reflected_vector[0]), vector_norm, 5*std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n    for (int j = 1; j < sizes[i]; ++j) {\n      if (!CheckDoubleWithin(reflected_vector[j], 0.0, 5*std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n  }\n\n  return total_errors;\n}\n\n/*!\\rst\n  Check that ``A * B`` works where ``A, B`` are matrices.\n  Outline:\n\n  1. Simple hand-checked test case.\n  2. Generate a random orthogonal matrix and verify that ``Q * Q^T = I``.\n  3. Generate a random SPD matrix and guarantee good conditioning: verify ``A * A^-1 = I``.\n\n  \\return\n    number of cases where matrix-matrix multiply failed\n\\endrst*/\nOL_WARN_UNUSED_RESULT int TestGeneralMatrixMatrixMultiply() noexcept {\n  int total_errors = 0;\n\n  // simple, hand-checked problems that are be minimally affected by floating point errors\n  {  // hide scope\n    static const int kSize_m = 3;  // rows of A, C\n    static const int kSize_k = 5;  // cols of A, rows of B\n    static const int kSize_n = 2;  // cols of B, C\n\n    double matrix_A[kSize_m*kSize_k] =\n        {-7.4, 0.1, 9.1,  // first COLUMN of A (col-major storage)\n         1.5, -8.8, -0.3,\n         -2.9, 6.4, -9.7,\n         -9.1, -6.6, 3.1,\n         4.6, 3.0, -1.0\n        };\n\n    double matrix_B[kSize_k*kSize_n] =\n        {-1.3, -8.1, -7.2, -0.4, -5.5,\n         7.4, 5.3, -3.1, -2.3, 1.9\n        };\n\n    double matrix_AB_exact[kSize_m*kSize_n] =\n        {-3.309999999999995, 11.210000000000001, 64.700000000000003,\n         -8.150000000000006, -44.860000000000014, 86.789999999999992\n        };\n    double matrix_AB_computed[kSize_m*kSize_n];\n\n    GeneralMatrixMatrixMultiply(matrix_A, 'N', matrix_B, 1.0, 0.0, kSize_m, kSize_k, kSize_n, matrix_AB_computed);\n\n    for (int i = 0; i < kSize_m*kSize_n; ++i) {\n      if (!CheckDoubleWithinRelative(matrix_AB_computed[i], matrix_AB_exact[i], 3.0 * std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n  }\n\n  const int num_tests = 3;\n  const int sizes[num_tests] = {3, 11, 20};\n\n  UniformRandomGenerator uniform_generator(34187);\n  // in each iteration, we perform two tests on matrix-matrix multiply.\n  //   1) form a matrix Q such that Q * Q^T = I (orthogonal matrix); nontrivial in that Q != I\n  //      Compute Q * Q^T and check the result.\n  //   2) build a random, SPD matrix, A. (ill-conditioned).\n  //      Improve A's conditioning: A = A + size*I (condition number near 1 now)\n  //      Form A^-1 (this is OK because A is well-conditioned)\n  //      Check A * A^-1 is near I.\n  for (int i = 0; i < num_tests; ++i) {\n    std::vector<double> orthog_symm_matrix(sizes[i]*sizes[i]);\n    std::vector<double> orthog_symm_matrix_T(sizes[i]*sizes[i]);\n    std::vector<double> product_matrix(sizes[i]*sizes[i]);\n    std::vector<double> spd_matrix(sizes[i]*sizes[i]);\n    std::vector<double> cholesky_factor(sizes[i]*sizes[i]);\n    std::vector<double> inverse_spd_matrix(sizes[i]*sizes[i]);\n    std::vector<double> identity_matrix(sizes[i]*sizes[i]);\n\n    BuildIdentityMatrix(sizes[i], identity_matrix.data());\n\n    BuildOrthogonalSymmetricMatrix(sizes[i], orthog_symm_matrix.data());\n    // not technically necessary since this orthog matrix is also symmetric\n    MatrixTranspose(orthog_symm_matrix.data(), sizes[i], sizes[i], orthog_symm_matrix_T.data());\n\n    // Q * Q^T = I if Q is orthogonal\n    GeneralMatrixMatrixMultiply(orthog_symm_matrix.data(), 'N', orthog_symm_matrix_T.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], product_matrix.data());\n    VectorAXPY(sizes[i]*sizes[i], -1.0, identity_matrix.data(), product_matrix.data());\n    for (int j = 0; j < sizes[i]*sizes[i]; ++j) {\n      // do not use relative comparison b/c we're testing against 0\n      if (!CheckDoubleWithin(product_matrix[j], 0.0, 20*std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    // and again testing the T version\n    GeneralMatrixMatrixMultiply(orthog_symm_matrix.data(), 'T', orthog_symm_matrix.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], product_matrix.data());\n    VectorAXPY(sizes[i]*sizes[i], -1.0, identity_matrix.data(), product_matrix.data());\n    for (int j = 0; j < sizes[i]*sizes[i]; ++j) {\n      // do not use relative comparison b/c we're testing against 0\n      if (!CheckDoubleWithin(product_matrix[j], 0.0, 20*std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    BuildRandomSPDMatrix(sizes[i], &uniform_generator, spd_matrix.data());\n    // ensure spd matrix is well-conditioned (or we can't form A^-1 stably)\n    ModifyMatrixDiagonal(sizes[i], static_cast<double>(sizes[i]), spd_matrix.data());\n\n    std::copy(spd_matrix.begin(), spd_matrix.end(), cholesky_factor.begin());\n    if (ComputeCholeskyFactorL(sizes[i], cholesky_factor.data()) != 0) {\n      ++total_errors;\n    }\n    SPDMatrixInverse(cholesky_factor.data(), sizes[i], inverse_spd_matrix.data());\n    GeneralMatrixMatrixMultiply(spd_matrix.data(), 'N', inverse_spd_matrix.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], product_matrix.data());\n    VectorAXPY(sizes[i]*sizes[i], -1.0, identity_matrix.data(), product_matrix.data());\n    for (int j = 0; j < sizes[i]*sizes[i]; ++j) {\n      // do not use relative comparison b/c we're testing against 0\n      if (!CheckDoubleWithin(product_matrix[j], 0.0, 10*std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n  }\n\n  return total_errors;\n}\n\n/*!\\rst\n  Check that ``Ax`` works for the special cases of ``A`` being:\n\n  1. triangular\n  2. symmetric\n\n  Assuming that dgemv() is correct, we then check (using random matrices):\n\n  1. Assert that dtrmv (triangular) matches dgemv for the appropriate matrices.\n  2. Assert that dsymv (symmetric) match dgemv for the appropriate matrices.\n\n  \\return\n    number of cases where matrix-vector multiply does not match triangular or symmetric specialized multiplies.\n\\endrst*/\nOL_WARN_UNUSED_RESULT int TestSpecialMatrixVectorMultiply() {\n  int total_errors_dsymv = 0;\n  int total_errors_dtrmv = 0;\n  int total_errors_dtrmv_T = 0;\n  const int num_tests = 3;\n  const int sizes[num_tests] = {3, 11, 20};\n\n  UniformRandomGenerator uniform_generator(34187);\n  for (int i = 0; i < num_tests; ++i) {\n    std::vector<double> matrix(sizes[i]*sizes[i]);\n    std::vector<double> lower_triangular_part_matrix(sizes[i]*sizes[i]);\n    std::vector<double> upper_triangular_part_matrix(sizes[i]*sizes[i]);\n    std::vector<double> multiplicand_vector(sizes[i]);\n    std::vector<double> product_by_dgemv(sizes[i]);\n    std::vector<double> product_by_dsymv(sizes[i]);\n    std::vector<double> product_by_dtrmv(sizes[i]);\n\n    BuildRandomSymmetricMatrix(sizes[i], -1.0, 1.0, &uniform_generator, matrix.data());\n    ExtractLowerTriangularPart(matrix.data(), sizes[i], lower_triangular_part_matrix.data());\n    BuildRandomVector(sizes[i], -2.0, 2.0, &uniform_generator, multiplicand_vector.data());\n\n    // testing dsymv\n    // generate truth value\n    GeneralMatrixVectorMultiply(matrix.data(), 'N', multiplicand_vector.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], product_by_dgemv.data());\n\n    // generate test value\n    // note: dsymv does not access the upper triangular part, so we will check this\n    // by giving it a matrix where that region is all 0s\n    SymmetricMatrixVectorMultiply(lower_triangular_part_matrix.data(), multiplicand_vector.data(), sizes[i], product_by_dsymv.data());\n\n    for (int j = 0; j < sizes[i]; ++j) {\n      if (!CheckDoubleWithinRelative(product_by_dsymv[j], product_by_dgemv[j], 1000*std::numeric_limits<double>::epsilon())) {\n        ++total_errors_dsymv;\n      }\n    }\n\n    // testing dtrmv, no transpose\n    // generate truth value\n    GeneralMatrixVectorMultiply(lower_triangular_part_matrix.data(), 'N', multiplicand_vector.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], product_by_dgemv.data());\n\n    // generate test value\n    // note: dsymv does not access the upper triangular part, so we will check this\n    // by giving it a matrix where that region is populated\n    std::copy(multiplicand_vector.begin(), multiplicand_vector.end(), product_by_dtrmv.begin());\n    TriangularMatrixVectorMultiply(matrix.data(), 'N', sizes[i], product_by_dtrmv.data());\n\n    for (int j = 0; j < sizes[i]; ++j) {\n      if (!CheckDoubleWithinRelative(product_by_dtrmv[j], product_by_dgemv[j], 1000*std::numeric_limits<double>::epsilon())) {\n        ++total_errors_dtrmv;\n      }\n    }\n\n    // testing dtrmv, transpose\n    // generate truth value\n    GeneralMatrixVectorMultiply(lower_triangular_part_matrix.data(), 'T', multiplicand_vector.data(), 1.0, 0.0, sizes[i], sizes[i], sizes[i], product_by_dgemv.data());\n\n    // generate test value\n    // note: dsymv does not access the upper triangular part, so we will check this\n    // by giving it a matrix where that region is populated\n    std::copy(multiplicand_vector.begin(), multiplicand_vector.end(), product_by_dtrmv.begin());\n    TriangularMatrixVectorMultiply(matrix.data(), 'T', sizes[i], product_by_dtrmv.data());\n\n    for (int j = 0; j < sizes[i]; ++j) {\n      if (!CheckDoubleWithinRelative(product_by_dtrmv[j], product_by_dgemv[j], 1000*std::numeric_limits<double>::epsilon())) {\n        ++total_errors_dtrmv_T;\n      }\n    }\n  }\n\n  if (total_errors_dsymv != 0) {\n    OL_ERROR_PRINTF(\"dsymv failed\\n\");\n  }\n  if (total_errors_dtrmv != 0) {\n    OL_ERROR_PRINTF(\"dtrmv failed\\n\");\n  }\n  if (total_errors_dtrmv_T != 0) {\n    OL_ERROR_PRINTF(\"dtrmv_T failed\\n\");\n  }\n\n  return total_errors_dsymv + total_errors_dtrmv + total_errors_dtrmv_T;\n}\n\n/*!\\rst\n  Check that matrix-transpose works.\n\n  \\return\n    number of entries where ``A`` and ``A^T`` do not match\n\\endrst*/\nOL_WARN_UNUSED_RESULT int TestMatrixTranspose() noexcept {\n  const int size_m = 3;\n  const int size_n = 5;\n  int total_errors = 0;\n\n  std::vector<double> matrix(size_m*size_n);\n  std::vector<double> matrix_T(size_m*size_n);\n  std::vector<double> product_matrix(size_n*size_n);\n  UniformRandomGenerator uniform_generator(34187);\n\n  BuildRandomVector(size_m*size_n, -1.0, 1.0, &uniform_generator, matrix.data());\n  MatrixTranspose(matrix.data(), size_m, size_n, matrix_T.data());\n\n  for (int j = 0; j < size_n; ++j) {\n    for (int i = 0; i < size_m; ++i) {\n      if (CheckDoubleWithin(matrix[j*size_m + i], matrix_T[i*size_n + j], 0.0) == false) {\n        ++total_errors;\n        break;\n      }\n    }\n  }\n\n  return total_errors;\n}\n\n/*!\\rst\n  Check that ``A = PLU`` factorization works.\n\n  Test is conducted using a case from Trefethen's \"Numerical Linear Algebra\", 1997.\n\n  \\return\n    number of cases where PLU fails.\n\\endrst*/\nOL_WARN_UNUSED_RESULT int TestPLUFactor() noexcept {\n  const int size = 4;\n  int total_errors;\n  int pivot[size] = {0};\n  const int truth_pivot[size] = {1, 2, 3, 4};\n  double matrix[Square(size)] = {2.0, 1.0, 1.0, 0.0, 4.0, 3.0, 3.0, 1.0, 8.0, 7.0, 9.0, 5.0, 6.0, 7.0, 9.0, 8.0};\n  const double truth_matrix[Square(size)] = {2.0, 0.5, 0.5, 0.0, 4.0, 1.0, 1.0, 1.0, 8.0, 3.0, 2.0, 1.0, 6.0, 4.0, 2.0, 2.0};\n\n  total_errors = ComputePLUFactorization(size, pivot, matrix);\n  for (int i = 0; i < size; ++i) {\n    if (!CheckIntEquals(pivot[i], truth_pivot[i])) {\n      ++total_errors;\n    }\n  }\n\n  for (int i = 0; i < Square(size); ++i) {\n    if (!CheckDoubleWithinRelative(matrix[i], truth_matrix[i], std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n  }\n  return total_errors;\n}\n\n/*!\\rst\n  Check that solving ``Ax = b`` works when using PLU factorization + backsolves.\n\n  Test is conducted using a case from Trefethen's \"Numerical Linear Algebra\", 1997.\n\n  \\return\n    number of cases where PLU fails.\n\\endrst*/\nOL_WARN_UNUSED_RESULT int TestPLUSolve() noexcept {\n  const int size = 4;\n  int total_errors;\n  int pivot[size] = {0};\n  double matrix[Square(size)] = {2.0, 1.0, 1.0, 0.0, 4.0, 3.0, 3.0, 1.0, 8.0, 7.0, 9.0, 5.0, 6.0, 7.0, 9.0, 8.0};\n  double rhs1[size] = {58.0, 56.0, 70.0, 49.0};\n  const double truth_rhs1[size] = {1.0, 2.0, 3.0, 4.0};\n  double rhs2[size] = {64.0, 71.0, 91.0, 73.0};\n  const double truth_rhs2[size] = {-5.0, 2.0, 3.0, 7.0};\n  double rhs3[size] = {-20.0, -16.0, -20.0, -6.0};\n  const double truth_rhs3[size] = {4.0, -2.0, -4.0, 2.0};\n\n  total_errors = ComputePLUFactorization(size, pivot, matrix);\n  PLUMatrixVectorSolve(size, matrix, pivot, rhs1);\n  PLUMatrixVectorSolve(size, matrix, pivot, rhs2);\n  PLUMatrixVectorSolve(size, matrix, pivot, rhs3);\n\n  for (int i = 0; i < size; ++i) {\n    if (!CheckDoubleWithinRelative(rhs1[i], truth_rhs1[i], std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n    if (!CheckDoubleWithinRelative(rhs2[i], truth_rhs2[i], std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n    if (!CheckDoubleWithinRelative(rhs3[i], truth_rhs3[i], std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n  }\n\n  return total_errors;\n}\n\n/*!\\rst\n  Test vector norm.\n\n  For several problem sizes, check:\n\n  1. zeros have ``norm = 0``\n  2. ``\\|\\alpha\\| = \\alpha`` where \\alpha is scalar\n  3. Scaling a vector by its own norm results in a vector with ``norm = 1.0``.\n  4. Columns of a matrix whose columns are *known* to have unit-norm.\n\n  \\return\n    number of cases where the norm is wrong\n\\endrst*/\nOL_WARN_UNUSED_RESULT int TestNorm() noexcept {\n  int total_errors = 0;\n  const int num_sizes = 3;\n  const int sizes[num_sizes] = {11, 100, 1007};\n  UniformRandomGenerator uniform_generator(34187);\n\n  for (int i = 0; i < num_sizes; ++i) {\n    std::vector<double> vector(sizes[i], 0.0);\n    // zero vector has zero norm\n    double norm = VectorNorm(vector.data(), vector.size());\n    if (!CheckDoubleWithin(norm, 0.0, 0.0)) {\n      ++total_errors;\n    }\n\n    BuildRandomVector(sizes[i], -1.0, 1.0, &uniform_generator, vector.data());\n\n    // norm of nothing element is 0\n    norm = VectorNorm(vector.data(), 0);\n    if (!CheckDoubleWithin(norm, 0.0, 0.0)) {\n      ++total_errors;\n    }\n\n    // norm of 1 element is |that element|\n    norm = VectorNorm(vector.data(), 1);\n    if (!CheckDoubleWithinRelative(norm, std::fabs(vector[0]), std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n\n    // unit vectors have unit norm\n    norm = VectorNorm(vector.data(), vector.size());\n    std::vector<double> unit_vector(vector);\n    VectorScale(unit_vector.size(), 1.0/norm, unit_vector.data());\n    double unit_norm = VectorNorm(unit_vector.data(), unit_vector.size());\n    if (!CheckDoubleWithinRelative(unit_norm, 1.0, std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n\n    if (i < num_sizes - 1) {  // don't do the largest case\n      std::vector<double> orthogonal_matrix(Square(sizes[i]));\n      BuildOrthogonalSymmetricMatrix(sizes[i], orthogonal_matrix.data());\n      for (int j = 0; j < sizes[i]; ++j) {\n        double column_norm = VectorNorm(orthogonal_matrix.data() + j*sizes[i], sizes[i]);\n        if (!CheckDoubleWithinRelative(column_norm, 1.0, std::sqrt(static_cast<double>(sizes[i]))*std::numeric_limits<double>::epsilon())) {\n          ++total_errors;\n        }\n      }\n    }\n  }\n\n  return total_errors;\n}\n\n/*!\\rst\n  Test several vector (BLAS-1) functions:\n\n  1. scale: ``y = \\alpha * y``\n  2. AXPY: ``y = \\alpha * x + y``\n  3. dot product: ``c = x^T * y``, ``c`` is scalar\n  4. norm: ``\\|x\\|``\n\\endrst*/\nOL_WARN_UNUSED_RESULT int TestVectorFunctions() noexcept {\n  int total_errors = 0;\n  const int size = 4;\n  const double orig_input[size] = {1.5, 2.0, 0.0, -3.2};\n  double input[size] = {0};\n  const double positive_scale = 2.0;\n  const double negative_scale = -3.0;\n  const double zero_scale = 0.0;\n\n  // test VectorScale\n  {\n    const double result_positive_scale[size] = {3.0, 4.0, 0.0, -6.4};\n    const double result_negative_scale[size] = {-4.5, -6.0, 0.0, 9.6};\n    const double result_zero_scale[size] = {0.0, 0.0, 0.0, 0.0};\n\n    std::copy(orig_input, orig_input + size, input);\n    VectorScale(size, positive_scale, input);\n    for (int i = 0; i < size; ++i) {\n      if (!CheckDoubleWithinRelative(input[i], result_positive_scale[i], std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    std::copy(orig_input, orig_input + size, input);\n    VectorScale(size, negative_scale, input);\n    for (int i = 0; i < size; ++i) {\n      if (!CheckDoubleWithinRelative(input[i], result_negative_scale[i], std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    std::copy(orig_input, orig_input + size, input);\n    VectorScale(size, zero_scale, input);\n    for (int i = 0; i < size; ++i) {\n      if (!CheckDoubleWithinRelative(input[i], result_zero_scale[i], std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n  }\n\n  // test VectorAXPY\n  {\n    const double vector_x[size] = {0.0, 0.5, -1.3, 3.0};\n    const double result_positive_scale[size] = {1.5, 3.0, -2.6, 2.8};\n    const double result_negative_scale[size] = {1.5, 0.5, 3.9, -12.2};\n    const double result_zero_scale[size] = {1.5, 2.0, 0.0, -3.2};\n\n    std::copy(orig_input, orig_input + size, input);\n    VectorAXPY(size, positive_scale, vector_x, input);\n    for (int i = 0; i < size; ++i) {\n      if (!CheckDoubleWithinRelative(input[i], result_positive_scale[i], std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    std::copy(orig_input, orig_input + size, input);\n    VectorAXPY(size, negative_scale, vector_x, input);\n    for (int i = 0; i < size; ++i) {\n      if (!CheckDoubleWithinRelative(input[i], result_negative_scale[i], std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n\n    std::copy(orig_input, orig_input + size, input);\n    VectorAXPY(size, zero_scale, vector_x, input);\n    for (int i = 0; i < size; ++i) {\n      if (!CheckDoubleWithinRelative(input[i], result_zero_scale[i], std::numeric_limits<double>::epsilon())) {\n        ++total_errors;\n      }\n    }\n  }\n\n  // test dot product\n  {\n    const double input2[size] = {0.0};\n    const double input3[size] = {0.0, 0.5, -1.3, 3.0};\n    double output;\n    const double result2 = 0.0;\n    const double result3 = 2.0*0.5 - 3.2*3.0;\n    output = DotProduct(orig_input, input2, size);\n    if (!CheckDoubleWithinRelative(output, result2, std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n    output = DotProduct(orig_input, input3, size);\n    if (!CheckDoubleWithinRelative(output, result3, std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n    // check symmetry\n    output = DotProduct(input3, orig_input, size);\n    if (!CheckDoubleWithinRelative(output, result3, std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n  }\n\n  // test norm\n  {\n    const double truth_norm_input = 4.060788100849391;\n    double norm = VectorNorm(orig_input, size);\n    if (!CheckDoubleWithinRelative(norm, truth_norm_input, std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n\n    std::copy(orig_input, orig_input + size, input);\n    VectorScale(size, positive_scale, input);\n    norm = VectorNorm(input, size);\n    if (!CheckDoubleWithinRelative(norm, positive_scale*truth_norm_input, std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n\n    std::copy(orig_input, orig_input + size, input);\n    VectorScale(size, negative_scale, input);\n    norm = VectorNorm(input, size);\n    if (!CheckDoubleWithinRelative(norm, -negative_scale*truth_norm_input, std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n\n    std::copy(orig_input, orig_input + size, input);\n    VectorScale(size, zero_scale, input);\n    norm = VectorNorm(input, size);\n    if (!CheckDoubleWithin(norm, 0.0, 0.0)) {\n      ++total_errors;\n    }\n\n    total_errors += TestNorm();\n  }\n  return total_errors;\n}\n\n/*!\\rst\n  Test that outerproduct is working with some small hand-checked cases.\n\n  \\return\n    number of entries where the outerproduct is invalid\n\\endrst*/\nOL_WARN_UNUSED_RESULT int TestOuterProduct() noexcept {\n  int total_errors = 0;\n  const int size_m = 2;\n  const int size_n = 3;\n  const double vector_v[size_m] = {1.2, -2.1};\n  const double vector_u[size_n] = {-2.7, 0.0, 3.3};\n  double positive_scale = 1.0;\n  double zero_scale = 0.0;\n  const double outer_prod[size_m*size_n] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0};\n  double input[size_m*size_n] = {0.0};\n  const double result_positive_scale[size_m*size_n] = {0.0 + (-2.7*1.2), 1.0 + (-2.7*-2.1), 2.0, 3.0, 4.0 + (3.3*1.2), 5.0 + (3.3*-2.1)};\n\n  std::copy(outer_prod, outer_prod + size_m*size_n, input);\n  OuterProduct(size_m, size_n, positive_scale, vector_v, vector_u, input);\n  for (int i = 0; i < size_m*size_n; ++i) {\n    if (!CheckDoubleWithinRelative(input[i], result_positive_scale[i], std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n  }\n\n  std::copy(outer_prod, outer_prod + size_m*size_n, input);\n  OuterProduct(size_m, size_n, zero_scale, vector_v, vector_u, input);\n  for (int i = 0; i < size_m*size_n; ++i) {\n    if (!CheckDoubleWithinRelative(input[i], outer_prod[i], std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n  }\n\n  return total_errors;\n}\n\n/*!\\rst\n  Test matrix trace and ``tr(AB)``.\n\n  \\return\n    number of cases where trace functions fail\n\\endrst*/\nOL_WARN_UNUSED_RESULT int TestMatrixTrace() noexcept {\n  int total_errors = 0;\n\n  UniformRandomGenerator uniform_generator(34187);\n\n  // test MatrixTrace\n  {\n    const int size = 4;\n    double matrix[Square(size)];\n    BuildRandomVector(Square(size), -1.0, 1.0, &uniform_generator, matrix);\n    // replace diagonal with known values\n    matrix[0*4 + 0] = 1.5;\n    matrix[1*4 + 1] = -2.3;\n    matrix[2*4 + 2] = 0.0;\n    matrix[3*4 + 3] = 3.1;\n    const double result = 1.5 - 2.3 + 0.0 + 3.1;\n    double output = MatrixTrace(matrix, size);\n    if (!CheckDoubleWithinRelative(output, result, std::numeric_limits<double>::epsilon())) {\n      ++total_errors;\n    }\n  }\n\n  // test TraceOfGeneralMatrixMatrixMultiply\n  // test by forming random matrices, evaluating the matrix product, and comparing traces of\n  // the explicit and shortcut solutions\n  {\n    double trace_by_explicit_product;\n    double trace_by_shortcut;\n    // loop over several sizes to make sure we hit all loop unroll paths\n    for (int i = 10; i < 15; ++i) {\n      std::vector<double> matrix_A(i*i);\n      std::vector<double> matrix_B(i*i);\n      std::vector<double> matrix_C(i*i);\n\n      BuildRandomVector(Square(i), -1.0, 1.0, &uniform_generator, matrix_A.data());\n      BuildRandomVector(Square(i), -1.0, 1.0, &uniform_generator, matrix_B.data());\n      GeneralMatrixMatrixMultiply(matrix_A.data(), 'N', matrix_B.data(), 1.0, 0.0, i, i, i, matrix_C.data());\n      trace_by_explicit_product = MatrixTrace(matrix_C.data(), i);\n      trace_by_shortcut = TraceOfGeneralMatrixMatrixMultiply(matrix_A.data(), matrix_B.data(), i);\n\n      if (!CheckDoubleWithinRelative(trace_by_shortcut, trace_by_explicit_product, 2.0e-14)) {\n        ++total_errors;\n      }\n    }\n  }\n  return total_errors;\n}\n\n}  // end unnamed namespace\n\nint RunLinearAlgebraTests() {\n  int current_errors = 0;\n  int total_errors = 0;\n\n  OL_VERBOSE_PRINTF(\"\\nLinear Algebra Unit Tests\\n\\n\");\n\n  current_errors = TestVectorFunctions();\n  total_errors += current_errors;\n  if (current_errors != 0) {\n    OL_PARTIAL_FAILURE_PRINTF(\"vector function errors = %d\\n\", current_errors);\n  }\n\n  current_errors = TestOuterProduct();\n  total_errors += current_errors;\n  if (current_errors != 0) {\n    OL_PARTIAL_FAILURE_PRINTF(\"outer product errors = %d\\n\", current_errors);\n  }\n\n  current_errors = TestMatrixTrace();\n  total_errors += current_errors;\n  if (current_errors != 0) {\n    OL_PARTIAL_FAILURE_PRINTF(\"matrix trace errors = %d\\n\", current_errors);\n  }\n\n  current_errors = TestCholesky();\n  total_errors += current_errors;\n  if (current_errors != 0) {\n    OL_PARTIAL_FAILURE_PRINTF(\"cholesky errors = %d\\n\", current_errors);\n  }\n\n  current_errors = TestSPDLinearSolvers();\n  total_errors += current_errors;\n  if (current_errors != 0) {\n    OL_PARTIAL_FAILURE_PRINTF(\"linear solve errors = %d\\n\", current_errors);\n  }\n\n  current_errors = TestGeneralMatrixVectorMultiply();\n  total_errors += current_errors;\n  if (current_errors != 0) {\n    OL_PARTIAL_FAILURE_PRINTF(\"dgemv errors = %d\\n\", current_errors);\n  }\n\n  current_errors = TestGeneralMatrixMatrixMultiply();\n  total_errors += current_errors;\n  if (current_errors != 0) {\n    OL_PARTIAL_FAILURE_PRINTF(\"dgemm errors = %d\\n\", current_errors);\n  }\n\n  current_errors = TestSpecialMatrixVectorMultiply();\n  total_errors += current_errors;\n  if (current_errors != 0) {\n    OL_PARTIAL_FAILURE_PRINTF(\"dsymv, dtrmv errors = %d\\n\", current_errors);\n  }\n\n  current_errors = TestMatrixTranspose();\n  total_errors += current_errors;\n  if (current_errors != 0) {\n    OL_PARTIAL_FAILURE_PRINTF(\"MatrixTranspose errors = %d\\n\", current_errors);\n  }\n\n  current_errors = TestPLUFactor();\n  total_errors += current_errors;\n  if (current_errors != 0) {\n    OL_PARTIAL_FAILURE_PRINTF(\"PLU Factorization errors = %d\\n\", current_errors);\n  }\n\n  current_errors = TestPLUSolve();\n  total_errors += current_errors;\n  if (current_errors != 0) {\n    OL_PARTIAL_FAILURE_PRINTF(\"PLU Solve errors = %d\\n\", current_errors);\n  }\n\n  return total_errors;\n}\n\n}  // end namespace optimal_learning\n", "meta": {"hexsha": "813b811e57eefab0c0872dbe7652b40f0e906817", "size": 51047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moe/optimal_learning/cpp/gpp_linear_algebra_test.cpp", "max_stars_repo_name": "dstoeckel/MOE", "max_stars_repo_head_hexsha": "5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 966.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T05:27:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T21:04:36.000Z", "max_issues_repo_path": "moe/optimal_learning/cpp/gpp_linear_algebra_test.cpp", "max_issues_repo_name": "dstoeckel/MOE", "max_issues_repo_head_hexsha": "5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2015-01-16T22:33:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:33:27.000Z", "max_forks_repo_path": "moe/optimal_learning/cpp/gpp_linear_algebra_test.cpp", "max_forks_repo_name": "dstoeckel/MOE", "max_forks_repo_head_hexsha": "5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 143.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T03:57:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T01:10:45.000Z", "avg_line_length": 38.4390060241, "max_line_length": 171, "alphanum_fraction": 0.6562579584, "num_tokens": 15072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.5829074448847492}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdLmgamma, Fvar) {\n  using stan::math::fvar;\n  using stan::math::lmgamma;\n\n  int x = 3;\n  fvar<double> y(3.2, 2.1);\n\n  fvar<double> a = lmgamma(x, y);\n  EXPECT_FLOAT_EQ(lmgamma(3, 3.2), a.val_);\n  EXPECT_FLOAT_EQ(4.9138227, a.d_);\n}\n\nTEST(AgradFwdLmgamma, FvarFvarDouble) {\n  using stan::math::fvar;\n  using stan::math::lmgamma;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 3.2;\n  x.val_.d_ = 2.1;\n\n  fvar<fvar<double> > a = lmgamma(3, x);\n\n  EXPECT_FLOAT_EQ(lmgamma(3, 3.2), a.val_.val_);\n  EXPECT_FLOAT_EQ(4.9138227, a.val_.d_);\n  EXPECT_FLOAT_EQ(0, a.d_.val_);\n  EXPECT_FLOAT_EQ(0, a.d_.d_);\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 3.2;\n  y.d_.val_ = 2.1;\n\n  a = lmgamma(3, y);\n  EXPECT_FLOAT_EQ(lmgamma(3, 3.2), a.val_.val_);\n  EXPECT_FLOAT_EQ(0, a.val_.d_);\n  EXPECT_FLOAT_EQ(4.9138227, a.d_.val_);\n  EXPECT_FLOAT_EQ(0, a.d_.d_);\n}\n\nstruct lmgamma_fun {\n  template <typename T0>\n  inline T0 operator()(const T0& arg1) const {\n    return lmgamma(3, arg1);\n  }\n};\n\nTEST(AgradFwdLmgamma, lmgamma_NaN_0) {\n  lmgamma_fun lmgamma_;\n  test_nan_fwd(lmgamma_, false);\n}\n", "meta": {"hexsha": "565914e4258e6af869c301d05585bb1fd2640899", "size": 1233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/fwd/scal/fun/lmgamma_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/fwd/scal/fun/lmgamma_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/fwd/scal/fun/lmgamma_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4181818182, "max_line_length": 54, "alphanum_fraction": 0.6715328467, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920211198871, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5828841382356046}}
{"text": "//\n//  minhash.cpp\n//  \n//\n//  Created by Roberto Perdisci on 1/7/17.\n//  Copyright \u00a9 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// Copyright 2020 Debabrata Mandal <mandaldebabrata123@gmail.com>\n// \n// Distributed under the Boost Software License, Version 1.0 \n// See accompanying file LICENSE_1_0.txt or copy at \n// http://www.boost.org/LICENSE_1_0.txt \n// \n\n#include <boost/gil.hpp>\n#include <boost/gil/extension/io/png.hpp>\n#include <boost/gil/image_processing/histogram_equalization.hpp>\n\nusing namespace boost::gil;\n\n// Demonstrates Histogram Equalization\n\n// See also:\n// histogram.cpp - General use of histograms in GIL\n// adaptive_he.cpp - Adaptive Histogram Equalization\n// histogram_matching.cpp - Reference-based histogram computation\n\nint main()\n{\n    gray8_image_t img;\n    \n    read_image(\"test_adaptive.png\", img, png_tag{});\n    gray8_image_t img_out(img.dimensions());\n\n    // Consider changing image to independent color space, e.g. cmyk\n    boost::gil::histogram_equalization(view(img),view(img_out));\n\n    write_view(\"histogram_gray_equalized.png\", view(img_out), png_tag{});\n\n    return 0;\n}\n", "meta": {"hexsha": "ae2ffd63298d8dd748840f94cd3e548bb1e771dc", "size": 988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/histogram_equalization.cpp", "max_stars_repo_name": "DhruvaG2000/gil", "max_stars_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/histogram_equalization.cpp", "max_issues_repo_name": "DhruvaG2000/gil", "max_issues_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/histogram_equalization.cpp", "max_forks_repo_name": "DhruvaG2000/gil", "max_forks_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4444444444, "max_line_length": 73, "alphanum_fraction": 0.737854251, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959545, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.5828841196612283}}
{"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": "//==================================================================================================\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_TRUNC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TRUNC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing trunc capabilities\n\n    Computes the truncation toward @ref Zero of its parameter.\n\n    @par semantic:\n    For any given value @c x of type @c T:\n\n    @code\n    T r = trunc(x);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    T r = sign(x)*floor(abs(x));\n    @endcode\n\n    @par Note:\n\n      - For floating point number it is also one of the two ouputs of\n        the @ref modf function.\n        And we have:\n        @code\n        trunc(x) + frac(x) == x;\n        @endcode\n        except for nans\n\n      - If large numbers correct behaviour is not needed the fast_ decorator can be used,\n        but 'fast_' means that no provisions are taken for floating values  too large to fit\n         in the same size integer type.\n\n    @par Alias:\n    fix\n\n    @par Decorators\n\n    std_, fast_ for floating entries\n\n    @see abs, frac, floor, sign, modf\n\n  **/\n  const boost::dispatch::functor<tag::trunc_> trunc = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/trunc.hpp>\n#include <boost/simd/function/simd/trunc.hpp>\n\n#endif\n", "meta": {"hexsha": "026465983f2f2b103611e8de4011dc68244f1f88", "size": 1680, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/trunc.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/trunc.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/trunc.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.661971831, "max_line_length": 100, "alphanum_fraction": 0.5863095238, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5828841127367499}}
{"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": "\ufeff#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": "#ifndef Eigen_Dense_Solver_hh\n#define Eigen_Dense_Solver_hh\n\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"Dense_Solver.hh\"\n\ntemplate<class Scalar>\nclass Eigen_Dense_Solver : public Dense_Solver<Scalar>\n{\npublic:\n    \n    // Matrices and vectors\n    typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> EMatrix;\n    typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> EMatrixR;\n    typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> EVector;\n    \n    // Mapped types\n    typedef Eigen::Map<EVector> EMVector;\n    typedef Eigen::Map<EMatrix> EMMatrix;\n    typedef Eigen::Map<EMatrixR> EMMatrixR;\n\n    // LU decomposition\n    typedef Eigen::FullPivLU<EMatrixR> ELU;\n\n    // Constructor\n    Eigen_Dense_Solver(int size):\n        initialized_(false),\n        size_(size)\n    {\n    }\n\n    // Rank of matrix\n    virtual int size() const override\n    {\n        return size_;\n    }\n    \n    // Check whether data has been initialized\n    virtual bool initialized() const override\n    {\n        return initialized_;\n    }\n    \n    // Set matrix and perform decomposition\n    virtual void initialize(std::vector<Scalar> &a_data) override\n    {\n        Check(a_data.size() == size_ * size_);\n        \n        a_ = EMMatrixR(&a_data[0], size_, size_);\n        lu_ = a_.fullPivLu();\n        initialized_ = true;\n    }\n    \n    // Solve problem Ax=b using temporary data (no initialization needed)\n    virtual void solve(std::vector<Scalar> &a_data,\n                       std::vector<Scalar> &b_data,\n                       std::vector<Scalar> &x_data) override\n    {\n        Check(a_data.size() == size_ * size_);\n        Check(b_data.size() == size_);\n        Check(x_data.size() == size_);\n        \n        EMMatrixR a(&a_data[0], size_, size_);\n        EMVector b(&b_data[0], size_);\n        EMVector x(&x_data[0], size_);\n        \n        x = a.fullPivLu().solve(b);\n    }\n    \n    // Apply to one vector\n    virtual void solve(std::vector<double> &b_data,\n                       std::vector<double> &x_data) override\n    {\n        Assert(initialized_);\n        Check(b_data.size() == size_);\n        Check(x_data.size() == size_);\n        \n        EMVector b(&b_data[0], size_);\n        EMVector x(&x_data[0], size_);\n        \n        x = lu_.solve(b);\n    }\n    \n    // Apply to multiple vectors (possibly a matrix)\n    virtual void multi_solve(int number_of_vectors,\n                             std::vector<double> &b_data,\n                             std::vector<double> &x_data) override\n    {\n        Assert(initialized_);\n        Check(b_data.size() == size_ * number_of_vectors);\n        Check(x_data.size() == size_ * number_of_vectors);\n\n        EMMatrix b(&b_data[0], size_, number_of_vectors);\n        EMMatrix x(&x_data[0], size_, number_of_vectors);\n\n        x = lu_.solve(b);\n    }\n\n    // Get inverse\n    virtual void inverse(std::vector<double> &ainv_data) override\n    {\n        Assert(initialized_);\n        Check(ainv_data.size() == size_ * size_);\n        \n        EMMatrixR ainv(&ainv_data[0], size_, size_);\n\n        ainv = lu_.inverse();\n    }\n\n    virtual void inverse(std::vector<double> &a_data,\n                         std::vector<double> &ainv_data) override\n    {\n        Check(a_data.size() == size_ * size_);\n        Check(ainv_data.size() == size_ * size_);\n\n        EMMatrixR a(&a_data[0], size_, size_);\n        EMMatrixR ainv(&ainv_data[0], size_, size_);\n\n        ainv = a.fullPivLu().inverse();\n    }\n    \n    // Get determinant\n    virtual Scalar determinant() override\n    {\n        Assert(initialized_);\n        \n        return lu_.determinant();\n    }\n    \nprivate:\n    \n    bool initialized_;\n    int size_;\n    EMatrixR a_;\n    ELU lu_;\n};\n\n#endif\n", "meta": {"hexsha": "f4ddde3898cbeaa8b171f438f72afd900fa47be2", "size": 3728, "ext": "hh", "lang": "C++", "max_stars_repo_path": "packages/utilities/Eigen_Dense_Solver.hh", "max_stars_repo_name": "brbass/ibex", "max_stars_repo_head_hexsha": "5a4cc5b4d6d46430d9667970f8a34f37177953d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-13T20:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-12T17:55:54.000Z", "max_issues_repo_path": "packages/utilities/Eigen_Dense_Solver.hh", "max_issues_repo_name": "brbass/ibex", "max_issues_repo_head_hexsha": "5a4cc5b4d6d46430d9667970f8a34f37177953d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-22T21:03:35.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-22T21:03:35.000Z", "max_forks_repo_path": "packages/utilities/Eigen_Dense_Solver.hh", "max_forks_repo_name": "brbass/ibex", "max_forks_repo_head_hexsha": "5a4cc5b4d6d46430d9667970f8a34f37177953d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-04-03T02:15:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T05:50:23.000Z", "avg_line_length": 26.2535211268, "max_line_length": 92, "alphanum_fraction": 0.5802038627, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5828254564047225}}
{"text": "//  (C) Copyright Pieter Bastiaan Ober 2014.\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/test/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/mpl/assert.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/accumulators/accumulators.hpp>\r\n#include <boost/accumulators/statistics/stats.hpp>\r\n\r\n#include <boost/accumulators/statistics/rolling_variance.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace unit_test;\r\nusing namespace accumulators;\r\n\r\ntemplate<typename T>\r\nvoid assert_is_double(T const &)\r\n{\r\n    BOOST_MPL_ASSERT((is_same<T, double>));\r\n}\r\n\r\n/*\r\nREFERENCE VALUES PROVIDED BY OCTAVE:\r\n\r\nx=[1.2 2.3 3.4 4.5 0.4 2.2 7.1 4.0]\r\n\r\nv1_2 = var(x(1:2))\r\nv1_3 = var(x(1:3))\r\nv1_4 = var(x(1:4))\r\nv2_5 = var(x(2:5))\r\nv3_6 = var(x(3:6))\r\nv4_7 = var(x(4:7))\r\nv5_8 = var(x(5:8))\r\n\r\nGIVES:\r\n\r\nv1_2 =  0.605000000000000\r\nv1_3 =  1.21000000000000\r\nv1_4 =  2.01666666666667\r\nv2_5 =  3.05666666666667\r\nv3_6 =  3.08250000000000\r\nv4_7 =  8.41666666666667\r\nv5_8 =  8.16250000000000\r\n*/\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// rolling_variance_test_impl\r\n// implements a test for window_size = 4\r\n\r\nsize_t window_size = 4;\r\n\r\ntemplate<typename accumulator_set_type>\r\nvoid rolling_variance_test_impl(accumulator_set_type& acc)\r\n{\r\n    // Window contains x(1), value is zero\r\n    acc(1.2);\r\n    BOOST_CHECK_CLOSE(rolling_variance(acc),0.0,1e-10);\r\n\r\n    // Window contains x(1)...x(2)\r\n    acc(2.3);\r\n    BOOST_CHECK_CLOSE(rolling_variance(acc),0.605,1e-10);\r\n\r\n    // Window contains x(1)...x(3)\r\n    acc(3.4);\r\n    BOOST_CHECK_CLOSE(rolling_variance(acc),1.21,1e-10);\r\n\r\n    // Window contains x(1)...x(4)\r\n    acc(4.5);\r\n    BOOST_CHECK_CLOSE(rolling_variance(acc),2.01666666666667,1e-10);\r\n\r\n    // Window contains x(2)...x(5)\r\n    acc(0.4);\r\n    BOOST_CHECK_CLOSE(rolling_variance(acc),3.05666666666667,1e-10);\r\n\r\n    // Window contains x(3)...x(6)\r\n    acc(2.2);\r\n    BOOST_CHECK_CLOSE(rolling_variance(acc),3.08250000000000,1e-10);\r\n\r\n    // Window contains x(4)...x(7)\r\n    acc(7.1);\r\n    BOOST_CHECK_CLOSE(rolling_variance(acc),8.41666666666667,1e-10);\r\n\r\n    // Window contains x(5)...x(8)\r\n    acc(4.0);\r\n    BOOST_CHECK_CLOSE(rolling_variance(acc),8.16250000000000,1e-10);\r\n\r\n    assert_is_double(rolling_variance(acc));\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// test_rolling_variance\r\n//\r\nvoid test_rolling_variance()\r\n{\r\n    // tag::rolling_window::window_size\r\n    accumulator_set<double, stats<tag::immediate_rolling_variance> >\r\n        acc_immediate_rolling_variance(tag::immediate_rolling_variance::window_size = window_size);\r\n\r\n    accumulator_set<double, stats<tag::immediate_rolling_variance, tag::rolling_mean> >\r\n        acc_immediate_rolling_variance2(tag::immediate_rolling_variance::window_size = window_size);\r\n\r\n    accumulator_set<double, stats<tag::rolling_variance(immediate)> >\r\n        acc_immediate_rolling_variance3(tag::immediate_rolling_variance::window_size = window_size);\r\n\r\n    accumulator_set<double, stats<tag::lazy_rolling_variance> >\r\n        acc_lazy_rolling_variance(tag::lazy_rolling_variance::window_size = window_size);\r\n\r\n    accumulator_set<double, stats<tag::rolling_variance(lazy)> >\r\n       acc_lazy_rolling_variance2(tag::immediate_rolling_variance::window_size = window_size);\r\n\r\n    accumulator_set<double, stats<tag::rolling_variance> >\r\n        acc_default_rolling_variance(tag::rolling_variance::window_size = window_size);\r\n\r\n    //// test the different implementations\r\n    rolling_variance_test_impl(acc_immediate_rolling_variance);\r\n    rolling_variance_test_impl(acc_immediate_rolling_variance2);\r\n    rolling_variance_test_impl(acc_immediate_rolling_variance3);\r\n    rolling_variance_test_impl(acc_lazy_rolling_variance);\r\n    rolling_variance_test_impl(acc_lazy_rolling_variance2);\r\n    rolling_variance_test_impl(acc_default_rolling_variance);\r\n\r\n    //// test that the default implementation is the 'immediate' computation\r\n    BOOST_REQUIRE(sizeof(acc_lazy_rolling_variance) != sizeof(acc_immediate_rolling_variance));\r\n    BOOST_CHECK  (sizeof(acc_default_rolling_variance) == sizeof(acc_immediate_rolling_variance));\r\n\r\n    //// test the equivalence of the different ways to indicate a feature\r\n    BOOST_CHECK  (sizeof(acc_immediate_rolling_variance) == sizeof(acc_immediate_rolling_variance2));\r\n    BOOST_CHECK  (sizeof(acc_immediate_rolling_variance) == sizeof(acc_immediate_rolling_variance3));\r\n    BOOST_CHECK  (sizeof(acc_lazy_rolling_variance) == sizeof(acc_lazy_rolling_variance2));\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// init_unit_test_suite\r\n//\r\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n    test_suite *test = BOOST_TEST_SUITE(\"rolling variance test\");\r\n\r\n    test->add(BOOST_TEST_CASE(&test_rolling_variance));\r\n\r\n    return test;\r\n}", "meta": {"hexsha": "8e0894a6686231dbd6b54775e82a1eb53c0e5237", "size": 5089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/accumulators/test/rolling_variance.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/accumulators/test/rolling_variance.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/accumulators/test/rolling_variance.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": 35.0965517241, "max_line_length": 102, "alphanum_fraction": 0.693652977, "num_tokens": 1298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.5828046662970572}}
{"text": "/*\n * proc/rng.cpp --\n *\n * This file is part of nettcl2d application.\n *\n * Copyright (c) 2012 Andrey V. Nakin <andrey.nakin@gmail.com>\n * All rights reserved.\n *\n * See the file \"COPYING\" for information on usage and redistribution\n * of this file, and for a DISCLAIMER OF ALL WARRANTIES.\n *\n */\n\n#ifndef PROC_RNG_HPP_\n#define PROC_RNG_HPP_\n\n#include <tcl.h>\n#include <string>\n\n#include <boost/shared_ptr.hpp>\n#include <phlib/tclutils.h>\n#include \"wrapper.hpp\"\n#include \"../calc/abstract_rng.hpp\"\n#include \"../rng/uniform_rng.hpp\"\n#include \"../rng/uniform2_rng.hpp\"\n#include \"../rng/const_rng.hpp\"\n\nnamespace proc {\n\n\tnamespace type {\n\t\textern const char* rng;\n\t}\n\n\tclass RngWrapper : public Wrapper<&type::rng> {\n\n\t\ttypedef Wrapper<&type::rng> Base;\n\n\t\texplicit RngWrapper(AbstractRng* const engine) :\n\t\t\tengine(engine) {}\n\n\t\tvirtual Base* clone() const {\n\t\t\treturn new RngWrapper(dynamic_cast<AbstractRng*>(engine->clone()));\n\t\t}\n\n\t\tstatic int doMain(ClientData clientData, Tcl_Interp * interp, int objc, Tcl_Obj * CONST objv[]) {\n\t\t\treturn process(clientData, interp, objc, objv, main);\n\t\t}\n\n\t\tstatic int main(ClientData clientData, Tcl_Interp * interp, int objc, Tcl_Obj * CONST objv[]) {\n\t\t\tif (objc < 2)\n\t\t\t\tthrow WrongNumArgs(interp, 1, objv, \"command\");\n\n\t\t\tconst std::string cmd = Tcl_GetStringFromObj(objv[1], NULL);\n\n\t\t\ttry {\n\t\t\t\tif (\"create\" == cmd) {\n\t\t\t\t\treturn create(interp, objc - 2, objv + 2);\n\t\t\t\t}\n\n\t\t\t\telse if (\"exists\" == cmd) {\n\t\t\t\t\treturn exists(interp, objc - 2, objv + 2);\n\t\t\t\t}\n\n\t\t\t\telse if (\"seed\" == cmd) {\n\t\t\t\t\treturn processInstance(clientData, interp, objc - 2, objv + 2, static_cast<InstanceHandler>(&RngWrapper::seed));\n\t\t\t\t}\n\n\t\t\t\telse if (\"next\" == cmd) {\n\t\t\t\t\treturn processInstance(clientData, interp, objc - 2, objv + 2, static_cast<InstanceHandler>(&RngWrapper::next));\n\t\t\t\t}\n\n\t\t\t\telse\n\t\t\t\t\tthrow WrongArgValue(interp, \"create | exists | seed | next\");\n\t\t\t} catch (WrongNumArgs& ex) {\n\t\t\t\tthrow WrongNumArgs(interp, 2 + ex.objc, objv, ex.message);\n\t\t\t}\n\n\t\t\treturn TCL_OK;\n\t\t}\n\n\t\tstatic int create(Tcl_Interp * interp, int objc, Tcl_Obj * CONST objv[]) {\n\t\t\tif (objc < 1)\n\t\t\t\tthrow WrongNumArgs(interp, 0, objv, \"rngType\");\n\n\t\t\tconst std::string methodName = Tcl_GetStringFromObj(objv[0], NULL);\n\t\t\tAbstractRng* rng;\n\n\t\t\tif (\"uniform\" == methodName) {\n\t\t\t\tif (objc != 3)\n\t\t\t\t\tthrow WrongNumArgs(interp, 1, objv, \"mean range\");\n\n\t\t\t\trng = new rng::Uniform(\n\t\t\t\t\t\tphlib::TclUtils::getDouble(interp, objv[1]),\n\t\t\t\t\t\tphlib::TclUtils::getDouble(interp, objv[2]));\n\t\t\t}\n\n\t\t\telse if (\"uniform2\" == methodName) {\n\t\t\t\tif (objc != 3)\n\t\t\t\t\tthrow WrongNumArgs(interp, 1, objv, \"min max\");\n\n\t\t\t\trng = new rng::Uniform2(\n\t\t\t\t\t\tphlib::TclUtils::getDouble(interp, objv[1]),\n\t\t\t\t\t\tphlib::TclUtils::getDouble(interp, objv[2]));\n\t\t\t}\n\n\t\t\telse if (\"const\" == methodName) {\n\t\t\t\tif (objc != 2)\n\t\t\t\t\tthrow WrongNumArgs(interp, 1, objv, \"value\");\n\n\t\t\t\trng = new rng::Const(phlib::TclUtils::getDouble(interp, objv[1]));\n\t\t\t}\n\n\t\t\telse\n\t\t\t\tthrow WrongArgValue(interp, \"const | uniform | uniform2\");\n\n\t\t\t// instantiate new TCL object\n\t\t\tTcl_Obj* const w = Tcl_NewObj();\n\t\t\tw->typePtr = RngWrapper::type();\n\t\t\tw->internalRep.otherValuePtr = new RngWrapper(rng);\n\t\t\t::Tcl_SetObjResult(interp, w);\n\n\t\t\treturn TCL_OK;\n\t\t}\n\n\t\tint seed(ClientData /* clientData */, Tcl_Interp * interp, int objc, Tcl_Obj * CONST objv[]) {\n\t\t\tif (objc != 1)\n\t\t\t\tthrow phlib::TclUtils::wrong_num_args_exception(interp, objc, objv);\n\n\t\t\tengine->seed(phlib::TclUtils::getLong(interp, objv[0]));\n\t\t\treturn TCL_OK;\n\t\t}\n\n\t\tint next(ClientData /* clientData */, Tcl_Interp * interp, int objc, Tcl_Obj * CONST objv[]) {\n\t\t\tif (objc != 0)\n\t\t\t\tthrow phlib::TclUtils::wrong_num_args_exception(interp, objc, objv);\n\n\t\t\t::Tcl_SetObjResult(interp, ::Tcl_NewDoubleObj(engine->generate()));\n\t\t\treturn TCL_OK;\n\t\t}\n\n\tpublic:\n\n\t\tboost::shared_ptr<AbstractRng> engine;\n\n\t\tstatic RngWrapper* validateArg(Tcl_Interp *interp, const Tcl_Obj* arg) {\n\t\t\treturn static_cast<RngWrapper*>(Base::validateArg(interp, arg));\n\t\t}\n\n\t\tstatic void registerCommands(Tcl_Interp * interp) {\n\t\t\tregisterCommand(interp, doMain);\n\t\t}\n\n\t};\n\n}\n\n#endif // PROC_RNG_HPP_\n", "meta": {"hexsha": "dc73687d2f83064c1a82ece1090aa8023fce4300", "size": 4113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/nettcl2d/proc/rng_wrapper.hpp", "max_stars_repo_name": "andrey-nakin/nettcl2d", "max_stars_repo_head_hexsha": "d35d9dee6d108e7a09345a06aa4a6349bef1c0fb", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nettcl2d/proc/rng_wrapper.hpp", "max_issues_repo_name": "andrey-nakin/nettcl2d", "max_issues_repo_head_hexsha": "d35d9dee6d108e7a09345a06aa4a6349bef1c0fb", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nettcl2d/proc/rng_wrapper.hpp", "max_forks_repo_name": "andrey-nakin/nettcl2d", "max_forks_repo_head_hexsha": "d35d9dee6d108e7a09345a06aa4a6349bef1c0fb", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0316455696, "max_line_length": 117, "alphanum_fraction": 0.6571845368, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.5827458899803458}}
{"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": "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n#include <cmath>\n#include <iostream>\n\n#include <lagrange/testing/common.h>\n\n#include <Eigen/Geometry>\n\n#include <lagrange/common.h>\n#include <lagrange/compute_pointcloud_pca.h>\n#include <lagrange/utils/safe_cast.h>\n\nTEST_CASE(\"ComputePointcloudPCA\", \"[compute_pointcloud_pca][symmetry]\")\n{\n    using namespace lagrange;\n\n\n    using MatrixX3dRowMajor = Eigen::Matrix<double, Eigen::Dynamic, 3, Eigen::RowMajor>;\n    using MatrixX3dColMajor = Eigen::Matrix<double, Eigen::Dynamic, 3, Eigen::ColMajor>;\n    const double eps = 1e-10;\n\n    // An arbitrary rotation\n    const Eigen::Matrix3d rotation =\n        Eigen::AngleAxisd(M_PI * 0.2657, Eigen::Vector3d(-1, 4, -7).normalized())\n            .toRotationMatrix();\n\n    // An arbitrary translation\n    const Eigen::Vector3d translation(1.34, -5.214, 0.35654);\n\n\n    // Some points on the x,y, and z axes\n    const double a = 0.1;\n    const double b = 0.4;\n    const double c = 1.2;\n\n    MatrixX3dRowMajor points(6, 3);\n    points.row(0) << a, 0, 0;\n    points.row(1) << -a, 0, 0;\n    points.row(2) << 0, -b, 0;\n    points.row(3) << 0, b, 0;\n    points.row(4) << 0, 0, c;\n    points.row(5) << 0, 0, -c;\n\n    // Make sure that the pca was correct\n    auto verify_pca = [eps, a, b, c](\n                          const double mass,\n                          const Eigen::MatrixXd& pts,\n                          const Eigen::MatrixXd& weights,\n                          const Eigen::MatrixXd& components,\n                          const Eigen::MatrixXd& R,\n                          const Eigen::VectorXd& t) {\n        const double a2 = a * a;\n        const double b2 = b * b;\n        const double c2 = c * c;\n\n        auto approx0 = Approx(0).margin(eps);\n\n        REQUIRE(weights(0) == Approx(mass * 2 * a2));\n        REQUIRE(weights(1) == Approx(mass * 2 * b2));\n        REQUIRE(weights(2) == Approx(mass * 2 * c2));\n        REQUIRE((components.col(0) - R * Eigen::Vector3d(1, 0, 0)).norm() == approx0);\n        REQUIRE((components.col(1) - R * Eigen::Vector3d(0, 1, 0)).norm() == approx0);\n        REQUIRE((components.col(2) - R * Eigen::Vector3d(0, 0, 1)).norm() == approx0);\n\n        Eigen::MatrixXd pminustr = pts.rowwise() - t.transpose();\n        REQUIRE(\n            (mass * pminustr.transpose() * pminustr -\n             components * weights.asDiagonal() * components.transpose())\n                .norm() == approx0);\n    };\n\n    SECTION(\"Column Major\")\n    {\n        using MatrixType = MatrixX3dColMajor;\n        SECTION(\"Simple case\")\n        {\n            MatrixType points_tr = points;\n            auto out =\n                compute_pointcloud_pca(points_tr, false /*shift_center*/, false /*normalize*/);\n            verify_pca(\n                1 /*mass*/,\n                points_tr,\n                out.weights,\n                out.components,\n                Eigen::Matrix3d::Identity(),\n                Eigen::Vector3d::Zero());\n        }\n\n        SECTION(\"With rotation\")\n        {\n            MatrixType points_tr = points * rotation.transpose();\n            auto out =\n                compute_pointcloud_pca(points_tr, false /*shift_center*/, false /*normalize*/);\n            verify_pca(\n                1 /* mass */,\n                points_tr,\n                out.weights,\n                out.components,\n                rotation,\n                Eigen::Vector3d::Zero());\n            REQUIRE(out.center.norm() == Approx(0.).margin(eps));\n        }\n\n        SECTION(\"With rotation and translation\")\n        {\n            MatrixType points_tr =\n                (points * rotation.transpose()).rowwise() + translation.transpose();\n            auto out =\n                compute_pointcloud_pca(points_tr, true /*shift_center*/, false /*normalize*/);\n            verify_pca(1 /* mass */, points_tr, out.weights, out.components, rotation, translation);\n            REQUIRE((out.center - translation).norm() == Approx(0.).margin(eps));\n        }\n\n        SECTION(\"With rotation and translation, also scale the covariance matrix\")\n        {\n            MatrixType points_tr =\n                (points * rotation.transpose()).rowwise() + translation.transpose();\n            const double mass = safe_cast<double>(1.) / (points.rows());\n            auto out = compute_pointcloud_pca(points_tr, true /*shift_center*/, true /*normalize*/);\n            verify_pca(mass, points_tr, out.weights, out.components, rotation, translation);\n            REQUIRE((out.center - translation).norm() == Approx(0.).margin(eps));\n        }\n    }\n\n    SECTION(\"ROW MAJOR\")\n    {\n        using MatrixType = MatrixX3dRowMajor;\n        SECTION(\"Simple case\")\n        {\n            MatrixType points_tr = points;\n            auto out =\n                compute_pointcloud_pca(points_tr, false /*shift_center*/, false /*normalize*/);\n            verify_pca(\n                1 /*mass*/,\n                points_tr,\n                out.weights,\n                out.components,\n                Eigen::Matrix3d::Identity(),\n                Eigen::Vector3d::Zero());\n        }\n\n        SECTION(\"With rotation\")\n        {\n            MatrixType points_tr = points * rotation.transpose();\n            auto out =\n                compute_pointcloud_pca(points_tr, false /*shift_center*/, false /*normalize*/);\n            verify_pca(\n                1 /* mass */,\n                points_tr,\n                out.weights,\n                out.components,\n                rotation,\n                Eigen::Vector3d::Zero());\n            REQUIRE(out.center.norm() == Approx(0.).margin(eps));\n        }\n\n        SECTION(\"With rotation and translation\")\n        {\n            MatrixType points_tr =\n                (points * rotation.transpose()).rowwise() + translation.transpose();\n            auto out =\n                compute_pointcloud_pca(points_tr, true /*shift_center*/, false /*normalize*/);\n            verify_pca(1 /* mass */, points_tr, out.weights, out.components, rotation, translation);\n            REQUIRE((out.center - translation).norm() == Approx(0.).margin(eps));\n        }\n\n        SECTION(\"With rotation and translation, also scale the covariance matrix\")\n        {\n            MatrixType points_tr =\n                (points * rotation.transpose()).rowwise() + translation.transpose();\n            const double mass = safe_cast<double>(1.) / (points.rows());\n            auto out = compute_pointcloud_pca(points_tr, true /*shift_center*/, true /*normalize*/);\n            verify_pca(mass, points_tr, out.weights, out.components, rotation, translation);\n            REQUIRE((out.center - translation).norm() == Approx(0.).margin(eps));\n        }\n    }\n\n} // end of TEST\n", "meta": {"hexsha": "d420aab495d5152768ab1a47b3fbbfc86dc98a02", "size": 7226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/tests/test_compute_pointcloud_pca.cpp", "max_stars_repo_name": "LaudateCorpus1/lagrange", "max_stars_repo_head_hexsha": "2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 156.0, "max_stars_repo_stars_event_min_datetime": "2021-01-08T19:53:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T18:32:52.000Z", "max_issues_repo_path": "modules/core/tests/test_compute_pointcloud_pca.cpp", "max_issues_repo_name": "LaudateCorpus1/lagrange", "max_issues_repo_head_hexsha": "2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T20:18:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T15:53:57.000Z", "max_forks_repo_path": "modules/core/tests/test_compute_pointcloud_pca.cpp", "max_forks_repo_name": "LaudateCorpus1/lagrange", "max_forks_repo_head_hexsha": "2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2021-01-11T21:03:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T06:27:44.000Z", "avg_line_length": 38.2328042328, "max_line_length": 100, "alphanum_fraction": 0.5622751176, "num_tokens": 1644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5827059132378994}}
{"text": "// Copyright Louis Dionne 2013-2017\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/maximum.hpp>\n#include <boost/hana/minimum.hpp>\n#include <boost/hana/set.hpp>\n#include <boost/hana/sum.hpp>\nnamespace hana = boost::hana;\n\n\nint main() {\n    constexpr auto xs = hana::make_set(hana::int_c<0>, hana::int_c<1>, hana::int_c<2>);\n    static_assert(hana::minimum(xs) == hana::int_c<0>, \"\");\n    static_assert(hana::maximum(xs) == hana::int_c<2>, \"\");\n    static_assert(hana::sum<>(xs) == hana::int_c<3>, \"\");\n}\n", "meta": {"hexsha": "0f17415eb6515e5eb09709726c6daf2cbad81f59", "size": 731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/hana/example/set/foldable.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/hana/example/set/foldable.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/hana/example/set/foldable.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 34.8095238095, "max_line_length": 87, "alphanum_fraction": 0.6963064295, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246118695627, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5827059085813764}}
{"text": "#include <ceres/gradient_checker.h>\n#include <Eigen/Core>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#include \"wave/wave_test.hpp\"\n#include \"wave/utils/math.hpp\"\n#include \"wave/geometry_og/transformation.hpp\"\n#include \"wave/optimization/ceres/odom_gp/constant_velocity.hpp\"\n#include \"wave/optimization/ceres/local_params/SE3Parameterization.hpp\"\n\nnamespace {\n/// Helper functions\nEigen::Matrix<double, 12, 12> calculateCVIntegrand(const wave::Mat6 &Qc,\n                                                   const double &delta_T,\n                                                   const wave::Vec6 &velocity) {\n    Eigen::Matrix<double, 12, 12> retval;\n    auto jacobian = wave::Transformation<>::SE3LeftJacobian(delta_T * velocity);\n    retval.block<6, 6>(0, 0) = delta_T * delta_T * jacobian * Qc * jacobian.transpose();\n    retval.block<6, 6>(6, 0) = delta_T * jacobian.transpose();\n    retval.block<6, 6>(0, 6) = delta_T * jacobian;\n    retval.block<6, 6>(6, 6) = Qc;\n    return retval;\n}\n\nvoid calculateTransitionMatrix(const double &delta_T,\n                               const wave::Vec6 &velocity,\n                               Eigen::Matrix<double, 12, 12> &transition_matrix) {\n    transition_matrix.setIdentity();\n    transition_matrix.block<6, 6>(0, 0) = wave::Transformation<>::expMapAdjoint(delta_T * velocity);\n    transition_matrix.block<6, 6>(0, 6) = delta_T * wave::Transformation<>::SE3LeftJacobian(delta_T * velocity);\n}\n\nEigen::Matrix<double, 12, 12> integrateCovariance(const wave::Mat6 &Qc,\n                                                  const double &delta_T,\n                                                  const wave::Vec6 &velocity,\n                                                  const int &steps) {\n    Eigen::Matrix<double, 12, 12> Qtotal;\n    Qtotal.setZero();\n    double step_size = delta_T / (double) steps;\n    Eigen::Matrix<double, 12, 12> Qincremental;\n    double step_delta_T;\n    for (int i = 0; i <= steps; i++) {\n        step_delta_T = delta_T - ((double) i) * step_size;\n        Qincremental = calculateCVIntegrand(Qc, step_delta_T, velocity);\n        if (i == 0 || i == steps) {\n            Qtotal.noalias() += 0.5 * Qincremental;\n        } else {\n            Qtotal.noalias() += Qincremental;\n        }\n    }\n    Qtotal = Qtotal * step_size;\n    return Qtotal;\n}\n}\n\nnamespace wave {\n\n/**\n * Due to hack to workaround Ceres local parameterization for speedup\n * the built-in gradient checker can't be used\n */\nTEST(ConstantVelocity, Jacobians) {\n    Transformation<Eigen::Matrix<double, 3, 4>> start, end;\n    Mat4 t_matrix;\n    t_matrix << 0.936293363584199, -0.275095847318244, 0.218350663146334, 1, 0.289629477625516, 0.956425085849232,\n      -0.036957013524625, 2, -0.198669330795061, 0.097843395007256, 0.975170327201816, 3, 0, 0, 0, 1;\n\n    start.setFromMatrix(t_matrix);\n    end.setFromMatrix(t_matrix);\n\n    const double delta_T = 0.1;\n    Vec6 start_vel, end_vel;\n\n    start_vel << -0, 0, 0.3, 20, 5, -0.1;\n    end_vel = start_vel;\n\n    end.manifoldPlus(delta_T * start_vel);\n\n    // Calculate transition matrix and weight matrix for residual\n    Mat6 Qc = Mat6::Identity();\n    Eigen::Matrix<double, 12, 12> covariance, weight;\n    covariance = integrateCovariance(Qc, delta_T, start_vel, 20);\n\n    weight = Eigen::Matrix<double, 12, 12>::Identity();\n\n    ceres::CostFunction *cost_function = new ConstantVelocityPrior(weight, delta_T);\n\n    const double **parameters;\n    parameters = new const double *[4];\n    parameters[0] = start.storage.data();\n    parameters[1] = end.storage.data();\n    parameters[2] = start_vel.data();\n    parameters[3] = end_vel.data();\n\n    double *residuals;\n    residuals = new double[12];\n\n    double **jacobians;\n    jacobians = new double *[4];\n    jacobians[0] = new double[144];\n    jacobians[1] = new double[144];\n    jacobians[2] = new double[72];\n    jacobians[3] = new double[72];\n\n    cost_function->Evaluate(parameters, residuals, jacobians);\n\n    Eigen::Matrix<double, 12, 1> residual_vec;\n    residual_vec = Eigen::Map<Eigen::Matrix<double, 12, 1>>(residuals);\n\n    EXPECT_NEAR(residual_vec.norm(), 0, 1e-6);\n\n    Eigen::Map<Eigen::Matrix<double, 12, 12, Eigen::RowMajor>> Jr_Ti(jacobians[0]);\n    Eigen::Map<Eigen::Matrix<double, 12, 12, Eigen::RowMajor>> Jr_Tip1(jacobians[1]);\n    Eigen::Map<Eigen::Matrix<double, 12, 6, Eigen::RowMajor>> Jr_Wi(jacobians[2]);\n    Eigen::Map<Eigen::Matrix<double, 12, 6, Eigen::RowMajor>> Jr_Wip1(jacobians[3]);\n\n    const double step_size = 1.4901e-07;\n    const double inv_step = 1.0 / step_size;\n    Vec6 delta;\n    delta.setZero();\n\n    Transformation<> Tk_perturbed, Tkp1_perturbed;\n    Vec6 vel_k_perturbed, vel_kp1_perturbed;\n\n    Tk_perturbed = (start);\n    Tkp1_perturbed = (end);\n    vel_k_perturbed = start_vel;\n    vel_kp1_perturbed = end_vel;\n\n    parameters[0] = Tk_perturbed.storage.data();\n    parameters[1] = Tkp1_perturbed.storage.data();\n    parameters[2] = vel_k_perturbed.data();\n    parameters[3] = vel_kp1_perturbed.data();\n\n    Eigen::Matrix<double, 12, 1> diff, result;\n\n    std::vector<Eigen::Matrix<double, 12, 6>> an_jacs, num_jacs;\n    num_jacs.resize(4);\n    an_jacs.resize(4);\n    an_jacs.at(0) = Jr_Ti.block<12, 6>(0, 0);\n    an_jacs.at(1) = Jr_Tip1.block<12, 6>(0, 0);\n    an_jacs.at(2) = Jr_Wi;\n    an_jacs.at(3) = Jr_Wip1;\n\n    for (uint32_t i = 0; i < 6; i++) {\n        delta(i) = step_size;\n        // First parameter\n        Tk_perturbed.manifoldPlus(delta);\n        cost_function->Evaluate(parameters, result.data(), nullptr);\n        diff = result - residual_vec;\n        num_jacs.at(0).block<12, 1>(0, i) = inv_step * diff;\n        Tk_perturbed = (start);\n        // Second parameter\n        Tkp1_perturbed.manifoldPlus(delta);\n        cost_function->Evaluate(parameters, result.data(), nullptr);\n        diff = result - residual_vec;\n        num_jacs.at(1).block<12, 1>(0, i) = inv_step * diff;\n        Tkp1_perturbed = (end);\n        // Third parameter\n        vel_k_perturbed = vel_k_perturbed + delta;\n        cost_function->Evaluate(parameters, result.data(), nullptr);\n        diff = result - residual_vec;\n        num_jacs.at(2).block<12, 1>(0, i) = inv_step * diff;\n        vel_k_perturbed = start_vel;\n        // Fourth parameter\n        vel_kp1_perturbed = vel_kp1_perturbed + delta;\n        cost_function->Evaluate(parameters, result.data(), nullptr);\n        diff = result - residual_vec;\n        num_jacs.at(3).block<12, 1>(0, i) = inv_step * diff;\n        vel_kp1_perturbed = end_vel;\n\n        delta.setZero();\n    }\n\n    for (uint32_t i = 0; i < 4; i++) {\n        double err = (num_jacs.at(i) - an_jacs.at(i)).norm();\n        EXPECT_NEAR(err, 0.0, 1e-6);\n        if (err > 1e-6) {\n            std::cout << \"Failed on index \" << i << std::endl\n                      << \"Numerical: \" << std::endl\n                      << num_jacs.at(i) << std::endl\n                      << \"Analytical:\" << std::endl\n                      << an_jacs.at(i) << std::endl\n                      << std::endl;\n        }\n    }\n}\n\n}\n", "meta": {"hexsha": "631fd87172081de356b6457027bd7e5b8f4dd1af", "size": 7006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wave_optimization/tests/ceres/constant_velocity_test.cpp", "max_stars_repo_name": "Jebediah/libwave", "max_stars_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T13:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T14:54:35.000Z", "max_issues_repo_path": "wave_optimization/tests/ceres/constant_velocity_test.cpp", "max_issues_repo_name": "Jebediah/libwave", "max_issues_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_optimization/tests/ceres/constant_velocity_test.cpp", "max_forks_repo_name": "Jebediah/libwave", "max_forks_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T02:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T02:27:29.000Z", "avg_line_length": 36.8736842105, "max_line_length": 114, "alphanum_fraction": 0.6107622038, "num_tokens": 2037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5827059068827108}}
{"text": "/*\n * @file sa_test.cpp\n * @auther Zhihao Lou\n *\n * Test file for SA (simulated annealing).\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/core/optimizers/sa/sa.hpp>\n#include <mlpack/core/optimizers/sa/exponential_schedule.hpp>\n#include <mlpack/core/optimizers/problems/generalized_rosenbrock_function.hpp>\n#include <mlpack/core/optimizers/problems/rosenbrock_function.hpp>\n#include <mlpack/core/optimizers/problems/rastrigin_function.hpp>\n\n#include <mlpack/core/metrics/ip_metric.hpp>\n#include <mlpack/core/metrics/lmetric.hpp>\n#include <mlpack/core/metrics/mahalanobis_distance.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace std;\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::optimization;\nusing namespace mlpack::optimization::test;\nusing namespace mlpack::metric;\n\nBOOST_AUTO_TEST_SUITE(SATest);\n\n// The Generalized-Rosenbrock function is a simple function to optimize.\nBOOST_AUTO_TEST_CASE(GeneralizedRosenbrockTest)\n{\n  size_t dim = 10;\n  GeneralizedRosenbrockFunction f(dim);\n\n  double iteration = 0;\n  double result = DBL_MAX;\n  arma::mat coordinates;\n  while (result > 1e-6)\n  {\n    ExponentialSchedule schedule;\n    // The convergence is very sensitive to the choices of maxMove and initMove.\n    SA<ExponentialSchedule> sa(schedule, 1000000, 1000., 1000, 100, 1e-10, 3,\n        1.5, 0.5, 0.3);\n    coordinates = f.GetInitialPoint();\n    result = sa.Optimize(f, coordinates);\n    ++iteration;\n\n    BOOST_REQUIRE_LT(iteration, 4); // No more than three tries.\n  }\n\n  // 0.1% tolerance for each coordinate.\n  BOOST_REQUIRE_SMALL(result, 1e-6);\n  for (size_t j = 0; j < dim; ++j)\n      BOOST_REQUIRE_CLOSE(coordinates[j], (double) 1.0, 0.1);\n}\n\n// The Rosenbrock function is a simple function to optimize.\nBOOST_AUTO_TEST_CASE(RosenbrockTest)\n{\n  RosenbrockFunction f;\n  ExponentialSchedule schedule;\n  // The convergence is very sensitive to the choices of maxMove and initMove.\n  SA<> sa(schedule, 1000000, 1000., 1000, 100, 1e-11, 3, 1.5, 0.3, 0.3);\n  arma::mat coordinates = f.GetInitialPoint();\n\n  const double result = sa.Optimize(f, coordinates);\n\n  BOOST_REQUIRE_SMALL(result, 1e-5);\n  BOOST_REQUIRE_CLOSE(coordinates[0], 1.0, 1e-2);\n  BOOST_REQUIRE_CLOSE(coordinates[1], 1.0, 1e-2);\n}\n\n/**\n * The Rastrigrin function, a (not very) simple nonconvex function. It has very\n * many local minima, so finding the true global minimum is difficult.\n */\nBOOST_AUTO_TEST_CASE(RastrigrinFunctionTest)\n{\n  // Simulated annealing isn't guaranteed to converge (except in very specific\n  // situations).  If this works 1 of 4 times, I'm fine with that.  All I want\n  // to know is that this implementation will escape from local minima.\n  size_t successes = 0;\n\n  for (size_t trial = 0; trial < 4; ++trial)\n  {\n    RastriginFunction f(2);\n    ExponentialSchedule schedule;\n    // The convergence is very sensitive to the choices of maxMove and initMove.\n    // SA<> sa(schedule, 2000000, 100, 50, 1000, 1e-12, 2, 2.0, 0.5, 0.1);\n    SA<> sa(schedule, 2000000, 100, 50, 1000, 1e-12, 2, 2.0, 0.5, 0.1);\n    arma::mat coordinates = f.GetInitialPoint();\n\n    const double result = sa.Optimize(f, coordinates);\n\n    if ((std::abs(result) < 1e-3) &&\n        (std::abs(coordinates[0]) < 1e-3) &&\n        (std::abs(coordinates[1]) < 1e-3))\n    {\n      ++successes;\n      break; // No need to continue.\n    }\n  }\n\n  BOOST_REQUIRE_GE(successes, 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "9f964166c0ea2ae26cf4eb87e2305c4d3b4629a8", "size": 3724, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/sa_test.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-02T21:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T21:10:55.000Z", "max_issues_repo_path": "src/mlpack/tests/sa_test.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/sa_test.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6666666667, "max_line_length": 80, "alphanum_fraction": 0.7142857143, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5827059016599664}}
{"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_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    Function object implementing acoth capabilities\n\n    Returns the hyperbolic cotangent argument \\f$\\frac12\\log\\frac{x^2+1}{x^2-1}\\f$\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = acoth(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = Half<T>()*log(oneplus(sqr(x))/minusone(sqr(x)));\n    @endcode\n\n    @see log, Half\n\n  **/\n  const boost::dispatch::functor<tag::acoth_> acoth = {};\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": "74faf87d7ef7b6efb39bedb8227d5039097b4000", "size": 1163, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/acoth.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/acoth.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/acoth.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.8039215686, "max_line_length": 100, "alphanum_fraction": 0.5760963027, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5827059016599664}}
{"text": "// Copyright (C) 2016  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n#include <dlib/optimization/elastic_net.h>\n#include \"tester.h\"\n#include <dlib/svm.h>\n#include <dlib/rand.h>\n#include <dlib/string.h>\n#include <vector>\n#include <sstream>\n#include <ctime>\n\nnamespace  \n{\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n    dlib::logger dlog(\"test.elastic_net\");\n\n// ----------------------------------------------------------------------------------------\n\n    matrix<double,0,1> basic_elastic_net(\n        const matrix<double>& X,\n        const matrix<double,0,1>& Y,\n        double ridge_lambda,\n        double lasso_budget,\n        double eps\n    )\n    {\n        DLIB_CASSERT(X.nc() == Y.nr(),\"\");\n\n\n        typedef matrix<double,0,1> sample_type;\n        typedef linear_kernel<sample_type> kernel_type;\n\n        svm_c_linear_dcd_trainer<kernel_type> trainer;\n        trainer.solve_svm_l2_problem(true);\n        const double C = 1/(2*ridge_lambda);\n        trainer.set_c(C);\n        trainer.set_epsilon(eps);\n        trainer.enable_shrinking(true);\n        trainer.include_bias(false);\n\n\n        std::vector<sample_type> samples;\n        std::vector<double> labels;\n        for (long r = 0; r < X.nr(); ++r)\n        {\n            sample_type temp = trans(rowm(X,r));\n\n            const double xmul = (1/lasso_budget);\n            samples.push_back(temp - xmul*Y);\n            labels.push_back(+1);\n            samples.push_back(temp + xmul*Y);\n            labels.push_back(-1);\n        }\n\n        svm_c_linear_dcd_trainer<kernel_type>::optimizer_state state;\n        auto df = trainer.train(samples, labels, state);\n        auto&& alpha = state.get_alpha();\n\n        matrix<double,0,1> betas(alpha.size()/2);\n        for (long i = 0; i < betas.size(); ++i)\n            betas(i) = lasso_budget*(alpha[2*i] - alpha[2*i+1]);\n        betas /= sum(mat(alpha));\n        return betas;\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    class test_elastic_net : public tester\n    {\n    public:\n        test_elastic_net (\n        ) :\n            tester (\n                \"test_elastic_net\",       \n                \"Run tests on the elastic_net object.\", \n                0                     \n            )\n        {\n        }\n\n        void perform_test (\n        )\n        {\n            matrix<double> w = {1,2,0,4, 0,0,0,0,0, 6, 7,8,0, 9, 0};\n\n            matrix<double> X = randm(w.size(),1000);\n            matrix<double> Y = trans(X)*w;\n            Y += 0.1*(randm(Y.nr(), Y.nc())-0.5);\n\n\n            double ridge_lambda = 0.1;\n            double lasso_budget = sum(abs(w));\n            double eps = 0.0000001;\n\n            dlib::elastic_net solver(X*trans(X),X*Y);\n            solver.set_epsilon(eps);\n\n\n            matrix<double,0,1> results;\n            matrix<double,0,1> results2;\n            for (double s = 1.2; s > 0.10; s *= 0.9)\n            {\n                print_spinner();\n                dlog << LINFO << \"s: \"<< s;\n                // make sure the two solvers agree.  \n                results = basic_elastic_net(X, Y, ridge_lambda, lasso_budget*s, eps);\n                results2 = solver(ridge_lambda, lasso_budget*s);\n                dlog << LINFO << \"error: \"<< max(abs(results - results2));\n                DLIB_TEST(max(abs(results - results2) < 1e-3));\n            }\n        }\n    } a;\n\n// ----------------------------------------------------------------------------------------\n\n}\n\n\n\n", "meta": {"hexsha": "4f3c2ad58b4c2d7eed04ade79b0999148997f060", "size": 3548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/elastic_net.cpp", "max_stars_repo_name": "yatonon/dlib-face", "max_stars_repo_head_hexsha": "0230c1034ee65d0846d007e6145bfe73ca0d6321", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 131.0, "max_stars_repo_stars_event_min_datetime": "2017-02-10T03:05:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:18:24.000Z", "max_issues_repo_path": "dlib/test/elastic_net.cpp", "max_issues_repo_name": "yatonon/dlib-face", "max_issues_repo_head_hexsha": "0230c1034ee65d0846d007e6145bfe73ca0d6321", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-08-12T05:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T03:51:44.000Z", "max_forks_repo_path": "dlib/test/elastic_net.cpp", "max_forks_repo_name": "yatonon/dlib-face", "max_forks_repo_head_hexsha": "0230c1034ee65d0846d007e6145bfe73ca0d6321", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2017-02-26T16:02:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T02:18:22.000Z", "avg_line_length": 28.8455284553, "max_line_length": 91, "alphanum_fraction": 0.4884441939, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5827058970034439}}
{"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": "#ifndef NDSS_MATRIX_HPP\n#define NDSS_MATRIX_HPP\n#include \"Vector.hpp\"\n\n#include <vector>\n#include <iostream>\n#ifdef USE_EIGEN\n#include <eigen3/Eigen/Dense>\n#endif\n#include <NTL/ZZX.h>\nclass EncryptedArray;\nnamespace MDL {\ntemplate<typename T>\nclass Matrix : public std::vector<Vector<T> > {\npublic:\n    Matrix(int rows = 0, int cols = 0)\n        : std::vector<Vector<T> >(rows, Vector<T>(cols)) {}\n\n    size_t rows() const;\n    size_t cols() const;\n\n\n    Matrix<T>  dot(const Matrix<T>& oth) const;\n    Vector<T>  dot(const Vector<T>& oth) const;\n#ifdef USE_EIGEN\n    double        maxEigenValue() const;\n    Matrix<double>inverse() const;\n    Eigen::MatrixXd to_Eigen_matrix_format() const;\n    void from_Eigen_matrix(const Eigen::MatrixXd& mat);\n#endif\n    std::vector<NTL::ZZX> encode(const EncryptedArray &ea) const;\n\n    Matrix& operator*=(const T &val);\n\n    Matrix& operator+=(const Matrix<T> &oth);\n\n    Matrix& operator-=(const Matrix<T> &oth);\n\n    void random(const T &domain);\n\n    Matrix<double> reduce(const double factor) const;\n\n    Matrix<long> div(long factor) const;\n\n    Vector<T> vector() const;\n\n    template<typename U>\n    friend std::ostream& operator<<(std::ostream& os,\n                                    Matrix<U>   & obj);\n    /// @create a submatrix from row r1, to row r2 and from column c1 to column c2.\n    Matrix<T> submatrix(long r1, long r2, long c1 = 0, long c2 = 0) const;\n\n    Matrix<T> transpose() const;\n};\n\nMatrix<long> eye(long dimension);\n\ntemplate<typename T>\nMatrix<T> covariance(const Vector<T> &a, const Vector<T> &b);\n\n} // namespace MDL\n#endif // ifndef NDSS_MATRIX_HPP\n", "meta": {"hexsha": "d1ab39018c7d1d8e11e5adf7ca741e00bebc9dd5", "size": 1621, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "algebra/Matrix.hpp", "max_stars_repo_name": "fionser/MDLHElib", "max_stars_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T06:20:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-17T12:36:34.000Z", "max_issues_repo_path": "algebra/Matrix.hpp", "max_issues_repo_name": "fionser/MDLHElib", "max_issues_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algebra/Matrix.hpp", "max_forks_repo_name": "fionser/MDLHElib", "max_forks_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-08-26T13:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T02:08:20.000Z", "avg_line_length": 25.7301587302, "max_line_length": 83, "alphanum_fraction": 0.6594694633, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5826762118551992}}
{"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": "//\n// Created by Alex Beccaro on 07/01/18.\n//\n\n#include \"problem48.hpp\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <generics.hpp>\n\nusing std::vector;\nusing boost::multiprecision::cpp_int;\nusing generics::digits;\n\nnamespace problems {\n    vector<uint32_t> problem48::solve(uint32_t ub) {\n        cpp_int sum = 1;\n\n        for (uint32_t i = 2; i <= ub; i++)\n            sum += pow((cpp_int) i, i);\n\n        vector<uint32_t> result = digits<uint64_t>((uint64_t) (sum % 10000000000));\n        result.insert(result.begin(), 10 - result.size(), 0);\n        return result;\n    }\n}", "meta": {"hexsha": "0696f256bd828e6697f7be055b02c4139008efac", "size": 583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/problems/1-50/48/problem48.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "src/problems/1-50/48/problem48.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/1-50/48/problem48.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2916666667, "max_line_length": 83, "alphanum_fraction": 0.6295025729, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5825778411892935}}
{"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": "#ifdef MEX\n\n#include <igl/avg_edge_length.h>\n#include <igl/edges.h>\n#include <igl/copyleft/cgal/wire_mesh.h>\n#include <igl/matlab/validate_arg.h>\n#include <igl/matlab/MexStream.h>\n#include <igl/matlab/mexErrMsgTxt.h>\n#include <igl/matlab/prepare_lhs.h>\n#include <igl/matlab/parse_rhs.h>\n#include <igl/C_STR.h>\n\n#include <mex.h>\n#include <Eigen/Dense>\n#include <iostream>\n\n#include <cstring>\n\nvoid parse_rhs(\n  const int nrhs, \n  const mxArray *prhs[], \n  Eigen::MatrixXd & WV,\n  Eigen::MatrixXi & WE,\n  double & th,\n  int & poly_size,\n  bool & solid)\n{\n  using namespace std;\n  using namespace igl;\n  using namespace igl::matlab;\n  using namespace Eigen;\n  mexErrMsgTxt(nrhs >= 2, \"The number of input arguments must be >=2.\");\n\n  const int dim = mxGetN(prhs[0]);\n  mexErrMsgTxt(dim == 3,\n    \"Mesh vertex list must be #V by 3 list of vertex positions\");\n\n  parse_rhs_double(prhs,WV);\n  parse_rhs_index(prhs+1,WE);\n  if(WE.cols()>2)\n  {\n    igl::edges(MatrixXi(WE),WE);\n  }\n\n  // defaults\n  // Thickness\n  th = 0.1*igl::avg_edge_length(WV,WE);\n  // Size of extrusion polygon\n  poly_size = 4;\n  solid = true;\n\n  {\n    int i = 2;\n    while(i<nrhs)\n    {\n      mexErrMsgTxt(mxIsChar(prhs[i]),\"Parameter names should be strings\");\n      // Cast to char\n      const char * name = mxArrayToString(prhs[i]);\n      if(strcmp(\"Thickness\",name) == 0)\n      {\n        validate_arg_double(i,nrhs,prhs,name);\n        validate_arg_scalar(i,nrhs,prhs,name);\n        th = (double)*mxGetPr(prhs[++i]);\n      }else if(strcmp(\"PolySize\",name) == 0)\n      {\n        validate_arg_double(i,nrhs,prhs,name);\n        validate_arg_scalar(i,nrhs,prhs,name);\n        poly_size = (int)*mxGetPr(prhs[++i]);\n      }else if(strcmp(\"Solid\",name) == 0)\n      {\n        validate_arg_logical(i,nrhs,prhs,name);\n        validate_arg_scalar(i,nrhs,prhs,name);\n        solid = (bool)*mxGetPr(prhs[++i]);\n      }else\n      {\n        mexErrMsgTxt(false,\"Unknown parameter\");\n      }\n      i++;\n    }\n  }\n}\n\nvoid mexFunction(\n  int nlhs, mxArray *plhs[], \n  int nrhs, const mxArray *prhs[])\n{\n  using namespace std;\n  using namespace Eigen;\n  using namespace igl;\n  using namespace igl::matlab;\n  using namespace igl::copyleft::cgal;\n\n  igl::matlab::MexStream mout;        \n  std::streambuf *outbuf = cout.rdbuf(&mout);\n  //mexPrintf(\"Compiled at %s on %s\\n\",__TIME__,__DATE__);\n\n  MatrixXd WV,V;\n  MatrixXi WE,F;\n  VectorXi J;\n  double th;\n  int poly_size;\n  bool solid;\n  parse_rhs(\n    nrhs,prhs,\n    WV,WE,\n    th,poly_size,solid);\n  wire_mesh(WV,WE,th,poly_size,solid,V,F,J);\n  switch(nlhs)\n  {\n    default:\n    {\n      mexErrMsgTxt(false,\"Too many output parameters.\");\n    }\n    case 3:\n    {\n      prepare_lhs_index(J,plhs+2);\n      // Fall through\n    }\n    case 2:\n    {\n      prepare_lhs_index(F,plhs+1);\n      // Fall through\n    }\n    case 1:\n    {\n      prepare_lhs_double(V,plhs+0);\n      // Fall through\n    }\n    case 0: break;\n  }\n\n  // Restore the std stream buffer Important!\n  std::cout.rdbuf(outbuf);\n}\n\n#endif\n\n\n", "meta": {"hexsha": "82f8b30d79d0e5dc1364d03d84cf7b133a75777f", "size": 2994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry_Processing_Toolbox/src/cppmex/wire_mesh.cpp", "max_stars_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_stars_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_stars_repo_licenses": ["MIT"], "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_Processing_Toolbox/src/cppmex/wire_mesh.cpp", "max_issues_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_issues_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Geometry_Processing_Toolbox/src/cppmex/wire_mesh.cpp", "max_forks_repo_name": "sidgairo18/SCILAB_MEX_TOOLBOX", "max_forks_repo_head_hexsha": "fc679f6d226c03b992b632823a5e57abea05cefa", "max_forks_repo_licenses": ["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.5395683453, "max_line_length": 74, "alphanum_fraction": 0.621242485, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5824055924883906}}
{"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:       Francois Godi\n *\n *    Copyright (C) 2015 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"bottleneck distance\"\n#include <boost/test/unit_test.hpp>\n\n#include <random>\n#include <gudhi/Bottleneck.h>\n#include <gudhi/Unitary_tests_utils.h>\n\nusing namespace Gudhi::persistence_diagram;\n\nint n1 = 81;  // a natural number >0\nint n2 = 180;  // a natural number >0\ndouble upper_bound = 406.43;  // any real >0\n\n\nstd::uniform_real_distribution<double> unif(0., upper_bound);\nstd::default_random_engine re;\nstd::vector< std::pair<double, double> > v1, v2;\n\nBOOST_AUTO_TEST_CASE(persistence_graph) {\n  // Random construction\n  for (int i = 0; i < n1; i++) {\n    double a = unif(re);\n    double b = unif(re);\n    v1.emplace_back(std::min(a, b), std::max(a, b));\n  }\n  for (int i = 0; i < n2; i++) {\n    double a = unif(re);\n    double b = unif(re);\n    v2.emplace_back(std::min(a, b), std::max(a, b));\n  }\n  Persistence_graph g(v1, v2, 0.);\n  std::vector<double> d(g.sorted_distances());\n  //\n  BOOST_CHECK(!g.on_the_u_diagonal(n1 - 1));\n  BOOST_CHECK(!g.on_the_u_diagonal(n1));\n  BOOST_CHECK(!g.on_the_u_diagonal(n2 - 1));\n  BOOST_CHECK(g.on_the_u_diagonal(n2));\n  BOOST_CHECK(!g.on_the_v_diagonal(n1 - 1));\n  BOOST_CHECK(g.on_the_v_diagonal(n1));\n  BOOST_CHECK(g.on_the_v_diagonal(n2 - 1));\n  BOOST_CHECK(g.on_the_v_diagonal(n2));\n  //\n  BOOST_CHECK(g.corresponding_point_in_u(0) == n2);\n  BOOST_CHECK(g.corresponding_point_in_u(n1) == 0);\n  BOOST_CHECK(g.corresponding_point_in_v(0) == n1);\n  BOOST_CHECK(g.corresponding_point_in_v(n2) == 0);\n  //\n  BOOST_CHECK(g.size() == (n1 + n2));\n  //\n  BOOST_CHECK((int) d.size() == (n1 + n2)*(n1 + n2) + n1 + n2 + 1);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance(0, 0))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance(0, n1 - 1))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance(0, n1))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance(0, n2 - 1))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance(0, n2))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance(0, (n1 + n2) - 1))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance(n1, 0))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance(n1, n1 - 1))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance(n1, n1))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance(n1, n2 - 1))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance(n1, n2))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance(n1, (n1 + n2) - 1))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance((n1 + n2) - 1, 0))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance((n1 + n2) - 1, n1 - 1))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance((n1 + n2) - 1, n1))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance((n1 + n2) - 1, n2 - 1))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance((n1 + n2) - 1, n2))) > 0);\n  BOOST_CHECK(std::count(d.begin(), d.end(), GUDHI_PROTECT_FLOAT(g.distance((n1 + n2) - 1, (n1 + n2) - 1))) > 0);\n}\n\nBOOST_AUTO_TEST_CASE(neighbors_finder) {\n  Persistence_graph g(v1, v2, 0.);\n  Neighbors_finder nf(g, 1.);\n  for (int v_point_index = 1; v_point_index < ((n2 + n1)*9 / 10); v_point_index += 2)\n    nf.add(v_point_index);\n  //\n  int v_point_index_1 = nf.pull_near(n2 / 2);\n  BOOST_CHECK((v_point_index_1 == -1) || (g.distance(n2 / 2, v_point_index_1) <= 1.));\n  std::vector<int> l = nf.pull_all_near(n2 / 2);\n  bool v = true;\n  for (auto it = l.cbegin(); it != l.cend(); ++it)\n    v = v && (g.distance(n2 / 2, *it) > 1.);\n  BOOST_CHECK(v);\n  int v_point_index_2 = nf.pull_near(n2 / 2);\n  BOOST_CHECK(v_point_index_2 == -1);\n}\n\nBOOST_AUTO_TEST_CASE(layered_neighbors_finder) {\n  Persistence_graph g(v1, v2, 0.);\n  Layered_neighbors_finder lnf(g, 1.);\n  for (int v_point_index = 1; v_point_index < ((n2 + n1)*9 / 10); v_point_index += 2)\n    lnf.add(v_point_index, v_point_index % 7);\n  //\n  int v_point_index_1 = lnf.pull_near(n2 / 2, 6);\n  BOOST_CHECK((v_point_index_1 == -1) || (g.distance(n2 / 2, v_point_index_1) <= 1.));\n  int v_point_index_2 = lnf.pull_near(n2 / 2, 6);\n  BOOST_CHECK(v_point_index_2 == -1);\n  v_point_index_1 = lnf.pull_near(n2 / 2, 0);\n  BOOST_CHECK((v_point_index_1 == -1) || (g.distance(n2 / 2, v_point_index_1) <= 1.));\n  v_point_index_2 = lnf.pull_near(n2 / 2, 0);\n  BOOST_CHECK(v_point_index_2 == -1);\n}\n\nBOOST_AUTO_TEST_CASE(graph_matching) {\n  Persistence_graph g(v1, v2, 0.);\n  Graph_matching m1(g);\n  m1.set_r(0.);\n  int e = 0;\n  while (m1.multi_augment())\n    ++e;\n  BOOST_CHECK(e > 0);\n  BOOST_CHECK(e <= 2 * sqrt(2 * (n1 + n2)));\n  Graph_matching m2 = m1;\n  BOOST_CHECK(!m2.multi_augment());\n  m2.set_r(upper_bound);\n  e = 0;\n  while (m2.multi_augment())\n    ++e;\n  BOOST_CHECK(e <= 2 * sqrt(2 * (n1 + n2)));\n  BOOST_CHECK(m2.perfect());\n  BOOST_CHECK(!m1.perfect());\n}\n\nBOOST_AUTO_TEST_CASE(global) {\n  std::uniform_real_distribution<double> unif1(0., upper_bound);\n  std::uniform_real_distribution<double> unif2(upper_bound / 10000., upper_bound / 100.);\n  std::default_random_engine re;\n  std::vector< std::pair<double, double> > v1, v2;\n  for (int i = 0; i < n1; i++) {\n    double a = unif1(re);\n    double b = unif1(re);\n    double x = unif2(re);\n    double y = unif2(re);\n    v1.emplace_back(std::min(a, b), std::max(a, b));\n    v2.emplace_back(std::min(a, b) + std::min(x, y), std::max(a, b) + std::max(x, y));\n    if (i % 5 == 0)\n      v1.emplace_back(std::min(a, b), std::min(a, b) + x);\n    if (i % 3 == 0)\n      v2.emplace_back(std::max(a, b), std::max(a, b) + y);\n  }\n  BOOST_CHECK(bottleneck_distance(v1, v2, 0.) <= upper_bound / 100.);\n  BOOST_CHECK(bottleneck_distance(v1, v2, upper_bound / 10000.) <= upper_bound / 100. + upper_bound / 10000.);\n  BOOST_CHECK(std::abs(bottleneck_distance(v1, v2, 0.) - bottleneck_distance(v1, v2, upper_bound / 10000.)) <= upper_bound / 10000.);\n\n  std::vector< std::pair<double, double> > empty;\n  std::vector< std::pair<double, double> > one = {{8, 10}};\n  BOOST_CHECK(bottleneck_distance(empty, empty) == 0);\n  BOOST_CHECK(bottleneck_distance(empty, one) == 1);\n}\n", "meta": {"hexsha": "44141baa1f7a29d98a77c010c6089f4802ce195f", "size": 6787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Bottleneck_distance/test/bottleneck_unit_test.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Bottleneck_distance/test/bottleneck_unit_test.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Bottleneck_distance/test/bottleneck_unit_test.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 41.8950617284, "max_line_length": 133, "alphanum_fraction": 0.6494769412, "num_tokens": 2328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5823544448503548}}
{"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": "// unit test file acosh.hpp for the special functions test suite\n\n//  (C) Copyright Hubert Holin 2003.\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 <functional>\n#include <iomanip>\n#include <iostream>\n\n\n#include <boost/math/special_functions/acosh.hpp>\n\n\n#include <boost/test/unit_test.hpp>\n\n\ntemplate<typename T>\nT    acosh_error_evaluator(T x)\n{\n    using    ::std::abs;\n    using    ::std::sinh;\n    using    ::std::cosh;\n        \n    using    ::std::numeric_limits;\n    \n    using    ::boost::math::acosh;\n    \n    \n    static T const    epsilon = numeric_limits<float>::epsilon();\n    \n    T                y = cosh(x);\n    T                z = acosh(y);\n    \n    T                absolute_error = abs(z-abs(x));\n    T                relative_error = absolute_error*abs(sinh(x));\n    T                scaled_error = relative_error/epsilon;\n    \n    return(scaled_error);\n}\n\n\nBOOST_TEST_CASE_TEMPLATE_FUNCTION(acosh_test, T)\n{\n    BOOST_MESSAGE(\"Testing acosh in the real domain for \"\n        << string_type_name<T>::_() << \".\");\n    \n    for    (int i = 0; i <= 100; i++)\n    {\n        T    x = static_cast<T>(i-50)/static_cast<T>(5);\n        \n        BOOST_CHECK_PREDICATE(::std::less_equal<T>(),\n            (acosh_error_evaluator(x))\n            (static_cast<T>(4)));\n    }\n}\n\n\nvoid    acosh_manual_check()\n{\n    BOOST_MESSAGE(\" \");\n    BOOST_MESSAGE(\"acosh\");\n    \n    for    (int i = 0; i <= 100; i++)\n    {\n        float        xf = static_cast<float>(i-50)/static_cast<float>(5);\n        double       xd = static_cast<double>(i-50)/static_cast<double>(5);\n        long double  xl = \n                static_cast<long double>(i-50)/static_cast<long double>(5);\n        \n        BOOST_MESSAGE(  ::std::setw(15)\n                     << acosh_error_evaluator(xf)\n                     << ::std::setw(15)\n                     << acosh_error_evaluator(xd)\n                     << ::std::setw(15)\n                     << acosh_error_evaluator(xl));\n    }\n    \n    BOOST_MESSAGE(\" \");\n}\n\n", "meta": {"hexsha": "162f2809a3000927a087f6e4bcf192c8c603edeb", "size": 2114, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/math/special_functions/acosh_test.hpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T13:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T02:55:10.000Z", "max_issues_repo_path": "libs/math/special_functions/acosh_test.hpp", "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/special_functions/acosh_test.hpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T14:34:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T08:25:58.000Z", "avg_line_length": 25.1666666667, "max_line_length": 75, "alphanum_fraction": 0.5444654683, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5823544226494471}}
{"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// monomials_horner::policy::multi_factorial.hpp                            //\n//                                                                          //\n//  (C) Copyright 2009 Erwann Rogard                                        //\n//  Use, modification and distribution are subject to the                   //\n//  Boost Software License, Version 1.0. (See accompanying file             //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)        //\n//////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_MONOMIALS_HORNER_POLICY_MULTI_FACTORIAL_HPP_ER_2009\n#define BOOST_MONOMIALS_HORNER_POLICY_MULTI_FACTORIAL_HPP_ER_2009\n#include <boost/math/special_functions/factorials.hpp>\n\nnamespace boost{\nnamespace monomials_horner{\n\n    // (a,b,c) --> a! b! c!\n    struct multi_factorial{\n        typedef unsigned                      result_type;\n        typedef unsigned                      first_argument_type;\n        typedef unsigned                      second_argument_type;\n        multi_factorial(){}\n        result_type operator()(\n            first_argument_type a1,\n            second_argument_type a2\n        )const{\n            return a1 * static_cast<result_type>(math::factorial<double>(a2));\n        }\n        static result_type initial_value;\n    };\n    multi_factorial::result_type multi_factorial:: initial_value\n        = static_cast<result_type>(1);\n\n}// monomials_horner\n}// boost\n\n#endif", "meta": {"hexsha": "5644937247997f21cac20c03ed9f2792a1ff17c9", "size": 1545, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "monomials_horner/boost/monomials_horner/policy/multi_factorial.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "monomials_horner/boost/monomials_horner/policy/multi_factorial.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "monomials_horner/boost/monomials_horner/policy/multi_factorial.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9166666667, "max_line_length": 78, "alphanum_fraction": 0.5236245955, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5823253390642057}}
{"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": "/**\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  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  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  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  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  return zeta;\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace LFPPDofHandling\n", "meta": {"hexsha": "6f1737a82c894578f8dbaae25297bd0504d87111", "size": 3357, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/LFPPDofHandling/templates/lfppdofhandling.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/LFPPDofHandling/templates/lfppdofhandling.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/LFPPDofHandling/templates/lfppdofhandling.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 30.5181818182, "max_line_length": 79, "alphanum_fraction": 0.6273458445, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.5823028597061243}}
{"text": "#ifndef DART_REALTIME_OBS_LOG\n#define DART_REALTIME_OBS_LOG\n\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"dart/math/MathTypes.hpp\"\nnamespace dart {\nnamespace realtime {\n\nstruct Observation\n{\n  long time;\n  Eigen::VectorXs pos;\n  Eigen::VectorXs vel;\n\n  Observation(long time, Eigen::VectorXs pos, Eigen::VectorXs vel);\n};\n\nclass ObservationLog\n{\npublic:\n  ObservationLog(\n      long startTime,\n      Eigen::VectorXs initialPos,\n      Eigen::VectorXs initialVel,\n      Eigen::VectorXs initialMass);\n\n  void observe(\n      long time,\n      Eigen::VectorXs pos,\n      Eigen::VectorXs vel,\n      Eigen::VectorXs mass);\n\n  Observation getClosestObservationBefore(long time);\n\n  Eigen::VectorXs getMass();\n\n  void discardBefore(long time);\n\nprotected:\n  int mDofs;\n  int mMassDim;\n  std::vector<Observation> mObservations;\n  Eigen::VectorXs mMass;\n};\n\n} // namespace realtime\n} // namespace dart\n\n#endif", "meta": {"hexsha": "80d8ce781f84479c8abf375ade1f0e2fb0ae2c9d", "size": 905, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/realtime/ObservationLog.hpp", "max_stars_repo_name": "jyf588/nimblephysics", "max_stars_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T06:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T09:59:09.000Z", "max_issues_repo_path": "dart/realtime/ObservationLog.hpp", "max_issues_repo_name": "jyf588/nimblephysics", "max_issues_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dart/realtime/ObservationLog.hpp", "max_forks_repo_name": "jyf588/nimblephysics", "max_forks_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T13:56:14.000Z", "avg_line_length": 17.4038461538, "max_line_length": 67, "alphanum_fraction": 0.7116022099, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.5823028562951124}}
{"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": "/// @file\n/// Tests that rotation conversion functions are inverses.\n\n#include <cmath>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n#include \"drake/math/cross_product.h\"\n#include \"drake/math/normalize_vector.h\"\n#include \"drake/math/quaternion.h\"\n#include \"drake/math/rotation_matrix.h\"\n\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::Quaterniond;\nusing Eigen::Vector3d;\nusing Eigen::Vector4d;\nusing Eigen::AngleAxis;\nusing Eigen::AngleAxisd;\nusing Eigen::Quaternion;\nusing Eigen::Quaterniond;\nusing std::sin;\nusing std::cos;\nusing std::numeric_limits;\n\nnamespace drake {\nnamespace math {\nnamespace {\n\n// kSweepSize is an even number, so that no samples are taken at zero. This\n// test scales as O(N^4) in sweep size, so be cautious about turning it up!\nconst int kSweepSize = 6;\n\nconst double kEpsilon = numeric_limits<double>::epsilon();\nconst double kTolerance = 1.0E-12;\n\nGTEST_TEST(EigenEulerAngleTest, MakeXYZRotation) {\n  // Verify MakeXRotation(theta), MakeYRotation(theta), MakeZRotation(theta) is\n  // the same as AngleAxis equivalents.\n  const double theta = 0.1234567;  // Arbitrary angle.\n  const RotationMatrixd Rx(RotationMatrixd::MakeXRotation(theta));\n  const RotationMatrixd Ry(RotationMatrixd::MakeYRotation(theta));\n  const RotationMatrixd Rz(RotationMatrixd::MakeZRotation(theta));\n  const Quaterniond qx(Eigen::AngleAxisd(theta, Vector3d::UnitX()));\n  const Quaterniond qy(Eigen::AngleAxisd(theta, Vector3d::UnitY()));\n  const Quaterniond qz(Eigen::AngleAxisd(theta, Vector3d::UnitZ()));\n  const double tolerance = 32 * kEpsilon;\n  EXPECT_TRUE(Rx.IsNearlyEqualTo(RotationMatrixd(qx), tolerance));\n  EXPECT_TRUE(Ry.IsNearlyEqualTo(RotationMatrixd(qy), tolerance));\n  EXPECT_TRUE(Rz.IsNearlyEqualTo(RotationMatrixd(qz), tolerance));\n}\n\nGTEST_TEST(EigenEulerAngleTest, BodyXYZ) {\n  // Verify ea = Eigen::eulerAngles(0, 1, 2) returns Euler angles about\n  // Body-fixed x-y'-z'' axes by [ea(0), ea(1), ea(2)].\n  const Vector3d input_angles(0.5, 0.4, 0.3);\n  const Matrix3d bodyXYZ_rotmat =\n      (RotationMatrix<double>::MakeXRotation(input_angles(0)) *\n       RotationMatrix<double>::MakeYRotation(input_angles(1)) *\n       RotationMatrix<double>::MakeZRotation(input_angles(2))).matrix();\n  const Vector3d output_angles = bodyXYZ_rotmat.eulerAngles(0, 1, 2);\n  // input_angles.isApprox(output_angles) is a valid test (rathan than\n  // comparing the converted quaternions) since all the angles are between\n  // 0 and PI/2.\n  EXPECT_TRUE(input_angles.isApprox(output_angles));\n}\n\nGTEST_TEST(EigenEulerAngleTest, SpaceXYZ) {\n  // Verify ea = Eigen::eulerAngles(2, 1, 0) returns Euler angles about\n  // Body-fixed z-y'-x'' axes by [ea(0), ea(1), ea(2)].\n  const Vector3d input_angles(0.5, 0.4, 0.3);\n  const Matrix3d spaceXYZ_rotmat =\n      (RotationMatrix<double>::MakeZRotation(input_angles(0)) *\n       RotationMatrix<double>::MakeYRotation(input_angles(1)) *\n       RotationMatrix<double>::MakeXRotation(input_angles(2))).matrix();\n  const Vector3d output_angles = spaceXYZ_rotmat.eulerAngles(2, 1, 0);\n  // input_angles.isApprox(output_angles) is a valid test (rathan than\n  // comparing the converted quaternions) since all the angles are between\n  // 0 and PI/2.\n  EXPECT_TRUE(input_angles.isApprox(output_angles));\n}\n\nGTEST_TEST(EigenEulerAngleTest, BodyZYZ) {\n  // Verify ea = Eigen::eulerAngles(2, 1, 0) returns Euler angles about\n  // Body-fixed z-y'-z'' axes by [ea(0), ea(1), ea(2)].\n  const Vector3d input_angles(0.5, 0.4, 0.3);\n  const Matrix3d bodyZYZ_angles =\n      (RotationMatrix<double>::MakeZRotation(input_angles(0)) *\n       RotationMatrix<double>::MakeYRotation(input_angles(1)) *\n       RotationMatrix<double>::MakeZRotation(input_angles(2))).matrix();\n  const Vector3d output_angles = bodyZYZ_angles.eulerAngles(2, 1, 2);\n  // input_angles.isApprox(output_angles) is a valid test (rathan than\n  // comparing the converted quaternions) since all the angles are between\n  // 0 and PI/2.\n  EXPECT_TRUE(input_angles.isApprox(output_angles));\n}\n\nclass RotationConversionTest : public ::testing::Test {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n protected:\n  void SetUp() override {\n    SetupRPYTestCases();\n    SetupAngleAxisTestCases();\n    SetupQuaternionTestCases();\n    SetupRotationMatrixTestCases();\n  }\n\n  void SetupRPYTestCases() {\n    // Set up a variety of specific tests for angles that may cause numerical\n    // problems as well as a sweep of values to test general functionality.\n    // Singularity issue associated with the second angle = pi/2\n    // in Euler Body-fixed z-y'-x'' rotation sequence.\n    // Singularity issue associated with the second angle = -pi/2\n    // in Euler Body-fixed z-y'-x'' rotation sequence.\n    // Singularity issue associated with the second angle close to pi/2\n    // in Euler Body-fixed z-y'-x'' rotation sequence.\n    // Singularity issue associated with the second angle close to -pi/2\n    // in Euler Body-fixed z-y'-x'' rotation sequence.\n\n    // pitch = pi/2\n    const RollPitchYaw<double> pitch_half_pi(M_PI / 4, M_PI / 2, M_PI / 3);\n    rpy_test_cases_.push_back(pitch_half_pi);\n\n    // pitch = -pi/2\n    const RollPitchYaw<double> pitch_neg_half_pi(M_PI / 4, -M_PI / 2, M_PI / 3);\n    rpy_test_cases_.push_back(pitch_neg_half_pi);\n\n    // pitch = 0.5*pi-eps\n    const RollPitchYaw<double> pitch_near_half_piA(\n        M_PI / 4, 0.5 * M_PI - kEpsilon, M_PI / 3);\n    rpy_test_cases_.push_back(pitch_near_half_piA);\n\n    // pitch = 0.5*pi-1.5*eps\n    const RollPitchYaw<double> pitch_near_half_piB(\n        M_PI / 4, 0.5 * M_PI - 1.5 * kEpsilon, M_PI / 3);\n    rpy_test_cases_.push_back(pitch_near_half_piB);\n\n    // pitch = 0.5*pi-2*eps\n    const RollPitchYaw<double> pitch_near_half_piC(\n        M_PI / 4, 0.5 * M_PI - 2 * kEpsilon, M_PI / 3);\n    rpy_test_cases_.push_back(pitch_near_half_piC);\n\n    // pitch = 0.5*pi - 1E-15\n    const RollPitchYaw<double> pitch_near_half_piD(\n        M_PI * 0.8, 0.5 * M_PI - 1E-15, 0.9 * M_PI);\n    rpy_test_cases_.push_back(pitch_near_half_piD);\n\n    // pitch = -0.5*pi+eps\n    const RollPitchYaw<double> pitch_near_neg_half_piA(\n        M_PI * -0.9, -0.5 * M_PI + kEpsilon, M_PI * 0.3);\n    rpy_test_cases_.push_back(pitch_near_neg_half_piA);\n\n    // pitch = -0.5*pi+1.5*eps\n    const RollPitchYaw<double> pitch_near_neg_half_piB(\n        M_PI * -0.6, -0.5 * M_PI + 1.5 * kEpsilon, M_PI * 0.3);\n    rpy_test_cases_.push_back(pitch_near_neg_half_piB);\n\n    // pitch = -0.5*pi+2*eps\n    const RollPitchYaw<double> pitch_near_neg_half_piC(\n        M_PI * -0.5, -0.5 * M_PI + 2 * kEpsilon, M_PI * 0.4);\n    rpy_test_cases_.push_back(pitch_near_neg_half_piC);\n\n    // pitch = -0.5*pi + 1E-15\n    const RollPitchYaw<double> pitch_near_neg_half_piD(\n        M_PI * 0.9, -0.5 * M_PI + 1E-15, 0.8 * M_PI);\n    rpy_test_cases_.push_back(pitch_near_neg_half_piD);\n\n    // non-singular cases\n    auto roll = Eigen::VectorXd::LinSpaced(Eigen::Sequential, kSweepSize,\n                                           -0.99 * M_PI, M_PI);\n    auto pitch = Eigen::VectorXd::LinSpaced(Eigen::Sequential, kSweepSize,\n                                            -0.49 * M_PI, 0.49 * M_PI);\n    auto yaw = Eigen::VectorXd::LinSpaced(Eigen::Sequential, kSweepSize,\n                                          -0.99 * M_PI, M_PI);\n    for (int i = 0; i < roll.size(); ++i) {\n      for (int j = 0; j < pitch.size(); ++j) {\n        for (int k = 0; k < yaw.size(); ++k) {\n          const RollPitchYaw<double> rpy(roll(i), pitch(j), yaw(k));\n          rpy_test_cases_.push_back(rpy);\n        }\n      }\n    }\n  }\n\n  void addAngleAxisTestCase(double angle, const Vector3d& axis) {\n    angle_axis_test_cases_.push_back(AngleAxisd(angle, axis));\n  }\n\n  void SetupAngleAxisTestCases() {\n    // Set up a variety of specific tests for angles/axes that may cause\n    // numerical problems as well as a sweep of values to test general\n    // functionality.\n    // Degenerate case, 0 rotation around x axis\n    // Degenerate case, 0 rotation around y axis\n    // Degenerate case, 0 rotation around z axis\n    // Degenerate case, 0 rotation around a unit axis\n    // Almost degenerate case, small positive rotation around an arbitrary axis\n    // Almost degenerate case, small negative rotation around an arbitrary axis\n    // Differentiation issue at 180 rotation around x axis\n    // Differentiation issue at 180 rotation around y axis\n    // Differentiation issue at 180 rotation around z axis\n    // Differentiation issue at 180 rotation around an arbitrary unit axis\n    // Differentiation issue close to 180 rotation around an arbitrary axis\n\n    // 0 rotation around x axis\n    addAngleAxisTestCase(0, Vector3d::UnitX());\n\n    // 0 rotation around y axis\n    addAngleAxisTestCase(0, Vector3d::UnitY());\n\n    // 0 rotation around z axis\n    addAngleAxisTestCase(0, Vector3d::UnitZ());\n\n    // 0 rotation around an arbitrary axis\n    Vector3d axis(0.5 * sqrt(2), 0.4 * sqrt(2), 0.3 * sqrt(2));\n    addAngleAxisTestCase(0, axis);\n\n    // epsilon rotation around an arbitrary axis\n    addAngleAxisTestCase(kEpsilon, axis);\n\n    // 1E-10 rotation around an arbitrary axis\n    addAngleAxisTestCase(1E-10, axis);\n\n    // -epsilon rotation around an arbitrary axis\n    addAngleAxisTestCase(-kEpsilon, axis);\n\n    // -1E-10 rotation around an arbitrary axis\n    addAngleAxisTestCase(-1E-10, axis);\n\n    // 180 rotation around x axis\n    addAngleAxisTestCase(M_PI, Vector3d::UnitX());\n\n    // 180 rotation around y axis\n    addAngleAxisTestCase(M_PI, Vector3d::UnitY());\n\n    // 180 rotation around z axis\n    addAngleAxisTestCase(M_PI, Vector3d::UnitZ());\n\n    // -180 rotation around x axis\n    addAngleAxisTestCase(-M_PI, Vector3d::UnitX());\n\n    // -180 rotation around y axis\n    addAngleAxisTestCase(-M_PI, Vector3d::UnitY());\n\n    // -180 rotation around z axis\n    addAngleAxisTestCase(-M_PI, Vector3d::UnitZ());\n\n    // 180 rotation around an arbitrary axis\n    addAngleAxisTestCase(M_PI, axis);\n\n    // -180 rotation around an arbitrary axis\n    addAngleAxisTestCase(-M_PI, axis);\n\n    // (1-epsilon)*pi rotation around an arbitrary axis\n    addAngleAxisTestCase((1 - kEpsilon) * M_PI, axis);\n\n    // (-1+epsilon)*pi rotation around an arbitrary axis\n    addAngleAxisTestCase((-1 + kEpsilon) * M_PI, axis);\n\n    // (1-2*epsilon)*pi rotation around an arbitrary axis\n    addAngleAxisTestCase((1 - 2 * kEpsilon) * M_PI, axis);\n\n    // (-1+2*epsilon)*pi rotation around an arbitrary axis\n    addAngleAxisTestCase((-1 + 2 * kEpsilon) * M_PI, axis);\n\n    // (1-1E-10)*pi rotation around an arbitrary axis\n    addAngleAxisTestCase((1 - 1E-10) * M_PI, axis);\n\n    // (-1+1E-10)*pi rotation around an arbitrary axis\n    addAngleAxisTestCase((-1 + 1E-10) * M_PI, axis);\n\n    // non-singularity cases\n    auto a_x = Eigen::VectorXd::LinSpaced(Eigen::Sequential, kSweepSize, -1, 1);\n    auto a_y = Eigen::VectorXd::LinSpaced(Eigen::Sequential, kSweepSize, -1, 1);\n    auto a_z = Eigen::VectorXd::LinSpaced(Eigen::Sequential, kSweepSize, -1, 1);\n    auto a_angle = Eigen::VectorXd::LinSpaced(Eigen::Sequential, kSweepSize,\n                                              -0.95 * M_PI, 0.95 * M_PI);\n    for (int i = 0; i < a_x.size(); ++i) {\n      for (int j = 0; j < a_y.size(); ++j) {\n        for (int k = 0; k < a_z.size(); ++k) {\n          Vector3d axis_ijk(a_x(i), a_y(j), a_z(k));\n          if (axis_ijk.norm() > 1E-3) {\n            axis_ijk.normalize();\n            for (int l = 0; l < a_angle.size(); ++l) {\n              addAngleAxisTestCase(a_angle(l), axis_ijk);\n            }\n          }\n        }\n      }\n    }\n  }\n\n  void SetupQuaternionTestCases() {\n    // Set up a variety of general tests for quaternions.\n    auto qw = Eigen::VectorXd::LinSpaced(Eigen::Sequential, kSweepSize, -1, 1);\n    auto qx = Eigen::VectorXd::LinSpaced(Eigen::Sequential, kSweepSize, -1, 1);\n    auto qy = Eigen::VectorXd::LinSpaced(Eigen::Sequential, kSweepSize, -1, 1);\n    auto qz = Eigen::VectorXd::LinSpaced(Eigen::Sequential, kSweepSize, -1, 1);\n    for (int i = 0; i < qw.size(); ++i) {\n      for (int j = 0; j < qx.size(); ++j) {\n        for (int k = 0; k < qy.size(); ++k) {\n          for (int l = 0; l < qz.size(); ++l) {\n            Vector4d q(qw(i), qx(j), qy(k), qz(l));\n            if (q.norm() > 1E-3) {\n              q.normalize();\n              quaternion_test_cases_.push_back(\n                  Quaterniond(q(0), q(1), q(2), q(3)));\n            }\n          }\n        }\n      }\n    }\n  }\n\n  void SetupRotationMatrixTestCases() {\n    for (const RollPitchYaw<double>& rpyi : rpy_test_cases_) {\n      const RotationMatrix<double> Ri(rpyi);\n      rotation_matrix_test_cases_.push_back(Ri);\n    }\n    for (const Eigen::AngleAxisd& ai : angle_axis_test_cases_) {\n      const RotationMatrix<double> Ri(ai);\n      rotation_matrix_test_cases_.push_back(Ri);\n    }\n    for (const Quaterniond& qi : quaternion_test_cases_) {\n      const RotationMatrix<double> Ri(qi);\n      rotation_matrix_test_cases_.push_back(Ri);\n    }\n  }\n  std::vector<RollPitchYaw<double>> rpy_test_cases_;\n  std::vector<AngleAxisd> angle_axis_test_cases_;\n  std::vector<Quaterniond> quaternion_test_cases_;\n  std::vector<RotationMatrix<double>> rotation_matrix_test_cases_;\n};\n\nTEST_F(RotationConversionTest, quaternionToRotationMatrixTest) {\n  for (const Quaterniond& qi : quaternion_test_cases_) {\n    // Compute the rotation matrix using Eigen geometry module, compare the\n    // result with RotationMatrix(quaternion).\n    const Matrix3d rotmat_expected = qi.toRotationMatrix();\n    const Matrix3d rotmat = RotationMatrix<double>(qi).matrix();\n    EXPECT_TRUE(CompareMatrices(rotmat_expected, rotmat, 1E-10,\n                                MatrixCompareType::absolute));\n    // RotationMatrix(quaternion) is inverse of RotationMatrix::ToQuaternion().\n    const Eigen::Quaterniond quat_expected =\n        RotationMatrix<double>::ToQuaternion(rotmat);\n    EXPECT_TRUE(\n        AreQuaternionsEqualForOrientation(qi, quat_expected, kTolerance));\n  }\n}\n\nTEST_F(RotationConversionTest, QuatRPY) {\n  for (const Quaterniond& qi : quaternion_test_cases_) {\n    const RollPitchYaw<double> rpy(qi);\n    const Eigen::Quaterniond q_expected = rpy.ToQuaternion();\n    // Test RollPitchYaw::ToQuaternion() is inverse of RollPitchYaw(quaternion).\n    EXPECT_TRUE(AreQuaternionsEqualForOrientation(qi, q_expected, kTolerance));\n    EXPECT_TRUE(rpy.IsRollPitchYawInCanonicalRange());\n  }\n}\n\nTEST_F(RotationConversionTest, RotmatQuat) {\n  // Compare Eigen's rotation matrix to quaternion result with the result from\n  // RotationMatrix::ToQuaternion().\n  for (const RotationMatrix<double>& Ri : rotation_matrix_test_cases_) {\n    const Eigen::Quaterniond quat_drake = Ri.ToQuaternion();\n    const Eigen::Quaterniond quat_eigen = Quaterniond(Ri.matrix());\n    EXPECT_TRUE(\n        AreQuaternionsEqualForOrientation(quat_drake, quat_eigen, kTolerance));\n    // Ensure the calculated quaternion produces the same rotation matrix.\n    // This test accuracy to near machine precision and uses a tolerance of\n    // 32 * kEpsilon (allows for 5 of the 53 mantissa bits to be inaccurate).\n    // This 5-bit estimate seems to be a reasonably tight bound which\n    // nevertheless passes a representative sampling of compilers and platforms.\n    const RotationMatrix<double> rotmat(quat_drake);\n    EXPECT_TRUE(Ri.IsNearlyEqualTo(rotmat, 32 * kEpsilon));\n  }\n}\n\nTEST_F(RotationConversionTest, rotmat2rpyTest) {\n  for (const RotationMatrix<double>& Ri : rotation_matrix_test_cases_) {\n    const RollPitchYaw<double> rpy(Ri);\n    const RotationMatrix<double> rotmat_expected(rpy);\n    // RollPitchYaw(RotationMatrix) is inverse of RotationMatrix(RollPitchYaw).\n    EXPECT_TRUE(Ri.IsNearlyEqualTo(rotmat_expected, 256 * kEpsilon));\n    EXPECT_TRUE(rpy.IsRollPitchYawInCanonicalRange());\n  }\n}\n\nTEST_F(RotationConversionTest, rpy2rotmatTest) {\n  for (const RollPitchYaw<double>& rpyi : rpy_test_cases_) {\n    const double roll = rpyi.roll_angle();\n    const double pitch = rpyi.pitch_angle();\n    const double yaw = rpyi.yaw_angle();\n    const Quaterniond q = Eigen::AngleAxisd(yaw, Vector3d::UnitZ()) *\n                          Eigen::AngleAxisd(pitch, Vector3d::UnitY()) *\n                          Eigen::AngleAxisd(roll, Vector3d::UnitX());\n    const RotationMatrix<double> R_from_quaternion(q);\n\n    // Compute rotation matrix by rotz(rpy(2))*roty(rpy(1))*rotx(rpy(0)),\n    // then compare the result with RotationMatrix(RollPitchYaw).\n    const RotationMatrix<double> R_from_rpy(rpyi);\n    EXPECT_TRUE(\n        R_from_rpy.IsNearlyEqualTo(R_from_quaternion, 512 * kEpsilon));\n\n    // RollPitchYaw(RotationMatrix) is inverse of RotationMatrix(RollPitchYaw).\n    const RollPitchYaw<double> rpy_expected(R_from_rpy);\n    EXPECT_TRUE(rpyi.IsNearlySameOrientation(rpy_expected, kTolerance));\n  }\n}\n\nTEST_F(RotationConversionTest, rpy2QuatTest) {\n  for (const RollPitchYaw<double>& rpyi : rpy_test_cases_) {\n    const Eigen::Quaterniond q = rpyi.ToQuaternion();\n    // Verify rpyi.ToQuaternion() is inverse of RollPitchYaw(Quaternion).\n    const RollPitchYaw<double> rpy_expected(q);\n    EXPECT_TRUE(rpyi.IsNearlySameOrientation(rpy_expected, 512 * kEpsilon));\n  }\n}\n\n}  // namespace\n}  // namespace math\n}  // namespace drake\n\n", "meta": {"hexsha": "b03f5b0e22a310574a92928e113f035e1713102c", "size": 17247, "ext": "cc", "lang": "C++", "max_stars_repo_path": "math/test/rotation_conversion_test.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "math/test/rotation_conversion_test.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/test/rotation_conversion_test.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 40.2027972028, "max_line_length": 80, "alphanum_fraction": 0.6852785992, "num_tokens": 4825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5823028499634955}}
{"text": "// Copyright 2015-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/mean.hpp\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/** Calculates mean and variance of sample.\n\n  Uses Welford's incremental algorithm to improve the numerical\n  stability of mean and variance computation.\n*/\ntemplate <class ValueType>\nstruct mean {\n    using value_type      = ValueType;\n    using const_reference = const value_type&;\n\n    mean() = default;\n\n    mean(const value_type& n,\n         const value_type& mean,\n         const value_type& variance) noexcept\n        : count(n)\n        , value(mean)\n        , _sum_of_deltas_squared(variance * (n - 1)) {}\n\n    mean(const value_type& sum,\n         const value_type& mean,\n         const value_type& _sum_of_deltas_squared,\n         bool /* Tag to trigger python internal constructor */)\n        : count(sum)\n        , value(mean)\n        , _sum_of_deltas_squared(_sum_of_deltas_squared) {}\n\n    void operator()(const value_type& x) noexcept {\n        count += static_cast<value_type>(1);\n        const auto delta = x - value;\n        value += delta / count;\n        _sum_of_deltas_squared += delta * (x - value);\n    }\n\n    void operator()(const boost::histogram::weight_type<value_type>& w,\n                    const value_type& x) noexcept {\n        count += w.value;\n        const auto delta = x - value;\n        value += w.value * delta / count;\n        _sum_of_deltas_squared += w.value * delta * (x - value);\n    }\n\n    mean& operator+=(const mean& rhs) noexcept {\n        if(rhs.count == 0)\n            return *this;\n\n        const auto mu1 = value;\n        const auto mu2 = rhs.value;\n        const auto n1  = count;\n        const auto n2  = rhs.count;\n\n        count += rhs.count;\n        value = (n1 * mu1 + n2 * mu2) / count;\n        _sum_of_deltas_squared += rhs._sum_of_deltas_squared;\n        _sum_of_deltas_squared\n            += n1 * (value - mu1) * (value - mu1) + n2 * (value - mu2) * (value - mu2);\n\n        return *this;\n    }\n\n    mean& operator*=(const value_type& s) noexcept {\n        value *= s;\n        _sum_of_deltas_squared *= s * s;\n        return *this;\n    }\n\n    bool operator==(const mean& rhs) const noexcept {\n        return count == rhs.count && value == rhs.value\n               && _sum_of_deltas_squared == rhs._sum_of_deltas_squared;\n    }\n\n    bool operator!=(const mean& rhs) const noexcept { return !operator==(rhs); }\n\n    value_type variance() const noexcept {\n        return _sum_of_deltas_squared / (count - 1);\n    }\n\n    template <class Archive>\n    void serialize(Archive& ar, unsigned) {\n        ar& boost::make_nvp(\"count\", count);\n        ar& boost::make_nvp(\"value\", value);\n        ar& boost::make_nvp(\"_sum_of_deltas_squared\", _sum_of_deltas_squared);\n    }\n\n    value_type count{};\n    value_type value{};\n    value_type _sum_of_deltas_squared{};\n};\n\n} // namespace accumulators\n", "meta": {"hexsha": "ce496e1f83512fbd0c60acb35c1d8ff2400c8d95", "size": 3255, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bh_python/accumulators/mean.hpp", "max_stars_repo_name": "andrzejnovak/boost-histogram", "max_stars_repo_head_hexsha": "cdbfabb1c22f5545bf3900be01f2025411e699f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 105.0, "max_stars_repo_stars_event_min_datetime": "2019-03-08T14:59:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T12:46:17.000Z", "max_issues_repo_path": "include/bh_python/accumulators/mean.hpp", "max_issues_repo_name": "andrzejnovak/boost-histogram", "max_issues_repo_head_hexsha": "cdbfabb1c22f5545bf3900be01f2025411e699f1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 400.0, "max_issues_repo_issues_event_min_datetime": "2019-03-11T23:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T14:02:06.000Z", "max_forks_repo_path": "include/bh_python/accumulators/mean.hpp", "max_forks_repo_name": "andrzejnovak/boost-histogram", "max_forks_repo_head_hexsha": "cdbfabb1c22f5545bf3900be01f2025411e699f1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2019-03-11T18:02:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T20:14:22.000Z", "avg_line_length": 29.8623853211, "max_line_length": 87, "alphanum_fraction": 0.624577573, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5823028472880937}}
{"text": "/*!\n * @file intmath_test.cpp\n *\n * @author Andrzej Ciarkowski <mailto:andrzej.ciarkowski@gmail.com>\n */\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp> \n\n#include <climits>\n#include <cstdint>\n#include <dsp++/intmath.h>\n\nusing namespace dsp;\n\nBOOST_AUTO_TEST_SUITE(intmath)\n\nBOOST_AUTO_TEST_CASE(test_signum)\n{\n\tBOOST_CHECK(dsp::signum(-10) == -1);\n\tBOOST_CHECK(dsp::signum(INT_MIN) == -1);\n\tBOOST_CHECK(dsp::signum(0) == 0);\n\tBOOST_CHECK(dsp::signum(100) == 1);\n\tBOOST_CHECK(dsp::signum(INT_MAX) == 1);\n\tBOOST_CHECK(dsp::signum(0u) == 0u);\n\tBOOST_CHECK(dsp::signum(123u) == 1u);\n}\n\nBOOST_AUTO_TEST_CASE(test_add)\n{\n\tBOOST_CHECK(dsp::add<dsp::overflow::fastest>(1, 1) == 2);\n\tBOOST_CHECK(dsp::add<dsp::overflow::fastest>(10, -10) == 0);\n\tBOOST_CHECK(dsp::add<dsp::overflow::fastest>(-100, -100) == -200);\n\tBOOST_CHECK(dsp::add<dsp::overflow::fastest>(-1000, 1000) == 0);\n\tBOOST_CHECK(dsp::add<dsp::overflow::fastest>(INT_MAX, 1000) < 0);\n\tBOOST_CHECK(dsp::add<dsp::overflow::fastest>(INT_MIN, -1000) > 0);\n\n\tBOOST_CHECK(dsp::add<dsp::overflow::fastest>(10000u, 1u) == 10001u);\n\tBOOST_CHECK(dsp::add<dsp::overflow::fastest>(0u, 0u) == 0u);\n\n\tBOOST_CHECK(dsp::add<dsp::overflow::saturate>(1, 1) == 2);\n\tBOOST_CHECK(dsp::add<dsp::overflow::saturate>(1, INT_MAX) == INT_MAX);\n\tBOOST_CHECK(dsp::add<dsp::overflow::saturate>(-1, INT_MIN) == INT_MIN);\n\tBOOST_CHECK(dsp::add<dsp::overflow::saturate>(INT_MAX - 100, 110) == INT_MAX);\n\tBOOST_CHECK(dsp::add<dsp::overflow::saturate>(INT_MIN + 1000, -1001) == INT_MIN);\n\tBOOST_CHECK(dsp::add<dsp::overflow::saturate>(1u, UINT_MAX) == UINT_MAX);\n\n\tBOOST_CHECK_NO_THROW(dsp::add<dsp::overflow::exception>(INT_MAX - 10, 10));\n\tBOOST_CHECK_NO_THROW(dsp::add<dsp::overflow::exception>(INT_MIN + 100, 100));\n\tBOOST_CHECK_THROW(dsp::add<dsp::overflow::exception>(INT_MAX - 10, 11), std::overflow_error);\n\tBOOST_CHECK_THROW(dsp::add<dsp::overflow::exception>(INT_MIN + 11, -15), std::overflow_error);\n}\n\nBOOST_AUTO_TEST_CASE(test_sub)\n{\n\tBOOST_CHECK(dsp::sub<dsp::overflow::fastest>(1, 1) == 0);\n\tBOOST_CHECK(dsp::sub<dsp::overflow::fastest>(10, -10) == 20);\n\tBOOST_CHECK(dsp::sub<dsp::overflow::fastest>(-100, -100) == 0);\n\tBOOST_CHECK(dsp::sub<dsp::overflow::fastest>(-1000, 1000) == -2000);\n\tBOOST_CHECK(dsp::sub<dsp::overflow::fastest>(INT_MIN, 1000) > 0);\n\tBOOST_CHECK(dsp::sub<dsp::overflow::fastest>(INT_MAX, -1000) < 0);\n\n\tBOOST_CHECK(dsp::sub<dsp::overflow::fastest>(10000u, 1u) == 9999u);\n\tBOOST_CHECK(dsp::sub<dsp::overflow::fastest>(0u, 0u) == 0u);\n\tBOOST_CHECK(dsp::sub<dsp::overflow::fastest>(0u, 100u) > 100u);\n\n\tBOOST_CHECK(dsp::sub<dsp::overflow::saturate>(1, 1) == 0);\n\tBOOST_CHECK(dsp::sub<dsp::overflow::saturate>(INT_MIN, 100) == INT_MIN);\n\tBOOST_CHECK(dsp::sub<dsp::overflow::saturate>(INT_MAX, -110) == INT_MAX);\n\tBOOST_CHECK(dsp::sub<dsp::overflow::saturate>(1u, UINT_MAX) == 0);\n\n\tBOOST_CHECK_NO_THROW(dsp::sub<dsp::overflow::exception>(INT_MIN + 10, 10));\n\tBOOST_CHECK_NO_THROW(dsp::sub<dsp::overflow::exception>(INT_MAX - 100, -100));\n\tBOOST_CHECK_THROW(dsp::sub<dsp::overflow::exception>(INT_MAX - 10, -11), std::overflow_error);\n\tBOOST_CHECK_THROW(dsp::sub<dsp::overflow::exception>(INT_MIN + 11, 15), std::overflow_error);\n}\n\nBOOST_AUTO_TEST_CASE(test_mul)\n{\n\tBOOST_CHECK(dsp::mul<dsp::overflow::fastest>(1, 1) == 1);\n\tBOOST_CHECK(dsp::mul<dsp::overflow::fastest>(10, -10) == -100);\n\tBOOST_CHECK(dsp::mul<dsp::overflow::fastest>(-100, -100) == 10000);\n\tBOOST_CHECK(dsp::mul<dsp::overflow::fastest>(-1000, 1000) == -1000000);\n\tBOOST_CHECK(dsp::mul<dsp::overflow::fastest>(INT_MAX, 2) < 0);\n\n\tBOOST_CHECK(dsp::mul<dsp::overflow::fastest>(10000u, 1u) == 10000u);\n\tBOOST_CHECK(dsp::mul<dsp::overflow::fastest>(0u, 0u) == 0u);\n\tBOOST_CHECK(dsp::mul<dsp::overflow::fastest>(0u, 100u) == 0u);\n\n\tBOOST_CHECK(dsp::mul<dsp::overflow::saturate>(1, 1) == 1);\n\tBOOST_CHECK(dsp::mul<dsp::overflow::saturate>(INT_MIN, 100) == INT_MIN);\n\tBOOST_CHECK(dsp::mul<dsp::overflow::saturate>(INT_MIN, -100) == INT_MAX);\n\tBOOST_CHECK(dsp::mul<dsp::overflow::saturate>(INT_MAX, 110) == INT_MAX);\n\tBOOST_CHECK(dsp::mul<dsp::overflow::saturate>(INT_MAX, -110) == INT_MIN);\n\tBOOST_CHECK(dsp::mul<dsp::overflow::saturate>(INT_MIN, -1) == INT_MAX);\n\tBOOST_CHECK(dsp::mul<dsp::overflow::saturate>(2u, UINT_MAX) == UINT_MAX);\n\n\tBOOST_CHECK_NO_THROW(dsp::mul<dsp::overflow::exception>(INT_MIN, 1));\n\tBOOST_CHECK_NO_THROW(dsp::mul<dsp::overflow::exception>(INT_MAX, -1));\n\tBOOST_CHECK_THROW(dsp::mul<dsp::overflow::exception>(INT_MIN, -1), std::overflow_error);\n\tBOOST_CHECK_THROW(dsp::mul<dsp::overflow::exception>(INT_MAX, 2), std::overflow_error);\n}\n\nBOOST_AUTO_TEST_CASE(test_div)\n{\n\tBOOST_CHECK(dsp::div<dsp::overflow::fastest>(1, 1) == 1);\n\tBOOST_CHECK(dsp::div<dsp::overflow::fastest>(10, -10) == -1);\n\tBOOST_CHECK(dsp::div<dsp::overflow::fastest>(-100, -100) == 1);\n\tBOOST_CHECK(dsp::div<dsp::overflow::fastest>(-1000, 1000) == -1);\n\tBOOST_CHECK(dsp::div<dsp::overflow::fastest>(INT_MAX, 2) > 0);\n\n\tBOOST_CHECK(dsp::div<dsp::overflow::fastest>(10000u, 2u) == 5000u);\n\tBOOST_CHECK(dsp::div<dsp::overflow::fastest>(0u, 100u) == 0u);\n\n\tBOOST_CHECK(dsp::div<dsp::overflow::saturate>(INT_MIN, -1) == INT_MAX);\n\tBOOST_CHECK_NO_THROW(dsp::div<dsp::overflow::exception>(INT_MIN, 1));\n\tBOOST_CHECK_NO_THROW(dsp::div<dsp::overflow::exception>(INT_MAX, -1));\n\tBOOST_CHECK_THROW(dsp::div<dsp::overflow::exception>(INT_MIN, -1), std::overflow_error);\n}\n\nBOOST_AUTO_TEST_CASE(test_mod)\n{\n\tBOOST_CHECK(dsp::mod<dsp::overflow::fastest>(1, 1) == 0);\n\tBOOST_CHECK(dsp::mod<dsp::overflow::fastest>(10, -10) == 0);\n\tBOOST_CHECK(dsp::mod<dsp::overflow::fastest>(-100, -100) == 0);\n\tBOOST_CHECK(dsp::mod<dsp::overflow::fastest>(-1000, 1000) == 0);\n\n\tBOOST_CHECK(dsp::mod<dsp::overflow::fastest>(11, 10) == 1);\n\tBOOST_CHECK(dsp::mod<dsp::overflow::fastest>(-11, 10) == -1);\n\tBOOST_CHECK(dsp::mod<dsp::overflow::fastest>(11, -10) == 1);\n\tBOOST_CHECK(dsp::mod<dsp::overflow::fastest>(-11, -10) == -1);\n\n\tBOOST_CHECK(dsp::mod<dsp::overflow::fastest>(INT_MAX, 2) == 1);\n\tBOOST_CHECK(dsp::mod<dsp::overflow::fastest>(INT_MIN, 2) == 0);\n\n\tBOOST_CHECK(dsp::mod<dsp::overflow::fastest>(10000u, 2u) == 0u);\n\tBOOST_CHECK(dsp::mod<dsp::overflow::fastest>(0u, 100u) == 0u);\n}\n\nBOOST_AUTO_TEST_CASE(test_neg)\n{\n\tBOOST_CHECK(dsp::neg<dsp::overflow::fastest>(1) == -1);\n\tBOOST_CHECK(dsp::neg<dsp::overflow::fastest>(10) == -10);\n\tBOOST_CHECK(dsp::neg<dsp::overflow::fastest>(-100) == 100);\n\tBOOST_CHECK(dsp::neg<dsp::overflow::fastest>(INT_MAX) == -INT_MAX);\n\n\tBOOST_CHECK(dsp::neg<dsp::overflow::saturate>(10000u) == 0u);\n\tBOOST_CHECK(dsp::neg<dsp::overflow::fastest>(0u) == 0u);\n\n\tBOOST_CHECK(dsp::neg<dsp::overflow::saturate>(INT_MIN) == INT_MAX);\n\tBOOST_CHECK_THROW(dsp::neg<dsp::overflow::exception>(INT_MIN), std::overflow_error);\n}\n\nBOOST_AUTO_TEST_CASE(test_round)\n{\n\tBOOST_CHECK((dsp::round<rounding::truncated>(19234, 0) == 19234));\n\tBOOST_CHECK((dsp::round<rounding::nearest>(19234, 0) == 19234));\n\tBOOST_CHECK((dsp::round<rounding::negative>(19234, -1) == 19234));\n\tBOOST_CHECK((dsp::round<rounding::positive>(19234, -15) == 19234));\n\n\tBOOST_CHECK((dsp::round<rounding::truncated>(10, 3) == 8));\n\tBOOST_CHECK((dsp::round<rounding::nearest>(10, 3) == 8));\n\tBOOST_CHECK((dsp::round<rounding::negative>(10, 3) == 8));\n\tBOOST_CHECK((dsp::round<rounding::positive>(10, 3) == 16));\n\n\tBOOST_CHECK((dsp::round<rounding::truncated>(12, 3) == 8));\n\tBOOST_CHECK((dsp::round<rounding::nearest>(12, 3) == 16));\n\tBOOST_CHECK((dsp::round<rounding::negative>(12, 3) == 8));\n\tBOOST_CHECK((dsp::round<rounding::positive>(12, 3) == 16));\n\n\tBOOST_CHECK((dsp::round<rounding::truncated>(-10, 3) == -8));\n\tBOOST_CHECK((dsp::round<rounding::nearest>(-10, 3) == -8));\n\tBOOST_CHECK((dsp::round<rounding::negative>(-10, 3) == -16));\n\tBOOST_CHECK((dsp::round<rounding::positive>(-10, 3) == -8));\n\n\tBOOST_CHECK((dsp::round<rounding::truncated>(-12, 3) == -8));\n\tBOOST_CHECK((dsp::round<rounding::nearest>(-12, 3) == -16));\n\tBOOST_CHECK((dsp::round<rounding::negative>(-12, 3) == -16));\n\tBOOST_CHECK((dsp::round<rounding::positive>(-12, 3) == -8));\n\n\tBOOST_CHECK((dsp::round<rounding::truncated>(std::int16_t(32767), 15) == 0));\n\tBOOST_CHECK((dsp::round<rounding::nearest>(std::int16_t(32767), 15) == 0));\n\tBOOST_CHECK((dsp::round<rounding::truncated>(std::int16_t(-32768), 15) == 0));\n\tBOOST_CHECK((dsp::round<rounding::nearest>(std::int16_t(-32768), 15) == 0));\n\n\tBOOST_CHECK_NO_THROW((dsp::round<rounding::truncated, overflow::exception>(std::int16_t(32767), 14)));\n\tBOOST_CHECK((dsp::round<rounding::truncated, overflow::exception>(std::int16_t(32767), 14) == 16384));\n\tBOOST_CHECK_THROW((dsp::round<rounding::nearest, overflow::exception>(std::int16_t(32767), 14)), std::overflow_error);\n\tBOOST_CHECK_NO_THROW((dsp::round<rounding::nearest, overflow::exception>(std::int16_t(-32767), 14)));\n\tBOOST_CHECK((dsp::round<rounding::nearest, overflow::exception>(std::int16_t(-32767), 14) == std::int16_t(-32768)));\n}\n\nBOOST_AUTO_TEST_CASE(test_check_overflow)\n{\n\tstd::int16_t val = 16383;\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(val, 14));\n\t++val;\n\tBOOST_CHECK_THROW(dsp::overflow_check_handle<overflow::exception>(val, 14), std::overflow_error);\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(val, 15));\n\tval = 32767;\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(val, 15));\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(val, 16));\n\tval = -16384;\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(val, 14));\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(val, 15));\n\t--val;\n\tBOOST_CHECK_THROW(dsp::overflow_check_handle<overflow::exception>(val, 14), std::overflow_error);\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(val, 15));\n\tval = 0;\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(val, 0));\n\t++val;\n\tBOOST_CHECK_THROW(dsp::overflow_check_handle<overflow::exception>(val, 0), std::overflow_error);\n\n\tstd::uint16_t uval = 16383;\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(uval, 14));\n\t++uval;\n\tBOOST_CHECK_THROW(dsp::overflow_check_handle<overflow::exception>(uval, 14), std::overflow_error);\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(uval, 15));\n\tuval = 32767;\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(uval, 15));\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(uval, 16));\n\tuval = 32768;\n\tBOOST_CHECK_THROW(dsp::overflow_check_handle<overflow::exception>(uval, 15), std::overflow_error);\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(uval, 16));\n\tuval = 0;\n\tBOOST_CHECK_NO_THROW(dsp::overflow_check_handle<overflow::exception>(uval, 0));\n\t++uval;\n\tBOOST_CHECK_THROW(dsp::overflow_check_handle<overflow::exception>(uval, 0), std::overflow_error);\n}\n\nBOOST_AUTO_TEST_CASE(test_rint)\n{\n\tBOOST_CHECK((dsp::rint<std::int16_t>(0.5f, rounding::truncated, overflow::fastest) == 0));\n\tBOOST_CHECK((dsp::rint<std::int16_t>(0.9f, rounding::truncated, overflow::fastest) == 0));\n\tBOOST_CHECK((dsp::rint<std::int16_t>(-0.9f, rounding::truncated, overflow::fastest) == 0));\n\tBOOST_CHECK((dsp::rint<std::int16_t>(-11.f, rounding::truncated, overflow::fastest) == -11));\n\tBOOST_CHECK((dsp::rint<std::int16_t>(100.f, rounding::truncated, overflow::fastest) == 100));\n\n\tBOOST_CHECK((dsp::rint<std::int16_t>(0.1, rounding::nearest, overflow::fastest) == 0));\n\tBOOST_CHECK((dsp::rint<std::int16_t>(-0.1, rounding::nearest, overflow::fastest) == 0));\n\tBOOST_CHECK((dsp::rint<std::int32_t>(100.7, rounding::nearest, overflow::fastest) == 101));\n\tBOOST_CHECK((dsp::rint<std::int32_t>(-100.7, rounding::nearest, overflow::fastest) == -101));\n\tBOOST_CHECK((dsp::rint<std::int16_t>(32767.6, rounding::positive, overflow::saturate) == 32767));\n\tBOOST_CHECK((dsp::rint<std::int16_t>(-32769.6, rounding::positive, overflow::saturate) == -32768));\n\tBOOST_CHECK((dsp::rint<std::int16_t>(-32767.6, rounding::negative, overflow::saturate) == -32768));\n\tBOOST_CHECK((dsp::rint<std::int16_t>(-32767.6, rounding::positive, overflow::saturate) == -32767));\n\n\tBOOST_CHECK_THROW((dsp::rint<std::int16_t>(-32768.6, rounding::nearest, overflow::exception)), std::overflow_error);\n\tBOOST_CHECK_THROW((dsp::rint<std::int16_t>(32767.6, rounding::nearest, overflow::exception)), std::overflow_error);\n\tBOOST_CHECK_THROW((dsp::rint<std::uint16_t>(-1., rounding::nearest, overflow::exception)), std::overflow_error);\n\tBOOST_CHECK_THROW((dsp::rint<std::uint16_t>(-1., rounding::nearest, overflow::exception)), std::overflow_error);\n\n\tBOOST_CHECK_THROW((dsp::rint<int>(-2147483648.5, rounding::nearest, overflow::exception)), std::overflow_error);\n\tBOOST_CHECK_THROW((dsp::rint<int>(2147483647.5, rounding::nearest, overflow::exception)), std::overflow_error);\n}\n\nBOOST_AUTO_TEST_CASE(test_gcd)\n{\n\tBOOST_CHECK(dsp::gcd(1, 1) == 1);\n\tBOOST_CHECK(dsp::gcd(5, 3) == 1);\n\tBOOST_CHECK(dsp::gcd(3, 5) == 1);\n\tBOOST_CHECK(dsp::gcd(6, 4) == 2);\n\tBOOST_CHECK(dsp::gcd(8, 4) == 4);\n\tBOOST_CHECK(dsp::gcd(44100, 48000) == 300);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "8083eb23511e4c087fb262b9b1cd18110b0464e5", "size": 13150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dsp++/test/intmath_test.cpp", "max_stars_repo_name": "andrzejc/dsp-", "max_stars_repo_head_hexsha": "fd39d2395a37ade36e3b551d261de0177b78296b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dsp++/test/intmath_test.cpp", "max_issues_repo_name": "andrzejc/dsp-", "max_issues_repo_head_hexsha": "fd39d2395a37ade36e3b551d261de0177b78296b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dsp++/test/intmath_test.cpp", "max_forks_repo_name": "andrzejc/dsp-", "max_forks_repo_head_hexsha": "fd39d2395a37ade36e3b551d261de0177b78296b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.0671641791, "max_line_length": 119, "alphanum_fraction": 0.7091254753, "num_tokens": 4296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5823028449695792}}
{"text": "#ifndef MLT_UTILS_EIGEN_HPP\n#define MLT_UTILS_EIGEN_HPP\n\n#include <random>\n\n#include <Eigen/Core>\n\n#include \"../defs.hpp\"\n\nnamespace mlt {\nnamespace utils {\nnamespace eigen {\n\tinline Map<const MatrixXd> ravel(MatrixXdRef x) {\n\t\treturn Map<const MatrixXd>(x.data(), x.size(), 1);\n\t}\n\n\tinline Map<const MatrixXd> unravel(MatrixXdRef x, size_t rows, size_t cols) {\n\t\treturn Map<const MatrixXd>(x.data(), rows, cols);\n\t}\n\n\ttemplate <class MatrixA, class MatrixB, typename Rng = default_random_engine >\n\tauto tied_random_cols_subset(MatrixA&& a, MatrixB&& b, size_t subset_size, Rng&& rng = Rng()) {\n\t\tassert(subset_size > 0);\n\t\tuniform_int_distribution<size_t> distribution(0, a.cols() - 1);\n\n\t\tauto a_batch = a.leftCols(subset_size).eval();\n\t\tauto b_batch = b.leftCols(subset_size).eval();\n\n\t\tfor (auto i = 0; i < subset_size; i++) {\n\t\t\tauto cidx = distribution(rng);\n\t\t\ta_batch.col(i) = a.col(cidx);\n\t\t\tb_batch.col(i) = b.col(cidx);\n\t\t}\n\n\t\treturn make_tuple(a_batch, b_batch);\n\t}\n\n\tauto classes_vector_to_classes_matrix(VectorXiRef classes) {\n\t\tauto classes_matrix = MatrixXi{ MatrixXi::Zero(classes.maxCoeff() + 1, classes.size()) };\n\n\t\tfor (unsigned int i = 0; i < classes.size(); i++) {\n\t\t\tclasses_matrix(classes(i), i) = 1;\n\t\t}\n\n\t\treturn classes_matrix;\n\t}\n\n\tauto classes_matrix_to_classes_vector(MatrixXiRef classes) {\n\t\tassert((classes.colwise().sum().array() == 1).all());\n\n\t\tauto classes_vector = VectorXi(classes.cols());\n\n\t\tfor (size_t col = 0; col < classes.cols(); col++) {\n\t\t\tfor (size_t row = 0; row < classes.rows(); row++) {\n\t\t\t\tif (classes(row, col) == 1) {\n\t\t\t\t\tclasses_vector(col) = (row);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn classes_vector;\n\t}\n\n\tinline auto max_row(VectorXdRef x) {\n\t\tint max_row;\n\t\tx.maxCoeff(&max_row);\n\t\treturn max_row;\n\t}\n}\n}\n}\n#endif", "meta": {"hexsha": "f8828a9d7728af0ce1746559453033db12777743", "size": 1774, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/utils/eigen.hpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/mlt/utils/eigen.hpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlt/utils/eigen.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": 24.301369863, "max_line_length": 96, "alphanum_fraction": 0.6724915445, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925404, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5822653988448376}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/StdVector>\n\nnamespace km\n{\nnamespace types\n{\ntemplate <typename Scalar_t, int M, int N>\nusing Mat = Eigen::Matrix<Scalar_t, M, N>;\n\ntemplate <typename Scalar_t, int N>\nusing Vec = Mat<Scalar_t, N, 1>;\n\ntemplate <typename Scalar_t>\nusing MatX = Mat<Scalar_t, Eigen::Dynamic, Eigen::Dynamic>;\n\ntemplate <typename Scalar_t>\nusing VecX = Vec<Scalar_t, Eigen::Dynamic>;\n\ntemplate <typename Scalar_t, int N>\nusing SquareMat = Mat<Scalar_t, N, N>;\n\ntemplate <typename T>\nusing vector_aligned = std::vector<T, Eigen::aligned_allocator<T>>;\n} // namespace types\n} // namespace km\n", "meta": {"hexsha": "00b89e79ac2bd1f82d0a00a14717f42e74ce0895", "size": 623, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/km_utils/types.hpp", "max_stars_repo_name": "kartikmohta/km_utils", "max_stars_repo_head_hexsha": "41fa812f3cfddcf214653081c8e4183f2b3fa543", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-26T23:21:22.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-26T23:21:22.000Z", "max_issues_repo_path": "include/km_utils/types.hpp", "max_issues_repo_name": "kartikmohta/km_utils", "max_issues_repo_head_hexsha": "41fa812f3cfddcf214653081c8e4183f2b3fa543", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/km_utils/types.hpp", "max_forks_repo_name": "kartikmohta/km_utils", "max_forks_repo_head_hexsha": "41fa812f3cfddcf214653081c8e4183f2b3fa543", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4827586207, "max_line_length": 67, "alphanum_fraction": 0.7303370787, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5822653901367281}}
{"text": "//            Copyright Daniel Trebbien 2010.\n// Distributed under the Boost Software License, Version 1.0.\n//   (See accompanying file LICENSE_1_0.txt or the copy at\n//         http://www.boost.org/LICENSE_1_0.txt)\n\n#include <cassert>\n#include <cstddef>\n#include <cstdlib>\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/one_bit_color_map.hpp>\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/typeof/typeof.hpp>\n\nstruct edge_t\n{\n  unsigned long first;\n  unsigned long second;\n};\n\n// A graphic of the min-cut is available at <http://www.boost.org/doc/libs/release/libs/graph/doc/stoer_wagner_imgs/stoer_wagner.cpp.gif>\nint main()\n{\n  using namespace std;\n\n  typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n    boost::no_property, boost::property<boost::edge_weight_t, int> > undirected_graph;\n  typedef boost::property_map<undirected_graph, boost::edge_weight_t>::type weight_map_type;\n  typedef boost::property_traits<weight_map_type>::value_type weight_type;\n\n  // define the 16 edges of the graph. {3, 4} means an undirected edge between vertices 3 and 4.\n  edge_t edges[] = {{3, 4}, {3, 6}, {3, 5}, {0, 4}, {0, 1}, {0, 6}, {0, 7},\n    {0, 5}, {0, 2}, {4, 1}, {1, 6}, {1, 5}, {6, 7}, {7, 5}, {5, 2}, {3, 4}};\n\n  // for each of the 16 edges, define the associated edge weight. ws[i] is the weight for the edge\n  // that is described by edges[i].\n  weight_type ws[] = {0, 3, 1, 3, 1, 2, 6, 1, 8, 1, 1, 80, 2, 1, 1, 4};\n\n  // construct the graph object. 8 is the number of vertices, which are numbered from 0\n  // through 7, and 16 is the number of edges.\n  undirected_graph g(edges, edges + 16, ws, 8, 16);\n\n  // define a property map, `parities`, that will store a boolean value for each vertex.\n  // Vertices that have the same parity after `stoer_wagner_min_cut` runs are on the same side of the min-cut.\n  BOOST_AUTO(parities, boost::make_one_bit_color_map(num_vertices(g), get(boost::vertex_index, g)));\n\n  // run the Stoer-Wagner algorithm to obtain the min-cut weight. `parities` is also filled in.\n  int w = boost::stoer_wagner_min_cut(g, get(boost::edge_weight, g), boost::parity_map(parities));\n\n  cout << \"The min-cut weight of G is \" << w << \".\\n\" << endl;\n  assert(w == 7);\n\n  cout << \"One set of vertices consists of:\" << endl;\n  size_t i;\n  for (i = 0; i < num_vertices(g); ++i) {\n    if (get(parities, i))\n      cout << i << endl;\n  }\n  cout << endl;\n\n  cout << \"The other set of vertices consists of:\" << endl;\n  for (i = 0; i < num_vertices(g); ++i) {\n    if (!get(parities, i))\n      cout << i << endl;\n  }\n  cout << endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "cb70b5130188bdac5ae3802ec450cf83abd02351", "size": 2735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/stoer_wagner.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/stoer_wagner.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/stoer_wagner.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": 37.9861111111, "max_line_length": 137, "alphanum_fraction": 0.6720292505, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5822653824077593}}
{"text": "//------------------------------------------------------------------------------\n/// \\file StateMonadExamples_tests.cpp\n/// \\author Ernest Yeung\n/// \\email  ernestyalumni@gmail.com\n/// \\ref Edward Ashford Lee, Sanjit Arunkumar Seshia.\n/// Introduction to Embedded Systems: A Cyber-Physical Systems Approach\n/// (The MIT Press) Second Edition. The MIT Press; Second edition\n/// (December 30, 2016). ISBN-10: 0262533812. ISBN-13: 978-0262533812\n//------------------------------------------------------------------------------\n#include \"Categories/Monads/StateMonad.h\"\n#include \"Categories/Monads/StateMonadExamples.h\"\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace Categories::Monads::StateMonad::Examples;\nusing Categories::Monads::StateMonad::Compose;\n\nBOOST_AUTO_TEST_SUITE(Categories)\nBOOST_AUTO_TEST_SUITE(Monads)\nBOOST_AUTO_TEST_SUITE(StateMonadExamples_tests)\n\nBOOST_AUTO_TEST_SUITE(GarageCounter_tests)\n\nconst GarageCounter::InputPorts up_not_down {\n\tGarageCounter::SignalPresence::present,\n\tGarageCounter::SignalPresence::absent};\n\nconst GarageCounter::InputPorts not_up_down {\n\tGarageCounter::SignalPresence::absent,\n\tGarageCounter::SignalPresence::present};\n\n// Example 3.4, Fig. 3.4, garage counter Finite-State Machine (FSM), Lee and\n// Seshia (2016), pp. 50\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(GarageCounterIncrements)\n{\n\tGarageCounter::GarageCounterMorphism1 reaction {up_not_down};\n\n\tBOOST_TEST(reaction(5).first == 6);\n\tBOOST_TEST(reaction(6).first == 7);\n\tBOOST_TEST(reaction(7).first == 8);\n\n\t{\n\t\tGarageCounter::GarageCounterMorphism garage_counter {};\n\t\tauto reaction = garage_counter(up_not_down);\n\n\t\tBOOST_TEST(reaction(5).first == 6);\n\t\tBOOST_TEST(reaction(6).first == 7);\n\t\tBOOST_TEST(reaction(7).first == 8);\n\t}\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(GarageCounterDecrements)\n{\n\tGarageCounter::GarageCounterMorphism1 reaction {not_up_down};\n\n\tBOOST_TEST(reaction(5).first == 4);\n\tBOOST_TEST(reaction(6).first == 5);\n\tBOOST_TEST(reaction(7).first == 6);\n\n\t{\n\t\tGarageCounter::GarageCounterMorphism garage_counter {};\n\t\tauto reaction = garage_counter(not_up_down);\n\n\t\tBOOST_TEST(reaction(5).first == 4);\n\t\tBOOST_TEST(reaction(6).first == 5);\n\t\tBOOST_TEST(reaction(7).first == 6);\n\t}\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ComposeGarageCounterMorphism1s)\n{\n\tauto composed_reactions = Compose(\n\t\tGarageCounter::GarageCounterMorphism{},\n\t\tGarageCounter::GarageCounterMorphism{});\n\n}\n\nBOOST_AUTO_TEST_SUITE_END() // GarageCounter_tests\n\nBOOST_AUTO_TEST_SUITE(ModestThermostatMorphism_tests)\n\n//------------------------------------------------------------------------------\n/// \\ref pp. 51, Lee and Seshia, Introduction to Embedded Systems, Figure 3.5:\n/// A model of a thermostat with hysteresis.\n//------------------------------------------------------------------------------\nModestThermostat::ModestThermostatMorphism thermostat {18, 22};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(NoChangeForTemperaturesInHysteresis)\n{\n\t{\n\t\tauto transition_function = thermostat(18.1);\n\t\tauto result = transition_function(ModestThermostat::State::cooling);\n\t\tBOOST_TEST((result.first == ModestThermostat::State::cooling));\n\t\tBOOST_TEST(!result.second);\n\t}\n\t{\n\t\tauto transition_function = thermostat(21.9);\n\t\tauto result = transition_function(ModestThermostat::State::heating);\n\t\tBOOST_TEST((result.first == ModestThermostat::State::heating));\n\t\tBOOST_TEST(!result.second);\n\t}\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ContinuesCoolingIfTemperatureIsAboveALimit)\n{\n\tauto transition_function = thermostat(22.1);\n\tauto result = transition_function(ModestThermostat::State::cooling);\n\tBOOST_TEST((result.first == ModestThermostat::State::cooling));\n\tBOOST_TEST(!result.second);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ContinuesCoolingIfTemperatureIsAtALimit)\n{\n\tauto transition_function = thermostat(22.0);\n\tauto result = transition_function(ModestThermostat::State::cooling);\n\tBOOST_TEST((result.first == ModestThermostat::State::cooling));\n\tBOOST_TEST(!result.second);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ContinuesHeatingIfTemperatureIsBelowALimit)\n{\n\tauto transition_function = thermostat(17.9);\n\tauto result = transition_function(ModestThermostat::State::heating);\n\tBOOST_TEST((result.first == ModestThermostat::State::heating));\n\tBOOST_TEST(!result.second);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ContinuesHeatingIfTemperatureIsBelowAtALimit)\n{\n\tauto transition_function = thermostat(18.0);\n\tauto result = transition_function(ModestThermostat::State::heating);\n\tBOOST_TEST((result.first == ModestThermostat::State::heating));\n\tBOOST_TEST(!result.second);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(BeginsHeatingIfTemperatureIsBelowALimitAndHadBeenCooling)\n{\n\tauto transition_function = thermostat(17.9);\n\tauto result = transition_function(ModestThermostat::State::cooling);\n\tBOOST_TEST((result.first == ModestThermostat::State::heating));\n\tBOOST_TEST(static_cast<bool>(result.second));\n\tBOOST_TEST((*result.second == ModestThermostat::Output::heatOn));\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(BeginsCoolingIfTemperatureIsAboveALimitAndHadBeenHeating)\n{\n\tauto transition_function = thermostat(22.1);\n\tauto result = transition_function(ModestThermostat::State::heating);\n\tBOOST_TEST((result.first == ModestThermostat::State::cooling));\n\tBOOST_TEST(static_cast<bool>(result.second));\n\tBOOST_TEST((*result.second == ModestThermostat::Output::heatOff));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // ModestThermostatMorphism_tests\n\nBOOST_AUTO_TEST_SUITE(TrafficLight_tests)\n\n//------------------------------------------------------------------------------\n/// \\ref pp. 62, Lee and Seshia, Introduction to Embedded Systems, Figure 3.10:\n/// State machine model of traffic light controller that keeps track of passage,\n/// assuming it reacts at regular intervals.\n//------------------------------------------------------------------------------\nconstexpr unsigned int count_time {60};\nconstexpr unsigned int yellow_to_red_time {5};\nTrafficLight::TrafficLightMorphism traffic_light {\n\tcount_time,\n\tyellow_to_red_time};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(\n\tTransitionsFromRedToGreenOnlyWhenCountIsGreaterThanOrEqualToCountTime)\n{\n\t{\n\t\tauto transition_function =\n\t\t\ttraffic_light(59, TrafficLight::Pedestrian::present);\n\t\tauto result = transition_function(TrafficLight::State::red);\n\t\tBOOST_TEST((result.first == TrafficLight::State::red));\n\t\tBOOST_TEST(!result.second.signal_);\n\t\tBOOST_TEST(!result.second.reset_count_);\n\t}\n\t{\n\t\tauto transition_function =\n\t\t\ttraffic_light(59, TrafficLight::Pedestrian::absent);\n\t\tauto result = transition_function(TrafficLight::State::red);\n\t\tBOOST_TEST((result.first == TrafficLight::State::red));\n\t\tBOOST_TEST(!result.second.signal_);\n\t\tBOOST_TEST(!result.second.reset_count_);\n\t}\n\t{\n\t\tauto transition_function =\n\t\t\ttraffic_light(60, TrafficLight::Pedestrian::present);\n\t\tauto result = transition_function(TrafficLight::State::red);\n\t\tBOOST_TEST((result.first == TrafficLight::State::green));\n\t\tBOOST_TEST((\n\t\t\tresult.second.signal_.value() == TrafficLight::Signal::signal_green));\n\t\tBOOST_TEST(result.second.reset_count_);\n\t}\n\t{\n\t\tauto transition_function =\n\t\t\ttraffic_light(61, TrafficLight::Pedestrian::present);\n\t\tauto result = transition_function(TrafficLight::State::red);\n\t\tBOOST_TEST((result.first == TrafficLight::State::green));\n\t\tBOOST_TEST((\n\t\t\tresult.second.signal_.value() == TrafficLight::Signal::signal_green));\n\t\tBOOST_TEST(result.second.reset_count_);\n\t}\n\t{\n\t\tauto transition_function =\n\t\t\ttraffic_light(60, TrafficLight::Pedestrian::absent);\n\t\tauto result = transition_function(TrafficLight::State::red);\n\t\tBOOST_TEST((result.first == TrafficLight::State::green));\n\t\tBOOST_TEST((\n\t\t\tresult.second.signal_.value() == TrafficLight::Signal::signal_green));\n\t\tBOOST_TEST(result.second.reset_count_);\n\t}\n\t{\n\t\tauto transition_function =\n\t\t\ttraffic_light(61, TrafficLight::Pedestrian::absent);\n\t\tauto result = transition_function(TrafficLight::State::red);\n\t\tBOOST_TEST((result.first == TrafficLight::State::green));\n\t\tBOOST_TEST((\n\t\t\tresult.second.signal_.value() == TrafficLight::Signal::signal_green));\n\t\tBOOST_TEST(result.second.reset_count_);\n\t}\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(GreenToYellowWhenCountIsGreaterThanOrEqualToCountTime)\n{\n\t{\n\t\tauto transition_function =\n\t\t\ttraffic_light(59, TrafficLight::Pedestrian::absent);\n\t\tauto result = transition_function(TrafficLight::State::green);\n\t\tBOOST_TEST((result.first == TrafficLight::State::green));\n\t\tBOOST_TEST(!result.second.signal_);\n\t\tBOOST_TEST(!result.second.reset_count_);\n\t}\n\t{\n\t\tauto transition_function =\n\t\t\ttraffic_light(60, TrafficLight::Pedestrian::present);\n\t\tauto result = transition_function(TrafficLight::State::green);\n\t\tBOOST_TEST((result.first == TrafficLight::State::yellow));\n\t\tBOOST_TEST((\n\t\t\tresult.second.signal_.value() == TrafficLight::Signal::signal_yellow));\n\t\tBOOST_TEST(result.second.reset_count_);\n\t}\n\t{\n\t\tauto transition_function =\n\t\t\ttraffic_light(61, TrafficLight::Pedestrian::present);\n\t\tauto result = transition_function(TrafficLight::State::green);\n\t\tBOOST_TEST((result.first == TrafficLight::State::yellow));\n\t\tBOOST_TEST((\n\t\t\tresult.second.signal_.value() == TrafficLight::Signal::signal_yellow));\n\t\tBOOST_TEST(result.second.reset_count_);\n\t}\n\t{\n\t\tauto transition_function =\n\t\t\ttraffic_light(60, TrafficLight::Pedestrian::absent);\n\t\tauto result = transition_function(TrafficLight::State::green);\n\t\tBOOST_TEST((result.first == TrafficLight::State::yellow));\n\t\tBOOST_TEST((\n\t\t\tresult.second.signal_.value() == TrafficLight::Signal::signal_yellow));\n\t\tBOOST_TEST(result.second.reset_count_);\n\t}\n\t{\n\t\tauto transition_function =\n\t\t\ttraffic_light(61, TrafficLight::Pedestrian::absent);\n\t\tauto result = transition_function(TrafficLight::State::green);\n\t\tBOOST_TEST((result.first == TrafficLight::State::yellow));\n\t\tBOOST_TEST((\n\t\t\tresult.second.signal_.value() == TrafficLight::Signal::signal_yellow));\n\t\tBOOST_TEST(result.second.reset_count_);\n\t}\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(\n\tYellowToPendingWhenCountIsLessThanCountTimeAndPedestrianPresent)\n{\n\t{\n\t\tauto transition_function =\n\t\t\ttraffic_light(59, TrafficLight::Pedestrian::present);\n\t\tauto result = transition_function(TrafficLight::State::green);\n\t\tBOOST_TEST((result.first == TrafficLight::State::pending));\n\t\tBOOST_TEST(!result.second.signal_);\n\t\tBOOST_TEST(!result.second.reset_count_);\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END() // TrafficLight_tests\n\nBOOST_AUTO_TEST_SUITE_END() // StateMonadExamples_tests\nBOOST_AUTO_TEST_SUITE_END() // Monads\nBOOST_AUTO_TEST_SUITE_END() // Categories", "meta": {"hexsha": "4e926e7635e475d3f74d1ff2567e6480a8903547", "size": 12380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Categories/Monads/StateMonadExamples_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Categories/Monads/StateMonadExamples_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Categories/Monads/StateMonadExamples_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9308176101, "max_line_length": 80, "alphanum_fraction": 0.6122778675, "num_tokens": 2470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.5822345784820986}}
{"text": "/* boost random/uniform_on_sphere.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: uniform_on_sphere.hpp,v 1.1.1.1 2007/10/29 07:32:44 cvsadmin Exp $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_UNIFORM_ON_SPHERE_HPP\n#define BOOST_RANDOM_UNIFORM_ON_SPHERE_HPP\n\n#include <vector>\n#include <algorithm>     // std::transform\n#include <functional>    // std::bind2nd, std::divides\n#include <boost/random/normal_distribution.hpp>\n\nnamespace boost {\n\ntemplate<class RealType = double, class Cont = std::vector<RealType> >\nclass uniform_on_sphere\n{\npublic:\n  typedef RealType input_type;\n  typedef Cont result_type;\n\n  explicit uniform_on_sphere(int dim = 2) : _container(dim), _dim(dim) { }\n\n  // compiler-generated copy ctor and assignment operator are fine\n\n  void reset() { _normal.reset(); }\n\n  template<class Engine>\n  const result_type & operator()(Engine& eng)\n  {\n    RealType sqsum = 0;\n    for(typename Cont::iterator it = _container.begin();\n        it != _container.end();\n        ++it) {\n      RealType val = _normal(eng);\n      *it = val;\n      sqsum += val * val;\n    }\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif\n    // for all i: result[i] /= sqrt(sqsum)\n    std::transform(_container.begin(), _container.end(), _container.begin(),\n                   std::bind2nd(std::divides<RealType>(), sqrt(sqsum)));\n    return _container;\n  }\n\n#if !defined(BOOST_NO_OPERATORS_IN_NAMESPACE) && !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)\n  template<class CharT, class Traits>\n  friend std::basic_ostream<CharT,Traits>&\n  operator<<(std::basic_ostream<CharT,Traits>& os, const uniform_on_sphere& sd)\n  {\n    os << sd._dim;\n    return os;\n  }\n\n  template<class CharT, class Traits>\n  friend std::basic_istream<CharT,Traits>&\n  operator>>(std::basic_istream<CharT,Traits>& is, uniform_on_sphere& sd)\n  {\n    is >> std::ws >> sd._dim;\n    sd._container.resize(sd._dim);\n    return is;\n  }\n#endif\n\nprivate:\n  normal_distribution<RealType> _normal;\n  result_type _container;\n  int _dim;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_UNIFORM_ON_SPHERE_HPP\n", "meta": {"hexsha": "4105a83f3e3b954cdf8d48c727a05644f47b017a", "size": 2371, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Game/boost/boost/random/uniform_on_sphere.hpp", "max_stars_repo_name": "hackerlank/SourceCode", "max_stars_repo_head_hexsha": "b702c9e0a9ca5d86933f3c827abb02a18ffc9a59", "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": "Game/boost/boost/random/uniform_on_sphere.hpp", "max_issues_repo_name": "shacojx/SourceCodeGameTLBB", "max_issues_repo_head_hexsha": "e3cea615b06761c2098a05427a5f41c236b71bf7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Game/boost/boost/random/uniform_on_sphere.hpp", "max_forks_repo_name": "shacojx/SourceCodeGameTLBB", "max_forks_repo_head_hexsha": "e3cea615b06761c2098a05427a5f41c236b71bf7", "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": 27.2528735632, "max_line_length": 91, "alphanum_fraction": 0.7001265289, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.582234565665}}
{"text": "#include \"pose_utils.h\"\n\n#include <fstream>\n#include <sstream>\n#include <stdexcept>\n\n#include <Eigen/Geometry>\n\nPoseList loadPosesKittiFormat(std::string fn)\n{\n  std::ifstream ifs(fn);\n  if(!ifs.is_open()) {\n    throw std::runtime_error(\"failed to open pose file\");\n  }\n\n  PoseList ret;\n  while(!ifs.eof()) {\n    std::string line;\n    std::getline(ifs, line);\n\n    std::stringstream ss(line);\n    double vals[12];\n    if(!line.empty()) {\n      for(int i = 0; i < 12; ++i) {\n        ss >> vals[i];\n      }\n\n      Mat44 T(Mat44::Identity());\n      for(int i = 0, c=0; i < 3; ++i) {\n        for(int j = 0; j < 4; ++j) {\n          T(i,j) = vals[c++];\n        }\n      }\n\n      ret.push_back( T );\n    }\n  }\n\n  return ret;\n}\n\n\nbool writePosesKittiFormat(std::string fn, const PoseList& T)\n{\n  std::ofstream ofs(fn);\n  if(!ofs.is_open())\n    return false;\n\n  for(size_t i = 0; i < T.size(); ++i) {\n    for(int r = 0; r < 3; ++r) {\n      for(int c = 0; c < 4; ++c) {\n        ofs << (T[i](r,c)) << \" \";\n      }\n    }\n    ofs << \"\\n\";\n  }\n\n  return true;\n}\n\n\nPoseList convertPoseToLocal(const PoseList& T_w)\n{\n  if(T_w.empty())\n    throw std::runtime_error(\"no poses\");\n\n  PoseList T_i(T_w.size());\n  T_i[0] = Eigen::Isometry3d( T_w[0] ).inverse().matrix();\n  for(size_t i = 1; i < T_w.size(); ++i) {\n    T_i[i] = Eigen::Isometry3d(T_w[i]).inverse().matrix() * T_w[i-1];\n  }\n\n  return T_i;\n}\n", "meta": {"hexsha": "472bc49eff03fad8cc7dc68a031b919445c608c3", "size": 1382, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pose_utils.cc", "max_stars_repo_name": "halismai/photobundle", "max_stars_repo_head_hexsha": "8b5466fa8ead930625771c4d72232ff4b8da6833", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2016-12-01T05:16:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T14:10:07.000Z", "max_issues_repo_path": "src/pose_utils.cc", "max_issues_repo_name": "halismai/photobundle", "max_issues_repo_head_hexsha": "8b5466fa8ead930625771c4d72232ff4b8da6833", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-07-31T07:25:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-31T07:25:05.000Z", "max_forks_repo_path": "src/pose_utils.cc", "max_forks_repo_name": "halismai/photobundle", "max_forks_repo_head_hexsha": "8b5466fa8ead930625771c4d72232ff4b8da6833", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2017-01-02T12:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-16T05:58:56.000Z", "avg_line_length": 18.4266666667, "max_line_length": 69, "alphanum_fraction": 0.5296671491, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5822345610514573}}
{"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": "#include <glm/models/links/identity.hpp>\n\n#include <armadillo>\n\nusing namespace arma;\nidentity_link::identity_link()\n    : glm_link::glm_link( \"identity\" )\n{\n}\n\nvec\nidentity_link::init_beta(const mat &X, const vec &y) const\n{ \n    vec mu = (y + 0.5) / 2.0;\n    vec eta = mu;\n    \n    return pinv( X ) * eta;\n}\n\nvec\nidentity_link::mu(const arma::vec &eta) const\n{\n    return eta;\n}\n\nvec\nidentity_link::eta(const arma::vec &mu) const\n{\n    return mu;\n}\n\nvec\nidentity_link::mu_eta(const arma::vec &mu) const\n{\n    return arma::ones<arma::vec>( mu.n_elem );\n}\n", "meta": {"hexsha": "12e6743b7289785b6df85bd60cecb3795240fbbf", "size": 556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/glm/models/links/identity.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/identity.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/identity.cpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 15.027027027, "max_line_length": 58, "alphanum_fraction": 0.6456834532, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5821970091233727}}
{"text": "//  (C) Copyright Gennadiy Rozental 2001-2014.\n//  Distributed under the Boost Software License, Version 1.0.\n//  (See accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n\n//  See http://www.boost.org/libs/test for the library home page.\n\n// Boost.Test\n#include <boost/test/unit_test.hpp>\n#include <boost/test/utils/algorithm.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/test/parameterized_test.hpp>\nusing namespace boost::unit_test;\n\n// BOOST\n#include <boost/functional.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/mem_fn.hpp>\n#include <boost/bind/bind.hpp>\n\n// STL\n#include <string>\n#include <stdexcept>\n#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <memory>\n#include <list>\n\n//____________________________________________________________________________//\n\ntemplate<int n>\nstruct power_of_10 {\n    BOOST_STATIC_CONSTANT( unsigned long, value = 10*power_of_10<n-1>::value );\n};\n\ntemplate<>\nstruct power_of_10<0> {\n    BOOST_STATIC_CONSTANT( unsigned long, value = 1 );\n};\n\n//____________________________________________________________________________//\n\ntemplate<int AlphabetSize>\nclass hash_function {\npublic:\n    BOOST_STATIC_ASSERT( AlphabetSize <= 5 );\n\n    explicit        hash_function( std::string const& alphabet )\n    : m_alphabet( alphabet )\n    {\n        if( m_alphabet.size() != AlphabetSize )\n            throw std::runtime_error( \"Wrong alphabet size\" );\n\n        std::sort( m_alphabet.begin(), m_alphabet.end() );\n\n        if( std::adjacent_find( m_alphabet.begin(), m_alphabet.end() ) != m_alphabet.end() )\n            throw std::logic_error( \"Duplicate characters in alphabet\" );\n    }\n\n    unsigned long   operator()( std::string const& arg )\n    {\n        m_result = 0;\n\n        if( arg.length() > 8 )\n            throw std::runtime_error( \"Wrong argument size\" );\n\n        std::string::const_iterator it = std::find_if( arg.begin(), arg.end(),\n            BOOST_TEST_BIND1ST( boost::mem_fun( &hash_function::helper_ ), this ) );\n\n        if( it != arg.end() )\n            throw std::out_of_range( std::string( \"Invalid character \" ) + *it );\n\n        return m_result;\n    }\n\nprivate:\n    bool            helper_( char c )\n    {\n        std::string::const_iterator it = std::find( m_alphabet.begin(), m_alphabet.end(), c );\n\n        if( it == m_alphabet.end() )\n            return true;\n\n        m_result += power_of_10_( it - m_alphabet.begin() );\n\n        return false;\n    }\n\n    unsigned long   power_of_10_( int i ) {\n        switch( i ) {\n        case 0: return power_of_10<0>::value;\n        case 1: return power_of_10<1>::value;\n        case 2: return power_of_10<2>::value;\n        case 3: return power_of_10<3>::value;\n        case 4: return power_of_10<4>::value;\n        default: return 0;\n        }\n    }\n\n    // Data members\n    std::string     m_alphabet;\n    unsigned long   m_result;\n};\n\n//____________________________________________________________________________//\n\nstruct hash_function_test_data {\n    std::string     orig_string;\n    unsigned long   exp_value;\n\n    friend std::istream& operator>>( std::istream& istr, hash_function_test_data& test_data )\n    {\n        std::istream& tmp = istr >> test_data.orig_string;\n        return  !tmp ? tmp : istr >> test_data.exp_value;\n    }\n};\n\n//____________________________________________________________________________//\n\nclass hash_function_tester {\npublic:\n    explicit        hash_function_tester( std::string const& alphabet )\n    : m_function_under_test( alphabet ) {}\n\n    void            test( hash_function_test_data const& test_data )\n    {\n        if( test_data.exp_value == (unsigned long)-1 )\n            BOOST_CHECK_THROW( m_function_under_test( test_data.orig_string ), std::runtime_error );\n        else if( test_data.exp_value == (unsigned long)-2 )\n            BOOST_CHECK_THROW( m_function_under_test( test_data.orig_string ), std::out_of_range );\n        else {\n            BOOST_TEST_MESSAGE( \"Testing: \" << test_data.orig_string );\n            BOOST_CHECK_EQUAL( m_function_under_test( test_data.orig_string ), test_data.exp_value );\n        }\n    }\n\nprivate:\n    hash_function<4> m_function_under_test;\n};\n\n//____________________________________________________________________________//\n\nstruct massive_hash_function_test : test_suite {\n    massive_hash_function_test() : test_suite( \"massive_hash_function_test\" ) {\n        std::string alphabet;\n        std::cout << \"Enter alphabet (4 characters without delimeters)\\n\";\n        std::cin >> alphabet;\n\n        boost::shared_ptr<hash_function_tester> instance( new hash_function_tester( alphabet ) );\n\n        std::cout << \"\\nEnter test data in a format [string] [value] to check correct calculation\\n\";\n        std::cout << \"Enter test data in a format [string] -1 to check long string validation\\n\";\n        std::cout << \"Enter test data in a format [string] -2 to check invalid argument string validation\\n\";\n\n        std::list<hash_function_test_data> test_data_store;\n\n        while( !std::cin.eof() ) {\n            hash_function_test_data test_data;\n\n            if( !(std::cin >> test_data) )\n                break;\n\n            test_data_store.push_back( test_data );\n        }\n\n        add( make_test_case( &hash_function_tester::test,\n                             \"hash_function_tester\",\n                             __FILE__,\n                             __LINE__,\n                             instance,\n                             test_data_store.begin(),\n                             test_data_store.end() ) );\n    }\n};\n\n//____________________________________________________________________________//\n\ntest_suite*\ninit_unit_test_suite( int, char* [] ) {\n    framework::master_test_suite().p_name.value = \"Unit test example 12\";\n\n    framework::master_test_suite().add( new massive_hash_function_test );\n\n    return 0;\n}\n\n//____________________________________________________________________________//\n\n// EOF\n", "meta": {"hexsha": "7deec270be95d17e89d41d3fb5077a0565ca5688", "size": 5998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/test/example/unit_test_example_12.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T11:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T03:08:16.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/test/example/unit_test_example_12.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 266.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T02:03:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:22:12.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/test/example/unit_test_example_12.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 185.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T18:09:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T18:07:05.000Z", "avg_line_length": 31.4031413613, "max_line_length": 109, "alphanum_fraction": 0.6553851284, "num_tokens": 1309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021787, "lm_q2_score": 0.7248702880639792, "lm_q1q2_score": 0.5821968347910484}}
{"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": "#ifndef CANNON_ML_PATTERN_SEARCH_H\n#define CANNON_ML_PATTERN_SEARCH_H \n\n/*!\n * \\file cannon/ml/pattern_search.hpp\n * \\brief File containing PatternSearchOptimizer 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&)>;\n\nnamespace cannon {\n  namespace ml {\n\n    CANNON_CLASS_FORWARD(OptimizationResult);\n\n    /*!\n     * \\brief Class representing a pattern search optimizer. Pattern Search is\n     * a derivative-free optimization method, similar to the Nelder-Mead method\n     * but with better convergence guarantees. See\n     * https://en.wikipedia.org/wiki/Pattern_search_(optimization).\n     */ \n    class PatternSearchOptimizer {\n      public:\n        PatternSearchOptimizer() = delete;\n\n        /*!\n         * \\brief Constructor taking a function to optimize, the dimension of\n         * input space, whether to reorient the search pattern, and tuning\n         * parameters.\n         */\n        PatternSearchOptimizer(RealFunc f, unsigned int dim, bool\n            reorient=false, double forcing_func_param=1.0, double reorient_param=0.1) : f_(f), dim_(dim),\n        reorient_(reorient), forcing_func_param_(forcing_func_param), reorient_param_(reorient_param) {}\n\n        /*!\n         * \\brief Minimize the unconstrained, derivative-free problem represented by this object. \n         *\n         * \\param start Start state for iterative optimization\n         * \\param iterations Maximum number of iterations to perform\n         * \\param eps Small number used for testing convergence\n         * \\param contraction_param Parameter used to shrink search step size\n         * \\param expansion_param Parameter used to expand search step size\n         * \\param initial_step Initial step size\n         */ \n        OptimizationResult optimize(const VectorXd& start, unsigned int iterations=1000, double eps=1e-10,\n            double contraction_param=0.9, double expansion_param=1.5, double\n            initial_step=1.0);\n\n      private:\n\n        /*!\n         * \\brief Create a positive spanning simplex set from the input vector.\n         * This ensures that the input direction is a search direction. \n         *\n         * \\param first The vector to build a simplex set around.\n         *\n         * \\returns The simplex direction set.\n         */\n        std::vector<VectorXd> create_simplex_set_(const VectorXd& first);\n\n        /*!\n         * \\brief Forcing function used to ensure that function evaluations\n         * decrease sufficiently.\n         *\n         * \\param t Input used to compute forcing term.\n         *\n         * \\returns Forcing term.\n         */\n        double forcing_func_(double t);\n\n        /*!\n         * \\brief Update leading direction by exponential averaging with the\n         * input difference vector.\n         *\n         * \\param leading_dir The leading search direction to update.\n         * \\param diff Difference vector to use for updating.\n         */\n        void update_leading_dir_(VectorXd& leading_dir, const VectorXd& diff);\n\n        RealFunc f_; //!< Function to be optimized\n        unsigned int dim_; //!< Input dimension\n        bool reorient_; //!< Whether to reorient leading direction \n\n        double forcing_func_param_; //!< Forcing function parameter\n        double reorient_param_; //!< Reorientation speed parameter\n\n    };\n\n  } // namespace ml\n} // namespace cannon\n\n#endif /* ifndef CANNON_ML_PATTERN_SEARCH_H */\n", "meta": {"hexsha": "7f5557b0e293eef8dc4c59a5921d69845dd35323", "size": 3510, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/ml/pattern_search.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/pattern_search.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/pattern_search.hpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7524752475, "max_line_length": 106, "alphanum_fraction": 0.6612535613, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7248702821204019, "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": "//  Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// Basic sanity check that header\n// #includes all the files that it needs to.\n//\n#include <boost/math/tools/cohen_acceleration.hpp>\n//\n// Note this header includes no other headers, this is\n// important if this test is to be meaningful:\n//\n#include \"test_compile_result.hpp\"\n\ntemplate<typename Real>\nclass G {\npublic:\n    G(){\n        k_ = 0;\n    }\n    \n    Real operator()() {\n        k_ += 1;\n        return 1/(k_*k_);\n    }\n\nprivate:\n    Real k_;\n};\n\nvoid compile_and_link_test()\n{    \n    auto f_g = G<float>();\n    check_result<float>(boost::math::tools::cohen_acceleration(f_g));\n\n    auto d_g = G<double>();\n    check_result<double>(boost::math::tools::cohen_acceleration(d_g));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    auto ld_g = G<long double>();\n    check_result<long double>(boost::math::tools::cohen_acceleration(ld_g));\n#endif\n}\n", "meta": {"hexsha": "5517540b790d77c4795c4386230792fec341ef26", "size": 1083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/tools_cohen_acceleration_incl_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/compile_test/tools_cohen_acceleration_incl_test.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/compile_test/tools_cohen_acceleration_incl_test.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 24.6136363636, "max_line_length": 76, "alphanum_fraction": 0.6777469991, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5821968068094905}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm trigonometry asin\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/data_customization_point/scalar.h\"\n#include \"fern/core/type_traits.h\"\n#include \"fern/algorithm/trigonometry/asin.h\"\n\n\nnamespace fa = fern::algorithm;\n\n\ntemplate<\n    class Value>\nusing OutOfDomainPolicy = fa::asin::OutOfDomainPolicy<Value>;\n\n\nBOOST_AUTO_TEST_CASE(out_of_domain_policy)\n{\n    {\n        OutOfDomainPolicy<double> policy;\n        BOOST_CHECK(!policy.within_domain(-1.1));\n        BOOST_CHECK(!policy.within_domain(1.1));\n        BOOST_CHECK(policy.within_domain(0));\n        BOOST_CHECK(policy.within_domain(-1));\n        BOOST_CHECK(policy.within_domain(1));\n    }\n}\n\n\ntemplate<\n    class Value,\n    class Result>\nvoid verify_value(\n    Value const& value,\n    Result const& result_we_want)\n{\n    fa::SequentialExecutionPolicy sequential;\n\n    Result result_we_get;\n    fa::trigonometry::asin(sequential, value, result_we_get);\n    BOOST_CHECK_CLOSE(result_we_get, result_we_want, 1e-6);\n}\n\n\nBOOST_AUTO_TEST_CASE(algorithm)\n{\n    verify_value<double, double>(-0.5, -fern::pi<double>() / 6.0);\n    verify_value<double, double>(0.0, 0.0);\n    verify_value<double, double>(1.0, fern::half_pi<double>());\n}\n", "meta": {"hexsha": "eb85baa5730dcb8b56567d87ef74738e2891d1de", "size": 1694, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/trigonometry/test/asin_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/trigonometry/test/asin_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/trigonometry/test/asin_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2068965517, "max_line_length": 80, "alphanum_fraction": 0.6493506494, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5821968068094905}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2021 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n//\n\n#ifdef _MSC_VER\n#define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#include <thread>\n#include <boost/detail/lightweight_test.hpp>\n#include <boost/array.hpp>\n#include <boost/math/special_functions/relative_difference.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/quadrature/tanh_sinh.hpp>\n#include \"test.hpp\"\n\n#if !defined(TEST_MPF_50) && !defined(TEST_MPFR_50)\n#define TEST_MPF_50\n#define TEST_MPFR_50\n\n#ifdef _MSC_VER\n#pragma message(\"CAUTION!!: No backend type specified so testing everything.... this will take some time!!\")\n#endif\n#ifdef __GNUC__\n#pragma warning \"CAUTION!!: No backend type specified so testing everything.... this will take some time!!\"\n#endif\n\n#endif\n\n#include <boost/multiprecision/mpfr.hpp>\n\n#if defined(TEST_MPF_50)\n#include <boost/multiprecision/gmp.hpp>\n#endif\n\ntemplate <class T>\nvoid thread_test_proc(unsigned digits)\n{\n   typedef boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<1000> > mpfr_float_1000;\n\n   if (!mpfr_buildopt_tls_p())\n      return;\n\n   T::thread_default_precision(digits);\n\n   T result, value;\n\n   value = boost::math::constants::pi<T>();\n   result.assign(boost::math::constants::pi<mpfr_float_1000>().str());\n   BOOST_CHECK_LE(boost::math::epsilon_difference(value, result), 20);\n   BOOST_CHECK_EQUAL(value.precision(), digits);\n\n   for (unsigned i = 20; i < 500; ++i)\n   {\n      T arg(i);\n      arg /= 3;\n      value = boost::math::tgamma(arg);\n      BOOST_CHECK_EQUAL(value.precision(), digits);\n      result.assign(boost::math::tgamma(mpfr_float_1000(arg)).str());\n      BOOST_CHECK_LE(boost::math::epsilon_difference(value, result), 800);\n   }\n\n   //\n   // Try tanh_sinh integration:\n   //\n   using namespace boost::math::constants;\n   boost::math::quadrature::tanh_sinh<T> integrator;\n   T                                     tol = 500;\n   // Example 1:\n   auto f1         = [](const T& t) { return static_cast<T>(t * boost::math::log1p(t)); };\n   T Q          = integrator.integrate(f1, (T)0, (T)1);\n   T Q_expected = half<T>() * half<T>();\n   BOOST_CHECK_EQUAL(Q.precision(), digits);\n   BOOST_CHECK_EQUAL(Q_expected.precision(), digits);\n   BOOST_CHECK_LE(boost::math::epsilon_difference(Q, Q_expected), tol);\n\n   // Example 2:\n   auto f2    = [](const T& t) { return static_cast<T>(t * t * atan(t)); };\n   Q          = integrator.integrate(f2, (T)0, (T)1);\n   Q_expected = (pi<T>() - 2 + 2 * ln_two<T>()) / 12;\n   BOOST_CHECK_EQUAL(Q.precision(), digits);\n   BOOST_CHECK_EQUAL(Q_expected.precision(), digits);\n   BOOST_CHECK_LE(boost::math::epsilon_difference(Q, Q_expected), tol);\n\n   // Example 3:\n   auto f3    = [](const T& t) { return static_cast<T>(exp(t) * cos(t)); };\n   Q          = integrator.integrate(f3, (T)0, half_pi<T>());\n   Q_expected = boost::math::expm1(half_pi<T>()) * half<T>();\n   BOOST_CHECK_EQUAL(Q.precision(), digits);\n   BOOST_CHECK_EQUAL(Q_expected.precision(), digits);\n   BOOST_CHECK_LE(boost::math::epsilon_difference(Q, Q_expected), tol);\n\n   // Example 4:\n   auto f4    = [](T x) -> T { T t0 = sqrt(x*x + 2); return atan(t0)/(t0*(x*x+1)); };\n   Q          = integrator.integrate(f4, (T)0, (T)1);\n   Q_expected = 5 * pi<T>() * pi<T>() / 96;\n   BOOST_CHECK_EQUAL(Q.precision(), digits);\n   BOOST_CHECK_EQUAL(Q_expected.precision(), digits);\n   BOOST_CHECK_LE(boost::math::epsilon_difference(Q, Q_expected), tol);\n\n   // Example 5:\n   auto f5    = [](const T& t)->T { return sqrt(t) * log(t); };\n   Q          = integrator.integrate(f5, (T)0, (T)1);\n   Q_expected = -4 / (T)9;\n   BOOST_CHECK_EQUAL(Q.precision(), digits);\n   BOOST_CHECK_EQUAL(Q_expected.precision(), digits);\n   BOOST_CHECK_LE(boost::math::epsilon_difference(Q, Q_expected), tol);\n\n   // Example 6:\n   auto f6    = [](const T& t)->T { return sqrt(1 - t * t); };\n   Q          = integrator.integrate(f6, (T)0, (T)1);\n   Q_expected = pi<T>() / 4;\n   BOOST_CHECK_EQUAL(Q.precision(), digits);\n   BOOST_CHECK_EQUAL(Q_expected.precision(), digits);\n   BOOST_CHECK_LE(boost::math::epsilon_difference(Q, Q_expected), tol);\n}\n\nint main()\n{\n#ifdef TEST_MPF_50\n   {\n      std::thread t1(thread_test_proc<boost::multiprecision::mpf_float>, 35);\n      std::thread t2(thread_test_proc<boost::multiprecision::mpf_float>, 55);\n      std::thread t3(thread_test_proc<boost::multiprecision::mpf_float>, 75);\n      std::thread t4(thread_test_proc<boost::multiprecision::mpf_float>, 105);\n      std::thread t5(thread_test_proc<boost::multiprecision::mpf_float>, 305);\n\n      t1.join();\n      t2.join();\n      t3.join();\n      t4.join();\n      t5.join();\n   }\n#endif\n#ifdef TEST_MPFR_50\n   {\n      std::thread t1(thread_test_proc<boost::multiprecision::mpfr_float>, 35);\n      std::thread t2(thread_test_proc<boost::multiprecision::mpfr_float>, 55);\n      std::thread t3(thread_test_proc<boost::multiprecision::mpfr_float>, 75);\n      std::thread t4(thread_test_proc<boost::multiprecision::mpfr_float>, 105);\n      std::thread t5(thread_test_proc<boost::multiprecision::mpfr_float>, 305);\n\n      t1.join();\n      t2.join();\n      t3.join();\n      t4.join();\n      t5.join();\n   }\n#endif\n   return boost::report_errors();\n}\n", "meta": {"hexsha": "d626b9a67d0eb0ab5bd9fe64c20291eb741935f7", "size": 5356, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/multiprecision/test/test_threaded_precision.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/multiprecision/test/test_threaded_precision.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "console/src/boost_1_78_0/libs/multiprecision/test/test_threaded_precision.cpp", "max_forks_repo_name": "vany152/FilesHash", "max_forks_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 34.7792207792, "max_line_length": 108, "alphanum_fraction": 0.6512322629, "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5821968068094904}}
{"text": "// workaround for the annoying boost message in boost 1.69\n#define BOOST_PENDING_INTEGER_LOG2_HPP\n#include <boost/integer/integer_log2.hpp>\n// end workaround\n\n#include <iostream>\n\n#include <gudhi/Coxeter_triangulation.h>\n#include <gudhi/Functions/Function_affine_plane_in_Rd.h>\n#include <gudhi/Functions/Function_Sm_in_Rd.h>\n#include <gudhi/Functions/Cartesian_product.h>\n#include <gudhi/Functions/Linear_transformation.h>\n#include <gudhi/Implicit_manifold_intersection_oracle.h>\n#include <gudhi/Manifold_tracing.h>\n#include <gudhi/Coxeter_triangulation/Cell_complex/Cell_complex.h>\n#include <gudhi/Functions/random_orthogonal_matrix.h>  // requires CGAL\n\n#include <gudhi/IO/build_mesh_from_cell_complex.h>\n#include <gudhi/IO/output_meshes_to_medit.h>\n\nusing namespace Gudhi::coxeter_triangulation;\n\nint main(int argc, char** argv) {\n  // Creating a circle S1 in R2 of specified radius\n  double radius = 1.0;\n  Function_Sm_in_Rd fun_circle(radius, 1);\n\n  // Creating a flat torus S1xS1 in R4 from two circle functions\n  auto fun_flat_torus = make_product_function(fun_circle, fun_circle);\n\n  // Apply a random rotation in R4\n  auto matrix = random_orthogonal_matrix(4);\n  auto fun_flat_torus_rotated = make_linear_transformation(fun_flat_torus, matrix);\n\n  // Computing the seed of the function fun_flat_torus\n  Eigen::VectorXd seed = fun_flat_torus_rotated.seed();\n\n  // Defining a domain function that defines the boundary, which is a hyperplane passing by the origin and orthogonal to\n  // x.\n  Eigen::MatrixXd normal_matrix = Eigen::MatrixXd::Zero(4, 1);\n  for (std::size_t i = 0; i < 4; i++) normal_matrix(i, 0) = -seed(i);\n  Function_affine_plane_in_Rd fun_bound(normal_matrix, -seed / 2);\n\n  // Defining the intersection oracle\n  auto oracle = make_oracle(fun_flat_torus_rotated, fun_bound);\n\n  // Define a Coxeter triangulation scaled by a factor lambda.\n  // The triangulation is translated by a random vector to avoid violating the genericity hypothesis.\n  double lambda = 0.2;\n  Coxeter_triangulation<> cox_tr(oracle.amb_d());\n  cox_tr.change_offset(Eigen::VectorXd::Random(oracle.amb_d()));\n  cox_tr.change_matrix(lambda * cox_tr.matrix());\n\n  // Manifold tracing algorithm\n  using MT = Manifold_tracing<Coxeter_triangulation<> >;\n  using Out_simplex_map = typename MT::Out_simplex_map;\n  std::vector<Eigen::VectorXd> seed_points(1, seed);\n  Out_simplex_map interior_simplex_map, boundary_simplex_map;\n  manifold_tracing_algorithm(seed_points, cox_tr, oracle, interior_simplex_map, boundary_simplex_map);\n\n  // Constructing the cell complex\n  std::size_t intr_d = oracle.amb_d() - oracle.cod_d();\n  Cell_complex<Out_simplex_map> cell_complex(intr_d);\n  cell_complex.construct_complex(interior_simplex_map, boundary_simplex_map);\n\n  // Output the cell complex to a file readable by medit\n  output_meshes_to_medit(3, \"flat_torus_with_boundary\",\n                         build_mesh_from_cell_complex(cell_complex, Configuration(true, true, true, 1, 5, 3),\n                                                      Configuration(true, true, true, 2, 13, 14)));\n\n  return 0;\n}\n", "meta": {"hexsha": "59fe2e2bb5bc00f507d16f7346aea0c19400df03", "size": 3080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Coxeter_triangulation/example/manifold_tracing_flat_torus_with_boundary.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T05:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T05:45:06.000Z", "max_issues_repo_path": "src/Coxeter_triangulation/example/manifold_tracing_flat_torus_with_boundary.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Coxeter_triangulation/example/manifold_tracing_flat_torus_with_boundary.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1917808219, "max_line_length": 120, "alphanum_fraction": 0.761038961, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5820932125290889}}
{"text": "#include <geometry.h>\n#include <tiny_math_types.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(raycast_dop)\n{\n  using std::sqrt;\n\n  typedef tiny::MathTypes<double>   MT;\n  typedef MT::vector3_type          V;\n  typedef MT::real_type             T;\n  typedef MT::value_traits          VT;\n\n  std::vector<V> corners(2u);\n\n  corners[0] = V::make(-1.0,-1.0,-1.0);\n  corners[1] = V::make( 1.0, 1.0, 1.0);\n\n  geometry::DOP<T, 6u> const dop = geometry::make_dop(corners.begin(), corners.end(), geometry::make3<V>() );\n\n  BOOST_CHECK(geometry::is_valid(dop));\n\n  // Hit straigth on\n  {\n    V const r      = V::make( 0.0, 0.0, 1.0);\n    V const p      = V::make( 0.0, 0.0,-3.0);\n\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_dop(ray, dop, q, length);\n\n    BOOST_CHECK( hit );\n\n    BOOST_CHECK_CLOSE( length, 2.0, 0.01);\n    BOOST_CHECK_CLOSE( q(0),  0.0, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  0.0, 0.01);\n    BOOST_CHECK_CLOSE( q(2), -1.0, 0.01);\n  }\n\n  // Hit straigth on corner\n  {\n    V const r      = V::make( 0.0, 0.0, 1.0);\n    V const p      = V::make( -1.0, -1.0,-3.0);\n\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_dop(ray, dop, q, length);\n\n    BOOST_CHECK( hit );\n\n    BOOST_CHECK_CLOSE( length, 2.0, 0.01);\n    BOOST_CHECK_CLOSE( q(0), -1.0, 0.01);\n    BOOST_CHECK_CLOSE( q(1), -1.0, 0.01);\n    BOOST_CHECK_CLOSE( q(2), -1.0, 0.01);\n  }\n\n\n  // Hit straigth on edge\n  {\n    V const r      = V::make( 0.0, 0.0, 1.0);\n    V const p      = V::make( 0.0, -1.0,-3.0);\n\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_dop(ray, dop, q, length);\n\n    BOOST_CHECK( hit );\n\n    BOOST_CHECK_CLOSE( length, 2.0, 0.01);\n    BOOST_CHECK_CLOSE( q(0),  0.0, 0.01);\n    BOOST_CHECK_CLOSE( q(1), -1.0, 0.01);\n    BOOST_CHECK_CLOSE( q(2), -1.0, 0.01);\n  }\n\n\n  // Aligned ray no hitting\n  {\n    V const r      = V::make( 0.0, 0.0, 1.0);\n    V const p      = V::make( -2.0, 0.0,-3.0);\n\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_dop(ray, dop, q, length);\n\n    BOOST_CHECK( !hit );\n\n    BOOST_CHECK_CLOSE( length, VT::infinity(), 0.01);\n    BOOST_CHECK_CLOSE( q(0),  0.0, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  0.0, 0.01);\n    BOOST_CHECK_CLOSE( q(2),  0.0, 0.01);\n  }\n\n\n  // Obligue ray no hitting\n  {\n    V const r      = V::make( 1.0, 1.0, 1.0);\n    V const p      = V::make( 0.0, 0.0,-10.0);\n\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_dop(ray, dop, q, length);\n\n    BOOST_CHECK( !hit );\n\n    BOOST_CHECK_CLOSE( length, VT::infinity(), 0.01);\n    BOOST_CHECK_CLOSE( q(0),  0.0, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  0.0, 0.01);\n    BOOST_CHECK_CLOSE( q(2),  0.0, 0.01);\n  }\n\n\n  // Obligue ray central hit\n  {\n    V const r      = V::make( 1.0,  1.0,  1.0);\n    V const p      = V::make(-2.0, -2.0, -3.0);\n\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_dop(ray, dop, q, length);\n\n    BOOST_CHECK( hit );\n\n    BOOST_CHECK_CLOSE( length, 2*1.732050807568877, 0.01);\n    BOOST_CHECK_CLOSE( q(0),  0.0, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  0.0, 0.01);\n    BOOST_CHECK_CLOSE( q(2), -1.0, 0.01);\n  }\n\n\n  // Obligue ray corner hit\n  {\n    V const r      = V::make( 1.0,  1.0,  1.0);\n    V const p      = V::make( 0.0,  0.0, -2.0);\n\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_dop(ray, dop, q, length);\n\n    BOOST_CHECK( hit );\n\n    BOOST_CHECK_CLOSE( length, 1.732050807568877, 0.01);\n    BOOST_CHECK_CLOSE( q(0),  1.0, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  1.0, 0.01);\n    BOOST_CHECK_CLOSE( q(2), -1.0, 0.01);\n  }\n\n\n  // Obligue ray edge hit\n  {\n    V const r      = V::make( 1.0,  1.0,  1.0);\n    V const p      = V::make( 0.0, -1.0, -2.0);\n\n    geometry::Ray<V> const ray = geometry::make_ray(p, r);\n\n    T       length = VT::zero();\n    V       q      = V::zero();\n\n    bool hit = geometry::compute_raycast_dop(ray, dop, q, length);\n\n    BOOST_CHECK( hit );\n\n    BOOST_CHECK_CLOSE( length, 1.732050807568877, 0.01);\n    BOOST_CHECK_CLOSE( q(0),  1.0, 0.01);\n    BOOST_CHECK_CLOSE( q(1),  0.0, 0.01);\n    BOOST_CHECK_CLOSE( q(2), -1.0, 0.01);\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "9708d6a7ad2d3a830fe82fb49f0d142142a51ba4", "size": 5025, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_dop/geometry_raycast_dop.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_dop/geometry_raycast_dop.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_raycast_dop/geometry_raycast_dop.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.125, "max_line_length": 109, "alphanum_fraction": 0.5568159204, "num_tokens": 1831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5820669403202616}}
{"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 \"constants.h\"\n#include \"pluginHeader.h\"\n\n#include <boost/algorithm/string.hpp> // starts_with\n#include <cstdlib>                    // atoi\n#include <cstring>                    /* strcpy  */\n#include <fstream>                    // ifstream, ofstream\n#include <iomanip>                    // setw\n#include <iostream>\n\nstruct Matrix\n{\n    int width;\n    int height;\n    float* elements;\n};\n\n// Matrix functions\nMatrix* readMatrixFile(const char* filename);\nint writeMatrixFile(const char* filename, const Matrix* matrix);\nvoid displayMatrix(const Matrix* matrix);\nvoid deleteMatrix(Matrix*& matrix);\n\n// matrixMulOnDevice is defined in \"matrix.cu\"\nextern void matrixMulOnDevice(const Matrix* A, const Matrix* B, Matrix* C);\nvoid matrixMulOnHost(const Matrix* A, const Matrix* B, Matrix* C);\n\nenum inputs\n{\n    INPUTA,\n    INPUTB,\n    OUTPUT,\n    DISPLAY\n};\n\n/* globals */\nchar params[][256] = {\"inputFileMatrixA.txt\", \"inputFileMatrixB.txt\", \"OutputFileMatrixC.txt\", \"0\"};\nconst int NUM_ARGS = sizeof params / sizeof params[0];\nclock_t total_t = 0;\nconst char* PARAM_INFO = \"inputFileMatrixA,inputFileMatrixB,OutputFileMatrixC,displayResult\";\n\n/******************************************************************************\n * main()\n * - this function is not used by the plugin, but this can be built as\n *   a standalone executable\n ******************************************************************************/\nint main(int argc, char** argv)\n{\n    if (argc == 1)\n    {\n        std::cout << \"Usage: \" << argv[0] << \" inputFileA inputFileB outputFileC displayResult\\n\";\n        return 0;\n    }\n\n    if (argc > 1)\n    {\n        if (strcmp(argv[1], \"--help\") == 0)\n        {\n            displayPluginInfo();\n            return 0;\n        }\n        strcpy(params[INPUTA], argv[1]);\n    }\n\n    if (argc > 2)\n        strcpy(params[INPUTB], argv[2]);\n\n    if (argc > 3)\n        strcpy(params[OUTPUT], argv[3]);\n\n    if (argc > 4)\n        strcpy(params[DISPLAY], argv[4]);\n\n    return run();\n}\n\n///////////////////////////// MATRIX FUNCTIONS ////////////////////////////////\n\n/******************************************************************************\n * TODO: implement me\n * matrixMulOnHost\n * - does the computation in serial, using the CPU\n ******************************************************************************/\nvoid matrixMulOnHost(const Matrix* A, const Matrix* B, Matrix* C) {}\n\n/******************************************************************************\n * readMatrixFile()\n * - opens the file for reading\n * - allocates the matrix, read the elements, return the allocated matrix\n ******************************************************************************/\nMatrix* readMatrixFile(const char* filename)\n{\n    // open the file\n    std::ifstream fin(filename);\n    if (!fin)\n        return nullptr;\n\n    int rows = 0;\n    int cols = 0;\n    float* elements = nullptr;\n    Matrix* matrix = nullptr;\n    std::string line;\n\n    // read the 1st 2 lines ~ should contain \"rows=\" and \"cols=\"\n    for (int i = 0; i < 2; i++)\n    {\n        getline(fin, line);\n        if (boost::starts_with(line, \"rows=\"))\n            rows = atoi(line.c_str() + 5);\n        else if (boost::starts_with(line, \"cols=\"))\n            cols = atoi(line.c_str() + 5);\n    }\n\n    if (rows <= 0 || cols <= 0)\n        return nullptr;\n\n    elements = new float[rows * cols](); // allocate the array of elements\n\n    // loop, reading al the elements into the array\n    int i = 0;\n    while (fin >> elements[i++] && (i < (rows * cols)))\n        ;\n\n    fin.close();\n\n    // allocate and assign the matrix items\n    matrix = new Matrix;\n    matrix->width = cols;\n    matrix->height = rows;\n    matrix->elements = elements;\n\n    return matrix;\n}\n\n/******************************************************************************\n * writeMatrix()\n * - writes the matrix to the file\n ******************************************************************************/\nint writeMatrixFile(const char* filename, const Matrix* matrix)\n{\n    // open the file\n    std::ofstream fout(filename);\n    if (!fout || !matrix)\n    {\n        return ERROR;\n    }\n\n    // write the 1st couple of header lines\n    fout << \"rows=\" << matrix->height << std::endl << \"cols=\" << matrix->width << std::endl << std::endl;\n\n    int padding = 4; // TODO: dynamically figure out the padding size\n\n    for (int row = 0; row < matrix->height; ++row)\n    {\n        for (int col = 0; col < matrix->width; ++col)\n            fout << std::setw(padding) << matrix->elements[row * matrix->width + col] << \" \";\n        fout << std::endl;\n    }\n    fout.close();\n    return OK;\n}\n\n/******************************************************************************\n * displays the Matrix elements\n ******************************************************************************/\nvoid displayMatrix(const Matrix* matrix)\n{\n    if (matrix)\n    {\n        int row;\n        int col;\n        for (row = 0; row < matrix->height; ++row)\n        {\n            for (col = 0; col < matrix->width; ++col)\n                std::cout << matrix->elements[row * matrix->width + col] << \" \";\n            std::cout << std::endl;\n        }\n    }\n}\n\n/******************************************************************************\n * deallocates the matrix elements\n ******************************************************************************/\nvoid deleteMatrix(Matrix*& matrix)\n{\n    if (matrix)\n    {\n        if (matrix->elements)\n        {\n            delete[] matrix->elements;\n            matrix->elements = nullptr;\n        }\n        matrix = nullptr;\n    }\n}\n\n///////////////////////////// PLUGIN FUNCTIONS ////////////////////////////////\n\n/******************************************************************************\n * run()\n * - computes the matrix multiplication: C = A * B\n * - reads the input files from the parameters: A = params[0], B = params[1]\n * - writes the output result C to the file set in params[2]\n * - if params[3] is set, then display the result to the screen\n ******************************************************************************/\nint run()\n{\n    clock_t start_t;\n    clock_t end_t;\n    total_t = 0; // reset the clock counter\n\n    // open and allocate the input Matrix Files\n    Matrix* A = readMatrixFile(params[INPUTA]);\n    Matrix* B = readMatrixFile(params[INPUTB]);\n    if (!A || !B)\n    {\n        std::cout << \"index: \" << params[!A ? 0 : 1] << std::endl;\n        std::cout << \"Failed to open Matrix file: \\\"\" << params[!A ? 0 : 1] << \"\\\"\\n\";\n        return ERROR;\n    }\n\n    if (A->width != B->height) // C = A * B = (example): 3x4 * 4x5 = 3x5\n    {\n        std::cout << \"Invalid matrix dimensions!\\n\"\n                  << \"Can't multiply \" << A->height << 'x' << A->width << \" * \" << B->height << 'x' << B->width\n                  << std::endl;\n        return ERROR;\n    }\n\n    // allocate the output Matrix\n    Matrix* C = nullptr;\n    C = new Matrix;\n    C->height = A->height;\n    C->width = B->width;\n    C->elements = new float[C->height * C->width]();\n\n#ifdef DEBUG\n    std::cout << \"Multiplying C = A * B\\n\";\n    std::cout << \"A:\\n\";\n    displayMatrix(A);\n    std::cout << \"B:\\n\";\n    displayMatrix(B);\n#endif\n\n    // compute the result using the GPU\n    start_t = clock();\n    matrixMulOnDevice(A, B, C); // using CUDA\n    end_t = clock();\n    total_t = end_t - start_t;\n\n    // write the result to the file\n    if (writeMatrixFile(params[OUTPUT], C) == ERROR)\n    {\n        std::cout << \"Failed to write Matrix to: \\\"\" << params[OUTPUT] << \"\\\"\\n\";\n    }\n\n    // check if the result should be displayed\n    if (atoi(params[DISPLAY])) // params[DISPLAY] => \"0\" or \"1\"\n    {\n        std::cout << \"result: \\n\";\n        displayMatrix(C);\n    }\n\n    // no memory leaks\n    deleteMatrix(A);\n    deleteMatrix(B);\n    deleteMatrix(C);\n\n    return OK;\n}\n\n/******************************************************************************\n * setParams()\n * - input: DELIM separated buffer\n * - splits the buffer and sets the \"params\" to the new passed in parameters\n * - this function only works if all the parameters are passed in to be set\n ******************************************************************************/\nint setParams(const char* buffer)\n{\n    int bufferSize = strlen(buffer) + 1; // +1 for '\\0'\n\n    // if the buffer is empty, then just return\n    if (bufferSize == 1 && NUM_ARGS == 0)\n        return OK;\n\n    // check if the passed in buffer will fit in our params\n    if (bufferSize > NUM_ARGS * BUFFER_SIZE)\n        return ERROR;\n\n    // count the number of arguments by counting the number of delimiters\n    int commas = 0;\n    const char* p;\n    for (p = buffer; *p; p++)\n        if (*p == DELIM)\n            commas++;\n\n    if (commas + 1 == NUM_ARGS)\n    {\n        // make a copy of the input buffer (so strtok doesnt change the original)\n        char buf[bufferSize];\n        strcpy(buf, buffer);\n        char* arg;\n        int i;\n\n        // copy the arguments to the params array\n        arg = strtok(buf, DELIM_STR);\n        for (i = 0; i < NUM_ARGS && arg; ++i)\n        {\n            strcpy(params[i], arg);\n            arg = strtok(nullptr, DELIM_STR);\n        }\n\n        return OK; // OK\n    }\n    return ERROR; // NOT_OK\n}\n\n/******************************************************************************\n * getParams()\n * - builds a DELIM delimited string of the current parameter values\n * - sets the \"buffer\" input to the newly built cstring\n ******************************************************************************/\nint getParams(char* buffer, int bufferSize)\n{\n    int i;\n\n    // count the size needed\n    int size = 0;\n    for (i = 0; i < NUM_ARGS; i++)\n        size += strlen(params[i]);\n    size += NUM_ARGS - 1;\n\n    // the size of the array must be big enough\n    if (bufferSize < size || bufferSize < 1)\n        return ERROR; // ERROR\n\n    // join the arguments into a DELIM separated list\n    buffer[0] = '\\0';\n    for (i = 0; i < NUM_ARGS; i++)\n    {\n        strcat(buffer, params[i]);\n        strcat(buffer, DELIM_STR); // NOTE: could use DC1 as delimeter\n    }\n    buffer[size] = '\\0'; // delete the last inserted comma\n    return OK;           // OK\n}\n\n/******************************************************************************\n * returns info / help on how to use this plugin\n ******************************************************************************/\nvoid* displayPluginInfo()\n{\n    std::cout << \"The Matrix plugin is intended to quickly compute the multiplication of matrices.\\n\"\n              << \"The paramaters that can be set are as follows:\\n\"\n              << \"\\t* inputFileMatrixA - the (left) matrix file operand\\n\"\n              << \"\\t* inputFileMatrixB - the (right) matrix file operand\\n\"\n              << \"\\t* inputFileMatrixC - the resulting matrix file (C = A * B)\\n\"\n              << \"\\t* displayResult - this option can be set to '0' or '1'.\\n \"\n              << \"                         if set to true, the result of the operation will be\\n\"\n              << \"                          displayed on the screen when done computing.\\n\"\n              << \"Note: the input files follow a very specific type of format.\\n\"\n              << \"They must list the number of rows and cols, followed by a blank line.\\n\"\n              << \"Following that, each matrix row should be located in a single line.\\n\";\n\n    return nullptr;\n}\n\n/******************************************************************************\n * returns a comma-separated list of the parameter names\n ******************************************************************************/\nconst char* getParamInfo()\n{\n    return PARAM_INFO;\n}\n\n/******************************************************************************\n * returns the number of arguments this plugin contains\n ******************************************************************************/\nconst int getNumArgs()\n{\n    return NUM_ARGS;\n}\n\n/******************************************************************************\n * returns how many milliseconds it took to run the main program\n ******************************************************************************/\nclock_t getRunTime()\n{\n    return total_t;\n}\n", "meta": {"hexsha": "2d9a6d9297d4ec64eddf812c67004fb16ddb1db9", "size": 12183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plugins/matrix.cpp", "max_stars_repo_name": "paulohefagundes/gpgpu_plugins", "max_stars_repo_head_hexsha": "0f09e757a2ff7406c05a307fbe5f1d32f2d7fbfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/plugins/matrix.cpp", "max_issues_repo_name": "paulohefagundes/gpgpu_plugins", "max_issues_repo_head_hexsha": "0f09e757a2ff7406c05a307fbe5f1d32f2d7fbfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plugins/matrix.cpp", "max_forks_repo_name": "paulohefagundes/gpgpu_plugins", "max_forks_repo_head_hexsha": "0f09e757a2ff7406c05a307fbe5f1d32f2d7fbfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-13T15:25:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-13T15:25:15.000Z", "avg_line_length": 31.1585677749, "max_line_length": 111, "alphanum_fraction": 0.4717228926, "num_tokens": 2635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5819831292016171}}
{"text": "#include <CAN/PCANDevice.h>\n#include <CAN/Registers.h>\n#include <CAN/RealTimeTask.hpp>\n#include <string.h>\n#include <iostream>\n#include <unistd.h>\n#include <cmath>\n\n#include <NomadBLDC/NomadBLDC.h>\n#include <nlohmann/json.hpp>\n#include <zmq.hpp>\n\n// Dart\n#include <dart/dynamics/Skeleton.hpp>\n#include <dart/dynamics/FreeJoint.hpp>\n#include <dart/dynamics/WeldJoint.hpp>\n#include <dart/dynamics/BallJoint.hpp>\n#include <dart/dynamics/BoxShape.hpp>\n#include <dart/simulation/World.hpp>\n#include <dart/utils/urdf/DartLoader.hpp>\n\n#include <dart/gui/osg/osg.hpp>\n\n\n#define DEVICE \"/dev/pcanusbfd32\"\n\nPCANDevice can;\n\ndouble q1_ref = 0.0f;\ndouble q2_ref = 0.0f;\ndouble frequency = 1.0f;\ndouble diameter = 0.05f;\n\ndouble home = 0.0308f;\ndouble home2 = -0.312458f;\n\nEigen::Vector2d foot_pos_des_;\nEigen::Vector2d foot_vel_des_;\n\nEigen::Vector2d k_P(2500, 2500);\nEigen::Vector2d k_D(20, 20);\n\n\ntypedef enum\n{\n    Zero = 0,\n    Homing = 1,\n    PreStand = 2,\n    Stand = 3,\n    Crouch = 4\n} FSMState_e;\n\n\nFSMState_e current_state_ = Zero;\nint debounce = 0;\n\nbool AlmostEquals(double A, double B, double epsilon = 0.005f)\n{\n    return (fabs(A - B) < epsilon);\n}\n\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\nnamespace Common\n{\n    CubicPolynomialTrajectory::CubicPolynomialTrajectory(double q_f, double t_f)\n        : q_0_(0.0), q_f_(q_f), v_0_(0.0), v_f_(0.0), t_0_(0.0), t_f_(t_f)\n    {\n        // Compute Coefficients\n        ComputeCoeffs();\n    }\n    CubicPolynomialTrajectory::CubicPolynomialTrajectory(double q_0, double q_f, double v_0, double v_f, double t_0, double t_f)\n        : q_0_(q_0), q_f_(q_f), v_0_(v_0), v_f_(v_f), t_0_(t_0), t_f_(t_f)\n    {\n        // Compute Coefficients\n        ComputeCoeffs();\n    }\n\n    CubicPolynomialTrajectory::CubicPolynomialTrajectory() // Empty Trajectory\n        : q_0_(0.0), q_f_(0.0), v_0_(0.0), v_f_(0.0), t_0_(0.0), t_f_(0.0)\n    {\n        // Compute Coefficients\n        ComputeCoeffs();\n    }\n\n    void CubicPolynomialTrajectory::Generate(double q_f, double t_f)\n    {\n        q_0_ = 0.0;\n        q_f_ = q_f;\n        v_0_ = 0.0;\n        v_f_ = 0.0;\n        t_0_ = 0.0;\n        t_f_ = t_f;\n\n        ComputeCoeffs();\n    }\n\n    void CubicPolynomialTrajectory::Generate(double q_0, double q_f, double v_0, double v_f, double t_0, double t_f)\n    {\n        q_0_ = q_0;\n        q_f_ = q_f;\n        v_0_ = v_0;\n        v_f_ = v_f;\n        t_0_ = t_0;\n        t_f_ = t_f;\n\n        ComputeCoeffs();\n    }\n\n    // TODO: Check for valid t between 0<->t_f\n    double CubicPolynomialTrajectory::Position(double t)\n    {\n        // Trim Position\n        // TODO: Function for this trimming/mapping\n        double t_eval = std::min(t, t_f_);\n        t_eval = std::max(t_eval, t_0_);\n        return a_(0) + a_(1) * t_eval + a_(2) * t_eval * t_eval + a_(3) * t_eval * t_eval * t_eval;\n    }\n    double CubicPolynomialTrajectory::Velocity(double t)\n    {\n        // Trim Position\n        // TODO: Function for this trimming/mapping\n        double t_eval = std::min(t, t_f_);\n        t_eval = std::max(t_eval, t_0_);\n        return a_(1) + 2 * a_(2) * t_eval + 3 * a_(3) * t_eval * t_eval;\n    }\n    double CubicPolynomialTrajectory::Acceleration(double t)\n    {\n        // Trim Position\n        // TODO: Function for this trimming/mapping\n        double t_eval = std::min(t, t_f_);\n        t_eval = std::max(t_eval, t_0_);\n        return 2 * a_(2) + 6 * a_(3) * t_eval;\n    }\n\n    void CubicPolynomialTrajectory::ComputeCoeffs()\n    {\n\n        Eigen::Matrix4d C; // Constraints\n        C << 1, t_0_, t_0_ * t_0_, t_0_ * t_0_ * t_0_,\n            0, 1, 2 * t_0_, 3 * t_0_ * t_0_,\n            1, t_f_, t_f_ * t_f_, t_f_ * t_f_ * t_f_,\n            0, 1, 2 * t_f_, 3 * t_f_ * t_f_;\n\n        Eigen::Vector4d b;\n        b << q_0_, v_0_, q_f_, v_f_;\n\n        // Solve for Coefficients\n        a_ = C.lu().solve(b);\n    }\n} // namespace Common\n\n\n\n Common::CubicPolynomialTrajectory com_traj_;\n\n\nclass LegTest : public Realtime::RealTimeTaskNode\n{\n\npublic:\n    // Block Diagram Class For Systems Task Node\n    // name = Task Name\n    // T_s = Sample Time (-1 for inherit)\n    LegTest(const std::string &name, const double T_s = -1);\n    virtual void Exit();\n\nprotected:\n    // Overriden Run Function\n    virtual void Run();\n\n    // Pre-Run Setup Routine.  Setup any one time initialization here.\n    virtual void Setup();\n\n    // TODO: Load Dart URDF\n    void SetupDART();\n\n    // Time\n    double time_;\n\n    // NOMAD Servos\n    NomadBLDC *servo1;\n    NomadBLDC *servo2;\n\n    // Zero MQ Context for PlotJuggler\n    zmq::context_t ctx;\n    zmq::socket_t *publisher;\n\n    // DART Objects\n    dart::dynamics::SkeletonPtr robot_;\n\n    dart::dynamics::DegreeOfFreedomPtr hfe;\n    dart::dynamics::DegreeOfFreedomPtr kfe;\n\n    dart::dynamics::BodyNodePtr hip_body_;\n    dart::dynamics::BodyNodePtr foot_body_;\n\n    Eigen::Vector2d foot_pos_;\n    Eigen::Vector2d foot_vel_;\n\n    Eigen::Vector2d q_;\n    Eigen::Vector2d qd_;\n    Eigen::Vector2d qdd_;\n\n    Eigen::MatrixXd J_; // Leg Jacobian\n\n    Eigen::Matrix2d k_P_cartesian_; // Cartesian P Gains\n    Eigen::Matrix2d k_D_cartesian_; // Cartesian D Gains\n\n    Eigen::Vector2d force_output = Eigen::Vector2d::Zero();\n\n    Eigen::VectorXd torque_output;\n};\n\nLegTest::LegTest(const std::string &name, const double T_s) : Realtime::RealTimeTaskNode(name, T_s, Realtime::Priority::HIGH, -1, PTHREAD_STACK_MIN), time_(0.0)\n{\n}\n\nvoid LegTest::SetupDART()\n{\n    // Load URDF\n    dart::utils::DartLoader loader;\n    std::string urdf = std::getenv(\"NOMAD_RESOURCE_PATH\");\n    urdf.append(\"/LegTest/Leg.urdf\");\n\n    robot_= loader.parseSkeleton(urdf);\n    robot_->getDof(\"j_hfe\")->setPosition(0.0f);\n    robot_->getDof(\"j_kfe\")->setPosition(0.0f);\n\n    //nomad->getJoint(\"j_kfe\")->setPositionLimitEnforced(true);\n    //robot_->getDof(\"j_kfe\")->setDampingCoefficient(1.5f);\n    //robot_->getDof(\"j_hfe\")->setDampingCoefficient(1.5f);\n    //nomad->getDof(\"j_kfe\")->setPositionLimits(0.0f, 2.0);\n\n    robot_->getDof(\"slider\")->setPositionLimits(-0.0, 0.0);\n    robot_->getJoint(\"slider\")->setPositionLimitEnforced(true);\n\n    hfe = robot_->getDof(\"j_hfe\");\n    kfe = robot_->getDof(\"j_kfe\");\n\n    hip_body_ = robot_->getBodyNode(\"HFE_Actuator1\");\n    foot_body_ = robot_->getBodyNode(\"Foot1\");\n\n    // Fix our base link (the stand)\n    robot_->getRootBodyNode()->moveTo<dart::dynamics::WeldJoint>(nullptr);\n\n    robot_->computeForwardKinematics();\n    robot_->computeForwardDynamics();\n\n    // Set Friction\n    //std::cout << nomad->getBodyNode(\"foot\")->getFrictionCoeff() << std::endl;\n    //nomad->getBodyNode(\"foot\")->setFrictionCoeff(10.8);\n}\nvoid LegTest::Run()\n{\n    auto start_time = std::chrono::high_resolution_clock::now();\n    time_ += dt_actual_;\n\n    q_[0] = servo1->GetPosition();// + q1_ref;\n    qd_[0] = servo1->GetVelocity();\n    qdd_[0]= servo1->GetTorque();\n\n    q_[1] = servo2->GetPosition();// + q2_ref;\n    qd_[1] = servo2->GetVelocity();\n    qdd_[1]= servo2->GetTorque();\n\n    robot_->setPosition(0, 0);\n    robot_->setVelocity(0, 0);\n    robot_->setForce(0, 0);\n\n    robot_->setPosition(1, q_[0]);\n    robot_->setVelocity(1, qd_[0]);\n    robot_->setForce(1, qdd_[0]);\n\n    robot_->setPosition(2, q_[1]);\n    robot_->setVelocity(2, qd_[1]);\n    robot_->setForce(2, qdd_[1]);\n\n    robot_->computeForwardKinematics();\n    robot_->computeForwardDynamics();\n\n    J_ = robot_->getLinearJacobian(foot_body_, hip_body_);\n    J_ = J_.bottomRows(2);\n    \n    foot_pos_ = foot_body_->getTransform(hip_body_).translation().tail(2);\n    foot_vel_ = (J_ * robot_->getVelocities()).tail(2);\n\n    Eigen::Vector3d torque;\n    double home_target = 0.2f;\n\n    switch (current_state_)\n    {\n    case FSMState_e::Homing:\n        //std::cout << \" STATE HOMING \" << std::endl;\n            servo1->ClosedLoopTorqueCommand(20.0f, 0.75f, home_target, 0.0f, 0.0f);\n            servo2->ClosedLoopTorqueCommand(20.0f, 0.75f, 0.0f, 0.0f, 0.0f);\n\n            if(AlmostEquals(q_[0], home_target, 0.1f))\n            {\n               // std::cout << \"Arrived!\" << std::endl;\n                debounce++;\n\n                if(debounce > 1000)\n                {\n                   // std::cout << \"NEXT STATE!\" << std::endl;\n                   time_ = 0.0f;\n                   com_traj_.Generate(foot_pos_[1], -0.42f, 0.0, 0.0, 0.0, 1.0f);\n                   current_state_ = FSMState_e::Stand;\n                }\n            }\n            else\n            {\n                //std::cout << \"Test: \" << q_[0] << std::endl;\n                debounce = 0;\n            }\n            // Check Position then goto PRESTAND\n        break;\n    case FSMState_e::Stand:\n\n        foot_pos_des_[1] = com_traj_.Position(time_);\n        foot_vel_des_[1] = com_traj_.Velocity(time_);\n\n        foot_pos_des_[0] = 0.01f;\n        foot_vel_des_[0] = 0.0f;\n\n        k_P_cartesian_ = k_P.asDiagonal();\n        k_D_cartesian_ = k_D.asDiagonal();\n        force_output = Eigen::Vector2d::Zero();\n        force_output += k_P_cartesian_ * (foot_pos_des_ - foot_pos_);\n        force_output += k_D_cartesian_ * (foot_vel_des_ - foot_vel_);\n\n        torque_output = J_.transpose() * force_output + robot_->getGravityForces() * 1.1f;\n\n        servo1->ClosedLoopTorqueCommand(0.0f, 0.0f, 0.0f, 0.0f, torque_output[1]);\n        servo2->ClosedLoopTorqueCommand(0.0f, 0.0f, 0.0f, 0.0f, torque_output[2]);\n\n        if (time_ > 1.0f)\n        {\n            time_ = 0.0f;\n            com_traj_.Generate(foot_pos_[1], -0.27f, 0.0, 0.0, 0.0, 0.3f);\n            current_state_ = FSMState_e::Crouch;\n\n            std::cout << \"GO TO CROUCH\" << std::endl;\n        }\n\n        break;\n    case FSMState_e::Crouch:\n\n        foot_pos_des_[0] = 0.01f;\n        foot_vel_des_[0] = 0.0f;\n\n        foot_pos_des_[1] = com_traj_.Position(time_);\n        foot_vel_des_[1] = com_traj_.Velocity(time_);\n\n\n        k_P_cartesian_ = k_P.asDiagonal();\n        k_D_cartesian_ = k_D.asDiagonal();\n        force_output = Eigen::Vector2d::Zero();\n        force_output += k_P_cartesian_ * (foot_pos_des_ - foot_pos_);\n        force_output += k_D_cartesian_ * (foot_vel_des_ - foot_vel_);\n\n        torque_output = J_.transpose() * force_output + robot_->getGravityForces() * 1.1f;\n\n        servo1->ClosedLoopTorqueCommand(0.0f, 0.0f, 0.0f, 0.0f, torque_output[1]);\n        servo2->ClosedLoopTorqueCommand(0.0f, 0.0f, 0.0f, 0.0f, torque_output[2]);\n\n        if (time_ > 0.6f)\n        {\n            time_ = 0.0f;\n            com_traj_.Generate(foot_pos_[1], -0.42f, 0.0, 0.0, 0.0, 0.27f);\n            current_state_ = FSMState_e::Stand;\n\n            std::cout << \"GO TO STAND\" << std::endl;\n        }\n\n\n        break;\n    default:\n        std::cout << \"DEFAULT\" << std::endl;\n        break;\n    }\n\n   // foot_pos_des_[0] = home;// + diameter * std::cos(2 * M_PI * frequency * time_);\n   // foot_pos_des_[1] = home2;// + diameter * std::sin(2 * M_PI * frequency * time_);\n\n  /*  Eigen::Vector2d force_output = Eigen::Vector2d::Zero();\n    Eigen::Vector2d tau_output;\n\n    Eigen::Vector2d k_P(600, 600);\n    Eigen::Vector2d k_D(2, 2);\n\n    k_P_cartesian_ = k_P.asDiagonal();\n    k_D_cartesian_ = k_D.asDiagonal();\n\n    force_output += k_P_cartesian_ * (foot_pos_des_ - foot_pos_);\n    force_output += k_D_cartesian_ * (foot_vel_des_ - foot_vel_);\n\n    Eigen::VectorXd torque = J_.transpose() * force_output + robot_->getGravityForces()*1.3f;\n\n    servo1->ClosedLoopTorqueCommand(0.0f, 0.0f, 0.0f, 0.0f, 0.0f);//torque[1]);\n    servo2->ClosedLoopTorqueCommand(0.0f, 0.0f, 0.0f, 0.0f, 0.0f);//torque[2]);*/\n\n    // Update DART Here\n    nlohmann::json test = {\n        {\"timestamp\", time_},\n        {\"motor\",\n            {{\"Foot_Pos_1\", foot_pos_[0]},\n            {\"tau_ref_1\", torque[1]},\n            {\"Foot_Des_1\",foot_pos_des_[0]},\n            {\"tau_1\", qdd_[0]},\n            {\"Foot_Pos_2\", foot_pos_[1]}, \n            {\"tau_ref_2\", torque[2]},\n            {\"Foot_Des_2\", foot_pos_des_[1]},\n            {\"tau_2\", qdd_[1]},\n            {\"Q_1\", q_[0]},\n            {\"Q_2\", q_[1]},}\n        }\n    };\n\n    auto data = nlohmann::json::to_msgpack(test);\n    zmq::message_t message(data.size());\n    memcpy(message.data(), &data[0], data.size());\n    publisher->send(message, zmq::send_flags::dontwait);\n\n    auto time_now = std::chrono::high_resolution_clock::now();\n    auto total_elapsed = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start_time).count();\n}\n\nvoid LegTest::Setup()\n{\n    // TODO: We need some sort of exceptions here if setup fails\n    CANDevice::Config_t config;\n    config.bitrate = 1e6; //1mbps\n    config.d_bitrate = 5e6; //2mbps\n    config.sample_point = 0.80f; //87.5% \n    config.d_sample_point = 0.625f; //60%\n    config.clock_freq = 80e6; // 80mhz // Read from driver?  \n    config.mode_fd = 1; // FD Mode\n\n    if(!can.Open(DEVICE, config, true))\n    {\n        std::cout << \"Unable to open CAN Device\" << std::endl;\n        return;\n    }\n\n    // Setup Filters\n    can.ClearFilters(); // Clear Existing/Reset.  Filters are saved on the device hardware.  Must make sure to clear\n    can.AddFilter(1, 2); // Only Listen to messages on id 1.  \n\n    servo1 = new NomadBLDC(1, 0x10, &can);\n    servo1->SetName(\"INPUT\");\n    if(!servo1->Connect())\n    {\n        std::cout << \"[ERROR]: Unable to connect to Nomad Servo!\" << std::endl;\n        exit(1);\n    }\n\n    std::cout << \"Nomad Servo: \" << \"[\" << servo1->GetName() << \"] : \" << servo1->GetServoId() << \" Connected!\" << std::endl;\n\n    servo2 = new NomadBLDC(2, 0x11, &can);\n    servo2->SetName(\"INPUT2\");\n    if(!servo2->Connect())\n    {\n        std::cout << \"[ERROR]: Unable to connect to Nomad Servo!\" << std::endl;\n        exit(1);\n    }\n\n    std::cout << \"Nomad Servo: \" << \"[\" << servo2->GetName() << \"] : \" << servo2->GetServoId() << \" Connected!\" << std::endl;\n\n    // Setup ZMQ\n    publisher = new zmq::socket_t(ctx, ZMQ_PUB);\n    std::string transport(\"tcp://*:9872\");\n    publisher->bind(transport);\n\n    std::cout << \"Please Zero Ac`tuator.  Enter to Continue.\" << std::endl;\n    getchar();\n\n    // Load DART\n    SetupDART();\n\n    servo1->ZeroOutput();\n    usleep(30000);\n    servo2->ZeroOutput();\n    usleep(30000);\n\n    // Start Motor Control Mode\n    usleep(8000000);\n    servo1->SetControlMode(PD_MODE);\n    servo2->SetControlMode(PD_MODE);\n\n    servo1->ClosedLoopTorqueCommand(0.0, 0.0f, 0.0f, 0.0f, 0.0f);\n    servo2->ClosedLoopTorqueCommand(0.0, 0.0f, 0.0f, 0.0f, 0.0f);\n\n    usleep(30000);\n\n    // Get Initial Values\n    q_[0] = servo1->GetPosition();\n    qd_[0] = servo1->GetVelocity();\n    qdd_[0]= servo1->GetTorque();\n\n    q_[1] = servo2->GetPosition();\n    qd_[1] = servo2->GetVelocity();\n    qdd_[1]= servo2->GetTorque();\n\n    robot_->setPosition(0, 0);\n    robot_->setVelocity(0, 0);\n    robot_->setForce(0, 0);\n\n    robot_->setPosition(1, q_[0]);\n    robot_->setVelocity(1, qd_[0]);\n    robot_->setForce(1, qdd_[0]);\n\n    robot_->setPosition(2, q_[1]);\n    robot_->setVelocity(2, qd_[1]);\n    robot_->setForce(2, qdd_[1]);\n\n    robot_->computeForwardKinematics();\n    robot_->computeForwardDynamics();\n\n    J_ = robot_->getLinearJacobian(foot_body_, hip_body_);\n    J_ = J_.bottomRows(2);\n\n    foot_pos_ = foot_body_->getTransform(hip_body_).translation().tail(2);\n    foot_vel_ = (J_ * robot_->getVelocities()).tail(2);\n    foot_pos_des_ = foot_pos_;\n\n    std::cout << \"Press Key to Start Control.\" << std::endl;\n    usleep(5000000);\n    current_state_ = FSMState_e::Homing;\n    std::cout << \"Foot Pos Here: \" << foot_pos_[0] << \", \" << foot_pos_[1] << std::endl;\n}\n\nvoid LegTest::Exit()\n{\n    std::cout << \"Exiting!\" << std::endl;\n\n    // Set back to idle.  In theory when no commands are sent it should auto back to idle or edamp?\n    servo1->SetControlMode(IDLE_MODE);\n    servo2->SetControlMode(IDLE_MODE);\n}\n\n\nint main(int argc, char *argv[])\n{\n    Realtime::RealTimeTaskManager::Instance();\n    if (!Realtime::RealTimeTaskManager::EnableRTMemory(500 * 1024 * 1024)) { // 500MB\n        std::cout << \"Error configuring Realtime Memory Requiremets!  Realtime Execution NOT guaranteed.\" << std::endl;\n    }\n    else {\n        std::cout << \"Real Time Memory Enabled!\" << std::endl;\n    }\n\n    LegTest pj_Node(\"Test\", 1/1000.0f); //500hz\n    pj_Node.SetStackSize(1024 * 1024);\n    pj_Node.SetTaskPriority(Realtime::Priority::HIGHEST);\n    pj_Node.SetCoreAffinity(2);\n    pj_Node.Start();\n\n    char input;\n    std::cin >> input;\n    if(input == 'q') {\n        std::cout << \"Got Q:\" << std::endl;\n    }\n\n    pj_Node.Exit();\n    pj_Node.Stop();\n}\n", "meta": {"hexsha": "4a0137816a26583e287e5e18bb0636d999b8508d", "size": 17306, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Hardware/Actuator/NomadBLDC/Tools/CANTest/NomadBLDC/test/leg_test.cpp", "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": "Hardware/Actuator/NomadBLDC/Tools/CANTest/NomadBLDC/test/leg_test.cpp", "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": "Hardware/Actuator/NomadBLDC/Tools/CANTest/NomadBLDC/test/leg_test.cpp", "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": 28.7475083056, "max_line_length": 160, "alphanum_fraction": 0.6051658384, "num_tokens": 5451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5819831051318515}}
{"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\u00e9dif, Olivier Tournaire, Didier Boldo\nemail : librjmcmc@ign.fr\n\nThis software is a generic C++ library for stochastic optimization.\n\nThis software is governed by the CeCILL license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty and the software's author, the holder of the\neconomic rights, and the successive licensors have only limited liability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading, using, modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean that it is complicated to manipulate, and that also\ntherefore means that it is reserved for developers and experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and, more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n\n***********************************************************************/\n\n#ifndef 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": "#include \"rank_commitment.h\"\n#include <NTL/GF2E.h>\n#include <NTL/GF2XFactoring.h>\n#include <utils/utils.h>\n\nvoid rank::rank_commitment::init(rank_commitment::context_t *context) {\n    context->irred_poly = NTL::BuildIrred_GF2X(EM);\n    NTL::GF2E::init(context->irred_poly);\n\n    context->is_init = 1;\n}\n\nvoid rank::rank_commitment::generate_public_key(\n        public_key_t *public_key) {\n\n    utils::generate_random_matrix_gf2e(\n            public_key->G,\n            K,\n            EN);\n}\n\nvoid rank::rank_commitment::generate_commitment(\n        NTL::vec_GF2E &c,\n        const NTL::vec_GF2 &s,\n        const NTL::vec_GF2 &m,\n        const NTL::mat_GF2E &g,\n        const NTL::vec_GF2E &e) {\n\n    auto s_m = utils::gf2e_from_two_gf2(s, m);\n    c = (s_m * g) + e;\n}\n\nvoid rank::rank_commitment::generate_commitment_without_e(\n        NTL::vec_GF2E &c,\n        const NTL::vec_GF2 &s,\n        const NTL::vec_GF2 &m,\n        const NTL::mat_GF2E &g) {\n\n    auto s_m = utils::gf2e_from_two_gf2(s, m);\n\n    NTL::vec_GF2E e;\n    utils::generate_vector_of_specific_rank(\n            e,\n            EN,\n            RHO);\n\n    c = (s_m * g) + e;\n}\n\nint rank::rank_commitment::verify_proof(\n        const NTL::vec_GF2E &c,\n        const NTL::vec_GF2 &s,\n        const NTL::vec_GF2 &m,\n        const NTL::mat_GF2E &g) {\n\n    auto s_m = utils::gf2e_from_two_gf2(s, m);\n    auto e = (s_m * g) + c;\n\n    if (utils::rank_of_vector(e) != RHO) {\n        return 1;\n    }\n\n    return 0;\n}", "meta": {"hexsha": "9e0b8423f3a3a56dbed0b747618e4695738cf1dd", "size": 1470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rank/rank_commitment/rank_commitment.cpp", "max_stars_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_stars_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rank/rank_commitment/rank_commitment.cpp", "max_issues_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_issues_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rank/rank_commitment/rank_commitment.cpp", "max_forks_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_forks_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-16T07:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-16T07:21:24.000Z", "avg_line_length": 22.96875, "max_line_length": 71, "alphanum_fraction": 0.5918367347, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5817175936442228}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_HYPERGEOMETRIC_RNG_HPP\r\n#define STAN_MATH_PRIM_SCAL_PROB_HYPERGEOMETRIC_RNG_HPP\r\n\r\n#include <stan/math/prim/meta.hpp>\r\n#include <boost/math/distributions/hypergeometric.hpp>\r\n\r\n#include <stan/math/prim/scal/err/check_bounded.hpp>\r\n#include <stan/math/prim/scal/err/check_positive.hpp>\r\n#include <stan/math/prim/scal/prob/uniform_rng.hpp>\r\n\r\nnamespace stan {\r\nnamespace math {\r\n\r\ntemplate <class RNG>\r\ninline int hypergeometric_rng(int N, int a, int b, RNG& rng) {\r\n  using boost::math::hypergeometric_distribution;\r\n  using boost::variate_generator;\r\n\r\n  static const char* function = \"hypergeometric_rng\";\r\n\r\n  check_bounded(function, \"Draws parameter\", N, 0, a + b);\r\n  check_positive(function, \"Draws parameter\", N);\r\n  check_positive(function, \"Successes in population parameter\", a);\r\n  check_positive(function, \"Failures in population parameter\", b);\r\n\r\n  hypergeometric_distribution<> dist(b, N, a + b);\r\n\r\n  double u = uniform_rng(0.0, 1.0, rng);\r\n  int min = 0;\r\n  int max = a - 1;\r\n  while (min < max) {\r\n    int mid = (min + max) / 2;\r\n    if (cdf(dist, mid + 1) > u)\r\n      max = mid;\r\n    else\r\n      min = mid + 1;\r\n  }\r\n  return min + 1;\r\n}\r\n\r\n}  // namespace math\r\n}  // namespace stan\r\n#endif\r\n", "meta": {"hexsha": "8b1ddd96cf022e6e66aebfe453bc5cf48ca0b857", "size": 1244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/math/prim/scal/prob/hypergeometric_rng.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/prob/hypergeometric_rng.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/prob/hypergeometric_rng.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": 28.2727272727, "max_line_length": 68, "alphanum_fraction": 0.6848874598, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276222, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5817175822829569}}
{"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 \"TranslationFirstPoseController.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\n\n\nnamespace DQ_robotics\n{\n\n\n\nTranslationFirstPoseController::TranslationFirstPoseController(DQ_kinematics robot, MatrixXd translation_feedback_gain, MatrixXd rotation_feedback_gain, double translation_damping, double rotation_damping) : DQ_controller()\n{\n\n    //Initialization of argument parameters\n    robot_dofs_          = (robot.links() - robot.n_dummy());\n    robot_               = robot;\n    kp_                  = translation_feedback_gain;\n\tkr_                  = rotation_feedback_gain;\n\ttranslation_damping_ = translation_damping;\n\trotation_damping_    = rotation_damping;\n\n    //Initilization of remaining parameters\n    thetas_         = MatrixXd(robot_dofs_,1);\n    delta_thetas_   = MatrixXd::Zero(robot_dofs_,1);\n\n    analytical_jacobian_  = MatrixXd(8,robot_dofs_);\n\trotation_jacobian_    = MatrixXd(4,robot_dofs_);\n\ttranslation_jacobian_ = MatrixXd(4,robot_dofs_);\n\n\tnullspace_projector_  = MatrixXd(robot_dofs_, robot_dofs_);\n\n    translation_jacobian_pseudoinverse_   = MatrixXd(robot_dofs_,4);\n\trotation_jacobian_pseudoinverse_   = MatrixXd(robot_dofs_,4);\n\n    identity4_           = Matrix<double,4,4>::Identity();\n\tidentityDOFS_        = MatrixXd::Identity(robot_dofs_,robot_dofs_);\n\n    error_translation_  = MatrixXd(4,1);\n\terror_rotation_     = MatrixXd(4,1);\n\n    end_effector_pose_           = DQ(0,0,0,0,0,0,0,0);\n\treference_translation_       = DQ(0,0,0,0,0,0,0,0);\n\treference_rotation_          = DQ(0,0,0,0,0,0,0,0);\n\n}\n\nVectorXd TranslationFirstPoseController::getNewJointPositions( const DQ reference, const VectorXd thetas)\n{\n\n    delta_thetas_ = getNewJointVelocities(reference, thetas);\n\n    // Send updated thetas to simulation\n    return (thetas_ + delta_thetas_);\n\n}\n\nVectorXd TranslationFirstPoseController::getNewJointVelocities( const DQ reference, const VectorXd thetas)\n{\n\n    ///--Remapping arguments\n    thetas_ = thetas;\n\n\t//Get translation and rotation individually\n\treference_translation_ = reference.translation();\n\treference_rotation_    = P(reference);\n\n    ///--Controller Step\n           \n    //Calculate jacobian and FKM\n    analytical_jacobian_  = robot_.analyticalJacobian(thetas_);\n    end_effector_pose_    = robot_.fkm(thetas_);\n\n    //Error\n    error_translation_ = vec4( reference_translation_ -  end_effector_pose_.translation() );\n\n\terror_rotation_    = vec4( reference_rotation_    - P(end_effector_pose_) );\n\n\t//Calculate Jacobians\n\ttranslation_jacobian_ = translationJacobian(analytical_jacobian_, vec8(end_effector_pose_));\n\trotation_jacobian_    = rotationJacobian(analytical_jacobian_);\n\n\t//Pseudoinverses calculation\n\ttranslation_jacobian_pseudoinverse_ = (translation_jacobian_.transpose())\n\t\t\t\t\t\t\t\t\t\t *(translation_jacobian_*translation_jacobian_.transpose() + translation_damping_*translation_damping_*identity4_).inverse();\n\n\trotation_jacobian_pseudoinverse_ =    (rotation_jacobian_.transpose())\n\t\t\t\t\t\t\t\t\t\t *(rotation_jacobian_*rotation_jacobian_.transpose() + rotation_damping_*rotation_damping_*identity4_).inverse();\n\t\n\t//Nullspace projector\n\tnullspace_projector_ = (identityDOFS_ - (pseudoInverse(translation_jacobian_))*translation_jacobian_ );\n\n    delta_thetas_ = translation_jacobian_pseudoinverse_ * kp_ * error_translation_ +\n\t\t\t\t\tnullspace_projector_ * rotation_jacobian_pseudoinverse_ * kr_ * error_rotation_;\n\n\n    return delta_thetas_;\n\n}\n\n\n\n\n\n}\n", "meta": {"hexsha": "45bc27f9f9b7309396d17d669f2449587028d3e3", "size": 3450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros_dqrobotics/dq_robotics/include/dq_robotics/controllers/TranslationFirstPoseController.cpp", "max_stars_repo_name": "birlrobotics/birlBaxter_demos", "max_stars_repo_head_hexsha": "a4871cbf2587a759c958c8451746554e1663e829", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-12-29T11:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T00:49:10.000Z", "max_issues_repo_path": "ros_dqrobotics/dq_robotics/include/dq_robotics/controllers/TranslationFirstPoseController.cpp", "max_issues_repo_name": "birlrobotics/birlBaxter_demos", "max_issues_repo_head_hexsha": "a4871cbf2587a759c958c8451746554e1663e829", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-20T05:52:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-30T09:07:56.000Z", "max_forks_repo_path": "ros_dqrobotics/dq_robotics/include/dq_robotics/controllers/TranslationFirstPoseController.cpp", "max_forks_repo_name": "birlrobotics/birlBaxter_demos", "max_forks_repo_head_hexsha": "a4871cbf2587a759c958c8451746554e1663e829", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-02-10T06:12:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T11:56:07.000Z", "avg_line_length": 32.2429906542, "max_line_length": 223, "alphanum_fraction": 0.7449275362, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276222, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.581717570921691}}
{"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": "#include <Eigen/Dense>\n#include <fmt/core.h>\n#include <fmt/ranges.h>\n\n#include <array>\n#include <cstdint>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <optional>\n#include <unordered_set>\n\nusing Mat = Eigen::Matrix<int, 5, 5>;\n\nauto parseRow(std::string const &line) {\n  Eigen::Vector<int, 5> out;\n  std::stringstream ss(line);\n  for (auto i = 0; i < 5; ++i) {\n    ss >> out[i];\n  }\n  return out;\n}\n\nauto parseFile(std::string const &fn) {\n  auto file = std::ifstream(fn);\n\n  std::string line;\n  std::getline(file, line);\n  for (auto &c : line) {\n    if (c == ',') {\n      c = ' ';\n    }\n  }\n  std::stringstream ss(line);\n\n  std::uint16_t num = 0;\n  std::vector<std::uint16_t> out;\n  while (ss >> num) {\n    out.push_back(num);\n  }\n\n  // Now for the matrices\n  std::vector<Mat> outM;\n  int row = 0;\n  while (std::getline(file, line)) {\n    auto pos = line.find_first_not_of(' ');\n    if (pos == std::string::npos || line[pos] == '\\n') {\n      row = 0;\n      outM.emplace_back();\n      continue;\n    }\n\n    outM.back().row(row++) = parseRow(line);\n  }\n\n  return std::make_pair(out, outM);\n}\n\nauto matWins(Mat const &m) {\n  for (auto r = 0; r < m.rows(); ++r) {\n    if (m.row(r).sum() == -5) {\n      return true;\n    }\n  }\n\n  for (auto c = 0; c < m.cols(); ++c) {\n    if (m.col(c).sum() == -5) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nint main(int _, char **argv) {\n  auto [rands, mats] = parseFile(argv[1]);\n\n  std::optional<Mat> winner;\n  std::optional<Mat> loser;\n  std::uint16_t rand_winner = 0;\n  std::uint16_t rand_loser = 0;\n  std::unordered_set<Mat*> winners;\n  for (auto r : rands) {\n    for (auto &m : mats) {\n      if(winners.count(&m) == 1){\n        continue;\n      }\n      m = (m.unaryExpr([&](int x) { return (x == r) ? -1 : x; }));\n      if (matWins(m)) {\n        if(!winner){\n          winner = m;\n          rand_winner = r;\n        }\n        winners.insert(&m);\n        if(winners.size() == mats.size()){\n          loser = m;\n          rand_loser = r;\n        }\n      }\n    }\n    if(loser){\n      break;\n    }\n  }\n\n  auto sum = (*winner).unaryExpr([](int x) { return x == -1 ? 0 : x; }).sum();\n  auto sum_loser = (*loser).unaryExpr([](int x) { return x == -1 ? 0 : x; }).sum();\n  fmt::print(\"Winning: {}\\n\", sum * rand_winner);\n  fmt::print(\"Losing: {}\\n\", sum_loser * rand_loser);\n}\n", "meta": {"hexsha": "8f3eeb8366da80ff855c5d249f2165cb0e88040a", "size": 2366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/day4/day4.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/day4/day4.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/day4/day4.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": 20.9380530973, "max_line_length": 83, "alphanum_fraction": 0.5321217244, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5817016503534964}}
{"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": "//          Copyright Carl Philipp Reh 2009 - 2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <fcppt/catch/begin.hpp>\n#include <fcppt/catch/end.hpp>\n#include <fcppt/math/is_zero_boost_units.hpp>\n#include <fcppt/math/vector/arithmetic.hpp>\n#include <fcppt/math/vector/comparison.hpp>\n#include <fcppt/math/vector/static.hpp>\n#include <fcppt/optional/comparison.hpp>\n#include <fcppt/optional/make.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/time.hpp>\n#include <boost/units/systems/si/velocity.hpp>\n#include <catch2/catch.hpp>\n#include <fcppt/config/external_end.hpp>\n\nFCPPT_CATCH_BEGIN\n\nTEST_CASE(\"math units\", \"[math]\")\n{\n  using unit_type = int;\n\n  using length = boost::units::quantity<boost::units::si::length, unit_type>;\n\n  using time = boost::units::quantity<boost::units::si::time, unit_type>;\n\n  using velocity = boost::units::quantity<boost::units::si::velocity, unit_type>;\n\n  using length2 = fcppt::math::vector::static_<length, 2>;\n\n  using time2 = fcppt::math::vector::static_<time, 2>;\n\n  using velocity2 = fcppt::math::vector::static_<velocity, 2>;\n\n  length2 const l1(length(-100 * boost::units::si::meter), length(200 * boost::units::si::meter));\n\n  time2 const t1(time(4 * boost::units::si::second), time(2 * boost::units::si::second));\n\n  CHECK(\n      l1 / t1 == fcppt::optional::make(velocity2{\n                     -25 * boost::units::si::meter / boost::units::si::second,\n                     100 * boost::units::si::meter / boost::units::si::second}));\n}\n\nFCPPT_CATCH_END\n", "meta": {"hexsha": "a357824be055de816a296be9fb302add7119ae8c", "size": 1747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/units.cpp", "max_stars_repo_name": "freundlich/fcppt", "max_stars_repo_head_hexsha": "17df1b1ad08bf2435f6902d5465e3bc3fe5e3022", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T18:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-29T14:08:29.000Z", "max_issues_repo_path": "test/math/units.cpp", "max_issues_repo_name": "cpreh/fcppt", "max_issues_repo_head_hexsha": "17df1b1ad08bf2435f6902d5465e3bc3fe5e3022", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-08-27T07:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-21T10:55:34.000Z", "max_forks_repo_path": "test/math/units.cpp", "max_forks_repo_name": "freundlich/fcppt", "max_forks_repo_head_hexsha": "17df1b1ad08bf2435f6902d5465e3bc3fe5e3022", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-01-10T09:22:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-01T08:31:12.000Z", "avg_line_length": 34.2549019608, "max_line_length": 98, "alphanum_fraction": 0.6949055524, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5817016287823599}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n#include <complex>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/matrix/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": "//==================================================================================================\n/*!\n\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#include <boost/simd/function/scalar/pow.hpp>\n#include <boost/simd/function/std.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/eight.hpp>\n#include <boost/simd/constant/third.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/function/is_negative.hpp>\n#include <boost/simd/function/is_positive.hpp>\n\nSTF_CASE_TPL(\"pow\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::pow;\n  using r_t =  decltype(pow(T(), T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(pow(bs::Inf<T>(), bs::Inf<T>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(pow(bs::Nan<T>(), bs::Nan<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(pow(bs::Minf<T>(), bs::Minf<T>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(pow(bs::Inf<T>(), bs::Minf<T>()), bs::Zero<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(pow(T(-1),T(6)), T(1), 0);\n  STF_ULP_EQUAL(pow(bs::Mone<T>(), bs::Mone<T>()), bs::Mone<r_t>(), 0);\n  STF_ULP_EQUAL(pow(bs::One<T>(), bs::One<T>()), bs::One<r_t>(), 0);\n  STF_ULP_EQUAL(pow(bs::Zero<T>(), bs::Zero<T>()), bs::One<r_t>(), 0);\n  STF_ULP_EQUAL(pow(T(-1),T(5)), T(-1), 0);\n  STF_ULP_EQUAL(pow(bs::Zero<T>(), bs::One<T>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(pow(T(8),bs::Third<T>()), r_t(2), 0.5);\n}\n\nSTF_CASE_TPL(\"powreal_int\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::pow;\n  using iT = bd::as_integer_t<T>;\n  using r_t =  decltype(pow(T(), iT()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  #ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(pow(bs::Inf<T>(),3), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(pow(bs::Minf<T>(),3), bs::Minf<r_t>(), 0);\n  STF_ULP_EQUAL(pow(bs::Nan<T>(),3), bs::Nan<r_t>(), 0);\n  #endif\n\n  STF_ULP_EQUAL(pow(bs::Two<T>(),-3), (bs::Ratio<r_t, 1, 8>()),  0);\n }\n\nSTF_CASE_TPL(\"powint\",  STF_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::pow;\n  using iT = bd::as_integer_t<T>;\n  using r_t =  decltype(pow(T(), iT()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  STF_EQUAL(pow(bs::Mone<T>(),3), bs::Mone<r_t>());\n  STF_EQUAL(pow(bs::Mone<T>(),4), bs::One<r_t>());\n  STF_EQUAL(pow(bs::One<T>(),3),  bs::One<r_t>());\n  STF_EQUAL(pow(bs::Two<T>(),3),  bs::Eight<r_t>());\n  STF_EQUAL(pow(bs::Zero<T>(),0), bs::One<r_t>());\n  STF_EQUAL(pow(bs::Zero<T>(),3), bs::Zero<r_t>());\n}\n\n\n\nSTF_CASE_TPL(\"pow conformity\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::pow;\n  using r_t =  decltype(pow(T(), T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  STF_ULP_EQUAL(pow(T(0), T(-1)), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(pow(-T(0), T(-1)), bs::Minf<r_t>(), 0);\n  STF_ULP_EQUAL(pow(-T(0), T(-2)), bs::Inf<T>(), 0);\n  STF_ULP_EQUAL(pow(T(0), T(-2)), bs::Inf<T>(), 0);\n  STF_ULP_EQUAL(pow(T(0),  bs::Minf<T>()),  bs::Inf<T>(), 0);\n  STF_ULP_EQUAL(pow(-T(0),  bs::Minf<T>()),  bs::Inf<T>(), 0);\n  STF_ULP_EQUAL(pow(-T(1),  bs::Minf<T>()),  bs::One<T>(), 0);\n  STF_ULP_EQUAL(pow(-T(1),  bs::Inf <T>()),  bs::One<T>(), 0);\n  STF_ULP_EQUAL(pow(T(1), bs::Nan<T>()) ,  bs::One<T>(), 0);\n  STF_ULP_EQUAL(pow(bs::Nan<T>(), T(0)) ,  bs::One<T>(), 0);\n  STF_ULP_EQUAL(pow(bs::Nan<T>(), -T(0)) ,  bs::One<T>(), 0);\n  STF_ULP_EQUAL(pow(T(0.5), bs::Inf<T>()),  bs::Zero<T>(), 0);\n  STF_ULP_EQUAL(pow(T(2), bs::Inf<T>()),  bs::Inf<T>(), 0);\n  STF_ULP_EQUAL(pow(T(0.5), bs::Minf<T>()),  bs::Inf<T>(), 0);\n  STF_ULP_EQUAL(pow(T(2), bs::Minf<T>()),  bs::Zero<T>(), 0);\n  STF_ULP_EQUAL(pow(-T(0.5), bs::Inf<T>()),  bs::Zero<T>(), 0);\n  STF_ULP_EQUAL(pow(-T(2), bs::Inf<T>()),  bs::Inf<T>(), 0);\n  STF_ULP_EQUAL(pow(-T(0.5), bs::Minf<T>()),  bs::Inf<T>(), 0);\n  STF_ULP_EQUAL(pow(-T(2), bs::Minf<T>()),  bs::Zero<T>(), 0);\n  STF_ULP_EQUAL(pow(bs::Minf<T>(), T(-3) ),  bs::Mzero<T>(), 0);\n  STF_EXPECT(bs::is_negative(pow(bs::Minf<T>(), T(-3) )));\n  STF_ULP_EQUAL(pow(bs::Minf<T>(), T(-4) ),  bs::Zero<T>(), 0);\n  STF_EXPECT(bs::is_positive(pow(bs::Minf<T>(), T(-4) )));\n  STF_ULP_EQUAL(pow(bs::Inf<T>(), T(4) ),  bs::Inf<T>(), 0);\n  STF_ULP_EQUAL(pow(bs::Inf<T>(), T(-4) ),  bs::Zero<T>(), 0);\n}\n", "meta": {"hexsha": "4df2867f36d04160bc6147b964d9460c395f33e2", "size": 4942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/pow.regular.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "test/function/scalar/pow.regular.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/scalar/pow.regular.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 37.4393939394, "max_line_length": 100, "alphanum_fraction": 0.5819506273, "num_tokens": 1739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5816726679608529}}
{"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\u00e8ve un bout de 60\u00b0\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 <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, log1m_inv_logit) {\n  using stan::math::log1m_inv_logit;\n  using std::log;\n  using stan::math::inv_logit;\n\n  EXPECT_FLOAT_EQ(log(1 - inv_logit(-7.2)), log1m_inv_logit(-7.2));\n  EXPECT_FLOAT_EQ(log(1 - inv_logit(0.0)), log1m_inv_logit(0.0));\n  EXPECT_FLOAT_EQ(log(1 - inv_logit(1.9)), log1m_inv_logit(1.9));\n}\n\nTEST(MathFunctions, log1m_inv_logit_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::log1m_inv_logit(nan));\n}\n", "meta": {"hexsha": "c532764a44fe3a4f37b47263cec30fc3237d0f67", "size": 643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log1m_inv_logit_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log1m_inv_logit_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log1m_inv_logit_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.619047619, "max_line_length": 67, "alphanum_fraction": 0.7138413686, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5816630111819276}}
{"text": "/*******************************************************************************\n *\n * Difference Bound Matrix domain based on the paper \"Exploiting\n * Sparsity in Difference-Bound Matrices\" by Gange, Navas, Schachte,\n * Sondergaard, and Stuckey published in SAS'16.\n\n * A re-engineered implementation of the Difference Bound Matrix\n * domain, which maintains bounds and relations separately.\n *\n * Closure operations based on the paper \"Fast and Flexible Difference\n * Constraint Propagation for DPLL(T)\" by Cotton and Maler.\n *\n * Author: Graeme Gange (gkgange@unimelb.edu.au)\n *\n * Contributors: Jorge A. Navas (jorge.navas@sri.com)\n ******************************************************************************/\n\n#pragma once\n\n#include <crab/common/types.hpp>\n#include <crab/common/debug.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/domains/graphs/graph_ops.hpp>\n#include <crab/domains/graphs/graph_config.hpp>\n#include <crab/domains/linear_constraints.hpp>\n#include <crab/domains/interval.hpp>\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\n#include <boost/optional.hpp>\n#include <boost/container/flat_map.hpp>\n#include <unordered_set>\n\n#define JOIN_CLOSE_AFTER_MEET \n//#define CHECK_POTENTIAL\n//#define SDBM_NO_NORMALIZE\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-compare\"\n\nnamespace crab {\n\n  namespace domains {\n\n    template<class Number, class VariableName, class Params = DBM_impl::DefaultParams<Number>>\n    class SplitDBM_ final:\n      public abstract_domain<SplitDBM_<Number,VariableName,Params>> {\n      typedef SplitDBM_<Number, VariableName, Params> DBM_t;\n      typedef abstract_domain<DBM_t> abstract_domain_t;\n      \n     public:\n      using typename abstract_domain_t::linear_expression_t;\n      using typename abstract_domain_t::linear_constraint_t;\n      using typename abstract_domain_t::linear_constraint_system_t;\n      using typename abstract_domain_t::disjunctive_linear_constraint_system_t;      \n      using typename abstract_domain_t::variable_t;\n      using typename abstract_domain_t::variable_vector_t;\n      using typename abstract_domain_t::pointer_constraint_t;\n      typedef Number number_t;\n      typedef VariableName varname_t;\n      \n      typedef typename linear_constraint_t::kind_t constraint_kind_t;\n      typedef interval<number_t>  interval_t;\n\n     private:\n      typedef bound<number_t>  bound_t;\n      typedef typename Params::Wt Wt;\n      typedef typename Params::graph_t graph_t;\n      typedef DBM_impl::NtoW<number_t, Wt> ntow;\n      typedef typename graph_t::vert_id vert_id;\n      typedef boost::container::flat_map<variable_t, vert_id> vert_map_t;\n      typedef typename vert_map_t::value_type vmap_elt_t;\n      typedef std::vector< boost::optional<variable_t>> rev_map_t;\n      typedef GraphOps<graph_t> GrOps;\n      typedef GraphPerm<graph_t> GrPerm;\n      typedef typename GrOps::edge_vector edge_vector;\n      // < <x, y>, k> == x - y <= k.\n      typedef std::pair<std::pair<variable_t, variable_t>, Wt> diffcst_t;\n      typedef std::unordered_set<vert_id> vert_set_t;\n\n    protected:\n        \n      //================\n      // Domain data\n      //================\n      // GKG: ranges are now maintained in the graph\n      vert_map_t vert_map; // Mapping from variables to vertices\n      rev_map_t rev_map;\n      graph_t g; // The underlying relation graph\n      std::vector<Wt> potential; // Stored potential for the vertex\n      vert_set_t unstable;\n      bool _is_bottom;\n\n      class Wt_max {\n      public:\n       Wt_max() { } \n       Wt apply(const Wt& x, const Wt& y) { return std::max(x, y); }\n       bool default_is_absorbing() { return true; }\n      };\n\n      class Wt_min {\n      public:\n        Wt_min() { }\n        Wt apply(const Wt& x, const Wt& y) { return std::min(x, y); }\n        bool default_is_absorbing() { return false; }\n      };\n\n      vert_id get_vert(variable_t v) {\n        auto it = vert_map.find(v);\n        if(it != vert_map.end())\n          return (*it).second;\n\n        vert_id vert(g.new_vertex());\n        vert_map.insert(vmap_elt_t(v, vert)); \n        // Initialize \n        assert(vert <= rev_map.size());\n        if(vert < rev_map.size())\n        {\n          potential[vert] = Wt(0);\n          rev_map[vert] = v;\n        } else {\n          potential.push_back(Wt(0));\n          rev_map.push_back(v);\n        }\n        vert_map.insert(vmap_elt_t(v, vert));\n\n        assert(vert != 0);\n\n        return vert;\n      }\n\n      vert_id get_vert(graph_t& g, vert_map_t& vmap, rev_map_t& rmap,\n\t\t       std::vector<Wt>& pot, variable_t v) {\n        auto it = vmap.find(v);\n        if(it != vmap.end())\n          return (*it).second;\n\n        vert_id vert(g.new_vertex());\n        vmap.insert(vmap_elt_t(v, vert)); \n        // Initialize \n        assert(vert <= rmap.size());\n        if(vert < rmap.size())\n        {\n          pot[vert] = Wt(0);\n          rmap[vert] = v;\n        } else {\n          pot.push_back(Wt(0));\n          rmap.push_back(v);\n        }\n        vmap.insert(vmap_elt_t(v, vert));\n\n        return vert;\n      }\n\n      template<class G, class P>\n      inline void check_potential(G& g, P& p, unsigned line)\n      {\n        #ifdef CHECK_POTENTIAL\n        for(vert_id v : g.verts())\n        {\n          for(vert_id d : g.succs(v))\n          {\n            if(p[v] + g.edge_val(v, d) - p[d] < Wt(0))\n            {\n\t      CRAB_ERROR(\"Invalid potential at line \", line, \":\",\n\t\t\t \"pot[\", v , \"]=\", p[v], \" \",\n\t\t\t \"pot[\", d , \"]=\", p[d], \" \",\n\t\t\t \"edge(\",v,\",\",d,\")=\", g.edge_val(v,d));\n            }\n          }\n        }\n        #endif\n      }\n\n      class vert_set_wrap_t {\n      public:\n        vert_set_wrap_t(const vert_set_t& _vs)\n          : vs(_vs)\n        { }\n\n        bool operator[](vert_id v) const {\n          return vs.find(v) != vs.end();\n        }\n        const vert_set_t& vs;\n      };\n\n      // Evaluate the potential value of a variable.\n      Wt pot_value(variable_t v) {\n        auto it = vert_map.find(v); \n        if(it != vert_map.end())\n          return potential[(*it).second];\n        return ((Wt) 0);\n      }\n\n      Wt pot_value(variable_t v, std::vector<Wt>& potential) {\n        auto it = vert_map.find(v); \n        if(it != vert_map.end())\n          return potential[(*it).second];\n        return ((Wt) 0);\n      }\n\n      // Evaluate an expression under the chosen potentials\n      Wt eval_expression(linear_expression_t e, bool overflow) {\n        Wt v(ntow::convert(e.constant(), overflow));\n\tif (overflow) {\n\t  return Wt(0);\n\t}\n\t\n        for(auto p : e) {\n\t  Wt coef = ntow::convert(p.first , overflow);\n\t  if (overflow) {\n\t    return Wt(0);\n\t  }\n\t  v += (pot_value(p.second) - potential[0])*coef;\n        }\n        return v;\n      }\n      \n      interval_t eval_interval(linear_expression_t e) {\n        interval_t r = e.constant();\n        for (auto p : e)\n          r += p.first * operator[](p.second);\n        return r;\n      }\n\n      interval_t compute_residual(linear_expression_t e, variable_t pivot) {\n\tinterval_t residual(-e.constant());\n\tfor (typename linear_expression_t::iterator it = e.begin(); it != e.end(); ++it) {\n\t  variable_t v = it->second;\n\t  if (v.index() != pivot.index()) {\n\t    residual = residual - (interval_t(it->first) * this->operator[](v));\n\t  }\n\t}\n\treturn residual;\n      }\n\n      /**\n       *  Turn an assignment into a set of difference constraints.\n       * \n       *  Given v := a*x + b*y + k, where a,b >= 0, we generate the\n       *  difference constraints:\n       * \n       *  if extract_upper_bounds\n       *     v - x <= ub((a-1)*x + b*y + k)\n       *     v - y <= ub(a*x + (b-1)*y + k)\n       *  else\n       *     x - v <= lb((a-1)*x + b*y + k)\n       *     y - v <= lb(a*x + (b-1)*y + k)\n       **/ \n      void diffcsts_of_assign(variable_t x, linear_expression_t exp,\n\t\t\t      /* if true then process the upper\n\t\t\t\t bounds, else the lower bounds */\n\t\t\t      bool extract_upper_bounds,\n\t\t\t      /* foreach {v, k} \\in diff_csts we have\n\t\t\t\t the difference constraint v - k <= k */\n\t\t\t      std::vector<std::pair<variable_t, Wt>>& diff_csts) {\n\n\tboost::optional<variable_t> unbounded_var;\n\tstd::vector< std::pair<variable_t, Wt>> terms;\n\tbool overflow;\n\t\n\tWt residual(ntow::convert(exp.constant(), overflow));\n\tif (overflow) {\n\t  return;\n\t}\n\t\n\tfor(auto p : exp) {\n\t  Wt coeff(ntow::convert(p.first, overflow));\n\t  if (overflow) {\n\t    continue;\n\t  }\n\t  \n\t  variable_t y(p.second);\t    \n\t  if(coeff < Wt(0)) {\n\t    // Can't do anything with negative coefficients.\n\t    bound_t y_val = (extract_upper_bounds ?\n\t\t\t     operator[](y).lb():\n\t\t\t     operator[](y).ub());\n\t    \n\t    if(y_val.is_infinite()) {\n\t      return;\n\t    }\n\t    residual += ntow::convert(*(y_val.number()), overflow) * coeff;\n\t    if (overflow) {\n\t      continue;\n\t    }\n\t    \n\t  } else {\n\t    bound_t y_val = (extract_upper_bounds ?\n\t\t\t     operator[](y).ub():\n\t\t\t     operator[](y).lb());\n\n\t    if(y_val.is_infinite()) {\n\t      if(unbounded_var || coeff != Wt(1)) {\n\t\treturn;\n\t      }\n\t      unbounded_var = y;\n\t    } else {\n\t      Wt ymax(ntow::convert(*(y_val.number()), overflow));\n\t      if (overflow) {\n\t\tcontinue;\n\t      }\n\t      residual += ymax*coeff;\n\t      terms.push_back({y, ymax});\n\t    }\n\t  }\n\t}\n\t\n\tif(unbounded_var) {\n\t  // There is exactly one unbounded variable with unit\n\t  // coefficient\n\t  diff_csts.push_back({*unbounded_var, residual});\n\t} else {\n\t  for(auto p : terms) {\n\t    diff_csts.push_back({p.first, residual - p.second});\n\t  }\n\t}\n      }\n      \n      // Turn an assignment into a set of difference constraints.\n      void diffcsts_of_assign(variable_t x, linear_expression_t exp,\n\t\t\t      std::vector<std::pair<variable_t, Wt>>& lb,\n\t\t\t      std::vector<std::pair<variable_t,Wt>>& ub) {\n\tdiffcsts_of_assign(x, exp, true, ub);\n\tdiffcsts_of_assign(x, exp, false, lb);\n      }\n\n      /**\n       * Turn a linear inequality into a set of difference\n       * constraints.\n       **/\n      void diffcsts_of_lin_leq(const linear_expression_t& exp,\n\t\t\t       /* difference contraints */\n\t\t\t       std::vector<diffcst_t>& csts,\n\t\t\t       /* x >= lb for each {x,lb} in lbs */\n\t\t\t       std::vector<std::pair<variable_t, Wt>>& lbs,\n\t\t\t       /* x <= ub for each {x,ub} in ubs */\n\t\t\t       std::vector<std::pair<variable_t, Wt>>& ubs) {\n\t\n        Wt unbounded_lbcoeff;\n        Wt unbounded_ubcoeff;\n        boost::optional<variable_t> unbounded_lbvar;\n        boost::optional<variable_t> unbounded_ubvar;\n\tbool underflow, overflow;\n\n        Wt exp_ub = -(ntow::convert(exp.constant(), overflow));\n\tif (overflow) {\n\t  return;\n\t}\n\n\t// temporary hack\n\tntow::convert(exp.constant() - 1, underflow);\n\tif (underflow) {\n\t  // We don't like MIN either because the code will compute\n\t  // minus MIN and it will silently overflow.\n\t  return;\n\t}\n\t\n        std::vector<std::pair<std::pair<Wt, variable_t>, Wt>> pos_terms, neg_terms;\n        for(auto p : exp) {\n          Wt coeff(ntow::convert(p.first, overflow));\n\t  if (overflow) {\n\t    continue;\n\t  }\n          if(coeff > Wt(0)) {\n            variable_t y(p.second);\n            bound_t y_lb = operator[](y).lb();\n            if(y_lb.is_infinite()) {\n              if(unbounded_lbvar) {\n                return;\n\t      }\n              unbounded_lbvar = y;\n              unbounded_lbcoeff = coeff;\n            } else {\n              Wt ymin(ntow::convert(*(y_lb.number()), overflow));\n\t      if (overflow) {\n\t\tcontinue;\n\t      }\n              exp_ub -= ymin*coeff;\n              pos_terms.push_back({{coeff, y}, ymin});\n            }\n          } else {\n            variable_t y(p.second);\n            bound_t y_ub = operator[](y).ub(); \n            if(y_ub.is_infinite()) {\n              if(unbounded_ubvar) {\n                return;\n\t      }\n              unbounded_ubvar = y;\n              unbounded_ubcoeff = -coeff;\n            } else {\n              Wt ymax(ntow::convert(*(y_ub.number()), overflow));\n\t      if (overflow) {\n\t\tcontinue;\n\t      }\n              exp_ub -= ymax*coeff;\n              neg_terms.push_back({{-coeff, y}, ymax});\n            }\n          }\n        }\n\n        if(unbounded_lbvar) {\n          variable_t x(*unbounded_lbvar);\n          if(unbounded_ubvar) {\n            if(unbounded_lbcoeff != Wt(1) || unbounded_ubcoeff != Wt(1)) {\n              return;\n\t    }\n            variable_t y(*unbounded_ubvar);\n            csts.push_back({{x, y}, exp_ub});\n          } else {\n            if(unbounded_lbcoeff == Wt(1)) {\n              for(auto p : neg_terms) {\n                csts.push_back({{x, p.first.second}, exp_ub - p.second});\n\t      }\n            }\n            // Add bounds for x\n            ubs.push_back({x, exp_ub/unbounded_lbcoeff});\n          }\n        } else {\n          if(unbounded_ubvar) {\n            variable_t y(*unbounded_ubvar);\n            if(unbounded_ubcoeff == Wt(1)) {\n              for(auto p : pos_terms) {\n                csts.push_back({{p.first.second, y}, exp_ub + p.second});\n\t      }\n\t    }\n\t    // Add bounds for y\n\t    lbs.push_back({y, -exp_ub/unbounded_ubcoeff});\n          } else {\n            for(auto pl : neg_terms) {\n              for(auto pu : pos_terms) {\n                csts.push_back({{pu.first.second, pl.first.second},\n\t\t                exp_ub - pl.second + pu.second});\n\t      }\n\t    }\n            for(auto pl : neg_terms) {\n              lbs.push_back({pl.first.second, -exp_ub/pl.first.first + pl.second});\n\t    }\n            for(auto pu : pos_terms) {\n              ubs.push_back({pu.first.second, exp_ub/pu.first.first + pu.second});\n\t    }\n          }\n        }\n      }\n      \n\n      bool add_linear_leq(const linear_expression_t& exp) {\n        CRAB_LOG(\"zones-split\",\n                 linear_expression_t exp_tmp(exp);\n                 crab::outs() << \"Adding: \"<< exp_tmp << \"<= 0\" <<\"\\n\");\n        std::vector<std::pair<variable_t, Wt>> lbs, ubs;\n        std::vector<diffcst_t> csts;\n        diffcsts_of_lin_leq(exp, csts, lbs, ubs);\n\n        check_potential(g, potential, __LINE__);\n\n        Wt_min min_op;\n        typename graph_t::mut_val_ref_t w;\n        for(auto p : lbs) {\n          CRAB_LOG(\"zones-split\",\n                   crab::outs() << p.first<< \">=\"<< p.second <<\"\\n\");\n          variable_t x(p.first);\n          vert_id v = get_vert(p.first);\n          if(g.lookup(v, 0, &w) && w.get() <= -p.second)\n            continue;\n          g.set_edge(v, -p.second, 0);\n\t  \n          if(!repair_potential(v, 0)) {\n            set_to_bottom();\n            return false;\n          }\n          check_potential(g, potential, __LINE__);\n          // Compute other updated bounds\n\t  if (Params::close_bounds_inline) {\n\t    for(auto e : g.e_preds(v)) {\n\t      if(e.vert == 0)\n\t\tcontinue;\n\t      g.update_edge(e.vert, e.val - p.second, 0, min_op);\n\t      \n\t      if(!repair_potential(e.vert, 0)) {\n\t\tset_to_bottom();\n\t\treturn false;\n\t      }\n\t      check_potential(g, potential, __LINE__);\n\t    }\n\t  }\n        }\n        for(auto p : ubs) {\n          CRAB_LOG(\"zones-split\",\n                   crab::outs() << p.first<< \"<=\"<< p.second <<\"\\n\");\n          variable_t x(p.first);\n          vert_id v = get_vert(p.first);\n          if(g.lookup(0, v, &w) && w.get() <= p.second)\n            continue;\n          g.set_edge(0, p.second, v);\n          if(!repair_potential(0, v)) {\n            set_to_bottom();\n            return false;\n          }\n          check_potential(g, potential, __LINE__);\n\n\t  if (Params::close_bounds_inline) {\t  \n\t    for(auto e : g.e_succs(v)) {\n\t      if(e.vert == 0)\n\t\tcontinue;\n\t      g.update_edge(0, e.val + p.second, e.vert, min_op);\n\t      if(!repair_potential(0, e.vert)) {\n\t\tset_to_bottom();\n\t\treturn false;\n\t      }\n\t      check_potential(g, potential, __LINE__);\n\t    }\n\t  }\n        }\n      \n        for(auto diff : csts) {\n          CRAB_LOG(\"zones-split\",\n                   crab::outs() << diff.first.first<< \"-\"<< diff.first.second<< \"<=\"\n\t\t                << diff.second <<\"\\n\");\n\n          vert_id src = get_vert(diff.first.second);\n          vert_id dest = get_vert(diff.first.first);\n          g.update_edge(src, diff.second, dest, min_op);\n          if(!repair_potential(src, dest)) { \n            set_to_bottom();\n            return false;\n          }\n          check_potential(g, potential, __LINE__);          \n          close_over_edge(src, dest);\n\t  check_potential(g, potential, __LINE__);\n        }\n\t// Collect bounds\n\t// GKG: Now done in close_over_edge\n\n\tif (!Params::close_bounds_inline) {\t  \n\t  edge_vector delta;\n\t  GrOps::close_after_assign(g, potential, 0, delta);\n\t  GrOps::apply_delta(g, delta);\n\t}\n\n        check_potential(g, potential, __LINE__);\n        // CRAB_WARN(\"SplitDBM::add_linear_leq not yet implemented.\");\n        return true;  \n      }\n\n      // x != n\n      bool add_univar_disequation(variable_t x, number_t n) {\n\tbool overflow;\n\tinterval_t i = get_interval(x);\n\tinterval_t new_i =\n\t  linear_interval_solver_impl::trim_interval<interval_t>(i, interval_t(n));\n\tif (new_i.is_bottom()) {\n\t  set_to_bottom();\n\t  return false;\n\t} else if (!new_i.is_top() && (new_i <= i)) {\n\t  vert_id v = get_vert(x);\n\t  typename graph_t::mut_val_ref_t w;\n\t  Wt_min min_op;\t  \n\t  if(new_i.lb().is_finite()) {\n\t    // strenghten lb\n\t    Wt lb_val = ntow::convert(-(*(new_i.lb().number())), overflow);\n\t    if (overflow) {\n\t      return true;\n\t    }\n\t    \n\t    if(g.lookup(v, 0, &w) && lb_val < w.get()) {\n\t      g.set_edge(v, lb_val, 0);\n\t      if(!repair_potential(v, 0)) {\n\t\tset_to_bottom();\n\t\treturn false;\n\t      }\n\t      check_potential(g, potential, __LINE__);\n\t      // Update other bounds\n\t      for(auto e : g.e_preds(v)) {\n\t\tif(e.vert == 0) continue;\n\t\tg.update_edge(e.vert, e.val + lb_val, 0, min_op);\n\t\tif(!repair_potential(e.vert, 0)) {\n\t\t  set_to_bottom();\n\t\t  return false;\n\t\t}\n\t\tcheck_potential(g, potential, __LINE__);\n\t      }\n\t    }\n\t  }\n\t  if(new_i.ub().is_finite()) {\t    \n\t    // strengthen ub\n\t    Wt ub_val = ntow::convert(*(new_i.ub().number()), overflow);\n\t    if (overflow) {\n\t      return true;\n\t    }\n\t    \n\t    if(g.lookup(0, v, &w) && (ub_val < w.get())) {\n\t      g.set_edge(0, ub_val, v);\n\t      if(!repair_potential(0, v)) {\n\t\tset_to_bottom();\n\t\treturn false;\n\t      }\t      \n\t      check_potential(g, potential, __LINE__);\n\t      // Update other bounds\n\t      for(auto e : g.e_succs(v)) {\n\t\tif(e.vert == 0) continue;\n\t\tg.update_edge(0, e.val + ub_val, e.vert, min_op);\n\t\tif(!repair_potential(0, e.vert)) {\n\t\t  set_to_bottom();\n\t\t  return false;\n\t\t}\n\t\tcheck_potential(g, potential, __LINE__);\n\t      }\n\t    }\n\t  }\n\t}\n\treturn true;\n      } \n      \n      void add_disequation(linear_expression_t e) {\n\t// XXX: similar precision as the interval domain\n\t\n\tfor (typename linear_expression_t::iterator it = e.begin(); it != e.end(); ++it) {\n\t  variable_t pivot = it->second;\n\t  interval_t i = compute_residual(e, pivot) / interval_t(it->first);\n\t  if (auto k = i.singleton()) {\n\t    if (!add_univar_disequation(pivot, *k)) {\n\t      // set_to_bottom() was already called\n\t      return;\n\t    }\n\t  }\n\t}\n\n\t\n        /*\n        // Can only exploit \\sum_i c_i x_i \\neq k if:\n        // (1) exactly one x_i is unfixed\n        // (2) lb(x_i) or ub(x_i) = k - \\sum_i' c_i' x_i'\n        Wt k = exp.constant();\n        auto it = exp.begin();\n        for(; it != exp.end(); ++it)\n        {\n          if(!var_is_fixed((*it).second)) \n            break;\n          k -= (*it).first*get_value((*it).second);\n        }\n\n        // All variables are fixed\n        if(it == exp.end())\n        {\n          if(k == Wt(0))\n            set_to_bottom();\n          return;\n        }\n\n        // Found one unfixed variable; collect the rest.\n        Wt ucoeff = (*it).first;\n        varname_t uvar((*it).second;\n        interval_t u_int = get_interval(ranges, uvar);\n        // We need at least one side of u to be finite.\n        if(u_int.lb().is_infinite() && u_int.ub().is_infinite())\n          return;\n\n        for(++it; it != exp.end(); ++it)\n        {\n          // Two unfixed variables; nothing we can do.\n          if(!var_is_fixed((*it).second))\n            return;\n          k -= (*it).first*get_value((*it).second);\n        }\n        */\n      }\n\n      interval_t get_interval(variable_t x) {\n        return get_interval(vert_map, g, x);\n      }\n\n      interval_t get_interval(vert_map_t& m, graph_t& r, variable_t x) {\n        auto it = m.find(x);\n        if(it == m.end())\n        {\n          return interval_t::top();\n        }\n        vert_id v = (*it).second;\n        interval_t x_out = interval_t(\n            r.elem(v, 0) ? -number_t(r.edge_val(v, 0)) : bound_t::minus_infinity(),\n            r.elem(0, v) ? number_t(r.edge_val(0, v)) : bound_t::plus_infinity());\n        return x_out;\n        /*\n        boost::optional< interval_t > v = r.lookup(x);\n        if(v)\n          return *v;\n        else\n          return interval_t::top();\n\t*/\n      }\n\n      // Resore potential after an edge addition\n      bool repair_potential(vert_id src, vert_id dest)\n      {\n        return GrOps::repair_potential(g, potential, src, dest);\n      }\n\n      // Restore closure after a single edge addition\n      void close_over_edge(vert_id ii, vert_id jj)\n      {\n        Wt_min min_op;\n\n        assert(ii != 0 && jj != 0);\n        SubGraph<graph_t> g_excl(g, 0);\n\n        Wt c = g_excl.edge_val(ii,jj);\n\n        typename graph_t::mut_val_ref_t w;\n\t\n\tif (Params::close_bounds_inline) {\t  \t\n\t  if(g.lookup(0, ii, &w))\n\t    g.update_edge(0, w.get() + c, jj, min_op);\n\t  if(g.lookup(jj, 0, &w))\n\t    g.update_edge(ii, w.get() + c, 0, min_op);\n\t}\n\n        // There may be a cheaper way to do this.\n        // GKG: Now implemented.\n        std::vector<std::pair<vert_id, Wt>> src_dec;\n        for(auto edge : g_excl.e_preds(ii))\n        {\n          vert_id se = edge.vert;\n          Wt wt_sij = edge.val + c;\n\n          assert(g_excl.succs(se).begin() != g_excl.succs(se).end());\n          if(se != jj)\n          {\n            if(g_excl.lookup(se, jj, &w))\n            {\n              if(w.get() <= wt_sij)\n                continue;\n\n              w = wt_sij;\n              // g_excl.set_edge(se, wt_sij, jj);\n            } else {\n              g_excl.add_edge(se, wt_sij, jj);\n            }\n            src_dec.push_back(std::make_pair(se, edge.val));  \n\t    if (Params::close_bounds_inline) {\t  \t\t    \n\t      if(g.lookup(0, se, &w))\n\t\tg.update_edge(0, w.get() + wt_sij, jj, min_op);\n\t      if(g.lookup(jj, 0, &w))\n\t\tg.update_edge(se, w.get() + wt_sij, 0, min_op);\n\t    }\n\n\t    /*\n            for(auto edge : g_excl.e_succs(jj))\n            {\n              vert_id de = edge.vert;\n              if(se != de)\n              {\n                Wt wt_sijd = wt_sij + edge.val;\n                if(g_excl.lookup(se, de, &w))\n                {\n                  if((*w) <= wt_sijd)\n                    continue;\n                  (*w) = wt_sijd;\n                } else {\n                  g_excl.add_edge(se, wt_sijd, de);\n                }\n\t\tif (Params::close_bounds_inline) {\t  \t\t    \n                  if(g.lookup(0, se, &w))\n\t\t    g.update_edge(0, (*w) + wt_sijd, de, min_op);\n                  if(g.lookup(de, 0, &w))\n                    g.update_edge(se, (*w) + wt_sijd, 0, min_op);\n\t\t}\n              }\n            }\n            */\n          }\n        }\n\n        std::vector<std::pair<vert_id, Wt>> dest_dec;\n        for(auto edge : g_excl.e_succs(jj))\n        {\n          vert_id de = edge.vert;\n          Wt wt_ijd = edge.val + c;\n          if(de != ii)\n          {\n            if(g_excl.lookup(ii, de, &w))\n            {\n              if(w.get() <= wt_ijd)\n                continue;\n              w = wt_ijd;\n            } else {\n              g_excl.add_edge(ii, wt_ijd, de);\n            }\n            dest_dec.push_back(std::make_pair(de, edge.val));\n\t    if (Params::close_bounds_inline) {\t  \t\t    \n\t      if(g.lookup(0,  ii, &w))\n\t\tg.update_edge(0, w.get() + wt_ijd, de, min_op);\n\t      if(g.lookup(de, 0, &w))\n\t\tg.update_edge(ii, w.get() + wt_ijd, 0, min_op);\n\t    }\n          }\n        }\n\n        for(auto s_p : src_dec)\n        {\n          vert_id se = s_p.first;\n          Wt wt_sij = c + s_p.second;\n          for(auto d_p : dest_dec)\n          {\n            vert_id de = d_p.first;\n            Wt wt_sijd = wt_sij + d_p.second; \n            if(g.lookup(se, de, &w))\n            {\n              if(w.get() <= wt_sijd)\n                continue;\n              w = wt_sijd;\n            } else {\n              g.add_edge(se, wt_sijd, de);\n            }\n\t    if (Params::close_bounds_inline) {\t  \t\t    \t    \n\t      if(g.lookup(0, se, &w))\n\t\tg.update_edge(0, w.get() + wt_sijd, de, min_op);\n\t      if(g.lookup(de, 0, &w))\n\t\tg.update_edge(se, w.get() + wt_sijd, 0, min_op);\n\t    }\n          }\n        }\n\n        // Closure is now updated.\n      }\n    \n      // Restore closure after a variable assignment\n      // Assumption: x = f(y_1, ..., y_n) cannot induce non-trivial\n      // relations between (y_i, y_j)\n      /*\n      bool close_after_assign(vert_id v)\n      {\n        // Run Dijkstra's forward to collect successors of v,\n        // and backward to collect predecessors\n        edge_vector delta; \n        if(!GrOps::close_after_assign(g, potential, v, delta))\n          return false;\n        GrOps::apply_delta(g, delta);\n        return true; \n      }\n\n      bool closure(void)\n      {\n        // Full Johnson-style all-pairs shortest path\n        CRAB_ERROR(\"SparseWtGraph::closure not yet implemented.\"); \n      }\n      */\n      \n      // return true if edge from x to y with weight k is unsatisfiable\n      bool is_unsat_edge(vert_id x, vert_id y, Wt k){\n\t\n        typename graph_t::mut_val_ref_t w;        \n        if (g.lookup(y,x,&w)) {\n          return ((w.get() + k) < Wt(0));\n        } else {\n          interval_t intv_x = interval_t::top();\n          interval_t intv_y = interval_t::top();\n          if (g.elem(0,x) || g.elem(x,0)) {\n            intv_x = interval_t(\n                g.elem(x, 0) ? -number_t(g.edge_val(x, 0)) : bound_t::minus_infinity(),\n                g.elem(0, x) ?  number_t(g.edge_val(0, x)) : bound_t::plus_infinity());\n          }\n          if (g.elem(0,y) || g.elem(y,0)) {\n            intv_y = interval_t(\n                g.elem(y, 0) ? -number_t(g.edge_val(y, 0)) : bound_t::minus_infinity(),\n                g.elem(0, y) ?  number_t(g.edge_val(0, y)) : bound_t::plus_infinity());\n          }\n          if (intv_x.is_top() || intv_y.is_top()) {\n            return false;\n          } else  {\n            return (!((intv_y - intv_x).lb() <= (number_t) k));\n          }\n        }\n      }\n      \n      SplitDBM_(vert_map_t&& _vert_map, rev_map_t&& _rev_map, graph_t&& _g,\n\t\tstd::vector<Wt>&& _potential, vert_set_t&& _unstable)\n        : vert_map(std::move(_vert_map))\n\t, rev_map(std::move(_rev_map))\n\t, g(std::move(_g))\n\t, potential(std::move(_potential))\n\t, unstable(std::move(_unstable))\n\t, _is_bottom(false) {\n\n\tcrab::CrabStats::count(getDomainName() + \".count.copy\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n\n\tCRAB_LOG(\"zones-split-size\",\n                 auto p = size();\n                 crab::outs() << \"#nodes = \" << p.first << \" #edges=\" << p.second << \"\\n\";);\n\t\n\tassert(g.size() > 0);\n      }\n      \n   public:\n      \n      SplitDBM_(bool is_bottom = false)\n\t: _is_bottom(is_bottom) {\n        g.growTo(1);  // Allocate the zero vector\n        potential.push_back(Wt(0));\n        rev_map.push_back(boost::none);\n      }\n\n      // FIXME: Rewrite to avoid copying if o is _|_\n      SplitDBM_(const DBM_t& o)\n        : vert_map(o.vert_map)\n\t, rev_map(o.rev_map)\n\t, g(o.g)\n\t, potential(o.potential)\n\t, unstable(o.unstable)\n\t, _is_bottom(false) {      \n        crab::CrabStats::count(getDomainName() + \".count.copy\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n\n        if(o._is_bottom)\n          set_to_bottom();\n\n        if(!_is_bottom)\n          assert(g.size() > 0);\n      }\n\n      SplitDBM_(DBM_t&& o)\n        : vert_map(std::move(o.vert_map))\n\t, rev_map(std::move(o.rev_map))\n\t, g(std::move(o.g))\n\t, potential(std::move(o.potential))\n\t, unstable(std::move(o.unstable))\n        , _is_bottom(o._is_bottom) {\n\tcrab::CrabStats::count(getDomainName() + \".count.copy\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n      }\n     \n      SplitDBM_& operator=(const SplitDBM_& o) {     \n        crab::CrabStats::count(getDomainName() + \".count.copy\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n\n        if(this != &o) {\n          if(o._is_bottom) {\n            set_to_bottom();\n\t  } else {\n            _is_bottom = false;\n            vert_map = o.vert_map;\n            rev_map = o.rev_map;\n            g = o.g;\n            potential = o.potential;\n            unstable = o.unstable;\n            assert(g.size() > 0);\n          }\n        }\n        return *this;\n      }\n\n      SplitDBM_& operator=(SplitDBM_&& o) {\n        crab::CrabStats::count(getDomainName() + \".count.copy\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n      \n        if(o._is_bottom) {\n          set_to_bottom();\n        } else {\n          _is_bottom = false;\n          vert_map = std::move(o.vert_map);\n          rev_map = std::move(o.rev_map);\n          g = std::move(o.g);\n          potential = std::move(o.potential);\n          unstable = std::move(o.unstable);\n        }\n        return *this;\n      }\n             \n      void set_to_top() {\n\tSplitDBM_ abs(false);\n\tstd::swap(*this, abs);\n      }\n\n      void set_to_bottom() {\n        vert_map.clear();\n        rev_map.clear();\n        g.clear();\n        potential.clear();\n        unstable.clear();\n        _is_bottom = true;\n      }\n\n      bool is_bottom() {\n        return _is_bottom;\n      }\n    \n      bool is_top() {\n        if(_is_bottom)\n          return false;\n        return g.is_empty();\n      }\n    \n      bool operator<=(DBM_t o)  {\n        crab::CrabStats::count(getDomainName() + \".count.leq\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".leq\");\n\n        // cover all trivial cases to avoid allocating a dbm matrix\n        if (is_bottom()) \n          return true;\n        else if(o.is_bottom())\n          return false;\n        else if (o.is_top())\n          return true;\n        else if (is_top())\n          return false;\n        else {\n          normalize();\n\n          // CRAB_LOG(\"zones-split\", crab::outs() << \"operator<=: \"<< *this<< \"<=?\"<< o <<\"\\n\");\n\n          if(vert_map.size() < o.vert_map.size()) \n            return false;\n\n          typename graph_t::mut_val_ref_t wx; typename graph_t::mut_val_ref_t wy;\n\n          // Set up a mapping from o to this.\n          std::vector<unsigned int> vert_renaming(o.g.size(),-1);\n          vert_renaming[0] = 0;\n          for(auto p : o.vert_map)\n          {\n            if(o.g.succs(p.second).size() == 0 && o.g.preds(p.second).size() == 0)\n              continue;\n\n            auto it = vert_map.find(p.first);\n            // We can't have this <= o if we're missing some\n            // vertex.\n            if(it == vert_map.end()) \n              return false;\n            vert_renaming[p.second] = (*it).second;\n            // vert_renaming[(*it).second] = p.second;\n          }\n\n          assert(g.size() > 0);\n\t  // GrPerm g_perm(vert_renaming, g);\n\n          for(vert_id ox : o.g.verts())\n          {\n            if(o.g.succs(ox).size() == 0)\n              continue;\n\n            assert(vert_renaming[ox] != -1);\n            vert_id x = vert_renaming[ox];\n            for(auto edge : o.g.e_succs(ox))\n            {\n              vert_id oy = edge.vert;\n              assert(vert_renaming[oy] != -1);\n              vert_id y = vert_renaming[oy];\n              Wt ow = edge.val;\n\n              if(g.lookup(x, y, &wx) && (wx.get() <= ow))\n                continue;\n\n              if(!g.lookup(x, 0, &wx) || !g.lookup(0, y, &wy)) \n                return false;\n              if(!(wx.get() + wy.get() <= ow)) \n                return false;\n              \n            }\n          }\n          return true;\n        }\n      }\n      \n      // FIXME: can be done more efficient\n      void operator|=(DBM_t o) {\n        *this = *this | o;\n      }\n\n      DBM_t operator|(DBM_t o) {\n        crab::CrabStats::count(getDomainName() + \".count.join\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n\n        if (is_bottom() || o.is_top())\n          return o;\n        else if (is_top() || o.is_bottom())\n          return *this;\n        else {\n          CRAB_LOG(\"zones-split\",\n                    crab::outs() << \"Before join:\\n\"<<\"DBM 1\\n\"<<*this<<\"\\n\"<<\"DBM 2\\n\"\n\t\t                 << o <<\"\\n\");\n\n          normalize();\n          o.normalize();\n\n          check_potential(g, potential, __LINE__);\n          check_potential(o.g, o.potential, __LINE__);\n\n          // Figure out the common renaming, initializing the\n          // resulting potentials as we go.\n          std::vector<vert_id> perm_x;\n          std::vector<vert_id> perm_y;\n          std::vector<variable_t> perm_inv;\n\n          std::vector<Wt> pot_rx;\n          std::vector<Wt> pot_ry;\n          vert_map_t out_vmap;\n          rev_map_t out_revmap;\n          // Add the zero vertex\n          assert(potential.size() > 0);\n          pot_rx.push_back(0);\n          pot_ry.push_back(0);\n          perm_x.push_back(0);\n          perm_y.push_back(0);\n          out_revmap.push_back(boost::none);\n\n          for(auto p : vert_map)\n          {\n            auto it = o.vert_map.find(p.first); \n            // Variable exists in both\n            if(it != o.vert_map.end())\n            {\n              out_vmap.insert(vmap_elt_t(p.first, perm_x.size()));\n              out_revmap.push_back(p.first);\n\n              pot_rx.push_back(potential[p.second] - potential[0]);\n              // XXX JNL: check this out\n              //pot_ry.push_back(o.potential[p.second] - o.potential[0]);\n              pot_ry.push_back(o.potential[(*it).second] - o.potential[0]);\n              perm_inv.push_back(p.first);\n              perm_x.push_back(p.second);\n              perm_y.push_back((*it).second);\n            }\n          }\n          unsigned int sz = perm_x.size();\n\n          // Build the permuted view of x and y.\n          assert(g.size() > 0);\n          GrPerm gx(perm_x, g);\n          assert(o.g.size() > 0);\n          GrPerm gy(perm_y, o.g);\n\n          // Compute the deferred relations\n          graph_t g_ix_ry;\n          g_ix_ry.growTo(sz);\n          SubGraph<GrPerm> gy_excl(gy, 0);\n          for(vert_id s : gy_excl.verts()) {\n            for(vert_id d : gy_excl.succs(s)) {\n              typename graph_t::mut_val_ref_t ws; typename graph_t::mut_val_ref_t wd;\n              if(gx.lookup(s, 0, &ws) && gx.lookup(0, d, &wd)) {\n                g_ix_ry.add_edge(s, ws.get() + wd.get(), d);\n\t      }\n            }\n          }\n          // Apply the deferred relations, and re-close.\n          bool is_closed;\n          graph_t g_rx(GrOps::meet(gx, g_ix_ry, is_closed));\n          check_potential(g_rx, pot_rx, __LINE__);\n          #ifdef JOIN_CLOSE_AFTER_MEET\n\t  // Conjecture: g_rx is closed\n          if(!is_closed) {\n\t    edge_vector delta;\t    \n            SubGraph<graph_t> g_rx_excl(g_rx, 0);\n            GrOps::close_after_meet(g_rx_excl, pot_rx, gx, g_ix_ry, delta);\n            GrOps::apply_delta(g_rx, delta);\n          }\n          #endif\n\t  \n          graph_t g_rx_iy;\n          g_rx_iy.growTo(sz);\n          SubGraph<GrPerm> gx_excl(gx, 0);\n          for(vert_id s : gx_excl.verts()) {\n            for(vert_id d : gx_excl.succs(s)) {\n              typename graph_t::mut_val_ref_t ws; typename graph_t::mut_val_ref_t wd;\n              // Assumption: gx.mem(s, d) -> gx.edge_val(s, d) <=\n\t      //             ranges[var(s)].ub() - ranges[var(d)].lb()\n              // That is, if the relation exists, it's at least as strong as the bounds.\n              if(gy.lookup(s, 0, &ws) && gy.lookup(0, d, &wd))\n                g_rx_iy.add_edge(s, ws.get() + wd.get(), d);\n            }\n          }\n          // Similarly, should use a SubGraph view.\n          graph_t g_ry(GrOps::meet(gy, g_rx_iy, is_closed));\n          check_potential(g_rx, pot_rx, __LINE__);\t  \n\t  #ifdef JOIN_CLOSE_AFTER_MEET\n\t  // Conjecture: g_ry is closed\n          if(!is_closed) {\n\t    edge_vector delta;\n            SubGraph<graph_t> g_ry_excl(g_ry, 0);\n            GrOps::close_after_meet(g_ry_excl, pot_ry, gy, g_rx_iy, delta);\n            GrOps::apply_delta(g_ry, delta);\n          }\n          #endif\n\t  \n          // We now have the relevant set of relations. Because g_rx\n          // and g_ry are closed, the result is also closed.\n          Wt_min min_op;\n          graph_t join_g(GrOps::join(g_rx, g_ry));\n\n          // Now reapply the missing independent relations.\n          // Need to derive vert_ids from lb_up/lb_down, and make sure the vertices exist\n          std::vector<vert_id> lb_up;\n          std::vector<vert_id> lb_down;\n          std::vector<vert_id> ub_up;\n          std::vector<vert_id> ub_down;\n\n          typename graph_t::mut_val_ref_t wx;\n          typename graph_t::mut_val_ref_t wy;\n          for(vert_id v : gx_excl.verts()) {\n            if(gx.lookup(0, v, &wx) && gy.lookup(0, v, &wy)) {\n              if(wx.get() < wy.get())\n                ub_up.push_back(v);\n              if(wy.get() < wx.get())\n                ub_down.push_back(v);\n            }\n            if(gx.lookup(v, 0, &wx) && gy.lookup(v, 0, &wy)) {\n              if(wx.get() < wy.get())\n                lb_down.push_back(v);\n              if(wy.get() < wx.get())\n                lb_up.push_back(v);\n            }\n          }\n\n          for(vert_id s : lb_up) {\n            Wt dx_s = gx.edge_val(s, 0);\n            Wt dy_s = gy.edge_val(s, 0);\n            for(vert_id d : ub_up) {\n              if(s == d) continue;\n              join_g.update_edge(s, std::max(dx_s + gx.edge_val(0, d),\n\t\t\t\t\t     dy_s + gy.edge_val(0, d)),\n\t\t\t\t d, min_op);\n            }\n          }\n\n          for(vert_id s : lb_down) {\n            Wt dx_s = gx.edge_val(s, 0);\n            Wt dy_s = gy.edge_val(s, 0);\n            for(vert_id d : ub_down) {\n              if(s == d) continue;\n              join_g.update_edge(s, std::max(dx_s + gx.edge_val(0, d),\n\t\t\t\t\t     dy_s + gy.edge_val(0, d)),\n\t\t\t\t d, min_op);\n            }\n          }\n\n          // Conjecture: join_g remains closed.\n          \n          // Now garbage collect any unused vertices\n          for(vert_id v : join_g.verts()) {\n            if(v == 0)\n              continue;\n            if(join_g.succs(v).size() == 0 && join_g.preds(v).size() == 0) {\n              join_g.forget(v);\n              if(out_revmap[v]) {\n                out_vmap.erase(*(out_revmap[v]));\n                out_revmap[v] = boost::none;\n              }\n            }\n          }\n          \n          // DBM_t res(join_range, out_vmap, out_revmap, join_g, join_pot);\n          DBM_t res(std::move(out_vmap), std::move(out_revmap), std::move(join_g), \n                    std::move(pot_rx), vert_set_t());\n          //join_g.check_adjs();\n          CRAB_LOG(\"zones-split\",\n                    crab::outs() << \"Result join:\\n\"<<res <<\"\\n\");\n           \n          return res;\n        }\n      }\n\n      DBM_t operator||(DBM_t o) {\t\n        crab::CrabStats::count(getDomainName() + \".count.widening\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n\n        if (is_bottom())\n          return o;\n        else if (o.is_bottom())\n          return *this;\n        else {\n          CRAB_LOG(\"zones-split\",\n                    crab::outs() << \"Before widening:\\n\"<<\"DBM 1\\n\"<<*this<<\"\\n\"<<\"DBM 2\\n\"\n\t\t    <<o <<\"\\n\");\n          o.normalize();\n          \n          // Figure out the common renaming\n          std::vector<vert_id> perm_x;\n          std::vector<vert_id> perm_y;\n          vert_map_t out_vmap;\n          rev_map_t out_revmap;\n          std::vector<Wt> widen_pot;\n          vert_set_t widen_unstable(unstable);\n\n          assert(potential.size() > 0);\n          widen_pot.push_back(Wt(0));\n          perm_x.push_back(0);\n          perm_y.push_back(0);\n          out_revmap.push_back(boost::none);\n          for(auto p : vert_map)\n          {\n            auto it = o.vert_map.find(p.first); \n            // Variable exists in both\n            if(it != o.vert_map.end())\n            {\n              out_vmap.insert(vmap_elt_t(p.first, perm_x.size()));\n              out_revmap.push_back(p.first);\n\n              widen_pot.push_back(potential[p.second] - potential[0]);\n              perm_x.push_back(p.second);\n              perm_y.push_back((*it).second);\n            }\n          }\n\n          // Build the permuted view of x and y.\n          assert(g.size() > 0);\n          GrPerm gx(perm_x, g);            \n          assert(o.g.size() > 0);\n          GrPerm gy(perm_y, o.g);\n         \n          // Now perform the widening \n          std::vector<vert_id> destabilized;\n          graph_t widen_g(GrOps::widen(gx, gy, destabilized));\n          for(vert_id v : destabilized)\n            widen_unstable.insert(v);\n\n          DBM_t res(std::move(out_vmap), std::move(out_revmap), std::move(widen_g), \n                    std::move(widen_pot), std::move(widen_unstable));\n           \n          CRAB_LOG(\"zones-split\",\n                    crab::outs() << \"Result widening:\\n\"<<res <<\"\\n\");\n          return res;\n        }\n      }\n\n      DBM_t widening_thresholds(DBM_t o, const iterators::thresholds<number_t>& ts) {\n        // TODO: use thresholds\n        return (*this || o);\n      }\n\n      DBM_t operator&(DBM_t o) {\n        crab::CrabStats::count(getDomainName() + \".count.meet\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".meet\");\n\n        if (is_bottom() || o.is_bottom())\n          return DBM_t::bottom();\n        else if (is_top())\n          return o;\n        else if (o.is_top())\n          return *this;\n        else{\n          CRAB_LOG(\"zones-split\",\n                    crab::outs() << \"Before meet:\\n\"<<\"DBM 1\\n\"<<*this<<\"\\n\"<<\"DBM 2\\n\"<<o\n\t\t                 <<\"\\n\");\n          normalize();\n          o.normalize();\n\n          check_potential(g, potential, __LINE__);\n          check_potential(o.g, o.potential, __LINE__);\n\t  \n          // We map vertices in the left operand onto a contiguous range.\n          // This will often be the identity map, but there might be gaps.\n          vert_map_t meet_verts;\n          rev_map_t meet_rev;\n\n          std::vector<vert_id> perm_x;\n          std::vector<vert_id> perm_y;\n          std::vector<Wt> meet_pi;\n          perm_x.push_back(0);\n          perm_y.push_back(0);\n          meet_pi.push_back(Wt(0));\n          meet_rev.push_back(boost::none);\n          for(auto p : vert_map)\n          {\n            vert_id vv = perm_x.size();\n            meet_verts.insert(vmap_elt_t(p.first, vv));\n            meet_rev.push_back(p.first);\n\n            perm_x.push_back(p.second);\n            perm_y.push_back(-1);\n            meet_pi.push_back(potential[p.second] - potential[0]);\n          }\n\n          // Add missing mappings from the right operand.\n          for(auto p : o.vert_map)\n          {\n            auto it = meet_verts.find(p.first);\n\n            if(it == meet_verts.end())\n            {\n              vert_id vv = perm_y.size();\n              meet_rev.push_back(p.first);\n\n              perm_y.push_back(p.second);\n              perm_x.push_back(-1);\n              meet_pi.push_back(o.potential[p.second] - o.potential[0]);\n              meet_verts.insert(vmap_elt_t(p.first, vv));\n            } else {\n              perm_y[(*it).second] = p.second;\n            }\n          }\n\n          // Build the permuted view of x and y.\n          assert(g.size() > 0);\n          GrPerm gx(perm_x, g);\n          assert(o.g.size() > 0);\n          GrPerm gy(perm_y, o.g);\n\n          // Compute the syntactic meet of the permuted graphs.\n          bool is_closed;\n          graph_t meet_g(GrOps::meet(gx, gy, is_closed));\n           \n          // Compute updated potentials on the zero-enriched graph\n          //vector<Wt> meet_pi(meet_g.size());\n          // We've warm-started pi with the operand potentials\n          if(!GrOps::select_potentials(meet_g, meet_pi))\n          {\n            // Potentials cannot be selected -- state is infeasible.\n            return DBM_t::bottom();\n          }\n\n          if(!is_closed)\n          {\n            edge_vector delta;\n            SubGraph<graph_t> meet_g_excl(meet_g, 0);\n\t    // GrOps::close_after_meet(meet_g_excl, meet_pi, gx, gy, delta);\n\n            if(Params::chrome_dijkstra)\n              GrOps::close_after_meet(meet_g_excl, meet_pi, gx, gy, delta);\n            else\n              GrOps::close_johnson(meet_g_excl, meet_pi, delta);\n\n            GrOps::apply_delta(meet_g, delta);\n\n\t    // Recover updated LBs and UBs.\n\t    if (Params::close_bounds_inline) {\t    \n\t      Wt_min min_op;\n\t      for(auto e : delta) {\n\t\tif(meet_g.elem(0, e.first.first))\n\t\t  meet_g.update_edge(0, meet_g.edge_val(0, e.first.first) + e.second,\n\t\t\t\t     e.first.second, min_op);\n\t\tif(meet_g.elem(e.first.second, 0))\n\t\t  meet_g.update_edge(e.first.first, meet_g.edge_val(e.first.second, 0) +\n\t\t\t\t     e.second, 0, min_op);\n\t      }\n\t    } else {\n\t      delta.clear();\n\t      GrOps::close_after_assign(meet_g, meet_pi, 0, delta);\n\t      GrOps::apply_delta(meet_g, delta);\n\t    }\n          }\n          check_potential(meet_g, meet_pi, __LINE__); \n          DBM_t res(std::move(meet_verts), std::move(meet_rev), std::move(meet_g), \n                    std::move(meet_pi), vert_set_t());\n          CRAB_LOG(\"zones-split\",\n                    crab::outs() << \"Result meet:\\n\"<<res <<\"\\n\");\n          return res;\n        }\n      }\n    \n      DBM_t operator&&(DBM_t o) {\n        crab::CrabStats::count(getDomainName() + \".count.narrowing\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".narrowing\");\n\n        if (is_bottom() || o.is_bottom())\n          return DBM_t::bottom();\n        else if (is_top())\n          return o;\n        else{\n          CRAB_LOG(\"zones-split\",\n                    crab::outs() << \"Before narrowing:\\n\"<<\"DBM 1\\n\"<<*this<<\"\\n\"<<\"DBM 2\\n\"\n\t\t                 << o <<\"\\n\");\n\n          // FIXME: Implement properly\n          // Narrowing as a no-op should be sound.\n          normalize();\n          DBM_t res(*this);\n\n          CRAB_LOG(\"zones-split\",\n                    crab::outs() << \"Result narrowing:\\n\"<<res <<\"\\n\");\n          return res;\n        }\n      }\t\n\n      void normalize() {\n        crab::CrabStats::count(getDomainName() + \".count.normalize\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".normalize\");\n\t\n        // dbm_canonical(_dbm);\n        // Always maintained in normal form, except for widening\n        #ifdef SDBM_NO_NORMALIZE\n        return;\n        #endif\n        if(unstable.size() == 0)\n          return;\n\n        edge_vector delta;\n\t// GrOps::close_after_widen(g, potential, vert_set_wrap_t(unstable), delta);\n        // GKG: Check\n        SubGraph<graph_t> g_excl(g, 0);\n        if(Params::widen_restabilize)\n          GrOps::close_after_widen(g_excl, potential, vert_set_wrap_t(unstable), delta);\n        else\n          GrOps::close_johnson(g_excl, potential, delta);\n        // Retrive variable bounds\n        GrOps::close_after_assign(g, potential, 0, delta);\n\n        GrOps::apply_delta(g, delta);\n\n        unstable.clear();\n      }\n\n      void minimize() {}\n      \n      void operator-=(variable_t v) {\n        crab::CrabStats::count(getDomainName() + \".count.forget\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n\t\n        if (is_bottom())\n          return;\n        normalize();\n\n        auto it = vert_map.find(v);\n        if (it != vert_map.end()) {\n          CRAB_LOG(\"zones-split\", crab::outs() << \"Before forget \"<< it->second<< \": \"\n\t\t                               << g <<\"\\n\");\n          g.forget(it->second);\n          CRAB_LOG(\"zones-split\", crab::outs() << \"After: \"<< g <<\"\\n\");\n          rev_map[it->second] = boost::none;\n          vert_map.erase(v);\n        }\n      }\n\n      void assign(variable_t x, linear_expression_t e) {\n        crab::CrabStats::count(getDomainName() + \".count.assign\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n\n        if(is_bottom()) {\n          return;\n\t}\n\t\n        CRAB_LOG(\"zones-split\", crab::outs() << \"Before assign: \"<< *this <<\"\\n\");\n        CRAB_LOG(\"zones-split\", crab::outs() << x<< \":=\"<< e <<\"\\n\");\n        normalize();\n\n        check_potential(g, potential, __LINE__);\n\n\tinterval_t x_int = eval_interval(e);\n\t\n\tboost::optional<Wt> lb_w, ub_w;\n\tbool overflow;\n\tif(x_int.lb().is_finite()) {\n\t  lb_w = ntow::convert(-(*(x_int.lb().number())), overflow);\n\t  if (overflow) {\n\t    operator-=(x);\n\t    CRAB_LOG(\"zones-split\", crab::outs() << \"---\"<< x<< \":=\"<< e<<\"\\n\"<<*this <<\"\\n\");\n\t    return;\n\t  }\n\t}\n\tif(x_int.ub().is_finite()) {\n\t  ub_w = ntow::convert(*(x_int.ub().number()), overflow);\n\t  if (overflow) {\n\t    operator-=(x);\n\t    CRAB_LOG(\"zones-split\", crab::outs() << \"---\"<< x<< \":=\"<< e<<\"\\n\"<<*this <<\"\\n\");\n\t    return;\n\t  }\n\t}\n\t\n\tbool is_rhs_constant = false;\n        // If it's a constant, just assign the interval.\n\tif (!Params::close_bounds_inline) {\n\t  // JN: it seems that we can only do this if\n\t  // close_bounds_inline is disabled. Otherwise, the meet\n\t  // operator misses some non-redundant edges. Need to\n\t  // investigate more this.\n\t  if (boost::optional<number_t> x_n = x_int.singleton()) {\n\t    set(x, *x_n);\n\t    is_rhs_constant = true;\n\t  }\n\t} else {\n\t  if (e.is_constant()) {\n\t    set(x, e.constant());\n\t    is_rhs_constant = true;\t    \n\t  }\n\t}\n\n\tif (!is_rhs_constant) {\n\t  std::vector<std::pair<variable_t, Wt>> diffs_lb, diffs_ub;\n\t  // Construct difference constraints from the assignment\n\t  diffcsts_of_assign(x, e, diffs_lb, diffs_ub);\n\t  if(diffs_lb.size() > 0 || diffs_ub.size() > 0) {\n\t    if(Params::special_assign) {\n\t      bool overflow;\n\t      Wt e_val = eval_expression(e, overflow);\n\t      if (overflow) {\n\t\toperator-=(x);\n\t\treturn;\n\t      }\n\t      // Allocate a new vertex for x\n\t      vert_id v = g.new_vertex();\n\t      assert(v <= rev_map.size());\n\t      if(v == rev_map.size()) {\n\t\trev_map.push_back(x);\n\t\tpotential.push_back(potential[0] + e_val);\n\t      } else {\n\t\tpotential[v] = potential[0] + e_val;\n\t\trev_map[v] = x;\n\t      }\n\t      \n\t      edge_vector delta;\n\t      for(auto diff : diffs_lb) {\n\t\tdelta.push_back({{v, get_vert(diff.first)}, -diff.second});\n\t      }\n\t      \n\t      for(auto diff : diffs_ub) {\n\t\tdelta.push_back({{get_vert(diff.first), v}, diff.second});\n\t      }\n\t      \n\t      // apply_delta should be safe here, as x has no edges in G.\n\t      GrOps::apply_delta(g, delta);\n\t      delta.clear();\n\t      SubGraph<graph_t> g_excl(g, 0);\n\t      GrOps::close_after_assign(g_excl, potential, v, delta);\n\t      GrOps::apply_delta(g, delta);\n\t      \n\t      Wt_min min_op;\n\t      if(lb_w) {\n\t\tg.update_edge(v, *lb_w, 0, min_op);\n\t      }\n\t      if(ub_w) {\n\t\tg.update_edge(0, *ub_w, v, min_op);\n\t      }\n\t      // Clear the old x vertex\n              operator-=(x);\n              vert_map.insert(vmap_elt_t(x, v));\n\t    } else {\n\t      // Assignment as a sequence of edge additions.\n\t      vert_id v = g.new_vertex();\n\t      assert(v <= rev_map.size());\n\t      if(v == rev_map.size()) {\n\t\trev_map.push_back(x);\n\t\tpotential.push_back(Wt(0));\n\t      } else {\n\t\tpotential[v] = Wt(0);\n\t\trev_map[v] = x;\n\t      }\n\t      Wt_min min_op;\n\t      edge_vector cst_edges;\n\t      \n\t      for(auto diff : diffs_lb) {\n\t\tcst_edges.push_back({{v, get_vert(diff.first)}, -diff.second});\n\t      }\n\t      \n\t      for(auto diff : diffs_ub) {\n\t\tcst_edges.push_back({{get_vert(diff.first), v}, diff.second});\n\t      }\n\t      \n\t      for(auto diff : cst_edges) {\n\t\tvert_id src = diff.first.first;\n\t\tvert_id dest = diff.first.second;\n\t\tg.update_edge(src, diff.second, dest, min_op);\n\t\tif(!repair_potential(src, dest)) {\n\t\t  assert(0 && \"Unreachable\");\n\t\t  set_to_bottom();\n\t\t}\n\t\tcheck_potential(g, potential, __LINE__);\t\t\n\t\tclose_over_edge(src, dest);\n\t\tcheck_potential(g, potential, __LINE__);\n\t      }\n\n\t      if(lb_w) {\n\t\tg.update_edge(v, *lb_w, 0, min_op);\n\t      }\n\t      if(ub_w) {\n\t\tg.update_edge(0, *ub_w, v, min_op);\n\t      }\n\t      \n\t      // Clear the old x vertex\n\t      operator-=(x);\n\t      vert_map.insert(vmap_elt_t(x, v));\n\t    }\n\t  } else {\n\t    set(x, x_int);\n\t  }\n\t}\n\t\n\t// CRAB_WARN(\"DBM only supports a cst or var on the rhs of assignment\");\n\t// this->operator-=(x);\n\t// g.check_adjs(); \n\n        check_potential(g, potential, __LINE__);\n        CRAB_LOG(\"zones-split\", crab::outs() << \"---\"<< x<< \":=\"<< e<<\"\\n\"<<*this <<\"\\n\");\n      }\n\n      void apply(operation_t op, variable_t x, variable_t y, variable_t z){\t\n        crab::CrabStats::count(getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        if(is_bottom()) {\n          return;\n\t}\n\n        normalize();\n\n        switch(op) {\n          case OP_ADDITION:\n            assign(x, y + z);\n            return;\n          case OP_SUBTRACTION:\n            assign(x, y - z);\n            return;\n          // For the rest of operations, we fall back on intervals.\n          case OP_MULTIPLICATION:\n            set(x, get_interval(y)*get_interval(z));\n            break;\n          case OP_SDIV:\n            set(x, get_interval(y)/get_interval(z));\n            break;\n          case OP_UDIV:\n            set(x, get_interval(y).UDiv(get_interval(z)));\n            break;\n          case OP_SREM:\n            set(x, get_interval(y).SRem(get_interval(z)));\n            break;\n          case OP_UREM:\n            set(x, get_interval(y).URem(get_interval(z)));\n            break;\n\t  default:\n\t    CRAB_ERROR(\"Operation \", op, \" not supported\");\n        }\n\t\n        CRAB_LOG(\"zones-split\",\n                 crab::outs() << \"---\"<< x<< \":=\"<< y<< op<< z<<\"\\n\"<< *this <<\"\\n\");\n      }\n\n    \n      void apply(operation_t op, variable_t x, variable_t y, number_t k) {\t\n        crab::CrabStats::count(getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        if(is_bottom()) {\n          return;\n\t}\n\n        normalize();\n\n        switch(op) {\n          case OP_ADDITION:\n            assign(x, y + k);\n            return;\n          case OP_SUBTRACTION:\n            assign(x, y - k);\n            return;\n          case OP_MULTIPLICATION:\n\t    assign(x, k * y);\n\t    return;\n          // For the rest of operations, we fall back on intervals.\t    \n          case OP_SDIV:\n            set(x, get_interval(y)/interval_t(k));\n            break;\n          case OP_UDIV:\n            set(x, get_interval(y).UDiv(interval_t(k)));\n            break;\n          case OP_SREM:\n            set(x, get_interval(y).SRem(interval_t(k)));\n            break;\n          case OP_UREM:\n            set(x, get_interval(y).URem(interval_t(k)));\n            break;\n\t  default:\n\t    CRAB_ERROR(\"Operation \", op, \" not supported\");\n        }\n\n        CRAB_LOG(\"zones-split\",\n                 crab::outs() << \"---\"<< x<< \":=\"<< y<< op<< k<<\"\\n\"<< *this <<\"\\n\");\n      }\n      \n      void backward_assign(variable_t x, linear_expression_t e, DBM_t inv) {\n        crab::CrabStats::count(getDomainName() + \".count.backward_assign\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".backward_assign\");\n\t\n\tcrab::domains::BackwardAssignOps<DBM_t>::\n\t  assign(*this, x, e, inv);\n      }\n      \n      void backward_apply(operation_t op, variable_t x, variable_t y, number_t z,\n\t\t\t  DBM_t inv) {\n        crab::CrabStats::count(getDomainName() + \".count.backward_apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".backward_apply\");\n\t\n\tcrab::domains::BackwardAssignOps<DBM_t>::\n\t  apply(*this, op, x, y, z, inv);\n      }\n      \n      void backward_apply(operation_t op, variable_t x, variable_t y, variable_t z,\n\t\t\t  DBM_t inv) {\n        crab::CrabStats::count(getDomainName() + \".count.backward_apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".backward_apply\");\n\t\n\tcrab::domains::BackwardAssignOps<DBM_t>::\n\t  apply(*this, op, x, y, z, inv);\n      }\n      \n      void operator+=(linear_constraint_t cst) {\n        crab::CrabStats::count(getDomainName() + \".count.add_constraints\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".add_constraints\");\n\n\t// XXX: we do nothing with unsigned linear inequalities\n\tif (cst.is_inequality() && cst.is_unsigned()) {\n\t  CRAB_WARN(\"unsigned inequality \", cst, \" skipped by split_dbm domain\");\t  \n\t  return;\n\t}\n\t\n        if(is_bottom())\n          return;\n        normalize();\n\n        if (cst.is_tautology())\n          return;\n\n\t// g.check_adjs();\n      \n        if (cst.is_contradiction()){\n          set_to_bottom();\n          return ;\n        }\n\n        if (cst.is_inequality()) {\n          if(!add_linear_leq(cst.expression())) {\n            set_to_bottom();\n\t  }\n\t  //  g.check_adjs();\n          CRAB_LOG(\"zones-split\",\n                   crab::outs() << \"--- \"<< cst<< \"\\n\"<< *this <<\"\\n\");\n          return;\n        }\n\n        if (cst.is_strict_inequality()) {\n\t  // We try to convert a strict to non-strict.\n\t  auto nc = linear_constraint_impl::strict_to_non_strict_inequality(cst);\n\t  if (nc.is_inequality()) {\n\t    // here we succeed\n\t    if(!add_linear_leq(nc.expression())) {\n\t      set_to_bottom();\n\t    }\n\t    CRAB_LOG(\"zones-split\",\n\t\t     crab::outs() << \"--- \"<< cst<< \"\\n\"<< *this <<\"\\n\");\n\t    return;\n\t  }\n\t}\n\t\n        if (cst.is_equality()) {\n          linear_expression_t exp = cst.expression();\n          if(!add_linear_leq(exp) || !add_linear_leq(-exp)) {\n            CRAB_LOG(\"zones-split\", crab::outs() << \" ~~> _|_\" <<\"\\n\");\n            set_to_bottom();\n          }\n\t  // g.check_adjs();\n          CRAB_LOG(\"zones-split\",\n                   crab::outs() << \"--- \"<< cst<< \"\\n\"<< *this <<\"\\n\");\n          return;\n        }\n\n        if (cst.is_disequation()) {\n          add_disequation(cst.expression());\n          return;\n        }\n\n        CRAB_WARN(\"Unhandled constraint \", cst, \" by split_dbm\");\n        CRAB_LOG(\"zones-split\",\n                 crab::outs() << \"---\"<< cst<< \"\\n\"<< *this <<\"\\n\");\n        return;\n      }\n    \n      void operator+=(linear_constraint_system_t csts) {  \n        if(is_bottom()) return;\n\n        for(auto cst: csts) {\n          operator+=(cst);\n        }\n      }\n\n      interval_t operator[](variable_t x) { \n        crab::CrabStats::count(getDomainName() + \".count.to_intervals\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".to_intervals\");\n\n        // if (is_top())    return interval_t::top();\n\n        if (is_bottom()) {\n\t  return interval_t::bottom();\n        } else {\n          return get_interval(vert_map, g, x);\n        }\n      }\n\n      void set(variable_t x, interval_t intv) {\n        crab::CrabStats::count(getDomainName() + \".count.assign\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n\n        if(is_bottom())\n\t  return;          \n\n\tif (intv.is_bottom()) {\n\t  set_to_bottom();\n\t  return;\n\t}\n\t\n        this->operator-=(x);\n\n        if(intv.is_top()) {\n          return;\n\t}\n\n        vert_id v = get_vert(x);\n\tbool overflow;\n        if(intv.ub().is_finite()) {\n          Wt ub = ntow::convert(*(intv.ub().number()), overflow);\n\t  if (overflow) {\n\t    return;\n\t  }\n          potential[v] = potential[0] + ub;\n          g.set_edge(0, ub, v);\n        }\n        if(intv.lb().is_finite()) {\n          Wt lb = ntow::convert(*(intv.lb().number()), overflow);\n\t  if (overflow) {\n\t    return;\n\t  }\n          potential[v] = potential[0] + lb;\n          g.set_edge(v, -lb, 0);\n        }\n      }\n\n      // int_cast_operators_api\n\n      void apply(int_conv_operation_t /*op*/, variable_t dst, variable_t src) {\n        // since reasoning about infinite precision we simply assign and\n        // ignore the widths.\n        assign(dst, src);\n      }\n\n      // bitwise_operators_api      \n      void apply(bitwise_operation_t op, variable_t x, variable_t y, variable_t z) {\n        crab::CrabStats::count(getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        if(is_bottom()) return;\n        normalize();\n\n        // Convert to intervals and perform the operation\t\n        interval_t yi = operator[](y);\n        interval_t zi = operator[](z);\n        interval_t xi = interval_t::bottom();\n        switch (op) {\n          case OP_AND: {\n            xi = yi.And(zi);\n            break;\n          }\n          case OP_OR: {\n            xi = yi.Or(zi);\n            break;\n          }\n          case OP_XOR: {\n            xi = yi.Xor(zi);\n            break;\n          }\n          case OP_SHL: {\n            xi = yi.Shl(zi);\n            break;\n          }\n          case OP_LSHR: {\n            xi = yi.LShr(zi);\n            break;\n          }\n          case OP_ASHR: {\n            xi = yi.AShr(zi);\n            break;\n          }\n          default: \n            CRAB_ERROR(\"DBM: unreachable\");\n        }\n        set(x, xi);\n      }\n    \n      void apply(bitwise_operation_t op, variable_t x, variable_t y, number_t k) {\n        crab::CrabStats::count(getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        if(is_bottom()) return;\n        normalize();\n\t\n        // Convert to intervals and perform the operation\n        interval_t yi = operator[](y);\n        interval_t zi(k);\n        interval_t xi = interval_t::bottom();\n\n        switch (op) {\n          case OP_AND: {\n            xi = yi.And(zi);\n            break;\n          }\n          case OP_OR: {\n            xi = yi.Or(zi);\n            break;\n          }\n          case OP_XOR: {\n            xi = yi.Xor(zi);\n            break;\n          }\n          case OP_SHL: {\n            xi = yi.Shl(zi);\n            break;\n          }\n          case OP_LSHR: {\n            xi = yi.LShr(zi);\n            break;\n          }\n          case OP_ASHR: {\n            xi = yi.AShr(zi);\n            break;\n          }\n          default: \n            CRAB_ERROR(\"DBM: unreachable\");\n        }\n        set(x, xi);\n      }\n\n      /* \n\t Begin unimplemented operations \n\t \n\t SplitDBM implements only standard abstract operations of a\n\t numerical domain.  The implementation of boolean, array, or\n\t pointer operations is empty because they should never be\n\t called.\n      */      \n      // boolean operations\n      void assign_bool_cst(variable_t lhs, linear_constraint_t rhs) {}\n      void assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs) {}\n      void apply_binary_bool(bool_operation_t op, variable_t x,variable_t y,variable_t z) {}\n      void assume_bool(variable_t v, bool is_negated) {}\n      // backward boolean operations\n      void backward_assign_bool_cst(variable_t lhs, linear_constraint_t rhs,\n\t\t\t\t    DBM_t invariant){}\n      void backward_assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs,\n\t\t\t\t      DBM_t invariant) {}\n      void backward_apply_binary_bool(bool_operation_t op,\n\t\t\t\t      variable_t x,variable_t y,variable_t z,\n\t\t\t\t      DBM_t invariant) {}\n      // array operations\n      void array_init(variable_t a, linear_expression_t elem_size,\n\t\t      linear_expression_t lb_idx, linear_expression_t ub_idx, \n\t\t      linear_expression_t val) {}      \n      void array_load(variable_t lhs,\n\t\t      variable_t a, linear_expression_t elem_size,\n\t\t      linear_expression_t i) {}\n      void array_store(variable_t a, linear_expression_t elem_size,\n\t\t       linear_expression_t i, linear_expression_t v, \n\t\t       bool is_strong_update) {}\n      void array_store(variable_t a_new, variable_t a_old,\n\t\t       linear_expression_t elem_size,\n\t\t       linear_expression_t i, linear_expression_t v, \n\t\t       bool is_strong_update) {}      \n      void array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t     linear_expression_t i, linear_expression_t j,\n\t\t\t     linear_expression_t v) {}\n      void array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t     linear_expression_t elem_size,\n\t\t\t     linear_expression_t i, linear_expression_t j,\n\t\t\t     linear_expression_t v) {}      \n      void array_assign(variable_t lhs, variable_t rhs) {}\n      // backward array operations\n      void backward_array_init(variable_t a, linear_expression_t elem_size,\n\t\t\t       linear_expression_t lb_idx, linear_expression_t ub_idx, \n\t\t\t       linear_expression_t val, DBM_t invariant) {}      \n      void backward_array_load(variable_t lhs,\n\t\t\t       variable_t a, linear_expression_t elem_size,\n\t\t\t       linear_expression_t i, DBM_t invariant) {}\n      void backward_array_store(variable_t a, linear_expression_t elem_size,\n\t\t\t\tlinear_expression_t i, linear_expression_t v, \n\t\t\t\tbool is_strong_update, DBM_t invariant) {}\n      void backward_array_store(variable_t a_new, variable_t a_old,\n\t\t\t\tlinear_expression_t elem_size,\n\t\t\t\tlinear_expression_t i, linear_expression_t v, \n\t\t\t\tbool is_strong_update, DBM_t invariant) {}      \n      void backward_array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t\t      linear_expression_t i, linear_expression_t j,\n\t\t\t\t      linear_expression_t v, DBM_t invariant) {}\n      void backward_array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t\t      linear_expression_t elem_size,\n\t\t\t\t      linear_expression_t i, linear_expression_t j,\n\t\t\t\t      linear_expression_t v, DBM_t invariant) {}          \n      void backward_array_assign(variable_t lhs, variable_t rhs, DBM_t invariant) {}      \n      // pointer operations\n      void pointer_load(variable_t lhs, variable_t rhs)  {}\n      void pointer_store(variable_t lhs, variable_t rhs) {} \n      void pointer_assign(variable_t lhs, variable_t rhs, linear_expression_t offset) {}\n      void pointer_mk_obj(variable_t lhs, ikos::index_t address) {}\n      void pointer_function(variable_t lhs, varname_t func) {}\n      void pointer_mk_null(variable_t lhs) {}\n      void pointer_assume(pointer_constraint_t cst) {}\n      void pointer_assert(pointer_constraint_t cst) {}\n      /* End unimplemented operations */\n\n      void project(const variable_vector_t& variables) {\n        crab::CrabStats::count(getDomainName() + \".count.project\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".project\");\n\n        if (is_bottom() || is_top()) {\n          return;\n\t}\n\t\n        if (variables.empty()) {\n\t  set_to_top();\n          return;\n\t}\n\n        normalize();\n\n        std::vector<bool> save(rev_map.size(), false);\n        for(auto x : variables) {\n          auto it = vert_map.find(x);\n          if(it != vert_map.end())\n            save[(*it).second] = true;\n        }\n\n        for(vert_id v = 0; v < rev_map.size(); v++) {\n          if(!save[v] && rev_map[v]) {\n            operator-=((*rev_map[v]));\n\t  }\n        }\n      }\n\n      \n      void forget(const variable_vector_t& variables) {\n        crab::CrabStats::count(getDomainName() + \".count.forget\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n\t\n        if (is_bottom() || is_top()) {\n          return;\n\t}\n\t\n        for (auto v: variables) {\n          auto it = vert_map.find(v);\n          if (it != vert_map.end()) {\n            operator-=(v);\n          }\n        }\n      }\n      \n      void expand(variable_t x, variable_t y) {\n        crab::CrabStats::count(getDomainName() + \".count.expand\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".expand\");\n\n        if(is_bottom() || is_top()) {\n          return;\n\t}\n        \n        CRAB_LOG(\"zones-split\",\n                  crab::outs() << \"Before expand \" << x << \" into \" << y << \":\\n\"\n\t\t               << *this <<\"\\n\");\n\n        auto it = vert_map.find(y);\n        if(it != vert_map.end()) {\n          CRAB_ERROR(\"split_dbm expand operation failed because y already exists\");\n        }\n        \n        vert_id ii = get_vert(x);\n        vert_id jj = get_vert(y);\n\n        for (auto edge : g.e_preds(ii)) {   \n          g.add_edge(edge.vert, edge.val, jj);\n\t}\n        \n        for (auto edge : g.e_succs(ii)) {  \n          g.add_edge(jj, edge.val, edge.vert);\n\t}\n\n\tpotential[jj] = potential[ii];\n\t\n        CRAB_LOG(\"zones-split\",\n                  crab::outs() << \"After expand \" << x << \" into \" << y << \":\\n\"\n\t\t               << *this <<\"\\n\");\n      }\n\n      void rename(const variable_vector_t &from, const variable_vector_t &to) {\n        crab::CrabStats::count(getDomainName() + \".count.rename\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".rename\");\n\t\n\tif (is_top() || is_bottom()) return;\n\t\n\t// renaming vert_map by creating a new vert_map since we are\n\t// modifying the keys.\n\t// rev_map is modified in-place since we only modify values.\n\tCRAB_LOG(\"zones-split\",\n\t\t crab::outs() << \"Replacing {\";\n\t\t for (auto v: from) crab::outs() << v << \";\";\n\t\t crab::outs() << \"} with \";\n\t\t for (auto v: to) crab::outs() << v << \";\";\n\t\t crab::outs() << \"}:\\n\";\n\t\t crab::outs() << *this << \"\\n\";);\n\t\n\tvert_map_t new_vert_map;\n\tfor (auto kv: vert_map) {\n\t  ptrdiff_t pos = std::distance(from.begin(),\n\t\t\t\t\tstd::find(from.begin(), from.end(), kv.first));\n\t  if (pos < from.size()) {\n\t    variable_t new_v(to[pos]);\n\t    new_vert_map.insert(vmap_elt_t(new_v, kv.second));\n\t    rev_map[kv.second] = new_v;\n\t  } else {\n\t    new_vert_map.insert(kv);\n\t  }\n\t}\n\tstd::swap(vert_map, new_vert_map);\n\n\tCRAB_LOG(\"zones-split\",\n\t\t crab::outs() << \"RESULT=\" << *this << \"\\n\");\n      }\n            \n      void extract(const variable_t& x, linear_constraint_system_t& csts,\n\t\t   bool only_equalities){\n        crab::CrabStats::count(getDomainName() + \".count.extract\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".extract\");\n\n        normalize();\n        if (is_bottom()) {\n\t  return;\n\t}\n\n        auto it = vert_map.find(x);\n        if(it != vert_map.end()) {\n          vert_id s = (*it).second;\n          if(rev_map[s]) {\n            variable_t vs = *rev_map[s];\n            SubGraph<graph_t> g_excl(g, 0);\n            for(vert_id d : g_excl.verts()) {\n              if(rev_map[d]) {\n                variable_t vd = *rev_map[d];\n                // We give priority to equalities since some domains\n                // might not understand inequalities\n                if (g_excl.elem(s, d) && g_excl.elem(d, s) &&\n                    g_excl.edge_val(s, d) == Wt(0) &&\n\t\t    g_excl.edge_val(d, s) == Wt(0)) {\n                  linear_constraint_t cst(linear_expression_t(vs) == vd);\n                  csts += cst;\n                } else {\n\t\t  if (!only_equalities && g_excl.elem(s, d)) {\n\t\t    linear_constraint_t cst(vd - vs <= number_t(g_excl.edge_val(s, d)));\n\t\t    csts += cst;\n\t\t  }\n\t\t  if (!only_equalities && g_excl.elem(d, s)) {\n\t\t    linear_constraint_t cst(vs - vd <= number_t(g_excl.edge_val(d, s)));\n\t\t    csts += cst;\n\t\t  }\n\t\t}\n              }\n            }\n          }\n        }\n      }\n\n      // -- begin array_sgraph_domain_helper_traits\n\t\n      // return true iff cst is unsatisfiable without modifying the DBM\n      bool is_unsat(linear_constraint_t cst) {\n        if (is_bottom() || cst.is_contradiction()) {\n          return true;\n      \t}\n\n        if (is_top() || cst.is_tautology()) {\n          return false;\n      \t}\n\n        std::vector<std::pair<variable_t, Wt>> lbs, ubs;\n        std::vector<diffcst_t> diffcsts;\n\t\n      \tif (cst.is_inequality()) {\n      \t  linear_expression_t exp = cst.expression();\n      \t  diffcsts_of_lin_leq(exp, diffcsts, lbs, ubs);\n      \t} else if (cst.is_strict_inequality()) {\n      \t  auto nc = linear_constraint_impl::strict_to_non_strict_inequality(cst);\n      \t  if (nc.is_inequality()) {\n      \t    linear_expression_t exp = nc.expression();\n      \t    diffcsts_of_lin_leq(exp, diffcsts, lbs, ubs);\t    \n      \t  } else {\n      \t    // we couldn't convert the strict into a non-strict \n      \t    return false;\n      \t  }\n      \t} else if (cst.is_equality()) {\n\t  linear_expression_t exp = cst.expression();\n\t  diffcsts_of_lin_leq(exp, diffcsts, lbs, ubs);\n\t  diffcsts_of_lin_leq(-exp, diffcsts, lbs, ubs);\n      \t} else {\n      \t  return false;\n      \t}\n\n      \t// check difference constraints\n      \tfor (auto diffcst: diffcsts) {\n\t  variable_t x = diffcst.first.first;\n\t  variable_t y = diffcst.first.second;\n\t  Wt k = diffcst.second;\n      \t  if (is_unsat_edge(get_vert(y), get_vert(x), k)) {\n      \t    return true;\n      \t  }\n      \t}\n\t\n      \t// check interval constraints\n      \tfor (auto ub: ubs) {\n      \t  if (is_unsat_edge(0, get_vert(ub.first), ub.second)) {\n      \t    return true;\n      \t  }\n      \t}\n      \tfor (auto lb: lbs) {\n      \t  if (is_unsat_edge(get_vert(lb.first), 0, -lb.second)) {\n      \t    return true;\n      \t  }\n      \t}\n\n      \treturn false;\n      }\n\n      void active_variables(std::vector<variable_t>& out) const {\n        out.reserve(g.size());\n        for (auto v: g.verts()) {\n          if (rev_map[v]) {\n            out.push_back((*(rev_map[v])));\n\t  }\n        }\n      }\n      // -- end array_sgraph_domain_helper_traits\n      \n      // Output function\n      void write(crab_os& o) {\n        crab::CrabStats::count(getDomainName() + \".count.write\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".write\");\n\n        normalize();\n        #if 0\n        o << \"edges={\";\n        for(vert_id v : g.verts())\n        {\n          for(vert_id d : g.succs(v))\n          {\n            if(!rev_map[v] || !rev_map[d])\n            {\n              CRAB_WARN(\"Edge incident to un-mapped vertex.\");\n              continue;\n            }\n            o << \"(\" << (*(rev_map[v])) << \",\" << (*(rev_map[d])) << \":\"\n\t             << g.edge_val(v,d) << \")\";\n          }\n        }\n        o << \"}\";\n        crab::outs() << \"rev_map={\";\n        for(unsigned i=0, e = rev_map.size(); i!=e; i++) {\n          if (rev_map[i])\n            crab::outs() << *(rev_map[i]) << \"(\" << i << \");\";\n        }\n        crab::outs() << \"}\\n\";\n        #endif \n\n        if(is_bottom()){\n          o << \"_|_\";\n          return;\n        }\n        else if (is_top()){\n          o << \"{}\";\n          return;\n        }\n        else\n        {\n          // Intervals\n          bool first = true;\n          o << \"{\";\n          // Extract all the edges\n          SubGraph<graph_t> g_excl(g, 0);\n          for(vert_id v : g_excl.verts())\n          {\n            if(!rev_map[v])\n              continue;\n            if(!g.elem(0, v) && !g.elem(v, 0))\n             continue; \n            interval_t v_out = interval_t(\n                g.elem(v, 0) ? -number_t(g.edge_val(v, 0)) : bound_t::minus_infinity(),\n                g.elem(0, v) ? number_t(g.edge_val(0, v)) : bound_t::plus_infinity());\n\n            if(first)\n              first = false;\n            else\n              o << \", \";\n            o << *(rev_map[v]) << \" -> \" << v_out;\n          }\n\n          for(vert_id s : g_excl.verts())\n          {\n            if(!rev_map[s])\n              continue;\n            variable_t vs = *rev_map[s];\n            for(vert_id d : g_excl.succs(s))\n            {\n              if(!rev_map[d])\n                continue;\n              variable_t vd = *rev_map[d];\n\n              if(first)\n                first = false;\n              else\n                o << \", \";\n              o << vd << \"-\" << vs << \"<=\" << g_excl.edge_val(s, d);\n            }\n          }\n          o << \"}\";\n\n\t  // linear_constraint_system_t inv = to_linear_constraint_system();\n\t  // o << inv;\n        }\n      }\n\n      linear_constraint_system_t to_linear_constraint_system() {\n        crab::CrabStats::count(getDomainName() + \".count.to_linear_constraints\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".to_linear_constraints\");\n\n        normalize();\n\n        linear_constraint_system_t csts;\n    \n        if(is_bottom()) {\n          csts += linear_constraint_t::get_false();\n          return csts;\n        }\n\n        // Extract all the edges\n\n        SubGraph<graph_t> g_excl(g, 0);\n\n        for(vert_id v : g_excl.verts()) {\n          if(!rev_map[v])\n            continue;\n          if(g.elem(v, 0)) {\n            csts += linear_constraint_t(\n\t    \t      linear_expression_t(*rev_map[v]) >= -number_t(g.edge_val(v, 0)));\n\t  }\n          if(g.elem(0, v))\n            csts += linear_constraint_t(\n\t\t      linear_expression_t(*rev_map[v]) <= number_t(g.edge_val(0, v)));\n        }\n\n        for(vert_id s : g_excl.verts()) {\n          if(!rev_map[s])\n            continue;\n          variable_t vs = *rev_map[s];\n          for(vert_id d : g_excl.succs(s)) {\n            if(!rev_map[d])\n              continue;\n            variable_t vd = *rev_map[d];\n            csts += linear_constraint_t(vd - vs <= number_t(g_excl.edge_val(s, d)));\n          }\n        }\n        return csts;\n      }\n\n      disjunctive_linear_constraint_system_t to_disjunctive_linear_constraint_system() {\n\tauto lin_csts = to_linear_constraint_system();\n\tif (lin_csts.is_false()) {\n\t  return disjunctive_linear_constraint_system_t(true /*is_false*/); \n\t} else if (lin_csts.is_true()) {\n\t  return disjunctive_linear_constraint_system_t(false /*is_false*/);\n\t} else {\n\t  return disjunctive_linear_constraint_system_t(lin_csts);\n\t}\n      }\n\n      // return number of vertices and edges\n      std::pair<std::size_t, std::size_t> size() const {\n\treturn {g.size(), g.num_edges()};\n      }\n      \n      static std::string getDomainName() {\n        return \"SplitDBM\";\n      }\n\n    }; // class SplitDBM_\n    \n    #if 1\n    template<class Number, class VariableName,\n\t     class Params = DBM_impl::DefaultParams<Number>>\n    using SplitDBM = SplitDBM_<Number,VariableName,Params>;    \n    #else\n\n    template<typename Number, typename VariableName, typename SplitDBMParams>    \n    struct abstract_domain_traits<SplitDBM_<Number, VariableName, SplitDBMParams>> {\n      typedef Number number_t;\n      typedef VariableName varname_t;       \n    };    \n    \n    // Quick wrapper which uses shared references with copy-on-write.\n    template<class Number, class VariableName,\n\t     class Params = DBM_impl::DefaultParams<Number>>\n    class SplitDBM final:\n      public abstract_domain<SplitDBM<Number,VariableName,Params>> {\n      typedef SplitDBM<Number, VariableName, Params> DBM_t;\n      typedef abstract_domain<DBM_t> abstract_domain_t;\n      \n    public:\n      \n      using typename abstract_domain_t::linear_expression_t;\n      using typename abstract_domain_t::linear_constraint_t;\n      using typename abstract_domain_t::linear_constraint_system_t;\n      using typename abstract_domain_t::disjunctive_linear_constraint_system_t;      \n      using typename abstract_domain_t::variable_t;\n      using typename abstract_domain_t::variable_vector_t;\n      using typename abstract_domain_t::pointer_constraint_t;\n      typedef Number number_t;\n      typedef VariableName varname_t;\n      typedef typename linear_constraint_t::kind_t constraint_kind_t;\n      typedef interval<number_t>  interval_t;\n\n    public:\n      \n      typedef SplitDBM_<number_t, varname_t, Params> dbm_impl_t;\n      typedef std::shared_ptr<dbm_impl_t> dbm_ref_t;\n\n      SplitDBM(dbm_ref_t _ref)\n\t: norm_ref(_ref) { }\n\n      SplitDBM(dbm_ref_t _base, dbm_ref_t _norm) \n        : base_ref(_base), norm_ref(_norm) { }\n       \n\n      DBM_t create(dbm_impl_t&& t) {\n        return std::make_shared<dbm_impl_t>(std::move(t));\n      }\n\n      DBM_t create_base(dbm_impl_t&& t) {\n        dbm_ref_t base = std::make_shared<dbm_impl_t>(t);\n        dbm_ref_t norm = std::make_shared<dbm_impl_t>(std::move(t));\n        return DBM_t(base, norm);\n      }\n\n      void lock(void) {\n        // Allocate a fresh copy.\n        if(!norm_ref.unique())\n          norm_ref = std::make_shared<dbm_impl_t>(*norm_ref);\n        base_ref.reset();\n      }\n\n    public:\n\n      void set_to_top() {\n\tSplitDBM abs(false);\n\tstd::swap(*this, abs);\n      }\n    \n      void set_to_bottom() {\n\tSplitDBM abs(true);\n\tstd::swap(*this, abs);\n      }\n\n      SplitDBM(bool is_bottom = false)\n        : norm_ref(std::make_shared<dbm_impl_t>(is_bottom)) { }\n\n      SplitDBM(const DBM_t& o)\n        : base_ref(o.base_ref), norm_ref(o.norm_ref)\n      { }\n\n      SplitDBM& operator=(const DBM_t& o) {\n\tif (this != &o) {\n\t  base_ref = o.base_ref;\n\t  norm_ref = o.norm_ref;\n\t}\n        return *this;\n      }\n\n      dbm_impl_t& base(void) {\n        if(base_ref)\n          return *base_ref;\n        else\n          return *norm_ref;\n      }\n      dbm_impl_t& norm(void) { return *norm_ref; }\n\n      bool is_bottom() { return norm().is_bottom(); }\n      bool is_top() { return norm().is_top(); }\n      bool operator<=(DBM_t o) { return norm() <= o.norm(); }\n      void operator|=(DBM_t o) { lock(); norm() |= o.norm(); }\n      DBM_t operator|(DBM_t o) { return create(norm() | o.norm()); }\n      DBM_t operator||(DBM_t o) { return create_base(base() || o.norm()); }\n      DBM_t operator&(DBM_t o) { return create(norm() & o.norm()); }\n      DBM_t operator&&(DBM_t o) { return create(norm() && o.norm()); }\n\n      DBM_t widening_thresholds(DBM_t o, const iterators::thresholds<number_t>& ts) {\n        return create_base(base().widening_thresholds(o.norm(), ts));\n      }\n\n      void normalize() { lock(); norm().normalize(); }\n      void minimize() {}\n      \n      void operator+=(linear_constraint_system_t csts) { lock(); norm() += csts; } \n      void operator-=(variable_t v) { lock(); norm() -= v; }\n      interval_t operator[](variable_t x) { return norm()[x]; }\n      void set(variable_t x, interval_t intv) { lock(); norm().set(x, intv); }\n\n      void assign(variable_t x, linear_expression_t e) { lock(); norm().assign(x, e); }\n      void apply(operation_t op, variable_t x, variable_t y, number_t k) {\n        lock(); norm().apply(op, x, y, k);\n      }\n      void apply(operation_t op, variable_t x, variable_t y, variable_t z) {\n        lock(); norm().apply(op, x, y, z);\n      }\n      void backward_assign(variable_t x, linear_expression_t e, DBM_t invariant) {\n\tlock(); norm().backward_assign(x, e, invariant.norm());\n      }\n      void backward_apply(operation_t op, variable_t x, variable_t y, number_t k,\n\t\t\t  DBM_t invariant) {\n\tlock(); norm().backward_apply(op, x, y, k, invariant.norm());\n      }\n      void backward_apply(operation_t op, variable_t x, variable_t y, variable_t z,\n\t\t\t  DBM_t invariant) {\n\tlock(); norm().backward_apply(op, x, y, z, invariant.norm());\n      }\t\n      void apply(int_conv_operation_t op, variable_t dst, variable_t src) {\n        lock(); norm().apply(op, dst, src);\n      }\n      void apply(bitwise_operation_t op, variable_t x, variable_t y, number_t k) {\n        lock(); norm().apply(op, x, y, k);\n      }\n      void apply(bitwise_operation_t op, variable_t x, variable_t y, variable_t z) {\n        lock(); norm().apply(op, x, y, z);\n      }\n      \n      /* Begin unimplemented operations */\n      // boolean operations\n      void assign_bool_cst(variable_t lhs, linear_constraint_t rhs) {}\n      void assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs) {}\n      void apply_binary_bool(bool_operation_t op, variable_t x,variable_t y,variable_t z) {}\n      void assume_bool(variable_t v, bool is_negated) {}\n      // backward boolean operations\n      void backward_assign_bool_cst(variable_t lhs, linear_constraint_t rhs,\n\t\t\t\t    DBM_t invariant){}\n      void backward_assign_bool_var(variable_t lhs, variable_t rhs, bool is_not_rhs,\n\t\t\t\t      DBM_t invariant) {}\n      void backward_apply_binary_bool(bool_operation_t op,\n\t\t\t\t      variable_t x,variable_t y,variable_t z,\n\t\t\t\t      DBM_t invariant) {}\n      // array operations\n      void array_init(variable_t a, linear_expression_t elem_size,\n\t\t      linear_expression_t lb_idx, linear_expression_t ub_idx, \n\t\t      linear_expression_t val) {}      \n      void array_load(variable_t lhs,\n\t\t      variable_t a, linear_expression_t elem_size,\n\t\t      linear_expression_t i) {}\n      void array_store(variable_t a, linear_expression_t elem_size,\n\t\t       linear_expression_t i, linear_expression_t v, \n\t\t       bool is_strong_update) {}\n      void array_store(variable_t a_new, variable_t a_old,\n\t\t       linear_expression_t elem_size,\n\t\t       linear_expression_t i, linear_expression_t v, \n\t\t       bool is_strong_update) {}      \n      void array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t     linear_expression_t i, linear_expression_t j,\n\t\t\t     linear_expression_t v) {}\n      void array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t     linear_expression_t elem_size,\n\t\t\t     linear_expression_t i, linear_expression_t j,\n\t\t\t     linear_expression_t v) {}       \n      void array_assign(variable_t lhs, variable_t rhs) {}\n      // backward array operations\n      void backward_array_init(variable_t a, linear_expression_t elem_size,\n\t\t\t       linear_expression_t lb_idx, linear_expression_t ub_idx, \n\t\t\t       linear_expression_t val, DBM_t invariant) {}      \n      void backward_array_load(variable_t lhs,\n\t\t\t       variable_t a, linear_expression_t elem_size,\n\t\t\t       linear_expression_t i, DBM_t invariant) {}\n      void backward_array_store(variable_t a, linear_expression_t elem_size,\n\t\t\t\tlinear_expression_t i, linear_expression_t v, \n\t\t\t\tbool is_strong_update, DBM_t invariant) {}\n      void backward_array_store(variable_t a_new, variable_t a_old,\n\t\t\t\tlinear_expression_t elem_size,\n\t\t\t\tlinear_expression_t i, linear_expression_t v, \n\t\t\t\tbool is_strong_update, DBM_t invariant) {}      \n      void backward_array_store_range(variable_t a, linear_expression_t elem_size,\n\t\t\t\t      linear_expression_t i, linear_expression_t j,\n\t\t\t\t      linear_expression_t v, DBM_t invariant) {}\n      void backward_array_store_range(variable_t a_new, variable_t a_old,\n\t\t\t\t      linear_expression_t elem_size,\n\t\t\t\t      linear_expression_t i, linear_expression_t j,\n\t\t\t\t      linear_expression_t v, DBM_t invariant) {}          \n      void backward_array_assign(variable_t lhs, variable_t rhs, DBM_t invariant) {}      \n      // pointer operations\n      void pointer_load(variable_t lhs, variable_t rhs)  {}\n      void pointer_store(variable_t lhs, variable_t rhs) {} \n      void pointer_assign(variable_t lhs, variable_t rhs, linear_expression_t offset) {}\n      void pointer_mk_obj(variable_t lhs, ikos::index_t address) {}\n      void pointer_function(variable_t lhs, varname_t func) {}\n      void pointer_mk_null(variable_t lhs) {}\n      void pointer_assume(pointer_constraint_t cst) {}\n      void pointer_assert(pointer_constraint_t cst) {}\n      /* End unimplemented operations */\n      \n      void expand(variable_t x, variable_t y) {\n\tlock(); norm().expand(x, y);\n      }\n      void forget(const variable_vector_t& vars) {\n\tlock(); norm().forget(vars);\n      }\n      void project(const variable_vector_t& vars) {\n\tlock(); norm().project(vars);\n      }\n      void rename(const variable_vector_t &from, const variable_vector_t &to) {\n\tlock(); norm().rename(from, to);\n      }\n      void extract(const variable_t& x, linear_constraint_system_t& csts,\n\t\t   bool only_equalities) {\n\tlock(); norm().extract(x, csts, only_equalities);\n      }\n\n      void write(crab_os& o) { norm().write(o); }\n\n      linear_constraint_system_t to_linear_constraint_system() {\n        return norm().to_linear_constraint_system();\n      }\n      disjunctive_linear_constraint_system_t to_disjunctive_linear_constraint_system() {\n        return norm().to_disjunctive_linear_constraint_system();\n      }\n      \n      static std::string getDomainName() { return dbm_impl_t::getDomainName(); }\n      std::pair<std::size_t, std::size_t> size() const {\n\treturn norm().size();\n      }\n      bool is_unsat(linear_constraint_t cst){ return norm().is_unsat(cst);}\n      void active_variables(std::vector<variable_t>& out){ norm().active_variables(out);}\n      \n    protected:  \n      dbm_ref_t base_ref;  \n      dbm_ref_t norm_ref;\n    };\n\n    #endif \n\n    template<typename Number, typename VariableName, typename SplitDBMParams>    \n    struct abstract_domain_traits<SplitDBM<Number, VariableName, SplitDBMParams>> {\n      typedef Number number_t;\n      typedef VariableName varname_t;       \n    };        \n    \n    template<typename Number, typename VariableName, typename SplitDBMParams>    \n    class reduced_domain_traits<SplitDBM<Number, VariableName, SplitDBMParams>> {\n    public:\n      typedef SplitDBM<Number, VariableName, SplitDBMParams> sdbm_domain_t;\n      typedef typename sdbm_domain_t::variable_t variable_t;\n      typedef typename sdbm_domain_t::linear_constraint_system_t linear_constraint_system_t;\n      \n      static void extract(sdbm_domain_t& dom, const variable_t& x,\n\t\t\t  linear_constraint_system_t& csts, bool only_equalities) {\n\tdom.extract(x, csts, only_equalities);\n      }\n    };\n  \n    template<typename Number, typename VariableName, typename SplitDBMParams>\n    struct array_sgraph_domain_helper_traits <SplitDBM<Number,VariableName, SplitDBMParams>> {\n      typedef SplitDBM<Number,VariableName,SplitDBMParams> sdbm_domain_t;\n      typedef typename sdbm_domain_t::linear_constraint_t linear_constraint_t;\n      typedef ikos::variable<Number, VariableName> variable_t;\n      \n      static bool is_unsat(sdbm_domain_t &inv, linear_constraint_t cst) { \n\treturn inv.is_unsat(cst);\n      }\n      \n      static void active_variables(sdbm_domain_t &inv, std::vector<variable_t>& out) {\n\tinv.active_variables(out);\n      }\n    };\n  \n  } // namespace domains\n} // namespace crab\n\n#pragma GCC diagnostic pop\n", "meta": {"hexsha": "443f6f67784f5bbdd2be0372e6f9ae9f0fd8d319", "size": 88999, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/split_dbm.hpp", "max_stars_repo_name": "numairmansur/crab", "max_stars_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crab/domains/split_dbm.hpp", "max_issues_repo_name": "numairmansur/crab", "max_issues_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crab/domains/split_dbm.hpp", "max_forks_repo_name": "numairmansur/crab", "max_forks_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1528179191, "max_line_length": 96, "alphanum_fraction": 0.5485230171, "num_tokens": 22779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5816630083733553}}
{"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 Rein Halbersma 2014-2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <xstd/cstdlib.hpp>             // div, floored_div, euclidean_div\n#include <boost/test/unit_test.hpp>     // BOOST_AUTO_TEST_SUITE, BOOST_AUTO_TEST_SUITE_END, BOOST_AUTO_TEST_CASE, BOOST_CHECK_EQUAL, BOOST_CHECK_EQUAL_COLLECTIONS\n#include <algorithm>                    // transform\n#include <array>                        // array\n#include <cstdlib>                      // div, div_t\n#include <iterator>                     // back_inserter\n#include <sstream>                      // stringstream\n#include <utility>                      // pair\n#include <vector>                       // vector\n\nBOOST_AUTO_TEST_SUITE(CStdLib)\n\nBOOST_AUTO_TEST_CASE(Abs)\n{\n        BOOST_CHECK_EQUAL(xstd::abs(-2), 2);\n        BOOST_CHECK_EQUAL(xstd::abs(-1), 1);\n        BOOST_CHECK_EQUAL(xstd::abs( 0), 0);\n        BOOST_CHECK_EQUAL(xstd::abs(+1), 1);\n        BOOST_CHECK_EQUAL(xstd::abs(+2), 2);\n}\n\nBOOST_AUTO_TEST_CASE(Sign)\n{\n        BOOST_CHECK_EQUAL(xstd::sign(-2), -1);\n        BOOST_CHECK_EQUAL(xstd::sign(-1), -1);\n        BOOST_CHECK_EQUAL(xstd::sign( 0),  0);\n        BOOST_CHECK_EQUAL(xstd::sign(+1), +1);\n        BOOST_CHECK_EQUAL(xstd::sign(+2), +1);\n}\n\n// http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf\n\nauto const input = std::array<std::pair<int, int>, 8>\n{{\n        {+8, +3}, {+8, -3}, {-8, +3}, {-8, -3},\n        {+1, +2}, {+1, -2}, {-1, +2}, {-1, -2}\n}};\n\nBOOST_AUTO_TEST_CASE(StdDiv)\n{\n        auto const std_div = std::vector<xstd::div_t>\n        {\n                {+2, +2}, {-2, +2}, {-2, -2}, {+2, -2},\n                { 0, +1}, { 0, +1}, { 0, -1}, { 0, -1}\n        };\n\n        std::vector<xstd::div_t> std_res;\n        std::transform(input.begin(), input.end(), std::back_inserter(std_res), [](auto const& p)\n                -> xstd::div_t {\n                auto const d = std::div(p.first, p.second);\n                return { d.quot, d.rem };\n        });\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(\n                std_res.begin(), std_res.end(),\n                std_div.begin(), std_div.end()\n        );\n}\n\nBOOST_AUTO_TEST_CASE(TruncatedDiv)\n{\n        auto const div = std::vector<xstd::div_t>\n        {\n                {+2, +2}, {-2, +2}, {-2, -2}, {+2, -2},\n                { 0, +1}, { 0, +1}, { 0, -1}, { 0, -1}\n        };\n\n        std::vector<xstd::div_t> truncated_res;\n        std::transform(input.begin(), input.end(), std::back_inserter(truncated_res), [](auto const& p) {\n                return xstd::div(p.first, p.second);\n        });\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(\n                truncated_res.begin(), truncated_res.end(),\n                div.begin(), div.end()\n        );\n}\n\nBOOST_AUTO_TEST_CASE(EuclideanDiv)\n{\n        auto const euclidean_div = std::vector<xstd::div_t>\n        {\n                {+2, +2}, {-2, +2}, {-3, +1}, {+3, +1},\n                { 0, +1}, { 0, +1}, {-1, +1}, {+1, +1}\n        };\n\n        std::vector<xstd::div_t> euclidean_res;\n        std::transform(input.begin(), input.end(), std::back_inserter(euclidean_res), [](auto const& p) {\n                return xstd::euclidean_div(p.first, p.second);\n        });\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(\n                euclidean_res.begin(), euclidean_res.end(),\n                euclidean_div.begin(), euclidean_div.end()\n        );\n}\n\nBOOST_AUTO_TEST_CASE(FlooredDiv)\n{\n        auto const floored_div = std::vector<xstd::div_t>\n        {\n                {+2, +2}, {-3, -1}, {-3, +1}, {+2, -2},\n                { 0, +1}, {-1, -1}, {-1, +1}, { 0, -1}\n        };\n\n        std::vector<xstd::div_t> floored_res;\n        std::transform(input.begin(), input.end(), std::back_inserter(floored_res), [](auto const& p) {\n                return xstd::floored_div(p.first, p.second);\n        });\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(\n                floored_res.begin(), floored_res.end(),\n                floored_div.begin(), floored_div.end()\n        );\n}\n\nBOOST_AUTO_TEST_CASE(IOStreamsOperators)\n{\n        xstd::div_t const a { 1, 1 };\n        xstd::div_t b;\n        std::stringstream sstr;\n        sstr << a;\n        sstr >> b;\n        BOOST_CHECK_EQUAL(a, b);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ed8cd8e3f9652883dd5f9950fdc42fce04920e07", "size": 4334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/cstdlib.cpp", "max_stars_repo_name": "rhalbersma/xstd", "max_stars_repo_head_hexsha": "fd7b00b39f8626ce11b4b7b21760c15a20838015", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-11-22T10:38:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T14:30:10.000Z", "max_issues_repo_path": "test/src/cstdlib.cpp", "max_issues_repo_name": "rhalbersma/xstd", "max_issues_repo_head_hexsha": "fd7b00b39f8626ce11b4b7b21760c15a20838015", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2017-01-09T07:20:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-02T19:31:47.000Z", "max_forks_repo_path": "test/src/cstdlib.cpp", "max_forks_repo_name": "rhalbersma/xstd", "max_forks_repo_head_hexsha": "fd7b00b39f8626ce11b4b7b21760c15a20838015", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-18T21:53:47.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-18T21:53:47.000Z", "avg_line_length": 32.5864661654, "max_line_length": 163, "alphanum_fraction": 0.5235348408, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5816630055647828}}
{"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": "#include \"solver/qp_solver.h\"\n\n#include <Eigen/Core>\n#include <glog/logging.h>\n\n#include <algorithm>\n#include <limits>\n#include <string>\n\n#include \"math/sparse_cholesky_llt.h\"\n#include \"util/stringprintf.h\"\n\nnamespace GraphSfM {\n\nQPSolver::QPSolver(const Options& options,\n                   const Eigen::SparseMatrix<double>& P,\n                   const Eigen::VectorXd& q,\n                   const double r)\n    : options_(options), P_(P), q_(q), r_(r) {\n  CHECK_EQ(P_.rows(), P_.cols()) << \"P must be a symmetric matrix.\";\n  CHECK_EQ(P_.cols(), q_.size())\n      << \"The dimensions of P and q must be consistent.\";\n\n  // Set the lower and upper bounds to be negative and positive infinity (i.e\n  // no bounds).\n  lb_.setConstant(P_.cols(), -std::numeric_limits<double>::infinity());\n  ub_.setConstant(P_.cols(), std::numeric_limits<double>::infinity());\n\n  // Set up the linear solver to compute the cholesky decomposition of:\n  //     P_ + rho * eye(N)\n  Eigen::SparseMatrix<double> spd_mat(P_.rows(), P_.cols());\n  spd_mat.setIdentity();\n  spd_mat *= options_.rho;\n  spd_mat += P_;\n\n  linear_solver_.Compute(spd_mat);\n  CHECK_EQ(linear_solver_.Info(), Eigen::Success);\n}\n\nvoid QPSolver::SetMaxIterations(const int max_iterations) {\n  options_.max_num_iterations = max_iterations;\n}\n\nvoid QPSolver::SetUpperBound(const Eigen::VectorXd& ub) { ub_ = ub.array(); }\n\nvoid QPSolver::SetLowerBound(const Eigen::VectorXd& lb) { lb_ = lb.array(); }\n\n// Solve the quadratic program.\nbool QPSolver::Solve(Eigen::VectorXd* solution) {\n  // Ensure the bounds are valid. If there are any invalid bounds then the\n  // difference between the bounds would be a negative value.\n  int coeff_index = -1;\n  if ((ub_ - lb_).minCoeff(&coeff_index) < 0) {\n    LOG(WARNING) << \"You specified invalid lower or upper bounds for the \"\n                    \"problem. lower_bound[\" << coeff_index\n                 << \"] = \" << lb_[coeff_index] << \" but upper_bound[\"\n                 << coeff_index << \"] = \" << ub_[coeff_index];\n    return false;\n  }\n\n  CHECK_NOTNULL(solution)->setZero(q_.size());\n  Eigen::VectorXd& x = *solution;\n  Eigen::VectorXd z(P_.rows()), u(P_.rows());\n  z.setZero();\n  u.setZero();\n\n  Eigen::VectorXd z_old(z.size()), x_hat(P_.rows());\n\n  // Precompute some convergence terms.\n  const double primal_abs_tolerance_eps =\n      std::sqrt(P_.rows()) * options_.absolute_tolerance;\n  const double dual_abs_tolerance_eps =\n      std::sqrt(P_.rows()) * options_.absolute_tolerance;\n  VLOG(2) << \"Iteration   Residual         R norm          S norm          \"\n             \"Primal eps      Dual eps\";\n  const std::string row_format =\n      \"  % 4d      % 4.4e     % 4.4e     % 4.4e     % 4.4e     % 4.4e\";\n\n  // Run the iterations.\n  for (int i = 0; i < options_.max_num_iterations; i++) {\n    // Update x.\n    x.noalias() = linear_solver_.Solve(options_.rho * (z - u) - q_);\n    if (linear_solver_.Info() != Eigen::Success) {\n      return false;\n    }\n\n    // Update x_hat.\n    std::swap(z, z_old);\n    x_hat.noalias() = options_.alpha * x + (1.0 - options_.alpha) * z_old;\n\n    // Update z.\n    z.noalias() = ub_.min(lb_.max((x_hat + u).array())).matrix();\n\n    // Update u.\n    u.noalias() += x_hat - z;\n\n    // Compute the convergence terms.\n    const double objval = 0.5 * x.dot(P_ * x) + q_.dot(x) + r_;\n    const double r_norm = (x - z).norm();\n    const double s_norm = (-options_.rho * (z - z_old)).norm();\n    const double max_norm = std::max({x.norm(), z.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 * (options_.rho * u).norm();\n\n    // Log the result to the screen.\n    VLOG(2) << StringPrintf(row_format.c_str(), objval, i, r_norm, s_norm,\n                            primal_eps, dual_eps);\n    // Determine if the minimizer has converged.\n    if (r_norm < primal_eps && s_norm < dual_eps) {\n      break;\n    }\n  }\n  return true;\n}\n\n}  // namespace GraphSfM\n", "meta": {"hexsha": "744df3fc6414820ecbdaf39ccf7d16949bdb0934", "size": 4031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solver/qp_solver.cpp", "max_stars_repo_name": "LumanYang/GraphSfM", "max_stars_repo_head_hexsha": "c04a63578ce63065eb76278f358812c099d4eeef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T06:18:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T06:18:43.000Z", "max_issues_repo_path": "src/solver/qp_solver.cpp", "max_issues_repo_name": "longchao343/GraphSfM", "max_issues_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver/qp_solver.cpp", "max_forks_repo_name": "longchao343/GraphSfM", "max_forks_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5916666667, "max_line_length": 77, "alphanum_fraction": 0.6239146614, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289533, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5816349948896132}}
{"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": "#ifndef LA_TOOLS_HPP_\n#define LA_TOOLS_HPP_\n\n#include <algorithm> //min\n#include <iostream>\n\n#include <NTL/mat_GF2.h>\n\n#include <xtensor/xarray.hpp>\n#include <xtensor/xview.hpp>\n#include <xtensor-blas/xlinalg.hpp>\n\nvoid gf2_syndrome(xt::xarray<int> *s, xt::xarray<int> *y,xt::xarray<int> *H);\nxt::xarray<int> gf2_syndrome(xt::xarray<int> *y,xt::xarray<int> *H);\n\nvoid gf2_rank(int* Matrix, int n_c, int n_v, int* r);\nint gf2_rank(int* Matrix, int n_c, int n_v);\n\nbool gf2_isEquiv(xt::xarray<int> e, xt::xarray<int> H, int n_c, int n_v);\n\nvoid gf4_syndrome(xt::xarray<int> *s, xt::xarray<int> *y,xt::xarray<int> *H);\nxt::xarray<int> gf4_syndrome(xt::xarray<int> *y,xt::xarray<int> *H);\n\nvoid gf4_rank(int* Matrix, int n_c, int n_v, int* r);\nint gf4_rank(int* Matrix, int n_c, int n_v);\n\nbool gf4_isEquiv(xt::xarray<int> e, xt::xarray<int> H, int n_c, int n_v);\n\nint gf4_mul(int a, int b);\nint gf4_conj(int a);\n\nint hamming_weight(xt::xarray<int>x);\n\nxt::xarray<int> get_x(xt::xarray<int> y);\nxt::xarray<int> get_z(xt::xarray<int> y);\n\n#endif", "meta": {"hexsha": "d1e1e15f9de84fdcf6bb093b12313a4838247968", "size": 1040, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bp_gbp/la_tools.hpp", "max_stars_repo_name": "josiasold/bp-gbp", "max_stars_repo_head_hexsha": "79fa4ff81da400072717ba82f95c0a27545f2bfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/bp_gbp/la_tools.hpp", "max_issues_repo_name": "josiasold/bp-gbp", "max_issues_repo_head_hexsha": "79fa4ff81da400072717ba82f95c0a27545f2bfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/bp_gbp/la_tools.hpp", "max_forks_repo_name": "josiasold/bp-gbp", "max_forks_repo_head_hexsha": "79fa4ff81da400072717ba82f95c0a27545f2bfe", "max_forks_repo_licenses": ["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.1081081081, "max_line_length": 77, "alphanum_fraction": 0.6961538462, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5816202200046722}}
{"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 \u2264 j \u2264 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\u22121, . . . , 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": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Vector3d v(1,0,0);\nVector3d w(1e-4,0,1);\ncout << \"Here's the vector v:\" << endl << v << endl;\ncout << \"Here's the vector w:\" << endl << w << endl;\ncout << \"v.isOrthogonal(w) returns: \" << v.isOrthogonal(w) << endl;\ncout << \"v.isOrthogonal(w,1e-3) returns: \" << v.isOrthogonal(w,1e-3) << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "7eebfc2e7629853df58dcd931b1c2b4146c98a61", "size": 444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_isOrthogonal.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_isOrthogonal.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_isOrthogonal.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": 23.3684210526, "max_line_length": 77, "alphanum_fraction": 0.6238738739, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5815447926101288}}
{"text": "\n// g++ -DNDEBUG -O3 -I.. benchEigenSolver.cpp  -o benchEigenSolver && ./benchEigenSolver\n// options:\n//  -DBENCH_GMM\n//  -DBENCH_GSL -lgsl /usr/lib/libcblas.so.3\n//  -DEIGEN_DONT_VECTORIZE\n//  -msse2\n//  -DREPEAT=100\n//  -DTRIES=10\n//  -DSCALAR=double\n\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include <bench/BenchUtil.h>\nusing namespace Eigen;\n\n#ifndef REPEAT\n#define REPEAT 1000\n#endif\n\n#ifndef TRIES\n#define TRIES 4\n#endif\n\n#ifndef SCALAR\n#define SCALAR float\n#endif\n\ntypedef SCALAR Scalar;\n\ntemplate <typename MatrixType>\n__attribute__ ((noinline)) void benchEigenSolver(const MatrixType& m)\n{\n  int rows = m.rows();\n  int cols = m.cols();\n\n  int stdRepeats = std::max(1,int((REPEAT*1000)/(rows*rows*sqrt(rows))));\n  int saRepeats = stdRepeats * 4;\n\n  typedef typename MatrixType::Scalar Scalar;\n  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;\n\n  MatrixType a = MatrixType::Random(rows,cols);\n  SquareMatrixType covMat =  a * a.adjoint();\n\n  BenchTimer timerSa, timerStd;\n\n  Scalar acc = 0;\n  int r = internal::random<int>(0,covMat.rows()-1);\n  int c = internal::random<int>(0,covMat.cols()-1);\n  {\n    SelfAdjointEigenSolver<SquareMatrixType> ei(covMat);\n    for (int t=0; t<TRIES; ++t)\n    {\n      timerSa.start();\n      for (int k=0; k<saRepeats; ++k)\n      {\n        ei.compute(covMat);\n        acc += ei.eigenvectors().coeff(r,c);\n      }\n      timerSa.stop();\n    }\n  }\n\n  {\n    EigenSolver<SquareMatrixType> ei(covMat);\n    for (int t=0; t<TRIES; ++t)\n    {\n      timerStd.start();\n      for (int k=0; k<stdRepeats; ++k)\n      {\n        ei.compute(covMat);\n        acc += ei.eigenvectors().coeff(r,c);\n      }\n      timerStd.stop();\n    }\n  }\n\n  if (MatrixType::RowsAtCompileTime==Dynamic)\n    std::cout << \"dyn   \";\n  else\n    std::cout << \"fixed \";\n  std::cout << covMat.rows() << \" \\t\"\n            << timerSa.value() * REPEAT / saRepeats << \"s \\t\"\n            << timerStd.value() * REPEAT / stdRepeats << \"s\";\n\n  #ifdef BENCH_GMM\n  if (MatrixType::RowsAtCompileTime==Dynamic)\n  {\n    timerSa.reset();\n    timerStd.reset();\n\n    gmm::dense_matrix<Scalar> gmmCovMat(covMat.rows(),covMat.cols());\n    gmm::dense_matrix<Scalar> eigvect(covMat.rows(),covMat.cols());\n    std::vector<Scalar> eigval(covMat.rows());\n    eiToGmm(covMat, gmmCovMat);\n    for (int t=0; t<TRIES; ++t)\n    {\n      timerSa.start();\n      for (int k=0; k<saRepeats; ++k)\n      {\n        gmm::symmetric_qr_algorithm(gmmCovMat, eigval, eigvect);\n        acc += eigvect(r,c);\n      }\n      timerSa.stop();\n    }\n    // the non-selfadjoint solver does not compute the eigen vectors\n//     for (int t=0; t<TRIES; ++t)\n//     {\n//       timerStd.start();\n//       for (int k=0; k<stdRepeats; ++k)\n//       {\n//         gmm::implicit_qr_algorithm(gmmCovMat, eigval, eigvect);\n//         acc += eigvect(r,c);\n//       }\n//       timerStd.stop();\n//     }\n\n    std::cout << \" | \\t\"\n              << timerSa.value() * REPEAT / saRepeats << \"s\"\n              << /*timerStd.value() * REPEAT / stdRepeats << \"s\"*/ \"   na   \";\n  }\n  #endif\n\n  #ifdef BENCH_GSL\n  if (MatrixType::RowsAtCompileTime==Dynamic)\n  {\n    timerSa.reset();\n    timerStd.reset();\n\n    gsl_matrix* gslCovMat = gsl_matrix_alloc(covMat.rows(),covMat.cols());\n    gsl_matrix* gslCopy = gsl_matrix_alloc(covMat.rows(),covMat.cols());\n    gsl_matrix* eigvect = gsl_matrix_alloc(covMat.rows(),covMat.cols());\n    gsl_vector* eigval  = gsl_vector_alloc(covMat.rows());\n    gsl_eigen_symmv_workspace* eisymm = gsl_eigen_symmv_alloc(covMat.rows());\n\n    gsl_matrix_complex* eigvectz = gsl_matrix_complex_alloc(covMat.rows(),covMat.cols());\n    gsl_vector_complex* eigvalz  = gsl_vector_complex_alloc(covMat.rows());\n    gsl_eigen_nonsymmv_workspace* einonsymm = gsl_eigen_nonsymmv_alloc(covMat.rows());\n\n    eiToGsl(covMat, &gslCovMat);\n    for (int t=0; t<TRIES; ++t)\n    {\n      timerSa.start();\n      for (int k=0; k<saRepeats; ++k)\n      {\n        gsl_matrix_memcpy(gslCopy,gslCovMat);\n        gsl_eigen_symmv(gslCopy, eigval, eigvect, eisymm);\n        acc += gsl_matrix_get(eigvect,r,c);\n      }\n      timerSa.stop();\n    }\n    for (int t=0; t<TRIES; ++t)\n    {\n      timerStd.start();\n      for (int k=0; k<stdRepeats; ++k)\n      {\n        gsl_matrix_memcpy(gslCopy,gslCovMat);\n        gsl_eigen_nonsymmv(gslCopy, eigvalz, eigvectz, einonsymm);\n        acc += GSL_REAL(gsl_matrix_complex_get(eigvectz,r,c));\n      }\n      timerStd.stop();\n    }\n\n    std::cout << \" | \\t\"\n              << timerSa.value() * REPEAT / saRepeats << \"s \\t\"\n              << timerStd.value() * REPEAT / stdRepeats << \"s\";\n\n    gsl_matrix_free(gslCovMat);\n    gsl_vector_free(gslCopy);\n    gsl_matrix_free(eigvect);\n    gsl_vector_free(eigval);\n    gsl_matrix_complex_free(eigvectz);\n    gsl_vector_complex_free(eigvalz);\n    gsl_eigen_symmv_free(eisymm);\n    gsl_eigen_nonsymmv_free(einonsymm);\n  }\n  #endif\n\n  std::cout << \"\\n\";\n\n  // make sure the compiler does not optimize too much\n  if (acc==123)\n    std::cout << acc;\n}\n\nint main(int argc, char* argv[])\n{\n  const int dynsizes[] = {4,6,8,12,16,24,32,64,128,256,512,0};\n  std::cout << \"size            selfadjoint       generic\";\n  #ifdef BENCH_GMM\n  std::cout << \"        GMM++          \";\n  #endif\n  #ifdef BENCH_GSL\n  std::cout << \"       GSL (double + ATLAS)  \";\n  #endif\n  std::cout << \"\\n\";\n  for (uint i=0; dynsizes[i]>0; ++i)\n    benchEigenSolver(Matrix<Scalar,Dynamic,Dynamic>(dynsizes[i],dynsizes[i]));\n\n  benchEigenSolver(Matrix<Scalar,2,2>());\n  benchEigenSolver(Matrix<Scalar,3,3>());\n  benchEigenSolver(Matrix<Scalar,4,4>());\n  benchEigenSolver(Matrix<Scalar,6,6>());\n  benchEigenSolver(Matrix<Scalar,8,8>());\n  benchEigenSolver(Matrix<Scalar,12,12>());\n  benchEigenSolver(Matrix<Scalar,16,16>());\n  return 0;\n}", "meta": {"hexsha": "6df17a461f960fee6e6dd4fe613cbb488d472ec9", "size": 5776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/bench/benchEigenSolver.cpp", "max_stars_repo_name": "mathstuf/ParaView", "max_stars_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T20:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T20:20:59.000Z", "max_issues_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/bench/benchEigenSolver.cpp", "max_issues_repo_name": "mathstuf/ParaView", "max_issues_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/bench/benchEigenSolver.cpp", "max_forks_repo_name": "mathstuf/ParaView", "max_forks_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-04-14T13:42:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T04:59:42.000Z", "avg_line_length": 27.3744075829, "max_line_length": 104, "alphanum_fraction": 0.6161703601, "num_tokens": 1774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5815447895012478}}
{"text": "/*\n * Copyright 2015 Christoph Jud (christoph.jud@unibas.ch)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <iostream>\n#include <memory>\n#include <ctime>\n#include <cmath>\n\n#include <boost/random.hpp>\n\n#include \"GaussianProcess.h\"\n#include \"Kernel.h\"\n#include \"MatrixIO.h\"\n\nusing namespace gpr;\n\ntypedef PeriodicKernel<double>\t\tDPKernelType;\ntypedef std::shared_ptr<DPKernelType> DPKernelTypePointer;\ntypedef GaussianProcess<double> DPGaussianProcessType;\ntypedef std::shared_ptr<DPGaussianProcessType> DPGaussianProcessTypePointer;\n\ntypedef PeriodicKernel<float>\t\tKernelType;\ntypedef std::shared_ptr<KernelType> KernelTypePointer;\ntypedef GaussianProcess<float> GaussianProcessType;\ntypedef std::shared_ptr<GaussianProcessType> GaussianProcessTypePointer;\n\ntypedef DPGaussianProcessType::VectorType DPVectorType;\ntypedef DPGaussianProcessType::MatrixType DPMatrixType;\ntypedef GaussianProcessType::VectorType VectorType;\ntypedef GaussianProcessType::MatrixType MatrixType;\n\n\nvoid Test1(){\n    /*\n     * Test 1: regression of a periodic signal (1D)\n     * - generate a periodic signal, and try to predict some more periods\n     * - ground truth is: sin(x)*cos(2.2*sin(x))\n     */\n    std::cout << \"Test 1: periodic signal regression ...\" << std::flush;\n\n    // ground truth periodic variable\n    auto f = [](double x)->double { return std::sin(x)*std::cos(2.2*std::sin(x)); };\n\n    double interval_start = 0;\n    double interval_end = 5 * 2*M_PI; // full interval\n    double interval_step = 0.1;\n\n    //--------------------------------------------------------------------------------\n    // generating ground truth\n    unsigned gt_size = (interval_end-interval_start) / interval_step;\n    VectorType y(gt_size);\n    for(unsigned i=0; i<gt_size; i++){\n        y[i] = f(interval_start + i*interval_step);\n    }\n\n    //--------------------------------------------------------------------------------\n    // perform training\n    double noise = 0.01;\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, noise);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n    double interval_training_end = 2 * 2*M_PI; // interval to train\n    unsigned number_of_samples = 50;\n\n    KernelTypePointer k(new KernelType(0.59, 0.5, 0.4)); // scale, period, smoothness\n    GaussianProcessTypePointer gp(new GaussianProcessType(k));\n    gp->SetSigma(noise); // noise\n\n    // add samples\n    double training_step_size = (interval_training_end - interval_start) / number_of_samples;\n    for(unsigned i=0; i<number_of_samples; i++){\n        VectorType x(1);\n        x(0) = interval_start + i*training_step_size;\n\n        VectorType y(1);\n        y(0) = f(x(0)) + r();\n\n        gp->AddSample(x, y);\n    }\n    gp->Initialize();\n\n\n    //--------------------------------------------------------------------------------\n    // predict full intervall\n    VectorType y_predict(gt_size);\n    for(unsigned i=0; i<gt_size; i++){\n        VectorType x(1);\n        x(0) = interval_start + i*interval_step;\n        y_predict[i] = gp->Predict(x)(0);\n    }\n\n    double err = (y-y_predict).norm();\n    if(err>0.4){\n        std::stringstream ss; ss<<err; throw ss.str();\n    }\n    else{\n        std::cout << \" [passed].\" << std::endl;\n    }\n\n}\n\nvoid Test2(){\n    /*\n     * Test 2: gaussian process save and load\n     */\n    std::cout << \"Test 2: save/load gaussian process... \" << std::flush;\n    KernelTypePointer k(new KernelType(3.24, 2.2, 0.3));\n    GaussianProcessTypePointer gp(new GaussianProcessType(k));\n    gp->SetSigma(0);\n\n    unsigned number_of_samples = 10;\n\n    // add training samples\n    for(unsigned i=0; i<number_of_samples; i++){\n        VectorType x(2);\n        x(0) = x(1) = i * 2*M_PI/number_of_samples;\n\n        VectorType y(2);\n        y(0) = std::sin(x(0));\n        y(1) = std::cos(x(1));\n\n        gp->AddSample(x,y);\n    }\n    gp->Initialize();\n\n    gp->Save(\"/tmp/gp_io_test-\");\n\n\n    KernelTypePointer k_dummy(new KernelType(1, 1, 1));\n    GaussianProcessTypePointer gp_read(new GaussianProcessType(k_dummy));\n    gp_read->Load(\"/tmp/gp_io_test-\");\n\n    if(*gp.get() == *gp_read.get()){\n        std::cout << \" [passed].\" << std::endl;\n    }\n    else{\n        throw std::string(\"gps are not equal\");\n    }\n}\n\nvoid Test3(){\n    std::cout << \"Test 3: parameter test...\" << std::flush;\n\n    KernelTypePointer k(new KernelType(4, 2.5, 0.01)); // scale, period, smoothness\n    KernelTypePointer k2(new KernelType(1, 1, 1)); // scale, period, smoothness\n\n    k2->SetParameters(k->GetParameters());\n\n    if((*k) != (*k2)){\n        throw std::string(\"kernels are not equal\");\n    }\n    else{\n        std::cout << \" [passed].\" << std::endl;\n    }\n}\n\nint main (int argc, char *argv[]){\n    std::cout << \"Periodic kernel test: \" << std::endl;\n    try{\n        Test1();\n        Test2();\n        Test3();\n    }\n    catch(std::string& s){\n        std::cout << \"[failed] Error: \" << s << std::endl;\n        return -1;\n    }\n\n\n    return 0;\n}\n\n", "meta": {"hexsha": "c464959e3a352488e1b46631b16050fc7c1082b6", "size": 5563, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/PeriodicKernelTest.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/PeriodicKernelTest.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/PeriodicKernelTest.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": 29.5904255319, "max_line_length": 104, "alphanum_fraction": 0.6176523459, "num_tokens": 1432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5815447731505178}}
{"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\u00b2([0,T], H\u00b9(\u03a9))\";\n}\n\ntemplate <int dim>\nstd::string L2H1<dim>::unique_id() const {\n  return \"L\u00b2([0,T], H\u00b9(\u03a9))\";\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": "#pragma once\n\n#include <paradiseo/eo/eo>\n\n#include <Eigen/Dense>\n#include <array>\n#include <cassert>\n\n#include \"aos/adaptive_operator_selection.hpp\"\n#include \"fla/FitnessLandscapeMetric.hpp\"\n#include \"global.hpp\"\n\nclass ProblemContext : public eoFunctorBase {\n  std::vector<FitnessLandscapeMetric*> metrics;\n\n public:\n  auto compute() -> std::vector<double> {\n    std::vector<double> values;\n    for (auto& metric : metrics) {\n      values.push_back(metric->compute());\n    }\n    return values;\n  }\n\n  void add(FitnessLandscapeMetric& metric) { metrics.emplace_back(&metric); }\n\n  [[nodiscard]] auto size() const -> int { return metrics.size(); }\n};\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\ntemplate <class OpT>\nclass LinUCB : public OperatorSelection<OpT> {\n  const double          alpha;\n  ProblemContext&       context;\n  std::vector<MatrixXd> A;\n  std::vector<VectorXd> b;\n  std::vector<VectorXd> theta;\n  VectorXd              x;\n  VectorXd              p;\n  int                   opIdx = -1;\n\n  protected:\n\n  auto selectOperatorIdx() -> int override {\n    p.maxCoeff(&opIdx);\n    return opIdx;\n  }\n\n public:\n  LinUCB(std::vector<OpT>             operators,\n         ProblemContext&              context,\n         const double                 alpha = 0.3)\n      : OperatorSelection<OpT>{operators},\n        alpha{alpha},\n        context{context},\n        A{operators.size(), MatrixXd::Identity(context.size(), context.size())},\n        b{operators.size(), VectorXd::Zero(context.size())},\n        theta{operators.size(), VectorXd{context.size()}},\n        x{context.size()},\n        p{VectorXd::Constant(operators.size(), 0.5)} {\n    assert(alpha >= 0);\n  }\n\n  void update() final{};\n\n  void doFeedback(double reward) final {\n    if (opIdx == -1)\n      return;\n    std::vector<double> features = context.compute();\n    x = Eigen::Map<VectorXd>(features.data(), features.size());\n\n    A[opIdx]     = A[opIdx] + x * x.transpose();\n    b[opIdx]     = b[opIdx] + reward * x;\n    theta[opIdx] = A[opIdx].colPivHouseholderQr().solve(b[opIdx]);\n\n    double prod = x.transpose() * A[opIdx] * x;\n    p(opIdx)    = theta[opIdx].transpose() * x + alpha * std::sqrt(prod);\n  }\n\n  auto printOn(std::ostream& os) -> std::ostream& final {\n    os << \"  strategy: LinUCB MAB\\n\"\n       << \"  alpha: \" << alpha << '\\n';\n    return os;\n  } \n};", "meta": {"hexsha": "25be907b7d0ee0bde9f15a126fe26a05d7ac01a1", "size": 2335, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/aos/lin_ucb.hpp", "max_stars_repo_name": "lucasmpavelski/Adaptive-IG", "max_stars_repo_head_hexsha": "cf48ffae80597a6fd1738da6b4871fe98a3b5189", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/aos/lin_ucb.hpp", "max_issues_repo_name": "lucasmpavelski/Adaptive-IG", "max_issues_repo_head_hexsha": "cf48ffae80597a6fd1738da6b4871fe98a3b5189", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/aos/lin_ucb.hpp", "max_forks_repo_name": "lucasmpavelski/Adaptive-IG", "max_forks_repo_head_hexsha": "cf48ffae80597a6fd1738da6b4871fe98a3b5189", "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.8390804598, "max_line_length": 80, "alphanum_fraction": 0.6042826552, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5815253982832557}}
{"text": "#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp>\n", "meta": {"hexsha": "9929b5787c11542773e1d14f490f45ffe12bce7f", "size": 68, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta_cash_karp54.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta_cash_karp54.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta_cash_karp54.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 34.0, "max_line_length": 67, "alphanum_fraction": 0.8529411765, "num_tokens": 21, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5815206213467861}}
{"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": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Framework/TestingFramework.hpp\"\n\n#include <array>\n#include <boost/optional.hpp>\n#include <cmath>\n#include <cstddef>\n#include <memory>\n#include <string>\n#include <unordered_map>\n\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/CoordinateMaps/TimeDependent/Rotation.hpp\"\n#include \"Domain/FunctionsOfTime/PiecewisePolynomial.hpp\"\n#include \"Framework/TestHelpers.hpp\"\n#include \"Helpers/Domain/CoordinateMaps/TestMapHelpers.hpp\"\n#include \"Utilities/ConstantExpressions.hpp\"\n\nclass DataVector;\nnamespace domain::FunctionsOfTime {\nclass FunctionOfTime;\n}  // namespace domain::FunctionsOfTime\n\nnamespace {\nstd::array<double, 2> expected_mapped_point(\n    const std::array<double, 2> initial_unmapped_point,\n    const double time) noexcept {\n  const double rotation_angle = square(time);\n  return {{initial_unmapped_point[0] * cos(rotation_angle) -\n               initial_unmapped_point[1] * sin(rotation_angle),\n           initial_unmapped_point[0] * sin(rotation_angle) +\n               initial_unmapped_point[1] * cos(rotation_angle)}};\n}\n\nstd::array<double, 2> expected_frame_velocity(\n    const std::array<double, 2> initial_unmapped_point,\n    const double time) noexcept {\n  const double rotation_angle = square(time);\n  const double angular_velocity = 2.0 * time;\n  return {\n      {initial_unmapped_point[0] * -sin(rotation_angle) * angular_velocity -\n           initial_unmapped_point[1] * cos(rotation_angle) * angular_velocity,\n       initial_unmapped_point[0] * cos(rotation_angle) * angular_velocity +\n           initial_unmapped_point[1] * -sin(rotation_angle) *\n               angular_velocity}};\n}\n}  // namespace\n\nnamespace domain {\nSPECTRE_TEST_CASE(\"Unit.Domain.CoordinateMaps.RotationTimeDep\",\n                  \"[Domain][Unit]\") {\n  double t{-1.0};\n  const double dt{0.6};\n  const double final_time{4.0};\n  constexpr size_t deriv_order{3};\n  constexpr size_t spatial_dim{2};\n\n  using Polynomial = domain::FunctionsOfTime::PiecewisePolynomial<deriv_order>;\n  using FoftPtr = std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>;\n\n  const std::string f_of_t_name{\"rotation_angle\"};\n  const std::array<DataVector, deriv_order + 1> init_func{\n      {{1.0}, {-2.0}, {2.0}, {0.0}}};\n  std::unordered_map<std::string, FoftPtr> f_of_t_list{};\n  f_of_t_list[f_of_t_name] =\n      std::make_unique<Polynomial>(t, init_func, final_time + dt);\n\n  const CoordinateMaps::TimeDependent::Rotation<spatial_dim> rotation_map{\n      f_of_t_name};\n  const auto rotation_map_deserialized =\n      serialize_and_deserialize(rotation_map);\n\n  const std::array<double, 2> initial_unmapped_point{{3.2, 4.5}};\n\n  while (t < final_time) {\n    const std::array<double, 2> expected{\n        expected_mapped_point(initial_unmapped_point, t)};\n    CHECK_ITERABLE_APPROX(rotation_map(initial_unmapped_point, t, f_of_t_list),\n                          expected);\n    CHECK_ITERABLE_APPROX(rotation_map.inverse(expected, t, f_of_t_list).get(),\n                          initial_unmapped_point);\n    CHECK_ITERABLE_APPROX(\n        rotation_map.frame_velocity(initial_unmapped_point, t, f_of_t_list),\n        expected_frame_velocity(initial_unmapped_point, t));\n\n    CHECK_ITERABLE_APPROX(\n        rotation_map_deserialized(initial_unmapped_point, t, f_of_t_list),\n        expected);\n    CHECK_ITERABLE_APPROX(\n        rotation_map_deserialized.inverse(expected, t, f_of_t_list).get(),\n        initial_unmapped_point);\n    CHECK_ITERABLE_APPROX(rotation_map_deserialized.frame_velocity(\n                              initial_unmapped_point, t, f_of_t_list),\n                          expected_frame_velocity(initial_unmapped_point, t));\n\n    const auto jac{\n        rotation_map.jacobian(initial_unmapped_point, t, f_of_t_list)};\n    const auto inv_jac{\n        rotation_map.inv_jacobian(initial_unmapped_point, t, f_of_t_list)};\n    const double cos_t_squared{cos(square(t))};\n    const double sin_t_squared{sin(square(t))};\n\n    CHECK(get<0, 0>(jac) == approx(cos_t_squared));\n    CHECK(get<0, 1>(jac) == approx(-sin_t_squared));\n    CHECK(get<1, 0>(jac) == approx(sin_t_squared));\n    CHECK(get<1, 1>(jac) == approx(cos_t_squared));\n\n    CHECK(get<0, 0>(inv_jac) == approx(cos_t_squared));\n    CHECK(get<0, 1>(inv_jac) == approx(sin_t_squared));\n    CHECK(get<1, 0>(inv_jac) == approx(-sin_t_squared));\n    CHECK(get<1, 1>(inv_jac) == approx(cos_t_squared));\n\n    const auto jac_deserialized{rotation_map_deserialized.jacobian(\n        initial_unmapped_point, t, f_of_t_list)};\n    const auto inv_jac_deserialized{rotation_map_deserialized.inv_jacobian(\n        initial_unmapped_point, t, f_of_t_list)};\n    CHECK(get<0, 0>(jac_deserialized) == approx(cos_t_squared));\n    CHECK(get<0, 1>(jac_deserialized) == approx(-sin_t_squared));\n    CHECK(get<1, 0>(jac_deserialized) == approx(sin_t_squared));\n    CHECK(get<1, 1>(jac_deserialized) == approx(cos_t_squared));\n\n    CHECK(get<0, 0>(inv_jac_deserialized) == approx(cos_t_squared));\n    CHECK(get<0, 1>(inv_jac_deserialized) == approx(sin_t_squared));\n    CHECK(get<1, 0>(inv_jac_deserialized) == approx(-sin_t_squared));\n    CHECK(get<1, 1>(inv_jac_deserialized) == approx(cos_t_squared));\n\n    t += dt;\n  }\n\n  // Check inequivalence operator\n  CHECK_FALSE(rotation_map != rotation_map);\n  CHECK_FALSE(rotation_map_deserialized != rotation_map_deserialized);\n\n  // Check serialization\n  CHECK(rotation_map == rotation_map_deserialized);\n  CHECK_FALSE(rotation_map != rotation_map_deserialized);\n\n  test_coordinate_map_argument_types(rotation_map, initial_unmapped_point, t,\n                                     f_of_t_list);\n  CHECK(\n      not CoordinateMaps::TimeDependent::Rotation<spatial_dim>{}.is_identity());\n}\n}  // namespace domain\n", "meta": {"hexsha": "ca7ea2450c7c3c6e393ce29186f713d036234c3c", "size": 5769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Domain/CoordinateMaps/Test_RotationTimeDep.cpp", "max_stars_repo_name": "tomwlodarczyk/spectre", "max_stars_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/Unit/Domain/CoordinateMaps/Test_RotationTimeDep.cpp", "max_issues_repo_name": "tomwlodarczyk/spectre", "max_issues_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Unit/Domain/CoordinateMaps/Test_RotationTimeDep.cpp", "max_forks_repo_name": "tomwlodarczyk/spectre", "max_forks_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5136986301, "max_line_length": 80, "alphanum_fraction": 0.7120818166, "num_tokens": 1423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5815206158455779}}
{"text": "\n#include <iostream>\n#include <chrono>\n#include <sstream>\n#include <fstream>\n#include <Eigen/Dense>\n#include \"Timer.h\"\n#include \"Projection.h\"\n#include \"Volumetric_helper.h\"\n#include \"KinectFrame.h\"\n#include \"KinectSpecs.h\"\n\n\n\n// Usage: ./NormalEstimate.exe ../../data/room.knt ../../data/room_normals.obj\nint main(int argc, char **argv)\n{\n\n\tif (argc < 3)\n\t{\n\t\tstd::cerr\n\t\t\t<< \"Missing parameters. Abort.\"\n\t\t\t<< std::endl\n\t\t\t<< \"Usage: ./NormalEstimate.exe ../../data/room.knt ../../data/room_normals.obj\"\n\t\t\t<< std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\n\tTimer timer;\n\tconst std::string input_filename = argv[1];\n\tconst std::string output_filename = argv[2];\n\n\n\n\ttry\n\t{\n\t\ttimer.start();\n\t\tKinectFrame frame;\n\t\tKinectFrame::load(input_filename, frame);\n\t\ttimer.print_interval(\"Importing kinect frame    : \");\n\n\t\tfloat fovy = KINECT_V2_FOVY; \n\t\tfloat aspect_ratio = KINECT_V2_DEPTH_ASPECT_RATIO;\n\t\tfloat near_plane = KINECT_V2_DEPTH_MIN;\n\t\tfloat far_plane = KINECT_V2_DEPTH_MAX;\n\n\t\tif (frame.depth_width() != 512)\t// it is not kinect version 2. It is version 1\n\t\t{\n\t\t\tfovy = KINECT_V1_FOVY;\n\t\t\taspect_ratio = KINECT_V1_ASPECT_RATIO;\n\t\t\tnear_plane = KINECT_V1_DEPTH_MIN;\n\t\t\tfar_plane = KINECT_V1_DEPTH_MAX;\n\t\t}\n\n\t\tstd::vector<Eigen::Vector3f> vertices(frame.depth.size(), Eigen::Vector3f(0, 0, 0));\n\t\tstd::vector<Eigen::Vector3f> normals(frame.depth.size(), Eigen::Vector3f(0, 0, 1));\n\t\tstd::vector<Eigen::Vector3i> colors(frame.depth.size(), Eigen::Vector3i(0, 0, 255));\n\n\t\ttimer.start();\n\n\t\tEigen::Vector3f vert_uv, vert_u1v, vert_uv1;\n\n\t\tfor (int x = 0; x < frame.depth_width() - 1; ++x)\n\t\t{\n\t\t\tfor (int y = 0; y < frame.depth_height() - 1; ++y)\n\t\t\t{\n\t\t\t\tconst float depth = frame.depth[y * frame.depth_width() + x];\n\t\t\t\tconst float depth_u1v = frame.depth[y * frame.depth_width() + x + 1];\n\t\t\t\tconst float depth_uv1 = frame.depth[(y + 1) * frame.depth_width() + x];\n\n\t\t\t\tif (depth > 0.01 && depth_u1v > 0.01 && depth_uv1 > 0.01)\n\t\t\t\t{\n\t\t\t\t\tvert_uv = window_coord_to_3d(Eigen::Vector2f(x, y), depth, fovy, aspect_ratio, near_plane, far_plane, frame.depth_width(), frame.depth_height());\n\t\t\t\t\tvert_u1v = window_coord_to_3d(Eigen::Vector2f(x + 1, y), depth_u1v, fovy, aspect_ratio, near_plane, far_plane, frame.depth_width(), frame.depth_height());\n\t\t\t\t\tvert_uv1 = window_coord_to_3d(Eigen::Vector2f(x, y + 1), depth_uv1, fovy, aspect_ratio, near_plane, far_plane, frame.depth_width(), frame.depth_height());\n\n\t\t\t\t\tconst Eigen::Vector3f n1 = vert_u1v - vert_uv;\n\t\t\t\t\tconst Eigen::Vector3f n2 = vert_uv1 - vert_uv;\n\t\t\t\t\tconst Eigen::Vector3f n = n1.cross(n2).normalized();\n\n\t\t\t\t\tint i = y * frame.depth_width() + x;\n\n\t\t\t\t\tvertices[i] = vert_uv;\n\t\t\t\t\tnormals[i] = n;\n\t\t\t\t\tcolors[i] = ((n * 0.5f + Eigen::Vector3f(0.5, 0.5, 0.5)) * 255.0f).cast<int>();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttimer.print_interval(\"Depth map back projection : \");\n\n\t\ttimer.start();\n\t\t//export_obj_with_normals(output_filename, vertices, normals);\n\t\texport_obj_with_colors(output_filename, vertices, colors);\n\t\ttimer.print_interval(\"Exporting output .obj     : \");\n\t}\n\tcatch (const std::exception& ex)\n\t{\n\t\tstd::cerr << \"Error: \" << ex.what() << std::endl;\n\t}\n\n\n\n\treturn 0;\n}\n\n\n\n", "meta": {"hexsha": "d2932f678dc484ad12afddbf4e6ad40484cd2cd9", "size": 3130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NormalEstimate.cpp", "max_stars_repo_name": "diegomazala/QtKinect", "max_stars_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-08-04T14:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-27T13:46:13.000Z", "max_issues_repo_path": "src/NormalEstimate.cpp", "max_issues_repo_name": "diegomazala/QtKinect", "max_issues_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NormalEstimate.cpp", "max_forks_repo_name": "diegomazala/QtKinect", "max_forks_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-12-08T06:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T10:29:17.000Z", "avg_line_length": 28.7155963303, "max_line_length": 159, "alphanum_fraction": 0.6667731629, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5815206000813449}}
{"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": "#ifndef MISC_HPP\n#define MISC_HPP\n\n#include <Eigen/Core>\n// #include <boost/utility.hpp>\n// #include <boost/type_traits.hpp>\n\n       \ndouble fastSigmoid(double x);\ndouble penaltyBoundToInterval(const double& v, const double m, const double& e); //v: The scalar that should be bounded, a: lower bound, b: upper bound,  e: safty margin \ndouble penaltyBoundAngle(double a1, double a2, double a3);\n\ninline double fastSigmoid(double x)\n{\n  return x / (1 + fabs(x));\n}\n\ninline double penaltyBound(const double& v, const double m, const double& e)\n{\n  if ( (v > m+e)  || (v <= m-e) )\n  {\n    return (1.0*(v + (m + e)));\n  }\n  else\n  {\n    return 0.0;\n  }\n}\n\n\ninline double penaltyBoundTime(const double& x, const double m, const double& e)\n{\n  if ( (x < m)  || (x >= m*e) )\n  {\n    return 1.0*(x  + m);\n  }\n  else\n  {\n    return 0.0;\n  }\n}\n\ninline double penaltyBoundAngle(double a1, double a2, double a3)\n{\n  double ret1 , ret2;\n  if ( a1 - a2 > M_PI /6 )\n    ret1 = (a1 - a2);\n  else\n    ret1 = 0.;\n  \n  if ( a2 - a3 > M_PI /6 )\n    ret2 = (a2 - a3);\n  else\n    ret2 = 0.;\n\n  return (ret1+ret2);\n}\n\n\n#endif ", "meta": {"hexsha": "b8156a7e15f6716be88bf8fee130004b9cb09b94", "size": 1102, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/marsupial_optimizer/misc.hpp", "max_stars_repo_name": "SaimonMR/marsupial_optimizer", "max_stars_repo_head_hexsha": "0e416c0fa2ad2a1b818b503bb206aef3c65c61dc", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/marsupial_optimizer/misc.hpp", "max_issues_repo_name": "SaimonMR/marsupial_optimizer", "max_issues_repo_head_hexsha": "0e416c0fa2ad2a1b818b503bb206aef3c65c61dc", "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": "include/marsupial_optimizer/misc.hpp", "max_forks_repo_name": "SaimonMR/marsupial_optimizer", "max_forks_repo_head_hexsha": "0e416c0fa2ad2a1b818b503bb206aef3c65c61dc", "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": 18.3666666667, "max_line_length": 170, "alphanum_fraction": 0.5980036298, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.581520589448624}}
{"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": "// STL includes\n#include <iostream>\n#include <vector>\n\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/biconnected_components.hpp>\n\nnamespace boost {\n    struct edge_component_t {\n        enum { num = 555 };\n        typedef edge_property_tag kind;\n    } edge_component;\n}\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_component_t, std::size_t >> graph;\ntypedef boost::graph_traits<graph>::edge_descriptor edge_desc;\ntypedef boost::graph_traits<graph>::vertex_descriptor vertex_desc;\n\n\nusing namespace std;\n\nstruct edge {\n    int u;\n    int v;\n\n    bool operator<(edge &o) const {\n        return u < o.u || (u == o.u && v < o.v);\n    }\n};\n\nvoid solve() {\n    int n;\n    cin >> n;\n    int m;\n    cin >> m;\n\n    graph G(n);\n\n    int u, v;\n    for (int i = 0; i < m; ++i) {\n        cin >> u;\n        cin >> v;\n        boost::add_edge(u, v, G);\n    }\n\n\n    boost::property_map<graph, boost::edge_component_t>::type component = get(boost::edge_component, G);\n    int ncc = biconnected_components(G, component);\n\n    vector<vector<edge_desc>> edgesOfComponent(ncc, vector<edge_desc>());\n\n    boost::graph_traits<graph>::edge_iterator ei, ei_end;\n    for (boost::tie(ei, ei_end) = edges(G); ei != ei_end; ++ei) {\n        edgesOfComponent[component[*ei]].push_back(*ei);\n    }\n\n    vector<edge> result;\n    for (int i = 0; i < ncc; ++i) {\n        if (edgesOfComponent[i].size() == 1) {\n            u = source(edgesOfComponent[i][0], G);\n            v = target(edgesOfComponent[i][0], G);\n            if (v < u) {\n                u = target(edgesOfComponent[i][0], G);\n                v = source(edgesOfComponent[i][0], G);\n            }\n            result.push_back({u, v});\n        }\n    }\n    sort(result.begin(), result.end());\n\n    cout << result.size() << endl;\n    for (auto e : result) {\n        cout << e.u << \" \" << e.v << endl;\n    }\n}\n\nint main() {\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve();\n    }\n}", "meta": {"hexsha": "6c89b25d72156334eab7e32f4331429f365d7831", "size": 2045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/important_bridges.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/important_bridges.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/important_bridges.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.3452380952, "max_line_length": 158, "alphanum_fraction": 0.5657701711, "num_tokens": 563, "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 \u0141o\u015b <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": "/* boost test framework. */\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_ALTERNATIVE_INIT_API\n#define BOOST_TEST_MODULE closed interval fixed - point class test\n#include <boost/test/unit_test.hpp>\n\n/* user headers. */\n#include \"ml/all.h\"\n\n/*\n * Helpers.\n */\n\nusing namespace ml;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(fp_closed_interval)\n\n/*\n * number representations.\n */\n\nconst closed_unit_interval<uint32_t> zero{0}, half{0.5}, one{1};\n\nBOOST_AUTO_TEST_CASE(representation)\n{\n    BOOST_CHECK(unwrap(zero) == 0);\n    BOOST_CHECK(unwrap(half) == std::numeric_limits<uint32_t>::max() / 2);\n    BOOST_CHECK(unwrap(one) == std::numeric_limits<uint32_t>::max());\n}\n\n/*\n * arithmetic.\n */\n\nBOOST_AUTO_TEST_CASE(arithmetic)\n{\n    BOOST_CHECK(to_float(half + half) == to_float(one));\n}\n\n/*\n * comparisons.\n */\n\nBOOST_AUTO_TEST_CASE(comparisons)\n{\n    BOOST_CHECK(zero < half);\n    BOOST_CHECK(zero < one);\n    BOOST_CHECK(half < one);\n\n    BOOST_CHECK(!(zero > zero));\n    BOOST_CHECK(zero >= zero);\n\n    BOOST_CHECK(!(half > half));\n    BOOST_CHECK(half >= half);\n    BOOST_CHECK(one >= half);\n\n    BOOST_CHECK(!(one > one));\n    BOOST_CHECK(one >= one);\n\n    BOOST_CHECK(half > zero);\n    BOOST_CHECK(one > zero);\n    BOOST_CHECK(one > half);\n\n    BOOST_CHECK(!(zero > zero));\n    BOOST_CHECK(zero >= zero);\n\n    BOOST_CHECK(!(half > half));\n    BOOST_CHECK(half >= half);\n    BOOST_CHECK(one >= half);\n\n    BOOST_CHECK(!(one > one));\n    BOOST_CHECK(one >= one);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "64a1b578e6a9a63d68133a4e1d08afbd9a5bccba", "size": 1494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/closed_interval.cpp", "max_stars_repo_name": "flubbe/ml", "max_stars_repo_head_hexsha": "0877924e7b7e21d0cb4b781617006aca2e13c1c4", "max_stars_repo_licenses": ["MIT"], "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/closed_interval.cpp", "max_issues_repo_name": "flubbe/ml", "max_issues_repo_head_hexsha": "0877924e7b7e21d0cb4b781617006aca2e13c1c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/closed_interval.cpp", "max_forks_repo_name": "flubbe/ml", "max_forks_repo_head_hexsha": "0877924e7b7e21d0cb4b781617006aca2e13c1c4", "max_forks_repo_licenses": ["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.4025974026, "max_line_length": 74, "alphanum_fraction": 0.6673360107, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5814595688156212}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2018.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/is_zero_boost_units.hpp>\n#include <fcppt/math/vector/arithmetic.hpp>\n#include <fcppt/math/vector/comparison.hpp>\n#include <fcppt/math/vector/static.hpp>\n#include <fcppt/optional/comparison.hpp>\n#include <fcppt/optional/make.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/time.hpp>\n#include <boost/units/systems/si/velocity.hpp>\n#include <catch2/catch.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nTEST_CASE(\n\t\"math units\",\n\t\"[math]\"\n)\n{\n\ttypedef\n\tint\n\tunit_type;\n\n\ttypedef\n\tboost::units::quantity<\n\t\tboost::units::si::length,\n\t\tunit_type\n\t>\n\tlength;\n\n\ttypedef\n\tboost::units::quantity<\n\t\tboost::units::si::time,\n\t\tunit_type\n\t>\n\ttime;\n\n\ttypedef\n\tboost::units::quantity<\n\t\tboost::units::si::velocity,\n\t\tunit_type\n\t>\n\tvelocity;\n\n\ttypedef\n\tfcppt::math::vector::static_<\n\t\tlength,\n\t\t2\n\t>\n\tlength2;\n\n\ttypedef\n\tfcppt::math::vector::static_<\n\t\ttime,\n\t\t2\n\t>\n\ttime2;\n\n\ttypedef\n\tfcppt::math::vector::static_<\n\t\tvelocity,\n\t\t2\n\t>\n\tvelocity2;\n\n\tlength2 const l1(\n\t\tlength(\n\t\t\t-100\n\t\t\t*\n\t\t\tboost::units::si::meter\n\t\t),\n\t\tlength(\n\t\t\t200\n\t\t\t*\n\t\t\tboost::units::si::meter\n\t\t)\n\t);\n\n\ttime2 const t1(\n\t\ttime(\n\t\t\t4\n\t\t\t*\n\t\t\tboost::units::si::second\n\t\t),\n\t\ttime(\n\t\t\t2\n\t\t\t*\n\t\t\tboost::units::si::second\n\t\t)\n\t);\n\n\tCHECK(\n\t\tl1\n\t\t/\n\t\tt1\n\t\t==\n\t\tfcppt::optional::make(\n\t\t\tvelocity2{\n\t\t\t\t-25\n\t\t\t\t*\n\t\t\t\tboost::units::si::meter\n\t\t\t\t/\n\t\t\t\tboost::units::si::second\n\t\t\t\t,\n\t\t\t\t100\n\t\t\t\t*\n\t\t\t\tboost::units::si::meter\n\t\t\t\t/\n\t\t\t\tboost::units::si::second\n\t\t\t}\n\t\t)\n\t);\n}\n", "meta": {"hexsha": "f5abe1818da260a75c48d46fba82f3d6828bed5c", "size": 1785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/units.cpp", "max_stars_repo_name": "pmiddend/fcppt", "max_stars_repo_head_hexsha": "9f437acbb10258e6df6982a550213a05815eb2be", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/units.cpp", "max_issues_repo_name": "pmiddend/fcppt", "max_issues_repo_head_hexsha": "9f437acbb10258e6df6982a550213a05815eb2be", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/units.cpp", "max_forks_repo_name": "pmiddend/fcppt", "max_forks_repo_head_hexsha": "9f437acbb10258e6df6982a550213a05815eb2be", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.7520661157, "max_line_length": 61, "alphanum_fraction": 0.6431372549, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5814595639937524}}
{"text": "#include \"layers/InputLayer.h\"\n#include \"layers/OutputLayer.h\"\n#include \"layers/FullyConnectedLayer.h\"\n#include \"layers/MappingInputLayer.h\"\n#include \"utils/MathUtils.h\"\n#include \"train/SimpleTrainer.h\"\n\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <stdexcept>\n#include <random>\n#include <unistd.h>\n#include <functional>\n\nusing namespace std;\nusing namespace alex;\n\nconst double LearningRate = 0.03;\nconst int InputWidth = 2;\nconst int OutputWidth = 2;\n\ndouble InputXWidth = 3.0;\ndouble InputYWidth = 1.0;\n\nstatic int setIndex(int index, double *output, int outputCount) {\n  if (index < 0 || index >= outputCount)\n    throw new std::invalid_argument(\"setIndex argument out of bound\");\n  for (int i = 0; i < outputCount; ++i) {\n    output[i] = -1;\n    if (i == index)\n      output[i] = 1;\n  }\n  return index;\n}\nauto realFunction = [](const double *input, int iw, double *output, int ow) -> int {\n  double x = input[0], y = input[1];\n  if ((x+2)*(x+2) + y*y < 1) {\n    return setIndex(0, output, ow);\n  }\n  else {\n    return setIndex(1, output, ow);\n  }\n};\n\nstd::vector<Layer*> initializeNetwork() {\n\n  MappingInputLayer *inputLayer = new MappingInputLayer(InputWidth, {\n      [](const double *input, int w) -> double { return sin(input[0]); },\n      [](const double *input, int w) -> double { return sin(input[1]); },\n      [](const double *input, int w) -> double { return input[0] * input[0]; },\n      [](const double *input, int w) -> double { return input[0] * input[1]; },\n//      [](const double *input, int w) -> double { return input[1] * input[1]; }\n  });\n  FullyConnectedLayer *layer1 = new FullyConnectedLayer(6, inputLayer);\n  FullyConnectedLayer *layer3 = new FullyConnectedLayer(6, layer1);\n  OutputLayer *outputLayer = new OutputLayer(OutputWidth, layer3);\n\n  vector<Layer*> layers;\n  Layer *last = inputLayer;\n  layers.push_back(last);\n  while (true) {\n    Layer *current = last->getNextLayer();\n    if (!current)\n      break;\n    layers.push_back(current);\n    last = current;\n  }\n\n  return layers;\n}\n\nvoid testLayers(std::vector<Layer *> &layers, unsigned int testTimes) {\n  int successCount = 0;\n  for (int i = 0; i < testTimes; ++i) {\n    double expectedOutput[OutputWidth], *inputData = new double[InputWidth], *outputData = nullptr;\n    inputData[0] = MathUtils::rand1() * InputXWidth;\n    inputData[1] = MathUtils::rand1() * InputYWidth;\n    int expectedIndex = realFunction(inputData, InputWidth, expectedOutput, OutputWidth);\n\n    for (auto layer : layers) {\n      outputData = new double[layer->OutputWidth];\n      layer->forwardPropagation(inputData, outputData);\n\n      delete [] inputData;\n      inputData = outputData;\n    }\n\n    double max = -1; int maxIndex = 0;\n    for (int j = 0; j < OutputWidth; ++j) {\n      if (inputData[j] > max) {\n        max = inputData[j];\n        maxIndex = j;\n      }\n    }\n    if (maxIndex == expectedIndex)\n      successCount++;\n\n    delete [] outputData;\n  }\n\n  // NOTE: layer 0 is not a FullyConnectedLayer\n  for (int i = 1; i < layers.size(); ++i) {\n    cout << \"layer\" << i << \" weights: \" << endl;\n    static_cast<FullyConnectedLayer*>(layers[i])->printWeights();\n  }\n\n  cout << \"success rate = \" << 100.0 * successCount / testTimes << \"%\" << endl;\n}\n\n#include <boost/program_options.hpp>\nint main(int argc, const char *argv[]) {\n  srand(1);\n\n  unsigned testTimes = 10000,\n          trainTimes = 10000;\n\n  try {\n    boost::program_options::options_description desc(\"Options\");\n    desc.add_options()\n            (\"help\", boost::program_options::value<string>(), \"Print help messages\")\n            (\"train-times\", boost::program_options::value<unsigned int>(), \"train times\")\n            (\"test-times\", boost::program_options::value<unsigned int>(), \"test times\");\n\n    boost::program_options::variables_map vm;\n    try {\n      boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc),\n                vm); // can throw\n\n      /** --help option\n       */\n      if (vm.count(\"help\")) {\n        std::cout << \"bp-ann\" << std::endl\n        << desc << std::endl;\n        return 0;\n      }\n\n      boost::program_options::notify(vm); // throws on error, so do after help in case\n      // there are any problems\n    }\n    catch(boost::program_options::error& e) {\n      std::cerr << \"ERROR: \" << e.what() << std::endl << std::endl;\n      std::cerr << desc << std::endl;\n      return 1;\n    }\n\n    if (vm.count(\"train-times\"))\n      trainTimes = vm[\"train-times\"].as<unsigned>();\n    if (vm.count(\"test-times\"))\n      testTimes = vm[\"test-times\"].as<unsigned>();\n\n    auto layers = initializeNetwork();\n    SimpleTrainer trainer(InputWidth, OutputWidth, LearningRate, trainTimes, layers,\n                          [=](double *input, int w) -> void {\n                            input[0] = MathUtils::rand1() * InputXWidth;\n                            input[1] = MathUtils::rand1() * InputYWidth;\n                          },\n                          realFunction,\n                          [](const double *output, const double *expected, double *error, int width) -> void {\n                            for (int i = 0; i < width; ++i) {\n                              error[i] = output[i] - expected[i];\n                            }\n                          },\n                          [](const double *err, int width) -> double {\n                            double sum = 0;\n                            for (int i = 0; i < width; ++i) {\n                              sum += err[i] * err[i];\n                            }\n                            return sum;\n                          });\n    trainer.startTraining();\n    testLayers(layers, testTimes);\n  }\n  catch(std::exception& e) {\n    std::cerr << \"Unhandled Exception reached the top of main: \"\n      << e.what() << \", application will now exit\" << std::endl;\n    return 2;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "0ac721d98c9cd62221dbc0560f7ed69e45afc054", "size": 5863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "a1exwang/bp-ann", "max_stars_repo_head_hexsha": "b81d7a5df3ae53c9ce7e998987e1533429ed59cd", "max_stars_repo_licenses": ["MIT"], "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": "a1exwang/bp-ann", "max_issues_repo_head_hexsha": "b81d7a5df3ae53c9ce7e998987e1533429ed59cd", "max_issues_repo_licenses": ["MIT"], "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": "a1exwang/bp-ann", "max_forks_repo_head_hexsha": "b81d7a5df3ae53c9ce7e998987e1533429ed59cd", "max_forks_repo_licenses": ["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.3922651934, "max_line_length": 110, "alphanum_fraction": 0.5737676957, "num_tokens": 1484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5814595572574128}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/function/zeta.hpp>\n#include <boost/math/special_functions/zeta.hpp>\n#include <eve/function/all.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/function/is_positive.hpp>\n#include <eve/function/is_negative.hpp>\n#include <eve/platform.hpp>\n\n#include <cmath>\n\nTTS_CASE_TPL(\"Check eve::zeta return type\", EVE_TYPE)\n{\n  TTS_EXPR_IS(eve::zeta(T(0)), T);\n}\n\nTTS_CASE_TPL(\"Check eve::zeta behavior\", EVE_TYPE)\n{\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_IEEE_EQUAL(eve::zeta(eve::nan(eve::as<T>())) , eve::nan(eve::as<T>()));\n    TTS_IEEE_EQUAL(eve::zeta(eve::inf(eve::as<T>())) , eve::one(eve::as<T>()));\n    TTS_IEEE_EQUAL(eve::zeta(eve::minf(eve::as<T>())), eve::nan(eve::as<T>()));\n  }\n\n  TTS_IEEE_EQUAL(eve::zeta(T(1))   , eve::nan(eve::as<T>()));\n   using v_t = eve::element_type_t<T>;\n   TTS_ULP_EQUAL(eve::zeta(T(0))    , T(boost::math::zeta(v_t(0))), 0.5);\n   TTS_ULP_EQUAL(eve::zeta(T(-0.0))   ,T(boost::math::zeta(v_t(-0.0))), 0.5);\n   TTS_ULP_EQUAL(eve::zeta(T(1.5))    , T(boost::math::zeta(v_t(1.5))), 0.5);\n   TTS_ULP_EQUAL(eve::zeta(T(-1.5))   ,T(boost::math::zeta(v_t(-1.5))), 2.0);\n   TTS_ULP_EQUAL(eve::zeta(T(14))    , T(boost::math::zeta(v_t(14))), 0.5);\n   TTS_ULP_EQUAL(eve::zeta(T(-14))   ,T(boost::math::zeta(v_t(-14))), 0.5);\n   TTS_ULP_EQUAL(eve::zeta(T(14.5))    , T(boost::math::zeta(v_t(14.5))), 0.5);\n   TTS_ULP_EQUAL(eve::zeta(T(-14.5))   ,T(boost::math::zeta(v_t(-14.5))), 1.5);\n}\n", "meta": {"hexsha": "8e13f52bd7cb2808b8dbdf9ddc759fbad530dd75", "size": 1827, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/special/zeta/regular/zeta.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/special/zeta/regular/zeta.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/special/zeta/regular/zeta.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6, "max_line_length": 100, "alphanum_fraction": 0.5670498084, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5814595543500146}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[assign\r\n//` Shows how to assign a geometry from another geometry\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/box.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\r\n\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\r\n\r\nint main()\r\n{\r\n    typedef boost::geometry::model::d2::point_xy<double> point;\r\n    typedef boost::geometry::model::box<point> box;\r\n    typedef boost::geometry::model::polygon<point> polygon;\r\n\r\n    point p1;\r\n    box b;\r\n    boost::geometry::assign_values(p1, 1, 1);\r\n    boost::geometry::assign_values(b, 1, 1, 2, 2);\r\n    \r\n    // Assign a box to a polygon (target = source)\r\n    polygon p;\r\n    boost::geometry::assign(p, b);\r\n\r\n    // Assign a point to another point type (conversion of point-type)\r\n    boost::tuple<double, double> p2;\r\n    boost::geometry::assign(p2, p1);\r\n        \r\n    using boost::geometry::dsv;\r\n    std::cout\r\n        << \"box: \" << dsv(b) << std::endl\r\n        << \"polygon: \" << dsv(p) << std::endl\r\n        << \"point: \" << dsv(p1) << std::endl\r\n        << \"point tuples: \" << dsv(p2) << std::endl\r\n        ;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[assign_output\r\n/*`\r\nOutput:\r\n[pre\r\nbox: ((1, 1), (2, 2))\r\npolygon: (((1, 1), (1, 2), (2, 2), (2, 1), (1, 1)))\r\npoint: (1, 1)\r\npoint tuples: (1, 1)\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "ba79be6f6a637fbafb69230c0efe94b4a48a8ed1", "size": 1767, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/assign.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/assign.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/assign.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3731343284, "max_line_length": 80, "alphanum_fraction": 0.6179966044, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.5814595512122305}}
{"text": "#pragma once \n\n#include \"common.hpp\"\n#include <boost/integer/static_log2.hpp>\n\nnamespace cindex\n{\n\ttemplate<typename BlockType>\n\tclass block_info\n\t{\n\tpublic:\n\t\ttypedef BlockType block_type;\n\n\t\tstatic const std::size_t bytes_per_block = sizeof(block_type);\n\t\tstatic const std::size_t bits_per_block = bytes_per_block * 8;\n\t\tstatic const std::size_t bit_mask = bits_per_block - 1;\n\t\tstatic const std::size_t log_bits_per_block = boost::static_log2<bits_per_block>::value;\n\n\t\tstatic std::size_t\n\t\tblock_count(std::size_t n) CINDEX_WARN_UNUSED_RESULT\n\t\t{\n\t\t\treturn (n + bits_per_block - 1) / bits_per_block;\n\t\t}\n\n\t\tstatic std::size_t\n\t\tsize(std::size_t n) CINDEX_WARN_UNUSED_RESULT\n\t\t{\n\t\t\treturn block_count(n) * bytes_per_block;\n\t\t}\n\t};\n}\n\n", "meta": {"hexsha": "d04a94232a02f5f3bab4a09c07c0e2f39463ed7d", "size": 737, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fawnds/cindex/block_info.hpp", "max_stars_repo_name": "ByteHamster/silt", "max_stars_repo_head_hexsha": "9970432b27db7b9ef3f23f56cdd0609183e9fd83", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 134.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T21:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T06:03:22.000Z", "max_issues_repo_path": "fawnds/cindex/block_info.hpp", "max_issues_repo_name": "theopengroup/silt", "max_issues_repo_head_hexsha": "9970432b27db7b9ef3f23f56cdd0609183e9fd83", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fawnds/cindex/block_info.hpp", "max_forks_repo_name": "theopengroup/silt", "max_forks_repo_head_hexsha": "9970432b27db7b9ef3f23f56cdd0609183e9fd83", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T03:12:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T09:19:28.000Z", "avg_line_length": 22.3333333333, "max_line_length": 90, "alphanum_fraction": 0.7421981004, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5814595408773353}}
{"text": "#define BOOST_TEST_MODULE blas\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/matrix/all.h++>\n#include <mla/vector/all.h++>\n\n#include <mla/operations/level2/syr.h++>\n\n\nusing Scalar = float;\n\ntypedef boost::mpl::list<\n\tmla::matrix::DenseRowMajor<Scalar>,\n\tmla::matrix::Diagonal<Scalar>,\n\tmla::matrix::SparseDOK<Scalar>,\n\tmla::matrix::SparseCRS<Scalar>\n> matrix_type_list;\n\n\ntemplate<typename T> using MatrixType = mla::matrix::DenseRowMajor<T>;\n\n\ntypedef boost::mpl::list<\n\tmla::vector::Dense<Scalar>,\n\tmla::vector::SparseCS<Scalar>\n> vector_type_list;\n\n\n\nBOOST_AUTO_TEST_SUITE(test_boost_level2)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( blas_level2_test_syr_DenseRowMajor_zero, VectorType, vector_type_list )\n{\n\tusing namespace mla;\n\n\tScalar alpha = 1.0f;\n\n\tsize_t length = 3;\n\tMatrixType<Scalar> A( length, length);\n\n\tVectorType x(length);\n\tx.setValue(0, 1.0f);\n\tx.setValue(1, 1.0f);\n\tx.setValue(2, 1.0f);\n\n\n\tsyr(alpha, x, A);\n\n\n\tfor(size_t i = 0; i < length; i++)\n\t{\n\t\tfor(size_t j = 0; j < length; j++)\n\t\t{\n\t\t\tBOOST_CHECK_CLOSE( A.getValue(i,j), 1.0f, 1.0e-5 );\n\t\t}\n\t}\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "699da15e6957845d209e41cdaada4ec7fe5fc501", "size": 1179, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_blas_level2_syr_DenseRowMajor.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/test_blas_level2_syr_DenseRowMajor.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/test_blas_level2_syr_DenseRowMajor.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3382352941, "max_line_length": 102, "alphanum_fraction": 0.7090754877, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5813200791484746}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, gamma_p) {\n  using stan::math::gamma_p;\n  \n  EXPECT_FLOAT_EQ(0.63212055, gamma_p(1.0,1.0));\n  EXPECT_FLOAT_EQ(0.82755178, gamma_p(0.1,0.1));\n  EXPECT_FLOAT_EQ(0.76189667, gamma_p(3.0,4.0));\n  EXPECT_FLOAT_EQ(0.35276812, gamma_p(4.0,3.0));\n  EXPECT_THROW(gamma_p(-4.0,3.0), std::domain_error);\n  EXPECT_THROW(gamma_p(4.0,-3.0), std::domain_error);\n}\n\nTEST(MathFunctions, gamma_p_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::gamma_p(1.0, nan));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::gamma_p(nan, 1.0));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::gamma_p(nan, nan));\n}\n", "meta": {"hexsha": "4d4146e32c6d8a56f8b0ebdf6328a1a1efc50f9e", "size": 855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/gamma_p_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/gamma_p_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/gamma_p_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5357142857, "max_line_length": 56, "alphanum_fraction": 0.6736842105, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5813200753067523}}
{"text": "/**\n * @file kernel_test.cpp\n * @author Ryan Curtin\n * @author Ajinkya Kale\n *\n * Tests for the various kernel classes.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core/kernels/cosine_distance.hpp>\n#include <mlpack/core/kernels/epanechnikov_kernel.hpp>\n#include <mlpack/core/kernels/gaussian_kernel.hpp>\n#include <mlpack/core/kernels/hyperbolic_tangent_kernel.hpp>\n#include <mlpack/core/kernels/laplacian_kernel.hpp>\n#include <mlpack/core/kernels/linear_kernel.hpp>\n#include <mlpack/core/kernels/polynomial_kernel.hpp>\n#include <mlpack/core/kernels/spherical_kernel.hpp>\n#include <mlpack/core/kernels/pspectrum_string_kernel.hpp>\n#include <mlpack/core/kernels/cauchy_kernel.hpp>\n#include <mlpack/core/metrics/lmetric.hpp>\n#include <mlpack/core/metrics/mahalanobis_distance.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n#include \"serialization.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::kernel;\nusing namespace mlpack::metric;\n\nBOOST_AUTO_TEST_SUITE(KernelTest);\n\n/**\n * Basic test of the Manhattan distance.\n */\nBOOST_AUTO_TEST_CASE(ManhattanDistanceTest)\n{\n  // A couple quick tests.\n  arma::vec a = \"1.0 3.0 4.0\";\n  arma::vec b = \"3.0 3.0 5.0\";\n\n  BOOST_REQUIRE_CLOSE(ManhattanDistance::Evaluate(a, b), 3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(ManhattanDistance::Evaluate(b, a), 3.0, 1e-5);\n\n  // Check also for when the root is taken (should be the same).\n  BOOST_REQUIRE_CLOSE((LMetric<1, true>::Evaluate(a, b)), 3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE((LMetric<1, true>::Evaluate(b, a)), 3.0, 1e-5);\n}\n\n/**\n * Basic test of squared Euclidean distance.\n */\nBOOST_AUTO_TEST_CASE(SquaredEuclideanDistanceTest)\n{\n  // Sample 2-dimensional vectors.\n  arma::vec a = \"1.0  2.0\";\n  arma::vec b = \"0.0 -2.0\";\n\n  BOOST_REQUIRE_CLOSE(SquaredEuclideanDistance::Evaluate(a, b), 17.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(SquaredEuclideanDistance::Evaluate(b, a), 17.0, 1e-5);\n}\n\n/**\n * Basic test of Euclidean distance.\n */\nBOOST_AUTO_TEST_CASE(EuclideanDistanceTest)\n{\n  arma::vec a = \"1.0 3.0 5.0 7.0\";\n  arma::vec b = \"4.0 0.0 2.0 0.0\";\n\n  BOOST_REQUIRE_CLOSE(EuclideanDistance::Evaluate(a, b), sqrt(76.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(EuclideanDistance::Evaluate(b, a), sqrt(76.0), 1e-5);\n}\n\n/**\n * Arbitrary test case for coverage.\n */\nBOOST_AUTO_TEST_CASE(ArbitraryCaseTest)\n{\n  arma::vec a = \"3.0 5.0 6.0 7.0\";\n  arma::vec b = \"1.0 2.0 1.0 0.0\";\n\n  BOOST_REQUIRE_CLOSE((LMetric<3, false>::Evaluate(a, b)), 503.0, 1e-5);\n  BOOST_REQUIRE_CLOSE((LMetric<3, false>::Evaluate(b, a)), 503.0, 1e-5);\n\n  BOOST_REQUIRE_CLOSE((LMetric<3, true>::Evaluate(a, b)), 7.95284762, 1e-5);\n  BOOST_REQUIRE_CLOSE((LMetric<3, true>::Evaluate(b, a)), 7.95284762, 1e-5);\n}\n\n/**\n * Make sure two vectors of all zeros return zero distance, for a few different\n * powers.\n */\nBOOST_AUTO_TEST_CASE(LMetricZerosTest)\n{\n  arma::vec a(250);\n  a.fill(0.0);\n\n  // We cannot use a loop because compilers seem to be unable to unroll the loop\n  // and realize the variable actually is knowable at compile-time.\n  BOOST_REQUIRE((LMetric<1, false>::Evaluate(a, a)) == 0);\n  BOOST_REQUIRE((LMetric<1, true>::Evaluate(a, a)) == 0);\n  BOOST_REQUIRE((LMetric<2, false>::Evaluate(a, a)) == 0);\n  BOOST_REQUIRE((LMetric<2, true>::Evaluate(a, a)) == 0);\n  BOOST_REQUIRE((LMetric<3, false>::Evaluate(a, a)) == 0);\n  BOOST_REQUIRE((LMetric<3, true>::Evaluate(a, a)) == 0);\n  BOOST_REQUIRE((LMetric<4, false>::Evaluate(a, a)) == 0);\n  BOOST_REQUIRE((LMetric<4, true>::Evaluate(a, a)) == 0);\n  BOOST_REQUIRE((LMetric<5, false>::Evaluate(a, a)) == 0);\n  BOOST_REQUIRE((LMetric<5, true>::Evaluate(a, a)) == 0);\n}\n\n/**\n * Simple test of Mahalanobis distance with unset covariance matrix in\n * constructor.\n */\nBOOST_AUTO_TEST_CASE(MDUnsetCovarianceTest)\n{\n  MahalanobisDistance<false> md;\n  md.Covariance() = arma::eye<arma::mat>(4, 4);\n  arma::vec a = \"1.0 2.0 2.0 3.0\";\n  arma::vec b = \"0.0 0.0 1.0 3.0\";\n\n  BOOST_REQUIRE_CLOSE(md.Evaluate(a, b), 6.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(md.Evaluate(b, a), 6.0, 1e-5);\n}\n\n/**\n * Simple test of Mahalanobis distance with unset covariance matrix in\n * constructor and t_take_root set to true.\n */\nBOOST_AUTO_TEST_CASE(MDRootUnsetCovarianceTest)\n{\n  MahalanobisDistance<true> md;\n  md.Covariance() = arma::eye<arma::mat>(4, 4);\n  arma::vec a = \"1.0 2.0 2.5 5.0\";\n  arma::vec b = \"0.0 2.0 0.5 8.0\";\n\n  BOOST_REQUIRE_CLOSE(md.Evaluate(a, b), sqrt(14.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(md.Evaluate(b, a), sqrt(14.0), 1e-5);\n}\n\n/**\n * Simple test of Mahalanobis distance setting identity covariance in\n * constructor.\n */\nBOOST_AUTO_TEST_CASE(MDEyeCovarianceTest)\n{\n  MahalanobisDistance<false> md(4);\n  arma::vec a = \"1.0 2.0 2.0 3.0\";\n  arma::vec b = \"0.0 0.0 1.0 3.0\";\n\n  BOOST_REQUIRE_CLOSE(md.Evaluate(a, b), 6.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(md.Evaluate(b, a), 6.0, 1e-5);\n}\n\n/**\n * Simple test of Mahalanobis distance setting identity covariance in\n * constructor and t_take_root set to true.\n */\nBOOST_AUTO_TEST_CASE(MDRootEyeCovarianceTest)\n{\n  MahalanobisDistance<true> md(4);\n  arma::vec a = \"1.0 2.0 2.5 5.0\";\n  arma::vec b = \"0.0 2.0 0.5 8.0\";\n\n  BOOST_REQUIRE_CLOSE(md.Evaluate(a, b), sqrt(14.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(md.Evaluate(b, a), sqrt(14.0), 1e-5);\n}\n\n/**\n * Simple test with diagonal covariance matrix.\n */\nBOOST_AUTO_TEST_CASE(MDDiagonalCovarianceTest)\n{\n  arma::mat cov = arma::eye<arma::mat>(5, 5);\n  cov(0, 0) = 2.0;\n  cov(1, 1) = 0.5;\n  cov(2, 2) = 3.0;\n  cov(3, 3) = 1.0;\n  cov(4, 4) = 1.5;\n  MahalanobisDistance<false> md(cov);\n\n  arma::vec a = \"1.0 2.0 2.0 4.0 5.0\";\n  arma::vec b = \"2.0 3.0 1.0 1.0 0.0\";\n\n  BOOST_REQUIRE_CLOSE(md.Evaluate(a, b), 52.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(md.Evaluate(b, a), 52.0, 1e-5);\n}\n\n/**\n * More specific case with more difficult covariance matrix.\n */\nBOOST_AUTO_TEST_CASE(MDFullCovarianceTest)\n{\n  arma::mat cov = \"1.0 2.0 3.0 4.0;\"\n                  \"0.5 0.6 0.7 0.1;\"\n                  \"3.4 4.3 5.0 6.1;\"\n                  \"1.0 2.0 4.0 1.0;\";\n  MahalanobisDistance<false> md(cov);\n\n  arma::vec a = \"1.0 2.0 2.0 4.0\";\n  arma::vec b = \"2.0 3.0 1.0 1.0\";\n\n  BOOST_REQUIRE_CLOSE(md.Evaluate(a, b), 15.7, 1e-5);\n  BOOST_REQUIRE_CLOSE(md.Evaluate(b, a), 15.7, 1e-5);\n}\n\n/**\n * Simple test case for the cosine distance.\n */\nBOOST_AUTO_TEST_CASE(CosineDistanceSameAngleTest)\n{\n  arma::vec a = \"1.0 2.0 3.0\";\n  arma::vec b = \"2.0 4.0 6.0\";\n\n  BOOST_REQUIRE_CLOSE(CosineDistance::Evaluate(a, b), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(CosineDistance::Evaluate(b, a), 1.0, 1e-5);\n}\n\n/**\n * Now let's have them be orthogonal.\n */\nBOOST_AUTO_TEST_CASE(CosineDistanceOrthogonalTest)\n{\n  arma::vec a = \"0.0 1.0\";\n  arma::vec b = \"1.0 0.0\";\n\n  BOOST_REQUIRE_SMALL(CosineDistance::Evaluate(a, b), 1e-5);\n  BOOST_REQUIRE_SMALL(CosineDistance::Evaluate(b, a), 1e-5);\n}\n\n/**\n * Some random angle test.\n */\nBOOST_AUTO_TEST_CASE(CosineDistanceRandomTest)\n{\n  arma::vec a = \"0.1 0.2 0.3 0.4 0.5\";\n  arma::vec b = \"1.2 1.0 0.8 -0.3 -0.5\";\n\n  BOOST_REQUIRE_CLOSE(CosineDistance::Evaluate(a, b), 0.1385349024, 1e-5);\n  BOOST_REQUIRE_CLOSE(CosineDistance::Evaluate(b, a), 0.1385349024, 1e-5);\n}\n\n/**\n * Linear Kernel test.\n */\nBOOST_AUTO_TEST_CASE(LinearKernelTest)\n{\n  arma::vec a = \".2 .3 .4 .1\";\n  arma::vec b = \".56 .21 .623 .82\";\n\n  LinearKernel lk;\n  BOOST_REQUIRE_CLOSE(lk.Evaluate(a, b), .5062, 1e-5);\n  BOOST_REQUIRE_CLOSE(lk.Evaluate(b, a), .5062, 1e-5);\n}\n\n/**\n * Linear Kernel test, orthogonal vectors.\n */\nBOOST_AUTO_TEST_CASE(LinearKernelOrthogonalTest)\n{\n  arma::vec a = \"1 0 0\";\n  arma::vec b = \"0 0 1\";\n\n  LinearKernel lk;\n  BOOST_REQUIRE_SMALL(lk.Evaluate(a, b), 1e-5);\n  BOOST_REQUIRE_SMALL(lk.Evaluate(b, a), 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(GaussianKernelTest)\n{\n  arma::vec a = \"1 0 0\";\n  arma::vec b = \"0 1 0\";\n  arma::vec c = \"0 0 1\";\n\n  GaussianKernel gk(.5);\n  BOOST_REQUIRE_CLOSE(gk.Evaluate(a, b), .018315638888734, 1e-5);\n  BOOST_REQUIRE_CLOSE(gk.Evaluate(b, a), .018315638888734, 1e-5);\n  BOOST_REQUIRE_CLOSE(gk.Evaluate(a, c), .018315638888734, 1e-5);\n  BOOST_REQUIRE_CLOSE(gk.Evaluate(c, a), .018315638888734, 1e-5);\n  BOOST_REQUIRE_CLOSE(gk.Evaluate(b, c), .018315638888734, 1e-5);\n  BOOST_REQUIRE_CLOSE(gk.Evaluate(c, b), .018315638888734, 1e-5);\n  /* check the single dimension evaluate function */\n  BOOST_REQUIRE_CLOSE(gk.Evaluate(1.0), 0.1353352832366127, 1e-5);\n  BOOST_REQUIRE_CLOSE(gk.Evaluate(2.0), 0.00033546262790251185, 1e-5);\n  BOOST_REQUIRE_CLOSE(gk.Evaluate(3.0), 1.5229979744712629e-08, 1e-5);\n  /* check the normalization constant */\n  BOOST_REQUIRE_CLOSE(gk.Normalizer(1), 1.2533141373155001, 1e-5);\n  BOOST_REQUIRE_CLOSE(gk.Normalizer(2), 1.5707963267948963, 1e-5);\n  BOOST_REQUIRE_CLOSE(gk.Normalizer(3), 1.9687012432153019, 1e-5);\n  BOOST_REQUIRE_CLOSE(gk.Normalizer(4), 2.4674011002723386, 1e-5);\n  /* check the convolution integral */\n  BOOST_REQUIRE_CLOSE(gk.ConvolutionIntegral(a, b), 0.024304474038457577, 1e-5);\n  BOOST_REQUIRE_CLOSE(gk.ConvolutionIntegral(a, c), 0.024304474038457577, 1e-5);\n  BOOST_REQUIRE_CLOSE(gk.ConvolutionIntegral(b, c), 0.024304474038457577, 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(GaussianKernelSerializationTest)\n{\n  GaussianKernel gk(0.5);\n  GaussianKernel xmlGk(1.5), textGk, binaryGk(15.0);\n\n  // Serialize the kernels.\n  SerializeObjectAll(gk, xmlGk, textGk, binaryGk);\n\n  BOOST_REQUIRE_CLOSE(gk.Bandwidth(), 0.5, 1e-5);\n  BOOST_REQUIRE_CLOSE(xmlGk.Bandwidth(), 0.5, 1e-5);\n  BOOST_REQUIRE_CLOSE(textGk.Bandwidth(), 0.5, 1e-5);\n  BOOST_REQUIRE_CLOSE(binaryGk.Bandwidth(), 0.5, 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(SphericalKernelTest)\n{\n  arma::vec a = \"1.0 0.0\";\n  arma::vec b = \"0.0 1.0\";\n  arma::vec c = \"0.2 0.9\";\n\n  SphericalKernel sk(.5);\n  BOOST_REQUIRE_CLOSE(sk.Evaluate(a, b), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(sk.Evaluate(a, c), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(sk.Evaluate(b, c), 1.0, 1e-5);\n  /* check the single dimension evaluate function */\n  BOOST_REQUIRE_CLOSE(sk.Evaluate(0.10), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(sk.Evaluate(0.25), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(sk.Evaluate(0.50), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(sk.Evaluate(1.00), 0.0, 1e-5);\n  /* check the normalization constant */\n  BOOST_REQUIRE_CLOSE(sk.Normalizer(1), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(sk.Normalizer(2), 0.78539816339744828, 1e-5);\n  BOOST_REQUIRE_CLOSE(sk.Normalizer(3), 0.52359877559829893, 1e-5);\n  BOOST_REQUIRE_CLOSE(sk.Normalizer(4), 0.30842513753404244, 1e-5);\n  /* check the convolution integral */\n  BOOST_REQUIRE_CLOSE(sk.ConvolutionIntegral(a, b), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(sk.ConvolutionIntegral(a, c), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(sk.ConvolutionIntegral(b, c), 1.0021155029652784, 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(EpanechnikovKernelTest)\n{\n  arma::vec a = \"1.0 0.0\";\n  arma::vec b = \"0.0 1.0\";\n  arma::vec c = \"0.1 0.9\";\n\n  EpanechnikovKernel ek(.5);\n  BOOST_REQUIRE_CLOSE(ek.Evaluate(a, b), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(ek.Evaluate(b, c), 0.92, 1e-5);\n  BOOST_REQUIRE_CLOSE(ek.Evaluate(a, c), 0.0, 1e-5);\n  /* check the single dimension evaluate function */\n  BOOST_REQUIRE_CLOSE(ek.Evaluate(0.10), 0.96, 1e-5);\n  BOOST_REQUIRE_CLOSE(ek.Evaluate(0.25), 0.75, 1e-5);\n  BOOST_REQUIRE_CLOSE(ek.Evaluate(0.50), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(ek.Evaluate(1.00), 0.0, 1e-5);\n  /* check the normalization constant */\n  BOOST_REQUIRE_CLOSE(ek.Normalizer(1), 0.666666666666666, 1e-5);\n  BOOST_REQUIRE_CLOSE(ek.Normalizer(2), 0.39269908169872414, 1e-5);\n  BOOST_REQUIRE_CLOSE(ek.Normalizer(3), 0.20943951023931956, 1e-5);\n  BOOST_REQUIRE_CLOSE(ek.Normalizer(4), 0.10280837917801415, 1e-5);\n  /* check the convolution integral */\n  BOOST_REQUIRE_CLOSE(ek.ConvolutionIntegral(a, b), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(ek.ConvolutionIntegral(a, c), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(ek.ConvolutionIntegral(b, c), 1.5263455690698258, 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(PolynomialKernelTest)\n{\n  arma::vec a = \"0 0 1\";\n  arma::vec b = \"0 1 0\";\n\n  PolynomialKernel pk(5.0, 5.0);\n  BOOST_REQUIRE_CLOSE(pk.Evaluate(a, b), 3125.0, 0);\n  BOOST_REQUIRE_CLOSE(pk.Evaluate(b, a), 3125.0, 0);\n}\n\nBOOST_AUTO_TEST_CASE(HyperbolicTangentKernelTest)\n{\n  arma::vec a = \"0 0 1\";\n  arma::vec b = \"0 1 0\";\n\n  HyperbolicTangentKernel tk(5.0, 5.0);\n  BOOST_REQUIRE_CLOSE(tk.Evaluate(a, b), 0.9999092, 1e-5);\n  BOOST_REQUIRE_CLOSE(tk.Evaluate(b, a), 0.9999092, 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(LaplacianKernelTest)\n{\n  arma::vec a = \"0 0 1\";\n  arma::vec b = \"0 1 0\";\n\n  LaplacianKernel lk(1.0);\n  BOOST_REQUIRE_CLOSE(lk.Evaluate(a, b), 0.243116734, 5e-5);\n  BOOST_REQUIRE_CLOSE(lk.Evaluate(b, a), 0.243116734, 5e-5);\n}\n\n// Ensure that the p-spectrum kernel successfully extracts all length-p\n// substrings from the data.\nBOOST_AUTO_TEST_CASE(PSpectrumSubstringExtractionTest)\n{\n  std::vector<std::vector<std::string> > datasets;\n\n  datasets.push_back(std::vector<std::string>());\n\n  datasets[0].push_back(\"herpgle\");\n  datasets[0].push_back(\"herpagkle\");\n  datasets[0].push_back(\"klunktor\");\n  datasets[0].push_back(\"flibbynopple\");\n\n  datasets.push_back(std::vector<std::string>());\n\n  datasets[1].push_back(\"floggy3245\");\n  datasets[1].push_back(\"flippydopflip\");\n  datasets[1].push_back(\"stupid fricking cat\");\n  datasets[1].push_back(\"food time isn't until later\");\n  datasets[1].push_back(\"leave me alone until 6:00\");\n  datasets[1].push_back(\"only after that do you get any food.\");\n  datasets[1].push_back(\"obloblobloblobloblobloblob\");\n\n  PSpectrumStringKernel p(datasets, 3);\n\n  // Ensure the sizes are correct.\n  BOOST_REQUIRE_EQUAL(p.Counts().size(), 2);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0].size(), 4);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1].size(), 7);\n\n  // herpgle: her, erp, rpg, pgl, gle\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][0].size(), 5);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][0][\"her\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][0][\"erp\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][0][\"rpg\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][0][\"pgl\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][0][\"gle\"], 1);\n\n  // herpagkle: her, erp, rpa, pag, agk, gkl, kle\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][1].size(), 7);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][1][\"her\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][1][\"erp\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][1][\"rpa\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][1][\"pag\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][1][\"agk\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][1][\"gkl\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][1][\"kle\"], 1);\n\n  // klunktor: klu, lun, unk, nkt, kto, tor\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][2].size(), 6);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][2][\"klu\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][2][\"lun\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][2][\"unk\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][2][\"nkt\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][2][\"kto\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][2][\"tor\"], 1);\n\n  // flibbynopple: fli lib ibb bby byn yno nop opp ppl ple\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][3].size(), 10);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][3][\"fli\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][3][\"lib\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][3][\"ibb\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][3][\"bby\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][3][\"byn\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][3][\"yno\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][3][\"nop\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][3][\"opp\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][3][\"ppl\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[0][3][\"ple\"], 1);\n\n  // floggy3245: flo log ogg ggy gy3 y32 324 245\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][0].size(), 8);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][0][\"flo\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][0][\"log\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][0][\"ogg\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][0][\"ggy\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][0][\"gy3\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][0][\"y32\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][0][\"324\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][0][\"245\"], 1);\n\n  // flippydopflip: fli lip ipp ppy pyd ydo dop opf pfl fli lip\n  // fli(2) lip(2) ipp ppy pyd ydo dop opf pfl\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][1].size(), 9);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][1][\"fli\"], 2);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][1][\"lip\"], 2);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][1][\"ipp\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][1][\"ppy\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][1][\"pyd\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][1][\"ydo\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][1][\"dop\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][1][\"opf\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][1][\"pfl\"], 1);\n\n  // stupid fricking cat: stu tup upi pid fri ric ick cki kin ing cat\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][2].size(), 11);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][2][\"stu\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][2][\"tup\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][2][\"upi\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][2][\"pid\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][2][\"fri\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][2][\"ric\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][2][\"ick\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][2][\"cki\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][2][\"kin\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][2][\"ing\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][2][\"cat\"], 1);\n\n  // food time isn't until later: foo ood tim ime isn unt nti til lat ate ter\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][3].size(), 11);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][3][\"foo\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][3][\"ood\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][3][\"tim\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][3][\"ime\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][3][\"isn\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][3][\"unt\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][3][\"nti\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][3][\"til\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][3][\"lat\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][3][\"ate\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][3][\"ter\"], 1);\n\n  // leave me alone until 6:00: lea eav ave alo lon one unt nti til\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][4].size(), 9);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][4][\"lea\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][4][\"eav\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][4][\"ave\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][4][\"alo\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][4][\"lon\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][4][\"one\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][4][\"unt\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][4][\"nti\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][4][\"til\"], 1);\n\n  // only after that do you get any food.:\n  // onl nly aft fte ter tha hat you get any foo ood\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5].size(), 12);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5][\"onl\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5][\"nly\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5][\"aft\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5][\"fte\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5][\"ter\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5][\"tha\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5][\"hat\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5][\"you\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5][\"get\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5][\"any\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5][\"foo\"], 1);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][5][\"ood\"], 1);\n\n  // obloblobloblobloblobloblob: obl(8) blo(8) lob(8)\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][6].size(), 3);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][6][\"obl\"], 8);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][6][\"blo\"], 8);\n  BOOST_REQUIRE_EQUAL(p.Counts()[1][6][\"lob\"], 8);\n}\n\nBOOST_AUTO_TEST_CASE(PSpectrumStringEvaluateTest)\n{\n  // Construct simple dataset.\n  std::vector<std::vector<std::string> > dataset;\n  dataset.push_back(std::vector<std::string>());\n  dataset[0].push_back(\"hello\");\n  dataset[0].push_back(\"jello\");\n  dataset[0].push_back(\"mellow\");\n  dataset[0].push_back(\"mellow jello\");\n\n  PSpectrumStringKernel p(dataset, 3);\n\n  arma::vec a(\"0 0\");\n  arma::vec b(\"0 0\");\n\n  BOOST_REQUIRE_CLOSE(p.Evaluate(a, b), 3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(p.Evaluate(b, a), 3.0, 1e-5);\n\n  b = \"0 1\";\n  BOOST_REQUIRE_CLOSE(p.Evaluate(a, b), 2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(p.Evaluate(b, a), 2.0, 1e-5);\n\n  b = \"0 2\";\n  BOOST_REQUIRE_CLOSE(p.Evaluate(a, b), 2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(p.Evaluate(b, a), 2.0, 1e-5);\n\n  b = \"0 3\";\n  BOOST_REQUIRE_CLOSE(p.Evaluate(a, b), 4.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(p.Evaluate(b, a), 4.0, 1e-5);\n\n  a = \"0 1\";\n  b = \"0 1\";\n  BOOST_REQUIRE_CLOSE(p.Evaluate(a, b), 3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(p.Evaluate(b, a), 3.0, 1e-5);\n\n  b = \"0 2\";\n  BOOST_REQUIRE_CLOSE(p.Evaluate(a, b), 2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(p.Evaluate(b, a), 2.0, 1e-5);\n\n  b = \"0 3\";\n  BOOST_REQUIRE_CLOSE(p.Evaluate(a, b), 5.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(p.Evaluate(b, a), 5.0, 1e-5);\n\n  a = \"0 2\";\n  b = \"0 2\";\n  BOOST_REQUIRE_CLOSE(p.Evaluate(a, b), 4.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(p.Evaluate(b, a), 4.0, 1e-5);\n\n  b = \"0 3\";\n  BOOST_REQUIRE_CLOSE(p.Evaluate(a, b), 6.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(p.Evaluate(b, a), 6.0, 1e-5);\n\n  a = \"0 3\";\n  BOOST_REQUIRE_CLOSE(p.Evaluate(a, b), 11.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(p.Evaluate(b, a), 11.0, 1e-5);\n}\n\n/**\n * Cauchy Kernel test.\n */\nBOOST_AUTO_TEST_CASE(CauchyKernelTest)\n{\n  arma::vec a = \"0 0 1\";\n  arma::vec b = \"0 1 0\";\n\n  CauchyKernel ck(5.0);\n  BOOST_REQUIRE_CLOSE(ck.Evaluate(a, b), 0.92592588, 1e-5);\n  BOOST_REQUIRE_CLOSE(ck.Evaluate(b, a), 0.92592588, 1e-5);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "048e8eff6db36e09e08ac2562d90c73564cfaa83", "size": 21572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/kernel_test.cpp", "max_stars_repo_name": "RMaron/mlpack", "max_stars_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-21T23:30:34.000Z", "max_issues_repo_path": "src/mlpack/tests/kernel_test.cpp", "max_issues_repo_name": "RMaron/mlpack", "max_issues_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-01-23T18:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T13:58:34.000Z", "max_forks_repo_path": "src/mlpack/tests/kernel_test.cpp", "max_forks_repo_name": "RMaron/mlpack", "max_forks_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-20T00:54:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-16T05:34:32.000Z", "avg_line_length": 34.4600638978, "max_line_length": 80, "alphanum_fraction": 0.6733265344, "num_tokens": 7640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5813200729078911}}
{"text": "#include <iostream>\n#include <mpc.hpp>\n#include <Eigen/Dense>\n#include <vector>\n#include <chrono>\n#include <cmath>\n#include <cstdlib>\n\n\nint main(int argc, char** argv) {\n    int N = 1;\n    if (argc > 1) {\n        N = atoi(argv[1]);\n    }\n\n    MPC mpc;\n    Eigen::VectorXd coeffs(4);\n    Eigen::VectorXd state(6);\n\n    coeffs << -0.354214,\n               0.002064,\n               0.00111025,\n               2.13429e-6;\n\n    state << 0.0,\n             0.0,\n             0.0,\n             19.7626,\n            -0.354214,\n            -0.002064;\n    std::vector<double> elapsed_vector(N);\n    for (auto i=0; i < N; i++) {\n        auto start = std::chrono::system_clock::now();\n        std::vector<double> optimal = mpc.Solve(state, coeffs);\n        elapsed_vector[i] = std::chrono::duration_cast< std::chrono::duration<double> >(std::chrono::system_clock::now()-start).count();\n        //std::cout << optimal[0] << \", \" << optimal[1] << std::endl;\n    }\n    /*\n     * expected output:\n     * 0.00547966, 0.314773\n     *\n     * actual output:\n     * 0.00547968, 0.314752\n     *\n     * result: pass\n     */\n    double mean = 0;\n    for (auto i=0; i < N; i++) {\n        mean += elapsed_vector[i];\n    }\n    mean /= static_cast<double>(N);\n\n    double var = 0;\n    for (auto i=0; i < N; i++) {\n        auto delta = elapsed_vector[i] - mean;\n        var = delta*delta;\n    }\n    double std = sqrt(var/static_cast<double>(N));\n\n    std::cout << \"----------------------TIMING STATS-----------------------\" << std::endl;\n    std::cout << \"runs: \" << N << \", mean: \" << mean << \", stddev: \" << std << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "19ee5705762740ec36d9c096d21a11ed24f4e5bf", "size": 1615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_install.cpp", "max_stars_repo_name": "jwdinius/ipopt-timing-test", "max_stars_repo_head_hexsha": "b2e9725df48235136ab7af0d457be563cd0a947f", "max_stars_repo_licenses": ["Apache-2.0"], "max_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_install.cpp", "max_issues_repo_name": "jwdinius/ipopt-timing-test", "max_issues_repo_head_hexsha": "b2e9725df48235136ab7af0d457be563cd0a947f", "max_issues_repo_licenses": ["Apache-2.0"], "max_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_install.cpp", "max_forks_repo_name": "jwdinius/ipopt-timing-test", "max_forks_repo_head_hexsha": "b2e9725df48235136ab7af0d457be563cd0a947f", "max_forks_repo_licenses": ["Apache-2.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.8461538462, "max_line_length": 136, "alphanum_fraction": 0.4897832817, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5813200640250163}}
{"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 <blitz/blitz.h>\n#include <random/exponential.h>\n#include <random/discrete-uniform.h>\n#include <random/F.h>\n\nusing namespace blitz;\nusing namespace ranlib;\n\n#include <time.h>\n\n// workaround for broken streams in Compaq cxx, can't handle long double\n#if defined(__DECCXX)\n#define LD_HACK(x) static_cast<double>(x)\n#else\n#define LD_HACK(x) x\n#endif\n\nint main2()\n{\n    DiscreteUniform<int> rng(100);\n    rng.seed((unsigned int)time(0));\n\n    for (int i=0; i < 100; ++i)\n        cout << rng.random() << \"  \";\n    cout << endl;\n    return 0;\n}\n\nint main3()\n{\n    MersenneTwister x;\n\n    for (int j=0; j<1000; j++) {\n        printf(\"%10u \", x.random());\n        if (j%8==7) printf(\"\\n\");\n    }\n\n    return 0;\n}\n\nint main()\n{\n    F<long double> rng(2.0,3.0);\n    rng.seed((unsigned int)time(0),(unsigned int)time(0)); \n\n    long double sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0;\n\n    const int N = 10000;\n\n    for (int i=0; i < N; ++i)\n    {\n        long double x = rng.random();\n        sum1 += x;\n        sum2 += x*x;\n        sum3 += x*x*x;\n        sum4 += x*x*x*x;\n    }\n\n    cout << \"k1 = \" << LD_HACK(sum1/N) << endl\n         << \"k2 = \" << LD_HACK(sum2/N) << endl\n         << \"k3 = \" << LD_HACK(sum3/N) << endl\n         << \"k4 = \" << LD_HACK(sum4/N) << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "6c5f70118bf78d166190b28c181cef3ec9ca3598", "size": 1280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/rand2.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/rand2.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/rand2.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": 19.1044776119, "max_line_length": 72, "alphanum_fraction": 0.53515625, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5813200503444182}}
{"text": "#define EIGEN_USE_MKL_ALL\n\n#include <iostream>\n#include <iterator>\n#include <random>\n\n#include <Eigen/Core>\n\n#include \"models/classifiers/optimizable_linear_classifier.hpp\"\n#include \"utils/optimizers/stochastic_gradient_descent.hpp\"\n#include \"utils/loss_functions.hpp\"\n#include \"utils/eigen.hpp\"\n#include \"../misc.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nusing namespace mlt::models::classifiers;\nusing namespace mlt::utils::optimizers;\nusing namespace mlt::utils::loss_functions;\nusing namespace mlt::utils::eigen;\n\nint main() {\n\tprint_info();\n\tcout << endl;\n\n\tauto n_features = 5;\n\tauto n_classes = 4;\n\tauto n_samples = 1000;\n\tauto n_training = 0.8 * n_samples;\n\tauto n_val = n_samples - n_training;\n\n\tauto input = MatrixXd{ MatrixXd::Random(n_features, n_samples).cwiseAbs() * 10 };\n\tauto classes = VectorXi(n_samples);\n\n\tfor (auto i = 0; i < n_samples; i++) {\n\t\tauto sum = input.col(i).sum();\n\t\tclasses(i) = sum / 10;\n\t}\n\n\tusing loss_t = SoftmaxLoss;\n\tusing opt_t = StochasticGradientDescent<>;\n\n\tauto loss = loss_t();\n\tauto opt = opt_t(200, 500, 0.001, 0.99);\n\n\tOptimizableLinearClassifier<loss_t, opt_t> model(loss, opt, 5, true);\n\n\tmodel.fit(input.leftCols(n_training), classes.topRows(n_training), false);\n\n\tcout << \"Accuracy: \" << model.score(input.rightCols(n_val), classes.bottomRows(n_val)) << endl;\n\n\teval_numerical_gradient(model, MatrixXd::Random(n_classes, n_features + 1), input, classes_vector_to_classes_matrix(classes).cast<double>());\n\n\tcin.get();\n\n\treturn 0;\n}", "meta": {"hexsha": "344a8d7af8bfd9ece318b3f875b60f9a51f37e46", "size": 1492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/main.cpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/examples/main.cpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/main.cpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.724137931, "max_line_length": 142, "alphanum_fraction": 0.7298927614, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5813066219852663}}
{"text": "#ifndef _MDL_EXPRESSION_GRAPH_HPP_\n#define _MDL_EXPRESSION_GRAPH_HPP_\n\n#include \"LookupTable.hpp\"\n#include \"Location.hpp\"\n#include <unordered_map>\n#include <unordered_set>\n#include <boost/pool/object_pool.hpp>\n#include \"FileStatus.hpp\"\n#include \"Symbol.hpp\"\n\nnamespace sdo\n{\n\n/**\n * A class that represents all definitions in a mdl file\n * as an expression graph.\n */\nclass ExpressionGraph : public FileStatus\n{\npublic:\n   enum Operator\n   {\n      /**\n       * Integ operator from mdl\n       *        INTEG(rate,initial)\n       *\n       * Differential equation with initial value 'initial'\n       * and change rate 'rate'.\n       */\n      INTEG,\n      /**\n       * IF THEN ELSE operator from mdl\n       *        IF THEN ELSE( cond, thenval, elseval )\n       *\n       * If cond evaluates to true the value is 'thenval'\n       * else the value is 'elseval'.\n       */\n      IF,\n      /**\n       * ACTIVE INITIAL operator from mdl\n       *        ACTIVE INITIAL( activeeq, initialeq )\n       *\n       * returns 'activeeq' as value but 'initialeq' when\n       * used as initial value.\n       */\n      ACTIVE_INITIAL,\n      /**\n       * INITIAL operator from mdl\n       *        INITIAL( arg )\n       *\n       * returns intial value of 'arg'.\n       */\n      INITIAL,\n      /**\n       * DELAY FIXED operator from mdl\n       *        DELAY FIXED( input, delaytime, initial )\n       *\n       * Returns the value of 'input' from current time minus 'delaytime'.\n       * If current time is smaller than 'delaytime' the value is the\n       * initial value of 'initial'.\n       */\n      DELAY_FIXED,\n      /**\n       * PULSE operator from mdl\n       *        PULSE( start, width )\n       *\n       * Returns 1.0 if the current time is between 'start'\n       * and 'start'+'width' and 0.0 otherwise.\n       */\n      PULSE,\n      /**\n       * PULSE TRAIN operator from mdl\n       *        PULSE( start, width )\n       *\n       * Returns 1.0 if the current time is between 'start'\n       * and 'start'+'width' and 0.0 otherwise.\n       */\n      PULSE_TRAIN,\n      /**\n       *\n       */\n      STEP,\n      /**\n       *\n       */\n      RAMP,\n      /**\n       * Two children with the bounds of the interval for\n       * choosing a random value with a uniform distribution.\n       */\n      RANDOM_UNIFORM,\n      /**\n       * Plus operator.\n       */\n      PLUS,\n      /**\n       * Minus operator.\n       */\n      MINUS,\n      /**\n       * Multiplication operator.\n       */\n      MULT,\n      /**\n       * Division operator.\n       */\n      DIV,\n      /**\n       * Greater than operator.\n       */\n      G,\n      /**\n       * Greater or equal operator\n       */\n      GE,\n      /**\n       * Lower than operator.\n       */\n      L,\n      /**\n       * Lower or equal operator.\n       */\n      LE,\n      /**\n       * Equal to operator.\n       */\n      EQ,\n      /**\n       * Not equal to operator.\n       */\n      NEQ,\n      /**\n       * :AND: operator\n       */\n      AND,\n      /**\n       * :OR: operator\n       */\n      OR,\n      /** POWER(base, exponent) */\n      POWER,\n      /** LOG( x, base ) */\n      LOG,\n      /** MIN(a,b) */\n      MIN,\n      /** MAX(a,b) */\n      MAX,\n      /** MODULO(x,y) */\n      MODULO,\n      /**  Unary minus operator. */\n      UMINUS,\n      /** SQRT(x) */\n      SQRT,\n      /** EXP(x) */\n      EXP,\n      /** LN(x) */\n      LN,\n      /** ABS(x) */\n      ABS,\n      /**\n       * Operator INTERGER(x): Round 'x' to the next integer value towards zero.\n       */\n      INTEGER,\n      /**\n       * :NOT: operator\n       */\n      NOT,\n      SIN,\n      COS,\n      TAN,\n      ARCSIN,\n      ARCCOS,\n      ARCTAN,\n      SINH,\n      COSH,\n      TANH,\n      /**\n       * Represents the value of the current time.\n       */\n      TIME,\n      /**\n       * Represents a constant the value is stored\n       * at node->value\n       */\n      CONSTANT,\n      /**\n       * Represents a control. Has three children than can be nullptr's.\n       * First child is the lower bound, second child the start value and\n       * third child the upper bound.\n       */\n      CONTROL,\n      /**\n       * Application of lookup table in child1 to the argument\n       * in child2\n       */\n      APPLY_LOOKUP,\n      /**\n       * Contains the actual lookup table in node->lookup_table.\n       */\n      LOOKUP_TABLE,\n      /** Undefined node. Will give an error during call to analyze() */\n      NIL\n   };\n\n   enum NodeType\n   {\n      /** The node is constant */\n      CONSTANT_NODE = 0, // 000\n      /** The node is constant for each time */\n      STATIC_NODE   = 1,   // 001\n      /** The node depends on a state */\n      DYNAMIC_NODE  = 3,  // 011\n      /** The node type is unknow. After analyze() no node shoudl have this type. */\n      UNKNOWN       = 7        // 111\n   };\n\n   enum InitialType\n   {\n      /** The initial value is a constant */\n      CONSTANT_INIT  = 0,\n      /** The initial value is a control */\n      CONTROLED_INIT = 1,\n      /** Type is unknown */\n      UNKNOWN_INIT = 2,\n   };\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\" //anonymous union is not standard\n\n   /**\n    * A node in the expression graph.\n    */\n   struct Node\n   {\n\n      /**\n       * The operator of the node\n       */\n      Operator    op;\n      /**\n       * The type of the node\n       */\n      NodeType    type = UNKNOWN;\n      /**\n       * Is the node integer (only variables)\n       */\n      bool    integer = false;\n      /**\n       * The initial type of the node\n       */\n      InitialType init = UNKNOWN_INIT;\n      union\n      {\n         struct\n         {\n            /**\n             * The first child if it exists\n             */\n            Node *child1;\n            /**\n             * The second child if it exists\n             */\n            Node *child2;\n            /**\n             * The third child if it exists\n             */\n            Node *child3;\n         };\n         /**\n          * The lookup table if it exists\n          */\n         LookupTable *lookup_table;\n      };\n      /**\n       * The level of the node, i.e. a number representing its topological\n       * order in the expression graph. If a node represents a+b its level\n       * is max(a->level,b->level)+1\n       */\n      int level;\n      union\n      {\n         /**\n          * The size of a control. E.g. the number of timesteps\n          * a control is valid for. If this is 0 then the control\n          * is the same for all times. If it is 1 there is a\n          * different control var at each time, and if it is greater\n          * than one it is a piecewise control.\n          */\n         int    control_size;\n         /**\n          * The initial value of a node. For constants this value\n          * is valid at all times. For nodes with init = CONTROLED_INIT\n          * this values means nothing.\n          */\n         double value;\n      };\n\n      Symbol unit;\n      boost::optional<double> lb;\n      boost::optional<double> ub;\n      /**\n       * Locations in the file where this node is used.\n       */\n      std::vector<FileLocation> usages;\n   };\n#pragma GCC diagnostic pop\n\n   /**\n    * Evaluate a static node at given time\n    */\n   double evaluateNode( const Node *node, double time, bool initial = false ) const;\n\n   /**\n    * Equality functor that compares two nodes by their structure, i.e.\n    * a+b is equal to b+a and some more transformations.\n    */\n   struct structural_node_eq\n   {\n      bool operator()( const Node *a, const Node *b ) const;\n   };\n\n   /**\n    * Hash functor that hashes two nodes, that are equal in their structure to\n    * the same hash value, e.g. a+b, b+a.\n    */\n   struct structural_node_hash\n   {\n      std::size_t operator()( const Node *node ) const;\n   };\n\n\n   /**\n    * Add a symbol to the expression graph.\n    *\n    * \\param s the symbol\n    * \\param node the node for the symbol\n    */\n   void addSymbol( const Symbol &s, Node *node );\n\n   /**\n    * \\return a reference to the symbol table.\n    */\n   std::unordered_map<Symbol, Node *> &getSymbolTable()\n   {\n      return symbol_table;\n   }\n\n   /**\n    * \\return a const reference to the symbol table.\n    */\n   const std::unordered_map<Symbol, Node *> &getSymbolTable() const\n   {\n      return symbol_table;\n   }\n\n   /**\n    * \\brief Get the node representing the given symbol.\n    *\n    * If the symbol does not exists yet, then a temporary node with\n    * operator NIL is created. If this node is used as operator\n    * to another node, then this usage is tracked. Later\n    * when the symbol s is added to the expression graph\n    * all usages of the temporary node will get substituted.\n    *\n    * \\param s the symbol\n    * \\return a node representing the symbol\n    */\n   Node *getNode( const Symbol &s );\n\n   /**\n    * \\brief Get the node representing the given operator applied to\n    * the given child node\n    *\n    * \\param op the operator\n    * \\param child the child node\n    * \\return the node\n    */\n   Node *getNode( Operator op, Node *child );\n\n   /**\n    * \\brief Get the node representing the given operator applied to\n    * the given child nodes.\n    *\n    * \\param op the operator\n    * \\param child1 the first child node\n    * \\param child2 the second child node\n    * \\return the node\n    */\n   Node *getNode( Operator op, Node *child1, Node *child2 );\n\n   /**\n    * \\brief Get the node representing the given operator applied to\n    * the given child nodes.\n    *\n    * \\param op the operator\n    * \\param child1 the first child node\n    * \\param child2 the second child node\n    * \\param child3 the third child node\n    * \\return the node\n    */\n   Node *getNode( Operator op, Node *child1, Node *child2, Node *child3 );\n\n   /**\n    * \\brief Get the node representing the given constant value.\n    *\n    * \\param val the constant value\n    * \\return the node\n    */\n   Node *getNode( double val );\n\n   /**\n    * \\brief Get the node representing the current time.\n    *\n    * \\return the node\n    */\n   Node *getTimeNode();\n\n   /**\n    * \\brief Wrap a lookup table as a node.\n    *\n    * \\return the node containing the lookup table.\n    */\n   Node *getNode( LookupTable *table );\n\n   /**\n    * Create an empty lookup table.\n    */\n   LookupTable *createLookupTable();\n\n   /**\n    * Create an undefined node for temporary usage.\n    */\n   Node *createTmpNode();\n\n   /**\n    * Substitute temporary node by another node\n    * in every usage of the temporary node.\n    */\n   void substituteTmpNode( Node *tmp, Node *subst );\n\n   /**\n    * Analyze the expression graph to identify useful information about nodes.\n    * Identifies if nodes are dynamic (states and values derived from states),\n    * static (values depending on the current time and constants only) or constant nodes.\n    * Also identifies if nodes have a constant intitial value or if their initial value\n    * depends on a control.\n    * Additionally a topological ordering on the nodes is computed and stored in node->level.\n    * In the ordering states get a level depending on their initial value.\n    *\n    * If there are errors in stored in this expression graph so far a sdo::parse_error will\n    * be thrown in this function.\n    */\n   void analyze();\n\n   /**\n    * If set to true, each constant will get a unique node.\n    * Useful if it is not desired that the symbols defined\n    * by A=1 and B=1 in a mdl file cannot be distinguished.\n    */\n   void useUniqueConstants( bool val );\n\n   /**\n    * A range of two iterators represented as an iterable\n    * object.\n    */\n   template<typename ITER>\n   class IteratorRange\n   {\n   public:\n      IteratorRange( std::pair<ITER, ITER> p ) : begin_( p.first ), end_( p.second ) {}\n\n      ITER begin() const\n      {\n         return begin_;\n      }\n\n      ITER end() const\n      {\n         return end_;\n      }\n\n      bool empty() const\n      {\n         return begin_ == end_;\n      }\n\n      std::size_t size() const\n      {\n         return end_ - begin_;\n      }\n\n   private:\n      ITER begin_;\n      ITER end_;\n   };\n\n   /**\n    * Get an iterator range containing all symbols for the given node.\n    *\n    * \\param node the node for which to retireve the symbols\n    *\n    * \\return the iterator range that contains the symbols.\n    */\n   IteratorRange<std::unordered_multimap<Node *, Symbol>::iterator> getSymbol( Node *const node )\n   {\n      return IteratorRange<std::unordered_multimap<Node *, Symbol>::iterator>( node_table.equal_range( node ) );\n   }\n\n   /**\n    * Get an iterator range containing all comments for the given symbol.\n    *\n    * \\param s the symbol\n    *\n    * \\return the iterator range that contains the comments.\n    */\n   IteratorRange<std::unordered_multimap<Symbol, Symbol>::iterator> getComments( const Symbol &s )\n   {\n      return IteratorRange<std::unordered_multimap<Symbol, Symbol>::iterator>( comments.equal_range( s ) );\n   }\n\n   /**\n    * Add comments in given container to the comments of the given symbols.\n    *\n    * \\param s the symbol\n    * \\param c the container which should have begin and end methods to be iterable.\n    */\n   template<typename Iterable>\n   void addComments( const Symbol &s, Iterable c )\n   {\n      for( auto & comment : c )\n         comments.emplace( s, comment );\n   }\n\nprivate:\n   std::unordered_map<Symbol, Node *>                                   symbol_table;\n   std::unordered_multimap<Node *, Symbol>                              node_table;\n   std::unordered_multimap<Symbol, Symbol>                             comments;\n   std::unordered_set<Node *, structural_node_hash, structural_node_eq> nodes_;\n   boost::object_pool<Node>                                            node_pool_;\n   boost::object_pool<LookupTable>                                     lookup_pool_;\n   std::unordered_multimap<Node *, Node **>                              temp_node_usages_;\n   bool unique_constants = false;\n};\n\n\n}\n\n#endif\n", "meta": {"hexsha": "12087887302b2963608e6b29240272681e89d3d0", "size": 13820, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdo/ExpressionGraph.hpp", "max_stars_repo_name": "rgottwald/libsdo", "max_stars_repo_head_hexsha": "6937784258672e3a2d4252107242796b95f026aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdo/ExpressionGraph.hpp", "max_issues_repo_name": "rgottwald/libsdo", "max_issues_repo_head_hexsha": "6937784258672e3a2d4252107242796b95f026aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdo/ExpressionGraph.hpp", "max_forks_repo_name": "rgottwald/libsdo", "max_forks_repo_head_hexsha": "6937784258672e3a2d4252107242796b95f026aa", "max_forks_repo_licenses": ["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.1730418944, "max_line_length": 112, "alphanum_fraction": 0.5519536903, "num_tokens": 3233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5812758792369858}}
{"text": "//\n//  complex_conjugate.cpp\n//  BGV-Adder\n//\n//  Created by Andris on 28/10/2020.\n//  Copyright \u00a9 2020 RUG. All rights reserved.\n//\n\n#include \"complex_conjugate.hpp\"\n#include <helib/FHE.h>\n#include <NTL/ZZX.h>\n#include <NTL/tools.h>\n\nusing helib::Ctxt;\n\nstd::array<long, ARRAY_SIZE> complex_conjugate(int16_t a, int16_t b) {\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 a_ciphertext = Ctxt(publicKey);\n    Ctxt b_ciphertext = Ctxt(publicKey);\n\n    \n    // Plaintext must be encrypted as a polynomial using zzx api.\n    publicKey.Encrypt(a_ciphertext, NTL::ZZX(a));\n    publicKey.Encrypt(b_ciphertext, NTL::ZZX(b));\n\n    \n    // Apply operations on the ciphertexts.\n    \n    b_ciphertext *= -1;\n    \n    std::array<Ctxt, ARRAY_SIZE> cipher_results = {a_ciphertext, b_ciphertext};\n    \n    // Decrypt the results using secret key and convert back from\n    // polynomial representation to numeric.\n    std::array<long, ARRAY_SIZE> return_values = {0,0};\n    std::array<NTL::ZZX, ARRAY_SIZE> plaintext_results;\n    for (size_t i = 0; i < 2; ++i) {\n        NTL::ZZX zzx;\n        secretKey.Decrypt(zzx, cipher_results[i]);\n        conv(return_values[i], zzx[0]);\n        // Compensate for negative numbers by checking if it's larger than p/2,\n        // In such case it wrapped around due to negative numbers\n        if (return_values[i] > p / 2) {\n            return_values[i] += (-1 * p);\n        }\n    }\n    return return_values;\n}\n", "meta": {"hexsha": "66dd9bb2726acda173ae9a8b83cd7d8f070bd20d", "size": 2448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGV-Adder/Algorithms/ComplexConjugate/complex_conjugate.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/ComplexConjugate/complex_conjugate.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/ComplexConjugate/complex_conjugate.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": 32.2105263158, "max_line_length": 79, "alphanum_fraction": 0.6405228758, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5812758681215728}}
{"text": "\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Mesh_triangulation_3.h>\n#include <CGAL/Mesh_complex_3_in_triangulation_3.h>\n#include <CGAL/Mesh_criteria_3.h>\n\n#include <CGAL/Labeled_mesh_domain_3.h>\n#include <CGAL/make_mesh_3.h>\n#include <CGAL/Image_3.h>\n#include <cstdlib>\n#include <iostream>\n\n#include <boost/container/flat_set.hpp>\n\ntypedef float Image_word_type;\n\n// Domain\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Labeled_mesh_domain_3<K> Mesh_domain;\n\n// Triangulation\ntypedef CGAL::Mesh_triangulation_3<Mesh_domain>::type Tr;\ntypedef CGAL::Mesh_complex_3_in_triangulation_3<Tr> C3t3;\n\n// Criteria\ntypedef CGAL::Mesh_criteria_3<Tr> Mesh_criteria;\n\n// To avoid verbose function and named parameters call\nusing namespace CGAL::parameters;\n\ntemplate <typename Set>\nstruct Image_to_multiple_iso_level_sets {\n  const Set& set;\n  Image_to_multiple_iso_level_sets(const Set& set) : set(set) {}\n\n  int operator()(double v) const {\n       return int(std::distance(set.begin(),\n                                set.lower_bound(float(v))));\n  }\n};\n\nint main(int argc, char*argv[])\n{\n  const std::string fname = (argc>1)?argv[1]:CGAL::data_file_path(\"images/skull_2.9.inr\");\n  // Load image\n  CGAL::Image_3 image;\n  if(!image.read(fname)){\n    std::cerr << \"Error: Cannot read file \" <<  fname << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  typedef boost::container::flat_set<float> Flat_set;\n  Flat_set iso_values;\n  if(argc < 2) {\n    iso_values.insert(1.5f);\n    iso_values.insert(2.9f);\n    iso_values.insert(3.5f);\n  } else {\n    for(int i = 2; i < argc; ++i) {\n      iso_values.insert(static_cast<float>(std::atof(argv[i])));\n    }\n  }\n\n  // Domain\n  namespace p = CGAL::parameters;\n  Mesh_domain domain =\n    Mesh_domain::create_gray_image_mesh_domain\n    (p::image = image,\n     p::image_values_to_subdomain_indices =\n       Image_to_multiple_iso_level_sets<Flat_set>(iso_values),\n     p::value_outside = 0.f\n     );\n\n  // Mesh criteria\n  Mesh_criteria criteria(facet_angle=30, facet_size=6, facet_distance=2,\n                         cell_radius_edge_ratio=3, cell_size=8);\n\n  // Meshing\n  C3t3 c3t3 = CGAL::make_mesh_3<C3t3>(domain, criteria);\n\n  // Output\n  std::ofstream medit_file(\"out.mesh\");\n  c3t3.output_to_medit(medit_file);\n\n  return 0;\n}\n", "meta": {"hexsha": "3ead928edf78d8d733b33c7fba521ac330db9310", "size": 2319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Mesh_3/examples/Mesh_3/mesh_3D_gray_image_multiple_values.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": "Mesh_3/examples/Mesh_3/mesh_3D_gray_image_multiple_values.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": "Mesh_3/examples/Mesh_3/mesh_3D_gray_image_multiple_values.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": 26.3522727273, "max_line_length": 90, "alphanum_fraction": 0.7076326003, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5812758642541209}}
{"text": "// NormalGenerator.hpp\r\n\r\n#ifndef NormalGenerator_HPP\r\n#define NormalGenerator_HPP\r\n\r\n// Import Boost library\r\n\r\n#include <boost/random.hpp>\r\n#include <boost/random/mersenne_twister.hpp>\r\n#include <boost/random/normal_distribution.hpp>\r\n#include <boost/random/variate_generator.hpp>\r\n\r\nclass NormalGenerator\r\n{\r\n\r\npublic:\r\n\r\n\t// Empty at the moment\r\n\tvirtual double getNormal() const = 0;\r\n};\r\n\r\n\r\nclass BoostNormal : public NormalGenerator\r\n{\r\nprivate:\r\n\r\n\tboost::lagged_fibonacci607 rng;\r\n\tboost::normal_distribution<> nor;\r\n\r\n\tboost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> >* myRandom;\r\n\r\n\r\npublic:\r\n\tBoostNormal();\t// NB no uniform parameters\r\n\r\n\t// Implement (variant) hook function\r\n\tdouble getNormal() const;\r\n\r\n\t~BoostNormal();\r\n};\r\n\r\n\r\n#endif\r\n", "meta": {"hexsha": "a1aeb6cdfd0457ebb3d2f314fe2252b277485194", "size": 790, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NormalGenerator.hpp", "max_stars_repo_name": "icezerowjj/Monte-Carlo-Simulation", "max_stars_repo_head_hexsha": "a9cfb6cc0fcdd274138590f2845b758d8bc3c9e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-27T15:17:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-27T15:17:59.000Z", "max_issues_repo_path": "NormalGenerator.hpp", "max_issues_repo_name": "icezerowjj/Monte-Carlo-Option-Pricing", "max_issues_repo_head_hexsha": "a9cfb6cc0fcdd274138590f2845b758d8bc3c9e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NormalGenerator.hpp", "max_forks_repo_name": "icezerowjj/Monte-Carlo-Option-Pricing", "max_forks_repo_head_hexsha": "a9cfb6cc0fcdd274138590f2845b758d8bc3c9e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-11T06:14:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T04:20:04.000Z", "avg_line_length": 17.9545454545, "max_line_length": 97, "alphanum_fraction": 0.7215189873, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853086009863259, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5812652927388062}}
{"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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n#ifndef ITL_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": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <limits>\n\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"tudat/math/quadrature/gaussianQuadrature.h\"\n#include \"tudat/math/basic/mathematicalConstants.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n\n// Functions to be tested\n\ndouble sinFunction( const double x )\n{\n    return std::sin( x );\n}\n\ndouble expFunction( const double x )\n{\n    return std::exp( x );\n}\n\ndouble polyFunction( const double x )\n{\n    return std::pow( x, 9 ) + 2 * std::pow( x, 7 ) - std::pow( x, 4 ) + 8 * std::pow( x, 2 ) - 11;\n}\n\n\n//! Even-order derivatives for error assessment\ndouble minSinFunction( const double x )\n{\n    return -std::sin( x );\n}\n\nstd::function< double( const double ) > dSinFunction( unsigned int n )\n{\n    if ( n % 2 == 0 )\n    {\n        if ( n % 4 == 0 )\n        {\n            return sinFunction;\n        }\n        else\n        {\n            return minSinFunction;\n        }\n    }\n    else\n    {\n        throw std::runtime_error( \"Unknown derivative\" );\n    }\n}\n\nstd::function< double( const double ) > dExpFunction( unsigned int n )\n{\n    return expFunction;\n}\n\ndouble d4PolyFunction( const double x )\n{\n    return 24 * ( 126 * std::pow( x, 5 ) + 70 * std::pow( x, 3 ) - 1 );\n}\n\ndouble d6PolyFunction( const double x )\n{\n    return 10080 * ( 6 * std::pow( x, 3 ) + x );\n}\n\ndouble d8PolyFunction( const double x )\n{\n    return 362800 * x;\n}\n\nstd::function< double( const double ) > dPolyFunction( unsigned int n )\n{\n    switch( n )\n    {\n    case 4: return d4PolyFunction;\n    case 6: return d6PolyFunction;\n    case 8: return d8PolyFunction;\n    default: throw std::runtime_error( \"Unknown derivative\" );\n    }\n}\n\n\n// Factorial\nunsigned int factorial( const unsigned int x )\n{\n    if ( x > 0 )\n    {\n        return x * factorial( x - 1 );\n    }\n    else\n    {\n        return 1;\n    }\n}\n\n// Error function for Gaussian quadrature [ from https://en.wikipedia.org/wiki/Gaussian_quadrature#Error_estimates ]\ndouble gaussianQuadratureError( const unsigned int n, std::function< double( const double ) > derivative2nth,\n                                const double abscissa, const double lowerLimit, const double upperLimit )\n{\n    return std::pow( upperLimit - lowerLimit, 2 * n + 1 ) * std::pow( factorial( n ), 4 )\n            / double( ( 2 * n + 1 ) * std::pow( factorial( 2 * n ), 3 ) ) * derivative2nth( abscissa );\n}\n\n// Check error is within bounds and decreasing for increasing number of nodes.\n// Number of nodes ranges from minOrder to maxOrder (both included).\n// It must hold that lowerLimit \u2264 abscissa \u2264 upperLimit.\n// The derivative is a function taking as input an `int n` (the nth derivative) that returns a function taking as input\n// a `double x` (the absicssa at which it will be evaluated).\nvoid checkErrorWithinBounds( const unsigned int minOrder, const unsigned int maxOrder,\n                             std::function< double( const double ) > function,\n                             const double lowerLimit, const double upperLimit,\n                             std::function< std::function< double( const double ) >( const unsigned int ) > derivative,\n                             const double abscissa, const double expectedSolution )\n{\n    double obtainedError = TUDAT_NAN;\n    double errorBound = TUDAT_NAN;\n    for ( unsigned int n = minOrder; n <= maxOrder; n++ )\n    {\n        const double previousObtainedError = obtainedError;\n        numerical_quadrature::GaussianQuadrature< double, double > integrator( function, lowerLimit, upperLimit, n );\n        obtainedError = std::fabs( expectedSolution - integrator.getQuadrature() );\n        errorBound = std::fabs( gaussianQuadratureError( n, derivative( 2 * n ), abscissa, lowerLimit, upperLimit ) );\n        BOOST_CHECK( obtainedError < errorBound );\n        if ( n > minOrder )\n        {\n            BOOST_CHECK( obtainedError < previousObtainedError );\n        }\n    }\n}\n\n\nBOOST_AUTO_TEST_SUITE( test_gaussian_quadrature )\n\n//! Test if quadrature is computed correctly (sine function with 1E4 data points).\nBOOST_AUTO_TEST_CASE( testIntegralSineFunction )\n{\n    using namespace mathematical_constants;\n    using namespace numerical_quadrature;\n\n    const unsigned int order = 8;\n    const double lowerLimit = 0.0;\n    const double upperLimit = PI;\n    GaussianQuadrature< double, double > integrator( sinFunction, lowerLimit, upperLimit, order );\n    double computedSolution = integrator.getQuadrature();\n\n    // Expected solution from Wolfram Alpha\n    double expectedSolution = 2.0;\n\n    // Check if computed solution matches expected value for a high order (8).\n    BOOST_CHECK_CLOSE_FRACTION( computedSolution, expectedSolution, 1E-10 );\n\n\n    /// Check that it is a Gaussian quadrature and not just any quadrature\n\n    // Check if error is within bounds for order 2...4\n    checkErrorWithinBounds( 2, 4, sinFunction, lowerLimit, upperLimit, dSinFunction, PI / 2, expectedSolution );\n\n    // Set to order 2\n    integrator.reset( sinFunction, lowerLimit, upperLimit, 2 );\n    computedSolution = integrator.getQuadrature();\n\n    // Expected solution from http://keisan.casio.com/exec/system/1330940731\n    expectedSolution = 1.9358195746511370184019497173109914411780661179299;\n\n    // Check if computed solution matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( computedSolution, expectedSolution, 1E-12 );\n}\n\n\n//! Test if quadrature is computed correctly (exponential function).\nBOOST_AUTO_TEST_CASE( testIntegralExpFunction )\n{\n    using namespace mathematical_constants;\n    using namespace numerical_quadrature;\n\n    const unsigned int order = 7;\n    const double lowerLimit = -2.0;\n    const double upperLimit = 2.0;\n    GaussianQuadrature< double, double > integrator( expFunction, lowerLimit, upperLimit, order );\n    double computedSolution = integrator.getQuadrature();\n\n    // Expected solution from Wolfram Alpha\n    double expectedSolution = 7.25372081569404;\n\n    // Check if computed solution matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( computedSolution, expectedSolution, 1E-10 );\n\n\n    /// Check that it is a Gaussian quadrature and not just any quadrature\n\n    // Check if error is within bounds for order 2...6\n    checkErrorWithinBounds( 2, 6, expFunction, lowerLimit, upperLimit, dExpFunction, 1.0, expectedSolution );\n\n    // Set to order 2\n    integrator.reset( expFunction, lowerLimit, upperLimit, 2 );\n    computedSolution = integrator.getQuadrature();\n\n    // Expected solution from http://keisan.casio.com/exec/system/1330940731\n    expectedSolution = 6.9764499206151121988504219845072175547665355367817;\n\n    // Check if computed solution matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( computedSolution, expectedSolution, 1E-12 );\n}\n\n\n//! Test if quadrature is computed correctly (polynomial function).\nBOOST_AUTO_TEST_CASE( testIntegralPolyFunction )\n{\n    using namespace mathematical_constants;\n    using namespace numerical_quadrature;\n\n    // A polynomial of order 2*steps - 1 is computed exactly. Order of tested polynomial is 9, thus steps = 5.\n    const unsigned int order = 5;\n    const double lowerLimit = -2.0;\n    const double upperLimit = 4.0;\n    GaussianQuadrature< double, double > integrator( polyFunction, lowerLimit, upperLimit, order );\n    double computedSolution = integrator.getQuadrature();\n\n    // Expected solution from Wolfram Alpha\n    double expectedSolution = 120990;\n\n    // Check if computed solution matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( computedSolution, expectedSolution, 1E-12 );\n\n    // Check that this isn't the case for 4 nodes\n    integrator.reset( polyFunction, lowerLimit, upperLimit, 4 );\n    computedSolution = integrator.getQuadrature();\n    BOOST_CHECK( std::fabs( computedSolution - expectedSolution) > 1 );\n\n\n    /// Check that it is a Gaussian quadrature and not just any quadrature\n\n    // Check if error is within bounds for order 2...4\n    checkErrorWithinBounds( 2, 4, polyFunction, lowerLimit, upperLimit, dPolyFunction, 2.0, expectedSolution );\n\n    // Set to order 2\n    integrator.reset( polyFunction, lowerLimit, upperLimit, 2 );\n    computedSolution = integrator.getQuadrature();\n\n    // Expected solution from http://keisan.casio.com/exec/system/1330940731\n    expectedSolution = 32214;\n\n    // Check if computed solution matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( computedSolution, expectedSolution, 1E-12 );\n}\n\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "88abf0f40f02ddada2261076581300ccdcb4e0d7", "size": 8963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/math/quadrature/unitTestGaussianQuadrature.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/math/quadrature/unitTestGaussianQuadrature.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/math/quadrature/unitTestGaussianQuadrature.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": 32.9522058824, "max_line_length": 119, "alphanum_fraction": 0.6934062256, "num_tokens": 2245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6992544085240402, "lm_q1q2_score": 0.5811804344796525}}
{"text": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2014 Benoit Dequidt <benoit.dequidt@gmail.com>\r\n//\r\n// Distributed under the Boost Software License, Version 1.0\r\n// See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt\r\n//\r\n// See http://boostorg.github.com/compute for more information.\r\n//---------------------------------------------------------------------------//\r\n\r\n#include <iostream>\r\n#include <cstdlib>\r\n\r\n#include <boost/compute/core.hpp>\r\n#include <boost/compute/algorithm/copy.hpp>\r\n#include <boost/compute/algorithm/inclusive_scan.hpp>\r\n#include <boost/compute/container/vector.hpp>\r\n#include <boost/compute/type_traits/type_name.hpp>\r\n#include <boost/compute/utility/source.hpp>\r\n\r\nnamespace compute = boost::compute;\r\n\r\n/// warning precision is not precise due\r\n/// to the float error accumulation when size is large enough\r\n/// for more precision use double\r\n/// or a kahan sum else results can diverge\r\n/// from the CPU implementation\r\ncompute::program make_sma_program(const compute::context& context)\r\n{\r\n    const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(\r\n        __kernel void SMA(__global const float *scannedValues, int size, __global float *output, int wSize)\r\n        {\r\n            const int gid = get_global_id(0);\r\n\r\n            float cumValues = 0.f;\r\n            int endIdx = gid + wSize/2;\r\n            int startIdx = gid -1 - wSize/2;\r\n\r\n            if(endIdx > size -1)\r\n                endIdx = size -1;\r\n\r\n            cumValues += scannedValues[endIdx];\r\n            if(startIdx < 0)\r\n                startIdx = -1;\r\n            else\r\n                cumValues -= scannedValues[startIdx];\r\n\r\n            output[gid] =(float)( cumValues / ( float )(endIdx - startIdx));\r\n        }\r\n   );\r\n\r\n    // create sma program\r\n    return compute::program::build_with_source(source,context);\r\n}\r\n\r\nbool check_results(const std::vector<float>& values, const std::vector<float>& smoothValues, unsigned int wSize)\r\n{\r\n    int size = values.size();\r\n    if(size != (int)smoothValues.size()) return false;\r\n\r\n    int semiWidth = wSize/2;\r\n\r\n    bool res = true;\r\n    for(int idx = 0 ; idx < size ; ++idx)\r\n    {\r\n        int start = (std::max)(idx - semiWidth,0);\r\n        int end = (std::min)(idx + semiWidth,size-1);\r\n        float res = 0;\r\n        for(int j = start ; j <= end ; ++j)\r\n        {\r\n            res+= values[j];\r\n        }\r\n\r\n        res /= float(end - start +1);\r\n\r\n        if(std::abs(res-smoothValues[idx]) > 1e-3)\r\n        {\r\n            std::cout << \"idx = \" << idx << \" -- expected = \" << res << \" -- result = \" << smoothValues[idx] << std::endl;\r\n            res = false;\r\n        }\r\n    }\r\n\r\n    return res;\r\n}\r\n\r\n// generate a uniform law over [0,10]\r\nfloat myRand()\r\n{\r\n    static const double divisor = double(RAND_MAX)+1.;\r\n    return double(rand())/divisor * 10.;\r\n}\r\n\r\nint main()\r\n{\r\n    unsigned int size = 1024;\r\n    // wSize must be odd\r\n    unsigned int wSize = 21;\r\n    // get the default device\r\n    compute::device device = compute::system::default_device();\r\n    // create a context for the device\r\n    compute::context context(device);\r\n    // get the program\r\n    compute::program program = make_sma_program(context);\r\n\r\n    // create vector of random numbers on the host\r\n    std::vector<float> host_vector(size);\r\n    std::vector<float> host_result(size);\r\n    std::generate(host_vector.begin(), host_vector.end(), myRand);\r\n\r\n    compute::vector<float> a(size,context);\r\n    compute::vector<float> b(size,context);\r\n    compute::vector<float> c(size,context);\r\n    compute::command_queue queue(context, device);\r\n\r\n    compute::copy(host_vector.begin(),host_vector.end(),a.begin(),queue);\r\n\r\n    // scan values\r\n    compute::inclusive_scan(a.begin(),a.end(),b.begin(),queue);\r\n    // sma kernel\r\n    compute::kernel kernel(program, \"SMA\");\r\n    kernel.set_arg(0,b.get_buffer());\r\n    kernel.set_arg(1,(int)b.size());\r\n    kernel.set_arg(2,c.get_buffer());\r\n    kernel.set_arg(3,(int)wSize);\r\n\r\n    using compute::uint_;\r\n    uint_ tpb = 128;\r\n    uint_ workSize = size;\r\n    queue.enqueue_1d_range_kernel(kernel,0,workSize,tpb);\r\n\r\n    compute::copy(c.begin(),c.end(),host_result.begin(),queue);\r\n\r\n    bool res = check_results(host_vector,host_result,wSize);\r\n    std::string status = res ? \"results are equivalent\" : \"GPU results differs from CPU one's\";\r\n    std::cout << status << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "f6b20623b32194d0bbf274684a8ca85e981e6f53", "size": 4475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/example/simple_moving_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": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/example/simple_moving_average.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/example/simple_moving_average.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 31.9642857143, "max_line_length": 123, "alphanum_fraction": 0.589273743, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430311279742, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5811804286302694}}
{"text": "/*\n * Author: Patrick Schmidt\n */\n\n#include \"Helpers.hh\"\n\n#include <Eigen/SparseQR>\n\nnamespace HomologyInference\n{\n\nint rank(const SparseMatrix& _M)\n{\n    ISM_INFO(\"Starting QR factorization\");\n\n    Eigen::SparseQR<SparseMatrix, Eigen::COLAMDOrdering<int>> QR;\n    QR.compute(_M);\n\n    ISM_INFO(\"Finished QR factorization\");\n\n    const int r = QR.rank();\n\n    ISM_ASSERT_EQ(_M.rows(), _M.cols());\n    ISM_DEBUG_OUT(\"Matrix has rank n - \" << _M.rows() - r);\n\n    return r;\n}\n\ndouble total_area(const TriMesh &_mesh)\n{\n    double result = 0.0;\n    for (auto fh : _mesh.faces())\n        result += _mesh.calc_face_area(fh);\n\n    return result;\n}\n\nstd::pair<Vec3d, Vec3d> bounding_box(\n        const TriMesh& _mesh)\n{\n    Vec3d pmin(+INF_DOUBLE, +INF_DOUBLE, +INF_DOUBLE);\n    Vec3d pmax(-INF_DOUBLE, -INF_DOUBLE, -INF_DOUBLE);\n    for (const auto& vh : _mesh.vertices())\n    {\n        const Vec3d& p = _mesh.point(vh);\n        pmin = pmin.cwiseMin(p);\n        pmax = pmax.cwiseMax(p);\n    }\n    return {pmin, pmax};\n}\n\ndouble bounding_box_diagonal(\n        const TriMesh& _mesh)\n{\n    const auto [pmin, pmax] = bounding_box(_mesh);\n    return (pmax - pmin).norm();\n}\n\nColor log_color(\n        const double _val,\n        const double _min,\n        const double _max,\n        const Color& _min_color,\n        const Color& _max_color)\n{\n    ISM_ASSERT_G(_val, 0.0);\n\n    double lambda = (std::log(_val) - std::log(_min)) / (std::log(_max) - std::log(_min));\n    lambda = std::min(std::max(lambda, 0.0), 1.0);\n\n    return (1.0 - lambda) * _min_color + lambda * _max_color;\n}\n\nbool incident(const TriMesh& _mesh, const VH _vh, const FH _fh)\n{\n    ISM_ASSERT(_mesh.is_valid_handle(_fh));\n    for (const auto& vh : _mesh.fv_range(_fh))\n        if (vh == _vh)\n            return true;\n    return false;\n}\n\nVH closest_vertex(\n        const TriMesh& _mesh,\n        const Vec3d& _p)\n{\n    double closest_dist = INF_DOUBLE;\n    VH closest_vh;\n    for (auto v : _mesh.vertices())\n    {\n        const double dist = (_mesh.point(v) - _p).norm();\n        if (dist < closest_dist)\n        {\n            closest_dist = dist;\n            closest_vh = v;\n        }\n    }\n\n    return closest_vh;\n}\n\n}\n", "meta": {"hexsha": "a079c0ce6646f68595bf9a8ff99789cf2e748110", "size": 2176, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/HomologyInference/Utils/Helpers.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/Utils/Helpers.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/Utils/Helpers.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": 21.1262135922, "max_line_length": 90, "alphanum_fraction": 0.6020220588, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5810603801147595}}
{"text": "//  Copyright John Maddock 2006.\n//  Copyright Paul A. Bristow 2007.\n\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (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/minima.hpp>\n#include <boost/test/included/test_exec_monitor.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\ntemplate <class T>\nstruct poly_test\n{\n   // minima is at (3,4):\n   T operator()(const T& v)\n   {\n      T a = v - 3;\n      return 3 * a * a + 4;\n   }\n};\n\ntemplate <class T>\nvoid test_minima(T, const char* /* name */)\n{\n   std::pair<T, T> m = boost::math::tools::brent_find_minima(poly_test<T>(), T(-10), T(10), 50);\n   BOOST_CHECK_CLOSE(m.first, T(3), T(0.001));\n   BOOST_CHECK_CLOSE(m.second, T(4), T(0.001));\n\n   T (*fp)(T);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   fp = boost::math::lgamma<T>;\n#else\n   fp = boost::math::lgamma;\n#endif\n\n   m = boost::math::tools::brent_find_minima(fp, T(0.5), T(10), 50);\n   BOOST_CHECK_CLOSE(m.first, T(1.461632), T(0.1));\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   fp = boost::math::tgamma<T>;\n#else\n   fp = boost::math::tgamma;\n#endif\n   m = boost::math::tools::brent_find_minima(fp, T(0.5), T(10), 50);\n   BOOST_CHECK_CLOSE(m.first, T(1.461632), T(0.1));\n}\n\nint test_main(int, char* [])\n{\n   test_minima(0.1f, \"float\");\n   test_minima(0.1, \"double\");\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_minima(0.1L, \"long double\");\n#endif\n   return 0;\n}\n\n\n", "meta": {"hexsha": "8d2b4a50b4d0d9b8470d9a55fec3f93beca8be09", "size": 1586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_minima.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/math/test/test_minima.cpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/test/test_minima.cpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4333333333, "max_line_length": 96, "alphanum_fraction": 0.6715006305, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5810603684145458}}
{"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    // \u653e\u7f6e\u6fc0\u5149\u96f7\u8fbe\u7684\u65f6\u95f4\u548c\u5339\u914d\u503c t_s s_x s_y s_th\n    vector<vector<double>> s_data;\n    // \u653e\u7f6e\u8f6e\u901f\u8ba1\u7684\u65f6\u95f4\u548c\u5de6\u53f3\u8f6e\u89d2\u901f\u5ea6 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 << \"\u8bf7\u5728\u6709scan_match.txt\u548codom.txt\u7684\u76ee\u5f55\u4e0b\u8fd0\u884c\u6b64\u7a0b\u5e8f\" << endl;\n        return 1;\n    }\n\n    // \u8bfb\u53d6\u6fc0\u5149\u96f7\u8fbe\u7684\u5339\u914d\u503c\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    // \u8bfb\u53d6\u4e24\u4e2a\u8f6e\u5b50\u7684\u89d2\u901f\u5ea6\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    // \u7b2c\u4e00\u6b65\uff1a\u8ba1\u7b97\u4e2d\u95f4\u53d8\u91cfJ_21\u548cJ_22\n    Eigen::MatrixXd A;\n    Eigen::VectorXd b;\n    // \u8bbe\u7f6e\u6570\u636e\u957f\u5ea6\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        // \u6fc0\u5149\u7684\u5339\u914d\u4fe1\u606f\n        const double &s_t = s_data[id_s][0];\n        const double &s_th = s_data[id_s][3];\n        // \u91cc\u7a0b\u8ba1\u4fe1\u606f\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        // \u57282\u5e27\u6fc0\u5149\u5339\u914d\u65f6\u95f4\u5185\u8fdb\u884c\u91cc\u7a0b\u8ba1\u89d2\u5ea6\u79ef\u5206\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            // \u586b\u5145A, b\u77e9\u9635\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    // \u8fdb\u884c\u6700\u5c0f\u4e8c\u4e58\u6c42\u89e3\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    // \u7b2c\u4e8c\u6b65\uff0c\u6c42\u89e3\u8f6e\u95f4\u8dddb\n    Eigen::VectorXd C;\n    Eigen::VectorXd S;\n    // \u8bbe\u7f6e\u6570\u636e\u957f\u5ea6\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        // \u6fc0\u5149\u7684\u5339\u914d\u4fe1\u606f\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        // \u91cc\u7a0b\u8ba1\u4fe1\u606f\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        // \u57282\u5e27\u6fc0\u5149\u5339\u914d\u65f6\u95f4\u5185\u8fdb\u884c\u91cc\u7a0b\u8ba1\u4f4d\u7f6e\u79ef\u5206\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            // \u586b\u5145C, S\u77e9\u9635\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    // \u8fdb\u884c\u6700\u5c0f\u4e8c\u4e58\u6c42\u89e3\uff0c\u8ba1\u7b97b, 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 << \"\u53c2\u8003\u7b54\u6848\uff1a\u8f6e\u95f4\u8dddb\u4e3a0.6m\u5de6\u53f3\uff0c\u4e24\u8f6e\u534a\u5f84\u4e3a0.1m\u5de6\u53f3\" << 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": "#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, 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\n\nusing namespace std;\n\nint dijkstra_dist(const weighted_graph &G, int s) {\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  int value = 0;\n  for (int i = 0; i < n; ++i) {\n    if (dist_map[i] != 2147483647)\n    value = max(value, dist_map[i]);\n  }\n\n  return value;\n}\n\nvoid solve() {\n  int n; cin >> n;\n  int m; cin >> m;\n  \n  weighted_graph G(4);\n  weight_map weights = boost::get(boost::edge_weight, G);\n\n  int u, v, w;\n  for (int i = 0; i < m; ++i) {\n    cin >> u;\n    cin >> v;\n    cin >> w;\n    boost::add_edge(u, v, w, G); \n  } \n  \n  vector<edge_desc> mst;    // vector to store MST edges (not a property map!)\n\n  boost::kruskal_minimum_spanning_tree(G, back_inserter(mst));\n\n  int weight = 0;\n  for (vector<edge_desc>::iterator it = mst.begin(); it != mst.end(); ++it) {\n    weight += boost::get(boost::edge_weight_t(), G, *it);\n  }\n\n  cout << weight << \" \" << dijkstra_dist(G, 0) << endl;\n}\n\nint main() {\n  int t; cin >> t;\n  for (int i = 0; i < t; ++i) {\n    solve();\n  }\n}", "meta": {"hexsha": "ae49be2bf4bbc491bb2933e519e6401083eea9cd", "size": 1759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/first_steps.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/first_steps.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/first_steps.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 26.6515151515, "max_line_length": 155, "alphanum_fraction": 0.6588971006, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.5810059543285443}}
{"text": "//\n//  quadratic_polynomial.cpp\n//  BGV-Adder\n//\n//  Created by Andris on 27/10/2020.\n//  Copyright \u00a9 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) //\u9884\u6d4b\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 \u4e0e ODOM\u4e0eIMU\u52a0\u6743\u5e73\u5747 \u540e\u7684\u7ed3\u679c\u8fdb\u884c\u518d\u6b21\u878d\u5408\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()  //\u53ea\u662f\u8fdb\u884c\u4f4d\u7f6e\u878d\u5408\n{\n    float odom_x, odom_y, odom_theta;\n    float imu_x, imu_y, imu_z, imu_theta;\n    float Roll; //\u7ffb\u6eda\u89d2\n    float Pitch; //\u4fef\u4ef0\u89d2\n    float Yaw; //\u504f\u822a\u89d2\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// Created by Alex Beccaro on 27/12/18.\n//\n\n#include \"problem111.hpp\"\n#include <primes.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing primes::is_prime;\nusing generics::from_digits;\nusing generics::combinations_repetition;\nusing std::vector;\nusing std::string;\n\nusing boost::multiprecision::uint128_t;\n\nnamespace problems {\n    uint64_t problem111::primes_sum_from_bitmask(const std::string bitmask, uint32_t digit) {\n        uint64_t n = bitmask.size(), m = 0;\n        vector<uint32_t> digits(n);\n\n        for (uint32_t i = 0; i < n; ++i) {\n            if (bitmask[i]) {\n                digits[i] = digit;\n                m++;\n            } else\n                digits[i] = digit + 1;\n        }\n\n        vector<uint32_t> all = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n        all.erase(std::remove(all.begin(), all.end(), digit), all.end());\n        auto combs = combinations_repetition(all, n - m);\n\n        uint64_t sum = 0;\n        for (const auto &c : combs) {\n            vector<uint32_t> digs(digits);\n            uint32_t j = 0;\n\n            for (uint32_t i = 0; i < digs.size(); i++)\n                if (digs[i] != digit)\n                    digs[i] = c[j++];\n\n\n            uint64_t num = from_digits<uint64_t>(digs);\n            if (digs[0] != 0 && is_prime<uint128_t>(num))\n                sum += num;\n        }\n\n        return sum;\n    }\n\n    uint64_t problem111::solve(uint32_t n) {\n        uint64_t res = 0;\n\n        for (uint32_t d = 0; d < 10; d++) {\n            uint32_t m = n;\n            uint64_t sum = 0;\n            bool found_m = false;\n\n            while (!found_m) {\n                m--;\n\n                string bitmask(m, 1); // 1 -> d\n                bitmask.resize(n, 0); // 0 -> !d\n\n                do {\n                    uint64_t s = primes_sum_from_bitmask(bitmask, d);\n\n                    if (s > 0) {\n                        found_m = true;\n                        sum += s;\n                    }\n                } while (std::prev_permutation(bitmask.begin(), bitmask.end()));\n            }\n\n            res += sum;\n        }\n\n        return res;\n    }\n}", "meta": {"hexsha": "e8a58a69c359ce8e8dd839d84fb402fe93e3fd34", "size": 2092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/problems/101-150/111/problem111.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "src/problems/101-150/111/problem111.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/101-150/111/problem111.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8271604938, "max_line_length": 93, "alphanum_fraction": 0.4722753346, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5809303257603607}}
{"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     gamma_distribution.cpp\n* \\author   Collin Johnson\n* \n* Implementation of GammaDistribution.\n*/\n\n#include <math/gamma_distribution.h>\n#include <math/roots.h>\n#include <boost/math/special_functions/gamma.hpp>\n#include <algorithm>\n#include <functional>\n#include <iostream>\n\nnamespace vulcan\n{\nnamespace math\n{\n\ndouble gamma_normalizer(double k, double theta) { return 1.0 / (boost::math::tgamma(k) * std::pow(theta, k)); }\n\n\nGammaDistribution::GammaDistribution(double k, double theta)\n: k_(k)\n, theta_(theta)\n{\n    assert(k_ > 0.0);\n    assert(theta_ > 0.0);\n    \n    normalizer_ = gamma_normalizer(k_, theta_);\n}\n\n\ndouble GammaDistribution::sample(void) const\n{\n    std::cout << \"STUB: GammaDistribution::sample(void)\\n\";\n    return 0.0;\n}\n\n\ndouble GammaDistribution::likelihood(double value) const\n{\n    return normalizer_ * std::pow(value, k_-1.0) * std::exp(-value / theta_);\n}\n\n\nbool GammaDistribution::save(std::ostream& out) const\n{\n    out << k_ << ' ' << theta_ << '\\n';\n    return out.good();\n}\n\n\nbool GammaDistribution::load(std::istream& in)\n{\n    in >> k_ >> theta_;\n    \n    assert(k_ > 0.0);\n    assert(theta_ > 0.0);\n    \n    normalizer_ = gamma_normalizer(k_, theta_);\n    \n    return in.good();\n}\n\n}\n}\n", "meta": {"hexsha": "3ccae6cc5c958127e6fcf4f1399fb53e8807c4ac", "size": 1599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/gamma_distribution.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/gamma_distribution.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/gamma_distribution.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": 20.7662337662, "max_line_length": 111, "alphanum_fraction": 0.6823014384, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5809303257603607}}
{"text": "//  (C) Copyright Eric Niebler 2005.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/with_error.hpp>\n#include <boost/accumulators/statistics/error_of_mean.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    accumulator_set<double, stats<tag::error_of<tag::mean(lazy)> > > acc;\n    acc(1.1);\n    acc(1.2);\n    acc(1.3);\n    BOOST_CHECK_CLOSE(0.057735, accumulators::error_of<tag::mean(lazy)>(acc), 1e-4);\n\n    accumulator_set<double, stats<tag::error_of<tag::mean(immediate)> > > acc2;\n    acc2(1.1);\n    acc2(1.2);\n    acc2(1.3);\n    BOOST_CHECK_CLOSE(0.057735, accumulators::error_of<tag::mean(immediate)>(acc2), 1e-4);\n\n    accumulator_set<double, stats<with_error<tag::mean(lazy)> > > acc3;\n    acc3(1.1);\n    acc3(1.2);\n    acc3(1.3);\n    BOOST_CHECK_CLOSE(0.057735, accumulators::error_of<tag::mean(lazy)>(acc3), 1e-4);\n\n    accumulator_set<double, stats<with_error<tag::mean(immediate)> > > acc4;\n    acc4(1.1);\n    acc4(1.2);\n    acc4(1.3);\n    BOOST_CHECK_CLOSE(0.057735, accumulators::error_of<tag::mean(immediate)>(acc4), 1e-4);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"mean test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n", "meta": {"hexsha": "058902396f4a7403ca4e882f3787e0733958611d", "size": 1853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/accumulators/test/error_of.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/accumulators/test/error_of.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/accumulators/test/error_of.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 31.9482758621, "max_line_length": 90, "alphanum_fraction": 0.6443604965, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5808299096658949}}
{"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\u2013Penrose pseudoinverse\n * info: http://eigen.tuxfamily.org/bz/show_bug.cgi?id=257\n * \\param a: Matrix to invert\n * \\param result: Result is written here\n * \\param epsilon: Numerical precision (for example 1e-6)\n * \\return true if successful\n */\ntemplate<typename _Matrix_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": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/functional.hpp>\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/integral.hpp>\nusing namespace boost::hana;\n\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto fact = fix(\n    [](auto fact, auto n) {\n        return eval_if(n == int_<0>,\n            always(int_<1>),\n            [=](auto id) { return n * fact(n - id(int_<1>)); }\n        );\n    }\n);\n\nconstexpr unsigned long long reference(unsigned long long n)\n{ return n == 0 ? 1 : n * reference(n - 1); }\n\ntemplate <int n>\nconstexpr void test() {\n    BOOST_HANA_CONSTANT_ASSERT(fact(ullong<n>) == ullong<reference(n)>);\n    test<n - 1>();\n}\n\ntemplate <> constexpr void test<-1>() { }\n\nint main() {\n    test<15>();\n}\n", "meta": {"hexsha": "d29b58c277b871d154f0cbee35efffa3ee324930", "size": 903, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/functional/fix.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/functional/fix.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/functional/fix.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7631578947, "max_line_length": 78, "alphanum_fraction": 0.6456256921, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5807898781389111}}
{"text": "/*\n * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// includes\n// std\n#include <iostream>\n\n// boost\n#define BOOST_TEST_MODULE MomentumTest\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/unit_test.hpp>\n\n// RBDyn\n#include \"RBDyn/CoM.h\"\n#include \"RBDyn/EulerIntegration.h\"\n#include \"RBDyn/FA.h\"\n#include \"RBDyn/FK.h\"\n#include \"RBDyn/FV.h\"\n#include \"RBDyn/Momentum.h\"\n#include \"RBDyn/MultiBody.h\"\n#include \"RBDyn/MultiBodyConfig.h\"\n\n// arm\n#include \"XYZSarm.h\"\n\nconst double TOL = 1e-6;\n\nBOOST_AUTO_TEST_CASE(centroidalMomentum)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  namespace cst = boost::math::constants;\n\n  rbd::MultiBody mb;\n  rbd::MultiBodyConfig mbc;\n  rbd::MultiBodyGraph mbg;\n  std::tie(mb, mbc, mbg) = makeXYZSarm();\n\n  VectorXd q(mb.nrParams());\n  VectorXd alpha(mb.nrDof());\n  CentroidalMomentumMatrix cmm(mb);\n\n  {\n    rbd::forwardKinematics(mb, mbc);\n    rbd::forwardVelocity(mb, mbc);\n    rbd::paramToVector(mbc.alpha, alpha);\n\n    Vector3d com = rbd::computeCoM(mb, mbc);\n    ForceVecd momentum = rbd::computeCentroidalMomentum(mb, mbc, com);\n    cmm.computeMatrix(mb, mbc, com);\n\n    ForceVecd momentumM(cmm.matrix() * alpha);\n\n    BOOST_CHECK_EQUAL(momentum.vector().norm(), 0.);\n    BOOST_CHECK_EQUAL(momentumM.vector().norm(), 0.);\n  }\n\n  // test J\u00b7q against computeCentroidalMomentum\n  for(int i = 0; i < 100; ++i)\n  {\n    q.setRandom();\n    q.segment<4>(mb.jointPosInParam(mb.jointIndexByName(\"j3\"))).normalize();\n    alpha.setRandom();\n    rbd::vectorToParam(q, mbc.q);\n    rbd::vectorToParam(alpha, mbc.alpha);\n\n    rbd::forwardKinematics(mb, mbc);\n    rbd::forwardVelocity(mb, mbc);\n\n    Vector3d com = rbd::computeCoM(mb, mbc);\n    ForceVecd momentum = rbd::computeCentroidalMomentum(mb, mbc, com);\n    cmm.computeMatrix(mb, mbc, com);\n\n    ForceVecd momentumM(cmm.matrix() * alpha);\n\n    BOOST_CHECK_SMALL((momentum - momentumM).vector().norm(), TOL);\n  }\n\n  // test J\u00b7q against CentroidalMomentumMatrix::momentum\n  for(int i = 0; i < 50; ++i)\n  {\n    std::vector<double> weight(mb.nrBodies());\n    for(std::size_t i = 0; i < weight.size(); ++i)\n    {\n      weight[i] = Eigen::Matrix<double, 1, 1>::Random()(0);\n    }\n\n    CentroidalMomentumMatrix cmmW(mb, weight);\n\n    q.setRandom();\n    q.segment<4>(mb.jointPosInParam(mb.jointIndexByName(\"j3\"))).normalize();\n    alpha.setRandom();\n    rbd::vectorToParam(q, mbc.q);\n    rbd::vectorToParam(alpha, mbc.alpha);\n\n    rbd::forwardKinematics(mb, mbc);\n    rbd::forwardVelocity(mb, mbc);\n\n    Vector3d com = rbd::computeCoM(mb, mbc);\n    ForceVecd momentum = cmmW.momentum(mb, mbc, com);\n    cmmW.computeMatrix(mb, mbc, com);\n\n    ForceVecd momentumM(cmmW.matrix() * alpha);\n\n    BOOST_CHECK_SMALL((momentum - momentumM).vector().norm(), TOL);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(centroidalMomentumDot)\n{\n  using namespace Eigen;\n  using namespace sva;\n  using namespace rbd;\n  namespace cst = boost::math::constants;\n\n  rbd::MultiBody mb;\n  rbd::MultiBodyConfig mbc;\n  rbd::MultiBodyGraph mbg;\n  std::tie(mb, mbc, mbg) = makeXYZSarm();\n\n  CentroidalMomentumMatrix cmm(mb);\n\n  VectorXd q(mb.nrParams());\n  VectorXd alpha(mb.nrDof());\n  VectorXd alphaD(mb.nrDof());\n\n  for(int i = 0; i < 10; ++i)\n  {\n    q.setRandom();\n    q.segment<4>(mb.jointPosInParam(mb.jointIndexByName(\"j3\"))).normalize();\n    alpha.setRandom();\n    alphaD.setRandom();\n    rbd::vectorToParam(q, mbc.q);\n    rbd::vectorToParam(alpha, mbc.alpha);\n    rbd::vectorToParam(alphaD, mbc.alphaD);\n\n    rbd::forwardKinematics(mb, mbc);\n    rbd::forwardVelocity(mb, mbc);\n    rbd::forwardAcceleration(mb, mbc);\n\n    for(int j = 0; j < 10; ++j)\n    {\n      Vector3d oldCom = rbd::computeCoM(mb, mbc);\n      ForceVecd oldMomentum = rbd::computeCentroidalMomentum(mb, mbc, oldCom);\n      Vector3d oldComVel = rbd::computeCoMVelocity(mb, mbc);\n\n      ForceVecd momentumDot = rbd::computeCentroidalMomentumDot(mb, mbc, oldCom, oldComVel);\n      cmm.computeMatrixAndMatrixDot(mb, mbc, oldCom, oldComVel);\n      MatrixXd cmmMatrix = cmm.matrix();\n      MatrixXd cmmMatrixDot = cmm.matrixDot();\n      Vector6d momentumDotCMM = cmmMatrix * alphaD + cmmMatrixDot * alpha;\n\n      // check that the momentum are the same\n      BOOST_CHECK_SMALL((momentumDot.vector() - momentumDotCMM).norm(), TOL);\n\n      // check that each compute compute the same thing\n      cmm.computeMatrix(mb, mbc, oldCom);\n      cmm.computeMatrixDot(mb, mbc, oldCom, oldComVel);\n\n      BOOST_CHECK_SMALL((cmmMatrix - cmm.matrix()).norm(), TOL);\n      BOOST_CHECK_SMALL((cmmMatrixDot - cmm.matrixDot()).norm(), TOL);\n\n      rbd::eulerIntegration(mb, mbc, 1e-8);\n\n      rbd::forwardKinematics(mb, mbc);\n      rbd::forwardVelocity(mb, mbc);\n      rbd::forwardAcceleration(mb, mbc);\n\n      rbd::paramToVector(mbc.alpha, alpha);\n      rbd::paramToVector(mbc.alphaD, alphaD);\n\n      Vector3d newCom = rbd::computeCoM(mb, mbc);\n      ForceVecd newMomentum = rbd::computeCentroidalMomentum(mb, mbc, newCom);\n      ForceVecd momentumDotDiff = (newMomentum - oldMomentum) * (1. / 1e-8);\n\n      BOOST_CHECK_SMALL((momentumDot - momentumDotDiff).vector().norm(), TOL);\n    }\n  }\n\n  // test JDot\u00b7q against CentroidalMomentumMatrix::normalMomentumDot\n  for(int i = 0; i < 50; ++i)\n  {\n    std::vector<double> weight(mb.nrBodies());\n    for(std::size_t i = 0; i < weight.size(); ++i)\n    {\n      weight[i] = Eigen::Matrix<double, 1, 1>::Random()(0);\n    }\n\n    CentroidalMomentumMatrix cmmW(mb, weight);\n\n    q.setRandom();\n    q.segment<4>(mb.jointPosInParam(mb.jointIndexByName(\"j3\"))).normalize();\n    alpha.setRandom();\n    alphaD.setZero();\n    rbd::vectorToParam(q, mbc.q);\n    rbd::vectorToParam(alpha, mbc.alpha);\n    // calcul the normal acceleration since alphaD is zero\n    rbd::vectorToParam(alphaD, mbc.alphaD);\n\n    rbd::forwardKinematics(mb, mbc);\n    rbd::forwardVelocity(mb, mbc);\n    rbd::forwardAcceleration(mb, mbc);\n\n    Vector3d com = rbd::computeCoM(mb, mbc);\n    Vector3d comDot = rbd::computeCoMVelocity(mb, mbc);\n    ForceVecd normalMomentumDot1 = cmmW.normalMomentumDot(mb, mbc, com, comDot);\n    ForceVecd normalMomentumDot2 = cmmW.normalMomentumDot(mb, mbc, com, comDot, mbc.bodyAccB);\n    cmmW.computeMatrixDot(mb, mbc, com, comDot);\n\n    ForceVecd normalMomentumDotM(cmmW.matrixDot() * alpha);\n\n    BOOST_CHECK_SMALL((normalMomentumDot1 - normalMomentumDotM).vector().norm(), TOL);\n    BOOST_CHECK_SMALL((normalMomentumDot2 - normalMomentumDotM).vector().norm(), TOL);\n  }\n}\n", "meta": {"hexsha": "9c372a14d5f456bf888064730d105de04ff565fc", "size": 6445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/MomentumTest.cpp", "max_stars_repo_name": "dbdxnuliba/RBDyn-provides-a-set-of-classes-and-functions-to-model-the-dynamics-of-rigid-body-systems.", "max_stars_repo_head_hexsha": "c3f498f8330e06be7dae55570d00931702b920d6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/MomentumTest.cpp", "max_issues_repo_name": "dbdxnuliba/RBDyn-provides-a-set-of-classes-and-functions-to-model-the-dynamics-of-rigid-body-systems.", "max_issues_repo_head_hexsha": "c3f498f8330e06be7dae55570d00931702b920d6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/MomentumTest.cpp", "max_forks_repo_name": "dbdxnuliba/RBDyn-provides-a-set-of-classes-and-functions-to-model-the-dynamics-of-rigid-body-systems.", "max_forks_repo_head_hexsha": "c3f498f8330e06be7dae55570d00931702b920d6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5642201835, "max_line_length": 94, "alphanum_fraction": 0.6741660202, "num_tokens": 2011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5807898772889324}}
{"text": "#include <stan/math/prim.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <limits>\n\nusing Eigen::VectorXd;\nusing stan::math::softmax;\n\nTEST(ProbDistributionsCategoricalLogit, error_check) {\n  using stan::math::categorical_logit_rng;\n  boost::random::mt19937 rng;\n\n  VectorXd beta(3);\n\n  beta << 1.0, 10.0, -10.0;\n  EXPECT_NO_THROW(categorical_logit_rng(beta, rng));\n\n  beta << -1e3, 1.1e3, 1e5;\n  EXPECT_NO_THROW(categorical_logit_rng(beta, rng));\n\n  beta(1) = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_THROW(categorical_logit_rng(beta, rng), std::domain_error);\n\n  beta(1) = std::numeric_limits<double>::infinity();\n  EXPECT_THROW(categorical_logit_rng(beta, rng), std::domain_error);\n}\n\nTEST(ProbDistributionsCategoricalLogit, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n  int K = 3;\n  VectorXd beta(K);\n\n  beta << -0.5, 0.1, 0.3;\n\n  VectorXd theta = softmax(beta);\n  boost::math::chi_squared mydist(K - 1);\n\n  int bin[K];\n  double expect[K];\n  for (int i = 0; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N * theta(i);\n  }\n\n  for (int i = 0; i < N; i++) {\n    int a = stan::math::categorical_logit_rng(beta, rng);\n    bin[a - 1]++;\n  }\n\n  double chi = 0;\n  for (int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n", "meta": {"hexsha": "43f421c5fb65def86ce6de99638e6e3469f0d354", "size": 1434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/categorical_logit_rng_test.cpp", "max_stars_repo_name": "HaoZeke/math", "max_stars_repo_head_hexsha": "fdf7f70dceed60f3b3f93137c6ac123a457b80a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-18T13:10:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T13:10:50.000Z", "max_issues_repo_path": "test/unit/math/prim/prob/categorical_logit_rng_test.cpp", "max_issues_repo_name": "HaoZeke/math", "max_issues_repo_head_hexsha": "fdf7f70dceed60f3b3f93137c6ac123a457b80a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T12:45:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T20:43:03.000Z", "max_forks_repo_path": "test/unit/math/prim/prob/categorical_logit_rng_test.cpp", "max_forks_repo_name": "SteveBronder/math", "max_forks_repo_head_hexsha": "3f21445458866897842878f65941c6bcb90641c2", "max_forks_repo_licenses": ["BSD-3-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.724137931, "max_line_length": 69, "alphanum_fraction": 0.6569037657, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.5807444271986317}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/cat.hpp\n *\n * \\brief Concatenate arrays along specified dimension.\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompwhiching file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\todo cat<1>, cat<2>, cat<tag::major>, ...\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLAS_OPERATION_EX_CAT_HPP\n#define BOOST_NUMERIC_UBLAS_OPERATION_EX_CAT_HPP\n\n\n#include <algorithm>\n#include <boost/numeric/ublas/exception.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/operation/num_columns.hpp>\n#include <boost/numeric/ublasx/operation/num_rows.hpp>\n#include <boost/numeric/ublasx/traits/layout_type.hpp>\n\n\n//TODO: add overloaded function to cat vectors and vector-matrix pairs\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\ntemplate <\n\ttypename M1,\n\ttypename M2\n>\nstruct matrix_cat_traits\n{\n\ttypedef typename promote_traits<\n\t\t\ttypename matrix_traits<M1>::value_type,\n\t\t\ttypename matrix_traits<M2>::value_type\n\t\t>::promote_type value_type;\n\t// Currently, the result type is simply a dense matrix since it is difficult\n\t// to know in advance whether a particular matrix structure will be\n\t// preserved after the 'cat' operation.\n\t// TODO: we might use the matrix_temporary_traits. However, how do we choose\n\t// between matrix_temporary_traits<M1> and matrix_temporary_traits<M2>?\n\ttypedef matrix<\n\t\t\tvalue_type,\n\t\t\ttypename layout_type<M1>::type\n\t\t> result_type;\n};\n\n\n/**\n * \\brief Concatenate arrays along columns.\n *\n * \\tparam InMatrixExpr1T The type of the first input matrix expression.\n * \\tparam InMatrixExpr2T The type of the second input matrix expression.\n *\n * \\param A The first input matrix expression.\n * \\param B The second input matrix expression.\n * \\return A new matrix with \\c max(num_rows(A),num_rows(B)) rows and\n *  \\c num_columns(A)+num_columns(B) columns.\n *\n * For two input matrices A and B, append each column of B to its respective\n * column of A. \n * If \\a A and \\a B have a different number of columns, the number of colums of\n * the resulting matrix will be the maximum between the number of columns of the\n * two input matrices and the elements of the matrix with the smaller number of\n * columns will be replaced with a zero value.\n *\n * Examples:\n * <pre>\n * A = [1 2 3;\n *      4 5 6;\n *      7 8 9]\n * B = [10 11;\n *      12 13]\n * C = cat_columns(A,B);\n * C == [ 1  2 3;\n *        4  5 6;\n *        7  8 9;\n *       10 11 0;\n *       12 13 0]\n * </pre>\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <\n\ttypename InMatrixExpr1T,\n\ttypename InMatrixExpr2T\n>\ntypename matrix_cat_traits<InMatrixExpr1T,InMatrixExpr2T>::result_type cat_columns(matrix_expression<InMatrixExpr1T> const& A, matrix_expression<InMatrixExpr2T> const& B)\n{\n\ttypedef typename matrix_cat_traits<InMatrixExpr1T,InMatrixExpr2T>::result_type out_matrix_type;\n\ttypedef typename matrix_traits<out_matrix_type>::value_type value_type;\n\ttypedef typename matrix_traits<out_matrix_type>::size_type size_type;\n\n//\t// precondition: num_columns(A) == num_columns(B)\n//\tBOOST_UBLAS_CHECK(\n//\t\tnum_columns(A) == num_columns(B),\n//\t\tbad_argument()\n//\t);\n\n\tsize_type A_nr = num_rows(A);\n\tsize_type A_nc = num_columns(A);\n\tsize_type B_nr = num_rows(B);\n\tsize_type B_nc = num_columns(B);\n\tsize_type nc = ::std::max(A_nc, B_nc);\n\n\tout_matrix_type X(A_nr+B_nr, nc, value_type());\n\n\tfor (size_type c = 0; c < nc; ++c)\n\t{\n\t\tif (c < A_nc)\n\t\t{\n\t\t\tfor (size_type r = 0; r < A_nr; ++r)\n\t\t\t{\n\t\t\t\tX(r,c) = A()(r,c);\n\t\t\t}\n\t\t}\n\t\tif (c < B_nc)\n\t\t{\n\t\t\tfor (size_type r = 0; r < B_nr; ++r)\n\t\t\t{\n\t\t\t\tX(r+A_nr,c) = B()(r,c);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn X;\n}\n\n\n/**\n * \\brief Concatenate arrays along rows.\n *\n * \\tparam InMatrixExpr1T The type of the first input matrix expression.\n * \\tparam InMatrixExpr2T The type of the second input matrix expression.\n *\n * \\param A The first input matrix expression.\n * \\param B The second input matrix expression.\n * \\return A new matrix with \\c num_rows(A)+num_rows(B) rows and\n *  \\c max(num_columns(A),num_columns(B)) columns.\n *\n * For two input matrices A and B, append each column of B to its respective\n * column of A.\n * If \\a A and \\a B have a different number of columns, the number of rows of\n * the resulting matrix will be the maximum between the number of rows of the\n * two input matrices and the elements of the matrix with the smaller number of\n * columns will be replaced with a zero value.\n *\n * Examples:\n * <pre>\n * A = [1 2 3;\n *      4 5 6;\n *      7 8 9]\n * B = [10 11;\n *      12 13]\n * C = cat_rows(A,B);\n * C == [1 2 3 10 11;\n *       4 5 6 12 13;\n *       7 8 9  0  0];\n * </pre>\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <\n\ttypename InMatrixExpr1T,\n\ttypename InMatrixExpr2T\n>\ntypename matrix_cat_traits<InMatrixExpr1T,InMatrixExpr2T>::result_type cat_rows(matrix_expression<InMatrixExpr1T> const& A, matrix_expression<InMatrixExpr2T> const& B)\n{\n\ttypedef typename matrix_cat_traits<InMatrixExpr1T,InMatrixExpr2T>::result_type out_matrix_type;\n\ttypedef typename matrix_traits<out_matrix_type>::value_type value_type;\n\ttypedef typename matrix_traits<out_matrix_type>::size_type size_type;\n\n\tsize_type A_nr = num_rows(A);\n\tsize_type A_nc = num_columns(A);\n\tsize_type B_nr = num_rows(B);\n\tsize_type B_nc = num_columns(B);\n\tsize_type nr = ::std::max(A_nr, B_nr);\n\n\tout_matrix_type X(nr, A_nc+B_nc, value_type());\n\n\tfor (size_type r = 0; r < nr; ++r)\n\t{\n\t\tif (r < A_nr)\n\t\t{\n\t\t\tfor (size_type c = 0; c < A_nc; ++c)\n\t\t\t{\n\t\t\t\tX(r,c) = A()(r,c);\n\t\t\t}\n\t\t}\n\t\tif (r < B_nr)\n\t\t{\n\t\t\tfor (size_type c = 0; c < B_nc; ++c)\n\t\t\t{\n\t\t\t\tX(r,c+A_nc) = B()(r,c);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn X;\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_CAT_HPP\n", "meta": {"hexsha": "a9420e8a4d1179ff2710d5e7a2477bb8fe351fc2", "size": 5925, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/cat.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/cat.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/cat.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4305555556, "max_line_length": 170, "alphanum_fraction": 0.6956962025, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.5807444271495974}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    Array<int,2> A(3,3);\n    A = 3, 5, 8,\n        2, 4, 9,\n        1, 0, 1;\n\n    // workaround for MIPSpro compiler bug\n#if defined(__sgi)\n    Array<int,2> Asqrd(3,3);\n    Asqrd = sqr(A);\n#endif\n\n    TinyVector<int,2> minpos = minIndex(A);\n\n    BZTEST(minpos(0) == 2);\n    BZTEST(minpos(1) == 1);\n\n    // workaround for MIPSpro compiler bug\n#if defined(__sgi)\n    minpos = minIndex(Asqrd);\n#else\n    minpos = minIndex(sqr(A));\n#endif\n    BZTEST(minpos(0) == 2);\n    BZTEST(minpos(1) == 1);\n\n    TinyVector<int,2> maxpos = maxIndex(A);\n    BZTEST(maxpos(0) == 1);\n    BZTEST(maxpos(1) == 2);\n\n    // workaround for MIPSpro compiler bug\n#if defined(__sgi)\n    maxpos = maxIndex(Asqrd);\n#else\n    maxpos = maxIndex(sqr(A));\n#endif\n    BZTEST(maxpos(0) == 1);\n    BZTEST(maxpos(1) == 2);\n}\n\n", "meta": {"hexsha": "01ff858a6f7f8c3d0ee40e43a969c55b33eebedd", "size": 876, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/peter-nordlund-3.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/testsuite/peter-nordlund-3.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/testsuite/peter-nordlund-3.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6382978723, "max_line_length": 43, "alphanum_fraction": 0.5867579909, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.580744423154153}}
{"text": "// Copyright (C) 2010  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n\r\n#include <sstream>\r\n#include <string>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include <dlib/statistics.h>\r\n#include <dlib/rand.h>\r\n#include <algorithm>\r\n\r\n#include \"tester.h\"\r\n\r\nnamespace  \r\n{\r\n\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n\r\n    logger dlog(\"test.statistics\");\r\n\r\n\r\n\r\n    class statistics_tester : public tester\r\n    {\r\n    public:\r\n        statistics_tester (\r\n        ) :\r\n            tester (\"test_statistics\",\r\n                    \"Runs tests on the statistics component.\")\r\n        {}\r\n\r\n        void test_random_subset_selector ()\r\n        {\r\n            random_subset_selector<double> rand_set;\r\n\r\n            for (int j = 0; j < 30; ++j)\r\n            {\r\n                print_spinner();\r\n\r\n                running_stats<double> rs, rs2;\r\n\r\n                rand_set.set_max_size(1000);\r\n\r\n                for (double i = 0; i < 100000; ++i)\r\n                {\r\n                    rs.add(i);\r\n                    rand_set.add(i);\r\n                }\r\n\r\n\r\n                for (unsigned long i = 0; i < rand_set.size(); ++i)\r\n                    rs2.add(rand_set[i]);\r\n\r\n\r\n                dlog << LDEBUG << \"true mean:    \" << rs.mean();\r\n                dlog << LDEBUG << \"true sampled: \" << rs2.mean();\r\n                double ratio = rs.mean()/rs2.mean();\r\n                DLIB_TEST_MSG(0.96 < ratio  && ratio < 1.04, \" ratio: \" << ratio);\r\n            }\r\n\r\n\r\n            {\r\n                random_subset_selector<int> r1, r2;\r\n                r1.set_max_size(300);\r\n                for (int i = 0; i < 4000; ++i)\r\n                    r1.add(i);\r\n\r\n                ostringstream sout;\r\n                serialize(r1, sout);\r\n                istringstream sin(sout.str());\r\n                deserialize(r2, sin);\r\n\r\n                DLIB_TEST(r1.size() == r2.size());\r\n                DLIB_TEST(r1.max_size() == r2.max_size());\r\n                DLIB_TEST(r1.next_add_accepts() == r2.next_add_accepts());\r\n                DLIB_TEST(std::equal(r1.begin(), r1.end(), r2.begin()));\r\n\r\n                for (int i = 0; i < 4000; ++i)\r\n                {\r\n                    r1.add(i);\r\n                    r2.add(i);\r\n                }\r\n\r\n                DLIB_TEST(r1.size() == r2.size());\r\n                DLIB_TEST(r1.max_size() == r2.max_size());\r\n                DLIB_TEST(r1.next_add_accepts() == r2.next_add_accepts());\r\n                DLIB_TEST(std::equal(r1.begin(), r1.end(), r2.begin()));\r\n            }\r\n        }\r\n\r\n        void test_random_subset_selector2 ()\r\n        {\r\n            random_subset_selector<double> rand_set;\r\n            DLIB_TEST(rand_set.next_add_accepts() == false);\r\n            DLIB_TEST(rand_set.size() == 0);\r\n            DLIB_TEST(rand_set.max_size() == 0);\r\n\r\n            for (int j = 0; j < 30; ++j)\r\n            {\r\n                print_spinner();\r\n\r\n                running_stats<double> rs, rs2;\r\n\r\n                rand_set.set_max_size(1000);\r\n                DLIB_TEST(rand_set.next_add_accepts() == true);\r\n\r\n                for (double i = 0; i < 100000; ++i)\r\n                {\r\n                    rs.add(i);\r\n                    if (rand_set.next_add_accepts())\r\n                        rand_set.add(i);\r\n                    else\r\n                        rand_set.add();\r\n                }\r\n\r\n                DLIB_TEST(rand_set.size() == 1000);\r\n                DLIB_TEST(rand_set.max_size() == 1000);\r\n\r\n                for (unsigned long i = 0; i < rand_set.size(); ++i)\r\n                    rs2.add(rand_set[i]);\r\n\r\n\r\n                dlog << LDEBUG << \"true mean:    \" << rs.mean();\r\n                dlog << LDEBUG << \"true sampled: \" << rs2.mean();\r\n                double ratio = rs.mean()/rs2.mean();\r\n                DLIB_TEST_MSG(0.96 < ratio  && ratio < 1.04, \" ratio: \" << ratio);\r\n            }\r\n        }\r\n\r\n        void test_running_covariance (\r\n        )\r\n        {\r\n            dlib::rand rnd;\r\n            std::vector<matrix<double,0,1> > vects;\r\n\r\n            running_covariance<matrix<double,0,1> > cov, cov2;\r\n            DLIB_TEST(cov.in_vector_size() == 0);\r\n\r\n            for (unsigned long dims = 1; dims < 5; ++dims)\r\n            {\r\n                for (unsigned long samps = 2; samps < 10; ++samps)\r\n                {\r\n                    vects.clear();\r\n                    cov.clear();\r\n                    DLIB_TEST(cov.in_vector_size() == 0);\r\n                    for (unsigned long i = 0; i < samps; ++i)\r\n                    {\r\n                        vects.push_back(randm(dims,1,rnd));\r\n                        cov.add(vects.back());\r\n\r\n                    }\r\n                    DLIB_TEST(cov.in_vector_size() == (long)dims);\r\n\r\n                    DLIB_TEST(equal(mean(vector_to_matrix(vects)), cov.mean()));\r\n                    DLIB_TEST_MSG(equal(covariance(vector_to_matrix(vects)), cov.covariance()),\r\n                              max(abs(covariance(vector_to_matrix(vects)) - cov.covariance()))\r\n                              << \"   dims = \" << dims << \"   samps = \" << samps\r\n                              );\r\n                }\r\n            }\r\n\r\n            for (unsigned long dims = 1; dims < 5; ++dims)\r\n            {\r\n                for (unsigned long samps = 2; samps < 10; ++samps)\r\n                {\r\n                    vects.clear();\r\n                    cov.clear();\r\n                    cov2.clear();\r\n                    DLIB_TEST(cov.in_vector_size() == 0);\r\n                    for (unsigned long i = 0; i < samps; ++i)\r\n                    {\r\n                        vects.push_back(randm(dims,1,rnd));\r\n                        if ((i%2) == 0)\r\n                            cov.add(vects.back());\r\n                        else\r\n                            cov2.add(vects.back());\r\n\r\n                    }\r\n                    DLIB_TEST((cov+cov2).in_vector_size() == (long)dims);\r\n\r\n                    DLIB_TEST(equal(mean(vector_to_matrix(vects)), (cov+cov2).mean()));\r\n                    DLIB_TEST_MSG(equal(covariance(vector_to_matrix(vects)), (cov+cov2).covariance()),\r\n                              max(abs(covariance(vector_to_matrix(vects)) - (cov+cov2).covariance()))\r\n                              << \"   dims = \" << dims << \"   samps = \" << samps\r\n                              );\r\n                }\r\n            }\r\n\r\n        }\r\n\r\n        void test_running_stats()\r\n        {\r\n            print_spinner();\r\n\r\n            running_stats<double> rs, rs2;\r\n\r\n            running_scalar_covariance<double> rsc1, rsc2;\r\n\r\n            for (double i = 0; i < 100; ++i)\r\n            {\r\n                rs.add(i);\r\n\r\n                rsc1.add(i,i);\r\n                rsc2.add(i,i);\r\n                rsc2.add(i,-i);\r\n            }\r\n\r\n            // make sure the running_stats and running_scalar_covariance agree\r\n            DLIB_TEST_MSG(std::abs(rs.mean() - rsc1.mean_x()) < 1e-10, std::abs(rs.mean() - rsc1.mean_x()));\r\n            DLIB_TEST(std::abs(rs.mean() - rsc1.mean_y()) < 1e-10);\r\n            DLIB_TEST(std::abs(rs.stddev() - rsc1.stddev_x()) < 1e-10);\r\n            DLIB_TEST(std::abs(rs.stddev() - rsc1.stddev_y()) < 1e-10);\r\n            DLIB_TEST(std::abs(rs.variance() - rsc1.variance_x()) < 1e-10);\r\n            DLIB_TEST(std::abs(rs.variance() - rsc1.variance_y()) < 1e-10);\r\n            DLIB_TEST(rs.current_n() == rsc1.current_n());\r\n\r\n            DLIB_TEST(std::abs(rsc1.correlation() - 1) < 1e-10);\r\n            DLIB_TEST(std::abs(rsc2.correlation() - 0) < 1e-10);\r\n\r\n\r\n\r\n            // test serialization of running_stats\r\n            ostringstream sout;\r\n            serialize(rs, sout);\r\n            istringstream sin(sout.str());\r\n            deserialize(rs2, sin);\r\n            // make sure the running_stats and running_scalar_covariance agree\r\n            DLIB_TEST_MSG(std::abs(rs2.mean() - rsc1.mean_x()) < 1e-10, std::abs(rs2.mean() - rsc1.mean_x()));\r\n            DLIB_TEST(std::abs(rs2.mean() - rsc1.mean_y()) < 1e-10);\r\n            DLIB_TEST(std::abs(rs2.stddev() - rsc1.stddev_x()) < 1e-10);\r\n            DLIB_TEST(std::abs(rs2.stddev() - rsc1.stddev_y()) < 1e-10);\r\n            DLIB_TEST(std::abs(rs2.variance() - rsc1.variance_x()) < 1e-10);\r\n            DLIB_TEST(std::abs(rs2.variance() - rsc1.variance_y()) < 1e-10);\r\n            DLIB_TEST(rs2.current_n() == rsc1.current_n());\r\n\r\n        }\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            test_random_subset_selector();\r\n            test_random_subset_selector2();\r\n            test_running_covariance();\r\n            test_running_stats();\r\n        }\r\n    } a;\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "46c7c4ebc78c2ff914a83da92b4ddec6a38597a7", "size": 8672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dlib/test/statistics.cpp", "max_stars_repo_name": "cpearce/HARM", "max_stars_repo_head_hexsha": "1e629099bbaa0203b19fe9007a71d9ab9c938be0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-10-11T18:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-11T18:37:52.000Z", "max_issues_repo_path": "src/dlib/test/statistics.cpp", "max_issues_repo_name": "wsgan001/HARM", "max_issues_repo_head_hexsha": "1e629099bbaa0203b19fe9007a71d9ab9c938be0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-27T22:58:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-28T04:46:52.000Z", "max_forks_repo_path": "src/dlib/test/statistics.cpp", "max_forks_repo_name": "wsgan001/HARM", "max_forks_repo_head_hexsha": "1e629099bbaa0203b19fe9007a71d9ab9c938be0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-19T06:15:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-02T11:11:57.000Z", "avg_line_length": 34.1417322835, "max_line_length": 111, "alphanum_fraction": 0.4406134686, "num_tokens": 2023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5806930175631231}}
{"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": "#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include \"../include/layer.h\"\n\nint main()\n{\n    using namespace Eigen;\n    using std::cout;\n    using std::endl;\n    using namespace MyDL;\n\n    int n = 1;\n    int c = 1;\n    int h = 3;\n    int w = 3;\n    int Fn = 2;\n    int Fh = 2;\n    int Fw = 2;\n    int stride = 1;\n    int pad = 1;\n\n    Conv2D conv(c, h, w, Fn, Fh, Fw, stride, pad, 0.1);\n\n    vector<MatrixXd> inputs, conv_outs, pooling_outs;\n    MatrixXd X = MatrixXd::Zero(n, c * h * w);\n    X << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n\n    n = 1;\n    c = Fn;\n    h = (pad*2+h-Fh)/stride + 1;\n    w = (pad*2+w-Fw)/stride + 1;\n    int Ph = 2;\n    int Pw = 2;\n    stride = 2;\n    pad = 0;\n\n    int Oh = (2*pad + h - Ph) / stride + 1;\n    int Ow = (2*pad + w - Pw) / stride + 1;\n\n    Pooling pooling(c, h, w, Ph, Pw, stride, pad);\n\n    // MatrixXd X = MatrixXd::Zero(n, h*w*c);\n\n    // X << 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16;\n    // X << 1,2,3,4,5,1,7,1,9,10,11,12,13,1,15,1;\n\n    // vector<MatrixXd> inputs, outputs;\n    // inputs.push_back(X);\n\n    // outputs = pooling.forward(inputs);\n\n    // cout << outputs[0] << endl;\n\n    // vector<MatrixXd> douts, grads;\n    // MatrixXd dout = MatrixXd::Zero(n, c*Oh*Ow);\n\n    // dout << 1,2,3,4;\n\n    // douts.push_back(dout);\n\n    // grads = pooling.backward(douts);\n\n    // cout << grads[0] << endl;\n\n    // -----------------------\n    //   Conv2D\u3068\u306e\u7d50\u5408\u306e\u52d5\u4f5c\u78ba\u8a8d\n    // -----------------------\n\n    inputs.push_back(X);\n    conv_outs = conv.forward(inputs);\n\n    cout << conv_outs[0] << endl;\n\n    pooling_outs = pooling.forward(conv_outs);\n\n    cout << pooling_outs[0] << endl;\n\n    cout << pooling._argmax << endl;\n\n    vector<MatrixXd> douts, pooling_grads, conv_grads;\n    MatrixXd dout = MatrixXd::Ones(n, Oh*Ow*c);\n    dout << 1,2,3,4,1,2,3,4;\n    douts.push_back(dout);\n\n    pooling_grads = pooling.backward(douts);\n\n    cout << pooling_grads[0] << endl;\n\n    conv_grads = conv.backward(pooling_grads);\n\n    cout << conv_grads[0] << endl;\n\n    return 0;\n}", "meta": {"hexsha": "7ac24ea7829d07dbfdabeb4861836459a666790d", "size": 2009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_pooling.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_pooling.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_pooling.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1473684211, "max_line_length": 55, "alphanum_fraction": 0.531110005, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5806725782190403}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2013-2015 Adam Wulkiewicz, Lodz, Poland.\n\n// This file was modified by Oracle on 2014, 2015, 2016, 2018.\n// Modifications copyright (c) 2014-2018 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#include \"test_within.hpp\"\n\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/multi_point.hpp>\n#include <boost/geometry/geometries/multi_linestring.hpp>\n#include <boost/geometry/geometries/multi_polygon.hpp>\n\ntemplate <typename P1, typename P2>\nvoid test_point_box()\n{\n    typedef bg::model::box<P1> box_type1;\n    typedef bg::model::box<P2> box_type2;\n\n    test_geometry<P1, box_type2>(\"POINT(1 1)\", \"BOX(0 0,2 2)\", true);\n    test_geometry<P1, box_type2>(\"POINT(0 0)\", \"BOX(0 0,2 2)\", false);\n    test_geometry<P1, box_type2>(\"POINT(2 2)\", \"BOX(0 0,2 2)\", false);\n    test_geometry<P1, box_type2>(\"POINT(0 1)\", \"BOX(0 0,2 2)\", false);\n    test_geometry<P1, box_type2>(\"POINT(1 0)\", \"BOX(0 0,2 2)\", false);\n\n    test_geometry<P1, box_type2>(\"POINT(3 3)\", \"BOX(1 1,4 4)\", true);\n    test_geometry<P2, box_type1>(\"POINT(3 3)\", \"BOX(0 0,5 5)\", true);\n\n    test_geometry<box_type1, box_type2>(\"BOX(1 1,2 2)\", \"BOX(0 0,3 3)\", true);\n    test_geometry<box_type1, box_type2>(\"BOX(0 0,3 3)\", \"BOX(1 1,2 2)\", false);\n\n    test_geometry<box_type1, box_type2>(\"BOX(1 1,3 3)\", \"BOX(0 0,3 3)\", true);\n    test_geometry<box_type1, box_type2>(\"BOX(3 1,3 3)\", \"BOX(0 0,3 3)\", false);\n\n    test_geometry<box_type1, box_type2>(\"BOX(1 1,4 4)\", \"BOX(0 0,5 5)\", true);\n    test_geometry<box_type2, box_type1>(\"BOX(0 0,5 5)\", \"BOX(1 1,4 4)\", false);\n\n    /*\n    test_within_code<P, box_type>(\"POINT(1 1)\", \"BOX(0 0,2 2)\", 1);\n    test_within_code<P, box_type>(\"POINT(1 0)\", \"BOX(0 0,2 2)\", 0);\n    test_within_code<P, box_type>(\"POINT(0 1)\", \"BOX(0 0,2 2)\", 0);\n    test_within_code<P, box_type>(\"POINT(0 3)\", \"BOX(0 0,2 2)\", -1);\n    test_within_code<P, box_type>(\"POINT(3 3)\", \"BOX(0 0,2 2)\", -1);\n\n    test_within_code<box_type, box_type>(\"BOX(1 1,2 2)\", \"BOX(0 0,3 3)\", 1);\n    test_within_code<box_type, box_type>(\"BOX(0 1,2 2)\", \"BOX(0 0,3 3)\", 0);\n    test_within_code<box_type, box_type>(\"BOX(1 0,2 2)\", \"BOX(0 0,3 3)\", 0);\n    test_within_code<box_type, box_type>(\"BOX(1 1,2 3)\", \"BOX(0 0,3 3)\", 0);\n    test_within_code<box_type, box_type>(\"BOX(1 1,3 2)\", \"BOX(0 0,3 3)\", 0);\n    test_within_code<box_type, box_type>(\"BOX(1 1,3 4)\", \"BOX(0 0,3 3)\", -1);\n    */\n}\n\nvoid test_point_box_3d()\n{\n    typedef boost::geometry::model::point<double, 3, boost::geometry::cs::cartesian> point_type;\n    typedef boost::geometry::model::box<point_type> box_type;\n    box_type box(point_type(0, 0, 0), point_type(4, 4, 4));\n    BOOST_CHECK_EQUAL(bg::within(point_type(2, 2, 2), box), true);\n    BOOST_CHECK_EQUAL(bg::within(point_type(2, 4, 2), box), false);\n    BOOST_CHECK_EQUAL(bg::within(point_type(2, 2, 4), box), false);\n    BOOST_CHECK_EQUAL(bg::within(point_type(2, 2, 5), box), false);\n\n    box_type box2(point_type(2, 2, 2), point_type(3, 3, 3));\n    BOOST_CHECK_EQUAL(bg::within(box2, box), true);\n\n}\n\ntemplate <typename P1, typename P2>\nvoid test_point_poly()\n{\n    typedef boost::geometry::model::polygon<P1> poly1;\n    typedef boost::geometry::model::polygon<P2> poly2;\n\n    test_geometry<P1, poly2>(\"POINT(3 3)\", \"POLYGON((0 0,0 5,5 5,5 0,0 0))\", true);\n    test_geometry<P2, poly1>(\"POINT(3 3)\", \"POLYGON((0 0,0 5,5 5,5 0,0 0))\", true);\n}\n\ntemplate <typename P1, typename P2>\nvoid test_all()\n{\n    test_point_box<P1, P2>();\n    test_point_poly<P1, P2>();\n}\n\ntemplate <typename P>\nvoid test_all()\n{\n    test_all<P, P>();\n}\n\nvoid test_strategy()\n{\n    // Test by explicitly specifying a strategy\n    typedef bg::model::d2::point_xy<double> point_type;\n    typedef bg::model::box<point_type> box_type;\n    point_type p(3, 3);\n    box_type b(point_type(0, 0), point_type(5, 5));\n    box_type b0(point_type(0, 0), point_type(5, 0));\n\n    bool r = bg::within(p, b,\n        bg::strategy::within::cartesian_point_box());\n    BOOST_CHECK_EQUAL(r, true);\n\n    r = bg::within(b, b,\n        bg::strategy::within::box_in_box<box_type, box_type>());\n    BOOST_CHECK_EQUAL(r, true);\n\n    r = bg::within(b0, b0,\n        bg::strategy::within::box_in_box<box_type, box_type>());\n    BOOST_CHECK_EQUAL(r, false);\n\n    r = bg::within(p, b,\n        bg::strategy::within::point_in_box_by_side<>());\n    BOOST_CHECK_EQUAL(r, true);\n}\n\n\nint test_main( int , char* [] )\n{\n    typedef boost::geometry::model::d2::point_xy<double> xyd;\n    typedef boost::geometry::model::d2::point_xy<float> xyf;\n    typedef boost::geometry::model::d2::point_xy<int> xyi;\n    typedef boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> p2d;\n    \n    test_all<xyd, p2d>();\n    test_all<xyf, p2d>();\n    test_all<xyi, xyd>();\n\n    test_all<xyi>();\n    test_all<xyd>();\n\n    test_point_box_3d();\n    test_strategy();\n\n    return 0;\n}\n", "meta": {"hexsha": "9cd98628e788d95fc0f017ccc928aa610df0e9a3", "size": 5269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/within/within.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T15:15:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T15:15:28.000Z", "max_issues_repo_path": "test/algorithms/within/within.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T08:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-06T20:49:05.000Z", "max_forks_repo_path": "test/algorithms/within/within.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 35.6013513514, "max_line_length": 96, "alphanum_fraction": 0.6530650977, "num_tokens": 1832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5806725702524818}}
{"text": "// Copyright John Maddock 2006.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// test_rayleigh.cpp\n\n#ifdef _MSC_VER\n#  pragma warning(disable: 4127) // conditional expression is constant.\n#  pragma warning(disable: 4100) // unreferenced formal parameter.\n#endif\n\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\n#include <boost/math/distributions/rayleigh.hpp>\n    using boost::math::rayleigh_distribution;\n#include <boost/math/tools/test.hpp>\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp> // Boost.Test\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include \"test_out_of_range.hpp\"\n\n#include <iostream>\n   using std::cout;\n   using std::endl;\n   using std::setprecision;\n\ntemplate <class RealType>\nvoid test_spot(RealType s, RealType x, RealType p, RealType q, RealType tolerance)\n{\n   BOOST_CHECK_CLOSE(\n      ::boost::math::cdf(\n         rayleigh_distribution<RealType>(s),\n         x),\n         p,\n         tolerance); // %\n   BOOST_CHECK_CLOSE(\n      ::boost::math::cdf(\n         complement(rayleigh_distribution<RealType>(s),\n         x)),\n         q,\n         tolerance); // %\n   // Special extra tests for p and q near to unity.\n   if(p < 0.999)\n   {\n      BOOST_CHECK_CLOSE(\n         ::boost::math::quantile(\n            rayleigh_distribution<RealType>(s),\n            p),\n            x,\n            tolerance); // %\n   }\n   if(q < 0.999)\n   {\n      BOOST_CHECK_CLOSE(\n         ::boost::math::quantile(\n            complement(rayleigh_distribution<RealType>(s),\n            q)),\n            x,\n            tolerance); // %\n   }\n   if(std::numeric_limits<RealType>::has_infinity)\n   {\n      RealType inf = std::numeric_limits<RealType>::infinity();\n      BOOST_CHECK_EQUAL(pdf(rayleigh_distribution<RealType>(s), inf), 0);\n      BOOST_CHECK_EQUAL(cdf(rayleigh_distribution<RealType>(s), inf), 1);\n      BOOST_CHECK_EQUAL(cdf(complement(rayleigh_distribution<RealType>(s), inf)), 0);\n   }\n} // void test_spot\n\ntemplate <class RealType>\nvoid test_spots(RealType T)\n{\n   using namespace std; // ADL of std names.\n   // Basic sanity checks.\n   // 50 eps as a percentage, up to a maximum of double precision\n   // (that's the limit of our test data: obtained by punching\n   // numbers into a calculator).\n   RealType tolerance = (std::max)(\n      static_cast<RealType>(boost::math::tools::epsilon<double>()),\n      boost::math::tools::epsilon<RealType>());\n   tolerance *= 10 * 100; // 10 eps as a percent\n   cout << \"Tolerance for type \" << typeid(T).name()  << \" is \" << tolerance << \" %\" << endl;\n\n  using namespace boost::math::constants;\n\n   // Things that are errors:\n   rayleigh_distribution<RealType> dist(0.5);\n\n   check_out_of_range<rayleigh_distribution<RealType> >(1);\n   BOOST_MATH_CHECK_THROW(\n       quantile(dist,\n       RealType(1.)), // quantile unity should overflow.\n       std::overflow_error);\n   BOOST_MATH_CHECK_THROW(\n       quantile(complement(dist,\n       RealType(0.))), // quantile complement zero should overflow.\n       std::overflow_error);\n   BOOST_MATH_CHECK_THROW(\n       pdf(dist, RealType(-1)), // Bad negative x.\n       std::domain_error);\n   BOOST_MATH_CHECK_THROW(\n       cdf(dist, RealType(-1)), // Bad negative x.\n       std::domain_error);\n   BOOST_MATH_CHECK_THROW(\n       cdf(rayleigh_distribution<RealType>(-1), // bad sigma < 0\n       RealType(1)),\n       std::domain_error);\n   BOOST_MATH_CHECK_THROW(\n       cdf(rayleigh_distribution<RealType>(0), // bad sigma == 0\n       RealType(1)),\n       std::domain_error);\n   BOOST_MATH_CHECK_THROW(\n       quantile(dist, RealType(-1)), // negative quantile probability.\n       std::domain_error);\n   BOOST_MATH_CHECK_THROW(\n       quantile(dist, RealType(2)), // > unity  quantile probability.\n       std::domain_error);\n\n   test_spot(\n      static_cast<RealType>(1.L), // sigma\n      static_cast<RealType>(1.L), // x\n      static_cast<RealType>(1 - exp_minus_half<RealType>()), // p\n      static_cast<RealType>(exp_minus_half<RealType>()), // q\n      tolerance);\n\n   test_spot(\n      static_cast<RealType>(0.5L), // sigma\n      static_cast<RealType>(0.5L), // x\n      static_cast<RealType>(1 - exp_minus_half<RealType>()), // p\n      static_cast<RealType>(exp_minus_half<RealType>()), //q\n      tolerance);\n\n   test_spot(\n      static_cast<RealType>(3.L), // sigma\n      static_cast<RealType>(3.L), // x\n      static_cast<RealType>(1 - exp_minus_half<RealType>()), // p\n      static_cast<RealType>(exp_minus_half<RealType>()), //q\n      tolerance);\n\n   BOOST_CHECK_CLOSE(\n      ::boost::math::pdf(\n         rayleigh_distribution<RealType>(1.L),\n         static_cast<RealType>(1.L)),              // x\n         static_cast<RealType>(exp_minus_half<RealType>()), // probability.\n         tolerance); // %\n   BOOST_CHECK_CLOSE(\n      ::boost::math::pdf(\n         rayleigh_distribution<RealType>(0.5L),\n         static_cast<RealType>(0.5L)),              // x\n         static_cast<RealType>(2 * exp_minus_half<RealType>()), // probability.\n         tolerance); // %\n   BOOST_CHECK_CLOSE(\n      ::boost::math::pdf(\n         rayleigh_distribution<RealType>(2.L),\n         static_cast<RealType>(2.L)),              // x\n         static_cast<RealType>(exp_minus_half<RealType>() /2),  // probability.\n         tolerance); // %\n\n   BOOST_CHECK_CLOSE(\n      ::boost::math::mean(\n         rayleigh_distribution<RealType>(1.L)),\n         static_cast<RealType>(root_half_pi<RealType>()),\n         tolerance); // %\n   BOOST_CHECK_CLOSE(\n      ::boost::math::variance(\n         rayleigh_distribution<RealType>(root_two<RealType>())),\n         static_cast<RealType>(four_minus_pi<RealType>()),\n         tolerance * 100); // %\n\n   BOOST_CHECK_CLOSE(\n      ::boost::math::mode(\n         rayleigh_distribution<RealType>(1.L)),\n         static_cast<RealType>(1.L),\n         tolerance); // %\n\n   BOOST_CHECK_CLOSE(\n      ::boost::math::median(\n         rayleigh_distribution<RealType>(1.L)),\n         static_cast<RealType>(sqrt(log(4.L))),  // sigma * sqrt(log_four)\n         tolerance); // %\n\n   BOOST_CHECK_CLOSE(\n      ::boost::math::skewness(\n         rayleigh_distribution<RealType>(1.L)),\n         static_cast<RealType>(2.L * root_pi<RealType>()) * (pi<RealType>() - 3) / (pow((4 - pi<RealType>()), static_cast<RealType>(1.5L))),\n         tolerance * 100); // %\n\n   BOOST_CHECK_CLOSE(\n      ::boost::math::skewness(\n         rayleigh_distribution<RealType>(1.L)),\n         static_cast<RealType>(0.63111065781893713819189935154422777984404221106391L),\n         tolerance * 100); // %\n\n   BOOST_CHECK_CLOSE(\n     ::boost::math::kurtosis_excess(\n     rayleigh_distribution<RealType>(1.L)),\n     -static_cast<RealType>(6 * pi<RealType>() * pi<RealType>() - 24 * pi<RealType>() + 16) /\n        ((4 - pi<RealType>()) * (4 - pi<RealType>())),\n        // static_cast<RealType>(0.2450893006876380628486604106197544154170667057995L),\n         tolerance * 1000); // %\n\n   BOOST_CHECK_CLOSE(\n      ::boost::math::kurtosis(\n         rayleigh_distribution<RealType>(1.L)),\n         static_cast<RealType>(3.2450893006876380628486604106197544154170667057995L),\n         tolerance * 100); // %\n\n\n   BOOST_CHECK_CLOSE(\n      ::boost::math::kurtosis_excess(rayleigh_distribution<RealType>(2)),\n      ::boost::math::kurtosis(rayleigh_distribution<RealType>(2)) -3,\n         tolerance* 100); // %\n   return;\n\n} // template <class RealType>void test_spots(RealType)\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n  // Check that can generate rayleigh distribution using the two convenience methods:\n   boost::math::rayleigh ray1(1.); // Using typedef\n   rayleigh_distribution<> ray2(1.); // Using default RealType double.\n\n  using namespace boost::math::constants;\n   // Basic sanity-check spot values.\n\n  // Double only tests.\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::pdf(\n      rayleigh_distribution<double>(1.),\n      static_cast<double>(1)), // x\n      static_cast<double>(exp_minus_half<double>()), // p\n         1e-15); // %\n\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::pdf(\n      rayleigh_distribution<double>(0.5),\n      static_cast<double>(0.5)), // x\n      static_cast<double>(2 * exp_minus_half<double>()), // p\n         1e-15); // %\n\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::pdf(\n      rayleigh_distribution<double>(2.),\n      static_cast<double>(2)), // x\n      static_cast<double>(exp_minus_half<double>() /2 ), // p\n         1e-15); // %\n\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::cdf(\n      rayleigh_distribution<double>(1.),\n      static_cast<double>(1)), // x\n      static_cast<double>(1- exp_minus_half<double>()), // p\n         1e-15); // %\n\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::cdf(\n      rayleigh_distribution<double>(2.),\n      static_cast<double>(2)), // x\n      static_cast<double>(1- exp_minus_half<double>()), // p\n         1e-15); // %\n\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::cdf(\n      rayleigh_distribution<double>(3.),\n      static_cast<double>(3)), // x\n      static_cast<double>(1- exp_minus_half<double>()), // p\n         1e-15); // %\n\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::cdf(\n      rayleigh_distribution<double>(4.),\n      static_cast<double>(4)), // x\n      static_cast<double>(1- exp_minus_half<double>()), // p\n         1e-15); // %\n\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::cdf(complement(\n      rayleigh_distribution<double>(4.),\n      static_cast<double>(4))), // x\n      static_cast<double>(exp_minus_half<double>()), // q = 1 - p\n         1e-15); // %\n\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::quantile(\n      rayleigh_distribution<double>(4.),\n      static_cast<double>(1- exp_minus_half<double>())), // x\n      static_cast<double>(4), // p\n         1e-15); // %\n\n   BOOST_CHECK_CLOSE_FRACTION(\n      ::boost::math::quantile(complement(\n      rayleigh_distribution<double>(4.),\n      static_cast<double>(exp_minus_half<double>()))), // x\n      static_cast<double>(4), // p\n         1e-15); // %\n\n   // (Parameter value, arbitrarily zero, only communicates the floating point type).\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %\n  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n  test_spots(0.0L); // Test long double.\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\n#endif\n#else\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\n      \"either because the long double overloads of the usual math functions are \"\n      \"not available at all, or because they are too inaccurate for these tests \"\n      \"to pass.</note>\" << std::endl;\n#endif\n\n   \n} // BOOST_AUTO_TEST_CASE( test_main )\n\n/*\n\nOutput is:\n\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\test_rayleigh.exe\"\nRunning 1 test case...\nTolerance for type float is 0.000119209 %\nTolerance for type double is 2.22045e-013 %\nTolerance for type long double is 2.22045e-013 %\nTolerance for type class boost::math::concepts::real_concept is 2.22045e-013 %\n*** No errors detected\n\n*/\n\n\n", "meta": {"hexsha": "242ec32f491a5aecaf80e9fccec71fefaa9ebb64", "size": 11263, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_rayleigh.cpp", "max_stars_repo_name": "btzy/boost-1.72.0-mirror", "max_stars_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-01T03:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T03:04:05.000Z", "max_issues_repo_path": "libs/math/test/test_rayleigh.cpp", "max_issues_repo_name": "btzy/boost-1.72.0-mirror", "max_issues_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/test/test_rayleigh.cpp", "max_forks_repo_name": "btzy/boost-1.72.0-mirror", "max_forks_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8228228228, "max_line_length": 140, "alphanum_fraction": 0.6368640682, "num_tokens": 2925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5806725618364282}}
{"text": "\n#include <stdlib.h>\n#include <boost/test/unit_test.hpp>\n#include \"sphere_shape.h\"\n#include \"octree.h\"\n\nBOOST_AUTO_TEST_SUITE (test_octree)\n\nBOOST_AUTO_TEST_CASE (test_subcluster_bounds)\n{\n\tspatial::Octree octree(math::aabb<3>(math::vec<3>(-1, -1, -1), math::vec<3>(1, 1, 1)));\n\n\t{\n\t\tmath::aabb<3> bounds = octree.get_subcluster_bounds(0);\n\t\tBOOST_REQUIRE ((bounds.lo - math::vec<3>(-1, -1, -1)).length_sq() < math::EPSILON);\n\t\tBOOST_REQUIRE ((bounds.hi - math::vec<3>(0, 0, 0)).length_sq() < math::EPSILON);\n\t}\n\n\t{\n\t\tmath::aabb<3> bounds = octree.get_subcluster_bounds(1);\n\t\tBOOST_REQUIRE ((bounds.lo - math::vec<3>(0, -1, -1)).length_sq() < math::EPSILON);\n\t\tBOOST_REQUIRE ((bounds.hi - math::vec<3>(1, 0, 0)).length_sq() < math::EPSILON);\n\t}\n\n\t{\n\t\tmath::aabb<3> bounds = octree.get_subcluster_bounds(2);\n\t\tBOOST_REQUIRE ((bounds.lo - math::vec<3>(-1, 0, -1)).length_sq() < math::EPSILON);\n\t\tBOOST_REQUIRE ((bounds.hi - math::vec<3>(0, 1, 0)).length_sq() < math::EPSILON);\n\t}\n\n\t{\n\t\tmath::aabb<3> bounds = octree.get_subcluster_bounds(3);\n\t\tBOOST_REQUIRE ((bounds.lo - math::vec<3>(0, 0, -1)).length_sq() < math::EPSILON);\n\t\tBOOST_REQUIRE ((bounds.hi - math::vec<3>(1, 1, 0)).length_sq() < math::EPSILON);\n\t}\n\n\t{\n\t\tmath::aabb<3> bounds = octree.get_subcluster_bounds(4);\n\t\tBOOST_REQUIRE ((bounds.lo - math::vec<3>(-1, -1, 0)).length_sq() < math::EPSILON);\n\t\tBOOST_REQUIRE ((bounds.hi - math::vec<3>(0, 0, 1)).length_sq() < math::EPSILON);\n\t}\n\n\t{\n\t\tmath::aabb<3> bounds = octree.get_subcluster_bounds(5);\n\t\tBOOST_REQUIRE ((bounds.lo - math::vec<3>(0, -1, 0)).length_sq() < math::EPSILON);\n\t\tBOOST_REQUIRE ((bounds.hi - math::vec<3>(1, 0, 1)).length_sq() < math::EPSILON);\n\t}\n\n\t{\n\t\tmath::aabb<3> bounds = octree.get_subcluster_bounds(6);\n\t\tBOOST_REQUIRE ((bounds.lo - math::vec<3>(-1, 0, 0)).length_sq() < math::EPSILON);\n\t\tBOOST_REQUIRE ((bounds.hi - math::vec<3>(0, 1, 1)).length_sq() < math::EPSILON);\n\t}\n\n\t{\n\t\tmath::aabb<3> bounds = octree.get_subcluster_bounds(7);\n\t\tBOOST_REQUIRE ((bounds.lo - math::vec<3>(0, 0, 0)).length_sq() < math::EPSILON);\n\t\tBOOST_REQUIRE ((bounds.hi - math::vec<3>(1, 1, 1)).length_sq() < math::EPSILON);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE (test_subcluster_by_point)\n{\n\tspatial::Octree octree(math::aabb<3>(math::vec<3>(-10, -100, -1000), math::vec<3>(10, 100, 1000)));\n\n\tfor (size_t i = 0; i < 1000; i++)\n\t{\n\t\tmath::vec<3> v(math::scalar((rand() % 20) - 10), math::scalar((rand() % 200) - 100),\n\t\t\tmath::scalar((rand() % 2000) - 1000));\n\n\t\tunsigned index = octree.get_subcluster_by_point(v);\n\t\tmath::aabb<3> bounds = octree.get_subcluster_bounds(index);\n\n\t\tBOOST_REQUIRE (bounds.contains(v));\n\t}\n}\n\nBOOST_AUTO_TEST_CASE (test_subclusters_mask_by_aabb)\n{\n\tspatial::Octree octree(math::aabb<3>(math::vec<3>(-5, -5, -5), math::vec<3>(5, 5, 5)));\n\n\t// -2,-2 -1,-2 | +1,-2 +2,-2\n    // -2,-1 -1,-1 | +1,-1 +2,-1\n\t// ------------+------------\n    // -2,+1 -1,+1 | +1,+1 +2,+1\n    // -2,+1 -1,+2 | +1,+1 +2,+2\n\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, -2, -2), math::vec<3>(-1, -1, -1))) == 1);\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(1, -2, -2), math::vec<3>(2, -1, -1))) == 2);\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, 1, -2), math::vec<3>(-1, 2, -1))) == 4);\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(1, 1, -2), math::vec<3>(2, 2, -1))) == 8);\n\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, -2, 1), math::vec<3>(-1, -1, 2))) == 16);\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(1, -2, 1), math::vec<3>(2, -1, 2))) == 32);\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, 1, 1), math::vec<3>(-1, 2, 2))) == 64);\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(1, 1, 1), math::vec<3>(2, 2, 2))) == 128);\n\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, -2, -2), math::vec<3>(2, -1, -1))) == (1 | 2));\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, -2, -2), math::vec<3>(-1, 2, -1))) == (1 | 4));\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(1, -2, -2), math::vec<3>(2, 2, -1))) == (2 | 8));\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, 1, -2), math::vec<3>(2, 2, -1))) == (4 | 8));\n\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, -2, 1), math::vec<3>(2, -1, 2))) == (16 | 32));\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, -2, 1), math::vec<3>(-1, 2, 2))) == (16 | 64));\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(1, -2, 1), math::vec<3>(2, 2, 2))) == (32 | 128));\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, 1, 1), math::vec<3>(2, 2, 2))) == (64 | 128));\n\n\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, -2, -2), math::vec<3>(2, 2, -1))) == (1 | 2 | 4 | 8));\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, -2, 1), math::vec<3>(2, 2, 2))) == (16 | 32 | 64 | 128));\n\n\tBOOST_REQUIRE (octree.get_subclusters_mask_by_aabb(math::aabb<3>(math::vec<3>(-2, -2, -2), math::vec<3>(2, 2, 2))) == (1 | 2 | 4 | 8 | 16 | 32 | 64 | 128));\n}\n\nBOOST_AUTO_TEST_CASE (test_intersect_correctness_1)\n{\n\tspatial::Octree octree(math::aabb<3>(math::vec<3>(-1, -1, -1), math::vec<3>(1, 1, 1)));\n\n\tstd::vector<spatial::ShapePtr> shapes;\n\tshapes.reserve(8);\n\n\tshapes.push_back(spatial::ShapePtr(new spatial::SphereShape(math::vec<3>(-0.5f, -0.5f, -0.5f), 0.1f)));\n\toctree.add_shape(shapes.back());\n\n\tshapes.push_back(spatial::ShapePtr(new spatial::SphereShape(math::vec<3>( 0.5f, -0.5f, -0.5f), 0.1f)));\n\toctree.add_shape(shapes.back());\n\n\tshapes.push_back(spatial::ShapePtr(new spatial::SphereShape(math::vec<3>(-0.5f,  0.5f, -0.5f), 0.1f)));\n\toctree.add_shape(shapes.back());\n\n\tshapes.push_back(spatial::ShapePtr(new spatial::SphereShape(math::vec<3>( 0.5f,  0.5f, -0.5f), 0.1f)));\n\toctree.add_shape(shapes.back());\n\n\tshapes.push_back(spatial::ShapePtr(new spatial::SphereShape(math::vec<3>(-0.5f, -0.5f,  0.5f), 0.1f)));\n\toctree.add_shape(shapes.back());\n\n\tshapes.push_back(spatial::ShapePtr(new spatial::SphereShape(math::vec<3>( 0.5f, -0.5f,  0.5f), 0.1f)));\n\toctree.add_shape(shapes.back());\n\n\tshapes.push_back(spatial::ShapePtr(new spatial::SphereShape(math::vec<3>(-0.5f,  0.5f,  0.5f), 0.1f)));\n\toctree.add_shape(shapes.back());\n\n\tshapes.push_back(spatial::ShapePtr(new spatial::SphereShape(math::vec<3>(0.5f,  0.5f,  0.5f), 0.1f)));\n\toctree.add_shape(shapes.back());\n\n\toctree.build_subclusters();\n\n\tfor (size_t i = 0; i < 100; i++)\n\t{\n\t\tmath::vec<3> centre(math::random(-1, 1), math::random(-1, 1),\n\t\t\tmath::random(-1, 1));\n\t\tmath::scalar radius = math::scalar(rand()) / RAND_MAX;\n\n\t\tboost::shared_ptr<spatial::SphereShape> shape(new spatial::SphereShape(centre, radius));\n\n\t\tspatial::ResultSetPtr result(new spatial::ResultSet());\n\t\toctree.query_intersection(shape, result);\n\n\t\tfor (size_t j = 0; j < shapes.size(); j++)\n\t\t{\n\t\t\tbool p1 = shapes[j]->test_intersection(shape.get());\n\t\t\tbool p2 = result->have(shapes[j]);\n\n\t\t\tBOOST_REQUIRE (p1 == p2);\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE (test_intersect_correctness_2)\n{\n\tspatial::Octree octree(math::aabb<3>(math::vec<3>(-1, -1, -1), math::vec<3>(1, 1, 1)));\n\n\tstatic size_t const N = 500;\n\tstatic size_t const M = 100;\n\n\tstd::vector<spatial::ShapePtr> shapes;\n\tshapes.reserve(N);\n\n\tfor (size_t i = 0; i < N; i++)\n\t{\n\t\tmath::vec<3> centre(math::random(-1, 1), math::random(-1, 1),\n\t\t\tmath::random(-1, 1));\n\t\tmath::scalar radius = math::scalar(rand()) / RAND_MAX;\n\n\t\tshapes.push_back(spatial::ShapePtr(new spatial::SphereShape(centre, radius)));\n\t\toctree.add_shape(shapes.back());\n\t}\n\n\tfor (size_t i = 0; i < M; i++)\n\t{\n\t\tmath::vec<3> centre(math::random(-1, 1), math::random(-1, 1),\n\t\t\tmath::random(-1, 1));\n\t\tmath::scalar radius = math::scalar(rand()) / RAND_MAX;\n\n\t\tspatial::ShapePtr shape(new spatial::SphereShape(centre, radius));\n\n\t\tspatial::ResultSetPtr result(new spatial::ResultSet());\n\t\toctree.query_intersection(shape, result);\n\n\t\tfor (size_t j = 0; j < N; j++)\n\t\t{\n\t\t\tbool p1 = shapes[j]->test_intersection(shape.get());\n\t\t\tbool p2 = result->have(shapes[j]);\n\n\t\t\tBOOST_REQUIRE (p1 == p2);\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE (test_remove_correctness)\n{\n\tspatial::Octree octree(math::aabb<3>(math::vec<3>(-1, -1, -1), math::vec<3>(1, 1, 1)));\n\n\tstatic size_t const N = 500;\n\tstatic size_t const M = 100;\n\n\tstd::vector<spatial::ShapePtr> shapes;\n\tshapes.reserve(N);\n\n\tfor (size_t i = 0; i < N; i++)\n\t{\n\t\tmath::vec<3> centre(math::random(-1, 1), math::random(-1, 1),\n\t\t\tmath::random(-1, 1));\n\t\tmath::scalar radius = math::scalar(rand()) / RAND_MAX;\n\n\t\tshapes.push_back(spatial::ShapePtr(new spatial::SphereShape(centre, radius)));\n\t\toctree.add_shape(shapes.back());\n\t}\n\n\t{\n\t\tstd::vector<spatial::ShapePtr> shapes_clone;\n\t\tshapes_clone.swap(shapes);\n\n\t\tshapes.reserve(N);\n\n\t\tfor (size_t i = 0; i < N; i++)\n\t\t{\n\t\t\tif (rand() & 1)\n\t\t\t{\n\t\t\t\tshapes.push_back(shapes_clone[i]);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\toctree.remove_shape(shapes_clone[i]);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (size_t i = 0; i < M; i++)\n\t{\n\t\tmath::vec<3> centre(math::random(-1, 1), math::random(-1, 1),\n\t\t\tmath::random(-1, 1));\n\t\tmath::scalar radius = math::scalar(rand()) / RAND_MAX;\n\n\t\tspatial::ShapePtr shape(new spatial::SphereShape(centre, radius));\n\n\t\tspatial::ResultSetPtr result(new spatial::ResultSet());\t\toctree.query_intersection(shape, result);\n\n\t\tfor (size_t j = 0; j < shapes.size(); j++)\n\t\t{\n\t\t\tbool p1 = shapes[j]->test_intersection(shape.get());\n\t\t\tbool p2 = result->have(shapes[j]);\n\n\t\t\tBOOST_REQUIRE (p1 == p2);\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE (test_move_correctness)\n{\n\tspatial::Octree octree(math::aabb<3>(math::vec<3>(-1, -1, -1), math::vec<3>(1, 1, 1)));\n\n\tstatic size_t const N = 500;\n\tstatic size_t const M = 100;\n\n\tstd::vector<spatial::ShapePtr> shapes;\n\tshapes.reserve(N);\n\n\tfor (size_t i = 0; i < N; i++)\n\t{\n\t\tmath::vec<3> centre(math::random(-1, 1), math::random(-1, 1),\n\t\t\tmath::random(-1, 1));\n\t\tmath::scalar radius = math::scalar(rand()) / RAND_MAX;\n\n\t\tshapes.push_back(spatial::ShapePtr(new spatial::SphereShape(centre, radius)));\n\t\toctree.add_shape(shapes.back());\n\t}\n\n\tfor (size_t i = 0; i < N; i++)\n\t{\n\t\tif (rand() & 1)\n\t\t{\n\t\t\tspatial::SphereShape *shape = static_cast<spatial::SphereShape *>(shapes[i].get());\n\n\t\t\tmath::aabb<3> old_bounds = shape->get_bounds();\n\n\t\t\tshape->centre += math::vec<3>(math::random(-1, 1),\n\t\t\t\tmath::random(-1, 1),\n\t\t\t\tmath::random(-1, 1));\n\n\t\t\tshape->radius *= math::random(0, 2);\n\n\t\t\toctree.post_move_shape(shapes[i], old_bounds);\n\t\t}\n\t}\n\n\tfor (size_t i = 0; i < M; i++)\n\t{\n\t\tmath::vec<3> centre(math::random(-1, 1), math::random(-1, 1),\n\t\t\tmath::random(-1, 1));\n\t\tmath::scalar radius = math::scalar(rand()) / RAND_MAX;\n\n\t\tspatial::ShapePtr shape(new spatial::SphereShape(centre, radius));\n\n\t\tspatial::ResultSetPtr result(new spatial::ResultSet());\n\t\toctree.query_intersection(shape, result);\n\n\t\tfor (size_t j = 0; j < shapes.size(); j++)\n\t\t{\n\t\t\tbool p1 = shapes[j]->test_intersection(shape.get());\n\t\t\tbool p2 = result->have(shapes[j]);\n\n\t\t\tBOOST_REQUIRE (p1 == p2);\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE (test_add_shape_result)\n{\n\tspatial::Octree octree(math::aabb<3>(math::vec<3>(-1, -1, -1), math::vec<3>(1, 1, 1)));\n\n\tstatic size_t const N = 500;\n\tstatic size_t const M = 100;\n\n\tstd::vector<spatial::ShapePtr> shapes;\n\tshapes.reserve(N);\n\n\tfor (size_t i = 0; i < N; i++)\n\t{\n\t\tmath::vec<3> centre(math::random(-1, 1), math::random(-1, 1),\n\t\t\tmath::random(-1, 1));\n\t\tmath::scalar radius = math::scalar(rand()) / RAND_MAX;\n\n\t\tspatial::ShapePtr shape(new spatial::SphereShape(centre, radius));\n\t\tshapes.push_back(shape);\n\n\t\t // result may not contain original shape\n\t\tspatial::ResultSetPtr result(new spatial::ResultSet());\n\t\toctree.add_shape(shape, result);\n\n\t\tfor (size_t j = 0; j < i; j++)\n\t\t{\n\t\t\tbool p1 = shapes[j]->test_intersection(shape.get());\n\t\t\tbool p2 = result->have(shapes[j]);\n\n\t\t\tBOOST_REQUIRE (p1 == p2);\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE (test_move_result)\n{\n\tspatial::Octree octree(math::aabb<3>(math::vec<3>(-1, -1, -1), math::vec<3>(1, 1, 1)));\n\n\tstatic size_t const N = 500;\n\tstatic size_t const M = 100;\n\n\tstd::vector<spatial::ShapePtr> shapes;\n\tshapes.reserve(N);\n\n\tfor (size_t i = 0; i < N; i++)\n\t{\n\t\tmath::vec<3> centre(math::random(-1, 1), math::random(-1, 1),\n\t\t\tmath::random(-1, 1));\n\t\tmath::scalar radius = math::scalar(rand()) / RAND_MAX;\n\n\t\tshapes.push_back(spatial::ShapePtr(new spatial::SphereShape(centre, radius)));\n\t\toctree.add_shape(shapes.back());\n\t}\n\n\tfor (size_t i = 0; i < N; i++)\n\t{\n\t\tspatial::SphereShape *shape = static_cast<spatial::SphereShape *>(shapes[i].get());\n\n\t\tmath::aabb<3> old_bounds = shape->get_bounds();\n\n\t\tshape->centre += math::vec<3>(math::random(-1, 1), math::random(-1, 1), math::random(-1, 1));\n\t\tshape->radius *= math::random(0, 2);\n\n\t\tspatial::ResultSetPtr result(new spatial::ResultSet());\n\t\toctree.post_move_shape(shapes[i], old_bounds, result);\n\n\t\tfor (size_t j = 0; j < i; j++)\n\t\t{\n\t\t\tbool p1 = shapes[j]->test_intersection(shape);\n\t\t\tbool p2 = result->have(shapes[j]);\n\n\t\t\tBOOST_REQUIRE (p1 == p2);\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "047bb01ad244d9cb9c458b8177439d14cfb876e8", "size": 13311, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/spatial/test_octree.cc", "max_stars_repo_name": "mnvl/scratch", "max_stars_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T11:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-15T11:55:32.000Z", "max_issues_repo_path": "src/spatial/test_octree.cc", "max_issues_repo_name": "mnvl/scratch", "max_issues_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spatial/test_octree.cc", "max_forks_repo_name": "mnvl/scratch", "max_forks_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.948019802, "max_line_length": 157, "alphanum_fraction": 0.6344376831, "num_tokens": 4837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5806348229482611}}
{"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 * @file scaling_test.cpp\n *\n * Tests for Scaling of dataset.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/core/data/scaler_methods/pca_whitening.hpp>\n#include <mlpack/core/data/scaler_methods/zca_whitening.hpp>\n#include <mlpack/core/data/scaler_methods/min_max_scaler.hpp>\n#include <mlpack/core/data/scaler_methods/max_abs_scaler.hpp>\n#include <mlpack/core/data/scaler_methods/standard_scaler.hpp>\n#include <mlpack/core/data/scaler_methods/mean_normalization.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::data;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(ScalingTest);\n\narma::mat dataset = \"-1 -0.5 0 1;\"\n                    \"2 6 10 18;\";\narma::mat scaleddataset;\narma::mat temp;\n\n/**\n * Test For MinMax Scaler Class.\n */\nBOOST_AUTO_TEST_CASE(MinMaxScalerTest)\n{\n  arma::mat scaled = \"0 0.2500 0.5000 1.000;\"\n                     \"0 0.2500 0.5000 1.000;\";\n  data::MinMaxScaler scale;\n  scale.Fit(dataset);\n  scale.Transform(dataset, scaleddataset);\n  scale.InverseTransform(scaleddataset, temp);\n  CheckMatrices(scaleddataset, scaled);\n  CheckMatrices(dataset, temp);\n}\n\n/**\n * Test For MaxAbs Scaler Class.\n */\nBOOST_AUTO_TEST_CASE(MaxAbsScalerTest)\n{\n  arma::mat scaled = \"-1 -0.5 0 1;\"\n                     \"0.1111111111 0.3333333333 0.55555556 1.0000;\";\n  data::MaxAbsScaler scale;\n  scale.Fit(dataset);\n  scale.Transform(dataset, scaleddataset);\n  scale.InverseTransform(scaleddataset, temp);\n  CheckMatrices(scaleddataset, scaled);\n  CheckMatrices(dataset, temp);\n}\n\n/**\n * Test For Standard Scaler Class.\n */\nBOOST_AUTO_TEST_CASE(StandardScalerTest)\n{\n  arma::mat scaled = \"-1.18321596 -0.50709255  0.16903085 1.52127766;\"\n                     \"-1.18321596 -0.50709255  0.16903085 1.52127766;\";\n  data::StandardScaler scale;\n  scale.Fit(dataset);\n  scale.Transform(dataset, scaleddataset);\n  scale.InverseTransform(scaleddataset, temp);\n  CheckMatrices(scaleddataset, scaled);\n  CheckMatrices(dataset, temp);\n}\n\n/**\n * Test For MeanNormalization Scaler Class.\n */\nBOOST_AUTO_TEST_CASE(MeanNormalizationTest)\n{\n  arma::mat scaled = \"-0.43750000000 -0.187500000 0.062500000 0.562500000;\"\n                     \"-0.43750000000 -0.187500000 0.062500000 0.562500000;\";\n  data::MeanNormalization scale;\n  scale.Fit(dataset);\n  scale.Transform(dataset, scaleddataset);\n  scale.InverseTransform(scaleddataset, temp);\n  CheckMatrices(scaleddataset, scaled);\n  CheckMatrices(dataset, temp);\n}\n\n/**\n * Test to pass same matrix as input and output\n */\nBOOST_AUTO_TEST_CASE(SameInputOutputTest)\n{\n  temp = dataset;\n  arma::mat scaled = \"-0.43750000000 -0.187500000 0.062500000 0.562500000;\"\n                     \"-0.43750000000 -0.187500000 0.062500000 0.562500000;\";\n  data::MeanNormalization scale;\n  scale.Fit(temp);\n  scale.Transform(temp, temp);\n  CheckMatrices(scaled, temp);\n  scale.InverseTransform(temp, temp);\n  CheckMatrices(dataset, temp);\n}\n\n/**\n * Test for Zero Matrix.\n */\nBOOST_AUTO_TEST_CASE(ZeroMatrixTest)\n{\n  arma::mat input(2, 4, arma::fill::zeros);\n  data::MeanNormalization scale;\n  scale.Fit(input);\n  scale.Transform(input, temp);\n  CheckMatrices(input, temp);\n  scale.InverseTransform(input, temp);\n  CheckMatrices(input, temp);\n}\n\n/**\n * Test for Zero Scale.\n */\nBOOST_AUTO_TEST_CASE(ZeroScaleTest)\n{\n  dataset = \"1 1 1 1;\"\n            \"2 6 10 18;\";\n  arma::mat scaled = \"0 0 0 0;\"\n                     \"0 0.2500 0.5000 1.000;\";\n  data::MinMaxScaler scale;\n  scale.Fit(dataset);\n  scale.Transform(dataset, scaleddataset);\n  scale.InverseTransform(scaleddataset, temp);\n  CheckMatrices(scaleddataset, scaled);\n  CheckMatrices(dataset, temp);\n}\n\n/**\n * Test for PCA whitening Scale.\n */\nBOOST_AUTO_TEST_CASE(PCAWhiteningTest)\n{\n  data::PCAWhitening scale;\n  arma::mat output;\n  scale.Fit(dataset);\n  scale.Transform(dataset, output);\n  arma::vec diagonals = (mlpack::math::ColumnCovariance(output)).diag();\n  // Checking covarience is close to 1.0\n  double ccovsum = 0.0;\n  for (size_t i = 0; i < diagonals.n_elem; i++)\n    ccovsum += diagonals(i);\n  BOOST_REQUIRE_CLOSE(ccovsum, 1.0, 1e-3);\n  scale.InverseTransform(output, temp);\n  CheckMatrices(dataset, temp);\n}\n\n/**\n * Test for ZCA whitening Scale.\n */\nBOOST_AUTO_TEST_CASE(ZCAWhiteningTest)\n{\n  data::ZCAWhitening scale;\n  arma::mat output;\n  scale.Fit(dataset);\n  scale.Transform(dataset, output);\n  arma::vec diagonals = (mlpack::math::ColumnCovariance(output)).diag();\n  // Check that the covariance is close to 1.0.\n  double ccovsum = 0.0;\n  for (size_t i = 0; i < diagonals.n_elem; i++)\n    ccovsum += diagonals(i);\n  BOOST_REQUIRE_CLOSE(ccovsum, 1.0, 1e-3);\n  scale.InverseTransform(output, temp);\n  CheckMatrices(dataset, temp);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "280fce85d256f8cf5f33421644b46b29c27f1652", "size": 5010, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/scaling_test.cpp", "max_stars_repo_name": "tomjpsun/mlpack", "max_stars_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-11T14:14:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T14:14:30.000Z", "max_issues_repo_path": "src/mlpack/tests/scaling_test.cpp", "max_issues_repo_name": "tomjpsun/mlpack", "max_issues_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-10T17:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-11T14:56:25.000Z", "max_forks_repo_path": "src/mlpack/tests/scaling_test.cpp", "max_forks_repo_name": "tomjpsun/mlpack", "max_forks_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9888268156, "max_line_length": 78, "alphanum_fraction": 0.7069860279, "num_tokens": 1433, "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// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a\n// component of the Texas A&M University System.\n\n// All rights reserved.\n\n// The information and source code contained herein is the exclusive\n// property of TEES and may not be disclosed, examined or reproduced\n// in whole or in part without explicit written authorization from TEES.\n*/\n\n#include <stapl/containers/sequential/graph/bgl_undirected_graph_adapter.hpp>\n#include <stapl/containers/sequential/graph/algorithms/graph_algo.h>\n#include <stapl/containers/sequential/graph/algorithms/find_cycle.h>\n#include <stapl/containers/sequential/graph/algorithms/connected_components.h>\n#include <stapl/containers/sequential/graph/algorithms/dijkstra.h>\n#include \"test_util.h\"\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/unordered_map.hpp>\n#include <papi.h>\n\nusing namespace boost;\nusing namespace stapl;\nusing namespace std;\nusing namespace __gnu_cxx;\n\nnamespace dijkstra_test {\n\ntemplate <class G, class ColorMap>\nvoid dijkstra_test_core_graph(G& g, ColorMap& cmap){\n  typedef typename G::vertex_descriptor VD;\n  stapl::graph<stapl::DIRECTED,stapl::NONMULTIEDGES,typename G::vertex_property, double> sssptree;\n  \n  bool err;\n  err=false;\n  \n  double tw1, tw2, tw3, tw4, tw5;\n\n  // Initialize the library\n  PAPI_library_init(PAPI_VER_CURRENT);\n\n\t\t/////////////////STAPL_ALGO ON STAPL_GRAPH///////////////////////////////////  \n  long_long t = PAPI_get_real_usec();\n\n\t\tvector<VD> parentmap(g.get_num_vertices());\n\t\tvector<double> weightmap(g.get_num_vertices());\n\n  dijkstra_sssp(g, parentmap, weightmap, 0);\n  t = PAPI_get_real_usec() - t;\n  std::cout <<\"\\t\"<< t << \", \"; \n\n\t\tstapl::convert_to_graph(parentmap, weightmap, sssptree);\n\n  cmap.reset();\n  if((sssptree.get_num_vertices() == g.get_num_vertices())\n     && (sssptree.get_num_vertices() == sssptree.get_num_edges()+1)\n     && (is_cycle(sssptree, cmap) == false)) {\n    cmap.reset();\n    if (get_cc_count(sssptree, cmap) == 1) {\n      tw1 = total_weight(sssptree);\n      cout<<\"<PASSED>\\t\"; // << endl;\n    }\n  } else {\n    cout<<\"{FAILED}\\t\";\n    cmap.reset();\n  }\n  if(N < 15) display1(sssptree);\n\n\t\t/////////////////BGL_ALGO ON STAPL_GRAPH///////////////////////////////////  \n  std::vector < typename G::vertex_descriptor >\n    p(g.get_num_vertices());\n\n  typedef boost::unordered_map<size_t, int> map_type;\n  //typedef std::map<size_t, int> map_type;\n  map_type distances(g.get_num_vertices());  // better performance.\n  boost::associative_property_map<map_type> dist_map(distances);\n\n  {\n    using namespace boost;\n\n\t\t\t\t// boost::property_map<G, edge_weight_t>::type weightmap = boost::get(edge_weight, g);\n\t\t\t\t// boost::property_map<G, vertex_distance_t>::type dist_map = get(vertex_distance, g);\n\t\t\n\t\t\t\tstd::vector<typename G::edge_property> weights_map(g.get_num_edges());\n\t\t\t\tfor (typename G::edge_iterator ei = g.edges_begin(); ei != g.edges_end(); ++ei)\n\t\t\t\t\t\tweights_map[ei.descriptor().id()] = ei.property();\n\n\t\t\t\tvector<typename G::edge_property>* w_vec_ptr = const_cast<vector<typename G::edge_property>* >(&weights_map);\n\n\t\t\t\tPAPI_library_init(PAPI_VER_CURRENT);\n\t\t\t\tlong_long t = PAPI_get_real_usec();\n\n\t\t\t\tstd::less<double> lsop;\n\t\t\t\tstd::plus<double> combine;\n\n\t\t\t\tdijkstra_shortest_paths\n\t\t\t\t\t\t(g, *vertices(g).first, &p[0], dist_map,\n\t\t\t\t\t\t\tstapl_graph_edge_wt_id_map<typename G::vertex_property,\n\t\t\t\t\t\t\ttypename G::edge_property>(const_cast<G*>(&g),\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\tw_vec_ptr),\n\t\t\t\t\t\tstapl_graph_id_map<typename G::vertex_property, typename G::edge_property>(),\n\t\t\t\t\t\t\tlsop, combine, std::numeric_limits<double>::max(), 0,\n\t\t\t\t\t\t\tdefault_dijkstra_visitor());\n\n\n    t = PAPI_get_real_usec() - t;\n    std::cout <<\"\\t\"<< t << \", \";\n\n    stapl::graph<stapl::DIRECTED,stapl::MULTIEDGES,typename G::vertex_property, int> boost_out_graph;\n    convert_to_graph(p, distances, boost_out_graph);\n    \n    cmap.reset();\n    if((boost_out_graph.get_num_vertices() == g.get_num_vertices())\n       && (boost_out_graph.get_num_vertices() == boost_out_graph.get_num_edges()+1)\n       && (is_cycle(boost_out_graph, cmap) == false)) {\n      cmap.reset();\n      if (get_cc_count(boost_out_graph, cmap) == 1) {\n        tw3 = total_weight(boost_out_graph);\n        cout<<\"<PASSED>\\t\"; // << endl;\n      }\n    } else {\n      cout<<\"{FAILED}\\t\";\n      cmap.reset();\n    }\n    if(N < 15) display2(boost_out_graph);\n  }\n\n  /////////////////BGL_ALGO ON BGL_GRAPH///////////////////////////////////  \n  {\n    using namespace boost;\n    typedef adjacency_list <vecS,\n      vecS,\n      undirectedS,\n      property<vertex_distance_t, int>,\n      property <edge_weight_t, double> > BOOST_GRAPH;\n    \n    BOOST_GRAPH bg;\n    \n    property_map<BOOST_GRAPH, edge_weight_t>::type weightmap;\n    generate_boost_graph_from_stapl(g, bg, weightmap);\n    \n    PAPI_library_init(PAPI_VER_CURRENT);\n    long_long t = PAPI_get_real_usec();\n    std::vector < graph_traits < BOOST_GRAPH >::vertex_descriptor >\n      parentmap(num_vertices(bg));\n    property_map<BOOST_GRAPH, vertex_distance_t>::type distmap = get(vertex_distance, bg);\n    property_map<BOOST_GRAPH, vertex_index_t>::type indexmap = get(vertex_index, bg);\n    \n    \n    std::less<double> lsop;\n    // detail::_project2nd<double,double> combine;  // for Prim's MST.\n    std::plus<double> combine;\n    \n    dijkstra_shortest_paths\n      (bg, *vertices(bg).first, &parentmap[0], distmap, weightmap, indexmap,\n       lsop, combine, std::numeric_limits<double>::max(), 0,\n       default_dijkstra_visitor());\n    \n    t = PAPI_get_real_usec() - t;\n    std::cout << \"\\t\"<< t << \", \";\n    \n    stapl::graph<stapl::DIRECTED,stapl::MULTIEDGES,typename G::vertex_property, int> boost_out_graph1;\n    convert_to_graph(parentmap, distmap, boost_out_graph1);\n    \n    cmap.reset();\n    if((boost_out_graph1.get_num_vertices() == g.get_num_vertices())\n       && (boost_out_graph1.get_num_vertices() == boost_out_graph1.get_num_edges()+1)\n       && (is_cycle(boost_out_graph1, cmap) == false)) {\n      cmap.reset();\n      if (get_cc_count(boost_out_graph1, cmap) == 1) {\n        tw5 = total_weight(boost_out_graph1);\n        cout<<\"<PASSED>\\t\"; // << endl;\n      }\n    } else {\n      cout<<\"{FAILED}\\t\";\n      cmap.reset();\n    }\n    if(N < 15) display1(boost_out_graph1);\n  }\n\t\t  \n  cout << endl;\n  cout << tw1 << \", \"  << tw2 << \", \"  << tw3 /*<< \", \" << tw4 */ << \", \"  << tw5 << \"\\n\"; \n}\n\n}  // end namespace dijkstra_test\n", "meta": {"hexsha": "e31474ca718f9b98c014ba7115bd99235c6a51e3", "size": 6430, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/test/containers/sequential/graph/test_dijkstra.cc", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stapl_release/test/containers/sequential/graph/test_dijkstra.cc", "max_issues_repo_name": "parasol-ppl/PPL_utils", "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stapl_release/test/containers/sequential/graph/test_dijkstra.cc", "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5698924731, "max_line_length": 113, "alphanum_fraction": 0.6556765163, "num_tokens": 1692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629214, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5806348083768519}}
{"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": "// Copyright Oleg Maximenko 2014.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n// See http://github.com/svgpp/svgpp for library home page.\n\n#pragma once\n\n#include <svgpp/definitions.hpp>\n#include <svgpp/utility/gil/common.hpp>\n#include <boost/gil/channel_algorithm.hpp>\n#include <boost/gil/color_base_algorithm.hpp>\n\nnamespace svgpp \n{ \n\nnamespace gil_detail \n{\n\nnamespace gil = boost::gil;\n\ntemplate<class CompositeModeTag, class ChannelValue>\nstruct composite_channel_fn;\n\ntemplate<class CompositeModeTag, class ChannelValue>\nstruct composite_alpha_fn;\n\ntemplate<class ChannelValue>\nstruct composite_arithmetic_channel_fn;\n\n// TODO: default implementation for non-8 bit channels\n\n// For signed channels we call unsigned analog, converting forward and back\ntemplate<class CompositeModeTag>\nstruct composite_channel_fn<CompositeModeTag, gil::bits8s>\n{\n  gil::bits8s operator()(gil::bits8s channel_a, gil::bits8s channel_b, gil::bits8s alpha_a, gil::bits8s alpha_b) const\n  {\n    typedef gil::detail::channel_convert_to_unsigned<gil::bits8s> to_unsigned;\n    typedef gil::detail::channel_convert_from_unsigned<gil::bits8s> from_unsigned;\n    composite_channel_fn<CompositeModeTag, gil::bits8> converter_unsigned;\n    return from_unsigned()(converter_unsigned(\n      to_unsigned()(channel_a), to_unsigned()(channel_b), to_unsigned()(alpha_a), to_unsigned()(alpha_b)));\n  }\n};\n\n// Dca' = Sca + Dca x (1 - Sa)\ntemplate<>\nstruct composite_channel_fn<tag::value::over, gil::bits8>\n{\n  gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8(channel_a + channel_b * (255 - alpha_a) / 255);\n  }\n};\n\n// Da'  = Sa + Da - Sa x Da\ntemplate<>\nstruct composite_alpha_fn<tag::value::over, gil::bits8>\n{\n  gil::bits8 operator()(int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8(alpha_a + alpha_b - alpha_a * alpha_b / 255);\n  }\n};\n\n// Dca' = Sca x Da\ntemplate<>\nstruct composite_channel_fn<tag::value::in, gil::bits8>\n{\n  gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return channel_a * alpha_b / 255;\n  }\n};\n\n// Da'  = Sa x Da\ntemplate<>\nstruct composite_alpha_fn<tag::value::in, gil::bits8>\n{\n  gil::bits8 operator()(int alpha_a, int alpha_b) const\n  {\n    return alpha_a * alpha_b / 255;\n  }\n};\n\n// Dca' = Sca x (1 - Da)\ntemplate<>\nstruct composite_channel_fn<tag::value::out, gil::bits8>\n{\n  gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return channel_a * alpha_a * (255 - alpha_b) / 65535;\n  }\n};\n\n// Da'  = Sa x (1 - Da)\ntemplate<>\nstruct composite_alpha_fn<tag::value::out, gil::bits8>\n{\n  gil::bits8 operator()(int alpha_a, int alpha_b) const\n  {\n    return alpha_a * (255 - alpha_b) / 255;\n  }\n};\n\n// Dca' = Sca x Da + Dca x (1 - Sa)\ntemplate<>\nstruct composite_channel_fn<tag::value::atop, gil::bits8>\n{\n  gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return (channel_a * alpha_a + channel_b * (255 - alpha_a)) * alpha_b / 65535;\n  }\n};\n\n// Da'  = Da\ntemplate<>\nstruct composite_alpha_fn<tag::value::atop, gil::bits8>\n{\n  gil::bits8 operator()(gil::bits8 alpha_a, gil::bits8 alpha_b) const\n  {\n    return alpha_b;\n  }\n};\n\n// Dca' = Sca x (1 - Da) + Dca x (1 - Sa)\ntemplate<>\nstruct composite_channel_fn<tag::value::xor_, gil::bits8>\n{\n  gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8((channel_a * alpha_a * (255 - alpha_b) + channel_b * alpha_b * (255 - alpha_a)) / 65535);\n  }\n};\n\n// Da'  = Sa + Da - 2 x Sa x Da\ntemplate<>\nstruct composite_alpha_fn<tag::value::xor_, gil::bits8>\n{\n  gil::bits8 operator()(int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8((alpha_a + alpha_b - 2 * alpha_a * alpha_b) / 255);\n  }\n};\n\n// result = k1*i1*i2 + k2*i1 + k3*i2 + k4\ntemplate<>\nstruct composite_arithmetic_channel_fn<gil::bits8>\n{\n  template<class Coefficient>\n  composite_arithmetic_channel_fn(Coefficient k1, Coefficient k2, Coefficient k3, Coefficient k4)\n    : k1_(k1 * 255), k2_(k2 * 255), k3_(k3 * 255), k4_(k4 * 255)\n  {}\n\n  gil::bits8 operator()(int channel_a, int channel_b) const \n  {\n    return clamp_channel_bits8(k1_ * channel_a * channel_b / 65535 + k2_ * channel_a / 255 + k3_ * channel_b / 255 + k4_);\n  }\n\nprivate:\n  int k1_, k2_, k3_, k4_;\n};\n\n} // namespace gil_detail \n\nnamespace gil_utility \n{\n\nnamespace gil = boost::gil;\n  \ntemplate<class CompositeModeTag>\nstruct composite_pixel\n{\n  template<class Color>\n  Color operator()(const Color & pixa, const Color & pixb) const \n  {\n    typename gil::color_element_type<Color, gil::alpha_t>::type \n      alpha_a = gil::get_color(pixa, gil::alpha_t()),\n      alpha_b = gil::get_color(pixb, gil::alpha_t());\n\n    Color result;\n\n    gil::get_color(result, gil::red_t()) \n      = gil_detail::composite_channel_fn<CompositeModeTag, typename gil::color_element_type<Color, gil::red_t>::type>()(\n        gil::get_color(pixa, gil::red_t()), gil::get_color(pixb, gil::red_t()),\n        alpha_a, alpha_b);\n\n    gil::get_color(result, gil::green_t()) \n      = gil_detail::composite_channel_fn<CompositeModeTag, typename gil::color_element_type<Color, gil::green_t>::type>()(\n        gil::get_color(pixa, gil::green_t()), gil::get_color(pixb, gil::green_t()),\n        alpha_a, alpha_b);\n\n    gil::get_color(result, gil::blue_t()) \n      = gil_detail::composite_channel_fn<CompositeModeTag, typename gil::color_element_type<Color, gil::blue_t>::type>()(\n        gil::get_color(pixa, gil::blue_t()), gil::get_color(pixb, gil::blue_t()),\n        alpha_a, alpha_b);\n\n    gil::get_color(result, gil::alpha_t()) = \n      gil_detail::composite_alpha_fn<CompositeModeTag, typename gil::color_element_type<Color, gil::alpha_t>::type>()(alpha_a, alpha_b);\n\n    return result;\n  }\n};\n\ntemplate<class Color>\nstruct composite_pixel_arithmetic\n{\n  template<class Coefficient>\n  composite_pixel_arithmetic(Coefficient k1, Coefficient k2, Coefficient k3, Coefficient k4)\n    : r_(k1, k2, k3, k4)\n    , g_(k1, k2, k3, k4)\n    , b_(k1, k2, k3, k4)\n    , a_(k1, k2, k3, k4)\n  {}\n\n  Color operator()(const Color & pixa, const Color & pixb) const \n  {\n    Color result;\n    gil::get_color(result, gil::red_t())   = r_(gil::get_color(pixa, gil::red_t())   , gil::get_color(pixb, gil::red_t())   );\n    gil::get_color(result, gil::green_t()) = r_(gil::get_color(pixa, gil::green_t()) , gil::get_color(pixb, gil::green_t()) );\n    gil::get_color(result, gil::blue_t())  = r_(gil::get_color(pixa, gil::blue_t())  , gil::get_color(pixb, gil::blue_t())  );\n    gil::get_color(result, gil::alpha_t()) = r_(gil::get_color(pixa, gil::alpha_t()) , gil::get_color(pixb, gil::alpha_t()) );\n    return result;\n  }\n\nprivate:\n  gil_detail::composite_arithmetic_channel_fn<typename gil::color_element_type<Color, gil::red_t  >::type> r_;\n  gil_detail::composite_arithmetic_channel_fn<typename gil::color_element_type<Color, gil::green_t>::type> g_;\n  gil_detail::composite_arithmetic_channel_fn<typename gil::color_element_type<Color, gil::blue_t >::type> b_;\n  gil_detail::composite_arithmetic_channel_fn<typename gil::color_element_type<Color, gil::alpha_t>::type> a_;\n};\n\n}}\n", "meta": {"hexsha": "45ceeca2a7602d6878c8ecbb1a8267c7a3f25cb7", "size": 7303, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "P0267_RefImpl/Samples/svg/external/svgpp/include/svgpp/utility/gil/composite.hpp", "max_stars_repo_name": "zmm-Embedded/io2d", "max_stars_repo_head_hexsha": "2e53612d60692d70700b4f7d0f9e4e34dbe11388", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "P0267_RefImpl/Samples/svg/external/svgpp/include/svgpp/utility/gil/composite.hpp", "max_issues_repo_name": "zmm-Embedded/io2d", "max_issues_repo_head_hexsha": "2e53612d60692d70700b4f7d0f9e4e34dbe11388", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P0267_RefImpl/Samples/svg/external/svgpp/include/svgpp/utility/gil/composite.hpp", "max_forks_repo_name": "zmm-Embedded/io2d", "max_forks_repo_head_hexsha": "2e53612d60692d70700b4f7d0f9e4e34dbe11388", "max_forks_repo_licenses": ["BSL-1.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.9449152542, "max_line_length": 136, "alphanum_fraction": 0.6946460359, "num_tokens": 2239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.5804691424295978}}
{"text": "#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <complex>\n#include <glog/logging.h>\n#include <math.h>\n\n#include \"theia/math/polynomial.h\"\n#include \"theia/math/rotation.h\"\n\n// for overloaded function in CameraInstrinsicsModel\ntemplate <typename... Args>\nusing overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;\n\nnamespace py = pybind11;\n#include <iostream>\n#include <pybind11/numpy.h>\n#include <vector>\n\nnamespace py = pybind11;\n\nnamespace pytheia {\nnamespace math {\n\nvoid pytheia_math_classes(py::module& m) {\n  m.def(\"FindQuadraticPolynomialRoots\", &theia::FindQuadraticPolynomialRoots);\n  \n  // rotation.h\n  m.def(\"AlignRotations\", &theia::AlignRotations,\n    \"Solves a nonlinear least squares problem so that: rotations * R = gt_rotations.\");\n  m.def(\"AlignOrientations\", &theia::AlignOrientations,\n    \"This functions takes as input a dictionary of view_ids to global orientations that should be aligned. Then it calls AlignRotations internally.\");\n  m.def(\"MultiplyRotations\", &theia::MultiplyRotations, \"return R = R1 * R2\");\n  m.def(\"RelativeRotationFromTwoRotations\", \n    py::overload_cast<const Eigen::Vector3d&, const Eigen::Vector3d&>(\n      &theia::RelativeRotationFromTwoRotations), \"returns R12 = R2 * R1^T\");\n  m.def(\"ApplyRelativeRotation\", &theia::ApplyRelativeRotation, \"returns R2 = R12 * R1\");\n  m.def(\"RelativeTranslationFromTwoPositions\", &theia::RelativeTranslationFromTwoPositions, \"returns t12 = R1*(p2-p1)\");\n}\n\nvoid pytheia_math(py::module& m) {\n  py::module m_submodule = m.def_submodule(\"math\");\n  pytheia_math_classes(m_submodule);\n}\n\n}  // namespace math\n}  // namespace pytheia", "meta": {"hexsha": "cf66d88f57694a19e3373da6b9d6b5dfec5244fc", "size": 1714, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pytheia/math/math.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/pytheia/math/math.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/pytheia/math/math.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": 34.28, "max_line_length": 150, "alphanum_fraction": 0.743873979, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.5804360239292691}}
{"text": "#include \"maplab-common/combinatorial.h\"\n\n#include <Eigen/Core>\n#include <glog/logging.h>\n\nnamespace common {\n\nvoid getAllBinaryCombinations(\n    size_t num_elements,\n    Aligned<std::vector, Eigen::VectorXi>* list_of_combinations) {\n  CHECK_NOTNULL(list_of_combinations)->clear();\n\n  if (num_elements == 0u) {\n    return;\n  }\n\n  const size_t num_combinations = 1 << num_elements;\n  list_of_combinations->resize(\n      num_combinations, Eigen::VectorXi::Zero(num_elements));\n\n  for (size_t offset = 0; offset < num_elements; ++offset) {\n    const size_t interval = 1 << offset;\n    size_t combination_idx = 0u;\n    int alternating_boolean = 0;\n    while (combination_idx < num_combinations) {\n      for (size_t interval_idx = 0u; interval_idx < interval; ++interval_idx) {\n        (*list_of_combinations)[combination_idx](offset) = alternating_boolean;\n        ++combination_idx;\n      }\n      alternating_boolean = (alternating_boolean + 1) % 2;\n    }\n  }\n}\n\n}  // namespace common\n", "meta": {"hexsha": "691b18ad33c9876ac86f5dca595adbe1bc41c254", "size": 983, "ext": "cc", "lang": "C++", "max_stars_repo_path": "common/maplab-common/src/combinatorial.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "common/maplab-common/src/combinatorial.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "common/maplab-common/src/combinatorial.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": 27.3055555556, "max_line_length": 79, "alphanum_fraction": 0.6937945066, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5804360196394981}}
{"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": "//  (C) Copyright John Maddock 2009.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//#define BOOST_MATH_INSTRUMENT\r\n\r\n#include <boost/math/bindings/rr.hpp>\r\n#include <boost/test/included/test_exec_monitor.hpp>\r\n#include <boost/math/distributions/hypergeometric.hpp>\r\n#include <boost/math/special_functions/trunc.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/math/tools/test.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/random/uniform_int.hpp>\r\n#include <fstream>\r\n\r\n#include <boost/math/tools/test_data.hpp>\r\n\r\nusing namespace boost::math::tools;\r\n\r\nstd::tr1::mt19937 rnd;\r\n\r\nstruct hypergeometric_generator\r\n{\r\n   std::tr1::tuple<\r\n      boost::math::ntl::RR, \r\n      boost::math::ntl::RR, \r\n      boost::math::ntl::RR, \r\n      boost::math::ntl::RR, \r\n      boost::math::ntl::RR,\r\n      boost::math::ntl::RR,\r\n      boost::math::ntl::RR> operator()(boost::math::ntl::RR rN, boost::math::ntl::RR rr, boost::math::ntl::RR rn)\r\n   {\r\n      using namespace std;\r\n      using namespace boost;\r\n      using namespace boost::math;\r\n\r\n      if((rr > rN) || (rr < rn))\r\n         throw std::domain_error(\"\");\r\n\r\n      try{\r\n         int N = itrunc(rN);\r\n         int r = itrunc(rr);\r\n         int n = itrunc(rn);\r\n         uniform_int<> ui((std::max)(0, n + r - N), (std::min)(n, r));\r\n         int k = ui(rnd);\r\n\r\n         hypergeometric_distribution<ntl::RR> d(r, n, N);\r\n\r\n         ntl::RR p = pdf(d, k);\r\n         if((p == 1) || (p == 0))\r\n         {\r\n            // trivial case, don't clutter up our table with it:\r\n            throw std::domain_error(\"\");\r\n         }\r\n         ntl::RR c = cdf(d, k);\r\n         ntl::RR cc = cdf(complement(d, k));\r\n\r\n         std::cout << \"N = \" << N << \" r = \" << r << \" n = \" << n << \" PDF = \" << p << \" CDF = \" << c << \" CCDF = \" << cc << std::endl;\r\n\r\n         return tr1::make_tuple(r, n, N, k, p, c, cc);\r\n      }\r\n      catch(const std::exception& e)\r\n      {\r\n         std::cout << e.what() << std::endl;\r\n         throw std::domain_error(\"\");\r\n      }\r\n   }\r\n};\r\n\r\nint test_main(int argc, char*argv [])\r\n{\r\n   boost::math::ntl::RR::SetPrecision(1000);\r\n   boost::math::ntl::RR::SetOutputPrecision(100);\r\n\r\n   std::string line;\r\n   parameter_info<boost::math::ntl::RR> arg1, arg2, arg3;\r\n   test_data<boost::math::ntl::RR> data;\r\n\r\n   std::cout << \"Welcome.\\n\"\r\n      \"This program will generate spot tests hypergeoemtric distribution:\\n\";\r\n\r\n   arg1 = make_power_param(boost::math::ntl::RR(0), 1, 21);\r\n   arg2 = make_power_param(boost::math::ntl::RR(0), 1, 21);\r\n   arg3 = make_power_param(boost::math::ntl::RR(0), 1, 21);\r\n\r\n   arg1.type |= dummy_param;\r\n   arg2.type |= dummy_param;\r\n   arg3.type |= dummy_param;\r\n\r\n   data.insert(hypergeometric_generator(), arg1, arg2, arg3);\r\n\r\n   line = \"hypergeometric_dist_data2.ipp\";\r\n   std::ofstream ofs(line.c_str());\r\n   write_code(ofs, data, \"hypergeometric_dist_data2\");\r\n   \r\n   return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "ba1eedcb0a6f00ecf601d572b7f090c3243522ff", "size": 3071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/hypergeometric_dist_data.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/math/tools/hypergeometric_dist_data.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/tools/hypergeometric_dist_data.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 30.4059405941, "max_line_length": 136, "alphanum_fraction": 0.5757082384, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5803978279328944}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestInnerProduct\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/algorithm/inner_product.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/iterator/counting_iterator.hpp>\n\n#include \"context_setup.hpp\"\n\nnamespace bc = boost::compute;\n\nBOOST_AUTO_TEST_CASE(inner_product_int)\n{\n    int data1[] = { 1, 2, 3, 4 };\n    bc::vector<int> input1(data1, data1 + 4, queue);\n\n    int data2[] = { 10, 20, 30, 40 };\n    bc::vector<int> input2(data2, data2 + 4, queue);\n\n    int product = bc::inner_product(input1.begin(),\n                                    input1.end(),\n                                    input2.begin(),\n                                    0,\n                                    queue);\n    BOOST_CHECK_EQUAL(product, 300);\n}\n\nBOOST_AUTO_TEST_CASE(inner_product_counting_iterator)\n{\n    BOOST_CHECK_EQUAL(\n        boost::compute::inner_product(\n            boost::compute::make_counting_iterator<int>(0),\n            boost::compute::make_counting_iterator<int>(100),\n            boost::compute::make_counting_iterator<int>(0),\n            0,\n            queue\n        ),\n        328350\n    );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3c67cd9d9552149110ea523e4ecd0a13c506de2f", "size": 1670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_inner_product.cpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "test/test_inner_product.cpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_inner_product.cpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9259259259, "max_line_length": 79, "alphanum_fraction": 0.5634730539, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5803978257969271}}
{"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": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \r\n// unit/quantity manipulation and conversion\r\n//\r\n// Copyright (C) 2014 Erik Erlandson\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//#include <boost/units/systems/information.hpp>\r\n\r\n/** \r\n\\file\r\n\r\n\\brief information.cpp\r\n\r\n\\details\r\nDemonstrate information unit system.\r\n\r\nOutput:\r\n@verbatim\r\nbytes= 1.25e+08 B\r\nbits= 8e+06 b\r\nnats= 4605.17 nat\r\n1024 bytes in a kibi-byte\r\n8.38861e+06 bits in a mebi-byte\r\n0.000434294 hartleys in a milli-nat\r\nentropy in bits= 1 b\r\nentropy in nats= 0.693147 nat\r\nentropy in hartleys= 0.30103 Hart\r\nentropy in shannons= 1 Sh\r\nentropy in bytes= 0.125 B\r\n@endverbatim\r\n**/\r\n\r\n#include <cmath>\r\n#include <iostream>\r\nusing std::cout;\r\nusing std::endl;\r\nusing std::log;\r\n\r\n#include <boost/units/quantity.hpp>\r\n#include <boost/units/io.hpp>\r\n#include <boost/units/conversion.hpp>\r\nnamespace bu = boost::units;\r\nusing bu::quantity;\r\nusing bu::conversion_factor;\r\n\r\n// SI prefixes\r\n#include <boost/units/systems/si/prefixes.hpp>\r\nnamespace si = boost::units::si;\r\n\r\n// information unit system\r\n#include <boost/units/systems/information.hpp>\r\nusing namespace bu::information;\r\n\r\n// Define a function for the entropy of a bernoulli trial.\r\n// The formula is computed using natural log, so the units are in nats.\r\n// The user provides the desired return unit, the only restriction being that it\r\n// must be a unit of information.  Conversion to the requested return unit is \r\n// accomplished automatically by the boost::units library.\r\ntemplate <typename Sys>\r\nconstexpr\r\nquantity<bu::unit<bu::information_dimension, Sys> > \r\nbernoulli_entropy(double p, const bu::unit<bu::information_dimension, Sys>&) {\r\n    typedef bu::unit<bu::information_dimension, Sys> requested_unit;\r\n    return quantity<requested_unit>((-(p*log(p) + (1-p)*log(1-p)))*nats);\r\n}\r\n\r\nint main(int argc, char** argv) {\r\n    // a quantity of information (default in units of bytes) \r\n    quantity<info> nbytes(1 * si::giga * bit);\r\n    cout << \"bytes= \" << nbytes << endl;\r\n\r\n    // a quantity of information, stored as bits\r\n    quantity<hu::bit::info> nbits(1 * si::mega * byte);\r\n    cout << \"bits= \" << nbits << endl;\r\n\r\n    // a quantity of information, stored as nats\r\n    quantity<hu::nat::info> nnats(2 * si::kilo * hartleys);\r\n    cout << \"nats= \" << nnats << endl;\r\n\r\n    // how many bytes are in a kibi-byte?\r\n    cout << conversion_factor(kibi * byte, byte) << \" bytes in a kibi-byte\" << endl;\r\n\r\n    // how many bits are in a mebi-byte?\r\n    cout << conversion_factor(mebi * byte, bit) << \" bits in a mebi-byte\" << endl;\r\n\r\n    // how many hartleys are in a milli-nat?\r\n    cout << conversion_factor(si::milli * nat, hartley) << \" hartleys in a milli-nat\" << endl;\r\n\r\n    // compute the entropy of a fair coin flip, in various units of information:\r\n    cout << \"entropy in bits= \" << bernoulli_entropy(0.5, bits) << endl;\r\n    cout << \"entropy in nats= \" << bernoulli_entropy(0.5, nats) << endl;\r\n    cout << \"entropy in hartleys= \" << bernoulli_entropy(0.5, hartleys) << endl;\r\n    cout << \"entropy in shannons= \" << bernoulli_entropy(0.5, shannons) << endl;\r\n    cout << \"entropy in bytes= \" << bernoulli_entropy(0.5, bytes) << endl;\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "eed52cd8046f3e0a8c982d6e12d49e7c4759e736", "size": 3361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/units/example/information.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/units/example/information.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/units/example/information.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 33.2772277228, "max_line_length": 95, "alphanum_fraction": 0.6727164534, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5803437527391524}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n\n#include <OpenTissue/core/math/optimization/optimization_make_constant_bounds.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\ntemplate<typename bound_function>\ninline void test_vector_bounds( bound_function const & B)\n{\n  double tol =0.01;\n\n  ublas::vector<double> x;\n\n\n  BOOST_CHECK_CLOSE( B(x,0) , 1.0 , tol );\n\n  BOOST_CHECK( B.partial_begin(0) == B.partial_end(0) );\n  BOOST_CHECK( B.partial_begin(1) == B.partial_end(1) );\n  BOOST_CHECK( B.partial_begin(2) == B.partial_end(2) );\n  BOOST_CHECK( B.partial_begin(3) == B.partial_end(3) );\n  BOOST_CHECK( B.partial_begin(4) == B.partial_end(4) );\n  BOOST_CHECK( B.partial_begin(5) == B.partial_end(5) );\n  BOOST_CHECK( B.partial_begin(6) == B.partial_end(6) );\n  BOOST_CHECK( B.partial_begin(7) == B.partial_end(7) );\n  BOOST_CHECK( B.partial_begin(8) == B.partial_end(8) );\n  BOOST_CHECK( B.partial_begin(9) == B.partial_end(9) );\n\n  BOOST_CHECK_CLOSE( B(x,1) , 2.0 , tol );\n  BOOST_CHECK_CLOSE( B(x,2) , 3.0 , tol );\n  BOOST_CHECK_CLOSE( B(x,3) , 4.0 , tol );\n  BOOST_CHECK_CLOSE( B(x,4) , 5.0 , tol );\n  BOOST_CHECK_CLOSE( B(x,5) , 6.0 , tol );\n  BOOST_CHECK_CLOSE( B(x,6) , 7.0 , tol );\n  BOOST_CHECK_CLOSE( B(x,7) , 8.0 , tol );\n  BOOST_CHECK_CLOSE( B(x,8) , 9.0 , tol );\n  BOOST_CHECK_CLOSE( B(x,9) , 10.0 , tol );\n\n}\n\ntemplate<typename bound_function>\ninline void test_scalar_bounds( bound_function const & B)\n{\n  double tol =0.01;\n  ublas::vector<double> x;\n\n  BOOST_CHECK( B.partial_begin(0) == B.partial_end(0) );\n  BOOST_CHECK( B.partial_begin(1) == B.partial_end(1) );\n  BOOST_CHECK( B.partial_begin(2) == B.partial_end(2) );\n  BOOST_CHECK( B.partial_begin(3) == B.partial_end(3) );\n  BOOST_CHECK( B.partial_begin(4) == B.partial_end(4) );\n  BOOST_CHECK( B.partial_begin(5) == B.partial_end(5) );\n\n  BOOST_CHECK_CLOSE( B(x,0) , 2.5 , tol );\n  BOOST_CHECK_CLOSE( B(x,1) , 2.5 , tol );\n  BOOST_CHECK_CLOSE( B(x,2) , 2.5 , tol );\n  BOOST_CHECK_CLOSE( B(x,3) , 2.5 , tol );\n  BOOST_CHECK_CLOSE( B(x,4) , 2.5 , tol );\n  BOOST_CHECK_CLOSE( B(x,5) , 2.5 , tol );\n}\n\n\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_make_const_bounds);\n\nBOOST_AUTO_TEST_CASE(test_case)\n{\n  ublas::vector<double> rhs;\n  rhs.resize(10,false);\n  rhs(0) = 1.0;\n  rhs(1) = 2.0;\n  rhs(2) = 3.0;\n  rhs(3) = 4.0;\n  rhs(4) = 5.0;\n  rhs(5) = 6.0;\n  rhs(6) = 7.0;\n  rhs(7) = 8.0;\n  rhs(8) = 9.0;\n  rhs(9) = 10.0;\n\n  test_vector_bounds( OpenTissue::math::optimization::make_constant_bounds( rhs ));\n\n  double value = 2.5;\n\n  test_scalar_bounds( OpenTissue::math::optimization::make_constant_bounds( value, 10 ) );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "c990b04f31bffb66e26d9570ff889dbc7dbe1077", "size": 3084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/const_bounds/src/unit_const_bounds.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/const_bounds/src/unit_const_bounds.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/const_bounds/src/unit_const_bounds.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 30.84, "max_line_length": 90, "alphanum_fraction": 0.6890402075, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.734119538534297, "lm_q1q2_score": 0.5803437527391524}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/bool.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/ext/std/utility.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <type_traits>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n//! [comparable]\nBOOST_HANA_CONSTANT_CHECK(nothing == nothing);\nBOOST_HANA_CONSTEXPR_CHECK(just('x') == just('x'));\nBOOST_HANA_CONSTEXPR_CHECK(just('x') != just('y'));\nBOOST_HANA_CONSTANT_CHECK(just('x') != nothing);\n//! [comparable]\n\n}{\n\n//! [orderable]\nBOOST_HANA_CONSTANT_CHECK(nothing < just(3));\nBOOST_HANA_CONSTANT_CHECK(just(0) > nothing);\nBOOST_HANA_CONSTEXPR_CHECK(just(1) < just(3));\nBOOST_HANA_CONSTEXPR_CHECK(just(3) > just(2));\n//! [orderable]\n\n}{\n\n//! [functor]\nBOOST_HANA_CONSTEXPR_LAMBDA auto inc = [](auto x) { return x + 1; };\nBOOST_HANA_CONSTANT_CHECK(transform(nothing, inc) == nothing);\nBOOST_HANA_CONSTEXPR_CHECK(transform(just(1), inc) == just(2));\n//! [functor]\n\n}{\n\n//! [applicative]\nBOOST_HANA_CONSTEXPR_CHECK(ap(just(succ), just('x')) == just('y'));\nBOOST_HANA_CONSTANT_CHECK(ap(nothing, just('x')) == nothing);\nBOOST_HANA_CONSTANT_CHECK(ap(just(succ), nothing) == nothing);\nBOOST_HANA_CONSTANT_CHECK(ap(nothing, nothing) == nothing);\n//! [applicative]\n\n}{\n\n//! [monad]\nBOOST_HANA_CONSTEXPR_LAMBDA auto inc = [](auto x) {\n    return just(x + 1);\n};\n\nBOOST_HANA_CONSTEXPR_CHECK(bind(just(1), inc) == just(2));\nBOOST_HANA_CONSTANT_CHECK(bind(nothing, inc) == nothing);\n\nBOOST_HANA_CONSTEXPR_CHECK(flatten(just(just(2))) == just(2));\n//! [monad]\n\n}{\n\n//! [monad_plus]\nBOOST_HANA_CONSTEXPR_CHECK(\n    concat(nothing, just('x')) == just('x')\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    concat(nothing, nothing) == nothing\n);\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    concat(just('x'), just('y')) == just('x')\n);\n\nBOOST_HANA_CONSTANT_CHECK(empty<Maybe>() == nothing);\n//! [monad_plus]\n\n}{\n\n//! [traversable]\nBOOST_HANA_CONSTEXPR_LAMBDA auto replicate3 = [](auto x) {\n    return make<Tuple>(x, x, x);\n};\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    traverse<Tuple>(just(1), replicate3)\n    ==\n    make<Tuple>(just(1), just(1), just(1))\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    traverse<Tuple>(nothing, replicate3)\n    ==\n    make<Tuple>(nothing)\n);\n//! [traversable]\n\n}{\n\n//! [foldable]\nBOOST_HANA_CONSTEXPR_LAMBDA auto plus = [](auto x, auto y) {\n    return x + y;\n};\n\nBOOST_HANA_CONSTEXPR_CHECK(foldr(nothing, 1, plus) == 1);\nBOOST_HANA_CONSTEXPR_CHECK(foldr(just(4), 1, plus) == 5);\n//! [foldable]\n\n}{\n\n//! [searchable]\nBOOST_HANA_CONSTEXPR_LAMBDA auto odd = [](auto x) {\n    return x % int_<2> != int_<0>;\n};\n\nBOOST_HANA_CONSTANT_CHECK(find_if(just(int_<3>), odd) == just(int_<3>));\nBOOST_HANA_CONSTANT_CHECK(find_if(just(int_<2>), odd) == nothing);\nBOOST_HANA_CONSTANT_CHECK(find_if(nothing, odd) == nothing);\n\nBOOST_HANA_CONSTANT_CHECK(all_of(just(int_<3>), odd));\nBOOST_HANA_CONSTANT_CHECK(all_of(nothing, odd));\n//! [searchable]\n\n}{\n\n//! [maybe]\nBOOST_HANA_CONSTEXPR_CHECK(maybe('x', succ, just(1)) == 2);\nBOOST_HANA_CONSTEXPR_CHECK(maybe('x', succ, nothing) == 'x');\n//! [maybe]\n\n}{\n\n//! [is_just]\nBOOST_HANA_CONSTANT_CHECK( is_just(just('x')));\nBOOST_HANA_CONSTANT_CHECK( is_just(just(nothing)));\nBOOST_HANA_CONSTANT_CHECK(!is_just(nothing));\n//! [is_just]\n\n}{\n\n//! [is_nothing]\nBOOST_HANA_CONSTANT_CHECK( is_nothing(nothing));\nBOOST_HANA_CONSTANT_CHECK(!is_nothing(just('x')));\nBOOST_HANA_CONSTANT_CHECK(!is_nothing(just(nothing)));\n//! [is_nothing]\n\n}{\n\n//! [from_maybe]\nBOOST_HANA_CONSTEXPR_CHECK(from_maybe('x', just(1)) == 1);\nBOOST_HANA_CONSTEXPR_CHECK(from_maybe('x', nothing) == 'x');\n//! [from_maybe]\n\n}{\n\n//! [only_when]\nBOOST_HANA_CONSTEXPR_LAMBDA auto even = [](auto x) {\n    return x % int_<2> == int_<0>;\n};\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto half = [](auto x) {\n    return x / int_<2>;\n};\n\nBOOST_HANA_CONSTANT_CHECK(only_when(even, half, int_<4>) == just(int_<2>));\nBOOST_HANA_CONSTANT_CHECK(only_when(even, half, int_<3>) == nothing);\n//! [only_when]\n\n}{\n\n//! [from_just]\nBOOST_HANA_CONSTEXPR_CHECK(from_just(just('x')) == 'x');\n// from_just(nothing); // compile-time static assertion\n//! [from_just]\n\n}{\n\n//! [nothing]\nconstexpr auto x = nothing;\n//! [nothing]\n\n//! [just]\nconstexpr auto just_x = just('x');\n//! [just]\n\n(void)x;\n(void)just_x;\n\n}{\n\n//! [sfinae]\nBOOST_HANA_CONSTEXPR_LAMBDA auto incr = [](auto x) -> decltype(x + 1) {\n    return x + 1;\n};\n\nBOOST_HANA_CONSTEXPR_CHECK(sfinae(incr)(1) == just(2));\n\nstruct invalid { };\nBOOST_HANA_CONSTANT_CHECK(sfinae(incr)(invalid{}) == nothing);\n//! [sfinae]\n\n}\n\n}\n\ntemplate <typename ...>\nusing void_t = void;\n\ntemplate <typename T, typename = void>\nstruct has_type : std::false_type { };\n\ntemplate <typename T>\nstruct has_type<T, void_t<typename T::type>>\n    : std::true_type\n{ };\n\n//! [sfinae_friendly_metafunctions]\nauto common_type_impl = sfinae([](auto t, auto u) -> decltype(type<\n    decltype(true ? traits::declval(t) : traits::declval(u))\n>) { return {}; });\n\ntemplate <typename T, typename U>\nusing common_type2 = decltype(common_type_impl(type<T>, type<U>));\n\nstatic_assert(!has_type<common_type2<int, int*>>{}, \"\");\nstatic_assert(std::is_same<common_type2<int, float>::type, float>{}, \"\");\n//! [sfinae_friendly_metafunctions]\n", "meta": {"hexsha": "f983f56633c91424dd6d472b4919a43b07a4280e", "size": 5392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/maybe.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/maybe.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/maybe.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8474576271, "max_line_length": 78, "alphanum_fraction": 0.6923219585, "num_tokens": 1566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5803437507878365}}
{"text": "#include \"stdafx.h\"\n\n#include <boost\\test\\unit_test.hpp>\n\n#include <boost\\gil\\extension\\opencv\\edge_detection.hpp>\n\n#include <boost\\gil\\extension\\io_new\\png_all.hpp>\n\nusing namespace boost::gil;\nusing namespace boost::gil::opencv;\n\nBOOST_AUTO_TEST_CASE( test_sobel )\n{\n    gray8_image_t src;\n    read_and_convert_image( \"..\\\\in\\\\in.png\", src, png_tag() ); \n\n    gray8_image_t dst( view( src ).dimensions() );\n\n    sobel( view( src )\n         , view( dst )\n         , aperture3()\n         );\n\n    write_view( \"..\\\\out\\\\sobel.png\", view( dst ), png_tag() );\n}\n\nBOOST_AUTO_TEST_CASE( test_laplace )\n{\n    rgb8_image_t src;\n    read_image( \"..\\\\in\\\\in.png\", src, png_tag() ); \n\n    rgb32f_image_t dst( view( src ).dimensions() );\n\n    laplace( view( src )\n           , view( dst )\n           , aperture3()\n           );\n\n    write_view( \"..\\\\out\\\\laplace.png\"\n              , color_converted_view< rgb8_pixel_t >( view( dst ))\n              , png_tag()\n              );\n}\n\nBOOST_AUTO_TEST_CASE( test_canny )\n{\n    gray8_image_t src;\n    read_and_convert_image( \"..\\\\in\\\\in.png\", src, png_tag() ); \n\n    gray8_image_t edges( view( src ).dimensions() );\n\n    canny( view( src   )\n         , view( edges )\n         , 60\n         , 180\n         , aperture3()\n         );\n\n    write_view( \"..\\\\out\\\\canny.png\", view( edges ), png_tag() );\n}\n\nBOOST_AUTO_TEST_CASE( test_pre_corner_detect )\n{\n    gray8_image_t src;\n    read_and_convert_image( \"..\\\\in\\\\in.png\", src, png_tag() ); \n\n    gray32f_image_t corners( view( src ).dimensions() );\n\n    precorner_detect( view( src     )\n                    , view( corners )\n                    , aperture3()\n                    );\n\n    write_view( \"..\\\\out\\\\precorner_detect.png\"\n              , color_converted_view< rgb8_pixel_t >( view( corners ))\n              , png_tag()\n              );\n\n    // try this for testing\n    /*\n    // assume that the image is floating-point\n    IplImage* corners = cvCloneImage(image);\n    IplImage* dilated_corners = cvCloneImage(image);\n    IplImage* corner_mask = cvCreateImage( cvGetSize(image), 8, 1 );\n    cvPreCornerDetect( image, corners, 3 );\n    cvDilate( corners, dilated_corners, 0, 1 );\n    cvSubS( corners, dilated_corners, corners );\n    cvCmpS( corners, 0, corner_mask, CV_CMP_GE );\n    cvReleaseImage( &corners );\n    cvReleaseImage( &dilated_corners );\n    */\n}\n\nBOOST_AUTO_TEST_CASE( test_corner_eigen_vals_and_vecs )\n{\n    gray8_image_t src;\n    read_and_convert_image( \"..\\\\in\\\\in.png\", src, png_tag() ); \n\n    gray32f_image_t eigen( view( src ).dimensions().x * 6\n                       , view( src ).dimensions().y\n                       );\n\n    corner_eigen_vals_and_vecs( view( src   )\n                              , view( eigen )\n                              , 3\n                              , aperture3()\n                              );\n\n    write_view( \"..\\\\out\\\\corner_eigen_vals_and_vecs.png\"\n              , color_converted_view< rgb8_pixel_t >( view( eigen ))\n              , png_tag()\n              );\n}", "meta": {"hexsha": "84741c6119b5cf665fd95dbf0fc836c9a1fb05d4", "size": 3007, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gil_2/libs/gil/opencv/unit_test/edge_detection.cpp", "max_stars_repo_name": "boost-gil/gil-contributions", "max_stars_repo_head_hexsha": "22c32e6221d0c52a4c4bd46d1395b00fdefbd061", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-19T00:50:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-19T00:50:12.000Z", "max_issues_repo_path": "gil_2/libs/gil/opencv/unit_test/edge_detection.cpp", "max_issues_repo_name": "boost-gil/gil-contributions-archive", "max_issues_repo_head_hexsha": "22c32e6221d0c52a4c4bd46d1395b00fdefbd061", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gil_2/libs/gil/opencv/unit_test/edge_detection.cpp", "max_forks_repo_name": "boost-gil/gil-contributions-archive", "max_forks_repo_head_hexsha": "22c32e6221d0c52a4c4bd46d1395b00fdefbd061", "max_forks_repo_licenses": ["BSL-1.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.610619469, "max_line_length": 70, "alphanum_fraction": 0.5573661457, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5803437481405926}}
{"text": "//=======================================================================\n// Copyright (c) 2014 Piotr Smulewicz\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file multiway_cut_test.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2014-01-09\n */\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/test_result_check.hpp\"\n\n#include \"paal/multiway_cut/multiway_cut.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/test/unit_test.hpp>\n\n\ntemplate <typename Graph>\nstd::pair<Graph, int> create_instance() {\n    std::vector<std::pair<int,int> > edges_p{{0,3},{1,3},\n                                            {0,4},{2,4},\n                                            {1,5},{2,5},\n                                            {3,6},{4,6},\n                                            {3,7},{5,7},\n                                            {4,8},{5,8},\n                                            {6,7},{6,8},{7,8}\n    };\n    const int nu_vertices = 9;\n    std::vector<int> cost_edges{100,100,100,100,100,100,10,10,10,10,10,10,1,1,1};\n\n    Graph graph(edges_p.begin(), edges_p.end(), cost_edges.begin(), nu_vertices);\n\n    const int terminals_num = 3;\n    int i = 0;\n    for (auto v : boost::make_iterator_range(vertices(graph))) {\n        put(boost::vertex_color, graph, v, i + 1);\n        ++i;\n        if (i == terminals_num) {\n            break;\n        }\n    }\n\n    const int optimal = 320;\n    return std::make_pair(graph, optimal);\n}\n\ntemplate <typename Graph> void run_test(const Graph &graph, int optimal) {\n    using VT = typename boost::graph_traits<Graph>::vertex_descriptor;\n    auto index = get(boost::vertex_index, graph);\n    auto weight = boost::get(boost::edge_weight, graph);\n    std::vector<std::pair<VT, int>> vertices_parts;\n\n    auto cost_cut = paal::multiway_cut(graph, back_inserter(vertices_parts));\n    LOGLN(\"cost cut: \" << cost_cut);\n    std::vector<int> vertices_to_parts(vertices_parts.size());\n    for (auto i: vertices_parts) {\n        LOG(i.first << \"(\" << i.second << \"), \");\n        vertices_to_parts[get(index, i.first)] = i.second;\n    }\n    LOGLN(\"\");\n    int cost_cut_verification = 0;\n    for (auto e : boost::make_iterator_range(edges(graph))){\n        if (vertices_to_parts[get(index, source(e, graph))] != vertices_to_parts[get(index, target(e, graph))])\n            cost_cut_verification += get(weight, e);\n    }\n\n    check_result(cost_cut, optimal, 2);\n    LOGLN(\"Cost Cut Verification: \" << cost_cut_verification);\n    BOOST_CHECK_EQUAL(cost_cut, cost_cut_verification);\n}\n\ntemplate <typename VertexList>\nusing Graph = boost::adjacency_list<\n    boost::vecS, VertexList, boost::undirectedS,\n    boost::property<boost::vertex_index_t, int,\n                    boost::property<boost::vertex_color_t, int>>,\n    boost::property<boost::edge_weight_t, int>>;\n\nBOOST_AUTO_TEST_CASE(multiway_cutS) {\n    auto instance = create_instance<Graph<boost::vecS>>();\n    run_test(instance.first, instance.second);\n}\n\nBOOST_AUTO_TEST_CASE(multiway_cutS_list) {\n    auto instance = create_instance<Graph<boost::listS>>();\n    auto graph = instance.first;\n    auto optimal = instance.second;\n\n    auto index = get(boost::vertex_index, graph);\n    int idx = 0;\n    for (auto v : boost::make_iterator_range(vertices(graph))) {\n        put(index, v, idx);\n        ++idx;\n    }\n\n    run_test(graph, optimal);\n}\n", "meta": {"hexsha": "f99d886745604c9e02fe38639d0b6910a9278959", "size": 3589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/linear_programming/multiway_cut/multiway_cut_test.cpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/linear_programming/multiway_cut/multiway_cut_test.cpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/linear_programming/multiway_cut/multiway_cut_test.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 33.858490566, "max_line_length": 111, "alphanum_fraction": 0.5820562831, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.5803437270991084}}
{"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": "\n#include <iostream>\n#include <armadillo>\n\nusing namespace arma;\nusing std::cout;\nusing std::endl;\n\nvoid cxmatLoad(cx_mat& uMat, int &size, char* file)\n{\n\tcx_mat uTest;\n\tint uCheck;\n\tuTest.load(file);\n\n\tif(uMat.n_rows !=  uMat.n_cols)\n\t{\n\t\tcout << \"[Error] : Input matrix is non square\" << endl;\n\t\texit(1);\n\t}\n\telse\n\t{\n\t\tsize = uMat.n_rows;\n\t}\n\n\tuCheck = static_cast<int>(real(trace(uMat * uMat.t())));\n\n\tif(uCheck != size)\n\t{\n\t\tcout << \"[Error] : Input matrix is non-unitary \" << endl;\n\t\texit(1);\n\t}\n\telse\n\t{\n\t\tuMat = uTest;\n\t}\n}\n", "meta": {"hexsha": "da6a17be5f7e8eb9928e1f688deb7b0eb0a07ee6", "size": 531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/io/cxmatLoad.cpp", "max_stars_repo_name": "Swaddle/qGeod", "max_stars_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/io/cxmatLoad.cpp", "max_issues_repo_name": "Swaddle/qGeod", "max_issues_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/io/cxmatLoad.cpp", "max_forks_repo_name": "Swaddle/qGeod", "max_forks_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.3513513514, "max_line_length": 59, "alphanum_fraction": 0.6177024482, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5802887885490026}}
{"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": "//=======================================================================\n// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file bounded_degree_mst_long_test.cpp\n * @brief\n * @author Piotr Godlewski\n * @version 1.0\n * @date 2013-06-10\n */\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/read_bounded_deg_mst.hpp\"\n#include \"test_utils/get_test_dir.hpp\"\n#include \"test_utils/system.hpp\"\n\n#include \"paal/data_structures/components/components_replace.hpp\"\n#include \"paal/iterative_rounding/bounded_degree_min_spanning_tree/bounded_degree_mst.hpp\"\n#include \"paal/iterative_rounding/iterative_rounding.hpp\"\n#include \"paal/utils/functors.hpp\"\n#include \"paal/utils/irange.hpp\"\n#include \"paal/utils/parse_file.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n                              boost::property<boost::vertex_index_t, int>,\n                              boost::property<boost::edge_weight_t, double>>\n    Graph;\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS,\n                                     boost::undirectedS> Traits;\ntypedef boost::graph_traits<Graph>::edge_descriptor Edge;\ntypedef boost::graph_traits<Graph>::vertex_descriptor Vertex;\n\ntypedef boost::property_map<Graph, boost::edge_weight_t>::type Cost;\ntypedef std::set<Edge> ResultTree;\n\ntemplate <typename Bound>\nvoid check_result(const Graph & g, const ResultTree & tree,\n                 const Cost & costs, const Bound & deg_bounds,\n                 int vertices_num, double best_cost, double tree_cost) {\n    int tree_edges(tree.size());\n    double result_cost = std::accumulate(tree.begin(), tree.end(), 0.,\n                        [&](double cost, Edge e){return cost + costs[e];});\n    BOOST_CHECK_EQUAL(result_cost, tree_cost);\n\n    LOGLN(\"tree edges: \" << tree_edges);\n    BOOST_CHECK(tree_edges == vertices_num - 1);\n    BOOST_CHECK(tree_cost <= best_cost);\n\n    auto verts = vertices(g);\n    int num_of_violations(0);\n\n    for (const Vertex & v : boost::make_iterator_range(verts.first, verts.second)) {\n        int tree_deg(0);\n        auto adj_vertices = adjacent_vertices(v, g);\n        for (Vertex u : boost::make_iterator_range(adj_vertices)) {\n            bool b; Edge e;\n            std::tie(e, b) = boost::edge(v, u, g);\n            assert(b);\n\n            if (tree.count(e)) {\n                ++tree_deg;\n            }\n        }\n\n        BOOST_CHECK(tree_deg <= deg_bounds(v) + 1);\n        if (tree_deg > deg_bounds(v)) {\n            ++num_of_violations;\n        }\n    }\n\n    LOGLN(\"Found cost = \" << tree_cost << \", cost upper bound = \" << best_cost);\n    LOGLN(\"Number of violated constraints = \" << num_of_violations);\n\n    Graph tree_g(vertices_num);\n\n    for (auto e : tree) {\n        add_edge(source(e, g), target(e, g), tree_g);\n    }\n\n    std::vector<int> component(vertices_num);\n    BOOST_CHECK(connected_components(tree_g, &component[0]) == 1);\n}\n\ntemplate <typename Oracle, typename Bound>\nvoid run_test(const Graph & g, const Cost & costs, const Bound & deg_bounds,\n             const int vertices_num, const double best_cost) {\n    namespace ir = paal::ir;\n    {\n        LOGLN(\"Unlimited relaxations\");\n        ResultTree tree;\n        auto result = ir::bounded_degree_mst_iterative_rounding<Oracle>(\n                            g, deg_bounds, std::inserter(tree, tree.end()));\n        BOOST_CHECK(result.first == paal::lp::OPTIMAL);\n        check_result(g, tree, costs, deg_bounds, vertices_num, best_cost, *(result.second));\n    }\n    {\n        LOGLN(\"Relaxations limit = 1/iter\");\n        ResultTree tree;\n        ir::bdmst_ir_components<> comps;\n        auto components = paal::data_structures::replace<ir::RelaxationsLimit>(\n                            ir::relaxations_limit_condition(), comps);\n        auto result = ir::bounded_degree_mst_iterative_rounding<Oracle>(\n                            g, deg_bounds, std::inserter(tree, tree.end()), components);\n        BOOST_CHECK(result.first == paal::lp::OPTIMAL);\n        check_result(g, tree, costs, deg_bounds, vertices_num, best_cost, *(result.second));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(bounded_degree_mst_long) {\n    std::string test_dir = paal::system::get_test_data_dir(\"BOUNDED_DEGREE_MST\");\n    using paal::system::build_path;\n\n    paal::parse(build_path(test_dir, \"bdmst.txt\"), [&](const std::string & fname, std::istream & is_test_cases) {\n        int vertices_num, edges_num;\n        double best_cost;\n        is_test_cases >> vertices_num >> edges_num;\n\n        LOGLN(fname);\n        std::ifstream ifs(build_path(test_dir, \"/cases/\" + fname + \".lgf\"));\n        assert(ifs.good());\n\n        Graph g(vertices_num);\n        Cost costs = get(boost::edge_weight, g);\n        std::vector<int> deg_bounds(vertices_num);\n\n        paal::read_bdmst(ifs, vertices_num, edges_num, g, costs,\n                        deg_bounds, best_cost);\n        auto bounds = paal::utils::make_array_to_functor(deg_bounds);\n\n        // default heuristics\n        for (int i : paal::irange(5)) {\n            LOGLN(\"random violated, seed \" << i);\n            srand(i);\n            run_test<paal::lp::random_violated_separation_oracle>(\n                            g, costs, bounds, vertices_num, best_cost);\n        }\n\n        // non-default heuristics\n        if (vertices_num <= 80) {\n            LOGLN(\"most violated\");\n            run_test<paal::lp::max_violated_separation_oracle>(\n                            g, costs, bounds, vertices_num, best_cost);\n        }\n\n        // non-default heuristics\n        if (vertices_num <= 60) {\n            LOGLN(\"first violated\");\n            run_test<paal::lp::first_violated_separation_oracle>(\n                            g, costs, bounds, vertices_num, best_cost);\n        }\n    });\n}\n", "meta": {"hexsha": "f3fcbffd733afe05b8e4bb8a4db21e47e651894e", "size": 6136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/iterative_rounding/bounded_degree_min_spanning_tree/bounded_degree_mst_long_test.cpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/iterative_rounding/bounded_degree_min_spanning_tree/bounded_degree_mst_long_test.cpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/iterative_rounding/bounded_degree_min_spanning_tree/bounded_degree_mst_long_test.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 36.9638554217, "max_line_length": 113, "alphanum_fraction": 0.6135919166, "num_tokens": 1444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5802887671344771}}
{"text": "#include <stan/math/mix/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <test/unit/math/rev/scal/fun/util.hpp>\n#include <test/unit/math/mix/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdRisingFactorial, FvarVar_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<var> a(4.0,1.0);\n  fvar<var> b(4.0,1.0);\n  fvar<var> c = rising_factorial(a,b);\n\n  EXPECT_FLOAT_EQ((840.0), c.val_.val());\n  EXPECT_FLOAT_EQ(840. * (2 * digamma(8) - digamma(4)), c.d_.val());\n\n  AVEC y = createAVEC(a.val_,b.val_);\n  VEC g;\n  c.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(840. * (digamma(8) - digamma(4)), g[0]);\n  EXPECT_FLOAT_EQ(840 * digamma(8), g[1]);\n}\nTEST(AgradFwdRisingFactorial, FvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<var> a(4.0,1.0);\n  double b(4.0);\n  fvar<var> c = rising_factorial(a,b);\n\n  EXPECT_FLOAT_EQ((840.0), c.val_.val());\n  EXPECT_FLOAT_EQ(840. * (digamma(8) - digamma(4)), c.d_.val());\n\n  AVEC y = createAVEC(a.val_);\n  VEC g;\n  c.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(840. * (digamma(8) - digamma(4)), g[0]);\n}\nTEST(AgradFwdRisingFactorial, Double_FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  double a(4.0);\n  fvar<var> b(4.0,1.0);\n  fvar<var> c = rising_factorial(a,b);\n\n  EXPECT_FLOAT_EQ((840.0), c.val_.val());\n  EXPECT_FLOAT_EQ(840 * digamma(8), c.d_.val());\n\n  AVEC y = createAVEC(b.val_);\n  VEC g;\n  c.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(840 * digamma(8), g[0]);\n}\nTEST(AgradFwdRisingFactorial, FvarVar_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<var> a(4.0,1.0);\n  fvar<var> b(4.0,1.0);\n  fvar<var> c = rising_factorial(a,b);\n\n  AVEC y = createAVEC(a.val_,b.val_);\n  VEC g;\n  c.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(1755.8143, g[0]);\n  EXPECT_FLOAT_EQ(4922.4102, g[1]);\n}\nTEST(AgradFwdRisingFactorial, FvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<var> a(4.0,1.0);\n  double b(4.0);\n  fvar<var> c = rising_factorial(a,b);\n\n  AVEC y = createAVEC(a.val_);\n  VEC g;\n  c.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(358, g[0]);\n}\nTEST(AgradFwdRisingFactorial, Double_FvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  double a(4.0);\n  fvar<var> b(4.0,1.0);\n  fvar<var> c = rising_factorial(a,b);\n\n  AVEC y = createAVEC(b.val_);\n  VEC g;\n  c.d_.grad(y,g);\n  EXPECT_FLOAT_EQ(3524.5959, g[0]);\n}\n\nTEST(AgradFwdRisingFactorial, FvarFvarVar_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<var> > y;\n  y.val_.val_ = 4.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = rising_factorial(x,y);\n\n  EXPECT_FLOAT_EQ((840.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(840. * (digamma(8) - digamma(4)), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(840 * digamma(8), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(1397.8143, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(840. * (digamma(8) - digamma(4)),g[0]);\n  EXPECT_FLOAT_EQ(840 * digamma(8), g[1]);\n}\nTEST(AgradFwdRisingFactorial, FvarFvarVar_Double_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n  double y(4.0);\n\n  fvar<fvar<var> > a = rising_factorial(x,y);\n\n  EXPECT_FLOAT_EQ((840.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(840. * (digamma(8) - digamma(4)), a.val_.d_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(840. * (digamma(8) - digamma(4)),g[0]);\n}\nTEST(AgradFwdRisingFactorial, Double_FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  double x(4.0);\n  fvar<fvar<var> > y;\n  y.val_.val_ = 4.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = rising_factorial(x,y);\n\n  EXPECT_FLOAT_EQ((840.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(840 * digamma(8), a.d_.val_.val());\n  EXPECT_FLOAT_EQ(0, a.d_.d_.val());\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(840 * digamma(8), g[0]);\n}\nTEST(AgradFwdRisingFactorial, FvarFvarVar_FvarFvarVar_2ndDeriv_x) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<var> > y;\n  y.val_.val_ = 4.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = rising_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(358,g[0]);\n  EXPECT_FLOAT_EQ(1397.8143, g[1]);\n}\nTEST(AgradFwdRisingFactorial, FvarFvarVar_FvarFvarVar_2ndDeriv_y) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<var> > y;\n  y.val_.val_ = 4.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = rising_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(1397.8143, g[0]);\n  EXPECT_FLOAT_EQ(3524.5959,g[1]);\n}\nTEST(AgradFwdRisingFactorial, FvarFvarVar_Double_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n  double y(4.0);\n\n  fvar<fvar<var> > a = rising_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(358,g[0]);\n}\nTEST(AgradFwdRisingFactorial, Double_FvarFvarVar_2ndDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  double x(4.0);\n  fvar<fvar<var> > y;\n  y.val_.val_ = 4.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = rising_factorial(x,y);\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(3524.5959, g[0]);\n}\nTEST(AgradFwdRisingFactorial, FvarFvarVar_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<var> > y;\n  y.val_.val_ = 4.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = rising_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(876.61487, g[0]);\n  EXPECT_FLOAT_EQ(3112.9858,g[1]);\n}\nTEST(AgradFwdRisingFactorial, FvarFvarVar_Double_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n  x.d_.val_ = 1.0;\n  double y(4.0);\n\n  fvar<fvar<var> > a = rising_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(132,g[0]);\n}\nTEST(AgradFwdRisingFactorial, Double_FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  double x(4.0);\n  fvar<fvar<var> > y;\n  y.val_.val_ = 4.0;\n  y.d_.val_ = 1.0;\n  y.val_.d_ = 1.0;\n\n  fvar<fvar<var> > a = rising_factorial(x,y);\n\n  AVEC p = createAVEC(y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  EXPECT_FLOAT_EQ(7540.293, g[0]);\n}\n\nstruct rising_factorial_fun {\n  template <typename T0, typename T1>\n  inline \n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return rising_factorial(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdRisingFactorial, nan) {\n  rising_factorial_fun rising_factorial_;\n  test_nan_mix(rising_factorial_,3.0,5.0,false);\n}\n\n", "meta": {"hexsha": "76c3503000761a89b95a41d088dcbd1e568a429e", "size": 8387, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/rising_factorial_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/rising_factorial_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/rising_factorial_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1107784431, "max_line_length": 69, "alphanum_fraction": 0.662811494, "num_tokens": 3236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825655188238, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5802751524753406}}
{"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// \u5bfb\u627e\u4e24\u4e2a\u56fe\u50cf\u4e2d\u7684\u5bf9\u5e94\u70b9\uff0c\u50cf\u7d20\u5750\u6807\u7cfb\n// \u8f93\u5165\uff1aimg1, img2 \u4e24\u5f20\u56fe\u50cf\n// \u8f93\u51fa\uff1apoints1, points2, \u4e24\u7ec4\u5bf9\u5e94\u76842D\u70b9\nint findCorrespondingPoints(const cv::Mat &img1, const cv::Mat &img2, vector<cv::Point2f> &points1, vector<cv::Point2f> &points2);\n\n// \u76f8\u673a\u5185\u53c2\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    // \u8c03\u7528\u683c\u5f0f\uff1a\u547d\u4ee4 [\u7b2c\u4e00\u4e2a\u56fe] [\u7b2c\u4e8c\u4e2a\u56fe]\n    if (argc != 3)\n    {\n        cout << \"Usage: ba_example img1, img2\" << endl;\n        exit(1);\n    }\n\n    // \u8bfb\u53d6\u56fe\u50cf\n    cv::Mat img1 = cv::imread(argv[1]);\n    cv::Mat img2 = cv::imread(argv[2]);\n\n    // \u627e\u5230\u5bf9\u5e94\u70b9\n    vector<cv::Point2f> pts1, pts2;\n    if (findCorrespondingPoints(img1, img2, pts1, pts2) == false)\n    {\n        cout << \"\u5339\u914d\u70b9\u4e0d\u591f\uff01\" << endl;\n        return 0;\n    }\n    cout << \"\u627e\u5230\u4e86\" << pts1.size() << \"\u7ec4\u5bf9\u5e94\u7279\u5f81\u70b9\u3002\" << endl;\n    // \u6784\u9020g2o\u4e2d\u7684\u56fe\n    // \u5148\u6784\u9020\u6c42\u89e3\u5668\n    g2o::SparseOptimizer optimizer;\n    // \u4f7f\u7528Cholmod\u4e2d\u7684\u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    std::unique_ptr<g2o::BlockSolver_6_3::LinearSolverType> linearSolver = g2o::make_unique<g2o::LinearSolverCholmod<g2o::BlockSolver_6_3::PoseMatrixType>>();\n\n    // 6*3 \u7684\u53c2\u6570\n    std::unique_ptr<g2o::BlockSolver_6_3> block_solver = g2o::make_unique<g2o::BlockSolver_6_3>(std::move(linearSolver));\n    // L-M \u4e0b\u964d\n    g2o::OptimizationAlgorithmLevenberg *algorithm = new g2o::OptimizationAlgorithmLevenberg(std::move(block_solver));\n\n    optimizer.setAlgorithm(algorithm);\n    optimizer.setVerbose(false);\n\n    // \u6dfb\u52a0\u8282\u70b9\n    // \u4e24\u4e2a\u4f4d\u59ff\u8282\u70b9\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); // \u7b2c\u4e00\u4e2a\u70b9\u56fa\u5b9a\u4e3a\u96f6\n        // \u9884\u8bbe\u503c\u4e3a\u5355\u4f4dPose\uff0c\u56e0\u4e3a\u6211\u4eec\u4e0d\u77e5\u9053\u4efb\u4f55\u4fe1\u606f\n        v->setEstimate(g2o::SE3Quat());\n        optimizer.addVertex(v);\n    }\n    // \u5f88\u591a\u4e2a\u7279\u5f81\u70b9\u7684\u8282\u70b9\n    // \u4ee5\u7b2c\u4e00\u5e27\u4e3a\u51c6\n    for (size_t i = 0; i < pts1.size(); i++)\n    {\n        g2o::VertexSBAPointXYZ *v = new g2o::VertexSBAPointXYZ();\n        v->setId(2 + i);\n        // \u7531\u4e8e\u6df1\u5ea6\u4e0d\u77e5\u9053\uff0c\u53ea\u80fd\u628a\u6df1\u5ea6\u8bbe\u7f6e\u4e3a1\u4e86\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    // \u51c6\u5907\u76f8\u673a\u53c2\u6570\n    g2o::CameraParameters *camera = new g2o::CameraParameters(fx, Eigen::Vector2d(cx, cy), 0);\n    camera->setId(0);\n    optimizer.addParameter(camera);\n\n    // \u51c6\u5907\u8fb9\n    // \u7b2c\u4e00\u5e27\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        // \u6838\u51fd\u6570\n        edge->setRobustKernel(new g2o::RobustKernelHuber());\n        optimizer.addEdge(edge);\n        edges.push_back(edge);\n    }\n    // \u7b2c\u4e8c\u5e27\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        // \u6838\u51fd\u6570\n        edge->setRobustKernel(new g2o::RobustKernelHuber());\n        optimizer.addEdge(edge);\n        edges.push_back(edge);\n    }\n\n    cout << \"\u5f00\u59cb\u4f18\u5316\" << endl;\n    optimizer.setVerbose(true);\n    optimizer.initializeOptimization();\n    optimizer.optimize(10);\n    cout << \"\u4f18\u5316\u5b8c\u6bd5\" << endl;\n\n    //\u6211\u4eec\u6bd4\u8f83\u5173\u5fc3\u4e24\u5e27\u4e4b\u95f4\u7684\u53d8\u6362\u77e9\u9635\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    // \u4ee5\u53ca\u6240\u6709\u7279\u5f81\u70b9\u7684\u4f4d\u7f6e\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    // \u4f30\u8ba1inlier\u7684\u4e2a\u6570\n    int inliers = 0;\n    for (auto e : edges)\n    {\n        e->computeError();\n        // chi2 \u5c31\u662f error*\\Omega*error, \u5982\u679c\u8fd9\u4e2a\u6570\u5f88\u5927\uff0c\u8bf4\u660e\u6b64\u8fb9\u7684\u503c\u4e0e\u5176\u4ed6\u8fb9\u5f88\u4e0d\u76f8\u7b26\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 << \"\u5206\u522b\u627e\u5230\u4e86\" << kp1.size() << \"\u548c\" << kp2.size() << \"\u4e2a\u7279\u5f81\u70b9\" << 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) //\u5339\u914d\u70b9\u592a\u5c11\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": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[intersection_segment\r\n//` Calculate the intersection point (or points) of two segments\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/io/wkt/wkt.hpp>\r\n\r\n#include <boost/foreach.hpp>\r\n\r\n\r\nint main()\r\n{\r\n    typedef boost::geometry::model::d2::point_xy<double> P;\r\n    boost::geometry::model::segment<P> segment1, segment2;\r\n    boost::geometry::read_wkt(\"linestring(1 1,2 2)\", segment1);\r\n    boost::geometry::read_wkt(\"linestring(2 1,1 2)\", segment2);\r\n\r\n    std::vector<P> intersections;\r\n    boost::geometry::intersection(segment1, segment2, intersections);\r\n\r\n    BOOST_FOREACH(P const& p, intersections)\r\n    {\r\n        std::cout << \" \" << boost::geometry::wkt(p);\r\n    }\r\n    std::cout << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[intersection_segment_output\r\n/*`\r\nOutput:\r\n[pre\r\n POINT(1.5 1.5)\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "434bcafbcc5ab849bbf64840515bd91daa6bff53", "size": 1252, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/intersection_segment.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/intersection_segment.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/intersection_segment.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": 24.0769230769, "max_line_length": 80, "alphanum_fraction": 0.6653354633, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.580230512907915}}
{"text": "#include \"optimization/ransac.h\"\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <random>\n\n#include \"gflags/gflags.h\"\n#include \"glog/logging.h\"\n#include \"glog/stl_logging.h\"\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"optimization/ransac_impl.h\"\n\nDEFINE_int32(num_test_cases, 10, \"Number of test cases to run.\");\n\nnamespace dungeon {\n\n// A model that fits a straight line to observations in 2D.\nclass LinearModel : public RansacModelBase {\n public:\n  // Given that each observation is a vector in R^2, fits parameters (m, b)\n  // to minimize L2 error:\n  //   \\sum_i || m*x(i, 0) + b - x(i, 1) ||^2\n  virtual void Fit(const std::vector<Eigen::MatrixXf>& observations) override {\n    Eigen::MatrixXf A(observations.size(), 2);\n    Eigen::MatrixXf b(observations.size(), 1);\n    for (size_t i = 0; i < observations.size(); ++i) {\n      const Eigen::MatrixXf& obs = observations[i];\n      CHECK_EQ(2, obs.rows());\n      CHECK_EQ(1, obs.cols());\n\n      A(i, 0) = obs(0, 0);\n      A(i, 1) = 1.0;\n      b(i, 0) = obs(1, 0);\n    }\n    params_ = A.colPivHouseholderQr().solve(b);\n    CHECK_EQ(2, params_.rows());\n    CHECK_EQ(1, params_.cols());\n  }\n\n  // Returns abs(m*x(0) + b - x(1)) for a given observation x.\n  virtual double EvaluateError(const Eigen::MatrixXf& pt) const override {\n    CHECK_EQ(2, pt.rows());\n    CHECK_EQ(1, pt.cols());\n    float x = pt(0, 0);\n    float y = pt(1, 0);\n    return std::abs(params_(0, 0) * x + params_(1, 0) - y);\n  }\n\n  virtual Eigen::MatrixXf params() const override { return params_; }\n\n  // Returns the minimum number of observations needed to fit the model.\n  virtual int min_num_observations() const { return 2; }\n\n private:\n  Eigen::MatrixXf params_;\n};\n\n// Returns a collection of observations for the above model.\nstd::vector<Eigen::MatrixXf> CreateObservationCollection(\n    const Eigen::MatrixXf& params, int num_observations) {\n  CHECK_EQ(2, params.rows());\n  CHECK_EQ(1, params.cols());\n  const float params_x = params(0, 0);\n  const float params_y = params(1, 0);\n  std::vector<Eigen::MatrixXf> output;\n  for (int i = 0; i < num_observations; ++i) {\n    float val = drand48() * 10.0 - 5.0;\n    output.push_back(\n        Eigen::MatrixXf(Eigen::Vector2f(val, params_x * val + params_y)));\n  }\n  return output;\n}\n\nstd::vector<Eigen::MatrixXf> GenerateRandomModelParams(int n) {\n  srand(0);\n  std::vector<Eigen::MatrixXf> output;\n  for (int i = 0; i < n; ++i) {\n    output.push_back(Eigen::MatrixXf::Random(2, 1));\n  }\n  return output;\n}\n\nclass RansacTest : public ::testing::Test,\n                   public ::testing::WithParamInterface<Eigen::MatrixXf> {\n public:\n  void SetUp() {\n    srand(0);\n    opts = RansacOptions{\n        .num_iterations = 1000,\n        .inlier_threshold = 0.001,\n        .min_inlier_fraction = 0.5,\n        .random_seed = 0,\n    };\n    CHECK_GT(kNumInliers / static_cast<double>(kNumInliers + kNumOutliers),\n             opts.min_inlier_fraction)\n        << \"The *actual* inlier ratio is smaller than the inlier ratio \"\n           \"required for RANSAC to find the solution. Your test is specifying \"\n           \"a scenario in which an algorithm will never succeed!!\";\n  }\n  RansacOptions opts;\n  static constexpr int kNumInliers = 10;\n  static constexpr int kNumOutliers = 3;\n};\n\nINSTANTIATE_TEST_CASE_P(\n    RansacTestSuite, RansacTest,\n    ::testing::ValuesIn(GenerateRandomModelParams(FLAGS_num_test_cases)));\n\nTEST_P(RansacTest, LeastSquareFitWithoutOutliersAndWithoutNoise) {\n  // Verify that RANSAC can be used to fit a line in absence of noise and\n  // absence of outliers.\n  const Eigen::MatrixXf params = GetParam();\n  std::vector<Eigen::MatrixXf> observations =\n      CreateObservationCollection(params, /*num_observations=*/kNumInliers);\n  auto solution =\n      RansacFit(std::make_unique<LinearModel>(), observations, opts);\n  ASSERT_TRUE(solution.success);\n  EXPECT_THAT(solution.inliers, ::testing::Each(true));\n  EXPECT_EQ(solution.num_inliers, observations.size());\n  EXPECT_LE(solution.error, 1e-3);\n  EXPECT_LE((solution.params - params).norm(), 1e-2);\n}\n\nTEST_P(RansacTest, LeastSquareFitWithOutliersAndWithoutNoise) {\n  // Verify that RANSAC can be used to fit a line in absence of noise but with\n  // some outliers.\n  const Eigen::MatrixXf params = GetParam();\n  std::vector<Eigen::MatrixXf> observations =\n      CreateObservationCollection(params, /*num_observations=*/kNumInliers);\n  std::vector<bool> inliers(kNumInliers, true);\n  // Add several outliers.\n  for (int i = 0; i < kNumOutliers; ++i) {\n    observations.push_back(10.0 * Eigen::MatrixXf::Random(2, 1));\n    inliers.push_back(false);\n  }\n\n  auto solution =\n      RansacFit(std::make_unique<LinearModel>(), observations, opts);\n  ASSERT_TRUE(solution.success);\n  EXPECT_EQ(solution.num_inliers, kNumInliers);\n  EXPECT_EQ(solution.inliers, inliers);\n  EXPECT_LE(solution.error, 1e-3);\n  EXPECT_LE((solution.params - params).norm(), 1e-2);\n}\n\nTEST(RansacRunOneIteration, Works) {\n  LinearModel model;\n  std::vector<Eigen::MatrixXf> observations{\n      Eigen::MatrixXf(Eigen::Vector2f(0, 0)),\n      Eigen::MatrixXf(Eigen::Vector2f(1, 1)),\n      Eigen::MatrixXf(Eigen::Vector2f(2, 2)),\n  };\n  RansacOptions opts{\n      .num_iterations = 0,  // unused\n      .inlier_threshold = 0.001,\n      .min_inlier_fraction = 0.5,\n      .random_seed = 0,  // unused\n  };\n  auto soln = internal::RansacRunOneIteration(\n      observations, std::unordered_set<int>{0, 1}, opts, model);\n  ASSERT_TRUE(soln.success);\n  EXPECT_NEAR(soln.error, 0.0, 1e-2);\n  EXPECT_EQ(soln.num_inliers, 3);\n}\n\nTEST(RansacIsSolutionBetter, Works) {\n  RansacSolution a{.success = true, .error = 1.0};\n  RansacSolution b{.success = true, .error = 10.0};\n  ASSERT_TRUE(internal::IsSolutionBetter(a, b));\n}\n\n}  // namespace dungeon\n", "meta": {"hexsha": "8b0fa3d01f6e02c108ca46d7eeb01c9a303a38fc", "size": 5760, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "optimization/ransac_test.cpp", "max_stars_repo_name": "vasiliykarasev/dungeon", "max_stars_repo_head_hexsha": "0ea62593ec68ddb0069ef5d79356a1245d4364d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optimization/ransac_test.cpp", "max_issues_repo_name": "vasiliykarasev/dungeon", "max_issues_repo_head_hexsha": "0ea62593ec68ddb0069ef5d79356a1245d4364d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimization/ransac_test.cpp", "max_forks_repo_name": "vasiliykarasev/dungeon", "max_forks_repo_head_hexsha": "0ea62593ec68ddb0069ef5d79356a1245d4364d5", "max_forks_repo_licenses": ["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.1034482759, "max_line_length": 79, "alphanum_fraction": 0.6760416667, "num_tokens": 1689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5801707578307683}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2015 Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include <rokko/rokko.hpp>\n#include <rokko/mapping_bc.hpp>\n#include <rokko/collective.hpp>\n#include <rokko/utility/solver_name.hpp>\n#include <rokko/utility/frank_matrix.hpp>\n#include <rokko/utility/check_orthogonality.hpp>\n#include <boost/lexical_cast.hpp>\n#include <iostream>\n\n\ntypedef rokko::matrix_col_major matrix_major;\n\ntemplate<typename T, typename MATRIX_MAJOR>\nvoid function_matrix(rokko::localized_vector<double> const& eigval_tmp, rokko::distributed_matrix<T, MATRIX_MAJOR> const& eigvec, rokko::distributed_matrix<T, MATRIX_MAJOR>& result, rokko::distributed_matrix<T, MATRIX_MAJOR>& tmp) {\n  for (int local_j=0; local_j<eigvec.get_n_local(); ++local_j) {\n    int global_j = eigvec.translate_l2g_col(local_j);\n    double coeff = eigval_tmp(global_j);\n    for (int local_i=0; local_i<eigvec.get_m_local(); ++local_i) {\n      double value = eigvec.get_local(local_i, local_j);\n      tmp.set_local(local_i, local_j, coeff * value); \n    }\n  }\n  product(1, tmp, false, eigvec, true, 0, result);\n}\n\ntemplate<typename T, typename MATRIX_MAJOR>\nvoid diagonalize_fixedB(rokko::parallel_dense_solver& solver, rokko::distributed_matrix<T, MATRIX_MAJOR>& A, rokko::distributed_matrix<T, MATRIX_MAJOR>& B,\n\t\t\trokko::localized_vector<double>& eigval, rokko::distributed_matrix<T, MATRIX_MAJOR>& eigvec, T tol = 0) {\n  rokko::distributed_matrix<double, matrix_major> tmp(A.get_mapping()), Binvroot(A.get_mapping()), mat(A.get_mapping());\n  rokko::parameters params;\n  int myrank = A.get_myrank();\n  params.set(\"routine\", \"\");\n  solver.diagonalize(B, eigval, eigvec, params);\n  // computation of B^{-1/2}\n  for(int i=0; i<eigval.size(); ++i)\n    eigval(i) = (eigval(i) > tol) ? sqrt(1/eigval(i)) : 0;\n  function_matrix(eigval, eigvec, Binvroot, tmp);\n  \n  // computation of B^{-1/2} A B^{-1/2}\n  product(1, Binvroot, false, A, false, 0, tmp);\n  product(1, tmp, false, Binvroot, false, 0, mat);\n  // diagonalization of B^{-1/2} A B^{-1/2}\n  solver.diagonalize(mat, eigval, tmp, params);\n\n  // computation of {eigvec of Ax=lambda Bx} = B^{-1/2} {eigvec of B^{-1/2} A B^{-1/2}}\n  product(1, Binvroot, false, tmp, false, 0, eigvec);\n}\n\ntemplate<typename T, typename MATRIX_MAJOR>\nvoid set_A_B(rokko::localized_matrix<T, MATRIX_MAJOR>& locA, rokko::localized_matrix<T, MATRIX_MAJOR>& locB) {\n  if ((locA.rows() != 4) || (locA.cols() != 4) || (locB.rows() != 4) || (locB.cols() != 4)) {\n    std::cerr << \"error: size must be 4!\" << std::endl;\n    throw;\n  }\n  locA << 0.24, 0.39, 0.42, -0.16,\n          0.39, -0.11, 0.79, 0.63,\n          0.42, 0.79, -0.25, 0.48,\n         -0.16, 0.63, 0.48, -0.03;\n\n  locB << 4.16, -3.12, 0.56, -0.10,\n         -3.12, 5.03, -0.83, 1.09,\n          0.56, -0.83, 0.76, 0.34,\n         -0.10, 1.09, 0.34, 1.18;\n}\n\n  \nint main(int argc, char *argv[]) {\n  int provided;\n  MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);\n  MPI_Comm comm = MPI_COMM_WORLD;\n  std::string library_routine(rokko::parallel_dense_solver::default_solver());\n  std::string library, routine;\n  int dim = 4;\n  if (argc >= 2) library_routine = argv[1];\n  rokko::split_solver_name(library_routine, library, routine);\n\n  rokko::grid g(comm);\n  int myrank = g.get_myrank();\n\n  std::cout.precision(5);\n\n  rokko::parallel_dense_solver solver(library);\n  solver.initialize(argc, argv);\n  if (myrank == 0)\n    std::cout << \"Eigenvalue decomposition of Frank matrix\" << std::endl\n\t      << \"library:routine = \" << library_routine << std::endl\n              << \"num_procs = \" << g.get_nprocs() << std::endl\n              #ifdef _OPENMP\n              << \"num_threads per process = \" << omp_get_max_threads() << std::endl\n              #endif\n\t      << \"routine = \" << routine << std::endl\n              << \"dimension = \" << dim << std::endl;\n\n  rokko::localized_matrix<double, matrix_major> locA(dim, dim), locB(dim, dim);\n  set_A_B(locA, locB);\n  if (myrank == 0) std::cout << \"locA:\" << std::endl << locA << std::endl;  \n\n  rokko::mapping_bc<matrix_major> map(dim, g, solver);\n  rokko::distributed_matrix<double, matrix_major> A(map), B(map), eigvec(map);\n  rokko::localized_vector<double> eigval(dim);\n  rokko::scatter(locA, A, 0);\n  rokko::scatter(locB, B, 0);\n  MPI_Barrier(comm);\n  if (myrank == 0) std::cout << \"A:\" << std::endl;\n  std::cout << A << std::endl;\n\n  diagonalize_fixedB(solver, A, B, eigval, eigvec);\n\n  rokko::localized_matrix<double, matrix_major> eigvec_loc(dim, dim);\n  rokko::gather(eigvec, eigvec_loc, 0);\n\n  set_A_B(locA, locB);\n\n  if (myrank == 0) {\n    bool sorted = true;\n    for (unsigned int i = 1; i < dim; ++i) sorted &= (eigval(i-1) <= eigval(i));\n    if (!sorted) std::cout << \"Warning: eigenvalues are not sorted in ascending order!\\n\";\n    std::cout << \"largest eigenvalues:\";\n    for (int i = 0; i < std::min(dim, 10); ++i) std::cout << ' ' << eigval(dim - 1 - i);\n    std::cout << std::endl;\n\n    std::cout << \"eigenvalues:\\n\" << eigval.transpose() << std::endl\n\t      << \"eigvectors:\\n\" << eigvec_loc << std::endl;\n    std::cout << \"orthogonality of eigenvectors:\" << std::endl\n\t      << eigvec_loc.transpose() * locB * eigvec_loc << std::endl;\n    std::cout << \"residual of the smallest eigenvalue/vector (A x - lambda B x):\" << std::endl\n\t      << (locA * eigvec_loc.col(0) - eigval(0) * locB * eigvec_loc.col(0)).transpose() << std::endl;\n  }\n\n  solver.finalize();\n  MPI_Finalize();\n}\n", "meta": {"hexsha": "0782d97c04073ed8d17bc122e38db801d716d605", "size": 5792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cxx/dense/gev_fixedB_mpi.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/cxx/dense/gev_fixedB_mpi.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/cxx/dense/gev_fixedB_mpi.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2222222222, "max_line_length": 232, "alphanum_fraction": 0.6305248619, "num_tokens": 1828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.580170741586817}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/detail/diff_div.hpp>\n#include <eve/function/diff/gegenbauer.hpp>\n#include <boost/math/special_functions/gegenbauer.hpp>\n#include <type_traits>\n\nTTS_CASE_TPL(\"Check diff(gegenbauer) return type\", EVE_TYPE)\n{\n    TTS_EXPR_IS(eve::diff(eve::gegenbauer)((unsigned int)(0), T(), T()), T);\n}\n\nTTS_CASE_TPL(\"Check eve::diff(eve::gegenbauer) behavior\", EVE_TYPE)\n{\n  using elt_t = eve::element_type_t<T>;\n  elt_t l(-3.0/8.0);\n  auto eve__gegenbauer =  [&l](unsigned n, auto x) { return eve::diff(eve::gegenbauer)(n, T(l), x); };\n  auto boost_gegenbauer =  [&l](unsigned n, auto x) { return boost::math::gegenbauer_derivative(n, double(l), x, 1u); };\n\n  for(unsigned int i=0; i < 10; ++i)\n  {\n    TTS_ULP_EQUAL(eve__gegenbauer(i, T(10)), T(boost_gegenbauer(i, 10.0)), 1);\n    TTS_ULP_EQUAL(eve__gegenbauer(i, T(5)), T(boost_gegenbauer(i, 5.0)), 1);\n    TTS_ULP_EQUAL(eve__gegenbauer(i, T(2)), T(boost_gegenbauer(i, 2.0)), 1);\n    TTS_ULP_EQUAL(eve__gegenbauer(i, T(1)), T(boost_gegenbauer(i, 1.0)), 20);\n    TTS_ULP_EQUAL(eve__gegenbauer(i, T(0)), T(boost_gegenbauer(i, 0.0)), 1);\n  }\n}\n", "meta": {"hexsha": "3bb416aa1d7679fb82928bcb47514c84010438dc", "size": 1411, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/core/gegenbauer/diff/gegenbauer.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/core/gegenbauer/diff/gegenbauer.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/core/gegenbauer/diff/gegenbauer.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5, "max_line_length": 120, "alphanum_fraction": 0.584691708, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.580170741586817}}
{"text": "#include \"prime.hpp\"\n\n// Miller-Rabin prime test algorithm.\n#include <boost/multiprecision/miller_rabin.hpp>\n#include <random>\n\nboost::multiprecision::cpp_int cryptb::prime::gen_random(const int num_bytes, random_engine& engine)\n{\n\tif (num_bytes <= 0)\n\t\tthrow std::invalid_argument(\"Error in function \\\"cryptb::prime::gen_random\\\".\"\n\t\t\t\" The argument: \\\"num_bytes\\\" <= 0. There is no prime number with that number of bytes.\");\n\tboost::multiprecision::cpp_int candidate;\n\t// TODO: Use seed_seq here to seed the std::mt19937_64 engine better.\n\t// Also, don't allocate the std::mt19937_64 engine on the stack because\n\t// it's more than 1000 bytes long.\n\tconst auto seed = engine.operator()(sizeof(std::mt19937_64::result_type));\n\tstd::mt19937_64 miller_rabin_engine(static_cast<std::mt19937_64::result_type>(seed));\n\tdo\n\t{\n\t\tcandidate = engine.operator()(num_bytes);\n\t\t// 64 Should be enough. The higher the number of trials, the lower the probability is for a false positive.\n\t\t// Note: making this number lower will significantly improve performance.\n\t} while (boost::multiprecision::miller_rabin_test(candidate, 64, miller_rabin_engine) == false);\n\treturn candidate;\n}\n", "meta": {"hexsha": "a76fa312052feb6ebc8caee971a928c2409be7a8", "size": 1169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rsa_cpp/prime.cpp", "max_stars_repo_name": "BigBIueWhale/rsa_cpp", "max_stars_repo_head_hexsha": "9711456119ec0a79f5931153c32bde2ea4082bb5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-08T18:16:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:16:06.000Z", "max_issues_repo_path": "rsa_cpp/prime.cpp", "max_issues_repo_name": "BigBIueWhale/rsa_cpp", "max_issues_repo_head_hexsha": "9711456119ec0a79f5931153c32bde2ea4082bb5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-12-29T18:07:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-08T18:15:42.000Z", "max_forks_repo_path": "rsa_cpp/prime.cpp", "max_forks_repo_name": "BigBIueWhale/rsa_cpp", "max_forks_repo_head_hexsha": "9711456119ec0a79f5931153c32bde2ea4082bb5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-29T10:42:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T13:46:46.000Z", "avg_line_length": 44.9615384615, "max_line_length": 109, "alphanum_fraction": 0.75106929, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5801439069467729}}
{"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": "/*\n supercell.hxx\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#pragma once\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\nnamespace ublas = boost::numeric::ublas;\n\nclass Supercell {\n\npublic:\n\n  Supercell(ublas::vector<long> supercell_extension,\n            long primitive_number_of_atoms,\n            ublas::matrix<double> primitive_lattice_vectors,\n            ublas::matrix<double> primitive_basis_vectors,\n\t    double concentration);\n\n  ublas::vector<long> supercell_extension;\n  long number_of_atoms;\n  ublas::matrix<double> lattice_vectors;\n  ublas::matrix<double> basis_vectors;\n  ublas::vector<long> pointers;\n  \nprivate:\n\n  long primitive_number_of_atoms_;\n  ublas::matrix<double> primitive_lattice_vectors_;\n  ublas::matrix<double> primitive_basis_vectors_;\n  double concentration_;\n\n};\n", "meta": {"hexsha": "5230607a64b575534465fc59cf30e79f7213f192", "size": 1017, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/supercell.hxx", "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.hxx", "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.hxx", "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": 24.2142857143, "max_line_length": 67, "alphanum_fraction": 0.7492625369, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5799953919848773}}
{"text": "/**\n * @file ind2sub_test.cpp\n * @author Nilay Jain\n *\n * Test the backported Armadillo ind2sub() and sub2ind() functions.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nBOOST_AUTO_TEST_SUITE(ind2subTest);\n\n/**\n * This test checks whether ind2sub and sub2ind are\n * compiled successfully and that they function properly.\n */\nBOOST_AUTO_TEST_CASE(ind2sub_test)\n{\n  arma::mat A = arma::randu(4, 5);\n  size_t index = 13;\n  arma::uvec u = arma::ind2sub(arma::size(A), index);\n\n  BOOST_REQUIRE_EQUAL(u(0), index % A.n_rows);\n  BOOST_REQUIRE_EQUAL(u(1), index / A.n_rows);\n\n  index = arma::sub2ind(arma::size(A), u(0), u(1));\n  BOOST_REQUIRE_EQUAL(index, u(0) + u(1) * A.n_rows);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "eb522e9d57953442f0a13f7585c5a2d44628ef60", "size": 1042, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/ind2sub_test.cpp", "max_stars_repo_name": "kosmaz/Mlpack", "max_stars_repo_head_hexsha": "62100ddca45880a57e7abb0432df72d285e5728b", "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": "2017-01-17T14:02:37.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-17T14:02:37.000Z", "max_issues_repo_path": "src/mlpack/tests/ind2sub_test.cpp", "max_issues_repo_name": "kosmaz/Mlpack", "max_issues_repo_head_hexsha": "62100ddca45880a57e7abb0432df72d285e5728b", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/ind2sub_test.cpp", "max_forks_repo_name": "kosmaz/Mlpack", "max_forks_repo_head_hexsha": "62100ddca45880a57e7abb0432df72d285e5728b", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9444444444, "max_line_length": 78, "alphanum_fraction": 0.7120921305, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925402, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5799737477862531}}
{"text": "//  (C) Copyright Eric Niebler 2005.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/time_series/characteristic_series.hpp>\r\n#include <boost/time_series/constant_series.hpp>\r\n#include <boost/time_series/dense_series.hpp>\r\n#include <boost/time_series/heaviside_series.hpp>\r\n#include <boost/time_series/piecewise_constant_series.hpp>\r\n#include <boost/time_series/shifted_series.hpp>\r\n#include <boost/time_series/sparse_series.hpp>\r\n#include <boost/time_series/ordered_inserter.hpp>\r\n#include <boost/time_series/numeric/shift.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace unit_test;\r\n\r\nnamespace seq = boost::sequence;\r\nnamespace rrs = boost::range_run_storage;\r\n\r\nusing time_series::inf;\r\n\r\nstd::ptrdiff_t min_ = -inf;\r\nstd::ptrdiff_t max_ = inf;\r\n\r\ntime_series::piecewise_constant_series<int> tmp;\r\n#define BOOST_CHECK_RANGE_RUN_EQUAL(x,y)\\\r\n    BOOST_CHECK_EQUAL(x, (boost::time_series::make_ordered_inserter(::tmp) y .commit(), ::tmp))\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// test_shift\r\n//\r\ntemplate<typename Series>\r\nvoid test_shift()\r\n{\r\n    Series base;\r\n\r\n    time_series::make_ordered_inserter(base)\r\n        (1, -1, 2)\r\n        (2, 3, 5)\r\n        (3, 6, 9)\r\n    .commit();\r\n\r\n    // Sanity check\r\n    BOOST_CHECK_RANGE_RUN_EQUAL(base, (1, -1, 2)(2, 3, 5)(3, 6, 9));\r\n\r\n    // Test1: shift right 1\r\n    Series test1 = time_series::shift(base, 1);\r\n    BOOST_CHECK_EQUAL(test1.discretization(), 1);\r\n    BOOST_CHECK_RANGE_RUN_EQUAL(test1, (1, 0, 3)(2, 4, 6)(3, 7, 10));\r\n\r\n    // Test2: shift left 1\r\n    Series test2 = time_series::shift(base, -1);\r\n    BOOST_CHECK_EQUAL(test2.discretization(), 1);\r\n    BOOST_CHECK_RANGE_RUN_EQUAL(test2, (1, -2, 1)(2, 2, 4)(3, 5, 8));\r\n\r\n    // Test3: shift right 5\r\n    Series test3 = time_series::shift(base, 5);\r\n    BOOST_CHECK_EQUAL(test3.discretization(), 1);\r\n    BOOST_CHECK_RANGE_RUN_EQUAL(test3, (1, 4, 7)(2, 8, 10)(3, 11, 14));\r\n\r\n    // Test4: shift left 5\r\n    Series test4 = time_series::shift(base, -5);\r\n    BOOST_CHECK_EQUAL(test4.discretization(), 1);\r\n    BOOST_CHECK_RANGE_RUN_EQUAL(test4, (1, -6, -3)(2, -2, 0)(3, 1, 4));\r\n\r\n    // Test5: shift right 4, self-assign\r\n    test3 = time_series::shift(test3, 4);\r\n    BOOST_CHECK_EQUAL(test3.discretization(), 1);\r\n    BOOST_CHECK_RANGE_RUN_EQUAL(test3, (1, 8, 11)(2, 12, 14)(3, 15, 18));\r\n\r\n    // Test6: shift left 4, self-assign\r\n    test4 = time_series::shift(test4, -4);\r\n    BOOST_CHECK_EQUAL(test4.discretization(), 1);\r\n    BOOST_CHECK_RANGE_RUN_EQUAL(test4, (1, -10, -7)(2, -6, -4)(3, -3, 0));\r\n}\r\n\r\nvoid test_shift2()\r\n{\r\n    using namespace boost;\r\n    using namespace time_series;\r\n\r\n    dense_series<int> d(-2, 8, 5);\r\n    shifted_series<dense_series<int> > sd = shift(d, 5);\r\n\r\n    characteristic_series<int> ch(3, 13, 5);\r\n    BOOST_CHECK_EQUAL(ch, sd);\r\n\r\n    constant_series<int> c(5);\r\n    shifted_series<constant_series<int> > sc = shift(c, -5);\r\n\r\n    BOOST_CHECK_EQUAL(0, std::distance(seq::begin(sc), seq::end(sc)));\r\n    BOOST_CHECK_EQUAL(min_, rrs::offset(rrs::pre_run(sc)));\r\n    BOOST_CHECK_EQUAL(max_, rrs::end_offset(rrs::pre_run(sc)));\r\n    BOOST_CHECK_EQUAL(5, rrs::pre_value(sc));\r\n}\r\n\r\nvoid test_heaviside()\r\n{\r\n    using namespace time_series;\r\n\r\n    heaviside_unit_series<int> h(start = 5);\r\n    heaviside_unit_series<int> r(start = 4);\r\n    h = shift(h, -1);\r\n\r\n    BOOST_CHECK_EQUAL(h, r);\r\n\r\n    make_ordered_inserter(r)(1, 6, inf).commit();\r\n    h = shift(h, 2);\r\n\r\n    BOOST_CHECK_EQUAL(h, r);\r\n}\r\n\r\nvoid test_floating_point_shift()\r\n{\r\n    using namespace boost;\r\n    using namespace time_series;\r\n\r\n    characteristic_series<int,int,double> ch(3.5, 13.5, 5);\r\n    shifted_series<characteristic_series<int,int,double> > sch = shift(ch, -0.5);\r\n\r\n    BOOST_CHECK_EQUAL(0, std::distance(seq::begin(sch), seq::end(sch)));\r\n    BOOST_CHECK_CLOSE(3.0, rrs::offset(rrs::pre_run(sch)),0.1);\r\n    BOOST_CHECK_CLOSE(13.0, rrs::end_offset(rrs::pre_run(sch)),0.1);\r\n    BOOST_CHECK_EQUAL(5, rrs::pre_value(sch));\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// init_unit_test_suite\r\n//\r\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n    test_suite *test = BOOST_TEST_SUITE(\"shift test\");\r\n\r\n    void (*pfn_dense)() = &test_shift<time_series::dense_series<int> >;\r\n    test->add(BOOST_TEST_CASE(pfn_dense));\r\n\r\n    void (*pfn_sparse)() = &test_shift<time_series::sparse_series<int> >;\r\n    test->add(BOOST_TEST_CASE(pfn_sparse));\r\n\r\n    void (*pfn_piecewise_constant)() = &test_shift<time_series::piecewise_constant_series<int> >;\r\n    test->add(BOOST_TEST_CASE(pfn_piecewise_constant));\r\n\r\n    test->add(BOOST_TEST_CASE(&test_shift2));\r\n    test->add(BOOST_TEST_CASE(&test_heaviside));\r\n    test->add(BOOST_TEST_CASE(&test_floating_point_shift));\r\n\r\n    return test;\r\n}\r\n", "meta": {"hexsha": "ea8f0173646211a0e27d8b30327835601164b606", "size": 5073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/time_series/test/shift.cpp", "max_stars_repo_name": "ericniebler/time_series", "max_stars_repo_head_hexsha": "4040119366cc21f25c7734bb355e4a647296a96d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T11:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T03:39:29.000Z", "max_issues_repo_path": "libs/time_series/test/shift.cpp", "max_issues_repo_name": "ericniebler/time_series", "max_issues_repo_head_hexsha": "4040119366cc21f25c7734bb355e4a647296a96d", "max_issues_repo_licenses": ["BSL-1.0"], "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/time_series/test/shift.cpp", "max_forks_repo_name": "ericniebler/time_series", "max_forks_repo_head_hexsha": "4040119366cc21f25c7734bb355e4a647296a96d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-05-09T02:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-02T13:39:29.000Z", "avg_line_length": 33.1568627451, "max_line_length": 98, "alphanum_fraction": 0.6501084171, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.5799737433983763}}
{"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_X86_SSE1_SIMD_FUNCTION_SORT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_SSE1_SIMD_FUNCTION_SORT_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/function/shuffle.hpp>\n#include <boost/simd/function/max.hpp>\n#include <boost/simd/function/min.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd =  boost::dispatch;\n  namespace bs =  boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( sort_\n                          , (typename A0)\n                          , bs::sse_\n                          , bs::pack_<bd::single_<A0>, bs::sse_>\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() ( const A0 & a0 ) const BOOST_NOEXCEPT\n    {\n      // half-permute\n      A0 p0 = shuffle<2,3,0,1>(a0);\n      A0 mn = min(a0,p0);\n      A0 mx = max(a0,p0);\n      // cross vector concatenation and reversal\n      A0 minmax = shuffle<0,1,6,7>(mn,mx);\n      A0 maxmin = shuffle<1,0,7,6>(mn,mx);\n\n      mn = min(minmax,maxmin);\n      mx = max(minmax,maxmin);\n\n      // rearrange partial max/min while keeping min and max in place\n         p0 = shuffle<0,2,5,7>(mn,mx);\n      A0 p1 = shuffle<0,2,1,3>(p0);\n\n      // Bring sorted min/max in the proper place\n      return shuffle<0,1,6,7>(min(p1,p0),max(p1,p0));\n    }\n  };\n} } }\n\n#endif\n\n", "meta": {"hexsha": "2df123d8fe5ccf1edb1540d13d14cd6921f941b9", "size": 1721, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/x86/sse1/simd/function/sort.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/x86/sse1/simd/function/sort.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/x86/sse1/simd/function/sort.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7321428571, "max_line_length": 100, "alphanum_fraction": 0.5438698431, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5799593578090008}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <StateSpace.hpp>\n\nnamespace RRT {\n\n/**\n * @brief A 2d plane with continuous states and no obstacles.\n */\nclass PlaneStateSpace : public StateSpace {\npublic:\n    PlaneStateSpace(double width, double height)\n        : _width(width), _height(height) {}\n\n    Eigen::Vector2d randomState() const {\n        return Eigen::Vector2d(drand48() * width(), drand48() * height());\n    }\n\n    Eigen::Vector2d intermediateState(const Eigen::Vector2d& source,\n                                  const Eigen::Vector2d& target,\n                                  double stepSize) const {\n        Eigen::Vector2d delta = target - source;\n        delta = delta / delta.norm();  //  unit vector\n\n        Eigen::Vector2d val = source + delta * stepSize;\n        return val;\n    }\n\n    double distance(const Eigen::Vector2d& from, const Eigen::Vector2d& to) const {\n        Eigen::Vector2d delta = from - to;\n        return sqrtf(powf(delta.x(), 2) + powf(delta.y(), 2));\n    }\n\n    /**\n     * Returns a boolean indicating whether the given point is within bounds.\n     */\n    bool stateValid(const Eigen::Vector2d& pt) const {\n        return pt.x() >= 0 && pt.y() >= 0 && pt.x() < width() &&\n               pt.y() < height();\n    }\n\n    double width() const { return _width; }\n    double height() const { return _height; }\n\nprivate:\n    double _width, _height;\n};\n\n}  // namespace RRT\n", "meta": {"hexsha": "f6b896fb20ae6249865b57ffaa8e501dcf644e9d", "size": 1407, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "robojackets_trajectory_planning_node/src/2dplane/PlaneStateSpace.hpp", "max_stars_repo_name": "JonathanSchmalhofer/RecursiveStereoUAV", "max_stars_repo_head_hexsha": "005642f5afbfe719c632ce81411af9ac5e8522f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2018-04-07T18:07:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T11:48:34.000Z", "max_issues_repo_path": "robojackets_trajectory_planning_node/src/2dplane/PlaneStateSpace.hpp", "max_issues_repo_name": "JonathanSchmalhofer/RecursiveStereoUAV", "max_issues_repo_head_hexsha": "005642f5afbfe719c632ce81411af9ac5e8522f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-21T12:55:07.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-21T14:33:09.000Z", "max_forks_repo_path": "robojackets_trajectory_planning_node/src/2dplane/PlaneStateSpace.hpp", "max_forks_repo_name": "JonathanSchmalhofer/RecursiveStereoUAV", "max_forks_repo_head_hexsha": "005642f5afbfe719c632ce81411af9ac5e8522f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-10-11T09:10:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T06:28:24.000Z", "avg_line_length": 27.5882352941, "max_line_length": 83, "alphanum_fraction": 0.5870646766, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5799593467187628}}
{"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 <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\n//declaration of the stencil kinEnergy\nBZ_DECLARE_STENCIL2(kinEnergy,A,B)\nB=Laplacian3D_stencilop(A);\nBZ_END_STENCIL_WITH_SHAPE(shape(-1,-1,-1),shape(+1,+1,+1))\n\ntypedef Array<complex<double>,3> array3d;\n\nint main()\n{\nconst int N=5;\narray3d A(N,N,N);\narray3d B(N,N,N);\n// Fill a three-dimensional array with a Gaussian function\nfirstIndex i;\nsecondIndex j;\nthirdIndex k;\nfloat midpoint = 3.;\nfloat c = - 1.;\n//A = exp(c * (sqr(i-midpoint) + sqr(j-midpoint)\n//    + sqr(k-midpoint)));\nA = zip( exp(c * (sqr(i-midpoint) + sqr(j-midpoint)\n    + sqr(k-midpoint))), 0.0, complex<double>());\n\napplyStencil(kinEnergy(),A,B);\n\nArray<complex<double>,1> a_view(A.data(),shape(N*N*N));\ncout << a_view;\nArray<complex<double>,1> out_view(B.data(),shape(N*N*N));\ncout << out_view<<endl;\n}\n\n", "meta": {"hexsha": "e1a0833e4bdd278cc03fb7807faf072923d8e5ee", "size": 829, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/matthias-troyer-2.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/testsuite/matthias-troyer-2.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/testsuite/matthias-troyer-2.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.0277777778, "max_line_length": 58, "alphanum_fraction": 0.6851628468, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5799593421639146}}
{"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": "#ifndef STAN_MATH_PRIM_SCAL_FUN_CONSTANTS_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_CONSTANTS_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/scal/fun/inv.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\nusing std::log;\nusing std::sqrt;\n\n/**\n * The base of the natural logarithm,\n * \\f$ e \\f$.\n */\nconst double E = boost::math::constants::e<double>();\n\n/**\n * The value of the square root of 2,\n * \\f$ \\sqrt{2} \\f$.\n */\nconst double SQRT_2 = sqrt(2.0);\n\n/**\n * The value of 1 over the square root of 2,\n * \\f$ 1 / \\sqrt{2} \\f$.\n */\nconst double INV_SQRT_2 = inv(SQRT_2);\n\n/**\n * The natural logarithm of 2,\n * \\f$ \\log 2 \\f$.\n */\nconst double LOG_2 = log(2.0);\n\n/**\n * The natural logarithm of 10,\n * \\f$ \\log 10 \\f$.\n */\nconst double LOG_10 = log(10.0);\n\n/**\n * Positive infinity.\n */\nconst double INFTY = std::numeric_limits<double>::infinity();\n\n/**\n * Negative infinity.\n */\nconst double NEGATIVE_INFTY = -INFTY;\n\n/**\n * (Quiet) not-a-number value.\n */\nconst double NOT_A_NUMBER = std::numeric_limits<double>::quiet_NaN();\n\n/**\n * Smallest positive value.\n */\nconst double EPSILON = std::numeric_limits<double>::epsilon();\n\n/**\n * Largest negative value (i.e., smallest absolute value).\n */\nconst double NEGATIVE_EPSILON = -EPSILON;\n\n/**\n * Largest rate parameter allowed in Poisson RNG\n */\nconst double POISSON_MAX_RATE = pow(2.0, 30);\n\n/**\n * Return the value of pi.\n *\n * @return Pi.\n */\ninline double pi() { return boost::math::constants::pi<double>(); }\n\n/**\n * Return the base of the natural logarithm.\n *\n * @return Base of natural logarithm.\n */\ninline double e() { return E; }\n\n/**\n * Return the square root of two.\n *\n * @return Square root of two.\n */\ninline double sqrt2() { return SQRT_2; }\n\n/**\n * Return natural logarithm of ten.\n *\n * @return Natural logarithm of ten.\n */\ninline double log10() { return LOG_10; }\n\n/**\n * Return positive infinity.\n *\n * @return Positive infinity.\n */\ninline double positive_infinity() { return INFTY; }\n\n/**\n * Return negative infinity.\n *\n * @return Negative infinity.\n */\ninline double negative_infinity() { return NEGATIVE_INFTY; }\n\n/**\n * Return (quiet) not-a-number.\n *\n * @return Quiet not-a-number.\n */\ninline double not_a_number() { return NOT_A_NUMBER; }\n\n/**\n * Returns the difference between 1.0 and the next value\n * representable.\n *\n * @return Minimum positive number.\n */\ninline double machine_precision() { return EPSILON; }\n\nconst double SQRT_PI = sqrt(pi());\n\nconst double SQRT_2_TIMES_SQRT_PI = SQRT_2 * SQRT_PI;\n\nconst double TWO_OVER_SQRT_PI = 2.0 / SQRT_PI;\n\nconst double NEG_TWO_OVER_SQRT_PI = -TWO_OVER_SQRT_PI;\n\nconst double SQRT_TWO_PI = sqrt(2.0 * pi());\n\nconst double INV_SQRT_TWO_PI = inv(SQRT_TWO_PI);\n\nconst double LOG_PI = log(pi());\n\nconst double LOG_PI_OVER_FOUR = LOG_PI / 4.0;\n\nconst double LOG_SQRT_PI = log(SQRT_PI);\n\nconst double LOG_ZERO = log(0.0);\n\nconst double LOG_HALF = log(0.5);\n\nconst double NEG_LOG_TWO = -LOG_2;\n\nconst double NEG_LOG_SQRT_TWO_PI = -log(SQRT_TWO_PI);\n\nconst double NEG_LOG_PI = -LOG_PI;\n\nconst double NEG_LOG_SQRT_PI = -LOG_SQRT_PI;\n\nconst double NEG_LOG_TWO_OVER_TWO = -LOG_2 / 2.0;\n\nconst double LOG_TWO_PI = LOG_2 + LOG_PI;\n\nconst double NEG_LOG_TWO_PI = -LOG_TWO_PI;\n\nconst double LOG_EPSILON = log(EPSILON);\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "c71358e4cb7c56e9937b71adad8ef7b7df2eb35f", "size": 3349, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/constants.hpp", "max_stars_repo_name": "PhilClemson/math", "max_stars_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T14:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T14:57:41.000Z", "max_issues_repo_path": "stan/math/prim/scal/fun/constants.hpp", "max_issues_repo_name": "Capri2014/math", "max_issues_repo_head_hexsha": "d4042bdf8623bba5a1633b557227325a324e32e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-23T19:58:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T12:03:41.000Z", "max_forks_repo_path": "stan/math/prim/scal/fun/constants.hpp", "max_forks_repo_name": "riddell-stan/math", "max_forks_repo_head_hexsha": "d84ee0d991400d6cf4b08a07a4e8d86e0651baea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3583815029, "max_line_length": 69, "alphanum_fraction": 0.6867721708, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5799591895625354}}
{"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": "\n#include <Eigen/Core>\n#include <aslam/common/pose-types.h>\n\n#include \"maplab-common/interpolation-helpers.h\"\n#include \"maplab-common/test/testing-entrypoint.h\"\n\nnamespace common {\n\nTEST(MaplabCommon, TestEigenInterpolation) {\n  Eigen::Vector3d vector_A;\n  vector_A << 1, 2, 3;\n  constexpr double kTimeA = 100.0;\n\n  Eigen::Vector3d vector_B;\n  vector_B << 4, 5, 6;\n  constexpr double kTimeB = 200.0;\n\n  const double interpolation_time = 150.0;\n\n  Eigen::Vector3d interpolated_vector;\n  linearInterpolation(\n      kTimeA, vector_A, kTimeB, vector_B, interpolation_time,\n      &interpolated_vector);\n\n  Eigen::Vector3d interpolated_vector_ground_truth;\n  interpolated_vector_ground_truth << 2.5, 3.5, 4.5;\n\n  EXPECT_EQ(interpolated_vector_ground_truth, interpolated_vector);\n\n  // Test boundaries.\n  linearInterpolation(\n      kTimeA, vector_A, kTimeB, vector_B, kTimeA, &interpolated_vector);\n  EXPECT_EQ(vector_A, interpolated_vector);\n  linearInterpolation(\n      kTimeA, vector_A, kTimeB, vector_B, kTimeB, &interpolated_vector);\n  EXPECT_EQ(vector_B, interpolated_vector);\n}\n\nTEST(MaplabCommon, TestGenericInterpolation) {\n  constexpr char kCharA = ' ';\n  constexpr int kTimeA = 32;\n\n  constexpr char kCharB = '~';\n  constexpr int kTimeB = 126;\n\n  constexpr int kInterpolationTime = 58;\n\n  char interpolated_char;\n  linearInterpolation(\n      kTimeA, kCharA, kTimeB, kCharB, kInterpolationTime, &interpolated_char);\n\n  constexpr char kInterpolatedCharGroundTruth = ':';\n  EXPECT_EQ(kInterpolatedCharGroundTruth, interpolated_char);\n\n  // Test boundaries.\n  linearInterpolation(\n      kTimeA, kCharA, kTimeB, kCharB, kTimeA, &interpolated_char);\n  EXPECT_EQ(kCharA, interpolated_char);\n  linearInterpolation(\n      kTimeA, kCharA, kTimeB, kCharB, kTimeB, &interpolated_char);\n  EXPECT_EQ(kCharB, interpolated_char);\n}\n\nTEST(MaplabCommon, TestRotationInterpolation) {\n  const double kSqrt2DividedBy2 = std::sqrt(2) / 2.0;\n  aslam::Quaternion quat_A(kSqrt2DividedBy2, 0, kSqrt2DividedBy2, 0);\n  quat_A.normalize();\n\n  constexpr double kTimeA = 100.0;\n\n  aslam::Quaternion quat_B(-kSqrt2DividedBy2, 0, kSqrt2DividedBy2, 0);\n  quat_B.normalize();\n\n  constexpr double kTimeB = 200.0;\n\n  constexpr double kInterpolationTime = 150.0;\n\n  aslam::Quaternion interpolated_quat;\n  interpolateRotation(\n      kTimeA, quat_A, kTimeB, quat_B, kInterpolationTime, &interpolated_quat);\n\n  aslam::Quaternion interpolated_quat_ground_truth(0.0, 0.0, 1.0, 0.0);\n  interpolated_quat_ground_truth.normalize();\n\n  constexpr double kTolerance = 1e-8;\n  EXPECT_NEAR(\n      interpolated_quat_ground_truth.x(), interpolated_quat.x(), kTolerance);\n  EXPECT_NEAR(\n      interpolated_quat_ground_truth.y(), interpolated_quat.y(), kTolerance);\n  EXPECT_NEAR(\n      interpolated_quat_ground_truth.z(), interpolated_quat.z(), kTolerance);\n  EXPECT_NEAR(\n      interpolated_quat_ground_truth.w(), interpolated_quat.w(), kTolerance);\n\n  // Test boundaries.\n  interpolateRotation(\n      kTimeA, quat_A, kTimeB, quat_B, kTimeA, &interpolated_quat);\n  EXPECT_NEAR(quat_A.x(), interpolated_quat.x(), kTolerance);\n  EXPECT_NEAR(quat_A.y(), interpolated_quat.y(), kTolerance);\n  EXPECT_NEAR(quat_A.z(), interpolated_quat.z(), kTolerance);\n  EXPECT_NEAR(quat_A.w(), interpolated_quat.w(), kTolerance);\n  interpolateRotation(\n      kTimeA, quat_A, kTimeB, quat_B, kTimeB, &interpolated_quat);\n  EXPECT_NEAR(quat_B.x(), interpolated_quat.x(), kTolerance);\n  EXPECT_NEAR(quat_B.y(), interpolated_quat.y(), kTolerance);\n  EXPECT_NEAR(quat_B.z(), interpolated_quat.z(), kTolerance);\n  EXPECT_NEAR(quat_B.w(), interpolated_quat.w(), kTolerance);\n}\n\n}  // namespace common\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "1513aa149340b869392d25e473a3dda6517f7dce", "size": 3654, "ext": "cc", "lang": "C++", "max_stars_repo_path": "common/maplab-common/test/test-interpolation-helpers.cc", "max_stars_repo_name": "ethz-asl/maplab_summer", "max_stars_repo_head_hexsha": "7d57dabcdc3feffd8e9409686f7565bb77801f08", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-09-16T02:11:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-20T22:49:32.000Z", "max_issues_repo_path": "common/maplab-common/test/test-interpolation-helpers.cc", "max_issues_repo_name": "ethz-asl/maplab_summer", "max_issues_repo_head_hexsha": "7d57dabcdc3feffd8e9409686f7565bb77801f08", "max_issues_repo_licenses": ["Apache-2.0"], "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/maplab-common/test/test-interpolation-helpers.cc", "max_forks_repo_name": "ethz-asl/maplab_summer", "max_forks_repo_head_hexsha": "7d57dabcdc3feffd8e9409686f7565bb77801f08", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-28T14:11:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T08:30:50.000Z", "avg_line_length": 32.0526315789, "max_line_length": 78, "alphanum_fraction": 0.749589491, "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5799591832942729}}
{"text": "// Copyright (c) 2018-2019 FRC Team 3512. All Rights Reserved.\n\n#pragma once\n\n#include <grpl/pf.h>\n\n#include <array>\n#include <tuple>\n\n#include <Eigen/Core>\n#include <frc/Timer.h>\n#include <frc/controller/StateSpaceLoop.h>\n#include <units.h>\n\n#include \"Constants.hpp\"\n#include \"control/DrivetrainCoeffs.hpp\"\n#include \"control/Pathfinder.hpp\"\n#include \"control/Pose.hpp\"\n#include \"control/TrajectoryPoint.hpp\"\n#include \"control/TrapezoidalMotionProfile.hpp\"\n\nclass DrivetrainController {\npublic:\n    // State tolerances in meters and meters/sec respectively.\n    static constexpr double kPositionTolerance = 0.05;\n    static constexpr double kVelocityTolerance = 2.0;\n\n    DrivetrainController();\n\n    DrivetrainController(const DrivetrainController&) = delete;\n    DrivetrainController& operator=(const DrivetrainController&) = delete;\n\n    void Enable();\n    void Disable();\n\n    /**\n     * Sets goal pose of drivetrain controller.\n     *\n     * @param pose The goal pose.\n     */\n    void SetGoal(const Pose& pose);\n\n    /**\n     * Sets goal pose of drivetrain controller.\n     *\n     * @param pose The goal pose.\n     */\n    void SetGoal(Pose&& pose);\n\n    /**\n     * Returns whether the drivetrain controller is at the goal pose.\n     */\n    bool AtGoal() const;\n\n    /**\n     * Sets the current encoder measurements.\n     *\n     * @param leftPosition  Velocity of left side in meters.\n     * @param rightPosition Velocity of right side in meters.\n     * @param heading       Angle of the robot.\n     */\n    void SetMeasuredStates(double leftVelocity, double rightVelocity,\n                           double heading);\n\n    /**\n     * Returns the control loop calculated voltage for the left side.\n     */\n    double ControllerLeftVoltage() const;\n\n    /**\n     * Returns the control loop calculated voltage for the left side.\n     */\n    double ControllerRightVoltage() const;\n\n    /**\n     * Returns the estimated left velocity.\n     */\n    double EstimatedLeftVelocity() const;\n\n    /**\n     * Returns the estimated right velocity.\n     */\n    double EstimatedRightVelocity() const;\n\n    /**\n     * Returns the error between the left velocity reference and the left\n     * velocity estimate.\n     */\n    double LeftVelocityError() const;\n\n    /**\n     * Returns the error between the right velocity reference and the right\n     * velocity estimate.\n     */\n    double RightVelocityError() const;\n\n    TrajectoryPoint EstimatedPose() const;\n\n    TrajectoryPoint GoalPose() const;\n\n    double LeftVelocityReference();\n\n    double RightVelocityReference();\n\n    /**\n     * Executes the control loop for a cycle.\n     */\n    void Update();\n\n    /**\n     * Resets any internal state.\n     */\n    void Reset();\n\nprivate:\n    // The current sensor measurements.\n    Eigen::Matrix<double, 2, 1> m_Y;\n    double m_headingMeasurement;\n\n    // The control loop.\n    frc::StateSpaceLoop<2, 2, 2> m_loop{MakeDrivetrainLoop()};\n\n    // The motion profiles.\n    TrapezoidalMotionProfile::Constraints positionConstraints{kRobotMaxV,\n                                                              kRobotMaxA};\n    TrapezoidalMotionProfile m_positionProfile{positionConstraints,\n                                               {0_m, 0_mps}};\n    TrapezoidalMotionProfile::Constraints angleConstraints{\n        kRobotMaxRotateRate, kRobotMaxRotateAccel};\n    TrapezoidalMotionProfile m_angleProfile{angleConstraints, {0_m, 0_mps}};\n\n    Pathfinder m_pathfinder;\n\n    // TrajectoryPoints that store x, y, theta, v, and omega (w) for usage\n    TrajectoryPoint m_goal;\n    TrajectoryPoint m_estimatedTrajectory;\n\n    bool m_atReferences = false;\n\n    /**\n     * Sets the references\n     *\n     * @param leftVelocity Velocity of the left side in meters per second.\n     * @param rightVelocity Velocity of the right side in meters per second.\n     */\n    void SetReferences(double leftVelocity, double rightVelocity);\n\n    /**\n     * Returns sinc(x) = std::sin(x) / x.\n     *\n     * @param x\n     */\n    static double Sinc(double x);\n\n    /**\n     * Returns a velocity and angular velocity corrected to account for failures\n     * to stay on course.\n     *\n     * @param pose_desired  Desired x, y, and theta values.\n     * @param v_desired     Desired velocity.\n     * @param omega_desired Desired angular velocity.\n     * @param pose          Current x, y, and theta values.\n     * @param b             Tuning parameter; makes convergence more aggressive.\n     * @param zeta          Tuning parameter in range (0,1); provides damping.\n     */\n    std::tuple<double, double> Ramsete(TrajectoryPoint trajectory_desired,\n                                       TrajectoryPoint trajectory, double b,\n                                       double zeta);\n\n    /**\n     * Returns left and right velocities from a central velocity and turning\n     * rate\n     *\n     * @param v     Center velocity\n     * @param omega Center turning rate\n     * @param d     Trackwidth\n     */\n    std::tuple<double, double> GetDiffVelocities(double v, double omega,\n                                                 double d);\n};\n", "meta": {"hexsha": "2938729044f3ecfe858a9728ba717e21a8c589cc", "size": 5086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/main/include/control/DrivetrainController.hpp", "max_stars_repo_name": "Team3512/Robot-2018.1", "max_stars_repo_head_hexsha": "67486bad03d3bb49cea2b36d764bf8b4bf131df9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-19T07:54:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-19T07:54:41.000Z", "max_issues_repo_path": "src/main/include/control/DrivetrainController.hpp", "max_issues_repo_name": "Team3512/Robot-2018.1", "max_issues_repo_head_hexsha": "67486bad03d3bb49cea2b36d764bf8b4bf131df9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main/include/control/DrivetrainController.hpp", "max_forks_repo_name": "Team3512/Robot-2018.1", "max_forks_repo_head_hexsha": "67486bad03d3bb49cea2b36d764bf8b4bf131df9", "max_forks_repo_licenses": ["BSD-3-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.0994475138, "max_line_length": 80, "alphanum_fraction": 0.6344868266, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5799591790523432}}
{"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": "// Test ../include/Spectra/LinAlg/UpperHessenbergQR.h and\n//      ../include/Spectra/LinAlg/DoubleShiftQR.h\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include <Spectra/LinAlg/UpperHessenbergQR.h>\n#include <Spectra/LinAlg/DoubleShiftQR.h>\n\nusing namespace Spectra;\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\ntypedef Eigen::Map<Eigen::MatrixXd> MapMat;\n\ntemplate <typename Solver, typename MatrixType>\nvoid run_test(MatrixType &H, double shift)\n{\n    Solver decomp(H, shift);\n    const int n = H.rows();\n    const double tol = 1e-12;\n    MatrixXd Hs = H - shift * MatrixXd::Identity(n, n);\n\n    // Obtain Q matrix\n    MatrixXd I = MatrixXd::Identity(n, n);\n    MatrixXd Q = I;\n    decomp.apply_QY(Q);\n\n    // Test orthogonality\n    MatrixXd QtQ = Q.transpose() * Q;\n    INFO(\"||Q'Q - I||_inf = \" << (QtQ - I).cwiseAbs().maxCoeff());\n    REQUIRE((QtQ - I).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    MatrixXd QQt = Q * Q.transpose();\n    INFO(\"||QQ' - I||_inf = \" << (QQt - I).cwiseAbs().maxCoeff());\n    REQUIRE((QQt - I).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    // Obtain R matrix and test whether it is upper triangular\n    MatrixXd R = decomp.matrix_R();\n    MatrixXd Rlower = R.triangularView<Eigen::StrictlyLower>();\n    INFO(\"Whether R is upper triangular, error = \" << Rlower.cwiseAbs().maxCoeff());\n    REQUIRE(Rlower.cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    // Compare Hs = H - s * I and QR\n    INFO(\"||Hs - QR||_inf = \" << (Hs - Q * R).cwiseAbs().maxCoeff());\n    REQUIRE((Hs - Q * R).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    // Obtain Q'HQ\n    MatrixXd QtHQ_true = Q.transpose() * H * Q;\n    MatrixXd QtHQ;\n    decomp.matrix_QtHQ(QtHQ);\n    INFO(\"max error of Q'HQ = \" << (QtHQ - QtHQ_true).cwiseAbs().maxCoeff());\n    REQUIRE((QtHQ - QtHQ_true).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    // Test \"apply\" functions\n    MatrixXd Y = MatrixXd::Random(n, n);\n\n    MatrixXd QY = Y;\n    decomp.apply_QY(QY);\n    INFO(\"max error of QY = \" << (QY - Q * Y).cwiseAbs().maxCoeff());\n    REQUIRE((QY - Q * Y).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    MatrixXd YQ = Y;\n    decomp.apply_YQ(YQ);\n    INFO(\"max error of YQ = \" << (YQ - Y * Q).cwiseAbs().maxCoeff());\n    REQUIRE((YQ - Y * Q).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    MatrixXd QtY = Y;\n    decomp.apply_QtY(QtY);\n    INFO(\"max error of Q'Y = \" << (QtY - Q.transpose() * Y).cwiseAbs().maxCoeff());\n    REQUIRE((QtY - Q.transpose() * Y).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    MatrixXd YQt = Y;\n    decomp.apply_YQt(YQt);\n    INFO(\"max error of YQ' = \" << (YQt - Y * Q.transpose()).cwiseAbs().maxCoeff());\n    REQUIRE((YQt - Y * Q.transpose()).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    // Test \"apply\" functions for vectors\n    VectorXd y = VectorXd::Random(n);\n\n    VectorXd Qy = y;\n    decomp.apply_QY(Qy);\n    INFO(\"max error of Qy = \" << (Qy - Q * y).cwiseAbs().maxCoeff());\n    REQUIRE((Qy - Q * y).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    VectorXd Qty = y;\n    decomp.apply_QtY(Qty);\n    INFO(\"max error of Q'y = \" << (Qty - Q.transpose() * y).cwiseAbs().maxCoeff());\n    REQUIRE((Qty - Q.transpose() * y).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n}\n\nTEST_CASE(\"QR of upper Hessenberg matrix\", \"[QR]\")\n{\n    std::srand(123);\n    int n = 100;\n    MatrixXd m = MatrixXd::Random(n, n);\n    m.array() -= 0.5;\n    MatrixXd H = m.triangularView<Eigen::Upper>();\n    H.diagonal(-1) = m.diagonal(-1);\n\n    run_test<UpperHessenbergQR<double> >(H, 1.2345);\n\n    MapMat Hmap(H.data(), H.rows(), H.cols());\n    run_test<UpperHessenbergQR<double> >(Hmap, 0.6789);\n}\n\nTEST_CASE(\"QR of Tridiagonal matrix\", \"[QR]\")\n{\n    std::srand(123);\n    int n = 100;\n    MatrixXd m = MatrixXd::Random(n, n);\n    m.array() -= 0.5;\n    MatrixXd H = MatrixXd::Zero(n, n);\n    H.diagonal() = m.diagonal();\n    H.diagonal(-1) = m.diagonal(-1);\n    H.diagonal(1) = m.diagonal(-1);\n\n    run_test<TridiagQR<double> >(H, 1.2345);\n\n    MapMat Hmap(H.data(), H.rows(), H.cols());\n    run_test<TridiagQR<double> >(Hmap, 0.6789);\n}\n\nTEST_CASE(\"QR decomposition with double shifts\", \"[QR]\")\n{\n    std::srand(123);\n    const int n = 100;\n    const double tol = 1e-12;\n\n    MatrixXd m = MatrixXd::Random(n, n);\n    m.array() -= 0.5;\n    MatrixXd H = m.triangularView<Eigen::Upper>();\n    H.diagonal(-1) = m.diagonal(-1);\n    H(1, 0) = 0;  // Test for the case when sub-diagonal element is zero\n\n    const double s = 2, t = 3;\n\n    MatrixXd M = H * H - s * H + t * MatrixXd::Identity(n, n);\n    Eigen::HouseholderQR<MatrixXd> qr(M);\n    MatrixXd Q0 = qr.householderQ();\n\n    DoubleShiftQR<double> decomp(H, s, t);\n    MatrixXd Q = MatrixXd::Identity(n, n);\n    decomp.apply_YQ(Q);\n\n    // Equal up to signs\n    INFO(\"max error of Q = \" << (Q.cwiseAbs() - Q0.cwiseAbs()).cwiseAbs().maxCoeff());\n    REQUIRE((Q.cwiseAbs() - Q0.cwiseAbs()).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    // Test Q'HQ\n    MatrixXd QtHQ;\n    decomp.matrix_QtHQ(QtHQ);\n    INFO(\"max error of Q'HQ = \" << (QtHQ - Q.transpose() * H * Q).cwiseAbs().maxCoeff());\n    REQUIRE((QtHQ - Q.transpose() * H * Q).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    // Test apply functions\n    VectorXd y = VectorXd::Random(n);\n    MatrixXd Y = MatrixXd::Random(n / 2, n);\n\n    VectorXd Qty = y;\n    decomp.apply_QtY(Qty);\n    INFO(\"max error of Q'y = \" << (Qty - Q.transpose() * y).cwiseAbs().maxCoeff());\n    REQUIRE((Qty - Q.transpose() * y).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n\n    MatrixXd YQ = Y;\n    decomp.apply_YQ(YQ);\n    INFO(\"max error of YQ = \" << (YQ - Y * Q).cwiseAbs().maxCoeff());\n    REQUIRE((YQ - Y * Q).cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n}\n", "meta": {"hexsha": "112e6a1739fe4e1e5d732768f78189537301a9b4", "size": 5793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/test/QR.cpp", "max_stars_repo_name": "mushroom-x/Misc3D", "max_stars_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2022-02-09T11:56:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:45:04.000Z", "max_issues_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/test/QR.cpp", "max_issues_repo_name": "mushroom-x/Misc3D", "max_issues_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2022-02-26T08:58:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T11:19:05.000Z", "max_forks_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/test/QR.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": 33.8771929825, "max_line_length": 93, "alphanum_fraction": 0.6012428793, "num_tokens": 1907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.5799430955750204}}
{"text": "#ifndef NEURAL_NET_HPP\n#define NEURAL_NET_HPP\n\n#include <Eigen/Dense>\n#include <random>\n#include <vector>\n\n// NN Utilities\nnamespace NN {\n    // RNGs\n    extern std::mt19937 gen;\n    extern std::normal_distribution<double> randn;\n    extern std::uniform_real_distribution<double> rand;\n\n    // Random initializers\n    Eigen::VectorXd getBias(int);\n    Eigen::MatrixXd getWeight(int, int);\n}; // namespace NN\n\n// Activation functions\nenum ActFunc {\n    SIGMOID,\n    RELU\n};\n\n/*\n * Feedforward Neural Network\n */\nclass NeuralNet {\nprivate:\n    std::vector<int> sizes;        // layer sizes\n    int layers;                    // number of layers\n    std::vector<ActFunc> actFuncs; // activation functions for each layer\n\n    void weightInitializer();                                    // random initializer\n    Eigen::VectorXd activate(const Eigen::VectorXd &, int = -1); // apply activation functions\n\npublic:\n    std::vector<Eigen::VectorXd> biases;  // NN biases\n    std::vector<Eigen::MatrixXd> weights; // NN weights\n\n    NeuralNet();\n    NeuralNet(const std::vector<int> &);\n    NeuralNet(const std::vector<int> &, const std::vector<Eigen::MatrixXd> &w, const std::vector<Eigen::VectorXd> &b);\n    Eigen::VectorXd feedforward(Eigen::VectorXd); // get feedforward outputs\n    void saveToFile(int fileOffset = 0);          // save network to file\n    void loadFromFile(int fileOffset = 0);        // load network from file\n};\n\n#endif", "meta": {"hexsha": "62ee9ce8cd4045269e017c4146faa3886f5e197c", "size": 1435, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/NN/NeuralNet.hpp", "max_stars_repo_name": "PragunSaini/snakes", "max_stars_repo_head_hexsha": "19b62fecca9c6854c712503e84bc854f8e2d1562", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T08:26:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T20:19:19.000Z", "max_issues_repo_path": "include/NN/NeuralNet.hpp", "max_issues_repo_name": "PragunSaini/snakes", "max_issues_repo_head_hexsha": "19b62fecca9c6854c712503e84bc854f8e2d1562", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/NN/NeuralNet.hpp", "max_forks_repo_name": "PragunSaini/snakes", "max_forks_repo_head_hexsha": "19b62fecca9c6854c712503e84bc854f8e2d1562", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7, "max_line_length": 118, "alphanum_fraction": 0.6557491289, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5799430887253196}}
{"text": "#include <cassert> // assert\n\n#include <boost/random/mersenne_twister.hpp> // boost::random::mt19937\n#include <boost/assign/list_of.hpp> // boost::assign::list_of()\n\n#include <mutation_accumulation/random/multinomial_distribution.h> // random::multinomial_distribution\n#include <mutation_accumulation/probability/cdf.h> // probability::CDF_discrete\n\n#include \"unit_test.h\"\n\ntypedef int int_type; // probability::CDF_discrete complains at compile-time if int_type is not int (for example long long int)\ntypedef mutation_accumulation::random::multinomial_distribution<int_type, double> mn_type;\n\n/*************************************************************************/\n\n\nvoid unit_test::unit_test_2Dmultinomial() {\n\n    std::cout << \"generate 2D multinomial CDF...\" << std::endl;\n\n    /* PRNG engine */\n    boost::random::mt19937 urng;\n\n    /* parameters of multinomial_distribution */\n    const int_type NN = 10;\n    const double pp = 0.75;\n    const std::vector<double> probabilities = boost::assign::list_of(pp)(1-pp);\n    std::ofstream fout(\"mn_2D_parameters.in\");\n    fout << \"N = \" << NN << std::endl;\n    fout << \"p = \" << pp << std::endl;\n\n    /* create 2D multinomial_distribution object */\n    mn_type mn_rnd(NN, probabilities);\n\n    /* number of samples to draw from distribution */\n    const int number_trials = 1e3;\n\n    /* sample space */\n    std::vector<int_type> sample_space(NN + 1, -1.0);\n    for (int_type ii = 0; ii < sample_space.size(); ii++) {\n        sample_space.at(ii) = ii;\n    }\n\n    /* create CDF object */\n    probability::CDF_discrete mn_cdf(sample_space, \"mn_2D_cdf.dat\");\n\n    /* repeatedly add samples to the CDF */\n    for (int ii = 0; ii < number_trials; ii++) \n        mn_cdf.update(mn_rnd(urng).at(0));\n\n    std::cout << \"... CDF generated\" << std::endl;\n    \n}\n\n\n/*************************************************************************/\n\n\nvoid unit_test::unit_test__sum_random_vector_elements() {\n\n    std::cout << \"testing sum of elements in random vector...\" << std::endl;\n\n    /* PRNG engine */\n    boost::random::mt19937 urng;\n\n    /* parameters of multinomial_distribution */\n    const int_type NN = 10;\n    const std::vector<double> probabilities = boost::assign::list_of(0.2)(0.2)(0.2)(0.4);\n\n    /* create multinomial_distribution object */\n    mn_type mn_rnd(NN, probabilities);\n    std::cout << \"generated \" << probabilities.size() << \"D multinomial distribution\" << std::endl;\n\n    /* number of samples to draw from distribution */\n    const int number_trials = 1e2;\n\n    /* sample multinomial distribution */\n    for (int ii = 0; ii < number_trials; ii++) {\n\n        std::vector<int_type> random_vector = mn_rnd(urng);\n\n        int_type sum = static_cast<int_type>(0);\n        for (int ii = 0; ii < random_vector.size(); ii++) {\n            sum += random_vector.at(ii);\n        }\n\n        assert(sum == NN);\n\n    }\n\n    std::cout << \"... finished testing sum of elements in random vector\" << std::endl;\n\n}\n\n/*************************************************************************/\n\n\nvoid unit_test::unit_test__3Dmultinomial() {\n\n    std::cout << \"sampling from 3D multinomial ... \" << std::endl;\n\n    /* PRNG engine */\n    boost::random::mt19937 urng;\n\n    /* parameters of multinomial_distribution */\n    const int_type NN = 20;\n    const std::vector<double> probabilities = boost::assign::list_of(0.8)(0.1)(0.1);\n    std::ofstream fin(\"mn_3D_parameters.in\");\n    fin << \"N = \" << NN << std::endl;\n    for (int ii = 0; ii < probabilities.size(); ii++)\n        fin << \"p\" << ii << \" = \" << probabilities.at(ii) << std::endl;\n\n    /* create multinomial_distribution object */\n    mn_type mn_rnd(NN, probabilities);\n    std::cout << \"generated \" << probabilities.size() << \"D multinomial distribution\" << std::endl;\n\n    /* number of samples to draw from distribution */\n    const int number_trials = 1e5;\n\n    /* open file to write samples to */\n    std::ofstream fout(\"mn_3D_samples.dat\");\n    \n    /* sample multinomial distribution */\n    for (int ii = 0; ii < number_trials; ii++) {\n\n        std::vector<int_type> random_vector = mn_rnd(urng);\n\n        for (int ii = 0; ii < random_vector.size(); ii++) {\n            fout << random_vector.at(ii) << \" \";\n        }\n        fout << std::endl;\n\n    }\n\n    std::cout << \"... finished sampling from 3D multinomial\" << std::endl;\n\n}\n\n/*************************************************************************/\n\n\nvoid unit_test::unit_test__4Dmultinomial() {\n\n    std::cout << \"sampling from 4D multinomial ... \" << std::endl;\n\n    /* PRNG engine */\n    boost::random::mt19937 urng;\n\n    /* parameters of multinomial_distribution */\n    const int_type NN = 10;\n    const std::vector<double> probabilities = boost::assign::list_of(0.6)(0.1)(0.1)(0.2);\n    std::ofstream fin(\"mn_4D_parameters.in\");\n    fin << \"N = \" << NN << std::endl;\n    for (int ii = 0; ii < probabilities.size(); ii++)\n        fin << \"p\" << ii << \" = \" << probabilities.at(ii) << std::endl;\n\n    /* create multinomial_distribution object */\n    mn_type mn_rnd(NN, probabilities);\n    std::cout << \"generated \" << probabilities.size() << \"D multinomial distribution\" << std::endl;\n\n    /* number of samples to draw from distribution */\n    const int number_trials = 1e5;\n\n    /* open file to write samples to */\n    std::ofstream fout(\"mn_4D_samples.dat\");\n\n    /* sample multinomial distribution */\n    for (int ii = 0; ii < number_trials; ii++) {\n\n        std::vector<int_type> random_vector = mn_rnd(urng);\n\n        for (int ii = 0; ii < random_vector.size(); ii++) {\n            fout << random_vector.at(ii) << \" \";\n        }\n        fout << std::endl;\n\n    }\n\n    std::cout << \"... finished sampling from 4D multinomial\" << std::endl;\n\n}\n\n\n/*************************************************************************/\n\n\nvoid unit_test::unit_test__3Dmultinomial_edgeCase() {\n\n    std::cout << \"sampling from 3D multinomial (edge case)... \" << std::endl;\n\n    /* PRNG engine */\n    boost::random::mt19937 urng;\n\n    /* parameters of multinomial_distribution */\n    const int_type NN = 5;\n    const std::vector<double> probabilities = boost::assign::list_of(0.0)(0.0)(1.0);\n    std::ofstream fin(\"mn_3D_edgeCase_parameters.in\");\n    fin << \"N = \" << NN << std::endl;\n    for (int ii = 0; ii < probabilities.size(); ii++)\n        fin << \"p\" << ii << \" = \" << probabilities.at(ii) << std::endl;\n\n    /* create multinomial_distribution object */\n    mn_type mn_rnd(NN, probabilities);\n    std::cout << \"generated \" << probabilities.size() << \"D multinomial distribution\" << std::endl;\n\n    /* number of samples to draw from distribution */\n    const int number_trials = 1e5;\n\n    /* sample multinomial distribution */\n    for (int ii = 0; ii < number_trials; ii++) {\n\n        std::vector<int_type> random_vector = mn_rnd(urng);\n\n        assert(random_vector.at(0) == 0);\n        assert(random_vector.at(1) == 0);\n        assert(random_vector.at(2) == NN);\n\n//        for (int ii = 0; ii < random_vector.size(); ii++) {\n//            std::cout << random_vector.at(ii) << \" \";\n//        }\n//        std::cout << std::endl;\n\n    }\n\n    std::cout << \"... finished sampling from 3D multinomial (edge case)\" << std::endl;\n\n}\n\n\n\n/*************************************************************************/\n\nvoid unit_test::unit_test__3Dmultinomial_zeroN() {\n\n    std::cout << \"sampling from 3D multinomial (N = 0)... \" << std::endl;\n\n    /* PRNG engine */\n    boost::random::mt19937 urng;\n\n    /* parameters of multinomial_distribution */\n    const int_type NN = 0;\n    const std::vector<double> probabilities = boost::assign::list_of(0.1)(0.1)(0.8);\n    std::ofstream fin(\"mn_3D_zeroN_parameters.in\");\n    fin << \"N = \" << NN << std::endl;\n    for (int ii = 0; ii < probabilities.size(); ii++)\n        fin << \"p\" << ii << \" = \" << probabilities.at(ii) << std::endl;\n\n    /* create multinomial_distribution object */\n    mn_type mn_rnd(NN, probabilities);\n    std::cout << \"generated \" << probabilities.size() << \"D multinomial distribution\" << std::endl;\n\n    /* number of samples to draw from distribution */\n    const int number_trials = 1e5;\n\n    /* sample multinomial distribution */\n    for (int ii = 0; ii < number_trials; ii++) {\n\n        std::vector<int_type> random_vector = mn_rnd(urng);\n\n        assert(random_vector.at(0) == 0);\n        assert(random_vector.at(1) == 0);\n        assert(random_vector.at(2) == 0);\n\n//        for (int ii = 0; ii < random_vector.size(); ii++) {\n//            std::cout << random_vector.at(ii) << \" \";\n//        }\n//        std::cout << std::endl;\n\n    }\n\n    std::cout << \"... finished sampling from 3D multinomial (N = 0)\" << std::endl;\n\n}\n\n\n\n", "meta": {"hexsha": "44048dbae013a39f775eab35123940bf6e91f300", "size": 8647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/multinomial/unit_test.cpp", "max_stars_repo_name": "petermchale/mutation_accumulation", "max_stars_repo_head_hexsha": "f4bd9182619bae1b2e8fa95700540ee398c2bdd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T10:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-09T10:02:52.000Z", "max_issues_repo_path": "unit_tests/multinomial/unit_test.cpp", "max_issues_repo_name": "petermchale/mutation_accumulation", "max_issues_repo_head_hexsha": "f4bd9182619bae1b2e8fa95700540ee398c2bdd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/multinomial/unit_test.cpp", "max_forks_repo_name": "petermchale/mutation_accumulation", "max_forks_repo_head_hexsha": "f4bd9182619bae1b2e8fa95700540ee398c2bdd6", "max_forks_repo_licenses": ["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.2166064982, "max_line_length": 127, "alphanum_fraction": 0.5796229906, "num_tokens": 2216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5799322185481361}}
{"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 <boost/test/unit_test.hpp>\n\n#include \"../include/calcutron.h\"\n\nusing namespace calcutron;\nusing namespace std;\n\n\nBOOST_AUTO_TEST_CASE(ReturnNumberTest)\n{\n\tBOOST_CHECK(calculate(\"1\") == 1);\n\tBOOST_CHECK(calculate(\"   1\") == 1);\n\tBOOST_CHECK(calculate(\"1   \") == 1);}\n\nBOOST_AUTO_TEST_CASE(SumTest)\n{\n\tBOOST_CHECK(calculate(\"1+1\") == 2);\n}\n\nBOOST_AUTO_TEST_CASE(LeadingMinusTest)\n{\n\tBOOST_CHECK(calculate(\"-1+1\") == 0);\n}\n\nBOOST_AUTO_TEST_CASE(SumWithSpacesTest)\n{\n\tBOOST_CHECK(calculate(\"1 + 1\") == 2);\n}\n\nBOOST_AUTO_TEST_CASE(SumFloatTest)\n{\n\tBOOST_CHECK(calculate(\"1.5 + 0,5\") == 2);\n}\n\nBOOST_AUTO_TEST_CASE(MinusTest)\n{\n\tBOOST_CHECK(calculate(\"3-1\") == 2);\n}\n\nBOOST_AUTO_TEST_CASE(MinusWithSpacesTest)\n{\n\tBOOST_CHECK(calculate(\"3 - 1\") == 2);\n}\n\nBOOST_AUTO_TEST_CASE(MultTest)\n{\n\tBOOST_CHECK(calculate(\"3*2\") == 6);\n}\n\nBOOST_AUTO_TEST_CASE(DivTest)\n{\n\tBOOST_CHECK(calculate(\"4/2\") == 2);\n}\n\nBOOST_AUTO_TEST_CASE(DivFloatTest)\n{\n\tBOOST_CHECK(calculate(\"3 / 1.5\") == 2);\n}\n\nBOOST_AUTO_TEST_CASE(ParenthesesSimpleTest)\n{\n\tBOOST_CHECK(calculate(\"(1+1)\") == 2);\n\tBOOST_CHECK(calculate(\"[1+1]\") == 2);\n}\n\nBOOST_AUTO_TEST_CASE(ParenthesesComplexTest)\n{\n\tBOOST_CHECK(calculate(\"-1*(4+2*(1-2))+3\") == 1);\n\tBOOST_CHECK(calculate(\"-1*(1+1)+3\") == 1);\n}\n\nBOOST_AUTO_TEST_CASE(MultipleOperatorsTest)\n{\n\tBOOST_CHECK(calculate(\"- - 1\") == 1);\n\tBOOST_CHECK(calculate(\"1 - - 1\") == 2);\n\tBOOST_CHECK(calculate(\"1 * - 1\") == -1);\t// \u0434\u0430, \u0442\u0430\u043a\u043e\u0435 \u0442\u0435\u043f\u0435\u0440\u044c \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043d\u043e\n\tBOOST_CHECK(calculate(\"1 / - 1 + 2\") == 1);\t// \u0434\u0430, \u0442\u0430\u043a\u043e\u0435 \u0442\u0435\u043f\u0435\u0440\u044c \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043d\u043e\n}\n\n// \u043f\u0440\u0438\u043c\u0435\u0440\u044b \u0432\u044b\u0440\u0430\u0436\u0435\u043d\u0438\u0439 \u0438\u0437 \u0442\u0435\u0445 \u0437\u0430\u0434\u0430\u043d\u0438\u044f\nBOOST_AUTO_TEST_CASE(FinalTest)\n{\n\tBOOST_CHECK(calculate(\"-1 + 5 - 3\") == 1);\n\tBOOST_CHECK(calculate(\"-10 + (8 * 2.5) - (3 / 1,5)\") == 8);\n\tBOOST_CHECK(calculate(\"1 + (2 * (2.5 + 2.5 + (3 - 2))) - (3 / 1.5)\") == 11);\n}\n", "meta": {"hexsha": "9c025d284c48986f0ff7162a09862aac1f81ca01", "size": 1785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/calcutron_test.cpp", "max_stars_repo_name": "deitry/LittleCalcutron", "max_stars_repo_head_hexsha": "6bda9a51c88d3d14fbbd9a161bc66188664fcc3c", "max_stars_repo_licenses": ["MIT"], "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/calcutron_test.cpp", "max_issues_repo_name": "deitry/LittleCalcutron", "max_issues_repo_head_hexsha": "6bda9a51c88d3d14fbbd9a161bc66188664fcc3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/calcutron_test.cpp", "max_forks_repo_name": "deitry/LittleCalcutron", "max_forks_repo_head_hexsha": "6bda9a51c88d3d14fbbd9a161bc66188664fcc3c", "max_forks_repo_licenses": ["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.5172413793, "max_line_length": 77, "alphanum_fraction": 0.6677871148, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645723, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5798069165257443}}
{"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": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <limits>\n\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/make_shared.hpp>\n\n#include <boost/math/distributions/lognormal.hpp>\n\n#include \"tudat/math/statistics/multiVariateGaussianProbabilityDistributions.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n// Test function for Gaussian cupola distribution (computation of pdf).\n// NOTE: This manner of testing the Gaussian cupola is not ideal, but no usable test data has been identified.\ndouble gaussianCopulaProbabilityDensity(\n        const Eigen::VectorXd& independentVariables , int dimension_ , Eigen::MatrixXd correlationMatrix_ )\n{\n    Eigen::MatrixXd inverseCorrelationMatrix_ = correlationMatrix_.inverse() ;\n    double determinant_ = correlationMatrix_.determinant( );\n\n    double probabilityDensity = 0.0 ;\n    Eigen::VectorXd y( dimension_ ) ;\n    boost::math::normal distribution( 0.0 , 1.0 );\n\n    for( int i = 0 ; i < dimension_; i++ )\n    {\n        y( i ) = boost::math::quantile( distribution , independentVariables( i ) ); // Inverse cdf\n    }\n\n    // Calculate probability density\n    Eigen::MatrixXd location = -0.5 *\n            ( y.transpose( )  * ( inverseCorrelationMatrix_ - Eigen::MatrixXd::Identity( dimension_ , dimension_ ) ) * y ) ;\n\n    probabilityDensity = ( ( 1.0 / ( std::sqrt( determinant_ ) ) ) * std::exp( location( 0, 0 ) ) ) ;\n    return probabilityDensity;\n}\n\n\n// Exact solution of 2D Gaussian distribution\n// Montgomery, D. C. & Runger, G. C. Applied statistics and Probability for engineers Wiley, 2014\ndouble computeBiGaussianPdf(\n        const double standardDeviationX, const double standardDeviationY, const double correlation,\n        const double meanX, const double meanY, const Eigen::VectorXd independentVariables )\n{\n    using tudat::mathematical_constants::PI;\n    using std::pow;\n    using std::exp;\n\n    return ( 1.0 / ( 2.0 * PI*standardDeviationX*standardDeviationY*sqrt( 1.0 - pow( correlation, 2.0 ) ) ) ) *\n            exp( ( -1.0 / ( 2.0 * ( 1.0 - pow( correlation, 2.0) ) ) ) * (\n                     ( pow( independentVariables( 0 ) - meanX, 2.0 ) ) /( pow( standardDeviationX, 2.0 ) )\n                     - ( 2.0 * correlation * ( independentVariables( 0 ) - meanX ) *\n                         ( independentVariables( 1 )- meanY ) ) / ( standardDeviationX * standardDeviationY )\n                     + ( pow( independentVariables( 1 ) - meanY, 2.0 ) ) / ( pow( standardDeviationY, 2.0 ) ) ) );\n}\n\n\nBOOST_AUTO_TEST_SUITE( test_probability_distributions )\n\n//! Test if Multi-dimensional Gaussian distribution class works correctly for 2 dimensions, using analytical solution for\n//! bigaussian distribution.\nBOOST_AUTO_TEST_CASE( testMultiDimensionalGaussianDistribution )\n{\n    using namespace tudat::statistics;\n\n    // Defined mean and covariance.\n    Eigen::VectorXd mean( 2 );\n    mean << 0.0 , 1.0;\n\n    Eigen::MatrixXd covariance( 2, 2 );\n    covariance << 3.0, -1.0, -1.0, 3.0;\n\n    // Create distribution\n    GaussianDistributionXd distribution( mean, covariance );\n\n    // Defined new mean and covariance.\n    Eigen::VectorXd mean2( 2 );\n    mean2 << -1.0 , 2.0;\n\n    Eigen::MatrixXd covariance2( 2, 2 );\n    covariance2 << 4.0, 1.5, 1.5, 4.0;\n\n    // Create second distribution\n    GaussianDistributionXd distribution2( mean2,covariance2 );\n\n    // Define test independent variables.\n    Eigen::VectorXd independentVariables( 2 );\n\n    // Test distributions for range of independent variables.\n    for( unsigned int i = 0; i < 81; i++ )\n    {\n        for( unsigned int j = 0; j < 81; j++ )\n        {\n            independentVariables( 0 ) = -4.0 + 0.1 * static_cast< double >( i );\n            independentVariables( 1 ) = -4.0 + 0.1 * static_cast< double >( j );\n\n            {\n                // Compute exact solution of pdf\n                double standardDeviationX = std::sqrt( covariance( 0, 0 ) );\n                double standardDeviationY = std::sqrt( covariance( 1, 1 ) );\n                double meanX = mean( 0 );\n                double meanY = mean( 1 );\n                double correlation = covariance( 0 , 1 ) / ( standardDeviationX * standardDeviationY );\n\n                double exactSolution = computeBiGaussianPdf(\n                            standardDeviationX, standardDeviationY, correlation, meanX, meanY, independentVariables );\n\n                // Test pdf value\n                BOOST_CHECK_SMALL( std::fabs( distribution.evaluatePdf( independentVariables) - exactSolution ),\n                                   std::numeric_limits< double >::epsilon( ) );\n            }\n\n            {\n                // Compute exact solution of pdf\n                double standardDeviationX = std::sqrt( covariance2( 0, 0 ) );\n                double standardDeviationY = std::sqrt( covariance2( 1, 1 ) );\n                double meanX = mean2( 0 );\n                double meanY = mean2( 1 );\n                double correlation = covariance2( 0 , 1 ) / ( standardDeviationX * standardDeviationY );\n\n                double exactSolution = computeBiGaussianPdf(\n                            standardDeviationX, standardDeviationY, correlation, meanX, meanY, independentVariables );\n\n                // Test pdf value\n                BOOST_CHECK_SMALL( std::fabs( distribution2.evaluatePdf( independentVariables ) - exactSolution ) ,\n                                   std::numeric_limits<double>::epsilon() ) ;\n            }\n        }\n    }\n}\n\n//! Test if Gaussian Copula distribution class works correctly.\nBOOST_AUTO_TEST_CASE( testGaussianCopula )\n{\n    using namespace tudat::statistics;\n    using tudat::mathematical_constants::PI;\n\n    // Define properties of distribution.\n    int dimension = 2 ;\n    Eigen::MatrixXd correlationMatrix( dimension , dimension ) ;\n    correlationMatrix << 1.0, 0.3, 0.3, 1.0 ;\n\n    // Create distribution\n    GaussianCopulaDistributionXd distribution( correlationMatrix );\n\n    Eigen::VectorXd independentVariables( 2 );\n    independentVariables << 0.5 , 0.3 ;\n\n    for( unsigned int i = 1; i < 40; i++ )\n    {\n        for( unsigned int j = 1; j < 40; j++ )\n        {\n            independentVariables( 0 ) = 0.025 * static_cast< double >( i );\n            independentVariables( 1 ) = 0.025 * static_cast< double >( j );\n\n            // Test Gaussian cupola at current independentVariables/\n            // NOTE: This manner of testing the Gaussian cupola (similar computation in source and test file) is not ideal,\n            // but no usable test data has been identified.\n            BOOST_CHECK_SMALL( std::fabs( gaussianCopulaProbabilityDensity(\n                                              independentVariables , dimension , correlationMatrix )\n                                          - distribution.evaluatePdf( independentVariables ) ), 1E-15 );\n\n        }\n    }\n\n    // Test out of bounds for distribution (pdf equals 0).\n    independentVariables << 1.1 , 0.5 ;\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluatePdf( independentVariables ) - 0.0 ) , 1E-15 );\n\n    independentVariables << 0.1 , -0.5 ;\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluatePdf( independentVariables ) - 0.0 ) , 1E-15 );\n\n    independentVariables << -0.1 , -0.5 ;\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluatePdf( independentVariables ) - 0.0 ) , 1E-15 );\n\n    independentVariables << 0.1 , 1.5 ;\n    BOOST_CHECK_SMALL( std::fabs( distribution.evaluatePdf( independentVariables ) - 0.0 ) , 1E-15 );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "b955930ad1e680e92805a3af213e122d23e17b7a", "size": 8001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/math/statistics/unitTestMultiVariateGaussianProbabilityDistributions.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/math/statistics/unitTestMultiVariateGaussianProbabilityDistributions.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/math/statistics/unitTestMultiVariateGaussianProbabilityDistributions.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": 39.8059701493, "max_line_length": 124, "alphanum_fraction": 0.6327959005, "num_tokens": 1967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5797034521303832}}
{"text": "/* Boost interval/arith2.hpp template implementation file\n *\n * This header provides some auxiliary arithmetic\n * functions: fmod, sqrt, square, pov, inverse and\n * a multi-interval division.\n *\n * Copyright 2002-2003 Herv\u00e9 Br\u00f6nnimann, Guillaume Melquiond, Sylvain Pion\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_INTERVAL_ARITH2_HPP\n#define BOOST_NUMERIC_INTERVAL_ARITH2_HPP\n\n#include <boost/config.hpp>\n#include <boost/numeric/interval/detail/interval_prototype.hpp>\n#include <boost/numeric/interval/detail/test_input.hpp>\n#include <boost/numeric/interval/detail/bugs.hpp>\n#include <boost/numeric/interval/detail/division.hpp>\n#include <boost/numeric/interval/arith.hpp>\n#include <boost/numeric/interval/policies.hpp>\n#include <algorithm>\n#include <cassert>\n#include <boost/config/no_tr1/cmath.hpp>\n\nnamespace boost {\nnamespace numeric {\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> fmod(const interval<T, Policies>& x,\n                           const interval<T, Policies>& y)\n{\n  if (interval_lib::detail::test_input(x, y))\n    return interval<T, Policies>::empty();\n  typename Policies::rounding rnd;\n  typedef typename interval_lib::unprotect<interval<T, Policies> >::type I;\n  T const &yb = interval_lib::user::is_neg(x.lower()) ? y.lower() : y.upper();\n  T n = rnd.int_down(rnd.div_down(x.lower(), yb));\n  return (const I&)x - n * (const I&)y;\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> fmod(const interval<T, Policies>& x, const T& y)\n{\n  if (interval_lib::detail::test_input(x, y))\n    return interval<T, Policies>::empty();\n  typename Policies::rounding rnd;\n  typedef typename interval_lib::unprotect<interval<T, Policies> >::type I;\n  T n = rnd.int_down(rnd.div_down(x.lower(), y));\n  return (const I&)x - n * I(y);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> fmod(const T& x, const interval<T, Policies>& y)\n{\n  if (interval_lib::detail::test_input(x, y))\n    return interval<T, Policies>::empty();\n  typename Policies::rounding rnd;\n  typedef typename interval_lib::unprotect<interval<T, Policies> >::type I;\n  T const &yb = interval_lib::user::is_neg(x) ? y.lower() : y.upper();\n  T n = rnd.int_down(rnd.div_down(x, yb));\n  return x - n * (const I&)y;\n}\n\nnamespace interval_lib {\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> division_part1(const interval<T, Policies>& x,\n                                     const interval<T, Policies>& y, bool& b)\n{\n  typedef interval<T, Policies> I;\n  b = false;\n  if (detail::test_input(x, y))\n    return I::empty();\n  if (zero_in(y))\n    if (!user::is_zero(y.lower()))\n      if (!user::is_zero(y.upper()))\n        return detail::div_zero_part1(x, y, b);\n      else\n        return detail::div_negative(x, y.lower());\n    else\n      if (!user::is_zero(y.upper()))\n        return detail::div_positive(x, y.upper());\n      else\n        return I::empty();\n  else\n    return detail::div_non_zero(x, y);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> division_part2(const interval<T, Policies>& x,\n                                     const interval<T, Policies>& y, bool b = true)\n{\n  if (!b) return interval<T, Policies>::empty();\n  return detail::div_zero_part2(x, y);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> multiplicative_inverse(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (detail::test_input(x))\n    return I::empty();\n  T one = static_cast<T>(1);\n  typename Policies::rounding rnd;\n  if (zero_in(x)) {\n    typedef typename Policies::checking checking;\n    if (!user::is_zero(x.lower()))\n      if (!user::is_zero(x.upper()))\n        return I::whole();\n      else\n        return I(checking::neg_inf(), rnd.div_up(one, x.lower()), true);\n    else\n      if (!user::is_zero(x.upper()))\n        return I(rnd.div_down(one, x.upper()), checking::pos_inf(), true);\n      else\n        return I::empty();\n  } else\n    return I(rnd.div_down(one, x.upper()), rnd.div_up(one, x.lower()), true);\n}\n\nnamespace detail {\n\ntemplate<class T, class Rounding> inline\nT pow_dn(const T& x_, int pwr, Rounding& rnd) // x and pwr are positive\n{\n  T x = x_;\n  T y = (pwr & 1) ? x_ : static_cast<T>(1);\n  pwr >>= 1;\n  while (pwr > 0) {\n    x = rnd.mul_down(x, x);\n    if (pwr & 1) y = rnd.mul_down(x, y);\n    pwr >>= 1;\n  }\n  return y;\n}\n\ntemplate<class T, class Rounding> inline\nT pow_up(const T& x_, int pwr, Rounding& rnd) // x and pwr are positive\n{\n  T x = x_;\n  T y = (pwr & 1) ? x_ : static_cast<T>(1);\n  pwr >>= 1;\n  while (pwr > 0) {\n    x = rnd.mul_up(x, x);\n    if (pwr & 1) y = rnd.mul_up(x, y);\n    pwr >>= 1;\n  }\n  return y;\n}\n\n} // namespace detail\n} // namespace interval_lib\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> pow(const interval<T, Policies>& x, int pwr)\n{\n  BOOST_USING_STD_MAX();\n  using interval_lib::detail::pow_dn;\n  using interval_lib::detail::pow_up;\n  typedef interval<T, Policies> I;\n\n  if (interval_lib::detail::test_input(x))\n    return I::empty();\n\n  if (pwr == 0)\n    if (interval_lib::user::is_zero(x.lower())\n        && interval_lib::user::is_zero(x.upper()))\n      return I::empty();\n    else\n      return I(static_cast<T>(1));\n  else if (pwr < 0)\n    return interval_lib::multiplicative_inverse(pow(x, -pwr));\n\n  typename Policies::rounding rnd;\n\n  if (interval_lib::user::is_neg(x.upper())) {        // [-2,-1]\n    T yl = pow_dn(static_cast<T>(-x.upper()), pwr, rnd);\n    T yu = pow_up(static_cast<T>(-x.lower()), pwr, rnd);\n    if (pwr & 1)     // [-2,-1]^1\n      return I(-yu, -yl, true);\n    else             // [-2,-1]^2\n      return I(yl, yu, true);\n  } else if (interval_lib::user::is_neg(x.lower())) { // [-1,1]\n    if (pwr & 1) {   // [-1,1]^1\n      return I(-pow_up(static_cast<T>(-x.lower()), pwr, rnd), pow_up(x.upper(), pwr, rnd), true);\n    } else {         // [-1,1]^2\n      return I(static_cast<T>(0), pow_up(max BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<T>(-x.lower()), x.upper()), pwr, rnd), true);\n    }\n  } else {                                // [1,2]\n    return I(pow_dn(x.lower(), pwr, rnd), pow_up(x.upper(), pwr, rnd), true);\n  }\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> sqrt(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x) || interval_lib::user::is_neg(x.upper()))\n    return I::empty();\n  typename Policies::rounding rnd;\n  T l = !interval_lib::user::is_pos(x.lower()) ? static_cast<T>(0) : rnd.sqrt_down(x.lower());\n  return I(l, rnd.sqrt_up(x.upper()), true);\n}\n\ntemplate<class T, class Policies> inline\ninterval<T, Policies> square(const interval<T, Policies>& x)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x))\n    return I::empty();\n  typename Policies::rounding rnd;\n  const T& xl = x.lower();\n  const T& xu = x.upper();\n  if (interval_lib::user::is_neg(xu))\n    return I(rnd.mul_down(xu, xu), rnd.mul_up(xl, xl), true);\n  else if (interval_lib::user::is_pos(x.lower()))\n    return I(rnd.mul_down(xl, xl), rnd.mul_up(xu, xu), true);\n  else\n    return I(static_cast<T>(0), (-xl > xu ? rnd.mul_up(xl, xl) : rnd.mul_up(xu, xu)), true);\n}\n\nnamespace interval_lib {\nnamespace detail {\n\ntemplate< class I > inline\nI root_aux(typename I::base_type const &x, int k) // x and k are bigger than one\n{\n  typedef typename I::base_type T;\n  T tk(k);\n  I y(static_cast<T>(1), x, true);\n  for(;;) {\n    T y0 = median(y);\n    I yy = intersect(y, y0 - (pow(I(y0, y0, true), k) - x) / (tk * pow(y, k - 1)));\n    if (equal(y, yy)) return y;\n    y = yy;\n  }\n}\n\ntemplate< class I > inline // x is positive and k bigger than one\ntypename I::base_type root_aux_dn(typename I::base_type const &x, int k)\n{\n  typedef typename I::base_type T;\n  typedef typename I::traits_type Policies;\n  typename Policies::rounding rnd;\n  T one(1);\n  if (x > one) return root_aux<I>(x, k).lower();\n  if (x == one) return one;\n  return rnd.div_down(one, root_aux<I>(rnd.div_up(one, x), k).upper());\n}\n\ntemplate< class I > inline // x is positive and k bigger than one\ntypename I::base_type root_aux_up(typename I::base_type const &x, int k)\n{\n  typedef typename I::base_type T;\n  typedef typename I::traits_type Policies;\n  typename Policies::rounding rnd;\n  T one(1);\n  if (x > one) return root_aux<I>(x, k).upper();\n  if (x == one) return one;\n  return rnd.div_up(one, root_aux<I>(rnd.div_down(one, x), k).lower());\n}\n\n} // namespace detail\n} // namespace interval_lib\n\ntemplate< class T, class Policies > inline\ninterval<T, Policies> nth_root(interval<T, Policies> const &x, int k)\n{\n  typedef interval<T, Policies> I;\n  if (interval_lib::detail::test_input(x)) return I::empty();\n  assert(k > 0);\n  if (k == 1) return x;\n  typename Policies::rounding rnd;\n  typedef typename interval_lib::unprotect<I>::type R;\n  if (!interval_lib::user::is_pos(x.upper())) {\n    if (interval_lib::user::is_zero(x.upper())) {\n      T zero(0);\n      if (!(k & 1) || interval_lib::user::is_zero(x.lower())) // [-1,0]^/2 or [0,0]\n        return I(zero, zero, true);\n      else               // [-1,0]^/3\n        return I(-interval_lib::detail::root_aux_up<R>(-x.lower(), k), zero, true);\n    } else if (!(k & 1)) // [-2,-1]^/2\n      return I::empty();\n    else {               // [-2,-1]^/3\n      return I(-interval_lib::detail::root_aux_up<R>(-x.lower(), k),\n               -interval_lib::detail::root_aux_dn<R>(-x.upper(), k), true);\n    }\n  }\n  T u = interval_lib::detail::root_aux_up<R>(x.upper(), k);\n  if (!interval_lib::user::is_pos(x.lower()))\n    if (!(k & 1) || interval_lib::user::is_zero(x.lower())) // [-1,1]^/2 or [0,1]\n      return I(static_cast<T>(0), u, true);\n    else                 // [-1,1]^/3\n      return I(-interval_lib::detail::root_aux_up<R>(-x.lower(), k), u, true);\n  else                   // [1,2]\n    return I(interval_lib::detail::root_aux_dn<R>(x.lower(), k), u, true);\n}\n\n} // namespace numeric\n} // namespace boost\n\n#endif // BOOST_NUMERIC_INTERVAL_ARITH2_HPP\n", "meta": {"hexsha": "4f56f23b642c142cc2ea26b980f3322b9d3418cc", "size": 10087, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/numeric/interval/arith2.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/numeric/interval/arith2.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/numeric/interval/arith2.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 32.9640522876, "max_line_length": 135, "alphanum_fraction": 0.6308119362, "num_tokens": 2906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5797034484355579}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EXPONENTIAL_FUNCTIONS_SIMD_COMMON_LOGSPACE_ADD_HPP_INCLUDED\n#define NT2_EXPONENTIAL_FUNCTIONS_SIMD_COMMON_LOGSPACE_ADD_HPP_INCLUDED\n\n#include <nt2/exponential/functions/logspace_add.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/exp.hpp>\n#include <nt2/include/functions/simd/log1p.hpp>\n#include <nt2/include/functions/simd/max.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/functions/simd/plus.hpp>\n#include <nt2/include/functions/simd/unary_minus.hpp>\n\n#ifndef BOOST_SIMD_NO_NANS\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/is_nan.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n\n  BOOST_DISPATCH_IMPLEMENT  ( logspace_add_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_< floating_<A0>, X >))\n                              ((simd_< floating_<A0>, X >))\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      A0 tmp = -nt2::abs(a0-a1);\n      A0 r = nt2::max(a0,a1)+nt2::log1p(nt2::exp(tmp));\n      #ifndef BOOST_SIMD_NO_NANS\n      r = if_else(is_nan(tmp), a0+a1, r);\n      #endif\n      return r;\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "295e7b268ea960413d3d360d9cf300fbfd7904e1", "size": 1771, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/simd/common/logspace_add.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/simd/common/logspace_add.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/simd/common/logspace_add.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": 35.42, "max_line_length": 80, "alphanum_fraction": 0.59175607, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5797034441436236}}
{"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": "////////////////////////////////////////////////////////////////////////////////\n//  Copyright (c) 2019 Prashant K. Jha\n//\n//  Distributed under the Boost Software License, Version 1.0. (See accompanying\n//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n////////////////////////////////////////////////////////////////////////////////\n\n#ifndef UTILS_RANDOM_DIST_H\n#define UTILS_RANDOM_DIST_H\n\n#include <boost/random.hpp>\n#include <random>\n\n#include \"libmesh/parallel.h\"\n\n#include \"utilIO.hpp\"\n\n// boost method\n//typedef boost::mt19937 RandGen;\n//typedef boost::lognormal_distribution<> LogNormalDist;\n//typedef boost::uniform_real<> UniformDist;\n//typedef boost::normal_distribution<> NormalDist;\n\ntypedef std::mt19937 RandGenerator;\ntypedef std::lognormal_distribution<> LogNormalDistribution;\ntypedef std::uniform_real_distribution<> UniformDistribution;\ntypedef std::normal_distribution<> NormalDistribution;\n\nnamespace util {\n\ninline RandGenerator get_rd_gen(int &seed) {\n\n  //return RandGenerator();\n\n  if (seed < 0) {\n    std::random_device rd;\n    seed = rd();\n  }\n\n  return RandGenerator(seed);\n}\n\ninline std::default_random_engine get_rd_engine(int &seed) {\n\n  //return std::default_random_engine();\n\n  if (seed < 0) {\n    std::random_device rd;\n    seed = rd();\n  }\n\n  return std::default_random_engine(seed);\n}\n\ninline double transform_to_normal_dist(double mean, double std, double sample) {\n  return std * sample + mean;\n}\n\ninline double transform_to_uniform_dist(double min, double max, double sample) {\n  return min + sample * (max - min);\n}\n\n\ntemplate<class T>\nclass DistributionSample {\npublic:\n  DistributionSample(double arg1, double arg2, int seed = -1)\n      : d_seed(seed), d_gen(get_rd_gen(seed)), d_dist(arg1, arg2){};\n\n  DistributionSample() : d_seed(-1){};\n\n  void init(double arg1, double arg2, int seed = -1) {\n\n    d_seed = seed;\n    d_gen = RandGenerator(get_rd_gen(seed));\n    d_dist = T(arg1, arg2);\n  }\n\n  double operator()() {\n    return d_dist(d_gen);\n  }\n\n  // not implemented for this\n  void debug_out(const std::string &filename) {\n    return;\n  }\n\n  int d_seed;\n  RandGenerator d_gen;\n  T d_dist;\n};\n\ntemplate<class T>\nclass DistributionSampleParallel {\npublic:\n  DistributionSampleParallel(double arg1, double arg2,\n                             libMesh::Parallel::Communicator *comm,\n                             int seed = -1,\n                             unsigned int sample_size = 1000)\n      : d_seed(seed), d_curSample(0), d_sampleSize(sample_size),\n        d_gen(get_rd_gen(seed)), d_dist(arg1, arg2), d_procRank(0),\n        d_procSize(0), d_comm_p(comm) {\n\n    if (comm) {\n      d_procRank = d_comm_p->rank();\n      d_procSize = d_comm_p->size();\n    }\n\n    d_samples.reserve(d_sampleSize);\n    if (d_procRank == 0)\n      d_samples.resize(d_sampleSize);\n\n    update();\n  };\n\n  DistributionSampleParallel()\n      : d_seed(-1), d_curSample(0), d_sampleSize(0), d_procRank(0),\n        d_procSize(0), d_comm_p(nullptr){};\n\n  void init(double arg1, double arg2,\n            libMesh::Parallel::Communicator *comm,\n            int seed = -1,\n            unsigned int sample_size = 1000) {\n\n    d_seed = seed;\n    d_curSample = 0;\n    d_sampleSize = sample_size;\n    d_gen = RandGenerator(get_rd_gen(seed));\n    d_dist = T(arg1, arg2);\n    d_comm_p = comm;\n\n    if (comm) {\n      d_procRank = d_comm_p->rank();\n      d_procSize = d_comm_p->size();\n    }\n\n    d_samples.reserve(d_sampleSize);\n    if (d_procRank == 0)\n      d_samples.resize(d_sampleSize);\n\n    update();\n  }\n\n  double operator()() {\n    if (d_curSample < d_sampleSize) {\n      return d_samples[d_curSample++];\n    } else {\n      update();\n      return d_samples[d_curSample++];\n    }\n  }\n\n  void update() {\n\n    d_curSample = 0;\n    if (d_procRank == 0) {\n      for (unsigned int i = 0; i < d_sampleSize; i++)\n        d_samples[i] = d_dist(d_gen);\n    } else {\n      d_samples.resize(0);\n    }\n\n    d_comm_p->allgather(d_samples);\n    if (d_samples.size() != d_sampleSize)\n      libmesh_error_msg(\"Error collecting samples\");\n  }\n\n  void debug_out(const std::string &filename) {\n    util::io::printFile(filename + \"_\" + std::to_string(d_procRank) + \".txt\", d_samples, 0, \" \");\n  }\n\n  int d_seed;\n  unsigned int d_curSample;\n  unsigned int d_sampleSize;\n  RandGenerator d_gen;\n  T d_dist;\n  unsigned int d_procRank;\n  unsigned int d_procSize;\n  libMesh::Parallel::Communicator *d_comm_p;\n  std::vector<double> d_samples;\n};\n\n} // namespace util\n\n#endif // UTILS_RANDOM_DIST_H\n", "meta": {"hexsha": "807ee8f9404e4fdf6d6dcff1310740cc2f1e94d2", "size": 4504, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "models/utils/random_dist.hpp", "max_stars_repo_name": "CancerModeling/Angiogenesis3D1D", "max_stars_repo_head_hexsha": "77527d3facd127e225ccb9e53874ddbba2096744", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-02T07:49:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T15:47:40.000Z", "max_issues_repo_path": "models/utils/random_dist.hpp", "max_issues_repo_name": "CancerModeling/Angiogenesis3D1D", "max_issues_repo_head_hexsha": "77527d3facd127e225ccb9e53874ddbba2096744", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/utils/random_dist.hpp", "max_forks_repo_name": "CancerModeling/Angiogenesis3D1D", "max_forks_repo_head_hexsha": "77527d3facd127e225ccb9e53874ddbba2096744", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2150537634, "max_line_length": 97, "alphanum_fraction": 0.6334369449, "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.579685235803999}}
{"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//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/interval/interval_boost_interval_type_traits.h>\n#include <OpenTissue/core/math/interval/interval.h>\n#include <OpenTissue/core/math/math_vector3.h>\n#include <OpenTissue/core/math/math_matrix3x3.h>\n#include <OpenTissue/utility/utility_timer.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n#include <iostream>\n\nusing namespace boost::numeric;\nusing namespace OpenTissue;\n\n\n// Performance Timings: Centrino Duo, 2GB RAM, .NET 2005\n//\n//    interval demo started\n//    OT type\n//        test took 1.74157 seconds\n//    boost default type\n//        test took 19.701 seconds\n//    boost default type with unprotect\n//        test took 0.940387 seconds\n//    boost smart type\n//        test took 0.794767 seconds\n//    boost smart type with unprotect\n//        test took 0.796035 seconds\n//\n//\n// Linux performance numbers:\n//\n//  henrik@blackmonster ~/Work/OpenTissue/optimized_test/demos/opengl/interval $ g++ -DHAVE_CONFIG_H -I. -I../../../../demos/opengl/interval -I../../..  -I../../../.. -I../../../../externals/include -O3 -march=pentium4 -fomit-frame-pointer -fwhole-program -pipe -DNDEBUG -o interval ../../../../demos/opengl/interval/src/main.cpp\n//  henrik@blackmonster ~/Work/OpenTissue/optimized_test/demos/opengl/interval $ ./interval\n//  interval demo started\n//  OT type\n//        test took 2.68147 seconds\n//  boost default type\n//        test took 6.14975 seconds\n//  boost default type with unprotect\n//        test took 4.89632 seconds\n//  boost smart type\n//        test took 4.12788 seconds\n//  boost smart type with unprotect\n//        test took 4.12735 seconds\n//\n//  henrik@blackmonster ~/Work/OpenTissue/optimized_test/demos/opengl/interval $ uname -a\n//  Linux blackmonster 2.6.17-gentoo-r8 #3 SMP Mon Nov 6 22:01:53 CET 2006 i686 Intel(R) Pentium(R) 4 CPU 1.60GHz GenuineIntel GNU/Linux\n//\n\n\ntemplate<typename interval_type>\nvoid interval_compile_testing()\n{\n  typedef typename interval_type::base_type    real_type;\n  typedef OpenTissue::math::Vector3<real_type>       vector3_type;\n  typedef OpenTissue::math::Vector3<interval_type>   vector3_interval_type;\n  typedef OpenTissue::math::Matrix3x3<interval_type> matrix3x3_interval_type;\n\n  //--- implicit type conversions\n  interval_type i1;\n  interval_type i2(5);\n  interval_type i3(5.0);\n  interval_type i4(5.0f);\n  interval_type i5(5,6);\n  interval_type i6(5.0,6.0);\n  interval_type i7(5.0f,6.0f);\n  interval_type A(-1.0,1.0);\n  interval_type B(0.0,1.0);\n  interval_type C(-1.0,0.0);\n  double s = 1.0;\n  //--- arithmetic testing\n  A += B;\n  A = B + C;\n  A -= B;\n  A = B - C;\n  B = -A;\n  A *= B;\n  A = B*C;\n  A = C*B;\n  A /= B;\n  A = B/C;\n  A = C/B;\n  A *= s;\n  A = B*s;\n  //A = s*B; // do not exist!!!\n  //--- only OpenTissue::interval\n  //A.clear();\n  //A.is_valid();  \n  //  A.get_abs_lower();\n  //  A.get_abs_upper();\n  //  A[-2];\n  //  A[0];\n  //  A[1];\n  //  A[2];\n  //  A(-2);\n  //  A(0);\n  //  A(1);\n  //  A(2);\n  //--- assignment testing\n  A.assign( -1.0,  1.0);\n  B.assign( -3.0, -2.0);\n  C.assign(  2.0,  4.0);\n  //--- logical/comparison testing\n  bool cmp1 = (A==B);\n  bool cmp2 = (A!=B);\n  bool cmp3 = (C<B) ;\n  bool cmp4 = (C>B) ;\n  bool cmp5 = (C<=B);\n  bool cmp6 = (C>=B);\n\n  cmp1 = cmp2 | cmp3 | cmp4 | cmp5 | cmp6; // To get rid of compiler warning: unused variable\n  \n  //--- intersect testing\n  A = intersect(B,C);    \n  B = interval_type(-2,-1);\n  C = interval_type(1,2);\n  A = intersect(B,C);\n  A = intersect(C,B);\n  B = interval_type(-2,1);\n  C = interval_type(-1,2);\n  A = intersect(B,C);\n  A = intersect(C,B);\n  B = interval_type(1,-1);\n  C = interval_type(1,1);\n  A = intersect(B,C);\n  A = intersect(C,B);\n}\n\n\ntemplate<typename interval_type>\nvoid performance_test(interval_type const & i)\n{\n  using namespace OpenTissue::math::interval;\n\n  OpenTissue::utility::Timer<double> watch;\n  watch.start();\n  typedef double                               real_type;\n  typedef OpenTissue::math::Vector3<real_type>       vector3_type;\n  typedef OpenTissue::math::Vector3<interval_type>   vector3_interval_type;\n  typedef OpenTissue::math::Matrix3x3<interval_type> matrix3x3_interval_type;\n  interval_type A(-1,1);\n  matrix3x3_interval_type IM(A,A,A,A,A,A,A,A,A);\n  vector3_interval_type IV(A,A,A);\n  vector3_type V(1,2,3);\n  for(unsigned int i=0u;i<10000000u;++i)\n    IV = IM * V + (IV*0.5);\n  watch.stop();\n  BOOST_TEST_MESSAGE( typeid(interval_type).name() << \" took \" << watch() << \" sec.\" );\n}\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_interval);\n\n  BOOST_AUTO_TEST_CASE(opentissue_testing)\n  {\n    typedef OpenTissue::math::interval::Interval<double> interval_type;\n    performance_test(interval_type());\n    void (*ptr) () = 0;\n    ptr = &interval_compile_testing< interval_type >;\n  }\n\n  BOOST_AUTO_TEST_CASE(boost_default_testing)\n  {\n    typedef boost::numeric::interval<double >      interval_type;\n    performance_test(interval_type());\n    void (*ptr) () = 0;\n    ptr = &interval_compile_testing< interval_type >;\n  }\n\n  BOOST_AUTO_TEST_CASE(boost_default_with_unprotect_testing)\n  {\n    typedef boost::numeric::interval<double >      interval_type;\n    interval_type::traits_type::rounding rnd;\n    typedef  boost::numeric::interval_lib::unprotect<interval_type>::type R;\n    performance_test(R());\n    void (*ptr) () = 0;\n    ptr = &interval_compile_testing< interval_type >;\n  }\n\n  BOOST_AUTO_TEST_CASE(boost_smart_type_testing)\n  {\n    typedef OpenTissue::math::interval::BoostIntervalTypeTraits<double>::interval_type interval_type;  \n    performance_test(interval_type());\n    void (*ptr) () = 0;\n    ptr = &interval_compile_testing< interval_type >;\n  }\n\n  BOOST_AUTO_TEST_CASE(boost_smart_type_with_unprotect_testing)\n  {\n    typedef OpenTissue::math::interval::BoostIntervalTypeTraits<double>::interval_type interval_type;\n    interval_type::traits_type::rounding rnd;\n\n    rnd;\n    \n    typedef  boost::numeric::interval_lib::unprotect<interval_type>::type R;\n    performance_test(R());\n    void (*ptr) () = 0;\n    ptr = &interval_compile_testing< interval_type >;\n  }\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "19c790753f25a44a62fb13aad9e162b8705a87a6", "size": 6506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/interval/src/unit_interval.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/interval/src/unit_interval.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/interval/src/unit_interval.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 30.4018691589, "max_line_length": 329, "alphanum_fraction": 0.6766062097, "num_tokens": 1878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5796852213825341}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2010-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#include <iostream>\n#include <string>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n#include <boost/geometry/algorithms/length.hpp>\n#include <boost/geometry/algorithms/num_points.hpp>\n#include <boost/geometry/algorithms/unique.hpp>\n#include <boost/geometry/extensions/algorithms/offset.hpp>\n#include <boost/geometry/multi/io/wkt/read.hpp>\n\n#include <boost/geometry/strategies/strategies.hpp>\n\n\n#if defined(TEST_WITH_SVG)\n#  include <boost/geometry/multi/algorithms/envelope.hpp>\n#  include <boost/geometry/io/svg/svg_mapper.hpp>\n#endif\n\n\ntemplate <typename GeometryOut, typename Geometry>\nvoid test_offset(std::string const& caseid, Geometry const& geometry,\n        double distance,\n        double expected_length, double percentage)\n{\n    typedef typename bg::coordinate_type<Geometry>::type coordinate_type;\n    typedef typename bg::point_type<Geometry>::type point_type;\n\n    // TODO: also make tests for miter\n    typedef bg::strategy::buffer::join_round\n        <\n            point_type,\n            point_type\n        > join_strategy;\n\n    GeometryOut moved_by_offset;\n    bg::offset(geometry, moved_by_offset, join_strategy(), distance);\n\n    typename bg::default_length_result<Geometry>::type length\n                    = bg::length(moved_by_offset);\n\n    /*\n    std::size_t count = bg::num_points(moved_by_offset);\n    BOOST_CHECK_MESSAGE(count == expected_point_count,\n            \"offset: \" << caseid\n            << \" #points expected: \" << expected_point_count\n            << \" detected: \" << count\n            << \" type: \" << string_from_type<coordinate_type>::name()\n            );\n    */\n\n\n    //BOOST_CHECK_EQUAL(holes, expected_hole_count);\n    BOOST_CHECK_CLOSE(length, expected_length, percentage);\n\n#if defined(TEST_WITH_SVG)\n    {\n        std::ostringstream filename;\n        filename << \"offset_\"\n            << caseid << \"_\"\n            << string_from_type<coordinate_type>::name()\n            << \".svg\";\n\n        std::ofstream svg(filename.str().c_str());\n\n        bg::svg_mapper\n            <\n                typename bg::point_type<Geometry>::type\n            > mapper(svg, 500, 500);\n        mapper.add(geometry);\n        mapper.add(moved_by_offset);\n\n        mapper.map(geometry, \"opacity:0.6;fill:rgb(0,0,255);stroke:rgb(0,0,0);stroke-width:1\");\n        mapper.map(moved_by_offset, \"opacity:0.6;fill:none;stroke:rgb(255,0,0);stroke-width:5\");\n    }\n#endif\n}\n\n\ntemplate <typename Geometry>\nvoid test_one(std::string const& caseid, std::string const& wkt, double distance,\n        double expected_length_plus, double expected_length_minus, bool do_plus, bool do_min)\n{\n    Geometry geometry;\n    bg::read_wkt(wkt, geometry);\n\n    double percentage = 0.01;\n    if (do_plus) test_offset<Geometry>(caseid + \"_a\", geometry, distance, expected_length_plus, percentage);\n    if (do_min) test_offset<Geometry>(caseid + \"_b\", geometry, -distance, expected_length_minus, percentage);\n}\n\n\n\n\ntemplate <typename P>\nvoid test_all()\n{\n\n    typedef bg::model::linestring<P> linestring;\n\n    static std::string const simplex = \"LINESTRING(0 0,1 1)\";\n    static std::string const one_bend = \"LINESTRING(0 0,4 5,7 4)\";\n    static std::string const two_bends = \"LINESTRING(0 0,4 5,7 4,10 6)\";\n    static std::string const overlapping = \"LINESTRING(0 0,4 5,7 4,10 6, 10 2,2 2)\";\n    static std::string const curve = \"LINESTRING(2 7,3 5,5 4,7 5,8 7)\";\n    static std::string const reallife1 = \"LINESTRING(76396.40464822574 410095.6795147947,76397.85016212701 410095.211865792,76401.30666443033 410095.0466387949,76405.05892643372 410096.1007777959,76409.45103273794 410098.257640797,76412.96309264141 410101.6522238015)\";\n\n    test_one<linestring>(\"ls_simplex\", simplex, 0.5, std::sqrt(2.0), std::sqrt(2.0), true, true);\n    test_one<linestring>(\"one_bend\", one_bend, 0.5, 10.17328, 8.8681, true, false);\n\n    // Most of the tests below fail because the internal implementation of buffer is changed in the meantime (on purpose).\n    // The offset now contains knots which should be removed separately, apart from the buffer algorithm.\n    // The offset algorithm is therefore hardly usable now (only convex pieces are handled correctly...)\n\n    // TODO: decide about this / implement this correctly.\n\n    //test_one<linestring>(\"two_bends\", two_bends, 0.5, 13.2898, 12.92811);\n    //test_one<linestring>(\"overlapping\", overlapping, 0.5, 27.1466, 22.0596);\n    test_one<linestring>(\"curve\", curve, 0.5, 7.7776,  10.0507, false, true);\n    //test_one<linestring>(\"reallife1\", reallife1, 16.5, 5.4654, 36.4943);\n}\n\n\nint test_main(int, char* [])\n{\n    test_all<bg::model::d2::point_xy<double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "3bdd664391e15b855a838fa011f8d4f100ca26f5", "size": 5041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/algorithms/offset.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/test/algorithms/offset.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/test/algorithms/offset.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 35.5, "max_line_length": 269, "alphanum_fraction": 0.6893473517, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.5796759506663549}}
{"text": "/**\n *  @copyright Copyright 2021 The J-PET Framework Authors. All rights reserved.\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 find a copy of the License in the LICENCE file.\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 CalibrationToolsTest.cpp\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE EventCategorizerToolsTests\n#include \"../calibrationProgram/CalibrationTools.h\"\n#include <boost/test/unit_test.hpp>\n#include <cstdlib>\n#include <chrono>\n#include <random>\n#include <ctime>\n\n/// Accuracy for BOOST_REQUIRE_CLOSE comparisons\nconst double kEpsilon = 0.01;\n\nBOOST_AUTO_TEST_SUITE(CalibrationProgramCheckSuite)\n\nBOOST_AUTO_TEST_CASE(checkEstimateExtremumBin) {\n  CalibrationTools calibTools;\n  std::vector<double> values;\n  unsigned numberOfPoints = 100;\n  double mean1 = -2000, mean2 = 2000;\n  double normalization = 1000000;\n  double sigma = 200;\n  double stepSize = 100;\n  double tempValue;\n  for (unsigned i=0; i<numberOfPoints; i++) {\n    tempValue = 0;\n    tempValue = normalization*exp(-pow(-0.5*stepSize*numberOfPoints + i*stepSize - mean1,2)/(2*pow(sigma,2)));\n    tempValue -= normalization*exp(-pow(-0.5*stepSize*numberOfPoints + i*stepSize - mean2,2)/(2*pow(sigma,2)));\n    values.push_back(tempValue);\n  }\n  unsigned extremumLeft = calibTools.EstimateExtremumBin(values, 0, 1, Side::Left);\n  unsigned extremumRight = calibTools.EstimateExtremumBin(values, 0, 1, Side::Right);\n  BOOST_REQUIRE_EQUAL((float)extremumLeft, 31);\n  BOOST_REQUIRE_EQUAL((float)extremumRight, 69);\n}\n\nBOOST_AUTO_TEST_CASE(checkFindingPeak) {\n  CalibrationTools calibTools;\n  std::vector<double> values = {-2, -1, 0, 1, 2};\n  std::vector<double> arguments = {0, 1, 2, 3, 4};\n  Parameter result = calibTools.FindPeak(arguments, values, 0, 4);\n  BOOST_REQUIRE_CLOSE(result.Value, 2, kEpsilon);\n}\n\nBOOST_AUTO_TEST_CASE(checkFindingMiddleAB) {\n  CalibrationTools calibTools;\n  TH1D* histo = new TH1D(\"TestDistributionAB\", \"Test distribution of AB\", 2500, -24990, 25010);\n  unsigned numberOfEvents = 10000000;\n  double uniformDistributionWidth = 5000; // 5 ns\n  double resolutionSigma = 150; // 150 ps\n  double tdiffAB, smearing, tempNumber2, tempNumber3;\n  \n  std::uniform_real_distribution<float> distribution(0.0, 1.0);\n  std::random_device rd;\n  std::default_random_engine generator(rd());\n  for (unsigned i=0; i<numberOfEvents; i++) {\n    tdiffAB = uniformDistributionWidth*distribution(generator);\n    tempNumber2 = distribution(generator);\n    tempNumber3 = distribution(generator);\n    smearing = sqrt(-2*log(tempNumber2))*cos(2*M_PI*tempNumber3);\n//Box-muller transformation\n    histo -> Fill(tdiffAB + smearing*resolutionSigma - 0.5*uniformDistributionWidth);\n  }\n  double meanTemp = histo->GetMean(1);\n  double rangeParameter = 4*histo->GetStdDev();\n  \n  Parameter resultLeft = calibTools.FindMiddle(histo, meanTemp - rangeParameter, meanTemp, Side::Left, \"\");\n  Parameter resultRight = calibTools.FindMiddle(histo, meanTemp, meanTemp + rangeParameter, Side::Right, \"\");\n  double acceptedRange = 2*kEpsilon*resolutionSigma;\n  BOOST_REQUIRE_CLOSE(resultLeft.Value, -0.5*uniformDistributionWidth, acceptedRange);\n  BOOST_REQUIRE_CLOSE(resultRight.Value, 0.5*uniformDistributionWidth, acceptedRange);\n  \n  delete histo;\n}\n\nBOOST_AUTO_TEST_CASE(checkFindingMiddlePALS) {\n  CalibrationTools calibTools;\n  TH1D* histo = new TH1D(\"TestDistributionPALS\", \"Test PALS distribution\", 2500, -24990, 25010);\n  unsigned numberOfEvents = 10000000;\n  double exponentialMean = 2000;\n  double resolutionSigma = 150; // 150 ps\n  srand((unsigned)time(NULL));\n  double tdiff, smearing, tempNumber2, tempNumber3;\n  \n  std::uniform_real_distribution<float> distribution(0.0, 1.0);\n  std::random_device rd;\n  std::default_random_engine generator(rd());\n  for (unsigned i=0; i<numberOfEvents; i++) {\n    tdiff = -log(distribution(generator))/exponentialMean;\n    tempNumber2 = distribution(generator);\n    tempNumber3 = distribution(generator);\n    smearing = sqrt(-2*log(tempNumber2))*cos(2*M_PI*tempNumber3);\n//Box-muller transformation\n    histo -> Fill(tdiff + smearing*resolutionSigma);\n  }\n  double meanTemp = histo->GetMean(1);\n  double rangeParameter = 4*histo->GetStdDev();\n    \n  Parameter results = calibTools.FindMiddle(histo, meanTemp - rangeParameter, meanTemp + rangeParameter, Side::MaxAnni, \"\");\n// Proper mode of the exponentially modified gaussian is estimated by erfcinvx function which is quite complicated. Instead a value\n// for 150ps is estimated here. Form is left in order someone want to expand it in future\n  double acceptedValue = pow(resolutionSigma, 2)/exponentialMean - sqrt(2.5)*resolutionSigma*kEpsilon;\n  double acceptedRange = 3*kEpsilon*resolutionSigma;\n  BOOST_REQUIRE_CLOSE(results.Value, acceptedValue, acceptedRange);\n  \n  delete histo;\n}\n\nBOOST_AUTO_TEST_CASE(checkFindingMaximum) {\n  std::vector<double> values = {1, 2, 3, 2, 1, 4, 5, 4, 3, 2, 1};\n  std::vector<double> arguments = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5};\n  unsigned maximum = FindMaximum(values, arguments, -3, 3);\n  BOOST_REQUIRE_EQUAL(maximum, 6);\n\n  unsigned maximum2 = FindMaximum(values, arguments, -6, -1);\n  BOOST_REQUIRE_EQUAL(maximum2, 2);\n}\n\nBOOST_AUTO_TEST_CASE(checkCalculationsMeanDifference) {\n  std::vector<double> vector1 = {1, 2, 3, 2, 1, 4, 5, 4, 3, 2, 1};\n  double diff = CalcMeanDiff(vector1, vector1);\n  BOOST_REQUIRE_CLOSE(diff, 0, kEpsilon);\n  \n  std::vector<double> vector2 = {0, 1, 2, 1, 0, 3, 4, 3, 2, 1, 0};\n  diff = CalcMeanDiff(vector1, vector2);\n  BOOST_REQUIRE_CLOSE(diff, 1, kEpsilon);\n}\n\nBOOST_AUTO_TEST_CASE(checkCalculationsMeanCorrection) {\n  Parameter par1, par2;\n  par1.Value = 2;\n  par2.Value = 1;\n  std::vector<Parameter> vector1 = {par1, par1, par1, par1, par1};\n  std::vector<std::vector<Parameter>> vector1_2 = {vector1, vector1, vector1};\n  Parameter diff = CalculateMeanCorrection(vector1_2, vector1_2);\n  BOOST_REQUIRE_CLOSE(diff.Value, 0, kEpsilon);\n  \n  std::vector<Parameter> vector2 = {par2, par2, par2, par2, par2};\n  std::vector<std::vector<Parameter>> vector2_2 = {vector2, vector2, vector2};\n  diff = CalculateMeanCorrection(vector1_2, vector2_2);\n  BOOST_REQUIRE_CLOSE(diff.Value, 1, kEpsilon);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e97b6a112d14be20213342118dd00923600d3dca", "size": 6575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TimeCalibration_lifetime/tests/CalibrationToolsTest.cpp", "max_stars_repo_name": "kdulski/j-pet-framework-examples", "max_stars_repo_head_hexsha": "ab2592a2c6cf8f901f5732f8878b750b9a7b6a49", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TimeCalibration_lifetime/tests/CalibrationToolsTest.cpp", "max_issues_repo_name": "kdulski/j-pet-framework-examples", "max_issues_repo_head_hexsha": "ab2592a2c6cf8f901f5732f8878b750b9a7b6a49", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TimeCalibration_lifetime/tests/CalibrationToolsTest.cpp", "max_forks_repo_name": "kdulski/j-pet-framework-examples", "max_forks_repo_head_hexsha": "ab2592a2c6cf8f901f5732f8878b750b9a7b6a49", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3522012579, "max_line_length": 131, "alphanum_fraction": 0.7394676806, "num_tokens": 1881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5796759469156186}}
{"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": "#include <benchmark/benchmark.h>\n\n#include <tnt/core/core.hpp>\n#include <tnt/math/math.hpp>\n\n#include <opencv2/core.hpp>\n#include <benchmark/opencv_utils.hpp>\n\n#include <Eigen/Dense>\n#include <blas/cblas.hpp>\n\ntemplate <typename DataType>\nstatic void multiply_TNT(benchmark::State& state, int size)\n{\n    while (state.KeepRunning()) {\n        state.PauseTiming(); // We don't count tensor creation\n        tnt::Shape shape{size, size};\n\n        tnt::Tensor<DataType> left(shape, 3.f);\n        tnt::Tensor<DataType> right(shape, 4.f);\n\n        state.ResumeTiming();\n        tnt::multiply(left, right);\n    }\n}\n\ntemplate <typename DataType>\nstatic void multiply_OCV(benchmark::State& state, int size)\n{\n    while (state.KeepRunning()) {\n        state.PauseTiming();\n\n        cv::Mat left  = tnt::create_cv_mat<DataType>(size, size, cv::Scalar(3));\n        cv::Mat right = tnt::create_cv_mat<DataType>(size, size, cv::Scalar(4));\n\n        state.ResumeTiming();\n        cv::Mat dst = left * right;\n    }\n}\n\ntemplate <typename DataType>\nstatic void multiply_EIG(benchmark::State& state, int size)\n{\n    using MatType = Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic>;\n\n    while (state.KeepRunning()) {\n        state.PauseTiming();\n\n        MatType left = MatType::Constant(size, size, 3);\n        MatType right = MatType::Constant(size, size, 4);\n\n        state.ResumeTiming();\n        MatType dst = left * right;\n    }\n}\n\ntemplate <typename DataType>\nstruct BLASMultiply {};\n\ntemplate <> struct BLASMultiply<float>\n{\n    static void run(int size, float* left, float* right, float* dst)\n    {\n        /* See https://www.christophlassner.de/using-blas-from-c-with-row-major-data.html */\n        /* For trick to use fortran order (col-major) */\n        cblas_sgemm(CblasColMajor, /* Memory order */\n                    CblasNoTrans,  /* Left is transposed? */\n                    CblasNoTrans,  /* Right is transposed? */\n                    size,          /* Rows of left */\n                    size,          /* Columns of right */\n                    size,          /* Columns of left and rows of right */\n                    1.,            /* Alpha (scale after mult) */\n                    right,         /* Left data */\n                    size,          /* lda, this is really for 2D mats */\n                    left,          /* right data */\n                    size,          /* ldb, this is really for 2D mats */\n                    0.,            /* beta (scale on result before addition) */\n                    dst,           /* result data */\n                    size);         /* ldc, this is really for 2D mats */\n    }\n};\n\ntemplate <> struct BLASMultiply<double>\n{\n    static void run(int size, double* left, double* right, double* dst)\n    {\n        /* See https://www.christophlassner.de/using-blas-from-c-with-row-major-data.html */\n        /* For trick to use fortran order (col-major) */\n        cblas_dgemm(CblasColMajor, /* Memory order */\n                    CblasNoTrans,  /* Left is transposed? */\n                    CblasNoTrans,  /* Right is transposed? */\n                    size,          /* Rows of left */\n                    size,          /* Columns of right */\n                    size,          /* Columns of left and rows of right */\n                    1.,            /* Alpha (scale after mult) */\n                    right,         /* Left data */\n                    size,          /* lda, this is really for 2D mats */\n                    left,          /* right data */\n                    size,          /* ldb, this is really for 2D mats */\n                    0.,            /* beta (scale on result before addition) */\n                    dst,           /* result data */\n                    size);         /* ldc, this is really for 2D mats */\n    }\n};\n\ntemplate <typename DataType>\nstatic void multiply_BLAS(benchmark::State& state, int size)\n{\n    while (state.KeepRunning()) {\n        state.PauseTiming();\n\n        DataType* left  = new DataType[size * size];\n        DataType* right = new DataType[size * size];\n\n        for (int i = 0; i < size * size; ++i) {\n            left[i] = 3;\n            right[i] = 4;\n        }\n\n        state.ResumeTiming();\n\n        // For fairness allocation happens during timing\n        DataType* dst = new DataType[size * size];\n\n        BLASMultiply<DataType>::run(size, left, right, dst);\n    }\n}\n\ntemplate <typename T>\nclass RegisterMatrixMultiplyBenchmark\n{\npublic:\n    RegisterMatrixMultiplyBenchmark(const std::string& type)\n    {\n        std::vector<int> sizes{4, 16, 64, 512, 2048, 3121};\n        for (int size : sizes) {\n            std::string suffix = type + \">[\" + std::to_string(size) + \"x\" + std::to_string(size) + \"]\";\n            benchmark::RegisterBenchmark((\"MatrixMultiply:TNT <\" + suffix).c_str(), multiply_TNT<T>, size);\n            benchmark::RegisterBenchmark((\"MatrixMultiply:OCV <\" + suffix).c_str(), multiply_OCV<T>, size);\n            benchmark::RegisterBenchmark((\"MatrixMultiply:EIG <\" + suffix).c_str(), multiply_EIG<T>, size);\n            benchmark::RegisterBenchmark((\"MatrixMultiply:BLAS<\" + suffix).c_str(), multiply_BLAS<T>, size);\n        }\n    }\n};\n\n//static RegisterMultiplyBenchmark<int>    multiply_benchmark_int(\"int\");\nstatic RegisterMatrixMultiplyBenchmark<float>  matrix_multiply_benchmark_float(\"float\");\nstatic RegisterMatrixMultiplyBenchmark<double> matrix_multiply_benchmark_double(\"double\");\n", "meta": {"hexsha": "46f45bb817444dd9cd5c39b2e486c268f9d7caf5", "size": 5431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/src/linear/matrix_multiply.cpp", "max_stars_repo_name": "JordanCheney/tnt", "max_stars_repo_head_hexsha": "a0fd378079d36b2bd39960c34e5c83f9633db0c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark/src/linear/matrix_multiply.cpp", "max_issues_repo_name": "JordanCheney/tnt", "max_issues_repo_head_hexsha": "a0fd378079d36b2bd39960c34e5c83f9633db0c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-09T04:40:01.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-09T04:40:01.000Z", "max_forks_repo_path": "benchmark/src/linear/matrix_multiply.cpp", "max_forks_repo_name": "JordanCheney/tnt", "max_forks_repo_head_hexsha": "a0fd378079d36b2bd39960c34e5c83f9633db0c0", "max_forks_repo_licenses": ["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.4496644295, "max_line_length": 108, "alphanum_fraction": 0.55533051, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5796759343095113}}
{"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// \u5305\u542b\u6587\u4ef6\u4e0e\u4e4b\u524d\u7684\u65e0\u77e9\u9635\u6559\u7a0b\u7a0b\u5e8f step-37 \u3001 step-48 \u548c step-59 \u76f8\u4f3c\u3002\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// \u4e0b\u9762\u7684\u6587\u4ef6\u5305\u62ecCellwiseInverseMassMatrix\u6570\u636e\u7ed3\u6784\uff0c\u6211\u4eec\u5c06\u5728\u8d28\u91cf\u77e9\u9635\u53cd\u6f14\u4e2d\u4f7f\u7528\u5b83\uff0c\u8fd9\u662f\u672c\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u552f\u4e00\u7684\u65b0\u5305\u542b\u6587\u4ef6\u3002\n\n#include <deal.II/matrix_free/operators.h> \n\nnamespace Euler_DG \n{ \n  using namespace dealii; \n\n// \u4e0e\u5176\u4ed6\u65e0\u77e9\u9635\u6559\u7a0b\u7a0b\u5e8f\u7c7b\u4f3c\uff0c\u6211\u4eec\u5728\u6587\u4ef6\u7684\u9876\u90e8\u6536\u96c6\u6240\u6709\u63a7\u5236\u7a0b\u5e8f\u6267\u884c\u7684\u53c2\u6570\u3002\u9664\u4e86\u6211\u4eec\u60f3\u8981\u8fd0\u884c\u7684\u7ef4\u5ea6\u548c\u591a\u9879\u5f0f\u7a0b\u5ea6\uff0c\u6211\u4eec\u8fd8\u6307\u5b9a\u4e86\u6211\u4eec\u60f3\u8981\u7528\u4e8e\u6b27\u62c9\u65b9\u7a0b\u4e2d\u975e\u7ebf\u6027\u9879\u7684\u9ad8\u65af\u6b63\u4ea4\u516c\u5f0f\u7684\u70b9\u6570\u3002\u6b64\u5916\uff0c\u6211\u4eec\u6307\u5b9a\u4e86\u968f\u65f6\u95f4\u53d8\u5316\u7684\u95ee\u9898\u7684\u65f6\u95f4\u95f4\u9694\uff0c\u5e76\u5b9e\u73b0\u4e86\u4e24\u4e2a\u4e0d\u540c\u7684\u6d4b\u8bd5\u6848\u4f8b\u3002\u7b2c\u4e00\u4e2a\u662f\u4e8c\u7ef4\u7684\u5206\u6790\u89e3\uff0c\u800c\u7b2c\u4e8c\u4e2a\u662f\u4ecb\u7ecd\u4e2d\u63cf\u8ff0\u7684\u56f4\u7ed5\u5706\u67f1\u4f53\u7684\u901a\u9053\u6d41\u3002\u6839\u636e\u6d4b\u8bd5\u6848\u4f8b\uff0c\u6211\u4eec\u8fd8\u6539\u53d8\u4e86\u8fd0\u884c\u6a21\u62df\u7684\u6700\u7ec8\u65f6\u95f4\uff0c\u4ee5\u53ca\u4e00\u4e2a\u53d8\u91cf`output_tick`\uff0c\u5b83\u6307\u5b9a\u4e86\u6211\u4eec\u8981\u5728\u54ea\u4e2a\u65f6\u95f4\u95f4\u9694\u5185\u5199\u5165\u8f93\u51fa\uff08\u5047\u8bbetick\u5927\u4e8e\u65f6\u95f4\u6b65\u957f\uff09\u3002\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// \u63a5\u4e0b\u6765\u662f\u65f6\u95f4\u79ef\u5206\u5668\u7684\u4e00\u4e9b\u7ec6\u8282\uff0c\u5373\u7528\u516c\u5f0f $\\Delta t =\n//  \\text{Cr} n_\\text{stages} \\frac{h}{(p+1)^{1.5} (\\|\\mathbf{u} +\n//  c)_\\text{max}}$ \u6765\u8861\u91cf\u65f6\u95f4\u6b65\u957f\u7684\u5e93\u6717\u6570\uff0c\u4ee5\u53ca\u9009\u62e9\u4e00\u4e9b\u4f4e\u5b58\u50a8\u91cf\u7684Runge--Kutta\u65b9\u6cd5\u3002\u6211\u4eec\u6307\u5b9aRunge--Kutta\u65b9\u6848\u6bcf\u7ea7\u7684Courant\u6570\uff0c\u56e0\u4e3a\u8fd9\u5bf9\u4e0d\u540c\u7ea7\u6570\u7684\u65b9\u6848\u7ed9\u51fa\u4e86\u4e00\u4e2a\u66f4\u5b9e\u9645\u7684\u6570\u503c\u6210\u672c\u8868\u8fbe\u3002\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// \u6700\u7ec8\uff0c\u6211\u4eec\u9009\u62e9\u4e86\u7a7a\u95f4\u79bb\u6563\u5316\u7684\u4e00\u4e2a\u7ec6\u8282\uff0c\u5373\u5355\u5143\u95f4\u9762\u7684\u6570\u503c\u901a\u91cf\uff08\u9ece\u66fc\u6c42\u89e3\u5668\uff09\u3002\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u5b9e\u73b0\u4e86Lax--Friedrichs\u901a\u91cf\u548cHarten--Lax--van Leer(HLL)\u901a\u91cf\u7684\u4e00\u4e2a\u6539\u8fdb\u7248\u672c\u3002\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// \u6211\u4eec\u73b0\u5728\u5b9a\u4e49\u4e86\u4e00\u4e2a\u5e26\u6709\u6d4b\u8bd5\u60c5\u51b50\u7684\u7cbe\u786e\u89e3\u7684\u7c7b\u548c\u4e00\u4e2a\u5e26\u6709\u6d4b\u8bd5\u60c5\u51b51\u7684\u901a\u9053\u80cc\u666f\u6d41\u573a\u7684\u7c7b\u3002\u9274\u4e8e\u6b27\u62c9\u65b9\u7a0b\u662f\u4e00\u4e2a\u5728 $d$ \u7ef4\u5ea6\u4e0a\u6709 $d+2$ \u4e2a\u65b9\u7a0b\u7684\u95ee\u9898\uff0c\u6211\u4eec\u9700\u8981\u544a\u8bc9\u51fd\u6570\u57fa\u7c7b\u6b63\u786e\u7684\u5206\u91cf\u6570\u91cf\u3002\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// \u5c31\u5b9e\u9645\u5b9e\u73b0\u7684\u51fd\u6570\u800c\u8a00\uff0c\u5206\u6790\u6027\u6d4b\u8bd5\u6848\u4f8b\u662f\u4e00\u4e2a\u7b49\u71b5\u6da1\u65cb\u6848\u4f8b\uff08\u4f8b\u5982\u53c2\u89c1Hesthaven\u548cWarburton\u7684\u4e66\uff0c\u7b2c209\u9875\u7b2c6.6\u8282\u4e2d\u7684\u4f8b6.1\uff09\uff0c\u5b83\u6ee1\u8db3\u6b27\u62c9\u65b9\u7a0b\uff0c\u53f3\u4fa7\u7684\u529b\u9879\u4e3a\u96f6\u3002\u8003\u8651\u5230\u8fd9\u4e2a\u5b9a\u4e49\uff0c\u6211\u4eec\u8fd4\u56de\u5bc6\u5ea6\u3001\u52a8\u91cf\u6216\u80fd\u91cf\uff0c\u8fd9\u53d6\u51b3\u4e8e\u6240\u8981\u6c42\u7684\u6210\u5206\u3002\u8bf7\u6ce8\u610f\uff0c\u5bc6\u5ea6\u7684\u539f\u59cb\u5b9a\u4e49\u6d89\u53ca\u4e00\u4e9b\u8868\u8fbe\u5f0f\u7684 $\\frac{1}{\\gamma -1}$ -\u6b21\u65b9\u3002\u7531\u4e8e `std::pow()` \u5728\u67d0\u4e9b\u7cfb\u7edf\u4e0a\u7684\u5b9e\u73b0\u76f8\u5f53\u6162\uff0c\u6211\u4eec\u7528\u5bf9\u6570\u548c\u6307\u6570\uff08\u4ee52\u4e3a\u5e95\uff09\u6765\u4ee3\u66ff\u5b83\uff0c\u8fd9\u5728\u6570\u5b66\u4e0a\u662f\u7b49\u4ef7\u7684\uff0c\u4f46\u901a\u5e38\u4f18\u5316\u5f97\u66f4\u597d\u3002\u4e0e `std::pow()`, \u76f8\u6bd4\uff0c\u5bf9\u4e8e\u975e\u5e38\u5c0f\u7684\u6570\u5b57\uff0c\u8fd9\u4e2a\u516c\u5f0f\u53ef\u80fd\u4f1a\u5728\u6700\u540e\u4e00\u4f4d\u6570\u5b57\u4e0a\u5931\u53bb\u51c6\u786e\u6027\uff0c\u4f46\u6211\u4eec\u8fd8\u662f\u5f88\u9ad8\u5174\uff0c\u56e0\u4e3a\u5c0f\u6570\u5b57\u6620\u5c04\u4e3a\u63a5\u8fd11\u7684\u6570\u636e\u3002\n\n// \u5bf9\u4e8e\u901a\u9053\u6d4b\u8bd5\u6848\u4f8b\uff0c\u6211\u4eec\u7b80\u5355\u5730\u9009\u62e9\u5bc6\u5ea6\u4e3a1\uff0c $x$ \u65b9\u5411\u7684\u901f\u5ea6\u4e3a0.4\uff0c\u5176\u4ed6\u65b9\u5411\u7684\u901f\u5ea6\u4e3a0\uff0c\u4ee5\u53ca\u5bf9\u5e94\u4e8e\u80cc\u666f\u901f\u5ea6\u573a\u6d4b\u91cf\u76841.3\u58f0\u901f\u7684\u80fd\u91cf\uff0c\u6839\u636e\u5173\u7cfb $E = \\frac{c^2}{\\gamma (\\gamma -1)} + \\frac 12 \\rho \\|u\\|^2$ \u8ba1\u7b97\u5f97\u51fa\u3002\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// \u63a5\u4e0b\u6765\u7684\u51e0\u884c\u5b9e\u73b0\u4e86\u4e00\u4e9b\u4f4e\u5b58\u50a8\u91cf\u7684Runge--Kutta\u65b9\u6cd5\u7684\u53d8\u4f53\u3002\u8fd9\u4e9b\u65b9\u6cd5\u6709\u7279\u5b9a\u7684\u5e03\u5f7b\u8868\uff0c\u7cfb\u6570\u4e3a $b_i$ \u548c $a_i$ \uff0c\u5982\u4ecb\u7ecd\u4e2d\u6240\u793a\u3002\u5982\u540cRunge--Kutta\u65b9\u6cd5\u7684\u60ef\u4f8b\uff0c\u6211\u4eec\u53ef\u4ee5\u4ece\u8fd9\u4e9b\u7cfb\u6570\u4e2d\u63a8\u5bfc\u51fa\u65f6\u95f4\u6b65\u9aa4 $c_i = \\sum_{j=1}^{i-2} b_i + a_{i-1}$ \u3002\u8fd9\u79cd\u65b9\u6848\u7684\u4e3b\u8981\u4f18\u70b9\u662f\u6bcf\u4e2a\u9636\u6bb5\u53ea\u9700\u8981\u4e24\u4e2a\u5411\u91cf\uff0c\u5373\u89e3\u7684\u7d2f\u79ef\u90e8\u5206 $\\mathbf{w}$ \uff08\u5728\u6700\u540e\u4e00\u4e2a\u9636\u6bb5\u540e\u7684\u65b0\u65f6\u95f4 $t^{n+1}$ \u4fdd\u6301\u89e3 $\\mathbf{w}^{n+1}$ \uff09\uff0c\u5728\u5404\u9636\u6bb5\u88ab\u8bc4\u4f30\u7684\u66f4\u65b0\u5411\u91cf $\\mathbf{r}_i$ \uff0c\u52a0\u4e0a\u4e00\u4e2a\u5411\u91cf $\\mathbf{k}_i$ \u6765\u4fdd\u6301\u7b97\u5b50\u8bc4\u4f30\u3002\u8fd9\u6837\u7684Runge--Kutta\u8bbe\u7f6e\u51cf\u5c11\u4e86\u5185\u5b58\u5b58\u50a8\u548c\u5185\u5b58\u8bbf\u95ee\u3002\u7531\u4e8e\u5185\u5b58\u5e26\u5bbd\u901a\u5e38\u662f\u73b0\u4ee3\u786c\u4ef6\u4e0a\u7684\u6027\u80fd\u9650\u5236\u56e0\u7d20\uff0c\u5f53\u5fae\u5206\u7b97\u5b50\u7684\u8bc4\u4f30\u5f97\u5230\u5f88\u597d\u7684\u4f18\u5316\u65f6\uff0c\u6027\u80fd\u53ef\u4ee5\u6bd4\u6807\u51c6\u7684\u65f6\u95f4\u79ef\u5206\u5668\u5f97\u5230\u6539\u5584\u3002\u8003\u8651\u5230\u4f20\u7edf\u7684Runge--Kutta\u65b9\u6848\u53ef\u80fd\u5141\u8bb8\u7a0d\u5927\u7684\u65f6\u95f4\u6b65\u957f\uff0c\u56e0\u4e3a\u66f4\u591a\u7684\u81ea\u7531\u53c2\u6570\u53ef\u4ee5\u83b7\u5f97\u66f4\u597d\u7684\u7a33\u5b9a\u6027\uff0c\u8fd9\u4e00\u70b9\u4e5f\u662f\u771f\u5b9e\u7684\u3002\n\n// \u5728\u672c\u6559\u7a0b\u4e2d\uff0c\u6211\u4eec\u96c6\u4e2d\u8ba8\u8bbaKennedy, Carpenter\u548cLewis(2000)\u6587\u7ae0\u4e2d\u5b9a\u4e49\u7684\u4f4e\u5b58\u50a8\u65b9\u6848\u7684\u51e0\u4e2a\u53d8\u4f53\uff0c\u4ee5\u53caTselios\u548cSimos(2007)\u63cf\u8ff0\u7684\u4e00\u4e2a\u53d8\u4f53\u3002\u8fd8\u6709\u4e00\u5927\u7cfb\u5217\u7684\u5176\u4ed6\u65b9\u6848\uff0c\u53ef\u4ee5\u901a\u8fc7\u989d\u5916\u7684\u7cfb\u6570\u96c6\u6216\u7a0d\u5fae\u4e0d\u540c\u7684\u66f4\u65b0\u516c\u5f0f\u6765\u89e3\u51b3\u3002\n\n// \u6211\u4eec\u4e3a\u8fd9\u56db\u79cd\u79ef\u5206\u5668\u5b9a\u4e49\u4e86\u4e00\u4e2a\u5355\u4e00\u7684\u7c7b\uff0c\u7528\u4e0a\u8ff0\u7684\u679a\u4e3e\u6765\u533a\u5206\u3002\u5bf9\u6bcf\u4e2a\u65b9\u6848\uff0c\u6211\u4eec\u518d\u5c06 $b_i$ \u548c $a_i$ \u7684\u5411\u91cf\u586b\u5145\u5230\u7c7b\u4e2d\u7684\u7ed9\u5b9a\u53d8\u91cf\u3002\n\n  class LowStorageRungeKuttaIntegrator \n  { \n  public: \n    LowStorageRungeKuttaIntegrator(const LowStorageRungeKuttaScheme scheme) \n    { \n      TimeStepping::runge_kutta_method lsrk; \n\n// \u9996\u5148\u662fKennedy\u7b49\u4eba\uff082000\uff09\u63d0\u51fa\u7684\u4e09\u9636\u65b9\u6848\u3002\u867d\u7136\u5b83\u7684\u7a33\u5b9a\u533a\u57df\u6bd4\u5176\u4ed6\u65b9\u6848\u5c0f\u5f97\u591a\uff0c\u4f46\u5b83\u53ea\u6d89\u53ca\u4e09\u4e2a\u9636\u6bb5\uff0c\u6240\u4ee5\u5728\u6bcf\u4e2a\u9636\u6bb5\u7684\u5de5\u4f5c\u65b9\u9762\u5f88\u6709\u7ade\u4e89\u529b\u3002\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// \u4e0b\u4e00\u4e2a\u65b9\u6848\u662f\u56db\u9636\u7684\u4e94\u7ea7\u65b9\u6848\uff0c\u540c\u6837\u5728Kennedy\u7b49\u4eba\uff082000\uff09\u7684\u8bba\u6587\u4e2d\u5b9a\u4e49\u3002\n\n          case stage_5_order_4: \n            { \n              lsrk = TimeStepping::LOW_STORAGE_RK_STAGE5_ORDER4; \n              break; \n            } \n\n// \u4e0b\u9762\u8fd9\u4e2a\u4e03\u7ea7\u548c\u56db\u9636\u7684\u65b9\u6848\u5df2\u7ecf\u660e\u786e\u5730\u63a8\u5bfc\u51fa\u7528\u4e8e\u58f0\u5b66\u95ee\u9898\u3002\u5b83\u5728\u56db\u9636\u65b9\u6848\u4e2d\u517c\u987e\u4e86\u865a\u7279\u5f81\u503c\u7684\u7cbe\u5ea6\uff0c\u5e76\u7ed3\u5408\u4e86\u4e00\u4e2a\u5927\u7684\u7a33\u5b9a\u533a\u57df\u3002\u7531\u4e8eDG\u65b9\u6848\u5728\u6700\u9ad8\u9891\u7387\u4e4b\u95f4\u662f\u8017\u6563\u7684\uff0c\u8fd9\u4e0d\u4e00\u5b9a\u8f6c\u5316\u4e3a\u6bcf\u7ea7\u53ef\u80fd\u7684\u6700\u9ad8\u65f6\u95f4\u6b65\u957f\u3002\u5728\u672c\u6559\u7a0b\u65b9\u6848\u7684\u80cc\u666f\u4e0b\uff0c\u6570\u503c\u901a\u91cf\u5728\u8017\u6563\u4e2d\u8d77\u7740\u81f3\u5173\u91cd\u8981\u7684\u4f5c\u7528\uff0c\u56e0\u6b64\u4e5f\u662f\u6700\u5927\u7684\u7a33\u5b9a\u65f6\u95f4\u6b65\u957f\u3002\u5bf9\u4e8e\u4fee\u6539\u540e\u7684Lax--Friedrichs\u901a\u91cf\uff0c\u5982\u679c\u53ea\u8003\u8651\u7a33\u5b9a\u6027\uff0c\u8be5\u65b9\u6848\u5728\u6bcf\u7ea7\u6b65\u957f\u65b9\u9762\u4e0e`stage_5_order_4`\u65b9\u6848\u76f8\u4f3c\uff0c\u4f46\u5bf9\u4e8eHLL\u901a\u91cf\u6765\u8bf4\uff0c\u6548\u7387\u7a0d\u4f4e\u3002\n\n          case stage_7_order_4: \n            { \n              lsrk = TimeStepping::LOW_STORAGE_RK_STAGE7_ORDER4; \n              break; \n            } \n\n// \u8fd9\u91cc\u5305\u62ec\u7684\u6700\u540e\u4e00\u4e2a\u65b9\u6848\u662fKennedy\u7b49\u4eba\uff082000\uff09\u7684\u4e94\u9636\u4e5d\u7ea7\u65b9\u6848\u3002\u5b83\u662f\u8fd9\u91cc\u4f7f\u7528\u7684\u65b9\u6848\u4e2d\u6700\u7cbe\u786e\u7684\uff0c\u4f46\u662f\u8f83\u9ad8\u7684\u7cbe\u5ea6\u727a\u7272\u4e86\u4e00\u4e9b\u7a33\u5b9a\u6027\uff0c\u6240\u4ee5\u6bcf\u7ea7\u7684\u5f52\u4e00\u5316\u6b65\u957f\u6bd4\u56db\u9636\u65b9\u6848\u8981\u5c0f\u3002\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// \u65f6\u95f4\u79ef\u5206\u5668\u7684\u4e3b\u8981\u529f\u80fd\u662f\u901a\u8fc7\u9636\u6bb5\uff0c\u8bc4\u4f30\u7b97\u5b50\uff0c\u4e3a\u4e0b\u4e00\u6b21\u8bc4\u4f30\u51c6\u5907  $\\mathbf{r}_i$  \u77e2\u91cf\uff0c\u5e76\u66f4\u65b0\u89e3\u51b3\u65b9\u6848\u77e2\u91cf  $\\mathbf{w}$  \u3002\u6211\u4eec\u628a\u5de5\u4f5c\u4ea4\u7ed9\u6240\u6d89\u53ca\u7684`pde_operator`\uff0c\u4ee5\u4fbf\u80fd\u591f\u628aRunge--Kutta\u8bbe\u7f6e\u7684\u77e2\u91cf\u64cd\u4f5c\u4e0e\u5fae\u5206\u7b97\u5b50\u7684\u8bc4\u4f30\u5408\u5e76\u8d77\u6765\uff0c\u4ee5\u83b7\u5f97\u66f4\u597d\u7684\u6027\u80fd\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u8fd9\u91cc\u6240\u505a\u7684\u5c31\u662f\u59d4\u6258\u77e2\u91cf\u548c\u7cfb\u6570\u3002\n\n// \u6211\u4eec\u5355\u72ec\u8c03\u7528\u7b2c\u4e00\u9636\u6bb5\u7684\u7b97\u5b50\uff0c\u56e0\u4e3a\u6211\u4eec\u9700\u8981\u7a0d\u5fae\u4fee\u6539\u4e00\u4e0b\u90a3\u91cc\u7684\u53c2\u6570\u3002\u6211\u4eec\u4ece\u65e7\u7684\u89e3\u51b3\u65b9\u6848 $\\mathbf{w}^n$ \u800c\u4e0d\u662f $\\mathbf r_i$ \u5411\u91cf\u4e2d\u8bc4\u4f30\u89e3\u51b3\u65b9\u6848\uff0c\u6240\u4ee5\u7b2c\u4e00\u4e2a\u53c2\u6570\u662f`solution`\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u8ba9\u9636\u6bb5\u5411\u91cf $\\mathbf{r}_i$ \u4e5f\u6301\u6709\u8bc4\u4f30\u7684\u4e34\u65f6\u7ed3\u679c\uff0c\u56e0\u4e3a\u5b83\u5728\u5176\u4ed6\u60c5\u51b5\u4e0b\u4e0d\u4f1a\u88ab\u4f7f\u7528\u3002\u5bf9\u4e8e\u6240\u6709\u540e\u7eed\u9636\u6bb5\uff0c\u6211\u4eec\u4f7f\u7528\u5411\u91cf`vec_ki`\u4f5c\u4e3a\u7b2c\u4e8c\u4e2a\u5411\u91cf\u53c2\u6570\u6765\u5b58\u50a8\u8fd0\u7b97\u7b26\u7684\u6c42\u503c\u7ed3\u679c\u3002\u6700\u540e\uff0c\u5f53\u6211\u4eec\u5230\u4e86\u6700\u540e\u4e00\u4e2a\u9636\u6bb5\uff0c\u6211\u4eec\u5fc5\u987b\u8df3\u8fc7\u5bf9\u5411\u91cf $\\mathbf{r}_{s+1}$ \u7684\u8ba1\u7b97\uff0c\u56e0\u4e3a\u6ca1\u6709\u7cfb\u6570 $a_s$ \u53ef\u7528\uff08\u4e5f\u4e0d\u4f1a\u7528\u5230\uff09\u3002\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// \u5728\u4e0b\u9762\u7684\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u5b9e\u73b0\u4e86\u4e0e\u6b27\u62c9\u65b9\u7a0b\u6709\u5173\u7684\u5404\u79cd\u7279\u5b9a\u95ee\u9898\u7684\u8fd0\u7b97\u3002\u6bcf\u4e2a\u51fd\u6570\u90fd\u4f5c\u7528\u4e8e\u6211\u4eec\u5728\u89e3\u5411\u91cf\u4e2d\u6301\u6709\u7684\u5b88\u6052\u53d8\u91cf\u5411\u91cf $[\\rho, \\rho\\mathbf{u}, E]$ \uff0c\u5e76\u8ba1\u7b97\u5404\u79cd\u6d3e\u751f\u91cf\u3002\n\n// \u9996\u5148\u662f\u901f\u5ea6\u7684\u8ba1\u7b97\uff0c\u6211\u4eec\u4ece\u52a8\u91cf\u53d8\u91cf $\\rho \\mathbf{u}$ \u9664\u4ee5 $\\rho$ \u5f97\u51fa\u3002\u8fd9\u91cc\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0c\u6211\u4eec\u7528\u5173\u952e\u5b57`DEAL_II_ALWAYS_INLINE`\u6765\u88c5\u9970\u6240\u6709\u8fd9\u4e9b\u51fd\u6570\u3002\u8fd9\u662f\u4e00\u4e2a\u7279\u6b8a\u7684\u5b8f\uff0c\u6620\u5c04\u5230\u4e00\u4e2a\u7f16\u8bd1\u5668\u4e13\u7528\u7684\u5173\u952e\u5b57\uff0c\u544a\u8bc9\u7f16\u8bd1\u5668\u6c38\u8fdc\u4e0d\u8981\u4e3a\u8fd9\u4e9b\u51fd\u6570\u521b\u5efa\u4e00\u4e2a\u51fd\u6570\u8c03\u7528\uff0c\u800c\u662f\u5c06\u5b9e\u73b0<a href=\"https:en.wikipedia.org/wiki/Inline_function\">inline</a>\u79fb\u5230\u5b83\u4eec\u88ab\u8c03\u7528\u7684\u5730\u65b9\u3002\u8fd9\u5bf9\u6027\u80fd\u81f3\u5173\u91cd\u8981\uff0c\u56e0\u4e3a\u6211\u4eec\u5bf9\u5176\u4e2d\u4e00\u4e9b\u51fd\u6570\u7684\u8c03\u7528\u8fbe\u5230\u4e86\u51e0\u767e\u4e07\u751a\u81f3\u51e0\u5341\u4ebf\u6b21\u3002\u4f8b\u5982\uff0c\u6211\u4eec\u65e2\u4f7f\u7528\u901f\u5ea6\u6765\u8ba1\u7b97\u901a\u91cf\uff0c\u4e5f\u4f7f\u7528\u901f\u5ea6\u6765\u8ba1\u7b97\u538b\u529b\uff0c\u800c\u8fd9\u4e24\u4e2a\u5730\u65b9\u90fd\u8981\u5728\u6bcf\u4e2a\u5355\u5143\u7684\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u8fdb\u884c\u8bc4\u4f30\u3002\u786e\u4fdd\u8fd9\u4e9b\u51fd\u6570\u662f\u5185\u8054\u7684\uff0c\u4e0d\u4ec5\u53ef\u4ee5\u786e\u4fdd\u5904\u7406\u5668\u4e0d\u5fc5\u6267\u884c\u8df3\u8f6c\u6307\u4ee4\u8fdb\u5165\u51fd\u6570\uff08\u4ee5\u53ca\u76f8\u5e94\u7684\u8fd4\u56de\u8df3\u8f6c\uff09\uff0c\u800c\u4e14\u7f16\u8bd1\u5668\u53ef\u4ee5\u5728\u8c03\u7528\u51fd\u6570\u7684\u5730\u65b9\u4e4b\u540e\u7684\u4ee3\u7801\u4e2d\u91cd\u65b0\u4f7f\u7528\u4e00\u4e2a\u51fd\u6570\u7684\u4e0a\u4e0b\u6587\u7684\u4e2d\u95f4\u4fe1\u606f\u3002(\u6211\u4eec\u6ce8\u610f\u5230\uff0c\u7f16\u8bd1\u5668\u901a\u5e38\u5f88\u5584\u4e8e\u81ea\u5df1\u627e\u51fa\u54ea\u4e9b\u51fd\u6570\u8981\u5185\u8054\u3002\u8fd9\u91cc\u6709\u4e00\u4e2a\u5730\u65b9\uff0c\u7f16\u8bd1\u5668\u53ef\u80fd\u662f\u81ea\u5df1\u60f3\u51fa\u6765\u7684\uff0c\u4e5f\u53ef\u80fd\u4e0d\u662f\uff0c\u4f46\u6211\u4eec\u53ef\u4ee5\u80af\u5b9a\u7684\u662f\uff0c\u5185\u8054\u662f\u4e00\u79cd\u80dc\u5229\u3002)\n\n// \u6211\u4eec\u5e94\u7528\u7684\u53e6\u4e00\u4e2a\u6280\u5de7\u662f\u4e3a\u53cd\u5bc6\u5ea6\u8bbe\u7f6e\u4e00\u4e2a\u5355\u72ec\u7684\u53d8\u91cf  $\\frac{1}{\\rho}$  \u3002\u8fd9\u4f7f\u5f97\u7f16\u8bd1\u5668\u53ea\u5bf9\u901a\u91cf\u8fdb\u884c\u4e00\u6b21\u9664\u6cd5\uff0c\u5c3d\u7ba1\u9664\u6cd5\u5728\u591a\u4e2a\u5730\u65b9\u4f7f\u7528\u3002\u7531\u4e8e\u9664\u6cd5\u7684\u8d39\u7528\u5927\u7ea6\u662f\u4e58\u6cd5\u6216\u52a0\u6cd5\u768410\u523020\u500d\uff0c\u907f\u514d\u591a\u4f59\u7684\u9664\u6cd5\u5bf9\u6027\u80fd\u81f3\u5173\u91cd\u8981\u3002\u6211\u4eec\u6ce8\u610f\u5230\uff0c\u7531\u4e8e\u56db\u820d\u4e94\u5165\u7684\u5f71\u54cd\uff0c\u5728\u6d6e\u70b9\u8fd0\u7b97\u4e2d\uff0c\u5148\u53d6\u53cd\u6570\uff0c\u540e\u4e0e\u4e4b\u76f8\u4e58\u5e76\u4e0d\u7b49\u540c\u4e8e\u9664\u6cd5\uff0c\u6240\u4ee5\u7f16\u8bd1\u5668\u4e0d\u5141\u8bb8\u7528\u6807\u51c6\u7684\u4f18\u5316\u6807\u5fd7\u6765\u4ea4\u6362\u4e00\u79cd\u65b9\u5f0f\u3002\u7136\u800c\uff0c\u4ee5\u6b63\u786e\u7684\u65b9\u5f0f\u7f16\u5199\u4ee3\u7801\u4e5f\u4e0d\u662f\u7279\u522b\u56f0\u96be\u3002\n\n// \u603b\u800c\u8a00\u4e4b\uff0c\u6240\u9009\u62e9\u7684\u603b\u662f\u5185\u8054\u548c\u4ed4\u7ec6\u5b9a\u4e49\u6602\u8d35\u7684\u7b97\u672f\u8fd0\u7b97\u7684\u7b56\u7565\u4f7f\u6211\u4eec\u80fd\u591f\u5199\u51fa\u7d27\u51d1\u7684\u4ee3\u7801\uff0c\u800c\u4e0d\u9700\u8981\u5c06\u6240\u6709\u7684\u4e2d\u95f4\u7ed3\u679c\u4f20\u9012\u51fa\u53bb\uff0c\u5c3d\u7ba1\u8981\u786e\u4fdd\u4ee3\u7801\u6620\u5c04\u5230\u4f18\u79c0\u7684\u673a\u5668\u7801\u3002\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// \u4e0b\u4e00\u4e2a\u51fd\u6570\u4ece\u4fdd\u5b88\u53d8\u91cf\u7684\u77e2\u91cf\u4e2d\u8ba1\u7b97\u538b\u529b\uff0c\u4f7f\u7528\u516c\u5f0f  $p = (\\gamma - 1) \\left(E - \\frac 12 \\rho \\mathbf{u}\\cdot \\mathbf{u}\\right)$  \u3002\u5982\u4e0a\u6240\u8ff0\uff0c\u6211\u4eec\u4f7f\u7528\u6765\u81ea`euler_velocity()`\u51fd\u6570\u7684\u901f\u5ea6\u3002\u6ce8\u610f\uff0c\u6211\u4eec\u9700\u8981\u5728\u8fd9\u91cc\u6307\u5b9a\u7b2c\u4e00\u4e2a\u6a21\u677f\u53c2\u6570`dim`\uff0c\u56e0\u4e3a\u7f16\u8bd1\u5668\u65e0\u6cd5\u4ece\u5f20\u91cf\u7684\u53c2\u6570\u4e2d\u63a8\u5bfc\u51fa\u5b83\uff0c\u800c\u7b2c\u4e8c\u4e2a\u53c2\u6570\uff08\u6570\u5b57\u7c7b\u578b\uff09\u53ef\u4ee5\u81ea\u52a8\u63a8\u5bfc\u51fa\u6765\u3002\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// \u8fd9\u91cc\u662f\u6b27\u62c9\u901a\u91cf\u51fd\u6570\u7684\u5b9a\u4e49\uff0c\u4e5f\u5c31\u662f\u5b9e\u9645\u65b9\u7a0b\u7684\u5b9a\u4e49\u3002\u8003\u8651\u5230\u901f\u5ea6\u548c\u538b\u529b\uff08\u7f16\u8bd1\u5668\u7684\u4f18\u5316\u5c06\u786e\u4fdd\u53ea\u505a\u4e00\u6b21\uff09\uff0c\u8003\u8651\u5230\u4ecb\u7ecd\u4e2d\u6240\u8bf4\u7684\u65b9\u7a0b\uff0c\u8fd9\u662f\u76f4\u622a\u4e86\u5f53\u7684\u3002\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// \u63a5\u4e0b\u6765\u7684\u8fd9\u4e2a\u51fd\u6570\u662f\u4e00\u4e2a\u7b80\u5316\u6570\u503c\u901a\u91cf\u5b9e\u73b0\u7684\u52a9\u624b\uff0c\u5b83\u5b9e\u73b0\u4e86\u4e00\u4e2a\u5f20\u91cf\u7684\u5f20\u91cf\uff08\u5177\u6709\u5927\u5c0f\u4e3a`dim + 2`\u7684\u975e\u6807\u51c6\u5916\u7ef4\uff0c\u6240\u4ee5deal.II\u7684\u5f20\u91cf\u7c7b\u63d0\u4f9b\u7684\u6807\u51c6\u91cd\u8f7d\u5728\u6b64\u4e0d\u9002\u7528\uff09\u4e0e\u53e6\u4e00\u4e2a\u76f8\u540c\u5185\u7ef4\u7684\u5f20\u91cf\u7684\u4f5c\u7528\uff0c\u5373\u4e00\u4e2a\u77e9\u9635-\u5411\u91cf\u79ef\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u5b9e\u73b0\u4e86\u6570\u503c\u901a\u91cf\uff08\u9ece\u66fc\u6c42\u89e3\u5668\uff09\u3002\u5b83\u4ece\u4e00\u4e2a\u754c\u9762\u7684\u4e24\u8fb9\u83b7\u5f97\u72b6\u6001\uff0c\u5e76\u83b7\u5f97\u6cd5\u5411\u91cf\uff0c\u4ece\u89e3\u7684\u4e00\u8fb9  $\\mathbf{w}^-$  \u5411\u89e3  $\\mathbf{w}^+$  \u7684\u65b9\u5411\u3002\u5728\u4f9d\u8d56\u7247\u65ad\u6052\u5b9a\u6570\u636e\u7684\u6709\u9650\u4f53\u79ef\u65b9\u6cd5\u4e2d\uff0c\u6570\u503c\u901a\u91cf\u662f\u6838\u5fc3\u6210\u5206\uff0c\u56e0\u4e3a\u5b83\u662f\u552f\u4e00\u8f93\u5165\u7269\u7406\u4fe1\u606f\u7684\u5730\u65b9\u3002\u5728DG\u65b9\u6cd5\u4e2d\uff0c\u7531\u4e8e\u5143\u7d20\u5185\u90e8\u7684\u591a\u9879\u5f0f\u548c\u90a3\u91cc\u4f7f\u7528\u7684\u7269\u7406\u901a\u91cf\uff0c\u6570\u503c\u901a\u91cf\u5c31\u4e0d\u90a3\u4e48\u6838\u5fc3\u4e86\u3002\u7531\u4e8e\u5728\u8fde\u7eed\u89e3\u7684\u6781\u9650\u4e2d\uff0c\u4e24\u8fb9\u7684\u6570\u503c\u4e00\u81f4\u7684\u9ad8\u9636\u63d2\u503c\uff0c\u6570\u503c\u901a\u91cf\u53ef\u4ee5\u88ab\u770b\u4f5c\u662f\u5bf9\u4e24\u8fb9\u89e3\u7684\u8df3\u8dc3\u7684\u63a7\u5236\uff0c\u4ee5\u5f31\u5316\u8fde\u7eed\u6027\u3002\u5fc5\u987b\u8ba4\u8bc6\u5230\uff0c\u5728\u5b58\u5728\u51b2\u51fb\u7684\u60c5\u51b5\u4e0b\uff0c\u4ec5\u9760\u6570\u503c\u901a\u91cf\u662f\u65e0\u6cd5\u7a33\u5b9a\u9ad8\u9636DG\u65b9\u6cd5\u7684\uff0c\u56e0\u6b64\u4efb\u4f55DG\u65b9\u6cd5\u90fd\u5fc5\u987b\u4e0e\u8fdb\u4e00\u6b65\u7684\u51b2\u51fb\u6355\u6349\u6280\u672f\u76f8\u7ed3\u5408\uff0c\u4ee5\u5904\u7406\u8fd9\u4e9b\u60c5\u51b5\u3002\u5728\u672c\u6559\u7a0b\u4e2d\uff0c\u6211\u4eec\u5c06\u91cd\u70b9\u8ba8\u8bba\u6b27\u62c9\u65b9\u7a0b\u5728\u6ca1\u6709\u5f3a\u4e0d\u8fde\u7eed\u7684\u4e9a\u58f0\u901f\u4f53\u7cfb\u4e2d\u7684\u6ce2\u72b6\u89e3\uff0c\u6211\u4eec\u7684\u57fa\u672c\u65b9\u6848\u5df2\u7ecf\u8db3\u591f\u4e86\u3002\n\n// \u5c3d\u7ba1\u5982\u6b64\uff0c\u6570\u503c\u901a\u91cf\u5bf9\u6574\u4e2a\u65b9\u6848\u7684\u6570\u503c\u8017\u6563\u8d77\u7740\u51b3\u5b9a\u6027\u4f5c\u7528\uff0c\u5e76\u5f71\u54cd\u5230\u663e\u5f0fRunge-Kutta\u65b9\u6cd5\u7684\u53ef\u63a5\u53d7\u7684\u65f6\u95f4\u6b65\u957f\u3002\u6211\u4eec\u8003\u8651\u4e24\u79cd\u9009\u62e9\uff0c\u4e00\u79cd\u662f\u6539\u826f\u7684Lax-Friedrichs\u65b9\u6848\uff0c\u53e6\u4e00\u79cd\u662f\u5e7f\u6cdb\u4f7f\u7528\u7684Harten-Lax-van Leer\uff08HLL\uff09\u901a\u91cf\u3002\u5bf9\u4e8e\u8fd9\u4e24\u79cd\u65b9\u6848\uff0c\u6211\u4eec\u9996\u5148\u9700\u8981\u5f97\u5230\u754c\u9762\u4e24\u8fb9\u7684\u901f\u5ea6\u548c\u538b\u529b\uff0c\u5e76\u8bc4\u4f30\u7269\u7406\u6b27\u62c9\u901a\u91cf\u3002\n\n// \u5bf9\u4e8e\u5c40\u90e8Lax--Friedrichs\u901a\u91cf\uff0c\u5176\u5b9a\u4e49\u662f $\\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^-}$  \uff0c\u5176\u4e2d\u56e0\u5b50 $\\lambda =\n//  \\max\\left(\\|\\mathbf{u}^-\\|+c^-, \\|\\mathbf{u}^+\\|+c^+\\right)$ \u7ed9\u51fa\u4e86\u6700\u5927\u6ce2\u901f\uff0c $c = \\sqrt{\\gamma p / \\rho}$ \u662f\u97f3\u901f\u3002\u5728\u8fd9\u91cc\uff0c\u8003\u8651\u5230\u901a\u91cf\u5bf9\u89e3\u7684\u5f71\u54cd\u5f88\u5c0f\uff0c\u4e3a\u4e86\u8ba1\u7b97\u6548\u7387\u7684\u539f\u56e0\uff0c\u6211\u4eec\u9009\u62e9\u4e86\u8be5\u8868\u8fbe\u5f0f\u7684\u4e24\u4e2a\u4fee\u6539\u3002\u5bf9\u4e8e\u4e0a\u8ff0\u56e0\u5b50 $\\lambda$ \u7684\u5b9a\u4e49\uff0c\u6211\u4eec\u9700\u8981\u53d6\u56db\u4e2a\u5e73\u65b9\u6839\uff0c\u4e24\u4e2a\u7528\u4e8e\u4e24\u4e2a\u901f\u5ea6\u89c4\u8303\uff0c\u4e24\u4e2a\u7528\u4e8e\u4e24\u4fa7\u7684\u58f0\u901f\u3002\u56e0\u6b64\uff0c\u7b2c\u4e00\u4e2a\u4fee\u6539\u662f\u5b81\u53ef\u4f7f\u7528 $\\sqrt{\\|\\mathbf{u}\\|^2+c^2}$ \u4f5c\u4e3a\u6700\u5927\u901f\u5ea6\u7684\u4f30\u8ba1\uff08\u5982\u4ecb\u7ecd\u4e2d\u6240\u793a\uff0c\u5b83\u4e0e\u5b9e\u9645\u6700\u5927\u901f\u5ea6\u6700\u591a\u76f8\u5dee2\u500d\uff09\u3002\u8fd9\u4f7f\u6211\u4eec\u80fd\u591f\u4ece\u6700\u5927\u901f\u5ea6\u4e2d\u63d0\u53d6\u5e73\u65b9\u6839\uff0c\u5e76\u4e14\u53ea\u9700\u8fdb\u884c\u4e00\u6b21\u5e73\u65b9\u6839\u8ba1\u7b97\u5c31\u53ef\u4ee5\u4e86\u3002\u7b2c\u4e8c\u4e2a\u4fee\u6539\u662f\u8fdb\u4e00\u6b65\u653e\u5bbd\u53c2\u6570 $\\lambda$ --\u5b83\u8d8a\u5c0f\uff0c\u8017\u6563\u7cfb\u6570\u5c31\u8d8a\u5c0f\uff08\u4e0e $\\mathbf{w}$ \u7684\u8df3\u8dc3\u76f8\u4e58\uff0c\u6700\u7ec8\u53ef\u80fd\u5bfc\u81f4\u8017\u6563\u53d8\u5c0f\u6216\u53d8\u5927\uff09\u3002\u8fd9\u4f7f\u5f97\u6211\u4eec\u53ef\u4ee5\u7528\u66f4\u5927\u7684\u65f6\u95f4\u6b65\u957f\u5c06\u9891\u8c31\u7eb3\u5165\u663e\u5f0fRunge--Kutta\u79ef\u5206\u5668\u7684\u7a33\u5b9a\u533a\u57df\u3002\u7136\u800c\uff0c\u6211\u4eec\u4e0d\u80fd\u4f7f\u8017\u6563\u592a\u5c0f\uff0c\u56e0\u4e3a\u5426\u5219\u5047\u60f3\u7684\u7279\u5f81\u503c\u4f1a\u8d8a\u6765\u8d8a\u5927\u3002\u6700\u540e\uff0c\u76ee\u524d\u7684\u4fdd\u5b88\u516c\u5f0f\u5728 $\\lambda\\to 0$ \u7684\u6781\u9650\u4e2d\u4e0d\u662f\u80fd\u91cf\u7a33\u5b9a\u7684\uff0c\u56e0\u4e3a\u5b83\u4e0d\u662f\u504f\u659c\u5bf9\u79f0\u7684\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\u9700\u8981\u989d\u5916\u7684\u63aa\u65bd\uff0c\u5982\u5206\u88c2\u5f62\u5f0f\u7684DG\u65b9\u6848\u3002\n\n// \u5bf9\u4e8eHLL\u901a\u91cf\uff0c\u6211\u4eec\u9075\u5faa\u6587\u732e\u4e2d\u7684\u516c\u5f0f\uff0c\u901a\u8fc7\u4e00\u4e2a\u53c2\u6570 $s$ \u5f15\u5165Lax--Friedrichs\u7684\u4e24\u4e2a\u72b6\u6001\u7684\u989d\u5916\u52a0\u6743\u3002\u5b83\u662f\u7531\u6b27\u62c9\u65b9\u7a0b\u7684\u7269\u7406\u4f20\u8f93\u65b9\u5411\u5f97\u51fa\u7684\uff0c\u4ee5\u5f53\u524d\u7684\u901f\u5ea6\u65b9\u5411\u548c\u58f0\u901f\u4e3a\u51c6\u3002\u5bf9\u4e8e\u901f\u5ea6\uff0c\u6211\u4eec\u5728\u6b64\u9009\u62e9\u4e00\u4e2a\u7b80\u5355\u7684\u7b97\u672f\u5e73\u5747\u6570\uff0c\u8fd9\u5bf9\u5371\u9669\u60c5\u51b5\u548c\u6750\u6599\u53c2\u6570\u7684\u9002\u5ea6\u8df3\u8dc3\u662f\u8db3\u591f\u7684\u3002\n\n// \u7531\u4e8e\u6570\u503c\u901a\u91cf\u5728\u5f31\u5f62\u5f0f\u4e0b\u662f\u4e0e\u6cd5\u5411\u91cf\u76f8\u4e58\u7684\uff0c\u56e0\u6b64\u6211\u4eec\u5bf9\u65b9\u7a0b\u4e2d\u7684\u6240\u6709\u9879\u90fd\u7528\u6cd5\u5411\u91cf\u6765\u4e58\u4ee5\u7ed3\u679c\u3002\u5728\u8fd9\u4e9b\u4e58\u6cd5\u4e2d\uff0c\u4e0a\u9762\u5b9a\u4e49\u7684 \"\u64cd\u4f5c\u7b26*\"\u53ef\u4ee5\u5b9e\u73b0\u7c7b\u4f3c\u4e8e\u6570\u5b66\u5b9a\u4e49\u7684\u7d27\u51d1\u7b26\u53f7\u3002\n\n// \u5728\u8fd9\u4e2a\u51fd\u6570\u548c\u4e0b\u9762\u7684\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u4f7f\u7528\u53d8\u91cf\u540e\u7f00`_m`\u548c`_p`\u6765\u8868\u793a\u4ece $\\mathbf{w}^-$ \u548c $\\mathbf{w}^+$ \u5f97\u51fa\u7684\u91cf\uff0c\u5373\u5728\u89c2\u5bdf\u76f8\u90bb\u5355\u5143\u65f6\u76f8\u5bf9\u4e8e\u5f53\u524d\u5355\u5143\u7684 \"\u8fd9\u91cc \"\u548c \"\u90a3\u91cc \"\u7684\u6570\u503c\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u548c\u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u8f85\u52a9\u51fd\u6570\uff0c\u63d0\u4f9b\u7d27\u51d1\u7684\u8bc4\u4f30\u8c03\u7528\uff0c\u56e0\u4e3a\u591a\u4e2a\u70b9\u901a\u8fc7VectorizedArray\u53c2\u6570\u88ab\u5206\u6279\u653e\u5728\u4e00\u8d77\uff08\u8be6\u89c1 step-37 \u6559\u7a0b\uff09\u3002\u8fd9\u4e2a\u51fd\u6570\u7528\u4e8e\u4e9a\u97f3\u901f\u5916\u6d41\u8fb9\u754c\u6761\u4ef6\uff0c\u6211\u4eec\u9700\u8981\u5c06\u80fd\u91cf\u5206\u91cf\u8bbe\u7f6e\u4e3a\u4e00\u4e2a\u89c4\u5b9a\u503c\u3002\u4e0b\u4e00\u4e2a\u51fd\u6570\u8bf7\u6c42\u6240\u6709\u5206\u91cf\u4e0a\u7684\u89e3\uff0c\u7528\u4e8e\u6d41\u5165\u8fb9\u754c\uff0c\u5176\u4e2d\u89e3\u7684\u6240\u6709\u5206\u91cf\u90fd\u88ab\u8bbe\u7f6e\u3002\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// \u8fd9\u4e2a\u7c7b\u5b9e\u73b0\u4e86\u6b27\u62c9\u95ee\u9898\u7684\u8bc4\u4f30\u5668\uff0c\u7c7b\u4f3c\u4e8e  step-37  \u6216  step-59  \u7684 `LaplaceOperator` \u7c7b\u3002\u7531\u4e8e\u672c\u7b97\u5b50\u662f\u975e\u7ebf\u6027\u7684\uff0c\u4e0d\u9700\u8981\u77e9\u9635\u63a5\u53e3\uff08\u4ea4\u7ed9\u9884\u5904\u7406\u7a0b\u5e8f\uff09\uff0c\u6211\u4eec\u8df3\u8fc7\u4e86\u65e0\u77e9\u9635\u7b97\u5b50\u4e2d\u7684\u5404\u79cd`vmult`\u51fd\u6570\uff0c\u53ea\u5b9e\u73b0\u4e86`apply`\u51fd\u6570\u4ee5\u53ca`apply`\u4e0e\u4e0a\u8ff0\u4f4e\u5b58\u50a8Runge-Kutta\u65f6\u95f4\u79ef\u5206\u5668\u6240\u9700\u7684\u77e2\u91cf\u66f4\u65b0\u7684\u7ec4\u5408\uff08\u79f0\u4e3a`perform_stage`\uff09\u3002\u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u589e\u52a0\u4e86\u4e09\u4e2a\u6d89\u53ca\u65e0\u77e9\u9635\u4f8b\u7a0b\u7684\u989d\u5916\u51fd\u6570\uff0c\u5373\u4e00\u4e2a\u662f\u6839\u636e\u5143\u7d20\u4e2d\u7684\u901f\u5ea6\u548c\u58f0\u901f\u8ba1\u7b97\u65f6\u95f4\u6b65\u957f\u7684\u4f30\u8ba1\u503c\uff08\u4e0e\u5b9e\u9645\u65f6\u95f4\u6b65\u957f\u7684Courant\u6570\u76f8\u7ed3\u5408\uff09\uff0c\u4e00\u4e2a\u662f\u89e3\u7684\u6295\u5f71\uff08\u4e13\u95e8\u9488\u5bf9DG\u60c5\u51b5\u7684 VectorTools::project() \uff09\uff0c\u8fd8\u6709\u4e00\u4e2a\u662f\u8ba1\u7b97\u4e0e\u53ef\u80fd\u7684\u5206\u6790\u89e3\u6216\u4e0e\u67d0\u4e9b\u80cc\u666f\u72b6\u6001\u7684\u89c4\u8303\u7684\u8bef\u5dee\u3002\n\n// \u8be5\u8bfe\u7684\u5176\u4f59\u90e8\u5206\u4e0e\u5176\u4ed6\u65e0\u77e9\u9635\u6559\u7a0b\u76f8\u4f3c\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u6211\u4eec\u63d0\u4f9b\u4e86\u51e0\u4e2a\u51fd\u6570\uff0c\u5141\u8bb8\u7528\u6237\u5728\u7531 types::boundary_id \u53d8\u91cf\u6807\u8bb0\u7684\u9886\u57df\u8fb9\u754c\u7684\u4e0d\u540c\u90e8\u5206\u4f20\u9012\u5404\u79cd\u5f62\u5f0f\u7684\u8fb9\u754c\u6761\u4ef6\uff0c\u4ee5\u53ca\u53ef\u80fd\u7684\u4f53\u529b\u3002\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// \u5bf9\u4e8e\u6b27\u62c9\u7b97\u5b50\u7684\u521d\u59cb\u5316\uff0c\u6211\u4eec\u8bbe\u7f6e\u4e86\u7c7b\u4e2d\u5305\u542b\u7684MatrixFree\u53d8\u91cf\u3002\u8fd9\u53ef\u4ee5\u901a\u8fc7\u7ed9\u5b9a\u4e00\u4e2a\u63cf\u8ff0\u53ef\u80fd\u7684\u5f2f\u66f2\u8fb9\u754c\u7684\u6620\u5c04\u4ee5\u53ca\u4e00\u4e2a\u63cf\u8ff0\u81ea\u7531\u5ea6\u7684DoFHandler\u5bf9\u8c61\u6765\u5b8c\u6210\u3002\u7531\u4e8e\u6211\u4eec\u5728\u8fd9\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u7684\u662f\u4e0d\u8fde\u7eed\u7684Galerkin\u79bb\u6563\u5316\uff0c\u6ca1\u6709\u5bf9\u89e3\u573a\u65bd\u52a0\u5f3a\u70c8\u7684\u7ea6\u675f\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u9700\u8981\u4f20\u5165AffineConstraints\u5bf9\u8c61\uff0c\u800c\u662f\u4f7f\u7528\u4e00\u4e2a\u5047\u7684\u6765\u6784\u9020\u3002\u5173\u4e8e\u6b63\u4ea4\uff0c\u6211\u4eec\u8981\u9009\u62e9\u4e24\u79cd\u4e0d\u540c\u7684\u65b9\u5f0f\u6765\u8ba1\u7b97\u57fa\u7840\u79ef\u5206\u3002\u7b2c\u4e00\u79cd\u662f\u7075\u6d3b\u7684\uff0c\u57fa\u4e8e\u6a21\u677f\u53c2\u6570`n_points_1d`\uff08\u5c06\u88ab\u5206\u914d\u5230\u672c\u6587\u4ef6\u9876\u90e8\u6307\u5b9a\u7684`n_q_points_1d`\u503c\uff09\u3002\u66f4\u7cbe\u786e\u7684\u79ef\u5206\u662f\u5fc5\u8981\u7684\uff0c\u4ee5\u907f\u514d\u7531\u4e8e\u6b27\u62c9\u7b97\u5b50\u4e2d\u7684\u53ef\u53d8\u7cfb\u6570\u800c\u4ea7\u751f\u7684\u6df7\u53e0\u95ee\u9898\u3002\u7b2c\u4e8c\u4e2a\u4e0d\u592a\u7cbe\u786e\u7684\u6b63\u4ea4\u516c\u5f0f\u662f\u4e00\u4e2a\u57fa\u4e8e`fe_degree+1`\u7684\u4e25\u5bc6\u516c\u5f0f\uff0c\u9700\u8981\u7528\u4e8e\u53cd\u8d28\u91cf\u77e9\u9635\u3002\u867d\u7136\u8be5\u516c\u5f0f\u53ea\u5728\u4eff\u751f\u5143\u7d20\u5f62\u72b6\u4e0a\u63d0\u4f9b\u4e86\u7cbe\u786e\u7684\u53cd\uff0c\u800c\u5728\u53d8\u5f62\u5143\u7d20\u4e0a\u5219\u6ca1\u6709\uff0c\u4f46\u5b83\u53ef\u4ee5\u901a\u8fc7\u5f20\u91cf\u79ef\u6280\u672f\u5feb\u901f\u53cd\u8f6c\u8d28\u91cf\u77e9\u9635\uff0c\u8fd9\u5bf9\u4e8e\u786e\u4fdd\u6574\u4f53\u7684\u6700\u4f73\u8ba1\u7b97\u6548\u7387\u662f\u5fc5\u8981\u7684\u3002\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// \u968f\u540e\u7684\u56db\u4e2a\u6210\u5458\u51fd\u6570\u662f\u5fc5\u987b\u4ece\u5916\u90e8\u8c03\u7528\u7684\uff0c\u4ee5\u6307\u5b9a\u5404\u79cd\u7c7b\u578b\u7684\u8fb9\u754c\u3002\u5bf9\u4e8e\u4e00\u4e2a\u6d41\u5165\u7684\u8fb9\u754c\uff0c\u6211\u4eec\u5fc5\u987b\u4ee5\u5bc6\u5ea6  $\\rho$  \u3001\u52a8\u91cf  $\\rho \\mathbf{u}$  \u548c\u80fd\u91cf  $E$  \u6765\u6307\u5b9a\u6240\u6709\u6210\u5206\u3002\u8003\u8651\u5230\u8fd9\u4e9b\u4fe1\u606f\uff0c\u6211\u4eec\u5c06\u51fd\u6570\u4e0e\u5404\u81ea\u7684\u8fb9\u754cID\u4e00\u8d77\u5b58\u50a8\u5728\u8fd9\u4e2a\u7c7b\u7684\u5730\u56fe\u6210\u5458\u53d8\u91cf\u4e2d\u3002\u540c\u6837\uff0c\u6211\u4eec\u5bf9\u4e9a\u97f3\u901f\u5916\u6d41\u8fb9\u754c\uff08\u6211\u4eec\u4e5f\u8981\u6c42\u4e00\u4e2a\u51fd\u6570\uff0c\u7528\u6765\u68c0\u7d22\u80fd\u91cf\uff09\u548c\u58c1\u9762\uff08\u65e0\u7a7f\u900f\uff09\u8fb9\u754c\u8fdb\u884c\u5904\u7406\uff0c\u5728\u58c1\u9762\u4e0a\u6211\u4eec\u65bd\u52a0\u96f6\u6cd5\u7ebf\u901f\u5ea6\uff08\u4e0d\u9700\u8981\u51fd\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u53ea\u8981\u6c42\u8fb9\u754cID\uff09\u3002\u5bf9\u4e8e\u76ee\u524d\u7684DG\u4ee3\u7801\u6765\u8bf4\uff0c\u8fb9\u754c\u6761\u4ef6\u53ea\u4f5c\u4e3a\u5f31\u5f62\u5f0f\u7684\u4e00\u90e8\u5206\u88ab\u5e94\u7528\uff08\u5728\u65f6\u95f4\u79ef\u5206\u671f\u95f4\uff09\uff0c\u8bbe\u7f6e\u8fb9\u754c\u6761\u4ef6\u7684\u8c03\u7528\u53ef\u4ee5\u51fa\u73b0\u5728\u5bf9\u8fd9\u4e2a\u7c7b\u7684`reinit()`\u8c03\u7528\u4e4b\u524d\u6216\u4e4b\u540e\u3002\u8fd9\u4e0e\u8fde\u7eed\u6709\u9650\u5143\u4ee3\u7801\u4e0d\u540c\uff0c\u5728\u8fde\u7eed\u6709\u9650\u5143\u4ee3\u7801\u4e2d\uff0c\u8fb9\u754c\u6761\u4ef6\u51b3\u5b9a\u4e86\u88ab\u9001\u5165MatrixFree\u521d\u59cb\u5316\u7684AffineConstraints\u5bf9\u8c61\u7684\u5185\u5bb9\uff0c\u56e0\u6b64\u9700\u8981\u5728\u65e0\u77e9\u9635\u6570\u636e\u7ed3\u6784\u7684\u521d\u59cb\u5316\u4e4b\u524d\u8bbe\u7f6e\u3002\n\n// \u5728\u56db\u4e2a\u51fd\u6570\u4e2d\u7684\u6bcf\u4e00\u4e2a\u4e2d\u6dfb\u52a0\u7684\u68c0\u67e5\u662f\u7528\u6765\u786e\u4fdd\u8fb9\u754c\u6761\u4ef6\u5728\u8fb9\u754c\u7684\u5404\u4e2a\u90e8\u5206\u662f\u76f8\u4e92\u6392\u65a5\u7684\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u7528\u6237\u4e0d\u4f1a\u610f\u5916\u5730\u5c06\u4e00\u4e2a\u8fb9\u754c\u65e2\u6307\u5b9a\u4e3a\u6d41\u5165\u8fb9\u754c\uff0c\u53c8\u6307\u5b9a\u4e3a\u4e9a\u58f0\u901f\u6d41\u51fa\u8fb9\u754c\u3002\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// \u73b0\u5728\u6211\u4eec\u5f00\u59cb\u7814\u7a76\u6b27\u62c9\u95ee\u9898\u7684\u5c40\u90e8\u8bc4\u4f30\u5668\u3002\u8bc4\u4f30\u5668\u76f8\u5bf9\u7b80\u5355\uff0c\u9075\u5faa  step-37  \u3001  step-48  \u6216  step-59  \u4e2d\u63d0\u51fa\u7684\u5185\u5bb9\u3002\u7b2c\u4e00\u4e2a\u663e\u8457\u7684\u533a\u522b\u662f\uff0c\u6211\u4eec\u4f7f\u7528\u7684\u662f\u5177\u6709\u975e\u6807\u51c6\u6b63\u4ea4\u70b9\u6570\u91cf\u7684FEE\u8bc4\u4f30\u3002\u4ee5\u524d\u6211\u4eec\u603b\u662f\u5c06\u6b63\u4ea4\u70b9\u7684\u6570\u91cf\u8bbe\u7f6e\u4e3a\u7b49\u4e8e\u591a\u9879\u5f0f\u5ea6\u6570\u52a01\uff08\u786e\u4fdd\u5728\u4eff\u751f\u5143\u7d20\u5f62\u72b6\u4e0a\u7684\u7cbe\u786e\u79ef\u5206\uff09\uff0c\u73b0\u5728\u6211\u4eec\u5c06\u6b63\u4ea4\u70b9\u7684\u6570\u91cf\u8bbe\u7f6e\u4e3a\u4e00\u4e2a\u5355\u72ec\u7684\u53d8\u91cf\uff08\u4f8b\u5982\u591a\u9879\u5f0f\u5ea6\u6570\u52a0\u591a\u9879\u5f0f\u5ea6\u6570\u7684\u4e8c\u5206\u4e4b\u4e00\u6216\u4e09\u5206\u4e4b\u4e00\uff09\uff0c\u4ee5\u66f4\u51c6\u786e\u5730\u5904\u7406\u975e\u7ebf\u6027\u9879\u3002\u7531\u4e8e\u8bc4\u4f30\u5668\u901a\u8fc7\u6a21\u677f\u53c2\u6570\u8f93\u5165\u4e86\u9002\u5f53\u7684\u5faa\u73af\u957f\u5ea6\uff0c\u5e76\u5728\u53d8\u91cf FEEvaluation::n_q_points, \u4e2d\u4fdd\u7559\u4e86\u6574\u4e2a\u5355\u5143\u683c\u7684\u6b63\u4ea4\u70b9\u6570\u91cf\uff0c\u6240\u4ee5\u6211\u4eec\u73b0\u5728\u81ea\u52a8\u64cd\u4f5c\u66f4\u7cbe\u786e\u7684\u516c\u5f0f\uff0c\u800c\u65e0\u9700\u8fdb\u4e00\u6b65\u4fee\u6539\u3002\n\n// \u7b2c\u4e8c\u4e2a\u533a\u522b\u662f\u7531\u4e8e\u6211\u4eec\u73b0\u5728\u8bc4\u4f30\u7684\u662f\u4e00\u4e2a\u591a\u5206\u91cf\u7cfb\u7edf\uff0c\u800c\u4e0d\u662f\u4e4b\u524d\u8003\u8651\u7684\u6807\u91cf\u7cfb\u7edf\u3002\u65e0\u77e9\u9635\u6846\u67b6\u63d0\u4f9b\u4e86\u51e0\u79cd\u65b9\u6cd5\u6765\u5904\u7406\u591a\u6210\u5206\u7684\u60c5\u51b5\u3002\u8fd9\u91cc\u663e\u793a\u7684\u53d8\u4f53\u662f\u5229\u7528\u4e00\u4e2a\u5d4c\u5165\u4e86\u591a\u4e2a\u5206\u91cf\u7684FEEvaluation\u5bf9\u8c61\uff0c\u7531\u7b2c\u56db\u4e2a\u6a21\u677f\u53c2\u6570`dim + 2`\u6307\u5b9a\u6b27\u62c9\u7cfb\u7edf\u4e2d\u7684\u5206\u91cf\u3002\u56e0\u6b64\uff0c FEEvaluation::get_value() \u7684\u8fd4\u56de\u7c7b\u578b\u4e0d\u518d\u662f\u4e00\u4e2a\u6807\u91cf\uff08\u8fd9\u5c06\u8fd4\u56de\u4e00\u4e2aVectorizedArray\u7c7b\u578b\uff0c\u6536\u96c6\u51e0\u4e2a\u5143\u7d20\u7684\u6570\u636e\uff09\uff0c\u800c\u662f\u4e00\u4e2a`dim+2`\u7ec4\u4ef6\u7684\u5f20\u91cf\u3002\u8be5\u529f\u80fd\u4e0e\u6807\u91cf\u7684\u60c5\u51b5\u7c7b\u4f3c\uff1b\u5b83\u7531\u4e00\u4e2a\u57fa\u7c7b\u7684\u6a21\u677f\u4e13\u4e1a\u5316\u5904\u7406\uff0c\u79f0\u4e3aFEEvaluationAccess\u3002\u53e6\u4e00\u4e2a\u53d8\u4f53\u662f\u4f7f\u7528\u51e0\u4e2aFEEvaluation\u5bf9\u8c61\uff0c\u4e00\u4e2a\u6807\u91cf\u5bf9\u8c61\u7528\u4e8e\u5bc6\u5ea6\uff0c\u4e00\u4e2a\u5e26`dim`\u5206\u91cf\u7684\u77e2\u91cf\u503c\u5bf9\u8c61\u7528\u4e8e\u52a8\u91cf\uff0c\u53e6\u4e00\u4e2a\u6807\u91cf\u8bc4\u4ef7\u5668\u7528\u4e8e\u80fd\u91cf\u3002\u4e3a\u4e86\u786e\u4fdd\u8fd9\u4e9b\u5206\u91cf\u6307\u5411\u89e3\u51b3\u65b9\u6848\u7684\u6b63\u786e\u90e8\u5206\uff0cFEEvaluation\u7684\u6784\u9020\u51fd\u6570\u5728\u6240\u9700\u7684MatrixFree\u5b57\u6bb5\u4e4b\u540e\u9700\u8981\u4e09\u4e2a\u53ef\u9009\u7684\u6574\u6570\u53c2\u6570\uff0c\u5373\u591aDoFHandler\u7cfb\u7edf\u7684DoFHandler\u7f16\u53f7\uff08\u9ed8\u8ba4\u53d6\u7b2c\u4e00\u4e2a\uff09\uff0c\u5982\u679c\u6709\u591a\u4e2aQuadrature\u5bf9\u8c61\uff0c\u5219\u53d6\u6b63\u4ea4\u70b9\u7684\u7f16\u53f7\uff08\u89c1\u4e0b\u6587\uff09\uff0c\u4ee5\u53ca\u4f5c\u4e3a\u7b2c\u4e09\u4e2a\u53c2\u6570\u7684\u77e2\u91cf\u7cfb\u7edf\u4e2d\u7684\u5206\u91cf\u3002\u7531\u4e8e\u6211\u4eec\u6709\u4e00\u4e2a\u5355\u4e00\u7684\u77e2\u91cf\u6765\u8868\u793a\u6240\u6709\u7684\u5206\u91cf\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u7b2c\u4e09\u4e2a\u53c2\u6570\uff0c\u5e76\u5c06\u5176\u8bbe\u7f6e\u4e3a`0`\u8868\u793a\u5bc6\u5ea6\uff0c`1`\u8868\u793a\u77e2\u91cf\u503c\u7684\u52a8\u91cf\uff0c`dim+1`\u8868\u793a\u80fd\u91cf\u69fd\u3002\u7136\u540eFEEvaluation\u5728 FEEvaluationBase::read_dof_values() \u548c FEEvaluation::distributed_local_to_global() \u6216\u66f4\u7d27\u51d1\u7684 FEEvaluation::gather_evaluate() \u548c FEEvaluation::integrate_scatter() \u8c03\u7528\u4e2d\u6311\u9009\u9002\u5f53\u7684\u89e3\u77e2\u91cf\u5b50\u8303\u56f4\u3002\n\n// \u5f53\u6d89\u53ca\u5230\u8eab\u4f53\u529b\u5411\u91cf\u7684\u8bc4\u4f30\u65f6\uff0c\u4e3a\u4e86\u6548\u7387\uff0c\u6211\u4eec\u533a\u5206\u4e86\u4e24\u79cd\u60c5\u51b5\u3002\u5982\u679c\u6211\u4eec\u6709\u4e00\u4e2a\u5e38\u6570\u51fd\u6570\uff08\u6e90\u81ea Functions::ConstantFunction), \uff09\uff0c\u6211\u4eec\u53ef\u4ee5\u5728\u6b63\u4ea4\u70b9\u7684\u5faa\u73af\u5916\u9884\u5148\u8ba1\u7b97\u51fa\u6570\u503c\uff0c\u5e76\u7b80\u5355\u5730\u5728\u6240\u6709\u5730\u65b9\u4f7f\u7528\u8be5\u6570\u503c\u3002\u5bf9\u4e8e\u4e00\u4e2a\u66f4\u901a\u7528\u7684\u51fd\u6570\uff0c\u6211\u4eec\u53cd\u800c\u9700\u8981\u8c03\u7528\u6211\u4eec\u4e0a\u9762\u63d0\u4f9b\u7684`evaluate_function()`\u65b9\u6cd5\uff1b\u8fd9\u4e2a\u8def\u5f84\u66f4\u6602\u8d35\uff0c\u56e0\u4e3a\u6211\u4eec\u9700\u8981\u8bbf\u95ee\u4e0e\u6b63\u4ea4\u70b9\u6570\u636e\u6709\u5173\u7684\u5185\u5b58\u3002\n\n// \u5176\u4f59\u90e8\u5206\u6cbf\u7528\u5176\u4ed6\u6559\u7a0b\u7684\u7a0b\u5e8f\u3002\u7531\u4e8e\u6211\u4eec\u5df2\u7ecf\u5728\u5355\u72ec\u7684`euler_flux()`\u51fd\u6570\u4e2d\u5b9e\u73b0\u4e86\u6b27\u62c9\u65b9\u7a0b\u7684\u6240\u6709\u7269\u7406\u5b66\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u6240\u8981\u505a\u7684\u5c31\u662f\u7ed9\u5b9a\u5728\u6b63\u4ea4\u70b9\u8bc4\u4f30\u7684\u5f53\u524d\u89e3\uff0c\u7531`phi.get_value(q)`\u8fd4\u56de\uff0c\u5e76\u544a\u8bc9FEEvaluation\u5bf9\u8c61\uff0c\u901a\u8fc7\u5f62\u72b6\u51fd\u6570\u7684\u68af\u5ea6\uff08\u8fd9\u662f\u4e00\u4e2a\u5916\u90e8`dim+2`\u5206\u91cf\u7684\u5f20\u91cf\uff0c\u6bcf\u4e2a\u5f20\u91cf\u6301\u6709\u4e00\u4e2a`dim`\u5206\u91cf\u7684 $x,y,z$  ] \u6b27\u62c9\u901a\u91cf\u7684\u5206\u91cf\uff09\u3002) \u6700\u540e\u503c\u5f97\u4e00\u63d0\u7684\u662f\uff0c\u5728\u6211\u4eec\u5f97\u5230\u4e00\u4e2a\u5916\u90e8\u51fd\u6570\u7684\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u901a\u8fc7\u6d4b\u8bd5\u51fd\u6570`phi.submit_value()`\u7684\u503c\u6765\u6392\u961f\u6d4b\u8bd5\u6570\u636e\u7684\u987a\u5e8f\u3002\u6211\u4eec\u5fc5\u987b\u5728\u8c03\u7528`phi.get_value(q)'\u4e4b\u540e\u8fdb\u884c\uff0c\u56e0\u4e3a`get_value()'\uff08\u8bfb\u53d6\u89e3\u51b3\u65b9\u6848\uff09\u548c`submit_value()'\uff08\u6392\u961f\u7b49\u5f85\u6d4b\u8bd5\u51fd\u6570\u7684\u4e58\u6cd5\u548c\u6b63\u4ea4\u70b9\u7684\u6c42\u548c\uff09\u8bbf\u95ee\u540c\u4e00\u4e2a\u5e95\u5c42\u6570\u636e\u57df\u3002\u8fd9\u91cc\u5f88\u5bb9\u6613\u5b9e\u73b0\u6ca1\u6709\u4e34\u65f6\u53d8\u91cf`w_q`\uff0c\u56e0\u4e3a\u503c\u548c\u68af\u5ea6\u4e4b\u95f4\u6ca1\u6709\u6df7\u5408\u3002\u5bf9\u4e8e\u66f4\u590d\u6742\u7684\u8bbe\u7f6e\uff0c\u5fc5\u987b\u9996\u5148\u590d\u5236\u51fa\u4f8b\u5982\u6b63\u4ea4\u70b9\u7684\u503c\u548c\u68af\u5ea6\uff0c\u7136\u540e\u901a\u8fc7 FEEvaluationBase::submit_value() \u548c FEEvaluationBase::submit_gradient(). \u518d\u6b21\u6392\u5217\u7ed3\u679c\u3002\n\n// \u4f5c\u4e3a\u6700\u540e\u7684\u8bf4\u660e\uff0c\u6211\u4eec\u63d0\u5230\u6211\u4eec\u6ca1\u6709\u4f7f\u7528\u8fd9\u4e2a\u51fd\u6570\u7684\u7b2c\u4e00\u4e2aMatrixFree\u53c2\u6570\uff0c\u8fd9\u662f\u4e00\u4e2a\u6765\u81ea MatrixFree::loop(). \u7684\u56de\u8c03\uff0c\u63a5\u53e3\u89c4\u5b9a\u4e86\u73b0\u5728\u7684\u53c2\u6570\u5217\u8868\uff0c\u4f46\u662f\u7531\u4e8e\u6211\u4eec\u5728\u4e00\u4e2a\u6210\u5458\u51fd\u6570\u4e2d\uff0cMatrixFree\u5bf9\u8c61\u5df2\u7ecf\u53ef\u4ee5\u4f5c\u4e3a`data`\u53d8\u91cf\uff0c\u6211\u4eec\u575a\u6301\u4f7f\u7528\uff0c\u4ee5\u907f\u514d\u6df7\u6dc6\u3002\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// \u4e0b\u4e00\u4e2a\u51fd\u6570\u6d89\u53ca\u5230\u5185\u90e8\u9762\u7684\u79ef\u5206\u8ba1\u7b97\uff0c\u5728\u8fd9\u91cc\u6211\u4eec\u9700\u8981\u4e0e\u9762\u76f8\u90bb\u7684\u4e24\u4e2a\u5355\u5143\u7684\u8bc4\u4f30\u5668\u3002\u6211\u4eec\u5c06\u53d8\u91cf`phi_m`\u4e0e\u89e3\u5206\u91cf $\\mathbf{w}^-$ \u76f8\u5173\u8054\uff0c\u5c06\u53d8\u91cf`phi_p`\u4e0e\u89e3\u5206\u91cf $\\mathbf{w}^+$ \u76f8\u5173\u8054\u3002\u6211\u4eec\u5728FEFaceEvaluation\u7684\u6784\u9020\u51fd\u6570\u4e2d\u901a\u8fc7\u7b2c\u4e8c\u4e2a\u53c2\u6570\u6765\u533a\u5206\u4e24\u8fb9\uff0c`true`\u8868\u793a\u5185\u4fa7\uff0c`false`\u8868\u793a\u5916\u4fa7\uff0c\u5185\u4fa7\u548c\u5916\u4fa7\u8868\u793a\u76f8\u5bf9\u4e8e\u6cd5\u5411\u91cf\u7684\u65b9\u5411\u3002\n\n// \u6ce8\u610f\u8c03\u7528 FEFaceEvaluation::gather_evaluate() \u548c FEFaceEvaluation::integrate_scatter() \u7ed3\u5408\u4e86\u5bf9\u5411\u91cf\u7684\u8bbf\u95ee\u548c\u56e0\u5f0f\u5206\u89e3\u90e8\u5206\u3002\u8fd9\u79cd\u5408\u5e76\u64cd\u4f5c\u4e0d\u4ec5\u8282\u7701\u4e86\u4e00\u884c\u4ee3\u7801\uff0c\u800c\u4e14\u8fd8\u5305\u542b\u4e86\u4e00\u4e2a\u91cd\u8981\u7684\u4f18\u5316\u3002\u9274\u4e8e\u6211\u4eec\u5728Gauss-Lobatto\u6b63\u4ea4\u516c\u5f0f\u7684\u70b9\u4e0a\u4f7f\u7528\u62c9\u683c\u6717\u65e5\u591a\u9879\u5f0f\u7684\u8282\u70b9\u57fa\u7840\uff0c\u5728\u6bcf\u4e2a\u9762\u4e0a\u53ea\u6709 $(p+1)^{d-1}$ \u7684\u57fa\u7840\u51fd\u6570\u8bc4\u4f30\u4e3a\u975e\u96f6\u3002\u56e0\u6b64\uff0c\u8bc4\u4f30\u5668\u53ea\u8bbf\u95ee\u4e86\u5411\u91cf\u4e2d\u7684\u5fc5\u8981\u6570\u636e\uff0c\u800c\u8df3\u8fc7\u4e86\u4e58\u4ee5\u96f6\u7684\u90e8\u5206\u3002\u5982\u679c\u6211\u4eec\u9996\u5148\u8bfb\u53d6\u5411\u91cf\uff0c\u6211\u4eec\u5c31\u9700\u8981\u4ece\u5411\u91cf\u4e2d\u52a0\u8f7d\u6240\u6709\u7684\u6570\u636e\uff0c\u56e0\u4e3a\u5b64\u7acb\u7684\u8c03\u7528\u4e0d\u77e5\u9053\u540e\u7eed\u64cd\u4f5c\u4e2d\u9700\u8981\u54ea\u4e9b\u6570\u636e\u3002\u5982\u679c\u968f\u540e\u7684 FEFaceEvaluation::evaluate() \u8c03\u7528\u8981\u6c42\u6570\u503c\u548c\u5bfc\u6570\uff0c\u786e\u5b9e\u9700\u8981\u6bcf\u4e2a\u5206\u91cf\u7684\u6240\u6709 $(p+1)^d$ \u5411\u91cf\u6761\u76ee\uff0c\u56e0\u4e3a\u6240\u6709\u57fa\u51fd\u6570\u7684\u6cd5\u5411\u5bfc\u6570\u90fd\u662f\u975e\u96f6\u7684\u3002\n\n// \u8bc4\u4ef7\u5668\u7684\u53c2\u6570\u4ee5\u53ca\u7a0b\u5e8f\u4e0e\u5355\u5143\u8bc4\u4ef7\u76f8\u4f3c\u3002\u7531\u4e8e\u975e\u7ebf\u6027\u9879\u7684\u5b58\u5728\uff0c\u6211\u4eec\u518d\u6b21\u4f7f\u7528\u66f4\u7cbe\u786e\u7684\uff08\u8fc7\u5ea6\uff09\u79ef\u5206\u65b9\u6848\uff0c\u6307\u5b9a\u4e3a\u5217\u8868\u4e2d\u7b2c\u4e09\u4e2a\u6a21\u677f\u53c2\u6570\u3002\u5728\u6b63\u4ea4\u70b9\u4e0a\uff0c\u6211\u4eec\u518d\u53bb\u627e\u6211\u4eec\u7684\u81ea\u7531\u51fd\u6570\u6765\u8ba1\u7b97\u6570\u503c\u901a\u91cf\u3002\u5b83\u4ece\u4e24\u8fb9\uff08\u5373 $\\mathbf{w}^-$ \u548c $\\mathbf{w}^+$ \uff09\u63a5\u6536\u5728\u6b63\u4ea4\u70b9\u8bc4\u4f30\u7684\u89e3\u51b3\u65b9\u6848\uff0c\u4ee5\u53ca\u5230\u51cf\u53bb\u4e00\u8fb9\u7684\u6cd5\u5411\u91cf\u3002\u6b63\u5982\u4e0a\u9762\u6240\u89e3\u91ca\u7684\uff0c\u6570\u503c\u901a\u91cf\u5df2\u7ecf\u4e58\u4ee5\u6765\u81ea\u51cf\u6cd5\u4fa7\u7684\u6cd5\u5411\u91cf\u4e86\u3002\u6211\u4eec\u9700\u8981\u8f6c\u6362\u7b26\u53f7\uff0c\u56e0\u4e3a\u5728\u5f15\u8a00\u4e2d\u5f97\u51fa\u7684\u5f31\u5f62\u5f0f\u4e2d\uff0c\u8fb9\u754c\u9879\u5e26\u6709\u4e00\u4e2a\u51cf\u53f7\u3002\u7136\u540e\uff0c\u901a\u91cf\u88ab\u6392\u961f\u5728\u51cf\u53f7\u548c\u52a0\u53f7\u4e0a\u8fdb\u884c\u6d4b\u8bd5\uff0c\u7531\u4e8e\u52a0\u53f7\u4e0a\u7684\u6cd5\u5411\u91cf\u4e0e\u51cf\u53f7\u4e0a\u7684\u6cd5\u5411\u91cf\u6b63\u597d\u76f8\u53cd\uff0c\u6240\u4ee5\u8981\u8c03\u6362\u7b26\u53f7\u3002\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// \u5bf9\u4e8e\u4f4d\u4e8e\u8fb9\u754c\u7684\u9762\uff0c\u6211\u4eec\u9700\u8981\u65bd\u52a0\u9002\u5f53\u7684\u8fb9\u754c\u6761\u4ef6\u3002\u5728\u8fd9\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u5b9e\u73b0\u4e86\u4e0a\u8ff0\u7684\u56db\u79cd\u60c5\u51b5\u3002\u7b2c\u4e94\u79cd\u60c5\u51b5\uff0c\u5373\u8d85\u97f3\u901f\u6d41\u51fa\u6761\u4ef6\uff0c\u5c06\u5728\u4e0b\u9762\u7684 \"\u7ed3\u679c \"\u90e8\u5206\u8ba8\u8bba\uff09\u3002\u4e0d\u8fde\u7eed\u7684Galerkin\u65b9\u6cd5\u5bf9\u8fb9\u754c\u6761\u4ef6\u7684\u65bd\u52a0\u4e0d\u662f\u4f5c\u4e3a\u7ea6\u675f\u6761\u4ef6\uff0c\u800c\u53ea\u662f\u5f31\u5316\u3002\u56e0\u6b64\uff0c\u5404\u79cd\u6761\u4ef6\u662f\u901a\u8fc7\u627e\u5230\u4e00\u4e2a\u9002\u5f53\u7684<i>exterior</i>\u91cf $\\mathbf{w}^+$ \u6765\u65bd\u52a0\u7684\uff0c\u7136\u540e\u5c06\u5176\u4ea4\u7ed9\u4e5f\u7528\u4e8e\u5185\u90e8\u9762\u7684\u6570\u503c\u901a\u91cf\u51fd\u6570\u3002\u5b9e\u8d28\u4e0a\uff0c\u6211\u4eec\u5728\u57df\u5916 \"\u5047\u88c5 \"\u4e00\u4e2a\u72b6\u6001\uff0c\u5982\u679c\u90a3\u662f\u73b0\u5b9e\uff0cPDE\u7684\u89e3\u5c06\u6ee1\u8db3\u6211\u4eec\u60f3\u8981\u7684\u8fb9\u754c\u6761\u4ef6\u3002\n\n// \u5bf9\u4e8e\u5899\u7684\u8fb9\u754c\uff0c\u6211\u4eec\u9700\u8981\u5bf9\u52a8\u91cf\u53d8\u91cf\u65bd\u52a0\u4e00\u4e2a\u65e0\u6b63\u6001\u901a\u91cf\u7684\u6761\u4ef6\uff0c\u800c\u5bf9\u4e8e\u5bc6\u5ea6\u548c\u80fd\u91cf\uff0c\u6211\u4eec\u4f7f\u7528\u7684\u662f\u8bfa\u4f0a\u66fc\u6761\u4ef6  $\\rho^+ = \\rho^-$  \u548c  $E^+ = E^-$  \u3002\u4e3a\u4e86\u5b9e\u73b0\u65e0\u6b63\u6001\u901a\u91cf\u6761\u4ef6\uff0c\u6211\u4eec\u5c06\u5916\u90e8\u6570\u503c\u8bbe\u5b9a\u4e3a\u5185\u90e8\u6570\u503c\uff0c\u5e76\u51cf\u53bb\u5899\u9762\u6cd5\u7ebf\u65b9\u5411\uff0c\u5373\u6cd5\u7ebf\u77e2\u91cf\u65b9\u5411\u4e0a\u7684\u901f\u5ea6\u76842\u500d\u3002\n\n// \u5bf9\u4e8e\u6d41\u5165\u8fb9\u754c\uff0c\u6211\u4eec\u7b80\u5355\u5730\u5c06\u7ed9\u5b9a\u7684Dirichlet\u6570\u636e $\\mathbf{w}_\\mathrm{D}$ \u4f5c\u4e3a\u8fb9\u754c\u503c\u3002\u53e6\u4e00\u79cd\u65b9\u6cd5\u662f\u4f7f\u7528 $\\mathbf{w}^+ = -\\mathbf{w}^- + 2 \\mathbf{w}_\\mathrm{D}$  \uff0c\u5373\u6240\u8c13\u7684\u955c\u50cf\u539f\u7406\u3002\n\n// \u5f3a\u52a0\u5916\u6d41\u672c\u8d28\u4e0a\u662f\u4e00\u4e2a\u8bfa\u4f0a\u66fc\u6761\u4ef6\uff0c\u5373\u8bbe\u5b9a  $\\mathbf{w}^+ = \\mathbf{w}^-$  \u3002\u5bf9\u4e8e\u4e9a\u58f0\u901f\u6d41\u51fa\u7684\u60c5\u51b5\uff0c\u6211\u4eec\u4ecd\u7136\u9700\u8981\u5f3a\u52a0\u4e00\u4e2a\u80fd\u91cf\u503c\uff0c\u6211\u4eec\u4ece\u5404\u81ea\u7684\u51fd\u6570\u4e2d\u5f97\u51fa\u8fd9\u4e2a\u503c\u3002\u5bf9\u4e8e<i>backflow</i>\u7684\u60c5\u51b5\uff0c\u5373\u5728Neumann\u90e8\u5206\u6709\u52a8\u91cf\u901a\u5165\u57df\u7684\u60c5\u51b5\uff0c\u9700\u8981\u4e00\u4e2a\u7279\u6b8a\u7684\u6b65\u9aa4\u3002\u6839\u636e\u6587\u732e\uff08\u8fd9\u4e00\u4e8b\u5b9e\u53ef\u4ee5\u901a\u8fc7\u9002\u5f53\u7684\u80fd\u91cf\u8bba\u8bc1\u5f97\u51fa\uff09\uff0c\u6211\u4eec\u5fc5\u987b\u5207\u6362\u5230\u6d41\u5165\u90e8\u5206\u7684\u901a\u91cf\u7684\u53e6\u4e00\u4e2a\u53d8\u4f53\uff0c\u89c1Gravemeier, Comerford, Yoshihara, Ismail, Wall, \"A novel formulation for Neumann inflow conditions in biomechanics\", Int. J. Numer. Meth. \u751f\u7269\u533b\u5b66\u3002Eng., vol. 28 (2012). \u8fd9\u91cc\uff0c\u52a8\u91cf\u9879\u9700\u8981\u518d\u6b21\u6dfb\u52a0\uff0c\u8fd9\u76f8\u5f53\u4e8e\u53bb\u9664\u52a8\u91cf\u53d8\u91cf\u4e0a\u7684\u901a\u91cf\u8d21\u732e\u3002\u6211\u4eec\u5728\u540e\u5904\u7406\u6b65\u9aa4\u4e2d\u8fd9\u6837\u505a\uff0c\u800c\u4e14\u53ea\u9002\u7528\u4e8e\u6211\u4eec\u90fd\u5904\u4e8e\u5916\u6d41\u8fb9\u754c\u4e14\u6cd5\u5411\u91cf\u4e0e\u52a8\u91cf\uff08\u6216\u7b49\u540c\u4e8e\u901f\u5ea6\uff09\u4e4b\u95f4\u7684\u70b9\u79ef\u4e3a\u8d1f\u7684\u60c5\u51b5\u3002\u7531\u4e8e\u6211\u4eec\u5728SIMD\u77e2\u91cf\u5316\u4e2d\u4e00\u6b21\u5904\u7406\u591a\u4e2a\u6b63\u4ea4\u70b9\u7684\u6570\u636e\uff0c\u8fd9\u91cc\u9700\u8981\u660e\u786e\u5730\u5728SIMD\u6570\u7ec4\u7684\u6761\u76ee\u4e0a\u5faa\u73af\u3002\n\n// \u5728\u4e0b\u9762\u7684\u5b9e\u73b0\u4e2d\uff0c\u6211\u4eec\u5728\u6b63\u4ea4\u70b9\u7684\u5c42\u9762\u4e0a\u68c0\u67e5\u5404\u79cd\u7c7b\u578b\u7684\u8fb9\u754c\u3002\u5f53\u7136\uff0c\u6211\u4eec\u4e5f\u53ef\u4ee5\u5c06\u51b3\u5b9a\u6743\u79fb\u51fa\u6b63\u4ea4\u70b9\u5faa\u73af\uff0c\u5c06\u6574\u4e2a\u9762\u5b54\u89c6\u4e3a\u540c\u7c7b\uff0c\u8fd9\u5c31\u907f\u514d\u4e86\u5728\u6b63\u4ea4\u70b9\u7684\u5185\u5faa\u73af\u4e2d\u8fdb\u884c\u4e00\u4e9b\u5730\u56fe/\u96c6\u5408\u7684\u67e5\u627e\u3002\u7136\u800c\uff0c\u6548\u7387\u7684\u635f\u5931\u5e76\u4e0d\u660e\u663e\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u8fd9\u91cc\u9009\u62e9\u4e86\u66f4\u7b80\u5355\u7684\u4ee3\u7801\u3002\u8fd8\u8981\u6ce8\u610f\u7684\u662f\uff0c\u6700\u540e\u7684 \"else \"\u5b50\u53e5\u4f1a\u6355\u6349\u5230\u8fd9\u6837\u7684\u60c5\u51b5\uff0c\u5373\u8fb9\u754c\u7684\u67d0\u4e9b\u90e8\u5206\u6ca1\u6709\u901a\u8fc7 `EulerOperator::set_..._boundary(...)`. \u5206\u914d\u4efb\u4f55\u8fb9\u754c\u6761\u4ef6\u3002\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// \u4e0b\u4e00\u4e2a\u51fd\u6570\u5b9e\u73b0\u4e86\u8d28\u91cf\u77e9\u9635\u7684\u9006\u8fd0\u7b97\u3002\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u5e7f\u6cdb\u8ba8\u8bba\u4e86\u7b97\u6cd5\u548c\u539f\u7406\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u8fd9\u91cc\u53ea\u8ba8\u8bba MatrixFreeOperators::CellwiseInverseMassMatrix \u7c7b\u7684\u6280\u672f\u95ee\u9898\u3002\u5b83\u6240\u505a\u7684\u64cd\u4f5c\u4e0e\u8d28\u91cf\u77e9\u9635\u7684\u6b63\u5411\u8bc4\u4f30\u7c7b\u4f3c\uff0c\u53ea\u662f\u4f7f\u7528\u4e86\u4e0d\u540c\u7684\u63d2\u503c\u77e9\u9635\uff0c\u4ee3\u8868\u9006 $S^{-1}$ \u56e0\u5b50\u3002\u8fd9\u4e9b\u4ee3\u8868\u4e86\u4ece\u6307\u5b9a\u7684\u57fa\u7840\uff08\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u9ad8\u65af--\u6d1b\u5df4\u6258\u6b63\u4ea4\u516c\u5f0f\u70b9\u4e2d\u7684\u62c9\u683c\u6717\u65e5\u57fa\u7840\uff09\u5230\u9ad8\u65af\u6b63\u4ea4\u516c\u5f0f\u70b9\u4e2d\u7684\u62c9\u683c\u6717\u65e5\u57fa\u7840\u7684\u6539\u53d8\u3002\u5728\u540e\u8005\u7684\u57fa\u7840\u4e0a\uff0c\u6211\u4eec\u53ef\u4ee5\u5e94\u7528\u70b9\u7684\u9006\u5411`JxW`\u56e0\u5b50\uff0c\u5373\u6b63\u4ea4\u6743\u91cd\u4e58\u4ee5\u4ece\u53c2\u8003\u5750\u6807\u5230\u5b9e\u5750\u6807\u7684\u6620\u5c04\u7684\u96c5\u5404\u5e03\u7cfb\u6570\u3002\u4e00\u65e6\u5b8c\u6210\u4e86\u8fd9\u4e00\u64cd\u4f5c\uff0c\u57fa\u6570\u5c06\u518d\u6b21\u53d8\u56de\u8282\u70b9\u9ad8\u65af-\u6d1b\u5df4\u6258\u57fa\u6570\u3002\u6240\u6709\u8fd9\u4e9b\u64cd\u4f5c\u90fd\u7531\u4e0b\u9762\u7684 \"apply() \"\u51fd\u6570\u5b8c\u6210\u3002\u6211\u4eec\u9700\u8981\u63d0\u4f9b\u7684\u662f\u8981\u64cd\u4f5c\u7684\u5c40\u90e8\u573a\uff08\u6211\u4eec\u901a\u8fc7\u4e00\u4e2aFEEvaluation\u5bf9\u8c61\u4ece\u5168\u5c40\u5411\u91cf\u4e2d\u63d0\u53d6\uff09\uff0c\u5e76\u5c06\u7ed3\u679c\u5199\u56de\u8d28\u91cf\u77e9\u9635\u64cd\u4f5c\u7684\u76ee\u6807\u5411\u91cf\u3002\n\n// \u9700\u8981\u6ce8\u610f\u7684\u4e00\u70b9\u662f\uff0c\u6211\u4eec\u5728FEEvaluation\u7684\u6784\u9020\u51fd\u6570\u4e2d\u6dfb\u52a0\u4e86\u4e24\u4e2a\u6574\u6570\u53c2\u6570\uff08\u53ef\u9009\uff09\uff0c\u7b2c\u4e00\u4e2a\u662f0\uff08\u5728\u591aDoFHandler\u7cfb\u7edf\u4e2d\u9009\u62e9DoFHandler\uff1b\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u53ea\u6709\u4e00\u4e2a\uff09\uff0c\u7b2c\u4e8c\u4e2a\u662f1\uff0c\u7528\u4e8e\u8fdb\u884c\u6b63\u4ea4\u516c\u5f0f\u9009\u62e9\u3002\u7531\u4e8e\u6211\u4eec\u5c06\u6b63\u4ea4\u516c\u5f0f0\u7528\u4e8e\u975e\u7ebf\u6027\u9879\u7684\u8fc7\u5ea6\u79ef\u5206\uff0c\u6211\u4eec\u4f7f\u7528\u516c\u5f0f1\u4e0e\u9ed8\u8ba4\u7684 $p+1$ \uff08\u6216\u53d8\u91cf\u540d\u79f0\u4e2d\u7684`fe_degree+1`\uff09\u70b9\u7528\u4e8e\u8d28\u91cf\u77e9\u9635\u3002\u8fd9\u5bfc\u81f4\u4e86\u5bf9\u8d28\u91cf\u77e9\u9635\u7684\u5e73\u65b9\u8d21\u732e\uff0c\u5e76\u786e\u4fdd\u4e86\u7cbe\u786e\u7684\u79ef\u5206\uff0c\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\u3002\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// \u6211\u4eec\u73b0\u5728\u6765\u5230\u5b9e\u73b0\u6b27\u62c9\u7b97\u5b50\u6574\u4f53\u8bc4\u4f30\u7684\u51fd\u6570\uff0c\u5373 $\\mathcal M^{-1} \\mathcal L(t, \\mathbf{w})$  \uff0c\u8c03\u7528\u4e0a\u9762\u4ecb\u7ecd\u7684\u5c40\u90e8\u8bc4\u4f30\u5668\u3002\u8fd9\u4e9b\u6b65\u9aa4\u5728\u524d\u9762\u7684\u4ee3\u7801\u4e2d\u5e94\u8be5\u662f\u6e05\u695a\u7684\u3002\u9700\u8981\u6ce8\u610f\u7684\u4e00\u70b9\u662f\uff0c\u6211\u4eec\u9700\u8981\u8c03\u6574\u4e0e\u8fb9\u754c\u5404\u90e8\u5206\u76f8\u5173\u7684\u51fd\u6570\u4e2d\u7684\u65f6\u95f4\uff0c\u4ee5\u4fbf\u5728\u8fb9\u754c\u6570\u636e\u4e0e\u65f6\u95f4\u76f8\u5173\u7684\u60c5\u51b5\u4e0b\u4e0e\u65b9\u7a0b\u4e00\u81f4\u3002\u7136\u540e\uff0c\u6211\u4eec\u8c03\u7528 MatrixFree::loop() \u6765\u6267\u884c\u5355\u5143\u548c\u9762\u7684\u79ef\u5206\uff0c\u5305\u62ec\u5728`src`\u5411\u91cf\u4e2d\u8fdb\u884c\u5fc5\u8981\u7684ghost\u6570\u636e\u4ea4\u6362\u3002\u8be5\u51fd\u6570\u7684\u7b2c\u4e03\u4e2a\u53c2\u6570\uff0c\"true\"\uff0c\u6307\u5b9a\u6211\u4eec\u8981\u5728\u5f00\u59cb\u5411\u5176\u7d2f\u79ef\u79ef\u5206\u4e4b\u524d\uff0c\u5c06 \"dst \"\u5411\u91cf\u4f5c\u4e3a\u5faa\u73af\u7684\u4e00\u90e8\u5206\u5f52\u96f6\u3002\u8fd9\u4e2a\u53d8\u4f53\u6bd4\u5728\u5faa\u73af\u4e4b\u524d\u660e\u786e\u8c03\u7528`dst = 0.;`\u8981\u597d\uff0c\u56e0\u4e3a\u5f52\u96f6\u64cd\u4f5c\u662f\u5728\u77e2\u91cf\u7684\u5b50\u8303\u56f4\u5185\u5b8c\u6210\u7684\uff0c\u5176\u90e8\u5206\u662f\u7531\u9644\u8fd1\u7684\u79ef\u5206\u5199\u5165\u7684\u3002\u8fd9\u52a0\u5f3a\u4e86\u6570\u636e\u7684\u5b9a\u4f4d\uff0c\u5e76\u5141\u8bb8\u7f13\u5b58\uff0c\u8282\u7701\u4e86\u5411\u91cf\u6570\u636e\u5230\u4e3b\u5185\u5b58\u7684\u4e00\u6b21\u5f80\u8fd4\uff0c\u63d0\u9ad8\u4e86\u6027\u80fd\u3002\u5faa\u73af\u7684\u6700\u540e\u4e24\u4e2a\u53c2\u6570\u51b3\u5b9a\u4e86\u54ea\u4e9b\u6570\u636e\u88ab\u4ea4\u6362\uff1a\u7531\u4e8e\u6211\u4eec\u53ea\u8bbf\u95ee\u4e00\u4e2a\u9762\u7684\u5f62\u72b6\u51fd\u6570\u7684\u503c\uff0c\u8fd9\u662f\u5178\u578b\u7684\u4e00\u9636\u53cc\u66f2\u95ee\u9898\uff0c\u5e76\u4e14\u7531\u4e8e\u6211\u4eec\u6709\u4e00\u4e2a\u8282\u70b9\u57fa\u7840\uff0c\u8282\u70b9\u4f4d\u4e8e\u53c2\u8003\u5143\u7d20\u8868\u9762\uff0c\u6211\u4eec\u53ea\u9700\u8981\u4ea4\u6362\u8fd9\u4e9b\u90e8\u5206\u3002\u8fd9\u53c8\u8282\u7701\u4e86\u5b9d\u8d35\u7684\u5185\u5b58\u5e26\u5bbd\u3002\n\n// \u4e00\u65e6\u5e94\u7528\u4e86\u7a7a\u95f4\u7b97\u5b50 $\\mathcal L$ \uff0c\u6211\u4eec\u9700\u8981\u8fdb\u884c\u7b2c\u4e8c\u8f6e\u64cd\u4f5c\uff0c\u5e94\u7528\u53cd\u8d28\u91cf\u77e9\u9635\u3002\u8fd9\u91cc\uff0c\u6211\u4eec\u8c03\u7528 MatrixFree::cell_loop() \uff0c\u56e0\u4e3a\u53ea\u6709\u5355\u5143\u683c\u79ef\u5206\u51fa\u73b0\u3002\u5355\u5143\u5faa\u73af\u6bd4\u5168\u5faa\u73af\u66f4\u4fbf\u5b9c\uff0c\u56e0\u4e3a\u53ea\u8bbf\u95ee\u4e0e\u672c\u5730\u62e5\u6709\u7684\u5355\u5143\u76f8\u5173\u7684\u81ea\u7531\u5ea6\uff0c\u8fd9\u53ea\u662fDG\u79bb\u6563\u5316\u7684\u672c\u5730\u62e5\u6709\u7684\u81ea\u7531\u5ea6\u3002\u56e0\u6b64\uff0c\u8fd9\u91cc\u4e0d\u9700\u8981\u9b3c\u9b42\u4ea4\u6362\u3002\n\n// \u5728\u6240\u6709\u8fd9\u4e9b\u51fd\u6570\u7684\u5468\u56f4\uff0c\u6211\u4eec\u8bbe\u7f6e\u4e86\u5b9a\u65f6\u5668\u8303\u56f4\u6765\u8bb0\u5f55\u8ba1\u7b97\u65f6\u95f4\uff0c\u4ee5\u7edf\u8ba1\u5404\u90e8\u5206\u7684\u8d21\u732e\u3002\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// \u8ba9\u6211\u4eec\u8f6c\u5230\u505aRunge--Kutta\u66f4\u65b0\u7684\u6574\u4e2a\u9636\u6bb5\u7684\u51fd\u6570\u3002\u5b83\u8c03\u7528 EulerOperator::apply() \uff0c\u7136\u540e\u5bf9\u5411\u91cf\u8fdb\u884c\u4e00\u4e9b\u66f4\u65b0\uff0c\u5373`next_ri = solution + factor_ai * k_i`\u548c`solution += factor_solution * k_i`\u3002\u4e0e\u5176\u901a\u8fc7\u5411\u91cf\u63a5\u53e3\u6267\u884c\u8fd9\u4e9b\u6b65\u9aa4\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u63d0\u51fa\u4e86\u4e00\u4e2a\u66ff\u4ee3\u7b56\u7565\uff0c\u5728\u57fa\u4e8e\u7f13\u5b58\u7684\u67b6\u6784\u4e0a\u901f\u5ea6\u66f4\u5feb\u3002\u7531\u4e8e\u5411\u91cf\u6240\u6d88\u8017\u7684\u5185\u5b58\u5f80\u5f80\u6bd4\u7f13\u5b58\u6240\u80fd\u5bb9\u7eb3\u7684\u8981\u5927\u5f97\u591a\uff0c\u56e0\u6b64\u6570\u636e\u5fc5\u987b\u6709\u6548\u5730\u6765\u81ea\u7f13\u6162\u7684RAM\u5185\u5b58\u3002\u8fd9\u79cd\u60c5\u51b5\u53ef\u4ee5\u901a\u8fc7\u5faa\u73af\u878d\u5408\u6765\u6539\u5584\uff0c\u5373\u5728\u4e00\u6b21\u626b\u63cf\u4e2d\u5bf9`next_ki`\u548c`solution`\u8fdb\u884c\u66f4\u65b0\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u5c06\u8bfb\u53d6\u4e24\u4e2a\u5411\u91cf`rhs`\u548c`solution`\u5e76\u5199\u5165`next_ki`\u548c`solution`\uff0c\u800c\u5728\u57fa\u7ebf\u60c5\u51b5\u4e0b\uff0c\u81f3\u5c11\u67094\u6b21\u8bfb\u53d6\u548c\u4e24\u6b21\u5199\u5165\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u66f4\u8fdb\u4e00\u6b65\uff0c\u5f53\u8d28\u91cf\u77e9\u9635\u53cd\u8f6c\u5728\u5411\u91cf\u7684\u67d0\u4e00\u90e8\u5206\u5b8c\u6210\u540e\uff0c\u7acb\u5373\u6267\u884c\u5faa\u73af\u3002  MatrixFree::cell_loop() \u63d0\u4f9b\u4e86\u4e00\u79cd\u673a\u5236\uff0c\u5728\u5355\u5143\u683c\u7684\u5faa\u73af\u7b2c\u4e00\u6b21\u63a5\u89e6\u5230\u4e00\u4e2a\u5411\u91cf\u6761\u76ee\u4e4b\u524d\uff0c\u9644\u52a0\u4e00\u4e2a `std::function` \uff08\u6211\u4eec\u5728\u8fd9\u91cc\u6ca1\u6709\u4f7f\u7528\uff0c\u4f46\u7528\u4e8e\u4f8b\u5982\u5411\u91cf\u7684\u5f52\u96f6\uff09\uff0c\u4ee5\u53ca\u5728\u5faa\u73af\u6700\u540e\u63a5\u89e6\u5230\u4e00\u4e2a\u6761\u76ee\u4e4b\u540e\uff0c\u8c03\u7528\u7b2c\u4e8c\u4e2a `std::function` \u3002\u56de\u8c03\u7684\u5f62\u5f0f\u662f\u7ed9\u5b9a\u5411\u91cf\u4e0a\u7684\u4e00\u4e2a\u8303\u56f4\uff08\u5c31MPI\u5b87\u5b99\u4e2d\u7684\u672c\u5730\u7d22\u5f15\u7f16\u53f7\u800c\u8a00\uff09\uff0c\u53ef\u4ee5\u7531`local_element()`\u51fd\u6570\u6765\u5904\u7406\u3002\n\n// \u5bf9\u4e8e\u8fd9\u4e2a\u7b2c\u4e8c\u4e2a\u56de\u8c03\uff0c\u6211\u4eec\u521b\u5efa\u4e00\u4e2alambda\uff0c\u5728\u4e00\u4e2a\u8303\u56f4\u5185\u5de5\u4f5c\uff0c\u5e76\u5728\u8fd9\u4e2a\u8303\u56f4\u5185\u5199\u5165\u76f8\u5e94\u7684\u66f4\u65b0\u3002\u7406\u60f3\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u4f1a\u5728\u672c\u5730\u5faa\u73af\u4e4b\u524d\u6dfb\u52a0`DEAL_II_OPENMP_SIMD_PRAGMA`\uff0c\u4ee5\u5efa\u8bae\u7f16\u8bd1\u5668\u5bf9\u8fd9\u4e2a\u5faa\u73af\u8fdb\u884cSIMD\u5e76\u884c\u5316\uff08\u8fd9\u610f\u5473\u7740\u5728\u5b9e\u8df5\u4e2d\u6211\u4eec\u8981\u786e\u4fdd\u5728\u5faa\u73af\u5185\u90e8\u4f7f\u7528\u7684\u6307\u9488\u7684\u7d22\u5f15\u8303\u56f4\u4e4b\u95f4\u6ca1\u6709\u91cd\u53e0\uff0c\u4e5f\u79f0\u4e3a\u522b\u540d\uff09\u3002\u4e8b\u5b9e\u8bc1\u660e\uff0c\u5728\u5199\u8fd9\u7bc7\u6587\u7ae0\u7684\u65f6\u5019\uff0cGCC 7.2\u65e0\u6cd5\u7f16\u8bd1lambda\u51fd\u6570\u4e2d\u7684OpenMP pragma\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u4e0b\u9762\u6ce8\u91ca\u4e86\u8fd9\u4e2apragma\u3002\u5982\u679c\u4f60\u7684\u7f16\u8bd1\u5668\u6bd4\u8f83\u65b0\uff0c\u4f60\u5e94\u8be5\u53ef\u4ee5\u518d\u6b21\u53d6\u6d88\u6ce8\u91ca\u8fd9\u4e9b\u884c\u3002\n\n// \u6ce8\u610f\uff0c\u5f53\u6211\u4eec\u4e0d\u9700\u8981\u66f4\u65b0`next_ri`\u5411\u91cf\u65f6\uff0c\u6211\u4eec\u4e3a\u6700\u540e\u7684Runge--Kutta\u9636\u6bb5\u9009\u62e9\u4e0d\u540c\u7684\u4ee3\u7801\u8def\u5f84\u3002\u8fd9\u4e2a\u7b56\u7565\u5e26\u6765\u4e86\u76f8\u5f53\u5927\u7684\u901f\u5ea6\u63d0\u5347\u3002\u572840\u6838\u673a\u5668\u4e0a\uff0c\u9ed8\u8ba4\u77e2\u91cf\u66f4\u65b0\u65f6\uff0c\u9006\u8d28\u91cf\u77e9\u9635\u548c\u77e2\u91cf\u66f4\u65b0\u9700\u898160%\u4ee5\u4e0a\u7684\u8ba1\u7b97\u65f6\u95f4\uff0c\u800c\u5728\u66f4\u4f18\u5316\u7684\u53d8\u4f53\u4e2d\uff0c\u8fd9\u4e00\u6bd4\u4f8b\u7ea6\u4e3a35%\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u8fd9\u662f\u4e00\u4e2a\u5927\u7ea6\u4e09\u5206\u4e4b\u4e00\u7684\u901f\u5ea6\u63d0\u5347\u3002\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// \u5728\u8ba8\u8bba\u4e86\u5c06\u89e3\u63d0\u524d\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u51fd\u6570\u7684\u5b9e\u73b0\u540e\uff0c\u73b0\u5728\u8ba9\u6211\u4eec\u6765\u770b\u770b\u5b9e\u73b0\u5176\u4ed6\u8f85\u52a9\u6027\u64cd\u4f5c\u7684\u51fd\u6570\u3002\u5177\u4f53\u6765\u8bf4\uff0c\u8fd9\u4e9b\u662f\u8ba1\u7b97\u6295\u5f71\u3001\u8bc4\u4f30\u8bef\u5dee\u548c\u8ba1\u7b97\u5355\u5143\u4e0a\u4fe1\u606f\u4f20\u8f93\u901f\u5ea6\u7684\u51fd\u6570\u3002\n\n// \u8fd9\u4e9b\u51fd\u6570\u4e2d\u7684\u7b2c\u4e00\u4e2a\u57fa\u672c\u4e0a\u7b49\u540c\u4e8e VectorTools::project(), \uff0c\u53ea\u662f\u901f\u5ea6\u5feb\u5f97\u591a\uff0c\u56e0\u4e3a\u5b83\u662f\u4e13\u95e8\u9488\u5bf9DG\u5143\u7d20\u7684\uff0c\u4e0d\u9700\u8981\u8bbe\u7f6e\u548c\u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\uff0c\u56e0\u4e3a\u6bcf\u4e2a\u5143\u7d20\u90fd\u6709\u72ec\u7acb\u7684\u57fa\u51fd\u6570\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u5c55\u793a\u4ee3\u7801\u7684\u539f\u56e0\uff0c\u9664\u4e86\u8fd9\u4e2a\u975e\u5173\u952e\u64cd\u4f5c\u7684\u5c0f\u5e45\u63d0\u901f\u4e4b\u5916\uff0c\u8fd8\u56e0\u4e3a\u5b83\u663e\u793a\u4e86 MatrixFreeOperators::CellwiseInverseMassMatrix. \u63d0\u4f9b\u7684\u989d\u5916\u529f\u80fd\u3002\n\n// \u6295\u5f71\u64cd\u4f5c\u7684\u5de5\u4f5c\u539f\u7406\u5982\u4e0b\u3002\u5982\u679c\u6211\u4eec\u7528 $S$ \u8868\u793a\u5728\u6b63\u4ea4\u70b9\u8bc4\u4f30\u7684\u5f62\u72b6\u51fd\u6570\u77e9\u9635\uff0c\u90a3\u4e48\u5728\u5355\u5143\u683c $K$ \u4e0a\u7684\u6295\u5f71\u662f\u4e00\u4e2a\u5f62\u5f0f\u4e3a $\\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}$ \u7684\u64cd\u4f5c\uff0c\u5176\u4e2d $J^K$ \u662f\u5305\u542b\u96c5\u5404\u5e03\u7cfb\u6570\u4e58\u4ee5\u6b63\u4ea4\u6743\u91cd\uff08JxW\uff09\u7684\u5bf9\u89d2\u77e9\u9635\uff0c $\\mathcal M^K$ \u662f\u5355\u5143\u683c\u7684\u8d28\u91cf\u77e9\u9635\uff0c $\\tilde{\\mathbf{w}}(\\mathbf{x}_q)_{q=1:n_q}$ \u662f\u8981\u6295\u5f71\u5230\u6b63\u4ea4\u70b9\u7684\u9886\u57df\u8bc4\u4f30\u3002\u5b9e\u9645\u4e0a\uff0c\u77e9\u9635 $S$ \u901a\u8fc7\u5f20\u91cf\u79ef\u6709\u989d\u5916\u7684\u7ed3\u6784\uff0c\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\uff09\u3002\u8fd9\u4e2a\u7cfb\u7edf\u73b0\u5728\u53ef\u4ee5\u7b49\u6548\u5730\u5199\u6210 $\\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}$  \u3002\u73b0\u5728\uff0c\u9879 $S^{-1} S$ \u548c $\\left(J^K\\right)^{-1} J^K$ \u76f8\u62b5\u6d88\uff0c\u5bfc\u81f4\u6700\u540e\u7684\u8868\u8fbe\u5f0f $\\mathbf{w}^K = S^{-\\mathrm T} \\tilde{\\mathbf{w}}(\\mathbf{x}_q)_{q=1:n_q}$  \u3002\u8fd9\u4e2a\u64cd\u4f5c\u7531 MatrixFreeOperators::CellwiseInverseMassMatrix::transform_from_q_points_to_basis(). \u5b9e\u73b0\u3002\u8fd9\u4e2a\u540d\u5b57\u6765\u81ea\u4e8e\u8fd9\u4e2a\u6295\u5f71\u53ea\u662f\u4e58\u4ee5 $S^{-\\mathrm T}$ \uff0c\u4e00\u4e2a\u4ece\u9ad8\u65af\u6b63\u4ea4\u70b9\u7684\u8282\u70b9\u57fa\u5230\u7ed9\u5b9a\u7684\u6709\u9650\u5143\u57fa\u7684\u57fa\u6570\u53d8\u5316\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u8c03\u7528 FEEvaluation::set_dof_values() \u5c06\u7ed3\u679c\u5199\u5165\u77e2\u91cf\uff0c\u8986\u76d6\u4e4b\u524d\u7684\u5185\u5bb9\uff0c\u800c\u4e0d\u662f\u50cf\u5178\u578b\u7684\u79ef\u5206\u4efb\u52a1\u90a3\u6837\u7d2f\u79ef\u7ed3\u679c--\u6211\u4eec\u53ef\u4ee5\u8fd9\u6837\u505a\uff0c\u56e0\u4e3a\u5bf9\u4e8e\u4e0d\u8fde\u7eed\u7684Galerkin\u79bb\u6563\uff0c\u6bcf\u4e2a\u77e2\u91cf\u6761\u76ee\u90fd\u53ea\u6709\u4e00\u4e2a\u5355\u5143\u7684\u8d21\u732e\u3002\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// \u4e0b\u4e00\u4e2a\u51fd\u6570\u518d\u6b21\u91cd\u590d\u4e86\u540c\u6837\u7531deal.II\u5e93\u63d0\u4f9b\u7684\u529f\u80fd\uff0c\u5373 VectorTools::integrate_difference(). \u6211\u4eec\u5728\u8fd9\u91cc\u5c55\u793a\u4e86\u660e\u786e\u7684\u4ee3\u7801\uff0c\u4ee5\u5f3a\u8c03\u8de8\u51e0\u4e2a\u5355\u5143\u7684\u77e2\u91cf\u5316\u662f\u5982\u4f55\u5de5\u4f5c\u7684\uff0c\u4ee5\u53ca\u5982\u4f55\u901a\u8fc7\u8be5\u63a5\u53e3\u7d2f\u79ef\u7ed3\u679c\u3002\u56de\u987e\u4e00\u4e0b\uff0c\u6bcf\u4e2a<i>lane</i>\u7684\u77e2\u91cf\u5316\u6570\u7ec4\u6301\u6709\u6765\u81ea\u4e0d\u540c\u5355\u5143\u7684\u6570\u636e\u3002\u901a\u8fc7\u5bf9\u5f53\u524dMPI\u8fdb\u7a0b\u6240\u62e5\u6709\u7684\u6240\u6709\u5355\u5143\u6279\u7684\u5faa\u73af\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u586b\u5145\u4e00\u4e2a\u7ed3\u679c\u7684VectorizedArray\uff1b\u4e3a\u4e86\u5f97\u5230\u4e00\u4e2a\u5168\u5c40\u7684\u603b\u548c\uff0c\u6211\u4eec\u9700\u8981\u8fdb\u4e00\u6b65\u53bb\u5bf9SIMD\u9635\u5217\u4e2d\u7684\u6761\u76ee\u8fdb\u884c\u6c42\u548c\u3002\u7136\u800c\uff0c\u8fd9\u6837\u7684\u7a0b\u5e8f\u5e76\u4e0d\u7a33\u5b9a\uff0c\u56e0\u4e3aSIMD\u6570\u7ec4\u4e8b\u5b9e\u4e0a\u53ef\u80fd\u5e76\u4e0d\u6301\u6709\u5176\u6240\u6709\u901a\u9053\u7684\u6709\u6548\u6570\u636e\u3002\u5f53\u672c\u5730\u62e5\u6709\u7684\u5355\u5143\u7684\u6570\u91cf\u4e0d\u662fSIMD\u5bbd\u5ea6\u7684\u500d\u6570\u65f6\uff0c\u5c31\u4f1a\u53d1\u751f\u8fd9\u79cd\u60c5\u51b5\u3002\u4e3a\u4e86\u907f\u514d\u65e0\u6548\u6570\u636e\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u8bbf\u95ee\u6570\u636e\u65f6\u660e\u786e\u5730\u8df3\u8fc7\u90a3\u4e9b\u65e0\u6548\u7684\u901a\u9053\u3002\u867d\u7136\u4eba\u4eec\u53ef\u4ee5\u60f3\u8c61\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u7b80\u5355\u5730\u5c06\u7a7a\u8f66\u9053\u8bbe\u7f6e\u4e3a\u96f6\uff08\u4ece\u800c\u4e0d\u5bf9\u603b\u548c\u505a\u51fa\u8d21\u732e\uff09\u6765\u4f7f\u5176\u5de5\u4f5c\uff0c\u4f46\u60c5\u51b5\u6bd4\u8fd9\u66f4\u590d\u6742\u3002\u5982\u679c\u6211\u4eec\u8981\u4ece\u52a8\u91cf\u4e2d\u8ba1\u7b97\u51fa\u4e00\u4e2a\u901f\u5ea6\u5462\uff1f\u90a3\u4e48\uff0c\u6211\u4eec\u5c31\u9700\u8981\u9664\u4ee5\u5bc6\u5ea6\uff0c\u800c\u5bc6\u5ea6\u662f\u96f6--\u7ed3\u679c\u5c31\u4f1a\u662fNaN\uff0c\u5e76\u6c61\u67d3\u7ed3\u679c\u3002\u5f53\u6211\u4eec\u5728\u5355\u5143\u683c\u6279\u6b21\u4e2d\u5faa\u73af\u65f6\uff0c\u4f7f\u7528\u51fd\u6570 MatrixFree::n_active_entries_per_cell_batch() \u7ed9\u6211\u4eec\u63d0\u4f9b\u6709\u6548\u6570\u636e\u7684\u901a\u9053\u6570\uff0c\u7d2f\u79ef\u6709\u6548SIMD\u8303\u56f4\u5185\u7684\u7ed3\u679c\uff0c\u5c31\u53ef\u4ee5\u907f\u514d\u8fd9\u79cd\u9677\u9631\u3002\u5b83\u5728\u5927\u591a\u6570\u5355\u5143\u4e0a\u7b49\u4e8e VectorizedArray::size() \uff0c\u4f46\u5982\u679c\u5355\u5143\u6570\u4e0eSIMD\u5bbd\u5ea6\u76f8\u6bd4\u6709\u4f59\u6570\uff0c\u5219\u5728\u6700\u540e\u4e00\u4e2a\u5355\u5143\u6279\u4e0a\u53ef\u80fd\u4f1a\u66f4\u5c11\u3002\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\u7c7b\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u662f\u7528\u6765\u4f30\u8ba1\u4f20\u8f93\u901f\u5ea6\u7684\uff0c\u7531\u7f51\u683c\u5927\u5c0f\u7f29\u653e\uff0c\u8fd9\u4e0e\u8bbe\u7f6e\u663e\u5f0f\u65f6\u95f4\u79ef\u5206\u5668\u7684\u65f6\u95f4\u6b65\u957f\u6709\u5173\u3002\u5728\u6b27\u62c9\u65b9\u7a0b\u4e2d\uff0c\u6709\u4e24\u79cd\u4f20\u8f93\u901f\u5ea6\uff0c\u5373\u5bf9\u6d41\u901f\u5ea6 $\\mathbf{u}$ \u548c\u76f8\u5bf9\u4e8e\u4ee5\u901f\u5ea6 $\\mathbf u$ \u8fd0\u52a8\u7684\u4ecb\u8d28\u800c\u8a00\uff0c\u58f0\u6ce2\u7684\u4f20\u64ad\u901f\u5ea6 $c = \\sqrt{\\gamma p/\\rho}$  \u3002\n\n// \u5728\u65f6\u95f4\u6b65\u957f\u7684\u516c\u5f0f\u4e2d\uff0c\u6211\u4eec\u611f\u5174\u8da3\u7684\u4e0d\u662f\u8fd9\u4e9b\u7edd\u5bf9\u901f\u5ea6\uff0c\u800c\u662f\u4fe1\u606f\u7a7f\u8fc7\u4e00\u4e2a\u5355\u5143\u6240\u9700\u7684\u65f6\u95f4\u91cf\u3002\u5bf9\u4e8e\u4e0e\u4ecb\u8d28\u4e00\u8d77\u4f20\u8f93\u7684\u4fe1\u606f\uff0c $\\mathbf u$ \u662f\u7531\u7f51\u683c\u5927\u5c0f\u7f29\u653e\u7684\uff0c\u6240\u4ee5\u6700\u5927\u901f\u5ea6\u7684\u4f30\u8ba1\u53ef\u4ee5\u901a\u8fc7\u8ba1\u7b97 $\\|J^{-\\mathrm T} \\mathbf{u}\\|_\\infty$  \u5f97\u5230\uff0c\u5176\u4e2d $J$ \u662f\u5b9e\u57df\u5230\u53c2\u8003\u57df\u7684\u8f6c\u6362\u7684\u96c5\u5404\u5e03\u3002\u8bf7\u6ce8\u610f\uff0c FEEvaluationBase::inverse_jacobian() \u8fd4\u56de\u7684\u662f\u53cd\u8f6c\u548c\u8f6c\u7f6e\u7684\u96c5\u5404\u5e03\uff0c\u4ee3\u8868\u4ece\u5b9e\u6570\u5230\u53c2\u8003\u5750\u6807\u7684\u5ea6\u91cf\u9879\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u9700\u8981\u518d\u6b21\u8f6c\u7f6e\u3002\u6211\u4eec\u5728\u4e0b\u9762\u7684\u4ee3\u7801\u4e2d\u628a\u8fd9\u4e2a\u6781\u9650\u5b58\u50a8\u5728\u53d8\u91cf`convective_limit`\u4e2d\u3002\n\n// \u58f0\u97f3\u7684\u4f20\u64ad\u662f\u5404\u5411\u540c\u6027\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u9700\u8981\u8003\u8651\u5230\u4efb\u4f55\u65b9\u5411\u7684\u7f51\u683c\u5c3a\u5bf8\u3002\u7136\u540e\uff0c\u9002\u5f53\u7684\u7f51\u683c\u5927\u5c0f\u6bd4\u4f8b\u7531 $J$ \u7684\u6700\u5c0f\u5947\u5f02\u503c\u7ed9\u51fa\uff0c\u6216\u8005\uff0c\u7b49\u540c\u4e8e $J^{-1}$ \u7684\u6700\u5927\u5947\u5f02\u503c\u3002\u8bf7\u6ce8\u610f\uff0c\u5f53\u5ffd\u7565\u5f2f\u66f2\u7684\u5355\u5143\u65f6\uff0c\u53ef\u4ee5\u7528\u5355\u5143\u9876\u70b9\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u6765\u8fd1\u4f3c\u8fd9\u4e2a\u91cf\u3002\u4e3a\u4e86\u5f97\u5230Jacobian\u7684\u6700\u5927\u5947\u5f02\u503c\uff0c\u4e00\u822c\u7684\u7b56\u7565\u662f\u4f7f\u7528\u4e00\u4e9bLAPACK\u51fd\u6570\u3002\u7531\u4e8e\u6211\u4eec\u5728\u8fd9\u91cc\u9700\u8981\u7684\u53ea\u662f\u4e00\u4e2a\u4f30\u8ba1\u503c\uff0c\u6240\u4ee5\u6211\u4eec\u53ef\u4ee5\u907f\u514d\u5c06\u4e00\u4e2a\u5411\u91cf\u6570\u7ec4\u7684\u5f20\u91cf\u5206\u89e3\u6210\u51e0\u4e2a\u77e9\u9635\u7684\u9ebb\u70e6\uff0c\u5e76\u5728\u6ca1\u6709\u5411\u91cf\u7684\u60c5\u51b5\u4e0b\u8fdb\u5165\u4e00\u4e2a\uff08\u6602\u8d35\u7684\uff09\u7279\u5f81\u503c\u51fd\u6570\uff0c\u800c\u662f\u4f7f\u7528\u5e94\u7528\u4e8e $J^{-1}J^{-\\mathrm T}$ \u7684\u5e42\u65b9\u6cd5\u8fdb\u884c\u51e0\u6b21\u8fed\u4ee3\uff08\u5728\u4e0b\u9762\u7684\u4ee3\u7801\u4e2d\u4e3a\u4e94\u6b21\uff09\u3002\u8fd9\u79cd\u65b9\u6cd5\u7684\u6536\u655b\u901f\u5ea6\u53d6\u51b3\u4e8e\u6700\u5927\u7279\u5f81\u503c\u4e0e\u6b21\u5927\u7279\u5f81\u503c\u7684\u6bd4\u7387\u4ee5\u53ca\u521d\u59cb\u731c\u6d4b\uff0c\u5373\u6240\u67091\u7684\u77e2\u91cf\u3002\u8fd9\u53ef\u80fd\u8868\u660e\uff0c\u6211\u4eec\u5728\u63a5\u8fd1\u7acb\u65b9\u4f53\u5f62\u72b6\u7684\u5355\u5143\u4e0a\u5f97\u5230\u7f13\u6162\u7684\u6536\u655b\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6240\u6709\u7684\u957f\u5ea6\u51e0\u4e4e\u90fd\u662f\u4e00\u6837\u7684\u3002\u7136\u800c\uff0c\u8fd9\u79cd\u7f13\u6162\u7684\u6536\u655b\u610f\u5473\u7740\u7ed3\u679c\u5c06\u4f4d\u4e8e\u4e24\u4e2a\u6700\u5927\u7684\u5947\u5f02\u503c\u4e4b\u95f4\uff0c\u800c\u8fd9\u4e24\u4e2a\u5947\u5f02\u503c\u65e0\u8bba\u5982\u4f55\u90fd\u662f\u63a5\u8fd1\u6700\u5927\u503c\u7684\u3002\u5728\u6240\u6709\u5176\u4ed6\u60c5\u51b5\u4e0b\uff0c\u6536\u655b\u5c06\u662f\u5feb\u901f\u7684\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u53ef\u4ee5\u53ea\u5728\u8fd9\u91cc\u786c\u7f16\u78015\u6b21\u8fed\u4ee3\uff0c\u5e76\u786e\u4fe1\u7ed3\u679c\u662f\u597d\u7684\u3002\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// \u4e0e\u524d\u9762\u7684\u51fd\u6570\u7c7b\u4f3c\uff0c\u6211\u4eec\u5fc5\u987b\u786e\u4fdd\u53ea\u5728\u4e00\u4e2a\u5355\u5143\u683c\u6279\u6b21\u7684\u6709\u6548\u5355\u5143\u683c\u4e0a\u79ef\u7d2f\u901f\u5ea6\u3002\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// \u8be5\u7c7b\u5c06EulerOperator\u7c7b\u4e0e\u65f6\u95f4\u79ef\u5206\u5668\u548c\u901a\u5e38\u7684\u5168\u5c40\u6570\u636e\u7ed3\u6784\uff08\u5982FiniteElement\u548cDoFHandler\uff09\u76f8\u7ed3\u5408\uff0c\u4ee5\u5b9e\u9645\u8fd0\u884cEuler\u95ee\u9898\u7684\u6a21\u62df\u3002\n\n// \u6210\u5458\u53d8\u91cf\u662f\u4e00\u4e2a\u4e09\u89d2\u5f62\u3001\u4e00\u4e2a\u6709\u9650\u5143\u3001\u4e00\u4e2a\u6620\u5c04\uff08\u7528\u4e8e\u521b\u5efa\u9ad8\u9636\u66f2\u9762\uff0c\u89c1 step-10 \uff09\uff0c\u4ee5\u53ca\u4e00\u4e2a\u63cf\u8ff0\u81ea\u7531\u5ea6\u7684DoFHandler\u3002\u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u4fdd\u7559\u4e86\u4e0a\u9762\u63cf\u8ff0\u7684EulerOperator\u7684\u5b9e\u4f8b\uff0c\u5b83\u5c06\u5b8c\u6210\u6240\u6709\u79ef\u5206\u65b9\u9762\u7684\u7e41\u91cd\u5de5\u4f5c\uff0c\u4ee5\u53ca\u4e00\u4e9b\u65f6\u95f4\u79ef\u5206\u7684\u53c2\u6570\uff0c\u5982\u5f53\u524d\u65f6\u95f4\u6216\u65f6\u95f4\u6b65\u957f\u3002\n\n// \u6b64\u5916\uff0c\u6211\u4eec\u4f7f\u7528\u4e00\u4e2aPostProcessor\u5b9e\u4f8b\u6765\u5411\u8f93\u51fa\u6587\u4ef6\u5199\u5165\u4e00\u4e9b\u989d\u5916\u7684\u4fe1\u606f\uff0c\u8fd9\u4e0e  step-33  \u4e2d\u7684\u505a\u6cd5\u7c7b\u4f3c\u3002DataPostprocessor\u7c7b\u7684\u63a5\u53e3\u5f88\u76f4\u89c2\uff0c\u8981\u6c42\u6211\u4eec\u63d0\u4f9b\u5173\u4e8e\u9700\u8981\u8bc4\u4f30\u7684\u4fe1\u606f\uff08\u901a\u5e38\u53ea\u6709\u89e3\u51b3\u65b9\u6848\u7684\u503c\uff0c\u9664\u4e86Schlieren\u56fe\uff0c\u6211\u4eec\u53ea\u5728\u4e8c\u7ef4\u4e2d\u542f\u7528\u5b83\u662f\u6709\u610f\u4e49\u7684\uff09\uff0c\u4ee5\u53ca\u88ab\u8bc4\u4f30\u7684\u4e1c\u897f\u7684\u540d\u79f0\u3002\u8bf7\u6ce8\u610f\uff0c\u4e5f\u53ef\u4ee5\u901a\u8fc7\u53ef\u89c6\u5316\u7a0b\u5e8f\uff08\u5982ParaView\uff09\u4e2d\u7684\u8ba1\u7b97\u5668\u5de5\u5177\u6765\u63d0\u53d6\u5927\u90e8\u5206\u4fe1\u606f\uff0c\u4f46\u5728\u5199\u8f93\u51fa\u65f6\u5c31\u5df2\u7ecf\u505a\u4e86\uff0c\u8fd9\u8981\u65b9\u4fbf\u5f97\u591a\u3002\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// \u5bf9\u4e8e\u5b57\u6bb5\u53d8\u91cf\u7684\u4e3b\u8981\u8bc4\u4f30\uff0c\u6211\u4eec\u9996\u5148\u68c0\u67e5\u6570\u7ec4\u7684\u957f\u5ea6\u662f\u5426\u7b49\u4e8e\u9884\u671f\u503c\uff08\u957f\u5ea6`2*dim+4`\u6216`2*dim+5`\u6765\u81ea\u6211\u4eec\u5728\u4e0b\u9762get_names()\u51fd\u6570\u4e2d\u6307\u5b9a\u7684\u540d\u5b57\u7684\u5927\u5c0f\uff09\u3002\u7136\u540e\u6211\u4eec\u5728\u6240\u6709\u7684\u8bc4\u4f30\u70b9\u4e0a\u5faa\u73af\uff0c\u586b\u5145\u76f8\u5e94\u7684\u4fe1\u606f\u3002\u9996\u5148\uff0c\u6211\u4eec\u586b\u5199\u5bc6\u5ea6 $\\rho$ \u3001\u52a8\u91cf $\\rho \\mathbf{u}$ \u548c\u80fd\u91cf $E$ \u7684\u539f\u59cb\u89e3\u53d8\u91cf\uff0c\u7136\u540e\u6211\u4eec\u8ba1\u7b97\u5f97\u51fa\u901f\u5ea6 $\\mathbf u$ \u3001\u538b\u529b $p$ \u3001\u58f0\u901f $c=\\sqrt{\\gamma p / \\rho}$ \uff0c\u4ee5\u53ca\u663e\u793a $s = |\\nabla \\rho|^2$ \u7684Schlieren\u56fe\uff0c\u5982\u679c\u5b83\u88ab\u542f\u7528\u3002\u53c2\u89c1 step-69 \u4e2d\u53e6\u4e00\u4e2a\u521b\u5efaSchlieren\u56fe\u7684\u4f8b\u5b50\uff09\u3002\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// \u5bf9\u4e8e\u91cf\u7684\u89e3\u91ca\uff0c\u6211\u4eec\u6709\u6807\u91cf\u5bc6\u5ea6\u3001\u80fd\u91cf\u3001\u538b\u529b\u3001\u58f0\u901f\u548cSchlieren\u56fe\uff0c\u4ee5\u53ca\u52a8\u91cf\u548c\u901f\u5ea6\u7684\u5411\u91cf\u3002\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// \u5173\u4e8e\u5fc5\u8981\u7684\u66f4\u65b0\u6807\u5fd7\uff0c\u6211\u4eec\u53ea\u9700\u8981\u6240\u6709\u6570\u91cf\u7684\u503c\uff0c\u4f46Schlieren\u56fe\u9664\u5916\uff0c\u5b83\u662f\u57fa\u4e8e\u5bc6\u5ea6\u68af\u5ea6\u7684\u3002\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// \u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u5e76\u4e0d\u4ee4\u4eba\u60ca\u8bb6\u3002\u6211\u4eec\u8bbe\u7f6e\u4e86\u4e00\u4e2a\u57fa\u4e8e \"MPI_COMM_WORLD \"\u901a\u4fe1\u5668\u7684\u5e73\u884c\u4e09\u89d2\u5f62\uff0c\u4e00\u4e2a\u5177\u6709 \"dim+2 \"\u5206\u91cf\u7684\u5bc6\u5ea6\u3001\u52a8\u91cf\u548c\u80fd\u91cf\u7684\u77e2\u91cf\u6709\u9650\u5143\uff0c\u4e00\u4e2a\u4e0e\u5e95\u5c42\u6709\u9650\u5143\u76f8\u540c\u7a0b\u5ea6\u7684\u9ad8\u9636\u6620\u5c04\uff0c\u5e76\u5c06\u65f6\u95f4\u548c\u65f6\u95f4\u6b65\u957f\u521d\u59cb\u5316\u4e3a\u96f6\u3002\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// \u4f5c\u4e3a\u4e00\u4e2a\u7f51\u683c\uff0c\u672c\u6559\u7a0b\u7a0b\u5e8f\u5b9e\u73b0\u4e86\u4e24\u79cd\u9009\u62e9\uff0c\u53d6\u51b3\u4e8e\u5168\u5c40\u53d8\u91cf`testcase`\u3002\u5bf9\u4e8e\u5206\u6790\u578b\u53d8\u91cf\uff08`testcase==0`\uff09\uff0c\u57df\u662f $(0, 10) \\times (-5, 5)$ \uff0c\u57df\u7684\u56db\u5468\u90fd\u6709\u8fea\u91cc\u5e0c\u7279\u8fb9\u754c\u6761\u4ef6\uff08\u6d41\u5165\uff09\u3002\u5bf9\u4e8e \"testcase==1\"\uff0c\u6211\u4eec\u5c06\u57df\u8bbe\u7f6e\u4e3a\u77e9\u5f62\u7bb1\u4e2d\u7684\u5706\u67f1\u4f53\uff0c\u6e90\u81eaSch&auml;fer\u548cTurek\uff081996\uff09\u5bf9\u4e0d\u53ef\u538b\u7f29\u7684\u7c98\u6027\u6d41\u52a8\u7684\u5706\u67f1\u4f53\u7684\u6d41\u52a8\u6d4b\u8bd5\u6848\u4f8b\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u6709\u66f4\u591a\u79cd\u7c7b\u7684\u8fb9\u754c\u3002\u901a\u9053\u5de6\u4fa7\u7684\u6d41\u5165\u90e8\u5206\u662f\u7ed9\u5b9a\u7684\u6d41\u5165\u7c7b\u578b\uff0c\u4e3a\u6b64\u6211\u4eec\u9009\u62e9\u4e86\u4e00\u4e2a\u6052\u5b9a\u7684\u6d41\u5165\u8f6e\u5ed3\uff0c\u800c\u6211\u4eec\u5728\u53f3\u4fa7\u8bbe\u7f6e\u4e86\u4e00\u4e2a\u4e9a\u58f0\u901f\u7684\u6d41\u51fa\u3002\u5bf9\u4e8e\u5706\u67f1\u4f53\u5468\u56f4\u7684\u8fb9\u754c\uff08\u8fb9\u754cid\u7b49\u4e8e2\uff09\u4ee5\u53ca\u901a\u9053\u58c1\uff08\u8fb9\u754cid\u7b49\u4e8e3\uff09\uff0c\u6211\u4eec\u4f7f\u7528\u58c1\u7684\u8fb9\u754c\u7c7b\u578b\uff0c\u5373\u65e0\u6b63\u6001\u6d41\u3002\u6b64\u5916\uff0c\u5bf9\u4e8e\u4e09\u7ef4\u5706\u67f1\u4f53\uff0c\u6211\u4eec\u8fd8\u5728\u5782\u76f4\u65b9\u5411\u4e0a\u589e\u52a0\u4e86\u4e00\u4e2a\u91cd\u529b\u3002\u6709\u4e86\u57fa\u7840\u7f51\u683c\uff08\u5305\u62ec\u7531 GridGenerator::channel_with_cylinder()), \u8bbe\u7f6e\u7684\u6d41\u5f62\uff09\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u6267\u884c\u6307\u5b9a\u6570\u91cf\u7684\u5168\u5c40\u7ec6\u5316\uff0c\u4eceDoFHandler\u521b\u5efa\u672a\u77e5\u7684\u7f16\u53f7\uff0c\u5e76\u5c06DoFHandler\u548cMapping\u5bf9\u8c61\u4ea4\u7ed9EulerOperator\u7684\u521d\u59cb\u5316\u3002\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// \u5728\u4e0b\u6587\u4e2d\uff0c\u6211\u4eec\u8f93\u51fa\u4e00\u4e9b\u5173\u4e8e\u95ee\u9898\u7684\u7edf\u8ba1\u6570\u636e\u3002\u56e0\u4e3a\u6211\u4eec\u7ecf\u5e38\u4f1a\u51fa\u73b0\u76f8\u5f53\u591a\u7684\u5355\u5143\u683c\u6216\u81ea\u7531\u5ea6\uff0c\u6240\u4ee5\u6211\u4eec\u5e0c\u671b\u7528\u9017\u53f7\u6765\u5206\u9694\u6bcf\u4e00\u7ec4\u7684\u4e09\u4f4d\u6570\u6765\u6253\u5370\u5b83\u4eec\u3002\u8fd9\u53ef\u4ee5\u901a\u8fc7 \"locales \"\u6765\u5b9e\u73b0\uff0c\u5c3d\u7ba1\u8fd9\u79cd\u5de5\u4f5c\u65b9\u5f0f\u4e0d\u662f\u7279\u522b\u76f4\u89c2\u3002  step-32 \u5bf9\u6b64\u6709\u7a0d\u5fae\u8be6\u7ec6\u7684\u89e3\u91ca\u3002\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// \u5bf9\u4e8e\u8f93\u51fa\uff0c\u6211\u4eec\u9996\u5148\u8ba9\u6b27\u62c9\u7b97\u5b50\u8ba1\u7b97\u51fa\u6570\u503c\u7ed3\u679c\u7684\u8bef\u5dee\u3002\u66f4\u786e\u5207\u5730\u8bf4\uff0c\u5bf9\u4e8e\u5206\u6790\u89e3\u7684\u60c5\u51b5\uff0c\u6211\u4eec\u8ba1\u7b97\u4e0e\u5206\u6790\u7ed3\u679c\u7684\u8bef\u5dee\uff0c\u800c\u5bf9\u4e8e\u7b2c\u4e8c\u4e2a\u6d4b\u8bd5\u60c5\u51b5\uff0c\u6211\u4eec\u8ba1\u7b97\u4e0e\u5bc6\u5ea6\u548c\u80fd\u91cf\u6052\u5b9a\u7684\u80cc\u666f\u573a\u4ee5\u53ca $x$ \u65b9\u5411\u7684\u6052\u5b9a\u901f\u5ea6\u7684\u504f\u5dee\u3002\n\n// \u4e0b\u4e00\u6b65\u662f\u521b\u5efa\u8f93\u51fa\u3002\u8fd9\u4e0e step-33 \u4e2d\u7684\u505a\u6cd5\u7c7b\u4f3c\uff1a\u6211\u4eec\u8ba9\u4e0a\u9762\u5b9a\u4e49\u7684\u540e\u5904\u7406\u5668\u63a7\u5236\u5927\u90e8\u5206\u7684\u8f93\u51fa\uff0c\u9664\u4e86\u6211\u4eec\u76f4\u63a5\u5199\u7684\u539f\u59cb\u573a\u3002\u5bf9\u4e8e\u5206\u6790\u89e3\u7684\u6d4b\u8bd5\u6848\u4f8b\uff0c\u6211\u4eec\u8fd8\u5bf9\u5206\u6790\u89e3\u8fdb\u884c\u4e86\u53e6\u4e00\u6b21\u6295\u5f71\uff0c\u5e76\u6253\u5370\u51fa\u8be5\u573a\u548c\u6570\u503c\u89e3\u4e4b\u95f4\u7684\u5dee\u5f02\u3002\u4e00\u65e6\u6211\u4eec\u5b9a\u4e49\u4e86\u6240\u6709\u8981\u5199\u7684\u91cf\uff0c\u6211\u4eec\u5c31\u5efa\u7acb\u8f93\u51fa\u7684\u8865\u4e01\u3002\u4e0e step-65 \u7c7b\u4f3c\uff0c\u6211\u4eec\u901a\u8fc7\u8bbe\u7f6e\u9002\u5f53\u7684\u6807\u5fd7\u6765\u521b\u5efa\u4e00\u4e2a\u9ad8\u9636VTK\u8f93\u51fa\uff0c\u8fd9\u4f7f\u6211\u4eec\u80fd\u591f\u53ef\u89c6\u5316\u9ad8\u591a\u9879\u5f0f\u5ea6\u7684\u573a\u3002\u6700\u540e\uff0c\u6211\u4eec\u8c03\u7528 `DataOutInterface::write_vtu_in_parallel()` \u51fd\u6570\uff0c\u5c06\u7ed3\u679c\u5199\u5165\u7ed9\u5b9a\u7684\u6587\u4ef6\u540d\u3002\u8fd9\u4e2a\u51fd\u6570\u4f7f\u7528\u4e86\u7279\u6b8a\u7684MPI\u5e76\u884c\u5199\u8bbe\u65bd\uff0c\u4e0e\u5176\u4ed6\u5927\u591a\u6570\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u7684\u6807\u51c6\u5e93\u7684 `std::ofstream` \u53d8\u4f53\u76f8\u6bd4\uff0c\u5b83\u901a\u5e38\u5bf9\u5e76\u884c\u6587\u4ef6\u7cfb\u7edf\u66f4\u52a0\u4f18\u5316\u3002`write_vtu_in_parallel()`\u51fd\u6570\u7684\u4e00\u4e2a\u7279\u522b\u597d\u7684\u7279\u70b9\u662f\uff0c\u5b83\u53ef\u4ee5\u5c06\u6240\u6709MPI\u884c\u5217\u7684\u8f93\u51fa\u5408\u5e76\u5230\u4e00\u4e2a\u6587\u4ef6\u4e2d\uff0c\u4f7f\u5f97\u6ca1\u6709\u5fc5\u8981\u6709\u4e00\u4e2a\u6240\u6709\u6b64\u7c7b\u6587\u4ef6\u7684\u4e2d\u592e\u8bb0\u5f55\uff08\u5373 \"pvtu \"\u6587\u4ef6\uff09\u3002\n\n// \u5bf9\u4e8e\u5e76\u884c\u7a0b\u5e8f\u6765\u8bf4\uff0c\u770b\u4e00\u4e0b\u5355\u5143\u5728\u5904\u7406\u5668\u4e4b\u95f4\u7684\u5212\u5206\u5f80\u5f80\u662f\u6709\u542f\u53d1\u7684\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u53ef\u4ee5\u5411 DataOut::add_data_vector() \u4f20\u9012\u4e00\u4e2a\u6570\u5b57\u5411\u91cf\uff0c\u5176\u4e2d\u5305\u542b\u4e0e\u5f53\u524d\u5904\u7406\u5668\u62e5\u6709\u7684\u6d3b\u52a8\u5355\u5143\u4e00\u6837\u591a\u7684\u6761\u76ee\uff1b\u7136\u540e\u8fd9\u4e9b\u6570\u5b57\u5e94\u8be5\u662f\u62e5\u6709\u8fd9\u4e9b\u5355\u5143\u7684\u5904\u7406\u5668\u7684\u7b49\u7ea7\u3002\u4f8b\u5982\uff0c\u8fd9\u6837\u4e00\u4e2a\u5411\u91cf\u53ef\u4ee5\u4ece GridTools::get_subdomain_association(). \u4e2d\u83b7\u5f97\u3002\u53e6\u4e00\u65b9\u9762\uff0c\u5728\u6bcf\u4e2aMPI\u8fdb\u7a0b\u4e2d\uff0cDataOut\u5c06\u53ea\u8bfb\u53d6\u90a3\u4e9b\u5bf9\u5e94\u4e8e\u672c\u5730\u62e5\u6709\u7684\u5355\u5143\u7684\u6761\u76ee\uff0c\u8fd9\u4e9b\u6761\u76ee\u5f53\u7136\u90fd\u6709\u76f8\u540c\u7684\u503c\uff1a\u5373\u5f53\u524d\u8fdb\u7a0b\u7684\u7b49\u7ea7\u3002\u77e2\u91cf\u7684\u5176\u4f59\u6761\u76ee\u4e2d\u7684\u5185\u5bb9\u5b9e\u9645\u4e0a\u5e76\u4e0d\u91cd\u8981\uff0c\u56e0\u6b64\u6211\u4eec\u53ef\u4ee5\u7528\u4e00\u4e2a\u5ec9\u4ef7\u7684\u6280\u5de7\u9003\u8131\u3002\u6211\u4eec\u53ea\u662f\u628a\u6211\u4eec\u7ed9 DataOut::add_data_vector() \u7684\u5411\u91cf\u7684\u6240\u6709*\u503c\u90fd\u586b\u4e0a\u5f53\u524dMPI\u8fdb\u7a0b\u7684\u7b49\u7ea7\u3002\u5173\u952e\u662f\u5728\u6bcf\u4e2a\u8fdb\u7a0b\u4e2d\uff0c\u53ea\u6709\u5bf9\u5e94\u4e8e\u672c\u5730\u62e5\u6709\u7684\u5355\u5143\u683c\u7684\u6761\u76ee\u4f1a\u88ab\u8bfb\u53d6\uff0c\u800c\u5ffd\u7565\u5176\u4ed6\u6761\u76ee\u4e2d\u7684\uff08\u9519\u8bef\uff09\u503c\u3002\u4e8b\u5b9e\u4e0a\uff0c\u6bcf\u4e2a\u8fdb\u7a0b\u63d0\u4ea4\u7684\u5411\u91cf\u4e2d\u7684\u6761\u76ee\u5b50\u96c6\u662f\u6b63\u786e\u7684\uff0c\u8fd9\u5c31\u8db3\u591f\u4e86\u3002\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() \u51fd\u6570\u5c06\u6240\u6709\u7684\u90e8\u5206\u7ec4\u5408\u8d77\u6765\u3002\u5b83\u9996\u5148\u8c03\u7528\u521b\u5efa\u7f51\u683c\u548c\u8bbe\u7f6e\u6570\u636e\u7ed3\u6784\u7684\u51fd\u6570\uff0c\u7136\u540e\u521d\u59cb\u5316\u65f6\u95f4\u79ef\u5206\u5668\u548c\u4f4e\u5b58\u50a8\u79ef\u5206\u5668\u7684\u4e24\u4e2a\u4e34\u65f6\u5411\u91cf\u3002\u6211\u4eec\u79f0\u8fd9\u4e9b\u5411\u91cf\u4e3a`rk_register_1`\u548c`rk_register_2`\uff0c\u5e76\u4f7f\u7528\u7b2c\u4e00\u4e2a\u5411\u91cf\u8868\u793a $\\mathbf{r}_i$ \uff0c\u7b2c\u4e8c\u4e2a\u5411\u91cf\u8868\u793a $\\mathbf{k}_i$ \uff0c\u5728\u4ecb\u7ecd\u4e2d\u6982\u8ff0\u7684Runge--Kutta\u65b9\u6848\u7684\u516c\u5f0f\u3002\u5728\u6211\u4eec\u5f00\u59cb\u65f6\u95f4\u5faa\u73af\u4e4b\u524d\uff0c\u6211\u4eec\u901a\u8fc7 `EulerOperator::compute_cell_transport_speed()` \u51fd\u6570\u8ba1\u7b97\u65f6\u95f4\u6b65\u957f\u3002\u4e3a\u4e86\u4fbf\u4e8e\u6bd4\u8f83\uff0c\u6211\u4eec\u5c06\u90a3\u91cc\u5f97\u5230\u7684\u7ed3\u679c\u4e0e\u6700\u5c0f\u7f51\u683c\u5c3a\u5bf8\u8fdb\u884c\u6bd4\u8f83\uff0c\u5e76\u5c06\u5b83\u4eec\u6253\u5370\u5230\u5c4f\u5e55\u4e0a\u3002\u5bf9\u4e8e\u50cf\u672c\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u63a5\u8fd1\u4e8e\u7edf\u4e00\u7684\u58f0\u901f\u548c\u901f\u5ea6\uff0c\u9884\u6d4b\u7684\u6709\u6548\u7f51\u683c\u5c3a\u5bf8\u5c06\u662f\u63a5\u8fd1\u7684\uff0c\u4f46\u5982\u679c\u7f29\u653e\u6bd4\u4f8b\u4e0d\u540c\uff0c\u5b83\u4eec\u53ef\u80fd\u4f1a\u6709\u53d8\u5316\u3002\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// \u73b0\u5728\u6211\u4eec\u51c6\u5907\u5f00\u59cb\u65f6\u95f4\u5faa\u73af\uff0c\u6211\u4eec\u4e00\u76f4\u8fd0\u884c\u5230\u65f6\u95f4\u8fbe\u5230\u9884\u671f\u7684\u7ed3\u675f\u65f6\u95f4\u3002\u6bcf\u96945\u4e2a\u65f6\u95f4\u6b65\u957f\uff0c\u6211\u4eec\u5c31\u8ba1\u7b97\u4e00\u4e2a\u65b0\u7684\u65f6\u95f4\u6b65\u957f\u4f30\u8ba1\u503c--\u7531\u4e8e\u89e3\u51b3\u65b9\u6848\u662f\u975e\u7ebf\u6027\u7684\uff0c\u5728\u6a21\u62df\u8fc7\u7a0b\u4e2d\u8c03\u6574\u8fd9\u4e2a\u503c\u662f\u6700\u6709\u6548\u7684\u3002\u5982\u679cCourant\u6570\u9009\u62e9\u5f97\u8fc7\u4e8e\u6fc0\u8fdb\uff0c\u6a21\u62df\u901a\u5e38\u4f1a\u5728\u65f6\u95f4\u6b65\u6570\u4e3aNaN\u65f6\u7206\u70b8\uff0c\u6240\u4ee5\u5728\u8fd9\u91cc\u5f88\u5bb9\u6613\u53d1\u73b0\u3002\u6709\u4e00\u70b9\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0c\u7531\u4e8e\u4e0d\u540c\u7684\u65f6\u95f4\u6b65\u957f\u9009\u62e9\u7684\u76f8\u4e92\u4f5c\u7528\uff0c\u56db\u820d\u4e94\u5165\u7684\u8bef\u5dee\u53ef\u80fd\u4f1a\u4f20\u64ad\u5230\u524d\u51e0\u4f4d\u6570\uff0c\u4ece\u800c\u5bfc\u81f4\u7565\u6709\u4e0d\u540c\u7684\u89e3\u51b3\u65b9\u6848\u3002\u4e3a\u4e86\u964d\u4f4e\u8fd9\u79cd\u654f\u611f\u6027\uff0c\u901a\u5e38\u7684\u505a\u6cd5\u662f\u5c06\u65f6\u95f4\u6b65\u957f\u56db\u820d\u4e94\u5165\u6216\u622a\u65ad\u5230\u51e0\u4f4d\u6570\uff0c\u4f8b\u5982\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\u662f3\u3002\u5982\u679c\u5f53\u524d\u65f6\u95f4\u63a5\u8fd1\u89c4\u5b9a\u7684\u8f93\u51fa \"\u523b\u5ea6 \"\u503c\uff08\u59820.02\uff09\uff0c\u6211\u4eec\u4e5f\u4f1a\u5199\u51fa\u8f93\u51fa\u3002\u5728\u65f6\u95f4\u5faa\u73af\u7ed3\u675f\u540e\uff0c\u6211\u4eec\u901a\u8fc7\u6253\u5370\u4e00\u4e9b\u7edf\u8ba1\u6570\u636e\u6765\u603b\u7ed3\u8ba1\u7b97\uff0c\u8fd9\u4e3b\u8981\u7531 TimerOutput::print_wall_time_statistics() \u51fd\u6570\u5b8c\u6210\u3002\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()\u51fd\u6570\u5e76\u4e0d\u4ee4\u4eba\u60ca\u8bb6\uff0c\u5b83\u9075\u5faa\u4e86\u4ee5\u524d\u6240\u6709MPI\u7a0b\u5e8f\u4e2d\u7684\u505a\u6cd5\u3002\u5f53\u6211\u4eec\u8fd0\u884c\u4e00\u4e2aMPI\u7a0b\u5e8f\u65f6\uff0c\u6211\u4eec\u9700\u8981\u8c03\u7528`MPI_Init()`\u548c`MPI_Finalize()`\uff0c\u6211\u4eec\u901a\u8fc7 Utilities::MPI::MPI_InitFinalize \u6570\u636e\u7ed3\u6784\u6765\u5b8c\u6210\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u53ea\u7528MPI\u6765\u8fd0\u884c\u7a0b\u5e8f\uff0c\u5e76\u5c06\u7ebf\u7a0b\u6570\u8bbe\u7f6e\u4e3a1\u3002\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": "#pragma once\n\n#include <random>\n#include <Eigen/Core>\n#include \"geometry.hpp\"\n\n\nclass SearchSpace {\n    int _state_size;\n\n    public:\n        SearchSpace() {}\n\n        SearchSpace(int state_size) {\n            set_state_size(state_size);\n        }\n\n        virtual Eigen::MatrixXd sample_free_space(int n) const {\n            return {1, 1};\n        }\n\n        virtual bool valid_transition(const Eigen::VectorXd& a, const Eigen::VectorXd& b) const {\n            return true;\n        }\n\n        virtual double transition_cost(const Eigen::VectorXd& a, const Eigen::VectorXd& b) const{\n            return 0.;\n        }\n\n        int state_size() const {return _state_size;}\n\n    protected:\n        void set_state_size(int state_size) {_state_size = state_size;}\n};\n\n\ntemplate<typename Numeric, typename Generator = std::mt19937>\nNumeric random(Numeric from, Numeric to)\n{\n    thread_local static Generator gen(std::random_device{}());\n\n    using dist_type = typename std::conditional\n    <\n        std::is_integral<Numeric>::value\n        , std::uniform_int_distribution<Numeric>\n        , std::uniform_real_distribution<Numeric>\n    >::type;\n\n    thread_local static dist_type dist;\n\n    return dist(gen, typename dist_type::param_type{from, to});\n}\n\n\nclass PolygonSpace : public SearchSpace {\n    std::vector<Polygon> _polygons;\n    \n    std::pair<double, double> _xrange, _yrange;\n\n    double _sample_x() const {\n        return random<double>(_xrange.first, _xrange.second);\n    }\n\n    double _sample_y() const {\n        return random<double>(_yrange.first, _yrange.second);\n    }\n\n    public:\n        PolygonSpace(const std::vector<Polygon>& polygons, std::pair<double, double> xrange, std::pair<double, double> yrange) {\n            _polygons = polygons;\n            \n            _xrange = xrange;\n            _yrange = yrange;\n\n            set_state_size(2);\n        }\n\n        Eigen::MatrixXd sample_free_space(int n) const;\n\n        bool valid_transition(const Eigen::VectorXd& a, const Eigen::VectorXd& b) const;\n\n        double transition_cost(const Eigen::VectorXd& a, const Eigen::VectorXd& b) const;\n};\n", "meta": {"hexsha": "eac8ed08297ea2c234484d43ae622a93ab993c6a", "size": 2113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/headers/search_space.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/search_space.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/search_space.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": 25.1547619048, "max_line_length": 128, "alphanum_fraction": 0.6341694274, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5796657735782613}}
{"text": "/* test_piecewise_constant_distribution.cpp\n *\n * Copyright Steven Watanabe 2011\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * $Id: test_piecewise_constant_distribution.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\n *\n */\n\n#include <boost/random/piecewise_constant_distribution.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/assign/list_of.hpp>\n#include <sstream>\n#include <vector>\n#include \"concepts.hpp\"\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\nusing boost::random::test::RandomNumberDistribution;\nusing boost::random::piecewise_constant_distribution;\nBOOST_CONCEPT_ASSERT((RandomNumberDistribution< piecewise_constant_distribution<> >));\n\nstruct gen {\n    double operator()(double arg) {\n        if(arg < 100) return 100;\n        else if(arg < 103) return 1;\n        else if(arg < 107) return 2;\n        else if(arg < 111) return 1;\n        else if(arg < 114) return 4;\n        else return 100;\n    }\n};\n\n#define CHECK_SEQUENCE(actual, expected)            \\\n    do {                                            \\\n        std::vector<double> _actual = (actual);     \\\n        std::vector<double> _expected = (expected); \\\n        BOOST_CHECK_EQUAL_COLLECTIONS(              \\\n            _actual.begin(), _actual.end(),         \\\n            _expected.begin(), _expected.end());    \\\n    } while(false)\n\nusing boost::assign::list_of;\n\nBOOST_AUTO_TEST_CASE(test_constructors) {\n    boost::random::piecewise_constant_distribution<> dist;\n    CHECK_SEQUENCE(dist.densities(), list_of(1.0));\n    CHECK_SEQUENCE(dist.intervals(), list_of(0.0)(1.0));\n\n#ifndef BOOST_NO_INITIALIZER_LISTS\n    boost::random::piecewise_constant_distribution<> dist_il = {\n        { 99, 103, 107, 111, 115 },\n        gen()\n    };\n    CHECK_SEQUENCE(dist_il.intervals(), list_of(99)(103)(107)(111)(115));\n    CHECK_SEQUENCE(dist_il.densities(), list_of(.03125)(.0625)(.03125)(.125));\n\n    boost::random::piecewise_constant_distribution<> dist_il2 = {\n        { 99 },\n        gen()\n    };\n    CHECK_SEQUENCE(dist_il2.intervals(), list_of(0.0)(1.0));\n    CHECK_SEQUENCE(dist_il2.densities(), list_of(1.0));\n#endif\n    std::vector<double> intervals = boost::assign::list_of(0)(1)(2)(3)(5);\n    std::vector<double> weights = boost::assign::list_of(1)(2)(1)(4);\n    std::vector<double> intervals2 = boost::assign::list_of(99);\n    std::vector<double> weights2;\n\n    boost::random::piecewise_constant_distribution<> dist_r(intervals, weights);\n    CHECK_SEQUENCE(dist_r.intervals(), list_of(0)(1)(2)(3)(5));\n    CHECK_SEQUENCE(dist_r.densities(), list_of(.125)(.25)(.125)(.25));\n\n    boost::random::piecewise_constant_distribution<>\n        dist_r2(intervals2, weights2);\n    CHECK_SEQUENCE(dist_r2.intervals(), list_of(0.0)(1.0));\n    CHECK_SEQUENCE(dist_r2.densities(), list_of(1.0));\n    \n    boost::random::piecewise_constant_distribution<> dist_it(\n        intervals.begin(), intervals.end(), weights.begin());\n    CHECK_SEQUENCE(dist_it.intervals(), list_of(0)(1)(2)(3)(5));\n    CHECK_SEQUENCE(dist_it.densities(), list_of(.125)(.25)(.125)(.25));\n    \n    boost::random::piecewise_constant_distribution<> dist_it2(\n        intervals2.begin(), intervals2.end(), weights2.begin());\n    CHECK_SEQUENCE(dist_it2.intervals(), list_of(0.0)(1.0));\n    CHECK_SEQUENCE(dist_it2.densities(), list_of(1.0));\n    \n    boost::random::piecewise_constant_distribution<> dist_fun(4, 99,115, gen());\n    CHECK_SEQUENCE(dist_fun.intervals(), list_of(99)(103)(107)(111)(115));\n    CHECK_SEQUENCE(dist_fun.densities(), list_of(.03125)(.0625)(.03125)(.125));\n    \n    boost::random::piecewise_constant_distribution<>\n        dist_fun2(1, 99, 115, gen());\n    CHECK_SEQUENCE(dist_fun2.intervals(), list_of(99)(115));\n    CHECK_SEQUENCE(dist_fun2.densities(), list_of(0.0625));\n\n    boost::random::piecewise_constant_distribution<> copy(dist);\n    BOOST_CHECK_EQUAL(dist, copy);\n    boost::random::piecewise_constant_distribution<> copy_r(dist_r);\n    BOOST_CHECK_EQUAL(dist_r, copy_r);\n\n    boost::random::piecewise_constant_distribution<> notpow2(3, 99, 111, gen());\n    BOOST_REQUIRE_EQUAL(notpow2.densities().size(), 3u);\n    BOOST_CHECK_CLOSE_FRACTION(notpow2.densities()[0], 0.0625, 0.00000000001);\n    BOOST_CHECK_CLOSE_FRACTION(notpow2.densities()[1], 0.125, 0.00000000001);\n    BOOST_CHECK_CLOSE_FRACTION(notpow2.densities()[2], 0.0625, 0.00000000001);\n    boost::random::piecewise_constant_distribution<> copy_notpow2(notpow2);\n    BOOST_CHECK_EQUAL(notpow2, copy_notpow2);\n}\n\nBOOST_AUTO_TEST_CASE(test_param) {\n    std::vector<double> intervals = boost::assign::list_of(0)(1)(2)(3)(5);\n    std::vector<double> weights = boost::assign::list_of(1)(2)(1)(4);\n    std::vector<double> intervals2 = boost::assign::list_of(0);\n    std::vector<double> weights2;\n    boost::random::piecewise_constant_distribution<> dist(intervals, weights);\n    boost::random::piecewise_constant_distribution<>::param_type\n        param = dist.param();\n    CHECK_SEQUENCE(param.intervals(), list_of(0)(1)(2)(3)(5));\n    CHECK_SEQUENCE(param.densities(), list_of(.125)(.25)(.125)(.25));\n    boost::random::piecewise_constant_distribution<> copy1(param);\n    BOOST_CHECK_EQUAL(dist, copy1);\n    boost::random::piecewise_constant_distribution<> copy2;\n    copy2.param(param);\n    BOOST_CHECK_EQUAL(dist, copy2);\n\n    boost::random::piecewise_constant_distribution<>::param_type\n        param_copy = param;\n    BOOST_CHECK_EQUAL(param, param_copy);\n    BOOST_CHECK(param == param_copy);\n    BOOST_CHECK(!(param != param_copy));\n    boost::random::piecewise_constant_distribution<>::param_type param_default;\n    CHECK_SEQUENCE(param_default.intervals(), list_of(0.0)(1.0));\n    CHECK_SEQUENCE(param_default.densities(), list_of(1.0));\n    BOOST_CHECK(param != param_default);\n    BOOST_CHECK(!(param == param_default));\n    \n#ifndef BOOST_NO_INITIALIZER_LISTS\n    boost::random::piecewise_constant_distribution<>::param_type parm_il = {\n        { 99, 103, 107, 111, 115 },\n        gen()\n    };\n    CHECK_SEQUENCE(parm_il.intervals(), list_of(99)(103)(107)(111)(115));\n    CHECK_SEQUENCE(parm_il.densities(), list_of(.03125)(.0625)(.03125)(.125));\n\n    boost::random::piecewise_constant_distribution<>::param_type parm_il2 = {\n        { 99 },\n        gen()\n    };\n    CHECK_SEQUENCE(parm_il2.intervals(), list_of(0.0)(1.0));\n    CHECK_SEQUENCE(parm_il2.densities(), list_of(1.0));\n#endif\n\n    boost::random::piecewise_constant_distribution<>::param_type\n        parm_r(intervals, weights);\n    CHECK_SEQUENCE(parm_r.intervals(), list_of(0)(1)(2)(3)(5));\n    CHECK_SEQUENCE(parm_r.densities(), list_of(.125)(.25)(.125)(.25));\n\n    boost::random::piecewise_constant_distribution<>::param_type\n        parm_r2(intervals2, weights2);\n    CHECK_SEQUENCE(parm_r2.intervals(), list_of(0.0)(1.0));\n    CHECK_SEQUENCE(parm_r2.densities(), list_of(1.0));\n    \n    boost::random::piecewise_constant_distribution<>::param_type\n        parm_it(intervals.begin(), intervals.end(), weights.begin());\n    CHECK_SEQUENCE(parm_it.intervals(), list_of(0)(1)(2)(3)(5));\n    CHECK_SEQUENCE(parm_it.densities(), list_of(.125)(.25)(.125)(.25));\n    \n    boost::random::piecewise_constant_distribution<>::param_type\n        parm_it2(intervals2.begin(), intervals2.end(), weights2.begin());\n    CHECK_SEQUENCE(parm_it2.intervals(), list_of(0.0)(1.0));\n    CHECK_SEQUENCE(parm_it2.densities(), list_of(1.0));\n    \n    boost::random::piecewise_constant_distribution<>::param_type\n        parm_fun(4, 99, 115, gen());\n    CHECK_SEQUENCE(parm_fun.intervals(), list_of(99)(103)(107)(111)(115));\n    CHECK_SEQUENCE(parm_fun.densities(), list_of(.03125)(.0625)(.03125)(.125));\n    \n    boost::random::piecewise_constant_distribution<>::param_type\n        parm_fun2(1, 99, 115, gen());\n    CHECK_SEQUENCE(parm_fun2.intervals(), list_of(99)(115));\n    CHECK_SEQUENCE(parm_fun2.densities(), list_of(0.0625));\n}\n\nBOOST_AUTO_TEST_CASE(test_min_max) {\n    std::vector<double> intervals = boost::assign::list_of(0)(1)(2)(3)(5);\n    std::vector<double> weights = boost::assign::list_of(1)(2)(1)(4);\n    boost::random::piecewise_constant_distribution<> dist;\n    BOOST_CHECK_EQUAL((dist.min)(), 0.0);\n    BOOST_CHECK_EQUAL((dist.max)(), 1.0);\n    boost::random::piecewise_constant_distribution<> dist_r(intervals, weights);\n    BOOST_CHECK_EQUAL((dist_r.min)(), 0.0);\n    BOOST_CHECK_EQUAL((dist_r.max)(), 5.0);\n}\n\nBOOST_AUTO_TEST_CASE(test_comparison) {\n    std::vector<double> intervals = boost::assign::list_of(0)(1)(2)(3)(5);\n    std::vector<double> weights = boost::assign::list_of(1)(2)(1)(4);\n    boost::random::piecewise_constant_distribution<> dist;\n    boost::random::piecewise_constant_distribution<> dist_copy(dist);\n    boost::random::piecewise_constant_distribution<> dist_r(intervals, weights);\n    boost::random::piecewise_constant_distribution<> dist_r_copy(dist_r);\n    BOOST_CHECK(dist == dist_copy);\n    BOOST_CHECK(!(dist != dist_copy));\n    BOOST_CHECK(dist_r == dist_r_copy);\n    BOOST_CHECK(!(dist_r != dist_r_copy));\n    BOOST_CHECK(dist != dist_r);\n    BOOST_CHECK(!(dist == dist_r));\n}\n\nBOOST_AUTO_TEST_CASE(test_streaming) {\n    std::vector<double> intervals = boost::assign::list_of(0)(1)(2)(3)(5);\n    std::vector<double> weights = boost::assign::list_of(1)(2)(1)(4);\n    boost::random::piecewise_constant_distribution<> dist(intervals, weights);\n    std::stringstream stream;\n    stream << dist;\n    boost::random::piecewise_constant_distribution<> restored_dist;\n    stream >> restored_dist;\n    BOOST_CHECK_EQUAL(dist, restored_dist);\n}\n\nBOOST_AUTO_TEST_CASE(test_generation) {\n    std::vector<double> intervals = boost::assign::list_of(1)(2);\n    std::vector<double> weights = boost::assign::list_of(1);\n    boost::minstd_rand0 gen;\n    boost::random::piecewise_constant_distribution<> dist;\n    boost::random::piecewise_constant_distribution<> dist_r(intervals, weights);\n    for(int i = 0; i < 10; ++i) {\n        double value = dist(gen);\n        BOOST_CHECK_GE(value, 0.0);\n        BOOST_CHECK_LT(value, 1.0);\n        double value_r = dist_r(gen);\n        BOOST_CHECK_GE(value_r, 1.0);\n        BOOST_CHECK_LT(value_r, 2.0);\n        double value_param = dist_r(gen, dist.param());\n        BOOST_CHECK_GE(value_param, 0.0);\n        BOOST_CHECK_LT(value_param, 1.0);\n        double value_r_param = dist(gen, dist_r.param());\n        BOOST_CHECK_GE(value_r_param, 1.0);\n        BOOST_CHECK_LT(value_r_param, 2.0);\n    }\n}\n", "meta": {"hexsha": "6d19a9b6f2c950ef9914991c8dffa2c1c2fbe02c", "size": 10508, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_piecewise_constant_distribution.cpp", "max_stars_repo_name": "AishwaryaDoosa/Boost1.49", "max_stars_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/random/test/test_piecewise_constant_distribution.cpp", "max_issues_repo_name": "AishwaryaDoosa/Boost1.49", "max_issues_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/random/test/test_piecewise_constant_distribution.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5425101215, "max_line_length": 93, "alphanum_fraction": 0.6847164065, "num_tokens": 2812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5796657659768464}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_basic_types.h>\n\n#include <OpenTissue/core/containers/grid/grid.h>\n#include <OpenTissue/core/containers/grid/util/grid_idx2coord.h>\n#include <OpenTissue/core/geometry/t4_cpu_scan/t4_cpu_scan.h>\n#include <OpenTissue/core/containers/mesh/polymesh/polymesh.h>\n#include <OpenTissue/core/containers/mesh/polymesh/util/polymesh_make_sphere.h>\n#include <OpenTissue/core/containers/mesh/polymesh/util/polymesh_compute_face_normal.h>\n#include <cmath> \n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_grid_util_t4_cpu_scan);\n\nBOOST_AUTO_TEST_CASE(signed_test_case)\n{\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  typedef math_types::vector3_type                         vector3_type;\n  typedef math_types::real_type                            real_type;\n  typedef OpenTissue::grid::Grid<float,math_types>                grid_type;\n  typedef OpenTissue::polymesh::PolyMesh<math_types>       mesh_type;\n  grid_type phi;\n  mesh_type surface;\n\n  real_type radius = 1.0;\n\n  size_t I = 8;\n  size_t J = 8;\n  size_t K = 8;\n\n  OpenTissue::polymesh::make_sphere( radius, 5, surface);\n\n  phi.create(vector3_type(-1.0,-1.0,-1.0),vector3_type(1.0,1.0,1.0), I, J, K);\n\n  OpenTissue::t4_cpu_scan(surface, radius, phi, OpenTissue::t4_cpu_signed() );\n\n  real_type tol = 5.0;\n\n  for(size_t i = 0;i<I;++i)\n    for(size_t j = 0;j<J;++j)\n      for(size_t k = 0;k<K;++k)\n      {\n        vector3_type coord;\n        OpenTissue::grid::idx2coord(phi, i,j,k,coord);\n        real_type tst = OpenTissue::math::length(coord) - radius;\n        real_type value = phi(i,j,k);\n        BOOST_CHECK_CLOSE(tst, value, tol);\n      }\n}\n\nBOOST_AUTO_TEST_CASE(unsigned_test_case)\n{\n  using std::fabs;\n\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  typedef math_types::vector3_type                         vector3_type;\n  typedef math_types::real_type                            real_type;\n  typedef OpenTissue::grid::Grid<float,math_types>                grid_type;\n  typedef OpenTissue::polymesh::PolyMesh<math_types>       mesh_type;\n  grid_type phi;\n  mesh_type surface;\n\n  real_type radius = 1.0;\n\n  size_t I = 8;\n  size_t J = 8;\n  size_t K = 8;\n\n  OpenTissue::polymesh::make_sphere( radius, 5, surface);\n\n  phi.create(vector3_type(-1.0,-1.0,-1.0),vector3_type(1.0,1.0,1.0), I, J, K);\n\n  OpenTissue::t4_cpu_scan(surface, radius, phi, OpenTissue::t4_cpu_unsigned() );\n\n  real_type tol = 5.0;\n\n  for(size_t i = 0;i<I;++i)\n    for(size_t j = 0;j<J;++j)\n      for(size_t k = 0;k<K;++k)\n      {\n        vector3_type coord;\n        OpenTissue::grid::idx2coord(phi, i,j,k,coord);\n        real_type tst = fabs( OpenTissue::math::length(coord) - radius );\n        real_type value = phi(i,j,k);\n        BOOST_CHECK_CLOSE(tst, value, tol);\n      }\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b048c48acb4fc63931fcac8a8b27734f4acf5e14", "size": 3310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/containers/grid/t4_cpu_scan/src/unit_t4_cpu_scan.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/containers/grid/t4_cpu_scan/src/unit_t4_cpu_scan.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/containers/grid/t4_cpu_scan/src/unit_t4_cpu_scan.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 32.1359223301, "max_line_length": 87, "alphanum_fraction": 0.6903323263, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5796493254625333}}
{"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": "#include <gtest/gtest.h>\n#include <Eigen/Dense>\n#include <EigenRand/EigenRand>\n\ntemplate<class Scalar>\nEigen::Matrix<Scalar, -1, 1> calcMean(const Eigen::Matrix<Scalar, -1, -1>& samples)\n{\n    return samples.rowwise().mean();\n}\n\ntemplate<class Scalar>\nEigen::Matrix<Scalar, -1, -1> calcCov(const Eigen::Matrix<Scalar, -1, -1>& samples)\n{\n    Eigen::Matrix<Scalar, -1, -1> t = samples.colwise() - samples.rowwise().mean();\n    return t * t.transpose() / (samples.cols() - 1);\n}\n\ntemplate<class Scalar>\nEigen::Matrix<Scalar, -1, -1> calcMatMean(const Eigen::Matrix<Scalar, -1, -1>& samples)\n{\n    Eigen::Map<const Eigen::Matrix<Scalar, -1, -1>> reshaped{ samples.data(), samples.rows() * samples.rows(), samples.cols() / samples.rows() };\n    Eigen::Matrix<Scalar, -1, -1> ret{ samples.rows(), samples.rows() };\n    Eigen::Map<Eigen::Matrix<Scalar, -1, 1>> reshapedRet{ ret.data(), samples.rows() * samples.rows() };\n    reshapedRet = reshaped.rowwise().mean();\n    return ret;\n}\n\ntemplate<class Scalar>\nEigen::Matrix<Scalar, -1, -1> calcMatVar(const Eigen::Matrix<Scalar, -1, -1>& samples)\n{\n    Eigen::Map<const Eigen::Array<Scalar, -1, -1>> reshaped{ samples.data(), samples.rows() * samples.rows(), samples.cols() / samples.rows() };\n    Eigen::Matrix<Scalar, -1, -1> ret{ samples.rows(), samples.rows() };\n    Eigen::Map<Eigen::Matrix<Scalar, -1, 1>> reshapedRet{ ret.data(), samples.rows() * samples.rows() };\n    reshapedRet = reshaped.pow(2).rowwise().mean() - reshaped.rowwise().mean().pow(2);\n    return ret;\n}\n\ntemplate<class Ty>\nauto relErrors(Ty real, Ty target, double minValue) -> decltype((real - target).abs() / real.abs().max(minValue))\n{\n    return (real - target).abs() / real.abs().max(minValue);\n}\n\ntemplate<class Ty>\nbool isSimilarWithErrors(Ty real, Ty target, double relError, double minValue)\n{\n    return (relErrors(real.array(), target.array(), minValue) <= relError).all();\n}\n\n#define EXPECT_SIMILAR_MATRIX(a, b, m) do\\\n{\\\n    bool t = isSimilarWithErrors(a, b, 0.1, m);\\\n    GTEST_TEST_BOOLEAN_(t, #a \" is not similar with \" #b, false, true, GTEST_NONFATAL_FAILURE_);\\\n    if (!t)\\\n    {\\\n        std::cout << #a \"\\n\" << a << std::endl;\\\n        std::cout << #b \"\\n\" << b << std::endl;\\\n        std::cout << \"re: \\n\" << relErrors(a.array(), b.array(), m) << std::endl;\\\n    }\\\n} while(0);\n\nstatic constexpr size_t numSamples = 5000;\n\ntemplate <class T>\nclass MvDistTest : public testing::Test\n{\n};\n\nusing ETypes = testing::Types<float, double>;\n\nTYPED_TEST_CASE(MvDistTest, ETypes);\n\nTYPED_TEST(MvDistTest, normal)\n{\n    std::cout << \"SIMD arch: \" << Eigen::SimdInstructionSetsInUse() << std::endl;\n    Eigen::Rand::P8_mt19937_64 rng{ 42 };\n\n    Eigen::Matrix<TypeParam, -1, 1> mean(9);\n    mean << -1, 0, 1, 2, 3, 2, 1, 0, -1;\n\n    Eigen::Matrix<TypeParam, -1, -1> cov(9, 9);\n    cov.setZero();\n    cov(0, 1) = 0.5;\n    cov(2, 7) = 0.5;\n    cov(3, 1) = 0.7;\n    cov.diagonal() << 1, 1.2, 1.4, 1.6, 1.8, 1.6, 1.4, 1.2, 1;\n    cov = cov * cov.transpose();\n\n    auto gen = Eigen::Rand::makeMvNormalGen(mean, cov);\n    auto samples = gen.generate(rng, numSamples).eval();\n    \n    auto mean2 = calcMean(samples);\n    auto cov2 = calcCov(samples);\n\n    EXPECT_SIMILAR_MATRIX(mean, mean2, 2.5);\n    EXPECT_SIMILAR_MATRIX(cov, cov2, 2.5);\n}\n\nTYPED_TEST(MvDistTest, wishart)\n{\n    Eigen::Rand::P8_mt19937_64 rng{ 42 };\n\n    int df = 12;\n    Eigen::Matrix<TypeParam, -1, -1> scale(9, 9);\n    scale.setZero();\n    scale(0, 1) = 0.5;\n    scale(2, 7) = 0.5;\n    scale(3, 1) = 0.7;\n    scale.diagonal() << 1, 1.2, 1.4, 1.6, 1.8, 1.6, 1.4, 1.2, 1;\n    scale = scale * scale.transpose();\n\n    auto gen = Eigen::Rand::makeWishartGen(df, scale);\n    auto samples = gen.generate(rng, numSamples).eval();\n\n    auto mean = (df * scale).eval();\n    auto var = (scale.diagonal() * scale.diagonal().transpose()).eval();\n    var.array() += scale.array() * scale.array();\n    var *= df;\n\n    auto mean2 = calcMatMean(samples);\n    auto var2 = calcMatVar(samples);\n\n    EXPECT_SIMILAR_MATRIX(mean, mean2, 5);\n    EXPECT_SIMILAR_MATRIX(var, var2, 5);\n}\n\nTYPED_TEST(MvDistTest, invWishart)\n{\n    Eigen::Rand::P8_mt19937_64 rng{ 42 };\n\n    float df = 15;\n    int p = 9;\n    Eigen::Matrix<TypeParam, -1, -1> scale(p, p);\n    scale.setZero();\n    scale(0, 1) = 0.5;\n    scale(2, 7) = 0.5;\n    scale(3, 1) = 0.7;\n    scale.diagonal() << 1, 1.2, 1.4, 1.6, 1.8, 1.6, 1.4, 1.2, 1;\n    scale = scale * scale.transpose();\n\n    auto gen = Eigen::Rand::makeInvWishartGen(df, scale);\n    auto samples = gen.generate(rng, numSamples).eval();\n\n    auto mean = (scale / (df - p - 1)).eval();\n    auto var = (scale.diagonal() * scale.diagonal().transpose() * (df - p - 1)).eval();\n    var.array() += (scale.array() * scale.array()) * (df - p + 1);\n    var /= (df - p) * (df - p - 1) * (df - p - 1) * (df - p - 3);\n\n    auto mean2 = calcMatMean(samples);\n    auto var2 = calcMatVar(samples);\n\n    EXPECT_SIMILAR_MATRIX(mean, mean2, 5);\n    EXPECT_SIMILAR_MATRIX(var, var2, 5);\n}\n\nTEST(MvDistTest, multinomial)\n{\n    Eigen::Rand::P8_mt19937_64 rng{ 42 };\n\n    int n = 10;\n    Eigen::Matrix<float, -1, 1> weight(9);\n    weight << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n    weight /= weight.sum();\n    auto gen = Eigen::Rand::makeMultinomialGen(n, weight);\n    auto samples = gen.generate(rng, numSamples).array().template cast<float>().matrix().eval();\n\n    auto mean = (weight * n).eval();\n    auto cov = (weight * weight.transpose() * -n).eval();\n    cov.diagonal() = weight.array() * (1 - weight.array()) * n;\n\n    auto mean2 = calcMean(samples);\n    auto cov2 = calcCov(samples);\n\n    EXPECT_SIMILAR_MATRIX(mean, mean2, 2.5);\n    EXPECT_SIMILAR_MATRIX(cov, cov2, 2.5);\n}\n\nTYPED_TEST(MvDistTest, dirichlet)\n{\n    Eigen::Rand::P8_mt19937_64 rng{ 42 };\n\n    Eigen::Matrix<TypeParam, -1, 1> weight(9);\n    weight << .1, .2, .3, .4, .5, .6, .7, .8, .9;\n    auto gen = Eigen::Rand::makeDirichletGen(weight);\n    auto samples = gen.generate(rng, numSamples).eval();\n\n    auto mean = (weight / weight.sum()).eval();\n    auto cov = (-mean * mean.transpose()).eval();\n    cov.diagonal() += mean;\n    cov /= weight.sum() + 1;\n\n    auto mean2 = calcMean(samples);\n    auto cov2 = calcCov(samples);\n\n    EXPECT_SIMILAR_MATRIX(mean, mean2, 2.5);\n    EXPECT_SIMILAR_MATRIX(cov, cov2, 2.5);\n}\n", "meta": {"hexsha": "caca909d296ae35892e2972df8961cdbb0ab8d2a", "size": 6251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_mv.cpp", "max_stars_repo_name": "bab2min/EigenRand", "max_stars_repo_head_hexsha": "be563c3abc65864e8c8c70a444a374bbb9b70825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 59.0, "max_stars_repo_stars_event_min_datetime": "2020-06-25T15:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T14:28:27.000Z", "max_issues_repo_path": "test/test_mv.cpp", "max_issues_repo_name": "bab2min/EigenRand", "max_issues_repo_head_hexsha": "be563c3abc65864e8c8c70a444a374bbb9b70825", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2020-10-03T15:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T15:39:15.000Z", "max_forks_repo_path": "test/test_mv.cpp", "max_forks_repo_name": "bab2min/EigenRand", "max_forks_repo_head_hexsha": "be563c3abc65864e8c8c70a444a374bbb9b70825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T14:04:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:41:12.000Z", "avg_line_length": 31.5707070707, "max_line_length": 145, "alphanum_fraction": 0.608862582, "num_tokens": 2085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5796391317011859}}
{"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": "#include <stan/math/prim/mat.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\n\nTEST(ProbDistributionsCategorical,Categorical) {\n  Matrix<double,Dynamic,1> theta(3,1);\n  theta << 0.3, 0.5, 0.2;\n  EXPECT_FLOAT_EQ(-1.203973, stan::math::categorical_log(1,theta));\n  EXPECT_FLOAT_EQ(-0.6931472, stan::math::categorical_log(2,theta));\n}\nTEST(ProbDistributionsCategorical,Propto) {\n  Matrix<double,Dynamic,1> theta(3,1);\n  theta << 0.3, 0.5, 0.2;\n  EXPECT_FLOAT_EQ(0.0, stan::math::categorical_log<true>(1,theta));\n  EXPECT_FLOAT_EQ(0.0, stan::math::categorical_log<true>(2,theta));\n}\n\nTEST(ProbDistributionsCategorical,VectorInt) {\n  Matrix<double,Dynamic,1> theta(3,1);\n  theta << 0.3, 0.5, 0.2;\n  std::vector<int> xs0;\n  EXPECT_FLOAT_EQ(0.0, stan::math::categorical_log(xs0,theta));\n\n  std::vector<int> xs(3);\n  xs[0] = 1;\n  xs[1] = 3;\n  xs[2] = 1;\n  \n  EXPECT_FLOAT_EQ(log(0.3) + log(0.2) + log(0.3),\n                  stan::math::categorical_log(xs,theta));\n}\n\nusing stan::math::categorical_log;\n\nTEST(ProbDistributionsCategorical, error) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  double inf = std::numeric_limits<double>::infinity();\n  \n  unsigned int n = 1;\n  unsigned int N = 3;\n  Matrix<double,Dynamic,1> theta(N,1);\n  theta << 0.3, 0.5, 0.2;\n\n  EXPECT_NO_THROW(categorical_log(N, theta));\n  EXPECT_NO_THROW(categorical_log(n, theta));\n  EXPECT_NO_THROW(categorical_log(2, theta));\n  EXPECT_THROW(categorical_log(N+1, theta), std::domain_error);\n  EXPECT_THROW(categorical_log(0, theta), std::domain_error);\n\n  \n  theta(0) = nan;\n  EXPECT_THROW(categorical_log(n, theta), std::domain_error);\n  theta(0) = inf;\n  EXPECT_THROW(categorical_log(n, theta), std::domain_error);\n  theta(0) = -inf;\n  EXPECT_THROW(categorical_log(n, theta), std::domain_error);\n  theta(0) = -1;\n  theta(1) = 1;\n  theta(2) = 0;\n  EXPECT_THROW(categorical_log(n, theta), std::domain_error);\n\n  std::vector<int> ns(3);\n  ns[0] = 3;\n  ns[1] = 2;\n  ns[2] = 3;\n  EXPECT_THROW(categorical_log(ns,theta), std::domain_error);\n  \n  theta << 0.3, 0.5, 0.2;\n  EXPECT_NO_THROW(categorical_log(ns,theta));\n  ns[1] = -1;\n  EXPECT_THROW(categorical_log(ns,theta), std::domain_error);\n\n  ns[1] = 1;\n  ns[2] = 12;\n  EXPECT_THROW(categorical_log(ns,theta), std::domain_error);\n  \n  \n}\n\nTEST(ProbDistributionsCategorical, error_check) {\n  boost::random::mt19937 rng;\n  \n  Matrix<double,Dynamic,Dynamic> theta(3,1);\n  theta << 0.15, \n    0.45,\n    0.50;\n\n  EXPECT_THROW(stan::math::categorical_rng(theta,rng),std::domain_error);\n}\n\nTEST(ProbDistributionsCategorical, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n\n  int N = 10000;\n  Matrix<double,Dynamic,Dynamic> theta(3,1);\n  theta << 0.15, \n    0.45,\n    0.40;\n  int K = theta.rows();\n  boost::math::chi_squared mydist(K-1);\n\n  Eigen::Matrix<double,Eigen::Dynamic,1> loc(theta.rows(),1);\n  for(int i = 0; i < theta.rows(); i++)\n    loc(i) = 0;\n\n  for(int i = 0; i < theta.rows(); i++) {\n    for(int j = i; j < theta.rows(); j++)\n      loc(j) += theta(i);\n  }\n\n  int count = 0;\n  int bin [K];\n  double expect [K];\n  for(int i = 0 ; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N * theta(i);\n  }\n\n  while (count < N) {\n    int a = stan::math::categorical_rng(theta,rng);\n    bin[a - 1]++;\n    count++;\n   }\n\n  double chi = 0;\n\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\n", "meta": {"hexsha": "e49d1e68ec9f4126e46c6bf3229c43ef1b998555", "size": 3537, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/categorical_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/categorical_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/categorical_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8175182482, "max_line_length": 73, "alphanum_fraction": 0.6477240599, "num_tokens": 1191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5796391154006467}}
{"text": "#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/extreme_value_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n#include \"fmath.hpp\"\n\n#include \"random.h\"\n\nnamespace SPN {\n  namespace random {\n    rand_gen _def_generator;\n    boost::random::extreme_value_distribution<double> _gumbel(0.0, 1.0);\n    boost::random::normal_distribution<double> _gaussian(0.0, 1.0);\n\n    rand_gen& get_generator(void) { return _def_generator; }\n\n    void set_seed(uint seed) { _def_generator.seed(seed); }\n\n    double gumbel(void) { return _gumbel(_def_generator); }\n\n    double gaussian(double loc, double scale) {\n      _gaussian.param(boost::random::normal_distribution<double>::param_type(loc, scale));\n      return _gaussian(_def_generator);\n    }\n  }\n}\n", "meta": {"hexsha": "3c3ea129aae03282e63bffb586f9bcef22c1afa9", "size": 775, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/random.cpp", "max_stars_repo_name": "RenatoGeh/zhaospn", "max_stars_repo_head_hexsha": "1e038156e00613e9ec006346b5d2b4a1281bcc10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/random.cpp", "max_issues_repo_name": "RenatoGeh/zhaospn", "max_issues_repo_head_hexsha": "1e038156e00613e9ec006346b5d2b4a1281bcc10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/random.cpp", "max_forks_repo_name": "RenatoGeh/zhaospn", "max_forks_repo_head_hexsha": "1e038156e00613e9ec006346b5d2b4a1281bcc10", "max_forks_repo_licenses": ["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.7037037037, "max_line_length": 90, "alphanum_fraction": 0.7303225806, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5796387735769057}}
{"text": "#ifndef HMonomialBasisForMinimumFrobeniusNormModel\n#define HMonomialBasisForMinimumFrobeniusNormModel\n\n#include \"BasisForSurrogateModelBaseClass.hpp\"\n#include \"QuadraticMonomial.hpp\"\n#include \"VectorOperations.hpp\"\n#include <Eigen/Dense>\n#include <vector>\n#include \"math.h\"\n\nclass MonomialBasisForMinimumFrobeniusNormModel : public BasisForSurrogateModelBaseClass, \n                                                  public QuadraticMonomial,\n                                                  protected VectorOperations {\n  private:\n    int nb_nodes;\n    Eigen::MatrixXd A_sysmat;\n    Eigen::MatrixXd S_coeffsolve;\n    Eigen::MatrixXd F_rhsmat;\n    int counter;\n    //! Evaluations of surrogate basis functions at nodes used to construct the basis\n    std::vector<double> basis_values;\n    std::vector<double> basis_constants;\n    std::vector< std::vector<double> > basis_gradients; \n    std::vector< std::vector< std::vector<double> > > basis_Hessians;   \n  public:\n    MonomialBasisForMinimumFrobeniusNormModel ( int );\n    void set_nb_nodes ( int );\n    std::vector<double> &evaluate ( std::vector<double> const& );    \n    double evaluate ( std::vector<double> const&, int);\n    double &value( int );\n    std::vector<double> &gradient ( int );\n    std::vector< std::vector<double> > &hessian ( int );\n    void compute_basis_coefficients ( std::vector< std::vector<double> > const& );\n    void compute_mat_vec_representation ( int );\n\n};\n\n#endif\n", "meta": {"hexsha": "8cbde0115dc4c67478cf6122588fcd173e429dc1", "size": 1448, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MonomialBasisForMinimumFrobeniusNormModel.hpp", "max_stars_repo_name": "snowpac/snowpac", "max_stars_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-04T20:18:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T23:50:27.000Z", "max_issues_repo_path": "include/MonomialBasisForMinimumFrobeniusNormModel.hpp", "max_issues_repo_name": "snowpac/snowpac", "max_issues_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/MonomialBasisForMinimumFrobeniusNormModel.hpp", "max_forks_repo_name": "snowpac/snowpac", "max_forks_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1282051282, "max_line_length": 90, "alphanum_fraction": 0.6843922652, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5795515593850502}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef ITL_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#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n\nusing namespace boost;\nusing namespace std;\n\nint main()\n{\n/*********************** Graph creation *********************************/\n  int N,a,b,j;\n  cout << \"Enter number of nodes: \"<<endl;\n  cin >> N;\n  j = N;\n  // Declares a graph g\n  adjacency_list <> g;\n  // Adding vertices to graph g\n  while(j){\n    add_vertex(g);\n    j--;\n  }\n\n\n  while(1)\n  {\n\tcout <<\"Connect Nodes (x->y) : \";\n\tcin >> a >> b;\n\tif( a < 0 || b < 0){\n\t\tcout << \"Your Graph is ready\\n\"<< endl;\n\t\tbreak;\n\t}\n\telse if(a < N || b < N) {\n\t\tcout << \"Connected: (\" << a << \"->\" << b <<\")\"<< endl;\n\t\tadd_edge(a, b, g);\n\t}\n  }\n\n/**************************** Print neighbors of each vertex *****************************/\n\n  graph_traits < adjacency_list <> >::vertex_iterator i, eend;\n  graph_traits < adjacency_list <> >::adjacency_iterator ai, a_end;\t// out_edge_iterator can also be used to get the list of adjacency vertices\n\n// A PropertyGraph is a graph that has some property associated with each of the vertices or edges in the graph.\n//\n// vertex_index_t is the type of property which is being accessed. 'vertex_index' is one of its value. \n// Eg. enum vertex_index_t\n//     {\n//\t vertex_index\n//     }\n// (https://www.boost.org/doc/libs/1_60_0/libs/graph/doc/property.html)\n//\n// get(vertex_index, g) returns the property map with the property of type vertex_index\n\n  property_map < adjacency_list <>, vertex_index_t >::type index_map = get(vertex_index, g);\n\n    for (tie(i, eend) = vertices(g); i != eend; i++) {\n    cout << \"Neighbors of vertex \" << (int)get(index_map, *i) << \" ==> \";\t\t\n        for (tie(ai, a_end) = adjacent_vertices(*i, g); ai != a_end; ai++) { \n            cout << (int)get(index_map, *ai) << \"  \";\n        }\n    cout << endl;\n    }\n}\n\n\n", "meta": {"hexsha": "51990942529f8623c95d90edb8b2350956d4edd6", "size": 1798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "A1/Demo example/graph.cpp", "max_stars_repo_name": "shreshthtuli/COL719_Assignments", "max_stars_repo_head_hexsha": "3f10dc9a6a0737f8ba3a9faa5cf0bc4e660a056e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A1/Demo example/graph.cpp", "max_issues_repo_name": "shreshthtuli/COL719_Assignments", "max_issues_repo_head_hexsha": "3f10dc9a6a0737f8ba3a9faa5cf0bc4e660a056e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A1/Demo example/graph.cpp", "max_forks_repo_name": "shreshthtuli/COL719_Assignments", "max_forks_repo_head_hexsha": "3f10dc9a6a0737f8ba3a9faa5cf0bc4e660a056e", "max_forks_repo_licenses": ["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.2424242424, "max_line_length": 143, "alphanum_fraction": 0.5723025584, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5793067010508656}}
{"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 <cstdlib>\n#include <ctime>\n#include <iostream>\n#include <armadillo>\n#include <random>\n#include <functional>\n\n\nusing namespace arma;\n\n\nclass RandDouble\n{\n  public:\n      RandDouble(double low, double high)\n      :r(std::bind(std::uniform_real_distribution<>(low,high),std::default_random_engine())){}\n\n      double operator()(){ return r(); }\n\n  private:\n      std::function<double()> r;\n};\n\n\nint randInt(int minInt, int  maxInt)\n{\n  return rand()%maxInt + minInt;\n}\n\n\ntemplate <typename T>\nvoid monteCarlo(const AmoebaParam<T> amoebaParam)\n{\n\n  srand(time(NULL));\n\n  vec guess(63);\n  for(int i=0; i<63; ++i)\n  {\n      if(i<37){\n        guess(i) = 0.0001;\n      }\n      else\n      {\n        guess(i) = 0.000000000001;\n      }\n  }\n  vec newGuess = guess;\n\n  cx_mat X1;\n\n  double tau = 6.28318530718;\n  double tol = 0.000001;\n  double objectRes = 100;\n  double objectResOld;\n\n  double change;\n\n  int entry;\n  int iters = 0;\n  int maxIters = 10000;\n  double scale = 1.0;\n\n  RandDouble randD{-0.00001,0.00001};\n\n  UAmoeba* amoeba = new UAmoeba(amoebaParam.maxAmoebaIters, amoebaParam.nGridPoints, amoebaParam.precision, amoebaParam.matSize, amoebaParam.lieDimension, amoebaParam.basis);\n  amoeba->startBoundary = amoebaParam.startBoundary;\n  amoeba->endBoundary = amoebaParam.endBoundary;\n\n  cout << \"start boundary : \" << amoeba->startBoundary << endl;\n  cout << \"end boundary : \" << amoeba->endBoundary << endl;\n\n  X1 = amoeba->curveFunc(guess);\n  objectResOld = amoeba->objectFunc(X1);\n\n  cout << \"initial weight : \" << objectResOld << endl;\n\n  while( iters < maxIters && objectRes > tol)\n  {\n\n    iters+=1;\n    cout << iters << endl;\n    //randomly select a entry\n    entry = iters%38;\n    //randomly vary the entry mod 2pi\n    change = randD();\n    newGuess(entry) = fmod((newGuess(entry) + change), tau);\n\n    //recompute geodesic\n    X1 = amoeba->curveFunc(newGuess);\n\n    //compute norm\n    objectRes = amoeba->objectFunc(X1);\n\n\n    if(objectRes < objectResOld)\n    {\n      //new guess is better\n      cout << \"changed entry :\" << entry << endl;\n      cout <<\"change : \" << change << endl;\n      cout << \"new weight : \" << objectRes << endl;\n      guess = newGuess;\n      objectResOld = objectRes;\n    }\n    //reset newGuess;\n    newGuess = guess;\n  }\n\n  amoeba->curvePrint(guess);\n  cout << \"best guess : \" << guess << endl;\n}\n", "meta": {"hexsha": "2a93f4cc92efdefbc3004976bb64f6b0e3b509a6", "size": 2340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/monte.cpp", "max_stars_repo_name": "Swaddle/qGeod", "max_stars_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solvers/monte.cpp", "max_issues_repo_name": "Swaddle/qGeod", "max_issues_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solvers/monte.cpp", "max_forks_repo_name": "Swaddle/qGeod", "max_forks_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8928571429, "max_line_length": 174, "alphanum_fraction": 0.6294871795, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5793046308363571}}
{"text": "#pragma once\n\n#include \"loader.hpp\"\n#include <Eigen/Dense>\n#include <any>\n#include <chrono>\n#include <map>\n#include <random>\n#include <unordered_set>\n#include <vector>\n\nclass Config;\nclass SpTensor_List;\nclass SpTensor_Hash;\nclass SpTensor_dX;\nclass DataStream;\n\nclass TensorStream;\nTensorStream* generateTensorStream(DataStream& paperX, const Config& config); // Generate the tensor stream\n\nclass TensorStream {\npublic:\n    TensorStream(DataStream& paperX, const Config& config);\n    virtual ~TensorStream(void);\n\n    void updateTensor(const DataStream::Event& e);\n    void updateFactor(void);\n\n    double elapsedTime(void) const; // sec\n\n    double find_reconst(const std::vector<int>& coord) const;\n    double density(void) const;\n\n    /* Load matrix */\n    void saveFactor(std::string fileName) const;\n\n    /* Get errors */\n    double rmse(void) const;\n    double fitness(void) const;\n    double fitness_latest(void) const;\n    double error(const std::vector<int>& coord) const; // Error of the given entry\n\n    void updateAtA(void); // Update the AtA when _use_AtA is false\n\nprotected:\n    const Config* _config;\n\n    std::vector<int> _compute_order;\n\n    virtual void _updateAlgorithm(void) {} // It will change the current updateAlgorithm later\n\n    double _norm_frobenius_reconst(void) const;\n    double _innerprod_X_X_reconst(void) const;\n\n    SpTensor_Hash* _X = nullptr;\n    SpTensor_dX* _dX = nullptr;\n    DataStream* _paperX;\n\n    Eigen::ArrayXd _lambda;\n    std::vector<Eigen::MatrixXd> _A;\n    std::vector<Eigen::ArrayXXd> _AtA;\n\n    bool _use_AtA = true;\n\n    long long _nextTime;\n\n    std::chrono::nanoseconds _elapsed_time; // Elapsed time\n\n    void _rand_init_A(void); // Randomly initialize factor matrices\n\n    void _als_base(void); // Base code for ALS\n    void _unnormalize_A(void); // Unnormalize the factor matrices\n\n    /* Basic factor update algorithms */\n    void _als(void);\n    void _recurrent_als(void);\n};\n\n/* General ALS until the convergence */\nclass TensorStream_ALS : public TensorStream {\npublic:\n    TensorStream_ALS(DataStream& paperX, const Config& config)\n        : TensorStream(paperX, config)\n    {\n    }\n    virtual ~TensorStream_ALS(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override\n    {\n        _als();\n    }\n};\n\n/* ALS using previous factor matrices as a initialization point until the convergence */\nclass TensorStream_RecurrentALS : public TensorStream {\npublic:\n    TensorStream_RecurrentALS(DataStream& paperX, const Config& config)\n        : TensorStream(paperX, config)\n    {\n    }\n    virtual ~TensorStream_RecurrentALS(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override\n    {\n        _recurrent_als();\n    }\n};\n\n/* ALS using previous factor matrices as a initialization point with fixed # of iterations */\nclass TensorStream_RecurrentALS_iter : public TensorStream_RecurrentALS {\npublic:\n    TensorStream_RecurrentALS_iter(DataStream& paperX, const Config& config);\n    virtual ~TensorStream_RecurrentALS_iter(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override;\n    int _numIter;\n};\n\n/* SelectiveALS */\nclass TensorStream_SelectiveALS : public TensorStream {\npublic:\n    TensorStream_SelectiveALS(DataStream& paperX, const Config& config)\n        : TensorStream(paperX, config)\n    {\n    }\n    virtual ~TensorStream_SelectiveALS(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override;\n};\n\nclass TensorStream_coordSelectiveALS : public TensorStream {\npublic:\n    TensorStream_coordSelectiveALS(DataStream& paperX, const Config& config);\n    virtual ~TensorStream_coordSelectiveALS(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override;\n    Eigen::ArrayXd _sqSumProd; // Product of sqSum\n    std::vector<Eigen::MatrixXd> _Aprev;\n    std::vector<Eigen::ArrayXXd> _AprevtA;\n    double _higherBound;\n};\n\n/* SamplingALS */\nclass TensorStream_SamplingALS : public TensorStream {\npublic:\n    TensorStream_SamplingALS(DataStream& paperX, const Config& config);\n    virtual ~TensorStream_SamplingALS(void) {}\n\n    /*\n        Save sampled entries and their reconstructed value.\n        deltidxLists: save changed index, numSel: number of changed idx in each mode.\n    */\n    void Sampling(const std::vector<std::vector<int>>& deltaIdxLists, const std::vector<int>& numSel);\n\n    typedef std::unordered_map<std::vector<int>, double> samples;\n    typedef std::vector<std::vector<samples>> totalSamples;\n\nprotected:\n    int _numSample; // # of sampling per selected slice\n    std::vector<std::vector<int>> _numCand; // Array for sampling candidates\n    std::vector<Eigen::ArrayXXd> _AprevtA; // For A_{t-1}^TA_t\n    totalSamples _sampledIdx; // Save sampled entries\n};\n\nclass TensorStream_baseSamplingALS : public TensorStream_SamplingALS {\npublic:\n    TensorStream_baseSamplingALS(DataStream& paperX, const Config& config)\n        : TensorStream_SamplingALS(paperX, config)\n    {\n    }\n    virtual ~TensorStream_baseSamplingALS(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override;\n\n    /* Compute the mttkrp result of one entry */\n    void mkpRow(const std::vector<int>& rawIdx, int currMode,\n        Eigen::MatrixXd& mkp, int rdx, bool changed, double reconVal = 0.0);\n};\n\n/* SamplingALS with coordinate descent */\nclass TensorStream_coordSamplingALS : public TensorStream_SamplingALS {\npublic:\n    TensorStream_coordSamplingALS(DataStream& paperX, const Config& config);\n    virtual ~TensorStream_coordSamplingALS(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override;\n    Eigen::ArrayXd _sqSumProd; // Product of sqSum\n    std::vector<Eigen::MatrixXd> _Aprev;\n    double _higherBound;\n};\n\nclass TensorStream_hybridALS : public TensorStream_baseSamplingALS {\npublic:\n    TensorStream_hybridALS(DataStream& paperX, const Config& config);\n    virtual ~TensorStream_hybridALS(void) {}\n\nprotected:\n    virtual void _updateAlgorithm(void) override;\n    std::vector<std::vector<int>> selIdxLists;\n    std::vector<std::vector<int>> samIdxLists;\n};\n\nclass TensorStream_coordHybridALS : public TensorStream_coordSamplingALS {\npublic:\n    TensorStream_coordHybridALS(DataStream& paperX, const Config& config);\n    virtual ~TensorStream_coordHybridALS(void) {}\n    double prodAtA(int numMode, int currMode, const std::vector<Eigen::ArrayXXd>& squareVec,\n        int currRow, int currCol);\n    double prodA(int numMode, int currMode,\n        const std::vector<Eigen::MatrixXd>& factorVec, const std::vector<int>& currIdx, int currCol);\n    void updateA_and_AtA(double newVal, int rank, int currMode, int currRow, int currCol);\n\nprotected:\n    virtual void _updateAlgorithm(void) override;\n    std::vector<std::vector<int>> selIdxLists;\n    std::vector<std::vector<int>> samIdxLists;\n};\n", "meta": {"hexsha": "42baacc70c2c71dd6c936d92f1732f2d51d7934b", "size": 6742, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tensorStream.hpp", "max_stars_repo_name": "DMLab-Tensor/SliceNStitch", "max_stars_repo_head_hexsha": "0695165e0aca60c0c1767477733c85e562a4f45b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-01T06:12:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T16:57:51.000Z", "max_issues_repo_path": "src/tensorStream.hpp", "max_issues_repo_name": "DMLab-Tensor/SliceNStitch", "max_issues_repo_head_hexsha": "0695165e0aca60c0c1767477733c85e562a4f45b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tensorStream.hpp", "max_forks_repo_name": "DMLab-Tensor/SliceNStitch", "max_forks_repo_head_hexsha": "0695165e0aca60c0c1767477733c85e562a4f45b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-30T06:23:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-21T08:44:31.000Z", "avg_line_length": 29.9644444444, "max_line_length": 107, "alphanum_fraction": 0.7284188668, "num_tokens": 1618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5793046250597966}}
{"text": "/**\n * @file ann_regularizer_test.cpp\n * @author Saksham Bansal\n *\n * Tests the ANN regularizer modules.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/layer/layer_types.hpp>\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n#include <mlpack/methods/ann/regularizer/regularizer.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"ann_test_tools.hpp\"\n#include \"serialization.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(ANNRegularizerTest);\n\nBOOST_AUTO_TEST_CASE(GradientL1RegularizerTest)\n{\n  // Add function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction() :\n      factor(0.6),\n      reg(factor)\n    {\n      // Nothing to do here.\n    }\n\n    double Output(const arma::mat& weight, size_t i, size_t j)\n    {\n      return std::abs(weight(i, j)) * factor;\n    }\n\n    void Gradient(arma::mat& weight, arma::mat& gradient)\n    {\n      reg.Evaluate(weight, gradient);\n    }\n\n    double factor;\n    L1Regularizer reg;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckRegularizerGradient(function), 1e-4);\n}\n\nBOOST_AUTO_TEST_CASE(GradientL2RegularizerTest)\n{\n  // Add function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction() :\n        factor(0.6),\n        reg(factor)\n    {\n      // Nothing to do here.\n    }\n\n    double Output(const arma::mat& weight, size_t i, size_t j)\n    {\n      return weight(i, j) * weight(i, j) * factor;\n    }\n\n    void Gradient(arma::mat& weight, arma::mat& gradient)\n    {\n      reg.Evaluate(weight, gradient);\n    }\n\n    double factor;\n    L2Regularizer reg;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckRegularizerGradient(function), 1e-4);\n}\n\nBOOST_AUTO_TEST_CASE(GradientOrthogonalRegularizerTest)\n{\n  // Add function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction() :\n        factor(0.6),\n        reg(factor)\n    {\n      // Nothing to do here.\n    }\n\n    double Output(const arma::mat& weight, size_t /* i */, size_t /* j */)\n    {\n      arma::mat x = arma::abs(weight * weight.t() -\n          arma::eye<arma::mat>(weight.n_rows, weight.n_cols)) * factor;\n      return arma::accu(x);\n    }\n\n    void Gradient(arma::mat& weight, arma::mat& gradient)\n    {\n      reg.Evaluate(weight, gradient);\n    }\n\n    double factor;\n    OrthogonalRegularizer reg;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckRegularizerGradient(function), 1e-4);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "ba7f3b58eecf45687cf6beafa781e62a46427aa5", "size": 2747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/ann_regularizer_test.cpp", "max_stars_repo_name": "tomjpsun/mlpack", "max_stars_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-11T14:14:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T14:14:30.000Z", "max_issues_repo_path": "src/mlpack/tests/ann_regularizer_test.cpp", "max_issues_repo_name": "tomjpsun/mlpack", "max_issues_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-10T17:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-11T14:56:25.000Z", "max_forks_repo_path": "src/mlpack/tests/ann_regularizer_test.cpp", "max_forks_repo_name": "tomjpsun/mlpack", "max_forks_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2796610169, "max_line_length": 78, "alphanum_fraction": 0.673825992, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382004, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5793046237514144}}
{"text": "#include <cellogram/remesh_adaptive.h>\n#include <igl/triangle/triangulate.h>\n#include <igl/write_triangle_mesh.h>\n#include <Eigen/Dense>\n#include <iostream>\n\nvoid isotropic_quad(Eigen::MatrixXd &OV, Eigen::MatrixXi &OF, double area) {\n\tstd::stringstream buf;\n\tbuf.precision(100);\n\tbuf.setf(std::ios::fixed, std::ios::floatfield);\n\n\tbuf << \"Qqa\" << area;\n\n\tEigen::MatrixXd V(4,2); V <<\n\t\t-1,-1,\n\t\t-1,1,\n\t\t1,1,\n\t\t1,-1;\n\n\tEigen::MatrixXi E(4,2); E <<\n\t\t0,1,\n\t\t1,2,\n\t\t2,3,\n\t\t3,0;\n\n\tEigen::MatrixXd H(0,2);\n\tigl::triangle::triangulate(V, E, H, buf.str(), OV, OF);\n}\n\nint main(int argc, char** argv) {\n\tEigen::MatrixXd V1, V2;\n\tEigen::MatrixXi F1, F2;\n\tEigen::VectorXd S;\n\n\tisotropic_quad(V1, F1, 0.01);\n\n\tS.resize(V1.rows());\n\tfor (int v = 0; v < V1.rows(); ++v) {\n\t\tEigen::RowVector2d p = V1.row(v);\n\t\tS(v) = 0.001 + 0.1 * p.squaredNorm();\n\t}\n\n\tcellogram::remesh_adaptive_2d(V1, F1, S, V2, F2);\n\tigl::write_triangle_mesh(\"output.obj\", V2, F2);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "fa723f111acca87a5d5981cbaa274e0160c70c2a", "size": 954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/adaptive_test.cpp", "max_stars_repo_name": "cellogram/cellogram", "max_stars_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-09-25T15:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T08:17:44.000Z", "max_issues_repo_path": "misc/adaptive_test.cpp", "max_issues_repo_name": "cellogram/cellogram", "max_issues_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/adaptive_test.cpp", "max_forks_repo_name": "cellogram/cellogram", "max_forks_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-14T01:36:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-11T20:27:57.000Z", "avg_line_length": 19.875, "max_line_length": 76, "alphanum_fraction": 0.6299790356, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5793046205916179}}
{"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": "\n\n#include <tagloc/tracking.h>\n#include <math.h>\n#include <stdio.h>\n#include <Eigen/Dense>\n#include <iostream>\nusing std::cout;\nusing std::endl;\nusing Eigen::MatrixXd;\n\n#define USE_MATH_DEFINES\nint main(int argc, char** argv){\n\n\tstd::vector<double> px,py,z,R;\n\tdouble t[2],c[4];\n\tdouble tp[2],cp[4];\n\n\tint i=1;\n\ttp[0] = atof(argv[i++]);\t\n\ttp[1] = atof(argv[i++]);\t\n\tcp[0] = atof(argv[i++]);\t\n\tcp[1] = atof(argv[i++]);\t\n\tcp[2] = atof(argv[i++]);\t\n\tcp[3] = atof(argv[i++]);\n\n\tfor(;i<argc-1;i+=3){\n\t\tpx.push_back(atof(argv[i]));\n\t\tpy.push_back(atof(argv[i+1]));\n\t\tz.push_back(atof(argv[i+2]));\n\t\tR.push_back(Rval);\n\t}\n\n\tsize_t N = R.size();\n\n\tRSN::line_intersection(N, px, py, z, &t[0], &t[1], c);\n\tRSN::BOT::IWLS_2D(N, px, py, z, R, t, c, true);\n\tprintf(\"iwls: %0.3f, %0.3f [%0.3f, %0.3f, %0.3f, %0.3f]\\n\",t[0],t[1],c[0],c[1],c[2],c[3]);\n\n\tMatrixXd x0(2,1);\n\tMatrixXd x1(2,1);\n\tMatrixXd p0(2,2);\n\tMatrixXd p1(2,2);\n\tfor (int i=0;i<2;i++){\n\t\tx0(i) = tp[i];\n\t\tx1(i) = t[i];\n\t\tfor (int j=0;j<2;j++){\n\t\t\tp0(i,j) = cp[i*2+j];\n\t\t\tp1(i,j) = c[i*2+j];\n\t\t}\n\t}\n\tcout<<x0<<endl<<endl;\n\tcout<<x1<<endl<<endl;\n\tcout<<p0<<endl<<endl;\n\tcout<<p1<<endl<<endl;\n\n\tcout<< (p0.inverse()+p1.inverse()).inverse() * (p0.inverse()*x0 + p1.inverse()*x1) <<endl;\n\t//printf(\"iwls+prior: %0.3f, %0.3f [%0.3f, %0.3f, %0.3f, %0.3f]\\n\",t[0],t[1],cov[0],cov[1],cov[2],cov[3]);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "f4bd6ec3b872ce197c08c9a1e2d811a485260982", "size": 1356, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/iwlstest_prior.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/iwlstest_prior.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/iwlstest_prior.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.8709677419, "max_line_length": 107, "alphanum_fraction": 0.5538348083, "num_tokens": 586, "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": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/features2d.hpp>\n#include <iostream>\n#include <armadillo>\n#include \"highgui.h\"\n\nusing namespace std;\nusing namespace cv;\n\nvoid detectcan(cv::Mat &frame) {\n\tint h1 = 100;\n\tint h2 = 179;\n\tint s1 = 125;\n\tint s2 = 255;\n\tint v1 = 50;\n\tint v2 = 170;\n\tcv::Mat hsv;\n\tcv::cvtColor(frame, hsv, COLOR_BGR2HSV);\n\tcv::Mat hsv2mask, hsv2;\n\tcv::inRange(hsv, cv::Scalar(h1, s1, v1), cv::Scalar(h2, s2, v2), hsv2mask);\n\n\tarma::mat I;\n\tcvt_opencv2arma(hsv2mask, I);\n\tif (arma::accu(I) < 10.0) {\n\t\treturn;\n\t}\n\tarma::rowvec r = arma::sum(I, 0);\n\tarma::colvec c = arma::sum(I, 1);\n\tdouble midx = arma::sum(r * arma::cumsum(arma::ones<arma::vec>(r.n_elem))) / arma::sum(r);\n\tdouble midy = arma::sum(c % arma::cumsum(arma::ones<arma::vec>(c.n_elem))) / arma::sum(c);\n\n\tdouble covx = sqrt(arma::sum(r * arma::square(arma::cumsum(arma::ones<arma::vec>(r.n_elem)) - midx)) / arma::sum(r));\n\t//double estw = covx;\n\t//double esth = estw / 0.5;\n\t//estw *= 3; // strange constants\n\t//esth *= 3;\n\n\tarma::vec cokecanpos = arma::vec({ midx, midy });\n\tdouble cokecanwidth = covx * 3;\n\tcout << \"pos: \" << cokecanpos << endl;\n\tcout << \"width: \" << cokecanwidth << endl;\n}\n\nint main(int argc, char *argv[]) {\n\tif (argc != 8) {\n\t\tcout << \"usage: ./test img h1 h2 s1 s2 v1 v2\\n\";\n\t\treturn 1;\n\t}\n\tint h1 = atoi(argv[2]);\n\tint h2 = atoi(argv[3]);\n\tint s1 = atoi(argv[4]);\n\tint s2 = atoi(argv[5]);\n\tint v1 = atoi(argv[6]);\n\tint v2 = atoi(argv[7]);\n\n\t// convert to hsv\n\tMat img = imread(argv[1]);\n\tMat hsv;\n\tcvtColor(img, hsv, COLOR_BGR2HSV);\n\n\t// in range masking\n\tMat hsv2mask, hsv2;\n\tinRange(hsv, Scalar(h1, s1, v1), Scalar(h2, s2, v2), hsv2mask);\n\t//hsv.copyTo(hsv2, hsv2mask);\n\n\tarma::mat I;\n\tcvt_opencv2arma(hsv2mask, I);\n\tarma::rowvec r = arma::sum(I, 0);\n\tarma::colvec c = arma::sum(I, 1);\n\tdouble midx = arma::sum(r * arma::cumsum(arma::ones<arma::vec>(r.n_elem))) / arma::sum(r);\n\tdouble midy = arma::sum(c % arma::cumsum(arma::ones<arma::vec>(c.n_elem))) / arma::sum(c);\n\tVec3b color(255, 0, 0);\n\tcircle(img, Point((int)midx, (int)midy), 4, color, 1);\n\n\tdouble covx = sqrt(arma::sum(r * arma::square(arma::cumsum(arma::ones<arma::vec>(r.n_elem)) - midx)) / arma::sum(r));\n\tdouble estw = covx;\n\tdouble esth = estw / 0.5;\n\testw *= 3; // strange constants\n\testh *= 3;\n\n\trectangle(img, Rect(midx-estw/2,midy-esth/2,estw,esth), Scalar(0, 0, 255), 2);\n\n\t// use histogram binning to get the center\n\n\t// create blob params\n\t/*SimpleBlobDetector::Params params;\n\n\t// Change thresholds\n\tparams.minThreshold = 10;\n\tparams.maxThreshold = 200;\n\n\t// Filter by Area.\n\tparams.filterByArea = true;\n\tparams.minArea = 1500;\n\n\t// Filter by Circularity\n\tparams.filterByCircularity = true;\n\tparams.minCircularity = 0.1;\n\n\t// Filter by Convexity\n\tparams.filterByConvexity = true;\n\tparams.minConvexity = 0.87;\n\n\t// Filter by Inertia\n\tparams.filterByInertia = true;\n\tparams.minInertiaRatio = 0.01;\n\n\tPtr<SimpleBlobDetector> blob = SimpleBlobDetector::create(params);\n\tvector<KeyPoint> kp;\n\tMat des;\n\tMat hsvd = hsv2mask * -0.75 + 255;\n\tblob->detect(hsvd, kp);\n\n\tcout << \"found \" << kp.size() << \" matches\\n\";\n\n\tMat kpimg;\n\tdrawKeypoints(img, kp, kpimg, Scalar(0, 0, 255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);*/\n\n\timshow(\"oldhsv\", hsv);\n\timshow(\"newhsv\", hsv2mask);\n\timshow(\"img\", img);\n\twaitKey(0);\n\treturn 1;\n}\n", "meta": {"hexsha": "9184e7dbbbcce7f6f9d16954f6590fbe3c16f5ee", "size": 3386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "visual/hsvcolorsegment/test.cpp", "max_stars_repo_name": "timrobot/Tachikoma-Project", "max_stars_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-11T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-11T19:04:33.000Z", "max_issues_repo_path": "visual/hsvcolorsegment/test.cpp", "max_issues_repo_name": "TimothyYong/Tachikoma-Project", "max_issues_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "visual/hsvcolorsegment/test.cpp", "max_forks_repo_name": "TimothyYong/Tachikoma-Project", "max_forks_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6614173228, "max_line_length": 118, "alphanum_fraction": 0.6488481985, "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382004, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5793046179748538}}
{"text": "#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54_classic.hpp>\n", "meta": {"hexsha": "1b2d3d557d155b94c837cbd75c7cdd4a129658f9", "size": 76, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta_cash_karp54_classic.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta_cash_karp54_classic.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta_cash_karp54_classic.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 38.0, "max_line_length": 75, "alphanum_fraction": 0.8684210526, "num_tokens": 23, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5792394595675143}}
{"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();  //\u89c4\u8303\u5316\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);  //\u51fa\u6765\u7684norm=1--\u59ff\u6001\u56db\u5143\u6570\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;  //\u5fc5\u987b\u5148\u89c4\u8303\u5316\n  std::cout << qw.dot(q) << std::endl;              // dot product \u5185\u79ef\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": "/**\n * @file\n * @brief Outputs location of global shape functions as managed by a Dofhandler\n * @author Ralf Hiptmair\n * @date   October 2018\n * @copyright MIT License\n */\n\n#include <boost/program_options.hpp>\n\n#include <lf/assemble/assemble.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include \"lf/assemble/assemble.h\"\n#include \"lf/mesh/test_utils/test_meshes.h\"\n#include \"lf/mesh/utils/utils.h\"\n\nint main(int argc, char** argv) {\n  // The following code is modeled after the example from\n  // https://theboostcpplibraries.com/boost.program_options\n  // and defines allowed command line arguments:\n  namespace po = boost::program_options;\n  po::options_description desc(\"Allowed options\");\n  // clang-format off\n  desc.add_options()\n  (\"help,h\", \"--ndof_node <N> --ndof_edge <N> --ndof_tria <N> --ndof_quad <N>\")\n  (\"ndof_node,n\", po::value<int>()->default_value(1), \"No of dofs on nodes\")\n  (\"ndof_edge,e\", po::value<int>()->default_value(2), \"No of dofs on edges\")\n  (\"ndof_tria,t\", po::value<int>()->default_value(1), \"No of dofs on triangles\")\n  (\"ndof_quad,q\", po::value<int>()->default_value(4), \"Mp of dofs on quadrilaterals\");\n  // clang-format on\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  if (vm.count(\"help\") > 0) {\n    std::cout << desc << std::endl;\n  } else {\n    // Retrieve number of degrees of freedom for each entity type from command\n    // line arguments\n    lf::base::size_type ndof_node = 1;\n    if (vm.count(\"ndof_node\") > 0) {\n      ndof_node = vm[\"ndof_node\"].as<int>();\n    }\n    lf::base::size_type ndof_edge = 2;\n    if (vm.count(\"ndof_edge\") > 0) {\n      ndof_edge = vm[\"ndof_edge\"].as<int>();\n    }\n    lf::base::size_type ndof_tria = 1;\n    if (vm.count(\"ndof_tria\") > 0) {\n      ndof_tria = vm[\"ndof_tria\"].as<int>();\n    }\n    lf::base::size_type ndof_quad = 4;\n    if (vm.count(\"ndof_quad\") > 0) {\n      ndof_quad = vm[\"ndof_quad\"].as<int>();\n    }\n    std::cout << \"LehrFEM++ demo: assignment of global shape functions\"\n              << std::endl;\n    std::cout << \"#dof/vertex = \" << ndof_node << std::endl;\n    std::cout << \"#dof/edge = \" << ndof_edge << std::endl;\n    std::cout << \"#dof/triangle = \" << ndof_tria << std::endl;\n    std::cout << \"#dof/quadrilateral = \" << ndof_quad << std::endl;\n\n    // Build a mesh comprising two cells\n    std::shared_ptr<lf::mesh::Mesh> mesh_p =\n        lf::mesh::test_utils::GenerateHybrid2DTestMesh(2);\n    // Output information about the mesh\n    lf::mesh::utils::printinfo_ctrl = 100;\n    lf::mesh::Entity::output_ctrl_ = 0;\n    lf::mesh::utils::PrintInfo(*mesh_p, std::cout);\n\n    // Create a dof handler object describing a uniform distribution\n    // of shape functions\n    lf::assemble::UniformFEDofHandler dof_handler(\n        mesh_p, {{lf::base::RefEl::kPoint(), ndof_node},\n                 {lf::base::RefEl::kSegment(), ndof_edge},\n                 {lf::base::RefEl::kTria(), ndof_tria},\n                 {lf::base::RefEl::kQuad(), ndof_quad}});\n    lf::assemble::DofHandler::output_ctrl_ = 30;\n    std::cout << dof_handler << std::endl;\n  }\n}  // end main\n", "meta": {"hexsha": "eb14338421e016571e8f7728d1053edfbb5c4e04", "size": 3119, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/assemble/dof_demo.cc", "max_stars_repo_name": "Cryoris/lehrfempp", "max_stars_repo_head_hexsha": "fe5b830c25b950be9be90dda0f4f693a6dcb054b", "max_stars_repo_licenses": ["MIT"], "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/assemble/dof_demo.cc", "max_issues_repo_name": "Cryoris/lehrfempp", "max_issues_repo_head_hexsha": "fe5b830c25b950be9be90dda0f4f693a6dcb054b", "max_issues_repo_licenses": ["MIT"], "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/assemble/dof_demo.cc", "max_forks_repo_name": "Cryoris/lehrfempp", "max_forks_repo_head_hexsha": "fe5b830c25b950be9be90dda0f4f693a6dcb054b", "max_forks_repo_licenses": ["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.5061728395, "max_line_length": 86, "alphanum_fraction": 0.6306508496, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5792195672648636}}
{"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 <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <test/unit/math/rev/scal/fun/nan_util.hpp>\n#include <test/unit/math/rev/scal/util.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <limits>\n\nTEST(AgradRev, ibeta_vvv) {\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  using stan::math::var;\n\n  using boost::math::ibeta_derivative;\n\n  AVAR a = 0.6;\n  AVAR b = 0.3;\n  AVAR c = 0.5;\n  AVAR f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n\n  AVEC x = createAVEC(a, b, c);\n  VEC grad_f;\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(-0.436993, grad_f[0]);\n  EXPECT_FLOAT_EQ(0.7779751, grad_f[1]);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a.val(), b.val(), c.val()), grad_f[2]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(a, b, c);\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(-0.03737671, grad_f[0]);\n  EXPECT_FLOAT_EQ(0.02507405, grad_f[1]);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a.val(), b.val(), c.val()), grad_f[2]);\n}\nTEST(AgradRev, ibeta_vvd) {\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  using stan::math::var;\n\n  using boost::math::ibeta_derivative;\n\n  AVAR a = 0.6;\n  AVAR b = 0.3;\n  double c = 0.5;\n  AVAR f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n\n  AVEC x = createAVEC(a, b);\n  VEC grad_f;\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(-0.436993, grad_f[0]);\n  EXPECT_FLOAT_EQ(0.7779751, grad_f[1]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(a, b);\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(-0.03737671, grad_f[0]);\n  EXPECT_FLOAT_EQ(0.02507405, grad_f[1]);\n}\nTEST(AgradRev, ibeta_vdv) {\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  using stan::math::var;\n\n  using boost::math::ibeta_derivative;\n\n  AVAR a = 0.6;\n  double b = 0.3;\n  AVAR c = 0.5;\n  AVAR f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n\n  AVEC x = createAVEC(a, c);\n  VEC grad_f;\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(-0.436993, grad_f[0]);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a.val(), b, c.val()), grad_f[1]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(a, c);\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(-0.03737671, grad_f[0]);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a.val(), b, c.val()), grad_f[1]);\n}\nTEST(AgradRev, ibeta_vdd) {\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  using stan::math::var;\n\n  using boost::math::ibeta_derivative;\n\n  AVAR a = 0.6;\n  double b = 0.3;\n  double c = 0.5;\n  AVAR f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n\n  AVEC x = createAVEC(a);\n  VEC grad_f;\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(-0.436993, grad_f[0]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(a);\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(-0.03737671, grad_f[0]);\n}\nTEST(AgradRev, ibeta_dvv) {\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  using stan::math::var;\n\n  using boost::math::ibeta_derivative;\n\n  double a = 0.6;\n  AVAR b = 0.3;\n  AVAR c = 0.5;\n  AVAR f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n\n  AVEC x = createAVEC(b, c);\n  VEC grad_f;\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(0.7779751, grad_f[0]);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a, b.val(), c.val()), grad_f[1]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(b, c);\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(0.02507405, grad_f[0]);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a, b.val(), c.val()), grad_f[1]);\n}\nTEST(AgradRev, ibeta_dvd) {\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  using stan::math::var;\n\n  using boost::math::ibeta_derivative;\n\n  double a = 0.6;\n  AVAR b = 0.3;\n  double c = 0.5;\n  AVAR f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n\n  AVEC x = createAVEC(b);\n  VEC grad_f;\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(0.7779751, grad_f[0]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(b);\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(0.02507405, grad_f[0]);\n}\nTEST(AgradRev, ibeta_ddv) {\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  using stan::math::var;\n\n  using boost::math::ibeta_derivative;\n\n  double a = 0.6;\n  double b = 0.3;\n  AVAR c = 0.5;\n  AVAR f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n\n  AVEC x = createAVEC(c);\n  VEC grad_f;\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a, b, c.val()), grad_f[0]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a, b, c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(c);\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a, b, c.val()), grad_f[0]);\n}\n\nstruct ibeta_fun {\n  template <typename T0, typename T1, typename T2>\n  inline typename stan::return_type<T0, T1, T2>::type operator()(\n      const T0& arg1, const T1& arg2, const T2& arg3) const {\n    return ibeta(arg1, arg2, arg3);\n  }\n};\n\nTEST(AgradRev, ibeta_NaN) {\n  ibeta_fun ibeta_;\n  test_nan(ibeta_, 0.6, 0.3, 0.5, true, false);\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  AVAR a = 0.6;\n  AVAR b = 0.3;\n  AVAR c = 0.5;\n  test::check_varis_on_stack(stan::math::ibeta(a, b, c));\n  test::check_varis_on_stack(stan::math::ibeta(a, b, 0.5));\n  test::check_varis_on_stack(stan::math::ibeta(a, 0.3, c));\n  test::check_varis_on_stack(stan::math::ibeta(a, 0.3, 0.5));\n  test::check_varis_on_stack(stan::math::ibeta(0.6, b, c));\n  test::check_varis_on_stack(stan::math::ibeta(0.6, b, 0.5));\n  test::check_varis_on_stack(stan::math::ibeta(0.6, 0.3, c));\n}\n", "meta": {"hexsha": "13c0dcab921d79a42e499956003ed9957fee3014", "size": 5538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/scal/fun/ibeta_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/rev/scal/fun/ibeta_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/rev/scal/fun/ibeta_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7682403433, "max_line_length": 74, "alphanum_fraction": 0.6283856988, "num_tokens": 2146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.579209274187771}}
{"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 * @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  //====================\n  \n  // allocate memory\n  A.reserve(7);\n\n  // Get |K| - note that each cell has the same shape, so we can\n  // get it outside of the loop\n  double h = 1.0/(M+1);\n  double K = 0.5*h*h;\n\n  // Looper over all nodes\n  for(int i=0; i<M2; ++i) {\n\n    A.coeffRef(i,j) = v;\n  }\n\n  //====================\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  //====================\n  double h = 1./(M+1);\n  double K = 0.5*h*h;\n\n  Eigen::Matrix3d A_K;\n  A_K << 2.0, -1.0, -1.0,\n        -1.0,  2.0,  0.0\n        -1.0,  0.0,  2.0;\n  A_K *= 0.5;\n\n  Eigen::Matrix3d M_K;\n  M_K << 2.0, 1.0, 1.0,\n         1.0, 2.0, 1.0,\n         1.0, 1.0, 2.0;\n  M_K *= K/12.0;\n\n  B_K = (1.0 - c)*A_K + c*M_K;\n  //====================\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  //====================\n  // Your code goes here\n  //====================\n  return assemble(M, B_K);\n}\n/* SAM_LISTING_END_4 */\n\n}  // namespace MaximumPrinciple\n", "meta": {"hexsha": "ef04c606d167eda51229baea999325ec43140ef4", "size": 1915, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MaximumPrinciple/mysolution/maximumprinciple.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/MaximumPrinciple/mysolution/maximumprinciple.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/MaximumPrinciple/mysolution/maximumprinciple.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": 21.7613636364, "max_line_length": 73, "alphanum_fraction": 0.5838120104, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.5789502800534353}}
{"text": "//Type:     Source file (Testing)\n//User:     n0688119 (Elliot Harding)\n//Purpose:  Testing the function route::maxGradient()\n\n/*\n                **Documentation**\n\nThis test file contains 14 tests for the function route::maxGradient(). The tests were chosen\nin order to test the full functionality of maxGradient, ensuring that it is implimented correctly.\nA range of data is used within the tests, this includes typical data, atypical data as well as\nincorrect data. This way the expected results from all types of data input can be tested.\n\nIn terms of atypical data, the extremes of input data can be tested. Once the edges of correct\ndata is tested, it is safe to assume that input data inbetween the edge cases will also work\ncorrectly.\n */\n\n//Includes:\n#include <boost/test/unit_test.hpp>\n#include \"logs.h\"\n#include \"route.h\"\n#include \"track.h\"\n\n//namespaces:\nusing namespace GPS;\n\n//Public variables:\nconst bool isFileName = true;\n\n//Test cases:\nBOOST_AUTO_TEST_SUITE(Route_maxGradient)\n\n/*\nTest 1:\ncreated using :     gpx log made manually\nDescription   :     This test case tests normal data, with variing elevation changes, the function should return\n                    the largest gradient between two points.\nGPX contains   :    Typical data, with varing elevation changes\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_ChangesInElevation){\n    Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_differentChangesInElevation.gpx\",isFileName);\n    BOOST_CHECK_CLOSE(route.maxGradient(),89.7426543,1);\n}\n\n/*\nTest 2:\ncreated using :     gpx log made manually\nDescription   :     Testing if the function finds the smallest negative gradient, given that all the gradients between\n                    points are negative.\nGPX contains   :    Positions all lower in elevation than the previous point, some to a greater extent\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_SmallestNegativeGradient){\n    Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_smallestNegativeGradient.gpx\",isFileName);\n    BOOST_CHECK_CLOSE(route.maxGradient(),-65.93637193,1);\n}\n\n/*\nTest 3:\ncreated using  :    generated via source function\nDescription    :    Testing if the function handles no change in latitude or longitude,\n                    as this would result in a division by zero as there is not change in\n                    distance(from a birds eye view)\nGPX contains   :    Assortment of positions, all with the same latitude and longitude\nExpected result:    function returns 90 degrees (-90 degrees in the case of a lower elevation)\n\n\n    !!!!TO NOTE!!!!\n    First I was going to do a boost check throw, but the teacher pointed out to me that\n    if the latitude and logitude are the same it is not an error but a feature, so instead I\n    compare with 90 degrees\n\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_noLatOrLongChange){\n    Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_noLatOrLongChange.gpx\",isFileName);\n    BOOST_CHECK_EQUAL(route.maxGradient(),90);\n}\n\n/*\nTest 4:\ncreated using :     generated via source function\nDescription   :     Testing the function returns 0 (meaning the greatest gradient change is 0), if there are no changes\n                    in elevation of the route\nGPX contains   :    Positions all the same elevation\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_NoElevationChange){\n    Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_noElevationChange.gpx\",isFileName);\n    BOOST_CHECK_EQUAL(route.maxGradient(),0);\n}\n\n/*\nTest 5:\ncreated using  :    generated via source function\nDescription    :    Testing the function handles a route if successive points have a positive gradient\nExpected result:    The largest positive gradient\nGPX contains   :    Positions all higher in elevation than the previous point with same increase between each\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_constantUpwards){\n    Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_constantUpwards.gpx\",isFileName);\n    BOOST_CHECK_CLOSE(route.maxGradient(),6.39971588,1);\n}\n\n/*\nTest 6:\ncreated using  :    generated via source function\nDescription    :    Testing the function handles a route if successive points have a negative gradient\nExpected result:    The largest negative gradient\nGPX contains   :    Positions all lower in elevation than the previous point with same decrease between each\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_constantDownwards){\n    Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_constantDownwards.gpx\",isFileName);\n    BOOST_CHECK_CLOSE(route.maxGradient(),-6.39971588,1);\n}\n\n/*\nTest 7:\ncreated using  :    generated via source function\nDescription    :    Testing the function handles a route gradient which goes up then down\nExpected result:    The largest positive gradient\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_UpThenDown){\n    Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_UpThenDown.gpx\",isFileName);\n    BOOST_CHECK_CLOSE(route.maxGradient(),6.39971588,1);\n}\n\n/*\nTest 8:\ncreated using  :    generated via source function\nDescription    :    Testing the function handles a route gradient which goes down then up\nExpected result:    The largest positive gradient\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_DownThenUp){\n    Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_DownThenUp.gpx\",isFileName);\n    BOOST_CHECK_CLOSE(route.maxGradient(),6.39971588,1);\n}\n\n/*\nTest 9:\ncreated using  :    generated via source function\nDescription    :    Testing the function can handle large elevation values\nExpected result:    The largest positive gradient\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_largeValues){\n    Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_largeValues.gpx\",isFileName);\n    BOOST_CHECK_CLOSE(route.maxGradient(),-6.39971588,0.1);\n}\n\n/*\nTest 10:\ncreated using  :    generated via source function\nDescription    :    Testing the function can handle precise decimal elevation values\nExpected result:    The largest positive gradient\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_smallValues){\n    Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_smallValues.gpx\",isFileName);\n    BOOST_CHECK_CLOSE(route.maxGradient(),-6.39971588,0.1);\n}\n\n/*\nTest 11:\ncreated using  :    generated via source function\nDescription    :    Testing the function can handle small decimal elevation values\nExpected result:    The largest positive gradient\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_smallElevationChanges){\n    Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_smallElevationChange.gpx\",isFileName);\n    BOOST_CHECK_CLOSE(route.maxGradient(),6.39971588,0.1);\n}\n\n/*\nTest 12:\ncreated using  :    generated via source function\nDescription    :    Testing if the function handles only one point, as two are needed to find a gradient\nGPX contains   :    Only one position\nExpected result:    std::invalid_argument thrown\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_onePoint){\n    Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_onePoint.gpx\",isFileName);\n    BOOST_CHECK_THROW(route.maxGradient(),std::invalid_argument);\n}\n\n/*\nTest 13:\ncreated using  :    gpx log made manually\nDescription    :    Testing if input that is not numbers is dealt with correctly\nGPX contains   :    Letters are input instead of numbers for the elevation\nExpected result:    std::invalid_argument thrown\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_incorrectInput){\n    BOOST_CHECK_THROW(Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_incorrectInput.gpx\",isFileName),std::invalid_argument);\n}\n\n/*\nTest 14:\ncreated using  :    generated via source function\nDescription    :    Testing if the function handles empty input correctly\nGPX contains   :    No data\nExpected result:    std::domain_error thrown\n*/\nBOOST_AUTO_TEST_CASE(n0688119_Route_maxGradient_noInput){\n    BOOST_CHECK_THROW(Route route = Route(LogFiles::GPXRoutesDir + \"n0688119_noInput.gpx\",isFileName),std::domain_error);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4266748b3e0a9d1f5982eb6dd25801d1cfe7a98f", "size": 8022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpx-tests/n0688119_Route_maxGradient.cpp", "max_stars_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_stars_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gpx-tests/n0688119_Route_maxGradient.cpp", "max_issues_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_issues_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gpx-tests/n0688119_Route_maxGradient.cpp", "max_forks_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_forks_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3235294118, "max_line_length": 132, "alphanum_fraction": 0.7615307903, "num_tokens": 1890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5789502682647766}}
{"text": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/saturated.hpp>\n#include <boost/simd/pack.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n\nnamespace bs = boost::simd;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& runtime)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], b[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i+1) : T(N+i+1);\n    b[i] = bs::sqr(a1[i]) ;\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n\n  STF_EQUAL(bs::sqr(aa1), bb);\n}\n\nSTF_CASE_TPL(\"Check sqr on pack\" , STF_NUMERIC_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  test<T, N>(runtime);\n  test<T, N/2>(runtime);\n  test<T, N*2>(runtime);\n}\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid tests(Env& runtime)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], b[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : T(-i);\n    b[i] = bs::saturated_(bs::sqr)(a1[i]) ;\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n\n  STF_EQUAL(bs::saturated_(bs::sqr)(aa1), bb);\n}\n\nSTF_CASE_TPL(\"Check saturated sqr on pack\" , STF_NUMERIC_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  tests<T, N>(runtime);\n  tests<T, N/2>(runtime);\n  tests<T, N*2>(runtime);\n}\n\n\nSTF_CASE_TPL (\" sqr real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::sqr;\n  using p_t = bs::pack<T>;\n  using r_t = decltype(sqr(p_t()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, p_t);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_EQUAL(sqr(bs::Inf<p_t>()), bs::Inf<p_t>());\n  STF_EQUAL(sqr(bs::Minf<p_t>()), bs::Inf<p_t>());\n  STF_IEEE_EQUAL(sqr(bs::Nan<p_t>()), bs::Nan<p_t>());\n#endif\n  STF_EQUAL(sqr(bs::Mone<p_t>()), bs::One<p_t>());\n  STF_EQUAL(sqr(bs::One<p_t>()), bs::One<p_t>());\n  STF_EQUAL(sqr(bs::Zero<p_t>()), bs::Zero<p_t>());\n} // end of test for floating_\n\nSTF_CASE_TPL (\" sqr unsigned_int\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::sqr;\n  using p_t = bs::pack<T>;\n  using r_t = decltype(sqr(p_t()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, p_t);\n\n  // specific values tests\n  STF_EQUAL(sqr(bs::One<p_t>()), bs::One<p_t>());\n  STF_EQUAL(sqr(bs::Zero<p_t>()), bs::Zero<p_t>());\n} // end of test for unsigned_int_\n\nSTF_CASE_TPL (\" sqr signed_int\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::sqr;\n  using p_t = bs::pack<T>;\n  using r_t = decltype(sqr(p_t()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, p_t);\n\n  // specific values tests\n  STF_EQUAL(sqr(bs::Mone<p_t>()), bs::One<p_t>());\n  STF_EQUAL(sqr(bs::One<p_t>()), bs::One<p_t>());\n  STF_EQUAL(sqr(bs::Zero<p_t>()), bs::Zero<p_t>());\n} // end of test for signed_int_\n\n", "meta": {"hexsha": "c52d4669320a2e04efd99b319658e90660f00da2", "size": 3443, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/sqr.regular.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "test/function/simd/sqr.regular.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/simd/sqr.regular.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": 26.0833333333, "max_line_length": 100, "alphanum_fraction": 0.5974440895, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7185944046238982, "lm_q1q2_score": 0.578922783186833}}
{"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": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/function/erfc_inv.hpp>\n#include <boost/math/special_functions/erf.hpp>\n#include <eve/function/is_negative.hpp>\n#include <eve/function/is_positive.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/platform.hpp>\n#include <cmath>\n\n// TTS_CASE_TPL(\"Check eve::erfc_inv return type\", EVE_TYPE)\n// {\n//   TTS_EXPR_IS(eve::erfc_inv(T(0)), T);\n// }\n\nTTS_CASE_TPL(\"Check eve::erfc_inv behavior\", EVE_TYPE)\n{\n  auto eve__erfc_inv =  [](auto x) { return eve::erfc_inv(x); };\n\n if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_IEEE_EQUAL(eve__erfc_inv(eve::nan(eve::as<T>()))  , eve::nan(eve::as<T>()) );\n    TTS_IEEE_EQUAL(eve__erfc_inv(eve::inf(eve::as<T>()))  , eve::nan(eve::as<T>()) );\n    TTS_IEEE_EQUAL(eve__erfc_inv(eve::minf(eve::as<T>())) , eve::nan(eve::as<T>()) );\n  }\n\n  TTS_ULP_EQUAL(eve__erfc_inv(T(35)), eve::nan(eve::as<T>()), 0.5);\n  TTS_ULP_EQUAL(eve__erfc_inv(T(-35)), eve::nan(eve::as<T>()), 0.5);\n\n TTS_IEEE_EQUAL(eve__erfc_inv(T( 0 )),eve::inf(eve::as<T>()) );\n TTS_ULP_EQUAL(eve__erfc_inv(T( 0.1 )), T( boost::math::erfc_inv(0.1)), 0.5 );\n  TTS_ULP_EQUAL(eve__erfc_inv(T( 0.2 )), T( boost::math::erfc_inv(0.2)), 1.0 );\n  TTS_ULP_EQUAL(eve__erfc_inv(T( 0.3 )), T( boost::math::erfc_inv(0.3)), 1 );\n  TTS_ULP_EQUAL(eve__erfc_inv(T( 0.5 )), T( boost::math::erfc_inv(0.5)),  1 );\n  TTS_ULP_EQUAL(eve__erfc_inv(T( 0.15)), T( boost::math::erfc_inv(0.15)), 0.5 );\n  TTS_ULP_EQUAL(eve__erfc_inv(T( 0.75)), T( boost::math::erfc_inv(0.75)), 0.5 );\n  TTS_ULP_EQUAL(eve__erfc_inv(T( 1.1 )), T( boost::math::erfc_inv(1.1)), 1.5 );\n  TTS_ULP_EQUAL(eve__erfc_inv(T( 1.2 )), T( boost::math::erfc_inv(1.2)), 1.5 );\n  TTS_ULP_EQUAL(eve__erfc_inv(T( 1.3 )), T( boost::math::erfc_inv(1.3)), 0.5 );\n  TTS_ULP_EQUAL(eve__erfc_inv(T( 1.5 )), T( boost::math::erfc_inv(1.5)),  1 );\n  TTS_ULP_EQUAL(eve__erfc_inv(T( 1.15)), T( boost::math::erfc_inv(1.15)), 1 );\n  TTS_ULP_EQUAL(eve__erfc_inv(T( 1.75)), T( boost::math::erfc_inv(1.75)), 0.5 );\n}\n", "meta": {"hexsha": "935159bbe2cf441d5c1648f3f026b36ebc6226de", "size": 2342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/special/erfc_inv/regular/erfc_inv.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/special/erfc_inv/regular/erfc_inv.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/special/erfc_inv/regular/erfc_inv.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.9215686275, "max_line_length": 100, "alphanum_fraction": 0.6033304868, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5789227783316737}}
{"text": "#include <stdlib.h>\n#include <iostream>\n#include <memory>\n#include \"conex/cone_program.h\"\n#include \"conex/constraint.h\"\n#include \"conex/linear_constraint.h\"\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\nnamespace conex {\nusing DenseMatrix = Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nTEST(LP, Dense) {\n  for (int i = 0; i < 1; i++) {\n    SolverConfiguration config;\n    config.prepare_dual_variables = true;\n    config.inv_sqrt_mu_max = 1000000;\n\n    int m = 5;\n    int n = 6 + 2 * i;\n    double eps = 1e-12;\n\n    DenseMatrix Alinear = DenseMatrix::Random(n, m);\n    DenseMatrix Clinear(n, 1);\n    Clinear.setConstant(1);\n\n    LinearConstraint linear_constraint{n, &Alinear, &Clinear};\n\n    Program prog(m);\n    prog.SetNumberOfVariables(m);\n    prog.AddConstraint(linear_constraint);\n\n    VectorXd b = Alinear.transpose() * Clinear;\n    DenseMatrix y(m, 1);\n    Solve(b, prog, config, y.data());\n\n    VectorXd x(n);\n    prog.GetDualVariable(0, &x);\n\n    VectorXd slack = Clinear - Alinear * y;\n    EXPECT_TRUE((Alinear.transpose() * x - b).norm() <= eps);\n    EXPECT_TRUE((slack).minCoeff() >= -eps);\n  }\n}\n\nEigen::VectorXd Vars(const Eigen::VectorXd& x, std::vector<int> indices) {\n  Eigen::VectorXd z(indices.size());\n  int cnt = 0;\n  for (auto i : indices) {\n    z(cnt++) = x(i);\n  }\n  return z;\n}\n\nusing Eigen::MatrixXd;\nusing std::vector;\nauto Combine(vector<MatrixXd> A, vector<MatrixXd> C,\n             vector<vector<int> > vars) {\n  int n = A.at(0).rows() * A.size();\n  int m = A.at(0).cols() * A.size();\n  Eigen::MatrixXd Af(n, m);\n  Eigen::MatrixXd Cf(n, 1);\n  Af.setZero();\n  Cf.setZero();\n  int cnt = 0;\n  int max_v = 0;\n  for (size_t i = 0; i < A.size(); i++) {\n    for (int k = 0; k < A.at(i).rows(); k++) {\n      Cf(cnt, 0) = C.at(i)(k, 0);\n      for (size_t j = 0; j < vars.at(i).size(); j++) {\n        Af(cnt, vars.at(i).at(j)) = A.at(i)(k, j);\n        if (vars.at(i).at(j) > max_v) {\n          max_v = vars.at(i).at(j);\n        }\n      }\n      cnt++;\n    }\n  }\n\n  Eigen::MatrixXd Ac = Af.topLeftCorner(cnt, max_v + 1);\n  Eigen::MatrixXd Cc = Cf.topLeftCorner(cnt, 1);\n  return LinearConstraint{Ac, Cc};\n}\n\nEigen::VectorXd SolveSparseHelper(bool sparse) {\n  double eps = 1e-8;\n  using Eigen::MatrixXd;\n  using std::vector;\n  SolverConfiguration config;\n  config.prepare_dual_variables = true;\n\n  int number_of_constraints = 50;\n  std::vector<std::vector<int> > variables(number_of_constraints);\n  vector<MatrixXd> A(number_of_constraints);\n  vector<MatrixXd> C(number_of_constraints);\n\n  srand(1);\n  int number_of_variables;\n  int vars_per_constraint = 5;\n  int rows_per_constraint = 10;\n  int var_start = 0;\n  for (int i = 0; i < number_of_constraints; i++) {\n    for (int j = 0; j < vars_per_constraint; j++) {\n      variables.at(i).push_back(var_start + j);\n    }\n    var_start = variables.at(i).back();\n  }\n  number_of_variables = variables.back().back() + 1;\n  for (int i = 0; i < number_of_constraints; i++) {\n    MatrixXd Ai =\n        DenseMatrix::Random(rows_per_constraint, variables.at(i).size());\n    MatrixXd Ci(rows_per_constraint, 1);\n    Ci.setConstant(1 * (i * .01 + 1));\n    C.at(i) = Ci;\n    A.at(i) = Ai;\n  }\n\n  auto E = C.at(0);\n  E.setConstant(1);\n  Eigen::VectorXd b(number_of_variables);\n  b.setZero();\n  for (int i = 0; i < number_of_constraints; i++) {\n    Eigen::VectorXd bi = A.at(i).transpose() * E;\n    int cnt = 0;\n    for (auto k : variables.at(i)) {\n      b(k) += bi(cnt++);\n    }\n  }\n\n  Program prog(number_of_variables);\n\n  MatrixXd y(number_of_variables, 1);\n  if (sparse) {\n    for (int i = 0; i < number_of_constraints; i++) {\n      prog.AddConstraint(LinearConstraint(A.at(i), C.at(i)), variables.at(i));\n    }\n\n    Solve(b, prog, config, y.data());\n    MatrixXd Ax = b * 0;\n    for (int i = 0; i < number_of_constraints; i++) {\n      VectorXd slack = C.at(i) - A.at(i) * Vars(y, variables.at(i));\n      EXPECT_TRUE((slack).minCoeff() >= -eps);\n\n      MatrixXd xi(A.at(i).rows(), 1);\n      prog.GetDualVariable(i, &xi);\n\n      VectorXd temp = A.at(i).transpose() * xi;\n      int k = 0;\n      for (auto vk : variables.at(i)) {\n        Ax(vk) += temp(k);\n        k++;\n      }\n    }\n    EXPECT_NEAR((Ax - b).norm(), 0, 1e-8);\n  } else {\n    prog.AddConstraint(Combine(A, C, variables));\n    Solve(b, prog, config, y.data());\n\n    auto res = b;\n    auto L = Combine(A, C, variables);\n    VectorXd slack = L.constraint_affine_ - L.constraint_matrix_ * y;\n\n    MatrixXd xi(L.constraint_affine_.rows(), 1);\n    prog.GetDualVariable(0, &xi);\n    EXPECT_NEAR((b - L.constraint_matrix_.transpose() * xi).norm(), 0, 1e-8);\n  }\n\n  return y;\n}\n\n// Solve the same problem in dense and sparse format.\nTEST(LP, Sparse) {\n  auto y1 = SolveSparseHelper(true);\n  auto y2 = SolveSparseHelper(false);\n  EXPECT_NEAR((y1 - y2).norm(), 0, 1e-7);\n}\n\nEigen::VectorXd SolveFillIn(bool sparse) {\n  double eps = 1e-8;\n  using Eigen::MatrixXd;\n  using std::vector;\n  SolverConfiguration config;\n  config.prepare_dual_variables = true;\n\n  int number_of_constraints = 4;\n  std::vector<std::vector<int> > variables{{0, 1}, {1, 2}, {2, 3}, {0, 3}};\n\n  int number_of_variables = 3 + 1;\n  vector<MatrixXd> A(number_of_constraints);\n  vector<MatrixXd> C(number_of_constraints);\n\n  srand(1);\n  int rows_per_constraint = 3;\n\n  for (int i = 0; i < number_of_constraints; i++) {\n    MatrixXd Ai =\n        DenseMatrix::Random(rows_per_constraint, variables.at(i).size());\n    MatrixXd Ci(rows_per_constraint, 1);\n    Ci.setConstant(1 * (i * .01 + 1));\n    C.at(i) = Ci;\n    A.at(i) = Ai;\n  }\n\n  auto E = C.at(0);\n  E.setConstant(1);\n  Eigen::VectorXd b(number_of_variables);\n  b.setZero();\n  for (int i = 0; i < number_of_constraints; i++) {\n    Eigen::VectorXd bi = A.at(i).transpose() * E;\n    int cnt = 0;\n    for (auto k : variables.at(i)) {\n      b(k) += bi(cnt++);\n    }\n  }\n\n  Program prog(number_of_variables);\n\n  MatrixXd y(number_of_variables, 1);\n  if (sparse) {\n    for (int i = 0; i < number_of_constraints; i++) {\n      prog.AddConstraint(LinearConstraint(A.at(i), C.at(i)), variables.at(i));\n    }\n\n    Solve(b, prog, config, y.data());\n    MatrixXd Ax = b * 0;\n    for (int i = 0; i < number_of_constraints; i++) {\n      VectorXd slack = C.at(i) - A.at(i) * Vars(y, variables.at(i));\n      EXPECT_TRUE((slack).minCoeff() >= -eps);\n\n      MatrixXd xi(A.at(i).rows(), 1);\n      prog.GetDualVariable(i, &xi);\n      VectorXd temp = A.at(i).transpose() * xi;\n      int k = 0;\n      for (auto vk : variables.at(i)) {\n        Ax(vk) += temp(k);\n        k++;\n      }\n    }\n    EXPECT_NEAR((Ax - b).norm(), 0, 1e-8);\n  } else {\n    prog.AddConstraint(Combine(A, C, variables));\n    Solve(b, prog, config, y.data());\n\n    auto res = b;\n    auto L = Combine(A, C, variables);\n    VectorXd slack = L.constraint_affine_ - L.constraint_matrix_ * y;\n\n    MatrixXd xi(L.constraint_affine_.rows(), 1);\n    prog.GetDualVariable(0, &xi);\n    EXPECT_NEAR((b - L.constraint_matrix_.transpose() * xi).norm(), 0, 1e-8);\n  }\n\n  return y;\n}\n\nTEST(LP, SparseWithFillIn) {\n  DUMP(\"HEHEH!\");\n  auto y1 = SolveFillIn(true);\n  auto y2 = SolveFillIn(false);\n  EXPECT_NEAR((y1 - y2).norm(), 0, 1e-7);\n}\n\n}  // namespace conex\n", "meta": {"hexsha": "33876db01025b2122196d2d1334257747405c32d", "size": 7125, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/test/test_lp.cc", "max_stars_repo_name": "ToyotaResearchInstitute/conex", "max_stars_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T08:02:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T21:53:22.000Z", "max_issues_repo_path": "conex/test/test_lp.cc", "max_issues_repo_name": "ToyotaResearchInstitute/conex", "max_issues_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/test/test_lp.cc", "max_forks_repo_name": "ToyotaResearchInstitute/conex", "max_forks_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T16:02:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T11:25:46.000Z", "avg_line_length": 26.8867924528, "max_line_length": 78, "alphanum_fraction": 0.6046315789, "num_tokens": 2162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5789227667695641}}
{"text": "/**\n * @file systemode_main.cc\n * @brief NPDE homework SystemODE\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n\n#include \"../../../lecturecodes/helperfiles/polyfit.h\"\n#include \"systemode.h\"\n\n/* SAM_LISTING_BEGIN_0 */\nint main() {\n  // PARAMETERS\n  double T = 1;\n  int n = 5;\n\n  // INITIAL VALUE\n  Eigen::VectorXd y0(2 * n);\n  for (int i = 0; i < n; ++i) {\n    y0(i) = (i + 1.) / n;\n    y0(i + n) = -1;\n  }\n\n  // SETUP\n  double conv_rate = 0;\n  std::cout << std::setw(8) << \"M\" << std::setw(20) << \"Error\" << std::endl;\n\n  //====================\n  // Your code goes here\n  //====================\n\n  std::cout << \"Convergence rate: \" << std::round(std::abs(conv_rate))\n            << std::endl;\n\n  return 0;\n}\n/* SAM_LISTING_END_0 */\n", "meta": {"hexsha": "4fe0429c0b096822cb41bce0db357419cebbf614", "size": 861, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/SystemODE/templates/systemode_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/SystemODE/templates/systemode_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/SystemODE/templates/systemode_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 19.5681818182, "max_line_length": 76, "alphanum_fraction": 0.556329849, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5788966351184278}}
{"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_ILOGB_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ILOGB_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing ilogb capabilities\n\n    This function returns the integer truncation\n    of the base 2 logarithm of x.\n\n    It coincides with the @ref exponent function\n    on all platforms supported.\n\n    @par Semantic:\n\n    @code\n    auto r = ilogb(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    auto r = saturated_(toint)(log2(x));\n    @endcode\n\n    @see exponent, log2, toint, saturated\n\n  **/\n  Value ilogb(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/ilogb.hpp>\n#include <boost/simd/function/simd/ilogb.hpp>\n\n#endif\n", "meta": {"hexsha": "191c7b3cd2259f3a92459837cd80d11c8ad7741b", "size": 1144, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/ilogb.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/ilogb.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/ilogb.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.0, "max_line_length": 100, "alphanum_fraction": 0.5839160839, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5788694018715311}}
{"text": "#pragma once\n\n#include <dlib/clustering.h>\n#include <optional>\n#include <vector>\n\nnamespace otus {\n  struct Point {\n    using Cluster = std::optional<unsigned long>;\n\n    Cluster cluster { };\n    float x { }, y { };\n  };\n\n  class Clusterer {\n  public:\n    Clusterer(std::vector<Point> &data, float gamma=0.1, float accuracy=0.01):\n    data(data),\n    kCentroid(KernelType(gamma), accuracy) { }\n\n    void operator()(int numberOfClusters);\n\n  private:\n    using SampleType = dlib::matrix<float, 2, 1>;\n    using KernelType = dlib::radial_basis_kernel<SampleType>;\n\n    std::vector<Point> & data;\n    dlib::kcentroid<KernelType> kCentroid;\n  };\n}\n", "meta": {"hexsha": "c32df9cff1f6e30f3285ad76f6943808c366ae6d", "size": 644, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/clusterer.hpp", "max_stars_repo_name": "bergentroll/otus-cpp-15", "max_stars_repo_head_hexsha": "f3c691570a438f4c91fcaf2464e442c68a9861e3", "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": "inc/clusterer.hpp", "max_issues_repo_name": "bergentroll/otus-cpp-15", "max_issues_repo_head_hexsha": "f3c691570a438f4c91fcaf2464e442c68a9861e3", "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": "inc/clusterer.hpp", "max_forks_repo_name": "bergentroll/otus-cpp-15", "max_forks_repo_head_hexsha": "f3c691570a438f4c91fcaf2464e442c68a9861e3", "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.7741935484, "max_line_length": 78, "alphanum_fraction": 0.6568322981, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5788693910357494}}
{"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": "#define CATCH_CONFIG_MAIN\n#include <Eigen/Dense>\n#include <catch.hpp>\n#include <random>\n\n#include \"EDP/ConstructSparseMat.hpp\"\n#include \"EDP/LocalHamiltonian.hpp\"\n\n#include \"yavque/Circuit.hpp\"\n#include \"yavque/operators.hpp\"\n#include \"yavque/utils.hpp\"\n\n#include \"common.hpp\"\n\ntbb::global_control gc(tbb::global_control::max_allowed_parallelism, 2);\n\nyavque::Circuit construct_diagonal_tfi(const uint32_t N)\n{\n\tyavque::Circuit circ(1 << N);\n\tEigen::VectorXd zz_all(1 << N);\n\n\tfor(uint32_t n = 0; n < (1u << N); ++n)\n\t{\n\t\tint elt = 0;\n\t\tfor(uint32_t k = 0; k < N; ++k)\n\t\t{\n\t\t\tint z0 = 1 - 2 * ((n >> k) & 1);\n\t\t\tint z1 = 1 - 2 * ((n >> ((k + 1) % N)) & 1);\n\t\t\telt += z0 * z1;\n\t\t}\n\t\tzz_all(n) = elt;\n\t}\n\n\tauto zz_all_ham = yavque::DiagonalOperator(zz_all, \"zz all\");\n\tauto x_all_ham\n\t\t= yavque::SumLocalHam(N, yavque::pauli_x().cast<yavque::cx_double>(), \"x all\");\n\n\tfor(uint32_t p = 0; p < 4; ++p)\n\t{\n\t\tcirc.add_op_right<yavque::DiagonalHamEvol>(zz_all_ham);\n\t\tcirc.add_op_right<yavque::SumLocalHamEvol>(x_all_ham);\n\t}\n\tcirc.add_op_right<yavque::DiagonalHamEvol>(zz_all_ham);\n\treturn circ;\n}\n\nauto construct_bare_tfi(const uint32_t N)\n{\n\tyavque::Circuit circ(1U << N);\n\tstd::vector<yavque::Variable> variables(9);\n\n\tstd::vector<yavque::Hamiltonian> zz_hams;\n\n\tfor(uint32_t k = 0; k < N; ++k)\n\t{\n\t\tedp::LocalHamiltonian<double> lh(N, 2);\n\t\tlh.addTwoSiteTerm({k, (k + 1) % N}, yavque::pauli_zz());\n\t\tzz_hams.emplace_back(edp::constructSparseMat<yavque::cx_double>(1 << N, lh));\n\t}\n\tauto x_all_ham\n\t\t= yavque::SumLocalHam(N, yavque::pauli_x().cast<yavque::cx_double>(), \"x all\");\n\n\tfor(uint32_t p = 0; p < 4; ++p)\n\t{\n\t\tfor(uint32_t k = 0; k < N; k++)\n\t\t{\n\t\t\tcirc.add_op_right<yavque::HamEvol>(zz_hams[k], variables[2 * p + 0]);\n\t\t}\n\t\tcirc.add_op_right<yavque::SumLocalHamEvol>(x_all_ham, variables[2 * p + 1]);\n\t}\n\tfor(uint32_t k = 0; k < N; k++)\n\t{\n\t\tcirc.add_op_right<yavque::HamEvol>(zz_hams[k], variables[8]);\n\t}\n\n\treturn std::make_pair(std::move(circ), std::move(variables));\n}\n\nEigen::VectorXcd analytic_twoqubit(double theta, double phi)\n{\n\tEigen::VectorXcd res(4);\n\tconstexpr yavque::cx_double I(0., 1.);\n\n\tres(0) = cos(2 * phi) * exp(-I * theta) - I * sin(2 * phi) * exp(I * theta);\n\tres(1) = cos(2 * phi) * exp(I * theta) - I * sin(2 * phi) * exp(-I * theta);\n\tres(2) = cos(2 * phi) * exp(I * theta) - I * sin(2 * phi) * exp(-I * theta);\n\tres(3) = cos(2 * phi) * exp(-I * theta) - I * sin(2 * phi) * exp(I * theta);\n\n\treturn res / 2;\n}\n\nEigen::MatrixXcd rot_x(double phi)\n{\n\tconstexpr yavque::cx_double I(0., 1.);\n\tEigen::MatrixXcd rot_x(2, 2);\n\n\trot_x << cos(phi), -I * sin(phi), -I * sin(phi), cos(phi);\n\n\treturn rot_x;\n}\n\nEigen::MatrixXcd kron_n(const Eigen::MatrixXcd& m, uint32_t n)\n{\n\tEigen::MatrixXcd res(m);\n\tfor(uint32_t k = 1; k < n; ++k)\n\t{\n\t\tres = Eigen::kroneckerProduct(res, m).eval();\n\t}\n\treturn res;\n}\n\nEigen::VectorXcd product_fourqubit(double theta1, double phi1, double theta2, double phi2)\n{\n\tEigen::VectorXcd res(16);\n\tconstexpr yavque::cx_double I(0., 1.);\n\n\tEigen::VectorXd zz(16);\n\tzz << 4, 0, 0, 0, 0, -4, 0, 0, 0, 0, -4, 0, 0, 0, 0, 4;\n\n\tEigen::VectorXcd v = Eigen::VectorXcd::Ones(16);\n\tv /= 4.0;\n\n\tv.array() *= (-I * theta1 * zz.array()).exp();\n\tv = kron_n(rot_x(phi1), 4) * v;\n\tv.array() *= (-I * theta2 * zz.array()).exp();\n\tv = kron_n(rot_x(phi2), 4) * v;\n\n\treturn v;\n}\n\nTEST_CASE(\"test two qubit\", \"[tfi-twoqubit]\")\n{\n\tusing namespace yavque;\n\tusing namespace Eigen;\n\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\n\tstd::normal_distribution<> ndist(0., 1.);\n\n\tconstexpr unsigned int N = 2;\n\tconst double eps = 1e-6;\n\n\tEigen::VectorXcd zz(1 << N);\n\n\tfor(uint32_t n = 0; n < (1u << N); ++n)\n\t{\n\t\tint z0 = 1 - 2 * ((n >> 0) & 1);\n\t\tint z1 = 1 - 2 * ((n >> 1) & 1);\n\t\tzz(n) = z0 * z1;\n\t}\n\n\tauto zz_all_ham = yavque::DiagonalOperator(zz, \"zz all\");\n\tauto x_all_ham\n\t\t= yavque::SumLocalHam(N, yavque::pauli_x().cast<yavque::cx_double>(), \"x all\");\n\n\tauto circ = yavque::Circuit(1 << N);\n\n\tfor(uint32_t p = 0; p < 1; ++p)\n\t{\n\t\tcirc.add_op_right<yavque::DiagonalHamEvol>(zz_all_ham);\n\t\tcirc.add_op_right<yavque::SumLocalHamEvol>(x_all_ham);\n\t}\n\n\tEigen::MatrixXd ham(4, 4);\n\tham << -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1;\n\n\tauto variables = circ.variables();\n\n\tEigen::VectorXcd ini = Eigen::VectorXcd::Ones(4);\n\tini /= sqrt(4.0);\n\n\tcirc.set_input(ini);\n\n\tfor(uint32_t _instance = 0; _instance < 10; ++_instance)\n\t{\n\t\tdouble theta = ndist(re);\n\t\tdouble phi = ndist(re);\n\t\tvariables[0] = theta;\n\t\tvariables[1] = phi;\n\n\t\tfor(uint32_t epoch = 0; epoch < 100; ++epoch)\n\t\t{ // learning loop\n\t\t\ttheta = variables[0].value();\n\t\t\tphi = variables[1].value();\n\n\t\t\tcirc.clear_evaluated();\n\t\t\tEigen::VectorXcd output = *circ.output();\n\t\t\tEigen::VectorXcd analytic = analytic_twoqubit(theta, phi);\n\n\t\t\tREQUIRE((output - analytic).norm() < 1e-6);\n\n\t\t\t// test grad\n\t\t\tfor(auto& p : variables)\n\t\t\t{\n\t\t\t\tp.zero_grad();\n\t\t\t}\n\t\t\tcirc.derivs();\n\t\t\tEigen::MatrixXcd grads(1 << N, 2);\n\t\t\tgrads.col(0) = *variables[0].grad();\n\t\t\tgrads.col(1) = *variables[1].grad();\n\t\t\tEigen::VectorXd egrad_circ = 2 * (output.adjoint() * ham * grads).real();\n\n\t\t\tEigen::VectorXcd v1 = analytic_twoqubit(theta + eps, phi);\n\t\t\tEigen::VectorXcd v2 = analytic_twoqubit(theta - eps, phi);\n\n\t\t\tEigen::VectorXd egrad_num(2);\n\t\t\tegrad_num.coeffRef(0) = real(cx_double(v1.adjoint() * ham * v1)\n\t\t\t                             - cx_double(v2.adjoint() * ham * v2))\n\t\t\t                        / (2 * eps);\n\n\t\t\tv1 = analytic_twoqubit(theta, phi + eps);\n\t\t\tv2 = analytic_twoqubit(theta, phi - eps);\n\n\t\t\tegrad_num.coeffRef(1) = real(cx_double(v1.adjoint() * ham * v1)\n\t\t\t                             - cx_double(v2.adjoint() * ham * v2))\n\t\t\t                        / (2 * eps);\n\n\t\t\tREQUIRE((egrad_circ - egrad_num).norm() < 1e-6);\n\n\t\t\tfor(uint32_t k = 0; k < variables.size(); ++k)\n\t\t\t{\n\t\t\t\tvariables[k] -= 0.02 * egrad_circ(k);\n\t\t\t}\n\n\t\t\tstd::cout << real(cx_double(output.adjoint() * ham * output)) << std::endl;\n\t\t}\n\t}\n}\n\nTEST_CASE(\"test four qubit\", \"[tfi-fourqubit]\")\n{\n\tusing namespace yavque;\n\tusing namespace Eigen;\n\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\n\tstd::normal_distribution<> ndist(0., 1.);\n\n\tconstexpr unsigned int N = 4;\n\tconst double eps = 1e-6;\n\n\tEigen::VectorXd zz_all(1 << N);\n\n\tfor(uint32_t n = 0; n < (1u << N); ++n)\n\t{\n\t\tint elt = 0;\n\t\tfor(uint32_t k = 0; k < N; ++k)\n\t\t{\n\t\t\tint z0 = 1 - 2 * ((n >> k) & 1);\n\t\t\tint z1 = 1 - 2 * ((n >> ((k + 1) % N)) & 1);\n\t\t\telt += z0 * z1;\n\t\t}\n\t\tzz_all(n) = elt;\n\t}\n\n\tauto zz_all_ham = yavque::DiagonalOperator(zz_all, \"zz all\");\n\tauto x_all_ham\n\t\t= yavque::SumLocalHam(N, yavque::pauli_x().cast<yavque::cx_double>(), \"x all\");\n\n\tauto circ = yavque::Circuit(1 << N);\n\n\tfor(uint32_t p = 0; p < 2; ++p)\n\t{\n\t\tcirc.add_op_right<yavque::DiagonalHamEvol>(zz_all_ham);\n\t\tcirc.add_op_right<yavque::SumLocalHamEvol>(x_all_ham);\n\t}\n\n\tEigen::MatrixXd ham = zz_all.asDiagonal();\n\n\tauto variables = circ.variables();\n\n\tEigen::VectorXcd ini = Eigen::VectorXcd::Ones(16);\n\tini /= 4.0;\n\n\tcirc.set_input(ini);\n\n\tfor(uint32_t _instance = 0; _instance < 10; ++_instance)\n\t{\n\t\tdouble theta1 = ndist(re);\n\t\tdouble theta2 = ndist(re);\n\t\tdouble phi1 = ndist(re);\n\t\tdouble phi2 = ndist(re);\n\n\t\tvariables[0] = theta1;\n\t\tvariables[1] = phi1;\n\t\tvariables[2] = theta2;\n\t\tvariables[3] = phi2;\n\n\t\tfor(uint32_t epoch = 0; epoch < 100; ++epoch)\n\t\t{ // learning loop\n\t\t\ttheta1 = variables[0].value();\n\t\t\tphi1 = variables[1].value();\n\t\t\ttheta2 = variables[2].value();\n\t\t\tphi2 = variables[3].value();\n\n\t\t\tcirc.clear_evaluated();\n\t\t\tEigen::VectorXcd output = *circ.output();\n\t\t\tEigen::VectorXcd analytic = product_fourqubit(theta1, phi1, theta2, phi2);\n\n\t\t\tREQUIRE((output - analytic).norm() < 1e-6);\n\n\t\t\t// test grad\n\t\t\tfor(auto& p : variables)\n\t\t\t{\n\t\t\t\tp.zero_grad();\n\t\t\t}\n\t\t\tcirc.derivs();\n\t\t\tEigen::MatrixXcd grads(1 << N, 4);\n\t\t\tfor(uint32_t k = 0; k < 4; k++)\n\t\t\t{\n\t\t\t\tgrads.col(k) = *variables[k].grad();\n\t\t\t}\n\t\t\tEigen::VectorXd egrad_circ = 2 * (output.adjoint() * ham * grads).real();\n\n\t\t\tEigen::VectorXcd v1 = product_fourqubit(theta1 + eps, phi1, theta2, phi2);\n\t\t\tEigen::VectorXcd v2 = product_fourqubit(theta1 - eps, phi1, theta2, phi2);\n\n\t\t\tEigen::VectorXd egrad_num(4);\n\t\t\tegrad_num.coeffRef(0) = real(cx_double(v1.adjoint() * ham * v1)\n\t\t\t                             - cx_double(v2.adjoint() * ham * v2))\n\t\t\t                        / (2 * eps);\n\n\t\t\tv1 = product_fourqubit(theta1, phi1 + eps, theta2, phi2);\n\t\t\tv2 = product_fourqubit(theta1, phi1 - eps, theta2, phi2);\n\t\t\tegrad_num.coeffRef(1) = real(cx_double(v1.adjoint() * ham * v1)\n\t\t\t                             - cx_double(v2.adjoint() * ham * v2))\n\t\t\t                        / (2 * eps);\n\n\t\t\tv1 = product_fourqubit(theta1, phi1, theta2 + eps, phi2);\n\t\t\tv2 = product_fourqubit(theta1, phi1, theta2 - eps, phi2);\n\t\t\tegrad_num.coeffRef(2) = real(cx_double(v1.adjoint() * ham * v1)\n\t\t\t                             - cx_double(v2.adjoint() * ham * v2))\n\t\t\t                        / (2 * eps);\n\n\t\t\tv1 = product_fourqubit(theta1, phi1, theta2, phi2 + eps);\n\t\t\tv2 = product_fourqubit(theta1, phi1, theta2, phi2 - eps);\n\t\t\tegrad_num.coeffRef(3) = real(cx_double(v1.adjoint() * ham * v1)\n\t\t\t                             - cx_double(v2.adjoint() * ham * v2))\n\t\t\t                        / (2 * eps);\n\n\t\t\tREQUIRE((egrad_circ - egrad_num).norm() < 1e-6);\n\n\t\t\tfor(uint32_t k = 0; k < variables.size(); ++k)\n\t\t\t{\n\t\t\t\tvariables[k] -= 0.02 * egrad_circ(k);\n\t\t\t}\n\n\t\t\tstd::cout << real(cx_double(output.adjoint() * ham * output)) << std::endl;\n\t\t}\n\t}\n}\n\nTEST_CASE(\"test tfi\", \"[tfi]\")\n{\n\tusing namespace yavque;\n\tusing namespace Eigen;\n\n\tconstexpr unsigned int N = 10;\n\tconstexpr cx_double I(0., 1.);\n\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\tstd::normal_distribution<> nd;\n\n\tauto circ1 = construct_diagonal_tfi(N);\n\tauto variables1 = circ1.variables();\n\n\tauto [circ2, variables2] = construct_bare_tfi(N);\n\n\tEigen::VectorXcd ini = Eigen::VectorXcd::Ones(1 << N);\n\tini /= sqrt(1 << N);\n\tcirc1.set_input(ini);\n\tcirc2.set_input(ini);\n\n\tfor(uint32_t k = 0; k < 9; ++k)\n\t{\n\t\tdouble v = nd(re);\n\t\tvariables1[k] = v;\n\t\tvariables2[k] = v;\n\t}\n\n\tfor(uint32_t _instance = 0; _instance < 100; ++_instance)\n\t{ // instance loop\n\t\tcirc1.clear_evaluated();\n\t\tcirc2.clear_evaluated();\n\n\t\tfor(uint32_t k = 0; k < 9; ++k)\n\t\t{\n\t\t\tvariables1[k].zero_grad();\n\t\t\tvariables2[k].zero_grad();\n\t\t}\n\n\t\tEigen::VectorXcd output1 = *circ1.output();\n\t\tEigen::VectorXcd output2 = *circ2.output();\n\n\t\tREQUIRE((output1 - output2).norm() < 1e-6);\n\n\t\tcirc1.derivs();\n\t\tcirc2.derivs();\n\n\t\tfor(uint32_t k = 0; k < 9; ++k)\n\t\t{\n\t\t\tEigen::VectorXcd grad1 = *variables1[k].grad();\n\t\t\tEigen::VectorXcd grad2 = *variables1[k].grad();\n\t\t\tREQUIRE((grad1 - grad2).norm() < 1e-6);\n\t\t}\n\n\t\tfor(uint32_t k = 0; k < 9; ++k)\n\t\t{\n\t\t\tvariables1[k] -= 0.01;\n\t\t\tvariables2[k] -= 0.01;\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "492458ff2a1be374b013289e310dcba0461e1dae", "size": 10761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/TestTFI.cpp", "max_stars_repo_name": "chaeyeunpark/Yavque", "max_stars_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests/TestTFI.cpp", "max_issues_repo_name": "chaeyeunpark/Yavque", "max_issues_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tests/TestTFI.cpp", "max_forks_repo_name": "chaeyeunpark/Yavque", "max_forks_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8057553957, "max_line_length": 90, "alphanum_fraction": 0.6011523093, "num_tokens": 3884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545425, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5788693802634804}}
{"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": "#include <vector>\n#include <list>\n#include <map>\n#include <set>\n\n#include <queue>\n#include <deque>\n#include <stack>\n#include <bitset>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <utility>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <cstring>\n#include <assert.h>\n#include <boost/lexical_cast.hpp>\n\n#define INF 1023123123\n#define EPS 1e-11\n#define LSOne(S) (S & (-S))\n\n#define M_PI           3.14159265358979323846  /* pi */\n\n#define FORN(X,Y) for (int (X) = 0;(X) < (Y);++(X))\n#define FORB(X,Y) for (int (X) = (Y);(X) >= 0;--(X))\n#define REP(X,Y,Z) for (int (X) = (Y);(X) < (Z);++(X))\n#define REPB(X,Y,Z) for (int (X) = (Y);(X) >= (Z);--(X))\n\n#define SZ(Z) ((int)(Z).size())\n#define ALL(W) (W).begin(), (W).end()\n#define PB push_back\n\n#define MP make_pair\n#define A first\n#define B second\n\n#define FORIT(X,Y) for(typeof((Y).begin()) X = (Y).begin();X!=(Y).end();X++)\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef double db;\ntypedef vector<int> vi;\ntypedef pair<int, int> ii;\ntypedef vector<ii> vii;\n\nvoid print_case(int i)\n{\n   cout << \"Case #\" << i + 1 << \": \";\n}\n\nbool almost_equal(double a, double b)\n{\n   return abs(a - b) < EPS;\n}\n\ndouble calc_failure(vector<double> vc)\n{\n   double prob = 1.0;\n   FORN(i, vc.size())\n   {\n      prob *= vc[i];\n   }\n   return prob;\n}\n\nvi failureTable(51);\n\nint targetNumSuccesses = 0;\nvector<double> successChances(50);\nint numEvents = 50;\nint totalNumEvents = 50;\n\nvoid resetFailureTable()\n{\n   FORN(i, failureTable.size())\n      failureTable[i] = 0;\n}\n\nvoid reverseSubList(vi& list, int front, int back)\n{\n   if (front > back)\n      swap(front, back);\n   reverse(list.begin() + front, list.begin() + back + 1);\n}\n\nvoid calcu()\n{\n   double numEventProbability = 0;\n   double totalProbability = 0;\n   bool exhausted = false;\n\n   for (numEvents = 1; numEvents <= (totalNumEvents - targetNumSuccesses); numEvents++)\n   {\n      resetFailureTable();\n      FORN(i, numEvents)\n         failureTable[i] = 1;\n\n      while (!exhausted)\n      {\n         double eventChainProbability = 1;\n         REP(subEvent, 1, numEvents + 1)\n         {\n            if (failureTable[subEvent - 1])\n               eventChainProbability = eventChainProbability*(1 - successChances[subEvent - 1]);\n            else\n               eventChainProbability = eventChainProbability*(successChances[subEvent - 1]);\n         }\n         numEventProbability = numEventProbability + eventChainProbability;\n\n         for (int i = totalNumEvents - 1; i >= 0; i--)\n         {\n            if (failureTable[i] && !failureTable[i + 1])\n            {\n               int rightmost;\n               for (int j = totalNumEvents - 1; j >= 0; j--) {\n                  if (!failureTable[j]) {\n                     rightmost = j; break;\n                  }\n               }\n\n               failureTable[i] = false;\n               failureTable[rightmost] = true;\n               reverseSubList(failureTable, i + 1, totalNumEvents - 1);\n               break;\n            }\n            else if (i == 1)\n               exhausted = true;\n         }\n      }\n\n      exhausted = false;\n      printf(\"Odds of being exactly %d failures: %.2f\", numEvents, numEventProbability);\n      totalProbability = totalProbability + numEventProbability;\n      numEventProbability = 0;\n   }\n\n   printf(\"Odds of at least %d successes: %f\", targetNumSuccesses, 1 - totalProbability);\n}\n\nint main()\n{\n   /*numEvents = 2;\n   totalNumEvents = 2;\n   targetNumSuccesses = 1;\n   successChances[0] = 0.4000;\n   successChances[1] = 0.6000;\n   calcu();*/\n\n   cout.precision(12);\n   int ntc;\n   cin >> ntc;\n\n   FORN(kk, ntc)\n   {\n      print_case(kk);\n      int n, k;\n      cin >> n >> k;\n      double units;\n      cin >> units;\n      vector<double> cores(n + 1);\n      cores[n] = 1.0;\n      FORN(i, n)\n      {\n         cin >> cores[i];\n      }\n\n      sort(cores.begin(), cores.end());\n\n      FORN(i, n)\n      {\n         int nrcoresequal = 1;\n         REP(j, 1, n)\n         {\n            if (!almost_equal(cores[i], cores[j]))\n            {\n               break;\n            }\n            nrcoresequal++;\n         }\n         double nextcore = cores[nrcoresequal];\n         double diff = nextcore - cores[0];\n         double tospend = min(units, nrcoresequal * diff);\n         FORN(j, nrcoresequal)\n         {\n            cores[j] += tospend / nrcoresequal;\n         }\n         units -= tospend;\n      }\n\n      cout << calc_failure(cores) << endl;\n   }\n}\n", "meta": {"hexsha": "9a6c4d60c66f8fbeb4bf4af35adc067d31afa2ab", "size": 4548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "UvA/CJ2017_1C_C.cpp", "max_stars_repo_name": "fvannee/competitive-coding", "max_stars_repo_head_hexsha": "92bc383c482b55f3e48a583cddc50d92474eb488", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "UvA/CJ2017_1C_C.cpp", "max_issues_repo_name": "fvannee/competitive-coding", "max_issues_repo_head_hexsha": "92bc383c482b55f3e48a583cddc50d92474eb488", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UvA/CJ2017_1C_C.cpp", "max_forks_repo_name": "fvannee/competitive-coding", "max_forks_repo_head_hexsha": "92bc383c482b55f3e48a583cddc50d92474eb488", "max_forks_repo_licenses": ["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.5148514851, "max_line_length": 96, "alphanum_fraction": 0.5534300792, "num_tokens": 1268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5788005409381328}}
{"text": "/* Copyright \u00a9 2017 Apple Inc. All rights reserved.\n *\n * Use of this source code is governed by a BSD-3-clause license that can\n * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n */\n#ifndef TURI_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": "//==============================================================================\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_ELLIPTIC_FUNCTIONS_SCALAR_ELLINT_1_HPP_INCLUDED\n#define NT2_TOOLBOX_ELLIPTIC_FUNCTIONS_SCALAR_ELLINT_1_HPP_INCLUDED\n#include <nt2/toolbox/elliptic/functions/ellint_1.hpp>\n#include <boost/math/special_functions.hpp>\n#include <nt2/include/constants/digits.hpp>\n#include <nt2/include/constants/infinites.hpp>\n#include <nt2/include/constants/real.hpp>\n#include <nt2/toolbox/trigonometric/constants.hpp>\n#include <nt2/include/functions/scalar/is_eqz.hpp>\n#include <nt2/sdk/error/policies.hpp>\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type  is fundamental_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::ellint_1_, tag::cpu_\n                            , (A0)\n                            , (scalar_< fundamental_<A0> >)\n                            )\n  {\n\n    typedef typename boost::dispatch::meta::as_floating<A0>::type result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      result_type x = a0;\n      if (x > One<result_type>()) return Nan<result_type>();\n      if (x == One<result_type>())  return Inf<result_type>();\n      if (is_eqz(x))      return Pio_2<result_type>();\n      return boost::math::ellint_1(x, nt2_policy());\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "e39ff4ea2329ea13f63f7f4253dafe56e806c4c6", "size": 1829, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/elliptic/include/nt2/toolbox/elliptic/functions/scalar/ellint_1.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/elliptic/include/nt2/toolbox/elliptic/functions/scalar/ellint_1.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/elliptic/include/nt2/toolbox/elliptic/functions/scalar/ellint_1.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7608695652, "max_line_length": 80, "alphanum_fraction": 0.5478403499, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5788005192667144}}
{"text": "#include \"helper/bearing_vector.h\"\n\n#include \"openvslam/type.h\"\n#include \"openvslam/solver/essential_solver.h\"\n#include \"openvslam/util/random_array.h\"\n\n#include <Eigen/Geometry>\n\n#include <gtest/gtest.h>\n\nusing namespace openvslam;\n\nTEST(essential_solver, check_E_solution_1) {\n    // 3\u6b21\u5143\u70b9\u3092\u4f5c\u6210\n    const unsigned int num_landmarks = 1000;\n    const auto landmarks = create_random_landmarks(num_landmarks);\n\n    // \u59ff\u52e2\u3092\u4f5c\u6210\n    const Mat33_t rot_1 = Eigen::AngleAxisd(54.0 * M_PI / 180, Vec3_t(5, 3, -2).normalized()).toRotationMatrix();\n    const Vec3_t trans_1 = Vec3_t(10.3, -1.6, 8.4);\n    const Mat33_t rot_2 = Eigen::AngleAxisd(-21.0 * M_PI / 180, Vec3_t(-2, -5, 6).normalized()).toRotationMatrix();\n    const Vec3_t trans_2 = Vec3_t(-5.4, 11.5, -24.6);\n\n    // bearing vectors\u3092\u4f5c\u6210\n    Mat33_t true_E_21;\n    eigen_alloc_vector<Vec3_t> bearings_1;\n    eigen_alloc_vector<Vec3_t> bearings_2;\n    create_bearing_vectors(rot_1, trans_1, rot_2, trans_2, landmarks, true_E_21, bearings_1, bearings_2);\n\n    // matches\u3092\u4f5c\u6210\n    std::vector<std::pair<int, int>> matches_12(num_landmarks);\n    for (unsigned int i = 0; i < num_landmarks; ++i) {\n        matches_12.at(i).first = i;\n        matches_12.at(i).second = i;\n    }\n\n    // E\u884c\u5217\u3092\u6c42\u3081\u308b\n    solver::essential_solver solver(bearings_1, bearings_2, matches_12);\n    solver.find_via_ransac(100);\n    Mat33_t E_21 = solver.get_best_E_21();\n\n    // \u30b9\u30b1\u30fc\u30eb\u3068\u6b63\u8ca0\u3092\u5408\u308f\u305b\u308b\n    true_E_21 /= true_E_21.norm();\n    E_21 /= E_21.norm();\n    if (true_E_21.mean() * E_21.mean() < 0) {\n        true_E_21 *= -1.0;\n    }\n\n    EXPECT_LT((true_E_21 - E_21).norm(), 1e-4);\n}\n\nTEST(essential_solver, check_E_solution_2) {\n    // 3\u6b21\u5143\u70b9\u3092\u4f5c\u6210\n    const unsigned int num_landmarks = 1000;\n    const auto landmarks = create_random_landmarks(num_landmarks);\n\n    // \u59ff\u52e2\u3092\u4f5c\u6210\n    const Mat33_t rot_1 = Eigen::AngleAxisd(54.0 * M_PI / 180, Vec3_t(5, 3, -2).normalized()).toRotationMatrix();\n    const Vec3_t trans_1 = Vec3_t(10.3, -1.6, 8.4);\n    const Mat33_t rot_2 = Eigen::AngleAxisd(-21.0 * M_PI / 180, Vec3_t(-2, -5, 6).normalized()).toRotationMatrix();\n    const Vec3_t trans_2 = Vec3_t(-5.4, 11.5, -24.6);\n\n    // bearing vectors\u3092\u4f5c\u6210\n    Mat33_t true_E_21;\n    eigen_alloc_vector<Vec3_t> bearings_1;\n    eigen_alloc_vector<Vec3_t> bearings_2;\n    create_bearing_vectors(rot_1, trans_1, rot_2, trans_2, landmarks, true_E_21, bearings_1, bearings_2, 0.01);\n\n    // matches\u3092\u4f5c\u6210\n    std::vector<std::pair<int, int>> matches_12(num_landmarks);\n    for (unsigned int i = 0; i < num_landmarks; ++i) {\n        matches_12.at(i).first = i;\n        matches_12.at(i).second = i;\n    }\n\n    // E\u884c\u5217\u3092\u6c42\u3081\u308b\n    solver::essential_solver solver(bearings_1, bearings_2, matches_12);\n    solver.find_via_ransac(100);\n    Mat33_t E_21 = solver.get_best_E_21();\n\n    // \u30b9\u30b1\u30fc\u30eb\u3068\u6b63\u8ca0\u3092\u5408\u308f\u305b\u308b\n    true_E_21 /= true_E_21.norm();\n    E_21 /= E_21.norm();\n    if (true_E_21.mean() * E_21.mean() < 0) {\n        true_E_21 *= -1.0;\n    }\n\n    EXPECT_LT((true_E_21 - E_21).norm(), 1e-1);\n}\n", "meta": {"hexsha": "1ce0ccb3f9283b46ef97fc7fb323877ac5307cd5", "size": 2955, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/openvslam/solver/essential_solver.cc", "max_stars_repo_name": "bumplzz69/openvslam", "max_stars_repo_head_hexsha": "6d03050a0f04323adfdf3fcf3693b180abc4553f", "max_stars_repo_licenses": ["BSD-2-Clause", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-10T02:16:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T02:16:52.000Z", "max_issues_repo_path": "test/openvslam/solver/essential_solver.cc", "max_issues_repo_name": "NamDinhRobotics/openvslam", "max_issues_repo_head_hexsha": "6d03050a0f04323adfdf3fcf3693b180abc4553f", "max_issues_repo_licenses": ["BSD-2-Clause", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/openvslam/solver/essential_solver.cc", "max_forks_repo_name": "NamDinhRobotics/openvslam", "max_forks_repo_head_hexsha": "6d03050a0f04323adfdf3fcf3693b180abc4553f", "max_forks_repo_licenses": ["BSD-2-Clause", "MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-03T23:26:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-03T23:26:34.000Z", "avg_line_length": 32.8333333333, "max_line_length": 115, "alphanum_fraction": 0.6670050761, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.682573734412324, "lm_q1q2_score": 0.578800514252209}}
{"text": "#include <iostream>\n#include <ostream>\n#include <fstream>\n#include <igl/readOFF.h>\n#include <Eigen/Core>\n#include <vector>\n#include <array>\n#include \"../external/dkm/include/dkm.hpp\"\nusing namespace std;\nusing namespace Eigen;\n\nMatrixXd V;\nMatrixXi F;\n\n#define N_VIEWS 102\n\nvoid eigen2std(const MatrixXd &mat, vector<array<double, 3>> &vec)\n{\n    for (size_t i = 0; i < mat.rows(); i++)\n    {\n        array<double, 3> line;\n        for (size_t j = 0; j < mat.cols(); j++)\n        {\n            line[j] = mat(i, j);\n        }\n        vec.push_back(line);\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    igl::readOFF(\"../sphere.off\", V, F);\n    \n    int nPoints = V.rows(), dim = V.cols();\n    vector<array<double,3> > points;\n    eigen2std(V, points);\n    auto res = dkm::kmeans_lloyd(points, N_VIEWS);\n    auto centroids = get<0>(res);\n\n    ofstream cameraFile;\n    cameraFile.open(\"../camera_position.xy\");\n    for (size_t i = 0; i < N_VIEWS; i++)\n    {\n        for (size_t j = 0; j < dim; j++)\n        {\n            cameraFile << centroids[i][j] << \" \";\n        }\n        cameraFile << endl;\n    }\n    cameraFile.close();\n    return 0;\n}", "meta": {"hexsha": "152071537e5124f0c2090128922de5b8e1bb5d58", "size": 1139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OccludingContours/createCameraFile.cpp", "max_stars_repo_name": "PierreTsr/Shape_Retrieval", "max_stars_repo_head_hexsha": "1a0246913c3653d43ef75c6168ea1d49cb23b295", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-30T09:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-30T09:13:54.000Z", "max_issues_repo_path": "OccludingContours/createCameraFile.cpp", "max_issues_repo_name": "PierreTsr/Shape_Retrieval", "max_issues_repo_head_hexsha": "1a0246913c3653d43ef75c6168ea1d49cb23b295", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OccludingContours/createCameraFile.cpp", "max_forks_repo_name": "PierreTsr/Shape_Retrieval", "max_forks_repo_head_hexsha": "1a0246913c3653d43ef75c6168ea1d49cb23b295", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-19T04:02:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T04:02:17.000Z", "avg_line_length": 21.9038461538, "max_line_length": 66, "alphanum_fraction": 0.5601404741, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5788005087767333}}
{"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": "#include <vector>\n#include <tuple>\n#include <cmath>\n#include <numeric>\n#include <Eigen/Dense>\n#include \"../happly.h\"\n#include \"../nanoflann.hpp\"\n#include \"utils.hpp\"\n\n\n\nfloat icp::mse_cost(std::vector<std::tuple<float, int, int>>& distances, float xi)\n{\n    size_t Np = distances.size();\n    size_t Npo = xi*Np;\n    \n    float Sts = std::accumulate(distances.begin(), distances.begin() + Npo, 0, tupleAccumulateOP);\n    xi = (float)std::pow(xi, 3);\n    float e = Sts/Npo;\n    \n    return e/xi;\n} \n\nbool icp::comparePairs(const std::tuple<float, int, int>& lhs, const std::tuple<float, int, int>& rhs)\n{\n    return std::get<0>(lhs) < std::get<0>(rhs);\n}\n\nfloat icp::tupleAccumulateOP(const float &a, const std::tuple<float, int, int> &b)\n{\n    return a+std::get<0>(b);\n}\n\nicp::PointCloud icp::readPointCloud(const std::string filename)\n{\n    //\"../data/fountain_a.ply\"\n    happly::PLYData plyData(filename);\n    // auto propsNames = plyData.getElement(\"vertex\").getPropertyNames();\n    std::vector<std::array<double, 3>> vPos = plyData.getVertexPositions();\n    size_t dim = 3;\n    size_t N = vPos.size();\n    icp::PointCloud mat(N, dim);\n  \n    mat.resize(N, dim);\n    for (size_t i = 0; i < N; i++)\n        for (size_t d = 0; d < dim; d++)\n            mat(i, d) = vPos[i][d];\n    // for(const auto& prop: propsNames)\n    //     std::cout<<prop<<std::endl;\n    return mat;\n}\n\nicp::PointCloud icp::addNoise(icp::PointCloud M)\n{\n    // get dimentions\n    size_t rows = M.rows();\n    size_t cols = M.cols();\n    \n    return icp::PointCloud::Random(rows, cols);\n}\n\n\n// rotation\nEigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> icp::rotate(icp::PointCloud& M, float deg, Eigen::Vector3f axis)\n{\n    // float deg = 10.f;\n    float rad = deg * M_PI / 180;\n    // Eigen::Vector3f axis(0,1,1);\n    Eigen::Transform<float, 3, Eigen::Affine> t;\n    Eigen::AngleAxis<float> rot(rad, axis);\n    t = rot;\n\n    // std::cout<<t.linear()<<std::endl;\n    // std::cout<<t.linear().inverse()<<std::endl;\n    // std::cout<<t.linear().inverse().matrix()<<std::endl;\n    M = (t.linear() * M.transpose()).transpose();\n    return t.linear().matrix();\n}", "meta": {"hexsha": "1d7e864e133c0e01805f410caad1669adec00b6b", "size": 2131, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils.cpp", "max_stars_repo_name": "SohilZidan/point-cloud-registration", "max_stars_repo_head_hexsha": "5e7f52fbf04f3a58238a2c92393143d5e110c8e4", "max_stars_repo_licenses": ["MIT"], "max_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": "SohilZidan/point-cloud-registration", "max_issues_repo_head_hexsha": "5e7f52fbf04f3a58238a2c92393143d5e110c8e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-27T17:52:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T07:04:05.000Z", "max_forks_repo_path": "src/utils.cpp", "max_forks_repo_name": "SohilZidan/point-cloud-registration", "max_forks_repo_head_hexsha": "5e7f52fbf04f3a58238a2c92393143d5e110c8e4", "max_forks_repo_licenses": ["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.3205128205, "max_line_length": 117, "alphanum_fraction": 0.6100422337, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5787313060461886}}
{"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 <pybind11/pybind11.h>\n\n#include <boost/geometry/geometries/register/point.hpp>\n\n#include \"pyinterp/detail/geometry/point.hpp\"\n#include \"pyinterp/geodetic/algorithm.hpp\"\n#include \"pyinterp/geodetic/system.hpp\"\n\nnamespace pyinterp::geodetic {\n\n// Handle a point in a equatorial spherical coordinates system in degrees.\nclass Point : public detail::geometry::GeographicPoint2D<double> {\n public:\n  /// Default constructor\n  Point() noexcept = default;\n\n  /// Build a new point with the coordinates provided.\n  Point(const double lon, const double lat)\n      : detail::geometry::GeographicPoint2D<double>(lon, lat) {}\n\n  /// Get longitude value in degrees\n  [[nodiscard]] inline auto lon() const -> double { return this->get<0>(); }\n\n  /// Get latitude value in degrees\n  [[nodiscard]] inline auto lat() const -> double { return this->get<1>(); }\n\n  /// Set longitude value in degrees\n  inline auto lon(double const v) -> void { this->set<0>(v); }\n\n  /// Set latitude value in degrees\n  inline auto lat(double const v) -> void { this->set<1>(v); }\n\n  /// Calculate the distance between the two points\n  [[nodiscard]] auto distance(const Point& other,\n                              const DistanceStrategy strategy,\n                              const std::optional<System>& wgs) const\n      -> double {\n    return geodetic::distance(*this, other, strategy, wgs);\n  }\n\n  /// Get a tuple that fully encodes the state of this instance\n  [[nodiscard]] auto getstate() const -> pybind11::tuple {\n    return pybind11::make_tuple(lon(), lat());\n  }\n\n  /// Create a new instance from a registered state of an instance of this\n  /// object.\n  static auto setstate(const pybind11::tuple& state) -> Point {\n    if (state.size() != 2) {\n      throw std::runtime_error(\"invalid state\");\n    }\n    return {state[0].cast<double>(), state[1].cast<double>()};\n  }\n\n  /// Converts a Point into a string with the same meaning as that of this\n  /// instance.\n  [[nodiscard]] auto to_string() const -> std::string {\n    std::stringstream ss;\n    ss << boost::geometry::dsv(*this);\n    return ss.str();\n  }\n\n  /// Returns true if the tow points are equal.\n  auto operator==(const Point& other) const -> bool {\n    return boost::geometry::equals(*this, other);\n  }\n};\n\n}  // namespace pyinterp::geodetic\n\n// BOOST specialization to accept pyinterp::geodectic::Point as a geometry\n// entity\nnamespace boost::geometry::traits {\n\nnamespace pg = pyinterp::geodetic;\n\n/// Coordinate tag\ntemplate <>\nstruct tag<pg::Point> {\n  /// Typedef for type\n  using type = point_tag;\n};\n\n/// Coordinate type\ntemplate <>\nstruct coordinate_type<pg::Point> {\n  /// Typedef for type\n  using type = double;\n};\n\n/// Coordinate system\ntemplate <>\nstruct coordinate_system<pg::Point> {\n  /// Typedef for type\n  using type = cs::geographic<degree>;\n};\n\ntemplate <>\nstruct dimension<pg::Point> : boost::mpl::int_<2> {};\n\n/// access struct defining with Cartesian\ntemplate <std::size_t I>\nstruct access<pg::Point, I> {\n  /// Accessor to pointer.\n  static auto get(pg::Point const& p) -> double { return p.template get<I>(); }\n\n  /// Pointer setter.\n  static void set(pg::Point& p, double const& v) {  // NOLINT\n    p.template set<I>(v);\n  }\n};\n\n}  // namespace boost::geometry::traits\n", "meta": {"hexsha": "311a688ebd731bb9c536761bbb9bb03e54c63e5d", "size": 3406, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/geodetic/point.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/geodetic/point.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/geodetic/point.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": 28.6218487395, "max_line_length": 79, "alphanum_fraction": 0.6670581327, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5786909796903603}}
{"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": "#include <cstdio>\n\n#include <cctbx/sgtbx/direct_space_asu/proto/direct_space_asu.h>\n#include <boost/shared_ptr.hpp> // necessary for pair_tables.h\n#include <cctbx/crystal/pair_tables.h>\n\n// @@@@@@@@\n// This file is a translation of find_distances_using_cpp_objects.py into C++\n// @@@@@@@@\n\nnamespace cc {\n  using namespace cctbx::sgtbx;\n  using namespace cctbx::uctbx;\n  using namespace cctbx::sgtbx::asu;\n  using namespace cctbx::crystal::direct_space_asu;\n  using cctbx::crystal::pair_asu_table;\n  using cctbx::crystal::pair_sym_table;\n  using cctbx::crystal::pair_sym_dict;\n  using cctbx::crystal::pair_sym_ops;\n  typedef scitbx::vec3<double> double3;\n};\n\nvoid find_distances(\n  const cc::unit_cell &unit_cell,\n  const cc::space_group &space_group,\n  const scitbx::af::const_ref< cc::double3 > &sites_frac,\n  double distance_cutoff)\n{\n  cc::direct_space_asu metric_free_asu( space_group.type() );\n  cc::float_asu<> float_asu = metric_free_asu.as_float_asu(unit_cell, 1.0E-6);\n  boost::shared_ptr< cc::asu_mappings<> > asu_mappings(\n    new cc::asu_mappings<> (space_group, float_asu, distance_cutoff) );\n  asu_mappings->process_sites_frac(sites_frac, 0.5);\n  cc::pair_asu_table<> pair_asu_table(asu_mappings);\n  pair_asu_table.add_all_pairs(distance_cutoff);\n  cc::pair_sym_table pair_sym_table = pair_asu_table.extract_pair_sym_table();\n  for(unsigned i=0; i<pair_sym_table.size(); ++i) // af::shared  array\n  {\n    std::printf(\"i: %d\\n\", i);\n    const cctbx::fractional<> frac_i = sites_frac[i];\n    const cc::pair_sym_dict pair_sym_dict = pair_sym_table[i];\n    for(cc::pair_sym_dict::const_iterator pair=pair_sym_dict.begin();\n      pair!=pair_sym_dict.end(); ++pair ) // std::map\n    {\n      const int j = pair->first;\n      std::printf(\"  j: %d\\n\", j);\n      const cctbx::fractional<> frac_j = sites_frac[j];\n      const cc::pair_sym_ops sym_ops = pair->second;\n      for(cc::pair_sym_ops::const_iterator sym_op = sym_ops.begin();\n        sym_op!=sym_ops.end(); ++sym_op) // std::vector\n      {\n        const cctbx::fractional<> frac_ji = (*sym_op) * frac_j;\n          std::printf(\"    %-20s %8.3f\\n\", sym_op->as_xyz().c_str(),\n            unit_cell.distance(frac_i, frac_ji));\n      }\n    }\n  }\n}\n\nint main(int argc, char *[])\n{\n  CCTBX_ASSERT( argc==1 );\n  scitbx::af::double6 cell(5.01, 5.01, 5.47, 90.0, 90.0, 120.0);\n  cc::unit_cell unit_cell(cell);\n  cc::space_group space_group(cctbx::sgtbx::space_group_symbols(\"P6222\"));\n  scitbx::af::shared< cc::double3 > sites_frac;\n  sites_frac.push_back( cc::double3(0.5, 0.5, 1.0/3.0) );\n  sites_frac.push_back( cc::double3(0.197, -0.197, 0.83333) );\n  find_distances(unit_cell, space_group, sites_frac.const_ref(), 5.0);\n  return 0;\n}\n", "meta": {"hexsha": "e412695377fee1d5d8ca3ef83a2b4d7c8c362e62", "size": 2693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/examples/find_distances.cpp", "max_stars_repo_name": "dperl-sol/cctbx_project", "max_stars_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "cctbx/examples/find_distances.cpp", "max_issues_repo_name": "dperl-sol/cctbx_project", "max_issues_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "cctbx/examples/find_distances.cpp", "max_forks_repo_name": "dperl-sol/cctbx_project", "max_forks_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 37.4027777778, "max_line_length": 78, "alphanum_fraction": 0.6903082065, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927838, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5786842339618637}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <geometry_test_common.hpp>\n\n#if defined(_MSC_VER)\n#  pragma warning( disable : 4101 )\n#endif\n\n#include <boost/timer.hpp>\n\n#include <boost/concept/requires.hpp>\n#include <boost/concept_check.hpp>\n#include <boost/core/ignore_unused.hpp>\n\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>\n#include <boost/geometry/strategies/concepts/distance_concept.hpp>\n\n\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n\n#include <test_common/test_point.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\n\ntemplate <typename P1, typename P2>\nvoid test_null_distance_3d()\n{\n    P1 p1;\n    bg::assign_values(p1, 1, 2, 3);\n    P2 p2;\n    bg::assign_values(p2, 1, 2, 3);\n\n    typedef bg::strategy::distance::pythagoras<> pythagoras_type;\n    typedef typename bg::strategy::distance::services::return_type<pythagoras_type, P1, P2>::type return_type;\n\n    pythagoras_type pythagoras;\n    return_type result = pythagoras.apply(p1, p2);\n\n    BOOST_CHECK_EQUAL(result, return_type(0));\n}\n\ntemplate <typename P1, typename P2>\nvoid test_axis_3d()\n{\n    P1 p1;\n    bg::assign_values(p1, 0, 0, 0);\n    P2 p2;\n    bg::assign_values(p2, 1, 0, 0);\n\n    typedef bg::strategy::distance::pythagoras<> pythagoras_type;\n    typedef typename bg::strategy::distance::services::return_type<pythagoras_type, P1, P2>::type return_type;\n\n    pythagoras_type pythagoras;\n\n    return_type result = pythagoras.apply(p1, p2);\n    BOOST_CHECK_EQUAL(result, return_type(1));\n\n    bg::assign_values(p2, 0, 1, 0);\n    result = pythagoras.apply(p1, p2);\n    BOOST_CHECK_EQUAL(result, return_type(1));\n\n    bg::assign_values(p2, 0, 0, 1);\n    result = pythagoras.apply(p1, p2);\n    BOOST_CHECK_CLOSE(result, return_type(1), 0.001);\n}\n\ntemplate <typename P1, typename P2>\nvoid test_arbitrary_3d()\n{\n    P1 p1;\n    bg::assign_values(p1, 1, 2, 3);\n    P2 p2;\n    bg::assign_values(p2, 9, 8, 7);\n\n    {\n        typedef bg::strategy::distance::pythagoras<> strategy_type;\n        typedef typename bg::strategy::distance::services::return_type<strategy_type, P1, P2>::type return_type;\n\n        strategy_type strategy;\n        return_type result = strategy.apply(p1, p2);\n        BOOST_CHECK_CLOSE(result, return_type(10.77032961427), 0.001);\n    }\n\n    {\n        // Check comparable distance\n        typedef bg::strategy::distance::comparable::pythagoras<> strategy_type;\n        typedef typename bg::strategy::distance::services::return_type<strategy_type, P1, P2>::type return_type;\n\n        strategy_type strategy;\n        return_type result = strategy.apply(p1, p2);\n        BOOST_CHECK_EQUAL(result, return_type(116));\n    }\n}\n\ntemplate <typename P1, typename P2, typename CalculationType>\nvoid test_services()\n{\n    namespace bgsd = bg::strategy::distance;\n    namespace services = bg::strategy::distance::services;\n\n    {\n\n        // Compile-check if there is a strategy for this type\n        typedef typename services::default_strategy\n            <\n                bg::point_tag, bg::point_tag, P1, P2\n            >::type pythagoras_strategy_type;\n\n        boost::ignore_unused<pythagoras_strategy_type>();\n    }\n\n\n    P1 p1;\n    bg::assign_values(p1, 1, 2, 3);\n\n    P2 p2;\n    bg::assign_values(p2, 4, 5, 6);\n\n    double const sqr_expected = 3*3 + 3*3 + 3*3; // 27\n    double const expected = sqrt(sqr_expected); // sqrt(27)=5.1961524227\n\n    // 1: normal, calculate distance:\n\n    typedef bgsd::pythagoras<CalculationType> strategy_type;\n\n    BOOST_CONCEPT_ASSERT( (bg::concepts::PointDistanceStrategy<strategy_type, P1, P2>) );\n\n    typedef typename bgsd::services::return_type<strategy_type, P1, P2>::type return_type;\n\n    strategy_type strategy;\n    return_type result = strategy.apply(p1, p2);\n    BOOST_CHECK_CLOSE(result, return_type(expected), 0.001);\n\n    // 2: the strategy should return the same result if we reverse parameters\n    result = strategy.apply(p2, p1);\n    BOOST_CHECK_CLOSE(result, return_type(expected), 0.001);\n\n\n    // 3: \"comparable\" to construct a \"comparable strategy\" for P1/P2\n    //    a \"comparable strategy\" is a strategy which does not calculate the exact distance, but\n    //    which returns results which can be mutually compared (e.g. avoid sqrt)\n\n    // 3a: \"comparable_type\"\n    typedef typename services::comparable_type<strategy_type>::type comparable_type;\n\n    // 3b: \"get_comparable\"\n    comparable_type comparable = bgsd::services::get_comparable<strategy_type>::apply(strategy);\n\n    return_type c_result = comparable.apply(p1, p2);\n    BOOST_CHECK_CLOSE(c_result, return_type(sqr_expected), 0.001);\n\n    // 4: the comparable_type should have a distance_strategy_constructor as well,\n    //    knowing how to compare something with a fixed distance\n    return_type c_dist5 = services::result_from_distance<comparable_type, P1, P2>::apply(comparable, 5.0);\n    return_type c_dist6 = services::result_from_distance<comparable_type, P1, P2>::apply(comparable, 6.0);\n\n    // If this is the case:\n    BOOST_CHECK(c_dist5 < c_result && c_result < c_dist6);\n\n    // This should also be the case\n    return_type dist5 = services::result_from_distance<strategy_type, P1, P2>::apply(strategy, 5.0);\n    return_type dist6 = services::result_from_distance<strategy_type, P1, P2>::apply(strategy, 6.0);\n    BOOST_CHECK(dist5 < result && result < dist6);\n}\n\n\ntemplate <typename CoordinateType, typename CalculationType, typename AssignType>\nvoid test_big_2d_with(AssignType const& x1, AssignType const& y1,\n                 AssignType const& x2, AssignType const& y2)\n{\n    typedef bg::model::point<CoordinateType, 2, bg::cs::cartesian> point_type;\n    typedef bg::strategy::distance::pythagoras<CalculationType> pythagoras_type;\n\n    pythagoras_type pythagoras;\n    typedef typename bg::strategy::distance::services::return_type<pythagoras_type, point_type, point_type>::type return_type;\n\n\n    point_type p1, p2;\n    bg::assign_values(p1, x1, y1);\n    bg::assign_values(p2, x2, y2);\n    return_type d = pythagoras.apply(p1, p2);\n\n    /***\n    std::cout << typeid(CalculationType).name()\n        << \" \" << std::fixed << std::setprecision(20) << d\n        << std::endl << std::endl;\n    ***/\n\n\n    BOOST_CHECK_CLOSE(d, return_type(1076554.5485833955678294387789057), 0.001);\n}\n\ntemplate <typename CoordinateType, typename CalculationType>\nvoid test_big_2d()\n{\n    test_big_2d_with<CoordinateType, CalculationType>\n        (123456.78900001, 234567.89100001,\n        987654.32100001, 876543.21900001);\n}\n\ntemplate <typename CoordinateType, typename CalculationType>\nvoid test_big_2d_string()\n{\n    test_big_2d_with<CoordinateType, CalculationType>\n        (\"123456.78900001\", \"234567.89100001\",\n        \"987654.32100001\", \"876543.21900001\");\n}\n\ntemplate <typename CoordinateType>\nvoid test_integer(bool check_types)\n{\n    typedef bg::model::point<CoordinateType, 2, bg::cs::cartesian> point_type;\n\n    point_type p1, p2;\n    bg::assign_values(p1, 12345678, 23456789);\n    bg::assign_values(p2, 98765432, 87654321);\n\n    typedef bg::strategy::distance::pythagoras<> pythagoras_type;\n    typedef typename bg::strategy::distance::services::comparable_type\n        <\n            pythagoras_type\n        >::type comparable_type;\n\n    typedef typename bg::strategy::distance::services::return_type\n        <\n            pythagoras_type, point_type, point_type\n        >::type distance_type;\n    typedef typename bg::strategy::distance::services::return_type\n        <\n            comparable_type, point_type, point_type\n        >::type cdistance_type;\n\n    pythagoras_type pythagoras;\n    distance_type distance = pythagoras.apply(p1, p2);\n    BOOST_CHECK_CLOSE(distance, 107655455.02347542, 0.001);\n\n    comparable_type comparable;\n    cdistance_type cdistance = comparable.apply(p1, p2);\n    BOOST_CHECK_EQUAL(cdistance, 11589696996311540.0);\n\n    distance_type distance2 = sqrt(distance_type(cdistance));\n    BOOST_CHECK_CLOSE(distance, distance2, 0.001);\n\n    if (check_types)\n    {\n        BOOST_CHECK((boost::is_same<distance_type, double>::type::value));\n        // comparable_distance results in now double too, obviously because\n        // comp.distance point-segment can be fraction, even for integer input\n        BOOST_CHECK((boost::is_same<cdistance_type, double>::type::value));\n    }\n}\n\n\ntemplate <typename P1, typename P2>\nvoid test_all_3d()\n{\n    test_null_distance_3d<P1, P2>();\n    test_axis_3d<P1, P2>();\n    test_arbitrary_3d<P1, P2>();\n}\n\ntemplate <typename P>\nvoid test_all_3d()\n{\n    test_all_3d<P, int[3]>();\n    test_all_3d<P, float[3]>();\n    test_all_3d<P, double[3]>();\n    test_all_3d<P, test::test_point>();\n    test_all_3d<P, bg::model::point<int, 3, bg::cs::cartesian> >();\n    test_all_3d<P, bg::model::point<float, 3, bg::cs::cartesian> >();\n    test_all_3d<P, bg::model::point<double, 3, bg::cs::cartesian> >();\n}\n\ntemplate <typename P, typename Strategy>\nvoid time_compare_s(int const n)\n{\n    boost::timer t;\n    P p1, p2;\n    bg::assign_values(p1, 1, 1);\n    bg::assign_values(p2, 2, 2);\n    Strategy strategy;\n    typename bg::strategy::distance::services::return_type<Strategy, P, P>::type s = 0;\n    for (int i = 0; i < n; i++)\n    {\n        for (int j = 0; j < n; j++)\n        {\n            bg::set<0>(p2, bg::get<0>(p2) + 0.001);\n            s += strategy.apply(p1, p2);\n        }\n    }\n    std::cout << \"s: \" << s << \" t: \" << t.elapsed() << std::endl;\n}\n\ntemplate <typename P>\nvoid time_compare(int const n)\n{\n    time_compare_s<P, bg::strategy::distance::pythagoras<> >(n);\n    time_compare_s<P, bg::strategy::distance::comparable::pythagoras<> >(n);\n}\n\nint test_main(int, char* [])\n{\n    test_integer<int>(true);\n    test_integer<boost::long_long_type>(true);\n    test_integer<double>(false);\n\n    test_all_3d<int[3]>();\n    test_all_3d<float[3]>();\n    test_all_3d<double[3]>();\n\n    test_all_3d<test::test_point>();\n\n    test_all_3d<bg::model::point<int, 3, bg::cs::cartesian> >();\n    test_all_3d<bg::model::point<float, 3, bg::cs::cartesian> >();\n    test_all_3d<bg::model::point<double, 3, bg::cs::cartesian> >();\n\n    test_big_2d<float, float>();\n    test_big_2d<double, double>();\n    test_big_2d<long double, long double>();\n    test_big_2d<float, long double>();\n\n    test_services<bg::model::point<float, 3, bg::cs::cartesian>, double[3], long double>();\n    test_services<double[3], test::test_point, float>();\n\n\n    // TODO move this to another non-unit test\n    // time_compare<bg::model::point<double, 2, bg::cs::cartesian> >(10000);\n\n    return 0;\n}\n", "meta": {"hexsha": "66fd7763468b2453b2d0054cc8f262230abf017a", "size": 11241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/strategies/pythagoras.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "test/strategies/pythagoras.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "test/strategies/pythagoras.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 32.2091690544, "max_line_length": 126, "alphanum_fraction": 0.6881950004, "num_tokens": 3184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5786684420493003}}
{"text": "/**\n * @file stableevaluationatapoint_test.cc\n * @brief NPDE homework StableEvaluationAtAPoint\n * @author Am\u00e9lie Loher\n * @date 29/04/2020\n * @copyright Developed at ETH Zurich\n */\n\n#include \"../stableevaluationatapoint.h\"\n\n#include <gtest/gtest.h>\n#include <lf/fe/fe.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <cmath>\n#include <memory>\n#include <utility>\n\nTEST(StableEvaluationAtAPoint, PSL) {\n  auto mesh_factory_init = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader_init(std::move(mesh_factory_init),\n                                 CURRENT_SOURCE_DIR \"/../../meshes/square.msh\");\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = reader_init.mesh();\n\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\n  const Eigen::Vector2d x(0.3, 0.4);\n\n  const double val = StableEvaluationAtAPoint::PSL(mesh_p, u, x);\n\n  const double ref_val = 0.15525;\n\n  double tol = 1.e-4;\n\n  ASSERT_NEAR(std::abs(ref_val - val), 0.0, tol);\n}\n\nTEST(StableEvaluationAtAPoint, PDL) {\n  auto mesh_factory_init = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader_init(std::move(mesh_factory_init),\n                                 CURRENT_SOURCE_DIR \"/../../meshes/square.msh\");\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = reader_init.mesh();\n\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\n  const Eigen::Vector2d x(0.3, 0.4);\n\n  const double val = StableEvaluationAtAPoint::PDL(mesh_p, u, x);\n\n  const double ref_val = -0.484226;\n\n  double tol = 1.e-4;\n\n  ASSERT_NEAR(std::abs(ref_val - val), 0.0, tol);\n}\n\nTEST(StableEvaluationAtAPoint, PointEval) {\n  auto mesh_factory_init = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader_init(std::move(mesh_factory_init),\n                                 CURRENT_SOURCE_DIR \"/../../meshes/square.msh\");\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = reader_init.mesh();\n\n  double error = StableEvaluationAtAPoint::PointEval(mesh_p);\n\n  double ref_error = 0.0784387;\n\n  double tol = 1.e-4;\n\n  ASSERT_NEAR(std::abs(ref_error - error), 0.0, tol);\n}\n\nTEST(StableEvaluationAtAPoint, Jstar) {\n  auto mesh_factory_init = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader_init(std::move(mesh_factory_init),\n                                 CURRENT_SOURCE_DIR\n                                 \"/../../meshes/square7.msh\");\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = reader_init.mesh();\n\n  std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\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\n  lf::mesh::utils::MeshFunctionGlobal mf_u{u};\n  Eigen::VectorXd uFE = lf::fe::NodalProjection(*fe_space, mf_u);\n\n  const Eigen::Vector2d x(0.3, 0.4);\n\n  double val = StableEvaluationAtAPoint::Jstar(fe_space, uFE, x);\n\n  double ref_val = u(x);\n\n  double tol = 1.e-2;\n\n  ASSERT_NEAR(val, ref_val, tol);\n}\n\n/*\nTEST(StableEvaluationAtAPoint, stab_pointEval) {\n  auto mesh_factory_init = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader_init(std::move(mesh_factory_init),\n                                 CURRENT_SOURCE_DIR \"/../../meshes/square.msh\");\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = reader_init.mesh();\n\n  std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\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\n  const Eigen::Vector2d x(0.3, 0.4);\n\n  double val = StableEvaluationAtAPoint::StablePointEvaluation(fe_space, u, x);\n\n  double ref_val = 0.0;\n\n  double tol = 1.e-4;\n\n  ASSERT_NEAR(std::abs(ref_val - val), 0.0, tol);\n}\n*/\n", "meta": {"hexsha": "28b9ce564c7f80767058de0f892e2d811d8827cb", "size": 4137, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/StableEvaluationAtAPoint/templates/test/stableevaluationatapoint_test.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T10:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T10:59:19.000Z", "max_issues_repo_path": "homeworks/StableEvaluationAtAPoint/templates/test/stableevaluationatapoint_test.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/StableEvaluationAtAPoint/templates/test/stableevaluationatapoint_test.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": 29.9782608696, "max_line_length": 80, "alphanum_fraction": 0.6565143824, "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5786684245511322}}
{"text": "//\n//  functions.hpp\n//  spreadsheet\n//\n//  Created by Irit Katriel on 05/08/2012.\n//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.\n//\n\n#pragma once\n\n#include \"streamulus.h\"\n\n#include <boost/type_traits.hpp>\n#include <boost/utility/enable_if.hpp>\n\nnamespace spreadsheet {\n\nnamespace bm = boost::mpl;\n    \n    \ntemplate<typename F, typename ARG>\nstruct StreamifyType\n{\n    typedef typename bp::result_of::make_expr<bp::tag::function, F, ARG const &>::type type;\n};\n    \nstruct ABS_FUNC\n{\n    template<class Sig> struct result;\n\n    template<class This,typename A> \n    struct result<This(A)>\n    {\n        typedef A type; \n    };\n        \n    template<typename A>\n    typename boost::enable_if<boost::is_integral<A>, typename result<ABS_FUNC(A)>::type>::type\n    operator()(const A& value) const\n    { \n        return std::abs(value); \n    }\n\n    template<typename A>\n    typename boost::enable_if<boost::is_floating_point<A>, typename result<ABS_FUNC(A)>::type>::type\n    operator()(const A& value) const\n    { \n        return std::fabs(value); \n    }\n};\n\ntemplate<double FUNC(double)>\nstruct DOUBLE_TO_DOUBLE_FUNC\n{\n    template<class Sig> struct result;\n    \n    template<class This,typename A> \n    struct result<This(A)>\n    {\n        typedef A type; \n    };\n  \n    template<typename A>\n    typename result<DOUBLE_TO_DOUBLE_FUNC<FUNC>(A)>::type\n    operator()(const A& value) const\n    { \n        return FUNC(value); \n    }\n};\n    \n#define LAZY_FUNC1(NAME, FUNC) \\\ntemplate<typename A> \\\ntypename StreamifyType<FUNC,A>::type \\\nNAME(const A& arg) \\\n{ \\\n    return streamulus::Streamify<FUNC>(arg); \\\n}\n    \nLAZY_FUNC1(ABS,   ABS_FUNC);\nLAZY_FUNC1(ACOS,  DOUBLE_TO_DOUBLE_FUNC<std::acos >);\nLAZY_FUNC1(ASIN,  DOUBLE_TO_DOUBLE_FUNC<std::asin >);\nLAZY_FUNC1(ATAN,  DOUBLE_TO_DOUBLE_FUNC<std::atan >);\nLAZY_FUNC1(CEIL,  DOUBLE_TO_DOUBLE_FUNC<std::ceil >);\nLAZY_FUNC1(COS,   DOUBLE_TO_DOUBLE_FUNC<std::cos  >);\nLAZY_FUNC1(COSH,  DOUBLE_TO_DOUBLE_FUNC<std::cosh >);\nLAZY_FUNC1(EXP,   DOUBLE_TO_DOUBLE_FUNC<std::exp  >);\nLAZY_FUNC1(FLOOR, DOUBLE_TO_DOUBLE_FUNC<std::floor>);\nLAZY_FUNC1(LOG,   DOUBLE_TO_DOUBLE_FUNC<std::log  >);\nLAZY_FUNC1(LOG10, DOUBLE_TO_DOUBLE_FUNC<std::log10>);\nLAZY_FUNC1(SIN,   DOUBLE_TO_DOUBLE_FUNC<std::sin  >);\nLAZY_FUNC1(SINH,  DOUBLE_TO_DOUBLE_FUNC<std::sinh >);\nLAZY_FUNC1(SQRT,  DOUBLE_TO_DOUBLE_FUNC<std::sqrt >);\nLAZY_FUNC1(TAN,   DOUBLE_TO_DOUBLE_FUNC<std::tan  >);\nLAZY_FUNC1(TANH,  DOUBLE_TO_DOUBLE_FUNC<std::tanh >);\n\n#undef LAZY_FUNC1\n\n} // ns spreadsheet", "meta": {"hexsha": "05543f2979099c9960c7710634817b2f27989631", "size": 2502, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Chapter06/source_code/spreadsheet-master/math_funcs.hpp", "max_stars_repo_name": "ngdzu/CPP-Reactive-Programming", "max_stars_repo_head_hexsha": "e1a19feb40be086d47227587b8ed3d509b7518ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 98.0, "max_stars_repo_stars_event_min_datetime": "2018-07-03T08:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T22:16:58.000Z", "max_issues_repo_path": "Chapter06/source_code/spreadsheet-master/math_funcs.hpp", "max_issues_repo_name": "ngdzu/CPP-Reactive-Programming", "max_issues_repo_head_hexsha": "e1a19feb40be086d47227587b8ed3d509b7518ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-30T10:38:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T06:56:20.000Z", "max_forks_repo_path": "Chapter06/source_code/spreadsheet-master/math_funcs.hpp", "max_forks_repo_name": "ngdzu/CPP-Reactive-Programming", "max_forks_repo_head_hexsha": "e1a19feb40be086d47227587b8ed3d509b7518ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2018-07-06T02:09:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T08:42:50.000Z", "avg_line_length": 25.5306122449, "max_line_length": 100, "alphanum_fraction": 0.68745004, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451416, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5786282089910433}}
{"text": "// This file is part of the dune-xt project:\n//   https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt\n// Copyright 2009-2021 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//   Felix Schindler (2017)\n//   Ren\u00e9 Fritze     (2017 - 2020)\n//   Tobias Leibner  (2020)\n\n#ifndef DUNE_XT_COMMON_VECTOR_STATISTICS_HH\n#define DUNE_XT_COMMON_VECTOR_STATISTICS_HH\n\n#include <algorithm>\n\n#include <dune/xt/common/type_traits.hh>\n#include <dune/xt/common/vector.hh>\n\n#include <boost/accumulators/statistics/variance.hpp>\n\nnamespace Dune::XT::Common {\n\ntemplate <class VectorType>\ntypename std::enable_if<is_vector<VectorType>::value, typename VectorAbstraction<VectorType>::S>::type\nstandard_deviation(const VectorType& vector)\n{\n  using namespace boost::accumulators;\n  using FieldType = typename VectorAbstraction<VectorType>::S;\n  accumulator_set<FieldType, stats<tag::lazy_variance>> acc;\n  std::for_each(vector.begin(), vector.end(), [&](FieldType value) { acc(value); });\n  return std::sqrt(variance(acc));\n}\n\n\n} // namespace Dune::XT::Common\n\n#endif // DUNE_XT_COMMON_VECTOR_STATISTICS_HH\n", "meta": {"hexsha": "9267bd3aac62925f7b3776eba6c1bee2e1568ab2", "size": 1365, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/xt/common/vector_statistics.hh", "max_stars_repo_name": "dune-community/dune-xt", "max_stars_repo_head_hexsha": "da921524c6fff8d60c715cb4849a0bdd5f020d2b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T04:08:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-01T18:54:14.000Z", "max_issues_repo_path": "dune/xt/common/vector_statistics.hh", "max_issues_repo_name": "dune-community/dune-xt", "max_issues_repo_head_hexsha": "da921524c6fff8d60c715cb4849a0bdd5f020d2b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-08-19T12:06:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-27T08:20:39.000Z", "max_forks_repo_path": "dune/xt/common/vector_statistics.hh", "max_forks_repo_name": "dune-community/dune-xt", "max_forks_repo_head_hexsha": "da921524c6fff8d60c715cb4849a0bdd5f020d2b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-08T04:09:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T04:09:34.000Z", "avg_line_length": 35.0, "max_line_length": 102, "alphanum_fraction": 0.7450549451, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.578628206864451}}
{"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": "\n// BLAS level 2 -- complex numbers\n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/atlas/cblas1.hpp>\n#include <boost/numeric/bindings/atlas/cblas2.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#ifdef F_USE_STD_VECTOR\n#include <vector>\n#include <boost/numeric/bindings/traits/std_vector.hpp> \n#endif \n#include \"utils.h\" \n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::cout;\nusing std::endl; \n\ntypedef double real_t;\ntypedef std::complex<real_t> cmplx_t; \n\n#ifndef F_USE_STD_VECTOR\ntypedef ublas::vector<cmplx_t> vct_t;\ntypedef ublas::matrix<cmplx_t, ublas::row_major> m_t;\n#else\ntypedef ublas::vector<cmplx_t, std::vector<cmplx_t> > vct_t;\ntypedef ublas::matrix<cmplx_t, ublas::column_major, std::vector<cmplx_t> > m_t;\n#endif \n\nint main() {\n\n  cout << endl; \n\n  vct_t vx (2);\n  atlas::set (cmplx_t (1., 0.), vx);\n  print_v (vx, \"vx\"); \n  vct_t vy (4); // vector size can be larger \n                // than corresponding matrix size \n  atlas::set (cmplx_t (0., 0.), vy); \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  m_t m (3, 2);\n  init_m (m, kpp (1)); \n  print_m (m, \"m\"); \n  cout << endl; \n\n  // vy = m vx\n  atlas::gemv (CblasNoTrans, 1.0, m, vx, 0.0, vy);\n  print_v (vy, \"m vx\"); \n  atlas::gemv (m, vx, vy);\n  print_v (vy, \"m vx\"); \n  cout << endl; \n\n  m (0, 0) = cmplx_t (0., 1.);\n  m (0, 1) = cmplx_t (0., 2.);\n  m (1, 0) = cmplx_t (0., 3.);\n  m (1, 1) = cmplx_t (0., 4.);\n  m (2, 0) = cmplx_t (0., 5.);\n  m (2, 1) = cmplx_t (0., 6.);\n  print_m (m, \"m\"); \n  cout << endl; \n\n  // vy = m vx\n  atlas::gemv (CblasNoTrans, 1.0, m, vx, 0.0, vy);\n  print_v (vy, \"m vx\"); \n  atlas::gemv (m, vx, vy);\n  print_v (vy, \"m vx\"); \n  cout << endl; \n\n  m (0, 0) = cmplx_t (-1., 1.);\n  m (0, 1) = cmplx_t (-2., 2.);\n  m (1, 0) = cmplx_t (-3., 3.);\n  m (1, 1) = cmplx_t (-4., 4.);\n  m (2, 0) = cmplx_t (-5., 5.);\n  m (2, 1) = cmplx_t (-6., 6.);\n  print_m (m, \"m\"); \n  cout << endl; \n\n  // vy = m vx\n  atlas::gemv (CblasNoTrans, 1.0, m, vx, 0.0, vy);\n  print_v (vy, \"m vx\"); \n  atlas::gemv (m, vx, vy);\n  print_v (vy, \"m vx\"); \n  cout << endl; \n\n  atlas::set (cmplx_t (0., 1.), vx);\n  print_v (vx, \"vx\"); \n\n  // vy = m vx\n  atlas::gemv (CblasNoTrans, 1.0, m, vx, 0.0, vy);\n  print_v (vy, \"m vx\"); \n  atlas::gemv (m, vx, vy);\n  print_v (vy, \"m vx\"); \n  cout << endl; \n\n  atlas::set (cmplx_t (1., 1.), vx);\n  print_v (vx, \"vx\"); \n\n  // vy = m vx\n  atlas::gemv (CblasNoTrans, 1.0, m, vx, 0.0, vy);\n  print_v (vy, \"m vx\"); \n  atlas::gemv (m, vx, vy);\n  print_v (vy, \"m vx\"); \n  cout << endl; \n\n  // vx = m^H vy\n  atlas::set (cmplx_t (-1., -1.), vy); \n  print_v (vy, \"vy\"); \n  atlas::gemv (CblasConjTrans, 1.0, m, vy, 0.0, vx);\n  print_v (vx, \"m^H vy\"); \n  cout << endl; \n\n  m_t mx (2, 2); \n  m_t my (3, 2); \n\n  ublas::matrix_column<m_t> mxc0 (mx, 0), mxc1 (mx, 1); \n  ublas::matrix_column<m_t> myc0 (my, 0), myc1 (my, 1); \n\n  atlas::set (cmplx_t (1., 0.), mxc0);\n  atlas::set (cmplx_t (0., 0.), mxc1);\n  atlas::set (cmplx_t (0., 0.), myc0);\n  atlas::set (cmplx_t (0., 0.), myc1);\n  print_m (mx, \"mx\");\n  cout << endl; \n  print_m (my, \"my\");\n  cout << endl; \n\n  // my[.,0] = m mx[.,0] \n  atlas::gemv (m, mxc0, myc0); \n  print_m (my, \"m mx[.,0]\");\n\n  cout << endl;\n\n}\n", "meta": {"hexsha": "a39f5a01b35010017e0e8909ace3041237e701e8", "size": 3451, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_cmatr2.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_cmatr2.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_cmatr2.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 24.1328671329, "max_line_length": 79, "alphanum_fraction": 0.5714285714, "num_tokens": 1412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5786282013320596}}
{"text": "#include <Eigen/Core>\n#include \"iris/iris.h\"\n#include \"test_util.h\"\n\nint main() {\n  // A simple example with a sphere centered at the origin\n  Eigen::MatrixXd C(2,2);\n  C << 1, 0,\n       0, 1;\n  Eigen::VectorXd d(2);\n  d << 0, 0;\n  iris::Ellipsoid ellipsoid(C, d);\n\n  Eigen::MatrixXd obs(2,4);\n  obs << 2, 3, 3, 2,\n         2, 2, 3, 3;\n  std::vector<Eigen::MatrixXd> obstacles;\n  obstacles.push_back(obs);\n\n  iris::Polyhedron result(2);\n  bool infeasible_start;\n  iris::separating_hyperplanes(obstacles, ellipsoid, result, infeasible_start);\n  valuecheck(infeasible_start, false);\n  Eigen::MatrixXd A_expected(1, 2);\n  A_expected << 1/std::sqrt(2), 1/std::sqrt(2);\n  Eigen::VectorXd b_expected(1);\n  b_expected << 2.0 * 2.0 * 1.0/std::sqrt(2);\n  valuecheckMatrix(result.getA(), A_expected, 1e-6);\n  valuecheckMatrix(result.getB(), b_expected, 1e-6);\n\n  return 0;\n}", "meta": {"hexsha": "6f7ab889504534cb52990ec1b75f9082a8b838e4", "size": 864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cxx/test/test_separating_hyperplanes.cpp", "max_stars_repo_name": "tardani95/iris-distro", "max_stars_repo_head_hexsha": "dbb1ebbde2e52b4cc747b4aa2fe88518b238071a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 82.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T15:32:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:03:08.000Z", "max_issues_repo_path": "src/cxx/test/test_separating_hyperplanes.cpp", "max_issues_repo_name": "tardani95/iris-distro", "max_issues_repo_head_hexsha": "dbb1ebbde2e52b4cc747b4aa2fe88518b238071a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2015-01-21T16:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T02:47:52.000Z", "max_forks_repo_path": "src/cxx/test/test_separating_hyperplanes.cpp", "max_forks_repo_name": "tardani95/iris-distro", "max_forks_repo_head_hexsha": "dbb1ebbde2e52b4cc747b4aa2fe88518b238071a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 61.0, "max_forks_repo_forks_event_min_datetime": "2015-03-20T18:49:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T12:35:38.000Z", "avg_line_length": 27.0, "max_line_length": 79, "alphanum_fraction": 0.6574074074, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5786281911200808}}
{"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": "// (C) Copyright Jeremy Siek 2001.\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/config.hpp>\n#include <iostream>\n#include <boost/graph/isomorphism.hpp>\n#include <boost/graph/adjacency_list.hpp>\n\n#include <boost/graph/graph_utility.hpp>\n\n/*\n  Sample output:\n  isomorphic? 1\n  f: 9 10 11 0 1 3 2 4 6 8 7 5\n */\n\nint main()\n{\n    using namespace boost;\n\n    const int n = 12;\n\n    typedef adjacency_list< vecS, listS, undirectedS,\n        property< vertex_index_t, int > >\n        graph_t;\n    graph_t g1(n), g2(n);\n\n    std::vector< graph_traits< graph_t >::vertex_descriptor > v1(n), v2(n);\n\n    property_map< graph_t, vertex_index_t >::type v1_index_map\n        = get(vertex_index, g1),\n        v2_index_map = get(vertex_index, g2);\n\n    graph_traits< graph_t >::vertex_iterator i, end;\n    int id = 0;\n    for (boost::tie(i, end) = vertices(g1); i != end; ++i, ++id)\n    {\n        put(v1_index_map, *i, id);\n        v1[id] = *i;\n    }\n    id = 0;\n    for (boost::tie(i, end) = vertices(g2); i != end; ++i, ++id)\n    {\n        put(v2_index_map, *i, id);\n        v2[id] = *i;\n    }\n    add_edge(v1[0], v1[1], g1);\n    add_edge(v1[1], v1[2], g1);\n    add_edge(v1[0], v1[2], g1);\n    add_edge(v1[3], v1[4], g1);\n    add_edge(v1[4], v1[5], g1);\n    add_edge(v1[5], v1[6], g1);\n    add_edge(v1[6], v1[3], g1);\n    add_edge(v1[7], v1[8], g1);\n    add_edge(v1[8], v1[9], g1);\n    add_edge(v1[9], v1[10], g1);\n    add_edge(v1[10], v1[11], g1);\n    add_edge(v1[11], v1[7], g1);\n\n    add_edge(v2[9], v2[10], g2);\n    add_edge(v2[10], v2[11], g2);\n    add_edge(v2[11], v2[9], g2);\n    add_edge(v2[0], v2[1], g2);\n    add_edge(v2[1], v2[3], g2);\n    add_edge(v2[3], v2[2], g2);\n    add_edge(v2[2], v2[0], g2);\n    add_edge(v2[4], v2[5], g2);\n    add_edge(v2[5], v2[7], g2);\n    add_edge(v2[7], v2[8], g2);\n    add_edge(v2[8], v2[6], g2);\n    add_edge(v2[6], v2[4], g2);\n\n    std::vector< graph_traits< graph_t >::vertex_descriptor > f(n);\n\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n    bool ret = isomorphism(g1, g2,\n        make_iterator_property_map(f.begin(), v1_index_map, f[0]),\n        degree_vertex_invariant(), get(vertex_index, g1),\n        get(vertex_index, g2));\n#else\n    bool ret = isomorphism(g1, g2,\n        isomorphism_map(\n            make_iterator_property_map(f.begin(), v1_index_map, f[0])));\n#endif\n    std::cout << \"isomorphic? \" << ret << std::endl;\n\n    std::cout << \"f: \";\n    for (std::size_t v = 0; v != f.size(); ++v)\n        std::cout << get(get(vertex_index, g2), f[v]) << \" \";\n    std::cout << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "6a21520b40a00f3b8548af4bc1d49d9584f3902b", "size": 2671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/isomorphism.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/isomorphism.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/isomorphism.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": 27.8229166667, "max_line_length": 75, "alphanum_fraction": 0.5746911269, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5785818817246582}}
{"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": "/*    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 *      GTOP, http://www.esa.int/gsp/ACT/doc/INF/Code/globopt/GTOPtoolbox.rar.\n *\n *    Notes\n *      Note that for some of the near-parabolic cases, the tolerance used for the to-and-fro\n *      conversions (Test 4) is several order of magnitudes higher than used for the regular cases.\n *      This should be investigated further in the future to fully characterize the nature of the\n *      conversions in the near-parabolic cases.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/test/unit_test.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\n#include <fstream>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/convertMeanToEccentricAnomalies.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/unitConversions.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace orbital_element_conversions;\nusing namespace mathematical_constants;\n\n//! Error writing function.\n/*!\n * This function writes the input values that led to errors to a unique file, if any errors occured\n * during the random tests. To make the file unique, the date and time of execution is added. An\n * error message also shows the location of the file.\n * \\param eccentricities A vector containing the eccentricities that caused a failure.\n * \\param meanAnomalies A vector containing the mean anomalies that caused a failure.\n * \\param testName A string specifying the name of the test that failed.\n */\nvoid writeErrorsToFile( std::vector< double > eccentricities, std::vector< double > meanAnomalies,\n                        std::string testName )\n{\n    // Obtain the current time.\n    const boost::posix_time::ptime now = boost::posix_time::second_clock::local_time( );\n\n    // Make a string containing the output file name. This output file is tagged with the date and\n    // time at which the code was executed. The default date format is: YYYYMMDDTHHMMSS, in which T\n    // separates date and time.\n    const std::string outputFileName = input_output::getTudatRootPath( ) +\n            \"Astrodynamics/BasicAstrodynamics/UnitTests/\" +\n            \"ErrorReportConversionMeanToHyperbolicEccentricAnomaly\" +\n            testName + \"RunAt\" + boost::posix_time::to_iso_string( now )\n            + \".txt\";\n\n    // Make a stream to a file.\n    std::ofstream errorFile( outputFileName.c_str( ) );\n\n    // Write an introduction in the file explaining what happened. 70 lines long.\n    errorFile << \"This error report was generated because the unit test for the\" << std::endl\n              << \"conversion of mean to hyperbolic eccentric anomaly has failed in\" << std::endl\n              << \"one of the random tests. To ensure the data for which it failed is\" << std::endl\n              << \"not lost, the corresponding input variables for these cases are\" << std::endl\n              << \"listed below. Please report a bug on the Tudat website \" << std::endl\n              << \"(tudat.tudelft.nl), with these values, so that someone will look\" << std::endl\n              << \"into it and the code can be improved.\" << std::endl << std::endl\n              << \"Eccentricities:           Mean anomalies:\" << std::endl;\n\n    // Set the precision for the output of the variables to 16 digits.\n    errorFile.precision( 16 );\n\n    // Add the corresponding eccentricities and mean anomalies at neatly arranged positions.\n    for ( unsigned int counter = 0; counter < eccentricities.size( ); counter++ )\n    {\n        errorFile << std::setw( 25 ) << eccentricities[ counter ]\n                  << std::setw( 25 ) << meanAnomalies[ counter ] << std::endl;\n    }\n    errorFile.close( );\n\n    // Add an error message specifying the file that the values have been written to.\n    std::cerr << \"One or multiple errors occurred during random sampling. \" << std::endl\n              << \"The values leading to these errors have been written to the following file: \"\n              << std::endl << outputFileName;\n}\n\nBOOST_AUTO_TEST_SUITE( test_mean_to_hyperbolic_eccentric_anomaly_conversion )\n\n//! Test 1: Test a range of values for the conversion.\nBOOST_AUTO_TEST_CASE( test_convertMeanAnomalyToHyperbolicEccentricAnomaly_range )\n{\n    // Set array of test values for eccentricity.\n    const double arrayOfTestEccentricities [ 6 ] = { 1.03, 1.28, 1.97, 2.56, 10.87, 99.72 };\n\n    // Set array of test values for mean anomaly.\n    const double arrayOfTestMeanAnomalies [ 6 ] = { 1.5, 6.0, 0.5, -4.0, 5.5, 2.5 };\n\n    // Set array of expected values for hyperbolic eccentric anomaly. These values were converted\n    // back and forth to verify their correctness. Also the conversion was verified by comparing\n    // with GTOP. GTOP uses a different definition for the hyperbolic eccentric anomaly. Hence\n    // the mean anomalies were converted to cartesian positions and compared to the same conversion\n    // using Tudat methods. (GTOP also does not use true anomaly as explicit step.)\n    const double arrayOfExpectedHyperbolicAnomalies [ 6 ] = { 1.9132897042137,\n                                                              2.60400218106873,\n                                                              0.478057581067141,\n                                                              -1.50971422579796,\n                                                              0.529595060186511,\n                                                              0.0253214157050963 };\n\n    // Loop over sets of data.\n    for ( int counter = 0; counter < 6; counter++ )\n    {\n        // Compute the hyperbolic eccentric anomaly.\n        const double hyperbolicEccentricAnomaly = convertMeanAnomalyToHyperbolicEccentricAnomaly(\n                    arrayOfTestEccentricities[ counter ], arrayOfTestMeanAnomalies[ counter ] );\n\n        // Check if computed eccentric anomaly is less than error tolerance.\n        BOOST_CHECK_CLOSE_FRACTION( arrayOfExpectedHyperbolicAnomalies[ counter ],\n                                    hyperbolicEccentricAnomaly,\n                                    1.0E-14 );\n    }\n}\n\n//! Test 2: Test a value that is out of range.\nBOOST_AUTO_TEST_CASE( test_convertMeanAnomalyToHyperbolicEccentricAnomaly_TooLow )\n{\n    // Set test value for eccentricity.\n    const double testEccentricity = 0.5;\n\n    // Set test value for mean anomaly.\n    const double testMeanAnomaly = 0.5;\n\n    // Check if a runtime error is thrown if the anomaly is converted for this eccentricity.\n    BOOST_CHECK_THROW( convertMeanAnomalyToHyperbolicEccentricAnomaly(\n                           testEccentricity, testMeanAnomaly ), std::runtime_error );\n}\n\n//! Test 3: Test conversion for near-parabolic orbits.\nBOOST_AUTO_TEST_CASE( test_convertMeanAnomalyToHyperbolicEccentricAnomaly_nearParabolic )\n{\n    // Set test value for eccentricity.\n    const double testEccentricity = 1.0 + 1.0e-10;\n\n    // Set array of test values for mean anomaly.\n    const double arrayOfTestMeanAnomalies[ 4 ] = { -10.0, -1.4, 0.5, 7.6 };\n\n    // Set array of expected values for hyperbolic eccentric anomaly. These values were converted\n    // back and forth to verify their correctness. Also the conversion was verified by comparing\n    // with GTOP. GTOP uses a different definition for the hyperbolic eccentric anomaly. Hence\n    // the mean anomalies were converted to cartesian positions and compared to the same conversion\n    // using Tudat methods. (GTOP also does not use true anomaly as explicit step)\n    const double arrayOfExpectedHyperbolicAnomalies [ 4 ] = { -3.280887528670698,\n                                                              -1.913052492643601,\n                                                              1.396250871565077,\n                                                              3.062027761338891 };\n\n    // Loop over sets of data.\n    for ( int counter = 0; counter < 4; counter++ )\n    {\n        // Compute the hyperbolic eccentric anomaly.\n        const double hyperbolicEccentricAnomaly = convertMeanAnomalyToHyperbolicEccentricAnomaly(\n                    testEccentricity, arrayOfTestMeanAnomalies[ counter ] );\n\n        // Check if computed eccentric anomaly is less than error tolerance.\n        BOOST_CHECK_CLOSE_FRACTION( arrayOfExpectedHyperbolicAnomalies[ counter ],\n                                    hyperbolicEccentricAnomaly,\n                                    1.0E-14 );\n    }\n\n}\n\n//! Generalized function to test many to and fro mean to hyperbolic eccentric anomalies.\n/*!\n *  Generalized function to test many to and fro mean to hyperbolic eccentric anomalies.\n *  The function allows random variations of both the mean anomlay and eccentricity. The\n *  eccentricity may be fixed, for instance to test near-parabolic orbits for many mean\n *  anomalies. Furthermore, the range of mean anomalies and eccentricities may be set\n *  as exponential, so that a random number of 4.5 generates an eccentricity of 10^(4.5), to allow\n *  testing of extreme orbits.\n *  \\param caseId Name of test case, to be used for error output purposes.\n *  \\param testTolerance Acceptance tolerance to be used for difference between original and\n *  reconverted mean anomaly. Tolerance is absolute if useExponentialValues is false and relative\n *  if useExponentialValues is true.\n *  \\param meanAnomalyLimit Limit of mean anomaly values, range of mean anomalies is set as\n *  [-meanAnomalyLimit,meanAnomalyLimit].\n *  \\param useConstantEccentricity Boolean determining if a constant eccentricity is used.\n *  \\param useExponentialValues Boolean determining whether exponential values are used for\n *  random mean anomalies and eccentricities.\n *  \\param minimumEccentricity Minimum value to be used for random eccentricities (only used if\n *  useConstantEccentricity is false).\n *  \\param maximumEccentricity Maximum value to be used for random eccentricities (only used if\n *  useConstantEccentricity is false).\n *  \\param constantEccentricity Constant value to be used for eccentricity (only used if\n *  useConstantEccentricity is true).\n *  \\param numberOfSamples Number of random cases that are to be tested.\n */\ntemplate< typename ScalarType >\nvoid testMeanToHyperbolicEccentricAnomalyConversions(\n        const std::string& caseId,\n        const ScalarType testTolerance,\n        const ScalarType meanAnomalyLimit,\n        const bool useConstantEccentricity = 0,\n        const bool useExponentialValues = 0,\n        const ScalarType minimumEccentricity = TUDAT_NAN,\n        const ScalarType maximumEccentricity = TUDAT_NAN,\n        const ScalarType constantEccentricity = TUDAT_NAN,\n        const int numberOfSamples = 1E5)\n{\n    // Create vectors that will store the input variables of a test that resulted in an error, such\n    // that the error scenario can be reproduced.\n    std::vector< double > failedMeanAnomalies, failedEccentricities;\n\n    // Boolean that will be set true if a runtime error occurred.\n    bool aRuntimeErrorOccurred = false;\n\n    // Set test value for eccentricity.\n    ScalarType testEccentricity = constantEccentricity;\n\n    // Initialize both test and reverse calculated mean anomaly and the eccentric anomaly.\n    ScalarType testMeanAnomaly, reverseCalculatedMeanAnomaly, eccentricAnomaly = 0.0;\n\n    // Instantiate random number generator.\n    boost::mt19937 randomNumbergenerator( time( 0 ) );\n\n    // Create generator for eccentricity (only used if useConstantEccentricity is false).\n    boost::random::uniform_real_distribution< > eccentricityDistribution;\n    if( !useConstantEccentricity )\n    {\n        eccentricityDistribution =\n                boost::random::uniform_real_distribution< >(\n                    minimumEccentricity, maximumEccentricity );\n    }\n\n\n    boost::variate_generator< boost::mt19937&, boost::random::uniform_real_distribution < > >\n            eccentricityGenerator(\n                randomNumbergenerator, eccentricityDistribution );\n\n    // Create generator for mean anomaly.\n    boost::random::uniform_real_distribution< ScalarType > meanAnomalyDistibution(\n                -meanAnomalyLimit, meanAnomalyLimit );\n    boost::variate_generator<\n            boost::mt19937&, boost::random::uniform_real_distribution < ScalarType > >\n            generateMeanAnomaly( randomNumbergenerator, meanAnomalyDistibution );\n\n    // Perform the conversion for the specified number of samples and test whether the values that\n    // are subsequently converted back match the initial values.\n    for ( int counter = 0; counter < numberOfSamples; counter++ )\n    {\n        // Set random value in test mean anomaly.\n        testMeanAnomaly = generateMeanAnomaly( );\n\n        if( useExponentialValues )\n        {\n            testMeanAnomaly = testMeanAnomaly *\n                    std::pow( getFloatingInteger< ScalarType >( 10 ), generateMeanAnomaly( ) );\n        }\n        // If eccentricity is to be varied, generate random value\n        if( !useConstantEccentricity )\n        {\n            testEccentricity = eccentricityGenerator( );\n\n            if( useExponentialValues )\n            {\n                testEccentricity = getFloatingInteger< ScalarType >( 1 ) +\n                        std::pow( getFloatingInteger< ScalarType >( 10 ), testEccentricity );\n            }\n        }\n\n        // If the Rootfinder does not converge, it will produce a runtime error. In order to make\n        // sure that these values that led to the error will not be lost, they will be stored in\n        // the failed input data vectors. To do so, a try-catch sequence is used.\n        try\n        {\n            // Compute eccentric anomaly.\n            eccentricAnomaly = convertMeanAnomalyToHyperbolicEccentricAnomaly< ScalarType>(\n                        testEccentricity, testMeanAnomaly );\n        }\n        catch( std::runtime_error )\n        {\n            // Store the fact that a runtime error occurred, such that the values will be stored.\n            aRuntimeErrorOccurred = true;\n        }\n\n        // Calculate the mean anomaly from this eccentric anomaly.\n        reverseCalculatedMeanAnomaly = convertHyperbolicEccentricAnomalyToMeanAnomaly< ScalarType>(\n                    eccentricAnomaly, testEccentricity );\n\n        // Test whether the computed mean anomaly is equal to the mean anomaly from the input and\n        // that no runtime errors occurred. If an error was found, store the values leading to this\n        // error in a vector for later use. '!' operator is there to ensure that a NaN value will\n        // result in the values being written away. It is also checked that the mean anomaly is\n        // not equal to 0.0, because that would result in falsely writing an error.\n        if( !useExponentialValues )\n        {\n            if ( ( ( !( std::abs( testMeanAnomaly - reverseCalculatedMeanAnomaly ) <\n                        testTolerance ) )\n                   && !( testMeanAnomaly == getFloatingInteger< ScalarType >( 0 ) ||\n                         reverseCalculatedMeanAnomaly == getFloatingInteger< ScalarType >( 0 ) ) )\n                 && !aRuntimeErrorOccurred )\n            {\n                failedMeanAnomalies.push_back( testMeanAnomaly );\n                failedEccentricities.push_back( testEccentricity );\n            }\n        }\n        else\n        {\n            if ( ( ( !( std::abs( testMeanAnomaly - reverseCalculatedMeanAnomaly ) /\n                        testMeanAnomaly < testTolerance ) )\n                   && !( testMeanAnomaly == getFloatingInteger< ScalarType >( 0 ) ||\n                         reverseCalculatedMeanAnomaly == getFloatingInteger< ScalarType >( 0 ) ) )\n                 && !aRuntimeErrorOccurred )\n            {\n                failedMeanAnomalies.push_back( testMeanAnomaly );\n                failedEccentricities.push_back( testEccentricity );\n            }\n        }\n\n        // Reset boolean.\n        aRuntimeErrorOccurred = false;\n    }\n\n    // Check that no values have been written to the failedMeanAnomalies vector.  If so, this test\n    // is passed. Otherwisely these values will be written away and this test will fail.\n    BOOST_CHECK( failedMeanAnomalies.empty( ) );\n\n    // If the vector is not empty, write the failed cases of this test case to a file.\n    if ( !( failedMeanAnomalies.empty( ) ) )\n    {\n        writeErrorsToFile( failedEccentricities, failedMeanAnomalies, caseId );\n    }\n}\n\n//! Test 4: Test large number of anomalies and eccentricities\nBOOST_AUTO_TEST_CASE( test_convertMeanAnomalyToEccentricAnomaly_nearParabolic_random_double )\n{\n    long double ratioOfPrecision = std::numeric_limits< long double >::epsilon( ) /\n            std::numeric_limits< double >::epsilon( );\n\n    // Test random conversions for near-parabolic orbits\n    testMeanToHyperbolicEccentricAnomalyConversions< double >(\n                \"DoubleParabolic\", 1.0E-13, 20.0, 1, 0, TUDAT_NAN, TUDAT_NAN, 1.0 + 1.0e-15 );\n    testMeanToHyperbolicEccentricAnomalyConversions< long double >(\n                \"LongDoubleParabolic\", 1.0E-13L * ratioOfPrecision, 20.0L, 1, 0,\n                TUDAT_NAN, TUDAT_NAN, 1.0L + 1.0e-15L * ratioOfPrecision );\n\n    // Test random conversions for random orbits\n    testMeanToHyperbolicEccentricAnomalyConversions< double >(\n                \"DoubleTypical\", 1.0E-13, 20.0, 0, 0, 1.0 + 1.0e-15, 10.0, TUDAT_NAN );\n    testMeanToHyperbolicEccentricAnomalyConversions< long double >(\n                \"LongDoubleTypical\", 1.0E-13L, 20.0L, 0, 0, 1.0L + 1.0e-15L * ratioOfPrecision,\n                10.0L, TUDAT_NAN );\n\n    // Test random conversions for extreme values of eccentricity and mean anomaly.\n    testMeanToHyperbolicEccentricAnomalyConversions< double >(\n                \"DoubleHighlyEccentric\", 1.0E-14, 12.0, 0, 1, 0.0, 15.0, TUDAT_NAN );\n    testMeanToHyperbolicEccentricAnomalyConversions< long double >(\n                \"LongDoubleHighlyEccentric\", 1.0E-14L, 12.0L, 0, 1, 0.0L, 15.0L, TUDAT_NAN );\n\n}\n\n//! Test 5: Test functionality of specifying the initial guess.\nBOOST_AUTO_TEST_CASE( test_convertMeanAnomalyToHyperbolicEccentricAnomaly_specificInitialGuess )\n{\n    // Set test value for eccentricity.\n    const double testEccentricity = 1.97;\n\n    // Set test value for mean anomaly.\n    const double testHyperbolicMeanAnomaly = 0.5;\n\n    // Set expected hyperbolic eccentric anomaly. (Similar case as in Test 1.)\n    const double expectedHyperbolicEccentricAnomaly = 0.478057581067141;\n\n    // Set the initial guess.\n    const double initialGuess = 2.0 * testHyperbolicMeanAnomaly / testEccentricity - 1.8;\n\n    // Compute eccentric anomaly.\n    const double hyperbolicEccentricAnomaly = convertMeanAnomalyToHyperbolicEccentricAnomaly(\n                testEccentricity, testHyperbolicMeanAnomaly, false, initialGuess );\n\n    // Check if computed eccentric anomaly is NaN for invalid eccentricity.\n    BOOST_CHECK_CLOSE_FRACTION( expectedHyperbolicEccentricAnomaly, hyperbolicEccentricAnomaly,\n                                1.0E-14 );\n}\n\n// End Boost test suite.\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "40e4ae8332af55464f06a72109350c3b8dbcb39f", "size": 19659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestConvertMeanAnomalyToHyperbolicEccentricAnomaly.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestConvertMeanAnomalyToHyperbolicEccentricAnomaly.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestConvertMeanAnomalyToHyperbolicEccentricAnomaly.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.7816377171, "max_line_length": 99, "alphanum_fraction": 0.6751106363, "num_tokens": 4694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5785818722364885}}
{"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": "/* boost random/lognormal_distribution.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: lognormal_distribution.hpp,v 1.1.1.1 2007/10/29 07:32:44 cvsadmin Exp $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_LOGNORMAL_DISTRIBUTION_HPP\n#define BOOST_RANDOM_LOGNORMAL_DISTRIBUTION_HPP\n\n#include <cmath>      // std::exp, std::sqrt\n#include <cassert>\n#include <iostream>\n#include <boost/limits.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n#ifdef BOOST_NO_STDC_NAMESPACE\nnamespace std {\n  using ::log;\n  using ::sqrt;\n}\n#endif\n\nnamespace boost {\n\n#if defined(__GNUC__) && (__GNUC__ < 3)\n// Special gcc workaround: gcc 2.95.x ignores using-declarations\n// in template classes (confirmed by gcc author Martin v. Loewis)\n  using std::sqrt;\n  using std::exp;\n#endif\n\ntemplate<class RealType = double>\nclass lognormal_distribution\n{\npublic:\n  typedef typename normal_distribution<RealType>::input_type input_type;\n  typedef RealType result_type;\n\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n    BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);\n#endif\n\n  explicit lognormal_distribution(result_type mean = result_type(1),\n                                  result_type sigma = result_type(1))\n    : _mean(mean), _sigma(sigma)\n  { \n    assert(mean > result_type(0));\n    init();\n  }\n\n  // compiler-generated copy ctor and assignment operator are fine\n\n  RealType& mean() const { return _mean; }\n  RealType& sigma() const { return _sigma; }\n  void reset() { _normal.reset(); }\n\n  template<class Engine>\n  result_type operator()(Engine& eng)\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    // allow for Koenig lookup\n    using std::exp;\n#endif\n    return exp(_normal(eng) * _nsigma + _nmean);\n  }\n\n#if !defined(BOOST_NO_OPERATORS_IN_NAMESPACE) && !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)\n  template<class CharT, class Traits>\n  friend std::basic_ostream<CharT,Traits>&\n  operator<<(std::basic_ostream<CharT,Traits>& os, const lognormal_distribution& ld)\n  {\n    os << ld._normal << \" \" << ld._mean << \" \" << ld._sigma;\n    return os;\n  }\n\n  template<class CharT, class Traits>\n  friend std::basic_istream<CharT,Traits>&\n  operator>>(std::basic_istream<CharT,Traits>& is, lognormal_distribution& ld)\n  {\n    is >> std::ws >> ld._normal >> std::ws >> ld._mean >> std::ws >> ld._sigma;\n    ld.init();\n    return is;\n  }\n#endif\n\nprivate:\n  void init()\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    // allow for Koenig lookup\n    using std::exp; using std::log; using std::sqrt;\n#endif\n    _nmean = log(_mean*_mean/sqrt(_sigma*_sigma + _mean*_mean));\n    _nsigma = sqrt(log(_sigma*_sigma/_mean/_mean+result_type(1)));\n  }\n\n  RealType _mean, _sigma;\n  RealType _nmean, _nsigma;\n  normal_distribution<result_type> _normal;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_LOGNORMAL_DISTRIBUTION_HPP\n", "meta": {"hexsha": "731c6506121f3b3745ce80450a2216aa958fb4fa", "size": 3131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Game/boost/boost/random/lognormal_distribution.hpp", "max_stars_repo_name": "hackerlank/SourceCode", "max_stars_repo_head_hexsha": "b702c9e0a9ca5d86933f3c827abb02a18ffc9a59", "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": "Game/boost/boost/random/lognormal_distribution.hpp", "max_issues_repo_name": "shacojx/SourceCodeGameTLBB", "max_issues_repo_head_hexsha": "e3cea615b06761c2098a05427a5f41c236b71bf7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Game/boost/boost/random/lognormal_distribution.hpp", "max_forks_repo_name": "shacojx/SourceCodeGameTLBB", "max_forks_repo_head_hexsha": "e3cea615b06761c2098a05427a5f41c236b71bf7", "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": 27.2260869565, "max_line_length": 91, "alphanum_fraction": 0.7141488342, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5785717230447307}}
{"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": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/config.hpp>\n#ifdef BOOST_NO_CXX11_HDR_ARRAY\n\nint main()\n{\n    return 0;\n}\n\n#else //this example needs C++11 std::array\n\n//[std_array\n//` Shows how to use a C++11 std::array using Boost.Geometry's distance, set and assign_values algorithms\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/adapted/std_array.hpp>\n\nBOOST_GEOMETRY_REGISTER_STD_ARRAY_CS(cs::cartesian)\n\nint main()\n{\n    std::array<float, 2> a = { {1, 2} };\n    std::array<double, 2> b = { {2, 3} };\n    std::cout << boost::geometry::distance(a, b) << std::endl;\n\n    boost::geometry::set<0>(a, 1.1f);\n    boost::geometry::set<1>(a, 2.2f);\n    std::cout << boost::geometry::distance(a, b) << std::endl;\n\n    boost::geometry::assign_values(b, 2.2, 3.3);\n    std::cout << boost::geometry::distance(a, b) << std::endl;\n\n    boost::geometry::model::linestring<std::array<double, 2> > line;\n    line.push_back(b);\n\n    return 0;\n}\n\n//]\n\n#endif //BOOST_NO_CXX11_HDR_ARRAY\n\n//[std_array_output\n/*`\nOutput:\n[pre\n1.41421\n1.20416\n1.55563\n]\n*/\n//]\n", "meta": {"hexsha": "043cf6494bb4440f37cd62b4ce0adcc76cc95b11", "size": 1441, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/geometries/adapted/std_array.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "doc/src/examples/geometries/adapted/std_array.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "doc/src/examples/geometries/adapted/std_array.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 22.515625, "max_line_length": 105, "alphanum_fraction": 0.6814712006, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.5785637069335026}}
{"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 \u00d7 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 \u00d7 3 region around\nit have gradient magnitudes greater than thigh, keep the edge (write out white).\n\u0095If none of pixel (x, y)\u0092s neighbors have high gradient magnitudes but at least one falls between tlow and thigh,\nsearch the 5 \u00d7 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": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[convert\n//` Shows how to convert a geometry into another geometry\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<double> point;\n    typedef boost::geometry::model::box<point> box;\n    typedef boost::geometry::model::polygon<point> polygon;\n\n    point p1(1, 1);\n    box bx = boost::geometry::make<box>(1, 1, 2, 2);\n    \n    // Assign a box to a polygon (conversion box->poly)\n    polygon poly;\n    boost::geometry::convert(bx, poly);\n\n    // Convert a point to another point type (conversion of point-type)\n    boost::tuple<double, double> p2;\n    boost::geometry::convert(p1, p2); // source -> target\n        \n    using boost::geometry::dsv;\n    std::cout\n        << \"box: \" << dsv(bx) << std::endl\n        << \"polygon: \" << dsv(poly) << std::endl\n        << \"point: \" << dsv(p1) << std::endl\n        << \"point tuples: \" << dsv(p2) << std::endl\n        ;\n\n    return 0;\n}\n\n//]\n\n\n//[convert_output\n/*`\nOutput:\n[pre\nbox: ((1, 1), (2, 2))\npolygon: (((1, 1), (1, 2), (2, 2), (2, 1), (1, 1)))\npoint: (1, 1)\npoint tuples: (1, 1)\n]\n*/\n//]\n", "meta": {"hexsha": "6d43fd4d85cee00dc79b2979ddfb49dec1755bd0", "size": 1699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/geometry/doc/src/examples/algorithms/convert.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/geometry/doc/src/examples/algorithms/convert.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/geometry/doc/src/examples/algorithms/convert.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 26.1384615385, "max_line_length": 79, "alphanum_fraction": 0.6450853443, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.5784865595361387}}
{"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": "//==================================================================================================\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_REFINE_REC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REFINE_REC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing refine_rec capabilities\n\n    Performs a Newton-Raphson step to improve precision of reciprocate estimate.\n    This function can be used in conjunction with raw_(rec)\n    to add more precision to the estimate if their default\n    precision is not enough.\n\n    @par semantic:\n    For any given value @c x, @c est  of floating type T:\n\n    @code\n    T r =refine_rec(x, est);\n    @endcode\n\n    is similar to\n\n    @code\n    T r = fma(fnms(est, a0, One<T>()), est, est);\n    @endcode\n\n    @see rec\n\n  **/\n  Value refine_rec(Value const & v0, Value const& est);\n} }\n#endif\n\n#include <boost/simd/function/scalar/refine_rec.hpp>\n#include <boost/simd/function/simd/refine_rec.hpp>\n\n#endif\n", "meta": {"hexsha": "99b56938d6ef8c70aabb18da2b2abec76fdd23cf", "size": 1307, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/refine_rec.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "include/boost/simd/function/refine_rec.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/refine_rec.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 25.1346153846, "max_line_length": 100, "alphanum_fraction": 0.6044376435, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5784409403356322}}
{"text": "#include \"utils/data_generator.cpp\"\n#include \"../src/numerical/gradient_descent/penalized_gd_solver.h\"\n#include \"../src/logging/easylogging++.h\"\n#include <armadillo>\n\nusing arma::mat;\n\nINITIALIZE_EASYLOGGINGPP\n\nmat WEIGHTS = {100, -20, 50, -0.5};\n\nint main(int argc, char *argv[])\n{\n    el::Configurations conf(\"./logging-config.conf\");\n    el::Loggers::reconfigureLogger(\"default\", conf);\n\n    auto data_generator = DataGenerator();\n    auto L = data_generator.generate_library();\n    auto s = data_generator.generate_signal(WEIGHTS);\n\n    LOG(INFO) << \"True: \" << WEIGHTS;\n\n    PenalizedGDSolver solver = PenalizedGDSolver(L, 100, 500, 0.0000000001, 1000000);\n    mat result = solver.solve(s);\n    LOG(INFO) << \"Penalized GD solver fit: \" << result;\n\n    return 0;\n}", "meta": {"hexsha": "524ae763e6db36ed93429b589c6e5f00df528f7f", "size": 768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/penalized_gd_solver.cpp", "max_stars_repo_name": "omyllymaki/math", "max_stars_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T09:12:24.000Z", "max_issues_repo_path": "samples/penalized_gd_solver.cpp", "max_issues_repo_name": "omyllymaki/math", "max_issues_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "samples/penalized_gd_solver.cpp", "max_forks_repo_name": "omyllymaki/math", "max_forks_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4285714286, "max_line_length": 85, "alphanum_fraction": 0.69140625, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5784409350942934}}
{"text": "#ifndef OPENCV_RGBD_GRAPH_NODE_H\n#define OPENCV_RGBD_GRAPH_NODE_H\n\n#include <map>\n#include <unordered_map>\n\n#include \"opencv2/core/affine.hpp\"\n#if defined(HAVE_EIGEN)\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"opencv2/core/eigen.hpp\"\n#endif\n\n#if defined(CERES_FOUND)\n#include <ceres/ceres.h>\n#endif\n\nnamespace cv\n{\nnamespace kinfu\n{\n/*! \\class GraphNode\n *  \\brief Defines a node/variable that is optimizable in a posegraph\n *\n *  Detailed description\n */\n#if defined(HAVE_EIGEN)\nstruct Pose3d\n{\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    Eigen::Vector3d t;\n    Eigen::Quaterniond r;\n\n    Pose3d()\n    {\n        t.setZero();\n        r.setIdentity();\n    };\n    Pose3d(const Eigen::Matrix3d& rotation, const Eigen::Vector3d& translation)\n        : t(translation), r(Eigen::Quaterniond(rotation))\n    {\n        normalizeRotation();\n    }\n\n    Pose3d(const Matx33d& rotation, const Vec3d& translation)\n    {\n        Eigen::Matrix3d R;\n        cv2eigen(rotation, R);\n        cv2eigen(translation, t);\n        r = Eigen::Quaterniond(R);\n        normalizeRotation();\n    }\n\n    explicit Pose3d(const Matx44f& pose)\n    {\n        Matx33d rotation(pose.val[0], pose.val[1], pose.val[2], pose.val[4], pose.val[5],\n                         pose.val[6], pose.val[8], pose.val[9], pose.val[10]);\n        Vec3d translation(pose.val[3], pose.val[7], pose.val[11]);\n        Pose3d(rotation, translation);\n    }\n\n    // NOTE: Eigen overloads quaternion multiplication appropriately\n    inline Pose3d operator*(const Pose3d& otherPose) const\n    {\n        Pose3d out(*this);\n        out.t += r * otherPose.t;\n        out.r *= otherPose.r;\n        out.normalizeRotation();\n        return out;\n    }\n\n    inline Pose3d& operator*=(const Pose3d& otherPose)\n    {\n        t += otherPose.t;\n        r *= otherPose.r;\n        normalizeRotation();\n        return *this;\n    }\n\n    inline Pose3d inverse() const\n    {\n        Pose3d out;\n        out.r = r.conjugate();\n        out.t = out.r * (t * -1.0);\n        return out;\n    }\n\n    inline void normalizeRotation()\n    {\n        if (r.w() < 0)\n            r.coeffs() *= -1.0;\n        r.normalize();\n    }\n};\n#endif\n\nstruct PoseGraphNode\n{\n   public:\n    explicit PoseGraphNode(int _nodeId, const Affine3f& _pose)\n        : nodeId(_nodeId), isFixed(false), pose(_pose)\n    {\n#if defined(HAVE_EIGEN)\n        se3Pose = Pose3d(_pose.rotation(), _pose.translation());\n#endif\n    }\n    virtual ~PoseGraphNode() = default;\n\n    int getId() const { return nodeId; }\n    inline Affine3f getPose() const\n    {\n        return pose;\n    }\n    void setPose(const Affine3f& _pose)\n    {\n        pose = _pose;\n#if defined(HAVE_EIGEN)\n        se3Pose = Pose3d(pose.rotation(), pose.translation());\n#endif\n    }\n#if defined(HAVE_EIGEN)\n    void setPose(const Pose3d& _pose)\n    {\n        se3Pose = _pose;\n        const Eigen::Matrix3d& rotation    = se3Pose.r.toRotationMatrix();\n        const Eigen::Vector3d& translation = se3Pose.t;\n        Matx33d rot;\n        Vec3d trans;\n        eigen2cv(rotation, rot);\n        eigen2cv(translation, trans);\n        Affine3d poseMatrix(rot, trans);\n        pose = poseMatrix;\n    }\n#endif\n    void setFixed(bool val = true) { isFixed = val; }\n    bool isPoseFixed() const { return isFixed; }\n\n   public:\n    int nodeId;\n    bool isFixed;\n    Affine3f pose;\n#if defined(HAVE_EIGEN)\n    Pose3d se3Pose;\n#endif\n};\n\n/*! \\class PoseGraphEdge\n *  \\brief Defines the constraints between two PoseGraphNodes\n *\n *  Detailed description\n */\nstruct PoseGraphEdge\n{\n   public:\n    PoseGraphEdge(int _sourceNodeId, int _targetNodeId, const Affine3f& _transformation,\n                  const Matx66f& _information = Matx66f::eye())\n        : sourceNodeId(_sourceNodeId),\n          targetNodeId(_targetNodeId),\n          transformation(_transformation),\n          information(_information)\n    {\n    }\n    virtual ~PoseGraphEdge() = default;\n\n    int getSourceNodeId() const { return sourceNodeId; }\n    int getTargetNodeId() const { return targetNodeId; }\n\n    bool operator==(const PoseGraphEdge& edge)\n    {\n        if ((edge.getSourceNodeId() == sourceNodeId && edge.getTargetNodeId() == targetNodeId) ||\n            (edge.getSourceNodeId() == targetNodeId && edge.getTargetNodeId() == sourceNodeId))\n            return true;\n        return false;\n    }\n\n   public:\n    int sourceNodeId;\n    int targetNodeId;\n    Affine3f transformation;\n    Matx66f information;\n};\n\n//! @brief Reference: A tutorial on SE(3) transformation parameterizations and on-manifold\n//! optimization Jose Luis Blanco Compactly represents the jacobian of the SE3 generator\n// clang-format off\n/* static const std::array<Matx44f, 6> generatorJacobian = { */\n/*     // alpha */\n/*     Matx44f(0, 0,  0, 0, */\n/*             0, 0, -1, 0, */\n/*             0, 1,  0, 0, */\n/*             0, 0,  0, 0), */\n/*     // beta */\n/*     Matx44f( 0, 0, 1, 0, */\n/*              0, 0, 0, 0, */\n/*             -1, 0, 0, 0, */\n/*              0, 0, 0, 0), */\n/*     // gamma */\n/*     Matx44f(0, -1, 0, 0, */\n/*             1,  0, 0, 0, */\n/*             0,  0, 0, 0, */\n/*             0,  0, 0, 0), */\n/*     // x */\n/*     Matx44f(0, 0, 0, 1, */\n/*             0, 0, 0, 0, */\n/*             0, 0, 0, 0, */\n/*             0, 0, 0, 0), */\n/*     // y */\n/*     Matx44f(0, 0, 0, 0, */\n/*             0, 0, 0, 1, */\n/*             0, 0, 0, 0, */\n/*             0, 0, 0, 0), */\n/*     // z */\n/*     Matx44f(0, 0, 0, 0, */\n/*             0, 0, 0, 0, */\n/*             0, 0, 0, 1, */\n/*             0, 0, 0, 0) */\n/* }; */\n// clang-format on\n\nclass PoseGraph\n{\n   public:\n    typedef std::vector<PoseGraphNode> NodeVector;\n    typedef std::vector<PoseGraphEdge> EdgeVector;\n\n    explicit PoseGraph(){};\n    virtual ~PoseGraph() = default;\n\n    //! PoseGraph can be copied/cloned\n    PoseGraph(const PoseGraph&) = default;\n    PoseGraph& operator=(const PoseGraph&) = default;\n\n    void addNode(const PoseGraphNode& node) { nodes.push_back(node); }\n    void addEdge(const PoseGraphEdge& edge) { edges.push_back(edge); }\n\n    bool nodeExists(int nodeId) const\n    {\n        return std::find_if(nodes.begin(), nodes.end(), [nodeId](const PoseGraphNode& currNode) {\n                   return currNode.getId() == nodeId;\n               }) != nodes.end();\n    }\n\n    bool isValid() const;\n\n    int getNumNodes() const { return int(nodes.size()); }\n    int getNumEdges() const { return int(edges.size()); }\n\n   public:\n    NodeVector nodes;\n    EdgeVector edges;\n};\n\nnamespace Optimizer\n{\nvoid optimize(PoseGraph& poseGraph);\n\n#if defined(CERES_FOUND)\nvoid createOptimizationProblem(PoseGraph& poseGraph, ceres::Problem& problem);\n\n//! Error Functor required for Ceres to obtain an auto differentiable cost function\nclass Pose3dErrorFunctor\n{\n   public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    Pose3dErrorFunctor(const Pose3d& _poseMeasurement, const Matx66d& _sqrtInformation)\n        : poseMeasurement(_poseMeasurement)\n    {\n        cv2eigen(_sqrtInformation, sqrtInfo);\n    }\n    Pose3dErrorFunctor(const Pose3d& _poseMeasurement,\n                       const Eigen::Matrix<double, 6, 6>& _sqrtInformation)\n        : poseMeasurement(_poseMeasurement), sqrtInfo(_sqrtInformation)\n    {\n    }\n\n    template<typename T>\n    bool operator()(const T* const _pSourceTrans, const T* const _pSourceQuat,\n                    const T* const _pTargetTrans, const T* const _pTargetQuat, T* _pResidual) const\n    {\n        Eigen::Map<const Eigen::Matrix<T, 3, 1>> sourceTrans(_pSourceTrans);\n        Eigen::Map<const Eigen::Matrix<T, 3, 1>> targetTrans(_pTargetTrans);\n        Eigen::Map<const Eigen::Quaternion<T>> sourceQuat(_pSourceQuat);\n        Eigen::Map<const Eigen::Quaternion<T>> targetQuat(_pTargetQuat);\n        Eigen::Map<Eigen::Matrix<T, 6, 1>> residual(_pResidual);\n\n        Eigen::Quaternion<T> targetQuatInv = targetQuat.conjugate();\n\n        Eigen::Quaternion<T> relativeQuat    = targetQuatInv * sourceQuat;\n        Eigen::Matrix<T, 3, 1> relativeTrans = targetQuatInv * (targetTrans - sourceTrans);\n\n        //! Definition should actually be relativeQuat * poseMeasurement.r.conjugate()\n        Eigen::Quaternion<T> deltaRot =\n            poseMeasurement.r.template cast<T>() * relativeQuat.conjugate();\n\n        residual.template block<3, 1>(0, 0) = relativeTrans - poseMeasurement.t.template cast<T>();\n        residual.template block<3, 1>(3, 0) = T(2.0) * deltaRot.vec();\n\n        residual.applyOnTheLeft(sqrtInfo.template cast<T>());\n\n        return true;\n    }\n\n    static ceres::CostFunction* create(const Pose3d& _poseMeasurement,\n                                       const Matx66f& _sqrtInformation)\n    {\n        return new ceres::AutoDiffCostFunction<Pose3dErrorFunctor, 6, 3, 4, 3, 4>(\n            new Pose3dErrorFunctor(_poseMeasurement, _sqrtInformation));\n    }\n\n   private:\n    const Pose3d poseMeasurement;\n    Eigen::Matrix<double, 6, 6> sqrtInfo;\n};\n#endif\n\n}  // namespace Optimizer\n\n}  // namespace kinfu\n}  // namespace cv\n#endif /* ifndef OPENCV_RGBD_GRAPH_NODE_H */\n", "meta": {"hexsha": "e8b7c34c53b5942c52ab3d534f20eda351bdc0fe", "size": 9005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/rgbd/src/pose_graph.hpp", "max_stars_repo_name": "Trevol/opencv_contrib", "max_stars_repo_head_hexsha": "1803962b3be42ab69ea927c9362b63f1b4abc8fd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2021-01-07T11:58:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T11:35:25.000Z", "max_issues_repo_path": "modules/rgbd/src/pose_graph.hpp", "max_issues_repo_name": "Trevol/opencv_contrib", "max_issues_repo_head_hexsha": "1803962b3be42ab69ea927c9362b63f1b4abc8fd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-31T00:55:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-31T00:55:15.000Z", "max_forks_repo_path": "modules/rgbd/src/pose_graph.hpp", "max_forks_repo_name": "Trevol/opencv_contrib", "max_forks_repo_head_hexsha": "1803962b3be42ab69ea927c9362b63f1b4abc8fd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-12-14T09:13:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T07:03:53.000Z", "avg_line_length": 27.9658385093, "max_line_length": 99, "alphanum_fraction": 0.6007773459, "num_tokens": 2531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5784409350942934}}
{"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": "#include <vector>\n#include <iostream>\n#include <boost/gil/extension/numeric/kernel.hpp>\n#include <boost/gil/extension/numeric/convolve.hpp>\n#include <boost/gil/extension/io/png.hpp>\n\n#include <boost/gil/extension/io/jpeg.hpp>\nusing namespace boost::gil;\nusing namespace std;\nint main()\n{\n    //gray8_image_t img;\n    //read_image(\"test_adaptive.png\", img, png_tag{});\n    //gray8_image_t img_out(img.dimensions());\n\n    gray8_image_t img;\n    read_image(\"src_view.png\", img, png_tag{});\n    gray8_image_t img_out(img.dimensions()), img_out1(img.dimensions());\n\n    std::vector<float> v(9, 1.0f / 9.0f);\n    detail::kernel_2d<float> kernel(v.begin(), v.size(), 1, 1);\n    detail::convolve_2d(view(img), kernel, view(img_out1));\n\n    //write_view(\"out-convolve2d.png\", view(img_out), png_tag{});\n    write_view(\"out-convolve2d.png\", view(img_out1), jpeg_tag{});\n\n\n    //------------------------------------//\n    std::vector<float> v1(3, 1.0f / 3.0f);\n    kernel_1d<float> kernel1(v1.begin(), v1.size(), 1);\n\n    detail::convolve_1d<gray32f_pixel_t>(const_view(img), kernel1, view(img_out), boundary_option::extend_zero);\n    write_view(\"out-convolve_option_extend_zero.png\", view(img_out), png_tag{});\n\n    if (equal_pixels(view(img_out1), view(img_out)))cout << \"convolve_option_extend_zero\" << endl;\n\n    cout << \"done\\n\";\n    cin.get();\n\n    return 0;\n}\n", "meta": {"hexsha": "338f49a3abf0331f086755716fa12b883676295b", "size": 1356, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/convolve2d.cpp", "max_stars_repo_name": "NEDJIMAbelgacem/gil", "max_stars_repo_head_hexsha": "8ea3644825d4b2dcabda6d4ce6281d4882f45c61", "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": "3rdparty/boost_1_73_0/libs/gil/example/convolve2d.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/gil/example/convolve2d.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 32.2857142857, "max_line_length": 112, "alphanum_fraction": 0.6651917404, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5784356884702904}}
{"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": "#pragma once\n\n#include <math/Vec.hpp>\n#include <boost/range.hpp>\n\ntemplate <class T>\nstruct Rectangle {\n\tRectangle() : top_(0), left_(0), bottom_(0), right_(0) { }\n\n\tRectangle(T const & top, T const & left,\n\t\tT const & bottom, T const & right)\n\t:\n\t\ttop_(top), left_(left),\n\t\tbottom_(bottom), right_(right)\n\t{ }\n\t\n\tT const & get_top() const { return top_; }\n\tvoid set_top(T const & top) { top_ = top; }\n\n\tT const & get_left() const { return left_; }\n\tvoid set_left(T const & left) { left_ = left; }\n\n\tT const & get_bottom() const { return bottom_; }\n\tvoid set_bottom() { return bottom_; }\n\n\tT const & get_right() const { return right_; }\n\tvoid set_right(T const & right) { right_ = right; }\n\n\ttemplate <class U>\n\tbool contains(U const & x, U const & y) const {\n\t\treturn left_ <= x && x < right_\n\t\t\t&& bottom_ <= y && y < top_;\n\t}\n\n\ttemplate <class U>\n\tbool contains(Vec<2, U> const & v) const {\n\t\treturn contains(v.x(), v.y());\n\t}\n\n\ttemplate <class stream>\n\tfriend stream & operator << (stream & out, Rectangle<T> const & rect) {\n\t\treturn out << \"Rect(\"\n\t\t\t<< rect.top_ << \", \"\n\t\t\t<< rect.left_ << \", \"\n\t\t\t<< rect.bottom_ << \", \"\n\t\t\t<< rect.right_ << \")\";\n\t}\n\n\tprivate:\n\t\tT top_, left_, bottom_, right_;\n};\n\ntemplate <class Iterator>\ninline Rectangle<float> get_bounding_rectangle(Iterator begin, Iterator end) {\n\tVec2 lower_left = *begin, upper_right = *begin;\n\t++begin;\n\n\tfor (; begin != end; ++begin) {\n\t\tlower_left = min(lower_left, *begin);\n\t\tupper_right = max(upper_right, *begin);\n\t}\n\n\treturn Rectangle<float>(upper_right.y(), lower_left.x(),\n\t\tlower_left.y(), upper_right.x());\n}\n\ntemplate <class Container>\ninline Rectangle<float> get_bounding_rectangle(Container const & c) {\n\treturn get_bounding_rectangle(boost::begin(c), boost::end(c));\n}\n\ntemplate <class Iterator, class F>\ninline Rectangle<float> get_bounding_rectangle(Iterator begin, Iterator end, F const & f) {\n\tVec2 lower_left = f(*begin), upper_right = f(*begin);\n\t++begin;\n\n\tfor (; begin != end; ++begin) {\n\t\tlower_left = min(lower_left, f(*begin));\n\t\tupper_right = max(upper_right, f(*begin));\n\t}\n\n\treturn Rectangle<float>(upper_right.y(), lower_left.x(),\n\t\tlower_left.y(), upper_right.x());\n}\n", "meta": {"hexsha": "6fdb413cd9a6ae4ce90d800a4d170c1700c09f8e", "size": 2166, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math/Rectangle.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/Rectangle.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/Rectangle.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.4823529412, "max_line_length": 91, "alphanum_fraction": 0.6505078486, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5784356765752575}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2011-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\r\n#include <geometry_test_common.hpp>\r\n\r\n#include <boost/geometry/strategies/cartesian/side_of_intersection.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/segment.hpp>\r\n\r\n\r\nnamespace bg = boost::geometry;\r\n\r\nint test_main(int, char* [])\r\n{\r\n    typedef bg::model::d2::point_xy<int> point;\r\n    typedef bg::model::segment<point> segment;\r\n\r\n    segment a(point(20, 10), point(10, 20));\r\n\r\n    segment b1(point(11, 16), point(20, 14));  // IP with a: (14.857, 15.143)\r\n    segment b2(point(10, 16), point(20, 14));  // IP with a: (15, 15)\r\n\r\n    segment c1(point(15, 16), point(13, 8));\r\n    segment c2(point(15, 16), point(14, 8));\r\n    segment c3(point(15, 16), point(15, 8));\r\n\r\n    typedef bg::strategy::side::side_of_intersection side;\r\n\r\n    BOOST_CHECK_EQUAL( 1, side::apply(a, b1, c1));\r\n    BOOST_CHECK_EQUAL(-1, side::apply(a, b1, c2));\r\n    BOOST_CHECK_EQUAL(-1, side::apply(a, b1, c3));\r\n\r\n    BOOST_CHECK_EQUAL( 1, side::apply(a, b2, c1));\r\n    BOOST_CHECK_EQUAL( 1, side::apply(a, b2, c2));\r\n    BOOST_CHECK_EQUAL( 0, side::apply(a, b2, c3));\r\n\r\n    // Check internal calculation-method:\r\n    BOOST_CHECK_EQUAL(-1400, side::side_value<int>(a, b1, c2));\r\n    BOOST_CHECK_EQUAL( 2800, side::side_value<int>(a, b1, c1));\r\n\r\n    BOOST_CHECK_EQUAL (2800, side::side_value<int>(a, b1, c1));\r\n    BOOST_CHECK_EQUAL(-1400, side::side_value<int>(a, b1, c2));\r\n    BOOST_CHECK_EQUAL(-5600, side::side_value<int>(a, b1, c3));\r\n\r\n    BOOST_CHECK_EQUAL(12800, side::side_value<int>(a, b2, c1));\r\n    BOOST_CHECK_EQUAL( 6400, side::side_value<int>(a, b2, c2));\r\n    BOOST_CHECK_EQUAL(    0, side::side_value<int>(a, b2, c3));\r\n\r\n    // TODO: we might add a check calculating the IP, determining the side\r\n    // with the normal side strategy, and verify the results are equal\r\n\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "5238de9bef8d64693d5aaf9239c84ef3b5eadad6", "size": 2180, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/strategies/side_of_intersection.cpp", "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": "libs/geometry/test/strategies/side_of_intersection.cpp", "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": "libs/geometry/test/strategies/side_of_intersection.cpp", "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": 35.1612903226, "max_line_length": 80, "alphanum_fraction": 0.6582568807, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5784356765752574}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/matrix/infinity_norm.hpp>\n#include <fcppt/math/matrix/row.hpp>\n#include <fcppt/math/matrix/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(infinity_norm)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tint,\n\t\t3,\n\t\t3\n\t>\n\tmatrix_type;\n\n\tmatrix_type const t(\n\t\tfcppt::math::matrix::row(\n\t\t\t3, 5, 7\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t2, 6, 4\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t0, 2, 8\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::matrix::infinity_norm(\n\t\t\tt\n\t\t),\n\t\t15\n\t);\n}\n", "meta": {"hexsha": "d153a038472b355cb94ada0e83c3821b2bb1cb03", "size": 1048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/matrix/infinity_norm.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/matrix/infinity_norm.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/matrix/infinity_norm.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1538461538, "max_line_length": 61, "alphanum_fraction": 0.7108778626, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5784356738471058}}
{"text": "/*\n * Copyright 2016 Maikel Nadolski\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 \"hidden-markov-models.t.h\"\n\n#include \"maikel/hmm/stochastical_conditions.h\"\n\n#include <fstream>\n#include <Eigen/Dense>\n\nnamespace {\n\nCASE( \"Read array data in 'array.dat' and its same as hard coded.\" )\n{\n  std::ifstream datafile(\"array.dat\");\n  EXPECT(datafile);\n  Eigen::ArrayXf array_hardcoded(3);\n  array_hardcoded << 0.3, 0.3, 0.4;\n  Eigen::ArrayXf array_from_file(3);\n  std::copy(std::istream_iterator<float>(datafile),\n            std::istream_iterator<float>(),\n            array_from_file.data());\n  EXPECT(array_hardcoded.size() == array_from_file.size());\n  for (int i = 0; i < array_from_file.size(); ++i)\n    EXPECT(array_from_file(i) == array_hardcoded(i));\n}\n\nCASE( \"is stochastic or not\" )\n{\n  Eigen::ArrayXf array(3);\n  array << 0.5, 0.2, 0.3;\n  EXPECT(maikel::hmm::is_probability_array(array));\n}\n\nCASE( \"is stochastic matrix \")\n{\n  Eigen::MatrixXf matrix(2,2);\n  matrix << 0.3, 0.7,\n            0.5, 0.5;\n  EXPECT(maikel::hmm::rows_are_probability_arrays(matrix));\n}\n\n}\n", "meta": {"hexsha": "cabcb6eee2da404b3dc7ce1d466d533012d0f79a", "size": 1595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/arrays.t.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": "tests/arrays.t.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": "tests/arrays.t.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": 27.9824561404, "max_line_length": 75, "alphanum_fraction": 0.6921630094, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5784356738471057}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2014 Adam Wulkiewicz, Lodz, Poland.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[boost_polygon_point\n//`Shows how to use Boost.Polygon point_data within Boost.Geometry\n\n#include <iostream>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/adapted/boost_polygon.hpp>\n\nint main()\n{\n    boost::polygon::point_data<int> a(1, 2), b(3, 4);\n    std::cout << \"Distance (using Boost.Geometry): \"\n        << boost::geometry::distance(a, b) << std::endl;\n    std::cout << \"Distance (using Boost.Polygon): \"\n        << boost::polygon::euclidean_distance(a, b) << std::endl;\n\n    return 0;\n}\n\n//]\n\n//[boost_polygon_point_output\n/*`\nOutput:\n[pre\nDistance (using Boost.Geometry): 2.82843\nDistance (using Boost.Polygon): 2.82843\n]\n*/\n//]\n", "meta": {"hexsha": "0f71f3f7972d0001b424448c1636c6977cb71eff", "size": 1049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/geometries/adapted/boost_polygon_point.cpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/geometries/adapted/boost_polygon_point.cpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/geometries/adapted/boost_polygon_point.cpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 26.225, "max_line_length": 79, "alphanum_fraction": 0.6987607245, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5784356719918166}}
{"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": "#ifndef MATHTOOLBOX_CLASSICAL_MDS_HPP\n#define MATHTOOLBOX_CLASSICAL_MDS_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\nnamespace mathtoolbox\n{\n    /// \\brief This function computes low-dimensional embedding by using classical multi-dimensional scaling (MDS)\n    /// \\param D Distance (dissimilarity) matrix and a target dimension for embedding\n    /// \\param dim Target dimension\n    /// \\return Coordinate matrix whose i-th column corresponds to the embedded coordinates of the i-th entry\n    Eigen::MatrixXd ComputeClassicalMds(const Eigen::MatrixXd& D, unsigned dim);\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_CLASSICAL_MDS_HPP\n", "meta": {"hexsha": "ea863667c801f5325823e65945a2b6e765000115", "size": 649, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/classical-mds.hpp", "max_stars_repo_name": "amazing89/mathtoolbox", "max_stars_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-01T03:39:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-01T03:39:24.000Z", "max_issues_repo_path": "include/mathtoolbox/classical-mds.hpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mathtoolbox/classical-mds.hpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1764705882, "max_line_length": 114, "alphanum_fraction": 0.7796610169, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.5783580210364082}}
{"text": "/*\n * @file\n * @author University of Warwick\n * @version 1.0\n *\n * @section LICENSE\n *\n * @section DESCRIPTION\n *\n */\n\n#define BOOST_TEST_MODULE EuclideanPlane3D\n#include <boost/test/unit_test.hpp>\n#include <boost/test/output_test_stream.hpp>\n#include <stdexcept>\n\n#include \"EuclideanPlane3D.h\"\n#include \"Error.h\"\n\nnamespace utf = boost::unit_test;\nnamespace euc = cupcfd::geometry::euclidean;\n\n// === Constructor ===\n// Test 1: Test the correct values are setup by the constructor\nBOOST_AUTO_TEST_CASE(constructor_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\t// Check Points have been copied\n\tBOOST_CHECK_EQUAL(plane.p1.cmp[0], p1.cmp[0]);\n\tBOOST_CHECK_EQUAL(plane.p1.cmp[1], p1.cmp[1]);\n\tBOOST_CHECK_EQUAL(plane.p1.cmp[2], p1.cmp[2]);\n\n\tBOOST_CHECK_EQUAL(plane.p2.cmp[0], p2.cmp[0]);\n\tBOOST_CHECK_EQUAL(plane.p2.cmp[1], p2.cmp[1]);\n\tBOOST_CHECK_EQUAL(plane.p2.cmp[2], p2.cmp[2]);\n\n\tBOOST_CHECK_EQUAL(plane.p3.cmp[0], p3.cmp[0]);\n\tBOOST_CHECK_EQUAL(plane.p3.cmp[1], p3.cmp[1]);\n\tBOOST_CHECK_EQUAL(plane.p3.cmp[2], p3.cmp[2]);\n\n\t// Check Plane Equation (These are the Non GCD Versions)\n\tBOOST_TEST(plane.a == 432.25);\n\tBOOST_TEST(plane.b == -228.15);\n\tBOOST_TEST(plane.c == -130.0999);\n\tBOOST_TEST(plane.d == 340.35);\n}\n\n// === operator = ===\n// Test 1: Check copy works successfully\nBOOST_AUTO_TEST_CASE(operator_single_equals_test1, * utf::tolerance(0.00001))\n{\n\n}\n\n// === operator == ===\n// Test 1: Test that true is obtained when the stored values are the same\nBOOST_AUTO_TEST_CASE(operator_double_equals_test1, * utf::tolerance(0.00001))\n{\n\n}\n\n// Test 2: Test that false is obtained when p1 is different\nBOOST_AUTO_TEST_CASE(operator_double_equals_test2, * utf::tolerance(0.00001))\n{\n\n}\n\n// Test 3: Test that false is obtained when p2 is different\nBOOST_AUTO_TEST_CASE(operator_double_equals_test3, * utf::tolerance(0.00001))\n{\n\n}\n\n// Test 4: Test that false is obtained when p3 is different\nBOOST_AUTO_TEST_CASE(operator_double_equals_test4, * utf::tolerance(0.00001))\n{\n\n}\n\n// === operator != ===\n// Test 1: Test that false is obtained when the stored values are the same\nBOOST_AUTO_TEST_CASE(operator_double_notequals_test1, * utf::tolerance(0.00001))\n{\n\n}\n\n// Test 2: Test that true is obtained when p1 is different and p2, p3 are the same\nBOOST_AUTO_TEST_CASE(operator_double_notequals_test2, * utf::tolerance(0.00001))\n{\n\n}\n\n// Test 3: Test that true is obtained when p2 is different and p1, p3 are the same\nBOOST_AUTO_TEST_CASE(operator_double_notequals_test3, * utf::tolerance(0.00001))\n{\n\n}\n\n// Test 4: Test that true is obtained when p3 is different and p1, p2 are the same\nBOOST_AUTO_TEST_CASE(operator_double_notequals_test4, * utf::tolerance(0.00001))\n{\n\n}\n\n// === operator < ===\n// ToDo\nBOOST_AUTO_TEST_CASE(operator_less_than_test1, * utf::tolerance(0.00001))\n{\n\n}\n\n// === operator <= ===\n// ToDo\nBOOST_AUTO_TEST_CASE(operator_less_than_or_equals_test1, * utf::tolerance(0.00001))\n{\n\n}\n\n// === operator > ===\n// ToDo\nBOOST_AUTO_TEST_CASE(operator_greater_than_test1, * utf::tolerance(0.00001))\n{\n\n}\n\n// === operator >= ===\n// ToDo\nBOOST_AUTO_TEST_CASE(operator_greater_than_or_equals_test1, * utf::tolerance(0.00001))\n{\n\n}\n\n// === getNormal ===\n// Test 1: Get the correct normal from a plane object\n// ToDo\nBOOST_AUTO_TEST_CASE(getNormal_test1, * utf::tolerance(0.00001))\n{\n\n}\n\n// === normal ===\n// Test 1: Test correct normal\nBOOST_AUTO_TEST_CASE(normal_test2, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanVector3D<double> norm;\n\n\tnorm = euc::EuclideanPlane3D<double>::calculateNormal(p1, p2, p3);\n\n\t// Wolfram Alpha gives these, but these are the GCD version\n\t//BOOST_TEST(norm.x == 0.854612);\n\t//BOOST_TEST(norm.y == -0.451081);\n\t//BOOST_TEST(norm.z == -0.257224);\n\n\tBOOST_TEST(norm.cmp[0] == 432.25);\n\tBOOST_TEST(norm.cmp[1] == -228.15);\n\tBOOST_TEST(norm.cmp[2] == -130.0999);\n}\n\n// === computeScalarPlaneEquation ===\n// Test 1: Test correct equation is calculated\nBOOST_AUTO_TEST_CASE(computeScalarPlaneEquation_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\tdouble a, b, c, d;\n\n\tplane.computeScalarPlaneEquation(&a, &b, &c, &d);\n\n\t// Wolfram Alpha gives these, but these are the GCD version - factor ~ -131\n\t//BOOST_TEST(a == -3.32244);\n\t//BOOST_TEST(b == 1.75365);\n\t//BOOST_TEST(c == 1.0);\n\t//BOOST_TEST(d == -2.61606);\n\n\tBOOST_TEST(a == 432.25);\n\tBOOST_TEST(b == -228.15);\n\tBOOST_TEST(c == -130.0999);\n\tBOOST_TEST(d == 340.35);\n}\n\n// === isPointOnPlane ===\n// Test 1: Test true is returned when the point lies on the plane - Test point p1\nBOOST_AUTO_TEST_CASE(isPointOnPlane_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\tbool check = plane.isPointOnPlane(p1);\n\tBOOST_CHECK_EQUAL(check, true);\n}\n\n// Test 2: Test true is returned when the point lies on the plane - Test point p2\nBOOST_AUTO_TEST_CASE(isPointOnPlane_test2, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\tbool check = plane.isPointOnPlane(p2);\n\tBOOST_CHECK_EQUAL(check, true);\n}\n\n// Test 3: Test true is returned when the point lies on the plane - Test point p3\nBOOST_AUTO_TEST_CASE(isPointOnPlane_test3, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\tbool check = plane.isPointOnPlane(p3);\n\tBOOST_CHECK_EQUAL(check, true);\n}\n\n// Test 4: Test true is returned when the point lies on the plane - Arbitrary point\nBOOST_AUTO_TEST_CASE(isPointOnPlane_test4, * utf::tolerance(0.00001))\n{\n\n}\n\n// Test 5: Test false is returned when the point does not lie on the plane\nBOOST_AUTO_TEST_CASE(isPointOnPlane_test5, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPoint<double,3> p4(-2000.0, -2000.0, -2000.0);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\tbool check = plane.isPointOnPlane(p4);\n\tBOOST_CHECK_EQUAL(check, false);\n}\n\n// === computeProjectedPoint ===\n// Test 1: Test the correct projection of a point that lies above a flat plane in the z-axis\nBOOST_AUTO_TEST_CASE(computeProjectedPoint_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.8, 4.0, 2.0);\n\teuc::EuclideanPoint<double,3> p2(21.7, 6.0, 2.0);\n\teuc::EuclideanPoint<double,3> p3(14.3, 1.0, 2.0);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\teuc::EuclideanPoint<double,3> testPoint(21.7, 6.0, 21.3);\n\n\teuc::EuclideanPoint<double,3> compare(21.7, 6.0, 2.0);\n\teuc::EuclideanPoint<double,3> result;\n\n\tresult = plane.computeProjectedPoint(testPoint);\n\n\tBOOST_TEST(compare.cmp[0] == result.cmp[0]);\n\tBOOST_TEST(compare.cmp[1] == result.cmp[1]);\n\tBOOST_TEST(compare.cmp[2] == result.cmp[2]);\n}\n\n// Test 2: Test the correct projection of a point that lies below a flat plane in the z-axis\nBOOST_AUTO_TEST_CASE(computeProjectedPoint_test2, * utf::tolerance(0.00001))\n{\n\n}\n\n// Test 3: Test the correct projection of a point that lies on a flat plane in the z-axis (i.e. should be same point)\nBOOST_AUTO_TEST_CASE(computeProjectedPoint_test3, * utf::tolerance(0.00001))\n{\n\n}\n\n// === isVectorParallel ===\n// Test 1: Test that a vector is correctly identified as being in parallel\nBOOST_AUTO_TEST_CASE(isVectorParallel_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\t// Vector from p1 to p2 should be in parallel\n\teuc::EuclideanVector<double,3> vec = p2 - p1;\n\tbool parallel = plane.isVectorParallel(vec);\n\tBOOST_CHECK_EQUAL(parallel, true);\n}\n\n// Test 2: Test that a vector is correctly identified as not being in parallel\nBOOST_AUTO_TEST_CASE(isVectorParallel_test2, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\t// Normal vector should not be in parallel by definition\n\teuc::EuclideanVector<double,3> vec(432.25, -228.15, -130.0999);\n\tbool parallel = plane.isVectorParallel(vec);\n\tBOOST_CHECK_EQUAL(parallel, false);\n}\n\n// === isVectorParallelInPlane ===\n// Test 1: Test true is returned when a parallel vector in the plane is detected\nBOOST_AUTO_TEST_CASE(isVectorParallelInPlane_test1, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\t// Generate a vector that is parallel to the plane\n\teuc::EuclideanVector<double,3> vec = p2 - p1;\n\n\t// Test and Check - Select a point on the plane with the parallel vector\n\tbool result = plane.isVectorParallelInPlane(vec, p1);\n\tBOOST_CHECK_EQUAL(result, true);\n}\n\n// Test 2: Test false is returned when a vector is parallel but does not lie on the plane\nBOOST_AUTO_TEST_CASE(isVectorParallelInPlane_test2, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPoint<double,3> origin(0.0, 0.0, 0.0);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\t// Generate a vector that is parallel to the plane\n\teuc::EuclideanVector<double,3> vec = p2 - p1;\n\n\t// Test and Check - Select a point on the plane with the parallel vector\n\tbool result = plane.isVectorParallelInPlane(vec, origin);\n\tBOOST_CHECK_EQUAL(result, false);\n}\n\n// Test 3: Test false is returned when a vector is not parallel\nBOOST_AUTO_TEST_CASE(isVectorParallelInPlane_test3, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\t// Generate a vector that is parallel to the plane\n\teuc::EuclideanVector<double,3> vec(0.0, 0.0, 4.0);\n\n\t// Test and Check - Select a point on the plane with the parallel vector\n\tbool result = plane.isVectorParallelInPlane(vec, p1);\n\tBOOST_CHECK_EQUAL(result, false);\n}\n\n// === linePlaneIntersection  ===\n// Test 1: Find intersection of non-parallel vector with plane\nBOOST_AUTO_TEST_CASE(linePlaneIntersection_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> p2(1.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> p3(0.0, 1.0, 0.0);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\teuc::EuclideanVector<double,3> vec(1.0, 1.0, -1.0);\n\teuc::EuclideanPoint<double,3> origin(2.0, 5.0, 1.0);\n\n\teuc::EuclideanPoint<double,3> result;\n\tcupcfd::error::eCodes status = plane.linePlaneIntersection(vec, origin, result);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(result.cmp[0], 3.0);\n\tBOOST_CHECK_EQUAL(result.cmp[1], 6.0);\n\tBOOST_CHECK_EQUAL(result.cmp[2], 0.0);\n}\n\n// Test 2: Error code when vector is parallel in plane\nBOOST_AUTO_TEST_CASE(linePlaneIntersection_test2, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\teuc::EuclideanVector<double,3> parallelVec = p2-p1;\n\teuc::EuclideanPoint<double,3> result;\n\n\tcupcfd::error::eCodes status = plane.linePlaneIntersection(parallelVec, p1, result);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_EUC_VEC_PARALLEL);\n}\n\n// Test 3: Error code when vector is parallel but not in plane\nBOOST_AUTO_TEST_CASE(linePlaneIntersection_test3, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\teuc::EuclideanVector<double,3> parallelVec = p2-p1;\n\teuc::EuclideanPoint<double,3> l0(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double,3> result;\n\n\tcupcfd::error::eCodes status = plane.linePlaneIntersection(parallelVec, l0, result);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_EUC_VEC_PARALLEL);\n}\n\n// === shortestDistance ===\n// Test 1: Correctly compute the distance to a point from the plane where both are on the positive side of the origin\nBOOST_AUTO_TEST_CASE(shortestDistance_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\teuc::EuclideanPoint<double,3> point(15.3,8.9, 43.5);\n\n\tdouble distance = plane.shortestDistance(point);\n\n\tBOOST_TEST(distance == 1.45538);\n}\n\n// Test 2: Correctly compute the distance to a point from the plane where the planes are on different sides of the origin\nBOOST_AUTO_TEST_CASE(shortestDistance_test2, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\teuc::EuclideanPoint<double,3> point(201.7,165.3,198.4);\n\n\tdouble distance = plane.shortestDistance(point);\n\n\tBOOST_TEST(distance == 47.4512);\n}\n\n// Test 3: Correctly compute the distance to a point on the plane\nBOOST_AUTO_TEST_CASE(shortestDistance_test3, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double,3> p1(2.0, 3.0, 4.0);\n\teuc::EuclideanPoint<double,3> p2(18.6, 17.4, 33.9);\n\teuc::EuclideanPoint<double,3> p3(15.3, 6.7, 41.7);\n\teuc::EuclideanPlane3D<double> plane(p1, p2, p3);\n\n\teuc::EuclideanPoint<double,3> point(18.6, 17.4, 33.9);\n\n\tdouble distance = plane.shortestDistance(point);\n\n\tBOOST_TEST(distance == 0.0);\n}\n", "meta": {"hexsha": "7423cde427e059c9513636ec9b7c3a2554130187", "size": 14792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/geometry/euclidean/implementation/component/EuclideanPlane3DTests.cpp", "max_stars_repo_name": "thorbenlouw/CUP-CFD", "max_stars_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T10:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T14:43:19.000Z", "max_issues_repo_path": "tests/geometry/euclidean/implementation/component/EuclideanPlane3DTests.cpp", "max_issues_repo_name": "thorbenlouw/CUP-CFD", "max_issues_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T15:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T14:27:28.000Z", "max_forks_repo_path": "tests/geometry/euclidean/implementation/component/EuclideanPlane3DTests.cpp", "max_forks_repo_name": "thorbenlouw/CUP-CFD", "max_forks_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T15:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T15:24:24.000Z", "avg_line_length": 32.4385964912, "max_line_length": 121, "alphanum_fraction": 0.7157247161, "num_tokens": 5129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.5783580164678095}}
{"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": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[assign_2d_point\n//` Shows the usage of assign to set point coordinates\n\n#include <iostream>\n#include <iomanip>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\nint main()\n{\n    using boost::geometry::assign_values;\n\n\n    boost::geometry::model::d2::point_xy<double> p1;\n    assign_values(p1, 1.2345, 2.3456);\n\n    std::cout\n        << std::setprecision(20)\n        << boost::geometry::dsv(p1) << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[assign_2d_point_output\n/*`\nOutput:\n[pre\n(1.2344999999999999, 2.3456000000000001)\n(1.2345, 2.3456)\n]\n*/\n//]\n", "meta": {"hexsha": "f5604625e187cbbed566e4524948524202f26bf5", "size": 913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/assign_2d_point.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "doc/src/examples/algorithms/assign_2d_point.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/geometry/doc/src/examples/algorithms/assign_2d_point.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 19.847826087, "max_line_length": 79, "alphanum_fraction": 0.6944140197, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.5781780986883718}}
{"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": "// Copyright 2011-2012 Renato Tegon Forti\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// -----------------------------------------------------------------------------\n// This example shows how implement a work quee (thread pool) to work with\n// Boost.Application using Boost.Asio.\n//\n// The result will be printed on CTRL-C (Stop) signal\n// -----------------------------------------------------------------------------\n\n#include <boost/application.hpp>\n#include <boost/timer/timer.hpp>\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <utility>\n#include <vector>\n#include <functional>\n#include <mutex>\n\n#include \"work_queue.hpp\"\n\nusing namespace boost;\n\nusing matrix_type = std::vector<std::vector<double>>;\n\n// worker class that calculate gaussian blur\n// http://en.wikipedia.org/wiki/Gaussian_blur\ntemplate< int kernelRadius = 3>\nstruct gaussian_blur\n{\n   using callback = std::function<void(const matrix_type&)>;\n\n   explicit gaussian_blur(callback cb)\n      : callback_(std::move(cb))\n   {\n   }\n\n   void operator()()\n   {\n      boost::timer::cpu_timer timer;\n\n      kernel2d_ = produce_gaussian_kernel(kernelRadius);\n\n      boost::timer::cpu_times const elapsed_times(timer.elapsed());\n\n      std::cout\n         << \"gaussian_blur takes:\"\n         <<  format(elapsed_times, 9)\n         << \", for size: \"\n         << kernelRadius\n         << std::endl;\n\n      callback_(kernel2d_);\n   }\n\nprotected:\n\n   double gaussian(double x, double mu, double sigma)\n   {\n      return exp(-(((x-mu)/(sigma))*((x-mu)/(sigma)))/2.0);\n   }\n\n   matrix_type produce_gaussian_kernel(int internalKernelRadius)\n   {\n      // get kernel matrix\n      matrix_type kernel2d(2*internalKernelRadius+1, std::vector<double>(2*internalKernelRadius+1));\n\n      // determine sigma\n      double sigma = internalKernelRadius/2.;\n\n      // fill values\n      double sum = 0;\n      for (std::size_t row = 0; row < kernel2d.size(); row++)\n      {\n         for (std::size_t col = 0; col < kernel2d[row].size(); col++)\n         {\n            kernel2d[row][col] = gaussian(row, internalKernelRadius, sigma) * gaussian(col, internalKernelRadius, sigma);\n            sum += kernel2d[row][col];\n         }\n      }\n\n      // normalize kernel, or the image becomes dark\n      for (auto & row : kernel2d)\n         for (double & col : row)\n            col /= sum;\n\n      return kernel2d;\n   }\n\nprivate:\n\n   callback callback_;\n   matrix_type kernel2d_;\n};\n\n// application class\nclass myapp : work_queue<0>\n{\npublic:\n\n   explicit myapp(application::context& context)\n      : task_count_(0), context_(context)\n   {\n   }\n\n   void add_result(const matrix_type& kernel2d)\n   {\n      std::lock_guard<std::mutex> lock(mutex_);\n\n      task_count_++;\n\n      result_.push_back(kernel2d);\n\n      if(task_count_== 3)\n      {\n         std::cout << \"all tasks are completed, waiting ctrl-c to display the results...\" << std::endl;\n      }\n   }\n\n   int operator()()\n   {\n      // your application logic here!\n      task_count_ = 0;\n\n      //our tasks\n      add_task(gaussian_blur<3>([this](const matrix_type& kernel2d) { add_result(kernel2d); }));\n      add_task(gaussian_blur<6>([this](const matrix_type& kernel2d) { add_result(kernel2d); }));\n      add_task(gaussian_blur<9>([this](const matrix_type& kernel2d) { add_result(kernel2d); }));\n\n      context_.find<application::wait_for_termination_request>()->wait();\n\n      return 0;\n   }\n\n   bool stop()\n   {\n      std::cout << \"Result...\" << std::endl;\n\n      for(std::size_t i = 0; i < result_.size(); ++i)\n      {\n         std::cout << i << \" : -----------------------\" << std::endl;\n\n         auto& kernel2d = result_[i];\n\n         for (auto & row : kernel2d) {\n            for (double col : row) {\n               std::cout << std::setprecision(5) << std::fixed << col << \" \";\n            }\n            std::cout << std::endl;\n         }\n      }\n\n      return true;\n   }\n\nprivate:\n\n   std::mutex mutex_;\n   std::vector<std::vector<std::vector<double>>> result_;\n\n   int task_count_;\n\n   application::context& context_;\n}; // myapp\n\nint main(int /*argc*/, char */*argv*/[])\n{\n   application::context app_context;\n   myapp app(app_context);\n\n   application::handler<>::callback cb = [&app] { return app.stop(); };\n\n   app_context.insert<application::termination_handler>(\n      std::make_shared<application::termination_handler_default_behaviour>(cb));\n\n   return application::launch<application::common>(app, app_context);\n}\n", "meta": {"hexsha": "1ef8629acae973e09b30d7a2b56a3fa4b3e0e58c", "size": 4548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/work_queue/work_queue.cpp", "max_stars_repo_name": "mlegenovic/Boost.Application", "max_stars_repo_head_hexsha": "e69d4926027274dadb7d89c45964ddafa1edd7f5", "max_stars_repo_licenses": ["BSL-1.0"], "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/work_queue/work_queue.cpp", "max_issues_repo_name": "mlegenovic/Boost.Application", "max_issues_repo_head_hexsha": "e69d4926027274dadb7d89c45964ddafa1edd7f5", "max_issues_repo_licenses": ["BSL-1.0"], "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/work_queue/work_queue.cpp", "max_forks_repo_name": "mlegenovic/Boost.Application", "max_forks_repo_head_hexsha": "e69d4926027274dadb7d89c45964ddafa1edd7f5", "max_forks_repo_licenses": ["BSL-1.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.989010989, "max_line_length": 121, "alphanum_fraction": 0.5949868074, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5781265106308434}}
{"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_GEOMETRY_VECTOR3D_HPP\r\n#define UTILITIES_GEOMETRY_VECTOR3D_HPP\r\n\r\n#include \"../UtilitiesAPI.hpp\"\r\n#include \"../data/Vector.hpp\"\r\n#include \"../core/Logger.hpp\"\r\n\r\n#include <vector>\r\n#include <boost/optional.hpp>\r\n\r\nnamespace openstudio{\r\n\r\n  class UTILITIES_API Vector3d{\r\n  public:\r\n\r\n    /// default constructor creates vector with 0, 0, 0\r\n    Vector3d();\r\n\r\n    /// constructor with x, y, z\r\n    Vector3d(double x, double y, double z);\r\n\r\n    /// copy constructor\r\n    Vector3d(const Vector3d& other);\r\n\r\n    /// get x\r\n    double x() const;\r\n\r\n    /// get y\r\n    double y() const;\r\n\r\n    /// get z\r\n    double z() const;\r\n\r\n    /// addition\r\n    Vector3d operator+(const Vector3d& other) const;\r\n\r\n    /// addition\r\n    Vector3d& operator+=(const Vector3d& other);\r\n\r\n    /// subtraction\r\n    Vector3d operator-(const Vector3d& other) const;\r\n\r\n    /// subtraction\r\n    Vector3d& operator-=(const Vector3d& other);\r\n\r\n    /// check equality\r\n    bool operator==(const Vector3d& other) const;\r\n\r\n    /// normalize to one\r\n    bool normalize();\r\n\r\n    /// get a vector which is the reverse of this\r\n    Vector3d reverseVector() const;\r\n\r\n    /// get length\r\n    double length() const;\r\n\r\n    /// set length\r\n    bool setLength(double newLength);\r\n\r\n    /// dot product with another Vector3d\r\n    double dot(const Vector3d& other) const;\r\n\r\n    /// cross product with another Vector3d\r\n    Vector3d cross(const Vector3d& other) const;\r\n\r\n    /// get the Vector directly\r\n    Vector vector() const;\r\n\r\n  private:\r\n\r\n    REGISTER_LOGGER(\"utilities.Vector3d\");\r\n\r\n    Vector m_storage;\r\n\r\n  };\r\n\r\n  /// ostream operator\r\n  UTILITIES_API std::ostream& operator<<(std::ostream& os, const Vector3d& vec);\r\n\r\n  /// ostream operator\r\n  UTILITIES_API std::ostream& operator<<(std::ostream& os, const std::vector<Vector3d>& vecVector);\r\n\r\n  /// negation\r\n  UTILITIES_API Vector3d operator-(const Vector3d& vec);\r\n\r\n  /// multiplication by a scalar\r\n  UTILITIES_API Vector3d operator*(double mult, const Vector3d& vec);\r\n\r\n  // optional Vector3d\r\n  typedef boost::optional<Vector3d> OptionalVector3d;\r\n\r\n  // vector of Vector3d\r\n  typedef std::vector<Vector3d> Vector3dVector;\r\n\r\n} // openstudio\r\n\r\n#endif //UTILITIES_GEOMETRY_VECTOR3D_HPP\r\n", "meta": {"hexsha": "9c956da25b4b75e189d238e96564559e4cf38c28", "size": 3247, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/geometry/Vector3d.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/geometry/Vector3d.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/geometry/Vector3d.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": 27.5169491525, "max_line_length": 100, "alphanum_fraction": 0.6418232214, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5781106912011136}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/integral_constant.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [zero]\nBOOST_HANA_CONSTANT_CHECK(zero<IntegralConstant<int>>() == int_<0>);\nBOOST_HANA_CONSTEXPR_CHECK(zero<long>() == 0l);\n//! [zero]\n\n}{\n\n//! [plus]\nBOOST_HANA_CONSTANT_CHECK(plus(int_<3>, int_<5>) == int_<8>);\nBOOST_HANA_CONSTEXPR_CHECK(plus(1, 2) == 3);\nBOOST_HANA_CONSTEXPR_CHECK(plus(1.5f, 2.4) == 3.9);\n//! [plus]\n\n}\n\n}\n", "meta": {"hexsha": "512b5f2ecc298a9c4ae97dda8af0c57386d7304c", "size": 631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/monoid.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/monoid.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/monoid.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.71875, "max_line_length": 78, "alphanum_fraction": 0.7036450079, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5781106764921989}}
{"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\u2019t 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": "#ifndef PARS_VIEWER_TRANSFORM_HPP\n#define PARS_VIEWER_TRANSFORM_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace pars\n{\nclass transform\n{\npublic:\n  explicit transform  ();\n  transform           (const transform&  that) = default;\n  transform           (      transform&& temp) = default;\n  virtual ~transform  ()                       = default;\n  transform& operator=(const transform&  that) = default;\n  transform& operator=(      transform&& temp) = default;\n\n  Eigen::Vector3f    translation       () const;\n  Eigen::Quaternionf rotation          () const;\n  Eigen::Vector3f    rotation_euler    () const;\n  Eigen::Vector3f    scale             () const;\n                              \n  Eigen::Vector3f    right             () const;\n  Eigen::Vector3f    up                () const;\n  Eigen::Vector3f    forward           () const;\n            \n  void               set_translation   (const Eigen::Vector3f   & translation);\n  void               set_rotation      (const Eigen::Quaternionf& rotation   );\n  void               set_rotation_euler(const Eigen::Vector3f   & rotation   );\n  void               set_scale         (const Eigen::Vector3f   & scale      );\n                                                                    \n  void               translate         (const Eigen::Vector3f   & value      );\n  void               rotate            (const Eigen::Quaternionf& value      , const bool postmultiply = false);\n  void               rotate_euler      (const Eigen::Vector3f   & value      , const bool postmultiply = false);\n  void               scale             (const Eigen::Vector3f   & value      );\n  void               look_at           (const Eigen::Vector3f   & forward    , const Eigen::Vector3f& up = Eigen::Vector3f(0.0f, 1.0f, 0.0f));\n  void               reset             ();\n            \nprotected: \n  Eigen::Vector3f    translation_;\n  Eigen::Quaternionf rotation_   ;\n  Eigen::Vector3f    scale_      ;\n};\n}\n\n#endif", "meta": {"hexsha": "ad4c7dae5f1ba4f91103a1bd3f26460c68004355", "size": 1968, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pars_viewer/include/pars_viewer/transform.hpp", "max_stars_repo_name": "acdemiralp/pars", "max_stars_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-12T18:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T12:04:14.000Z", "max_issues_repo_path": "pars_viewer/include/pars_viewer/transform.hpp", "max_issues_repo_name": "acdemiralp/pars", "max_issues_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pars_viewer/include/pars_viewer/transform.hpp", "max_forks_repo_name": "acdemiralp/pars", "max_forks_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-18T14:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T14:35:49.000Z", "avg_line_length": 41.8723404255, "max_line_length": 142, "alphanum_fraction": 0.5264227642, "num_tokens": 435, "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) 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": "#include <bits/stdc++.h>\n#include <alglib/graph/directed_graph.h>\n#include <alglib/graph/dfs.h>\n\nusing namespace std;\nusing namespace alglib::graph;\n\nint main() {\n    directed_graph<int> g;\n\n    vector<int> numbers = {2, 3, 5, 6, 7, 8, 10, 12};\n    \n    for(int nu : numbers)\n        g.add_vertex(nu);\n\n    // create an edge (a, b) if a | b for all pairs\n    for(int i = 0; i < numbers.size(); i++)\n        for(int j = i+1; j < numbers.size(); j++)\n            if(numbers[j] % numbers[i] == 0)\n                g.add_edge(numbers[i], numbers[j]);\n\n    vector<int> dfs;\n    preorder_dfs(g, back_inserter(dfs));\n\n    for(int no : dfs)\n        cout << no << \"\\t\";\n    cout << endl;\n}\n", "meta": {"hexsha": "0e48776ad937447af0dec0b5e8a51c22798222f3", "size": 680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/graph/dfs.cpp", "max_stars_repo_name": "divkakwani/alglib", "max_stars_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-26T13:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-02T12:30:03.000Z", "max_issues_repo_path": "test/graph/dfs.cpp", "max_issues_repo_name": "divkakwani/alglib", "max_issues_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/graph/dfs.cpp", "max_forks_repo_name": "divkakwani/alglib", "max_forks_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T14:07:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T10:30:28.000Z", "avg_line_length": 23.4482758621, "max_line_length": 53, "alphanum_fraction": 0.5514705882, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5781106713602062}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2003 Ferdinando Ametrano\nCopyright (C) 2007, 2008 Klaus Spanderen\nCopyright (C) 2007 Neil Firth\nCopyright (C) 2015 CompatibL\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef cl_adjoint_matrices_hpp\n#define cl_adjoint_matrices_hpp\n#pragma once\n\n#include <boost/test/unit_test.hpp>\n#include <ql/math/matrix.hpp>\n\nclass AdjointMatricesTest{\npublic:\n    static bool testInverse();\n    static bool testDeterminant();\n    static bool testSqrt();\n    static bool testPolynom();\n    static bool testEigenvectors();\n    //static bool testHighamSqrt();\n    //static bool testSVD();\n    //static bool testQRDecomposition();\n    //static bool testQRSolve();\n    static bool testOrthogonalProjection();\n    static boost::unit_test_framework::test_suite* suite();\n};\n\n#endif", "meta": {"hexsha": "c7d718863fcc56c3566bdbae50f1ebec07284e03", "size": 1489, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointmatricestest.hpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite-adjoint/adjointmatricestest.hpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite-adjoint/adjointmatricestest.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": 33.0888888889, "max_line_length": 79, "alphanum_fraction": 0.7521826729, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5781106649755918}}
{"text": "#pragma once\n\n#include <boost/mp11.hpp>\n\nnamespace xzr\n{\nnamespace utility\n{\nnamespace impl\n{\ntemplate <typename T,\n          T Begin,\n          T Steps,\n          bool Increase,\n          T Delta = T(1),\n          typename = boost::mp11::make_integer_sequence<T, Steps>>\nstruct generate_range;\n\ntemplate <typename T, T B, T S, T D, T... Ns>\nstruct generate_range<T, B, S, true, D, boost::mp11::integer_sequence<T, Ns...>>\n{\n    using type = boost::mp11::integer_sequence<T, B + D * Ns...>;\n};\n\ntemplate <typename T, T B, T S, T D, T... Ns>\nstruct generate_range<T, B, S, false, D, boost::mp11::integer_sequence<T, Ns...>>\n{\n    using type = boost::mp11::integer_sequence<T, B - D * Ns...>;\n};\n} // namespace impl\n\ntemplate <typename T, T N, T M>\nusing make_integer_range = typename impl::generate_range<T, N, (N <= M) ? (M - N) : (N - M), (N <= M)>::type;\n\n// see https://github.com/taocpp/sequences\ntemplate <std::size_t N, std::size_t M>\nusing make_index_range = make_integer_range<std::size_t, N, M>;\n} // namespace utility\n} // namespace xzr\n", "meta": {"hexsha": "9ff9b0f73fc460e0a56c4bd2724fb1d8a0085a69", "size": 1047, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/lib/utility.hpp", "max_stars_repo_name": "XzoRit/cpp_test_eq_op", "max_stars_repo_head_hexsha": "32abe7949499fd81bd82aefccc6b4ccf550f0628", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/lib/utility.hpp", "max_issues_repo_name": "XzoRit/cpp_test_eq_op", "max_issues_repo_head_hexsha": "32abe7949499fd81bd82aefccc6b4ccf550f0628", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/lib/utility.hpp", "max_forks_repo_name": "XzoRit/cpp_test_eq_op", "max_forks_repo_head_hexsha": "32abe7949499fd81bd82aefccc6b4ccf550f0628", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.175, "max_line_length": 109, "alphanum_fraction": 0.6313276027, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5780818880975175}}
{"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": "/* -*- 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 \"zabr.hpp\"\n#include \"utilities.hpp\"\n\n#include <boost/assign/list_of.hpp>\n\n#include <ql/termstructures/volatility/sabrsmilesection.hpp>\n#include <ql/experimental/volatility/zabrsmilesection.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\nvoid ZabrTest::testConsistency() {\n\n    Real tol = 1E-4;\n\n    Real alpha = 0.08;\n    Real beta = 0.70;\n    Real nu = 0.20;\n    Real rho = -0.30;\n    Real tau = 5.0;\n    Real forward = 0.03;\n\n    SabrSmileSection sabr(tau, forward,\n                          boost::assign::list_of(alpha)(beta)(nu)(rho));\n\n    ZabrSmileSection<ZabrShortMaturityLognormal> zabr0(\n        tau, forward, boost::assign::list_of(alpha)(beta)(nu)(rho)(1.0));\n\n    ZabrSmileSection<ZabrShortMaturityNormal> zabr1(\n        tau, forward, boost::assign::list_of(alpha)(beta)(nu)(rho)(1.0));\n\n    ZabrSmileSection<ZabrLocalVolatility> zabr2(\n        tau, forward, boost::assign::list_of(alpha)(beta)(nu)(rho)(1.0));\n\n    // for full finite prices reduce the number of intermediate points here\n    // below the recommended value to speed up the test\n    ZabrSmileSection<ZabrFullFd> zabr3(\n        tau, forward, boost::assign::list_of(alpha)(beta)(nu)(rho)(1.0),\n        std::vector<Real>(), 2);\n\n    Real k = 0.0001;\n    while (k <= 0.70) {\n        Real c0 = sabr.optionPrice(k);\n        Real z0 = zabr0.optionPrice(k);\n        Real z1 = zabr1.optionPrice(k);\n        Real z2 = zabr2.optionPrice(k);\n        Real z3 = zabr3.optionPrice(k);\n        if (std::fabs(z0 - c0) > tol)\n            BOOST_ERROR(\"Zabr short maturity lognormal expansion price \"\n                          \"(\"\n                          << z0 << \") deviates from Sabr Hagan 2002 price \"\n                                   \"by \" << (z0 - c0));\n        if (std::fabs(z1 - c0) > tol)\n            BOOST_ERROR(\"Zabr short maturity normal expansion price \"\n                          \"(\"\n                          << z1 << \") deviates from Sabr Hagan 2002 price \"\n                                   \"by \" << (z1 - c0));\n        if (std::fabs(z2 - c0) > tol)\n            BOOST_ERROR(\"Zabr local volatility price \"\n                          \"(\"\n                          << z2 << \") deviates from Sabr Hagan 2002 price \"\n                                   \"by \" << (z2 - c0));\n        if (std::fabs(z3 - c0) > tol)\n            BOOST_ERROR(\"Zabr full finite difference price \"\n                          \"(\"\n                          << z3 << \") deviates from Sabr Hagan 2002 price \"\n                                   \"by \" << (z3 - c0));\n        k += 0.0001;\n    }\n}\n\ntest_suite *ZabrTest::suite() {\n    test_suite *suite = BOOST_TEST_SUITE(\"NoArbSabrModel tests\");\n    suite->add(QUANTLIB_TEST_CASE(&ZabrTest::testConsistency));\n    return suite;\n}\n", "meta": {"hexsha": "148aa6415a37ee388415d72c6cab825df9155890", "size": 3557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/zabr.cpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite/zabr.cpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "test-suite/zabr.cpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 37.0520833333, "max_line_length": 79, "alphanum_fraction": 0.5906662918, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5780818761557542}}
{"text": "// 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/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"utils.hpp\"\n\nusing namespace boost::numeric::ublas;\n\nstatic const double TOL(1.0e-5); ///< Used for comparing two real numbers.\n\nBOOST_UBLAS_TEST_DEF ( test_double_scaled_norm_2 ) {\n    vector<double> v(2);\n    v[0] = 0; v[1] = 1.0e155;\n\n    const double expected = 1.0e155;\n\n    BOOST_UBLAS_DEBUG_TRACE( \"norm is \" << norm_2(v) );\n    BOOST_UBLAS_TEST_CHECK(std::abs(norm_2(v) - expected) < TOL);\n}\n\nBOOST_UBLAS_TEST_DEF ( test_float_scaled_norm_2 ) {\n    vector<float> v(2);\n    v[0] = 0; v[1] = 1.0e20;\n\n    const float expected = 1.0e20;\n\n    BOOST_UBLAS_DEBUG_TRACE( \"norm is \" << norm_2(v) );\n    BOOST_UBLAS_TEST_CHECK(std::abs(norm_2(v) - expected) < TOL);\n}\n\nint main() {\n    BOOST_UBLAS_TEST_BEGIN();\n\n    BOOST_UBLAS_TEST_DO( test_double_scaled_norm_2 );\n    BOOST_UBLAS_TEST_DO( test_float_scaled_norm_2 );\n\n    BOOST_UBLAS_TEST_END();\n}\n", "meta": {"hexsha": "74065048f419aad753d8b4615b1f4ccdff1cb35e", "size": 1097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/test/test_scaled_norm.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/ublas/test/test_scaled_norm.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/ublas/test/test_scaled_norm.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 26.119047619, "max_line_length": 74, "alphanum_fraction": 0.6973564266, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5780818753661716}}
{"text": "#include \"utils/data_generator.cpp\"\n#include \"../src/numerical/gauss-newton/gn_solver.h\"\n#include \"../src/logging/easylogging++.h\"\n#include <armadillo>\n\nusing arma::mat;\n\nINITIALIZE_EASYLOGGINGPP\n\nmat WEIGHTS = {100, -20, 50, -0.5};\n\narma::mat quadratic_model(arma::mat x, arma::mat L)\n{\n    return x * arma::pow(L, 2);\n}\n\nint main(int argc, char *argv[])\n{\n    el::Configurations conf(\"./logging-config.conf\");\n    el::Loggers::reconfigureLogger(\"default\", conf);\n\n    auto data_generator = DataGenerator();\n    auto L = data_generator.generate_library();\n    auto s = data_generator.generate_signal(WEIGHTS);\n    auto s_quadratic = data_generator.generate_signal(WEIGHTS, L, quadratic_model);\n\n    LOG(INFO) << \"True: \" << WEIGHTS;\n\n    GNSolver gn_solver = GNSolver(L);\n    arma::mat result1 = gn_solver.solve(s);\n    LOG(INFO) << \"GN fit: \" << result1;\n\n    GNSolver gn_solver_quadratic = GNSolver(L);\n    gn_solver_quadratic.set_model(quadratic_model);\n    arma::mat result2 = gn_solver_quadratic.solve(s_quadratic);\n    LOG(INFO) << \"GN quadratic fit: \" << result2;\n\n    return 0;\n}", "meta": {"hexsha": "ca836de0c5247f3e94186e359e1a6cd15cbbd1a3", "size": 1088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/gn_solver.cpp", "max_stars_repo_name": "omyllymaki/math", "max_stars_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T09:12:24.000Z", "max_issues_repo_path": "samples/gn_solver.cpp", "max_issues_repo_name": "omyllymaki/math", "max_issues_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "samples/gn_solver.cpp", "max_forks_repo_name": "omyllymaki/math", "max_forks_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8974358974, "max_line_length": 83, "alphanum_fraction": 0.6875, "num_tokens": 298, "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": "/*************************************************************************\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": "/*\n * Copyright 2020 \u00a9 Centre Interdisciplinaire de d\u00e9veloppement en Cartographie des Oc\u00e9ans (CIDCO), Tous droits r\u00e9serv\u00e9s\n */\n\n/* \n * File:   DependencyTest.hpp\n * Author: Jordan McManus\n */\n\n#ifndef DEPENDENCYTEST_HPP\n#define DEPENDENCYTEST_HPP\n\n#include \"catch.hpp\"\n#include \"opencv2/opencv.hpp\"\n#include <Eigen>\n\nTEST_CASE(\"Test Eigen\") {\n    Eigen::Vector3d v(1.0, 2.0, 3.0);\n    \n    double eps = 1e-9;\n    REQUIRE(std::abs(v(0) - 1.0) < eps);\n    REQUIRE(std::abs(v(1) - 2.0) < eps);\n    REQUIRE(std::abs(v(2) - 3.0) < eps);\n    \n}\n\nTEST_CASE(\"Test opencv\") {\n    \n    cv::Mat * I = new cv::Mat();\n    \n    REQUIRE(I);\n    \n}\n\n#endif /* DEPENDENCYTEST_HPP */\n\n", "meta": {"hexsha": "61c92c7ba58bfe11927c625ba106eb6477ebfe5a", "size": 667, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/DependencyTest.hpp", "max_stars_repo_name": "JordanMcManus/OpenSidescan", "max_stars_repo_head_hexsha": "c14cd58a90d48d0f3a14b9c1381bdc5692662d98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-11-01T19:00:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T20:12:16.000Z", "max_issues_repo_path": "test/DependencyTest.hpp", "max_issues_repo_name": "JordanMcManus/OpenSidescan", "max_issues_repo_head_hexsha": "c14cd58a90d48d0f3a14b9c1381bdc5692662d98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 68.0, "max_issues_repo_issues_event_min_datetime": "2019-08-20T17:38:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T17:43:29.000Z", "max_forks_repo_path": "test/DependencyTest.hpp", "max_forks_repo_name": "JordanMcManus/OpenSidescan", "max_forks_repo_head_hexsha": "c14cd58a90d48d0f3a14b9c1381bdc5692662d98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T14:15:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:25:03.000Z", "avg_line_length": 18.027027027, "max_line_length": 119, "alphanum_fraction": 0.6146926537, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5780154448120005}}
{"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": "#include <cmath>\n#include \"conex/debug_macros.h\"\n#include \"conex/divergence.h\"\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\nnamespace conex {\n\nusing Eigen::MatrixXd;\n\nTEST(MuSelection, DivergenceBound) {\n  int n = 3;\n  MatrixXd gw = Eigen::VectorXd::Random(n, 1).array().abs();\n\n  double gw_norm_squared = gw.squaredNorm();\n  double gw_norm_inf = gw.maxCoeff();\n  double gw_trace = gw.sum();\n  double hub_desired = 1;\n  double k = DivergenceUpperBoundInverse(hub_desired, gw_norm_squared,\n                                         gw_norm_inf, gw_trace, n);\n  double hub =\n      DivergenceUpperBound(k, gw_norm_squared, gw_norm_inf, gw_trace, n);\n\n  EXPECT_TRUE(k >= 0);\n  EXPECT_TRUE(2 - k * gw_norm_inf >= 0);\n  EXPECT_NEAR(hub, hub_desired, 1e-12);\n}\n\n}  // namespace conex\n", "meta": {"hexsha": "ccc240d9d57f1f8a2f55a397b16f2d90005489bd", "size": 780, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/test/test_divergence.cc", "max_stars_repo_name": "ToyotaResearchInstitute/conex", "max_stars_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T08:02:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T21:53:22.000Z", "max_issues_repo_path": "conex/test/test_divergence.cc", "max_issues_repo_name": "ToyotaResearchInstitute/conex", "max_issues_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/test/test_divergence.cc", "max_forks_repo_name": "ToyotaResearchInstitute/conex", "max_forks_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T16:02:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T11:25:46.000Z", "avg_line_length": 26.0, "max_line_length": 73, "alphanum_fraction": 0.6730769231, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5780154207024497}}
{"text": "//\r\n// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n\r\n#include <OpenTissue/core/math/math_basic_types.h>\r\n\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <OpenTissue/utility/utility_push_boost_filter.h>\r\n#include <boost/test/auto_unit_test.hpp>\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_math_axis_angle);\r\n\r\nBOOST_AUTO_TEST_CASE(simple_test)\r\n{\r\n\r\n  typedef OpenTissue::math::BasicMathTypes<double,size_t> math_types;\r\n\r\n  typedef math_types::real_type        T;\r\n  typedef math_types::vector3_type     V;\r\n  typedef math_types::quaternion_type  Q;\r\n\r\n  // Small positive angle\r\n  {\r\n    Q q;\r\n    T const phi = 0.01;\r\n    V const m = unit( V( 1.0, 1.0, 1.0 ) );\r\n    q.Ru( phi, m);\r\n\r\n    T theta;\r\n    V n;\r\n    OpenTissue::math::get_axis_angle( q, n, theta );\r\n\r\n    BOOST_CHECK_CLOSE( phi, theta, 0.01 );\r\n    BOOST_CHECK_CLOSE( m(0), n(0), 0.01 );\r\n    BOOST_CHECK_CLOSE( m(1), n(1), 0.01 );\r\n    BOOST_CHECK_CLOSE( m(2), n(2), 0.01 );\r\n  }\r\n  // See what happens if axis is flipped\r\n  {\r\n    Q q;\r\n    T const phi = 0.01;\r\n    V const m = -unit( V( 1.0, 1.0, 1.0 ) );\r\n    q.Ru( phi, m);\r\n\r\n    T theta;\r\n    V n;\r\n    OpenTissue::math::get_axis_angle( q, n, theta );\r\n\r\n    BOOST_CHECK_CLOSE( phi, theta, 0.01 );\r\n    BOOST_CHECK_CLOSE( m(0), n(0), 0.01 );\r\n    BOOST_CHECK_CLOSE( m(1), n(1), 0.01 );\r\n    BOOST_CHECK_CLOSE( m(2), n(2), 0.01 );\r\n  }\r\n  // Pick larger angle\r\n  {\r\n    Q q;\r\n    T const phi = 3.0;\r\n    V const m = unit( V( 1.0, 1.0, 1.0 ) );\r\n    q.Ru( phi, m);\r\n\r\n    T theta;\r\n    V n;\r\n    OpenTissue::math::get_axis_angle( q, n, theta );\r\n\r\n    BOOST_CHECK_CLOSE( phi, theta, 0.01 );\r\n    BOOST_CHECK_CLOSE( m(0), n(0), 0.01 );\r\n    BOOST_CHECK_CLOSE( m(1), n(1), 0.01 );\r\n    BOOST_CHECK_CLOSE( m(2), n(2), 0.01 );\r\n  }\r\n  // Pick larger negative angle, the positive angle version representation should be returned!\r\n  {\r\n    Q q;\r\n    T const phi = -3.0;\r\n    V const m = unit( V( 1.0, 1.0, 1.0 ) );\r\n    q.Ru( phi, m);\r\n\r\n    T theta;\r\n    V n;\r\n    OpenTissue::math::get_axis_angle( q, n, theta );\r\n\r\n    BOOST_CHECK_CLOSE( -phi, theta, 0.01 );\r\n    BOOST_CHECK_CLOSE( -m(0), n(0), 0.01 );\r\n    BOOST_CHECK_CLOSE( -m(1), n(1), 0.01 );\r\n    BOOST_CHECK_CLOSE( -m(2), n(2), 0.01 );\r\n  }\r\n  // Flip the axis\r\n  {\r\n    Q q;\r\n    T const phi = -3.0;\r\n    V const m = -unit( V( 1.0, 1.0, 1.0 ) );\r\n    q.Ru( phi, m);\r\n\r\n    T theta;\r\n    V n;\r\n    OpenTissue::math::get_axis_angle( q, n, theta );\r\n\r\n    BOOST_CHECK_CLOSE( -phi, theta, 0.01 );\r\n    BOOST_CHECK_CLOSE( -m(0), n(0), 0.01 );\r\n    BOOST_CHECK_CLOSE( -m(1), n(1), 0.01 );\r\n    BOOST_CHECK_CLOSE( -m(2), n(2), 0.01 );\r\n  }\r\n  // Large positive angle\r\n  {\r\n    Q q;\r\n    T const phi = 6.0;\r\n    V const m = unit( V( 1.0, 1.0, 1.0 ) );\r\n    q.Ru( phi, m);\r\n\r\n    T theta;\r\n    V n;\r\n    OpenTissue::math::get_axis_angle( q, n, theta );\r\n\r\n    BOOST_CHECK_CLOSE( phi, theta, 0.01 );\r\n    BOOST_CHECK_CLOSE( m(0), n(0), 0.01 );\r\n    BOOST_CHECK_CLOSE( m(1), n(1), 0.01 );\r\n    BOOST_CHECK_CLOSE( m(2), n(2), 0.01 );\r\n  }\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "f5b8c41baab25c2cafc77138bf6ed6459e93ab7a", "size": 3368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/axis_angle/src/unit_axis_angle.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/axis_angle/src/unit_axis_angle.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/axis_angle/src/unit_axis_angle.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 26.1085271318, "max_line_length": 95, "alphanum_fraction": 0.5825415677, "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5779792013914232}}
{"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 <iostream>\n#include <cassert>\n\n#include \"libff/common/profiling.hpp\"\n\n#include <NTL/mat_ZZ_p.h>\n#include <gmp.h>\n\n#include \"bgroup/bgroup.tcc\"\n#include \"ssfe/ssfe_sm.tcc\"\n\nusing namespace ssfe;\n\nconst size_t S = 128;\nconst size_t K = 2;\n\nconst size_t Repeat = 10;\n\nint main() {\n    Prms prms;\n    Msk msk;\n    Vct x;\n    Vct y;\n    Key sk(S);\n    Cph cph(S);\n    bool r;\n    size_t i, j;\n\n    bgroup_init();\n    libff::start_profiling();\n\n    for(i=0;i<Repeat;i++) {\n        x.SetLength(S);\n        y.SetLength(S);\n        for(j=0;j<S;j++) {\n            x[j]=random_ZZ_p();\n            y[j]=random_ZZ_p();\n            x[j+1]=x[j];\n            y[j+1]=-y[j];\n            j++;\n        }\n\n        setup(prms,S,K);\n        keygen(msk,prms);\n\n        libff::enter_block(\"Extract\");\n        extract(sk,y,msk,prms);\n        libff::leave_block(\"Extract\");\n\n        libff::enter_block(\"Encrypt\");\n        encrypt(cph,x,msk,prms);\n        libff::leave_block(\"Encrypt\");\n\n        libff::enter_block(\"Decrypt\");\n        r=decrypt(cph,sk,prms);\n        libff::leave_block(\"Decrypt\");\n\n        //Orthogonality should be true\n        assert(r != 0);\n\n        y[0]=random_ZZ_p();\n        extract(sk,y,msk,prms);\n        r = decrypt(cph,sk,prms);\n\n        //Orthogonality should be false\n        assert(r == 0);\n    }\n\n    std::cout << \"OK!\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "ba81f1a87ade22ee8975c89e5bd582bd7b7b438e", "size": 1353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/test_ssfe_sm.cpp", "max_stars_repo_name": "mbbarbosa/orthoginalityfe", "max_stars_repo_head_hexsha": "6d26cec15f4c6048f3f0028bb31f2ff3d99073ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T06:36:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T06:36:15.000Z", "max_issues_repo_path": "src/tests/test_ssfe_sm.cpp", "max_issues_repo_name": "mbbarbosa/orthoginalityfe", "max_issues_repo_head_hexsha": "6d26cec15f4c6048f3f0028bb31f2ff3d99073ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_ssfe_sm.cpp", "max_forks_repo_name": "mbbarbosa/orthoginalityfe", "max_forks_repo_head_hexsha": "6d26cec15f4c6048f3f0028bb31f2ff3d99073ee", "max_forks_repo_licenses": ["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.5342465753, "max_line_length": 39, "alphanum_fraction": 0.5232815965, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5779464224013542}}
{"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 *      Easy calculation. Newton's Law of Gravity Tutorial,\n *          http://easycalculation.com/physics/classical-physics/learn-newtons-law.php, last\n *          accessed: 12th February, 2012.\n *\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <limits>\n\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"tudat/astro/gravitation/centralGravityModel.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_gravitational_force )\n\n//! Test if gravitational force is computed correctly.\nBOOST_AUTO_TEST_CASE( testGravitationalForce )\n{\n    // Case 1: Compute gravitational force exerted on boy, due to Earth (Easy calculation, 2012).\n    {\n        // Set gravitational parameter of Earth [m^3 s^-2].\n        double gravitationalParameterOfEarth = 6.6726e-11 * 5.98e24;\n\n        // Set position vector of Earth [m].\n        Eigen::Vector3d positionOfEarth = Eigen::Vector3d::Zero( );\n\n        // Set mass of boy [kg]\n        double massOfBoy = 70.0;\n\n        // Set position vector of boy [m].\n        Eigen::Vector3d positionOfBoy( 6.38e6, 0.0, 0.0 );\n\n        // Compute gravitational force acting on boy [N].\n        Eigen::Vector3d gravitationalForceExertedOnBoy\n                = gravitation::computeGravitationalForce(\n                    massOfBoy, positionOfBoy,\n                    gravitationalParameterOfEarth, positionOfEarth );\n\n        // Check if computed gravitational force matches expected value.\n        BOOST_CHECK_CLOSE_FRACTION( 685.54, gravitationalForceExertedOnBoy.norm( ), 1.0e-3 );\n    }\n\n    // Case 2: Compute gravitational force exerted on arbitrary body1, due to arbitrary body2\n    //         (Easy calculation, 2012).\n    {\n        // Set universal gravitational constant [m^3 kg^-1 s^-2].\n        double universalGravitationalConstant = 6.6726e-11;\n\n        // Set mass of body1 [kg].\n        double massOfBody1 = 1.0e4;\n\n        // Set position vector of body1 [m].\n        Eigen::Vector3d positionOfBody1( 0.0, 5.0, 0.0 );\n\n        // Set mass of body2 [kg].\n        double massOfBody2 = 2.0e4;\n\n        // Set position vector of body2 [m].\n        Eigen::Vector3d positionOfBody2( 0.0, -5.0, 0.0 );\n\n        // Compute gravitational force acting on body1 [N].\n        Eigen::Vector3d gravitationalForceExertedOnBody1\n                = gravitation::computeGravitationalForce(\n                    universalGravitationalConstant, massOfBody1,\n                    positionOfBody1, massOfBody2, positionOfBody2 );\n\n        // Check if computed gravitational force matches expected value.\n        BOOST_CHECK_CLOSE_FRACTION( 13345200.0e-11, gravitationalForceExertedOnBody1.norm( ),\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "4ffdb6974ff617306c917d6470772d56df2c6ff3", "size": 3339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/gravitation/unitTestGravitationalForce.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/astro/gravitation/unitTestGravitationalForce.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/astro/gravitation/unitTestGravitationalForce.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": 34.4226804124, "max_line_length": 97, "alphanum_fraction": 0.6633722671, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.6261241842048093, "lm_q1q2_score": 0.5779371477156046}}
{"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//\u52a0\u9876\u70b9\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//\u751f\u6210\u89c2\u6d4b\u503c\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,\u6b64\u503c\u4e0d\u80fd\u592a\u5927,\u8fc7\u5927\u65f6exp(3*x^2 + 2*x + 1)\u5c31\u6ea2\u51fa\u4e86\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//\u52a0\u8fb9\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//\u5f00\u59cb\u8fdb\u884c\u4f18\u5316\u4f30\u8ba1\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": "#include \"Day15-DuelingGenerators.h\"\n\n#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>\n\n__BEGIN_LIBRARIES_DISABLE_WARNINGS\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <string>\n#include <vector>\n#include <cassert>\n__END_LIBRARIES_DISABLE_WARNINGS\n\nnamespace\n{\n\nconst unsigned GENERATOR_A_MULTIPLIER = 16807;\nconst unsigned GENERATOR_B_MULTIPLIER = 48271;\n\nconst unsigned GENERATOR_A_MULTIPLE_CRITERION = 4;\nconst unsigned GENERATOR_B_MULTIPLE_CRITERION = 8;\n\nconst unsigned GENERATOR_MODULUS = 2'147'483'647;\n\nconst unsigned NO_CRITERIA_NUM_ROUNDS = 40'000'000;\nconst unsigned CRITERIA_NUM_ROUNDS = 5'000'000;\n\nconst unsigned JUDGE_NUM_BINARY_DIGITS_TO_MATCH = 16;\n\n}\n\nnamespace AdventOfCode\n{\nnamespace Year2017\n{\nnamespace Day15\n{\n\nunsigned generatorStartFromLine(const std::string& line)\n{\n    std::vector<std::string> tokens;\n    boost::split(tokens, line, boost::is_any_of(\" \"));\n\n    if (tokens.size() != 5)\n    {\n        throw std::runtime_error(\"Input line needs to have exactly 5 tokens.\");\n    }\n\n    return boost::lexical_cast<unsigned>(tokens[4]);\n}\n\nconstexpr uint64_t generateNextValue(uint64_t prevValue, unsigned multiplier, unsigned multipleCriterion) noexcept\n{\n    uint64_t currValue{};\n    while (true)\n    {\n        currValue = (prevValue * multiplier) % GENERATOR_MODULUS;\n\n        if (currValue % multipleCriterion == 0)\n        {\n            break;\n        }\n\n        prevValue = currValue;\n    }\n\n    return currValue;\n\n}\n\nunsigned judgeFinalCount(unsigned generatorAStart, unsigned generatorBStart, unsigned numRounds, bool isUsingCriteria)\n{\n    const double judgeModulusDouble = (pow(2, JUDGE_NUM_BINARY_DIGITS_TO_MATCH));\n    assert(judgeModulusDouble <= std::numeric_limits<unsigned>::max());\n\n    const unsigned judgeModulus = static_cast<unsigned>(judgeModulusDouble);\n\n    uint64_t generatorAPrevValue = generatorAStart;\n    uint64_t generatorBPrevValue = generatorBStart;\n\n    unsigned judgeScore = 0;\n\n    for (unsigned i = 0; i < numRounds; ++i)\n    {\n        const uint64_t generatorACurrValue = generateNextValue(generatorAPrevValue, GENERATOR_A_MULTIPLIER, isUsingCriteria ? GENERATOR_A_MULTIPLE_CRITERION : 1);\n        const uint64_t generatorBCurrValue = generateNextValue(generatorBPrevValue, GENERATOR_B_MULTIPLIER, isUsingCriteria ? GENERATOR_B_MULTIPLE_CRITERION : 1);\n\n        if (generatorACurrValue % judgeModulus == generatorBCurrValue % judgeModulus)\n        {\n            ++judgeScore;\n        }\n\n        generatorAPrevValue = generatorACurrValue;\n        generatorBPrevValue = generatorBCurrValue;\n    }\n\n    return judgeScore;\n}\n\nunsigned judgeFinalCountNoCriteria(unsigned generatorAStart, unsigned generatorBStart)\n{\n    return judgeFinalCount(generatorAStart, generatorBStart, NO_CRITERIA_NUM_ROUNDS, false);\n}\n\nunsigned judgeFinalCountWithCriteria(unsigned generatorAStart, unsigned generatorBStart)\n{\n    return judgeFinalCount(generatorAStart, generatorBStart, CRITERIA_NUM_ROUNDS, true);\n}\n\n}\n}\n}\n", "meta": {"hexsha": "3bb86f3c8102de0f93375a72e31941d923a619d7", "size": 3006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AdventOfCode2017/Day15-DuelingGenerators/Day15-DuelingGenerators.cpp", "max_stars_repo_name": "dbartok/advent-of-code-cpp", "max_stars_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AdventOfCode2017/Day15-DuelingGenerators/Day15-DuelingGenerators.cpp", "max_issues_repo_name": "dbartok/advent-of-code-cpp", "max_issues_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AdventOfCode2017/Day15-DuelingGenerators/Day15-DuelingGenerators.cpp", "max_forks_repo_name": "dbartok/advent-of-code-cpp", "max_forks_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6017699115, "max_line_length": 162, "alphanum_fraction": 0.751164338, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5779239711305773}}
{"text": "// Copyright \u00a9 2016-2019 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n\n#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 \u03a4\u03b5\u03c7\u03bd\u03bf\u03bb\u03bf\u03b3\u03af\u03b5\u03c2 \u03a5\u03bb\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7\u03c2 \u0391\u03bb\u03b3\u03bf\u03c1\u03af\u03b8\u03bc\u03c9\u03bd/2\u03b7 \u0386\u03c3\u03ba\u03b7\u03c3\u03b7/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 \u03a4\u03b5\u03c7\u03bd\u03bf\u03bb\u03bf\u03b3\u03af\u03b5\u03c2 \u03a5\u03bb\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7\u03c2 \u0391\u03bb\u03b3\u03bf\u03c1\u03af\u03b8\u03bc\u03c9\u03bd/2\u03b7 \u0386\u03c3\u03ba\u03b7\u03c3\u03b7/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 \u03a4\u03b5\u03c7\u03bd\u03bf\u03bb\u03bf\u03b3\u03af\u03b5\u03c2 \u03a5\u03bb\u03bf\u03c0\u03bf\u03af\u03b7\u03c3\u03b7\u03c2 \u0391\u03bb\u03b3\u03bf\u03c1\u03af\u03b8\u03bc\u03c9\u03bd/2\u03b7 \u0386\u03c3\u03ba\u03b7\u03c3\u03b7/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": "#include <math.h>\n#include <uWS/uWS.h>\n#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include \"MPC.h\"\n#include \"json.hpp\"\n#include \"tools.hpp\"\n\n// for convenience\nusing json = nlohmann::json;\n\nconst int N_ref = 15; // number of points for reference trajectory\nconst double wp_delta = 5.0; // delta between waypoints in x direction\nconst double latency_s = 0.07; // estimated latency in seconds for future state prediction\n\n// This value assumes the model presented in the classroom is used.\n// It was obtained by measuring the radius formed by running the vehicle in the\n// simulator around in a circle with a constant steering angle and velocity on a\n// flat terrain.\n//\n// Lf was tuned until the the radius formed by the simulating the model\n// presented in the classroom matched the previous radius.\n//\n// This is the length from front to CoG that has a similar radius.\nconst double Lf = 2.67;\n\n// Reference velocity\nconst double ref_v = 120.0;\n\n\n\nint main() {\n  uWS::Hub h;\n\n  // MPC is initialized here!\n  MPC mpc(ref_v, Lf, 0.1, -0.6, 1.0, 200.);\n\n  // save steering angle and throttle values in case optimizer failed\n  double steer_value = 0.0;\n  double throttle_value = 1.0;\n\n  h.onMessage([&mpc, &steer_value, &throttle_value](uWS::WebSocket<uWS::SERVER> ws,\n                                                    char *data, size_t length, uWS::OpCode opCode) {\n    // \"42\" at the start of the message means there's a websocket message event.\n    // The 4 signifies a websocket message\n    // The 2 signifies a websocket event\n    std::chrono::high_resolution_clock::time_point begin = std::chrono::high_resolution_clock::now();\n    string sdata = string(data).substr(0, length);\n    if (sdata.size() > 2 && sdata[0] == '4' && sdata[1] == '2') {\n      string s = hasData(sdata);\n      if (s != \"\") {\n        auto j = json::parse(s);\n        string event = j[0].get<string>();\n        if (event == \"telemetry\") {\n          // j[1] is the data JSON object\n          vector<double> waypts_x = j[1][\"ptsx\"];\n          vector<double> waypts_y = j[1][\"ptsy\"];\n          double px               = j[1][\"x\"];\n          double py               = j[1][\"y\"];\n          double psi              = j[1][\"psi\"];\n          double v                = j[1][\"speed\"];\n          double cte, epsi;\n          bool success = false;\n\n          //Display the waypoints/reference line\n          vector<double> next_x_vals(N_ref);\n          vector<double> next_y_vals(N_ref);\n          //Display the MPC predicted trajectory \n          vector<double> mpc_x_vals;\n          vector<double> mpc_y_vals;\n\n          // Transform waypoints from global coordinate system into the local car coordinate system\n          // where px and py are the cars translational offset and -psi the rotational offset\n          std::vector<double> waypts_x_trans;\n          std::vector<double> waypts_y_trans;\n          Tranform2d(waypts_x_trans, waypts_y_trans, waypts_x, waypts_y, px, py, -psi);\n          Eigen::Map<Eigen::VectorXd> wp_x(waypts_x_trans.data(), waypts_x_trans.size());\n          Eigen::Map<Eigen::VectorXd> wp_y(waypts_y_trans.data(), waypts_y_trans.size());\n\n          // Fit a polynomial of order 3 to the above x and y coordinates\n          auto coeffs = polyfit(wp_x, wp_y, 3);\n\n          for (int x = 0; x < (int) next_x_vals.size(); x++) {\n            next_x_vals[x] = wp_delta*x;\n            next_y_vals[x] = polyeval(coeffs, next_x_vals[x]);\n          }\n\n          // Calculate the cross-track-error\n          // current CTE is fitted polynomial (road curve), evaluated at px = 0.0\n          cte = coeffs[0];\n\n          // Current heading error epsi is the tangent (derivative) to the road curve,\n          // also evaluated at px = 0.0.\n          // f = ax^3 + bx + c --> f'(x)=2ax+b --> f'(0)=b\n          // y(x)   = a*x^3 + b*x^2 + c*x + d --->  y'(x) = 3*a*x^2 + 2*b*x + c\n          // coeffs = [d, c, b, a]\n          // epsi = arctan(y'(0)) = arctan(coeffs[1])\n          epsi = -atan(coeffs[1]);\n\n          // In initial state for trajectory planning x, y, and psi are 0\n          // because they now represent the position and orientation in \n          // local car coordinates.\n          px = py = psi = 0.0;\n          // Predicting offset to initial state by taking actuation delays into account\n          if  (latency_s > 0.0) {\n            px    += v * cos(-psi) * latency_s;\n            py    += v * sin(-psi) * latency_s;\n            psi    = fmod(psi + v * steer_value / Lf * latency_s, 2*M_PI);\n            cte   += v * sin(epsi) * latency_s;\n            epsi  += v * steer_value / Lf * latency_s;\n            v     += throttle_value * latency_s;\n          }\n\n          Eigen::VectorXd state(6);\n          state << px, py, psi, v, cte, epsi;\n\n          auto solution = mpc.Solve(state, coeffs, mpc_x_vals, mpc_y_vals, success);\n\n          // Calculate steering angle and throttle using MPC.\n          // Both are in between [-1, 1].\n          // But only update values if solver succeeded, otherwise keep old values!\n          if (success) {\n            steer_value    = solution[0];\n            throttle_value = solution[1];\n          } else {\n            std::cout << \"Optimizer failed to find solution!\" << std::endl;\n          }\n\n          json msgJson;\n\n          // Note:\n          // - If steering is positive we rotate counter-clockwise, or turn left.\n          //   In the simulator however, a positive value implies a right turn and a negative value implies a left turn.\n          //   Therefore we change directions here.\n          // - Remember to divide by deg2rad(25) before you send the steering value back.\n          //   Otherwise the values will be in between [-deg2rad(25), deg2rad(25] instead of [-1, 1].\n          msgJson[\"steering_angle\"] = -steer_value / deg2rad(25);\n          msgJson[\"throttle\"] = throttle_value;\n\n          //.. add (x,y) points to list here, points are in reference to the vehicle's coordinate system\n          // the points in the simulator are connected by a Green line\n          msgJson[\"mpc_x\"] = mpc_x_vals;\n          msgJson[\"mpc_y\"] = mpc_y_vals;\n\n          //.. add (x,y) points to list here, points are in reference to the vehicle's coordinate system\n          // the points in the simulator are connected by a Yellow line\n          msgJson[\"next_x\"] = next_x_vals;\n          msgJson[\"next_y\"] = next_y_vals;\n\n          auto msg = \"42[\\\"steer\\\",\" + msgJson.dump() + \"]\";\n          //std::cout << msg << std::endl;\n\n          // Latency\n          // The purpose is to mimic real driving conditions where\n          // the car does actuate the commands instantly.\n          //\n          // Feel free to play around with this value but should be to drive\n          // around the track with 100ms latency.\n          //\n          // NOTE: REMEMBER TO SET THIS TO 100 MILLISECONDS BEFORE\n          // SUBMITTING.\n          chrono::high_resolution_clock::time_point end= chrono::high_resolution_clock::now();\n          std::cout << \"elapsed seconds: \" << \n                       1e-3*chrono::duration_cast<chrono::milliseconds>(end-begin).count() << endl;\n\n          this_thread::sleep_for(chrono::milliseconds(100));\n          ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\n        }\n      } else {\n        // Manual driving\n        std::string msg = \"42[\\\"manual\\\",{}]\";\n        ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\n      }\n    }\n  });\n\n  // We don't need this since we're not using HTTP but if it's removed the\n  // program\n  // doesn't compile :-(\n  h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,\n                     size_t, size_t) {\n    const std::string s = \"<h1>Hello world!</h1>\";\n    if (req.getUrl().valueLength == 1) {\n      res->end(s.data(), s.length());\n    } else {\n      // i guess this should be done more gracefully?\n      res->end(nullptr, 0);\n    }\n  });\n\n  h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {\n    std::cout << \"Connected!!!\" << std::endl;\n  });\n\n  h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,\n                         char *message, size_t length) {\n    ws.close();\n    std::cout << \"Disconnected\" << std::endl;\n  });\n\n  int port = 4567;\n  if (h.listen(port)) {\n    std::cout << \"Listening to port \" << port << std::endl;\n  } else {\n    std::cerr << \"Failed to listen to port\" << std::endl;\n    return -1;\n  }\n  h.run();\n}\n", "meta": {"hexsha": "d1a4930ec5dd706a7fe6fcf2477bcd51cc94183e", "size": 8472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "da-phil/SDC-Model-Predictive-Control", "max_stars_repo_head_hexsha": "563e8f16f61713096170728cda576b86dba4d3cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "da-phil/SDC-Model-Predictive-Control", "max_issues_repo_head_hexsha": "563e8f16f61713096170728cda576b86dba4d3cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "da-phil/SDC-Model-Predictive-Control", "max_forks_repo_head_hexsha": "563e8f16f61713096170728cda576b86dba4d3cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5887850467, "max_line_length": 120, "alphanum_fraction": 0.5814447592, "num_tokens": 2181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5778850360187825}}
{"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 \u2264 j \u2264 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\u22121, . . . , 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": "#include <vector>\n#include <Eigen/Dense>\n#include \"../simple_lib/include/simple_activation.h\"\n#include <matplotlibcpp.h>\n\nnamespace plt = matplotlibcpp;\nusing namespace Eigen;\n\nint main(){\n    using std::vector;\n\n    int n = 201;\n    VectorXd x = VectorXd::LinSpaced(n, -10, 10);\n    VectorXd y;\n\n    y = x.unaryExpr([](double p){return MyDL::relu<double>(p);});\n\n    // plot\u306e\u305f\u3081\u306b\u3001STL\u30b3\u30f3\u30c6\u30ca\u306b\u8a70\u3081\u66ff\u3048\n    vector<double> xs(n), ys(n);\n    Map<VectorXd>(&xs[0], n) = x;\n    Map<VectorXd>(&ys[0], n) = y;\n\n    plt::named_plot(\"ReLU\", xs, ys, \"--b\");\n    plt::grid(true);\n    plt::legend();\n    plt::save(\"ch3/images/relu.png\");\n\n    return 0;\n}", "meta": {"hexsha": "389f7d096ffd91c60a105b413c58937eade56cfb", "size": 633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/visualize_relu.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch3/visualize_relu.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/visualize_relu.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8275862069, "max_line_length": 65, "alphanum_fraction": 0.6097946288, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5776643943455062}}
{"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// \u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u7b2c\u4e00\u4e2a\u4efb\u52a1\u662f\u5305\u62ec\u8fd9\u4e9b\u8457\u540d\u7684deal.II\u5e93\u6587\u4ef6\u548c\u4e00\u4e9bC++\u5934\u6587\u4ef6\u7684\u529f\u80fd\u3002\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// \u8fd9\u662f\u552f\u4e00\u4e00\u4e2a\u65b0\u7684\u5305\u542b\u6587\u4ef6\uff1a\u5b83\u5305\u62ec\u6240\u6709\u7684Runge-Kutta\u65b9\u6cd5\u3002\n\n#include <deal.II/base/time_stepping.h> \n\n// \u63a5\u4e0b\u6765\u7684\u6b65\u9aa4\u4e0e\u4e4b\u524d\u6240\u6709\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e00\u6837\u3002\u6211\u4eec\u628a\u6240\u6709\u7684\u4e1c\u897f\u653e\u5230\u4e00\u4e2a\u81ea\u5df1\u7684\u547d\u540d\u7a7a\u95f4\u4e2d\uff0c\u7136\u540e\u628adeal.II\u7684\u7c7b\u548c\u51fd\u6570\u5bfc\u5165\u5176\u4e2d\u3002\n\nnamespace Step52 \n{ \n  using namespace dealii; \n// @sect3{The <code>Diffusion</code> class}  \n\n// \u4e0b\u4e00\u5757\u662f\u4e3b\u7c7b\u7684\u58f0\u660e\u3002\u8fd9\u4e2a\u7c7b\u4e2d\u7684\u5927\u90e8\u5206\u51fd\u6570\u5e76\u4e0d\u65b0\u9c9c\uff0c\u5728\u4ee5\u524d\u7684\u6559\u7a0b\u4e2d\u5df2\u7ecf\u89e3\u91ca\u8fc7\u4e86\u3002\u552f\u4e00\u6709\u8da3\u7684\u51fd\u6570\u662f  <code>evaluate_diffusion()</code>  \u548c  <code>id_minus_tau_J_inverse()</code>. <code>evaluate_diffusion()</code>  \u8bc4\u4f30\u6269\u6563\u65b9\u7a0b\uff0c  $M^{-1}(f(t,y))$  \uff0c\u5728\u4e00\u4e2a\u7ed9\u5b9a\u7684\u65f6\u95f4\u548c\u4e00\u4e2a\u7ed9\u5b9a\u7684  $y$  \u3002  <code>id_minus_tau_J_inverse()</code>  \u5728\u7ed9\u5b9a\u7684\u65f6\u95f4\u548c\u7ed9\u5b9a\u7684 $\\tau$ \u548c $y$ \u4e0b\uff0c\u8bc4\u4f30 $\\left(I-\\tau M^{-1} \\frac{\\partial f(t,y)}{\\partial y}\\right)^{-1}$ \u6216\u7c7b\u4f3c\u7684 $\\left(M-\\tau \\frac{\\partial f}{\\partial y}\\right)^{-1} M$ \u3002\u5f53\u4f7f\u7528\u9690\u5f0f\u65b9\u6cd5\u65f6\uff0c\u5c31\u9700\u8981\u8fd9\u4e2a\u51fd\u6570\u3002\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// \u63a5\u4e0b\u6765\u7684\u4e09\u4e2a\u51fd\u6570\u5206\u522b\u662f\u663e\u5f0f\u65b9\u6cd5\u3001\u9690\u5f0f\u65b9\u6cd5\u548c\u5d4c\u5165\u5f0f\u663e\u5f0f\u65b9\u6cd5\u7684\u9a71\u52a8\u3002\u5d4c\u5165\u663e\u5f0f\u65b9\u6cd5\u7684\u9a71\u52a8\u51fd\u6570\u8fd4\u56de\u6267\u884c\u7684\u6b65\u6570\uff0c\u9274\u4e8e\u5b83\u53ea\u63a5\u53d7\u4f5c\u4e3a\u53c2\u6570\u4f20\u9012\u7684\u65f6\u95f4\u6b65\u6570\u4f5c\u4e3a\u63d0\u793a\uff0c\u4f46\u5185\u90e8\u8ba1\u7b97\u4e86\u6700\u4f73\u65f6\u95f4\u6b65\u6570\u672c\u8eab\u3002\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// \u6211\u4eec\u9009\u62e9\u4e8c\u6b21\u65b9\u6709\u9650\u5143\uff0c\u5e76\u521d\u59cb\u5316\u53c2\u6570\u3002\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// \u73b0\u5728\uff0c\u6211\u4eec\u521b\u5efa\u7ea6\u675f\u77e9\u9635\u548c\u7a00\u758f\u6a21\u5f0f\u3002\u7136\u540e\uff0c\u6211\u4eec\u521d\u59cb\u5316\u8fd9\u4e9b\u77e9\u9635\u548c\u6c42\u89e3\u5411\u91cf\u3002\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>}  \u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u8ba1\u7b97  $-\\int D \\nabla b_i \\cdot \\nabla b_j d\\boldsymbol{r} - \\int \\Sigma_a b_i b_j d\\boldsymbol{r}$  \u548c\u8d28\u91cf\u77e9\u9635  $\\int b_i b_j d\\boldsymbol{r}$  \u3002\u7136\u540e\u4f7f\u7528\u76f4\u63a5\u6c42\u89e3\u5668\u5bf9\u8d28\u91cf\u77e9\u9635\u8fdb\u884c\u53cd\u6f14\uff1b\u7136\u540e <code>inverse_mass_matrix</code> \u53d8\u91cf\u5c06\u5b58\u50a8\u8d28\u91cf\u77e9\u9635\u7684\u53cd\u503c\uff0c\u8fd9\u6837 $M^{-1}$ \u5c31\u53ef\u4ee5\u4f7f\u7528\u8be5\u5bf9\u8c61\u7684 <code>vmult()</code> \u51fd\u6570\u5e94\u7528\u4e8e\u4e00\u4e2a\u77e2\u91cf\u3002\u5728\u5185\u90e8\uff0cUMFPACK\u5e76\u6ca1\u6709\u771f\u6b63\u5b58\u50a8\u77e9\u9635\u7684\u9006\uff0c\u800c\u662f\u5b58\u50a8\u5b83\u7684LU\u56e0\u5b50\uff1b\u5e94\u7528\u77e9\u9635\u7684\u9006\u76f8\u5f53\u4e8e\u7528\u8fd9\u4e24\u4e2a\u56e0\u5b50\u505a\u4e00\u6b21\u6b63\u89e3\u548c\u4e00\u6b21\u9006\u89e3\uff0c\u8fd9\u4e0e\u5e94\u7528\u77e9\u9635\u7684\u663e\u5f0f\u9006\u5177\u6709\u76f8\u540c\u7684\u590d\u6742\u6027\uff09\u3002\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// \u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u8ba1\u7b97\u51fa\u7279\u5b9a\u65f6\u95f4\u548c\u7279\u5b9a\u70b9\u7684\u65b9\u7a0b\u7684\u6e90\u9879\u3002\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// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5728\u7ed9\u5b9a\u7684\u65f6\u95f4  $t$  \u548c\u7ed9\u5b9a\u7684\u77e2\u91cf  $y$  \u8bc4\u4ef7\u6269\u6563\u65b9\u7a0b\u7684\u5f31\u5f62\u5f0f\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\uff0c\u6211\u4eec\u8bc4\u4f30  $M^{-1}(-{\\cal D}y - {\\cal A}y + {\\cal S})$  \u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u5fc5\u987b\u5c06\u77e9\u9635 $-{\\cal D} - {\\cal A}$ \uff08\u4e4b\u524d\u8ba1\u7b97\u5e76\u5b58\u50a8\u5728\u53d8\u91cf <code>system_matrix</code> \u4e2d\uff09\u5e94\u7528\u4e8e $y$ \uff0c\u7136\u540e\u6dfb\u52a0\u6e90\u9879\uff0c\u6211\u4eec\u50cf\u901a\u5e38\u90a3\u6837\u8fdb\u884c\u79ef\u5206\u3002(\u5982\u679c\u4f60\u60f3\u8282\u7701\u51e0\u884c\u4ee3\u7801\uff0c\u6216\u8005\u60f3\u5229\u7528\u5e76\u884c\u79ef\u5206\u7684\u4f18\u52bf\uff0c\u53ef\u4ee5\u7528 VectorTools::create_right_hand_side() \u6765\u8fdb\u884c\u79ef\u5206\u3002) \u7136\u540e\u5c06\u7ed3\u679c\u4e58\u4ee5 $M^{-1}$  \u3002\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// \u6211\u4eec\u8ba1\u7b97  $\\left(M-\\tau \\frac{\\partial f}{\\partial y}\\right)^{-1} M$  \u3002\u8fd9\u8981\u5206\u51e0\u4e2a\u6b65\u9aa4\u8fdb\u884c\u3002 \n\n// - \u8ba1\u7b97  $M-\\tau \\frac{\\partial f}{\\partial y}$  \u3002  \n\n// - \u53cd\u8f6c\u77e9\u9635\uff0c\u5f97\u5230  $\\left(M-\\tau \\frac{\\partial f} {\\partial y}\\right)^{-1}$  \u3002  \n\n// --\u8ba1\u7b97 $tmp=My$ \u3002  \n\n// --\u8ba1\u7b97 $z=\\left(M-\\tau \\frac{\\partial f}{\\partial y}\\right)^{-1} tmp =  \\left(M-\\tau \\frac{\\partial f}{\\partial y}\\right)^{-1} My$ \u3002  \n\n// - \u8fd4\u56dez\u3002\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// \u4e0b\u9762\u7684\u51fd\u6570\u5c06\u89e3\u51b3\u65b9\u6848\u4ee5vtu\u6587\u4ef6\u7684\u5f62\u5f0f\u8f93\u51fa\uff0c\u5e76\u4ee5\u65f6\u95f4\u6b65\u957f\u548c\u65f6\u95f4\u6b65\u957f\u65b9\u6cd5\u7684\u540d\u79f0\u4e3a\u7d22\u5f15\u3002\u5f53\u7136\uff0c\u6240\u6709\u65f6\u95f4\u6b65\u957f\u65b9\u6cd5\u7684\uff08\u7cbe\u786e\uff09\u7ed3\u679c\u5e94\u8be5\u662f\u4e00\u6837\u7684\uff0c\u4f46\u8fd9\u91cc\u7684\u8f93\u51fa\u81f3\u5c11\u53ef\u4ee5\u8ba9\u6211\u4eec\u5bf9\u5b83\u4eec\u8fdb\u884c\u6bd4\u8f83\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u662f\u6240\u6709\u663e\u5f0f\u65b9\u6cd5\u7684\u9a71\u52a8\u3002\u5728\u9876\u90e8\uff0c\u5b83\u521d\u59cb\u5316\u4e86\u65f6\u95f4\u6b65\u957f\u548c\u89e3\u51b3\u65b9\u6848\uff08\u901a\u8fc7\u5c06\u5176\u8bbe\u7f6e\u4e3a\u96f6\uff0c\u7136\u540e\u786e\u4fdd\u8fb9\u754c\u503c\u548c\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u5f97\u5230\u5c0a\u91cd\uff1b\u5f53\u7136\uff0c\u5bf9\u4e8e\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u7684\u7f51\u683c\uff0c\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u5b9e\u9645\u4e0a\u4e0d\u662f\u4e00\u4e2a\u95ee\u9898\uff09\u3002\u7136\u540e\u8c03\u7528 <code>evolve_one_time_step</code> \uff0c\u6267\u884c\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u3002\u65f6\u95f4\u662f\u901a\u8fc7DiscreteTime\u5bf9\u8c61\u6765\u5b58\u50a8\u548c\u589e\u52a0\u7684\u3002\n\n// \u5bf9\u4e8e\u663e\u5f0f\u65b9\u6cd5\uff0c <code>evolve_one_time_step</code> \u9700\u8981\u8bc4\u4f30 $M^{-1}(f(t,y))$ \uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5b83\u9700\u8981 <code>evaluate_diffusion</code>  \u3002\u56e0\u4e3a <code>evaluate_diffusion</code> \u662f\u4e00\u4e2a\u6210\u5458\u51fd\u6570\uff0c\u5b83\u9700\u8981\u88ab\u7ed1\u5b9a\u5230 <code>this</code> \u3002\u5728\u6bcf\u4e2a\u8fdb\u5316\u6b65\u9aa4\u4e4b\u540e\uff0c\u6211\u4eec\u518d\u6b21\u5e94\u7528\u6b63\u786e\u7684\u8fb9\u754c\u503c\u548c\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u3002\n\n// \u6700\u540e\uff0c\u6bcf\u969410\u4e2a\u65f6\u95f4\u6b65\u9aa4\u5c31\u4f1a\u8f93\u51fa\u89e3\u51b3\u65b9\u6848\u3002\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>}  \u8fd9\u4e2a\u51fd\u6570\u7b49\u540c\u4e8e <code>explicit_method</code> \uff0c\u4f46\u7528\u4e8e\u9690\u5f0f\u65b9\u6cd5\u3002\u5f53\u4f7f\u7528\u9690\u5f0f\u65b9\u6cd5\u65f6\uff0c\u6211\u4eec\u9700\u8981\u8bc4\u4f30 $M^{-1}(f(t,y))$ \u548c $\\left(I-\\tau M^{-1} \\frac{\\partial f(t,y)}{\\partial y}\\right)^{-1}$ \uff0c\u4e3a\u6b64\u6211\u4eec\u4f7f\u7528\u4e4b\u524d\u4ecb\u7ecd\u7684\u4e24\u4e2a\u6210\u5458\u51fd\u6570\u3002\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>}  \u8fd9\u4e2a\u51fd\u6570\u662f\u5d4c\u5165\u5f0f\u663e\u5f0f\u65b9\u6cd5\u7684\u9a71\u52a8\u3002\u5b83\u9700\u8981\u66f4\u591a\u7684\u53c2\u6570\u3002 \n\n// - coarsen_param\uff1a\u5f53\u8bef\u5dee\u4f4e\u4e8e\u9608\u503c\u65f6\uff0c\u4e58\u4ee5\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u7684\u7cfb\u6570\u3002 \n\n// - refine_param: \u5f53\u8bef\u5dee\u9ad8\u4e8e\u9608\u503c\u65f6\uff0c\u4e58\u4ee5\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u7684\u7cfb\u6570\u3002 \n\n// - min_delta: \u53ef\u63a5\u53d7\u7684\u6700\u5c0f\u65f6\u95f4\u6b65\u957f\u3002 \n\n// - max_delta: \u53ef\u63a5\u53d7\u7684\u6700\u5927\u65f6\u95f4\u6b65\u957f\u3002 \n\n// - refine_tol\uff1a\u65f6\u95f4\u6b65\u957f\u8d85\u8fc7\u7684\u9608\u503c\u3002 \n\n// - coarsen_tol\uff1a\u9608\u503c\uff0c\u4f4e\u4e8e\u8be5\u9608\u503c\u7684\u65f6\u95f4\u6b65\u957f\u5c06\u88ab\u7c97\u5316\u3002\n\n// \u5d4c\u5165\u65b9\u6cd5\u4f7f\u7528\u4e00\u4e2a\u731c\u6d4b\u7684\u65f6\u95f4\u6b65\u957f\u3002\u5982\u679c\u4f7f\u7528\u8fd9\u4e2a\u65f6\u95f4\u6b65\u957f\u7684\u8bef\u5dee\u592a\u5927\uff0c\u65f6\u95f4\u6b65\u957f\u5c06\u88ab\u7f29\u5c0f\u3002\u5982\u679c\u8bef\u5dee\u4f4e\u4e8e\u9608\u503c\uff0c\u5219\u5728\u4e0b\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u65f6\u5c06\u5c1d\u8bd5\u66f4\u5927\u7684\u65f6\u95f4\u6b65\u957f\u3002  <code>delta_t_guess</code> \u662f\u7531\u5d4c\u5165\u5f0f\u65b9\u6cd5\u4ea7\u751f\u7684\u731c\u6d4b\u7684\u65f6\u95f4\u6b65\u957f\u3002\u603b\u4e4b\uff0c\u65f6\u95f4\u6b65\u957f\u6709\u53ef\u80fd\u4ee5\u4e09\u79cd\u65b9\u5f0f\u4fee\u6539\u3002 \n\n// - \u5728 TimeStepping::EmbeddedExplicitRungeKutta::evolve_one_time_step(). \u5185\u51cf\u5c11\u6216\u589e\u52a0\u65f6\u95f4\u6b65\u957f\u3002  \n\n// - \u4f7f\u7528\u8ba1\u7b97\u51fa\u7684  <code>delta_t_guess</code>  \u3002 \n\n// - \u81ea\u52a8\u8c03\u6574\u6700\u540e\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\uff0c\u4ee5\u786e\u4fdd\u6a21\u62df\u5728  <code>final_time</code>  \u5904\u7cbe\u786e\u7ed3\u675f\u3002\u8fd9\u79cd\u8c03\u6574\u662f\u5728DiscreteTime\u5b9e\u4f8b\u4e2d\u5904\u7406\u7684\u3002\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// \u4e0b\u9762\u662f\u8be5\u7a0b\u5e8f\u7684\u4e3b\u8981\u529f\u80fd\u3002\u5728\u9876\u90e8\uff0c\u6211\u4eec\u521b\u5efa\u7f51\u683c\uff08\u4e00\u4e2a[0,5]x[0,5]\u7684\u6b63\u65b9\u5f62\uff09\u5e76\u5bf9\u5176\u8fdb\u884c\u56db\u6b21\u7ec6\u5316\uff0c\u5f97\u5230\u4e00\u4e2a\u670916\u4e5816\u5355\u5143\u7684\u7f51\u683c\uff0c\u5171256\u4e2a\u3002 \u7136\u540e\u6211\u4eec\u5c06\u8fb9\u754c\u6307\u793a\u5668\u8bbe\u7f6e\u4e3a1\uff0c\u7528\u4e8e\u8fb9\u754c\u4e2d $x=0$ \u548c $x=5$ \u7684\u90e8\u5206\u3002\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// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u8bbe\u7f6e\u7ebf\u6027\u7cfb\u7edf\u5e76\u4e3a\u5176\u586b\u5145\u5185\u5bb9\uff0c\u4ee5\u4fbf\u5728\u6574\u4e2a\u65f6\u95f4\u6b65\u8fdb\u8fc7\u7a0b\u4e2d\u4f7f\u7528\u5b83\u4eec\u3002\n\n    setup_system(); \n\n    assemble_system(); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u4f7f\u7528\u547d\u540d\u7a7a\u95f4TimeStepping\u4e2d\u5b9e\u73b0\u7684\u51e0\u79cdRunge-Kutta\u65b9\u6cd5\u6765\u89e3\u51b3\u6269\u6563\u95ee\u9898\uff0c\u6bcf\u6b21\u90fd\u4f1a\u5728\u7ed3\u675f\u65f6\u8f93\u51fa\u8bef\u5dee\u3002(\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\uff0c\u7531\u4e8e\u7cbe\u786e\u89e3\u5728\u6700\u540e\u65f6\u95f4\u4e3a\u96f6\uff0c\u6240\u4ee5\u8bef\u5dee\u7b49\u4e8e\u6570\u503c\u89e3\uff0c\u53ea\u9700\u53d6\u89e3\u5411\u91cf\u7684 $l_2$ \u51c6\u5219\u5373\u53ef\u8ba1\u7b97\u51fa\u6765\u3002)\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// \u4e0b\u9762\u7684 <code>main</code> \u51fd\u6570\u4e0e\u524d\u9762\u7684\u4f8b\u5b50\u7c7b\u4f3c\uff0c\u4e0d\u9700\u8981\u6ce8\u91ca\u3002\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 \"rectangle.hpp\"\n\n#include <cmath>\n#include <iostream>\n#include <stdexcept>\n\n#include <boost/format.hpp>\n\n#include \"base-types.hpp\"\n\nyakovlev::Rectangle::Rectangle(double width, double height, const point_t & pos, double rotation) :\n  vertices_{\n    { pos.x + width / 2.0, pos.y + height / 2.0 },\n    { pos.x + width / 2.0, pos.y - height / 2.0 },\n    { pos.x - width / 2.0, pos.y - height / 2.0 },\n    { pos.x - width / 2.0, pos.y + height / 2.0 }\n  }\n{\n  if (width <= 0.0) {\n    throw std::invalid_argument{ (boost::format(\"Invalid rectangle width %1% - can not be negative or zero\") % width ).str() };\n  }\n  if (height <= 0.0) {\n    throw std::invalid_argument{ (boost::format(\"Invalid rectangle height %1% - can not be negative or zero\") % height ).str() };\n  }\n  rotate(rotation);\n}\n\nbool yakovlev::Rectangle::operator==(const Rectangle & other) const noexcept\n{\n  for (const point_t & vert : vertices_) {\n    bool hasEqual = false;\n    for (const point_t & othervert : other.vertices_) {\n      if (vert == othervert) {\n        hasEqual = true;\n      }\n    }\n    if (!hasEqual) {\n      return false;\n    }\n  }\n  return true;\n}\n\nbool yakovlev::Rectangle::operator!=(const Rectangle & other) const noexcept\n{\n  return !(*this == other);\n}\n\ndouble yakovlev::Rectangle::getWidth() const noexcept\n{\n  return getDistanceBetweenPoints(vertices_[1], vertices_[2]);\n}\n\ndouble  yakovlev::Rectangle::getHeight() const noexcept\n{\n  return getDistanceBetweenPoints(vertices_[0], vertices_[1]);\n}\n\nyakovlev::point_t yakovlev::Rectangle::getCenter() const noexcept\n{\n  double sumX = vertices_[0].x;\n  double sumY = vertices_[0].y;\n  for (size_t i = 1u; i < 4u; ++i) {\n    sumX += vertices_[i].x;\n    sumY += vertices_[i].y;\n  }\n  return { sumX / 4.0, sumY / 4.0 };\n}\n\ndouble yakovlev::Rectangle::getArea() const noexcept\n{\n  return getWidth() * getHeight();\n}\n\nyakovlev::rectangle_t yakovlev::Rectangle::getFrameRect() const noexcept\n{\n  double maxX = vertices_[0].x, maxY = vertices_[0].y;\n  double minX = vertices_[0].x, minY = vertices_[0].y;\n  for (int i = 1; i < 4; ++i) {\n    minX = std::min(vertices_[i].x, minX);\n    maxX = std::max(vertices_[i].x, maxX);\n    minY = std::min(vertices_[i].y, minY);\n    maxY = std::max(vertices_[i].y, maxY);\n  }\n  \n  double width = maxX - minX, height = maxY - minY;\n  return { width, height, { minX + (width / 2.0), minY + (height / 2.0) } };\n}\n\nvoid yakovlev::Rectangle::move(const point_t & pos) noexcept\n{\n  point_t center = getCenter();\n  move(pos.x - center.x, pos.y - center.y);\n}\n\nvoid yakovlev::Rectangle::move(double x, double y) noexcept\n{\n  for (point_t & vert : vertices_) {\n    vert.x += x;\n    vert.y += y;\n  }\n}\n\nvoid yakovlev::Rectangle::rotate(double rotation) noexcept\n{\n  double rad = rotation * M_PI / 180.0;\n  double rotSin = sin(rad);\n  double rotCos = cos(rad);\n  point_t pos = getCenter();\n  for (point_t & vert : vertices_) {\n    point_t local = { vert.x - pos.x, vert.y - pos.y };\n    vert = {\n        pos.x + local.x * rotCos - local.y * rotSin,\n        pos.y + local.x * rotSin + local.y * rotCos\n    };\n  }\n}\n\nvoid yakovlev::Rectangle::scale(double coef)\n{\n  if (coef <= 0.0) {\n    throw std::invalid_argument{ (boost::format(\"Invalid rectangle scale coefficient %1% - can not be negative or zero\") % coef ).str() };\n  }\n  point_t pos = getCenter();\n  for (point_t & vert : vertices_) {\n    vert = {\n        pos.x + (vert.x - pos.x) * coef,\n        pos.y + (vert.y - pos.y) * coef\n    };\n  }\n} \n\nvoid yakovlev::Rectangle::print(std::ostream & os) const\n{\n  os << \"Rectangle \" << getWidth() << \" wide, \" << getHeight()\n      << \" high placed on \" << getCenter() << '\\n';\n}\n", "meta": {"hexsha": "0a35fe9cf78d9a576e9f28e138465e71a479a8e3", "size": 3642, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/rectangle.cpp", "max_stars_repo_name": "NekoSilverFox/CPP", "max_stars_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T20:57:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T06:24:41.000Z", "max_issues_repo_path": "508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/rectangle.cpp", "max_issues_repo_name": "NekoSilverFox/CPP", "max_issues_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-02T14:44:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-11T16:25:33.000Z", "max_forks_repo_path": "508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/rectangle.cpp", "max_forks_repo_name": "NekoSilverFox/CPP", "max_forks_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-27T17:30:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T09:48:23.000Z", "avg_line_length": 26.3913043478, "max_line_length": 138, "alphanum_fraction": 0.6144975288, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5776125892987842}}
{"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    // \u03bc + \u03c3 * 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": "\ufeff#include \"testpendulum.h\"\n#include <Eigen>\n#include <Core>\nnamespace csv::internals {\nusing std::to_string;\n}\n#include \"csv.hpp\"\n\nusing namespace Eigen;\n\nMatrixXd matFromCsv(const std::string& path)\n{\n    csv::CSVFormat format;\n    format.no_header();\n    csv::CSVReader reader(path, format);\n    MatrixXd mat;\n\n    size_t maxRowSize = 0;\n    size_t rowNum = 0;\n    bool first = true;\n    for(auto& row : reader)\n    {\n        size_t col = 0;\n        if(first)\n        {\n            maxRowSize = row.size();\n            mat.resize(1000, maxRowSize);\n            first = false;\n        }\n        for(auto& field : row)\n        {\n            if(col > maxRowSize)\n            {\n                maxRowSize = col;\n                mat.conservativeResize(1000, maxRowSize);\n            }\n            mat(rowNum, col) = field.get<double>();\n            col++;\n        }\n        if(col<maxRowSize)\n            for(size_t i=1; i<=col-maxRowSize; i++)\n            {\n                mat(rowNum, col+i) = 0;\n            }\n        rowNum++;\n        if (rowNum % 1000 == 0)\n        {\n            mat.conservativeResize(rowNum+1000, maxRowSize);\n        }\n    }\n    mat.conservativeResize(rowNum, maxRowSize);\n    return mat;\n}\n\ndouble TestPendulum::d2x(double x1, double y1, double x0, double y0)\n{\n    Array4d arr = {x1, y1, x0, y0};\n    return (arr.transpose()*A1.row(0).array()).sum();\n}\n\ndouble TestPendulum::d2y(double x1, double y1, double x0, double y0)\n{\n    Array4d arr = {x1, y1, x0, y0};\n    return (arr.transpose()*A1.row(1).array()).sum();\n}\n\nvoid TestPendulum::reset()\n{\n    stop = 500;\n    x0 = 60;\n    y0 = 0;\n    x1 = 0;\n    y1 = 0;\n    x2 = d2x(x1, y1, x0, y0);\n    y2 = d2y(x1, y1, x0, y0);\n    prevLinePoint = {x0, 0, y0};\n    graph.clearLines();\n}\n\nTestPendulum::TestPendulum()\n{\n    ball = MeshRenderer::createCubeSphere(10);\n    graph.setPointSize(8);\n\n    // Import data from CSV files\n    auto data1 = matFromCsv(\"../assets/misc/data1.csv\");\n    auto data2 = matFromCsv(\"../assets/misc/data2.csv\");\n\n    // Separate matrices\n    auto data1X = data1.block(0, 0, data1.rows(), 2).transpose();\n    auto data1Z = data1.block(0, 2, data1.rows(), 4).transpose();\n\n    auto data2X = data2.block(0, 0, data2.rows(), 2).transpose();\n    auto data2Z = data2.block(0, 2, data2.rows(), 4).transpose();\n\n    // Make [Z;Z^2] matrix\n    auto Zsq = pow(data2Z.array(), 2);\n    MatrixXd ZAndZsq(Zsq.rows()*2, Zsq.cols());\n    ZAndZsq.block(0,0,Zsq.rows(), Zsq.cols()) = data2Z;\n    ZAndZsq.block(Zsq.rows(),0,Zsq.rows(), Zsq.cols()) = Zsq;\n\n    // Calculate coefficiants for linear and sqr equations\n    A1 = (data2X*data2Z.transpose())*(data2Z*data2Z.transpose()).inverse();\n    A2 = (data2X*ZAndZsq.transpose())*(ZAndZsq*ZAndZsq.transpose()).inverse();\n\n\n\n    // Calculate MSE1\n    vec3 prevPoint = {0,0,0};\n    bool first = true;\n    double MSEx1 = 0;\n    double MSEy1 = 0;\n    for(int i=0; i<data1X.cols(); i++)\n    {\n        auto ddxTrue = data1X(0, i);\n        auto ddxComp = (data1Z.col(i).transpose().array() * A1.row(0).array()).sum();\n        MSEx1 += (ddxTrue-ddxComp)*(ddxTrue-ddxComp);\n\n        auto ddyTrue = data1X(1, i);\n        auto ddyComp = (data1Z.col(i).transpose().array() * A1.row(1).array()).sum();\n        MSEy1 += (ddyTrue-ddyComp)*(ddyTrue-ddyComp);\n\n        // Add lines from data1 to graph\n        vec3 point = {data1Z(2, i), 0, data1Z(3, i)};\n        if(!first)\n        {\n            if(glm::length(prevPoint-point)>1) // only draw line if the length > 1\n            {\n                graph2.addLine(prevPoint, point, {0, 1, 0, 1});\n                prevPoint = point;\n            }\n        }\n        else\n        {\n            prevPoint = point;\n            first = false;\n        }\n    }\n    MSE1 = (MSEx1+MSEy1)/(data1X.cols()*2);\n\n    // Calculate MSE2\n    double MSEx2 = 0;\n    double MSEy2 = 0;\n    auto Zsq1 = pow(data1Z.array(), 2);\n    MatrixXd ZAndZsq1(Zsq1.rows()*2, Zsq1.cols());\n    ZAndZsq1.block(0,0,Zsq1.rows(), Zsq1.cols()) = data1Z;\n    ZAndZsq1.block(Zsq1.rows(),0,Zsq1.rows(), Zsq1.cols()) = Zsq1;\n\n    for(int i=0; i<data1X.cols(); i++)\n    {\n\n        auto ddxTrue = data1X(0, i);\n        auto ddxComp = (ZAndZsq1.col(i).transpose().array() * A2.row(0).array()).sum();\n        MSEx2 += (ddxTrue-ddxComp)*(ddxTrue-ddxComp);\n\n        auto ddyTrue = data1X(1, i);\n        auto ddyComp = (ZAndZsq1.col(i).transpose().array() * A2.row(1).array()).sum();\n        MSEy2 += (ddyTrue-ddyComp)*(ddyTrue-ddyComp);\n//        std::cout<<\"MSEx2 += (\"<<ddxTrue<<\" - \"<<ddxComp<<\") ^2\\n\";\n//        std::cout<<\"MSEy2 += (\"<<ddyTrue<<\" - \"<<ddyComp<<\") ^2\\n\";\n    }\n    MSE2 = (MSEx2+MSEy2)/(data1X.cols()*2);\n}\n\nvoid TestPendulum::onStart()\n{\n    GraphicsContext::setClearColor({0.184f, 0.200f, 0.329f, 1.f});\n    auto camera = GraphicsContext::getCamera();\n    camera->setFov(50.f);\n    camera->setPosition({0 ,50.f,50});\n    camera->setFocusPoint({0,0,0});\n    reset();\n    std::cout<<\"A1:\\n\"<<A1<<\"\\n\\n\";\n    std::cout<<\"A2:\\n\"<<A2<<\"\\n\\n\\n\";\n    std::cout<<\"MSE1: \"<<MSE1<<\"\\n\";\n    std::cout<<\"MSE2: \"<<MSE2<<\"\\n\";\n}\n\nvoid TestPendulum::onUpdate(float dt)\n{\n    // Controls\n    if(App::getKeyOnce(GLFW_KEY_KP_SUBTRACT))\n        dtMulti -= 1;\n    if(App::getKeyOnce(GLFW_KEY_KP_ADD))\n        dtMulti += 1;\n    if(App::getKeyOnce(GLFW_KEY_SPACE))\n        reset();\n\n    // Clear ball and its line\n    graph.clearPoints();\n    graph.removeLastLine();\n\n    // Simulate pendulum\n    double timeToSim = dt*dtMulti;\n    if(stop>0)\n    {\n        uint simSteps = (uint)(timeToSim/h);\n        for(uint i=0; i<simSteps; i++)\n        {\n            x0 = x0 + h*x1;\n            x1 = x1 + h*x2;\n\n            y0 = y0 + h*y1;\n            y1 = y1 + h*y2;\n\n            x2 = d2x(x1, y1, x0, y0);\n            y2 = d2y(x1, y1, x0, y0);\n        }\n        stop-=timeToSim;\n    }\n    vec3 point = {x0, 0, y0};\n    if(glm::length(prevLinePoint-point)>1)\n    {\n        graph.addLine(prevLinePoint, point, {1,0,0,1});\n        prevLinePoint = point;\n    }\n\n    // Draw\n    float lh = 90;\n    vec3 lv = point - vec3{0, 100, 0};\n    point.y = 100-sqrt(lh*lh - lv.x*lv.x - lv.z*lv.z);\n    graph.addPoints(&point, 1, {1,0,0,1});\n    graph.addLine({0, 100, 0}, point, {1,1,1,1});\n    graph.draw ({-22,0,0},dt);\n    graph2.draw({ 2,0,0},dt);\n}\n", "meta": {"hexsha": "f504b64d88ec86ccbe65fec505175e9b5604e9ac", "size": 6241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "old_tests/testpendulum.cpp", "max_stars_repo_name": "lou000/Primor_Engine", "max_stars_repo_head_hexsha": "a73d80b44d21667a293d77fee7be761b6b3e5832", "max_stars_repo_licenses": ["MIT"], "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_tests/testpendulum.cpp", "max_issues_repo_name": "lou000/Primor_Engine", "max_issues_repo_head_hexsha": "a73d80b44d21667a293d77fee7be761b6b3e5832", "max_issues_repo_licenses": ["MIT"], "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_tests/testpendulum.cpp", "max_forks_repo_name": "lou000/Primor_Engine", "max_forks_repo_head_hexsha": "a73d80b44d21667a293d77fee7be761b6b3e5832", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-14T18:05:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T22:09:51.000Z", "avg_line_length": 27.4933920705, "max_line_length": 87, "alphanum_fraction": 0.5390161833, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.577505599182502}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/LU>\n\n#include \"apriltag_mit/AprilTags/GrayModel.h\"\n\nnamespace AprilTags {\n\nvoid GrayModel::AddBlackObs(float x, float y, float v) {\n  black_model_.AddObservation(x, y, v);\n}\n\nvoid GrayModel::AddWhiteObs(float x, float y, float v) {\n  white_model_.AddObservation(x, y, v);\n}\n\nvoid GrayModel::Fit() {\n  black_model_.Fit();\n  white_model_.Fit();\n}\n\nfloat GrayModel::CalcThreshold(float x, float y) const {\n  return (black_model_.Predict(x, y) + white_model_.Predict(x, y)) / 2;\n}\n\nIntensityModel::IntensityModel()\n    : A_(), c_(), b_(), num_obs_(0), dirty_(false) {\n  A_.setZero();\n  c_.setZero();\n  b_.setZero();\n}\n\nvoid IntensityModel::AddObservation(float x, float y, float v) {\n  float xy = x * y;\n\n  // update only upper-right elements. A'A is symmetric,\n  // we'll fill the other elements in later.\n  A_(0, 0) += x * x;\n  A_(0, 1) += x * y;\n  A_(0, 2) += x * xy;\n  A_(0, 3) += x;\n  A_(1, 1) += y * y;\n  A_(1, 2) += y * xy;\n  A_(1, 3) += y;\n  A_(2, 2) += xy * xy;\n  A_(2, 3) += xy;\n  A_(3, 3) += 1;\n\n  b_[0] += x * v;\n  b_[1] += y * v;\n  b_[2] += xy * v;\n  b_[3] += v;\n\n  num_obs_++;\n  dirty_ = true;\n}\n\nfloat IntensityModel::Predict(float x, float y) const {\n  return c_[0] * x + c_[1] * y + c_[2] * x * y + c_[3];\n}\n\nvoid IntensityModel::Fit() {\n  // we really only need 4 linearly independent observations to fit our answer,\n  // but we'll be very sensitive to noise if we don't have an over-determined\n  // system. Thus, require at least 6 observations (or we'll use a constant\n  // model below).\n\n  if (num_obs_ >= 6) {\n    // make symmetric\n    for (int i = 0; i < 4; ++i) {\n      for (int j = i + 1; j < 4; ++j) {\n        A_(j, i) = A_(i, j);\n      }\n    }\n\n    bool invertible;\n    double det_unused;\n    Eigen::Matrix4d Ainv;\n    A_.computeInverseAndDetWithCheck(Ainv, det_unused, invertible);\n    if (invertible) {\n      c_ = Ainv * b_;\n      return;\n    }\n  }\n\n  // If we get here, either nobs < 6 or the matrix inverse generated\n  // an underflow, so use a constant model.\n  c_.setZero(); // need the cast to avoid operator= ambiguity wrt. const-ness\n  c_[3] = b_[3] / num_obs_;\n}\n\nbool IsOnOuterBorder(int x, int y, int l, bool black_corner) {\n  if (black_corner) {\n    // Black corners will be excluded\n    const bool on_corner = (x == -1 && y == -1) || (x == -1 && y == l) ||\n                           (x == l && y == -1) || (x == l && y == l);\n    return (y == -1 || y == l || x == -1 || x == l) && !on_corner;\n  } else {\n    return (y == -1 || y == l || x == -1 || x == l);\n  }\n}\n\nbool IsOnInnerBorder(int x, int y, int l) {\n  return (y == 0 || y == (l - 1) || x == 0 || x == (l - 1));\n}\n\nbool IsInsideInnerBorder(int x, int y, int l) {\n  return (y >= 1 && y < (l - 1) && x >= 1 && x < (l - 1));\n}\n\n} // namespace AprilTags\n", "meta": {"hexsha": "617bff027a3d009800db8a4cac75c3cec499eed8", "size": 2784, "ext": "cc", "lang": "C++", "max_stars_repo_path": "apriltag_mit/src/GrayModel.cc", "max_stars_repo_name": "versatran01/sv_fiducial", "max_stars_repo_head_hexsha": "7e054d975f4da423d1e230ec699512e6c83e3261", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2016-08-11T13:50:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T22:27:45.000Z", "max_issues_repo_path": "apriltag_mit/src/GrayModel.cc", "max_issues_repo_name": "versatran01/sv_fiducial", "max_issues_repo_head_hexsha": "7e054d975f4da423d1e230ec699512e6c83e3261", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-08-29T12:41:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-07T22:06:04.000Z", "max_forks_repo_path": "apriltag_mit/src/GrayModel.cc", "max_forks_repo_name": "versatran01/sv_fiducial", "max_forks_repo_head_hexsha": "7e054d975f4da423d1e230ec699512e6c83e3261", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2016-08-09T00:54:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T13:20:17.000Z", "avg_line_length": 25.0810810811, "max_line_length": 79, "alphanum_fraction": 0.5599856322, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.577505599182502}}
{"text": "#include <catch2/catch.hpp>\n#include <Euclid/Geometry/TriMeshGeometry.h>\n\n#include <string>\n#include <vector>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseCholesky>\n#include <Euclid/IO/OffIO.h>\n#include <Euclid/IO/PlyIO.h>\n#include <Euclid/MeshUtil/CGALMesh.h>\n#include <Euclid/MeshUtil/EigenMesh.h>\n#include <Euclid/Util/Color.h>\n#include <igl/invert_diag.h>\n\n#include <config.h>\n\nusing Kernel = CGAL::Simple_cartesian<float>;\nusing Point_3 = typename Kernel::Point_3;\nusing Vector_3 = typename Kernel::Vector_3;\nusing Mesh = CGAL::Surface_mesh<Point_3>;\n\nTEST_CASE(\"Geometry, TriMeshGeometry\", \"[geometry][trimeshgeometry]\")\n{\n    std::string fcube(DATA_DIR);\n    fcube.append(\"cube_ascii.ply\");\n    std::vector<float> cpositions;\n    std::vector<int> cindices;\n    Euclid::read_ply<3>(\n        fcube, cpositions, nullptr, nullptr, &cindices, nullptr);\n    Mesh cube;\n    Euclid::make_mesh<3>(cube, cpositions, cindices);\n\n    std::string fbumpy(DATA_DIR);\n    fbumpy.append(\"bumpy.off\");\n    std::vector<float> bpositions;\n    std::vector<int> bindices;\n    Euclid::read_off<3>(fbumpy, bpositions, nullptr, &bindices, nullptr);\n    Mesh bumpy;\n    Euclid::make_mesh<3>(bumpy, bpositions, bindices);\n    Eigen::MatrixXf bumpy_v;\n    Eigen::MatrixXi bumpy_f;\n    Euclid::make_mesh<3>(bumpy_v, bumpy_f, bpositions, bindices);\n\n    SECTION(\"vertex normal\")\n    {\n        auto fnormals = Euclid::face_normals(bumpy);\n\n        SECTION(\"uniform\")\n        {\n            auto w = Euclid::VertexNormal::uniform;\n            std::vector<float> vnormals1;\n            for (auto v : vertices(bumpy)) {\n                auto vn1 = Euclid::vertex_normal(v, bumpy, w);\n                auto vn2 = Euclid::vertex_normal(v, bumpy, fnormals, w);\n                REQUIRE(vn1 == vn2);\n                vnormals1.push_back(vn1.x());\n                vnormals1.push_back(vn1.y());\n                vnormals1.push_back(vn1.z());\n            }\n            auto vnormals2 = Euclid::vertex_normals(bumpy, fnormals, w);\n            REQUIRE(vnormals1.size() == vnormals2.size() * 3);\n            REQUIRE(vnormals1[0] == vnormals2[0].x());\n            REQUIRE(vnormals1[1] == vnormals2[0].y());\n            REQUIRE(vnormals1[2] == vnormals2[0].z());\n\n            for (auto& n : vnormals1) {\n                n = (n + 1.0f) * 127.5f;\n            }\n            std::string fout(TMP_DIR);\n            fout.append(\"bumpy_vn_uniform.ply\");\n            Euclid::write_ply<3>(\n                fout, bpositions, nullptr, nullptr, &bindices, &vnormals1);\n        }\n\n        SECTION(\"face_area\")\n        {\n            auto w = Euclid::VertexNormal::face_area;\n            std::vector<float> vnormals1;\n            for (auto v : vertices(bumpy)) {\n                auto vn1 = Euclid::vertex_normal(v, bumpy, w);\n                auto vn2 = Euclid::vertex_normal(v, bumpy, fnormals, w);\n                REQUIRE(vn1 == vn2);\n                vnormals1.push_back(vn1.x());\n                vnormals1.push_back(vn1.y());\n                vnormals1.push_back(vn1.z());\n            }\n            auto vnormals2 = Euclid::vertex_normals(bumpy, fnormals, w);\n            REQUIRE(vnormals1.size() == vnormals2.size() * 3);\n            REQUIRE(vnormals1[0] == vnormals2[0].x());\n            REQUIRE(vnormals1[1] == vnormals2[0].y());\n            REQUIRE(vnormals1[2] == vnormals2[0].z());\n\n            for (auto& n : vnormals1) {\n                n = (n + 1.0f) * 127.5f;\n            }\n            std::string fout(TMP_DIR);\n            fout.append(\"bumpy_vn_area.ply\");\n            Euclid::write_ply<3>(\n                fout, bpositions, nullptr, nullptr, &bindices, &vnormals1);\n        }\n\n        SECTION(\"incident angle\")\n        {\n            auto w = Euclid::VertexNormal::incident_angle;\n            std::vector<float> vnormals1;\n            for (auto v : vertices(bumpy)) {\n                auto vn1 = Euclid::vertex_normal(v, bumpy, w);\n                auto vn2 = Euclid::vertex_normal(v, bumpy, fnormals, w);\n                REQUIRE(vn1 == vn2);\n                vnormals1.push_back(vn1.x());\n                vnormals1.push_back(vn1.y());\n                vnormals1.push_back(vn1.z());\n            }\n            auto vnormals2 = Euclid::vertex_normals(bumpy, fnormals, w);\n            REQUIRE(vnormals1.size() == vnormals2.size() * 3);\n            REQUIRE(vnormals1[0] == vnormals2[0].x());\n            REQUIRE(vnormals1[1] == vnormals2[0].y());\n            REQUIRE(vnormals1[2] == vnormals2[0].z());\n\n            for (auto& n : vnormals1) {\n                n = (n + 1.0f) * 127.5f;\n            }\n            std::string fout(TMP_DIR);\n            fout.append(\"bumpy_vn_angle.ply\");\n            Euclid::write_ply<3>(\n                fout, bpositions, nullptr, nullptr, &bindices, &vnormals1);\n        }\n    }\n\n    SECTION(\"veretx area\")\n    {\n        SECTION(\"barycentric\")\n        {\n            auto w = Euclid::VertexArea::barycentric;\n            std::vector<float> vareas1;\n            for (auto v : vertices(bumpy)) {\n                auto va = Euclid::vertex_area(v, bumpy, w);\n                vareas1.push_back(va);\n                vareas1.push_back(0.0f);\n                vareas1.push_back(0.0f);\n            }\n            auto vareas2 = Euclid::vertex_areas(bumpy, w);\n            REQUIRE(vareas1.size() == vareas2.size() * 3);\n            REQUIRE(vareas1[0] == vareas2[0]);\n\n            auto amax = *std::max_element(vareas1.begin(), vareas1.end());\n            amax = 1.0f / amax;\n            for (auto& a : vareas1) {\n                a *= amax * 255.0f;\n            }\n            std::string fout(TMP_DIR);\n            fout.append(\"bumpy_va_barycentric.ply\");\n            Euclid::write_ply<3>(\n                fout, bpositions, nullptr, nullptr, &bindices, &vareas1);\n        }\n\n        SECTION(\"voronoi\")\n        {\n            auto w = Euclid::VertexArea::voronoi;\n            std::vector<float> vareas1;\n            for (auto v : vertices(bumpy)) {\n                auto va = Euclid::vertex_area(v, bumpy, w);\n                vareas1.push_back(va);\n                vareas1.push_back(0.0f);\n                vareas1.push_back(0.0f);\n            }\n            auto vareas2 = Euclid::vertex_areas(bumpy, w);\n            REQUIRE(vareas1.size() == vareas2.size() * 3);\n            REQUIRE(vareas1[0] == vareas2[0]);\n\n            auto amax = *std::max_element(vareas1.begin(), vareas1.end());\n            amax = 1.0f / amax;\n            for (auto& a : vareas1) {\n                a *= amax * 255.0f;\n            }\n            std::string fout(TMP_DIR);\n            fout.append(\"bumpy_va_voronoi.ply\");\n            Euclid::write_ply<3>(\n                fout, bpositions, nullptr, nullptr, &bindices, &vareas1);\n        }\n\n        SECTION(\"mixed voronoi\")\n        {\n            auto w = Euclid::VertexArea::mixed_voronoi;\n            std::vector<float> vareas1;\n            for (auto v : vertices(bumpy)) {\n                auto va = Euclid::vertex_area(v, bumpy, w);\n                vareas1.push_back(va);\n                vareas1.push_back(0.0f);\n                vareas1.push_back(0.0f);\n            }\n            auto vareas2 = Euclid::vertex_areas(bumpy, w);\n            REQUIRE(vareas1.size() == vareas2.size() * 3);\n            REQUIRE(vareas1[0] == vareas2[0]);\n\n            auto amax = *std::max_element(vareas1.begin(), vareas1.end());\n            amax = 1.0f / amax;\n            for (auto& a : vareas1) {\n                a *= amax * 255.0f;\n            }\n            std::string fout(TMP_DIR);\n            fout.append(\"bumpy_va_mixed.ply\");\n            Euclid::write_ply<3>(\n                fout, bpositions, nullptr, nullptr, &bindices, &vareas1);\n        }\n    }\n\n    SECTION(\"edge length and squared length\")\n    {\n        auto [ebeg, eend] = edges(cube);\n        auto e = *(++ebeg);\n        auto he = halfedge(e, cube);\n        auto elens = Euclid::edge_lengths(cube);\n        auto sq_elens = Euclid::squared_edge_lengths(cube);\n\n        REQUIRE(Euclid::edge_length(e, cube) == Approx(2.0f));\n        REQUIRE(Euclid::edge_length(he, cube) == Approx(2.0f));\n        REQUIRE(elens[1] == Approx(2.0f));\n        REQUIRE(elens.size() == num_edges(cube));\n\n        REQUIRE(Euclid::squared_edge_length(e, cube) == Approx(4.0f));\n        REQUIRE(Euclid::squared_edge_length(he, cube) == Approx(4.0f));\n        REQUIRE(sq_elens[1] == Approx(4.0f));\n        REQUIRE(sq_elens.size() == num_edges(cube));\n    }\n\n    SECTION(\"face normal\")\n    {\n        auto [fbeg, fend] = faces(cube);\n        auto f = *fbeg;\n        REQUIRE(Euclid::face_normal(f, cube) == Vector_3(0.0f, 0.0f, -1.0f));\n\n        auto fnormals = Euclid::face_normals(cube);\n        REQUIRE(fnormals.size() == num_faces(cube));\n        REQUIRE(fnormals[0] == Vector_3(0.0f, 0.0f, -1.0f));\n    }\n\n    SECTION(\"face area\")\n    {\n        auto [fbeg, fend] = faces(cube);\n        auto f = *fbeg;\n        auto fareas = Euclid::face_areas(cube);\n\n        REQUIRE(Euclid::face_area(f, cube) == 2.0f);\n        REQUIRE(fareas.size() == num_faces(cube));\n        REQUIRE(fareas[0] == 2.0f);\n    }\n\n    SECTION(\"face barycenter\")\n    {\n        auto [fbeg, fend] = faces(cube);\n        auto f = *fbeg;\n        auto c = Euclid::barycenter(f, cube);\n        auto centroids = Euclid::barycenters(cube);\n\n        REQUIRE(c.x() == Approx(-1.0 / 3.0));\n        REQUIRE(c.y() == Approx(1.0 / 3.0));\n        REQUIRE(c.z() == -1.0);\n        REQUIRE(centroids[0] == c);\n    }\n\n    SECTION(\"gaussian curvature\")\n    {\n        std::vector<float> gaussian_curvatures;\n        for (auto v : vertices(bumpy)) {\n            auto c = Euclid::gaussian_curvature(v, bumpy);\n            gaussian_curvatures.push_back(c);\n        }\n\n        auto [vbeg, vend] = vertices(bumpy);\n        auto curvatures = Euclid::gaussian_curvatures(bumpy);\n        REQUIRE(Euclid::gaussian_curvature(*vbeg, bumpy) == curvatures[0]);\n        REQUIRE(curvatures.size() == num_vertices(bumpy));\n\n        std::vector<uint8_t> colors;\n        Euclid::colormap(igl::COLOR_MAP_TYPE_JET, curvatures, colors, true);\n        std::string fout(TMP_DIR);\n        fout.append(\"bumpy_gaussian_curvature.ply\");\n        Euclid::write_ply<3>(\n            fout, bpositions, nullptr, nullptr, &bindices, &colors);\n    }\n\n    SECTION(\"mean curvature w/ laplace beltrami operator\")\n    {\n        auto laplacian = Euclid::cotangent_matrix(bumpy);\n        auto mass = Euclid::mass_matrix(bumpy);\n        Eigen::SparseMatrix<float> inv_mass;\n        igl::invert_diag(mass, inv_mass);\n        Eigen::MatrixXf hn = inv_mass * laplacian * bumpy_v;\n        Eigen::VectorXf norms = hn.rowwise().norm();\n\n        std::vector<float> mean_curvatures(hn.rows() * 3);\n        auto nmax = norms.maxCoeff();\n        nmax = 255.0 / nmax;\n        for (int i = 0; i < hn.rows(); ++i) {\n            mean_curvatures[i * 3 + 0] = norms(i) * nmax;\n            mean_curvatures[i * 3 + 1] = 0.0f;\n            mean_curvatures[i * 3 + 2] = 0.0f;\n        }\n        std::string fout(TMP_DIR);\n        fout.append(\"bumpy_mean_curvature_lbo.ply\");\n        Euclid::write_ply<3>(\n            fout, bpositions, nullptr, nullptr, &bindices, &mean_curvatures);\n    }\n\n    SECTION(\"mean curvature w/ graph laplacian operator\")\n    {\n        auto [adj, degree] = Euclid::adjacency_matrix(bumpy);\n        auto laplacian = degree - adj;\n        Eigen::SparseMatrix<float> inv_degree;\n        igl::invert_diag(degree, inv_degree);\n        Eigen::MatrixXf hn = inv_degree * laplacian * bumpy_v;\n        Eigen::VectorXf norms = hn.rowwise().norm();\n\n        std::vector<float> mean_curvatures(hn.rows() * 3);\n        auto nmax = norms.maxCoeff();\n        nmax = 255.0 / nmax;\n        for (int i = 0; i < hn.rows(); ++i) {\n            mean_curvatures[i * 3 + 0] = norms(i) * nmax;\n            mean_curvatures[i * 3 + 1] = 0.0f;\n            mean_curvatures[i * 3 + 2] = 0.0f;\n        }\n        std::string fout(TMP_DIR);\n        fout.append(\"bumpy_mean_curvature_gl.ply\");\n        Euclid::write_ply<3>(\n            fout, bpositions, nullptr, nullptr, &bindices, &mean_curvatures);\n    }\n}\n", "meta": {"hexsha": "8cf5ee7fda72e7d40ec3813f3fa25658a7636c86", "size": 12081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Geometry/test_TriMeshGeometry.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "test/Geometry/test_TriMeshGeometry.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Geometry/test_TriMeshGeometry.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 36.2792792793, "max_line_length": 77, "alphanum_fraction": 0.5444913501, "num_tokens": 3435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5774498548324407}}
{"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": "// This scripts runs the simulations with four populations (Section 6.1)\n\n#include <src/algorithms/neal2_algorithm.h>\n#include <src/algorithms/semihdp_sampler.h>\n#include <src/collectors/file_collector.h>\n#include <src/collectors/memory_collector.h>\n#include <src/includes.h>\n#include <src/utils/rng.h>\n\n#include <Eigen/Dense>\n#include <chrono>\n#include <stan/math/prim.hpp>\n#include <vector>\n\nusing Eigen::MatrixXd;\n\nMatrixXd generate_mixture(double m1, double s1, double m2, double s2, double w,\n                          int n, std::mt19937_64& rng) {\n  MatrixXd out(n, 1);\n  for (int i = 0; i < n; i++) {\n    if (stan::math::uniform_rng(0, 1, rng) < w) {\n      out(i, 0) = stan::math::normal_rng(m1, s1, rng);\n    } else {\n      out(i, 0) = stan::math::normal_rng(m2, s2, rng);\n    }\n  }\n  return out;\n}\n\nvoid run_semihdp2(const std::vector<MatrixXd> data, std::string chainfile,\n                  std::string update_c = \"full\") {\n  // compute overall mean\n  double mu0 = std::accumulate(\n      data.begin(), data.end(), 0,\n      [&](int curr, const MatrixXd dat) { return curr + dat.sum(); });\n  mu0 /= std::accumulate(\n      data.begin(), data.end(), 0.0,\n      [&](int curr, const MatrixXd dat) { return curr + dat.rows(); });\n  auto hier = std::make_shared<NNIGHierarchy>();\n  bayesmix::NNIGPrior hier_prior;\n  hier_prior.mutable_fixed_values()->set_mean(mu0);\n  hier_prior.mutable_fixed_values()->set_var_scaling(0.1);\n  hier_prior.mutable_fixed_values()->set_shape(2.0);\n  hier_prior.mutable_fixed_values()->set_scale(2.0);\n  hier->get_mutable_prior()->CopyFrom(hier_prior);\n  hier->initialize();\n\n  // Collect pseudo priors\n  std::vector<MemoryCollector> pseudoprior_collectors;\n  pseudoprior_collectors.resize(data.size());\n  bayesmix::DPPrior mix_prior;\n  double totalmass = 1.0;\n  mix_prior.mutable_fixed_value()->set_totalmass(totalmass);\n#pragma omp parallel for\n  for (int i = 0; i < data.size(); i++) {\n    auto mixing = std::make_shared<DirichletMixing>();\n    mixing->get_mutable_prior()->CopyFrom(mix_prior);\n    mixing->set_num_components(5);\n    auto hier = std::make_shared<NNIGHierarchy>();\n    bayesmix::NNIGPrior hier_prior;\n    hier_prior.mutable_fixed_values()->set_mean(data[i].mean());\n    hier_prior.mutable_fixed_values()->set_var_scaling(0.1);\n    hier_prior.mutable_fixed_values()->set_shape(2.0);\n    hier_prior.mutable_fixed_values()->set_scale(2.0);\n    hier->get_mutable_prior()->CopyFrom(hier_prior);\n\n    Neal2Algorithm sampler;\n    sampler.set_maxiter(2000);\n    sampler.set_burnin(1000);\n    sampler.set_mixing(mixing);\n    sampler.set_data(data[i]);\n    sampler.set_hierarchy(hier);\n    sampler.run(&pseudoprior_collectors[i], false);\n  }\n\n  auto start = std::chrono::high_resolution_clock::now();\n  int nburn = 5000;\n  int niter = 5000;\n  MemoryCollector collector;\n\n  bayesmix::SemiHdpParams params;\n  bayesmix::read_proto_from_file(\n      \"/home/mario/dev/bayesmix/resources/semihdp_params.asciipb\", &params);\n  params.set_rest_allocs_update(update_c);\n\n  SemiHdpSampler sampler(data, hier, params);\n  sampler.run(500, nburn, niter, 5, &collector, pseudoprior_collectors, true,\n              200);\n  auto end = std::chrono::high_resolution_clock::now();\n  auto duration =\n      std::chrono::duration_cast<std::chrono::seconds>(end - start).count();\n  std::cout << \"Finished running, duration: \" << duration << std::endl;\n  collector.write_to_file<bayesmix::SemiHdpState>(chainfile);\n}\n\nint main() {\n  // Scenario VII\n  std::vector<MatrixXd> data(100);\n\n  auto& rng = bayesmix::Rng::Instance().get();\n\n  for (int i = 0; i < 20; i++) {\n    auto rng = bayesmix::Rng::Instance().get();\n    data[i] = generate_mixture(-5, 1.0, 5, 1.0, 0.5, 100, rng);\n  }\n  for (int i = 20; i < 40; i++) {\n    auto rng = bayesmix::Rng::Instance().get();\n    data[i] = generate_mixture(-5.0, 1.0, 0.0, 1.0, 0.5, 100, rng);\n  }\n  for (int i = 40; i < 60; i++) {\n    auto rng = bayesmix::Rng::Instance().get();\n    data[i] = generate_mixture(0.0, 1.0, 5.0, 0.1, 0.5, 100, rng);\n  }\n  for (int i = 60; i < 80; i++) {\n    auto rng = bayesmix::Rng::Instance().get();\n    data[i] = generate_mixture(-10, 1.0, 0.0, 1.0, 0.5, 100, rng);\n  }\n  for (int i = 80; i < 100; i++) {\n    auto rng = bayesmix::Rng::Instance().get();\n    data[i] = generate_mixture(-10, 1.0, 0.0, 1.0, 0.1, 100, rng);\n  }\n\n  run_semihdp2(data,\n               \"/home/mario/PhD/exchangeability/semihdp-scripts/\"\n               \"new_chains/s100.recordio\",\n               \"metro_dist\");\n}", "meta": {"hexsha": "3764251ab01892800b7b58ff1c2b4a560c307d7f", "size": 4473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "run_simulation_many.cpp", "max_stars_repo_name": "mberaha/semihdp-scripts", "max_stars_repo_head_hexsha": "fbf5e9c97644096357912c05bb8b4d7715d01b9e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "run_simulation_many.cpp", "max_issues_repo_name": "mberaha/semihdp-scripts", "max_issues_repo_head_hexsha": "fbf5e9c97644096357912c05bb8b4d7715d01b9e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "run_simulation_many.cpp", "max_forks_repo_name": "mberaha/semihdp-scripts", "max_forks_repo_head_hexsha": "fbf5e9c97644096357912c05bb8b4d7715d01b9e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2204724409, "max_line_length": 79, "alphanum_fraction": 0.6552649229, "num_tokens": 1378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5774266975919659}}
{"text": "#define BOOST_TEST_MODULE test_onecellcadbug\n\n#include <optional>\n\n#include <boost/test/unit_test.hpp>\n\n#include <smtrat-common/smtrat-common.h>\n#include <smtrat-mcsat/smtrat-mcsat.h>\n\n#include <carl/core/MultivariatePolynomial.h>\n#include <carl/core/Variable.h>\n#include <carl/formula/model/evaluation/ModelEvaluation.h>\n\n#include <smtrat-mcsat/explanations/onecellcad/Explanation.h>\n\n\nusing namespace smtrat;\n\nBOOST_AUTO_TEST_CASE(OneCellCadBug) {\n\t// Variable x cannot be assigned for x^2 + x^4 + b*x^3 <= 0 , x != 0 under b -> -1\n\t\n\tcarl::Variable x = carl::freshRealVariable(\"x\");\n\tcarl::Variable b = carl::freshRealVariable(\"b\");\n  carl::Variables vars({x,b});\n\n\tFormulaT f1(ConstraintT((Poly(x)*x) + (Poly(x)*x*x*x) + (Poly(b)*x*x*x), carl::Relation::LEQ));\n  FormulaT f2(ConstraintT(x, carl::Relation::NEQ));\n\n\t// generate explanation\n  mcsat::Bookkeeping bookkeeping;\n  bookkeeping.updateVariables(vars);\n  bookkeeping.pushConstraint(f1);\n  bookkeeping.pushConstraint(f2);\n  bookkeeping.pushAssignment(b, Rational(-1), FormulaT(carl::FormulaType::TRUE));\n  ::smtrat::mcsat::onecellcad::Explanation expl;\n  auto explanation = expl(bookkeeping, x, FormulasT({f1,f2}));\n\n\n  // proof that satisfying assignment exist\n  Model model;\n\tmodel.assign(b, Rational(-5));\n  model.assign(x, Rational(1));\n\n  auto res = carl::model::evaluate(f1, model);\n\tBOOST_CHECK(res.isBool() && res.asBool());\n  auto res1 = carl::model::evaluate(f2, model);\n\tBOOST_CHECK(res1.isBool() && res1.asBool());\n\n  auto res2 = carl::model::evaluate(boost::get<FormulaT>(*explanation), model);\n  BOOST_CHECK(res2.isBool());\n  BOOST_CHECK(res2.asBool());\n}", "meta": {"hexsha": "f22a3a24e4d6b1c16fb5c3df3e2cdf4a9af66a70", "size": 1629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/onecellcad/Test_OneCellCADBug.cpp", "max_stars_repo_name": "modass/smtrat", "max_stars_repo_head_hexsha": "2e6909bb764cf30d6afc231a2d447dfc13f3fa40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/onecellcad/Test_OneCellCADBug.cpp", "max_issues_repo_name": "modass/smtrat", "max_issues_repo_head_hexsha": "2e6909bb764cf30d6afc231a2d447dfc13f3fa40", "max_issues_repo_licenses": ["MIT"], "max_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/onecellcad/Test_OneCellCADBug.cpp", "max_forks_repo_name": "modass/smtrat", "max_forks_repo_head_hexsha": "2e6909bb764cf30d6afc231a2d447dfc13f3fa40", "max_forks_repo_licenses": ["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.3269230769, "max_line_length": 96, "alphanum_fraction": 0.7188459177, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5774266829871927}}
{"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": "#pragma once\n\n#include \"permutation.hxx\"\n#include <Eigen/OrderingMethods>\n#include <vector>\n#include <limits>\n\nnamespace LPMP {\n\n    template<typename ADJACENCY_GRAPH>\n    permutation minimum_degree_ordering(const ADJACENCY_GRAPH& adj, const size_t nr_vars)\n    {\n        MEASURE_FUNCTION_EXECUTION_TIME;\n        Eigen::AMDOrdering<int> ordering;\n        Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic, int> perm(adj.size());\n        Eigen::SparseMatrix<double> A(adj.size(), adj.size()); \n        std::vector< Eigen::Triplet<double> > adjacency_list;\n        for(std::size_t i=0; i<adj.size(); ++i) {\n            for(const std::size_t j : adj[i]) {\n                assert(j <= std::numeric_limits<int>::max());\n                adjacency_list.push_back({i,j,1.0});\n                adjacency_list.push_back({i,j,1.0});\n            }\n        }\n        A.setFromTriplets(adjacency_list.begin(), adjacency_list.end());\n        ordering(A, perm);\n        permutation o;\n        for(std::size_t i=0; i<perm.indices().size(); ++i) {\n            if (perm.indices()[i] < nr_vars)\n                o.push_back(perm.indices()[i]);\n        }\n        assert(is_permutation(o.begin(), o.end()));\n        return o; \n    }\n\n\n} \n", "meta": {"hexsha": "5bc58edf885396751e2b69816a24ca1b3aaf9510", "size": 1220, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/minimum_degree_ordering.hxx", "max_stars_repo_name": "aabbas90/BDD", "max_stars_repo_head_hexsha": "abab0c746a22ae04e8ca5ceacbec1d8f75b758bb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-20T11:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:43:14.000Z", "max_issues_repo_path": "include/minimum_degree_ordering.hxx", "max_issues_repo_name": "aabbas90/BDD", "max_issues_repo_head_hexsha": "abab0c746a22ae04e8ca5ceacbec1d8f75b758bb", "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/minimum_degree_ordering.hxx", "max_forks_repo_name": "aabbas90/BDD", "max_forks_repo_head_hexsha": "abab0c746a22ae04e8ca5ceacbec1d8f75b758bb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-03-31T15:26:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:58:01.000Z", "avg_line_length": 32.1052631579, "max_line_length": 89, "alphanum_fraction": 0.587704918, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5773761673259755}}
{"text": "/*\r\nCopyright (c) 2017 InversePalindrome\r\nInPal - GrapherPanel.cpp\r\nInversePalindrome.com\r\n*/\r\n\r\n\r\n#include \"GrapherPanel.hpp\"\r\n\r\n#include <wx/sizer.h>\r\n#include <wx/button.h>\r\n#include <wx/choice.h>\r\n\r\n#include <boost/algorithm/string/replace.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n\r\n#include <algorithm>\r\n\r\n\r\nGrapherPanel::GrapherPanel(wxWindow* parent, MathDataDefault* mathData) :\r\n    wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, \"GrapherPanel\"),\r\n    mathData(mathData),\r\n    graphText(new wxStaticText(this, wxID_ANY, \"F(x) = \")),\r\n    graphEntry(new wxTextCtrl(this, wxID_ANY, \"\", wxDefaultPosition, wxSize(550u, 0u)))\r\n{\r\n    SetBackgroundColour(wxColor(128u, 128u, 128u));\r\n\r\n    mathData->graphData.plotWindow = new mpWindow(this, wxID_ANY, wxDefaultPosition, wxSize(100u, 100u), wxSUNKEN_BORDER);\r\n    mathData->graphData.graphType = \"Cartesian\";\r\n    mathData->graphData.minX = -10;\r\n    mathData->graphData.maxX = 10;\r\n\r\n    auto* topSizer = new wxBoxSizer(wxVERTICAL);\r\n    auto* bottomSizer = new wxBoxSizer(wxHORIZONTAL);\r\n\r\n    mathData->graphData.plotWindow->AddLayer(new mpScaleX(\"X\", mpALIGN_CENTER));\r\n    mathData->graphData.plotWindow->AddLayer(new mpScaleY(\"Y\", mpALIGN_CENTER));\r\n    mathData->graphData.plotWindow->SetMPScrollbars(false);\r\n    mathData->graphData.plotWindow->EnableMousePanZoom(false);\r\n    mathData->graphData.plotWindow->Fit(mathData->graphData.minX, mathData->graphData.maxX,\r\n        mathData->graphData.minX, mathData->graphData.maxX);\r\n\r\n    auto* graphButton = new wxButton(this, wxID_ANY, \"Graph\");\r\n\r\n    auto& font = wxFont(16u, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD);\r\n\r\n    graphText->SetFont(font);\r\n    graphEntry->SetFont(font);\r\n\r\n    bottomSizer->Add(graphText, 0u, wxALL, 2u);\r\n    bottomSizer->Add(graphEntry, 0u, wxALL | wxEXPAND, 2u);\r\n    bottomSizer->Add(graphButton, 0u, wxALL, 5u);\r\n\r\n    topSizer->Add(mathData->graphData.plotWindow, 1u, wxALL | wxEXPAND, 10u);\r\n    topSizer->Add(bottomSizer, 0u, wxALL, 10u);\r\n\r\n    topSizer->Fit(this);\r\n    topSizer->SetSizeHints(this);\r\n\r\n    SetSizer(topSizer);\r\n\r\n    graphButton->Bind(wxEVT_LEFT_DOWN, &GrapherPanel::OnGraphButton, this);\r\n}\r\n\r\nvoid GrapherPanel::OnUpdateGraphType(wxCommandEvent& event)\r\n{\r\n    const auto& typeSelection = dynamic_cast<wxChoice*>(this->FindWindowById(wxID_APPLY))->GetStringSelection();\r\n\r\n    if (typeSelection == \"Cartesian\")\r\n    {\r\n        this->graphText->SetLabel(\"F(x) = \");\r\n    }\r\n    else if (typeSelection == \"Polar\")\r\n    {\r\n        this->graphText->SetLabel(\"r(t) = \");\r\n    }\r\n}\r\n\r\nvoid GrapherPanel::graphCartesian(std::vector<double>& xCoordinates, std::vector<double>& yCoordinates,\r\n    std::size_t numberOfPoints, double minX, double maxX)\r\n{\r\n    for (double i = minX; i <= maxX; i += std::abs(maxX - minX) / numberOfPoints)\r\n    {\r\n        auto graphEquation = this->graphEntry->GetValue().ToStdString();\r\n\r\n        boost::replace_all(graphEquation, \"x\", \"(\" + std::to_string(i) + \")\");\r\n\r\n        this->mathData->mathSolver.setTask(graphEquation);\r\n\r\n        if (this->mathData->mathSolver.solve())\r\n        {\r\n            xCoordinates.push_back(i);\r\n            yCoordinates.push_back(this->mathData->mathSolver.getValue());\r\n        }\r\n    }\r\n}\r\n\r\nvoid GrapherPanel::graphPolar(std::vector<double>& xCoordinates, std::vector<double>& yCoordinates, std::size_t numberOfPoints)\r\n{\r\n    const auto& pi = boost::math::constants::pi<double>();\r\n\r\n    for (double i = 0.0; i <= 2.0 * pi; i += (2 * pi) / numberOfPoints)\r\n    {\r\n        auto graphEquation = this->graphEntry->GetValue().ToStdString();\r\n\r\n        boost::replace_all(graphEquation, \"t\", \"(\" + std::to_string(i) + \")\");\r\n\r\n        this->mathData->mathSolver.setTask(graphEquation);\r\n\r\n        if (mathData->mathSolver.solve())\r\n        {\r\n            xCoordinates.push_back(this->mathData->mathSolver.getValue() * std::cos(i));\r\n            yCoordinates.push_back(this->mathData->mathSolver.getValue() * std::sin(i));\r\n        }\r\n    }\r\n}\r\n\r\nvoid GrapherPanel::OnGraphButton(wxMouseEvent& event)\r\n{\r\n    const std::size_t numberOfPoints = 2500u;\r\n\r\n    std::vector<double> xCoordinates;\r\n    std::vector<double> yCoordinates;\r\n\r\n    double minX = this->mathData->graphData.minX;\r\n    double maxX = this->mathData->graphData.maxX;\r\n\r\n    if (mathData->graphData.graphType == \"Cartesian\")\r\n    {\r\n        this->graphCartesian(xCoordinates, yCoordinates, numberOfPoints, minX, maxX);\r\n    }\r\n    else if (mathData->graphData.graphType == \"Polar\")\r\n    {\r\n        this->graphPolar(xCoordinates, yCoordinates, numberOfPoints);\r\n    }\r\n\r\n    this->mathData->graphData.graphs.push_back(new mpFXYVector(this->graphEntry->GetValue().ToStdString()));\r\n    this->mathData->graphData.graphs.back()->SetData(xCoordinates, yCoordinates);\r\n    this->mathData->graphData.graphs.back()->SetContinuity(true);\r\n    this->mathData->graphData.graphs.back()->ShowName(false);\r\n\r\n    this->mathData->graphData.plotWindow->AddLayer(this->mathData->graphData.graphs.back());\r\n\r\n    this->mathData->graphData.plotWindow->Fit();\r\n}", "meta": {"hexsha": "0e43dc492c8cb88ca5230db68058a57efeb001f2", "size": 5099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GrapherPanel.cpp", "max_stars_repo_name": "saktheeswaranswan/InPalgrapher", "max_stars_repo_head_hexsha": "2afa5d327a9fffbc9aede62d8b826ef76d69405a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-07-21T14:15:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-25T21:40:47.000Z", "max_issues_repo_path": "src/GrapherPanel.cpp", "max_issues_repo_name": "InversePalindrome/Prime-Numbers", "max_issues_repo_head_hexsha": "2afa5d327a9fffbc9aede62d8b826ef76d69405a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GrapherPanel.cpp", "max_forks_repo_name": "InversePalindrome/Prime-Numbers", "max_forks_repo_head_hexsha": "2afa5d327a9fffbc9aede62d8b826ef76d69405a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1655172414, "max_line_length": 128, "alphanum_fraction": 0.6679741126, "num_tokens": 1339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5773761452152248}}
{"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// \u7a0b\u5e8f\u4ee5\u901a\u5e38\u7684\u5305\u542b\u6587\u4ef6\u5f00\u59cb\uff0c\u6240\u6709\u8fd9\u4e9b\u6587\u4ef6\u4f60\u73b0\u5728\u5e94\u8be5\u90fd\u89c1\u8fc7\u4e86\u3002\n\n#include <deal.II/base/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// \u7136\u540e\u7167\u4f8b\u5c06\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u6240\u6709\u5185\u5bb9\u653e\u5165\u4e00\u4e2a\u547d\u540d\u7a7a\u95f4\uff0c\u5e76\u5c06deal.II\u547d\u540d\u7a7a\u95f4\u5bfc\u5165\u5230\u6211\u4eec\u5c06\u8981\u5de5\u4f5c\u7684\u547d\u540d\u7a7a\u95f4\u4e2d\u3002\n\nnamespace Step26 \n{ \n  using namespace dealii; \n// @sect3{The <code>HeatEquation</code> class}  \n\n// \u4e0b\u4e00\u4e2a\u90e8\u5206\u662f\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u7684\u58f0\u660e\u3002\u5b83\u6cbf\u7528\u4e86\u4ee5\u524d\u7684\u4f8b\u5b50\u4e2d\u516c\u8ba4\u7684\u8def\u5f84\u3002\u5982\u679c\u4f60\u770b\u8fc7 step-6 \uff0c\u4f8b\u5982\uff0c\u8fd9\u91cc\u552f\u4e00\u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c\u6211\u4eec\u9700\u8981\u5efa\u7acb\u4e24\u4e2a\u77e9\u9635\uff08\u8d28\u91cf\u548c\u62c9\u666e\u62c9\u65af\u77e9\u9635\uff09\uff0c\u5e76\u4fdd\u5b58\u5f53\u524d\u548c\u524d\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7684\u89e3\u3002\u7136\u540e\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u5b58\u50a8\u5f53\u524d\u65f6\u95f4\u3001\u65f6\u95f4\u6b65\u957f\u548c\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u7684\u7f16\u53f7\u3002\u6700\u540e\u4e00\u4e2a\u6210\u5458\u53d8\u91cf\u8868\u793a\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684theta\u53c2\u6570\uff0c\u5b83\u5141\u8bb8\u6211\u4eec\u5728\u4e00\u4e2a\u7a0b\u5e8f\u4e2d\u5904\u7406\u663e\u5f0f\u548c\u9690\u5f0f\u6b27\u62c9\u65b9\u6cd5\uff0c\u4ee5\u53caCrank-Nicolson\u65b9\u6cd5\u548c\u5176\u4ed6\u901a\u7528\u65b9\u6cd5\u3002\n\n// \u5c31\u6210\u5458\u51fd\u6570\u800c\u8a00\uff0c\u552f\u4e00\u53ef\u80fd\u7684\u60ca\u559c\u662f <code>refine_mesh</code> \u51fd\u6570\u9700\u8981\u6700\u5c0f\u548c\u6700\u5927\u7684\u7f51\u683c\u7ec6\u5316\u7ea7\u522b\u7684\u53c2\u6570\u3002\u8fd9\u6837\u505a\u7684\u76ee\u7684\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u4e86\u3002\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// \u5728\u4e0b\u9762\u7684\u7c7b\u548c\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u5b9e\u73b0\u4e86\u5b9a\u4e49\u8fd9\u4e2a\u95ee\u9898\u7684\u5404\u79cd\u6570\u636e\uff08\u53f3\u624b\u8fb9\u548c\u8fb9\u754c\u503c\uff09\uff0c\u8fd9\u4e9b\u6570\u636e\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u4f7f\u7528\uff0c\u6211\u4eec\u9700\u8981\u51fd\u6570\u5bf9\u8c61\u3002\u53f3\u624b\u8fb9\u7684\u9009\u62e9\u662f\u5728\u4ecb\u7ecd\u7684\u6700\u540e\u8ba8\u8bba\u7684\u3002\u5bf9\u4e8e\u8fb9\u754c\u503c\uff0c\u6211\u4eec\u9009\u62e9\u96f6\u503c\uff0c\u4f46\u8fd9\u5f88\u5bb9\u6613\u5728\u4e0b\u9762\u6539\u53d8\u3002\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// \u73b0\u5728\u662f\u5b9e\u73b0\u4e3b\u7c7b\u7684\u65f6\u5019\u4e86\u3002\u8ba9\u6211\u4eec\u4ece\u6784\u9020\u51fd\u6570\u5f00\u59cb\uff0c\u5b83\u9009\u62e9\u4e86\u4e00\u4e2a\u7ebf\u6027\u5143\u7d20\uff0c\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u4e3a1/500\u7684\u5e38\u6570\uff08\u8bb0\u5f97\u4e0a\u9762\u628a\u53f3\u8fb9\u7684\u6e90\u7684\u4e00\u4e2a\u5468\u671f\u8bbe\u7f6e\u4e3a0.2\uff0c\u6240\u4ee5\u6211\u4eec\u7528100\u4e2a\u65f6\u95f4\u6b65\u957f\u6765\u89e3\u51b3\u6bcf\u4e2a\u5468\u671f\uff09\uff0c\u5e76\u901a\u8fc7\u8bbe\u7f6e  $\\theta=1/2$  \u9009\u62e9\u4e86Crank Nicolson\u65b9\u6cd5.\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// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u8bbe\u7f6eDoFHandler\u5bf9\u8c61\uff0c\u8ba1\u7b97\u7ea6\u675f\uff0c\u5e76\u5c06\u7ebf\u6027\u4ee3\u6570\u5bf9\u8c61\u8bbe\u7f6e\u4e3a\u6b63\u786e\u7684\u5927\u5c0f\u3002\u6211\u4eec\u8fd8\u5728\u8fd9\u91cc\u901a\u8fc7\u7b80\u5355\u5730\u8c03\u7528\u5e93\u4e2d\u7684\u4e24\u4e2a\u51fd\u6570\u6765\u8ba1\u7b97\u8d28\u91cf\u548c\u62c9\u666e\u62c9\u65af\u77e9\u9635\u3002\n\n// \u6ce8\u610f\u6211\u4eec\u5728\u7ec4\u88c5\u77e9\u9635\u65f6\u4e0d\u8003\u8651\u60ac\u6302\u8282\u70b9\u7684\u7ea6\u675f\uff08\u4e24\u4e2a\u51fd\u6570\u90fd\u6709\u4e00\u4e2aAffineConstraints\u53c2\u6570\uff0c\u9ed8\u8ba4\u4e3a\u4e00\u4e2a\u7a7a\u5bf9\u8c61\uff09\u3002\u8fd9\u662f\u56e0\u4e3a\u6211\u4eec\u8981\u5728\u7ed3\u5408\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u7684\u77e9\u9635\u540e\uff0c\u5728run()\u4e2d\u6d53\u7f29\u7ea6\u675f\u3002\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// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u89e3\u51b3\u5355\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7684\u5b9e\u9645\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\u3002\u8fd9\u91cc\u6ca1\u6709\u4ec0\u4e48\u503c\u5f97\u60ca\u8bb6\u7684\u3002\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// \u5728\u751f\u6210\u56fe\u5f62\u8f93\u51fa\u65b9\u9762\u4e5f\u6ca1\u6709\u4ec0\u4e48\u65b0\u4e1c\u897f\uff0c\u53ea\u662f\u6211\u4eec\u544a\u8bc9DataOut\u5bf9\u8c61\u5f53\u524d\u7684\u65f6\u95f4\u548c\u65f6\u95f4\u6b65\u957f\u662f\u591a\u5c11\uff0c\u4ee5\u4fbf\u5c06\u5176\u5199\u5165\u8f93\u51fa\u6587\u4ef6\u4e2d\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u662f\u7a0b\u5e8f\u4e2d\u6700\u6709\u8da3\u7684\u90e8\u5206\u3002\u5b83\u8d1f\u8d23\u81ea\u9002\u5e94\u7f51\u683c\u7ec6\u5316\u7684\u5de5\u4f5c\u3002\u8fd9\u4e2a\u51fd\u6570\u6267\u884c\u7684\u4e09\u4e2a\u4efb\u52a1\u662f\uff1a\u9996\u5148\u627e\u51fa\u9700\u8981\u7ec6\u5316/\u7c97\u5316\u7684\u5355\u5143\uff0c\u7136\u540e\u5b9e\u9645\u8fdb\u884c\u7ec6\u5316\uff0c\u6700\u540e\u5728\u4e24\u4e2a\u4e0d\u540c\u7684\u7f51\u683c\u4e4b\u95f4\u4f20\u8f93\u89e3\u5411\u91cf\u3002\u7b2c\u4e00\u4e2a\u4efb\u52a1\u662f\u901a\u8fc7\u4f7f\u7528\u6210\u719f\u7684\u51ef\u5229\u8bef\u5dee\u4f30\u8ba1\u5668\u6765\u5b9e\u73b0\u7684\u3002\u7b2c\u4e8c\u9879\u4efb\u52a1\u662f\u5b9e\u9645\u8fdb\u884c\u518d\u7ec6\u5316\u3002\u8fd9\u4e5f\u53ea\u6d89\u53ca\u5230\u57fa\u672c\u7684\u51fd\u6570\uff0c\u4f8b\u5982 <code>refine_and_coarsen_fixed_fraction</code> \uff0c\u5b83\u53ef\u4ee5\u7ec6\u5316\u90a3\u4e9b\u5177\u6709\u6700\u5927\u4f30\u8ba1\u8bef\u5dee\u7684\u5355\u5143\uff0c\u8fd9\u4e9b\u8bef\u5dee\u52a0\u8d77\u6765\u536060%\uff0c\u5e76\u7c97\u5316\u90a3\u4e9b\u5177\u6709\u6700\u5c0f\u8bef\u5dee\u7684\u5355\u5143\uff0c\u8fd9\u4e9b\u5355\u5143\u52a0\u8d77\u6765\u536040%\u7684\u8bef\u5dee\u3002\u8bf7\u6ce8\u610f\uff0c\u5bf9\u4e8e\u50cf\u5f53\u524d\u8fd9\u6837\u7684\u95ee\u9898\uff0c\u5373\u6709\u4e8b\u53d1\u751f\u7684\u533a\u57df\u6b63\u5728\u56db\u5904\u79fb\u52a8\uff0c\u6211\u4eec\u5e0c\u671b\u79ef\u6781\u5730\u8fdb\u884c\u7c97\u5316\uff0c\u4ee5\u4fbf\u6211\u4eec\u80fd\u591f\u5c06\u5355\u5143\u683c\u79fb\u52a8\u5230\u6709\u5fc5\u8981\u7684\u5730\u65b9\u3002\n\n// \u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u7684\uff0c\u592a\u5c0f\u7684\u7f51\u683c\u4f1a\u5bfc\u81f4\u592a\u5c0f\u7684\u65f6\u95f4\u6b65\u957f\uff0c\u800c\u592a\u5927\u7684\u7f51\u683c\u4f1a\u5bfc\u81f4\u592a\u5c0f\u7684\u5206\u8fa8\u7387\u3002\u56e0\u6b64\uff0c\u5728\u524d\u4e24\u4e2a\u6b65\u9aa4\u4e4b\u540e\uff0c\u6211\u4eec\u6709\u4e24\u4e2a\u5faa\u73af\uff0c\u5c06\u7ec6\u5316\u548c\u7c97\u5316\u9650\u5236\u5728\u4e00\u4e2a\u5141\u8bb8\u7684\u5355\u5143\u8303\u56f4\u5185\u3002\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// \u4e0a\u9762\u8fd9\u4e24\u4e2a\u5faa\u73af\u7565\u6709\u4e0d\u540c\uff0c\u4f46\u8fd9\u5f88\u5bb9\u6613\u89e3\u91ca\u3002\u5728\u7b2c\u4e00\u4e2a\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u6ca1\u6709\u8c03\u7528  <code>triangulation.end()</code>  \uff0c\u800c\u662f\u8c03\u7528  <code>triangulation.end_active(max_grid_level)</code>  \u3002\u8fd9\u4e24\u4e2a\u8c03\u7528\u5e94\u8be5\u4ea7\u751f\u76f8\u540c\u7684\u8fed\u4ee3\u5668\uff0c\u56e0\u4e3a\u8fed\u4ee3\u5668\u662f\u6309\u7ea7\u522b\u6392\u5e8f\u7684\uff0c\u4e0d\u5e94\u8be5\u6709\u4efb\u4f55\u7ea7\u522b\u9ad8\u4e8e <code>max_grid_level</code> \u7684\u5355\u5143\u683c\u3002\u4e8b\u5b9e\u4e0a\uff0c\u8fd9\u6bb5\u4ee3\u7801\u786e\u4fdd\u4e86\u8fd9\u79cd\u60c5\u51b5\u7684\u53d1\u751f\u3002\n\n// \u4f5c\u4e3a\u7f51\u683c\u7ec6\u5316\u7684\u4e00\u90e8\u5206\uff0c\u6211\u4eec\u9700\u8981\u5c06\u65e7\u7684\u7f51\u683c\u4e2d\u7684\u89e3\u5411\u91cf\u8f6c\u79fb\u5230\u65b0\u7684\u7f51\u683c\u4e2d\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u4f7f\u7528\u4e86SolutionTransfer\u7c7b\uff0c\u6211\u4eec\u5fc5\u987b\u51c6\u5907\u597d\u9700\u8981\u8f6c\u79fb\u5230\u65b0\u7f51\u683c\u7684\u89e3\u5411\u91cf\uff08\u4e00\u65e6\u5b8c\u6210\u7ec6\u5316\uff0c\u6211\u4eec\u5c06\u5931\u53bb\u65e7\u7684\u7f51\u683c\uff0c\u6240\u4ee5\u8f6c\u79fb\u5fc5\u987b\u4e0e\u7ec6\u5316\u540c\u65f6\u53d1\u751f\uff09\u3002\u5728\u6211\u4eec\u8c03\u7528\u8fd9\u4e2a\u51fd\u6570\u7684\u65f6\u5019\uff0c\u6211\u4eec\u5c06\u521a\u521a\u8ba1\u7b97\u51fa\u89e3\u51b3\u65b9\u6848\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u518d\u9700\u8981old_solution\u53d8\u91cf\uff08\u5b83\u5c06\u5728\u7f51\u683c\u88ab\u7ec6\u5316\u540e\u88ab\u89e3\u51b3\u65b9\u6848\u8986\u76d6\uff0c\u4e5f\u5c31\u662f\u5728\u65f6\u95f4\u6b65\u957f\u7ed3\u675f\u65f6\uff1b\u89c1\u4e0b\u6587\uff09\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u6211\u4eec\u53ea\u9700\u8981\u4e00\u4e2a\u6c42\u89e3\u5411\u91cf\uff0c\u5e76\u5c06\u5176\u590d\u5236\u5230\u4e00\u4e2a\u4e34\u65f6\u5bf9\u8c61\u4e2d\uff0c\u5f53\u6211\u4eec\u8fdb\u4e00\u6b65\u5411\u4e0b\u8c03\u7528 <code>setup_system()</code> \u65f6\uff0c\u5b83\u5c31\u4e0d\u4f1a\u88ab\u91cd\u7f6e\u3002\n\n// \u56e0\u6b64\uff0c\u6211\u4eec\u5c06\u4e00\u4e2aSolutionTransfer\u5bf9\u8c61\u9644\u52a0\u5230\u65e7\u7684DoF\u5904\u7406\u7a0b\u5e8f\u4e2d\uff0c\u4ee5\u521d\u59cb\u5316\u5b83\u3002\u7136\u540e\uff0c\u6211\u4eec\u51c6\u5907\u597d\u4e09\u89d2\u5f62\u548c\u6570\u636e\u5411\u91cf\uff0c\u4ee5\u4fbf\u8fdb\u884c\u7ec6\u5316\uff08\u6309\u7167\u8fd9\u4e2a\u987a\u5e8f\uff09\u3002\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// \u73b0\u5728\u4e00\u5207\u90fd\u51c6\u5907\u597d\u4e86\uff0c\u6240\u4ee5\u8fdb\u884c\u7ec6\u5316\u5e76\u5728\u65b0\u7f51\u683c\u4e0a\u91cd\u65b0\u521b\u5efaDoF\u7ed3\u6784\uff0c\u6700\u540e\u5728 <code>setup_system</code> \u51fd\u6570\u4e2d\u521d\u59cb\u5316\u77e9\u9635\u7ed3\u6784\u548c\u65b0\u7684\u5411\u91cf\u3002\u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5b9e\u9645\u6267\u884c\u4ece\u65e7\u7f51\u683c\u5230\u65b0\u7f51\u683c\u7684\u63d2\u503c\u89e3\u3002\u6700\u540e\u4e00\u6b65\u662f\u5bf9\u89e3\u5411\u91cf\u5e94\u7528\u60ac\u7a7a\u8282\u70b9\u7ea6\u675f\uff0c\u5373\u786e\u4fdd\u4f4d\u4e8e\u60ac\u7a7a\u8282\u70b9\u4e0a\u7684\u81ea\u7531\u5ea6\u503c\uff0c\u4f7f\u89e3\u662f\u8fde\u7eed\u7684\u3002\u8fd9\u662f\u5fc5\u8981\u7684\uff0c\u56e0\u4e3aSolutionTransfer\u53ea\u5bf9\u5355\u5143\u683c\u8fdb\u884c\u5c40\u90e8\u64cd\u4f5c\uff0c\u4e0d\u8003\u8651\u90bb\u57df\u3002\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// \u8fd9\u662f\u7a0b\u5e8f\u7684\u4e3b\u8981\u9a71\u52a8\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u5faa\u73af\u6240\u6709\u7684\u65f6\u95f4\u6b65\u9aa4\u3002\u5728\u51fd\u6570\u7684\u9876\u90e8\uff0c\u6211\u4eec\u901a\u8fc7\u91cd\u590d\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\uff0c\u8bbe\u7f6e\u521d\u59cb\u5168\u5c40\u7f51\u683c\u7ec6\u5316\u7684\u6570\u91cf\u548c\u81ea\u9002\u5e94\u7f51\u683c\u7ec6\u5316\u7684\u521d\u59cb\u5468\u671f\u6570\u91cf\u3002\u7136\u540e\uff0c\u6211\u4eec\u521b\u5efa\u4e00\u4e2a\u7f51\u683c\uff0c\u521d\u59cb\u5316\u6211\u4eec\u8981\u5904\u7406\u7684\u5404\u79cd\u5bf9\u8c61\uff0c\u8bbe\u7f6e\u4e00\u4e2a\u6807\u7b7e\uff0c\u8bf4\u660e\u6211\u4eec\u5728\u91cd\u65b0\u8fd0\u884c\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u957f\u65f6\u5e94\u8be5\u4ece\u54ea\u91cc\u5f00\u59cb\uff0c\u5e76\u5c06\u521d\u59cb\u89e3\u63d2\u503c\u5230\u7f51\u683c\u4e0a\uff08\u6211\u4eec\u5728\u8fd9\u91cc\u9009\u62e9\u4e86\u96f6\u51fd\u6570\uff0c\u5f53\u7136\uff0c\u6211\u4eec\u53ef\u4ee5\u7528\u66f4\u7b80\u5355\u7684\u65b9\u6cd5\uff0c\u76f4\u63a5\u5c06\u89e3\u5411\u91cf\u8bbe\u7f6e\u4e3a\u96f6\uff09\u3002\u6211\u4eec\u8fd8\u8f93\u51fa\u4e00\u6b21\u521d\u59cb\u65f6\u95f4\u6b65\u957f\u3002\n\n//  @note  \u5982\u679c\u4f60\u662f\u4e00\u4e2a\u6709\u7ecf\u9a8c\u7684\u7a0b\u5e8f\u5458\uff0c\u4f60\u53ef\u80fd\u4f1a\u5bf9\u6211\u4eec\u5728\u8fd9\u6bb5\u4ee3\u7801\u4e2d\u4f7f\u7528 <code>goto</code> \u8bed\u53e5\u611f\u5230\u5403\u60ca   <code>goto</code> \u8bed\u53e5\u73b0\u5728\u5df2\u7ecf\u4e0d\u662f\u7279\u522b\u53d7\u4eba\u6b22\u8fce\u4e86\uff0c\u56e0\u4e3a\u8ba1\u7b97\u673a\u79d1\u5b66\u754c\u7684\u5927\u5e08\u4e4b\u4e00Edsgar Dijkstra\u57281968\u5e74\u5199\u4e86\u4e00\u5c01\u4fe1\uff0c\u53eb\u505a \"Go To Statement considered harmful\"\uff08\u89c1<a href=\"http:en.wikipedia.org/wiki/Considered_harmful\">here</a>\uff09\u3002\u8fd9\u6bb5\u4ee3\u7801\u7684\u4f5c\u8005\u5168\u5fc3\u5168\u610f\u5730\u8d5e\u540c\u8fd9\u4e00\u89c2\u5ff5\u3002  <code>goto</code> \u662f\u96be\u4ee5\u7406\u89e3\u7684\u3002\u4e8b\u5b9e\u4e0a\uff0cdeal.II\u51e0\u4e4e\u4e0d\u5305\u542b\u4efb\u4f55\u51fa\u73b0\u7684\u60c5\u51b5\uff1a\u4e0d\u5305\u62ec\u57fa\u672c\u4e0a\u662f\u4ece\u4e66\u672c\u4e0a\u8f6c\u5f55\u7684\u4ee3\u7801\uff0c\u4e5f\u4e0d\u8ba1\u7b97\u91cd\u590d\u7684\u4ee3\u7801\u7247\u65ad\uff0c\u5728\u5199\u8fd9\u7bc7\u7b14\u8bb0\u65f6\uff0c\u5927\u7ea660\u4e07\u884c\u4ee3\u7801\u4e2d\u67093\u4e2a\u4f4d\u7f6e\uff1b\u6211\u4eec\u8fd8\u57284\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u5b83\uff0c\u5176\u80cc\u666f\u4e0e\u8fd9\u91cc\u5b8c\u5168\u76f8\u540c\u3002\u4e0e\u5176\u5728\u8fd9\u91cc\u8bd5\u56fe\u8bc1\u660e\u8fd9\u79cd\u60c5\u51b5\u7684\u51fa\u73b0\uff0c\u4e0d\u5982\u5148\u770b\u770b\u4ee3\u7801\uff0c\u6211\u4eec\u5728\u51fd\u6570\u7684\u6700\u540e\u518d\u6765\u8ba8\u8bba\u8fd9\u4e2a\u95ee\u9898\u3002\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// \u7136\u540e\u6211\u4eec\u5f00\u59cb\u4e3b\u5faa\u73af\uff0c\u76f4\u5230\u8ba1\u7b97\u7684\u65f6\u95f4\u8d85\u8fc7\u6211\u4eec\u7684\u7ed3\u675f\u65f6\u95f40.5\u3002\u7b2c\u4e00\u4e2a\u4efb\u52a1\u662f\u5efa\u7acb\u6211\u4eec\u9700\u8981\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u89e3\u51b3\u7684\u7ebf\u6027\u7cfb\u7edf\u7684\u53f3\u624b\u8fb9\u3002\u56de\u987e\u4e00\u4e0b\uff0c\u5b83\u5305\u542b\u9879 $MU^{n-1}-(1-\\theta)k_n AU^{n-1}$  \u3002\u6211\u4eec\u628a\u8fd9\u4e9b\u9879\u653e\u5230\u53d8\u91cfsystem_rhs\u4e2d\uff0c\u501f\u52a9\u4e8e\u4e00\u4e2a\u4e34\u65f6\u77e2\u91cf\u3002\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// \u7b2c\u4e8c\u5757\u662f\u8ba1\u7b97\u6e90\u9879\u7684\u8d21\u732e\u3002\u8fd9\u4e0e\u672f\u8bed  $k_n \\left[ (1-\\theta)F^{n-1} + \\theta F^n \\right]$  \u76f8\u5bf9\u5e94\u3002\u4e0b\u9762\u7684\u4ee3\u7801\u8c03\u7528  VectorTools::create_right_hand_side  \u6765\u8ba1\u7b97\u5411\u91cf  $F$  \uff0c\u5728\u8fd9\u91cc\u6211\u4eec\u5728\u8bc4\u4f30\u4e4b\u524d\u8bbe\u7f6e\u4e86\u53f3\u4fa7\uff08\u6e90\uff09\u51fd\u6570\u7684\u65f6\u95f4\u3002\u8fd9\u4e00\u5207\u7684\u7ed3\u679c\u6700\u7ec8\u90fd\u5728forcing_terms\u53d8\u91cf\u4e2d\u3002\n\n        RightHandSide<dim> rhs_function; \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// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5c06\u5f3a\u8feb\u9879\u52a0\u5165\u5230\u6765\u81ea\u65f6\u95f4\u6b65\u957f\u7684\u5f3a\u8feb\u9879\u4e2d\uff0c\u540c\u65f6\u5efa\u7acb\u77e9\u9635 $M+k_n\\theta A$ \uff0c\u6211\u4eec\u5fc5\u987b\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u8fdb\u884c\u53cd\u8f6c\u3002\u8fd9\u4e9b\u64cd\u4f5c\u7684\u6700\u540e\u4e00\u5757\u662f\u6d88\u9664\u7ebf\u6027\u7cfb\u7edf\u4e2d\u60ac\u6302\u7684\u8282\u70b9\u7ea6\u675f\u81ea\u7531\u5ea6\u3002\n\n        system_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// \u5728\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u4e4b\u524d\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u505a\u4e00\u4e2a\u64cd\u4f5c\uff1a\u8fb9\u754c\u503c\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u521b\u5efa\u4e00\u4e2a\u8fb9\u754c\u503c\u5bf9\u8c61\uff0c\u5c06\u9002\u5f53\u7684\u65f6\u95f4\u8bbe\u7f6e\u4e3a\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u7684\u65f6\u95f4\uff0c\u5e76\u50cf\u4ee5\u524d\u591a\u6b21\u90a3\u6837\u5bf9\u5176\u8fdb\u884c\u8bc4\u4f30\u3002\u5176\u7ed3\u679c\u4e5f\u88ab\u7528\u6765\u5728\u7ebf\u6027\u7cfb\u7edf\u4e2d\u8bbe\u7f6e\u6b63\u786e\u7684\u8fb9\u754c\u503c\u3002\n\n        { \n          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// \u6709\u4e86\u8fd9\u4e9b\uff0c\u6211\u4eec\u8981\u505a\u7684\u5c31\u662f\u89e3\u51b3\u8fd9\u4e2a\u7cfb\u7edf\uff0c\u751f\u6210\u56fe\u5f62\u6570\u636e\uff0c\u4ee5\u53ca......\n\n        solve_time_step(); \n\n        output_results(); \n\n// ...\u8d1f\u8d23\u7f51\u683c\u7684\u7ec6\u5316\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u8981\u505a\u7684\u662f\uff1a(i)\u5728\u6c42\u89e3\u8fc7\u7a0b\u7684\u6700\u5f00\u59cb\uff0c\u7ec6\u5316\u6240\u8981\u6c42\u7684\u6b21\u6570\uff0c\u4e4b\u540e\u6211\u4eec\u8df3\u5230\u9876\u90e8\u91cd\u65b0\u5f00\u59cb\u65f6\u95f4\u8fed\u4ee3\uff0c(ii)\u4e4b\u540e\u6bcf\u9694\u4e94\u6b65\u7ec6\u5316\u4e00\u6b21\u3002\n\n// \u65f6\u95f4\u5faa\u73af\u548c\u7a0b\u5e8f\u7684\u4e3b\u8981\u90e8\u5206\u4ee5\u5f00\u59cb\u8fdb\u5165\u4e0b\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7ed3\u675f\uff0c\u5c06old_solution\u8bbe\u7f6e\u4e3a\u6211\u4eec\u521a\u521a\u8ba1\u7b97\u51fa\u7684\u89e3\u51b3\u65b9\u6848\u3002\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// \u73b0\u5728\u4f60\u5df2\u7ecf\u770b\u5230\u4e86\u8fd9\u4e2a\u51fd\u6570\u7684\u4f5c\u7528\uff0c\u8ba9\u6211\u4eec\u518d\u6765\u770b\u770b  <code>goto</code>  \u7684\u95ee\u9898\u3002\u4ece\u672c\u8d28\u4e0a\u8bb2\uff0c\u4ee3\u7801\u6240\u505a\u7684\u4e8b\u60c5\u662f\u8fd9\u6837\u7684\u3002\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//  \u8fd9\u91cc\uff0c\"\u5bf9\u7ed3\u679c\u6ee1\u610f \"\u7684\u6761\u4ef6\u662f\u6211\u4eec\u60f3\u4fdd\u7559\u5f53\u524d\u7684\u7f51\u683c\uff0c\u8fd8\u662f\u5b81\u613f\u7ec6\u5316\u7f51\u683c\u5e76\u5728\u65b0\u7f51\u683c\u4e0a\u91cd\u65b0\u5f00\u59cb\u3002\u6211\u4eec\u5f53\u7136\u53ef\u4ee5\u7528\u4e0b\u9762\u7684\u65b9\u6cd5\u6765\u53d6\u4ee3  <code>goto</code>  \u7684\u4f7f\u7528\u3002\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//  \u8fd9\u6837\u505a\u7684\u597d\u5904\u662f\u6446\u8131\u4e86 <code>goto</code> \uff0c\u4f46\u7f3a\u70b9\u662f\u5fc5\u987b\u5728\u4e24\u4e2a\u4e0d\u540c\u7684\u5730\u65b9\u91cd\u590d\u5b9e\u73b0 \"\u89e3\u7b97\u65f6\u95f4\u6b65\u957f \"\u548c \"\u540e\u5904\u7406 \"\u64cd\u4f5c\u7684\u4ee3\u7801\u3002\u8fd9\u53ef\u4ee5\u901a\u8fc7\u5c06\u8fd9\u4e9b\u90e8\u5206\u7684\u4ee3\u7801\uff08\u5728\u4e0a\u9762\u7684\u5b9e\u9645\u5b9e\u73b0\u4e2d\u662f\u76f8\u5f53\u5927\u7684\u5757\uff09\u653e\u5230\u81ea\u5df1\u7684\u51fd\u6570\u4e2d\u6765\u89e3\u51b3\uff0c\u4f46\u662f\u4e00\u4e2a\u5e26\u6709 <code>break</code> \u8bed\u53e5\u7684 <code>while(true)</code> \u5faa\u73af\u5e76\u4e0d\u771f\u7684\u6bd4 <code>goto</code> \u5bb9\u6613\u9605\u8bfb\u6216\u7406\u89e3\u3002\n\n// \u6700\u540e\uff0c\u4eba\u4eec\u53ef\u80fd\u4f1a\u7b80\u5355\u5730\u540c\u610f\uff0c<i>in general</i> \u3002\n// <code>goto</code>  \u8bed\u53e5\u662f\u4e2a\u574f\u4e3b\u610f\uff0c\u4f46\u8981\u52a1\u5b9e\u5730\u6307\u51fa\uff0c\u5728\u67d0\u4e9b\u60c5\u51b5\u4e0b\uff0c\u5b83\u4eec\u53ef\u4ee5\u5e2e\u52a9\u907f\u514d\u4ee3\u7801\u91cd\u590d\u548c\u5c34\u5c2c\u7684\u63a7\u5236\u6d41\u3002\u8fd9\u53ef\u80fd\u5c31\u662f\u5176\u4e2d\u4e4b\u4e00\uff0c\u5b83\u4e0eSteve McConnell\u5728\u4ed6\u5173\u4e8e\u826f\u597d\u7f16\u7a0b\u5b9e\u8df5\u7684\u4f18\u79c0\u4e66\u7c4d \"Code Complete\"  @cite CodeComplete \u4e2d\u91c7\u53d6\u7684\u7acb\u573a\u4e00\u81f4\uff08\u89c1 step-1 \u7684\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\u8fd9\u672c\u4e66\uff09\uff0c\u8be5\u4e66\u82b1\u4e86\u60ca\u4eba\u768410\u9875\u6765\u8ba8\u8bba\u4e00\u822c\u7684 <code>goto</code> \u95ee\u9898\u3002\n\n//  @sect3{The <code>main</code> function}  \n\n// \u8d70\u5230\u8fd9\u4e00\u6b65\uff0c\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e3b\u51fd\u6570\u53c8\u6ca1\u6709\u4ec0\u4e48\u597d\u8ba8\u8bba\u7684\u4e86\uff1a\u5b83\u770b\u8d77\u6765\u5c31\u50cf\u81ea step-6 \u4ee5\u6765\u7684\u6240\u6709\u6b64\u7c7b\u51fd\u6570\u4e00\u6837\u3002\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": "/* Boost numeric test of the runge kutta steppers test file\n\n Copyright 2012 Mario Mulansky\n Copyright 2012 Karsten Ahnert\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n*/\n\n// disable checked iterator warning for msvc\n#include <boost/config.hpp>\n#ifdef BOOST_MSVC\n    #pragma warning(disable:4996)\n#endif\n\n#define BOOST_TEST_MODULE numeric_runge_kutta\n\n#include <iostream>\n#include <cmath>\n\n#include <boost/array.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/vector.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\nnamespace mpl = boost::mpl;\n\ntypedef double value_type;\n\ntypedef boost::array< double , 1 > state_type;\n\n// harmonic oscillator, analytic solution x[0] = sin( t )\nstruct osc\n{\n    void operator()( const state_type &x, const state_type &v, state_type &a,\n                     const double t ) const\n    {\n        a[0] = -x[0];\n    }\n};\n\nBOOST_AUTO_TEST_SUITE( velocity_verlet_test )\n\nBOOST_AUTO_TEST_CASE( numeric_velocity_verlet_test )\n{\n\n    velocity_verlet<state_type> stepper;\n    const int steps = 10;\n    // order of the error is order of approximation + 1\n    const int o = stepper.order() + 1;\n\n    const state_type x0 = {{ 0.0 }};\n    const state_type v0 = {{ 1.0 }};\n    state_type x = x0;\n    state_type v = v0;\n    const double t = 0.0;\n    /* do a first step with dt=0.1 to get an estimate on the prefactor of the error dx = f * dt^(order+1) */\n    double dt = 0.5;\n    for ( int step = 0; step < steps; ++step )\n    {\n        stepper.do_step(\n            osc(), std::make_pair( boost::ref( x ), boost::ref( v ) ), t, dt );\n    }\n    const double f = steps * std::abs( sin( steps * dt ) - x[0] ) /\n                     std::pow( dt, o ); // upper bound\n\n    std::cout << o << \" , \" << f << std::endl;\n\n    /* as long as we have errors above machine precision */\n    while( f*std::pow( dt , o ) > 1E-16 )\n    {\n        x = x0;\n        v = v0;\n        stepper.reset();\n        for ( int step = 0; step < steps; ++step )\n        {\n            stepper.do_step( osc() , std::make_pair(boost::ref(x), boost::ref(v)) , t , dt );\n        }\n        std::cout << \"Testing dt=\" << dt << std::endl;\n        BOOST_CHECK_LT( std::abs( sin( steps * dt ) - x[0] ),\n                        f * std::pow( dt, o ) );\n        dt *= 0.5;\n    }\n};\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "97387e66765df15e5ccd60f71ffd9ee80d6a1aee", "size": 2473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/numeric/odeint/test/numeric/velocity_verlet.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/libs/numeric/odeint/test/numeric/velocity_verlet.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/libs/numeric/odeint/test/numeric/velocity_verlet.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 26.3085106383, "max_line_length": 108, "alphanum_fraction": 0.6045289123, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5773616561626063}}
{"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": "/*\n * utilities_cumtrapz_test.cpp Test fixtures for the cumtrapz function\n *\n * Author:                   Tom Clark (thclark @ github)\n *\n * Copyright (c) 2016-9 Octue Ltd. All Rights Reserved.\n *\n */\n\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\n#include \"utilities/cumtrapz.h\"\n\n\nusing namespace utilities;\n\n\nclass CumtrapzTest : public ::testing::Test {};\n\n\nTEST_F(CumtrapzTest, test_colwise_cumtrapz_1_row) {\n\n    // Test that zeros are returned when trying to colwise integrate an array with 1 row\n    Eigen::ArrayXXf integrand(1, 4);\n    integrand << 1, 2, 6, 9;\n    Eigen::ArrayXXf integral_correct(1, 4);\n    integral_correct << 0, 0, 0, 0;\n    Eigen::ArrayXXf integral = cumtrapz(integrand);\n    EXPECT_EQ(integral.matrix(), integral_correct.matrix());\n\n}\n\n\nTEST_F(CumtrapzTest, test_colwise_cumtrapz_2_rows) {\n\n    // Test that uniform spaced integration works on an array with 2 rows\n    Eigen::ArrayXXf integrand(2,6);\n    integrand << 1.0, 2.0, 3.0, 4.0, 5.0, 6.0,\n        7.0, 8.0, 9.0, 10.0, 11.0, 12.0;\n    Eigen::ArrayXXf integral_correct(2,6);\n    integral_correct << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0;\n    Eigen::ArrayXXf integral = cumtrapz(integrand);\n    EXPECT_EQ(integral.matrix(), integral_correct.matrix());\n\n}\n\n\nTEST_F(CumtrapzTest, test_colwise_cumtrapz_6_rows) {\n\n    Eigen::ArrayXXf integrand(6,1);\n    integrand << 1.0, 2.0, 3.0, 4.0, 5.0, 6.0;\n\n    Eigen::ArrayXXf integral_correct(6,1);\n    integral_correct<< 0.0, 1.5, 4.0, 7.5, 12.0, 17.5;\n\n    Eigen::ArrayXXf integral = cumtrapz(integrand);\n    EXPECT_EQ(integral.matrix(), integral_correct.matrix());\n\n}\n\n\nTEST_F(CumtrapzTest, test_colwise_nonuniform_cumtrapz) {\n\n    // Test that non-uniform spacing works with an n x 1 spacing array\n    Eigen::ArrayXXf spacing(3, 1);\n    spacing << 2,\n        5,\n        7;\n    Eigen::ArrayXXf integrand(3,4);\n    integrand << 1, 2, 6, 9,\n        3, 1, 7, 2,\n        4, 8, 3, 1;\n    Eigen::ArrayXXf integral_correct(3,4);\n    integral_correct << 0.0, 0.0, 0.0, 0.0,\n                        6.0, 4.5, 19.5, 16.5,\n                        13.0, 13.5, 29.5, 19.5;\n    Eigen::ArrayXXf integral(3,4);\n    cumtrapz(integral, spacing, integrand);\n    EXPECT_EQ(integral.matrix(), integral_correct.matrix());\n\n}\n", "meta": {"hexsha": "6dcc532e7c593570ae66200f16645069bb098518", "size": 2255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/utilities_cumtrapz_test.cpp", "max_stars_repo_name": "octue/es-flow", "max_stars_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_stars_repo_licenses": ["Intel", "MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-01-07T13:55:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T16:30:03.000Z", "max_issues_repo_path": "test/unit/utilities_cumtrapz_test.cpp", "max_issues_repo_name": "octue/es-flow", "max_issues_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_issues_repo_licenses": ["Intel", "MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-09-04T10:40:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-02T10:13:25.000Z", "max_forks_repo_path": "test/unit/utilities_cumtrapz_test.cpp", "max_forks_repo_name": "octue/es-flow", "max_forks_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_forks_repo_licenses": ["Intel", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1686746988, "max_line_length": 88, "alphanum_fraction": 0.6350332594, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.5773307473405456}}
{"text": "#include \"pch.h\"\n\n// Slow, but simple csv parsing lib\n#include \"include/rapidcsv/rapidcsv.h\"\n\n// Boost matrix\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/range/algorithm.hpp>\n\nusing namespace boost::numeric::ublas;\nusing namespace std;\n\n\n////------------------------------COMMON OPERATIONS-----------------------------//\n\ntemplate <class T>\npair<T, T> getMatrixMinMax(matrix<T> * x)  // Could be changed to boost vector minMax\n{\n\tpair<T, T> minMax;\n\tminMax.first = (x)->operator()(0, 0); // Min\n\tminMax.second = (x)->operator()(0, 0); // Max\n\n\tfor (int m = 0; m < (x)->size1(); ++m)\n\t\tfor (int n = 0; n < (x)->size2(); n++)\n\t\t{\n\t\t\tT value = (x)->operator()(m, n);\n\t\t\tif (value < minMax.first)\n\t\t\t\tminMax.first = value;\n\t\t\tif (value > minMax.second)\n\t\t\t\tminMax.second = value;\n\n\t\t}\n\treturn minMax;\n}\n\ntemplate <class T>\nvoid normlizeMatrix(matrix<T> * x) {\n\n\tpair<T, T> minMax = getMatrixMinMax<T>(x);\n\tT range = minMax.second - minMax.first;\n\tfor (int m = 0; m < (x)->size1(); ++m)\n\t\tfor (int n = 0; n < (x)->size2(); n++)\n\t\t{\n\t\t\tT old_value = (x)->operator()(m, n);\n\t\t\t(x)->operator()(m, n) = (old_value - minMax.first) / range;\n\t\t}\n}\n\ntemplate <class T>\nvoid unsignMatrix(matrix<T> * x) {\n\n\tpair<T, T> minMax = getMatrixMinMax<T>(x);\n\tif (minMax.first >= 0) // If content not have no negative values -> do nothing\n\t{\n\t\treturn;\n\t}\n\telse // else, add make all values geater, than zero by substracting min value\n\t{\n\t\tfor (int m = 0; m < (x)->size1(); ++m)\n\t\t\tfor (int n = 0; n < (x)->size2(); n++)\n\t\t\t{\n\t\t\t\tT old_value = (x)->operator()(m, n);\n\t\t\t\t(x)->operator()(m, n) = old_value - minMax.first;\n\t\t\t}\n\t}\n}\n", "meta": {"hexsha": "e0ec2970dd8017fb47d58cc4b1c4ea5fc0cf12e5", "size": 1749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "KernelFiltering_Test/KernelFiltering_Test/kernelCommon.cpp", "max_stars_repo_name": "vcxz09876/kernelFiltering", "max_stars_repo_head_hexsha": "ceda31655cd869e7988f7eaa76cb79da0a54fb5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KernelFiltering_Test/KernelFiltering_Test/kernelCommon.cpp", "max_issues_repo_name": "vcxz09876/kernelFiltering", "max_issues_repo_head_hexsha": "ceda31655cd869e7988f7eaa76cb79da0a54fb5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KernelFiltering_Test/KernelFiltering_Test/kernelCommon.cpp", "max_forks_repo_name": "vcxz09876/kernelFiltering", "max_forks_repo_head_hexsha": "ceda31655cd869e7988f7eaa76cb79da0a54fb5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9857142857, "max_line_length": 85, "alphanum_fraction": 0.5917667238, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.577330730828736}}
{"text": "#pragma once\n#include \"trajopt/robot_and_dof.hpp\"\n\n#include \"osgviewer/osgviewer.hpp\"\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include \"utils/eigen_conversions.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace util;\n\nnamespace trajopt {\n\n#define STEP 0.00048828125\n\nclass TRAJOPT_API BeliefRobotAndDOF : public RobotAndDOF {\npublic:\n\tBeliefRobotAndDOF(OpenRAVE::RobotBasePtr _robot, const IntVec& _joint_inds, int _affinedofs=0, const OR::Vector _rotationaxis=OR::Vector());\n\n\tvoid ForwardKinematics(const VectorXd& dofs, Vector3d& eetrans);\n\n\tvoid SetBeliefValues(const DblVec& theta);\n\tDblVec GetBeliefValues();\n\n\tMatrixXd GetDynNoise();\n\tMatrixXd GetObsNoise();\n\n\tVectorXd Observe(const VectorXd& x, const VectorXd& r);\n\tVectorXd Dynamics(const VectorXd& x, const VectorXd& u, const VectorXd& q);\n\n\tMatrixXd dfdx(const VectorXd& x, const VectorXd& u, const VectorXd& q);\n\tMatrixXd dfdq(const VectorXd& x, const VectorXd& u, const VectorXd& q);\n\tMatrixXd dhdx(const VectorXd& x, const VectorXd& r);\n\tMatrixXd dhdr(const VectorXd& x, const VectorXd& r);\n\n\tVectorXd BeliefDynamics(const VectorXd& theta0, const VectorXd& u0);\n\tMatrixXd dgdb(const VectorXd& theta, const VectorXd& u);\n\tMatrixXd dgdu(const VectorXd& theta, const VectorXd& u);\n\n\tVectorXd VectorXdRand(int size);\n\tVectorXd mvnrnd(const VectorXd& mu, const MatrixXd& Sigma);\n\n\ttemplate <typename T> Matrix<T,Dynamic,1> toSigmaVec(const Matrix<T,Dynamic,Dynamic>& rt_S) {\n\t\tMatrix<T,Dynamic,1> rt_S_vec(s_dim);\n\t\tint idx = 0;\n\t\tfor (int i=0; i < x_dim; i++) {\n\t\t\tfor (int j=i; j < x_dim; j++) {\n\t\t\t\trt_S_vec[idx] = 0.5 * (rt_S(i,j)+rt_S(j,i));\n\t\t\t\tidx++;\n\t\t\t}\n\t\t}\n\t\treturn rt_S_vec;\n\t}\n\n\ttemplate <typename T> Matrix<T,Dynamic,Dynamic> toSigmaMatrix(const Matrix<T,Dynamic,1>& rt_S_vec) {\n\t\tMatrix<T,Dynamic,Dynamic> rt_S(x_dim, x_dim);\n\t\tint idx = 0;\n\t\tfor (int j = 0; j < x_dim; ++j) {\n\t\t\tfor (int i = j; i < x_dim; ++i) {\n\t\t\t\trt_S(i,j) = rt_S(j,i) = rt_S_vec[idx];\n\t\t\t\tidx++;\n\t\t\t}\n\t\t}\n\t\treturn rt_S;\n\t}\n\n\tvoid composeBelief(const VectorXd& x, const MatrixXd& rt_S, VectorXd& theta);\n\tvoid decomposeBelief(const VectorXd& theta, VectorXd& x, MatrixXd& rt_S);\n\n\tvoid ekfUpdate(const VectorXd& u0, const VectorXd& x0, const MatrixXd& rtSigma0, VectorXd& x, MatrixXd& rtSigma, bool observe, const VectorXd& z);\n\n\tMatrixXd sigmaPoints(const VectorXd& theta);\n\tMatrixXd sigmaPoints(const VectorXd& mean, const MatrixXd& sqrtcov);\n\tVectorXd sigmaPoint(const VectorXd& mean, const MatrixXd& cov, int idx);\n\n\tvoid ukfUpdate(const VectorXd& u0, const VectorXd& x0, const MatrixXd& rtSigma0, VectorXd& x, MatrixXd& rtSigma, bool observe, const VectorXd& z);\n\n\tvoid GetEndEffectorNoiseAsGaussian(const VectorXd& theta, Vector3d& mean, Matrix3d& cov);\n\n\tMatrixXd djdb(const VectorXd& theta, int sigma_pt_ind);\n\t// theta needs to be set accordingly before calling this (i.e. call SetBeliefValues)\n\tMatrixXd BeliefJacobian(int link_ind, int sigma_pt_ind, const OR::Vector& pt);\n\n\tvoid SetSigmaPointsScale(double scale) { sigma_pts_scale = scale; }\n\n\tinline int GetXDim() { return x_dim; }\n\tinline int GetBDim() { return b_dim; }\n\tinline int GetSDim() { return s_dim; }\n\tinline int GetQDim() { return q_dim; }\n\tinline int GetZDim() { return z_dim; }\n\tinline int GetRDim() { return r_dim; }\n\tinline int GetUDim() { return u_dim; }\n\n\tOR::KinBody::LinkPtr endeffector;\n\t// Scaled UKF update vars\n\tdouble alpha, beta, kappa;\n\nprivate:\n\tdouble sigma_pts_scale;\n\t// returns the indices of the terms in Sigma_vec that are in the jth column of the corresponding Sigma_matrix\n\tinline vector<int> sigmaColToSigmaIndices(int j) { return sigma_col_to_indices[j]; }\n\tvector<vector<int> > sigma_col_to_indices;\n\tboost::variate_generator<boost::mt19937, boost::normal_distribution<> > generator;\n\tDblVec sigma_vec;\n\tint x_dim, b_dim, s_dim, z_dim, q_dim, r_dim, u_dim;\n};\n\ntypedef boost::shared_ptr<BeliefRobotAndDOF> BeliefRobotAndDOFPtr;\n\nosg::Matrix gaussianAsTransform(const Vector3d& mean, const Matrix3d& cov);\n\n}\n", "meta": {"hexsha": "394211ac84f1bb0594c214455d0ccb4b4d84ab7e", "size": 4070, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/trajopt/belief.hpp", "max_stars_repo_name": "alexlee-gk/trajopt", "max_stars_repo_head_hexsha": "49f56583b22a921d88eede6b268181167b049b41", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-04-07T14:03:38.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-07T14:03:38.000Z", "max_issues_repo_path": "src/trajopt/belief.hpp", "max_issues_repo_name": "alexlee-gk/trajopt", "max_issues_repo_head_hexsha": "49f56583b22a921d88eede6b268181167b049b41", "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/trajopt/belief.hpp", "max_forks_repo_name": "alexlee-gk/trajopt", "max_forks_repo_head_hexsha": "49f56583b22a921d88eede6b268181167b049b41", "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.0862068966, "max_line_length": 147, "alphanum_fraction": 0.7393120393, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.5772823063806447}}
{"text": "#include \"utils/plotting.cpp\"\n#include \"utils/data_generator.cpp\"\n#include \"../src/analytical/linear/ls_solver.h\"\n#include \"../src/numerical/gauss-newton/gn_solver.h\"\n#include \"../src/numerical/gradient_descent/gd_solver.h\"\n#include \"../src/robust/ransac_solver.cpp\"\n#include \"../src/logging/easylogging++.h\"\n#include <armadillo>\n\nusing std::cout;\nusing std::endl;\n\nINITIALIZE_EASYLOGGINGPP\n\narma::mat WEIGHTS = {100, -20, 50, -0.5};\n\nint main(int argc, char *argv[])\n{\n    el::Configurations conf(\"./logging-config.conf\");\n    el::Loggers::reconfigureLogger(\"default\", conf);\n\n    auto data_generator = DataGenerator();\n    auto L = data_generator.generate_library();\n    std::vector<int> outlier_indices = {0, 5, 11, 13, 15, 18, 20, 25, 40, 60};\n    auto s = data_generator.generate_signal(WEIGHTS, outlier_indices);\n\n    LOG(INFO) << \"True: \" << WEIGHTS;\n\n    auto solver = GDSolver(L);\n    arma::mat result = solver.solve(s);\n    LOG(INFO) << \"Regular fit: \" << result;\n\n    int n_channels = 4;\n    int n_max_iter = 1000;\n    float accepted_error = 0.1;\n    int n_accepted_points = 70;\n    float objective_value_threshold = 0.0001;\n    std::shared_ptr<GDSolver> gd_solver_ptr(new GDSolver(solver));\n    auto ransac_solver = RansacSolver(gd_solver_ptr, n_channels, accepted_error, n_accepted_points, objective_value_threshold, n_max_iter);\n    auto solution = ransac_solver.solve(s);\n    LOG(INFO) << \"RANSAC fit: \" << solution;\n\n    auto estimate = ransac_solver.get_signal_estimate();\n\n#ifdef PLOT_FIGURES\n    plot_arma_vec(s);\n    plot_arma_vec(estimate);\n    plt::show();\n#endif\n\n    return 0;\n}", "meta": {"hexsha": "e9e0987ce2e52b14383dee955bd739b9641d7204", "size": 1602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/ransac_solver.cpp", "max_stars_repo_name": "omyllymaki/math", "max_stars_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T09:12:24.000Z", "max_issues_repo_path": "samples/ransac_solver.cpp", "max_issues_repo_name": "omyllymaki/math", "max_issues_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "samples/ransac_solver.cpp", "max_forks_repo_name": "omyllymaki/math", "max_forks_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8076923077, "max_line_length": 139, "alphanum_fraction": 0.6972534332, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5772491748732378}}
{"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": "#include \"initial_conditions/radial_wave.hpp\"\n#include <cmath>\n#include <boost/test/unit_test.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics/sum.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <fstream>\n#include <iostream>\n\nusing namespace boost::accumulators;\n\nusing accumulator_t = accumulator_set<double, stats<tag::sum, tag::mean, tag::variance, tag::max, tag::min > >;\n\nBOOST_AUTO_TEST_SUITE(radial_init_tests)\n\nBOOST_AUTO_TEST_CASE(phi_dist)\n{\n    using namespace boost;\n\n    init_cond::RadialWave3D wave(3);\n    wave.setEnergyNormalization(false);\n    wave.setParticleCount(1000000);\n    wave.init();\n    \n    std::size_t num_bins = 180;\n    \n    std::vector<std::size_t> counts(num_bins, 0);\n    // fix range\n    for(InitialCondition cond = wave.next(); cond; ++cond)\n    {\n        auto& vel = cond.getState().getVelocity();\n        double x = vel[0];\n        double y = vel[1];\n        double z = vel[2];\n        double c = std::sqrt(1 - z*z);\n        double phi = std::atan2(y/c, x/c);\n        //double azi = std::asin( z ) * 90 / std::acos(0);\n        double phi_deg = std::floor(phi * 90 / std::acos(0) + 180);\n        ++counts.at( int(phi_deg * num_bins / 360) );\n    }\n    \n    std::fstream res(\"result.txt\", std::fstream::out);\n    \n    accumulator_t acc;\n    \n    for(int i = 0; i < num_bins; ++i)\n    {\n        res << i << \" \" << counts[i] << std::endl; \n        acc(counts[i]);\n    }\n    \n    double mx = max(acc);\n    double mi = min(acc);\n    double disx = (mx / mean(acc)-1) * 100;\n    double disi = (1 - mi / mean(acc)) * 100;\n    double max_relative_error = std::max(disx, disi);\n    \n    double mean_relative_error = std::sqrt(variance(acc) / sum(acc)) / num_bins * 100;\n    \n    // check that mean error is lower than .025%\n    BOOST_CHECK( mean_relative_error < 0.025 );\n    \n    // check that maximum error is lower than 4.2%\n    BOOST_CHECK( max_relative_error < 4.2 );\n\n    std::cout << \"mean relative error: \" << mean_relative_error << \"%\\n\";\n    std::cout << \"max relative error: \"  << max_relative_error << \"%\\n\";\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ba6e503c96fb85d159fe04e95374f2f9b6541bcf", "size": 2392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tracer/test/sound_test (copy).cpp", "max_stars_repo_name": "ngc92/branchedflowsim", "max_stars_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tracer/test/sound_test (copy).cpp", "max_issues_repo_name": "ngc92/branchedflowsim", "max_issues_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tracer/test/sound_test (copy).cpp", "max_forks_repo_name": "ngc92/branchedflowsim", "max_forks_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4736842105, "max_line_length": 111, "alphanum_fraction": 0.639632107, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5771955950047696}}
{"text": "#include <dlib/dnn.h>\n#include <dlib/matrix.h>\n\n#include <experimental/filesystem>\n#include <iostream>\n#include <random>\n#include <regex>\n#include <sstream>\nnamespace fs = std::experimental::filesystem;\n\nint main(int argc, char** argv) {\n  using namespace dlib;\n  if (argc > 1) {\n    if (fs::exists(argv[1])) {\n      std::stringstream str_stream;\n      {\n        // replace categorial values with numeric ones\n        std::ifstream data_stream(argv[1]);\n        std::string data_string((std::istreambuf_iterator<char>(data_stream)),\n                                std::istreambuf_iterator<char>());\n\n        // replace string labels, because SharkML parssr can't handle strings\n        data_string =\n            std::regex_replace(data_string, std::regex(\"Iris-setosa\"), \"1\");\n        data_string =\n            std::regex_replace(data_string, std::regex(\"Iris-versicolor\"), \"2\");\n        data_string =\n            std::regex_replace(data_string, std::regex(\"Iris-virginica\"), \"3\");\n\n        str_stream << data_string;\n      }\n\n      matrix<double> data;\n      str_stream >> data;\n\n      std::cout << data << std::endl;\n\n      matrix<double> x_data = subm(data, 0, 0, data.nr(), data.nc() - 1);\n\n      std::vector<matrix<double>> samples;\n      for (int r = 0; r < x_data.nr(); ++r) {\n        samples.push_back(rowm(x_data, r));\n      }\n\n      // Normalization\n      // Standardization\n      matrix<double> m(mean(mat(samples)));\n      matrix<double> sd(reciprocal(stddev(mat(samples))));\n      for (size_t i = 0; i < samples.size(); ++i)\n        samples[i] = pointwise_multiply(samples[i] - m, sd);\n      std::cout << mat(samples) << std::endl;\n\n      // Another approach\n      // vector_normalizer<matrix<double>> normalizer;\n      // samples normalizer.train(samples);\n      // samples = normalizer(samples);\n    } else {\n      std::cerr << \"Invalid file path \" << argv[1] << std::endl;\n    }\n  } else {\n    std::cerr << \"Please provide a path to a dataset\\n\";\n  }\n  return 0;\n}\n", "meta": {"hexsha": "344f1fd41bb7844967adc33358e347a288a4ad26", "size": 1982, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter02/csv/dlib/csv_dlib.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": "Chapter02/csv/dlib/csv_dlib.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": "Chapter02/csv/dlib/csv_dlib.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": 30.4923076923, "max_line_length": 80, "alphanum_fraction": 0.5933400605, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5771561911622599}}
{"text": "\n#include <iostream>\n\n#include <harp_test.hpp>\n\n#include <boost/random.hpp>\n\nusing namespace std;\nusing namespace harp;\n\n#define DATASIZE 100\n#define SIGSIZE 6\n#define MAX 1000.0\n#define TOL 1.0e-6\n\nvoid harp::test_invcov ( string const & datadir ) {\n\n  int np;\n  int myp;\n\n  MPI_Comm_size ( MPI_COMM_WORLD, &np );\n  MPI_Comm_rank ( MPI_COMM_WORLD, &myp );\n\n  El::Grid grid ( El::mpi::COMM_WORLD );\n\n  if ( myp == 0 ) {\n    cerr << \"Testing inverse covariance construction...\" << endl;\n  }\n\n  cerr.precision(15);\n  cout.precision(15);\n  \n  // construct random sparse matrix\n\n  matrix_sparse AT ( SIGSIZE, DATASIZE, El::mpi::COMM_WORLD );\n\n  matrix_local compAT ( SIGSIZE, DATASIZE );\n  local_matrix_zero ( compAT );\n\n  size_t local_firstrow = AT.FirstLocalRow();\n  size_t local_rows = AT.LocalHeight();\n\n  typedef boost::ecuyer1988 base_generator_type;\n  base_generator_type generator(42u);\n\n  double rms = 0.5;\n  boost::normal_distribution < double > dist ( 0.0, rms );\n  boost::variate_generator < base_generator_type&, boost::normal_distribution < double > > gauss ( generator, dist );\n\n\n  AT.StartAssembly();\n\n  size_t nnz = 10;\n\n  AT.Reserve ( nnz * local_rows );\n\n  size_t col;\n\n  for ( size_t i = 0; i < SIGSIZE; ++i ) {\n\n    for ( size_t j = 0; j < nnz; ++j ) {\n\n      col = (size_t)( 2 * i + 8*j );\n\n      compAT.Set ( i, col, 1.0 );\n\n      if ( ( i >= local_firstrow ) && ( i < local_firstrow + local_rows ) ) {\n        AT.Update ( i, col, 1.0 );\n      }\n\n    }\n\n  }\n\n  AT.StopAssembly();\n\n  // truth\n\n  matrix_dist truth ( SIGSIZE, 1, grid );\n\n  matrix_local signal ( DATASIZE, 1 );\n\n  for ( int i = 0; i < SIGSIZE; ++i ) {\n    truth.Set ( i, 0, 40.0 + 10.0*(double)i );\n  }\n\n  spec_project ( AT, truth, signal );\n  \n  // fake noise covariance and measured data\n\n  matrix_local noise ( DATASIZE, 1 );\n\n  matrix_local measured ( DATASIZE, 1 );\n\n  matrix_local invpix ( DATASIZE, 1 );\n\n  for ( size_t i = 0; i < DATASIZE; ++i ) {\n    invpix.Set ( i, 0, 1.0/(rms * rms) );\n    noise.Set ( i, 0, gauss() );\n    measured.Set ( i, 0, signal.Get(i,0) + noise.Get(i,0) );\n  }\n\n  // RHS\n\n  matrix_dist z ( SIGSIZE, 1, grid );\n\n  noise_weighted_spec ( AT, invpix, measured, z );\n\n  \n  // construct test output\n\n  matrix_local compinv ( SIGSIZE, SIGSIZE );\n  local_matrix_zero ( compinv );\n\n  matrix_local compATN ( compAT );\n\n  for ( size_t i = 0; i < SIGSIZE; ++i ) {\n\n    for ( size_t j = 0; j < nnz; ++j ) {\n\n      col = (size_t)( 2 * i + 8*j );\n\n      compATN.Set ( i, col, 1.0/(rms * rms) );\n\n    }\n\n  }\n\n  El::Gemm ( El::NORMAL, El::TRANSPOSE, 1.0, compATN, compAT, 0.0, compinv );\n\n  if ( myp == 0 ) {\n    El::Print ( compinv, \"Serial inverse covariance\" );\n  }\n\n  // parallel implementation\n\n  matrix_dist inv ( SIGSIZE, SIGSIZE, grid );\n\n  inverse_covariance ( AT, invpix, inv );\n\n  El::Print ( inv, \"MPI inverse covariance\" );\n\n  // compare results in lower triangle\n\n  matrix_local local_inv ( SIGSIZE, SIGSIZE );\n  local_matrix_zero ( local_inv );\n\n  El::AxpyInterface < double > globloc;\n  globloc.Attach( El::GLOBAL_TO_LOCAL, inv );\n  globloc.Axpy ( 1.0, local_inv, 0, 0 );\n  globloc.Detach();\n\n  for ( size_t i = 0; i < SIGSIZE; ++i ) {\n    for ( size_t j = i; j < SIGSIZE; ++j ) {\n      double locval = local_inv.Get ( j, i );\n      double compval = compinv.Get ( j, i );\n      if ( fabs ( locval - compval ) / compval > TOL ) {\n        cerr << \"proc \" << myp << \" FAIL on element (\" << j << \", \" << i << \"); \" << locval << \" != \" << compval << endl;\n        exit(1);\n      }\n\n    }\n  }\n\n  if ( myp == 0 ) {\n    cerr << \"  (PASSED)\" << endl;\n    cerr << \"Testing extraction...\" << endl;\n  }\n\n  matrix_dist W ( SIGSIZE, SIGSIZE, grid );\n  matrix_dist D ( SIGSIZE, 1, grid );\n  eigen_decompose ( inv, D, W );\n\n  matrix_dist sq ( SIGSIZE, SIGSIZE, grid );\n  eigen_compose ( EIG_SQRT, D, W, sq );\n\n  El::Print ( sq, \"sqrt of invcov\" );\n\n  matrix_dist Rdirect ( sq );\n  matrix_dist R ( SIGSIZE, SIGSIZE, grid );\n  matrix_dist S ( SIGSIZE, 1, grid );\n\n  norm ( D, W, S );\n\n  El::Print ( S, \"column norm from eigen decomposition\" );\n\n  apply_norm ( S, Rdirect );\n\n  El::Print ( Rdirect, \"direct resolution matrix\" );\n\n  resolution ( D, W, S, R );\n\n  El::Print ( R, \"resolution matrix\" );\n\n  matrix_dist f ( SIGSIZE, 1, grid );\n\n  matrix_dist Rf ( SIGSIZE, 1, grid );\n\n  extract ( D, W, S, z, Rf, f );\n\n  matrix_dist Rtruth ( SIGSIZE, 1, grid );\n\n  El::Gemv ( El::NORMAL, 1.0, R, truth, 0.0, Rtruth );\n\n  for ( size_t i = 0; i < SIGSIZE; ++i ) {\n    double tr = truth.Get ( i, 0 );\n    double rt = Rtruth.Get ( i, 0 );\n    double rf = Rf.Get ( i, 0 );\n    double errval = S.Get ( i, 0 );\n    double ze = z.Get ( i, 0 );\n    if ( myp == 0 ) {\n      cout << \"  truth = \" << tr << \", z = \" << ze << \", convolved = \" << rt << \", Rf = \" << rf << \", err = \" << errval << endl;\n    }\n  }\n  \n\n  if ( myp == 0 ) {\n    cerr << \"  (PASSED)\" << endl;\n  }\n\n\n  return;\n}\n", "meta": {"hexsha": "b1b7ce50239afa1f84b50719c7a1ca2a3944d617", "size": 4866, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests-mpi/harp_test_invcov.cpp", "max_stars_repo_name": "tskisner/HARP", "max_stars_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests-mpi/harp_test_invcov.cpp", "max_issues_repo_name": "tskisner/HARP", "max_issues_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests-mpi/harp_test_invcov.cpp", "max_forks_repo_name": "tskisner/HARP", "max_forks_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7232142857, "max_line_length": 128, "alphanum_fraction": 0.5731607069, "num_tokens": 1587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5771561863219161}}
{"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 <codegenvar/Eigen>\n#include <codegenvar/BooleanEvaluator.h>\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace codegenvar;\n\nint main()\n{    \n    Mat2 m2 = namedMatrix(\"m\", 2, 2);\n    std::cout << \"m' = \" << std::endl << m2.inverse() << std::endl << std::endl;\n\n    BooleanEvaluator evaluator;\n    Mat m = namedMatrix(\"m\", 2, 2);\n    Mat inv(2, 2);\n    do\n    {\n        inv |= m.inverse();\n    } while (!evaluator.isFullyEvaluated());\n\n    std::cout << \"m11' = \" << std::endl << inv(0,0) << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "e83676c4b1ce3eaadbf60e353c27d75748e10c88", "size": 535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/eigen_inverse.cpp", "max_stars_repo_name": "bjornpiltz/CppCodeGenVar", "max_stars_repo_head_hexsha": "4f4707c88202695300e55db8909af29107bdc157", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-01-23T09:41:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T05:44:14.000Z", "max_issues_repo_path": "examples/eigen_inverse.cpp", "max_issues_repo_name": "bjornpiltz/CppCodeGenVar", "max_issues_repo_head_hexsha": "4f4707c88202695300e55db8909af29107bdc157", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-01-18T13:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-25T21:42:34.000Z", "max_forks_repo_path": "examples/eigen_inverse.cpp", "max_forks_repo_name": "bjornpiltz/CppCodeGenVar", "max_forks_repo_head_hexsha": "4f4707c88202695300e55db8909af29107bdc157", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2916666667, "max_line_length": 80, "alphanum_fraction": 0.5738317757, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476385, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.577150597570727}}
{"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": "#include <iostream>\n#include <cassert>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n\ntypedef boost::adjacency_list<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    Graph;\n\nvoid testcase()\n{\n  int m, n, k, c;\n  std::cin >> m >> n >> k >> c;\n  assert(m >= 0 && m <= 50 && n >= 0 && n <= 50);\n  assert(k >= 0 && k <= m * n);\n  assert(c >= 0 && c <= 4);\n\n  int total_nodes = 2 + 2 * m * n + m * (n + 1) + n * (m + 1);\n  Graph G(total_nodes);\n  int next_free_node = 0;\n  Graph::vertex_descriptor source_node = next_free_node++;\n  Graph::vertex_descriptor sink_node = next_free_node++;\n  auto node_from_intersection = [next_free_node, m, n](int col, int row, bool source_part) -> Graph::vertex_descriptor {\n    assert(col >= 0 && col < m && row >= 0 && row < n);\n    return next_free_node + 2 * (col * n + row) + (source_part ? 1 : 0);\n  };\n  next_free_node += 2 * m * n;\n  auto node_from_col_hall = [next_free_node, m, n](int col, int hall) -> Graph::vertex_descriptor {\n    assert(col >= 0 && col < m && hall >= 0 && hall <= n);\n    return next_free_node + col * (n + 1) + hall;\n  };\n  next_free_node += m * (n + 1);\n  auto node_from_row_hall = [next_free_node, m, n](int row, int hall) -> Graph::vertex_descriptor {\n    assert(row >= 0 && row < n && hall >= 0 && hall <= m);\n    return next_free_node + row * (m + 1) + hall;\n  };\n  next_free_node += n * (m + 1);\n  assert(next_free_node == total_nodes);\n\n  auto capacity_map = boost::get(boost::edge_capacity, G);\n  auto reverse_map = boost::get(boost::edge_reverse, G);\n  auto add_edge = [&G, &capacity_map, &reverse_map, total_nodes](int from, int to, int capacity) {\n    assert(from >= 0 && from < total_nodes && to >= 0 && to < total_nodes);\n    Graph::edge_descriptor e = boost::add_edge(from, to, G).first;\n    Graph::edge_descriptor rev_e = boost::add_edge(to, from, G).first;\n    capacity_map[e] = capacity;\n    capacity_map[rev_e] = 0;\n    reverse_map[e] = rev_e;\n    reverse_map[rev_e] = e;\n  };\n\n  for (int col = 0; col < m; col++)\n  {\n    add_edge(node_from_col_hall(col, 0), sink_node, 1);\n    add_edge(node_from_col_hall(col, n), sink_node, 1);\n    for (int i = 0; i < n; i++)\n    {\n      auto intersection_source = node_from_intersection(col, i, true);\n      auto intersection_target = node_from_intersection(col, i, false);\n      for (int hall : {i, i + 1})\n      {\n        auto hall_node = node_from_col_hall(col, hall);\n        add_edge(hall_node, intersection_source, 1);\n        add_edge(intersection_target, hall_node, 1);\n      }\n    }\n  }\n\n  for (int row = 0; row < n; row++)\n  {\n    add_edge(node_from_row_hall(row, 0), sink_node, 1);\n    add_edge(node_from_row_hall(row, m), sink_node, 1);\n    for (int i = 0; i < m; i++)\n    {\n      auto intersection_source = node_from_intersection(i, row, true);\n      auto intersection_target = node_from_intersection(i, row, false);\n      for (int hall : {i, i + 1})\n      {\n        auto hall_node = node_from_row_hall(row, hall);\n        add_edge(hall_node, intersection_source, 1);\n        add_edge(intersection_target, hall_node, 1);\n      }\n    }\n  }\n\n  for (int col = 0; col < m; col++)\n  {\n    for (int row = 0; row < n; row++)\n    {\n      add_edge(node_from_intersection(col, row, true), node_from_intersection(col, row, false), c);\n    }\n  }\n\n  for (int i = 0; i < k; i++)\n  {\n    int x, y;\n    std::cin >> x >> y;\n    assert(x >= 0 && x < m && y >= 0 && y < n);\n    add_edge(source_node, node_from_intersection(x, y, true), 1);\n  }\n\n  int flow = boost::push_relabel_max_flow(G, source_node, sink_node);\n  std::cout << flow << \"\\n\";\n}\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n\n  int t;\n  std::cin >> t;\n  for (int i = 0; i < t; i++)\n  {\n    testcase();\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "901255bc402d2b2ebfec55d7b7800cdad6f87bc9", "size": 4165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-06/knights/src/main.cpp", "max_stars_repo_name": "tehwalris/algolab", "max_stars_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T08:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T08:21:32.000Z", "max_issues_repo_path": "week-06/knights/src/main.cpp", "max_issues_repo_name": "tehwalris/algolab", "max_issues_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-06/knights/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1393442623, "max_line_length": 133, "alphanum_fraction": 0.5944777911, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5770440063302457}}
{"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 * Copyright (C) Omar Thor <omarthoro@gmail.com> - All Rights Reserved\n * Unauthorized copying of this file, via any medium is strictly prohibited\n * Proprietary and confidential\n *\n * Written by Omar Thor <omarthoro@gmail.com>, 2017\n */\n\n#define BOOST_TEST_MODULE sp_util_lookback\n#include <boost/test/unit_test.hpp>\n#include <string>\n\n#include <iostream>\n\n#include \"sp/util/lookback.hpp\"\n\nusing namespace sp::util;\n\nBOOST_AUTO_TEST_CASE( test_sp_util_lookback_simple) {\n\n    fixed_lookback<float> hist(20);\n\n\n    for(int i = 1; i < 20; ++i) {\n        BOOST_REQUIRE_EQUAL(hist.mean(i), 0.0f);\n    }\n\n    hist.tick(5);\n    hist.tick(5);\n    hist.tick(5);\n    hist.tick(5);\n    hist.tick(5);\n\n    BOOST_REQUIRE_EQUAL(hist.min(5), 5.0f);\n    BOOST_REQUIRE_EQUAL(hist.max(5), 5.0f);\n    BOOST_REQUIRE_EQUAL(hist.deriv(5), 0);\n    BOOST_REQUIRE_EQUAL(hist.mean(5), 5.0f);\n\n    BOOST_REQUIRE_EQUAL(hist.min(10), 0.0f);\n    BOOST_REQUIRE_EQUAL(hist.max(10), 5.0f);\n    BOOST_REQUIRE_EQUAL(hist.deriv(10), 5.0f / 9.0f);\n    BOOST_REQUIRE_EQUAL(hist.mean(10), 2.5f);\n\n    hist.tick(6);\n    hist.tick(7);\n    hist.tick(8);\n    hist.tick(9);\n    hist.tick(10);\n\n    BOOST_REQUIRE_EQUAL(hist.min(10), 5.0f);\n    BOOST_REQUIRE_EQUAL(hist.max(10), 10.0f);\n    BOOST_REQUIRE_EQUAL(hist.deriv(10), 5.0f / 9.0f);\n    BOOST_REQUIRE_EQUAL(hist.mean(10), 6.5f);\n\n    BOOST_REQUIRE_EQUAL(hist.min(20), 0.0f);\n    BOOST_REQUIRE_EQUAL(hist.max(20), 10.0f);\n    BOOST_REQUIRE_EQUAL(hist.deriv(20), 10.0f / 19.0f);\n    BOOST_REQUIRE_EQUAL(hist.mean(20), 3.25f);\n\n    hist.tick(11);\n    hist.tick(12);\n    hist.tick(13);\n    hist.tick(14);\n    hist.tick(15);\n    hist.tick(16);\n    hist.tick(17);\n    hist.tick(18);\n    hist.tick(19);\n    hist.tick(20);\n\n    BOOST_REQUIRE_EQUAL(hist.min(5), 16.0f);\n    BOOST_REQUIRE_EQUAL(hist.max(5), 20.0f);\n    BOOST_REQUIRE_EQUAL(hist.deriv(5), 1.0f);\n    BOOST_REQUIRE_EQUAL(hist.mean(10), 15.5f);\n\n    BOOST_REQUIRE_EQUAL(hist.min(20), 5.0f);\n    BOOST_REQUIRE_EQUAL(hist.max(20), 20.0f);\n    BOOST_REQUIRE_EQUAL(hist.deriv(20), 0.789473712f);\n    BOOST_REQUIRE_EQUAL(hist.mean(20), 11.0f);\n}\n\nBOOST_AUTO_TEST_CASE( test_sp_util_lookback_large) {\n\n    fixed_lookback<float> hist(100);\n\n    for(int i = 0; i < 100000; ++i) {\n        hist.tick(i);\n    }\n\n    BOOST_REQUIRE_EQUAL(hist.mean(99), 99950);\n}\nBOOST_AUTO_TEST_CASE( test_sp_util_lookback_running ) {\n\n    rolling_lookback<float> hist(0.1);\n\n    for(int i = 1; i <= 10; ++i) {\n        hist.tick(i);\n    }\n\n    BOOST_REQUIRE_EQUAL(hist.mean(), 4.13810539f);\n\n}\n\n\n", "meta": {"hexsha": "e4dcfae96a6e2c31229dee32ad217956ba5136f0", "size": 2539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_util_lookback.cpp", "max_stars_repo_name": "thorigin/sp", "max_stars_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_util_lookback.cpp", "max_issues_repo_name": "thorigin/sp", "max_issues_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "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": "test/test_util_lookback.cpp", "max_forks_repo_name": "thorigin/sp", "max_forks_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "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.180952381, "max_line_length": 75, "alphanum_fraction": 0.6573454116, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5770318345583247}}
{"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": "//==================================================================================================\n/*!\n  @file\n\n    @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_REM_2PI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REM_2PI_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 compute the remainder modulo \\f$2\\pi\\f$.\n\n\n\n    @par Header <boost/simd/function/rem_2pi.hpp>\n\n    @par Note\n\n     - The result is in \\f$[-\\pi, \\pi]\\f$.\n\n     - If the input is near \\f$\\pi\\f$ the output can be \\f$\\pi\\f$ or \\f$-\\pi\\f$\n      depending  on register disponibility if extended arithmetic is used.\n\n    @par Example:\n\n      @snippet rem_2pi.cpp rem_2pi\n\n    @par Possible output:\n\n      @snippet rem_2pi.txt rem_2pi\n\n  **/\n  IEEEValue rem_2pi(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/rem_2pi.hpp>\n#include <boost/simd/function/simd/rem_2pi.hpp>\n\n#endif\n", "meta": {"hexsha": "e59f19f8bf35bc3c11daccb4d40d7f296b04327a", "size": 1224, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/rem_2pi.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/rem_2pi.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/rem_2pi.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.48, "max_line_length": 100, "alphanum_fraction": 0.5874183007, "num_tokens": 297, "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": "// Boost.Geometry\r\n// Unit Test\r\n\r\n// Copyright (c) 2016-2018 Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n// Contributed and/or modified by Adeel Ahmad, as part of Google Summer of Code 2018 program\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include \"test_formula.hpp\"\r\n#include \"direct_cases.hpp\"\r\n#include \"direct_cases_antipodal.hpp\"\r\n\r\n#include <boost/geometry/formulas/vincenty_direct.hpp>\r\n#include <boost/geometry/formulas/thomas_direct.hpp>\r\n#include <boost/geometry/formulas/karney_direct.hpp>\r\n//#include <boost/geometry/formulas/series_expansion_direct.hpp>\r\n#include <boost/geometry/formulas/spherical.hpp>\r\n\r\n#include <boost/geometry/srs/srs.hpp>\r\n\r\ntemplate <typename Result>\r\nvoid check_direct(Result const& result, expected_result const& expected, expected_result const& reference,\r\n                  double reference_error, bool check_reference_only = false)\r\n{\r\n    check_direct_sph(result, expected, reference, reference_error, check_reference_only);\r\n    check_one(result.reduced_length, expected.reduced_length, reference.reduced_length, reference_error);\r\n    check_one(result.geodesic_scale, expected.geodesic_scale, reference.geodesic_scale, reference_error);\r\n}\r\n\r\ntemplate <typename Result>\r\nvoid check_direct_sph(Result const& result, expected_result const& expected, expected_result const& reference,\r\n                      double reference_error, bool check_reference_only = false)\r\n{\r\n    check_one(result.lon2, expected.lon2, reference.lon2, reference_error, true, check_reference_only);\r\n    check_one(result.lat2, expected.lat2, reference.lat2, reference_error, true, check_reference_only);\r\n    check_one(result.reverse_azimuth, expected.reverse_azimuth, reference.reverse_azimuth, reference_error, true, check_reference_only);\r\n}\r\n\r\nvoid test_all(expected_results const& results)\r\n{\r\n    double const d2r = bg::math::d2r<double>();\r\n    double const r2d = bg::math::r2d<double>();\r\n\r\n    double lon1r = results.p1.lon * d2r;\r\n    double lat1r = results.p1.lat * d2r;\r\n    double distance = results.distance;\r\n    double azi12r = results.azimuth12 * d2r;\r\n\r\n    double lon1d = results.p1.lon;\r\n    double lat1d = results.p1.lat;\r\n    double azi12d = results.azimuth12;\r\n\r\n    // WGS84\r\n    bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);\r\n    bg::srs::sphere<double> const sphere;\r\n\r\n    bg::formula::result_direct<double> result;\r\n\r\n    typedef bg::formula::vincenty_direct<double, true, true, true, true> vi_t;\r\n    result = vi_t::apply(lon1r, lat1r, distance, azi12r, spheroid);\r\n    result.lon2 *= r2d;\r\n    result.lat2 *= r2d;\r\n    result.reverse_azimuth *= r2d;\r\n    check_direct(result, results.vincenty, results.karney, 0.00000001);\r\n\r\n    typedef bg::formula::thomas_direct<double, true, true, true, true, true> th_t;\r\n    result = th_t::apply(lon1r, lat1r, distance, azi12r, spheroid);\r\n    result.lon2 *= r2d;\r\n    result.lat2 *= r2d;\r\n    result.reverse_azimuth *= r2d;\r\n    check_direct(result, results.thomas, results.karney, 0.0000001);\r\n\r\n    typedef bg::formula::thomas_direct<double, false, true, true, true, true> th_t1st;\r\n    result = th_t1st::apply(lon1r, lat1r, distance, azi12r, spheroid);\r\n    result.lon2 *= r2d;\r\n    result.lat2 *= r2d;\r\n    result.reverse_azimuth *= r2d;\r\n    check_direct(result, results.thomas1st, results.karney, 0.0000001);\r\n/*\r\n    typedef bg::formula::series_expansion_direct<double, true, true, true, true, 4> series;\r\n    result = series::apply(lon1r, lat1r, distance, azi12r, spheroid);\r\n    result.lon2 *= r2d;\r\n    result.lat2 *= r2d;\r\n    result.reverse_azimuth *= r2d;\r\n    check_direct(result, results.series, results.karney, 0.0000001);\r\n*/\r\n    result = bg::formula::spherical_direct<true, true>(lon1r, lat1r, distance,\r\n                                                       azi12r, sphere);\r\n    result.lon2 *= r2d;\r\n    result.lat2 *= r2d;\r\n    result.reverse_azimuth *= r2d;\r\n    check_direct_sph(result, results.spherical, results.karney, 0.1);\r\n\r\n    typedef bg::formula::karney_direct<double, true, true, true, true, 2> ka_t;\r\n    result = ka_t::apply(lon1d, lat1d, distance, azi12d, spheroid);\r\n    check_direct(result, results.thomas, results.karney, 0.0000001);\r\n}\r\n\r\nvoid test_karney_antipodal(expected_results_antipodal const& results)\r\n{\r\n    double lon1d = results.p1.lon;\r\n    double lat1d = results.p1.lat;\r\n    double distance = results.distance;\r\n    double azi12d = results.azimuth12;\r\n\r\n    // WGS84\r\n    bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);\r\n\r\n    bg::formula::result_direct<double> result;\r\n\r\n    typedef bg::formula::karney_direct<double, true, true, true, true, 8> ka_t;\r\n    result = ka_t::apply(lon1d, lat1d, distance, azi12d, spheroid);\r\n    check_direct(result, results.karney, results.karney, 0.0000001, true);\r\n}\r\n\r\nint test_main(int, char*[])\r\n{\r\n    for (size_t i = 0; i < expected_size; ++i)\r\n    {\r\n        test_all(expected[i]);\r\n    }\r\n\r\n    for (size_t i = 0; i < expected_size_antipodal; ++i)\r\n    {\r\n        test_karney_antipodal(expected_antipodal[i]);\r\n    }\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "8b0d36b65f6ebddd6ef6a7e02383c69d7a812834", "size": 5358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/libs/geometry/test/formulas/direct.cpp", "max_stars_repo_name": "Jackarain/tinyrpc", "max_stars_repo_head_hexsha": "07060e3466776aa992df8574ded6c1616a1a31af", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/geometry/test/formulas/direct.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "third_party/boost/libs/geometry/test/formulas/direct.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 39.6888888889, "max_line_length": 137, "alphanum_fraction": 0.6976483763, "num_tokens": 1456, "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 * @file crossprod.cc\n * @brief NPDE homework CrossProd code\n * @author Unknown, Oliver Rietmann\n * @date 31.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"crossprod.h\"\n\n#include <Eigen/Geometry>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nnamespace CrossProd {\n\n/* SAM_LISTING_BEGIN_0 */\nvoid tab_crossprod() {\n  // TO DO (13-1.e): solve the cross-product ODE with the implicit RK method\n  // defined in solve_imp_mid. Tabulate the norms of the results at all steps.\n  //====================\n  // Your code goes here\n  //====================\n  /* SAM_LISTING_END_0 */\n\n  /* SAM_LISTING_BEGIN_1 */\n  // TO DO (13-1.g): solve the cross-product ODE with the implicit RK method\n  // defined in solve_lin_mid. Tabulate the norms of the results at all steps.\n  //====================\n  // Your code goes here\n  //====================\n  /* SAM_LISTING_END_1 */\n}\n\n}  // namespace CrossProd\n", "meta": {"hexsha": "0eb902c8cc83a046e06c224c9dfe54767f888c89", "size": 916, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/CrossProd/templates/crossprod.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/CrossProd/templates/crossprod.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/CrossProd/templates/crossprod.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7567567568, "max_line_length": 78, "alphanum_fraction": 0.6299126638, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.5769460296415517}}
{"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": "#ifndef _DUAL_CC_ISOSURFACE_H_\n#define _DUAL_CC_ISOSURFACE_H_\n\n#include <sisl/sisl.hpp>\n#include <sisl/sparse_array.hpp>\n#include <sisl/utility/ply_writer.hpp>\n\n#include <Eigen/Dense>\n\n#include <tuple>\n#include <unordered_map>\n#include <map>\n\nnamespace sisl{\nnamespace utility{\nusing namespace std;\n\ntemplate<class T>\nclass dualcc_isosurface{\npublic:\n\tstruct cell_vertex\n\t{\n\t\tcell_vertex(){}\n\t\tstd::vector<vector3<T> > touching;\n\t\tvector3<T> vertex;\n\t\tint vertexId;\n\t};\n\n\tdualcc_isosurface() : face_hash_table(1,1,1, {}){\n\t\tthis->faceList.clear();\n\t}\n\n\n\ttemplate<class L, class I, class O>\n\tvoid contour(\n\t\t\tL *f,\n\t\t\tconst O &isoValue, \n\t\t\tconst I &scalingParameter,\n\t\t\tsisl::vector3<I> origin,\n\t\t\tsisl::vector3<I> boundary ){\n\n\t\tI dh = scalingParameter;\n\t\tint res = int(1./(dh));\n\t\tthis->faceList = sisl::sparse_array3<cell_vertex>(res+2, res+2, res+2, {});\n\n\t\t// Go over every lattice point\n\t\t#pragma omp parallel for\n\t\tfor(int i = 2; i < res-2; i++) {\n\t\t\t/* \n\t\t\t * We keep this local to each worker, so we only have to delve into \n\t\t\t * a critical section at the end of each loop\n\t\t\t */\n\t\t\tstd::vector<std::vector<vector3<int>>> localFaceList;\n\n\t\t\tfor(int j = 2; j < res-2; j++)\n\t\t\t\tfor(int k = 2; k < res-2; k++){\n\t\t\t\t\tint ii = i;\n\t\t\t\t\tint jj = j;\n\t\t\t\t\tint kk = k;\n\n\t\t\t\t\tO value = f->f(dh*ii, dh*jj, dh*kk) - isoValue;\n\n\t\t\t\t\t// For each face in the minimal amount of faces of\n\t\t\t\t\t// the polyhedron\n\t\t\t\t\tfor(auto idx : minimal_face_set) {\n\t\t\t\t\t\tauto polyhedron_vertex = polyhedron_vertices[idx];\n\t\t\t\t\t\tint x = polyhedron_vertex.i + ii, \n\t\t\t\t\t\t\ty = polyhedron_vertex.j + jj, \n\t\t\t\t\t\t\tz = polyhedron_vertex.k + kk;\n\t\t\t\t\t\tO next_value = f->f(dh*x, dh*y, dh*z) - isoValue;\n\t\t\t\t\t\tI zero_solution = 0.5; \n\n\t\t\t\t\t\tvector3<T> pv, n;\n\n\t\t\t\t\t\t// No sign change?\n\t\t\t\t\t\tif((next_value > 0 && value > 0) || (next_value <0 && value < 0))\n\t\t\t\t\t\t\tcontinue; // Whatever\n\n\t\t\t\t\t\t// Find the sign change.\n\t\t\t\t\t\tzero_solution = ((value - 0)/(value - next_value));\n\t\t\t\t\t\tpv = n = vector3<T>(x,y,z) - vector3<T>(ii,jj,kk);\n\t\t\t\t\t\tpv = vector3<T>(ii,jj,kk) + pv * zero_solution;\n\t\t\t\t\t\tn = n * (value > next_value ? -1 : 1);\n\n\n\t\t\t\t\t\t// Lookup all the dual points that touch this vertex\n\t\t\t\t\t\tstd::vector<int> adj = adj_index[idx - 1];\n\t\t\t\t\t\tstd::vector<std::vector<int>> luf = triangle_lookup[idx - 1];\n\n\t\t\t\t\t\t// Push all the faces into our local face list.\n\t\t\t\t\t\tfor(auto triangle : luf) {\n\t\t\t\t\t\t\tvector3<int> \n\t\t\t\t\t\t\t\t\thash1 = center_hash_offsets[triangle[0]] + vector3<int>(ii*2, jj*2, kk*2),\n\t\t\t\t\t\t\t\t\thash2 = center_hash_offsets[triangle[1]] + vector3<int>(ii*2, jj*2, kk*2),\n\t\t\t\t\t\t\t\t\thash3 = center_hash_offsets[triangle[2]] + vector3<int>(ii*2, jj*2, kk*2);\n\n\t\t\t\t\t\t\tvector3<int> t = (hash2 - hash1)%(hash3 - hash1);\n\t\t\t\t\t\t\tvector3<T> dir(t.i, t.j, t.k);\n\t\t\t\t\t\t\tif(dir * n > 0) localFaceList.push_back((std::vector<vector3<int>>){hash1, hash2, hash3});\n\t\t\t\t\t\t\telse localFaceList.push_back((std::vector<vector3<int>>){hash3, hash2, hash1});\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Mark the hashed dual vertex as having seen this primal vertex\n\t\t\t\t\t\tfor(auto jdx : adj) {\n\t\t\t\t\t\t\tvector3<int> hash = center_hash_offsets[jdx] + vector3<int>(ii*2, jj*2, kk*2);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t#pragma omp critical (hash_bash_bcc)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tface_hash_table(hash.i, hash.j, hash.k).touching.push_back({pv.i, pv.j, pv.k});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Merge the faces back in to global face list\n\t\t\t\t#pragma omp critical (lizst_cyst)\n\t\t\t\t{\n\t\t\t\t\tfaceList.reserve(faceList.size() + localFaceList.size());\n\t\t\t\t\tfaceList.insert(faceList.end(), localFaceList.begin(), localFaceList.end());\n\t\t\t\t}\n\t\t}\n\t\tprocessVertices<L,I,O>(f, dh);\n\t\tprocessFaces();\n\t}\n\n\tbool writeSurface(const std::string &out) const {\n\t\treturn output_mesh.writePly(out);\n\t}\n\nprivate:\n\ttemplate<class L, class I, class O>\n\tvoid processVertices(L *f, const I &dh){\n\t\t// Calculate the vertex for each cell\n\t\tfor (auto it = face_hash_table.siteMap.begin(); it != face_hash_table.siteMap.end(); ++it) {\n\t\t\tauto hash = it->first;\n\t\t\tauto vcache = it->second;\n\n\t\t\tstd::vector<vector3<T>> normals;\n\t\t\tfor(auto v : vcache.touching) \n\t\t\t\tnormals.push_back(f->grad_f(v*dh).normalize());\n\t\t\t\n\n\t\t\tauto pavg = optimize_for_feature(vcache.touching, normals) * dh;\n\t\t\tauto normal = f->grad_f(pavg).normalize();\n\t\t\t\n\t\t\tface_hash_table.siteMap[hash].vertexId = output_mesh.addVertex({pavg, normal});\n\t\t}\n\t}\n\n\tvoid processFaces(){\n\t\t/* Build the final face list */\n\t\tfor(auto face : faceList) {\n\t\t\tstd::vector<int> index_face; \n\t\t\tfor(auto hash : face) {\n\t\t\t\tindex_face.push_back(face_hash_table(hash.i, hash.j, hash.k).vertexId);\n\t\t\t}\n\t\t\toutput_mesh.addPolygon(index_face);\n\t\t}\n\t}\n\n\tstd::vector<std::vector<vector3<int>>> faceList;\n\tsisl::sparse_array3<cell_vertex> face_hash_table; \n\tutility::ply_writer<T> output_mesh;\n\t\n\tconst std::vector<vector3<int>> polyhedron_vertices = {\n\t\t{0,0,0}, {0,0,1}, {0,1,0}, {1,0,0},\n\t\t{-1,0,0},  {0,-1,0}, {0,0,-1},\n\t};\n\n\tconst std::vector<vector3<int>> center_hash_offsets = {\n\t\t{1,1,1}, {1,1,-1}, {1,-1,1}, {1,-1,-1}, \n\t\t{-1,1,1}, {-1,1,-1}, {-1,-1,1}, {-1,-1,-1},\n\t};\n\n\tconst std::vector<std::vector<int>> adj_index = {\n\t\t{0,2,4,6}, {0,4,1,5}, {0,2,3,1},\n\t\t{4,6,5,7}, {6,2,7,3}, {7,3,5,1}\n\t};\n\n\tconst std::vector<std::vector<std::vector<int>>> triangle_lookup = {\n\t\t{{0,2,4}, {2,4,6}}, {{0,4,1}, {4,1,5}},\n\t    {{0,2,3}, {3,1,0}}, {{4,6,5}, {6,5,7}},\n\t    {{6,2,7}, {2,7,3}}, {{7,3,5}, {3,5,1}}\n\t};\n\n\tconst std::vector<int> minimal_face_set = {2, 3, 6};\n\n\n\tvector3<T> optimize_for_feature(\n\t\t\tconst std::vector<vector3<T>> &points, \n\t\t\tconst std::vector<vector3<T>> &normals,\n\t\t\tconst T &threshold = 0.1,\n\t\t\tconst bool &optimize = true) {\n\t\tusing namespace Eigen;\n\t\ttypedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> EMatrix;\n\t\tvector3<T> center(0,0,0);\n\t\tEMatrix A(points.size(), 3), b(points.size(), 1);\n\t\tunsigned int i = 0; \n\n\t\t// Calculate the center and setup the matix\n\t\tfor(auto v : points) { \n\t\t\tcenter += v; \n\n\t\t\tA(i, 0) = v.i;\n\t\t\tA(i, 1) = v.j;\n\t\t\tA(i, 2) = v.k;\n\n\t\t\tb(i, 0) = points[i] * normals[i];\n\t\t\ti++;\n\t\t}\n\n\t\tcenter = center * (1./(T(points.size())));\n\n\n\n\t\treturn center;\n\t}\n\n};\n};\n};\n\n#endif // _DUAL_CC_ISOSURFACE_H_", "meta": {"hexsha": "881c84c94c831ea7b903aadd101cfa4e5573e6cd", "size": 6083, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sisl/utility/dualcc.hpp", "max_stars_repo_name": "jjh13/dual-marching", "max_stars_repo_head_hexsha": "cff7abc6a3a9ad4158aee93e2de4956f60658d53", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sisl/utility/dualcc.hpp", "max_issues_repo_name": "jjh13/dual-marching", "max_issues_repo_head_hexsha": "cff7abc6a3a9ad4158aee93e2de4956f60658d53", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-05-05T04:51:40.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-08T14:57:25.000Z", "max_forks_repo_path": "include/sisl/utility/dualcc.hpp", "max_forks_repo_name": "jjh13/dual-marching", "max_forks_repo_head_hexsha": "cff7abc6a3a9ad4158aee93e2de4956f60658d53", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2780269058, "max_line_length": 97, "alphanum_fraction": 0.6062797962, "num_tokens": 2003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5769347482028745}}
{"text": "#ifndef OBJECTIVE_HPP\n#define OBJECTIVE_HPP\n\n#include <math.h>\n#include <armadillo>\n#include \"wrap2Pi.hpp\"\n#include \"../dynamicalSystems/koopman/basis_functions/basis_template.hpp\"\n\n\n\nclass Objective {\n\npublic:\n    arma::mat Q;\n    arma::mat Qf;\n    arma::mat R;\n    arma::mat xd;\n    Basis* basis;\n\n    arma::mat Qfk;\n\n    Objective(arma::mat _Q, arma::mat _R, arma::mat _Qf, arma::vec _xd, Basis* _basis) {\n        Q = _Q;\n        R = _R;\n        Qf = _Qf;\n        xd = _xd;\n        basis = _basis;\n        arma::vec Qfkdiag = arma::ones<arma::vec>(_basis->_nX);\n        Qfk = arma::diagmat(Qfkdiag);\n\n    }\n\n    inline double l(const arma::vec& x, const arma::vec& u, const arma::vec& phi) {\n        arma::vec xn = x;\n        arma::vec fk = basis->fk(xn, u);\n        return  arma::as_scalar(0.5 * (xn.t() - xd.t()) * Q * (xn - xd));\n    }\n\n    arma::vec ldx(const arma::vec& x, const arma::vec& u, const arma::vec& phi) {\n        arma::vec xn = x;\n        arma::vec fk = basis->fk(xn, u);\n        return Q * (xn - xd);\n\n    }\n\n    double m(const arma::vec& x) {\n        return arma::as_scalar((x.t() - xd.t()) * Qf * (x - xd) );\n    }\n\n    arma::vec mdx(const arma::vec& x) {\n        return  Qf * (x - xd);\n    }\n\n    double get_cost(const arma::mat& x, const arma::mat& u, const arma::mat & phi) {\n        double J = 0.0;\n        for (int k = 0; k  < u.n_cols; k++ ) {\n            J += l(x.col(k), u.col(k), phi.col(k));\n        }\n        return J + m(x.tail_cols(1));\n    }\n\n};\n\n#endif\n", "meta": {"hexsha": "f35847cf4a683292908ab4281ee5efc59e54893c", "size": 1491, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/model_based_shared_control/src/robotlib/dSAClib/objective.hpp", "max_stars_repo_name": "argallab/model_based_shared_control", "max_stars_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T19:47:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:43:31.000Z", "max_issues_repo_path": "src/model_based_shared_control/src/robotlib/dSAClib/objective.hpp", "max_issues_repo_name": "argallab/model_based_shared_control", "max_issues_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/model_based_shared_control/src/robotlib/dSAClib/objective.hpp", "max_forks_repo_name": "argallab/model_based_shared_control", "max_forks_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-08T19:47:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T10:10:17.000Z", "avg_line_length": 22.9384615385, "max_line_length": 88, "alphanum_fraction": 0.5204560698, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5769347448110577}}
{"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": "//\n//  Copyright (c) 2018-2020, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019-2020, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n//  And we acknowledge the support from all contributors.\n\n\n#include <iostream>\n#include <algorithm>\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"utility.hpp\"\n\nBOOST_AUTO_TEST_SUITE ( test_tensor_functions)\n\n\nusing test_types = zip<int,float,std::complex<float>>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\n//using test_types = zip<int>::with_t<boost::numeric::ublas::layout::first_order>;\n\n\nstruct fixture\n{\n    using dynamic_extents_type = boost::numeric::ublas::extents<>;\n    fixture()\n      : extents {\n          dynamic_extents_type{1,1}, // 1\n          dynamic_extents_type{2,3}, // 2\n          dynamic_extents_type{2,3,1}, // 3\n          dynamic_extents_type{4,2,3}, // 4\n          dynamic_extents_type{4,2,3,5}} // 5\n    {\n    }\n\n    std::vector<dynamic_extents_type> extents;\n};\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_prod_vector, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type   = typename value::first_type;\n    using layout_type  = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n    using vector_type  = typename tensor_type::vector_type;\n\n\n    for(auto const& n : extents){\n\n        auto a = tensor_type(n, value_type{2});\n\n        for(auto m = 0u; m < ublas::size(n); ++m){\n\n            auto b = vector_type  (n[m], value_type{1} );\n\n            auto c = ublas::prod(a, b, m+1);\n\n            for(auto i = 0u; i < c.size(); ++i)\n                BOOST_CHECK_EQUAL( c[i] , value_type( static_cast< inner_type_t<value_type> >(n[m]) ) * a[i] );\n\n        }\n    }\n  auto n = extents[4];\n  auto a = tensor_type(n, value_type{2});\n  auto b = vector_type(n[0], value_type{1});\n\n  auto empty = vector_type{};\n\n  BOOST_CHECK_THROW(prod(a, b, 0), std::length_error);\n  BOOST_CHECK_THROW(prod(a, b, 9), std::length_error);\n  BOOST_CHECK_THROW(prod(a, empty, 2), std::length_error);\n\n}\n\nBOOST_AUTO_TEST_CASE( test_tensor_prod_vector_exception )\n{\n//    namespace ublas = boost::numeric::ublas;\n//    using value_type   = float;\n//    using layout_type  = ublas::layout::first_order;\n//    using d_tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n//    using vector_type  = typename d_tensor_type::vector_type;\n\n//    auto t1 = d_tensor_type{ublas::extents<>{},1.f};\n//    auto v1 = vector_type{3,value_type{1}};\n\n//    BOOST_REQUIRE_THROW(prod(t1,v1,0),std::length_error);\n//    BOOST_REQUIRE_THROW(prod(t1,v1,1),std::length_error);\n//    BOOST_REQUIRE_THROW(prod(t1,v1,3),std::length_error);\n}\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_prod_matrix, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type   = typename value::first_type;\n    using layout_type  = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n    using matrix_type  = typename tensor_type::matrix_type;\n\n\n    for(auto const& n : extents) {\n\n        auto a = tensor_type(n, value_type{2});\n\n        for(auto m = 0u; m < ublas::size(n); ++m){\n\n            auto b  = matrix_type  ( n[m], n[m], value_type{1} );\n\n            auto c = ublas::prod(a, b, m+1);\n\n            for(auto i = 0u; i < c.size(); ++i)\n                BOOST_CHECK_EQUAL( c[i] , value_type( static_cast< inner_type_t<value_type> >(n[m]) ) * a[i] );\n\n        }\n    }\n\n  auto n = extents[4];\n  auto a = tensor_type(n, value_type{2});\n  auto b = matrix_type(n[0], n[0], value_type{1});\n\n  auto empty = matrix_type{};\n\n  BOOST_CHECK_THROW(prod(a, b, 0), std::length_error);\n  BOOST_CHECK_THROW(prod(a, b, 9), std::length_error);\n  BOOST_CHECK_THROW(prod(a, empty, 2), std::invalid_argument);\n}\n\nBOOST_AUTO_TEST_CASE( test_tensor_prod_matrix_exception )\n{\n//    namespace ublas = boost::numeric::ublas;\n//    using value_type   = float;\n//    using layout_type  = ublas::layout::first_order;\n//    using d_extents_type = ublas::extents<>;\n//    using d_tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n//    using matrix_type  = typename d_tensor_type::matrix_type;\n\n//    auto t1 = d_tensor_type{d_extents_type{},1.f};\n//    auto m1 = matrix_type{3,3,value_type{1}};\n\n\n//    BOOST_REQUIRE_THROW(prod(t1,m1,0),std::length_error);\n//    BOOST_REQUIRE_THROW(prod(t1,m1,1),std::length_error);\n//    BOOST_REQUIRE_THROW(prod(t1,m1,3),std::length_error);\n}\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_prod_tensor_1, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type   = typename value::first_type;\n    using layout_type  = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n    // left-hand and right-hand side have the\n    // the same number of elements\n\n    for(auto const& na : extents) {\n\n        auto a  = tensor_type( na, value_type{2} );\n        auto b  = tensor_type( na, value_type{3} );\n\n        auto const pa = a.rank();\n\n        // the number of contractions is changed.\n        for( auto q = 0ul; q <= pa; ++q) { // pa\n\n            auto phi = std::vector<std::size_t> ( q );\n\n            std::iota(phi.begin(), phi.end(), 1ul);\n\n            auto c = ublas::prod(a, b, phi);\n\n            auto acc = value_type(1);\n            for(auto i = 0ul; i < q; ++i)\n                acc *= value_type( static_cast< inner_type_t<value_type> >( a.extents().at(phi.at(i)-1) ) );\n\n            for(auto i = 0ul; i < c.size(); ++i)\n                BOOST_CHECK_EQUAL( c[i] , acc * a[0] * b[0] );\n\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE( test_tensor_prod_tensor_1_exception )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type   = float;\n    using layout_type  = ublas::layout::first_order;\n    using d_extents_type = ublas::extents<>;\n    using d_tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n\n    std::vector<std::size_t> phia = {1,2,3};\n    std::vector<std::size_t> phib = {1,2,3,4,5};\n\n\n    auto t3 = d_tensor_type{d_extents_type{1,2},1.f};\n    auto t4 = d_tensor_type{d_extents_type{1,2},1.f};\n    BOOST_REQUIRE_THROW(prod(t3,t4,phia,phib),std::runtime_error);\n\n\n    auto t5 = d_tensor_type{d_extents_type{1,2,3,4},1.f};\n    auto t6 = d_tensor_type{d_extents_type{1,2},1.f};\n    BOOST_REQUIRE_THROW(prod(t5,t6,phia,phib),std::runtime_error);\n\n\n    auto t7 = d_tensor_type{d_extents_type{1,2,3,4,5},1.f};\n    auto t8 = d_tensor_type{d_extents_type{1,2,3,4,5},1.f};\n    BOOST_REQUIRE_THROW(prod(t7,t8,phia,phib),std::runtime_error);\n\n    std::vector<std::size_t> phia_2 = {1,2,3,5,4};\n    std::vector<std::size_t> phib_2 = {1,2,3,4,5};\n    auto t9 = d_tensor_type{d_extents_type{1,2,3,4,5,6},1.f};\n    auto t10 = d_tensor_type{d_extents_type{1,2,3,4,5,6},1.f};\n    BOOST_REQUIRE_THROW(prod(t9,t10,phia_2,phib_2),std::runtime_error);\n}\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_prod_tensor_2, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type   = typename value::first_type;\n    using layout_type  = typename value::second_type;    \n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n    using extents_type = typename tensor_type::extents_type;\n\n\n    auto compute_factorial = [](auto const& p){\n        auto f = 1ul;\n        for(auto i = 1u; i <= p; ++i)\n            f *= i;\n        return f;\n    };\n\n    auto permute_extents = [](auto const& pi, auto const& na){\n      auto nb_base = na.base();\n      assert(pi.size() == ublas::size(na));\n      for(auto j = 0u; j < pi.size(); ++j)\n        nb_base[pi[j]-1] = na[j];\n      return extents_type(nb_base);\n    };\n\n\n    // left-hand and right-hand side have the\n    // the same number of elements\n\n    for(auto const& na : extents) {\n\n        auto a  = tensor_type( na, value_type{2} );\n        auto const pa = a.rank();\n\n\n        auto pi   = std::vector<std::size_t>(pa);\n        auto fac = compute_factorial(pa);\n        std::iota( pi.begin(), pi.end(), 1 );\n\n        for(auto f = 0ul; f < fac; ++f)\n        {\n            auto nb = permute_extents( pi, na  );\n            auto b  = tensor_type( nb, value_type{3} );\n\n            // the number of contractions is changed.\n            for( auto q = 0ul; q <= pa; ++q) { // pa\n\n                auto phia = std::vector<std::size_t> ( q );  // concatenation for a\n                auto phib = std::vector<std::size_t> ( q );  // concatenation for b\n\n                std::iota(phia.begin(), phia.end(), 1ul);\n                std::transform(  phia.begin(), phia.end(), phib.begin(),\n                                 [&pi] ( std::size_t i ) { return pi.at(i-1); } );\n\n                auto c = ublas::prod(a, b, phia, phib);\n\n                auto acc = value_type(1);\n                for(auto i = 0ul; i < q; ++i)\n                    acc *= value_type( static_cast< inner_type_t<value_type> >( a.extents().at(phia.at(i)-1) ) );\n\n                for(auto i = 0ul; i < c.size(); ++i)\n                    BOOST_CHECK_EQUAL( c[i] , acc * a[0] * b[0] );\n\n            }\n\n            std::next_permutation(pi.begin(), pi.end());\n        }\n    }\n\n    auto phia = std::vector<std::size_t >(3);\n    auto sphia = std::vector<std::size_t>(2);\n\n//    BOOST_CHECK_THROW(ublas::prod(tensor_type{}, tensor_type({2,1,2}), phia, phia), std::runtime_error);\n//        BOOST_CHECK_THROW(ublas::prod(tensor_type({1,2,3}), tensor_type(), phia, phia), std::runtime_error);\n        BOOST_CHECK_THROW(ublas::prod(tensor_type{1,2,4}, tensor_type{2,1}, phia, phia), std::runtime_error);\n        BOOST_CHECK_THROW(ublas::prod(tensor_type{1,2}, tensor_type{2,1,2}, phia, phia), std::runtime_error);\n        BOOST_CHECK_THROW(ublas::prod(tensor_type{1,2}, tensor_type{2,1,3}, sphia, phia), std::runtime_error);\n        BOOST_CHECK_THROW(ublas::prod(tensor_type{1,2}, tensor_type{2,2}, phia, sphia), std::runtime_error);\n        BOOST_CHECK_THROW(ublas::prod(tensor_type{1,2}, tensor_type{4,4}, sphia, phia), std::runtime_error);\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_inner_prod, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type   = typename value::first_type;\n    using layout_type  = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n\n    for(auto const& n : extents) {\n\n        auto a  = tensor_type(n, value_type(2));\n        auto b  = tensor_type(n, value_type(1));\n\n        auto c = ublas::inner_prod(a, b);\n        auto r = std::inner_product(a.begin(),a.end(), b.begin(),value_type(0));\n\n        BOOST_CHECK_EQUAL( c , r );\n\n    }\n  BOOST_CHECK_THROW(ublas::inner_prod(tensor_type{1,2,3}, tensor_type{1,2,3,4}), std::length_error); // rank different\n//  BOOST_CHECK_THROW(ublas::inner_prod(tensor_type(), tensor_type()), std::length_error); //empty tensor\n  BOOST_CHECK_THROW(ublas::inner_prod(tensor_type{1,2,3}, tensor_type{3,2,1}), std::length_error); // different extent\n}\n\n\nBOOST_AUTO_TEST_CASE( test_tensor_inner_prod_exception )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type   = float;\n    using layout_type  = ublas::layout::first_order;\n    using d_extents_type = ublas::extents<>;\n    using d_tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n    auto t1 = d_tensor_type{d_extents_type{1,2},1.f};\n    auto t2 = d_tensor_type{d_extents_type{1,2,3},1.f};\n    BOOST_REQUIRE_THROW( ublas::inner_prod(t1, t2), std::length_error);\n}\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_norm, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type   = typename value::first_type;\n    using layout_type  = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n\n    for(auto const& n : extents) {\n\n        auto a  = tensor_type(n);\n\n        auto one = value_type(1);\n        auto v = one;\n        for(auto& aa: a)\n            aa = v, v += one;\n\n\n        auto c = ublas::inner_prod(a, a);\n        auto r = std::inner_product(a.begin(),a.end(), a.begin(),value_type(0));\n\n        tensor_type var = (a+a)/value_type(2); // std::complex<float>/int not allowed as expression is captured\n        auto r2 = ublas::norm( var );\n\n//        BOOST_CHECK_THROW(ublas::norm(tensor_type{}), std::runtime_error);\n\n        BOOST_CHECK_EQUAL( c , r );\n        BOOST_CHECK_EQUAL( std::sqrt( c ) , r2 );\n\n    }\n}\n\nBOOST_FIXTURE_TEST_CASE( test_tensor_real_imag_conj, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type   = float;\n    using complex_type = std::complex<value_type>;\n    using layout_type  = ublas::layout::first_order;\n\n    using tensor_complex_type  = ublas::tensor_dynamic<complex_type, layout_type>;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n    for(auto const& n : extents) {\n\n        auto a   = tensor_type(n);\n        auto r0  = tensor_type(n);\n        auto r00 = tensor_complex_type(n);\n\n\n        auto one = value_type(1);\n        auto v = one;\n        for(auto& aa: a)\n            aa = v, v += one;\n\n        tensor_type b = (a+a) / value_type( 2 );\n        tensor_type r1 = ublas::real( (a+a) / value_type( 2 )  );\n        std::transform(  b.begin(), b.end(), r0.begin(), [](auto const& l){ return std::real( l );  }   );\n        BOOST_CHECK( (bool) (r0 == r1) );\n\n        tensor_type r2 = ublas::imag( (a+a) / value_type( 2 )  );\n        std::transform(  b.begin(), b.end(), r0.begin(), [](auto const& l){ return std::imag( l );  }   );\n        BOOST_CHECK( (bool) (r0 == r2) );\n        \n        tensor_complex_type r3 = ublas::conj( (a+a) / value_type( 2 )  );\n        std::transform(  b.begin(), b.end(), r00.begin(), [](auto const& l){ return std::conj( l );  }   );\n        BOOST_CHECK( (bool) (r00 == r3) );\n\n    }\n\n    for(auto const& n : extents) {\n\n        auto a   = tensor_complex_type(n);\n\n        auto r00 = tensor_complex_type(n);\n        auto r0  = tensor_type(n);\n\n\n        auto one = complex_type(1,1);\n        auto v = one;\n        for(auto& aa: a)\n            aa = v, v = v + one;\n\n        tensor_complex_type b = (a+a) / complex_type( 2,2 );\n\n\n        tensor_type r1 = ublas::real( (a+a) / complex_type( 2,2 )  );\n        std::transform(  b.begin(), b.end(), r0.begin(), [](auto const& l){ return std::real( l );  }   );\n        BOOST_CHECK( (bool) (r0 == r1) );\n\n        tensor_type r2 = ublas::imag( (a+a) / complex_type( 2,2 )  );\n        std::transform(  b.begin(), b.end(), r0.begin(), [](auto const& l){ return std::imag( l );  }   );\n        BOOST_CHECK( (bool) (r0 == r2) );\n\n        tensor_complex_type r3 = ublas::conj( (a+a) / complex_type( 2,2 )  );\n        std::transform(  b.begin(), b.end(), r00.begin(), [](auto const& l){ return std::conj( l );  }   );\n        BOOST_CHECK( (bool) (r00 == r3) );\n\n\n\n    }\n\n\n\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_outer_prod, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type   = typename value::first_type;\n    using layout_type  = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n    for(auto const& n1 : extents) {\n        auto a  = tensor_type(n1, value_type(2));\n        for(auto const& n2 : extents) {\n\n            auto b  = tensor_type(n2, value_type(1));\n            auto c  = ublas::outer_prod(a, b);\n\n            for(auto const& cc : c)\n                BOOST_CHECK_EQUAL( cc , a[0]*b[0] );\n        }\n    }\n}\n\ntemplate<class V>\nvoid init(std::vector<V>& a)\n{\n    auto v = V(1);\n    for(auto i = 0u; i < a.size(); ++i, ++v){\n        a[i] = v;\n    }\n}\n\ntemplate<class V>\nvoid init(std::vector<std::complex<V>>& a)\n{\n    auto v = std::complex<V>(1,1);\n    for(auto i = 0u; i < a.size(); ++i){\n        a[i] = v;\n        v.real(v.real()+1);\n        v.imag(v.imag()+1);\n    }\n}\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_trans, value,  test_types, fixture )\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type   = typename value::first_type;\n    using layout_type  = typename value::second_type;\n    using tensor_type  = ublas::tensor_dynamic<value_type,layout_type>;\n\n    auto fak = [](auto const& p){\n        auto f = 1ul;\n        for(auto i = 1u; i <= p; ++i)\n            f *= i;\n        return f;\n    };\n\n    auto inverse = [](auto const& pi){\n        auto pi_inv = pi;\n        for(auto j = 0u; j < pi.size(); ++j)\n            pi_inv[pi[j]-1] = j+1;\n        return pi_inv;\n    };\n\n    for(auto const& n : extents)\n    {\n      auto const p = ublas::size(n);\n      auto const s = ublas::product(n);\n        auto aref = tensor_type(n);\n        auto v    = value_type{};\n        for(auto i = 0u; i < s; ++i, v+=1)\n            aref[i] = v;\n        auto a    = aref;\n\n\n        auto pi = std::vector<std::size_t>(p);\n        std::iota(pi.begin(), pi.end(), 1);\n        a = ublas::trans( a, pi );\n        bool res1 = a == aref;\n        BOOST_CHECK( res1 );\n\n\n        auto const pfak = fak(p);\n        auto i = 0u;\n        for(; i < pfak-1; ++i) {\n            std::next_permutation(pi.begin(), pi.end());\n            a = ublas::trans( a, pi );\n        }\n        std::next_permutation(pi.begin(), pi.end());\n        for(; i > 0; --i) {\n            std::prev_permutation(pi.begin(), pi.end());\n            auto pi_inv = inverse(pi);\n            a = ublas::trans( a, pi_inv );\n        }\n        bool res2 = a == aref; // it was an expression. so evaluate into bool\n        BOOST_CHECK( res2 );\n\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c5a55048c4e9a80c42112f360d40beb16d0b072d", "size": 17950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_functions.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_functions.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_functions.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 32.3423423423, "max_line_length": 149, "alphanum_fraction": 0.60545961, "num_tokens": 5210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5769068750494755}}
{"text": "#include \"math_unit_test.hpp\"\n#include <boost/math/fft/bsl_backend.hpp>\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/constants/constants.hpp>\n\n#include <algorithm>\n#include <list>\n#include <type_traits>\n#include <complex>\n#include <vector>\n#include <limits>\n#include <cmath>\n#include <random>\n\nusing namespace boost::math::fft;\n\ntemplate<class T>\nstd::vector<std::complex<T>> random_vector(int N)\n{\n  using local_vector_complex_type = std::vector<std::complex<T>>;\n\n  std::mt19937 rng;\n  std::uniform_real_distribution<T> U(0.0,1.0);\n  local_vector_complex_type A(N);\n  for(auto& x: A)\n  {\n    x.real( U(rng) );\n    x.imag( U(rng) );\n  }\n  return A;\n}\ntemplate<class Container1, class Container2>\ntypename Container1::value_type::value_type difference(const Container1& A, const Container2& B)\n{\n  BOOST_MATH_ASSERT_MSG( A.size()==B.size(), \"Different container sizes.\");\n  using ComplexType = typename Container1::value_type;\n  using RealType = typename ComplexType::value_type;\n  const RealType inv_N = RealType{1}/B.size();\n  RealType diff =\n    std::inner_product(\n      A.begin(),A.end(),\n      B.begin(),\n      RealType{0.0},\n      std::plus<RealType>(),\n      [inv_N](const ComplexType & a, const ComplexType& b)\n      {\n        return std::norm(a-b*inv_N);\n      });\n  diff = std::sqrt(diff)/A.size();\n  return diff;\n}\n\ntemplate<class Backend>\nvoid test_inverse(int N, int tolerance)\n{\n  using ComplexType = typename Backend::value_type;\n  using RealType    = typename ComplexType::value_type;\n  \n  const RealType tol = tolerance*std::numeric_limits<RealType>::epsilon();\n  const std::vector< ComplexType > A{random_vector<RealType>(N)};\n  \n  Backend plan(1);\n  {\n    std::vector<ComplexType> B(N), C(N);\n    \n    plan.forward(std::begin(A),std::end(A),std::begin(B));\n    plan.backward(std::begin(B),std::end(B),std::begin(C));\n    \n    RealType diff{difference(A,C)};\n    CHECK_MOLLIFIED_CLOSE(RealType{0.0},diff,tol);\n  }\n  {\n    std::vector<ComplexType>  C(N);\n    std::list<ComplexType> B;\n\n    plan.forward(std::begin(A),std::end(A),std::back_inserter(B));\n    plan.backward(std::begin(B),std::end(B),std::begin(C));\n\n    RealType diff{difference(A,C)};\n    CHECK_MOLLIFIED_CLOSE(RealType{0.0},diff,tol);\n  }\n  {\n    std::list<ComplexType> C;\n\n    plan.forward(std::begin(A),std::end(A),std::back_inserter(C));\n    plan.backward(std::begin(C),std::end(C),std::begin(C));\n\n    RealType diff{difference(A,C)};\n    CHECK_MOLLIFIED_CLOSE(RealType{0.0},diff,tol);\n  }\n}\n\n#if defined(__GNUC__)\ntemplate<class T>\nusing complex_fftw_dft = fftw_dft< boost::multiprecision::complex<T>  >;\n\ntemplate<class T>\nusing complex_gsl_dft = gsl_dft< boost::multiprecision::complex<T>  >;\n#endif\n\ntemplate<class T>\nusing complex_bsl_dft = bsl_dft< boost::multiprecision::complex<T>  >;\n\nint main()\n{\n  for(int i=1;i<=(1<<12); i*=2)\n  {\n#if defined(__GNUC__)\n    test_inverse<complex_fftw_dft<float>>(i,1);\n    test_inverse<complex_fftw_dft<double>>(i,1);\n    test_inverse<complex_fftw_dft<long double>>(i,1);\n\n    test_inverse<complex_gsl_dft<double>>(i,1);\n#endif\n\n    test_inverse<complex_bsl_dft<float>>(i,1);\n    test_inverse<complex_bsl_dft<double>>(i,1);\n    test_inverse<complex_bsl_dft<long double>>(i,1);\n  }\n  return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "c5333f37583b9dab13d388a94e76c805a2cadd23", "size": 3349, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fft_iterators.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/fft_iterators.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/fft_iterators.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": 26.792, "max_line_length": 96, "alphanum_fraction": 0.6837862048, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6959583124210895, "lm_q1q2_score": 0.5769068659040535}}
{"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": "// Software License for MTL\r\n//\r\n// Copyright (c) 2007 The Trustees of Indiana University.\r\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\r\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\r\n// All rights reserved.\r\n// Authors: Peter Gottschling and Andrew Lumsdaine\r\n//\r\n// This file is part of the Matrix Template Library\r\n//\r\n// See also license.mtl.txt in the distribution.\r\n\r\n// File: dense_lu_test.cpp\r\n#include <iostream>\r\n#include <boost/numeric/mtl/mtl.hpp>\r\n\r\ntemplate <typename Matrix>\r\nvoid singularity_test(const Matrix& A)\r\n{\r\n     try {\r\n\tMatrix B(lu_f(A));\r\n\r\n    } catch (mtl::matrix_singular excp) {\r\n\tstd::cout << \"Exception for singularity successfully caught\\n\"; return;\r\n    }\r\n    throw \"Singularity not detected\";\r\n}\r\n\r\n\r\nint main(int , char**)\r\n{\r\n    using namespace mtl;\r\n    dense2D<double, mat::parameters<tag::col_major> > A(5, 5);\r\n    dense2D<double, mat::parameters<tag::col_major> > B(5, 5);\r\n    dense2D<float, mat::parameters<tag::col_major> > bsp(4, 4);\r\n    dense2D<float, mat::parameters<tag::col_major> > bsp1(4, 4);\r\n\r\n    bsp(0,0)=0;\r\n    bsp(0,1)=0;\r\n    bsp(0,2)=1;\r\n    bsp(0,3)=1;\r\n    bsp(1,0)=2;\r\n    bsp(1,1)=2;\r\n    bsp(1,2)=2;\r\n    bsp(1,3)=2;\r\n    bsp(2,0)=1;\r\n    bsp(2,1)=2;\r\n    bsp(2,2)=2;\r\n    bsp(2,3)=2;\r\n    bsp(3,0)=1;\r\n    bsp(3,1)=2;\r\n    bsp(3,2)=3;\r\n    bsp(3,3)=6;\r\n\r\n    // Assign a three times the identity to A\r\n    A= 3;\r\n    A(2,3)=7.0;\r\n    A(3,0)=7.0;\r\n    A(4,1)=7.0;\r\n    B=A;\r\n    std::cout << \"bsp is \\n\" << bsp << \"\\n\";\r\n    bsp1 = bsp;\r\n    singularity_test(bsp1);\r\n    // bsp1=lu_f(bsp1); // throws exception\r\n\r\n    mtl::dense_vector<int> P;\r\n    lu(bsp, P);\r\n    std::cout << \"LU(bsp) with pivoting \\n\" << bsp << \"Permutation is \" << P << \"\\n\";\r\n    std::cout << \"LU_f(bsp) \\n\" << bsp1 << \"\\n\";\r\n\r\n    std::cout << \"A is \\n\" << A << \"\\n\";\r\n    A=lu_f(A);\r\n    std::cout << \"LU_f(A) is \\n\" << A << \"\\n\";\r\n    lu(B, P);\r\n    std::cout << \"LU with pivoting is \\n\" << with_format(B, 5, 2) << \"Permutation is \" << P << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "96754f43fda1358071bf3a9179723420f1fed693", "size": 2094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/dense_lu_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/numeric/mtl/test/dense_lu_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/mtl/test/dense_lu_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5063291139, "max_line_length": 101, "alphanum_fraction": 0.5520534862, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580806813577, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.5767488879567628}}
{"text": "#include <cmath>\n#include <string>\n#include <iostream>\n#include <stdexcept>\n#include <limits>\n#include <boost/multiprecision/cpp_dec_float.hpp> \n#include \"ARPoly.h\"\n#include \"GaussSeq.h\"\n#include \"utils.h\"\nusing utils::my_float;\n\n\n/*\n *  Constructors and destructors\n */\nARPoly::ARPoly(std::map<int, my_float> mp, std::map<int, my_float> powers):\n    ARSeq(mp),\n    powers{powers}\n{}\nARPoly::ARPoly(std::map<int, my_float> mp, std::map<int, my_float> powers, my_float bias):\n    ARSeq(mp, bias),\n    powers{powers}\n{}\n\n/*\n *  Member functions\n */\nmy_float ARPoly::next() {\n    namespace mp = boost::multiprecision;\n    std::vector<my_float> copy_prev = prev_val;\n\n    for (const auto& ele : powers) {\n        float possible_val = mp::pow(prev_val[ele.first - 1], ele.second).convert_to<float>();\n        if (std::fpclassify(possible_val == FP_NAN) {\n            throw std::runtime_error(\"Exponentiation returns complex value!\");\n        }\n        if (std::fabs(possible_val - std::numeric_limits<float>::max()) < std::numeric_limits<float>::epsilon()) {\n            throw std::runtime_error(\"Exponentiation returns infinite value!\");\n        }\n        // subtract one since the zero-index is the previous value\n        copy_prev[ele.first - 1] = mp::pow(prev_val[ele.first - 1], ele.second);\n    }\n    // Since the lag coefficients are only non-zero at non-zero constants, take the dot-product\n    my_float result = utils::dot_product(copy_prev, lag_coeff) + g.next() + bias;\n    utils::shift_vector(prev_val);\n    prev_val[0] = result;\n    return result;\n}\n", "meta": {"hexsha": "2efdb6e5394bedc1eb16aebf5dbb2b86bd7ff846", "size": 1558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gen-data/lib/ARPoly.cpp", "max_stars_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_stars_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gen-data/lib/ARPoly.cpp", "max_issues_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_issues_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gen-data/lib/ARPoly.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": 31.7959183673, "max_line_length": 114, "alphanum_fraction": 0.6636713736, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5767310210741354}}
{"text": "#define BOOST_TEST_MODULE BNMR_SLR\n#include <boost/test/included/unit_test.hpp>\n\n#include <cmath>\n#include <triumf/bnmr/nuclei.hpp>\n#include <triumf/bnmr/slr/bi_exp.hpp>\n#include <triumf/bnmr/slr/cbrt_exp.hpp>\n#include <triumf/bnmr/slr/exp.hpp>\n#include <triumf/bnmr/slr/gauss_dist_exp.hpp>\n#include <triumf/bnmr/slr/magnesium_31/exp.hpp>\n#include <triumf/bnmr/slr/mod_str_exp.hpp>\n#include <triumf/bnmr/slr/sq_exp.hpp>\n#include <triumf/bnmr/slr/sqrt_exp.hpp>\n#include <triumf/bnmr/slr/str_exp.hpp>\n#include <triumf/numpy.hpp>\n#include <tuple>\n\ntypedef std::tuple<float, double, long double> test_types;\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(pulsed_exp, T, test_types) {\n  //\n  constexpr T pulse_length = 4.0;\n  constexpr T nuclear_lifetime = triumf::bnmr::nuclei::lithium_8<T>::lifetime();\n  constexpr T initial_asymmetry = 1.0;\n  constexpr T slr_rate = 1.0;\n  //\n  BOOST_TEST(triumf::bnmr::slr::pulsed_exp<T>(-1.0, nuclear_lifetime,\n                                              pulse_length, initial_asymmetry,\n                                              slr_rate) == 0.0);\n  BOOST_TEST(triumf::bnmr::slr::pulsed_exp<T>(0.0, nuclear_lifetime,\n                                              pulse_length, initial_asymmetry,\n                                              slr_rate) == initial_asymmetry);\n  //\n  for (auto &time : triumf::numpy::linspace<T>(0.0, 16.0, 100)) {\n    BOOST_TEST(triumf::bnmr::slr::pulsed_exp<T>(time, nuclear_lifetime,\n                                                pulse_length, initial_asymmetry,\n                                                slr_rate) <= initial_asymmetry);\n  }\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(pulsed_exp_31mg, T, test_types) {\n  //\n  constexpr T pulse_length = 1.0;\n  constexpr T nuclear_lifetime =\n      triumf::bnmr::nuclei::magnesium_31<T>::lifetime();\n  constexpr T initial_asymmetry = 1.0;\n  constexpr T slr_rate = 1.0;\n  //\n  BOOST_TEST(triumf::bnmr::slr::magnesium_31::pulsed_exp<T>(\n                 -1.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                 slr_rate) == 0.0);\n  BOOST_TEST(triumf::bnmr::slr::magnesium_31::pulsed_exp<T>(\n                 0.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                 slr_rate) == initial_asymmetry);\n  //\n  for (auto &time : triumf::numpy::linspace<T>(0.0, 4.0, 100)) {\n    BOOST_TEST(triumf::bnmr::slr::magnesium_31::pulsed_exp<T>(\n                   time, nuclear_lifetime, pulse_length, initial_asymmetry,\n                   slr_rate) <= initial_asymmetry);\n  }\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(pulsed_sq_exp, T, test_types) {\n  //\n  constexpr T pulse_length = 4.0;\n  constexpr T nuclear_lifetime = triumf::bnmr::nuclei::lithium_8<T>::lifetime();\n  constexpr T initial_asymmetry = 1.0;\n  constexpr T slr_rate = 1.0;\n  //\n  BOOST_TEST(\n      triumf::bnmr::slr::pulsed_sq_exp<T>(-1.0, nuclear_lifetime, pulse_length,\n                                          initial_asymmetry, slr_rate) == 0.0);\n  BOOST_TEST(triumf::bnmr::slr::pulsed_sq_exp<T>(\n                 0.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                 slr_rate) == initial_asymmetry);\n  //\n  for (auto &time : triumf::numpy::linspace<T>(0.0, 16.0, 100)) {\n    BOOST_TEST(triumf::bnmr::slr::pulsed_sq_exp<T>(\n                   time, nuclear_lifetime, pulse_length, initial_asymmetry,\n                   slr_rate) <= initial_asymmetry);\n  }\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(pulsed_sqrt_exp, T, test_types) {\n  //\n  constexpr T pulse_length = 4.0;\n  constexpr T nuclear_lifetime = triumf::bnmr::nuclei::lithium_8<T>::lifetime();\n  constexpr T initial_asymmetry = 1.0;\n  constexpr T slr_rate = 1.0;\n  //\n  BOOST_TEST(triumf::bnmr::slr::pulsed_sqrt_exp<T>(\n                 -1.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                 slr_rate) == 0.0);\n  BOOST_TEST(triumf::bnmr::slr::pulsed_sqrt_exp<T>(\n                 0.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                 slr_rate) == initial_asymmetry);\n  //\n  for (auto &time : triumf::numpy::linspace<T>(0.0, 16.0, 100)) {\n    BOOST_TEST(triumf::bnmr::slr::pulsed_sqrt_exp<T>(\n                   time, nuclear_lifetime, pulse_length, initial_asymmetry,\n                   slr_rate) <= initial_asymmetry);\n  }\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(pulsed_cbrt_exp, T, test_types) {\n  //\n  constexpr T pulse_length = 4.0;\n  constexpr T nuclear_lifetime = triumf::bnmr::nuclei::lithium_8<T>::lifetime();\n  constexpr T initial_asymmetry = 1.0;\n  constexpr T slr_rate = 1.0;\n  //\n  BOOST_TEST(triumf::bnmr::slr::pulsed_cbrt_exp<T>(\n                 -1.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                 slr_rate) == 0.0);\n  BOOST_TEST(triumf::bnmr::slr::pulsed_cbrt_exp<T>(\n                 0.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                 slr_rate) == initial_asymmetry);\n  //\n  for (auto &time : triumf::numpy::linspace<T>(0.0, 16.0, 100)) {\n    BOOST_TEST(triumf::bnmr::slr::pulsed_cbrt_exp<T>(\n                   time, nuclear_lifetime, pulse_length, initial_asymmetry,\n                   slr_rate) <= initial_asymmetry);\n  }\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(pulsed_str_exp, T, test_types) {\n  //\n  constexpr T pulse_length = 4.0;\n  constexpr T nuclear_lifetime = triumf::bnmr::nuclei::lithium_8<T>::lifetime();\n  constexpr T initial_asymmetry = 1.0;\n  constexpr T slr_rate = 1.0;\n  //\n  for (const auto &beta : triumf::numpy::linspace<T>(0.1, 1.0, 10)) {\n    BOOST_TEST(triumf::bnmr::slr::pulsed_str_exp<T>(\n                   -1.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                   slr_rate, beta) == 0.0);\n    BOOST_TEST(triumf::bnmr::slr::pulsed_str_exp<T>(\n                   0.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                   slr_rate, beta) == initial_asymmetry);\n    //\n    for (const auto &time : triumf::numpy::linspace<T>(0.0, 16.0, 100)) {\n      BOOST_TEST(triumf::bnmr::slr::pulsed_str_exp<T>(\n                     time, nuclear_lifetime, pulse_length, initial_asymmetry,\n                     slr_rate, beta) <= initial_asymmetry);\n    }\n  }\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(pulsed_mod_str_exp, T, test_types) {\n  //\n  constexpr T pulse_length = 4.0;\n  constexpr T nuclear_lifetime = triumf::bnmr::nuclei::lithium_8<T>::lifetime();\n  constexpr T initial_asymmetry = 1.0;\n  constexpr T slr_rate = 1.0;\n  //\n  for (const auto &beta : triumf::numpy::linspace<T>(0.1, 1.0, 10)) {\n    for (const auto &slr_rate_initial :\n         triumf::numpy::logspace<T>(-2.0, 2.0, 10)) {\n      BOOST_TEST(triumf::bnmr::slr::pulsed_mod_str_exp<T>(\n                     -1.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                     slr_rate_initial, slr_rate, beta) == 0.0);\n      BOOST_TEST(triumf::bnmr::slr::pulsed_mod_str_exp<T>(\n                     0.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                     slr_rate_initial, slr_rate, beta) == initial_asymmetry);\n      //\n      for (const auto &time : triumf::numpy::linspace<T>(0.0, 16.0, 100)) {\n        BOOST_TEST(triumf::bnmr::slr::pulsed_mod_str_exp<T>(\n                       time, nuclear_lifetime, pulse_length, initial_asymmetry,\n                       slr_rate_initial, slr_rate, beta) <= initial_asymmetry);\n      }\n    }\n  }\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(pulsed_bi_exp, T, test_types) {\n  //\n  constexpr T pulse_length = 4.0;\n  constexpr T nuclear_lifetime = triumf::bnmr::nuclei::lithium_8<T>::lifetime();\n  constexpr T initial_asymmetry = 1.0;\n  constexpr T fraction_slow = 0.75;\n  constexpr T slr_rate_slow = 0.10;\n  constexpr T slr_rate_fast = 10.0;\n  //\n  BOOST_TEST(triumf::bnmr::slr::pulsed_bi_exp<T>(\n                 -1.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                 fraction_slow, slr_rate_slow, slr_rate_fast) == 0.0);\n  BOOST_TEST(triumf::bnmr::slr::pulsed_bi_exp<T>(\n                 0.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                 fraction_slow, slr_rate_slow,\n                 slr_rate_fast) == initial_asymmetry);\n  //\n  for (const auto &time : triumf::numpy::linspace<T>(0.0, 16.0, 100)) {\n    BOOST_TEST(triumf::bnmr::slr::pulsed_bi_exp<T>(\n                   time, nuclear_lifetime, pulse_length, initial_asymmetry,\n                   fraction_slow, slr_rate_slow,\n                   slr_rate_fast) <= initial_asymmetry);\n  }\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(pulsed_gauss_dist_exp, T, test_types) {\n  //\n  constexpr T pulse_length = 4.0;\n  constexpr T nuclear_lifetime = triumf::bnmr::nuclei::lithium_8<T>::lifetime();\n  constexpr T initial_asymmetry = 1.0;\n  constexpr T slr_rate = 1.0;\n  //\n  for (const auto &sigma : triumf::numpy::logspace<T>(-4.0, -1.0, 10)) {\n    BOOST_TEST(triumf::bnmr::slr::pulsed_gauss_dist_exp<T>(\n                   -1.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                   slr_rate, sigma) == 0.0);\n    BOOST_TEST(triumf::bnmr::slr::pulsed_gauss_dist_exp<T>(\n                   0.0, nuclear_lifetime, pulse_length, initial_asymmetry,\n                   slr_rate, sigma) == initial_asymmetry);\n    //\n    for (const auto &time : triumf::numpy::linspace<T>(0.0, 16.0, 100)) {\n      BOOST_TEST(triumf::bnmr::slr::pulsed_gauss_dist_exp<T>(\n                     time, nuclear_lifetime, pulse_length, initial_asymmetry,\n                     slr_rate, sigma) <= initial_asymmetry);\n    }\n  }\n}\n", "meta": {"hexsha": "6afd09b0b7ce2ac88990e38a1c52129b44496f61", "size": 9317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/bnmr_slr.cpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/bnmr_slr.cpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/bnmr_slr.cpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3333333333, "max_line_length": 80, "alphanum_fraction": 0.6278845122, "num_tokens": 2781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5767310033100574}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <queue>\n#include <set>\n#include <map>\n#include <cstdio>\n#include <cstdlib>\n#include <cctype>\n#include <cmath>\n#include <climits>\n#include <numeric>\n#include <Eigen/Dense>\n#undef NDEBUG\n#include <cassert>\n\n#include \"io_redirect.h\"\n\n#define FOR(i, a, b) for(std::size_t (i) = (a); (i) < (b); ++(i))\n#define REP(i, n) FOR(i, 0, n)\n#define TRACE(x) std::cout << #x <<\" = \" <<(x) <<std::endl;\n\n\nusing namespace std;\n\nusing UInt = uint64_t;\nusing Int = int64_t;\n\n\nstatic const std::vector<std::string> NUMBERS = { \"ZERO\", \"ONE\", \"TWO\", \"THREE\", \"FOUR\", \"FIVE\", \"SIX\", \"SEVEN\", \"EIGHT\", \"NINE\"};\n\nint main(int argc, char* argv[])\n{\n  //////////////////////// INPUT/OUTPUT //////////////////////////\n  if (!redirect_io(argc, argv))\n    return 0;\n  ////////////////////////////////////////////////////////////////\n\n\n  std::set<char> a;\n  for (const auto& n : NUMBERS)\n    for (const char c : n)\n      a.insert(c);\n\n  Eigen::MatrixXd m(a.size(), NUMBERS.size());\n  m.setZero();\n\n  REP(i, NUMBERS.size())\n  {\n    REP(j, NUMBERS[i].size())\n    {\n      const auto d = std::distance(a.cbegin(), a.find(NUMBERS[i][j]));\n      m(d, i) += 1;\n    }\n  }\n\n  size_t num_test_cases;\n  cin >> num_test_cases;\n\n  for (size_t i = 0; i < num_test_cases; ++i)\n  {\n    std::string vs;\n    cin >> vs;\n\n    Eigen::VectorXd b(a.size());\n    b.setZero();\n    REP(c, vs.size())\n    {\n      const auto d = std::distance(a.cbegin(), a.find(vs[c]));\n      b(d) += 1;\n    }\n    const Eigen::VectorXd x = m.fullPivHouseholderQr().solve(b);\n\n    string o{};\n    REP(c, NUMBERS.size())\n    {\n      const size_t count = static_cast<size_t>(std::round(x(c)));\n      REP(d, count)\n      {\n        o += std::to_string(c);\n      }\n    }\n    std::cout <<\"Case #\" <<(i+1) <<\": \" <<o <<endl;\n  }\n\n\n  ////////////////////////////////////////////////////////////////\n  cleanup_io();\n  return 0;\n}\n", "meta": {"hexsha": "cd0dd7cba13436cb432d4df37d2a2ae28a71c35e", "size": 1971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2016_Round_1B/A_Getting_The_Digits_2/template.cpp", "max_stars_repo_name": "risteon/code_jam", "max_stars_repo_head_hexsha": "db6941a6926042c8ae125a4996322f00e83f728f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2016_Round_1B/A_Getting_The_Digits_2/template.cpp", "max_issues_repo_name": "risteon/code_jam", "max_issues_repo_head_hexsha": "db6941a6926042c8ae125a4996322f00e83f728f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2016_Round_1B/A_Getting_The_Digits_2/template.cpp", "max_forks_repo_name": "risteon/code_jam", "max_forks_repo_head_hexsha": "db6941a6926042c8ae125a4996322f00e83f728f", "max_forks_repo_licenses": ["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.9680851064, "max_line_length": 130, "alphanum_fraction": 0.5129375951, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338729, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5767047029397104}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n\n#include <Utils/Math/AutomaticDifferentiation/VectorDerivatives3D.h>\n#include <gmock/gmock.h>\n#include <Eigen/Geometry>\n\nusing namespace testing;\nnamespace Scine {\nnamespace Utils {\nnamespace Tests {\n\n/**\n * @class AVectorDerivatives3DTest VectorDerivatives3DTest.cpp\n * @brief Comprises tests for the class Scine::Utils::VectorDerivatives3D.\n * @test\n */\nclass AVectorDerivatives3DTest : public Test {\n public:\n  double x = 0.231;\n  double y = -0.2922;\n  double z = 0.787;\n  Eigen::Vector3d v;\n\n protected:\n  void SetUp() override {\n    v = Eigen::Vector3d(x, y, z);\n  }\n};\n\nTEST_F(AVectorDerivatives3DTest, IsCorrectForDotProductWithItself) {\n  auto dv = VectorDerivatives3D::spatialVectorHessian3D(v);\n\n  AutomaticDifferentiation::Second3D dotProduct = dv.dot(dv);\n\n  ASSERT_THAT(dotProduct.value(), DoubleEq(x * x + y * y + z * z));\n  ASSERT_THAT(dotProduct.dx(), DoubleEq(2 * x));\n  ASSERT_THAT(dotProduct.dy(), DoubleEq(2 * y));\n  ASSERT_THAT(dotProduct.dz(), DoubleEq(2 * z));\n  ASSERT_THAT(dotProduct.XX(), DoubleEq(2));\n  ASSERT_THAT(dotProduct.YY(), DoubleEq(2));\n  ASSERT_THAT(dotProduct.ZZ(), DoubleEq(2));\n  ASSERT_THAT(dotProduct.XY(), DoubleEq(0));\n  ASSERT_THAT(dotProduct.XZ(), DoubleEq(0));\n  ASSERT_THAT(dotProduct.YZ(), DoubleEq(0));\n}\n\nTEST_F(AVectorDerivatives3DTest, IsCorrectForDotProductWithVector3d) {\n  auto dv = VectorDerivatives3D::spatialVectorHessian3D(v);\n  double x2 = -3.2, y2 = 0.21, z2 = 5.121;\n  Eigen::Vector3d v2(x2, y2, z2);\n\n  AutomaticDifferentiation::Second3D dotProduct = dv.dot(v2);\n\n  ASSERT_THAT(dotProduct.value(), DoubleEq(x * x2 + y * y2 + z * z2));\n  ASSERT_THAT(dotProduct.dx(), DoubleEq(x2));\n  ASSERT_THAT(dotProduct.dy(), DoubleEq(y2));\n  ASSERT_THAT(dotProduct.dz(), DoubleEq(z2));\n  ASSERT_THAT(dotProduct.XX(), DoubleEq(0));\n  ASSERT_THAT(dotProduct.YY(), DoubleEq(0));\n  ASSERT_THAT(dotProduct.ZZ(), DoubleEq(0));\n  ASSERT_THAT(dotProduct.XY(), DoubleEq(0));\n  ASSERT_THAT(dotProduct.XZ(), DoubleEq(0));\n  ASSERT_THAT(dotProduct.YZ(), DoubleEq(0));\n}\n\nTEST_F(AVectorDerivatives3DTest, IsCorrectForCrossProduct) {\n  double x2 = -3.2, y2 = 0.21, z2 = 5.121;\n  Eigen::Vector3d v2(x2, y2, z2);\n  double factor = 3.121;\n\n  auto dv = VectorDerivatives3D::spatialVectorHessian3D(v);\n  auto dv2 = VectorDerivatives3D::spatialVectorHessian3D(v2) * factor;\n\n  auto crossProduct = dv.cross(dv2);\n  Eigen::Vector3d expectedValue = v.cross(v2 * factor);\n\n  // Check values (compare with Eigen::cross):\n  ASSERT_THAT(crossProduct.x().value(), DoubleEq(expectedValue.x()));\n  ASSERT_THAT(crossProduct.y().value(), DoubleEq(expectedValue.y()));\n  ASSERT_THAT(crossProduct.z().value(), DoubleEq(expectedValue.z()));\n\n  // Check only x component derivatives\n  auto xDer = crossProduct.x();\n  ASSERT_THAT(xDer.dx(), DoubleEq(0));\n  ASSERT_THAT(xDer.dy(), DoubleEq(factor * z2 - factor * z));\n  ASSERT_THAT(xDer.dz(), DoubleEq(factor * y - factor * y2));\n  ASSERT_THAT(xDer.XX(), DoubleEq(0));\n  ASSERT_THAT(xDer.YY(), DoubleEq(0));\n  ASSERT_THAT(xDer.ZZ(), DoubleEq(0));\n  ASSERT_THAT(xDer.XY(), DoubleEq(0));\n  ASSERT_THAT(xDer.XZ(), DoubleEq(0));\n  ASSERT_THAT(xDer.YZ(), DoubleEq(0));\n}\n\nTEST_F(AVectorDerivatives3DTest, IsCorrectForNorm) {\n  AutomaticDifferentiation::Second3D X(5 * x, 5, 0, 0);\n  AutomaticDifferentiation::Second3D Y(2 * y, 0, 2, 0);\n  AutomaticDifferentiation::Second3D Z(-z, 0, 0, -1);\n\n  VectorDerivatives3D dv(X, Y, Z);\n\n  auto norm = dv.norm();\n  double root = std::sqrt(25 * x * x + 4 * y * y + z * z);\n\n  ASSERT_THAT(norm.value(), DoubleEq(root));\n  ASSERT_THAT(norm.dx(), DoubleEq(5 * (5 * x) / root));\n  ASSERT_THAT(norm.dy(), DoubleEq(2 * (2 * y) / root));\n  ASSERT_THAT(norm.dz(), DoubleEq((-1) * (-z) / root));\n}\n\n} /* namespace Tests */\n} /* namespace Utils */\n} /* namespace Scine */", "meta": {"hexsha": "d81f1309f13ba600529a7b5c7e688224fb3b52ad", "size": 3977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Tests/Math/VectorDerivatives3DTest.cpp", "max_stars_repo_name": "DockBio/utilities", "max_stars_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Tests/Math/VectorDerivatives3DTest.cpp", "max_issues_repo_name": "DockBio/utilities", "max_issues_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Tests/Math/VectorDerivatives3DTest.cpp", "max_forks_repo_name": "DockBio/utilities", "max_forks_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_forks_repo_licenses": ["BSD-3-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.7033898305, "max_line_length": 86, "alphanum_fraction": 0.6924817702, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5767046931614732}}
{"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": "#include <iostream>\n#include <math/TransformTool.hpp>\n#include <math/common.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef Eigen::Matrix<double, 7, 1> Vector7d;\n\nint main(int argc, const char** argv)\n{\n    if(argc != 8) return -1;\n\n    Vector7d tq;\n    for(int i=1; i<argc; ++i)\n        tq[i-1] = atof(argv[i]);\n\n    TransformTool tt;\n    cout << tt.tq2matrix(tq) << endl;\n    return 0;\n}", "meta": {"hexsha": "300d2899eccd8688f1bde653408f0351424c88dd", "size": 438, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/examples/tq2matrix.cpp", "max_stars_repo_name": "bin70/Toolkit", "max_stars_repo_head_hexsha": "ef47b0bd97334a2ceca415f01570886bfbb11e4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "toolkits/examples/tq2matrix.cpp", "max_issues_repo_name": "bin70/Toolkit", "max_issues_repo_head_hexsha": "ef47b0bd97334a2ceca415f01570886bfbb11e4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/examples/tq2matrix.cpp", "max_forks_repo_name": "bin70/Toolkit", "max_forks_repo_head_hexsha": "ef47b0bd97334a2ceca415f01570886bfbb11e4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-30T08:03:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-30T08:03:44.000Z", "avg_line_length": 19.9090909091, "max_line_length": 45, "alphanum_fraction": 0.6461187215, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5766334922045828}}
{"text": "#ifndef CRADLE_GEOMETRY_DECODE_MATRIX_HPP\n#define CRADLE_GEOMETRY_DECODE_MATRIX_HPP\n\n#include <boost/optional/optional.hpp>\n#include <cradle/geometry/angle.hpp>\n#include <cradle/geometry/common.hpp>\n\n// This file provides various functions for decoding transformation matrices.\n\nnamespace cradle {\n\n// Determine if the given transformation matrix has a rotational component.\ntemplate<unsigned N, typename T>\nbool\nhas_rotation(matrix<N, N, T> const& m);\n\n// Given a matrix that represents a 3D rotation about the X-axis (and only\n// that), this returns the angle of the rotation.  For any other matrix,\n// it returns an uninitialized value.\ntemplate<typename T>\noptional<angle<T, radians>>\ndecode_rotation_about_x(matrix<3, 3, T> const& m);\n\n// Decode a rotation about the Y-axis.\ntemplate<typename T>\noptional<angle<T, radians>>\ndecode_rotation_about_y(matrix<3, 3, T> const& m);\n\n// Decode a rotation about the Z-axis.\ntemplate<typename T>\noptional<angle<T, radians>>\ndecode_rotation_about_z(matrix<3, 3, T> const& m);\n\n} // namespace cradle\n\n#include <cradle/geometry/decode_matrix.ipp>\n\n#endif\n", "meta": {"hexsha": "89bb8b3b34ee8e973e61c5a11adb21eade83fdb3", "size": 1097, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cradle/geometry/decode_matrix.hpp", "max_stars_repo_name": "mghro/astroid-core", "max_stars_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cradle/geometry/decode_matrix.hpp", "max_issues_repo_name": "mghro/astroid-core", "max_issues_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-26T18:45:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T18:46:06.000Z", "max_forks_repo_path": "src/cradle/geometry/decode_matrix.hpp", "max_forks_repo_name": "mghro/astroid-core", "max_forks_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1282051282, "max_line_length": 77, "alphanum_fraction": 0.7721057429, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5766334745942794}}
{"text": "/**\n * @file test_irreducible_ntl.hpp\n *\n * @test program for f2p_is_irreducible.\n *\n * @author Mutsuo Saito\n * @author Makoto Matsumoto (Hiroshima University)\n *\n * Copyright (C) 2019 Mutsuo Saito, Makoto Matsumoto\n * and Hiroshima University.\n * All rights reserved.\n *\n * The MIT License is applied to this software, see\n * LICENSE.txt\n */\n\n#include <NTL/GF2X.h>\n#include <NTL/GF2XFactoring.h>\n#include \"test_ntl.hpp\"\n#include \"f2p_gmp.h\"\n#include <string>\n#include <stdio.h>\n#include <inttypes.h>\n\nusing namespace NTL;\nusing namespace std;\n\nint test_irreducible(const string& hexstr)\n{\n    GF2X poly;\n    hexto_poly(poly, hexstr);\n    bool irre_ntl = IterIrredTest(poly);\n    mpz_t gmppoly;\n    mpz_init(gmppoly);\n    f2p_set_hexstr(gmppoly, hexstr.c_str());\n    bool irre_f2p = f2p_is_irreducible(gmppoly);\n    int ok = 1;\n    if (irre_ntl == irre_f2p) {\n        ok = 1;\n    } else {\n        printf(\"irrentl = %d, irre_f2p = %d\\n\", irre_ntl, irre_f2p);\n        ok = 0;\n    }\n    mpz_clear(gmppoly);\n    return ok;\n}\n\nint test_irreducible(int n, const bool verbose)\n{\n    GF2X poly;\n    GF2X ranpoly;\n    int ok = 1;\n    string str;\n    char okstr[2] = {'x','o'};\n    BuildIrred(poly, n);\n    for (int i = 0; i < 100; i++) {\n        BuildRandomIrred(ranpoly, poly);\n        to_hexstring(str, ranpoly);\n        int r = test_irreducible(str);\n        if (verbose) {\n            printf(\"%c\", okstr[r & 1]);\n        }\n        ok &= r;\n    }\n    for (int i = 0; i < 100; i++) {\n        random(ranpoly, n);\n        to_hexstring(str, ranpoly);\n        int r = test_irreducible(str);\n        if (verbose) {\n            printf(\"%c\", okstr[r & 1]);\n        }\n        ok &= r;\n    }\n    if (verbose) {\n        printf(\"\\n\");\n    }\n    if (ok) {\n        printf(\"irreducible OK\\n\");\n        return 0;\n    } else {\n        printf(\"irreducible NG\\n\");\n        return 1;\n    }\n}\n\nint main(int argc, char * argv[])\n{\n    bool verbose = false;\n    int r = 0;\n    int n = 200;\n    if (argc > 1 && argv[1][0] == 'v') {\n        verbose = true;\n    }\n    r += test_irreducible(n, verbose);\n    if (r == 0) {\n        return 0;\n    } else {\n        return -1;\n    }\n}\n", "meta": {"hexsha": "8e9abd7438c13310cdcefe5ef850ee4e1ce52478", "size": 2147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_irreducible_ntl.cpp", "max_stars_repo_name": "MSaito/f2p-gmp", "max_stars_repo_head_hexsha": "64d4d7d3d1f7b246b59fee519c69c9c2db8ccbad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_irreducible_ntl.cpp", "max_issues_repo_name": "MSaito/f2p-gmp", "max_issues_repo_head_hexsha": "64d4d7d3d1f7b246b59fee519c69c9c2db8ccbad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_irreducible_ntl.cpp", "max_forks_repo_name": "MSaito/f2p-gmp", "max_forks_repo_head_hexsha": "64d4d7d3d1f7b246b59fee519c69c9c2db8ccbad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2574257426, "max_line_length": 68, "alphanum_fraction": 0.5533302282, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.7341195385342972, "lm_q1q2_score": 0.5765103656309686}}
{"text": "//==================================================================================================\n//  GlobalTypes.hpp\n//\n//  Created by Zachary Clawson on 7/19/2015\n//  Copyright (c) 2015 Zachary Clawson. All rights reserved.\n//==================================================================================================\n\n#ifndef __GlobalTypes_hpp\n#define __GlobalTypes_hpp\n\n#include <Eigen/Dense>\n\n// Double:\nusing real_t = double;\n//using real_t = float;\n\n// Double vector:\n//namespace Eigen{\n\nusing Vector2real_t   = Eigen::Matrix<real_t, 2, 1>;\nusing ArrayXreal_t    = Eigen::Array<real_t, Eigen::Dynamic, Eigen::Dynamic>;\nusing MatrixXreal_t   = Eigen::Matrix<real_t, Eigen::Dynamic, Eigen::Dynamic>;\n    \n//}\n\n#endif /* GLOBALTYPES_HPP */", "meta": {"hexsha": "f163c4617571cd9b02b1ff5d8a1d949f0a102d55", "size": 753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "config/GlobalTypes.hpp", "max_stars_repo_name": "skimnc/BiLinearInterpolation", "max_stars_repo_head_hexsha": "78c00980d3e7f3894ba27030e8019b8a9d04468d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-27T22:03:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-27T22:03:35.000Z", "max_issues_repo_path": "config/GlobalTypes.hpp", "max_issues_repo_name": "skimnc/BiLinearInterpolation", "max_issues_repo_head_hexsha": "78c00980d3e7f3894ba27030e8019b8a9d04468d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "config/GlobalTypes.hpp", "max_forks_repo_name": "skimnc/BiLinearInterpolation", "max_forks_repo_head_hexsha": "78c00980d3e7f3894ba27030e8019b8a9d04468d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-22T08:57:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T08:57:15.000Z", "avg_line_length": 28.9615384615, "max_line_length": 100, "alphanum_fraction": 0.5205843293, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5765103656309686}}
{"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": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\n\ntemplate <typename Derived1, typename Derived2>\nvoid copyUpperTriangularPart(MatrixBase<Derived1>& dst, const MatrixBase<Derived2>& src)\n{\n  /* Note the 'template' keywords in the following line! */\n  dst.template triangularView<Upper>() = src.template triangularView<Upper>();\n}\n\nint main()\n{\n  MatrixXi m1 = MatrixXi::Ones(5,5);\n  MatrixXi m2 = MatrixXi::Random(4,4);\n  std::cout << \"m2 before copy:\" << std::endl;\n  std::cout << m2 << std::endl << std::endl;\n  copyUpperTriangularPart(m2, m1.topLeftCorner(4,4));\n  std::cout << \"m2 after copy:\" << std::endl;\n  std::cout << m2 << std::endl << std::endl;\n}\n", "meta": {"hexsha": "9d85292dd5d267fa3fd621c67aec308d796d9b8c", "size": 677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/TemplateKeyword_flexible.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/TemplateKeyword_flexible.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/TemplateKeyword_flexible.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 29.4347826087, "max_line_length": 88, "alphanum_fraction": 0.682422452, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.6992544085240402, "lm_q1q2_score": 0.5765086487429258}}
{"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 \u90e8\u5206\n#include <Eigen/Core>\n// \u7a20\u5bc6\u77e9\u9635\u7684\u4ee3\u6570\u8fd0\u7b97\uff08\u9006\uff0c\u7279\u5f81\u503c\u7b49\uff09\n#include <Eigen/Dense>\n#include\"hw.h\"\n#define MATRIX_SIZE 50\n\nvoid homework()\n{\n\n\n//\u4f5c\u4e1a\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\u6765\u89e3\u65b9\u7a0b\n\n\n    /*******************\u65f6\u95f4\u6bd4\u8f83*********************/\n\n    clock_t time_stt = clock();\n    x = matrix_A.colPivHouseholderQr().solve(matrix_b);  //\u5229\u7528QR\u5206\u89e3\u6c42\u89e3\u65b9\u7a0b\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;;  //\u5229\u7528\u6c42\u9006\u6765\u89e3\u65b9\u7a0b\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\u6765\u89e3\u65b9\u7a0b\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": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/saturated.hpp>\n#include <boost/simd/meta/cardinal_of.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/function/fast.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/zero.hpp>\n\nnamespace bs = boost::simd;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], a2[N], b[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(1+i) : T(3+i);\n    a2[i] = (i%2) ? T(i+N) : T(2*i+1);\n    b[i] = bs::divides(a1[i], a2[i]);\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t aa2(&a2[0], &a2[0]+N);\n  p_t bb(&b[0], &b[0]+N);\n\n  STF_ULP_EQUAL(bs::divides(aa1, aa2), bb, 0.5);\n  STF_ULP_EQUAL(aa1/aa2, bb, 0.5);\n}\n\nSTF_CASE_TPL(\"Check divides on pack\" , STF_NUMERIC_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\nSTF_CASE_TPL( \"Check divides behavior with floating\", STF_IEEE_TYPES )\n{\n  namespace bs = boost::simd;\n  using bs::divides;\n  using p_t = bs::pack<T>;\n  using r_t = decltype(divides(p_t(), p_t()));\n\n  STF_TYPE_IS(r_t, p_t);\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_IEEE_EQUAL(divides(bs::Inf<p_t>(),  bs::Inf<p_t>()), bs::Nan<r_t>());\n  STF_IEEE_EQUAL(divides(bs::Minf<p_t>(), bs::Minf<p_t>()), bs::Nan<r_t>());\n  STF_IEEE_EQUAL(divides(bs::Nan<p_t>(),  bs::Nan<p_t>()), bs::Nan<r_t>());\n#endif\n  STF_EQUAL(divides(p_t(1), p_t(0)), bs::Inf<r_t>());\n  STF_IEEE_EQUAL(divides(p_t(0), p_t(0)), bs::Nan<r_t>());\n  STF_EQUAL(divides(p_t(1), p_t(1)), bs::One<r_t>());\n}\n\n", "meta": {"hexsha": "a6951f0fd03a0f42f21f4dc5bf2fb13a73f9a3b4", "size": 2094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/divides.regular.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "test/function/simd/divides.regular.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/simd/divides.regular.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 29.4929577465, "max_line_length": 100, "alphanum_fraction": 0.5754536772, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.5764167830070966}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//! \\file\r\n//!\\brief Tests for the transcendental exponential function of (fixed_point) for a tiny digit range.\r\n\r\n#include <cmath>\r\n\r\n#define BOOST_TEST_MODULE test_negatable_func_exp_tiny\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_func_exp_tiny)\r\n{\r\n  typedef boost::fixed_point::negatable<4, -11> fixed_point_type;\r\n  typedef fixed_point_type::float_type          float_point_type;\r\n\r\n  const fixed_point_type tol = ldexp(fixed_point_type(1), fixed_point_type::resolution + 2);\r\n\r\n  // Check positive arguments.\r\n  for(int i = 12; i >= 2; --i)\r\n  {\r\n    const fixed_point_type x = exp(fixed_point_type(3.1415926535897932385L) / fixed_point_type(i));\r\n\r\n    using std::exp;\r\n    const float_point_type y = exp(float_point_type(3.1415926535897932385L) / float_point_type(i));\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n  }\r\n\r\n  // Check negative arguments.\r\n  for(int i = 12; i >= 2; --i)\r\n  {\r\n    const fixed_point_type x = exp(fixed_point_type(-3.1415926535897932385L) / fixed_point_type(i));\r\n\r\n    using std::exp;\r\n    const float_point_type y = exp(float_point_type(-3.1415926535897932385L) / float_point_type(i));\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n  }\r\n\r\n  const fixed_point_type local_e = boost::fixed_point::negatable_constants<fixed_point_type>::e();\r\n\r\n  BOOST_CHECK_EQUAL(exp(fixed_point_type(1)), local_e);\r\n}\r\n", "meta": {"hexsha": "aa606e245a2edc01c56ce028cdd528e780f8bfb9", "size": 1856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_func_exp_tiny.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_func_exp_tiny.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_func_exp_tiny.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.0188679245, "max_line_length": 101, "alphanum_fraction": 0.6961206897, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.5764167830070966}}
{"text": "#ifdef STAN_OPENCL\n\n#include <stan/math/opencl/kernel_generator.hpp>\n#include <stan/math/opencl/matrix_cl.hpp>\n#include <stan/math/opencl/copy.hpp>\n#include <test/unit/util.hpp>\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\nTEST(KernelGenerator, constant_test) {\n  stan::math::matrix_cl<double> m1_cl(stan::math::constant(1.2, 3, 4));\n\n  Eigen::MatrixXd res = stan::math::from_matrix_cl(m1_cl);\n  EXPECT_MATRIX_EQ(res, Eigen::MatrixXd::Constant(3, 4, 1.2));\n}\n\n#endif\n", "meta": {"hexsha": "a14dbabff5bf69ebd39573daa8fba442e60cef4f", "size": 471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/opencl/kernel_generator/constant_test.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "test/unit/math/opencl/kernel_generator/constant_test.cpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/opencl/kernel_generator/constant_test.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 26.1666666667, "max_line_length": 71, "alphanum_fraction": 0.7346072187, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143953, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5763685913062332}}
{"text": "#include <catch2/catch.hpp>\n\n#include <Eigen/Core>\n\n#include <ipc/broad_phase/hash_grid.hpp>\n\nusing namespace ipc;\n\n// TEST_CASE(\"AABB initilization\", \"[hash_grid][AABB]\")\n// {\n//     int dim = GENERATE(2, 3);\n//     CAPTURE(dim);\n//     AABB aabb;\n//     ArrayMax3d actual_center(dim);\n//     SECTION(\"Empty AABB\")\n//     {\n//         aabb = AABB(ArrayMax3d::Zero(dim), ArrayMax3d::Zero(dim));\n//         actual_center.setZero();\n//     }\n//     SECTION(\"Box centered at zero\")\n//     {\n//         ArrayMax3d min =\n//             ArrayMax3d::Random(dim).array() - 1; // in range [-2, 0]\n//         ArrayMax3d max = -min;\n//         aabb = AABB(min, max);\n//         actual_center.setZero();\n//     }\n//     SECTION(\"Box not centered at zero\")\n//     {\n//         ArrayMax3d min(dim), max(dim);\n//         if (dim == 2) {\n//             min << 5.1, 3.14;\n//             max << 10.4, 7.89;\n//             actual_center << 7.75, 5.515;\n//         } else {\n//             min << 5.1, 3.14, 7.94;\n//             max << 10.4, 7.89, 10.89;\n//             actual_center << 7.75, 5.515, 9.415;\n//         }\n//         aabb = AABB(min, max);\n//     }\n//     ArrayMax3d center_diff = aabb.getCenter() - actual_center;\n//     CHECK(center_diff.matrix().norm() == Approx(0.0).margin(1e-12));\n// }\n\nTEST_CASE(\"AABB overlapping\", \"[has_grid][AABB]\")\n{\n    AABB a, b;\n    bool are_overlapping = false;\n    SECTION(\"a to the right of b\")\n    {\n        a = AABB(Eigen::Array2d(-1, 0), Eigen::Array2d(0, 1));\n        SECTION(\"overlapping\")\n        {\n            b = AABB(Eigen::Array2d(-0.5, 0), Eigen::Array2d(0.5, 1));\n            are_overlapping = true;\n        }\n        SECTION(\"not overlapping\")\n        {\n            b = AABB(Eigen::Array2d(0.5, 0), Eigen::Array2d(1.5, 1));\n            are_overlapping = false;\n        }\n    }\n    SECTION(\"b to the right of a\")\n    {\n        b = AABB(Eigen::Array2d(-1, 0), Eigen::Array2d(0, 1));\n        SECTION(\"overlapping\")\n        {\n            a = AABB(Eigen::Array2d(-0.5, 0), Eigen::Array2d(0.5, 1));\n            are_overlapping = true;\n        }\n        SECTION(\"not overlapping\")\n        {\n            a = AABB(Eigen::Array2d(0.5, 0), Eigen::Array2d(1.5, 1));\n            are_overlapping = false;\n        }\n    }\n    SECTION(\"a above b\")\n    {\n        a = AABB(Eigen::Array2d(0, -1), Eigen::Array2d(1, 0));\n        SECTION(\"overlapping\")\n        {\n            b = AABB(Eigen::Array2d(0, -0.5), Eigen::Array2d(1, 0.5));\n            are_overlapping = true;\n        }\n        SECTION(\"not overlapping\")\n        {\n            b = AABB(Eigen::Array2d(0, 0.5), Eigen::Array2d(1, 1.5));\n            are_overlapping = false;\n        }\n    }\n    SECTION(\"a above b\")\n    {\n        b = AABB(Eigen::Array2d(0, -1), Eigen::Array2d(1, 0));\n        SECTION(\"overlapping\")\n        {\n            a = AABB(Eigen::Array2d(0, -0.5), Eigen::Array2d(1, 0.5));\n            are_overlapping = true;\n        }\n        SECTION(\"not overlapping\")\n        {\n            a = AABB(Eigen::Array2d(0, 0.5), Eigen::Array2d(1, 1.5));\n            are_overlapping = false;\n        }\n    }\n    CHECK(AABB::are_overlapping(a, b) == are_overlapping);\n}\n", "meta": {"hexsha": "e2190d790adfd25fcd2befebf37c4c3c40ef1af3", "size": 3148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/broad_phase/test_hash_grid.cpp", "max_stars_repo_name": "ipc-sim/ipc-toolk", "max_stars_repo_head_hexsha": "81873d0288810e30166d871419da4104329860e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T21:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:24:31.000Z", "max_issues_repo_path": "tests/broad_phase/test_hash_grid.cpp", "max_issues_repo_name": "dbelgrod/ipc-toolkit", "max_issues_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-12T05:54:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T18:39:30.000Z", "max_forks_repo_path": "tests/broad_phase/test_hash_grid.cpp", "max_forks_repo_name": "dbelgrod/ipc-toolkit", "max_forks_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T12:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T04:55:49.000Z", "avg_line_length": 29.1481481481, "max_line_length": 71, "alphanum_fraction": 0.4876111817, "num_tokens": 988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5763653392526952}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include \"TransformMatrix.hpp\"\n\nusing namespace Geometry2d;\n\nTEST(TransformMatrix, Convert) {\n    // Test conversion to/from Eigen\n    TransformMatrix transform(Point(0, 1), 1.0);\n    Eigen::Matrix<double, 3, 3> transformEigen = transform;\n    EXPECT_EQ(transformEigen * Eigen::Vector3d(0, 0, 1),\n              Eigen::Vector3d(0, 1, 1));\n    TransformMatrix transformedBack = transformEigen;\n    EXPECT_EQ(transform * Point(0, 1), transformedBack * Point(0, 1));\n    EXPECT_EQ(transform * Point(1, 0), transformedBack * Point(1, 0));\n}\n\nTEST(TransformMatrix, Compose) {\n    // Test composition: self-compose a 90-degree rotation with an offset from\n    // the origin\n    TransformMatrix transform1(Point(0, 1), M_PI / 2);\n    TransformMatrix transform2(Point(1, 0), M_PI / 2);\n\n    EXPECT_LT(((transform1 * transform2) * Point(1, 0) -\n               transform1 * (transform2 * Point(1, 0)))\n                  .mag(),\n              1e-6)\n        << \"Composition should be associative!\";\n\n    EXPECT_LT(((transform2 * transform1) * Point(1, 0) -\n               transform2 * (transform1 * Point(1, 0)))\n                  .mag(),\n              1e-6)\n        << \"Composition should be associative!\";\n}\n\nTEST(TransformMatrix, Reconstruct) {\n    Eigen::Matrix<double, 3, 3> transformEigen;\n    transformEigen << 0, 1, 0, -1, 0, 1, 0, 0, 1;\n    TransformMatrix transform = transformEigen;\n    EXPECT_EQ(transform.origin(), Point(0, 1));\n    EXPECT_NEAR(transform.rotation(), -M_PI / 2 + 2 * M_PI, 1e-6);\n}\n", "meta": {"hexsha": "cd7f03121cebae29e7f0b9f91965b61cf626096f", "size": 1547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common/Geometry2d/TransformMatrixTest.cpp", "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/TransformMatrixTest.cpp", "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/TransformMatrixTest.cpp", "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": 34.3777777778, "max_line_length": 78, "alphanum_fraction": 0.6237879767, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.5763384851428475}}
{"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 \"WilhelmsenProjection.h\"\n#include <iterator>\n#include <cassert>\n\n#ifdef USE_EIGEN\n#include <Eigen/LU>\nUSING_PART_OF_NAMESPACE_EIGEN\n#else\n#include <cml/cml.h>\nusing namespace cml;\n#endif\n\ntemplate <class T> std::vector<int> WilhelmsenProjection<T>::constraints;\ntemplate <class T> const T WilhelmsenProjection<T>::eps   = 1e-7;\ntemplate <class T> const T WilhelmsenProjection<T>::eps2  = 1e-14;\n\n// --------------------------------------------------------------------------\ntemplate <class T>\n#ifdef USE_EIGEN\n        Eigen::Matrix<T, Eigen::Dynamic, 1>\n#else\n        cml::vector< T, cml::dynamic<> >\n#endif\n        WilhelmsenProjection<T>::projectSubspace(const std::vector<vector6> &S,\n                                              const vector6 &q)\n{\n    // set up an nxn linear system, Ax = b, to solve for the projection\n    //  if S = { e_1, e_2, ..., e_n }\n    //  then the system is \\sum_{i=1}^n x_i <e_i e_j> = <q e_j> for j = 1..n\n\n    int n = S.size();\n    vectorn result(n);\n\n    // residuals to check which solution is better\n//    T cmlR, eigenR;\n\n#ifdef USE_EIGEN\n    // use Eigen's LU factorization to solve the normal equations\n    matrixn A(n, n);\n    for (int i = 0; i < n; ++i)\n        for (int j = i; j < n; ++j)\n            A(i, j) = A(j, i) = S[i].dot(S[j]);\n\n    vectorn b(n);\n    for (int j = 0; j < n; ++j)\n        b[j] = q.dot(S[j]);\n\n    vectorn x;\n    A.lu().solve(b, &x);\n    result = x;\n\n//    T det = A.determinant();\n//    if (fabs(det) < eps2)\n//        std::cout << \"Warning: det(A) = \" << det << std::endl;\n\n    // compute the residual from the solution\n//    eigenR = (A*x - b).norm();\n\n#else\n    // set up the matrix A\n    matrixn A(n, n);\n    for (int i = 0; i < n; ++i)\n        for (int j = i; j < n; ++j)\n            A(i, j) = A(j, i) = dot(S[i], S[j]);\n\n    // set up the vector b\n    vectorn b(n);\n    for (int j = 0; j < n; ++j)\n        b[j] = dot(q, S[j]);\n\n    // compute x by inverting the matrix A\n    vectorn x = inverse(A) * b;\n    result = x;\n\n    // compute the residual from the solution\n//    cmlR = length(A*x - b);\n#endif\n\n\n    // output a status to see which one performs better\n//    static int counter = 0;\n//    if (++counter > 500)\n//    {\n//        std::cout << \"CML residual: \" << cmlR << '\\t'\n//                << \"Eigen residual:\" << eigenR << std::endl;\n//        counter = 0;\n//    }\n\n    return result;\n}\n\n// --------------------------------------------------------------------------\ntemplate <class T>\n#ifdef USE_EIGEN\n        Eigen::Matrix<T, 6, 1>\n#else\n        cml::vector< T, cml::fixed<6> >\n#endif\n        WilhelmsenProjection<T>::projectCone(const std::vector<vector6> &K,\n                                             const vector6 &q)\n{\n    // Step 0: find an initial vector in the direction of q\n    int n = K.size(), ki = 0;\n    vector6 p = zero6();\n\n    std::vector<vector6>    F;\n    std::vector<int>        index;\n    std::vector<T>          lambda;\n    std::vector<bool>       used(n, false);\n\n    for (; ki < n && dot(q, K[ki]) < eps2; ++ki);\n    if (ki < n) {\n        F.push_back(K[ki]);\n        index.push_back(ki);\n        lambda.push_back(dot(q, F[0]) / norm2(F[0]));\n        p = lambda[0] * F[0];\n        used[ki] = true;\n    }\n    else return p;\n\n    // main algorithm iteration loop\n    for (;;)\n    {\n        // Step 1: look for the next generator that lies between the current\n        //         subcone and the target point\n        vector6 eta = q - p;\n        if (norm2(eta) < eps2) break;\n\n        // this search is linear... can we do better?\n        for (ki = 0; ki < n; ++ki) {\n            if (used[ki]) continue;\n            if (dot(eta, K[ki]) > eps) break;\n        }\n        if (ki < n) {\n            F.push_back(K[ki]);\n            index.push_back(ki);\n            lambda.push_back(0.0);\n            used[ki] = true;\n        }\n        else break;\n\n        // auxiliary loop to reduce the subcone to the smallest face\n        bool repeat;\n        do\n        {\n            // Step 2: project the target onto the span of F and see if the point\n            //         lies within the subcone generated by F\n            vectorn beta = projectSubspace(F, q);\n            int m = F.size();\n            T lo = smallest(beta);\n\n            // if the projected point is outside the subcone, we need to find\n            // the nearest point in the subspace within the subcone generated by F\n            if (lo < -eps)\n            {\n                T rho = 1.0;\n                for (int i = 0; i < m; ++i)\n                    if (lambda[i] - beta[i] >= eps)\n                        rho = std::min(rho, lambda[i] / (lambda[i] - beta[i]));\n\n                // compute new barycentric coordinates gamma\n                for (int i = 0; i < m; ++i)\n                    beta[i] = (1.0 - rho) * lambda[i] + rho * beta[i];\n                lo = smallest(beta);\n                repeat = true;\n            }\n            // otherwise the projected point is already within the subcone,\n            // so just remove redundant generators from F\n            else repeat = false;\n\n            // remove generators not on the separating hyperplane (zero barycentric)\n            if (lo < eps) {\n                std::vector<vector6> E; E.swap(F);\n                std::vector<int> edex; edex.swap(index);\n                lambda.clear();\n                for (int i = 0; i < m; ++i) {\n                    if (beta[i] >= eps) {\n                        F.push_back(E[i]);\n                        index.push_back(edex[i]);\n                        lambda.push_back(beta[i]);\n                    }\n                }\n            }\n            else {\n                for (int i = 0; i < m; ++i)\n                    lambda[i] = beta[i];\n            }\n\n            // compute the new projected point p based on F and lambda\n            m = F.size();\n            p = zero6();\n            for (int i = 0; i < m; ++i)\n                p += lambda[i] * F[i];\n\n        } while (repeat);\n    }\n\n    constraints = index;\n\n    return p;\n}\n\n// --------------------------------------------------------------------------\ntemplate <class T>\n        void WilhelmsenProjection<T>::conditionGenerators(std::vector<vector6> &K)\n{\n    std::vector<vector6> C;\n    for (typename std::vector<vector6>::iterator kt = K.begin(); kt != K.end(); ++kt)\n    {\n        // check vector length\n        T len = norm(*kt);\n        if (len < eps) continue;\n        vector6 v = *kt / len;\n\n        // check for parallel vectors\n        bool indep = true;\n        for (typename std::vector<vector6>::iterator ct = C.begin(); ct != C.end(); ++ct)\n            if (1.0 - dot(v, *ct) < eps) { indep = false; break; }\n        if (indep) C.push_back(v);\n    }\n\n    // swap K with the set of conditioned generators\n    K.swap(C);\n}\n\n// --------------------------------------------------------------------------\n// debug function to print out the last set of active constraints\n\ntemplate <class T>\n        void WilhelmsenProjection<T>::printConstraints()\n{\n    std::cout << \"Wilhelmson constraints: \";\n    std::copy(constraints.begin(), constraints.end(),\n              std::ostream_iterator<int>(std::cout, \"  \"));\n    std::cout << std::endl;\n}\n\n// --------------------------------------------------------------------------\n// template instantiations for double and long double data types\n\ntemplate class WilhelmsenProjection<double>;\ntemplate class WilhelmsenProjection<long double>;\n\n// --------------------------------------------------------------------------\n", "meta": {"hexsha": "d00ef7ff27fe6f1a03952a3d3c18d360c46c4d8f", "size": 7491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "teleop_and_haptics/haptic_display_tools/src/Haptics/WilhelmsenProjection.cpp", "max_stars_repo_name": "atp42/jks-ros-pkg", "max_stars_repo_head_hexsha": "367fc00f2a9699f33d05c7957d319a80337f1ed4", "max_stars_repo_licenses": ["FTL"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-02-02T13:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-17T11:52:13.000Z", "max_issues_repo_path": "teleop_and_haptics/haptic_display_tools/src/Haptics/WilhelmsenProjection.cpp", "max_issues_repo_name": "salisbury-robotics/jks-ros-pkg", "max_issues_repo_head_hexsha": "367fc00f2a9699f33d05c7957d319a80337f1ed4", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "teleop_and_haptics/haptic_display_tools/src/Haptics/WilhelmsenProjection.cpp", "max_forks_repo_name": "salisbury-robotics/jks-ros-pkg", "max_forks_repo_head_hexsha": "367fc00f2a9699f33d05c7957d319a80337f1ed4", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5755102041, "max_line_length": 89, "alphanum_fraction": 0.4747029769, "num_tokens": 1935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5763384651510362}}
{"text": "#include <iostream>\n\n#include \"AnimatedTetrahedronMesh.h\"\n\n#include <Eigen/Dense>\n\n#include <map>\n\ntemplate<class T>\nstruct LatticeMesh : public AnimatedTetrahedonMesh<T>\n{\n    using Base = AnimatedTetrahedonMesh<T>;\n\n    // from AnimatedTetrahedonMesh\n    using Base::m_meshElements;\n    using Base::m_particleX;\n    using Base::initializeUSD;\n    using Base::initializeTopology;\n    using Base::initializeParticles;\n    using Vector3 = typename Base::Vector3;\n\n    std::array<int, 3> m_cellSize; // dimensions in grid cells\n    int m_radius; // radius of sphere in grid cells\n    T m_gridDX;\n\n    std::vector<std::array<int, 3>> m_activeCells; // Marks the \"active\" cells in the lattice\n    std::map<std::array<int, 3>, int> m_activeNodes; // Maps the \"active\" nodes to their particle index\n\n    void initialize()\n    {\n        initializeUSD(\"Demo3D.usda\");\n\n        // Activate cells within a sphere of radius m_radius (in cells)\n\n        for(int cell_i = 0; cell_i < m_cellSize[0]; cell_i++)\n        for(int cell_j = 0; cell_j < m_cellSize[1]; cell_j++)\n        for(int cell_k = 0; cell_k < m_cellSize[1]; cell_k++){\n\n            int r = (cell_i - m_cellSize[0]/2) * (cell_i - m_cellSize[0]/2) +\n                    (cell_j - m_cellSize[1]/2) * (cell_j - m_cellSize[1]/2) +\n                    (cell_k - m_cellSize[2]/2) * (cell_k - m_cellSize[2]/2);\n\n            if(r <= m_radius * m_radius)\n                m_activeCells.push_back(std::array<int, 3>{cell_i, cell_j, cell_k});\n\n        }\n\n        std::cout << \"Created a model including \" << m_activeCells.size() << \" lattice cells\" <<std::endl;\n\n        // Create (uniquely numbered) particles at the node corners of active cells\n\n        for(const auto& cell: m_activeCells){\n            std::array<int, 3> node;\n            for(node[0] = cell[0]; node[0] <= cell[0]+1; node[0]++)\n            for(node[1] = cell[1]; node[1] <= cell[1]+1; node[1]++)\n            for(node[2] = cell[2]; node[2] <= cell[2]+1; node[2]++){\n                auto search = m_activeNodes.find(node);\n                if(search == m_activeNodes.end()){ // Particle not yet created at this lattice node location -> make one\n                    m_activeNodes.insert({node, m_particleX.size()});\n                    m_particleX.emplace_back(m_gridDX * T(node[0]), m_gridDX * T(node[1]), m_gridDX * T(node[2]));\n                }\n            }\n        }\n        std::cout << \"Model contains \" << m_particleX.size() << \" particles\" << std::endl;\n\n        // Make tetrahedra out of all active cells (6 tetrahedra per cell)\n\n        for(const auto& cell: m_activeCells){\n            int vertexIndices[2][2][2];\n            for(int i = 0; i <= 1; i++)\n            for(int j = 0; j <= 1; j++)\n            for(int k = 0; k <= 1; k++){\n                std::array<int, 3> node{cell[0] + i, cell[1] + j, cell[2] + k};\n                auto search = m_activeNodes.find(node);\n                if(search != m_activeNodes.end())\n                    vertexIndices[i][j][k] = search->second;\n                else\n                    throw std::logic_error(\"particle at cell vertex not found\");\n            }\n\n            m_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][0][0], vertexIndices[1][1][0], vertexIndices[1][1][1]});\n            m_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][0][0], vertexIndices[1][1][1], vertexIndices[1][0][1]});\n            m_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][0][1], vertexIndices[1][1][1], vertexIndices[0][0][1]});\n            m_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][1][1], vertexIndices[0][1][1], vertexIndices[0][0][1]});\n            m_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][1][1], vertexIndices[0][1][0], vertexIndices[0][1][1]});\n            m_meshElements.push_back(std::array<int, 4>{ vertexIndices[0][0][0], vertexIndices[1][1][0], vertexIndices[0][1][0], vertexIndices[1][1][1]});\n        }\n        \n        // Perform the USD-specific initialization of topology & particles\n        // (this will also create a boundary *surface* to visualuze\n\n        initializeTopology();\n        initializeParticles();\n\n        // Check particle indexing in mesh\n\n        for(const auto& element: m_meshElements)\n            for(const auto vertex: element)\n                if(vertex < 0 || vertex >= m_particleX.size())\n                    throw std::logic_error(\"mismatch between mesh vertex and particle array\");\n    }\n};\n\nint main(int argc, char *argv[])\n{\n    LatticeMesh<float> simulationMesh;\n    simulationMesh.m_cellSize = { 20, 20, 20 };\n    simulationMesh.m_radius = 8;\n    simulationMesh.m_gridDX = 0.1;\n\n    // Initialize the simulation example\n    simulationMesh.initialize();\n\n    // Output the initial shape of the mesh\n    simulationMesh.writeFrame(0);\n\n    // Write the entire timeline to USD\n    simulationMesh.writeUSD();\n\n    return 0;\n}\n\n", "meta": {"hexsha": "e739a8d9184fc9847ce30a729a3ca682dc98cf2a", "size": 5012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Finite-Element-Tests/tests/Demo3D/main.cpp", "max_stars_repo_name": "uwgraphics/PhysicsBasedModeling-Demos", "max_stars_repo_head_hexsha": "82dc905fe9e7eda7fda5f4e3cd98153edeb42d5e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-09-20T21:24:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T20:51:08.000Z", "max_issues_repo_path": "Finite-Element-Tests/tests/Demo3D/main.cpp", "max_issues_repo_name": "uwgraphics/PhysicsBasedModeling-Demos", "max_issues_repo_head_hexsha": "82dc905fe9e7eda7fda5f4e3cd98153edeb42d5e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Finite-Element-Tests/tests/Demo3D/main.cpp", "max_forks_repo_name": "uwgraphics/PhysicsBasedModeling-Demos", "max_forks_repo_head_hexsha": "82dc905fe9e7eda7fda5f4e3cd98153edeb42d5e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-09-07T16:17:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T05:34:07.000Z", "avg_line_length": 40.7479674797, "max_line_length": 154, "alphanum_fraction": 0.5909816441, "num_tokens": 1360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5762682534181928}}
{"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": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/monoid.hpp>\n#include <boost/hana/range.hpp>\n#include <boost/hana/tuple.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [make<Range>]\nconstexpr auto irange = make<Range>(int_<0>, int_<10>); // [0, 10) int\nconstexpr auto lrange = make<Range>(int_<0>, long_<10>); // [0, 10) long\nBOOST_HANA_CONSTANT_CHECK(lrange == make<Range>(long_<0>, long_<10>));\n//! [make<Range>]\n(void)irange;\n\n}{\n\n//! [comparable]\n// empty ranges are equal\nBOOST_HANA_CONSTANT_CHECK(range(int_<6>, int_<6>) == range(int_<0>, int_<0>));\n\n// otherwise, ranges are equal if and only if they span the same interval\nBOOST_HANA_CONSTANT_CHECK(range(int_<2>, int_<5>) == range(int_<2>, int_<5>));\nBOOST_HANA_CONSTANT_CHECK(range(int_<0>, int_<3>) != range(int_<-1>, int_<3>));\n//! [comparable]\n\n}{\n\n//! [foldable]\nBOOST_HANA_CONSTANT_CHECK(\n    foldl(range(int_<0>, int_<4>), int_<0>, plus) == int_<6>\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    unpack(range(int_<-2>, int_<2>), make<Tuple>) ==\n    make<Tuple>(int_<-2>, int_<-1>, int_<0>, int_<1>)\n);\n//! [foldable]\n\n}{\n\n//! [iterable]\nconstexpr auto r = range(int_<0>, int_<1000>);\nBOOST_HANA_CONSTANT_CHECK(head(r) == int_<0>);\nBOOST_HANA_CONSTANT_CHECK(last(r) == int_<999>);\nBOOST_HANA_CONSTANT_CHECK(tail(r) == range(int_<1>, int_<1000>));\nBOOST_HANA_CONSTANT_CHECK(!is_empty(r));\nBOOST_HANA_CONSTANT_CHECK(is_empty(range(int_<3>, int_<3>)));\n//! [iterable]\n\n}{\n\n//! [searchable]\nBOOST_HANA_CONSTANT_CHECK(find(range(int_<1>, int_<25>), int_<10>) == just(int_<10>));\nBOOST_HANA_CONSTANT_CHECK(find(range(int_<1>, int_<25>), int_<200>) == nothing);\n//! [searchable]\n\n}{\n\n//! [range_c]\nBOOST_HANA_CONSTANT_CHECK(head(range_c<int, 0, 5>) == int_<0>);\nBOOST_HANA_CONSTANT_CHECK(last(range_c<unsigned long, 0, 5>) == ulong<4>);\nBOOST_HANA_CONSTANT_CHECK(tail(range_c<int, 0, 5>) == range(int_<1>, int_<5>));\n//! [range_c]\n\n}\n\n}\n", "meta": {"hexsha": "989c40edc0a44969c35ad0694d7b8fafb277c71d", "size": 2181, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/range.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/range.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/range.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9259259259, "max_line_length": 86, "alphanum_fraction": 0.6886749198, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.576262471338023}}
{"text": "//\n//  dt_util.cpp\n//  Classifer_RF\n//\n//  Created by jimmy on 2017-02-16.\n//  Copyright (c) 2017 Nowhere Planet. All rights reserved.\n//\n\n#include \"dt_util.hpp\"\n#include <Eigen/QR>\n#include <iostream>\n\nusing std::cout;\nusing std::endl;\n\ntemplate <class T>\ndouble DTUtil::spatialVariance(const vector<T> & labels, const vector<unsigned int> & indices)\n{\n    if (indices.size() <= 0) {\n        return 0.0;\n    }\n    assert(indices.size() > 0);\n    \n    T mean = T::Zero(labels[0].size());\n    \n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < labels.size());\n        mean += labels[index];\n    }\n    mean /= indices.size();\n    \n    double var = 0.0;\n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < labels.size());\n        T dif = labels[index] - mean;\n        for (int j = 0; j<dif.size(); j++) {\n            var += dif[j] * dif[j];\n        }\n    }\n    return var;\n}\n\ntemplate <class T>\nvoid DTUtil::meanStddev(const vector<T> & labels, const vector<unsigned int> & indices, T & mean, T & sigma)\n{\n    assert(indices.size() > 0);\n    \n    mean = T::Zero(labels[0].size());\n    \n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < labels.size());\n        mean += labels[index];\n    }\n    mean /= indices.size();\n    \n    sigma = T::Zero(labels[0].size());\n    if (indices.size() == 1) {\n        return;\n    }\n    for (int i = 0; i<indices.size(); i++) {\n        T dif = labels[indices[i]] - mean;\n        for (int j = 0; j<sigma.size(); j++) {\n            sigma[j] += dif[j] * dif[j];\n        }\n    }\n    for (int j = 0; j<sigma.size(); j++) {\n        sigma[j] = sqrt(fabs(sigma[j])/indices.size());\n    }\n}\n\ntemplate <class T>\nT DTUtil::mean(const vector<T> & data, const vector<unsigned int> & indices)\n{\n    assert(indices.size() > 0);\n    \n    T m = T::Zero(data[0].size());\n    \n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < data.size());\n        m += data[index];\n    }\n    m /= indices.size();\n    \n    return m;\n}\n\ntemplate <class T>\nT DTUtil::mean(const vector<T> & data)\n{\n    assert(data.size() > 0);\n    \n    T m = T::Zero(data[0].size());\n    \n    for (int i = 0; i<data.size(); i++) {\n        m += data[i];\n    }\n    m /= data.size();\n    return m;\n}\n\ntemplate <class T>\nvoid DTUtil::meanMedianError(const vector<T> & errors,\n                                  T & mean,\n                                  T & median)\n{\n    assert(errors.size() > 0);\n    const int dim = (int)errors[0].size();\n    mean = T::Zero(dim);\n    median = T::Zero(dim);\n    \n    vector<vector<double> > each_dim_data(dim);\n    for (int i = 0; i<errors.size(); i++) {\n        T err = errors[i].cwiseAbs();\n        mean += err;\n        for (int j = 0; j<err.size(); j++) {\n            each_dim_data[j].push_back(err[j]);\n        }\n    }\n    mean /= errors.size();\n    \n    for (int i = 0; i<each_dim_data.size(); i++) {\n        std::sort(each_dim_data[i].begin(), each_dim_data[i].end());\n        median[i] = each_dim_data[i][each_dim_data[i].size()/2];\n    }\n}\n\n\ndouble DTUtil::balanceLoss(const int leftNodeSize, const int rightNodeSize)\n{\n    double dif = leftNodeSize - rightNodeSize;\n    double num = leftNodeSize + rightNodeSize;\n    double loss = fabs(dif)/num;\n    assert(loss >= 0);\n    return loss;\n}\n\n\n\n\ntemplate double\nDTUtil::spatialVariance(const vector<Eigen::VectorXf> & labels, const vector<unsigned int> & indices);\n\n\n\n\n\ntemplate void\nDTUtil::meanStddev(const vector<Eigen::VectorXf> & labels, const vector<unsigned int> & indices, Eigen::VectorXf & mean, Eigen::VectorXf & sigma);\n\ntemplate Eigen::VectorXf\nDTUtil::mean(const vector<Eigen::VectorXf> & data, const vector<unsigned int> & indices);\n\ntemplate Eigen::VectorXf\nDTUtil::mean(const vector<Eigen::VectorXf> & data);\n\ntemplate void\nDTUtil::meanMedianError(const vector<Eigen::VectorXf> & errors, Eigen::VectorXf & mean, Eigen::VectorXf & median);\n\n\n\n\n\n\n\n", "meta": {"hexsha": "e2d2a61a1c2cd5603f4c3d646cb2cf5d57470541", "size": 4077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dt_common/dt_util.cpp", "max_stars_repo_name": "LiliMeng/btrf", "max_stars_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-28T15:24:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T13:51:05.000Z", "max_issues_repo_path": "src/dt_common/dt_util.cpp", "max_issues_repo_name": "LiliMeng/btrf", "max_issues_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "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/dt_common/dt_util.cpp", "max_forks_repo_name": "LiliMeng/btrf", "max_forks_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-11-08T16:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-21T03:40:02.000Z", "avg_line_length": 24.124260355, "max_line_length": 146, "alphanum_fraction": 0.5523669365, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604181, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.576262467079097}}
{"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": "// g2o - General Graph Optimization\n// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright notice,\n//   this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright\n//   notice, this list of conditions and the following disclaimer in the\n//   documentation and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n// IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <Eigen/Core>\n#include <Eigen/StdVector>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include \"g2o/core/block_solver.h\"\n#include \"g2o/core/factory.h\"\n#include \"g2o/core/optimization_algorithm_gauss_newton.h\"\n#include \"g2o/core/optimization_algorithm_levenberg.h\"\n#include \"g2o/core/robust_kernel_impl.h\"\n#include \"g2o/core/solver.h\"\n#include \"g2o/core/sparse_optimizer.h\"\n#include \"g2o/solvers/dense/linear_solver_dense.h\"\n#include \"g2o/solvers/eigen/linear_solver_eigen.h\"\n#include \"g2o/types/sim3/types_seven_dof_expmap.h\"\n#include \"g2o/types/slam3d/edge_se3.h\"\n#include \"g2o/types/slam3d/types_slam3d.h\"\n#include \"g2o/types/slam3d/vertex_se3.h\"\n\nusing namespace std;\nusing namespace g2o;\n\nextern \"C\" void G2O_FACTORY_EXPORT g2o_type_VertexSE3(void);\n\n// Convert SE3 Vertex to Sim3 Vertex\nvoid ToVertexSim3(const g2o::VertexSE3& v_se3,\n                  g2o::VertexSim3Expmap* const v_sim3) {\n  Eigen::Isometry3d se3 = v_se3.estimate().inverse();\n  Eigen::Matrix3d r = se3.rotation();\n  Eigen::Vector3d t = se3.translation();\n  g2o::Sim3 sim3(r, t, 1.0);\n\n  v_sim3->setEstimate(sim3);\n}\n\n// Convert Sim3 Vertex to SE3 Vertex\nvoid ToVertexSE3(const g2o::VertexSim3Expmap& v_sim3,\n                 g2o::VertexSE3* const v_se3) {\n  g2o::Sim3 sim3 = v_sim3.estimate().inverse();\n  Eigen::Matrix3d r = sim3.rotation().toRotationMatrix();\n  Eigen::Vector3d t = sim3.translation();\n  Eigen::Isometry3d se3;\n  se3 = r;\n  se3.translation() = t;\n\n  v_se3->setEstimate(se3);\n}\n\n// Converte EdgeSE3 to EdgeSim3\nvoid ToEdgeSim3(const g2o::EdgeSE3& e_se3, g2o::EdgeSim3* const e_sim3) {\n  Eigen::Isometry3d se3 = e_se3.measurement().inverse();\n  Eigen::Matrix3d r = se3.rotation();\n  Eigen::Vector3d t = se3.translation();\n  g2o::Sim3 sim3(r, t, 1.0);\n\n  e_sim3->setMeasurement(sim3);\n}\n\n// Using VertexSim3 and EdgeSim3 is the core of this example.\n// This example optimize the data created by create_sphere.\n// Because the data is recore by VertexSE3 and EdgeSE3, SE3 is used for\n// interface and Sim is used for optimization.\n// g2o_viewer is avaliable to the result.\n\nint main(int argc, char** argv) {\n  g2o_type_VertexSE3();\n  if (argc != 2) {\n    cout << \"Usage: pose_graph_g2o_SE3 sphere.g2o\" << endl;\n    return 1;\n  }\n  ifstream fin(argv[1]);\n  if (!fin) {\n    cout << \"file \" << argv[1] << \" does not exist.\" << endl;\n    return 1;\n  }\n\n  //  define the optimizer\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<7, 7>> BlockSolverType;\n  typedef g2o::LinearSolverEigen<BlockSolverType::PoseMatrixType>\n      LinearSolverType;\n  auto solver = new g2o::OptimizationAlgorithmLevenberg(\n      g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n\n  g2o::SparseOptimizer optimizer;\n  optimizer.setAlgorithm(solver);\n  optimizer.setVerbose(true);\n\n  // Load and Save in SE3\n  g2o::SparseOptimizer interface;\n  interface.load(argv[1]);\n\n  // Convert all vertices\n  for (auto& tmp : interface.vertices()) {\n    const int& id = tmp.first;\n    g2o::VertexSE3* v_se3 = static_cast<g2o::VertexSE3*>(tmp.second);\n    g2o::VertexSim3Expmap* v_sim3 = new g2o::VertexSim3Expmap();\n    v_sim3->setId(id);\n    v_sim3->setMarginalized(false);\n\n    ToVertexSim3(*v_se3, v_sim3);\n    optimizer.addVertex(v_sim3);\n    if (id == 0) {\n      v_sim3->setFixed(true);\n    }\n  }\n\n  // Convert all edges\n  int edge_index = 0;\n  for (auto& tmp : interface.edges()) {\n    g2o::EdgeSE3* e_se3 = static_cast<g2o::EdgeSE3*>(tmp);\n    int idx0 = e_se3->vertex(0)->id();\n    int idx1 = e_se3->vertex(1)->id();\n    g2o::EdgeSim3* e_sim3 = new g2o::EdgeSim3();\n\n    ToEdgeSim3(*e_se3, e_sim3);\n    e_sim3->setId(edge_index++);\n    e_sim3->setVertex(0, optimizer.vertices()[idx0]);\n    e_sim3->setVertex(1, optimizer.vertices()[idx1]);\n    e_sim3->information() = Eigen::Matrix<double, 7, 7>::Identity();\n\n    optimizer.addEdge(e_sim3);\n  }\n\n  cout << \"optimizing ...\" << endl;\n  optimizer.initializeOptimization();\n  optimizer.optimize(30);\n\n  cout << \"saving optimization results in VertexSE3...\" << endl;\n  auto vertices_sim3 = optimizer.vertices();\n  auto vertices_se3 = interface.vertices();\n\n  for (auto& tmp : vertices_sim3) {\n    const int& id = tmp.first;\n    g2o::VertexSim3Expmap* v_sim3 =\n        static_cast<g2o::VertexSim3Expmap*>(tmp.second);\n    g2o::VertexSE3* v_se3 = static_cast<g2o::VertexSE3*>(vertices_se3[id]);\n\n    ToVertexSE3(*v_sim3, v_se3);\n  }\n\n  interface.save(\"result.g2o\");\n  return 0;\n}\n", "meta": {"hexsha": "118b59721247fb32ec7611ce97822f83e3cdfb78", "size": 5864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/g2o/g2o/examples/sim3/optimize_sphere_by_sim3.cpp", "max_stars_repo_name": "Refstop/VSLAM_Example", "max_stars_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3rdparty/g2o/g2o/examples/sim3/optimize_sphere_by_sim3.cpp", "max_issues_repo_name": "Refstop/VSLAM_Example", "max_issues_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/g2o/g2o/examples/sim3/optimize_sphere_by_sim3.cpp", "max_forks_repo_name": "Refstop/VSLAM_Example", "max_forks_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0930232558, "max_line_length": 79, "alphanum_fraction": 0.7128240109, "num_tokens": 1697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.5760858937447555}}
{"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 \u0421\u0430\u0448\u0430 \u041c\u0438\u043b\u0435\u043d\u043a\u043e\u0432\u0438\u045b                                 *\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] \u00b1 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 \u2212 b*y^2 + (ac\u22124d)*y \u2212 a^2*d\u2212c^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": "//===============================================================================//\r\n// Name\t\t\t: utils.hpp\r\n// Author(s)\t: Barbara Bruno, Antonello Scalmato\r\n// Affiliation\t: University of Genova, Italy - dept. DIBRIS\r\n// Version\t\t: 1.1\r\n// Description\t: Frequently used functions (for Creator and Classifier)\r\n//===============================================================================//\r\n\r\n#include <armadillo>\r\n\r\n\r\nusing namespace arma;\r\n\r\n#ifndef UTILS_HPP_\r\n#define UTILS_HPP_\r\n\r\n//===============================================================================//\r\n// BASIC MATRIX-HANDLING FUNCTIONS\r\n// create a row-vector of the form: start:1:stop\r\nmat createInterval(int start, int stop);\r\n// convert a matrix in MAT format to float format\r\nfloat** matToFloat(mat &matrix);\r\n// convert a matrix in float format to MAT format\r\nmat floatToMat(float** matrix, int Nrows, int Ncols);\r\n//===============================================================================//\r\n\r\n//===============================================================================//\r\n// FILTERING FUNCTIONS\r\n// compute the median value of a vector\r\ndouble median(rowvec &vector);\r\n// perform median filtering on a matrix\r\nvoid medianFilter(mat &matrix, int size);\r\n// apply ChebyshevI filter on a matrix\r\nmat ChebyshevFilter(mat matrix);\r\n//===============================================================================//\r\n\r\n#endif\r\n", "meta": {"hexsha": "0660fc73137daa3a31435dff6b6dfc2a5d9b2a36", "size": 1417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/HMPdetector/utils.hpp", "max_stars_repo_name": "Yeshasvitvs/HMP", "max_stars_repo_head_hexsha": "cdaa4cf2a9eaa0ebe4708d965b110b44698ef666", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/HMPdetector/utils.hpp", "max_issues_repo_name": "Yeshasvitvs/HMP", "max_issues_repo_head_hexsha": "cdaa4cf2a9eaa0ebe4708d965b110b44698ef666", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/HMPdetector/utils.hpp", "max_forks_repo_name": "Yeshasvitvs/HMP", "max_forks_repo_head_hexsha": "cdaa4cf2a9eaa0ebe4708d965b110b44698ef666", "max_forks_repo_licenses": ["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.2894736842, "max_line_length": 84, "alphanum_fraction": 0.4629498941, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5760238691786881}}
{"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 uniform_sensor.hpp\n * \\date September 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <fl/util/descriptor.hpp>\n#include <fl/distribution/uniform_distribution.hpp>\n#include <fl/model/sensor/interface/sensor_density.hpp>\n#include <fl/model/sensor/interface/sensor_function.hpp>\n\nnamespace fl\n{\n\ntemplate <typename State_>\nclass UniformSensor\n    : public SensorFunction<Vector1d, State_, Vector1d>,\n      public SensorDensity<Vector1d, State_>,\n      public Descriptor\n{\npublic:\n    typedef Vector1d Obsrv;\n    typedef Vector1d Noise;\n    typedef State_   State;\n\npublic:\n    UniformSensor(\n        Real min_value,\n        Real max_value,\n        int state_dim = DimensionOf<State>::Value)\n        : state_dim_(state_dim),\n          density_(min_value, max_value)\n    { }\n\n    Real log_probability(const Obsrv& obsrv, const State& state) const override\n    {\n        return density_.log_probability(obsrv);\n    }\n\n    Real probability(const Obsrv& obsrv, const State& state) const override\n    {\n        return density_.probability(obsrv);\n    }\n\n    Obsrv observation(const State& state, const Noise& noise) const override\n    {\n        Obsrv y = density_.map_standard_normal(noise);\n        return y;\n    }\n\n    virtual int obsrv_dimension() const { return 1; }\n    virtual int noise_dimension() const { return 1; }\n    virtual int state_dimension() const { return state_dim_; }\n\n    virtual std::string name() const\n    {\n        return \"UniformSensor\";\n    }\n\n    virtual std::string description() const\n    {\n        return \"UniformSensor\";\n    }\n\nprivate:\n    int state_dim_;\n    UniformDistribution density_;\n};\n\n}\n", "meta": {"hexsha": "08040981af8f3336ee8a481a68b8bbf4817d1e04", "size": 2105, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/model/sensor/uniform_sensor.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/model/sensor/uniform_sensor.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/model/sensor/uniform_sensor.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": 23.9204545455, "max_line_length": 79, "alphanum_fraction": 0.6793349169, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5760238618975817}}
{"text": "/* test_fisher_f.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id: test_fisher_f.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\r\n *\r\n */\r\n\r\n#include <boost/random/fisher_f_distribution.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/math/distributions/fisher_f.hpp>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::fisher_f_distribution<>\r\n#define BOOST_RANDOM_DISTRIBUTION_NAME fisher_f\r\n#define BOOST_MATH_DISTRIBUTION boost::math::fisher_f\r\n#define BOOST_RANDOM_ARG1_TYPE double\r\n#define BOOST_RANDOM_ARG1_NAME m\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\r\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)\r\n#define BOOST_RANDOM_ARG2_TYPE double\r\n#define BOOST_RANDOM_ARG2_NAME n\r\n#define BOOST_RANDOM_ARG2_DEFAULT 1000.0\r\n#define BOOST_RANDOM_ARG2_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)\r\n\r\n#include \"test_real_distribution.ipp\"\r\n", "meta": {"hexsha": "b474bfd533bc31fcba5e6f0d06019a1055dc6fd7", "size": 1055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_fisher_f.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/random/test/test_fisher_f.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/random/test/test_fisher_f.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 36.3793103448, "max_line_length": 76, "alphanum_fraction": 0.790521327, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5760238599449349}}
{"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": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, log1p_exp) {\n  using stan::math::log1p_exp;\n\n  // exp(10000.0) overflows\n  EXPECT_FLOAT_EQ(10000.0,log1p_exp(10000.0));\n  EXPECT_FLOAT_EQ(0.0,log1p_exp(-10000.0));\n}\n\nTEST(MathFunctions, log1p_exp_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::log1p_exp(nan));\n}\n", "meta": {"hexsha": "542e11fd8ee9c6028da3c6b3d6acd0bc0957654a", "size": 489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log1p_exp_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log1p_exp_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log1p_exp_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7368421053, "max_line_length": 56, "alphanum_fraction": 0.7096114519, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.5760238579922872}}
{"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": "//  (C) Copyright Nick Thompson 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <random>\n#include <array>\n#include <vector>\n#include <iostream>\n#include <benchmark/benchmark.h>\n#include <boost/math/tools/cubic_roots.hpp>\n\nusing boost::math::tools::cubic_roots;\n\ntemplate<class Real>\nvoid CubicRoots(benchmark::State& state)\n{\n    std::random_device rd;\n    auto seed = rd();\n    // This seed generates 3 real roots:\n    //uint32_t seed = 416683252;\n    std::mt19937_64 mt(seed);\n    std::uniform_real_distribution<Real> unif(-10, 10);\n\n    Real a = unif(mt);\n    Real b = unif(mt);\n    Real c = unif(mt);\n    Real d = unif(mt);\n    for (auto _ : state)\n    {\n        auto roots = cubic_roots(a,b,c,d);\n        benchmark::DoNotOptimize(roots[0]);\n    }\n}\n\nBENCHMARK_TEMPLATE(CubicRoots, float);\nBENCHMARK_TEMPLATE(CubicRoots, double);\nBENCHMARK_TEMPLATE(CubicRoots, long double);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "3550677dda9436e8dc9f4192941d87940d9d160d", "size": 1057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/libs/math/reporting/performance/cubic_roots_performance.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "lib/boost_1.78.0/libs/math/reporting/performance/cubic_roots_performance.cpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "lib/boost_1.78.0/libs/math/reporting/performance/cubic_roots_performance.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 25.7804878049, "max_line_length": 68, "alphanum_fraction": 0.6877956481, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5760206368730033}}
{"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": "///////////////////////////////////////////////////////////////\n//  Copyright 2015 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <iterator>\n\n// Contains Quickbook snippets in comments.\n\n//[IE2\n\n/*`\nImporting or exporting cpp_bin_float is similar, but we must proceed via an intermediate integer:\n*/\n/*=\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <iterator>\n*/\n\nint main()\n{\n   using boost::multiprecision::cpp_bin_float_100;\n   using boost::multiprecision::cpp_int;\n   // Create a cpp_bin_float to import/export:\n   cpp_bin_float_100 f(1);\n   f /= 3;\n   // export into 8-bit unsigned values, most significant bit first:\n   std::vector<unsigned char> v;\n   export_bits(cpp_int(f.backend().bits()), std::back_inserter(v), 8);\n   // Grab the exponent as well:\n   int e = f.backend().exponent();\n   // Import back again, and check for equality, we have to proceed via\n   // an intermediate integer:\n   cpp_int i;\n   import_bits(i, v.begin(), v.end());\n   cpp_bin_float_100 g(i);\n   g.backend().exponent() = e;\n   BOOST_ASSERT(f == g);\n}\n\n//]\n\n", "meta": {"hexsha": "045cbc86901ef6c8e431f609c91abbf24f82a294", "size": 1352, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/multiprecision/example/cpp_bin_float_import_export.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/example/cpp_bin_float_import_export.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/multiprecision/example/cpp_bin_float_import_export.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": 27.04, "max_line_length": 97, "alphanum_fraction": 0.6730769231, "num_tokens": 332, "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": "// 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": "#define CATCH_CONFIG_ENABLE_BENCHMARKING\n#include \"catch.hpp\"\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include <libUncertainty/correlation.hpp>\n#include <libUncertainty/uncertain.hpp>\n#include <libUncertainty/propagate.hpp>\n#include <BoostUnitDefinitions/Units.hpp>\n\nusing namespace boost::units;\nusing namespace libUncertainty;\n\nTEST_CASE(\"Correlations Utilities\")\n{\n  SECTION(\"Correlation matrix\")\n  {\n    correlation_matrix<double> mat(3);\n    CHECK(mat(0, 1) == Approx(0).scale(1));\n    CHECK(mat(1, 0) == Approx(0).scale(1));\n    CHECK(mat(0, 2) == Approx(0).scale(1));\n    CHECK(mat(2, 0) == Approx(0).scale(1));\n    CHECK(mat(0, 3) == Approx(0).scale(1));\n    CHECK(mat(3, 0) == Approx(0).scale(1));\n    CHECK(mat(0, 0) == Approx(1));\n    CHECK(mat(1, 1) == Approx(1));\n    CHECK(mat(2, 2) == Approx(1));\n\n    mat(0, 1) = 0.1;\n    mat(0, 2) = 0.2;\n    mat(1, 2) = 0.3;\n\n    CHECK(mat(0, 1) == Approx(0.1));\n    CHECK(mat(1, 0) == Approx(0.1));\n    CHECK(mat(0, 2) == Approx(0.2));\n    CHECK(mat(2, 0) == Approx(0.2));\n    CHECK(mat(0, 3) == Approx(0.3));\n    CHECK(mat(3, 0) == Approx(0.3));\n    CHECK(mat(0, 0) == Approx(1));\n    CHECK(mat(1, 1) == Approx(1));\n    CHECK(mat(2, 2) == Approx(1));\n  }\n\n  SECTION(\"Error propagation w/ correlation matrix.\")\n  {\n    boost::numeric::ublas::matrix<double> corr(2, 2);\n    corr(0, 0) = 1;\n    corr(1, 0) = 1;\n    corr(0, 1) = 1;\n    corr(1, 1) = 1;\n\n    uncertain<double> x(2, 0.1), y(3, 0.1);\n\n    auto z = basic_error_propagator::propagate_error([](double a, double b) { return b - a; }, corr, x, y);\n\n    // a and b are directly correlated, so there is no uncertainy in their difference.\n    // the nominal and upper values should be the same.\n    CHECK(z.nominal() == Approx(1));\n    CHECK(z.upper() == Approx(1));\n  }\n\n  SECTION(\"add_correlation_coefficients Mixin\")\n  {\n    add_correlation_coefficient_array<uncertain<double>> x({2.2, 0.1});\n    add_correlation_coefficient_array<uncertain<double>> y = {3.3, 0.2};\n\n    CHECK(x.get_correlation_coefficients().size() == 0);\n    x.set_correlation_coefficient_array_size(3);\n    x.get_correlation_coefficients()[0] = 1;\n    x.get_correlation_coefficients()[1] = 2;\n    x.get_correlation_coefficients()[2] = 3;\n\n    auto z = x;\n\n    CHECK(x.get_correlation_coefficients().size() == 3);\n    CHECK(x.get_correlation_coefficients()[0] == Approx(1));\n    CHECK(x.get_correlation_coefficients()[1] == Approx(2));\n    CHECK(x.get_correlation_coefficients()[2] == Approx(3));\n\n    CHECK(z.get_correlation_coefficients().size() == 3);\n    CHECK(z.get_correlation_coefficients()[0] == Approx(1));\n    CHECK(z.get_correlation_coefficients()[1] == Approx(2));\n    CHECK(z.get_correlation_coefficients()[2] == Approx(3));\n  }\n\n  SECTION(\"Correlation store\")\n  {\n    add_id<uncertain<double>> x,y,z;\n    correlation_store<double> store;\n\n    store.add(x, y, 0.1);\n    store.add(y, z, 0.2);\n\n    CHECK_THROWS(store.add(x, y, 0.1));\n\n    CHECK(store.get(x, y) == Approx(0.1));\n    CHECK(store.get(y, z) == Approx(0.2));\n\n    auto& global_store = get_global_correlation_store();\n\n    global_store.add(x, y, 0.1);\n    global_store.add(x, z, 0.2);\n\n    CHECK_THROWS(global_store.add(y, x, 0.1));\n\n    CHECK(global_store.get(x, y) == Approx(0.1));\n    CHECK(global_store.get(x, z) == Approx(0.2));\n\n    global_store.set(x,y,0.5);\n    global_store.set(x,z,-0.5);\n    global_store.set(z,y,1);\n\n    CHECK(global_store.get(y,x) == Approx(0.5) );\n    CHECK(global_store.get(z,x) == Approx(-0.5) );\n    CHECK(global_store.get(z,y) == Approx(1) );\n\n  }\n\n  SECTION(\"Error propagation w/ correlation\")\n  {\n    SECTION(\"Doubles\")\n    {\n      uncertain<double> x(1, 0.1), y(2, 0.2);\n\n      SECTION(\"Independent\")\n      {\n        auto z_and_correlation = basic_error_propagator::propagate_error_and_correlation([](double a, double b) { return a + b; }, x, y);\n\n        double unc = sqrt(0.1 * 0.1 + 0.2 * 0.2);\n        CHECK(z_and_correlation.nominal() == Approx(3));\n        CHECK(z_and_correlation.upper() == Approx(3 + unc));\n        CHECK(z_and_correlation.get_correlation_coefficients().size() == 2);\n        CHECK(z_and_correlation.get_correlation_coefficient(0) == Approx(0.1 / unc));\n        CHECK(z_and_correlation.get_correlation_coefficient(1) == Approx(0.2 / unc));\n      }\n\n      SECTION(\"with Correlation Matrix\")\n      {\n        correlation_matrix<double> corr(2);\n        corr(0, 1) = -1;\n\n        auto z_and_correlation = basic_error_propagator::propagate_error_and_correlation([](double a, double b) { return a + b; }, corr, x, y);\n\n        double unc = 0.1;\n        CHECK(z_and_correlation.nominal() == Approx(3));\n        CHECK(z_and_correlation.upper() == Approx(3 + unc));\n        CHECK(z_and_correlation.get_correlation_coefficients().size() == 2);\n        CHECK(z_and_correlation.get_correlation_coefficients().size() == 2);\n        CHECK(z_and_correlation.get_correlation_coefficient(0) == Approx((0.1 + 0.2 * -1) / unc));\n        CHECK(z_and_correlation.get_correlation_coefficient(1) == Approx((0.2 + 0.1 * -1) / unc));\n      }\n      SECTION(\"with Correlation Store\")\n      {\n        correlation_store<double> cstore;\n        add_id<uncertain<double>> xx;\n        add_id<uncertain<double>> yy;\n        xx = x;\n        yy = y;\n\n        cstore.add(xx, yy, -1);\n\n        auto z = basic_error_propagator::propagate_error([](double a, double b) { return a + b; }, cstore, xx, yy);\n\n        double unc = 0.1;\n        CHECK(z.nominal() == Approx(3));\n        CHECK(z.upper() == Approx(3 + unc));\n        CHECK(cstore.get(z, xx) == Approx((0.1 + 0.2 * -1) / unc));\n        CHECK(cstore.get(z, yy) == Approx((0.2 + 0.1 * -1) / unc));\n\n      }\n\n    }\n\n    SECTION(\"boost quantities\")\n    {\n      uncertain<quantity<t::cm>> x(1 * i::cm, 0.1 * i::cm), y(2 * i::cm, 0.2 * i::cm);\n      SECTION(\"Independent\")\n      {\n        SECTION(\"Addition\")\n        {\n          auto z_and_correlation = basic_error_propagator::propagate_error_and_correlation([](auto a, auto b) { return a + b; }, x, y);\n\n          double unc = sqrt(0.1 * 0.1 + 0.2 * 0.2);\n          CHECK(z_and_correlation.nominal().value() == Approx(3));\n          CHECK(z_and_correlation.upper().value() == Approx(3 + unc));\n          CHECK(z_and_correlation.get_correlation_coefficients().size() == 2);\n          CHECK(z_and_correlation.get_correlation_coefficients().size() == 2);\n          CHECK(z_and_correlation.get_correlation_coefficient(0) == Approx(0.1 / unc));\n          CHECK(z_and_correlation.get_correlation_coefficient(1) == Approx(0.2 / unc));\n        }\n\n        SECTION(\"Multiplyication\")\n        {\n          auto z_and_correlation = basic_error_propagator::propagate_error_and_correlation([](auto a, auto b) { return a * b; }, x, y);\n\n          double unc = sqrt(0.2 * 0.2 + 0.2 * 0.2);\n          CHECK(z_and_correlation.nominal().value() == Approx(2));\n          CHECK(z_and_correlation.upper().value() == Approx(2 + unc));\n          CHECK(z_and_correlation.get_correlation_coefficients().size() == 2);\n          CHECK(z_and_correlation.get_correlation_coefficient(0) == Approx(0.2 / unc));\n          CHECK(z_and_correlation.get_correlation_coefficient(1) == Approx(0.2 / unc));\n        }\n      }\n      SECTION(\"with Correlation Matrix\")\n      {\n        correlation_matrix<double> corr(2);\n        corr(0, 1) = -1;\n\n        auto z_and_correlation = basic_error_propagator::propagate_error_and_correlation([](auto a, auto b) { return a + b; }, corr, x, y);\n\n        double unc = 0.1;\n        CHECK(z_and_correlation.nominal().value() == Approx(3));\n        CHECK(z_and_correlation.upper().value() == Approx(3 + unc));\n        CHECK(z_and_correlation.get_correlation_coefficients().size() == 2);\n        CHECK(z_and_correlation.get_correlation_coefficients().size() == 2);\n        CHECK(z_and_correlation.get_correlation_coefficient(0) == Approx((0.1 + 0.2 * -1) / unc));\n        CHECK(z_and_correlation.get_correlation_coefficient(1) == Approx((0.2 + 0.1 * -1) / unc));\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "911a14820047d6d020fbdd772803f15766b5c642", "size": 7954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/CatchTests/correlation.cpp", "max_stars_repo_name": "CD3/libUncertainty", "max_stars_repo_head_hexsha": "b7220cf1ae56032cdc806be41daca2fe1ab43dcb", "max_stars_repo_licenses": ["MIT"], "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/CatchTests/correlation.cpp", "max_issues_repo_name": "CD3/libUncertainty", "max_issues_repo_head_hexsha": "b7220cf1ae56032cdc806be41daca2fe1ab43dcb", "max_issues_repo_licenses": ["MIT"], "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/CatchTests/correlation.cpp", "max_forks_repo_name": "CD3/libUncertainty", "max_forks_repo_head_hexsha": "b7220cf1ae56032cdc806be41daca2fe1ab43dcb", "max_forks_repo_licenses": ["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.9909502262, "max_line_length": 143, "alphanum_fraction": 0.613150616, "num_tokens": 2386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.576015062979081}}
{"text": "\ufeff\n#pragma once\n\n#include <Eigen/Core>\n\n\nusing Vec2i = Eigen::Vector2i;\nusing Vec2f = Eigen::Vector2f;\nusing Vec2d = Eigen::Vector2d;\n\nusing Vec3i = Eigen::Vector3i;\nusing Vec3f = Eigen::Vector3f;\nusing Vec3d = Eigen::Vector3d;", "meta": {"hexsha": "0255879feea67349ae8ecc1dc42d81d784e5a5ec", "size": 226, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/vector.hpp", "max_stars_repo_name": "Lacty/YanaiLib", "max_stars_repo_head_hexsha": "b26d1eb5e50d2534bf34f5c05203434e7a72ef23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-06-27T07:24:05.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-18T05:02:19.000Z", "max_issues_repo_path": "src/lib/vector.hpp", "max_issues_repo_name": "Lacty/YanaiLib", "max_issues_repo_head_hexsha": "b26d1eb5e50d2534bf34f5c05203434e7a72ef23", "max_issues_repo_licenses": ["MIT"], "max_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/vector.hpp", "max_forks_repo_name": "Lacty/YanaiLib", "max_forks_repo_head_hexsha": "b26d1eb5e50d2534bf34f5c05203434e7a72ef23", "max_forks_repo_licenses": ["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.3846153846, "max_line_length": 30, "alphanum_fraction": 0.7256637168, "num_tokens": 75, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.576015062979081}}
{"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": "#ifndef STAN_MATH_PRIM_FUN_INC_BETA_DDZ_HPP\n#define STAN_MATH_PRIM_FUN_INC_BETA_DDZ_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/fun/exp.hpp>\n#include <stan/math/prim/fun/lgamma.hpp>\n#include <stan/math/prim/fun/log.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Returns the partial derivative of the regularized\n * incomplete beta function, I_{z}(a, b) with respect to z.\n *\n * @tparam T scalar types of arguments\n * @param a first argument\n * @param b second argument\n * @param z upper bound of the integral\n * @return partial derivative of the incomplete beta with respect to z\n *\n * @pre a > 0\n * @pre b > 0\n * @pre 0 < z <= 1\n */\ntemplate <typename T>\nT inc_beta_ddz(T a, T b, T z) {\n  using std::exp;\n  using std::log;\n  return exp((b - 1) * log(1 - z) + (a - 1) * log(z) + lgamma(a + b) - lgamma(a)\n             - lgamma(b));\n}\n\ntemplate <>\ninline double inc_beta_ddz(double a, double b, double z) {\n  using boost::math::ibeta_derivative;\n  return ibeta_derivative(a, b, z);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "b1d8f42df1100e509182b13c68bad9bdc9dd0b80", "size": 1121, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/inc_beta_ddz.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-05-18T13:10:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T13:10:50.000Z", "max_issues_repo_path": "stan/math/prim/fun/inc_beta_ddz.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T12:45:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T20:43:03.000Z", "max_forks_repo_path": "stan/math/prim/fun/inc_beta_ddz.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": 24.9111111111, "max_line_length": 80, "alphanum_fraction": 0.6842105263, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5760093824997125}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2015 Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <boost/tuple/tuple.hpp>\n\n#include <rokko/utility/xyz_hamiltonian.hpp>\n#include <rokko/localized_matrix.hpp>\n#include <rokko/localized_vector.hpp>\n\nint main(int argc, char *argv[]) {\n  int L, N, num_bonds;\n  L = 4;\n  num_bonds = L - 1;\n  N = 1 << L;\n  std::vector<std::pair<int, int> > lattice;\n  std::vector<boost::tuple<double, double, double> > coupling;\n  for (int i=0; i<L-1; ++i) {\n    lattice.push_back(std::make_pair(i, i+1));\n    coupling.push_back(boost::make_tuple(1, 1, 1));\n  }\n\n  std::cout << \"dim=\" << N << std::endl;  \n  std::cout << \"L=\" << L << std::endl;\n  for (int i=0; i<num_bonds; ++i) {\n    std::cout << lattice[i].first << \" \" << lattice[i].second << \" \" << coupling[i].get<0>() << \" \" << coupling[i].get<1>() << \" \" << coupling[i].get<2>() << std::endl;\n  }\n\n\n  rokko::localized_matrix<double, rokko::matrix_col_major> mat1(N, N);\n  std::cout << \"multiply:\" << std::endl;\n  for (int i=0; i<N; ++i) {\n    std::vector<double> v, w;\n    v.assign(N, 0);\n    v[i] = 1;\n    w.assign(N, 0);\n    rokko::xyz_hamiltonian::multiply(L, lattice, coupling, v, w);\n    for (int j=0; j<N; ++j) {\n      mat1(j,i) = w[j];\n      std::cout << w[j] << \" \";\n    }\n    std::cout << std::endl;\n  }\n\n  std::cout << \"fill_diagonal:\" << std::endl;\n  rokko::localized_vector<double> diagonal(N);\n  std::vector<double> v(N);\n  rokko::xyz_hamiltonian::fill_diagonal(L, lattice, coupling, v);\n  for (int j=0; j<N; ++j) {\n    diagonal(j) = v[j];\n    std::cout << v[j] << \" \";\n  }\n  std::cout << std::endl;\n\n  std::cout << \"fill_matrix:\" << std::endl;\n  rokko::localized_matrix<double, rokko::matrix_col_major> mat2(N, N);\n  rokko::xyz_hamiltonian::generate(L, lattice, coupling, mat2);\n  for (int i=0; i<N; ++i) {\n    for (int j=0; j<N; ++j) {\n      std::cout << mat2(i,j) << \" \";\n    }\n    std::cout << std::endl;\n  }\n\n  if (mat1 == mat2) {\n    std::cout << \"OK: matrix by 'multiply' equals to a matrix by 'generate'.\" << std::endl;\n  } else {\n    std::cout << \"ERROR: matrix by 'multiply' is differnet from a matrix by 'generate'.\"<< std::endl;\n    exit(1);\n  }\n\n  if (diagonal == mat2.diagonal()) {\n    std::cout << \"OK: diagonal by 'fill_diagonal' equals to diagonal elementas of a matrix by 'genertate'.\"<< std::endl;\n  } else {\n    std::cout << \"ERROR: diagonal by 'fill_diagonal' is differnet from diagonal elementas of a matrix by 'genertate'.\"<< std::endl;\n    exit(1);\n  }\n\n}\n\n\n", "meta": {"hexsha": "76389a49a6314997f947f2dc03212973683980eb", "size": 2916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/generate_matrix/xyz.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/generate_matrix/xyz.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/generate_matrix/xyz.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6956521739, "max_line_length": 168, "alphanum_fraction": 0.5692729767, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5759997247042193}}
{"text": "/* test_chi_squared_distribution.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/chi_squared_distribution.hpp>\r\n#include <limits>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::chi_squared_distribution<>\r\n#define BOOST_RANDOM_ARG1 n\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1.0\r\n#define BOOST_RANDOM_ARG1_VALUE 7.5\r\n\r\n#define BOOST_RANDOM_DIST0_MIN 0\r\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST1_MIN 0\r\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST2_MIN 0\r\n#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<double>::infinity)()\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS\r\n#define BOOST_RANDOM_TEST1_MIN 0.0\r\n#define BOOST_RANDOM_TEST1_MAX 100.0\r\n\r\n#define BOOST_RANDOM_TEST2_PARAMS (10000.0)\r\n#define BOOST_RANDOM_TEST2_MIN 100.0\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "9ca3c50a286e7c9d399b63bfe8a8eb47183b658c", "size": 1075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_chi_squared_distribution.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/random/test/test_chi_squared_distribution.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/random/test/test_chi_squared_distribution.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 30.7142857143, "max_line_length": 76, "alphanum_fraction": 0.7851162791, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5759997123372829}}
{"text": "#include \"hoNDFFT.h\"\n#include \"hoNDArray_math.h\"\n#include \"complext.h\"\n#include <gtest/gtest.h>\n#include <boost/random.hpp>\n#include <random>\n\nusing namespace Gadgetron;\nusing testing::Types;\n\ntemplate<typename REAL> class hoNDFFT_test : public ::testing::Test {\nprotected:\n\tvirtual void SetUp(){\n\t\tboost::random::mt19937 rng;\n\t\tboost::random::uniform_real_distribution<REAL> uni(0,1);\n\t\tstd::vector<size_t > dimensions(3,128);\n\n\t\tArray = hoNDArray<complext<REAL> >(dimensions);\n\t\tcomplext<REAL>* data = Array.get_data_ptr();\n\n\t\tfor (size_t i = 0; i < Array.get_number_of_elements(); i++)\n\t\t\tdata[i] = complext<REAL>(uni(rng),uni(rng));\n\n\t\tArray2 = Array;\n\t}\n\n\thoNDArray<complext<REAL> > Array;\n\n\thoNDArray<complext<REAL> > Array2;\n\n};\ntypedef Types<float, double> realImplementations;\nTYPED_TEST_SUITE(hoNDFFT_test, realImplementations);\n\nTYPED_TEST(hoNDFFT_test,fftNrm2Test){\n\thoNDFFT<TypeParam>::instance()->fft(&this->Array);\n\n\tEXPECT_NEAR(nrm2(&this->Array2),nrm2(&this->Array),nrm2(&this->Array)*1e-2);\n\n}\n\n\nTYPED_TEST(hoNDFFT_test,ifftNrm2Test){\n\thoNDFFT<TypeParam>::instance()->ifft(&this->Array);\n\n\tEXPECT_NEAR(nrm2(&this->Array2),nrm2(&this->Array),nrm2(&this->Array)*1e-2);\n\n}\n\n\n\n\nTYPED_TEST(hoNDFFT_test,fft1Nrm2Test){\n    hoNDFFT<TypeParam>::instance()->fft(&this->Array,0);\n\n    EXPECT_NEAR(nrm2(&this->Array2),nrm2(&this->Array),nrm2(&this->Array)*1e-2);\n\n}\n\nTEST(FFTshiftTest,shift1d_inplace){\n\n    auto array = hoNDArray<std::complex<float>>(24);\n    array.fill(0.0f);\n    array(2) = 1;\n    hoNDFFT<float>::instance()->fftshift1D(array);\n    EXPECT_EQ(array(14),1.0f);\n    EXPECT_EQ(array(2),0.0f);\n\n}\n\n\nTEST(FFTshiftTest,shift1d){\n\n    auto array = hoNDArray<std::complex<float>>(24);\n    array.fill(0.0f);\n    array(2) = 1;\n    auto output = array;\n    output.fill(0.0f);\n    hoNDFFT<float>::instance()->fftshift1D(array,output);\n    EXPECT_EQ(output(14),1.0f);\n    EXPECT_EQ(output(2),0.0f);\n\n}\n\nTEST(FFTshiftTest,shift2d_inplace){\n\n    auto array = hoNDArray<std::complex<float>>(24,8);\n    array.fill(0.0f);\n    array(2,3) = 1;\n    hoNDFFT<float>::instance()->fftshift2D(array);\n    EXPECT_EQ(array(14,7),1.0f);\n    EXPECT_EQ(array(2,3),0.0f);\n\n}\n\n\nTEST(FFTshiftTest,shift2d){\n\n    auto array = hoNDArray<std::complex<float>>(24,8);\n    array.fill(0.0f);\n    array(2,3) = 1;\n    auto output = array;\n    output.fill(0.0f);\n    hoNDFFT<float>::instance()->fftshift2D(array,output);\n    EXPECT_EQ(output(14,7),1.0f);\n    EXPECT_EQ(output(2,3),0.0f);\n\n}\n\nTEST(FFTshiftTest,shift3d_inplace){\n\n    auto array = hoNDArray<std::complex<float>>(24,8, 26,3);\n    array.fill(0.0f);\n    array(2,3, 4,0) = 1;\n    hoNDFFT<float>::instance()->fftshift3D(array);\n    EXPECT_EQ(array(14,7, 17,0),1.0f);\n    EXPECT_EQ(array(2,3, 4,0),0.0f);\n\n}\n\n\nTEST(FFTshiftTest,shift3d){\n\n    auto array = hoNDArray<std::complex<float>>(24,8, 26,3);\n    array.fill(0.0f);\n    array(2,3, 4,0) = 1;\n    auto output = array;\n    output.fill(0.0f);\n    hoNDFFT<float>::instance()->fftshift3D(array,output);\n    EXPECT_EQ(output(14,7,17,0),1.0f);\n    EXPECT_EQ(output(2,3, 4,0),0.0f);\n\n}\n\ntemplate<class... INDICES>\nstatic auto make_random_array(INDICES... indices){\n    auto array = hoNDArray<std::complex<float>>(indices...);\n    std::default_random_engine e1;\n    std::uniform_real_distribution<float> dist{};\n    for (auto& val : array) val = {dist(e1),dist(e1)};\n\n    return array;\n}\n\nTEST(FFTshiftTest, shift3d_random){\n    auto array = make_random_array(24,8,26,3);\n\n    const auto array_copy = array;\n\n    hoNDFFT<float>::instance()->fftshift3D(array);\n    hoNDFFT<float>::instance()->ifftshift3D(array);\n\n    EXPECT_EQ(array,array_copy);\n\n    auto buffer = array;\n    hoNDFFT<float>::instance()->fftshift3D(array,buffer);\n    hoNDFFT<float>::instance()->ifftshift3D(buffer,array);\n\n    EXPECT_EQ(array,array_copy);\n\n\n\n    hoNDFFT<float>::instance()->ifftshift3D(array, buffer);\n    hoNDFFT<float>::instance()->fftshift3D(buffer);\n\n    EXPECT_EQ(buffer,array_copy);\n\n}\n\n\n", "meta": {"hexsha": "8e57a3ec7ed76a2775127f70dee9bbd3d2cd92c1", "size": 3965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/hoNDFFT_test.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "test/hoNDFFT_test.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/hoNDFFT_test.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1871345029, "max_line_length": 80, "alphanum_fraction": 0.6698612863, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5759996999703453}}
{"text": "\n// solving A * X = B\n// A symmetric\n// driver function sysv()\n\n#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/lapack/sysv.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_symmetric.hpp>\n#include <boost/numeric/bindings/traits/ublas_hermitian.hpp>\n#include \"utils2.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; \ntypedef std::complex<real> cmplx_t; \n\ntypedef ublas::matrix<real, ublas::column_major> m_t;\ntypedef ublas::matrix<cmplx_t, ublas::column_major> cm_t;\n\ntypedef ublas::symmetric_adaptor<m_t, ublas::lower> symml_t; \ntypedef ublas::symmetric_adaptor<m_t, ublas::upper> symmu_t; \n\ntypedef ublas::symmetric_adaptor<cm_t, ublas::lower> csymml_t; \ntypedef ublas::symmetric_adaptor<cm_t, ublas::upper> csymmu_t; \n\ntemplate <typename M>\nvoid init_symm2 (M& m) {\n  for (int i = 0; i < m.size1(); ++i) \n    for (int j = i; j < m.size1(); ++j)\n      m (i, j) = m (j, i) = 1 + j - i; \n}\n\nint main() {\n\n  cout << endl; \n\n  // symmetric \n  cout << \"real symmetric\\n\" << endl; \n\n  size_t n;\n  cout << \"n -> \";\n  cin >> n;\n  if (n < 5) n = 5; \n  cout << \"min n = 5\" << endl << endl; \n  size_t nrhs = 2; \n  m_t al (n, n), au (n, n);  // matrices (storage)\n  symml_t sal (al);   // symmetric adaptor\n  symmu_t sau (au);   // symmetric adaptor\n  m_t x (n, nrhs);\n  m_t bl (n, nrhs), bu (n, nrhs);  // RHS matrices\n\n  init_symm2 (al); \n  ublas::swap (row (al, 1), row (al, 4)); \n  ublas::swap (column (al, 1), column (al, 4)); \n\n  print_m (al, \"al\"); \n  cout << endl; \n\n  init_symm2 (au); \n  ublas::swap (row (au, 2), row (au, 3)); \n  ublas::swap (column (au, 2), column (au, 3)); \n\n  print_m (au, \"au\"); \n  cout << endl; \n\n  for (int i = 0; i < x.size1(); ++i) {\n    x (i, 0) = 1.;\n    x (i, 1) = 2.; \n  }\n  bl = ublas::prod (sal, x); \n  bu = ublas::prod (sau, x); \n\n  print_m (bl, \"bl\"); \n  cout << endl; \n  print_m (bu, \"bu\"); \n  cout << endl; \n\n  m_t al1 (al), au1 (au);  // for part 2\n  m_t bl1 (bl), bu1 (bu); \n\n  lapack::sysv (sal, bl);  \n  print_m (bl, \"xl\"); \n  cout << endl; \n\n  lapack::sysv (sau, bu);  \n  print_m (bu, \"xu\"); \n  cout << endl; \n\n  // part 2 \n\n  std::vector<int> ipiv (n); \n  std::vector<real> work (1); \n\n  int err = lapack::sysv ('L', al1, ipiv, bl1, work);  \n  print_m (al1, \"al1 factored\"); \n  cout << endl; \n  print_v (ipiv, \"ipiv\"); \n  cout << endl; \n  print_m (bl1, \"xl1\"); \n  cout << endl; \n\n  err = lapack::sysv ('U', au1, ipiv, bu1, work);  \n  print_m (au1, \"au1 factored\"); \n  cout << endl; \n  print_v (ipiv, \"ipiv\"); \n  cout << endl; \n  print_m (bu1, \"xu1\"); \n  cout << endl; \n  cout << endl; \n\n  //////////////////////////////////////////////////////////\n  cout << \"\\n==========================================\\n\" << endl; \n  cout << \"complex symmetric\\n\" << endl; \n\n  cm_t cal (n, n), cau (n, n);   // matrices (storage)\n  csymml_t scal (cal);   // hermitian adaptor \n  csymmu_t scau (cau);   // hermitian adaptor \n  cm_t cx (n, 1); \n  cm_t cbl (n, 1), cbu (n, 1);  // RHS\n\n  init_symm2 (cal); \n  init_symm2 (cau); \n  cal *= cmplx_t (1, 1); \n  cau *= cmplx_t (1, -0.5); \n\n  print_m (cal, \"cal\"); \n  cout << endl; \n  print_m (cau, \"cau\"); \n  cout << endl; \n\n  for (int i = 0; i < cx.size1(); ++i) \n    cx (i, 0) = cmplx_t (1, -1); \n  print_m (cx, \"cx\"); \n  cout << endl; \n  cbl = ublas::prod (scal, cx);\n  cbu = ublas::prod (scau, cx);\n  print_m (cbl, \"cbl\"); \n  cout << endl; \n  print_m (cbu, \"cbu\"); \n  cout << endl; \n\n  int ierr = lapack::sysv (scal, cbl); \n  if (ierr == 0)\n    print_m (cbl, \"cxl\"); \n  else \n    cout << \"matrix is not regular: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n  std::vector<cmplx_t> cwork (n); \n\n  ierr = lapack::sysv (scau, ipiv, cbu, cwork); \n  if (ierr == 0) {\n    print_v (ipiv, \"ipiv\"); \n    cout << endl; \n    print_m (cbu, \"cxu\"); \n  }\n  else \n    cout << \"matrix is not regular: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "88343c169e60aae67542abd4fec3fe951045642d", "size": 4160, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/vc6/ublas_sysv.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/vc6/ublas_sysv.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/vc6/ublas_sysv.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 23.5028248588, "max_line_length": 68, "alphanum_fraction": 0.5579326923, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5759216550220441}}
{"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 * 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/LinearMeasurementModel.h>\n\n#include <Eigen/Dense>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nstd::pair<bool, bfl::Data> LinearMeasurementModel::predictedMeasure(const Eigen::Ref<const Eigen::MatrixXd>& cur_states) const\n{\n    MatrixXd prediction = getMeasurementMatrix() * cur_states;\n\n    return std::make_pair(true, std::move(prediction));\n}\n\n\nstd::pair<bool, bfl::Data> LinearMeasurementModel::innovation(const bfl::Data& predicted_measurements, const bfl::Data& measurements) const\n{\n    MatrixXd innovation = -(any::any_cast<MatrixXd>(predicted_measurements).colwise() - any::any_cast<MatrixXd>(measurements).col(0));\n\n    return std::make_pair(true, std::move(innovation));\n}\n", "meta": {"hexsha": "6030feb10c304d98942b415a4ccd3ff01b119028", "size": 929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesFilters/src/LinearMeasurementModel.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/LinearMeasurementModel.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/LinearMeasurementModel.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": 30.9666666667, "max_line_length": 139, "alphanum_fraction": 0.7524219591, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.575921622845796}}
{"text": "#include <iostream>\n#include <cstdio>\n#include <ctime>\n\n#define EIGEN_NO_DEBUG // turn off assertions\n\n#include <Eigen/Dense>\n#include \"boost/program_options.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\nnamespace po = boost::program_options;\n\n// m: numRows, n: numCols\ninline double simpleDenseTest_Eigen(const int m, const int n, const int num_trials) {\n  MatrixXd A = MatrixXd::Random(m, n);\n  MatrixXd B = MatrixXd::Random(m, n);\n  MatrixXd C = MatrixXd::Random(m, n);\n  MatrixXd D = MatrixXd::Random(m, n);\n  MatrixXd E = MatrixXd::Random(m, n);\n  \n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    MatrixXd res = ((A + B).cwiseQuotient(C) - D).cwiseProduct(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_Eigen(const int m, const int n, const int k, const int num_trials) {\n\n  MatrixXd A = MatrixXd::Random(m, n);\n  MatrixXd C = MatrixXd::Random(n, k);\n  MatrixXd E = MatrixXd::Random(m, k);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    E.noalias() += A * C;\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 gemmDenseTest_Eigen(const int m, const int n, const int k, const int num_trials) {\n\n  MatrixXd A = MatrixXd::Random(m, n);\n  MatrixXd B = MatrixXd::Random(m, n);\n  MatrixXd C = MatrixXd::Random(n, k);\n  MatrixXd D = MatrixXd::Random(n, k);\n  MatrixXd E = MatrixXd::Random(m, k);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    E.noalias() += (A + B) * (C - D);\n\n  }\n  double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  return duration / num_trials;\n\n}\n\ninline double mulDenseTest_Eigen(const int a, const int b, const int c, const int d, const int num_trials) {\n\n  MatrixXd A = MatrixXd::Random(a, a);\n  MatrixXd B = MatrixXd::Random(a, b);\n  MatrixXd C = MatrixXd::Random(b, c);\n  MatrixXd D = MatrixXd::Random(c, d);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    MatrixXd res = A * B * C * D;\n\n  }\n  double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  return duration / num_trials;\n\n}\n\n// m: numRows of A, n: numCols of A, and numRows of B, k: numCols of B\ninline double denseVectorTest_Eigen(int l, int num_trials) {\n\n  VectorXd a = VectorXd::Random(l);\n  VectorXd b = VectorXd::Random(l);\n  VectorXd c = VectorXd::Random(l);\n  VectorXd d = VectorXd::Random(l);\n  VectorXd 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 runEigenTests(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 << \"Eigen Vectors Test:\\t\" << denseVectorTest_Eigen(l, num_trials) << endl;\n  if (!skip_simple)\n    cout << \"Eigen Simple Test:\\t\" << simpleDenseTest_Eigen(m, n, num_trials) << endl;\n  if (!skip_gemm) {\n    cout << \"Eigen gemmSanity Test:\\t\" << gemmDenseTest_Eigen(m, n, k, num_trials) << endl;\n    cout << \"Eigen gemm Test:\\t\" << gemmDenseTest_Eigen(m, n, k, num_trials) << endl;\n  }\n\n  if (!skip_mult)\n    cout << \"Eigen mulDense Test:\\t\" << mulDenseTest_Eigen(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    runEigenTests(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": "d44c9e513c2bb95e503b7551cc92747e9f4f403e", "size": 5480, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main/cpp/eigen.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/eigen.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/eigen.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.4942528736, "max_line_length": 108, "alphanum_fraction": 0.6226277372, "num_tokens": 1623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435188319626, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5759025415615163}}
{"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": "//  Copyright John Maddock 2009.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include \"required_defines.hpp\"\n\n#include \"performance_measure.hpp\"\n\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/array.hpp>\n\n#define T double\n#include \"../test/bessel_j_data.ipp\"\n#include \"../test/bessel_j_int_data.ipp\"\n#include \"../test/bessel_j_large_data.ipp\"\n#include \"../test/bessel_y01_data.ipp\"\n#include \"../test/bessel_yn_data.ipp\"\n#include \"../test/bessel_yv_data.ipp\"\n#include \"../test/bessel_k_int_data.ipp\"\n#include \"../test/bessel_k_data.ipp\"\n#include \"../test/bessel_i_int_data.ipp\"\n#include \"../test/bessel_i_data.ipp\"\n#include \"../test/sph_bessel_data.ipp\"\n#include \"../test/sph_neumann_data.ipp\"\n\n\ntemplate <std::size_t N>\ndouble bessel_evaluate2(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::cyl_bessel_j(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"cyl_bessel_j\")\n{\n   double result= bessel_evaluate2(bessel_j_data);\n   result += bessel_evaluate2(bessel_j_int_data);\n   result += bessel_evaluate2(bessel_j_large_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(bessel_j_data) \n      + sizeof(bessel_j_int_data) \n      + sizeof(bessel_j_large_data)) / sizeof(bessel_j_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble bessel_y_evaluate2(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::cyl_neumann(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"cyl_neumann\")\n{\n   double result= bessel_y_evaluate2(bessel_y01_data);\n   result += bessel_y_evaluate2(bessel_yn_data);\n   result += bessel_y_evaluate2(bessel_yv_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(bessel_y01_data) \n      + sizeof(bessel_yn_data) \n      + sizeof(bessel_yv_data)) / sizeof(bessel_j_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble bessel_i_evaluate(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::cyl_bessel_i(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"cyl_bessel_i\")\n{\n   double result= bessel_i_evaluate(bessel_i_int_data);\n   result += bessel_i_evaluate(bessel_i_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(bessel_i_data) \n      + sizeof(bessel_i_int_data)) / sizeof(bessel_i_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble bessel_k_evaluate(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::cyl_bessel_k(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"cyl_bessel_k\")\n{\n   double result= bessel_k_evaluate(bessel_k_data);\n   result += bessel_k_evaluate(bessel_k_int_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(bessel_k_data) \n      + sizeof(bessel_k_int_data)) / sizeof(bessel_k_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble bessel_sph_j_evaluate(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::sph_bessel(static_cast<unsigned>(data[i][0]), data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"sph_bessel\")\n{\n   double result= bessel_sph_j_evaluate(sph_bessel_data);\n\n   consume_result(result);\n   set_call_count(\n      sizeof(sph_bessel_data) / sizeof(sph_bessel_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble bessel_sph_y_evaluate(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::sph_neumann(static_cast<unsigned>(data[i][0]), data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"sph_neumann\")\n{\n   double result= bessel_sph_y_evaluate(sph_neumann_data);\n\n   consume_result(result);\n   set_call_count(\n      sizeof(sph_neumann_data) / sizeof(sph_neumann_data[0]));\n}\n\n#ifdef TEST_DCDFLIB\n\n#endif\n\n#ifdef TEST_CEPHES\n\nextern \"C\" double jv(double, double);\nextern \"C\" double yv(double, double);\nextern \"C\" double iv(double, double);\n\ntemplate <std::size_t N>\ndouble bessel_evaluate2_cephes(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += jv(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"cyl_bessel_j-cephes\")\n{\n   double result = bessel_evaluate2_cephes(bessel_j_data);\n   result += bessel_evaluate2_cephes(bessel_j_int_data);\n   result += bessel_evaluate2_cephes(bessel_j_large_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(bessel_j_data) \n      + sizeof(bessel_j_int_data) \n      + sizeof(bessel_j_large_data)) / sizeof(bessel_j_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble bessel_y_evaluate2_cephes(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += yv(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"cyl_neumann-cephes\")\n{\n   double result= bessel_y_evaluate2_cephes(bessel_y01_data);\n   result += bessel_y_evaluate2_cephes(bessel_yn_data);\n   result += bessel_y_evaluate2_cephes(bessel_yv_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(bessel_y01_data) \n      + sizeof(bessel_yn_data) \n      + sizeof(bessel_yv_data)) / sizeof(bessel_j_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble bessel_i_evaluate_cephes(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += iv(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"cyl_bessel_i-cephes\")\n{\n   double result= bessel_i_evaluate_cephes(bessel_i_int_data);\n   result += bessel_i_evaluate_cephes(bessel_i_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(bessel_i_data) \n      + sizeof(bessel_i_int_data)) / sizeof(bessel_i_data[0]));\n}\n\n#endif\n\n#ifdef TEST_GSL\n\n#include <gsl/gsl_sf_bessel.h>\n\ntemplate <std::size_t N>\ndouble bessel_evaluate2_gsl(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += gsl_sf_bessel_Jnu(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"cyl_bessel_j-gsl\")\n{\n   double result = bessel_evaluate2_gsl(bessel_j_data);\n   result += bessel_evaluate2_gsl(bessel_j_int_data);\n   result += bessel_evaluate2_gsl(bessel_j_large_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(bessel_j_data) \n      + sizeof(bessel_j_int_data) \n      + sizeof(bessel_j_large_data)) / sizeof(bessel_j_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble bessel_y_evaluate2_gsl(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += gsl_sf_bessel_Ynu(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"cyl_neumann-gsl\")\n{\n   double result= bessel_y_evaluate2_gsl(bessel_y01_data);\n   result += bessel_y_evaluate2_gsl(bessel_yn_data);\n   result += bessel_y_evaluate2_gsl(bessel_yv_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(bessel_y01_data) \n      + sizeof(bessel_yn_data) \n      + sizeof(bessel_yv_data)) / sizeof(bessel_j_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble bessel_i_evaluate_gsl(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += gsl_sf_bessel_Inu(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"cyl_bessel_i-gsl\")\n{\n   double result= bessel_i_evaluate_gsl(bessel_i_int_data);\n   result += bessel_i_evaluate_gsl(bessel_i_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(bessel_i_data) \n      + sizeof(bessel_i_int_data)) / sizeof(bessel_i_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble bessel_k_evaluate_gsl(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += gsl_sf_bessel_Knu(data[i][0], data[i][1]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(bessel_test, \"cyl_bessel_k-gsl\")\n{\n   double result= bessel_k_evaluate_gsl(bessel_k_data);\n   result += bessel_k_evaluate_gsl(bessel_k_int_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(bessel_k_data) \n      + sizeof(bessel_k_int_data)) / sizeof(bessel_k_data[0]));\n}\n\n#endif\n\n", "meta": {"hexsha": "5d2ebe7643fcdfaf64bee03d47d6a21caae5862e", "size": 8734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/performance/test_bessel.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/math/performance/test_bessel.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "boost/libs/math/performance/test_bessel.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 27.8152866242, "max_line_length": 88, "alphanum_fraction": 0.7049461873, "num_tokens": 2581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5758232807512021}}
{"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;    // \u786e\u5b9a\u7cfb\u6570\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); // \u8c03\u7528OpenCV \u7684 PnP \u6c42\u89e3\uff0c\u53ef\u9009\u62e9EPNP\uff0cDLS\u7b49\u65b9\u6cd5\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\u4e3a\u65cb\u8f6c\u5411\u91cf\u5f62\u5f0f\uff0c\u7528Rodrigues\u516c\u5f0f\u8f6c\u6362\u4e3a\u77e9\u9635\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\u4e3a\u65cb\u8f6c\u5411\u91cf\u5f62\u5f0f\uff0c\u7528Rodrigues\u516c\u5f0f\u8f6c\u6362\u4e3a\u77e9\u9635\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    // \u521d\u59cb\u5316g2o\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3> > Block;  // pose\u7ef4\u5ea6\u4e3a 6, landmark \u7ef4\u5ea6\u4e3a 3\n    Block::LinearSolverType *linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    Block *solver_ptr = new Block(linearSolver);     // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n    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": "/*\n * Copyright 2010,\n * Fran\u00e7ois Bleibel,\n * Olivier Stasse,\n *\n * CNRS/AIST\n *\n */\n\n#ifndef __SOT_MATRIX_SVD_H__\n#define __SOT_MATRIX_SVD_H__\n\n/* --- Matrix --- */\n#include <Eigen/SVD>\n#include <dynamic-graph/linear-algebra.h>\n\nnamespace dg = dynamicgraph;\n/* --------------------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\nnamespace Eigen {\n\nvoid pseudoInverse(dg::Matrix &_inputMatrix, dg::Matrix &_inverseMatrix,\n                   const double threshold = 1e-6);\n\nvoid dampedInverse(const JacobiSVD<dg::Matrix> &svd, dg::Matrix &_inverseMatrix,\n                   const double threshold = 1e-6);\n\nvoid dampedInverse(const dg::Matrix &_inputMatrix, dg::Matrix &_inverseMatrix,\n                   dg::Matrix &Uref, dg::Vector &Sref, dg::Matrix &Vref,\n                   const double threshold = 1e-6);\n\nvoid dampedInverse(const dg::Matrix &_inputMatrix, dg::Matrix &_inverseMatrix,\n                   const double threshold = 1e-6);\n\n} // namespace Eigen\n\n#endif /* #ifndef __SOT_MATRIX_SVD_H__ */\n", "meta": {"hexsha": "435edd24a89e339f8f24ac7c9ee2e1c4c1e0a036", "size": 1163, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/sot/core/matrix-svd.hh", "max_stars_repo_name": "florent-lamiraux/sot-core", "max_stars_repo_head_hexsha": "bf6998f1f76ad46c22aa1f350273fac484b3ae7d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sot/core/matrix-svd.hh", "max_issues_repo_name": "florent-lamiraux/sot-core", "max_issues_repo_head_hexsha": "bf6998f1f76ad46c22aa1f350273fac484b3ae7d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/sot/core/matrix-svd.hh", "max_forks_repo_name": "florent-lamiraux/sot-core", "max_forks_repo_head_hexsha": "bf6998f1f76ad46c22aa1f350273fac484b3ae7d", "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.8205128205, "max_line_length": 80, "alphanum_fraction": 0.5296646604, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.575748595939493}}
{"text": "/**TODO:  Add copyright*/\n\n#define BOOST_TEST_MODULE ModelInterpreterFile test suite \n#include <boost/test/included/unit_test.hpp>\n#include <EvoNet/io/ModelInterpreterFileDefaultDevice.h>\n#include <EvoNet/ml/ModelInterpreterDefaultDevice.h>\n\nusing namespace EvoNet;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(ModelInterpreterFile1)\n\nModel<float> makeModel1()\n{\n\t/**\n\t* Directed Acyclic Graph Toy Network Model\n\t*/\n\tNode<float> i1, i2, h1, h2, o1, o2, b1, b2;\n\tLink l1, l2, l3, l4, lb1, lb2, l5, l6, l7, l8, lb3, lb4;\n\tWeight<float> w1, w2, w3, w4, wb1, wb2, w5, w6, w7, w8, wb3, wb4;\n\tModel<float> model1;\n\n\t// Toy network: 1 hidden layer, fully connected, DAG\n\ti1 = Node<float>(\"0\", NodeType::input, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\ti2 = Node<float>(\"1\", NodeType::input, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\th1 = Node<float>(\"2\", NodeType::hidden, NodeStatus::deactivated, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\th2 = Node<float>(\"3\", NodeType::hidden, NodeStatus::deactivated, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\to1 = Node<float>(\"4\", NodeType::output, NodeStatus::deactivated, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\to2 = Node<float>(\"5\", NodeType::output, NodeStatus::deactivated, std::make_shared<ReLUOp<float>>(ReLUOp<float>()), std::make_shared<ReLUGradOp<float>>(ReLUGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\tb1 = Node<float>(\"6\", NodeType::bias, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\tb2 = Node<float>(\"7\", NodeType::bias, NodeStatus::activated, std::make_shared<LinearOp<float>>(LinearOp<float>()), std::make_shared<LinearGradOp<float>>(LinearGradOp<float>()), std::make_shared<SumOp<float>>(SumOp<float>()), std::make_shared<SumErrorOp<float>>(SumErrorOp<float>()), std::make_shared<SumWeightGradOp<float>>(SumWeightGradOp<float>()));\n\n\t// weights  \n\tstd::shared_ptr<WeightInitOp<float>> weight_init;\n\tstd::shared_ptr<SolverOp<float>> solver;\n\t// weight_init.reset(new RandWeightInitOp(1.0)); // No random init for testing\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw1 = Weight<float>(\"0\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw2 = Weight<float>(\"1\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw3 = Weight<float>(\"2\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw4 = Weight<float>(\"3\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\twb1 = Weight<float>(\"4\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\twb2 = Weight<float>(\"5\", weight_init, solver);\n\t// input layer + bias\n\tl1 = Link(\"0\", \"0\", \"2\", \"0\");\n\tl2 = Link(\"1\", \"0\", \"3\", \"1\");\n\tl3 = Link(\"2\", \"1\", \"2\", \"2\");\n\tl4 = Link(\"3\", \"1\", \"3\", \"3\");\n\tlb1 = Link(\"4\", \"6\", \"2\", \"4\");\n\tlb2 = Link(\"5\", \"6\", \"3\", \"5\");\n\t// weights\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw5 = Weight<float>(\"6\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw6 = Weight<float>(\"7\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw7 = Weight<float>(\"8\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\tw8 = Weight<float>(\"9\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\twb3 = Weight<float>(\"10\", weight_init, solver);\n\tweight_init = std::make_shared<ConstWeightInitOp<float>>(ConstWeightInitOp<float>(1.0));\n\tsolver = std::make_shared<SGDOp<float>>(SGDOp<float>(0.01, 0.9));\n\twb4 = Weight<float>(\"11\", weight_init, solver);\n\t// hidden layer + bias\n\tl5 = Link(\"6\", \"2\", \"4\", \"6\");\n\tl6 = Link(\"7\", \"2\", \"5\", \"7\");\n\tl7 = Link(\"8\", \"3\", \"4\", \"8\");\n\tl8 = Link(\"9\", \"3\", \"5\", \"9\");\n\tlb3 = Link(\"10\", \"7\", \"4\", \"10\");\n\tlb4 = Link(\"11\", \"7\", \"5\", \"11\");\n\tmodel1.setId(1);\n\tmodel1.setName(\"1\");\n\tmodel1.addNodes({ i1, i2, h1, h2, o1, o2, b1, b2 });\n\tmodel1.addWeights({ w1, w2, w3, w4, wb1, wb2, w5, w6, w7, w8, wb3, wb4 });\n\tmodel1.addLinks({ l1, l2, l3, l4, lb1, lb2, l5, l6, l7, l8, lb3, lb4 });\n  model1.setInputAndOutputNodes();\n\treturn model1;\n}\n\nBOOST_AUTO_TEST_CASE(constructor) \n{\n  ModelInterpreterFileDefaultDevice<float>* ptr = nullptr;\n\tModelInterpreterFileDefaultDevice<float>* nullPointer = nullptr;\n  ptr = new ModelInterpreterFileDefaultDevice<float>();\n  BOOST_CHECK_NE(ptr, nullPointer);\n}\n\nBOOST_AUTO_TEST_CASE(destructor) \n{\n\tModelInterpreterFileDefaultDevice<float>* ptr = nullptr;\n\tptr = new ModelInterpreterFileDefaultDevice<float>();\n  delete ptr;\n}\n\nModel<float> model1 = makeModel1();\nBOOST_AUTO_TEST_CASE(loadModelBinary1)\n{\n\tModelInterpreterFileDefaultDevice<float> data;\n\n\t// START: model_interpreter test taken from ModelinterpreterCpu_test\n\tModelInterpreterDefaultDevice<float> model_interpreter;\n\tconst int batch_size = 4;\n\tconst int memory_size = 1;\n\tconst bool train = true;\n\n\t// compile the graph into a set of operations and allocate all tensors\n\tmodel_interpreter.getForwardPropogationOperations(model1, batch_size, memory_size, train, false, true, true);\n\n\t// Store the model interpreter\n\tstd::string filename = \"ModelInterpreterFileTest.binary\";\n\tdata.storeModelInterpreterBinary(filename, model_interpreter);\n\n\t// Read in the test model_interpreter\n\tModelInterpreterDefaultDevice<float> model_interpreter_test;\n\tdata.loadModelInterpreterBinary(filename, model_interpreter_test);\n\n\tBOOST_CHECK(model_interpreter_test.getTensorOpsSteps() == model_interpreter.getTensorOpsSteps());\n\tBOOST_CHECK_EQUAL(model_interpreter_test.getModelResources().size(), model_interpreter.getModelResources().size());\n\t//BOOST_CHECK(model_interpreter_test.getModelResources() == model_interpreter.getModelResources());\n}\n\nModel<float> model2 = makeModel1();\nBOOST_AUTO_TEST_CASE(loadModelBinary2)\n{\n\tModelInterpreterFileDefaultDevice<float> data;\n\n\t// START: model_interpreter test taken from ModelinterpreterCpu_test\n\tModelInterpreterDefaultDevice<float> model_interpreter;\n\tconst int batch_size = 4;\n\tconst int memory_size = 1;\n\tconst bool train = true;\n\n\t// update the model solver\n\tstd::shared_ptr<SolverOp<float>> solver(new AdamOp<float>(0.001, 0.9, 0.999, 1e-8));\n\tfor (auto& weight_map : model2.getWeightsMap()) {\n\t\tif (weight_map.second->getSolverOpShared()->getName() == \"SGDOp\")\n\t\t\tweight_map.second->setSolverOp(solver);\n\t}\n\n\t// compile the graph into a set of operations and allocate all tensors\n\tmodel_interpreter.getForwardPropogationOperations(model2, batch_size, memory_size, train, false, true, true);\n\tmodel_interpreter.allocateModelErrorTensor(batch_size, memory_size, 0);\n\n\t// create the input\n\tconst std::vector<std::string> node_ids = { \"0\", \"1\" };\n\tEigen::Tensor<float, 3> input(batch_size, memory_size, (int)node_ids.size());\n\tinput.setValues({\n\t\t{{1, 5}},\n\t\t{{2, 6}},\n\t\t{{3, 7}},\n\t\t{{4, 8}} });\n\n\t// create the expected output\n\tstd::vector<std::string> output_nodes = { \"4\", \"5\" };\n\tEigen::Tensor<float, 2> expected(batch_size, (int)output_nodes.size());\n\texpected.setValues({ {0, 1}, {0, 1}, {0, 1}, {0, 1} });\n\tLossFunctionTensorOp<float, Eigen::DefaultDevice>* loss_function = new MSELossTensorOp<float, Eigen::DefaultDevice>();\n\tLossFunctionGradTensorOp<float, Eigen::DefaultDevice>* loss_function_grad = new MSELossGradTensorOp<float, Eigen::DefaultDevice>();\n\tconst int layer_id = model2.getNode(\"4\").getTensorIndex().first;\n\n\t// iterate until we find the optimal values\n\tconst int max_iter = 20;\n\tfor (int iter = 0; iter < max_iter; ++iter)\n\t{\n\t\t// assign the input data\n\t\tmodel_interpreter.mapValuesToLayers(model2, input, node_ids, \"output\");\n\t\tmodel_interpreter.initBiases(model2); // create the bias\t\n\n\t\tmodel_interpreter.executeForwardPropogationOperations(0); //FP\n\n\t\t// calculate the model error and node output error\n\t\tmodel_interpreter.executeModelErrorOperations(expected, layer_id, loss_function, loss_function_grad, 0);\n\t\tstd::cout << \"Error at iteration: \" << iter << \" is \" << model_interpreter.getModelError()->getError().sum() << std::endl;\n\n\t\tmodel_interpreter.executeBackwardPropogationOperations(0); // BP\n\t\tmodel_interpreter.executeWeightErrorOperations(); // Weight error\n\t\tmodel_interpreter.executeWeightUpdateOperations(0); // Weight update\n\n\t\t// reinitialize the model\n\t\tif (iter != max_iter - 1) {\n\t\t\tmodel_interpreter.reInitNodes();\n\t\t\tmodel_interpreter.reInitModelError();\n\t\t}\n\t}\n\tconst Eigen::Tensor<float, 0> total_error = model_interpreter.getModelError()->getError().sum();\n\tBOOST_CHECK(total_error(0) <= 757.0);\n\t// END: model_interpreter test taken from ModelinterpreterCpu_test\n\n\t// Store the model interpreter\n\tstd::string filename = \"ModelInterpreterFileTest.binary\";\n\tdata.storeModelInterpreterBinary(filename, model_interpreter);\n\n\t// Read in the test model_interpreter\n\tModelInterpreterDefaultDevice<float> model_interpreter_test;\n\tdata.loadModelInterpreterBinary(filename, model_interpreter_test);\n\n\t// Test for the expected model_interpreter operations\n\tmodel_interpreter.getModelResults(model2, true, true, true, true);\n\tmodel_interpreter.clear_cache();\n\n\t// Compile the graph into a set of operations and allocate all tensors\n\tmodel_interpreter_test.getForwardPropogationOperations(model2, batch_size, memory_size, train, false, true, true);\n\tmodel_interpreter_test.allocateModelErrorTensor(batch_size, memory_size, 0);\n\n\tBOOST_CHECK(model_interpreter_test == model_interpreter);  // Trivial comparison; instead we use the following from `ModelInterpreterCpu_test.cpp`\n\n\t// RE-START: model_interpreter test taken from ModelinterpreterCpu_test\n\t// iterate until we find the optimal values\n\tfor (int iter = 0; iter < max_iter; ++iter)\n\t{\n\t\t// assign the input data\n\t\tmodel_interpreter_test.mapValuesToLayers(model2, input, node_ids, \"output\");\n\t\tmodel_interpreter_test.initBiases(model2); // create the bias\t\n\n\t\tmodel_interpreter_test.executeForwardPropogationOperations(0); //FP\n\n\t\t// calculate the model error and node output error\n\t\tmodel_interpreter_test.executeModelErrorOperations(expected, layer_id, loss_function, loss_function_grad, 0);\n\t\tstd::cout << \"Error at iteration: \" << iter << \" is \" << model_interpreter_test.getModelError()->getError().sum() << std::endl;\n\n\t\tmodel_interpreter_test.executeBackwardPropogationOperations(0); // BP\n\t\tmodel_interpreter_test.executeWeightErrorOperations(); // Weight error\n\t\tmodel_interpreter_test.executeWeightUpdateOperations(0); // Weight update\n\n\t\t// reinitialize the model\n\t\tif (iter != max_iter - 1) {\n\t\t\tmodel_interpreter_test.reInitNodes();\n\t\t\tmodel_interpreter_test.reInitModelError();\n\t\t}\n\t}\n\n\tconst Eigen::Tensor<float, 0> total_error_test = model_interpreter_test.getModelError()->getError().sum();\n\tBOOST_CHECK(total_error_test(0) <= 757.0);\n\t// END RE-START: model_interpreter test taken from ModelinterpreterCpu_test\n}\n\nModel<float> model3 = makeModel1();\nBOOST_AUTO_TEST_CASE(loadModelCsv1)\n{\n  ModelInterpreterFileDefaultDevice<float> data;\n\n  // START: model_interpreter test taken from ModelinterpreterCpu_test\n  ModelInterpreterDefaultDevice<float> model_interpreter;\n  const int batch_size = 4;\n  const int memory_size = 1;\n  const bool train = true;\n\n  // compile the graph into a set of operations and allocate all tensors\n  model_interpreter.getForwardPropogationOperations(model3, batch_size, memory_size, train, false, true, true);\n\n  // Store the model interpreter\n  std::string filename = \"ModelInterpreterFileTest.csv\";\n  data.storeModelInterpreterCsv(filename, model_interpreter);\n\n  // NO TESTS\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "691894fb38299eff5a2c244078f7c2c7f6be53ab", "size": 14208, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/class_tests/evonet/source/ModelInterpreterFile_test.cpp", "max_stars_repo_name": "dmccloskey/smartPeak_cpp", "max_stars_repo_head_hexsha": "47a19a804b65daef712418b4e278704b340d20b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/class_tests/evonet/source/ModelInterpreterFile_test.cpp", "max_issues_repo_name": "dmccloskey/smartPeak_cpp", "max_issues_repo_head_hexsha": "47a19a804b65daef712418b4e278704b340d20b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-01-11T20:39:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-11T21:02:31.000Z", "max_forks_repo_path": "src/tests/class_tests/evonet/source/ModelInterpreterFile_test.cpp", "max_forks_repo_name": "dmccloskey/smartPeak_cpp", "max_forks_repo_head_hexsha": "47a19a804b65daef712418b4e278704b340d20b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.6654545455, "max_line_length": 353, "alphanum_fraction": 0.7412021396, "num_tokens": 3948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.57574857994906}}
{"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": "//\n// Created by Hamza El-Kebir on 4/17/21.\n//\n\n#include \"Lodestar/analysis/LinearSystemInverse.hpp\"\n#include \"Lodestar/systems/StateSpace.hpp\"\n#include <Eigen/Dense>\n\nls::systems::StateSpace<> linearSystemInverseExample()\n{\n    Eigen::MatrixXd A(3, 3), B(3, 2), C(2, 3), D(2, 2);\n    A.block(0, 0, 3, 3) << 1, 2, 0, 4, -1, 0, 0, 0, 1;\n    B.block(0, 0, 3, 2) << 1, 0, 0, 1, 1, 0;\n    C.block(0, 0, 2, 3) << 0, 1, -1, 0, 0, 1;\n    D.block(0, 0, 2, 2) << 4, 0, 0, 1;\n\n    ls::systems::StateSpace<> lti = ls::systems::StateSpace<>(A, B, C, D);\n    return lti;\n//    ls::systems::StateSpace<> ilti = ls::analysis::LinearSystemInverse::inverse(lti);\n//\n//    return ilti;\n}\n", "meta": {"hexsha": "aad52e638aebf976b6b83bd423711d96b6b8ee83", "size": 670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/analysis/LinearSystemInverse_test.cpp", "max_stars_repo_name": "helkebir/Lodestar", "max_stars_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T14:08:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T22:15:31.000Z", "max_issues_repo_path": "tests/analysis/LinearSystemInverse_test.cpp", "max_issues_repo_name": "helkebir/Lodestar", "max_issues_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T15:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T17:43:20.000Z", "max_forks_repo_path": "tests/analysis/LinearSystemInverse_test.cpp", "max_forks_repo_name": "helkebir/Lodestar", "max_forks_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T03:15:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T03:15:23.000Z", "avg_line_length": 29.1304347826, "max_line_length": 87, "alphanum_fraction": 0.576119403, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5757363626136812}}
{"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 = 0, ans = 0; cin >> a;\n    while(a > 1) {\n        a /= 2, b++;\n    }\n    for (int i = 0; i <= b; i++) ans += (cpp_int)pow(2, i);\n    cout << ans << endl;\n}\n", "meta": {"hexsha": "57c4d6d7897dd0ddc46577a6d1e63c564eee45b9", "size": 367, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc153/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/abc153/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/abc153/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": 22.9375, "max_line_length": 59, "alphanum_fraction": 0.583106267, "num_tokens": 113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.575729251710607}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n#include <Eigen/StdVector>\n\nconst float MTR_PI = 3.1415926535f;\n\ntypedef double scalar;\ntypedef unsigned long long uint64;\ntypedef unsigned char uchar;\n\ntypedef Eigen::Matrix<scalar, 2, 1> vec2s;\ntypedef Eigen::Matrix<float, 2, 1> vec2f;\ntypedef Eigen::Matrix<int, 2, 1> vec2i;\ntypedef Eigen::Matrix<scalar, 3, 1> vec3s;\ntypedef Eigen::Matrix<float, 3, 1> vec3f;\ntypedef Eigen::Matrix<int, 3, 1> vec3i;\ntypedef Eigen::Matrix<scalar, 4, 1> vec4s;\ntypedef Eigen::Matrix<float, 4, 1> vec4f;\ntypedef Eigen::Matrix<int, 4, 1> vec4i;\ntypedef Eigen::Matrix<float, Eigen::Dynamic, 1> vecNf;\n\ntypedef Eigen::Matrix<scalar, 4, 4> mat4s;\ntypedef Eigen::Matrix<float, 4, 4> mat4f;\ntypedef Eigen::Matrix<int, 4, 4> mat4i;\n\nfloat clamp(float min, float max, float a);\n\nfloat to_degrees(float radian);\nfloat to_radians(float degree);\n\nmat4f perspective(float fovy, float aspect, float near, float far);\nmat4f ortho(float left, float right, float bottom, float top, float near,\n            float far);\nmat4f look_at(const vec3f &eye, const vec3f &center, const vec3f &up);\n\nmat4f translate_mat(float offset_x, float offset_y, float offset_z);\nmat4f rotate_mat(const vec3f &pivot, float angle);\nmat4f scale_mat(float s_x, float s_y, float s_z);\n\nvec3f barycentric2D(float x, float y, vec4f *v);\n", "meta": {"hexsha": "8da1a584a81397aeae687ecf3883ab632dea05a6", "size": 1387, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/MTR/math_defs.hpp", "max_stars_repo_name": "UnderSilence/MetaRay", "max_stars_repo_head_hexsha": "e82c7bb890912e1b61a0aef051309bed89b7b266", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MTR/math_defs.hpp", "max_issues_repo_name": "UnderSilence/MetaRay", "max_issues_repo_head_hexsha": "e82c7bb890912e1b61a0aef051309bed89b7b266", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MTR/math_defs.hpp", "max_forks_repo_name": "UnderSilence/MetaRay", "max_forks_repo_head_hexsha": "e82c7bb890912e1b61a0aef051309bed89b7b266", "max_forks_repo_licenses": ["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.8222222222, "max_line_length": 73, "alphanum_fraction": 0.7390050469, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5757292413447093}}
{"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": "// Driver program for solution to Advent of Code, Day 22\n// Jeff Trull <edaskel@att.net>\n\n#include <iostream>\n#include <fstream>\n#include <regex>\n#include <algorithm>\n\n#include <boost/coroutine2/all.hpp>\n#include <boost/graph/astar_search.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/properties.hpp>\n\n#include \"graph.h\"\n\nstruct goal_reached {\n    server_state_t state;\n};\n\n// specialize an astar visitor to detect when we've reached our goal\nstruct goal_state_finder : public boost::default_astar_visitor {\n\n    void examine_vertex( server_state_t state, move_graph_t const& g) {\n        if ((g.servers()[state.data_offset()].x == 0) &&\n            (g.servers()[state.data_offset()].y == 0)) {\n            throw goal_reached{state};\n        }\n    }\n};\n\n// a heuristic to guide the A* search\nstruct server_move_heuristic_t {\n    server_move_heuristic_t(std::vector<server_t> const& servers) : servers_(servers) {}\n\n    using vertex_t = move_graph_t::vertex_t;\n\n    int operator()(const vertex_t& v) const {\n\n        // Heuristic plan:\n        // We need enough steps to move the original data to the origin\n        // That ends up being about 5 times the Manhattan distance due to the need to move\n        // the \"blank tile\" (server with sufficient capacity) back into place between the\n        // target data and the origin each time.\n        // In addition, we need to move the \"blank tile\" into position in the first place.\n\n        // Manhattan distance to goal\n        // we must make at least this many moves to get the original data home\n        server_t current_server = servers_[v.data_offset()];\n        int mdist = current_server.x + current_server.y;\n\n        // if mdist is 0, we are at the target, so simply return 0\n        if (mdist == 0) {\n            return 0;\n        }\n\n        // Finding the distance to the \"blank tile\"\n        // First, find the nearest (to the origin) server of sufficient reserve capacity\n        // to hold the target data\n\n        std::vector<server_t> eligible_servers;\n        for (size_t i = 0; i < servers_.size(); ++i) {\n            if ((servers_[i].capacity - v.usage(i)) >= v.usage(v.data_offset())) {\n                eligible_servers.push_back(servers_[i]);\n            }\n        }\n        // take the one with the minimum Manhattan distance to the server with our data\n        auto min_it = min_element(eligible_servers.begin(), eligible_servers.end(),\n                                  [&current_server](server_t const& a, server_t const& b) {\n                                      return ((abs(current_server.x - a.x) + abs(current_server.y - a.y)) <\n                                              (abs(current_server.x - b.x) + abs(current_server.y - b.y)));\n                                  });\n        assert(min_it != eligible_servers.end());   // insoluble!\n\n        // calculate distance to point above or to left of target data, whichever is shorter\n        int hole_dist = std::numeric_limits<int>::max();\n        if (current_server.y > 0) {\n            // distance to point above target\n            hole_dist = abs((current_server.y - 1) - min_it->y) + abs(current_server.x - min_it->x);\n        }\n        if (current_server.x > 0) {\n            // distance to point left of target\n            hole_dist = std::min(hole_dist,\n                                 abs((current_server.x - 1) - min_it->x) + abs(current_server.y - min_it->y));\n        }\n\n        // each move of the target data requires 5 moves overall, except for the last one\n        return (5*(mdist-1)+ 1) + hole_dist;\n    }\n\nprivate:\n\n    std::vector<server_t> const & servers_;\n\n};\n\nint main(int argc, char **argv) {\n    using namespace std;\n\n    if (argc != 2) {\n        cerr << \"usage: day22 input.txt\\n\";\n        return 1;\n    }\n\n    ifstream input(argv[1]);\n    if (!input.is_open()) {\n        cerr << \"error opening \" << argv[1] << \"\\n\";\n        return 1;\n    }\n\n    regex df_re(R\"(^/dev/grid/node-x(\\d+)-y(\\d+)\\s+(\\d+)T\\s+(\\d+)T\\s.*)\");\n    vector<server_t> servers;\n    using capacity_t = server_t::capacity_t;\n    std::vector<capacity_t> usages;\n    while (!input.eof()) {\n        string instr;\n        getline(input, instr);\n        match_results<string::iterator> matches;\n        if (regex_match(instr.begin(), instr.end(), matches, df_re)) {\n            // collect info on this server\n            int capacity = stoi(matches.str(3));\n            assert(capacity <= std::numeric_limits<capacity_t>::max());\n            servers.push_back({\n                    stoi(matches.str(1)),\n                    stoi(matches.str(2)),\n                    static_cast<capacity_t>(capacity)});\n            int usage = stoi(matches.str(4));\n            assert(usage <= std::numeric_limits<capacity_t>::max());\n            usages.push_back(usage);\n        }        \n    }        \n    move_graph_t move_graph(servers);\n\n    server_state_t   initial_state(move_graph.ur_corner(),\n                                   usages.begin(), usages.end());\n\n    // now see how many viable pairs there are\n    // create a generator from the pair calculation:\n\n    using namespace boost::coroutines2;\n    using viable_pair_coro_t = boost::coroutines2::coroutine<std::pair<int, int>>;\n    auto viable_pair_generator =\n        [&](viable_pair_coro_t::push_type & sink) {\n        // faster way is to sort by capacity but this is good enough for now\n        for (size_t i = 0; i < servers.size(); ++i) {\n            for (size_t j = 0; j < servers.size(); ++j) {\n                if (initial_state.usage(i) == 0) {\n                    continue;\n                }\n\n                if (i == j) {\n                    continue;\n                }\n\n                if (initial_state.usage(i) <= (servers[j].capacity - initial_state.usage(j))) {\n                    // room to move there, if there is a path\n                    sink(make_pair(i, j));\n                }\n            }\n        }};\n\n    // create a sequence from the generator\n    viable_pair_coro_t::pull_type viable_pairs(viable_pair_generator);\n\n    // count pairs in sequence\n    size_t viable_pair_count = 0;\n    for (auto const& v : viable_pairs) {\n        (void)v;\n        ++viable_pair_count;\n    }\n\n    cout << viable_pair_count << \" viable pairs\\n\";\n\n    // next, find a sequence of moves of data that will result in the data in the\n    // upper right being in the upper left\n\n    // requirements for A* search\n    using vertex_t = move_graph_t::vertex_t;\n    map<vertex_t, size_t> vertex_index_map;\n    map<vertex_t, size_t> rank_map;\n    map<vertex_t, boost::default_color_type> color_map;\n    map<vertex_t, vertex_t> predecessor_map;  // results (path) storage\n    // the distance map needs to default to a large number instead of 0\n    // because initially all vertices have unknown paths to them\n    map<vertex_t, size_t> distance_map;\n    auto distance_lookup =\n        [&distance_map](vertex_t const& v) -> size_t& {\n        if (distance_map.find(v) == distance_map.end()) {\n            distance_map[v] = numeric_limits<size_t>::max();\n        }\n        return distance_map[v];\n    };\n    auto distance_pmap =\n        boost::make_function_property_map<vertex_t, size_t&, decltype(distance_lookup)>(\n            distance_lookup);\n\n    // set up initial state\n    distance_map[initial_state] = 0;\n    predecessor_map[initial_state] = initial_state;\n\n    using namespace boost;\n    try {\n        // no_init is the appropriate variant for implicit graphs like ours\n        astar_search_no_init(\n            move_graph,\n            initial_state,\n            server_move_heuristic_t(servers),\n            // named params\n            weight_map(make_static_property_map<vertex_t, size_t>(1)).\n            vertex_index_map(associative_property_map<map<vertex_t, size_t>>(vertex_index_map)).\n            rank_map(associative_property_map<map<vertex_t, size_t>>(rank_map)).\n            distance_map(distance_pmap).\n            color_map(associative_property_map<map<vertex_t, default_color_type>>(color_map)).\n            visitor(goal_state_finder()).\n            predecessor_map(associative_property_map<map<vertex_t, vertex_t>>(predecessor_map))\n            );\n    } catch (goal_reached const& e) {\n        // reverse path for display\n        vector<server_state_t> soln_path;\n        auto next_state = e.state;\n        do {\n            soln_path.push_back(next_state);\n            next_state = predecessor_map[next_state];\n        } while (!(soln_path.back() == next_state));\n        reverse(soln_path.begin(), soln_path.end());\n\n        // describe the path\n        cout << \"solution: \" << (soln_path.size() - 1) << \" steps to goal state:\\n\";\n        copy(soln_path.begin(), soln_path.end(),\n                  ostream_iterator<server_state_t>(cout, \"\\n\"));\n\n        return 0;\n    }\n    cerr << \"could not find solution\\n\";\n    return 1;\n}\n", "meta": {"hexsha": "21400fb47c7c42723ace5447ae8642293e1b32a0", "size": 8840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "22/main.cpp", "max_stars_repo_name": "jefftrull/advent_of_code", "max_stars_repo_head_hexsha": "55a94a33d68dd27effead7a7f89ce8b8fbec19ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "22/main.cpp", "max_issues_repo_name": "jefftrull/advent_of_code", "max_issues_repo_head_hexsha": "55a94a33d68dd27effead7a7f89ce8b8fbec19ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "22/main.cpp", "max_forks_repo_name": "jefftrull/advent_of_code", "max_forks_repo_head_hexsha": "55a94a33d68dd27effead7a7f89ce8b8fbec19ab", "max_forks_repo_licenses": ["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.4576271186, "max_line_length": 110, "alphanum_fraction": 0.5952488688, "num_tokens": 2043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5757195554698192}}
{"text": "#include <boost/numeric/odeint/stepper/runge_kutta_fehlberg78.hpp>\n", "meta": {"hexsha": "1ba7c45b8e87640f7c149c551fa938568edb0f1e", "size": 67, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta_fehlberg78.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta_fehlberg78.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_runge_kutta_fehlberg78.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 33.5, "max_line_length": 66, "alphanum_fraction": 0.8507462687, "num_tokens": 22, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5757195508723344}}
{"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 John Maddock 2006.\n// Copyright Paul A. Bristow 2007, 2009\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/math/tools/stats.hpp>\n#include <boost/math/tools/test.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/array.hpp>\n#include \"functor.hpp\"\n\n#include \"handle_test_result.hpp\"\n#include \"table_type.hpp\"\n\n#include <boost/math/special_functions/hypergeometric_1F0.hpp>\n\n#ifndef SC_\n#define SC_(x) static_cast<typename table_type<T>::type>(BOOST_JOIN(x, L))\n#endif\n\n\ntemplate <class T>\nvoid test_spots(T)\n{\n   using std::pow;\n   //\n   // basic sanity checks, tolerance is 10 epsilon expressed as a percentage:\n   //\n   T tolerance = boost::math::tools::epsilon<T>() * 1000;\n\n   BOOST_CHECK_CLOSE(boost::math::hypergeometric_1F0(T(-3), T(2)), T(-1), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::hypergeometric_1F0(T(-3), T(4)), T(-27), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::hypergeometric_1F0(T(-3), T(0.5)), T(0.125), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::hypergeometric_1F0(T(3), T(0.5)), T(8), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::hypergeometric_1F0(T(3), T(2)), T(-1), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::hypergeometric_1F0(T(3), T(4)), T(T(-1) / 27), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::hypergeometric_1F0(T(3), T(-0.5)), pow(T(1.5), -3), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::hypergeometric_1F0(T(3), T(-2)), T(1 / T(27)), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::hypergeometric_1F0(T(3), T(-4)), T(T(1) / 125), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::hypergeometric_1F0(T(-3), T(-0.5)), pow(T(1.5), 3), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::hypergeometric_1F0(T(-3), T(-2)), T(27), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::hypergeometric_1F0(T(-3), T(-4)), T(125), tolerance);\n\n   BOOST_CHECK_THROW(boost::math::hypergeometric_1F0(T(3), T(1)), std::domain_error);\n   BOOST_CHECK_THROW(boost::math::hypergeometric_1F0(T(-3), T(1)), std::domain_error);\n   BOOST_CHECK_THROW(boost::math::hypergeometric_1F0(T(3.25), T(1)), std::domain_error);\n   BOOST_CHECK_THROW(boost::math::hypergeometric_1F0(T(-3.25), T(1)), std::domain_error);\n   BOOST_CHECK_THROW(boost::math::hypergeometric_1F0(T(3.25), T(2)), std::domain_error);\n   BOOST_CHECK_THROW(boost::math::hypergeometric_1F0(T(-3.25), T(2)), std::domain_error);\n}\n\n", "meta": {"hexsha": "9c2e996928b65472da5402a174ac2895015a0cb2", "size": 2811, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/test_1F0.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": "3rdparty/boost_1_73_0/libs/math/test/test_1F0.hpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/test/test_1F0.hpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 46.0819672131, "max_line_length": 97, "alphanum_fraction": 0.7235859125, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5757195453091749}}
{"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": "#include <boost/test/unit_test.hpp>\n\n\n#include \"geometry.h\"\n#include \"logs.h\"\n#include \"route.h\"\n\nusing namespace GPS;\n\nBOOST_AUTO_TEST_SUITE( Route_maxGradient_N0697611 )\n\nconst bool isFileName = true;\n\n\nBOOST_AUTO_TEST_CASE( elev_zero_throughout )//checks that the output is 0 if all elevations are 0\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"ABCD.gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.maxGradient(), 0 );\n}\n\nBOOST_AUTO_TEST_CASE( One_Point )//checks that the output is 0 when there is only 1 position\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"N0697611_M_OnePoint.gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.maxGradient(), 0 );\n}\n\n\nBOOST_AUTO_TEST_CASE(  typical_flat)//Checks that a flat route still returns 0 at an elevation other than 0\n{\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_ACE_CliftonCampus.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), 0,0.15) ;\n\n}\n\n\nBOOST_AUTO_TEST_CASE( typical_uphill)//Checks that a correct uphill gradient is calculated\n{\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_CHM_CliftonCampus.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(100,1000)),0.15) ;\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE(  typical_downhill)//Checks that a correct downhill gradient is calculated\n{\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_MRW_CliftonCampus.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(-100,1000)),0.15) ;\n\n}\n\nBOOST_AUTO_TEST_CASE( typical_uturn)//Checks that if two gradients of equal magnitude, but one positive and one negative, the positive one is the one returned\n{\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_JIGQST_CliftonCampus.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(100,1000)),0.15) ;\n\n}\n\n\n//\nBOOST_AUTO_TEST_CASE( Flat_near_equator)//Checks that 0 is returned for a flat route\n{                                         //this test is repeated at the equator\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_ACE_Pontianak.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), 0,0.15) ;\n\n}\n\nBOOST_AUTO_TEST_CASE( Equatorial_uphill)//Checks that a correct uphill gradient is calculated\n{                                         //this test is repeated at the equator\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_CHM_Pontianak.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(100,1000)),0.15) ;\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE( Equatorial_downhill)//Checks that a correct downhill gradient is calculated\n{                                         //this test is repeated at the equator\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_MRW_Pontianak.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(-100,1000)),0.15) ;\n\n}\n\nBOOST_AUTO_TEST_CASE( Equatorial_uturn)//Checks that if two gradients of equal magnitude, but one positive and one negative, the positive one is the one returned\n{                                       //this test repeats this at the equator\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_JIGQST_Pontianak.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(100,1000)),0.15) ;\n\n}\n\n\n\n//\n\n\nBOOST_AUTO_TEST_CASE( EquatorialMeridian_uturn)//Checks that if two gradients of equal magnitude, but one positive and one negative, the positive one is the one returned\n{                                               //This test repeats this at the equatorial meridian\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_JIGQST_EquatorialMeridian.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(100,1000)),0.15) ;\n\n}\n\n//\n\nBOOST_AUTO_TEST_CASE( EquatorialAntiMeridian_uturn)//Checks that if two gradients of equal magnitude, but one positive and one negative, the positive one is the one returned\n{                                                   //this test repeats this at the equatorial anti meridian\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_JIGQST_EquatorialAntiMeridian.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(100,1000)),0.15) ;\n\n}\n\n\n\n//\n\nBOOST_AUTO_TEST_CASE( Northpole_flat)//Tests a flat route near the north pole\n{\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_ACE_NorthPole.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), 0,0.15) ;\n\n}\nBOOST_AUTO_TEST_CASE( NorthPole_uphill)//Checks the gradient is accurate when going uphill near the northpole\n{\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_CHM_NorthPole.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(100,1000)),0.15) ;\n\n}\n\n\n\nBOOST_AUTO_TEST_CASE( NorthPole_downhill)//Checks the gradient is accurate when going downhill near the northpole\n{\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_MRW_NorthPole.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(-100,1000)),0.15) ;\n\n}\n\n\nBOOST_AUTO_TEST_CASE( Flat_then_up) //checks that the correct gradient is returned when choosing between 0 and a positive gradient\n{\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_VWXS_FlatThenUp.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(100,1000)),0.15) ;\n\n}\n\nBOOST_AUTO_TEST_CASE( Flat_then_down)//checks that the correct gradient is returned when choosing between 0 and a negative gradient\n{\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_GHID_FlatThenDown.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), 0,0.15) ;\n\n}\n\nBOOST_AUTO_TEST_CASE( Steep_up) //checks that an extreme positive gradient is returned correctly\n{\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_LM_Steepup.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(10000000,100)),0.15) ;\n\n}\n\n\nBOOST_AUTO_TEST_CASE( Steep_down)//checks that an extreme negative gradient is returned correctly\n{\nRoute route = Route(LogFiles::GPXRoutesDir + \"N0697611_MN_Steepdown.gpx\", isFileName);\n\nBOOST_CHECK_CLOSE(route.maxGradient(), radToDeg(atan2(-10000000,100)),0.15) ;\n\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "adb3b7d8b3b5a64c830f14f592ca1be878afab20", "size": 6064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpx-tests/maxGradient-N0697611.cpp", "max_stars_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_stars_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gpx-tests/maxGradient-N0697611.cpp", "max_issues_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_issues_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gpx-tests/maxGradient-N0697611.cpp", "max_forks_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_forks_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2553191489, "max_line_length": 173, "alphanum_fraction": 0.7490105541, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5757195351485299}}
{"text": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <utility> // std::pair\n#include <algorithm> // std::max_element()\n#include <string> // std::to_string()\n\n#include <armadillo>\n\n#include \"AudioFFT/AudioFFT.h\"\n\nusing std::chrono::high_resolution_clock;\nusing std::chrono::duration;\nusing AudioVec = std::vector<float>;\nusing audiofft::AudioFFT;\nusing FftwData = std::tuple<AudioFFT& // fft class\n                           ,AudioVec& // input vector\n\t\t\t\t\t\t   ,AudioVec& // real vector\n\t\t\t\t\t\t   ,AudioVec& // imag vector\n\t\t\t\t\t\t   ,AudioVec&>; // output vector\n\nnamespace {\n\tuint32_t num = 1;\n\tuint32_t fft_size = 48000;\n\tuint32_t conv_ir_size = 72000;\n\tuint32_t conv_sig_size = 5760000;\n}\n\nstd::pair<duration<double>, arma::fvec> Convolution(arma::fvec sig, arma::fvec ir) {\n\tsize_t size = (::conv_sig_size+::conv_ir_size-1);\n\tir = arma::flipud(ir);\n\tarma::fvec sig_new = arma::zeros<arma::fvec>(::conv_sig_size + 2*(::conv_ir_size-1));\n\tsig_new.subvec(::conv_ir_size - 1, ::conv_sig_size + ::conv_ir_size -2) = sig;\n\tarma::fvec output (::conv_sig_size + ::conv_ir_size - 1, arma::fill::zeros);\n\n\tauto begin = high_resolution_clock::now();\n\tfor (uint32_t cnt=0;cnt<::num;++cnt) {\n\t\tfor (uint32_t sample_cnt=0;sample_cnt<size;++sample_cnt) {\n\t\t\tfor (uint32_t ir_cnt=0;ir_cnt<::conv_ir_size;++ir_cnt) {\n\t\t\t\toutput[sample_cnt] += sig_new[sample_cnt+ir_cnt] * ir[ir_cnt];\n\t\t\t}\n\t\t}\n\t}\n\tAudioVec output_copy = arma::conv_to<AudioVec>::from(output);\n\tauto end = high_resolution_clock::now();\n\n\treturn std::make_pair(end - begin, output);\n}\n\nstd::pair<duration<double>, arma::fvec> ArmadilloConv(arma::fvec sig, arma::fvec ir) {\n\tarma::fvec output;\n\n\tauto begin = high_resolution_clock::now();\n\tfor (uint32_t cnt=0;cnt<::num;++cnt) {\n\t\toutput = arma::conv(sig, ir);\n\t}\n\tAudioVec output_copy = arma::conv_to<AudioVec>::from(output);\n\tauto end = high_resolution_clock::now();\n\n\treturn std::make_pair(end - begin, output);\n}\n\nduration<double> FftwConv(FftwData sig, FftwData ir) {\n\tauto sig_in = std::get<1>(sig);\n\tauto sig_re = std::get<2>(sig);\n\tauto sig_im = std::get<3>(sig);\n\tauto ir_in = std::get<1>(ir);\n\tauto ir_re = std::get<2>(ir);\n\tauto ir_im = std::get<3>(ir);\n\tAudioVec re (sig_re.size());\n\tAudioVec im (sig_re.size());\n\n\tauto begin = high_resolution_clock::now();\n\tstd::get<0>(sig).fft(sig_in.data(), sig_re.data(), sig_im.data());\n\tstd::get<0>(ir).fft(ir_in.data(), ir_re.data(), ir_im.data());\n\tfor (size_t cnt=0;cnt<sig_re.size();++cnt) {\n\t\tre[cnt] = sig_re[cnt]*ir_re[cnt] - sig_im[cnt]*ir_im[cnt];\n\t\tim[cnt] = sig_re[cnt]*ir_im[cnt] + sig_im[cnt]*ir_re[cnt];\n\t}\n\tstd::get<0>(sig).ifft(std::get<4>(sig).data(), re.data(), im.data());\n\tauto end = high_resolution_clock::now();\n\n\treturn end - begin;\n}\n\nstd::pair<duration<double>, arma::fvec> ArmadilloFftConv(arma::fvec sig, arma::fvec ir) {\n\tarma::cx_fvec output;\n\tsize_t size = sig.size() + ir.size() - 1;\n\n\tauto begin = high_resolution_clock::now();\n\tfor (uint32_t cnt=0;cnt<::num;++cnt) {\n\t\toutput = arma::ifft(arma::fft(sig, size) % arma::fft(ir, size));\n\t}\n\tAudioVec output_copy = arma::conv_to<AudioVec>::from(arma::real(output));\n\tauto end = high_resolution_clock::now();\n\n\treturn std::make_pair(end - begin, arma::real(output));\n}\n\nstd::pair<duration<double>, arma::fvec> ArmadilloFftPow2Conv(arma::fvec sig, arma::fvec ir) {\n\tuint32_t size = pow(2,ceil(log2(::conv_sig_size + ::conv_ir_size - 1)));\n\tarma::cx_fvec output;\n\n\tauto begin = high_resolution_clock::now();\n\tfor (uint32_t cnt=0;cnt<::num;++cnt) {\n\t\toutput = arma::ifft(arma::fft(sig,size) % arma::fft(ir,size));\n\t}\n\tAudioVec output_copy = arma::conv_to<AudioVec>::from(arma::real(output));\n\tauto end = high_resolution_clock::now();\n\n\treturn std::make_pair(end - begin, arma::real(output.subvec(0, ::conv_sig_size + ::conv_ir_size - 2)));\n}\n\nstd::pair<duration<double>,arma::fvec> ArmadilloFft(arma::fvec input) {\n\tarma::cx_fvec output_fd;\n\tarma::cx_fvec output_td;\n\n\tauto begin = high_resolution_clock::now();\n\tfor (uint32_t cnt=0;cnt<::num;++cnt) {\n\t\toutput_fd = arma::fft(input);\n\t\toutput_td = arma::ifft(output_fd);\n\n\t}\n\tAudioVec output_copy = arma::conv_to<AudioVec>::from(arma::real(output_td));\n\tauto end = high_resolution_clock::now();\n\n\treturn std::make_pair(end - begin,arma::real(output_td));\n}\n\nint main(int argc, char* argv[]) {\n\n\tstd::cout << \"generating input signals\" << std::endl;\n\tarma::fvec sig {arma::randn<arma::fvec>(::conv_sig_size)};\n\tarma::fvec ir {arma::randn<arma::fvec>(::conv_ir_size)};\n\tsize_t out_size = ::conv_sig_size + ::conv_ir_size - 1;\n\n\tstd::cout << \"initializing FFTW\" << std::flush;\n\tsize_t fft_size (pow(2,ceil(log2(out_size))));\n\tAudioVec sig_vec  (fft_size, 0);\n\tstd::copy_n(sig.begin(), ::conv_sig_size, sig_vec.begin());\n\tAudioVec ir_vec (fft_size, 0);\n\tstd::copy_n(ir.begin(), ::conv_ir_size, ir_vec.begin());\n\tAudioVec sig_re(AudioFFT::ComplexSize(fft_size)); \n\tAudioVec ir_re(AudioFFT::ComplexSize(fft_size));\n\tAudioVec sig_im(AudioFFT::ComplexSize(fft_size)); \n\tAudioVec ir_im(AudioFFT::ComplexSize(fft_size)); \n\tAudioVec output(fft_size);\n\tAudioFFT fft_sig;\n\tauto begin = high_resolution_clock::now();\n\tfft_sig.init(fft_size);\n\tauto end = high_resolution_clock::now();\n\tstd::cout << \"\\n\\tduration: \" << (std::chrono::duration_cast<duration<double>>(end - begin)).count() << std::endl;\n\tAudioFFT fft_ir;\n\tfft_ir.init(fft_size);\n\tFftwData sig_data = std::forward_as_tuple(fft_sig, sig_vec, sig_re, sig_im, output);\n\tFftwData ir_data = std::forward_as_tuple(fft_ir, ir_vec, ir_re, ir_im, output);\n\n\tstd::cout << \"Armadillo FFT: \" << std::flush;\n\tauto result_arma_fft = ArmadilloFft(sig);\n\tstd::cout << \"\\n\\tduration: \" << result_arma_fft.first.count() << std::endl;\n\n\t// normal convolution, this is our reference output\n\tstd::cout << \"convolution: \" << std::flush;\n\tauto result_conv = Convolution(sig, ir);\n\tstd::cout << \"\\n\\tduration: \" << result_conv.first.count() << std::endl;\n\n\tstd::cout << \"Armadillo FFT-Pow2-convolution: \" << std::flush;\n\tauto result_arma_fft_pow2_conv = ArmadilloFftPow2Conv(sig, ir);\n\tstd::cout << \"\\n\\tduration: \" << result_arma_fft_pow2_conv.first.count();\n\tstd::cout << \"\\n\\tmaximum difference of result: \"\n\t\t\t  << arma::abs(result_conv.second - result_arma_fft_pow2_conv.second).max()\n\t\t\t  << std::endl;\n\n\tstd::cout << \"FFTW FFT-Pow2-convolution: \" << std::flush;\n\tauto result_fftw_pow2_conv = FftwConv( sig_data, ir_data);\n\tAudioVec diff;\n\tstd::transform(\n\t\t\tresult_conv.second.begin()\n\t\t\t, result_conv.second.end()\n\t\t\t, std::get<4>(sig_data).begin()\n\t\t\t, std::back_inserter(diff)\n\t\t\t, [](float a, float b) { return fabs(a-b); }\n\t\t\t);\n\tstd::cout << \"\\n\\tduration: \" << result_fftw_pow2_conv.count();\n\tstd::cout << \"\\n\\tmaximum difference of result: \"\n\t\t\t  << std::to_string(*std::max_element(diff.begin(), diff.end()))\n\t\t\t  << std::endl;\n\n\tstd::cout << \"Armadillo FFT-convolution: \" << std::flush;\n\tauto result_arma_fft_conv = ArmadilloFftConv(sig, ir);\n\tstd::cout << \"\\n\\tduration: \" << result_arma_fft_conv.first.count();\n\tstd::cout << \"\\n\\tmaximum difference of result: \"\n\t\t\t  << arma::abs(result_conv.second - result_arma_fft_conv.second).max()\n\t\t\t  << std::endl;\n\n\tstd::cout << \"Armadillo convolution: \" << std::flush;\n\tauto result_arma_conv = ArmadilloConv(sig, ir);\n\tstd::cout << \"\\n\\tduration: \" << result_arma_conv.first.count();\n\tstd::cout << \"\\n\\tmaximum difference of result: \"\n\t\t\t  << arma::abs(result_conv.second - result_arma_conv.second).max()\n\t\t\t  << std::endl;\n}\n", "meta": {"hexsha": "36bff09341794111dcde3f36164c3e38ad3c0977", "size": 7397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "ThomasFeher/fft-comparison", "max_stars_repo_head_hexsha": "5cf2c25c0f9b3b7c9b51ec9958e78372f4f12d6d", "max_stars_repo_licenses": ["MIT"], "max_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": "ThomasFeher/fft-comparison", "max_issues_repo_head_hexsha": "5cf2c25c0f9b3b7c9b51ec9958e78372f4f12d6d", "max_issues_repo_licenses": ["MIT"], "max_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": "ThomasFeher/fft-comparison", "max_forks_repo_head_hexsha": "5cf2c25c0f9b3b7c9b51ec9958e78372f4f12d6d", "max_forks_repo_licenses": ["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.4384236453, "max_line_length": 115, "alphanum_fraction": 0.6805461674, "num_tokens": 2223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5757195346656931}}
{"text": "#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n\ntypedef tiny::Vector<3u, tiny::float_traits>  Vf;\ntypedef tiny::Vector<3u, tiny::double_traits> Vd;\n\n\nBOOST_AUTO_TEST_SUITE(tiny_truncate);\n\n  BOOST_AUTO_TEST_CASE(double_testing)\n  {\n    double const tol = 0.1;\n\n    Vd const A  = Vd::make( 0.2, 0.01, 0.09999 );\n\n    Vd const tB = tiny::truncate(A, tol);\n\n\n    BOOST_CHECK_CLOSE(tB(0), 0.2, 0.01);\n    BOOST_CHECK_CLOSE(tB(1), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(tB(2), 0.0, 0.01);\n  }\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "a8b8566217a8f5e04a94837e197277489dcb64e7", "size": 688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_truncate/tiny_truncate.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_truncate/tiny_truncate.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_truncate/tiny_truncate.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5, "max_line_length": 51, "alphanum_fraction": 0.7078488372, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5756845800045628}}
{"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": "#pragma once\n\n#include <Eigen/Core>\n\n#ifdef USE_FLOAT\ntypedef float Real;\ntypedef Eigen::MatrixXf MatD;\ntypedef Eigen::VectorXf VecD;\n#else\ntypedef double Real;\ntypedef Eigen::MatrixXd MatD;\ntypedef Eigen::VectorXd VecD;\n#endif\n\ntypedef Eigen::MatrixXi MatI;\ntypedef Eigen::VectorXi VecI;\n#define REAL_MAX std::numeric_limits<Real>::max()\n", "meta": {"hexsha": "84796c8a877ab773a71b664e0381a3e37a8e843d", "size": 339, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Matrix.hpp", "max_stars_repo_name": "shipleyxie/N3LP", "max_stars_repo_head_hexsha": "37d8ff0279e30a2df10248c11b813c82eb734967", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2015-12-16T13:17:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T17:02:51.000Z", "max_issues_repo_path": "Matrix.hpp", "max_issues_repo_name": "helianglen/N3LP", "max_issues_repo_head_hexsha": "37d8ff0279e30a2df10248c11b813c82eb734967", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-01-03T23:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-17T05:29:08.000Z", "max_forks_repo_path": "Matrix.hpp", "max_forks_repo_name": "helianglen/N3LP", "max_forks_repo_head_hexsha": "37d8ff0279e30a2df10248c11b813c82eb734967", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2016-01-07T15:52:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T00:55:26.000Z", "avg_line_length": 18.8333333333, "max_line_length": 49, "alphanum_fraction": 0.7787610619, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.5756845694580414}}
{"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: \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u0435\u0442 \u0442\u043e\u0447\u043a\u0443 \u0432\u0445\u043e\u0434\u0430 \u0434\u043b\u044f \u043a\u043e\u043d\u0441\u043e\u043b\u044c\u043d\u043e\u0433\u043e \u043f\u0440\u0438\u043b\u043e\u0436\u0435\u043d\u0438\u044f.\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 <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include <aikido/common/RNG.hpp>\n\n#include \"PolynomialConstraint.hpp\"\n\nusing aikido::statespace::R1;\n\nTEST(PolynomialConstraint, Constructor)\n{\n  PolynomialConstraint<1> p(Eigen::Vector3d(1, 2, 3));\n  EXPECT_THROW(\n      PolynomialConstraint<1>(Eigen::Vector3d(1, 2, 0)), std::invalid_argument);\n}\n\nTEST(PolynomialConstraint, GetValue)\n{\n  PolynomialConstraint<1> p(Eigen::Vector3d(1, 2, 3));\n\n  Eigen::VectorXd v(1);\n  v(0) = -2;\n\n  R1 rvss;\n  auto s1 = rvss.createState();\n  s1.setValue(v);\n\n  Eigen::VectorXd value;\n  p.getValue(s1, value);\n\n  EXPECT_DOUBLE_EQ(value(0), 9);\n}\n\nTEST(PolynomialConstraint, GetJacobian)\n{\n  PolynomialConstraint<1> p(Eigen::Vector3d(1, 2, 3));\n\n  Eigen::VectorXd v(1);\n  v(0) = -2;\n\n  R1 rvss;\n  auto s1 = rvss.createState();\n  s1.setValue(v);\n\n  Eigen::MatrixXd jac;\n  p.getJacobian(s1, jac);\n  EXPECT_DOUBLE_EQ(-10, jac(0, 0));\n}\n", "meta": {"hexsha": "b4c3fd57f4ad16c812d34c6020153ece9274bf55", "size": 915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/constraint/test_PolynomialConstraint.cpp", "max_stars_repo_name": "personalrobotics/r3", "max_stars_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 181.0, "max_stars_repo_stars_event_min_datetime": "2016-04-22T15:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T12:51:08.000Z", "max_issues_repo_path": "tests/constraint/test_PolynomialConstraint.cpp", "max_issues_repo_name": "personalrobotics/r3", "max_issues_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 514.0, "max_issues_repo_issues_event_min_datetime": "2016-04-20T04:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T19:46:21.000Z", "max_forks_repo_path": "tests/constraint/test_PolynomialConstraint.cpp", "max_forks_repo_name": "personalrobotics/r3", "max_forks_repo_head_hexsha": "1303e3f3ef99a0c2249abc7415d19113f0026565", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-03-17T09:53:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:35:05.000Z", "avg_line_length": 18.6734693878, "max_line_length": 80, "alphanum_fraction": 0.6797814208, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5755314798081221}}
{"text": "//          Copyright Alain Miniussi 2014.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n// Authors: Alain Miniussi\n\n#include <vector>\n#include <iostream>\n\n#include <boost/mpicxx/communicator.hpp>\n#include <boost/mpicxx/collectives.hpp>\n#include <boost/mpicxx/environment.hpp>\n#include <boost/mpicxx/cartesian_communicator.hpp>\n\n#include \"check_test.hpp\"\n\nnamespace mpi = boost::mpicxx;\nint main(int argc, char* argv[])\n{\n  mpi::environment  env;\n  mpi::communicator world;\n  \n  if (world.size() != 24)  return -1;\n  mpi::cartesian_dimension dims[] = {{2, true}, {3,true}, {4,true}};\n  mpi::cartesian_communicator cart(world, mpi::cartesian_topology(dims));\n  for (int r = 0; r < cart.size(); ++r) {\n    cart.barrier();\n    if (r == cart.rank()) {\n      std::vector<int> c = cart.coordinates(r);\n      std::cout << \"rk :\" << r << \" coords: \" \n                << c[0] << ' ' << c[1] << ' ' << c[2] << '\\n';\n    }\n  }\n  return 0;\n}\n\n", "meta": {"hexsha": "19b028be0bbaf503e708e604d9bc3a8e17b4bd10", "size": 1054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cartesian_communicator.cpp", "max_stars_repo_name": "aminiussi/mpicxx", "max_stars_repo_head_hexsha": "eb838ce8c3046bfbf1c0f8d96a56cd8b2076b317", "max_stars_repo_licenses": ["Apache-2.0"], "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/cartesian_communicator.cpp", "max_issues_repo_name": "aminiussi/mpicxx", "max_issues_repo_head_hexsha": "eb838ce8c3046bfbf1c0f8d96a56cd8b2076b317", "max_issues_repo_licenses": ["Apache-2.0"], "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/cartesian_communicator.cpp", "max_forks_repo_name": "aminiussi/mpicxx", "max_forks_repo_head_hexsha": "eb838ce8c3046bfbf1c0f8d96a56cd8b2076b317", "max_forks_repo_licenses": ["Apache-2.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.7368421053, "max_line_length": 73, "alphanum_fraction": 0.619544592, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5755314715847203}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/module/bessel.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n#include <eve/detail/diff_div.hpp>\n\nEVE_TEST_TYPES( \"Check return types of sph_bessel_j0\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  TTS_EXPR_IS(eve::sph_bessel_j0(T(0)), T);\n  TTS_EXPR_IS(eve::sph_bessel_j0(v_t(0)), v_t);\n};\n\n EVE_TEST( \"Check behavior of sph_bessel_j0 on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.0, 5.5),\n                              eve::test::randoms(5.5, 9.5),\n                              eve::test::randoms(9.5, 60.0))\n         )\n   <typename T>(T const& a0, T const& a1, T const& a2)\n{\n  using v_t = eve::element_type_t<T>;\n  auto eve__sph_bessel_j0 =  [](auto x) { return eve::sph_bessel_j0(x); };\n  auto std__sph_bessel_j0 =  [](auto x)->v_t { return boost::math::sph_bessel(0u, double(x)); };\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__sph_bessel_j0(eve::inf(eve::as<v_t>())), eve::zero(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_j0(eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_j0(eve::inf(eve::as< T>())),  eve::zero(eve::as< T>()), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_j0(eve::nan(eve::as< T>())), eve::nan(eve::as< T>()), 0);\n  }\n  TTS_ULP_EQUAL(eve__sph_bessel_j0(v_t(500)), std__sph_bessel_j0(v_t(500)), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0(v_t(10)), std__sph_bessel_j0(v_t(10))  , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0(v_t(5)),  std__sph_bessel_j0(v_t(5))   , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0(v_t(2)),  std__sph_bessel_j0(v_t(2))   , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0(v_t(1.5)),std__sph_bessel_j0(v_t(1.5)) , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0(v_t(0.5)),std__sph_bessel_j0(v_t(0.5)) , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0(v_t(1)),  std__sph_bessel_j0(v_t(1))   , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0(v_t(0)),  eve::one(eve::as<v_t>()), 0.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_j0( T(500)),  T(std__sph_bessel_j0(v_t(500)) ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0( T(10)) ,  T(std__sph_bessel_j0( v_t(10)) ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0( T(5))  ,  T(std__sph_bessel_j0( v_t(5))  ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0( T(2))  ,  T(std__sph_bessel_j0( v_t(2))  ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0( T(1.5)),  T(std__sph_bessel_j0( v_t(1.5))), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0( T(0.5)),  T(std__sph_bessel_j0( v_t(0.5))), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0( T(1))  ,  T(std__sph_bessel_j0( v_t(1))  ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0( T(0))  , eve::one(eve::as< T>()), 0.0);\n\n\n  TTS_ULP_EQUAL(eve__sph_bessel_j0(a0), map(std__sph_bessel_j0, a0), 10.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0(a1), map(std__sph_bessel_j0, a1), 10.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_j0(a2), map(std__sph_bessel_j0, a2), 10.0);\n\n};\n\nEVE_TEST( \"Check behavior of diff(sph_bessel_j0) on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(1.0, 10.0))\n        )\n  <typename T>(T a0 )\n{\n  auto eve__diff_bessel_j0 =  [](auto x) { return eve::diff(eve::sph_bessel_j0)(x); };\n  auto df = [](auto x){return eve::detail::centered_diffdiv(eve::sph_bessel_j0, x); };\n\n  TTS_RELATIVE_EQUAL(eve__diff_bessel_j0(a0),   df(a0), 2.0e-2);\n};\n", "meta": {"hexsha": "e6a9626187745eb80f026cbf36df643e72123e60", "size": 3771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/bessel/sph_bessel_j0.cpp", "max_stars_repo_name": "clayne/eve", "max_stars_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/bessel/sph_bessel_j0.cpp", "max_issues_repo_name": "clayne/eve", "max_issues_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/bessel/sph_bessel_j0.cpp", "max_forks_repo_name": "clayne/eve", "max_forks_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.7341772152, "max_line_length": 100, "alphanum_fraction": 0.6313975073, "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5755314715847202}}
{"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": "\n/*\n* Authors:\n* Nicolas Stoiber (nicolas.stoi@gmail.com)\n*\n* 2016\n*/\n\n#ifndef _DENSE_IM_REG_CPU_HPP\n#define _DENSE_IM_REG_CPU_HPP\n\n// ************************** EIGEN SPECIFIC DEFS *****************************\n// setting the flag below could help see if there are hidden allocations.\n//#define EIGEN_NO_AUTOMATIC_RESIZING\n//#define EIGEN_RUNTIME_NO_MALLOC\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n#define malloc_allowed(v) Eigen::internal::set_is_malloc_allowed(v)\n#else\n#define malloc_allowed(v)\n#endif\n\n#define EIGEN_DEFAULT_TO_ROW_MAJOR // comment out this line to use ColMajor\n// ****************************************************************************\n\n#undef Success //(X11 and Eigen both define the Success macro)\n\n// match our own structure orders with Eigen internal's\n#ifdef EIGEN_DEFAULT_TO_ROW_MAJOR\n    #define MY_STORAGE_ORDER Eigen::RowMajor\n#else\n    #define MY_STORAGE_ORDER Eigen::ColMajor\n#endif\n\n#include <Eigen/Dense>\n\n#include <vector>\n\n#include <CImg.h>\n\n#include \"errCodes.h\"\n\n#include \"im_processing_utils.hpp\"\n#include \"optimization_utils.hpp\"\n\n\ntemplate <typename FloatPrec>\nstruct DenseImageRegistrationSolver\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\npublic:\n    DenseImageRegistrationSolver() {}\n    ~DenseImageRegistrationSolver() {}\npublic:\n    /*\n    * initialize registration solver\n    * This preallocates most internal variables used in registration\n    */\n    Common::ErrCode\n    init(\n            const uint32_t  template_width,\n            const uint32_t  template_height,\n            const uint32_t  nb_levels,\n            const FloatPrec lvl_resz_ratio);\n\n    /*\n    * record the template to be registered in images\n    * i_normz_factor is a normalization factor to map image values to a favorable\n    * floating point range (typically [0., 1.]\n    */\n    Common::ErrCode\n    set_template(\n            const cimg_library::CImg<unsigned char> & i_ref_image,\n            std::vector<FloatPrec> &                  i_annot_pts,\n            FloatPrec                                 i_normz_factor = 1./255.);\n\n    /*\n    * register the recorded template (set with 'set_template' in the input\n    * image.\n    */\n    Common::ErrCode\n    register_image(\n            const cimg_library::CImg<unsigned char> & i_reg_image,\n            uint32_t                                  i_nb_iterations,\n            std::vector<FloatPrec> &                  io_reg_pts);\n\n    /*\n    * get the level templates as images (mainly for debug purposes)\n    */\n    Common::ErrCode\n    get_template_image(\n            std::vector<cimg_library::CImg<unsigned char> > & o_lvl_templims) const;\n\n    /*\n    * get nb levels\n    */\n    inline uint32_t nb_levels() const {return m_nb_levels;}\n\npublic: // public typedefs\n    typedef Eigen::Matrix<FloatPrec, Eigen::Dynamic, Eigen::Dynamic, MY_STORAGE_ORDER>\n            MatrixNN;\n    typedef Eigen::Matrix<FloatPrec, Eigen::Dynamic, 2, MY_STORAGE_ORDER>\n            MatrixN2;\n    typedef Eigen::Matrix<FloatPrec, Eigen::Dynamic, 4, MY_STORAGE_ORDER>\n            MatrixN4;\n    typedef Eigen::Matrix<FloatPrec, Eigen::Dynamic, 6, MY_STORAGE_ORDER>\n            MatrixN6;\n    typedef Eigen::Matrix<FloatPrec, 1, Eigen::Dynamic, MY_STORAGE_ORDER>\n            VecN;\n    typedef Eigen::Matrix<FloatPrec, 1, 6, MY_STORAGE_ORDER>\n            Vec6;\n    typedef Eigen::Matrix<FloatPrec, 4, 2, MY_STORAGE_ORDER>\n            Matrix42;\nprivate: // private typedefs\n    typedef Common::ImDim<uint32_t>                         ImDim;\n    typedef std::vector<ImDim>                              LvlList_ImDim;\n    typedef std::vector<FloatPrec>                          LvlList_Ratio;\n    typedef std::vector<VecN>                               LvlList_VecN;\n    typedef std::vector<std::vector<FloatPrec> >            LvlList_StdN4;\n    typedef std::vector<MatrixN4>                           LvlList_MatN4;\n    typedef std::vector<MatrixN2>                           LvlList_MatN2;\n    typedef std::vector<cimg_library::CImg<unsigned char> > LvlList_Images;\n    typedef std::vector<MatrixNN>                           LvlList_MatNN;\n// public:\nprivate:\n    bool           m_is_init = false;\n    bool           m_template_is_set = false;\n    uint32_t       m_nb_levels = 3;\n    FloatPrec      m_lvl_resz_ratio = 0.5;\n    FloatPrec      m_normz_factor = 1./255.;\n    ImDim          m_ref_imdim;\n    LvlList_Ratio  m_lvl_abs_resz_ratio;\n    LvlList_ImDim  m_lvl_templdims;\n    LvlList_VecN   m_lvl_templates;\n    LvlList_StdN4  m_lvl_Ws;\n    LvlList_MatN4  m_lvl_Ws_eigen;\n    LvlList_MatN2  m_lvl_gridpts_eigen;\n    LvlList_Images m_reg_im_pyr; // registration image resolution pyramid\n    // solver containers\n    VecN           m_delta_vars;\n    LvlList_VecN   m_lvl_errs;\n    LvlList_MatNN  m_lvl_jacos;\n    LvlList_MatNN  m_lvl_jTj;\n    LvlList_VecN   m_lvl_jTb;\n    VecN           m_mr_errs; // mr: multi resolution\n    MatrixNN       m_mr_jaco;\n    MatrixNN       m_mr_jTj;\n    VecN           m_mr_jTb;\n    VecN           m_curr_pts;\nprivate:\n    // The following makes the copy contructor and the assignment operator\n    // private to emulate a \"non-copyable\" class.\n    DenseImageRegistrationSolver(DenseImageRegistrationSolver const &);\n    DenseImageRegistrationSolver & operator = (DenseImageRegistrationSolver const &);\nprivate:\n    /*\n    * compute multi-resolution pixel error vector for a given configuration of\n    * points\n    */\n    void\n    compute_multires_pix_error(\n            const VecN & i_pts,\n            VecN &       o_mr_pix_err);\n\n    /*\n    * compute pixel error vector for a given configuration of\n    * points for a given resoltion level\n    */\n    void\n    compute_lvl_pix_error(\n            const VecN & i_pts,\n            uint32_t     i_lvl,\n            VecN &       o_lvl_pix_err);\n\n    /*\n    * compute multi-resolution pixel jacobian matrix for a given configuration of\n    * points\n    */\n    void\n    compute_multires_pix_jacobian(\n            const VecN & i_pts,\n            MatrixNN &   o_mr_pix_err);\n\n    /*\n    * compute pixel jacobian matrix for a given configuration of\n    * points for a given resoltion level\n    */\n    void\n    compute_lvl_pix_jacobian(\n            const VecN & i_pts,\n            uint32_t     i_lvl,\n            MatrixNN &   o_mr_pix_err);\n};\n\n#include \"dense_im_reg_cpu.inl.hpp\"\n\n#endif // #ifndef _DENSE_IM_REG_CPU_HPP\n\n\n\n", "meta": {"hexsha": "2ca5a70484b22ac7475dc07bd01fd20021ba0604", "size": 6334, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dense_im_registration/CPU/src/dense_im_reg_cpu.hpp", "max_stars_repo_name": "spaceapple/cpu-gpu-numerical-optim-bench", "max_stars_repo_head_hexsha": "2bdd520e68a9c2324cc1faa4c8d83e027b95b0f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dense_im_registration/CPU/src/dense_im_reg_cpu.hpp", "max_issues_repo_name": "spaceapple/cpu-gpu-numerical-optim-bench", "max_issues_repo_head_hexsha": "2bdd520e68a9c2324cc1faa4c8d83e027b95b0f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dense_im_registration/CPU/src/dense_im_reg_cpu.hpp", "max_forks_repo_name": "spaceapple/cpu-gpu-numerical-optim-bench", "max_forks_repo_head_hexsha": "2bdd520e68a9c2324cc1faa4c8d83e027b95b0f3", "max_forks_repo_licenses": ["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.5124378109, "max_line_length": 86, "alphanum_fraction": 0.6313545943, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5755077527946388}}
{"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": "#pragma once\n#include <Eigen/Core>\n#include \"nn.hpp\"\n#include <algorithm>\n#include <random>\n\nusing Eigen::Matrix;\n\nconstexpr int agent_num_states = 6;\nconstexpr int agent_num_inputs = 11 + agent_num_states;\n\nenum class AgentAction {Right, Down, Left, Up};\n\nclass AgentController: public SmallNN<agent_num_inputs, 20, 4+agent_num_states> {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  AgentAction calc(const Matrix<float, agent_num_inputs, 1> &inputs, float *states, std::default_random_engine &rng) {\n    Matrix<float, 4+agent_num_states, 1> o = predict(inputs);\n    using std::max;\n    using std::exp;\n\n    // First 4 outputs represent 4 actions.\n    // Select a random action according to softmax probabilities.\n    //\n    // def softmax(x):\n    //     e_x = np.exp(x - np.max(x))\n    //     return e_x / e_x.sum(axis=0)\n    //\n    float m = max(o(0), max(o(1), max(o(2), o(3))));\n    float c0 = exp(o(0)-m);\n    float c1 = exp(o(1)-m);\n    float c2 = exp(o(2)-m);\n    float c3 = exp(o(3)-m);\n    float sum = c0+c1+c2+c3;\n    std::uniform_real_distribution<float> dist(0, sum);\n    float roll = dist(rng);\n    AgentAction action;\n    if (roll < c0) action = AgentAction::Right;\n    else if (roll < c0+c1) action = AgentAction::Down;\n    else if (roll < c0+c1+c2) action = AgentAction::Left;\n    else action = AgentAction::Up;\n\n    constexpr float state_decay = 0.01;\n    for (int i=0; i<agent_num_states; i++) {\n      states[i] = (1.0-state_decay)*states[i] + state_decay*o(i+4);\n    }\n\n    return action;\n  }\n};\n", "meta": {"hexsha": "c7906af3a3f10cce38d51364f6338b871fb54cef", "size": 1515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "world/agent.hpp", "max_stars_repo_name": "martinxyz/pixelcrawl", "max_stars_repo_head_hexsha": "e1218be20ec2fb65ab577b366f54546b59db5854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-24T13:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-26T08:50:21.000Z", "max_issues_repo_path": "world/agent.hpp", "max_issues_repo_name": "martinxyz/pixelcrawl", "max_issues_repo_head_hexsha": "e1218be20ec2fb65ab577b366f54546b59db5854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T02:21:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T02:21:46.000Z", "max_forks_repo_path": "world/agent.hpp", "max_forks_repo_name": "martinxyz/pixelcrawl", "max_forks_repo_head_hexsha": "e1218be20ec2fb65ab577b366f54546b59db5854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T13:32:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T13:32:10.000Z", "avg_line_length": 29.7058823529, "max_line_length": 118, "alphanum_fraction": 0.6455445545, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5754923374790376}}
{"text": "//\r\n// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n\r\n#include <OpenTissue/core/math/math_basic_types.h>\r\n#include <OpenTissue/collision/gjk/gjk_reduce_tetrahedron.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <OpenTissue/utility/utility_push_boost_filter.h>\r\n#include <boost/test/auto_unit_test.hpp>\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\r\n\r\n#include <cmath>\r\n\r\nusing namespace OpenTissue;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_collision_gjk_reduce_tetrahedron);\r\n\r\nBOOST_AUTO_TEST_CASE(case_by_case_test_not_touching)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n  typedef math_types::vector3_type                         vector3_type;\r\n  typedef math_types::real_type                            real_type;\r\n\r\n  typedef OpenTissue::gjk::Simplex<vector3_type>           simplex_type;\r\n\r\n  // First we create a simplex that represents a tetrahedron\r\n  vector3_type const a = vector3_type( 0.0,  0.0, 0.0);\r\n  vector3_type const b = vector3_type( 1.0,  0.0, 0.0);\r\n  vector3_type const c = vector3_type( 0.0,  1.0, 0.0);\r\n  vector3_type const d = vector3_type( 0.0,  0.0, 1.0);\r\n\r\n  // Inside tetrahedron region new simplex should be ABC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a + b + c + d)*0.25;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 4u );\r\n\r\n    BOOST_CHECK(S.m_bitmask == 15u);\r\n    BOOST_CHECK(S.m_v[0] == a);\r\n    BOOST_CHECK(S.m_a[0] == a);\r\n    BOOST_CHECK(S.m_b[0] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[1] == b);\r\n    BOOST_CHECK(S.m_a[1] == b);\r\n    BOOST_CHECK(S.m_b[1] == b);\r\n\r\n    BOOST_CHECK(S.m_v[2] == c);\r\n    BOOST_CHECK(S.m_a[2] == c);\r\n    BOOST_CHECK(S.m_b[2] == c);\r\n\r\n    BOOST_CHECK(S.m_v[3] == d);\r\n    BOOST_CHECK(S.m_a[3] == d);\r\n    BOOST_CHECK(S.m_b[3] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[0], 0.25, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[1], 0.25, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[2], 0.25, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[3], 0.25, 0.01);\r\n  }\r\n\r\n  // Inside ABC face region new simplex should be ABC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a+b+c)/3.0 - vector3_type(0,0,1);\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == c);\r\n    BOOST_CHECK(S.m_a[idx_C] == c);\r\n    BOOST_CHECK(S.m_b[idx_C] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.3333333333333333, 0.01);\r\n  }\r\n\r\n\r\n  // Inside BCD face region new simplex should be BCD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (b+c+d)/3.0 + vector3_type(1,1,1);\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == d);\r\n    BOOST_CHECK(S.m_a[idx_C] == d);\r\n    BOOST_CHECK(S.m_b[idx_C] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.3333333333333333, 0.01);\r\n  }\r\n\r\n  // Inside ABD face region new simplex should be ABD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a+b+d)/3.0 - vector3_type(0,1,0);\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    \r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == d);\r\n    BOOST_CHECK(S.m_a[idx_C] == d);\r\n    BOOST_CHECK(S.m_b[idx_C] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.3333333333333333, 0.01);\r\n  }\r\n\r\n\r\n  // Inside ACD face region new simplex should be ACD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a+c+d)/3.0 - vector3_type(1,0,0);\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == d);\r\n    BOOST_CHECK(S.m_a[idx_C] == d);\r\n    BOOST_CHECK(S.m_b[idx_C] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.3333333333333333, 0.01);\r\n  }\r\n\r\n  // Inside AB edge region new simplex should be AB\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a+b)/2.0 - vector3_type(0,1,1);\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n  // Inside AC edge region new simplex should be AC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a+c)/2.0 - vector3_type(1,0,1);\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n  // Inside AD edge region new simplex should be AD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a+d)/2.0 - vector3_type(1,1,0);\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == d);\r\n    BOOST_CHECK(S.m_a[idx_B] == d);\r\n    BOOST_CHECK(S.m_b[idx_B] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n  // Inside BC edge region new simplex should be BC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (b+c)/2.0 + vector3_type(0,0,-1) + unit( vector3_type(1,1,1) );\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n  // Inside BD edge region new simplex should be BD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (b+d)/2.0 + vector3_type(0.0,-1.0,0.0) + unit(vector3_type(1.0,1.0,1.0));\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == d);\r\n    BOOST_CHECK(S.m_a[idx_B] == d);\r\n    BOOST_CHECK(S.m_b[idx_B] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n  // Inside CD edge region new simplex should be CD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (c+d)/2.0 + vector3_type(-1.0,0.0,0.0) + unit( vector3_type(1.0,1.0,1.0) );\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == c);\r\n    BOOST_CHECK(S.m_a[idx_A] == c);\r\n    BOOST_CHECK(S.m_b[idx_A] == c);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == d);\r\n    BOOST_CHECK(S.m_a[idx_B] == d);\r\n    BOOST_CHECK(S.m_b[idx_B] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n  // Inside A vertex region new simplex should be A\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = a + vector3_type(-1.0,-1.0,-1.0);\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A );\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\r\n  }\r\n\r\n  // Inside B vertex region new simplex should be B\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = b + vector3_type(0.0,-1.0,0.0)+ vector3_type(0.0,0.0,-1.0) + unit( vector3_type(1,1,1) );\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A );\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n    \r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\r\n  }\r\n\r\n  // Inside C vertex region new simplex should be C\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = c + vector3_type(-1.0,0.0,0.0) + vector3_type(0,0,-1)  + unit( vector3_type(1,1,1) );\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A );\r\n    BOOST_CHECK(S.m_v[idx_A] == c);\r\n    BOOST_CHECK(S.m_a[idx_A] == c);\r\n    BOOST_CHECK(S.m_b[idx_A] == c);\r\n    \r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\r\n  }\r\n\r\n  // Inside D vertex region new simplex should be D\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = d + vector3_type(-1.0,0.0,0.0) + vector3_type(0.0,-1.0,0.0) + unit( vector3_type(1,1,1) );\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A );\r\n    BOOST_CHECK(S.m_v[idx_A] == d);\r\n    BOOST_CHECK(S.m_a[idx_A] == d);\r\n    BOOST_CHECK(S.m_b[idx_A] == d);\r\n    \r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\r\n  }\r\n\r\n}\r\n\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(case_by_case_test_touching)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n  typedef math_types::vector3_type                         vector3_type;\r\n  typedef math_types::real_type                            real_type;\r\n\r\n  typedef OpenTissue::gjk::Simplex<vector3_type>           simplex_type;\r\n\r\n  // First we create a simplex that represents a tetrahedron\r\n  vector3_type const a = vector3_type( 0.0,  0.0, 0.0);\r\n  vector3_type const b = vector3_type( 1.0,  0.0, 0.0);\r\n  vector3_type const c = vector3_type( 0.0,  1.0, 0.0);\r\n  vector3_type const d = vector3_type( 0.0,  0.0, 1.0);\r\n\r\n  // Inside tetrahedron region new simplex should be ABCD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a + b + c + d)*0.25;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 4u );\r\n\r\n    BOOST_CHECK(S.m_bitmask == 15u);\r\n    BOOST_CHECK(S.m_v[0] == a);\r\n    BOOST_CHECK(S.m_a[0] == a);\r\n    BOOST_CHECK(S.m_b[0] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[1] == b);\r\n    BOOST_CHECK(S.m_a[1] == b);\r\n    BOOST_CHECK(S.m_b[1] == b);\r\n\r\n    BOOST_CHECK(S.m_v[2] == c);\r\n    BOOST_CHECK(S.m_a[2] == c);\r\n    BOOST_CHECK(S.m_b[2] == c);\r\n\r\n    BOOST_CHECK(S.m_v[3] == d);\r\n    BOOST_CHECK(S.m_a[3] == d);\r\n    BOOST_CHECK(S.m_b[3] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[0], 0.25, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[1], 0.25, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[2], 0.25, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[3], 0.25, 0.01);\r\n  }\r\n\r\n  // Inside ABC face region new simplex should be ABC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a+b+c)/3.0;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == c);\r\n    BOOST_CHECK(S.m_a[idx_C] == c);\r\n    BOOST_CHECK(S.m_b[idx_C] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.3333333333333333, 0.01);\r\n  }\r\n\r\n\r\n  // Inside BCD face region new simplex should be BCD\r\n  {\r\n\r\n    // This case fails, problem is with numerical precision, the\r\n    // triangle face plane distance is computed to something like -5e-17, very\r\n    // small but negative. This means the test point is seen as being inside\r\n    // the tetrahedron and we get the full simplex back!\r\n\r\n    // It means that all the test cases for this case fails!\r\n\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (b+c+d)/3.0;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    //BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    //int bit_A    = 0;\r\n    //size_t idx_A = 0;\r\n    //int bit_B    = 0;\r\n    //size_t idx_B = 0;\r\n    //int bit_C    = 0;\r\n    //size_t idx_C = 0;\r\n    //OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    //BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    //BOOST_CHECK(S.m_v[idx_A] == b);\r\n    //BOOST_CHECK(S.m_a[idx_A] == b);\r\n    //BOOST_CHECK(S.m_b[idx_A] == b);\r\n    //\r\n    //BOOST_CHECK(S.m_v[idx_B] == c);\r\n    //BOOST_CHECK(S.m_a[idx_B] == c);\r\n    //BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    //BOOST_CHECK(S.m_v[idx_C] == d);\r\n    //BOOST_CHECK(S.m_a[idx_C] == d);\r\n    //BOOST_CHECK(S.m_b[idx_C] == d);\r\n\r\n    //BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.3333333333333333, 0.01);\r\n    //BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.3333333333333333, 0.01);\r\n    //BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.3333333333333333, 0.01);\r\n  }\r\n\r\n  // Inside ABD face region new simplex should be ABD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a+b+d)/3.0;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    \r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == d);\r\n    BOOST_CHECK(S.m_a[idx_C] == d);\r\n    BOOST_CHECK(S.m_b[idx_C] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.3333333333333333, 0.01);\r\n  }\r\n\r\n\r\n  // Inside ACD face region new simplex should be ACD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a+c+d)/3.0;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == d);\r\n    BOOST_CHECK(S.m_a[idx_C] == d);\r\n    BOOST_CHECK(S.m_b[idx_C] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.3333333333333333, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.3333333333333333, 0.01);\r\n  }\r\n\r\n  // Inside AB edge region new simplex should be AB\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a+b)/2.0;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n  // Inside AC edge region new simplex should be AC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a+c)/2.0;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n  // Inside AD edge region new simplex should be AD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (a+d)/2.0;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == d);\r\n    BOOST_CHECK(S.m_a[idx_B] == d);\r\n    BOOST_CHECK(S.m_b[idx_B] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n  // Inside BC edge region new simplex should be BC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (b+c)/2.0;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n  // Inside BD edge region new simplex should be BD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (b+d)/2.0;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == d);\r\n    BOOST_CHECK(S.m_a[idx_B] == d);\r\n    BOOST_CHECK(S.m_b[idx_B] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n  // Inside CD edge region new simplex should be CD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = (c+d)/2.0;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == c);\r\n    BOOST_CHECK(S.m_a[idx_A] == c);\r\n    BOOST_CHECK(S.m_b[idx_A] == c);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == d);\r\n    BOOST_CHECK(S.m_a[idx_B] == d);\r\n    BOOST_CHECK(S.m_b[idx_B] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.5, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.5, 0.01);\r\n  }\r\n\r\n  // Inside A vertex region new simplex should be A\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = a;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A );\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\r\n  }\r\n\r\n  // Inside B vertex region new simplex should be B\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = b;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A );\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n    \r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\r\n  }\r\n\r\n  // Inside C vertex region new simplex should be C\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = c;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A );\r\n    BOOST_CHECK(S.m_v[idx_A] == c);\r\n    BOOST_CHECK(S.m_a[idx_A] == c);\r\n    BOOST_CHECK(S.m_b[idx_A] == c);\r\n    \r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\r\n  }\r\n\r\n  // Inside D vertex region new simplex should be D\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = d;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 1u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A );\r\n\r\n    BOOST_CHECK(S.m_bitmask == bit_A );\r\n    BOOST_CHECK(S.m_v[idx_A] == d);\r\n    BOOST_CHECK(S.m_a[idx_A] == d);\r\n    BOOST_CHECK(S.m_b[idx_A] == d);\r\n    \r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 1.0, 0.01);\r\n  }\r\n\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(case_by_case_test_assymmetric)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n  typedef math_types::vector3_type                         vector3_type;\r\n  typedef math_types::real_type                            real_type;\r\n\r\n  typedef OpenTissue::gjk::Simplex<vector3_type>           simplex_type;\r\n\r\n  // First we create a simplex that represents a tetrahedron\r\n  vector3_type const a = vector3_type( 0.0,  0.0, 0.0);\r\n  vector3_type const b = vector3_type( 1.0,  0.0, 0.0);\r\n  vector3_type const c = vector3_type( 0.0,  1.0, 0.0);\r\n  vector3_type const d = vector3_type( 0.0,  0.0, 1.0);\r\n\r\n  // New simplex should be ABCD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = 0.1*a + 0.2*b + 0.3*c + 0.4*d;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 4u );\r\n\r\n    BOOST_CHECK(S.m_bitmask == 15u);\r\n    BOOST_CHECK(S.m_v[0] == a);\r\n    BOOST_CHECK(S.m_a[0] == a);\r\n    BOOST_CHECK(S.m_b[0] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[1] == b);\r\n    BOOST_CHECK(S.m_a[1] == b);\r\n    BOOST_CHECK(S.m_b[1] == b);\r\n\r\n    BOOST_CHECK(S.m_v[2] == c);\r\n    BOOST_CHECK(S.m_a[2] == c);\r\n    BOOST_CHECK(S.m_b[2] == c);\r\n\r\n    BOOST_CHECK(S.m_v[3] == d);\r\n    BOOST_CHECK(S.m_a[3] == d);\r\n    BOOST_CHECK(S.m_b[3] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[0], 0.1, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[1], 0.2, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[2], 0.3, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[3], 0.4, 0.01);\r\n  }\r\n\r\n  // New simplex should be ABC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = 0.2*a+0.3*b+0.5*c;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == c);\r\n    BOOST_CHECK(S.m_a[idx_C] == c);\r\n    BOOST_CHECK(S.m_b[idx_C] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.2, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.3, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.5, 0.01);\r\n  }\r\n\r\n  // New simplex should be BCD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = 0.2*b+0.3*c+0.5*d;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == d);\r\n    BOOST_CHECK(S.m_a[idx_C] == d);\r\n    BOOST_CHECK(S.m_b[idx_C] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.2, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.3, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.5, 0.01);\r\n  }\r\n\r\n  // New simplex should be ABD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = 0.2*a+0.3*b+0.5*d;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    \r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == d);\r\n    BOOST_CHECK(S.m_a[idx_C] == d);\r\n    BOOST_CHECK(S.m_b[idx_C] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.2, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.3, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.5, 0.01);\r\n  }\r\n\r\n  // New simplex should be ACD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = 0.2*a + 0.3*c + 0.5*d;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 3u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    int bit_C    = 0;\r\n    size_t idx_C = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B , idx_C, bit_C );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B | bit_C));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK(S.m_v[idx_C] == d);\r\n    BOOST_CHECK(S.m_a[idx_C] == d);\r\n    BOOST_CHECK(S.m_b[idx_C] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.2, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.3, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_C], 0.5, 0.01);\r\n  }\r\n\r\n  // New simplex should be AB\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = 0.4*a+0.6*b;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == b);\r\n    BOOST_CHECK(S.m_a[idx_B] == b);\r\n    BOOST_CHECK(S.m_b[idx_B] == b);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.4, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.6, 0.01);\r\n  }\r\n\r\n  // New simplex should be AC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = 0.4*a+0.6*c;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.4, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.6, 0.01);\r\n  }\r\n\r\n  // New simplex should be AD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = 0.4*a+0.6*d;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == a);\r\n    BOOST_CHECK(S.m_a[idx_A] == a);\r\n    BOOST_CHECK(S.m_b[idx_A] == a);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == d);\r\n    BOOST_CHECK(S.m_a[idx_B] == d);\r\n    BOOST_CHECK(S.m_b[idx_B] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.4, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.6, 0.01);\r\n  }\r\n\r\n  // New simplex should be BC\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = 0.4*b+0.6*c;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == c);\r\n    BOOST_CHECK(S.m_a[idx_B] == c);\r\n    BOOST_CHECK(S.m_b[idx_B] == c);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.4, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.6, 0.01);\r\n  }\r\n\r\n  // New simplex should be BD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = 0.4*b+0.6*d;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == b);\r\n    BOOST_CHECK(S.m_a[idx_A] == b);\r\n    BOOST_CHECK(S.m_b[idx_A] == b);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == d);\r\n    BOOST_CHECK(S.m_a[idx_B] == d);\r\n    BOOST_CHECK(S.m_b[idx_B] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.4, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.6, 0.01);\r\n  }\r\n\r\n  // New simplex should be CD\r\n  {\r\n    simplex_type S;\r\n\r\n    OpenTissue::gjk::add_point_to_simplex( a, a, a, S);\r\n    OpenTissue::gjk::add_point_to_simplex( b, b, b, S);\r\n    OpenTissue::gjk::add_point_to_simplex( c, c, c, S);\r\n    OpenTissue::gjk::add_point_to_simplex( d, d, d, S);\r\n\r\n    vector3_type const p = 0.4*c+0.6*d;\r\n\r\n    OpenTissue::gjk::detail::reduce_tetrahedron( p, S );\r\n\r\n    BOOST_CHECK( OpenTissue::gjk::dimension( S ) == 2u );\r\n\r\n    int bit_A    = 0;\r\n    size_t idx_A = 0;\r\n    int bit_B    = 0;\r\n    size_t idx_B = 0;\r\n    OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B );\r\n\r\n    BOOST_CHECK(S.m_bitmask == (bit_A | bit_B ));\r\n    BOOST_CHECK(S.m_v[idx_A] == c);\r\n    BOOST_CHECK(S.m_a[idx_A] == c);\r\n    BOOST_CHECK(S.m_b[idx_A] == c);\r\n    \r\n    BOOST_CHECK(S.m_v[idx_B] == d);\r\n    BOOST_CHECK(S.m_a[idx_B] == d);\r\n    BOOST_CHECK(S.m_b[idx_B] == d);\r\n\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_A], 0.4, 0.01);\r\n    BOOST_CHECK_CLOSE(S.m_w[idx_B], 0.6, 0.01);\r\n  }\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "2bdde84b01b87b31f85f216a6e7f80254d3b6d3e", "size": 47582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/collision/gjk/reduce_tetrahedron/src/unit_reduce_tetrahedron.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/collision/gjk/reduce_tetrahedron/src/unit_reduce_tetrahedron.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/collision/gjk/reduce_tetrahedron/src/unit_reduce_tetrahedron.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 31.140052356, "max_line_length": 118, "alphanum_fraction": 0.6011727124, "num_tokens": 16456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.5754866636073419}}
{"text": "/*\n *  Distributed under the MIT License (See accompanying file /LICENSE )\n */\n#include <doctest/doctest.h>  // for ResultBuilder\n\n#include <boost/multiprecision/cpp_int.hpp>  // for cpp_int\n#include <ostream>                           // for operator<<\n#include <tuple>                             // for tuple\n#include <type_traits>                       // for move\n\n#include \"projgeom/common_concepts.h\"  // for Value_type\n#include \"projgeom/euclid_plane.hpp\"   // for Ar\n#include \"projgeom/fractions.hpp\"      // for operator*\n#include \"projgeom/persp_plane.hpp\"    // for persp_eucl...\n#include \"projgeom/pg_common.hpp\"      // for sq\n#include \"projgeom/pg_line.hpp\"        // for pg_line\n#include \"projgeom/pg_object.hpp\"      // for operator*\n#include \"projgeom/pg_point.hpp\"       // for pg_point\n#include \"projgeom/proj_plane.hpp\"     // for coincident\n// #include <iostream>\n\nusing namespace fun;\n\nstatic const auto Zero = doctest::Approx(0).epsilon(0.01);\n\n/**\n * @brief\n *\n * @tparam PG\n * @param[in] myck\n */\ntemplate <typename PG> void chk_degenerate(const PG& myck) {\n    using Point = typename PG::point_t;\n    // using Line = typename PG::line_t;\n    using K = Value_type<Point>;\n\n    auto a1 = Point{-1, 0, 3};\n    auto a2 = Point{4, -2, 1};\n    auto a3 = Point{3, -1, 1};\n\n    const auto m12 = myck.midpoint(a1, a2);\n    const auto m23 = myck.midpoint(a2, a3);\n    const auto m13 = myck.midpoint(a1, a3);\n    const auto t1 = a1 * m23;\n    const auto t2 = a2 * m13;\n    const auto t3 = a3 * m12;\n\n    auto triangle = std::tuple{std::move(a1), std::move(a2), std::move(a3)};\n    const auto trilateral = tri_dual(triangle);\n\n    // const auto& [a1, a2, a3] = triangle;\n    const auto& [l1, l2, l3] = trilateral;\n\n    const auto [q1, q2, q3] = myck.tri_quadrance(triangle);\n    const auto [s1, s2, s3] = myck.tri_spread(trilateral);\n\n    const auto tqf = sq(q1 + q2 + q3) - 2 * (q1 * q1 + q2 * q2 + q3 * q3);\n    const auto tsf = sq(s1 + s2 + s3) - 2 * (s1 * s1 + s2 * s2 + s3 * s3) - 4 * s1 * s2 * s3;\n\n    if constexpr (Integral<K>) {\n        CHECK(!myck.is_parallel(l1, l2));\n        CHECK(!myck.is_parallel(l2, l3));\n        CHECK(coincident(t1 * t2, t3));\n        CHECK(tqf == Ar(q1, q2, q3));\n        CHECK(tsf == K(0));\n    } else {\n        CHECK(myck.l_infty().dot(l1 * l2) != Zero);\n        CHECK(myck.l_infty().dot(l2 * l3) != Zero);\n        CHECK(t1.dot(t2 * t3) == Zero);\n        CHECK(tqf - Ar(q1, q2, q3) == Zero);\n        CHECK(tsf == Zero);\n    }\n}\n\n/**\n * @brief\n *\n * @tparam PG\n * @param[in] myck\n */\ntemplate <typename PG> void chk_degenerate2(const PG& myck) {\n    using Point = typename PG::point_t;\n    // using Line = typename PG::line_t;\n    using K = Value_type<Point>;\n\n    auto a1 = Point{-1, 0, 3};\n    auto a2 = Point{4, -2, 1};\n    auto a4 = plucker(3, a1, 4, a2);\n\n    const auto tri2 = std::tuple{std::move(a1), std::move(a2), std::move(a4)};\n    const auto [qq1, qq2, qq3] = myck.tri_quadrance(tri2);\n    const auto tqf2 = Ar(qq1, qq2, qq3);  // get 0\n\n    if constexpr (Integral<K>) {\n        CHECK(tqf2 == 0);\n    } else {\n        CHECK(tqf2 == Zero);\n    }\n}\n\nTEST_CASE(\"Perspective Euclid plane (cpp_int)\") {\n    using boost::multiprecision::cpp_int;\n\n    auto Ire = pg_point<cpp_int>(0, 1, 1);\n    auto Iim = pg_point<cpp_int>(1, 0, 0);\n    auto l_inf = pg_line<cpp_int>(0, -1, 1);\n\n    const auto P = persp_euclid_plane{std::move(Ire), std::move(Iim), std::move(l_inf)};\n    chk_degenerate(P);\n    chk_degenerate2(P);\n}\n\nTEST_CASE(\"Perspective Euclid plane (floating point)\") {\n    auto Ire = pg_point{0., 1., 1.};\n    auto Iim = pg_point{1., 0., 0.};\n    auto l_inf = pg_line{0., -1., 1.};\n\n    const auto P = persp_euclid_plane{std::move(Ire), std::move(Iim), std::move(l_inf)};\n    chk_degenerate(P);\n    chk_degenerate2(P);\n}\n", "meta": {"hexsha": "cbf022278d5c769be3770f9cf98f7a7c46d8d6bc", "size": 3786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/source/test_persp_plane.cpp", "max_stars_repo_name": "luk036/projgeom-cpp", "max_stars_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/source/test_persp_plane.cpp", "max_issues_repo_name": "luk036/projgeom-cpp", "max_issues_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/source/test_persp_plane.cpp", "max_forks_repo_name": "luk036/projgeom-cpp", "max_forks_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0327868852, "max_line_length": 93, "alphanum_fraction": 0.588748019, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5754158545347262}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, inv_Phi) {\n  using stan::math::inv_Phi;\n  using stan::math::Phi;\n  EXPECT_FLOAT_EQ(0.0, inv_Phi(0.5));\n  double p = 0.123456789;\n  EXPECT_FLOAT_EQ(p, Phi(inv_Phi(p)));\n  p = 8e-311;\n  EXPECT_FLOAT_EQ(p, Phi(inv_Phi(p)));\n  p = 0.99;\n  EXPECT_FLOAT_EQ(p, Phi(inv_Phi(p)));\n\n  // breakpoints\n  p = 0.02425;\n  EXPECT_FLOAT_EQ(p, Phi(inv_Phi(p)));\n  p = 0.97575;\n  EXPECT_FLOAT_EQ(p, Phi(inv_Phi(p)));\n}\nTEST(MathFunctions, inv_Phi_inf) {\n  using stan::math::inv_Phi;\n  double p = 7e-311;\n  const double inf = std::numeric_limits<double>::infinity();\n  EXPECT_EQ(inv_Phi(p),-inf);\n  p = 1.0;\n  EXPECT_EQ(inv_Phi(p),inf);\n}\nTEST(MathFunctions, inv_Phi_nan) {\n  using stan::math::inv_Phi;\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_THROW(inv_Phi(nan), std::domain_error);\n  EXPECT_THROW(inv_Phi(-2.0), std::domain_error);\n  EXPECT_THROW(inv_Phi(2.0), std::domain_error);\n}\n", "meta": {"hexsha": "40239028cb2e8f2c7f172058e7b1579775b150ed", "size": 1026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/inv_Phi_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/inv_Phi_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/inv_Phi_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7297297297, "max_line_length": 61, "alphanum_fraction": 0.6910331384, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5753788952811144}}
{"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   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// *** ViennaCL\n//\n#define VIENNACL_WITH_UBLAS 1\n\n//#define VIENNACL_DEBUG_ALL\n//#define VIENNACL_DEBUG_BUILD\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/reduce.hpp\"\n#include \"viennacl/device_specific/code_generator.hpp\"\n#include \"viennacl/scheduler/io.hpp\"\n\n#define CHECK_RESULT(cpu,gpu, op) \\\n    if ( double delta = fabs ( diff ( cpu, gpu) ) > epsilon ) {\\\n        std::cout << \"# Error at operation: \" #op << std::endl;\\\n        std::cout << \"  diff: \" << delta << std::endl;\\\n        retval = EXIT_FAILURE;\\\n    }\\\n\n\nusing namespace boost::numeric;\nusing namespace viennacl;\n\ntemplate<typename ScalarType, typename VCLMatrixType>\nScalarType diff(ublas::matrix<ScalarType> & mat1, VCLMatrixType & mat2)\n{\n   ublas::matrix<ScalarType> mat2_cpu(mat2.size1(), mat2.size2());\n   viennacl::backend::finish();  //workaround for a bug in APP SDK 2.7 on Trinity APUs (with Catalyst 12.8)\n   viennacl::copy(mat2, mat2_cpu);\n   double ret = 0;\n   double act = 0;\n\n    for (unsigned int i = 0; i < mat2_cpu.size1(); ++i)\n    {\n      for (unsigned int j = 0; j < mat2_cpu.size2(); ++j)\n      {\n         act = std::fabs(mat2_cpu(i,j) - mat1(i,j)) / std::max<ScalarType>( std::fabs(mat2_cpu(i, j)), std::fabs(mat1(i,j)) );\n         if (act > ret)\n           ret = act;\n      }\n    }\n   //std::cout << ret << std::endl;\n   return ret;\n}\n\ntemplate<typename ScalarType, unsigned int Alignment>\nScalarType diff ( ublas::vector<ScalarType> & v1, viennacl::vector<ScalarType,Alignment> & v2 ) {\n    ublas::vector<ScalarType> v2_cpu ( v2.size() );\n    viennacl::copy( v2.begin(), v2.end(), v2_cpu.begin() );\n    for ( unsigned int i=0; i<v1.size(); ++i ) {\n        if ( std::max ( std::fabs ( v2_cpu[i] ), std::fabs ( v1[i] ) ) > 0 )\n            v2_cpu[i] = std::fabs ( v2_cpu[i] - v1[i] ) / std::max<ScalarType>( std::fabs ( v2_cpu[i] ), std::fabs ( v1[i] ) );\n        else\n            v2_cpu[i] = 0.0;\n    }\n    return norm_inf ( v2_cpu );\n}\n\n\ntemplate< typename NumericT, class Layout, typename Epsilon >\nint test( Epsilon const& epsilon) {\n    int retval = EXIT_SUCCESS;\n\n    ublas::vector<NumericT> cx;\n    ublas::vector<NumericT> cy;\n\n    ublas::matrix<NumericT> cA;\n    ublas::matrix<NumericT> cB;\n    ublas::matrix<NumericT> cC;\n    ublas::matrix<NumericT> cD;\n\n    unsigned int size1 = 762;\n    unsigned int size2 = 663;\n\n    cA.resize(size1,size2);\n    cx.resize(size2);\n    cy.resize(size1);\n\n    srand(0);\n\n    for (unsigned int i=0; i<size1; ++i){\n        for (unsigned int j=0; j<size2; ++j){\n            cA(i,j)=j;\n        }\n    }\n\n    for (unsigned int i=0; i<size2; ++i){\n        cx(i) = i;\n    }\n\n    for (unsigned int i=0; i<size1; ++i){\n        cy(i) = i;\n    }\n\n//    std::cout << \"Running tests for matrix of size \" << cA.size1() << \",\" << cA.size2() << std::endl;\n\n    viennacl::matrix<NumericT,Layout> A (size1, size2);\n    viennacl::matrix<NumericT,Layout> B (size1, size2);\n    viennacl::matrix<NumericT,Layout> C (size1, size2);\n    viennacl::matrix<NumericT,Layout> D (size1, size2);\n\n    viennacl::vector<NumericT> x(size2);\n    viennacl::vector<NumericT> y(size1);\n\n\n    cB = cA;\n    cC = cA;\n    cD = cA;\n    viennacl::copy(cA,A);\n    viennacl::copy(cB,B);\n    viennacl::copy(cC,C);\n    viennacl::copy(cD,D);\n\n    viennacl::copy(cx,x);\n    viennacl::copy(cy,y);\n\n\n    // --------------------------------------------------------------------------\n    {\n        std::cout << \"y = A*x...\" << std::endl;\n        cy     =  ublas::prod(cA,cx);\n        viennacl::scheduler::statement statement(y, viennacl::op_assign(), viennacl::linalg::prod(A,x));\n        //std::cout << statement << std::endl;\n        device_specific::generate_enqueue_statement(statement, statement.array()[0]);\n        viennacl::backend::finish();\n        CHECK_RESULT(cy,y,y=A*x)\n    }\n\n    {\n        std::cout << \"x = trans(A)*y...\" << std::endl;\n        cx     =  ublas::prod(trans(cA),cy);\n        viennacl::scheduler::statement statement(x, viennacl::op_assign(), viennacl::linalg::prod(trans(A),y));\n        device_specific::generate_enqueue_statement(statement, statement.array()[0]);\n        viennacl::backend::finish();\n        CHECK_RESULT(cx,x,x=trans(A)*y)\n    }\n\n    {\n        std::cout << \"y = reduce_rows<add>(A)...\" << std::endl;\n        for (unsigned int i = 0; i < size1; ++i){\n            NumericT acc = cA(i,0);\n            for (unsigned int j = 1; j < size2; ++j){\n                acc += cA(i,j);\n            }\n            cy(i) = acc;\n        }\n        viennacl::scheduler::statement statement(y, viennacl::op_assign(), viennacl::linalg::reduce_rows<viennacl::op_add>(A));\n        //std::cout << statement << std::endl;\n\n        device_specific::generate_enqueue_statement(statement, statement.array()[0]);\n        viennacl::backend::finish();\n        CHECK_RESULT(cy,y,y = reduce_rows<max>(A))\n    }\n\n    {\n        std::cout << \"x = reduce_columns<add>(A)...\" << std::endl;\n        for (unsigned int j = 0; j < size2; ++j){\n            NumericT acc = cA(0,j);\n            for (unsigned int i = 1; i < size1; ++i){\n                acc += cA(i,j);\n            }\n            cx(j) = acc;\n        }\n        viennacl::scheduler::statement statement(x, viennacl::op_assign(), viennacl::linalg::reduce_columns<viennacl::op_add>(A));\n        device_specific::generate_enqueue_statement(statement, statement.array()[0]);\n        viennacl::backend::finish();\n        CHECK_RESULT(cx,x,x = reduce_columns<max>(A))\n    }\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 :: Generated BLAS2\" << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << std::endl;\n\n    int retval = EXIT_SUCCESS;\n\n    std::cout << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << std::endl;\n    {\n        double epsilon = 1.0E-4;\n        std::cout << \"# Testing setup:\" << std::endl;\n        std::cout << \"  numeric: float\" << std::endl;\n        std::cout << \"  --------------\" << std::endl;\n        std::cout << \"  Row-Major\"      << std::endl;\n        std::cout << \"  --------------\" << std::endl;\n        retval = test<float, viennacl::row_major> (epsilon);\n        std::cout << \"  --------------\" << std::endl;\n        std::cout << \"  Column-Major\"   << std::endl;\n        std::cout << \"  --------------\" << std::endl;\n        retval &= test<float, viennacl::column_major> (epsilon);\n\n        if ( retval == EXIT_SUCCESS )\n            std::cout << \"# Test passed\" << std::endl;\n        else\n            return retval;\n    }\n\n//    std::cout << std::endl;\n//    std::cout << \"----------------------------------------------\" << std::endl;\n//    std::cout << std::endl;\n//#ifdef VIENNACL_WITH_OPENCL\n//   if ( viennacl::ocl::current_device().double_support() )\n//#endif\n//    {\n//        double epsilon = 1.0E-4;\n//        std::cout << \"# Testing setup:\" << std::endl;\n//        std::cout << \"  numeric: double\" << std::endl;\n//        std::cout << \"  --------------\" << std::endl;\n//        std::cout << \"  Row-Major\"      << std::endl;\n//        std::cout << \"  --------------\" << std::endl;\n//        retval = test<double, viennacl::row_major> (epsilon);\n//        std::cout << \"  --------------\" << std::endl;\n//        std::cout << \"  Column-Major\"   << std::endl;\n//        std::cout << \"  --------------\" << std::endl;\n//        retval &= test<double, viennacl::column_major> (epsilon);\n\n//        if ( retval == EXIT_SUCCESS )\n//            std::cout << \"# Test passed\" << std::endl;\n//        else\n//            return retval;\n//    }\n}\n", "meta": {"hexsha": "03136c041bb166feb2ecb64eee01f864c66c9e3a", "size": 8802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/generator_blas2.cpp", "max_stars_repo_name": "denis14/ViennaCL-1.5.2", "max_stars_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/generator_blas2.cpp", "max_issues_repo_name": "denis14/ViennaCL-1.5.2", "max_issues_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/generator_blas2.cpp", "max_forks_repo_name": "denis14/ViennaCL-1.5.2", "max_forks_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3409090909, "max_line_length": 130, "alphanum_fraction": 0.5089752329, "num_tokens": 2419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5753788801458486}}
{"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": "//  Copyright (C) Eric Niebler 2005.\n//  Copyright (C) Pieter Bastiaan Ober 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#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/rolling_moment.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace accumulators;\n\ntemplate<typename T>\nvoid assert_is_double(T const &)\n{\n    BOOST_MPL_ASSERT((is_same<T, double>));\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// test_rolling_moment\n//\n\nvoid test_rolling_second_moment()\n{\n    accumulator_set<int, stats<tag::rolling_moment<2> > > acc(tag::rolling_moment<2>::window_size = 3);\n\n    acc(2);\n\n    BOOST_CHECK_CLOSE(rolling_moment<2>(acc), 4.0/1 ,1e-5);\n\n    acc(4);\n\n    BOOST_CHECK_CLOSE(rolling_moment<2>(acc), (4.0 + 16.0)/2, 1e-5);\n\n    acc(5);\n\n    BOOST_CHECK_CLOSE(rolling_moment<2>(acc), (4.0 + 16.0 + 25.0)/3, 1e-5);\n\n    acc(6);\n\n    BOOST_CHECK_CLOSE(rolling_moment<2>(acc), (16.0 + 25.0 + 36.0)/3, 1e-5);\n\n    assert_is_double(rolling_moment<2>(acc));\n}\n\nvoid test_rolling_fifth_moment()\n{\n    accumulator_set<int, stats<tag::rolling_moment<5> > > acc(tag::rolling_moment<2>::window_size = 3);\n\n    acc(2);\n\n    BOOST_CHECK_CLOSE(rolling_moment<5>(acc), 32.0/1, 1e-5);\n\n    acc(3);\n\n    BOOST_CHECK_CLOSE(rolling_moment<5>(acc), (32.0 + 243.0)/2, 1e-5);\n\n    acc(4);\n\n    BOOST_CHECK_CLOSE(rolling_moment<5>(acc), (32.0 + 243.0 + 1024.0)/3, 1e-5);\n\n    acc(5);\n\n    BOOST_CHECK_CLOSE(rolling_moment<5>(acc), (243.0 + 1024.0 + 3125.0)/3, 1e-5);\n\n    assert_is_double(rolling_moment<5>(acc));\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"rolling moment test\");\n\n    test->add(BOOST_TEST_CASE(&test_rolling_second_moment));\n    test->add(BOOST_TEST_CASE(&test_rolling_fifth_moment));\n\n    return test;\n}", "meta": {"hexsha": "9a25920679712b09c6f6e091fcbcf5d0518fa772", "size": 2284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost/libs/accumulators/test/rolling_moment.cpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/boost/libs/accumulators/test/rolling_moment.cpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/boost/libs/accumulators/test/rolling_moment.cpp", "max_forks_repo_name": "alexhenrie/poedit", "max_forks_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 26.8705882353, "max_line_length": 103, "alphanum_fraction": 0.6501751313, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.57537887510076}}
{"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": "\n#include <iostream>\n#include <algorithm>\n#include <cmath>        // abs() for float, and fabs()\n#include <math.h>       // pow()\n#include <random>\n#include <climits>\n\n#include <Eigen/Dense>\n\n#define print(var) \\\n  std::cout<<#var\" = \"<<(var)<<std::endl;\n#define printstr(str) \\\n  std::cout<<str<<std::endl;\n#define printLine() \\\n  std::cout<<\"============================\"<<std::endl;\n", "meta": {"hexsha": "7138a4a8d474f5c88a34f3b2794ce7c8e5c1a14e", "size": 386, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "eigen/pso.hpp", "max_stars_repo_name": "keit0222/various-pso-examples", "max_stars_repo_head_hexsha": "2a680ae8c66c0c4fb92e96cbc0e131231aa343ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-19T09:39:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-19T09:39:47.000Z", "max_issues_repo_path": "eigen/pso.hpp", "max_issues_repo_name": "keit0222/various-pso-examples", "max_issues_repo_head_hexsha": "2a680ae8c66c0c4fb92e96cbc0e131231aa343ae", "max_issues_repo_licenses": ["MIT"], "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/pso.hpp", "max_forks_repo_name": "keit0222/various-pso-examples", "max_forks_repo_head_hexsha": "2a680ae8c66c0c4fb92e96cbc0e131231aa343ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-02T14:38:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-02T14:38:08.000Z", "avg_line_length": 22.7058823529, "max_line_length": 55, "alphanum_fraction": 0.5621761658, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5753727856980131}}
{"text": "#include <iostream>\n#include <string>\n#include <fstream>\n#include \"partitionCounting.h\"\n#include \"counting.h\"\n#include \"utils.h\"\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <chrono>\ntypedef std::chrono::high_resolution_clock Clock;\n\n// define the format you want, you only need one instance of this...\nconst static IOFormat CSVFormat(StreamPrecision, DontAlignCols, \", \", \"\\n\");\n\nstatic void show_usage(std::string name)\n{\n    std::cerr << \"Usage: \" << name << \" <option(s)>\"\n              << \"Options:\\n\"\n              << \"\\t-h,--help\\t\\tShow this help message\\n\"\n              << \"\\t-n, NUM\\tSpecify the number n from which the partitions are generated. Default: 20.\"\n              << std::endl;\n}\n\n// To write the results in a CSV file\nvoid writeToCSVfile(const string &name, const MatrixXUL &matrix) {\n    std::ofstream file(name.c_str());\n    file << matrix.format(CSVFormat);\n}\n\nint main(int argc, char *argv[]) {\n  // n is the maximum sum of the elements of the compositions\n  int n=20;\n  for (int i = 1; i < argc; ++i) {\n    std::string arg = argv[i];\n    if ((arg == \"-h\") || (arg == \"--help\")) {\n        show_usage(argv[0]);\n        return 0;\n    } else if ((arg == \"-n\")) {\n        if (i + 1 < argc) { // Make sure we aren't at the end of argv!\n            n = atoi(argv[++i]); // Increment 'i' so we don't get the argument as the next argv[i].\n        } else { // Uh-oh, there was no argument to the destination option.\n            std::cerr << \"The -n option requires one argument.\" << std::endl;\n            return 1;\n        }\n    } else {\n      show_usage(argv[0]);\n      return 1;\n    }\n  }\n\n  // Definition of the alpha parameter, choose a value in (0,2)\n  double alpha = 20.0;\n  // This object will be called for counting the partitions\n  Counter ct(n);\n  // Partition generation\n  cout << \"[INF] Generating partitions of n=\" << n << std::endl;\n  // Enumerate all the partitions of n. They will come in ascending lexicographical order\n  std::list<std::vector<unsigned int> >partitionsOfN;\n  ascPartition(n,partitionsOfN);\n\n  // Add the trivial one because the algorithm does not give it as an output\n  std::vector<unsigned int> trivialPartition; trivialPartition.push_back(n);\n  partitionsOfN.push_back(trivialPartition);\n\n  // Number of partitions\n  int dim = partitionsOfN.size();\n  cout << \"[INF] Number of partitions:\" << dim << std::endl;\n\n  // Esta es la parte que nos interesa, vamos a estudiar una cadena de Markov con valores en las composiciones\n  // (lo que llamo composiciones es nuestra manera de representar las particiones con el n\u00famero\n  // de bloques de cada tama\u00f1o, en plan (2,1,1...) )\n\n  cout << \"[INF] Filling Rmatrix\" << endl;\n  // Definition of the state matrix, the rows Rmatrix[i] are compositions\n  // Rmatrix= np.zeros((dim,n), dtype=int)\n  MatrixXi Rmatrix(dim,n);\n  int i=0;\n  // Enumerate all the generated partitions\n  for (auto partition: partitionsOfN) {\n    // Take the partition one by one\n    // Count how many elements in the partition have the value j+1.\n    for (int j=0; j<n; j++) {\n      Rmatrix(i,j) = countElements(partition,j+1);\n    }\n    i++;\n  }\n  cout << Rmatrix << endl;\n\n  // Precompute all the sum(R[i])\n  cout << \"[INF] Computing rowwise sums\" << endl;\n  MatrixXi S = Rmatrix.rowwise().sum();\n\n  // Constructs all the compositions\n  std::cout << \"[INF] Building the list of partition descriptors (compositions)\" << std::endl;\n  std::vector<partitionDescriptor> P;\n  for (auto partition: partitionsOfN) {\n    P.push_back(partitionDescriptor(partition,n));\n  }\n  auto t1 = Clock::now();\n\n  // Precompute all the Cbr or read them from file\n  std::cout << \"[INF] Computing counts\" << std::endl;\n  MatrixXUL Combin(dim,dim);\n  bool computeCombin = true;\n  if (computeCombin)\n    for (int j=0; j<dim; j++) {\n      printBar((float)j/dim);\n      ct.resetValues();\n      for (int i=0; i<j; i++) {\n        Combin(i,j)=ct.recursiveCount_DescBreak(P[i],P[j]);\n      }\n    }\n  auto t2 = Clock::now();\n  std::cout << std::endl;\n  std::cout << \"[INF] Took: \" << std::chrono::duration_cast<std::chrono::seconds>(t2 - t1).count() << \" seconds\" << std::endl;\n\n  Counter::printCalls();\n\n  std::string fileName;\n  std::stringstream ss(fileName);\n  ss << \"Combin-\" << setw(3) << setfill('0') << n << \".csv\";\n  writeToCSVfile(ss.str(),Combin);\n\n  return 0;\n\n//      df = pd.DataFrame(data=Combin.astype(float))\n//      df.to_csv('outfile' + str(n) + '.csv', sep=' ', header=False, float_format='%.10f', index=False)\n//  else\n//  //    try:\n//          df  =pd.read_csv('outfile' + str(n) + '.csv', delim_whitespace=True, header=None)\n//          Combin=df.astype(float).values\n//          computeCombin = False\n//      except IOError as e:\n//          print(\"Error in reading file\")\n//          print(e)\n//  printCalls()\n//  print(Combin)\n//  print(Combin.min())\n//  print(Combin.max())\n\n}\n", "meta": {"hexsha": "d5a03d63cbb6e59b2bb018d4dd6eb9fa83363ba8", "size": 4932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "jbhayet/SFS", "max_stars_repo_head_hexsha": "c4681b6bd5bc1746eca0863c527c9b3e1205f42c", "max_stars_repo_licenses": ["Apache-2.0"], "max_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": "jbhayet/SFS", "max_issues_repo_head_hexsha": "c4681b6bd5bc1746eca0863c527c9b3e1205f42c", "max_issues_repo_licenses": ["Apache-2.0"], "max_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": "jbhayet/SFS", "max_forks_repo_head_hexsha": "c4681b6bd5bc1746eca0863c527c9b3e1205f42c", "max_forks_repo_licenses": ["Apache-2.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.1006711409, "max_line_length": 126, "alphanum_fraction": 0.6267234388, "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5753727780570977}}
{"text": "#define BOOST_TEST_MAIN\n#if !defined(WIN32)\n#define BOOST_TEST_DYN_LINK\n#endif\n\n#include \"Parser.h\"\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(unary_input)\n{\n    Parser const parser(\"2\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 2);\n}\n\nBOOST_AUTO_TEST_CASE(valid_input)\n{\n    Parser const parser(\"2 + 3\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 5);\n}\n\nBOOST_AUTO_TEST_CASE(check_precendence)\n{\n    Parser const parser(\"2 + 3 * 5\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 17);\n}\n\nBOOST_AUTO_TEST_CASE(paranthesis)\n{\n    Parser const parser(\"(2 + 3) * 5\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 25);\n}\n\nBOOST_AUTO_TEST_CASE(parantheses)\n{\n    Parser const parser(\"(2 + 3) * 5\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 25);\n}\n\nBOOST_AUTO_TEST_CASE(nested_parantheses)\n{\n    Parser const parser(\"(2 * (3 + 2)) * 5\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 50);\n}\n\nBOOST_AUTO_TEST_CASE(complex_parantheses)\n{\n    Parser const parser(\"(2 * (3 + 2)) * 5 + 5 / (3 - 1)\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 52);\n}\n\nBOOST_AUTO_TEST_CASE(division)\n{\n    Parser const parser(\"6/2\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 3);\n}\n\nBOOST_AUTO_TEST_CASE(integer_division)\n{\n    Parser const parser(\"1/2\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(integer_division_rounding)\n{\n    Parser const parser(\"1/2+1/2\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(integer_division_rounding_2)\n{\n    Parser const parser(\"2/6*3\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(arithmetic)\n{\n    Parser const parser(\"(4 + 5 * (7 - 3)) - 2\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 22);\n}\n\nBOOST_AUTO_TEST_CASE(arithmetic_2)\n{\n    Parser const parser(\"4+5+7/2\");\n    BOOST_CHECK_EQUAL(parser.createAst()->evaluate(), 12);\n}\n", "meta": {"hexsha": "55c63d34a2247caae5ecbba4487f39d50c3fe2b7", "size": 1965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/parser/ValidInputsTest.cpp", "max_stars_repo_name": "vedant1811/arithmetic-parser", "max_stars_repo_head_hexsha": "fcaab37d4317b28dbe0c019eeabf3f565cf412c3", "max_stars_repo_licenses": ["MIT"], "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/parser/ValidInputsTest.cpp", "max_issues_repo_name": "vedant1811/arithmetic-parser", "max_issues_repo_head_hexsha": "fcaab37d4317b28dbe0c019eeabf3f565cf412c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/parser/ValidInputsTest.cpp", "max_forks_repo_name": "vedant1811/arithmetic-parser", "max_forks_repo_head_hexsha": "fcaab37d4317b28dbe0c019eeabf3f565cf412c3", "max_forks_repo_licenses": ["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.8488372093, "max_line_length": 59, "alphanum_fraction": 0.6956743003, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7185943865443349, "lm_q1q2_score": 0.5753727780570976}}
{"text": "#include \"ocv_kmeans_wrapper.h\"\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <Eigen/Dense>\nvoid ocv_kmeans(const Eigen::MatrixXd& F, const int num_labels, const int num_iter, Eigen::MatrixXd& D, Eigen::VectorXi& labels){ \n\t// const Eigen::MatrixXd& F, //data. Every column is a feature\n\t// const int num_labels, // number of clusters\n\t// const int num_iter, // number of iterations\n\t// Eigen::MatrixXd& D, // dictionary of clusters (every column is a cluster)\n\t// Eigen::VectorXi& labels){ // map D to F.\n\n\tassert(sizeof(float) == 4);\n\tcv::Mat cv_F(F.rows(), F.cols(), CV_32F);\n\tfor (int i = 0; i < F.rows(); ++i){\n\t    for (int j = 0; j < F.cols(); ++j){\n\t        cv_F.at<float>(i,j) = F(i,j);\n\t    }\n\t}\n\n\tcv::Mat cv_labels;\n\tcv::Mat cv_centers;\n\tcv::TermCriteria criteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 1000, 0.01);\n\tcv::kmeans(cv_F, num_labels, cv_labels, criteria, num_iter, cv::KMEANS_PP_CENTERS, cv_centers);\n\n\tint num_points = F.rows();\n\tint num_features = F.cols();\n\t// D.resize(num_features, num_labels);\n\n\t// for (int i=0; i<cv_centers.rows; ++i)\n\t//     for (int j=0; j<cv_centers.cols; ++j)\n\t//         D(j,i) = cv_centers.at<float>(i,j);\n\n\tlabels.resize(num_points);\n\tfor (int i=0; i<labels.rows(); ++i){\n\t    labels(i) = cv_labels.at<int>(i,0);\n\t}\n}", "meta": {"hexsha": "d53fde6b7fa00b9e7aec762e4d8f3e59155329a1", "size": 1294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PreProcessing/ocv_kmeans_wrapper.cpp", "max_stars_repo_name": "itsvismay/fast_muscles", "max_stars_repo_head_hexsha": "86c9d93bd14da92ce2140bf47857810b579e7b2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T22:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T01:38:52.000Z", "max_issues_repo_path": "PreProcessing/ocv_kmeans_wrapper.cpp", "max_issues_repo_name": "alecjacobson/fast_muscles", "max_issues_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-08T21:10:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-08T21:10:36.000Z", "max_forks_repo_path": "PreProcessing/ocv_kmeans_wrapper.cpp", "max_forks_repo_name": "alecjacobson/fast_muscles", "max_forks_repo_head_hexsha": "92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-08T21:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-08T21:11:10.000Z", "avg_line_length": 34.972972973, "max_line_length": 130, "alphanum_fraction": 0.6499227202, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5753569614295628}}
{"text": "#include <iostream>\n#include <cmath>\nusing namespace std; \n#include <Eigen/Core>\n#include <Eigen/Geometry>\n \n// \u674e\u7fa4\u674e\u4ee3\u6570 \u5e93 \n#include \"sophus/so3.hpp\"\n#include \"sophus/se3.hpp\"\n\n#include<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": "#pragma once\r\n#ifndef KNEIGHBOR_HPP_\r\n#define KNEIGHBOR_HPP_\r\n\r\n// #define CGAL_LINKED_WITH_TBB \r\n\r\n#include <CGAL/Simple_cartesian.h>\r\n#include <CGAL/point_generators_3.h>\r\n#include <CGAL/Orthogonal_k_neighbor_search.h>\r\n#include <CGAL/Search_traits_3.h>\r\n#include <CGAL/Search_traits_adapter.h>\r\n#include <CGAL/property_map.h>\r\n#include <boost/iterator/zip_iterator.hpp>\r\n#include <iostream>\r\n#include <utility>\r\n#include <vector>\r\n\r\n#ifdef CGAL_LINKED_WITH_TBB \r\n\t#include <tbb/blocked_range.h>\r\n\t#include <tbb/parallel_for.h>\r\n#endif\r\n\r\nusing std::vector;\r\n//glog\r\n#include <glog/logging.h>\r\n\r\nclass kNeighbor\r\n{\r\n\ttypedef CGAL::Simple_cartesian<double> K;\r\n\ttypedef K::Point_3 Point_d;\r\n\ttypedef CGAL::Search_traits_3<K> TreeTraits;\r\n\r\n\ttypedef boost::tuple<Point_d, int>  Point_and_int;\r\n\ttypedef CGAL::Search_traits_adapter<Point_and_int,\r\n\t\tCGAL::Nth_of_tuple_property_map<0, Point_and_int>,\r\n\t\tTreeTraits>                     Traits;\r\n\ttypedef CGAL::Orthogonal_k_neighbor_search<Traits> Neighbor_search;\r\n\ttypedef Neighbor_search::Tree Tree;\r\n\r\npublic:\r\n\tkNeighbor() {\r\n\t\tLOG(INFO) << \"Init\";\r\n\t\tpoints_.resize(0);\r\n\t\tindices_.resize(0);\r\n\t\tk_ = 1;\r\n\t};\r\n\r\n\tkNeighbor(std::vector<Point_d> points)\r\n\t{\r\n\t\tLOG(INFO) << \"Init and setInputCloud\";\r\n\t\tpoints_ = points;\r\n\t\tk_ = 1;\r\n\r\n\t\tbuild_tree_();\r\n\t}\r\n\r\n\tkNeighbor(std::vector<Eigen::Vector3f> points)\r\n\t{\r\n\t\tLOG(INFO) << \"Init and setInputCloud\";\r\n\t\tint i = 0;\r\n\t\tfor (auto it : points) {\r\n\t\t\tpoints_.push_back(Point_d(it(0), it(1), it(2)));\r\n\t\t\tindices_.push_back(i);\r\n\t\t\ti++;\r\n\t\t}\r\n\t\tk_ = 1;\r\n\r\n\t\tbuild_tree_();\r\n\t}\r\n\t\r\n\tkNeighbor(std::vector<Eigen::Vector4f> points)\r\n\t{\r\n\t\tLOG(INFO) << \"Init and setInputCloud\";\r\n\t\tint i = 0;\r\n\t\tfor (auto it : points) {\r\n\t\t\tpoints_.push_back(Point_d(it(0), it(1), it(2)));\r\n\t\t\tindices_.push_back(i);\r\n\t\t\ti++;\r\n\t\t}\r\n\t\tk_ = 1;\r\n\r\n\t\tbuild_tree_();\r\n\t}\r\n\t~kNeighbor() { };\r\n\r\n\ttemplate <typename EigenT>\r\n\tvoid setInputData(std::vector<EigenT> points) {\r\n\t\tLOG(INFO) << \"set input Data \";\r\n\t\tint i = 0;\r\n\t\tfor (auto it : points) {\r\n\t\t\tpoints_.push_back(Point_d(it(0), it(1), it(2)));\r\n\t\t\tindices_.push_back(i);\r\n\t\t\ti++;\r\n\t\t}\r\n\t\tk_ = 1;\r\n\r\n\t\tbuild_tree_();\r\n\t}\r\n\r\n\t// search knn\r\n\tvoid searchK(Point_d t, size_t k);\r\n\t\r\n\ttemplate <typename EigenT>\r\n\tvoid searchK(EigenT t, size_t k);\r\n\t\r\n\t// search rnn\r\n\tvoid searchR(Point_d t, float r);\r\n\ttemplate <typename EigenT>\r\n\tvoid searchR(EigenT t, float r);\r\n\r\n\t// get quary \r\n\tstd::vector<Eigen::Vector4f> getQuary() { \r\n\t\tLOG_IF(INFO, quary_.size() != 0) << \"get knn quary successful\";\r\n\t\tLOG_IF(INFO, quary_.size() == 0) << \"get knn quary failed\";\r\n\t\treturn quary_; };\r\n\t\r\nprivate:\r\n\t// \r\n\tsize_t k_;\r\n\r\n\t// store the raw point cloud\r\n\tstd::vector<Point_d> points_;\r\n\t// the indices of points\r\n\tstd::vector<int> indices_;\r\n\r\n\t// the result of knn or rnn\r\n\tstd::vector<Eigen::Vector4f> quary_;\r\n\r\n\t// kdtree\r\n\tTree tree_;\r\n\r\n\tbool isIndices_ = true;\r\n\r\n\t// init tree\r\n\tbool build_tree_();\r\n};\r\n\r\ntemplate <typename EigenT>\r\nvoid kNeighbor::searchK(EigenT t, size_t k)\r\n{\r\n\tPoint_d p(t(0), t(1), t(2));\r\n\tsearchK(p, k);\r\n}\r\n\r\nvoid kNeighbor::searchK(Point_d t, size_t k)\r\n{\r\n\tLOG(INFO) << \"search K(\" << k << \")nn  P(\" << t << \")\" ;\r\n\tquary_.clear();\r\n\r\n\tNeighbor_search search(tree_, t, k);\r\n\r\n\tfor (Neighbor_search::iterator it = search.begin(); it != search.end(); ++it) {\r\n\t\tint indices = boost::get<1>(it->first);\r\n\t\tEigen::Vector4f point(boost::get<0>(it->first).x(), boost::get<0>(it->first).y(), boost::get<0>(it->first).z(), indices);\r\n\r\n\t\tquary_.push_back(point);\r\n\t}\r\n}\r\n\r\nvoid kNeighbor::searchR(Point_d t, float r)\r\n{\r\n\tLOG(INFO) << \"search R(\" << r << \")nn  P(\" << t << \")\";\r\n\tquary_.clear();\r\n\r\n\tNeighbor_search search(tree_, t, 20);\r\n\r\n\tfor (Neighbor_search::iterator it = search.begin(); it != search.end(); ++it) {\r\n\t\tint indices = boost::get<1>(it->first);\r\n\t\tEigen::Vector4f point(boost::get<0>(it->first).x(), boost::get<0>(it->first).y(), boost::get<0>(it->first).z(), indices);\r\n\r\n\t\tif (it->second < r) quary_.push_back(point);\r\n\t}\r\n}\r\n\r\nbool kNeighbor::build_tree_()\r\n{\r\n\tif (points_.size() == 0) {\r\n\t\tLOG(WARNING) << \"No input points, tree build failed\";\r\n\t\treturn false;\r\n\t}\r\n\tif (!tree_.is_built()) {\r\n\t\t// if (isIndices_ == false)\r\n\t\t// \ttree_.insert(points_.begin(), points_.end());\r\n\t\tif (isIndices_ == true)\r\n\t\t \ttree_.insert(boost::make_zip_iterator(boost::make_tuple(points_.begin(), indices_.begin())),\r\n\t\t \t\tboost::make_zip_iterator(boost::make_tuple(points_.end(), indices_.end())));\r\n\t\t#ifdef CGAL_LINKED_WITH_TBB \r\n\t\t\ttree_.build<CGAL::Parallel_tag>();\r\n\t\t#else\r\n\t\t\ttree_.build<CGAL::Sequential_tag>();\r\n\t\t#endif \r\n\t\tLOG(INFO) << \"tree build successful\";\r\n\t}\r\n\tLOG(INFO) << \"tree has built\";\r\n\treturn true;\r\n}\r\n\r\ntemplate <typename EigenT>\r\nvoid kNeighbor::searchR(EigenT t, float r)\r\n{\r\n\tPoint_d p(t(0), t(1), t(2));\r\n\tsearchR(p, r);\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "fe1d1e7349f0b0f342a953c370038af716c3823b", "size": 4824, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kNeighbor.hpp", "max_stars_repo_name": "GreenAvocado92/knn", "max_stars_repo_head_hexsha": "1a9eea59037a2fa45c2334043f510b8545ed2020", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kNeighbor.hpp", "max_issues_repo_name": "GreenAvocado92/knn", "max_issues_repo_head_hexsha": "1a9eea59037a2fa45c2334043f510b8545ed2020", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kNeighbor.hpp", "max_forks_repo_name": "GreenAvocado92/knn", "max_forks_repo_head_hexsha": "1a9eea59037a2fa45c2334043f510b8545ed2020", "max_forks_repo_licenses": ["Apache-2.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.4174757282, "max_line_length": 124, "alphanum_fraction": 0.6310116086, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5753569569455097}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\nusing namespace std;\n\n#include <boost/range/algorithm_ext/push_back.hpp>\n#include <boost/range/irange.hpp>\n\n#include <catch2/catch.hpp>\n#include <cpp_algs.hpp>\n\nTEST_CASE(\"Sorting Alorithms test\") {\n\n    auto rng = std::default_random_engine{};\n\n    std::vector<int> v_int;\n    boost::push_back(v_int, boost::irange<int>(1, 1001));\n    REQUIRE(v_int.size() == 1000);\n    std::shuffle(std::begin(v_int), std::end(v_int), rng);\n    REQUIRE(!std::is_sorted(std::begin(v_int), std::end(v_int)));\n\n    std::vector<char> v_char;\n    for (int i = 0; i < 1000; i++) {\n        char c = i % 255;\n        v_char.push_back(c);\n    }\n    REQUIRE(v_char.size() == 1000);\n    std::shuffle(std::begin(v_char), std::end(v_char), rng);\n    REQUIRE(!std::is_sorted(std::begin(v_char), std::end(v_char)));\n\n    std::vector<double> v_double;\n    boost::push_back(v_double, boost::irange<double>(1.0, 1001.0));\n    REQUIRE(v_double.size() == 1000);\n    std::shuffle(std::begin(v_double), std::end(v_double), rng);\n    REQUIRE(!std::is_sorted(std::begin(v_double), std::end(v_double)));\n\n    SECTION(\"Bubble Sort\") {\n        al::bubbleSort<int>(v_int);\n        REQUIRE(std::is_sorted(std::begin(v_int), std::end(v_int)));\n\n        al::bubbleSort<char>(v_char);\n        REQUIRE(std::is_sorted(std::begin(v_char), std::end(v_char)));\n\n        al::bubbleSort<double>(v_double);\n        REQUIRE(std::is_sorted(std::begin(v_double), std::end(v_double)));\n    }\n\n    SECTION(\"Heap Sort\") {\n        al::heapSort<int>(v_int);\n        REQUIRE(std::is_sorted(std::begin(v_int), std::end(v_int)));\n\n        al::heapSort<char>(v_char);\n        REQUIRE(std::is_sorted(std::begin(v_char), std::end(v_char)));\n\n        al::heapSort<double>(v_double);\n        REQUIRE(std::is_sorted(std::begin(v_double), std::end(v_double)));\n    }\n\n    SECTION(\"Insertion Sort\") {\n        al::insertionSort<int>(v_int);\n        REQUIRE(std::is_sorted(std::begin(v_int), std::end(v_int)));\n\n        al::insertionSort<char>(v_char);\n        REQUIRE(std::is_sorted(std::begin(v_char), std::end(v_char)));\n\n        al::insertionSort<double>(v_double);\n        REQUIRE(std::is_sorted(std::begin(v_double), std::end(v_double)));\n    }\n\n    SECTION(\"Merge Sort\") {\n        al::mergeSort<int>(v_int);\n        REQUIRE(std::is_sorted(std::begin(v_int), std::end(v_int)));\n\n        al::mergeSort<char>(v_char);\n        REQUIRE(std::is_sorted(std::begin(v_char), std::end(v_char)));\n\n        al::mergeSort<double>(v_double);\n        REQUIRE(std::is_sorted(std::begin(v_double), std::end(v_double)));\n    }\n\n    SECTION(\"Quick Sort\") {\n        al::quickSort<int>(v_int);\n        REQUIRE(std::is_sorted(std::begin(v_int), std::end(v_int)));\n\n        al::quickSort<char>(v_char);\n        REQUIRE(std::is_sorted(std::begin(v_char), std::end(v_char)));\n\n        al::quickSort<double>(v_double);\n        REQUIRE(std::is_sorted(std::begin(v_double), std::end(v_double)));\n    }\n\n    SECTION(\"Selection Sort\") {\n        al::selectionSort<int>(v_int);\n        REQUIRE(std::is_sorted(std::begin(v_int), std::end(v_int)));\n\n        al::selectionSort<char>(v_char);\n        REQUIRE(std::is_sorted(std::begin(v_char), std::end(v_char)));\n\n        al::selectionSort<double>(v_double);\n        REQUIRE(std::is_sorted(std::begin(v_double), std::end(v_double)));\n    }\n\n    SECTION(\"Shell Sort\") {\n        al::shellSort<int>(v_int);\n        REQUIRE(std::is_sorted(std::begin(v_int), std::end(v_int)));\n\n        al::shellSort<char>(v_char);\n        REQUIRE(std::is_sorted(std::begin(v_char), std::end(v_char)));\n\n        al::shellSort<double>(v_double);\n        REQUIRE(std::is_sorted(std::begin(v_double), std::end(v_double)));\n    }\n}", "meta": {"hexsha": "c31abac3ab27770a5f0336a7d2692e95f16e48e0", "size": 3729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_al_sort.cpp", "max_stars_repo_name": "pskrunner14/cpp-practice", "max_stars_repo_head_hexsha": "c59928bb9b91204588a0bafdc9f42deaacc64d29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T14:17:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-02T00:20:52.000Z", "max_issues_repo_path": "tests/test_al_sort.cpp", "max_issues_repo_name": "pskrunner14/cpp-practice", "max_issues_repo_head_hexsha": "c59928bb9b91204588a0bafdc9f42deaacc64d29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-28T19:45:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-28T19:50:02.000Z", "max_forks_repo_path": "tests/test_al_sort.cpp", "max_forks_repo_name": "pskrunner14/cpp-practice", "max_forks_repo_head_hexsha": "c59928bb9b91204588a0bafdc9f42deaacc64d29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-29T19:58:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-29T19:58:08.000Z", "avg_line_length": 32.7105263158, "max_line_length": 74, "alphanum_fraction": 0.6170555109, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.5753374256760573}}
{"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 * Copyright 1998-2015 by authors (see AUTHORS.txt)                        *\n *                                                                         *\n *   This file is part of LuxRender.                                       *\n *                                                                         *\n * Licensed under the Apache License, Version 2.0 (the \"License\");         *\n * you may not use this file except in compliance with the License.        *\n * You may obtain a copy of the License at                                 *\n *                                                                         *\n *     http://www.apache.org/licenses/LICENSE-2.0                          *\n *                                                                         *\n * Unless required by applicable law or agreed to in writing, software     *\n * distributed under the License is distributed on an \"AS IS\" BASIS,       *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*\n * See the License for the specific language governing permissions and     *\n * limitations under the License.                                          *\n ***************************************************************************/\n\n#include <boost/lexical_cast.hpp>\n#include <boost/serialization/export.hpp>\n\n#include \"slg/film/film.h\"\n#include \"slg/film/imagepipeline/plugins/tonemaps/reinhard02.h\"\n\nusing namespace std;\nusing namespace luxrays;\nusing namespace slg;\n\n//------------------------------------------------------------------------------\n// Reinhard02 tone mapping\n//------------------------------------------------------------------------------\n\nBOOST_CLASS_EXPORT_IMPLEMENT(slg::Reinhard02ToneMap)\n\nvoid Reinhard02ToneMap::Apply(const Film &film, Spectrum *pxls, std::vector<bool> &pixelsMask) const {\n\tRGBColor *rgbPixels = (RGBColor *)pxls;\n\n\tconst float alpha = .1f;\n\tconst u_int pixelCount = film.GetWidth() * film.GetHeight();\n\n\tfloat Ywa = 0.f;\n\tfor (u_int i = 0; i < pixelCount; ++i) {\n\t\tif (pixelsMask[i] && !rgbPixels[i].IsInf())\n\t\t\tYwa += logf(max(rgbPixels[i].Y(), 1e-6f));\n\t}\n\tif (pixelCount > 0)\n\t\tYwa = expf(Ywa / pixelCount);\n\n\t// Avoid division by zero\n\tif (Ywa == 0.f)\n\t\tYwa = 1.f;\n\n\tconst float invB2 = burn > 0.f ? 1.f / (burn * burn) : 1e5f;\n\tconst float scale = alpha / Ywa;\n\tconst float preS = scale / preScale;\n\tconst float postS = scale * postScale;\n\n\tfor (u_int i = 0; i < pixelCount; ++i) {\n\t\tif (pixelsMask[i]) {\n\t\t\tconst float ys = rgbPixels[i].Y() * preS;\n\t\t\t// Note: I don't need to convert to XYZ and back because I'm only\n\t\t\t// scaling the value.\n\t\t\trgbPixels[i] *= postS * (1.f + ys * invB2) / (1.f + ys);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "7dd8c2258bb6e78cbef63130fa39a915aed7c740", "size": 2741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/slg/film/imagepipeline/plugins/tonemaps/reinhard02.cpp", "max_stars_repo_name": "DavidBluecame/LuxRays", "max_stars_repo_head_hexsha": "be0f5228b8b65268278a6c6a1c98564ebdc27c05", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/slg/film/imagepipeline/plugins/tonemaps/reinhard02.cpp", "max_issues_repo_name": "DavidBluecame/LuxRays", "max_issues_repo_head_hexsha": "be0f5228b8b65268278a6c6a1c98564ebdc27c05", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/slg/film/imagepipeline/plugins/tonemaps/reinhard02.cpp", "max_forks_repo_name": "DavidBluecame/LuxRays", "max_forks_repo_head_hexsha": "be0f5228b8b65268278a6c6a1c98564ebdc27c05", "max_forks_repo_licenses": ["Apache-2.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.9104477612, "max_line_length": 102, "alphanum_fraction": 0.4823057278, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5750963228394681}}
{"text": "#ifndef LSHFUNC_ITQ_HPP\n#define LSHFUNC_ITQ_HPP\n\n#ifndef EIGEN_CONFIG_H_\n#define EIGEN_CONFIG_H_\n\n#include <boost/serialization/array.hpp>\n// w.r.t Eigen_3.2.4/Eigen/Core\n#define EIGEN_DENSEBASE_PLUGIN \"../../../../EigenDenseBaseAddons.hpp\"\n#include <Eigen/Core>\n#endif // EIGEN_CONFIG_H_\n\n\n#include <Eigen/Dense>\n#include <boost/random.hpp>\n#include <boost/filesystem.hpp>\n#include <cmath>\n#include <functional>\n#include <chrono>\n#include <boost/dynamic_bitset.hpp>\n#include \"config.hpp\"\n\nusing namespace std;\nusing namespace std::chrono;\nnamespace fs = boost::filesystem;\n\nclass LSHFunc_ITQ {\n  int nbits; // number of bits in a function (length of key)\n  int dim; // dimension of features\n  Eigen::VectorXf mean; // for centering the data\n  Eigen::MatrixXf R; // rotation matrix (ITQ)\n  Eigen::MatrixXf pc; // PCA embedding (the top-<nbits> eigen vectors)\n  \npublic:\n  LSHFunc_ITQ(int _nbits): nbits(_nbits) {}\n  LSHFunc_ITQ() {} // used while serializing\n\n  void train(const vector<vector<float>>& sampleDataAsVec, int nTrainIter = 50) {\n    /*\n    // TODO: REMOVE, only for debugging\n    vector<vector<float>> sampleDataAsVec2 = sampleDataAsVec;\n    for (int i = 0; i < sampleDataAsVec.size(); i++) {\n      sampleDataAsVec2[i].erase(sampleDataAsVec2[i].begin() + 9216, sampleDataAsVec2[i].end());\n    }\n    ///////////////////////////////////\n    */\n    assert(sampleDataAsVec.size() > 0);\n    dim = sampleDataAsVec[0].size();\n    genLSHfunc(sampleDataAsVec, nTrainIter);\n  }\n\n  void computeAndSetCenter(const Eigen::MatrixXf& sampleData) {\n    mean = sampleData.colwise().mean();\n  }\n\n  void centerData(Eigen::MatrixXf& data) const {\n    data = data.rowwise() - mean.adjoint();\n  }\n\n  void learnPCAEmbedding(const Eigen::MatrixXf& data) {\n    high_resolution_clock::time_point start = high_resolution_clock::now();\n    cout << \"Learning PCA Embedding ... \";\n    cout.flush();\n    Eigen::MatrixXf cov = data.adjoint() * data;\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> eig(cov);\n    pc = eig.eigenvectors().rightCols(nbits).rowwise().reverse();\n    high_resolution_clock::time_point end = high_resolution_clock::now();\n    cout << \"Done in \" << duration_cast<minutes>(end - start).count() << \"min\" << endl;\n  }\n\n  void pcaEmbed(Eigen::MatrixXf& data) const {\n    data *= pc;\n  }\n  \n  void pcaEmbed(Eigen::VectorXf& data) const {\n    data = data.adjoint() * pc;\n  }\n\n  void genLSHfunc(const vector<vector<float>>& sampleDataAsVec, int nIter) {\n    // Map to Eigen::Matrix\n    Eigen::MatrixXf sampleData(sampleDataAsVec.size(), sampleDataAsVec[0].size());\n    for (int i = 0; i < sampleDataAsVec.size(); i++) {\n      sampleData.row(i) = Eigen::VectorXf::Map(&sampleDataAsVec[i][0], sampleDataAsVec[i].size());\n    }\n    // directly translated Gong's code\n    learnPCAEmbedding(sampleData);\n    pcaEmbed(sampleData);\n    computeAndSetCenter(sampleData);\n    centerData(sampleData);\n    R = Eigen::MatrixXf::Random(nbits, nbits);\n    cout << \"Running ITQ Training...\" << endl;\n    cout.flush();\n    Eigen::JacobiSVD<Eigen::MatrixXf> svd(R, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    R = svd.matrixU().leftCols(nbits);\n    for (int iter = 0; iter < nIter; iter++) {\n      cout << \"Running iteration \" << iter << \" ...\";\n      cout.flush();\n      high_resolution_clock::time_point start = high_resolution_clock::now();\n      Eigen::MatrixXf Z = sampleData * R;\n      Eigen::MatrixXf UX = Eigen::MatrixXf::Ones(Z.rows(), Z.cols()) * (-1);\n      for (int i = 0; i < UX.rows(); i++) {\n        for (int j = 0; j < UX.cols(); j++) {\n          UX(i, j) = Z(i, j) >= 0 ? 1 : -1;\n        }\n      }\n      Eigen::MatrixXf C = UX.adjoint() * sampleData;\n      // Eigen::BDCSVD<Eigen::MatrixXf> svd2(C, Eigen::ComputeThinU | Eigen::ComputeThinV);\n      Eigen::JacobiSVD<Eigen::MatrixXf> svd2(C, Eigen::ComputeThinU | Eigen::ComputeThinV);\n      R = svd2.matrixV() * svd2.matrixU().adjoint();\n      high_resolution_clock::time_point end = high_resolution_clock::now();\n      cout << \"Done in \" << duration_cast<milliseconds>(end - start).count()\n           << \"ms\" << endl;\n    }\n  }\n\n  boost::dynamic_bitset<> computeHash(const vector<float>& _feat) const {\n    boost::dynamic_bitset<> hash(nbits);\n    if (_feat.size() == 0) {\n      return hash; // all 0s!\n    }\n    Eigen::VectorXf feat = Eigen::VectorXf::Map(&_feat[0], _feat.size());\n    #if NORMALIZE_FEATS == 1\n      feat = feat / feat.norm(); // normalize the feature\n    #endif\n    pcaEmbed(feat);\n    Eigen::VectorXf res = feat.adjoint() * R;\n    for (unsigned i = 0; i < res.rows(); i++) {\n      hash[i] = res(i) > 0 ? 1 : 0;\n    }\n    return hash;\n  }\n\n  template<class Archive>\n  void serialize(Archive &ar, const unsigned int version) {\n    ar & nbits;\n    ar & dim;\n    ar & mean;\n    ar & pc;\n    ar & R;\n  }\n};\n\n#endif\n\n", "meta": {"hexsha": "ebc11b7f375494329a0897a48ec5d49f97c1693a", "size": 4786, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ScalableLSH/DiskE2LSH/LSHFunc_ITQ.hpp", "max_stars_repo_name": "USCDataScience/cmu-fg-bg-similarity", "max_stars_repo_head_hexsha": "d8fc9a53937551f7a052bc2c6f442bcc29ea2615", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-04-13T21:40:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T11:32:31.000Z", "max_issues_repo_path": "ScalableLSH/DiskE2LSH/LSHFunc_ITQ.hpp", "max_issues_repo_name": "USCDataScience/cmu-fg-bg-similarity", "max_issues_repo_head_hexsha": "d8fc9a53937551f7a052bc2c6f442bcc29ea2615", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ScalableLSH/DiskE2LSH/LSHFunc_ITQ.hpp", "max_forks_repo_name": "USCDataScience/cmu-fg-bg-similarity", "max_forks_repo_head_hexsha": "d8fc9a53937551f7a052bc2c6f442bcc29ea2615", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0068965517, "max_line_length": 98, "alphanum_fraction": 0.6383201003, "num_tokens": 1390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5750963183430584}}
{"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": "//  (C) Copyright Jeremy Murphy 2015.\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/config.hpp>\n#define BOOST_TEST_MAIN\n#include <boost/array.hpp>\n#include <boost/math/tools/polynomial.hpp>\n#include <boost/integer/common_factor_rt.hpp>\n#include <boost/mpl/list.hpp>\n#include <boost/mpl/joint_view.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <utility>\n#include <array>\n#include <list>\n\n#if !defined(TEST1) && !defined(TEST2) && !defined(TEST3)\n#  define TEST1\n#  define TEST2\n#  define TEST3\n#endif\n\nusing namespace boost::math;\nusing boost::integer::gcd;\nusing namespace boost::math::tools;\nusing namespace std;\nusing boost::integer::gcd_detail::Euclid_gcd;\nusing boost::math::tools::subresultant_gcd;\n\ntemplate <typename T>\nstruct answer\n{\n    answer(std::pair< polynomial<T>, polynomial<T> > const &x) :\n    quotient(x.first), remainder(x.second) {}\n\n    polynomial<T> quotient;\n    polynomial<T> remainder;\n};\n\nstd::array<double, 4> const d3a = {{10, -6, -4, 3}};\nstd::array<double, 4> const d3b = {{-7, 5, 6, 1}};\n\nstd::array<double, 2> const d1a = {{-2, 1}};\nstd::array<double, 1> const d0a = {{6}};\nstd::array<double, 2> const d0a1 = {{0, 6}};\nstd::array<double, 6> const d0a5 = {{0, 0, 0, 0, 0, 6}};\n\n\nstd::array<int, 9> const d8 = {{-5, 2, 8, -3, -3, 0, 1, 0, 1}};\nstd::array<int, 9> const d8b = {{0, 2, 8, -3, -3, 0, 1, 0, 1}};\n\n\n\nBOOST_AUTO_TEST_CASE(trivial)\n{\n   /* We have one empty test case here, so that there is always something for Boost.Test to do even if the tests below are #if'ed out */\n}\n\n\n#ifdef TEST1\n\nstd::array<double, 4> const d3c = {{10.0/3.0, -2.0, -4.0/3.0, 1.0}};\nstd::array<double, 3> const d2a = {{-2, 2, 3}};\nstd::array<double, 3> const d2b = {{-7, 5, 6}};\nstd::array<double, 3> const d2c = {{31, -21, -22}};\nstd::array<double, 1> const d0b = {{3}};\nstd::array<int, 7> const d6 = {{21, -9, -4, 0, 5, 0, 3}};\nstd::array<int, 3> const d2 = {{-6, 0, 9}};\nstd::array<int, 6> const d5 = {{-9, 0, 3, 0, -15}};\n\n\nBOOST_AUTO_TEST_CASE( test_construction )\n{\n    polynomial<double> const a(d3a.begin(), d3a.end());\n    polynomial<double> const b(d3a.begin(), 3);\n    BOOST_CHECK_EQUAL(a, b);\n}\n\n#ifdef BOOST_MATH_HAS_IS_CONST_ITERABLE\n\n#include <list>\n#include <array>\n\nBOOST_AUTO_TEST_CASE(test_range_construction)\n{\n   std::list<double> l{ 1, 2, 3, 4 };\n   std::array<double, 4> a{ 3, 4, 5, 6 };\n   polynomial<double> p1{ 1, 2, 3, 4 };\n   polynomial<double> p2{ 3, 4, 5, 6 };\n\n   polynomial<double> p3(l);\n   polynomial<double> p4(a);\n\n   BOOST_CHECK_EQUAL(p1, p3);\n   BOOST_CHECK_EQUAL(p2, p4);\n}\n#endif\n\n#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST) && !BOOST_WORKAROUND(BOOST_GCC_VERSION, < 40500)\nBOOST_AUTO_TEST_CASE( test_initializer_list_construction )\n{\n    polynomial<double> a(begin(d3a), end(d3a));\n    polynomial<double> b = {10, -6, -4, 3};\n    polynomial<double> c{10, -6, -4, 3};\n    polynomial<double> d{10, -6, -4, 3, 0, 0};\n    BOOST_CHECK_EQUAL(a, b);\n    BOOST_CHECK_EQUAL(b, c);\n    BOOST_CHECK_EQUAL(d.degree(), 3u);\n}\n\nBOOST_AUTO_TEST_CASE( test_initializer_list_assignment )\n{\n    polynomial<double> a(begin(d3a), end(d3a));\n    polynomial<double> b;\n    b = {10, -6, -4, 3, 0, 0};\n    BOOST_CHECK_EQUAL(b.degree(), 3u);\n    BOOST_CHECK_EQUAL(a, b);\n}\n#endif\n\n\nBOOST_AUTO_TEST_CASE( test_degree )\n{\n    polynomial<double> const zero;\n    polynomial<double> const a(d3a.begin(), d3a.end());\n    BOOST_CHECK_THROW(zero.degree(), std::logic_error);\n    BOOST_CHECK_EQUAL(a.degree(), 3u);\n}\n\n\nBOOST_AUTO_TEST_CASE( test_division_over_field )\n{\n    polynomial<double> const a(d3a.begin(), d3a.end());\n    polynomial<double> const b(d1a.begin(), d1a.end());\n    polynomial<double> const q(d2a.begin(), d2a.end());\n    polynomial<double> const r(d0a.begin(), d0a.end());\n    polynomial<double> const c(d3b.begin(), d3b.end());\n    polynomial<double> const d(d2b.begin(), d2b.end());\n    polynomial<double> const e(d2c.begin(), d2c.end());\n    polynomial<double> const f(d0b.begin(), d0b.end());\n    polynomial<double> const g(d3c.begin(), d3c.end());\n    polynomial<double> const zero;\n    polynomial<double> const one(1.0);\n\n    answer<double> result = quotient_remainder(a, b);\n    BOOST_CHECK_EQUAL(result.quotient, q);\n    BOOST_CHECK_EQUAL(result.remainder, r);\n    BOOST_CHECK_EQUAL(a, q * b + r); // Sanity check.\n\n    result = quotient_remainder(a, c);\n    BOOST_CHECK_EQUAL(result.quotient, f);\n    BOOST_CHECK_EQUAL(result.remainder, e);\n    BOOST_CHECK_EQUAL(a, f * c + e); // Sanity check.\n\n    result = quotient_remainder(a, f);\n    BOOST_CHECK_EQUAL(result.quotient, g);\n    BOOST_CHECK_EQUAL(result.remainder, zero);\n    BOOST_CHECK_EQUAL(a, g * f + zero); // Sanity check.\n    // Check that division by a regular number gives the same result.\n    BOOST_CHECK_EQUAL(a / 3.0, g);\n    BOOST_CHECK_EQUAL(a % 3.0, zero);\n\n    // Sanity checks.\n    BOOST_CHECK_EQUAL(a / a, one);\n    BOOST_CHECK_EQUAL(a % a, zero);\n    // BOOST_CHECK_EQUAL(zero / zero, zero); // TODO\n}\n\nBOOST_AUTO_TEST_CASE( test_division_over_ufd )\n{\n    polynomial<int> const zero;\n    polynomial<int> const one(1);\n    polynomial<int> const aa(d8.begin(), d8.end());\n    polynomial<int> const bb(d6.begin(), d6.end());\n    polynomial<int> const q(d2.begin(), d2.end());\n    polynomial<int> const r(d5.begin(), d5.end());\n\n    answer<int> result = quotient_remainder(aa, bb);\n    BOOST_CHECK_EQUAL(result.quotient, q);\n    BOOST_CHECK_EQUAL(result.remainder, r);\n\n    // Sanity checks.\n    BOOST_CHECK_EQUAL(aa / aa, one);\n    BOOST_CHECK_EQUAL(aa % aa, zero);\n}\n\n#endif\n\ntemplate <typename T>\nstruct FM2GP_Ex_8_3__1\n{\n    polynomial<T> x;\n    polynomial<T> y;\n    polynomial<T> z;\n\n    FM2GP_Ex_8_3__1()\n    {\n        std::array<T, 5> const x_data = {{105, 278, -88, -56, 16}};\n        std::array<T, 5> const y_data = {{70, 232, -44, -64, 16}};\n        std::array<T, 3> const z_data = {{35, -24, 4}};\n        x = polynomial<T>(x_data.begin(), x_data.end());\n        y = polynomial<T>(y_data.begin(), y_data.end());\n        z = polynomial<T>(z_data.begin(), z_data.end());\n    }\n};\n\ntemplate <typename T>\nstruct FM2GP_Ex_8_3__2\n{\n    polynomial<T> x;\n    polynomial<T> y;\n    polynomial<T> z;\n\n    FM2GP_Ex_8_3__2()\n    {\n        std::array<T, 5> const x_data = {{1, -6, -8, 6, 7}};\n        std::array<T, 5> const y_data = {{1, -5, -2, 15, 11}};\n        std::array<T, 3> const z_data = {{1, 2, 1}};\n        x = polynomial<T>(x_data.begin(), x_data.end());\n        y = polynomial<T>(y_data.begin(), y_data.end());\n        z = polynomial<T>(z_data.begin(), z_data.end());\n    }\n};\n\n\ntemplate <typename T>\nstruct FM2GP_mixed\n{\n    polynomial<T> x;\n    polynomial<T> y;\n    polynomial<T> z;\n\n    FM2GP_mixed()\n    {\n        std::array<T, 4> const x_data = {{-2.2, -3.3, 0, 1}};\n        std::array<T, 3> const y_data = {{-4.4, 0, 1}};\n        std::array<T, 2> const z_data= {{-2, 1}};\n        x = polynomial<T>(x_data.begin(), x_data.end());\n        y = polynomial<T>(y_data.begin(), y_data.end());\n        z = polynomial<T>(z_data.begin(), z_data.end());\n    }\n};\n\n\ntemplate <typename T>\nstruct FM2GP_trivial\n{\n    polynomial<T> x;\n    polynomial<T> y;\n    polynomial<T> z;\n\n    FM2GP_trivial()\n    {\n        std::array<T, 4> const x_data = {{-2, -3, 0, 1}};\n        std::array<T, 3> const y_data = {{-4, 0, 1}};\n        std::array<T, 2> const z_data= {{-2, 1}};\n        x = polynomial<T>(x_data.begin(), x_data.end());\n        y = polynomial<T>(y_data.begin(), y_data.end());\n        z = polynomial<T>(z_data.begin(), z_data.end());\n    }\n};\n\n// Sanity checks to make sure I didn't break it.\n#ifdef TEST1\ntypedef boost::mpl::list<signed char, short, int, long> integral_test_types;\ntypedef boost::mpl::list<int, long> large_integral_test_types;\ntypedef boost::mpl::list<> mp_integral_test_types;\n#elif defined(TEST2)\ntypedef boost::mpl::list<\n#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1500)\n   boost::multiprecision::cpp_int\n#endif\n> integral_test_types;\ntypedef integral_test_types large_integral_test_types;\ntypedef large_integral_test_types mp_integral_test_types;\n#elif defined(TEST3)\ntypedef boost::mpl::list<> large_integral_test_types;\ntypedef boost::mpl::list<> integral_test_types;\ntypedef large_integral_test_types mp_integral_test_types;\n#endif\n\n#ifdef TEST1\ntypedef boost::mpl::list<double, long double> non_integral_test_types;\n#elif defined(TEST2)\ntypedef boost::mpl::list<\n#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1500)\n   boost::multiprecision::cpp_rational\n#endif\n> non_integral_test_types;\n#elif defined(TEST3)\ntypedef boost::mpl::list<\n#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1500)\n   boost::multiprecision::cpp_bin_float_single, boost::multiprecision::cpp_dec_float_50\n#endif\n> non_integral_test_types;\n#endif\n\ntypedef boost::mpl::joint_view<integral_test_types, non_integral_test_types> all_test_types;\n\n\ntemplate <typename T>\nvoid normalize(polynomial<T> &p)\n{\n    if (leading_coefficient(p) < T(0))\n        std::transform(p.data().begin(), p.data().end(), p.data().begin(), std::negate<T>());\n}\n\n/**\n * Note that we do not expect 'pure' gcd algorithms to normalize the result.\n * However, the usual public interface function gcd() will do that.\n */\n\nBOOST_AUTO_TEST_SUITE(test_subresultant_gcd)\n\n// This test is just to show that gcd<polynomial<T>>(u, v) is defined (and works) when T is integral and multiprecision.\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( gcd_interface, T, mp_integral_test_types, FM2GP_Ex_8_3__1<T> )\n{\n    typedef FM2GP_Ex_8_3__1<T> fixture_type;\n    polynomial<T> w;\n    w = gcd(fixture_type::x, fixture_type::y);\n    normalize(w);\n    BOOST_CHECK_EQUAL(w, fixture_type::z);\n    w = gcd(fixture_type::y, fixture_type::x);\n    normalize(w);\n    BOOST_CHECK_EQUAL(w, fixture_type::z);\n}\n\n// This test is just to show that gcd<polynomial<T>>(u, v) is defined (and works) when T is floating point.\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( gcd_float_interface, T, non_integral_test_types, FM2GP_Ex_8_3__1<T> )\n{\n    typedef FM2GP_Ex_8_3__1<T> fixture_type;\n    polynomial<T> w;\n    w = gcd(fixture_type::x, fixture_type::y);\n    normalize(w);\n    BOOST_CHECK_EQUAL(w, fixture_type::z);\n    w = gcd(fixture_type::y, fixture_type::x);\n    normalize(w);\n    BOOST_CHECK_EQUAL(w, fixture_type::z);\n}\n\n// The following tests call subresultant_gcd explicitly to remove any ambiguity\n// and to permit testing on single-precision integral types.\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( Ex_8_3__1, T, large_integral_test_types, FM2GP_Ex_8_3__1<T> )\n{\n    typedef FM2GP_Ex_8_3__1<T> fixture_type;\n    polynomial<T> w;\n    w = subresultant_gcd(fixture_type::x, fixture_type::y);\n    normalize(w);\n    BOOST_CHECK_EQUAL(w, fixture_type::z);\n    w = subresultant_gcd(fixture_type::y, fixture_type::x);\n    normalize(w);\n    BOOST_CHECK_EQUAL(w, fixture_type::z);\n}\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( Ex_8_3__2, T, large_integral_test_types, FM2GP_Ex_8_3__2<T> )\n{\n    typedef FM2GP_Ex_8_3__2<T> fixture_type;\n    polynomial<T> w;\n    w = subresultant_gcd(fixture_type::x, fixture_type::y);\n    normalize(w);\n    BOOST_CHECK_EQUAL(w, fixture_type::z);\n    w = subresultant_gcd(fixture_type::y, fixture_type::x);\n    normalize(w);\n    BOOST_CHECK_EQUAL(w, fixture_type::z);\n}\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( trivial_int, T, large_integral_test_types, FM2GP_trivial<T> )\n{\n    typedef FM2GP_trivial<T> fixture_type;\n    polynomial<T> w;\n    w = subresultant_gcd(fixture_type::x, fixture_type::y);\n    normalize(w);\n    BOOST_CHECK_EQUAL(w, fixture_type::z);\n    w = subresultant_gcd(fixture_type::y, fixture_type::x);\n    normalize(w);\n    BOOST_CHECK_EQUAL(w, fixture_type::z);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_addition, T, all_test_types )\n{\n    polynomial<T> const a(d3a.begin(), d3a.end());\n    polynomial<T> const b(d1a.begin(), d1a.end());\n    polynomial<T> const zero;\n\n    polynomial<T> result = a + b; // different degree\n    std::array<T, 4> tmp = {{8, -5, -4, 3}};\n    polynomial<T> expected(tmp.begin(), tmp.end());\n    BOOST_CHECK_EQUAL(result, expected);\n    BOOST_CHECK_EQUAL(a + zero, a);\n    BOOST_CHECK_EQUAL(a + b, b + a);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_subtraction, T, all_test_types )\n{\n    polynomial<T> const a(d3a.begin(), d3a.end());\n    polynomial<T> const zero;\n\n    BOOST_CHECK_EQUAL(a - T(0), a);\n    BOOST_CHECK_EQUAL(T(0) - a, -a);\n    BOOST_CHECK_EQUAL(a - zero, a);\n    BOOST_CHECK_EQUAL(zero - a, -a);\n    BOOST_CHECK_EQUAL(a - a, zero);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_multiplication, T, all_test_types )\n{\n    polynomial<T> const a(d3a.begin(), d3a.end());\n    polynomial<T> const b(d1a.begin(), d1a.end());\n    polynomial<T> const zero;\n    std::array<T, 7> const d3a_sq = {{100, -120, -44, 108, -20, -24, 9}};\n    polynomial<T> const a_sq(d3a_sq.begin(), d3a_sq.end());\n\n    BOOST_CHECK_EQUAL(a * T(0), zero);\n    BOOST_CHECK_EQUAL(a * zero, zero);\n    BOOST_CHECK_EQUAL(zero * T(0), zero);\n    BOOST_CHECK_EQUAL(zero * zero, zero);\n    BOOST_CHECK_EQUAL(a * b, b * a);\n    polynomial<T> aa(a);\n    aa *= aa;\n    BOOST_CHECK_EQUAL(aa, a_sq);\n    BOOST_CHECK_EQUAL(aa, a * a);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_arithmetic_relations, T, all_test_types )\n{\n    polynomial<T> const a(d8b.begin(), d8b.end());\n    polynomial<T> const b(d1a.begin(), d1a.end());\n\n    BOOST_CHECK_EQUAL(a * T(2), a + a);\n    BOOST_CHECK_EQUAL(a - b, -b + a);\n    BOOST_CHECK_EQUAL(a, (a * a) / a);\n    BOOST_CHECK_EQUAL(a, (a / a) * a);\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_non_integral_arithmetic_relations, T, non_integral_test_types )\n{\n    polynomial<T> const a(d8b.begin(), d8b.end());\n    polynomial<T> const b(d1a.begin(), d1a.end());\n\n    BOOST_CHECK_EQUAL(a * T(0.5), a / T(2));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_cont_and_pp, T, integral_test_types)\n{\n    std::array<polynomial<T>, 4> const q={{\n        polynomial<T>(d8.begin(), d8.end()),\n        polynomial<T>(d8b.begin(), d8b.end()),\n        polynomial<T>(d3a.begin(), d3a.end()),\n        polynomial<T>(d3b.begin(), d3b.end())\n    }};\n    for (std::size_t i = 0; i < q.size(); i++)\n    {\n        BOOST_CHECK_EQUAL(q[i], content(q[i]) * primitive_part(q[i]));\n        BOOST_CHECK_EQUAL(primitive_part(q[i]), primitive_part(q[i], content(q[i])));\n    }\n\n    polynomial<T> const zero;\n    BOOST_CHECK_EQUAL(primitive_part(zero), zero);\n    BOOST_CHECK_EQUAL(content(zero), T(0));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_self_multiply_assign, T, all_test_types )\n{\n    polynomial<T> a(d3a.begin(), d3a.end());\n    polynomial<T> const b(a);\n    std::array<double, 7> const d3a_sq = {{100, -120, -44, 108, -20, -24, 9}};\n    polynomial<T> const asq(d3a_sq.begin(), d3a_sq.end());\n\n    a *= a;\n\n    BOOST_CHECK_EQUAL(a, b*b);\n    BOOST_CHECK_EQUAL(a, asq);\n\n    a *= a;\n\n    BOOST_CHECK_EQUAL(a, b*b*b*b);\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_right_shift, T, all_test_types )\n{\n    polynomial<T> a(d8b.begin(), d8b.end());\n    polynomial<T> const aa(a);\n    polynomial<T> const b(d8b.begin() + 1, d8b.end());\n    polynomial<T> const c(d8b.begin() + 5, d8b.end());\n    a >>= 0u;\n    BOOST_CHECK_EQUAL(a, aa);\n    a >>= 1u;\n    BOOST_CHECK_EQUAL(a, b);\n    a = a >> 4u;\n    BOOST_CHECK_EQUAL(a, c);\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_left_shift, T, all_test_types )\n{\n    polynomial<T> a(d0a.begin(), d0a.end());\n    polynomial<T> const aa(a);\n    polynomial<T> const b(d0a1.begin(), d0a1.end());\n    polynomial<T> const c(d0a5.begin(), d0a5.end());\n    a <<= 0u;\n    BOOST_CHECK_EQUAL(a, aa);\n    a <<= 1u;\n    BOOST_CHECK_EQUAL(a, b);\n    a = a << 4u;\n    BOOST_CHECK_EQUAL(a, c);\n    polynomial<T> zero;\n    // Multiplying zero by x should still be zero.\n    zero <<= 1u;\n    BOOST_CHECK_EQUAL(zero, zero_element(multiplies< polynomial<T> >()));\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_odd_even, T, all_test_types)\n{\n    polynomial<T> const zero;\n    BOOST_CHECK_EQUAL(odd(zero), false);\n    BOOST_CHECK_EQUAL(even(zero), true);\n    polynomial<T> const a(d0a.begin(), d0a.end());\n    BOOST_CHECK_EQUAL(odd(a), true);\n    BOOST_CHECK_EQUAL(even(a), false);\n    polynomial<T> const b(d0a1.begin(), d0a1.end());\n    BOOST_CHECK_EQUAL(odd(b), false);\n    BOOST_CHECK_EQUAL(even(b), true);\n}\n\n// NOTE: Slightly unexpected: this unit test passes even when T = char.\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_pow, T, all_test_types )\n{\n   if (std::numeric_limits<T>::digits < 32)\n      return;   // Invokes undefined behaviour\n    polynomial<T> a(d3a.begin(), d3a.end());\n    polynomial<T> const one(T(1));\n    std::array<double, 7> const d3a_sqr = {{100, -120, -44, 108, -20, -24, 9}};\n    std::array<double, 10> const d3a_cub =\n        {{1000, -1800, -120, 2124, -1032, -684, 638, -18, -108, 27}};\n    polynomial<T> const asqr(d3a_sqr.begin(), d3a_sqr.end());\n    polynomial<T> const acub(d3a_cub.begin(), d3a_cub.end());\n\n    BOOST_CHECK_EQUAL(pow(a, 0), one);\n    BOOST_CHECK_EQUAL(pow(a, 1), a);\n    BOOST_CHECK_EQUAL(pow(a, 2), asqr);\n    BOOST_CHECK_EQUAL(pow(a, 3), acub);\n    BOOST_CHECK_EQUAL(pow(a, 4), pow(asqr, 2));\n    BOOST_CHECK_EQUAL(pow(a, 5), asqr * acub);\n    BOOST_CHECK_EQUAL(pow(a, 6), pow(acub, 2));\n    BOOST_CHECK_EQUAL(pow(a, 7), acub * acub * a);\n\n    BOOST_CHECK_THROW(pow(a, -1), std::domain_error);\n    BOOST_CHECK_EQUAL(pow(one, 137), one);\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_bool, T, all_test_types)\n{\n    polynomial<T> const zero;\n    polynomial<T> const a(d0a.begin(), d0a.end());\n    BOOST_CHECK_EQUAL(bool(zero), false);\n    BOOST_CHECK_EQUAL(bool(a), true);\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_set_zero, T, all_test_types)\n{\n    polynomial<T> const zero;\n    polynomial<T> a(d0a.begin(), d0a.end());\n    a.set_zero();\n    BOOST_CHECK_EQUAL(a, zero);\n    a.set_zero(); // Ensure that setting zero to zero is a no-op.\n    BOOST_CHECK_EQUAL(a, zero);\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_leading_coefficient, T, all_test_types)\n{\n    polynomial<T> const zero;\n    BOOST_CHECK_EQUAL(leading_coefficient(zero), T(0));\n    polynomial<T> a(d0a.begin(), d0a.end());\n    BOOST_CHECK_EQUAL(leading_coefficient(a), T(d0a.back()));\n}\n\n#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX)\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_prime, T, all_test_types)\n{\n    std::vector<T> d{1,1,1,1,1};\n    polynomial<T> p(std::move(d));\n    polynomial<T> q = p.prime();\n    BOOST_CHECK_EQUAL(q(0), T(1));\n\n    for (size_t i = 0; i < q.size(); ++i)\n    {\n        BOOST_CHECK_EQUAL(q[i], i+1);\n    }\n\n    polynomial<T> P = p.integrate();\n    BOOST_CHECK_EQUAL(P(0), T(0));\n    for (size_t i = 1; i < P.size(); ++i)\n    {\n        BOOST_CHECK_EQUAL(P[i], 1/static_cast<T>(i));\n    }\n\n    polynomial<T> empty;\n    q = empty.prime();\n    BOOST_CHECK_EQUAL(q.size(), 0);\n\n}\n#endif\n", "meta": {"hexsha": "e13ceb619612eb017d0bca9df6e00f712a50fc74", "size": 18901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_polynomial.cpp", "max_stars_repo_name": "jamesfolberth/math", "max_stars_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_polynomial.cpp", "max_issues_repo_name": "jamesfolberth/math", "max_issues_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_polynomial.cpp", "max_forks_repo_name": "jamesfolberth/math", "max_forks_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6834415584, "max_line_length": 136, "alphanum_fraction": 0.6601767102, "num_tokens": 5680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5749781377187099}}
{"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 <boost/graph/adjacency_list.hpp>\n#include <boost/graph/rmat_graph_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <iostream>\n#include <ctime>\n#include <stdio.h>\n\nusing namespace boost;\ntypedef adjacency_list<> Graph;\n// The length of cycle of rand48 is 2^48-1, which is much longer than\n// minstd_rand.\n// http://www.boost.org/doc/libs/1_55_0/doc/html/boost_random/reference.html\ntypedef rand48 rand_gen_t;\ntypedef rmat_iterator<rand_gen_t, Graph> RMATGen;\ntypedef graph_traits<Graph>::vertex_iterator vertex_iter;\ntypedef property_map<Graph, vertex_index_t>::type IndexMap;\n\nint main(int argc, char* argv[])\n{\n\tif (argc < 3) {\n\t\tfprintf(stderr, \"usage: make_graph #vertices, #numedges [output]\\n\");\n\t\treturn EXIT_FAILURE;\n\t}\n\ttypedef boost::graph_traits<Graph>::vertices_size_type vertices_size_type;\n\ttypedef boost::graph_traits<Graph>::edges_size_type edges_size_type;\n\tvertices_size_type n = atol(argv[1]);\n\tedges_size_type m = atol(argv[2]);\n\n\tFILE *f = stdout;\n\tstd::string out_file;\n\tif (argc >= 4) {\n\t\tout_file = argv[3];\n\t\tf = fopen(argv[3], \"w\");\n\t\tassert(f);\n\t}\n\n\tfprintf(stderr, \"Vertices = %ld\\n\", n);\n\tfprintf(stderr, \"Edges = %ld\\n\", m);\n\n\tstd::clock_t start;\n\tstart = std::clock();\n\trand_gen_t gen(time(NULL));\n\tRMATGen gen_it(gen, n, m, 0.57, 0.19, 0.19, 0.05, true);\n\tRMATGen gen_end;\n\tfor (; gen_it != gen_end; ++gen_it) {\n\t\tfprintf(f, \"%ld %ld\\n\", gen_it->first, gen_it->second);\n\t}\n#if 0\n\t// Create graph with 100 nodes and 400 edges\n\tGraph g(RMATGen(gen, n, m, 0.57, 0.19, 0.19, 0.05, true), RMATGen(), n);\n\n\tIndexMap index = get(vertex_index, g);\n\n\t// Get vertex set\n#if 0\n\tstd::pair<vertex_iter, vertex_iter> vp;\n\tfor (vp = vertices(g); vp.first != vp.second; ++vp.first)\n\t\tstd::cout << index[*vp.first] <<  \" \";\n\tstd::cout << std::endl;\n#endif\n\n\t// Get edge set\n\tgraph_traits<Graph>::edge_iterator ei, ei_end;\n\tfor (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n\t\tstd::cout << index[source(*ei, g)]<< \" \" << index[target(*ei, g)] << \"\\n\";\n#endif\n\tif (f != stdout) {\n\t\tprintf(\"close %s\\n\", out_file.c_str());\n\t\tfclose(f);\n\t}\n\n\tstd::cerr << \"The time to build the graph = \" << (std::clock()-start)/(double)CLOCKS_PER_SEC << std::endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "25c6039369d93112cdaf15d1714d5dcd32361118", "size": 2246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "flash-graph/tools/rmat-gen.cpp", "max_stars_repo_name": "kjhyun824/uncertain-graph-engine", "max_stars_repo_head_hexsha": "17aa1b8b5d03b03200583797ab0cfb4a42ff8845", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 140.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T21:28:55.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-22T01:25:03.000Z", "max_issues_repo_path": "flash-graph/tools/rmat-gen.cpp", "max_issues_repo_name": "kjhyun824/uncertain-graph-engine", "max_issues_repo_head_hexsha": "17aa1b8b5d03b03200583797ab0cfb4a42ff8845", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 160.0, "max_issues_repo_issues_event_min_datetime": "2016-11-07T18:37:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-10T22:57:07.000Z", "max_forks_repo_path": "flash-graph/tools/rmat-gen.cpp", "max_forks_repo_name": "kjhyun824/uncertain-graph-engine", "max_forks_repo_head_hexsha": "17aa1b8b5d03b03200583797ab0cfb4a42ff8845", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-11-14T04:31:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-28T04:58:44.000Z", "avg_line_length": 29.5526315789, "max_line_length": 107, "alphanum_fraction": 0.6798753339, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5749194069562371}}
{"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": "#pragma once\r\n\r\n#include <Eigen/Core>\r\n#include <Eigen/SparseCore>\r\n\r\n\r\nusing real = double;\r\nusing uint = unsigned int;\r\n\r\nusing Mat = Eigen::MatrixXd;\r\nusing Vec = Eigen::VectorXd;\r\nusing Vec3 = Eigen::Vector3d;\r\nusing Vec3i = Eigen::Vector3i;\r\nusing Vec4i = Eigen::Vector4i;\r\nusing SpMat = Eigen::SparseMatrix<double, Eigen::ColMajor>;\r\nusing SpVec = Eigen::SparseVector<double, Eigen::ColMajor>;\r\n", "meta": {"hexsha": "8f4e4a4ca683cecfac23eff84b46fc1632763969", "size": 401, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solv_plug/mathdef.hpp", "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/mathdef.hpp", "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/mathdef.hpp", "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": 23.5882352941, "max_line_length": 60, "alphanum_fraction": 0.710723192, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.574919396650328}}
{"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": "/**\n * @file radauthreetimestepping_test.cc\n * @brief NPDE homework \"RadauThreeTimestepping\" code\n * @author Tobias Rohner, edited by Oliver Rietmann\n * @date 16.03.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n\n#include <gtest/gtest.h>\n\n#include <lf/assemble/assemble.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include \"../radauthreetimestepping.h\"\n\nnamespace RadauThreeTimestepping::test {\n\nTEST(RadauThreeTimestepping, TrapRuleLinFEElemVecProvider) {\n  // Get some triangular test mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n  // Define some easy functions to test the provider with\n  auto f1 = [](const Eigen::Vector2d &x) { return 0.0; };\n  auto f2 = [](const Eigen::Vector2d &x) { return 1.0; };\n  auto f3 = [](const Eigen::Vector2d &x) { return x[0]; };\n  // Check the element vector for each triangle\n  RadauThreeTimestepping::TrapRuleLinFEElemVecProvider f1p(f1);\n  RadauThreeTimestepping::TrapRuleLinFEElemVecProvider f2p(f2);\n  RadauThreeTimestepping::TrapRuleLinFEElemVecProvider f3p(f3);\n  for (const auto tria : mesh_p->Entities(0)) {\n    const auto geom = tria->Geometry();\n    auto ev1 = f1p.Eval(*tria);\n    auto ev2 = f2p.Eval(*tria);\n    auto ev3 = f3p.Eval(*tria);\n    ASSERT_TRUE(ev1.isApprox(Eigen::Vector3d::Zero()));\n    ASSERT_TRUE(ev2.isApprox(\n        Eigen::Vector3d::Constant(lf::geometry::Volume(*geom) / 3)));\n    Eigen::Vector3d e3_correct =\n        lf::geometry::Volume(*geom) / 3 * lf::geometry::Corners(*geom).row(0);\n    ASSERT_TRUE(ev3.isApprox(e3_correct));\n  }\n}\n\nTEST(RadauThreeTimestepping, rhsVectorheatSource) {\n  // Generate a triangular test mesh on [0,1]^2\n  const auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3, 1. / 3);\n  // Create a DOF handler\n  const lf::uscalfe::FeSpaceLagrangeO1<double> fespace(mesh_p);\n  const auto &dofh = fespace.LocGlobMap();\n  // Assemble the vectors for t=0 and t=0.5\n  const Eigen::VectorXd rhs0 =\n      RadauThreeTimestepping::rhsVectorheatSource(dofh, 0.0);\n  const Eigen::VectorXd rhs1 =\n      RadauThreeTimestepping::rhsVectorheatSource(dofh, 0.5);\n  // Get the DOFs on the boundary\n  const auto boundary = lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 2);\n\n  // Create a functional for time t=0 and t=0.5\n  auto f0 = [](const Eigen::Vector2d &x) {\n    return ((x[0] - 0.5) * (x[0] - 0.5) + x[1] * x[1] < 0.25) ? 1.0 : 0.0;\n  };\n  auto f1 = [](const Eigen::Vector2d &x) {\n    return (x[0] * x[0] + (x[1] - 0.5) * (x[1] - 0.5) < 0.25) ? 1.0 : 0.0;\n  };\n\n  // Assume TrapRuleLinFEElemVecProvider works correctly,\n  // as it is tested above\n  RadauThreeTimestepping::TrapRuleLinFEElemVecProvider provider0(f0);\n  RadauThreeTimestepping::TrapRuleLinFEElemVecProvider provider1(f1);\n  Eigen::VectorXd rhs0_test = Eigen::VectorXd::Zero(dofh.NumDofs());\n  Eigen::VectorXd rhs1_test = Eigen::VectorXd::Zero(dofh.NumDofs());\n  lf::assemble::AssembleVectorLocally(0, dofh, provider0, rhs0_test);\n  lf::assemble::AssembleVectorLocally(0, dofh, provider1, rhs1_test);\n\n  double tol = 1e-10;\n\n  // Make sure the TrapRuleLinFEElemVecProvider is indeed implemented already\n  ASSERT_TRUE(rhs0_test.norm() > tol);\n  ASSERT_TRUE(rhs1_test.norm() > tol);\n\n  for (int i = 0; i < dofh.NumDofs(); ++i) {\n    if (boundary(dofh.Entity(i))) {\n      // Check whether boundary DOFs are set to zero\n      ASSERT_DOUBLE_EQ(rhs0[i], 0)\n          << \"Have you forgotten to set the boundary values to zero?\";\n      ASSERT_DOUBLE_EQ(rhs1[i], 0)\n          << \"Have you forgotten to set the boundary values to zero?\";\n    } else {\n      // Check whether the value coincides with the one\n      // computed previously\n      ASSERT_NEAR(rhs0[i], rhs0_test[i], tol);\n      ASSERT_NEAR(rhs1[i], rhs1_test[i], tol);\n    }\n  }\n}\n\nTEST(RadauThreeTimestepping, solveHeatEvolution) {\n  // Generate a triangular test mesh on [0,1]^2\n  const auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3, 1. / 3);\n  // Create a DOF handler\n  const lf::uscalfe::FeSpaceLagrangeO1<double> fespace(mesh_p);\n  const auto &dofh = fespace.LocGlobMap();\n\n  // Solve heat evolution with zero initial and boundary conditions\n  double final_time = 1.0;\n  unsigned int m = 50;\n\n  Eigen::VectorXd sol =\n      RadauThreeTimestepping::solveHeatEvolution(dofh, m, final_time);\n\n  Eigen::VectorXd ref_sol(13);\n  ref_sol << 0, 0, 0, 1.47965e-06, 1.46476e-06, 0, 0, 1.78839e-06, 1.36475e-06,\n      0, 0, 0, 0;\n\n  double tol = 1.e-4;\n\n  ASSERT_NEAR((ref_sol - sol).norm(), 0.0, tol);\n}\n\nTEST(RadauThreeTimestepping, dropMatrixRowsColumns) {\n  // Generate a triangular test mesh on [0,1]^2\n  const auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3, 1. / 3);\n  // Create a DOF handler\n  const lf::uscalfe::FeSpaceLagrangeO1<double> fespace(mesh_p);\n  const auto &dofh = fespace.LocGlobMap();\n  const lf::base::size_type N_dofs = dofh.NumDofs();\n\n  // Obtain an array of boolean flags for the vertices of the mesh: 'true'\n  // indicates that the vertex lies on the boundary.\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 2)};\n  // Index predicate for the selectvals FUNCTOR of dropMatrixRowsColumns\n  auto bdy_vertices_selector = [&bd_flags, &dofh](unsigned int idx) -> bool {\n    return bd_flags(dofh.Entity(idx));\n  };\n\n  lf::assemble::COOMatrix<double> A_COO(N_dofs, N_dofs);\n  lf::uscalfe::LinearFELaplaceElementMatrix elLapMat_builder;\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elLapMat_builder, A_COO);\n\n  RadauThreeTimestepping::dropMatrixRowsColumns(bdy_vertices_selector, A_COO);\n\n  Eigen::SparseMatrix<double> A_sps = A_COO.makeSparse();\n\n  Eigen::MatrixXd A(A_sps);\n\n  Eigen::MatrixXd A_ref = Eigen::MatrixXd::Zero(N_dofs, N_dofs);\n  A_ref(0, 0) = 1;\n  A_ref(1, 1) = 1;\n  A_ref(2, 2) = 1;\n  A_ref(3, 3) = 3.625;\n  A_ref(3, 4) = -0.625;\n  A_ref(3, 7) = -0.25;\n  A_ref(3, 8) = -0.75;\n  A_ref(4, 3) = -0.625;\n  A_ref(4, 4) = 4.375;\n  A_ref(4, 7) = -2;\n  A_ref(5, 5) = 1;\n  A_ref(6, 6) = 1;\n  A_ref(7, 3) = -0.25;\n  A_ref(7, 4) = -2;\n  A_ref(7, 7) = 4.5;\n  A_ref(7, 8) = -0.75;\n  A_ref(8, 3) = -0.75;\n  A_ref(8, 7) = -0.75;\n  A_ref(8, 8) = 3.75;\n  A_ref(9, 9) = 1;\n  A_ref(10, 10) = 1;\n  A_ref(11, 11) = 1;\n  A_ref(12, 12) = 1;\n\n  double tol = 1.e-4;\n\n  ASSERT_NEAR((A - A_ref).norm(), 0.0, tol);\n}\n\nTEST(RadauThreeTimestepping, LinFEMassMatrixProvider) {\n  // Generate a triangular test mesh on [0,1]^2\n  const auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3, 1. / 3);\n  // Create a DOF handler\n  const lf::uscalfe::FeSpaceLagrangeO1<double> fespace(mesh_p);\n  const auto &dofh = fespace.LocGlobMap();\n\n  // Compare the element matrices for every cell\n  RadauThreeTimestepping::LinFEMassMatrixProvider provider;\n  for (const auto cell : mesh_p->Entities(0)) {\n    const auto geom = cell->Geometry();\n    // Compute the correct element matrix\n    Eigen::Matrix3d em_correct;\n    em_correct.setConstant(lf::geometry::Volume(*geom) / 12);\n    em_correct.diagonal() *= 2;\n    // Get the element matrix from the element matrix provider\n    Eigen::Matrix3d em_prov = provider.Eval(*cell);\n    // Compare the matrices\n    ASSERT_TRUE(em_correct.isApprox(em_prov));\n  }\n}\n\nTEST(RadauThreeTimestepping, discreteEvolutionOperator) {\n  // Generate a triangular test mesh on [0,1]^2\n  const auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3, 1. / 3);\n  // Create a DOF handler\n  const lf::uscalfe::FeSpaceLagrangeO1<double> fespace(mesh_p);\n  const auto &dofh = fespace.LocGlobMap();\n\n  // Compute A and M\n  lf::uscalfe::LinearFELaplaceElementMatrix A_provider;\n  RadauThreeTimestepping::LinFEMassMatrixProvider M_provider;\n  lf::assemble::COOMatrix<double> A_COO(dofh.NumDofs(), dofh.NumDofs());\n  lf::assemble::COOMatrix<double> M_COO(dofh.NumDofs(), dofh.NumDofs());\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, A_provider, A_COO);\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, M_provider, M_COO);\n  const auto bd_flags = lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 2);\n  const auto selector = [&](unsigned idx) {\n    return bd_flags(dofh.Entity(idx));\n  };\n  RadauThreeTimestepping::dropMatrixRowsColumns(selector, A_COO);\n  RadauThreeTimestepping::dropMatrixRowsColumns(selector, M_COO);\n  Eigen::SparseMatrix<double> A = A_COO.makeSparse();\n  Eigen::SparseMatrix<double> M = M_COO.makeSparse();\n\n  const double dt = 0.0001;\n  const Eigen::VectorXd phi =\n      RadauThreeTimestepping::rhsVectorheatSource(dofh, dt);\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver(M + dt * A);\n  RadauThreeTimestepping::Radau3MOLTimestepper timestepper(dofh);\n  // Test for different mu\n  for (unsigned i = 0; i < dofh.NumDofs(); ++i) {\n    Eigen::VectorXd mu0(dofh.NumDofs());\n    mu0.setZero();\n    mu0[i] = 1;\n    // Compute mu at the next timestep using discreteEvolutionOperator\n    const Eigen::VectorXd mu_dEO =\n        timestepper.discreteEvolutionOperator(0, dt, mu0);\n    // Compute mu at the next timestep using implicit euler\n    const Eigen::VectorXd mu_iE = solver.solve(M * mu0 + dt * phi);\n    // Compare the two mu\n    ASSERT_TRUE((mu_dEO - mu_iE).array().abs().maxCoeff() < 1e-4);\n  }\n}\n\n}  // end namespace RadauThreeTimestepping::test\n", "meta": {"hexsha": "aee499eb5f14ce61e64a4a191a794c81742085e1", "size": 9223, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/RadauThreeTimestepping/templates/test/radauthreetimestepping_test.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/RadauThreeTimestepping/templates/test/radauthreetimestepping_test.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/RadauThreeTimestepping/templates/test/radauthreetimestepping_test.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4918699187, "max_line_length": 80, "alphanum_fraction": 0.6914236149, "num_tokens": 3136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.5748989298723105}}
{"text": "\r\n/*\r\n\r\n\tkrandmptest01.cpp\r\n\r\n\tWritten by Koji Yamamoto\r\n\tCopyright (C) 2020 Koji Yamamoto\r\n\t\r\n\tTesting krandmp Ver.k09.00\r\n\r\n\tUse compilation options:\r\n\t> cl krandmptest01.cpp -EHsc -openmp -Ox\r\n\t> g++ krandmptest01.cpp -std=c++17 -fopenmp -O3\r\n\r\n*/\r\n\t\r\n\r\n/* ********** Preprocessor Directives ********** */\r\n\r\n#include <iostream>\r\n#include <chrono>\r\n\r\n#include <boost/math/tools/bivariate_statistics.hpp>\r\n\r\n#include <k09/krand00.cpp>\r\n#include <k09/krandmp00.cpp>\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\ndouble corr( const std::vector <double> &, const std::vector <double> &);\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 argc, char *argv[])\r\n{\r\n\r\n\tusing time_point = std::chrono::system_clock::time_point;\r\n\r\n\tint npoints = 50000000;\r\n\r\n\tint nmaxthreads = getNMaxThreads();\r\n\tstd::cout << \"N Max Threads: \" << nmaxthreads << std::endl << std::endl;\r\n\r\n\tint nusedthreads = getNUsedThreads();\r\n\tstd::cout << \"N Used Threads: \" << nusedthreads << std::endl << std::endl;\r\n\r\n\t// \u30de\u30eb\u30c1\u30b9\u30ec\u30c3\u30c9\r\n\t{\r\n\t\t\r\n\t\tstd::cout << \"Trial 1: Multi-Threaded\" << std::endl;\r\n\r\n\t\ttime_point startt = std::chrono::system_clock::now();\r\n\t\r\n\t\tRandomNumberEngineMP xrnemp( 123);\r\n\t\tRandomNumberEngineMP yrnemp( 456);\r\n\t\t// below instances will be initialized by moved objects\r\n\t\tstd::vector <double> xvec = xrnemp.getRealUniformSeq( npoints, -1.0, 1.0);\r\n\t\tstd::vector <double> yvec = yrnemp.getRealUniformSeq( npoints, -1.0, 1.0); \r\n\r\n\t\ttime_point endt = std::chrono::system_clock::now();\r\n\t\tauto millisec = std::chrono::duration_cast <chrono::milliseconds> ( endt - startt);\r\n\t\tstd::cout << millisec.count() << \" milliseconds passed.\" << std::endl;\r\n\t\tstd::cout << \"Corr: \" << corr( xvec, yvec) << std::endl;\r\n\t\tstd::cout << std::endl;\r\n\t\t\r\n\t}\r\n\r\n\r\n\t// \u30b7\u30f3\u30b0\u30eb\u30b9\u30ec\u30c3\u30c9\u3067\u306e\u6bd4\u8f03\u7528\r\n\t{\r\n\t\t\r\n\t\tstd::cout << \"Trial 2: Single-Threaded\" << std::endl;\r\n\r\n\t\ttime_point startt = std::chrono::system_clock::now();\r\n\t\r\n\t\tRandomNumberEngine xrne( 123);\r\n\t\tRandomNumberEngine yrne( 456);\r\n\t\t// below instances will be initialized by moved objects\r\n\t\tvector <double> xvec = xrne.getRealUniformSeq( npoints, -1.0, 1.0);\r\n\t\tvector <double> yvec = yrne.getRealUniformSeq( npoints, -1.0, 1.0); \r\n\r\n\t\ttime_point endt = std::chrono::system_clock::now();\r\n\t\tauto millisec = std::chrono::duration_cast <chrono::milliseconds> ( endt - startt);\r\n\t\tstd::cout << millisec.count() << \" milliseconds passed.\" << std::endl;\r\n\t\tstd::cout << \"Corr: \" << corr( xvec, yvec) << std::endl;\r\n\t\tstd::cout << std::endl;\r\n\r\n\t}\r\n\r\n\treturn 0;\r\n\t\r\n}\r\n\r\n\r\ndouble corr( const std::vector <double> &xvec, const std::vector <double> &yvec)\r\n{\r\n\r\n\tdouble ret = boost::math::tools::correlation_coefficient( xvec, yvec);\r\n\treturn ret;\r\n\r\n}\r\n\r\n\r\n/* ********** Definitions of Member Functions ********** */\r\n\r\n", "meta": {"hexsha": "70257efb9e3f49c874bb7b2248ef13e06ef8fbdb", "size": 3158, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "k09/test/krandmptest01.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/test/krandmptest01.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/test/krandmptest01.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": 24.480620155, "max_line_length": 86, "alphanum_fraction": 0.5968967701, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5748989227827451}}
{"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": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <numeric>\n#include <functional>\n\nnamespace northstar {\n    namespace math {\n        namespace types {\n            typedef Eigen::Transform<double, 3, Eigen::TransformTraits::Affine, Eigen::ColMajor> AffineMatrix4d;\n            typedef Eigen::Transform<double, 3, Eigen::TransformTraits::Isometry, Eigen::ColMajor> IsometryMatrix4d;\n            typedef Eigen::Transform<double, 3, Eigen::TransformTraits::AffineCompact, Eigen::ColMajor> AffineMatrix4x3d;\n            typedef Eigen::Transform<double, 3, Eigen::TransformTraits::Projective, Eigen::ColMajor> ProjMatrix4d;\n            typedef Eigen::Translation<double, 3> Translation3d;\n            typedef Eigen::Vector<double, 2> Vector2d;\n            typedef Eigen::Vector<double, 3> Vector3d;\n            typedef Eigen::Vector<double, 4> Vector4d;\n            typedef Eigen::ParametrizedLine<double, 3> Ray3d;\n            typedef Eigen::Hyperplane<double, 3> Plane3d;\n            typedef Eigen::Quaternion<double> Quaterniond;\n            typedef Eigen::Vector<int32_t, 2> Vector2i;\n            typedef Eigen::AngleAxis<double> AngleAxisd;\n            \n            struct SPose {\n                Vector3d position;\n                Quaterniond orientation;\n            };\n\n            struct SSphere {\n                Vector3d origin;\n                double radius;\n            };\n            \n            // NOTE: this hash function gets worse with the number of elements being iterated\n            template<typename T>\n            struct SHasher {\n                std::size_t operator()(const T & IterativeEigen) const {\n                    return std::transform_reduce(\n                        IterativeEigen.begin(),\n                        IterativeEigen.end(),\n                        static_cast<double>(0.0),\n                        std::bit_xor<std::size_t>(),\n                        std::hash<typename T::Scalar>());\n                }\n            };\n        }\n    }\n}", "meta": {"hexsha": "7e1496d16ffa64897af51eaeaed349f83d8282c9", "size": 2000, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "northstar/include/math/Types.hpp", "max_stars_repo_name": "BryanChrisBrown/project_northstar_openvr_driver", "max_stars_repo_head_hexsha": "cf16e98e24804aee699805dca766b8153f4e52e5", "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": "northstar/include/math/Types.hpp", "max_issues_repo_name": "BryanChrisBrown/project_northstar_openvr_driver", "max_issues_repo_head_hexsha": "cf16e98e24804aee699805dca766b8153f4e52e5", "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": "northstar/include/math/Types.hpp", "max_forks_repo_name": "BryanChrisBrown/project_northstar_openvr_driver", "max_forks_repo_head_hexsha": "cf16e98e24804aee699805dca766b8153f4e52e5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8163265306, "max_line_length": 121, "alphanum_fraction": 0.568, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5747295567008587}}
{"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": "/**\n * @file init_rules_test.cpp\n * @author Marcus Edel\n *\n * Tests for the various weight initialize methods.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/core/math/random.hpp>\n\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/layer/layer_types.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n\n#include <mlpack/methods/ann/init_rules/kathirvalavakumar_subavathi_init.hpp>\n#include <mlpack/methods/ann/init_rules/nguyen_widrow_init.hpp>\n#include <mlpack/methods/ann/init_rules/oivs_init.hpp>\n#include <mlpack/methods/ann/init_rules/orthogonal_init.hpp>\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n#include <mlpack/methods/ann/init_rules/const_init.hpp>\n#include <mlpack/methods/ann/init_rules/gaussian_init.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(InitRulesTest);\n\n/**\n * Test the RandomInitialization class with a constant value.\n */\nBOOST_AUTO_TEST_CASE(ConstantInitTest)\n{\n  arma::mat weights;\n  RandomInitialization constantInit(1, 1);\n  constantInit.Initialize(weights, 100, 100);\n\n  bool b = arma::all(arma::vectorise(weights) == 1);\n  BOOST_REQUIRE_EQUAL(b, 1);\n}\n\n/**\n * Simple test of the OrthogonalInitialization class with two different\n * sizes.\n */\nBOOST_AUTO_TEST_CASE(OrthogonalInitTest)\n{\n  arma::mat weights;\n  OrthogonalInitialization orthogonalInit;\n  orthogonalInit.Initialize(weights, 100, 200);\n\n  arma::mat orthogonalWeights = arma::eye<arma::mat>(100, 100);\n  weights *= weights.t();\n\n  for (size_t i = 0; i < weights.n_rows; i++)\n    for (size_t j = 0; j < weights.n_cols; j++)\n      BOOST_REQUIRE_SMALL(weights.at(i, j) - orthogonalWeights.at(i, j), 1e-3);\n\n  orthogonalInit.Initialize(weights, 200, 100);\n  weights = weights.t() * weights;\n\n  for (size_t i = 0; i < weights.n_rows; i++)\n    for (size_t j = 0; j < weights.n_cols; j++)\n      BOOST_REQUIRE_SMALL(weights.at(i, j) - orthogonalWeights.at(i, j), 1e-3);\n}\n\n/**\n * Test the OrthogonalInitialization class with a non default gain.\n */\nBOOST_AUTO_TEST_CASE(OrthogonalInitGainTest)\n{\n  arma::mat weights;\n\n  const double gain = 2;\n  OrthogonalInitialization orthogonalInit(gain);\n  orthogonalInit.Initialize(weights, 100, 200);\n\n  arma::mat orthogonalWeights = arma::eye<arma::mat>(100, 100);\n  orthogonalWeights *= (gain * gain);\n  weights *= weights.t();\n\n  for (size_t i = 0; i < weights.n_rows; i++)\n    for (size_t j = 0; j < weights.n_cols; j++)\n      BOOST_REQUIRE_SMALL(weights.at(i, j) - orthogonalWeights.at(i, j), 1e-3);\n}\n\n/**\n * Test the ConstInitialization class. If you think about it, it's kind of\n * ridiculous to test the const init rule. But at least we make sure it\n * builds without any problems.\n */\nBOOST_AUTO_TEST_CASE(ConstInitTest)\n{\n  arma::mat weights;\n  ConstInitialization zeroInit(0);\n  zeroInit.Initialize(weights, 100, 100);\n\n  bool b = arma::all(arma::vectorise(weights) == 0);\n  BOOST_REQUIRE_EQUAL(b, 1);\n}\n\n/*\n * Simple test of the KathirvalavakumarSubavathiInitialization class with\n * two different sizes.\n */\nBOOST_AUTO_TEST_CASE(KathirvalavakumarSubavathiInitTest)\n{\n  arma::mat data = arma::randu<arma::mat>(100, 1);\n\n  arma::mat weights;\n  arma::cube weights3d;\n\n  KathirvalavakumarSubavathiInitialization kathirvalavakumarSubavathiInit(\n      data, 1.5);\n\n  kathirvalavakumarSubavathiInit.Initialize(weights, 100, 100);\n  kathirvalavakumarSubavathiInit.Initialize(weights3d, 100, 100, 2);\n\n  BOOST_REQUIRE_EQUAL(weights.n_rows, 100);\n  BOOST_REQUIRE_EQUAL(weights.n_cols, 100);\n\n  BOOST_REQUIRE_EQUAL(weights3d.n_rows, 100);\n  BOOST_REQUIRE_EQUAL(weights3d.n_cols, 100);\n  BOOST_REQUIRE_EQUAL(weights3d.n_slices, 2);\n}\n\n/**\n * Simple test of the NguyenWidrowInitialization class.\n */\nBOOST_AUTO_TEST_CASE(NguyenWidrowInitTest)\n{\n  arma::mat weights;\n  arma::cube weights3d;\n\n  NguyenWidrowInitialization nguyenWidrowInit;\n\n  nguyenWidrowInit.Initialize(weights, 100, 100);\n  nguyenWidrowInit.Initialize(weights3d, 100, 100, 2);\n\n  BOOST_REQUIRE_EQUAL(weights.n_rows, 100);\n  BOOST_REQUIRE_EQUAL(weights.n_cols, 100);\n\n  BOOST_REQUIRE_EQUAL(weights3d.n_rows, 100);\n  BOOST_REQUIRE_EQUAL(weights3d.n_cols, 100);\n  BOOST_REQUIRE_EQUAL(weights3d.n_slices, 2);\n}\n\n/**\n * Simple test of the OivsInitialization class with two different sizes.\n */\nBOOST_AUTO_TEST_CASE(OivsInitTest)\n{\n  arma::mat weights;\n  arma::cube weights3d;\n\n  OivsInitialization<> oivsInit;\n\n  oivsInit.Initialize(weights, 100, 100);\n  oivsInit.Initialize(weights3d, 100, 100, 2);\n\n  BOOST_REQUIRE_EQUAL(weights.n_rows, 100);\n  BOOST_REQUIRE_EQUAL(weights.n_cols, 100);\n\n  BOOST_REQUIRE_EQUAL(weights3d.n_rows, 100);\n  BOOST_REQUIRE_EQUAL(weights3d.n_cols, 100);\n  BOOST_REQUIRE_EQUAL(weights3d.n_slices, 2);\n}\n\n/**\n * Simple test of the GaussianInitialization class.\n */\nBOOST_AUTO_TEST_CASE(GaussianInitTest)\n{\n  const size_t rows = 7;\n  const size_t cols = 8;\n  const size_t slices = 2;\n\n  arma::mat weights;\n  arma::cube weights3d;\n\n  GaussianInitialization t(0, 0.2);\n\n  t.Initialize(weights, rows, cols);\n  t.Initialize(weights3d, rows, cols, slices);\n\n  BOOST_REQUIRE_EQUAL(weights.n_rows, rows);\n  BOOST_REQUIRE_EQUAL(weights.n_cols, cols);\n\n  BOOST_REQUIRE_EQUAL(weights3d.n_rows, rows);\n  BOOST_REQUIRE_EQUAL(weights3d.n_cols, cols);\n  BOOST_REQUIRE_EQUAL(weights3d.n_slices, slices);\n}\n\n/**\n * Simple test of the NetworkInitialization class, we test it with every\n * implemented initialization rule and make sure the output is reasonable.\n */\nBOOST_AUTO_TEST_CASE(NetworkInitTest)\n{\n  arma::mat input = arma::ones(5, 1);\n  arma::mat response;\n  NegativeLogLikelihood<> outputLayer;\n\n  // Create a simple network and use the RandomInitialization rule to\n  // initialize the network parameters.\n  RandomInitialization randomInit(0.5, 0.5);\n\n  FFN<NegativeLogLikelihood<>, RandomInitialization> randomModel(\n      std::move(outputLayer), randomInit);\n  randomModel.Add<IdentityLayer<> >();\n  randomModel.Add<Linear<> >(5, 5);\n  randomModel.Add<Linear<> >(5, 2);\n  randomModel.Add<LogSoftMax<> >();\n  randomModel.Predict(input, response);\n\n  bool b = arma::all(arma::vectorise(randomModel.Parameters()) == 0.5);\n  BOOST_REQUIRE_EQUAL(b, 1);\n  BOOST_REQUIRE_EQUAL(randomModel.Parameters().n_elem, 42);\n\n  // Create a simple network and use the OrthogonalInitialization rule to\n  // initialize the network parameters.\n  FFN<NegativeLogLikelihood<>, OrthogonalInitialization> orthogonalModel;\n  orthogonalModel.Add<IdentityLayer<> >();\n  orthogonalModel.Add<Linear<> >(5, 5);\n  orthogonalModel.Add<Linear<> >(5, 2);\n  orthogonalModel.Add<LogSoftMax<> >();\n  orthogonalModel.Predict(input, response);\n\n  BOOST_REQUIRE_EQUAL(orthogonalModel.Parameters().n_elem, 42);\n\n  // Create a simple network and use the ZeroInitialization rule to\n  // initialize the network parameters.\n  FFN<NegativeLogLikelihood<>, ConstInitialization>\n    zeroModel(NegativeLogLikelihood<>(), ConstInitialization(0));\n  zeroModel.Add<IdentityLayer<> >();\n  zeroModel.Add<Linear<> >(5, 5);\n  zeroModel.Add<Linear<> >(5, 2);\n  zeroModel.Add<LogSoftMax<> >();\n  zeroModel.Predict(input, response);\n\n  BOOST_REQUIRE_EQUAL(arma::accu(zeroModel.Parameters()), 0);\n  BOOST_REQUIRE_EQUAL(zeroModel.Parameters().n_elem, 42);\n\n  // Create a simple network and use the\n  // KathirvalavakumarSubavathiInitialization rule to initialize the network\n  // parameters.\n  KathirvalavakumarSubavathiInitialization kathirvalavakumarSubavathiInit(\n      input, 1.5);\n  FFN<NegativeLogLikelihood<>, KathirvalavakumarSubavathiInitialization>\n      ksModel(std::move(outputLayer), kathirvalavakumarSubavathiInit);\n  ksModel.Add<IdentityLayer<> >();\n  ksModel.Add<Linear<> >(5, 5);\n  ksModel.Add<Linear<> >(5, 2);\n  ksModel.Add<LogSoftMax<> >();\n  ksModel.Predict(input, response);\n\n  BOOST_REQUIRE_EQUAL(ksModel.Parameters().n_elem, 42);\n\n  // Create a simple network and use the OivsInitialization rule to\n  // initialize the network parameters.\n  FFN<NegativeLogLikelihood<>, OivsInitialization<> > oivsModel;\n  oivsModel.Add<IdentityLayer<> >();\n  oivsModel.Add<Linear<> >(5, 5);\n  oivsModel.Add<Linear<> >(5, 2);\n  oivsModel.Add<LogSoftMax<> >();\n  oivsModel.Predict(input, response);\n\n  BOOST_REQUIRE_EQUAL(oivsModel.Parameters().n_elem, 42);\n\n  // Create a simple network and use the GaussianInitialization rule to\n  // initialize the network parameters.\n  FFN<NegativeLogLikelihood<>, GaussianInitialization> gaussianModel;\n  gaussianModel.Add<IdentityLayer<> >();\n  gaussianModel.Add<Linear<> >(5, 5);\n  gaussianModel.Add<Linear<> >(5, 2);\n  gaussianModel.Add<LogSoftMax<> >();\n  gaussianModel.Predict(input, response);\n\n  BOOST_REQUIRE_EQUAL(gaussianModel.Parameters().n_elem, 42);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "079c4263e562110ebcc4cd403d2411744df1aaa3", "size": 9000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/init_rules_test.cpp", "max_stars_repo_name": "MJ10/mlpack", "max_stars_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-02T21:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T21:10:55.000Z", "max_issues_repo_path": "src/mlpack/tests/init_rules_test.cpp", "max_issues_repo_name": "MJ10/mlpack", "max_issues_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/init_rules_test.cpp", "max_forks_repo_name": "MJ10/mlpack", "max_forks_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1418685121, "max_line_length": 79, "alphanum_fraction": 0.7435555556, "num_tokens": 2444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5746450587597873}}
{"text": "#include \"fieldtrack/DimensionParser.h\"\n#include \"argus_utils/geometry/PoseSE2.h\"\n#include \"argus_utils/geometry/PoseSE3.h\"\n\n#include <boost/algorithm/string.hpp>\n\nnamespace argus\n{\n\nunsigned int twod_to_threed( unsigned int d )\n{\n\t// NOTE Integer division rounding down\n\tunsigned int order = d / PoseSE2::TangentDimension;\n\tunsigned int ind = d - order * PoseSE2::TangentDimension;\n\tif( ind == 2 ) { ind = 5; } // 2D angle maps to 3D z angle\n\treturn order * PoseSE3::TangentDimension + ind;\n}\n\nMatrixType promote_3d_matrix( bool twoDimensional, unsigned int order )\n{\n\tunsigned int fullDim = PoseSE3::TangentDimension * (order + 1);\n\tif( !twoDimensional )\n\t{\n\t\treturn MatrixType::Identity( fullDim, fullDim );\n\t}\n\t\n\tunsigned int dim = twoDimensional ? PoseSE2::TangentDimension\n\t\t\t\t\t\t\t: PoseSE3::TangentDimension;\n\tunsigned int inDim = dim * (order + 1);\n\t\n\tMatrixType p = MatrixType::Zero( fullDim, inDim );\n\n\tfor( unsigned int i = 0; i < inDim; ++i )\n\t{\n\t\tp( twod_to_threed(i), i ) = 1;\n\t}\n\treturn p;\n}\n\nunsigned int parse_dim_string( const std::string& s,\n                               bool twoDimensional,\n                               unsigned int maxOrder,\n                               unsigned int minOrder )\n{\n\tstd::vector<std::string> splits;\n\tboost::split( splits, s, boost::is_any_of( \"_\" ), boost::token_compress_on );\n\tif( splits.size() != 3 )\n\t{\n\t\tthrow std::invalid_argument( \"String \" + s + \" invalid format\" );\n\t}\n\n\tstd::string typeStr = splits[0];\n\tstd::string dimStr = splits[1];\n\n\tunsigned int order = std::stoi( splits[2] ); // NOTE Should really use stoul\n\tif( order < minOrder || order > maxOrder )\n\t{\n\t\tthrow std::invalid_argument( \"String \" + s + \" order exceeds order limits\" );\n\t}\n\torder = order - minOrder;\n\n\tunsigned int typeInd, dimInd;\n\tif( typeStr == \"pos\" )\n\t{\n\t\ttypeInd = 0;\n\t}\n\telse if( typeStr == \"ori\" )\n\t{\n\t\ttypeInd = twoDimensional ? 0 : 3;\n\t}\n\telse\n\t{\n\t\tthrow std::invalid_argument( \"String \" + s + \" type invalid\" );\n\t}\n\n\tif( dimStr == \"x\" )\n\t{\n\t\tdimInd = 0;\n\t}\n\telse if( dimStr == \"y\" )\n\t{\n\t\tdimInd = 1;\n\t}\n\telse if( dimStr == \"z\" )\n\t{\n\t\tdimInd = 2;\n\t}\n\telse\n\t{\n\t\tthrow std::invalid_argument( \"String \" + s + \" dim invalid\" );\n\t}\n\n\tif( twoDimensional )\n\t{\n\t\tif( (typeStr == \"pos\" && dimStr == \"z\") ||\n\t\t    (typeStr == \"ori\" && dimStr == \"x\") ||\n\t\t    (typeStr == \"ori\" && dimStr == \"y\") )\n\t\t{\n\t\t\tthrow std::invalid_argument( \"String \" + s + \" invalid in 2D mode\" );\n\t\t}\n\t}\n\n\tunsigned int baseDim = twoDimensional ? 3 : 6;\n\n\treturn baseDim * order + typeInd + dimInd;\n}\n\nstd::vector<unsigned int> parse_dim_string( const std::vector<std::string>& s,\n                                            bool twoDimensional,\n                                            unsigned int maxOrder,\n                                            unsigned int minOrder )\n{\n\tstd::vector<unsigned int> ret;\n\tret.reserve( s.size() );\n\tfor( unsigned int i = 0; i < s.size(); ++i )\n\t{\n\t\tret.push_back( parse_dim_string( s[i], twoDimensional, maxOrder, minOrder ) );\n\t}\n\treturn ret;\n}\n}\n", "meta": {"hexsha": "f7ab19c57cca1d742568688720eeb86641c41363", "size": 3007, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DimensionParser.cpp", "max_stars_repo_name": "Humhu/fieldtrack", "max_stars_repo_head_hexsha": "78f787e08c14ebbb102efbfb7bf1cffcb81fb099", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-15T09:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T09:32:18.000Z", "max_issues_repo_path": "src/DimensionParser.cpp", "max_issues_repo_name": "Humhu/fieldtrack", "max_issues_repo_head_hexsha": "78f787e08c14ebbb102efbfb7bf1cffcb81fb099", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DimensionParser.cpp", "max_forks_repo_name": "Humhu/fieldtrack", "max_forks_repo_head_hexsha": "78f787e08c14ebbb102efbfb7bf1cffcb81fb099", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-24T18:42:35.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-24T18:42:35.000Z", "avg_line_length": 24.6475409836, "max_line_length": 80, "alphanum_fraction": 0.5979381443, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.574645048793252}}
{"text": "#include \"RANSAC.h\"\n\n#include \"Line.h\"\n#include <Eigen/Core>\n#include <opencv2/highgui/highgui.hpp>\n\n#include <ctime>\n\nnamespace RANSAC\n{\n\nusing Vector = Eigen::Vector2f;\nusing Line = localization::Line;\n\nVector findBestConvergencePoint(const std::vector<Line>& lines, int k)\n{\n    std::srand(std::time(NULL));\n    float bestDistance = std::numeric_limits<float>::max();\n    Vector bestConvergencePoint(0.0, 0.0);\n    for (int i = 0; i < k; ++i) {\n        const Line& firstLine = lines[std::rand() % lines.size()];\n        const Line& otherLine = lines[std::rand() % lines.size()];\n\n        Vector intersection;\n        bool isIntersecting = firstLine.findIntersection(otherLine, intersection);\n        if (isIntersecting) {\n            double distance = summConvergeDistance(lines, firstLine, intersection);\n            distance += summConvergeDistance(lines, otherLine, intersection);\n            if (distance < bestDistance) {\n                bestConvergencePoint = intersection; \n                bestDistance = distance;\n            }\n        }\n        // else handle parallel lines here.\n    }\n    return bestConvergencePoint;\n}\n\nfloat summConvergeDistance(const std::vector<Line>& lines, const Line& pivot, const Vector& convergence)\n{\n    float distance = 0.0;\n    for (int i = 0; i < lines.size(); ++i) {\n        Vector intersection;\n        bool isIntersecting = lines[i].findIntersection(pivot, intersection);\n        if (isIntersecting) {\n            distance += (intersection - convergence).squaredNorm();\n        }\n    } \n    return distance;\n}\n\nbool findBestOrientationSplit(const std::vector<localization::Line>& lines, int k, Vector bestOrientations[2])\n{\n    std::srand(std::time(NULL));\n    float bestFitWeight = 0.0;\n    for (int i = 0; i < k; ++i) {\n        const Line& line = lines[std::rand() % lines.size()];\n        Vector orientation = line.getOrientation();\n\n        Vector orientations[2] = { orientation, \n                                   { orientation.y(),\n                                    -orientation.x() }};\n        float fitWeight = evaluateOrientationModel(lines, orientations);\n        if (fitWeight > bestFitWeight) {\n            bestFitWeight = fitWeight;\n            bestOrientations[0] = orientations[0];\n            bestOrientations[1] = orientations[1];\n        }\n    }\n    return true;\n}\n\nfloat evaluateOrientationModel(const std::vector<localization::Line>& lines, Eigen::Vector2f orientations[2])\n{\n    double dotSumm = 0.0;\n    for (int i = 0; i < lines.size(); ++i) {\n        Vector u = lines[i].getOrientation();\n\n        double udotv = std::abs(u.dot(orientations[0]));\n        double udotw = std::abs(u.dot(orientations[1]));\n\n        bool isCloserToV = udotv > udotw;\n        dotSumm += (isCloserToV) ? udotv : udotw;\n        int iOrientation = (isCloserToV) ? 0 : 1;\n    }\n    return dotSumm;\n}\n\n}", "meta": {"hexsha": "6c517512653a2d73b76a84f328ba61c7d16c8b49", "size": 2853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/localization/arena-detection/algorithm/RANSAC.cpp", "max_stars_repo_name": "elikos/elikos_localization", "max_stars_repo_head_hexsha": "0eca76e5c836b1b0f407afffe0d1b85605d3cfa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-24T08:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-24T08:29:06.000Z", "max_issues_repo_path": "src/localization/arena-detection/algorithm/RANSAC.cpp", "max_issues_repo_name": "elikos/elikos_localization", "max_issues_repo_head_hexsha": "0eca76e5c836b1b0f407afffe0d1b85605d3cfa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/localization/arena-detection/algorithm/RANSAC.cpp", "max_forks_repo_name": "elikos/elikos_localization", "max_forks_repo_head_hexsha": "0eca76e5c836b1b0f407afffe0d1b85605d3cfa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T23:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-12T23:06:13.000Z", "avg_line_length": 32.0561797753, "max_line_length": 110, "alphanum_fraction": 0.6088328076, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5746450358104829}}
{"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": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\ntemplate <int ROWS>\nusing VecNd = Eigen::Matrix<double, ROWS, 1>;\n\ntemplate <int ROWS, int COLS>\nusing MatNd = Eigen::Matrix<double, ROWS, COLS>;\n\nusing VecXd = Eigen::VectorXd;\nusing MatXd = Eigen::MatrixXd;\n\ntemplate <int ROWS>\nusing SquareMatNd = Eigen::Matrix<double, ROWS, ROWS>;\n\ntemplate <typename Eig>\nusing StdVector = std::vector<Eig, Eigen::aligned_allocator<Eig>>;\n\nnamespace jcc {\nusing Vec1 = VecNd<1>;\nusing Vec2 = Eigen::Vector2d;\nusing Vec3 = Eigen::Vector3d;\nusing Vec4 = Eigen::Vector4d;\nusing Vec5 = VecNd<5>;\nusing Vec6 = VecNd<6>;\n\n}  // namespace jcc\n", "meta": {"hexsha": "3f469581e4c16b6c1ae720154672fb0dba875ab2", "size": 639, "ext": "hh", "lang": "C++", "max_stars_repo_path": "eigen.hh", "max_stars_repo_name": "IJDykeman/experiments-1", "max_stars_repo_head_hexsha": "22badf166b2ea441e953939463f751020b8c251b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-28T04:19:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T04:19:34.000Z", "max_issues_repo_path": "eigen.hh", "max_issues_repo_name": "IJDykeman/experiments-1", "max_issues_repo_head_hexsha": "22badf166b2ea441e953939463f751020b8c251b", "max_issues_repo_licenses": ["MIT"], "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.hh", "max_forks_repo_name": "IJDykeman/experiments-1", "max_forks_repo_head_hexsha": "22badf166b2ea441e953939463f751020b8c251b", "max_forks_repo_licenses": ["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.3, "max_line_length": 66, "alphanum_fraction": 0.7183098592, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5746080811674839}}
{"text": "/**\n * @file kde_test.cpp\n * @author Roberto Hueso\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/kde/kde.hpp>\n#include <mlpack/core/tree/binary_space_tree.hpp>\n#include <mlpack/core/tree/octree.hpp>\n#include <mlpack/core/tree/cover_tree.hpp>\n#include <mlpack/core/tree/rectangle_tree.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n#include \"serialization.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::kde;\nusing namespace mlpack::metric;\nusing namespace mlpack::tree;\nusing namespace mlpack::kernel;\n\nusing namespace boost::serialization;\n\nBOOST_AUTO_TEST_SUITE(KDETest);\n\n// Brute force gaussian KDE.\ntemplate <typename KernelType>\nvoid BruteForceKDE(const arma::mat& reference,\n                   const arma::mat& query,\n                   arma::vec& densities,\n                   KernelType& kernel)\n{\n  metric::EuclideanDistance metric;\n  for (size_t i = 0; i < query.n_cols; ++i)\n  {\n    for (size_t j = 0; j < reference.n_cols; ++j)\n    {\n      double distance = metric.Evaluate(query.col(i), reference.col(j));\n      densities(i) += kernel.Evaluate(distance);\n    }\n  }\n  densities /= reference.n_cols;\n}\n\n/**\n * Test if simple case is correct according to manually calculated results.\n */\nBOOST_AUTO_TEST_CASE(KDESimpleTest)\n{\n  // Transposed reference and query sets because it's easier to read.\n  arma::mat reference = { {-1.0, -1.0},\n                          {-2.0, -1.0},\n                          {-3.0, -2.0},\n                          { 1.0,  1.0},\n                          { 2.0,  1.0},\n                          { 3.0,  2.0} };\n  arma::mat query = { { 0.0,  0.5},\n                      { 0.4, -3.0},\n                      { 0.0,  0.0},\n                      {-2.1,  1.0} };\n  arma::inplace_trans(reference);\n  arma::inplace_trans(query);\n  arma::vec estimations;\n  // Manually calculated results.\n  arma::vec estimationsResult = {0.08323668699564207296148765,\n                                 0.00167470061366603324010116,\n                                 0.07658867126520703394465527,\n                                 0.01028120384800740999553525};\n  KDE<GaussianKernel,\n      EuclideanDistance,\n      arma::mat,\n      KDTree>\n      kde(0.0, 0.01, GaussianKernel(0.8));\n  kde.Train(reference);\n  kde.Evaluate(query, estimations);\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(estimations[i], estimationsResult[i], 0.01);\n}\n\n/**\n * Test Train(Tree...) and Evaluate(Tree...).\n */\nBOOST_AUTO_TEST_CASE(KDETreeAsArguments)\n{\n  // Transposed reference and query sets because it's easier to read.\n  arma::mat reference = { {-1.0, -1.0},\n                          {-2.0, -1.0},\n                          {-3.0, -2.0},\n                          { 1.0,  1.0},\n                          { 2.0,  1.0},\n                          { 3.0,  2.0} };\n  arma::mat query = { { 0.0,  0.5},\n                      { 0.4, -3.0},\n                      { 0.0,  0.0},\n                      {-2.1,  1.0} };\n  arma::inplace_trans(reference);\n  arma::inplace_trans(query);\n  arma::vec estimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec estimationsResult = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.8;\n\n  // Get brute force results.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                estimationsResult,\n                                kernel);\n\n  // Get dual-tree results.\n  typedef KDTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree;\n  std::vector<size_t> oldFromNewQueries, oldFromNewReferences;\n  Tree* queryTree = new Tree(query, oldFromNewQueries, 2);\n  Tree* referenceTree = new Tree(reference, oldFromNewReferences, 2);\n  KDE<GaussianKernel,\n      EuclideanDistance,\n      arma::mat,\n      KDTree>\n      kde(0.0, 1e-6, GaussianKernel(kernelBandwidth));\n  kde.Train(referenceTree, &oldFromNewReferences);\n  kde.Evaluate(queryTree, std::move(oldFromNewQueries), estimations);\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(estimations[i], estimationsResult[i], 0.01);\n  delete queryTree;\n  delete referenceTree;\n}\n\n/**\n * Test dual-tree implementation results against brute force results.\n */\nBOOST_AUTO_TEST_CASE(GaussianKDEBruteForceTest)\n{\n  arma::mat reference = arma::randu(2, 200);\n  arma::mat query = arma::randu(2, 60);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.12;\n  const double relError = 0.05;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::KDTree>\n      kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n}\n\n/**\n * Test single-tree implementation results against brute force results.\n */\nBOOST_AUTO_TEST_CASE(GaussianSingleKDEBruteForceTest)\n{\n  arma::mat reference = arma::randu(2, 300);\n  arma::mat query = arma::randu(2, 100);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.3;\n  const double relError = 0.04;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::KDTree>\n      kde(relError, 0.0, kernel, KDEMode::SINGLE_TREE_MODE, metric);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n}\n\n/**\n * Test single-tree implementation results against brute force results using\n * a cover-tree and Epanechnikov kernel.\n */\nBOOST_AUTO_TEST_CASE(EpanechnikovCoverSingleKDETest)\n{\n  arma::mat reference = arma::randu(2, 300);\n  arma::mat query = arma::randu(2, 100);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 1.1;\n  const double relError = 0.08;\n\n  // Brute force KDE.\n  EpanechnikovKernel kernel(kernelBandwidth);\n  BruteForceKDE<EpanechnikovKernel>(reference,\n                                    query,\n                                    bfEstimations,\n                                    kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<EpanechnikovKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::StandardCoverTree>\n      kde(relError, 0.0, kernel, KDEMode::SINGLE_TREE_MODE, metric);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n}\n\n/**\n * Test single-tree implementation results against brute force results using\n * a cover-tree and Gaussian kernel.\n */\nBOOST_AUTO_TEST_CASE(GaussianCoverSingleKDETest)\n{\n  arma::mat reference = arma::randu(2, 300);\n  arma::mat query = arma::randu(2, 100);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 1.1;\n  const double relError = 0.08;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::StandardCoverTree>\n      kde(relError, 0.0, kernel, KDEMode::SINGLE_TREE_MODE, metric);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n}\n\n/**\n * Test single-tree implementation results against brute force results using\n * an octree and Epanechnikov kernel.\n */\nBOOST_AUTO_TEST_CASE(EpanechnikovOctreeSingleKDETest)\n{\n  arma::mat reference = arma::randu(2, 300);\n  arma::mat query = arma::randu(2, 100);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 1.0;\n  const double relError = 0.05;\n\n  // Brute force KDE.\n  EpanechnikovKernel kernel(kernelBandwidth);\n  BruteForceKDE<EpanechnikovKernel>(reference,\n                                    query,\n                                    bfEstimations,\n                                    kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<EpanechnikovKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::Octree>\n      kde(relError, 0.0, kernel, KDEMode::SINGLE_TREE_MODE, metric);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n}\n\n/**\n * Test BallTree dual-tree implementation results against brute force results.\n */\nBOOST_AUTO_TEST_CASE(BallTreeGaussianKDETest)\n{\n  arma::mat reference = arma::randu(2, 200);\n  arma::mat query = arma::randu(2, 60);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.4;\n  const double relError = 0.05;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // BallTree KDE.\n  typedef BallTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree;\n  std::vector<size_t> oldFromNewQueries, oldFromNewReferences;\n  Tree* queryTree = new Tree(query, oldFromNewQueries, 2);\n  Tree* referenceTree = new Tree(reference, oldFromNewReferences, 2);\n  KDE<GaussianKernel,\n      EuclideanDistance,\n      arma::mat,\n      BallTree>\n      kde(relError, 0.0, GaussianKernel(kernelBandwidth));\n  kde.Train(referenceTree, &oldFromNewReferences);\n  kde.Evaluate(queryTree, std::move(oldFromNewQueries), treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n\n  delete queryTree;\n  delete referenceTree;\n}\n\n/**\n * Test Octree dual-tree implementation results against brute force results.\n */\nBOOST_AUTO_TEST_CASE(OctreeGaussianKDETest)\n{\n  arma::mat reference = arma::randu(2, 500);\n  arma::mat query = arma::randu(2, 200);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.3;\n  const double relError = 0.01;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::Octree>\n      kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n}\n\n/**\n * Test RTree dual-tree implementation results against brute force results.\n */\nBOOST_AUTO_TEST_CASE(RTreeGaussianKDETest)\n{\n  arma::mat reference = arma::randu(2, 500);\n  arma::mat query = arma::randu(2, 200);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.3;\n  const double relError = 0.01;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::RTree>\n      kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n}\n\n/**\n * Test Standard Cover Tree dual-tree implementation results against brute\n * force results using Gaussian kernel.\n */\nBOOST_AUTO_TEST_CASE(StandardCoverTreeGaussianKDETest)\n{\n  arma::mat reference = arma::randu(2, 500);\n  arma::mat query = arma::randu(2, 200);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.3;\n  const double relError = 0.01;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::StandardCoverTree>\n      kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n}\n\n/**\n * Test Standard Cover Tree dual-tree implementation results against brute\n * force results using Epanechnikov kernel.\n */\nBOOST_AUTO_TEST_CASE(StandardCoverTreeEpanechnikovKDETest)\n{\n  arma::mat reference = arma::randu(2, 500);\n  arma::mat query = arma::randu(2, 200);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.3;\n  const double relError = 0.01;\n\n  // Brute force KDE.\n  EpanechnikovKernel kernel(kernelBandwidth);\n  BruteForceKDE<EpanechnikovKernel>(reference,\n                                    query,\n                                    bfEstimations,\n                                    kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<EpanechnikovKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::StandardCoverTree>\n      kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n}\n\n/**\n * Test duplicated value in reference matrix.\n */\nBOOST_AUTO_TEST_CASE(DuplicatedReferenceSampleKDETest)\n{\n  arma::mat reference = arma::randu(2, 30);\n  arma::mat query = arma::randu(2, 10);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.4;\n  const double relError = 0.05;\n\n  // Duplicate value.\n  reference.col(2) = reference.col(3);\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Dual-tree KDE.\n  typedef KDTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree;\n  std::vector<size_t> oldFromNewQueries, oldFromNewReferences;\n  Tree* queryTree = new Tree(query, oldFromNewQueries, 2);\n  Tree* referenceTree = new Tree(reference, oldFromNewReferences, 2);\n  KDE<GaussianKernel,\n      EuclideanDistance,\n      arma::mat,\n      KDTree>\n      kde(relError, 0.0, GaussianKernel(kernelBandwidth));\n  kde.Train(referenceTree, &oldFromNewReferences);\n  kde.Evaluate(queryTree, oldFromNewQueries, treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n\n  delete queryTree;\n  delete referenceTree;\n}\n\n/**\n * Test duplicated value in query matrix.\n */\nBOOST_AUTO_TEST_CASE(DuplicatedQuerySampleKDETest)\n{\n  arma::mat reference = arma::randu(2, 30);\n  arma::mat query = arma::randu(2, 10);\n  arma::vec estimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.4;\n  const double relError = 0.05;\n\n  // Duplicate value.\n  query.col(2) = query.col(3);\n\n  // Dual-tree KDE.\n  typedef KDTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree;\n  std::vector<size_t> oldFromNewQueries, oldFromNewReferences;\n  Tree* queryTree = new Tree(query, oldFromNewQueries, 2);\n  Tree* referenceTree = new Tree(reference, oldFromNewReferences, 2);\n  KDE<GaussianKernel,\n      EuclideanDistance,\n      arma::mat,\n      KDTree>\n      kde(relError, 0.0, GaussianKernel(kernelBandwidth));\n  kde.Train(referenceTree, &oldFromNewReferences);\n  kde.Evaluate(queryTree, oldFromNewQueries, estimations);\n\n  // Check whether results are equal.\n  BOOST_REQUIRE_CLOSE(estimations[2], estimations[3], relError * 100);\n\n  delete queryTree;\n  delete referenceTree;\n}\n\n/**\n * Test dual-tree breadth-first implementation results against brute force\n * results.\n */\nBOOST_AUTO_TEST_CASE(BreadthFirstKDETest)\n{\n  arma::mat reference = arma::randu(2, 200);\n  arma::mat query = arma::randu(2, 60);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.8;\n  const double relError = 0.01;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Breadth-First KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::KDTree,\n      tree::KDTree<metric::EuclideanDistance,\n                   kde::KDEStat,\n                   arma::mat>::template BreadthFirstDualTreeTraverser>\n      kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n}\n\n/**\n * Test 1-dimensional implementation results against brute force results.\n */\nBOOST_AUTO_TEST_CASE(OneDimensionalTest)\n{\n  arma::mat reference = arma::randu(1, 200);\n  arma::mat query = arma::randu(1, 60);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.7;\n  const double relError = 0.01;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::KDTree>\n      kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // Check whether results are equal.\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100);\n}\n\n/**\n * Test a case where an empty reference set is given to train the model.\n */\nBOOST_AUTO_TEST_CASE(EmptyReferenceTest)\n{\n  arma::mat reference;\n  arma::mat query = arma::randu(1, 10);\n  arma::vec estimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.7;\n  const double relError = 0.01;\n\n  // KDE.\n  metric::EuclideanDistance metric;\n  GaussianKernel kernel(kernelBandwidth);\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::KDTree>\n      kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);\n\n  // When training using the dataset matrix.\n  BOOST_REQUIRE_THROW(kde.Train(reference), std::invalid_argument);\n\n  // When training using a tree.\n  std::vector<size_t> oldFromNewReferences;\n  typedef KDTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree;\n  Tree* referenceTree = new Tree(reference, oldFromNewReferences, 2);\n  BOOST_REQUIRE_THROW(\n      kde.Train(referenceTree, &oldFromNewReferences), std::invalid_argument);\n\n  delete referenceTree;\n}\n\n/**\n * Tests when reference set values and query set values dimensions don't match.\n */\nBOOST_AUTO_TEST_CASE(EvaluationMatchDimensionsTest)\n{\n  arma::mat reference = arma::randu(3, 10);\n  arma::mat query = arma::randu(1, 10);\n  arma::vec estimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.7;\n  const double relError = 0.01;\n\n  // KDE.\n  metric::EuclideanDistance metric;\n  GaussianKernel kernel(kernelBandwidth);\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::KDTree>\n      kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);\n  kde.Train(reference);\n\n  // When evaluating using the query dataset matrix.\n  BOOST_REQUIRE_THROW(kde.Evaluate(query, estimations),\n                    std::invalid_argument);\n\n  // When evaluating using a query tree.\n  typedef KDTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree;\n  std::vector<size_t> oldFromNewQueries;\n  Tree* queryTree = new Tree(query, oldFromNewQueries, 3);\n  BOOST_REQUIRE_THROW(kde.Evaluate(queryTree, oldFromNewQueries, estimations),\n                    std::invalid_argument);\n  delete queryTree;\n}\n\n/**\n * Tests when an empty query set is given to be evaluated.\n */\nBOOST_AUTO_TEST_CASE(EmptyQuerySetTest)\n{\n  arma::mat reference = arma::randu(1, 10);\n  arma::mat query;\n  // Set estimations to the wrong size.\n  arma::vec estimations(33, arma::fill::zeros);\n  const double kernelBandwidth = 0.7;\n  const double relError = 0.01;\n\n  // KDE.\n  metric::EuclideanDistance metric;\n  GaussianKernel kernel(kernelBandwidth);\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::KDTree>\n      kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);\n  kde.Train(reference);\n\n  // The query set must be empty.\n  BOOST_REQUIRE_EQUAL(query.n_cols, 0);\n  // When evaluating using the query dataset matrix.\n  BOOST_REQUIRE_NO_THROW(kde.Evaluate(query, estimations));\n\n  // When evaluating using a query tree.\n  typedef KDTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree;\n  std::vector<size_t> oldFromNewQueries;\n  Tree* queryTree = new Tree(query, oldFromNewQueries, 3);\n  BOOST_REQUIRE_NO_THROW(\n      kde.Evaluate(queryTree, oldFromNewQueries, estimations));\n  delete queryTree;\n\n  // Estimations must be empty.\n  BOOST_REQUIRE_EQUAL(estimations.size(), 0);\n}\n\n/**\n * Tests serialiation of KDE models.\n */\nBOOST_AUTO_TEST_CASE(SerializationTest)\n{\n  // Initial KDE model to be serialized.\n  const double relError = 0.25;\n  const double absError = 0.0;\n  const bool monteCarlo = false;\n  const double MCProb = 0.8;\n  const size_t initialSampleSize = 35;\n  const double entryCoef = 5;\n  const double breakCoef = 0.6;\n  arma::mat reference = arma::randu(4, 800);\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::KDTree>\n    kde(relError,\n        absError,\n        GaussianKernel(0.25),\n        KDEMode::DUAL_TREE_MODE,\n        metric::EuclideanDistance(),\n        monteCarlo,\n        MCProb,\n        initialSampleSize,\n        entryCoef,\n        breakCoef);\n  kde.Train(reference);\n\n  // Get estimations to compare.\n  arma::mat query = arma::randu(4, 100);;\n  arma::vec estimations = arma::vec(query.n_cols, arma::fill::zeros);\n  kde.Evaluate(query, estimations);\n\n  // Initialize serialized objects.\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::KDTree> kdeXml, kdeText, kdeBinary;\n  SerializeObjectAll(kde, kdeXml, kdeText, kdeBinary);\n\n  // Check everything is correct.\n  BOOST_REQUIRE_CLOSE(kde.RelativeError(), relError, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeXml.RelativeError(), relError, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeText.RelativeError(), relError, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeBinary.RelativeError(), relError, 1e-8);\n\n  BOOST_REQUIRE_CLOSE(kde.AbsoluteError(), absError, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeXml.AbsoluteError(), absError, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeText.AbsoluteError(), absError, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeBinary.AbsoluteError(), absError, 1e-8);\n\n  BOOST_REQUIRE_EQUAL(kde.IsTrained(), true);\n  BOOST_REQUIRE_EQUAL(kdeXml.IsTrained(), true);\n  BOOST_REQUIRE_EQUAL(kdeText.IsTrained(), true);\n  BOOST_REQUIRE_EQUAL(kdeBinary.IsTrained(), true);\n\n  const KDEMode mode = KDEMode::DUAL_TREE_MODE;\n  BOOST_REQUIRE_EQUAL(kde.Mode(), mode);\n  BOOST_REQUIRE_EQUAL(kdeXml.Mode(), mode);\n  BOOST_REQUIRE_EQUAL(kdeText.Mode(), mode);\n  BOOST_REQUIRE_EQUAL(kdeBinary.Mode(), mode);\n\n  BOOST_REQUIRE_EQUAL(kde.MonteCarlo(), monteCarlo);\n  BOOST_REQUIRE_EQUAL(kdeXml.MonteCarlo(), monteCarlo);\n  BOOST_REQUIRE_EQUAL(kdeText.MonteCarlo(), monteCarlo);\n  BOOST_REQUIRE_EQUAL(kdeBinary.MonteCarlo(), monteCarlo);\n\n  BOOST_REQUIRE_CLOSE(kde.MCProb(), MCProb, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeXml.MCProb(), MCProb, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeText.MCProb(), MCProb, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeBinary.MCProb(), MCProb, 1e-8);\n\n  BOOST_REQUIRE_EQUAL(kde.MCInitialSampleSize(), initialSampleSize);\n  BOOST_REQUIRE_EQUAL(kdeXml.MCInitialSampleSize(), initialSampleSize);\n  BOOST_REQUIRE_EQUAL(kdeText.MCInitialSampleSize(), initialSampleSize);\n  BOOST_REQUIRE_EQUAL(kdeBinary.MCInitialSampleSize(), initialSampleSize);\n\n  BOOST_REQUIRE_CLOSE(kde.MCEntryCoef(), entryCoef, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeXml.MCEntryCoef(), entryCoef, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeText.MCEntryCoef(), entryCoef, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeBinary.MCEntryCoef(), entryCoef, 1e-8);\n\n  BOOST_REQUIRE_CLOSE(kde.MCBreakCoef(), breakCoef, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeXml.MCBreakCoef(), breakCoef, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeText.MCBreakCoef(), breakCoef, 1e-8);\n  BOOST_REQUIRE_CLOSE(kdeBinary.MCBreakCoef(), breakCoef, 1e-8);\n\n  // Test if execution gives the same result.\n  arma::vec xmlEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec textEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec binEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n\n  kdeXml.Evaluate(query, xmlEstimations);\n  kdeText.Evaluate(query, textEstimations);\n  kdeBinary.Evaluate(query, binEstimations);\n\n  for (size_t i = 0; i < query.n_cols; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(estimations[i], xmlEstimations[i], relError * 100);\n    BOOST_REQUIRE_CLOSE(estimations[i], textEstimations[i], relError * 100);\n    BOOST_REQUIRE_CLOSE(estimations[i], binEstimations[i], relError * 100);\n  }\n}\n\n/**\n * Test if the copy constructor and copy operator works properly.\n */\nBOOST_AUTO_TEST_CASE(CopyConstructor)\n{\n  arma::mat reference = arma::randu(2, 300);\n  arma::mat query = arma::randu(2, 100);\n  arma::vec estimations1, estimations2, estimations3;\n  const double kernelBandwidth = 1.5;\n  const double relError = 0.05;\n\n  typedef KDE<GaussianKernel, metric::EuclideanDistance, arma::mat>\n      KDEType;\n\n  // KDE.\n  KDEType kde(relError, 0, kernel::GaussianKernel(kernelBandwidth));\n  kde.Train(std::move(reference));\n\n  // Copy constructor KDE.\n  KDEType constructor(kde);\n\n  // Copy operator KDE.\n  KDEType oper = kde;\n\n  // Evaluations.\n  kde.Evaluate(query, estimations1);\n  constructor.Evaluate(query, estimations2);\n  oper.Evaluate(query, estimations3);\n\n  // Check results.\n  for (size_t i = 0; i < query.n_cols; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(estimations1[i], estimations2[i], 1e-10);\n    BOOST_REQUIRE_CLOSE(estimations2[i], estimations3[i], 1e-10);\n  }\n}\n\n/**\n * Test if the move constructor works properly.\n */\nBOOST_AUTO_TEST_CASE(MoveConstructor)\n{\n  arma::mat reference = arma::randu(2, 300);\n  arma::mat query = arma::randu(2, 100);\n  arma::vec estimations1, estimations2, estimations3;\n  const double kernelBandwidth = 1.2;\n  const double relError = 0.05;\n\n  typedef KDE<EpanechnikovKernel, metric::EuclideanDistance, arma::mat>\n      KDEType;\n\n  // KDE.\n  KDEType kde(relError, 0, kernel::EpanechnikovKernel(kernelBandwidth));\n  kde.Train(std::move(reference));\n  kde.Evaluate(query, estimations1);\n\n  // Move constructor KDE.\n  KDEType constructor(std::move(kde));\n  constructor.Evaluate(query, estimations2);\n\n  // Check results.\n  BOOST_REQUIRE_THROW(kde.Evaluate(query, estimations3), std::runtime_error);\n  for (size_t i = 0; i < query.n_cols; ++i)\n    BOOST_REQUIRE_CLOSE(estimations1[i], estimations2[i], 1e-10);\n}\n\n/**\n * Test if an untrained KDE works properly.\n */\nBOOST_AUTO_TEST_CASE(NotTrained)\n{\n  arma::mat query = arma::randu(1, 10);\n  std::vector<size_t> oldFromNew;\n  arma::vec estimations;\n\n  KDE<> kde;\n  KDE<>::Tree queryTree(query, oldFromNew);\n\n  // Check results.\n  BOOST_REQUIRE_THROW(kde.Evaluate(query, estimations), std::runtime_error);\n  BOOST_REQUIRE_THROW(kde.Evaluate(&queryTree, oldFromNew, estimations),\n                      std::runtime_error);\n  BOOST_REQUIRE_THROW(kde.Evaluate(estimations), std::runtime_error);\n}\n\n/**\n * Test single KD-tree implementation results against brute force results using\n * Monte Carlo estimations when possible.\n */\nBOOST_AUTO_TEST_CASE(GaussianSingleKDTreeMonteCarloKDE)\n{\n  arma::mat reference = arma::randu(2, 3000);\n  arma::mat query = arma::randu(2, 100);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.35;\n  const double relError = 0.05;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::KDTree>\n    kde(relError,\n        0.0,\n        kernel,\n        KDEMode::SINGLE_TREE_MODE,\n        metric,\n        true,\n        0.95,\n        100,\n        2,\n        0.7);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // The Monte Carlo estimation has a random component so it can fail. Therefore\n  // we require a reasonable amount of results to be right.\n  size_t correctResults = 0;\n  for (size_t i = 0; i < query.n_cols; ++i)\n  {\n    const double resultRelativeError =\n      std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]);\n    if (resultRelativeError < relError)\n      ++correctResults;\n  }\n\n  BOOST_REQUIRE_GT(correctResults, 70);\n}\n\n/**\n * Test single cover-tree implementation results against brute force results\n * using Monte Carlo estimations when possible.\n */\nBOOST_AUTO_TEST_CASE(GaussianSingleCoverTreeMonteCarloKDE)\n{\n  arma::mat reference = arma::randu(2, 3000);\n  arma::mat query = arma::randu(2, 100);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.35;\n  const double relError = 0.05;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::StandardCoverTree>\n    kde(relError,\n        0.0,\n        kernel,\n        KDEMode::SINGLE_TREE_MODE,\n        metric,\n        true,\n        0.95,\n        100,\n        2,\n        0.7);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // The Monte Carlo estimation has a random component so it can fail. Therefore\n  // we require a reasonable amount of results to be right.\n  size_t correctResults = 0;\n  for (size_t i = 0; i < query.n_cols; ++i)\n  {\n    const double resultRelativeError =\n      std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]);\n    if (resultRelativeError < relError)\n      ++correctResults;\n  }\n\n  BOOST_REQUIRE_GT(correctResults, 70);\n}\n\n/**\n * Test single octree implementation results against brute force results\n * using Monte Carlo estimations when possible.\n */\nBOOST_AUTO_TEST_CASE(GaussianSingleOctreeMonteCarloKDE)\n{\n  arma::mat reference = arma::randu(2, 3000);\n  arma::mat query = arma::randu(2, 100);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.55;\n  const double relError = 0.02;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::Octree>\n    kde(relError,\n        0.0,\n        kernel,\n        KDEMode::SINGLE_TREE_MODE,\n        metric,\n        true,\n        0.95,\n        100,\n        3,\n        0.8);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // The Monte Carlo estimation has a random component so it can fail. Therefore\n  // we require a reasonable amount of results to be right.\n  size_t correctResults = 0;\n  for (size_t i = 0; i < query.n_cols; ++i)\n  {\n    const double resultRelativeError =\n      std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]);\n    if (resultRelativeError < relError)\n      ++correctResults;\n  }\n\n  BOOST_REQUIRE_GT(correctResults, 70);\n}\n\n/**\n * Test dual kd-tree implementation results against brute force results\n * using Monte Carlo estimations when possible.\n */\nBOOST_AUTO_TEST_CASE(GaussianDualKDTreeMonteCarloKDE)\n{\n  arma::mat reference = arma::randu(2, 3000);\n  arma::mat query = arma::randu(2, 200);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.4;\n  const double relError = 0.05;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::KDTree>\n    kde(relError,\n        0.0,\n        kernel,\n        KDEMode::DUAL_TREE_MODE,\n        metric,\n        true,\n        0.95,\n        100,\n        3,\n        0.8);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // The Monte Carlo estimation has a random component so it can fail. Therefore\n  // we require a reasonable amount of results to be right.\n  size_t correctResults = 0;\n  for (size_t i = 0; i < query.n_cols; ++i)\n  {\n    const double resultRelativeError =\n      std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]);\n    if (resultRelativeError < relError)\n      ++correctResults;\n  }\n\n  BOOST_REQUIRE_GT(correctResults, 70);\n}\n\n/**\n * Test dual Cover-tree implementation results against brute force results\n * using Monte Carlo estimations when possible.\n */\nBOOST_AUTO_TEST_CASE(GaussianDualCoverTreeMonteCarloKDE)\n{\n  arma::mat reference = arma::randu(2, 3000);\n  arma::mat query = arma::randu(2, 200);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.5;\n  const double relError = 0.025;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::StandardCoverTree>\n    kde(relError,\n        0.0,\n        kernel,\n        KDEMode::DUAL_TREE_MODE,\n        metric,\n        true,\n        0.95,\n        100,\n        3,\n        0.8);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // The Monte Carlo estimation has a random component so it can fail. Therefore\n  // we require a reasonable amount of results to be right.\n  size_t correctResults = 0;\n  for (size_t i = 0; i < query.n_cols; ++i)\n  {\n    const double resultRelativeError =\n      std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]);\n    if (resultRelativeError < relError)\n      ++correctResults;\n  }\n\n  BOOST_REQUIRE_GT(correctResults, 70);\n}\n\n/**\n * Test dual octree implementation results against brute force results\n * using Monte Carlo estimations when possible.\n */\nBOOST_AUTO_TEST_CASE(GaussianDualOctreeMonteCarloKDE)\n{\n  arma::mat reference = arma::randu(2, 3000);\n  arma::mat query = arma::randu(2, 200);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.7;\n  const double relError = 0.03;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::Octree>\n    kde(relError,\n        0.0,\n        kernel,\n        KDEMode::DUAL_TREE_MODE,\n        metric,\n        true,\n        0.95,\n        100,\n        3,\n        0.8);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // The Monte Carlo estimation has a random component so it can fail. Therefore\n  // we require a reasonable amount of results to be right.\n  size_t correctResults = 0;\n  for (size_t i = 0; i < query.n_cols; ++i)\n  {\n    const double resultRelativeError =\n      std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]);\n    if (resultRelativeError < relError)\n      ++correctResults;\n  }\n\n  BOOST_REQUIRE_GT(correctResults, 70);\n}\n\n/**\n * Test dual kd-tree breadth first traversal implementation results against\n * brute force results using Monte Carlo estimations when possible.\n */\nBOOST_AUTO_TEST_CASE(GaussianBreadthDualKDTreeMonteCarloKDE)\n{\n  arma::mat reference = arma::randu(2, 3000);\n  arma::mat query = arma::randu(2, 200);\n  arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros);\n  const double kernelBandwidth = 0.7;\n  const double relError = 0.025;\n\n  // Brute force KDE.\n  GaussianKernel kernel(kernelBandwidth);\n  BruteForceKDE<GaussianKernel>(reference,\n                                query,\n                                bfEstimations,\n                                kernel);\n\n  // Optimized KDE.\n  metric::EuclideanDistance metric;\n  KDE<GaussianKernel,\n      metric::EuclideanDistance,\n      arma::mat,\n      tree::KDTree,\n      tree::KDTree<metric::EuclideanDistance,\n                   kde::KDEStat,\n                   arma::mat>::template BreadthFirstDualTreeTraverser>\n    kde(relError,\n        0.0,\n        kernel,\n        KDEMode::DUAL_TREE_MODE,\n        metric,\n        true,\n        0.95,\n        100,\n        3,\n        0.8);\n  kde.Train(reference);\n  kde.Evaluate(query, treeEstimations);\n\n  // The Monte Carlo estimation has a random component so it can fail. Therefore\n  // we require a reasonable amount of results to be right.\n  size_t correctResults = 0;\n  for (size_t i = 0; i < query.n_cols; ++i)\n  {\n    const double resultRelativeError =\n      std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]);\n    if (resultRelativeError < relError)\n      ++correctResults;\n  }\n\n  BOOST_REQUIRE_GT(correctResults, 70);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "81da7bb0fdce77a951bb42cc298fd81ee856b140", "size": 42001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/kde_test.cpp", "max_stars_repo_name": "tomjpsun/mlpack", "max_stars_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-11T14:14:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T14:14:30.000Z", "max_issues_repo_path": "src/mlpack/tests/kde_test.cpp", "max_issues_repo_name": "tomjpsun/mlpack", "max_issues_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-10T17:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-11T14:56:25.000Z", "max_forks_repo_path": "src/mlpack/tests/kde_test.cpp", "max_forks_repo_name": "tomjpsun/mlpack", "max_forks_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1846743295, "max_line_length": 80, "alphanum_fraction": 0.6614366325, "num_tokens": 11138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6825737473266736, "lm_q1q2_score": 0.5746080758054799}}
{"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": "#pragma once\n\n#include \"util.hpp\"\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/ring.hpp>\n#include <boost/geometry/algorithms/covered_by.hpp>\n\n#ifndef HABITAT_H\n#define HABITAT_H\n\ntypedef boost::geometry::model::point<double,2,boost::geometry::cs::cartesian> Point;\ntypedef boost::geometry::model::ring<Point> Ring;\n\n/*\n The habitat is represented as a ring (a polygon without holes).\n The vertices of the ring are specified by the user in the file `datapath.outer`.\n For example, suppose that `datapath.outer` contains the following six lines:\n 0 0\n 3 3\n 0 6\n 12 6\n 12 0\n 0 0\n Then the habitat is given by (0,0) - (3,3) - (0,6) - (12,6) - (12,0) - (0,0).\n The vertices of the population graph (the demes) will fall inside the habitat by construction.\n \n However, EEMS will not check that the sampling locations fall inside the habitat -- instead,\n each sample will be assigned to the closest deme. Therefore, the user should specify a habitat\n that is sufficiently large to cover all sampling locations.\n */\n\nclass Habitat {\npublic:\n    \n    Habitat( );\n    ~Habitat( );\n    \n    void generate_outer(const string &datapath);\n    bool dlmwrite_outer(const string &mcmcpath) const;\n    bool in_point(const double x, const double y) const;\n    \n    double get_area( ) const;\n    double get_xmin( ) const;\n    double get_xmax( ) const;\n    double get_ymin( ) const;\n    double get_ymax( ) const;\n    double get_xspan( ) const;\n    double get_yspan( ) const;\n    \nprivate:\n    \n    Ring domain;\n    double xmin, xmax, xspan;\n    double ymin, ymax, yspan;\n    \n};\n\n#endif\n", "meta": {"hexsha": "df9c553e78c44b9baad8412ff0ad5441eeda3ee9", "size": 1635, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/habitat.hpp", "max_stars_repo_name": "halasadi/eems2", "max_stars_repo_head_hexsha": "92c6b54cdd2cf30c0c363fa716487f4ace584fd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-10-20T15:47:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:25:11.000Z", "max_issues_repo_path": "src/habitat.hpp", "max_issues_repo_name": "halasadi/eems2", "max_issues_repo_head_hexsha": "92c6b54cdd2cf30c0c363fa716487f4ace584fd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-01-05T16:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-04T09:41:02.000Z", "max_forks_repo_path": "src/habitat.hpp", "max_forks_repo_name": "halasadi/eems2", "max_forks_repo_head_hexsha": "92c6b54cdd2cf30c0c363fa716487f4ace584fd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-04-09T09:07:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T14:31:57.000Z", "avg_line_length": 26.8032786885, "max_line_length": 95, "alphanum_fraction": 0.7033639144, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5746080649338494}}
{"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": "// Copyright (c) 2005-2009  INRIA Sophia-Antipolis (France).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org); you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public License as\n// published by the Free Software Foundation; either version 3 of the License,\n// or (at your option) any later version.\n//\n// Licensees holding a valid commercial license may use this file in\n// accordance with the commercial license agreement provided with the software.\n//\n// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n//\n// $URL$\n// $Id$\n// \n//\n// Author(s)     : Sebastien Loriot, Sylvain Pion\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include<boost/shared_ptr.hpp>\n#include <CGAL/CGAL_Ipelet_base.h> \n#include<CGAL/create_offset_polygons_2.h>\n#include <boost/format.hpp>\n\n\nnamespace CGAL_skeleton{\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\n  \nconst std::string Slab[] = {\n  \"Interior skeleton\", \"Exterior skeleton\",\"Interior offset\",\"Exterior offset\",\"Interior offsets\",\"Exterior offsets\", \"Help\"\n};\n\nconst std::string Hmsg[] = {\n  \"Draw the interior skeleton of one polygon\",\n  \"Draw the exterior skeleton of one polygon\",\n  \"Draw an interior offset of one polygon\",\n  \"Draw an exterior offset of one polygon\",\n  \"Draw several interior offsets of one polygon\",\n  \"Draw several exterior offsets of one polygon\"\n};\n\n\nclass SkeletonIpelet \n  : public CGAL::Ipelet_base<Kernel,7>{\n    \n  typedef boost::shared_ptr<Polygon_2>        PolygonPtr ;\n  typedef std::vector<PolygonPtr>             PolygonPtrVector ;    \n  typedef CGAL::Straight_skeleton_2<Kernel>   Skeleton ;\n  typedef boost::shared_ptr<Skeleton>         SkeletonPtr ;\n\n  void draw_straight_skeleton(const Skeleton& skeleton,double);\n    \npublic:\n  SkeletonIpelet()\n    :CGAL::Ipelet_base<Kernel,7>(\"Skeleton and offset\",Slab,Hmsg){}\n  void protected_run(int);\n};\n\nvoid SkeletonIpelet::draw_straight_skeleton(const Skeleton& skeleton,double /*max_edge*/)\n{\n  typedef Skeleton::Vertex_const_handle     Vertex_const_handle ;\n  typedef Skeleton::Halfedge_const_handle   Halfedge_const_handle ;\n  typedef Skeleton::Halfedge_const_iterator Halfedge_const_iterator ;\n  \n  Halfedge_const_handle null_halfedge ;\n  Vertex_const_handle   null_vertex ;\n\n  std::list<Segment_2> seglist;\n  std::back_insert_iterator< std::list<Segment_2> > out=std::back_inserter(seglist);\n  \n  for ( Halfedge_const_iterator i = skeleton.halfedges_begin();\n                                i != skeleton.halfedges_end();\n                                ++i )\n    if ( i->is_bisector() && ((i->id()%2)==0) ){\n        out++=Segment_2(i->opposite()->vertex()->point(),i->vertex()->point());\n    }\n  draw_in_ipe(seglist.begin(),seglist.end());\n}\n\nvoid SkeletonIpelet::protected_run(int fn)\n{\n  \n  if (fn==6) {\n    show_help();\n    return;\n  }\n\n  std::list<Polygon_2> pol_list;\n  Iso_rectangle_2 bbox=\n    read_active_objects( CGAL::dispatch_or_drop_output<Polygon_2>( std::back_inserter(pol_list) ) );\n\n  \n  \n  if (pol_list.size()!=1){\n    print_error_message(\"Exactly one polygon must be selected\");\n    return;\n  }\n  \n  Polygon_2 polygon=*pol_list.begin();\n  \n    \n  if (!polygon.is_simple()){\n    print_error_message(\"Polygon must be simple\");\n    return;\n  }\n  \n  if (polygon.orientation()!=CGAL::COUNTERCLOCKWISE)\n    polygon.reverse_orientation();\n  \n  std::list<double> offsets;\n    //~ \"Interior skeleton\", \"Exterior skeleton\",\"Interior offset\",\"Exterior offset\",\"Interior offsets\",\"Exterior offsets\", \"Help\"\n  SkeletonPtr ss;\n  double max_edge=std::max((bbox.xmax()-bbox.xmin()),(bbox.ymax()-bbox.ymin()));\n  double dist=0.;\n  int ret_val=-1;\n  switch(fn){\n    case 3://Exterior offset\n    case 5://Exterior offsets\n    case 1://Exterior skeleton\n      ss = CGAL::create_exterior_straight_skeleton_2(max_edge,polygon);      \n      break;\n    case 2://Interior offset\n    case 4://Interior offsets\n    case 0://Interior skeleton\n      ss = CGAL::create_interior_straight_skeleton_2(polygon);\n      break;\n  }\n  \n  \n  if (fn==0 || fn==1)\n    draw_straight_skeleton(*ss,max_edge);\n  else{\n    boost::tie(ret_val,dist)=\n      request_value_from_user<double>(\n        (boost::format(\"Offset value (BBox %1%x%2%)\") % (bbox.xmax()-bbox.xmin()) % (bbox.ymax()-bbox.ymin())).str() \n      );\n    if (ret_val == -1){\n      print_error_message(\"Bad value provided\");\n      return;    \n    }\n\n    if (fn==2 || fn==3)\n      offsets.push_back(dist);\n    else{\n      for (int i=1;i<static_cast<int>(ceil(max_edge/dist/2.))+1;++i)\n        offsets.push_back(i*dist);\n    }\n    \n    for (std::list<double>::iterator it=offsets.begin();it!=offsets.end();++it){\n      PolygonPtrVector offset_polygons = CGAL::create_offset_polygons_2<Polygon_2>(*it,*ss);\n      for( PolygonPtrVector::const_iterator pi = offset_polygons.begin() ; pi != offset_polygons.end() ; ++ pi )\n        draw_in_ipe(**pi);\n    }\n    \n    if (offsets.size()>1)\n      group_selected_objects_();\n  }\n}\n\n}\n\n\n\n\n\n\n\nCGAL_IPELET(CGAL_skeleton::SkeletonIpelet)\n\n", "meta": {"hexsha": "570a0ccb5700f5d8d57b62eb719e6127f38a90a5", "size": 5137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/CGAL_ipelets/skeleton.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/CGAL_ipelets/skeleton.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/demo/CGAL_ipelets/skeleton.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 29.6936416185, "max_line_length": 130, "alphanum_fraction": 0.6803581857, "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5745512394153154}}
{"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": "#define BOOST_TEST_MODULE \"test_area\"\n\n#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST\n#include <boost/test/unit_test.hpp>\n#else\n#define BOOST_TEST_NO_LIB\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <periortree/boundary_condition.hpp>\n#include <periortree/area.hpp>\n#include <test/point_type.hpp>\n#include <test/aabb_type.hpp>\n\nBOOST_AUTO_TEST_CASE(test_aabb_unlimited)\n{\n    {\n        const perior::test::xyz  l(0., 0., 0.);\n        const perior::test::xyz  u(10., 10., 10.);\n        const perior::test::aabb box(l, u);\n        const perior::unlimited_boundary<perior::test::xyz> boundary;\n\n        const double area = perior::area(box, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(area, 1000.0, 1e-12);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_xyz_cubic_periodic)\n{\n    const perior::test::xyz lw(0., 0., 0.);\n    const perior::test::xyz up(10., 10., 10.);\n    const perior::cubic_periodic_boundary<perior::test::xyz> boundary(lw, up);\n\n    {\n        const perior::test::xyz l(3.0, 3.0, 3.0);\n        const perior::test::xyz u(7.0, 7.0, 7.0);\n        const perior::test::aabb box(l, u);\n        const double area = perior::area(box, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(area, 64.0, 1e-12);\n    }\n\n    {\n        const perior::test::xyz l(8.0, 8.0, 8.0);\n        const perior::test::xyz u(2.0, 2.0, 2.0);\n        const perior::test::aabb box(l, u);\n        const double area = perior::area(box, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(area, 64.0, 1e-12);\n    }\n\n    {\n        const perior::test::xyz l(8.0, 4.0, 8.0);\n        const perior::test::xyz u(2.0, 8.0, 2.0);\n        const perior::test::aabb box(l, u);\n        const double area = perior::area(box, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(area, 64.0, 1e-12);\n    }\n}\n", "meta": {"hexsha": "d099c03f0f8a362635adc4b0319d5e53fac92016", "size": 1752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_area.cpp", "max_stars_repo_name": "lasergyro/periortree", "max_stars_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-09-01T14:46:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T11:11:50.000Z", "max_issues_repo_path": "test/test_area.cpp", "max_issues_repo_name": "lasergyro/periortree", "max_issues_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-02-14T03:37:38.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-14T12:16:29.000Z", "max_forks_repo_path": "test/test_area.cpp", "max_forks_repo_name": "lasergyro/periortree", "max_forks_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-02-14T03:52:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T15:49:30.000Z", "avg_line_length": 30.2068965517, "max_line_length": 78, "alphanum_fraction": 0.6284246575, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5745460843660235}}
{"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 <Eigen/Dense>\n\n#include \"gravityField.hpp\"\n\nusing namespace SnowSimulator;\n\nGravityField::GravityField(const Eigen::Vector3f &gravity)\n    : m_gravity(gravity) {}\n\nEigen::Vector3f GravityField::force(const Eigen::Vector3f &pos,\n                                    float mass) const {\n  return m_gravity * mass;\n}\n\nEigen::Matrix3f GravityField::gradForce(const Eigen::Vector3f &pos,\n                                        float mass) const {\n  return Eigen::Matrix3f::Zero();\n}\n", "meta": {"hexsha": "132745d70c45050f52cdf7acbb331363ac8247a3", "size": 487, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gravityField.cpp", "max_stars_repo_name": "kvchen/snowsim", "max_stars_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gravityField.cpp", "max_issues_repo_name": "kvchen/snowsim", "max_issues_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-14T16:38:11.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-14T16:38:11.000Z", "max_forks_repo_path": "src/gravityField.cpp", "max_forks_repo_name": "kvchen/snowsim", "max_forks_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_forks_repo_licenses": ["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.6315789474, "max_line_length": 67, "alphanum_fraction": 0.6303901437, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5745098946607706}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\nusing namespace boost::math;\n\nTEST( BoostMath, Stats )\n{\n\t// get a normal distribution with mean and standard deviation\n\tdouble mean = 0.0;\n\tdouble stdev = 1.0;\n\tnormal dist( mean, stdev );\n\n\t// 95% of distribution is below q:\n\tdouble q = quantile(dist, 0.95);\n\tEXPECT_FLOAT_EQ( 1.6448536, q );\n}\n", "meta": {"hexsha": "a812ae600f1ce7e31363ebdd4fd8ab1109db771e", "size": 362, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/BOOST/MATH/test/tstBOOST_MATH.cc", "max_stars_repo_name": "murraypurves/BootsOnTheGround", "max_stars_repo_head_hexsha": "15acc4ed064e368f6af5114408f1be8a62749f32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-02-01T00:39:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-09T11:53:18.000Z", "max_issues_repo_path": "src/BOOST/MATH/test/tstBOOST_MATH.cc", "max_issues_repo_name": "murraypurves/BootsOnTheGround", "max_issues_repo_head_hexsha": "15acc4ed064e368f6af5114408f1be8a62749f32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2017-01-19T17:56:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-27T21:52:35.000Z", "max_forks_repo_path": "src/BOOST/MATH/test/tstBOOST_MATH.cc", "max_forks_repo_name": "murraypurves/BootsOnTheGround", "max_forks_repo_head_hexsha": "15acc4ed064e368f6af5114408f1be8a62749f32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-03T12:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-03T12:13:36.000Z", "avg_line_length": 22.625, "max_line_length": 62, "alphanum_fraction": 0.7044198895, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5745098899828266}}
{"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 <Eigen/Dense>\n\nusing Eigen::Matrix;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::Vector3d;\nusing Eigen::Dynamic;\n\n#ifndef HERMITE_H\n#define HERMITE_H\n\n#define HERMITE_DATA_ROWS 7\n\nclass Hermite\n{\nprivate:\n  int N; // number of particles\n  double t; // current simulation time\n  double dt; // integration timestep\n  double eps; // softening\n\n  Matrix<double, HERMITE_DATA_ROWS, Dynamic> particles;\n  Matrix<double, 3, Dynamic> x0; // current positions\n  Matrix<double, 3, Dynamic> v0; // current velocities\n  Matrix<double, 3, Dynamic> xp; // predicted next positions\n  Matrix<double, 3, Dynamic> vp; // predicted next velocities\n  Matrix<double, 3, Dynamic> x1; // corrected next positions\n  Matrix<double, 3, Dynamic> v1; // corrected next velocities\n  Matrix<double, 3, Dynamic> a0; // predicted accelerations\n  Matrix<double, 3, Dynamic> a1; // corrected accelerations\n  Matrix<double, 3, Dynamic> jerk0; // predicted jerks\n  Matrix<double, 3, Dynamic> jerk1; // corrected jerks\n\n  VectorXd energy;\n  std::string filename;\n  bool lean; // if set to true solver will not write position files because they can get quite large\n  int blockSize;\n  Matrix<double, 3, Dynamic> totalData; // positions of all particles over all time steps\n\n  void computeEnergy(int step);\n  void step();\n  MatrixXd computeForces(const MatrixXd mass, const MatrixXd pos, const MatrixXd vel);\npublic:\n  Hermite();\n  void enableLean();\n  void disableLean();\n  void setBlockSize(int size);\n  void setSoftening(double newEps);\n  void integrate(double dt, int numSteps);\n  bool readData(const std::string &filename);\n  const Matrix<double, 3, Dynamic> &data();\n};\n\n#endif // HERMITE_H\n", "meta": {"hexsha": "90ac4ed520ab1bd71ca450433493e79f15582825", "size": 1680, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hermite.hpp", "max_stars_repo_name": "azurite/AST-245-N-Body", "max_stars_repo_head_hexsha": "cc3e3acd61f62415c1e5f40c8aba5b93703837fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/hermite.hpp", "max_issues_repo_name": "azurite/AST-245-N-Body", "max_issues_repo_head_hexsha": "cc3e3acd61f62415c1e5f40c8aba5b93703837fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/hermite.hpp", "max_forks_repo_name": "azurite/AST-245-N-Body", "max_forks_repo_head_hexsha": "cc3e3acd61f62415c1e5f40c8aba5b93703837fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5454545455, "max_line_length": 100, "alphanum_fraction": 0.731547619, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5744153294727858}}
{"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 * Copyright (c) 2015 Carnegie Mellon University, Daniel Maturana <dimatura@cmu.edu>\n *\n * For License information please see the LICENSE file in the root directory.\n *\n */\n\n#ifndef FIXEDGRID2_HPP_UYCWT1KR\n#define FIXEDGRID2_HPP_UYCWT1KR\n\n#include <stdint.h>\n#include <math.h>\n\n#include <vector>\n#include <algorithm>\n\n#include <boost/shared_ptr.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <ros/console.h>\n\n#include <geom_cast/geom_cast.hpp>\n#include <pcl_util/point_types.hpp>\n\n#include \"scrollgrid/grid_types.hpp\"\n#include \"scrollgrid/box.hpp\"\n\nnamespace ca\n{\n\ntemplate<class Scalar>\nclass FixedGrid2 {\npublic:\n  typedef Scalar ScalarType;\n  typedef Eigen::Matrix<Scalar, 2, 1> Vec2;\n\n  typedef boost::shared_ptr<FixedGrid2> Ptr;\n  typedef boost::shared_ptr<const FixedGrid2> ConstPtr;\n\npublic:\n  FixedGrid2() :\n      box_(),\n      origin_(0, 0),\n      dimension_(0, 0),\n      num_cells_(0),\n      strides_(0, 0),\n      resolution_(0)\n  { }\n\n  FixedGrid2(const Vec2& center,\n             const Vec2Ix& dimension,\n             Scalar resolution) :\n      box_(),\n      origin_(center-box_.radius()),\n      dimension_(dimension),\n      num_cells_(dimension.prod()),\n      strides_(dimension[1], 1),\n      resolution_(resolution)\n  {\n    Vec2 min_pt = center-(dimension.cast<Scalar>()*resolution)/2;\n    Vec2 max_pt = center+(dimension.cast<Scalar>()*resolution)/2;\n    Vec2 radius = (max_pt-min_pt)/2;\n\n    box_.set_center(center);\n    box_.set_radius(radius);\n    box_.set_max_pt(max_pt);\n    box_.set_min_pt(min_pt);\n    origin_ = center-box_.radius();\n  }\n\n  FixedGrid2(const FixedGrid2& other) :\n      box_(other.box_),\n      origin_(other.origin_),\n      dimension_(other.dimension_),\n      num_cells_(other.num_cells_),\n      strides_(other.strides_),\n      resolution_(other.resolution_)\n  {\n  }\n\n  FixedGrid2& operator=(const FixedGrid2& other) {\n    if (*this==other) { return *this; }\n    box_ = other.box_;\n    origin_ = other.origin_;\n    dimension_ = other.dimension_;\n    num_cells_ = other.num_cells_;\n    strides_ = other.strides_;\n    resolution_ = other.resolution_;\n    return *this;\n  }\n\n  virtual ~FixedGrid2() { }\n\npublic:\n  void reset(const Vec2& center,\n             const Vec2Ix& dimension,\n             Scalar resolution) {\n    box_.set_center(center);\n    box_.set_radius((dimension.cast<Scalar>()*resolution)/2);\n    origin_ = center - box_.radius();\n    dimension_ = dimension;\n    num_cells_ = dimension.prod();\n    strides_ = Vec2Ix(dimension[1], 1);\n    resolution_ = resolution;\n  }\n\n  void copy_from(ca::FixedGrid2<Scalar>& other) {\n    this->reset(other.center(),\n                other.dimension(),\n                other.resolution());\n  }\n\n  /**\n   * Is inside 3D box containing grid?\n   * pt is in same frame as center (probably world_view)\n   */\n  bool is_inside_box(Scalar x, Scalar y) const {\n    return box_.contains(Vec2(x, y));\n  }\n\n  bool is_inside_box(const Vec2& pt) const {\n    return box_.contains(pt);\n  }\n\n  template<class PointT>\n  bool is_inside_box(const PointT& pt) const {\n    return box_.contains(ca::point_cast<Eigen::Vector2d>(pt));\n  }\n\n  /**\n   * is i, j inside the grid limits?\n   */\n  bool is_inside_grid(const Vec2Ix& grid_ix) const {\n    return ((grid_ix.array() >= 0).all() &&\n            (grid_ix.array() < dimension_.array()).all());\n  }\n\n  bool is_inside_grid(grid_ix_t i, grid_ix_t j) const {\n    return this->is_inside_grid(Vec2Ix(i, j));\n  }\n\n  /**\n   * Given position in world coordinates, return grid coordinates.\n   * Note: does not check if point is inside grid.\n   */\n  Vec2Ix world_to_grid(const Vec2& xy) const {\n    Vec2 tmp = ((xy - origin_).array() - 0.5*resolution_)/resolution_;\n    //return tmp.cast<grid_ix_t>();\n    return Vec2Ix(round(tmp.x()), round(tmp.y()));\n  }\n\n  Vec2Ix world_to_grid(Scalar x, Scalar y) const {\n    return this->world_to_grid(Vec2(x, y));\n  }\n\n  Vec2 grid_to_world(const Vec2Ix& grid_ix) const {\n    Vec2 w((grid_ix.cast<Scalar>()*resolution_ + origin_).array() + 0.5*resolution_);\n    return w;\n  }\n\n  Vec2 grid_to_world(grid_ix_t i, grid_ix_t j) const {\n    return this->grid_to_world(Vec2Ix(i, j));\n  }\n\n  mem_ix_t grid_to_mem(grid_ix_t i, grid_ix_t j) const {\n    return this->grid_to_mem(Vec2Ix(i, j));\n  }\n\n  /**\n   * Note that this wraps the z dimension.\n   * TODO c-order/f-order config\n   */\n  mem_ix_t grid_to_mem(const Vec2Ix& grid_ix) const {\n    return strides_.dot(grid_ix);\n  }\n\n  Vec2Ix mem_to_grid(mem_ix_t mem_ix) const {\n    grid_ix_t i = mem_ix/strides_[0];\n    mem_ix -= i*strides_[0];\n    grid_ix_t j = mem_ix;\n    mem_ix -= j;\n    return Vec2Ix(i, j);\n  }\n\n public:\n  grid_ix_t dim_i() const { return dimension_[0]; }\n  grid_ix_t dim_j() const { return dimension_[1]; }\n  const Vec2Ix& dimension() const { return dimension_; }\n  const Vec2& radius() const { return box_.radius(); }\n  const Vec2& origin() const { return origin_; }\n  Vec2 min_pt() const { return box_.min_pt(); }\n  Vec2 max_pt() const { return box_.max_pt(); }\n  const Vec2& center() const { return box_.center(); }\n  Scalar resolution() const { return resolution_; }\n\n  grid_ix_t num_cells() const { return num_cells_; }\n\n private:\n  // 3d box enclosing grid. In whatever coordinates were given (probably\n  // world_view)\n  ca::scrollgrid::Box<Scalar, 2> box_;\n\n  // static origin of the grid coordinate system.\n  Vec2 origin_;\n\n  // number of grid cells along each axis\n  Vec2Ix dimension_;\n\n  // number of cells\n  grid_ix_t num_cells_;\n\n  // grid strides to translate from linear to 3D layout.\n  // C-ordering, ie x slowest, z fastest.\n  Vec2Ix strides_;\n\n  // size of grid cells\n  Scalar resolution_;\n};\n\n}\n\n#endif /* end of include guard: FIXEDGRID2_HPP_UYCWT1KR */\n", "meta": {"hexsha": "90a7dc00b33200626420bdba5cf5bd2efafc0446", "size": 5689, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/scrollgrid/fixedgrid2.hpp", "max_stars_repo_name": "castacks/scrollgrid", "max_stars_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-07-20T23:04:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T08:03:10.000Z", "max_issues_repo_path": "include/scrollgrid/fixedgrid2.hpp", "max_issues_repo_name": "castacks/scrollgrid", "max_issues_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/scrollgrid/fixedgrid2.hpp", "max_forks_repo_name": "castacks/scrollgrid", "max_forks_repo_head_hexsha": "710324173907a182eb688effcf1c9ec998ade1e0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T16:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T01:39:22.000Z", "avg_line_length": 25.2844444444, "max_line_length": 85, "alphanum_fraction": 0.6614519248, "num_tokens": 1537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5743804486327192}}
{"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     *  \u23a1    2     2                          \u23a4\n     *  \u23a2- sy  - sz      sx\u22c5sy        sx\u22c5sz   \u23a5\n     *  \u23a2                                     \u23a5\n     *  \u23a2                 2     2             \u23a5\n     *  \u23a2   sx\u22c5sy     - sx  - sz      sy\u22c5sz   \u23a5\n     *  \u23a2                                     \u23a5\n     *  \u23a2                              2     2\u23a5\n     *  \u23a3   sx\u22c5sz        sy\u22c5sz     - sx  - sy \u23a6\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         *  \u23a1by\u22c5rz - bz\u22c5ry \u23a4   \u23a1 B23 - B32 \u23a4\n         *  \u23a2              \u23a5   |           \u23a5\n         *  \u23a2-bx\u22c5rz + bz\u22c5rx\u23a5 = | B31 - B13 \u23a5\n         *  \u23a2              \u23a5   |           \u23a5\n         *  \u23a3bx\u22c5ry - by\u22c5rx \u23a6   \u23a3 B12 - B21 \u23a6\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": "#include <voltu/types/intrinsics.hpp>\n#include <Eigen/Eigen>\n\nEigen::Matrix3d voltu::Intrinsics::matrix() {\n\tEigen::Matrix3d K;\n\tK <<\t\tfocal_x,\t\t\t0.0,\t-principle_x,\n\t\t\t\t\t0.0,\t\tfocal_y,\t-principle_y,\n\t\t\t\t\t0.0,\t\t\t0.0,\t\t\t 1.0;\n\treturn K;\n}\n\nEigen::Vector2i voltu::Intrinsics::size() {\n\treturn { width, height };\n}\n", "meta": {"hexsha": "a9f94944b2872c6b23f5122959e336c6cae15bb1", "size": 311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SDK/CPP/public/src/types/intrinsics.cpp", "max_stars_repo_name": "knicos/voltu", "max_stars_repo_head_hexsha": "70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-28T15:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-27T12:37:15.000Z", "max_issues_repo_path": "SDK/CPP/public/src/types/intrinsics.cpp", "max_issues_repo_name": "knicos/voltu", "max_issues_repo_head_hexsha": "70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SDK/CPP/public/src/types/intrinsics.cpp", "max_forks_repo_name": "knicos/voltu", "max_forks_repo_head_hexsha": "70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-13T05:28:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T03:37:11.000Z", "avg_line_length": 20.7333333333, "max_line_length": 45, "alphanum_fraction": 0.6366559486, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5743804315681879}}
{"text": "// http://arma.sourceforge.net/docs.html#example_prog\n\n#include <iostream>\n#include <armadillo>\n#include <gnuplot-iostream.h>\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n    arma_rng::set_seed_random();\n\n    mat A = randu<mat>(4, 5);\n    mat B = randu<mat>(4, 5);\n    mat C = A * B.t();\n\n    cout << C << endl;\n\n    Gnuplot gp;\n    gp << \"plot \" << gp.file1d(vec{C.col(1)}) << \"with lines\" << endl;\n\n    getchar();\n\n    return 0;\n}\n", "meta": {"hexsha": "082d1ea2294c42f788136ea3bccfbd2158d3784f", "size": 446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia1/ejercicio1.cpp", "max_stars_repo_name": "junrrein/ic-template", "max_stars_repo_head_hexsha": "84aa7e39b2e51580b841404cb48947924f6ac66c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-11T14:24:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-03T00:56:18.000Z", "max_issues_repo_path": "guia1/ejercicio1.cpp", "max_issues_repo_name": "junrrein/ic-template", "max_issues_repo_head_hexsha": "84aa7e39b2e51580b841404cb48947924f6ac66c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "guia1/ejercicio1.cpp", "max_forks_repo_name": "junrrein/ic-template", "max_forks_repo_head_hexsha": "84aa7e39b2e51580b841404cb48947924f6ac66c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-18T12:32:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T12:32:49.000Z", "avg_line_length": 16.5185185185, "max_line_length": 70, "alphanum_fraction": 0.5896860987, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5743804212954925}}
{"text": "/**\n * @file\n *\n * @copyright\n * SPDX-License-Identifier: Apache-2.0\n *\n * @test @b eigen_gemm_double14\n * @parblock\n * This piece of code aims to stress test the exec (in particular FMA)\n * by repetitively solving general matrix matrix multiplication.  The\n * multiplication function is from the 3rd party library Eigen.  A\n * pair of random matrices are generated as inputs and then multiplied\n * using Eigen's gemm. The multiplication result is compared against a\n * golden result that is computed during init.  This particular\n * version of the test goes for double precision input matrices. This\n * variation adds extra copies and consistency checks.\n *\n * @note Although the test should run fine on a single thread, it is\n * only expected to catch defects if run on at least 2 cores.\n * @endparblock\n */\n\n#include <sandstone.h>\n\n#include <Eigen/Core>\nusing namespace Eigen;\n\n#define M_DIM 256\n\ntypedef Matrix < double, Dynamic, Dynamic > Mat;\n\nnamespace {\nstruct eigen_test_data {\n    Mat lhs;\n    Mat rhs;\n    Mat prod;\n};\n}\n\n#define CAST(_x) static_cast<struct eigen_test_data *>(_x)\n\nstatic int eigen_gemm_double14_init(struct test *test) {\n    test->data = new(eigen_test_data);\n    try {\n        CAST(test->data)->lhs = Mat::Random(M_DIM, M_DIM);\n        CAST(test->data)->rhs = Mat::Random(M_DIM, M_DIM);\n        CAST(test->data)->prod = CAST(test->data)->lhs * CAST(test->data)->rhs;\n    } catch (...) {\n        report_fail_msg(\"Exception on Eigen code, most probably OOM\");\n    }\n    return EXIT_SUCCESS;\n}\n\nstatic int eigen_gemm_double14_run(struct test *test, int cpu) {\n    do {\n        auto testdata = CAST(test->data);\n        Mat _x;\n        _x = testdata->lhs;\n        Mat _y;\n        _y = testdata->rhs;\n        Mat _prod;\n        _prod = _x * _y;\n\n        if (!_x.isApprox(testdata->lhs)) {\n                report_fail_msg(\"_x.isApprox failed\");\n        }\n        memcmp_or_fail(_x.data(), testdata->lhs.data(), M_DIM * M_DIM);\n\n        if (!_y.isApprox(testdata->rhs)) {\n                report_fail_msg(\"_y.isApprox failed\");\n        }\n        memcmp_or_fail(_y.data(), testdata->rhs.data(), M_DIM * M_DIM);\n\n        if (!_prod.isApprox(testdata->prod)) {\n                report_fail_msg(\"_prod.isApprox failed\");\n        }\n        memcmp_or_fail(_prod.data(), testdata->prod.data(), M_DIM * M_DIM);\n    } while (test_time_condition(test));\n    return EXIT_SUCCESS;\n}\n\nstatic int eigen_gemm_double14_finish(struct test *test) {\n    delete(CAST(test->data));\n    return EXIT_SUCCESS;\n}\n\nDECLARE_TEST(eigen_gemm_double14, \"Eigen GEMM payload (double, dynamic, square)\")\n  .groups = DECLARE_TEST_GROUPS(&group_math),\n  .test_init = eigen_gemm_double14_init,\n  .test_run = eigen_gemm_double14_run,\n  .test_cleanup = eigen_gemm_double14_finish,\n  .fracture_loop_count = 4,\n  .quality_level = TEST_QUALITY_PROD,\nEND_DECLARE_TEST\n", "meta": {"hexsha": "91c636a96b38a4a6a0472024c2f61cdb9d4602c1", "size": 2847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/eigen_gemm/double14.cpp", "max_stars_repo_name": "jposwiata/opendcdiag", "max_stars_repo_head_hexsha": "4ce25562ebaca238150ffd7e8ceea9de4daf0992", "max_stars_repo_licenses": ["Apache-2.0"], "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/eigen_gemm/double14.cpp", "max_issues_repo_name": "jposwiata/opendcdiag", "max_issues_repo_head_hexsha": "4ce25562ebaca238150ffd7e8ceea9de4daf0992", "max_issues_repo_licenses": ["Apache-2.0"], "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/eigen_gemm/double14.cpp", "max_forks_repo_name": "jposwiata/opendcdiag", "max_forks_repo_head_hexsha": "4ce25562ebaca238150ffd7e8ceea9de4daf0992", "max_forks_repo_licenses": ["Apache-2.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.9684210526, "max_line_length": 81, "alphanum_fraction": 0.6691253952, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5743804161591444}}
{"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\u00e7ois-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\u2019approche PLS. Revue de statistique appliqu\u00e9e 47, 5\u201340 (1999).\r\n// Vancolen, S. La R\u00e9gression PLS. M\u00e9moire Postgrade en Statistiques, University of Neuch\u00e2tel (Switzerland) 1--28 (2004).\r\n// Wold, S., Sj\u00f6str\u00f6m, M. & Eriksson, L. PLS-regression: a basic tool of chemometrics. Chemometrics and intelligent laboratory systems 58, 109\u2013130 (2001).\r\n// M\u00e9moire m2 de ghislain : https://plmbox.math.cnrs.fr/f/1192b14f90ea44a1b26a/\r\n// Kr\u00e4mer, N. An overview on the shrinkage properties of partial least squares regression. Computational Statistics 22, 249\u2013273 (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": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file    testPCGSolver.cpp\n * @brief   Unit tests for PCGSolver class\n * @author  Yong-Dian Jian\n * @date    Aug 06, 2014\n */\n\n#include <tests/smallExample.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/PCGSolver.h>\n#include <gtsam/linear/SubgraphPreconditioner.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/base/Matrix.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <memory>\n#include <boost/assign/std/list.hpp> // for operator +=\nusing namespace boost::assign;\n\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace gtsam;\n\nconst double tol = 1e-3;\n\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\n/* ************************************************************************* */\n// Test cholesky decomposition\nTEST( PCGSolver, llt ) {\n  Matrix R = (Matrix(3,3) <<\n                1., -1., -1.,\n                0.,  2., -1.,\n                0.,  0.,  1.).finished();\n  Matrix AtA = R.transpose() * R;\n\n  Vector Rvector = (Vector(9) << 1., -1., -1.,\n                                 0.,  2., -1.,\n                                 0.,  0.,  1.).finished();\n//  Vector Rvector = (Vector(6) << 1., -1., -1.,\n//                                      2., -1.,\n//                                           1.).finished();\n\n  Vector b = Vector3(1., 2., 3.);\n\n  Vector x = Vector3(6.5, 2.5, 3.) ;\n\n  /* test cholesky */\n  Matrix Rhat = AtA.llt().matrixL().transpose();\n  EXPECT(assert_equal(R, Rhat, 1e-5));\n\n  /* test backward substitution */\n  Vector xhat = Rhat.triangularView<Eigen::Upper>().solve(b);\n  EXPECT(assert_equal(x, xhat, 1e-5));\n\n  /* test in-place back substitution */\n  xhat = b;\n  Rhat.triangularView<Eigen::Upper>().solveInPlace(xhat);\n  EXPECT(assert_equal(x, xhat, 1e-5));\n\n  /* test triangular matrix map */\n  Eigen::Map<Eigen::MatrixXd> Radapter(Rvector.data(), 3, 3);\n  xhat = Radapter.transpose().triangularView<Eigen::Upper>().solve(b);\n  EXPECT(assert_equal(x, xhat, 1e-5));\n\n}\n\n/* ************************************************************************* */\n// Test GaussianFactorGraphSystem::multiply and getb\nTEST( GaussianFactorGraphSystem, multiply_getb)\n{\n  // Create a Gaussian Factor Graph\n  GaussianFactorGraph simpleGFG;\n  SharedDiagonal unit2 = noiseModel::Diagonal::Sigmas(Vector2(0.5, 0.3));\n  simpleGFG += JacobianFactor(2, (Matrix(2,2)<< 10, 0, 0, 10).finished(), (Vector(2) << -1, -1).finished(), unit2);\n  simpleGFG += JacobianFactor(2, (Matrix(2,2)<< -10, 0, 0, -10).finished(), 0, (Matrix(2,2)<< 10, 0, 0, 10).finished(), (Vector(2) << 2, -1).finished(), unit2);\n  simpleGFG += JacobianFactor(2, (Matrix(2,2)<< -5, 0, 0, -5).finished(), 1, (Matrix(2,2)<< 5, 0, 0, 5).finished(), (Vector(2) << 0, 1).finished(), unit2);\n  simpleGFG += JacobianFactor(0, (Matrix(2,2)<< -5, 0, 0, -5).finished(), 1, (Matrix(2,2)<< 5, 0, 0, 5).finished(), (Vector(2) << -1, 1.5).finished(), unit2);\n  simpleGFG += JacobianFactor(0, (Matrix(2,2)<< 1, 0, 0, 1).finished(), (Vector(2) << 0, 0).finished(), unit2);\n  simpleGFG += JacobianFactor(1, (Matrix(2,2)<< 1, 0, 0, 1).finished(), (Vector(2) << 0, 0).finished(), unit2);\n  simpleGFG += JacobianFactor(2, (Matrix(2,2)<< 1, 0, 0, 1).finished(), (Vector(2) << 0, 0).finished(), unit2);\n\n  // Create a dummy-preconditioner and a GaussianFactorGraphSystem\n  DummyPreconditioner dummyPreconditioner;\n  KeyInfo keyInfo(simpleGFG);\n  std::map<Key,Vector> lambda;\n  dummyPreconditioner.build(simpleGFG, keyInfo, lambda);\n  GaussianFactorGraphSystem gfgs(simpleGFG, dummyPreconditioner, keyInfo, lambda);\n\n  // Prepare container for each variable\n  Vector initial, residual, preconditionedResidual, p, actualAp;\n  initial = (Vector(6) << 0., 0., 0., 0., 0., 0.).finished();\n\n  // Calculate values using GaussianFactorGraphSystem same as inside of PCGSolver\n  gfgs.residual(initial, residual);                         /* r = b-Ax */\n  gfgs.leftPrecondition(residual, preconditionedResidual);  /* pr = L^{-1} (b-Ax) */\n  gfgs.rightPrecondition(preconditionedResidual, p);        /* p = L^{-T} pr */\n  gfgs.multiply(p, actualAp);                                     /* A p */\n\n  // Expected value of Ap for the first iteration of this example problem\n  Vector expectedAp = (Vector(6) << 100400, -249074.074, -2080, 148148.148, -146480, 37962.963).finished();\n  EXPECT(assert_equal(expectedAp, actualAp, 1e-3));\n\n  // Expected value of getb\n  Vector expectedb = (Vector(6) << 100.0, -194.444, -20.0, 138.889, -120.0, -55.556).finished();\n  Vector actualb;\n  gfgs.getb(actualb);\n  EXPECT(assert_equal(expectedb, actualb, 1e-3));\n}\n\n/* ************************************************************************* */\n// Test Dummy Preconditioner\nTEST( PCGSolver, dummy )\n{\n  LevenbergMarquardtParams paramsPCG;\n  paramsPCG.linearSolverType = LevenbergMarquardtParams::Iterative;\n  PCGSolverParameters::shared_ptr pcg = std::make_shared<PCGSolverParameters>();\n  pcg->preconditioner_ = std::make_shared<DummyPreconditionerParameters>();\n  paramsPCG.iterativeParams = pcg;\n\n  NonlinearFactorGraph fg = example::createReallyNonlinearFactorGraph();\n\n  Point2 x0(10,10);\n  Values c0;\n  c0.insert(X(1), x0);\n\n  Values actualPCG = LevenbergMarquardtOptimizer(fg, c0, paramsPCG).optimize();\n\n  DOUBLES_EQUAL(0,fg.error(actualPCG),tol);\n}\n\n/* ************************************************************************* */\n// Test Block-Jacobi Precondioner\nTEST( PCGSolver, blockjacobi )\n{\n  LevenbergMarquardtParams paramsPCG;\n  paramsPCG.linearSolverType = LevenbergMarquardtParams::Iterative;\n  PCGSolverParameters::shared_ptr pcg = std::make_shared<PCGSolverParameters>();\n  pcg->preconditioner_ = std::make_shared<BlockJacobiPreconditionerParameters>();\n  paramsPCG.iterativeParams = pcg;\n\n  NonlinearFactorGraph fg = example::createReallyNonlinearFactorGraph();\n\n  Point2 x0(10,10);\n  Values c0;\n  c0.insert(X(1), x0);\n\n  Values actualPCG = LevenbergMarquardtOptimizer(fg, c0, paramsPCG).optimize();\n\n  DOUBLES_EQUAL(0,fg.error(actualPCG),tol);\n}\n\n/* ************************************************************************* */\n// Test Incremental Subgraph PCG Solver\nTEST( PCGSolver, subgraph )\n{\n  LevenbergMarquardtParams paramsPCG;\n  paramsPCG.linearSolverType = LevenbergMarquardtParams::Iterative;\n  PCGSolverParameters::shared_ptr pcg = std::make_shared<PCGSolverParameters>();\n  pcg->preconditioner_ = std::make_shared<SubgraphPreconditionerParameters>();\n  paramsPCG.iterativeParams = pcg;\n\n  NonlinearFactorGraph fg = example::createReallyNonlinearFactorGraph();\n\n  Point2 x0(10,10);\n  Values c0;\n  c0.insert(X(1), x0);\n\n  Values actualPCG = LevenbergMarquardtOptimizer(fg, c0, paramsPCG).optimize();\n\n  DOUBLES_EQUAL(0,fg.error(actualPCG),tol);\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n\n", "meta": {"hexsha": "f3bf479d4325e187c9595bd7a5b87b43c92e1fa0", "size": 7281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testPCGSolver.cpp", "max_stars_repo_name": "ProfFan/gtsam", "max_stars_repo_head_hexsha": "67ce22c039cc0d04b0085203651dd859bbc44934", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/testPCGSolver.cpp", "max_issues_repo_name": "ProfFan/gtsam", "max_issues_repo_head_hexsha": "67ce22c039cc0d04b0085203651dd859bbc44934", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T21:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T18:47:40.000Z", "max_forks_repo_path": "tests/testPCGSolver.cpp", "max_forks_repo_name": "ProfFan/gtsam", "max_forks_repo_head_hexsha": "67ce22c039cc0d04b0085203651dd859bbc44934", "max_forks_repo_licenses": ["BSD-3-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.1479591837, "max_line_length": 160, "alphanum_fraction": 0.6128279083, "num_tokens": 2145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5743706601144726}}
{"text": "#ifndef FFT_FEATURES_EMISSION_H\n#define FFT_FEATURES_EMISSION_H\n\n#include <armadillo>\n#include <emissions.hpp>\n#include <iostream>\n#include <robotics/utils/random.hpp>\n#include <vector>\n\nnamespace hsmm {\n\n    class MultivariateGaussianEmission : public\n                                         AbstractEmissionObsCondIIDgivenState {\n        public:\n            MultivariateGaussianEmission(\n                    std::vector<robotics::random::NormalDist> states_);\n\n            MultivariateGaussianEmission* clone() const;\n\n            double loglikelihood(int state,\n                    const arma::vec &single_obs) const;\n\n            void fitFromLabels(const arma::field<arma::mat> &observations_seq,\n                    const arma::field<arma::ivec> &labels_seq);\n\n            // TODO: throw a not implemented exception.\n            void reestimate(int min_duration,\n                    const arma::field<arma::cube>& meta,\n                    const arma::field<arma::field<arma::mat>>& mobs) {}\n\n            arma::field<arma::mat> sampleFromState(int state, int size,\n                    std::mt19937 &rng) const;\n\n        private:\n            std::vector<robotics::random::NormalDist> states_;\n    };\n\n};\n\n#endif\n\n", "meta": {"hexsha": "5b8af0b3cd0fa8a17f9663850dbfcc7e29cb0432", "size": 1218, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Multivariate_Gaussian_emission.hpp", "max_stars_repo_name": "DiegoAE/BOSD", "max_stars_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T05:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:14:31.000Z", "max_issues_repo_path": "include/Multivariate_Gaussian_emission.hpp", "max_issues_repo_name": "DiegoAE/BOSD", "max_issues_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T15:29:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T10:14:54.000Z", "max_forks_repo_path": "include/Multivariate_Gaussian_emission.hpp", "max_forks_repo_name": "DiegoAE/BOSD", "max_forks_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T07:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T07:44:09.000Z", "avg_line_length": 29.0, "max_line_length": 79, "alphanum_fraction": 0.5977011494, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5743706550225073}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n#include <boost/numeric/itl/pc/ilut.hpp>\n\ntemplate <typename Matrix>\ndouble test_factorization(const Matrix& A, unsigned p, double tau)\n{\n    itl::pc::ilut<Matrix>  P(A, p, tau);\n    //itl::pc::ilu_0<Matrix>  P(A);\n    Matrix L(P.get_L()), U(P.get_U()), I(num_rows(A), num_cols(A));\n    I= 1.0;\n    L+= I;\n    invert_diagonal(U);\n    //std::cout << \"L is\\n\" << L << '\\n';\n    //std::cout << \"U is\\n\" << U << '\\n';\n    Matrix LU(L*U);\n    //std::cout << \"LU is\\n\" << LU << '\\n';\n    LU-= A;\n    //std::cout << \"LU-A is\\n\" << LU << '\\n';\n    double diff_norm= frobenius_norm(LU);\n    std::cout << \"|A-LU|_1 with p = \" << p << \", tau = \" << tau << \" is \" << diff_norm << '\\n';\n    return diff_norm;\n}\n\nint main()\n{\n#ifndef __PGI\n    // For a more realistic example set sz to 1000 or larger\n    const unsigned size = 4, N = size * size;\n\n    mtl::compressed2D<double>          A(N, N);\n    laplacian_setup(A, size, size);\n       \n    std::cout << \"A is\\n\" << A << '\\n';\n    MTL_THROW_IF(test_factorization(A, 3, 0.001) > 0.24, mtl::logic_error(\"ILUT(3, 0.001) too bad\"));\n\n#if 0\n    for(unsigned i= 2; i <= size; i++)\n\tfor (double f= 0.5; f > 0.000001; f/= 2)\n\t    test_factorization(A, i, f);\n\n    itl::pc::ic_0<matrix_type, float>  P(A);\n    mtl::dense_vector<double>          x(N), y, yc(N);\n    iota(x);\n    yc= 1.03194,1.60198,1.45357,2.5258,3.55386,3.16,2.91787,4.09338,3.81335;\n    \n    std::cout << x << '\\n';\n    y= solve(P, x);\n    std::cout << y << '\\n';\n\n    MTL_THROW_IF(two_norm(mtl::dense_vector<double>(y - yc)) > 0.001, \n\t\t mtl::logic_error(\"IC(0) doesn't yield expected result\"));\t\n#endif\n\n#endif\n    return 0;\n}\n", "meta": {"hexsha": "239f3961fea0eda1d433bc6f394b043d8847eee8", "size": 2165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/ilut_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/ilut_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/ilut_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.4929577465, "max_line_length": 101, "alphanum_fraction": 0.5852193995, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5743706550225073}}
{"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": "//  io_ex1.cpp  ----------------------------------------------------------//\r\n\r\n//  Copyright 2010 Howard Hinnant\r\n//  Copyright 2010 Vicente J. Botet Escriba\r\n\r\n//  Distributed under the Boost Software License, Version 1.0.\r\n//  See http://www.boost.org/LICENSE_1_0.txt\r\n\r\n/*\r\nThis code was adapted by Vicente J. Botet Escriba from Hinnant's html documentation.\r\nMany thanks to Howard for making his code available under the Boost license.\r\n\r\n*/\r\n\r\n#include <boost/chrono/chrono_io.hpp>\r\n#include <ostream>\r\n#include <iostream>\r\n\r\n// format duration as [-]d/hh::mm::ss.cc\r\ntemplate <class CharT, class Traits, class Rep, class Period>\r\nstd::basic_ostream<CharT, Traits>&\r\ndisplay(std::basic_ostream<CharT, Traits>& os,\r\n        boost::chrono::duration<Rep, Period> d)\r\n{\r\n    using std::cout;\r\n    using namespace boost;\r\n    using namespace boost::chrono;\r\n\r\n    typedef duration<long long, ratio<86400> > days;\r\n    typedef duration<long long, centi> centiseconds;\r\n\r\n    // if negative, print negative sign and negate\r\n    if (d < duration<Rep, Period>(0))\r\n    {\r\n        d = -d;\r\n        os << '-';\r\n    }\r\n    // round d to nearest centiseconds, to even on tie\r\n    centiseconds cs = duration_cast<centiseconds>(d);\r\n    if (d - cs > milliseconds(5)\r\n        || (d - cs == milliseconds(5) && cs.count() & 1))\r\n        ++cs;\r\n    // separate seconds from centiseconds\r\n    seconds s = duration_cast<seconds>(cs);\r\n    cs -= s;\r\n    // separate minutes from seconds\r\n    minutes m = duration_cast<minutes>(s);\r\n    s -= m;\r\n    // separate hours from minutes\r\n    hours h = duration_cast<hours>(m);\r\n    m -= h;\r\n    // separate days from hours\r\n    days dy = duration_cast<days>(h);\r\n    h -= dy;\r\n    // print d/hh:mm:ss.cc\r\n    os << dy.count() << '/';\r\n    if (h < hours(10))\r\n        os << '0';\r\n    os << h.count() << ':';\r\n    if (m < minutes(10))\r\n        os << '0';\r\n    os << m.count() << ':';\r\n    if (s < seconds(10))\r\n        os << '0';\r\n    os << s.count() << '.';\r\n    if (cs < centiseconds(10))\r\n        os << '0';\r\n    os << cs.count();\r\n    return os;\r\n}\r\n\r\nint main()\r\n{\r\n    using std::cout;\r\n    using namespace boost;\r\n    using namespace boost::chrono;\r\n\r\n#ifdef BOOST_CHRONO_HAS_CLOCK_STEADY\r\n    display(cout, steady_clock::now().time_since_epoch()\r\n                  + duration<long, mega>(1)) << '\\n';\r\n#endif\r\n    display(cout, -milliseconds(6)) << '\\n';\r\n    display(cout, duration<long, mega>(1)) << '\\n';\r\n    display(cout, -duration<long, mega>(1)) << '\\n';\r\n}\r\n\r\n//~ 12/06:03:22.95\r\n//~ -0/00:00:00.01\r\n//~ 11/13:46:40.00\r\n//~ -11/13:46:40.00\r\n", "meta": {"hexsha": "3e217f6668a57588e02416cd90877dc22c81ea27", "size": 2582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/chrono/example/io_ex5.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/chrono/example/io_ex5.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/chrono/example/io_ex5.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": 28.3736263736, "max_line_length": 85, "alphanum_fraction": 0.5623547637, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5743706385932101}}
{"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_EXPONENT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_EXPONENT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-ieee\n    This function object returns the exponent of the floating input.\n\n\n\n    @par Header <boost/simd/function/exponent.hpp>\n\n    @par Note:\n\n     The exponent \\f$e\\f$ and mantissa \\f$m\\f$ of a floating point entry \\f$x\\f$ are related by\n    \\f$x =  m\\times 2^e\\f$, with  \\f$ |m| \\in [1, 2[\\f$ (except for \\f$x = 0\\f$,\n    where \\f$m=0\\f$ and \\f$e=0\\f$ ).\n\n    For integral type inputs exponent is always 0 and mantissa reduces to identity.\n\n    @see mantissa,  frexp, ldexp\n\n\n    @par Example:\n\n      @snippet exponent.cpp exponent\n\n    @par Possible output:\n\n      @snippet exponent.txt exponent\n\n  **/\n  as_integer_t<Value> exponent(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/exponent.hpp>\n#include <boost/simd/function/simd/exponent.hpp>\n\n#endif\n", "meta": {"hexsha": "8a134967b91d8fba02d03ec2a46d4114c4d39490", "size": 1358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/exponent.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/exponent.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/exponent.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 25.1481481481, "max_line_length": 100, "alphanum_fraction": 0.5898379971, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5743706374398087}}
{"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": "#include <bitset>\n#include <boost/dynamic_bitset.hpp>\n#include <chrono>\n#include <vector>\n\n#include <stdio.h>\n\nbool verbose = true;\nconst int bits = 30;\nconst int64_t mask = (1<<30) - 1;\n\nvoid sieve(int64_t n) \n{ \n  auto start = std::chrono::system_clock::now();\n  std::vector<boost::dynamic_bitset<>> notprime(1+(n>>bits), boost::dynamic_bitset<>((1LL<<bits)+1));\n  printf(\"constructed %lld %lld\\n\", 1+(n>>bits), (1LL<<bits)+1);\n  for (int64_t p = 2; p*p <= n; p++) {\n    if (notprime[p>>bits][p&mask] == 0) {\n      for (int64_t q = p*2; q <= n; q += p)\n\tnotprime[q>>bits][q&mask] = 1;\n    }\n  }\n  auto end = std::chrono::system_clock::now();\n  std::chrono::duration<double> elapsed_seconds = end-start;\n  printf(\"Computation took %f sec\\n\", elapsed_seconds.count());\n  \n  int64_t k = 0;\n  printf(\"Primes <= %lld\\n\", n);\n  for (int64_t p = 2; p <= n; p++) \n    if (notprime[p>>bits][p&mask] == 0) {\n      ++k;\n      if (verbose) {\n\tprintf(\"%lld \", p);\n      }\n    }\n  if (verbose)\n    printf(\"\\n\");\n  printf(\"%lld primes\\n\", k);\n} \n  \nint main(int argc, char* argv[]) { \n  if (argc < 2) {\n    printf(\"era [-quiet] <n>: computes primes <= n\\n\");\n    return -1;\n  }\n  if (!strcmp(argv[1], \"-quiet\")) {\n    verbose = false;\n  }\n  int64_t n = std::stoll(argv[argc-1]);\n  sieve(n); \n  return 0; \n} \n", "meta": {"hexsha": "041a95d254389607fb6d0c258ba5dee64f178ded", "size": 1295, "ext": "cc", "lang": "C++", "max_stars_repo_path": "primes/era64.cc", "max_stars_repo_name": "maxpoletto/primes", "max_stars_repo_head_hexsha": "956d0694bd4d0f7e592ac2e121d07d31f06b8930", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "primes/era64.cc", "max_issues_repo_name": "maxpoletto/primes", "max_issues_repo_head_hexsha": "956d0694bd4d0f7e592ac2e121d07d31f06b8930", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "primes/era64.cc", "max_forks_repo_name": "maxpoletto/primes", "max_forks_repo_head_hexsha": "956d0694bd4d0f7e592ac2e121d07d31f06b8930", "max_forks_repo_licenses": ["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.4339622642, "max_line_length": 101, "alphanum_fraction": 0.566023166, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.5743687773489283}}
{"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 2014 Jonathan Graehl - http://graehl.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#ifndef GRAEHL__SHARED__TIME_SERIES_HPP\n#define GRAEHL__SHARED__TIME_SERIES_HPP\n\n//FIXME: curvature does nothing if <=0 for score_t, otherwise results in +INF (bug) if positive\n\n#ifdef SAMPLE\n//# define DEBUG_TIME_SERIES\n#endif\n\n#ifdef DEBUG_TIME_SERIES\n#define GRAEHL__DEBUG_PRINT\n# include <graehl/shared/debugprint.hpp>\n#endif\n#include <boost/config.hpp>\n#include <cstddef>\n#include <cmath>\n#include <cassert>\n#include <functional>\n#include <ostream>\n\nnamespace graehl {\n\ninline double pow(double x, double y)\n{\n  return std::pow(x, y);  // this isn't found with using namespace std, so ...\n}\n\n/*\n  template <class V>\n  struct time_series\n  {\n  typedef V value_type;\n  typedef std::size_t time_type;\n  virtual V series_value_at(time_type t)=0;\n  };\n*/\n\n/// Computes must support: Computes=pow(Value,double),+, -,*,/.\n/// adaptable unary function: time_type(=double) -> Returns\ntemplate <class Computes = double, class Returns = Computes>\nstruct clamped_time_series : public std::unary_function<double, Returns>\n{\n  typedef Computes value_type;\n  typedef Returns result_type;\n  typedef double time_type;\n  typedef time_type first_argument_type;\n  value_type x0;\n  value_type k;\n  value_type x_origin;\n  time_type t_max;\n  //    BOOST_STATIC_CONSTANT(double,linear= -1.7976931348623157e308); // bad answers (all 0) for anything near -INF.  fast math lib failure?\n  BOOST_STATIC_CONSTANT(int, linear=-100000000);\n  BOOST_STATIC_CONSTANT(int, exponential = 0);\n  BOOST_STATIC_CONSTANT(int, constant = 0);\n\n  clamped_time_series()\n  {\n    set(0, 0);\n  }\n\n  clamped_time_series(value_type start, value_type end,// start and end should both be positive.  at t<=0, return start, at t>=duration-1, return end.  in between, depends on alpha\n                      time_type duration = constant, // varies over t in [0,duration);\n                      double curvature = exponential)\n      // curvature=0->regular exponential decay (x[n+1]=k*x[n]).  curvature->(-infty) -> (nearly) linear.  curvature>=1 -> impossible. curvature->1 -> quickly drops to end and stays nearly constant\n  {\n    assert(curvature<=1);\n    /* //FIXME: disabled because decoder_filters fixing end to 2 (start at 0)\n       if (false && duration && start!=end) {\n       assert(start>0);\n       assert(end>0);\n       }\n    */\n    set(start, end, duration, curvature);\n  }\n\n  // duration <= 0 -> constant series (=start)\n  void set(value_type start, value_type end, time_type duration = constant, double curvature = exponential)\n  {\n#ifdef DEBUG_TIME_SERIES\n    DBP4(start, end, duration, curvature);\n#endif\n    if (duration <= 0 || start == end) { //set constant fn\n      k = 1;\n      t_max = 1;\n      x0 = start;\n      x_origin = 0;\n      return;\n    }\n    t_max = duration;\n    value_type xN;\n    if (curvature) {\n      x_origin = (end*static_cast<value_type>(curvature));\n      x0 = start-x_origin;\n      xN = end-x_origin;\n    } else {\n      x_origin = 0;\n      x0 = start;\n      xN = end;\n    }\n    k = xN/x0;\n#ifdef DEBUG_TIME_SERIES\n    DBP3(x0, xN, k);\n#endif\n  }\n  bool is_constant() const\n  {\n    return k==1;\n  }\n  value_type start() const\n  {\n    return x0+x_origin;\n  }\n  value_type end() const\n  {\n    return x0*k+x_origin; // because k=xN/x0, and xN=end-x_origin\n  }\n  value_type curvature() const\n  {\n    return x_origin/end();\n  }\n\n  value_type value(time_type t) const\n  {\n    if (t<=0)\n      return start();\n    else if (t>=t_max)\n      return end();\n    else\n      return x0*pow(k, t/t_max)+x_origin;\n  }\n\n  result_type operator()(time_type t) const\n  {\n    return static_cast<result_type>(value(t));\n  }\n\n  void print(std::ostream &o) const\n  {\n    if (is_constant())\n      o<<\"[constant]\"<<start();\n    else\n      o<<\"[0..\"<<t_max<<\"]=\"<<start()<<\"..\"<<end()<<\";c=\"<<curvature();\n  }\n\n  typedef clamped_time_series<Computes, Returns> self_type;\n  inline friend std::ostream & operator <<(std::ostream &o, self_type const& s)\n  {\n    s.print(o);\n    return o;\n  }\n};\n\n} //graehl\n\n#ifdef SAMPLE\n# define TIME_SERIES_SAMPLE\n#endif\n\n#ifdef TIME_SERIES_SAMPLE\n# include <iostream>\n\nusing namespace graehl;\n\ntypedef clamped_time_series<double> dser;\n\ndouble s = 8, e = .2, t_max = 3;\ndouble linear = dser::linear;\ndouble curves[] = {\n  0, .9, linear\n};\n\ndser series[] = {\n  dser(s, e, t_max, 0)\n};\n\nint main(int argc, char *argv[])\n{\n  using namespace std;\n  for (unsigned i = 0; i<sizeof(curves)/sizeof(curves[0]); ++i) {\n    dser d(s, e, t_max, curves[i]);\n    cout << d << \"\\n\";\n    for (double t = 0; t<=t_max+1; t += .5)\n      cout << \"t=\"<<t<<\"\\t\"<<d(t)<<endl;\n  }\n\n  cout <<\"\\n\\n\";\n\n  {\n\n    clamped_time_series<double>\n        s1(s, e, t_max, 0),\n        s2(s, e, t_max, .9),\n        s3(s, e, t_max, linear);\n\n\n    for (double t = 0; t<=t_max+1; t += .5) {\n      cout << \"t=\"<<t<<\"\\t\"<<s1(t);\n      cout <<\"\\t\"<<s2(t)<<\"\\t\"<<s3(t)<<endl;\n    }\n  }\n\n  cout<<\"\\n\\n\";\n\n  {\n\n    clamped_time_series<double, unsigned>\n        s1(s, e, t_max, 0),\n        s2(s, e, t_max, .9),\n        s3(s, e, t_max, linear);\n    for (double t = 0; t<=t_max+1; t += .5) {\n      cout << \"t=\"<<t<<\"\\t\"<<s1(t);\n      cout <<\"\\t\"<<s2(t)<<\"\\t\"<<s3(t)<<endl;\n    }\n\n  }\n\n  return 0;\n}\n\n#endif\n\n\n#endif\n", "meta": {"hexsha": "e25c886dd6aeae3483a73221988f87e0732a8467", "size": 5773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "graehl/shared/time_series.hpp", "max_stars_repo_name": "graehl/carmel", "max_stars_repo_head_hexsha": "4a5d0990a17d0d853621348272b2f05a0dab3450", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T16:52:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T07:36:10.000Z", "max_issues_repo_path": "graehl/shared/time_series.hpp", "max_issues_repo_name": "graehl/carmel", "max_issues_repo_head_hexsha": "4a5d0990a17d0d853621348272b2f05a0dab3450", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-04-18T17:20:37.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-23T07:36:38.000Z", "max_forks_repo_path": "graehl/shared/time_series.hpp", "max_forks_repo_name": "graehl/carmel", "max_forks_repo_head_hexsha": "4a5d0990a17d0d853621348272b2f05a0dab3450", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-06-11T14:48:13.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-12T16:06:19.000Z", "avg_line_length": 24.358649789, "max_line_length": 197, "alphanum_fraction": 0.6305213927, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581049086031, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5742608365155778}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <fstream>\n#include <array>\n#include <random>\n#include <mutex>\n#include <iostream>\n#include <map>\n#include <tuple>\n#include <gtest/gtest.h>\n#include <mpi.h>\n\n#include \"tasktorrent/tasktorrent.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace ttor;\n\ntypedef array<int, 2> int2;\ntypedef array<int, 3> int3;\n\nint VERB = 0;\nbool LOG = false;\nint n_threads_ = 4;\nint n_ = 100;\nint N_ = 20;\nint p_ = 1;\nint q_ = 1;\n\nvoid cholesky(int n_threads, int n, int N, int p, int q)\n{\n    // MPI info\n    const int rank = comm_rank();\n    const int n_ranks = comm_size();\n    if(VERB) printf(\"[%d] Hello from %s\\n\", comm_rank(), processor_name().c_str());\n\n    assert(p * q == n_ranks);\n    assert(p >= 1);\n    assert(q >= 1);\n\n    // Form the matrix : let every node have a copy of A for now\n    auto gen = [&](int i, int j) { \n        if(i == j) {\n            return static_cast<double>(N*n+2);\n        } else {\n            int k = (i+j)%3;\n            if(k == 0) {\n                return 0.0;\n            } else if (k == 1) {\n                return 0.5;\n            } else {\n                return 1.0;\n            }\n        }\n    };\n    MatrixXd A = MatrixXd::NullaryExpr(N * n, N * n, gen);\n    MatrixXd Aref = A;\n    A = A.triangularView<Lower>();\n\n    // Mapper\n    auto block2rank = [&](int2 ij){\n        int i = ij[0];\n        int j = ij[1];\n        int ii = i % p;\n        int jj = j % q;\n        int r = ii + jj * p;\n        assert(r <= n_ranks);\n        return r;\n    };\n\n    // Gives the priority\n    auto block2prio = [&](int2 ij) {\n        int i = ij[0]+1;\n        int j = ij[1]+1;\n        assert(i >= j);\n        return static_cast<double>(N*N - ((i*(i-1))/2 + j));\n    };\n\n    // Block the matrix for every node\n    // Store it in a map\n    // Later on we can probably optimize this, to avoid storing the whole thing\n    // Note: concurrent access to the map should _NOT_ modify it, otherwise we need a lock\n    map<int2, MatrixXd> Mat;\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j <= i; j++) {\n            if(block2rank({i,j}) == rank) {\n                Mat[{i,j}] = A.block(i * n, j * n, n, n);\n            } else {\n                Mat[{i,j}] = MatrixXd::Zero(n, n);\n            }\n        }\n    }\n\n    // Factorize\n    {\n        // Initialize the communicator structure\n        Communicator comm(MPI_COMM_WORLD, VERB);\n\n        // Threadpool\n        Threadpool tp(n_threads, &comm, VERB, \"[\" + to_string(rank) + \"]_\");\n        Taskflow<int> potf_tf(&tp, VERB);\n        Taskflow<int2> trsm_tf(&tp, VERB);\n        Taskflow<int3> gemm_tf(&tp, VERB);\n\n        // Log\n        DepsLogger dlog(1000000);\n        Logger log(1000000);\n        if(LOG) {\n            tp.set_logger(&log);\n            comm.set_logger(&log);\n        }\n        \n        // Active messages\n        // Sends a pivot and trigger multiple trsms in one columns\n        auto am_trsm = comm.make_active_msg( \n            [&](view<double> &Lkk, int& j, view<int>& is) {\n                Mat.at({j,j}) = Map<MatrixXd>(Lkk.data(), n, n);\n                for(auto& i: is) {\n                    trsm_tf.fulfill_promise({i,j});\n                }\n            });\n\n        // Sends a panel bloc and trigger multiple gemms\n        auto am_gemm = comm.make_large_active_msg(\n            [&](int&, int& j, view<int2>& ijs) {\n                for(auto& ij: ijs) {\n                    int gi = ij[0];\n                    int gj = ij[1];\n                    int gk = j;\n                    gemm_tf.fulfill_promise({gi,gj,gk});\n                }\n            },\n            [&](int& i, int& j, view<int2>&) {\n                return Mat.at({i,j}).data();\n            },\n            [&](int&, int&, view<int2>&) {\n                return;\n            });\n\n\n        // potf \n        potf_tf.set_mapping([&](int j) {\n                return (j % n_threads);\n            })\n            .set_indegree([](int) {\n                return 1;\n            })\n            .set_task([&](int j) {\n                LLT<Ref<MatrixXd>> llt(Mat.at({j,j}));\n                assert(llt.info() == Eigen::Success);\n            })\n            .set_fulfill([&](int j) {\n                // Dependencies\n                map<int,vector<int>> to_fulfill; // rank -> trsm[i,j] on that rank at (i,j)\n                for(int i = j+1; i<N; i++) {\n                    int r = block2rank({i,j});\n                    if(to_fulfill.count(r) == 0) {\n                        to_fulfill[r] = {i};\n                    } else {\n                        to_fulfill[r].push_back(i);\n                    }\n                }\n                // Send data & trigger tasks\n                for(auto& p: to_fulfill) {\n                    int r = p.first;\n                    // Task is local. Just fulfill.\n                    if(r == rank) {\n                        for(auto& i: p.second) {\n                            trsm_tf.fulfill_promise({i,j});\n                        }\n                    // Task is remote. Send data and fulfill.\n                    } else {\n                        auto Ljjv = view<double>(Mat.at({j,j}).data(), n*n);\n                        auto isv = view<int>(p.second.data(), p.second.size());\n                        am_trsm->send(r, Ljjv, j, isv);\n                    }\n                }\n            })\n            .set_name([](int j) {\n                return \"potf_\" + to_string(j);\n            })\n            .set_priority([&](int j) {\n                return block2prio({j,j});\n            });\n\n        // trsm\n        trsm_tf.set_mapping([&](int2 ij) {\n                return ((ij[0] + ij[1] * N) % n_threads);\n            })\n            .set_indegree([](int2 ij) {\n                return (ij[1] == 0 ? 0 : 1) + 1;\n            })\n            .set_task([&](int2 ij) {\n                int i = ij[0];\n                int j = ij[1];\n                auto L = Mat.at({j,j}).triangularView<Lower>().transpose();\n                Mat.at({i,j}) = L.solve<OnTheRight>(Mat.at({i,j}));\n            })\n            .set_fulfill([&](int2 ij) {\n                int i = ij[0];\n                int j = ij[1];\n                // Dependencies\n                map<int,vector<int2>> to_fulfill; // rank -> gemm[i,j,k] on that rank at (i,j)            \n                for (int k = j+1; k<=i; k++) // on the right, row i, cols k=j+1, ..., i\n                {\n                    int r = block2rank({i,k});\n                    if(to_fulfill.count(r) == 0) {\n                        to_fulfill[r] = { {i,k} };\n                    } else {\n                        to_fulfill[r].push_back({i,k});\n                    }\n                }\n                for (int k = i+1; k<N; k++) // below, col i, row k=i+1, ..., N\n                {\n                    int r = block2rank({k,i});\n                    if(to_fulfill.count(r) == 0) {\n                        to_fulfill[r] = { {k,i} };\n                    } else {\n                        to_fulfill[r].push_back({k,i});\n                    }\n                }\n                // Send data & trigger tasks\n                for(auto& p: to_fulfill) {\n                    int r = p.first;\n                    // Task is local. Just fulfill.\n                    if(r == rank) {\n                        for(auto& ij: p.second) {\n                            int gi = ij[0];\n                            int gj = ij[1];\n                            int gk = j;\n                            gemm_tf.fulfill_promise({gi,gj,gk});\n                        }\n                    // Task is remote. Send data and fulfill.\n                    } else {\n                        auto Lijv = view<double>(Mat.at({i,j}).data(), n*n);\n                        auto ijsv = view<int2>(p.second.data(), p.second.size());\n                        am_gemm->send_large(r, Lijv, i, j, ijsv);\n                    }\n                } \n            })\n            .set_name([](int2 ij) {\n                return \"trsm_\" + to_string(ij[0]) + \"_\" + to_string(ij[1]);\n            })\n            .set_priority([&](int2 ij) {\n                return block2prio(ij);\n            });\n\n        // gemm\n        gemm_tf.set_mapping([&](int3 ijk) {\n                return ((ijk[0] + ijk[1] * N + ijk[2] * N * N) % n_threads);\n            })\n            .set_indegree([](int3 ijk) {\n                int i = ijk[0];\n                int j = ijk[1];\n                int k = ijk[2];\n                return (k == 0 ? 0 : 1) + (i == j ? 1 : 2);\n            })\n            .set_task([&](int3 ijk) {\n                int i = ijk[0];\n                int j = ijk[1];\n                int k = ijk[2];\n                Mat.at({i,j}).noalias() -= Mat.at({i,k}) * Mat.at({j,k}).transpose();\n                ASSERT_TRUE(k < N - 1);\n            })\n            .set_fulfill([&](int3 ijk) {\n                int i = ijk[0];\n                int j = ijk[1];\n                int k = ijk[2];\n                if (k + 1 == i && k + 1 == j)\n                {\n                    potf_tf.fulfill_promise(k+1); // same node, no comms\n                }\n                else if (k + 1 == j)\n                {\n                    trsm_tf.fulfill_promise({i, k + 1}); // same node, no comms\n                }\n                else\n                {\n                    gemm_tf.fulfill_promise({i, j, k + 1}); // same node, no comms\n                }\n            })\n            .set_name([](int3 ijk) {\n                return \"gemm_\" + to_string(ijk[0]) + \"_\" + to_string(ijk[1]) + \"_\" + to_string(ijk[2]);\n            })\n            .set_priority([&](int3 ijk) {\n                return block2prio({ijk[0], ijk[1]});\n            });\n\n            if(rank == 0) printf(\"Starting Cholesky\\n\");\n            MPI_Barrier(MPI_COMM_WORLD);\n            timer t0 = wctime();\n            if (rank == 0){\n                potf_tf.fulfill_promise(0);\n            }\n            tp.join();\n            timer t1 = wctime();\n            MPI_Barrier(MPI_COMM_WORLD);\n            if(rank == 0)\n            {\n                cout << \"Time : \" << elapsed(t0, t1) << endl;\n            }\n\n            if(LOG) {\n                std::ofstream logfile;\n                string filename = \"cholesky_\"+ to_string(n_ranks)+\".log.\"+to_string(rank);\n                logfile.open(filename);\n                logfile << log;\n                logfile.close();\n            }\n    }\n\n    // Gather everything on rank 0 and test for accuracy\n    {\n        Communicator comm(MPI_COMM_WORLD, VERB);\n        Threadpool tp(n_threads, &comm, VERB);\n        Taskflow<int2> gather_tf(&tp, VERB);\n        auto am_gather = comm.make_active_msg(\n        [&](view<double> &Lij, int& i, int& j) {\n        \tA.block(i * n, j * n, n, n) = Map<MatrixXd>(Lij.data(), n, n);\n        });\n        // potf \n        gather_tf.set_mapping([&](int2 ij) {\n                return ( (ij[0] + ij[1]) % n_threads );\n            })\n            .set_indegree([](int2) {\n                return 1;\n            })\n            .set_task([&](int2 ij) {\n                int i = ij[0];\n                int j = ij[1];\n                if(rank != 0) {\n                    auto Lijv = view<double>(Mat.at({i,j}).data(), n*n);\n                    am_gather->send(0, Lijv, i, j);\n                } else {\n                    A.block(i * n, j * n, n, n) = Mat.at({i,j});\n                }\n            })\n            .set_name([](int2 ij) {\n                return \"gather_\" + to_string(ij[0]) + \"_\" + to_string(ij[1]);\n            });\n\n        for(int i = 0; i < N; i++) {\n            for(int j = 0; j <= i; j++) {\n                if(block2rank({i,j}) == rank) {\n                    gather_tf.fulfill_promise({i,j});\n                }\n            }\n        }\n        tp.join();\n        MPI_Barrier(MPI_COMM_WORLD);\n\n        if(rank == 0) {\n            // Test 1         \n            {\n                auto L = A.triangularView<Lower>();\n                VectorXd x = VectorXd::Random(n * N);\n                VectorXd b = Aref*x;\n                VectorXd bref = b;\n                L.solveInPlace(b);\n                L.transpose().solveInPlace(b);\n                double error = (b - x).norm() / x.norm();\n                cout << \"Error solve: \" << error << endl;\n                EXPECT_LE(error, 1e-8);\n            }\n            // Test 2\n            {\n                // MatrixXd L = A.triangularView<Lower>();\n                // MatrixXd A = L * L.transpose();\n                // double error = (A - Aref).norm() / Aref.norm();\n                // cout << \"Error LLT : \" << error << endl;\n                // EXPECT_LE(error, 1e-8);\n            }\n        }\n    }\n}\n\nTEST(cholesky, one)\n{\n    int n_threads = n_threads_;\n  \tint n = n_;\n  \tint N = N_;\n    int p = p_;\n    int q = q_;\n    cholesky(n_threads, n, N, p, q);\n}\n\nclass ManyTest : public ::testing::Test, public ::testing::WithParamInterface<tuple<int, int, int>> {};\n\nTEST_P(ManyTest, MixedTwoSteps) {\n    int n_threads, n, N;\n    std::tie(n_threads, n, N) = GetParam();\n    cholesky(n_threads, n, N, p_, q_);\n}\n\nINSTANTIATE_TEST_SUITE_P(\n    cholesky, ManyTest,\n    ::testing::Combine(\n        ::testing::Values(1, 4),\n        ::testing::Values(1, 5, 10),\n        ::testing::Values(1, 16, 64)\n    ),\n    [](const ::testing::TestParamInfo<ManyTest::ParamType>& info) -> string {\n        return \"nt\" + to_string(get<0>(info.param)) + \"n\" + to_string(get<1>(info.param)) + \"N\" + to_string(get<2>(info.param));\n    }\n);\n\n\nint main(int argc, char **argv)\n{\n    int req = MPI_THREAD_FUNNELED;\n    int prov = -1;\n\n    MPI_Init_thread(NULL, NULL, req, &prov);\n\n    assert(prov == req);\n\n    ::testing::InitGoogleTest(&argc, argv);\n\n    if (argc >= 2)\n    {\n        n_threads_ = atoi(argv[1]);\n    }\n\n    if (argc >= 3)\n    {\n        n_ = atoi(argv[2]);\n    }\n\n    if (argc >= 4)\n    {\n        N_ = atoi(argv[3]);\n    }\n\n    if (argc >= 5)\n    {\n        p_ = atoi(argv[4]);\n    }\n\n    if (argc >= 6)\n    {\n        q_ = atoi(argv[5]);\n    }\n\n    if (argc >= 7)\n    {\n        VERB = atoi(argv[6]);\n    }\n\n    const int return_flag = RUN_ALL_TESTS();\n\n    MPI_Finalize();\n\n    return return_flag;\n}\n", "meta": {"hexsha": "e11c948a326ba64fe84bbf3b20e46de851286738", "size": 14001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/mpi/cholesky.cpp", "max_stars_repo_name": "qyz96/tasktorrent", "max_stars_repo_head_hexsha": "4418d83da7de657363ac99ee263602794a0b97a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2019-09-29T19:33:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:48:40.000Z", "max_issues_repo_path": "tests/mpi/cholesky.cpp", "max_issues_repo_name": "qyz96/tasktorrent", "max_issues_repo_head_hexsha": "4418d83da7de657363ac99ee263602794a0b97a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-11T18:14:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T22:32:56.000Z", "max_forks_repo_path": "tests/mpi/cholesky.cpp", "max_forks_repo_name": "qyz96/tasktorrent", "max_forks_repo_head_hexsha": "4418d83da7de657363ac99ee263602794a0b97a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-10-22T06:40:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T08:17:39.000Z", "avg_line_length": 30.7714285714, "max_line_length": 128, "alphanum_fraction": 0.4061852725, "num_tokens": 3672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5742608260240679}}
{"text": "#ifndef JSPACE_PSEUDO_INVERSE_HPP\n#define JSPACE_PSEUDO_INVERSE_HPP\n\n#include <Eigen/Dense>\n\nnamespace myUtils {\n  void pseudoInverse(Eigen::MatrixXd const & matrix,\n                     double sigmaThreshold,\n                     Eigen::MatrixXd & invMatrix,\n                     Eigen::VectorXd * opt_sigmaOut = 0);\n\n  Eigen::MatrixXd getNullSpace(const Eigen::MatrixXd & J,\n                               const double threshold = 0.00001);\n\n  void weightedInverse(const Eigen::MatrixXd & J,\n                       const Eigen::MatrixXd & Winv,\n                       Eigen::MatrixXd & Jinv);\n}\n\n#endif\n", "meta": {"hexsha": "cdfdedc43e4940aab27e0721c22f15059ce3eddc", "size": 605, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Utils/Math/pseudo_inverse.hpp", "max_stars_repo_name": "shbang91/PnC", "max_stars_repo_head_hexsha": "880cbbcf96a48a93a0ab646634781e4f112a71f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T22:36:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T22:36:54.000Z", "max_issues_repo_path": "Utils/Math/pseudo_inverse.hpp", "max_issues_repo_name": "shbang91/PnC", "max_issues_repo_head_hexsha": "880cbbcf96a48a93a0ab646634781e4f112a71f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Utils/Math/pseudo_inverse.hpp", "max_forks_repo_name": "shbang91/PnC", "max_forks_repo_head_hexsha": "880cbbcf96a48a93a0ab646634781e4f112a71f6", "max_forks_repo_licenses": ["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.8095238095, "max_line_length": 65, "alphanum_fraction": 0.5884297521, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5742608234940639}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright Christopher Kormanyos 2015.\n//  Copyright Paul Bristow 2015.\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//! \\file\n//!\\brief Tests for the fixed_point functions next, prior, distance, advance.\n\n#define BOOST_TEST_MODULE test_negatable_func_next_prior\n#define BOOST_LIB_DIAGNOSTIC\n\n#include <boost/fixed_point/fixed_point.hpp>\n#include <boost/test/included/unit_test.hpp>\n\n// Basic tests using any type and any value (except max, lowest or -max).\ntemplate<typename T>\nvoid tests(T value)\n{\n  using namespace boost::fixed_point;\n\n  const T x(value);\n  const T xn = fixed_next(x);\n  const T xp = fixed_prior(x);\n\n  BOOST_CHECK_EQUAL(fixed_prior(xn),  x); // next then prior should be x.\n  BOOST_CHECK_EQUAL(fixed_next(xp), x);   // prior then next should be x.\n\n  const T xx = fixed_next(xp);\n\n  const bool b = (xx == x);\n\n  BOOST_CHECK_EQUAL(b, true);\n\n  const T np = fixed_next(xp);\n\n  BOOST_CHECK_EQUAL(np.bit_pattern(), x.bit_pattern()); // prior then next should be x.\n  BOOST_CHECK_EQUAL(np, x);\n  BOOST_CHECK_EQUAL(fixed_distance(xp, xn), 2);\n  BOOST_CHECK_EQUAL(fixed_advance(xp, 2), xn);\n} // void tests.\n\nBOOST_AUTO_TEST_CASE(test_negatable_func_next_prior)\n{\n  typedef boost::fixed_point::negatable< 0,   -7> fixed_point_type_0m7;     //  8-bit fixed_point type using all 7 bits for resolution.\n  typedef boost::fixed_point::negatable< 2,   -5> fixed_point_type_2m5;     //  8-bit fixed_point type 2 range 5 resolution.\n  typedef boost::fixed_point::negatable< 7,   -8> fixed_point_type_7m8;     //  16-bit fixed_point type with even split.\n  typedef boost::fixed_point::negatable< 0,  -63> fixed_point_type_0m63;   //  64-bit fixed_point type using all 63 bits for resolution.\n  typedef boost::fixed_point::negatable<15,  -48> fixed_point_type_15m48;  //  64-bit fixed_point type.\n  typedef boost::fixed_point::negatable<15, -240> fixed_point_type_15m240; // 256-bit using multiprecision\n  typedef boost::fixed_point::negatable<55, -200> big_fixed_point_type;    // 256-bit using multiprecision\n\n  using boost::fixed_point::fixed_next;\n  using boost::fixed_point::fixed_prior;\n  using boost::fixed_point::fixed_advance;\n  using boost::fixed_point::fixed_distance;\n\n  // Simple test using unity and a single fixed_point type.\n  const fixed_point_type_7m8 x(1);\n  BOOST_CHECK_EQUAL(x.bit_pattern(), \"0000000100000000\");\n\n  const fixed_point_type_7m8 xn = fixed_next(x);\n  BOOST_CHECK_EQUAL(xn.bit_pattern(), \"0000000100000001\");\n\n  const fixed_point_type_7m8 xp = fixed_prior(x);\n  BOOST_CHECK_EQUAL(xp.bit_pattern(), \"0000000011111111\");\n  BOOST_CHECK_EQUAL(fixed_prior(xn), x);\n  BOOST_CHECK_EQUAL(fixed_next(xp), x);\n  BOOST_CHECK_EQUAL(fixed_distance(xp, xn), 2);\n  BOOST_CHECK_EQUAL(fixed_advance(xp, 2), xn);\n\n  // Check that nextafter gives same results.\n  // (Useful in case fixed_next, etc. are not implemented using nextafter).\n  BOOST_CHECK_EQUAL(fixed_prior(x), nextafter(x, x - 1));\n  BOOST_CHECK_EQUAL(fixed_next(x),  nextafter(x, x + 1));\n\n  // Use 8-bit all solution bit type fixed_point_type_0m7\n  // tests(fixed_point_type_0m7(-1)); // Cannot represent unity with this type.\n  tests(fixed_point_type_0m7( 0));\n  tests((std::numeric_limits<fixed_point_type_0m7>::min)()); // small value.\n\n  // Repeat above tests using multiple types and multiple values.\n  tests(fixed_point_type_7m8( 1));\n  tests(fixed_point_type_7m8(-1));\n  tests(fixed_point_type_7m8( 0));\n  tests((std::numeric_limits<fixed_point_type_7m8>::min)()); // small value.\n\n  tests(fixed_prior((std::numeric_limits<fixed_point_type_7m8>::max)()));   // penultimate value.\n  tests(fixed_next ( std::numeric_limits<fixed_point_type_7m8>::lowest())); // penultimate value.\n\n  //tests((std::numeric_limits<fixed_point_type_7m8>::max)());    // Expected to fail!\n  //tests((std::numeric_limits<fixed_point_type_7m8>::lowest)()); // Expected to fail!\n\n  // Use a 64-bit types:  fixed_point_type_15m48\n  tests(fixed_point_type_15m48( 1));\n  tests(fixed_point_type_15m48(-1));\n  tests(fixed_point_type_15m48( 0));\n  tests((std::numeric_limits<fixed_point_type_7m8>::min)()); // small value.\n  // fixed_point_type_0m63 all resolution bits.\n  tests((std::numeric_limits<fixed_point_type_0m63>::min)()); // small value.\n\n\n  tests(fixed_prior((std::numeric_limits<fixed_point_type_15m48>::max)()));   // penultimate value.\n  tests(fixed_next ( std::numeric_limits<fixed_point_type_15m48>::lowest())); // penultimate value.\n\n    // Test using a big 256-bit type using multiprecision.\n  tests(fixed_point_type_15m240( 1));\n  tests(fixed_point_type_15m240(-1));\n  tests(fixed_point_type_15m240( 0));\n  tests((std::numeric_limits<fixed_point_type_15m240>::min)()); // small value.\n\n  tests(fixed_prior((std::numeric_limits<fixed_point_type_15m240>::max)()));   // penultimate value.\n  tests(fixed_next ( std::numeric_limits<fixed_point_type_15m240>::lowest())); // penultimate value.\n\n  // Test using a big 256-bit type using multiprecision.\n  tests(big_fixed_point_type( 1));\n  tests(big_fixed_point_type(-1));\n  tests(big_fixed_point_type( 0));\n  tests((std::numeric_limits<big_fixed_point_type>::min)()); // small value.\n\n  tests(fixed_prior((std::numeric_limits<big_fixed_point_type>::max)()));   // penultimate value.\n  tests(fixed_next ( std::numeric_limits<big_fixed_point_type>::lowest())); // penultimate value.\n\n  tests(fixed_point_type_2m5(0));\n\n} // BOOST_AUTO_TEST_CASE(test_negatable_func_next_prior)\n", "meta": {"hexsha": "d65d5cb47e5059c536702c101c0ad38576dcbb09", "size": 5597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_func_next_prior.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_func_next_prior.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_func_next_prior.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": 43.7265625, "max_line_length": 136, "alphanum_fraction": 0.7300339468, "num_tokens": 1567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.5742608212618959}}
{"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 <Eigen/Core>\n#include <iostream>\nusing namespace Eigen;\nusing namespace std;\n\ntemplate<typename Derived>\nEigen::VectorBlock<Derived>\nsegmentFromRange(MatrixBase<Derived>& v, int start, int end)\n{\n  return Eigen::VectorBlock<Derived>(v.derived(), start, end-start);\n}\n\ntemplate<typename Derived>\nconst Eigen::VectorBlock<const Derived>\nsegmentFromRange(const MatrixBase<Derived>& v, int start, int end)\n{\n  return Eigen::VectorBlock<const Derived>(v.derived(), start, end-start);\n}\n\nint main(int, char**)\n{\n  Matrix<int,1,6> v; v << 1,2,3,4,5,6;\n  cout << segmentFromRange(2*v, 2, 4) << endl; // calls the const version\n  segmentFromRange(v, 1, 3) *= 5;              // calls the non-const version\n  cout << \"Now the vector v is:\" << endl << v << endl;\n  return 0;\n}\n", "meta": {"hexsha": "dc213df20f8c5aaaa81d06a16b43e51168499d34", "size": 775, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/class_VectorBlock.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/class_VectorBlock.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/class_VectorBlock.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": 27.6785714286, "max_line_length": 77, "alphanum_fraction": 0.6890322581, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5742523132806476}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2011 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <iostream>\n\nvoid t1()\n{\n   //[mpz_eg\n   //=#include <boost/multiprecision/gmp.hpp>\n\n   using namespace boost::multiprecision;\n\n   mpz_int v = 1;\n\n   // Do some arithmetic:\n   for(unsigned i = 1; i <= 1000; ++i)\n      v *= i;\n\n   std::cout << v << std::endl; // prints 1000!\n\n   // Access the underlying representation:\n   mpz_t z;\n   mpz_init(z);\n   mpz_set(z, v.backend().data());\n   //]\n   mpz_clear(z);\n}\n\nvoid t2()\n{\n   //[mpf_eg\n   //=#include <boost/multiprecision/gmp.hpp>\n\n   using namespace boost::multiprecision;\n\n   // Operations at variable precision and limited standard library support:\n   mpf_float a = 2;\n   mpf_float::default_precision(1000);\n   std::cout << mpf_float::default_precision() << std::endl;\n   std::cout << sqrt(a) << std::endl; // print root-2\n\n   // Operations at fixed precision and full standard library support:\n   mpf_float_100 b = 2;\n   std::cout << std::numeric_limits<mpf_float_100>::digits << std::endl;\n   // We can use any C++ std lib function:\n   std::cout << 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\n   // Access the underlying representation:\n   mpf_t f;\n   mpf_init(f);\n   mpf_set(f, a.backend().data());\n   //]\n   mpf_clear(f);\n}\n\nvoid t3()\n{\n   //[mpq_eg\n   //=#include <boost/multiprecision/gmp.hpp>\n\n   using namespace boost::multiprecision;\n\n   mpq_rational v = 1;\n\n   // Do some arithmetic:\n   for(unsigned i = 1; i <= 1000; ++i)\n      v *= i;\n   v /= 10;\n\n   std::cout << v << std::endl; // prints 1000! / 10\n   std::cout << numerator(v) << std::endl;\n   std::cout << denominator(v) << std::endl;\n\n   mpq_rational w(2, 3);  // component wise constructor\n   std::cout << w << std::endl; // prints 2/3\n\n   // Access the underlying data:\n   mpq_t q;\n   mpq_init(q);\n   mpq_set(q, v.backend().data());\n   //]\n   mpq_clear(q);\n}\n\nint main()\n{\n   t1();\n   t2();\n   t3();\n   return 0;\n}\n\n", "meta": {"hexsha": "3ee75bf3e5cf3af414b7d30eaddd8e92616a0012", "size": 2406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/example/gmp_snips.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-01-25T05:31:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T01:50:31.000Z", "max_issues_repo_path": "libs/multiprecision/example/gmp_snips.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "libs/multiprecision/example/gmp_snips.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-17T15:37:11.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-10T14:06:31.000Z", "avg_line_length": 23.8217821782, "max_line_length": 76, "alphanum_fraction": 0.6051537822, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.5742522967001681}}
{"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  // returns the number of global shape functions (managed by the local-> global index ing mapping encoded\n  // in the dofhander) associated with mesh entities of co-domensioon 0, 1, and 2 respectively\n  // the co-dimension also serves as index for the returned array\n  \n  // loop over all mesh entitesm get the inices of the global shape functions\n  // associated with them via DofHandker::InteriorGlobalDofIndices()\n  // and count them \n  // this number is alo available through DofHandler::NumInteriorDofs()\n\n  // iterate over entities in the mesh and get interior number of dofs for each\n  std::shared_ptr<lf::mesh::Mesh> mesh = dofhandler.Mesh(); \n  for (int co_dim =0 ; co_dim <=2; co_dim++){\n    entityDofs[co_dim] =0; \n    for (auto el : mesh->Entities(co_dim)){\n      entity_Dofs[co_dim] += dofhandler.interiorGlobalDofIndices(el); \n    }\n  }\n  \n\n  //====================\n  return entityDofs;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nstd::size_t countBoundaryDofs(const lf::assemble::DofHandler &dofhandler) {\n  std::shared_ptr<const lf::mesh::Mesh> mesh = dofhandler.Mesh();\n  // given an entity, bd\\_flags(entity) == true, if the entity is on the\n  // boundary\n  lf::mesh::utils::AllCodimMeshDataSet<bool> bd_flags(\n      lf::mesh::utils::flagEntitiesOnBoundary(mesh));\n  std::size_t no_dofs_on_bd = 0;\n  //====================\n  // Your code goes here\n  // tells the number of global shape functions associated with mesh entities located on the \n  // boundary \n  // use the function flagEntitiesonBoundary to obtain the array of flags whether an entity is located on the boundary \n  // edges and nodes can be on the boundary; \n  for (auto edge: mesh->Entity(1)){\n    if (bd_flags(edge) == TRUE){\n      no_dofs_on_bd += dofhandler.InteriorGlobalDofIndices(edge); \n    }\n  }\n\n  for (auto node: mesh->Entity(2)){\n    if (bd_flags(node) == TRUE){\n      no_dofs_on_bd += dofhandler.InteriorGlobalDofIndices(node); \n    }\n  }\n\n  //====================\n  return no_dofs_on_bd;\n}\n/* SAM_LISTING_END_2 */\n\n// clang-format off\n/* SAM_LISTING_BEGIN_3 */\ndouble integrateLinearFEFunction(\n    const lf::assemble::DofHandler& dofhandler,\n    const Eigen::VectorXd& mu) {\n  double I = 0;\n  //====================\n  // Your code goes here\n  // computes the ...\n  // whose nodal bases coefficients are passed in mu \n  // the dofhandler arguments provides the local-> global mapping \n  // check whether the lf::assemble::DofHandler object dofhandler really fits the \n  // lagrangian finite element space \n  // run over all cells\n  // get the indices of the tent functions covering them via \n  //DofHandler::GlobalDofIndices, \n  // sum the corresponding entries of the coefficient vectors\n  // in linear Lagarangian FE, the integral over the basis functions \n  // over a triangle K is 1/3*vol(k)\n\n  std::shared_ptr<lf::mesh::Mesh> mesh = dofhandler.Mesh(); \n\n\n  for(auto cell: mesh->Entities(0)){\n    // lf::assemble::DofHandler::GlobalDofIndices \n    // access to indices of global dof's belonging to an entity \n    auto glob_dof_indices = dofhandler.GlobalDofIndices(*cell); \n\n    double I_dof =0; \n    for(auto dof_indice = glob_dof_indices.start(); dof_indice =glob_dof_indices.end(); dof_indice++){\n      I_dof += mu(dof_indice); \n    }\n    lf::geometry::Geometry *cell->Geometry(); \n    I_dof *= 1/3*lf::geometry::Volume(cell); \n    I+=I_dof; \n  }\n  \n  //====================\n  return I;\n}\n/* SAM_LISTING_END_3 */\n// clang-format on\n\n/* SAM_LISTING_BEGIN_4 */\ndouble integrateQuadraticFEFunction(const lf::assemble::DofHandler &dofhandler,\n                                    const Eigen::VectorXd &mu) {\n  double I = 0;\n  //====================\n  // Your code goes here\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  return zeta;\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace LFPPDofHandling\n", "meta": {"hexsha": "dfe917a968d01d0bc8177e663d1eb6acbba8a5d5", "size": 5897, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/LFPPDofHandling/mysolution/lfppdofhandling.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/LFPPDofHandling/mysolution/lfppdofhandling.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/LFPPDofHandling/mysolution/lfppdofhandling.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": 33.8908045977, "max_line_length": 119, "alphanum_fraction": 0.6581312532, "num_tokens": 1583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.5742265940572551}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>\n// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"main.h\"\n#include <Eigen/Eigenvalues>\n\ntemplate<typename Scalar,int Size> void hessenberg(int size = Size)\n{\n  typedef Matrix<Scalar,Size,Size> MatrixType;\n\n  // Test basic functionality: A = U H U* and H is Hessenberg\n  for(int counter = 0; counter < g_repeat; ++counter) {\n    MatrixType m = MatrixType::Random(size,size);\n    HessenbergDecomposition<MatrixType> hess(m);\n    MatrixType Q = hess.matrixQ();\n    MatrixType H = hess.matrixH();\n    VERIFY_IS_APPROX(m, Q * H * Q.adjoint());\n    for(int row = 2; row < size; ++row) {\n      for(int col = 0; col < row-1; ++col) {\n\tVERIFY(H(row,col) == (typename MatrixType::Scalar)0);\n      }\n    }\n  }\n\n  // Test whether compute() and constructor returns same result\n  MatrixType A = MatrixType::Random(size, size);\n  HessenbergDecomposition<MatrixType> cs1;\n  cs1.compute(A);\n  HessenbergDecomposition<MatrixType> cs2(A);\n  VERIFY_IS_EQUAL(cs1.matrixH().eval(), cs2.matrixH().eval());\n  MatrixType cs1Q = cs1.matrixQ();\n  MatrixType cs2Q = cs2.matrixQ();  \n  VERIFY_IS_EQUAL(cs1Q, cs2Q);\n\n  // Test assertions for when used uninitialized\n  HessenbergDecomposition<MatrixType> hessUninitialized;\n  VERIFY_RAISES_ASSERT( hessUninitialized.matrixH() );\n  VERIFY_RAISES_ASSERT( hessUninitialized.matrixQ() );\n  VERIFY_RAISES_ASSERT( hessUninitialized.householderCoefficients() );\n  VERIFY_RAISES_ASSERT( hessUninitialized.packedMatrix() );\n\n  // TODO: Add tests for packedMatrix() and householderCoefficients()\n}\n\nEIGEN_DECLARE_TEST(hessenberg)\n{\n  CALL_SUBTEST_1(( hessenberg<std::complex<double>,1>() ));\n  CALL_SUBTEST_2(( hessenberg<std::complex<double>,2>() ));\n  CALL_SUBTEST_3(( hessenberg<std::complex<float>,4>() ));\n  CALL_SUBTEST_4(( hessenberg<float,Dynamic>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE)) ));\n  CALL_SUBTEST_5(( hessenberg<std::complex<double>,Dynamic>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE)) ));\n\n  // Test problem size constructors\n  CALL_SUBTEST_6(HessenbergDecomposition<MatrixXf>(10));\n}\n", "meta": {"hexsha": "0e1b0098dacd12ea9cef0648ca8212a8906450f5", "size": 2404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/eigen/test/hessenberg.cpp", "max_stars_repo_name": "Krissmedt/imprunko", "max_stars_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2111.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:48:14.000Z", "max_issues_repo_path": "tools/eigen/test/hessenberg.cpp", "max_issues_repo_name": "Krissmedt/imprunko", "max_issues_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 131.0, "max_issues_repo_issues_event_min_datetime": "2019-02-18T10:56:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:07:00.000Z", "max_forks_repo_path": "tools/eigen/test/hessenberg.cpp", "max_forks_repo_name": "Krissmedt/imprunko", "max_forks_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:22:01.000Z", "avg_line_length": 38.1587301587, "max_line_length": 109, "alphanum_fraction": 0.7196339434, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.5742265817690937}}
{"text": "//######################################################################\n//#   SDF_Fusion Module \n//#   \n//#   Copyright (C) 2020 Siemens AG\n//#   SPDX-License-Identifier: MIT\n//#   Author 2020: This module has been developed by \n//#                or under supervision of Slobodan Ilic\n//#######################################################################\n\n#ifndef UTILS_HPP\n#define UTILS_HPP\n\n#include <iostream>\n#include <fstream>\n#include <Eigen/Core>\n\n\ntemplate<typename T>\ninline Eigen::Matrix<T, 3, 3> read_intrinsics_from_file(const std::string &in_file)\n{\n\tstd::vector<T> intrinsics_vector = read_matrix_one_line<T>(in_file);\n\treturn matrix_from_vector_rowwise<T, 3, 3>(intrinsics_vector);\n}\n\ntemplate<typename T>\ninline Eigen::Matrix<T, 2, 1> project_point(const Eigen::Matrix<T, 3, 1> &point, const Eigen::Matrix<T, 3, 3> &intrinsics)\n{\n\tEigen::Matrix<T, 3, 1> projected = point / point(2);\n\tprojected = intrinsics * projected;\n\treturn { projected(0), projected(1) };\n}\n\n\ntemplate<typename T, int R, int C>\ninline Eigen::Matrix<T, R, C> matrix_from_vector_rowwise(std::vector<T> v)\n{\n\tif (v.size() != R * C)\n\t{\n\t\tstd::cerr << \"Invalid input vector of size \" << v.size() << \" for \" << R << \"x\" << C << \" matrix\" << std::endl;\n\t\tthrow std::invalid_argument(\"Invalid vector size\");\n\t}\n\n\treturn Eigen::Map<Eigen::Matrix<T, R, C, Eigen::RowMajor>>(&v[0]);\n}\n\n\ntemplate<typename T>\ninline std::vector<T> read_matrix_one_line(const std::string &in_file)\n{\n\tstd::string line;\n\tstd::vector<T> elements;\n\n\tstd::ifstream f(in_file);\n\n\twhile (std::getline(f, line))\n\t{\n\t\tstringstream ss(line);\n\t\tT current_value;\n\n\t\twhile (ss >> current_value)\n\t\t{\n\t\t\telements.push_back(current_value);\n\t\t}\n\n\t}\n\n\treturn elements;\n}\n\n#endif\n", "meta": {"hexsha": "5329c44a89b62a1201483327c721a856fa546eff", "size": 1726, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdf_fusion/src/aruco_sdffusion/include/utils.hpp", "max_stars_repo_name": "YyYyYong0331/homebrewdb", "max_stars_repo_head_hexsha": "02fb883b1630f21db6348e2605def5bd8cc6e2c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T16:29:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T05:47:29.000Z", "max_issues_repo_path": "sdf_fusion/src/aruco_sdffusion/include/utils.hpp", "max_issues_repo_name": "YyYyYong0331/homebrewdb", "max_issues_repo_head_hexsha": "02fb883b1630f21db6348e2605def5bd8cc6e2c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-04-16T15:03:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T07:28:52.000Z", "max_forks_repo_path": "sdf_fusion/src/aruco_sdffusion/include/utils.hpp", "max_forks_repo_name": "YyYyYong0331/homebrewdb", "max_forks_repo_head_hexsha": "02fb883b1630f21db6348e2605def5bd8cc6e2c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-27T09:02:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T10:42:33.000Z", "avg_line_length": 24.3098591549, "max_line_length": 122, "alphanum_fraction": 0.6164542294, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.574226577476728}}
{"text": "\r\n\r\n\r\n#include <iostream>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n\r\ntypedef float                                RealNumber;\r\ntypedef boost::numeric::ublas::matrix<float> Matrix44;\r\n\r\n\r\nMatrix44 mtxMulTranslate(Matrix44 matrix, RealNumber x, RealNumber y, RealNumber z) throw()\r\n{\r\n\tmatrix(0, 3) += matrix(0, 0)*x + matrix(0, 1)*y + matrix(0, 2)*z;\r\n\tmatrix(1, 3) += matrix(1, 0)*x + matrix(1, 1)*y + matrix(1, 2)*z;\r\n\tmatrix(2, 3) += matrix(2, 0)*x + matrix(2, 1)*y + matrix(2, 2)*z;\r\n\tmatrix(3, 3) += matrix(3, 0)*x + matrix(3, 1)*y + matrix(3, 2)*z;\r\n\treturn matrix;\r\n}\r\n\r\n\r\nint main()\r\n{\r\n\tMatrix44 matrix = boost::numeric::ublas::identity_matrix<float> (4);\r\n\r\n\tmtxMulTranslate(matrix, 2.0f, 2.0f, 2.0f);\r\n\r\n\r\n\r\n\r\n\treturn 0;\r\n}\r\n\r\n", "meta": {"hexsha": "746b8ca6b4b0c55a084d578f8105e682b5bcbee5", "size": 740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/MatrixTest/matrixTest.cpp", "max_stars_repo_name": "taku-xhift/labo", "max_stars_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/MatrixTest/matrixTest.cpp", "max_issues_repo_name": "taku-xhift/labo", "max_issues_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/MatrixTest/matrixTest.cpp", "max_forks_repo_name": "taku-xhift/labo", "max_forks_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4242424242, "max_line_length": 92, "alphanum_fraction": 0.5891891892, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5741707619802002}}
{"text": "#include <Eigen/Core>\n#include <chrono>\n#include <fstream>\n#include <iostream>\n\nint main() {\n  using namespace std;\n  using namespace std::chrono;\n  using namespace Eigen;\n  int height = 1080;\n  int width = 1920;\n  int sv_count = 30;\n\n  system_clock::time_point start, stop;\n  double elapsed_time;\n\n  int u_buffer_size = 3 * height * sv_count * sizeof(float);\n  float *u_buffer = (float *)malloc(u_buffer_size);\n  int v_buffer_size = 3 * sv_count * width * sizeof(float);\n  float *v_buffer = (float *)malloc(v_buffer_size);\n  int sv_buffer_size = 3 * sv_count * sizeof(float);\n  float *sv_buffer = (float *)malloc(sv_buffer_size);\n  int svd_buffer_size = 3 * width * height * sizeof(float);\n  float *svd_buffer = (float *)malloc(svd_buffer_size);\n\n  start = high_resolution_clock::now();\n  std::ifstream svd_file(\"SVD_metadata_10/1.bin\", std::ios::binary);\n  svd_file.read((char *)sv_buffer, sv_buffer_size);\n  svd_file.read((char *)u_buffer, u_buffer_size);\n  svd_file.read((char *)v_buffer, v_buffer_size);\n  svd_file.close();\n  stop = high_resolution_clock::now();\n  elapsed_time = duration<double, std::milli>(stop - start).count();\n  cout << \"Time to read file: \" << elapsed_time << endl;\n\n  Map<Matrix<float, Dynamic, Dynamic, RowMajor>> eigen_u_buffer(\n      u_buffer, 3 * height, sv_count);\n  Map<Matrix<float, Dynamic, Dynamic, RowMajor>> eigen_v_buffer(\n      v_buffer, 3 * sv_count, width);\n  Map<Matrix<float, Dynamic, 1>> eigen_svd_buffer(svd_buffer, 3 * sv_count);\n  start = high_resolution_clock::now();\n  for (int color = 0; color < 3; color++) {\n    Map<Matrix<float, Dynamic, Dynamic, RowMajor>, 0, InnerStride<3>> eigen_svd(\n        svd_buffer + color, height, width);\n    eigen_svd =\n        eigen_u_buffer.block(color * height, 0, height, sv_count) *\n        eigen_svd_buffer.segment(color * sv_count, sv_count).asDiagonal() *\n        eigen_v_buffer.block(color * sv_count, 0, sv_count, width);\n  }\n  stop = high_resolution_clock::now();\n  elapsed_time = duration<double, std::milli>(stop - start).count();\n  cout << \"Time to recover SAT: \" << elapsed_time << endl;\n\n  free(u_buffer);\n  free(v_buffer);\n  free(sv_buffer);\n  free(svd_buffer);\n}", "meta": {"hexsha": "291887b6d36d882c1c618f6edc28e72855cc00fa", "size": 2164, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/eigen_sat_generate.cc", "max_stars_repo_name": "AugmentariumLab/foveated-360-video", "max_stars_repo_head_hexsha": "bd5cb585712cc67b20da1264430c33c8bc68cf49", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T15:46:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-26T03:20:15.000Z", "max_issues_repo_path": "src/eigen_sat_generate.cc", "max_issues_repo_name": "AugmentariumLab/foveated-360-video", "max_issues_repo_head_hexsha": "bd5cb585712cc67b20da1264430c33c8bc68cf49", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigen_sat_generate.cc", "max_forks_repo_name": "AugmentariumLab/foveated-360-video", "max_forks_repo_head_hexsha": "bd5cb585712cc67b20da1264430c33c8bc68cf49", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:46:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T09:53:38.000Z", "avg_line_length": 37.3103448276, "max_line_length": 80, "alphanum_fraction": 0.6913123845, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5741707540555894}}
{"text": "#pragma once\n\n#include <ros/ros.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <algorithm>\n\nnamespace dr {\n\n\t/// A pose convention.\n\tstruct PoseHeader {\n\t\tstd::string parent_frame;\n\t\tstd::string child_frame;\n\t};\n\n\t/// A pose with source and target frame information.\n\tstruct Pose {\n\t\tPoseHeader header;\n\t\tEigen::Isometry3d isometry;\n\t};\n\n\t/// Elementary axes.\n\tnamespace axes {\n\t\t/// Get a vector representing the X axis.\n\t\tinline Eigen::Vector3d x() { return Eigen::Vector3d::UnitX(); }\n\n\t\t/// Get a vector representing the Y axis.\n\t\tinline Eigen::Vector3d y() { return Eigen::Vector3d::UnitY(); }\n\n\t\t/// Get a vector representing the Z axis.\n\t\tinline Eigen::Vector3d z() { return Eigen::Vector3d::UnitZ(); }\n\t}\n\n\t/// Create an aligned box with a center and dimensions.\n\tinline Eigen::AlignedBox3d makeCenteredBox(Eigen::Vector3d const & center, Eigen::Vector3d const & size) {\n\t\treturn Eigen::AlignedBox3d(center - size / 2, center + size / 2);\n\t}\n\n\t/// Create a hyperplane with a position and normal.\n\tinline Eigen::Hyperplane<double, 3> makePlane(Eigen::Vector3d const & normal, Eigen::Vector3d const & point) {\n\t\treturn Eigen::Hyperplane<double, 3>(normal, point);\n\t}\n\n\t/// Create a hyperplane from a pose.\n\tinline Eigen::Hyperplane<double, 3> makeXyPlane(Eigen::Isometry3d const & pose) {\n\t\treturn Eigen::Hyperplane<double, 3>(pose.rotation() * axes::z(), pose.translation());\n\t}\n\n\t/// Create a translation from a vector.\n\tinline Eigen::Translation3d translate(Eigen::Vector3d translation) {\n\t\treturn Eigen::Translation3d{translation};\n\t}\n\n\t/// Create a translation from X, Y and Z components.\n\tinline Eigen::Translation3d translate(double x, double y, double z) {\n\t\treturn translate(Eigen::Vector3d{x, y, z});\n\t}\n\n\t/// Create a rotation with a given angle and axis.\n\tinline Eigen::AngleAxisd rotate(double angle, Eigen::Vector3d const & axis) {\n\t\treturn Eigen::AngleAxisd{angle, axis};\n\t}\n\n\t/// Create a rotation with a given angle and axis and center of rotation.\n\tinline Eigen::Isometry3d rotate(double angle, Eigen::Vector3d const & axis, Eigen::Vector3d const & pivot_point) {\n\t\treturn dr::translate(pivot_point) * Eigen::AngleAxisd{angle, axis} * dr::translate(-pivot_point);\n\t}\n\n\t/// Create a rotation around the X axis with a given angle.\n\tinline Eigen::AngleAxisd rotateX(double angle) {\n\t\treturn dr::rotate(angle, axes::x());\n\t}\n\n\t/// Create a rotation around the X axis with a given angle and center of rotation.\n\tinline Eigen::Isometry3d rotateX(double angle, Eigen::Vector3d const & pivot_point) {\n\t\treturn dr::rotate(angle, axes::x(), pivot_point);\n\t}\n\n\t/// Create a rotation around the Y axis with a given angle.\n\tinline Eigen::AngleAxisd rotateY(double angle) {\n\t\treturn dr::rotate(angle, axes::y());\n\t}\n\n\t/// Create a rotation around the Y axis with a given angle and center of rotation.\n\tinline Eigen::Isometry3d rotateY(double angle, Eigen::Vector3d const & pivot_point) {\n\t\treturn dr::rotate(angle, axes::y(), pivot_point);\n\t}\n\n\t/// Create a rotation around the Z axis with a given angle.\n\tinline Eigen::AngleAxisd rotateZ(double angle) {\n\t\treturn dr::rotate(angle, axes::z());\n\t}\n\n\t/// Create a rotation around the Z axis with a given angle and center of rotation.\n\tinline Eigen::Isometry3d rotateZ(double angle, Eigen::Vector3d const & pivot_point) {\n\t\treturn dr::rotate(angle, axes::z(), pivot_point);\n\t}\n\n\t/// Convert rpy to quaternions. Convention here is z-y-x.\n\tinline Eigen::Quaterniond rpyToQuaternion(double r, double p, double y) {\n\t\treturn rotateZ(y) * rotateY(p) * rotateX(r);\n\t}\n\n\t/// Convert rpy to quaternions. Convention here is z-y-x.\n\tinline Eigen::Quaterniond rpyToQuaternion(Eigen::Vector3d const & rpy) {\n\t\treturn rpyToQuaternion(rpy[0], rpy[1], rpy[2]);\n\t}\n\n\t/// Convert a quaternion to rpy. Convention here is z-y-x.\n\tinline Eigen::Vector3d quaternionToRpy(Eigen::Quaterniond const & quaternion) {\n\t\tEigen::Vector3d rpy = quaternion.matrix().eulerAngles(2, 1, 0);\n\n\t\tstd::swap(rpy[0], rpy[2]);\n\n\t\treturn rpy;\n\t}\n\n\t/// Project vector a onto b.\n\t/**\n\t * \\return The projection of a onto b.\n\t */\n\ttemplate<typename A, typename B>\n\tauto projection(\n\t\tA const & a, ///< Vector a.\n\t\tB const & b  ///< Vector b.\n\t) -> decltype((a.dot(b) / b.dot(b)) * b) {\n\t\treturn (a.dot(b) / b.dot(b)) * b;\n\t}\n\n\t/// Get the rejection of vector a onto b.\n\t/**\n\t * \\return The rejection of a onto b.\n\t */\n\ttemplate<typename A, typename B>\n\tauto rejection(\n\t\tA const & a, ///< Vector a.\n\t\tB const & b  ///< Vector b.\n\t) -> decltype(a - projection(a, b)) {\n\t\treturn a - projection(a, b);\n\t}\n}\n", "meta": {"hexsha": "8004c54d1f606a251784dd747aea512d312b48ca", "size": 4533, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dr_eigen/eigen.hpp", "max_stars_repo_name": "delftrobotics/dr_eigen", "max_stars_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-06-02T14:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-02T14:14:37.000Z", "max_issues_repo_path": "include/dr_eigen/eigen.hpp", "max_issues_repo_name": "delftrobotics/dr_eigen", "max_issues_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dr_eigen/eigen.hpp", "max_forks_repo_name": "delftrobotics/dr_eigen", "max_forks_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4791666667, "max_line_length": 115, "alphanum_fraction": 0.692918597, "num_tokens": 1240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5741578364657786}}
{"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": "// TestNonCentralChiSquared.cpp\r\n//\r\n// Test of noncentral chi^2 distribution (boost 1.36!!!). Once you understand\r\n// the member functions and global functions for 1 kind of distribitions it becomes\r\n// very easy to apply them to other kinds of distributions.\r\n//\r\n// Contents:\r\n//\r\n//\t1. Statistcal properties of some distributions\r\n//\t2. Create a table of power of a test using non central chi^2, similar to boost except\r\n//  we store all the data in an 1) normal matrix, 2) associative matrix. The advantage of approach\r\n//  2 is that we can index using specific values of the degrees of freedom and non centrality parameter.\r\n//\r\n//\tDJD, based on adaption of code in Chapter 3.\r\n//\r\n//\t2009-1-8 DD creating look up tables\r\n//\r\n// (C) Datasim Education BV 2009\r\n//\r\n\r\n#include <boost/math/distributions/non_central_chi_squared.hpp> // for NC chi_squared_distribution\r\n#include <boost/math/special_functions/cbrt.hpp>\t\t\t\t// for chi_squared_distribution\r\n#include <boost/math/distributions.hpp>\t\t\t\t\t\t\t// For non-member functions of distributions\r\n\r\n#include <boost/math/distributions/chi_squared.hpp> \r\n#include <boost/math/distributions/poisson.hpp>\r\n\r\n#include \"UtilitiesDJD/AssociativeStructures/AssocArray.cpp\"\r\n#include \"UtilitiesDJD/AssociativeStructures/AssocMatrix.cpp\"\r\n\r\n#include \"UtilitiesDJD/CompileTimeVectorsAndMatrices/VectorSpace.cpp\"\r\n#include \"UtilitiesDJD/CompileTimeVectorsAndMatrices/VectorSpaceMechanisms.cpp\"\r\n#include \"UtilitiesDJD/VectorsAndMatrices/Vector.cpp\"\r\n#include \"UtilitiesDJD/VectorsAndMatrices/NumericMatrix.cpp\"\r\n#include \"UtilitiesDJD/VectorsAndMatrices/ArrayMechanisms.cpp\"\r\n#include \"UtilitiesDJD/ExcelDriver/ExcelMechanisms.hpp\"\r\n#include \"UtilitiesDJD/Geometry/Range.cpp\"\r\n#include \"UtilitiesDJD/BitsAndPieces/StringConversions.hpp\"\r\n#include \"UtilitiesDJD/ExceptionClasses/DatasimException.hpp\"\r\n#include \"UtilitiesDJD/ExceptionClasses/DatasimException.hpp\"\r\n#include \"UtilitiesDJD/RNG/UniformGenerator.hpp\"\r\n#include \"UtilitiesDJD/RNG/NormalGenerator.hpp\"\r\n\r\n\r\n#include <iostream>\r\nusing namespace std;\r\n\r\ntemplate <typename Key1, typename Key2, typename Value>\r\n\tvoid print(const AssocMatrix<Key1, Key2, Value>& assMat)\r\n{\r\n\r\n\t// Iterating in the map\r\n\tAssocMatrix<Key1, Key2, Value>::const_iterator iter = assMat.begin();\r\n\r\n\r\n\t\r\n\tfor (long i = assMat.mat->MinRowIndex(); i <= assMat.mat->MaxRowIndex(); ++i)\r\n\t{\r\n\t\tcout << \"Row \" << (*iter).first << \":  \";\r\n\t\tfor (long j = assMat.mat->MinColumnIndex(); j <= assMat.mat->MaxColumnIndex(); ++j)\r\n\t\t{\r\n\t\t\tcout << std::setprecision(3) << (*assMat.mat)(i,j) << \", \";\r\n\t\t}\r\n\t\tcout << endl;iter++;\r\n\t}\r\n\t\r\n\tcout << endl;\r\n}\r\n\r\nint main()\r\n{\r\n\r\n\t// Significance level\r\n\tdouble level = 0.05;\r\n\tdouble cs;\t\t\t// Temporary variable for chi^2 distribution\r\n\r\n\t// Now create the row and column indices\r\n\tVectorCollectionGenerator<double, double> dofRows; // Degrees of freedom\r\n\tdofRows.Start = 2.0;\r\n\tdofRows.Increment = 1.0;\r\n\tdofRows.Size = 9;\r\n\tSet<double> dofSet = createSet<double>(dofRows);\r\n\r\n\tVectorCollectionGenerator<double, double> nonCentralParameterColumns; // non cen parameter\r\n\tnonCentralParameterColumns.Start = 2.0;\r\n\tnonCentralParameterColumns.Increment = 2.0;\r\n\tnonCentralParameterColumns.Size = 5;\r\n\tSet<double> nonCentralParameterSet = createSet<double>(nonCentralParameterColumns);\r\n\r\n\r\n\t// Start values for rows and columns\r\n\tdouble r1 = dofRows.Start;\r\n\tdouble c1 = nonCentralParameterColumns.Start;\r\n\r\n\t// Lookup table dimensions\r\n\tlong NRows = dofRows.Size;\t\t\t\t\t\t\t\t// Degrees of freedom\r\n\tlong NColumns = nonCentralParameterColumns.Size;\t\t// Non-centrality parameter\r\n\tdouble incrementRow = dofRows.Increment;\r\n\tdouble incrementColumn = nonCentralParameterColumns.Increment;\r\n\r\n\tNumericMatrix<double, long> mat(NRows, NColumns);\r\n\tusing namespace boost::math; // For convenience\r\n\t// Basic case, no associativity\r\n\tfor (long r = mat.MinRowIndex(); r <= mat.MaxRowIndex(); ++r)\r\n\t{\t\r\n\t\tc1 = nonCentralParameterColumns.Start;\r\n\t\tfor (long c = mat.MinColumnIndex(); c <= mat.MaxColumnIndex(); ++c)\r\n\t\t{\r\n//\t\t cs = quantile(complement(chi_squared(r1), 0.05));\r\n//\t\t mat(r,c)=cdf(complement(non_central_chi_squared(r1,c1),cs));\r\n//\t\t c1 += incrementColumn;\r\n\t\t cs = quantile(chi_squared(r1), 0.05);\r\n\t\t mat(r,c)=cdf(non_central_chi_squared(r1,c1),cs);\r\n\t\t c1 += incrementColumn;\r\n\t\t}\r\n\r\n\t\tr1 += incrementRow;\r\n\t}\r\n\r\n\t// Now create the associative matrix\r\n\tAssocMatrix<double, double, double> myAssocMat(dofSet, nonCentralParameterSet, mat);\r\n\tprint(myAssocMat);\r\n\r\n\tprintAssocMatrixInExcel(myAssocMat, string(\"NCCQT\"));\r\n\r\n    return 0;\r\n}", "meta": {"hexsha": "dda03bcb9b4200d980326e205d8aeb30edaeec54", "size": 4548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI Interop Test (Chi-Squared)/CPPVersion2/Main.cpp", "max_stars_repo_name": "jdm7dv/financial", "max_stars_repo_head_hexsha": "673a552d58751643dbca0ba633aeff119eda107d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T06:54:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T06:54:08.000Z", "max_issues_repo_path": "windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI Interop Test (Chi-Squared)/CPPVersion2/Main.cpp", "max_issues_repo_name": "jdm7dv/financial", "max_issues_repo_head_hexsha": "673a552d58751643dbca0ba633aeff119eda107d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI Interop Test (Chi-Squared)/CPPVersion2/Main.cpp", "max_forks_repo_name": "jdm7dv/financial", "max_forks_repo_head_hexsha": "673a552d58751643dbca0ba633aeff119eda107d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-19T19:27:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T06:26:06.000Z", "avg_line_length": 35.811023622, "max_line_length": 105, "alphanum_fraction": 0.7286719437, "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5741578253523659}}
{"text": "//\n//  main.cpp\n//  CameraCalibration\n//\n//  Created by Michael Schwendeman on 8/11/15.\n//  Copyright (c) 2015 MSS. All rights reserved.\n//\n\n#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <opencv2/highgui.hpp>\n#include <boost/filesystem.hpp>\n\nusing namespace cv;\nusing namespace std;\nusing namespace boost::filesystem;\n\nint main() {\n    // Set plot options\n    bool plotUndistort = true;\n    bool plotCheckerboard = false;\n    if (plotCheckerboard || plotUndistort)\n        namedWindow(\"Image\", CV_WINDOW_AUTOSIZE); //create window for left image\n    \n    // Set path\n    path p = \"/Volumes/Data/PAPA/TGTcruise2015/StereoSystem/15Jan2015/1740UTC_flea35\";\n    //path p = \"/Volumes/Data/PAPA/TGTcruise2015/StereoSystem/15Jan2015/1804UTC_flea34\";\n    //path p = \"/Volumes/Data/PAPA/TGTcruise2015/StereoSystem/15Jan2015/1750UTC_flea65\";\n    //path p = \"/Volumes/Data/PAPA/TGTcruise2015/StereoSystem/15Jan2015/1834UTC_flea18\";\n    //path p = \"/Volumes/Data/PAPA/TGTcruise2015/StereoSystem/15Jan2015/1811UTC_flea21\";\n    //path p = \"/Volumes/Data/PAPA/TGTcruise2015/StereoSystem/15Jan2015/1825UTC_flea83\";\n    \n    vector<path> imageVec;\n    copy(directory_iterator(p),directory_iterator(),back_inserter(imageVec));\n    \n    // Setup checkerboard\n    int numCornersHor = 7;\n    int numCornersVer = 4;\n    int numSquares = numCornersHor * numCornersVer;\n    Size board_sz = Size(numCornersHor, numCornersVer);\n    vector<vector<Point3f>> object_points;\n    vector<vector<Point2f>> image_points;\n    vector<Point2f> corners;\n    vector<Point3f> obj;\n    for(int j=0;j<numSquares;j++)\n        obj.push_back(Point3f((j/numCornersHor)*2*25.4, (j%numCornersHor)*2*25.4, 0.0f));\n    \n    // Detect checkerboard\n    Mat image;\n    string filename;\n    int skip = 100;\n    int iframe = 0;\n    for ( vector<path>::const_iterator it = imageVec.begin(); it != imageVec.end(); ++it )\n    {\n        if ( !(it->extension().empty()) && (it->extension().string() == \".pgm\") && (iframe % skip == 0) )\n        {\n            filename = it->string();\n            image = imread(filename,CV_LOAD_IMAGE_GRAYSCALE);\n            bool found = findChessboardCorners(image, board_sz, corners, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS);\n            \n            if(found)\n            {\n                cornerSubPix(image, corners, Size(11, 11), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1));\n                if (plotCheckerboard)\n                {\n                    drawChessboardCorners(image, board_sz, corners, found);\n                    imshow(\"Image\",image);\n                    waitKey(0);\n                }\n                image_points.push_back(corners);\n                object_points.push_back(obj);\n            }\n        }\n        iframe++;\n    }\n    \n    // Calculate calibration\n    Mat intrinsic = Mat(3, 3, CV_32FC1);\n    Mat distCoeffs;\n    vector<Mat> rvecs;\n    vector<Mat> tvecs;\n    calibrateCamera(object_points, image_points, image.size(), intrinsic, distCoeffs, rvecs, tvecs, CV_CALIB_ZERO_TANGENT_DIST, TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 1000, DBL_EPSILON));\n    \n    // Check undistort\n    iframe = 0;\n    if (plotUndistort)\n    {\n        namedWindow(\"Undistorted\", CV_WINDOW_AUTOSIZE); //create window for left image\n        Mat imageUndistorted;\n        for (vector<path>::const_iterator it (imageVec.begin()); it != imageVec.end(); ++it)\n        {\n            if ( !(it->extension().empty()) && (it->extension().string() == \".pgm\") && (iframe % skip == 0) )\n            {\n                filename = it->string();\n                image = imread(filename);\n                undistort(image, imageUndistorted, intrinsic, distCoeffs);\n                imshow(\"Image\", image);\n                imshow(\"Undistorted\", imageUndistorted);\n                waitKey(0);\n            }\n            iframe++;\n        }\n        destroyWindow(\"Undistorted\"); //create window for left image\n    }\n    \n    // Close windows\n    if (plotCheckerboard || plotUndistort)\n        destroyWindow(\"Image\"); //create window for left image\n    \n    // Save intrinsic matrix and distortion coefficients\n    string outputFile;\n    outputFile = p.string() + \"/OpenCVCalibrationResults.yml\";\n    FileStorage fs(outputFile, FileStorage::WRITE);\n    fs << \"Intrinsic Matrix\" << intrinsic;\n    fs << \"Distortion Coefficients\" << distCoeffs;\n    fs.release();\n    return 0;\n}\n", "meta": {"hexsha": "01e670853510e1fcd1415fd89571dca627f370d9", "size": 4398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CameraCalibration/CameraCalibration/main.cpp", "max_stars_repo_name": "mikeschwendy/StereoOpenCV", "max_stars_repo_head_hexsha": "fc5c9ba2c11f1dc179093fff1123b1b0fe4e0f49", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-19T17:23:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-19T17:23:40.000Z", "max_issues_repo_path": "CameraCalibration/CameraCalibration/main.cpp", "max_issues_repo_name": "mikeschwendy/StereoOpenCV", "max_issues_repo_head_hexsha": "fc5c9ba2c11f1dc179093fff1123b1b0fe4e0f49", "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": "CameraCalibration/CameraCalibration/main.cpp", "max_forks_repo_name": "mikeschwendy/StereoOpenCV", "max_forks_repo_head_hexsha": "fc5c9ba2c11f1dc179093fff1123b1b0fe4e0f49", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9579831933, "max_line_length": 197, "alphanum_fraction": 0.6223283311, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5741493819602281}}
{"text": "#include \"truncated_svd.hpp\"\n\n#include <gtest/gtest.h>\n\n#include <armadillo>\n#include <cmath>\n#include <limits>\n#include <random>\n#include <stdexcept>\n#include <vector>\n\n#include \"thin_lq.hpp\"\n\ntemplate <typename Real>\nvoid CreateTestMatrix(long m, long n, long r, arma::Mat<Real> &A,\n                      long &rank_cutoff, Real &absolute_tolerance,\n                      Real &relative_tolerance) {\n    if (m < 1 || n < 1) {\n        throw std::invalid_argument(\n            \"Number of rows and columns must be positive\");\n    }\n\n    // Create Ut factor\n    arma::Mat<Real> Ut;\n    {\n        arma::Mat<Real> temp(r, m, arma::fill::randn);\n\n        arma::Mat<Real> L;\n        ThinLq<Real>(temp, L, Ut);\n    }\n\n    // Create s factor; s[i] ~ Uniform([(r - 1 - i), (r - i)])\n    arma::Col<Real> s(r, arma::fill::randu);\n    for (long i = 0; i < r; ++i) {\n        s(i) += r - i - 1;\n    }\n\n    // Create Vt factor\n    arma::Mat<Real> Vt;\n    {\n        arma::Mat<Real> temp(r, n, arma::fill::randn);\n\n        arma::Mat<Real> L;\n        ThinLq<Real>(temp, L, Vt);\n    }\n\n    // Compute A = Ut.conjugate() * diagmat(s) * Vt\n    A = Ut.t() * arma::diagmat(s) * Vt;\n\n    // Compute absolute and relative errors given specified maximum rank\n    std::vector<Real> absolute_error(r);\n\n    absolute_error[r - 1] = static_cast<Real>(0);\n    for (long i = r - 1; i > 0; --i) {\n        absolute_error[i - 1] = absolute_error[i] + std::pow(s(i), 2);\n    }\n    Real frobenius_norm = absolute_error[0] + std::pow(s(0), 2);\n\n    for (long i = 0; i < r; ++i) {\n        absolute_error[i] = std::sqrt(absolute_error[i]);\n    }\n    frobenius_norm = std::sqrt(frobenius_norm);\n\n    std::vector<Real> relative_error(r);\n\n    for (long i = 0; i < r; ++i) {\n        relative_error[i] = absolute_error[i] / frobenius_norm;\n    }\n\n    // Determine 75% Frobenius norm cutoff rank\n    rank_cutoff = 1;\n    while (rank_cutoff <= r) {\n        if (relative_error[rank_cutoff - 1] <= static_cast<Real>(0.25)) {\n            break;\n        }\n        ++rank_cutoff;\n    }\n\n    // Compute accuracy levels based on cutoff rank\n    absolute_tolerance =\n        (absolute_error[rank_cutoff - 2] + absolute_error[rank_cutoff - 1]) / 2;\n    relative_tolerance =\n        (relative_error[rank_cutoff - 2] + relative_error[rank_cutoff - 1]) / 2;\n}\n\ntemplate <typename Real>\nvoid SvdFactorQualityTest(const arma::Mat<Real> &U, const arma::Col<Real> &s,\n                          const arma::Mat<Real> &V) {\n    const long m = U.n_rows;\n    const long n = V.n_rows;\n    const long r = s.n_rows;\n\n    for (long j1 = 0; j1 < r; ++j1) {\n        for (long j2 = 0; j2 < j1; ++j2) {\n            Real dot_product = static_cast<Real>(0);\n            for (long i = 0; i < m; ++i) {\n                dot_product += U(i, j1) * U(i, j2);\n            }\n\n            ASSERT_NEAR(dot_product, static_cast<Real>(0),\n                        100 * std::numeric_limits<Real>::epsilon());\n        }\n\n        Real norm_squared = static_cast<Real>(0);\n        for (long i = 0; i < m; ++i) {\n            norm_squared += std::pow(U(i, j1), 2);\n        }\n\n        ASSERT_NEAR(norm_squared, static_cast<Real>(1),\n                    100 * std::numeric_limits<Real>::epsilon());\n    }\n\n    for (long i = 0; i < r; ++i) {\n        if (i < r - 1) {\n            ASSERT_GE(s(i), s(i + 1));\n        } else {\n            ASSERT_GT(s(i), static_cast<Real>(0));\n        }\n    }\n\n    for (long j1 = 0; j1 < r; ++j1) {\n        for (long j2 = 0; j2 < j1; ++j2) {\n            Real dot_product = static_cast<Real>(0);\n            for (long i = 0; i < n; ++i) {\n                dot_product += V(i, j1) * V(i, j2);\n            }\n\n            ASSERT_NEAR(dot_product, static_cast<Real>(0),\n                        100 * std::numeric_limits<Real>::epsilon());\n        }\n\n        Real norm_squared = static_cast<Real>(0);\n        for (long i = 0; i < n; ++i) {\n            norm_squared += std::pow(V(i, j1), 2);\n        }\n\n        ASSERT_NEAR(norm_squared, static_cast<Real>(1),\n                    100 * std::numeric_limits<Real>::epsilon());\n    }\n}\n\ntemplate <typename Real>\nvoid ThinSvdTest(long m, long n, long r) {\n    if (m < 1 || n < 1 || r < 1) {\n        throw std::invalid_argument(\"Matrix sizes and rank must be positive\");\n    }\n\n    if (r > m || r > n) {\n        throw std::invalid_argument(\"Rank must be smaller than matrix size\");\n    }\n\n    // Construct appropriate matrix\n    arma::Mat<Real> A;\n    long rank_cutoff;\n    Real absolute_tolerance;\n    Real relative_tolerance;\n    CreateTestMatrix<Real>(m, n, r, A, rank_cutoff, absolute_tolerance,\n                           relative_tolerance);\n\n    // Test\n    arma::Mat<Real> U;\n    arma::Col<Real> s;\n    arma::Mat<Real> V;\n    long rank;\n    TruncatedSvd<Real>(A, 0, false, U, s, V, rank);\n\n    const Real frobenius_error =\n        arma::norm(A - U * arma::diagmat(s) * V.t(), \"fro\");\n\n    ASSERT_EQ(rank, std::min(m, n));\n    SvdFactorQualityTest<Real>(U, s, V);\n    ASSERT_LE(frobenius_error, 1000 * std::numeric_limits<Real>::epsilon());\n}\n\ntemplate <typename Real>\nvoid TruncatedSvdAbsoluteToleranceTest(long m, long n, long r) {\n    if (m < 1 || n < 1 || r < 1) {\n        throw std::invalid_argument(\"Matrix sizes and rank must be positive\");\n    }\n\n    if (r > m || r > n) {\n        throw std::invalid_argument(\"Rank must be smaller than matrix size\");\n    }\n\n    // Construct appropriate matrix\n    arma::Mat<Real> A;\n    long rank_cutoff;\n    Real absolute_tolerance;\n    Real relative_tolerance;\n    CreateTestMatrix<Real>(m, n, r, A, rank_cutoff, absolute_tolerance,\n                           relative_tolerance);\n\n    // Test\n    arma::Mat<Real> U;\n    arma::Col<Real> s;\n    arma::Mat<Real> V;\n    long rank;\n    TruncatedSvd<Real>(A, absolute_tolerance, false, U, s, V, rank);\n\n    const Real frobenius_error =\n        arma::norm(A - U * arma::diagmat(s) * V.t(), \"fro\");\n\n    ASSERT_EQ(rank, rank_cutoff);\n    SvdFactorQualityTest<Real>(U, s, V);\n    ASSERT_LE(frobenius_error, absolute_tolerance);\n}\n\ntemplate <typename Real>\nvoid TruncatedSvdRelativeToleranceTest(long m, long n, long r) {\n    if (m < 1 || n < 1 || r < 1) {\n        throw std::invalid_argument(\"Matrix sizes and rank must be positive\");\n    }\n\n    if (r > m || r > n) {\n        throw std::invalid_argument(\"Rank must be smaller than matrix size\");\n    }\n\n    // Construct appropriate matrix\n    arma::Mat<Real> A;\n    long rank_cutoff;\n    Real absolute_tolerance;\n    Real relative_tolerance;\n    CreateTestMatrix<Real>(m, n, r, A, rank_cutoff, absolute_tolerance,\n                           relative_tolerance);\n\n    // Test\n    arma::Mat<Real> U;\n    arma::Col<Real> s;\n    arma::Mat<Real> V;\n    long rank;\n    TruncatedSvd<Real>(A, relative_tolerance, true, U, s, V, rank);\n\n    const Real frobenius_norm = arma::norm(A, \"fro\");\n    const Real frobenius_error =\n        arma::norm(A - U * arma::diagmat(s) * V.t(), \"fro\");\n\n    ASSERT_EQ(rank, rank_cutoff);\n    SvdFactorQualityTest<Real>(U, s, V);\n    ASSERT_LE(frobenius_error, relative_tolerance * frobenius_norm);\n}\n\nTEST(TruncatedSvd, ThinSvd_ShortMatrix) {\n    ThinSvdTest<float>(16, 64, 8);\n    ThinSvdTest<double>(16, 64, 8);\n}\n\nTEST(TruncatedSvd, ThinSvd_SquareMatrix) {\n    ThinSvdTest<float>(32, 32, 8);\n    ThinSvdTest<double>(32, 32, 8);\n}\n\nTEST(TruncatedSvd, ThinSvd_TallMatrix) {\n    ThinSvdTest<float>(64, 16, 8);\n    ThinSvdTest<double>(64, 16, 8);\n}\n\nTEST(TruncatedSvd, TruncatedSvdAbsoluteTolerance_ShortMatrix) {\n    TruncatedSvdAbsoluteToleranceTest<float>(16, 64, 8);\n    TruncatedSvdAbsoluteToleranceTest<double>(16, 64, 8);\n}\n\nTEST(TruncatedSvd, TruncatedSvdAbsoluteTolerance_SquareMatrix) {\n    TruncatedSvdAbsoluteToleranceTest<float>(32, 32, 8);\n    TruncatedSvdAbsoluteToleranceTest<double>(32, 32, 8);\n}\n\nTEST(TruncatedSvd, TruncatedSvdAbsoluteTolerance_TallMatrix) {\n    TruncatedSvdAbsoluteToleranceTest<float>(64, 16, 8);\n    TruncatedSvdAbsoluteToleranceTest<double>(64, 16, 8);\n}\n\nTEST(TruncatedSvd, TruncatedSvdRelativeTolerance_ShortMatrix) {\n    TruncatedSvdRelativeToleranceTest<float>(16, 64, 8);\n    TruncatedSvdRelativeToleranceTest<double>(16, 64, 8);\n}\n\nTEST(TruncatedSvd, TruncatedSvdRelativeTolerance_SquareMatrix) {\n    TruncatedSvdRelativeToleranceTest<float>(32, 32, 8);\n    TruncatedSvdRelativeToleranceTest<double>(32, 32, 8);\n}\n\nTEST(TruncatedSvd, TruncatedSvdRelativeTolerance_TallMatrix) {\n    TruncatedSvdRelativeToleranceTest<float>(64, 16, 8);\n    TruncatedSvdRelativeToleranceTest<double>(64, 16, 8);\n}\n\nint main(int argc, char **argv) {\n    ::testing::InitGoogleTest(&argc, argv);\n\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "290fb4fd5d1173d4fdd3e2ece3e7fef6cb9a462c", "size": 8585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/truncated_svd_test.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": "test/truncated_svd_test.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": "test/truncated_svd_test.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": 29.4006849315, "max_line_length": 80, "alphanum_fraction": 0.595573675, "num_tokens": 2506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5741493819602281}}
{"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 * @brief Tests for GeoLib::Surface::isPntInSfc()\n *\n * @copyright\n * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/LICENSE.txt\n */\n\n#include <array>\n#include <memory>\n#include <random>\n#include <vector>\n\n#include \"gtest/gtest.h\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"GeoLib/GEOObjects.h\"\n#include \"GeoLib/Point.h\"\n#include \"GeoLib/Surface.h\"\n#include \"GeoLib/Triangle.h\"\n#include \"GeoLib/AnalyticalGeometry.h\"\n\n#include \"MathLib/LinAlg/Dense/DenseMatrix.h\"\n#include \"MathLib/Point3d.h\"\n\n#include \"MeshLib/Mesh.h\"\n#include \"MeshLib/Node.h\"\n#include \"MeshLib/convertMeshToGeo.h\"\n#include \"MeshLib/MeshGenerators/MeshGenerator.h\"\n\ninline double constant(double , double )\n{\n    return 0.0;\n}\n\ninline double coscos(double x, double y)\n{\n    return std::cos(x) * std::cos(y);\n}\n\ninline MathLib::Point3d\ngetEdgeMiddlePoint(MathLib::Point3d const&a, MathLib::Point3d const& b)\n{\n    return MathLib::Point3d(std::array<double,3>({{\n        (a[0]+b[0])/2, (a[1]+b[1])/2, (a[2]+b[2])/2}}));\n}\n\ninline std::tuple<MathLib::Point3d, MathLib::Point3d, MathLib::Point3d>\ngetEdgeMiddlePoints(GeoLib::Triangle const& tri)\n{\n    return std::make_tuple(\n        getEdgeMiddlePoint(*tri.getPoint(0), *tri.getPoint(1)),\n        getEdgeMiddlePoint(*tri.getPoint(1), *tri.getPoint(2)),\n        getEdgeMiddlePoint(*tri.getPoint(2), *tri.getPoint(0)));\n}\n\n/// Computes rotation matrix according to the z,x',z'' convention\ninline MathLib::DenseMatrix<double, std::size_t>\ngetRotMat(double alpha, double beta, double gamma)\n{\n    MathLib::DenseMatrix<double, std::size_t> rot_mat(3,3);\n    rot_mat(0,0) = cos(alpha)*cos(gamma) - sin(alpha)*cos(beta)*sin(gamma);\n    rot_mat(0,1) = sin(alpha)*cos(gamma) + cos(alpha)*cos(beta)*sin(gamma);\n    rot_mat(0,2) = sin(beta)*sin(gamma);\n    rot_mat(1,0) = -cos(alpha)*sin(gamma) - sin(alpha)*cos(beta)*cos(gamma);\n    rot_mat(1,1) = -sin(alpha)*sin(gamma) + cos(alpha)*cos(beta)*cos(gamma);\n    rot_mat(1,2) = sin(beta)*cos(gamma);\n    rot_mat(2,0) = sin(alpha)*sin(beta);\n    rot_mat(2,1) = -cos(alpha)*sin(beta);\n    rot_mat(2,2) = cos(beta);\n    return rot_mat;\n}\n\nTEST(GeoLib, SurfaceIsPointInSurface)\n{\n    std::vector<std::function<double(double, double)>> surface_functions;\n    surface_functions.emplace_back(constant);\n    surface_functions.emplace_back(coscos);\n\n    for (const auto& f : surface_functions) {\n        std::random_device rd;\n\n        std::string name(\"Surface\");\n        // generate ll and ur in random way\n        std::mt19937 random_engine_mt19937(rd());\n        std::normal_distribution<> normal_dist_ll(-10, 2);\n        std::normal_distribution<> normal_dist_ur(10, 2);\n        MathLib::Point3d ll(std::array<double,3>({{\n            normal_dist_ll(random_engine_mt19937),\n            normal_dist_ll(random_engine_mt19937),\n            0.0}}));\n        MathLib::Point3d ur(std::array<double,3>({{\n            normal_dist_ur(random_engine_mt19937),\n            normal_dist_ur(random_engine_mt19937),\n            0.0}}));\n        for (std::size_t k(0); k<3; ++k)\n            if (ll[k] > ur[k])\n                std::swap(ll[k], ur[k]);\n\n        // random discretization of the domain\n        std::default_random_engine re(rd());\n        std::uniform_int_distribution<std::size_t> uniform_dist(2, 25);\n        std::array<std::size_t,2> n_steps = {{uniform_dist(re),uniform_dist(re)}};\n\n        std::unique_ptr<MeshLib::Mesh> sfc_mesh(\n            MeshLib::MeshGenerator::createSurfaceMesh(\n                name, ll, ur, n_steps, f\n            )\n        );\n\n        // random rotation angles\n        std::normal_distribution<> normal_dist_angles(\n            0, boost::math::double_constants::two_pi);\n        std::array<double,3> euler_angles = {{\n            normal_dist_angles(random_engine_mt19937),\n            normal_dist_angles(random_engine_mt19937),\n            normal_dist_angles(random_engine_mt19937)\n            }};\n\n        MathLib::DenseMatrix<double, std::size_t> rot_mat(getRotMat(\n            euler_angles[0], euler_angles[1], euler_angles[2]));\n\n        std::vector<MeshLib::Node*> const& nodes(sfc_mesh->getNodes());\n        GeoLib::rotatePoints<MeshLib::Node>(rot_mat, nodes);\n\n        MathLib::Vector3 const normal(0,0,1.0);\n        MathLib::Vector3 const surface_normal(rot_mat * normal);\n        double const scaling(1e-6);\n        MathLib::Vector3 const displacement(scaling * surface_normal);\n\n        GeoLib::GEOObjects geometries;\n        MeshLib::convertMeshToGeo(*sfc_mesh, geometries);\n\n        std::vector<GeoLib::Surface*> const& sfcs(*geometries.getSurfaceVec(name));\n        GeoLib::Surface const*const sfc(sfcs.front());\n        std::vector<GeoLib::Point*> const& pnts(*geometries.getPointVec(name));\n\n        double const eps(std::numeric_limits<double>::epsilon());\n\n        // test triangle edge point of the surface triangles\n        for (auto const p : pnts) {\n            EXPECT_TRUE(sfc->isPntInSfc(*p, eps));\n            MathLib::Point3d q(*p);\n            for (std::size_t k(0); k<3; ++k)\n                q[k] += displacement[k];\n            EXPECT_FALSE(sfc->isPntInSfc(q, eps));\n        }\n        // test edge middle points of the triangles\n        for (std::size_t k(0); k<sfc->getNumberOfTriangles(); ++k) {\n            MathLib::Point3d p, q, r;\n            std::tie(p,q,r) = getEdgeMiddlePoints(*(*sfc)[k]);\n            EXPECT_TRUE(sfc->isPntInSfc(p, eps));\n            EXPECT_TRUE(sfc->isPntInSfc(q, eps));\n            EXPECT_TRUE(sfc->isPntInSfc(r, eps));\n        }\n    }\n}\n", "meta": {"hexsha": "11fd33e8c64f71096e155f6d9730b3e0037dc4c9", "size": 5669, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/GeoLib/TestSurfaceIsPointInSurface.cpp", "max_stars_repo_name": "mjamoein/ogs", "max_stars_repo_head_hexsha": "52e4d1bcf3bc21a44ee7710fc9900d8729334ad4", "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": "Tests/GeoLib/TestSurfaceIsPointInSurface.cpp", "max_issues_repo_name": "mjamoein/ogs", "max_issues_repo_head_hexsha": "52e4d1bcf3bc21a44ee7710fc9900d8729334ad4", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tests/GeoLib/TestSurfaceIsPointInSurface.cpp", "max_forks_repo_name": "mjamoein/ogs", "max_forks_repo_head_hexsha": "52e4d1bcf3bc21a44ee7710fc9900d8729334ad4", "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": 35.2111801242, "max_line_length": 83, "alphanum_fraction": 0.6325630623, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.5741126065365129}}
{"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": "/* Copyright (C) 2017 Karl Phillip Buhr <karlphillip@gmail.com>\n *\n * This work is licensed under the MIT License.\n * To view a copy of this license, visit:\n *      https://opensource.org/licenses/MIT\n *\n * This file is part of Madplotlib, a C++ library for building simple\n * 2D plots inspired on matplotlib.\n */\n/*\n * plot() has many forms. This file demonstrates how to use some of them.\n * However, the most complete form of plot() currently is:\n *     plot(x, y, marker, label, alpha, color, linewidth, markeredgecolor, markersize)\n *\n * Happy plotting!\n */\n\n#include <Eigen/Dense>\n\n#include \"Madplotlib.h\"\n\n#include <QApplication>\n\n// Uncomment the line below to save each chart as PNG image\n#define SCRSHOT\n\n/* Use case: simple line chart.\n * plot() draws the values of x and y on a line chart.\n * show() creates a new window to display the chart.\n * savefig() saves a screenshot of the chart as PNG image.\n */\nvoid test1()\n{\n    Eigen::ArrayXf x(16);\n    x <<   0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7,\n         0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5;\n\n    Eigen::ArrayXf y(16);\n    y <<  65,  79,  80,  68,  77,  81, 100, 102,\n         105, 111, 120, 126, 120, 104,  85,  92;\n\n    Madplotlib plt;\n    plt.plot(x, y);\n    plt.show();\n\n#ifdef SCRSHOT\n    plt.savefig(\"test1.png\");\n#endif\n}\n\n/* Use case: simple scatter chart.\n * plot() draws the values of x and y on a scatter chart.\n * show() creates a new window to display the chart.\n */\nvoid test2()\n{\n    float period = 0.5;\n    Eigen::ArrayXf x = Eigen::ArrayXf::LinSpaced(72, 0, 20);\n    Eigen::ArrayXf y = x.cos() * period;\n\n    Madplotlib plt;\n    plt.title(\"Test 2: Simple Scatter Plot\");\n    plt.plot(x, y, QString(\"o\"));\n    plt.show();\n\n#ifdef SCRSHOT\n    plt.savefig(\"test2.png\");\n#endif\n}\n\n/* Use case: plot 3 data sets on a line chart.\n * + axis() defines the X,Y range to make the labels look cooler.\n * + plot() draws X and Y as a continuous line, thicker (linewidth = 4).\n * + plot() adds 5 to every element if the Y axis and then draws it as a dashed line.\n * + plot() adds 10 to every element if the Y axis and then draws it as a dotted line.\n * + legend() with no args, displays the labels passed to plot() at a default position.\n */\nvoid test3()\n{\n    float period = 2;\n    Eigen::ArrayXf x = Eigen::ArrayXf::LinSpaced(100, 0, 25);\n    Eigen::ArrayXf y = x.cos() * period;\n\n    Madplotlib plt;\n    plt.title(\"Test 3: Multiple Data Series\");\n    plt.axis(0, 25, 0, 14);\n    plt.plot(x, y, marker=QString(\"--\"), label=QString(\"label=Dashed Line\"));\n    plt.plot(x, y+5, label=QString(\"label=Default Line\"), (quint32)4);\n    plt.plot(x, y+10, QString(\".\"), label=QString(\"label=Dotted Line\"));\n    plt.legend(); // default position is \"lower center\"\n    plt.show();\n\n#ifdef SCRSHOT\n    plt.savefig(\"test3.png\");\n#endif\n}\n\n/* Use case: simple scatter chart.\n * + Generates 50 random values between [0, 50] for the first data series.\n * + Generates 72 random values between [0, 75] for the second data series.\n * + title()\n * + locator_params() displays 10 ticks on the X axis.\n * + axis() defines the range of values for each axis.\n * + plot() uses the parameter \"o\" for a scatter plot,\n *          changes the transparency level to 30% for a red color marker,\n *          with a markersize of 8.\n * + plot() uses the parameter \"o\" for a scatter plot,\n *          changes the transparency level to 50% for a blue color marker.\n */\nvoid test4()\n{\n    Eigen::ArrayXf x_rand = Eigen::ArrayXf::Random(64) * 50;\n    Eigen::ArrayXf x = x_rand.abs();\n\n    Eigen::ArrayXf y_rand = Eigen::ArrayXf::Random(64) * 50;\n    Eigen::ArrayXf y = y_rand.abs();\n\n    Eigen::ArrayXf x_rand2 = Eigen::ArrayXf::Random(72) * 75;\n    Eigen::ArrayXf x2 = x_rand2.abs();\n\n    Eigen::ArrayXf y_rand2 = Eigen::ArrayXf::Random(72) * 75;\n    Eigen::ArrayXf y2 = y_rand2.abs();\n\n    Madplotlib plt;\n    plt.title(\"Test 4: Random Scatter Plot\");\n    plt.locator_params(\"x\", 10);\n    plt.axis(-25, 100, -25, 100);\n    plt.plot(x, y, marker=QString(\"o\"), 0.7f, QColor(255, 0, 0), 8.0f); // red, 30% transparent, markersize 8\n    plt.plot(x2, y2, marker=QString(\"o\"), 0.5f, QColor(0, 0, 255));     // blue, 50% transparent\n    plt.show();\n\n#ifdef SCRSHOT\n    plt.savefig(\"test4.png\");\n#endif\n}\n\n\n/* Use case that defines 3 series of data containing only Y axis values.\n * + title()\n * + ylabel()\n * + xlabel()\n * + plot() automatically creates data for the X axis and labels it Linear.\n * + plot() automatically creates data for the X axis and labels it Exponential.\n * + plot() automatically creates data for the X axis and labels it Flat.\n * + legend() displays all labels set through plot() in a legend positioned at the right.\n */\nvoid test5()\n{\n    // linear\n    Eigen::ArrayXf a = Eigen::ArrayXf::LinSpaced(20, 0, 2000);\n\n    // exponential\n    Eigen::ArrayXf b = Eigen::ArrayXf::LinSpaced(20, 0, 100);\n    b = b * b;\n\n    // flat\n    Eigen::ArrayXf c = Eigen::ArrayXf::Zero(20);\n    c = 1000;\n\n    Madplotlib plt;\n    plt.title(\"Test 5: Linear vs Exponential vs Flat\");\n    plt.ylabel(\"Y Values\");\n    plt.xlabel(\"X Values\");\n\n    plt.plot(a, QString(\"label=Linear\"));\n    plt.plot(b, QString(\"label=Exponential\"));\n    plt.plot(c, QString(\"label=Flat\"));\n    plt.legend(\"loc=center right\");\n    plt.show();\n\n#ifdef SCRSHOT\n    plt.savefig(\"test5.png\");\n#endif\n}\n\n\n/* Use case that plots 4 data sets.\n * + plot() argument \"o\" defines a scatter plot.\n * + plot() argument QColor defines the color for the line plot.\n * + xlabel() defines the label for the X axis.\n * + ylabel() defines the label for the Y axis.\n */\nvoid test6()\n{\n    Eigen::ArrayXf x(16);\n    x <<   0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7,\n         0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5;\n\n    Eigen::ArrayXf y(16);\n    y <<  65,  79,  80,  68,  77,  81, 100, 102,\n         105, 111, 120, 126, 120, 104,  85,  92;\n\n    Madplotlib plt;\n    plt.plot(x, y, color=QColor(0xFF2700));               // red\n    plt.plot(x, y, marker=QString(\"o\"), color=QColor(0xFF2700));\n    plt.plot(x, y-40, color=QColor(0x008FD5));            // blue\n    plt.plot(x, y-40, marker=QString(\"o\"), color=QColor(0x008FD5));\n\n    plt.title(\"Test 6: Line + Scatter\");\n    plt.xlabel(\"X values\");\n    plt.ylabel(\"Y values\");\n    plt.show();\n\n#ifdef SCRSHOT\n    plt.savefig(\"test6.png\");\n#endif\n}\n\n/* Use case with several UI customizations.\n * + title()\n * + xlabel() defines the label for the X axis.\n * + ylabel() defines the label for the Y axis.\n * + yticks() changes the default categories of Y axis for customized ones:\n *      Low:    represents all data between [0, 1]\n *      High:   represents all data between [1, 2]\n * + ylim() defines the range for the Y axis.\n * + plot() draws a scatter plot with larger circles (markersize = 7.0).\n * + grid() enables drawing of the background grid.\n */\nvoid test7()\n{\n    const double pi = std::acos(-1.0);\n\n    Eigen::ArrayXf x = Eigen::ArrayXf::LinSpaced(64, 0.0, 5.0);\n    Eigen::ArrayXf y = Eigen::cos(2 * pi * x) * Eigen::exp(-x);\n\n    Eigen::ArrayXf y_ticks(2);\n    y_ticks << 1, 2;\n\n    QVector<QString> y_labels;\n    y_labels.push_back(\"Low\");\n    y_labels.push_back(\"High\");\n\n    Madplotlib plt;\n    plt.title(\"Test 7: UI Customizations: Grid & Categories\");\n    plt.xlabel(\"time (s)\");\n    plt.ylabel(\"voltage (mV)\");\n    plt.yticks(y_ticks, y_labels);\n\n    // On Qt 7.5, Qt Charts has a bug spacing correctly categories on negative Y axis (-1, 1).\n    // For now, drawing (y+1) will bypass that since the values will fall between (0, 2).\n    plt.ylim(0, 2);\n    plt.plot(x, y+1, marker=QString(\"o\"), alpha=1.f, linewidth=2, markersize=7.0f); // alpha=1.f, linewidth=2, markersize=7.f\n    plt.grid(true);\n\n    plt.show();\n\n#ifdef SCRSHOT\n    plt.savefig(\"test7.png\");\n#endif\n}\n\n/* Use case that displays two waves on a scatter plot and then connects them with lines.\n * + axis() param \"off\" hides both axis ticks.\n * + plot() draw the X series using x's squared root as the Y series.\n * + plot() draw the X series using x's negative squared root as the Y series.\n * + noise is an array with 50 random numbers between [0, 2].\n * + plot() draw the X series using the difference of x's squared root and the noise asthe Y series.\n * + plot() draw the X series using the difference of x's negative squared root and the noise as the Y series.\n */\nvoid test8()\n{\n    Eigen::ArrayXf x = Eigen::ArrayXf::LinSpaced(50, 0, 100);\n\n    Madplotlib plt;\n    plt.title(\"Test 8: Line + Square Markers + Hidden Ticks\");\n    plt.axis(\"off\");\n    plt.plot(x, x.sqrt(), color=QColor(0, 0, 0));\n    plt.plot(x, -x.sqrt(), color = QColor(0, 0, 0));\n\n    Eigen::ArrayXf noise = Eigen::ArrayXf::Random(50) * 2;\n\n    plt.plot(x, x.sqrt() - noise, marker=QString(\"s\"), alpha = 0.7f, color=QColor(19, 154, 255), edgecolor=QColor(19, 154, 255)); // red squares without black edges\n    plt.plot(x, -x.sqrt() - noise, marker = QString(\"s\"), alpha = 0.7f, color=QColor(255, 41, 5), edgecolor=QColor(255, 41, 5));    // blue squares without black edges\n    plt.show();\n\n#ifdef SCRSHOT\n    plt.savefig(\"test8.png\");\n#endif\n}\n\n/* Use case that displays Y data twice with custom limits and ticks for both axis.\n * + title()\n * + xlabel()\n * + ylabel()\n * + plot() draws X,Y using a specific color.\n * + plot() uses circular markers with green edges filled with white.\n */\nvoid test9()\n{\n    Eigen::ArrayXf x(26);\n    x << 0, 102, 205, 301, 404,\n         500, 601, 701, 804, 904,\n         1006, 1503, 2016, 3086, 4002,\n         5178, 10094, 16012, 21267, 25985,\n         32641, 48486, 54925, 58145, 63291,\n         98029;\n\n    Eigen::ArrayXf y(26);\n    y << 924, 794, 2708, 3324, 5037,\n         3849, 6150, 5975, 9275, 5410,\n         9222, 10592, 12374, 22348, 27508,\n         18361, 39910, 31354, 36074, 20413,\n         69383, 252988, 12457, 48495, 171303,\n         69783;\n\n    Madplotlib plt;\n    plt.title(\"Test 9: Fox News Facebook Shares vs Likes\");\n    plt.xlabel(\"Fox News Shares\");\n    plt.ylabel(\"Fox News Likes\");\n\n    plt.plot(x, y, QColor(169, 206, 0)); // plot green line\n    plt.plot(x, y, QString(\"o\"), QColor(255, 255, 255), 2, QColor(169, 206, 0), 6.5f); // plot markers, linewith=2, markersize=6.5\n    plt.show();\n\n#ifdef SCRSHOT\n    plt.savefig(\"test9.png\");\n#endif\n}\n\n/* Use case that displays Y data twice and hides the labels from X axis.\n * + plot() draws Y data as a thicker red line (linewidth = 4).\n * + plot() draws Y data as scattered with larger colored markers (markersize = 15.0f).\n */\nvoid test10()\n{\n    const double pi = std::acos(-1.0);\n    Eigen::ArrayXf X = Eigen::ArrayXf::LinSpaced(256, 0, 2*pi);\n    Eigen::ArrayXf C = Eigen::cos(X);\n    Eigen::ArrayXf S = Eigen::sin(X);\n\n    Madplotlib plt;\n    plt.title(\"Test 10\");\n    plt.grid(true);\n\n    Eigen::ArrayXf x_ticks(4);\n    x_ticks << pi/2, pi, (3*pi)/2, 2*pi;\n\n    QVector<QString> x_labels;\n    x_labels.push_back(\"\u03c0/2\");\n    x_labels.push_back(\"\u03c0\");\n    x_labels.push_back(\"3\u03c0/2\");\n    x_labels.push_back(\"2\u03c0\");\n\n    // On Qt 7.5, Qt Charts has a bug spacing correctly categories on negative X axis (-3.1, 3.1).\n    // For now, make sure you are using only positive X values to bypass that problem.\n    plt.plot(X, C);\n    plt.plot(X, S, marker=QString(\"--\"));\n    plt.xlim(0, 2*pi);\n    plt.xticks(x_ticks, x_labels);\n    plt.show();\n\n#ifdef SCRSHOT\n    plt.savefig(\"test10.png\");\n#endif\n}\n\nvoid run_test(int id)\n{\n    if (id == 0 || id == 1)\n        test1();\n\n    if (id == 0 || id == 2)\n        test2();\n\n    if (id == 0 || id == 3)\n        test3();\n\n    if (id == 0 || id == 4)\n        test4();\n\n    if (id == 0 || id == 5)\n        test5();\n\n    if (id == 0 || id == 6)\n        test6();\n\n    if (id == 0 || id == 7)\n        test7();\n\n    if (id == 0 || id == 8)\n        test8();\n\n    if (id == 0 || id == 9)\n        test9();\n\n    if (id == 0 || id == 10)\n        test10();\n}\n\nvoid run_test(int begin, int end)\n{\n    for (int i = begin; i <= end; i++)\n        run_test(i);\n}\n\n\nint main(int argc, char* argv[])\n{\n    QApplication app(argc, argv);\n\n    // runtest(0)    - executes all tests.\n    // runtest(5, 9) - executes all tests between 5 and 9.\n    run_test(0);\n\n    qInfo() << \"* Done!\";\n\n    // NOTE:\n    // Creating an object with the default constructor makes the window\n    // block/freeze your program execution upon show().\n    // When the user closes the window, your program continues to run\n    // normally until the next show() is called.\n    // This is how matplotlib behaves!\n    //\n    // However, if you don't want Madplotlib to block you need\n    // to create a Madplotlib object and pass TRUE to the constructor.\n    // This will make Madplotlib behave like a traditional widget.\n    // This is what you need to do if you plan to write custom Qt GUIs\n    // with widgets. Also, don't forget to invoke app.exec().\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "9d14ee838135566445d4aeb140125e972d5f04d4", "size": 12755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_tests.cpp", "max_stars_repo_name": "madplotlib/madplotlib", "max_stars_repo_head_hexsha": "923e55b1ff1bdea070e679f44bdd806c5559f999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 243.0, "max_stars_repo_stars_event_min_datetime": "2017-06-12T16:06:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T04:37:52.000Z", "max_issues_repo_path": "eigen_tests.cpp", "max_issues_repo_name": "eborghi10/madplotlib", "max_issues_repo_head_hexsha": "1924ecec379bda4582d221ce98fc6efbc3268848", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-06-13T15:04:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-16T09:05:14.000Z", "max_forks_repo_path": "eigen_tests.cpp", "max_forks_repo_name": "eborghi10/madplotlib", "max_forks_repo_head_hexsha": "1924ecec379bda4582d221ce98fc6efbc3268848", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T17:19:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T06:37:21.000Z", "avg_line_length": 30.0117647059, "max_line_length": 167, "alphanum_fraction": 0.6149745198, "num_tokens": 3986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5741065703282411}}
{"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": "//  (C) Copyright Gennadiy Rozental 2011-2015.\r\n//  Distributed under the Boost Software License, Version 1.0.\r\n//  (See accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  See http://www.boost.org/libs/test for the library home page.\r\n\r\n\r\n//[example_code\r\n#define BOOST_TEST_MODULE example\r\n#include <boost/test/included/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\nBOOST_AUTO_TEST_CASE( test )\r\n{\r\n  double v1 = 1.23456e-10;\r\n  double v2 = 1.23457e-10;\r\n\r\n  BOOST_CHECK_CLOSE( v1, v2, 0.0001 );\r\n  // Absolute value of difference between these two values is 1e-15. They seems \r\n  // to be very close. But we want to checks that these values differ no more then 0.0001%\r\n  // of their value. And this test will fail at tolerance supplied.\r\n}\r\n//]\r\n", "meta": {"hexsha": "136778f8dcc0e93bd312c27440097e1e640b8623", "size": 818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/test/doc/examples/example42.run-fail.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/test/doc/examples/example42.run-fail.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/test/doc/examples/example42.run-fail.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 32.72, "max_line_length": 91, "alphanum_fraction": 0.7114914425, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5740207738191965}}
{"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 zienkiewiczzhuestimator_test.cc\n * @brief NPDE homework \"ZienkiewiczZhuEstimator\" code\n * @author Philipp Lindenberger\n * @date 25.03.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include <memory>\n// Eigen includes\n#include <gtest/gtest.h>\n\n// Lehrfem++ includes\n#include <lf/assemble/assemble.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <unsupported/Eigen/KroneckerProduct>\n\n#include \"../zienkiewiczzhuestimator.h\"\n\nnamespace ZienkiewiczZhuEstimator::test {\n\n/**\n * @brief test VectorProjectionMatrixProvider implementation\n */\nTEST(ZienkiewiczZhuEstimator, VectorProjectionMatrixProvider) {\n  // Load triangular mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n  // Pointer to scalar FE-space\n  auto fe_space_p =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  Eigen::Matrix2d identity = Eigen::MatrixXd::Identity(2, 2);\n  auto mf_one = lf::mesh::utils::MeshFunctionConstant(1.0);\n  auto mf_zero = lf::mesh::utils::MeshFunctionConstant(0.0);\n\n  // Student solution\n  ZienkiewiczZhuEstimator::VectorProjectionMatrixProvider student_elmat_builder;\n  // Reference solution\n  lf::uscalfe::ReactionDiffusionElementMatrixProvider<double, decltype(mf_zero),\n                                                      decltype(mf_one)>\n      elmat_builder_exact(fe_space_p, mf_zero, mf_one);\n\n  // Loop over all dim-2 entities, compute error\n  for (const auto tria : mesh_p->Entities(0)) {\n    auto student_elem_mat = student_elmat_builder.Eval(*tria);\n    auto elem_mat_scalar_exact = elmat_builder_exact.Eval(*tria);\n    auto elem_mat_exact =\n        Eigen::KroneckerProduct(elem_mat_scalar_exact, identity);\n    double error = (student_elem_mat - elem_mat_exact).norm();\n    EXPECT_LT(error, 1.0e-12);\n  }\n}\n\n/**\n * @brief test GradientProjectionVectorProvider implementation\n */\nTEST(ZienkiewiczZhuEstimator, GradientProjectionVectorProvider) {\n  // Load triangular mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n  // Pointer to scalar FE-space\n  auto fe_space_p =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  // Scalar DOF-Handler\n  auto &dofh = fe_space_p->LocGlobMap();\n\n  // Solution vector 1:\n  auto mu_x = [](Eigen::Vector2d x) -> double { return x[0]; };\n  auto mf_mu_x = lf::mesh::utils::MeshFunctionGlobal(\n      [&mu_x](Eigen::Vector2d x) -> double { return mu_x(x); });\n  auto mu_x_vec = lf::fe::NodalProjection(*fe_space_p, mf_mu_x);\n\n  // Solution vector 2:\n  auto mu_y = [](Eigen::Vector2d x) -> double { return x[1]; };\n  auto mf_mu_y = lf::mesh::utils::MeshFunctionGlobal(\n      [&mu_y](Eigen::Vector2d x) -> double { return mu_y(x); });\n  auto mu_y_vec = lf::fe::NodalProjection(*fe_space_p, mf_mu_y);\n\n  // Retrieve unit triangle from mesh (see documentation of\n  // GenerateHybrid2DTestMesh(3) on LF++)\n  auto unit_tria = mesh_p->EntityByIndex(0, 1);\n\n  // Student solutions\n  ZienkiewiczZhuEstimator::GradientProjectionVectorProvider grad_vec_builder_x(\n      fe_space_p, mu_x_vec);\n  ZienkiewiczZhuEstimator::GradientProjectionVectorProvider grad_vec_builder_y(\n      fe_space_p, mu_y_vec);\n\n  auto unit_tria_grad_x = grad_vec_builder_x.Eval(*unit_tria);\n  auto unit_tria_grad_y = grad_vec_builder_y.Eval(*unit_tria);\n\n  for (int i = 0; i < 6; i += 2) {\n    ASSERT_NEAR(unit_tria_grad_x(i), 0.25, 1.0e-8);\n    ASSERT_NEAR(unit_tria_grad_x(i + 1), 0.0, 1.0e-8);\n    ASSERT_NEAR(unit_tria_grad_y(i), 0.0, 1.0e-8);\n    ASSERT_NEAR(unit_tria_grad_y(i + 1), 0.25, 1.0e-8);\n  }\n}\n\n/**\n * @brief test computeLumpedProjection implementation\n */\nTEST(ZienkiewiczZhuEstimator, computeLumpedProjection) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4);\n  auto fe_space_p =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  // Obtain reference to scalar dofh\n  const lf::assemble::DofHandler &dofh{fe_space_p->LocGlobMap()};\n  // Produce a dof handler for the vector-valued finite element space\n  lf::assemble::UniformFEDofHandler vec_dofh(mesh_p,\n                                             {{lf::base::RefEl::kPoint(), 2},\n                                              {lf::base::RefEl::kSegment(), 0},\n                                              {lf::base::RefEl::kTria(), 0},\n                                              {lf::base::RefEl::kQuad(), 0}});\n\n  // Solution vector 1:\n  auto mu_x = [](Eigen::Vector2d x) -> double { return x[0]; };\n  auto mf_mu_x = lf::mesh::utils::MeshFunctionGlobal(\n      [&mu_x](Eigen::Vector2d x) -> double { return mu_x(x); });\n  auto mu_x_vec = lf::fe::NodalProjection(*fe_space_p, mf_mu_x);\n\n  // Solution vector 2:\n  auto mu_y = [](Eigen::Vector2d x) -> double { return x[1]; };\n  auto mf_mu_y = lf::mesh::utils::MeshFunctionGlobal(\n      [&mu_y](Eigen::Vector2d x) -> double { return mu_y(x); });\n  auto mu_y_vec = lf::fe::NodalProjection(*fe_space_p, mf_mu_y);\n\n  // Student solutions\n  auto sol_x = ZienkiewiczZhuEstimator::computeLumpedProjection(dofh, mu_x_vec,\n                                                                vec_dofh);\n  auto sol_y = ZienkiewiczZhuEstimator::computeLumpedProjection(dofh, mu_y_vec,\n                                                                vec_dofh);\n\n  for (int i = 0; i < sol_x.size(); i += 2) {\n    ASSERT_NEAR(sol_x(i), 1.0, 1.0e-8);\n    ASSERT_NEAR(sol_x(i + 1), 0.0, 1.0e-8);\n    ASSERT_NEAR(sol_y(i), 0.0, 1.0e-8);\n    ASSERT_NEAR(sol_y(i + 1), 1.0, 1.0e-8);\n  }\n}\n\n/**\n * @brief test computeL2Deviation implementation\n */\nTEST(ZienkiewiczZhuEstimator, computeL2Deviation) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4);\n  auto fe_space_p =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  // Obtain reference to scalar dofh\n  const lf::assemble::DofHandler &dofh{fe_space_p->LocGlobMap()};\n  // Produce a dof handler for the vector-valued finite element space\n  lf::assemble::UniformFEDofHandler vec_dofh(mesh_p,\n                                             {{lf::base::RefEl::kPoint(), 2},\n                                              {lf::base::RefEl::kSegment(), 0},\n                                              {lf::base::RefEl::kTria(), 0},\n                                              {lf::base::RefEl::kQuad(), 0}});\n\n  auto mu = ZienkiewiczZhuEstimator::solveBVP(fe_space_p);\n\n  // Assumes computeLumpedProjection works as expected (tested above)\n  auto mu_grad =\n      ZienkiewiczZhuEstimator::computeLumpedProjection(dofh, mu, vec_dofh);\n  // Student solution\n  double error_grad = computeL2Deviation(dofh, mu, vec_dofh, mu_grad);\n\n  ASSERT_NEAR(error_grad, 0.0419009, 1.0e-6);\n}\n\n}  // namespace ZienkiewiczZhuEstimator::test\n", "meta": {"hexsha": "f5fdd821d8ee43f4f8a0aa09fc5c35287a8f19c9", "size": 6750, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ZienkiewiczZhuEstimator/templates/test/zienkiewiczzhuestimator_test.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ZienkiewiczZhuEstimator/templates/test/zienkiewiczzhuestimator_test.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ZienkiewiczZhuEstimator/templates/test/zienkiewiczzhuestimator_test.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 39.0173410405, "max_line_length": 80, "alphanum_fraction": 0.6565925926, "num_tokens": 1968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5740207658230959}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/vector/parameter.hpp>\n#include <boost/numeric/mtl/operation/operators.hpp>\n#include <boost/numeric/mtl/io/test_ostream.hpp>\n\nusing namespace std;\n\n\n\n\nint main()\n{\n    using mtl::io::tout;\n    using mtl::vec::parameters;\n\n    bool with_errors= false;\n\n    mtl::dense_vector<int>                                u(3), v, ref(3);\n    mtl::dense_vector<int, parameters<mtl::row_major> >   ur(3), vr, refr(3);\n\n    u= 1, 2, 3;\n    ur= 1, 2, 3;\n\n    v= u * u;   \n    tout << \"u * u = \" << v << endl;\n\n    vr= ur * ur;   \n    tout << \"ur * ur = \" << vr << endl;\n\n    ref= 1, 4, 9;\n    refr= 1, 4, 9;\n\n    if (v != ref) {\n\tcerr << \"Wrong result in element-wise product (column vectors)\" << endl;\n\twith_errors= true;\n    }\n\n    if (vr != refr) {\n\tcerr << \"Wrong result in element-wise product (row vectors)\" << endl;\n\twith_errors= true;\n    }\n    \n    return with_errors ? 1 : 0;\n}\n", "meta": {"hexsha": "97c813203592309ebc36181b9f5248751354a656", "size": 1470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/vector_element_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/vector_element_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/vector_element_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": 24.5, "max_line_length": 94, "alphanum_fraction": 0.6176870748, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.5740207658230958}}
{"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": "#include \"./include/rsa.h\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <iostream>\n#include <string>\n\nint main(int argc, char const *argv[])\n{\n    RSA::key_generator key_gen(512);\n    auto k1 = key_gen.get_public_key_1();\n    auto k2 = key_gen.get_public_key_2();\n    auto k3 = key_gen.get_private_key();\n\n    std::cout << \"Chave p\u00fablica 1:\\t\" << k1 << std::endl;\n    std::cout << \"Chave p\u00fablica 2:\\t\" << k2 << std::endl;   \n    std::cout << \"Chave privada:\\t\\t\" << k3 << std::endl;\n    \n    RSA::encoder manager;\n    std::string file(\"messages/text.txt\");\n    std::string file1(\"messages/encoded.txt\");\n    std::string file2(\"messages/decoded.txt\");\n    \n    manager.encode(file, file1, k1, k2);\n    manager.decode(file1, file2, k1, k3);\n    \n    return 0;\n}\n", "meta": {"hexsha": "025214f4ad42d41e7aaa657684270449bf042f17", "size": 768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "RafaelGranza/RSA", "max_stars_repo_head_hexsha": "7600c458a5477237b577de24c9b7d60a091d6c92", "max_stars_repo_licenses": ["MIT"], "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": "RafaelGranza/RSA", "max_issues_repo_head_hexsha": "7600c458a5477237b577de24c9b7d60a091d6c92", "max_issues_repo_licenses": ["MIT"], "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": "RafaelGranza/RSA", "max_forks_repo_head_hexsha": "7600c458a5477237b577de24c9b7d60a091d6c92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-17T19:28:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-17T19:28:57.000Z", "avg_line_length": 28.4444444444, "max_line_length": 60, "alphanum_fraction": 0.625, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5738632478028957}}
{"text": "#ifndef TEST_UNIT_TORSTEN_PK_FRIBERG_KARLSSON_MODEL_TEST_FIXTURE\n#define TEST_UNIT_TORSTEN_PK_FRIBERG_KARLSSON_MODEL_TEST_FIXTURE\n\n#include <gtest/gtest.h>\n#include <boost/numeric/odeint.hpp>\n#include <stan/math/rev/fun/pow.hpp>\n#include <stan/math/torsten/pmx_onecpt_model.hpp>\n#include <stan/math/torsten/pmx_ode_model.hpp>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\n\nstruct FribergKarlsson {\n   // parms contains both the PK and the PD parameters.\n   // x contains both the PK and the PD states.\n  template <typename T0, typename T1, typename T2, typename T3>\n  inline\n  Eigen::Matrix<typename stan::return_type_t<T0, T1, T2, T3>, -1, 1>\n  operator()(const T0& t,\n             const Eigen::Matrix<T1, -1, 1>& x,\n             std::ostream* pstream__,\n             const std::vector<T2>& parms,\n             const std::vector<T3>& x_r,\n             const std::vector<int>& x_i) const {\n    using Eigen::Matrix;\n    using Eigen::Dynamic;\n    using scalar = typename stan::return_type_t<T0, T1, T2, T3>;\n\n    // PK variables\n    T2\n      CL = parms[0],\n      Q = parms[1],\n      VC = parms[2],\n      VP = parms[3],\n      ka = parms[4],\n      k10 = CL / VC,\n      k12 = Q / VC,\n      k21 = Q / VP;\n\n    // PD variables\n    T2\n      MTT = parms[5],\n      circ0 = parms[6],\n      gamma = parms[7],\n      alpha = parms[8],\n      ktr = 4 / MTT;\n    typename stan::return_type_t<T1, T2>\n      prol = x[3] + circ0,\n      transit1 = x[4] + circ0,\n      transit2 = x[5] + circ0,\n      transit3 = x[6] + circ0,\n      circ = stan::math::fmax(stan::math::machine_precision(), x[7] + circ0);\n\n    Eigen::Matrix<scalar, -1, 1> dxdt(8);\n    dxdt[0] = -ka * x[0];\n    dxdt[1] = ka * x[0] - (k10 + k12) * x[1] + k21 * x[2];\n    dxdt[2] = k12 * x[1] - k21 * x[2];\n\n    scalar conc = x[1] / VC;\n    scalar Edrug = alpha * conc;\n\n    dxdt[3] = ktr * prol * (((1 - Edrug) * pow((circ0 / circ), gamma)) - 1);\n    dxdt[4] = ktr * (prol - transit1);\n    dxdt[5] = ktr * (transit1 - transit2);\n    dxdt[6] = ktr * (transit2 - transit3);\n    dxdt[7] = ktr * (transit3 - circ);\n\n    return dxdt;\n  }\n};\n\nstruct FribergKarlssonTest : public testing::Test {\n  const FribergKarlsson f;\n  int nCmt;\n  int nt;\n  std::vector<std::vector<double> > theta;\n  std::vector<std::vector<double> > biovar;\n  std::vector<std::vector<double> > tlag;\n  std::vector<double> time;\n  std::vector<double> amt;\n  std::vector<double> rate;\n  std::vector<int> cmt;\n  std::vector<int> evid;\n  std::vector<double> ii;\n  std::vector<int> addl;\n  std::vector<int> ss;\n\n  void SetUp() {\n    // make sure memory's clean before starting each test\n    stan::math::recover_memory();\n  }\n\n  FribergKarlssonTest() :\n    f(),\n    nCmt(8),\n    nt(10),\n    // CL , Q , Vc , Vp , ka , MTT , Circ0 , alpha , gamma\n    theta(1, {10, 15, 35, 105, 2.0, 125, 5, 0.17, 3e-4}),\n    biovar(1, {1, 1, 1, 1, 1, 1, 1, 1}),\n    tlag(1, {0, 0, 0, 0, 0, 0, 0, 0}),\n    time(nt),\n    amt(nt, 0),\n    rate(nt, 0),\n    cmt(nt, 2),\n    evid(nt, 0),\n    ii(nt, 0),\n    addl(nt, 0),\n    ss(nt, 0)\n  {\n    time[0] = 0.0;\n    for(int i = 1; i < nt; i++) time[i] = i * 1.25;\n\n    amt[0] = 80 * 1000.0;\n    cmt[0] = 1;\n    evid[0] = 1;\n    ii[0] = 12;\n\n    SetUp();\n  }\n\n  void resize(int n) {\n    nt = n;\n    time.resize(nt);\n    amt .resize(nt);\n    rate.resize(nt);\n    cmt .resize(nt);\n    evid.resize(nt);\n    ii  .resize(nt);\n    addl.resize(nt);\n    ss  .resize(nt);\n  }\n};\n\n#endif\n", "meta": {"hexsha": "c4cbb7fe9923b224770161cc23b5962077ba659a", "size": 3430, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/pmx_friberg_karlsson_test_fixture.hpp", "max_stars_repo_name": "metrumresearchgroup/torsten_math", "max_stars_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/pmx_friberg_karlsson_test_fixture.hpp", "max_issues_repo_name": "metrumresearchgroup/torsten_math", "max_issues_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-27T23:53:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T23:57:43.000Z", "max_forks_repo_path": "test/unit/pmx_friberg_karlsson_test_fixture.hpp", "max_forks_repo_name": "metrumresearchgroup/torsten_math", "max_forks_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2205882353, "max_line_length": 77, "alphanum_fraction": 0.5618075802, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5738632478028957}}
{"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 * Sha1.cpp\n *\n *  Created on: Nov 25, 2016\n *      Author: victor\n */\n\n#include \"../../algorithms/sha/Sha1.h\"\n\n#include <boost/assert.hpp>\n#include <string>\n#include <iostream>\n\n#include \"../../binary/BinaryString.h\"\n#include \"../../binary/BinaryWord.h\"\n#include \"../../binary/Endianness.h\"\n#include \"../../binary/tools/BinaryStringUtils.h\"\n#include \"../../binary/tools/Utils.h\"\nusing namespace std;\n\n\nstd::string algorithms::Sha1::preprocess_message(const std::string& initial_message) {\n\tstd::string tmp_message;\n\n\t// Check assumption: sizeof(char) = 8\n\tBOOST_ASSERT_MSG(BYTE_TO_BIT_SIZE(sizeof(char)) == 8,\n\t\t\t\"This function expects a char size of 1 byte.\");\n\n\t// -------------------------\n\t// Message preprocessing\n\t// -------------------------\n\tstd::string  message = initial_message;\n\t// Append the bit '1' to the message e.g. by adding 0x80 if message length is a multiple of 8 bits.\n\tmessage += 0x80;\n\n\t// Append 0 \u2264 k < 512 bits '0', such that the resulting message length in bits\n\t// is congruent to \u221264 \u2261 448 (mod 512)\n\tmessage = algorithms::utils::pad_with_character(message, 0x00,\n\t\t\tBIT_TO_BYTE_SIZE(ChunkSizes::CHUNK_BIT_SIZE),\n\t\t\tBIT_TO_BYTE_SIZE(ChunkSizes::LAST_CHUNK_BIT_SIZE));\n\n\t// Append ml, the original message length, as a 64-bit big-endian integer. Thus, the total\n\t// length is a multiple of 512 bits.\n\tmessage += algorithms::utils::length_to_string_64b(BYTE_TO_BIT_SIZE(initial_message.size()));\n\n\treturn message;\n}\n\n\nvoid algorithms::Sha1::word_array_init(unsigned int chunk_id,\n\t\tBinaryString& bin_message, vector<std::uint32_t>& words) {\n\n\tbin_message.get_words_from_chunk(chunk_id, words);\n\twords.resize(80);\n\n\t// Extend the sixteen 32-bit words into eighty 32-bit words:\n\tfor (unsigned int i = 16; i < 80; ++i) {\n\t\twords[i] = algorithms::utils::circular_left_shift<1>(\n\t\t\t\twords[i - 3] ^ words[i - 8] ^ words[i - 14] ^ words[i - 16]);\n\t}\n}\n\nvoid algorithms::Sha1::main_loop(std::uint32_t& h0, std::uint32_t& h1,\n\t\tstd::uint32_t& h2, std::uint32_t& h3, std::uint32_t& h4,\n\t\tconst vector<std::uint32_t>& words) {\n\n\t//TODO: MUST addition be % 2^32?\n\n\tstd::uint32_t a, b, c, d, e, f, k, temp;\n\n\t// Initialize hash value for this chunk:\n\ta = h0;\n\tb = h1;\n\tc = h2;\n\td = h3;\n\te = h4;\n\n\t// Main loop:\n\tfor (unsigned int i = 0; i < 80; ++i){\n\t\tif (i <= 19){\n\t\t\tf = (b & c) | ((~b) & d);\n\t\t\tk = 0x5A827999;\n\t\t}\n\t\telse{\n\t\t\tif (i >= 20 && i <= 39){\n\t\t\t\tf = b ^ c ^ d;\n\t\t\t\tk = 0x6ED9EBA1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif (i>= 40 && i <= 59){\n\t\t\t\t\tf = (b & c) | (b & d) | (c & d);\n\t\t\t\t\tk = 0x8F1BBCDC;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tif (i>= 60 && i <= 79){\n\t\t\t\t\t\tf = b ^ c ^ d;\n\t\t\t\t\t\tk = 0xCA62C1D6;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttemp = algorithms::utils::circular_left_shift<5>(a) + f + e + k + words[i];\n\t\te = d;\n\t\td = c;\n\t\tc = algorithms::utils::circular_left_shift<30>(b);\n\t\tb = a;\n\t\ta = temp;\n\t}\n\t// From https://www.ipa.go.jp/security/rfc/RFC3174EN.html\n\t\t// Better version for parallelization\n\t\t/*unsigned int t;\n\t\tfor (t = 0; t < 20; t++) {\n\t\t\ttemp = SHA1CircularShift(5, a) + ((b & c) | ((~b) & d)) + e + words[t]\n\t\t\t\t\t+ 0x5A827999;\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = SHA1CircularShift(30, b);\n\t\t\tb = a;\n\t\t\ta = temp;\n\t\t}\n\t\tfor (t = 20; t < 40; t++) {\n\t\t\ttemp = SHA1CircularShift(5,a) + (b ^ c ^ d) + e + words[t] + 0x6ED9EBA1;\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = SHA1CircularShift(30, b);\n\t\t\tb = a;\n\t\t\ta = temp;\n\t\t}\n\t\tfor (t = 40; t < 60; t++) {\n\t\t\ttemp = SHA1CircularShift(5, a) + ((b & c) | (b & d) | (c & d)) + e\n\t\t\t\t\t+ words[t] + 0x8F1BBCDC;\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = SHA1CircularShift(30, b);\n\t\t\tb = a;\n\t\t\ta = temp;\n\t\t}\n\t\tfor (t = 60; t < 80; t++) {\n\t\t\ttemp = SHA1CircularShift(5,a) + (b ^ c ^ d) + e + words[t] + 0xCA62C1D6;\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = SHA1CircularShift(30, b);\n\t\t\tb = a;\n\t\t\ta = temp;\n\t\t}*/\n\n\t// Add this chunk's hash to result so far:\n\th0 += a;\n\th1 += b;\n\th2 += c;\n\th3 += d;\n\th4 += e;\n}\n\nstd::string algorithms::Sha1::calculate_hash(const std::string& initial_message) {\n\n\tstd::uint32_t h0 = InitialHashValues::H0;\n\tstd::uint32_t h1 = InitialHashValues::H1;\n\tstd::uint32_t h2 = InitialHashValues::H2;\n\tstd::uint32_t h3 = InitialHashValues::H3;\n\tstd::uint32_t h4 = InitialHashValues::H4;\n\n\tstd::string message = preprocess_message(initial_message);\n\n\t// Process the message in successive 512-bit chunks:\n\t// break message into 512-bit chunks\n\tBinaryString bin_message(message);\n\tunsigned int number_of_chunks = bin_message.get_num_512b_chunks();\n\n\tvector<std::uint32_t> words;\n\tfor(unsigned int chunk_id = 0; chunk_id < number_of_chunks; ++chunk_id){\n\n\t\tword_array_init(chunk_id, bin_message, words);\n\n\t\tmain_loop(h0, h1, h2, h3, h4, words);\n\n\t}\n\n\t// Produce the final hash value (big-endian) as a 160 bit number:\n\tstring hash = BinaryWord(h0, Endianness::BIG).to_string() +\n\t\t\tBinaryWord(h1, Endianness::BIG).to_string() +\n\t\t\tBinaryWord(h2, Endianness::BIG).to_string() +\n\t\t\tBinaryWord(h3, Endianness::BIG).to_string() +\n\t\t\tBinaryWord(h4, Endianness::BIG).to_string();\n\n\treturn hash;\n}\n\n\n", "meta": {"hexsha": "01ff42480a291aee90e8b78ecb11390af736cd52", "size": 4900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/SRP/src/algorithms/sha/Sha1.cpp", "max_stars_repo_name": "victor-gil-sepulveda/SecureRemotePasswordProtocol", "max_stars_repo_head_hexsha": "3a7694e52a73b8e1520061289ee6eeb5f2a1f950", "max_stars_repo_licenses": ["MIT"], "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++/SRP/src/algorithms/sha/Sha1.cpp", "max_issues_repo_name": "victor-gil-sepulveda/SecureRemotePasswordProtocol", "max_issues_repo_head_hexsha": "3a7694e52a73b8e1520061289ee6eeb5f2a1f950", "max_issues_repo_licenses": ["MIT"], "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++/SRP/src/algorithms/sha/Sha1.cpp", "max_forks_repo_name": "victor-gil-sepulveda/SecureRemotePasswordProtocol", "max_forks_repo_head_hexsha": "3a7694e52a73b8e1520061289ee6eeb5f2a1f950", "max_forks_repo_licenses": ["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.7894736842, "max_line_length": 100, "alphanum_fraction": 0.6128571429, "num_tokens": 1661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5737971834932638}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <sstream>\n\n#include <boost/mpl/if.hpp>\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/geometry.hpp>\n\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n\n#include <boost/geometry/algorithms/comparable_distance.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n\n\n#include <boost/geometry/geometries/geometries.hpp>\n\n\ntemplate <typename P>\nvoid test_distance_result()\n{\n    typedef typename bg::default_distance_result<P, P>::type distance_type;\n\n    P p1 = bg::make<P>(0, 0);\n    P p2 = bg::make<P>(3, 0);\n    P p3 = bg::make<P>(0, 4);\n\n    distance_type dr12 = bg::comparable_distance(p1, p2);\n    distance_type dr13 = bg::comparable_distance(p1, p3);\n    distance_type dr23 = bg::comparable_distance(p2, p3);\n\n    BOOST_CHECK_CLOSE(dr12, 9.000, 0.001);\n    BOOST_CHECK_CLOSE(dr13, 16.000, 0.001);\n    BOOST_CHECK_CLOSE(dr23, 25.000, 0.001);\n\n}\n\ntemplate <typename P>\nvoid test_distance_point()\n{\n    P p1;\n    bg::set<0>(p1, 1);\n    bg::set<1>(p1, 1);\n\n    P p2;\n    bg::set<0>(p2, 2);\n    bg::set<1>(p2, 2);\n\n    typename bg::coordinate_type<P>::type d = bg::comparable_distance(p1, p2);\n    BOOST_CHECK_CLOSE(d, 2.0, 0.001);\n}\n\ntemplate <typename P>\nvoid test_distance_segment()\n{\n    typedef typename bg::coordinate_type<P>::type coordinate_type;\n\n    P s1 = bg::make<P>(2, 2);\n    P s2 = bg::make<P>(3, 3);\n\n    // Check points left, right, projected-left, projected-right, on segment\n    P p1 = bg::make<P>(0, 0);\n    P p2 = bg::make<P>(4, 4);\n    P p3 = bg::make<P>(2.4, 2.6);\n    P p4 = bg::make<P>(2.6, 2.4);\n    P p5 = bg::make<P>(2.5, 2.5);\n\n    bg::model::referring_segment<P const> const seg(s1, s2);\n\n    coordinate_type d1 = bg::comparable_distance(p1, seg); BOOST_CHECK_CLOSE(d1, 8.0, 0.001);\n    coordinate_type d2 = bg::comparable_distance(p2, seg); BOOST_CHECK_CLOSE(d2, 2.0, 0.001);\n    coordinate_type d3 = bg::comparable_distance(p3, seg); BOOST_CHECK_CLOSE(d3, 0.02, 0.001);\n    coordinate_type d4 = bg::comparable_distance(p4, seg); BOOST_CHECK_CLOSE(d4, 0.02, 0.001);\n    coordinate_type d5 = bg::comparable_distance(p5, seg); BOOST_CHECK_CLOSE(d5, 0.0, 0.001);\n\n    // Reverse case\n    coordinate_type dr1 = bg::comparable_distance(seg, p1); BOOST_CHECK_CLOSE(dr1, d1, 0.001);\n    coordinate_type dr2 = bg::comparable_distance(seg, p2); BOOST_CHECK_CLOSE(dr2, d2, 0.001);\n}\n\ntemplate <typename P>\nvoid test_distance_linestring()\n{\n    bg::model::linestring<P> points;\n    points.push_back(bg::make<P>(1, 1));\n    points.push_back(bg::make<P>(3, 3));\n\n    P p = bg::make<P>(2, 1);\n\n    typename bg::coordinate_type<P>::type d = bg::comparable_distance(p, points);\n    BOOST_CHECK_CLOSE(d, 0.5, 0.001);\n\n    p = bg::make<P>(5, 5);\n    d = bg::comparable_distance(p, points);\n    BOOST_CHECK_CLOSE(d, 8.0, 0.001);\n\n\n    bg::model::linestring<P> line;\n    line.push_back(bg::make<P>(1,1));\n    line.push_back(bg::make<P>(2,2));\n    line.push_back(bg::make<P>(3,3));\n\n    p = bg::make<P>(5, 5);\n\n    d = bg::comparable_distance(p, line);\n    BOOST_CHECK_CLOSE(d, 8.0, 0.001);\n\n    // Reverse case\n    d = bg::comparable_distance(line, p);\n    BOOST_CHECK_CLOSE(d, 8.0, 0.001);\n}\n\ntemplate <typename P>\nvoid test_all()\n{\n    test_distance_result<P>();\n    test_distance_point<P>();\n    test_distance_segment<P>();\n    test_distance_linestring<P>();\n}\n\nint test_main(int, char* [])\n{\n    //test_all<bg::model::d2::point_xy<int> >();\n    test_all<bg::model::d2::point_xy<float> >();\n    test_all<bg::model::d2::point_xy<double> >();\n\n#ifdef HAVE_TTMATH\n    test_all<bg::model::d2::point_xy<ttmath_big> >();\n#endif\n    return 0;\n}\n", "meta": {"hexsha": "294321c4f8aa776c729aeabae0f22c8cdf273e01", "size": 4223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/algorithms/comparable_distance.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "libs/geometry/test/algorithms/comparable_distance.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "libs/geometry/test/algorithms/comparable_distance.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 28.7278911565, "max_line_length": 94, "alphanum_fraction": 0.6680085247, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5737971736513235}}
{"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": "#pragma once\n#include <ros/ros.h>\n#include <Eigen/Dense>\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/Imu.h>\n#include <tf/transform_datatypes.h>\n\nnamespace Turtlebot\n{\n\nclass ExtendedKalmanFilter\n{\npublic:\n    ExtendedKalmanFilter(ros::NodeHandle &nh, ros::NodeHandle &pnh);\n    ~ExtendedKalmanFilter() = default;\n\nprivate:\n\n    void odomCallback(const nav_msgs::Odometry::ConstPtr &msg);\n    void imuCallback(const sensor_msgs::Imu::ConstPtr &msg);\n\n    void initializeFilter(ros::NodeHandle &pnh);\n    void filterOdom();\n    const Eigen::MatrixXf calcG();\n    const Eigen::MatrixXf calcCovarianceBar(const Eigen::MatrixXf &G);\n    const Eigen::MatrixXf calcUBar();\n    const Eigen::MatrixXf calczBar(const Eigen::MatrixXf &u_);\n    const Eigen::MatrixXf calcH(const Eigen::MatrixXf &u_);\n    const Eigen::MatrixXf calcKalmanGain(const Eigen::MatrixXf &cov_, const Eigen::MatrixXf &H);\n    const Eigen::MatrixXf calcU(const Eigen::MatrixXf &u_, const Eigen::MatrixXf &K);\n    void calcCovariance(const Eigen::MatrixXf & cov_, const Eigen::MatrixXf &H, const Eigen::MatrixXf &K);\n\n    void integrateIMUToOdom();\n    void setz();\n    void pubOdom(const Eigen::MatrixXf &u);\n\n    ros::Subscriber m_odom_sub;\n    ros::Subscriber m_imu_sub;\n    ros::Publisher m_odom_pub;\n\n    nav_msgs::Odometry m_odom_filtered;\n\n    nav_msgs::Odometry::ConstPtr m_odom;\n    Eigen::MatrixXf m_z;\n    nav_msgs::Odometry::ConstPtr m_prev_odom;\n    sensor_msgs::Imu::ConstPtr m_imu;\n    sensor_msgs::Imu m_imu_at_odom;\n    sensor_msgs::Imu m_imu_at_last_odom;\n    sensor_msgs::Imu::ConstPtr m_prev_imu;\n\n    Eigen::MatrixXf m_covariance;\n    Eigen::MatrixXf m_imu_covariance;\n    Eigen::MatrixXf m_odom_covariance;\n\n    bool m_have_odom = false;\n    bool m_have_imu = false;\n\n    bool m_compensate;\n\n\n};\n\n}\n", "meta": {"hexsha": "b3e093d0a10ae82f4655b739db4c9bf738a14ebd", "size": 1792, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/odom_ekf/include/odom_ekf/extended_kalman_filter.hpp", "max_stars_repo_name": "wpi-arn-spring-2019/Turtlebot-3-Navigation", "max_stars_repo_head_hexsha": "c02dbe75de2d4f2fc31d6c2f4873d56f0927a286", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/odom_ekf/include/odom_ekf/extended_kalman_filter.hpp", "max_issues_repo_name": "wpi-arn-spring-2019/Turtlebot-3-Navigation", "max_issues_repo_head_hexsha": "c02dbe75de2d4f2fc31d6c2f4873d56f0927a286", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/odom_ekf/include/odom_ekf/extended_kalman_filter.hpp", "max_forks_repo_name": "wpi-arn-spring-2019/Turtlebot-3-Navigation", "max_forks_repo_head_hexsha": "c02dbe75de2d4f2fc31d6c2f4873d56f0927a286", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-07-06T04:04:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-17T01:46:34.000Z", "avg_line_length": 28.0, "max_line_length": 106, "alphanum_fraction": 0.7220982143, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5737911413348917}}
{"text": "#include \"principal_curvatures_can.hpp\"\n#include <Eigen/Dense>\n\nvoid PrincipalCurvaturesEstimationCAN::compute(\n  PointCloudOut &output) {\n  // From: Curvature Estimation of 3D Point Cloud Surfaces Through the Fitting of Normal Section Curvatures (Zhang et. al. 2008)\n  output.resize(this->input_->size());\n  std::vector<int> neighbor_ids;\n  std::vector<float> sq_distances;\n  Eigen::Vector3f x = (Eigen::Vector3f() << 1, 0, 0).finished();\n  Eigen::Vector3f z = (Eigen::Vector3f() << 0, 0, 1).finished();\n  Eigen::Vector3f N, p, q, Q, n, mu, max_eigenvector;\n  Eigen::Matrix3f R;\n  Eigen::MatrixXf M;\n  Eigen::VectorXf r;\n  Eigen::Matrix2f W;\n  Eigen::EigenSolver<Eigen::Matrix2f> eigen_solver;\n  Eigen::Vector2f::Index max_ind;\n  Eigen::Vector2f eigenvalues;\n  float nxy, k, theta;\n  int jn, j, row_ind;\n  for (int i=0; i<this->input_->size(); i++) {\n    p = Eigen::Vector3f::Map(this->input_.get()->points[i].data);\n    N = Eigen::Vector3f::Map(this->normals_.get()->points[i].data_n);\n    R = (2 * ((N + z) * (N + z).transpose()) / ((N + z).transpose() * (N + z))) - Eigen::Matrix3f::Identity(); // https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d\n    if(this->tree_->radiusSearch(this->input_.get()->points[i], this->search_radius_, neighbor_ids, sq_distances) > 2) {\n      M.resize(neighbor_ids.size() - 1, 3);\n      r.resize(neighbor_ids.size() - 1); // Subtracting one because we skip the search point.\n      row_ind = 0;\n      for(j=1; j<neighbor_ids.size(); j++) {\n        jn = neighbor_ids[j];\n        q = R * (Eigen::Vector3f::Map(this->input_.get()->points[jn].data) - p);\n        Q << q.head<2>(), 0;\n        n = R * Eigen::Vector3f::Map(this->normals_.get()->points[jn].data_n);\n        nxy = (q(0) * n(0) + q(1) * n(1)) / sqrt(pow(q(0), 2) + pow(q(1), 2));\n        k = -nxy / sqrt((pow(nxy, 2) + pow(n(2), 2)) * (pow(q(0), 2) + pow(q(1), 2)));\n        theta = acos(x.dot(Q) / (x.norm() * Q.norm()));\n        if(!isnan(k)) {\n          M(row_ind, 0) = pow(cos(theta), 2);\n          M(row_ind, 1) = 2 * cos(theta) * sin(theta);\n          M(row_ind, 2) = pow(sin(theta), 2);\n          r(row_ind) = k;\n          ++row_ind;\n        } else {\n          M.resize(M.rows() - 1, 3);\n          r.resize(r.rows() - 1);\n        }\n      }\n      mu = M.colPivHouseholderQr().solve(r);\n      if(!isnan(mu(0))) {\n        W << mu(0), mu(1), mu(1), mu(2);\n        eigen_solver.compute(W, true);\n        eigenvalues = eigen_solver.eigenvalues().real();\n        output[i].pc1 = eigenvalues.maxCoeff(&max_ind);\n        output[i].pc2 = eigenvalues.minCoeff();\n        max_eigenvector = R.transpose() * (Eigen::Vector3f() << eigen_solver.eigenvectors().col(max_ind).real(), 0).finished();\n        output[i].principal_curvature_x = max_eigenvector(0);\n        output[i].principal_curvature_y = max_eigenvector(1);\n        output[i].principal_curvature_z = max_eigenvector(2);\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "32f6e97545d4c363760520f5204247968418a601", "size": 2946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/principal_curvatures_can.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": "src/principal_curvatures_can.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": "src/principal_curvatures_can.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": 46.03125, "max_line_length": 223, "alphanum_fraction": 0.5923285811, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5737911361356853}}
{"text": "/***********************************************************************\nThis file is part of the librjmcmc project source files.\n\nCopyright : Institut Geographique National (2008-2012)\nContributors : Mathieu Br\u00e9dif, Olivier Tournaire, Didier Boldo\nemail : librjmcmc@ign.fr\n\nThis software is a generic C++ library for stochastic optimization.\n\nThis software is governed by the CeCILL license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty and the software's author, the holder of the\neconomic rights, and the successive licensors have only limited liability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading, using, modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean that it is complicated to manipulate, and that also\ntherefore means that it is reserved for developers and experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and, more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n\n***********************************************************************/\n\n#ifndef RJMCMC_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 2012 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include \"test.hpp\"\n\nusing Integer = boost::multiprecision::cpp_int;\n\nvoid check_sqrt(const Integer& s, const Integer& r, const Integer& v) {\n   BOOST_CHECK_EQUAL(s * s + r, v);\n   BOOST_CHECK_GE(r, Integer(0));\n   BOOST_CHECK_LE(s * s, v);\n   BOOST_CHECK_GT((s + 1) * (s + 1), v);\n}\n\ntemplate<typename I>\nvoid check(const I& v) {\n   I r;\n   I s = boost::multiprecision::sqrt(v, r);\n   check_sqrt(Integer(s), Integer(r), Integer(v));\n}\n\nvoid check_types(const Integer& v) {\n   using namespace boost::multiprecision;\n   size_t bits = 0;\n   if (v > 0) {\n      bits = msb(v);\n   }\n   if (bits < 32) {\n      check(static_cast<uint32_t>(v));\n   }\n   if (bits < 64) {\n      check(static_cast<uint64_t>(v));\n   }\n   if (bits < 128) {\n      check(uint128_t(v));\n   }\n   if (bits < 256) {\n      check(uint256_t(v));\n   }\n   if (bits < 512) {\n      check(uint512_t(v));\n   }\n   check(v);\n}\n\nvoid check_near(const Integer& v) {\n   check_types(v);\n   for (size_t j = 0; j < 8; j++) {\n      check_types(v - Integer(1 << j));\n      check_types(v - Integer(1 << j) - 1);\n      check_types(v - Integer(1 << j) + 1);\n      check_types(v + Integer(1 << j));\n      check_types(v + Integer(1 << j) - 1);\n      check_types(v + Integer(1 << j) + 1);\n   }\n}\n\nvoid test_first() {\n   for (size_t i = 0; i < (1 << 16); i++) {\n      check_types(Integer(i));\n   }\n}\n\nvoid test_perfect() {\n   for (size_t i = 256; i < (1 << 14); i++) {\n      check_near(Integer(i) * Integer(i));\n   }\n}\n\nvoid test_powers() {\n   for (size_t i = 24; i < 2048; i++) {\n      check_near(Integer(i) << i);\n   }\n}\n\nvoid test_big() {\n   for (size_t bits = 128; bits <= 2048; bits *= 2) {\n      Integer i = Integer(1) << bits;\n      Integer s = (i >> 8);\n      Integer step = (i - s) / (1 << 8);\n      for (Integer j = s; j <= i; j += step) {\n         check_near(j);\n      }\n   }\n}\n\nint main()\n{\n   using namespace boost::multiprecision;\n\n   test_first();\n   test_perfect();\n   test_powers();\n   test_big();\n\n   return boost::report_errors();\n}\n", "meta": {"hexsha": "fcd79983ca014bb992d5607b5d618087c29b31ff", "size": 2287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/multiprecision/test/test_int_sqrt.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/multiprecision/test/test_int_sqrt.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "console/src/boost_1_78_0/libs/multiprecision/test/test_int_sqrt.cpp", "max_forks_repo_name": "vany152/FilesHash", "max_forks_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 22.6435643564, "max_line_length": 71, "alphanum_fraction": 0.5478793179, "num_tokens": 698, "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 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of rbf_kernel class.\n */\n#include \"num_collect/interp/kernel/rbf_kernel.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\n#include \"num_collect/interp/kernel/euclidean_distance.h\"\n#include \"num_collect/interp/kernel/gaussian_rbf.h\"\n\nTEST_CASE(\"num_collect::interp::kernel::rbf_kernel\") {\n    using num_collect::interp::kernel::euclidean_distance;\n    using num_collect::interp::kernel::gaussian_rbf;\n    using num_collect::interp::kernel::rbf_kernel;\n\n    SECTION(\"calculate kernel\") {\n        const auto kernel = rbf_kernel<euclidean_distance<Eigen::Vector3d>,\n            gaussian_rbf<double>>();\n\n        const auto var1 = Eigen::Vector3d(1.234, 2.345, 3.456);\n        const auto var2 = Eigen::Vector3d(1.357, 2.468, 3.579);\n        const double expected = std::exp(-(var1 - var2).squaredNorm());\n        REQUIRE_THAT(kernel(var1, var2), Catch::Matchers::WithinRel(expected));\n    }\n\n    SECTION(\"set length parameter\") {\n        auto kernel = rbf_kernel<euclidean_distance<Eigen::Vector3d>,\n            gaussian_rbf<double>>();\n\n        constexpr double len_param = 0.1;\n        kernel.len_param(len_param);\n        REQUIRE_THAT(kernel.len_param(), Catch::Matchers::WithinRel(len_param));\n\n        const auto var1 = Eigen::Vector3d(1.234, 2.345, 3.456);\n        const auto var2 = Eigen::Vector3d(1.357, 2.468, 3.579);\n        const double expected =\n            std::exp(-(var1 - var2).squaredNorm() / (len_param * len_param));\n        REQUIRE_THAT(kernel(var1, var2), Catch::Matchers::WithinRel(expected));\n    }\n\n    SECTION(\"set length parameter via kernel parameter\") {\n        auto kernel = rbf_kernel<euclidean_distance<Eigen::Vector3d>,\n            gaussian_rbf<double>>();\n\n        constexpr double len_param = 0.1;\n        kernel.kernel_param(std::log10(len_param));\n        REQUIRE_THAT(kernel.kernel_param(),\n            Catch::Matchers::WithinRel(std::log10(len_param)));\n\n        const auto var1 = Eigen::Vector3d(1.234, 2.345, 3.456);\n        const auto var2 = Eigen::Vector3d(1.357, 2.468, 3.579);\n        const double expected =\n            std::exp(-(var1 - var2).squaredNorm() / (len_param * len_param));\n        REQUIRE_THAT(kernel(var1, var2), Catch::Matchers::WithinRel(expected));\n    }\n\n    SECTION(\"call kernel_param_search_region\") {\n        const auto kernel = rbf_kernel<euclidean_distance<Eigen::Vector3d>,\n            gaussian_rbf<double>>();\n\n        const auto list = std::vector<Eigen::Vector3d,\n            Eigen::aligned_allocator<Eigen::Vector3d>>{\n            Eigen::Vector3d(1.234, 2.345, 3.456),\n            Eigen::Vector3d(1.357, 2.468, 3.579)};\n        const auto [lower, upper] = kernel.kernel_param_search_region(list);\n        REQUIRE(lower < upper);\n    }\n\n    SECTION(\"call kernel_param_search_region with only one variable\") {\n        const auto kernel = rbf_kernel<euclidean_distance<Eigen::Vector3d>,\n            gaussian_rbf<double>>();\n\n        const auto list = std::vector<Eigen::Vector3d,\n            Eigen::aligned_allocator<Eigen::Vector3d>>{\n            Eigen::Vector3d(1.234, 2.345, 3.456)};\n        REQUIRE_THROWS((void)kernel.kernel_param_search_region(list));\n    }\n\n    SECTION(\"call kernel_param_search_region without variable\") {\n        const auto kernel = rbf_kernel<euclidean_distance<Eigen::Vector3d>,\n            gaussian_rbf<double>>();\n\n        const auto list = std::vector<Eigen::Vector3d,\n            Eigen::aligned_allocator<Eigen::Vector3d>>{};\n        REQUIRE_THROWS((void)kernel.kernel_param_search_region(list));\n    }\n}\n", "meta": {"hexsha": "b792fad1650535d1942d72b8ce175dc87463424d", "size": 4219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/interp/kernel/rbf_kernel_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/units/interp/kernel/rbf_kernel_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/units/interp/kernel/rbf_kernel_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8018867925, "max_line_length": 80, "alphanum_fraction": 0.6679307893, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5737441396481449}}
{"text": "/*\n* Copyright 2019 \u00a9 Centre Interdisciplinaire de d\u00e9veloppement en Cartographie des Oc\u00e9ans (CIDCO), Tous droits r\u00e9serv\u00e9s\n*/\n\n#ifndef GEOREFERENCING_HPP\n#define GEOREFERENCING_HPP\n\n#include <Eigen/Dense>\n#include \"math/CoordinateTransform.hpp\"\n#include \"Raytracing.hpp\"\n\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": "#include <iostream>\n#include <armadillo>\n\n#ifndef MLMATH\n#define MLMATH\n\n#include \"MLMath.h\"\n\n#endif\n\n#ifndef PLOTTER\n#define PLOTTER\n\n#include \"plot.h\"\n\n#endif\n\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char *argv[])\n{\n\n\n  // for(int i=0; i<argc; i++){\n  //   cout << argv[i] << endl;\n  // }\n\n  if(argc > 1){\n    cout << \"param: \" << argv[1] << endl;\n    string param_1 = argv[1];\n    if(param_1 == \"test\"){\n      cout << \"running all tests\" << endl;\n      cout << \"------------------------------\" << endl;\n    }\n  }\n\n\n  // if(test == \"test\"){\n  //   cout << \"testing: \" << test << endl;\n  // }else{\n  //   cout << \"not testing: \" << test << endl;\n  // }\n\n\n  vec identity, input;\n  mat hypotheses, inputMatrix;\n\n  //the input values in single value calculations\n  // input << 2104 << 1416 << 1534 << 852;\n\n  //identity matrix for input\n  // identity << 1 << 1 << 1 << 1;\n\n  //join identity matrix to input values\n  // inputMatrix = join_rows(identity,input);\n  inputMatrix.load(\"input.txt\", raw_ascii);\n\n  //load hypothesis values\n  hypotheses.load(\"hypotheses.txt\", raw_ascii);\n\n  //create MLMath object with inputmatrix, and hypotheses\n  MLMath<mat> math(inputMatrix,hypotheses);\n\n  //calculate input matrix times hypotheses matrix\n  math.linearMultiply();\n\n  //demo_3d();\n\n\n  //callthis();\n  //return 0;\n\n\n}\n", "meta": {"hexsha": "f8380bdb7e6966c8e3cb0b1acb937e65c60277de", "size": 1333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ML.cpp", "max_stars_repo_name": "Jovonni/RealTimeMLLib", "max_stars_repo_head_hexsha": "2155c80cafbee273c04a3e6c30d6ac4b425b7968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-03-15T16:50:26.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-06T01:54:05.000Z", "max_issues_repo_path": "ML.cpp", "max_issues_repo_name": "Jovonni/RealTimeMLLib", "max_issues_repo_head_hexsha": "2155c80cafbee273c04a3e6c30d6ac4b425b7968", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ML.cpp", "max_forks_repo_name": "Jovonni/RealTimeMLLib", "max_forks_repo_head_hexsha": "2155c80cafbee273c04a3e6c30d6ac4b425b7968", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5394736842, "max_line_length": 57, "alphanum_fraction": 0.5918979745, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5737095926086917}}
{"text": "// Copyright (c) Dewetron 2017\n#include \"otfft.h\"\n\n#undef VALGRIND_MEM_LEAK_DETECTION\n\n#include <boost/test/unit_test.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <vector>\n\nnamespace\n{\n    /**\n     * Test that spectrum of a delta signal is constant.\n     */\n    template <std::size_t SIZE>\n    void deltaSpectrumTest()\n    {\n        // delta signal: 1, 0, 0, 0...\n        double testArray[SIZE] = {0};\n        testArray[0] = 1;\n\n        std::vector<OTFFT::complex_t> spectrum(SIZE);\n        {\n            auto fft = OTFFT::Factory::createRealFFT(static_cast<int>(SIZE));\n            OTFFT::double_vector fft_in{testArray};\n            OTFFT::complex_vector fft_out{spectrum.data()};\n            fft->fwd0(fft_in, fft_out);\n        }\n\n        double absSpectrum[SIZE] = {0};\n        std::transform(std::begin(spectrum), std::end(spectrum), absSpectrum, [] (OTFFT::complex_t x) {\n            return std::sqrt(OTFFT::norm(x));\n        });\n\n        double expected[SIZE];\n        std::fill_n(expected, SIZE, 1.0);\n        for (std::size_t idx{0}; idx < SIZE / 2; ++idx)\n        {\n            if (std::fabs(expected[idx]) < 1e-10)\n            {\n                BOOST_CHECK_SMALL(absSpectrum[idx], 1e-8);\n            }\n            else\n            {\n                BOOST_CHECK_CLOSE(expected[idx], absSpectrum[idx], .1);\n            }\n        }\n    }\n\n    /**\n     * Test that spectrum of a constant signal is a scaled delta.\n     */\n    template <std::size_t SIZE>\n    void constSpectrumTest()\n    {\n        double testArray[SIZE];\n        std::fill_n(testArray, SIZE, 1.0);\n\n        std::vector<OTFFT::complex_t> spectrum(SIZE);\n        {\n            auto fft = OTFFT::Factory::createRealFFT(static_cast<int>(SIZE));\n            OTFFT::double_vector fft_in{testArray};\n            OTFFT::complex_vector fft_out{spectrum.data()};\n            fft->fwd0(fft_in, fft_out);\n        }\n\n        double absSpectrum[SIZE] = {0};\n        std::transform(std::begin(spectrum), std::end(spectrum), absSpectrum, [] (OTFFT::complex_t x) {\n            return std::sqrt(OTFFT::norm(x));\n        });\n\n        // expecting a delta scaled by SIZE\n        double expected[SIZE] = {0};\n        expected[0] = SIZE * 1.0;\n        for (std::size_t idx{0}; idx < SIZE / 2; ++idx)\n        {\n            if (std::fabs(expected[idx]) < 1e-10)\n            {\n                BOOST_CHECK_SMALL(absSpectrum[idx], 1e-8);\n            }\n            else\n            {\n                BOOST_CHECK_CLOSE(expected[idx], absSpectrum[idx], .1);\n            }\n        }\n    }\n\n    /**\n     * Test that inverse of a delta spectrum is a constant signal.\n     */\n    template <std::size_t SIZE>\n    void deltaInverseTest()\n    {\n        std::vector<OTFFT::complex_t> spectrum(SIZE, 0);\n        spectrum[0] = SIZE * 1.0;\n        std::vector<double> output(SIZE);\n        {\n            auto fft = OTFFT::Factory::createRealFFT(static_cast<int>(SIZE));\n            OTFFT::complex_vector fft_in{spectrum.data()};\n            OTFFT::double_vector fft_out{output.data()};\n            fft->invn(fft_in, fft_out);\n        }\n\n        double expected[SIZE];\n        std::fill_n(expected, SIZE, 1.0);\n        for (std::size_t idx{0}; idx < SIZE / 2; ++idx)\n        {\n            if (std::fabs(expected[idx]) < 1e-10)\n            {\n                BOOST_CHECK_SMALL(output[idx], 1e-8);\n            }\n            else\n            {\n                BOOST_CHECK_CLOSE(expected[idx], output[idx], .1);\n            }\n        }\n    }\n\n    /**\n     * Test that inverse of a constant spectrum is a delta signal.\n     */\n    template <std::size_t SIZE>\n    void constInverseTest()\n    {\n        std::vector<OTFFT::complex_t> spectrum(SIZE, 1.0);\n        std::vector<double> output(SIZE);\n        {\n            auto fft = OTFFT::Factory::createRealFFT(static_cast<int>(SIZE));\n            OTFFT::complex_vector fft_in{spectrum.data()};\n            OTFFT::double_vector fft_out{output.data()};\n            fft->invn(fft_in, fft_out);\n        }\n\n        double expected[SIZE] = {0};\n        expected[0] = 1.0;\n        for (std::size_t idx{0}; idx < SIZE / 2; ++idx)\n        {\n            if (std::fabs(expected[idx]) < 1e-10)\n            {\n                BOOST_CHECK_SMALL(output[idx], 1e-8);\n            }\n            else\n            {\n                BOOST_CHECK_CLOSE(expected[idx], output[idx], .1);\n            }\n        }\n    }\n\n    /**\n     * Test that IFFT(FFT(x)) == x.\n     */\n    template <std::size_t SIZE>\n    void identityTest()\n    {\n        std::vector<double> testArray(SIZE);\n        std::fill_n(testArray.begin(), SIZE, 1.0);\n\n        std::vector<OTFFT::complex_t> spectrum(SIZE);\n        {\n            auto fft = OTFFT::Factory::createRealFFT(static_cast<int>(SIZE));\n            OTFFT::double_vector fft_in{testArray.data()};\n            OTFFT::complex_vector fft_out{spectrum.data()};\n            fft->fwd(fft_in, fft_out);\n        }\n\n        std::vector<double> output(SIZE);\n        {\n            auto fft = OTFFT::Factory::createRealFFT(static_cast<int>(SIZE));\n            OTFFT::complex_vector fft_in{spectrum.data()};\n            OTFFT::double_vector fft_out{output.data()};\n            fft->inv(fft_in, fft_out);\n        }\n\n        for (std::size_t idx{0}; idx < SIZE / 2; ++idx)\n        {\n            BOOST_CHECK_CLOSE(testArray[idx], output[idx], .1);\n        }\n    }\n\n    void fftUtilize(std::size_t fft_size, OTFFT::TransformationType fft_type)\n    {\n        switch (fft_type)\n        {\n        case OTFFT::TransformationType::TRANSFORM_FFT_REAL:\n            {\n                std::vector<double> workspace_real(fft_size, 1.0);\n                std::vector<OTFFT::complex_t> workspace_complex(fft_size);\n                {\n                    auto fft = OTFFT::Factory::createRealFFT(static_cast<int>(fft_size));\n                    OTFFT::double_vector fft_in{workspace_real.data()};\n                    OTFFT::complex_vector fft_out{workspace_complex.data()};\n                    fft->fwd(fft_in, fft_out);\n                }\n\n                {\n                    auto fft = OTFFT::Factory::createRealFFT(static_cast<int>(fft_size));\n                    OTFFT::complex_vector fft_in{workspace_complex.data()};\n                    OTFFT::double_vector fft_out{workspace_real.data()};\n                    fft->inv(fft_in, fft_out);\n                }\n            }\n            break;\n        case OTFFT::TransformationType::TRANSFORM_FFT_COMPLEX:\n            {\n                std::vector<OTFFT::complex_t> workspace(fft_size, OTFFT::complex_t(1.0, 1.0));\n                {\n                    auto fft = OTFFT::Factory::createComplexFFT(static_cast<int>(fft_size));\n                    OTFFT::complex_vector workspace_ptr{workspace.data()};\n                    fft->fwd(workspace_ptr);\n                }\n\n                {\n                    auto fft = OTFFT::Factory::createComplexFFT(static_cast<int>(fft_size));\n                    OTFFT::complex_vector workspace_ptr{workspace.data()};\n                    fft->inv(workspace_ptr);\n                }\n            }\n            break;\n        case OTFFT::TransformationType::TRANSFORM_DCT:\n            {\n                std::vector<double> workspace(fft_size, 1.0);\n                {\n                    auto fft = OTFFT::Factory::createDCT(static_cast<int>(fft_size));\n                    OTFFT::double_vector workspace_ptr{workspace.data()};\n                    fft->fwd(workspace_ptr);\n                }\n\n                {\n                    auto fft = OTFFT::Factory::createDCT(static_cast<int>(fft_size));\n                    OTFFT::double_vector workspace_ptr{workspace.data()};\n                    fft->inv(workspace_ptr);\n                }\n            }\n            break;\n        case OTFFT::TransformationType::TRANSFORM_BLUESTEIN:\n            {\n                std::vector<OTFFT::complex_t> workspace(fft_size, OTFFT::complex_t(1.0, 1.0));\n                {\n                    auto fft = OTFFT::Factory::createBluesteinFFT(static_cast<int>(fft_size));\n                    OTFFT::complex_vector workspace_ptr{workspace.data()};\n                    fft->fwd(workspace_ptr);\n                }\n\n                {\n                    auto fft = OTFFT::Factory::createBluesteinFFT(static_cast<int>(fft_size));\n                    OTFFT::complex_vector workspace_ptr{workspace.data()};\n                    fft->inv(workspace_ptr);\n                }\n            }\n            break;\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE(otfft_transform_test)\n\nBOOST_AUTO_TEST_CASE(TestDeltaSpectrum)\n{\n    deltaSpectrumTest<8>();\n    deltaSpectrumTest<16>();\n    deltaSpectrumTest<256>();\n    deltaSpectrumTest<512>();\n    deltaSpectrumTest<1024>();\n    deltaSpectrumTest<8192>();\n    deltaSpectrumTest<16384>();\n}\n\nBOOST_AUTO_TEST_CASE(TestConstSpectrum)\n{\n    constSpectrumTest<8>();\n    constSpectrumTest<16>();\n    constSpectrumTest<256>();\n    constSpectrumTest<512>();\n    constSpectrumTest<1024>();\n    constSpectrumTest<8192>();\n    constSpectrumTest<16384>();\n}\n\nBOOST_AUTO_TEST_CASE(TestDeltaInverse)\n{\n    deltaInverseTest<8>();\n    deltaInverseTest<16>();\n    deltaInverseTest<256>();\n    deltaInverseTest<512>();\n    deltaInverseTest<1024>();\n    deltaInverseTest<8192>();\n    deltaInverseTest<16384>();\n}\n\nBOOST_AUTO_TEST_CASE(TestConstInverse)\n{\n    constInverseTest<8>();\n    constInverseTest<16>();\n    constInverseTest<256>();\n    constInverseTest<512>();\n    constInverseTest<1024>();\n    constInverseTest<8192>();\n    constInverseTest<16384>();\n}\n\nBOOST_AUTO_TEST_CASE(TestIdentity)\n{\n    identityTest<8>();\n    identityTest<16>();\n    identityTest<256>();\n    identityTest<512>();\n    identityTest<1024>();\n    identityTest<8192>();\n    identityTest<16384>();\n}\n\n#ifdef VALGRIND_MEM_LEAK_DETECTION\nBOOST_AUTO_TEST_CASE(TestValgrind)\n{\n    const std::size_t N = static_cast<std::size_t>(std::pow(2, 24));\n\n    for (std::size_t n = 8; n < N;)\n    {\n        fftUtilize(n, OTFFT::TransformationType::TRANSFORM_FFT_COMPLEX);\n        fftUtilize(n, OTFFT::TransformationType::TRANSFORM_BLUESTEIN);\n\n        if ((n & 1) == 0)\n        {\n            fftUtilize(n, OTFFT::TransformationType::TRANSFORM_FFT_REAL);\n            fftUtilize(n, OTFFT::TransformationType::TRANSFORM_DCT);\n        }\n\n        const std::size_t log_n = static_cast<std::size_t>(std::log2(n));\n        n += static_cast<std::size_t>(std::ceil(std::pow(log_n, std::sqrt(log_n))));\n    }\n\n    BOOST_CHECK(true);\n}\n#endif\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "90ded1a2a6a84f00ffb3f15f176c928ad8992f08", "size": 10462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/otfft_transform_test.cpp", "max_stars_repo_name": "24icewolf42/otfft", "max_stars_repo_head_hexsha": "6069f7017043af06f556a275662a465a56111c42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-24T22:46:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T00:57:59.000Z", "max_issues_repo_path": "unit_tests/otfft_transform_test.cpp", "max_issues_repo_name": "24icewolf42/otfft", "max_issues_repo_head_hexsha": "6069f7017043af06f556a275662a465a56111c42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-16T10:39:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-16T15:42:37.000Z", "max_forks_repo_path": "unit_tests/otfft_transform_test.cpp", "max_forks_repo_name": "24icewolf42/otfft", "max_forks_repo_head_hexsha": "6069f7017043af06f556a275662a465a56111c42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-01-16T15:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T00:21:50.000Z", "avg_line_length": 30.7705882353, "max_line_length": 103, "alphanum_fraction": 0.5452112407, "num_tokens": 2516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5737095761486448}}
{"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": "#include \"trinary.h\"\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(_1_yields_decimal_1)\n{\n    BOOST_REQUIRE_EQUAL(1, trinary::to_decimal(\"1\"));\n}\n\nBOOST_AUTO_TEST_CASE(_2_yields_decimal_2)\n{\n    BOOST_REQUIRE_EQUAL(2, trinary::to_decimal(\"2\"));\n}\n\nBOOST_AUTO_TEST_CASE(_10_yields_decimal_3)\n{\n    BOOST_REQUIRE_EQUAL(3, trinary::to_decimal(\"10\"));\n}\n\nBOOST_AUTO_TEST_CASE(_11_yields_decimal_4)\n{\n    BOOST_REQUIRE_EQUAL(4, trinary::to_decimal(\"11\"));\n}\n\nBOOST_AUTO_TEST_CASE(_100_yields_decimal_9)\n{\n    BOOST_REQUIRE_EQUAL(9, trinary::to_decimal(\"100\"));\n}\n\nBOOST_AUTO_TEST_CASE(_112_yields_decimal_14)\n{\n    BOOST_REQUIRE_EQUAL(14, trinary::to_decimal(\"112\"));\n}\n\nBOOST_AUTO_TEST_CASE(_222_yields_decimal_26)\n{\n    BOOST_REQUIRE_EQUAL(26, trinary::to_decimal(\"222\"));\n}\n\nBOOST_AUTO_TEST_CASE(_1122000120_yields_decimal_32091)\n{\n    BOOST_REQUIRE_EQUAL(32091, trinary::to_decimal(\"1122000120\"));\n}\n\nBOOST_AUTO_TEST_CASE(invalid_yields_decimal_0)\n{\n    BOOST_REQUIRE_EQUAL(0, trinary::to_decimal(\"carrot\"));\n}\n#if defined(EXERCISM_RUN_ALL_TESTS)\n#endif\n", "meta": {"hexsha": "4865df2050250c43d9b73b29254a36502fa04bc1", "size": 1089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trinary/trinary_test.cpp", "max_stars_repo_name": "cmccandless/ExercismSolutions-cpp", "max_stars_repo_head_hexsha": "1a97e2a68513a34883b29ed047443b6602e77d3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trinary/trinary_test.cpp", "max_issues_repo_name": "cmccandless/ExercismSolutions-cpp", "max_issues_repo_head_hexsha": "1a97e2a68513a34883b29ed047443b6602e77d3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trinary/trinary_test.cpp", "max_forks_repo_name": "cmccandless/ExercismSolutions-cpp", "max_forks_repo_head_hexsha": "1a97e2a68513a34883b29ed047443b6602e77d3b", "max_forks_repo_licenses": ["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.3529411765, "max_line_length": 66, "alphanum_fraction": 0.7796143251, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.5737095692873132}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[register_box_2d_4values\r\n//` Show the use of the macro BOOST_GEOMETRY_REGISTER_BOX_2D_4VALUES\r\n\r\n#include <iostream>\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/register/point.hpp>\r\n#include <boost/geometry/geometries/register/box.hpp>\r\n\r\nstruct my_point\r\n{\r\n    int x, y;\r\n};\r\n\r\nstruct my_box\r\n{\r\n    int left, top, right, bottom;\r\n};\r\n\r\nBOOST_GEOMETRY_REGISTER_POINT_2D(my_point, int, cs::cartesian, x, y)\r\n\r\n// Register the box type, also notifying that it is based on \"my_point\"\r\n// (even if it does not contain it)\r\nBOOST_GEOMETRY_REGISTER_BOX_2D_4VALUES(my_box, my_point, left, top, right, bottom)\r\n\r\nint main()\r\n{\r\n    my_box b = boost::geometry::make<my_box>(0, 0, 2, 2);\r\n    std::cout << \"Area: \"  << boost::geometry::area(b) << std::endl;\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[register_box_2d_4values_output\r\n/*`\r\nOutput:\r\n[pre\r\nArea: 4\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "030415278dad6e6d2d4d91b3e449260f7f6e0749", "size": 1223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/geometries/register/box_2d_4values.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/geometry/doc/src/examples/geometries/register/box_2d_4values.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/geometry/doc/src/examples/geometries/register/box_2d_4values.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5192307692, "max_line_length": 83, "alphanum_fraction": 0.6892886345, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5736093864685264}}
{"text": "/*****************************************************************************\n * slicing.cpp        Blitz++ Array slicing & subarrays example\n *****************************************************************************/\n\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    Array<int,2> A(6,6), B(3,3);\n  \n    // Set the upper left quadrant of A to 5 \n    A(Range(0,2), Range(0,2)) = 5; \n\n    // Set the upper right quadrant of A to an identity matrix\n    B = 1, 0, 0,\n        0, 1, 0,\n        0, 0, 1;\n    A(Range(0,2), Range(3,5)) = B;\n\n    // Set the fourth row to 1\n\n#ifdef BZ_HAVE_PARTIAL_ORDERING\n    A(3, Range::all()) = 1;\n#else\n    cout << \"Warning: your compiler does not support partial ordering of\"\n         << endl << \"member templates; using kludge.\" << endl;\n    A(Range(3,3), Range::all()) = 1;\n#endif\n\n    // Set the last two rows to 0\n    A(Range(4, toEnd), Range::all()) = 0;\n\n    // Set the bottom right element to 8\n    A(5,5) = 8;\n\n    cout << \"A = \" << A << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "aa83a8eebf58b74fc494cc9abae8da483b844d48", "size": 1025, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/slicing.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/examples/slicing.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/examples/slicing.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8372093023, "max_line_length": 79, "alphanum_fraction": 0.4712195122, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.5736093825682157}}
{"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": "//==================================================================================================\n/*!\n  @file\n\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/rem_2pi.hpp>\n#include <boost/simd/meta/cardinal_of.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/pio_2.hpp>\n#include <boost/simd/constant/twopi.hpp>\n#include <boost/simd/constant/ten.hpp>\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], m[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : -T((i));\n     m[i] = bs::rem_2pi(a1[i]);\n   }\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t mm(&m[0], &m[0]+N);\n  STF_IEEE_EQUAL( bs::rem_2pi(aa1), mm);\n}\n\nSTF_CASE_TPL(\"Check rem_2pi on pack\" , STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T>;\n  static const std::size_t N = bs::cardinal_of<p_t>::value;\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\n\nSTF_CASE_TPL (\" rem_2pi\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::rem_2pi;\n  using p_t = bs::pack<T>;\n\n  {\n    p_t res = rem_2pi(bs::Zero<p_t>());\n    STF_ULP_EQUAL( res, bs::Zero<p_t>(), 1.5);\n    res = rem_2pi(bs::Pi<p_t>()-bs::Ten<p_t>()*bs::Eps<p_t>());\n    STF_ULP_EQUAL( res, bs::Pi<p_t>()-bs::Ten<p_t>()*bs::Eps<p_t>(), 1.5);\n    res = rem_2pi(bs::Pi<p_t>()+bs::Ten<p_t>()*bs::Eps<p_t>());\n    STF_ULP_EQUAL( res, bs::Ten<p_t>()*bs::Eps<p_t>()-bs::Pi<p_t>(), 1.5);\n    res = rem_2pi(bs::Twopi<p_t>());\n    STF_ULP_EQUAL( res, bs::Zero<p_t>(), 1.5);\n    res = rem_2pi(bs::Pio_2<p_t>());\n    STF_ULP_EQUAL( res, bs::Pio_2<p_t>(), 1.5);\n  }\n} // end of test for floating_\n", "meta": {"hexsha": "a103253bc5224b68bfe8ef8df4a86f5662818eed", "size": 2429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/rem_2pi.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "test/function/simd/rem_2pi.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/simd/rem_2pi.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 30.746835443, "max_line_length": 100, "alphanum_fraction": 0.5883079457, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.5735725330873132}}
{"text": "/*\n   The MIT License (MIT)\n\n   Copyright (c) 2011 - 2013, Philipp Heise and Sebastian Klose\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 <cvt/math/SE3.h>\n#include <cvt/math/Math.h>\n#include <cvt/util/CVTTest.h>\n#include <cvt/vision/Vision.h>\n\n#include <Eigen/Core>\n\nnamespace cvt {\n\n    static bool testJacobian()\n    {\n        Eigen::Matrix<double, 6, 1> parameter = Eigen::Matrix<double, 6, 1>::Zero();\n        Eigen::Matrix<double, 6, 1> delta = Eigen::Matrix<double, 6, 1>::Zero();\n        Eigen::Matrix<double, 3, 6> jNumeric, jAnalytic, jDiff;\n\n        parameter[ 0 ] = Math::deg2Rad(  3 );\n        parameter[ 1 ] = Math::deg2Rad( -6 );\n        parameter[ 2 ] = Math::deg2Rad(  5 );\n        parameter[ 3 ] = 20;\n        parameter[ 4 ] = 30;\n        parameter[ 5 ] = 40;\n\n        SE3<double> pose;\n        pose.set( parameter );\n\n        Eigen::Matrix<double, 3, 1> point, ppoint;\n        Eigen::Matrix<double, 3, 1> p, pp;\n        point[ 0 ] = 13; point[ 1 ] = 8; point[ 2 ] = 12;;\n\n        pose.transform( p, point );\n\n        double h = 0.0001;\n        for( size_t i = 0; i < 6; i++ ){\n            delta[ i ] = h;\n\n            pose.apply( delta );\n\n            pose.transform( pp, point );\n            jNumeric.col( i ) = ( pp - p ) / h;\n\n            delta[ i ] = 0;\n            pose.set( parameter );\n        }\n\n        pose.jacobian( jAnalytic, point );\n\n        bool b, ret = true;\n        jDiff = jAnalytic - jNumeric;\n\n        b = ( jDiff.array().abs().sum() / 18.0 ) < 0.001;\n\n        CVTTEST_PRINT( \"Pose Jacobian\", b );\n        if( !b ){\n            std::cout << \"Analytic:\\n\" << jAnalytic << std::endl;\n            std::cout << \"Numeric:\\n\" << jNumeric << std::endl;\n            std::cout << \"Difference:\\n\" << jDiff << std::endl;\n        }\n        ret &= b;\n\n        return ret;\n    }\n\n    static bool testHessian()\n    {\n        Eigen::Matrix<double, 6, 1> delta = Eigen::Matrix<double, 6, 1>::Zero();\n        Eigen::Matrix<double, 24, 6> hN, hA;\n\n        SE3<double> pose;\n        pose.set( Math::deg2Rad( 10.0 ), Math::deg2Rad( 40.0 ), Math::deg2Rad( -120.0 ), -100.0, 200.0, 300.0 );\n\n        Eigen::Matrix<double, 3, 3> K( Eigen::Matrix<double, 3, 3>::Zero() );\n        K( 0, 0 ) = 650.0; K( 0, 2 ) = 320.0;\n        K( 1, 1 ) = 650.0; K( 1, 2 ) = 240.0;\n        K( 2, 2 ) = 1.0;\n\n        Eigen::Matrix<double, 3, 1> point;\n        Eigen::Matrix<double, 3, 1> p, ff, fb, bf, bb, xxf, xxb, hess;\n        point[ 0 ] = 16;\n        point[ 1 ] = 80;\n        point[ 2 ] = 13;\n\n        pose.transform( p, point );\n\n        double h = 0.0001;\n        for( size_t i = 0; i < 6; i++ ){\n            for( size_t j = 0; j < 6; j++ ){\n                delta.setZero();\n                if( i == j ){\n                    // +\n                    delta[ j ] = h;\n                    pose.apply( delta );\n                    pose.transform( xxf, point );\n                    pose.apply( -delta );\n\n                    delta[ j ] = -h;\n                    pose.apply( delta );\n                    pose.transform( xxb, point );\n                    pose.apply( -delta );\n\n                    hess = ( xxb - 2 * p + xxf ) / ( h*h );\n                } else {\n                    delta[ i ] = h;\n                    delta[ j ] = h;\n                    pose.apply( delta );\n                    pose.transform( ff, point );\n                    pose.apply( -delta );\n\n                    delta[ i ] = h;\n                    delta[ j ] = -h;\n                    pose.apply( delta );\n                    pose.transform( fb, point );\n                    pose.apply( -delta );\n\n                    delta[ i ] = -h;\n                    delta[ j ] =  h;\n                    pose.apply( delta );\n                    pose.transform( bf, point );\n                    pose.apply( -delta );\n\n                    delta[ i ] = -h;\n                    delta[ j ] = -h;\n                    pose.apply( delta );\n                    pose.transform( bb, point );\n                    pose.apply( -delta );\n\n                    hess = ( ff - bf - fb + bb ) / ( 4 * h * h );\n                }\n\n                hN( 4 * i , j ) = hess[ 0 ];\n                hN( 4 * i + 1 , j ) = hess[ 1 ];\n                hN( 4 * i + 2 , j ) = hess[ 2 ];\n                hN( 4 * i + 3 , j ) = 0.0;\n            }\n        }\n\n        pose.hessian( hA, p );\n\n        bool b, ret = true;\n        Eigen::Matrix<double, 24, 6> jDiff;\n        jDiff = hN - hA;\n\t\tb = ( jDiff.array().abs().sum() / ( double )( jDiff.rows() * jDiff.cols() ) ) < 0.00001;\n\n        CVTTEST_PRINT( \"Pose Hessian\", b );\n        if( !b ){\n            std::cout << \"Analytic:\\n\" << hA << std::endl;\n            std::cout << \"Numeric:\\n\" << hN << std::endl;\n            std::cout << \"Difference:\\n\" << jDiff << std::endl;\n        }\n        ret &= b;\n\n        return ret;\n    }\n\n    static void projectWithCam( Eigen::Matrix<double, 2, 1> & sp,\n                                const Eigen::Matrix<double, 3, 1> & p3d,\n                                const Eigen::Matrix<double, 3, 3> & K )\n    {\n        sp[ 0 ] = K( 0, 0 ) * p3d.x() / p3d.z() + K( 0, 2 );\n        sp[ 1 ] = K( 1, 1 ) * p3d.y() / p3d.z() + K( 1, 2 );\n    }\n\n    static bool testScreenJacobian()\n    {\n        Eigen::Matrix<double, 6, 1> delta = Eigen::Matrix<double, 6, 1>::Zero();\n        Eigen::Matrix<double, 2, 6> shNumeric, sh;\n\n        SE3<double> pose;\n        pose.set( Math::deg2Rad( 10.0 ), Math::deg2Rad( 40.0 ), Math::deg2Rad( -120.0 ), -100.0, 200.0, 300.0 );\n\n        Eigen::Matrix<double, 3, 3> K( Eigen::Matrix<double, 3, 3>::Zero() );\n        K( 0, 0 ) = 650.0; K( 0, 2 ) = 320.0;\n        K( 1, 1 ) = 650.0; K( 1, 2 ) = 240.0;\n        K( 2, 2 ) = 1.0;\n\n        Eigen::Matrix<double, 3, 1> point, ptrans;\n        Eigen::Matrix<double, 2, 1> sp, ff, bb, jac;\n        point[ 0 ] = 100; point[ 1 ] = 200; point[ 2 ] = 300;\n\n        // project the point with current parameters\n        pose.transform( ptrans, point );\n        projectWithCam( sp, ptrans, K );\n\n        double h = 0.001;\n        for( size_t i = 0; i < 6; i++ ){\n            delta[ i ] = h;\n            pose.apply( delta );\n            pose.transform( ptrans, point );\n            projectWithCam( ff, ptrans, K );\n            pose.apply( -delta );\n\n            delta[ i ] = -h;\n            pose.apply( delta );\n            pose.transform( ptrans, point );\n            projectWithCam( bb, ptrans, K );\n            pose.apply( -delta );\n\n            jac = ( ff - bb ) / ( 2 * h );\n            delta.setZero();\n\n            shNumeric( 0, i ) = jac[ 0 ];\n            shNumeric( 1, i ) = jac[ 1 ];\n\n        }\n\n        pose.transform( ptrans, point );\n        pose.screenJacobian( sh, ptrans, K );\n\n        bool b, ret = true;\n        Eigen::Matrix<double, 2, 6> jDiff;\n        jDiff = shNumeric - sh;\n\t\tb = ( jDiff.array().abs().sum() / ( double )( jDiff.rows() * jDiff.cols() ) ) < 0.0001;\n\n        CVTTEST_PRINT( \"Pose ScreenJacobian\", b );\n        if( !b ){\n            std::cout << \"Analytic:\\n\" << sh << std::endl;\n            std::cout << \"Numeric:\\n\" << shNumeric << std::endl;\n            std::cout << \"Difference:\\n\" << jDiff << std::endl;\n        }\n        ret &= b;\n\n        return ret;\n    }\n    static bool testScreenHessian()\n    {\n        Eigen::Matrix<double, 6, 1> delta = Eigen::Matrix<double, 6, 1>::Zero();\n        Eigen::Matrix<double, 6, 6> shNumericX, shNumericY, shX, shY;\n\n\n        SE3<double> pose;\n        pose.set( Math::deg2Rad( 10.0 ), Math::deg2Rad( 40.0 ), Math::deg2Rad( -120.0 ), -100.0, 200.0, 300.0 );\n\n        Eigen::Matrix<double, 3, 3> K( Eigen::Matrix<double, 3, 3>::Zero() );\n        K( 0, 0 ) = 650.0; K( 0, 2 ) = 320.0;\n        K( 1, 1 ) = 650.0; K( 1, 2 ) = 240.0;\n        K( 2, 2 ) = 1.0;\n\n        Eigen::Matrix<double, 3, 1> point, ptrans;\n        Eigen::Matrix<double, 2, 1> sp, ff, fb, bf, bb, xxf, xxb, hess;\n        point[ 0 ] = 100; point[ 1 ] = 200; point[ 2 ] = 300;\n\n        // project the point with current parameters\n        pose.transform( ptrans, point );\n        projectWithCam( sp, ptrans, K );\n\n        double h = 0.001;\n        for( size_t i = 0; i < 6; i++ ){\n            for( size_t j = 0; j < 6; j++ ){\n\n                if( i == j ){\n                    // +\n                    delta[ j ] = h;\n                    pose.apply( delta );\n                    pose.transform( ptrans, point );\n                    projectWithCam( xxf, ptrans, K );\n                    delta[ j ] = -2 * h;\n                    pose.apply( delta );\n                    pose.transform( ptrans, point );\n                    projectWithCam( xxb, ptrans, K );\n\n                    hess = ( xxb - 2 * sp + xxf ) / ( h*h );\n\n                    // back to start\n                    delta[ j ] = h;\n                    pose.apply( delta );\n                    delta[ j ] = 0;\n                } else {\n                    delta[ i ] = h;\n                    delta[ j ] = h;\n                    pose.apply( delta );\n                    pose.transform( ptrans, point );\n                    projectWithCam( ff, ptrans, K );\n                    pose.apply( -delta );\n\n                    delta[ i ] = h;\n                    delta[ j ] = -h;\n                    pose.apply( delta );\n                    pose.transform( ptrans, point );\n                    projectWithCam( fb, ptrans, K );\n                    pose.apply( -delta );\n\n                    delta[ i ] = -h;\n                    delta[ j ] =  h;\n                    pose.apply( delta );\n                    pose.transform( ptrans, point );\n                    projectWithCam( bf, ptrans, K );\n                    pose.apply( -delta );\n\n                    delta[ i ] = -h;\n                    delta[ j ] = -h;\n                    pose.apply( delta );\n                    pose.transform( ptrans, point );\n                    projectWithCam( bb, ptrans, K );\n                    pose.apply( -delta );\n\n                    hess = ( ff - bf - fb + bb ) / ( 4 * h * h );\n                    delta.setZero();\n                }\n\n                shNumericX( i, j ) = hess[ 0 ];\n                shNumericY( i, j ) = hess[ 1 ];\n\n            }\n        }\n\n        pose.transform( ptrans, point );\n        pose.screenHessian( shX, shY, ptrans, K );\n\n        bool b, ret = true;\n        Eigen::Matrix<double, 6, 6> jDiff;\n\t\tjDiff = shNumericX - shX;\n\t\tb = ( jDiff.array().abs().sum() / ( double )( jDiff.rows() * jDiff.cols() ) ) < 0.0001;\n\n        CVTTEST_PRINT( \"Pose ScreenHessian X\", b );\n        if( !b ){\n            std::cout << \"Analytic:\\n\" << shX << std::endl;\n            std::cout << \"Numeric:\\n\" << shNumericX << std::endl;\n            std::cout << \"Difference:\\n\" << jDiff << std::endl;\n        }\n        ret &= b;\n\n        jDiff = shNumericY - shY;\n\t\tb = ( jDiff.array().abs().sum() / ( double )( jDiff.rows() * jDiff.cols() ) ) < 0.0001;\n\n        CVTTEST_PRINT( \"Pose ScreenHessian Y\", b );\n        if( !b ){\n            std::cout << \"Analytic:\\n\" << shY << std::endl;\n            std::cout << \"Numeric:\\n\" << shNumericY << std::endl;\n            std::cout << \"Difference:\\n\" << jDiff << std::endl;\n        }\n        ret &= b;\n\n        return ret;\n    }\n\n    static bool testApply()\n    {\n        bool b, ret;\n        // apply delta:\n        Eigen::Matrix<double, 6, 1> delta = Eigen::Matrix<double, 6, 1>::Zero();\n        Eigen::Matrix<double, 4, 4> expectedT = Eigen::Matrix<double, 4, 4>::Identity();\n        Eigen::Matrix<double, 4, 4> diff;\n\n        SE3<double> pose;\n        pose.set( delta );\n        delta[ 0 ] = Math::deg2Rad( 1.5 );\n        delta[ 1 ] = Math::deg2Rad( 1.1 );\n        delta[ 2 ] = Math::deg2Rad( 1.6 );\n        delta[ 3 ] = 1;\n        delta[ 4 ] = 1;\n        delta[ 5 ] = 1;\n        pose.apply( delta );\n\n        expectedT( 0, 3 ) = delta[ 3 ];\n        expectedT( 1, 3 ) = delta[ 4 ];\n        expectedT( 2, 3 ) = delta[ 5 ];\n\n        Eigen::Matrix<double, 3, 1> axis = delta.segment<3>( 0 );\n        double angle = axis.norm();\taxis /= angle;\n\n        expectedT.block<3, 3>( 0, 0 ) = Eigen::AngleAxis<double>( angle, axis ).toRotationMatrix();\n        diff = expectedT - pose.transformation();\n\n        ret = b = ( diff.array().abs().sum() / 12 < 0.001 );\n\n        if( !b ){\n            std::cout << expectedT << std::endl;\n            std::cout << pose.transformation() << std::endl;\n            std::cout << \"avg SAD: \" << diff.array().abs().sum() / 12 << std::endl;\n        }\n\n        pose.apply( -delta );\n        expectedT.setIdentity();\n\n        b &= ( ( expectedT - pose.transformation() ).array().abs().sum() / 12 < 0.0001 );\n        CVTTEST_PRINT( \"apply\", b );\n        ret &= b;\n\n        return ret;\n    }\n\n    static bool testInitAndSet()\n    {\n        bool ret = true;\n        SE3<double> pose;\n\n        bool b;\n        b = ( pose.transformation() == Eigen::Matrix<double, 4, 4>::Identity() );\n        ret &= b;\n        CVTTEST_PRINT( \"Initialization\", b );\n\n        pose.set( 0, 0, 0, 100, 200, 300 );\n        b = ( pose.transformation()( 0, 3 ) == 100 ) &&\n            ( pose.transformation()( 1, 3 ) == 200 ) &&\n            ( pose.transformation()( 2, 3 ) == 300 ) &&\n            ( pose.transformation()( 3, 3 ) ==   1 ) &&\n            ( pose.transformation()( 2, 2 ) ==   1 ) &&\n            ( pose.transformation()( 1, 1 ) ==   1 ) &&\n            ( pose.transformation()( 0, 0 ) ==   1 );\n\n        pose.set( Math::deg2Rad( 90.0 ), 0, 0, 0, 0, 0 );\n        b &= ( pose.transformation()( 0, 3 ) ==   0 );\n        b &= ( pose.transformation()( 1, 3 ) ==   0 );\n        b &= ( pose.transformation()( 2, 3 ) ==   0 );\n        b &= ( pose.transformation()( 3, 3 ) ==   1 );\n        b &= ( pose.transformation()( 0, 0 ) ==   1 );\n        b &= ( pose.transformation()( 0, 1 ) ==   0 );\n        b &= ( pose.transformation()( 0, 2 ) ==   0 );\n        b &= ( pose.transformation()( 1, 0 ) ==   0 );\n        b &= ( pose.transformation()( 2, 0 ) ==   0 );\n        b &= ( pose.transformation()( 1, 2 ) + 1 < 0.0000001 );\n        b &= ( pose.transformation()( 2, 1 ) - 1 < 0.0000001 );\n        b &= ( Math::abs( pose.transformation()( 2, 2 ) ) <  0.0000001 );\n        b &= ( Math::abs( pose.transformation()( 1, 1 ) ) <  0.0000001 );\n\n        CVTTEST_PRINT( \"Set\", b );\n\n        ret &= b;\n\n        return ret;\n    }\n\n    static void fillExpMatrix( Eigen::Matrix4d& S, const SE3<double>::ParameterVectorType& delta )\n    {\n        S( 0, 0 ) =         0;\n        S( 0, 1 ) = -delta[ 2 ];\n        S( 0, 2 ) =  delta[ 1 ];\n        S( 0, 3 ) =  delta[ 3 ];\n\n        S( 1, 0 ) =  delta[ 2 ];\n        S( 1, 1 ) =         0;\n        S( 1, 2 ) = -delta[ 0 ];\n        S( 1, 3 ) =  delta[ 4 ];\n\n        S( 2, 0 ) = -delta[ 1 ];\n        S( 2, 1 ) =  delta[ 0 ];\n        S( 2, 2 ) =         0;\n        S( 2, 3 ) =  delta[ 5 ];\n\n        S( 3, 0 ) = S( 3, 1 ) = S( 3, 2 ) = 0;\n        S( 3, 3 ) = 0;\n    }\n\n    static bool testExponential()\n    {\n        SE3<double> pose;\n\n        Eigen::Matrix4d S, expectedExp, closedForm;\n        S.setZero(); expectedExp.setZero(), closedForm.setZero();\n\n        SE3<double>::ParameterVectorType delta;\n\n\t\tsize_t n = 5000;\n\n\t\tbool b = true;\n\t\twhile( n-- ){\n\t\t\tdelta[ 0 ] = Math::rand( -2.6, 2.6 );\n\t\t\tdelta[ 1 ] = Math::rand( -2.6, 2.6 );\n\t\t\tdelta[ 2 ] = Math::rand( -2.6, 2.6 );\n\t\t\tdelta[ 3 ] = Math::rand( -10.0, 10.0 );\n\t\t\tdelta[ 4 ] = Math::rand( -10.0, 10.0 );\n\t\t\tdelta[ 5 ] = Math::rand( -10.0, 10.0 );\n\n\t\t\tfillExpMatrix( S, delta );\n\t\t\tcvt::Math::exponential( S, expectedExp, 10 );\n\t\t\tpose.evalExp( closedForm, delta );\n\t\t\tbool res = ( ( expectedExp - closedForm ).array().abs().sum() / 12 < 0.00001 );\n\n\t\t\tif( !res ){\n\t\t\t\tstd::cout << \"Expected: \\n\" << expectedExp << std::endl;\n\t\t\t\tstd::cout << \"Closed Form: \\n\" << closedForm << std::endl;\n\t\t\t}\n\t\t\tb &= res;\n\t\t}\n\n        CVTTEST_PRINT( \"exp()\", b );\n\n        return b;\n    }\n\nBEGIN_CVTTEST( SE3 )\n    bool ret = true;\n\n    ret &= testInitAndSet();\n    ret &= testApply();\n    ret &= testJacobian();\n    ret &= testScreenJacobian();\n    ret &= testHessian();\n    ret &= testScreenHessian();\n    ret &= testExponential();\n\n    return ret;\nEND_CVTTEST\n\n}\n", "meta": {"hexsha": "f79cb71c327301a632e5ce52daa1e13b66d88d7c", "size": 17049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cvt/math/SE3Test.cpp", "max_stars_repo_name": "tuxmike/cvt", "max_stars_repo_head_hexsha": "c6a5df38af4653345e795883b8babd67433746e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-04T16:38:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T11:31:26.000Z", "max_issues_repo_path": "cvt/math/SE3Test.cpp", "max_issues_repo_name": "tuxmike/cvt", "max_issues_repo_head_hexsha": "c6a5df38af4653345e795883b8babd67433746e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cvt/math/SE3Test.cpp", "max_forks_repo_name": "tuxmike/cvt", "max_forks_repo_head_hexsha": "c6a5df38af4653345e795883b8babd67433746e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-04-11T00:58:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T07:35:40.000Z", "avg_line_length": 32.8497109827, "max_line_length": 112, "alphanum_fraction": 0.452225937, "num_tokens": 5187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5735482829413566}}
{"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": "/**\n * @file contourplot_test.cc\n * @brief NPDE homework ContourPlot code\n * @author Oliver Rietmann\n * @date 25.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"../contourplot.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\nnamespace ContourPlot::test {\n\nconstexpr double Square(double x) { return x * x; }\n\n// Leads to isoline F(x) = 2\ndouble F(Eigen::Vector2d x) { return 0.5 * Square(x(0)) + Square(x(1)); };\nconst Eigen::Vector2d y0(2.0, 0.0);\nconst double T = 6.0;\n\n// Compute F(x) - 2 along isoline, which should be zero\nEigen::VectorXd errorAlongIsoline(const Eigen::MatrixXd &isolinePoints) {\n  int M = isolinePoints.cols();\n  Eigen::VectorXd errors(M);\n  for (int m = 0; m < M; ++m) {\n    Eigen::Vector2d x =\n        Eigen::Vector2d(isolinePoints(0, m), isolinePoints(1, m));\n    errors(m) = F(x) - 2.0;\n  }\n  return errors;\n}\n\nTEST(ContourPlot, computeIsolinePoints) {\n  auto gradF = [](Eigen::Vector2d x) -> Eigen::Vector2d {\n    return Eigen::Vector2d(x(0), 2.0 * x(1));\n  };\n  Eigen::MatrixXd isolinePoints = computeIsolinePoints(gradF, y0, T);\n  Eigen::VectorXd errors = errorAlongIsoline(isolinePoints);\n  double tol = 1.0e-5;\n  ASSERT_NEAR(0.0, errors.lpNorm<Eigen::Infinity>(), tol);\n}\n\nTEST(ContourPlot, computeIsolinePointsDQ) {\n  Eigen::MatrixXd isolinePointsDQ = computeIsolinePointsDQ(F, y0, T);\n  Eigen::VectorXd errors = errorAlongIsoline(isolinePointsDQ);\n  double tol = 1.0e-5;\n  ASSERT_NEAR(0.0, errors.lpNorm<Eigen::Infinity>(), tol);\n}\n\n}  // namespace ContourPlot::test\n", "meta": {"hexsha": "8929ef036dcc6cb5fcb309f210cf3b55ad791cda", "size": 1518, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ContourPlot/templates/test/contourplot_test.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ContourPlot/templates/test/contourplot_test.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ContourPlot/templates/test/contourplot_test.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 28.1111111111, "max_line_length": 74, "alphanum_fraction": 0.6805006588, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.5733267622202943}}
{"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        // \u6570\u636e\u683c\u5f0f\uff1a\u56fe\u50cf\u6587\u4ef6\u540d tx, ty, tz, qx, qy, qz, qw \uff0c\u6ce8\u610f\u662f TWC \u800c\u975e TCW\n        string image;\n        fin >> image;\n        double data[7];\n        for (double &d:data) fin >> d;\n\n        color_image_files.push_back(path + string(\"/images/\") + image);\n        poses.push_back(\n            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\u00e4nkt), 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": "#ifndef HAMILTONIANS_NONINTEGRABLE_HPP\n#define HAMILTONIANS_NONINTEGRABLE_HPP\n#include <Eigen/Eigen>\n#include <nlohmann/json.hpp>\n\nclass NonIntegrable\n{\nprivate:\n\tint n_;\n\tdouble J_;\n\tdouble h_;\npublic:\n\n\tNonIntegrable(int n, double J, double h)\n\t\t: n_(n), J_(J), h_(h)\n\t{\n\t}\n\n\tnlohmann::json params() const\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"TFIsing\"},\n\t\t\t{\"n\", n_},\n\t\t\t{\"J\", J_},\n\t\t\t{\"h\", h_}\n\t\t};\n\t}\n\t\n\ttemplate<class State>\n\ttypename State::Scalar operator()(const State& smp) const\n\t{\n\t\ttypename State::Scalar s = 0.0;\n\t\t//Nearest-neighbor\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\ts += -J_*smp.sigmaAt(i)*smp.sigmaAt((i+1)%n_);\n\t\t\ts += -1.0*smp.ratio(i);\n\t\t\ts += -h_*smp.sigmatAt(i);\n\t\t}\n\t\treturn s;\n\t}\n\n\tEigen::VectorXd getCol(long long int col) const\n\t{\n\t\tEigen::VectorXd res = Eigen::VectorXd::Zero(1<<n_);\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint s1 = (col >> i) & 1;\n\t\t\tint s2 = (col >> ((i+1) % n_)) & 1;\n\t\t\tlong long int x = (1 << i);\n\t\t\tres(col ^ x) += -h_;\n\t\t\tres(col) += -J_*(1-2*s1)*(1-2*s2);\n\t\t\tres(col) += -1.0*(1-2*s1);\n\t\t}\n\t\treturn res;\n\t}\n};\n#endif//HAMILTONIANS_NONINTEGRABLE_HPP\n", "meta": {"hexsha": "ea65056dd207468e6383f1ec5411d8ca0d401982", "size": 1107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Hamiltonians/NonIntegrable.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/NonIntegrable.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/NonIntegrable.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.45, "max_line_length": 58, "alphanum_fraction": 0.5799457995, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5731803665468986}}
{"text": "//  Boost integer/static_log2.hpp header file  -------------------------------//\r\r\n\r\r\n//  (C) Copyright Daryle Walker 2001.  Permission to copy, use, modify, sell and\r\r\n//  distribute this software is granted provided this copyright notice appears \r\r\n//  in all copies.  This software is provided \"as is\" without express or\r\r\n//  implied warranty, and with no claim as to its suitability for any purpose. \r\r\n\r\r\n//  See http://www.boost.org for updates, documentation, and revision history. \r\r\n\r\r\n#ifndef BOOST_INTEGER_STATIC_LOG2_HPP\r\r\n#define BOOST_INTEGER_STATIC_LOG2_HPP\r\r\n\r\r\n#include <boost/integer_fwd.hpp>  // self include\r\r\n\r\r\n#include <boost/config.hpp>  // for BOOST_STATIC_CONSTANT, etc.\r\r\n#include <boost/limits.hpp>  // for std::numeric_limits\r\r\n\r\r\n#ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\r\r\n#include <boost/pending/ct_if.hpp>  // for boost::ct_if<>\r\r\n#endif\r\r\n\r\r\n\r\r\nnamespace boost\r\r\n{\r\r\n\r\r\n\r\r\n//  Implementation details  --------------------------------------------------//\r\r\n\r\r\nnamespace detail\r\r\n{\r\r\n\r\r\n// Forward declarations\r\r\ntemplate < unsigned long Val, int Place = 0, int Index\r\r\n = std::numeric_limits<unsigned long>::digits >\r\r\n    struct static_log2_helper_t;\r\r\n\r\r\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\r\r\n\r\r\ntemplate < unsigned long Val, int Place >\r\r\n    struct static_log2_helper_t< Val, Place, 1 >;\r\r\n\r\r\n#else\r\r\n\r\r\ntemplate < int Place >\r\r\n    struct static_log2_helper_final_step;\r\r\n\r\r\ntemplate < unsigned long Val, int Place = 0, int Index\r\r\n = std::numeric_limits<unsigned long>::digits >\r\r\n    struct static_log2_helper_nopts_t;\r\r\n\r\r\n#endif\r\r\n\r\r\n// Recursively build the logarithm by examining the upper bits\r\r\ntemplate < unsigned long Val, int Place, int Index >\r\r\nstruct static_log2_helper_t\r\r\n{\r\r\nprivate:\r\r\n    BOOST_STATIC_CONSTANT( int, half_place = Index / 2 );\r\r\n    BOOST_STATIC_CONSTANT( unsigned long, lower_mask = (1ul << half_place)\r\r\n     - 1ul );\r\r\n    BOOST_STATIC_CONSTANT( unsigned long, upper_mask = ~lower_mask );\r\r\n    BOOST_STATIC_CONSTANT( bool, do_shift = (Val & upper_mask) != 0ul );\r\r\n\r\r\n    BOOST_STATIC_CONSTANT( unsigned long, new_val = do_shift ? (Val\r\r\n     >> half_place) : Val );\r\r\n    BOOST_STATIC_CONSTANT( int, new_place = do_shift ? (Place + half_place)\r\r\n     : Place );\r\r\n    BOOST_STATIC_CONSTANT( int, new_index = Index - half_place );\r\r\n\r\r\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\r\r\n    typedef static_log2_helper_t<new_val, new_place, new_index>  next_step_type;\r\r\n#else\r\r\n    typedef static_log2_helper_nopts_t<new_val, new_place, new_index>  next_step_type;\r\r\n#endif\r\r\n\r\r\npublic:\r\r\n    BOOST_STATIC_CONSTANT( int, value = next_step_type::value );\r\r\n\r\r\n};  // boost::detail::static_log2_helper_t\r\r\n\r\r\n// Non-recursive case\r\r\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\r\r\n\r\r\ntemplate < unsigned long Val, int Place >\r\r\nstruct static_log2_helper_t< Val, Place, 1 >\r\r\n{\r\r\npublic:\r\r\n    BOOST_STATIC_CONSTANT( int, value = Place );\r\r\n\r\r\n};  // boost::detail::static_log2_helper_t\r\r\n\r\r\n#else\r\r\n\r\r\ntemplate < int Place >\r\r\nstruct static_log2_helper_final_step\r\r\n{\r\r\npublic:\r\r\n    BOOST_STATIC_CONSTANT( int, value = Place );\r\r\n\r\r\n};  // boost::detail::static_log2_helper_final_step\r\r\n\r\r\ntemplate < unsigned long Val, int Place, int Index >\r\r\nstruct static_log2_helper_nopts_t\r\r\n{\r\r\nprivate:\r\r\n    typedef static_log2_helper_t<Val, Place, Index>  recursive_step_type;\r\r\n    typedef static_log2_helper_final_step<Place>     final_step_type;\r\r\n\r\r\n    typedef typename ct_if<( Index != 1 ), recursive_step_type,\r\r\n     final_step_type>::type  next_step_type;\r\r\n\r\r\npublic:\r\r\n    BOOST_STATIC_CONSTANT( int, value = next_step_type::value );\r\r\n\r\r\n};  // boost::detail::static_log2_helper_nopts_t\r\r\n\r\r\n#endif\r\r\n\r\r\n}  // namespace detail\r\r\n\r\r\n\r\r\n//  Compile-time log-base-2 evaluator class declaration  ---------------------//\r\r\n\r\r\ntemplate < unsigned long Value >\r\r\nstruct static_log2\r\r\n{\r\r\n    BOOST_STATIC_CONSTANT( int, value\r\r\n     = detail::static_log2_helper_t<Value>::value );\r\r\n};\r\r\n\r\r\ntemplate < >\r\r\nstruct static_log2< 0ul >\r\r\n{\r\r\n    // The logarithm of zero is undefined.\r\r\n};\r\r\n\r\r\n\r\r\n}  // namespace boost\r\r\n\r\r\n\r\r\n#endif  // BOOST_INTEGER_STATIC_LOG2_HPP\r\r\n", "meta": {"hexsha": "972b970c9e6a636bf21a733fb3226f50233e9573", "size": 4163, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/boost/integer/static_log2.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T06:40:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:24:28.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/boost/integer/static_log2.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/boost/integer/static_log2.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "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": 29.3169014085, "max_line_length": 88, "alphanum_fraction": 0.6757146289, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5731803557553339}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n\n#include \"nlmatode.h\"\n\nint main() {\n  double T = 1;\n  unsigned int n = 3;\n\n  Eigen::MatrixXd Y0(n, n);\n  Y0 << 1, 1, 0, 0, 3, 2, 1, 5, 2;\n\n  Eigen::MatrixXd YT = NLMatODE::matode(Y0, T);\n\n  std::cout << YT << std::endl << std::endl;\n  Eigen::MatrixXd M0(n, n);\n  M0 << 1, 1, 0, 1, 3, 1, 0, 1, 1;\n  // check whether invariant is perserved or not\n  bool is_invariant = NLMatODE::checkinvariant(Y0, T);\n  bool is_invar_sym = NLMatODE::checkinvariant(M0, T);\n  std::cout << \"Test whether invariant was preserved or not...\" << std::endl;\n\n  if (is_invariant) {\n    std::cout << \"Invariant for Y0 preserved.\" << std::endl;\n  } else {\n    std::cout << \"Invariant for Y0 NOT preserved.\" << std::endl;\n  }\n  if (is_invar_sym) {\n    std::cout << \"Invariant for M0 preserved.\" << std::endl;\n  } else {\n    std::cout << \"Invariant for M0 NOT preserved.\" << std::endl;\n  }\n\n  double rate = NLMatODE::cvgDiscreteGradientMethod();\n  std::cout << \"\\nThe fitted rate for the discrete gradient method is:\\n\"\n            << rate << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "3fbf4f7041fb776b4ce4a02609b9957a3033af4b", "size": 1081, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/NLMatODE/templates/nlmatode_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/NLMatODE/templates/nlmatode_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/NLMatODE/templates/nlmatode_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": 27.7179487179, "max_line_length": 77, "alphanum_fraction": 0.6096207216, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5731803557022808}}
{"text": "#include \"cluster_utils.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n\n#include \"lib/progressbar/progressbar.h\"\n#include \"proto_utils.h\"\n\nEigen::MatrixXd bayesmix::posterior_similarity(\n    const Eigen::MatrixXd &alloc_chain) {\n  unsigned int n_data = alloc_chain.cols();\n  Eigen::MatrixXd mean_diss = Eigen::MatrixXd::Zero(n_data, n_data);\n  // Loop over pairs (i,j) of data points\n  for (int i = 0; i < n_data; i++) {\n    for (int j = 0; j < i; j++) {\n      Eigen::ArrayXd diff = alloc_chain.col(i) - alloc_chain.col(j);\n      mean_diss(i, j) = (diff == 0).count();\n    }\n  }\n  return mean_diss / alloc_chain.rows();\n}\n\nEigen::VectorXd bayesmix::cluster_estimate(\n    const Eigen::MatrixXd &alloc_chain) {\n  // Initialize objects\n  unsigned n_iter = alloc_chain.rows();\n  unsigned int n_data = alloc_chain.cols();\n  std::vector<Eigen::SparseMatrix<double> > all_diss;\n  progresscpp::ProgressBar bar(n_iter, 60);\n\n  // Compute mean\n  std::cout << \"(Computing mean dissimilarity... \" << std::flush;\n  Eigen::MatrixXd mean_diss = bayesmix::posterior_similarity(alloc_chain);\n  std::cout << \"Done)\" << std::endl;\n\n  // Compute Frobenius norm error of all iterations\n  Eigen::VectorXd errors(n_iter);\n  for (int k = 0; k < n_iter; k++) {\n    for (int i = 0; i < n_data; i++) {\n      for (int j = 0; j < i; j++) {\n        int x = (alloc_chain(k, i) == alloc_chain(k, j));\n        errors(k) += (x - mean_diss(i, j)) * (x - mean_diss(i, j));\n      }\n    }\n    // Progress bar\n    ++bar;\n    bar.display();\n  }\n  bar.done();\n\n  // Find iteration with the least error\n  std::ptrdiff_t ibest;\n  unsigned int min_err = errors.minCoeff(&ibest);\n  return alloc_chain.row(ibest).transpose();\n}\n", "meta": {"hexsha": "eb8b8fa9363caa1a75f44da3dddf8669c35fe387", "size": 1690, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/utils/cluster_utils.cc", "max_stars_repo_name": "mberaha/bayesmix", "max_stars_repo_head_hexsha": "4448f0e9f69ac71f3aacc11a239e3114790c1aaa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/cluster_utils.cc", "max_issues_repo_name": "mberaha/bayesmix", "max_issues_repo_head_hexsha": "4448f0e9f69ac71f3aacc11a239e3114790c1aaa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/cluster_utils.cc", "max_forks_repo_name": "mberaha/bayesmix", "max_forks_repo_head_hexsha": "4448f0e9f69ac71f3aacc11a239e3114790c1aaa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1785714286, "max_line_length": 74, "alphanum_fraction": 0.6402366864, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5731803556492273}}
{"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#include \"fdcev.hpp\"\n#include \"utilities.hpp\"\n\n#include <ql/math/functional.hpp>\n#include <ql/math/randomnumbers/rngtraits.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/math/statistics/generalstatistics.hpp>\n#include <ql/pricingengines/vanilla/analyticcevengine.hpp>\n#include <ql/pricingengines/vanilla/fdcevvanillaengine.hpp>\n\n#include <ql/methods/finitedifferences/utilities/cevrndcalculator.hpp>\n\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\nusing boost::unit_test_framework::test_suite;\n\n\nnamespace {\n    class ExpectationFct {\n      public:\n        ExpectationFct(const CEVRNDCalculator& calculator, Time t)\n        : t_(t), calculator_(calculator) { }\n\n        Real operator()(Real f) const { return f*calculator_.pdf(f, t_); }\n\n      private:\n        const Time t_;\n        const CEVRNDCalculator& calculator_;\n    };\n}\n\nvoid FdCevTest::testLocalMartingale() {\n    BOOST_TEST_MESSAGE(\n        \"Testing local martingale property of CEV process with PDF ...\");\n\n    const Time t = 1.0;\n\n    const Real f0 = 2.1;\n    const Real alpha = 1.75;\n    const Real betas[] = {-2.4, 0.23, 0.9, 1.1, 1.5};\n\n    for (Size i=0; i < LENGTH(betas); ++i) {\n        const Real beta = betas[i];\n        const CEVRNDCalculator rndCalculator(f0, alpha, beta);\n\n        const Real eps = 1e-10;\n        const Real tol = 100*eps;\n\n        const Real upperBound = 10*rndCalculator.invcdf(1-eps, t);\n\n        const Real expectationValue = GaussLobattoIntegral(10000, eps)(\n            ExpectationFct(rndCalculator, t), QL_EPSILON, upperBound);\n\n        const Real diff = expectationValue-f0;\n\n\n        if (beta < 1.0 && std::fabs(diff) > tol) {\n            BOOST_ERROR(\"CEV process should be a martingale for beta < 1.0\"\n                        << \"\\n    expected:   \" << f0\n                        << std::scientific\n                        << \"\\n    difference  \" << diff\n                        << \"\\n    tolerance:  \" << tol);\n        }\n\n        if (beta > 1.0 && diff > -tol) {\n            BOOST_ERROR(\"CEV process should only be a local martingale \"\n                        \"for beta > 1.0. Expectation is E[F_t|F_0] < F_0\"\n                        << \"\\n    E[F_t|F_0]: \" << expectationValue\n                        << \"\\n    F_0:        \" << f0);\n        }\n\n        // check local martingale property with Monte-Carlo simulation\n        const Size nSims = 5000;\n\n        const Size nSteps = 2000;\n        const Real dt = t / nSteps;\n        const Real sqrtDt = std::sqrt(dt);\n\n        GeneralStatistics stat;\n        const PseudoRandom::rng_type mt(MersenneTwisterUniformRng(42));\n\n        if (beta > 1.2) {\n            for (Size i=0; i < nSims; ++i) {\n                Real f = f0;\n                for (Size j=0; j < nSteps; ++j) {\n                    f += alpha * std::pow(f, beta) * mt.next().value * sqrtDt;\n                    f = std::max(0.0, f);\n\n                    if (f == 0.0) break; // absorbing boundary\n                }\n                stat.add(f - f0);\n            }\n\n            const Real calculated = stat.mean();\n            const Real error = stat.errorEstimate();\n\n            if (std::fabs(calculated - diff) > 2.35*error) {\n                BOOST_ERROR(\n                    \"failed to calculate local martingale property \"\n                    \"by Monte-Carlo Simulation for beta > 1.0. \"\n                            << \"\\n    E[F_t|F_0]   : \" << expectationValue\n                            << \"\\n    E_MC[F_t|F_0]: \" << calculated + f0\n                            << \"\\n    error_MC     : \" << error\n                            << \"\\n    difference   : \" << std::fabs(calculated - diff)\n                            << \"\\n    tolerance    : \" << 2.35*error);\n            }\n        }\n    }\n}\n\nvoid FdCevTest::testFdmCevOp() {\n    BOOST_TEST_MESSAGE(\n            \"Testing FDM constant elasticity of variance (CEV) operator...\");\n\n    SavedSettings backup;\n\n    const Date today = Date(22, February, 2018);\n    const DayCounter dc = Actual365Fixed();\n    Settings::instance().evaluationDate() = today;\n\n    const Date maturityDate = today + Period(12, Months);\n    const Real strike = 2.3;\n\n    const Option::Type optionTypes[] = { Option::Call, Option::Put};\n\n    const ext::shared_ptr<Exercise> exercise =\n        ext::make_shared<EuropeanExercise>(maturityDate);\n\n    for (Size i=0; i < LENGTH(optionTypes); ++i) {\n        const Option::Type optionType = optionTypes[i];\n\n        const ext::shared_ptr<PlainVanillaPayoff> payoff =\n            ext::make_shared<PlainVanillaPayoff>(optionType, strike);\n\n        const ext::shared_ptr<YieldTermStructure> rTS =\n            flatRate(today, 0.15, dc);\n\n        const Real f0 = 2.1;\n        const Real alpha = 0.75;\n\n        const Real betas[] = { -2.0, -0.5, 0.45, 0.6, 0.9, 1.45 };\n        for (Size j=0; j < LENGTH(betas); ++j) {\n\n            const Real beta = betas[j];\n\n            VanillaOption option(payoff, exercise);\n            option.setPricingEngine(ext::make_shared<AnalyticCEVEngine>(\n                f0, alpha, beta, Handle<YieldTermStructure>(rTS)));\n\n            const Real analyticNPV = option.NPV();\n\n            const Real eps = 1e-3;\n\n            option.setPricingEngine(ext::make_shared<AnalyticCEVEngine>(\n                f0*(1+eps), alpha, beta, Handle<YieldTermStructure>(rTS)));\n            const Real analyticUpNPV = option.NPV();\n\n            option.setPricingEngine(ext::make_shared<AnalyticCEVEngine>(\n                f0*(1-eps), alpha, beta, Handle<YieldTermStructure>(rTS)));\n            const Real analyticDownNPV = option.NPV();\n\n            const Real analyticDelta = (analyticUpNPV - analyticDownNPV)\n                /(2*eps*f0);\n\n            option.setPricingEngine(ext::make_shared<FdCEVVanillaEngine>(\n                f0, alpha, beta, Handle<YieldTermStructure>(rTS),\n                100, 1000, 1, 1.0, 1e-6));\n\n            const Real calculatedNPV = option.NPV();\n            const Real calculatedDelta = option.delta();\n\n            const Real tol = 0.01;\n            if (std::fabs(calculatedNPV - analyticNPV) > tol\n                || std::fabs(calculatedDelta - analyticDelta) > tol) {\n                BOOST_ERROR(\n                    \"failed to calculate vanilla option prices/delta \"\n                    << \"\\n    beta            : \" << beta\n                    << \"\\n    option type     : \"\n                    << ((payoff->optionType() == Option::Call) ? \"Call\" : \"Put\")\n                    << \"\\n    analytic npv    : \" << analyticNPV\n                    << \"\\n    pde npv         : \" << calculatedNPV\n                    << \"\\n    npv difference  : \"\n                    << std::fabs(calculatedNPV - analyticNPV)\n                    << \"\\n    tolerance       : \" << tol\n                    << \"\\n    analytic delta  : \" << analyticDelta\n                    << \"\\n    pde delta       : \" << calculatedDelta\n                    << \"\\n    delta difference: \"\n                    << std::fabs(calculatedDelta - analyticDelta)\n                    << \"\\n    tolerance       : \" << tol);\n            }\n        }\n    }\n}\n\n\ntest_suite* FdCevTest::suite(SpeedLevel speed) {\n    test_suite* suite = BOOST_TEST_SUITE(\"Finite Difference CEV tests\");\n\n\n    suite->add(QUANTLIB_TEST_CASE(&FdCevTest::testLocalMartingale));\n    suite->add(QUANTLIB_TEST_CASE(&FdCevTest::testFdmCevOp));\n\n    return suite;\n}\n", "meta": {"hexsha": "0e70625ef4c07dc552777922129a4b96bf75ad97", "size": 8139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/fdcev.cpp", "max_stars_repo_name": "NJeanray/QuantLib", "max_stars_repo_head_hexsha": "ee2de22acbb5e5441c810a45b33bbd7b3a87d669", "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": "test-suite/fdcev.cpp", "max_issues_repo_name": "NJeanray/QuantLib", "max_issues_repo_head_hexsha": "ee2de22acbb5e5441c810a45b33bbd7b3a87d669", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-11T15:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-11T15:35:14.000Z", "max_forks_repo_path": "test-suite/fdcev.cpp", "max_forks_repo_name": "NJeanray/QuantLib", "max_forks_repo_head_hexsha": "ee2de22acbb5e5441c810a45b33bbd7b3a87d669", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-11T08:32:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T08:32:27.000Z", "avg_line_length": 36.1733333333, "max_line_length": 86, "alphanum_fraction": 0.5571937584, "num_tokens": 2085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5731803448576624}}
{"text": "//\n//  soptolsTestQuadratic.cpp\n//\n//\n//  Created by Jose V. Alcala Burgos on 7/30/13.\n//  Copyright [2013] Jose V. Alcala Burgos\n//\n\n#include \"base/soptolsTestQuadratic.h\"\n\n// System\n#include <armadillo>\n\n#include <cmath>\n#include <ctime>\n#include <iostream>\n#include <random>\n\n// Project\n#include \"base/seqols.h\"\n#include \"base/soptols.h\"\n#include \"base/stochasticTools.h\"\n\nusing arma::mat;\n\n\nint main(int argc, char * const argv[]) {\n  // Initialize the random number generator\n  mt19937 generator;\n\n  // Simulation parameters\n  int num_parameters = 4;\n  int num_initial_samples = num_parameters + 1;  // Ensure precision full rank\n\n  // Inititalize the quadratic test parameters randomly.\n\n  // The Hessian matrix for the quadratic loss.\n  mat H = randu<mat>(num_parameters, num_parameters);\n  H = H * H.t();  // Hessian is symmetric and positive definite\n\n  // The covariance matrix for the quadratic loss.\n  mat Sigma = randu<mat>(num_parameters, num_parameters);\n  Sigma = Sigma * Sigma.t();\n\n  // The parameter we will try to estimate.\n  mat alpha_optimal = randu<mat>(1, num_parameters);\n\n  // Print to screen the parameters created randomly.\n  H.print(\" H : \");\n  mat G = H.i();\n  G.print(\" G : \");\n  Sigma.print(\" Sigma : \");\n  alpha_optimal.print(\" alpha_optimal : \");\n\n  // Construct the stochastic gradient sampler\n  stochasticGradient stoGrad(H, Sigma, alpha_optimal);\n\n  // Create the first num_initial_samples + 1  samples randomly\n  // The matrix with num_initial_samples + 1 initial predictors\n  mat X = randu<mat>(num_initial_samples + 1, num_parameters);\n\n  // Save parameters to csv files\n  H.save(\"output/H.mat\", csv_ascii);\n  Sigma.save(\"output/Sigma.mat\", csv_ascii);\n  alpha_optimal.save(\"output/alpha_optimal.mat\", csv_ascii);\n  X.save(\"output/X.mat\", csv_ascii);\n\n  // Construct the Stochastic Optimization\n  SOptOls sopt(stoGrad, X);\n  sopt.optimize(generator);\n\n  return 0;\n}\n", "meta": {"hexsha": "092b9e1d94c887f80f6ac1dad3213a24b858d804", "size": 1906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/soptolsTestQuadratic.cpp", "max_stars_repo_name": "vidalalcala/sopt-ols", "max_stars_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/soptolsTestQuadratic.cpp", "max_issues_repo_name": "vidalalcala/sopt-ols", "max_issues_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/soptolsTestQuadratic.cpp", "max_forks_repo_name": "vidalalcala/sopt-ols", "max_forks_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7567567568, "max_line_length": 78, "alphanum_fraction": 0.7056663169, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.5731803448046091}}
{"text": "/**\n * \\file      probability-law-simulation.hpp\n * \\author    Mehdi Benallegue\n * \\date       2013\n * \\brief\n *\n *\n *\n */\n\n#ifndef SENSORSSIMULATIONPROBABILITYLAWSIMULATIONHPP\n#define SENSORSSIMULATIONPROBABILITYLAWSIMULATIONHPP\n\n#include <boost/random.hpp>\n\n#include <state-observation/api.h>\n#include <state-observation/tools/definitions.hpp>\n\nnamespace stateObservation\n{\nnamespace tools\n{\nclass STATE_OBSERVATION_DLLAPI ProbabilityLawSimulation\n{\npublic:\n  /// gets a scalar Gaussian random variable\n  /// having a given bias and standard deviation(std)\n  /// default is the cetered unit Gaussian\n  double getGaussianScalar(double std = 1, double bias = 0);\n\n  /// gets vector Gaussian random variable\n  /// having a given bias and standard deviation(std)\n  static Matrix getGaussianVector(const Matrix & std, const Matrix & bias, Index rows, Index cols = 1);\n\nprotected:\n  static boost::lagged_fibonacci1279 gen_;\n};\n\n} // namespace tools\n} // namespace stateObservation\n\n#endif // SENSORSSIMULATIONPROBABILITYLAWSIMULATIONHPP\n", "meta": {"hexsha": "6f20e516976eb7eb17ff2fa2552e1547c9f5785f", "size": 1033, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/state-observation/tools/probability-law-simulation.hpp", "max_stars_repo_name": "arntanguy/state-observation", "max_stars_repo_head_hexsha": "333d826eb3790f6f65c5694018052dbbc7aec9fc", "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/state-observation/tools/probability-law-simulation.hpp", "max_issues_repo_name": "arntanguy/state-observation", "max_issues_repo_head_hexsha": "333d826eb3790f6f65c5694018052dbbc7aec9fc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-03T04:30:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-03T04:30:00.000Z", "max_forks_repo_path": "include/state-observation/tools/probability-law-simulation.hpp", "max_forks_repo_name": "arntanguy/state-observation", "max_forks_repo_head_hexsha": "333d826eb3790f6f65c5694018052dbbc7aec9fc", "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.023255814, "max_line_length": 103, "alphanum_fraction": 0.7550822846, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.682573734412324, "lm_q1q2_score": 0.5731803447515555}}
{"text": "#pragma once\n\n#include <tf/tf.h>\n\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n\n// std\n#include <iostream>\n\n#include \"darkroom/Triangulation.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\nnamespace PoseEstimatorSensorDistance {\n\n// Generic functor for Eigen Levenberg-Marquardt minimizer\n    template<typename _Scalar, int NX = Dynamic, int NY = Dynamic>\n    struct Functor {\n        typedef _Scalar Scalar;\n        enum {\n            InputsAtCompileTime = NX,\n            ValuesAtCompileTime = NY\n        };\n        typedef Matrix<Scalar, InputsAtCompileTime, 1> InputType;\n        typedef Matrix<Scalar, ValuesAtCompileTime, 1> ValueType;\n        typedef Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime> JacobianType;\n\n        const int m_inputs, m_values;\n\n        Functor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n\n        Functor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n        int inputs() const { return m_inputs; }\n\n        int values() const { return m_values; }\n    };\n\n    struct PoseEstimator : Functor<double> {\n        /**\n         * Default amount of sensors needed for Eigen templated structure\n         * @param numberOfSamples the pose will be estimated using this amount of samples\n         * @param distanceBetweenSensors the distance between the two sensors in mm\n         */\n        PoseEstimator(int numberOfSamples, double distanceBetweenSensors, MatrixXd &rays0_A, MatrixXd &rays0_B,\n                      MatrixXd &rays1_A, MatrixXd &rays1_B);\n\n        /**\n         * This is the function that is called in each iteration\n         * @param x the pose vector (3 rotational 3 translational parameters)\n         * @param fvec the error function (the difference between the sensor positions)\n         * @return\n         */\n        int operator()(const VectorXd &x, VectorXd &fvec) const;\n\n        VectorXd pose;\n        MatrixXd rays0_A, rays0_B, rays1_A, rays1_B; // rays of each lighthouse pointing to the sensors\n        double distanceBetweenSensors;\n        int numberOfSamples;\n        Matrix4d RT_A, RT_B;\n        static int counter;\n    };\n\n}", "meta": {"hexsha": "d4f6a1cc033ea35543b0ae5c2753dc67919c9aa0", "size": 2238, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/darkroom/PoseEstimatorSensorDistance.hpp", "max_stars_repo_name": "Roboy/DarkRoom_rviz", "max_stars_repo_head_hexsha": "8f049218bc600d4b179303493a70bfe2389df73c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-06T15:34:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-04T00:22:54.000Z", "max_issues_repo_path": "include/darkroom/PoseEstimatorSensorDistance.hpp", "max_issues_repo_name": "Roboy/DarkRoom_rviz", "max_issues_repo_head_hexsha": "8f049218bc600d4b179303493a70bfe2389df73c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/darkroom/PoseEstimatorSensorDistance.hpp", "max_forks_repo_name": "Roboy/DarkRoom_rviz", "max_forks_repo_head_hexsha": "8f049218bc600d4b179303493a70bfe2389df73c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4347826087, "max_line_length": 111, "alphanum_fraction": 0.6715817694, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5731803446985015}}
{"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//  Copyright Toon Knapen, Karl Meerbergen\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include \"../../blas/test/random.hpp\"\n\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/lapack/computational/geqrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/ormqr.hpp>\n#include <boost/numeric/bindings/lapack/computational/orgqr.hpp>\n#include <boost/numeric/bindings/lapack/computational/unmqr.hpp>\n#include <boost/numeric/bindings/lapack/computational/ungqr.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/conj.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/type_traits/is_complex.hpp>\n#include <boost/mpl/if.hpp>\n\n#include <iostream>\n#include <limits>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\nnamespace tag = boost::numeric::bindings::tag;\n\n// Randomize a matrix\ntemplate <typename M>\nvoid randomize(M& m) {\n   typedef typename M::size_type  size_type ;\n   typedef typename M::value_type value_type ;\n\n   size_type size1 = m.size1() ;\n   size_type size2 = m.size2() ;\n\n   for (size_type i=0; i<size2; ++i) {\n      for (size_type j=0; j<size1; ++j) {\n         m(j,i) = random_value< value_type >() ;\n      }\n   }\n} // randomize()\n\ntemplate <typename M>\nublas::triangular_adaptor<const M, ublas::upper> upper_part(const M& m) {\n   return ublas::triangular_adaptor<const M, ublas::upper>( m );\n}\n\ntemplate <typename T, typename W>\nint do_memory_type(int n, W workspace) {\n   typedef typename bindings::remove_imaginary<T>::type real_type ;\n   typedef std::complex< real_type >                                            complex_type ;\n\n   typedef ublas::matrix<T, ublas::column_major> matrix_type ;\n   typedef ublas::vector<T>                      vector_type ;\n\n   // Set matrix\n   matrix_type a( n, n );\n   vector_type tau( n );\n\n   randomize( a );\n   matrix_type a2( a );\n   matrix_type a3( a );\n\n   // Compute QR factorization.\n   lapack::geqrf( a, tau, workspace ) ;\n\n   // Apply the orthogonal transformations to a2\n   if( boost::is_complex<T>::value ) {\n        lapack::unmqr( tag::left(), bindings::conj( a ), tau, a2, workspace );\n   } else {\n        lapack::unmqr( tag::left(), bindings::trans( a ), tau, a2, workspace );\n   }\n\n   // The upper triangular parts of a and a2 must be equal.\n   if (norm_frobenius( upper_part( a - a2 ) )\n            > std::numeric_limits<real_type>::epsilon() * 10.0 * norm_frobenius( upper_part( a ) ) ) return 255 ;\n\n   // Generate orthogonal matrix\n   lapack::ungqr( a, tau, workspace );\n\n   // The result of lapack::ormqr and the equivalent matrix product must be equal.\n   if (norm_frobenius( a2 - prod(herm(a), a3) )\n            > std::numeric_limits<real_type>::epsilon() * 10.0 * norm_frobenius( a2 ) ) return 255 ;\n\n   return 0 ;\n} // do_value_type()\n\n\n\ntemplate <typename T>\nint do_value_type() {\n   const int n = 8 ;\n   \n   if (do_memory_type<T,lapack::optimal_workspace>( n, lapack::optimal_workspace() ) ) return 255 ;\n   if (do_memory_type<T,lapack::minimal_workspace>( n, lapack::minimal_workspace() ) ) return 255 ;\n\n   ublas::vector<T> work( n );\n   if (do_memory_type<T, lapack::detail::workspace1<ublas::vector<T> > >( n, lapack::workspace(work) ) ) return 255 ;\n   return 0;\n} // do_value_type()\n\n\nint main() {\n   // Run tests for different value_types\n   if (do_value_type<float>()) return 255;\n   if (do_value_type<double>()) return 255;\n   if (do_value_type< std::complex<float> >()) return 255;\n   if (do_value_type< std::complex<double> >()) return 255;\n\n   std::cout << \"Regression test succeeded\\n\" ;\n   return 0;\n}\n\n", "meta": {"hexsha": "b1984cb501492bfc020b985346efc30ecebba48b", "size": 3946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_geqrf.cpp", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-08-02T14:21:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-05T10:34:45.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_geqrf.cpp", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T21:30:35.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-08T19:44:18.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_geqrf.cpp", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-28T21:11:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-28T21:11:52.000Z", "avg_line_length": 32.3442622951, "max_line_length": 117, "alphanum_fraction": 0.6773948302, "num_tokens": 1098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5731555833264491}}
{"text": "/*\n *  Distributed under the MIT License (See accompanying file /LICENSE )\n */\n#include \"recti/fractions.hpp\"\n// #include <boost/multiprecision/cpp_int.hpp>\n#include <doctest/doctest.h>\n#include <iostream>\n\nusing namespace fun;\n\nTEST_CASE(\"GCD\")\n{\n    CHECK(gcd(0, 0) == 0);\n    CHECK(gcd(1, 0) == 1);\n    CHECK(gcd(0, 1) == 1);\n    CHECK(gcd(-1, 0) == 1);\n    CHECK(gcd(0, -1) == 1);\n    CHECK(lcm(0, 0) == 0);\n    CHECK(lcm(1, 0) == 0);\n    CHECK(lcm(0, 1) == 0);\n}\n\nTEST_CASE(\"Fraction\")\n{\n    // using boost::multiprecision::cpp_int;\n    // static_assert(Integral<cpp_int>);\n    const auto a = 3;\n    const auto b = 4;\n    const auto c = 5;\n    const auto d = 6;\n    // const auto f = -30;\n    // const auto g = 4;\n    // const auto z = 0;\n    // const auto h = -g;\n\n    auto p = Fraction {a, b};\n    std::cout << p << '\\n';\n    const auto q = Fraction {c, d};\n\n    CHECK(p == Fraction(30, 40));\n    CHECK(2 * p == Fraction(6, 4));\n    p *= 2;\n    CHECK(p == Fraction(6, 4));\n    CHECK(p / 2 == Fraction(30, 40));\n\n    p /= 2;\n    CHECK(p + q == Fraction(19, 12));\n    CHECK(p - q == Fraction(-1, 12));\n    CHECK(p < q);\n    CHECK(p != q);\n    CHECK(0 < p);\n}\n\nTEST_CASE(\"Fraction Special Cases\")\n{\n    const auto p = Fraction {3, 4};\n    const auto inf = Fraction {1, 0};\n    // const auto nan = Fraction {0, 0};\n    const auto zero = Fraction {0, 1};\n\n    CHECK(-inf < zero);\n    CHECK(zero < inf);\n    CHECK(-inf < p);\n    CHECK(p < inf);\n    CHECK(inf == inf);\n    CHECK(-inf < inf);\n    CHECK(inf == inf * p);\n    CHECK(inf == inf * inf);\n    CHECK(inf == p / zero);\n    CHECK(inf == inf / zero);\n    // CHECK(nan == nan);\n    // CHECK(nan == inf * zero);\n    // CHECK(nan == -inf * zero);\n    // CHECK(nan == inf / inf);\n    // CHECK(nan == nan * zero);\n    // CHECK(nan == nan * nan);\n    // CHECK(nan == inf - inf);\n    CHECK(inf == inf + inf);\n    CHECK(inf + p == inf);   // ???\n    CHECK(-inf + p == -inf); // ???\n    CHECK(p + zero == p);\n}\n", "meta": {"hexsha": "badc6ce3f4490b28502118c910bbe5c32a596e9a", "size": 1957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/test/src/test_frac.cpp", "max_stars_repo_name": "luk036/physdes", "max_stars_repo_head_hexsha": "1a6a6c06a92798cc36d5efd70a968f545d406568", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-30T04:51:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-30T04:51:25.000Z", "max_issues_repo_path": "lib/test/src/test_frac.cpp", "max_issues_repo_name": "luk036/physdes", "max_issues_repo_head_hexsha": "1a6a6c06a92798cc36d5efd70a968f545d406568", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-19T10:28:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-11T04:11:51.000Z", "max_forks_repo_path": "lib/test/src/test_frac.cpp", "max_forks_repo_name": "luk036/physdes", "max_forks_repo_head_hexsha": "1a6a6c06a92798cc36d5efd70a968f545d406568", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-11T05:12:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T05:12:37.000Z", "avg_line_length": 23.578313253, "max_line_length": 71, "alphanum_fraction": 0.5063873275, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5731555806599642}}
{"text": "/***************************************************************************\n *\n *   Copyright (C) 2021 by fxzjshm\n *   Licensed under the GNU General Public License, version 2.0\n *\n ***************************************************************************/\n\n// pad missing channels with 0\n// used for converting filterbank file to wave\n\n#include <boost/program_options.hpp>\n#include <filesystem>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n\n#include \"io.hpp\"\n#include \"types.h\"\n\n// Edited from https://www.geeksforgeeks.org/program-find-gcd-floating-point-numbers/\ntemplate <typename T, typename U, typename V>\nT gcd(T a, U b, V epsilon) {\n    if (a < b) {\n        std::swap(a, b);\n    }\n\n    if (std::abs(b) < epsilon) {\n        return a;\n    }\n    return (gcd(b, a - std::floor(a / b) * b, epsilon));\n}\n\nint main(int argc, char **argv) {\n    boost::program_options::options_description all_option(\"Options\");\n    using boost::program_options::value;\n    /* clang-format off */\n    all_option.add_options()\n        (\"help,h\", \"Show help message\")\n        (\"samples_count\", value<size_t>()->required(), \"Number of samples in file\")\n        (\"input_file,f\", value<std::string>()->required(), \"Input file\")\n        (\"output_file,o\", value<std::string>()->required(), \"Output file\")\n        (\"in_text\", \"Read input file as text\")\n        (\"out_text\", \"Write output file as text\")\n        (\"fmax\", value<float>()->required(), \"Max of frequency of input channel\")\n        (\"df\", value<float>()->required(), \"Input Channel bandwidth\")\n        (\"nchans\", value<size_t>()->required(), \"Number of channels in input file\")\n        (\"epsilon\", value<float>()->required(), \"Minial channel bandwidth in output file\")\n        (\"fmax_out\", value<float>()->required(), \"Max of frequency of out channel\")\n        (\"pad_value_real,pad_value\", value<float>()->default_value(0.0f), \"Value to fill real part in padded area\")\n        (\"pad_imaginary_part\", \"Whether to pad imaginary part\")\n        (\"pad_value_imaginary\", value<float>()->default_value(0.0f), \"Value to fill real part in padded area\")\n    ;\n    /* clang-format on */\n    boost::program_options::positional_options_description p;\n    p.add(\"input_file\", 1);\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(all_option).positional(p).run(), vm);\n    boost::program_options::notify(vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << all_option << std::endl;\n        return 0;\n    }\n\n    float in_fmax = vm[\"fmax\"].as<float>();\n    float in_df = std::abs(vm[\"df\"].as<float>());\n    float gcd_epsilon = vm[\"epsilon\"].as<float>();\n    float out_df = gcd(in_fmax, in_df, gcd_epsilon);\n    size_t nchans = vm[\"nchans\"].as<size_t>();\n    float in_fmin = in_fmax - in_df * (nchans - 1);\n    size_t samples_count = vm[\"samples_count\"].as<size_t>();\n    float out_fmax;\n    if (vm.count(\"fmax_out\")) {\n        out_fmax = vm[\"fmax_out\"].as<float>();\n    } else {\n        out_fmax = in_fmax;\n    }\n    if (out_fmax < in_fmax) {\n        std::cerr << \"Warn: setting out_fmax to in_max\" << std::endl;\n    }\n    size_t out_seg_length = static_cast<size_t>(std::round(out_fmax / out_df)) + 1;\n    float pad_value_real = vm[\"pad_value_real\"].as<float>();\n\n    std::cout << \"out_df = \" << out_df << std::endl\n              << \"out_seg_length = \" << out_seg_length << std::endl;\n\n    std::vector<data_type> h_in;\n    std::string in_file_name = vm[\"input_file\"].as<std::string>();\n    std::string out_file_name = vm[\"output_file\"].as<std::string>();\n    size_t in_file_nsamps;\n    if (vm.count(\"in_text\")) {\n        std::ifstream in_file_stream(in_file_name);\n        // h_in = std::vector<data_type>(std::istream_iterator<data_type>(in_file_stream), {});\n        data_type tmp;\n        while (in_file_stream >> tmp) {\n            h_in.push_back(tmp);\n        }\n        in_file_nsamps = h_in.size();\n    } else {\n        FILE *in_file_stream;\n        in_file_stream = fopen(in_file_name.c_str(), \"rb\");\n        size_t in_file_length = std::filesystem::file_size(in_file_name);\n        in_file_nsamps = in_file_length / sizeof(data_type);\n        h_in.resize(in_file_nsamps);\n        fread(&h_in[0], 1, in_file_length, in_file_stream);\n        fclose(in_file_stream);\n    }\n    write_vector(h_in, \"pad_fil-h_in.txt\");\n\n    std::vector<data_type> h_out_real; // output is padded filterbank\n    std::fill(h_out_real.begin(), h_out_real.end(), pad_value_real);\n    h_out_real.resize(out_seg_length * samples_count, pad_value_real);\n\n    for (size_t s = 0; s < samples_count; s++) {\n        for (size_t i = 0; i < nchans; i++) {\n            size_t in_idx = nchans * s + i;\n            float f_current = in_fmax - in_df * i;\n            size_t f_current_idx = static_cast<size_t>(std::round(f_current / out_df));\n            assert(f_current_idx < out_seg_length);\n            size_t out_idx = out_seg_length * s + f_current_idx;\n            if (in_idx < h_in.size() && out_idx < h_out_real.size()) {\n                h_out_real[out_idx] = h_in[in_idx];\n            } else {\n                std::cout << \"Warning: \"\n                          << \"in_idx = \" << in_idx << \", \"\n                          << \"h_in.size() = \" << h_in.size() << \", \"\n                          << \"out_idx = \" << out_idx << \", \"\n                          << \"h_out_real.size() = \" << h_out_real.size() << std::endl;\n            }\n        }\n    }\n\n    if (vm.count(\"pad_imaginary_part\")) {\n        float pad_value_imaginary = vm[\"pad_value_imaginary\"].as<float>();\n        std::vector<data_type> h_out_complex(2 * h_out_real.size());\n        for (size_t i = 0; i < h_out_real.size(); i++) {\n            h_out_complex[2 * i] = h_out_real[i];\n            h_out_complex[2 * i + 1] = pad_value_imaginary;\n        }\n        if (vm.count(\"out_text\")) {\n            write_vector(h_out_complex, 2 * out_seg_length, samples_count, out_file_name);\n        } else {\n            write_vector_binary(h_out_complex, 2 * out_seg_length * samples_count, out_file_name);\n        }\n    } else {\n        if (vm.count(\"out_text\")) {\n            write_vector(h_out_real, out_seg_length, samples_count, out_file_name);\n        } else {\n            write_vector_binary(h_out_real, out_seg_length * samples_count, out_file_name);\n        }\n    }\n\n    return 0;\n}", "meta": {"hexsha": "2b1614e002bd67f7f0e3c1496141dc385afe8619", "size": 6343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/pad_filterbank.cpp", "max_stars_repo_name": "fxzjshm/filterbank-generation-test", "max_stars_repo_head_hexsha": "f432657c27282dbc88804e2eb7e5fe12aff3b7ce", "max_stars_repo_licenses": ["CC-BY-2.0"], "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/pad_filterbank.cpp", "max_issues_repo_name": "fxzjshm/filterbank-generation-test", "max_issues_repo_head_hexsha": "f432657c27282dbc88804e2eb7e5fe12aff3b7ce", "max_issues_repo_licenses": ["CC-BY-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/pad_filterbank.cpp", "max_forks_repo_name": "fxzjshm/filterbank-generation-test", "max_forks_repo_head_hexsha": "f432657c27282dbc88804e2eb7e5fe12aff3b7ce", "max_forks_repo_licenses": ["CC-BY-2.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.1883116883, "max_line_length": 135, "alphanum_fraction": 0.5860003153, "num_tokens": 1599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5731555781405752}}
{"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\u2500\u2500\u2500\u25004\n   * \u2502    \u2502\n   * \u2502    \u2502\n   * 1\u2500\u2500\u2500\u25003\n   * ```\n   *\n   *\n   * Numbering of vertices in 3D\n   *\n   * ```\n   *      4\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25008\n   *     \u2571\u2502       \u2571\u2502\n        \u2571 \u2502      \u2571 \u2502\n   *   \u2571  \u2502     \u2571  \u2502\n   *  \u2571   \u2502    \u2571   \u2502\n   * 2\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25006 \u2500\u2500\u25007\n   * \u2502   \u25713   \u2502   \u2571\n   * \u2502  \u2571     \u2502  \u2571\n     \u2502 \u2571      \u2502 \u2571\n   * \u2502\u2571       \u2502\u2571\n   * 1\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25005\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 `\u03c4[n, i, j]` are constant in each cell n. They induce the\n   * average strains `\u03b5[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 `\u03c4`,\n   *            `\u03c4^[k, :, :]`\n   * @param eta the `k`-th Fourier component of `-\u03b5`, `-\u03b5^[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": "#include <Eigen/Dense>\n#include <unsupported/Eigen/AutoDiff>\n#include \"gtest/gtest.h\"\n#define SOLVER_DEBUG\n#define SQP_SOLVER_PRINTING\n#define QP_SOLVER_PRINTING\n#define SOLVER_ASSERT(x) EXPECT_TRUE(x)\n#include \"solvers/sqp.hpp\"\n\nusing namespace sqp;\n\nnamespace sqp_test_autodiff {\n\ntemplate <typename _Derived, typename _Scalar, int _VAR_SIZE, int _NUM_EQ=0, int _NUM_INEQ=0>\nstruct ProblemBase {\n    enum {\n        VAR_SIZE = _VAR_SIZE,\n        NUM_EQ = _NUM_EQ,\n        NUM_INEQ = _NUM_INEQ,\n    };\n\n    using Scalar = double;\n    using var_t = Eigen::Matrix<Scalar, VAR_SIZE, 1>;\n    using grad_t = Eigen::Matrix<Scalar, VAR_SIZE, 1>;\n    using hessian_t = Eigen::Matrix<Scalar, VAR_SIZE, VAR_SIZE>;\n    using MatX = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n\n    using b_eq_t = Eigen::Matrix<Scalar, NUM_EQ, 1>;\n    using A_eq_t = Eigen::Matrix<Scalar, NUM_EQ, VAR_SIZE>;\n    using b_ineq_t = Eigen::Matrix<Scalar, NUM_INEQ, 1>;\n    using A_ineq_t = Eigen::Matrix<Scalar, NUM_INEQ, VAR_SIZE>;\n    using box_t = var_t;\n\n    using ADScalar = Eigen::AutoDiffScalar<grad_t>;\n    using ad_var_t = Eigen::Matrix<ADScalar, VAR_SIZE, 1>;\n    using ad_eq_t = Eigen::Matrix<ADScalar, NUM_EQ, 1>;\n    using ad_ineq_t = Eigen::Matrix<ADScalar, NUM_INEQ, 1>;\n\n    template <typename vec>\n    void AD_seed(vec &x)\n    {\n        for (int i=0; i<x.rows(); i++) {\n            x[i].derivatives().coeffRef(i) = 1;\n        }\n    }\n\n    void cost_linearized(const var_t& x, grad_t &grad, Scalar &cst)\n    {\n        ad_var_t _x = x;\n        ADScalar _cst;\n        AD_seed(_x);\n        /* Static polymorphism using CRTP */\n        static_cast<_Derived*>(this)->cost(_x, _cst);\n        cst = _cst.value();\n        grad = _cst.derivatives();\n    }\n\n    void constraint_linearized(const var_t& x, A_eq_t& A_eq, b_eq_t& b_eq, A_ineq_t& A_ineq, b_ineq_t& b_ineq, box_t& lbx, box_t& ubx)\n    {\n        ad_eq_t ad_eq;\n        ad_ineq_t ad_ineq;\n\n        ad_var_t _x = x;\n        AD_seed(_x);\n        static_cast<_Derived*>(this)->constraint(_x, ad_eq, ad_ineq, lbx, ubx);\n\n        for (int i = 0; i < ad_eq.rows(); i++) {\n            b_eq[i] = ad_eq[i].value();\n            Eigen::Ref<MatX> deriv = ad_eq[i].derivatives().transpose();\n            A_eq.row(i) = deriv;\n        }\n\n        for (int i = 0; i < ad_ineq.rows(); i++) {\n            b_ineq[i] = ad_ineq[i].value();\n            Eigen::Ref<MatX> deriv = ad_ineq[i].derivatives().transpose();\n            A_ineq.row(i) = deriv;\n        }\n    }\n};\n\n\nstruct SOFCModel : public ProblemBase<SOFCModel,\n                                double,\n                                /* Nx    */5,\n                                /* Neq   */1,\n                                /* Nineq */2>  {\n    const Scalar delta_air = 1e-5;\n    const Scalar delta_cool = 1e-4;\n    const Scalar LHV_CH4 = 833.33;      // [J/kg]\n    const Scalar N_cell = 70;\n    const Scalar F = 96486.00/16e3;    // [C/kg]\n    const Scalar Pel_ref = 1000.00;    // [W]\n    //const Scalar conv_Lm_to_mols = 7.4356e-4;    // [W]\n\n    //Eigen::Matrix<Scalar, 2, 1> SOLUTION = {0.7071067812, 0.707106781};\n\n    template <typename DerivedA, typename DerivedB>\n    void cost(const DerivedA& x, DerivedB &cst)\n    {\n        // x =[u (4), U_cell(1), theta(15)]\n        // cst = -N_cell * x(4) * x(2)/(x(0) * LHV_CH4) + delta_air * pow(x(1), 2) + delta_cool * pow(x(3), 2);\n        cst = -1*N_cell * x(4) * x(2) + 1*(1*delta_air * pow(x(1), 2) + 1*delta_cool * pow(x(3), 2))*(x(0) * LHV_CH4);\n    }\n\n    template <typename A, typename B, typename C>\n    void constraint(const A& x, B& eq, C& ineq, box_t& lbx, box_t& ubx)\n    {\n        // nu < 0.8, lambda > 4\n        ineq << N_cell*x(2) - 0.8*(8*F*x(0)), 4.0*(2.0*x(0)) - x(1);\n        //ineq << N_cell*x(2)/(8*F*x(0)) - 0.8, 3.0 - x(1)/(2.0*x(0));\n        // x^2 + y^2 == 1\n        // eq << x.squaredNorm() - 1;\n        // SOFC dynamics, function - f\n        eq << Pel_ref - N_cell * x(4) * x(2);//, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n\n        const Scalar infinity = std::numeric_limits<Scalar>::infinity();\n        lbx << 1, 85, 0, 0, 0.76;//, 650, -infinity, -infinity, -infinity, 650, -infinity, -infinity, -infinity, -infinity, -infinity, -infinity, -infinity, -infinity, -infinity, -infinity;\n        ubx << 7, 200, 50, 40, infinity;//, 750, infinity, infinity, infinity, 790, 890, infinity, infinity, infinity, infinity, infinity, infinity, infinity, infinity, infinity;\n    }\n};\n\ntemplate <typename Solver>\nvoid callback(void *solver_p)\n{\n    Solver& s = *static_cast<Solver*>(solver_p);\n\n    Eigen::IOFormat fmt(Eigen::StreamPrecision, 0, \", \", \",\", \"[\", \"],\");\n    std::cout << s.info().iter << \" \" << s._x.transpose().format(fmt) << s._qp_solver.info().status << \" \" << s._cost << std::endl;\n}\n\n#if 0 // suspended, see issue #13\nTEST(SQPTestCase, TestConstrainedRosenbrock) {\n    using Solver = SQP<ConstrainedRosenbrock>;\n    ConstrainedRosenbrock problem;\n    Solver solver;\n    Eigen::Vector2d x0, x;\n    Eigen::Vector4d y0;\n    y0.setZero();\n\n    x0 << 0, 0;\n    solver.settings().max_iter = 1000;\n    solver.settings().line_search_max_iter = 10;\n    // solver.settings().iteration_callback = callback<Solver>;\n    solver.solve(problem, x0, y0);\n\n    x = solver.primal_solution();\n\n    std::cout << \"iter \" << solver.info().iter << std::endl;\n    std::cout << \"Solution \" << x.transpose() << std::endl;\n\n    EXPECT_TRUE(x.isApprox(problem.SOLUTION, 1e-2));\n    EXPECT_LT(solver.info().iter, solver.settings().max_iter);\n}\n#endif\n\n\nTEST(SQPTestCase, TestSOFCModel) {\n    using Solver = SQP<SOFCModel>;\n    SOFCModel problem;\n    Solver solver;\n    Eigen::Matrix<double, 5, 1> x;\n    Eigen::Matrix<double, 5, 1> x0;\n    x0 << 1.75, 150, 18, 30, 0.9;//, 500, 710, 711, 712, 713, 1000, 800, 700, 750, 800, 700, 750, 800, 700, 750;\n\n    solver.settings().max_iter = 500;\n    solver.settings().line_search_max_iter = 1;\n    //solver._qp_solver.settings().adaptive_rho = true;\n    solver._qp_solver.settings().verbose = false;\n    solver._qp_solver.settings().max_iter = 1000;\n    solver._qp_solver.settings().check_termination = 25;\n    solver._qp_solver.settings().adaptive_rho_interval = 25;\n    solver.settings().iteration_callback = callback<Solver>;\n    solver.solve(problem, x0);\n\n    x = solver.primal_solution();\n\n    std::cout << \"iter \" << solver.info().iter << std::endl;\n    std::cout << \"Solution \" << x.transpose() << std::endl;\n\n    EXPECT_LT(solver.info().iter, solver.settings().max_iter);\n}\n/*\nstruct Rosenbrock : public ProblemBase<Rosenbrock,\n                                       double,\n                                       2,\n                                       0,\n                                       0>  {\n    const Scalar a = 1;\n    const Scalar b = 100;\n    Eigen::Vector2d SOLUTION = {1.0, 1.0};\n\n    template <typename DerivedA, typename DerivedB>\n    void cost(const DerivedA& x, DerivedB &cst)\n    {\n        // (a-x)^2 + b*(y-x^2)^2\n        cst = pow(a - x(0), 2) + b * pow(x(1) - pow(x(0), 2), 2);\n    }\n\n    template <typename A, typename B, typename C>\n    void constraint(const A& x, B& eq, C& ineq, box_t& lbx, box_t& ubx)\n    {\n        // unconstrained\n        const Scalar infinity = std::numeric_limits<Scalar>::infinity();\n        lbx << -infinity, -infinity;\n        ubx << infinity, infinity;\n    }\n};\n\nstruct SimpleNLP : ProblemBase<SimpleNLP, double, 2, 0, 2> {\n    var_t SOLUTION = {1, 1};\n\n    template <typename A, typename B>\n    void cost(const A& x, B& cst)\n    {\n        cst = -x(0) -x(1);\n    }\n\n    template <typename A, typename B, typename C>\n    void constraint(const A& x, B& eq, C& ineq, var_t& lbx, var_t& ubx)\n    {\n        const Scalar infinity = std::numeric_limits<Scalar>::infinity();\n        ineq << 1 - x.squaredNorm(),\n                  x.squaredNorm() - 2; // 1 <= x0^2 + x1^2 <= 2\n        lbx << 0, 0; // x0 > 0 and x1 > 0\n        ubx << infinity, infinity;\n    }\n\n};\n\nTEST(SQPTestCase, TestSimpleNLP) {\n    using Solver = SQP<SimpleNLP>;\n    SimpleNLP problem;\n    Solver solver;\n\n    // feasible initial point\n    Eigen::Vector2d x;\n    Eigen::Vector2d x0 = {1.2, 0.1};\n    Eigen::Vector4d y0;\n    y0.setZero();\n\n    solver.settings().max_iter = 100;\n    solver.settings().line_search_max_iter = 4;\n    solver.settings().iteration_callback = callback<Solver>;\n    solver.solve(problem, x0, y0);\n\n    x = solver.primal_solution();\n\n    std::cout << \"iter \" << solver.info().iter << std::endl;\n    std::cout << \"qp_iter \" << solver.info().qp_solver_iter << std::endl;\n    std::cout << \"Solution \" << x.transpose() << std::endl;\n\n    EXPECT_TRUE(x.isApprox(problem.SOLUTION, 1e-2));\n    EXPECT_LT(solver.info().iter, solver.settings().max_iter);\n}\n*/\n} // namespace sqp_test_autodiff\n", "meta": {"hexsha": "36f9bd69e8293b475b84f7c72b4c80ee80c018a7", "size": 8722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "polympc/tests/solvers/sqp/sofc_test.cpp", "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/tests/solvers/sqp/sofc_test.cpp", "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/tests/solvers/sqp/sofc_test.cpp", "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": 33.9377431907, "max_line_length": 189, "alphanum_fraction": 0.5807154322, "num_tokens": 2737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5731555618474719}}
{"text": "#include <omp.h>\n// #define EIGEN_DONT_PARALLELIZE\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <algorithm>\n#include <chrono>\n#include <experimental/filesystem>\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <unordered_map>\n#include <unordered_set>\n\n#include \"data_loader.h\"\n\nnamespace fs = std::experimental::filesystem;\nusing DataType = float;\n// using Eigen::ColMajor is Eigen restriction -  todense method always returns\n// matrices in ColMajor order\nusing Matrix =\n    Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;\n\nusing SparseMatrix = Eigen::SparseMatrix<DataType, Eigen::ColMajor>;\n\nusing DiagonalMatrix =\n    Eigen::DiagonalMatrix<DataType, Eigen::Dynamic, Eigen::Dynamic>;\n\n// Initialize matrix with random values and normalize them\nMatrix InitialiseMatrix(Eigen::Index rows, Eigen::Index cols) {\n  Matrix mat = Matrix::Random(rows, cols).array().abs();\n  auto row_sums = mat.rowwise().sum();\n  mat.array().colwise() /= row_sums.array();\n  return mat;\n}\n\nMatrix RatingsPredictions(const Matrix& x, const Matrix& y) {\n  return x * y.transpose();\n}\n\nDataType CalculateWeightedMse(const Matrix& x,\n                              const Matrix& y,\n                              const SparseMatrix& p,\n                              const SparseMatrix& ratings_matrix,\n                              DataType alpha) {\n  Matrix c(ratings_matrix);\n  c.array() *= alpha;\n  c.array() += 1.0;\n\n  Matrix diff(p - RatingsPredictions(x, y));\n  diff = diff.array().pow(2.f);\n\n  Matrix weighted_diff = c.array() * diff.array();\n  return weighted_diff.array().mean();\n}\n\nvoid PrintRecommendations(const Matrix& ratings_matrix,\n                          const Matrix& ratings_matrix_pred,\n                          const std::vector<std::string>& movie_titles) {\n  // auto m = ratings_matrix.rows();\n  auto n = ratings_matrix.cols();\n  std::vector<std::string> liked;\n  std::vector<std::string> recommended;\n  for (Eigen::Index u = 0; u < 5; ++u) {\n    for (Eigen::Index i = 0; i < n; ++i) {\n      DataType orig_value = ratings_matrix(u, i);\n      if (orig_value >= 3.f) {\n        liked.push_back(movie_titles[static_cast<size_t>(i)]);\n      }\n      DataType pred_value = ratings_matrix_pred(u, i);\n      if (pred_value >= 0.8f && orig_value < 1.f) {\n        recommended.push_back(movie_titles[static_cast<size_t>(i)]);\n      }\n    }\n    std::cout << \"\\nUser \" << u << \" liked :\";\n    for (auto& l : liked) {\n      std::cout << l << \"; \";\n    }\n    std::cout << \"\\nUser \" << u << \" recommended :\";\n    for (auto& r : recommended) {\n      std::cout << r << \"; \";\n    }\n    std::cout << std::endl;\n    liked.clear();\n    recommended.clear();\n  }\n}\n\nint main(int argc, char** argv) {\n  if (argc == 2) {\n    Eigen::initParallel();\n    auto root_path = fs::path(argv[1]);\n    if (fs::exists(root_path)) {\n      SparseMatrix ratings_matrix;  // user-item ratings\n      SparseMatrix p;               // binary variables\n      std::vector<std::string> movie_titles;\n      {\n        std::cout << \"Data loading ..\" << std::endl;\n        // load data\n        auto movies_file = root_path / \"movies.csv\";\n        auto movies = LoadMovies(movies_file);\n\n        auto ratings_file = root_path / \"ratings.csv\";\n        auto ratings = LoadRatings(ratings_file);\n\n        std::cout << \"Data loaded\" << std::endl;\n\n        // merge movies and users\n        std::cout << \"Data merging...\" << std::endl;\n        // fill matrix\n        ratings_matrix.resize(static_cast<Eigen::Index>(ratings.size()),\n                              static_cast<Eigen::Index>(movies.size()));\n        ratings_matrix.setZero();\n        p.resize(ratings_matrix.rows(), ratings_matrix.cols());\n        p.setZero();\n\n        movie_titles.resize(movies.size());\n\n        Eigen::Index user_idx = 0;\n        for (auto& r : ratings) {\n          for (auto& m : r.second) {\n            auto mi = movies.find(m.first);\n            Eigen::Index movie_idx = std::distance(movies.begin(), mi);\n            movie_titles[static_cast<size_t>(movie_idx)] = mi->second;\n            ratings_matrix.insert(user_idx, movie_idx) =\n                static_cast<DataType>(m.second);\n            p.insert(user_idx, movie_idx) = 1.0;\n          }\n          ++user_idx;\n        }\n        ratings_matrix.makeCompressed();\n        std::cout << \"Data merged\" << std::endl;\n      }\n\n      // prepare for learning\n      auto m = ratings_matrix.rows();\n      auto n = ratings_matrix.cols();\n\n      std::cout << \"Users \" << m << \" Movies \" << n << std ::endl;\n\n      Eigen::Index n_factors = 100;\n      auto y = InitialiseMatrix(n, n_factors);\n      auto x = InitialiseMatrix(m, n_factors);\n\n      // Test initialization\n      DataType alpha = 40.f;  // confidence level parameter\n      auto w_mse = CalculateWeightedMse(x, y, p, ratings_matrix, alpha);\n      std::cout << \"Initial weighted mse \" << w_mse << std::endl;\n\n      // Precalculate regularization term\n      DataType reg_lambda = 0.1f;\n      SparseMatrix reg =\n          (reg_lambda * Matrix::Identity(n_factors, n_factors)).sparseView();\n\n      // Define diagonal identity terms\n      SparseMatrix user_diag = -1 * Matrix::Identity(n, n).sparseView();\n      SparseMatrix item_diag = -1 * Matrix::Identity(m, m).sparseView();\n\n      // define weights\n      std::cout << \"Calculate weights ...\" << std::endl;\n      std::vector<DiagonalMatrix> user_weights(static_cast<size_t>(m));\n      std::vector<DiagonalMatrix> item_weights(static_cast<size_t>(n));\n      {\n        Matrix weights(ratings_matrix);\n        weights.array() *= alpha;\n        weights.array() += 1;\n\n        for (Eigen::Index i = 0; i < m; ++i) {\n          user_weights[static_cast<size_t>(i)] = weights.row(i).asDiagonal();\n        }\n        for (Eigen::Index i = 0; i < n; ++i) {\n          item_weights[static_cast<size_t>(i)] = weights.col(i).asDiagonal();\n        }\n      }\n\n      // learning loop\n      size_t n_iterations = 5;\n      std::cout << \"Start learning ...\" << std::endl;\n      // omp_set_num_threads(4);\n      for (size_t k = 0; k < n_iterations; ++k) {\n        auto start_time = std::chrono::steady_clock::now();\n        auto yt = y.transpose();\n        auto yty = yt * y;\n\n#pragma omp parallel\n        {\n          Matrix diff;\n          Matrix ytcuy;\n          Matrix a, b, update_y;\n#pragma omp for private(diff, ytcuy, a, b, update_y)\n          for (size_t i = 0; i < static_cast<size_t>(m); ++i) {\n            diff = user_diag;\n            diff += user_weights[i];\n            ytcuy = yty + yt * diff * y;\n            auto p_val = p.row(static_cast<Eigen::Index>(i)).transpose();\n\n            a = ytcuy + reg;\n            b = yt * user_weights[i] * p_val;\n\n            update_y = a.colPivHouseholderQr().solve(b);\n            x.row(static_cast<Eigen::Index>(i)) = update_y.transpose();\n          }\n        }\n\n        auto xt = x.transpose();\n        auto xtx = xt * x;\n\n#pragma omp parallel\n        {\n          Matrix diff;\n          Matrix xtcux;\n          Matrix a, b, update_x;\n#pragma omp for private(diff, xtcux, a, b, update_x)\n          for (size_t i = 0; i < static_cast<size_t>(n); ++i) {\n            diff = item_diag;\n            diff += item_weights[i];\n            xtcux = xtx + xt * diff * x;\n            auto p_val = p.col(static_cast<Eigen::Index>(i));\n\n            a = xtcux + reg;\n            b = xt * item_weights[i] * p_val;\n\n            update_x = a.colPivHouseholderQr().solve(b);\n            y.row(static_cast<Eigen::Index>(i)) = update_x.transpose();\n          }\n        }\n\n        w_mse = CalculateWeightedMse(x, y, p, ratings_matrix, alpha);\n        auto finish_time = std::chrono::steady_clock::now();\n        double elapsed_seconds =\n            std::chrono::duration_cast<std::chrono::duration<double>>(\n                finish_time - start_time)\n                .count();\n\n        std::cout << \"Initeration \" << k << \" weighted mse \" << w_mse\n                  << \" time \" << elapsed_seconds << std::endl;\n      }\n      std::cout << \"Learning done\" << std::endl;\n\n      PrintRecommendations(ratings_matrix, RatingsPredictions(x, y),\n                           movie_titles);\n\n      return 0;\n    }\n  }\n\n  std::cout << \"please specify data set directory\\n\";\n  return 0;\n};\n", "meta": {"hexsha": "1e6d55d5bc38d4ebc18c8a5c34f907cc429d2293", "size": 8254, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter08/eigen/eigen_recommender.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": "Chapter08/eigen/eigen_recommender.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": "Chapter08/eigen/eigen_recommender.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": 32.8844621514, "max_line_length": 78, "alphanum_fraction": 0.5739035619, "num_tokens": 2030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5730994989117587}}
{"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// \u6211\u4eec\u9700\u8981\u5305\u62ec\u4ee5\u4e0b\u6587\u4ef6\u6765\u505a\u8ba1\u65f6\u3002\n\n#include <deal.II/base/timer.h> \n\n// \u8fd9\u5305\u62ec\u6211\u4eec\u4f7f\u7528\u51e0\u4f55\u591a\u7f51\u683c\u6240\u9700\u7684\u6587\u4ef6\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// \u4e3a\u4e86\u4fbf\u4e8e\u5728\u6240\u4f7f\u7528\u7684\u4e0d\u540c\u6c42\u89e3\u5668\u4e4b\u95f4\u8fdb\u884c\u5207\u6362\uff0c\u6211\u4eec\u58f0\u660e\u4e86\u4e00\u4e2a\u679a\u4e3e\uff0c\u53ef\u4ee5\u4f5c\u4e3a\u53c2\u6570\u4f20\u9012\u7ed9\u4e3b\u7c7b\u7684\u6784\u9020\u51fd\u6570\u3002\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\u7c7b\u7528\u4e8e\u5b9a\u4e49\u8fb9\u754c\u6761\u4ef6\u548c\u8ba1\u7b97\u6570\u503c\u89e3\u7684\u8bef\u5dee\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u9700\u8981\u5b9a\u4e49\u6570\u503c\u548c\u68af\u5ea6\uff0c\u4ee5\u4fbf\u8ba1\u7b97L2\u548cH1\u8bef\u5dee\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u51b3\u5b9a\u4f7f\u7528\u6a21\u677f\u7684\u7279\u6b8a\u5316\u6765\u5206\u79bb2D\u548c3D\u7684\u5b9e\u73b0\u3002\n\n// \u8bf7\u6ce8\u610f\uff0c\u524d\u51e0\u4e2a\u5206\u91cf\u662f\u901f\u5ea6\u5206\u91cf\uff0c\u6700\u540e\u4e00\u4e2a\u5206\u91cf\u662f\u538b\u529b\u3002\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// \u6ce8\u610f\uff0c\u5bf9\u4e8e\u68af\u5ea6\uff0c\u6211\u4eec\u9700\u8981\u8fd4\u56de\u4e00\u4e2aTensor<1,dim>\u3002\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// \u5b9e\u73b0  $f$  \u3002\u66f4\u591a\u4fe1\u606f\u8bf7\u53c2\u89c1\u4ecb\u7ecd\u3002\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// \u5728\u4e0b\u6587\u4e2d\uff0c\u6211\u4eec\u5c06\u5b9e\u73b0\u4e00\u4e2a\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u5b83\u6269\u5c55\u4e86  step-22  \u7684\u7ed3\u679c\u90e8\u5206\u6240\u8ba8\u8bba\u7684\u60f3\u6cd5\u3002\u5177\u4f53\u6765\u8bf4\uff0c\u6211\u4eec1.\u4f7f\u7528\u4e00\u4e2a\u4e0a\u5757\u4e09\u89d2\u7684\u9884\u5904\u7406\u5668\uff0c\u56e0\u4e3a\u6211\u4eec\u60f3\u4f7f\u7528\u53f3\u9884\u5904\u7406\u30022.\u53ef\u9009\u62e9\u5141\u8bb8\u5bf9\u901f\u5ea6\u5757\u4f7f\u7528\u5185\u90e8\u6c42\u89e3\u5668\uff0c\u800c\u4e0d\u662f\u4f7f\u7528\u5355\u4e00\u7684\u9884\u5904\u7406\u7a0b\u5e8f\u30023.\u4e0d\u4f7f\u7528InverseMatrix\uff0c\u800c\u662f\u660e\u786e\u5730\u8c03\u7528SolverCG\u3002\u8fd9\u79cd\u65b9\u6cd5\u4e5f\u7528\u4e8eASPECT\u4ee3\u7801\uff08\u89c1https:aspect.geodynamics.org\uff09\uff0c\u8be5\u4ee3\u7801\u5728\u6a21\u62df\u5730\u5e54\u5bf9\u6d41\u7684\u80cc\u666f\u4e0b\u6c42\u89e3\u65af\u6258\u514b\u65af\u65b9\u7a0b\uff0c\u8be5\u4ee3\u7801\u5df2\u88ab\u7528\u4e8e\u89e3\u51b3\u6210\u5343\u4e0a\u4e07\u4e2a\u5904\u7406\u5668\u4e0a\u7684\u95ee\u9898\u3002\n\n//\u6784\u9020\u51fd\u6570\u4e2d\u7684bool\u6807\u5fd7 @p do_solve_A \u5141\u8bb8\u6211\u4eec\u5bf9\u901f\u5ea6\u5757\u5e94\u7528\u4e00\u6b21\u9884\u5904\u7406\uff0c\u6216\u8005\u4f7f\u7528\u5185\u90e8\u8fed\u4ee3\u6c42\u89e3\u5668\u6765\u4ee3\u66ff\u66f4\u7cbe\u786e\u7684\u8fd1\u4f3c\u3002\n\n// \u6ce8\u610f\u6211\u4eec\u662f\u5982\u4f55\u8ddf\u8e2a\u5185\u90e8\u8fed\u4ee3\u7684\u603b\u548c\uff08\u9884\u5904\u7406\u7a0b\u5e8f\u7684\u5e94\u7528\uff09\u7684\u3002\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// \u9996\u5148\u7528S\u7684\u8fd1\u4f3c\u503c\u6c42\u89e3\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// \u7b2c\u4e8c\uff0c\u5e94\u7528\u53f3\u4e0a\u65b9\u7684\u5757\uff08B^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// \u6700\u540e\uff0c\u8981\u4e48\u7528\u5de6\u4e0a\u89d2\u7684\u5757\u6c42\u89e3\uff0c\u8981\u4e48\u53ea\u5e94\u7528\u4e00\u4e2a\u9884\u8bbe\u6761\u4ef6\u5668\u626b\u9891\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// \u8fd9\u662f\u8be5\u95ee\u9898\u7684\u4e3b\u7c7b\u3002\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// \u4ec5\u4e3a\u901f\u5ea6\u7684\u6709\u9650\u5143\u3002\n\n    velocity_fe(FE_Q<dim>(pressure_degree + 1), dim) \n    , \n\n// \u6574\u4e2a\u7cfb\u7edf\u7684\u6709\u9650\u5143\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u8bbe\u7f6e\u4e86DoFHandler\u3001\u77e9\u9635\u3001\u5411\u91cf\u548cMultigrid\u7ed3\u6784\uff08\u5982\u679c\u9700\u8981\uff09\u3002\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// \u4e3bDoFHandler\u53ea\u9700\u8981\u6d3b\u52a8\u7684DoF\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u5728\u8fd9\u91cc\u8c03\u7528distribution_mg_dofs()\n\n    dof_handler.distribute_dofs(fe); \n\n// \u8fd9\u4e2a\u5757\u7ed3\u6784\u5c06dim\u901f\u5ea6\u5206\u91cf\u4e0e\u538b\u529b\u5206\u91cf\uff08\u7528\u4e8e\u91cd\u65b0\u6392\u5e8f\uff09\u5206\u5f00\u3002\u6ce8\u610f\uff0c\u6211\u4eec\u67092\u4e2a\u800c\u4e0d\u662f\u50cf step-22 \u4e2d\u7684dim+1\u5757\uff0c\u56e0\u4e3a\u6211\u4eec\u7684FESystem\u662f\u5d4c\u5957\u7684\uff0cdim\u901f\u5ea6\u5206\u91cf\u4f5c\u4e3a\u4e00\u4e2a\u5757\u51fa\u73b0\u3002\n\n    std::vector<unsigned int> block_component(2); \n    block_component[0] = 0; \n    block_component[1] = 1; \n\n// \u901f\u5ea6\u4ece\u7ec4\u4ef60\u5f00\u59cb\u3002\n\n    const FEValuesExtractors::Vector velocities(0); \n\n//\u5982\u679c\u6211\u4eec\u5e94\u7528\u91cd\u65b0\u6392\u5e8f\u6765\u51cf\u5c11\u586b\u5145\uff0c\n//ILU\u7684\u8868\u73b0\u4f1a\u66f4\u597d\u3002\u5bf9\u4e8e\u5176\u4ed6\u6c42\u89e3\u5668\u6765\u8bf4\uff0c\u8fd9\u6837\u505a\u5e76\u6ca1\u6709\u4ec0\u4e48\u597d\u5904\u3002\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// \u8fd9\u786e\u4fdd\u4e86\u6240\u6709\u7684\u901f\u5ea6DoFs\u5728\u538b\u529b\u672a\u77e5\u6570\u4e4b\u524d\u88ab\u5217\u4e3e\u51fa\u6765\u3002\u8fd9\u5141\u8bb8\u6211\u4eec\u4f7f\u7528\u5757\u6765\u5904\u7406\u5411\u91cf\u548c\u77e9\u9635\uff0c\u5e76\u5141\u8bb8\u6211\u4eec\u4e3adof_handler\u548cvelocity_dof_handler\u83b7\u5f97\u76f8\u540c\u7684DoF\u7f16\u53f7\u3002\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// \u8fd9\u5c06\u5728\u4e00\u4e2a\u5355\u72ec\u7684DoFHandler\u4e2d\u5206\u914d\u901f\u5ea6\u7a7a\u95f4\u7684\u4e3b\u52a8\u9053\u592b\u548c\u591a\u7f51\u683c\u9053\u592b\uff0c\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\u3002\n\n        velocity_dof_handler.distribute_dofs(velocity_fe); \n        velocity_dof_handler.distribute_mg_dofs(); \n\n// \u4e0b\u9762\u7684\u4ee3\u7801\u5757\u521d\u59cb\u5316\u4e86MGConstrainedDofs\uff08\u4f7f\u7528\u901f\u5ea6\u7684\u8fb9\u754c\u6761\u4ef6\uff09\uff0c\u4ee5\u53ca\u6bcf\u4e2a\u5c42\u6b21\u7684\u7a00\u758f\u6a21\u5f0f\u548c\u77e9\u9635\u3002MGLevelObject<T>\u7684resize()\u51fd\u6570\u5c06\u7834\u574f\u6240\u6709\u73b0\u6709\u7684\u5305\u542b\u5bf9\u8c61\u3002\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// \u4e0b\u9762\u5229\u7528\u5206\u91cf\u63a9\u7801\u5bf9\u901f\u5ea6\u7684\u8fb9\u754c\u503c\u8fdb\u884c\u63d2\u503c\uff0c\u8fd9\u5728\u77e2\u91cf\u503cdealii  step-20 \u6559\u7a0b\u4e2d\u8fdb\u4e00\u6b65\u8bf4\u660e\u3002\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// \u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u6211\u4eec\u9700\u8981\u56fa\u5b9a\u538b\u529b\u53d8\u91cf\u7684\u4e00\u4e2a\u81ea\u7531\u5ea6\u4ee5\u786e\u4fdd\u95ee\u9898\u7684\u53ef\u89e3\u6027\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u5c06\u7b2c\u4e00\u4e2a\u538b\u529b\u81ea\u7531\u5ea6\u6807\u8bb0\u4e3a\u53d7\u9650\u81ea\u7531\u5ea6\uff0c\u8be5\u81ea\u7531\u5ea6\u7684\u7d22\u5f15\u4e3an_u\u3002\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// \u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\uff0c\u7cfb\u7edf\u77e9\u9635\u88ab\u7ec4\u88c5\u8d77\u6765\u3002\u6211\u4eec\u5728(1,1)\u5757\u4e2d\u7ec4\u88c5\u538b\u529b\u8d28\u91cf\u77e9\u9635\uff08\u5982\u679c\u9700\u8981\uff09\uff0c\u5e76\u5728\u6b64\u51fd\u6570\u7ed3\u675f\u65f6\u5c06\u5176\u79fb\u51fa\u6b64\u4f4d\u7f6e\u3002\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// \u5982\u679c\u4e3a\u771f\uff0c\u6211\u4eec\u5c06\u5728(1,1)\u5757\u4e2d\u88c5\u914d\u538b\u529b\u8d28\u91cf\u77e9\u9635\u3002\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// \u5728\u8fd9\u91cc\uff0c\u4e0e step-16 \u4e2d\u4e00\u6837\uff0c\u6211\u4eec\u6709\u4e00\u4e2a\u51fd\u6570\uff0c\u7528\u4e8e\u7ec4\u88c5\u591a\u7f51\u683c\u9884\u5904\u7406\u7a0b\u5e8f\u6240\u9700\u7684\u6c34\u5e73\u77e9\u9635\u548c\u754c\u9762\u77e9\u9635\u3002\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// \u8fd9\u4e2a\u8fed\u4ee3\u5668\u4f1a\u8986\u76d6\u6240\u6709\u7684\u5355\u5143\u683c\uff08\u4e0d\u4ec5\u4ec5\u662f\u6d3b\u52a8\u7684\uff09\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u6839\u636e\u4f60\u60f3\u4f7f\u7528ILU\u6216GMG\u4f5c\u4e3a\u9884\u5904\u7406\u7a0b\u5e8f\u7684\u60c5\u51b5\u8fdb\u884c\u4e0d\u540c\u7684\u8bbe\u7f6e\u3002 \u8fd9\u4e24\u79cd\u65b9\u6cd5\u5171\u4eab\u76f8\u540c\u7684\u6c42\u89e3\u5668\uff08FGMRES\uff09\uff0c\u4f46\u9700\u8981\u521d\u59cb\u5316\u4e0d\u540c\u7684\u9884\u5904\u7406\u5668\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u4e0d\u4ec5\u4e3a\u6574\u4e2a\u6c42\u89e3\u51fd\u6570\u8ba1\u65f6\uff0c\u8fd8\u4e3a\u9884\u5904\u7406\u7a0b\u5e8f\u7684\u8bbe\u7f6e\u4ee5\u53ca\u6c42\u89e3\u672c\u8eab\u5206\u522b\u8ba1\u65f6\u3002\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// \u8fd9\u91cc\u6211\u4eec\u5fc5\u987b\u786e\u4fdd\u4ee5 \"\u8db3\u591f\u597d \"\u7684\u7cbe\u5ea6\u6c42\u89e3\u6b8b\u5dee\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// \u8fd9\u662f\u7528\u6765\u4f20\u9012\u6211\u4eec\u662f\u5426\u8981\u5728\u9884\u5904\u7406\u7a0b\u5e8f\u4e2d\u89e3\u51b3A\u7684\u95ee\u9898\u3002 \u6211\u4eec\u53ef\u4ee5\u628a\u5b83\u6539\u4e3afalse\uff0c\u770b\u770b\u662f\u5426\u8fd8\u80fd\u6536\u655b\uff0c\u5982\u679c\u80fd\u6536\u655b\uff0c\u90a3\u4e48\u7a0b\u5e8f\u7684\u8fd0\u884c\u901f\u5ea6\u662f\u5feb\u662f\u6162\uff1f\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// \u5728\u5404\u7ea7\u4e4b\u95f4\u8f6c\u79fb\u8fd0\u7b97\u7b26\n\n        MGTransferPrebuilt<Vector<double>> mg_transfer(mg_constrained_dofs); \n        mg_transfer.build(velocity_dof_handler); \n\n// \u8bbe\u7f6e\u7c97\u7565\u7684\u7f51\u683c\u89e3\u7b97\u5668\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\u4f5c\u4e3aCG\u7684\u9884\u5904\u7406\u7a0b\u5e8f\u65f6\uff0c\u9700\u8981\u662f\u4e00\u4e2a\u5bf9\u79f0\u7684\u8fd0\u7b97\u5668\uff0c\u6240\u4ee5\u5e73\u6ed1\u5668\u5fc5\u987b\u662f\u5bf9\u79f0\u7684\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// \u73b0\u5728\uff0c\u6211\u4eec\u51c6\u5907\u8bbe\u7f6eV\u578b\u5faa\u73af\u7b97\u5b50\u548c\u591a\u7ea7\u9884\u5904\u7406\u7a0b\u5e8f\u3002\n\n        Multigrid<Vector<double>> mg( \n          mg_matrix, coarse_grid_solver, mg_transfer, mg_smoother, mg_smoother); \n        mg.set_edge_matrices(mg_interface_down, mg_interface_up); \n\n        PreconditionMG<dim, Vector<double>, MGTransferPrebuilt<Vector<double>>> \n          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// \u8fd9\u4e2a\u51fd\u6570\u8ba1\u7b97\u51fa\u89e3\u51b3\u65b9\u6848\u7684L2\u548cH1\u8bef\u5dee\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9700\u8981\u786e\u4fdd\u538b\u529b\u7684\u5e73\u5747\u503c\u4e3a\u96f6\u3002\n\n  template <int dim> \n  void StokesProblem<dim>::compute_errors() \n  { \n\n// \u8ba1\u7b97\u5e73\u5747\u538b\u529b $\\frac{1}{\\Omega} \\int_{\\Omega} p(x) dx $ \uff0c\u7136\u540e\u4ece\u6bcf\u4e2a\u538b\u529b\u7cfb\u6570\u4e2d\u51cf\u53bb\u5b83\u3002\u8fd9\u5c06\u4ea7\u751f\u4e00\u4e2a\u5e73\u5747\u503c\u4e3a\u96f6\u7684\u538b\u529b\u3002\u8fd9\u91cc\u6211\u4eec\u5229\u7528\u4e86\u538b\u529b\u662f\u5206\u91cf $dim$ \u548c\u6709\u9650\u5143\u7a7a\u95f4\u662f\u7ed3\u70b9\u7684\u4e8b\u5b9e\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u751f\u6210\u56fe\u5f62\u8f93\u51fa\uff0c\u5c31\u50cf\u5728  step-22  \u4e2d\u6240\u505a\u7684\u90a3\u6837\u3002\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// \u65af\u6258\u514b\u65af\u7c7b\u7684\u6700\u540e\u4e00\u6b65\u662f\u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u751f\u6210\u521d\u59cb\u7f51\u683c\u7684\u51fd\u6570\uff0c\u5e76\u6309\u5404\u81ea\u7684\u987a\u5e8f\u8c03\u7528\u5176\u4ed6\u51fd\u6570\u3002\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\u7684\u9009\u9879\u3002umfpack 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": "#include <complex>\n#include <limits>\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <rsvd/StandardNormalRandom.hpp>\n\nusing Eigen::Index;\nusing Rsvd::Internal::standardNormalRandom;\n\ntemplate <typename T> struct StandardNormalRandom : public ::testing::Test {\n  using MatrixType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n  using RealType = typename Eigen::NumTraits<T>::Real;\n\n  const Index numRows = 10;\n  const Index numCols = 1;\n  const Index numTrials = 1'000;\n  const unsigned int prngSeed = 777;\n  const RealType tol = 1e-1;\n};\n\nusing NumericalTypes = ::testing::Types<float, double, std::complex<float>, std::complex<double>>;\n\nTYPED_TEST_CASE(StandardNormalRandom, NumericalTypes, );\n\nTYPED_TEST(StandardNormalRandom, ZeroMean) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  MatrixType acc = MatrixType::Zero(TestFixture::numRows, TestFixture::numCols);\n\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n  for (unsigned int i = 0; i < TestFixture::numTrials; ++i) {\n    acc += standardNormalRandom<MatrixType, std::mt19937_64>(TestFixture::numRows,\n                                                             TestFixture::numCols, randomEngine);\n  }\n  acc /= TestFixture::numTrials;\n\n  // Since the vector has 10 independent elements, we want to check for the worst case among them\n  ASSERT_LE(acc.cwiseAbs().maxCoeff(), TestFixture::tol);\n}\n\nTYPED_TEST(StandardNormalRandom, Covariance) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  MatrixType x = MatrixType::Zero(TestFixture::numRows, TestFixture::numTrials);\n\n  std::mt19937_64 randomEngine;\n  randomEngine.seed(TestFixture::prngSeed);\n  for (unsigned int i = 0; i < TestFixture::numTrials; ++i) {\n    x.col(i) = standardNormalRandom<MatrixType, std::mt19937_64>(\n        TestFixture::numRows, TestFixture::numCols, randomEngine);\n  }\n  MatrixType covariance = x * x.adjoint() / TestFixture::numTrials;\n\n  const typename MatrixType::Scalar unitVariance = 1;\n  // Check diagonal entries: They should be almost equal to one (unit variance)\n  for (Index i = 0; i < TestFixture::numRows; ++i) {\n    ASSERT_LE(std::abs(covariance(i, i) - unitVariance), TestFixture::tol);\n  }\n\n  // Remove diagonal entries\n  covariance.diagonal().setZero();\n  // Check all remaining entries: They should be almost zero (independent distributions)\n  ASSERT_LE(covariance.cwiseAbs().maxCoeff(), TestFixture::tol);\n}\n", "meta": {"hexsha": "1386c51d91973baa8c1d93286e9549adc6adc451", "size": 2430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/StandardNormalRandom.cpp", "max_stars_repo_name": "valerii-filev-picsart/rsvd", "max_stars_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-09-16T09:12:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T15:40:04.000Z", "max_issues_repo_path": "test/StandardNormalRandom.cpp", "max_issues_repo_name": "valerii-filev-picsart/rsvd", "max_issues_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/StandardNormalRandom.cpp", "max_forks_repo_name": "valerii-filev-picsart/rsvd", "max_forks_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-08T18:45:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-08T18:45:56.000Z", "avg_line_length": 35.7352941176, "max_line_length": 98, "alphanum_fraction": 0.7176954733, "num_tokens": 639, "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\u00b2([0,T], L\u00b2(\u03a9))\";\n}\n\ntemplate <int dim>\nstd::string L2L2<dim>::unique_id() const {\n  return \"L\u00b2([0,T], L\u00b2(\u03a9))\";\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 2007.\r\n//  Copyright Paul A> Bristow 2010\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <iostream>\r\nusing std::cout; using std::endl;\r\n#include <cerrno> // for ::errno\r\n\r\n//[policy_eg_1\r\n\r\n#include <boost/math/special_functions/gamma.hpp>\r\nusing boost::math::tgamma;\r\n\r\n// Define the policy to use:\r\nusing namespace boost::math::policies; // may be convenient, or\r\n\r\nusing boost::math::policies::policy;\r\n// Types of error whose action can be altered by policies:.\r\nusing boost::math::policies::evaluation_error;\r\nusing boost::math::policies::domain_error;\r\nusing boost::math::policies::overflow_error;\r\nusing boost::math::policies::domain_error;\r\nusing boost::math::policies::pole_error;\r\n// Actions on error (in enum error_policy_type):\r\nusing boost::math::policies::errno_on_error;\r\nusing boost::math::policies::ignore_error;\r\nusing boost::math::policies::throw_on_error;\r\nusing boost::math::policies::user_error;\r\n\r\ntypedef policy<\r\n   domain_error<errno_on_error>,\r\n   pole_error<errno_on_error>,\r\n   overflow_error<errno_on_error>,\r\n   evaluation_error<errno_on_error> \r\n> c_policy;\r\n//\r\n// Now use the policy when calling tgamma:\r\n\r\n// http://msdn.microsoft.com/en-us/library/t3ayayh1.aspx \r\n// Microsoft errno declared in STDLIB.H as \"extern int errno;\" \r\n\r\nint main()\r\n{\r\n   errno = 0; // Reset.\r\n   cout << \"Result of tgamma(30000) is: \" \r\n      << tgamma(30000, c_policy()) << endl; // Too big parameter\r\n   cout << \"errno = \" << errno << endl; // errno 34 Numerical result out of range.\r\n   cout << \"Result of tgamma(-10) is: \" \r\n      << boost::math::tgamma(-10, c_policy()) << endl; // Negative parameter.\r\n   cout << \"errno = \" << errno << endl; // error 33 Numerical argument out of domain.\r\n} // int main()\r\n\r\n//]\r\n\r\n/* Output\r\n\r\npolicy_eg_1.cpp\r\n  Generating code\r\n  Finished generating code\r\n  policy_eg_1.vcxproj -> J:\\Cpp\\MathToolkit\\test\\Math_test\\Release\\policy_eg_1.exe\r\n  Result of tgamma(30000) is: 1.#INF\r\n  errno = 34\r\n  Result of tgamma(-10) is: 1.#QNAN\r\n  errno = 33\r\n\r\n*/\r\n\r\n\r\n", "meta": {"hexsha": "99d645aae42351913374b128200a8126239df0f7", "size": 2195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/policy_eg_1.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/math/example/policy_eg_1.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/math/example/policy_eg_1.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 30.9154929577, "max_line_length": 86, "alphanum_fraction": 0.6879271071, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.5730319339974972}}
{"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": "// Copyright Andr\u00e1s Vukics 2006\u20132020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#include \"Simulated.h\"\n\n#include <boost/bind.hpp>\n\n\nusing namespace std       ;\nusing namespace trajectory;\nusing namespace parameters;\n\n\ntypedef blitz::Array<double,1> DA1R;\n\n/*\n  y(0) Re y\n  y(1) Im y\n  y(2) Re dy/dt\n  y(3) Im dy/dt\n*/\n\nvoid derivs(double tau, const DA1R& y, DA1R& dydt, double omega, double gamma)\n{\n  dydt(0)=y(2); dydt(1)=y(3); \n  dydt(2)=cos(omega*tau)-2*gamma*y(2)-y(0); dydt(3)=sin(omega*tau)-2*gamma*y(3)-y(1);\n}\n\n\nint main(int argc, char* argv[])\n{\n  ParameterTable p;\n\n  Pars pt(p);\n\n  double& omega=p.add(\"O\",\"Driving frequency\",1.);\n  double& gamma=p.add(\"G\",\"Damping rate\"     ,1.);\n\n  dcomp&    yinit=p.add(   \"yinit\",\" y   initial condition\",dcomp( 1,-1));\n  dcomp& dydtinit=p.add(\"dydtinit\",\"dydt initial condition\",dcomp(-1, 1));\n\n  // Parameter finalization\n  update(p,argc,argv,\"--\");\n\n  if (pt.T<0) pt.T=10./min(1.,min(omega,gamma));\n  // Note: 1.0 is also an existing frequency in the system, which defines the unit of time \n\n  DA1R y(4); y=yinit.real(),yinit.imag(),dydtinit.real(),dydtinit.imag();\n\n  Simulated<DA1R> S(y,\n                    bind(derivs,_1,_2,_3,omega,gamma),\n                    .1/max(1.,max(omega,gamma)),\n                    pt);\n\n  run(S,pt);\n\n}\n", "meta": {"hexsha": "5d6932e6e52ca7d30ada66fdf7b3b21f8316a94d", "size": 1342, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDutils/examples/HarmonicOscillator.cc", "max_stars_repo_name": "bartoszek/cppqed", "max_stars_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CPPQEDutils/examples/HarmonicOscillator.cc", "max_issues_repo_name": "bartoszek/cppqed", "max_issues_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CPPQEDutils/examples/HarmonicOscillator.cc", "max_forks_repo_name": "bartoszek/cppqed", "max_forks_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_forks_repo_licenses": ["BSL-1.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.9642857143, "max_line_length": 132, "alphanum_fraction": 0.6207153502, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5730266046470134}}
{"text": "#include <math.h>\n#include <algorithm>  // std::min, std::max\n#include <uWS/uWS.h>\n#include <chrono>\n#include <iostream>\n#include <thread>\n#include <vector>\n#include \"Eigen-3.3/Eigen/Core\"\n#include \"Eigen-3.3/Eigen/QR\"\n#include \"MPC.h\"\n#include \"json.hpp\"\n\n// For latency measurment/compensation.\n#include <boost/circular_buffer.hpp>\n#include <chrono>\n\n\n\n\n//////// PARAMETERS ////////\nstatic const unsigned int poly_order = 3;\n// NOTE: REMEMBER TO SET THIS TO 100 MILLISECONDS BEFORE\n// SUBMITTING.\nstatic const size_t LATENCY = 100;\nstatic const size_t MAX_DELAYS = 10;\n\n\n\n\n// for convenience\nusing json = nlohmann::json;\n\n// For converting back and forth between radians and degrees.\nconstexpr double pi() { return M_PI; }\n\ndouble deg2rad(double x) { return x * pi() / 180; }\n\ndouble rad2deg(double x) { return x * 180 / pi(); }\n\n\n// Return a duple.\nstruct Pair {\n    double x;\n    double y;\n};\n\n\n// Wrap a rotation+translation in a nice class.\nclass Transformation_Matrix {\nprivate:\n    Eigen::Matrix<double, 3, 3> A;\n    double theta, xt, yt;\n\npublic:\n    Transformation_Matrix(double theta, double xt, double yt) {\n        this->theta = theta;\n        this->xt = xt;\n        this->yt = yt;\n\n        double c = cos(theta);\n        double s = sin(theta);\n        A << c,-s, xt,\n            s, c, yt,\n            0, 0, 1;\n    }\n\n    Pair operator()(double xa, double ya) {\n        Eigen::Matrix<double, 3, 1> XA;\n        XA << xa, ya, 1;\n        auto XB = A * XA;\n        Pair result;\n        result.x = XB(0, 0);\n        result.y = XB(1, 0);\n        return result;\n    }\n\n    Transformation_Matrix inverse() {\n        // Derived by inverting A with Mathematica.\n        double xr = -xt * cos(theta) - yt * sin(theta);\n        double yr =  xt * sin(theta) - yt * cos(theta);\n        return Transformation_Matrix(-theta, xr, yr);\n    }\n};\n\n\n// Checks if the SocketIO event has JSON data.\n// If there is data the JSON object in string format will be returned,\n// else the empty string \"\" will be returned.\nstring hasData(string s) {\n    auto found_null = s.find(\"null\");\n    auto b1 = s.find_first_of(\"[\");\n    auto b2 = s.rfind(\"}]\");\n    if (found_null != string::npos) {\n        return \"\";\n    } else if (b1 != string::npos && b2 != string::npos) {\n        return s.substr(b1, b2 - b1 + 2);\n    }\n    return \"\";\n}\n\n\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,\n                        unsigned 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 (unsigned int i = 0; i < xvals.size(); i++) {\n        A(i, 0) = 1.0;\n    }\n\n    for (unsigned int j = 0; j < xvals.size(); j++) {\n        for (unsigned short i = 0; i < order; i++) {\n            A(j, i + 1) = A(j, i) * xvals(j);\n        }\n    }\n\n    auto Q = A.householderQr();\n    auto result = Q.solve(yvals);\n    return result;\n}\n\n\n/*\n * Keep a running mean of MPC-solve latency times,\n * and use this to provide an adjusted starting position\n * for MPC to use in its projected trajectories.\n */\nclass DelayPredictor {\nprivate:\n    double d, a;\n    std::chrono::time_point<std::chrono::system_clock> t_prev;\n    boost::circular_buffer<double> previous_delay_times;\n\npublic:\n    DelayPredictor() : previous_delay_times(MAX_DELAYS) {\n        d = 0;\n        a = 0;\n        previous_delay_times.push_back(.001*LATENCY);\n        t_prev = std::chrono::system_clock::now();\n    }\n\n    /*\n     * Return a running mean of the remembered latency durations.\n     */\n    double estimate_latency() {\n        double dt_est = 0;\n        for(auto dt : previous_delay_times) {\n            dt_est += dt;\n        }\n        dt_est /= previous_delay_times.size();\n        //std::cout << \"dt_est = \" << dt_est << std::endl;\n        return dt_est;\n    }\n\n    /*\n     * Project the given state values forward the current latency estimate.\n     */\n    std::vector<double> get_delayed_state(double px, double py, double psi, double v) {\n        const double dt_est = estimate_latency();\n        const double px_delay = px + v * cos(psi) * dt_est;\n        const double py_delay = py + v * sin(psi) * dt_est;\n        const double psi_delay = psi + v / 2.67 * d * dt_est;\n        const double v_delay = v + a * dt_est;\n\n        return {px_delay, py_delay, psi_delay, v_delay};\n    }\n\n    /*\n     * Record the actuated control values AND, as a side effect,\n     * append a measurement of the latency.\n     */\n    void set_previous_control_actuations(double steer_value, double throttle_value) {\n        d = steer_value * -deg2rad(25.0);\n        a = throttle_value;\n\n        // Measure the latency.\n        std::chrono::time_point<std::chrono::system_clock> t\n        = std::chrono::system_clock::now();\n        std::chrono::duration<double> dt = t - t_prev;\n        set_time(t);\n        previous_delay_times.push_back(dt.count());\n    }\n\n    void set_time(std::chrono::time_point<std::chrono::system_clock> t) {\n        t_prev = t;\n    }\n\n    /*\n     * Set the last-measured time mark. This must be used when we first start communicating\n     * with the simulator, since that connection might happen significantly after\n     * when the DelayPredictor class is constructed.\n     */\n    void set_time() {\n        set_time(std::chrono::system_clock::now());\n    }\n};\n\n\n\nint main() {\n    uWS::Hub h;\n\n    // MPC is initialized here!\n    MPC mpc;\n\n    // Keep track of most-recent actuations.\n    DelayPredictor delay_predictor;\n\n    h.onMessage([&mpc, &delay_predictor](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length,\n                       uWS::OpCode opCode) {\n        // \"42\" at the start of the message means there's a websocket message event.\n        // The 4 signifies a websocket message\n        // The 2 signifies a websocket event\n        string sdata = string(data).substr(0, length);\n        if (sdata.size() > 2 && sdata[0] == '4' && sdata[1] == '2') {\n            string s = hasData(sdata);\n            if (s != \"\") {\n                auto j = json::parse(s);\n                string event = j[0].get<string>();\n                if (event == \"telemetry\") {\n\n                    // Extract the current state and nearby road midpoints.\n                    vector<double> ptsx = j[1][\"ptsx\"];\n                    vector<double> ptsy = j[1][\"ptsy\"];\n                    double px = j[1][\"x\"];\n                    double py = j[1][\"y\"];\n                    double psi = j[1][\"psi\"];\n                    double v = j[1][\"speed\"];\n\n                    // Convert speed to meters/second\n                    v *= 5280. / 3.2808 / 3600.;\n\n                    // Estimate a transformation from vehicle to map and v/v.\n                    Transformation_Matrix vehicle2map(psi, px, py);\n                    Transformation_Matrix map2vehicle = vehicle2map.inverse();\n\n                    // Predict the next state with latency.\n                    // Running the MPC takes time, so, realistically, it should assume\n                    // not a starting point of the current state,\n                    // but the current state plus a small uncontrolled delay.\n                    // See MPC.cpp for some more details on this motion model.\n                    auto delayed_state = delay_predictor.get_delayed_state(px, py, psi, v);\n                    px = delayed_state[0];\n                    py = delayed_state[1];\n                    psi = delayed_state[2];\n                    v = delayed_state[3];\n\n                    // Fit a polynomial to the centerline coordinates.\n                    // Sadly, polyfit wants a VectorXD, not a vector<double>.\n                    Eigen::VectorXd ptsx_v(ptsx.size());\n                    Eigen::VectorXd ptsy_v(ptsy.size());\n                    ptsx_v.fill(0);\n                    ptsy_v.fill(0);\n                    vector<double> ptsx_vehicle, ptsy_vehicle;\n                    for(unsigned int i=0; i<ptsx.size(); i++) {\n                        Pair polyxy = map2vehicle(ptsx[i], ptsy[i]);\n                        ptsx_v[i] = polyxy.x;\n                        ptsy_v[i] = polyxy.y;\n                        ptsx_vehicle.push_back(polyxy.x);\n                        ptsy_vehicle.push_back(polyxy.y);\n                    }\n                    const auto coeffs = polyfit(ptsx_v, ptsy_v, std::min((unsigned int) ptsx.size()-1, poly_order));\n\n                    // calculate the cross track error\n                    // Negative sign is here because if the poly evaluates positive, our y coordinate (0) is too small.\n                    const double cte = -polyeval(coeffs, px);\n\n                    // calculate the orientation error\n                    // Negative sign is here because if slope is positive, angle is positive,\n                    // and our angle of 0 radians is too small.\n                    const double epsi = -atan(coeffs[1]);\n\n                    // First three state values (x, y, psi) are all zero because we're considering MPC solutions\n                    // that start from the car's position in its own coordinate frame.\n                    Eigen::VectorXd state(6);\n                    state << 0, 0, 0, v, cte, epsi;\n\n                    /*\n                    * Calculate steering angle and throttle using MPC.\n                    *\n                    * Both are in between [-1, 1].\n                    *\n                    */\n                    auto result = mpc.Solve(state, coeffs);\n                    auto vars = result.variables;\n                    double steer_value = -vars[6] / deg2rad(25.0);\n                    // If braking is causing the simulator to stick, consider only using the gas.\n                    //double throttle_value = max(vars[7], 0.0);\n                    double throttle_value = vars[7];\n\n                    json msgJson;\n                    msgJson[\"steering_angle\"] = steer_value;\n                    msgJson[\"throttle\"] = throttle_value;\n\n                    //Display the MPC predicted trajectory\n                    //.. add (x,y) points to list here, points are in reference to the vehicle's coordinate system\n                    // the points in the simulator are connected by a green line\n                    vector<double> mpc_x_vals = result.path.x;\n                    vector<double> mpc_y_vals = result.path.y;\n                    msgJson[\"mpc_x\"] = mpc_x_vals;\n                    msgJson[\"mpc_y\"] = mpc_y_vals;\n\n                    //Display the waypoints/reference line\n                    //.. add (x,y) points to list here, points are in reference to the vehicle's coordinate system\n                    // the points in the simulator are connected by a yellow line\n                    vector<double> next_x_vals = result.fit.x;\n                    vector<double> next_y_vals = result.fit.y;\n                    msgJson[\"next_x\"] = next_x_vals;\n                    msgJson[\"next_y\"] = next_y_vals;\n\n\n                    auto msg = \"42[\\\"steer\\\",\" + msgJson.dump() + \"]\";\n                    // Latency\n                    // The purpose is to mimic real driving conditions where\n                    // the car does actuate the commands instantly.\n                    //\n                    // Feel free to play around with this value but should be to drive\n                    // around the track with 100ms latency.\n                    this_thread::sleep_for(chrono::milliseconds(LATENCY));\n                    delay_predictor.set_previous_control_actuations(steer_value, throttle_value);\n                    ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\n                }\n            } else {\n                // Manual driving\n                std::string msg = \"42[\\\"manual\\\",{}]\";\n                ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\n            }\n        }\n    });\n\n    // We don't need this since we're not using HTTP but if it's removed the\n    // program\n    // doesn't compile :-(\n    h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,\n                       size_t, size_t) {\n        const std::string s = \"<h1>Hello world!</h1>\";\n        if (req.getUrl().valueLength == 1) {\n            res->end(s.data(), s.length());\n        } else {\n            // i guess this should be done more gracefully?\n            res->end(nullptr, 0);\n        }\n    });\n\n    h.onConnection([&h, &delay_predictor](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {\n        std::cout << \"Connected!!!\" << std::endl;\n\n        // Only set t0 for latency estimation once we've actually connected.\n        delay_predictor.set_time();\n    });\n\n    h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,\n                           char *message, size_t length) {\n        ws.close();\n        std::cout << \"Disconnected\" << std::endl;\n    });\n\n    int port = 4567;\n    if (h.listen(port)) {\n        std::cout << \"Listening to port \" << port << std::endl;\n    } else {\n        std::cerr << \"Failed to listen to port\" << std::endl;\n        return -1;\n    }\n    h.run();\n}\n", "meta": {"hexsha": "a00a8e5129b920b2247c93a6cbecb357794288bc", "size": 13128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "tsbertalan/CarND-MPC-Project", "max_stars_repo_head_hexsha": "58e3262c37d91940f7cb91e5ce2d75d1e21fc9a3", "max_stars_repo_licenses": ["MIT"], "max_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": "tsbertalan/CarND-MPC-Project", "max_issues_repo_head_hexsha": "58e3262c37d91940f7cb91e5ce2d75d1e21fc9a3", "max_issues_repo_licenses": ["MIT"], "max_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": "tsbertalan/CarND-MPC-Project", "max_forks_repo_head_hexsha": "58e3262c37d91940f7cb91e5ce2d75d1e21fc9a3", "max_forks_repo_licenses": ["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.3854447439, "max_line_length": 119, "alphanum_fraction": 0.5413619744, "num_tokens": 3065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5730265932282683}}
{"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//\u9876\u70b9\uff0c\u5373\u5f85\u4f18\u5316\u53d8\u91cf\uff0c\u76ee\u6807\u503c\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_) //\u66f4\u65b0\u9876\u70b9\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//\u8fb9\uff0c\u63cf\u8ff0\u9876\u70b9\u4e4b\u95f4\u7684\u5173\u7cfb\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// \u8ba1\u7b97\u8bef\u5dee\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)); // \u89c2\u6d4b\u91cf\u51cf\u53bb\u4f30\u8ba1\u91cf\n        // cout << \"cee \"<<_error << endl;\n\n    }\n// \u8ba1\u7b97\u96c5\u53ef\u6bd4\u77e9\u9635\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        //\u8bef\u5dee\u9879\u5bf9\u5f85\u4f18\u5316\u53d8\u91cf\u7684Jacobian\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    // // \u6bcf\u4e2a\u8bef\u5dee\u9879\u4f18\u5316\u53d8\u91cf\u7ef4\u5ea6\u4e3a 4\uff0c\u8bef\u5dee\u503c\u7ef4\u5ea6\u4e3a1\n    // typedef g2o::BlockSolver<g2o::BlockSolverTraits<4,1>> Block;\n    // // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\uff1a \u7a20\u5bc6\u7684\u589e\u91cf\u65b9\u7a0b\n    // Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>();\n\n    // // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n    // Block* solver_ptr = new Block(std::unique_ptr<Block::LinearSolverType>(linearSolver));\n    \n    // // \u68af\u5ea6\u4e0b\u964d\u65b9\u6cd5\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    // // \u521d\u59cb\u503c\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);//\u6dfb\u52a0\u9876\u70b9\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);//\u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n    //     edge->setMeasurement(y_data[i]);\n\n    //     //\u4fe1\u606f\u77e9\u9635\uff1a \u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\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; // \u771f\u5b9e\u53c2\u6570\u503c\n    int N = 100;\n    double w_sigma = 2.0;   // \u566a\u58f0\u503cSigma\n    cv::RNG rng;    // \u968f\u673a\u6570\u4ea7\u751f\u5668OpenCV\n    double abcd[4] = {0, 0, 0, 0};  // \u53c2\u6570\u7684\u4f30\u8ba1\u503cabc\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    // \u6784\u5efa\u56fe\u4f18\u5316\uff0c\u5148\u8bbe\u5b9ag2o\n    // \u77e9\u9635\u5757\uff1a\u6bcf\u4e2a\u8bef\u5dee\u9879\u4f18\u5316\u53d8\u91cf\u7ef4\u5ea6\u4e3a4 \uff0c\u8bef\u5dee\u503c\u7ef4\u5ea6\u4e3a1\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<4, 1> > Block;\n    // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\uff1a\u7a20\u5bc6\u7684\u589e\u91cf\u65b9\u7a0b\n    // Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>();\n\n    typedef g2o::LinearSolverDense<Block::PoseMatrixType> MyLinearSolver;\n    // Block* solver_ptr = new Block(linearSolver);    // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n\n    // // \u68af\u5ea6\u4e0b\u964d\u65b9\u6cd5\uff0c\u4eceGN, LM, DogLeg \u4e2d\u9009\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    // \u77e9\u9635\u5757\u6c42\u89e3\u5668\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;     // \u56fe\u6a21\u578b\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 );   // \u8bbe\u7f6e\u6c42\u89e3\u5668\n    optimizer.setVerbose(true);     // \u6253\u5f00\u8c03\u8bd5\u8f93\u51fa\n\n    // \u5f80\u56fe\u4e2d\u589e\u52a0\u9876\u70b9\n    CurveFittingVertex *v = new CurveFittingVertex();\n    // \u8bbe\u7f6e\u4f18\u5316\u521d\u59cb\u4f30\u8ba1\u503c\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    // \u5f80\u56fe\u4e2d\u589e\u52a0\u8fb9\n    for(int i = 0; i < N; i++)\n    {\n        CurveFittingEdge* edge = new CurveFittingEdge();\n        edge->setId(i+1);\n        edge->setVertex(0, v);      // \u8bbe\u7f6e\u8fde\u63a5\u7684\u9876\u70b9\n        edge->setMeasurement( y_data[i] );      // \u89c2\u6d4b\u6570\u503c\n\n        // \u4fe1\u606f\u77e9\u9635\uff1a\u534f\u65b9\u5dee\u77e9\u9635\u4e4b\u9006\n        edge->setInformation( Eigen::Matrix<double, 1, 1>::Identity() );\n\n        edge->_x = x_data[i];\n\n        optimizer.addEdge( edge );\n    }\n\n    // \u6267\u884c\u4f18\u5316\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    // \u8f93\u51fa\u4f18\u5316\u503c\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": "#include \"catch.hpp\"\n#include \"acs_metric_tsp_approx.h\"\n#include \"simple_point.h\"\n#include \"TourMatcher.h\"\n#include <bits/stl_iterator.h>\n#include <boost/container_hash/hash.hpp>\n\nusing namespace boost;\nusing namespace acs;\ntypedef simple_point<float> pos;\ntypedef adjacency_list<vecS, vecS, bidirectionalS, pos> G;\ntypedef graph_traits<G>::vertex_descriptor V;\n\nTEST_CASE(\"[ACS] Simple linear 4-node graph\", \"[full]\") {\n    G g;\n    V a = add_vertex({3, 0}, g);\n    V b = add_vertex({0, 0}, g);\n    V c = add_vertex({2, 0}, g);\n    V d = add_vertex({1, 0}, g);\n    std::vector<V> desired = { b, d, c, a };\n    std::vector<V> solution;\n    auto itr = std::back_inserter(solution);\n    auto vis = boost::make_tsp_tour_visitor(itr);\n    acs_metric_tsp_approx(g, vis);\n    REQUIRE_THAT(solution, TourEqual(desired));\n}\n\nTEST_CASE(\"[ACS] Circular graph\", \"[full]\") {\n    const int N = 8;\n    G g;\n    std::vector<V> desired(N);\n\n    SECTION(\"Rotated\") {\n        int order[]{ 3, 4, 5, 6, 7, 0, 1, 2 };\n        for (int i = 0; i < N; ++i) {\n            float theta = 2 * M_PI * ((float)order[i]) / ((float) N);\n            V v = add_vertex({cosf(theta), sinf(theta)}, g);\n            desired[order[i]] = v;\n        }\n        std::vector<V> solution;\n        auto itr = std::back_inserter(solution);\n        auto vis = boost::make_tsp_tour_visitor(itr);\n        acs_metric_tsp_approx(g, vis);        \n        REQUIRE_THAT(solution, TourEqual(desired));\n    }\n\n    SECTION(\"Reordered\") {\n        int order[]{ 4, 7, 5, 1, 3, 0, 2, 6 };\n        for (int i = 0; i < N; ++i) {\n            float theta = 2 * M_PI * ((float)order[i]) / ((float) N);\n            V v = add_vertex({cosf(theta), sinf(theta)}, g);\n            desired[order[i]] = v;\n        }\n        std::vector<V> solution;\n        auto itr = std::back_inserter(solution);\n        auto vis = boost::make_tsp_tour_visitor(itr);\n        acs_metric_tsp_approx(g, vis);\n        REQUIRE_THAT(solution, TourEqual(desired));\n    }\n}\n\nTEST_CASE(\"[ACS] Restricted simple linear graph\", \"[full]\") {\n    G g;\n    V a = add_vertex({4, 0}, g);\n    V b = add_vertex({0, 0}, g);\n    V c = add_vertex({2, 0}, g);\n    V d = add_vertex({1, 0}, g);\n    add_edge(c, d, g);\n    std::vector<V> desired = { b, c, d, a };\n    std::vector<V> solution;\n    auto itr = std::back_inserter(solution);\n    auto vis = boost::make_tsp_tour_visitor(itr);\n    acs_metric_tsp_approx(g, vis, _sop=true);\n    REQUIRE_THAT(solution, TourEqual(desired));\n}", "meta": {"hexsha": "01875f0874371d9aec7a72cd40c1e8d9f23b2fdc", "size": 2467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_acs_metric_tsp_approx.cpp", "max_stars_repo_name": "jmlowenthal/survey", "max_stars_repo_head_hexsha": "030fb473f9a30d41654475e3bfa00a83348bb1f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-16T15:01:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-16T15:01:11.000Z", "max_issues_repo_path": "src/test_acs_metric_tsp_approx.cpp", "max_issues_repo_name": "jmlowenthal/survey", "max_issues_repo_head_hexsha": "030fb473f9a30d41654475e3bfa00a83348bb1f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test_acs_metric_tsp_approx.cpp", "max_forks_repo_name": "jmlowenthal/survey", "max_forks_repo_head_hexsha": "030fb473f9a30d41654475e3bfa00a83348bb1f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8933333333, "max_line_length": 69, "alphanum_fraction": 0.5816781516, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5730265887245392}}
{"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": "#define EIGEN2_SUPPORT\r\n#include <Eigen/Core>\r\n#include <iostream>\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n  Matrix3i m = Matrix3i::Random();\r\n  cout << \"Here is the matrix m:\" << endl << m << endl;\r\n  Matrix3i n = Matrix3i::Random();\r\n  cout << \"And here is the matrix n:\" << endl << n << endl;\r\n  cout << \"The coefficient-wise product of m and n is:\" << endl;\r\n  cout << m.cwise() * n << endl;\r\n  cout << \"Taking the cube of the coefficients of m yields:\" << endl;\r\n  cout << m.cwise().pow(3) << endl;\r\n}\r\n", "meta": {"hexsha": "00c2212e2b7372ee7ec1731d0142b988e1e353cf", "size": 534, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/eigen3.2.10/doc/examples/MatrixBase_cwise_const.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/doc/examples/MatrixBase_cwise_const.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/doc/examples/MatrixBase_cwise_const.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": 28.1052631579, "max_line_length": 70, "alphanum_fraction": 0.6048689139, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.7371581684030621, "lm_q1q2_score": 0.5729929495693766}}
{"text": "#include \"libs/experiments/mse.h\"\n#include <boost/range/algorithm/transform.hpp>\n#include <boost/range/size.hpp>\n#include <boost/range/numeric.hpp>\n#include <functional>\n//#define PRINT_DATA_FOR_ALGO\n#ifdef PRINT_DATA_FOR_ALGO\n#   include <iostream>\n#   include <iterator>\n#   include <algorithm>\n#   define PRINTOUT_DATA(_data)  std::copy(std::begin(_data), std::end(_data), std::ostream_iterator<value_type>(std::cout, \", \")); std::cout<<std::endl\n#else\n#    define PRINTOUT_DATA(_data) \n#endif  // PRINT_DATA_FOR_ALGO\n\n/*\n\n#include <opencv/cxcore.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/ml/ml.hpp>\n\nnamespace exprs\n{\nfloat mse(cv::Mat &a,cv::Mat &b)\n{\n    auto N = a.rows;\n    auto c = a - b;\n    c=c.t()*c;\n    return c.at<float>(0,0)/N;\n}\n}\t// end of namespace exprs\n*/\nnamespace exprs\n{ \n\nmse_results mse(const std::vector<value_type>& predictions,\n\tconst std::vector<value_type>& mesured)\n{\n    if (boost::size(predictions) != boost::size(mesured)) {\n        throw std::runtime_error{\"both ranges must be same prediction = \" + \n\t\tstd::to_string(boost::size(predictions)) + \", mesured = \" +\n\t\tstd::to_string(boost::size(mesured))};\n    }\n    PRINTOUT_DATA(predictions);\n    PRINTOUT_DATA(mesured);\n    std::vector<value_type> tmp_res(boost::size(mesured), 0.f);\n    boost::transform(predictions, mesured, std::begin(tmp_res), std::minus<value_type>()); \n    return mse_results{boost::inner_product(tmp_res, tmp_res, 0.f)}; \n}\n\n}\t// end namespace exprs\n\n", "meta": {"hexsha": "c0432a21d2cfb85f9518e9acaf4a229515c12ea2", "size": 1475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/experiments/src/mse.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/mse.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/mse.cpp", "max_forks_repo_name": "boazsade/machine_learinig_models", "max_forks_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8301886792, "max_line_length": 152, "alphanum_fraction": 0.6874576271, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5729351173793015}}
{"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 << \"\u03bcs.\\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 << \"\u03bcs.\\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\u00e4nkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\n\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": "/*\nCopyright 2015 Glen Joseph Fernandes\n(glenjofe@gmail.com)\n\nDistributed under the Boost Software License, Version 1.0.\n(http://www.boost.org/LICENSE_1_0.txt)\n*/\n#ifndef BOOST_ALIGN_ALIGN_UP_HPP\n#define BOOST_ALIGN_ALIGN_UP_HPP\n\n#include <boost/align/detail/align_up.hpp>\n\nnamespace boost {\nnamespace alignment {\n\nBOOST_CONSTEXPR inline std::size_t\nalign_up(std::size_t value, std::size_t alignment) BOOST_NOEXCEPT\n{\n    return (value + alignment - 1) & ~(alignment - 1);\n}\n\n} /* alignment */\n} /* boost */\n\n#endif\n", "meta": {"hexsha": "6401ea848a63f19d229d5b2e719ca121dfc0bc4f", "size": 516, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/align/include/boost/align/align_up.hpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_stars_repo_licenses": ["BSL-1.0"], "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": "libs/align/include/boost/align/align_up.hpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "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": "libs/align/include/boost/align/align_up.hpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "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": 19.8461538462, "max_line_length": 65, "alphanum_fraction": 0.746124031, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430394931457, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5729115707795787}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/function/jacobi_elliptic.hpp>\n#include <boost/math/special_functions/jacobi_elliptic.hpp>\n#include <eve/constant/eps.hpp>\n#include <eve/constant/one.hpp>\n#include <eve/constant/pio_2.hpp>\n#include <eve/constant/zero.hpp>\n#include <eve/wide.hpp>\n\n\n\nTTS_CASE_TPL(\"Check eve::jacobi_elliptic behavior\", EVE_TYPE)\n{\n  using eve::jacobi_elliptic;\n  using eve::tag::jacobi_elliptic_;\n  using elt_t = eve::element_type_t<T>;\n  using eve::as;\n\n  auto nan   =  eve::nan(as<elt_t>());\n  auto pio_2 =  eve::pio_2(as<elt_t>());\n  auto one   =  eve::one(as<elt_t>());\n  auto zero  =  eve::zero(as<elt_t>());\n\n  auto refje = []<typename U>(U x,  U y){\n    U cn, dn;\n    U sn = boost::math::jacobi_elliptic(y, x, &cn, &dn);\n    return std::make_tuple(sn, cn, dn);\n  };\n\n  {\n    auto [esn, ecn, edn] = jacobi_elliptic(one,elt_t(0));\n    auto [bsn, bcn, bdn] = refje(one,elt_t(0));\n    TTS_ULP_EQUAL(esn, bsn, 1);\n    TTS_ULP_EQUAL(ecn, bcn, 1);\n    TTS_ULP_EQUAL(edn, bdn, 1);\n  }\n  {\n    auto [esn, ecn, edn] = jacobi_elliptic(zero,elt_t(0));\n    auto [bsn, bcn, bdn] = refje(zero,elt_t(0));\n    TTS_ULP_EQUAL(esn, bsn, 1);\n    TTS_ULP_EQUAL(ecn, bcn, 1);\n    TTS_ULP_EQUAL(edn, bdn, 1);\n  }\n  {\n    auto [esn, ecn, edn] = jacobi_elliptic(pio_2,elt_t(0));\n    auto [bsn, bcn, bdn] = refje(pio_2,elt_t(0));\n    TTS_ULP_EQUAL(esn, bsn, 1);\n    TTS_ULP_EQUAL(ecn, bcn, 3.5);\n    TTS_ULP_EQUAL(edn, bdn, 1);\n  }\n\n  {\n    auto [esn, ecn, edn] = jacobi_elliptic(one,elt_t(0.5));\n    auto [bsn, bcn, bdn] = refje(one,elt_t(0.5));\n    TTS_ULP_EQUAL(esn, bsn, 1);\n    TTS_ULP_EQUAL(ecn, bcn, 1);\n    TTS_ULP_EQUAL(edn, bdn, 1);\n  }\n  {\n    auto [esn, ecn, edn] = jacobi_elliptic(zero,elt_t(0.5));\n    auto [bsn, bcn, bdn] = refje(zero,elt_t(0.5));\n    TTS_ULP_EQUAL(esn, bsn, 1);\n    TTS_ULP_EQUAL(ecn, bcn, 1);\n    TTS_ULP_EQUAL(edn, bdn, 1);\n  }\n  {\n    auto [esn, ecn, edn] = jacobi_elliptic(pio_2,elt_t(0.5));\n    auto [bsn, bcn, bdn] = refje(pio_2,elt_t(0.5));\n    TTS_ULP_EQUAL(esn, bsn, 1);\n    TTS_ULP_EQUAL(ecn, bcn, 9);\n    TTS_ULP_EQUAL(edn, bdn, 1);\n  }\n  {\n    auto [esn, ecn, edn] = jacobi_elliptic(pio_2,elt_t(0.5));\n    auto [bsn, bcn, bdn] = refje(pio_2,elt_t(0.5));\n    TTS_ULP_EQUAL(esn, bsn, 1);\n    TTS_ULP_EQUAL(ecn, bcn, 9);\n    TTS_ULP_EQUAL(edn, bdn, 1);\n  }\n\n  {\n    auto [esn, ecn, edn] = jacobi_elliptic(one,elt_t(1.0));\n    auto [bsn, bcn, bdn] = refje(one,elt_t(1.0));\n    TTS_ULP_EQUAL(esn, bsn, 1);\n    TTS_ULP_EQUAL(ecn, bcn, 1);\n    TTS_ULP_EQUAL(edn, bdn, 1);\n  }\n  {\n    auto [esn, ecn, edn] = jacobi_elliptic(pio_2,elt_t(1.0));\n    auto [bsn, bcn, bdn] = refje(pio_2,elt_t(1.0));\n    TTS_ULP_EQUAL(esn, bsn, 1);\n    TTS_ULP_EQUAL(ecn, bcn, 1);\n    TTS_ULP_EQUAL(edn, bdn, 1.5);\n  }\n  {\n    auto [esn, ecn, edn] = jacobi_elliptic(nan,elt_t(1.0));\n    TTS_ULP_EQUAL(esn, nan, 1);\n    TTS_ULP_EQUAL(ecn, nan, 1);\n    TTS_ULP_EQUAL(edn, nan, 1);\n  }\n}\n", "meta": {"hexsha": "fa25512aeef8505e5ebf0ceb9b1274b83ac01229", "size": 3194, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/elliptic/jacobi_elliptic/regular/jacobi_elliptic.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/elliptic/jacobi_elliptic/regular/jacobi_elliptic.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/elliptic/jacobi_elliptic/regular/jacobi_elliptic.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5740740741, "max_line_length": 100, "alphanum_fraction": 0.5776455855, "num_tokens": 1295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5729115663974206}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n\n\n#include <boost/numeric/mtl/mtl.hpp>\n# include \"boost/rational.hpp\"\n# include \"boost/range.hpp\"\n\ntypedef boost::rational<long>  t_Q;\ntypedef mtl::dense_vector<t_Q> t_dVecQ;\ntypedef mtl::dense2D<t_Q> t_dMatQ;\n\nint main(int, char* [])\n{\n    //! Test Matrix-Vector operators\n    t_dMatQ mQ1(3,3); mtl::mat::diagonal_setup(mQ1,2);\n    std::cout << \"mQ1:\\n\" << mQ1 << \"\\n\";\n    std::cout << \"size(mQ1):\\n\" << mtl::mat::size(mQ1) << \"\\n\";\n\n    t_dVecQ vQ4(3,1);\n    //vQ4 *= mQ1;      // not defined yet -> ticket #254\n    std::cout << \"vQ4: \" << vQ4 << \"\\n\";\n\n    t_dVecQ vQ5( mQ1 * vQ4 );\n    std::cout << \"vQ5: \" << vQ5 << \"\\n\";\n\n    return 0;\n}\n\n", "meta": {"hexsha": "b043ca3d907208ea12a5a9dc732b8314496f1a01", "size": 1090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_vector_rational_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_rational_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_rational_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 27.25, "max_line_length": 94, "alphanum_fraction": 0.6229357798, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5729115663974206}}
{"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": "#ifndef GRADIENT_SH_H_\n#define GRADIENT_SH_H_\n\n#include \"gradient.hpp\"\n#include <Eigen/Dense>\n#include <complex>\n#include <memory>\n#include <vector>\n\nusing VecAry2cd =\n    std::vector<Eigen::Array22cd, Eigen::aligned_allocator<Eigen::Array22cd>>;\n\nnamespace grad_sh {\n\nclass GRTCoeff {\n  friend class IntegralLayer;\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  GRTCoeff(const Eigen::Ref<const Eigen::ArrayXXd> model, const double freq,\n           const double c);\n\nprivate:\n  void initialize_nv();\n  void initialize_E();\n  std::complex<double> get_Ad(const double z, const int ind_layer) const;\n  std::complex<double> get_Au(const double z, const int ind_layer) const;\n  std::complex<double> get_Ad_der(const double z, const int ind_layer) const;\n  std::complex<double> get_Au_der(const double z, const int ind_layer) const;\n\n  void compute_rtc();\n  void compute_grtc();\n  void compute_CdCu();\n\n  const Eigen::ArrayXd z_, rho_, beta_, alpha_, mu_;\n  const int nl_;\n  const std::complex<double> angfreq_;\n  const double c_;\n\n  Eigen::ArrayXcd nv_;\n  std::vector<Eigen::Matrix2cd, Eigen::aligned_allocator<Eigen::Matrix2cd>> e_;\n  Eigen::VectorXcd t_d_, r_ud_, r_du_, t_u_;\n  Eigen::VectorXcd gt_d_, gr_ud_, gr_du_, gt_u_;\n  Eigen::VectorXcd cd_, cu_;\n};\n\nclass IntegralLayer {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  IntegralLayer(const Eigen::Ref<const Eigen::ArrayXXd> model,\n                const double freq, const double c);\n\n  double compute_I1();\n  double compute_I2();\n  double compute_I3();\n  Eigen::ArrayXd compute_kvs();\n\nprivate:\n  void initialize_P();\n  void initialize_sigma();\n\n  double intker_ut2_top(int id_layer);\n  double intker_dut2_top(int id_layer);\n\n  double intker_ut2_bottom(int id_layer);\n  double intker_dut2_bottom(int id_layer);\n\n  void integrate_ut2();\n  void integrate_dut2();\n\n  const std::unique_ptr<GRTCoeff> grtc_;\n  const int nl_;\n  const double k_;\n  const double pvel_;\n  Eigen::ArrayXd z_, beta_, rho_, mu_;\n  Eigen::ArrayXcd nv_;\n  Eigen::ArrayXd thickness_;\n\n  Eigen::VectorXcd cd_, cu_;\n  VecAry2cd matP_u_u_;\n  VecAry2cd matP_uc_u_;\n  VecAry2cd matP_uc_uc_;\n  VecAry2cd matP_du_du_;\n  VecAry2cd matP_duc_du_;\n  VecAry2cd matP_duc_duc_;\n  VecAry2cd sigma_x_sigma_top_;\n  VecAry2cd sigmac_x_sigma_top_;\n  VecAry2cd sigma_x_sigmac_top_;\n  VecAry2cd sigmac_x_sigmac_top_;\n  VecAry2cd sigma_x_sigma_bottom_;\n  VecAry2cd sigmac_x_sigma_bottom_;\n  VecAry2cd sigma_x_sigmac_bottom_;\n  VecAry2cd sigmac_x_sigmac_bottom_;\n\n  Eigen::ArrayXd int_ut2_;\n  Eigen::ArrayXd int_dut2_;\n};\n\nclass GradientSH : public Gradient {\npublic:\n  using Gradient::Gradient;\n  ~GradientSH();\n  Eigen::ArrayXd compute(const double freq, const double c) const override;\n};\n\n} // namespace grad_sh\n#endif", "meta": {"hexsha": "2b80a6c6e349f84def6f590ac122e928410ee3fc", "size": 2717, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gradient_sh.hpp", "max_stars_repo_name": "pan3rock/DisbaTomo", "max_stars_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-07-30T03:27:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T14:05:47.000Z", "max_issues_repo_path": "include/gradient_sh.hpp", "max_issues_repo_name": "pan3rock/DisbaTomo", "max_issues_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gradient_sh.hpp", "max_forks_repo_name": "pan3rock/DisbaTomo", "max_forks_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2021-07-31T12:38:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T15:07:53.000Z", "avg_line_length": 25.3925233645, "max_line_length": 79, "alphanum_fraction": 0.7482517483, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900945711678, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.572841601879121}}
{"text": "// test_input.cpp - a test driver for UNtoU3 class.\n// \n// License: BSD 2-Clause (https://opensource.org/licenses/BSD-2-Clause)\n//\n// Copyright (c) 2019, Daniel Langr\n// All rights reserved.\n//\n// Program implements the U(N) to U(3) the input irrep [f] specified by the HO level n, N=(n+1)*(n+2)/2, \n// and its number of twos, ones, and zeros read from the standard input.\n// For instance, for the input U(21) irrep [f] = [2,2,2,2,2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],\n// the user should provide the following numbers: 5 6 1 14.\n//\n// The program performs the U(N) to U(3) reduction and calculates the sum of the dimensions\n// of resulting U(3) irrpes multiplied by their level dimensionalities, and print it to the\n// standard output. For instance, for the input irrep specified above, the output should read:\n// U(3) irreps total dim = 2168999910\n//\n// This sum should be equal to dim[f], which can be calculated analytically with the support \n// of rational numbers. The program performs this calculcation as well if the Boost library \n// is available and uses its Boost.Rational sublibrary. Availabitliy of Boost is indicated by\n// users by definition of HAVE_BOOST preprocessor symbol. \n// For the input irrep [f] specified above, the program should first print out:\n// U(N) irrep dim = 2168999910\n\n#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <stdexcept>\n#include <vector>\n\n#ifdef HAVE_BOOST\n#include <boost/rational.hpp>\n#endif\n\n//#define UNTOU3_DISABLE_TCE\n//#define UNTOU3_DISABLE_UNORDERED\n//#define UNTOU3_DISABLE_PRECALC\n#define UNTOU3_ENABLE_OPENMP\n#include \"UNtoU3.h\"\n\n#ifdef HAVE_BOOST\n// Impelments analytical formula for calculation of a dimension of a generic U(N) irrep [f].\n// [f] is specified by its labels passed as an array (generaly any indexed data structure)\n// argument irrep.\ntemplate <typename T>\nunsigned long dim(const T & irrep) {\n   const auto N = irrep.size();\n   boost::rational<unsigned long> result{1};\n   for (uint32_t l = 2; l <= N; l++)\n      for (uint32_t k = 1; k <= l - 1; k++)\n         result *= { irrep[k - 1] - irrep[l - 1] + l - k, l - k };\n\n   assert(result.denominator() == 1);\n   return result.numerator();\n}\n#endif\n\n// Implements analytical formula for calculcation of a dimension of an input U(3) irrep.\n// (Does not require rational arithmetics.)\nunsigned long dim(const UNtoU3<>::U3Weight & irrep) {\n   return (irrep[0] - irrep[1] + 1) * (irrep[0] - irrep[2] + 2) * (irrep[1] - irrep[2] + 1) / 2;\n}\n\nint main() {\n   // HO level \n   unsigned long n;\n   // specification of intput U(N) irrep\n   unsigned short n2, n1, n0;\n   std::cin >> n >> n2 >> n1 >> n0;\n\n   if (n2 + n1 + n0 != (n + 1) * (n + 2) / 2)\n      throw std::invalid_argument(\"Arguments mismatch!\");\n\n#ifdef HAVE_BOOST\n   // analytical calculation of dim([f])\n   std::vector<unsigned long> f(n2, 2);\n   std::fill_n(std::back_inserter(f), n1, 1);\n   std::fill_n(std::back_inserter(f), n0, 0);\n   std::cout << \"U(N) irrep dim = \" << dim(f) << std::endl;\n#endif\n\n   UNtoU3<> gen;\n   // generate HO vectors for a given n\n   gen.generateXYZ(n);\n   // generation of U(3) irreps in the input U(N) irrep [f]\n   gen.generateU3Weights(n2, n1, n0);\n   // calculated sum\n   unsigned long sum = 0;\n   // iteration over generated U(3) weights\n   for (const auto & pair : gen.multMap()) {\n      // get U(3) weight lables\n      const auto & weight = pair.first;\n      // get its level dimensionality if its nonzero and the U(3) weight is a U(3) irrep \n      if (auto D_l = gen.getLevelDimensionality(weight)) \n         // add contribution of this U(3) irrep to the sum\n         sum += D_l * dim(weight);\n   }\n   std::cout << \"U(3) irreps total dim = \" << sum << std::endl;\n}\n", "meta": {"hexsha": "3ce084e4c855ca1284ecd2a6a10baf6f52967ca2", "size": 3716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_input.cpp", "max_stars_repo_name": "kc9jud/UNtoU3", "max_stars_repo_head_hexsha": "999d12d73909c483a9dc92842badee515e814997", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-24T22:53:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T22:53:11.000Z", "max_issues_repo_path": "test_input.cpp", "max_issues_repo_name": "kc9jud/UNtoU3", "max_issues_repo_head_hexsha": "999d12d73909c483a9dc92842badee515e814997", "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": "test_input.cpp", "max_forks_repo_name": "kc9jud/UNtoU3", "max_forks_repo_head_hexsha": "999d12d73909c483a9dc92842badee515e814997", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-25T04:34:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T04:34:59.000Z", "avg_line_length": 36.7920792079, "max_line_length": 105, "alphanum_fraction": 0.6671151776, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959545, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5728342763895792}}
{"text": "#pragma once\n\n#include <boost/random/uniform_real.hpp>\n#include \"gen_generic.hpp\"\n#include \"matrix.hpp\"\n\nclass random_matrix_generator: public matrix_generator\n{\nprivate:\n  double _nonzero_probability;\n\npublic:\n  random_matrix_generator(size_t height, size_t width, double nonzero_probability, tu::log_level level) :\n    matrix_generator(\"random\", height, width, level), _nonzero_probability(nonzero_probability)\n  {\n\n  }\n\n  virtual ~random_matrix_generator()\n  {\n\n  }\n\n  virtual void generate()\n  {\n    log_generate_start();\n    boost::uniform_real<double> dist;\n\n    for (size_t row = 0; row < _height; ++row)\n    {\n      for (size_t column = 0; column < _width; ++column)\n      {\n        _matrix(row, column) = dist(_rng) > _nonzero_probability ? 0 : 1;\n      }\n    }\n    log_generate_end();\n    sign();\n  }\n\n  virtual bool do_pivot(size_t row, size_t column)\n  {\n    tu::matrix_ternary_pivot(_matrix, row, column);\n    return true;\n  }\n};\n", "meta": {"hexsha": "6d91b5e5c60666db6fec68a90b99837fd7144e79", "size": 943, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cmr/gen_random.hpp", "max_stars_repo_name": "discopt/cmr", "max_stars_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-04-13T12:48:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T11:56:31.000Z", "max_issues_repo_path": "src/cmr/gen_random.hpp", "max_issues_repo_name": "xammy/unimodularity-test", "max_issues_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2021-08-19T09:06:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-27T23:18:47.000Z", "max_forks_repo_path": "src/cmr/gen_random.hpp", "max_forks_repo_name": "discopt/cmr", "max_forks_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5, "max_line_length": 105, "alphanum_fraction": 0.6797454931, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5728342598680453}}
{"text": "/**\n * @file IrisTest.cpp\n *\n * @breif A very basic MLP to classify Iris\n *\n * @date 12/26/17\n * @author Ben Caine\n */\n\n#include \"../nn/Net.h\"\n#include \"../nn/loss/CrossEntropy.h\"\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n#include <map>\n#include <iomanip>\n\n\nconst std::map<std::string, int> IRIS_TYPE_TO_INT {\n        {\"Iris-setosa\", 0},\n        {\"Iris-versicolor\", 1},\n        {\"Iris-virginica\", 2}\n};\n\nstruct IrisDataset {\n    std::vector<std::array<float, 4>> data;\n    std::vector<int> labels;\n};\n\nIrisDataset loadIrisDataset(const std::string &path = \"../examples/data/iris_data.csv\") {\n    IrisDataset dataset;\n\n    std::ifstream irisFile(path);\n    std::string line;\n    while (std::getline(irisFile, line, '\\n')) {\n        std::vector<std::string> values;\n\n        // TODO: Replace boost or link properly in CMake. Can't figure out canoical name\n        // for algorithm/string\n        boost::split(values, line, [](char c) {\n            return c == ',';\n        });\n\n        if (values.size() < 5) {\n            std::cout << \"Found line with less than five elements, skipping\" << std::endl;\n            continue;\n        }\n\n        float sepalLength = std::stof(values[0]);\n        float sepalWidth  = std::stof(values[1]);\n        float petalLength = std::stof(values[2]);\n        float petalWidth  = std::stof(values[3]);\n        std::string labelName = values[4];\n\n        auto labelIter = IRIS_TYPE_TO_INT.find(labelName);\n\n        if (labelIter == IRIS_TYPE_TO_INT.end()) {\n            std::cerr << \"Unknown Iris type of: \" << labelName << \" please check dataset.\" << std::endl;\n            exit(-1);\n        }\n        int labelInt = labelIter->second;\n        dataset.data.push_back({sepalLength, sepalWidth, petalLength, petalWidth});\n        dataset.labels.push_back(labelInt);\n    }\n\n    return dataset;\n}\n\nint main() {\n    auto dataset = loadIrisDataset();\n\n    // TODO: Split into training and test\n    int batchSize = dataset.labels.size();\n    int numFeatures = dataset.data[0].size();\n    int numClasses = *std::max_element(dataset.labels.begin(), dataset.labels.end()) + 1;\n\n    Eigen::Tensor<float, 2> input(batchSize, numFeatures);\n    Eigen::Tensor<float, 2> labels(batchSize, numClasses);\n    input.setZero();\n    labels.setZero();\n\n    for (unsigned int ii = 0; ii < batchSize; ++ii) {\n        for (unsigned int feature = 0; feature < numFeatures; ++feature) {\n            input(ii, feature) = dataset.data[ii][feature];\n        }\n\n        labels(ii, dataset.labels[ii]) = 1.0;\n    }\n\n    int numHiddenNodes = 20;\n    bool useBias = true;\n\n    nn::Net<float> net;\n    net.add(new nn::Dense<>(batchSize, numFeatures, numHiddenNodes, useBias));\n    net.add(new nn::Relu<>());\n    net.add(new nn::Dense<>(batchSize, numHiddenNodes, numHiddenNodes, useBias));\n    net.add(new nn::Relu<>());\n    net.add(new nn::Dense<>(batchSize, numHiddenNodes, numClasses, useBias));\n    net.add(new nn::Softmax<>());\n\n    nn::CrossEntropyLoss<float, 2> lossFunc;\n    net.registerOptimizer(new nn::Adam<float>(0.01));\n\n    int numEpoch = 250;\n    for (unsigned int ii = 0; ii < numEpoch; ++ii) {\n        auto result = net.forward<2, 2>(input);\n\n        float loss = lossFunc.loss(result, labels);\n        float accuracy = lossFunc.accuracy(result, labels);\n        std::cout << std::setprecision(5);\n        std::cout << \"Epoch: \" << ii << \" loss: \" << loss << \" accuracy: \" << accuracy << std::endl;\n\n        auto lossBack = lossFunc.backward(result, labels);\n        net.backward(lossBack);\n        net.step();\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "319399d709e294fa0c6720dc6f2e93a4eeb84ebf", "size": 3562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/IrisTest.cpp", "max_stars_repo_name": "bcaine/nn_cpp", "max_stars_repo_head_hexsha": "447ffa49f591e1c1c6dad0a1ab8b4f72411385b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T03:52:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-06T14:32:49.000Z", "max_issues_repo_path": "examples/IrisTest.cpp", "max_issues_repo_name": "bcaine/nn_cpp", "max_issues_repo_head_hexsha": "447ffa49f591e1c1c6dad0a1ab8b4f72411385b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-10T09:32:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-10T09:32:21.000Z", "max_forks_repo_path": "examples/IrisTest.cpp", "max_forks_repo_name": "bcaine/nn_cpp", "max_forks_repo_head_hexsha": "447ffa49f591e1c1c6dad0a1ab8b4f72411385b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-17T04:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T09:42:35.000Z", "avg_line_length": 29.6833333333, "max_line_length": 104, "alphanum_fraction": 0.6005053341, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5727948861549083}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/concept/value.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/constant/pio_2.hpp>\n#include <eve/function/ellint_rc.hpp>\n#include <boost/math/special_functions/ellint_rc.hpp>\n#include <cmath>\n\n//==================================================================================================\n// Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of ellint_rc\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n\n  TTS_EXPR_IS( eve::ellint_rc(T(), T())  , T);\n  TTS_EXPR_IS( eve::ellint_rc(v_t(), v_t()), v_t);\n  TTS_EXPR_IS( eve::ellint_rc(T(), v_t()), T);\n  TTS_EXPR_IS( eve::ellint_rc(v_t(), T()), T);\n};\n\n//==================================================================================================\n// ellint_rc  tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of ellint_rc on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate( eve::test::randoms(0, 100.0)\n                             , eve::test::randoms(0, 100.0))\n        )\n<typename T>(T const& x, T const& y)\n{\n  using eve::detail::map;\n  using v_t = eve::element_type_t<T>;\n\n  TTS_ULP_EQUAL(eve::ellint_rc(x, y) , map([](auto e, auto f) -> v_t { return boost::math::ellint_rc(e, f); }, x, y), 11);\n};\n", "meta": {"hexsha": "32d69a04f36d4da296feb208291c4c9e64cbd837", "size": 1802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/elliptic/ellint_rc.cpp", "max_stars_repo_name": "leha-bot/eve", "max_stars_repo_head_hexsha": "30e7a7f6bcc5cf524a6c2cc624234148eee847be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 340.0, "max_stars_repo_stars_event_min_datetime": "2020-09-16T21:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:40:33.000Z", "max_issues_repo_path": "test/unit/module/real/elliptic/ellint_rc.cpp", "max_issues_repo_name": "leha-bot/eve", "max_issues_repo_head_hexsha": "30e7a7f6bcc5cf524a6c2cc624234148eee847be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383.0, "max_issues_repo_issues_event_min_datetime": "2020-09-17T06:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T15:58:53.000Z", "max_forks_repo_path": "test/unit/module/real/elliptic/ellint_rc.cpp", "max_forks_repo_name": "leha-bot/eve", "max_forks_repo_head_hexsha": "30e7a7f6bcc5cf524a6c2cc624234148eee847be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-02-27T23:11:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T12:31:29.000Z", "avg_line_length": 38.3404255319, "max_line_length": 122, "alphanum_fraction": 0.4173140954, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5727948800224222}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"WindowFuncs.hpp\"\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FFT.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/FluidTensor.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass STFT\n{\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXXd = Eigen::ArrayXXd;\n  using ArrayXcd = Eigen::ArrayXcd;\n  using ArrayXXcd = Eigen::ArrayXXcd;\n\npublic:\n  STFT(index windowSize, index fftSize, index hopSize, index windowType = 0)\n      : mWindowSize(windowSize), mHopSize(hopSize), mFrameSize(fftSize / 2 + 1),\n        mFFT(fftSize)\n  {\n    mWindow = ArrayXd::Zero(mWindowSize);\n    auto windowTypeIndex = static_cast<WindowFuncs::WindowTypes>(windowType);\n    WindowFuncs::map()[windowTypeIndex](mWindowSize, mWindow);\n  }\n\n  static void magnitude(const FluidTensorView<std::complex<double>, 2> in,\n                        FluidTensorView<double, 2>                     out)\n  {\n    ArrayXXd mag = _impl::asEigen<Eigen::Array>(in).abs().real();\n    out <<= _impl::asFluid(mag);\n  }\n\n  static void magnitude(const FluidTensorView<std::complex<double>, 1> in,\n                        FluidTensorView<double, 1>                     out)\n  {\n    ArrayXd mag = _impl::asEigen<Eigen::Array>(in).abs().real();\n    out <<= _impl::asFluid(mag);\n  }\n\n  static void phase(const FluidTensorView<std::complex<double>, 2> in,\n                    FluidTensorView<double, 2>                     out)\n  {\n    ArrayXXd phase = _impl::asEigen<Eigen::Array>(in).arg().real();\n    out <<= _impl::asFluid(phase);\n  }\n\n  static void phase(const FluidTensorView<std::complex<double>, 1> in,\n                    FluidTensorView<double, 1>                     out)\n  {\n    phase(FluidTensorView<std::complex<double>, 2>(in),\n          FluidTensorView<double, 2>(out));\n  }\n\n\n  void process(const RealVectorView audio, ComplexMatrixView spectrogram)\n  {\n    index   halfWindow = mWindowSize / 2;\n    ArrayXd padded(audio.size() + mWindowSize + mHopSize);\n    padded.fill(0);\n    padded.segment(halfWindow, audio.size()) =\n        Eigen::Map<const ArrayXd>(audio.data(), audio.size());\n    index nFrames = static_cast<index>(\n        std::floor((padded.size() - mWindowSize) / mHopSize));\n\n    ArrayXXcd result(nFrames, mFrameSize);\n    for (index i = 0; i < nFrames; i++)\n    {\n      result.row(i) =\n          mFFT.process(padded.segment(i * mHopSize, mWindowSize) * mWindow);\n    }\n    spectrogram <<= _impl::asFluid(result);\n  }\n\n  void processFrame(const RealVectorView frame, ComplexVectorView out)\n  {\n    assert(frame.size() == mWindowSize);\n    ArrayXcd spectrum =\n        mFFT.process(_impl::asEigen<Eigen::Array>(frame) * mWindow);\n    out <<= _impl::asFluid(spectrum);\n  }\n\n  void processFrame(Eigen::Ref<ArrayXd> frame, Eigen::Ref<ArrayXcd> out)\n  {\n    assert(frame.size() == mWindowSize);\n    out = mFFT.process(frame * mWindow);\n  }\n\n\n  RealVectorView window()\n  {\n    return RealVectorView(mWindow.data(), 0, mWindowSize);\n  }\n\nprivate:\n  index   mWindowSize;\n  index   mHopSize;\n  index   mFrameSize;\n  ArrayXd mWindow;\n  FFT     mFFT;\n};\n\nclass ISTFT\n{\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXcd = Eigen::ArrayXcd;\n  using ArrayXXcd = Eigen::ArrayXXcd;\n\npublic:\n  ISTFT(index windowSize, index fftSize, index hopSize, index windowType = 0)\n      : mWindowSize(windowSize), mHopSize(hopSize), mScale(1 / double(fftSize)),\n        mIFFT(fftSize), mBuffer(mWindowSize)\n  {\n    mWindow = ArrayXd::Zero(mWindowSize);\n    auto windowTypeIndex = static_cast<WindowFuncs::WindowTypes>(windowType);\n    WindowFuncs::map()[windowTypeIndex](mWindowSize, mWindow);\n    mWindowSquared = mWindow * mWindow;\n  }\n\n  void process(const ComplexMatrixView spectrogram, RealVectorView audio)\n  {\n    const auto& epsilon = std::numeric_limits<double>::epsilon;\n\n    index halfWindow = mWindowSize / 2;\n    index nFrames = spectrogram.rows();\n    index outputSize = mWindowSize + (nFrames - 1) * mHopSize;\n    outputSize += mWindowSize + mHopSize;\n    ArrayXXcd specData = _impl::asEigen<Eigen::Array>(spectrogram);\n    ArrayXd   outputPadded = ArrayXd::Zero(outputSize);\n    ArrayXd   norm = ArrayXd::Zero(outputSize);\n    for (index i = 0; i < nFrames; i++)\n    {\n      ArrayXd frame = mIFFT.process(specData.row(i)).segment(0, mWindowSize);\n      outputPadded.segment(i * mHopSize, mWindowSize) +=\n          frame * mScale * mWindow;\n      norm.segment(i * mHopSize, mWindowSize) += mWindow * mWindow;\n    }\n    outputPadded = outputPadded / norm.max(epsilon());\n    ArrayXd trimmed = outputPadded.segment(halfWindow, audio.size());\n    audio <<= _impl::asFluid(trimmed);\n  }\n\n  void processFrame(const ComplexVectorView frame, RealVectorView audio)\n  {\n    mBuffer = mIFFT.process(_impl::asEigen<Eigen::Array>(frame))\n                  .segment(0, mWindowSize) *\n              mWindow * mScale;\n    audio <<= _impl::asFluid(mBuffer);\n  }\n\n  void processFrame(Eigen::Ref<ArrayXcd> frame, Eigen::Ref<ArrayXd> audio)\n  {\n    audio = mIFFT.process(frame).segment(0, mWindowSize) * mWindow * mScale;\n  }\n\n  RealVectorView window()\n  {\n    return RealVectorView(mWindow.data(), 0, mWindowSize);\n  }\n\nprivate:\n  index   mWindowSize{1024};\n  index   mHopSize{512};\n  ArrayXd mWindow;\n  ArrayXd mWindowSquared;\n  double  mScale{1};\n  IFFT    mIFFT;\n  ArrayXd mBuffer;\n};\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "f6d68c13a7b7411c6ae23c6d6ad524cda8c92163", "size": 5854, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/STFT.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/STFT.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/STFT.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9735449735, "max_line_length": 80, "alphanum_fraction": 0.6643320806, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5727680035745888}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/gamma.hpp>\n#include <test/unit/math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdGammaQ, Fvar){\n  using stan::math::fvar;\n  using stan::math::gamma_q;\n  using boost::math::gamma_q;\n\n  fvar<double> x(0.5);\n  x.d_ = 1.0;\n  fvar<double> y (1.0);\n  y.d_ = 1.0;\n\n  fvar<double> a = gamma_q(x,y);\n  EXPECT_FLOAT_EQ(gamma_q(0.5,1.0), a.val_);\n  EXPECT_FLOAT_EQ(0.18228334, a.d_);\n\n  double z = 1.0;\n  double w = 0.5;\n\n  a = gamma_q(x,z);\n  EXPECT_FLOAT_EQ(gamma_q(0.5,1.0), a.val_);\n  EXPECT_FLOAT_EQ(0.38983709, a.d_);\n\n  a = gamma_q(w,y);\n  EXPECT_FLOAT_EQ(gamma_q(0.5,1.0), a.val_);\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0), a.d_);\n\n  EXPECT_THROW(gamma_q(-x,y), std::domain_error);\n  EXPECT_THROW(gamma_q(x,-y), std::domain_error);\n}\n\nTEST(AgradFwdGammaQ, FvarFvarDouble) {\n  using stan::math::fvar;\n  using boost::math::gamma_q;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<double> > a = gamma_q(x,y);\n\n  EXPECT_FLOAT_EQ(gamma_q(0.5,1.0), a.val_.val_);\n  EXPECT_FLOAT_EQ(0.38983709, a.val_.d_);\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5,1.0), a.d_.val_);\n  EXPECT_FLOAT_EQ(-0.40753385, a.d_.d_);\n}\n\nstruct gamma_q_fun {\n  template <typename T0, typename T1>\n  inline \n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return gamma_q(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdGammaQ, nan) {\n  gamma_q_fun gamma_q_;\n  test_nan_fwd(gamma_q_,3.0,5.0,false);\n}\n", "meta": {"hexsha": "8703f12e38c54bf51e9d1933bfd3570ec735b70f", "size": 1646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/gamma_q_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/gamma_q_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/gamma_q_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8550724638, "max_line_length": 72, "alphanum_fraction": 0.6658566221, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5727253401497464}}
{"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 * Copyright 2015 C. Brett Witherspoon\n */\n\n#define BOOST_TEST_MODULE signum_tests\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\n#include <cmath>\n\n#include \"signum/oscillator.hpp\"\n\nBOOST_AUTO_TEST_CASE(double_oscillator_test)\n{\n  const double thresh = 1e-14;\n  const double freq = 10;\n  const double rate = 50;\n\n  std::array<double, 50> output;\n\n  signum::oscillator<double> osc(freq, rate);\n\n  osc(output);\n\n  for (auto i = 0U; i < output.size(); ++i)\n    if (std::abs(output[i]) > thresh)\n      BOOST_CHECK_CLOSE(output[i], sin(2*M_PI*freq/rate*(i+1)), 0.0001);\n}\n\nBOOST_AUTO_TEST_CASE(complex_oscillator_test)\n{\n  const double thresh = 1e-12;\n  const double freq = 100;\n  const double rate = 650;\n\n  std::array<std::complex<double>, 650> output;\n\n  signum::oscillator<std::complex<double>> osc(freq, rate);\n\n  osc(output);\n\n  for (auto i = 0U; i < output.size(); ++i)\n  {\n    if (std::abs(output[i].real()) > thresh)\n      BOOST_CHECK_CLOSE(output[i].real(), cos(2*M_PI*freq/rate*i), 0.0001);\n    if (std::abs(output[i].imag()) > thresh)\n      BOOST_CHECK_CLOSE(output[i].imag(), sin(2*M_PI*freq/rate*i), 0.01);\n  }\n}\n", "meta": {"hexsha": "511f05163cfd4c2658377cb15430ab2ef4a2618d", "size": 1167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/oscillator_test.cpp", "max_stars_repo_name": "spoonb/libcomm", "max_stars_repo_head_hexsha": "5638dac889bddb16420d8321067c783438a5deaf", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/oscillator_test.cpp", "max_issues_repo_name": "spoonb/libcomm", "max_issues_repo_head_hexsha": "5638dac889bddb16420d8321067c783438a5deaf", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/oscillator_test.cpp", "max_forks_repo_name": "spoonb/libcomm", "max_forks_repo_head_hexsha": "5638dac889bddb16420d8321067c783438a5deaf", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.34, "max_line_length": 75, "alphanum_fraction": 0.6692373608, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782012, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5727116337362567}}
{"text": "#include \"stdafx.h\"\n\n#include <iostream>\n#include <stdio.h>\n\n#include <Math.h>\n#include <Eigen/Geometry>\n\n#include <opencv2/core/core.hpp>\n\nusing namespace std;\nusing namespace cv;\n\nconst int SMOOTHING_WINDOW_SIZE = 10;\n\nvector<Point2d> point_history;\n\nvector<float> weights;\nfloat weight_sum = 0;\n\n// create and initialize weights and history vectors\nvoid gaze_smoothing_init(){\n\tfor (float i = 1; i < SMOOTHING_WINDOW_SIZE; i++){\n\t\tweights.push_back(i);\n\t\tweight_sum += i;\n\t\tpoint_history.push_back(Point2d(0,0));\n\t}\n}\n\n// very simple smoothing low-pass filter\nPoint2d smooth_gaze(Point2d gaze_point){\n\t\n\tPoint2d point_to_return(0,0);\n\n\trotate(point_history.begin(), point_history.begin() + 1, point_history.end());\n\tpoint_history[point_history.size()-1] = gaze_point;\n\n\tfor (int i = 0; i < weights.size(); i++)\n\t\tpoint_to_return += point_history[i] * (weights[i]/weight_sum);\n\n\treturn point_to_return;\n}", "meta": {"hexsha": "e9febeb8221a36b619a4c2e0aa89ad98fea184ef", "size": 906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EyeTab_SP2/gaze_smoothing.cpp", "max_stars_repo_name": "errollw/EyeTab", "max_stars_repo_head_hexsha": "4aa63fdd23c3a9eadcfa30a356cd6d48f55a9055", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-03-16T06:00:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:22:35.000Z", "max_issues_repo_path": "EyeTab_SP2/gaze_smoothing.cpp", "max_issues_repo_name": "Amal-Vincent/EyeTab", "max_issues_repo_head_hexsha": "4aa63fdd23c3a9eadcfa30a356cd6d48f55a9055", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-11-01T06:49:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-12T08:43:36.000Z", "max_forks_repo_path": "EyeTab_SP2/gaze_smoothing.cpp", "max_forks_repo_name": "Amal-Vincent/EyeTab", "max_forks_repo_head_hexsha": "4aa63fdd23c3a9eadcfa30a356cd6d48f55a9055", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-02-18T21:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T10:56:01.000Z", "avg_line_length": 21.5714285714, "max_line_length": 79, "alphanum_fraction": 0.729580574, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276224, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5727116291355094}}
{"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": "/**\n *          Copyright Matthias Walter 2010.\n * Distributed under the Boost Software License, Version 1.0.\n *    (See accompanying file LICENSE_1_0.txt or copy at\n *          http://www.boost.org/LICENSE_1_0.txt)\n **/\n\n#ifndef GEN_RANDOM_HPP_\n#define GEN_RANDOM_HPP_\n\n#include <boost/random/uniform_real.hpp>\n#include \"gen_generic.hpp\"\n#include \"matrix.hpp\"\n\nclass random_matrix_generator: public matrix_generator\n{\nprivate:\n  double _nonzero_probability;\n\npublic:\n  random_matrix_generator(size_t height, size_t width, double nonzero_probability, unimod::log_level level) :\n    matrix_generator(\"random\", height, width, level), _nonzero_probability(nonzero_probability)\n  {\n\n  }\n\n  virtual ~random_matrix_generator()\n  {\n\n  }\n\n  virtual void generate()\n  {\n    log_generate_start();\n    boost::uniform_real<double> dist;\n\n    for (size_t row = 0; row < _height; ++row)\n    {\n      for (size_t column = 0; column < _width; ++column)\n      {\n        _matrix(row, column) = dist(_rng) > _nonzero_probability ? 0 : 1;\n      }\n    }\n    log_generate_end();\n    sign();\n  }\n\n  virtual bool do_pivot(size_t row, size_t column)\n  {\n    unimod::matrix_ternary_pivot(_matrix, row, column);\n    return true;\n  }\n};\n\n#endif\n", "meta": {"hexsha": "a4d0b963454eb6784f7b20636fde4a6cd8e83592", "size": 1216, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "unimodularity-library-1.2c/src/gen_random.hpp", "max_stars_repo_name": "vios-fish/CompetitiveProgramming", "max_stars_repo_head_hexsha": "6953f024e4769791225c57ed852cb5efc03eb94b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-05T21:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-08T01:33:12.000Z", "max_issues_repo_path": "src/gen_random.hpp", "max_issues_repo_name": "vbraun/unimodularity-library", "max_issues_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gen_random.hpp", "max_forks_repo_name": "vbraun/unimodularity-library", "max_forks_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7142857143, "max_line_length": 109, "alphanum_fraction": 0.6833881579, "num_tokens": 308, "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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// With contributions from Cornelius Steinhardt\n\n#ifndef MTL_MATRIX_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": "/*\n * Copyright Nick Thompson, 2019\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <boost/math/interpolators/cardinal_quadratic_b_spline.hpp>\nusing boost::math::interpolators::cardinal_quadratic_b_spline;\n\ntemplate<class Real>\nvoid test_constant()\n{\n    Real c = 7.2;\n    Real t0 = 0;\n    Real h = Real(1)/Real(16);\n    size_t n = 512;\n    std::vector<Real> v(n, c);\n    auto qbs = cardinal_quadratic_b_spline<Real>(v.data(), v.size(), t0, h);\n\n    size_t i = 0;\n    while (i < n) {\n      Real t = t0 + i*h;\n      CHECK_ULP_CLOSE(c, qbs(t), 2);\n      CHECK_MOLLIFIED_CLOSE(0, qbs.prime(t), 100*std::numeric_limits<Real>::epsilon());\n      ++i;\n    }\n\n    i = 0;\n    while (i < n) {\n      Real t = t0 + i*h + h/2;\n      CHECK_ULP_CLOSE(c, qbs(t), 2);\n      CHECK_MOLLIFIED_CLOSE(0, qbs.prime(t), 300*std::numeric_limits<Real>::epsilon());\n      t = t0 + i*h + h/4;\n      CHECK_ULP_CLOSE(c, qbs(t), 2);\n      CHECK_MOLLIFIED_CLOSE(0, qbs.prime(t), 150*std::numeric_limits<Real>::epsilon());\n      ++i;\n    }\n}\n\ntemplate<class Real>\nvoid test_linear()\n{\n    Real m = 8.3;\n    Real b = 7.2;\n    Real t0 = 0;\n    Real h = Real(1)/Real(16);\n    size_t n = 512;\n    std::vector<Real> y(n);\n    for (size_t i = 0; i < n; ++i) {\n      Real t = i*h;\n      y[i] = m*t + b;\n    }\n    auto qbs = cardinal_quadratic_b_spline<Real>(y.data(), y.size(), t0, h);\n\n    size_t i = 0;\n    while (i < n) {\n      Real t = t0 + i*h;\n      CHECK_ULP_CLOSE(m*t+b, qbs(t), 2);\n      CHECK_ULP_CLOSE(m, qbs.prime(t), 820);\n      ++i;\n    }\n\n    i = 0;\n    while (i < n) {\n      Real t = t0 + i*h + h/2;\n      CHECK_ULP_CLOSE(m*t+b, qbs(t), 2);\n      CHECK_MOLLIFIED_CLOSE(m, qbs.prime(t), 1500*std::numeric_limits<Real>::epsilon());\n      t = t0 + i*h + h/4;\n      CHECK_ULP_CLOSE(m*t+b, qbs(t), 3);\n      CHECK_MOLLIFIED_CLOSE(m, qbs.prime(t), 1500*std::numeric_limits<Real>::epsilon());\n      ++i;\n    }\n}\n\ntemplate<class Real>\nvoid test_quadratic()\n{\n    Real a = 8.2;\n    Real b = 7.2;\n    Real c = -9.2;\n    Real t0 = 0;\n    Real h = Real(1)/Real(16);\n    size_t n = 513;\n    std::vector<Real> y(n);\n    for (size_t i = 0; i < n; ++i) {\n      Real t = i*h;\n      y[i] = a*t*t + b*t + c;\n    }\n    Real t_max = t0 + (n-1)*h;\n    auto qbs = cardinal_quadratic_b_spline<Real>(y, t0, h, b, 2*a*t_max + b);\n\n    size_t i = 0;\n    while (i < n) {\n      Real t = t0 + i*h;\n      CHECK_ULP_CLOSE(a*t*t + b*t + c, qbs(t), 2);\n      ++i;\n    }\n\n    i = 0;\n    while (i < n) {\n      Real t = t0 + i*h + h/2;\n      CHECK_ULP_CLOSE(a*t*t + b*t + c, qbs(t), 47);\n\n      t = t0 + i*h + h/4;\n      if (!CHECK_ULP_CLOSE(a*t*t + b*t + c, qbs(t), 104)) {\n          std::cerr << \"  Problem abscissa t = \" << t << \"\\n\";\n      }\n      ++i;\n    }\n}\n\nint main()\n{\n    test_constant<float>();\n    test_constant<double>();\n    test_constant<long double>();\n\n    test_linear<float>();\n    test_linear<double>();\n    test_linear<long double>();\n\n    test_quadratic<double>();\n    test_quadratic<long double>();\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "33ad0efe0352c1ba72b8b02782f7642eee7e3220", "size": 3233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/test/cardinal_quadratic_b_spline_test.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/math/test/cardinal_quadratic_b_spline_test.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/math/test/cardinal_quadratic_b_spline_test.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 24.679389313, "max_line_length": 88, "alphanum_fraction": 0.5505722239, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5726152860356942}}
{"text": "/**\n * @file activation_functions_test.cpp\n * @author Marcus Edel\n *\n * Tests for the various activation functions.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>\n#include <mlpack/methods/ann/activation_functions/identity_function.hpp>\n#include <mlpack/methods/ann/activation_functions/softsign_function.hpp>\n#include <mlpack/methods/ann/activation_functions/tanh_function.hpp>\n#include <mlpack/methods/ann/activation_functions/rectifier_function.hpp>\n\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n#include <mlpack/methods/ann/optimizer/rmsprop.hpp>\n#include <mlpack/methods/ann/performance_functions/mse_function.hpp>\n\n#include <mlpack/methods/ann/layer/bias_layer.hpp>\n#include <mlpack/methods/ann/layer/linear_layer.hpp>\n#include <mlpack/methods/ann/layer/base_layer.hpp>\n#include <mlpack/methods/ann/layer/binary_classification_layer.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(ActivationFunctionsTest);\n\n// Be careful!  When writing new tests, always get the boolean value and store\n// it in a temporary, because the Boost unit test macros do weird things and\n// will cause bizarre problems.\n\n// Generate dataset for activation function tests.\nconst arma::colvec activationData(\"-2 3.2 4.5 -100.2 1 -1 2 0\");\n\n/*\n * Implementation of the activation function test.\n *\n * @param input Input data used for evaluating the activation function.\n * @param target Target data used to evaluate the activation.\n *\n * @tparam ActivationFunction Activation function used for the check.\n */\ntemplate<class ActivationFunction>\nvoid CheckActivationCorrect(const arma::colvec input, const arma::colvec target)\n{\n  // Test the activation function using a single value as input.\n  for (size_t i = 0; i < target.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(ActivationFunction::fn(input.at(i)),\n        target.at(i), 1e-3);\n  }\n\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  ActivationFunction::fn(input, activations);\n  for (size_t i = 0; i < activations.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3);\n  }\n}\n\n/*\n * Implementation of the activation function derivative test.\n *\n * @param input Input data used for evaluating the activation function.\n * @param target Target data used to evaluate the activation.\n *\n * @tparam ActivationFunction Activation function used for the check.\n */\ntemplate<class ActivationFunction>\nvoid CheckDerivativeCorrect(const arma::colvec input, const arma::colvec target)\n{\n  // Test the calculation of the derivatives using a single value as input.\n  for (size_t i = 0; i < target.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(ActivationFunction::deriv(input.at(i)),\n        target.at(i), 1e-3);\n  }\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec derivatives;\n  ActivationFunction::deriv(input, derivatives);\n  for (size_t i = 0; i < derivatives.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3);\n  }\n}\n\n/*\n * Implementation of the activation function inverse test.\n *\n * @param input Input data used for evaluating the activation function.\n * @param target Target data used to evaluate the activation.\n *\n * @tparam ActivationFunction Activation function used for the check.\n */\ntemplate<class ActivationFunction>\nvoid CheckInverseCorrect(const arma::colvec input)\n{\n    // Test the calculation of the inverse using a single value as input.\n  for (size_t i = 0; i < input.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(ActivationFunction::inv(ActivationFunction::fn(\n        input.at(i))), input.at(i), 1e-3);\n  }\n\n  // Test the calculation of the inverse using the entire vector as input.\n  arma::colvec activations;\n  ActivationFunction::fn(input, activations);\n  ActivationFunction::inv(activations, activations);\n\n  for (size_t i = 0; i < input.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), input.at(i), 1e-3);\n  }\n}\n\n/**\n * Basic test of the tanh function.\n */\nBOOST_AUTO_TEST_CASE(TanhFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-0.96402758 0.9966824 0.99975321 -1 \\\n                                         0.76159416 -0.76159416 0.96402758 0\");\n\n  const arma::colvec desiredDerivatives(\"0.07065082 0.00662419 0.00049352 0 \\\n                                         0.41997434 0.41997434 0.07065082 1\");\n\n  CheckActivationCorrect<TanhFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<TanhFunction>(desiredActivations, desiredDerivatives);\n  CheckInverseCorrect<TanhFunction>(desiredActivations);\n}\n\n/**\n * Basic test of the logistic function.\n */\nBOOST_AUTO_TEST_CASE(LogisticFunctionTest)\n{\n  const arma::colvec desiredActivations(\"1.19202922e-01 9.60834277e-01 \\\n                                         9.89013057e-01 3.04574e-44 \\\n                                         7.31058579e-01 2.68941421e-01 \\\n                                         8.80797078e-01 0.5\");\n\n  const arma::colvec desiredDerivatives(\"0.10499359 0.03763177 0.01086623 \\\n                                         3.04574e-44 0.19661193 0.19661193 \\\n                                         0.10499359 0.25\");\n\n  CheckActivationCorrect<LogisticFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<LogisticFunction>(desiredActivations,\n      desiredDerivatives);\n  CheckInverseCorrect<LogisticFunction>(activationData);\n}\n\n/**\n * Basic test of the softsign function.\n */\nBOOST_AUTO_TEST_CASE(SoftsignFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-0.66666667 0.76190476 0.81818182 \\\n                                         -0.99011858 0.5 -0.5 0.66666667 0\");\n\n  const arma::colvec desiredDerivatives(\"0.11111111 0.05668934 0.03305785 \\\n                                         9.7642e-05 0.25 0.25 0.11111111 1\");\n\n  CheckActivationCorrect<SoftsignFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<SoftsignFunction>(desiredActivations,\n      desiredDerivatives);\n  CheckInverseCorrect<SoftsignFunction>(desiredActivations);\n}\n\n/**\n * Basic test of the identity function.\n */\nBOOST_AUTO_TEST_CASE(IdentityFunctionTest)\n{\n  const arma::colvec desiredDerivatives = arma::ones<arma::colvec>(\n      activationData.n_elem);\n\n  CheckActivationCorrect<IdentityFunction>(activationData, activationData);\n  CheckDerivativeCorrect<IdentityFunction>(activationData, desiredDerivatives);\n}\n\n/**\n * Basic test of the rectifier function.\n */\nBOOST_AUTO_TEST_CASE(RectifierFunctionTest)\n{\n  const arma::colvec desiredActivations(\"0 3.2 4.5 0 1 0 2 0\");\n\n  const arma::colvec desiredDerivatives(\"0 1 1 0 1 0 1 0\");\n\n  CheckActivationCorrect<RectifierFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<RectifierFunction>(desiredActivations,\n      desiredDerivatives);\n}\n\n/*\n * Implementation of the numerical gradient checking.\n *\n * @param input Input data used for evaluating the network.\n * @param target Target data used to calculate the network error.\n * @param perturbation Constant perturbation value.\n * @param threshold Threshold used as bounding check.\n *\n * @tparam ActivationFunction Activation function used for the gradient check.\n */\ntemplate<class ActivationFunction>\nvoid CheckGradientNumericallyCorrect(const arma::mat input,\n                                     const arma::mat target,\n                                     const double perturbation,\n                                     const double threshold)\n{\n  // Specify the structure of the feed forward neural network.\n  RandomInitialization randInit(-0.5, 0.5);\n  arma::mat error;\n\n  // Number of hidden layer units.\n  const size_t hiddenLayerSize = 4;\n\n  LinearLayer<mlpack::ann::RMSPROP, RandomInitialization> linearLayer0(\n        input.n_rows, hiddenLayerSize, randInit);\n  BiasLayer<> biasLayer0(hiddenLayerSize);\n  BaseLayer<ActivationFunction> baseLayer0;\n\n  LinearLayer<mlpack::ann::RMSPROP, RandomInitialization> linearLayer1(\n         hiddenLayerSize, hiddenLayerSize, randInit);\n  BiasLayer<> biasLayer1(hiddenLayerSize);\n  BaseLayer<ActivationFunction> baseLayer1;\n\n  LinearLayer<mlpack::ann::RMSPROP, RandomInitialization> linearLayer2(\n         hiddenLayerSize, target.n_rows, randInit);\n  BiasLayer<> biasLayer2(target.n_rows);\n  BaseLayer<ActivationFunction> baseLayer2;\n\n  BinaryClassificationLayer classOutputLayer;\n\n  auto modules = std::tie(linearLayer0, biasLayer0, baseLayer0,\n                          linearLayer1, biasLayer1, baseLayer1,\n                          linearLayer2, biasLayer2, baseLayer2);\n\n  FFN<decltype(modules), decltype(classOutputLayer), MeanSquaredErrorFunction>\n      net(modules, classOutputLayer);\n\n  // Initialize the feed forward neural network.\n  net.FeedForward(input, target, error);\n  net.FeedBackward(input, error);\n\n  std::vector<std::reference_wrapper<decltype(linearLayer0)> > layer {\n         linearLayer0, linearLayer1, linearLayer2 };\n\n  std::vector<arma::mat> gradient {linearLayer0.Gradient(),\n                                   linearLayer1.Gradient(),\n                                   linearLayer2.Gradient()};\n\n  double weight, mLoss, pLoss, dW, e;\n\n  for (size_t l = 0; l < layer.size(); ++l)\n  {\n    for (size_t i = 0; i < layer[l].get().Weights().n_rows; ++i)\n    {\n      for (size_t j = 0; j < layer[l].get().Weights().n_cols; ++j)\n      {\n        // Store original weight.\n        weight = layer[l].get().Weights()(i, j);\n\n        // Add negative perturbation and compute error.\n        layer[l].get().Weights().at(i, j) -= perturbation;\n        net.FeedForward(input, target, error);\n        mLoss = arma::as_scalar(0.5 * arma::sum(arma::pow(error, 2)));\n\n        // Add positive perturbation and compute error.\n        layer[l].get().Weights().at(i, j) += (2 * perturbation);\n        net.FeedForward(input, target, error);\n        pLoss = arma::as_scalar(0.5 * arma::sum(arma::pow(error, 2)));\n\n        // Compute symmetric difference.\n        dW = (pLoss - mLoss) / (2 * perturbation);\n        e = std::abs(dW - gradient[l].at(i, j));\n\n        bool b = e < threshold;\n        BOOST_REQUIRE_EQUAL(b, 1);\n\n        // Restore original weight.\n        layer[l].get().Weights().at(i, j) = weight;\n      }\n    }\n  }\n}\n\n/**\n * The following test implements numerical gradient checking. It computes the\n * numerical gradient, a numerical approximation of the partial derivative of J\n * with respect to the i-th input argument, evaluated at g. The numerical\n * gradient should be approximately the partial derivative of J with respect to\n * g(i).\n *\n * Given a function g(\\theta) that is supposedly computing:\n *\n * @f[\n * \\frac{\\partial}{\\partial \\theta} J(\\theta)\n * @f]\n *\n * we can now numerically verify its correctness by checking:\n *\n * @f[\n * g(\\theta) \\approx \\frac{J(\\theta + eps) - J(\\theta - eps)}{2 * eps}\n * @f]\n */\nBOOST_AUTO_TEST_CASE(GradientNumericallyCorrect)\n{\n  // Initialize dataset.\n  const arma::colvec input = arma::randu<arma::colvec>(10);\n  const arma::colvec target(\"0 1;\");\n\n  // Perturbation and threshold constant.\n  const double perturbation = 1e-6;\n  const double threshold = 1e-5;\n\n  CheckGradientNumericallyCorrect<LogisticFunction>(input, target,\n      perturbation, threshold);\n\n  CheckGradientNumericallyCorrect<IdentityFunction>(input, target,\n      perturbation, threshold);\n\n  CheckGradientNumericallyCorrect<RectifierFunction>(input, target,\n      perturbation, threshold);\n\n  CheckGradientNumericallyCorrect<SoftsignFunction>(input, target,\n      perturbation, threshold);\n\n  CheckGradientNumericallyCorrect<TanhFunction>(input, target,\n      perturbation, threshold);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "f1d855764e8cbc53b8468eefc136deea8c8c7498", "size": 11768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/activation_functions_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/activation_functions_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/activation_functions_test.cpp", "max_forks_repo_name": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5102639296, "max_line_length": 80, "alphanum_fraction": 0.6990992522, "num_tokens": 2892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5726080264289103}}
{"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//! [rem]\n#include <boost/simd/arithmetic.hpp>\n#include <boost/simd/pack.hpp>\n#include <iostream>\n\nnamespace bs = boost::simd;\nusing pack_ft = bs::pack <float, 4>;\n\nint main()\n{\n  pack_ft pf = { 5.0f, -5.0f, 3.0f,  5.0f };\n  pack_ft qf = { 2.0f,  2.0f, 3.0f, -2.0f };\n\n  std::cout\n    <<  \"---- simd\" << '\\n'\n    << \" <- pf =                             \" << pf << '\\n'\n    << \" <- qf =                             \" << qf << '\\n'\n    << \" -> bs::rem(pf, qf) =                \" << bs::rem(pf, qf) << '\\n'\n    << \" -> bs::rem(bs::fix, pf, qf) =       \" << bs::rem(bs::fix, pf, qf) << '\\n'\n    << \" -> bs::rem(bs::ceil, pf, qf) =      \" << bs::rem(bs::ceil, pf, qf) << '\\n'\n    << \" -> bs::rem(bs::floor, pf, qf) =     \" << bs::rem(bs::floor, pf, qf) << '\\n'\n    << \" -> bs::rem(bs::round, pf, qf) =     \" << bs::rem(bs::round, pf, qf) << '\\n'\n    << \" -> bs::rem(bs::nearbyint, pf, qf) = \" << bs::rem(bs::nearbyint, pf, qf) << '\\n';\n\n  float xf = 5.0, yf = 2.0f;\n\n  std::cout\n    << \"---- scalar\"  << '\\n'\n    << \" <- xf =                             \" << xf << '\\n'\n    << \" <- yf =                             \" << yf << '\\n'\n    << \" -> bs::rem( xf, yf) =               \" << bs::rem(xf, yf) << '\\n'\n    << \" -> bs::rem(bs::fix, xf, yf) =       \" << bs::rem(bs::fix, xf, yf) << '\\n'\n    << \" -> bs::rem(bs::ceil, xf, yf) =      \" << bs::rem(bs::ceil, xf, yf) << '\\n'\n    << \" -> bs::rem(bs::floor, xf, yf) =     \" << bs::rem(bs::floor, xf, yf) << '\\n'\n    << \" -> bs::rem(bs::round, xf, yf) =     \" << bs::rem(bs::round, xf, yf) << '\\n'\n    << \" -> bs::rem(bs::nearbyint, xf, yf) = \" << bs::rem(bs::nearbyint, xf, yf) << '\\n';\n  return 0;\n}\n//! [rem]\n", "meta": {"hexsha": "41dfa8d9e2c21edf1b8c97f8a63d2b056455ad78", "size": 2033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/arithmetic/rem.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/rem.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/rem.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": 42.3541666667, "max_line_length": 100, "alphanum_fraction": 0.3635022135, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5726080143827833}}
{"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": "/* btcTools.cxx */\n/* ====================================================================\n * INCLUDE ALL BITCOIN RELATED FUNCTIONS FOR THIS PROJECT.\n * DO NOT USE DIRECTLY; ONLY USE BY INCLUDING.\n * ====================================================================\n *\n * FUNCTIONS EXPLAINED:\n *\n * #1 uint256_t urandom_256():\n *    Generate a random 256-bit unsigned integer which serves as a Bitcoin\n *    private key. Cryptographically secure URANDOM engine is needed\n *    for the function. Return the large number.\n *\n * #2 string priv_to_wif_comp(uint256_t):\n *    Convert a Bitcoin private key into Wallet Import Format-compressed\n *    (string starts with K or L). Return the encoded key string.\n *\n * #3 uint256_t wif_to_priv(string):\n *    Convert a WIF-compressed key into its raw format(256-bit integer).\n *    Can process WIF-uncompressed keys but not used for this project.\n *    Return the large number.\n *\n * #4 string wif_comp_to_pkh(string):\n *    Derive the public key from the WIF-compressed using elliptical curve\n *    cryptography specified in Bitcoin; then use one way hash functions\n *    and base58 check encoding to produce a standard Bitcoin address\n *    (string starts with 1). Return the address.\n *\n * #5 string wif_comp_to_cipher6p(string, string):\n *    Consume a WIF-compressed key and produce a encrypted cipher based\n *    roughly on the BIP-38 standard with a slight change in KDF; instead\n *    of using scrypt, SHA512 is chosen to generate the key for AES256\n *    encryption. Flag byte is set to be 0xF0 which causes the cipher to\n *    begin with \"6Pb/6Pc\". Return the cipher string.\n *\n * #6 uint256_t cipher6p_decrypt(string, string):\n *    Use a password to convert the cipher string back into the raw private key.\n *    This process does not automatically verify the passowrd in execution.\n *    Wrong password will produce a wrong private key. Return the large number.\n *\n * #7 int get_ecdsa_sig(unsigned char*, int, unsigned char*, unsigned char**):\n *    Use the given message array and the private key to produce a ECDSA\n *    signature which complies with the Bitcoin consensus rules. It is used\n *    to authorize the spending of Bitcoin available to this wallet. The\n *    signature data is in DER encoding. Return the length of the signature.\n *\n * #8 void get_output_serial(std::string, double, unsigned char*):\n *    Generate a serialized output data for a raw transaction.\n *    Locking script is a simple P2PKH script. Return nothing.\n *\n * #9 string create_raw_transaction(vector<UTXO>&, vector<string>&, string, string, double, double):\n *    Respond to a send Bitcoin request from the user by generating a raw\n *    transaction data chunk which can be directly mined by the network.\n *    UTXOs chosen to be used as inputs will be voided after the transaction is\n *    created. It only supports sending Bitcoin to one recipient's address and\n *    will automatically generate a change output to refund the user the\n *    remaining balance(minus fee). The change output will be credited to the\n *    wallet's balance with the user's consent.\n *\n * #\n *\n *\n */\n\n#include \"btcStructs.h\"\n#include \"btcTools.h\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <openssl/evp.h>\n#include <openssl/sha.h>\n#include <openssl/ripemd.h>\n#include <openssl/bn.h>\n#include <openssl/obj_mac.h>\n#include <openssl/ec.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <cmath>\n#include <iomanip>\n#include <sstream>\n\nusing namespace std;\nusing namespace boost::multiprecision;\n\ntypedef vector<unsigned char>::iterator vbit;\n\n\nuint256_t urandom_256() {\n\n\tuint256_t real_key;\n\tuint256_t part_1, part_2, part_3, part_4;\n\tlong part;\n\tsize_t part_size = sizeof(part);\n\n\tifstream urandom(\"/dev/urandom\", ios::in|ios::binary);\n\tif (urandom) {\n\t\turandom.read(reinterpret_cast<char*>(&part_1), part_size);\n\t\turandom.read(reinterpret_cast<char*>(&part_2), part_size);\n\t\turandom.read(reinterpret_cast<char*>(&part_3), part_size);\n\t\turandom.read(reinterpret_cast<char*>(&part_4), part_size);\n\t\t}\n\turandom.close();\n\n\treal_key += part_4 << 192;\n\treal_key += part_3 << 128;\n\treal_key += part_2 << 64;\n\treal_key += part_1;\n\n\treturn real_key;\n\n\t}\n\n\nstring priv_to_wif_comp(uint256_t t_raw_key) {\n\n\tvector<unsigned char> main_stream;\n\tmain_stream.push_back(0x80);\n\n\tuint256_t chunk;\n\tunsigned char temp_byte = 0;\n\tfor (int i = 31; i >= 0; --i) {\n\t\tchunk = (t_raw_key >> (i * 8)) & 0xFF;\n\n\t\twhile (chunk > 0) {\n\t\t\ttemp_byte += 1;\n\t\t\t--chunk;\n\t\t\t}\n\n\t\tmain_stream.push_back(temp_byte);\n\t\ttemp_byte = 0;\n\t\t}\n\tmain_stream.push_back(0x01);\n\n\tunsigned char hash_one[SHA256_DIGEST_LENGTH];\n\tSHA256_CTX hash_state;\n\tSHA256_Init(&hash_state);\n\tfor (vbit iit = main_stream.begin(); iit != main_stream.end(); ++iit) {\n\t\tSHA256_Update(&hash_state, &(*iit), 1);\n\t\t}\n\tSHA256_Final(hash_one, &hash_state);\n\n\tunsigned char hash_two[SHA256_DIGEST_LENGTH];\n\tSHA256_Init(&hash_state);\n\tfor (int j = 0; j < 32; ++j) {\n\t\tSHA256_Update(&hash_state, &(hash_one[j]), 1);\n\t\t}\n\tSHA256_Final(hash_two, &hash_state);\n\n\tvector<unsigned char> check_sum;\n\tfor (int k = 0; k < 4; ++k) {\n\t\tcheck_sum.push_back(hash_two[k]);\n\t\tmain_stream.push_back(hash_two[k]);\n\t\t}\n\n\tconst string encoder = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\tuint512_t long_key;\n\tuint512_t shifter;\n\tint sfcounter = 37;\n\tfor (vbit kkt = main_stream.begin(); kkt != main_stream.end(); ++kkt) {\n\t\tshifter = *kkt;\n\t\tlong_key += (shifter << (sfcounter * 8));\n\t\tsfcounter -= 1;\n\t\t}\n\n\tstring final_code = \"\";\n\tvector<char> parts;\n\tuint512_t temp_modulo;\n\tint modulo = 0;\n\n\twhile (long_key > 0) {\n\t\ttemp_modulo = long_key % 58;\n\t\tlong_key -= temp_modulo;\n\t\tlong_key /= 58;\n\n\t\twhile (temp_modulo > 0) {\n\t\t\tmodulo += 1;\n\t\t\ttemp_modulo -= 1;\n\t\t\t}\n\n\t\tparts.push_back(encoder[modulo]);\n\t\tmodulo = 0;\n\t\t}\n\n\tfor (int l = parts.size() - 1; l >= 0; --l) {\n\t\tfinal_code += parts[l];\n\t\t}\n\n\treturn final_code;\n\n\t}\n\n\nuint256_t wif_to_priv(string t_wif_key) {\n\n\tuint256_t priv_key;\n\tstring const decoder = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n\tbool comp;\n\tif (t_wif_key.find(\"5\") == 0) {\n\t\tcomp = false;\n\t\t} else {comp = true;}\n\n\tuint512_t long_key;\n\tchar code;\n\tint index;\n\tint power;\n\tuint512_t chunk;\n\tfor (size_t i = 0; i < t_wif_key.length(); ++i) {\n\t\tcode = t_wif_key[i];\n\t\tindex = decoder.find(code);\n\t\tpower = (t_wif_key.length() - 1) - i;\n\t\tchunk = 58;\n\t\tchunk = pow(chunk, power) * index;\n\t\tlong_key += chunk;\n\t\t}\n\n\tvector<unsigned char> long_stream;\n\tvector<unsigned char> checksum;\n\tunsigned char ibyte = 0;\n\tuint512_t trunc;\n\tfor (int j = 36; j >= 0; --j) {\n\t\ttrunc = (long_key >> (j * 8)) & 0xFF;\n\n\t\twhile (trunc > 0) {\n\t\t\tibyte += 1;\n\t\t\ttrunc -= 1;\n\t\t\t}\n\n\t\tif (j < 4) {\n\t\t\tchecksum.push_back(ibyte);\n\t\t\t}else {\n\t\t\t\tif (comp and j != 4) {long_stream.push_back(ibyte);}\n\t\t\t\telse if (not comp and j != 36) {long_stream.push_back(ibyte);}\n\t\t\t\t}\n\t\tibyte = 0;\n\t\t}\n\n\tuint256_t key_part;\n\tint shifter = 31;\n\tfor (vbit kkt = long_stream.begin(); kkt != long_stream.end(); ++kkt) {\n\t\tkey_part = *kkt;\n\t\tkey_part = (key_part << shifter * 8);\n\t\tpriv_key += key_part;\n\t\tshifter -= 1;\n\t\t}\n\n\treturn priv_key;\n\n\t}\n\n\nstring wif_comp_to_pkh(string t_wif_comp) {\n\n\tstring final_address;\n\tuint256_t raw_key;\n\traw_key = wif_to_priv(t_wif_comp);\n\n\tunsigned char priv_key[32];\n\tunsigned char tbt = 0;\n\tuint256_t tchunk;\n\tfor (int i = 0; i < 32; ++i) {\n\t\ttchunk = (raw_key >> ((31 - i) * 8)) & 0xFF;\n\n\t\twhile (tchunk > 0) {\n\t\t\t++tbt;\n\t\t\t--tchunk;\n\t\t\t}\n\n\t\tpriv_key[i] = tbt;\n\t\ttbt = 0;\n\t\t}\n\n\tunsigned char pub_key[33];\n\tsize_t klen = 33;\n\n\tEC_GROUP *ec256;\n\tec256 = EC_GROUP_new_by_curve_name(NID_secp256k1);\n\n\tBN_CTX *ctx;\n\tctx = BN_CTX_new();\n\tBN_CTX_start(ctx);\n\n\tBIGNUM *bn_priv;\n\tbn_priv = BN_new();\n\tBN_bin2bn(priv_key, 32, bn_priv);\n\n\tEC_POINT *pt_pub;\n\tpt_pub = EC_POINT_new(ec256);\n\n\tEC_POINT_mul(ec256, pt_pub, bn_priv, NULL, NULL, ctx);\n\tEC_POINT_point2oct(ec256, pt_pub, POINT_CONVERSION_COMPRESSED,\n\t\t\t\t\t   pub_key, klen, ctx);\n\n\tSHA256_CTX SH;\n\tSHA256_CTX *sha_state = &SH;\n\tunsigned char sha_one[SHA256_DIGEST_LENGTH];\n\tSHA256_Init(sha_state);\n\tfor (int j = 0; j < 33; ++j) {\n\t\tSHA256_Update(sha_state, &pub_key[j], 1);\n\t\t}\n\tSHA256_Final(sha_one, sha_state);\n\n\tRIPEMD160_CTX RIP;\n\tRIPEMD160_CTX *rip_state = &RIP;\n\tunsigned char rip_one[RIPEMD160_DIGEST_LENGTH];\n\tRIPEMD160_Init(rip_state);\n\tfor (int k = 0; k < 32; ++k) {\n\t\tRIPEMD160_Update(rip_state, &sha_one[k], 1);\n\t\t}\n\tRIPEMD160_Final(rip_one, rip_state);\n\n\tunsigned char ex_pub_key[25];\n\tex_pub_key[0] = 0x00;\n\n\tunsigned char sha_two[32];\n\tunsigned char sha_three[32];\n\tSHA256_Init(sha_state);\n\tSHA256_Update(sha_state, &ex_pub_key[0], 1);\n\tfor (int l = 0; l < 20; ++l) {\n\t\tSHA256_Update(sha_state, &rip_one[l], 1);\n\t\t}\n\tSHA256_Final(sha_two, sha_state);\n\n\tSHA256_Init(sha_state);\n\tfor (int m = 0; m < 32; ++m) {\n\t\tSHA256_Update(sha_state, &sha_two[m], 1);\n\t\t}\n\tSHA256_Final(sha_three, sha_state);\n\n\tfor (int n = 0; n < 20; ++n) {\n\t\tex_pub_key[n + 1] = rip_one[n];\n\t\t}\n\tfor (int o = 0; o < 4; ++o) {\n\t\tex_pub_key[o + 21] = sha_three[o];\n\t\t}\n\n\tconst string encoder = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\tint lead_zero_count = 0;\n\twhile (ex_pub_key[lead_zero_count] == 0x00) {\n\t\tfinal_address += \"1\";\n\t\tlead_zero_count += 1;\n\t\t}\n\n\tuint256_t bn_ex_key;\n\tuint256_t tchunk2;\n\tfor (int p = 0; p < 25; ++p) {\n\t\ttchunk2 = ex_pub_key[p];\n\t\ttchunk2 = tchunk2 << ((24 - p) * 8);\n\t\tbn_ex_key += tchunk2;\n\t\t}\n\n\tvector<char> address_char;\n\tint modu = 0;\n\tuint256_t mchunk;\n\twhile (bn_ex_key > 0) {\n\t\tmchunk = bn_ex_key % 58;\n\t\tbn_ex_key -= mchunk;\n\t\tbn_ex_key /= 58;\n\t\twhile (mchunk > 0) {\n\t\t\tmodu += 1;\n\t\t\tmchunk -= 1;\n\t\t\t}\n\t\taddress_char.push_back(encoder[modu]);\n\t\tmodu = 0;\n\t\t}\n\n\tfor (int q = address_char.size() - 1; q >= 0; --q) {\n\t\tfinal_address += address_char[q];\n\t\t}\n\n\treturn final_address;\n\n\t}\n\n\nstring wif_comp_to_cipher6p(string t_wif_comp, string t_password) {\n\n\tstring address;\n\tsize_t addr_len;\n\n\tunsigned char pre1 = 0x01;\n\tunsigned char pre2 = 0x42;\n\tunsigned char flag = 0xF0;\n\n\taddress = wif_comp_to_pkh(t_wif_comp);\n\taddr_len = address.length();\n\tunsigned char addr_bytes[addr_len];\n\tcopy(address.begin(), address.end(), addr_bytes);\n\n\tunsigned char saltsha1[32];\n\tunsigned char saltsha2[32];\n\tSHA256_CTX sha_state;\n\tSHA256_Init(&sha_state);\n\tfor (size_t i = 0; i < addr_len; ++i) {\n\t\tSHA256_Update(&sha_state, &addr_bytes[i], 1);\n\t\t}\n\tSHA256_Final(saltsha1, &sha_state);\n\n\tSHA256_Init(&sha_state);\n\tfor (int j = 0; j < 32; ++j) {\n\t\tSHA256_Update(&sha_state, &saltsha1[j], 1);\n\t\t}\n\tSHA256_Final(saltsha2, &sha_state);\n\n\tconst unsigned char addr_hash[4] = {saltsha2[0], saltsha2[1],\n\t\t\t\t\t\t\t\t\t\tsaltsha2[2], saltsha2[3]};\n\n\t// !! USE SHA512 INSTEAD OF SCRYPT TO DERIVE THE KEY !!\n\tunsigned char keyout[SHA512_DIGEST_LENGTH];\n\n\tunsigned char dh1[32];\n\tunsigned char dh2[32];\n\n\tsize_t pass_len = t_password.length();\n\tunsigned char password[pass_len];\n\tcopy(t_password.begin(), t_password.end(), password);\n\n\tSHA512_CTX ss512;\n\tSHA512_Init(&ss512);\n\tSHA512_Update(&ss512, &addr_hash[0], 1);\n\tSHA512_Update(&ss512, &addr_hash[1], 1);\n\tSHA512_Update(&ss512, &addr_hash[2], 1);\n\tSHA512_Update(&ss512, &addr_hash[3], 1);\n\tfor (size_t i = 0; i < pass_len; ++i) {\n\t\tSHA512_Update(&ss512, &password[i], 1);\n\t\t}\n\tSHA512_Final(keyout, &ss512);\n\n\tfor (int j = 0; j < 32; ++j) {\n\t\tdh1[j] = keyout[j];\n\t\tdh2[j] = keyout[j + 32];\n\t\t}\n\n\tconst unsigned char r_key2[32] = {\n\t\tdh2[0], dh2[1], dh2[2], dh2[3], dh2[4], dh2[5],\n\t\tdh2[6], dh2[7], dh2[8], dh2[9], dh2[10], dh2[11],\n\t\tdh2[12], dh2[13], dh2[14], dh2[15], dh2[16], dh2[17],\n\t\tdh2[18], dh2[19], dh2[20], dh2[21], dh2[22], dh2[23],\n\t\tdh2[24], dh2[25], dh2[26], dh2[27], dh2[28], dh2[29],\n\t\tdh2[30], dh2[31]};\n\tconst unsigned char* key2 = r_key2;\n\n\tuint256_t raw_key = wif_to_priv(t_wif_comp);\n\tunsigned char priv_key[32];\n\tunsigned char tbt = 0;\n\tuint256_t tchunk;\n\tfor (int i = 0; i < 32; ++i) {\n\t\ttchunk = (raw_key >> ((31 - i) * 8)) & 0xFF;\n\t\twhile (tchunk > 0) {\n\t\t\t++tbt;\n\t\t\t--tchunk;}\n\t\tpriv_key[i] = tbt;\n\t\ttbt = 0;}\n\n\tunsigned char tempb1[16];\n\tunsigned char tempb2[16];\n\tfor (int j = 0; j < 16; ++j) {\n\t\ttempb1[j] = priv_key[j] ^ dh1[j];\n\t\ttempb2[j] = priv_key[j + 16] ^ dh1[j + 16];\n\t\t}\n\tconst unsigned char r_block1[16] = {\n\t\ttempb1[0], tempb1[1], tempb1[2], tempb1[3], tempb1[4], tempb1[5],\n\t\ttempb1[6], tempb1[7], tempb1[8], tempb1[9], tempb1[10], tempb1[11],\n\t\ttempb1[12], tempb1[13], tempb1[14], tempb1[15]};\n\tconst unsigned char r_block2[16] = {\n\t\ttempb2[0], tempb2[1], tempb2[2], tempb2[3], tempb2[4], tempb2[5],\n\t\ttempb2[6], tempb2[7], tempb2[8], tempb2[9], tempb2[10], tempb2[11],\n\t\ttempb2[12], tempb2[13], tempb2[14], tempb2[15]};\n\n\tconst unsigned char* block1 = r_block1;\n\tconst unsigned char* block2 = r_block2;\n\tint block_len = 16;\n\n\tEVP_CIPHER_CTX *ctx;\n\tctx = EVP_CIPHER_CTX_new();\n\tEVP_CIPHER_CTX *ctx2;\n\tctx2 = EVP_CIPHER_CTX_new();\n\n\tunsigned char eh1[16];\n\tunsigned char eh2[16];\n\tunsigned char* eout1 = eh1;\n\tunsigned char* eout2 = eh2;\n\tint eh_len = sizeof(eh1);\n\n\tEVP_EncryptInit(ctx, EVP_aes_256_cbc(), key2, NULL);\n\tEVP_EncryptUpdate(ctx, eout1, &eh_len, block1, block_len);\n\tEVP_CIPHER_CTX_free(ctx);\n\n\tEVP_EncryptInit(ctx2, EVP_aes_256_cbc(), key2, NULL);\n\tEVP_EncryptUpdate(ctx2, eout2, &eh_len, block2, block_len);\n\tEVP_CIPHER_CTX_free(ctx2);\n\n\tvector<unsigned char> cipher_stream;\n\tcipher_stream.push_back(pre1);\n\tcipher_stream.push_back(pre2);\n\tcipher_stream.push_back(flag);\n\tcipher_stream.push_back(addr_hash[0]);\n\tcipher_stream.push_back(addr_hash[1]);\n\tcipher_stream.push_back(addr_hash[2]);\n\tcipher_stream.push_back(addr_hash[3]);\n\n\tfor (int i = 0; i < 16; ++i) {cipher_stream.push_back(eh1[i]);}\n\tfor (int i = 0; i < 16; ++i) {cipher_stream.push_back(eh2[i]);}\n\tassert (cipher_stream.size() == 39);\n\n\tunsigned char csm[SHA256_DIGEST_LENGTH];\n\tSHA256_Init(&sha_state);\n\tfor (size_t j = 0; j < cipher_stream.size(); ++j) {\n\t\tSHA256_Update(&sha_state, &cipher_stream[j], 1);}\n\tSHA256_Final(csm, &sha_state);\n\n\tcipher_stream.push_back(csm[0]);\n\tcipher_stream.push_back(csm[1]);\n\tcipher_stream.push_back(csm[2]);\n\tcipher_stream.push_back(csm[3]);\n\tassert (cipher_stream.size() == 43);\n\n\tconst string encoder = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\tuint512_t long_key;\n\tuint512_t shifter;\n\tint sfcounter = 42;\n\tfor (vbit iit = cipher_stream.begin(); iit != cipher_stream.end(); ++iit) {\n\t\tshifter = *iit;\n\t\tlong_key += (shifter << (sfcounter * 8));\n\t\tsfcounter -= 1;\n\t\t}\n\n\tstring final_cipher;\n\tvector<char> parts;\n\tuint512_t temp_modulo;\n\tint modulo = 0;\n\n\twhile (long_key > 0) {\n\t\ttemp_modulo = long_key % 58;\n\t\tlong_key -= temp_modulo;\n\t\tlong_key /= 58;\n\n\t\twhile (temp_modulo > 0) {\n\t\t\tmodulo += 1;\n\t\t\ttemp_modulo -= 1;\n\t\t\t}\n\n\t\tparts.push_back(encoder[modulo]);\n\t\tmodulo = 0;\n\t\t}\n\n\tfor (int i = parts.size() - 1; i >= 0; --i) {final_cipher += parts[i];}\n\n\treturn final_cipher;\n\n\t}\n\n\nuint256_t cipher6p_decrypt(string t_cipher6p, string t_password) {\n\n\tint cp_len = t_cipher6p.length();\n\n\tconst string decoder = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\tuint512_t bn_cipher, chunk = 58;\n\tint value;\n\tfor (int i = cp_len - 1; i > -1; --i) {\n\t\tvalue = decoder.find(t_cipher6p[cp_len - 1 - i]);\n\t\tchunk = pow(chunk, i) * value;\n\t\tbn_cipher += chunk;\n\t\tchunk = 58;\n\t\t}\n\n\tvector<unsigned char> cipher_bytes;\n\tunsigned char cbyte = 0;\n\tchunk = 0;\n\tfor (int j = 42; j > -1; --j) {\n\t\tchunk = (bn_cipher >> (j * 8)) & 0xFF;\n\t\twhile (chunk > 0) {++cbyte; --chunk;}\n\t\tcipher_bytes.push_back(cbyte);\n\t\tcbyte = 0;\n\t\t}\n\n\tconst unsigned char salt[4] = {cipher_bytes[3], cipher_bytes[4],\n\t\t\t\t\t\t\t\t   cipher_bytes[5], cipher_bytes[6]};\n\n\tunsigned char password[t_password.length()];\n\tcopy(t_password.begin(), t_password.end(), password);\n\n\tconst unsigned char eh1[16] = {\n\t\tcipher_bytes[7], cipher_bytes[8], cipher_bytes[9], cipher_bytes[10],\n\t\tcipher_bytes[11], cipher_bytes[12], cipher_bytes[13], cipher_bytes[14],\n\t\tcipher_bytes[15], cipher_bytes[16], cipher_bytes[17], cipher_bytes[18],\n\t\tcipher_bytes[19], cipher_bytes[20], cipher_bytes[21], cipher_bytes[22]};\n\tconst unsigned char eh2[16] = {\n\t\tcipher_bytes[23], cipher_bytes[24], cipher_bytes[25], cipher_bytes[26],\n\t\tcipher_bytes[27], cipher_bytes[28], cipher_bytes[29], cipher_bytes[30],\n\t\tcipher_bytes[31], cipher_bytes[32], cipher_bytes[33], cipher_bytes[34],\n\t\tcipher_bytes[35], cipher_bytes[36], cipher_bytes[37], cipher_bytes[38]};\n\tconst unsigned char* dblock1 = eh1;\n\tconst unsigned char* dblock2 = eh2;\n\n\tunsigned char full_key[SHA512_DIGEST_LENGTH];\n\tunsigned char d1h1[16];\n\tunsigned char d1h2[16];\n\tSHA512_CTX ss512;\n\tSHA512_Init(&ss512);\n\tSHA512_Update(&ss512, &salt[0], 1);\n\tSHA512_Update(&ss512, &salt[1], 1);\n\tSHA512_Update(&ss512, &salt[2], 1);\n\tSHA512_Update(&ss512, &salt[3], 1);\n\tfor (size_t i = 0; i < t_password.length(); ++i) {\n\t\tSHA512_Update(&ss512, &password[i], 1);}\n\tSHA512_Final(full_key, &ss512);\n\n\tfor (int j = 0; j < 16; ++j) {\n\t\td1h1[j] = full_key[j];\n\t\td1h2[j] = full_key[j + 16];\n\t\t}\n\n\tconst unsigned char d2h[32] = {\n\t\tfull_key[32], full_key[33], full_key[34], full_key[35],\n\t\tfull_key[36], full_key[37], full_key[38], full_key[39],\n\t\tfull_key[40], full_key[41], full_key[42], full_key[43],\n\t\tfull_key[44], full_key[45], full_key[46], full_key[47],\n\t\tfull_key[48], full_key[49], full_key[50], full_key[51],\n\t\tfull_key[52], full_key[53], full_key[54], full_key[55],\n\t\tfull_key[56], full_key[57], full_key[58], full_key[59],\n\t\tfull_key[60], full_key[61], full_key[62], full_key[63]\n\t\t};\n\tconst unsigned char* dhkey = d2h;\n\n\tunsigned char result1[16];\n\tunsigned char result2[16];\n\tunsigned char* out1 = result1;\n\tunsigned char* out2 = result2;\n\tint out_len = 16;\n\n\tEVP_CIPHER_CTX *ctx;\n\tctx = EVP_CIPHER_CTX_new();\n\tEVP_CIPHER_CTX *ctx2;\n\tctx2 = EVP_CIPHER_CTX_new();\n\n\tEVP_DecryptInit(ctx, EVP_aes_256_cbc(), dhkey, NULL);\n\tEVP_DecryptUpdate(ctx, out1, &out_len, dblock1, 16);\n\tEVP_CIPHER_CTX_free(ctx);\n\n\tEVP_DecryptInit(ctx2, EVP_aes_256_cbc(), dhkey, NULL);\n\tEVP_DecryptUpdate(ctx2, out2, &out_len, dblock2, 16);\n\tEVP_CIPHER_CTX_free(ctx2);\n\n\tunsigned char pkh1[16];\n\tunsigned char pkh2[16];\n\tfor (int i = 0; i < 16; ++i) {\n\t\tpkh1[i] = result1[i] ^ d1h1[i];\n\t\tpkh2[i] = result2[i] ^ d1h2[i];\n\t\t}\n\n\tuint256_t final_priv_key, chunk1, chunk2;\n\tfor (int j = 15; j > -1; --j) {\n\t\tchunk1 = pkh1[15 - j];\n\t\tchunk2 = pkh2[15 - j];\n\t\tchunk1 = chunk1 << ((j + 16) * 8);\n\t\tchunk2 = chunk2 << (j * 8);\n\t\tfinal_priv_key += (chunk1 + chunk2);\n\t\t}\n\n\t// string final_wif_comp = priv_to_wif_comp(final_priv_key);\n\t// return final_wif_comp;\n\n\treturn final_priv_key;\n\n\t}\n\n\nint get_ecdsa_sig(unsigned char* t_digest, int t_dlen, unsigned char* t_secret, unsigned char** t_sigpp) {\n\n\tconst EC_GROUP* ecgroup = EC_GROUP_new_by_curve_name(NID_secp256k1);\n\tEC_KEY* eckey = EC_KEY_new_by_curve_name(NID_secp256k1);\n\tEC_POINT* ecpoint = EC_POINT_new(ecgroup);\n\n\tBN_CTX* bnctx = BN_CTX_new();\n\tconst BIGNUM* priv_bn = BN_bin2bn(t_secret, 32, NULL);\n\n\tEC_POINT_mul(ecgroup, ecpoint, priv_bn, NULL, NULL, bnctx);\n\tconst EC_POINT* pubkey = EC_POINT_dup(ecpoint, ecgroup);\n\tEC_KEY_set_private_key(eckey, priv_bn);\n\tEC_KEY_set_public_key(eckey, pubkey);\n\n\tconst ECDSA_SIG* ecwit = ECDSA_do_sign(t_digest, t_dlen, eckey);\n\tsize_t siglen = i2d_ECDSA_SIG(ecwit, t_sigpp);\n\t*t_sigpp -= siglen;\n\n\treturn siglen;\n\n\t}\n\n\nvoid get_output_serial(string t_address, double t_amount, unsigned char* osout) {\n\t// output size = 8 + 4 + 20 + 2 = 34.\n\n\tunsigned char* rawpub = new unsigned char;\n\n\tconst string decoder = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\tsize_t adlen = t_address.length();\n\tuint256_t bigN, chunk, cbyte;\n\tint value;\n\tfor (size_t i = 0; i < adlen; ++i) {\n\t\tvalue = decoder.find(t_address[i]);\n\t\tchunk = 58;\n\t\tchunk = pow(chunk, adlen - 1 - i) * value;\n\t\tbigN += chunk;\n\t\t}\n\n\tunsigned char ibyte;\n\tfor (int j = 0; j < 20; ++j) {\n\t\tcbyte = (bigN >> (23 - j) * 8) & 0xFF;\n\t\twhile (cbyte > 0) {++ibyte; --cbyte;}\n\t\trawpub[j] = ibyte;\n\t\tibyte = 0;\n\t\t}\n\n\tuint64_t satoshi = t_amount * 100000000;\n\tunsigned char abyte;\n\tfor (int i = 0; i < 8; ++i) {\n\t\tabyte = (satoshi >> (i * 8)) & 0xFF;\n\t\tosout[i] = abyte;\n\t\t}\n\n\tosout[8] = 0x19;\n\tosout[9] = 0x76;\n\tosout[10] = 0xa9;\n\tosout[11] = 0x14;\n\n\tfor (int i = 0; i < 20; ++i)\n\t{osout[12 + i] = rawpub[i];}\n\n\tosout[32] = 0x88;\n\tosout[33] = 0xac;\n\n\t}\n\n\nstring create_raw_transaction(vector<UTXO>& t_uts, vector<string>& t_wif_set, string t_recip, string t_chg, double t_pay, double t_fee) {\n\n\tvector<UTXO> utins;\n\tsize_t allulen = t_uts.size();\n\tdouble wealth = 0, gross = t_pay + t_fee;\n\tfor (size_t i = 0; i < allulen; ++i) {\n\t\tif (wealth < gross) {\n\t\t\tif (t_uts[i].good()) {\n\t\t\t\tutins.push_back(t_uts[i]);\n\t\t\t\tt_uts[i].destroy();\n\t\t\t\twealth = wealth + t_uts[i].get_balance();}\n\t\t\t}\n\t\telse {break;}\n\t\t}\n\n\tdouble change = wealth - t_pay - t_fee;\n\tunsigned char ninp = (unsigned char)utins.size();\n\tunsigned char noup = 0x02;\n\n\tvector<unsigned char> tx_struct, tx_final;\n\ttx_struct.push_back(0x01); tx_final.push_back(0x01);\n\ttx_struct.push_back(0x00); tx_final.push_back(0x00);\n\ttx_struct.push_back(0x00); tx_final.push_back(0x00);\n\ttx_struct.push_back(0x00); tx_final.push_back(0x00);\n\ttx_struct.push_back(ninp); tx_final.push_back(ninp);\t// branch off.\n\n\tfor (size_t i = 0; i < utins.size(); ++i) {\n\t\tunsigned char* stc_input = new unsigned char[66];\n\t\tutins[i].input_serial(stc_input);\n\t\tfor (int j = 0; j < 66; ++j)\n\t\t{tx_struct.push_back(stc_input[j]);}\n\t\t}\n\n\ttx_struct.push_back(noup);\n\tunsigned char* rec_out = new unsigned char[34];\n\tunsigned char* chg_out = new unsigned char[34];\n\tget_output_serial(t_recip, t_pay, rec_out);\n\tget_output_serial(t_chg, change, chg_out);\n\n\tfor (int i = 0; i < 34; ++i)\n\t{tx_struct.push_back(rec_out[i]);}\n\tfor (int i = 0; i < 34; ++i)\n\t{tx_struct.push_back(chg_out[i]);}\n\ttx_struct.push_back(0x00); tx_struct.push_back(0x00);\n\ttx_struct.push_back(0x00); tx_struct.push_back(0x00);\n\ttx_struct.push_back(0x01); tx_struct.push_back(0x00);\n\ttx_struct.push_back(0x00); tx_struct.push_back(0x00);\n\n\t// get signature.\n\tunsigned char* d1 = new unsigned char[32];\n\tunsigned char* digest_stc = new unsigned char[32];\n\tSHA256_CTX shactx;\n\tSHA256_Init(&shactx);\n\tfor (size_t i = 0; i < tx_struct.size(); ++i)\n\t{SHA256_Update(&shactx, &tx_struct[i], 1);}\n\tSHA256_Final(d1, &shactx);\n\tSHA256_Init(&shactx);\n\tfor (size_t i = 0; i < 32; ++i)\n\t{SHA256_Update(&shactx, &(d1[i]), 1);}\n\tSHA256_Final(digest_stc, &shactx);\n\n\n\tunsigned char tm;\n\tvector<unsigned char> all_sigs;\n\tvector<int> all_siglens;\n\tint wlen;\n\tfor (size_t i = 0; i < utins.size(); ++i) {\n\t\tunsigned char* so = new unsigned char[1024];\n\t\tunsigned char** sigpp = &so;\n\t\tunsigned char* isecret = new unsigned char[32];\n\t\tutins[i].fetch_private(t_wif_set, isecret);\n\t\twlen = get_ecdsa_sig(digest_stc, 32, isecret, sigpp);\n\t\tall_siglens.push_back(wlen);\n\t\tfor (int j = 0; j < wlen; ++j) {\n\t\t\ttm = (*sigpp)[j];\n\t\t\tall_sigs.push_back(tm);\n\t\t\t}\n\t\t}\n\n\t// finalize the tx.\n\tunsigned char publen = 0x21;\n\tunsigned char ecslen;\n\tunsigned char sigplen;\n\tunsigned char fullsiglen;\n\tint sigmark = 0;\n\tfor (size_t i = 0; i < utins.size(); ++i) {\n\t\tunsigned char* bcs = new unsigned char[36];\n\t\tutins[i].bc_partial_serial(bcs);\n\t\tfor (int j = 0; j < 36; ++j)\n\t\t{tx_final.push_back(bcs[j]);}\n\n\t\tecslen = (unsigned char)all_siglens[i];\n\t\tsigplen = ecslen + 0x01;\n\t\tfullsiglen = ecslen + 0x02 + 0x01 + publen;\n\t\ttx_final.push_back(fullsiglen);\n\t\ttx_final.push_back(sigplen);\n\t\tfor (int j = 0; j < ecslen; ++j) {\n\t\t\ttm = all_sigs[j + sigmark];\n\t\t\ttx_final.push_back(tm);\n\t\t\t}\n\t\tsigmark += ecslen;\n\t\ttx_final.push_back(0x01);\n\n\t\tunsigned char* asecret = new unsigned char[32];\n\t\tunsigned char* acs = new unsigned char[38];\n\t\tutins[i].fetch_private(t_wif_set, asecret);\n\t\tutins[i].ac_partial_serial(asecret, acs);\n\t\tfor (int j = 0; j < 38; ++j)\n\t\t{tx_final.push_back(acs[j]);}\n\t\t}\n\n\ttx_final.push_back(noup);\n\tunsigned char* nrec_out = new unsigned char[34];\n\tunsigned char* nchg_out = new unsigned char[34];\n\tget_output_serial(t_recip, t_pay, nrec_out);\n\tget_output_serial(t_chg, change, nchg_out);\n\tfor (int i = 0; i < 34; ++i)\n\t{tx_final.push_back(nrec_out[i]);}\n\tfor (int i = 0; i < 34; ++i)\n\t{tx_final.push_back(nchg_out[i]);}\n\ttx_final.push_back(0x00); tx_final.push_back(0x00);\n\ttx_final.push_back(0x00); tx_final.push_back(0x00);\n\n\tunsigned char* id1 = new unsigned char[32];\n\tunsigned char* txid = new unsigned char[32];\n\tSHA256_Init(&shactx);\n\tfor (size_t i = 0; i < tx_final.size(); ++i)\n\t{SHA256_Update(&shactx, &(tx_final[i]), 1);}\n\tSHA256_Final(id1, &shactx);\n\tSHA256_Init(&shactx);\n\tfor (int i = 0; i < 32; ++i)\n\t{SHA256_Update(&shactx, &(id1[i]), 1);}\n\tSHA256_Final(txid, &shactx);\n\n\tstring final_id;\n\tstring hex_table = \"0123456789abcdef\";\n\tint big, small;\n\tfor (int i = 31; i >= 0; --i) {\n\t\tsmall = txid[i] % 16;\n\t\tbig = (txid[i] - small) / 16;\n\t\tfinal_id += hex_table[big];\n\t\tfinal_id += hex_table[small];\n\t\t}\n\n\tcout << \"\\n---------- New Transaction ----------\\n\" << endl;\n\tcout << \"Full TX Data: \" << hex;\n\tfor (size_t i = 0; i < tx_final.size(); ++i)\n\t{cout << setfill('0') << setw(2) << (int)tx_final[i];}\n\tcout << \"     ----- End of Data\\n\" << endl;\n\tcout << \"Data Size: \" << dec << tx_final.size() << \" Bytes\" << endl;\n\tcout << \"New TXID: \" << final_id << endl;\n\tcout << \"Change Paid Back: \" << change << \" BTC\" << endl;\n\tcout << \"Adding Outputs to UTXO Set......\";\n\tt_uts.push_back(UTXO(final_id, t_recip, \"NO\", 0, t_pay));\n\tt_uts.push_back(UTXO(final_id, t_chg, \"NO\", 1, change));\n\tcout << \" Finished.\\n\" << endl;\n\tcout << \"---------- Operation Complete ----------\\n\" << endl;\n\n\treturn final_id;\n\n\t}\n", "meta": {"hexsha": "91bfc33074deb2f055361e9915c66de277587350", "size": 25451, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "btcTools.cxx", "max_stars_repo_name": "Kairn/bitcoin-safebook", "max_stars_repo_head_hexsha": "2fb3482b1b83236dc1b7eefffe1bc8a471143a5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-23T05:55:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-23T05:55:19.000Z", "max_issues_repo_path": "btcTools.cxx", "max_issues_repo_name": "Kairn/bitcoin-SafeBook", "max_issues_repo_head_hexsha": "2fb3482b1b83236dc1b7eefffe1bc8a471143a5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "btcTools.cxx", "max_forks_repo_name": "Kairn/bitcoin-SafeBook", "max_forks_repo_head_hexsha": "2fb3482b1b83236dc1b7eefffe1bc8a471143a5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-26T14:54:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-01T17:16:34.000Z", "avg_line_length": 28.3103448276, "max_line_length": 137, "alphanum_fraction": 0.6697968646, "num_tokens": 8442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5724285601621978}}
{"text": "/**\n * Copyright (c) 2015-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD+Patents license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n// Copyright 2004-present Facebook. All Rights Reserved\n\n#include <cstdio>\n#include <cstdlib>\n\n#include <boost/test/unit_test.hpp>\n#include \"test-util.h\"\n\n#include <faiss/IndexIVFPQ.h>\n#include <faiss/IndexFlat.h>\n#include <faiss/index_io.h>\n\nBOOST_AUTO_TEST_CASE(IVFPQ_index) {\n\n    // dimension of the vectors to index\n    int d = 64;\n\n    // size of the database we plan to index\n    size_t nb = 1000;\n\n    // make a set of nt training vectors in the unit cube\n    // (could be the database)\n    size_t nt = 10000;\n\n    // make the index object and train it\n    faiss::IndexFlatL2 coarse_quantizer (d);\n\n    // a reasonable number of cetroids to index nb vectors\n    int ncentroids = 25;\n\n    faiss::IndexIVFPQ index (&coarse_quantizer, d,\n                             ncentroids, 16, 8);\n\n    // index that gives the ground-truth\n    faiss::IndexFlatL2 index_gt (d);\n\n    //srand48 (35);\n\tint nSeed = 35;\n\n    { // training\n\n        std::vector <float> trainvecs (nt * d);\n\t\tgenerate_float_vector(d, trainvecs.data(), nt,nSeed);\n        index.verbose = true;\n        index.train (nt, trainvecs.data());\n    }\n\n    { // populating the database\n\n        std::vector <float> database (nb * d);\n\t\tgenerate_float_vector(d, database.data(), nb, nSeed+1);\n\n        index.add (nb, database.data());\n        index_gt.add (nb, database.data());\n    }\n\n    int nq = 200;\n    int n_ok;\n\n    { // searching the database\n\n        std::vector <float> queries (nq * d);\n\t\tgenerate_float_vector(d, queries.data(), nq, nSeed+2);\n\n        std::vector<faiss::Index::idx_t> gt_nns (nq);\n        std::vector<float>               gt_dis (nq);\n\n        index_gt.search (nq, queries.data(), 1,\n                         gt_dis.data(), gt_nns.data());\n\n        index.nprobe = 5;\n        int k = 5;\n        std::vector<faiss::Index::idx_t> nns (k * nq);\n        std::vector<float>               dis (k * nq);\n\n        index.search (nq, queries.data(), k, dis.data(), nns.data());\n\n        n_ok = 0;\n        for (int q = 0; q < nq; q++) {\n\n            for (int i = 0; i < k; i++)\n                if (nns[q * k + i] == gt_nns[q])\n                    n_ok++;\n        }\n\t\tBOOST_TEST_MESSAGE(\"number of ok \" << n_ok);\n        BOOST_CHECK(n_ok>nq * 0.4);\n    }\n\n}\n", "meta": {"hexsha": "b868d9bf686b9eb5419d505e673b7c2d9acf6a84", "size": 2450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_ivfpq_indexing.cpp", "max_stars_repo_name": "bitsun/faiss-windows", "max_stars_repo_head_hexsha": "4ecd22981f8473ecd213a740264873ac0dbc083e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2019-01-20T22:14:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T08:08:32.000Z", "max_issues_repo_path": "tests/test_ivfpq_indexing.cpp", "max_issues_repo_name": "anthonyaue/faiss-windows", "max_issues_repo_head_hexsha": "47486c44cab3badf52be4ed8dd9ec6d692212bcc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-01-16T08:16:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-15T16:30:17.000Z", "max_forks_repo_path": "tests/test_ivfpq_indexing.cpp", "max_forks_repo_name": "bitsun/faiss-windows", "max_forks_repo_head_hexsha": "4ecd22981f8473ecd213a740264873ac0dbc083e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-05-17T13:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-18T01:18:33.000Z", "avg_line_length": 25.0, "max_line_length": 74, "alphanum_fraction": 0.5763265306, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.572418843947205}}
{"text": "#include <iostream>\n#include <mlpack/methods/ann/dists/bernoulli_distribution.hpp>\n#include <armadillo>\n#define PRINT 1\n\nusing namespace mlpack::ann;\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n  // Using this only for demo purposes. This will dropout second channel always.\n  arma_rng::set_seed(0);\n\n  // User input\n  arma::mat input(12, 1);\n  input << 0.4963 << 0.0885 << 0.7682 << 0.1320 << 0.3074 << 0.4901 << 0.6341 << 0.8964 << 0.4556 << 0.3489 << 0.6323 << 0.4017 << endr;\n  input = input.t();\n\n  double ratio = 0.2;\n  size_t size = 3; // input channels\n\n  arma::mat output;\n  output.zeros(arma::size(input));\n\n  // Forward()\n  size_t batchSize = input.n_cols;\n  size_t inputSize = input.n_rows / size;\n  double scale = 1.0 / (1.0 - ratio);\n  arma::cube inputTemp(const_cast<arma::mat&>(input).memptr(), inputSize, size, batchSize, false, false);\n  arma::cube outputTemp(const_cast<arma::mat&>(output).memptr(), inputSize, size, batchSize, false, false);\n  arma::mat probabilities(1, size);\n  arma::mat maskRow(1, size);\n  arma::mat mask;\n  probabilities.fill(ratio);\n  BernoulliDistribution<> bernoulli_dist(probabilities, false);\n  maskRow = bernoulli_dist.Sample();\n  mask = arma::repmat(maskRow, inputSize, 1);\n\n  for(size_t n = 0; n < batchSize; n++)\n  {\n    arma::mat& inputImage = inputTemp.slice(n);\n    arma::mat& outputImage = outputTemp.slice(n);\n    outputImage = inputImage % mask * scale;\n\n    if(PRINT)\n    {\n      cout << \"Image \" << n << \" calculations: \" << endl;\n      cout << \"-----------------------------------\" << endl;\n      cout << \"-----------------------------------\" << endl;\n      cout << \"INPUT for Spatial Dropout: \" << endl;\n      cout << inputImage << endl;\n      cout << \"-----------------------------------\" << endl;\n      cout << \"OUTPUT for Spatial Dropout: \" << endl;\n      cout << outputImage << endl;\n      cout << \"-----------------------------------\" << endl;\n    }\n  }\n\n  // this is gy for Spatial Dropout layer simulated as a tensor filled with an arbitrary sequence of values.\n  arma::mat gy;\n  gy << 1 << 3 << 2 << 4 << 5 << 7 << 6 << 8 << 9 << 11 << 10 << 12 << endr;\n  gy = gy.t();\n\n  // Backward()\n  arma::mat g;\n  g.zeros(arma::size(input));\n\n  arma::cube gyTemp(const_cast<arma::mat&>(gy).memptr(), inputSize, size, batchSize, false, false);\n  arma::cube gTemp(const_cast<arma::mat&>(g).memptr(), inputSize, size, batchSize, false, false);\n\n  for(size_t n = 0; n < batchSize; n++)\n  {\n    arma::mat& gyImage = gyTemp.slice(n);\n    arma::mat& gImage = gTemp.slice(n);\n\n    gImage = gyImage % mask * scale;\n\n    if(PRINT)\n    {\n      cout << \"Image \" << n << \" calculations: \" << endl;\n      cout << \"-----------------------------------\" << endl;\n      cout << \"-----------------------------------\" << endl;\n      cout << \"Hypothetical gy for Spatial Dropout: \" << endl;\n      cout << gyImage << endl;\n      cout << \"-----------------------------------\" << endl;\n      cout << \"g for Spatial Dropout: \" << endl;\n      cout << gImage << endl;\n      cout << \"-----------------------------------\" << endl;\n    }\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "eceed6b5e2c3787d4c01b59c02334aa66e6d9871", "size": 3097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spatial_dropout/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": "spatial_dropout/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": "spatial_dropout/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": 32.6, "max_line_length": 136, "alphanum_fraction": 0.5427833387, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5724188368882239}}
{"text": "\ufeff#include <Engine/MeshEdit/ARAP.h>\n#include <Engine/MeshEdit/CParameterize.h>\n#include <Engine/Primitive/TriMesh.h>\n#include <assert.h>\n#include <Eigen/Sparse>\n\n#include <Engine/MeshEdit/Paramaterize.h>\n\nusing namespace Ubpa;\nusing namespace std;\nusing namespace Eigen;\n\nUbpa::ARAP::ARAP(Ptr<TriMesh> triMesh)\n\t: heMesh(make_shared<HEMesh<V>>())\n{\n\tInit(triMesh);\n\ttexture_flag = false;\n}\n\n\nvoid Ubpa::ARAP::Clear()\n{\n\theMesh->Clear();\n\n\ttriMesh = nullptr;\n}\n\nbool Ubpa::ARAP::Init(Ptr<TriMesh> triMesh)\n{\n\tClear();\n\tif (triMesh == nullptr)\n\t\treturn true;\n\tif (triMesh->GetType() == TriMesh::INVALID) {\n\t\tprintf(\"ERROR::ARAP::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is invalid\\n\");\n\t\treturn false;\n\t}\n\n\tthis->nT = triMesh->GetTriangles().size();\n\tthis->nV = triMesh->GetPositions().size();\n\n\t// step1: init half-edge structure\n\tvector<vector<size_t>> triangles;\n\ttriangles.reserve(triMesh->GetTriangles().size());\n\tfor (auto triangle : triMesh->GetTriangles())\n\t\ttriangles.push_back({ triangle->idx[0], triangle->idx[1], triangle->idx[2] });\n\theMesh->Reserve(this->nV);\n\theMesh->Init(triangles);\n\tif (!heMesh->IsTriMesh() || !heMesh->HaveBoundary()) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is not a triangle mesh or hasn't a boundaries\\n\");\n\t\theMesh->Clear();\n\t\treturn false;\n\t}\n\tfor (int i = 0; i < this->nV; i++) {\n\t\tauto v = heMesh->Vertices().at(i);\n\t\tv->pos = triMesh->GetPositions()[i].cast_to<vecf3>();\n\t}\n\n\tthis->triMesh = triMesh;\n\n\t// step2: initializing the points2d and cotan \n\t// (locally coordinates and cotangent of every angle for every triangle)\n\tCongruentMapping2D();\n\n\t// step3: locally parameterization with boundry\n\tauto parameterizeUniformCircle = ParameterizeUniformCircle::New(triMesh);\n\tif (parameterizeUniformCircle->Run()) {\n\t\tprintf(\"paramaterizeUniformSquare done\\n\");\n\t}\n\n\t// step4: pick two anchor vertexes, \n\t// which can (a) remove ratation and displacement of the result (b) avoid  degradation solution.\n\tauto triangle = heMesh->Polygons().back();\n\tauto v1 = triangle->BoundaryVertice()[0];\n\tanchor_v1_idx = heMesh->Index(v1);\n\tauto v2 = triangle->BoundaryVertice()[1];\n\tanchor_v2_idx = heMesh->Index(v2);\n\tanchor_pos1 = pointf2(0, 0);\n\tanchor_pos2 = pointf2(2, 2);\n\n\t// step5: generate and compute the coefficient matrix A, \n\t// which is constant in all iterations, so it can be generated and computed only once.\n\tGenerate_and_compute_A();\n\n\treturn true;\n}\n\nbool Ubpa::ARAP::Run()\n{\n\tif (heMesh->IsEmpty() || !triMesh) {\n\t\tprintf(\"ERROR::MinSurf::Run\\n\"\n\t\t\t\"\\t\"\"heMesh->IsEmpty() || !triMesh\\n\");\n\t\treturn false;\n\t}\n\n\terror = -1;\n\tARAP_Pipeline(); // kernel iteration of the ARAP algorithm\n\n\t// Finally, half-edge structure -> triangle mesh, end. \n\tvector<pointf3> positions;\n\tvector<unsigned> indice;\n\tvector<pointf2> texcoords;\n\n\tthis->nV = heMesh->NumVertices();\n\tconst std::vector<Ptr<Ubpa::Triangle>>& triangles = triMesh->GetTriangles();\n\tthis->nT = triangles.size();\n\n\tpositions.reserve(this->nV);\n\tindice.reserve(3 * this->nT);\n\ttexcoords.reserve(this->nV);\n\n\tfor (auto v : heMesh->Vertices()) {\n\t\tpositions.push_back(v->pos.cast_to<pointf3>());\n\t\ttexcoords.push_back(v->pos.cast_to<pointf2>());\n\t}\n\tfor (auto f : heMesh->Polygons()) { // f is triangle\n\t\tfor (auto v : f->BoundaryVertice()) // vertices of the triangle\n\t\t\tindice.push_back(static_cast<unsigned>(heMesh->Index(v)));\n\t}\n\n\tif (this->texture_flag)\n\t\tthis->triMesh->Update(texcoords);\n\telse\n\t\tthis->triMesh->Update(positions);\n\treturn true;\n}\n\nvoid Ubpa::ARAP::Add_texture()\n{\n\ttexture_flag = true;\n\n}\n\nvoid Ubpa::ARAP::ARAP_Pipeline()\n{\n\n\t// stop condition\n\tsize_t iter_n = 2;\n\n\tfor (int i = 0; i < iter_n; i++)\n\t{\n\t\tLocal_Phase();\n\t\tGlobal_Phase();\n\t\tcout << \"iter:\" << i << \" error: \" << error << endl;\n\t}\n}\n\nvoid Ubpa::ARAP::Global_Phase()\n{\n\t// step1: set b\n\tsetb(anchor_v1_idx, anchor_pos1, anchor_v2_idx, anchor_pos2);\n\n\n\t// Then solve the equation\n\tARAP_solution = solver.solve(ARAP_mat_b);\n\n\tthis->texCoor.clear();\n\tfor (size_t i = 0; i < this->nV; i++)\n\t{\n\t\tdouble dist = pointf3::distance(pointf3(ARAP_solution(i, 0), ARAP_solution(i, 1), 0.0), heMesh->Vertices()[i]->pos.cast_to<pointf3>());\n\t\tif (error < 0)\n\t\t{\n\t\t\terror = dist;\n\t\t}\n\t\telse if (error < dist)\n\t\t{\n\t\t\terror = dist;\n\t\t}\n\n\t\theMesh->Vertices()[i]->pos[0] = ARAP_solution(i, 0);\n\t\theMesh->Vertices()[i]->pos[1] = ARAP_solution(i, 1);\n\t\theMesh->Vertices()[i]->pos[2] = 0.0;\n\t\t// update tex coordinates\n\t\ttexCoor.push_back(pointf2(ARAP_solution(i, 0), ARAP_solution(i, 1)));\n\t}\n}\n\n\nvoid Ubpa::ARAP::Local_Phase() // \u4f7f\u7528SVD\u5206\u89e3\u6c42\u89e3\u6700\u4f18\u7684Lt\n{\n\t// Get newest u per iteration ,\n\ttriangle_points.clear();\t// remember to clear\n\tfor (auto triangle : heMesh->Polygons())\n\t{\n\t\tif (triangle != nullptr)\n\t\t{\n\t\t\tthis->triangle_points.push_back(triangle->BoundaryVertice());\n\t\t}\n\t}\n\n\t// \u6784\u9020St(u)\n\tLt_array.clear(); // \u540e\u9762\u66f4\u65b0Lt\n\tfor (size_t t = 0; t < this->nT; t++)\n\t{\n\t\tauto vec_u = triangle_points[t];\n\t\tauto mapped_u = points2d[t];\n\t\tMatrix2d St;\n\t\tSt.setZero();\n\n\t\t// get St\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tV* u0 = vec_u[i];\n\t\t\tV* u1 = vec_u[(i + 1) % 3];\n\t\t\tMatrixXd delta_u(2, 1);\n\t\t\tdelta_u <<\n\t\t\t\tu0->pos[0] - u1->pos[0], u0->pos[1] - u1->pos[1];\n\n\t\t\tpointf3 x0 = mapped_u[u0];\n\t\t\tpointf3 x1 = mapped_u[u1];\n\t\t\tMatrixXd delta_x(2, 1);\n\t\t\tdelta_x <<\n\t\t\t\tx0[0] - x1[0], x0[1] - x1[1];\n\n\t\t\tdouble cot = getCotan(t, vec_u[(i + 2) % 3]);\n\n\t\t\tSt += cot * delta_u * delta_x.transpose();\n\t\t}\n\n\t\t// Do SVD Composition on St\n\t\tJacobiSVD<MatrixXd> svd(St, ComputeThinU | ComputeThinV);\n\t\tMatrix2d Lt = svd.matrixU() * svd.matrixV().transpose(); // Lt = U * V^T\n\n\t\tLt_array.push_back(Lt);\n\n\t}\n}\n\nvoid Ubpa::ARAP::Generate_and_compute_A()\n{\n\t// Two Anchor points \n\tA_sparse.resize(this->nV, this->nV);\n\tARAP_coeff.push_back(Eigen::Triplet<double>(anchor_v1_idx, anchor_v1_idx, 1));\n\t//ARAP_coeff.push_back(Eigen::Triplet<double>(anchor_v2_idx, anchor_v2_idx, 1));\n\n\t// Other non-anchor points\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\tif (i != anchor_v1_idx /*&& i != anchor_v2_idx*/) {\n\t\t\tauto v = heMesh->Vertices()[i];\n\t\t\tdouble cotan_sum = 0.0;\n\n\t\t\t// traverse adjacent vertrices\n\t\t\tfor (auto adj_v : v->AdjVertices())\n\t\t\t{\n\t\t\t\tsize_t adj_idx = heMesh->Index(adj_v);\n\n\t\t\t\t// To get cotan \n\t\t\t\tauto e = v->EdgeWith(adj_v);\n\t\t\t\tauto he1 = e->HalfEdge();\n\n\t\t\t\tdouble cot1 = 0.0;\n\t\t\t\tif (he1->Polygon() != nullptr)\n\t\t\t\t{\n\t\t\t\t\tauto tri1_idx = heMesh->Index(he1->Polygon()); // get index of adjacent triangle\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tauto tri_v1 = he1->Next()->End(); // get vertix of adjacent triangle \n\t\t\t\t\t\tassert(heMesh->Index(tri_v1) != heMesh->Index(v)\n\t\t\t\t\t\t\t&& heMesh->Index(tri_v1) != heMesh->Index(adj_v));\n\n\t\t\t\t\t\tcot1 = getCotan(tri1_idx, tri_v1);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::exception& e)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"cannot find cot 1 in map. \" << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tauto he2 = e->HalfEdge()->Pair();\n\n\t\t\t\tdouble cot2 = 0.0;\n\t\t\t\tif (he2->Polygon() != nullptr)\n\t\t\t\t{\n\t\t\t\t\tauto tri2_idx = heMesh->Index(he2->Polygon());\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tauto tri_v2 = he2->Next()->End();\n\t\t\t\t\t\tassert(heMesh->Index(tri_v2) != heMesh->Index(v)\n\t\t\t\t\t\t\t&& heMesh->Index(tri_v2) != heMesh->Index(adj_v));\n\t\t\t\t\t\tcot2 = getCotan(tri2_idx, tri_v2);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::exception& e)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"cannot find cot 2 in map. \" << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tARAP_coeff.push_back(Eigen::Triplet<double>(i, adj_idx, -(cot1 + cot2)));\n\n\t\t\t\tcotan_sum += (cot1 + cot2);\n\t\t\t}\n\n\t\t\tARAP_coeff.push_back(Eigen::Triplet<double>(i, i, cotan_sum));\n\t\t}\n\t}\n\tA_sparse.setFromTriplets(ARAP_coeff.begin(), ARAP_coeff.end());\n\t// pre-computation\n\tsolver.compute(A_sparse);\n\tif (solver.info() != Success) {\n\t\tqDebug() << \"decomposition failed\" << endl;\n\t}\n\n}\n\n\n\n\nvoid ARAP::CongruentMapping2D()\n{\n\tthis->points2d.clear();\n\tthis->cot2d.clear();\n\tfor (auto triangle : this->heMesh->Polygons())\n\t{\n\t\tif (triangle != nullptr) {\n\t\t\tmap<V*, pointf3> map_v_2d;\n\n\t\t\tauto v0 = triangle->BoundaryVertice()[0];\n\t\t\tauto v1 = triangle->BoundaryVertice()[1];\n\t\t\tauto v2 = triangle->BoundaryVertice()[2];\n\n\t\t\tmap_v_2d[v0] = pointf3(0, 0, 0); // set new v0 = (0,0,0)\n\n\t\t\t// get 2d coordinates\n\t\t\tdouble dist01 = pointf3::distance(v0->pos.cast_to<pointf3>(), v1->pos.cast_to<pointf3>());\n\t\t\tdouble dist02 = pointf3::distance(v0->pos.cast_to<pointf3>(), v2->pos.cast_to<pointf3>());\n\t\t\tdouble cos01_02 = vecf3::cos_theta((v1->pos - v0->pos), (v2->pos - v0->pos)); // angle of edge 01 and 02\n\t\t\tdouble sin01_02 = sqrt(1 - cos01_02 * cos01_02);\n\n\t\t\tmap_v_2d[v1] = pointf3(dist01, 0, 0);   // set new v1 = (dist01,0,0)\n\t\t\tmap_v_2d[v2] = pointf3(dist02 * cos01_02, dist02 * sin01_02, 0);  // set new v2 = (d02 * cos, d02 * sin, 0)\n\n\t\t\tthis->points2d.push_back(map_v_2d); // triangle in points2d has the same sequence with heMesh->triangles()\n\n\t\t\t// get cot\n\t\t\tmap<V*, double> cotan_2d;\n\t\t\tfor (size_t i = 0; i < 3; i++)\n\t\t\t{\n\t\t\t\tdouble cos = vecf3::cos_theta((triangle->BoundaryVertice()[i]->pos - triangle->BoundaryVertice()[(i + 2) % 3]->pos),\n\t\t\t\t\t(triangle->BoundaryVertice()[(i + 1) % 3]->pos - triangle->BoundaryVertice()[(i + 2) % 3]->pos));\n\t\t\t\tdouble sin = sqrt(1 - cos * cos);\n\t\t\t\tcotan_2d[triangle->BoundaryVertice()[(i + 2) % 3]] = (cos / sin); // store the angle of edge i, i+1. idx is V_{(i+2) %3}\n\t\t\t}\n\t\t\tassert(cotan_2d.size() == 3);\n\t\t\tthis->cot2d.push_back(cotan_2d);\n\t\t}\n\t}\n\n\tassert(this->points2d.size() == this->nT);\n\tassert(this->cot2d.size() == this->nT);\n\n}\n\ndouble ARAP::getCotan(int tri_idx, V* v)\n{\n\tassert(this->cot2d.size() == this->nT);\n\ttry\n\t{\n\t\tauto cotan = cot2d[tri_idx].at(v);\n\t\treturn cotan;\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\tcout << \"[Error] Cannot find V in map. \";\n\t}\n}\ndouble ARAP::getCotan(V* v0, V* v1, V* v2)\n{\n\tdouble cos = vecf3::cos_theta((v0->pos - v2->pos), (v1->pos - v2->pos));\n\tdouble sin = sqrt(1 - cos * cos);\n\treturn cos / sin;\n}\n\n\nvoid ARAP::setb(size_t idx1, pointf2 pos1, size_t idx2, pointf2 pos2)\n{\n\tARAP_mat_b = MatrixXd(this->nV, 2);\n\tARAP_mat_b.setZero();\n\n\t// two anchor points\n\tARAP_mat_b(idx1, 0) = pos1[0];  // x\n\tARAP_mat_b(idx1, 1) = pos1[1]; // y\n\n\t//ARAP_mat_b(idx2, 0) = pos2[0];  // x\n\t//ARAP_mat_b(idx2, 1) = pos2[1]; // y\n\n\t// Other non-anchor points\n\tfor (size_t i = 0; i < this->nV; i++)\n\t{\n\t\tif (i != idx1/* && i != idx2*/) {\n\t\t\tauto v = heMesh->Vertices()[i];\n\t\t\tMatrixXd b(2, 1);\n\t\t\tb.setZero();\n\t\t\t//cout << \"v idx: \" << heMesh->Index(v) << endl<<endl;\n\t\t\t// traverse adjecent vertrices\n\t\t\tfor (auto adj_v : v->AdjVertices())\n\t\t\t{\n\t\t\t\tsize_t adj_idx = heMesh->Index(adj_v);  // get index of adj_v\n\t\t\t\t// get adjacent triangles\n\t\t\t\tauto e = v->EdgeWith(adj_v);\n\t\t\t\tauto he1 = e->HalfEdge();\n\t\t\t\tauto he2 = e->HalfEdge()->Pair();\n\n\t\t\t\t// get Lt and cot\n\t\t\t\tauto triangle1 = he1->Polygon();\n\t\t\t\tif (triangle1 != nullptr)\n\t\t\t\t{\n\t\t\t\t\tauto tri_v1 = he1->Next()->End();\n\t\t\t\t\tassert(heMesh->Index(tri_v1) != heMesh->Index(v)\n\t\t\t\t\t\t&& heMesh->Index(tri_v1) != heMesh->Index(adj_v));\n\n\t\t\t\t\tsize_t tri_idx = heMesh->Index(triangle1);\n\t\t\t\t\tdouble cot1 = getCotan(tri_idx, tri_v1);\n\t\t\t\t\tmap<V*, pointf3> mapped_v = this->points2d[tri_idx]; // congruent mapping of triangle1 \n\t\t\t\t\tMatrixXd Lt = Lt_array[tri_idx];\n\t\t\t\t\tMatrixXd delta_x(2, 1);\n\t\t\t\t\tdelta_x <<\n\t\t\t\t\t\tmapped_v[v][0] - mapped_v[adj_v][0],\n\t\t\t\t\t\tmapped_v[v][1] - mapped_v[adj_v][1];\n\n\t\t\t\t\tb += cot1 * Lt * delta_x;\n\t\t\t\t}\n\n\t\t\t\tauto triangle2 = he2->Polygon();\n\t\t\t\tif (triangle2 != nullptr)\n\t\t\t\t{\n\t\t\t\t\tauto tri_v2 = he2->Next()->End();\n\t\t\t\t\tassert(heMesh->Index(tri_v2) != heMesh->Index(v)\n\t\t\t\t\t\t&& heMesh->Index(tri_v2) != heMesh->Index(adj_v));\n\n\t\t\t\t\tsize_t tri_idx = heMesh->Index(triangle2);\n\t\t\t\t\tdouble cot2 = getCotan(tri_idx, tri_v2);\n\t\t\t\t\tmap<V*, pointf3> mapped_v = this->points2d[tri_idx]; // congruent mapping of triangle1 \n\t\t\t\t\tMatrixXd Lt = Lt_array[tri_idx];\n\t\t\t\t\tMatrixXd delta_x(2, 1);\n\t\t\t\t\tdelta_x <<\n\t\t\t\t\t\tmapped_v[v][0] - mapped_v[adj_v][0],\n\t\t\t\t\t\tmapped_v[v][1] - mapped_v[adj_v][1];\n\t\t\t\t\tb += cot2 * Lt * delta_x;\n\t\t\t\t}\n\t\t\t}\n\t\t\tARAP_mat_b(i, 0) = b(0); // x\n\t\t\tARAP_mat_b(i, 1) = b(1); // y \n\t\t}\n\t}\n}", "meta": {"hexsha": "3f35bb88bc5ed67579bef594a2d254bf665c4acf", "size": 11857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/ARAP.cpp", "max_stars_repo_name": "bigpehi/USTC_CG", "max_stars_repo_head_hexsha": "847f5685ecdb45a9e8c9373f575e573a5328ae65", "max_stars_repo_licenses": ["MIT"], "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/ARAP.cpp", "max_issues_repo_name": "bigpehi/USTC_CG", "max_issues_repo_head_hexsha": "847f5685ecdb45a9e8c9373f575e573a5328ae65", "max_issues_repo_licenses": ["MIT"], "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/ARAP.cpp", "max_forks_repo_name": "bigpehi/USTC_CG", "max_forks_repo_head_hexsha": "847f5685ecdb45a9e8c9373f575e573a5328ae65", "max_forks_repo_licenses": ["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.5852017937, "max_line_length": 137, "alphanum_fraction": 0.6259593489, "num_tokens": 4060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.721743206297598, "lm_q1q2_score": 0.5724188321413272}}
{"text": "#ifndef _MLES_LAYER_HPP_\n#define _MLES_LAYER_HPP_\n\n#include <memory>\n#include <Eigen/Dense>\n#include \"Activation.hpp\"\n#include <fstream>\n\nnamespace mles\n{\n    class Layer\n    {\n        private:\n            unsigned int id;\n            bool isOutput;\n            Eigen::MatrixXd weight;\n            ActivationPtr activation;\n\n            Eigen::MatrixXd z, dz, A, delta;\n\n        public:\n            Layer();\n            Layer(unsigned int id, unsigned int inputSize, unsigned int outputSize, ActivationPtr activation, bool isOutput);\n            virtual ~Layer();\n\n            double error(const Eigen::MatrixXd& y);\n            Eigen::MatrixXd forward(const Eigen::MatrixXd& x);\n            Eigen::MatrixXd backward(const Eigen::MatrixXd& y, Layer *layer);\n            Eigen::MatrixXd update(double learningRate, const Eigen::MatrixXd& a);\n\n            void load(std::ifstream& f);\n            void write(std::ofstream& f);\n            void print();\n\n            void reset();\n\n    };\n}\n\n#endif\n", "meta": {"hexsha": "fa25a62289c86a532eca092fa6700a2ae57c97de", "size": 996, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/mles/Layer.hpp", "max_stars_repo_name": "AlexanderSilvaB/mles", "max_stars_repo_head_hexsha": "e1bc81de8a0a4625343500a69ebd0001729ad654", "max_stars_repo_licenses": ["MIT"], "max_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/mles/Layer.hpp", "max_issues_repo_name": "AlexanderSilvaB/mles", "max_issues_repo_head_hexsha": "e1bc81de8a0a4625343500a69ebd0001729ad654", "max_issues_repo_licenses": ["MIT"], "max_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/mles/Layer.hpp", "max_forks_repo_name": "AlexanderSilvaB/mles", "max_forks_repo_head_hexsha": "e1bc81de8a0a4625343500a69ebd0001729ad654", "max_forks_repo_licenses": ["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.2926829268, "max_line_length": 125, "alphanum_fraction": 0.5853413655, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5724188298292426}}
{"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": "// Including SDKDDKVer.h defines the highest available Windows platform.\n// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and\n// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.\n#include <SDKDDKVer.h>\n\n#include \"CppUnitTest.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\n\n#include \"ComputeRigidTransform.h\"\n#include <Eigen/Dense>\n#include <time.h>\n#include <vector>\n\n\n\nnamespace TestComputeRigidTransform\n{\t\t\n\tTEST_CLASS(UnitTestRigidTransform)\n\t{\n\tpublic:\n\t\t\n\t\tTEST_METHOD(TestNoTransform)\n\t\t{\n\t\t\ttypedef double Type;\n\t\t\tsrand(time(NULL));\n\t\t\t\n\t\t\tstd::vector<Eigen::Matrix<Type, 3, 1>> vertices;\n\n\t\t\tfor (int i = 0; i < 100; ++i)\n\t\t\t{\n\t\t\t\tconst Eigen::Matrix<Type, 3, 1> v(rand(), rand(), rand());\n\t\t\t\tvertices.push_back(v);\n\t\t\t}\n\n\t\t\tEigen::Matrix<Type, 3, 3> R = Eigen::Matrix<Type, 3, 3>::Zero();\n\t\t\tEigen::Matrix<Type, 3, 1> t = Eigen::Matrix<Type, 3, 1>::Zero();\n\t\t\tComputeRigidTransform(vertices, vertices, R, t);\n\n\t\t\tAssert::IsTrue(R.isIdentity(0.00001), L\"\\n<Rotation matrix is not identity>\\n\", LINE_INFO());\n\t\t\tAssert::IsTrue(t.isZero(0.00001), L\"\\n<Translation vector is not zero>\\n\", LINE_INFO());\n\t\t}\n\n\t};\n\n\n}", "meta": {"hexsha": "19f6f71e51afc793dcd33056803fc61f11a1eed1", "size": 1232, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Test/TestComputeRigidTransform.cpp", "max_stars_repo_name": "diegomazala/QtKinect", "max_stars_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-08-04T14:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-27T13:46:13.000Z", "max_issues_repo_path": "src/Test/TestComputeRigidTransform.cpp", "max_issues_repo_name": "diegomazala/QtKinect", "max_issues_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Test/TestComputeRigidTransform.cpp", "max_forks_repo_name": "diegomazala/QtKinect", "max_forks_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-12-08T06:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T10:29:17.000Z", "avg_line_length": 25.6666666667, "max_line_length": 97, "alphanum_fraction": 0.6923701299, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5722093805085147}}
{"text": "//  (C) Copyright Eric Niebler 2005.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Test case for pot_quantile.hpp (weighted feature)\n\n#define BOOST_NUMERIC_FUNCTIONAL_STD_COMPLEX_SUPPORT\n#define BOOST_NUMERIC_FUNCTIONAL_STD_VALARRAY_SUPPORT\n#define BOOST_NUMERIC_FUNCTIONAL_STD_VECTOR_SUPPORT\n\n#include <boost/random.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    // tolerance in %\n    double epsilon = 1.;\n\n    double mu1, mu2, l;\n\n    mu1 = 1.;\n    mu2 = -1.;\n    l = 0.5;\n\n    // two random number generators\n    boost::lagged_fibonacci607 rng;\n    boost::normal_distribution<> mean_sigma1(mu1,1);\n    boost::normal_distribution<> mean_sigma2(mu2,1);\n    boost::exponential_distribution<> lambda(l);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal1(rng, mean_sigma1);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal2(rng, mean_sigma2);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::exponential_distribution<> > exponential(rng, lambda);\n\n    accumulator_set<double, stats<tag::weighted_pot_quantile<right>(with_threshold_value)>, double > acc1(\n        pot_threshold_value = 3.\n    );\n    accumulator_set<double, stats<tag::weighted_pot_quantile<right>(with_threshold_probability)>, double > acc2(\n        right_tail_cache_size = 10000\n      , pot_threshold_probability = 0.99\n    );\n    accumulator_set<double, stats<tag::weighted_pot_quantile<left>(with_threshold_value)>, double > acc3(\n        pot_threshold_value = -3.\n    );\n    accumulator_set<double, stats<tag::weighted_pot_quantile<left>(with_threshold_probability)>, double > acc4(\n        left_tail_cache_size = 10000\n      , pot_threshold_probability = 0.01\n    );\n\n    accumulator_set<double, stats<tag::weighted_pot_quantile<right>(with_threshold_value)>, double > acc5(\n        pot_threshold_value = 5.\n    );\n    accumulator_set<double, stats<tag::weighted_pot_quantile<right>(with_threshold_probability)>, double > acc6(\n        right_tail_cache_size = 10000\n      , pot_threshold_probability = 0.995\n    );\n\n    for (std::size_t i = 0; i < 100000; ++i)\n    {\n        double sample1 = normal1();\n        double sample2 = normal2();\n        acc1(sample1, weight = std::exp(-mu1 * (sample1 - 0.5 * mu1)));\n        acc2(sample1, weight = std::exp(-mu1 * (sample1 - 0.5 * mu1)));\n        acc3(sample2, weight = std::exp(-mu2 * (sample2 - 0.5 * mu2)));\n        acc4(sample2, weight = std::exp(-mu2 * (sample2 - 0.5 * mu2)));\n    }\n\n    for (std::size_t i = 0; i < 100000; ++i)\n    {\n        double sample = exponential();\n        acc5(sample, weight = 1./l * std::exp(-sample * (1. - l)));\n        acc6(sample, weight = 1./l * std::exp(-sample * (1. - l)));\n    }\n\n    BOOST_CHECK_CLOSE( quantile(acc1, quantile_probability = 0.999), 3.090232, epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc2, quantile_probability = 0.999), 3.090232, epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc3, quantile_probability = 0.001), -3.090232, epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc4, quantile_probability = 0.001), -3.090232, epsilon );\n\n    BOOST_CHECK_CLOSE( quantile(acc5, quantile_probability = 0.999), 6.908, epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc6, quantile_probability = 0.999), 6.908, epsilon );\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"weighted_pot_quantile test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n", "meta": {"hexsha": "28d424ac064b417d95f2f3bfe0253525557b6ed8", "size": 4085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/accumulators/test/weighted_pot_quantile.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/accumulators/test/weighted_pot_quantile.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/accumulators/test/weighted_pot_quantile.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 38.9047619048, "max_line_length": 119, "alphanum_fraction": 0.6717258262, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5722093805085147}}
{"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() );// \u4fe1\u606f\u77e9\u9635\u8868\u793a2\u7ef4\u4e0a\u4fa7\u91cd\u54ea\u4e00\u7ef4\uff0cxy\u662f\u4e00\u6837\u91cd\u8981\u7684\uff0c\u6240\u4ee5\u5c31\u662f\u5355\u4f4d\u77e9\u9635\uff0c\u4f46\u662f\u57286\u7ef4\u7684\u4f4d\u59ff\u4e2d\uff0c\u6709\u53ef\u80fd\u66f4\u4fa7\u91cd\u4f18\u5316\u65cb\u8f6c\u6216\u8005\u4f4d\u79fb\uff0c\u5c31\u9700\u8981\u8bbe\u7f6e\u4fe1\u606f\u77e9\u9635\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": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2011-2014, Willow Garage, Inc.\n *  Copyright (c) 2014-2015, Open Source Robotics Foundation\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\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 Open Source Robotics Foundation 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\n#define BOOST_TEST_MODULE FCL_MATH\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\n#include <hpp/fcl/data_types.h>\n#include <hpp/fcl/math/transform.h>\n\n#include <hpp/fcl/internal/intersect.h>\n#include <hpp/fcl/internal/tools.h>\n\nusing namespace hpp::fcl;\n\n\n\nBOOST_AUTO_TEST_CASE(vec_test_eigen_vec64)\n{\n  Vec3f v1(1.0, 2.0, 3.0);\n  BOOST_CHECK(v1[0] == 1.0);\n  BOOST_CHECK(v1[1] == 2.0);\n  BOOST_CHECK(v1[2] == 3.0);\n\n  Vec3f v2 = v1;\n  Vec3f v3(3.3, 4.3, 5.3);\n  v1 += v3;\n  BOOST_CHECK(isEqual(v1, v2 + v3));\n  v1 -= v3;\n  BOOST_CHECK(isEqual(v1, v2));\n  v1 -= v3;\n  BOOST_CHECK(isEqual(v1, v2 - v3));\n  v1 += v3;\n\n  v1.array() *= v3.array();\n  BOOST_CHECK(isEqual(v1, v2.cwiseProduct(v3)));\n  v1.array() /= v3.array();\n  BOOST_CHECK(isEqual(v1, v2));\n  v1.array() /= v3.array();\n  BOOST_CHECK(isEqual(v1, v2.cwiseQuotient(v3)));\n  v1.array() *= v3.array();\n\n  v1 *= 2.0;\n  BOOST_CHECK(isEqual(v1, v2 * 2.0));\n  v1 /= 2.0;\n  BOOST_CHECK(isEqual(v1, v2));\n  v1 /= 2.0;\n  BOOST_CHECK(isEqual(v1, v2 / 2.0));\n  v1 *= 2.0;\n\n  v1.array() += 2.0;\n  BOOST_CHECK(isEqual(v1, (v2.array() + 2.0).matrix()));\n  v1.array() -= 2.0;\n  BOOST_CHECK(isEqual(v1, v2));\n  v1.array() -= 2.0;\n  BOOST_CHECK(isEqual(v1, (v2.array() - 2.0).matrix()));\n  v1.array() += 2.0;\n\n  BOOST_CHECK(isEqual((-Vec3f(1.0, 2.0, 3.0)), Vec3f(-1.0, -2.0, -3.0)));\n\n  v1 = Vec3f(1.0, 2.0, 3.0);\n  v2 = Vec3f(3.0, 4.0, 5.0);\n  BOOST_CHECK(isEqual((v1.cross(v2)), Vec3f(-2.0, 4.0, -2.0)));\n  BOOST_CHECK(std::abs(v1.dot(v2) - 26) < 1e-5);\n\n  v1 = Vec3f(3.0, 4.0, 5.0);\n  BOOST_CHECK(std::abs(v1.squaredNorm() - 50) < 1e-5);\n  BOOST_CHECK(std::abs(v1.norm() - sqrt(50)) < 1e-5);\n  BOOST_CHECK(isEqual(v1.normalized(), v1 / v1.norm()));\n\n\n  v1 = Vec3f(1.0, 2.0, 3.0);\n  v2 = Vec3f(3.0, 4.0, 5.0);\n  BOOST_CHECK(isEqual(v1.cross(v2), Vec3f(-2.0, 4.0, -2.0)));\n  BOOST_CHECK(v1.dot(v2) == 26);\n}\n\nVec3f rotate (Vec3f input, FCL_REAL w, Vec3f vec) {\n  return 2*vec.dot(input)*vec + (w*w - vec.dot(vec))*input + 2*w*vec.cross(input);\n}\n\nBOOST_AUTO_TEST_CASE(quaternion)\n{\n  Quaternion3f q1 (Quaternion3f::Identity()), q2, q3;\n  q2 = fromAxisAngle(Vec3f(0,0,1), M_PI/2);\n  q3 = q2.inverse();\n\n  Vec3f v(1,-1,0);\n\n  BOOST_CHECK(isEqual(v, q1 * v));\n  BOOST_CHECK(isEqual(Vec3f(1,1,0), q2 * v));\n  BOOST_CHECK(isEqual(rotate(v, q3.w(), Vec3f(q3.x(), q3.y(), q3.z())), q3 * v));\n}\n\nBOOST_AUTO_TEST_CASE(transform)\n{\n  Quaternion3f q = fromAxisAngle(Vec3f(0,0,1), M_PI/2);\n  Vec3f T (0,1,2);\n  Transform3f tf (q, T);\n\n  Vec3f v(1,-1,0);\n\n  BOOST_CHECK(isEqual(q * v + T, q * v + T));\n\n  Vec3f rv (q * v);\n  // typename Transform3f::transform_return_type<Vec3f>::type output =\n    // tf * v;\n  // std::cout << rv << std::endl;\n  // std::cout << output.lhs() << std::endl;\n  BOOST_CHECK(isEqual(rv + T, tf.transform(v)));\n}\n", "meta": {"hexsha": "61a1717aaa78d7e472c5bf487fdc3a48c4419c23", "size": 4572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math.cpp", "max_stars_repo_name": "rstrudel/hpp-fcl", "max_stars_repo_head_hexsha": "9e4d930b5af2b699475af1483c6dbe5a672bbab8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math.cpp", "max_issues_repo_name": "rstrudel/hpp-fcl", "max_issues_repo_head_hexsha": "9e4d930b5af2b699475af1483c6dbe5a672bbab8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math.cpp", "max_forks_repo_name": "rstrudel/hpp-fcl", "max_forks_repo_head_hexsha": "9e4d930b5af2b699475af1483c6dbe5a672bbab8", "max_forks_repo_licenses": ["BSD-3-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.3150684932, "max_line_length": 82, "alphanum_fraction": 0.6609798775, "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5721721359944839}}
{"text": "#include <fmt/format.h>\n#include <scn/scn.h>\n\n#include <boost/spirit/include/karma.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 <cassert>\n#include <charconv>\n#include <cmath>\n#include <cstdlib>\n#include <cstring>\n#include <iomanip>\n#include <numbers>\n#include <random>\n#include <sstream>\n#include <string_view>\n\nconstexpr int DEFAULT_PRECISION = 17;\n\nconstexpr int BUF_SIZE =\n    1 /*'-'*/ +\n    (std::numeric_limits<double>::max_exponent10 + 1) /*exponent+1 digits*/\n    + 1 /*'.'*/ + DEFAULT_PRECISION /* precision*/ + 1 /*terminating null*/;\n\ntemplate <typename Format, typename... Args>\nvoid error(Format &&format, Args &&...args) {\n  throw std::runtime_error(\n      fmt::format(format, std::forward<Args>(args)...));\n}\n\ntemplate <typename T>\nclass Rng {\n public:\n  explicit Rng(unsigned seed = 0) : gen_{seed} {}\n\n  T operator()() { return dist_(gen_); }\n\n private:\n  std::mt19937 gen_;\n  using dist = std::conditional_t<std::is_integral_v<T>,\n                                  std::uniform_int_distribution<T>,\n                                  std::uniform_real_distribution<T>>;\n  dist dist_;\n};\n\ntemplate <typename Method>\nstatic size_t verifyValue(double value, Method method,\n                          const std::string_view expect = \"\") {\n  auto str = method(value);\n\n  if (not expect.empty() && str != expect) {\n    error(\"Error: expect {} but actual {}\", expect, str);\n  }\n\n  auto [roundtrip, processed] = method(str);\n\n  if (processed < 0) {\n    return 0;\n  }\n\n  if (str.size() != static_cast<size_t>(processed)) {\n    error(\"Error: some extra character {} -> '{}'\", value, str);\n  }\n\n  if (value != roundtrip) {\n    error(\"Error: roundtrip fail {:.17g} -> '{}' -> {:.17g}\", value, str,\n          roundtrip);\n  }\n\n  return str.size();\n}\n\ntemplate <typename Method>\nstatic void verify(const std::string_view fname, Method method) try {\n  fmt::print(\"Verifying {:20} ... \", fname);\n\n  // Boundary and simple cases\n  verifyValue(0, method);\n  verifyValue(0.1, method, \"0.1\");\n  verifyValue(0.12, method, \"0.12\");\n  verifyValue(0.123, method, \"0.123\");\n  verifyValue(0.1234, method, \"0.1234\");\n  verifyValue(1.2345, method, \"1.2345\");\n  verifyValue(1.0 / 3.0, method);\n  verifyValue(2.0 / 3.0, method);\n  verifyValue(10.0 / 3.0, method);\n  verifyValue(20.0 / 3.0, method);\n  verifyValue(std::numeric_limits<double>::min(), method);\n  verifyValue(std::numeric_limits<double>::max(), method);\n  verifyValue(std::numeric_limits<double>::denorm_min(), method);\n\n  Rng<double> r;\n\n  constexpr unsigned kVerifyRandomCount = 100000;\n\n  uint64_t lenSum = 0;\n  size_t lenMax = 0;\n  for (unsigned i = 0; i < kVerifyRandomCount; i++) {\n    double d;\n    do {\n      d = r();\n    } while (std::isnan(d) || std::isinf(d));\n    size_t len = verifyValue(d, method);\n    lenSum += len;\n    lenMax = std::max(lenMax, len);\n  }\n\n  double lenAvg = double(lenSum) / kVerifyRandomCount;\n  fmt::print(\"OK. Length Avg = {:2.3f}, Max = {}\\n\", lenAvg, lenMax);\n} catch (const std::exception &ex) {\n  fmt::print(\"{}\\n\", ex.what());\n}\n\n// parse the 2 strings as numbers, add the numbers and return the result as a\n// string String add(String lhs, String rhs);\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wfloat-conversion\"\n#pragma GCC diagnostic ignored \"-Wconversion\"\n\n// https://github.com/dspinellis/unix-history-repo/blob/Research-V6/usr/source/iolib/ftoa.c\nvoid ftoa(double x, char *str, int prec, int format) {\n  /* converts a floating point number to an ascii string */\n  /* x is stored into str, which should be at least 30 chars long */\n  int ie, i, k, ndig, fstyle;\n  double y;\n  // if (nargs() != 7)\n  //   IEHzap(\"ftoa  \");\n  ndig = (prec <= 0) ? 7 : (prec > 22 ? 23 : prec + 1);\n  if (format == 'f' || format == 'F')\n    fstyle = 1;\n  else\n    fstyle = 0;\n  /* print in e format unless last arg is 'f' */\n  ie = 0;\n  /* if x negative, write minus and reverse */\n  if (x < 0) {\n    *str++ = '-';\n    x = -x;\n  }\n\n  /* put x in range 1 <= x < 10 */\n  if (x > 0.0)\n    while (x < 1.0) {\n      x *= 10.0;\n      ie--;\n    }\n  while (x >= 10.0) {\n    x = x / 10.0;\n    ie++;\n  }\n\n  /* in f format, number of digits is related to size */\n  if (fstyle) ndig += ie;\n\n  /* round. x is between 1 and 10 and ndig will be printed to\n     right of decimal point so rounding is ... */\n  for (y = i = 1; i < ndig; i++) y = y / 10.;\n  x += y / 2.;\n  if (x >= 10.0) {\n    x = 1.0;\n    ie++;\n  } /* repair rounding disasters */\n  /* now loop.  put out a digit (obtain by multiplying by\n    10, truncating, subtracting) until enough digits out */\n  /* if fstyle, and leading zeros, they go out special */\n  if (fstyle && ie < 0) {\n    *str++ = '0';\n    *str++ = '.';\n    if (ndig < 0) ie = ie - ndig; /* limit zeros if underflow */\n    for (i = -1; i > ie; i--) *str++ = '0';\n  }\n  for (i = 0; i < ndig; i++) {\n    k = x;\n    *str++ = k + '0';\n    if (i == (fstyle ? ie : 0)) /* where is decimal point */\n      *str++ = '.';\n    x -= (y = k);\n    x *= 10.0;\n  }\n\n  /* now, in estyle,  put out exponent if not zero */\n  if (!fstyle && ie != 0) {\n    *str++ = 'E';\n    if (ie < 0) {\n      ie = -ie;\n      *str++ = '-';\n    }\n    for (k = 100; k > ie; k /= 10)\n      ;\n    for (; k > 0; k /= 10) {\n      *str++ = ie / k + '0';\n      ie = ie % k;\n    }\n  }\n  *str = '\\0';\n  return;\n}\n\n#pragma GCC diagnostic pop\n\nstruct to_double_res {\n  double res = 0;\n  ptrdiff_t processed;\n};\n\n[[maybe_unused]] struct {\n  to_double_res operator()(const std::string &str) const {\n    return {std::atof(str.c_str()), static_cast<ptrdiff_t>(str.size())};\n  }\n\n  std::string operator()(const double d) const {\n    char buf[BUF_SIZE];\n    ftoa(d, buf, DEFAULT_PRECISION, 'f');\n    return buf;\n  }\n} XtoY;\n\n[[maybe_unused]] struct {\n  to_double_res operator()(const std::string &str) const {\n    char *end;\n    auto res = std::strtod(str.c_str(), &end);\n    return {res, errno != 0 ? -1 : (end - str.c_str())};\n  }\n\n  std::string operator()(const double d) const {\n    char buf[BUF_SIZE];\n    gcvt(d, DEFAULT_PRECISION, buf);\n    return buf;\n  }\n} strtoX_gcvt;\n\n[[maybe_unused]] struct {\n  to_double_res operator()(const std::string &str) const {\n    double res = 0;\n    ptrdiff_t processed = -1;\n    std::sscanf(str.c_str(), \"%lf%tn\", &res, &processed);\n    return {res, processed};\n  }\n\n  std::string operator()(const double d) const {\n    char buf[BUF_SIZE];\n    std::sprintf(buf, \"%g\", d);\n    return buf;\n  }\n} sXf;\n\n[[maybe_unused]] struct {\n  to_double_res operator()(const std::string &str) const {\n    std::istringstream in{str};\n    double res = 0;\n    in >> res;\n    auto processed = [&]() -> ptrdiff_t {\n      if (in.eof()) {\n        return std::ssize(str);\n      }\n      return in.tellg();\n    }();\n    return {res, processed};\n  }\n\n  std::string operator()(const double d) const {\n    std::ostringstream out;\n    out << std::defaultfloat << d;\n    return out.str();\n  }\n} stringstream;\n\n[[maybe_unused]] struct {\n  to_double_res operator()(const std::string &str) const {\n    std::ios_base::iostate err = std::ios_base::goodbit;\n    std::istringstream sst;\n    using Facet = std::num_get<char, std::string::const_iterator>;\n    static std::locale loc{std::locale::classic(), new Facet};\n    double res = 0;\n    auto end =\n        std::use_facet<Facet>(loc).get(str.begin(), str.end(), sst, err, res);\n    return {res, (err & std::ios_base::failbit) ? -1 : (end - str.begin())};\n  }\n\n  std::string operator()(const double d) const {\n    std::ostringstream sst;\n    sst << std::defaultfloat;\n    std::string res;\n    res.reserve(BUF_SIZE);\n    using Facet = std::num_put<char, decltype(std::back_inserter(res))>;\n    std::locale loc{sst.getloc(), new Facet};\n    std::use_facet<Facet>(loc).put(std::back_inserter(res), sst, sst.fill(), d);\n    return res;\n  }\n} num_X;\n\n[[maybe_unused]] struct {\n  to_double_res operator()(const std::string &str) const {\n    return {std::stod(str), static_cast<ptrdiff_t>(str.size())};\n  }\n\n  std::string operator()(const double d) const { return std::to_string(d); }\n} stoX_to_string;\n\n[[maybe_unused]] struct {\n  to_double_res operator()(const std::string &str) const {\n    double res = 0;\n    const auto [end, ec] =\n        std::from_chars(str.data(), str.data() + str.size(), res);\n    return {res, std::error_condition{ec} ? -1 : (end - str.data())};\n  }\n\n  std::string operator()(const double d) const {\n    std::string res(BUF_SIZE, 0);\n    const auto [end, _] = std::to_chars(res.data(), res.data() + res.size(), d);\n    res.resize(static_cast<size_t>(end - res.data()));\n    return res;\n  }\n} X_chars;\n\n[[maybe_unused]] struct {\n  to_double_res operator()(const std::string &str) const {\n    double res = 0;\n    auto scan_result = scn::scan(str, \"{}\", res);\n    return {res, !scan_result ? -1 : (scan_result.begin() - str.data())};\n  }\n\n  std::string operator()(const double d) const { return fmt::format(\"{}\", d); }\n} scan_format;\n\n[[maybe_unused]] struct {\n  template <typename Num>\n  struct precision_policy : boost::spirit::karma::real_policies<Num>\n  {\n    precision_policy(unsigned precision) : precision_{precision} {}\n    unsigned precision(Num /*n*/) const { return precision_; }\n    unsigned precision_;\n  };\n\n  to_double_res operator()(const std::string &str) const {\n    namespace qi = boost::spirit::qi;\n\n    using boost::phoenix::ref;\n    using qi::_1;\n    using qi::double_;\n\n    double res = 0;\n    auto first = str.begin();\n    auto success = qi::parse(first, str.end(), double_[ref(res) = _1]);\n    return { res, !success ? -1 : first - str.begin() };\n  }\n\n  std::string operator()(const double d) const {\n    namespace karma = boost::spirit::karma;\n    using karma::double_;\n\n    std::string res;\n    using precision_double_ =\n        karma::real_generator<double, precision_policy<double>>;\n    karma::generate(std::back_inserter(res), precision_double_{DEFAULT_PRECISION}, d);\n    return res;\n  }\n} qi_karma;\n\nint main() {\n  verify(\"XtoY\", XtoY);\n  verify(\"strtoX_gcvt\", strtoX_gcvt);\n  verify(\"sXf\", sXf);\n  verify(\"stringstream\", stringstream);\n  verify(\"num_X\", num_X);\n  verify(\"stoX_to_string\", stoX_to_string);\n  verify(\"X_chars\", X_chars);\n  verify(\"scan_format\", scan_format);\n  verify(\"qi_karma\", qi_karma);\n}\n", "meta": {"hexsha": "431300768de4f90e8ca6c88d99cf403668a94dd4", "size": 10276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slides/number-string/examples/verify.cpp", "max_stars_repo_name": "dvirtz/slides", "max_stars_repo_head_hexsha": "b69d6b74ee3dc9d1461297309e68bb387f571fe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slides/number-string/examples/verify.cpp", "max_issues_repo_name": "dvirtz/slides", "max_issues_repo_head_hexsha": "b69d6b74ee3dc9d1461297309e68bb387f571fe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides/number-string/examples/verify.cpp", "max_forks_repo_name": "dvirtz/slides", "max_forks_repo_head_hexsha": "b69d6b74ee3dc9d1461297309e68bb387f571fe6", "max_forks_repo_licenses": ["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.5495978552, "max_line_length": 91, "alphanum_fraction": 0.6046126898, "num_tokens": 3034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5721721194103706}}
{"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": "/*-----------------------------------------------------------------------------+\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\r\n/** Example custom_interval.cpp \\file custom_interval.cpp \r\n    \\brief Shows how to use interval containers with own interval classes. \r\n\r\n    There may be instances, where we want to use interval container with our\r\n    own user defined interval classes. Boost interval containers can be adapted\r\n    to your interval class by partial template specialisation. Only a few lines\r\n    of code are needed to achieve this.\r\n\r\n    \\include custom_interval_/custom_interval.cpp\r\n*/\r\n//[example_custom_interval\r\n#include <iostream>\r\n#include <boost/icl/interval_set.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost::icl;\r\n\r\n// Here is a typical class that may model intervals in your application.\r\nclass MyInterval\r\n{\r\npublic:\r\n    MyInterval(): _first(), _past(){}\r\n    MyInterval(int lo, int up): _first(lo), _past(up){}\r\n    int first()const{ return _first; }\r\n    int past ()const{ return _past; }\r\nprivate:\r\n    int _first, _past;\r\n};\r\n\r\nnamespace boost{ namespace icl \r\n{\r\n// Class template interval_traits serves as adapter to register and customize your interval class\r\ntemplate<>\r\nstruct interval_traits< MyInterval >       //1.  Partially specialize interval_traits for \r\n{                                          //    your class MyInterval\r\n                                           //2.  Define associated types\r\n    typedef MyInterval     interval_type;  //2.1 MyInterval will be the interval_type\r\n    typedef int            domain_type;    //2.2 The elements of the domain are ints \r\n    typedef std::less<int> domain_compare; //2.3 This is the way our element shall be ordered.\r\n                                           //3.  Next we define the essential functions \r\n                                           //    of the specialisation\r\n                                           //3.1 Construction of intervals\r\n    static interval_type construct(const domain_type& lo, const domain_type& up) \r\n    { return interval_type(lo, up); }        \r\n                                           //3.2 Selection of values \r\n    static domain_type lower(const interval_type& inter_val){ return inter_val.first(); };\r\n    static domain_type upper(const interval_type& inter_val){ return inter_val.past(); };\r\n};\r\n\r\ntemplate<>\r\nstruct interval_bound_type<MyInterval>     //4.  Finally we define the interval borders.\r\n{                                          //    Choose between static_open         (lo..up)\r\n    typedef interval_bound_type type;      //                   static_left_open    (lo..up]\r\n    BOOST_STATIC_CONSTANT(bound_type, value = interval_bounds::static_right_open);//[lo..up)\r\n};                                         //               and static_closed       [lo..up] \r\n\r\n}} // namespace boost icl\r\n\r\nvoid custom_interval()\r\n{\r\n    // Now we can use class MyInterval with interval containers:\r\n    typedef interval_set<int, std::less, MyInterval> MyIntervalSet;\r\n    MyIntervalSet mySet;\r\n    mySet += MyInterval(1,9);\r\n    cout << mySet << endl;\r\n    mySet.subtract(3) -= 6;\r\n    cout << mySet << \"            subtracted 3 and 6\\n\";\r\n    mySet ^= MyInterval(2,8);\r\n    cout << mySet <<      \"  flipped between 2 and 7\\n\";\r\n}\r\n\r\n\r\nint main()\r\n{\r\n    cout << \">>Interval Container Library: Sample custom_interval.cpp <<\\n\";\r\n    cout << \"-----------------------------------------------------------\\n\";\r\n    cout << \"This program uses a user defined interval class:\\n\";\r\n    custom_interval();\r\n    return 0;\r\n}\r\n\r\n// Program output:\r\n/*-----------------------------------------------------------------------------\r\n>>Interval Container Library: Sample custom_interval.cpp <<\r\n-----------------------------------------------------------\r\nThis program uses a user defined interval class:\r\n{[1,                      9)}\r\n{[1,  3)   [4,  6)   [7,  9)}       subtracted 3 and 6\r\n{[1,2) [3,4)     [6,7) [8,9)}  flipped between 2 and 7\r\n-----------------------------------------------------------------------------*/\r\n//]\r\n\r\n", "meta": {"hexsha": "411707a38d29c66082e4b4ee579a34dce7720774", "size": 4532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/icl/example/custom_interval_/custom_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/custom_interval_/custom_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/custom_interval_/custom_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": 43.5769230769, "max_line_length": 98, "alphanum_fraction": 0.5408208297, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.572070327839158}}
{"text": "#pragma once\n#include <cmath>\n\n#include <boost/any.hpp>\n\n#include <SFML/System/Vector2.hpp>\n\nnamespace tt\n{\n\nusing Tile = sf::Vector2f;\nusing Size = sf::Vector2f;\nusing Scale = sf::Vector2f;\n\nenum class TileType\n{\n    NONE,\n    ZONE\n};\n\nstruct TileInfo\n{\n    TileType        type;\n    boost::any      data;\n    Tile            tile;\n};\n\nnamespace tiles\n{\n\ninline Tile getTileFromGlobal(const sf::Vector2f& global, const Size& tilesize, const Scale& scale)\n{\n    sf::Vector2f temp;\n    temp.x = global.x / scale.x;\n    temp.y = global.y / scale.y;\n\n    temp.x = std::floor(temp.x / tilesize.x);\n    temp.y = std::floor(temp.y / tilesize.y);\n\n    return temp;\n}\n\ninline sf::Vector2f getGlobalFromTile(const Tile& tilepos, const Size& tileSize, const Scale& scale)\n{\n    sf::Vector2f temp;\n    \n    temp.x = static_cast<float>(tilepos.x * tileSize.x * scale.x);\n    temp.y = static_cast<float>(tilepos.y * tileSize.y * scale.y);\n    \n    return temp;\n}\n\n} // tiles\n} // namespace tt", "meta": {"hexsha": "74891eb7f00b1942368b6287343e79f748e410b2", "size": 979, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Tiles.hpp", "max_stars_repo_name": "zethon/ttvg", "max_stars_repo_head_hexsha": "51d79ee3154669447dd522731aa0f7057e723abd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-02T20:51:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T21:53:41.000Z", "max_issues_repo_path": "src/Tiles.hpp", "max_issues_repo_name": "zethon/ttvg", "max_issues_repo_head_hexsha": "51d79ee3154669447dd522731aa0f7057e723abd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2020-07-20T16:37:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T00:52:06.000Z", "max_forks_repo_path": "src/Tiles.hpp", "max_forks_repo_name": "zethon/ttvg", "max_forks_repo_head_hexsha": "51d79ee3154669447dd522731aa0f7057e723abd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-02T20:51:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-02T20:51:37.000Z", "avg_line_length": 18.1296296296, "max_line_length": 100, "alphanum_fraction": 0.6373850868, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5720507571335116}}
{"text": "#include <iostream>\n#include <cstdio>\n#include <ctime>\n#include <boost/numeric/mtl/mtl.hpp>\n#include \"boost/program_options.hpp\"\n\n\nusing namespace std;\nusing namespace mtl;\nusing namespace mtl::mat;\nnamespace po = boost::program_options;\n\n// m: numRows, n: numCols\ninline double simpleDenseTest_MTL(int m, int n, int num_trials) {\n\n  dense2D<double, parameters<tag::col_major> > A(m, n); random(A);\n  dense2D<double, parameters<tag::col_major> > B(m, n); random(B);\n  dense2D<double, parameters<tag::col_major> > C(m, n); random(C);\n  dense2D<double, parameters<tag::col_major> > D(m, n); random(D);\n  dense2D<double, parameters<tag::col_major> > E(m, n); random(E);\n\n  clock_t start;\n  double duration = 0.0;\n      \n  for (unsigned i = 0; i < num_trials; i++) {\n    start = clock();\n\n    (ele_div((A + B), C) - D) * E;\n\n    duration += ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  }\n  return duration / num_trials;\n\n}\n\n// m: numRows of A, n: numCols of A, and numRows of B, k: numCols of B\ninline double gemmDenseTest_MTL(int m, int n, int k, int num_trials) {\n\n  dense2D<double, parameters<tag::col_major> > A(m, n); random(A);\n  dense2D<double, parameters<tag::col_major> > B(m, n); random(B);\n  dense2D<double, parameters<tag::col_major> > C(n, k); random(C);\n  dense2D<double, parameters<tag::col_major> > D(n, k); random(D);\n  dense2D<double, parameters<tag::col_major> > E(m, k); random(E);\n\n  clock_t start;\n  double duration = 0.0;\n      \n  for (unsigned i = 0; i < num_trials; i++) {\n    start = clock();\n\n    E += (A + B) * (C - D);\n\n    duration += ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  }\n  return duration / num_trials;\n\n}\n\ninline double mulDenseTest_MTL(int a, int b, int c, int d, int num_trials) {\n\n  dense2D<double, parameters<tag::col_major> > A(a, a); random(A);\n  dense2D<double, parameters<tag::col_major> > B(a, b); random(B);\n  dense2D<double, parameters<tag::col_major> > C(b, c); random(C);\n  dense2D<double, parameters<tag::col_major> > D(c, d); random(D);\n\n  clock_t start;\n  double duration = 0.0;\n      \n  for (unsigned i = 0; i < num_trials; i++) {\n    start = clock();\n\n    A * B * C * D;\n\n    duration += ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  }\n\n  return duration / num_trials;\n\n}\n\nvoid runMTLTests(int num_trials, 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   cout << \"MTL Simple Test:\\t\" << simpleDenseTest_MTL(m, n, num_trials) << endl;\n   cout << \"MTL gemm Test:\\t\" << gemmDenseTest_MTL(m, n, k, num_trials) << endl;\n   cout << \"MTL mulDense Test:\\t\" << mulDenseTest_MTL(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    runMTLTests(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": "5c704edd0633e0b6e73751bbb66ceeceec9045aa", "size": 4504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main/cpp/mtl.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/mtl.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/mtl.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": 33.8646616541, "max_line_length": 93, "alphanum_fraction": 0.6136767318, "num_tokens": 1333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5720462438257773}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#ifndef SPLINEFUNCTION_HPP\n#define SPLINEFUNCTION_HPP\n\n#include <algorithm>\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n#include <unsupported/Eigen/Splines>\n\n\n/*! \\file SplineFunction.hpp\n *  \\class SplineFunction\n *  \\brief Spline interpolation of a function\n *  \\author Roberto Di Remigio\n *  \\date 2015\n *\n *  Taken from StackOverflow http://stackoverflow.com/a/29825204/2528668\n */\n\nclass SplineFunction __final\n{\nprivate:\n    typedef Eigen::Spline<double, 1> CubicSpline;\npublic:\n    /*! \\brief Constructor from abscissa and function values\n     *  \\param[in] x vector with abscissa values\n     *  \\param[in] y vector with function values\n     *\n     *  Interpolation happens in the initialization of the spline_ data\n     *  member. We use std::min to set the degree in order to ensure that no\n     *  more than a cubic spline is used, but short vectors are still accepted.\n     */\n    SplineFunction(const Eigen::VectorXd & x, const Eigen::VectorXd & y)\n\t    : xMin_(x.minCoeff()), xMax_(x.maxCoeff()),\n\t    spline_(Eigen::SplineFitting<CubicSpline>::Interpolate(y.transpose(),\n\t\t      std::min<int>(x.rows() - 1, 3), fitVector(x))\n\t           )\n\t{}\n    /*! \\brief Evaluate spline at given point\n     *  \\param[in] x evaluation point\n     */\n    double operator()(double x) const {\n\treturn spline_(fitScalar(x))(0);\n    }\nprivate:\n    double xMin_;\n    double xMax_;\n    CubicSpline spline_;\n    /*! \\brief Scale a scalar value to [0, 1] interval\n     *  \\param[in] x value to be scaled\n     *\n     *  val is defined in [min, max] This function returns the variable\n     *  as scaled to fit in the [0, 1] interval.\n     */\n    double fitScalar(double x) const {\n\t    return (x - xMin_) / (xMax_ - xMin_);\n    }\n    /*! \\brief Scale a vector to [0, 1] interval\n     *  \\param[in] x_vec a vector\n     *\n     *  Given column vector, returns a *row* vector with the values scaled\n     *  to fit a preset interval. The interval is embedded in the callable object.\n     */\n#ifdef HAS_CXX11_LAMBDA\n    Eigen::RowVectorXd fitVector(const Eigen::VectorXd & x_vec) const {\n\t    return x_vec.unaryExpr([this](double x) -> double { return fitScalar(x); }).transpose();\n    }\n#else /* HAS_CXX11_LAMBDA */\n    Eigen::RowVectorXd fitVector(const Eigen::VectorXd & x_vec) const {\n        pcm::function<double(double)> fit = pcm::bind(&SplineFunction::fitScalar, this, pcm::_1);\n\t    return x_vec.unaryExpr(fit).transpose();\n    }\n#endif /*HAS_CXX11_LAMBDA */\n};\n#endif // SPLINEFUNCTION_HPP\n", "meta": {"hexsha": "866368766cbb46458aa549fd15612eec4b6b0cab", "size": 3597, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/utils/SplineFunction.hpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/utils/SplineFunction.hpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/utils/SplineFunction.hpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2647058824, "max_line_length": 97, "alphanum_fraction": 0.6711148179, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.572046227302763}}
{"text": "#ifndef _DATA_ITEM_HPP_\n#define _DATA_ITEM_HPP_\n\n#include <fstream>\n#include <vector>\n#include <utility>\n#include <Eigen\\Dense>\n\nstruct LabeledData {\n  std::vector<unsigned> labels;\n  Eigen::MatrixXd data;\n};\n\nstruct DataItem {\n  unsigned target;\n  Eigen::RowVectorXd point;\n};\n\nstruct PredicitonItem {\n  unsigned target;\n  unsigned prediction;\n};\n\n\nEigen::MatrixXd StlVectorsToEigenMatrix(\n  const std::vector<std::vector<double> >& data) {\n/**\n *\n */\n  Eigen::MatrixXd matrix(data.size(), data[0].size());\n\n  unsigned i;\n  unsigned j;\n  for (i = 0; i < data.size(); ++i) {\n    for (j = 0; j < data[0].size(); ++j) {\n      matrix(i, j) = data[i][j];\n    }\n  }\n\n  return matrix;\n}\n\nLabeledData \nReadDataFromFile(const char* file_name) {\n/**\n *\n */\n  std::fstream fin;\n  fin.open(file_name);\n\n  std::vector<unsigned> labels;\n  std::vector<std::vector<double>> data;\n  double dummy;\n  while (fin.good()) {\n    fin >> dummy;\n    labels.push_back((unsigned) dummy);\n\n    std::vector<double> row;\n    unsigned i;\n    for (i = 0; i < 256; ++i) {\n      fin >> dummy;\n      row.push_back(dummy);\n    }\n    data.push_back(row);\n  }\n\n  LabeledData labeledData = {\n    labels, StlVectorsToEigenMatrix(data)\n  };\n\n  return labeledData;\n}\n\nEigen::MatrixXd GetDataSubset(const LabeledData* labeledData, std::vector<int> labels) {\n/**\n *\n */\n\n\n\n\n  return Eigen::MatrixXd(1,1);\n}\n\n\n#endif //define _DATA_ITEM_HPP_", "meta": {"hexsha": "8677ebee244cf0a358951324b68ccb50bac29218", "size": 1397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "STAT775/HW07/HW07/HW07/data_item.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": "STAT775/HW07/HW07/HW07/data_item.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": "STAT775/HW07/HW07/HW07/data_item.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": 16.2441860465, "max_line_length": 88, "alphanum_fraction": 0.637079456, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.5720462242019619}}
{"text": "#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n\n#include \"DenseMatrix.hpp\"\n\n#define BOOST_TEST_MODULE custom_main\n#define BOOST_TEST_NO_MAIN\n#define BOOST_TEST_ALTERNATIVE_API\n\n#ifndef REAL\n#define REAL double\n#endif\n\n#define TOL 1.0e-06\nconst int SIZE = 100;\nconst int size = 10;\n\nint add(int x, int y);\n\ntemplate<class T>\nstatic T multiply(T x, T y);\n\n// BOOST_AUTO_TEST_SUITE( boost_test_suite )\n\nBOOST_AUTO_TEST_CASE( test_case_00 )\n{\n  // Seven ways to check and report errors\n  // BOOST_CHECK( add(2,3) == 5 );\n  // BOOST_REQUIRE( add(2,3) == 5 );\n  // if ( add(2,3) != 5 ) BOOST_ERROR(\"Incorrect answer\");\n  // if ( add(2,3) != 5 ) BOOST_FAIL(\"Incorrect answer\");\n  // if ( add(2,3) != 5 ) throw \"Incorrect answer\";\n  // BOOST_CHECK_MESSAGE( add(2,3) == 5, \"add(...) result: \" << add(2,3) );\n  // BOOST_CHECK_EQUAL( add(2,3), 5);\n\n  REAL *A = (REAL*) calloc (SIZE, sizeof(REAL));\n  REAL *B = (REAL*) calloc (SIZE, sizeof(REAL));\n  REAL *C = (REAL*) calloc (SIZE, sizeof(REAL));\n\n  boost::numeric::ublas::matrix<double> A_bst(size, size), B_bst(size, size), \n    C_bst(size, size);\n\n  randMatrix(A, size, size); \n  randMatrix(B, size, size);\n  for (int i=0; i<SIZE; ++i) C[i] = 0.0;\n\n  // Assign all element values to Boost matrices\n  for (int i=0; i<size; ++i){\n    for (int j=0; j<size; ++j){\n      int idx = i*size + j;\n      A_bst(i, j) = A[idx];\n      B_bst(i, j) = B[idx];\n    }\n  }\n  \n  // Manual Version\n  dgemm(A, size, size, B, size, size, C);\n  // Boost Version\n  boost::numeric::ublas::axpy_prod(A_bst, B_bst, C_bst, true);\n\n  for (int i=0; i<size; ++i){\n    for (int j=0; j<size; ++j){\n      int idx = i*size + j;\n      BOOST_CHECK_CLOSE(C_bst(i,j), C[idx], TOL);\n    }\n  }\n\n}\n\nBOOST_AUTO_TEST_CASE( test_case_01 )\n{\n  int x = 5; int y = 7; int z = add(x, y);\n  BOOST_CHECK_EQUAL( z, 12 );\n}\n\nBOOST_AUTO_TEST_CASE( test_case_02 )\n{\n  long int x = 50; long int y = 30; \n  long int z = multiply<long int> (x, y);\n  BOOST_CHECK_EQUAL(z, 1500);\n}\n\n\n// BOOST_AUTO_TEST_SUITE_END()\n\nbool init_unit_test(){ return true; }\nint main(int argc, char **argv){ \n  return boost::unit_test::unit_test_main( &init_unit_test, argc, argv ); \n} \n\nint add(int x, int y) { return (x + y); }\n\ntemplate<class T>\nstatic T multiply(T x, T y)\n{ return (x*y); }\n", "meta": {"hexsha": "36cd902bf2e9fb5bca5145292068c774293ff38e", "size": 2351, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DENSE_MATRIX/BTEST/main.cpp", "max_stars_repo_name": "lnugraha/mtx-toolbox", "max_stars_repo_head_hexsha": "188078b4749db8b42f15ac5607501cc4b660317f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T20:51:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T20:51:22.000Z", "max_issues_repo_path": "DENSE_MATRIX/BTEST/main.cpp", "max_issues_repo_name": "lnugraha/mtx-toolbox", "max_issues_repo_head_hexsha": "188078b4749db8b42f15ac5607501cc4b660317f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DENSE_MATRIX/BTEST/main.cpp", "max_forks_repo_name": "lnugraha/mtx-toolbox", "max_forks_repo_head_hexsha": "188078b4749db8b42f15ac5607501cc4b660317f", "max_forks_repo_licenses": ["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.7474747475, "max_line_length": 78, "alphanum_fraction": 0.6278179498, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5720462156857025}}
{"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": "#ifndef PWALK_UTIL_MATH_FUNCTIONS_HPP_\n#define PWALK_UTIL_MATH_FUNCTIONS_HPP_\n\n#include <Eigen/Dense>\n\nnamespace pwalk {\n\ntemplate <typename Dtype>\nvoid sample_gaussian(const int n, const Dtype mu, const Dtype sigma, Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& r);\n\ntemplate <typename Dtype>\nDtype rng_uniform(const Dtype a, const Dtype b);\n\n// unnormalized gaussian density\ntemplate <typename Dtype>\nDtype gaussian_density(const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& x, const Eigen::Matrix<Dtype, Eigen::Dynamic, 1>& mu, const Eigen::Matrix<Dtype, Eigen::Dynamic, Eigen::Dynamic>& sqrt_inv_cov);\n\n} // namespace pwalk\n\n\n\n#endif // PWALK_UTIL_MATH_FUNTIONS_HPP_\n", "meta": {"hexsha": "74e9848671f7afac234eb06a0cbc1c5e91122d0c", "size": 662, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "polytopewalk/src/util/math_functions.hpp", "max_stars_repo_name": "yuachen/polytopewalk", "max_stars_repo_head_hexsha": "7e7431594489b5d5b6fe9947b4ccab21eee11152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-11-16T19:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T01:02:56.000Z", "max_issues_repo_path": "polytopewalk/src/util/math_functions.hpp", "max_issues_repo_name": "yuachen/polytopewalk", "max_issues_repo_head_hexsha": "7e7431594489b5d5b6fe9947b4ccab21eee11152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T11:15:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T11:15:29.000Z", "max_forks_repo_path": "polytopewalk/src/util/math_functions.hpp", "max_forks_repo_name": "yuachen/polytopewalk", "max_forks_repo_head_hexsha": "7e7431594489b5d5b6fe9947b4ccab21eee11152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-16T18:11:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-12T23:13:27.000Z", "avg_line_length": 28.7826086957, "max_line_length": 198, "alphanum_fraction": 0.7749244713, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5720293431843654}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n  Copyright (C) 2019 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include \"fdsabr.hpp\"\n#include \"utilities.hpp\"\n#include <ql/functional.hpp>\n#include <ql/instruments/vanillaoption.hpp>\n#include <ql/math/comparison.hpp>\n#include <ql/math/randomnumbers/rngtraits.hpp>\n#include <ql/math/randomnumbers/sobolbrownianbridgersg.hpp>\n#include <ql/math/richardsonextrapolation.hpp>\n#include <ql/math/statistics/generalstatistics.hpp>\n#include <ql/methods/finitedifferences/utilities/cevrndcalculator.hpp>\n#include <ql/pricingengines/vanilla/analyticcevengine.hpp>\n#include <ql/pricingengines/vanilla/fdsabrvanillaengine.hpp>\n#include <ql/processes/blackscholesprocess.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/volatility/sabr.hpp>\n#include <boost/make_shared.hpp>\n#include <utility>\n\nusing namespace QuantLib;\nusing boost::unit_test_framework::test_suite;\n\nnamespace {\n    class SabrMonteCarloPricer {\n      public:\n        SabrMonteCarloPricer(Real f0,\n                             Time maturity,\n                             ext::shared_ptr<Payoff> payoff,\n                             Real alpha,\n                             Real beta,\n                             Real nu,\n                             Real rho)\n        : f0_(f0), maturity_(maturity), payoff_(std::move(payoff)), alpha_(alpha), beta_(beta),\n          nu_(nu), rho_(rho) {}\n\n        Real operator()(Real dt) const {\n            const Size nSims = 64*1024;\n\n            const Real timeStepsPerYear = 1./dt;\n            const Size timeSteps = Size(maturity_*timeStepsPerYear+1e-8);\n\n            const Real sqrtDt = std::sqrt(dt);\n            const Real w = std::sqrt(1.0-rho_*rho_);\n\n            const Real logAlpha = std::log(alpha_);\n\n            SobolBrownianBridgeRsg rsg(2, timeSteps, SobolBrownianGenerator::Diagonal, 12345U);\n\n            GeneralStatistics stats;\n\n            for (Size i=0; i < nSims; ++i) {\n                Real f = f0_;\n                Real a = logAlpha;\n\n                const std::vector<Real> n = rsg.nextSequence().value;\n\n                for (Size j=0; j < timeSteps && f > 0.0; ++j) {\n\n                    const Real r1 = n[j];\n                    const Real r2 = rho_*r1 + n[j+timeSteps]*w;\n\n                    //Sample CEV distribution: accurate but slow\n                    //\n                    //const CEVRNDCalculator calc(f, std::exp(a), beta_);\n                    //const Real u = CumulativeNormalDistribution()(r1);\n                    //f = calc.invcdf(u, dt);\n\n                    // simple Euler method\n                    f += std::exp(a)*std::pow(f, beta_)*r1*sqrtDt;\n                    a += - 0.5*nu_*nu_*dt + nu_*r2*sqrtDt;\n                }\n                f = std::max(0.0, f);\n                stats.add((*payoff_)(f));\n            }\n\n            return stats.mean();\n        }\n\n      private:\n        const Real f0_;\n        const Time maturity_;\n        const ext::shared_ptr<Payoff> payoff_;\n        const Real alpha_, beta_, nu_, rho_;\n    };\n\n}\n\n\nvoid FdSabrTest::testFdmSabrOp() {\n    BOOST_TEST_MESSAGE(\"Testing FDM SABR operator...\");\n\n    SavedSettings backup;\n\n    const Date today = Date(22, February, 2018);\n    const DayCounter dc = Actual365Fixed();\n    Settings::instance().evaluationDate() = today;\n\n    const Date maturityDate = today + Period(2, Years);\n    const Time maturityTime = dc.yearFraction(today, maturityDate);\n\n    const Real strike = 1.5;\n\n    const ext::shared_ptr<Exercise> exercise =\n        ext::make_shared<EuropeanExercise>(maturityDate);\n\n    const ext::shared_ptr<PlainVanillaPayoff> putPayoff =\n        ext::make_shared<PlainVanillaPayoff>(Option::Put, strike);\n    const ext::shared_ptr<PlainVanillaPayoff> callPayoff =\n        ext::make_shared<PlainVanillaPayoff>(Option::Call, strike);\n\n    VanillaOption optionPut(putPayoff, exercise);\n    VanillaOption optionCall(callPayoff, exercise);\n\n    const Handle<YieldTermStructure> rTS =\n        Handle<YieldTermStructure>(flatRate(today, 0.0, dc));\n\n    const Real f0    = 1.0;\n    const Real alpha = 0.35;\n    const Real nu    = 1.0;\n    const Real rho   = 0.25;\n\n    const Real betas[] = { 0.25, 0.6 };\n\n    const ext::shared_ptr<GeneralizedBlackScholesProcess> bsProcess =\n        ext::make_shared<GeneralizedBlackScholesProcess>(\n            Handle<Quote>(ext::make_shared<SimpleQuote>(f0)),\n            rTS, rTS, Handle<BlackVolTermStructure>(flatVol(0.2, dc)));\n\n    for (double beta : betas) {\n\n        const ext::shared_ptr<PricingEngine> pdeEngine =\n            ext::make_shared<FdSabrVanillaEngine>(f0, alpha, beta, nu, rho, rTS, 100, 400, 100);\n\n        optionPut.setPricingEngine(pdeEngine);\n        const Real pdePut = optionPut.NPV();\n\n        // check put/call parity\n        optionCall.setPricingEngine(pdeEngine);\n        const Real pdeCall = optionCall.NPV();\n\n        const Real pdeFwd = pdeCall - pdePut;\n\n        const Real parityDiff = std::fabs(pdeFwd - (f0 - strike));\n        const Real parityTol = 1e-4;\n        if (parityDiff > parityTol) {\n            BOOST_ERROR(\n                \"failed to validate the call/put parity\"\n                << \"\\n    beta           : \" << beta\n                << \"\\n    strike         : \" << strike\n                << \"\\n    fwd (call/put) : \" << pdeFwd\n                << \"\\n    fwd (f0-strike): \" << f0-strike\n                << \"\\n    diff           : \" << parityDiff\n                << \"\\n    tol            : \" << parityTol);\n        }\n\n        const Real putPdeImplVol =\n            optionPut.impliedVolatility(optionPut.NPV(), bsProcess, 1e-6);\n\n        const ext::function<Real(Real)> mcSabr(\n            SabrMonteCarloPricer(f0, maturityTime, putPayoff,\n                                 alpha, beta, nu, rho));\n\n        const Real mcNPV = RichardsonExtrapolation(\n            mcSabr, 1/4.0)(4.0, 2.0);\n\n        const Real putMcImplVol =\n            optionPut.impliedVolatility(mcNPV, bsProcess, 1e-6);\n\n        const Real volDiff = std::fabs(putPdeImplVol - putMcImplVol);\n\n        const Real volTol = 5e-3;\n        if (volDiff > volTol) {\n            BOOST_ERROR(\n                \"failed to validate PDE against MC implied volatility\"\n                << \"\\n    beta         : \" << beta\n                << \"\\n    strike       : \" << strike\n                << \"\\n    PDE impl vol : \" << putPdeImplVol\n                << \"\\n    MC  impl vol : \" << putMcImplVol\n                << \"\\n    diff         : \" << volDiff\n                << \"\\n    tol          : \" << volTol);\n        }\n    }\n}\n\nvoid FdSabrTest::testFdmSabrCevPricing() {\n    BOOST_TEST_MESSAGE(\"Testing FDM CEV pricing with trivial SABR model...\");\n\n    SavedSettings backup;\n\n    const Date today = Date(3, January, 2019);\n    const DayCounter dc = Actual365Fixed();\n    Settings::instance().evaluationDate() = today;\n\n    const Date maturityDate = today + Period(12, Months);\n\n    const Real betas[]   = { 0.1, 0.9 };\n    const Real strikes[] = { 0.9, 1.5 };\n\n    const Real f0    = 1.2;\n    const Real alpha = 0.35;\n    const Real nu    = 1e-3;\n    const Real rho   = 0.25;\n\n    const Handle<YieldTermStructure> rTS = Handle<YieldTermStructure>(\n        flatRate(today, 0.05, dc));\n\n    const ext::shared_ptr<Exercise> exercise =\n        ext::make_shared<EuropeanExercise>(maturityDate);\n\n    const Option::Type optionTypes[] = {Option::Put, Option::Call};\n\n    const Real tol = 5e-5;\n\n    for (auto optionType : optionTypes) {\n        for (double strike : strikes) {\n            const ext::shared_ptr<PlainVanillaPayoff> payoff =\n                ext::make_shared<PlainVanillaPayoff>(optionType, strike);\n\n            VanillaOption option(payoff, exercise);\n\n            for (double beta : betas) {\n                option.setPricingEngine(ext::make_shared<FdSabrVanillaEngine>(\n                    f0, alpha, beta, nu, rho, rTS, 100, 400, 3));\n\n                const Real calculated = option.NPV();\n\n                option.setPricingEngine(ext::make_shared<AnalyticCEVEngine>(\n                    f0, alpha, beta, rTS));\n\n                const Real expected = option.NPV();\n\n                if (std::fabs(expected-calculated) > tol) {\n                    BOOST_ERROR(\n                        \"failed to calculate vanilla CEV option prices\"\n                        << \"\\n    beta            : \" << beta\n                        << \"\\n    strike          : \" << strike\n                        << \"\\n    option type     : \"\n                        << ((payoff->optionType() == Option::Call) ? \"Call\" : \"Put\")\n                        << \"\\n    analytic npv    : \" << expected\n                        << \"\\n    pde npv         : \" << calculated\n                        << \"\\n    npv difference  : \"\n                        << std::fabs(expected - calculated)\n                        << \"\\n    tolerance       : \" << tol);\n                }\n            }\n        }\n    }\n}\n\nvoid FdSabrTest::testFdmSabrVsVolApproximation() {\n    BOOST_TEST_MESSAGE(\"Testing FDM SABR vs approximations...\");\n\n    SavedSettings backup;\n\n    const Date today = Date(8, January, 2019);\n    const DayCounter dc = Actual365Fixed();\n    Settings::instance().evaluationDate() = today;\n\n    const Date maturityDate = today + Period(6, Months);\n    const Time maturityTime = dc.yearFraction(today, maturityDate);\n\n    const Handle<YieldTermStructure> rTS = Handle<YieldTermStructure>(\n        flatRate(today, 0.05, dc));\n\n    const Real f0 = 100;\n\n    const ext::shared_ptr<GeneralizedBlackScholesProcess> bsProcess =\n        ext::make_shared<GeneralizedBlackScholesProcess>(\n            Handle<Quote>(ext::make_shared<SimpleQuote>(f0)),\n            rTS, rTS, Handle<BlackVolTermStructure>(flatVol(0.2, dc)));\n\n    const Real alpha = 0.35;\n    const Real beta  = 0.85;\n    const Real nu    = 0.75;\n    const Real rho   = 0.85;\n\n    const Real strikes[] = { 90, 100, 110};\n    const Option::Type optionTypes[] = {Option::Put, Option::Call};\n\n    const Real tol = 2.5e-3;\n    for (auto optionType : optionTypes) {\n        for (double strike : strikes) {\n            VanillaOption option(ext::make_shared<PlainVanillaPayoff>(optionType, strike),\n                                 ext::make_shared<EuropeanExercise>(maturityDate));\n\n            option.setPricingEngine(ext::make_shared<FdSabrVanillaEngine>(\n                f0, alpha, beta, nu, rho, rTS, 25, 100, 50));\n\n            const Volatility fdmVol =\n                option.impliedVolatility(option.NPV(), bsProcess);\n\n            const Real hagenVol = sabrVolatility(\n                strike, f0, maturityTime, alpha, beta, nu, rho);\n\n            const Real diff = std::fabs(fdmVol - hagenVol);\n\n            if (std::fabs(fdmVol-hagenVol) > tol) {\n                BOOST_ERROR(\n                    \"large difference between Hagen formula and FDM\"\n                    << \"\\n    strike          : \" << strike\n                    << \"\\n    option type     : \"\n                    << ((optionType == Option::Call) ? \"Call\" : \"Put\")\n                    << \"\\n    Hagen vol       : \" << hagenVol\n                    << \"\\n    pde vol         : \" << fdmVol\n                    << \"\\n    vol difference  : \" << diff\n                    << \"\\n    tolerance       : \" << tol);\n            }\n        }\n    }\n}\n\n\nnamespace {\n    /*\n     * Example and reference values are taken from\n     * B. Chen, C.W. Oosterlee, H. Weide,\n     * Efficient unbiased simulation scheme for the SABR stochastic volatility model.\n     * https://http://ta.twi.tudelft.nl/mf/users/oosterle/oosterlee/SABRMC.pdf\n     */\n\n    class OsterleeReferenceResults {\n      public:\n        explicit OsterleeReferenceResults(Size i) : i_(i) { }\n\n        Real operator()(Real t) const {\n            Size i;\n            if (close_enough(t, 1/16.))\n                i = 0;\n            else if (close_enough(t, 1/32.))\n                i = 1;\n            else\n                QL_FAIL(\"unmatched reference result lookup\");\n\n            return data_[i_][i];\n        }\n\n      private:\n        const Size i_;\n        static Real data_[9][3];\n    };\n\n    Real OsterleeReferenceResults::data_[9][3] = {\n        { 0.0610, 0.0604 }, { 0.0468, 0.0463 }, { 0.0347, 0.0343 },\n        { 0.0632, 0.0625 }, { 0.0512, 0.0506 }, { 0.0406, 0.0400 },\n        { 0.0635, 0.0630 }, { 0.0523, 0.0520 }, { 0.0422, 0.0421 }\n    };\n}\n\nvoid FdSabrTest::testOosterleeTestCaseIV() {\n    BOOST_TEST_MESSAGE(\"Testing Chen, Oosterlee and Weide test case IV...\");\n\n    SavedSettings backup;\n\n    const Date today = Date(8, January, 2019);\n    const DayCounter dc = Actual365Fixed();\n    Settings::instance().evaluationDate() = today;\n\n    const Handle<YieldTermStructure> rTS =\n        Handle<YieldTermStructure>(flatRate(today, 0.0, dc));\n\n    const Real f0    =  0.07;\n    const Real alpha =  0.4;\n    const Real nu    =  0.8;\n    const Real beta  =  0.4;\n    const Real rho   = -0.6;\n\n    const Period maturities[] = {\n        Period(2, Years), Period(5, Years), Period(10, Years)\n    };\n\n    const Real strikes[] = { 0.4*f0, f0, 1.6*f0 };\n\n    const Real tol = 0.00035;\n    for (Size i=0; i < LENGTH(maturities); ++i) {\n        const Date maturityDate = today + maturities[i];\n        const Time maturityTime = dc.yearFraction(today, maturityDate);\n\n        const Size timeSteps = Size(5*maturityTime);\n\n        const ext::shared_ptr<PricingEngine> engine =\n            ext::make_shared<FdSabrVanillaEngine>(\n                f0, alpha, beta, nu, rho, rTS, timeSteps, 200, 21);\n\n        const ext::shared_ptr<Exercise> exercise =\n            ext::make_shared<EuropeanExercise>(maturityDate);\n\n        for (Size j=0; j < LENGTH(strikes); ++j) {\n            const ext::shared_ptr<StrikedTypePayoff> payoff =\n                ext::make_shared<PlainVanillaPayoff>(Option::Call, strikes[j]);\n\n            VanillaOption option(payoff, exercise);\n            option.setPricingEngine(engine);\n\n            const Real calculated = option.NPV();\n\n            const OsterleeReferenceResults referenceResuts(i*3+j);\n\n            const Real expected = RichardsonExtrapolation(\n                ext::function<Real(Real)>(referenceResuts), 1/16., 1)(2.);\n\n            const Real diff = std::fabs(calculated - expected);\n            if (diff > tol) {\n                BOOST_ERROR(\n                    \"can not reproduce reference values from Monte-Carlo\"\n                    << \"\\n    strike     : \" << payoff->strike()\n                    << \"\\n    maturity   : \" << maturityDate\n                    << \"\\n    reference  : \" << expected\n                    << \"\\n    calculated : \" << calculated\n                    << \"\\n    difference : \" << diff\n                    << \"\\n    tolerance  : \" << tol);\n            }\n        }\n    }\n}\n\nvoid FdSabrTest::testBenchOpSabrCase() {\n    BOOST_TEST_MESSAGE(\"Testing SABR BenchOp problem...\");\n\n    /*\n     * von Sydow, L, Milovanovi\u0107, S, Larsson, E, In't Hout, K,\n     * Wiktorsson, M, Oosterlee, C.W, Shcherbakov, V, Wyns, M,\n     * Leitao Rodriguez, A, Jain, S, et al. (2018)\n     * BENCHOP\u2013SLV: the BENCHmarking project in Option\n     * Pricing\u2013Stochastic and Local Volatility problems\n     * https://ir.cwi.nl/pub/28249\n     */\n\n    SavedSettings backup;\n\n    const Date today = Date(8, January, 2019);\n    const DayCounter dc = Actual365Fixed();\n    Settings::instance().evaluationDate() = today;\n\n    const Handle<YieldTermStructure> rTS =\n        Handle<YieldTermStructure>(flatRate(today, 0.0, dc));\n\n    const Size maturityInYears[] = { 2, 10 };\n\n    const Real f0s[]    = { 0.5, 0.07 };\n    const Real alphas[] = { 0.5, 0.4 };\n    const Real nus[]    = { 0.4, 0.8 };\n    const Real betas[]  = { 0.5, 0.5 };\n    const Real rhos[]   = { 0.0, -0.6 };\n\n    const Real expected[2][3] = {\n        { 0.221383196830866, 0.193836689413803, 0.166240814653231 },\n        { 0.052450313614407, 0.046585753491306, 0.039291470612989 }\n    };\n\n    const Size gridX = 400;\n    const Size gridY = 25;\n    const Size gridT = 10;\n\n    const Real factor = 2;\n\n    const Real tol = 2e-4;\n\n    for (Size i=0; i < LENGTH(f0s); ++i) {\n\n        const Date maturity = today + Period(maturityInYears[i]*365, Days);\n        const Time T = dc.yearFraction(today, maturity);\n\n        const Real f0    = f0s[i];\n        const Real alpha = alphas[i];\n        const Real nu    = nus[i];\n        const Real beta  = betas[i];\n        const Real rho   = rhos[i];\n\n        const Real strikes[] = {\n            f0*std::exp(-0.1*std::sqrt(T)), f0, f0*std::exp(0.1*std::sqrt(T))\n        };\n\n        for (Size j=0; j < LENGTH(strikes); ++j) {\n            const Real strike = strikes[j];\n\n            VanillaOption option(\n                ext::make_shared<PlainVanillaPayoff>(Option::Call, strike),\n                ext::make_shared<EuropeanExercise>(maturity));\n\n            option.setPricingEngine(ext::make_shared<FdSabrVanillaEngine>(\n                    f0, alpha, beta, nu, rho, rTS,\n                    Size(gridT*factor),\n                    Size(gridX*factor),\n                    Size(gridY*std::sqrt(factor))));\n\n            const Real calculated = option.NPV();\n            const Real diff = std::fabs(calculated - expected[i][j]);\n\n            if (diff > tol) {\n                BOOST_ERROR(\n                    \"failed to reproduce reference values\"\n                    << \"\\n    strike     : \" << strike\n                    << \"\\n    maturity   : \" << maturity\n                    << \"\\n    reference  : \" << expected[i][j]\n                    << \"\\n    calculated : \" << calculated\n                    << \"\\n    difference : \" << diff\n                    << \"\\n    tolerance  : \" << tol);\n            }\n        }\n    }\n}\n\ntest_suite* FdSabrTest::suite(SpeedLevel speed) {\n    auto* suite = BOOST_TEST_SUITE(\"Finite Difference SABR tests\");\n\n    suite->add(QUANTLIB_TEST_CASE(&FdSabrTest::testFdmSabrCevPricing));\n    suite->add(QUANTLIB_TEST_CASE(&FdSabrTest::testFdmSabrVsVolApproximation));\n    suite->add(QUANTLIB_TEST_CASE(&FdSabrTest::testOosterleeTestCaseIV));\n    suite->add(QUANTLIB_TEST_CASE(&FdSabrTest::testBenchOpSabrCase));\n\n    if (speed <= Fast) {\n        suite->add(QUANTLIB_TEST_CASE(&FdSabrTest::testFdmSabrOp));\n    }\n\n    return suite;\n}\n", "meta": {"hexsha": "883bbba493488b204e1e5e65fe04be7b89306739", "size": 18802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/fdsabr.cpp", "max_stars_repo_name": "jiangjiali/QuantLib", "max_stars_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3358.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T02:56:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:42:47.000Z", "max_issues_repo_path": "test-suite/fdsabr.cpp", "max_issues_repo_name": "jiangjiali/QuantLib", "max_issues_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 965.0, "max_issues_repo_issues_event_min_datetime": "2015-12-21T10:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T02:47:00.000Z", "max_forks_repo_path": "test-suite/fdsabr.cpp", "max_forks_repo_name": "jiangjiali/QuantLib", "max_forks_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1663.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T17:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:58:29.000Z", "avg_line_length": 35.1439252336, "max_line_length": 96, "alphanum_fraction": 0.5582916711, "num_tokens": 4986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5720293374803507}}
{"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": "// Component\n#include \"ForwardSimHelper.hpp\"\n\n// Ros\n#include <tf/tf.h>\n#include <tf/transform_datatypes.h>\n\n// Libraries\n#include <boost/cstdfloat.hpp>\n#include <boost/shared_ptr.hpp>\n\n// Standard\n#include <utility>\n\nnamespace cm\n{\n\nusing float64_t = boost::float64_t; ///< Alias for 64 bit float\n\nnav_msgs::Odometry::ConstPtr ForwardSimHelper::forwardSimPose(const nav_msgs::Odometry::ConstPtr& pose, const ros::Time& now_s)\n{\n    const ros::Duration dt_s = pose->header.stamp - now_s;\n\n    nav_msgs::Odometry new_pose = *pose;\n\n    const float64_t x_mps = pose->twist.twist.linear.x;\n    const float64_t y_mps = pose->twist.twist.linear.y;\n    const float64_t z_mps = pose->twist.twist.linear.z;\n\n    new_pose.pose.pose.position.x = pose->pose.pose.position.x + x_mps*dt_s.toSec();\n    new_pose.pose.pose.position.y = pose->pose.pose.position.y + y_mps*dt_s.toSec();\n    new_pose.pose.pose.position.z = pose->pose.pose.position.z + z_mps*dt_s.toSec();\n\n    tf::Quaternion q;\n    tf::quaternionMsgToTF(pose->pose.pose.orientation, q);\n    float64_t roll_r, pitch_r, yaw_r;\n    tf::Matrix3x3(std::move(q)).getRPY(roll_r, pitch_r, yaw_r);\n\n    roll_r  += pose->twist.twist.angular.x*dt_s.toSec();\n    pitch_r += pose->twist.twist.angular.y*dt_s.toSec();\n    yaw_r   += pose->twist.twist.angular.z*dt_s.toSec();  \n\n    new_pose.twist.twist.linear.x =  x_mps*std::cos(yaw_r) + y_mps*std::sin(yaw_r);        \n    new_pose.twist.twist.linear.y = -x_mps*std::sin(yaw_r) + y_mps*std::cos(yaw_r);\n        \n    geometry_msgs::Quaternion new_q;\n    tf::quaternionTFToMsg(tf::createQuaternionFromRPY(roll_r, pitch_r, yaw_r), new_q);\n    new_pose.pose.pose.orientation = new_q;\n\n    return boost::make_shared<nav_msgs::Odometry>(new_pose);\n}\n\n} // namespace cm", "meta": {"hexsha": "21570b615ae7279dbf36d4ab597780bd03bd398b", "size": 1749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/costmap/src/types/helper/ForwardSimHelper.cpp", "max_stars_repo_name": "WPI-Capstone-Project-Team-1-2020/Capstone-Final-Mile", "max_stars_repo_head_hexsha": "60cf6be95305ec720f001bf18327ae881168443c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/costmap/src/types/helper/ForwardSimHelper.cpp", "max_issues_repo_name": "WPI-Capstone-Project-Team-1-2020/Capstone-Final-Mile", "max_issues_repo_head_hexsha": "60cf6be95305ec720f001bf18327ae881168443c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/costmap/src/types/helper/ForwardSimHelper.cpp", "max_forks_repo_name": "WPI-Capstone-Project-Team-1-2020/Capstone-Final-Mile", "max_forks_repo_head_hexsha": "60cf6be95305ec720f001bf18327ae881168443c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0, "max_line_length": 127, "alphanum_fraction": 0.6992567181, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5720238905946395}}
{"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": "//! [reduc]\n#include <boost/simd/constant/zero.hpp>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\n#include <boost/simd/meta/cardinal_of.hpp>\n#include <boost/simd/pack.hpp>\n//! [reduc-inc]\n#include <boost/simd/function/sum.hpp>\n//! [reduc-inc]\n\nint main()\n{\n  //! [reduc-simd-types]\n  namespace bs = boost::simd;\n  using pack_t = bs::pack<int32_t>;\n\n  constexpr std::size_t size = 64;\n  std::int32_t card_int      = bs::cardinal_of<pack_t>();\n\n  std::vector<int32_t> array(size);\n  std::iota(array.begin(), array.end(), 0);\n  //! [reduc-simd-types]\n\n  //! [reduc-scalar]\n  // Scalar version\n  int32_t sum = 0;\n  for (size_t i = 0; i < size; ++i) {\n    sum += array[i];\n  }\n  //! [reduc-scalar]\n  std::cout << \"Scalar sum for size \" << size << \" is \" << sum << std::endl;\n\n  //! [reduc-simd-l]\n  sum = 0;\n  bs::pack<int32_t, size> array_pack(array.data());\n  sum = bs::sum(array_pack);\n  //! [reduc-simd-l]\n  std::cout << \"SIMD sum 1 for size \" << size << \" is \" << sum << std::endl;\n\n  //! [reduc-simd-o]\n  sum = 0;\n  pack_t sum_p{0};\n  for (size_t i = 0; i < size; i += card_int) {\n    sum_p += pack_t(array.data() + i);\n  }\n  sum = bs::sum(sum_p);\n  //! [reduc-simd-o]\n  std::cout << \"SIMD sum 2 for size \" << size << \" is \" << sum << std::endl;\n\n  //! [reduc-simd-r]\n  // The input data is an arbitrary size\n  size_t newsize = size + 13;\n  array.resize(newsize);\n  std::iota(array.begin(), array.end(), 0);\n\n  sum_p    = bs::Zero<pack_t>();\n  size_t i = 0;\n  for (; i + card_int <= newsize; i += card_int) {\n    sum_p += pack_t(array.data() + i);\n  }\n  sum = bs::sum(sum_p);\n  for (; i < newsize; ++i) {\n    sum += array[i];\n  }\n  //! [reduc-simd-r]\n\n  std::cout << \"SIMD sum 3 for size \" << newsize << \" is \" << sum << std::endl;\n\n  return 0;\n}\n//! [reduc-compile]\n// This code can be compiled using (for instance for gcc)\n// g++ reduction.cpp -msse4.2 -std=c++11 -O3 -DNDEBUG -o reduction\n// -I/path_to/boost_simd/ -I/path_to/boost/\n//! [reduc-compile]\n//! [reduc]\n", "meta": {"hexsha": "ed27c062ce015e12c889ca412a0f65f3e78f1fd4", "size": 1981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/reduction.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/reduction.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/reduction.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": 25.0759493671, "max_line_length": 79, "alphanum_fraction": 0.5790005048, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.5720188553464319}}
{"text": "///////////////////////////////////////////////////////////////\r\n//  Copyright 2012 John Maddock. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\r\n\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n\r\nusing namespace boost::multiprecision;\r\n\r\nnumber<cpp_int_backend<> > a;\r\nnumber<cpp_int_backend<>, et_off> b;\r\nnumber<cpp_int_backend<64, 64, signed_magnitude, checked, void>, et_off> c;\r\nnumber<cpp_int_backend<128, 128, signed_magnitude, checked, void>, et_off> d;\r\nnumber<cpp_int_backend<500, 500, signed_magnitude, checked, void>, et_off> e;\r\n\r\n\r\n", "meta": {"hexsha": "8d6d55fc2a1e85947307345b77cab95a251eac81", "size": 649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/test/include_test/cpp_int_include_test.cpp", "max_stars_repo_name": "Abce/boost", "max_stars_repo_head_hexsha": "2d7491a27211aa5defab113f8e2d657c3d85ca93", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/multiprecision/test/include_test/cpp_int_include_test.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/multiprecision/test/include_test/cpp_int_include_test.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": 38.1764705882, "max_line_length": 78, "alphanum_fraction": 0.6748844376, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.5720188550519171}}
{"text": "#include \"spdlog/spdlog.h\"\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <limits>\n#include <mimkl/data_structures.hpp>\n#include <mimkl/definitions.hpp>\n#include <mimkl/io.hpp>\n#include <mimkl/kernels.hpp>\n#include <mimkl/linear_algebra.hpp>\n#include <mimkl/models/easy_mkl.hpp>\n#include <mimkl/solvers/komd.hpp>\n#include <mimkl/utilities.hpp>\n#include <numeric>\n#include <spdlog/fmt/ostr.h>\n#include <utility>\n\nusing dlib::mat;\nusing mimkl::data_structures::DataFrame;\nusing mimkl::data_structures::indexing_from_vector;\nusing mimkl::data_structures::range;\nusing mimkl::definitions::Indexing;\nusing mimkl::utilities::check_invocable;\nusing mimkl::utilities::print_type;\n\n//#define SPDLOG_DEBUG_ON\n//#define SPDLOG_TRACE_ON\n\n// Compile time log levels\n// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON\n// SPDLOG_TRACE(console, \"Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}\",\n// 1, 3.23);  SPDLOG_DEBUG(console, \"Enabled only #ifdef SPDLOG_DEBUG_ON.. {}\n// ,{}\", 1, 3.23);\n\nint main(int argc, char **argv)\n{\n\n    // Runtime log levels\n    spdlog::set_level(spdlog::level::trace); // Set global log level to info\n    auto console = spdlog::stdout_color_mt(\"console\");\n\n    const Index rows = 4; // 3 to reproduce single member in class  error\n    const Index dims = 2;\n\n    MATRIX(double) X(rows, 2);\n    //\tX << 1., 1., 3., 1., 1., 2.;\n    X << 1., 1., 3., 1., 1., 4., 3., 2.;\n    console->info(\"X\\n{}\", X);\n\n    std::vector<std::string> labels;\n    labels.reserve(rows);\n    labels.push_back(\"a\");\n    labels.push_back(\"b\");\n    labels.push_back(\"a\");\n    labels.push_back(\"b\");\n\n    Eigen::SparseMatrix<double> L(dims, dims);\n    mimkl::linear_algebra::fill_sparse_diagonal(L, 1.0);\n\n    Eigen::SparseMatrix<double> L1(dims, dims);\n    typedef Eigen::Triplet<double> TripletDouble; // (row,col,coef)\n    std::vector<TripletDouble> triplet_list;\n    triplet_list.reserve(4);\n    triplet_list.push_back(TripletDouble(0, 1, 1.));\n    //  triplet_list.push_back(TripletDouble(1, 2, 1.));\n    triplet_list.push_back(TripletDouble(1, 0, 1.));\n    //  triplet_list.push_back(TripletDouble(2, 1, 1.));\n    L1.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n    MATRIX(double)\n    K_ref0 = mimkl::induction::induce_linear_kernel<MATRIX(double)>(X, X, L);\n    console->info(\"a kernel:\\n{}\", K_ref0);\n    //\n    MATRIX(double)\n    K_ref1 =\n    mimkl::induction::induce_polynomial_kernel<MATRIX(double)>(X, X, L1, 1, 0);\n    console->info(\"another kernel:\\n{}\", K_ref1);\n\n    std::vector<Eigen::SparseMatrix<double>> inducer_vec;\n    inducer_vec.reserve(2);\n    inducer_vec.push_back(L);\n    inducer_vec.push_back(L1);\n\n    typedef std::function<MATRIX(double)(const MATRIX(double) &, const MATRIX(double) &,\n                                         const Eigen::SparseMatrix<double>)>\n    InducerFunction;\n    typedef std::function<MATRIX(double)(const MATRIX(double) &,\n                                         const MATRIX(double) &)>\n    InducedFunction;\n\n    const double degree = 1.;\n    const double offset = 0.;\n\n    InducerFunction k_poly =\n    [degree, offset](const MATRIX(double) & lhs, const MATRIX(double) & rhs,\n                     const Eigen::SparseMatrix<double> inducer) {\n        return mimkl::induction::induce_polynomial_kernel<MATRIX(double)>(\n        lhs, rhs, inducer, degree, offset);\n    };\n\n    MATRIX(double) K(rows, rows);\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\",\n                  print_type<decltype(k_poly(X, X, L))>());\n    console->info(\"decltype argument evaluated? (no):\\n{}\", K);\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\", print_type(k_poly));\n    console->info(\"check_invocable? {}\", check_invocable(k_poly));\n\n    std::vector<InducedFunction> function_vec =\n    mimkl::induction::inducer_combination(k_poly, inducer_vec);\n\n    MATRIX(double) K2 = function_vec[0](X, X);\n    console->info(\"a kernel from function:\\n{}\", K2);\n\n    MATRIX(double) K3 = function_vec[1](X, X);\n    console->info(\"another kernel from function:\\n{}\", K3);\n\n    assert(((K_ref0 - K2).norm() == 0) && \"Identity Inducer\");\n    assert(((K_ref1 - K3).norm() == 0) && \"non-identity Inducer\");\n\n    console->info(\"\\e[1;35m not callable\"); //-----------\n    console->info(\"int is not invocable! {}\",\n                  mimkl::utilities::is_invocable<int>::value);\n\n    console->info(\"\\e[1;35m function pointer\"); //-----------\n    // lambda to function pointer only without any captures\n    void (*foo)(int) = [](int a) {};\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\", print_type(foo));\n    console->info(\"function pointer check_invocable?: {}\", check_invocable(foo));\n    console->info(\"function pointer is_function_t?: {}\",\n                  mimkl::utilities::is_function_t<decltype(foo)>::value);\n\n    std::function<void(int)> bar = foo;\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\", print_type(bar));\n    console->info(\"function pointer cast to std::function invocable?: {}\",\n                  check_invocable(bar));\n\n    console->info(\"\\e[1;35m lambdas\"); //-----------\n    auto lam = []() {};\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\", print_type(lam));\n    console->info(\"is lambda invocable? {}\",\n                  mimkl::utilities::is_invocable<decltype(lam)>::value);\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\", print_type([]() {}));\n    console->info(\"check_invocable? {}\", check_invocable([]() {}));\n\n    console->info(\"\\e[1;35m function object\"); //-----------\n    struct FunctionObject\n    {\n        int operator()(int a) { return a; };\n    };\n    FunctionObject fo;\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\", print_type(fo));\n    console->info(\"is invocable? {}\",\n                  mimkl::utilities::is_invocable<FunctionObject>::value);\n    console->info(\"check invocable {}\", check_invocable(fo));\n\n    console->info(\"\\e[1;35m std::function<>\"); //-----------\n    //  console->info(\"\\e[1;32mtype: \\e[0m \\n{}\",\n    //  print_type<mimkl::induction::induce_polynomial_kernel>());\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\",\n                  print_type<std::function<void(int)>>());\n    console->info(\"is invocable? {}\",\n                  mimkl::utilities::is_invocable<std::function<void(int)>>::value);\n\n    console->info(\"\\e[1;35m function_vec element\"); //-----------\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\", print_type(function_vec[0]));\n    console->info(\"element check_invocable {}\", check_invocable(function_vec[0]));\n    console->info(\"element is invocable? {}\",\n                  mimkl::utilities::is_invocable<decltype(function_vec[0])>::value);\n    console->info(\"element is_function? {}\",\n                  std::is_function<decltype(function_vec[0])>::value);\n    console->info(\"is_function_t ? {}\",\n                  mimkl::utilities::is_function_t<decltype(function_vec[0])>::value);\n    //  console->info(\"is invocable?\n    //  {}\",mimkl::utilities::is_invocable<decltype(mimkl::induction::inducer_combination)>::value);\n\n    console->info(\"\\e[1;35m function_vec::value_type\"); //-----------\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\", print_type(function_vec));\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\",\n                  print_type<decltype(function_vec)::value_type>());\n    console->info(\"is vector type std::function? {}\",\n                  std::is_function<decltype(function_vec)::value_type>::value);\n    console->info(\n    \"is vector type invocable? {}\",\n    mimkl::utilities::is_invocable<decltype(function_vec)::value_type>::value);\n\n    console->info(\"\\e[1;35m Eigen::Matrix\"); //-----------\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\", print_type(K2));\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\", print_type<MATRIX(double)>());\n    console->info(\"is std::function? {}\", std::is_function<decltype(K2)>::value);\n    console->info(\"is invocable? {}\",\n                  mimkl::utilities::is_invocable<decltype(K2)>::value);\n    console->info(\"check_invocable {}\", check_invocable(K2));\n\n    console->info(\n    \"\\e[1;35m checkout move semantics of Eigen\"); //-----------checkout move\n    // semantics\n    std::function<MATRIX(double)()> spaghetti_monster = [console]() {\n        MATRIX(double) B = MATRIX(double)::Constant(3, 3, 42);\n        auto B_ptr = (void *)B.data();\n        console->info(\"pointer to B {}\", B_ptr);\n        return B;\n    };\n    std::function<MATRIX(double)()> illuminati = [console]() {\n        return MATRIX(double)::Constant(3, 3, 1) +\n               MATRIX(double)::Constant(3, 3, 22);\n    };\n\n    MATRIX(double) A = 10 * MATRIX(double)::Random(3, 3);\n    console->info(\"A {}\", A);\n    console->info(\"type of A.data():  {}\", print_type(A.data()));\n    console->info(\"type of (void *)A.data():  {}\", print_type((void *)A.data()));\n    auto A_ptr = (void *)A.data();\n    console->info(\"pointer to A {}\", A_ptr);\n\n    A = spaghetti_monster();\n    console->info(\"nooo, the spaghetti_monster!\");\n    auto C_ptr = (void *)A.data();\n    console->info(\"pointer to A, is B? {}\", C_ptr);\n\n    double *A1_ptr = A.data();\n    console->info(\"pointer to A (same, eh) {}\", (void *)A1_ptr);\n    MATRIX(double) D;\n    D = std::move(A);\n    double *D_ptr = D.data();\n    console->info(\"pointer to D, is moved A? {}\", (void *)D_ptr);\n    console->info(\"D \\n{}\", D);\n\n    D = illuminati();\n    console->info(\"nooo, the illuminati!\");\n    double *E_ptr = D.data();\n    console->info(\"pointer to D, is prolly pointer to temporary of evalueted \"\n                  \"expression?{}\",\n                  (void *)E_ptr);\n    console->info(\"E \\n{}\", D);\n}\n", "meta": {"hexsha": "bc0c27c1d607a4e29f5a02fda04053f6c9f10598", "size": 9435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/kernel_lambdas/main.cpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "test/kernel_lambdas/main.cpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "test/kernel_lambdas/main.cpp", "max_forks_repo_name": "vishalbelsare/mimkl", "max_forks_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:40:27.000Z", "avg_line_length": 40.1489361702, "max_line_length": 100, "alphanum_fraction": 0.6109167992, "num_tokens": 2667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5719159289758922}}
{"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// \u672c\u6559\u7a0b\u7684\u5305\u542b\u6587\u4ef6\u4e0e  step-6  \u4e2d\u7684\u57fa\u672c\u76f8\u540c\u3002\u91cd\u8981\u7684\u662f\uff0c\u6211\u4eec\u5c06\u4f7f\u7528\u7684TransfiniteInterpolationManifold\u7c7b\u662f\u7531`deal.II/grid/manifold_lib.h`\u63d0\u4f9b\u3002\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// \u552f\u4e00\u7684\u65b0include\u6587\u4ef6\u662fMappingQCache\u7c7b\u7684\u6587\u4ef6\u3002\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// \u5728\u8fd9\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u8981\u89e3\u51b3\u6cca\u677e\u65b9\u7a0b\uff0c\u5176\u7cfb\u6570\u6cbf\u534a\u5f84\u4e3a0.5\u7684\u7403\u4f53\u8df3\u8dc3\uff0c\u5e76\u4f7f\u7528\u4e00\u4e2a\u6052\u5b9a\u7684\u53f3\u624b\u8fb9\u503c $f(\\mathbf{x}) = -3$  \u3002\uff08\u8fd9\u4e2a\u8bbe\u7f6e\u4e0e step-5 \u548c step-6 \u76f8\u4f3c\uff0c\u4f46\u7cfb\u6570\u548c\u53f3\u624b\u8fb9\u7684\u5177\u4f53\u6570\u503c\u4e0d\u540c\uff09\u3002\u7531\u4e8e\u7cfb\u6570\u7684\u8df3\u8dc3\uff0c\u5206\u6790\u89e3\u5fc5\u987b\u6709\u4e00\u4e2a\u7ed3\u70b9\uff0c\u5373\u7cfb\u6570\u4ece\u4e00\u4e2a\u503c\u5207\u6362\u5230\u53e6\u4e00\u4e2a\u503c\u3002\u4e3a\u4e86\u4fdd\u6301\u7b80\u5355\uff0c\u6211\u4eec\u9009\u62e9\u4e86\u4e00\u4e2a\u5728\u6240\u6709\u5206\u91cf\u4e2d\u90fd\u662f\u4e8c\u6b21\u7684\u5206\u6790\u89e3\uff0c\u5373\u5728\u534a\u5f84\u4e3a0.5\u7684\u7403\u4e2d\u4e3a $u(x,y,z) = x^2 + y^2 + z^2$ \uff0c\u5728\u57df\u7684\u5916\u90e8\u4e3a $u(x,y,z) = 0.1(x^2 + y^2 + z^2) + 0.25-0.025$ \u3002\u8fd9\u4e2a\u5206\u6790\u89e3\u5728\u5185\u7403\u7684\u7cfb\u6570\u4e3a0.5\uff0c\u5916\u7403\u7684\u7cfb\u6570\u4e3a5\u7684\u60c5\u51b5\u4e0b\u4e0e\u53f3\u624b\u8fb9\u517c\u5bb9\u3002\u5b83\u4e5f\u662f\u6cbf\u7740\u534a\u5f84\u4e3a0.5\u7684\u5706\u8fde\u7eed\u7684\u3002\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// \u6cca\u677e\u95ee\u9898\u7684\u5b9e\u73b0\u4e0e\u6211\u4eec\u5728  step-5  \u6559\u7a0b\u4e2d\u4f7f\u7528\u7684\u975e\u5e38\u76f8\u4f3c\u3002\u4e24\u4e2a\u4e3b\u8981\u7684\u533a\u522b\u662f\uff0c\u6211\u4eec\u5411\u7a0b\u5e8f\u4e2d\u7684\u5404\u4e2a\u6b65\u9aa4\u4f20\u9012\u4e86\u4e00\u4e2a\u6620\u5c04\u5bf9\u8c61\uff0c\u4ee5\u4fbf\u5728\u4e24\u79cd\u6620\u5c04\u8868\u793a\u6cd5\u4e4b\u95f4\u8fdb\u884c\u5207\u6362\uff0c\u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u89e3\u91ca\u7684\u90a3\u6837\uff0c\u8fd8\u6709\u4e00\u4e2a`\u8ba1\u65f6\u5668'\u5bf9\u8c61\uff08TimerOutput\u7c7b\u578b\uff09\uff0c\u5c06\u7528\u4e8e\u6d4b\u91cf\u5404\u79cd\u60c5\u51b5\u4e0b\u7684\u8fd0\u884c\u65f6\u95f4\u3002(\u6620\u5c04\u5bf9\u8c61\u7684\u6982\u5ff5\u5728 step-10 \u548c step-11 \u4e2d\u9996\u6b21\u63d0\u51fa\uff0c\u5982\u679c\u4f60\u60f3\u67e5\u4e00\u4e0b\u8fd9\u4e9b\u7c7b\u7684\u7528\u9014\u7684\u8bdd)\u3002\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// \u5728\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u8bbe\u7f6e\u4e86\u5b9a\u65f6\u5668\u5bf9\u8c61\u6765\u8bb0\u5f55\u5899\u7684\u65f6\u95f4\uff0c\u4f46\u5728\u6b63\u5e38\u6267\u884c\u8fc7\u7a0b\u4e2d\u662f\u5b89\u9759\u7684\u3002\u6211\u4eec\u5c06\u5728 `PoissonProblem::run()` \u51fd\u6570\u4e2d\u67e5\u8be2\u5b83\u7684\u8ba1\u65f6\u7ec6\u8282\u3002\u6b64\u5916\uff0c\u6211\u4eec\u4e3a\u6b63\u5728\u4f7f\u7528\u7684\u6709\u9650\u5143\u9009\u62e9\u4e86\u4e00\u4e2a\u76f8\u5bf9\u8f83\u9ad8\u7684\u591a\u9879\u5f0f\u4e09\u5ea6\u3002\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// \u63a5\u4e0b\u6765\u7684\u51fd\u6570\u4ecb\u7ecd\u4e86TransfiniteInterpolationManifold\u7684\u5178\u578b\u7528\u6cd5\u3002\u7b2c\u4e00\u6b65\u662f\u521b\u5efa\u6240\u9700\u7684\u7f51\u683c\uff0c\u8fd9\u53ef\u4ee5\u901a\u8fc7GridGenerator\u7684\u4e24\u4e2a\u7f51\u683c\u7684\u7ec4\u5408\u6765\u5b8c\u6210\u3002\u5185\u7403\u7f51\u683c\u662f\u5f88\u7b80\u5355\u7684\u3002\u6211\u4eec\u4ee5\u539f\u70b9\u4e3a\u4e2d\u5fc3\u8fd0\u884c GridGenerator::hyper_cube() \uff0c\u534a\u5f84\u4e3a0.5\uff08\u7b2c\u4e09\u4e2a\u51fd\u6570\u53c2\u6570\uff09\u3002\u7b2c\u4e8c\u4e2a\u7f51\u683c\u66f4\u6709\u8da3\uff0c\u6784\u5efa\u65b9\u6cd5\u5982\u4e0b\u3002\u6211\u4eec\u5e0c\u671b\u6709\u4e00\u4e2a\u5728\u5185\u90e8\u662f\u7403\u5f62\u7684\uff0c\u4f46\u5728\u5916\u8868\u9762\u662f\u5e73\u7684\u7f51\u683c\u3002\u6b64\u5916\uff0c\u5185\u7403\u7684\u7f51\u683c\u62d3\u6251\u7ed3\u6784\u5e94\u8be5\u4e0e\u5916\u7403\u7684\u7f51\u683c\u517c\u5bb9\uff0c\u5373\u5b83\u4eec\u7684\u9876\u70b9\u91cd\u5408\uff0c\u8fd9\u6837\u624d\u80fd\u4f7f\u4e24\u4e2a\u7f51\u683c\u5408\u5e76\u8d77\u6765\u3002\u4ece GridGenerator::hyper_shell \u51fa\u6765\u7684\u7f51\u683c\u6ee1\u8db3\u4e86\u5185\u4fa7\u7684\u8981\u6c42\uff0c\u5982\u679c\u5b83\u662f\u7528 $2d$ \u7684\u7c97\u5927\u5355\u5143\u521b\u5efa\u7684\uff08\u57283D\u4e2d\u6211\u4eec\u5c06\u4f7f\u75286\u4e2a\u7c97\u5927\u5355\u5143\uff09&ndash\uff1b\u8fd9\u4e0e\u7403\u7684\u8fb9\u754c\u9762\u7684\u5355\u5143\u6570\u91cf\u76f8\u540c\u3002\u5bf9\u4e8e\u5916\u8868\u9762\uff0c\u6211\u4eec\u5229\u7528\u8fd9\u6837\u4e00\u4e2a\u4e8b\u5b9e\uff1a\u6ca1\u6709\u6d41\u5f62\u9644\u7740\u7684\u58f3\u8868\u9762\u76846\u4e2a\u9762\u5c06\u9000\u5316\u4e3a\u7acb\u65b9\u4f53\u7684\u8868\u9762\u3002\u6211\u4eec\u4ecd\u7136\u7f3a\u5c11\u7684\u662f\u5916\u58f3\u8fb9\u754c\u7684\u534a\u5f84\u3002\u7531\u4e8e\u6211\u4eec\u60f3\u8981\u4e00\u4e2a\u8303\u56f4\u4e3a $[-1, 1]$ \u7684\u7acb\u65b9\u4f53\uff0c\u800c6\u5355\u5143\u58f3\u5c06\u51768\u4e2a\u5916\u9876\u70b9\u653e\u57288\u6761\u5bf9\u89d2\u7ebf\u4e0a\uff0c\u6211\u4eec\u5fc5\u987b\u5c06\u70b9 $(\\pm 1, \\pm 1, \\pm 1)$ \u8f6c\u5316\u4e3a\u534a\u5f84\u3002\u663e\u7136\uff0c\u5728 $d$ \u7ef4\u5ea6\u4e0a\uff0c\u534a\u5f84\u5fc5\u987b\u662f $\\sqrt{d}$ \uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5bf9\u4e8e\u6211\u4eec\u8981\u8003\u8651\u7684\u4e09\u7ef4\u60c5\u51b5\uff0c\u534a\u5f84\u662f $\\sqrt{3}$ \u3002\n\n// \u8fd9\u6837\uff0c\u6211\u4eec\u5c31\u6709\u4e86\u4e00\u4e2a\u8ba1\u5212\u3002\u5728\u521b\u5efa\u4e86\u7403\u7684\u5185\u90e8\u4e09\u89d2\u5f62\u548c\u5916\u58f3\u7684\u4e09\u89d2\u5f62\u4e4b\u540e\uff0c\u6211\u4eec\u5c06\u8fd9\u4e24\u4e2a\u7f51\u683c\u5408\u5e76\uff0c\u4f46\u662f\u5c06GridGenerator\u4e2d\u7684\u51fd\u6570\u53ef\u80fd\u4ece\u4ea7\u751f\u7684\u4e09\u89d2\u5f62\u4e2d\u8bbe\u7f6e\u7684\u6240\u6709\u6d41\u5f62\u79fb\u9664\uff0c\u4ee5\u786e\u4fdd\u6211\u4eec\u5bf9\u6d41\u5f62\u6709\u5145\u5206\u7684\u63a7\u5236\u3002\u7279\u522b\u662f\uff0c\u6211\u4eec\u5e0c\u671b\u5728\u7ec6\u5316\u8fc7\u7a0b\u4e2d\u5728\u8fb9\u754c\u4e0a\u6dfb\u52a0\u7684\u989d\u5916\u70b9\u80fd\u591f\u9075\u5faa\u5e73\u5766\u7684\u6d41\u5f62\u63cf\u8ff0\u3002\u4e3a\u4e86\u5f00\u59cb\u6dfb\u52a0\u66f4\u5408\u9002\u7684\u6d41\u5f62ID\u7684\u8fc7\u7a0b\uff0c\u6211\u4eec\u7ed9\u6240\u6709\u7684\u7f51\u683c\u5b9e\u4f53\uff08\u5355\u5143\u3001\u9762\u3001\u7ebf\uff09\u5206\u914d\u6d41\u5f62ID 0\uff0c\u8fd9\u4e9b\u5b9e\u4f53\u4ee5\u540e\u5c06\u4e0eTransfiniteInterpolationManifold\u76f8\u5173\u8054\u3002\u7136\u540e\uff0c\u6211\u4eec\u5fc5\u987b\u8bc6\u522b\u6cbf\u7740\u534a\u5f84\u4e3a0.5\u7684\u7403\u4f53\u7684\u9762\u548c\u7ebf\uff0c\u5e76\u7ed9\u5b83\u4eec\u6807\u8bb0\u4e00\u4e2a\u4e0d\u540c\u7684\u6d41\u5f62ID\uff0c\u4ee5\u4fbf\u968f\u540e\u7ed9\u8fd9\u4e9b\u9762\u548c\u7ebf\u5206\u914d\u4e00\u4e2aSphericalManifold\u3002\u7531\u4e8e\u6211\u4eec\u5728\u8c03\u7528 GridGenerator::hyper_ball(), \u540e\u4e22\u5f03\u4e86\u6240\u6709\u9884\u5148\u5b58\u5728\u7684\u6d41\u5f62\uff0c\u6211\u4eec\u624b\u52a8\u68c0\u67e5\u4e86\u7f51\u683c\u7684\u5355\u5143\u683c\u548c\u6240\u6709\u7684\u9762\u3002\u5982\u679c\u56db\u4e2a\u9876\u70b9\u7684\u534a\u5f84\u90fd\u662f0.5\uff0c\u6211\u4eec\u5c31\u5728\u7403\u4f53\u4e0a\u627e\u5230\u4e86\u4e00\u4e2a\u9762\uff0c\u6216\u8005\u50cf\u6211\u4eec\u5728\u7a0b\u5e8f\u4e2d\u5199\u7684\u90a3\u6837\uff0c\u6709  $r^2-0.25 \\approx 0$  \u3002\u6ce8\u610f\uff0c\u6211\u4eec\u8c03\u7528`cell->face(f)->set_all_manifold_ids(1)`\u6765\u8bbe\u7f6e\u9762\u548c\u5468\u56f4\u7ebf\u4e0a\u7684\u6d41\u5f62id\u3002\u6b64\u5916\uff0c\u6211\u4eec\u5e0c\u671b\u901a\u8fc7\u4e00\u4e2a\u6750\u6599ID\u6765\u533a\u5206\u7403\u5185\u548c\u7403\u5916\u7684\u5355\u5143\uff0c\u4ee5\u4fbf\u4e8e\u53ef\u89c6\u5316\uff0c\u5bf9\u5e94\u4e8e\u4ecb\u7ecd\u4e2d\u7684\u56fe\u7247\u3002\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// \u6709\u4e86\u6240\u6709\u5355\u5143\u683c\u3001\u9762\u548c\u7ebf\u7684\u9002\u5f53\u6807\u8bb0\uff0c\u6211\u4eec\u53ef\u4ee5\u5c06\u6d41\u5f62\u5bf9\u8c61\u9644\u52a0\u5230\u8fd9\u4e9b\u6570\u5b57\u4e0a\u3002\u6d41\u5f62ID\u4e3a1\u7684\u5b9e\u4f53\u5c06\u5f97\u5230\u4e00\u4e2a\u7403\u5f62\u6d41\u5f62\uff0c\u800c\u6d41\u5f62ID\u4e3a0\u7684\u5176\u4ed6\u5b9e\u4f53\u5c06\u88ab\u5206\u914d\u5230TransfiniteInterpolationManifold\u3002\u6b63\u5982\u4ecb\u7ecd\u4e2d\u63d0\u5230\u7684\uff0c\u6211\u4eec\u5fc5\u987b\u901a\u8fc7\u8c03\u7528 TransfiniteInterpolationManifold::initialize() \u663e\u5f0f\u521d\u59cb\u5316\u5f53\u524d\u7f51\u683c\u7684\u6d41\u5f62\uff0c\u4ee5\u83b7\u53d6\u7c97\u7565\u7684\u7f51\u683c\u5355\u5143\u548c\u8fde\u63a5\u5230\u8fd9\u4e9b\u5355\u5143\u8fb9\u754c\u7684\u6d41\u5f62\u3002\u6211\u4eec\u8fd8\u6ce8\u610f\u5230\uff0c\u6211\u4eec\u5728\u8fd9\u4e2a\u51fd\u6570\u4e2d\u672c\u5730\u521b\u5efa\u7684\u6d41\u5f62\u5bf9\u8c61\u662f\u5141\u8bb8\u8d85\u51fa\u8303\u56f4\u7684\uff08\u5c31\u50cf\u5b83\u4eec\u5728\u51fd\u6570\u8303\u56f4\u7ed3\u675f\u65f6\u90a3\u6837\uff09\uff0c\u56e0\u4e3aTriangulation\u5bf9\u8c61\u5728\u5185\u90e8\u590d\u5236\u5b83\u4eec\u3002\n\n// \u5728\u8fde\u63a5\u4e86\u6240\u6709\u7684\u6d41\u5f62\u4e4b\u540e\uff0c\u6211\u4eec\u6700\u540e\u5c06\u53bb\u7ec6\u5316\u7f51\u683c\u51e0\u6b21\uff0c\u4ee5\u521b\u5efa\u4e00\u4e2a\u8db3\u591f\u5927\u7684\u6d4b\u8bd5\u6848\u4f8b\u3002\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// \u4e0b\u9762\u7684\u51fd\u6570\u5728\u5176\u4ed6\u6559\u7a0b\u4e2d\u662f\u4f17\u6240\u5468\u77e5\u7684\uff0c\u5b83\u679a\u4e3e\u4e86\u81ea\u7531\u5ea6\uff0c\u521b\u5efa\u4e86\u4e00\u4e2a\u7ea6\u675f\u5bf9\u8c61\u5e76\u4e3a\u7ebf\u6027\u7cfb\u7edf\u8bbe\u7f6e\u4e86\u4e00\u4e2a\u7a00\u758f\u77e9\u9635\u3002\u552f\u4e00\u503c\u5f97\u4e00\u63d0\u7684\u662f\uff0c\u8be5\u51fd\u6570\u63a5\u6536\u4e86\u4e00\u4e2a\u6620\u5c04\u5bf9\u8c61\u7684\u5f15\u7528\uff0c\u7136\u540e\u6211\u4eec\u5c06\u5176\u4f20\u9012\u7ed9 VectorTools::interpolate_boundary_values() \u51fd\u6570\uff0c\u4ee5\u786e\u4fdd\u6211\u4eec\u7684\u8fb9\u754c\u503c\u5728\u7528\u4e8e\u88c5\u914d\u7684\u9ad8\u9636\u7f51\u683c\u4e0a\u88ab\u8bc4\u4f30\u3002\u5728\u672c\u4f8b\u4e2d\uff0c\u8fd9\u5e76\u4e0d\u91cd\u8981\uff0c\u56e0\u4e3a\u5916\u8868\u9762\u662f\u5e73\u7684\uff0c\u4f46\u5bf9\u4e8e\u5f2f\u66f2\u7684\u5916\u5355\u5143\uff0c\u8fd9\u5c06\u5bfc\u81f4\u8fb9\u754c\u503c\u7684\u66f4\u7cbe\u786e\u7684\u8fd1\u4f3c\u3002\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// \u7ec4\u88c5\u7ebf\u6027\u7cfb\u7edf\u7684\u51fd\u6570\u5728\u524d\u9762\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u4e5f\u662f\u4f17\u6240\u5468\u77e5\u7684\u3002\u6709\u4e00\u70b9\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0c\u6211\u4eec\u5c06\u6b63\u4ea4\u70b9\u7684\u6570\u91cf\u8bbe\u7f6e\u4e3a\u591a\u9879\u5f0f\u7684\u5ea6\u6570\u52a02\uff0c\u800c\u4e0d\u662f\u50cf\u5176\u4ed6\u5927\u591a\u6570\u6559\u7a0b\u4e2d\u7684\u5ea6\u6570\u52a01\u3002\u8fd9\u662f\u56e0\u4e3a\u6211\u4eec\u671f\u671b\u6709\u4e00\u4e9b\u989d\u5916\u7684\u7cbe\u5ea6\uff0c\u56e0\u4e3a\u6620\u5c04\u4e5f\u6d89\u53ca\u5230\u6bd4\u89e3\u7684\u591a\u9879\u5f0f\u591a\u4e00\u5ea6\u7684\u7a0b\u5ea6\u3002\n\n// \u6c47\u7f16\u4e2d\u552f\u4e00\u6709\u70b9\u4e0d\u5bfb\u5e38\u7684\u4ee3\u7801\u662f\u6211\u4eec\u8ba1\u7b97\u5355\u5143\u683c\u77e9\u9635\u7684\u65b9\u5f0f\u3002\u6211\u4eec\u6ca1\u6709\u4f7f\u7528\u6b63\u4ea4\u70b9\u7d22\u5f15\u3001\u884c\u548c\u77e9\u9635\u5217\u7684\u4e09\u4e2a\u5d4c\u5957\u5faa\u73af\uff0c\u800c\u662f\u9996\u5148\u6536\u96c6\u5f62\u72b6\u51fd\u6570\u7684\u5bfc\u6570\uff0c\u4e58\u4ee5\u7cfb\u6570\u548c\u79ef\u5206\u56e0\u5b50`JxW`\u7684\u4e58\u79ef\u7684\u5e73\u65b9\u6839\uff0c\u653e\u5728\u4e00\u4e2a\u5355\u72ec\u7684\u77e9\u9635`partial_matrix`\u4e2d\u3002\u4e3a\u4e86\u8ba1\u7b97\u5355\u5143\u77e9\u9635\uff0c\u6211\u4eec\u5728 \"partial_matrix.mTmult(cell_matrix, partial_matrix); \"\u4e00\u884c\u4e2d\u6267\u884c \"cell_matrix = partial_matrix * transpose(partial_matrix)\"\u3002\u4e3a\u4e86\u7406\u89e3\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u8981\u77e5\u9053\u77e9\u9635\u4e0e\u77e9\u9635\u7684\u4e58\u6cd5\u662f\u5bf9`partial_matrix`\u7684\u5404\u5217\u8fdb\u884c\u6c42\u548c\u3002\u5982\u679c\u6211\u4eec\u7528 \n// $a(\\mathbf{x}_q)$ \u8868\u793a\u7cfb\u6570\uff0c\u4e34\u65f6\u77e9\u9635\u7684\u6761\u76ee\u662f $\\sqrt{\\text{det}(J) w_q a(x)} \\frac{\\partial \\varphi_i(\\boldsymbol\n//  \\xi_q)}{\\partial x_k}$ \u3002\u5982\u679c\u6211\u4eec\u5c06\u8be5\u77e9\u9635\u7684\u7b2c<i>i</i>\u884c\u4e0e\u7b2c<i>j</i>\u5217\u76f8\u4e58\uff0c\u6211\u4eec\u8ba1\u7b97\u51fa\u4e00\u4e2a\u6d89\u53ca $\\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}$ \u7684\u5d4c\u5957\u548c\uff0c\u8fd9\u6b63\u662f\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u7684\u53cc\u7ebf\u6027\u5f62\u5f0f\u6240\u9700\u7684\u6761\u6b3e\u3002\n\n// \u9009\u62e9\u8fd9\u79cd\u6709\u70b9\u4e0d\u5bfb\u5e38\u7684\u65b9\u6848\u7684\u539f\u56e0\u662f\u7531\u4e8e\u8ba1\u7b97\u4e09\u7ef4\u4e2d\u76f8\u5bf9\u8f83\u9ad8\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\u7684\u5355\u5143\u77e9\u9635\u6240\u6d89\u53ca\u7684\u7e41\u91cd\u5de5\u4f5c\u3002\u7531\u4e8e\u6211\u4eec\u60f3\u5728\u8fd9\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u5f3a\u8c03\u6620\u5c04\u7684\u6210\u672c\uff0c\u6211\u4eec\u6700\u597d\u4ee5\u4f18\u5316\u7684\u65b9\u5f0f\u8fdb\u884c\u88c5\u914d\uff0c\u4ee5\u4fbf\u4e0d\u8ffd\u9010\u5df2\u7ecf\u88ab\u793e\u533a\u89e3\u51b3\u7684\u74f6\u9888\u3002\u77e9\u9635-\u77e9\u9635\u4e58\u6cd5\u662fHPC\u80cc\u666f\u4e0b\u6700\u597d\u7684\u4f18\u5316\u5185\u6838\u4e4b\u4e00\uff0c FullMatrix::mTmult() \u51fd\u6570\u5c06\u8c03\u7528\u5230\u90a3\u4e9b\u4f18\u5316\u7684BLAS\u51fd\u6570\u3002\u5982\u679c\u7528\u6237\u5728\u914d\u7f6edeal.II\u65f6\u63d0\u4f9b\u4e86\u4e00\u4e2a\u597d\u7684BLAS\u5e93\uff08\u5982OpenBLAS\u6216\u82f1\u7279\u5c14\u7684MKL\uff09\uff0c\u90a3\u4e48\u5355\u5143\u77e9\u9635\u7684\u8ba1\u7b97\u5c06\u6267\u884c\u5230\u63a5\u8fd1\u5904\u7406\u5668\u7684\u5cf0\u503c\u7b97\u672f\u6027\u80fd\u3002\u987a\u4fbf\u63d0\u4e00\u4e0b\uff0c\u5c3d\u7ba1\u6709\u4f18\u5316\u7684\u77e9\u9635-\u77e9\u9635\u4e58\u6cd5\uff0c\u4f46\u76ee\u524d\u7684\u7b56\u7565\u5728\u590d\u6742\u6027\u65b9\u9762\u662f\u6b21\u4f18\u7684\uff0c\u56e0\u4e3a\u8981\u505a\u7684\u5de5\u4f5c\u4e0e $(p+1)^9$ \u5ea6 $p$ \u7684\u8fd0\u7b97\u6210\u6b63\u6bd4\uff08\u8fd9\u4e5f\u9002\u7528\u4e8e\u7528FEValues\u7684\u901a\u5e38\u8bc4\u4f30\uff09\u3002\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u5229\u7528\u5f62\u72b6\u51fd\u6570\u7684\u5f20\u91cf\u4e58\u79ef\u7ed3\u6784\uff0c\u7528 $\\mathcal O((p+1)^7)$ \u7684\u64cd\u4f5c\u6765\u8ba1\u7b97\u5355\u5143\u683c\u77e9\u9635\uff0c\u5c31\u50cf\u4ea4\u6613\u4e8c\u4e2d\u7684\u65e0\u77e9\u9635\u6846\u67b6\u90a3\u6837\u3002\u6211\u4eec\u53c2\u8003 step-37 \u548c\u5f20\u91cf\u79ef\u611f\u77e5\u8bc4\u4f30\u5668FEEvaluation\u7684\u6587\u6863\uff0c\u4ee5\u4e86\u89e3\u5982\u4f55\u5b9e\u73b0\u66f4\u6709\u6548\u7684\u5355\u5143\u77e9\u9635\u8ba1\u7b97\u7684\u7ec6\u8282\u3002\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// \u5bf9\u4e8e\u7ebf\u6027\u7cfb\u7edf\u7684\u6c42\u89e3\uff0c\u6211\u4eec\u9009\u62e9\u4e00\u4e2a\u7b80\u5355\u7684\u96c5\u53ef\u6bd4\u6761\u4ef6\u5171\u8f6d\u68af\u5ea6\u6c42\u89e3\u5668\uff0c\u7c7b\u4f3c\u4e8e\u65e9\u671f\u6559\u7a0b\u4e2d\u7684\u8bbe\u7f6e\u3002\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// \u5728\u4e0b\u4e00\u4e2a\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u5bf9\u89e3\u51b3\u65b9\u6848\u505a\u4e86\u5404\u79cd\u540e\u5904\u7406\u6b65\u9aa4\uff0c\u6240\u6709\u8fd9\u4e9b\u6b65\u9aa4\u90fd\u4ee5\u8fd9\u79cd\u6216\u90a3\u79cd\u65b9\u5f0f\u6d89\u53ca\u6620\u5c04\u3002\n\n// \u6211\u4eec\u505a\u7684\u7b2c\u4e00\u4e2a\u64cd\u4f5c\u662f\u628a\u89e3\u51b3\u65b9\u6848\u4ee5\u53ca\u6750\u6599ID\u5199\u5230VTU\u6587\u4ef6\u4e2d\u3002\u8fd9\u4e0e\u5176\u4ed6\u8bb8\u591a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u7684\u505a\u6cd5\u7c7b\u4f3c\u3002\u8fd9\u4e2a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u63d0\u51fa\u7684\u65b0\u5185\u5bb9\u662f\uff0c\u6211\u4eec\u8981\u786e\u4fdd\u5199\u5230\u6587\u4ef6\u4e2d\u7528\u4e8e\u53ef\u89c6\u5316\u7684\u6570\u636e\u5b9e\u9645\u4e0a\u662fdeal.II\u5185\u90e8\u4f7f\u7528\u7684\u6570\u636e\u7684\u5fe0\u5b9e\u4ee3\u8868\u3002\u8fd9\u662f\u56e0\u4e3a\u5927\u591a\u6570\u53ef\u89c6\u5316\u6570\u636e\u683c\u5f0f\u53ea\u7528\u9876\u70b9\u5750\u6807\u8868\u793a\u5355\u5143\uff0c\u4f46\u6ca1\u6709\u529e\u6cd5\u8868\u793adeal.II\u4e2d\u4f7f\u7528\u9ad8\u9636\u6620\u5c04\u65f6\u7684\u66f2\u7ebf\u8fb9\u754c--\u6362\u53e5\u8bdd\u8bf4\uff0c\u4f60\u5728\u53ef\u89c6\u5316\u5de5\u5177\u4e2d\u770b\u5230\u7684\u4e1c\u897f\u5b9e\u9645\u4e0a\u4e0d\u662f\u4f60\u6b63\u5728\u8ba1\u7b97\u7684\u4e1c\u897f\u3002\u987a\u5e26\u4e00\u63d0\uff0c\u5728\u4f7f\u7528\u9ad8\u9636\u5f62\u72b6\u51fd\u6570\u65f6\u4e5f\u662f\u5982\u6b64\u3002\u5927\u591a\u6570\u53ef\u89c6\u5316\u5de5\u5177\u53ea\u5448\u73b0\u53cc\u7ebf\u6027/\u4e09\u7ebf\u6027\u7684\u8868\u793a\u3002\u8fd9\u5728 DataOut::build_patches().) \u4e2d\u6709\u8be6\u7ec6\u7684\u8ba8\u8bba\u3002\n\n// \u6240\u4ee5\u6211\u4eec\u9700\u8981\u786e\u4fdd\u9ad8\u9636\u8868\u793a\u88ab\u5199\u5165\u6587\u4ef6\u4e2d\u3002\u6211\u4eec\u9700\u8981\u8003\u8651\u4e24\u4e2a\u7279\u522b\u7684\u8bdd\u9898\u3002\u9996\u5148\uff0c\u6211\u4eec\u901a\u8fc7 DataOutBase::VtkFlags \u544a\u8bc9DataOut\u5bf9\u8c61\uff0c\u6211\u4eec\u6253\u7b97\u628a\u5143\u7d20\u7684\u7ec6\u5206\u89e3\u91ca\u4e3a\u9ad8\u9636\u62c9\u683c\u6717\u65e5\u591a\u9879\u5f0f\uff0c\u800c\u4e0d\u662f\u53cc\u7ebf\u6027\u8865\u4e01\u7684\u96c6\u5408\u3002\u6700\u8fd1\u7684\u53ef\u89c6\u5316\u7a0b\u5e8f\uff0c\u5982ParaView 5.5\u7248\u6216\u66f4\u65b0\u7684\u7a0b\u5e8f\uff0c\u7136\u540e\u53ef\u4ee5\u5448\u73b0\u9ad8\u9636\u89e3\u51b3\u65b9\u6848\uff08\u66f4\u591a\u7ec6\u8282\u89c1<a\n//  href=\"https:github.com/dealii/dealii/wiki/Notes-on-visualizing-high-order-output\">wiki\n//  page</a>\uff09\u3002\u5176\u6b21\uff0c\u6211\u4eec\u9700\u8981\u786e\u4fdd\u6620\u5c04\u88ab\u4f20\u9012\u7ed9 DataOut::build_patches() \u65b9\u6cd5\u3002\u6700\u540e\uff0cDataOut\u7c7b\u9ed8\u8ba4\u53ea\u6253\u5370<i>boundary</i>\u5355\u5143\u7684\u66f2\u9762\uff0c\u6240\u4ee5\u6211\u4eec\u9700\u8981\u786e\u4fdd\u901a\u8fc7\u6620\u5c04\u5c06\u5185\u90e8\u5355\u5143\u4e5f\u6253\u5370\u6210\u66f2\u9762\u3002\n\n  template <int dim> \n  void 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// \u540e\u5904\u7406\u51fd\u6570\u7684\u4e0b\u4e00\u4e2a\u64cd\u4f5c\u662f\u5bf9\u7167\u5206\u6790\u89e3\u8ba1\u7b97 $L_2$ \u548c $H^1$ \u8bef\u5dee\u3002\u7531\u4e8e\u5206\u6790\u89e3\u662f\u4e00\u4e2a\u4e8c\u6b21\u591a\u9879\u5f0f\uff0c\u6211\u4eec\u671f\u671b\u5728\u8fd9\u4e00\u70b9\u4e0a\u5f97\u5230\u4e00\u4e2a\u975e\u5e38\u51c6\u786e\u7684\u7ed3\u679c\u3002\u5982\u679c\u6211\u4eec\u662f\u5728\u4e00\u4e2a\u5177\u6709\u5e73\u9762\u9762\u7684\u7b80\u5355\u7f51\u683c\u4e0a\u6c42\u89e3\uff0c\u5e76\u4e14\u7cfb\u6570\u7684\u8df3\u52a8\u4e0e\u5355\u5143\u95f4\u7684\u9762\u5bf9\u9f50\uff0c\u90a3\u4e48\u6211\u4eec\u4f1a\u671f\u671b\u6570\u503c\u7ed3\u679c\u4e0e\u5206\u6790\u89e3\u76f8\u543b\u5408\uff0c\u76f4\u81f3\u820d\u53bb\u7cbe\u5ea6\u3002\u7136\u800c\uff0c\u7531\u4e8e\u6211\u4eec\u4f7f\u7528\u7684\u662f\u8ddf\u968f\u7403\u4f53\u7684\u53d8\u5f62\u5355\u5143\uff0c\u8fd9\u4e9b\u5355\u5143\u53ea\u80fd\u75314\u5ea6\u7684\u591a\u9879\u5f0f\u8ddf\u8e2a\uff08\u6bd4\u6709\u9650\u5143\u7684\u5ea6\u6570\u591a\u4e00\u4e2a\uff09\uff0c\u6211\u4eec\u4f1a\u53d1\u73b0\u5728 $10^{-7}$ \u9644\u8fd1\u6709\u4e00\u4e2a\u8bef\u5dee\u3002\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u589e\u52a0\u591a\u9879\u5f0f\u7684\u5ea6\u6570\u6216\u7ec6\u5316\u7f51\u683c\u6765\u83b7\u5f97\u66f4\u591a\u7684\u7cbe\u5ea6\u3002\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// \u6211\u4eec\u5728\u8fd9\u91cc\u505a\u7684\u6700\u540e\u4e00\u4e2a\u540e\u5904\u7406\u64cd\u4f5c\u662f\u7528KellyErrorEstimator\u8ba1\u7b97\u51fa\u4e00\u4e2a\u8bef\u5dee\u4f30\u8ba1\u3002\u6211\u4eec\u4f7f\u7528\u4e86\u4e0e step-6 \u6559\u7a0b\u7a0b\u5e8f\u4e2d\u5b8c\u5168\u76f8\u540c\u7684\u8bbe\u7f6e\uff0c\u53ea\u662f\u6211\u4eec\u8fd8\u4ea4\u51fa\u4e86\u6620\u5c04\uff0c\u4ee5\u786e\u4fdd\u8bef\u5dee\u662f\u6cbf\u7740\u66f2\u7ebf\u5143\u7d20\u8bc4\u4f30\u7684\uff0c\u4e0e\u7a0b\u5e8f\u7684\u5176\u4f59\u90e8\u5206\u4e00\u81f4\u3002\u7136\u800c\uff0c\u6211\u4eec\u5e76\u6ca1\u6709\u771f\u6b63\u4f7f\u7528\u8fd9\u91cc\u7684\u7ed3\u679c\u6765\u9a71\u52a8\u7f51\u683c\u9002\u5e94\u6b65\u9aa4\uff08\u4f1a\u6cbf\u7740\u7403\u4f53\u7ec6\u5316\u6750\u6599\u754c\u9762\u5468\u56f4\u7684\u7f51\u683c\uff09\uff0c\u56e0\u4e3a\u8fd9\u91cc\u7684\u91cd\u70b9\u662f\u8fd9\u4e2a\u64cd\u4f5c\u7684\u6210\u672c\u3002\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// \u6700\u540e\uff0c\u6211\u4eec\u5b9a\u4e49\u4e86`run()`\u51fd\u6570\uff0c\u63a7\u5236\u6211\u4eec\u5982\u4f55\u6267\u884c\u8fd9\u4e2a\u7a0b\u5e8f\uff08\u7531main()\u51fd\u6570\u4ee5\u5e38\u89c4\u65b9\u5f0f\u8c03\u7528\uff09\u3002\u6211\u4eec\u9996\u5148\u8c03\u7528`create_grid()`\u51fd\u6570\uff0c\u7528\u9002\u5f53\u7684\u6d41\u5f62\u8bbe\u7f6e\u6211\u4eec\u7684\u51e0\u4f55\u4f53\u3002\u7136\u540e\u6211\u4eec\u8fd0\u884c\u4e24\u4e2a\u6c42\u89e3\u5668\u94fe\u7684\u5b9e\u4f8b\uff0c\u4ece\u65b9\u7a0b\u7684\u8bbe\u7f6e\u5f00\u59cb\uff0c\u7ec4\u88c5\u7ebf\u6027\u7cfb\u7edf\uff0c\u7528\u4e00\u4e2a\u7b80\u5355\u7684\u8fed\u4ee3\u6c42\u89e3\u5668\u6c42\u89e3\uff0c\u4ee5\u53ca\u4e0a\u9762\u8ba8\u8bba\u7684\u540e\u5904\u7406\u3002\u8fd9\u4e24\u4e2a\u5b9e\u4f8b\u5728\u4f7f\u7528\u6620\u5c04\u7684\u65b9\u5f0f\u4e0a\u6709\u6240\u4e0d\u540c\u3002\u7b2c\u4e00\u4e2a\u4f7f\u7528\u4f20\u7edf\u7684MappingQGeneric\u6620\u5c04\u5bf9\u8c61\uff0c\u6211\u4eec\u5c06\u5176\u521d\u59cb\u5316\u4e3a\u6bd4\u6709\u9650\u5143\u591a\u4e00\u7ea7\u7684\u7a0b\u5ea6\uff1b\u6bd5\u7adf\uff0c\u6211\u4eec\u671f\u671b\u51e0\u4f55\u8868\u793a\u662f\u74f6\u9888\uff0c\u56e0\u4e3a\u5206\u6790\u89e3\u53ea\u662f\u4e8c\u6b21\u591a\u9879\u5f0f\u3002\u5b9e\u9645\u4e0a\uff0c\u4e8b\u60c5\u5728\u76f8\u5f53\u7a0b\u5ea6\u4e0a\u662f\u76f8\u4e92\u5173\u8054\u7684\uff0c\u56e0\u4e3a\u5b9e\u5750\u6807\u4e2d\u591a\u9879\u5f0f\u7684\u8bc4\u4f30\u6d89\u53ca\u5230\u9ad8\u9636\u591a\u9879\u5f0f\u7684\u6620\u5c04\uff0c\u800c\u9ad8\u9636\u591a\u9879\u5f0f\u4ee3\u8868\u4e00\u4e9b\u5149\u6ed1\u7684\u6709\u7406\u51fd\u6570\u3002\u56e0\u6b64\uff0c\u9ad8\u9636\u591a\u9879\u5f0f\u8fd8\u662f\u6709\u56de\u62a5\u7684\uff0c\u6240\u4ee5\u8fdb\u4e00\u6b65\u589e\u52a0\u6620\u5c04\u7684\u5ea6\u6570\u662f\u6ca1\u6709\u610f\u4e49\u7684)\u3002\u4e00\u65e6\u7b2c\u4e00\u904d\u5b8c\u6210\uff0c\u6211\u4eec\u5c31\u8ba9\u5b9a\u65f6\u5668\u6253\u5370\u51fa\u5404\u4e2a\u9636\u6bb5\u7684\u8ba1\u7b97\u65f6\u95f4\u7684\u6458\u8981\u3002\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// \u5bf9\u4e8e\u7b2c\u4e8c\u4e2a\u5b9e\u4f8b\uff0c\u6211\u4eec\u8f6c\u800c\u8bbe\u7f6e\u4e86MappingQCache\u7c7b\u3002\u5b83\u7684\u4f7f\u7528\u975e\u5e38\u7b80\u5355\u3002\u5728\u6784\u5efa\u597d\u5b83\u4e4b\u540e\uff08\u8003\u8651\u5230\u6211\u4eec\u5e0c\u671b\u5b83\u5728\u5176\u4ed6\u60c5\u51b5\u4e0b\u663e\u793a\u6b63\u786e\u7684\u5ea6\u6570\u529f\u80fd\uff0c\u6240\u4ee5\u7528\u5ea6\u6570\uff09\uff0c\u6211\u4eec\u901a\u8fc7 MappingQCache::initialize() \u51fd\u6570\u586b\u5145\u7f13\u5b58\u3002\u5728\u8fd9\u4e2a\u9636\u6bb5\uff0c\u6211\u4eec\u4e3a\u7f13\u5b58\u6307\u5b9a\u6211\u4eec\u60f3\u8981\u4f7f\u7528\u7684\u6620\u5c04\uff08\u5f88\u660e\u663e\uff0c\u4e0e\u4e4b\u524d\u7684MappingQGeneric\u76f8\u540c\uff0c\u4ee5\u4fbf\u91cd\u590d\u76f8\u540c\u7684\u8ba1\u7b97\uff09\uff0c\u7136\u540e\u518d\u6b21\u8fd0\u884c\u76f8\u540c\u7684\u51fd\u6570\uff0c\u73b0\u5728\u4ea4\u51fa\u4fee\u6539\u540e\u7684\u6620\u5c04\u3002\u6700\u540e\uff0c\u6211\u4eec\u518d\u6b21\u6253\u5370\u91cd\u7f6e\u540e\u7684\u7d2f\u8ba1\u58c1\u6302\u65f6\u95f4\uff0c\u770b\u770b\u8fd9\u4e9b\u65f6\u95f4\u4e0e\u539f\u6765\u7684\u8bbe\u7f6e\u76f8\u6bd4\u5982\u4f55\u3002\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": "//! \\file\n// e_float_test.cpp\n\n// Copyright Paul A. Bristow 2011.\n// Copyright Christopher Kormanyos 2011.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Test of using e_float and Boost.Check macro/functions.\n\n#define BOOST_TEST_MAIN\n#define BOOST_LIB_DIAGNOSTIC \"on\"// Show library file details.\n// Linking to lib file: libboost_unit_test_framework-vc100-mt-gd-1_48.lib  (trunk at Jul 11)\n\n//  #define E_FLOAT_DIGITS10 50 as command line using MSVC or in jamfile (but needs b2 -a option?)\n\n#include <iostream>\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::dec;\nusing std::hex;\nusing std::boolalpha;\nusing std::scientific;\nusing std::fixed;\nusing std::defaultfloat;\nusing std::showpos;\nusing std::showpoint;\n\n#include <iomanip>\nusing std::setprecision;\nusing std::setw;\n#include <string>\nusing std::string;\n#include <sstream>\n//using std::istringstream;\n//using std::ostringstream\n\n#include <boost/test/unit_test.hpp> // Enhanced for unit_test framework autolink.\n#include <boost/test/floating_point_comparison.hpp>\n\n#include <boost/e_float/e_float.hpp>\n#include <boost/e_float/e_float_constants.hpp>\n\nnamespace test\n{\n  namespace real\n  {\n    // See \\boost-sandbox\\e_float\\libs\\e_float\\test\\real\\test_real.cpp  and /cases/ *.cpp\n    // \\boost-sandbox\\e_float\\libs\\e_float\\test\\real\\cases\\test_case_0000x_overflow_underflow.cpp\n    bool test_case_00001_overflow_mul_x(const bool);\n    bool test_case_00002_underflow_mul_x (const bool);\n    bool test_case_00003_overflow_x_mul_by_n(const bool);\n    bool test_case_00004_underflow_x_div_by_n(const bool);\n    // \\boost-sandbox\\e_float\\libs\\e_float\\test\\real\\cases\\test_case_0000y_write_to_ostream.cpp\n    bool test_case_00006_write_os_floatfield_fixed(const bool);\n    bool test_case_00007_write_os_floatfield_scientific(const bool);\n    bool test_case_00008_write_os_floatfield_not_set(const bool);\n    // \\boost-sandbox\\e_float\\libs\\e_float\\test\\real\\cases\\test_case_0000z_global_ops_pod.cpp\n    bool test_case_00009_global_ops_pod_equate         (const bool);\n    bool test_case_00010_global_ops_pod_operations     (const bool);\n    // \\boost-sandbox\\e_float\\libs\\e_float\\test\\real\\cases\\test_case_00011_various_elem_math.cpp\n    bool test_case_00011_various_elem_math             (const bool);\n    bool test_case_00021_bernoulli                     (const bool);\n    bool test_case_00051_factorial                     (const bool);\n    bool test_case_00052_factorial2                    (const bool);\n    bool test_case_00071_various_int_func              (const bool);\n    bool test_case_00101_sin                           (const bool);\n    bool test_case_00102_cos                           (const bool);\n    bool test_case_00103_exp                           (const bool);\n    bool test_case_00104_log                           (const bool);\n    bool test_case_00105_sqrt                          (const bool);\n    bool test_case_00106_rootn                         (const bool);\n    bool test_case_00111_sin_small_x                   (const bool);\n    bool test_case_00112_cos_x_near_pi_half            (const bool);\n    bool test_case_00113_atan_x_small_to_large         (const bool);\n    bool test_case_00114_various_trig                  (const bool);\n    bool test_case_00115_various_elem_trans            (const bool);\n    bool test_case_00121_sinh                          (const bool);\n    bool test_case_00122_cosh                          (const bool);\n    bool test_case_00123_tanh                          (const bool);\n    bool test_case_00124_asinh                         (const bool);\n    bool test_case_00125_acosh                         (const bool);\n    bool test_case_00126_atanh                         (const bool);\n    bool test_case_00201_gamma                         (const bool);\n    bool test_case_00202_gamma_medium_x                (const bool);\n    bool test_case_00203_gamma_small_x                 (const bool);\n    bool test_case_00204_gamma_tiny_x                  (const bool);\n    bool test_case_00205_gamma_near_neg_n              (const bool);\n    bool test_case_00221_various_gamma_func            (const bool);\n    bool test_case_00901_zeta_small_x                  (const bool);\n    bool test_case_00902_zeta_all_x                    (const bool);\n    bool test_case_00903_zeta_neg_x                    (const bool);\n  } // namespace real\n} // namespace test\n\n\n//Macros to Check using manips output expected string result, for example:\n// CHECK_OUT(hex << showbase << setw(10) << i, \"       0xf\")\n// CHECK_OUT(scientific << setw(20) << d, \"       1.234568e+001\");\n\n// Compare a output with expected result. \n#define CHECK_OUT(manips, result)\\\n{ \\\n  std::ostringstream oss;\\\n  oss << manips;\\\n  BOOST_CHECK_EQUAL(oss.str(), result);\\\n}\n\n#define  CHECK_LENGTH(manips, result)\\\n{\\\n  BOOST_CHECK_EQUAL(oss.str().length(), strlen(result));\\\n}\\\n\n// Compare results of reading string in,\n#define  CHECK_IN(in, value)\\\n{\\\n  e_float r;\\\n  std::istringstream iss(in);\\\n  iss >> r;\\\n  BOOST_CHECK_CLOSE_FRACTION(r, value, std::numeric_limits<e_float>::epsilon());\\\n} // #define  CHECK_IN(in, value, sd, df, types)\n\n// CHECK_OUT_IN Output via manips, and read back in, check is same. 'Loopback'.\n#define  CHECK_OUT_IN(manips, result, value)\\\n{\\\n  std::stringstream ss;\\\n  ss << manips;\\\n  BOOST_CHECK_EQUAL(ss.str(), result);\\\n  e_float r;\\\n  ss >> r;\\\n  BOOST_CHECK_CLOSE_FRACTION(r, value, std::numeric_limits<e_float>::epsilon());\\\n}// #define  CHECK_OUT_IN(manips, result)\n\n\n// Must #define E_FLOAT_TYPE_EFX; in project properties.\n\n// Note: exact double means exactly representable as double, for example: 0.5,\n// but NOT 0.1.\n// Integral may be an integer or a double having an integral value.\n\nBOOST_AUTO_TEST_CASE(e_float_test_template)\n{ // These are just examples of using Boost.Test.\n  // Need to be removed when no longer helpful.\n  BOOST_TEST_MESSAGE(\"Test Boost.e_float\"); // Only appears if command line has --log_level=\"message\"\n\n  string m = \"Test with \";\n  m+= __FILE__;\n  m+= \" edited \";\n  m += __TIMESTAMP__ \".\\n\"; \n  BOOST_TEST_MESSAGE(m);\n  BOOST_CHECK(true);\n  BOOST_CHECK_EQUAL(1, 1);\n  BOOST_CHECK_NE(1, -1);\n  BOOST_CHECK_CLOSE_FRACTION(1.0, 1.0+std::numeric_limits<double>::epsilon(), std::numeric_limits<double>::epsilon());\n  double d = 123.456789;\n  // cout << scientific << d << endl; //  Outputs: \"1.234568e+003\"\n  CHECK_OUT(d, \"123.457\"); // Default. == << std::defaultfloat\n  CHECK_OUT(defaultfloat << d, \"123.457\"); // Default. == << std::defaultfloat\n  string ddef = \"123.457\"; // default float output.\n  CHECK_OUT(d, ddef); // Default. == << std::defaultfloat\n  CHECK_OUT(defaultfloat << d, ddef); // Default. == << std::defaultfloat\n  CHECK_OUT(scientific << d, \"1.234568e+002\");\n  CHECK_OUT(fixed << d, \"123.456789\");\n  int m1 = -1; // negative variable.\n  CHECK_OUT(m1, \"-1\"); //  negative constant. \n  CHECK_OUT(hex << m1, \"ffffffff\"); // with hex manipulator.\n  // Checking input with inline.\n  e_float r;\n  std::istringstream iss(\"123.456\");\n  iss >> r;\n  BOOST_CHECK_CLOSE_FRACTION(r, e_float(\"123.456\"), std::numeric_limits<e_float>::epsilon());\n  BOOST_CHECK_EQUAL(r, e_float(\"123.456\")); // Also works\n  // Repeat same test using CHECK_IN macro defined above.\n  CHECK_IN(\"123.456\", e_float(\"123.456\"));\n  \n  //CHECK_IN(\"123.456\", e_float(123.456)); // Mistaken conversion from less accurate double.\n  // Fails r{123.456} and e_float(123.456){123.4560000000000030695446184836328029632568359375}\n  // differ by more than 1e-49.\n\n  // CHECK_OUT_IN Output via manips, and read back in, check is same. 'Loopback'.\n  // #define  CHECK_OUT_IN(manips, result, value)\n  { // Integer example.\n    int i = 255;\n    std::string result = \"ff\";\n    int value = 255;\n    std::stringstream ss;\n    ss << hex << i;\n    BOOST_CHECK_EQUAL(ss.str(), result);\n    int read;\n    ss >> read;\n    BOOST_CHECK_EQUAL(read, value);\n  }\n  { // double example\n    double w = 123.456;\n    std::string result = \"123.456000\";\n    double value = 123.456;\n    std::stringstream ss;\n    ss << std::fixed << w;\n    //cout << ss.str() << endl;\n    BOOST_CHECK_EQUAL(ss.str(), result);\n    double read;\n    ss >> read;\n    BOOST_CHECK_EQUAL(read, value);\n    BOOST_CHECK_CLOSE_FRACTION(read, value, std::numeric_limits<double>::epsilon());\n  }\n  { // e_float example\n    e_float w(\"123.456\");\n    std::string result = \"123.456000\";  // double result was \"123.456000\";\n    e_float value(\"123.456\");\n    std::stringstream ss;\n    ss << std::fixed << w;\n    //cout << ss.str() << endl;\n    BOOST_CHECK_EQUAL(ss.str(), result);\n    e_float read;\n    ss >> read;\n    BOOST_CHECK_EQUAL(read, value);\n    BOOST_CHECK_CLOSE_FRACTION(read, value, std::numeric_limits<e_float>::epsilon());\n\n    CHECK_OUT_IN(std::fixed << w, result, value);\n  }\n\n} // BOOST_AUTO_TEST_CASE(e_float_template)\n\nBOOST_AUTO_TEST_CASE(e_float_test_macros)\n{ // Check some macro values.\n  // \n  BOOST_CHECK_EQUAL(E_FLOAT_DIGITS10, 50); // Assumes we are testing at 50 digits, NOT the default.\n} // BOOST_AUTO_TEST_CASE(e_float_test_macros)\n\n\nBOOST_AUTO_TEST_CASE(e_float_test_ios)\n{ // Check some IOS defaults.\n  BOOST_CHECK_EQUAL(cout.precision(), 6);\n  std::ostringstream oss;\n  BOOST_CHECK_EQUAL(oss.precision(), 6);\n  }\n\nBOOST_AUTO_TEST_CASE(e_float_test_input)\n{ // \n  BOOST_TEST_MESSAGE(\"Test Boost.e_float input.\"); \n\n   CHECK_IN(\"2\", e_float(\"2\"));\n   CHECK_IN(\"-2\", e_float(\"-2\"));\n   CHECK_IN(\"+2\", e_float(\"+2\"));\n   CHECK_IN(\"-2.\", e_float(\"-2.\"));\n\n   CHECK_IN(\"123.456\", e_float(\"123.456\"));\n   CHECK_IN(\"0.0123456\", e_float(\"0.0123456\"));\n   CHECK_IN(\"1e-6\", e_float(\"1e-6\"));\n   CHECK_IN(\"-1e-6\", e_float(\"-1e-6\"));\n} // BOOST_AUTO_TEST_CASE(e_float_test_input)\n\nBOOST_AUTO_TEST_CASE(e_float_tests)\n{ // Original real tests from \\e_float\\libs\\e_float\\test\\real\\cases\n  BOOST_TEST_MESSAGE(\"Test Boost.e_float numerical.\"); \n  \n  BOOST_CHECK(test::real::test_case_00001_overflow_mul_x                 (false));\n  BOOST_CHECK(test::real::test_case_00002_underflow_mul_x                (false));\n  BOOST_CHECK(test::real::test_case_00003_overflow_x_mul_by_n            (false));\n  BOOST_CHECK(test::real::test_case_00004_underflow_x_div_by_n           (false));\n  BOOST_CHECK(test::real::test_case_00006_write_os_floatfield_fixed      (false));\n  BOOST_CHECK(test::real::test_case_00007_write_os_floatfield_scientific (false));\n  BOOST_CHECK(test::real::test_case_00008_write_os_floatfield_not_set    (false));\n  BOOST_CHECK( test::real::test_case_00001_overflow_mul_x                (false));\n  BOOST_CHECK( test::real::test_case_00002_underflow_mul_x               (false));\n  BOOST_CHECK( test::real::test_case_00003_overflow_x_mul_by_n           (false));\n  BOOST_CHECK( test::real::test_case_00004_underflow_x_div_by_n          (false));\n  BOOST_CHECK( test::real::test_case_00006_write_os_floatfield_fixed     (false));\n  BOOST_CHECK( test::real::test_case_00007_write_os_floatfield_scientific(false));\n  BOOST_CHECK( test::real::test_case_00008_write_os_floatfield_not_set   (false));\n  BOOST_CHECK( test::real::test_case_00009_global_ops_pod_equate         (false));\n  BOOST_CHECK( test::real::test_case_00010_global_ops_pod_operations     (false));\n  BOOST_CHECK( test::real::test_case_00011_various_elem_math             (false));\n  BOOST_CHECK( test::real::test_case_00021_bernoulli                     (false));\n  BOOST_CHECK( test::real::test_case_00051_factorial                     (false));\n  BOOST_CHECK( test::real::test_case_00052_factorial2                    (false));\n  BOOST_CHECK( test::real::test_case_00071_various_int_func              (false));\n  BOOST_CHECK( test::real::test_case_00101_sin                           (false));\n  BOOST_CHECK( test::real::test_case_00102_cos                           (false));\n  BOOST_CHECK( test::real::test_case_00103_exp                           (false));\n  BOOST_CHECK( test::real::test_case_00104_log                           (false));\n  BOOST_CHECK( test::real::test_case_00105_sqrt                          (false));\n  BOOST_CHECK( test::real::test_case_00106_rootn                         (false));\n  BOOST_CHECK( test::real::test_case_00111_sin_small_x                   (false));\n  BOOST_CHECK( test::real::test_case_00112_cos_x_near_pi_half            (false));\n  BOOST_CHECK( test::real::test_case_00113_atan_x_small_to_large         (false));\n  BOOST_CHECK( test::real::test_case_00114_various_trig                  (false));\n  BOOST_CHECK( test::real::test_case_00115_various_elem_trans            (false));\n  BOOST_CHECK( test::real::test_case_00121_sinh                          (false));\n  BOOST_CHECK( test::real::test_case_00122_cosh                          (false));\n  BOOST_CHECK( test::real::test_case_00123_tanh                          (false));\n  BOOST_CHECK( test::real::test_case_00124_asinh                         (false));\n  BOOST_CHECK( test::real::test_case_00125_acosh                         (false));\n  BOOST_CHECK( test::real::test_case_00126_atanh                         (false));\n  BOOST_CHECK( test::real::test_case_00201_gamma                         (false));\n  BOOST_CHECK( test::real::test_case_00202_gamma_medium_x                (false));\n  BOOST_CHECK( test::real::test_case_00203_gamma_small_x                 (false));\n  BOOST_CHECK( test::real::test_case_00204_gamma_tiny_x                  (false));\n  BOOST_CHECK( test::real::test_case_00205_gamma_near_neg_n              (false));\n  BOOST_CHECK( test::real::test_case_00221_various_gamma_func            (false));\n  BOOST_CHECK( test::real::test_case_00901_zeta_small_x                  (false));\n  BOOST_CHECK( test::real::test_case_00902_zeta_all_x                    (false));\n  BOOST_CHECK( test::real::test_case_00903_zeta_neg_x                    (false));\n\n} //  BOOST_AUTO_TEST_CASE(e_float_tests)\n", "meta": {"hexsha": "835d4a306fbfc2ee42375394abeab6cb17e31c29", "size": 13912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/e_float/test/e_float_numerical_test/e_float_test.cpp", "max_stars_repo_name": "ckormanyos/e_float-2021", "max_stars_repo_head_hexsha": "fac3eef3aa15cc5b74fb19135d6474396cbc6fa8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/e_float/test/e_float_numerical_test/e_float_test.cpp", "max_issues_repo_name": "ckormanyos/e_float-2021", "max_issues_repo_head_hexsha": "fac3eef3aa15cc5b74fb19135d6474396cbc6fa8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T14:43:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T15:12:27.000Z", "max_forks_repo_path": "libs/e_float/test/e_float_numerical_test/e_float_test.cpp", "max_forks_repo_name": "ckormanyos/e_float-2021", "max_forks_repo_head_hexsha": "fac3eef3aa15cc5b74fb19135d6474396cbc6fa8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8774193548, "max_line_length": 118, "alphanum_fraction": 0.6650373778, "num_tokens": 3615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.5719159246992284}}
{"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": "#include \"my_tarjan.cpp\"\n#include <boost/graph/erdos_renyi_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/graphml.hpp>\n#include <boost/property_map/dynamic_property_map.hpp>\n#include <boost/graph/transitive_closure.hpp>\n\nusing namespace boost;\n\nint main(int argc, char*argv[])\n{\n    //An example of alternative way to design a graph \"by hand\" in order to use our algorithm\n    /*typedef std::pair<int, int> Edge;\n    int n=1000;\n    Edge edge_array[n-1];\n\n    int k=0;\n    for(int i=0;i<n-1;i++){\n        edge_array[i]=Edge(i,i+1);\n    }\n    \n    int num_arcs = sizeof(edge_array) / sizeof(Edge);\n    Graph g(&edge_array[0], &edge_array[n-1], n);*/\n\n    //This function takes a graph formatted by graphml fashion from the stdin\n    Graph g;\n    dynamic_properties dp;\n    read_graphml(std::cin, g, dp);\n\n    std::cout << \"A directed graph:\" << std::endl;\n    print_graph(g, get(vertex_index,g));\n    std::cout << std::endl;\n\n    //This is the TarjanClass object\n    TarjanClass<typeInt, typeInt, typeInt, typeBool, typeBool, typeInt> tarjan(&g);\n    std::vector<int>* comp_tarjan = tarjan.tarjan_scc();\n\n    //Printing\n    IndexMap index = get(vertex_index,g);\n\n    for (int i = 0; i != comp_tarjan->size(); ++i){\n        std::cout << index[i] << \" -> \" << (*comp_tarjan)[i] << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "87a91c5c6f3cdd69196cf59b03ad2c80b2f4ff8b", "size": 1349, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main_tarjan.cpp", "max_stars_repo_name": "phisco/advance_algorithms_project", "max_stars_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T13:46:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-28T16:42:31.000Z", "max_issues_repo_path": "main_tarjan.cpp", "max_issues_repo_name": "phisco/advance_algorithms_project", "max_issues_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main_tarjan.cpp", "max_forks_repo_name": "phisco/advance_algorithms_project", "max_forks_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3260869565, "max_line_length": 93, "alphanum_fraction": 0.6501111935, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.5719159080833357}}
{"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": "/*\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_INTRISICS_MATRIX_HPP\n#define PIC_COMPUTER_VISION_INTRISICS_MATRIX_HPP\n\n#include <vector>\n#include <random>\n#include <stdlib.h>\n\n#include \"../base.hpp\"\n\n#include \"../util/math.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n    #ifndef PIC_EIGEN_NOT_BUNDLED\n        #include \"../externals/Eigen/Dense\"\n        #include \"../externals/Eigen/Geometry\"\n    #else\n        #include <Eigen/Dense>\n        #include <Eigen/Geometry>\n    #endif\n\n#endif\n\nnamespace pic {\n\n/**\n * @brief getFocalLengthFromFOVAngle\n * @param fovy is an angle in radians.\n * @return\n */\nPIC_INLINE double getFocalLengthFromFOVAngle(double fovy)\n{\n    return 1.0 / tan(fovy / 2.0);\n}\n\n/**\n * @brief getFOVAngleFromFocalSensor\n * @param f is the focal length in mm\n * @param x is the sensor width in mm\n * @param y is the sensor height in mm\n * @return\n */\nPIC_INLINE double getFOVAngleFromFocalSensor(double f, double x, double y)\n{\n    double d = sqrt(x * x + y * y);\n    return 2.0 * atan(d /  (2.0 * f));\n}\n\n/**\n * @brief getFocalLengthPixels\n * @param focal_length_mm\n * @param sensor_size_mm\n * @param sensor_size_px\n * @return\n */\nPIC_INLINE double getFocalLengthPixels(double focal_length_mm, double sensor_size_mm, double sensor_size_px)\n{\n    return (focal_length_mm * sensor_size_px) / sensor_size_mm;\n}\n\n#ifndef PIC_DISABLE_EIGEN\n\n/**\n * @brief getIntrinsicsMatrix\n * @param focal_length\n * @param m_x\n * @param m_y\n * @param opitical_center_x\n * @param opitical_center_y\n * @return\n */\nPIC_INLINE Eigen::Matrix3d getIntrinsicsMatrix(double focal_length, double m_x, double m_y, double opitical_center_x, double opitical_center_y)\n{\n    Eigen::Matrix3d K;\n    K.setZero();\n    K(0, 0) = focal_length * m_x;\n    K(1, 1) = focal_length * m_y;\n    K(2, 2) = 1.0;\n\n    K(0, 2) = opitical_center_x;\n    K(1, 2) = opitical_center_y;\n\n    return K;\n}\n\n/**\n * @brief getIntrinsicsMatrix\n * @param focal_length_x\n * @param focal_length_y\n * @param opitical_center_y\n * @return\n */\nPIC_INLINE Eigen::Matrix3d getIntrinsicsMatrix(double focal_length_x, double focal_length_y, double opitical_center_x, double opitical_center_y)\n{\n    Eigen::Matrix3d K;\n    K.setZero();\n    K(0, 0) = focal_length_x;\n    K(1, 1) = focal_length_y;\n    K(2, 2) = 1.0;\n\n    K(0, 2) = opitical_center_x;\n    K(1, 2) = opitical_center_y;\n\n    return K;\n}\n\n/**\n * @brief removeLensDistortion\n * @param point\n * @param K\n * @return\n */\nPIC_INLINE Eigen::Vector2d removeLensDistortion(Eigen::Vector2d &p, double k[5])\n{\n    Eigen::Vector2d ret;\n\n    double r_2 = p[0] * p[0] + p[1] * p[1];\n    double r_4 = r_2 * r_2;\n\n    double c = 1.0 + k[0] * r_2 + k[1] * r_4 + k[4] * r_4 *r_2;\n\n    Eigen::Vector2d dx;\n    dx[0] = 2 * k[2] * p[0] * p[1] + k[3] * (r_2 + 2.0 * p[0] * p[0]);\n    dx[1] = k[2] * (r_2 + 2 * p[1] * p[1]) + 2.0 * k[3] * p[0] * p[1];\n\n    ret = p * c + dx;\n\n    return ret;\n}\n\n#endif // PIC_DISABLE_EIGEN\n\n} // end namespace pic\n\n#endif // PIC_COMPUTER_VISION_INTRISICS_MATRIX_HPP\n", "meta": {"hexsha": "d52e20c4d5ac868f55e53154838ecb6c836bd93b", "size": 3344, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/computer_vision/intrisics_matrix.hpp", "max_stars_repo_name": "ecarpita93/HPC_projet_1", "max_stars_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/computer_vision/intrisics_matrix.hpp", "max_issues_repo_name": "ecarpita93/HPC_projet_1", "max_issues_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/computer_vision/intrisics_matrix.hpp", "max_forks_repo_name": "ecarpita93/HPC_projet_1", "max_forks_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8562091503, "max_line_length": 144, "alphanum_fraction": 0.6686602871, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.571755453904014}}
{"text": "#include \"uint.h\"\n\n#include <algorithm>\n#include <boost/static_assert.hpp>\n#include <assert.h>\n\nconst char kDigits[] = \"0123456789abcdef\";\nBOOST_STATIC_ASSERT(sizeof kDigits == 17);\n\nstd::string UnsignedInt::toHex() const\n{\n  std::string result;\n  result.reserve(value_.size()*8);\n\n  if (value_.empty())\n  {\n    result.push_back('0');\n    return result;\n  }\n\n  assert(value_.size() > 0);\n  for (size_t i = 0; i < value_.size()-1; ++i)\n  {\n    uint32_t x = value_[i];\n    for (int j = 0; j < 8; ++j)\n    {\n      int lsd = x % 16;\n      x /= 16;\n      result.push_back(kDigits[lsd]);\n    }\n  }\n\n  uint32_t x = value_.back();\n  do\n  {\n    int lsd = x % 16;\n    x /= 16;\n    result.push_back(kDigits[lsd]);\n  } while (x != 0);\n\n  std::reverse(result.begin(), result.end());\n\n  return result;\n}\n\nstd::string UnsignedInt::toDec() const\n{\n  const uint32_t segment = 1000000000;\n  std::string result;\n  if (value_.empty())\n  {\n    result.push_back('0');\n    return result;\n  }\n\n  result.reserve(9*value_.size() + 7*value_.size()/11 + 1);\n  // log10(2**32) = 32*log10(2) = 9.633 digits per word\n  UnsignedInt copy = *this;\n  while (copy.value_.size() > 1)\n  {\n    uint32_t x = copy.devide(segment);\n    for (int i = 0; i < 9; ++i)\n    {\n      int lsd = x  % 10;\n      x /= 10;\n      result.push_back(kDigits[lsd]);\n    }\n  }\n\n  uint32_t x = copy.value_[0];\n  do\n  {\n    int lsd = x % 10;\n    x /= 10;\n    result.push_back(kDigits[lsd]);\n  } while (x != 0);\n\n  std::reverse(result.begin(), result.end());\n\n  return result;\n}\n\nUnsignedInt::UnsignedInt(const std::string& x, Radix r)\n{\n  if (r == kDec)\n  {\n    parseDec(x);\n  }\n  else if (r == kHex)\n  {\n    parseHex(x);\n  }\n  else\n  {\n    assert(0 && \"Radix invalid\");\n    abort();\n  }\n}\n\nuint32_t fromHex(char c)\n{\n  if (c >= '0' && c <= '9')\n    return c - '0';\n  if (c >= 'a' && c <= 'f')\n    return c - 'a' + 10;\n  if (c >= 'A' && c <= 'F')\n    return c - 'A' + 10;\n  return -1;\n}\n\nvoid UnsignedInt::parseHex(const std::string& str)\n{\n  value_.reserve((str.size()+7) / 8);\n  for (size_t i = 0; i < str.size(); ++i)\n  {\n    if (i % 8 == 0)\n      value_.push_back(0);\n    uint32_t digit = fromHex(str[str.size() - i - 1]);\n    uint32_t shift = 4 * (i % 8);\n    value_.back() |= (digit << shift);\n  }\n  if (value_.size() == 1 && value_[0] == 0)\n  {\n    value_.clear();\n  }\n}\n\nuint32_t fromDec(char c)\n{\n  if (c >= '0' && c <= '9')\n    return c - '0';\n  return -1;\n}\n\nuint32_t parseSegment(const char* str, int len)\n{\n  uint32_t seg = 0;\n  for (int i = 0; i < len; ++i)\n  {\n    seg *= 10;\n    seg += fromDec(str[i]);\n  }\n  return seg;\n}\n\nvoid UnsignedInt::parseDec(const std::string& str)\n{\n  const uint32_t kSegment = 1000 * 1000 * 1000;\n  const uint32_t kSegmentDigits = 9;\n  // log2(10)/32 = 0.10381025296523\n  // 8/77 = 0.103896103896104\n  value_.reserve(1 + str.size() * 8 / 77);\n\n  int first = str.size() % kSegmentDigits;\n  if (first)\n  {\n    uint32_t seg = parseSegment(str.c_str(), first);\n    add(seg);\n  }\n  for (size_t i = first; i < str.size(); i += kSegmentDigits)\n  {\n    assert(i + kSegmentDigits <= str.size());\n    uint32_t seg = parseSegment(str.c_str() + i, kSegmentDigits);\n    multiply(kSegment);\n    add(seg);\n  }\n}\n", "meta": {"hexsha": "adab5682dc1d6080fa2da9b22b145fecf968164e", "size": 3178, "ext": "cc", "lang": "C++", "max_stars_repo_path": "KM/03code/cpp/chenshuo/recipes/basic/uint.cc", "max_stars_repo_name": "wangcy6/weekly.github.io", "max_stars_repo_head_hexsha": "f249bed5cf5a2b14d798ac33086cea0c1efe432e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-03-17T10:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T03:23:34.000Z", "max_issues_repo_path": "KM/03code/cpp/chenshuo/recipes/basic/uint.cc", "max_issues_repo_name": "wangcy6/weekly.github.io", "max_issues_repo_head_hexsha": "f249bed5cf5a2b14d798ac33086cea0c1efe432e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2018-12-14T02:35:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T09:12:10.000Z", "max_forks_repo_path": "KM/03code/cpp/chenshuo/recipes/basic/uint.cc", "max_forks_repo_name": "wangcy6/weekly", "max_forks_repo_head_hexsha": "f249bed5cf5a2b14d798ac33086cea0c1efe432e", "max_forks_repo_licenses": ["Apache-2.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.9166666667, "max_line_length": 65, "alphanum_fraction": 0.5538074261, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5717554539040139}}
{"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": "// Boost.Geometry\n\n// Copyright (c) 2017-2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DENSIFY_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DENSIFY_HPP\n\n\n#include <boost/geometry/algorithms/detail/convert_point_to_point.hpp>\n#include <boost/geometry/algorithms/detail/signed_size_type.hpp>\n#include <boost/geometry/arithmetic/arithmetic.hpp>\n#include <boost/geometry/arithmetic/dot_product.hpp>\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/strategies/densify.hpp>\n#include <boost/geometry/util/algorithm.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace densify\n{\n\n\n/*!\n\\brief Densification of cartesian segment.\n\\ingroup strategies\n\\tparam CalculationType \\tparam_calculation\n\n\\qbk{\n[heading See also]\n[link geometry.reference.algorithms.densify.densify_4_with_strategy densify (with strategy)]\n}\n */\ntemplate\n<\n    typename CalculationType = void\n>\nclass cartesian\n{\npublic:\n    template <typename Point, typename AssignPolicy, typename T>\n    static inline void apply(Point const& p0, Point const& p1, AssignPolicy & policy, T const& length_threshold)\n    {\n        typedef typename AssignPolicy::point_type out_point_t;\n        typedef typename coordinate_type<out_point_t>::type out_coord_t;\n        typedef typename select_most_precise\n            <\n                typename coordinate_type<Point>::type, out_coord_t,\n                CalculationType\n            >::type calc_t;\n\n        typedef model::point<calc_t, geometry::dimension<Point>::value, cs::cartesian> calc_point_t;\n        \n        assert_dimension_equal<calc_point_t, out_point_t>();\n\n        calc_point_t cp0, dir01;\n        // dir01 = p1 - p0\n        geometry::detail::for_each_dimension<calc_point_t>([&](auto index)\n        {\n            calc_t const coord0 = boost::numeric_cast<calc_t>(get<index>(p0));\n            calc_t const coord1 = boost::numeric_cast<calc_t>(get<index>(p1));\n            set<index>(cp0, coord0);\n            set<index>(dir01, coord1 - coord0);\n        });\n\n        calc_t const dot01 = geometry::dot_product(dir01, dir01);\n        calc_t const len = math::sqrt(dot01);\n\n        BOOST_GEOMETRY_ASSERT(length_threshold > T(0));\n\n        signed_size_type const n = signed_size_type(len / length_threshold);\n        if (n <= 0)\n        {\n            return;\n        }\n\n        calc_t const den = calc_t(n + 1);\n        for (signed_size_type i = 0 ; i < n ; ++i)\n        {\n            out_point_t out;\n            \n            calc_t const num = calc_t(i + 1);\n            geometry::detail::for_each_dimension<out_point_t>([&](auto index)\n            {\n                // out = p0 + d * dir01\n                calc_t const coord = get<index>(cp0) + get<index>(dir01) * num / den;\n\n                set<index>(out, boost::numeric_cast<out_coord_t>(coord));\n            });\n\n            policy.apply(out);\n        }\n    }\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <>\nstruct default_strategy<cartesian_tag>\n{\n    typedef strategy::densify::cartesian<> type;\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::densify\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DENSIFY_HPP\n", "meta": {"hexsha": "0a897bad9835b03c71f3c9e79a3037c9510bdfd9", "size": 3702, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/cartesian/densify.hpp", "max_stars_repo_name": "pranavgo/RRT", "max_stars_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "boost/geometry/strategies/cartesian/densify.hpp", "max_issues_repo_name": "pranavgo/RRT", "max_issues_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "boost/geometry/strategies/cartesian/densify.hpp", "max_forks_repo_name": "pranavgo/RRT", "max_forks_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 28.6976744186, "max_line_length": 112, "alphanum_fraction": 0.6801728795, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5717500588136374}}
{"text": "#include <stan/math/prim.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <limits>\n#include <vector>\n\nstan::math::vector_d get_simplex_inv_logit(double lambda,\n                                           const stan::math::vector_d& c) {\n  using stan::math::inv_logit;\n  int K = c.size() + 1;\n  stan::math::vector_d theta(K);\n  theta(0) = 1.0 - inv_logit(lambda - c(0));\n  for (int k = 1; k < (K - 1); ++k)\n    theta(k) = inv_logit(lambda - c(k - 1)) - inv_logit(lambda - c(k));\n  // - 0.0\n  theta(K - 1) = inv_logit(lambda - c(K - 2));\n  return theta;\n}\n\nTEST(ProbDistributions, ordered_logistic_vals) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n\n  using stan::math::inv_logit;\n  using stan::math::ordered_logistic_log;\n\n  std::vector<int> y{1, 2, 3, 4, 5};\n  std::vector<int> zero{1, 2, 0, 4, 5};\n  std::vector<int> six{1, 2, 6, 4, 5};\n  int K = 5;\n  Matrix<double, Dynamic, 1> c(K - 1);\n  c << -1.7, -0.3, 1.2, 2.6;\n\n  Matrix<double, Dynamic, 1> lambda(K);\n  lambda << 1.1, 1.1, 1.1, 1.1, 1.1;\n\n  stan::math::vector_d theta = get_simplex_inv_logit(lambda[0], c);\n\n  double sum = 0.0;\n  double log_sum = 0.0;\n  for (int k = 0; k < theta.size(); ++k) {\n    sum += theta(k);\n    log_sum += log(theta(k));\n  }\n  EXPECT_FLOAT_EQ(1.0, sum);\n\n  for (int k = 0; k < K; ++k)\n    EXPECT_FLOAT_EQ(log(theta(k)), ordered_logistic_log(k + 1, lambda[k], c));\n\n  EXPECT_FLOAT_EQ(log_sum, ordered_logistic_log(y, lambda, c));\n\n  EXPECT_THROW(ordered_logistic_log(0, lambda[0], c), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(6, lambda[0], c), std::domain_error);\n\n  EXPECT_THROW(ordered_logistic_log(zero, lambda, c), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(six, lambda, c), std::domain_error);\n}\n\nTEST(ProbDistributions, ordered_logistic_vals_2) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n\n  using stan::math::inv_logit;\n  using stan::math::ordered_logistic_log;\n\n  std::vector<int> y{1, 2, 3};\n  std::vector<int> zero{1, 0, 3};\n  std::vector<int> six{1, 6, 3};\n\n  int K = 3;\n  Matrix<double, Dynamic, 1> c(K - 1);\n  c << -0.2, 4;\n  Matrix<double, Dynamic, 1> lambda(K);\n  lambda << -0.9, -0.9, -0.9;\n\n  stan::math::vector_d theta = get_simplex_inv_logit(lambda[0], c);\n\n  double sum = 0.0;\n  double log_sum = 0.0;\n  for (int k = 0; k < theta.size(); ++k) {\n    sum += theta(k);\n    log_sum += log(theta(k));\n  }\n  EXPECT_FLOAT_EQ(1.0, sum);\n\n  for (int k = 0; k < K; ++k)\n    EXPECT_FLOAT_EQ(log(theta(k)), ordered_logistic_log(k + 1, lambda[0], c));\n\n  EXPECT_FLOAT_EQ(log_sum, ordered_logistic_log(y, lambda, c));\n\n  EXPECT_THROW(ordered_logistic_log(0, lambda[0], c), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(4, lambda[0], c), std::domain_error);\n\n  EXPECT_THROW(ordered_logistic_log(zero, lambda, c), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(six, lambda, c), std::domain_error);\n}\n\nTEST(ProbDistributions, ordered_logistic) {\n  using stan::math::ordered_logistic_log;\n  std::vector<int> y{1, 1, 1, 1};\n  int K = 4;\n  Eigen::Matrix<double, Eigen::Dynamic, 1> c(K - 1);\n  c << -0.3, 0.1, 1.2;\n  Eigen::Matrix<double, Eigen::Dynamic, 1> lambda(K);\n  lambda << 0.5, 0.5, 0.5, 0.5;\n\n  // init size zero\n  Eigen::Matrix<double, Eigen::Dynamic, 1> c_zero;\n  EXPECT_EQ(0, c_zero.size());\n  EXPECT_THROW(ordered_logistic_log(1, lambda[0], c_zero),\n               std::invalid_argument);\n  EXPECT_THROW(ordered_logistic_log(y, lambda, c_zero), std::invalid_argument);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> c_neg(1);\n  c_neg << -13.7;\n  EXPECT_NO_THROW(ordered_logistic_log(1, lambda[0], c_neg));\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> c_unord(3);\n  c_unord << 1.0, 0.4, 2.0;\n  EXPECT_THROW(ordered_logistic_log(1, lambda[0], c_unord), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(y, lambda, c_unord), std::domain_error);\n\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  double inf = std::numeric_limits<double>::infinity();\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> nan_vec(4);\n  nan_vec << nan, nan, nan, nan;\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> inf_vec(4);\n  inf_vec << inf, inf, inf, inf;\n\n  EXPECT_THROW(ordered_logistic_log(1, nan, c), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(1, inf, c), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(y, nan_vec, c), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(y, inf_vec, c), std::domain_error);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> cbad(2);\n  cbad << 0.2, inf;\n  EXPECT_THROW(ordered_logistic_log(1, 1.0, cbad), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(y, lambda, cbad), std::domain_error);\n  cbad[1] = nan;\n  EXPECT_THROW(ordered_logistic_log(1, 1.0, cbad), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(y, lambda, cbad), std::domain_error);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> cbad1(1);\n  cbad1 << inf;\n  EXPECT_THROW(ordered_logistic_log(1, 1.0, cbad1), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(y, lambda, cbad1), std::domain_error);\n  cbad1[0] = nan;\n  EXPECT_THROW(ordered_logistic_log(1, 1.0, cbad1), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(y, lambda, cbad1), std::domain_error);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> cbad3(3);\n  cbad3 << 0.5, inf, 1.0;\n  EXPECT_THROW(ordered_logistic_log(1, 1.0, cbad3), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(y, lambda, cbad3), std::domain_error);\n  cbad3[1] = nan;\n  EXPECT_THROW(ordered_logistic_log(1, 1.0, cbad3), std::domain_error);\n  EXPECT_THROW(ordered_logistic_log(y, lambda, cbad3), std::domain_error);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> lambda_small(3);\n  lambda_small << 1, 1, 1;\n  EXPECT_THROW(ordered_logistic_log(y, lambda_small, c), std::invalid_argument);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> c_small(K - 2);\n  c_small << -0.3, 0.1;\n  std::vector<Eigen::Matrix<double, Eigen::Dynamic, 1>> c_small_vec(4);\n  c_small_vec[0] = c;\n  c_small_vec[1] = c;\n  c_small_vec[2] = c_small;\n  c_small_vec[3] = c;\n  EXPECT_THROW(ordered_logistic_log(y, lambda, c_small_vec),\n               std::invalid_argument);\n}\n\nTEST(ProbDistributionOrderedLogistic, error_check) {\n  boost::random::mt19937 rng;\n  double inf = std::numeric_limits<double>::infinity();\n  Eigen::VectorXd c(4);\n  c << -2, 2.0, 5, 10;\n  EXPECT_NO_THROW(stan::math::ordered_logistic_rng(4.0, c, rng));\n\n  EXPECT_THROW(\n      stan::math::ordered_logistic_rng(stan::math::positive_infinity(), c, rng),\n      std::domain_error);\n  c << -inf, 2.0, -5, inf;\n  EXPECT_THROW(stan::math::ordered_logistic_rng(4.0, c, rng),\n               std::domain_error);\n\n  c << -2, 5, 2.0, 10;\n  EXPECT_THROW(stan::math::ordered_logistic_rng(4.0, c, rng),\n               std::domain_error);\n}\n\nTEST(ProbDistributionOrderedLogistic, chiSquareGoodnessFitTest) {\n  using stan::math::inv_logit;\n  boost::random::mt19937 rng;\n  int N = 10000;\n  double eta = 1.0;\n  Eigen::VectorXd theta(3);\n  theta << -0.4, 4.0, 6.2;\n  Eigen::VectorXd prob(4);\n  prob(0) = 1 - inv_logit(eta - theta(0));\n  prob(1) = inv_logit(eta - theta(0)) - inv_logit(eta - theta(1));\n  prob(2) = inv_logit(eta - theta(1)) - inv_logit(eta - theta(2));\n  prob(3) = inv_logit(eta - theta(2));\n  int K = prob.rows();\n  boost::math::chi_squared mydist(K - 1);\n\n  Eigen::VectorXd loc(prob.rows());\n  for (int i = 0; i < prob.rows(); i++)\n    loc(i) = 0;\n\n  for (int i = 0; i < prob.rows(); i++) {\n    for (int j = i; j < prob.rows(); j++)\n      loc(j) += prob(i);\n  }\n\n  int count = 0;\n  int bin[K];\n  double expect[K];\n  for (int i = 0; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N * prob(i);\n  }\n\n  while (count < N) {\n    int a = stan::math::ordered_logistic_rng(eta, theta, rng);\n    bin[a - 1]++;\n    count++;\n  }\n\n  double chi = 0;\n\n  for (int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n", "meta": {"hexsha": "3ef96688e56f76e4e8a501d0c92b6104f6b6e908", "size": 7908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/ordered_logistic_test.cpp", "max_stars_repo_name": "bayesmix-dev/math", "max_stars_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "test/unit/math/prim/prob/ordered_logistic_test.cpp", "max_issues_repo_name": "bayesmix-dev/math", "max_issues_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/prim/prob/ordered_logistic_test.cpp", "max_forks_repo_name": "bayesmix-dev/math", "max_forks_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 32.95, "max_line_length": 80, "alphanum_fraction": 0.6528831563, "num_tokens": 2691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5717500480328034}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n\n#include <power_diagram.h>\n#include <testincludes.h>\n\n\nusing namespace POWER_DIAGRAM;\n\nint main()\n{\n#ifdef _FLOATTEST\n\t//Specifying Number Type and Vector Type\n\ttypedef float number_type;\n\ttypedef Eigen::Vector3f Coord; //fake vector4->3f might be even faster\n#else\n\ttypedef double number_type;\n\ttypedef Eigen::Vector3d Coord;\n#endif\n        typedef std::vector<Coord,Eigen::aligned_allocator<Coord> > PDVector;\n\tPDVector coords; //Vector of coordinates\n\tstd::vector<number_type> weights; //Vector of weights\n\tstd::vector<int> bond_to; //best guess for connectivity\n\n\n\tcoords.push_back(Coord(1.0,2.0,3.0));\n\tweights.push_back(0.56789);\n\tbond_to.push_back(0);\n\tcoords.push_back(Coord(5.0,3.0,3.0));\n\tweights.push_back(1.12);\n\tbond_to.push_back(0);\n\tcoords.push_back(Coord(5.1,3.2,3.5));\n\tweights.push_back(1.23);\n\tbond_to.push_back(1);\n\tcoords.push_back(Coord(1.3,3.2,1.5));\n\tweights.push_back(1.34);\n\tbond_to.push_back(2);\n\tcoords.push_back(Coord(0.0,3.4,1.7));\n\tweights.push_back(1.45);\n\tbond_to.push_back(3);\n\tcoords.push_back(Coord(5.4,3.4,1.7));\n\tweights.push_back(1.56);\n\tbond_to.push_back(4);\n\tcoords.push_back(Coord(3.4,2.1,1.4));\n\tweights.push_back(1.67);\n\tbond_to.push_back(5);\n\n\tstd::cout << \"Testing Power Diagram, 7 verts: \" << std::endl;\n\tPowerDiagram<number_type,Coord,3> pd = PowerDiagram<number_type,Coord,3>::create(coords.size(),coords.begin(),weights.begin(),bond_to.begin())\n\t\t.with_radiiGiven(1).with_calculate(1).with_cells(1).with_Warnings(0);\n\tbond_to.clear();\n\tparse(\"lucy25K\",coords,weights);\n\tbond_to.push_back(0);\n\tconst double scale=1;\n\tcoords[0]*=scale;\n\tweights[0]*=scale;\n\tfor (unsigned int i = 1; i < coords.size(); ++i)\n\t{\n\t\tcoords[i]*=scale;\n\t\tweights[i]*=scale;\n\t\tbond_to.push_back(i-1);\n\t}\n\tstd::cout << \"Testing Power Diagram, bunny_set: \" << std::endl;\n\tPowerDiagram<number_type,Coord,3> pd2 = PowerDiagram<number_type,Coord,3>::create(coords.size(),coords.begin(),weights.begin(),bond_to.begin())\n\t\t.with_radiiGiven(1).with_calculate(1).with_cells(1).with_Warnings(0);\n\t//pd2.update_coords(coords);\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "469f2c542d3ebfabbe4e68b7649e62a27256ea9c", "size": 2130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/powersasa/powertest.cpp", "max_stars_repo_name": "confitarlaburra/pteros2.0", "max_stars_repo_head_hexsha": "25de81f39bc8948a37e10e3b389d58ca71195d8d", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-01T10:28:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T10:28:52.000Z", "max_issues_repo_path": "thirdparty/powersasa/powertest.cpp", "max_issues_repo_name": "confitarlaburra/pteros2.0", "max_issues_repo_head_hexsha": "25de81f39bc8948a37e10e3b389d58ca71195d8d", "max_issues_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty/powersasa/powertest.cpp", "max_forks_repo_name": "confitarlaburra/pteros2.0", "max_forks_repo_head_hexsha": "25de81f39bc8948a37e10e3b389d58ca71195d8d", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5833333333, "max_line_length": 144, "alphanum_fraction": 0.7225352113, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5717373809820587}}
{"text": "#include <bits/stdc++.h>\n#include <boost/optional.hpp>\nusing namespace std;\n\n/**\n * \u69cb\u7bc9 O(NlogN)\u3001\u30af\u30a8\u30ea O(1)\n * @tparam T\n */\ntemplate<typename T>\nclass SparseTable {\n private:\n  vector<T> values;\n  vector<vector<unsigned long>> table;\n  vector<unsigned long> msb;\n  function<T(T, T)> fn;\n\n  static vector<vector<unsigned long >> build(const vector<T> &values, function<T(T, T)> fn) {\n    unsigned long size = (unsigned long) log2(values.size()) + 1;\n\n    vector<vector<unsigned long >> st(values.size(), vector<unsigned long>(size));\n    for (unsigned long i = 0; i < values.size(); ++i) st[i][0] = i;\n    for (unsigned long p = 1; p < size; ++p) {\n      for (unsigned long i = 0; i < values.size(); ++i) {\n        unsigned long q = min(i + (1 << (p - 1)), (unsigned long) values.size() - 1);\n        unsigned long l = st[i][p - 1];\n        unsigned long r = st[q][p - 1];\n        if (values[l] == fn(values[l], values[r])) {\n          st[i][p] = l;\n        } else {\n          st[i][p] = r;\n        }\n      }\n    }\n    return st;\n  }\n\n public:\n  SparseTable(const vector<T> &values, function<T(T, T)> fn) {\n    this->values = values;\n    this->fn = fn;\n\n    // table[i][p]: [i, i + 2^p) \u306b fn \u3092\u9069\u7528\u3057\u305f\u7d50\u679c\u306e\u5024\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\n    table = build(values, fn);\n\n    // msb[i]: \u6700\u4e0a\u4f4d\u30d3\u30c3\u30c8; \u3069\u306e p \u3092\u898b\u308b\u3079\u304d\u304b\n    msb = vector<unsigned long>(values.size() + 1);\n    for (unsigned long i = 2; i < values.size() + 1; ++i) {\n      msb[i] = msb[i >> 1] + 1;\n    }\n  }\n\n  /**\n   * [a, b) \u306b fn \u3092\u9069\u7528\u3057\u305f\u7d50\u679c\n   */\n  T get(unsigned long a, unsigned long b) {\n    if (b <= a) throw invalid_argument(\"a < b \u3067\u306a\u3044\u3068\u3044\u3051\u307e\u305b\u3093\");\n    if (b > values.size()) throw invalid_argument(\"\u7bc4\u56f2\u5916\u3067\u3059\");\n    unsigned long p = msb[b - a];\n    return fn(values[table[a][p]], values[table[b - (1 << p)][p]]);\n  }\n};\n", "meta": {"hexsha": "e7ce39f6fabcccfa0606d66ae4a263eec42e41da", "size": 1737, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sparse_table.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": "sparse_table.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": "sparse_table.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": 28.0161290323, "max_line_length": 94, "alphanum_fraction": 0.5486470927, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5716925597147426}}
{"text": "#include \"../include/simple_fft/fft_settings.h\"\n\n#ifdef __USE_SQUARE_BRACKETS_FOR_ELEMENT_ACCESS_OPERATOR\n#undef __USE_SQUARE_BRACKETS_FOR_ELEMENT_ACCESS_OPERATOR\n#endif\n\n#include \"../include/simple_fft/fft.h\"\n#include \"test_fft.h\"\n#include <iostream>\n#include <armadillo>\n\nusing namespace arma;\n\nnamespace simple_fft {\nnamespace fft_test {\n\nint testArmadillo()\n{\n    std::cout << \"Testing FFT algorithms with Armadillo C++\" << std::endl;\n\n    using namespace pulse_params;\n\n    std::vector<real_type> t, x;\n    makeGridsForPulse(t, x);\n\n    // typedefing arrays\n    typedef Row<real_type> RealArray1D;\n    typedef Row<complex_type> ComplexArray1D;\n    typedef Mat<real_type> RealArray2D;\n    typedef Mat<complex_type> ComplexArray2D;\n\n    // 1D fields and spectrum\n    RealArray1D E1_real(nt);\n    ComplexArray1D E1_complex(nt), G1(nt), E1_restored(nt);\n\n    // 2D fields and spectrum\n    RealArray2D E2_real(nt, nx);\n    ComplexArray2D E2_complex(nt, nx), G2(nt, nx), E2_restored(nt, nx);\n\n    if (!commonPartsForTests(E1_real, E2_real, E1_complex, E2_complex, G1, G2,\n                             E1_restored, E2_restored, t, x))\n    {\n        std::cout << \"Tests of FFT algorithms with Armadillo C++ matrix and row \"\n                  << \"returned with errors!\" << std::endl;\n        return FAILURE;\n    }\n\n    std::cout << \"Tests of FFT with Armadillo C++ matrix and row completed successfully!\"\n              << std::endl;\n    return SUCCESS;\n}\n\n} // namespace fft_test\n} // namespace simple_fft\n", "meta": {"hexsha": "ff8296bf4859581b0235d3a2074a47ee2af05aef", "size": 1502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit-tests/test_with_armadillo_matrix_and_row.cpp", "max_stars_repo_name": "opalcompany/Simple-FFT", "max_stars_repo_head_hexsha": "5f397670ecac53c68ab1df90c36a319bd277b5d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T23:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T01:09:49.000Z", "max_issues_repo_path": "unit-tests/test_with_armadillo_matrix_and_row.cpp", "max_issues_repo_name": "opalcompany/Simple-FFT", "max_issues_repo_head_hexsha": "5f397670ecac53c68ab1df90c36a319bd277b5d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-07-26T21:42:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T20:24:03.000Z", "max_forks_repo_path": "unit-tests/test_with_armadillo_matrix_and_row.cpp", "max_forks_repo_name": "opalcompany/Simple-FFT", "max_forks_repo_head_hexsha": "5f397670ecac53c68ab1df90c36a319bd277b5d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-03-20T14:41:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T09:51:54.000Z", "avg_line_length": 27.3090909091, "max_line_length": 89, "alphanum_fraction": 0.6804260985, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5716925597147426}}
{"text": "#define _USE_MATH_DEFINES\n#include \"matplotlibcpp.h\"\n#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n\nnamespace plt = matplotlibcpp;\n\nint main() {\n  // Prepare data.\n  int n = 5000;\n  Eigen::VectorXd x(n), y(n), z(n), w = 2 * Eigen::VectorXd::Ones(n);\n  for (int i = 0; i < n; ++i) {\n    x(i) = i * i;\n    y(i) = sin(2 * M_PI * i / 360.0);\n    z(i) = log(i);\n  }\n\n  // Set the size of output image = 1200x780 pixels\n  plt::figure_size(1200, 780);\n\n  // Plot line from given x and y data. Color is selected automatically.\n  plt::plot(x, y);\n\n  // Plot a red dashed line from given x and y data.\n  plt::plot(x, w, \"r--\");\n\n  // Plot a line whose name will show up as \"log(x)\" in the legend.\n  plt::plot(x, z, {{\"label\", \"log(x)\"}});\n\n  // Set x-axis to interval [0,1000000]\n  plt::xlim(0, 1000 * 1000);\n\n  // Add graph title\n  plt::title(\"Sample figure\");\n\n  // Enable legend.\n  plt::legend();\n\n  // save figure\n  const char *filename = \"./eigen_basic.png\";\n  std::cout << \"Saving result to \" << filename << std::endl;\n\n  plt::savefig(filename);\n}\n", "meta": {"hexsha": "30c06962b3e28ad1059fa6b4d6ec64bb4fb6ae70", "size": 1058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen.cpp", "max_stars_repo_name": "LucaMac1/matplotlib-cpp", "max_stars_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/eigen.cpp", "max_issues_repo_name": "LucaMac1/matplotlib-cpp", "max_issues_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigen.cpp", "max_forks_repo_name": "LucaMac1/matplotlib-cpp", "max_forks_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0, "max_line_length": 72, "alphanum_fraction": 0.6001890359, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.571692549466677}}
{"text": "#include<iostream>\n#define EIGEN_USE_MKL_ALL\n#include <Eigen/Eigenvalues> \n#include\"numerics.hpp\"\n#include\"reddm.hpp\"\n#include\"tpoperators.hpp\"\n#include \"files.hpp\"\n#include\"FTLanczos.hpp\"\nusing namespace Many_Body;\n    using Mat= Operators::Mat;\nint main(int argc, char *argv[])\n{\n   using Mat= Operators::Mat;\n    int L=3;\n  double omega=1;\n  double gamma=1;\n  double t0=1;\n  int M=2;\n  double mean=0.5*omega*L*M;;\n  \n  double beta=1;\n  \n  double T=1./beta;\n   using HolsteinBasis= TensorProduct<ElectronBasis, PhononBasis>;\n      \n  ElectronBasis e( L, 1);\n\n  \n  PhononBasis ph(L, M);\n\n  HolsteinBasis TP(e, ph);\n\n\n        Mat E1=Operators::EKinOperatorL(TP, e, t0, true);\n       Mat Ebdag=Operators::NBosonCOperator(TP, ph, gamma, true);\n       std::cout<< \"dim \"<< TP.dim<< std::endl;\n       Mat Eb=Operators::NBosonDOperator(TP, ph, gamma, true);\n       Mat Eph=Operators::NumberOperator(TP, ph, omega,  true);\n      \n      Mat N=Operators::NumberOperator(TP, ph, 1,  true);\n      //    std::cout<< HH << std::endl;\n      Eigen::VectorXd eigenVals(TP.dim);\n       \tMat H=E1+Eph +Ebdag + Eb;\n       Mat O=N;\n       std::vector<Mat> v{H, O};\n       //       auto HH=Eigen::MatrixXd(H);\n\n      auto ev=Eigen::VectorXd(H.rows());\n      //    diagMat(HH, ev);\n\n      auto  o=FTLM(H, v, T, 800);\n\n       std::cout<< \"for beta/mean = \" << beta << std::endl;\n       for(auto& l: o)\n   \t{std::cout<< l<<std::endl; }\n  \n  return 0;\n}\n", "meta": {"hexsha": "450ed600d43ec236f856a1971568a933a74968ad", "size": 1430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/holstFTLM.cpp", "max_stars_repo_name": "jansendavid/many-body-lib", "max_stars_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/holstFTLM.cpp", "max_issues_repo_name": "jansendavid/many-body-lib", "max_issues_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/holstFTLM.cpp", "max_forks_repo_name": "jansendavid/many-body-lib", "max_forks_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2372881356, "max_line_length": 66, "alphanum_fraction": 0.5979020979, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5716875000024756}}
{"text": "#include <boost/program_options.hpp>\n#include <iostream>\n#include <random>\n\nnamespace po = boost::program_options;\n\nint main(int argc, char* argv[]) {\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (\"help\", \"produce help message\")\n        (\"n\", po::value<int>(), \"number of random values to generate\")\n    ;\n\n    po::variables_map vm;        \n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);    \n\n    if (vm.count(\"help\")) {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    int n {1};\n    if (vm.count(\"n\"))\n        n = vm[\"n\"].as<int>();\n    std::random_device device;\n    std::mt19937 engine(device());\n    std::uniform_real_distribution<double> distr(0.0, 1.0);\n    for (int i = 0; i < n; ++i)\n        std::cout << distr(engine) << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "20fa5d29938e93af46b9335f72049dcd84d05d01", "size": 852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Boost/ProgramOptions/random.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/Boost/ProgramOptions/random.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/Boost/ProgramOptions/random.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": 25.0588235294, "max_line_length": 70, "alphanum_fraction": 0.5727699531, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5716853693824815}}
{"text": "// Petter Strandmark 2013\n//\n// This is a test suite of non-linear least-squares problems\n// from NIST.\n// http://www.itl.nist.gov/div898/strd/nls/nls_main.shtml\n//\n// The code loading the NIST data files has been adapted from\n// Ceres, see http://code.google.com/ceres-solver .\n//\n// Note: g++ 4.5.3 gives array out of bounds warnings for\n// specializations in auto_diff_term.h. As far as I can tell,\n// these specializations are never executed and the warnings\n// disappear when the number of tests change.\n// \n\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n\n#include <Eigen/Dense>\n\n#include <catch.hpp>\n\n#include <spii/auto_diff_term.h>\n#include <spii/solver.h>\n\nusing namespace spii;\n\nstd::ofstream output_file(\"nist.log\");\n\nvoid skip_lines(std::istream* in, int num_lines)\n{\n\tstd::string str;\n\tfor (int i = 0; i < num_lines; ++i) {\n\t\tstd::getline(*in, str);\n\t}\n}\n\nvoid split_string(const std::string& str, std::vector<std::string>* tokens)\n{\n\tstd::stringstream sin(str);\n\ttokens->clear();\n\twhile (true) {\n\t\tstd::string s;\n\t\tsin >> s;\n\t\tif (sin) {\n\t\t\ttokens->push_back(s);\n\t\t}\n\t\telse {\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\ntemplate<typename T>\nT convert(const std::string& str)\n{\n\tstd::stringstream sin(str);\n\tT t;\n\tsin >> t;\n\tif (!sin) {\n\t\tthrow std::runtime_error(\"Conversion failed.\");\n\t}\n\treturn t;\n}\n\nvoid get_and_split_line(std::istream* in, std::vector<std::string>* tokens)\n{\n\tstd::string str;\n\tstd::getline(*in, str);\n\tsplit_string(str, tokens);\n}\n\nclass NISTProblem\n{\npublic:\n\tNISTProblem(std::string filename)\n\t{\n\t\tstd::ifstream fin(filename);\n\t\tif (!fin) {\n\t\t\t// Perhaps we are running the command from the root\n\t\t\t// project folder.\n\t\t\tfilename = \"bin/\" + filename;\n\t\t\tfin.open(filename);\n\t\t\tif (!fin) {\n\t\t\t\t// Perhaps we are running the command from the test\n\t\t\t\t// project folder.\n\t\t\t\tfilename = \"../\" + filename;\n\t\t\t\tfin.open(filename);\n\t\t\t\tif (!fin) {\n\t\t\t\t\tstd::string error = \"Failed to open \";\n\t\t\t\t\terror += filename;\n\t\t\t\t\tthrow std::runtime_error(error.c_str());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstd::vector<std::string> tokens;\n\n\t\tskip_lines(&fin, 24);\n\t\tget_and_split_line(&fin, &tokens);\n\t\tconst int num_responses = convert<int>(tokens.at(1));\n\n\t\tget_and_split_line(&fin, &tokens);\n\t\tconst int num_predictors = convert<int>(tokens.at(0));\n\n\t\tget_and_split_line(&fin, &tokens);\n\t\tconst int num_observations = convert<int>(tokens.at(0));\n\n\t\tskip_lines(&fin, 4);\n\t\tget_and_split_line(&fin, &tokens);\n\t\tconst int num_parameters = convert<int>(tokens.at(0));\n\t\tskip_lines(&fin, 8);\n\n\t\tget_and_split_line(&fin, &tokens);\n\t\tconst int num_tries = static_cast<int>(tokens.size() - 4);\n\n\t\tthis->predictor.resize(num_observations, num_predictors);\n\t\tthis->response.resize(num_observations, num_responses);\n\t\tthis->initial_parameters.resize(num_tries, num_parameters);\n\t\tthis->final_parameters.resize(1, num_parameters);\n\n\t\tint parameter_id = 0;\n\t\tfor (int i = 0; i < num_tries; ++i) {\n\t\t\tthis->initial_parameters(i, parameter_id) =\n\t\t\t\tconvert<double>(tokens.at(i + 2));\n\t\t}\n\t\tfinal_parameters(0, parameter_id) =\n\t\t\tconvert<double>(tokens.at(2 + num_tries));\n\n\t\tfor (parameter_id = 1; parameter_id < num_parameters; ++parameter_id) {\n\t\t\tget_and_split_line(&fin, &tokens);\n\t\t\t\tfor (int i = 0; i < num_tries; ++i) {\n\t\t\t\tthis->initial_parameters(i, parameter_id) =\n\t\t\t\t\tconvert<double>(tokens.at(i + 2));\n\t\t\t}\n\t\t\tfinal_parameters(0, parameter_id) =\n\t\t\t\tconvert<double>(tokens.at(2 + num_tries));\n\t\t}\n\n\t\tskip_lines(&fin, 1);\n\t\tget_and_split_line(&fin, &tokens);\n\t\tthis->certified_cost = convert<double>(tokens.at(4));\n\n\t\tskip_lines(&fin, 18 - num_parameters);\n\t\tfor (int i = 0; i < num_observations; ++i) {\n\t\t\tget_and_split_line(&fin, &tokens);\n\t\t\tfor (int j = 0; j < num_responses; ++j) {\n\t\t\t\tthis->response(i, j) = convert<double>(tokens.at(j));\n\t\t\t}\n\n\t\t\tfor (int j = 0; j < num_predictors; ++j) {\n\t\t\t\tthis->predictor(i, j) =\n\t\t\t\t\tconvert<double>(tokens.at(j + num_responses));\n\t\t\t}\n\t\t}\n\t}\n\n\tEigen::MatrixXd predictor, response, initial_parameters, final_parameters;\n\tdouble certified_cost;\n};\n\ntemplate<typename SolverClass>\nSolverClass create_solver()\n{\n\treturn {};\n}\n\ntemplate<>\nNewtonSolver create_solver<NewtonSolver>()\n{\n\tNewtonSolver solver;\n\tsolver.maximum_iterations = 5000;\n\tsolver.function_improvement_tolerance = 0;\n\tsolver.argument_improvement_tolerance = 0;\n\tsolver.gradient_tolerance = 1e-8;\n\n\tsolver.line_search_rho = 0.6;\n\n\tsolver.factorization_method = NewtonSolver::FactorizationMethod::MESCHACH;\n\treturn solver;\n}\n\nconst bool use_sym_ildl =\n#ifdef USE_SYM_ILDL\n\ttrue;\n#else\n\tfalse;\n#endif\n\nclass NewtonSolverSYM_ILDL\n\t: public NewtonSolver\n{\n};\n\ntemplate<>\nNewtonSolverSYM_ILDL create_solver<NewtonSolverSYM_ILDL>()\n{\n\tNewtonSolverSYM_ILDL solver;\n\tstatic_cast<NewtonSolver&>(solver) = create_solver<NewtonSolver>();\n\tsolver.factorization_method = NewtonSolver::FactorizationMethod::SYM_ILDL;\n\treturn solver;\n}\n\ntemplate<>\nLBFGSSolver create_solver<LBFGSSolver>()\n{\n\tLBFGSSolver solver;\n\tsolver.maximum_iterations = 10000;\n\tsolver.function_improvement_tolerance = 0;\n\tsolver.argument_improvement_tolerance = 0;\n\tsolver.gradient_tolerance = 1e-7;\n\n\treturn solver;\n}\n\ntemplate<>\nNelderMeadSolver create_solver<NelderMeadSolver>()\n{\n\tNelderMeadSolver solver;\n\tsolver.maximum_iterations = 10000;\n\tsolver.function_improvement_tolerance = 1e-14;\n\tsolver.argument_improvement_tolerance = 1e-14;\n\tsolver.gradient_tolerance = 1e-12;\n\tsolver.area_tolerance = 1e-60;\n\n\treturn solver;\n}\n\ntemplate<typename SolverClass, typename Model, int num_variables>\nvoid run_problem_main(const std::string& filename)\n{\n\tNISTProblem problem(filename);\n\tREQUIRE(problem.response.cols() == 1);\n\tREQUIRE(problem.initial_parameters.cols() == num_variables);\n\n\t// Run a test for each starting point provicded by the data file.\n\tfor (int start = 0; start < problem.initial_parameters.rows(); ++start) {\n\t\tINFO(\"Start \" << start + 1 << \" of \" << problem.initial_parameters.rows());\n\n\t\tEigen::VectorXd initial_parameters =\n\t\t\tproblem.initial_parameters.row(start);\n\t\tREQUIRE(initial_parameters.size() == num_variables);\n\n\t\tFunction function;\n\t\tfunction.add_variable(initial_parameters.data(), num_variables);\n\n\t\tfor (int i = 0; i < problem.predictor.rows(); ++i) {\n\t\t\tdouble x = problem.predictor(i, 0);\n\t\t\tdouble y = problem.response(i, 0);\n\t\t\tauto term = std::make_shared<AutoDiffTerm<Model, num_variables>>(x, y);\n\t\t\tfunction.add_term(term, initial_parameters.data());\n\t\t}\n\n\t\tauto initial_cost = function.evaluate();\n\n\t\tauto solver = create_solver<SolverClass>();\n\n\t\tstd::stringstream sout;\n\t\tsolver.log_function = [&sout](const std::string& s) { sout << s << std::endl; };\n\n\t\tSolverResults results;\n\t\tsolver.solve(function, &results);\n\n\t\tauto final_cost = function.evaluate();\n\n\t\t// Print the solver results to the log stringstream.\n\t\tINFO(sout.str());\n\t\tINFO(results);\n\t\tfor (int i = 0; i < num_variables; ++i) {\n\t\t\tINFO(\"b[\" << i << \"] = \" << initial_parameters[i]);\n\t\t}\n\n\t\tconst double optimum = problem.certified_cost;\n\t\tint num_matching_digits = static_cast<int>(\n\t\t\t-std::log10(fabs(function.evaluate() - optimum) / optimum));\n\n\t\tINFO(\"Number of matching digits: \" << num_matching_digits);\n\n\t\t// Compute log_relative_error with code from Ceres Solver.\n\t\t//\n\t\t// Compute the LRE by comparing each component of the solution\n\t\t// with the ground truth, and taking the minimum.\n\t\tauto final_parameters = problem.final_parameters;\n\t\tconst double kMaxNumSignificantDigits = 11;\n\t\tdouble log_relative_error = kMaxNumSignificantDigits + 1;\n\t\tfor (int i = 0; i < num_variables; ++i) {\n\t\t\tconst double tmp_lre =\n\t\t\t\t-std::log10(std::fabs(final_parameters(i) - initial_parameters(i)) /\n\t\t\t\t\t\t\tstd::fabs(final_parameters(i)));\n\t\t\t// The maximum LRE is capped at 11 - the precision at which the\n\t\t\t// ground truth is known.\n\t\t\t//\n\t\t\t// The minimum LRE is capped at 0 - no digits match between the\n\t\t\t// computed solution and the ground truth.\n\t\t\tlog_relative_error =\n\t\t\tstd::min(log_relative_error,\n\t\t\t\t\t std::max(0.0, std::min(kMaxNumSignificantDigits, tmp_lre)));\n\t\t}\n\n\t\toutput_file << typeid(Model).name() << \" \"\n\t\t            << typeid(SolverClass).name() << \" \"\n\t\t            << \"start: \" << start + 1 << \" \"\n\t\t\t\t\t<< (log_relative_error < 4 ? \"FAILURE\" : \"SUCCESS\") << \" \"\n\t\t            << \"LRE: \" << log_relative_error << \" \"\n\t\t            << \"Initial cost: \" << initial_cost << \" \"\n\t\t            << \"Final cost: \" << final_cost << \" \"\n\t\t            << \"Certified cost: \" << problem.certified_cost\n\t\t\t\t\t<< std::endl;\n\n\t\t// If the optimum was reached, everything is OK.\n\t\tif (num_matching_digits >= 4) {\n\t\t\tCHECK(num_matching_digits >= 4);  // To log the test.\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Otherwise, reaching a stationary point is enough.\n\t\tCHECK(results.exit_condition ==\n\t\t      SolverResults::GRADIENT_TOLERANCE);\n\n\t\t// But for Nelder-Mead, a small area is not equivalent to a\n\t\t// stationary point.\n\t\tif (typeid(SolverClass) == typeid(NelderMeadSolver)) {\n\t\t\tCHECK(num_matching_digits >= 4);\n\t\t}\n\t}\n}\n\n#define NIST_TEST_START(Problem)         \\\nstruct Problem                           \\\n{                                        \\\n\tdouble x_param, y_param;             \\\n\tProblem(double x, double y)          \\\n\t{                                    \\\n\t\tthis->x_param = x;               \\\n\t\tthis->y_param = y;               \\\n\t}                                    \\\n\ttemplate<typename R>                 \\\n\tR operator()(const R* const b) const \\\n\t{                                    \\\n\t\tconst R x(x_param);              \\\n\t\tconst R y(y_param);              \\\n\t\tR d = y - (                      \\\n\n#define NIST_TEST_END(Category, Problem, n) \\\n\t\t);                               \\\n\t\treturn d*d;                      \\\n\t}                                    \\\n};                                       \\\nTEST_CASE(#Category \"/\" #Problem, \"\")    \\\n{                                        \\\n\tSECTION(\"Newton\") {\t\t\t\t\t \\\n\t\trun_problem_main<NewtonSolver, Problem, n>(    \\\n\t\t\t\"nist/\" #Problem \".dat\");    \\\n\t}                                    \\\n\tSECTION(\"NewtonSolverSYM_ILDL\") {    \\\n\t\tif (use_sym_ildl) {              \\\n\t\t\trun_problem_main<NewtonSolverSYM_ILDL, Problem, n>(    \\\n\t\t\t\"nist/\" #Problem \".dat\");    \\\n\t\t}                                \\\n\t}                                    \\\n\tSECTION(\"LBFGS\") {                   \\\n\t\trun_problem_main<LBFGSSolver, Problem, n>(    \\\n\t\t\t\"nist/\" #Problem \".dat\");    \\\n\t}                                    \\\n}\n\nconst double kPi = 3.141592653589793238462643383279;\n\nNIST_TEST_START(Bennett5)\n\tb[0] * pow(b[1] + x, R(-1.0) / b[2])\nNIST_TEST_END(Hard, Bennett5, 3)\n\nNIST_TEST_START(BoxBOD)\n  b[0] * (R(1.0) - exp(-b[1] * x))\nNIST_TEST_END(Hard, BoxBOD, 2)\n\nNIST_TEST_START(Chwirut1)\n  exp(-b[0] * x) / (b[1] + b[2] * x)\nNIST_TEST_END(Easy, Chwirut1, 3)\n\nNIST_TEST_START(Chwirut2)\n  exp(-b[0] * x) / (b[1] + b[2] * x)\nNIST_TEST_END(Easy, Chwirut2, 3)\n\nNIST_TEST_START(DanWood)\n  b[0] * pow(x, b[1])\nNIST_TEST_END(Easy, DanWood, 2)\n\nNIST_TEST_START(Gauss1)\n  b[0] * exp(-b[1] * x) +\n  b[2] * exp(-pow((x - b[3])/b[4], 2)) +\n  b[5] * exp(-pow((x - b[6])/b[7],2))\nNIST_TEST_END(Easy, Gauss1, 8)\n\nNIST_TEST_START(Gauss2)\n  b[0] * exp(-b[1] * x) +\n  b[2] * exp(-pow((x - b[3])/b[4], 2)) +\n  b[5] * exp(-pow((x - b[6])/b[7],2))\nNIST_TEST_END(Medium, Gauss2, 8)\n\nNIST_TEST_START(Gauss3)\n  b[0] * exp(-b[1] * x) +\n  b[2] * exp(-pow((x - b[3])/b[4], 2)) +\n  b[5] * exp(-pow((x - b[6])/b[7],2))\nNIST_TEST_END(Medium, Gauss3, 8)\n\nNIST_TEST_START(Lanczos1)\n  b[0] * exp(-b[1] * x) + b[2] * exp(-b[3] * x) + b[4] * exp(-b[5] * x)\nNIST_TEST_END(Medium, Lanczos1, 6)\n\nNIST_TEST_START(Lanczos2)\n  b[0] * exp(-b[1] * x) + b[2] * exp(-b[3] * x) + b[4] * exp(-b[5] * x)\nNIST_TEST_END(Medium, Lanczos2, 6)\n\nNIST_TEST_START(Hahn1)\n  (b[0] + b[1] * x + b[2] * x * x + b[3] * x * x * x) /\n  (R(1.0) + b[4] * x + b[5] * x * x + b[6] * x * x * x)\nNIST_TEST_END(Medium, Hahn1, 7)\n\nNIST_TEST_START(Kirby2)\n  (b[0] + b[1] * x + b[2] * x * x) /\n  (R(1.0) + b[3] * x + b[4] * x * x)\nNIST_TEST_END(Medium, Kirby2, 5)\n\nNIST_TEST_START(MGH09)\n  b[0] * (x * x + x * b[1]) / (x * x + x * b[2] + b[3])\nNIST_TEST_END(Hard, MGH09, 4)\n\nNIST_TEST_START(MGH10)\n  b[0] * exp(b[1] / (x + b[2]))\nNIST_TEST_END(Hard, MGH10, 3)\n\nNIST_TEST_START(MGH17)\n  b[0] + b[1] * exp(-x * b[3]) + b[2] * exp(-x * b[4])\nNIST_TEST_END(Medium, MGH17, 5)\n\nNIST_TEST_START(Misra1a)\n  b[0] * (R(1.0) - exp(-b[1] * x))\nNIST_TEST_END(Easy, Misra1a, 2)\n\nNIST_TEST_START(Misra1b)\n  b[0] * (R(1.0) - R(1.0)/ ((R(1.0) + b[1] * x / 2.0) * (R(1.0) + b[1] * x / 2.0)))\nNIST_TEST_END(Easy, Misra1b, 2)\n\nNIST_TEST_START(Misra1c)\n  b[0] * (R(1.0) - pow(R(1.0) + R(2.0) * b[1] * x, -0.5))\nNIST_TEST_END(Medium, Misra1c, 2)\n\nNIST_TEST_START(Misra1d)\n  b[0] * b[1] * x / (R(1.0) + b[1] * x)\nNIST_TEST_END(Medium, Misra1d, 2)\n\nNIST_TEST_START(Roszman1)\n  b[0] - b[1] * x - atan(b[2] / (x - b[3]))/R(kPi)\nNIST_TEST_END(Medium, Roszman1, 4)\n\nNIST_TEST_START(Rat42)\n  b[0] / (R(1.0) + exp(b[1] - b[2] * x))\nNIST_TEST_END(Hard, Rat42, 3)\n\nNIST_TEST_START(Rat43)\n  b[0] / pow(R(1.0) + exp(b[1] - b[2] * x), R(1.0) / b[3])\nNIST_TEST_END(Hard, Rat43, 4)\n\nNIST_TEST_START(Thurber)\n  (b[0] + b[1] * x + b[2] * x * x  + b[3] * x * x * x) /\n  (R(1.0) + b[4] * x + b[5] * x * x + b[6] * x * x * x)\nNIST_TEST_END(Hard, Thurber, 7)\n\nNIST_TEST_START(ENSO)\n  b[0] + b[1] * cos(R(2.0 * kPi) * x / R(12.0)) +\n         b[2] * sin(R(2.0 * kPi) * x / R(12.0)) +\n         b[4] * cos(R(2.0 * kPi) * x / b[3]) +\n         b[5] * sin(R(2.0 * kPi) * x / b[3]) +\n         b[7] * cos(R(2.0 * kPi) * x / b[6]) +\n         b[8] * sin(R(2.0 * kPi) * x / b[6])\nNIST_TEST_END(Medium, ENSO, 9)\n\nNIST_TEST_START(Eckerle4)\n  b[0] / b[1] * exp(R(-0.5) * pow((x - b[2])/b[1], 2))\nNIST_TEST_END(Hard, Eckerle4, 3)\n", "meta": {"hexsha": "5bd88074a2c6a6a283b160da46f760e6497c1084", "size": 13706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_nist.cpp", "max_stars_repo_name": "PetterS/spii", "max_stars_repo_head_hexsha": "98c5847223d7c3febea5a1aac6f4978dfef207ec", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-03-03T16:21:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T08:02:12.000Z", "max_issues_repo_path": "tests/test_nist.cpp", "max_issues_repo_name": "nashdingsheng/spii", "max_issues_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-07-16T14:41:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-09T19:27:22.000Z", "max_forks_repo_path": "tests/test_nist.cpp", "max_forks_repo_name": "nashdingsheng/spii", "max_forks_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-09-21T23:09:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T20:20:30.000Z", "avg_line_length": 28.1437371663, "max_line_length": 83, "alphanum_fraction": 0.6133080403, "num_tokens": 4397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5716853620668494}}
{"text": "#include <aslam/backend/ErrorTermMotionBST.hpp>\n#include <aslam/backend/ErrorTermPriorBST.hpp>\n#include <aslam/backend/ExpressionErrorTerm.hpp>\n#include <aslam/backend/OptimizationProblem.hpp>\n#include <aslam/backend/Optimizer2.hpp>\n#include <aslam/backend/Optimizer2Options.hpp>\n#include <aslam/backend/DenseQrLinearSystemSolver.hpp>\n#include <iostream>\n// Bring in some random number generation from Schweizer Messer.\n#include <sm/random.hpp>\n#include <vector>\n#include <algorithm>\n#include <boost/shared_ptr.hpp>\n\n#include <aslam/backend/EuclideanPoint.hpp>\n#include <sm/kinematics/RotationVector.hpp>\n#include <aslam/splines/OPTBSpline.hpp>\n#include <bsplines/EuclideanBSpline.hpp>\n#include <aslam/backend/Scalar.hpp>\n\nint main(int argc, char ** argv)\n{\n  if(argc != 2)\n    {\n      std::cout << \"Usage: example K\\n\";\n      std::cout << \"The argument K is the number of timesteps to include in the optimization\\n\";\n      return 1;\n    }\n\n  const int K = atoi(argv[1]);\n\n  try \n    {\n      // The true wall position\n      const double true_w = 5.0;\n      \n      // The noise properties.\n      const double sigma_n = 0.01;\n      const double sigma_u = 0.1;\n      const double sigma_x = 0.01;\n\n      // Create random odometry\n      std::vector<double> true_u_k(K);\n      for(double& u : true_u_k)\n      {\n        u = 1;//sm::random::uniform();\n      }\n      \n      // Create the noisy odometry\n      std::vector<double> u_k(K);\n      for(int k = 0; k < K; ++k)\n      {\n        u_k[k] = true_u_k[k] + (sigma_u * sm::random::normal());\n      }\n\n      // Create the states from noisy odometry.\n      std::vector<double> x_k(K);\n      std::vector<double> true_x_k(K);\n      x_k[0] = 10.0;\n      true_x_k[0] = 10.0;\n      for(int k = 1; k < K; ++k)\n      {\n        true_x_k[k] = true_x_k[k-1] + true_u_k[k];\n        x_k[k] = x_k[k-1] + u_k[k];\n      }\n\n\n      // Create the noisy measurments\n      std::vector<double> y_k(K);\n      for(int k = 0; k < K; ++k)\n      {\n        y_k[k] = (true_w / true_x_k[k]) + sigma_n * sm::random::normal();\n      }\n      \n      // Now we can build an optimization problem.\n      boost::shared_ptr<aslam::backend::OptimizationProblem> problem( new aslam::backend::OptimizationProblem);\n\n      typedef aslam::splines::OPTBSpline<bsplines::EuclideanBSpline<4, 1>::CONF> PosSpline;\n      PosSpline robotPosSpline;\n      const int pointSize = robotPosSpline.getPointSize();\n\n      PosSpline::point_t initPoint(pointSize);\n\n      initPoint(0,0) = x_k[0];\n\n      // initialize the spline uniformly with from time 0 to K with K segments and the initPoint as a constant value\n      robotPosSpline.initConstantUniformSpline(0, K, K, initPoint);\n\n      // add the robot pose spline to the problem\n      for(size_t i = 0; i < robotPosSpline.numDesignVariables(); i++)\n      {\n        robotPosSpline.designVariable(i)->setActive(true);\n        problem->addDesignVariable(robotPosSpline.designVariable(i), false);\n      }\n\n      // set up wall position\n      double wallPosition = true_w + sm::random::normal();\n      std::cout << \"Noisy wall position : \" << wallPosition << std::endl;\n\n      // First, create a design variable for the wall position.\n      boost::shared_ptr<aslam::backend::Scalar> dv_w(new aslam::backend::Scalar(true_w));\n      // Setting this active means we estimate it.\n      dv_w->setActive(true);\n      // Add it to the optimization problem.\n      problem->addDesignVariable(dv_w.get(), false);\n\n      // Now create a prior for this initial state.\n      auto vecPosExpr = robotPosSpline.getExpressionFactoryAt<0>(0).getValueExpression(0);\n      boost::shared_ptr<aslam::backend::ErrorTermPriorBST> prior(new aslam::backend::ErrorTermPriorBST(vecPosExpr, true_x_k[0], sigma_x * sigma_x));\n      // and add it to the problem.\n      problem->addErrorTerm(prior);\n\n      // Now march through the states creating design variables,\n      // odometry error terms and measurement error terms.\n      for(int k = 0; k < K; ++k)\n      {\n        // Create expression factory at time k, prepared for time derivatives up to 1 (for that we need the \"<1>\").\n        auto exprFactory = robotPosSpline.getExpressionFactoryAt<1>(k);\n\n        // Create odometry error via ErrorTermMotionBST\n        auto vecVelExpr = exprFactory.getValueExpression(1); // 1 => first derivative of position ~ robot velocity\n        boost::shared_ptr<aslam::backend::ErrorTermMotionBST> em(new aslam::backend::ErrorTermMotionBST(vecVelExpr, u_k[k], sigma_u * sigma_u));\n        problem->addErrorTerm(em);\n\n        // Create observation error using expressions and toErrorTerm to create an ExpressionErrorTerm\n        auto vecPosExpr = exprFactory.getValueExpression(0); // 0 => spline value itself ~ robot position\n        // We want to compute an error term e := dv_w / vecPosExpr[0] - y_k[k] + v, with v ~ N(0, sigma_n)\n        problem->addErrorTerm(toErrorTerm(dv_w->toExpression() / vecPosExpr.toScalarExpression<0>() - y_k[k], 1.0 / (sigma_n * sigma_n)));\n      }\n\n      // Now we have a valid optimization problem full of design variables and error terms.\n      // Create some optimization options.\n      aslam::backend::Optimizer2Options options;\n      options.verbose = true;\n      options.linearSystemSolver.reset(new aslam::backend::DenseQrLinearSystemSolver());\n//      options.levenbergMarquardtLambdaInit = 10;\n      options.doSchurComplement = false;\n//      options.doLevenbergMarquardt = true;\n      // Force it to over-optimize\n      options.convergenceDeltaX = 1e-12;\n      options.convergenceDeltaError = 1e-12;\n      // Then create the optimizer and go!\n      aslam::backend::Optimizer2 optimizer(options);\n      optimizer.setProblem(problem);\n\n      optimizer.optimize();\n\n      // the wall is at\n      std::cout << \"After optimization, the wall is at: \" << std::endl << dv_w->toExpression().toScalar() << std::endl;\n\n      for(int i = 0; i < K; i++)\n      {\n        // This time we don't need expressions because we are only going to print the values. There fore we only create an \"evaluator\" instead of an expression factory.\n        // Create evaluator at time k, supporting time derivatives up to 1 (for that we need the \"<1>\").\n        auto evaluator = robotPosSpline.getEvaluatorAt<1>(i);\n        auto vecPos = evaluator.evalD(0);\n        auto vecVel = evaluator.evalD(1);\n\n        std::cout << \"Robot at \" << i << \" is: \" << vecPos(0) << std::endl;\n        std::cout << \"Velocity at \" << i << \" is: \" << vecVel(0) << std::endl;\n      }\n    }\n  catch(const std::exception & e)\n    {\n      std::cout << \"Exception during processing: \" << e.what();\n      return 1;\n    }\n\n  std::cout << \"Processing completed successfully\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "03dbf00d1dc5861cd551de55edb4acdc333a4a28", "size": 6665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_backend_bsplines_tutorial/src/exampleBST.cpp", "max_stars_repo_name": "Curium-sg/aslam_splines", "max_stars_repo_head_hexsha": "d2c8c69d28d2f742b1d96a6a4e43a5c5112497af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aslam_backend_bsplines_tutorial/src/exampleBST.cpp", "max_issues_repo_name": "Curium-sg/aslam_splines", "max_issues_repo_head_hexsha": "d2c8c69d28d2f742b1d96a6a4e43a5c5112497af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aslam_backend_bsplines_tutorial/src/exampleBST.cpp", "max_forks_repo_name": "Curium-sg/aslam_splines", "max_forks_repo_head_hexsha": "d2c8c69d28d2f742b1d96a6a4e43a5c5112497af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.75, "max_line_length": 168, "alphanum_fraction": 0.648612153, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5716579699299694}}
{"text": "#ifndef _FITTING_HPP_\n#define _FITTING_HPP_\n\n#include <Eigen/Dense>\n#include \"Eigen/Spline/Spline.h\"\n#include \"Eigen/Spline/SplineFitting.h\"\n\n#include <boost/function.hpp>\n\nusing namespace std;\n\nnamespace spline_planner {\n\n  template<unsigned int D>\n  class Spline3D {\n  public:\n    typedef Eigen::Spline3d SplineType;\n\n    typedef boost::function<void(double, double, const Eigen::MatrixXd&)> SampleCallbackType;\n\n    /*\n     * points: input points for fitting spline\n     */\n    Spline3D(const Eigen::MatrixXd &points, const Eigen::MatrixXd &derivatives, const Eigen::VectorXi &index) {\n      this->spline_ = Eigen::SplineFitting<Spline3D::SplineType>::InterpolateWithDerivatives(points, derivatives,\n                                                                                             index, D);\n    }\n\n    /*\n     * points: input points for fitting spline\n     */\n    Spline3D(const Eigen::MatrixXd &points) {\n      Spline3D::SplineType::KnotVectorType chord_vector;\n      Eigen::ChordLengths(points, chord_vector);\n\n      this->spline_ = Eigen::SplineFitting<Spline3D::SplineType>::Interpolate(points, D, chord_vector);\n    }\n\n    void Sample(SampleCallbackType callback, double sample_ds = 0.1, double s_limit = 100.0, unsigned int degree = D, double dt = 0.01) {\n      std::size_t i = 0;\n      double t = 0.0;\n      double s = 0.0;\n      double last_s = 0.0;\n      double last_deriv1_norm = 0;\n      while ((t = i++ * dt) <= 1 && s <= s_limit) {\n        const Eigen::MatrixXd& derivs = spline_.derivatives(t, degree);\n        double deriv1_norm = static_cast<const Eigen::VectorXd&>(derivs.col(1)).norm();\n        if (t > 1e-7) {\n          s += 0.5 * (deriv1_norm + last_deriv1_norm) * dt;\n        }\n        last_deriv1_norm = deriv1_norm;\n\n        if ((s - last_s) >= sample_ds || (i * dt) > 1.0 || s <= 1e-7) {\n          last_s = s;\n          callback(t, s, derivs);\n        }\n      }\n    }\n\n  private:\n    SplineType spline_;\n\n  };\n}\n\n#endif\n", "meta": {"hexsha": "b27c7d21bf61cc3e37e6e8ca88753cca212eca55", "size": 1960, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spline_planner/src/eigen_spline.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": "spline_planner/src/eigen_spline.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": "spline_planner/src/eigen_spline.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": 29.2537313433, "max_line_length": 137, "alphanum_fraction": 0.6051020408, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5716579696553323}}
{"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": "\ufeff//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// See LICENSE file in the project root for full license information.\n//\n#include <boost/test/unit_test.hpp>\n\n#include \"LayerTests.hpp\"\n#include \"test/TensorHelpers.hpp\"\n\n#include \"backends/RefWorkloadFactory.hpp\"\n\n#include \"test/UnitTests.hpp\"\n\nBOOST_AUTO_TEST_SUITE(Compute_Reference)\nusing FactoryType = armnn::RefWorkloadFactory;\n\n// ============================================================================\n// UNIT tests\n\n// Convolution\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5, SimpleConvolution2d3x5Test, true)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x5Uint8, SimpleConvolution2d3x5Uint8Test, true)\n\nARMNN_AUTO_TEST_CASE(UnbiasedConvolution2d, SimpleConvolution2d3x5Test, false)\nARMNN_AUTO_TEST_CASE(UnbiasedConvolutionUint8, SimpleConvolution2d3x5Uint8Test, false)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution1d, Convolution1dTest, true)\nARMNN_AUTO_TEST_CASE(SimpleConvolution1dUint8, Convolution1dUint8Test, true)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3, SimpleConvolution2d3x3Test, true)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2d3x3Uint8, SimpleConvolution2d3x3Uint8Test, true)\n\nARMNN_AUTO_TEST_CASE(UnbiasedConvolution2dSquare, SimpleConvolution2d3x3Test, false)\n\nARMNN_AUTO_TEST_CASE(SimpleConvolution2dAsymmetricPaddingLargerThanHalfKernelSize,\n    Convolution2dAsymmetricPaddingLargerThanHalfKernelSizeTest)\nARMNN_AUTO_TEST_CASE(SimpleConvolution2dAsymmetricPadding, Convolution2dAsymmetricPaddingTest)\n\n// Depthwise Convolution\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2d, DepthwiseConvolution2dTest, true)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dUint8, DepthwiseConvolution2dUint8Test, true)\n\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2d, DepthwiseConvolution2dTest, false)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dUint8, DepthwiseConvolution2dUint8Test, false)\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul1, DepthwiseConvolution2dDepthMul1Test, true)\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dDepthMul1Uint8, DepthwiseConvolution2dDepthMul1Uint8Test, true)\n\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dDepthMul1, DepthwiseConvolution2dDepthMul1Test, false)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dDepthMul1Uint8, DepthwiseConvolution2dDepthMul1Uint8Test, false)\n\nARMNN_AUTO_TEST_CASE(DepthwiseConvolution2dAsymmetric, DepthwiseConvolution2dAsymmetricTest, true)\nARMNN_AUTO_TEST_CASE(UnbiasedDepthwiseConvolution2dAsymmetric, DepthwiseConvolution2dAsymmetricTest, false)\n\n// Pooling\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize2x2Stride2x2, SimpleMaxPooling2dSize2x2Stride2x2Test, false)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize2x2Stride2x2Uint8, SimpleMaxPooling2dSize2x2Stride2x2Uint8Test, false)\n\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize3x3Stride2x4, SimpleMaxPooling2dSize3x3Stride2x4Test, false)\nARMNN_AUTO_TEST_CASE(SimpleMaxPooling2dSize3x3Stride2x4Uint8, SimpleMaxPooling2dSize3x3Stride2x4Uint8Test, false)\n\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleMaxPooling2d, IgnorePaddingSimpleMaxPooling2dTest)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleMaxPooling2dUint8, IgnorePaddingSimpleMaxPooling2dUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingMaxPooling2dSize3, IgnorePaddingMaxPooling2dSize3Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingMaxPooling2dSize3Uint8, IgnorePaddingMaxPooling2dSize3Uint8Test)\n\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2d, IgnorePaddingSimpleAveragePooling2dTest)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2dUint8, IgnorePaddingSimpleAveragePooling2dUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2dNoPadding, IgnorePaddingSimpleAveragePooling2dNoPaddingTest)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleAveragePooling2dNoPaddingUint8,\n    IgnorePaddingSimpleAveragePooling2dNoPaddingUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3, IgnorePaddingAveragePooling2dSize3Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3Uint8, IgnorePaddingAveragePooling2dSize3Uint8Test)\n\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleL2Pooling2d, IgnorePaddingSimpleL2Pooling2dTest)\nARMNN_AUTO_TEST_CASE(IgnorePaddingSimpleL2Pooling2dUint8, IgnorePaddingSimpleL2Pooling2dUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingL2Pooling2dSize3, IgnorePaddingL2Pooling2dSize3Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingL2Pooling2dSize3Uint8, IgnorePaddingL2Pooling2dSize3Uint8Test)\n\nARMNN_AUTO_TEST_CASE(SimpleAveragePooling2d, SimpleAveragePooling2dTest)\nARMNN_AUTO_TEST_CASE(SimpleAveragePooling2dUint8, SimpleAveragePooling2dUint8Test)\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3x2Stride2x2,\n                     IgnorePaddingAveragePooling2dSize3x2Stride2x2Test, false)\nARMNN_AUTO_TEST_CASE(IgnorePaddingAveragePooling2dSize3x2Stride2x2NoPadding,\n                     IgnorePaddingAveragePooling2dSize3x2Stride2x2Test, true)\n\nARMNN_AUTO_TEST_CASE(LargeTensorsAveragePooling2d, LargeTensorsAveragePooling2dTest)\nARMNN_AUTO_TEST_CASE(LargeTensorsAveragePooling2dUint8, LargeTensorsAveragePooling2dUint8Test)\n\nARMNN_AUTO_TEST_CASE(SimpleL2Pooling2d, SimpleL2Pooling2dTest)\nARMNN_AUTO_TEST_CASE(SimpleL2Pooling2dUint8, SimpleL2Pooling2dUint8Test)\n\nARMNN_AUTO_TEST_CASE(L2Pooling2dSize7, L2Pooling2dSize7Test)\nARMNN_AUTO_TEST_CASE(L2Pooling2dSize7Uint8, L2Pooling2dSize7Uint8Test)\n\nARMNN_AUTO_TEST_CASE(AsymmNonSquarePooling2d, AsymmetricNonSquarePooling2dTest)\nARMNN_AUTO_TEST_CASE(AsymmNonSquarePooling2dUint8, AsymmetricNonSquarePooling2dUint8Test)\n\n// Activation\nARMNN_AUTO_TEST_CASE(ConstantLinearActivation, ConstantLinearActivationTest)\nARMNN_AUTO_TEST_CASE(ConstantLinearActivationUint8, ConstantLinearActivationUint8Test)\n\nARMNN_AUTO_TEST_CASE(SimpleNormalizationAcross, SimpleNormalizationAcrossTest)\nARMNN_AUTO_TEST_CASE(SimpleNormalizationWithin, SimpleNormalizationWithinTest)\n\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxBeta1, SimpleSoftmaxTest, 1.0f)\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxBeta2, SimpleSoftmaxTest, 2.0f)\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxBeta1Uint8, SimpleSoftmaxUint8Test, 1.0f)\nARMNN_AUTO_TEST_CASE(SimpleSoftmaxBeta2Uint8, SimpleSoftmaxUint8Test, 2.0f)\n\nARMNN_AUTO_TEST_CASE(SimpleSigmoid, SimpleSigmoidTest)\nARMNN_AUTO_TEST_CASE(SimpleSigmoidUint8, SimpleSigmoidUint8Test)\n\nARMNN_AUTO_TEST_CASE(ReLu1, BoundedReLuUpperAndLowerBoundTest)\nARMNN_AUTO_TEST_CASE(ReLu6, BoundedReLuUpperBoundOnlyTest)\nARMNN_AUTO_TEST_CASE(ReLu1Uint8, BoundedReLuUint8UpperAndLowerBoundTest)\nARMNN_AUTO_TEST_CASE(ReLu6Uint8, BoundedReLuUint8UpperBoundOnlyTest)\n\n// Fully Conected\nARMNN_AUTO_TEST_CASE(SimpleFullyConnected, FullyConnectedFloat32Test, false, false)\nARMNN_AUTO_TEST_CASE(FullyConnectedUint8, FullyConnectedUint8Test, false)\nARMNN_AUTO_TEST_CASE(SimpleFullyConnectedWithBias, FullyConnectedFloat32Test, true, false)\nARMNN_AUTO_TEST_CASE(FullyConnectedBiasedUint8, FullyConnectedUint8Test, true)\nARMNN_AUTO_TEST_CASE(SimpleFullyConnectedWithTranspose, FullyConnectedFloat32Test, false, true)\n\nARMNN_AUTO_TEST_CASE(FullyConnectedLarge, FullyConnectedLargeTest, false)\nARMNN_AUTO_TEST_CASE(FullyConnectedLargeTransposed, FullyConnectedLargeTest, true)\n\n// Splitter\nBOOST_AUTO_TEST_CASE(SimpleSplitter)\n{\n    armnn::RefWorkloadFactory workloadFactory;\n    auto testResult = SplitterTest(workloadFactory);\n    for (unsigned int i = 0; i < testResult.size(); ++i)\n    {\n        BOOST_TEST(CompareTensors(testResult[i].output, testResult[i].outputExpected));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(SplitterUint8)\n{\n    armnn::RefWorkloadFactory workloadFactory;\n    auto testResult = SplitterUint8Test(workloadFactory);\n    for (unsigned int i = 0; i < testResult.size(); ++i)\n    {\n        BOOST_TEST(CompareTensors(testResult[i].output, testResult[i].outputExpected));\n    }\n}\n\nARMNN_AUTO_TEST_CASE(CopyViaSplitter, CopyViaSplitterTest)\nARMNN_AUTO_TEST_CASE(CopyViaSplitterUint8, CopyViaSplitterUint8Test)\n\n// Merger\nARMNN_AUTO_TEST_CASE(SimpleMerger, MergerTest)\nARMNN_AUTO_TEST_CASE(MergerUint8, MergerUint8Test)\n\n// Add\nARMNN_AUTO_TEST_CASE(SimpleAdd, AdditionTest)\nARMNN_AUTO_TEST_CASE(AddBroadcast1Element, AdditionBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(AddBroadcast, AdditionBroadcastTest)\n\nARMNN_AUTO_TEST_CASE(AdditionUint8, AdditionUint8Test)\nARMNN_AUTO_TEST_CASE(AddBroadcastUint8, AdditionBroadcastUint8Test)\nARMNN_AUTO_TEST_CASE(AddBroadcast1ElementUint8, AdditionBroadcast1ElementUint8Test)\n\n// Mul\nARMNN_AUTO_TEST_CASE(SimpleMultiplication, MultiplicationTest)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1Element, MultiplicationBroadcast1ElementTest)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1DVector, MultiplicationBroadcast1DVectorTest)\nARMNN_AUTO_TEST_CASE(MultiplicationUint8, MultiplicationUint8Test)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1ElementUint8, MultiplicationBroadcast1ElementUint8Test)\nARMNN_AUTO_TEST_CASE(MultiplicationBroadcast1DVectorUint8, MultiplicationBroadcast1DVectorUint8Test)\n\n// Batch Norm\nARMNN_AUTO_TEST_CASE(BatchNorm, BatchNormTest)\nARMNN_AUTO_TEST_CASE(BatchNormUint8, BatchNormUint8Test)\n\n// Resize Bilinear\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinear, SimpleResizeBilinearTest)\nARMNN_AUTO_TEST_CASE(SimpleResizeBilinearUint8, SimpleResizeBilinearUint8Test)\nARMNN_AUTO_TEST_CASE(ResizeBilinearNop, ResizeBilinearNopTest)\nARMNN_AUTO_TEST_CASE(ResizeBilinearNopUint8, ResizeBilinearNopUint8Test)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMin, ResizeBilinearSqMinTest)\nARMNN_AUTO_TEST_CASE(ResizeBilinearSqMinUint8, ResizeBilinearSqMinUint8Test)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMin, ResizeBilinearMinTest)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMinUint8, ResizeBilinearMinUint8Test)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMag, ResizeBilinearMagTest)\nARMNN_AUTO_TEST_CASE(ResizeBilinearMagUint8, ResizeBilinearMagUint8Test)\n\n// Fake Quantization\nARMNN_AUTO_TEST_CASE(FakeQuantization, FakeQuantizationTest)\n\n// L2 Noramlization\nARMNN_AUTO_TEST_CASE(L2Normalization1d, L2Normalization1dTest)\nARMNN_AUTO_TEST_CASE(L2Normalization2d, L2Normalization2dTest)\nARMNN_AUTO_TEST_CASE(L2Normalization3d, L2Normalization3dTest)\nARMNN_AUTO_TEST_CASE(L2Normalization4d, L2Normalization4dTest)\n\n// Constant\nARMNN_AUTO_TEST_CASE(Constant, ConstantTest)\nARMNN_AUTO_TEST_CASE(ConstantUint8, ConstantUint8Test)\n\n// Concat\nARMNN_AUTO_TEST_CASE(Concatenation1d, Concatenation1dTest)\nARMNN_AUTO_TEST_CASE(Concatenation1dUint8, Concatenation1dUint8Test)\n\nARMNN_AUTO_TEST_CASE(Concatenation2dDim0, Concatenation2dDim0Test)\nARMNN_AUTO_TEST_CASE(Concatenation2dDim0Uint8, Concatenation2dDim0Uint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation2dDim1, Concatenation2dDim1Test)\nARMNN_AUTO_TEST_CASE(Concatenation2dDim1Uint8, Concatenation2dDim1Uint8Test)\n\nARMNN_AUTO_TEST_CASE(Concatenation2dDim0DiffInputDims, Concatenation2dDim0DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concatenation2dDim0DiffInputDimsUint8, Concatenation2dDim0DiffInputDimsUint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation2dDim1DiffInputDims, Concatenation2dDim1DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concatenation2dDim1DiffInputDimsUint8, Concatenation2dDim1DiffInputDimsUint8Test)\n\nARMNN_AUTO_TEST_CASE(Concatenation3dDim0, Concatenation3dDim0Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim0Uint8, Concatenation3dDim0Uint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim1, Concatenation3dDim1Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim1Uint8, Concatenation3dDim1Uint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim2, Concatenation3dDim2Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim2Uint8, Concatenation3dDim2Uint8Test)\n\nARMNN_AUTO_TEST_CASE(Concatenation3dDim0DiffInputDims, Concatenation3dDim0DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim0DiffInputDimsUint8, Concatenation3dDim0DiffInputDimsUint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim1DiffInputDims, Concatenation3dDim1DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim1DiffInputDimsUint8, Concatenation3dDim1DiffInputDimsUint8Test)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim2DiffInputDims, Concatenation3dDim2DiffInputDimsTest)\nARMNN_AUTO_TEST_CASE(Concatenation3dDim2DiffInputDimsUint8, Concatenation3dDim2DiffInputDimsUint8Test)\n\n// Floor\nARMNN_AUTO_TEST_CASE(SimpleFloor, SimpleFloorTest)\n\n// Reshape\nARMNN_AUTO_TEST_CASE(SimpleReshapeFloat32, SimpleReshapeFloat32Test)\nARMNN_AUTO_TEST_CASE(SimpleReshapeUint8, SimpleReshapeUint8Test)\n\n// Permute\nARMNN_AUTO_TEST_CASE(SimplePermuteFloat32, SimplePermuteFloat32Test)\nARMNN_AUTO_TEST_CASE(SimplePermuteUint8, SimplePermuteUint8Test)\nARMNN_AUTO_TEST_CASE(PermuteFloat32ValueSet1, PermuteFloat32ValueSet1Test)\nARMNN_AUTO_TEST_CASE(PermuteFloat32ValueSet2, PermuteFloat32ValueSet2Test)\nARMNN_AUTO_TEST_CASE(PermuteFloat32ValueSet3, PermuteFloat32ValueSet3Test)\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "b60483a4d95473457c9d6156c7eb624ae80dbab9", "size": 12575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/armnn/backends/test/Reference.cpp", "max_stars_repo_name": "Air000/armnn_s32v", "max_stars_repo_head_hexsha": "ec3ee60825d6b7642a70987c4911944cef7a3ee6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-19T08:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-19T08:44:28.000Z", "max_issues_repo_path": "src/armnn/backends/test/Reference.cpp", "max_issues_repo_name": "Air000/armnn_s32v", "max_issues_repo_head_hexsha": "ec3ee60825d6b7642a70987c4911944cef7a3ee6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/armnn/backends/test/Reference.cpp", "max_forks_repo_name": "Air000/armnn_s32v", "max_forks_repo_head_hexsha": "ec3ee60825d6b7642a70987c4911944cef7a3ee6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-11T05:58:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-11T05:58:56.000Z", "avg_line_length": 51.1178861789, "max_line_length": 116, "alphanum_fraction": 0.8971769384, "num_tokens": 3575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5716579586075072}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef 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 \"partitioning_1d.h\"\n#include <boost/assert.hpp>\n\n/*\n * get the first and last elements within a partition\n * assuming 0 <= part_id < partinfo._num_partitions\n*/\nPartition1D get_partition(const int part_id, const PartitioningInfo& partinfo) {\n\t    Partition1D part;\n\t\tBOOST_ASSERT_MSG(part_id>=0, \"negative partition id specified\");\n\t\tBOOST_ASSERT_MSG(part_id < partinfo._num_partitions, \"requested partition with higher id than existing partitions\");\n\n\t\t// compute first element\n\t\tint overhead = part_id - partinfo._num_partitions_full_load;\n\t\tif (overhead >0) {\n\t\t\t    part._first_id= part_id * partinfo._size_full_load - overhead;\n\t\t}\n\t\telse {\n\t\t\t    part._first_id= part_id *partinfo._size_full_load;\n\t\t}\n\n\t\t// compute last element\n\t\tif (part_id < partinfo._num_partitions_full_load) {\n\t\t\t    part._last_id = part._first_id + partinfo._size_full_load-1; // -1 as last element is inclusive in the range\n\t\t}\n\t\telse {\n\t\t\t    part._last_id = part._first_id + partinfo._size_full_load-2; // -2 as last element is inclusive and the partition is of reduced (-1) size\n\t\t}\n\n\t\treturn part;\n}\n\nPartitioningInfo split_work(const int num_partitions, const int ids_to_process) {\n\treturn {\n\t\t._num_partitions = num_partitions,\n\t\t._num_partitions_full_load = ids_to_process - ((ids_to_process/num_partitions) * num_partitions),\n\t\t._size_full_load = (ids_to_process/num_partitions) + 1\n\t};\n}\n\nint get_workload(const int part_id, const PartitioningInfo& partinfo) {\n\tif (part_id < partinfo._num_partitions_full_load) {\n\t\treturn partinfo._size_full_load;\n\t}\n\telse {\n\t\treturn partinfo._size_full_load-1;\n\t}\n}\n\n", "meta": {"hexsha": "785b0d7e011a3b84d328cc0c4698efb4e818f48a", "size": 1602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scrimppp/src/partitioning_1d.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/partitioning_1d.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/partitioning_1d.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": 32.04, "max_line_length": 144, "alphanum_fraction": 0.7453183521, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.5715558321804839}}
{"text": "\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Sparse>\n\n#include <random>\n#include <iostream>\n#include <vector>\n#include <set>\n\n#include <igl/cotmatrix.h>\n#include <igl/boundary_loop.h>\n\n#include \"ElasticShellMaterial.h\"\n#include \"../MeshConnectivity.h\"\n#include \"../GeometryDerivatives.h\"\n\ndouble ElasticShellMaterial::cotan_v0(const Eigen::Vector3d v0, const Eigen::Vector3d v1, const Eigen::Vector3d v2)\n{\n    double e0 = (v2 - v1).norm(); \n    double e1 = (v2 - v0).norm(); \n    double e2 = (v0 - v1).norm(); \n    double angle0 = acos((e1 * e1 + e2 * e2 - e0 * e0) / (2 * e1 * e2));\n    double cot = 1.0 / tan(angle0);\n        \n    return cot;\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "df68144d624c1fe0a09ff4c66f0280204ec8c84c", "size": 704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ElasticShell/ElasticShellMaterial.cpp", "max_stars_repo_name": "csyzzkdcz/effective-garbanzo", "max_stars_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ElasticShell/ElasticShellMaterial.cpp", "max_issues_repo_name": "csyzzkdcz/effective-garbanzo", "max_issues_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ElasticShell/ElasticShellMaterial.cpp", "max_forks_repo_name": "csyzzkdcz/effective-garbanzo", "max_forks_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1142857143, "max_line_length": 115, "alphanum_fraction": 0.6477272727, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5715487825058252}}
{"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 <cstdlib>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main (const int argc, const char** argv) {\n    if (argc > 2) {\n        using namespace boost::numeric::ublas;\n\n        matrix<double> m(atoi(argv[1]), atoi(argv[2])); // build\n        for (unsigned i = 0; i < m.size1(); i++)\n            for (unsigned j = 0; j < m.size2(); j++)\n                m(i, j) = 1.0 + i + j; // fill\n        std::cout << m << std::endl; // print\n        return EXIT_SUCCESS;\n    }\n\n    return EXIT_FAILURE;\n}\n", "meta": {"hexsha": "22013d4f5bc1c94023e94babd020ff6a4c1429a2", "size": 538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/create-a-two-dimensional-array-at-runtime-4.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "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++/create-a-two-dimensional-array-at-runtime-4.cpp", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/C++/create-a-two-dimensional-array-at-runtime-4.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": 28.3157894737, "max_line_length": 64, "alphanum_fraction": 0.5408921933, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.571498641288926}}
{"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": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Copyright 2012 The MITRE Corporation                                      *\n *                                                                           *\n * Licensed under the Apache License, Version 2.0 (the \"License\");           *\n * you may not use this file except in compliance with the License.          *\n * You may obtain a copy of the License at                                   *\n *                                                                           *\n *     http://www.apache.org/licenses/LICENSE-2.0                            *\n *                                                                           *\n * Unless required by applicable law or agreed to in writing, software       *\n * distributed under the License is distributed on an \"AS IS\" BASIS,         *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *\n * See the License for the specific language governing permissions and       *\n * limitations under the License.                                            *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <Eigen/Dense>\n\n#include <openbr/plugins/openbr_internal.h>\n\nnamespace br\n{\n\n/*!\n * \\ingroup distances\n * \\brief L2 distance computed using eigen.\n * \\author Josh Klontz \\cite jklontz\n */\nclass L2Distance : public UntrainableDistance\n{\n    Q_OBJECT\n\n    float compare(const cv::Mat &a, const cv::Mat &b) const\n    {\n        const int size = a.rows * a.cols;\n        Eigen::Map<Eigen::VectorXf> aMap((float*)a.data, size);\n        Eigen::Map<Eigen::VectorXf> bMap((float*)b.data, size);\n        return (aMap-bMap).squaredNorm();\n    }\n};\n\nBR_REGISTER(Distance, L2Distance)\n\n} // namespace br\n\n#include \"distance/L2.moc\"\n", "meta": {"hexsha": "a966c20e324f7e61cc63714fe896a70c2107170d", "size": 1814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbr/plugins/distance/L2.cpp", "max_stars_repo_name": "kassemitani/openbr", "max_stars_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1883.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:33:37.000Z", "max_issues_repo_path": "openbr/plugins/distance/L2.cpp", "max_issues_repo_name": "kassemitani/openbr", "max_issues_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 272.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T09:53:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T08:04:33.000Z", "max_forks_repo_path": "openbr/plugins/distance/L2.cpp", "max_forks_repo_name": "kassemitani/openbr", "max_forks_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 718.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T18:51:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T08:10:53.000Z", "avg_line_length": 38.5957446809, "max_line_length": 79, "alphanum_fraction": 0.4740904079, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5714625694232929}}
{"text": "\ufeff#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\u2212v\u2212w\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": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_ISNORMAL_HPP\n#define BOOST_MATH_ISNORMAL_HPP\n\n#include <cmath>\n#include <limits>\n#include <type_traits>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n#include <boost/math/ccmath/abs.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n\nnamespace boost::math::ccmath {\n\ntemplate <typename T>\ninline constexpr bool isnormal(T x)\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))\n    {   \n        return x == T(0) ? false :\n               boost::math::ccmath::isinf(x) ? false :\n               boost::math::ccmath::isnan(x) ? false :\n               boost::math::ccmath::abs(x) < (std::numeric_limits<T>::min)() ? false : true;\n    }\n    else\n    {\n        using std::isnormal;\n\n        if constexpr (!std::is_integral_v<T>)\n        {\n            return isnormal(x);\n        }\n        else\n        {\n            return isnormal(static_cast<double>(x));\n        }\n    }\n}\n}\n\n#endif // BOOST_MATH_ISNORMAL_HPP\n", "meta": {"hexsha": "f352a0466a744d678a9b6bc2407a37fab44f56ab", "size": 1186, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/isnormal.hpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "include/boost/math/ccmath/isnormal.hpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "include/boost/math/ccmath/isnormal.hpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 25.7826086957, "max_line_length": 92, "alphanum_fraction": 0.6323777403, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.571462564313038}}
{"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": "#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 <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nusing Mat = Eigen::MatrixXi;\n\nstruct Fold {\n  enum dir { column, row };\n\n  dir d;\n  int coord;\n};\n\nMat linesToMat(std::vector<std::string> &lines) {\n  std::vector<std::pair<int, int>> coord;\n  int max_x = 0;\n  int max_y = 0;\n  for (auto &l : lines) {\n    if (l.empty()) {\n      break;\n    }\n    for (char &c : l) {\n      if (c == ',') {\n        c = ' ';\n      }\n    }\n\n    int x;\n    int y;\n    std::stringstream ss(l);\n    ss >> x;\n    ss >> y;\n\n    max_x = std::max(x, max_x);\n    max_y = std::max(y, max_y);\n    coord.push_back({x, y});\n  }\n\n  Mat out(max_y + 1, max_x + 1);\n  out.setZero();\n\n  for (auto &[c, r] : coord) {\n    out(r, c) = 1;\n  }\n\n  return out;\n}\n\nstd::vector<Fold> linesToFolds(std::vector<std::string> const &lines) {\n  std::vector<Fold> folds;\n  for (auto const &l : lines) {\n    Fold f;\n    auto pos = l.find_first_of('=');\n    std::string snum(l.data() + pos + 1, l.data() + l.size());\n    f.coord = std::stoi(snum);\n\n    auto pos2 = l.find_last_of(' ');\n    std::string sdir(l.data() + pos2 + 1, l.data() + pos);\n\n    if (sdir == \"x\") {\n      f.d = Fold::column;\n    } else if (sdir == \"y\") {\n      f.d = Fold::row;\n    } else {\n      fmt::print(\"Error in fold parsing\\n\");\n      std::abort();\n    }\n\n    folds.push_back(f);\n  }\n  return folds;\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  auto mat = linesToMat(out);\n  auto blank = std::find_if(out.begin(), out.end(),\n                            [](std::string const &l) { return l.empty(); });\n  out.erase(out.begin(), blank + 1);\n  return std::make_pair(mat, linesToFolds(out));\n}\n\nint main(int _, char **argv) {\n  auto [M, folds] = parseFile(argv[1]);\n  fmt::print(\"M({}, {})\\n\", M.rows(), M.cols());\n  for (auto const &f : folds) {\n    fmt::print(\"{}: {}\\n\", f.d, f.coord);\n  }\n\n  Mat Mc = M;\n  auto sum = 0;\n  for (auto const &f : folds) {\n    auto coord = f.coord;\n    if (f.d == Fold::column) {\n      auto r = coord + 1;\n      auto l = coord - 1;\n      if (coord >= ((Mc.cols() - 1) / 2)) { // Right side has fewer\n        while (r < Mc.cols() && l >= 0) {\n          Mc.col(l--) += Mc.col(r++);\n        }\n        Mc = Mc.leftCols(coord).eval();\n      } else { // left side has fewer\n        while (r < Mc.cols() && l >= 0) {\n          Mc.col(r++) += Mc.col(l--);\n        }\n        Mc = Mc.rightCols(coord).eval();\n      }\n    } else {\n      auto t = coord - 1;\n      auto b = coord + 1;\n      if (coord >= ((Mc.rows() - 1) / 2)) { // bottom side has fewer\n        while (b < Mc.rows() && t >= 0) {\n          Mc.row(t--) += Mc.row(b++);\n        }\n        Mc = Mc.topRows(coord).eval();\n      } else { // top side has fewer\n        while (b < Mc.rows() && b >= 0) {\n          Mc.row(b++) += Mc.row(t--);\n        }\n        Mc = Mc.bottomRows(coord).eval();\n      }\n    }\n\n    for (auto i = 0; i < Mc.size(); ++i) {\n      if (Mc.data()[i] > 1) {\n        Mc.data()[i] = 1;\n      }\n    }\n\n    if(sum == 0){\n      sum = Mc.sum();\n    }\n  }\n\n  fmt::print(\"Part 1: {}\\n\", sum);\n  fmt::print(\"Part 2\\n\");\n  for(auto r = 0; r < Mc.rows(); ++r){\n    for(auto c = 0; c < Mc.cols(); ++c){\n      if(Mc(r,c) == 1){\n        std::cout << \"#\";\n      } else {\n        std::cout << \" \";\n      }\n    }\n    std::cout << \"\\n\";\n  }\n}\n", "meta": {"hexsha": "f49cc666800ba75ce3bb73b08c8d21a08aa89ea5", "size": 3662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/day13/day13.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/day13/day13.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/day13/day13.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.9281437126, "max_line_length": 76, "alphanum_fraction": 0.4868924085, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5714625601432515}}
{"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  // // \u5b57\u6bcd D \u8868\u793a\u6570\u503c\u7c7b\u578b\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": "//==================================================================================================\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_ACOSH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACOSH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-hyperbolic\n    Function object implementing acosh capabilities\n\n    Returns the hyperbolic cosine argument: \\f$\\log(x+\\sqrt{x^2-1})\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = acosh(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = log(x+sqrt{minusone(sqr(x))});\n    @endcode\n\n    @see log, sqrt, cosh, minusone\n\n  **/\n  const boost::dispatch::functor<tag::acosh_> acosh = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/acosh.hpp>\n#include <boost/simd/function/simd/acosh.hpp>\n\n#endif\n", "meta": {"hexsha": "5c091f80bfad1f2ff239060f9e75ccc80a128938", "size": 1150, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/acosh.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/function/acosh.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/acosh.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5490196078, "max_line_length": 100, "alphanum_fraction": 0.5739130435, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5713921707214474}}
{"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 \"boundary.hpp\"\n#include \"eigen_ext.hpp\"\n#include \"function.hpp\"\n#include \"integrate_func.hpp\"\n#include \"parameters.hpp\"\n#include \"stiff.hpp\"\n\n#include <cassert>\n#include <cstdlib>\n#include <iostream>\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/QR>\n#include <Eigen/Sparse>\n\n// TYPE DEFINITIONS\ntypedef Eigen::MatrixXd Mat;\ntypedef Eigen::VectorXd Vec;\ntypedef Eigen::MatrixXi MatI;\ntypedef Eigen::VectorXi VecI;\ntypedef Eigen::SparseMatrix<double, Eigen::RowMajor> SpMat;\n\nint main(int args, char *argv[]) {\n\n  // PRELIMINARIES\n  int max_iter = 1E+2; // 1E+3;\n  double tol_min = 1E-10;\n  double tol = 1;\n\n  // EXTRACT DATA\n  MatI nodes =\n      pear::load_csv<MatI>(\"/Users/hdeplaen/Documents/KULeuven/Project/\"\n                           \"the_winning_pear/imports/node.csv\");\n  MatI boundary =\n      pear::load_csv<MatI>(\"/Users/hdeplaen/Documents/KULeuven/Project/\"\n                           \"the_winning_pear/imports/boundary.csv\");\n  Mat points = pear::load_csv<Mat>(\"/Users/hdeplaen/Documents/KULeuven/Project/\"\n                                   \"the_winning_pear/imports/points.csv\");\n\n  int np = points.rows();\n  Vec xp(np);\n  Vec yp(np);\n  xp = points.col(0);\n  yp = points.col(1);\n\n  // INITIALIZE MATRICES\n  Mat Ku(np, np);\n  Mat Kv(np, np);\n  Mat int_F(np, np);\n  Vec Bu(np);\n  Vec Bv(np);\n  Mat Kbu(np, np);\n  Mat Kbv(np, np);\n\n  pear::stiff(xp, yp, nodes, Ku, Kv);\n  int_F = pear::int_func(xp, yp, nodes);\n  pear::boundary_vector(xp, yp, boundary, Bu, Bv, Kbu, Kbv);\n\n  // INITIAL SOLUTION\n  Vec Cu(np);\n  Vec Cv(np);\n  Vec sol(2 * np);\n  Vec sol_buff(2 * np);\n\n  Eigen::BiCGSTAB<Mat> solver;\n\n  solver.compute(Ku + (pear::Vmu / pear::Kmu) * int_F - Kbu);\n  Cu = solver.solve(Bu);\n\n  /* std::cout << Cu << std::endl; */\n\n  solver.compute(Kv - Kbv);\n  Cv = solver.solve(pear::rq * (pear::Vmu / pear::Kmu) * int_F * Cu + Bv);\n\n  std::cout << \"Initial solution computed\" << std::endl << std::endl;\n\n  // NON-LINEAR SOLUTION\n  Vec Ru(np);\n  Vec Rv(np);\n  Mat RudCu(np, np);\n  Mat RudCv(np, np);\n  Mat RvdCu(np, np);\n  Mat RvdCv(np, np);\n\n  Vec F(2 * np);\n  Mat JF(2 * np, 2 * np);\n\n  for (int iter = 0; iter < max_iter; iter++) {\n    pear::fun_diff(Cu, Cv, Ru, Rv, RudCu, RudCv, RvdCu, RvdCv);\n\n    F.block(0, 0, np, 1) = Ku * Cu + int_F * Ru - Kbu * Cu - Bu;\n    F.block(np, 0, np, 1) = Kv * Cv - int_F * Rv - Kbv * Cv - Bv;\n\n    JF.block(0, 0, np, np) = Ku + int_F * RudCu - Kbu;\n    JF.block(0, np, np, np) = int_F * RudCv;\n    JF.block(np, 0, np, np) = -int_F * RvdCu;\n    JF.block(np, np, np, np) = Kv - int_F * RvdCv - Kbv;\n\n    solver.compute(JF);\n\n    sol_buff.block(0, 0, np, 1) = Cu;\n    sol_buff.block(np, 0, np, 1) = Cv;\n\n    sol = sol_buff - solver.solve(F);\n\n    tol = (sol - sol_buff).norm();\n\n    std::cout << \"Iteration: \" << iter + 1 << std::endl;\n    std::cout << \"Tolerance: \" << tol << std::endl << std::endl;\n\n    if (tol < tol_min) {\n      break;\n    }\n\n    Cu = sol.block(0, 0, np, 1);\n    Cv = sol.block(np, 0, np, 1);\n  }\n\n  // EXPORTS\n  pear::write_csv<Vec>(\"/Users/hdeplaen/Documents/KULeuven/Project/\"\n                       \"the_winning_pear/exports/cu.csv\",\n                       Cu);\n\n  pear::write_csv<Vec>(\"/Users/hdeplaen/Documents/KULeuven/Project/\"\n                       \"the_winning_pear/exports/cv.csv\",\n                       Cv);\n  return 0;\n}\n", "meta": {"hexsha": "8dedb3bb07ff91413a715079eafb51f52c515447", "size": 3346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.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/main.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/main.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": 25.5419847328, "max_line_length": 80, "alphanum_fraction": 0.584279737, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5713261449370951}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/ARModel.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <vector>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass TransientExtraction\n{\n\n  using ARModel = algorithm::ARModel;\n  using MatrixXd = Eigen::MatrixXd;\n  using VectorXd = Eigen::VectorXd;\n\npublic:\n  void init(index order, index blockSize, index padSize)\n  {\n    mModel = ARModel(order);\n    prepareStream(blockSize, padSize);\n    mInitialized = true;\n  }\n\n  void setDetectionParameters(double power, double threshHi, double threshLo,\n                              index halfWindow = 7, index hold = 25)\n  {\n    mDetectPowerFactor = power;\n    mDetectThreshHi = threshHi;\n    mDetectThreshLo = threshLo;\n    mDetectHalfWindow = halfWindow;\n    mDetectHold = hold;\n  }\n\n  void prepareStream(index blockSize, index padSize)\n  {\n    mBlockSize = std::max(blockSize, modelOrder());\n    mPadSize = std::max(padSize, modelOrder());\n    resizeStorage();\n  }\n\n  index modelOrder() const { return static_cast<index>(mModel.order()); }\n  index blockSize() const { return mBlockSize; }\n  index hopSize() const { return mBlockSize - modelOrder(); }\n  index padSize() const { return mPadSize; }\n  index inputSize() const { return hopSize() + mPadSize; }\n  index analysisSize() const { return mBlockSize + mPadSize + mPadSize; }\n\n  const double* getDetect() const { return mDetect.data(); }\n  const double* getForwardError() const\n  {\n    return mForwardError.data() + modelOrder();\n  }\n  const double* getBackwardError() const\n  {\n    return mBackwardError.data() + modelOrder();\n  }\n  const double* getForwardWindowedError() const\n  {\n    return mForwardWindowedError.data();\n  }\n  const double* getBackwardWindowedError() const\n  {\n    return mBackwardWindowedError.data();\n  }\n\n  index detect(const double* input, index inSize)\n  {\n    frame(input, inSize);\n    analyze();\n    detection();\n    return mCount;\n  }\n\n  void process(const RealVectorView input, RealVectorView transients,\n               RealVectorView residual)\n  {\n    assert(mInitialized);\n    index inSize = input.extent(0);\n    frame(input.data(), inSize);\n    analyze();\n    detection();\n    interpolate(transients.data(), residual.data());\n  }\n\n  void process(const RealVectorView input, const RealVectorView unknowns,\n               RealVectorView transients, RealVectorView residual)\n  {\n    index inSize = input.extent(0);\n    std::copy(unknowns.data(), unknowns.data() + hopSize(), mDetect.data());\n    mCount = 0;\n    for (index i = 0, size = hopSize(); i < size; i++)\n      if (mDetect[asUnsigned(i)] != 0) mCount++;\n    frame(input.data(), inSize);\n    if (mCount) analyze();\n    interpolate(transients.data(), residual.data());\n  }\n\n  bool initialized() { return mInitialized; }\n\nprivate:\n  void frame(const double* input, index inSize)\n  {\n    using namespace std;\n    inSize = std::min(inSize, inputSize());\n    copy(mInput.data() + hopSize(),\n         mInput.data() + modelOrder() + padSize() + blockSize(), mInput.data());\n    copy(input, input + inSize,\n         mInput.data() + modelOrder() + padSize() + modelOrder());\n    fill(mInput.data() + modelOrder() + padSize() + modelOrder() + inSize,\n         mInput.data() + modelOrder() + analysisSize(), 0.0);\n  }\n\n  void analyze()\n  {\n    mModel.setMinVariance(0.0000001);\n    mModel.estimate(mInput.data() + modelOrder(), analysisSize());\n  }\n\n  void detection()\n  {\n    const double* input = mInput.data() + modelOrder() + padSize();\n\n    // Forward and backward error\n    const double normFactor = 1.0 / sqrt(mModel.variance());\n    errorCalculation<&ARModel::forwardErrorArray>(\n        mForwardError.data(), input, blockSize() + mDetectHalfWindow + 1,\n        normFactor);\n    errorCalculation<&ARModel::backwardErrorArray>(\n        mBackwardError.data(), input, blockSize() + mDetectHalfWindow + 1,\n        normFactor);\n\n    // Window error functions (brute force convolution)\n    windowError(mForwardWindowedError.data(),\n                mForwardError.data() + modelOrder(), hopSize());\n    windowError(mBackwardWindowedError.data(),\n                mBackwardError.data() + modelOrder(), hopSize());\n\n    // Detection\n    index        count = 0;\n    const double hiThresh = mDetectThreshHi;\n    const double loThresh = mDetectThreshLo;\n    const index  offHold = mDetectHold;\n\n    bool click = false;\n\n    for (index i = 0, size = hopSize(); i < size; i++)\n    {\n      if (!click && (mBackwardWindowedError[asUnsigned(i)] > loThresh) &&\n          (mForwardWindowedError[asUnsigned(i)] > hiThresh))\n      { click = true; }\n      else if (click && (mBackwardWindowedError[asUnsigned(i)] < loThresh))\n      {\n        click = false;\n\n        for (index j = i; (j < i + offHold) && (j < size); j++)\n        {\n          if (mBackwardWindowedError[asUnsigned(j)] > loThresh)\n          {\n            click = true;\n            break;\n          }\n        }\n      }\n\n      if (click) count++;\n\n      mDetect[asUnsigned(i)] = click ? 1.0 : 0.0;\n    }\n\n    // Count Validation\n    if (count > (hopSize() / 2))\n    {\n      std::fill(mDetect.data(), mDetect.data() + hopSize(), 0.0);\n      count = 0;\n    }\n\n    // RMS validation\n    /*\n    const double frameRMS = calcStat<&Descriptors::RMS>(input, blockSize());\n\n    for (index i = 0, size = hopSize(); i < size;)\n    {\n      for (; i < size; i++)\n          if (mDetect[i])\n            break;\n\n      index beg = i;\n\n      for (; i < size; i++)\n        if (!mDetect[i])\n          break;\n\n      if (i <= beg)\n        continue;\n\n      const double clickRMS = calcStat<&Descriptors::RMS>(input + modelOrder() +\n    beg, i - beg);\n\n      if ((clickRMS / frameRMS) < 0.001)\n      {\n        count -= (i - beg);\n        std::fill(mDetect.data() + beg, mDetect.data() + i, 0.0);\n      }\n    }\n    */\n    mCount = count;\n  }\n\n  template <double Method(const RealVectorView&)>\n  double calcStat(const double* input, index size)\n  {\n    RealVectorView view(const_cast<double*>(input), 0, size);\n    return Method(view);\n  }\n\n  void interpolate(double* transients, double* residual)\n  {\n    const double* input = mInput.data() + padSize() + modelOrder();\n    const double* parameters = mModel.getParameters();\n    index         order = modelOrder();\n    index         size = blockSize();\n\n    if (!mCount)\n    {\n      std::copy(input + order, input + order + hopSize(), residual);\n      std::fill_n(transients, hopSize(), 0.0);\n      return;\n    }\n\n    // Declare matrices\n    MatrixXd A = MatrixXd::Zero(size - order, size);\n    MatrixXd U = MatrixXd::Zero(size, mCount);\n    MatrixXd K = MatrixXd::Zero(size, size - mCount);\n    VectorXd xK(size - mCount);\n\n    // Form data\n    for (index i = 0; i < size - order; i++)\n    {\n      for (index j = 0; j < order; j++)\n        A(i, j + i) = -parameters[order - (j + 1)];\n\n      A(i, order + i) = 1.0;\n    }\n\n    for (index i = 0, uCount = 0, kCount = 0; i < size; i++)\n    {\n      if (i >= order && mDetect[asUnsigned(i - order)] != 0)\n        U(i, uCount++) = 1.0;\n      else\n      {\n        K(i, kCount) = 1.0;\n        xK[kCount++] = input[i];\n      }\n    }\n\n    // Solve\n    MatrixXd Au = A * U;\n    MatrixXd M = -(Au.transpose() * Au);\n    MatrixXd u = M.fullPivLu().solve(Au.transpose() * (A * K) * xK);\n\n    // Write the output\n    for (index i = 0, uCount = 0; i < (size - order); i++)\n    {\n      if (mDetect[asUnsigned(i)] != 0)\n        residual[i] = u(uCount++);\n      else\n        residual[i] = input[i + order];\n    }\n\n    if (mRefine) refine(residual, size, Au, u);\n\n    for (index i = 0; i < (size - order); i++)\n      transients[i] = input[i + order] - residual[i];\n\n    // Copy the residual indexo the correct place\n    std::copy(residual, residual + (size - order),\n              mInput.data() + padSize() + order + order);\n  }\n\n  void refine(double* io, index size, Eigen::MatrixXd& Au, Eigen::MatrixXd& ls)\n  {\n    const double energy = mModel.variance() * mCount;\n    double       energyLS = 0.0;\n    index        order = modelOrder();\n\n    for (index i = 0; i < (size - order); i++)\n    {\n      if (mDetect[asUnsigned(i)] != 0)\n      {\n        const double error = mModel.forwardError(io + i);\n        energyLS += error * error;\n      }\n    }\n\n    if (energyLS < energy)\n    {\n      // Create the square matrix and solve\n      Eigen::LLT<Eigen::MatrixXd> M(Au.transpose() *\n                                    Au); // Cholesky decomposition\n\n      Eigen::VectorXd u(mCount);\n\n      Eigen::MatrixXd correction = M.solve(u) + ls;\n\n      // Write the output\n      for (index i = 0, uCount = 0; i < (size - order); i++)\n      {\n        if (mDetect[asUnsigned(i)] != 0) io[asUnsigned(i)] = u(uCount++);\n      }\n    }\n  }\n\n  double randomSampling(Eigen::VectorXd& output, double variance)\n  {\n    std::normal_distribution<double> gaussian(0.0, sqrt(variance));\n    double                           sum = 0.0;\n\n    for (index i = 0; i < output.size(); i++)\n    {\n      output[i] = gaussian(mRandomGenerator);\n      sum += output[i] * output[i];\n    }\n\n    return sum;\n  }\n\n  template <void (ARModel::*Method)(double*, const double*, index)>\n  void errorCalculation(double* error, const double* input, index size,\n                        double normFactor)\n  {\n    (mModel.*Method)(error, input, size);\n\n    // Take absolutes and normalise\n    for (index i = 0; i < size; i++)\n      error[i] = std::fabs(error[i]) * normFactor;\n  }\n\n  // Triangle window\n  double calcWindow(double norm) { return std::min(norm, 1.0 - norm); }\n\n  void windowError(double* errorWindowed, const double* error, index size)\n  {\n    const index  windowSize = mDetectHalfWindow * 2 + 1;\n    const index  windowOffset = mDetectHalfWindow;\n    const double powFactor = mDetectPowerFactor;\n\n    // Calculate window normalisation factor\n    double windowNormFactor = 0.0;\n\n    for (index j = 0; j < windowSize; j++)\n      windowNormFactor += calcWindow((double) j / windowSize);\n\n    windowNormFactor = 1.0 / windowNormFactor;\n\n    // Do window processing\n    for (index i = 0; i < size; i++)\n    {\n      double windowed = 0.0;\n\n      for (index j = 1; j < windowSize; j++)\n      {\n        const double value = pow(fabs(error[i - windowOffset + j]), powFactor);\n        windowed += value * calcWindow((double) j / windowSize);\n        ;\n      }\n\n      errorWindowed[i] = pow((windowed * windowNormFactor), 1.0 / powFactor);\n    }\n  }\n\n  void resizeStorage()\n  {\n    mInput.resize(asUnsigned(analysisSize() + modelOrder()), 0.0);\n    mDetect.resize(asUnsigned(hopSize()), 0.0);\n    mForwardError.resize(asUnsigned(mBlockSize + modelOrder()), 0.0);\n    mBackwardError.resize(asUnsigned(mBlockSize + modelOrder()), 0.0);\n    mForwardWindowedError.resize(asUnsigned(hopSize()), 0.0);\n    mBackwardWindowedError.resize(asUnsigned(hopSize()), 0.0);\n  }\n\n  ARModel mModel{20};\n\n  std::mt19937_64 mRandomGenerator{std::random_device()()};\n\n  index  mBlockSize{0};\n  index  mPadSize{0};\n  index  mCount{0};\n  bool   mRefine{false};\n  index  mDetectHalfWindow{1};\n  index  mDetectHold{25};\n  double mDetectPowerFactor{1.4};\n  double mDetectThreshHi{1.5};\n  double mDetectThreshLo{3.0};\n\n  std::vector<double> mInput;\n  std::vector<double> mDetect;\n  std::vector<double> mForwardError;\n  std::vector<double> mBackwardError;\n  std::vector<double> mForwardWindowedError;\n  std::vector<double> mBackwardWindowedError;\n  bool                mInitialized{false};\n};\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "8bb39fb02af8eee6ee3acb6c3bcc5aa7750cd73d", "size": 11941, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/TransientExtraction.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/public/TransientExtraction.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/public/TransientExtraction.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 28.2293144208, "max_line_length": 80, "alphanum_fraction": 0.6079055355, "num_tokens": 3247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5713261388182573}}
{"text": "#include <boost/numeric/odeint/stepper/generation/generation_runge_kutta_cash_karp54_classic.hpp>\n", "meta": {"hexsha": "af8eb492e3b3a8d7f2ab84fca1cde866fb161a34", "size": 98, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_generation_generation_runge_kutta_cash_karp54_classic.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_generation_generation_runge_kutta_cash_karp54_classic.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_generation_generation_runge_kutta_cash_karp54_classic.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 49.0, "max_line_length": 97, "alphanum_fraction": 0.887755102, "num_tokens": 27, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5712956888768738}}
{"text": "#include <geometry_msgs/PoseStamped.h>\n\n#include <OgreMovableObject.h>\n#include <OgreSceneManager.h>\n\n#include <rviz/display_context.h>\n#include <rviz/load_resource.h>\n#include <rviz/geometry.h>\n#include <rviz/viewport_mouse_event.h>\n#include <rviz/selection/selection_manager.h>\n\n#include <rviz/properties/color_property.h>\n#include <rviz/properties/int_property.h>\n#include <rviz/properties/string_property.h>\n\n#include <rviz_tool_cursor/rviz_tool_cursor.h>\n\n#include <Eigen/Dense>\n\nnamespace\n{\n\nEigen::Matrix3f createMatrix(const Eigen::Vector3f& norm)\n{\n  Eigen::Matrix3f mat (Eigen::Matrix3f::Identity());\n  mat.col(2) = norm;\n\n  // Create plane from point normal\n  Eigen::Hyperplane<float, 3> plane (norm, Eigen::Vector3f(0, 0, 0));\n\n  // If the normal and global x-axis are not closely aligned\n  if (std::abs(norm.dot(Eigen::Vector3f::UnitX())) < 0.90f)\n  {\n    // Project the global x-axis onto the plane to generate the x-axis\n    Eigen::Vector3f x_axis = plane.projection(Eigen::Vector3f::UnitX()).normalized();\n    mat.col(0) = x_axis;\n    mat.col(1) = norm.cross(x_axis);\n  }\n  else\n  {\n    // Project the global y-axis onto the plane to generate the y-axis\n    Eigen::Vector3f y_axis = plane.projection(Eigen::Vector3f::UnitY()).normalized();\n    mat.col(0) = y_axis.cross(norm);\n    mat.col(1) = y_axis;\n  }\n\n  return mat;\n}\n\nOgre::Quaternion estimateNormal(const std::vector<Ogre::Vector3>& points,\n                                const Ogre::Vector3& camera_norm)\n{\n  Eigen::MatrixXf data;\n  data.resize(points.size(), 3);\n\n  for(std::size_t i = 0; i < points.size(); ++i)\n  {\n    data.row(i) = Eigen::Map<const Eigen::Vector3f>(points[i].ptr());\n  }\n\n  Eigen::MatrixXf centered = data.rowwise() - data.colwise().mean();\n\n  // Use principal component analysis to the get eigenvectors\n  Eigen::MatrixXf cov = centered.transpose() * centered;\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> eig(cov);\n\n  // Get the eigenvector associated with the smallest eigenvalue\n  // (should be Z-axis, assuming points are relatively planar)\n  Eigen::Vector3f norm = eig.eigenvectors().col(0);\n  norm.normalize();\n\n  Eigen::Vector3f camera_normal;\n  camera_normal << camera_norm.x, camera_norm.y, camera_norm.z;\n  camera_normal.normalize();\n\n  if(norm.dot(camera_normal) < 0)\n  {\n    norm *= -1;\n  }\n\n  // Create an arbitrary orientation matrix with the normal being in the direction of the smallest eigenvector\n  Eigen::Matrix3f mat = createMatrix(norm);\n\n  Eigen::Quaternionf q(mat); //Eigen::AngleAxisf(0.0, evecs.col(2)));\n  Ogre::Quaternion out;\n  out.w = q.w();\n  out.x = q.x();\n  out.y = q.y();\n  out.z = q.z();\n\n  return out;\n}\n\n} // namepsace anonymous\n\nnamespace rviz_tool_cursor\n{\n\nToolCursor::ToolCursor()\n  : rviz::Tool()\n{\n  shortcut_key_ = 'c';\n\n\n  topic_property_ = new rviz::StringProperty(\"Topic\", \"/selection_point\",\n                                             \"The topic on which to publish points\",\n                                             getPropertyContainer(), SLOT(updateTopic()), this);\n\n  patch_size_property_ = new rviz::IntProperty(\"Patch Size\", 10,\n                                               \"The number of pixels with which to estimate the surface normal\",\n                                               getPropertyContainer());\n\n  color_property_ = new rviz::ColorProperty(\"Color\", QColor(255, 255, 255),\n                                            \"The color of the tool visualization\",\n                                            getPropertyContainer(), SLOT(updateToolVisualization()), this);\n\n  updateTopic();\n}\n\nToolCursor::~ToolCursor()\n{\n\n}\n\nvoid ToolCursor::onInitialize()\n{\n  // Initialize the scene node\n  cursor_node_ = scene_manager_->getRootSceneNode()->createChildSceneNode();\n\n  // Create the visual tool object\n  Ogre::MovableObject* obj = createToolVisualization();\n\n  // Attach the tool visualization to the scene\n  cursor_node_->attachObject(obj);\n  cursor_node_->setVisible(false);\n\n  // Set the cursors\n  hit_cursor_ = cursor_;\n  std_cursor_ = rviz::getDefaultCursor();\n}\n\nvoid ToolCursor::activate()\n{\n  cursor_node_->setVisible(true);\n}\n\nvoid ToolCursor::deactivate()\n{\n  cursor_node_->setVisible(false);\n}\n\nvoid ToolCursor::updateTopic()\n{\n  pub_ = nh_.advertise<geometry_msgs::PoseStamped>(topic_property_->getStdString(), 1, true);\n}\n\nint ToolCursor::processMouseEvent(rviz::ViewportMouseEvent& event)\n{\n  // Get the 3D point in space indicated by the mouse and a patch of points around it\n  // with which to estimate the surface normal\n  Ogre::Vector3 position;\n  std::vector<Ogre::Vector3> points;\n\n  const unsigned patch_size = static_cast<unsigned>(patch_size_property_->getInt());\n\n  // Set the visibility of this node off so the selection manager won't choose a point on our cursor mesh in the point and patch\n  cursor_node_->setVisible(false);\n\n  bool got_point = context_->getSelectionManager()->get3DPoint(event.viewport, event.x, event.y, position);\n  bool got_patch = context_->getSelectionManager()->get3DPatch(event.viewport, event.x, event.y, patch_size, patch_size, true, points);\n\n  // Revisualize the cursor node\n  cursor_node_->setVisible(true);\n\n  if(got_point && got_patch && points.size() > 3)\n  {\n    // Set the cursor\n    rviz::Tool::setCursor(hit_cursor_);\n\n    // Estimate the surface normal from the patch of points\n    Ogre::Quaternion q = estimateNormal(points, event.viewport->getCamera()->getDirection());\n    cursor_node_->setOrientation(q);\n    cursor_node_->setPosition(position);\n\n    if(event.leftUp())\n    {\n      // Publish a point message upon release of the left mouse button\n      geometry_msgs::PoseStamped msg;\n      msg.header.frame_id = context_->getFixedFrame().toStdString();\n      msg.header.stamp = ros::Time::now();\n\n      msg.pose.position.x = static_cast<double>(position.x);\n      msg.pose.position.y = static_cast<double>(position.y);\n      msg.pose.position.z = static_cast<double>(position.z);\n\n      msg.pose.orientation.w = static_cast<double>(q.w);\n      msg.pose.orientation.x = static_cast<double>(q.x);\n      msg.pose.orientation.y = static_cast<double>(q.y);\n      msg.pose.orientation.z = static_cast<double>(q.z);\n\n      pub_.publish(msg);\n    }\n  }\n  else\n  {\n    // Set the standard cursor\n    rviz::Tool::setCursor(std_cursor_);\n\n    // Project the tool visualization onto the ground\n    Ogre::Plane plane (Ogre::Vector3::UNIT_Z, 0.0f);\n    rviz::getPointOnPlaneFromWindowXY(event.viewport, plane, event.x, event.y, position);\n    cursor_node_->setOrientation(1.0f, 0.0f, 0.0f, 0.0f);\n    cursor_node_->setPosition(position);\n  }\n\n  return rviz::Tool::Render;\n}\n\n} // namespace rviz_tool_cursor\n", "meta": {"hexsha": "08b7819e4982d9ffadb2efa0be296347f3c73771", "size": 6632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rviz_tool_cursor/rviz_tool_cursor.cpp", "max_stars_repo_name": "youngbend/rviz_tool_cursor", "max_stars_repo_head_hexsha": "c200eb09d2867ccb4887eaedfc6eb80b1e9148f3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rviz_tool_cursor/rviz_tool_cursor.cpp", "max_issues_repo_name": "youngbend/rviz_tool_cursor", "max_issues_repo_head_hexsha": "c200eb09d2867ccb4887eaedfc6eb80b1e9148f3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rviz_tool_cursor/rviz_tool_cursor.cpp", "max_forks_repo_name": "youngbend/rviz_tool_cursor", "max_forks_repo_head_hexsha": "c200eb09d2867ccb4887eaedfc6eb80b1e9148f3", "max_forks_repo_licenses": ["Apache-2.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.1454545455, "max_line_length": 135, "alphanum_fraction": 0.6762665862, "num_tokens": 1636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.571285816876799}}
{"text": "/* test_weibull.cpp\r\n *\r\n * Copyright Steven Watanabe 2010\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id: test_weibull.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\r\n *\r\n */\r\n\r\n#include <boost/random/weibull_distribution.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/math/distributions/weibull.hpp>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::weibull_distribution<>\r\n#define BOOST_RANDOM_DISTRIBUTION_NAME weibull\r\n#define BOOST_MATH_DISTRIBUTION boost::math::weibull\r\n#define BOOST_RANDOM_ARG1_TYPE double\r\n#define BOOST_RANDOM_ARG1_NAME a\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\r\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)\r\n#define BOOST_RANDOM_ARG2_TYPE double\r\n#define BOOST_RANDOM_ARG2_NAME b\r\n#define BOOST_RANDOM_ARG2_DEFAULT 1000.0\r\n#define BOOST_RANDOM_ARG2_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)\r\n\r\n#include \"test_real_distribution.ipp\"\r\n", "meta": {"hexsha": "4125bd89ef5674e48c4a7f820ab5acb7d8250c40", "size": 1048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_weibull.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/random/test/test_weibull.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/random/test/test_weibull.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 36.1379310345, "max_line_length": 76, "alphanum_fraction": 0.7891221374, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146849, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.571208653305393}}
{"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 test for Arpaca's eigensolver.\n *\n * To compile this program: \n * g++ \\\n *    -std=c++11 \\\n *    -I [/path/to/eigen] \\\n *    -O3 \\\n *    -DNDEBUG \\\n *    performance_main.cpp \\\n *    -L [/path/to/libarpack.a] \\\n *    -larpack \\\n *    -o performance_main\n *\n * This assumes that arpaca.hpp is in the same directory.\n */\n\n#include <iostream>\n#include <vector>\n#include <random>\n#include <chrono>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include \"arpaca.hpp\"\n\nnamespace chrono = std::chrono;\n\ntypedef Eigen::Triplet<double> T;\ntypedef Eigen::SparseMatrix<double, Eigen::RowMajor> SMatrix;\n\ntemplate<typename RandomNumberGenerator>\nSMatrix\nMakeSparseSymmetricRandomMatrix(int n, int k, RandomNumberGenerator& rnd)\n{\n    std::uniform_int_distribution<int> r_int(0,n-1);\n    std::normal_distribution<double> r_real;\n\n    std::vector<T> ts;\n    ts.reserve(n*k);\n    for (int l=0; l<n*k; l++)\n    {\n        // If we randomly create two or more triplets for the same matrix\n        // element, the values of all triplets will be summed...\n        int i = r_int(rnd);\n        int j = r_int(rnd);\n        double v = r_real(rnd);\n        ts.push_back(T(i,j,v));\n    }\n\n    SMatrix mat(n, n);\n    mat.setFromTriplets(ts.begin(),ts.end());\n    return mat.selfadjointView<Eigen::Upper>();\n}\n\narpaca::EigenvalueType\nGetEigenvalueType(const std::string& name)\n{\n    if (name == \"LA\")\n        return arpaca::ALGEBRAIC_LARGEST;\n    else if (name == \"SA\")\n        return arpaca::ALGEBRAIC_SMALLEST;\n    else if (name == \"BE\")\n        return arpaca::ALGEBRAIC_BOTH_END;\n    else if (name == \"LM\")\n        return arpaca::MAGNITUDE_LARGEST;\n    else if (name == \"SM\")\n        return arpaca::MAGNITUDE_SMALLEST;\n    throw std::invalid_argument(\"invalid eigenvalue type\");\n}\n\nint main(int argc, char** argv)\n{\n    if (argc != 5) {\n        std::cerr << \"usage: \" << argv[0]\n                  << \" <dimension>\"\n                  << \" <# of non-zero values in each row>\"\n                  << \" <# of eigenvectors>\"\n                  << \" <type of eigenvalues>\"\n                  << std::endl;\n        std::cerr << \"\\ttype of eigenvalues: LA SA BE LM SM\" << std::endl;\n        return 1;\n    }\n\n    const int n = std::atoi(argv[1]),\n    k = std::atoi(argv[2]),\n    r = std::atoi(argv[3]);\n    const arpaca::EigenvalueType type = GetEigenvalueType(argv[4]);\n\n    std::cerr << \"Making matrix\" << std::endl;\n    std::mt19937 generator(42);\n    SMatrix X = MakeSparseSymmetricRandomMatrix(n, k, generator);\n\n    std::cerr << \"Start performance test\" << std::endl;\n    chrono::steady_clock::time_point begin = chrono::steady_clock::now();\n\n    arpaca::SymmetricEigenSolver<double> solver = arpaca::Solve(X, r, type);\n\n    chrono::steady_clock::time_point end = chrono::steady_clock::now();\n\n    chrono::duration<double> duration_ = \n        chrono::duration_cast<chrono::duration<double>>(end - begin);\n    const double duration = duration_.count();\n\n    std::cout << \"        DIMENSION: \" << X.rows() << std::endl;\n    std::cout << \"         NONZEROS: \" << X.nonZeros() << std::endl;\n    std::cout << \"         DURATION: \"\n              << duration << \" SEC.\" << std::endl;\n    std::cout << \"             ITER: \"\n              << solver.num_actual_iterations() << std::endl;\n    std::cout << \"CONVERGED EIGVALS: \"\n              << solver.num_converged_eigenvalues() << std::endl;\n    std::cout << \"             INFO: \" << solver.GetInfo() << std::endl;\n}\n", "meta": {"hexsha": "369e03845ee1e782e91f2c2d17a18db5dce5246f", "size": 3615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "performance_main.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_main.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_main.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": 30.6355932203, "max_line_length": 76, "alphanum_fraction": 0.5950207469, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.571208653305393}}
{"text": "// Boost.GIL (Generic Image Library) - tests\n//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n#include <boost/gil.hpp>\n#include <boost/gil/extension/io/png.hpp>\n\n#include <limits>\n#include <vector>\n\nnamespace gil = boost::gil;\n\nconst std::ptrdiff_t size = 256;\n\nvoid line_bresenham(std::ptrdiff_t width, std::ptrdiff_t height, const std::string& output_name)\n{\n    const auto rasterizer = gil::bresenham_line_rasterizer{};\n    std::vector<gil::point_t> line_points(rasterizer.point_count(width, height));\n\n    gil::gray8_image_t image(size, size);\n    auto view = gil::view(image);\n\n    rasterizer({0, 0}, {width - 1, height - 1}, line_points.begin());\n    for (const auto& point : line_points)\n    {\n        view(point) = std::numeric_limits<gil::uint8_t>::max();\n    }\n\n    gil::write_view(output_name, view, gil::png_tag{});\n}\n\nint main()\n{\n    line_bresenham(256, 256, \"line-bresenham-256-256.png\");\n    line_bresenham(256, 128, \"line-bresenham-256-128.png\");\n    line_bresenham(256, 1, \"line-bresenham-256-1.png\");\n    line_bresenham(1, 256, \"line-bresenham-1-256.png\");\n}\n", "meta": {"hexsha": "9f02a347a4db3af633fb26e86f5c061e665edafd", "size": 1297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/rasterizer_line.cpp", "max_stars_repo_name": "harsh-4/gil", "max_stars_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "example/rasterizer_line.cpp", "max_issues_repo_name": "harsh-4/gil", "max_issues_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "example/rasterizer_line.cpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 30.1627906977, "max_line_length": 96, "alphanum_fraction": 0.6954510409, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146847, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5712086433984582}}
{"text": "//! \\file examples/Arrangement_on_surface_2/bgl_primal_adapter.cpp\n// Adapting an arrangement to a BGL graph.\n\n#include <vector>\n\n#include <CGAL/config.h>\n\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/property_map/vector_property_map.hpp>\n\n#include <CGAL/graph_traits_Arrangement_2.h>\n#include <CGAL/Arr_vertex_index_map.h>\n#include <CGAL/property_map.h>\n\n#include \"arr_exact_construction_segments.h\"\n#include \"Edge_length.h\"\n\ntypedef CGAL::Arr_vertex_index_map<Arrangement>  Vertex_index_map;\ntypedef Edge_length<Arrangement>                 My_edge_length;\n\nint main() {\n  // Construct an arrangement of seven intersecting line segments.\n  // We keep a handle for the vertex v0 that corresponds to the point (1,1).\n  Point p1(1, 1), p2(1, 4), p3(2, 2), p4(3, 7), p5(4, 4), p6(7, 1), p7(9, 3);\n  Arrangement arr;\n  Segment s(p1, p6);\n  Arrangement::Halfedge_handle e = insert_non_intersecting_curve(arr, s);\n  Arrangement::Vertex_handle v0 = e->source();\n  insert(arr, Segment(p1, p4));  insert(arr, Segment(p2, p6));\n  insert(arr, Segment(p3, p7));  insert(arr, Segment(p3, p5));\n  insert(arr, Segment(p6, p7));  insert(arr, Segment(p4, p7));\n\n  // Create a mapping of the arrangement vertices to indices.\n  Vertex_index_map index_map(arr);\n\n  // Create a property map based on std::vector to keep the result distances.\n  boost::vector_property_map<Number_type, Vertex_index_map>\n    dist_map(static_cast<unsigned int>(arr.number_of_vertices()), index_map);\n\n  // Perform Dijkstra's algorithm from the vertex v0.\n  My_edge_length edge_length;\n  boost::dijkstra_shortest_paths(arr, v0, boost::vertex_index_map(index_map).\n                                 weight_map(edge_length).distance_map(dist_map).\n                                 distance_zero(Number_type(0)).\n                                 distance_inf(Number_type(1000)));\n\n  // Print the distance of each vertex from v0.\n  std::cout << \"The graph distances of the arrangement vertices from (\"\n            << v0->point() << \") :\\n\";\n  for (auto vit = arr.vertices_begin(); vit != arr.vertices_end(); ++vit)\n    std::cout << \"(\" << vit->point() << \") at distance \"\n              << CGAL::to_double(dist_map[vit]) << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "c232a671542bdca742a306631b8d9c994b6e29f6", "size": 2225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Arrangement_on_surface_2/examples/Arrangement_on_surface_2/bgl_primal_adapter.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": "Arrangement_on_surface_2/examples/Arrangement_on_surface_2/bgl_primal_adapter.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": "Arrangement_on_surface_2/examples/Arrangement_on_surface_2/bgl_primal_adapter.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 39.7321428571, "max_line_length": 80, "alphanum_fraction": 0.682247191, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5712086318274109}}
{"text": "//\n// Created by Alex Beccaro on 25/01/2019.\n//\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include <primes.hpp>\n#include <numeric>\n#include \"../../src/problems/101-150/133/problem133.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Problem133 )\n\n    BOOST_AUTO_TEST_CASE( Example ) {\n        auto res = problems::problem133::solve(100);\n        std::vector<uint32_t> primes = primes::primes_up_to<uint32_t>(100);\n        auto solution = std::accumulate(primes.begin(), primes.end(), 0);\n        BOOST_CHECK_EQUAL(res, solution - 142);\n    }\n\n    BOOST_AUTO_TEST_CASE( Solution ) {\n        auto res = problems::problem133::solve();\n        BOOST_CHECK_EQUAL(res, 453647705);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "89b99f1e2c4f0f20d339268a2ae5caaf604dade8", "size": 711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/101-150/test_problem133.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "tests/101-150/test_problem133.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/101-150/test_problem133.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.44, "max_line_length": 75, "alphanum_fraction": 0.682137834, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5712086318274108}}
{"text": "#define BOOST_TEST_MODULE \"test_centroid\"\n\n#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST\n#include <boost/test/unit_test.hpp>\n#else\n#define BOOST_TEST_NO_LIB\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <periortree/boundary_condition.hpp>\n#include <periortree/centroid.hpp>\n#include <test/point_type.hpp>\n#include <test/aabb_type.hpp>\n\nBOOST_AUTO_TEST_CASE(test_centroid_unlimited)\n{\n    {\n        const perior::test::xyz  l(0., 0., 0.);\n        const perior::test::xyz  u(10., 10., 10.);\n        const perior::test::aabb box(l, u);\n        const perior::unlimited_boundary<perior::test::xyz> boundary;\n\n        const perior::test::xyz c = perior::centroid(box, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(c.x, 5.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(c.y, 5.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(c.z, 5.0, 1e-12);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_centroid_cubic_periodic)\n{\n    const perior::test::xyz lw(0., 0., 0.);\n    const perior::test::xyz up(10., 10., 10.);\n    const perior::cubic_periodic_boundary<perior::test::xyz> boundary(lw, up);\n\n    {\n        const perior::test::xyz  l(3.0, 3.0, 3.0);\n        const perior::test::xyz  u(7.0, 7.0, 7.0);\n        const perior::test::aabb box(l, u);\n\n        const perior::test::xyz c = perior::centroid(box, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(c.x, 5.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(c.y, 5.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(c.z, 5.0, 1e-12);\n    }\n\n    {\n        const perior::test::xyz  l(7.0, 7.0, 7.0);\n        const perior::test::xyz  u(3.0, 3.0, 3.0);\n        const perior::test::aabb box(l, u);\n        const perior::test::xyz c = perior::centroid(box, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(c.x, 10.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(c.y, 10.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(c.z, 10.0, 1e-12);\n    }\n\n    {\n        const perior::test::xyz l(8.0, 4.0, 8.0);\n        const perior::test::xyz u(2.0, 8.0, 2.0);\n        const perior::test::aabb box(l, u);\n        const perior::test::xyz c = perior::centroid(box, boundary);\n        BOOST_CHECK_CLOSE_FRACTION(c.x, 10.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(c.y,  6.0, 1e-12);\n        BOOST_CHECK_CLOSE_FRACTION(c.z, 10.0, 1e-12);\n    }\n}\n", "meta": {"hexsha": "597de3061e0b9b1102a51fac60f7da30e847a674", "size": 2242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_centroid.cpp", "max_stars_repo_name": "lasergyro/periortree", "max_stars_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-09-01T14:46:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T11:11:50.000Z", "max_issues_repo_path": "test/test_centroid.cpp", "max_issues_repo_name": "lasergyro/periortree", "max_issues_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-02-14T03:37:38.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-14T12:16:29.000Z", "max_forks_repo_path": "test/test_centroid.cpp", "max_forks_repo_name": "lasergyro/periortree", "max_forks_repo_head_hexsha": "1ab9abb385228d0aef08fa0eabdf5adb6f71c0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-02-14T03:52:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T15:49:30.000Z", "avg_line_length": 33.4626865672, "max_line_length": 78, "alphanum_fraction": 0.6302408564, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5712086268739432}}
{"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": "// Copyright(c) 2021, Richardson Lab at Duke\n// Licensed under the Apache 2 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 permissionsand\n// limitations under the License.\n\n#include <cmath>\n#include <scitbx/constants.h>\n#include <algorithm>\n#include <boost/lexical_cast.hpp>\n#include \"DotSpheres.h\"\n\nnamespace molprobity {\nnamespace probe {\n\nDotSphere::DotSphere(double radius, double density)\n  : m_rad(radius), m_dens(density)\n{\n  // Clamp our inputs to non-negative\n  if (m_rad < 0) { m_rad = 0; }\n  if (m_dens < 0) { m_dens = 0; }\n\n  // If we have a zero radius or density, we're done\n  if (m_rad == 0 || m_dens == 0) { return; }\n\n  // Estimate the number of dots to be placed given the radius and density.\n  // This code is pulled from DotDph.cpp in Reduce.\n  size_t num_dots = static_cast<size_t>(floor(4.0 * scitbx::constants::pi * density * (radius * radius)));\n\n  // Generate the dots, spreading them across the sphere.\n  double offset = 0.2;\n  double ang, cosang, sinang, phi, theta, xy0, x0, y0, z0;\n  int nequator, nvert, nhoriz;\n  bool odd = true;\n\n  nequator = static_cast<int>(floor(sqrt(num_dots * scitbx::constants::pi)));\n\n  ang = 5.0 * scitbx::constants::pi / 360.0;\n  cosang = cos(ang);\n  sinang = sin(ang);\n\n  nvert = nequator / 2;\n  for (int j = 0; j <= nvert; j++) {\n    phi = (scitbx::constants::pi * j) / nvert;\n    z0 = cos(phi) * radius;\n    xy0 = sin(phi) * radius;\n\n    nhoriz = static_cast<int>(floor(nequator * sin(phi)));\n    if (nhoriz < 1) { nhoriz = 1; }\n    for (int k = 0; k < nhoriz; k++) {\n      if (odd) { theta = (2.0 * scitbx::constants::pi * k + offset) / nhoriz; }\n      else { theta = (2.0 * scitbx::constants::pi * k) / nhoriz; }\n      x0 = cos(theta) * xy0;\n      y0 = sin(theta) * xy0;\n\n      m_vec.push_back(molprobity::probe::Point(x0, y0 * cosang - z0 * sinang, y0 * sinang + z0 * cosang));\n    }\n    odd = !odd;\n  }\n}\n\nstd::string DotSphere::test()\n{\n  // Test creation with negative density and/or radius\n  {\n    DotSphere d(-1, 10);\n    if (d.radius() != 0 || d.dots().size() != 0) {\n      return \"molprobity::probe::DotSphere::test(): Construction with negative radius failed\";\n    }\n  }\n  {\n    DotSphere d(5, -3);\n    if (d.density() != 0 || d.dots().size() != 0) {\n      return \"molprobity::probe::DotSphere::test(): Construction with negative density failed\";\n    }\n  }\n  {\n    DotSphere d(-5, -3);\n    if (d.radius() != 0 || d.density() != 0 || d.dots().size() != 0) {\n      return \"molprobity::probe::DotSphere::test(): Construction with negative radius and density failed\";\n    }\n  }\n\n  // Test creating with extremely small density to be sure we get a single dot\n  {\n    DotSphere d(1, 1e-10);\n    if (d.radius() != 1 || d.density() != 1e-10 || d.dots().size() > 2) {\n      return \"molprobity::probe::DotSphere::test(): Construction with small density failed\";\n    }\n  }\n\n  // Test creating with a different densities and see whether the number of dots is close.\n  {\n    for (double den = 1; den < 128; den *= 1.3) {\n      DotSphere d(1, den);\n      double expected = ceil(4.0 * scitbx::constants::pi * den * (1 * 1));\n      long found = static_cast<long>(d.dots().size());\n      double diff = abs(found - expected);\n      if (diff > std::max(3.0, expected*0.2)) {\n        return std::string(\"molprobity::probe::DotSphere::test(): Construction with density \")\n          +boost::lexical_cast<std::string>(den) + \" failed: \"\n          + \"found \" + boost::lexical_cast<std::string>(found) + \" dots but expected \"\n          + boost::lexical_cast<std::string>(expected);\n      }\n    }\n  }\n\n  // Test creating with reasonable density to be sure we get dots in all octants\n  {\n    DotSphere d(1, 5);\n    bool px = false, mx = false, py = false, my = false, pz = false, mz = false;\n    const scitbx::af::shared<Point>& dots = d.dots();\n    for (size_t i = 0; i < dots.size(); i++) {\n      Point dot = dots[i];\n      if (dot[0] > 0) { px = true; }\n      if (dot[0] < 0) { mx = true; }\n      if (dot[1] > 0) { py = true; }\n      if (dot[1] < 0) { my = true; }\n      if (dot[2] > 0) { pz = true; }\n      if (dot[2] < 0) { mz = true; }\n    }\n    if (!px || !mx || !py || !my || !pz || !mz) {\n      return \"molprobity::probe::DotSphere::test(): Construction with reasoneble density \"\n        \"did not have dots in all octants\";\n    }\n  }\n\n  // All tests passed.\n  return \"\";\n}\n\nconst DotSphere& DotSphereCache::get_sphere(double radius)\n{\n  std::map<double, DotSphere>::const_iterator ret = m_spheres.find(radius);\n  if (ret == m_spheres.end()) {\n    // We don't have a sphere with this radius -- create one and insert it\n    std::pair<std::map<double, DotSphere>::iterator, bool> iRet =\n      m_spheres.insert(std::pair<double, DotSphere>(radius, DotSphere(radius, m_dens)));\n    ret = iRet.first;\n  }\n  return ret->second;\n}\n\nstd::string DotSphereCache::test()\n{\n  // Object to use for our tests\n  DotSphereCache dsc(10);\n\n  // Test creation of a single sphere\n  const DotSphere& sp1 = dsc.get_sphere(1.0);\n  if (dsc.size() != 1) {\n    return \"molprobity::probe::DotSphereCache::test(): Single sphere creation failed\";\n  }\n\n  // Ask for another sphere of the same size and make sure we get the same one.\n  const DotSphere& sp2 = dsc.get_sphere(1.0);\n  if (dsc.size() != 1 || sp1 != sp2) {\n    return \"molprobity::probe::DotSphereCache::test(): Identical sphere creation failed\";\n  }\n\n  // Ask a sphere of a differnt size and make sure we get a different one.\n  const DotSphere& sp3 = dsc.get_sphere(2.0);\n  if (dsc.size() != 2 || sp1 == sp3) {\n    return \"molprobity::probe::DotSphereCache::test(): Unique sphere creation failed\";\n  }\n\n  // All tests passed.\n  return \"\";\n}\n\nstd::string DotSpheres_test()\n{\n  std::string ret;\n\n  /// Test DotSphere class\n  ret = DotSphere::test();\n  if (!ret.empty()) {\n    return std::string(\"molprobity::probe::DotSpheres_test(): failed: \") + ret;\n  }\n\n  /// Test DotSphereCache class\n  ret = DotSphereCache::test();\n  if (!ret.empty()) {\n    return std::string(\"molprobity::probe::DotSpheres_test(): failed: \") + ret;\n  }\n\n  // All tests passed.\n  return \"\";\n}\n\n\n} // end namespace probe\n} // end namespace molprobity\n", "meta": {"hexsha": "e2e2f8f524481b9ee9bf7457c6a0170e1e67088c", "size": 6505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mmtbx/probe/DotSpheres.cpp", "max_stars_repo_name": "dperl-sol/cctbx_project", "max_stars_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "mmtbx/probe/DotSpheres.cpp", "max_issues_repo_name": "dperl-sol/cctbx_project", "max_issues_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "mmtbx/probe/DotSpheres.cpp", "max_forks_repo_name": "dperl-sol/cctbx_project", "max_forks_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 32.3631840796, "max_line_length": 106, "alphanum_fraction": 0.6190622598, "num_tokens": 1969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5711653788921223}}
{"text": "/**\n * @file\n * Test of rotation-chain example using Ceres autodiff, for comparison\n */\n#include <benchmark/benchmark.h>\n#include <ceres/ceres.h>\n#include <Eigen/Core>\n\n#include \"../bechmark_helpers.hpp\"\n\ntemplate <typename T>\nusing EigenVector = std::vector<T, Eigen::aligned_allocator<T>>;\n\ntemplate <typename Scalar>\nusing Mat3 = Eigen::Matrix<Scalar, 3, 3, Eigen::RowMajor>;\n\ntemplate <typename Scalar>\nusing Vec3 = Eigen::Matrix<Scalar, 3, 1>;\n\ntemplate <typename Scalar>\nusing Mat9 = Eigen::Matrix<Scalar, 9, 9, Eigen::RowMajor>;\n\ntemplate <typename Scalar>\nusing InVec3 = Eigen::Map<const Vec3<Scalar>>;\n\ntemplate <typename Scalar>\nusing OutVec3 = Eigen::Map<Vec3<Scalar>>;\n\ntemplate <typename Scalar>\nusing InQuat = Eigen::Map<const Eigen::Quaternion<Scalar>>;\n\ntemplate <typename Scalar>\nusing OutQuat = Eigen::Map<Eigen::Quaternion<Scalar>>;\n\ntemplate <typename Scalar>\nusing InMat3 = Eigen::Map<const Mat3<Scalar>>;\n\ntemplate <typename Scalar>\nusing OutMat3 = Eigen::Map<Mat3<Scalar>>;\n\nusing InMat34d = Eigen::Map<const Eigen::Matrix<double, 3, 4, Eigen::RowMajor>>;\nusing InMat43d = Eigen::Map<const Eigen::Matrix<double, 4, 3, Eigen::RowMajor>>;\n\nstruct ChainFunctor1 {\n    template <typename T>\n    bool operator()(const T *const x0, const T *const x1, T *e) const {\n        InVec3<T> v1{x0};\n        InQuat<T> q1{x1};\n        OutVec3<T> v2{e};\n\n        v2 = q1 * v1;\n        return true;\n    }\n};\n\nstruct ChainFunctor2 {\n    template <typename T>\n    bool operator()(const T *const x0, const T *const x1, const T *const x2, T *e) const {\n        InVec3<T> v1{x0};\n        InQuat<T> q1{x1}, q2{x2};\n        OutVec3<T> v2{e};\n\n        v2 = q1 * q2 * v1;\n        return true;\n    }\n};\n\nstruct ChainFunctor3 {\n    template <typename T>\n    bool operator()(const T *const x0,\n                    const T *const x1,\n                    const T *const x2,\n                    const T *const x3,\n                    T *e) const {\n        InVec3<T> v1{x0};\n        InQuat<T> q1{x1}, q2{x2}, q3{x3};\n        OutVec3<T> v2{e};\n\n        v2 = q1 * q2 * q3 * v1;\n        return true;\n    }\n};\n\nstruct ChainFunctor4 {\n    template <typename T>\n    bool operator()(const T *const x0,\n                    const T *const x1,\n                    const T *const x2,\n                    const T *const x3,\n                    const T *const x4,\n                    T *e) const {\n        InVec3<T> v1{x0};\n        InQuat<T> q1{x1}, q2{x2}, q3{x3}, q4{x4};\n        OutVec3<T> v2{e};\n\n        v2 = q1 * q2 * q3 * q4 * v1;\n        return true;\n    }\n};\n\nstruct ChainFunctor5 {\n    template <typename T>\n    bool operator()(const T *const x0,\n                    const T *const x1,\n                    const T *const x2,\n                    const T *const x3,\n                    const T *const x4,\n                    const T *const x5,\n                    T *e) const {\n        InVec3<T> v1{x0};\n        InQuat<T> q1{x1}, q2{x2}, q3{x3}, q4{x4}, q5{x5};\n        OutVec3<T> v2{e};\n\n        v2 = q1 * q2 * q3 * q4 * q5 * v1;\n        return true;\n    }\n};\n\nstruct ChainFunctor6 {\n    template <typename T>\n    bool operator()(const T *const x0,\n                    const T *const x1,\n                    const T *const x2,\n                    const T *const x3,\n                    const T *const x4,\n                    const T *const x5,\n                    const T *const x6,\n                    T *e) const {\n        InVec3<T> v1{x0};\n        InQuat<T> q1{x1}, q2{x2}, q3{x3}, q4{x4}, q5{x5}, q6{x6};\n        OutVec3<T> v2{e};\n\n        v2 = q1 * q2 * q3 * q4 * q5 * q6 * v1;\n        return true;\n    }\n};\n\nstruct ChainFunctor7 {\n    template <typename T>\n    bool operator()(const T *const x0,\n                    const T *const x1,\n                    const T *const x2,\n                    const T *const x3,\n                    const T *const x4,\n                    const T *const x5,\n                    const T *const x6,\n                    const T *const x7,\n                    T *e) const {\n        InVec3<T> v1{x0};\n        InQuat<T> q1{x1}, q2{x2}, q3{x3}, q4{x4}, q5{x5}, q6{x6}, q7{x7};\n        OutVec3<T> v2{e};\n\n        v2 = q1 * q2 * q3 * q4 * q5 * q6 * q7 * v1;\n        return true;\n    }\n};\n\nclass RotateChain : public benchmark::Fixture {\n protected:\n    const int N = 1000;\n    // Use wave::RotationM just for the Random() method, which produces valid SO(3)\n    using waveRot = wave::RotationQd;\n    const EigenVector<waveRot> R1_vec = randomMatrices<waveRot>(N);\n    const EigenVector<waveRot> R2_vec = randomMatrices<waveRot>(N);\n    const EigenVector<waveRot> R3_vec = randomMatrices<waveRot>(N);\n    const EigenVector<waveRot> R4_vec = randomMatrices<waveRot>(N);\n    const EigenVector<waveRot> R5_vec = randomMatrices<waveRot>(N);\n    const EigenVector<waveRot> R6_vec = randomMatrices<waveRot>(N);\n    const EigenVector<waveRot> R7_vec = randomMatrices<waveRot>(N);\n    const EigenVector<Eigen::Vector3d> v1_vec = randomMatrices<Eigen::Vector3d>(N);\n};\n\nBENCHMARK_F(RotateChain, ceres1)(benchmark::State &state) {\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor1, 3, 3, 4>{new ChainFunctor1()}};\n\n    ceres::EigenQuaternionParameterization qp{};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            double res[3];\n            double J0[3 * 3];\n            double J1_global[3 * 4];\n            Mat3<double> J1, J2;\n\n\n            double const *const inputs[] = {v1_vec[i].data(),\n                                            R1_vec[i].value().coeffs().data()};\n            double *jacobians[] = {J0, J1_global};\n\n            // Compute result and global (3*4) jacobians\n            cost_function->Evaluate(inputs, res, jacobians);\n\n            // Compute local (3*3) jacobians\n            double J_global_local[4 * 3];\n            qp.ComputeJacobian(R1_vec[i].value().coeffs().data(), J_global_local);\n            J1 = InMat34d{J1_global} * InMat43d{J_global_local};\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J1);\n        }\n    }\n}\n\n\nBENCHMARK_F(RotateChain, ceres2)(benchmark::State &state) {\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor2, 3, 3, 4, 4>{new ChainFunctor2()}};\n\n    ceres::EigenQuaternionParameterization qp{};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            double res[3];\n            double J0[3 * 3];\n            double J1_global[3 * 4], J2_global[3 * 4];\n            Mat3<double> J1, J2;\n\n\n            double const *const inputs[] = {v1_vec[i].data(),\n                                            R1_vec[i].value().coeffs().data(),\n                                            R2_vec[i].value().coeffs().data()};\n            double *jacobians[] = {J0, J1_global, J2_global};\n\n            // Compute result and global (3*4) jacobians\n            cost_function->Evaluate(inputs, res, jacobians);\n\n            // Compute local (3*3) jacobians\n            double J_global_local[4 * 3];\n            qp.ComputeJacobian(R1_vec[i].value().coeffs().data(), J_global_local);\n            J1 = InMat34d{J1_global} * InMat43d{J_global_local};\n            qp.ComputeJacobian(R2_vec[i].value().coeffs().data(), J_global_local);\n            J2 = InMat34d{J2_global} * InMat43d{J_global_local};\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J1);\n            benchmark::DoNotOptimize(J2);\n        }\n    }\n}\n\nBENCHMARK_F(RotateChain, ceres3)(benchmark::State &state) {\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor3, 3, 3, 4, 4, 4>{new ChainFunctor3()}};\n\n    ceres::EigenQuaternionParameterization qp{};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            double res[3];\n            double J0[3 * 3];\n            double J1_global[3 * 4], J2_global[3 * 4], J3_global[3 * 4];\n            Mat3<double> J1, J2, J3;\n\n\n            double const *const inputs[] = {v1_vec[i].data(),\n                                            R1_vec[i].value().coeffs().data(),\n                                            R2_vec[i].value().coeffs().data(),\n                                            R3_vec[i].value().coeffs().data()};\n            double *jacobians[] = {J0, J1_global, J2_global, J3_global};\n\n            // Compute result and global (3*4) jacobians\n            cost_function->Evaluate(inputs, res, jacobians);\n\n            // Compute local (3*3) jacobians\n            double J_global_local[4 * 3];\n            qp.ComputeJacobian(R1_vec[i].value().coeffs().data(), J_global_local);\n            J1 = InMat34d{J1_global} * InMat43d{J_global_local};\n            qp.ComputeJacobian(R2_vec[i].value().coeffs().data(), J_global_local);\n            J2 = InMat34d{J2_global} * InMat43d{J_global_local};\n            qp.ComputeJacobian(R3_vec[i].value().coeffs().data(), J_global_local);\n            J3 = InMat34d{J3_global} * InMat43d{J_global_local};\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J1);\n            benchmark::DoNotOptimize(J2);\n            benchmark::DoNotOptimize(J3);\n        }\n    }\n}\n\nBENCHMARK_F(RotateChain, ceres4)(benchmark::State &state) {\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor4, 3, 3, 4, 4, 4, 4>{\n        new ChainFunctor4()}};\n\n    ceres::EigenQuaternionParameterization qp{};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            double res[3];\n            double J0[3 * 3];\n            double J1_global[3 * 4], J2_global[3 * 4], J3_global[3 * 4], J4_global[3 * 4];\n            Mat3<double> J1, J2, J3, J4;\n\n\n            double const *const inputs[] = {v1_vec[i].data(),\n                                            R1_vec[i].value().coeffs().data(),\n                                            R2_vec[i].value().coeffs().data(),\n                                            R3_vec[i].value().coeffs().data(),\n                                            R4_vec[i].value().coeffs().data()};\n            double *jacobians[] = {J0, J1_global, J2_global, J3_global, J4_global};\n\n            // Compute result and global (3*4) jacobians\n            cost_function->Evaluate(inputs, res, jacobians);\n\n            // Compute local (3*3) jacobians\n            double J_global_local[4 * 3];\n            qp.ComputeJacobian(R1_vec[i].value().coeffs().data(), J_global_local);\n            J1 = InMat34d{J1_global} * InMat43d{J_global_local};\n            qp.ComputeJacobian(R2_vec[i].value().coeffs().data(), J_global_local);\n            J2 = InMat34d{J2_global} * InMat43d{J_global_local};\n            qp.ComputeJacobian(R3_vec[i].value().coeffs().data(), J_global_local);\n            J3 = InMat34d{J3_global} * InMat43d{J_global_local};\n            qp.ComputeJacobian(R4_vec[i].value().coeffs().data(), J_global_local);\n            J4 = InMat34d{J4_global} * InMat43d{J_global_local};\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J1);\n            benchmark::DoNotOptimize(J2);\n            benchmark::DoNotOptimize(J3);\n            benchmark::DoNotOptimize(J4);\n        }\n    }\n}\n\nBENCHMARK_F(RotateChain, ceres5)(benchmark::State &state) {\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor5, 3, 3, 4, 4, 4, 4, 4>{\n        new ChainFunctor5()}};\n\n    ceres::EigenQuaternionParameterization qp{};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            double res[3];\n            double J0[3 * 3];\n            double J1_global[3 * 4], J2_global[3 * 4], J3_global[3 * 4], J4_global[3 * 4],\n              J5_global[3 * 4];\n            Mat3<double> J1, J2, J3, J4, J5;\n\n\n            double const *const inputs[] = {v1_vec[i].data(),\n                                            R1_vec[i].value().coeffs().data(),\n                                            R2_vec[i].value().coeffs().data(),\n                                            R3_vec[i].value().coeffs().data(),\n                                            R4_vec[i].value().coeffs().data(),\n                                            R5_vec[i].value().coeffs().data()};\n            double *jacobians[] = {\n              J0, J1_global, J2_global, J3_global, J4_global, J5_global};\n\n            // Compute result and global (3*4) jacobians\n            cost_function->Evaluate(inputs, res, jacobians);\n\n            // Compute local (3*3) jacobians\n            double J_global_local[4 * 3];\n            qp.ComputeJacobian(R1_vec[i].value().coeffs().data(), J_global_local);\n            J1 = InMat34d{J1_global} * InMat43d{J_global_local};\n            qp.ComputeJacobian(R2_vec[i].value().coeffs().data(), J_global_local);\n            J2 = InMat34d{J2_global} * InMat43d{J_global_local};\n            qp.ComputeJacobian(R3_vec[i].value().coeffs().data(), J_global_local);\n            J3 = InMat34d{J3_global} * InMat43d{J_global_local};\n            qp.ComputeJacobian(R4_vec[i].value().coeffs().data(), J_global_local);\n            J4 = InMat34d{J4_global} * InMat43d{J_global_local};\n            qp.ComputeJacobian(R5_vec[i].value().coeffs().data(), J_global_local);\n            J5 = InMat34d{J5_global} * InMat43d{J_global_local};\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J1);\n            benchmark::DoNotOptimize(J2);\n            benchmark::DoNotOptimize(J3);\n            benchmark::DoNotOptimize(J4);\n            benchmark::DoNotOptimize(J5);\n        }\n    }\n}\n\nBENCHMARK_F(RotateChain, ceres6)(benchmark::State &state) {\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor6, 3, 3, 4, 4, 4, 4, 4, 4>{\n        new ChainFunctor6()}};\n\n    ceres::EigenQuaternionParameterization qp{};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            double res[3];\n            double J0[3 * 3];\n            double J_global[6][3 * 4];\n            EigenVector<Mat3<double>> J_local(6);\n\n\n            double const *const inputs[] = {v1_vec[i].data(),\n                                            R1_vec[i].value().coeffs().data(),\n                                            R2_vec[i].value().coeffs().data(),\n                                            R3_vec[i].value().coeffs().data(),\n                                            R4_vec[i].value().coeffs().data(),\n                                            R5_vec[i].value().coeffs().data(),\n                                            R6_vec[i].value().coeffs().data()};\n            double *jacobians[] = {J0,\n                                   J_global[0],\n                                   J_global[1],\n                                   J_global[2],\n                                   J_global[3],\n                                   J_global[4],\n                                   J_global[5]};\n\n            // Compute result and global (3*4) jacobians\n            cost_function->Evaluate(inputs, res, jacobians);\n\n            // Compute local (3*3) jacobians\n            double J_global_local[4 * 3];\n            for (int i = 0; i < 6; ++i) {\n                qp.ComputeJacobian(R1_vec[i].value().coeffs().data(), J_global_local);\n                J_local[i] = InMat34d{J_global[i]} * InMat43d{J_global_local};\n            }\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J_local);\n        }\n    }\n}\n\nBENCHMARK_F(RotateChain, ceres7)(benchmark::State &state) {\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor7, 3, 3, 4, 4, 4, 4, 4, 4, 4>{\n        new ChainFunctor7()}};\n\n    ceres::EigenQuaternionParameterization qp{};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            double res[3];\n            double J0[3 * 3];\n            double J_global[7][3 * 4];\n            EigenVector<Mat3<double>> J_local(7);\n\n\n            double const *const inputs[] = {v1_vec[i].data(),\n                                            R1_vec[i].value().coeffs().data(),\n                                            R2_vec[i].value().coeffs().data(),\n                                            R3_vec[i].value().coeffs().data(),\n                                            R4_vec[i].value().coeffs().data(),\n                                            R5_vec[i].value().coeffs().data(),\n                                            R6_vec[i].value().coeffs().data(),\n                                            R7_vec[i].value().coeffs().data()};\n            double *jacobians[] = {J0,\n                                   J_global[0],\n                                   J_global[1],\n                                   J_global[2],\n                                   J_global[3],\n                                   J_global[4],\n                                   J_global[5],\n                                   J_global[6]};\n\n            // Compute result and global (3*4) jacobians\n            cost_function->Evaluate(inputs, res, jacobians);\n\n            // Compute local (3*3) jacobians\n            double J_global_local[4 * 3];\n            for (int i = 0; i < 7; ++i) {\n                qp.ComputeJacobian(R1_vec[i].value().coeffs().data(), J_global_local);\n                J_local[i] = InMat34d{J_global[i]} * InMat43d{J_global_local};\n            }\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J_local);\n        }\n    }\n}\n\nWAVE_BENCHMARK_MAIN()\n", "meta": {"hexsha": "359e5e26b6cb0f3f0b903261f3af52338f8f8094", "size": 17776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/rotate_chain/rotate_chain_ceres_quat_bench.cpp", "max_stars_repo_name": "wavelab/wave_geometry", "max_stars_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2018-05-07T00:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:14:07.000Z", "max_issues_repo_path": "benchmarks/rotate_chain/rotate_chain_ceres_quat_bench.cpp", "max_issues_repo_name": "wavelab/wave_geometry", "max_issues_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-08-02T20:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T17:45:29.000Z", "max_forks_repo_path": "benchmarks/rotate_chain/rotate_chain_ceres_quat_bench.cpp", "max_forks_repo_name": "wavelab/wave_geometry", "max_forks_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-05-27T01:08:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T13:46:31.000Z", "avg_line_length": 37.0333333333, "max_line_length": 90, "alphanum_fraction": 0.5168766877, "num_tokens": 4825, "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": "#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": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/ext/std/integral_constant.hpp>\n#include <boost/hana/ext/std/tuple.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/pair.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/type.hpp>\n\n#include <sstream>\n#include <string>\n#include <type_traits>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [comparable]\nBOOST_HANA_CONSTEXPR_CHECK(make<Tuple>(1, 2, 3) == make<Tuple>(1, 2, 3));\nBOOST_HANA_CONSTEXPR_CHECK(make<Tuple>(1, 2, 3) != make<Tuple>(1, 2, 3, 4));\n//! [comparable]\n\n}{\n\n//! [orderable]\nBOOST_HANA_CONSTEXPR_CHECK(make<Tuple>(1, 2, 3) < make<Tuple>(2, 3, 4));\nBOOST_HANA_CONSTEXPR_CHECK(make<Tuple>(1, 2, 3) < make<Tuple>(1, 2, 3, 4));\n//! [orderable]\n\n}{\n\n//! [foldable]\nauto to_string = [](auto x) {\n    return static_cast<std::ostringstream const&>(std::ostringstream{} << x).str();\n};\n\nauto show = [=](auto x, auto y) {\n    return \"(\" + to_string(x) + \" + \" + to_string(y) + \")\";\n};\n\nBOOST_HANA_RUNTIME_CHECK(foldl(make<Tuple>(2, \"3\", '4'), \"1\", show) == \"(((1 + 2) + 3) + 4)\");\n//! [foldable]\n\n}{\n\n//! [iterable]\nBOOST_HANA_CONSTEXPR_CHECK(head(make<Tuple>(1, '2', 3.3)) == 1);\nBOOST_HANA_CONSTEXPR_CHECK(tail(make<Tuple>(1, '2', 3.3)) == make<Tuple>('2', 3.3));\nBOOST_HANA_CONSTANT_CHECK(!is_empty(make<Tuple>(1, '2', 3.3)));\nBOOST_HANA_CONSTANT_CHECK(is_empty(make<Tuple>()));\n//! [iterable]\n\n}{\n\n//! [searchable]\nusing namespace std::string_literals;\n\nBOOST_HANA_RUNTIME_CHECK(\n    find_if(make<Tuple>(1, '2', 3.3, \"abc\"s), is_a<std::string>) == just(\"abc\"s)\n);\n\nBOOST_HANA_RUNTIME_CHECK(\n    \"abc\"s ^in^ make<Tuple>(1, '2', 3.3, \"abc\"s)\n);\n//! [searchable]\n\n}{\n\n//! [functor]\nauto to_string = [](auto x) {\n    return static_cast<std::ostringstream const&>(std::ostringstream{} << x).str();\n};\n\nBOOST_HANA_RUNTIME_CHECK(\n    transform(make<Tuple>(1, '2', \"345\", std::string{\"67\"}), to_string) ==\n    make<Tuple>(\"1\", \"2\", \"345\", \"67\")\n);\n//! [functor]\n\n}{\n\n//! [applicative]\nBOOST_HANA_CONSTEXPR_CHECK(lift<Tuple>('x') == make<Tuple>('x'));\nBOOST_HANA_CONSTEXPR_CHECK(equal(lift<ext::std::Tuple>('x'), std::make_tuple('x')));\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto f = pair;\nBOOST_HANA_CONSTEXPR_LAMBDA auto g = flip(pair);\nBOOST_HANA_CONSTEXPR_CHECK(\n    ap(make<Tuple>(f, g), make<Tuple>(1, 2, 3), make<Tuple>('a', 'b'))\n        ==\n    make<Tuple>(\n        f(1, 'a'), f(1, 'b'), f(2, 'a'), f(2, 'b'), f(3, 'a'), f(3, 'b'),\n        g(1, 'a'), g(1, 'b'), g(2, 'a'), g(2, 'b'), g(3, 'a'), g(3, 'b')\n    )\n);\n//! [applicative]\n\n}{\n\n//! [monad]\nBOOST_HANA_CONSTEXPR_LAMBDA auto f = [](auto x) {\n    return make<Tuple>(x, -x);\n};\n\nBOOST_HANA_CONSTEXPR_CHECK((make<Tuple>(1, 2, 3) | f) == make<Tuple>(1, -1, 2, -2, 3, -3));\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    flatten(make<Tuple>(make<Tuple>(1, 2), make<Tuple>(3, 4), make<Tuple>(make<Tuple>(5, 6))))\n    ==\n    make<Tuple>(1, 2, 3, 4, make<Tuple>(5, 6))\n);\n//! [monad]\n\n}{\n\n//! [monad_plus]\nusing namespace std::string_literals;\n\nBOOST_HANA_CONSTANT_CHECK(empty<Tuple>() == make<Tuple>());\nBOOST_HANA_CONSTEXPR_CHECK(\n    append(make<Tuple>(1, '2', 3.3), nullptr) == make<Tuple>(1, '2', 3.3, nullptr)\n);\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    concat(make<Tuple>(1, '2', 3.3), make<Tuple>(\"abcdef\"s)) ==\n    make<Tuple>(1, '2', 3.3, \"abcdef\"s)\n);\n//! [monad_plus]\n\n}{\n\n//! [traversable]\nusing namespace std::string_literals;\n\nBOOST_HANA_RUNTIME_CHECK(\n    sequence<Tuple>(\n        make<Tuple>(make<Tuple>(\"a1\"s, \"a2\"s),\n                    make<Tuple>(\"b1\"s),\n                    make<Tuple>(\"c1\"s, \"c2\"s, \"c3\"s))\n    )\n    ==\n    make<Tuple>(\n        make<Tuple>(\"a1\"s, \"b1\"s, \"c1\"s),\n        make<Tuple>(\"a1\"s, \"b1\"s, \"c2\"s),\n        make<Tuple>(\"a1\"s, \"b1\"s, \"c3\"s),\n\n        make<Tuple>(\"a2\"s, \"b1\"s, \"c1\"s),\n        make<Tuple>(\"a2\"s, \"b1\"s, \"c2\"s),\n        make<Tuple>(\"a2\"s, \"b1\"s, \"c3\"s)\n    )\n);\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto half = [](auto x) {\n    return if_(x % int_<2> == int_<0>,\n        just(x / int_<2>),\n        nothing\n    );\n};\n\nBOOST_HANA_CONSTANT_CHECK(\n    traverse<Maybe>(make<Tuple>(int_<2>, int_<4>, int_<6>), half)\n    ==\n    just(make<Tuple>(int_<1>, int_<2>, int_<3>))\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    traverse<Maybe>(make<Tuple>(int_<2>, int_<3>, int_<6>), half)\n    ==\n    nothing\n);\n//! [traversable]\n\n}{\n\n//! [make]\nBOOST_HANA_CONSTANT_CHECK(make<Tuple>() == make<Tuple>());\nBOOST_HANA_CONSTEXPR_CHECK(make<Tuple>(1, '2', 3.3) == make<Tuple>(1, '2', 3.3));\n//! [make]\n\n}{\n\n//! [init]\nusing namespace literals;\nBOOST_HANA_CONSTANT_CHECK(init(make<Tuple>(1)) == make<Tuple>());\nBOOST_HANA_CONSTEXPR_CHECK(init(make<Tuple>(1, '2', 3.3, 4_c)) == make<Tuple>(1, '2', 3.3));\n//! [init]\n\n}{\n\n//! [intersperse]\nBOOST_HANA_CONSTEXPR_CHECK(\n    intersperse(make<Tuple>(1, '2', 3.3), 'x') == make<Tuple>(1, 'x', '2', 'x', 3.3)\n);\nBOOST_HANA_CONSTANT_CHECK(intersperse(make<Tuple>(), 'x') == make<Tuple>());\n//! [intersperse]\n\n}{\n\n//! [remove_at]\nBOOST_HANA_CONSTEXPR_CHECK(\n    remove_at(int_<2>, make<Tuple>(0, '1', 2.2, 3u)) == make<Tuple>(0, '1', 3u)\n);\n//! [remove_at]\n\n}{\n\n//! [remove_at_c]\nBOOST_HANA_CONSTEXPR_CHECK(\n    remove_at_c<2>(make<Tuple>(0, '1', 2.2, 3u)) == make<Tuple>(0, '1', 3u)\n);\n//! [remove_at_c]\n\n}{\n\n//! [reverse]\nBOOST_HANA_CONSTEXPR_CHECK(reverse(make<Tuple>(1, '2', 3.3)) == make<Tuple>(3.3, '2', 1));\n//! [reverse]\n\n}{\n\n//! [group_by]\nBOOST_HANA_CONSTEXPR_CHECK(\n    group_by(equal ^on^ decltype_,\n        make<Tuple>(1, 2, 3, 'x', 'y', 4.4, 5.5)\n    )\n    == make<Tuple>(\n        make<Tuple>(1, 2, 3),\n        make<Tuple>('x', 'y'),\n        make<Tuple>(4.4, 5.5)\n    )\n);\n//! [group_by]\n\n}{\n\n//! [group]\nBOOST_HANA_CONSTANT_CHECK(\n    group(make<Tuple>(int_<1>, long_<1>, type<int>, char_<'x'>, char_<'x'>))\n    ==\n    make<Tuple>(\n        make<Tuple>(int_<1>, long_<1>),\n        make<Tuple>(type<int>),\n        make<Tuple>(char_<'x'>, char_<'x'>)\n    )\n);\n//! [group]\n\n}{\n\n//! [zip]\nBOOST_HANA_CONSTEXPR_CHECK(\n    zip(make<Tuple>(1, 'a'), make<Tuple>(2, 3.3))\n    ==\n    make<Tuple>(make<Tuple>(1, 2), make<Tuple>('a', 3.3))\n);\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    zip(make<Tuple>(1, 'a'), make<Tuple>(2, 3.3), make<Tuple>(3, 'c', \"ignored\"))\n    ==\n    make<Tuple>(make<Tuple>(1, 2, 3), make<Tuple>('a', 3.3, 'c'))\n);\n//! [zip]\n\n}{\n\n//! [zip_with]\nBOOST_HANA_CONSTEXPR_CHECK(\n    zip.with(_ * _, make<Tuple>(1, 2, 3, 4), make<Tuple>(5, 6, 7, 8, \"ignored\"))\n    ==\n    make<Tuple>(5, 12, 21, 32)\n);\n//! [zip_with]\n\n}{\n\n//! [unzip]\nBOOST_HANA_CONSTEXPR_CHECK(\n    unzip(make<Tuple>(make<Tuple>(1, '2', 3.3), make<Tuple>('4', 5.5, 6)))\n    ==\n    make<Tuple>(make<Tuple>(1, '4'), make<Tuple>('2', 5.5), make<Tuple>(3.3, 6))\n);\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    unzip(make<Tuple>(make<Tuple>(1, '2', 3.3), make<Tuple>('4', 5.5, 6, \"ignored\")))\n    ==\n    make<Tuple>(make<Tuple>(1, '4'), make<Tuple>('2', 5.5), make<Tuple>(3.3, 6))\n);\n//! [unzip]\n\n}{\n\n//! [take_while]\nusing namespace literals;\nBOOST_HANA_CONSTANT_CHECK(\n    take_while(tuple_c<int, 0, 1, 2, 3>, _ < 2_c)\n    ==\n    tuple_c<int, 0, 1>\n);\n//! [take_while]\n\n}{\n\n//! [take_until]\nusing namespace literals;\nBOOST_HANA_CONSTANT_CHECK(\n    take_until(tuple_c<int, 3, 2, 1, 0>, _ < 2_c)\n    ==\n    tuple_c<int, 3, 2>\n);\n//! [take_until]\n\n}{\n\n//! [take]\nusing namespace literals;\nBOOST_HANA_CONSTANT_CHECK(take(0_c, make<Tuple>(1, '2', 3.3)) == make<Tuple>());\nBOOST_HANA_CONSTEXPR_CHECK(take(1_c, make<Tuple>(1, '2', 3.3)) == make<Tuple>(1));\nBOOST_HANA_CONSTEXPR_CHECK(take(2_c, make<Tuple>(1, '2', 3.3)) == make<Tuple>(1, '2'));\nBOOST_HANA_CONSTEXPR_CHECK(take(3_c, make<Tuple>(1, '2', 3.3)) == make<Tuple>(1, '2', 3.3));\nBOOST_HANA_CONSTEXPR_CHECK(take(4_c, make<Tuple>(1, '2', 3.3)) == make<Tuple>(1, '2', 3.3));\n//! [take]\n\n}{\n\n//! [take_c]\nBOOST_HANA_CONSTEXPR_CHECK(take_c<2>(make<Tuple>(1, '2', 3.3)) == make<Tuple>(1, '2'));\n//! [take_c]\n\n}{\n\n//! [span]\nBOOST_HANA_CONSTEXPR_LAMBDA auto xs = make<Tuple>(int_<1>, int_<2>, int_<3>, int_<4>);\nBOOST_HANA_CONSTANT_CHECK(\n    span(xs, _ < int_<3>)\n    ==\n    pair(make<Tuple>(int_<1>, int_<2>), make<Tuple>(int_<3>, int_<4>))\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    span(xs, _ < int_<0>)\n    ==\n    pair(make<Tuple>(), xs)\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    span(xs, _ < int_<5>)\n    ==\n    pair(xs, make<Tuple>())\n);\n//! [span]\n\n}{\n\n//! [sort]\nusing namespace literals;\nBOOST_HANA_CONSTANT_CHECK(\n    sort(make<Tuple>(1_c, -2_c, 3_c, 0_c)) == make<Tuple>(-2_c, 0_c, 1_c, 3_c)\n);\n//! [sort]\n\n}{\n\n//! [sort_by]\nusing namespace literals;\nBOOST_HANA_CONSTANT_CHECK(\n    sort_by(_>_, make<Tuple>(1_c, -2_c, 3_c, 0_c))\n    ==\n    make<Tuple>(3_c, 1_c, 0_c, -2_c)\n);\n//! [sort_by]\n\n}{\n\n//! [slice]\nBOOST_HANA_CONSTEXPR_CHECK(\n    slice(make<Tuple>(1, '2', 3.3, type<float>), int_<1>, int_<3>)\n    ==\n    make<Tuple>('2', 3.3)\n);\n//! [slice]\n\n}{\n\n//! [slice_c]\nBOOST_HANA_CONSTEXPR_CHECK(\n    slice_c<1, 3>(make<Tuple>(1, '2', 3.3, type<float>))\n    ==\n    make<Tuple>('2', 3.3)\n);\n//! [slice_c]\n\n}{\n\n//! [permutations]\nBOOST_HANA_CONSTEXPR_LAMBDA auto is_permutation_of = curry<2>([](auto xs, auto perm) {\n    return elem(permutations(xs), perm);\n});\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    all_of(\n        make<Tuple>(\n            make<Tuple>('1', 2, 3.0),\n            make<Tuple>('1', 3.0, 2),\n            make<Tuple>(2, '1', 3.0),\n            make<Tuple>(2, 3.0, '1'),\n            make<Tuple>(3.0, '1', 2),\n            make<Tuple>(3.0, 2, '1')\n        ),\n        is_permutation_of(make<Tuple>('1', 2, 3.0))\n    )\n);\n//! [permutations]\n\n}{\n\n//! [unfoldl]\nBOOST_HANA_CONSTEXPR_LAMBDA auto f = [](auto x) {\n    return if_(x == int_<0>, nothing, just(pair(x - int_<1>, x)));\n};\n\nBOOST_HANA_CONSTANT_CHECK(\n    unfoldl<Tuple>(f, int_<10>)\n    ==\n    tuple_c<int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10>\n);\n//! [unfoldl]\n\n}{\n\n//! [unfoldr]\nBOOST_HANA_CONSTEXPR_LAMBDA auto f = [](auto x) {\n    return if_(x == int_<0>, nothing, just(pair(x, x - int_<1>)));\n};\n\nBOOST_HANA_CONSTANT_CHECK(\n    unfoldr<Tuple>(f, int_<10>)\n    ==\n    tuple_c<int, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1>\n);\n//! [unfoldr]\n\n}{\n\n//! [scanl]\nauto to_string = [](auto x) {\n    return static_cast<std::ostringstream const&>(std::ostringstream{} << x).str();\n};\n\nauto show = [=](auto x, auto y) {\n    return \"(\" + to_string(x) + \" + \" + to_string(y) + \")\";\n};\n\nBOOST_HANA_RUNTIME_CHECK(scanl(make<Tuple>(2, \"3\", '4'), 1, show) == make<Tuple>(\n    1,\n    \"(1 + 2)\",\n    \"((1 + 2) + 3)\",\n    \"(((1 + 2) + 3) + 4)\"\n));\n//! [scanl]\n\n}{\n\n//! [scanl1]\nauto to_string = [](auto x) {\n    return static_cast<std::ostringstream const&>(std::ostringstream{} << x).str();\n};\n\nauto show = [=](auto x, auto y) {\n    return \"(\" + to_string(x) + \" + \" + to_string(y) + \")\";\n};\n\nBOOST_HANA_RUNTIME_CHECK(scanl1(make<Tuple>(1, \"2\", '3'), show) == make<Tuple>(\n    1,\n    \"(1 + 2)\",\n    \"((1 + 2) + 3)\"\n));\n//! [scanl1]\n\n}{\n\n//! [scanr]\nauto to_string = [](auto x) {\n    return static_cast<std::ostringstream const&>(std::ostringstream{} << x).str();\n};\n\nauto show = [=](auto x, auto y) {\n    return \"(\" + to_string(x) + \" + \" + to_string(y) + \")\";\n};\n\nBOOST_HANA_RUNTIME_CHECK(scanr(make<Tuple>(1, \"2\", '3'), 4, show) == make<Tuple>(\n    \"(1 + (2 + (3 + 4)))\",\n    \"(2 + (3 + 4))\",\n    \"(3 + 4)\",\n    4\n));\n//! [scanr]\n\n}{\n\n//! [scanr1]\nauto to_string = [](auto x) {\n    return static_cast<std::ostringstream const&>(std::ostringstream{} << x).str();\n};\n\nauto show = [=](auto x, auto y) {\n    return \"(\" + to_string(x) + \" + \" + to_string(y) + \")\";\n};\n\nBOOST_HANA_RUNTIME_CHECK(scanr1(make<Tuple>(1, \"2\", '3'), show) == make<Tuple>(\n    \"(1 + (2 + 3))\",\n    \"(2 + 3)\",\n    '3'\n));\n//! [scanr1]\n\n}{\n\n//! [partition]\nBOOST_HANA_CONSTANT_CHECK(\n    partition(tuple_c<int, 1, 2, 3, 4, 5, 6, 7>, [](auto x) {\n        return x % int_<2> != int_<0>;\n    })\n    ==\n    pair(\n        tuple_c<int, 1, 3, 5, 7>,\n        tuple_c<int, 2, 4, 6>\n    )\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    partition(tuple_t<void, int, float, char, double>, trait<std::is_floating_point>)\n    ==\n    pair(\n        tuple_t<float, double>,\n        tuple_t<void, int, char>\n    )\n);\n//! [partition]\n\n}\n\n}\n", "meta": {"hexsha": "dcb8bc0afb978c3447058296a33dc92372c0209c", "size": 12257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/sequence.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/sequence.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/sequence.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.164556962, "max_line_length": 94, "alphanum_fraction": 0.572815534, "num_tokens": 4210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.5711479033940009}}
{"text": "#include <boost/variant.hpp>\n#include <vector>\n#include <string>\n#include <iostream>\n\ntypedef boost::variant<int, float, std::string> cell_t;\ntypedef std::vector<cell_t> db_row_t;\n\ndb_row_t get_row(const char* query) {\n\tdb_row_t row;\n\trow.push_back(10);\n\trow.push_back(10.1f);\n\trow.push_back(\"hello again\");\n\treturn row;\n}\n\nstruct db_sum_visitor : public boost::static_visitor<double> {\n\tdouble operator() (int value) const {\n\t\treturn value;\n\t}\n\t\n\tdouble operator() (float value) const {\n\t\treturn value;\n\t}\n\t\n\tdouble operator() (const std::string&) const {\n\t\treturn 0.0;\n\t}\n};\n\nint main(int argc, char **argv) {\n\tdb_row_t row = get_row(\"Give me that!\");\n\tdouble res = 0.0;\n\tdb_row_t::const_iterator it = row.begin(), end = row.end();\n\tfor(; it!=end; ++it) {\n\t\tres += boost::apply_visitor(db_sum_visitor(), *it);\n\t}\n\t\n\tstd::cout << \"Sum of arithmetic types in database row is: \" << res << std::endl;\n\treturn 0;\n}\n\n", "meta": {"hexsha": "da79587777e77c10319b42c13ca3cfc4856aa63b", "size": 913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "variant/variant-2.cpp", "max_stars_repo_name": "dexpota/boost-api-examples", "max_stars_repo_head_hexsha": "e62ba87fdee3fcb4b8448074c15e12da715bc2cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-10T05:06:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-10T05:06:27.000Z", "max_issues_repo_path": "variant/variant-2.cpp", "max_issues_repo_name": "dexpota/boost-api-examples", "max_issues_repo_head_hexsha": "e62ba87fdee3fcb4b8448074c15e12da715bc2cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "variant/variant-2.cpp", "max_forks_repo_name": "dexpota/boost-api-examples", "max_forks_repo_head_hexsha": "e62ba87fdee3fcb4b8448074c15e12da715bc2cf", "max_forks_repo_licenses": ["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.2325581395, "max_line_length": 81, "alphanum_fraction": 0.6725082147, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5711478987108709}}
{"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 \u00a9 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\u00b0 over 360\u00b0\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\u00b0 and 44\u00b0\n            cout << \"Compass angle                          \" << (90-(bearing - 90*quadrant)) << \"\u00b0\" <<     endl;\n            cout << \"Secondary compass direction:           \"<< cardinals[(quadrant+1)]<< endl;\n        }\n    }\n    //When the angle is 45\u00b0 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\u00b0 and 359\u00b0\n        angle = getBearing(angle);\n        cout << \"Your bearing is \"<<angle<< \"\u00b0C 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\u00b0 and 359\u00b0\n        angle = getBearing(angle);\n        \n        //Outputs the bearing and a correct direction\n        cout << \"Your bearing is \"<<angle<< \"\u00b0C 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": "//  (C) Copyright 2006 Eric Niebler, Olivier Gygi.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Test case for weighted_kurtosis.hpp\n\n#include <boost/random.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/numeric/functional/vector.hpp>\n#include <boost/accumulators/numeric/functional/complex.hpp>\n#include <boost/accumulators/numeric/functional/valarray.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/weighted_kurtosis.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    // tolerance in %\n    // double epsilon = 1;\n\n    accumulator_set<double, stats<tag::weighted_kurtosis>, double > acc1;\n    accumulator_set<int, stats<tag::weighted_kurtosis>, int > acc2;\n\n    // two random number generators\n    boost::lagged_fibonacci607 rng;\n    boost::normal_distribution<> mean_sigma(0,1);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal(rng, mean_sigma);\n\n    for (std::size_t i=0; i<100000; ++i)\n    {\n        acc1(normal(), weight = rng());\n    }\n\n    // This check fails because epsilon is relative and not absolute\n    // BOOST_CHECK_CLOSE( weighted_kurtosis(acc1), 0., epsilon );\n\n    acc2(2, weight = 4);\n    acc2(7, weight = 1);\n    acc2(4, weight = 3);\n    acc2(9, weight = 1);\n    acc2(3, weight = 2);\n\n    BOOST_CHECK_EQUAL( weighted_mean(acc2), 42./11. );\n    BOOST_CHECK_EQUAL( accumulators::weighted_moment<2>(acc2), 212./11. );\n    BOOST_CHECK_EQUAL( accumulators::weighted_moment<3>(acc2), 1350./11. );\n    BOOST_CHECK_EQUAL( accumulators::weighted_moment<4>(acc2), 9956./11. );\n    BOOST_CHECK_CLOSE( weighted_kurtosis(acc2), 0.58137026432, 1e-6 );\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"weighted_kurtosis test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n\n", "meta": {"hexsha": "3cedd5a25f2af8c504c2221c2d585d1017a7b419", "size": 2390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/accumulators/test/weighted_kurtosis.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/accumulators/test/weighted_kurtosis.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/accumulators/test/weighted_kurtosis.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": 33.661971831, "max_line_length": 113, "alphanum_fraction": 0.6719665272, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5710569608852298}}
{"text": "/**\r\n * @file Filter.hpp\r\n * @author Jorge Ag\u00fcero Zamora\r\n * @brief Contains `Filter` class in charge of creating filters\r\n * @version 0.1\r\n * @date 2021-06-13\r\n * \r\n */\r\n#ifndef FILTER_H\r\n#define FILTER_H\r\n\r\n#define DIRTY_IMAGE_SUFFIX \"_dirty.png\" //!< suffix used in saved noisy image filenames\r\n\r\n#include <vector>\r\n#include <string>\r\n#include <armadillo>\r\n#include <time.h>\r\n#include <chrono>\r\n\r\n#include \"FilterInfo.hpp\"\r\n#include \"VecImage.hpp\"\r\n#include \"ImageLoader.hpp\"\r\n#include \"libfrcima.hpp\"\r\n\r\nnamespace AppLogic\r\n{\r\n    using arma::mat;\r\n    using std::string;\r\n    using std::vector;\r\n    using std::chrono::duration;\r\n    using std::chrono::duration_cast;\r\n    using std::chrono::high_resolution_clock;\r\n    using std::chrono::seconds;\r\n\r\n    /**\r\n     * @brief enum with the calculation methods for the filter\r\n     * \r\n     */\r\n    typedef enum\r\n    {\r\n        RCIMA_METHOD,\r\n        FAST_RCIMA_METHOD\r\n    } calc_method_t;\r\n\r\n    /**\r\n     * @brief Allows to create filters based on training sets of images\r\n     * \r\n     */\r\n    class Filter\r\n    {\r\n    private:\r\n        FilterInfo calc_info; //!< filter calculation information\r\n        vector<VecImage> working_images; //!< list of loaded images \r\n        mat image_set; //!< training matrix of loaded images\r\n        vector<string> loaded_file_paths; //!< paths to the loaded image files \r\n        vector<string> loaded_file_names; //!< names of the loaded images\r\n        noise_type_t last_used_noise_type; //!< last noise type used\r\n        size_t last_used_noise_value; //!< last noise value used\r\n        bool is_canceled; //!< indicates whether filter calculation has been canceled\r\n        mat F_matrix; //!< created filter matrix\r\n\r\n        /**\r\n         * @brief generates training matrix out of the loaded images\r\n         * \r\n         * @return mat training matrix where each column is a vectorized form of each loaded image\r\n         */\r\n        mat getWorkingImagesMat();\r\n\r\n        /**\r\n         * @brief generates training matrix out of the loaded images applying last used noise on them\r\n         * \r\n         * @return mat training matrix where each column is a vectorized form of each loaded image with noise applied\r\n         */\r\n        mat getDirtyWorkingImagesMat();\r\n\r\n    public:\r\n        /**\r\n         * @brief Construct a new Filter object\r\n         * \r\n         */\r\n        Filter();\r\n\r\n        /**\r\n         * @brief applies selected noise to an image and returns a new image object\r\n         * \r\n         * @param image_id the index of the loaded image to apply noise to\r\n         * @param noise_value percentage value (0-99) of amount of noise to apply\r\n         * @param noise_type type of noise to apply to the image         \r\n         * @return VecImage new VecImage with the applied noise\r\n         */\r\n        VecImage applyNoiseToImage(size_t image_id, size_t noise_value, noise_type_t noise_type = noise_type_t::GAUSSIAN);\r\n\r\n        /**\r\n         * @brief sets the name of the filter\r\n         * \r\n         * @param name name of the filter\r\n         */\r\n        inline void setFilterName(string name)\r\n        {\r\n            this->calc_info.filter_name = name;\r\n        }\r\n\r\n        /**\r\n         * @brief Get the Fmatrix object\r\n         * \r\n         * @return mat& filter matrix\r\n         */\r\n        inline mat &getFmatrix()\r\n        {\r\n            return this->F_matrix;\r\n        };\r\n\r\n        /**\r\n         * @brief Get the Filter Info object\r\n         * \r\n         * @return FilterInfo* filter calculation information\r\n         */\r\n        inline FilterInfo *getFilterInfo()\r\n        {\r\n            return &this->calc_info;\r\n        };\r\n\r\n        /**\r\n         * @brief removes all loaded image information\r\n         * \r\n         */\r\n        inline void clearWorkingImages()\r\n        {\r\n            this->working_images.clear();\r\n            this->loaded_file_paths.clear();\r\n            this->loaded_file_names.clear();\r\n        }\r\n\r\n        /**\r\n         * @brief loads images from specified full path to a folder\r\n         * \r\n         * This function will look for the first valid image in the folder and will load \r\n         * all other valid images of the same resolution as that first loaded image, other \r\n         * images are ignored.\r\n         * \r\n         * @param folder_path full path to the directory containing the images\r\n         * @return vector<string> list of names of the images that were loaded\r\n         */\r\n        vector<string> loadImagesFromFolder(string folder_path);\r\n\r\n        /**\r\n         * @brief loads a single image and adds it to the working images\r\n         * \r\n         * @param file_path path of the image file\r\n         * @return string name of the loaded image\r\n         */\r\n        string loadSingleImage(string folder_path);\r\n\r\n        /**\r\n         * @brief load images from a zip file\r\n         * \r\n         * This function will go through all files in a zip file. It  will look for the first \r\n         * valid image in the folder and will load all other valid images of the same resolution\r\n         * as the first loaded image, other images are ignored.\r\n         * \r\n         * @param file_path full path of a valid zip file\r\n         * @return vector<string> list of names of the images that were loaded\r\n         */\r\n        vector<string> loadImagesFromZip(string file_path);\r\n\r\n        /**\r\n         * @brief returns the path of the loaded image specified by index\r\n         * \r\n         * @param index the index of the loaded image to get the path for\r\n         * @return string path of the loaded image in the filesystem\r\n         */\r\n        string getImagePath(size_t index);\r\n\r\n        /**\r\n         * @brief returns a pointer to the loaded VecImage specified by index\r\n         * \r\n         * @param index the index of the loaded image to get\r\n         * @return VecImage* pointer to the VecImage object of the loaded image\r\n         */\r\n        VecImage *getLoadedImage(const size_t index);\r\n\r\n        /**\r\n         * @brief calculates the filter\r\n         * \r\n         * Calculates the filter using the last noise type and value applied, rank, and selected calculation method.\r\n         * Sets the calculation information in `calc_info`\r\n         * \r\n         * @param rank the rank to use for filter calculation. Must be a value between 1 and the minimun between the amount\r\n         *              of images used and the size of the vectorized image.\r\n         * @param calc_method calculation method to use. Either RCIMA or fast-RCIMA\r\n         * @return true if calculation is successful\r\n         * @return false if an error is encountered during calculation or calculation is canceled\r\n         */\r\n        bool calculateFilter(size_t rank, calc_method_t calc_method);\r\n\r\n        /**\r\n         * @brief saves filter matrix to file\r\n         * \r\n         * @param file_path full path of the file where the matrix will be saved\r\n         * @return true if matrix is saved successfully\r\n         * @return false if there is an error saving the matrix\r\n         */\r\n        bool saveToFile(string file_path = ImageLoader::FILTER_SAVE_LOCATION);\r\n\r\n        /**\r\n         * @brief loads filter matrix from file\r\n         * \r\n         * @param file_path full path of the file where the matrix is stored\r\n         * @return true if matrix is loaded successfully\r\n         * @return false if there is an error loading the matrix\r\n         */\r\n        bool loadFmatrixFromFile(string file_path);\r\n\r\n        /**\r\n         * @brief applies noise to all working images and saves them in the specified path\r\n         * \r\n         * Applies noise to all loaded images using the last noise type and value applied and\r\n         * saves them to the folder path provided as PNG (.png) images. This operation does not\r\n         * modify the loaded images.\r\n         * \r\n         * @param folder_path path where the images will be saved\r\n         * @return true if images are saved correctly\r\n         * @return false if an eror is encountered or saving process is canceled\r\n         */\r\n        bool saveAllDirtyImages(string folder_path);\r\n\r\n        /**\r\n         * @brief applies noise to image and saves it in the specified path\r\n         * \r\n         * Applies noise to the loaded image specified by the index image_id, using the \r\n         * last noise type and value applied and saves it to the folder path provided \r\n         * as a PNG (.png) image. This operation does not modify the loaded image.\r\n         * \r\n         * @param image_id index of the image to apply noise to and save\r\n         * @param folder_path name of the file to save the dirty image\r\n         * @return true if image is saved corectly\r\n         * @return false if there is an error saving the image\r\n         */\r\n        bool saveDirtyImage(size_t image_id, string folder_path);\r\n\r\n        /**\r\n         * @brief saves filter calculation information in the app's data directory\r\n         * \r\n         * @param folder_path path where the filter_info is stored\r\n         * @return true if filter information is saved correctly\r\n         * @return false if there is an error saving the filter information\r\n         */\r\n        bool saveFilterInfo(string folder_path = ImageLoader::FILTER_SAVE_LOCATION);\r\n\r\n    \r\n         /**\r\n         * @brief cancels the process of saving images with noise applied\r\n         * \r\n         */\r\n        void cancelSaveDirtyImages();\r\n\r\n        /**\r\n         * @brief returns a string name for the calculation method\r\n         * \r\n         * @param calc_method calculation method\r\n         * @return string name of the calculation method\r\n         */\r\n        static string getCalculationMethodName(calc_method_t calc_method);\r\n    };\r\n\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "a162c9a1430d37e4ad7c6510d71645eedcb0722b", "size": 9729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/AppLogic/Filter.hpp", "max_stars_repo_name": "h4koo/FSP_ImageDeconvolution", "max_stars_repo_head_hexsha": "724b3c9a1a0a7c45803bd783f61e0363046a2d79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AppLogic/Filter.hpp", "max_issues_repo_name": "h4koo/FSP_ImageDeconvolution", "max_issues_repo_head_hexsha": "724b3c9a1a0a7c45803bd783f61e0363046a2d79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AppLogic/Filter.hpp", "max_forks_repo_name": "h4koo/FSP_ImageDeconvolution", "max_forks_repo_head_hexsha": "724b3c9a1a0a7c45803bd783f61e0363046a2d79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1672862454, "max_line_length": 124, "alphanum_fraction": 0.5952307534, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.571056955654358}}
{"text": "\n// Author: Steffen Urban (urbste@gmail.com)\n\n#include <Eigen/Core>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n#include <theia/theia.h>\n\n#include <algorithm>\n#include <memory>\n#include <string>\n\n#include \"print_reconstruction_statistics.h\"\n\nDEFINE_string(reconstruction, \"\", \"Reconstruction file\");\n\nint main(int argc, char* argv[]) {\n  google::InitGoogleLogging(argv[0]);\n  THEIA_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);\n\n  // Load the SIFT descriptors into the cameras.\n  std::unique_ptr<theia::Reconstruction> reconstruction(\n      new theia::Reconstruction());\n  CHECK(theia::ReadReconstruction(FLAGS_reconstruction, reconstruction.get()))\n      << \"Could not read reconstruction file.\";\n\n  std::cout << \"\\nNum views: \" << reconstruction->NumViews()\n            << \"\\nNum 3D points: \" << reconstruction->NumTracks() << \"\\n\";\n\n  theia::BundleAdjustmentOptions options;\n  for (int i = 0; i < reconstruction->TrackIds().size(); ++i) {\n    Eigen::Matrix3d cov;\n    double empirical_variance;\n    theia::BundleAdjustmentSummary summary =\n        theia::BundleAdjustTrack(options,\n                                 reconstruction->TrackIds()[i],\n                                 reconstruction.get(),\n                                 &cov,\n                                 &empirical_variance);\n\n    std::cout << \"FInal cost: \" << summary.final_cost << \"\\n\";\n    std::cout << \"standard deviations: \"\n              << cov.diagonal().array().sqrt().transpose() * 1000. << \" [mm]\\n\";\n  }\n  return 0;\n}\n", "meta": {"hexsha": "e967dd28e8fb15283ee1d9c919ffe287659583d1", "size": 1526, "ext": "cc", "lang": "C++", "max_stars_repo_path": "applications/estimate_covariance_for_tracks.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": "applications/estimate_covariance_for_tracks.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": "applications/estimate_covariance_for_tracks.cc", "max_forks_repo_name": "urbste/TheiaSfM", "max_forks_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-20T03:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T08:08:52.000Z", "avg_line_length": 32.4680851064, "max_line_length": 80, "alphanum_fraction": 0.620576671, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5710569549103272}}
{"text": "\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <CGAL/Simple_cartesian.h>\n#include <cassert>\n#include <vector>\n#include <algorithm>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/algorithm.h>\n\nusing namespace CGAL;\n\ntypedef Simple_cartesian<int>         K;\ntypedef K::Point_2                    Point;\ntypedef Creator_uniform_2<int,Point>  Creator;\n\n\nvoid\ngrid(int N, double eps)\n{\n  CGAL::Random rng;\n  std::cout << N*N << std::endl;\n  for(double i = 0; i < N; i++){\n    for(double j = 0; j < N; j++){\n      std::cout << i + rng.get_double(-eps,eps) << \" \"\n                << j + rng.get_double(-eps,eps) << \"\\n\";\n    }\n  }\n}\n\nint main(int argc, char* argv[])\n{\n  int N= 10;\n  double eps = 0;\n  try {\n\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n      (\"help\", \"Generator of perturbed points on a grid\")\n      (\"N\", po::value<int>(), \"generate a grid with N x N points\")\n      (\"eps\", po::value<double>(), \"perturb x and y of points by eps\")\n      ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n      std::cout << desc << \"\\n\";\n      return 1;\n    }\n\n    if (vm.count(\"N\")) {\n      N = vm[\"N\"].as<int>();\n    }\n\n    if (vm.count(\"eps\")) {\n      eps = vm[\"eps\"].as<double>();\n    }\n  }\n  catch(std::exception& e) {\n    std::cerr << \"error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n\n  grid(N,eps);\n  return 0;\n}\n", "meta": {"hexsha": "064409ec25b3c9d29083346a9beccfa3f1975a6e", "size": 1479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Generator/benchmark/Generator/random_grid.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": "Generator/benchmark/Generator/random_grid.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": "Generator/benchmark/Generator/random_grid.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": 21.1285714286, "max_line_length": 70, "alphanum_fraction": 0.5598377282, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.571056948191393}}
{"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": "/**\n * @file bias_svd_test.cpp\n * @author Siddharth Agrawal\n * @author Wenhao Huang\n *\n * Test the BiasSVDFunction class.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/bias_svd/bias_svd.hpp>\n\n#include <ensmallen.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::svd;\n\nBOOST_AUTO_TEST_SUITE(BiasSVDTest);\n\nBOOST_AUTO_TEST_CASE(BiasSVDFunctionRandomEvaluate)\n{\n  // Define useful constants.\n  const size_t numUsers = 100;\n  const size_t numItems = 100;\n  const size_t numRatings = 1000;\n  const size_t maxRating = 5;\n  const size_t rank = 10;\n  const size_t numTrials = 50;\n\n  // Make a random rating dataset.\n  arma::mat data = arma::randu(3, numRatings);\n  data.row(0) = floor(data.row(0) * numUsers);\n  data.row(1) = floor(data.row(1) * numItems);\n  data.row(2) = floor(data.row(2) * maxRating + 0.5);\n\n  // Manually set last row to maximum user and maximum item.\n  data(0, numRatings - 1) = numUsers - 1;\n  data(1, numRatings - 1) = numItems - 1;\n\n  // Make a BiasSVDFunction with zero regularization.\n  BiasSVDFunction<arma::mat> biasSVDFunc(data, rank, 0);\n\n  for (size_t i = 0; i < numTrials; i++)\n  {\n    arma::mat parameters = arma::randu(rank + 1, numUsers + numItems);\n\n    // Calculate cost by summing up cost of each example.\n    double cost = 0;\n    for (size_t j = 0; j < numRatings; j++)\n    {\n      const size_t user = data(0, j);\n      const size_t item = data(1, j) + numUsers;\n\n      const double rating = data(2, j);\n      const double userBias = parameters(rank, user);\n      const double itemBias = parameters(rank, item);\n      const double ratingError = rating - userBias - itemBias -\n          arma::dot(parameters.col(user).subvec(0, rank - 1),\n                    parameters.col(item).subvec(0, rank - 1));\n      const double ratingErrorSquared = ratingError * ratingError;\n\n      cost += ratingErrorSquared;\n    }\n\n    // Compare calculated cost and value obtained using Evaluate().\n    BOOST_REQUIRE_CLOSE(cost, biasSVDFunc.Evaluate(parameters), 1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(BiasSVDFunctionRegularizationEvaluate)\n{\n  // Define useful constants.\n  const size_t numUsers = 100;\n  const size_t numItems = 100;\n  const size_t numRatings = 1000;\n  const size_t maxRating = 5;\n  const size_t rank = 10;\n  const size_t numTrials = 50;\n\n  // Make a random rating dataset.\n  arma::mat data = arma::randu(3, numRatings);\n  data.row(0) = floor(data.row(0) * numUsers);\n  data.row(1) = floor(data.row(1) * numItems);\n  data.row(2) = floor(data.row(2) * maxRating + 0.5);\n\n  // Manually set last row to maximum user and maximum item.\n  data(0, numRatings - 1) = numUsers - 1;\n  data(1, numRatings - 1) = numItems - 1;\n\n  // Make three BiasSVDFunction objects with different amounts of\n  // regularization.\n  BiasSVDFunction<arma::mat> biasSVDFuncNoReg(data, rank, 0);\n  BiasSVDFunction<arma::mat> biasSVDFuncSmallReg(data, rank, 0.5);\n  BiasSVDFunction<arma::mat> biasSVDFuncBigReg(data, rank, 20);\n\n  for (size_t i = 0; i < numTrials; i++)\n  {\n    arma::mat parameters = arma::randu(rank + 1, numUsers + numItems);\n\n    // Calculate the regularization contributions of parameters corresponding to\n    // each rating and sum them up.\n    double smallRegTerm = 0;\n    double bigRegTerm = 0;\n    for (size_t j = 0; j < numRatings; j++)\n    {\n      const size_t user = data(0, j);\n      const size_t item = data(1, j) + numUsers;\n\n      const double userVecNorm = arma::norm(parameters.col(user), 2);\n      const double itemVecNorm = arma::norm(parameters.col(item), 2);\n\n      smallRegTerm += 0.5 * (userVecNorm * userVecNorm +\n                             itemVecNorm * itemVecNorm);\n      bigRegTerm += 20 * (userVecNorm * userVecNorm +\n                          itemVecNorm * itemVecNorm);\n    }\n\n    // Cost with regularization should be close to the sum of cost without\n    // regularization and the regularization terms.\n    BOOST_REQUIRE_CLOSE(biasSVDFuncNoReg.Evaluate(parameters) + smallRegTerm,\n        biasSVDFuncSmallReg.Evaluate(parameters), 1e-5);\n    BOOST_REQUIRE_CLOSE(biasSVDFuncNoReg.Evaluate(parameters) + bigRegTerm,\n        biasSVDFuncBigReg.Evaluate(parameters), 1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(BiasSVDFunctionGradient)\n{\n  // Define useful constants.\n  const size_t numUsers = 50;\n  const size_t numItems = 50;\n  const size_t numRatings = 100;\n  const size_t maxRating = 5;\n  const size_t rank = 10;\n\n  // Make a random rating dataset.\n  arma::mat data = arma::randu(3, numRatings);\n  data.row(0) = floor(data.row(0) * numUsers);\n  data.row(1) = floor(data.row(1) * numItems);\n  data.row(2) = floor(data.row(2) * maxRating + 0.5);\n\n  // Manually set last row to maximum user and maximum item.\n  data(0, numRatings - 1) = numUsers - 1;\n  data(1, numRatings - 1) = numItems - 1;\n\n  arma::mat parameters = arma::randu(rank + 1, numUsers + numItems);\n\n  // Make two BiasSVDFunction objects, one with regularization and one\n  // without.\n  BiasSVDFunction<arma::mat> biasSVDFunc1(data, rank, 0);\n  BiasSVDFunction<arma::mat> biasSVDFunc2(data, rank, 0.5);\n\n  // Calculate gradients for both the objects.\n  arma::mat gradient1, gradient2;\n  biasSVDFunc1.Gradient(parameters, gradient1);\n  biasSVDFunc2.Gradient(parameters, gradient2);\n\n  // Perturbation constant.\n  const double epsilon = 0.0001;\n  double costPlus1, costMinus1, numGradient1;\n  double costPlus2, costMinus2, numGradient2;\n\n  for (size_t i = 0; i < rank; i++)\n  {\n    for (size_t j = 0; j < numUsers + numItems; j++)\n    {\n      // Perturb parameter with a positive constant and get costs.\n      parameters(i, j) += epsilon;\n      costPlus1 = biasSVDFunc1.Evaluate(parameters);\n      costPlus2 = biasSVDFunc2.Evaluate(parameters);\n\n      // Perturb parameter with a negative constant and get costs.\n      parameters(i, j) -= 2 * epsilon;\n      costMinus1 = biasSVDFunc1.Evaluate(parameters);\n      costMinus2 = biasSVDFunc2.Evaluate(parameters);\n\n      // Compute numerical gradients using the costs calculated above.\n      numGradient1 = (costPlus1 - costMinus1) / (2 * epsilon);\n      numGradient2 = (costPlus2 - costMinus2) / (2 * epsilon);\n\n      // Restore the parameter value.\n      parameters(i, j) += epsilon;\n\n      // Compare numerical and backpropagation gradient values.\n      if (std::abs(gradient1(i, j)) <= 1e-6)\n        BOOST_REQUIRE_SMALL(numGradient1, 1e-5);\n      else\n        BOOST_REQUIRE_CLOSE(numGradient1, gradient1(i, j), 0.02);\n\n      if (std::abs(gradient2(i, j)) <= 1e-6)\n        BOOST_REQUIRE_SMALL(numGradient2, 1e-5);\n      else\n        BOOST_REQUIRE_CLOSE(numGradient2, gradient2(i, j), 0.02);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(BiasSVDOutputSizeTest)\n{\n  // Define useful constants.\n  const size_t numUsers = 100;\n  const size_t numItems = 50;\n  const size_t numRatings = 500;\n  const size_t maxRating = 5;\n  const size_t rank = 5;\n  const size_t iterations = 10;\n\n  // Make a random rating dataset.\n  arma::mat data = arma::randu(3, numRatings);\n  data.row(0) = floor(data.row(0) * numUsers);\n  data.row(1) = floor(data.row(1) * numItems);\n  data.row(2) = floor(data.row(2) * maxRating + 0.5);\n\n  // Manually set last row to maximum user and maximum item.\n  data(0, numRatings - 1) = numUsers - 1;\n  data(1, numRatings - 1) = numItems - 1;\n\n  // Resulting user/item matrices/bias.\n  arma::mat userLatent, itemLatent;\n  arma::vec userBias, itemBias;\n\n  // Apply Bias SVD.\n  BiasSVD<> biasSVD(iterations);\n  biasSVD.Apply(data, rank, itemLatent, userLatent, itemBias, userBias);\n\n  // Check the size of outputs.\n  BOOST_REQUIRE_EQUAL(itemLatent.n_rows, numItems);\n  BOOST_REQUIRE_EQUAL(itemLatent.n_cols, rank);\n  BOOST_REQUIRE_EQUAL(userLatent.n_rows, rank);\n  BOOST_REQUIRE_EQUAL(userLatent.n_cols, numUsers);\n  BOOST_REQUIRE_EQUAL(itemBias.n_elem, numItems);\n  BOOST_REQUIRE_EQUAL(userBias.n_elem, numUsers);\n}\n\nBOOST_AUTO_TEST_CASE(BiasSVDFunctionOptimize)\n{\n  // Define useful constants.\n  const size_t numUsers = 50;\n  const size_t numItems = 50;\n  const size_t numRatings = 100;\n  const size_t iterations = 30;\n  const size_t rank = 10;\n  const double alpha = 0.01;\n  const double lambda = 0.01;\n\n  // Initiate random parameters.\n  arma::mat parameters = arma::randu(rank + 1, numUsers + numItems);\n\n  // Make a random rating dataset.\n  arma::mat data = arma::randu(3, numRatings);\n  data.row(0) = floor(data.row(0) * numUsers);\n  data.row(1) = floor(data.row(1) * numItems);\n\n  // Manually set last row to maximum user and maximum item.\n  data(0, numRatings - 1) = numUsers - 1;\n  data(1, numRatings - 1) = numItems - 1;\n\n  // Make rating entries based on the parameters.\n  for (size_t i = 0; i < numRatings; i++)\n  {\n    const size_t user = data(0, i);\n    const size_t item = data(1, i) + numUsers;\n    const double userBias = parameters(rank, user);\n    const double itemBias = parameters(rank, item);\n    data(2, i) = userBias + itemBias +\n        arma::dot(parameters.col(user).subvec(0, rank - 1),\n                  parameters.col(item).subvec(0, rank - 1));\n  }\n\n  // Make the Bias SVD function and the optimizer.\n  BiasSVDFunction<arma::mat> biasSVDFunc(data, rank, lambda);\n  ens::StandardSGD optimizer(alpha, iterations * numRatings);\n\n  // Obtain optimized parameters after training.\n  arma::mat optParameters = arma::randu(rank + 1, numUsers + numItems);\n  optimizer.Optimize(biasSVDFunc, optParameters);\n\n  // Get predicted ratings from optimized parameters.\n  arma::mat predictedData(1, numRatings);\n  for (size_t i = 0; i < numRatings; i++)\n  {\n    const size_t user = data(0, i);\n    const size_t item = data(1, i) + numUsers;\n    const double userBias = optParameters(rank, user);\n    const double itemBias = optParameters(rank, item);\n    predictedData(0, i) = userBias + itemBias +\n        arma::dot(optParameters.col(user).subvec(0, rank - 1),\n                  optParameters.col(item).subvec(0, rank - 1));\n  }\n\n  // Calculate relative error.\n  const double relativeError = arma::norm(data.row(2) - predictedData, \"frob\") /\n                               arma::norm(data, \"frob\");\n\n  // Relative error should be small.\n  BOOST_REQUIRE_SMALL(relativeError, 1e-2);\n}\n\n// The test is only compiled if the user has specified OpenMP to be\n// used.\n#ifdef HAS_OPENMP\n\n// Test Bias SVD with parallel SGD.\nBOOST_AUTO_TEST_CASE(BiasSVDFunctionParallelOptimize)\n{\n  // Define useful constants.\n  const size_t numUsers = 50;\n  const size_t numItems = 50;\n  const size_t numRatings = 100;\n  const size_t rank = 10;\n  const double alpha = 0.01;\n  const double lambda = 0.01;\n\n  // Initiate random parameters.\n  arma::mat parameters = arma::randu(rank + 1, numUsers + numItems);\n\n  // Make a random rating dataset.\n  arma::mat data = arma::randu(3, numRatings);\n  data.row(0) = floor(data.row(0) * numUsers);\n  data.row(1) = floor(data.row(1) * numItems);\n\n  // Manually set last row to maximum user and maximum item.\n  data(0, numRatings - 1) = numUsers - 1;\n  data(1, numRatings - 1) = numItems - 1;\n\n  // Make rating entries based on the parameters.\n  for (size_t i = 0; i < numRatings; i++)\n  {\n    const size_t user = data(0, i);\n    const size_t item = data(1, i) + numUsers;\n    const double userBias = parameters(rank, user);\n    const double itemBias = parameters(rank, item);\n    data(2, i) = userBias + itemBias +\n        arma::dot(parameters.col(user).subvec(0, rank - 1),\n                  parameters.col(item).subvec(0, rank - 1));\n  }\n\n  // Make the Bias SVD function and the optimizer.\n  BiasSVDFunction<arma::mat> biasSVDFunc(data, rank, lambda);\n\n  ens::ConstantStep decayPolicy(alpha);\n\n  // Iterate till convergence.\n  // The threadShareSize is chosen such that each function gets optimized.\n  ens::ParallelSGD<ens::ConstantStep> optimizer(0,\n      std::ceil((float) biasSVDFunc.NumFunctions() / omp_get_max_threads()), 1e-5,\n      true, decayPolicy);\n\n  // Obtain optimized parameters after training.\n  arma::mat optParameters = arma::randu(rank + 1, numUsers + numItems);\n  optimizer.Optimize(biasSVDFunc, optParameters);\n\n  // Get predicted ratings from optimized parameters.\n  arma::mat predictedData(1, numRatings);\n  for (size_t i = 0; i < numRatings; i++)\n  {\n    const size_t user = data(0, i);\n    const size_t item = data(1, i) + numUsers;\n    const double userBias = optParameters(rank, user);\n    const double itemBias = optParameters(rank, item);\n    predictedData(0, i) = userBias + itemBias +\n        arma::dot(optParameters.col(user).subvec(0, rank - 1),\n                  optParameters.col(item).subvec(0, rank - 1));\n  }\n\n  // Calculate relative error.\n  const double relativeError = arma::norm(data.row(2) - predictedData, \"frob\") /\n                               arma::norm(data, \"frob\");\n\n  // Relative error should be small.\n  BOOST_REQUIRE_SMALL(relativeError, 1e-2);\n}\n\n#endif\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "bae98933a5e09243538555a009cb4a6f8fdf808d", "size": 13070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/bias_svd_test.cpp", "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": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-04T16:51:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-04T16:51:20.000Z", "max_issues_repo_path": "src/mlpack/tests/bias_svd_test.cpp", "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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/bias_svd_test.cpp", "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": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1253263708, "max_line_length": 82, "alphanum_fraction": 0.6758990054, "num_tokens": 3769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867585368343, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.571041950487837}}
{"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": "#include \"ExponentialPlusPiecewisePolynomial.h\"\n#include <Eigen/Core>\n#include <random>\n#include <iostream>\n#include <cmath>\n#include \"testUtil.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\ndefault_random_engine generator;\n\ntemplate <typename CoefficientType>\nvoid testSimpleCase() {\n  typedef ExponentialPlusPiecewisePolynomial<CoefficientType> ExponentialPlusPiecewisePolynomialType;\n  typedef typename ExponentialPlusPiecewisePolynomialType::MatrixX MatrixX;\n  typedef typename ExponentialPlusPiecewisePolynomialType::VectorX VectorX;\n  int num_coefficients = 5;\n  int num_segments = 1;\n\n  MatrixX K = MatrixX::Random(1, 1);\n  MatrixX A = MatrixX::Random(1, 1);\n  MatrixX alpha = MatrixX::Random(1, 1);\n\n  auto segment_times = PiecewiseFunction::randomSegmentTimes(num_segments, generator);\n  auto polynomial_part = PiecewisePolynomial<CoefficientType>::random(1, 1, num_coefficients, segment_times);\n\n  ExponentialPlusPiecewisePolynomial<CoefficientType> expPlusPp(K, A, alpha, polynomial_part);\n  ExponentialPlusPiecewisePolynomial<CoefficientType> derivative = expPlusPp.derivative();\n\n  uniform_real_distribution<CoefficientType> uniform(expPlusPp.getStartTime(), expPlusPp.getEndTime());\n  double t = uniform(generator);\n  auto check = K(0) * std::exp(A(0) * (t - expPlusPp.getStartTime())) * alpha(0) + polynomial_part.scalarValue(t);\n  auto derivative_check = K(0) * A(0) * std::exp(A(0) * (t - expPlusPp.getStartTime())) * alpha(0) + polynomial_part.derivative().scalarValue(t);\n\n  valuecheck(check, expPlusPp.value(t)(0), 1e-8);\n  valuecheck(derivative_check, derivative.value(t)(0), 1e-8);\n}\n\nint main(int argc, char **argv) {\n  testSimpleCase<double>();\n  std::cout << \"test passed\";\n  return 0;\n}\n", "meta": {"hexsha": "d0c5a783c2bcaa001dad73f584cc69df61eb79db", "size": 1715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "drake/systems/trajectories/test/testExponentialPlusPiecewisePolynomial.cpp", "max_stars_repo_name": "ericmanzi/double_pendulum_lqr", "max_stars_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T09:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T21:59:27.000Z", "max_issues_repo_path": "drake/systems/trajectories/test/testExponentialPlusPiecewisePolynomial.cpp", "max_issues_repo_name": "ericmanzi/double_pendulum_lqr", "max_issues_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drake/systems/trajectories/test/testExponentialPlusPiecewisePolynomial.cpp", "max_forks_repo_name": "ericmanzi/double_pendulum_lqr", "max_forks_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-08-24T20:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-24T20:32:03.000Z", "avg_line_length": 38.1111111111, "max_line_length": 145, "alphanum_fraction": 0.766180758, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7371581684030621, "lm_q1q2_score": 0.5709904687464602}}
{"text": "#include <algorithm>\n#include <array>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <vector>\n\n#include <boost/range/irange.hpp>\n\n/* ====================\n * SHOP INVENTORY BEGIN\n * ====================\n */\n// the dmg and ac values can be represented by the index, since they are sequential\nconstexpr auto weapons = std::array{ 8, 10, 25, 40, 74 };\nconstexpr auto armors  = std::array{ 0, 13, 31, 53, 75, 102 }; // zero cost for no armor\n\nconstexpr auto rings_dmg = std::array{ 25, 50, 100 };\nconstexpr auto rings_ac  = std::array{ 20, 40, 80 };\n\n/* ====================\n * SHOP INVENTORY END\n * ====================\n */\n\n/* =====================\n * PRECALCULATIONS BEGIN\n * =====================\n */\nconstexpr auto MAX_NUM_RINGS = 2;\nconstexpr auto MIN_WPN_DMG   = 4;\nconstexpr auto MIN_DMG       = 1;\n\ntemplate<typename T>\nconstexpr auto factorial(T n) -> T {\n    return (n > 1) ? (n * factorial(n-1)) : 1;\n}\n\ntemplate<typename N, typename K>\nconstexpr auto binomial_coefficient(N n, K k) {\n  return (factorial(n) / (factorial(k) * factorial(n-k)));\n}\n\nconstexpr auto num_ring_combos(const int n) {\n  auto num_combos = 0;\n  for(auto k = 0; k <= MAX_NUM_RINGS; ++k) {\n    num_combos += binomial_coefficient(n, k);\n  }\n  return num_combos;\n}\n\nstruct RingComboStats {\n  int num_rings,\n      rings_cost,\n      bonuses;\n};\n\ntemplate<typename Array>\nconstexpr auto ring_combo_stats(Array rings) {\n\n  constexpr auto rings_size = rings.size();\n  constexpr auto array_size = num_ring_combos(rings_size);\n\n  auto stats = std::array<RingComboStats, array_size>{};\n\n  // first combo is the one with no rings\n  stats.front() = {};\n\n  auto current = 1;\n\n  for(auto i = 0; i < static_cast<decltype(i)>(rings_size); ++i) {\n\n    const auto ring_i = rings[i];\n\n    // the i'th ring (0,1,2) has a bonus of (1,2,3) -> (i + 1)\n    stats[current++] = { 1 , ring_i, (i + 1) };\n\n    for(auto j = (i + 1); j < static_cast<decltype(j)>(rings_size); ++j) {\n\n      // the i'th + j'th rings have a bonus of (i+1) + (j+1) -> (i + j + 2)\n      stats[current++] = { 2, (ring_i + rings[j]), (i + j + 2) };\n    }\n  }\n\n  return stats;\n}\n\nconstexpr auto ring_dmg_combos = ring_combo_stats(rings_dmg);\nconstexpr auto ring_ac_combos  = ring_combo_stats(rings_ac);\n\ntemplate<typename T, typename U>\nconstexpr auto costs_size(const T& items, const U& ring_combos) {\n  const auto max_combo_cost = std::max_element(ring_combos.begin(), ring_combos.end(), [] (const auto& lhs, const auto& rhs) {\n    return lhs.bonuses < rhs.bonuses;\n  });\n  return (items.size() + max_combo_cost->bonuses);\n}\n\nconstexpr auto dmg_costs_size = costs_size(weapons, ring_dmg_combos);\nconstexpr auto ac_costs_size  = costs_size(armors, ring_ac_combos);\n\nstruct ComboCost {\n  int total_cost,\n      num_rings;\n};\n\nstruct CostLookup {\n  std::array<std::vector<ComboCost>, dmg_costs_size> dmg_combo_costs;\n  std::array<std::vector<ComboCost>, ac_costs_size>  ac_combo_costs;\n};\n\nauto precalc_combo_costs() {\n\n  auto lookup = CostLookup{};\n\n  const auto precalc = [] (const auto& items, const auto& ring_combos, auto& lookup) {\n    for(const auto i : boost::irange(items.size())) {\n      const auto item_cost = items[i];\n      for(const auto& combo_stats : ring_combos) {\n        lookup[i+combo_stats.bonuses].push_back({\n          (item_cost + combo_stats.rings_cost),\n          combo_stats.num_rings\n        });\n      }\n    }\n  };\n\n  precalc(weapons, ring_dmg_combos, lookup.dmg_combo_costs);\n  precalc(armors, ring_ac_combos, lookup.ac_combo_costs);\n\n  return lookup;\n}\n\n/* =====================\n * PRECALCULATIONS END\n * =====================\n */\n\nstruct Entity {\n  int health,\n      damage,\n      armor;\n};\n\nauto run_game(const CostLookup& lookup, const Entity& boss, const int player_hp) {\n\n  const auto min_armor_to_lose = [&] (const int player_dmg) {\n    const auto player_real_dmg = std::max((player_dmg - boss.armor), MIN_DMG);\n    const auto num_rounds_to_win = ((boss.health / player_real_dmg) + ((boss.health % player_real_dmg) > 0));\n    const auto num_rounds_to_last = (num_rounds_to_win - 1);\n    const auto max_health_loss_per_round = (player_hp / num_rounds_to_last);\n\n    // if player has no hp left after num_rounds_to_last, then they need extra armor\n    const auto extra_armor = ((player_hp % num_rounds_to_last) == 0);\n    const auto min_armor_to_win = (boss.damage - max_health_loss_per_round + extra_armor);\n\n    // if min_armor is below minimum required for a win, then that's a loss\n    return (min_armor_to_win - 1);\n  };\n\n  auto max_cost = std::numeric_limits<int>::min();\n\n  const auto& dmg_combo_costs = lookup.dmg_combo_costs;\n  const auto& ac_combo_costs  = lookup.ac_combo_costs;\n\n  for(const auto i : boost::irange(dmg_combo_costs.size())) {\n    /*\n     * MIN_WPN_DMG is there because we need to adjust the damage value\n     * represented by the index of the array we are iterating over,\n     * which was started from 0 for convenience in the precalculations\n     */\n    const auto player_dmg = (i + MIN_WPN_DMG);\n\n    const auto min_armor = min_armor_to_lose(player_dmg);\n\n    using Type = std::decay_t<decltype(min_armor)>;\n\n    // suppress gcc warning\n    if(min_armor < static_cast<Type>(ac_combo_costs.size())) {\n\n      for(const auto& ac_combo_cost : ac_combo_costs[min_armor]) {\n\n        for(const auto& dmg_combo_cost : dmg_combo_costs[i]) {\n\n          const auto num_rings = (ac_combo_cost.num_rings + dmg_combo_cost.num_rings);\n\n          if(num_rings <= MAX_NUM_RINGS) {\n\n            const auto new_cost = (ac_combo_cost.total_cost + dmg_combo_cost.total_cost);\n\n            max_cost = std::max(new_cost, max_cost);\n          }\n        }\n      }\n    }\n  }\n\n  return max_cost;\n}\n\nauto solution(const Entity& boss, const int player_hp) {\n  const auto& lookup = precalc_combo_costs();\n  const auto max_cost = run_game(lookup, boss, player_hp);\n  return max_cost;\n}\n\n\nint main() {\n\n  const auto boss = Entity{103, 9, 2};\n  const auto player_hp = 100;\n\n  std::cout << solution(boss, player_hp) << std::endl;\n\n}\n", "meta": {"hexsha": "a312c596394aefebe943b7a074e2fd63d56142b9", "size": 5999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 21 Part 2/main_v2.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 21 Part 2/main_v2.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 21 Part 2/main_v2.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7731481481, "max_line_length": 126, "alphanum_fraction": 0.6527754626, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5709397366335258}}
{"text": "#include <ros/ros.h>\n#include \"std_msgs/String.h\"\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/Pose.h>\n#include <stdlib.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/QR>\n#include <Eigen/LU>\n#include <math.h>\n#include <stdio.h>\n//#include <turtlesim/Pose.h>\n#include <Eigen/Geometry>\n#include \"gazebo_msgs/LinkStates.h\"\n// #include <LinkStates.h>\n\nusing namespace Eigen;\n\n//For geometry_msgs::Twist using:\n// \t\tdummy.linear.x\n// \t\tdummy.linear.y\n// \t\tdummy.angular.z\ngeometry_msgs::Twist robot_position;\ngeometry_msgs::Twist target_position;\n\n//rate_hz assignment\ndouble rate_hz = 30;\n\n//Assign the position of the robot (from other topic) to robot_position.\n//Assuming the topic that generate the robot position uses geometry_msgs::Twist\n//and the information is in *.linear. This might need to be modifed\nvoid getRobotPose(const gazebo_msgs::LinkStates& msg) {\n\n\t// msg.name[1]\n\trobot_position.linear.x = msg.pose[1].position.x;\n\trobot_position.linear.y = msg.pose[1].position.y;\n    robot_position.angular.z = 0;//msg.pose[1].angular.z; \n}\n\n//Assign the position of the target (from other topic) to target_position.\n//Assuming the topic that generate the robot position uses geometry_msgs::Twist\n//and the information is in *.linear. This might need to be modifed\nvoid getTargetPose(const geometry_msgs::Twist& msg) {\n\ttarget_position.linear.x = msg.linear.x;\n\ttarget_position.linear.y = msg.linear.y;\n    target_position.angular.z = msg.angular.z; \n}\n\n//Function to determine if the goal is still far.\n//Variables epsilon_x and epsilon_y used to determined if the goal has been reach\nbool isGoalFar(geometry_msgs::Twist p_start, geometry_msgs::Twist p_goal) {\n\tdouble epsilon_x, epsilon_y;\n\tepsilon_x = .2; \n\tepsilon_y = .2;\n\tdouble distance_x = abs(p_goal.linear.x - p_start.linear.x);\n\tdouble distance_y = abs(p_goal.linear.y - p_start.linear.y);\n\tif (distance_x > epsilon_x || distance_y > epsilon_y)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\n//Function to generate a Linear Constant Velocity from robot's position to the target's position\ngeometry_msgs::Twist generateConstantVelocity(double constant_speed, geometry_msgs::Twist p_start, geometry_msgs::Twist p_goal){\n\n    // Compute direction to goal\n\tVector3d p_start_vector(p_start.linear.x,p_start.linear.y,p_start.angular.z);\n\tVector3d p_goal_vector(p_goal.linear.x, p_goal.linear.y, p_goal.angular.z);\n\t// Vector3d goal_direction_vector = p_goal_vector-p_start_vector;\n\tVector3d goal_direction_vector = p_start_vector - p_goal_vector;\n\n    // Compute speed in the direction to goal\n\tVector3d velocity_vector = constant_speed * (goal_direction_vector/ goal_direction_vector.norm());\n\n\tgeometry_msgs::Twist velocity;\n\n\tvelocity.linear.x = velocity_vector.x();\n\tvelocity.linear.y = velocity_vector.y();\n\tvelocity.angular.z = velocity_vector.z();\n\n\treturn velocity;\n}\n\n// Function to keep velocity under the allowed robot limits\ngeometry_msgs::Twist boundVelocity(geometry_msgs::Twist velocity) {\n\n\tdouble max_linear_speed = 30;\n\tdouble min_linear_speed = 0;\n\tdouble max_angular_speed = M_PI*4;\n\tdouble min_angular_speed = M_PI/16;\n\n\tif (velocity.linear.x > max_linear_speed)\n\t\tvelocity.linear.x = max_linear_speed;\n\telse if (velocity.linear.x < -max_linear_speed)\n\t\tvelocity.linear.x = -max_linear_speed;\n\tif (velocity.linear.y > max_linear_speed)\n\t\tvelocity.linear.y = max_linear_speed;\n\telse if (velocity.linear.y < -max_linear_speed)\n\t\tvelocity.linear.y = -max_linear_speed;\n\tif (velocity.angular.z > max_angular_speed)\n\t\tvelocity.angular.z = max_angular_speed;\n\telse if (velocity.angular.z < -max_angular_speed)\n\t\tvelocity.angular.z = -max_angular_speed;\n\n    // Lower speed bounds\n\tif (velocity.linear.x > 0 && velocity.linear.x < min_linear_speed)\n\t\tvelocity.linear.x = min_linear_speed;\n\telse if (velocity.linear.x < 0 && velocity.linear.x > -min_linear_speed)\n\t\tvelocity.linear.x = -min_linear_speed;\n\tif (velocity.linear.y > 0 && velocity.linear.y<min_linear_speed)\n\t\tvelocity.linear.y = min_linear_speed;\n\telse if (velocity.linear.y < 0 && velocity.linear.y > -min_linear_speed)\n\t\tvelocity.linear.y = -min_linear_speed;\n\tif (velocity.angular.z >0 && velocity.angular.z < min_angular_speed)\n\t\tvelocity.angular.z = min_angular_speed;\n\telse if (velocity.angular.z < 0 && velocity.linear.z > - min_angular_speed )\n\t\tvelocity.angular.z = -min_angular_speed;\n\n}\n\n\nint main(int argc, char **argv){\n\tros::init(argc,argv,\"turtle_trajectory_node\");\n\tros::NodeHandle nh;\n\tROS_INFO_STREAM(\"turtle_trajectory_node initialized\");\n\tROS_INFO_STREAM(ros::this_node::getName());\n\t\n\t//Topic to publish velocity command, queue size equals rate_hz to keep up with the rate at which messages are generated,\n\n    //Publish to the turtle topic \"/turtle1/cmd_vel at rate_hz\"\n\tros::Publisher pub_vel_turtle = nh.advertise<geometry_msgs::Twist>(\"/target_vel_topic\", rate_hz);\n\n\t//Topics to acquire robot and target position (from the vision node) \n\tros::Subscriber sub_robot_pos = nh.subscribe(\"/gazebo/model_states\", 1, &getRobotPose); \n\tros::Subscriber sub_ball_pos = nh.subscribe(\"/target_position_topic\", 1, &getTargetPose);\n\n    //Twist variable to publish velocity (trajectories)\n\tgeometry_msgs::Twist desired_velocity;\n\tdouble tiempo = 0;\n\n    //define the max speed\n\tdouble cruise_speed = 30;\n\n    //define the rate\n\tros::Rate rate(rate_hz);\n\n\twhile (ros::ok())\n\t{\n        //ROS_INFO_STREAM use for debugging \n\t\tROS_INFO_STREAM(\"Robot Position:\"\n\t\t\t<<\" X=\"<<robot_position.linear.x\n\t\t\t<<\",Y=\"<<robot_position.linear.y\n\t\t\t<<\",W=\"<<robot_position.angular.z);\n\t\tROS_INFO_STREAM(\"Target position:\"\n\t\t\t<<\" X=\"<<target_position.linear.x\n\t\t\t<<\",Y=\"<<target_position.linear.y\n\t\t\t<<\",W=\"<<target_position.angular.z);\n\n\t\tif (isGoalFar(robot_position, target_position)) {\t\n\n\t\t\tdesired_velocity = generateConstantVelocity(cruise_speed, robot_position, target_position);\n\t\t\tdesired_velocity = boundVelocity(desired_velocity);\n\t\t} else { \n            // Goal has been reach ==> dont move\n\t\t\tdesired_velocity.linear.x = 0;\n\t\t\tdesired_velocity.linear.y = 0;\n\t\t\tdesired_velocity.angular.z = 0;\n\t\t}\n\t\t//ROS_INFO_STREAM use for debugging \n\t\tROS_INFO_STREAM(\"Desired Velocity:\"\n\t\t\t<<\"X:\"<<desired_velocity.linear.x\n\t\t\t<<\",Y:\"<<desired_velocity.linear.y\n\t\t\t<<\",W:\"<<desired_velocity.angular.z);\n\n\t\t//publish the new velocity\n\t\tpub_vel_turtle.publish(desired_velocity);\n\t\t\n\t\tros::spinOnce();\n\t\trate.sleep();\n        tiempo+=(1/rate_hz); \n    }\n    return 0;\n}\n", "meta": {"hexsha": "f8f7ccb14248c28671506106dc5f86c1f70b5698", "size": 6415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/SDI-11911/Proyecto2/src/ekbot_ctrl/robot_trajectory_node.cpp", "max_stars_repo_name": "khairulislam/phys", "max_stars_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/SDI-11911/Proyecto2/src/ekbot_ctrl/robot_trajectory_node.cpp", "max_issues_repo_name": "khairulislam/phys", "max_issues_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/SDI-11911/Proyecto2/src/ekbot_ctrl/robot_trajectory_node.cpp", "max_forks_repo_name": "khairulislam/phys", "max_forks_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8641304348, "max_line_length": 128, "alphanum_fraction": 0.7434138737, "num_tokens": 1605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5709397233962163}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"STFT.hpp\"\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 <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass GriffinLim\n{\n\npublic:\n  void process(ComplexMatrixView in, index nSamples, index nIter, index winSize,\n               index fftSize, index hopSize)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    using namespace std::complex_literals;\n    double    momentum = 0.9;\n    auto      stft = STFT(winSize, fftSize, hopSize);\n    auto      istft = ISTFT(winSize, fftSize, hopSize);\n    ArrayXd   tmp = ArrayXd::Zero(nSamples);\n    ArrayXXcd magnitude = asEigen<Array>(in).abs();\n    ArrayXXcd phase =\n        ArrayXXcd::Random(magnitude.rows(), magnitude.cols()) * 2 * 1i * pi;\n    phase = phase.exp();\n    ArrayXXcd estimate = ArrayXXcd::Zero(magnitude.rows(), magnitude.cols());\n    ArrayXXcd prev = ArrayXXcd::Zero(magnitude.rows(), magnitude.cols());\n    for (index i = 0; i < nIter; i++)\n    {\n      prev = estimate;\n      ArrayXXcd spectrogram = magnitude * phase;\n      istft.process(asFluid(spectrogram), asFluid(tmp));\n      stft.process(asFluid(tmp), asFluid(estimate));\n      phase = estimate - (momentum / (1 + momentum)) * prev;\n      phase = phase / (phase.abs() + epsilon);\n    }\n    estimate = magnitude * phase;\n    in <<= asFluid(estimate);\n  }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "8004fe99d123c25875c219001e8488ffcc43fd2e", "size": 1904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/GriffinLim.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/GriffinLim.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/GriffinLim.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.2711864407, "max_line_length": 80, "alphanum_fraction": 0.6827731092, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5709397172201758}}
{"text": "#include <ros/ros.h>\n#include <vector>\n#include <math.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <pcl_ros/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/sample_consensus/ransac.h>\n#include <pcl/sample_consensus/sac_model_plane.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/segmentation/extract_clusters.h>\n#include <boost/foreach.hpp>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <boost/thread/thread.hpp>\n#include <pcl/ModelCoefficients.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/features/moment_of_inertia_estimation.h>\n#include <pcl/kdtree/kdtree.h>\n#include <std_msgs/String.h>\n#include <sstream>\n\ntypedef pcl::PointCloud<pcl::PointXYZRGB> PointCloud;\n\nvoid callback(const PointCloud::ConstPtr& msg)\n{\n  ros::NodeHandle n;\n  ros::Publisher pub = n.advertise<std_msgs::String>(\"/kinect_data\",100);\n  ROS_INFO(\"I heard: [%d] [%d]\",msg->width, msg->height);\n  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;\n  pcl::VoxelGrid<pcl::PointXYZRGB> vg;\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr filtered (new pcl::PointCloud<pcl::PointXYZRGB>());\n  vg.setInputCloud(msg);\n  vg.setLeafSize(0.03f, 0.03f, 0.03f);\n  vg.filter(*filtered);\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);\n  std::vector<int> inl;\n  pcl::SampleConsensusModelPlane<pcl::PointXYZRGB>::Ptr model_p(new pcl::SampleConsensusModelPlane<pcl::PointXYZRGB> (filtered));\n  pcl::RandomSampleConsensus<pcl::PointXYZRGB> ransac(model_p);\n  ransac.setDistanceThreshold(0.05);\n  ransac.computeModel();\n  ransac.getInliers(inl);\n  pcl::copyPointCloud<pcl::PointXYZRGB>(*filtered, inl, *cloud);\n  pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients);\n  pcl::PointIndices::Ptr inliers (new pcl::PointIndices);\n  pcl::SACSegmentation<pcl::PointXYZRGB> seg;\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_plane (new pcl::PointCloud<pcl::PointXYZRGB> ()), cloud_f (new pcl::PointCloud<pcl::PointXYZRGB>);\n  seg.setOptimizeCoefficients(true);\n  seg.setModelType(pcl::SACMODEL_PLANE);\n  seg.setMethodType(pcl::SAC_RANSAC);\n  //seg.setMaxIterations (100);\n  seg.setDistanceThreshold(0.05);\n  int i = 0, nr_points = (int)filtered->points.size();\n  while(filtered->points.size() > 0.4*nr_points)\n  {\n    seg.setInputCloud(filtered);\n    seg.segment(*inliers, *coefficients);\n    pcl::ExtractIndices<pcl::PointXYZRGB> extract;\n    extract.setInputCloud(filtered);\n    extract.setIndices(inliers);\n    extract.setNegative(false);\n    extract.filter (*cloud_plane);\n    extract.setNegative (true);\n    extract.filter (*cloud_f);\n    *filtered = *cloud_f;    \n  }\n  // Creating the KdTree object for the search method of the extraction\n  pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB>);\n  tree->setInputCloud (filtered);\n  std::vector<pcl::PointIndices> cluster_indices;\n  pcl::EuclideanClusterExtraction<pcl::PointXYZRGB> ec;\n  ec.setClusterTolerance (0.03); // 2cm\n  ec.setMinClusterSize (50);\n  ec.setMaxClusterSize (10000);\n  ec.setSearchMethod (tree);\n  ec.setInputCloud (filtered);\n  ec.extract (cluster_indices);  \n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_cluster (new pcl::PointCloud<pcl::PointXYZRGB>);\n  int j = 0;\n  std::vector<std::vector<float> > moi, xcor;\n  for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it)\n  {\n    j++;\n    pcl::PointCloud<pcl::PointXYZRGB>::Ptr clusters (new pcl::PointCloud<pcl::PointXYZRGB>);\n    for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); ++pit)\n    {\n      clusters->points.push_back (filtered->points[*pit]); //*      \n      cloud_cluster->points.push_back (filtered->points[*pit]); //*\n    }\n    pcl::MomentOfInertiaEstimation <pcl::PointXYZRGB> feature_extractor;\n    feature_extractor.setInputCloud (clusters);\n    feature_extractor.compute ();\n    std::vector <float> moment_of_inertia;\n    std::vector <float> eccentricity;\n    pcl::PointXYZRGB min_point_AABB;\n    pcl::PointXYZRGB max_point_AABB;\n    pcl::PointXYZRGB min_point_OBB;\n    pcl::PointXYZRGB max_point_OBB;\n    pcl::PointXYZRGB position_OBB;\n    Eigen::Matrix3f rotational_matrix_OBB;\n    float major_value, middle_value, minor_value;\n    Eigen::Vector3f major_vector, middle_vector, minor_vector;\n    Eigen::Vector3f mass_center;\n    feature_extractor.getMomentOfInertia (moment_of_inertia);\n    feature_extractor.getEccentricity (eccentricity);\n    feature_extractor.getAABB (min_point_AABB, max_point_AABB);\n    feature_extractor.getOBB (min_point_OBB, max_point_OBB, position_OBB, rotational_matrix_OBB);\n    feature_extractor.getEigenValues (major_value, middle_value, minor_value);\n    feature_extractor.getEigenVectors (major_vector, middle_vector, minor_vector);\n    feature_extractor.getMassCenter (mass_center);  \n    std::vector<float> row1;\n    for(int k=0;k<2;k++)\n      row1.push_back(mass_center[k]);\n    moi.push_back(row1);\n    std::vector<float> row2;\n    row2.push_back(min_point_AABB.x);\n    row2.push_back(max_point_AABB.x);\n    row2.push_back(min_point_AABB.z);\n    row2.push_back(max_point_AABB.z);\n    row2.push_back(min_point_AABB.y);\n    row2.push_back(max_point_AABB.y);\n    xcor.push_back(row2);\n  }\n  std::cout<<endl<<j<<endl;\n  std::stringstream ss;\n  std_msgs::String kin_val;\n  for(int i=0; i<j; i++)\n      {\n        if(xcor[i][2]<2.0 && xcor[i][5]-xcor[i][4]>0.15)\n        {\n          if(moi[i][0]>=0)\n\t  {\n            std::cout<<\"left\\n\";\n\t    ss << \"left\";\n            kin_val.data = ss.str();\n\t    goto label;\n\t  }\n          else \n\t  {\n            std::cout<<\"right\\n\";\n\t    ss << \"right\";\n            kin_val.data = ss.str();\n\t    goto label;\n\t  }\n        }\n       }\n\tstd::cout<<\"straight\\n\";\n\tss << \"straight\";\n  \tkin_val.data = ss.str();\n      label:\n\tpub.publish(kin_val);\n}\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"obs_av\");\n  ros::NodeHandle n;\n  ros::Subscriber sub = n.subscribe(\"/camera/depth/color/points\", 1, callback);\n  ros::spin();\n  return 0;\n}\n", "meta": {"hexsha": "b33d751dcffd6ec251126f88f6c562559270988f", "size": 6226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Autonomous/auto_trav/src/obs_av.cpp", "max_stars_repo_name": "leander-dsouza/URC-2019", "max_stars_repo_head_hexsha": "6773e6b66dfb840bdbb4463441e8a855b42b1123", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-10T11:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T07:00:40.000Z", "max_issues_repo_path": "Autonomous/auto_trav/src/obs_av.cpp", "max_issues_repo_name": "leander-dsouza/URC-2019", "max_issues_repo_head_hexsha": "6773e6b66dfb840bdbb4463441e8a855b42b1123", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Autonomous/auto_trav/src/obs_av.cpp", "max_forks_repo_name": "leander-dsouza/URC-2019", "max_forks_repo_head_hexsha": "6773e6b66dfb840bdbb4463441e8a855b42b1123", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-13T14:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T18:05:05.000Z", "avg_line_length": 37.9634146341, "max_line_length": 145, "alphanum_fraction": 0.7062319306, "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5709397101640459}}
{"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//\u56fa\u5b9a\u7f51\u683cx\u5750\u6807\u6700\u5c0f\u70b9\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": "#pragma once\n\n#include <Eigen/Core>\n#include <autodiff/forward/eigen.hpp>\n\nnamespace samson::types\n{\n    using autodiff::Vector3dual;\n    using Vector6dual = Eigen::Matrix<dual, 6, 1>;\n    using Matrix6dual = Eigen::Matrix<dual, 6, 6>;\n\n} // namespace samson::types\n", "meta": {"hexsha": "4c0be68e8e19e3146f1d9ca0e9d4a6065486929a", "size": 266, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/samson/types.hpp", "max_stars_repo_name": "tingelst/samson", "max_stars_repo_head_hexsha": "a34717d40d61868cb87560b94f422859d59d8bde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/samson/types.hpp", "max_issues_repo_name": "tingelst/samson", "max_issues_repo_head_hexsha": "a34717d40d61868cb87560b94f422859d59d8bde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/samson/types.hpp", "max_forks_repo_name": "tingelst/samson", "max_forks_repo_head_hexsha": "a34717d40d61868cb87560b94f422859d59d8bde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4615384615, "max_line_length": 50, "alphanum_fraction": 0.6992481203, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5707679597080976}}
{"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 <string>\n#include \"Encryptor.h\"\n#include \"RSA.h\"\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\nusing namespace Crypto;\nusing std::string;\n\nEncryptor::Encryptor(const PublicKey* key) : text(\"\"), public_key(key)\n{};\n\nCryptoString Encryptor::encryptString(string &input)\n{\n  CryptoString str;\n\n  int256_t tmp;\n  int it;\n  for (it = 0; it < input.length(); it++)\n  {\n    tmp = powm((int256_t)input.at(it), public_key->r, public_key->m);\n    str.push_back(tmp);\n  }\n\n  return str;\n}\n\nCryptoChar Encryptor::encryptChar(char c) const\n{\n  CryptoChar res = powm((CryptoChar)c, public_key->r, public_key->m);\n  return res.convert_to<int>();\n}", "meta": {"hexsha": "2e1d375b548e90068cc9f0ff67458ab9a306ce5e", "size": 679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Encryptor.cpp", "max_stars_repo_name": "weniseb/RSA_CPP", "max_stars_repo_head_hexsha": "ea819e30e133205e780df94c17dc5f9236ec9739", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T07:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:03:49.000Z", "max_issues_repo_path": "src/Encryptor.cpp", "max_issues_repo_name": "weniseb/RSA_CPP", "max_issues_repo_head_hexsha": "ea819e30e133205e780df94c17dc5f9236ec9739", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-01-10T13:03:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-22T19:12:02.000Z", "max_forks_repo_path": "src/Encryptor.cpp", "max_forks_repo_name": "weniseb/RSA_CPP", "max_forks_repo_head_hexsha": "ea819e30e133205e780df94c17dc5f9236ec9739", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-25T20:57:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T08:42:35.000Z", "avg_line_length": 21.21875, "max_line_length": 70, "alphanum_fraction": 0.6995581738, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5706827711807746}}
{"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": "#include <gtest/gtest.h>\n#include <fstream>\n#include <iostream>\n#include <cmath>\n#include <Eigen/Dense>\n\n// testing following API\n#include \"estimation/ParticleFilterSIR.h\"\n#include \"probability/pdfs.h\"\n#include \"probability/sampling.h\"\n\nusing namespace std;\nusing namespace estimation;\nusing namespace probability;\n\nnamespace logTest\n{\n  // -----------------------------------------\n  // logging for nice pictures\n  // -----------------------------------------\n  void f_log(VectorXd& x, const VectorXd& u)\n  {\n    x[0] = x[0];\n  }\n  void h_log(VectorXd& z, const VectorXd& x)\n  {\n    z[0] = x[0];\n  }\n\n  TEST(LogTest, logEstimationOfConstantNoisySignal)\n  {\n    // example 1: constant signal, but gaussian noisy with mean 0,\n    // variance 1\n\n    // create and open log file(s): signal, particles\n    ofstream logSignal;\n    logSignal.open(\"logEstimationOfConstantNoisySignal_signal.dat\");\n    ofstream logParticles;\n    logParticles.open(\"logEstimationOfConstantNoisySignal_particles.dat\");\n    ofstream logWeights;\n    logWeights.open(\"logEstimationOfConstantNoisySignal_weights.dat\");\n    ofstream logNeff;\n    logNeff.open(\"logEstimationOfConstantNoisySignal_Neff.dat\");\n    ofstream logSignalEstimated;\n    logSignalEstimated.open(\"logEstimationOfConstantNoisySignal_signalEstimated.dat\");\n\n    // init particle filter\n    ParticleFilterSIR pf(1000);\n\n    pf.setStateTransitionModel(f_log);\n    pf.setObservationModel(h_log);\n    MatrixXd Q(1,1); Q << 0.01;\n    pf.setProcessNoiseCovariance(Q);\n    MatrixXd R(1,1); R << 1;\n    pf.setMeasurementNoiseCovariance(R);\n    VectorXd x0(1); x0 << 1;\n    pf.setInitialState(x0);\n\n    pf.validate();\n    \n    // measurements\n    VectorXd mean = VectorXd::Ones(1);\t\t// mean = 1\n    MatrixXd var = MatrixXd::Identity(1,1);\t// variance = 1\n\n    Input signal(InputValue(1));\n    Output signalEstimated;\n\n    // start filtering and log\n    for (int i = 0; i < 40; i++)\n    {\n      // create new measurement\n      double sample = sampleNormalDistribution(mean,var)[0];\n      signal[0].setValue(sample);\n\n      // estimate\n      signalEstimated = pf.estimate(signal);\n\n      // log\n      logSignal << (i+1) << \" \" \n\t\t<< sample << endl;\n      pf.log(logParticles, ParticleFilterSIR::PARTICLES, 0);\n      pf.log(logWeights, ParticleFilterSIR::WEIGHTS, 0);\n      logNeff << (i+1) << \" \";\n      pf.log(logNeff, ParticleFilterSIR::NEFF, 0);\n      logSignalEstimated << (i+1) << \" \"\n\t\t\t << signalEstimated[0].getValue() << \" \"\n\t\t\t << sqrt(signalEstimated[0].getVariance())\n\t\t\t << endl;\n    }\n\n    logSignal.close();\n    logParticles.close();\n    logWeights.close();\n    logNeff.close();\n    logSignalEstimated.close();\n  }\n\n  TEST(LogTest, logSampleNormalDistribution)\n  {\n    int N = 10000;\n    VectorXd mean = VectorXd::Zero(1);\n    MatrixXd cov = MatrixXd::Identity(1,1);\n\n    ofstream logFile;\n    logFile.open(\"logSampleNormalDistribution.dat\");\n    for (int i = 0; i < N; i++)\n      logFile << sampleNormalDistribution(mean, cov) \n    \t      << endl;\n\n    logFile.close();\n  }\n\n  TEST(LogTest, logSampleUniformDistribution)\n  {\n    int N = 10000;\n    VectorXd a = VectorXd::Zero(1);\n    VectorXd b = VectorXd::Ones(1);\n\n    ofstream logFile;\n    logFile.open(\"logSampleUniformDistribution.dat\");\n    for (int i = 0; i < N; i++)\n      logFile << sampleUniformDistribution(a, b) \n    \t      << endl;\n\n    logFile.close();\n  }\n\n  TEST(LogTest, logPdfNormalDistribution)\n  {\n    VectorXd x = VectorXd::Zero(1);\n    VectorXd mean = VectorXd::Zero(1);\n    MatrixXd cov = MatrixXd::Identity(1,1);\n\n    ofstream logFile;\n    logFile.open(\"logPdfNormalDistribution.dat\");\n    for (float i = -2.0; i < 2.0; i=i+0.1)\n    {\n      x[0] = i;\n      logFile << i << \" \"\n\t      << pdfNormalDistribution(x, mean, cov) \n    \t      << endl;\n    }\n    logFile.close();\n  }\n}\n", "meta": {"hexsha": "fb848fad5c47d6b7c86245ef6abcee9343778481", "size": 3795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sf_estimation/tests/utest_log.cpp", "max_stars_repo_name": "tuw-cpsg/sf-pkg", "max_stars_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T09:47:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T16:01:11.000Z", "max_issues_repo_path": "sf_estimation/tests/utest_log.cpp", "max_issues_repo_name": "ros-agriculture/sf-pkg", "max_issues_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T04:59:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-13T14:39:24.000Z", "max_forks_repo_path": "sf_estimation/tests/utest_log.cpp", "max_forks_repo_name": "tuw-cpsg/sf-pkg", "max_forks_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-17T21:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T17:00:28.000Z", "avg_line_length": 25.9931506849, "max_line_length": 86, "alphanum_fraction": 0.6281949934, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5706115918132443}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"util.h\"\n#include \"basic_bpnn.h\"\n\nusing Eigen::MatrixXd;\n\nint main() {\n    using namespace std;\n\n\tcout.sync_with_stdio(false);\n\n\t/* inputs matrix: [n * m], m is the pixels number of one image, n is the number of examples.\n\t * labels matrix: [m * 1], m is the number of labels.\n\t */\n    auto train_inputs = util::read_mnist_matrix(\"../../../data/mnist/train-images.idx3-ubyte\", true);\n    auto train_labels = util::read_mnist_matrix(\"../../../data/mnist/train-labels.idx1-ubyte\", false);\n\tauto test_inputs = util::read_mnist_matrix(\"../../../data/mnist/t10k-images.idx3-ubyte\", true);\n\tauto test_labels = util::read_mnist_matrix(\"../../../data/mnist/t10k-labels.idx1-ubyte\", false);\n\n    CppMLNN bpnn;\n    bpnn.set_hidden_layers(vector<size_t> ({256}));\n    bpnn.set_output_size(10);\n    bpnn.set_learn_rate(1);\n    bpnn.set_max_epoch(5);\n\tbpnn.set_minibatch_size(256);\n    bpnn.run_train(train_inputs, train_labels);\n\tbpnn.run_test(test_inputs, test_labels);\n    return 0;\n}", "meta": {"hexsha": "5c38880b16253602379e32eb2b74caaf19f090a2", "size": 1026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cppcnn/cppmlnn/run_mnist.cpp", "max_stars_repo_name": "jin-qin/cppcnn", "max_stars_repo_head_hexsha": "96c58a2d8a7f2bafac7ea1d02b76fa67ae15159b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-12-20T03:10:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T23:53:31.000Z", "max_issues_repo_path": "src/cppcnn/cppmlnn/run_mnist.cpp", "max_issues_repo_name": "jin-qin/cppcnn", "max_issues_repo_head_hexsha": "96c58a2d8a7f2bafac7ea1d02b76fa67ae15159b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cppcnn/cppmlnn/run_mnist.cpp", "max_forks_repo_name": "jin-qin/cppcnn", "max_forks_repo_head_hexsha": "96c58a2d8a7f2bafac7ea1d02b76fa67ae15159b", "max_forks_repo_licenses": ["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.2, "max_line_length": 102, "alphanum_fraction": 0.693957115, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5705787815454877}}
{"text": "\n#include \"GLKinectFrame.h\"\n#include \"KinectFrame.h\"\n#include <iostream>\n#include <QVector2D>\n#include <QVector3D>\n\n#include <Eigen/Dense>\n#include \"Projection.h\"\n#include \"KinectFrame.h\"\n\n\nGLKinectFrame::GLKinectFrame()\n{\n}\n\n\nGLKinectFrame::~GLKinectFrame()\n{\n}\n\nGLuint GLKinectFrame::vertexBufferId() const\n{\n\treturn vertexBuf.bufferId();\n}\n\n\nvoid GLKinectFrame::initGL()\n{\n\tinitializeOpenGLFunctions();\n\n\t// Generate VBOs\n\tvertexBuf.create();\n\tcolorBuf.create();\n\tnormalBuf.create();\n\n\t//KinectFrame frame;\n\t//QKinectIO::loadFrame(\"../../data/room.knt\", frame);\n\t//setFrame(&frame);\n}\n\n\nvoid GLKinectFrame::cleanupGL()\n{\n\tvertexBuf.destroy();\n\tcolorBuf.destroy();\n\tnormalBuf.destroy();\n}\n\n\n\nvoid GLKinectFrame::setFrame(KinectFrame* frame)\n{\n\ttry\n\t{\n\t\tconst int color_map_width = 1920;\n\t\tconst int color_map_height = 1080;\n\t\tconst int depth_map_width = 512;\n\t\tconst int depth_map_height = 424;\n\t\tconst float fovy = 70.0f;\n\t\tconst float aspect_ratio = static_cast<float>(depth_map_width) / static_cast<float>(depth_map_height);\n\t\tconst float near_plane = 0.1f;\n\t\tconst float far_plane = 10240.0f;\n\n\t\tstd::vector<Eigen::Vector3f> vertices;\n\t\tstd::vector<Eigen::Vector3f> normals;\n\t\tstd::vector<Eigen::Vector3f> colors;\n\n\t\tconst float depth_to_color_width = color_map_width / depth_map_width;\n\t\tconst float depth_to_color_height = color_map_height / depth_map_height;\n\n\t\tfor (int x = 1; x < depth_map_width - 1; ++x)\n\t\t{\n\t\t\tfor (int y = 1; y < depth_map_height - 1; ++y)\n\t\t\t{\n\t\t\t\tconst float depth = static_cast<float>(frame->depth[y * depth_map_width + x]) / 100.f;\n\t\t\t\tconst Eigen::Vector3f vert_uv = window_coord_to_3d(Eigen::Vector2f(x, y), depth, fovy, aspect_ratio, near_plane, far_plane, depth_map_width, depth_map_height);\n\t\t\t\tconst Eigen::Vector3f vert_u1v = window_coord_to_3d(Eigen::Vector2f(x + 1, y), depth, fovy, aspect_ratio, near_plane, far_plane, depth_map_width, depth_map_height);\n\t\t\t\tconst Eigen::Vector3f vert_uv1 = window_coord_to_3d(Eigen::Vector2f(x, y + 1), depth, fovy, aspect_ratio, near_plane, far_plane, depth_map_width, depth_map_height);\n\n\t\t\t\tfloat x_color = x * depth_to_color_width;\n\t\t\t\tfloat y_color = y * depth_to_color_height;\n\n\t\t\t\tif (!vert_uv.isZero() && !vert_u1v.isZero() && !vert_uv1.isZero())\n\t\t\t\t{\n\t\t\t\t\tconst Eigen::Vector3f n1 = vert_u1v - vert_uv;\n\t\t\t\t\tconst Eigen::Vector3f n2 = vert_uv1 - vert_uv;\n\t\t\t\t\tconst Eigen::Vector3f n = n1.cross(n2).normalized();\n\n\t\t\t\t\tvertices.push_back(vert_uv);\n\t\t\t\t\tnormals.push_back(n);\n\n\t\t\t\t\tconst uchar r = static_cast<uchar>(frame->color[4 * y_color * color_map_width + x_color + 0]);\n\t\t\t\t\tconst uchar g = static_cast<uchar>(frame->color[4 * y_color * color_map_width + x_color + 1]);\n\t\t\t\t\tconst uchar b = static_cast<uchar>(frame->color[4 * y_color * color_map_width + x_color + 2]);\n\n\t\t\t\t\t//colors.push_back((n * 0.5f + Eigen::Vector3f(0.5, 0.5, 0.5)) * 255.0f);\n\t\t\t\t\t//colors.push_back(Eigen::Vector3f(0, 1, 0));\n\n\t\t\t\t\tcolors.push_back(Eigen::Vector3f(static_cast<float>(r) / 255.f, static_cast<float>(g) / 255.f, static_cast<float>(b) / 255.f));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvertexBuf.bind();\n\t\tvertexBuf.allocate(&vertices[0][0], vertices.size() * sizeof(Eigen::Vector3f));\n\n\t\tcolorBuf.bind();\n\t\tcolorBuf.allocate(&colors[0][0], colors.size() * sizeof(Eigen::Vector3f));\n\n\t\tnormalBuf.bind();\n\t\tnormalBuf.allocate(&normals[0][0], normals.size() * sizeof(Eigen::Vector3f));\n\t}\n\tcatch (const std::exception& ex)\n\t{\n\t\tstd::cerr << \"Error: \" << ex.what() << std::endl;\n\t}\n}\n\n\n\n\nvoid GLKinectFrame::render(QOpenGLShaderProgram *program)\n{\n    vertexBuf.bind();\n    int vertexLocation = program->attributeLocation(\"in_position\");\n    program->enableAttributeArray(vertexLocation);\n\tprogram->setAttributeBuffer(vertexLocation, GL_FLOAT, 0, 3, sizeof(Eigen::Vector3f));\n\n\tcolorBuf.bind();\n\tint colorLocation = program->attributeLocation(\"in_color\");\n\tprogram->enableAttributeArray(colorLocation);\n\tprogram->setAttributeBuffer(colorLocation, GL_FLOAT, 0, 3, sizeof(Eigen::Vector3f));\n\n\tnormalBuf.bind();\n\tint normalLocation = program->attributeLocation(\"in_normal\");\n\tprogram->enableAttributeArray(normalLocation);\n\tprogram->setAttributeBuffer(normalLocation, GL_FLOAT, 0, 3, sizeof(Eigen::Vector3f));\n \n    // Draw geometry \n\tglDrawArrays(GL_POINTS, 0, vertexBuf.size() / sizeof(Eigen::Vector3f));\n}\n\n", "meta": {"hexsha": "7b178b5f23d3a000248f49cd245fb0fbfb5c981f", "size": 4267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GLKinectFrame.cpp", "max_stars_repo_name": "diegomazala/QtKinect", "max_stars_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-08-04T14:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-27T13:46:13.000Z", "max_issues_repo_path": "src/GLKinectFrame.cpp", "max_issues_repo_name": "diegomazala/QtKinect", "max_issues_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GLKinectFrame.cpp", "max_forks_repo_name": "diegomazala/QtKinect", "max_forks_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-12-08T06:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T10:29:17.000Z", "avg_line_length": 29.6319444444, "max_line_length": 168, "alphanum_fraction": 0.7089289899, "num_tokens": 1247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.5705693928380566}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nEigen::Matrix3d getRotMatrix(const Eigen::Vector3d eulers) {\n    Eigen::AngleAxisd Rx(eulers(0), Eigen::Vector3d::UnitX());\n    Eigen::AngleAxisd Ry(eulers(1), Eigen::Vector3d::UnitY());\n    Eigen::AngleAxisd Rz(eulers(2), Eigen::Vector3d::UnitZ());\n    return Rx.toRotationMatrix() * Ry.toRotationMatrix() * Rz.toRotationMatrix();\n}\n\nint main() {\n    std::cout << getRotMatrix(Eigen::Vector3d(M_PI / 4, M_PI / 2, 0)) << std::endl;\n    printf(\"%lf\\n\", atan2(0.0, 0.0));\n}", "meta": {"hexsha": "ee942b9273f64afa70d567e80248f7d570516ec2", "size": 515, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/axis6/apps/testGetRot.cc", "max_stars_repo_name": "Enigmatisms/Axis6", "max_stars_repo_head_hexsha": "049fc674355be5a01a4fbafca90808255df82d57", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-10-30T13:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-30T14:16:44.000Z", "max_issues_repo_path": "src/axis6/apps/testGetRot.cc", "max_issues_repo_name": "Enigmatisms/Axis6", "max_issues_repo_head_hexsha": "049fc674355be5a01a4fbafca90808255df82d57", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/axis6/apps/testGetRot.cc", "max_forks_repo_name": "Enigmatisms/Axis6", "max_forks_repo_head_hexsha": "049fc674355be5a01a4fbafca90808255df82d57", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-30T14:17:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T14:17:03.000Z", "avg_line_length": 36.7857142857, "max_line_length": 83, "alphanum_fraction": 0.6640776699, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5705693834443682}}
{"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": "//==============================================================================\n//         Copyright 2009 - 2013 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2014 MetaScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_REFINE_REC_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_REFINE_REC_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/refine_rec.hpp>\n#include <boost/simd/include/functions/simd/fnms.hpp>\n#include <boost/simd/include/functions/simd/fma.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( refine_rec_, tag::cpu_\n                                    , (A0)\n                                    , (generic_< floating_<A0> >)\n                                      (generic_< floating_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0,A0 const& a1) const\n    {\n      // Newton-Raphson: 1/X ~= x*(1-a0*x) + x\n      return fma(fsm(One<A0>(), a0, a1), a1, a1);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "b4086e2dcd79096da7395acfbbcd97a5d85f1691", "size": 1443, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/refine_rec.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/refine_rec.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/refine_rec.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.0, "max_line_length": 80, "alphanum_fraction": 0.5412335412, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5705460504058129}}
{"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": "/*\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 00_points 00_points.cpp\n*/\n\n\n#include<iostream>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\nusing namespace boost::geometry;\n\n// declare some points. There are type templates in the library.\n\ntypedef model::d2::point_xy<double> point_a;\n\n// but what if we have old c-style libraries around? The array case:\n\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian) //<-- this tags the type with a coordinate system! nice.\n\nint main(int argc, char **argv)\n{\n\n    point_a p(42,11), q(43,12);\n    std::cout << \"The distance of P and Q is: \" << distance(p,q) << std::endl;\n\n    int p2[2]={42,11}, q2[2]={43,12};\n    std::cout << \"The distance of P2 and Q2 is: \" << distance(p2,q2) << std::endl;\n\n    // but what if we use a spheroid Earth model?\n    \n    \n    return 0;\n}\n", "meta": {"hexsha": "cb5303226b3bcfbf97e759940418f425c4c96028", "size": 1118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "02_geo/00_points.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/00_points.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/00_points.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": 26.619047619, "max_line_length": 106, "alphanum_fraction": 0.6887298748, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5704481153094335}}
{"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": "///////////////////////////////////////////////////////////////////////////////\n// random::example::poisson_speed.cpp     \t\t\t\t\t\t     \t\t //\n//                                                                           //\n//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#include <vector>\n#include <algorithm>\n#include <iterator>\n\n#include <boost/timer.hpp>\n\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/random/poisson_ext/devroye/detail/step4/standard.hpp>\n#include <boost/random/poisson_ext/devroye/detail/step4/squeeze.hpp>\n#include <boost/random/poisson_ext/devroye/sampler/meta_int_mean.hpp>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n\ntemplate<typename Int>\nvoid example_poisson_speed(\n\tstd::ostream& os,\n    std::size_t n, \t\t\t//sample size\n    int n_loops,\n    int mean,\t\t\n    int factor \t\t\t// mean *= factor at each loop\n){\n\tos << \"poisson_speed{\" << std::endl;\n\n\tnamespace devroye = boost::random::poisson::devroye;\n\ttypedef boost::timer timer_;\n    typedef Int \tint_;\n    typedef double \tval_;\n    timer_ timer;\n\ttypedef boost::mt19937 urng_;\n    typedef boost::poisson_distribution<int_> random1_;\n    typedef devroye::tag::standard tag3_;\n    typedef devroye::tag::squeeze tag4_;\n    typedef typename devroye::sampler::meta_int_mean<tag3_,int_>::type random3_;\n    typedef typename devroye::sampler::meta_int_mean<tag4_,int_>::type random4_;\n    \n    urng_ urng;\n\turng_ urng1 = urng;\n    urng_ urng3 = urng;\n    urng_ urng4 = urng;\n\n\ttypedef boost::variate_generator<urng_&,random1_> vg1_;\n\ttypedef boost::variate_generator<urng_&,random3_> vg3_;\n\ttypedef boost::variate_generator<urng_&,random4_> vg4_;\n\n\tval_ t1, t3, t4 = 0;\n\tos << \"n = \" << n << std::endl;\n\tos << \"(mean,{time[j] : j = default,devroye-st,devroye-sq})\" << std::endl;\n\tfor(int_ i1 = 0; i1<n_loops; ++i1){\n\t\tvg1_ vg1(urng1,random1_(mean));\n\t\tvg3_ vg3(urng3,random3_(mean));\n\t\tvg4_ vg4(urng4,random4_(mean));\n\n        for(int_ i2 = 0; i2<n; i2++){\n            timer.restart(); vg1();\tt1 += timer.elapsed();\n            timer.restart(); vg3();\tt3 += timer.elapsed();\n            timer.restart(); vg4();\tt4 += timer.elapsed();\n        }\n        mean *= factor;\n        os \n        \t<< '(' \n            << mean\n            << ',' \n            << t1 \n            << ',' \n            << t3 \n            << ',' \n            << t4\n            << ')' \n            << std::endl;\n    }\n\n\tos << \"}\" << std::endl;\n\n}\n\n", "meta": {"hexsha": "6609a8b2165516465a07e65aee6c675c86f7aa80", "size": 2721, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/libs/random/example/poisson_speed.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "random/libs/random/example/poisson_speed.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "random/libs/random/example/poisson_speed.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3928571429, "max_line_length": 80, "alphanum_fraction": 0.5575156193, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.570329423821939}}
{"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": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#include <type_traits>\n#include <algorithm>\n#define BOOST_UBLAS_NO_ELEMENT_PROXIES\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/hermitian.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/banded.hpp>\n#include <boost/numeric/bindings/ublas/hermitian.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef std::complex<double> complex;\n    typedef ublas::vector<complex> vector;\n    typedef ublas::banded_matrix<complex, ublas::column_major> matrix;\n    typedef typename std::make_signed<vector::size_type>::type size_type;\n    rand_normal<complex>::reset();\n    size_type n=8;\n    matrix A(n, n, 2, 2);\n    matrix A_u(n, n, 0, 2), A_l(n, n, 2, 0);\n    for (size_type j=0; j<n; ++j) {\n      A(j, j)=rand_normal<complex>::get().real();\n      A_u(j, j)=A(j, j);\n      A_l(j, j)=A(j, j);\n      for (size_type i=std::max(size_type(0), j-2); i<j; ++i) {\n\tA(i, j)=rand_normal<complex>::get();\n\tA(j, i)=std::conj(A(i, j));\n\tA_u(i, j)=A(i, j);\n\tA_l(j, i)=A(j, i);\n      }\n    }\n    ublas::hermitian_adaptor<matrix, ublas::upper> B_u(A_u);\n    ublas::hermitian_adaptor<matrix, ublas::lower> B_l(A_l);\n    vector x(n);\n    for (size_type i=0; i<n; ++i)\n      x(i)=rand_normal<complex>::get();\n    vector y(n);\n    for (size_type i=0; i<n; ++i)\n      y(i)=rand_normal<complex>::get();\n    complex alpha(rand_normal<complex>::get());\n    complex beta(rand_normal<complex>::get());\n    vector y1(alpha*ublas::prod(A, x)+beta*y);\n    vector y2(y);\n    blas::hbmv(alpha, B_l, x, beta, y2);\n    vector y3(y);\n    blas::hbmv(alpha, B_u, x, beta, y3);\n    std::cout << \"testing boost::ublas containers\\n\"\n    \t      << \"using ublas       : \" << print_vec(y1) << '\\n'\n\t      << \"using blas (lower): \" << print_vec(y2) << '\\n'\n\t      << \"using blas (upper): \" << print_vec(y3) << '\\n'\n    \t      << '\\n';\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "8806ef03851a203179be693dc3e2c2d809333879", "size": 2166, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/hbmv.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/hbmv.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/hbmv.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.84375, "max_line_length": 73, "alphanum_fraction": 0.6269621422, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5703294129109329}}
{"text": "#include \"stdafx.h\"\r\n#include <chrono>\r\n#include <iostream>\r\n\r\n#include <fmt/format.h>\r\n\r\n#include \"timer.h\"\r\n#include \"judge.h\"\r\n\r\n#define USE_BOOST_GEOMETRY\r\n#if defined(USE_BOOST_GEOMETRY)\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\nnamespace bg = boost::geometry;\r\nusing BoostPoint = bg::model::d2::point_xy<double>;\r\nusing BoostPolygon = bg::model::polygon<BoostPoint>;\r\nusing BoostLinestring = bg::model::linestring<BoostPoint>;\r\n\r\ntemplate <typename T>\r\nBoostPoint ToBoostPoint(const T& point) {\r\n  const auto [x, y] = point;\r\n  return BoostPoint(x, y);\r\n}\r\n\r\ntemplate <typename T>\r\nBoostPolygon ToBoostPolygon(const std::vector<T>& points) {\r\n  BoostPolygon polygon;\r\n  for (std::size_t i = 0; i <= points.size(); ++i) {\r\n    polygon.outer().push_back(ToBoostPoint(points[i % points.size()]));\r\n  }\r\n  if (bg::area(polygon) < 0.0) {\r\n    bg::reverse(polygon);\r\n  }\r\n  return polygon;\r\n}\r\n\r\ntemplate <typename T, typename U>\r\ndouble SquaredDistance(const T& vertex0, const U& vertex1) {\r\n  const auto [x0, y0] = vertex0;\r\n  const auto [x1, y1] = vertex1;\r\n  return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);\r\n}\r\n\r\ntemplate <typename T>\r\ndouble SquaredEdgeLength(const T& vertices, const Edge& edge) {\r\n  const auto [a, b] = edge;\r\n  return SquaredDistance(vertices[a], vertices[b]);\r\n}\r\n\r\nvoid test_bg() {\r\n    typedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;\r\n\r\n    polygon blue;\r\n    boost::geometry::read_wkt(\r\n        \"POLYGON((0 0, 10 0, 10 5, 5 5, 5 10, 0 10))\", blue);\r\n\r\n    if (bg::area(blue) < 0.0) {\r\n      bg::reverse(blue);\r\n    }\r\n\r\n    BoostLinestring ls({ToBoostPoint(Point(5.0, 8.0)), ToBoostPoint(Point(8.0, 5.0))});\r\n\r\n    LOG(INFO) << \"linestring coverd by blue?:\" << boost::geometry::covered_by(ls, blue);\r\n\r\n}\r\n#endif\r\n\r\nSJudgeResult judge(const SProblem& problem, const SSolution& solution) {\r\n  SJudgeResult res;\r\n  for (auto& b : solution.bonuses) {\n    if (b.type == SBonus::Type::GLOBALIST) {\n      res.is_globalist_mode = true;\n    }\n    if (b.type == SBonus::Type::WALLHACK) {\n      res.is_wallhack_mode = true;\n    }\n    if (b.type == SBonus::Type::SUPERFLEX) {\n      res.is_superflex_mode = true;\n    }\n  }\n\r\n  // all figure points are inside the hole.\n  for (size_t ivert = 0; ivert < solution.vertices.size(); ++ivert) {\n    // (c) Every point located on any line segment of the figure in the assumed pose must either lay inside the hole, or on its boundary \n    if (contains(problem.hole_polygon, solution.vertices[ivert]) == EContains::EOUT) {\n      res.out_of_hole_vertices.push_back(ivert);\n    }\n  }\n\n  if (res.is_wallhack_mode) {\n    if (res.out_of_hole_vertices.size() == 1) {\n      res.wallhacking_index = res.out_of_hole_vertices[0];\n    }\n  }\n\n  // figure does not intersect with edges of the hole.\r\n#if defined(USE_BOOST_GEOMETRY)\r\n  //test_bg();\r\n\r\n  auto hole_polygon_ = ToBoostPolygon(problem.hole_polygon);\r\n  for (size_t iedge = 0; iedge < problem.edges.size(); ++iedge) {\r\n    const auto [a, b] = problem.edges[iedge];\r\n    BoostLinestring linestring{ToBoostPoint(solution.vertices[a]), ToBoostPoint(solution.vertices[b])};\r\n    if (!bg::covered_by(linestring, hole_polygon_)) {\r\n      const bool wallhacking_edge = res.wallhacking_index.value_or(-1) == a || res.wallhacking_index.value_or(-1) == b;\n      if (!wallhacking_edge) {\n        res.out_of_hole_edges_except_wallhack.push_back(iedge);\n      }\n      res.out_of_hole_edges.push_back(iedge);\r\n    }\r\n  }\r\n#else\r\n\r\n  std::vector<Point2d> hole_polygon_d;\r\n  for (auto& p : problem.hole_polygon) {\r\n    hole_polygon_d.emplace_back(p.first, p.second);\r\n  }\r\n\r\n  for (size_t iedge = 0; iedge < problem.edges.size(); ++iedge) {\r\n    const auto& edge = problem.edges[iedge];\r\n    auto moved_i = solution.vertices[edge.first];\r\n    auto moved_j = solution.vertices[edge.second];\r\n    const Line figure_segment = {moved_i, moved_j};\r\n\r\n    bool intersects = false;\r\n    for (size_t ihole = 0; ihole < problem.hole_polygon.size(); ++ihole) {\r\n      auto h0 = problem.hole_polygon[ihole];\r\n      auto h1 = problem.hole_polygon[(ihole + 1) % problem.hole_polygon.size()];\r\n      const Line hole_segment = {h0, h1};\r\n      if (intersectSS_strict(figure_segment, hole_segment)) {\r\n        intersects = true;\r\n        break;\r\n      }\r\n    }\r\n    if (!intersects\r\n      && contains(problem.hole_polygon, moved_i) == EContains::EON\r\n      && contains(problem.hole_polygon, moved_j) == EContains::EON\r\n      ) {\r\n      bool on_edge = false;\r\n      for (size_t ihole = 0; ihole < problem.hole_polygon.size(); ++ihole) {\r\n        auto h0 = problem.hole_polygon[ihole];\r\n        auto h1 = problem.hole_polygon[(ihole + 1) % problem.hole_polygon.size()];\r\n        if ((moved_i == h0 && moved_j == h1) ||\r\n            (moved_i == h1 && moved_j == h0)) {\r\n          on_edge = true;\r\n          break;\r\n        }\r\n      }\r\n      if (!on_edge) {\r\n        // if moved_i, moved_j is exactly on the hole polygon, intersectSS / bg::difference always say that\r\n        // the segment is INSIDE the polygon which is wrong when it is concave.\r\n        // dirty hack:\r\n        const double p = 1e-6;\r\n        const Point2d interp {\r\n          get_x(moved_i) * p + get_x(moved_j) * (1.0 - p) ,\r\n          get_y(moved_i) * p + get_y(moved_j) * (1.0 - p) ,\r\n        };\r\n        if (contains(hole_polygon_d, interp) == EContains::EOUT) {\r\n          intersects = true;\r\n        }\r\n      }\r\n    }\r\n    if (intersects) {\r\n      res.out_of_hole_edges.push_back(iedge);\r\n    }\r\n  }\r\n#endif\r\n  \r\n  // stretch\r\n  if (res.is_globalist_mode) {\r\n    double globalist = 0.0;\r\n    for (size_t iedge = 0; iedge < problem.edges.size(); ++iedge) {\r\n      const auto& edge = problem.edges[iedge];\r\n      auto org_i = problem.vertices[edge.first];\r\n      auto org_j = problem.vertices[edge.second];\r\n      auto moved_i = solution.vertices[edge.first];\r\n      auto moved_j = solution.vertices[edge.second];\r\n      globalist += std::abs(double(distance2(moved_i, moved_j)) / double(distance2(org_i, org_j)) - 1);\r\n    }\r\n    if (globalist * 1000000.0 > problem.edges.size() * problem.epsilon) {\r\n      res.violates_globalist = true;\r\n    }\r\n  } else {\r\n    for (size_t iedge = 0; iedge < problem.edges.size(); ++iedge) {\r\n      const auto& edge = problem.edges[iedge];\r\n      auto org_i = problem.vertices[edge.first];\r\n      auto org_j = problem.vertices[edge.second];\r\n      auto moved_i = solution.vertices[edge.first];\r\n      auto moved_j = solution.vertices[edge.second];\r\n      if (!tolerate(distance2(org_i, org_j), distance2(moved_i, moved_j), problem.epsilon)) {\r\n        res.stretch_violating_edges.push_back(iedge);\r\n      }\r\n    }\r\n    if (res.is_superflex_mode && res.stretch_violating_edges.size() == 1) {\n      res.superflex_index = res.stretch_violating_edges[0];\n    }\n  }\r\n\r\n  // dislikes\r\n  res.individual_dislikes.assign(problem.hole_polygon.size(), 0);\r\n  for (size_t ihole = 0; ihole < problem.hole_polygon.size(); ++ihole) {\r\n    const auto& h = problem.hole_polygon[ihole];\r\n    integer minval = std::numeric_limits<integer>::max();\r\n    for (size_t ivert = 0; ivert < solution.vertices.size(); ++ivert) {\r\n      const auto& v = solution.vertices[ivert];\r\n      minval = std::min(minval, distance2(h, v));\r\n    }\r\n    res.individual_dislikes[ihole] = minval;\r\n    res.dislikes += minval;\r\n  }\r\n\r\n  // gain bonus\r\n  res.gained_bonus_indices.clear();\r\n  for (size_t ibonus = 0; ibonus < problem.bonuses.size(); ++ibonus) {\r\n    for (size_t ivert = 0; ivert < solution.vertices.size(); ++ivert) {\r\n      if (problem.bonuses[ibonus].position == solution.vertices[ivert]) {\r\n        res.gained_bonus_indices.push_back(ibonus);\r\n        break;\r\n      }\r\n    }\r\n  }\r\n\r\n  return res;\r\n}\r\n\r\nbool update_judge(const SProblem& problem, const SJudgeResult& res, nlohmann::json& solution_json) {\r\n  if (solution_json.find(\"meta\") == solution_json.end()) solution_json[\"meta\"] = {};\r\n  auto& meta_json = solution_json[\"meta\"];\r\n  if (meta_json.find(\"judge\") == meta_json.end()) meta_json[\"judge\"] = {};\r\n  \r\n  meta_json[\"judge\"][\"dislikes\"] = res.dislikes;\r\n  meta_json[\"judge\"][\"fit_in_hole\"] = res.fit_in_hole();\r\n  meta_json[\"judge\"][\"satisfy_stretch\"] = res.satisfy_stretch();\r\n  meta_json[\"judge\"][\"is_valid\"] = res.is_valid();\r\n\r\n  meta_json[\"judge\"][\"gained_bonuses\"] = nlohmann::json::array();\r\n  for (auto bid : res.gained_bonus_indices) {\r\n    meta_json[\"judge\"][\"gained_bonuses\"].push_back({\r\n      {\"position\", problem.bonuses[bid].position},\r\n      {\"bonus\", SBonus::bonus_name(problem.bonuses[bid].type)},\r\n      {\"problem\", problem.bonuses[bid].problem_id},\r\n      });\r\n  }\r\n\r\n  return true;\r\n}\r\n", "meta": {"hexsha": "f52e9e91f8d01246381b93667273b7aaf7028f2b", "size": 8719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/judge.cpp", "max_stars_repo_name": "nodchip/icfpc2021", "max_stars_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:52:18.000Z", "max_issues_repo_path": "src/judge.cpp", "max_issues_repo_name": "nodchip/icfpc2021", "max_issues_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/judge.cpp", "max_forks_repo_name": "nodchip/icfpc2021", "max_forks_repo_head_hexsha": "e50f0172fd62097049dab19c01875c57468a13f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:49:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:49:18.000Z", "avg_line_length": 35.016064257, "max_line_length": 137, "alphanum_fraction": 0.6316091295, "num_tokens": 2408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.5703294129109328}}
{"text": "#include \"scene.hpp\"\n\n#include \"intersection_info.hpp\"\n#include \"object.hpp\"\n\n#include <math/ray3d.hpp>\n\n#include <boost/optional.hpp>\n#include <boost/none.hpp>\n\n#include <algorithm>\n#include <numeric>\n\nnamespace core\n{\n\nbool intersects(const scene& scn, math::ray3d ray)\n{\n  return std::any_of(std::begin(scn.objects), std::end(scn.objects), [=](const object& obj){\n    return intersects(obj, ray);\n  });\n}\n\nboost::optional<core::intersection_info> closest_intersection(const scene& scn, math::ray3d ray)\n{\n  core::intersection_info info;\n  float min_dist = std::numeric_limits<float>::infinity();\n\n  for (auto &obj : scn.objects)\n  {\n    auto possible_inter = closest_intersection(obj, ray);\n\n    if (possible_inter.is_initialized() == false) { continue; }\n\n    auto curr_dist = math::distance(ray.origin, possible_inter.get().point);\n    if (curr_dist < min_dist)\n    {\n      min_dist = curr_dist;\n      info.obj = &obj;\n      info.shape_info = possible_inter.get();\n    }\n  }\n\n  if (min_dist == std::numeric_limits<float>::infinity()) { return boost::none; }\n\n  return info;\n}\n\n}", "meta": {"hexsha": "2922631cecee5d73dfb2dc9cafa8ce358b7bedeb", "size": 1083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/scene.cpp", "max_stars_repo_name": "TiagoRabello/Path-Tracer", "max_stars_repo_head_hexsha": "1ad32741fdff0b8f48ef675e9071c1495cbcdde3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/scene.cpp", "max_issues_repo_name": "TiagoRabello/Path-Tracer", "max_issues_repo_head_hexsha": "1ad32741fdff0b8f48ef675e9071c1495cbcdde3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-02-01T09:14:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-01T09:14:44.000Z", "max_forks_repo_path": "src/core/scene.cpp", "max_forks_repo_name": "TiagoRabello/Path-Tracer", "max_forks_repo_head_hexsha": "1ad32741fdff0b8f48ef675e9071c1495cbcdde3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1020408163, "max_line_length": 96, "alphanum_fraction": 0.6814404432, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5703294074677199}}
{"text": "//\n//  meanie3D-detect\n//  cf-algorithms\n//\n//  Created by J\u00fcrgen Lorenz Simon on 5/3/12.\n//  Copyright (c) 2012 J\u00fcrgen 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 *         Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II\n *         Copyright 2009 & onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n *\n *          Distributed under the Boost Software License, Version 0x01.0.\n *                 See accompanying file LICENSE.txt or copy at\n *                     http://www.boost.org/LICENSE_1_0.txt\n ******************************************************************************/\n#define NT2_UNIT_MODULE \"nt2::memory::is_power_of_2\"\n\n#include <nt2/sdk/memory/meta/is_power_of_2.hpp>\n\n#include <boost/mpl/int.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/basic.hpp>\n\n////////////////////////////////////////////////////////////////////////////////\n// Test the meta::is_power_of_2 version on int_\n////////////////////////////////////////////////////////////////////////////////\nNT2_TEST_CASE(is_power_of_2)\n{\n  using nt2::meta::is_power_of_2;\n  using boost::mpl::int_;\n\n  NT2_TEST(!(is_power_of_2< int_<0x00> >::value));\n  NT2_TEST( (is_power_of_2< int_<0x01> >::value));\n  NT2_TEST( (is_power_of_2< int_<0x02> >::value));\n  NT2_TEST(!(is_power_of_2< int_<0x03> >::value));\n  NT2_TEST( (is_power_of_2< int_<0x04> >::value));\n  NT2_TEST(!(is_power_of_2< int_<0x05> >::value));\n  NT2_TEST(!(is_power_of_2< int_<0x06> >::value));\n  NT2_TEST(!(is_power_of_2< int_<0x07> >::value));\n  NT2_TEST( (is_power_of_2< int_<0x08> >::value));\n  NT2_TEST( (is_power_of_2< int_<0x10> >::value));\n  NT2_TEST( (is_power_of_2< int_<0x20> >::value));\n  NT2_TEST( (is_power_of_2< int_<0x40> >::value));\n  NT2_TEST( (is_power_of_2< int_<0x80> >::value));\n  NT2_TEST(!(is_power_of_2< int_<1337> >::value));\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Test the meta::is_power_of_2 version on integer\n////////////////////////////////////////////////////////////////////////////////\nNT2_TEST_CASE(is_power_of_2_c)\n{\n  using nt2::meta::is_power_of_2_c;\n\n  NT2_TEST(!(is_power_of_2_c< 0x00 >::value));\n  NT2_TEST( (is_power_of_2_c< 0x01 >::value));\n  NT2_TEST( (is_power_of_2_c< 0x02 >::value));\n  NT2_TEST(!(is_power_of_2_c< 0x03 >::value));\n  NT2_TEST( (is_power_of_2_c< 0x04 >::value));\n  NT2_TEST(!(is_power_of_2_c< 0x05 >::value));\n  NT2_TEST(!(is_power_of_2_c< 0x06 >::value));\n  NT2_TEST(!(is_power_of_2_c< 0x07 >::value));\n  NT2_TEST( (is_power_of_2_c< 0x08 >::value));\n  NT2_TEST( (is_power_of_2_c< 0x10 >::value));\n  NT2_TEST( (is_power_of_2_c< 0x20 >::value));\n  NT2_TEST( (is_power_of_2_c< 0x40 >::value));\n  NT2_TEST( (is_power_of_2_c< 0x80 >::value));\n  NT2_TEST(!(is_power_of_2_c< 1337 >::value));\n}\n", "meta": {"hexsha": "f57f7ce6cf544613a9c439475d023ab7bf08f877", "size": 2682, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/sdk/unit/memory/is_power_of_2.cpp", "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/sdk/unit/memory/is_power_of_2.cpp", "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/sdk/unit/memory/is_power_of_2.cpp", "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": 42.5714285714, "max_line_length": 80, "alphanum_fraction": 0.5581655481, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067222797121, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5703217523367885}}
{"text": "/**\n * SAMPLE APPLICATION FOR DEMONSTRATING gdb-plot functionality\n *\n * BUILD: g++ -g -I/usr/include/eigen3 eigen_example.cpp -o eigen_example\n * RUN: gdb eigen_example\n *      (gdb) b 51\n *      (gdb) plot sin_array cos_array\n */\n\n#include <iostream>\n#include <complex>\n#include <list>\n#include <set>\n#include <map>\n#include <vector>\n\n// Eigen Types\n#include <Eigen/Dense>\n\n\nint main(void)\n{\n\n    Eigen::MatrixXd m(1,10);\n    Eigen::ArrayXcd eigen_complex_array(10);\n    Eigen::ArrayXd eigen_double_array(10);\n    Eigen::ArrayXcd eca2(2048);\n    Eigen::ArrayXd  eda2(2048);\n    Eigen::ArrayXd  sin_array(2048);\n    Eigen::ArrayXd  cos_array(2048);\n    Eigen::ArrayXd  tan_array(2048);\n\n    // Push some data around\n    for ( std::size_t ii=0; ii < 10; ii++ )\n    {\n        m(0,ii) = ii * M_PI;\n        eigen_double_array( ii ) = M_PI * ii;\n        eigen_complex_array( ii ) = M_PI * ii + 0.1j;\n    }\n\n    for ( std::size_t ii=0; ii < eca2.size(); ii++ )\n    {\n        eda2(ii) = ii * 0.01;\n        eca2(ii) = ii + 0.1j;\n    }\n\n    sin_array = eda2.sin();\n    cos_array = eda2.cos();\n    tan_array = eda2.tan();\n    \n    std::cout << \"\\n\\n----------------------------------------\\n\\n\"\n              << \"Break on line \" <<  __LINE__ << \" to plot: \\n\"\n              << \"  plot eda2 for an Eigen double array\\n\"\n              << \"  plot eca2 for an Eigen complex array\\n\"\n              << \"  plot sin_array cos_array  tan_array for trig plots\\n\"\n              << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "8008ac543df87a3f23fff48caf90710b92dea3b5", "size": 1489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gdb-plot/examples/eigen_example.cpp", "max_stars_repo_name": "bthcode/cmake_scipy_ctypes_example", "max_stars_repo_head_hexsha": "64a7afdd825f0bb6a50cb174f4ced231b3017c8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gdb-plot/examples/eigen_example.cpp", "max_issues_repo_name": "bthcode/cmake_scipy_ctypes_example", "max_issues_repo_head_hexsha": "64a7afdd825f0bb6a50cb174f4ced231b3017c8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdb-plot/examples/eigen_example.cpp", "max_forks_repo_name": "bthcode/cmake_scipy_ctypes_example", "max_forks_repo_head_hexsha": "64a7afdd825f0bb6a50cb174f4ced231b3017c8d", "max_forks_repo_licenses": ["BSD-3-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.8166666667, "max_line_length": 73, "alphanum_fraction": 0.5540631296, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.570321740811513}}
{"text": "/*\n\u0422\u0435\u0441\u0442 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u0430 \u043d\u0430\u0445\u043e\u0436\u0434\u0435\u043d\u0438\u044f \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0433\u043e \u043e\u0441\u0442\u043e\u0432\u043d\u043e\u0433\u043e \u0434\u0435\u0440\u0435\u0432\u0430\n\u0438\u0437 \u0431\u0438\u0431\u043b\u0438\u043e\u0442\u0435\u043a\u0438 boost. \u041c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u043e\u0441\u0442\u043e\u0432\u043d\u043e\u0435 \u0434\u0435\u0440\u0435\u0432\u043e \u0441\u043e\u0435\u0434\u0438\u043d\u044f\u0435\u0442\n\u0432\u0435\u0440\u0448\u0438\u043d\u044b \u0433\u0440\u0430\u0444\u0430 \u0442\u0430\u043a, \u0447\u0442\u043e \u0441\u0443\u043c\u043c\u0430\u0440\u043d\u044b\u0439 \u0432\u0435\u0441 \u0434\u0435\u0440\u0435\u0432\u0430 \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u044b\u0439.\n\n\u0412 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0435 \u043f\u0440\u0438 \u043a\u043e\u043c\u043f\u0438\u043b\u044f\u0446\u0438\u0438 \u0433\u0440\u0430\u0444 \u043c\u043e\u0436\u043d\u043e \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u0442\u044c \u043a\u0430\u043a \u0432\n\u0432\u0438\u0434\u0435 \u0441\u043f\u0438\u0441\u043a\u0430 \u0441\u043c\u0435\u0436\u043d\u043e\u0441\u0442\u0438 (ADJ_LIST), \u0442\u0430\u043a \u0438 \u0432 \u0432\u0438\u0434\u0435 \u043c\u0430\u0442\u0440\u0438\u0446\u044b\n\u0441\u043c\u0435\u0436\u043d\u043e\u0441\u0442\u0438 (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//\u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0442\u043e\u043b\u044c\u043a\u043e \u0441\u043e\u0432\u043c\u0435\u0441\u0442\u043d\u043e\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//\u0441\u0432\u043e\u0439\u0441\u0442\u0432\u043e \u0440\u0435\u0431\u0435\u0440 - \u0432\u0435\u0441 (\u0434\u043b\u044f \u043d\u0430\u0441 - \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435)\ntypedef property<edge_weight_t, double> EdgeWeightProperty;\n#ifdef ADJ_LIST\n//\u0433\u0440\u0430\u0444 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d \u0432 \u0432\u0438\u0434\u0435 \u0441\u043f\u0438\u0441\u043a\u0430 \u0441\u043c\u0435\u0436\u043d\u043e\u0441\u0442\u0438\ntypedef boost::adjacency_list<vecS,vecS,undirectedS,no_property,EdgeWeightProperty> mygraph;\n#endif\n#ifdef ADJ_MATRIX\n//\u0433\u0440\u0430\u0444 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d \u0432 \u0432\u0438\u0434\u0435 \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u0441\u043c\u0435\u0436\u043d\u043e\u0441\u0442\u0438\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//\u0441\u043b\u0443\u0447\u0430\u0439\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u0432 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b\u0435\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//\u0441\u043b\u0443\u0447\u0430\u0439\u043d\u0430\u044f \u0442\u043e\u0447\u043a\u0430\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//\u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435 \u043c\u0435\u0436\u0434\u0443 \u0442\u043e\u0447\u043a\u0430\u043c\u0438\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//\u0447\u0438\u0441\u043b\u043e \u0442\u043e\u0447\u0435\u043a\n\tconst int pnum = 600;\n\t//\u0433\u0440\u0430\u043d\u0438\u0447\u043d\u043e\u0435 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435 \u043c\u0435\u0436\u0434\u0443 \u0442\u043e\u0447\u043a\u0430\u043c\u0438\n\t//\u0435\u0441\u043b\u0438 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0435 \u043c\u0435\u0436\u0434\u0443 \u0442\u043e\u0447\u043a\u0430\u043c\u0438 \u043c\u0435\u043d\u044c\u0448\u0435 max_dst,\n\t//\u0442\u043e \u043c\u0435\u0436\u0434\u0443 \u0442\u043e\u0447\u043a\u0430\u043c\u0438 \u0441\u043e\u0437\u0434\u0430\u0435\u0442\u0441\u044f \u0440\u0435\u0431\u0440\u043e \u0433\u0440\u0430\u0444\u0430,\n\t//\u0438\u043d\u0430\u0447\u0435 \u043d\u0435\u0442. \u041d\u0443\u0436\u043d\u043e \u0434\u043b\u044f \u043e\u043f\u0442\u0438\u043c\u0438\u0437\u0430\u0446\u0438\u0438 \u0440\u0430\u0441\u0445\u043e\u0434\u0430 \u043f\u0430\u043c\u044f\u0442\u0438 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b\n\tconst float max_dst = 10.0;\n\t//\u0441\u043e\u0437\u0434\u0430\u0435\u043c \u043c\u0430\u0441\u0441\u0438\u0432 \u0438\u0437 \u0445\u0430\u043e\u0442\u0438\u0447\u043d\u043e \u0440\u0430\u0441\u043f\u043e\u043b\u043e\u0436\u0435\u043d\u043d\u044b\u0445 \u0442\u043e\u0447\u0435\u043a\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//\u0432 \u0433\u0440\u0430\u0444 \u0437\u0430\u043f\u0438\u0441\u044b\u0432\u0430\u0435\u043c \u0432\u0441\u0435 \u0445\u0430\u043e\u0442\u0438\u0447\u043d\u043e \u0440\u0430\u0441\u043f\u043e\u043b\u043e\u0436\u0435\u043d\u043d\u044b\u0435 \u0442\u043e\u0447\u043a\u0438\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//\u043e\u0431\u0445\u043e\u0434 \u0433\u0440\u0430\u0444\u0430\n\n\t//\u043d\u0430\u0445\u043e\u0434\u0438\u043c \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u043e\u0441\u0442\u043e\u0432\u043d\u043e\u0435 \u0434\u0435\u0440\u0435\u0432\u043e\n\t//\u043e\u043d\u043e \u0432 \u0432\u0438\u0434\u0435 \u0441\u043f\u0438\u0441\u043a\u0430 \u043f\u0430\u0440 \u0432\u0435\u0440\u0448\u0438\u043d\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//\u0434\u043e\u0441\u0442\u0430\u0435\u043c \u0438\u043d\u0434\u0435\u043a\u0441\u044b \u0432\u0435\u0440\u0448\u0438\u043d \u0438\u0437 spanning_tree\n\t\tEdge e = *i;\n\t\t//\u0432\u0435\u0440\u0448\u0438\u043d\u0430, \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0438\u0434\u0435\u0442 \u0440\u0435\u0431\u0440\u043e\n\t\tsize_t source_index = e.m_source;\n\t\t//\u0432\u0435\u0440\u0448\u0438\u043d\u0430, \u0432 \u043a\u043e\u0442\u043e\u0440\u0443\u044e \u0438\u0434\u0435\u0442 \u0440\u0435\u0431\u0440\u043e\n\t\tsize_t dest_index = e.m_target;\n\t\t//\u043f\u0440\u043e\u0441\u0442\u043e \u0432\u044b\u0432\u043e\u0434\u0438\u043c \u0438\u043d\u0434\u0435\u043a\u0441\u044b, \u0445\u043e\u0442\u044f \u043c\u043e\u0436\u0435\u043c \u0434\u0435\u043b\u0430\u0442\u044c \u0447\u0442\u043e-\u0442\u043e \u043f\u043e\u043b\u0435\u0437\u043d\u043e\u0435\n\t\t//\u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0441\u0442\u0440\u043e\u0438\u0442\u044c \u043c\u043e\u0441\u0442\u0438\u043a\u0438 \u043c\u0435\u0436\u0434\u0443 \u043f\u043e\u043b\u0438\u0433\u043e\u043d\u0430\u043c\u0438 \u0441 \u0437\u0430\u0434\u0430\u043d\u043d\u044b\u043c\u0438 \u0438\u043d\u0434\u0435\u043a\u0441\u0430\u043c\u0438\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// \u50cf\u7d20\u5750\u6807\u8f6c\u76f8\u673a\u5f52\u4e00\u5316\u5750\u6807\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  //-- \u8bfb\u53d6\u56fe\u50cf\n  Mat img_1 = imread(argv[1], CV_LOAD_IMAGE_COLOR);\n  Mat img_2 = imread(argv[2], CV_LOAD_IMAGE_COLOR);\n\n  vector<KeyPoint> keypoints_1, keypoints_2;\n  vector<DMatch> matches;\n  find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n  cout << \"\u4e00\u5171\u627e\u5230\u4e86\" << matches.size() << \"\u7ec4\u5339\u914d\u70b9\" << endl;\n\n  // \u5efa\u7acb3D\u70b9\n  Mat d1 = imread(argv[3],\n                  CV_LOAD_IMAGE_UNCHANGED);  // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n  Mat K = (Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n  vector<Point3f> pts_3d;\n  vector<Point2f> pts_2d;\n  for (DMatch m : matches) {\n    ushort d = d1.ptr<unsigned short>(\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);  // \u8c03\u7528OpenCV \u7684 PnP \u6c42\u89e3\uff0c\u53ef\u9009\u62e9EPNP\uff0cDLS\u7b49\u65b9\u6cd5\n  Mat R;\n  cv::Rodrigues(r, R);  // r\u4e3a\u65cb\u8f6c\u5411\u91cf\u5f62\u5f0f\uff0c\u7528Rodrigues\u516c\u5f0f\u8f6c\u6362\u4e3a\u77e9\u9635\n\n  cout << \"R=\" << endl << R << endl;\n  cout << \"t=\" << endl << t << endl;\n\n  cout << \"calling bundle adjustment\" << endl;\n\n  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  //-- \u521d\u59cb\u5316\n  Mat descriptors_1, descriptors_2;\n  // used in OpenCV3\n  Ptr<FeatureDetector> detector = ORB::create();\n  Ptr<DescriptorExtractor> descriptor = ORB::create();\n  // use this if you are in OpenCV2\n  // Ptr<FeatureDetector> detector = FeatureDetector::create ( \"ORB\" );\n  // Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( \"ORB\"\n  // );\n  Ptr<DescriptorMatcher> matcher =\n      DescriptorMatcher::create(\"BruteForce-Hamming\");\n  //-- \u7b2c\u4e00\u6b65:\u68c0\u6d4b Oriented FAST \u89d2\u70b9\u4f4d\u7f6e\n  detector->detect(img_1, keypoints_1);\n  detector->detect(img_2, keypoints_2);\n\n  //-- \u7b2c\u4e8c\u6b65:\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97 BRIEF \u63cf\u8ff0\u5b50\n  descriptor->compute(img_1, keypoints_1, descriptors_1);\n  descriptor->compute(img_2, keypoints_2, descriptors_2);\n\n  //-- \u7b2c\u4e09\u6b65:\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n  vector<DMatch> match;\n  // BFMatcher matcher ( NORM_HAMMING );\n  matcher->match(descriptors_1, descriptors_2, match);\n\n  //-- \u7b2c\u56db\u6b65:\u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n  double min_dist = 10000, max_dist = 0;\n\n  //\u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb,\n  //\u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb\n  for (int i = 0; i < descriptors_1.rows; i++) {\n    double dist = match[i].distance;\n    if (dist < min_dist) min_dist = dist;\n    if (dist > max_dist) max_dist = dist;\n  }\n\n  printf(\"-- Max dist : %f \\n\", max_dist);\n  printf(\"-- Min dist : %f \\n\", min_dist);\n\n  //\u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\n  for (int i = 0; i < descriptors_1.rows; i++) {\n    if (match[i].distance <= max(2 * min_dist, 30.0)) {\n      matches.push_back(match[i]);\n    }\n  }\n}\n\nPoint2d pixel2cam(const Point2d& p, const Mat& K) {\n  return Point2d((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  // \u521d\u59cb\u5316g2o\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>>\n      Block;  // pose \u7ef4\u5ea6\u4e3a 6, landmark \u7ef4\u5ea6\u4e3a 3\n  Block::LinearSolverType* linearSolver =\n      new g2o::LinearSolverCSparse<Block::PoseMatrixType>();  // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n  Block* solver_ptr = new Block(linearSolver);  // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n  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 \u4e2d\u5fc5\u987b\u8bbe\u7f6e marg \u53c2\u89c1\u7b2c\u5341\u8bb2\u5185\u5bb9\n    optimizer.addVertex(point);\n  }\n\n  // parameter: camera intrinsics\n  g2o::CameraParameters* camera = new g2o::CameraParameters(\n      K.at<double>(0, 0),\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": "/*!=======================================================\n  |                                                     |\n  |              test_micro_element.cpp                 |\n  |                                                     |\n  -------------------------------------------------------\n  | The unit test file for micro_element.h/cpp.         |\n  | This file tests the classes and functions defined   |\n  | in micro_element.h/cpp.                             |\n  |                                                     |\n  | Generated files:                                    |\n  |    Results.tex:  A LaTeX file which contains the    |\n  |                  results as they will be included   |\n  |                  in the generated report.           |\n  =======================================================\n  | Dependencies:                                       |\n  | Eigen:  An implementation of various matrix         |\n  |         commands. The implementation of the data    |\n  |         matrix uses such a matrix.                  |\n  | tensor: An implementation of a tensor which stores  |\n  |         the data in a 2D matrix but allows access   |\n  |         through n dimensional index notation.       |\n  =======================================================*/\n  \n#include <functional>\n#include <iostream>\n#include <fstream>\n#include <numeric>\n#include <vector>\n#include <Eigen/Dense>\n#include <tensor.h>\n#include <micro_element.h>\n#include <finite_difference.h>\n#include <ctime>\n#include <stdlib.h>\n\nvoid print_vector(std::string name, std::vector< double > V){\n    /*!======================\n    |    print_vector    |\n    ======================\n    \n    Print a vector to the screen\n    \n    */\n    \n    std::cout << name << \": \";\n    \n    for(int i=0; i<V.size(); i++){\n        std::cout << V[i] << \" \";\n    }\n    std::cout << \"\\n\";\n}\n\nvoid print_vector_of_vectors(std::string name, std::vector< std::vector< double > > V){\n    /*!=================================\n    |    print_vector_of_vectors    |\n    =================================\n    \n    Print a vector of vectors to the screen\n    \n    */\n    \n    for(int i=0; i<V.size(); i++){\n        std::cout << name << \"[\" << i << \"]: \";\n        for(int j=0; j<V[i].size(); j++){\n            std::cout << V[i][j] << \" \";\n        }\n        std::cout << \"\\n\";\n    }\n}\n\nbool double_compare(double d1, double d2, double abs_tol=1e-6, double rel_tol = 1e-6){\n    /*!========================\n    |    double_compare    |\n    ========================\n    \n    Compare two doubles using a \n    tolerance.\n    \n    */\n    \n    double abs_error = fabs(d1-d2);\n    double rel_error;\n    \n    if(std::max(fabs(d1),fabs(d2))>abs_tol){\n        rel_error = fabs(d1-d2)/std::max(fabs(d1),fabs(d2));\n    }\n    \n    if((abs_error>abs_tol) && (rel_error>rel_tol)){return false;}\n    return true;\n}\n\nstd::vector< double > generate_current_coordinates(std::vector< double > reference_coord){\n    /*!======================================\n    |    generate_current_coordinates    |\n    ======================================\n    \n    Generate output coordinates of the incoming coordinates \n    such that a known deformation can be applied.\n    \n    Input:\n        reference_coord: The coordinates in the reference \n                         configuration which will be mapped \n                         to a coordinate in the current \n                         configuration.\n    \n    */\n    \n    std::vector< double > current_coord(3,0.);\n    \n    current_coord[0] =  1.30*reference_coord[0]-0.375*reference_coord[1]+1.20*reference_coord[2]+1.0;\n    current_coord[1] =  0.75*reference_coord[0]+0.650*reference_coord[1]-0.31*reference_coord[2]-2.3;\n    current_coord[2] = -2.30*reference_coord[0]+1.400*reference_coord[1]+0.44*reference_coord[2]+0.3;\n    \n    return current_coord;\n}\n\ntensor::Tensor23 get_gradient_coordinates(std::vector< double > reference_coord){\n    /*!==================================\n    |    get_gradient_coordinates    |\n    ==================================\n    \n    Generate the gradient of the output coordinates\n    with respect to the incoming coordinates.\n    \n    Input:\n        reference_coord: The coordinates in the reference \n                         configuration which will be mapped \n                         to a coordinate in the current \n                         configuration.\n    \n    */\n    \n    tensor::Tensor23 T;\n    T(0,0) =  1.300;\n    T(0,1) = -0.375;\n    T(0,2) =  1.200;\n    T(1,0) =  0.750;\n    T(1,1) =  0.650;\n    T(1,2) = -0.310;\n    T(2,0) = -2.300;\n    T(2,1) =  1.400;\n    T(2,2) =  0.440;\n    \n    return T;\n    \n}\n\nint test_constructors(std::ofstream &results){\n    /*!===========================\n    |    test_constructors    |\n    ===========================\n    \n    Run tests on the constructors to ensure that \n    they result in the expected behavior.\n    \n    */\n    \n    //Seed the random number generator\n    srand (1);\n    \n    //!Initialize test results\n    int  test_num        = 8;\n    std::vector<bool> test_results(test_num,false);\n    \n    //!Form the required vectors\n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0,0,1,1,0,1,1,1,1,0,1,1};\n    std::vector< double > U;\n    std::vector< double > dU;\n    U.resize(96);\n    dU.resize(96);\n    for(int i=0; i<96; i++){\n        U[i]  = (rand()%100-50)/1000.;\n        dU[i] = (rand()%100-50)/10000.;\n    }\n    \n    //!|=> Test 1\n    //!Test the empty constructor\n    micro_element::Hex8 A = micro_element::Hex8();\n    \n    test_results[0]  = A.RHS.rows()    == 96;\n    test_results[1]  = A.AMATRX.rows() == 96;\n    test_results[1]  = test_results[1] * (A.AMATRX.cols() == 96);\n    \n    //!|=> Test 2\n    //!Test the constructor with the reference node locations\n    micro_element::Hex8 B = micro_element::Hex8(reference_coords);\n    \n    std::vector< std::vector< double > > B_answer= {{0,0,0},{1,0,0},{1,1,0},{0,1,0},\n                                                    {0,0,1},{1,0,1},{1,1,1},{0,1,1}}; //!The desired format of reference_coords and current_coords\n    \n    test_results[2] = B_answer==B.reference_coords;\n    test_results[3] = B_answer==B.current_coords;\n    \n    //!Test the constructor with the reference node locations and the degree of freedom vectors\n    micro_element::Hex8 C = micro_element::Hex8(reference_coords,U,dU);\n    \n    std::vector< std::vector< double > > U_answer;\n    std::vector< std::vector< double > > dU_answer;\n    \n    U_answer.resize(8);\n    dU_answer.resize(8);\n    \n    //!|=> Test 3\n    //!Test if the dof vectors were parsed correctly\n    for(int n=0; n<8; n++){\n        U_answer[n].resize(12);\n        dU_answer[n].resize(12);\n        \n        for(int i=0; i<12; i++){\n            U_answer[n][i]  = U[i+n*12];\n            dU_answer[n][i] = dU[i+n*12];\n        }\n    }\n    \n    test_results[4] = U_answer == C.dof_at_nodes;\n    test_results[5] = dU_answer == C.Delta_dof_at_nodes;\n    \n    //!|=> Test 4\n    //!Check if the current coordinates were updated correctly\n    test_results[6] = true;\n    for(int n=0; n<8; n++){\n        for(int i=0; i<3; i++){\n            test_results[6] = test_results[6] * (fabs(C.current_coords[n][i]-(U[i+n*12]+reference_coords[i+n*3]))<1e-6);\n        }\n    }\n    \n    //!|=> Test 5\n    //!Check if the phi values were updated correctly\n    tensor::Tensor23 phic({3,3});\n    \n    test_results[7] = true;\n    for(int n=0; n<8; n++){\n        phic(0,0) = C.dof_at_nodes[n][ 3];\n        phic(1,1) = C.dof_at_nodes[n][ 4];\n        phic(2,2) = C.dof_at_nodes[n][ 5];\n        phic(1,2) = C.dof_at_nodes[n][ 6];\n        phic(0,2) = C.dof_at_nodes[n][ 7];\n        phic(0,1) = C.dof_at_nodes[n][ 8];\n        phic(2,1) = C.dof_at_nodes[n][ 9];\n        phic(2,0) = C.dof_at_nodes[n][10];\n        phic(1,0) = C.dof_at_nodes[n][11];\n        \n        test_results[7] = test_results[7] * (phic.data == C.node_phis[n].data);\n    }\n    \n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_constructors & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_constructors & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return 1;\n}\n\nint test_shape_functions(std::ofstream &results){\n    /*!==============================\n    |    test_shape_functions    |\n    ==============================\n    \n    Run tests on the shape functions and related \n    methods to ensure they are functioning \n    properly\n    \n    */\n    \n    //Seed the random number generator\n    srand (1);\n    \n    //!Initialize test results\n    int  test_num        = 8;\n    std::vector<bool> test_results(test_num,false);\n    \n    //!Form the required vectors for element formation\n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0,0,1,1,0,1,1,1,1,0,1,1};\n    std::vector< double > U;\n    std::vector< double > dU;\n    U.resize(96);\n    dU.resize(96);\n    for(int i=0; i<96; i++){\n        U[i]  = (rand()%100-50)/1000.;\n        dU[i] = (rand()%100-50)/10000.;\n    }\n    \n    //!Form the hexehedral test element.\n    micro_element::Hex8 element = micro_element::Hex8(reference_coords,U,dU);\n    \n    \n    //!=\n    //!| Tests of Hex8::set_shape_function and Hex8::set_shape_functions\n    //!=\n    \n    //!|=> Test 1\n    //!Test whether the shape functions values are unity at the correct nodes\n    //!and zero elsewhere.\n    \n    element.points     = {{-1,-1,-1},{ 1,-1,-1},{ 1, 1,-1},{-1, 1,-1},\n                          {-1,-1, 1},{ 1,-1, 1},{ 1, 1, 1},{-1, 1, 1}}; //Set the gauss points of the element to the nodes (done for testing purposes)\n    test_results[0] = true;\n    for(int n=0; n<8; n++){\n        element.set_gpt_num(n);        //Set the, \"gauss point,\" of the element to the current node\n        element.set_shape_functions(); //Compute all of the values of the shape functions\n        test_results[0] = test_results[0] * ((1e-9>(element.get_N(n)-1) && (element.get_N(n)-1))>=0); //The shape function should be equal to one at the specified node\n        for(int m=0; m<8; m++){\n            if(n==m){test_results[0] = test_results[0] * ((1e-9>(element.get_N(n)-element.get_N(m))) && ((element.get_N(n)-element.get_N(m))>=0));} //The shape function should only be 1 at N==M\n            else{test_results[0] = test_results[0] * (1e-9>element.get_N(n)-element.get_N(m)-1>=0);}\n        }\n    }\n    \n    //!|=> Test 2\n    //!Test whether the sum of the shape functions values are unity at a\n    //!point within the element\n    \n    element.points[0] = {0,0,0}; //!The local coordinate (set as a false gauss point)\n    for(int i=0; i<3; i++){element.points[0][i] = (rand()%1000-500)/1000.;} //!Populate the local coordinate at a location in each direction between -1 and 1\n    element.set_gpt_num(0);\n\n    double sum_Ns;\n    \n    element.set_shape_functions(); //Compute all of the nodal shape functions at the given point\n\n    for(int n=0; n<8; n++){sum_Ns += element.get_N(n);} //Sum up all of the values of the shape function at the point\n    \n    test_results[1] = ((1e-9>(sum_Ns-1.)) && ((sum_Ns-1.)>=0));\n    \n    //!|=> Test 3\n    //!Test whether the gradient of the shape function w.r.t. the local \n    //!coordinates are correct at the center of the element\n    \n    element.points[0] = {0.,0.,0.};\n    std::vector< std::vector< double > > dNdxi_answers = {{ -0.125, -0.125, -0.125},{  0.125, -0.125, -0.125},{  0.125,  0.125, -0.125},{-0.125,  0.125, -0.125},\n                                                          { -0.125, -0.125,  0.125},{  0.125, -0.125,  0.125},{  0.125,  0.125,  0.125},{-0.125,  0.125,  0.125}};\n    \n    element.set_gpt_num(0);\n    //std::cout << \"Setting the local gradient of the shape functions\\n\";\n    element.set_local_gradient_shape_functions();\n    //std::cout << \"Comparing the results vs. the answers\\n\";\n  \n    test_results[2] = true;\n    double temp_diff;\n    for(int n=0; n<8; n++){\n        for(int i=0; i<3; i++){\n            temp_diff        = fabs(element.get_dNdxi(n)[i]-dNdxi_answers[n][i]);\n            test_results[2] = test_results[2] * (1e-9>temp_diff);\n        }\n    }\n    \n    //!|=> Test 4\n    //!Test whether the gradient of the shape function w.r.t. the local\n    //!coordinates are correct at a location off the center of the \n    //!element.\n    \n    element.points[0] = {0.3,-0.6,0.7};\n    element.set_gpt_num(0);\n    dNdxi_answers = {{-0.06   , -0.02625, -0.14},{ 0.06   , -0.04875, -0.26},{ 0.015  ,  0.04875, -0.065},{-0.015  ,  0.02625, -0.035},\n                     {-0.34   , -0.14875,  0.14},{ 0.34   , -0.27625,  0.26},{ 0.085  ,  0.27625,  0.065},{-0.085  ,  0.14875,  0.035}};\n    \n    element.set_local_gradient_shape_functions();\n  \n    test_results[3] = true;\n    bool temp;\n    for(int n=0; n<8; n++){\n        for(int i=0; i<3; i++){\n            temp_diff = fabs(element.get_dNdxi(n)[i]-dNdxi_answers[n][i]);\n            test_results[3] = test_results[3] * ((1e-9>temp_diff) && (temp_diff>=0));\n        }\n    }\n    \n    //!|=> Test 5\n    //!Test whether the jacobian is computed correctly for the reference coordinates \n    //!at a location off the center of the element.\n    \n    tensor::Tensor23 J_answer({3,3}); //!The answer jacobian.\n    tensor::Tensor23 J_result = element.get_jacobian(0);\n    for(int n=0; n<8; n++){\n        //J_answer += micro_element::vector_dyadic_product(dNdxi_answers[n],element.reference_coords[n]); //Compute the expected value of the jacobian\n        J_answer += micro_element::vector_dyadic_product(element.reference_coords[n],dNdxi_answers[n]);\n    }\n    test_results[4] = J_result.data.isApprox(J_answer.data); //Test the results\n    \n    //!|=> Test 6\n    //!Test whether the jacobian is computed correctly for the current coordinates\n    \n    J_answer.data.setZero();\n    J_result = element.get_jacobian(1);\n    \n    for(int n=0; n<8; n++){\n        //J_answer += micro_element::vector_dyadic_product(dNdxi_answers[n],element.current_coords[n]);\n        J_answer += micro_element::vector_dyadic_product(element.current_coords[n],dNdxi_answers[n]);\n    }\n    \n    test_results[5] = J_result.data.isApprox(J_answer.data);\n    \n    //!|=> Test 7\n    //!Test whether the gradient of the shape function with respect to the \n    //!reference coordinates is computed correctly.\n    \n    std::vector< std::vector< double > > dNdX_answer; //Initialize the expected answer\n    dNdX_answer.resize(8);\n    tensor::Tensor23 Jtemp = element.get_jacobian(0); //Get dXdxi\n    Jtemp = Jtemp.inverse();                          //Get dxidX\n    \n    for(int n=0; n<8; n++){\n        dNdX_answer[n].resize(3); //Resize the gradient to be in three dimensions\n        for(int i=0; i<3; i++){dNdX_answer[n][i]=0;} //Zero out the gradient\n        for(int i=0; i<3; i++){\n            for(int j=0; j<3; j++){\n                dNdX_answer[n][i] += Jtemp(j,i)*dNdxi_answers[n][j]; // Compute dxi_j dX_i dN dxi_j \n            }\n        }\n    }\n    \n    element.set_global_gradient_shape_functions(0);\n    \n    //Check the answer to the result\n    test_results[6] = true;\n    for(int n=0; n<8; n++){\n        //print_vector(\"result\",element.get_dNdx(0,n));\n        //print_vector(\"answer\",dNdX_answer[n]);\n        for(int i=0; i<3; i++){\n            test_results[6] = test_results[6] * (1e-9>fabs(element.get_dNdx(0,n)[i]-dNdX_answer[n][i]));\n        }\n    }\n    \n    //!|=> Test 8\n    //!Test whether the gradient of the shape function with respect to the \n    //!current coordinates is computed correctly.\n    \n    std::vector< std::vector< double > > dNdx_answer; //Initialize the expected answer\n    dNdx_answer.resize(8);\n    Jtemp = element.get_jacobian(1); //Get dxdxi\n    Jtemp = Jtemp.inverse();         //Get dxidx\n    \n    for(int n=0; n<8; n++){\n        dNdx_answer[n].resize(3); //Resize the gradient to be in three dimensions\n        for(int i=0; i<3; i++){dNdx_answer[n][i]=0;} //Zero out the gradient\n        for(int i=0; i<3; i++){\n            for(int j=0; j<3; j++){\n                dNdx_answer[n][i] += Jtemp(j,i)*dNdxi_answers[n][j]; // Compute dxi_j dx_i dN dxi_j \n            }\n        }\n    }\n    \n    element.set_global_gradient_shape_functions(1);\n    \n    //Check the answer to the result\n    test_results[7] = true;\n    for(int n=0; n<8; n++){\n        //print_vector(\"result\",element.get_dNdx(1,n));\n        //print_vector(\"answer\",dNdx_answer[n]);\n        for(int i=0; i<3; i++){\n            test_results[7] = test_results[7] * (1e-9>fabs(element.get_dNdx(1,n)[i]-dNdx_answer[n][i]));\n        }\n    }\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_shape_functions & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_shape_functions & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return 1;\n\n}\n\nstd::vector< double > test_deformation(std::vector< double > reference_position){\n    /*!==========================\n    |    test_deformation    |\n    ==========================\n    \n    Compute a test deformation \n    to show that the deformation gradient \n    and microdisplacement are being computed \n    correctly.\n    \n    */\n    \n    double X = reference_position[0];\n    double Y = reference_position[1];\n    double Z = reference_position[2];\n    \n    std::vector< double > U;\n    U.resize(12,0);\n    \n    //!Set the displacements\n    U[ 0] =  0.32*X-0.14*Y+0.61*Z;\n    U[ 1] = -0.50*X+0.24*Y-0.38*Z;\n    U[ 2] = -0.22*X+0.47*Y+0.62*Z;\n    U[ 3] = -1.10*X+0.04*Y+2.30*Z; //phi_11\n    U[ 4] = -0.74*X+1.22*Y+2.22*Z; //phi_22\n    U[ 5] = -2.24*X+5.51*Y+1.11*Z; //phi_33\n    U[ 6] = -5.75*X+2.26*Y+7.66*Z; //phi_23\n    U[ 7] = -6.22*X+8.63*Y+2.72*Z; //phi_13\n    U[ 8] = -2.76*X+3.37*Y+3.93*Z; //phi_12\n    U[ 9] = -6.32*X+6.73*Y+7.22*Z; //phi_32\n    U[10] = -3.83*X+4.29*Y+1.51*Z; //phi_31\n    U[11] = -9.18*X+3.61*Y+9.08*Z; //phi_21\n    \n    return U;\n    \n}\n    \nstd::vector< std::vector< double > > compute_gradients(std::vector< double > reference_position){\n    /*!===========================\n    |    compute_gradients    |\n    ===========================\n    \n    Compute the gradients of the test \n    deformation numerically so that the \n    results are consistent.\n    \n    */\n    \n    finite_difference::FiniteDifference FD(test_deformation,2,reference_position,1e-6);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n    \n}\n\nstd::vector< double > parse_F(std::vector< double > U_in){\n    /*!=================\n    |    parse_F    |\n    =================\n    \n    Parse the computed deformation gradient \n    into a form which can be read by the \n    gradient computation.\n    \n    */\n    \n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1}; //!The reference coordinates.\n    \n    micro_element::Hex8 test_element(reference_coords,U_in,U_in);  //Note: dU is a copy of U. This shouldn't matter.\n    test_element.set_gpt_num(0); //Use the first gauss point\n    test_element.update_shape_function_values();\n    test_element.set_fundamental_measures();                       //Set the fundamental deformation measures\n    tensor::Tensor23 Ftmp = test_element.get_F();\n        \n    //Parse the current value of the deformation gradient\n    std::vector< double > out_F(9,0);\n    out_F[0] = Ftmp(0,0);\n    out_F[1] = Ftmp(0,1);\n    out_F[2] = Ftmp(0,2);\n    out_F[3] = Ftmp(1,0);\n    out_F[4] = Ftmp(1,1);\n    out_F[5] = Ftmp(1,2);\n    out_F[6] = Ftmp(2,0);\n    out_F[7] = Ftmp(2,1);\n    out_F[8] = Ftmp(2,2);\n        \n    return out_F;\n}\n\nstd::vector< std::vector< double > > compute_gradient_F(std::vector< double > U){\n    /*!============================\n    |    compute_gradient_F    |\n    ============================\n    \n    Compute a numeric gradient of the \n    deformation gradient with respect to \n    the degree of freedom vector.\n    \n    */\n    \n    //Define a lambda function to parse the deformation gradient\n    \n    finite_difference::FiniteDifference FD(parse_F,2,U,1e-6);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n}\n\nstd::vector< double > parse_chi(std::vector< double > U_in){\n    /*!===================\n    |    parse_chi    |\n    ===================\n    \n    Parse the computed micro-displacement\n    tensor into a form which can be \n    read by the gradient computation.\n    \n    */\n    \n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1}; //!The reference coordinates.\n    \n    micro_element::Hex8 test_element(reference_coords,U_in,U_in);  //Note: dU is a copy of U. This shouldn't matter.\n    test_element.set_gpt_num(0); //Use the first gauss point\n    test_element.update_shape_function_values();\n    test_element.set_fundamental_measures();                       //Set the fundamental deformation measures\n    tensor::Tensor23 chitmp = test_element.get_chi();\n        \n    //Parse the current value of the deformation gradient\n    std::vector< double > out_chi(9,0);\n    out_chi[0] = chitmp(0,0);\n    out_chi[1] = chitmp(0,1);\n    out_chi[2] = chitmp(0,2);\n    out_chi[3] = chitmp(1,0);\n    out_chi[4] = chitmp(1,1);\n    out_chi[5] = chitmp(1,2);\n    out_chi[6] = chitmp(2,0);\n    out_chi[7] = chitmp(2,1);\n    out_chi[8] = chitmp(2,2);\n        \n    return out_chi;\n}\n\nstd::vector< std::vector< double > > compute_gradient_chi(std::vector< double > U){\n    /*!==============================\n    |    compute_gradient_chi    |\n    ==============================\n    \n    Compute a numeric gradient of the \n    micro-displacement tensor with \n    respect to the degree of freedom \n    vector.\n    \n    */\n    \n    //Define a lambda function to parse the deformation gradient\n    \n    finite_difference::FiniteDifference FD(parse_chi,2,U,1e-6);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n}\n\nstd::vector< double > parse_grad_chi(std::vector< double > U_in){\n    /*!========================\n    |    parse_grad_chi    |\n    ========================\n    \n    Parse the computed gradient of \n    the micro-displacement tensor \n    into a form which can be read \n    by the gradient computation.\n    \n    */\n    \n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1}; //!The reference coordinates.\n    \n    micro_element::Hex8 test_element(reference_coords,U_in,U_in);  //Note: dU is a copy of U. This shouldn't matter.\n    test_element.set_gpt_num(0); //Use the first gauss point\n    test_element.update_shape_function_values();\n    test_element.set_fundamental_measures();                       //Set the fundamental deformation measures\n    tensor::Tensor33 grad_chitmp = test_element.get_grad_chi();\n        \n    //Parse the current value of the deformation gradient\n    std::vector< double > out_grad_chi(27,0);\n    out_grad_chi[ 0] = grad_chitmp(0,0,0);\n    out_grad_chi[ 1] = grad_chitmp(0,1,0);\n    out_grad_chi[ 2] = grad_chitmp(0,2,0);\n    out_grad_chi[ 3] = grad_chitmp(1,0,0);\n    out_grad_chi[ 4] = grad_chitmp(1,1,0);\n    out_grad_chi[ 5] = grad_chitmp(1,2,0);\n    out_grad_chi[ 6] = grad_chitmp(2,0,0);\n    out_grad_chi[ 7] = grad_chitmp(2,1,0);\n    out_grad_chi[ 8] = grad_chitmp(2,2,0);\n    out_grad_chi[ 9] = grad_chitmp(0,0,1);\n    out_grad_chi[10] = grad_chitmp(0,1,1);\n    out_grad_chi[11] = grad_chitmp(0,2,1);\n    out_grad_chi[12] = grad_chitmp(1,0,1);\n    out_grad_chi[13] = grad_chitmp(1,1,1);\n    out_grad_chi[14] = grad_chitmp(1,2,1);\n    out_grad_chi[15] = grad_chitmp(2,0,1);\n    out_grad_chi[16] = grad_chitmp(2,1,1);\n    out_grad_chi[17] = grad_chitmp(2,2,1);\n    out_grad_chi[18] = grad_chitmp(0,0,2);\n    out_grad_chi[19] = grad_chitmp(0,1,2);\n    out_grad_chi[20] = grad_chitmp(0,2,2);\n    out_grad_chi[21] = grad_chitmp(1,0,2);\n    out_grad_chi[22] = grad_chitmp(1,1,2);\n    out_grad_chi[23] = grad_chitmp(1,2,2);\n    out_grad_chi[24] = grad_chitmp(2,0,2);\n    out_grad_chi[25] = grad_chitmp(2,1,2);\n    out_grad_chi[26] = grad_chitmp(2,2,2);\n        \n    return out_grad_chi;\n}\n\nstd::vector< std::vector< double > > compute_gradient_grad_chi(std::vector< double > U){\n    /*!===================================\n    |    compute_gradient_grad_chi    |\n    ===================================\n    \n    Compute a numeric gradient of the \n    gradient of the micro-displacement \n    tensor with respect to the degree \n    of freedom vector.\n    \n    */\n    \n    //Define a lambda function to parse the deformation gradient\n    \n    finite_difference::FiniteDifference FD(parse_grad_chi,2,U,1e-6);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n}\n\nstd::vector< double > parse_C(std::vector< double > U_in){\n    /*!=================\n    |    parse_C    |\n    =================\n    \n    Parse the computed right Cauchy-Green \n    deformation tensor into a form which \n    can be read by the gradient computation.\n    \n    */\n    \n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1}; //!The reference coordinates.\n    \n    micro_element::Hex8 test_element(reference_coords,U_in,U_in);  //Note: dU is a copy of U. This shouldn't matter.\n    test_element.set_gpt_num(0); //Use the first gauss point\n    test_element.update_shape_function_values();\n    test_element.set_fundamental_measures();                       //Set the fundamental deformation measures\n    test_element.set_deformation_measures();                       //Set the deformation measures\n    tensor::Tensor23 Ctmp = test_element.get_C();\n        \n    //Parse the current value of the deformation gradient\n    std::vector< double > out_C(9,0);\n    out_C[0] = Ctmp(0,0);\n    out_C[1] = Ctmp(0,1);\n    out_C[2] = Ctmp(0,2);\n    out_C[3] = Ctmp(1,0);\n    out_C[4] = Ctmp(1,1);\n    out_C[5] = Ctmp(1,2);\n    out_C[6] = Ctmp(2,0);\n    out_C[7] = Ctmp(2,1);\n    out_C[8] = Ctmp(2,2);\n        \n    return out_C;\n}\n\nstd::vector< std::vector< double > > compute_gradient_C(std::vector< double > U){\n    /*!============================\n    |    compute_gradient_C    |\n    ============================\n    \n    Compute a numeric gradient of the \n    right Cauchy-Green deformation tensor  \n    the degree of freedom vector.\n    \n    */\n    \n    //Define a lambda function to parse the deformation gradient\n    \n    finite_difference::FiniteDifference FD(parse_C,2,U,1e-6);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n}\n\nstd::vector< double > parse_Psi(std::vector< double > U_in){\n    /*!===================\n    |    parse_Psi    |\n    ===================\n    \n    Parse the computed micro-deformation\n    tensor into a form which can be read \n    by the gradient computation.\n    \n    */\n    \n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1}; //!The reference coordinates.\n    \n    micro_element::Hex8 test_element(reference_coords,U_in,U_in);  //Note: dU is a copy of U. This shouldn't matter.\n    test_element.set_gpt_num(0); //Use the first gauss point\n    test_element.update_shape_function_values();\n    test_element.set_fundamental_measures();                       //Set the fundamental deformation measures\n    test_element.set_deformation_measures();                       //Set the deformation measures\n    tensor::Tensor23 Psitmp = test_element.get_Psi();\n        \n    //Parse the current value of the deformation gradient\n    std::vector< double > out_Psi(9,0);\n    out_Psi[0] = Psitmp(0,0);\n    out_Psi[1] = Psitmp(0,1);\n    out_Psi[2] = Psitmp(0,2);\n    out_Psi[3] = Psitmp(1,0);\n    out_Psi[4] = Psitmp(1,1);\n    out_Psi[5] = Psitmp(1,2);\n    out_Psi[6] = Psitmp(2,0);\n    out_Psi[7] = Psitmp(2,1);\n    out_Psi[8] = Psitmp(2,2);\n        \n    return out_Psi;\n}\n\nstd::vector< std::vector< double > > compute_gradient_Psi(std::vector< double > U){\n    /*!==============================\n    |    compute_gradient_Psi    |\n    ==============================\n    \n    Compute a numeric gradient of the \n    micro-deformation tensor with \n    respect to the degree of freedom \n    vector.\n    \n    */\n    \n    //Define a lambda function to parse the deformation gradient\n    \n    finite_difference::FiniteDifference FD(parse_Psi,2,U,1e-6);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n}\n\nstd::vector< double > parse_Gamma(std::vector< double > U_in){\n    /*!=====================\n    |    parse_Gamma    |\n    =====================\n    \n    Parse the computed value of \n    gamma into a form which can \n    be read by the gradient \n    computation.\n    \n    */\n    \n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1}; //!The reference coordinates.\n    \n    micro_element::Hex8 test_element(reference_coords,U_in,U_in);  //Note: dU is a copy of U. This shouldn't matter.\n    test_element.set_gpt_num(0); //Use the first gauss point\n    test_element.update_shape_function_values();\n    test_element.set_fundamental_measures();                       //Set the fundamental deformation measures\n    test_element.set_deformation_measures();                       //Set the deformation measures.\n    tensor::Tensor33 Gamma = test_element.get_Gamma();\n        \n    //Parse the current value of the deformation gradient\n    std::vector< double > out_Gamma(27,0);\n    out_Gamma[ 0] = Gamma(0,0,0);\n    out_Gamma[ 1] = Gamma(0,1,0);\n    out_Gamma[ 2] = Gamma(0,2,0);\n    out_Gamma[ 3] = Gamma(1,0,0);\n    out_Gamma[ 4] = Gamma(1,1,0);\n    out_Gamma[ 5] = Gamma(1,2,0);\n    out_Gamma[ 6] = Gamma(2,0,0);\n    out_Gamma[ 7] = Gamma(2,1,0);\n    out_Gamma[ 8] = Gamma(2,2,0);\n    out_Gamma[ 9] = Gamma(0,0,1);\n    out_Gamma[10] = Gamma(0,1,1);\n    out_Gamma[11] = Gamma(0,2,1);\n    out_Gamma[12] = Gamma(1,0,1);\n    out_Gamma[13] = Gamma(1,1,1);\n    out_Gamma[14] = Gamma(1,2,1);\n    out_Gamma[15] = Gamma(2,0,1);\n    out_Gamma[16] = Gamma(2,1,1);\n    out_Gamma[17] = Gamma(2,2,1);\n    out_Gamma[18] = Gamma(0,0,2);\n    out_Gamma[19] = Gamma(0,1,2);\n    out_Gamma[20] = Gamma(0,2,2);\n    out_Gamma[21] = Gamma(1,0,2);\n    out_Gamma[22] = Gamma(1,1,2);\n    out_Gamma[23] = Gamma(1,2,2);\n    out_Gamma[24] = Gamma(2,0,2);\n    out_Gamma[25] = Gamma(2,1,2);\n    out_Gamma[26] = Gamma(2,2,2);\n        \n    return out_Gamma;\n}\n\nstd::vector< std::vector< double > > compute_gradient_Gamma(std::vector< double > U){\n    /*!================================\n    |    compute_gradient_Gamma    |\n    ================================\n    \n    Compute a numeric gradient of the \n    gradient of Gamma with respect to \n    the degree of freedom vector.\n    \n    */\n    \n    finite_difference::FiniteDifference FD(parse_Gamma,2,U,1e-6);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n}\n\nstd::vector< double > parse_PK2(std::vector< double > U_in){\n    /*!===================\n    |    parse_PK2    |\n    ===================\n    \n    Parse the computed second Piola-Kirchhoff \n    stress tensor into a form which can be \n    read by the gradient computation.\n    \n    */\n    \n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1}; //!The reference coordinates.\n    \n    //!Initialize the floating point parameters\n    std::vector< double > fparams(19,0.);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    micro_element::Hex8 test_element = micro_element::Hex8(reference_coords,U_in,U_in,fparams);  //Note: dU is a copy of U. This shouldn't matter.\n    test_element.set_gpt_num(0); //Use the first gauss point\n    test_element.update_shape_function_values();\n    test_element.set_fundamental_measures();                       //Set the fundamental deformation measures\n    test_element.set_deformation_measures();                       //Set the deformation measures\n    test_element.set_stresses();                                   //Set the stress measures\n    tensor::Tensor23 PK2tmp = test_element.PK2[0];                 //Using first gauss point\n        \n    //Parse the current value of the deformation gradient\n    std::vector< double > out_PK2(9,0);\n    out_PK2[0] = PK2tmp(0,0);\n    out_PK2[1] = PK2tmp(0,1);\n    out_PK2[2] = PK2tmp(0,2);\n    out_PK2[3] = PK2tmp(1,0);\n    out_PK2[4] = PK2tmp(1,1);\n    out_PK2[5] = PK2tmp(1,2);\n    out_PK2[6] = PK2tmp(2,0);\n    out_PK2[7] = PK2tmp(2,1);\n    out_PK2[8] = PK2tmp(2,2);\n        \n    return out_PK2;\n}\n\nstd::vector< std::vector< double > > compute_gradient_PK2(std::vector< double > U){\n    /*!==============================\n    |    compute_gradient_PK2    |\n    ==============================\n    \n    Compute the numeric gradient of the \n    second Piola-Kirchhoff stress tensor \n    with respect to the degree of \n    freedom vector.\n    \n    */\n    \n    finite_difference::FiniteDifference FD(parse_PK2,2,U,1e-6);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n}\n\nstd::vector< double > parse_SIGMA(std::vector< double > U_in){\n    /*!=====================\n    |    parse_SIGMA    |\n    =====================\n    \n    Parse the computed symmetric \n    stress tensor into a form which can be \n    read by the gradient computation.\n    \n    */\n    \n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1}; //!The reference coordinates.\n    \n    //!Initialize the floating point parameters\n    std::vector< double > fparams(19,0.);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    micro_element::Hex8 test_element = micro_element::Hex8(reference_coords,U_in,U_in,fparams);  //Note: dU is a copy of U. This shouldn't matter.\n    test_element.set_gpt_num(0); //Use the first gauss point\n    test_element.update_shape_function_values();\n    test_element.set_fundamental_measures();                       //Set the fundamental deformation measures\n    test_element.set_deformation_measures();                       //Set the deformation measures\n    test_element.set_stresses();                                   //Set the stress measures\n    tensor::Tensor23 SIGMAtmp = test_element.SIGMA[0];             //Using first gauss point\n        \n    //Parse the current value of the deformation gradient\n    std::vector< double > out_SIGMA(9,0);\n    out_SIGMA[0] = SIGMAtmp(0,0);\n    out_SIGMA[1] = SIGMAtmp(0,1);\n    out_SIGMA[2] = SIGMAtmp(0,2);\n    out_SIGMA[3] = SIGMAtmp(1,0);\n    out_SIGMA[4] = SIGMAtmp(1,1);\n    out_SIGMA[5] = SIGMAtmp(1,2);\n    out_SIGMA[6] = SIGMAtmp(2,0);\n    out_SIGMA[7] = SIGMAtmp(2,1);\n    out_SIGMA[8] = SIGMAtmp(2,2);\n        \n    return out_SIGMA;\n}\n\nstd::vector< std::vector< double > > compute_gradient_SIGMA(std::vector< double > U){\n    /*!================================\n    |    compute_gradient_SIGMA    |\n    ================================\n    \n    Compute the numeric gradient of the \n    symmetric stress tensor \n    with respect to the degree of \n    freedom vector.\n    \n    */\n    \n    finite_difference::FiniteDifference FD(parse_SIGMA,2,U,1e-6);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n}\n\nstd::vector< double > parse_M(std::vector< double > U_in){\n    /*!=================\n    |    parse_M    |\n    =================\n    \n    Parse the higher order  \n    stress tensor into a form which can be \n    read by the gradient computation.\n    \n    */\n    \n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1}; //!The reference coordinates.\n    \n    //!Initialize the floating point parameters\n    std::vector< double > fparams(19,0.);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    micro_element::Hex8 test_element = micro_element::Hex8(reference_coords,U_in,U_in,fparams);  //Note: dU is a copy of U. This shouldn't matter.\n    test_element.set_gpt_num(0); //Use the first gauss point\n    test_element.update_shape_function_values();\n    test_element.set_fundamental_measures();                       //Set the fundamental deformation measures\n    test_element.set_deformation_measures();                       //Set the deformation measures\n    test_element.set_stresses();                                   //Set the stress measures\n    tensor::Tensor33 Mtmp = test_element.M[0];                     //Using first gauss point\n        \n    //Parse the current value of the deformation gradient\n    std::vector< double > out_M(27,0);\n    out_M[ 0] = Mtmp(0,0,0);\n    out_M[ 1] = Mtmp(0,1,0);\n    out_M[ 2] = Mtmp(0,2,0);\n    out_M[ 3] = Mtmp(1,0,0);\n    out_M[ 4] = Mtmp(1,1,0);\n    out_M[ 5] = Mtmp(1,2,0);\n    out_M[ 6] = Mtmp(2,0,0);\n    out_M[ 7] = Mtmp(2,1,0);\n    out_M[ 8] = Mtmp(2,2,0);\n    out_M[ 9] = Mtmp(0,0,1);\n    out_M[10] = Mtmp(0,1,1);\n    out_M[11] = Mtmp(0,2,1);\n    out_M[12] = Mtmp(1,0,1);\n    out_M[13] = Mtmp(1,1,1);\n    out_M[14] = Mtmp(1,2,1);\n    out_M[15] = Mtmp(2,0,1);\n    out_M[16] = Mtmp(2,1,1);\n    out_M[17] = Mtmp(2,2,1);\n    out_M[18] = Mtmp(0,0,2);\n    out_M[19] = Mtmp(0,1,2);\n    out_M[20] = Mtmp(0,2,2);\n    out_M[21] = Mtmp(1,0,2);\n    out_M[22] = Mtmp(1,1,2);\n    out_M[23] = Mtmp(1,2,2);\n    out_M[24] = Mtmp(2,0,2);\n    out_M[25] = Mtmp(2,1,2);\n    out_M[26] = Mtmp(2,2,2);\n        \n    return out_M;\n}\n\nstd::vector< std::vector< double > > compute_gradient_M(std::vector< double > U){\n    /*!============================\n    |    compute_gradient_M    |\n    ============================\n    \n    Compute the numeric gradient of the \n    higher order stress tensor \n    with respect to the degree of \n    freedom vector.\n    \n    */\n    \n    finite_difference::FiniteDifference FD(parse_M,2,U,1e-6);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n}\n\n//extern double test_temp1 = 0;\n//extern double test_temp2 = 0;\n\nstd::vector< double > parse_Fint(std::vector< double > U_in){\n    /*!====================\n    |    parse_Fint    |\n    ====================\n    \n    Parse the internal force vector \n    for gradient calculation.\n    \n    */\n    \n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1}; //!The reference coordinates.\n    \n    //!Initialize the floating point parameters\n    std::vector< double > fparams(19,0.);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    //print_vector(\"U_in:\",U_in);\n    \n    micro_element::Hex8 test_element = micro_element::Hex8(reference_coords,U_in,U_in,fparams);  //Note: dU is a copy of U. This shouldn't matter.\n    test_element.set_gpt_num(0);                                                                 //Use the first gauss point\n    test_element.update_gauss_point();\n    \n    test_element.add_internal_nodal_forces();                                                    //Add the internal nodal forces to the RHS vector\n    \n    std::vector< double > out(96,0.);\n    for(int i=0; i<96; i++){out[i] = test_element.RHS(i);}\n    \n    //print_vector(\"out\",out);\n    \n    //if(fabs(test_temp1)<1e-9){test_temp1=out[0];}\n    //else{\n    //    test_temp2=out[0];\n    \n    //if(fabs(test_temp1)<1e-9){test_temp1=test_element.get_Jhatdet(0);}\n    //else{\n    //    test_temp2 = test_element.get_Jhatdet(0);\n    //    std::cout << \"test_temp1: \" << test_temp1 << \"\\n\";\n    //    std::cout << \"test_temp2: \" << test_temp2 << \"\\n\";\n    //    std::cout << test_temp2 - test_temp1 << \"\\n\";\n    //    std::cout << \"dJhatdetdU: \" << (test_temp2-test_temp1)/(2.*1e-7) << \"\\n\";\n    //    \n    //    test_temp1 = 0.;\n    //    test_temp2 = 0.;\n    //}\n    \n    return out;\n}\n\nstd::vector< std::vector< double > > compute_gradient_Fint(std::vector< double > U){\n    /*!===============================\n    |    compute_gradient_Fint    |\n    ===============================\n    \n    Compute the numeric gradient of the \n    forces with respect to the degree \n    of freedom vector.\n    \n    */\n    \n    finite_difference::FiniteDifference FD(parse_Fint,2,U,1e-7);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n}\n\nstd::vector< double > parse_Mint(std::vector< double > U_in){\n    /*!====================\n    |    parse_Mint    |\n    ====================\n    \n    Parse the internal force vector \n    for gradient calculation.\n    \n    */\n    \n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1}; //!The reference coordinates.\n    \n    //!Initialize the floating point parameters\n    std::vector< double > fparams(19,0.);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    //print_vector(\"U_in:\",U_in);\n    \n    micro_element::Hex8 test_element = micro_element::Hex8(reference_coords,U_in,U_in,fparams);  //Note: dU is a copy of U. This shouldn't matter.\n    test_element.set_gpt_num(0);                                                                 //Use the first gauss point\n    test_element.update_gauss_point();\n    \n    test_element.add_internal_moments();                                                    //Add the internal nodal forces to the RHS vector\n    \n    std::vector< double > out(96,0.);\n    for(int i=0; i<96; i++){out[i] = test_element.RHS(i);}\n    \n    //print_vector(\"out\",out);\n    \n    //if(fabs(test_temp1)<1e-9){test_temp1=out[0];}\n    //else{\n    //    test_temp2=out[0];\n    \n    //if(fabs(test_temp1)<1e-9){test_temp1=test_element.get_Jhatdet(0);}\n    //else{\n    //    test_temp2 = test_element.get_Jhatdet(0);\n    //    std::cout << \"test_temp1: \" << test_temp1 << \"\\n\";\n    //    std::cout << \"test_temp2: \" << test_temp2 << \"\\n\";\n    //    std::cout << test_temp2 - test_temp1 << \"\\n\";\n    //    std::cout << \"dJhatdetdU: \" << (test_temp2-test_temp1)/(2.*1e-7) << \"\\n\";\n    //    \n    //    test_temp1 = 0.;\n    //    test_temp2 = 0.;\n    //}\n    \n    return out;\n}\n\nstd::vector< std::vector< double > > compute_gradient_Mint(std::vector< double > U){\n    /*!===============================\n    |    compute_gradient_Mint    |\n    ===============================\n    \n    Compute the numeric gradient of the \n    internal term in the balance of first \n    moment of momentum.\n    \n    */\n    \n    finite_difference::FiniteDifference FD(parse_Mint,2,U,1e-7);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n}\n\nstd::vector< double > parse_RHS(std::vector< double > U_in){\n    /*!===================\n    |    parse_RHS    |\n    ===================\n    \n    Parse the right hand side \n    vector for the gradient \n    calculation.\n    \n    */\n    \n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1}; //!The reference coordinates.\n    \n    //!Initialize the floating point parameters\n    std::vector< double > fparams(19,0.);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    //print_vector(\"U_in:\",U_in);\n    \n    micro_element::Hex8 test_element = micro_element::Hex8(reference_coords,U_in,U_in,fparams);  //Note: dU is a copy of U. This shouldn't matter.\n    test_element.integrate_element();                                                            //Integrate the element\n    \n    std::vector< double > out(96,0.);\n    for(int i=0; i<96; i++){out[i] = test_element.RHS(i);}\n    \n    //print_vector(\"out\",out);\n    \n    //if(fabs(test_temp1)<1e-9){test_temp1=out[0];}\n    //else{\n    //    test_temp2=out[0];\n    \n    //if(fabs(test_temp1)<1e-9){test_temp1=test_element.get_Jhatdet(0);}\n    //else{\n    //    test_temp2 = test_element.get_Jhatdet(0);\n    //    std::cout << \"test_temp1: \" << test_temp1 << \"\\n\";\n    //    std::cout << \"test_temp2: \" << test_temp2 << \"\\n\";\n    //    std::cout << test_temp2 - test_temp1 << \"\\n\";\n    //    std::cout << \"dJhatdetdU: \" << (test_temp2-test_temp1)/(2.*1e-7) << \"\\n\";\n    //    \n    //    test_temp1 = 0.;\n    //    test_temp2 = 0.;\n    //}\n    \n    return out;\n}\n\nstd::vector< std::vector< double > > compute_gradient_element(std::vector< double > U){\n    /*!==================================\n    |    compute_gradient_element    |\n    ==================================\n    \n    Compute the numeric gradient of the \n    element with respect to the degree \n    of freedom vector.\n    \n    */\n    \n    finite_difference::FiniteDifference FD(parse_RHS,2,U,1e-7);\n    std::vector< std::vector< double > > gradient = FD.numeric_gradient();\n    return gradient;\n}\n\n    \nint test_fundamental_measures(std::ofstream &results){\n    /*!===================================\n    |    test_fundamental_measures    |\n    ===================================\n    \n    Run tests on the fundamental deformation measures\n    and related methods to ensure they are functioning \n    properly\n    \n    */\n    \n    //Seed the random number generator\n    srand (1);\n    \n    //!Initialize test results\n    int  test_num        = 6;\n    std::vector<bool> test_results(test_num,false);\n    \n    //!Form the required vectors for element formation\n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1};\n    std::vector< double > Unode;\n    std::vector< double > Xnode;\n    std::vector< double > U;\n    std::vector< double > dU;\n    Xnode.resize(3);\n    Unode.resize(96);\n    U.resize(96);\n    dU.resize(96);\n    int inc = 0;\n    for(int n=0; n<8; n++){\n        Xnode[0] = reference_coords[0+n*3]; //Get the position of the current node\n        Xnode[1] = reference_coords[1+n*3];\n        Xnode[2] = reference_coords[2+n*3];\n        \n        Unode = test_deformation(Xnode);    //Update the deformation\n        \n        for(int i=0; i<12; i++){\n            U[inc]  = Unode[i];   //Assign the deformation\n            dU[inc] = 0.1*Unode[i];  //Assign the change in deformation (1/10 of the deformation)\n            inc++;\n        }\n    }\n    \n    //!Form the hexehedral test element.\n    micro_element::Hex8 element = micro_element::Hex8(reference_coords,U,dU);\n    \n    //!Set the gauss point\n    element.set_gpt_num(0); //Use the first gauss point since the gradients should be constant\n    \n    //!Compute the shape function values\n    element.update_shape_function_values();\n    \n    //!Set the fundamental deformation measures\n    element.set_fundamental_measures();\n    \n    //!Compare the computed values to the expected result\n    tensor::Tensor23 F_answer({3,3});\n    tensor::Tensor23 chi_answer({3,3});\n    tensor::Tensor33 grad_chi_answer({3,3,3});\n    \n    //!Populate the expected gradients\n    std::vector< std::vector< double > > gradients = compute_gradients(element.points[0]); //Compute the numeric gradients\n    \n    for(int i=0; i<3; i++){\n        //!Populate the deformation gradient\n        F_answer(0,i)          = gradients[i][ 0];\n        F_answer(1,i)          = gradients[i][ 1];\n        F_answer(2,i)          = gradients[i][ 2];\n        //!Populate the gradient of chi\n        grad_chi_answer(0,0,i) = gradients[i][ 3];\n        grad_chi_answer(1,1,i) = gradients[i][ 4];\n        grad_chi_answer(2,2,i) = gradients[i][ 5];\n        grad_chi_answer(1,2,i) = gradients[i][ 6];\n        grad_chi_answer(0,2,i) = gradients[i][ 7];\n        grad_chi_answer(0,1,i) = gradients[i][ 8];\n        grad_chi_answer(2,1,i) = gradients[i][ 9];\n        grad_chi_answer(2,0,i) = gradients[i][10];\n        grad_chi_answer(1,0,i) = gradients[i][11];\n    }\n    \n    //Because we are specifying the deformation, and \n    //not the actual current coordinates, we have to \n    //add 1 to the diagonal terms\n    F_answer(0,0) += 1;\n    F_answer(1,1) += 1;\n    F_answer(2,2) += 1;\n    \n    //!Populate the expected chi\n    chi_answer(0,0) = 1.;\n    chi_answer(1,1) = 1.;\n    chi_answer(2,2) = 1.;\n    for(int n=0; n<8; n++){\n        for(int i=0; i<3; i++){\n            for(int j=0; j<3; j++){\n                chi_answer(i,j) += element.get_N(n)*element.node_phis[n](i,j);\n            }\n        }\n    }\n    \n    test_results[0] = F_answer.data.isApprox(element.get_F().data,1e-9);\n    test_results[1] = chi_answer.data.isApprox(element.get_chi().data);\n    test_results[2] = grad_chi_answer.data.isApprox(element.get_grad_chi().data,1e-9);\n    \n    //!Compare tangents\n    element.set_fundamental_tangents(); //Compute the tangents for the element\n    \n    //!Compare the deformation gradient tangent\n    std::vector< std::vector< double > > gradient = compute_gradient_F(U);\n    \n    //Compare the numeric and analytic tangents\n    test_results[3] = true;\n    \n    tensor::BaseTensor<3,288> dFdU_result = element.get_dFdU();\n    \n    //std::cout << \"dFdU:\\n\" << dFdU_result.data << \"\\n\";\n    \n    for(int K=0; K<96; K++){\n        \n        for(int I=0; I<3; I++){\n            for(int J=0; J<3; J++){\n                test_results[3] = test_results[3] * (1e-9>fabs(gradient[K][3*I+J] - dFdU_result(I,J,K)));\n                //std::cout << \"answer: \" << gradient[K][3*I+J] << \"\\nresult: \" << dFdU_result(I,J,K) << \"\\n\";\n                if(!test_results[3]){break;}\n            }\n            if(!test_results[3]){break;}\n        }\n        if(!test_results[3]){break;}\n    }\n    \n    //!Compare the micro-displacement tangent\n    gradient = compute_gradient_chi(U);\n    \n    //print_vector_of_vectors(\"gradient\",gradient);\n    \n    test_results[4] = true;\n    \n    tensor::BaseTensor<3,288> dchidU_result = element.get_dchidU();\n    \n    //std::cout << \"dchidU:\\n\" << dchidU_result.data << \"\\n\";\n    \n    for(int K=0; K<96; K++){\n        \n        for(int I=0; I<3; I++){\n            for(int J=0; J<3; J++){\n                test_results[4] = test_results[4] * (1e-9>fabs(gradient[K][3*I+J] - dchidU_result(I,J,K)));\n                //std::cout << \"answer: \" << gradient[K][3*I+J] << \"\\nresult: \" << dchidU_result(I,J,K) << \"\\n\";\n                if(!test_results[4]){break;}\n            }\n            if(!test_results[4]){break;}\n        }\n        if(!test_results[4]){break;}\n    }\n    \n    //!Compare the micro-displacement gradient tangent\n    gradient = compute_gradient_grad_chi(U);\n    \n    //print_vector_of_vectors(\"gradient\",gradient);\n    \n    test_results[5] = true;\n    \n    tensor::BaseTensor<9,288> dgrad_chidU_result = element.get_dgrad_chidU();\n    \n    //std::cout << \"dgrad_chidU_result:\\n\" << dgrad_chidU_result.data << \"\\n\";\n    \n    for(int I=0; I<3; I++){\n        for(int J=0; J<3; J++){\n            for(int K=0; K<3; K++){\n                for(int L=0; L<96; L++){\n                    test_results[5] = test_results[5] * (1e-8>fabs(gradient[L][9*K+3*I+J] - dgrad_chidU_result(I,J,K,L)));\n                    //std::cout << \"answer: \" << gradient[L][9*K+3*I+J] << \"\\nresult: \" << dgrad_chidU_result(I,J,K,L) << \"\\ndiff: \" << fabs(gradient[L][9*K+3*I+J] - dgrad_chidU_result(I,J,K,L)) << \"\\n\";\n                    if(!test_results[5]){break;}\n                }\n                if(!test_results[5]){break;}\n            }\n            if(!test_results[5]){break;}\n        }\n        if(!test_results[5]){break;}\n    }\n    \n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_fundamental_measures & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_fundamental_measures & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return 1;\n    \n}\n\nint test_deformation_measures(std::ofstream &results){\n    /*!===================================\n    |    test_deformation_measures    |\n    ===================================\n    \n    Run tests on the deformation measures and \n    related methods to ensure they are functioning \n    properly\n    \n    */\n    \n    //Seed the random number generator\n    srand (1);\n    \n    //!Initialize test results\n    int  test_num        = 6;\n    std::vector<bool> test_results(test_num,false);\n    \n    //!Initialize the floating point parameters\n    std::vector< double > fparams(19,0.);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    //!Form the required vectors for element formation\n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1};\n    std::vector< double > Unode;\n    std::vector< double > Xnode;\n    std::vector< double > U;\n    std::vector< double > dU;\n    Xnode.resize(3);\n    Unode.resize(96);\n    U.resize(96);\n    dU.resize(96);\n    int inc = 0;\n    for(int n=0; n<8; n++){\n        Xnode[0] = reference_coords[0+n*3]; //Get the position of the current node\n        Xnode[1] = reference_coords[1+n*3];\n        Xnode[2] = reference_coords[2+n*3];\n        \n        Unode = test_deformation(Xnode);    //Update the deformation\n        \n        for(int i=0; i<12; i++){\n            U[inc]  = Unode[i];   //Assign the deformation\n            dU[inc] = 0.1*Unode[i];  //Assign the change in deformation (1/10 of the deformation)\n            inc++;\n        }\n    }\n    \n    //!Form the hexehedral test element.\n    micro_element::Hex8 element = micro_element::Hex8(reference_coords,U,dU,fparams);\n    \n    //!Set the gauss point\n    element.set_gpt_num(0); //Use the first gauss point since the gradients should be constant\n    \n    //!Compute the shape function values\n    element.update_shape_function_values();\n    \n    //!Set the fundamental deformation measures\n    element.set_fundamental_measures();\n    \n    //!Set the deformation measures\n    element.set_deformation_measures();\n    \n    //!Compare the computed values to the expected result\n    tensor::Tensor23 C_answer({3,3});\n    tensor::Tensor23 Psi_answer({3,3});\n    tensor::Tensor33 Gamma_answer({3,3,3});\n    \n    for(int I=0; I<3; I++){\n        for(int J=0; J<3; J++){\n            \n            for(int i=0; i<3; i++){\n                C_answer(I,J)   += element.get_F()(i,I)*element.get_F()(i,J);\n                Psi_answer(I,J) += element.get_F()(i,I)*element.get_chi()(i,J);\n            }\n            \n        }\n    }\n    \n    for(int I=0; I<3; I++){\n        for(int J=0; J<3; J++){\n            for(int K=0; K<3; K++){\n                for(int i=0; i<3; i++){\n                    Gamma_answer(I,J,K)   += element.get_F()(i,I)*element.get_grad_chi()(i,J,K);\n                }\n            }            \n        }\n    }\n    \n    test_results[0] = C_answer.data.isApprox(element.get_C().data);\n    test_results[1] = Psi_answer.data.isApprox(element.get_Psi().data);\n    test_results[2] = Gamma_answer.data.isApprox(element.get_Gamma().data);\n    \n    //!Compare tangents\n    \n    element.set_fundamental_tangents();\n    element.set_deformation_tangents();\n    \n    //!Compare the deformation gradient tangent\n    std::vector< std::vector< double > > gradient = compute_gradient_C(U);\n    \n    //print_vector_of_vectors(\"gradient\",gradient);\n    \n    //Compare the numeric and analytic tangents\n    test_results[3] = true;\n    \n    tensor::BaseTensor<3,288> dCdU_result = element.get_dCdU();\n    \n    //std::cout << \"dCdU:\\n\" << dCdU_result.data << \"\\n\";\n    \n    for(int K=0; K<96; K++){\n        \n        for(int I=0; I<3; I++){\n            for(int J=0; J<3; J++){\n                test_results[3] = test_results[3] * (1e-9>fabs(gradient[K][3*I+J] - dCdU_result(I,J,K)));\n                //std::cout << \"answer: \" << gradient[K][3*I+J] << \"\\nresult: \" << dFdU_result(I,J,K) << \"\\n\";\n                if(!test_results[3]){break;}\n            }\n            if(!test_results[3]){break;}\n        }\n        if(!test_results[3]){break;}\n    }\n    \n    //!Compare the micro-deformation tangent\n    gradient = compute_gradient_Psi(U);\n    \n    //print_vector_of_vectors(\"gradient\",gradient);\n    \n    test_results[4] = true;\n    \n    tensor::BaseTensor<3,288> dPsidU_result = element.get_dPsidU();\n    \n    //std::cout << \"dPsidU:\\n\" << dPsidU_result.data << \"\\n\";\n    \n    for(int K=0; K<96; K++){\n        \n        for(int I=0; I<3; I++){\n            for(int J=0; J<3; J++){\n                test_results[4] = test_results[4] * (1e-9>fabs(gradient[K][3*I+J] - dPsidU_result(I,J,K)));\n                //std::cout << \"answer: \" << gradient[K][3*I+J] << \"\\nresult: \" << dchidU_result(I,J,K) << \"\\n\";\n                if(!test_results[4]){break;}\n            }\n            if(!test_results[4]){break;}\n        }\n        if(!test_results[4]){break;}\n    }\n    \n    //!Compare the gradient of Gamma tangent\n    gradient = compute_gradient_Gamma(U);\n    \n    //print_vector_of_vectors(\"gradient\",gradient);\n    \n    test_results[5] = true;\n    \n    tensor::BaseTensor<9,288> dGammadU_result = element.get_dGammadU();\n    \n    //std::cout << \"dGammadU_result:\\n\" << dGammadU_result.data << \"\\n\";\n    \n    for(int I=0; I<3; I++){\n        for(int J=0; J<3; J++){\n            for(int K=0; K<3; K++){\n                for(int L=0; L<96; L++){\n                    test_results[5] = test_results[5] * (1e-8>fabs(gradient[L][9*K+3*I+J] - dGammadU_result(I,J,K,L)));\n                    //std::cout << \"answer: \" << gradient[L][9*K+3*I+J] << \"\\nresult: \" << dGammadU_result(I,J,K,L) << \"\\n\";\n                    //std::cout << I << J << K << L << \"\\n\";\n                    if(!test_results[5]){break;}\n                }\n                if(!test_results[5]){break;}\n            }\n            if(!test_results[5]){break;}\n        }\n        if(!test_results[5]){break;}\n    }\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_deformation_measures & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_deformation_measures & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return 1;\n}\n\nint test_stress_tangents(std::ofstream &results){\n    /*!==============================\n    |    test_stress_tangents    |\n    ==============================\n    \n    Run tests of the tangents of the stress \n    measures with respect to the degree of \n    freedom vector.\n    \n    */\n    \n    //Seed the random number generator\n    srand (1);\n    \n    //!Initialize test results\n    int  test_num        = 3;\n    std::vector<bool> test_results(test_num,false);\n    \n    //!Initialize the floating point parameters\n    std::vector< double > fparams(19,0.);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    //!Form the required vectors for element formation\n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1};\n    std::vector< double > Unode;\n    std::vector< double > Xnode;\n    std::vector< double > U;\n    std::vector< double > dU;\n    Xnode.resize(3);\n    Unode.resize(96);\n    U.resize(96);\n    dU.resize(96);\n    int inc = 0;\n    for(int n=0; n<8; n++){\n        Xnode[0] = reference_coords[0+n*3]; //Get the position of the current node\n        Xnode[1] = reference_coords[1+n*3];\n        Xnode[2] = reference_coords[2+n*3];\n        \n        Unode = test_deformation(Xnode);    //Update the deformation\n        \n        for(int i=0; i<12; i++){\n            U[inc]  = Unode[i];   //Assign the deformation\n            dU[inc] = 0.1*Unode[i];  //Assign the change in deformation (1/10 of the deformation)\n            inc++;\n        }\n    }\n    \n    //!Form the hexehedral test element.\n    micro_element::Hex8 element = micro_element::Hex8(reference_coords,U,dU,fparams);\n    \n    //!Set the gauss point\n    element.set_gpt_num(0); //Use the first gauss point since the gradients should be constant\n    \n    //!Compute the shape function values\n    element.update_shape_function_values();\n    \n    //!Set the fundamental deformation measures\n    element.set_fundamental_measures();\n    \n    //!Set the deformation measures\n    element.set_deformation_measures();\n    \n    //!Set the deformation tangents\n    element.set_fundamental_tangents();\n    element.set_deformation_tangents();\n    \n    //!Set the stresses at the gauss point\n    element.set_stresses(true);\n    \n    //!Set the stress tangents\n    element.set_stress_tangents();\n    \n    //!Compare the PK2 tangent\n    std::vector< std::vector< double > > gradient = compute_gradient_PK2(U);\n    \n    //Compare the numeric and analytic tangents\n    test_results[0] = true;\n    \n    tensor::BaseTensor<3,288> dPK2dU_result = element.get_dPK2dU();\n    //std::cout << \"dPK2dU checked:\\n\" << dPK2dU_result.data << \"\\n\";\n    \n    for(int K=0; K<96; K++){\n        \n        for(int I=0; I<3; I++){\n            for(int J=0; J<3; J++){\n                test_results[0] = test_results[0] * (double_compare(gradient[K][3*I+J],dPK2dU_result(I,J,K)));\n                //std::cout << \"answer: \" << gradient[K][3*I+J] << \"\\nresult: \" << dPK2dU_result(I,J,K) << \"\\n\";\n                if(!test_results[0]){break;}\n            }\n            if(!test_results[0]){break;}\n        }\n        if(!test_results[0]){break;}\n    }\n    \n    //!Compare the SIGMA tangent\n    gradient = compute_gradient_SIGMA(U);\n    \n    //Compare the numeric and analytic tangents\n    test_results[1] = true;\n    \n    tensor::BaseTensor<3,288> dSIGMAdU_result = element.get_dSIGMAdU();\n    \n    for(int K=0; K<96; K++){\n        \n        for(int I=0; I<3; I++){\n            for(int J=0; J<3; J++){\n                test_results[2] = test_results[2] * (double_compare(gradient[K][3*I+J],dSIGMAdU_result(I,J,K)));\n                //std::cout << \"answer: \" << gradient[K][3*I+J] << \"\\nresult: \" << dPK2dU_result(I,J,K) << \"\\n\";\n                if(!test_results[1]){break;}\n            }\n            if(!test_results[1]){break;}\n        }\n        if(!test_results[1]){break;}\n    }\n    \n    //!Compare the gradient of higher order stress\n    gradient = compute_gradient_M(U);\n    \n    //print_vector_of_vectors(\"gradient\",gradient);\n    \n    test_results[2] = true;\n    \n    tensor::BaseTensor<9,288> dMdU_result = element.get_dMdU();\n    \n    //std::cout << \"dMdU_result:\\n\" << dMdU_result.data << \"\\n\";\n    \n    for(int I=0; I<3; I++){\n        for(int J=0; J<3; J++){\n            for(int K=0; K<3; K++){\n                for(int L=0; L<96; L++){\n                    test_results[2] = test_results[2] * (double_compare(gradient[L][9*K+3*I+J],dMdU_result(I,J,K,L)));\n                    //std::cout << \"answer: \" << gradient[L][9*K+3*I+J] << \"\\nresult: \" << dMdU_result(I,J,K,L) << \"\\n\";\n                    //std::cout << I << J << K << L << \"\\n\";\n                    if(!test_results[2]){break;}\n                }\n                if(!test_results[2]){break;}\n            }\n            if(!test_results[2]){break;}\n        }\n        if(!test_results[2]){break;}\n    }\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_stress_tangents & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_stress_tangents & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return 1;\n}\n\nint test_balance_of_linear_momentum(std::ofstream &results){\n    /*!=========================================\n    |    test_balance_of_linear_momentum    |\n    =========================================\n    \n    Run tests on the formation of the residual of the \n    balance of linear momentum.\n    \n    */\n    \n    //Seed the random number generator\n    srand (1);\n    \n    //!Initialize test results\n    int  test_num        = 2;\n    std::vector<bool> test_results(test_num,false);\n    \n    //!Initialize the floating point parameters\n    std::vector< double > fparams(19,0.);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    //!Form the required vectors for element formation\n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1};\n    std::vector< double > Unode;\n    std::vector< double > Xnode;\n    std::vector< double > U;\n    std::vector< double > dU;\n    Xnode.resize(3);\n    Unode.resize(96);\n    U.resize(96);\n    dU.resize(96);\n    int inc = 0;\n    for(int n=0; n<8; n++){\n        Xnode[0] = reference_coords[0+n*3]; //Get the position of the current node\n        Xnode[1] = reference_coords[1+n*3];\n        Xnode[2] = reference_coords[2+n*3];\n        \n        Unode = test_deformation(Xnode);    //Update the deformation\n        \n        for(int i=0; i<12; i++){\n            U[inc]  = Unode[i];   //Assign the deformation\n            dU[inc] = 0.1*Unode[i];  //Assign the change in deformation (1/10 of the deformation)\n            inc++;\n        }\n    }\n    \n    //!Form the hexehedral test element.\n    micro_element::Hex8 element = micro_element::Hex8(reference_coords,U,dU,fparams);\n    \n    //!Set the gauss point\n    element.set_gpt_num(0); //Use the first gauss point since the gradients should be constant\n    element.update_gauss_point(true); //!Update the values for the gauss point\n/*    //!Compute the shape function values\n    element.update_shape_function_values();\n    \n    //!Set the fundamental deformation measures\n    element.set_fundamental_measures();\n    \n    //!Set the deformation measures\n    element.set_deformation_measures();\n    \n    //!Set the deformation tangents\n    element.set_fundamental_tangents();\n    element.set_deformation_tangents();\n    \n    //!Set the stresses at the gauss point\n    element.set_stresses(true);\n    \n    //!Set the stress tangents\n    element.set_stress_tangents();*/\n    \n    //!Set the residual vector due to the given gauss point\n    element.add_internal_nodal_forces();\n    \n    //!Compute the expected residual vector\n    std::vector< double > RHS(96,0.);\n    \n    //!Compute the internal forces\n    for(int n=0; n<8; n++){\n        for(int j=0; j<3; j++){\n            for(int I=0; I<3; I++){\n                for(int J=0; J<3; J++){\n                    RHS[j+12*n] += -element.get_dNdx(0,n)[I]*element.PK2[0](I,J)*element.get_F()(j,J)*element.get_Jhatdet(0)*element.weights[0];\n                }\n            }\n        }\n    }\n    \n    //!Compare the expected results to the element results\n    test_results[0] = true;\n    for(int i=0; i<96; i++){\n        test_results[0] = test_results[0] * (1e-9>fabs(element.RHS(i)-RHS[i]));\n    }\n    \n    //!Compare the tangents\n    \n    element.add_dFintdU();\n    \n    std::vector< std::vector< double > > gradient = compute_gradient_Fint(U);\n    \n    //print_vector_of_vectors(\"gradient\",gradient);\n    //print_vector_of_vectors(\"AMATRX\",element.AMATRX);\n    \n    test_results[1]=true;\n    for(int i=95; i>=0; i--){\n        for(int j=95; j>=0; j--){\n            test_results[1] = test_results[1] * (double_compare(gradient[i][j],element.AMATRX(j,i),1e-5,1e-5));\n            //std::cout << \"(\" << i << \", \" << j << \")\\n\";\n            //std::cout << \"answer: \" << gradient[i][j] << \"\\nresult: \" << element.AMATRX[j][i] << \"\\ndiff: \" << gradient[i][j]-element.AMATRX[j][i] <<\"\\n\";\n            if(!test_results[1]){break;}\n        }\n        if(!test_results[1]){break;}\n    }\n    \n    \n    \n    \n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_balance_of_linear_momentum & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_balance_of_linear_momentum & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return 1;\n}\n\nint test_mass_matrix(std::ofstream &results){\n    /*!==========================\n    |    test_mass_matrix    |\n    ==========================\n    \n    Run tests on the formation of the mass \n    matrix.\n    \n    */\n    \n    //Seed the random number generator\n    srand (1);\n    \n    //!Initialize test results\n    int  test_num        = 2;\n    std::vector<bool> test_results(test_num,false);\n    \n    //!Initialize the floating point parameters\n    std::vector< double > fparams(19,0.);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    //!Form the required vectors for element formation\n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1};\n    std::vector< double > Unode;\n    std::vector< double > Xnode;\n    std::vector< double > U;\n    std::vector< double > dU;\n    Xnode.resize(3);\n    Unode.resize(96);\n    U.resize(96);\n    dU.resize(96);\n    int inc = 0;\n    for(int n=0; n<8; n++){\n        Xnode[0] = reference_coords[0+n*3]; //Get the position of the current node\n        Xnode[1] = reference_coords[1+n*3];\n        Xnode[2] = reference_coords[2+n*3];\n        \n        Unode = test_deformation(Xnode);    //Update the deformation\n        \n        for(int i=0; i<12; i++){\n            U[inc]  = Unode[i];   //Assign the deformation\n            dU[inc] = 0.1*Unode[i];  //Assign the change in deformation (1/10 of the deformation)\n            inc++;\n        }\n    }\n    \n    //!Form the hexehedral test element.\n    micro_element::Hex8 element = micro_element::Hex8(reference_coords,U,dU,fparams);\n    \n    //!Set the gauss point\n    element.set_gpt_num(0); //Use the first gauss point since the gradients should be constant\n    element.update_gauss_point(true,true); //!Update the values for the gauss point\n/*    //!Compute the shape function values\n    element.update_shape_function_values();\n    \n    //!Set the fundamental deformation measures\n    element.set_fundamental_measures();\n    \n    //!Set the deformation measures\n    element.set_deformation_measures();\n    \n    //!Set the deformation tangents\n    element.set_fundamental_tangents();\n    element.set_deformation_tangents();\n    \n    //!Set the stresses at the gauss point\n    element.set_stresses(true);\n    \n    //!Set the stress tangents\n    element.set_stress_tangents();*/\n    \n    \n    //!Compute the expected mini mass matrix for a gauss point\n    Eigen::Matrix<double,8,8> mini_mass  = Eigen::Matrix<double,8,8>::Zero(8,8);\n    \n    //!Compute the internal forces\n    for(int m=0; m<8; m++){\n        for(int n=0; n<8; n++){\n            mini_mass(m,n) += element.get_N(m)*element.get_N(n)*fparams[0]*element.get_Jhatdet(0)*element.weights[0];\n        }\n    }\n    \n    test_results[0] = true;\n    for(int m=0; m<8; m++){\n        for(int n=0; n<8; n++){\n            test_results[0] = test_results[0] * (1e-9>fabs(mini_mass(m,n)-element.mini_mass(m,n)));\n        }\n    }\n    \n    //!Compute the total mass matrix\n    Eigen::Matrix<double, 96, 96> mass_matrix = Eigen::Matrix<double,96,96>::Zero(96,96);\n    Eigen::Matrix<double, 12, 96> N_matrix    = Eigen::Matrix<double,12,96>::Zero(12,96);\n    \n    for(int n=0; n<8; n++){\n        element.set_gpt_num(n);\n        element.update_gauss_point(false,true);\n        for(int i=0; i<8; i++){\n            for(int j=0; j<12; j++){\n                N_matrix(j,j+12*i) = element.get_N(i);\n            }\n        }\n        \n        mass_matrix += N_matrix.transpose()*N_matrix*fparams[0]*element.get_Jhatdet(0)*element.weights[0];\n    }\n    \n    micro_element::Hex8 element2 = micro_element::Hex8(reference_coords,U,dU,fparams);\n    element2.integrate_element(false,true,true);\n    \n    \n    //std::cout << \"mass_matrix:\\n\" << mass_matrix << \"\\n\";\n    //std::cout << \"AMATRX:\\n\" << element2.AMATRX  << \"\\n\";\n    \n    test_results[1] = true;\n    for(int m=0; m<96; m++){\n        for(int n=0; n<96; n++){\n            test_results[1] = test_results[1] * (1e-9>fabs(element2.AMATRX(m,n)-mass_matrix(m,n)));\n        }\n    }\n    \n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_mass_matrix & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_mass_matrix & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return 1;\n}\n\nint test_balance_of_first_moment_of_momentum(std::ofstream &results){\n    /*!==================================================\n    |    test_balance_of_first_moment_of_momentum    |\n    ==================================================\n    \n    Run tests on the formation of the residual of the \n    first moment of momentum.\n    \n    */\n    \n    //Seed the random number generator\n    srand (1);\n    \n    //!Initialize test results\n    int  test_num        = 2;\n    std::vector<bool> test_results(test_num,false);\n    \n    //!Initialize the floating point parameters\n    std::vector< double > fparams(19,0.);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    //!Form the required vectors for element formation\n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1};\n    std::vector< double > Unode;\n    std::vector< double > Xnode;\n    std::vector< double > U;\n    std::vector< double > dU;\n    Xnode.resize(3);\n    Unode.resize(96);\n    U.resize(96);\n    dU.resize(96);\n    int inc = 0;\n    for(int n=0; n<8; n++){\n        Xnode[0] = reference_coords[0+n*3]; //Get the position of the current node\n        Xnode[1] = reference_coords[1+n*3];\n        Xnode[2] = reference_coords[2+n*3];\n        \n        Unode = test_deformation(Xnode);    //Update the deformation\n        \n        for(int i=0; i<12; i++){\n            U[inc]  = Unode[i];   //Assign the deformation\n            dU[inc] = 0.1*Unode[i];  //Assign the change in deformation (1/10 of the deformation)\n            inc++;\n        }\n    }\n    \n    //!Form the hexehedral test element.\n    micro_element::Hex8 element = micro_element::Hex8(reference_coords,U,dU,fparams);\n    \n    //!Set the gauss point\n    element.set_gpt_num(0); //Use the first gauss point since the gradients should be constant\n    \n    //!Update the values for the gauss point\n    element.update_gauss_point(true);\n    \n/*    //!Compute the shape function values\n    element.update_shape_function_values();\n    \n    //!Set the fundamental deformation measures\n    element.set_fundamental_measures();\n    \n    //!Set the deformation measures\n    element.set_deformation_measures();\n    \n    //!Set the stresses at the gauss point\n    element.set_stresses();*/\n    \n    //!Set the residual vector due to the given gauss point\n    element.add_internal_moments();\n    \n    //!Compute the expected residual vector\n    std::vector< double > RHS(96,0.);\n    \n    //!Define the internal stress balance\n    tensor::Tensor23 mu_int({3,3});\n    \n    //!Compute the internal stresses\n    for(int n=0; n<8; n++){\n        mu_int.data.setZero();\n        \n        for(int i=0; i<3; i++){\n            for(int j=0; j<3; j++){\n                for(int I=0; I<3; I++){\n                    for(int J=0; J<3; J++){\n                        mu_int(i,j) += -element.get_N(n)*element.get_F()(i,I)*(element.SIGMA[0](I,J) - element.PK2[0](I,J))*element.get_F()(j,J)*element.get_Jhatdet(0)*element.weights[0];\n                    }\n                }\n                for(int I=0; I<3; I++){\n                    for(int J=0; J<3; J++){\n                        for(int K=0; K<3; K++){\n                            mu_int(i,j) += -element.get_dNdx(0,n)[K]*element.get_F()(j,J)*element.get_chi()(i,I)*element.M[0](K,J,I)*element.get_Jhatdet(0)*element.weights[0];\n                        }\n                    }\n                }\n            }\n        }\n        \n        RHS[0+n*12+3] = mu_int(0,0);\n        RHS[1+n*12+3] = mu_int(1,1);\n        RHS[2+n*12+3] = mu_int(2,2);\n        RHS[3+n*12+3] = mu_int(1,2);\n        RHS[4+n*12+3] = mu_int(0,2);\n        RHS[5+n*12+3] = mu_int(0,1);\n        RHS[6+n*12+3] = mu_int(2,1);\n        RHS[7+n*12+3] = mu_int(2,0);\n        RHS[8+n*12+3] = mu_int(1,0);\n        \n    }\n    \n    //!Compare the tangents\n    element.add_dMintdU();\n    \n    std::vector< std::vector< double > > gradient = compute_gradient_Mint(U);\n    \n    //print_vector_of_vectors(\"gradient\",gradient);\n    //print_vector_of_vectors(\"AMATRX\",element.AMATRX);\n    \n    test_results[1]=true;\n    for(int i=0; i<96; i++){\n        for(int j=0; j<96; j++){\n            test_results[1] = test_results[1] * (double_compare(gradient[i][j],element.AMATRX(j,i),1e-5,1e-5));\n            //std::cout << \"(\" << i << \", \" << j << \")\\n\";\n            //std::cout << \"answer: \" << gradient[i][j] << \"\\nresult: \" << element.AMATRX[j][i] << \"\\ndiff: \" << gradient[i][j]-element.AMATRX[j][i] <<\"\\n\";\n            if(!test_results[1]){break;}\n        }\n        if(!test_results[1]){break;}\n    }\n    \n    //!Compare the expected results to the element results\n    test_results[0] = true;\n    for(int i=0; i<96; i++){\n        test_results[0] = test_results[0] * (1e-9>fabs(element.RHS(i)-RHS[i]));\n    }\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_balance_of_first_moment_of_momentum & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_balance_of_first_moment_of_momentum & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return 1;\n}\n\nint test_integrate_element(std::ofstream &results){\n    /*!================================\n    |    test_integrate_element    |\n    ================================\n    \n    Run tests on the integration of the \n    finite element.\n    \n    */\n    \n    //Seed the random number generator\n    srand (1);\n    \n    //!Initialize test results\n    int  test_num        = 2;\n    std::vector<bool> test_results(test_num,false);\n    \n    //!Initialize the floating point parameters\n    std::vector< double > fparams(19,0.);\n    \n    fparams[0] = 1000.;\n    \n    for(int i=1; i<19; i++){\n        fparams[i] = 0.1*(i+1);\n    }\n    \n    //!Form the required vectors for element formation\n    std::vector< double > reference_coords = {0,0,0,1,0,0,1,1,0,0,1,0,0.1,-0.2,1,1.1,-0.2,1.1,1.1,0.8,1.1,0.1,0.8,1};\n    std::vector< double > Unode;\n    std::vector< double > Xnode;\n    std::vector< double > U;\n    std::vector< double > dU;\n    Xnode.resize(3);\n    Unode.resize(96);\n    U.resize(96);\n    dU.resize(96);\n    int inc = 0;\n    for(int n=0; n<8; n++){\n        Xnode[0] = reference_coords[0+n*3]; //Get the position of the current node\n        Xnode[1] = reference_coords[1+n*3];\n        Xnode[2] = reference_coords[2+n*3];\n        \n        Unode = test_deformation(Xnode);    //Update the deformation\n        \n        for(int i=0; i<12; i++){\n            U[inc]  = Unode[i];   //Assign the deformation\n            dU[inc] = 0.1*Unode[i];  //Assign the change in deformation (1/10 of the deformation)\n            inc++;\n        }\n    }\n    \n    //std::clock_t start;\n    //double duration;\n\n    \n    \n    //!Form the hexehedral test element.\n    micro_element::Hex8 element = micro_element::Hex8(reference_coords,U,dU,fparams);\n    \n    //start = std::clock();\n    \n    //!Integrate the element\n    element.integrate_element(true);\n    \n    //duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n\n    //std::cout<<\"printf: \"<< duration <<'\\n';\n    \n    //!Compute the expected residual vector\n    std::vector< double > RHS(96,0.);\n    \n    //!Define the internal stress balance\n    tensor::Tensor23 mu_int({3,3});\n    \n    //!Integrate the element\n    for(int gpt_num=0; gpt_num<8; gpt_num++){\n        element.set_gpt_num(gpt_num);\n        element.update_gauss_point();\n        \n        //!Compute the internal stresses\n        for(int n=0; n<8; n++){\n            \n            //!Add the internal force residual\n            for(int j=0; j<3; j++){\n                for(int I=0; I<3; I++){\n                    for(int J=0; J<3; J++){\n                        RHS[j+12*n] += -element.get_dNdx(0,n)[I]*element.PK2[gpt_num](I,J)*element.get_F()(j,J)*element.get_Jhatdet(0)*element.weights[gpt_num];\n                    }\n                }\n            }\n            \n            //!Add the internal stress residual\n            mu_int.data.setZero();\n        \n            for(int i=0; i<3; i++){\n                for(int j=0; j<3; j++){\n                    for(int I=0; I<3; I++){\n                        for(int J=0; J<3; J++){\n                            mu_int(i,j) += -element.get_N(n)*element.get_F()(i,I)*(element.SIGMA[gpt_num](I,J) - element.PK2[gpt_num](I,J))*element.get_F()(j,J)*element.get_Jhatdet(0)*element.weights[gpt_num];\n                        }\n                    }\n                    for(int I=0; I<3; I++){\n                        for(int J=0; J<3; J++){\n                            for(int K=0; K<3; K++){\n                                mu_int(i,j) += -element.get_dNdx(0,n)[K]*element.get_F()(j,J)*element.get_chi()(i,I)*element.M[gpt_num](K,J,I)*element.get_Jhatdet(0)*element.weights[gpt_num];\n                            }\n                        }\n                    }\n                }\n            }\n            \n            RHS[0+n*12+3] += mu_int(0,0);\n            RHS[1+n*12+3] += mu_int(1,1);\n            RHS[2+n*12+3] += mu_int(2,2);\n            RHS[3+n*12+3] += mu_int(1,2);\n            RHS[4+n*12+3] += mu_int(0,2);\n            RHS[5+n*12+3] += mu_int(0,1);\n            RHS[6+n*12+3] += mu_int(2,1);\n            RHS[7+n*12+3] += mu_int(2,0);\n            RHS[8+n*12+3] += mu_int(1,0);\n        \n        }\n    }\n    \n    //!Compare the expected results to the element results\n    test_results[0] = true;\n    for(int i=0; i<96; i++){\n        test_results[0] = test_results[0] * (1e-9>fabs(element.RHS(i)-RHS[i]));\n    }\n    \n    //!Compare the tangents\n    \n    std::vector< std::vector< double > > gradient = compute_gradient_element(U);\n    \n    //print_vector_of_vectors(\"gradient\",gradient);\n    //print_vector_of_vectors(\"AMATRX\",element.AMATRX);\n    \n    test_results[1]=true;\n    for(int i=0; i<96; i++){\n        for(int j=0; j<96; j++){\n            test_results[1] = test_results[1] * (double_compare(gradient[i][j],element.AMATRX(j,i),1e-5,1e-5));\n            //std::cout << \"(\" << i << \", \" << j << \")\\n\";\n            //std::cout << \"answer: \" << gradient[i][j] << \"\\nresult: \" << element.AMATRX[j][i] << \"\\ndiff: \" << gradient[i][j]-element.AMATRX[j][i] <<\"\\n\";\n            if(!test_results[1]){break;}\n        }\n        if(!test_results[1]){break;}\n    }\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_integrate_element & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_integrate_element & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return 1;\n}\n\nint main(){\n    /*!==========================\n    |         main            |\n    ===========================\n    \n    The main loop which runs the tests defined in the \n    accompanying functions. Each function should output\n    the function name followed by & followed by True or \n    False if the test passes or fails respectively.*/\n    \n    std::ofstream results;\n    //Open the results file\n    results.open (\"results.tex\");\n    \n    //!Run the test functions\n    test_constructors(results);\n    test_shape_functions(results);\n    test_mass_matrix(results);\n    test_fundamental_measures(results);\n    test_deformation_measures(results);\n    test_stress_tangents(results);\n    test_balance_of_linear_momentum(results);\n    test_balance_of_first_moment_of_momentum(results);\n    test_integrate_element(results);\n    \n    //Close the results file\n    results.close();\n}\n\n", "meta": {"hexsha": "11edfd0371d2504ea0ef1f3a637d32a794c30237", "size": 84720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/tests/micro_element/test_micro_element.cpp", "max_stars_repo_name": "lanl/tardigrade-micromorphic-element", "max_stars_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/tests/micro_element/test_micro_element.cpp", "max_issues_repo_name": "lanl/tardigrade-micromorphic-element", "max_issues_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/tests/micro_element/test_micro_element.cpp", "max_forks_repo_name": "lanl/tardigrade-micromorphic-element", "max_forks_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7529880478, "max_line_length": 209, "alphanum_fraction": 0.5452195467, "num_tokens": 24942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5702791149673845}}
{"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": "//! [distance-hypot-all]\n#include <chrono>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n\n#include <boost/simd/function/aligned_load.hpp>\n#include <boost/simd/function/aligned_store.hpp>\n#include <boost/simd/function/fast.hpp>\n#include <boost/simd/function/hypot.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/memory/allocator.hpp>\n\nint main(int argc, char** argv)\n{\n  using namespace std::chrono;\n  namespace bs = boost::simd;\n  typedef float T;\n  using pack_t = bs::pack<T>;\n\n  std::size_t num_points = 1600000;\n  std::vector<T, bs::allocator<T>> X(num_points);\n  std::vector<T, bs::allocator<T>> Y(num_points);\n  std::vector<T, bs::allocator<T>> distance0(num_points);\n  std::vector<T, bs::allocator<T>> distance1(num_points);\n  std::vector<T, bs::allocator<T>> distance2(num_points);\n  std::vector<T, bs::allocator<T>> distance3(num_points);\n\n  std::generate(X.begin(), X.end(), [](){return T(std::rand()) / std::numeric_limits<int>::max();});\n  std::generate(Y.begin(), Y.end(), [](){return T(std::rand()) / std::numeric_limits<int>::max();});\n\n  T refX = 0, refY = 0;\n\n  auto t0 = high_resolution_clock::now();\n  //! [distance-hypot-scalar]\n  for (int i = 0; i < num_points; ++i) {\n    auto x = refX - X[i];\n    auto y = refY - Y[i];\n    distance0[i] = std::hypot(refX - X[i], refY - Y[i]);\n  }\n  //! [distance-hypot-scalar]\n  auto t1 = high_resolution_clock::now();\n  std::cout << \" time scalar \" << duration_cast<microseconds>(t1 - t0).count() << std::endl;\n\n  //! [distance-hypot-time]\n  t0 = high_resolution_clock::now();\n  //! [distance-hypot-calc]\n  pack_t vrefX = pack_t(refX);\n  pack_t vrefY = pack_t(refY);\n\n  for (int i = 0; i < num_points; i += pack_t::static_size) {\n    pack_t vX  = bs::aligned_load<pack_t>(&X[i]);\n    pack_t vY  = bs::aligned_load<pack_t>(&Y[i]);\n    pack_t res = bs::hypot(vrefX - vX, vrefY - vY);\n    bs::aligned_store(res, &distance1[i]);\n  }\n  //! [distance-hypot-calc]\n\n  t1 = high_resolution_clock::now();\n  std::cout << \" time SIMD hypot \" << duration_cast<microseconds>(t1 - t0).count() << std::endl;\n\n  t0 = high_resolution_clock::now();\n  //! [distance-hypot-fast-hypot]\n  for (int i = 0; i < num_points; i += pack_t::static_size) {\n    pack_t vX  = bs::aligned_load<pack_t>(&X[i]);\n    pack_t vY  = bs::aligned_load<pack_t>(&Y[i]);\n    pack_t res = bs::fast_(bs::hypot)(vrefX - vX, vrefY - vY);\n    bs::aligned_store(res, &distance2[i]);\n  }\n  ////! [distance-hypot-fast-hypot]\n  t1 = high_resolution_clock::now();\n  std::cout << \" time SIMD fast hypot \" << duration_cast<microseconds>(t1 - t0).count() << std::endl;\n}\n//! [distance-hypot-all]\n\n", "meta": {"hexsha": "82820341536b7d73ec877fc762220570da01102c", "size": 2617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/distance_hypot.cpp", "max_stars_repo_name": "timblechmann/boost.simd", "max_stars_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "doc/examples/distance_hypot.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/examples/distance_hypot.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 34.4342105263, "max_line_length": 101, "alphanum_fraction": 0.6415743217, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5702744374840797}}
{"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": "#ifndef PLANE3D_HPP\n#define PLANE3D_HPP\n#include <Eigen/Dense>\n\n//#define DEBUG_PLANE\n\n\n/** Representation of the plane equation\n* ax + by + cz + d = dist \n*/\nclass Plane3D\n{\npublic:\n\n  /** \n   * Coefficient constructor - simply copy the given coefficients\n   * @param coeffs Coefficients {a,b,c,d}\n   */\n  Plane3D(const double coeffs[4])\n    {\n      for(int i = 0; i < 4; i++)\n      {\n\tm_coeffs[i] = coeffs[i];\n      }\n    }\n  \n  /**\n   * Matrix constructor - treat the z axis of the rotation part of the matrix as a normal vector\n   * @param coeffs Matrix to construct from\n   */ \n  Plane3D(const Eigen::Matrix4f coeffs)\n    {\n      for(int i = 0; i < 3; i++)\n      {\n\tm_coeffs[i] = coeffs(i,2);\n      }\n      m_coeffs[3] = 0.0;\n      for(int i = 0; i < 3; i++)\n      {\n\t\n\tm_coeffs[3] -= m_coeffs[i]*coeffs(i,3);\n      }\n    }\n\n  /**\n   * Matrix constructor - treat the z axis of the rotation part of the matrix as a normal vector\n   * @param coeffs Matrix to construct from\n   */\n  Plane3D(const Eigen::Matrix4d coeffs)\n    {\n      for(int i = 0; i < 3; i++)\n      {\n\tm_coeffs[i] = coeffs(i,2);\n      }\n      m_coeffs[3] = 0.0;\n      for(int i = 0; i < 3; i++)\n      {\n\t\n\tm_coeffs[3] -= m_coeffs[i]*coeffs(i,3);\n      }\n    }\n  \n  /**\n   * Zero constructor. Initialize coefficients to zero\n   */\n  Plane3D() \n    { \n      for(int i = 0; i < 4; i++) \n      { \n\tm_coeffs[i] = 0.0; \n      } \n    };\n  ~Plane3D() { }\n\n  /**\n   * Set a coefficient\n   * @param i coefficient to set\n   * @param c value to set it to\n   */\n  inline void setCoefficient(const int i, const double c)\n    {\n      m_coeffs[i] = c;\n    }\n  /**\n   * Get a coefficient\n   * @param i coefficient to get\n   * @return coefficient\n   */\n  inline double getCoefficient(const int i)\n    {\n      return m_coeffs[i];\n    }\n  /**\n   * Get distance from the plane to a point\n   * @param pt point to find distance to\n   * @return distance to point\n   */\n  inline double getDistance(double const pt[3]) const\n    {\n      double ret = 0.0;\n      for(int i = 0; i < 3; i++)\n      {\n\tret += pt[i]*m_coeffs[i];\n      }\n      ret += m_coeffs[3];\n#ifdef DEBUG_PLANE\n      cerr << \"Distance: \" << ret << endl;\n#endif\n      return ret;\n    }\n  \n  /**\n   * Project a point onto the plane\n   * @param projected Projected point will be returned here\n   * @param pt Point to project\n   */\n // void projectOnto(double projected[3], double const pt[3] ) const; DELETED\n      \nprotected:\n  /**\n   * The plane equation coefficients a,b,c,d\n   */\n  double m_coeffs[4];\n  \n};\n\n#endif // PLANE3D_HPP\n", "meta": {"hexsha": "05eeff1ed67a6e4d72d29340707307e441c3d310", "size": 2540, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/plane3d.hpp", "max_stars_repo_name": "Danielhiversen/AngleCorr", "max_stars_repo_head_hexsha": "01acc6547c95e506b88c20011789784a129a16bb", "max_stars_repo_licenses": ["MIT"], "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/plane3d.hpp", "max_issues_repo_name": "Danielhiversen/AngleCorr", "max_issues_repo_head_hexsha": "01acc6547c95e506b88c20011789784a129a16bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-23T12:30:47.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T12:30:47.000Z", "max_forks_repo_path": "core/plane3d.hpp", "max_forks_repo_name": "Danielhiversen/AngleCorr", "max_forks_repo_head_hexsha": "01acc6547c95e506b88c20011789784a129a16bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-02T10:18:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-02T10:18:43.000Z", "avg_line_length": 19.84375, "max_line_length": 96, "alphanum_fraction": 0.5590551181, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5702744264629928}}
{"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": "#include <igl/boundary_facets.h>\n#include <igl/colon.h>\n#include <igl/cotmatrix.h>\n#include <igl/jet.h>\n#include <igl/min_quad_with_fixed.h>\n#include <igl/readOFF.h>\n#include <igl/setdiff.h>\n#include <igl/slice.h>\n#include <igl/slice_into.h>\n#include <igl/unique.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <Eigen/Sparse>\n#include <iostream>\n#include \"tutorial_shared_path.h\"\n\nint main(int argc, char *argv[])\n{\n  using namespace Eigen;\n  using namespace std;\n  MatrixXd V;\n  MatrixXi F;\n  igl::readOFF(TUTORIAL_SHARED_PATH \"/camelhead.off\",V,F);\n  // Find boundary edges\n  MatrixXi E;\n  igl::boundary_facets(F,E);\n  // Find boundary vertices\n  VectorXi b,IA,IC;\n  igl::unique(E,b,IA,IC);\n  // List of all vertex indices\n  VectorXi all,in;\n  igl::colon<int>(0,V.rows()-1,all);\n  // List of interior indices\n  igl::setdiff(all,b,in,IA);\n\n  // Construct and slice up Laplacian\n  SparseMatrix<double> L,L_in_in,L_in_b;\n  igl::cotmatrix(V,F,L);\n  igl::slice(L,in,in,L_in_in);\n  igl::slice(L,in,b,L_in_b);\n\n  // Dirichlet boundary conditions from z-coordinate\n  VectorXd bc;\n  VectorXd Z = V.col(2);\n  igl::slice(Z,b,bc);\n\n  // Solve PDE\n  SimplicialLLT<SparseMatrix<double > > solver(-L_in_in);\n  VectorXd Z_in = solver.solve(L_in_b*bc);\n  // slice into solution\n  igl::slice_into(Z_in,in,Z);\n\n  // Alternative, short hand\n  igl::min_quad_with_fixed_data<double> mqwf;\n  // Linear term is 0\n  VectorXd B = VectorXd::Zero(V.rows(),1);\n  // Empty constraints\n  VectorXd Beq;\n  SparseMatrix<double> Aeq;\n  // Our cotmatrix is _negative_ definite, so flip sign\n  igl::min_quad_with_fixed_precompute((-L).eval(),b,Aeq,true,mqwf);\n  igl::min_quad_with_fixed_solve(mqwf,B,bc,Beq,Z);\n\n  // Pseudo-color based on solution\n  MatrixXd C;\n  igl::jet(Z,true,C);\n\n  // Plot the mesh with pseudocolors\n  igl::opengl::glfw::Viewer viewer;\n  viewer.data().set_mesh(V, F);\n  viewer.data().show_lines = false;\n  viewer.data().set_colors(C);\n  viewer.launch();\n}\n", "meta": {"hexsha": "f64dc80fa64726d510fd940eda5ea0e126d4b5d2", "size": 1943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/tutorial/303_LaplaceEquation/main.cpp", "max_stars_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_stars_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "isometric-deformation/ext/libigl/tutorial/303_LaplaceEquation/main.cpp", "max_issues_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_issues_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isometric-deformation/ext/libigl/tutorial/303_LaplaceEquation/main.cpp", "max_forks_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_forks_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2567567568, "max_line_length": 67, "alphanum_fraction": 0.6984045291, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5702718455741416}}
{"text": "/*\nlicense in here\nThis is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, compile, sell, or\ndistribute this software, either in source code form or as a compiled\nbinary, for any purpose, commercial or non-commercial, and by any\nmeans.\n\nIn jurisdictions that recognize copyright laws, the author or authors\nof this software dedicate any and all copyright interest in the\nsoftware to the public domain. We make this dedication for the benefit\nof the public at large and to the detriment of our heirs and\nsuccessors. We intend this dedication to be an overt act of\nrelinquishment in perpetuity of all present and future rights to this\nsoftware under copyright law.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n\nFor more information, please refer to <https://unlicense.org>\n*/\n\n#include <boost/random.hpp>\n#include <iostream>\n\nint main(int argc,char *argv[])\n{\n  boost::mt19937 gen; //\u4f2a\u968f\u673a\u6570\u53d1\u751f\u5668\uff08generator\uff09\n  boost::uniform_int<>dist(1,6);\n  boost::variate_generator<boost::mt19937&, boost::uniform_int<>>die(gen,dist);\n  \n  for(auto i = 0; i < 10; ++i)\n  {\n\tstd::cout << die() << \"  \";  \n  }\n  std::cout << \"\\n\";\n}\n\n\n", "meta": {"hexsha": "8ac5223f15504d954bd7a3e1fdf3d8f54293a6bb", "size": 1571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/boost/random/randon.cpp", "max_stars_repo_name": "UMP-45/C-_Study", "max_stars_repo_head_hexsha": "708aef36931c4881f830bd3d2a7732c0d3856ed0", "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++/boost/random/randon.cpp", "max_issues_repo_name": "UMP-45/C-_Study", "max_issues_repo_head_hexsha": "708aef36931c4881f830bd3d2a7732c0d3856ed0", "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++/boost/random/randon.cpp", "max_forks_repo_name": "UMP-45/C-_Study", "max_forks_repo_head_hexsha": "708aef36931c4881f830bd3d2a7732c0d3856ed0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.152173913, "max_line_length": 79, "alphanum_fraction": 0.7562062381, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.5702205084788176}}
{"text": "#include <boost/mpi.hpp>\n#include \"mpi_impl/scatter_mesh.hpp\"\n#include \"mpi_impl/poisson.hpp\"\n\nnamespace mpi = boost::mpi;\nusing namespace schro_mpi;\n\ndouble f(double x, double y)\n{\n    return x*x - y*y;\n}\n\nbool test_poisson(mpi::communicator& comm)\n{\n    int order = 6;\n    \n    Mesh<double> mesh = scatter_mesh<double>(order, \"../meshes/small_mesh\", comm, 0);\n    mesh.compute_metrics();\n\n    int dof = mesh.dof(); // processor-local degrees of freedom\n    dof = mpi::all_reduce(comm, dof, std::plus<int>{}); // total degrees of freedom\n\n    const auto& z = mesh.quadrature.x;\n\n    SparseData<matrix<double>> F, u;\n    for (auto& [e, element] : mesh.elements)\n    {\n        F[e] = arma::zeros(mesh.N, mesh.N);\n        u[e] = arma::zeros(mesh.N, mesh.N);\n\n        for (int i=0; i < mesh.N; ++i)\n            for (int j=0; j < mesh.N; ++j)\n            {\n                auto [x, y] = mesh.elements[e].from_local_coo(z[i], z[j]);\n                F[e](i, j) = f(x, y);\n            }\n    }\n    \n    auto rslts = poisson<double>(u, F, mesh, dof, 1e-10);\n\n    if (comm.rank() == 0)\n        std::cout << \"poisson returned after \" << rslts.n_iter << \" iteration with residual \" << rslts.residual << std::endl;\n\n    return rslts.success;\n}", "meta": {"hexsha": "5d97711ef219c10184e7ddc7500854f3860a2826", "size": 1230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mpi_tests/poisson.cpp", "max_stars_repo_name": "arotem3/SchrodingerSEM", "max_stars_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mpi_tests/poisson.cpp", "max_issues_repo_name": "arotem3/SchrodingerSEM", "max_issues_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mpi_tests/poisson.cpp", "max_forks_repo_name": "arotem3/SchrodingerSEM", "max_forks_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3333333333, "max_line_length": 125, "alphanum_fraction": 0.5691056911, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.570149578324582}}
{"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": "//\n// Created by \u0421\u0435\u0440\u0433\u0435\u0439 \u041a\u0440\u0438\u0432\u043e\u043d\u043e\u0441 on 10.08.17.\n//\n#define BOOST_TEST_MODULE Extrapolator test\n#include <boost/test/unit_test.hpp>\n#include \"Extrapolator.h\"\n#include \"math/Sum.h\"\n\nusing namespace omnn::math;\nusing namespace boost::unit_test;\n\n\nstd::string l(const omnn::math::Valuable& v)\n{\n    std::stringstream ss;\n    ss << v;\n    return ss.str();\n}\n\nBOOST_AUTO_TEST_CASE(ExtrapolatorSolve_test)\n{\n    \n}\n\nBOOST_AUTO_TEST_CASE(Extrapolator_test, *disabled())\n{\n    // lets define math vars:\n    // TODO : link to youtube video with description of the sample for deep learning\n    // for example we'll take bool square 2x2\n    // lets say the goal is to determine type of squere\n    // verticals:   {1,0},{1,0} or {0,1},{0,1}\n    // horizontals: {1,1},{0,0} or {0,0},{1,1}\n    // diagonals:   {1,0},{0,1} or {0,1},{1,0}\n    // this way the vars are as follows:\n    // box four vars a,b,c,d;  quantors: is_vericals, is_horizontals, is_diagonals\n    \n    //    Extrapolator<> e_verticals {{ {1,0,\n    //                                   1,0,      1},\n    //\n    //                                  {0,1,\n    //                                   0,1,      1},\n    //\n    //                                        {0,0,0,0,0},\n    //                                        {1,1,1,1,0},\n    //                                        {0,1,1,0,0}\n    //                      }};\n    \n    // Test vericals:\n    Extrapolator e_verticals {{\n        {1,-1,\n            1,-1},\n        \n        {-1,1,\n            -1,1},\n        \n        //        {-1,-1,-1,-1},\n        //        {1,1,1,1}\n    }};\n    \n    ublas::vector<double> augment(e_verticals.size1());\n    augment[0] = 2;\n    augment[1] = 1;\n    //    augment[2] = -1;\n    //    augment[3] = -2;\n    //BOOST_TEST(e_verticals.Consistent(augment));\n    \n    auto r = e_verticals.Solve(augment);\n    std::cout << r[0] << ' ' << r[1] << ' ' << r[2] << ' ' << r[3] << std::endl;\n    auto val = r[0] * 1 + r[1] * -1 + r[2] * 1 + r[3] * -1;\n    std::cout << \"(r[0] * 1 + r[1] * -1 + r[2] * 1 + r[3] * -1) is \" << val << std::endl;\n    BOOST_TEST(r[0] * 1 + r[1] * -1 + r[2] * 1 + r[3] * -1 == 1.);\n    val = r[0] * -1 + r[1] * 1 + r[2] * -1 + r[3] * 1;\n    std::cout << \"(r[0] * -1 + r[1] * 1 + r[2] * -1 + r[3] * 1) is \" << val << std::endl;\n    BOOST_TEST(r[0] * -1 + r[1] * 1 + r[2] * -1 + r[3] * 1 == 2);\n    val = r[0] * -1 + r[1] * -1 + r[2] * -1 + r[3] * -1;\n    std::cout << \"(r[0] * 1 + r[1] * 1 + r[2] * 1 + r[3] * 1) is \" << val << std::endl;\n    BOOST_TEST(r[0] * -1 + r[1] * -1 + r[2] * -1 + r[3] * -1 == -1);\n    val = r[0] * 1 + r[1] * 1 + r[2] * 1 + r[3] * 1;\n    std::cout << \"(r[0] * 1 + r[1] * 1 + r[2] * 1 + r[3] * 1) is \" << val << std::endl;\n    BOOST_TEST(r[0] * 1 + r[1] * 1 + r[2] * 1 + r[3] * 1 == -2);\n    \n    Extrapolator e {{\n        {0,0,0,0, 0,0,0},\n        // verticals\n        {1,0,1,0, 1,0,0},\n        {0,1,0,1, 1,0,0},\n        // horizontals\n        {1,1,0,0, 0,1,0},\n        {0,0,1,1, 0,1,0},\n        // diagonals\n        {0,1,1,0, 0,0,1},\n        {1,0,0,1, 0,0,1},\n    }};\n    BOOST_CHECK_NO_THROW(e.Determinant());\n    \n    //BOOST_TEST(e.Consistent());\n}\n\nBOOST_AUTO_TEST_CASE(ViewMatrix_test)\n{\n    Extrapolator e {{ {1, 2},\n        {3, 4} }};\n    {\n        Valuable v = e;\n        std::cout << v << std::endl;\n    }\n    \n    // view matrix\n    //    0 0 1\n    //    0 1 2\n    //    1 0 3\n    //    1 1 4\n    auto vm = e.ViewMatrix();\n    BOOST_TEST(vm.size1() == 4);\n    BOOST_TEST(vm.size2() == 3);\n    BOOST_TEST(vm(0,0) == 0); BOOST_TEST(vm(0,1) == 0); BOOST_TEST(vm(0,2) == 1);\n    BOOST_TEST(vm(1,0) == 0); BOOST_TEST(vm(1,1) == 1); BOOST_TEST(vm(1,2) == 2);\n    BOOST_TEST(vm(2,0) == 1); BOOST_TEST(vm(2,1) == 0); BOOST_TEST(vm(2,2) == 3);\n    BOOST_TEST(vm(3,0) == 1); BOOST_TEST(vm(3,1) == 1); BOOST_TEST(vm(3,2) == 4);\n    {\n        // ax+by+cz=0\n        // a=0:N, b=0:M, c=-(ax+by)/z     // if x=0 and y=0 then c becames 0 but it wasnt;\n        // lets make c a va\n        Valuable eq = 1_v;\n        Variable x,y,z;\n        for (auto i=vm.size1(); i--;) {\n            auto e1 = x - vm(i,0);\n            auto e2 = y - vm(i,1);\n            auto e3 = z - vm(i,2);\n            auto subsyst = e1*e1 + e2*e2 + e3*e3; // squares sum equivalent to conjunction\n            std::cout << subsyst << std::endl;\n            \n            eq *= subsyst;\n\n            BOOST_TEST(subsyst.IsSum());\n            auto formula = FormulaOfVaWithSingleIntegerRoot(z, subsyst.as<Sum>());\n            std::cout << \"formula of value: \" << formula << std::endl;\n            auto evaluated = formula(vm(i, 0), vm(i, 1));\n            std::cout << evaluated << std::endl;\n            evaluated.optimize();\n            std::cout << evaluated << std::endl;\n            BOOST_TEST(evaluated == vm(i, 2)); // test row formula\n            \n            subsyst.Eval(x, vm(i, 0));\n            subsyst.Eval(y, vm(i, 1));\n            subsyst.Eval(z, vm(i, 2));\n            subsyst.optimize();\n            BOOST_TEST(subsyst == 0); // test row equation\n            \n            auto e = eq;\n            e.Eval(x, vm(i, 0));\n            e.Eval(y, vm(i, 1));\n            e.Eval(z, vm(i, 2));\n            e.optimize();\n//            std::cout << e.str() << std::endl;\n            BOOST_TEST(e == 0); //test current eq\n        }\n        std::cout << \"Total equation:\" << eq << std::endl;\n        BOOST_TEST(eq.IsSum());\n        auto f = FormulaOfVaWithSingleIntegerRoot(z, eq.as<Sum>());\n        std::cout << \"Formula : \" << f << std::endl;\n        // checking\n        for (auto i=vm.size1(); i--;) {\n            Valuable v = eq;\n            v.Eval(x, vm(i,0));\n            v.Eval(y, vm(i,1));\n            v.Eval(z, vm(i,2));\n            v.optimize();\n            BOOST_TEST(v == 0);  //test whole equation\n//            std::cout << std::endl << vm(i,2) << \" : \" << v << std::endl;\n            BOOST_TEST(f(vm(i,0),vm(i,1))==vm(i,2)); // test formula\n        }\n    }\n    Extrapolator m {{\n        {0,0},\n        {0,1},\n        {1,0},\n        {1,1}\n    }};\n    ublas::vector<Valuable> au(4);\n    for(int i=1; i<4; ++i)\n    {\n        au[i] = i;\n    }\n}\n\nBOOST_AUTO_TEST_CASE(Codec_test)\n{\n    Extrapolator ex {{\n        //  input   output\n        {0,0,0,0, 0,0,0},\n        // verticals\n        {1,0,1,0, 1,0,0},\n        {0,1,0,1, 1,0,0},\n        // horizontals\n        {1,1,0,0, 0,1,0},\n        {0,0,1,1, 0,1,0},\n        // diagonals\n        {0,1,1,0, 0,0,1},\n        {1,0,0,1, 0,0,1},\n    }};\n\n//    Extrapolator e {{       // input    output\n//        {0,0},              //{0,0,0,0, 0,0,0},\n//        // verticals\n//        {10,4},             //{1,0,1,0, 1,0,0},\n//        {5,4},              //{0,1,0,1, 1,0,0},\n//        // horizontals\n//        {12,2},             //{1,1,0,0, 0,1,0},\n//        {3,2},              //{0,0,1,1, 0,1,0},\n//        // diagonals\n//        {6,1},              //{0,1,1,0, 0,0,1},\n//        {9,1},              //{1,0,0,1, 0,0,1},\n//    }};\n    \n    Variable x,y,z;\n    auto f = ex.Factors(y,x,z);\n    std::list<Variable> formulaParamSequence = {y,x};\n    FormulaOfVaWithSingleIntegerRoot fo(z, f, &formulaParamSequence);\n    \n    // TODO : extrapolation\n//    std::cout << fo(ex.size1(), ex.size2()) << std::endl;\n\n    // inbound data deduce\n    for (auto i=ex.size1(); i--;) { // raw\n        for (auto j=ex.size2(); j--;) { // column\n            auto c = f;\n            c.Eval(x, j);\n            c.Eval(y, i);\n            c.Eval(z, ex(i,j));\n            c.optimize();\n            BOOST_TEST(c==0_v);//\n            \n            c = fo(i,j);\n            std::cout << c.str() << std::endl;\n            BOOST_TEST(c == ex(i,j));\n        }\n    }\n}\n", "meta": {"hexsha": "d58dd02e5770878951a1fef1ddc81842b6b17fbe", "size": 7625, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/extrapolator/test/test_extrapolator.cpp", "max_stars_repo_name": "ApusDT/openmind", "max_stars_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-08-13T18:46:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T14:18:10.000Z", "max_issues_repo_path": "omnn/extrapolator/test/test_extrapolator.cpp", "max_issues_repo_name": "SergMariaDB/openmind", "max_issues_repo_head_hexsha": "98ad7f1c2c5c02d41418c7f9af25876342270d25", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2017-11-26T12:42:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T09:38:33.000Z", "max_forks_repo_path": "omnn/extrapolator/test/test_extrapolator.cpp", "max_forks_repo_name": "SergMariaDB/openmind", "max_forks_repo_head_hexsha": "98ad7f1c2c5c02d41418c7f9af25876342270d25", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-08-28T07:00:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T19:59:55.000Z", "avg_line_length": 31.7708333333, "max_line_length": 90, "alphanum_fraction": 0.4194098361, "num_tokens": 2736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5701221145721121}}
{"text": "#ifndef USE_EIGEN_HPP\n#define USE_EIGEN_HPP\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/StdVector>\n\n#define EIGEN_DONT_PARALLELIZE\n\n#ifdef HAS_HPX\n#include \"serialization/eigen_matrix.hpp\"\n#endif\n\nnamespace SO {\nconstexpr int ColumnMajor = Eigen::StorageOptions::ColMajor;\nconstexpr int RowMajor    = Eigen::StorageOptions::RowMajor;\n}\n\ntemplate <typename Matrix>\nusing Column = typename Eigen::DenseBase<Matrix>::ColXpr;\n\ntemplate <typename T, uint m>\nusing StatVector = Eigen::Matrix<T, m, 1>;\ntemplate <typename T, uint m, uint n>\nusing StatMatrix = Eigen::Matrix<T, m, n>;\n\ntemplate <typename T>\nusing DynVector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\ntemplate <typename T>\nusing DynRowVector = Eigen::Matrix<T, 1, Eigen::Dynamic>;\ntemplate <typename T, int SO = SO::ColumnMajor>\nusing DynMatrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\ntemplate <typename T, uint m>\nusing HybMatrix = Eigen::Matrix<T, m, Eigen::Dynamic>;\n\ntemplate <typename T>\nusing SparseVector = Eigen::SparseVector<T>;\ntemplate <typename T>\nusing SparseMatrix = Eigen::SparseMatrix<T>;\n\ntemplate <typename EigenType>\nusing AlignedAllocator = Eigen::aligned_allocator<EigenType>;\n\ntemplate <typename T>\nDynMatrix<T> IdentityMatrix(const uint size) {\n    return Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Identity(size, size);\n}\n\ntemplate <typename T>\nDynVector<T> IdentityVector(const uint size) {\n    DynVector<T> I_vector = DynVector<T>::Zero(size * size);\n    for (uint i = 0; i < size; ++i) {\n        I_vector[i * size + i] = 1.0;\n    }\n    return I_vector;\n}\n\ntemplate <typename T>\nstruct SparseMatrixMeta {\n    std::vector<Eigen::Triplet<T>> data;\n\n    void add_triplet(const uint row, const uint col, const T value) {\n        this->data.emplace_back(Eigen::Triplet<T>(row, col, value));\n    }\n\n    void get_sparse_matrix(SparseMatrix<T>& sparse_matrix) { sparse_matrix.setFromTriplets(data.begin(), data.end()); }\n};\n\n/* Vector/Matrix (aka Tensor) Operations */\ntemplate <typename ArrayType>\nvoid set_constant(ArrayType&& array, const double value) {\n    array = std::remove_reference<ArrayType>::type::Constant(\n        std::forward<ArrayType>(array).rows(), std::forward<ArrayType>(array).cols(), value);\n}\n\ntemplate <typename ArrayType>\ndecltype(auto) transpose(const ArrayType& array) {\n    return array.transpose();\n}\n\ntemplate <typename ArrayType>\ndouble norm(const ArrayType& array) {\n    return array.norm();\n}\n\ntemplate <typename ArrayType>\ndouble sq_norm(const ArrayType& array) {\n    return array.squaredNorm();\n}\n\ntemplate <typename ArrayType>\ndecltype(auto) power(const ArrayType& array, const double exp) {\n    return array.array().pow(exp);\n}\n\n/* Vector Operations */\ntemplate <typename VectorType>\nuint size(const VectorType& vector) {\n    return vector.size();\n}\n\ntemplate <typename LeftVectorType, typename RightVectorType>\ndecltype(auto) vec_cw_mult(const LeftVectorType& vector_left, const RightVectorType& vector_right) {\n    return vector_left.cwiseProduct(vector_right);\n}\n\ntemplate <typename LeftVectorType, typename RightVectorType>\ndecltype(auto) vec_cw_div(const LeftVectorType& vector_left, const RightVectorType& vector_right) {\n    return vector_left.cwiseQuotient(vector_right);\n}\n\ntemplate <typename T>\nEigen::Map<DynVector<T>> vector_from_array(T* array, const uint m) {\n    return Eigen::Map<DynVector<T>>(array, m);\n}\n\ntemplate <typename VectorType>\ndecltype(auto) subvector(VectorType&& vector, const uint start_row, const uint size_row) {\n    return vector.segment(start_row, size_row);\n}\n\ntemplate <typename T, int m, int n = m, int SO = Eigen::StorageOptions::RowMajor>\nEigen::Map<Eigen::Matrix<T, m, n, SO>> reshape(const StatVector<T, m * n>& vector) {\n    return Eigen::Map<Eigen::Matrix<T, m, n, SO>>(const_cast<T*>(vector.data()), m, n);\n}\n\ntemplate <typename T, int m, int SO = Eigen::StorageOptions::RowMajor>\nEigen::Map<Eigen::Matrix<T, m, Eigen::Dynamic, SO>> reshape(const DynVector<T>& vector, const int n) {\n    return Eigen::Map<Eigen::Matrix<T, m, Eigen::Dynamic, SO>>(const_cast<T*>(vector.data()), m, n);\n}\n\ntemplate <typename T, int SO = Eigen::StorageOptions::RowMajor>\nEigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, SO>> reshape(const DynVector<T>& vector,\n                                                                         const int m,\n                                                                         const int n) {\n    return Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, SO>>(const_cast<T*>(vector.data()), m, n);\n}\n\n/* Matrix Operations */\ntemplate <typename MatrixType>\nuint rows(const MatrixType& matrix) {\n    return matrix.rows();\n}\n\ntemplate <typename MatrixType>\nuint columns(const MatrixType& matrix) {\n    return matrix.cols();\n}\n\ntemplate <typename MatrixType>\ndecltype(auto) submatrix(MatrixType&& matrix,\n                         const uint start_row,\n                         const uint start_col,\n                         const uint size_row,\n                         const uint size_col) {\n    return matrix.block(start_row, start_col, size_row, size_col);\n}\n\ntemplate <typename MatrixType>\ndecltype(auto) row(MatrixType&& matrix, const uint row) {\n    return matrix.row(row);\n}\n\ntemplate <typename MatrixType>\ndecltype(auto) column(MatrixType&& matrix, const uint col) {\n    return matrix.col(col);\n}\n\ntemplate <typename MatrixType>\ndecltype(auto) determinant(MatrixType& matrix) {\n    return matrix.determinant();\n}\n\ntemplate <typename MatrixType>\ndecltype(auto) inverse(MatrixType& matrix) {\n    return matrix.inverse();\n}\n\ntemplate <typename T, int m, int n = m, int SO = Eigen::StorageOptions::RowMajor>\nStatVector<T, m * n> flatten(const StatMatrix<T, m, n>& matrix) {\n    StatVector<T, m * n> ret;\n    Eigen::Map<Eigen::Matrix<double, m, n, SO>>(ret.data(), m, n) = matrix;\n    return ret;\n}\n\ntemplate <typename T, int m, int SO = Eigen::StorageOptions::RowMajor>\nDynVector<T> flatten(const HybMatrix<T, m>& matrix) {\n    uint n = matrix.cols();\n\n    DynVector<T> ret(m * n);\n    Eigen::Map<Eigen::Matrix<double, m, Eigen::Dynamic, SO>>(ret.data(), m, n) = matrix;\n    return ret;\n}\n\ntemplate <typename T, int SO = Eigen::StorageOptions::RowMajor>\nDynVector<T> flatten(const DynMatrix<T>& matrix) {\n    uint m = matrix.rows();\n    uint n = matrix.cols();\n\n    DynVector<T> ret(m * n);\n    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, SO>>(ret.data(), m, n) = matrix;\n    return ret;\n}\n\ntemplate <typename T, int SO = Eigen::StorageOptions::RowMajor>\nvoid flatten(const DynMatrix<T>& matrix, T* mem) {\n    uint m                                                                           = matrix.rows();\n    uint n                                                                           = matrix.cols();\n    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, SO>>(mem, m, n) = matrix;\n}\n\n/* Solving Linear System */\ntemplate <typename MatrixType, typename ArrayType>\nvoid solve_sle(MatrixType& A, ArrayType& B) {\n    B = A.fullPivLu().solve(B);\n}\n\ntemplate <typename ArrayType, typename T>\nvoid solve_sle(SparseMatrix<T>& A_sparse, ArrayType& B) {\n    Eigen::SparseLU<SparseMatrix<T>> solver;\n    solver.analyzePattern(A_sparse);\n    solver.factorize(A_sparse);\n    B = solver.solve(B);\n}\n\n#endif", "meta": {"hexsha": "481fc4d699b7ad41167d3a8d6f7159d38e18215b", "size": 7273, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/utilities/linear_algebra/use_eigen.hpp", "max_stars_repo_name": "bremerm31/dgswemv2", "max_stars_repo_head_hexsha": "5ddddfdf1b5f51e9dbc348f2e69f187546649957", "max_stars_repo_licenses": ["MIT"], "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/utilities/linear_algebra/use_eigen.hpp", "max_issues_repo_name": "bremerm31/dgswemv2", "max_issues_repo_head_hexsha": "5ddddfdf1b5f51e9dbc348f2e69f187546649957", "max_issues_repo_licenses": ["MIT"], "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/utilities/linear_algebra/use_eigen.hpp", "max_forks_repo_name": "bremerm31/dgswemv2", "max_forks_repo_head_hexsha": "5ddddfdf1b5f51e9dbc348f2e69f187546649957", "max_forks_repo_licenses": ["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.1814159292, "max_line_length": 119, "alphanum_fraction": 0.6748246941, "num_tokens": 1761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.5701156034383666}}
{"text": "#include <boost/random/mersenne_twister.hpp>\n#include <boost/random.hpp>\n#include <boost/random/binomial_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include \"GenRandomNetworkMapFunction.h\"\n#include \"core/Hash.h\"\n\nGenRandomNetworkMapFunction::GenRandomNetworkMapFunction(\n  uint64_t _numVertices, double _edgeProbability, uint64_t _maxNeighbors,\n  uint64_t _mypeerid, uint64_t _numPeers)\n  : numVertices(_numVertices), edgeProbability(_edgeProbability),\n    maxNeighbors(_maxNeighbors), mypeerid(_mypeerid), numPeers(_numPeers) {\n}\n\n\n/**\n   Each mapper should run exactly one instance of this map function; we assume\n   that the function is kick-started by a single <mapper ID / # mappers> pair.\n\n   Each map function is responsible for generating the adjacency lists for\n   a disjoint set of approximately (numVertices / numPeers) vertices.\n\n   The vertex structures output by the map function are an array of the\n   following form:\n\n   <numNeighbors (uint64_t), firstNeighborID (uint64_t), ..., lastNeighborID\n   (uint64_t), vertexPageRankValue (double)>\n\n */\nvoid GenRandomNetworkMapFunction::map(KeyValuePair& kvPair,\n                                      KVPairWriterInterface& writer) {\n  uint64_t *pMapperID = (uint64_t*) kvPair.getKey();\n  uint64_t *pNumMappers = (uint64_t*) kvPair.getValue();\n\n  uint64_t maxAdjListSize = (numVertices < maxNeighbors) ?\n                                              numVertices : maxNeighbors;\n\n  // Need two additional slots to store the number of neighbors and the node's\n  // initial PageRank\n  uint64_t *outputValue = new uint64_t[maxAdjListSize + 2];\n\n  srand48(Timer::posixTimeInMicros() * getpid());\n\n  // partition at node level Determine the portion of the vertex space for\n  // which this node is responsible\n  uint64_t numVerticesPerPeer = numVertices / numPeers;\n  if (numVertices % numPeers != 0) {\n    numVerticesPerPeer++;\n  }\n\n  uint64_t nodeBeginningVertex = mypeerid * numVerticesPerPeer;\n  uint64_t nodeEndingVertex = nodeBeginningVertex + numVerticesPerPeer;\n\n  if (nodeEndingVertex > numVertices) {\n    nodeEndingVertex = numVertices;\n  }\n\n  // Determine the range of vertex IDs that this map function is responsible\n  // for generating\n  uint64_t numVerticesAtThisNode = nodeEndingVertex - nodeBeginningVertex;\n  uint64_t numVerticesPerMapper = numVerticesAtThisNode / (*pNumMappers);\n  if (numVerticesAtThisNode % (*pNumMappers) != 0) {\n    numVerticesPerMapper++;\n  }\n  uint64_t beginningVertex = nodeBeginningVertex + (*pMapperID) *\n    numVerticesPerMapper;\n\n  uint64_t endingVertex = beginningVertex + numVerticesPerMapper;\n\n  if (endingVertex > nodeEndingVertex) {\n    endingVertex = nodeEndingVertex;\n  }\n\n  unsigned short nrandBuf[3];\n  nrandBuf[0] = (unsigned short) Timer::posixTimeInMicros();\n  nrandBuf[1] = (unsigned short) getpid();\n  nrandBuf[2] = (unsigned short) *pMapperID;\n\n  // We will draw the number of edges from a binomial distribution so that the\n  // probability that any two vertices are connected by an edge is roughly\n  // equal to edgeProbability\n\n  boost::mt19937 mersenneTwister;\n  boost::binomial_distribution<> binomialDistribution(\n    numVertices, edgeProbability);\n  boost::variate_generator<boost::mt19937&, boost::binomial_distribution<> >\n    nextBinomialValue(mersenneTwister, binomialDistribution);\n\n  for (uint64_t i = beginningVertex; i < endingVertex; i++) {\n    uint64_t numEdges = 0;\n\n    if ((int) edgeProbability == 1) {\n      // If edge probability is 1, generate maxNeighbors random neighbors\n      numEdges = maxAdjListSize;\n    } else {\n      // Draw the number of edges from the binomial distribution\n      numEdges = std::min<uint64_t>(nextBinomialValue(), maxAdjListSize);\n    }\n\n    for (uint64_t j = 1; j <= numEdges; j++) {\n      uint32_t neighbor = nrand48(nrandBuf) % numVertices;\n      outputValue[j] = Hash::hash(neighbor);\n    }\n\n    double initialPageRank = 1.0 / numVertices;\n    outputValue[0] = numEdges;\n    memcpy(&outputValue[numEdges + 1], &initialPageRank, sizeof(double));\n\n    KeyValuePair outputKVPair;\n    uint64_t key = Hash::hash(i);\n\n    outputKVPair.setKey(reinterpret_cast<const uint8_t *>(&key),\n                                                sizeof(uint64_t));\n    outputKVPair.setValue(reinterpret_cast<const uint8_t *>(outputValue),\n                                 (numEdges + 2) * sizeof(uint64_t));\n\n    writer.write(outputKVPair);\n  }\n\n  delete[] outputValue;\n}\n", "meta": {"hexsha": "19a598ce75bd98b54153a0768cbfd09a102ef7ba", "size": 4439, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tritonsort/mapreduce/functions/map/GenRandomNetworkMapFunction.cc", "max_stars_repo_name": "anku94/themis_tritonsort", "max_stars_repo_head_hexsha": "68fd3e2f1c0b2947e187151a2e9717f6b9b0ed0d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-12-14T05:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T22:02:32.000Z", "max_issues_repo_path": "src/tritonsort/mapreduce/functions/map/GenRandomNetworkMapFunction.cc", "max_issues_repo_name": "anku94/themis_tritonsort", "max_issues_repo_head_hexsha": "68fd3e2f1c0b2947e187151a2e9717f6b9b0ed0d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tritonsort/mapreduce/functions/map/GenRandomNetworkMapFunction.cc", "max_forks_repo_name": "anku94/themis_tritonsort", "max_forks_repo_head_hexsha": "68fd3e2f1c0b2947e187151a2e9717f6b9b0ed0d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-12-22T19:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-15T12:09:00.000Z", "avg_line_length": 36.0894308943, "max_line_length": 78, "alphanum_fraction": 0.7129984231, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5701156004541746}}
{"text": "// Boost.Geometry\n// Unit Test\n\n// Copyright (c) 2016-2021 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Copyright (c) 2018 Adeel Ahmad, Islamabad, Pakistan.\n\n// Contributed and/or modified by Adeel Ahmad, as part of Google Summer of Code 2018 program\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <sstream>\n\n#include \"test_formula.hpp\"\n#include \"inverse_cases.hpp\"\n#include \"inverse_cases_antipodal.hpp\"\n#include \"inverse_cases_small_angles.hpp\"\n\n#include <boost/geometry/formulas/karney_inverse.hpp>\n\n#include <boost/geometry/srs/spheroid.hpp>\n\n#include <boost/geometry/util/math.hpp>\n\nvoid test_all(expected_results const& results)\n{\n    double lon1d = results.p1.lon * bg::math::d2r<double>();\n    double lat1d = results.p1.lat * bg::math::d2r<double>();\n    double lon2d = results.p2.lon * bg::math::d2r<double>();\n    double lat2d = results.p2.lat * bg::math::d2r<double>();\n\n    // WGS84\n    bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);\n\n    bg::formula::result_inverse<double> result_k;\n\n    typedef bg::formula::karney_inverse<double, true, true, true, true, true> ka_t;\n    result_k = ka_t::apply(lon1d, lat1d, lon2d, lat2d, spheroid);\n    result_k.azimuth *= bg::math::r2d<double>();\n    result_k.reverse_azimuth *= bg::math::r2d<double>();\n    check_inverse(\"karney\", results, result_k, results.vincenty, results.reference, 0.0000001);\n}\n\ntemplate <typename ExpectedResults>\nvoid test_karney(ExpectedResults const& results)\n{\n    double lon1d = results.p1.lon * bg::math::d2r<double>();\n    double lat1d = results.p1.lat * bg::math::d2r<double>();\n    double lon2d = results.p2.lon * bg::math::d2r<double>();\n    double lat2d = results.p2.lat * bg::math::d2r<double>();\n\n\n    // WGS84\n    bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);\n\n    bg::formula::result_inverse<double> result;\n\n    typedef bg::formula::karney_inverse<double, true, true, true, true, true> ka_t;\n    result = ka_t::apply(lon1d, lat1d, lon2d, lat2d, spheroid);\n    result.azimuth *= bg::math::r2d<double>();\n    result.reverse_azimuth *= bg::math::r2d<double>();\n    check_inverse(\"karney\", results, result, results.karney, results.karney, 0.0000001);\n}\n\nint test_main(int, char*[])\n{\n    for (size_t i = 0; i < expected_size; ++i)\n    {\n        test_all(expected[i]);\n    }\n\n    for (size_t i = 0; i < expected_size_antipodal; ++i)\n    {\n        test_karney(expected_antipodal[i]);\n    }\n\n    for (size_t i = 0; i < expected_size_small_angles; ++i)\n    {\n        test_karney(expected_small_angles[i]);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "d506d54ed4b4f0c1c5ab5a9df8d81d1fa42caf37", "size": 2844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/geometry/test/formulas/inverse_karney.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/geometry/test/formulas/inverse_karney.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "console/src/boost_1_78_0/libs/geometry/test/formulas/inverse_karney.cpp", "max_forks_repo_name": "vany152/FilesHash", "max_forks_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 31.6, "max_line_length": 95, "alphanum_fraction": 0.6912798875, "num_tokens": 840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5701155982720774}}
{"text": "//\n// Created by kerail on 10.07.16.\n//\n#include \"geom/SO3.hpp\"\n\n#define BOOST_TEST_MODULE boost_test_so3\n#define BOOST_TEST_LOG_LEVEL all\n#include <boost/test/unit_test.hpp>\n\nusing Eigen::Quaterniond;\nusing Eigen::Vector3d;\nusing Eigen::AngleAxisd;\n\nBOOST_AUTO_TEST_CASE(test_so3) {\n  const double tol = 1e-5;\n  boost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_messages);\n\n  for (double i = -1; i <= 1; i += 1) {\n    for (double j = -1; j <= 1; j += 1) {\n      for (double k = -1; k <= 1; k += 1) {\n        for (double a = -2; a <= 2; a += 0.5) {\n          Vector3d axisAngle(i, j, k);\n          if (fabs(i) + fabs(j) + fabs(k) > 0) {\n            axisAngle.normalize();\n          }\n          double angle = M_PI * a;\n\n          BOOST_TEST_MESSAGE(\"Axis:\\n\" << axisAngle << \"\\n\");\n          BOOST_TEST_MESSAGE(\"Angle:\\n\" << angle << \"\\n\");\n\n          BOOST_TEST_MESSAGE(\n              \"Rotation SO3:\\n\" << axisAngle * angle << \" \\nNorm: \" << (axisAngle * angle).norm() << \"\\n\");\n\n          SO3d so3(axisAngle * angle);\n\n          Quaterniond q(AngleAxisd(angle, axisAngle));\n          q.normalize();\n\n          SO3d so3FromQ(q);\n\n          Quaterniond rotationQ = so3.getQuaternion();\n\n          Quaterniond rotationQinv = so3.inverted().getQuaternion();\n          Quaterniond qInv = q.inverse();\n\n          BOOST_TEST_MESSAGE(\"Rotation from so3:\\n\" << rotationQ.coeffs() << \"\\n\");\n          BOOST_TEST_MESSAGE(\"Rotation from q:\\n\" << q.coeffs() << \"\\n\");\n\n          bool t1 = (rotationQ.coeffs() - q.coeffs()).norm() < tol;\n          bool t2 = (rotationQ.coeffs() + q.coeffs()).norm() < tol;\n\n          BOOST_REQUIRE(t1 || t2);\n\n          bool t3 = (rotationQinv.coeffs() - qInv.coeffs()).norm() < tol;\n          bool t4 = (rotationQinv.coeffs() + qInv.coeffs()).norm() < tol;\n\n          BOOST_REQUIRE(t3 || t4);\n\n          BOOST_TEST_MESSAGE(\"SO3:\\n\" << so3.coeffs() << \"\\n\");\n          BOOST_TEST_MESSAGE(\"SO3 from q:\\n\" << so3FromQ.coeffs() << \"\\n\");\n\n//          BOOST_REQUIRE((so3FromQ.coeffs() - so3.coeffs()).norm() < tol);\n          bool t5 = (so3FromQ.getQuaternion().coeffs() - so3.getQuaternion().coeffs()).norm() < tol;\n          bool t6 = (so3FromQ.getQuaternion().coeffs() + so3.getQuaternion().coeffs()).norm() < tol;\n          BOOST_REQUIRE(t5 || t6);\n\n          for (double i2 = -1; i2 <= 1; i2 += 1) {\n            for (double j2 = -1; j2 <= 1; j2 += 1) {\n              for (double k2 = -1; k2 <= 1; k2 += 1) {\n                Vector3d v(i2, j2, k2);\n\n                Vector3d checkVector = q.toRotationMatrix() * v;\n\n                Vector3d rotatedVecByFunc = so3.rotateVector(v);\n                Vector3d rotatedVecByMatrix = so3.getMatrix() * v;\n\n                BOOST_TEST_MESSAGE(\"Check vector:\\n \" << checkVector << \"\\n\\n\");\n                BOOST_TEST_MESSAGE(\"Check rotatedVecByFunc:\\n \" << rotatedVecByFunc << \"\\n\");\n                BOOST_TEST_MESSAGE(\"Check rotationMatrix so3:\\n \" << so3.getMatrix() << \"\\n\");\n                BOOST_TEST_MESSAGE(\"Check rotationMatrix q:\\n \" << q.toRotationMatrix() << \"\\n\");\n                BOOST_TEST_MESSAGE(\"Check rotatedVecByMatrix:\\n \" << rotatedVecByMatrix << \"\\n\");\n\n                BOOST_REQUIRE((rotatedVecByFunc - checkVector).norm() < tol);\n                BOOST_REQUIRE((rotatedVecByMatrix - checkVector).norm() < tol);\n\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n\n//  cout << \"Original vector: \" << v << endl << endl;\n//  cout << \"Rotate vector by func: \" << endl << so3.rotateVector(v) << endl << endl;\n//  cout << \"Rotation matrix: \" << endl << so3.getMatrix() << endl << endl;\n//  cout << \"Rotate vector by matrix: \" << endl << (so3.getMatrix()*v) << endl << endl;\n//  cout << \"Rotate vector by quaternion: \" << endl << (so3.getQuaternion().toRotationMatrix()*v) << endl << endl;\n//  cout << \"Rotate vector by test quaternion: \" << endl << (q.toRotationMatrix()*v) << endl << endl;\n}", "meta": {"hexsha": "f9caf03cf2a3e93bb5db1830be2bd8532cf2b7e1", "size": 3914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geom/test/test_so3.cpp", "max_stars_repo_name": "kerail/Daisu", "max_stars_repo_head_hexsha": "d028dd44bf94c3a94897b508beae4efc384bffd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geom/test/test_so3.cpp", "max_issues_repo_name": "kerail/Daisu", "max_issues_repo_head_hexsha": "d028dd44bf94c3a94897b508beae4efc384bffd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geom/test/test_so3.cpp", "max_forks_repo_name": "kerail/Daisu", "max_forks_repo_head_hexsha": "d028dd44bf94c3a94897b508beae4efc384bffd0", "max_forks_repo_licenses": ["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.7524752475, "max_line_length": 114, "alphanum_fraction": 0.5493101686, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5701155978710302}}
{"text": "\n#include <NTL/FacVec.h>\n#include <NTL/ZZ.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\nNTL_vector_impl(IntFactor,vec_IntFactor)\n\nstatic\nvoid swap(IntFactor& x, IntFactor& y)\n{\n   IntFactor t;\n\n   t = x;  x = y;  y = t;\n}\n\nstatic\nvoid FindMin(FacVec& v, long lo, long hi)\n{\n   long minv = 0;\n   long minp = -1;\n   long i;\n\n   for (i = lo; i <= hi; i++) {\n      if (minv == 0 || v[i].val < minv) {\n         minv = v[i].val;\n         minp = i;\n      }\n   }\n\n   swap(v[lo], v[minp]);\n}\n\n\nvoid FactorInt(FacVec& fvec, long n)\n{\n   if (n <= 1) Error(\"internal error: FactorInt(FacVec,long n) with n<=1\");\n\n   if (NTL_OVERFLOW(n, 1, 0))\n      Error(\"internal error: FactorInt(FacVec,long n) with n too large\");\n\n   long NumFactors;\n   long q;\n\n   fvec.SetLength(2*NextPowerOfTwo(n));\n\n   NumFactors = 0;\n   q = 2;\n\n   while (n != 1) {\n      if (n%q == 0) {\n         fvec[NumFactors].q = q;\n         n = n/q;\n         fvec[NumFactors].a = 1;\n         fvec[NumFactors].val = q;\n         while (n%q == 0) {\n            n = n/q;\n            (fvec[NumFactors].a)++;\n            fvec[NumFactors].val *= q;\n         }         \n         fvec[NumFactors].link = -1;\n         NumFactors++;\n      }\n\n      q++;\n   }\n\n   fvec.SetLength(2*NumFactors-1);\n\n   long lo = 0;\n   long hi = NumFactors - 1;\n\n   while (lo < hi) {\n      FindMin(fvec, lo, hi);\n      FindMin(fvec, lo+1, hi);\n      hi++;\n      fvec[hi].link = lo;\n      fvec[hi].val = fvec[lo].val * fvec[lo+1].val;\n      lo += 2;\n   }\n}\n\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "fc24bdff248c12694e6f147f68fbb780fbf3de10", "size": 1487, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/FacVec.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RUNETag/WinNTL/src/FacVec.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/src/FacVec.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 16.8977272727, "max_line_length": 75, "alphanum_fraction": 0.5016812374, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.6992544335934765, "lm_q1q2_score": 0.5700549388668484}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <pybind11/stl.h>\n\n#include <Eigen/Dense>\n#include <sophus/se3.hpp>\n\n#include <kontiki/trajectories/uniform_se3_spline_trajectory.h>\n#include \"trajectory_helper.h\"\n#include \"spline_helpers.h\"\n\nnamespace py = pybind11;\n\nnamespace TT = kontiki::trajectories;\n\n\nstruct PySE3SplineHelper {\n  using PyControlPointType = Eigen::Matrix4d;\n\n  static Eigen::Matrix4d ConvertCppToPy(const Sophus::SE3d & cp) {\n    return cp.matrix();\n  }\n\n  static Sophus::SE3d ConvertPyToCpp(const Eigen::Matrix4d& cp) {\n    ValidateSE3Element(cp); // Throws domain_error on error\n    return Sophus::SE3d(cp);\n  }\n\n  static void ValidateSE3Element(const Eigen::Matrix4d &cp) {\n    double eps = Sophus::Constants<double>::epsilon();\n    Eigen::Matrix3d R = cp.topLeftCorner(3, 3);\n    if (std::abs<double>(R.determinant() - 1) >= eps) {\n      throw std::domain_error(\"Rotation matrix determinant is not 1!\");\n    }\n    else if ((cp.row(3) - Eigen::Matrix<double, 1, 4>(0, 0, 0, 1)).squaredNorm() >= eps) {\n      throw std::domain_error(\"Final row must be [0, 0, 0, 1]\");\n    }\n  }\n};\n\n\nPYBIND11_MODULE(_uniform_se3_spline_trajectory, m) {\n  m.doc() = \"Uniform splined trajectory in SE3\";\n\n  using Class = TT::UniformSE3SplineTrajectory;\n  using Helper = PySE3SplineHelper;\n  auto cls = py::class_<Class, std::shared_ptr<Class>>(m, \"UniformSE3SplineTrajectory\");\n  cls.doc() = R\"pbdoc( A spline with control points in SE(3)\n\n  Control points are 4x4 matrices T = [R, p; 0, 1].\n  )pbdoc\";\n\n  cls.def(\"evaluate\", [](Class &self, double t){\n    Sophus::SE3d P_SE3;\n    Eigen::Matrix4d P, P_prim, P_bis;\n    self.EvaluateSpline(t, 0xff, P_SE3, P_prim, P_bis);\n    P = P_SE3.matrix();\n\n    return std::make_tuple(P, P_prim, P_bis);\n  });\n\n\n  // Common attributes\n  declare_spline_common<Class, Helper>(cls);\n  declare_trajectory_common<Class>(cls);\n\n} // PYBIND11_MODULE", "meta": {"hexsha": "22eede5a49cd5630cc63d22a77eab7dd3265f728", "size": 1904, "ext": "cc", "lang": "C++", "max_stars_repo_path": "python/src/kontiki/trajectories/py_uniform_se3_spline_trajectory.cc", "max_stars_repo_name": "copark86/kontiki", "max_stars_repo_head_hexsha": "431349f9500c6ee954bc46c0643f49281163a7f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 94.0, "max_stars_repo_stars_event_min_datetime": "2018-06-19T05:59:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:25:29.000Z", "max_issues_repo_path": "python/src/kontiki/trajectories/py_uniform_se3_spline_trajectory.cc", "max_issues_repo_name": "copark86/kontiki", "max_issues_repo_head_hexsha": "431349f9500c6ee954bc46c0643f49281163a7f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-23T06:52:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T15:27:11.000Z", "max_forks_repo_path": "python/src/kontiki/trajectories/py_uniform_se3_spline_trajectory.cc", "max_forks_repo_name": "hovren/kontiki", "max_forks_repo_head_hexsha": "4c44edb7ef041c6abd549e1fe66fe3e9ca255399", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T12:10:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T18:34:13.000Z", "avg_line_length": 28.4179104478, "max_line_length": 90, "alphanum_fraction": 0.6885504202, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083132, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5700549298167997}}
{"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": "#ifndef SEGMENT_3D_HPP\n#define SEGMENT_3D_HPP\n\n#include <vector>\n#include <Eigen/Dense>\n\nstruct Segment3D\n{\n    Eigen::Vector3d pt0, pt1;\n\n    Segment3D(const Eigen::Vector3d& p0, const Eigen::Vector3d& p1) : pt0(p0), pt1(p1) { }\n\n    void generate_data(std::vector<Eigen::Vector3d>& data, int num_points)\n    {\n        Eigen::Vector3d v = pt1 - pt0;\n        for(int i = 0; i < num_points; ++i)\n        {\n            data.push_back(pt0 + ((1.0/(num_points-1))*i)*v);\n        }\n    }\n};\n\n#endif // SEGMENT_3D_HPP\n", "meta": {"hexsha": "59c5b8dd578fd2e70121e9938df9a3edd46c81dc", "size": 512, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry/Segment3D.hpp", "max_stars_repo_name": "myirci/3d_circle_estimation", "max_stars_repo_head_hexsha": "7161005ab14d510503310e0bb028fea5ad2a1389", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-07-16T18:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T01:25:54.000Z", "max_issues_repo_path": "geometry/Segment3D.hpp", "max_issues_repo_name": "myirci/3d_circle_estimation", "max_issues_repo_head_hexsha": "7161005ab14d510503310e0bb028fea5ad2a1389", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry/Segment3D.hpp", "max_forks_repo_name": "myirci/3d_circle_estimation", "max_forks_repo_head_hexsha": "7161005ab14d510503310e0bb028fea5ad2a1389", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-08T13:49:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T13:49:32.000Z", "avg_line_length": 21.3333333333, "max_line_length": 90, "alphanum_fraction": 0.603515625, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5699215010433318}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE fold\n#include <boost/test/unit_test.hpp>\n\n#include <type_traits>\n#include \"foldr.hpp\"\n#include \"foldl.hpp\"\n\ntemplate<typename left, typename right>\nstruct max;\n\ntemplate<typename int_type, int_type left, int_type right>\nstruct max<std::integral_constant<int_type, left>, std::integral_constant<int_type, right>>\n{\n\tusing type = std::integral_constant<int_type, left < right ? right : left>;\n};\n\ntemplate<typename List, typename Type> struct append;\n\ntemplate<template<typename...> class List, typename... Types, typename Type>\nstruct append<List<Types...>, Type>\n{\n\tusing type = List<Types..., Type>;\n};\n\ntemplate<typename...> struct list_t;\n\nBOOST_AUTO_TEST_CASE(fold_max_test)\n{\n\tusing list1 =\n\t\tstd::tuple<\n\t\t\tstd::integral_constant<unsigned, 1>,\n\t\t\tstd::integral_constant<unsigned, 2>,\n\t\t\tstd::integral_constant<unsigned, 3>,\n\t\t\tstd::integral_constant<unsigned, 4>,\n\t\t\tstd::integral_constant<unsigned, 5>,\n\t\t\tstd::integral_constant<unsigned, 6>\n\t\t>;\n\n\tBOOST_CHECK( (meta::foldr<max, std::integral_constant<unsigned,0>, list1>::type::value == 6) );\n\tBOOST_CHECK( (meta::foldl<max, std::integral_constant<unsigned,0>, list1>::type::value == 6) );\n}\n\nBOOST_AUTO_TEST_CASE(fold_append_test)\n{\n\tusing list2 = std::tuple<int,float, double>;\n\tBOOST_CHECK( (\n\t\tstd::is_same<\n\t\t\ttypename meta::foldl<append, std::tuple<>, list2>::type,\n\t\t\tstd::tuple<int, float, double>\n\t\t>::value == true\n\t) );\n}\n", "meta": {"hexsha": "c5a336fe960b0da613f766e4adc2c24d3a9b8d24", "size": 1446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_fold.cpp", "max_stars_repo_name": "wickedmic/multidispatch-lib", "max_stars_repo_head_hexsha": "d30b031e99fc3d911bc7fc9c0ff43e0fa869e33e", "max_stars_repo_licenses": ["MIT"], "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_fold.cpp", "max_issues_repo_name": "wickedmic/multidispatch-lib", "max_issues_repo_head_hexsha": "d30b031e99fc3d911bc7fc9c0ff43e0fa869e33e", "max_issues_repo_licenses": ["MIT"], "max_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_fold.cpp", "max_forks_repo_name": "wickedmic/multidispatch-lib", "max_forks_repo_head_hexsha": "d30b031e99fc3d911bc7fc9c0ff43e0fa869e33e", "max_forks_repo_licenses": ["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.7777777778, "max_line_length": 96, "alphanum_fraction": 0.7219917012, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5699214962636622}}
{"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": "#include <PCP/Common/Option.h>\n#include <PCP/Common/Log.h>\n#include <PCP/Common/Progress.h>\n#include <PCP/Common/String.h>\n\n#include <PCP/Geometry/Geometry.h>\n#include <PCP/Geometry/PLY.h>\n\n#include <PCP/SpacePartitioning/KdTree.h>\n\n#include <Ponca/Fitting>\n\n#include <Eigen/Eigenvalues>\n\nusing namespace pcp;\n\nusing WeightKernel = Ponca::SmoothWeightKernel<Scalar>;\nusing WeightFunc   = Ponca::DistWeightFunc<ConstPoint, WeightKernel>;\nusing SphereFit    = Ponca::Basket<ConstPoint, WeightFunc, Ponca::OrientedSphereFit>;\n\nint main(int argc, char *argv[])\n{\n    Option opt(argc, argv);\n    const String in_input  = opt.get_string(\"input\",  \"i\").set_required();\n    const String in_output = opt.get_string(\"output\", \"o\").set_default(\"output\");\n    const Scalar in_scale  = opt.get_float( \"scale\"     ).set_default(0.01);\n    const int    in_iter   = opt.get_int(   \"iter\"      ).set_default(30);\n    const int    in_every  = opt.get_int(   \"every\"     ).set_default(30);\n\n    bool ok = opt.ok();\n    if(!ok) return 1;\n    info() << opt;\n\n    Geometry g;\n    ok = PLY::load(in_input, g);\n    if(!ok) return 1;\n    PCP_ASSERT(g.has_normals());\n    Geometry g2 = g;\n\n    const auto aabb = g.aabb();\n    const auto aabb_diag = aabb.diagonal().norm();\n    const auto radius = in_scale * aabb_diag;\n    info() << \"radius = \" << radius;\n\n    auto prog = Progress(in_iter);\n    const int digits = std::to_string(in_iter).size();\n\n    for(int iter=1; iter<=in_iter; ++iter)\n    {\n        g.build_kdtree();\n\n        #pragma omp parallel for\n        for(int i=0; i<g.size(); ++i)\n        {\n            SphereFit fit;\n            fit.setWeightFunc(WeightFunc(radius));\n            fit.init(g[i]);\n\n            for(int j : g.kdtree().range_neighbors(g[i], radius))\n            {\n                fit.addNeighbor(g.at(j));\n            }\n\n            const auto status = fit.finalize();\n\n            if(status == Ponca::STABLE)\n            {\n                // projection on the sphere\n                g2.point(i) = fit.project(g[i]);\n                g2.normal(i) = fit.primitiveGradient(g2.point(i)).normalized();\n\n                // re-orient if necessary\n                if(g2.normal(i).dot(g.normal(i)) < 0) g2.normal(i) *= -1;\n            }\n            else\n            {\n                warning() << \"Unstable fit at point \" << i;\n            }\n        }\n        std::swap(g, g2);\n\n        // save\n        if(iter % in_every == 0 || iter == in_iter)\n        {\n            PLY::save(in_output + \"_\" + str::to_string(iter,digits) + \".ply\", g, false);\n        }\n\n        ++prog;\n    }\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "ff1e68eeb3260b1cb1eb3e38e931206ae213e9cb", "size": 2591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "figures/app/Figures/ComputeFlowSphere.cpp", "max_stars_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_stars_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-29T18:19:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T12:42:52.000Z", "max_issues_repo_path": "figures/app/Figures/ComputeFlowSphere.cpp", "max_issues_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_issues_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-12T08:51:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T09:38:17.000Z", "max_forks_repo_path": "figures/app/Figures/ComputeFlowSphere.cpp", "max_forks_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_forks_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T08:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T11:40:21.000Z", "avg_line_length": 27.2736842105, "max_line_length": 88, "alphanum_fraction": 0.555769973, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5699214822072938}}
{"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* Author: Matthew Beauregard Smith                                             *\n* Affiliation: The University of Texas at Austin                               *\n* Department: Oden Institute and Institute for Cellular and Molecular Biology  *\n* PI: Edward Marcotte                                                          *\n* Project: Protein Fluorosequencing                                            *\n\\******************************************************************************/\n\n// Boost unit test framework (recommended to be the first include):\n#include <boost/test/unit_test.hpp>\n\n// File under test:\n#include \"log-normal-distribution-fitter.h\"\n\n// Standard C++ library headers:\n#include <cmath>\n\n// Local project headers:\n#include \"common/error-model.h\"\n\nnamespace whatprot {\n\nnamespace {\nusing boost::unit_test::tolerance;\nusing std::log;\nusing std::sqrt;\nconst double TOL = 0.000000001;\n}  // namespace\n\nBOOST_AUTO_TEST_SUITE(hmm_suite)\nBOOST_AUTO_TEST_SUITE(fit_suite)\nBOOST_AUTO_TEST_SUITE(log_normal_distribution_fitter_suite)\n\nBOOST_AUTO_TEST_CASE(constructor_test, *tolerance(TOL)) {\n    LogNormalDistributionFitter lndf;\n    BOOST_TEST(lndf.w_sum_log_x_over_n == 0.0);\n    BOOST_TEST(lndf.w_sum_log_x_over_n_sq == 0.0);\n    BOOST_TEST(lndf.total_weight == 0.0);\n}\n\nBOOST_AUTO_TEST_CASE(add_sample_once_n_eq_0_test, *tolerance(TOL)) {\n    LogNormalDistributionFitter lndf;\n    double x = 1.277;\n    int n = 0;\n    double w = 0.98;\n    lndf.add_sample(x, n, w);\n    BOOST_TEST(lndf.w_sum_log_x_over_n == 0.0);\n    BOOST_TEST(lndf.w_sum_log_x_over_n_sq == 0.0);\n    BOOST_TEST(lndf.total_weight == 0.0);\n}\n\nBOOST_AUTO_TEST_CASE(add_sample_once_x_eq_0_test, *tolerance(TOL)) {\n    LogNormalDistributionFitter lndf;\n    double x = 0.0;\n    int n = 1;\n    double w = 0.98;\n    lndf.add_sample(x, n, w);\n    BOOST_TEST(lndf.w_sum_log_x_over_n == 0.0);\n    BOOST_TEST(lndf.w_sum_log_x_over_n_sq == 0.0);\n    BOOST_TEST(lndf.total_weight == 0.0);\n}\n\nBOOST_AUTO_TEST_CASE(add_sample_once_n_eq_1_test, *tolerance(TOL)) {\n    LogNormalDistributionFitter lndf;\n    double x = 1.277;\n    int n = 1;\n    double w = 0.98;\n    lndf.add_sample(x, n, w);\n    BOOST_TEST(lndf.w_sum_log_x_over_n == log(x / (double)n) * w);\n    BOOST_TEST(lndf.w_sum_log_x_over_n_sq\n               == log(x / (double)n) * log(x / (double)n) * w);\n    BOOST_TEST(lndf.total_weight == w);\n}\n\nBOOST_AUTO_TEST_CASE(add_sample_once_n_gt_1_test, *tolerance(TOL)) {\n    LogNormalDistributionFitter lndf;\n    double x = 3.1415928;\n    int n = 3;\n    double w = 0.979;\n    lndf.add_sample(x, n, w);\n    BOOST_TEST(lndf.w_sum_log_x_over_n == log(x / (double)n) * w);\n    BOOST_TEST(lndf.w_sum_log_x_over_n_sq\n               == log(x / (double)n) * log(x / (double)n) * w);\n    BOOST_TEST(lndf.total_weight == w);\n}\n\nBOOST_AUTO_TEST_CASE(add_sample_twice_n_eq_1_test, *tolerance(TOL)) {\n    LogNormalDistributionFitter lndf;\n    double x1 = 1.277;\n    int n1 = 1;\n    double w1 = 0.98;\n    double x2 = 1.166;\n    int n2 = 1;\n    double w2 = 0.49;\n    lndf.add_sample(x1, n1, w1);\n    lndf.add_sample(x2, n2, w2);\n    BOOST_TEST(lndf.w_sum_log_x_over_n\n               == log(x1 / (double)n1) * w1 + log(x2 / (double)n2) * w2);\n    BOOST_TEST(lndf.w_sum_log_x_over_n_sq\n               == log(x1 / (double)n1) * log(x1 / (double)n1) * w1\n                          + log(x2 / (double)n2) * log(x2 / (double)n2) * w2);\n    BOOST_TEST(lndf.total_weight == w1 + w2);\n}\n\nBOOST_AUTO_TEST_CASE(add_sample_twice_n_gt_1_test, *tolerance(TOL)) {\n    LogNormalDistributionFitter lndf;\n    double x1 = 3.43;\n    int n1 = 3;\n    double w1 = 0.98;\n    double x2 = 4.91;\n    int n2 = 5;\n    double w2 = 0.49;\n    lndf.add_sample(x1, n1, w1);\n    lndf.add_sample(x2, n2, w2);\n    BOOST_TEST(lndf.w_sum_log_x_over_n\n               == log(x1 / (double)n1) * w1 + log(x2 / (double)n2) * w2);\n    BOOST_TEST(lndf.w_sum_log_x_over_n_sq\n               == log(x1 / (double)n1) * log(x1 / (double)n1) * w1\n                          + log(x2 / (double)n2) * log(x2 / (double)n2) * w2);\n    BOOST_TEST(lndf.total_weight == w1 + w2);\n}\n\nBOOST_AUTO_TEST_CASE(get_type_test, *tolerance(TOL)) {\n    LogNormalDistributionFitter lndf;\n    BOOST_TEST(lndf.get_type() == DistributionType::LOGNORMAL);\n}\n\nBOOST_AUTO_TEST_CASE(get_mu_one_sample_test, *tolerance(TOL)) {\n    LogNormalDistributionFitter lndf;\n    double x1 = 3.43;\n    int n1 = 3;\n    double w1 = 0.98;\n    lndf.add_sample(x1, n1, w1);\n    BOOST_TEST(lndf.get_mu() == log(x1 / (double)n1));\n}\n\nBOOST_AUTO_TEST_CASE(get_mu_two_samples_test, *tolerance(TOL)) {\n    LogNormalDistributionFitter lndf;\n    double x1 = 3.43;\n    int n1 = 3;\n    double w1 = 0.98;\n    double x2 = 4.91;\n    int n2 = 5;\n    double w2 = 0.49;\n    lndf.add_sample(x1, n1, w1);\n    lndf.add_sample(x2, n2, w2);\n    BOOST_TEST(lndf.get_mu()\n               == (log(x1 / (double)n1) * w1 + log(x2 / (double)n2) * w2)\n                          / (w1 + w2));\n}\n\nBOOST_AUTO_TEST_CASE(get_sigma_one_sample_test, *tolerance(TOL)) {\n    LogNormalDistributionFitter lndf;\n    double x1 = 3.43;\n    int n1 = 3;\n    double w1 = 0.98;\n    lndf.add_sample(x1, n1, w1);\n    double mu = lndf.get_mu();\n    BOOST_TEST(lndf.get_sigma()\n               == sqrt((log(x1 / n1) - mu) * (log(x1 / n1) - mu)));\n}\n\nBOOST_AUTO_TEST_CASE(get_sigma_two_samples_test, *tolerance(TOL)) {\n    LogNormalDistributionFitter lndf;\n    double x1 = 3.43;\n    int n1 = 3;\n    double w1 = 0.98;\n    double x2 = 4.91;\n    int n2 = 5;\n    double w2 = 0.49;\n    lndf.add_sample(x1, n1, w1);\n    lndf.add_sample(x2, n2, w2);\n    double mu = lndf.get_mu();\n    BOOST_TEST(lndf.get_sigma()\n               == sqrt(((log(x1 / n1) - mu) * (log(x1 / n1) - mu) * w1\n                        + (log(x2 / n2) - mu) * (log(x2 / n2) - mu) * w2)\n                       / (w1 + w2)));\n}\n\nBOOST_AUTO_TEST_SUITE_END()  // log_normal_distribution_fitter_suite\nBOOST_AUTO_TEST_SUITE_END()  // fit_suite\nBOOST_AUTO_TEST_SUITE_END()  // hmm_suite\n\n}  // namespace whatprot\n", "meta": {"hexsha": "6112cede84f62884c5a346d62af541865601b1bf", "size": 6059, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cc_code/src/hmm/fit/log-normal-distribution-fitter.test.cc", "max_stars_repo_name": "erisyon/whatprot", "max_stars_repo_head_hexsha": "176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cc_code/src/hmm/fit/log-normal-distribution-fitter.test.cc", "max_issues_repo_name": "erisyon/whatprot", "max_issues_repo_head_hexsha": "176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-12T00:50:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T17:59:12.000Z", "max_forks_repo_path": "cc_code/src/hmm/fit/log-normal-distribution-fitter.test.cc", "max_forks_repo_name": "erisyon/whatprot", "max_forks_repo_head_hexsha": "176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-11T19:34:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T19:34:43.000Z", "avg_line_length": 32.7513513514, "max_line_length": 80, "alphanum_fraction": 0.6050503383, "num_tokens": 1922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5698966290721843}}
{"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": "//\n// Copyright (c) 2019 INRIA\n//\n\n#include <pinocchio/autodiff/casadi.hpp>\n\n#include <pinocchio/math/quaternion.hpp>\n#include <pinocchio/spatial/se3.hpp>\n#include <pinocchio/spatial/motion.hpp>\n\n#include <boost/variant.hpp> // to avoid C99 warnings\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_se3)\n{\n  typedef pinocchio::SE3Tpl<casadi::SX> SE3;\n  SE3 M1 = SE3::Identity();\n  SE3 M2 = SE3::Random();\n  \n  SE3 M3 = M2 * M1;\n  SE3 M1inv = M1.inverse();\n}\n\nBOOST_AUTO_TEST_CASE(test_motion)\n{\n  typedef pinocchio::MotionTpl<casadi::SX> Motion;\n  Motion v1 = Motion::Zero();\n  Motion v2 = Motion::Random();\n  \n  Motion v3 = v1 + v2;\n}\n\nBOOST_AUTO_TEST_CASE(test_quaternion)\n{\n  typedef pinocchio::SE3Tpl<casadi::SX> SE3AD;\n  typedef pinocchio::SE3 SE3;\n  \n  SE3AD ad_M;\n  SE3AD::Matrix3 & ad_rot = ad_M.rotation();\n  \n  casadi::SX cs_rot = casadi::SX::sym(\"rot\", 3,3);\n  pinocchio::casadi::copy(cs_rot,ad_rot);\n  \n  SE3AD::Quaternion ad_quat;\n  pinocchio::quaternion::assignQuaternion(ad_quat,ad_rot);\n  \n  casadi::SX cs_quat(4,1);\n  pinocchio::casadi::copy(ad_quat.coeffs(),cs_quat);\n  \n  casadi::Function eval_quat(\"eval_quat\",\n                             casadi::SXVector {cs_rot},\n                             casadi::SXVector {cs_quat});\n  \n\n  for(int k = 0; k < 1e4; ++k)\n  {\n    SE3 M(SE3::Random());\n    SE3::Quaternion quat_ref(M.rotation());\n\n    casadi::DM vec_rot(3,3);\n    pinocchio::casadi::copy(M.rotation(),vec_rot);\n\n    casadi::DM quat_res = eval_quat(casadi::DMVector {vec_rot})[0];\n    SE3::Quaternion quat_value;\n    \n    quat_value.coeffs() = Eigen::Map<Eigen::Vector4d>(static_cast< std::vector<double> >(quat_res).data());\n    BOOST_CHECK(pinocchio::quaternion::defineSameRotation(quat_value,quat_ref));\n//    if(not quat_value.coeffs().isApprox(quat_ref.coeffs()))\n//    {\n//      std::cout << \"quat_value: \" << quat_value.coeffs().transpose() << std::endl;\n//      std::cout << \"quat_ref: \" << quat_ref.coeffs().transpose() << std::endl;\n//    }\n  }\n  \n  \n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f180494a16849a40123dcdf2a805840513609c56", "size": 2108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/casadi-spatial.cpp", "max_stars_repo_name": "ikalevatykh/pinocchio", "max_stars_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittest/casadi-spatial.cpp", "max_issues_repo_name": "ikalevatykh/pinocchio", "max_issues_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/casadi-spatial.cpp", "max_forks_repo_name": "ikalevatykh/pinocchio", "max_forks_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T14:29:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T14:29:02.000Z", "avg_line_length": 25.3975903614, "max_line_length": 107, "alphanum_fraction": 0.6589184061, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5698570883922309}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/included/unit_test.hpp>\n#include <srook/tmpl/vt/concat.hpp>\n#include <srook/tmpl/vt/foldl.hpp>\n#include <srook/tmpl/vt/foldr.hpp>\n#include <srook/tmpl/vt/reverse.hpp>\n#include <srook/tmpl/vt/max.hpp>\n#include <srook/tmpl/vt/filterD.hpp>\n#include <srook/tmpl/vt/bind.hpp>\n#include <srook/tmpl/vt/tt_proxy.hpp>\n#include <srook/tmpl/vt/sort/qsort.hpp>\n#include <srook/type_traits/is_same.hpp>\n#include <srook/cstdint.hpp>\n\nBOOST_AUTO_TEST_SUITE(srook_tmpl_vt_fold_test)\n\ntemplate <class L, class... R>\nstruct snoc : srook::tmpl::vt::concat<R..., L> {};\n\ntemplate <class Li, class X>\nstruct f\n    : srook::tmpl::vt::concat<\n        SROOK_DEDUCED_TYPENAME srook::tmpl::vt::concat<\n            SROOK_DEDUCED_TYPENAME srook::tmpl::vt::filterD<srook::tmpl::vt::bind<srook::tmpl::vt::tt_proxy<srook::tmpl::vt::lt>::template type, srook::tmpl::vt::placeholders::_1, X>, Li>::type, X\n        >::type,\n        SROOK_DEDUCED_TYPENAME srook::tmpl::vt::filterD<srook::tmpl::vt::bind<srook::tmpl::vt::geq, srook::tmpl::vt::placeholders::_1, X>, Li>::type\n    > {};\n      \nBOOST_AUTO_TEST_CASE(fold_test1)\n{\n    typedef srook::tmpl::vt::packer<srook::uint32_t, srook::uint8_t, srook::uint64_t, srook::uint16_t> type;\n\n    // reverse\n    typedef SROOK_DEDUCED_TYPENAME srook::tmpl::vt::foldr<snoc, srook::tmpl::vt::packer<>, type>::type rev;\n    SROOK_ST_ASSERT(srook::is_same<SROOK_DEDUCED_TYPENAME srook::tmpl::vt::reverse<type>::type, rev>::value);\n\n    // deriving the maximum type where `maximum` is defined by <srook/tmpl/vt/compare.hpp>\n    typedef SROOK_DEDUCED_TYPENAME srook::tmpl::vt::foldr<srook::tmpl::vt::max, srook::tmpl::vt::packer<>, type>::type maxi; \n    SROOK_ST_ASSERT(srook::is_same<srook::uint64_t, maxi>::value);\n\n    // insertion sort with foldl\n    typedef SROOK_DEDUCED_TYPENAME srook::tmpl::vt::foldl<f, srook::tmpl::vt::packer<>, type>::type isorted;\n    SROOK_ST_ASSERT(srook::is_same<SROOK_DEDUCED_TYPENAME srook::tmpl::vt::qsort<type>::type, isorted>::value);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "280ae17a28c3348c529aa2fdda5f38c725fa427c", "size": 2050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/tmpl/vt/fold.cpp", "max_stars_repo_name": "falgon/srookCppLibraries", "max_stars_repo_head_hexsha": "ebcfacafa56026f6558bcd1c584ec774cc751e57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-01T07:54:37.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-01T07:54:37.000Z", "max_issues_repo_path": "tests/tmpl/vt/fold.cpp", "max_issues_repo_name": "falgon/srookCppLibraries", "max_issues_repo_head_hexsha": "ebcfacafa56026f6558bcd1c584ec774cc751e57", "max_issues_repo_licenses": ["MIT"], "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/tmpl/vt/fold.cpp", "max_forks_repo_name": "falgon/srookCppLibraries", "max_forks_repo_head_hexsha": "ebcfacafa56026f6558bcd1c584ec774cc751e57", "max_forks_repo_licenses": ["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.6170212766, "max_line_length": 196, "alphanum_fraction": 0.7112195122, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317475, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5698570666766731}}
{"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": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"DCT.hpp\"\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/PeakDetection.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Eigen>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass CepstrumF0\n{\n\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n\n  CepstrumF0(index maxSize) : mCepstrumStorage(maxSize) {}\n\n  void init(index size)\n  {\n    // avoid allocation of maxSize^2 at constructor\n    mDCT = DCT(size, size);\n    mDCT.init(size, size);\n\n    mCepstrum = mCepstrumStorage.segment(0, size);\n    mCepstrum.setZero();\n  }\n\n  void processFrame(const RealVectorView& input, RealVectorView output,\n                    double minFreq, double maxFreq, double sampleRate)\n  {\n    using namespace Eigen;\n    using namespace std;\n    PeakDetection pd;\n\n    ArrayXd mag = _impl::asEigen<Array>(input);\n    ArrayXd logMag = mag.max(epsilon).log();\n    double  pitch = 0;\n    double  confidence = 0;\n    index   minBin = min<index>(lrint(sampleRate / maxFreq), mag.size());\n    index   maxBin = min<index>(lrint(sampleRate / minFreq), mag.size());\n\n    mDCT.processFrame(logMag, mCepstrum);\n\n    if (maxBin > minBin)\n    {\n      auto seg = mCepstrum.segment(minBin, maxBin - minBin);\n      auto vec = pd.process(mCepstrum.segment(minBin, maxBin - minBin), 1,\n                            seg.minCoeff());\n      if (vec.size() > 0)\n      {\n        pitch = sampleRate / (vec[0].first + minBin);\n        confidence = vec[0].second / mCepstrum[0];\n      }\n    }\n    output(0) = pitch;\n    output(1) = min(abs(confidence), 1.0);\n  }\n\nprivate:\n  DCT     mDCT{0, 0};\n  ArrayXd mCepstrumStorage;\n  ArrayXd mCepstrum;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "4b0df471f6eaf9788a6264529e6f10d348bf58f1", "size": 2179, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/CepstrumF0.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/CepstrumF0.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/CepstrumF0.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9012345679, "max_line_length": 74, "alphanum_fraction": 0.6691142726, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.569766635034677}}
{"text": "/**\n * @file stableevaluationatapoint.cc\n * @brief NPDE homework StableEvaluationAtAPoint\n * @author Am\u00e9lie 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 <Eigen/Core>\r\n#include <iostream>\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\ntemplate<typename Derived>\r\nEigen::Block<Derived, 2, 2>\r\ntopLeft2x2Corner(MatrixBase<Derived>& m)\r\n{\r\n  return Eigen::Block<Derived, 2, 2>(m.derived(), 0, 0);\r\n}\r\n\r\ntemplate<typename Derived>\r\nconst Eigen::Block<const Derived, 2, 2>\r\ntopLeft2x2Corner(const MatrixBase<Derived>& m)\r\n{\r\n  return Eigen::Block<const Derived, 2, 2>(m.derived(), 0, 0);\r\n}\r\n\r\nint main(int, char**)\r\n{\r\n  Matrix3d m = Matrix3d::Identity();\r\n  cout << topLeft2x2Corner(4*m) << endl; // calls the const version\r\n  topLeft2x2Corner(m) *= 2;              // calls the non-const version\r\n  cout << \"Now the matrix m is:\" << endl << m << endl;\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "1486a15cf414714cbdd66e7eedbf7d39cf1b6ef0", "size": 724, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/class_FixedBlock.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/class_FixedBlock.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/class_FixedBlock.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 25.8571428571, "max_line_length": 72, "alphanum_fraction": 0.6491712707, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.5697590620767852}}
{"text": "#ifndef __ECTS_CONTROL_ALGORITHM__\n#define __ECTS_CONTROL_ALGORITHM__\n\n#include <ros/ros.h>\n#include <Eigen/Dense>\n#include <math.h>\n#include <kdl/chainjnttojacsolver.hpp>\n#include <limits>\n#include <stdexcept>\n#include <generic_control_toolbox/matrix_parser.hpp>\n#include <generic_control_toolbox/kdl_manager.hpp>\n#include <cmath>\n\n\nnamespace folding_algorithms{\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\ntypedef Eigen::Matrix<double, 6, 7> Matrix67d;\ntypedef Eigen::Matrix<double, 12, 12> Matrix12d;\ntypedef Eigen::Matrix<double, 14, 14> Matrix14d;\ntypedef Eigen::Matrix<double, 6, 14> MatrixECTSr;\ntypedef Eigen::Matrix<double, 12, 14> MatrixECTS;\ntypedef Eigen::Vector3d Vector3d;\ntypedef Eigen::Matrix<double, 7, 1> Vector7d;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\ntypedef Eigen::Matrix<double, 12, 1> Vector12d;\ntypedef Eigen::Matrix<double, 14, 1> Vector14d;\n\n  /**\n    Class that implements an extended cooperative task space (ECTS) control algorithm.\n\n    Hardcoded dimensions to fit two 7 DOF manipulators.\n  **/\n  class ECTSController\n  {\n  public:\n    /**\n      Construct an ECTS controller.\n\n      @param rod_eef key for the rod end-effector in the kdl_manager.\n      @param surface_eef key for the surface_eef in the kdl_manager.\n      @param kdl_manager Pointer to the kdl manager object, which is assumed to have been initialized with the relevant kinematic chains.\n    **/\n    ECTSController(const std::string &rod_eef, const std::string &surface_eef, std::shared_ptr<generic_control_toolbox::KDLManager> kdl_manager);\n    ~ECTSController();\n\n    /**\n      Computes the ECTS reference joint velocities for the two manipulators.\n\n      @param state The dual-arm manipulator joint state.\n      @param ri The virtual sticks connecting the manipulators end-effectors to the task C-Frame.\n      @param twist_a The commanded absolute motion twist.\n      @param twist_r The commanded relative motion twist.\n      @return The 14 dimensional joint velocities vector.\n    **/\n    Vector14d control(const sensor_msgs::JointState &state, const Vector3d &r1, const Vector3d &r2, const Vector6d &twist_a, const Vector6d &twist_r) const;\n\n    /**\n      Return the current alpha value that determines the degree of colaboration between arms.\n    **/\n    double getAlpha() const;\n\n    /**\n      Sets the alpha value.\n\n      @param alpha The desired ECTS alpha value.\n      @throw logic_error if alpha outside range [0, 1]\n    **/\n    void setAlpha(double alpha);\n\n  private:\n    ros::NodeHandle nh_;\n    double alpha_, damping_;\n    int beta_;\n    std::string rod_eef_, surface_eef_;\n    generic_control_toolbox::MatrixParser matrix_parser_;\n    std::shared_ptr<generic_control_toolbox::KDLManager> kdl_manager_;\n\n    /**\n      Computes the ECTS jacobian that maps joints to task space twists.\n\n      @param state The dual-arm manipulator joint state.\n      @param r_i virtual stick connecting eef i to task frame\n      @return The ECTS jacobian.\n    **/\n    MatrixECTS computeECTSJacobian(const sensor_msgs::JointState &state, const Vector3d &r_1, const Vector3d &r_2) const;\n\n    /**\n      Loads the ECTS controller parameters from the ros parameter server.\n\n      @throw logic_error for parameters with unsuitable values\n      @return True in case of success, False if some parameter is not available.\n    **/\n    bool getParams();\n  };\n}\n#endif\n", "meta": {"hexsha": "cf14b8b342ddf914ed606b8c8f7c90e5d49c074c", "size": 3360, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/folding_assembly_controller/ects.hpp", "max_stars_repo_name": "diogoalmeida/sarafun_folding_assembly", "max_stars_repo_head_hexsha": "e86eb85feb5480039139a14034bf70dd68f10991", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-12-16T16:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-23T01:09:24.000Z", "max_issues_repo_path": "include/folding_assembly_controller/ects.hpp", "max_issues_repo_name": "diogoalmeida/sarafun_folding_assembly", "max_issues_repo_head_hexsha": "e86eb85feb5480039139a14034bf70dd68f10991", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-11-08T20:26:00.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-15T19:57:37.000Z", "max_forks_repo_path": "include/folding_assembly_controller/ects.hpp", "max_forks_repo_name": "diogoalmeida/sarafun_folding_assembly", "max_forks_repo_head_hexsha": "e86eb85feb5480039139a14034bf70dd68f10991", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-03-06T14:05:57.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-05T13:29:35.000Z", "avg_line_length": 34.6391752577, "max_line_length": 156, "alphanum_fraction": 0.7285714286, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.5697259481535852}}
{"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// EIGEN\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n// CPLEX\n#include <ilcplex/ilocplex.h>\n\n// Submodules\n#include <rbp_corridor.hpp>\n#include <init_traj_planner.hpp>\n#include <mission.hpp>\n#include <param.hpp>\n\nILOSTLBEGIN\n\nnamespace SwarmPlanning {\n    class RBPPlanner {\n    public:\n        RBPPlanner(Mission _mission,\n                   Param _param)\n                : mission(std::move(_mission)),\n                  param(std::move(_param)) {\n            n = param.n; // degree of polynomial\n            phi = param.phi; // desired derivatives\n            N = mission.qn; // the number of agents\n            outdim = 3; // the number of outputs (x,y,z)\n\n            setBatch(0);\n        }\n\n        bool update(bool log, SwarmPlanning::PlanResult* _planResult_ptr) {\n            planResult_ptr = _planResult_ptr;\n            M = planResult_ptr->T.size() - 1; // the number of segments\n            offset_quad = M * (n + 1);\n            offset_seg = n + 1;\n\n            coef.resize(N);\n            for (int qi = 0; qi < N; qi++) {\n                coef[qi] = Eigen::MatrixXd::Zero(offset_quad, outdim);\n            }\n\n            IloEnv env;\n            Timer timer;\n            try {\n                // Construct constraint matrix\n                timer.reset();\n                buildConstMtx();\n                timer.stop();\n                ROS_INFO_STREAM(\"RBPPlanner: Constraint Matrix runtime=\" << timer.elapsedSeconds());\n\n                // Solve QP\n                timer.reset();\n                solveQP(env, log);\n                timer.stop();\n                ROS_INFO_STREAM(\"RBPPlanner: QP runtime=\" << timer.elapsedSeconds());\n                ROS_INFO_STREAM(\"RBPPlanner: x size=\" << count_x);\n                ROS_INFO_STREAM(\"RBPPlanner: eq const size=\" << count_eq);\n                ROS_INFO_STREAM(\"RBPPlanner: ineq const size=\" << count_lq);\n            }\n            catch (IloException &e) {\n                ROS_ERROR_STREAM(\"RBPPlanner: CPLEX Concert exception caught: \" << e);\n                return false;\n            }\n            catch (...) {\n                ROS_ERROR(\"RBPPlanner: CPLEX Unknown exception caught\");\n                return false;\n            }\n            env.end();\n\n            if(param.time_scale) {\n                timer.reset();\n                timeScale();\n                timer.stop();\n                ROS_INFO_STREAM(\"RBPPlanner: timeScale runtime=\" << timer.elapsedSeconds());\n            }\n\n            generateROSMsg();\n            if(param.log){\n                generateCoefCSV();\n            }\n            return true;\n        }\n\n    private:\n        Mission mission;\n        Param param;\n\n        SwarmPlanning::PlanResult* planResult_ptr;\n        std::vector<std::vector<int>> batches;\n        int M, n, phi, N, outdim, offset_quad, offset_seg;\n        IloNum count_x, count_eq, count_lq;\n\n        // std::shared_ptr<Eigen::MatrixXd> Q_obj, Aeq_obj, Alq_obj, deq_obj, dlq_obj;\n        Eigen::MatrixXd Q_base, Aeq_base, Alq, deq, dlq, basis;\n        Eigen::MatrixXd dummy;\n        std::vector<Eigen::MatrixXd> coef;\n\n        void buildConstMtx() {\n            build_Q_base();\n            build_Aeq_base();\n            build_deq();\n            build_dlq();\n\n            if (param.sequential) {\n                build_dummy();\n            }\n        }\n\n        void solveQP(const IloEnv &env, bool log) {\n            Timer timer;\n            IloNum total_cost = 0;\n\n            IloCplex cplex(env);\n//            cplex.setParam(IloCplex::Param::TimeLimit, 0.04);\n\n            // publish Initial trajectory\n            if(param.sequential && param.batch_iter == 0){\n                // Translate Bernstein basis to Polynomial coefficients\n                for (int k = 0; k < outdim; k++) {\n                    for (int qi = 0; qi < N; qi++) {\n                        for (int m = 0; m < M; m++) {\n                            Eigen::MatrixXd c = Eigen::MatrixXd::Zero(1, n + 1);\n                            Eigen::MatrixXd tm;\n                            timeMatrix(1.0 / (planResult_ptr->T[m+1] - planResult_ptr->T[m]), &tm);\n                            tm = basis * tm;\n\n                            for (int i = 0; i < n + 1; i++) {\n                                c = c + dummy(qi * offset_quad + m * offset_seg + i, k) * tm.row(i);\n                            }\n                            coef[qi].block(m * offset_seg, k, n + 1, 1) = c.transpose();\n                        }\n                    }\n                    timer.stop();\n                }\n                return;\n            }\n\n            for (int iter = 0; iter < param.iteration; iter++) {\n                total_cost = 0;\n                for (int l = 0; l < param.batch_iter; l++) {\n                    timer.reset();\n                    IloModel model(env);\n                    IloNumVarArray var(env);\n                    IloRangeArray con(env);\n\n                    populatebyrow(model, var, con, l);\n                    cplex.extract(model);\n                    if (log) {\n                        std::string QPmodel_path = param.package_path + \"/log/QPmodel.lp\";\n                        cplex.exportModel(QPmodel_path.c_str());\n                    } else {\n                        cplex.setOut(env.getNullStream());\n                    }\n\n                    // Optimize the problem and obtain solution.\n                    if (!cplex.solve()) {\n                        ROS_ERROR(\"RBPPlanner: Failed to optimize QP\");\n                        throw (-1);\n                    }\n\n                    IloNumArray vals(env);\n                    total_cost += cplex.getObjValue();\n                    cplex.getValues(vals, var);\n\n                    // Translate Bernstein basis to Polynomial coefficients\n                    int offset_dim = batches[l].size() * M * (n + 1);\n                    int batch_max_iter = ceil((double)N / (double)param.batch_size);\n                    for (int k = 0; k < outdim; k++) {\n                        for (int qi = 0; qi < N; qi++) {\n                            for (int m = 0; m < M; m++) {\n                                Eigen::MatrixXd c = Eigen::MatrixXd::Zero(1, n + 1);\n                                Eigen::MatrixXd tm;\n                                timeMatrix(1.0 / (planResult_ptr->T[m+1] - planResult_ptr->T[m]), &tm);\n                                tm = basis * tm;\n\n                                int bi = isQuadInBatch(qi, l);\n                                if (bi >= 0) {\n                                    for (int i = 0; i < n + 1; i++) {\n                                        c = c + vals[k * offset_dim + bi * offset_quad + m * offset_seg + i] * tm.row(i);\n                                        if (param.sequential) {\n                                            dummy(qi * offset_quad + m * (n + 1) + i, k) = vals[k * offset_dim + bi * offset_quad + m * offset_seg + i];\n                                        }\n                                    }\n                                    coef[qi].block(m * offset_seg, k, n + 1, 1) = c.transpose();\n                                } else if (param.sequential && param.batch_iter < batch_max_iter) {\n                                    for (int i = 0; i < n + 1; i++) {\n                                        c = c + dummy(qi * offset_quad + m * offset_seg + i, k) * tm.row(i);\n                                    }\n                                    coef[qi].block(m * offset_seg, k, n + 1, 1) = c.transpose();\n                                }\n                            }\n                        }\n                        timer.stop();\n                    }\n                    if (param.sequential) {\n                        ROS_INFO_STREAM(\"RBPPlanner: QP runtime of batch \" << l << \"=\" << timer.elapsedSeconds());\n                        ROS_INFO_STREAM(\"RBPPlanner: QP cost of batch \" << l << \"=\" << cplex.getObjValue());\n                    }\n                }\n                if (param.iteration > 1)\n                    ROS_INFO_STREAM(\"RBPPlanner: QP iteration \" << iter << \" total_cost=\" << total_cost);\n            }\n            ROS_INFO_STREAM(\"RBPPlanner: QP total cost=\" << total_cost);\n        }\n\n        // For all segment of trajectory, check maximum velocity and accelation, and scale the segment time\n        void timeScale() {\n            if (phi != 3 || n != 5) {\n                return;\n            }\n\n            Eigen::MatrixXd coef_der;\n            double time_scale, time_scale_tmp, acc_max;\n            time_scale = 1;\n            for (int qi = 0; qi < N; qi++) {\n                for (int k = 0; k < outdim; k++) {\n                    for (int m = 0; m < M; m++) {\n                        derivative_segment(qi, k, m, &coef_der);\n\n                        time_scale_tmp = scale_to_max_vel(qi, k, m, coef_der);\n                        if (time_scale < time_scale_tmp) {\n                            time_scale = time_scale_tmp;\n                        }\n\n                        time_scale_tmp = scale_to_max_acc(qi, k, m, coef_der);\n                        if (time_scale < time_scale_tmp) {\n                            time_scale = time_scale_tmp;\n                        }\n                    }\n                }\n            }\n\n            ROS_INFO_STREAM(\"RBPPlanner: Time scale=\" << time_scale);\n            if (time_scale != 1) {\n                for (int qi = 0; qi < N; qi++) {\n                    // trajectory\n                    for (int k = 0; k < outdim; k++) {\n                        for (int m = 0; m < M; m++) {\n                            Eigen::MatrixXd tm;\n                            timeMatrix(1.0 / time_scale, &tm);\n\n                            coef[qi].block(m * offset_seg, k, n + 1, 1) =\n                                    tm * coef[qi].block(m * offset_seg, k, n + 1, 1);\n                        }\n                    }\n\n                    // SFC\n                    for (int bi = 0; bi < planResult_ptr->SFC[qi].size(); bi++){\n                        planResult_ptr->SFC[qi][bi].second *= time_scale;\n                    }\n\n                    // RSFC\n                    for (int qj = qi + 1; qj < N; qj++){\n                        for (int ri = 0; ri < planResult_ptr->RSFC[qi][qj].size(); ri++){\n                            planResult_ptr->RSFC[qi][qj][ri].second *= time_scale;\n                        }\n                    }\n                }\n                // segment time\n                for (int m = 0; m < M + 1; m++) {\n                    planResult_ptr->T[m] *= time_scale;\n                }\n            }\n        }\n\n        // generate ros message to transfer planning result\n        void generateROSMsg() {\n            std::vector<double> traj_info;\n            traj_info.emplace_back(N);\n            traj_info.emplace_back(n);\n            traj_info.insert(traj_info.end(), planResult_ptr->T.begin(), planResult_ptr->T.end());\n            planResult_ptr->msgs_traj_info.data = traj_info;\n\n            planResult_ptr->msgs_traj_coef.resize(N);\n            for (int qi = 0; qi < N; qi++) {\n                std_msgs::MultiArrayDimension rows;\n                rows.size = M * (n + 1);\n                planResult_ptr->msgs_traj_coef[qi].layout.dim.emplace_back(rows);\n\n                std_msgs::MultiArrayDimension cols;\n                cols.size = outdim;\n                planResult_ptr->msgs_traj_coef[qi].layout.dim.emplace_back(cols);\n\n                std::vector<double> coef_temp(coef[qi].data(), coef[qi].data() + coef[qi].size());\n                planResult_ptr->msgs_traj_coef[qi].data.insert(planResult_ptr->msgs_traj_coef[qi].data.end(),\n                                                               coef_temp.begin(),\n                                                               coef_temp.end());\n            }\n        }\n\n        // translate coef to crazyswarm trajectory csv file\n        // n should be smaller than 7\n        void generateCoefCSV(){\n            if(n > 7){\n                ROS_WARN(\"RBPPlanner: n>8, do not make CSV file\");\n                return;\n            }\n            for(int qi = 0; qi < N; qi++) {\n                std::ofstream coefCSV;\n                coefCSV.open(param.package_path + \"/log/coef\" + std::to_string(qi + 1) + \".csv\");\n                coefCSV << \"duration,x^0,x^1,x^2,x^3,x^4,x^5,x^6,x^7,y^0,y^1,y^2,y^3,y^4,y^5,y^6,y^7,z^0,z^1,z^2,z^3,z^4,z^5,z^6,z^7,yaw^0,yaw^1,yaw^2,yaw^3,yaw^4,yaw^5,yaw^6,yaw^7\\n\";\n                for(int m = 0; m < M; m++) {\n                    coefCSV << planResult_ptr->T[m + 1] - planResult_ptr->T[m] << \",\";\n                    // x,y,z\n                    for (int k = 0; k < outdim; k++) {\n                        for (int i = n; i >= 0; i--) {\n                            coefCSV << coef[qi](m * offset_seg + i, k) << \",\";\n                        }\n                        // to match\n                        for(int i = 0; i < 7 - n; i++){\n                            coefCSV << \"0,\";\n                        }\n                    }\n                    // yaw\n                    for(int i = 0; i < 8; i++){\n                        coefCSV << \"0,\";\n                    }\n                    coefCSV << \"\\n\";\n                }\n                coefCSV.close();\n            }\n        }\n\n        // Cost matrix Q\n        void build_Q_base() {\n            if (phi == 3 && n == 5) {\n                Q_base = Eigen::MatrixXd::Zero(n + 1, n + 1);\n                Q_base << 720, -1800, 1200, 0, 0, -120,\n                        -1800, 4800, -3600, 0, 600, 0,\n                        1200, -3600, 3600, -1200, 0, 0,\n                        0, 0, -1200, 3600, -3600, 1200,\n                        0, 600, 0, -3600, 4800, -1800,\n                        -120, 0, 0, 1200, -1800, 720;\n\n                basis = Eigen::MatrixXd::Zero(n + 1, n + 1);\n                basis << -1, 5, -10, 10, -5, 1,\n                        5, -20, 30, -20, 5, 0,\n                        -10, 30, -30, 10, 0, 0,\n                        10, -20, 10, 0, 0, 0,\n                        -5, 5, 0, 0, 0, 0,\n                        1, 0, 0, 0, 0, 0;\n            } else {\n                ROS_ERROR(\"RBPPlanner: n should be 5\"); //TODO: debug when n is not 5\n            }\n        }\n\n        Eigen::MatrixXd build_Q_p(int qi, int m) {\n            return Q_base * pow(planResult_ptr->T[m+1] - planResult_ptr->T[m], -2 * phi + 1);\n        }\n\n        void build_Aeq_base() {\n            Aeq_base = Eigen::MatrixXd::Zero((2 * phi + (M - 1) * phi), M * (n + 1));\n            Eigen::MatrixXd A_waypoints = Eigen::MatrixXd::Zero(2 * phi, M * (n + 1));\n            Eigen::MatrixXd A_cont = Eigen::MatrixXd::Zero((M - 1) * phi, M * (n + 1));\n            Eigen::MatrixXd A_0 = Eigen::MatrixXd::Zero(n + 1, n + 1);\n            Eigen::MatrixXd A_T = Eigen::MatrixXd::Zero(n + 1, n + 1);\n\n            // Build A_0, A_T\n            if (phi == 3 && n == 5) {\n                A_0 << 1, 0, 0, 0, 0, 0,\n                        -1, 1, 0, 0, 0, 0,\n                        1, -2, 1, 0, 0, 0,\n                        -1, 3, -3, 1, 0, 0,\n                        1, -4, 6, -4, 1, 0,\n                        -1, 5, -10, 10, -5, 1;\n\n                A_T << 0, 0, 0, 0, 0, 1,\n                        0, 0, 0, 0, -1, 1,\n                        0, 0, 0, 1, -2, 1,\n                        0, 0, -1, 3, -3, 1,\n                        0, 1, -4, 6, -4, 1,\n                        -1, 5, -10, 10, -5, 1;\n            } else {\n                ROS_ERROR(\"RBPPlanner: n should be 5\"); //TODO: debug when n is not 5\n            }\n\n            // Build A_waypoints\n            int nn = 1;\n            for (int i = 0; i < phi; i++) {\n                A_waypoints.block(i, 0, 1, n + 1) =\n                        pow(planResult_ptr->T[1] - planResult_ptr->T[0], -i) * nn * A_0.row(i);\n                A_waypoints.block(phi + i, (n + 1) * (M - 1), 1, n + 1) =\n                        pow(planResult_ptr->T[planResult_ptr->T.size() - 1] - planResult_ptr->T[planResult_ptr->T.size() - 2], -i) * nn * A_T.row(i);\n                nn = nn * (n - i);\n            }\n\n            // Build A_cont\n            for (int m = 1; m < M; m++) {\n                nn = 1;\n                for (int j = 0; j < phi; j++) {\n                    A_cont.block(phi * (m - 1) + j, (n + 1) * (m - 1), 1, n + 1) =\n                            pow(planResult_ptr->T[m] - planResult_ptr->T[m-1], -j) * nn * A_T.row(j);\n                    A_cont.block(phi * (m - 1) + j, (n + 1) * m, 1, n + 1) =\n                            -pow(planResult_ptr->T[m+1] - planResult_ptr->T[m], -j) * nn * A_0.row(j);\n                    nn = nn * (n - j);\n                }\n            }\n\n            // Build Aeq_base\n            Aeq_base << A_waypoints,\n                    A_cont;\n\n        }\n\n        // Equality constraints condition vector deq\n        void build_deq() {\n//        deq_obj.reset(new Eigen::MatrixXd(N * (2*n + (M-1)*n), outdim));\n//        deq_obj->setZero();\n            deq = Eigen::MatrixXd::Zero(N * (2 * phi + (M - 1) * phi), outdim);\n            for (int qi = 0; qi < N; qi++) {\n                Eigen::MatrixXd d_waypoints = Eigen::MatrixXd::Zero(2 * phi, outdim);\n                Eigen::MatrixXd d_cont = Eigen::MatrixXd::Zero((M - 1) * phi, outdim);\n                for (int k = 0; k < outdim; k++) {\n                    d_waypoints(0, k) = mission.startState[qi][k];\n                    d_waypoints(1, k) = mission.startState[qi][k + 3];\n                    d_waypoints(2, k) = mission.startState[qi][k + 6];\n                    d_waypoints(phi, k) = mission.goalState[qi][k];\n                    d_waypoints(phi + 1, k) = mission.goalState[qi][k + 3];\n                    d_waypoints(phi + 2, k) = mission.goalState[qi][k + 6];\n                }\n\n                // Build deq\n                int deq_p_rows = d_waypoints.rows() + d_cont.rows();\n                int deq_p_cols = outdim;\n//            deq_obj->block(qi * deq_p_rows, 0, deq_p_rows, deq_p_cols) << d_waypoints,\n//                                                                          d_cont;\n                deq.block(qi * deq_p_rows, 0, deq_p_rows, deq_p_cols) << d_waypoints,\n                        d_cont;\n            }\n        }\n\n        // Inequality constraints condition vector dlq\n        void build_dlq() {\n//        dlq_obj.reset(new Eigen::MatrixXd(N*2*(n+1)*M + N*(N-1)*(n+1)*M, outdim));\n//        dlq_obj->setZero();\n            dlq = Eigen::MatrixXd::Zero(N * 2 * (n + 1) * M + N * (N - 1) * (n + 1) * M, outdim);\n            Eigen::MatrixXd dlq_rel = Eigen::MatrixXd::Zero(N * (N - 1) * (n + 1) * M, outdim);\n            Eigen::MatrixXd dlq_box = Eigen::MatrixXd::Zero(N * 2 * (n + 1) * M, outdim);\n\n            // Build dlq_box\n            for (int qi = 0; qi < N; qi++) {\n                Eigen::MatrixXd d_upper = Eigen::MatrixXd::Zero((n + 1) * M, outdim);\n                Eigen::MatrixXd d_lower = Eigen::MatrixXd::Zero((n + 1) * M, outdim);\n\n                int bi = 0;\n                for (int m = 0; m < M; m++) {\n                    // find box number\n                    while (bi < planResult_ptr->SFC[qi].size() &&\n                           planResult_ptr->SFC[qi][bi].second < planResult_ptr->T[m + 1]) {\n                        bi++;\n                    }\n\n                    d_upper.block((n + 1) * m, 0, n + 1, 1) =\n                            Eigen::MatrixXd::Constant(n + 1, 1, planResult_ptr->SFC[qi][bi].first[3]);\n                    d_lower.block((n + 1) * m, 0, n + 1, 1) =\n                            Eigen::MatrixXd::Constant(n + 1, 1, -planResult_ptr->SFC[qi][bi].first[0]);\n\n                    d_upper.block((n + 1) * m, 1, n + 1, 1) =\n                            Eigen::MatrixXd::Constant(n + 1, 1, planResult_ptr->SFC[qi][bi].first[4]);\n                    d_lower.block((n + 1) * m, 1, n + 1, 1) =\n                            Eigen::MatrixXd::Constant(n + 1, 1, -planResult_ptr->SFC[qi][bi].first[1]);\n\n                    d_upper.block((n + 1) * m, 2, n + 1, 1) =\n                            Eigen::MatrixXd::Constant(n + 1, 1, planResult_ptr->SFC[qi][bi].first[5]);\n                    d_lower.block((n + 1) * m, 2, n + 1, 1) =\n                            Eigen::MatrixXd::Constant(n + 1, 1, -planResult_ptr->SFC[qi][bi].first[2]);\n                }\n\n                int dlq_box_rows = d_upper.rows() + d_lower.rows();\n                dlq_box.block(qi * dlq_box_rows, 0, dlq_box_rows, outdim) << d_upper,\n                        d_lower;\n            }\n\n            // Build dlq_rel\n            int iter = 0;\n            for (int qi = 0; qi < N; qi++) {\n                for (int qj = qi + 1; qj < N; qj++) {\n                    Eigen::MatrixXd d_upper = Eigen::MatrixXd::Constant((n + 1) * M, outdim, 10000000);\n                    Eigen::MatrixXd d_lower = Eigen::MatrixXd::Constant((n + 1) * M, outdim, 10000000);\n\n                    for (int m = 0; m < M; m++) {\n                        // Find box number\n                        int ri = 0;\n                        while (ri < planResult_ptr->RSFC[qi][qj].size() &&\n                               planResult_ptr->RSFC[qi][qj][ri].second < planResult_ptr->T[m + 1]) {\n                            ri++;\n                        }\n\n                        octomap::point3d normal_vector = planResult_ptr->RSFC[qi][qj][ri].first;\n                        d_upper.block((n + 1) * m, 0, n + 1, 1) =\n                                Eigen::MatrixXd::Constant(n + 1, 1, normal_vector.x());\n                        d_upper.block((n + 1) * m, 1, n + 1, 1) =\n                                Eigen::MatrixXd::Constant(n + 1, 1, normal_vector.y());\n                        d_upper.block((n + 1) * m, 2, n + 1, 1) =\n                                Eigen::MatrixXd::Constant(n + 1, 1, normal_vector.z());\n                    }\n                    int dlq_rel_rows = d_upper.rows() + d_lower.rows();\n                    dlq_rel.block(iter * dlq_rel_rows, 0, dlq_rel_rows, outdim) << d_upper,\n                            d_lower;\n                    iter++;\n                }\n            }\n\n            // Build dlq\n//        dlq_obj->block(0, 0, dlq_box.rows(), dlq_box.cols()) = dlq_box;\n//        dlq_obj->block(dlq_box.rows(), 0, dlq_rel.rows(), dlq_rel.cols()) = dlq_rel;\n            dlq << dlq_box,\n                    dlq_rel;\n        }\n\n        void build_dummy() {\n            dummy = Eigen::MatrixXd::Zero(N * offset_quad, outdim);\n\n            for (int qi = 0; qi < N; qi++) {\n                int m = 0;\n                int idx = 0;\n                while (m < M) {\n                    if (idx >= planResult_ptr->initTraj[qi].size() - 1) {\n                        idx = planResult_ptr->initTraj[qi].size() - 1;\n                        for (int j = 0; j < n + 1; j++) {\n                            dummy(qi * offset_quad + m * (n + 1) + j, 0) = planResult_ptr->initTraj[qi][idx].x();\n                            dummy(qi * offset_quad + m * (n + 1) + j, 1) = planResult_ptr->initTraj[qi][idx].y();\n                            dummy(qi * offset_quad + m * (n + 1) + j, 2) = planResult_ptr->initTraj[qi][idx].z();\n                        }\n                        m++;\n                    } else {\n                        for (int j = 0; j < n + 1; j++) {\n                            int a = 1;\n                            if (j < (n + 1) / 2) {\n                                a = 0;\n                            }\n                            dummy(qi * offset_quad + m * (n + 1) + j, 0) =\n                                    (1 - a) * planResult_ptr->initTraj[qi][idx].x()\n                                    + a * planResult_ptr->initTraj[qi][idx + 1].x();\n                            dummy(qi * offset_quad + m * (n + 1) + j, 1) =\n                                    (1 - a) * planResult_ptr->initTraj[qi][idx].y()\n                                    + a * planResult_ptr->initTraj[qi][idx + 1].y();\n                            dummy(qi * offset_quad + m * (n + 1) + j, 2) =\n                                    (1 - a) * planResult_ptr->initTraj[qi][idx].z()\n                                    + a * planResult_ptr->initTraj[qi][idx + 1].z();\n                        }\n                        m++;\n                    }\n                    idx++;\n                }\n            }\n        }\n\n        void populatebyrow(IloModel model, IloNumVarArray x, IloRangeArray c, int l) {\n            int offset_dim = batches[l].size() * M * (n + 1);\n            IloEnv env = model.getEnv();\n            for (int k = 0; k < outdim; k++) {\n                for (int bi = 0; bi < batches[l].size(); bi++) {\n                    for (int m = 0; m < M; m++) {\n                        for (int i = 0; i < n + 1; i++) {\n                            x.add(IloNumVar(env, -IloInfinity, IloInfinity));\n\n                            int qi = batches[l][bi];\n                            int row = k * offset_dim + bi * offset_quad + m * (n + 1) + i;\n                            std::string name;\n                            if (k == 0) {\n                                name = \"x_\" + std::to_string(qi) + \"_\" + std::to_string(m) + \"_\" + std::to_string(i);\n                            } else if (k == 1) {\n                                name = \"y_\" + std::to_string(qi) + \"_\" + std::to_string(m) + \"_\" + std::to_string(i);\n                            } else if (k == 2) {\n                                name = \"z_\" + std::to_string(qi) + \"_\" + std::to_string(m) + \"_\" + std::to_string(i);\n                            } else {\n                                ROS_ERROR(\"RBPPlanner: Invalid outdim\");\n                            }\n\n                            x[row].setName(name.c_str());\n                        }\n                    }\n                }\n            }\n            count_x = x.getSize();\n\n            // Cost function\n            IloNumExpr cost(env);\n            for (int k = 0; k < outdim; k++) {\n                for (int bi = 0; bi < batches[l].size(); bi++) {\n                    for (int m = 0; m < M; m++) {\n                        int qi = batches[l][bi];\n                        Eigen::MatrixXd Q_p = build_Q_p(qi, m);\n\n                        for (int i = 0; i < n + 1; i++) {\n                            int row = qi * M * (n + 1) + m * (n + 1) + i;\n                            int row_idx = k * offset_dim + bi * offset_quad + m * (n + 1) + i;\n\n                            for (int j = 0; j < n + 1; j++) {\n                                int col = qi * M * (n + 1) + m * (n + 1) + j;\n                                int col_idx =\n                                        k * offset_dim + bi * offset_quad + m * (n + 1) + j;\n\n                                if (Q_p(i, j) != 0) {\n                                    cost += Q_p(i, j) * x[row_idx] * x[col_idx];\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n            model.add(IloMinimize(env, cost));\n\n            // Equality Constraints\n            for (int k = 0; k < outdim; k++) {\n                for (int bi = 0; bi < batches[l].size(); bi++) {\n                    for (int i = 0; i < 2 * phi + (M - 1) * phi; i++) {\n                        IloNumExpr expr(env);\n                        for (int j = 0; j < M * (n + 1); j++) {\n                            if (Aeq_base(i, j) != 0) {\n                                expr += Aeq_base(i, j) * x[k * offset_dim + bi * offset_quad + j];\n                            }\n                        }\n                        int qi = batches[l][bi];\n                        c.add(expr == deq(qi * (2 * phi + (M - 1) * phi) + i, k));\n                        expr.end();\n                    }\n                }\n            }\n            count_eq = c.getSize();\n\n            // Inequality Constraints\n            for (int k = 0; k < outdim; k++) {\n                for (int bi = 0; bi < batches[l].size(); bi++) {\n                    int qi = batches[l][bi];\n                    for (int j = 0; j < (n + 1) * M; j++) {\n                        int idx = k * offset_dim + bi * offset_quad + j;\n                        c.add(x[idx] <= dlq(2 * qi * offset_quad + j, k));\n                        c.add(-x[idx] <= dlq((2 * qi + 1) * offset_quad + j, k));\n                    }\n                }\n            }\n            int offset_box = 2 * N * offset_quad;\n            int iter = 0;\n            for (int qi = 0; qi < N; qi++) {\n                for (int qj = qi + 1; qj < N; qj++) {\n                    int bi = isQuadInBatch(qi, l);\n                    int bj = isQuadInBatch(qj, l);\n\n                    if (bi < 0 && bj < 0) {\n\n                    } else if (bi >= 0 && bj < 0) {\n                        for (int j = 0; j < M * (n + 1); j++) {\n                            int idx = bi * offset_quad + j;\n                            c.add(dlq(offset_box + offset_quad * 2 * iter + j, 0) *\n                                  (dummy(qj * offset_quad + j, 0) - x[0 * offset_dim + idx]) +\n                                  dlq(offset_box + offset_quad * 2 * iter + j, 1) *\n                                  (dummy(qj * offset_quad + j, 1) - x[1 * offset_dim + idx]) +\n                                  dlq(offset_box + offset_quad * 2 * iter + j, 2) *\n                                  (dummy(qj * offset_quad + j, 2) - x[2 * offset_dim + idx])\n                                  >= mission.quad_size[qi] + mission.quad_size[qj]);\n                        }\n                    } else if (bi < 0 && bj >= 0) {\n                        for (int j = 0; j < M * (n + 1); j++) {\n                            int jdx = bj * offset_quad + j;\n                            c.add(dlq(offset_box + offset_quad * 2 * iter + j, 0) *\n                                  (x[0 * offset_dim + jdx] - dummy(qi * offset_quad + j, 0)) +\n                                  dlq(offset_box + offset_quad * 2 * iter + j, 1) *\n                                  (x[1 * offset_dim + jdx] - dummy(qi * offset_quad + j, 1)) +\n                                  dlq(offset_box + offset_quad * 2 * iter + j, 2) *\n                                  (x[2 * offset_dim + jdx] - dummy(qi * offset_quad + j, 2))\n                                  >= mission.quad_size[qi] + mission.quad_size[qj]);\n                        }\n                    } else {\n                        for (int j = 0; j < M * (n + 1); j++) {\n                            int idx = bi * offset_quad + j;\n                            int jdx = bj * offset_quad + j;\n\n                            c.add(dlq(offset_box + offset_quad * 2 * iter + j, 0) *\n                                  (x[0 * offset_dim + jdx] - x[0 * offset_dim + idx]) +\n                                  dlq(offset_box + offset_quad * 2 * iter + j, 1) *\n                                  (x[1 * offset_dim + jdx] - x[1 * offset_dim + idx]) +\n                                  dlq(offset_box + offset_quad * 2 * iter + j, 2) *\n                                  (x[2 * offset_dim + jdx] - x[2 * offset_dim + idx])\n                                  >= mission.quad_size[qi] + mission.quad_size[qj]);\n                        }\n                    }\n\n                    iter++;\n                }\n            }\n            model.add(c);\n\n            count_lq = c.getSize() - count_eq;\n        }\n\n        // timeMatrix is mapping matrix (n + 1) x (n + 1)\n        // e.g. [1   0   0   ...]\n        //      [0   t   0   ...]\n        //      [0   0   t^2 ...]\n        //      [... ... ... ...]\n        void timeMatrix(double t, Eigen::MatrixXd* tm_ptr) {\n            *tm_ptr = Eigen::MatrixXd::Zero(n + 1, n + 1);\n            for (int i = 0; i < n + 1; i++) {\n                (*tm_ptr)(i, i) = pow(t, n - i);\n            }\n        }\n\n        // Get derivative of m^th segment(polynomial) of qi^th agent\n        // e.g. if phi = 3, n = 5, polynomial [1 1 1 1 1 1] then\n        //      coef_der = [1  1  1  1  1  1]\n        //                 [5  4  3  2  1  0]\n        //                 [20 12 6  2  0  0]\n        //                 [60 24 6  0  0  0]\n        void derivative_segment(int qi, int k, int m, Eigen::MatrixXd* coef_der_ptr) {\n            *coef_der_ptr = Eigen::MatrixXd::Zero(phi + 1, n + 1);\n            for (int i = 0; i < phi + 1; i++) {\n                for (int j = 0; j < n + 1; j++) {\n                    if (i <= j)\n                        (*coef_der_ptr)(i, n - j) = coef_derivative(i, j) * coef[qi](m * offset_seg + n - j, k);\n                    else\n                        (*coef_der_ptr)(i, n - j) = 0;\n                }\n            }\n        }\n\n        // Get j^th coefficient of i^th derivative of polynomial [1 1 1 1 ... 1]\n        int coef_derivative(int i, int j) {\n            return (i == 0) ? 1 : coef_derivative(i - 1, j - 1) * j;\n        }\n\n        // Get roots of i^th derivative of polynomial with coefficient coef\n        // The roots of the polynomial are calculated by computing the eigenvalues of the companion matrix, A\n        std::vector<double> roots_derivative(int i, const Eigen::MatrixXd& coef_der) {\n            std::vector<double> roots_der;\n            int n_der = n - i;\n            int iter = 0;\n            while(n_der > 0 && coef_der(i, n - i - n_der) == 0 ){\n                n_der--;\n            }\n            if(n_der == 0){\n                return roots_der; // return empty vector\n            }\n\n            Eigen::MatrixXd A = Eigen::MatrixXd::Zero(n_der, n_der);\n            for (int j = 0; j < n_der; j++) {\n                if (j < n_der - 1) {\n                    A(j + 1, j) = 1;\n                }\n                A(0, j) = -coef_der(i, n - i - n_der + j + 1) / coef_der(i, n - i - n_der);\n            }\n\n            Eigen::EigenSolver<Eigen::MatrixXd> es(A);\n            for (int j = 0; j < i; j++) {\n                complex<double> lambda = es.eigenvalues()[j];\n                if (lambda.imag() == 0) {\n                    roots_der.emplace_back(lambda.real());\n                }\n            }\n            return roots_der;\n        }\n\n        double scale_to_max_vel(int qi, int k, int m, const Eigen::MatrixXd& coef_der) {\n            assert(phi > 1);\n            double scale_update_rate = 1.1; //TODO: parameterization?\n\n            // Get maximum velocity\n            double vel_max = 0, t_max = 0;\n            std::vector<double> ts = roots_derivative(2, coef_der);\n            ts.emplace_back(0);\n            ts.emplace_back(planResult_ptr->T[m + 1] - planResult_ptr->T[m]);\n            for (auto t : ts) {\n                if (t < 0 || t > planResult_ptr->T[m + 1] - planResult_ptr->T[m]) {\n                    continue;\n                }\n\n                double vel = 0;\n                for (int i = 0; i <= (n - 1); i++) {\n                    vel += coef_der(1, i) * pow(t, n - 1 - i);\n                }\n                vel = abs(vel);\n                if (vel_max < vel) {\n                    vel_max = vel;\n                    t_max = t;\n                }\n            }\n\n            // time_scale update\n            double time_scale = 1;\n            while (vel_max > mission.max_vel[qi][k]) {\n                time_scale *= scale_update_rate;\n\n                double vel = 0;\n                for (int i = 0; i <= (n - 1); i++) {\n                    vel += coef_der(1, i) * pow(1 / time_scale, n - i) * pow(t_max, n - 1 - i);\n                }\n                vel_max = abs(vel);\n            }\n\n            return time_scale;\n        }\n\n\n        double scale_to_max_acc(int qi, int k, int m, const Eigen::MatrixXd &coef_der) {\n            assert(phi == 3 && n == 5);\n            double scale_update_rate = 1.1; //TODO: parameterization?\n\n            // Get maximum accelaration\n            double a, b, c, D, acc_max, t_max = 0;\n            a = coef_der(3, 0);\n            b = coef_der(3, 1);\n            c = coef_der(3, 2);\n            D = b * b - 4 * a * c;\n            acc_max = 0;\n\n            std::vector<double> ts{0, planResult_ptr->T[m+1] - planResult_ptr->T[m]};\n            if (D >= 0 && a != 0) {\n                ts.emplace_back((-b + sqrt(D)) / (2 * a));\n                ts.emplace_back((-b - sqrt(D)) / (2 * a));\n            }\n            else if(a == 0 && b != 0){\n                ts.emplace_back(-c/b);\n            }\n\n            for (auto t : ts) {\n                if (t < 0 || t > planResult_ptr->T[m+1] - planResult_ptr->T[m]) {\n                    continue;\n                }\n\n                double acc = 0;\n                for (int i = 0; i < 4; i++) {\n                    acc += coef_der(2, i) * pow(t, 3 - i);\n                }\n                acc = abs(acc);\n                if (acc_max < acc) {\n                    acc_max = acc;\n                    t_max = t;\n                }\n            }\n\n            // time_scale update\n            double time_scale = 1;\n            while (acc_max > mission.max_acc[qi][k]) {\n                time_scale *= scale_update_rate;\n\n                double acc = 0;\n                for (int i = 0; i < 4; i++) {\n                    acc += coef_der(2, i) * pow(1 / time_scale, n - i) * pow(t_max, 3 - i);\n                }\n                acc_max = abs(acc);\n            }\n\n            return time_scale;\n        }\n\n        void setBatch(int alg){\n            int batch_max_iter = ceil((double)N / (double)param.batch_size);\n            if (param.sequential) {\n                int batch_max_iter = ceil((double)N / (double)param.batch_size);\n                if (param.batch_iter < 0 || param.batch_iter > batch_max_iter) {\n                    param.batch_iter = batch_max_iter;\n                }\n            } else {\n                param.batch_size = N;\n                param.batch_iter = 1;\n            }\n\n            batches.resize(batch_max_iter);\n\n            //default groups\n            if(alg == 0) {\n                for (int qi = 0; qi < N; qi++) {\n                    batches[qi / param.batch_size].emplace_back(qi);\n                }\n            }\n            else{\n                ROS_ERROR(\"RBPPlaner: invalid batch algorithm\");\n            }\n        }\n\n        int isQuadInBatch(int qi, int l){\n            for(int bi = 0; bi < batches[l].size(); bi++){\n                if(qi == batches[l][bi]){\n                    return bi;\n                }\n            }\n            return -1;\n        }\n    };\n}", "meta": {"hexsha": "63f8e309fa3d00f271b24dc42441bca42e18d91a", "size": 38077, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "swarm_planner/include/rbp_planner.hpp", "max_stars_repo_name": "snu-larr/swarm_simulator", "max_stars_repo_head_hexsha": "dc3f272158132cda4e1c319c7bd1a965d7bf9c40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T03:50:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T03:50:54.000Z", "max_issues_repo_path": "swarm_planner/include/rbp_planner.hpp", "max_issues_repo_name": "snu-larr/swarm_simulator", "max_issues_repo_head_hexsha": "dc3f272158132cda4e1c319c7bd1a965d7bf9c40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swarm_planner/include/rbp_planner.hpp", "max_forks_repo_name": "snu-larr/swarm_simulator", "max_forks_repo_head_hexsha": "dc3f272158132cda4e1c319c7bd1a965d7bf9c40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T10:58:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T08:19:08.000Z", "avg_line_length": 43.1223103058, "max_line_length": 184, "alphanum_fraction": 0.3846679098, "num_tokens": 9789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5697147693911493}}
{"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": "#include \"test_jain_commitments.h\"\n#include <hamming/jain_commitment/jain_commitment.h>\n\n#include <NTL/vec_GF2.h>\n#include <NTL/mat_GF2.h>\n#include <utils/utils.h>\n#include \"test_params.h\"\n#include \"test_functions.h\"\n\nint test::hamming_metric::commitment::test_verify() {\n\n    NTL::vec_GF2 c, r, m;\n    ::hamming_metric::commitment::public_key_t public_key;\n\n    {\n        ::utils::generate_random_binary_vector(\n                m,\n                JAIN_V);\n        ::utils::generate_random_binary_vector(\n                r,\n                JAIN_L);\n        ::hamming_metric::commitment::generate_public_key(\n                &public_key);\n    }\n\n    ::hamming_metric::commitment::generate_commitment(\n            c,\n            &public_key,\n            r,\n            m);\n\n    return ::hamming_metric::commitment::verify(\n            c,\n            &public_key,\n            r,\n            m);\n}\n\nstatic void test_perf_generate_vector_of_weight_w() {\n\n    NTL::vec_GF2 e;\n\n    clock_t start, lap, total_time;\n    total_time = 0;\n    int i;\n\n    uint iterations = 0x100;\n    int total_iterations = iterations;\n\n    do {\n        start = clock();\n\n        for (i = 0; i < iterations; i++) {\n            ::utils::generate_vector_of_weight_w(\n                    e,\n                    JAIN_K,\n                    W);\n        }\n\n        lap = clock() - start;\n        total_time += lap;\n        total_iterations += iterations;\n\n        iterations <<= 1;\n\n    } while (lap < TESTRUN_LEN * CLOCKS_PER_SEC);\n\n    double total_time_in_seconds = (double) total_time / (double) CLOCKS_PER_SEC;\n    double operation_per_second = total_time_in_seconds / total_iterations;\n\n    test::test_functions::print_ops(\n            \"Hamming\",\n            \"Generate vector of weight w\",\n            total_time_in_seconds,\n            operation_per_second);\n}\n\nstatic void test_perf_generate_random_binary_matrix_A() {\n\n    NTL::mat_GF2 A;\n\n    clock_t start, lap, total_time;\n    total_time = 0;\n    int i;\n\n    uint iterations = 0x100;\n    int total_iterations = iterations;\n\n    do {\n        start = clock();\n\n        for (i = 0; i < iterations; i++) {\n            utils::generate_random_binary_matrix(\n                    A,\n                    JAIN_K,\n                    JAIN_L + JAIN_V);\n        }\n\n        lap = clock() - start;\n        total_time += lap;\n        total_iterations += iterations;\n\n        iterations <<= 1;\n\n    } while (lap < TESTRUN_LEN * CLOCKS_PER_SEC);\n\n    double total_time_in_seconds = (double) total_time / (double) CLOCKS_PER_SEC;\n    double operation_per_second = total_time_in_seconds / total_iterations;\n\n    test::test_functions::print_ops(\n            \"Hamming\",\n            \"Generate random binary matrix A\",\n            total_time_in_seconds,\n            operation_per_second);\n}\n\nstatic void test_perf_generate_commitment() {\n\n    NTL::mat_GF2 A;\n    NTL::vec_GF2 c, r, m, e;\n\n    ::utils::generate_random_binary_vector(\n            m,\n            JAIN_V);\n\n    ::utils::generate_random_binary_vector(\n            r,\n            JAIN_L);\n\n    utils::generate_random_binary_matrix(\n            A,\n            JAIN_K,\n            JAIN_L + JAIN_V);\n\n    ::utils::generate_vector_of_weight_w(\n            e,\n            JAIN_K,\n            W);\n\n    clock_t start, lap, total_time;\n    total_time = 0;\n    int i;\n\n    uint iterations = 0x100;\n    int total_iterations = iterations;\n\n    do {\n        start = clock();\n\n        for (i = 0; i < iterations; i++) {\n            ::hamming_metric::commitment::generate_commitment(\n                    c,\n                    A,\n                    r,\n                    m,\n                    e);\n        }\n\n        lap = clock() - start;\n        total_time += lap;\n        total_iterations += iterations;\n\n        iterations <<= 1;\n\n    } while (lap < TESTRUN_LEN * CLOCKS_PER_SEC);\n\n    double total_time_in_seconds = (double) total_time / (double) CLOCKS_PER_SEC;\n    double operation_per_second = total_time_in_seconds / total_iterations;\n\n    test::test_functions::print_ops(\n            \"Hamming\",\n            \"Generate commitment\",\n            total_time_in_seconds,\n            operation_per_second);\n}\n\nstatic void test_perf_recover_e_from_c() {\n\n    NTL::mat_GF2 A;\n    NTL::vec_GF2 c, r, m;\n\n    ::utils::generate_random_binary_vector(\n            m,\n            JAIN_V);\n\n    ::utils::generate_random_binary_vector(\n            r,\n            JAIN_L);\n\n    utils::generate_random_binary_matrix(\n            A,\n            JAIN_K,\n            JAIN_L + JAIN_V);\n\n    ::hamming_metric::commitment::generate_commitment(\n            c,\n            A,\n            r,\n            m);\n\n    clock_t start, lap, total_time;\n    total_time = 0;\n    int i;\n\n    uint iterations = 0x100;\n    int total_iterations = iterations;\n\n    do {\n        start = clock();\n\n        for (i = 0; i < iterations; i++) {\n            NTL::vec_GF2 _r(r);\n            _r.append(m);\n            auto e = (A * _r) + c;\n        }\n\n        lap = clock() - start;\n        total_time += lap;\n        total_iterations += iterations;\n\n        iterations <<= 1;\n\n    } while (lap < TESTRUN_LEN * CLOCKS_PER_SEC);\n\n    double total_time_in_seconds = (double) total_time / (double) CLOCKS_PER_SEC;\n    double operation_per_second = total_time_in_seconds / total_iterations;\n\n    test::test_functions::print_ops(\n            \"Hamming\",\n            \"Recover e from c\",\n            total_time_in_seconds,\n            operation_per_second);\n}\n\nstatic void test_perf_calculate_weight_of_vector() {\n\n    NTL::vec_GF2 e;\n\n    ::utils::generate_vector_of_weight_w(\n            e,\n            JAIN_K,\n            W);\n\n    clock_t start, lap, total_time;\n    total_time = 0;\n    int i;\n\n    uint iterations = 0x100;\n    int total_iterations = iterations;\n\n    do {\n        start = clock();\n\n        for (i = 0; i < iterations; i++) {\n            NTL::weight(e);\n        }\n\n        lap = clock() - start;\n        total_time += lap;\n        total_iterations += iterations;\n\n        iterations <<= 1;\n\n    } while (lap < TESTRUN_LEN * CLOCKS_PER_SEC);\n\n    double total_time_in_seconds = (double) total_time / (double) CLOCKS_PER_SEC;\n    double operation_per_second = total_time_in_seconds / total_iterations;\n\n    test::test_functions::print_ops(\n            \"Hamming\",\n            \"Calculate weight of vector\",\n            total_time_in_seconds,\n            operation_per_second);\n}\n\nvoid test::hamming_metric::commitment::test_perf() {\n\n    test_perf_generate_vector_of_weight_w();\n    test_perf_generate_random_binary_matrix_A();\n    test_perf_generate_commitment();\n    test_perf_recover_e_from_c();\n    test_perf_calculate_weight_of_vector();\n}\n", "meta": {"hexsha": "ff0c5163ab93db0f08b7e235877d2d0ba9a914e3", "size": 6662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_jain_commitments.cpp", "max_stars_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_stars_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/test_jain_commitments.cpp", "max_issues_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_issues_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/test_jain_commitments.cpp", "max_forks_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_forks_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-16T07:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-16T07:21:24.000Z", "avg_line_length": 23.4577464789, "max_line_length": 81, "alphanum_fraction": 0.5664965476, "num_tokens": 1548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5696786790990703}}
{"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": "#include \"pitts_parallel.hpp\"\n#include \"pitts_common.hpp\"\n#include \"pitts_multivector.hpp\"\n#include \"pitts_multivector_random.hpp\"\n#include \"pitts_multivector_tsqr.hpp\"\n#include \"pitts_tensor2.hpp\"\n#include \"pitts_tensor2_eigen_adaptor.hpp\"\n#include <exception>\n#include <charconv>\n#include <iostream>\n#pragma GCC push_options\n#pragma GCC optimize(\"no-unsafe-math-optimizations\")\n#include <Eigen/Dense>\n#pragma GCC pop_options\n\n\nint main(int argc, char* argv[])\n{\n  PITTS::initialize(&argc, &argv);\n\n  using mat = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>;\n  using Chunk = PITTS::Chunk<double>;\n\n  if( argc != 5 && argc != 6 )\n    throw std::invalid_argument(\"Requires 4 arguments (n m reductionFactor nIter [colBlockingSize] )!\");\n\n  long long n = 0, m = 0;\n  int reductionFactor = 20, nIter = 0;\n  int colBlockingSize = 0;\n  std::from_chars(argv[1], argv[2], n);\n  std::from_chars(argv[2], argv[3], m);\n  std::from_chars(argv[3], argv[4], reductionFactor);\n  std::from_chars(argv[4], argv[5], nIter);\n  if( argc == 6 )\n    std::from_chars(argv[5], argv[6], colBlockingSize);\n\n  const auto& [iProc,nProcs] = PITTS::internal::parallel::mpiProcInfo();\n  {\n    const auto& [nFirst,nLast] = PITTS::internal::parallel::distribute(n, {iProc,nProcs});\n    n = nLast - nFirst + 1;\n  }\n\n  PITTS::MultiVector<double> M(n, m);\n  randomize(M);\n\n  PITTS::Tensor2<double> R(m,m);\n\ndouble wtime = omp_get_wtime();\n  for(int iter = 0; iter < nIter; iter++)\n  {\n    block_TSQR(M, R, reductionFactor, true, colBlockingSize);\n  }\nwtime = omp_get_wtime() - wtime;\n  if( iProc == 0 )\n    std::cout << \"wtime: \" << wtime << \"\\n\";\n\n  if( iProc == 0 )\n  {\n    Eigen::BDCSVD<mat> svd(ConstEigenMap(R));\n    //std::cout << \"Result:\\n\" << M << \"\\n\";\n    std::cout << \"singular values (new):\\n\" << svd.singularValues().transpose() << \"\\n\";\n  }\n\n  PITTS::finalize();\n\n  return 0;\n}\n\n", "meta": {"hexsha": "c834c891434d92c826d5114ac4d75e4c08679c5f", "size": 1867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tsqr_bench.cpp", "max_stars_repo_name": "melven/pitts", "max_stars_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-31T08:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T14:48:49.000Z", "max_issues_repo_path": "src/tsqr_bench.cpp", "max_issues_repo_name": "melven/pitts", "max_issues_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tsqr_bench.cpp", "max_forks_repo_name": "melven/pitts", "max_forks_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0579710145, "max_line_length": 104, "alphanum_fraction": 0.6566684521, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.5696650145645609}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE CISHW1Test\n\n// system includes\n#include <boost/test/unit_test.hpp>\n#include <exception>\n#include <unistd.h>\n#include <boost/math/constants/constants.hpp>\n#include <iostream>\n#include <vector>\n#include <boost/bind.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n// local includes\n#include \"IterativeClosestPoint.hpp\"\n\n\nstatic const bool debug = false;\nstatic const double tolerance = 0.01l;\n\ntemplate<typename T>\nbool isWithinTolerance(const T& result, const T& groundTruth, double toleranceVal = tolerance){\n    return (result.isApprox(groundTruth,toleranceVal) || (result - groundTruth).norm() < toleranceVal);\n}\n\nBOOST_AUTO_TEST_SUITE(cisPA3test)\n\nvoid testClosestPoint(const Eigen::Vector3d&& point,std::vector<Eigen::Vector3d>& vertices, Eigen::VectorXd& triangle, const Eigen::Vector3d&& expectedResult){\n    \n    Eigen::Vector3d testresult = FindClosestPoint(point,vertices,triangle);\n    \n    if (!isWithinTolerance(testresult, expectedResult)) {\n        std::cout << \"error: input point:\" << point.transpose() << \" expectedResult: \" << expectedResult.transpose() << \" not equal to testresult: \" << testresult.transpose() << \"\\n\";\n    }\n    BOOST_CHECK(isWithinTolerance(testresult, expectedResult));\n}\n\nBOOST_AUTO_TEST_CASE(FindClosestPointPointTest)\n{\n\t// Unit Tests to Check if the function FindClosestPoint() works correctly\n    Eigen::VectorXd triangle(3);\n    triangle(0) = 0;\n    triangle(1) = 1;\n    triangle(2) = 2;\n\t\n\tstd::vector<Eigen::Vector3d> vertices;\n\tvertices.push_back(Eigen::Vector3d(0,1,0));\n    vertices.push_back(Eigen::Vector3d(1,0,0));\n    vertices.push_back(Eigen::Vector3d(0,0,0)); \n\n    testClosestPoint(Eigen::Vector3d(1,1,0)    , vertices, triangle, Eigen::Vector3d(  0.5   , 0.5    , 0.0 ));\n    testClosestPoint(Eigen::Vector3d(0.5,-1,0) , vertices, triangle, Eigen::Vector3d(  0.5   , 0.0    , 0.0 ));\n    testClosestPoint(Eigen::Vector3d(0.5,0.5,1), vertices, triangle, Eigen::Vector3d(  0.5   , 0.5    , 0.0 ));\n    testClosestPoint(Eigen::Vector3d(-1,0.5,0) , vertices, triangle, Eigen::Vector3d(  0.0   , 0.5    , 0.0 ));\n    testClosestPoint(Eigen::Vector3d(0,0,0)    , vertices, triangle, Eigen::Vector3d(  0.0   , 0.0    , 0.0 ));\n    testClosestPoint(Eigen::Vector3d(0.2,0.2,1), vertices, triangle, Eigen::Vector3d(  0.2   , 0.2    , 0.0 ));\n    testClosestPoint(Eigen::Vector3d(-1,-1,-1) , vertices, triangle, Eigen::Vector3d(  0.0   , 0.0    , 0.0 ));\n    testClosestPoint(Eigen::Vector3d(2,0,0)    , vertices, triangle, Eigen::Vector3d(  1.0   , 0.0    , 0.0 ));\n}\n    \n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "99cb5b4459ccbaa9cea1345161858369c49a7b09", "size": 2659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cisHW3test.cpp", "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": "test/cisHW3test.cpp", "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": "test/cisHW3test.cpp", "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": 40.9076923077, "max_line_length": 183, "alphanum_fraction": 0.690861226, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5696650108436124}}
{"text": "#include \"thin_lq.hpp\"\n\n#include <gtest/gtest.h>\n\n#include <armadillo>\n#include <cmath>\n#include <limits>\n#include <random>\n#include <stdexcept>\n#include <vector>\n\ntemplate <typename Real>\nvoid ThinLqTest(long m, long n) {\n    arma::Mat<Real> A(m, n, arma::fill::randn);\n\n    arma::Mat<Real> L;\n    arma::Mat<Real> Q;\n    ThinLq<Real>(A, L, Q);\n\n    const long k = std::min(m, n);\n\n    ASSERT_EQ(L.size(), m * k);\n    ASSERT_EQ(Q.size(), k * n);\n\n    for (long j = 0; j < k; ++j) {\n        for (long i = 0; i < j; ++i) {\n            ASSERT_NEAR(L(i, j), static_cast<Real>(0),\n                        10 * std::numeric_limits<Real>::epsilon());\n        }\n    }\n\n    for (long i1 = 0; i1 < k; ++i1) {\n        for (long i2 = 0; i2 < i1; ++i2) {\n            Real dot_product = static_cast<Real>(0);\n            for (long j = 0; j < n; ++j) {\n                dot_product += Q(i1, j) * Q(i2, j);\n            }\n\n            ASSERT_NEAR(dot_product, static_cast<Real>(0),\n                        10 * std::numeric_limits<Real>::epsilon());\n        }\n\n        Real norm_squared = static_cast<Real>(0);\n        for (long j = 0; j < n; ++j) {\n            norm_squared += std::pow(Q(i1, j), 2);\n        }\n\n        ASSERT_NEAR(norm_squared, static_cast<Real>(1),\n                    10 * std::numeric_limits<Real>::epsilon());\n    }\n\n    arma::Mat<Real> B = L * Q;\n\n    Real frobenius_error = static_cast<Real>(0);\n    for (long j = 0; j < n; ++j) {\n        for (long i = 0; i < m; ++i) {\n            frobenius_error += std::pow(B(i, j) - A(i, j), 2);\n        }\n    }\n    frobenius_error = std::sqrt(frobenius_error);\n    ASSERT_NEAR(frobenius_error, static_cast<Real>(0),\n                100 * std::numeric_limits<Real>::epsilon());\n}\n\nTEST(ThinLq, Short) {\n    ThinLqTest<float>(4, 64);\n    ThinLqTest<double>(4, 64);\n}\n\nTEST(ThinLq, Square) {\n    ThinLqTest<float>(16, 16);\n    ThinLqTest<double>(16, 16);\n}\n\nTEST(ThinLq, Tall) {\n    ThinLqTest<float>(64, 4);\n    ThinLqTest<double>(64, 4);\n}\n\nint main(int argc, char **argv) {\n    ::testing::InitGoogleTest(&argc, argv);\n\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "10140adaa2ee8947b502b04376bff7762a0f61f7", "size": 2093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/thin_lq_test.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": "test/thin_lq_test.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": "test/thin_lq_test.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": 24.6235294118, "max_line_length": 67, "alphanum_fraction": 0.5236502628, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5696650065337279}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \n//\n// This file is part of the Boost Graph Library\n//\n// You should have received a copy of the License Agreement for the\n// Boost Graph Library along with the software; see the file LICENSE.\n// If not, contact Office of Research, Indiana University,\n// Bloomington, IN 47405.\n//\n// Permission to modify the code and to distribute the code is\n// granted, provided the text of this NOTICE is retained, a notice if\n// the code was modified is included with the above COPYRIGHT NOTICE\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\n// LICENSE file is distributed with the modified code.\n//\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\n// By way of example, but not limitation, Licensor MAKES NO\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\n// OR OTHER RIGHTS.\n//=======================================================================\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/pending/integer_range.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/graph/graphviz.hpp>\n\n\n#include <iostream>\nusing namespace boost;\ntemplate < typename TimeMap > class dfs_time_visitor:public default_dfs_visitor {\n  typedef typename property_traits < TimeMap >::value_type T;\npublic:\n  dfs_time_visitor(TimeMap dmap, TimeMap fmap, T & t)\n:  m_dtimemap(dmap), m_ftimemap(fmap), m_time(t) {\n  }\n  template < typename Vertex, typename Graph >\n    void discover_vertex(Vertex u, const Graph & g) const\n  {\n    put(m_dtimemap, u, m_time++);\n  }\n  template < typename Vertex, typename Graph >\n    void finish_vertex(Vertex u, const Graph & g) const\n  {\n    put(m_ftimemap, u, m_time++);\n  }\n  TimeMap m_dtimemap;\n  TimeMap m_ftimemap;\n  T & m_time;\n};\n\n\nint\nmain()\n{\n  // Select the graph type we wish to use\n  typedef adjacency_list < vecS, vecS, directedS > graph_t;\n  typedef graph_traits < graph_t >::vertices_size_type size_type;\n  // Set up the vertex names\n  enum\n  { u, v, w, x, y, z, N };\n  char name[] = { 'u', 'v', 'w', 'x', 'y', 'z' };\n  // Specify the edges in the graph\n  typedef std::pair < int, int >E;\n  E edge_array[] = { E(u, v), E(u, x), E(x, v), E(y, x),\n    E(v, y), E(w, y), E(w, z), E(z, z)\n  };\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n  graph_t g(N);  \n  for (std::size_t j = 0; j < sizeof(edge_array) / sizeof(E); ++j)\n    add_edge(edge_array[j].first, edge_array[j].second, g);\n#else\n  graph_t g(edge_array, edge_array + sizeof(edge_array) / sizeof(E), N);\n#endif\n\n  // Typedefs\n  typedef boost::graph_traits < graph_t >::vertex_descriptor Vertex;\n  typedef size_type* Iiter;\n\nwrite_graphviz(std::cout, g);\n\n  // discover time and finish time properties\n  std::vector < size_type > dtime(num_vertices(g));\n  std::vector < size_type > ftime(num_vertices(g));\n  size_type t = 0;\n  dfs_time_visitor < size_type * >vis(&dtime[0], &ftime[0], t);\n\n  depth_first_search(g, visitor(vis));\n\n  // use std::sort to order the vertices by their discover time\n  std::vector < size_type > discover_order(N);\n  integer_range < size_type > r(0, N);\n  std::copy(r.begin(), r.end(), discover_order.begin());\n  std::sort(discover_order.begin(), discover_order.end(),\n            indirect_cmp < Iiter, std::less < size_type > >(&dtime[0]));\n  std::cout << \"order of discovery: \";\n  int i;\n  for (i = 0; i < N; ++i)\n    std::cout << name[discover_order[i]] << \" \";\n\n  std::vector < size_type > finish_order(N);\n  std::copy(r.begin(), r.end(), finish_order.begin());\n  std::sort(finish_order.begin(), finish_order.end(),\n            indirect_cmp < Iiter, std::less < size_type > >(&ftime[0]));\n  std::cout << std::endl << \"order of finish: \";\n  for (i = 0; i < N; ++i)\n    std::cout << name[finish_order[i]] << \" \";\n  std::cout << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "dbdac142929f6a2a1350813ca5a3b5522ab75bfd", "size": 4087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "inst/boostExamples/dfs-example.cpp", "max_stars_repo_name": "HenrikBengtsson/RBGL", "max_stars_repo_head_hexsha": "9e34efd0dcab3babe1cea49b060a643bee79931c", "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": "inst/boostExamples/dfs-example.cpp", "max_issues_repo_name": "HenrikBengtsson/RBGL", "max_issues_repo_head_hexsha": "9e34efd0dcab3babe1cea49b060a643bee79931c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-09-05T02:26:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-30T20:28:53.000Z", "max_forks_repo_path": "inst/boostExamples/dfs-example.cpp", "max_forks_repo_name": "HenrikBengtsson/RBGL", "max_forks_repo_head_hexsha": "9e34efd0dcab3babe1cea49b060a643bee79931c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-12-19T10:17:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T01:22:29.000Z", "avg_line_length": 35.850877193, "max_line_length": 81, "alphanum_fraction": 0.6579398092, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5696649985028945}}
{"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": "#include <stan/math/mix/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <test/unit/math/rev/scal/fun/util.hpp>\n#include <test/unit/math/mix/scal/fun/nan_util.hpp>\n\ndouble eps = 1e-6;\ndouble first_deriv_a =\n  (stan::math::falling_factorial(5.0 + eps, 3.0)\n  - stan::math::falling_factorial(5.0 - eps, 3.0))\n  / (2 * eps);\ndouble first_deriv_b =\n  (stan::math::falling_factorial(5.0, 3.0 + eps)\n  - stan::math::falling_factorial(5.0, 3.0 - eps))\n  / (2 * eps);\n\n\ndouble eps2 = 1e-4;\ndouble second_deriv_aa =\n  (stan::math::falling_factorial(5.0 + 2 * eps2, 3.0)\n  - 2 * stan::math::falling_factorial(5.0 + eps2, 3.0)\n  + stan::math::falling_factorial(5.0, 3.0))\n  / std::pow(eps2, 2);\ndouble second_deriv_bb =\n  (stan::math::falling_factorial(5.0, 3.0 + 2 * eps2)\n  - 2 * stan::math::falling_factorial(5.0, 3.0 + eps2)\n  + stan::math::falling_factorial(5.0, 3.0))\n  / std::pow(eps2, 2);\ndouble second_deriv_ab =\n  (stan::math::falling_factorial(5.0 + eps2, 3.0 + eps2)\n  - stan::math::falling_factorial(5.0 - eps2, 3.0 + eps2)\n  - stan::math::falling_factorial(5.0 + eps2, 3.0 - eps2)\n  + stan::math::falling_factorial(5.0 - eps2, 3.0 - eps2))\n  / 4 / std::pow(eps2, 2);\n\ndouble third_deriv_aab =\n  (stan::math::falling_factorial(5.0 + 2 * eps2, 3.0 + eps2)\n  - 2 * stan::math::falling_factorial(5.0 + eps2, 3.0 + eps2)\n  + stan::math::falling_factorial(5.0, 3.0 + eps2)\n  - stan::math::falling_factorial(5.0 + 2 * eps2, 3.0 - eps2)\n  + 2 * stan::math::falling_factorial(5.0 + eps2, 3.0 - eps2)\n  - stan::math::falling_factorial(5.0, 3.0 - eps2))\n  / 2 / std::pow(eps2, 3);\n\ndouble third_deriv_abb =\n  (stan::math::falling_factorial(5.0 + eps2, 3.0 + 2 * eps2)\n  - 2 * stan::math::falling_factorial(5.0 + eps2, 3.0 + eps2)\n  + stan::math::falling_factorial(5.0 + eps2, 3.0)\n  - stan::math::falling_factorial(5.0 - eps2, 3.0 + 2 * eps2)\n  + 2 * stan::math::falling_factorial(5.0 - eps2, 3.0 + eps2)\n  - stan::math::falling_factorial(5.0 - eps2, 3.0))\n  / 2 / std::pow(eps2, 3);\n\nTEST(AgradFwdFallingFactorial,FvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::falling_factorial;\n\n  fvar<var> a(5.0, 1.0);\n  fvar<var> b(3.0, 1.0);\n  fvar<var> c = falling_factorial(a,b);\n\n  EXPECT_FLOAT_EQ(60, c.val_.val());\n  EXPECT_FLOAT_EQ(first_deriv_a + first_deriv_b, c.d_.val());\n\n  AVEC y = createAVEC(a.val_,b.val_);\n  VEC g;\n  c.val_.grad(y,g);\n  EXPECT_FLOAT_EQ(first_deriv_a, g[0]);\n  EXPECT_FLOAT_EQ(first_deriv_b, g[1]);\n}\nTEST(AgradFwdFallingFactorial,FvarVar_2ndDeriv_x) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::falling_factorial;\n\n  fvar<var> a(5.0,1.0);\n  fvar<var> b(3.0,0.0);\n  fvar<var> c = falling_factorial(a,b);\n\n  AVEC y = createAVEC(a.val_,b.val_);\n  VEC g;\n  c.d_.grad(y,g);\n  ASSERT_NEAR(second_deriv_aa, g[0], 0.1);\n}\nTEST(AgradFwdFallingFactorial,FvarVar_2ndDeriv_y) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::falling_factorial;\n\n  fvar<var> a(5.0,0.0);\n  fvar<var> b(3.0,1.0);\n  fvar<var> c = falling_factorial(a,b);\n\n  AVEC y = createAVEC(a.val_,b.val_);\n  VEC g;\n  c.d_.grad(y,g);\n  ASSERT_NEAR(second_deriv_bb, g[1], 0.1);\n}\nTEST(AgradFwdFallingFactorial,FvarFvarVar_1stDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::falling_factorial;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 5.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = falling_factorial(x,y);\n\n  EXPECT_FLOAT_EQ(falling_factorial(5, 3.0), a.val_.val_.val());\n  EXPECT_FLOAT_EQ(first_deriv_a, a.val_.d_.val());\n  EXPECT_FLOAT_EQ(first_deriv_b, a.d_.val_.val());\n  ASSERT_NEAR(second_deriv_ab, a.d_.d_.val(), .01);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.val_.grad(p,g);\n  EXPECT_FLOAT_EQ(first_deriv_a, g[0]);\n  EXPECT_FLOAT_EQ(first_deriv_b, g[1]);\n}\n\nTEST(AgradFwdFallingFactorial,FvarFvarVar_2ndDeriv_x) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::falling_factorial;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 5.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = falling_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.val_.d_.grad(p,g);\n  ASSERT_NEAR(second_deriv_aa, g[0], 0.01);\n  ASSERT_NEAR(second_deriv_ab, g[1], 0.01);\n}\nTEST(AgradFwdFallingFactorial,FvarFvarVar_2ndDeriv_y) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::falling_factorial;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 5.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = falling_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.val_.grad(p,g);\n  ASSERT_NEAR(second_deriv_ab, g[0], 0.01);\n  ASSERT_NEAR(second_deriv_bb, g[1], 0.01);\n}\nTEST(AgradFwdFallingFactorial,FvarFvarVar_3rdDeriv) {\n  using stan::math::fvar;\n  using stan::math::var;\n  using stan::math::falling_factorial;\n\n  fvar<fvar<var> > x;\n  x.val_.val_ = 5.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<var> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<var> > a = falling_factorial(x,y);\n\n  AVEC p = createAVEC(x.val_.val_,y.val_.val_);\n  VEC g;\n  a.d_.d_.grad(p,g);\n  ASSERT_NEAR(third_deriv_aab, g[0], 0.03);\n  ASSERT_NEAR(third_deriv_abb, g[1], 0.03);\n}\n\nstruct falling_factorial_fun {\n  template <typename T0, typename T1>\n  inline\n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return falling_factorial(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdFallingFactorial, nan) {\n  falling_factorial_fun falling_factorial_;\n  test_nan_mix(falling_factorial_,3.0,5.0,false);\n}\n", "meta": {"hexsha": "eb7f37f7b78f48506a86244fb9894163cc0a14e6", "size": 5745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/falling_factorial_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/falling_factorial_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/mix/scal/fun/falling_factorial_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0243902439, "max_line_length": 64, "alphanum_fraction": 0.6612706701, "num_tokens": 2295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.569509705208617}}
{"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": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/breadth_first_search.hpp>\r\n#include <boost/pending/indirect_cmp.hpp>\r\n#include <boost/range/irange.hpp>\r\n\r\n#include <iostream>\r\n\r\nusing namespace boost;\r\ntemplate < typename TimeMap > class bfs_time_visitor:public default_bfs_visitor {\r\n  typedef typename property_traits < TimeMap >::value_type T;\r\npublic:\r\n  bfs_time_visitor(TimeMap tmap, T & t):m_timemap(tmap), m_time(t) { }\r\n  template < typename Vertex, typename Graph >\r\n    void discover_vertex(Vertex u, const Graph & g) const\r\n  {\r\n    put(m_timemap, u, m_time++);\r\n  }\r\n  TimeMap m_timemap;\r\n  T & m_time;\r\n};\r\n\r\n\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  // Select the graph type we wish to use\r\n  typedef adjacency_list < vecS, vecS, undirectedS > graph_t;\r\n  // Set up the vertex IDs and names\r\n  enum { r, s, t, u, v, w, x, y, N };\r\n  const char *name = \"rstuvwxy\";\r\n  // Specify the edges in the graph\r\n  typedef std::pair < int, int >E;\r\n  E edge_array[] = { E(r, s), E(r, v), E(s, w), E(w, r), E(w, t),\r\n    E(w, x), E(x, t), E(t, u), E(x, y), E(u, y)\r\n  };\r\n  // Create the graph object\r\n  const int n_edges = sizeof(edge_array) / sizeof(E);\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  // VC++ has trouble with the edge iterator constructor\r\n  graph_t g(N);\r\n  for (std::size_t j = 0; j < n_edges; ++j)\r\n    add_edge(edge_array[j].first, edge_array[j].second, g);\r\n#else\r\n  typedef graph_traits<graph_t>::vertices_size_type v_size_t;\r\n  graph_t g(edge_array, edge_array + n_edges, v_size_t(N));\r\n#endif\r\n\r\n  // Typedefs\r\n  typedef graph_traits < graph_t >::vertices_size_type Size;\r\n\r\n  // a vector to hold the discover time property for each vertex\r\n  std::vector < Size > dtime(num_vertices(g));\r\n  typedef\r\n    iterator_property_map<std::vector<Size>::iterator,\r\n                          property_map<graph_t, vertex_index_t>::const_type>\r\n    dtime_pm_type;\r\n  dtime_pm_type dtime_pm(dtime.begin(), get(vertex_index, g));\r\n\r\n  Size time = 0;\r\n  bfs_time_visitor < dtime_pm_type >vis(dtime_pm, time);\r\n  breadth_first_search(g, vertex(s, g), visitor(vis));\r\n\r\n  // Use std::sort to order the vertices by their discover time\r\n  std::vector<graph_traits<graph_t>::vertices_size_type > discover_order(N);\r\n  integer_range < int >range(0, N);\r\n  std::copy(range.begin(), range.end(), discover_order.begin());\r\n  std::sort(discover_order.begin(), discover_order.end(),\r\n            indirect_cmp < dtime_pm_type, std::less < Size > >(dtime_pm));\r\n\r\n  std::cout << \"order of discovery: \";\r\n  for (int i = 0; i < N; ++i)\r\n    std::cout << name[discover_order[i]] << \" \";\r\n  std::cout << std::endl;\r\n\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "c8982c2cb8d3e3ec66ddec298c8a951a2e7e698d", "size": 3049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/graph/example/bfs-example.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/graph/example/bfs-example.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/graph/example/bfs-example.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 35.8705882353, "max_line_length": 82, "alphanum_fraction": 0.6297146605, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.569484928677512}}
{"text": "/*\n   (c) Copyright 2012, Hewlett-Packard Development Company, LP\n\n   See the file named COPYING for license details\n*/\n\n/** @file\n    Interpolation search template\n*/\n\n#include <vector>\n#include <iostream>\n\n#include <boost/format.hpp>\n\n#include <Lintel/DebugFlag.hpp>\n#include <Lintel/unstable/InterpolationSearch.hpp>\n#include <Lintel/MersenneTwisterRandom.hpp>\n\nusing namespace std;\nusing lintel::interpolationLowerBound;\nusing boost::format;\n\n// static global so that the fact that std::lower_bound copies the comparator doesn't cause\n// any problems.\n\nsize_t eo_count, compare_count;\n\ntemplate<typename ValueT> struct EstimateOffsetCount {\n    size_t \n    operator()(const ValueT &v, const ValueT &first, const ValueT &last, size_t last_pos) const {\n        ++eo_count;\n        ValueT value_range = last - first;\n        double relative_pos = static_cast<double>(v - first) / value_range; // [0,1]\n        return relative_pos * last_pos;\n    }\n\n};\n\ntemplate<typename ValueT> struct CompareCount {\n    bool operator()(const ValueT &a, const ValueT &b) const {\n        ++compare_count;\n        return a < b;\n    }\n};\n\ntemplate<typename ValueT, typename Iterator> Iterator\ncountingILB(Iterator begin, Iterator end, const ValueT &v) {\n    EstimateOffsetCount<ValueT> eo;\n    return lintel::detail::interpolationLowerBound<2,4,256>(begin, end, v, eo, \n                                                            CompareCount<ValueT>());\n}\n\nvoid testSimple() {\n    vector<int> array;\n\n    for(int i=0; i < 1000; ++i) {\n        array.push_back(i);\n    }\n\n    SINVARIANT(interpolationLowerBound<int>(array.begin(), array.end(), -1) == array.begin());\n    SINVARIANT(interpolationLowerBound(array.begin(), array.end(), 1000) == array.end());\n    for(int i=0; i < 1000; ++i) {\n        vector<int>::iterator iter = interpolationLowerBound(array.begin(), array.end(), i);\n        SINVARIANT(iter >= array.begin() && iter < array.end());\n        SINVARIANT(*iter == i);\n    }\n\n    // Now with counting\n    SINVARIANT(countingILB<int>(array.begin(), array.end(), -1) == array.begin()); // 1 comparison\n    SINVARIANT(countingILB(array.begin(), array.end(), 1000) == array.end()); // 2 comparisons\n    for(int i=0; i < 1000; ++i) {\n        // 1 comparison for 0 (same as -1), 1 eo, 4 comparisons for rest\n        vector<int>::iterator iter = countingILB(array.begin(), array.end(), i);\n        SINVARIANT(iter >= array.begin() && iter < array.end());\n        SINVARIANT(*iter == i);\n    }\n    cout << format(\"%d offset estimations, %d comparisions\\n\") % eo_count % compare_count;\n\n    size_t expect_compare = 1 + 2 + 1 + 4 * 999;\n    IF_LINTEL_DEBUG(expect_compare += 2 * 999); // debug checks cost another 2 compares/cycle\n    SINVARIANT(eo_count == 999 && compare_count == expect_compare);\n\n    array.clear();\n    array.resize(1000);\n    for (ssize_t i = array.size() - 1; i >= 0; --i) {\n        array[i] = 2;\n        vector<int>::iterator at = interpolationLowerBound(array.begin(), array.end(), 1);\n        INVARIANT(at == (array.begin() + i), format(\"%d != %d\") % i % (at - array.begin()));\n    }\n    cout << \"test simple passed.\\n\";\n\n}\n\nvoid testRandom() {\n    MersenneTwisterRandom rng;\n    cout << format(\"test random seed=%d...\") % rng.seedUsed();\n\n    static const size_t nvals = 256 * 1024;\n\n    vector<int> array;\n\n    for(size_t i=0; i < nvals; ++i) {\n        // * 16 == some duplicates, mostly unique, efficient calculation\n        array.push_back(rng.randInt(nvals*16)); \n    }\n    sort(array.begin(), array.end());\n\n    for(size_t i=0;i < nvals; ++i) {\n        int v = rng.randInt(nvals*10);\n        vector<int>::iterator ilb = interpolationLowerBound(array.begin(), array.end(), v);\n        vector<int>::iterator lb = lower_bound(array.begin(), array.end(), v);\n        INVARIANT(ilb == lb, format(\"for %d: %d != %d\") % v % (ilb == array.end() ? -1 : *ilb)\n                  % (lb == array.end() ? -1 : *lb));\n    }\n\n    cout << \"passed.\\n\";\n}\n\nint main() {\n    testSimple();\n    testRandom();\n    return 0;\n}\n", "meta": {"hexsha": "6d6e4a720ff5ee1b359e292b45d595c099fe4734", "size": 4017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/interpolation-search.cpp", "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": "src/tests/interpolation-search.cpp", "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": "src/tests/interpolation-search.cpp", "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": 32.136, "max_line_length": 98, "alphanum_fraction": 0.6156335574, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5694849128116799}}
{"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": "//  (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 <random>\n#include <benchmark/benchmark.h>\n#include <boost/math/tools/agm.hpp>\n#include <boost/multiprecision/float128.hpp>\n\nusing boost::math::tools::agm;\ntemplate<class Real>\nvoid AGM(benchmark::State& state)\n{\n    std::random_device rd;\n    std::mt19937_64 mt(rd());\n    std::uniform_real_distribution<long double> unif(1,100);\n\n    Real x = static_cast<Real>(unif(mt));\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(agm(x,Real(1)));\n    }\n}\n\nBENCHMARK_TEMPLATE(AGM, float);\nBENCHMARK_TEMPLATE(AGM, double);\nBENCHMARK_TEMPLATE(AGM, long double);\nBENCHMARK_TEMPLATE(AGM, boost::multiprecision::float128);\n\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "53ee4b358595ec658bae97c41ed6c28c599c086b", "size": 883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reporting/performance/test_agm.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": "reporting/performance/test_agm.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/reporting/performance/test_agm.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 26.7575757576, "max_line_length": 68, "alphanum_fraction": 0.7191392978, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5694826978053893}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#include <boost/simd/function/scalar/nthroot.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/half.hpp>\n\nSTF_CASE_TPL (\" nthroot\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::nthroot;\n  using iT = bd::as_integer_t<T>;\n  using r_t = decltype(nthroot(T(), iT()));\n\n  // return type conformity test\n STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(nthroot(bs::Inf<T>(),iT(3)), bs::Inf<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Inf<T>(),iT(4)), bs::Inf<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Minf<T>(),iT(3)), bs::Minf<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Minf<T>(),iT(4)), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Nan<T>(),iT(3)), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Nan<T>(),iT(4)), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Mone<T>(),iT(4)), bs::Nan<r_t>(), 0.5);\n#endif\n  STF_ULP_EQUAL(nthroot(bs::Mone<T>(),iT(0)), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::One <T>(),iT(0)), bs::One<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Half<T>(),iT(0)), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Two <T>(),iT(0)), bs::Inf <r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Zero<T>(),iT(0)), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Two <T>(),iT(0)), bs::Inf<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Half<T>(),iT(0)), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Mone<T>(),iT(3)), bs::Mone<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::One<T>(),iT(3)), bs::One<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::One<T>(),iT(4)), bs::One<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Zero<T>(),iT(3)), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(bs::Zero<T>(),iT(4)), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(nthroot(T(-8),iT(3)), r_t(-2), 0.5);\n  STF_ULP_EQUAL(nthroot(T(256),iT(4)), r_t(4), 0.5);\n  STF_ULP_EQUAL(nthroot(T(8),iT(3)), r_t(2), 0.5);\n  STF_ULP_EQUAL(nthroot(T(0.5), iT(4)), r_t(0.84089641525371454303112547623321), 0.5);\n}\n\n\n\n", "meta": {"hexsha": "ae67a48af55e2b0d94b38f6ac6dde468e3218417", "size": 2691, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/nthroot.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "test/function/scalar/nthroot.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/scalar/nthroot.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 42.7142857143, "max_line_length": 100, "alphanum_fraction": 0.6012634708, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5694655893718552}}
{"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": "#pragma once\n#include <Eigen/Dense>\n#include <nlohmann/json.hpp>\n#include \"Optimizers/Optimizer.hpp\"\n\nnamespace yannq\n{\ntemplate<typename T>\nclass SGDMomentum\n\t: public Optimizer<T>\n{\npublic:\n\tusing typename Optimizer<T>::Vector;\n\tusing typename Optimizer<T>::RealVector;\n\n\tstatic constexpr double DEFAULT_PARAMS[] = {0.05, 0.0, 0.9};\n\nprivate:\n\tdouble alpha_;\n\tdouble p_;\n\tdouble gamma_;\n\n\tVector m_;\n\tint t_;\n\npublic:\n\n\tSGDMomentum(double alpha = DEFAULT_PARAMS[0], double p = DEFAULT_PARAMS[1], double gamma = DEFAULT_PARAMS[2])\n\t\t: alpha_{alpha}, p_{p}, gamma_{gamma}, t_{0}\n\t{\n\t}\n\n\tSGDMomentum(const nlohmann::json& params)\n\t\t: alpha_{params.value(\"alpha\", DEFAULT_PARAMS[0])}, \n\t\t\tp_{params.value(\"p\", DEFAULT_PARAMS[1])},\n\t\t\tgamma_{params.value(\"gamma\", DEFAULT_PARAMS[2])},\n\t\t\tt_{0}\n\t{\n\t}\n\n\tnlohmann::json desc() const override\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"SGD\"},\n\t\t\t{\"alhpa\", alpha_},\n\t\t\t{\"gamma\", gamma_},\n\t\t\t{\"p\", p_}\n\t\t};\n\t}\n\n\tVector getUpdate(const Vector& v) override\n\t{\n\t\tusing std::pow;\n\t\tif(t_ == 0)\n\t\t{\n\t\t\tm_ = Vector::Zero(v.size());\n\t\t}\n\n\t\t++t_;\n\t\tm_ *= gamma_;\n\t\tm_ += (1-gamma_)*v;\n\t\tdouble eta = std::max((alpha_/pow(t_, p_)), 1e-4)/(1.0 - pow(gamma_, t_));\n\t\treturn -eta*m_;\n\t}\n};\n}//namespace yannq\ntemplate<typename T>\nconstexpr double yannq::SGDMomentum<T>::DEFAULT_PARAMS[];\n", "meta": {"hexsha": "a1d6a209f8dd97c317856ed409215f3e9754349c", "size": 1318, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Optimizers/SGDMomentum.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/Optimizers/SGDMomentum.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/Optimizers/SGDMomentum.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8285714286, "max_line_length": 110, "alphanum_fraction": 0.653262519, "num_tokens": 422, "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": "#include <iostream>\n#include <string>\n#include <tuple>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <limits>\n#include <iterator>\n#include <armadillo>\n#include <cmath>\n#include <iomanip>\n\nusing namespace std;\n\n// Block of global vars\nconst long double PI = 3.141592653589793238L;\n// Block of global vars\n\n// Block of declarations\ntuple < vector < tuple < int, int > >, int, int > read_input( string file_name );\nvector < string > string_tokenizer( string string_to_tok, char separator );\nvector < tuple < int, int > > greedy( tuple < vector < tuple < int, int > >, int, int > input );\nvector < tuple < int, int > > divide_n_conquer( tuple < vector < tuple < int, int > >, int, int > input );\nvector < tuple < int, int > > divide_n_conquer_( vector < tuple < int, int > > input, vector < tuple < int, int > > fixed_points, int width, int height );\nvector < tuple < int, int > > divide_n_conquer2_( vector < tuple < int, int > > input, vector < tuple < int, int > > fixed_points, int width, int height );\nvector < tuple < int, int > > divide_n_conquer3_( vector < tuple < int, int > > input, int width, int height );\nvector < tuple < int, int > > dynamic( tuple < vector < tuple < int, int > >, int, int > input );\nvector < tuple < int, int > > dynamic_( vector < tuple < int, int > > input, vector < tuple < int, int > > fixed_points, int width, int height );\nvector < tuple < int, int > > dynamic2_( vector < tuple < int, int > > input, int width, int height );\nvector < tuple < int, int > > dynamic3_( vector < tuple < int, int > > input, int width, int height );\nvector < int > sort_by_radius( vector < int > input );\nbool are_intersected( tuple < int, int > new_point, vector < tuple < int, int > > fixed_points, int  height, int width );\nvector < tuple < int, int > > divide_n_conquer_merge_( vector < tuple < int, int > > input_0, vector < tuple < int, int > > input_1, int width, int height );\nstring get_geogebra_plot_command( vector < tuple < int, int > > points, int  height, int width );\nvector < vector < tuple < int, int > > > split_vector( vector < tuple < int, int > > vector_, int split_point );\nvector < tuple < int, int > > merge_vectors( vector < tuple < int, int > > vector_0, vector < tuple < int, int > > vector_1 );\nvector < tuple < int, int > > max( vector < tuple < int, int > > vector_0, vector < tuple < int, int > > vector_1 );\ndouble circle_area( double radius );\nvoid merge_sort(int arr[], int l, int r);\nvoid merge(int arr[], int l, int m, int r);\ndouble calculate_input_area( vector < tuple < int, int > > input );\n// End block of declarations\n\nint main( int argc, const char* argv[] ){\n\n    tuple < vector < tuple < int, int > >, int, int > input = read_input( \"input.txt\" );\n\n    int width = get< 1 >( input );\n    int height = get< 2 >( input );\n    vector < tuple < int, int > > points =  get< 0 >( input );\n\n    cout << endl << \"Comandos para Geogebra [ Entrada ]: \";\n    cout << get_geogebra_plot_command( points, height, width ) << endl;\n\n    vector < tuple < int, int > > greedy_solution = greedy( input );\n    cout << endl << \"Comandos para Geogebra [ Salida: Voraz, \u00c1rea: \" << calculate_input_area( greedy_solution ) << \" ]: \";\n    cout << get_geogebra_plot_command( greedy_solution, height, width ) << endl;\n\n    vector < tuple < int, int > > divide_n_conquer_solution = divide_n_conquer( input );\n    cout << endl << \"Comandos para Geogebra [ Salida: Divide y vencer\u00e1s, \u00c1rea: \" << calculate_input_area( divide_n_conquer_solution ) << \" ]: \";\n    cout << get_geogebra_plot_command( divide_n_conquer_solution, height, width ) << endl;\n\n    vector < tuple < int, int > > dynamic_solution = dynamic( input );\n    cout << endl << \"Comandos para Geogebra [ Salida: Programaci\u00f3n din\u00e1mica, \u00c1rea: \" << calculate_input_area( dynamic_solution ) << \" ]: \";\n    cout << get_geogebra_plot_command( dynamic_solution, height, width ) << endl;\n\n    cout << endl;\n    return 0;\n};\n\ntuple < vector < tuple < int, int > >, int, int > read_input( string file_name ){\n    tuple < vector < tuple < int, int > >, int, int > to_return;\n    vector < tuple < int, int > > points_info;\n    int width, height = 0;\n    bool first_line = true;\n    ifstream f_input( file_name.c_str() );\n    string line = \"\";\n    while( getline( f_input, line ) ){\n        if( ( line[0] != '#' ) && ( line[0] != ' ' ) ){\n            if( first_line ){\n                vector < string > map_info = string_tokenizer( line, ' ' );\n                width = stoi( map_info[0] );\n                height = stoi( map_info[1] );\n                first_line = false;\n            }else{\n                vector < string > map_info = string_tokenizer( line, ' ' );\n                tuple < int, int > point_info = make_tuple( stoi( map_info[0] ), stoi( map_info[1] ) );\n                points_info.push_back( point_info );\n            };\n        };\n    };\n    f_input.close();\n    to_return = make_tuple( points_info, width, height );\n    return to_return;\n};\n\nvector < string > string_tokenizer( string string_to_tok, char separator ){\n    vector < string > to_return;\n    string tmp_line = \"\";\n    for( int i = 0; i < string_to_tok.size(); i++ ){\n        if( string_to_tok[i] == separator ){\n            to_return.push_back( tmp_line );\n            tmp_line = \"\";\n        }else{\n            tmp_line.push_back( string_to_tok[i] );\n        };\n    };\n    to_return.push_back( tmp_line );\n    return to_return;\n};\n\nvector < tuple < int, int > > greedy( tuple < vector < tuple < int, int > >, int, int > input ){\n    vector < tuple < int, int > > to_return; \n    int width = get< 1 >( input );\n    int height = get< 2 >( input );\n    vector < tuple < int, int > > points =  get< 0 >( input );\n    vector < int > radius;\n    for( int i = 0; i < points.size(); i++ ){\n        radius.push_back( get< 1 >( points[i] ) );\n    };\n    radius = sort_by_radius( radius );\n    vector < tuple < int, int > > sorted_points;\n    for( int i = 0; i < radius.size(); i++ ){\n        for( int j = 0; j < points.size(); j++ ){\n            if( radius[i] == get< 1 >( points[j] ) ){\n                sorted_points.push_back( points[j] );\n                points.erase( points.begin() + j );\n            };\n        };\n    };\n    reverse( sorted_points.begin(), sorted_points.end() );\n    for( int i = 0; i < sorted_points.size(); i++ ){\n        bool are_intersected_ = are_intersected_ = are_intersected( sorted_points[i], to_return, height, width );\n        if( !are_intersected_ ){\n            to_return.push_back( sorted_points[i] );\n        };\n        //cout << \"P: \" << get<0>( sorted_points[i] ) << \" - R:\" << get<1>( sorted_points[i] ) << \" - TR: \" << are_intersected_ << endl;\n    };\n    return to_return;\n};\n\nvector < tuple < int, int > > divide_n_conquer( tuple < vector < tuple < int, int > >, int, int > input ){\n    int width = get< 1 >( input );\n    int height = get< 2 >( input );\n    vector < tuple < int, int > > fixed_points;\n    vector < tuple < int, int > > input_x = get<0>( input );\n    //Limpiando la entrada\n    for( int i = 0; i < input_x.size(); i++ ){\n        if( are_intersected( input_x[i], fixed_points, height, width ) ){\n            input_x.erase(input_x.begin() + i);\n        };\n    };\n    int input_x_size = input_x.size();\n    vector < int > radius;\n    vector < tuple < int, int > > sorted_points;\n    for( int i = 0; i < input_x.size(); i++ ){\n        radius.push_back( get< 1 >( input_x[i] ) );\n    };\n    int radius_size = radius.size();\n    radius = sort_by_radius( radius );\n    for( int i = 0; i < radius_size; i++ ){\n        for( int j = 0; j < input_x_size; j++ ){\n            if( radius[i] == get< 1 >( input_x[j] ) ){\n                sorted_points.push_back( input_x[j] );\n                input_x.erase( input_x.begin() + j );\n            };\n        };\n    };\n    reverse( sorted_points.begin(), sorted_points.end() );\n\n    //return divide_n_conquer_( get<0>( input ), fixed_points, width, height );\n    //return divide_n_conquer2_( input_x, fixed_points, width, height );\n    vector < tuple < int, int > > to_return = divide_n_conquer3_( sorted_points, width, height );\n    int to_return_size = to_return.size();\n    for(int i = 0; i < to_return_size; i++){\n        if( ( get<0>( to_return[i] ) == 0) && ( get<1>( to_return[i] ) == 0 ) ){\n            to_return.erase( to_return.begin() + i );\n        };\n    };\n    return to_return;\n};\n\nvector < tuple < int, int > > divide_n_conquer3_( vector < tuple < int, int > > input, int width, int height ){\n    int input_size = input.size();\n    if( input_size == 1 ){\n        return input;\n    }else{\n        int s_p = input_size/2;\n        vector < vector < tuple < int, int > > > vector_splited = split_vector( input, s_p );\n        return divide_n_conquer_merge_(\n            divide_n_conquer3_( vector_splited[0], width, height ),\n            divide_n_conquer3_( vector_splited[1], width, height ),\n            width,\n            height\n        );\n    };\n};\n\nvector < tuple < int, int > > divide_n_conquer_merge_( vector < tuple < int, int > > input_0, vector < tuple < int, int > > input_1, int width, int height ){\n    vector < tuple < int, int > > to_return;\n    int size_input_0 = input_0.size();\n    int size_input_1 = input_1.size();\n    int i = 0;\n    int j = 0; \n    int k;\n    if( size_input_0 >= size_input_1 ){\n        k = size_input_0 + ( size_input_0 - size_input_1 );\n    }else{\n        k = size_input_1 + ( size_input_1 - size_input_0 );\n    };\n    while( k >= 0 ){\n        if( ( size_input_0 > 0 ) && ( size_input_1 > 0 ) ){\n            int area_i = circle_area( get<1>( input_0[i] ) );\n            int area_j = circle_area( get<1>( input_1[j] ) );\n            if( area_i >= area_j ){\n                if( !are_intersected( input_0[i], to_return, height, width ) ){\n                    to_return.push_back( input_0[i] );\n                };\n                i++;\n            }else{\n                if( !are_intersected( input_1[j], to_return, height, width ) ){\n                    to_return.push_back( input_1[j] );\n                };\n                j++;\n            };\n        }else if( ( size_input_0 == 0 ) && ( size_input_1 > 0 ) ){\n            if( !are_intersected( input_1[j], to_return, height, width ) ){\n                to_return.push_back( input_1[j] );\n            };\n            j++;\n        }else if( ( size_input_0 > 0 ) && ( size_input_1 == 0 ) ){\n            if( !are_intersected( input_0[i], to_return, height, width ) ){\n                to_return.push_back( input_0[i] );\n            };\n            i++;\n        };\n        k--;\n    };\n    return to_return;\n};\n\nvector < tuple < int, int > > divide_n_conquer2_( vector < tuple < int, int > > input, vector < tuple < int, int > > fixed_points, int width, int height ){\n\n     if( input.size() == 1 ){\n         if( !are_intersected( input[0], fixed_points, height, width  ) ){\n            fixed_points.push_back( input[0] );\n            return fixed_points;\n         };\n    }else if( input.size() == 2 ){\n        vector < tuple < int, int > > points;\n        vector < tuple < int, int > > to_return;\n        points.push_back( input[1] );\n        if( !are_intersected( input[0], points, height, width  ) ){\n            points.push_back( points[0] );\n            return points;\n        }else{\n            if( get<1>(input[0]) > get<1>(input[1]) ){\n                to_return.push_back( input[0] );\n            }else{\n                to_return.push_back( input[1] );\n            };\n            return to_return;\n        };\n    }else{\n        int s_p = input.size()/2;\n        vector < vector < tuple < int, int > > > vector_splited = split_vector( input, s_p );\n        //vector < tuple < int, int > > max( vector < tuple < int, int > > vector_0, vector < tuple < int, int > > vector_1 );\n        return merge_vectors( \n            max ( \n                divide_n_conquer2_( vector_splited[0], fixed_points, width, height ), fixed_points ), \n                merge_vectors( \n                        max( divide_n_conquer2_( vector_splited[1], fixed_points, width, height ),fixed_points ), fixed_points )\n                );\n    };\n\n};\n\nvector < tuple < int, int > > divide_n_conquer_( vector < tuple < int, int > > input, vector < tuple < int, int > > fixed_points, int width, int height ){\n    if( input.size() == 0 ){\n        return fixed_points;\n    }else if( input.size() > 0 ){\n        int major_radius_index = 0;\n        for( int i = 0; i < input.size(); i++ ){\n            if( get<1>( input[i] ) >= get<1>( input[major_radius_index] ) ){\n                major_radius_index = i;\n            };\n        };\n        bool a_i = are_intersected( input[major_radius_index], fixed_points, height, width );\n        if( !a_i ){\n            fixed_points.push_back( input[major_radius_index] );\n            input.erase(input.begin() + major_radius_index);\n            return divide_n_conquer_( input, fixed_points, width, height );\n        }else{\n            input.erase(input.begin() + major_radius_index);\n            return divide_n_conquer_( input, fixed_points, width, height );\n        };\n    };\n};\n\nvector < tuple < int, int > > dynamic( tuple < vector < tuple < int, int > >, int, int > input ){\n    vector < tuple < int, int > > points = get<0>( input );\n    vector < tuple < int, int > > empty;\n    int width = get< 1 >( input );\n    int height = get< 2 >( input );\n    // int area = width * height;\n    //Limpiando la entrada\n    for( int i = 0; i < points.size(); i++ ){\n        if( are_intersected( points[i], empty, height, width ) ){\n            points.erase(points.begin() + i);\n        };\n    };\n    //return dynamic_( points, empty, width, height );\n    //return dynamic2_( points, width, height );\n    return dynamic3_( points, width, height );\n};\n\nvector < tuple < int, int > > dynamic_( vector < tuple < int, int > > input, vector < tuple < int, int > > fixed_points, int width, int height ){\n    vector < tuple < int, int > > to_return;\n    if( input.size() == 2 ){\n        vector < vector < tuple < int, int > > > v_s = split_vector( input, 1 );\n        bool a_i = are_intersected( v_s[0][0], v_s[1], height, width );\n        if( !a_i ){\n            return input;\n        }else{\n            vector < tuple < int, int > > empty;\n            return empty;\n        };\n    }else{\n        int s_p = input.size()/2;\n        vector < vector < tuple < int, int > > > vector_splited = split_vector( input, s_p );\n        fixed_points = merge_vectors( max( max (dynamic_( vector_splited[0], fixed_points, width, height ), fixed_points), max( dynamic_( vector_splited[1], fixed_points, width, height ), fixed_points ) ), fixed_points );\n        return fixed_points;\n    };\n};\n\nvector < tuple < int, int > > dynamic2_( vector < tuple < int, int > > input, int width, int height ){\n    cout << endl << \"DEBUG\" << endl << endl;\n    vector < tuple < int, int > > to_return;\n    vector < tuple < int, int > > empty;\n    vector < double > total_areas;\n    int input_size = input.size();\n    //Limpiando la entrada\n    for( int i = 0; i < input_size; i++ ){\n        if( are_intersected( input[i], empty, height, width ) ){\n            input.erase(input.begin() + i);\n        };\n    };\n    input_size = input.size();\n\n\n    vector < int > radius;\n    for( int i = 0; i < input.size(); i++ ){\n        radius.push_back( get< 1 >( input[i] ) );\n    };\n    radius = sort_by_radius( radius );\n    vector < tuple < int, int > > sorted_input;\n    for( int i = 0; i < radius.size(); i++ ){\n        for( int j = 0; j < input.size(); j++ ){\n            if( radius[i] == get< 1 >( input[j] ) ){\n                sorted_input.push_back( input[j] );\n                input.erase( input.begin() + j );\n            };\n        };\n    };\n    reverse( sorted_input.begin(), sorted_input.end() );\n    input = sorted_input;\n\n    double areas[ input_size ][ input_size ];\n    int id_major_area_row = 0;\n    for( int i = 0; i < input_size; i++ ){\n        double total_area_row = 0;\n        for( int j = 0; j < input_size; j++ ){\n            if( i == j ){\n                if( !are_intersected( input[i], empty, height, width ) ){\n                    areas[i][j] =PI * pow( get<1>( input[j] ), 2 ); \n                };\n            }else{\n                bool flag_valid = true;\n                if( are_intersected( input[i], empty, height, width ) ){\n                    flag_valid = false;\n                };\n                if( are_intersected( input[j], empty, height, width ) ){\n                    flag_valid = false;\n                };\n                if( flag_valid ){\n                    vector < tuple < int, int > > fixed_points;\n                    fixed_points.push_back( input[j] );\n                    flag_valid = !are_intersected( input[i], fixed_points, height, width );\n                    cout << i << \" \" << j << \" \" << flag_valid << endl;\n                };\n                if( flag_valid ){\n                    areas[i][j] = ( PI * pow( get<1>( input[i] ), 2 ) ) + ( PI * pow( get<1>( input[j] ), 2 ) ); \n                }else{\n                    areas[i][j] = 0;\n                };\n            };\n            total_area_row += areas[i][j];\n        };\n        total_areas.push_back( total_area_row );\n        if( total_area_row > total_areas[id_major_area_row] ){\n            id_major_area_row = i;\n        };\n    };\n\n    for( int x = 0; x < input_size; x++ ){\n        int total = 0;\n        for( int y = 0; y < input_size; y++ ){\n            cout << areas[x][y] << \" # \";\n            total += areas[x][y];\n        };\n        cout << \"   => TOTAL:\" << total;\n        cout << endl;\n    };\n\n    int pivot_row = id_major_area_row;\n    int filter_row[ input_size ][ input_size ];\n    cout << endl;\n    for( int i = 0; i < input_size; i++ ){\n        cout << \"Pivot: \" << pivot_row << endl;\n        for( int j = 0; j < input_size; j++ ){\n            if( areas[pivot_row][j] != 0 ){\n                filter_row[ i ][ j ] = 1;\n            }else{\n                filter_row[ i ][ j ] = 0;\n            };\n        };\n        for( int k = i; k < input_size; k++ ){\n            if( ( filter_row[ 0 ][k] == 1 ) ){\n                pivot_row = k;\n                break;\n            };\n        };\n    };\n    cout << endl << endl;\n    for( int i = 0; i < input_size; i++ ){\n        for( int j = 0; j < input_size; j++ ){\n            cout << filter_row[i][j] << \" \";\n        };\n        cout << endl;\n    };\n    cout << endl << \"Resultado\" << endl;\n    int result[ input_size ];\n    for( int i = 0; i < input_size; i++ ){\n        bool zero_flag = false;\n        for( int j = 0; j < input_size; j++ ){\n            if( filter_row[j][i] == 0 ){\n                zero_flag = true;\n                break;\n            };\n        };\n        if( zero_flag ){\n            result[i] = 0;\n        }else{\n            result[i] = 1;\n            to_return.push_back( input[i] );\n        };\n    };\n\n    for( int i = 0; i < input_size; i++ ){\n        cout << result[i] << \" \";\n    };\n    cout << endl;\n\n    for( int i = 0; i < input_size; i++ ){\n        cout << get<0>(input[i]) << \" - \" << get<1>(input[i]) << \" ||| \";\n    };\n\n    cout << endl << \"END DEBUG\" << endl;\n    return to_return;\n};\n\nvector < tuple < int, int > > dynamic3_( vector < tuple < int, int > > input, int width, int height ){\n\n    vector < tuple < int, int > > to_return;\n    vector < tuple < int, int > > empty;\n    int input_size = input.size();\n    //Limpiando la entrada\n    for( int i = 0; i < input_size; i++ ){\n        if( are_intersected( input[i], empty, height, width ) ){\n            input.erase(input.begin() + i);\n        };\n    };\n    input_size = input.size();\n    vector < tuple < int, int, double > > vec_start_end_n_area;\n    int array_end_points[ input_size ];\n    for( int i = 0; i < input_size; i++ ){\n        int point = get<0>( input[i] );\n        int radius = get<1>( input[i] );\n        tuple < int, int, double > tmp = make_tuple( (point - radius), (point + radius), circle_area( radius ) );\n        vec_start_end_n_area.push_back( tmp );\n        array_end_points[ i ] = (point + radius);\n    };\n    merge_sort( array_end_points, 0, input_size - 1 );\n    // std::cout << endl;\n    // for(int i = 0; i < input_size; i++){\n    //     std::cout << \"Start Point: \" << get<0>( vec_start_end_n_area[i] ) << \" end point \" << get<1>( vec_start_end_n_area[i] ) << std::endl;\n    //     std::cout << array_end_points[i] << std::endl; \n    // };\n\n    vector < tuple < int, int, double > > sorted_vec_start_end_n_area;\n    for(int i = 0; i < input_size; i++){\n        int vec_start_end_n_area_size = vec_start_end_n_area.size();\n        for(int j = 0; j < vec_start_end_n_area_size; j++){\n            int end = get<1>( vec_start_end_n_area[j] );\n            if( array_end_points[i] == end ){\n                sorted_vec_start_end_n_area.push_back( vec_start_end_n_area[j] );\n                vec_start_end_n_area.erase( vec_start_end_n_area.begin() + j );\n            };\n        };\n    };\n\n    std::cout << std::endl << \"Sorted circles\" << std::endl;\n    for(int i = 0; i < input_size; i++){\n        std::cout << \"Start Point: \" << get<0>( sorted_vec_start_end_n_area[i] ) << \", \" << get<1>( sorted_vec_start_end_n_area[i] ) << \", \" << get<2>( sorted_vec_start_end_n_area[i] )  << std::endl;\n    };\n\n    double total_areas[ input_size ]; \n    // Fist case\n    total_areas[ 0 ] = get<2>( sorted_vec_start_end_n_area[ 0 ] );\n\n    vector < tuple < vector < tuple < int, int, double > >, int > > sub_solutions;\n    int index_of_circles[ input_size ][ input_size ];\n    for( int i = 0; i < input_size; i++ ){\n        for( int j = 0; j < input_size; j++ ){\n            index_of_circles[i][j] = 0;\n        };\n    };\n\n    index_of_circles[0][0] = 1;\n\n    for( int i = 1; i < input_size; i++ ){\n        \n        int start = get<0>( sorted_vec_start_end_n_area[ i ] );\n        double acumulated_area = get<2>( sorted_vec_start_end_n_area[i] );\n        int new_j = -1;\n        //vector < tuple < int, int, double > > sub_solution;\n        for( int j = i - 1; j >= 0; j-- ){\n            int sub_end = get<1>( sorted_vec_start_end_n_area[ j ] );\n            if( sub_end <= start ){\n                new_j = j;\n                break;\n            };\n        };\n        if( new_j != -1 ){\n            acumulated_area += total_areas[ new_j ];\n        };\n        \n        // CASO 1 AUMENTA Y ENCUENTRA\n        // CASO 2 NO AUMENTA PERO ENCUENTRA\n        // CASO 3 NO AUMENTA NO ENCUENTRA\n        \n        total_areas[i] = std::max( total_areas[ i - 1 ], acumulated_area );\n        /*if( ( total_areas[i] == acumulated_area ) && (  new_j != -1 ) ){\n            for( int x = 0; x < input_size; x++ ){\n                //index_of_circles[i][x] = index_of_circles[i-1][x];\n                index_of_circles[i][x] = 0;\n             };\n            index_of_circles[i][new_j] = 1;\n            index_of_circles[i][i] = 1;\n        }else if( ( total_areas[i] == total_areas[ i - 1 ] ) && (  new_j != -1 ) ){\n            for( int x = 0; x < input_size; x++ ){\n                //index_of_circles[i][x] = index_of_circles[i-1][x];\n                index_of_circles[i][x] = 0;\n            };\n            //index_of_circles[i][new_j] = 1;\n            index_of_circles[i][new_j] = 1;\n            index_of_circles[i][i] = 1;\n        }else if( ( total_areas[i] == total_areas[ i - 1 ] ) && (  new_j == -1 ) ){\n            for( int x = 0; x < input_size; x++ ){\n                index_of_circles[i][x] = index_of_circles[i-1][x];\n             };\n            //index_of_circles[i][new_j] = 1;\n        }else if( ( total_areas[i] == acumulated_area ) && (  new_j == -1 ) ){\n            for( int x = 0; x < input_size; x++ ){\n                index_of_circles[i][x] = 0;\n             };\n            index_of_circles[i][i] = 1;\n        };*/\n        \n        if( new_j != -1 ){\n            index_of_circles[i][new_j] = 2;\n            index_of_circles[i][i] = 1;\n        }else{\n            index_of_circles[i][i] = 1;\n        };\n\n        //tuple < vector < tuple < int, int, double > >, int > sub_solution_with_area = make_tuple( sub_solution, acumulated_area );\n        //sub_solutions.push_back( sub_solution_with_area );\n    };\n\n    std::cout << \"\\n\" ;\n    double matrix_areas[ input_size ];\n    int id_max_matrix_areas = 0;\n    for( int i = 0; i < input_size; i++ ){\n        matrix_areas[ i ] = 0;\n        for( int j = 0; j < input_size; j++ ){\n            std::cout << index_of_circles[i][j] << \" \";\n            if( ( index_of_circles[i][j] == 1 ) || ( index_of_circles[i][j] == 2 ) ){\n                matrix_areas[ i ] += get<2>( sorted_vec_start_end_n_area[ j ] );\n            };\n        };\n        if( matrix_areas[ i ] >= matrix_areas[ id_max_matrix_areas ] ){\n            id_max_matrix_areas = i;\n        };\n        std::cout << \"  <= BA: \" << total_areas[i] << \" A: \" << matrix_areas[i];\n        std::cout << endl;\n    };\n\n    std::cout << \"\\n\u00c1rea m\u00e1xima, prog din\u00e1mica: \" << total_areas[ input_size - 1 ] << std::endl;\n\n    // std::cout << std::endl << \"Areas\" << std::endl;\n    // int id_max_subsolution = 0;\n    // int total_area_solution = 0;\n    // for(int i = 0; i < sub_solutions.size(); i++){\n    //     total_area_solution += get<1>(sub_solutions[i]);\n    //     std::cout << \"Sub_sol Area: \" << get<1>( sub_solutions[ i ] ) << \" T:\" << get<0>( sub_solutions[ i ] ).size() << std::endl;\n    //     int i_total_area_sub_solution = get<1>( sub_solutions[ i ] );\n    //     int current_total_area_solution = get<1>( sub_solutions[ id_max_subsolution ] );\n    //     if( i_total_area_sub_solution >= current_total_area_solution ){\n    //         id_max_subsolution = i;\n    //     };\n    // };\n    \n    // vector < tuple < int, int, double > > best_solution = get<0>( sub_solutions[ id_max_subsolution ] );\n    // int total_area_best_solution = get<1>( sub_solutions[ id_max_subsolution ] );\n    // int size_of_elements_in_solution = best_solution.size();\n    // for(int i = 0; i < size_of_elements_in_solution; i++){\n    //     std::cout << \"Start Point: \" << get<0>( best_solution[i] ) << \" end point \" << get<1>( best_solution[i] ) << std::endl;\n    // };\n\n    // Build solution\n    vector < int > index_sol_circles;\n    int i = id_max_matrix_areas;\n    int sorted_vec_start_end_n_area_size = sorted_vec_start_end_n_area.size();\n    while( i >= 0 ){\n        bool flag_two = false;\n        int pivot = -1;\n        for( int j = 0; j < sorted_vec_start_end_n_area_size; j++ ){\n            if( index_of_circles[ i ][ j ] == 1 ){\n                int index_sol_circles_size = index_sol_circles.size();\n                bool exist = false;\n                for( int k = 0; k < index_sol_circles_size; k++ ){\n                    if( index_sol_circles[k] == j ){\n                        exist = true;\n                        break;\n                    };\n                };\n                if( !exist ){\n                    index_sol_circles.push_back( j );\n                };\n            };\n            if( index_of_circles[ i ][ j ] == 2 ){\n                int index_sol_circles_size = index_sol_circles.size();\n                bool exist = false;\n                for( int k = 0; k < index_sol_circles_size; k++ ){\n                    if( index_sol_circles[k] == j ){\n                        exist = true;\n                        break;\n                    };\n                };\n                if( !exist ){\n                    index_sol_circles.push_back( j );\n                };\n                flag_two = true;\n                pivot = j;\n            };\n        };\n        if( !flag_two ){\n            break;\n        }else{\n            i = pivot;\n        };\n    };\n\n    int index_sol_circles_size = index_sol_circles.size();\n    for( int i = 0; i < index_sol_circles_size; i++ ){\n        int radius = ( get<1>( sorted_vec_start_end_n_area[ index_sol_circles[i] ] ) - get<0>( sorted_vec_start_end_n_area[ index_sol_circles[i] ] ) ) / 2;\n        int point = ( ( get<1>( sorted_vec_start_end_n_area[ index_sol_circles[i] ] ) - get<0>( sorted_vec_start_end_n_area[ index_sol_circles[i] ] ) ) / 2 ) + get<0>( sorted_vec_start_end_n_area[ index_sol_circles[i] ] );\n        tuple < int, int > circle_r = make_tuple( point, radius );\n        to_return.push_back( circle_r );\n    };\n\n    return to_return;\n};\n\nvector < int > sort_by_radius( vector < int > input ){\n    /*int mid = floor( input.size() / 2 );\n    if( input.size() == 1 ){\n        return input;\n    }else if( input.size() == 2 ){\n        if( input[0] > input[1] ){\n            iter_swap( input[0], input[1] );\n        }else{\n            return input;\n        };\n    }else{\n    };*/\n    vector < int > to_return;\n    int input_size = input.size();\n    for( int i = 0; i < input_size; i++ ){\n        int index_minor = -1;\n        int value = std::numeric_limits<int>::max();;\n        for( int j = 0; j < input.size(); j++ ){\n            if( value > input[j] ){\n                value = input[j];\n                index_minor = j;\n            };\n        };\n        to_return.push_back( input[index_minor] );\n        input.erase( input.begin() + index_minor );\n    };\n    return to_return;\n};\n\nbool are_intersected( tuple < int, int > new_point, vector < tuple < int, int > > fixed_points, int  height, int width ){\n    if( fixed_points.size() == 0 ){\n        int point_x = get< 0 >( new_point );\n        int radius_ = get< 1 >( new_point );\n        double y_max = (double) radius_ + (double) ( (double) height / (double) 2 );\n        double y_min = (double) ( (double) height / (double) 2 ) - (double) radius_;\n        int x_max = point_x + radius_;\n        int x_min = point_x - radius_;\n        if( (y_min < 0)||(x_min < 0) ){\n            //cout << \"C1: \" << y_min << \" \" << x_min << \" =>\";\n            return true;\n        }else if( (y_max > height)||(x_max > width) ){\n            //cout << \"C2\" << endl;\n            return true;\n        }else{\n            //cout << \"CT: \" << y_min << \" \" << x_min << \" =>\";\n            return false;\n        };\n    }else{\n        for( int i = 0; i < fixed_points.size(); i++ ){\n            if( get< 0 >( fixed_points[i] ) ==  get< 0 >( new_point ) ){\n                return true;\n            }else{\n                int fixed_point_x_max = get< 0 >( fixed_points[i] ) + get< 1 >( fixed_points[i] );\n                int fixed_point_x_min = get< 0 >( fixed_points[i] ) - get< 1 >( fixed_points[i] ); \n                int point_x = get< 0 >( new_point );\n                int radius_ = get< 1 >( new_point );\n                double y_max = (double) radius_ + (double) ( (double) height / (double) 2 );\n                double y_min =  (double) ( (double) height / (double) 2 ) - (double) radius_;\n                int x_max = point_x + radius_;\n                int x_min = point_x - radius_;\n                if( (y_min < 0)||(x_min < 0) ){\n                    return true;\n                }else if( (y_max > height)||(x_max > width) ){\n                    return true;\n                }else if( \n                            //Casos 1 sentido\n                            ( (x_max > fixed_point_x_min) && (x_max < fixed_point_x_max) ) || \n                            ( (x_min < fixed_point_x_max) && (x_min > fixed_point_x_min) ) || \n                            ( (x_max == fixed_point_x_max) && ( x_min == fixed_point_x_min ) ) ||\n                            ( (x_max < fixed_point_x_max) && ( x_min == fixed_point_x_min ) ) ||\n                            ( (x_max == fixed_point_x_max) && ( x_min > fixed_point_x_min ) )  ||\n                            // Casos 2 sentido\n                            ( (x_max > fixed_point_x_min) && (x_min < fixed_point_x_max) ) || \n                            ( (x_max > fixed_point_x_max) && (x_min < fixed_point_x_min) ) || \n                            ( (x_max > fixed_point_x_max) && ( x_min == fixed_point_x_min ) ) ||\n                            ( (x_max == fixed_point_x_max) && ( x_min < fixed_point_x_min ) ) \n                        ){\n                    //cout << \"C3: \" << x_max << \" \" << fixed_point_x_min << \" - \" << x_min << \" \" << fixed_point_x_max << \" - \" << \" =>\";\n                    return true;\n                };\n            };\n        };\n        return false;\n    };\n};\n\nstring get_geogebra_plot_command( vector < tuple < int, int > > points, int  height, int width ){\n    string command = \"\";\n    command += \"Execute[{\\\" x = \" + to_string(0) + \" \\\",\";\n    command += \" \\\" x = \" + to_string((double) width) + \" \\\",\";\n    command += \" \\\" y = \" + to_string((double) height / (double) 2) + \" \\\",\";\n    command += \" \\\" y = -\" + to_string((double) height / (double) 2) + \" \\\",\";\n    for( int i = 0; i < points.size(); i++ ){\n        command += \" \\\" Circle(( \" +  to_string(get<0>( points[i] )) + \" ,0), \" +  to_string(get<1>( points[i] )) + \")\\\"\";\n        if( i < ( points.size() - 1) ){\n            command += \",\";\n        }else{\n            command += \"}]\";\n        };\n    };\n    return command;\n};\n\nvector < vector < tuple < int, int > > > split_vector( vector < tuple < int, int > > vector_, int split_point ) {\n    vector < vector < tuple < int, int > > > to_return;\n    vector < tuple < int, int > > vector_0;\n    vector < tuple < int, int > > vector_1;\n    bool vector_toggle = false;\n    for( int i = 0; i < vector_.size(); i++ ){\n        if( !vector_toggle ){\n            vector_0.push_back( vector_[i] );\n            if( i == ( split_point - 1 ) ){\n                vector_toggle = true;\n            };\n        }else{\n            vector_1.push_back( vector_[i] );\n        };\n    };\n    to_return.push_back( vector_0 );\n    to_return.push_back( vector_1 );\n    return to_return;\n};\n\nvector < tuple < int, int > > merge_vectors( vector < tuple < int, int > > vector_0, vector < tuple < int, int > > vector_1 ) {\n    vector < tuple < int, int > > to_return;\n    for( int i = 0; i < vector_0.size(); i++ ){\n        to_return.push_back( vector_0[i] );\n    };\n    for( int i = 0; i < vector_1.size(); i++ ){\n        to_return.push_back( vector_1[i] );\n    };\n    return to_return;\n};\n\nvector < tuple < int, int > > max( vector < tuple < int, int > > vector_0, vector < tuple < int, int > > vector_1 ) {\n    int area_0 = 0;\n    int area_1 = 0;\n    for( int i = 0; i < vector_0.size(); i++ ){\n        area_0 += PI * pow( get<1>( vector_0[i] ), 2);\n    };\n    for( int i = 0; i < vector_1.size(); i++ ){\n        area_1 += PI * pow( get<1>( vector_1[i] ), 2);\n    };\n    if( area_0 >= 1 ){\n        return vector_0;\n    }else{\n        return vector_1;\n    };\n};\n\ndouble circle_area( double radius ){\n    return PI * pow( radius, 2 );\n};\n\nvoid merge_sort(int arr[], int l, int r)\n{\n    if (l < r)\n    {\n        int m = l+(r-l)/2;\n \n        merge_sort(arr, l, m);\n        merge_sort(arr, m+1, r);\n \n        merge(arr, l, m, r);\n    };\n};\n\nvoid merge(int arr[], int l, int m, int r){\n\n    int i, j, k;\n    int n1 = m - l + 1;\n    int n2 =  r - m;\n \n    int L[n1], R[n2];\n \n    for (i = 0; i < n1; i++){\n        L[i] = arr[l + i];\n    };\n    for (j = 0; j < n2; j++){\n        R[j] = arr[m + 1+ j];\n    };\n\n    i = 0;\n    j = 0;\n    k = l;\n\n    while (i < n1 && j < n2){\n        if (L[i] <= R[j])\n        {\n            arr[k] = L[i];\n            i++;\n        }\n        else\n        {\n            arr[k] = R[j];\n            j++;\n        }\n        k++;\n    }\n \n    while (i < n1){\n        arr[k] = L[i];\n        i++;\n        k++;\n    }\n \n    while (j < n2){\n        arr[k] = R[j];\n        j++;\n        k++;\n    };\n};\n\ndouble calculate_input_area( vector < tuple < int, int > > input ){\n    double to_return = 0;\n    int input_size = input.size();\n    for( int i = 0; i < input_size; i++ ){\n        to_return += circle_area( get<1>( input[ i ] ) );\n    };\n    return to_return;\n};\n", "meta": {"hexsha": "fbed050ac54cd2a43962bac6347ab5637d1d2635", "size": 35552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "vvbv/Proyecto-final-FADA", "max_stars_repo_head_hexsha": "323bd8a1b0f9b96f7fba402b0a8ed0548044e063", "max_stars_repo_licenses": ["MIT"], "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": "vvbv/Proyecto-final-FADA", "max_issues_repo_head_hexsha": "323bd8a1b0f9b96f7fba402b0a8ed0548044e063", "max_issues_repo_licenses": ["MIT"], "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": "vvbv/Proyecto-final-FADA", "max_forks_repo_head_hexsha": "323bd8a1b0f9b96f7fba402b0a8ed0548044e063", "max_forks_repo_licenses": ["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.197353914, "max_line_length": 222, "alphanum_fraction": 0.5113636364, "num_tokens": 9792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5693857877937909}}
{"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) 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 *      Wakker, K. F. (2007), Lecture Notes astro II (Chapter 18), TU Delft course AE4-874,\n *          Delft University of technology, Delft, The Netherlands.\n *\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"tudat/astro/mission_segments/escapeAndCapture.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Test patched conics implementation.\nBOOST_AUTO_TEST_SUITE( test_escape_and_capture )\n\n//! Test delta-V computation for the escape phase.\nBOOST_AUTO_TEST_CASE( testDeltaVEscape )\n{\n    // Set tolerance.\n    const double tolerance = 1.0e-15;\n\n    // Expected test result based on Table 18.2 of [Wakker, 2007]. Escape velocity to go to Mars\n    // starting from a parking orbit around Earth at 185 km altitude. Result calculated with more\n    // precision separately using Equation 18.25 of [Wakker, 2007].\n    const double expectedDeltaVEscape = 3614.64460281887;\n\n    // Set required parameters.\n    const double gravitationalParameterEarth = 3.986e14;\n    const double semiMajorAxis = 6.378e6 + 1.85e5;\n    const double eccentricity = 0.0;\n    const double excessVelocity = 2944.61246668719;\n\n    // Compute delta-V of escape phase.\n    const double deltaVEscape = mission_segments::computeEscapeOrCaptureDeltaV(\n                gravitationalParameterEarth, semiMajorAxis, eccentricity, excessVelocity );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( expectedDeltaVEscape, deltaVEscape, tolerance );\n}\n\n//! Test delta-V computation for the capture phase.\nBOOST_AUTO_TEST_CASE( testDeltaVCapture )\n{\n    // Set tolerance.\n    const double tolerance = 1.0e-15;\n\n    // Expected test result based on Table 18.2 of [Wakker, 2007]. Capture velocity to arrive at\n    // a parking orbit around Mars of 1.1 times the planetary radius starting from Earth. Result\n    // calculated with more precision separately using Equation 18.25 of [Wakker, 2007].\n    const double expectedDeltaVCapture = 2087.1062716740798;\n\n    // Set required parameters.\n    const double gravitationalParameterMars = 4.2830e13;\n    const double semiMajorAxis = 1.1 * 3.3895e6;\n    const double eccentricity = 0.0;\n    const double excessVelocity = 2648.83359973278;\n\n    // Compute delta-V of escape phase.\n    const double deltaVCapture = mission_segments::computeEscapeOrCaptureDeltaV(\n                gravitationalParameterMars, semiMajorAxis, eccentricity, excessVelocity );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( expectedDeltaVCapture, deltaVCapture, tolerance );\n}\n\n//! Test delta-V computation for an escape from an eccentric parking orbit.\nBOOST_AUTO_TEST_CASE( testDeltaVEscapeElliptical )\n{\n    // Set tolerance.\n    const double tolerance = 1.0e-15;\n\n    // Departure from 200 km perigee, 1800 km apogee parking orbit from Earth to Mars transfer.\n    // Result calculated to high precision separately using Equation 18.25 of [Wakker, 2007].\n    const double expectedDeltaVEscape = 3200.2178506657729;\n\n    // Set required parameters.\n    const double gravitationalParameterEarth = 3.986e14;\n    const double semiMajorAxis = 6.378e6 + 1.0e6;\n    const double eccentricity = 0.108430468961778;\n    const double excessVelocity = 2944.61246668719;\n\n    // Compute delta-V of escape phase.\n    const double deltaVEscape = mission_segments::computeEscapeOrCaptureDeltaV(\n                gravitationalParameterEarth, semiMajorAxis, eccentricity, excessVelocity );\n\n    // Test if the computed delta-V corresponds to the expected value within the specified\n    // tolerance.\n    BOOST_CHECK_CLOSE_FRACTION( expectedDeltaVEscape, deltaVEscape, tolerance );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "1e59220424836ef4ced7a863af735081483ef691", "size": 4372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/mission_segments/unitTestEscapeAndCaptureRoutines.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/astro/mission_segments/unitTestEscapeAndCaptureRoutines.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/astro/mission_segments/unitTestEscapeAndCaptureRoutines.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": 38.6902654867, "max_line_length": 97, "alphanum_fraction": 0.7403934126, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460027, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.569370759723704}}
{"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": "#include <yawiel/core/util/ngram_counter.hpp>\n#include <yawiel/colext/eam/am/pmi.hpp>\n#include <yawiel/colext/eam/am/dice.hpp>\n#include <yawiel/colext/eam/am/chi_squared.hpp>\n#include <yawiel/colext/eam/am/log_likelihood.hpp>\n#include <yawiel/colext/eam/ep/g0.hpp>\n#include <yawiel/colext/eam/ep/g1.hpp>\n#include <yawiel/colext/eam/ep/g2.hpp>\n#include <yawiel/colext/eam/ep/g3.hpp>\n#include <yawiel/colext/eam/ep/g4.hpp>\n#include <yawiel/colext/eam/ep/g5.hpp>\n#include <yawiel/colext/eam/ep/g6.hpp>\n#include <boost/test/unit_test.hpp>\n\nusing namespace std;\nusing namespace yawiel;\nusing namespace yawiel::text;\nusing namespace yawiel::util;\nusing namespace yawiel::colext;\n\nBOOST_AUTO_TEST_SUITE(EAMTest);\n\ntypedef NGramCounter<std::string> Counter;\nconst std::string text1 = \"this is a test a test\";\n\nBOOST_AUTO_TEST_CASE(PMITest)\n{\n  Corpus<string> corpus;\n  corpus.LoadString(text1);\n  Counter counter(corpus);\n  PMI<Counter> pmi(counter);\n  pmi.Precompute(3);\n\n  vector<size_t> gram1 {0, 1};\n  vector<size_t> gram2 {2};\n\n  const double result = pmi.Evaluate(gram1, gram2);\n  // Compare against a manually calculated PMI value.\n  BOOST_REQUIRE_CLOSE(result, 1.90833401257, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(DiceTest)\n{\n  Corpus<string> corpus;\n  corpus.LoadString(text1);\n  Counter counter(corpus);\n  Dice<Counter> dice(counter);\n  dice.Precompute(3);\n  const auto& vocab = corpus.GetVocabulary();\n\n  vector<size_t> gram1 {vocab.at(\"this\"), vocab.at(\"is\")};\n  vector<size_t> gram2 {vocab.at(\"a\")};\n\n  const double result = dice.Evaluate(gram1, gram2);\n  // Compare against a manually calculated Dice value.\n  BOOST_REQUIRE_CLOSE(result, 0.6666666666666, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(G1Test)\n{\n  Corpus<string> corpus;\n  corpus.LoadString(text1);\n  Counter counter(corpus);\n  vector<size_t> aTestA {2, 3, 2};\n  PMI<Counter> pmi(counter);\n  G1<PMI<Counter>> g1(counter, pmi);\n  g1.Precompute(3);\n\n  const double G1Result = g1.Evaluate(aTestA);\n\n  // Manual result.\n  vector<size_t> aTest {2, 3};\n  vector<size_t> a {2};\n  vector<size_t> testA {3, 2};\n  const double PMIResult1 = pmi.Evaluate(aTest, a);\n  const double PMIResult2 = pmi.Evaluate(a, testA);\n  const double ManualResult = (PMIResult1 + PMIResult2) / 2.0;\n  BOOST_REQUIRE_CLOSE(G1Result, ManualResult, 1e-8);\n}\n\nBOOST_AUTO_TEST_CASE(G0PMITest)\n{\n  Corpus<string> corpus;\n  corpus.LoadString(text1);\n  Counter counter(corpus);\n  vector<size_t> aTestA {2, 3, 2};\n  PMI<Counter> pmi(counter);\n  G0<PMI<Counter>> g0(counter, pmi);\n  g0.Precompute(3);\n\n  const double g0Result = g0.Evaluate(aTestA);\n\n  // Manual result.\n  const double numerator = 1.0 / 4.0;\n  const double denominator = std::pow((2.0 / 6.0), 3.0);\n  const double ManualResult = std::log2(numerator / denominator);\n  BOOST_REQUIRE_CLOSE(g0Result, ManualResult, 1e-8);\n}\n\nBOOST_AUTO_TEST_CASE(G2Test)\n{\n  Corpus<string> corpus;\n  corpus.LoadString(text1);\n  Counter counter(corpus);\n  const auto& vocab = corpus.GetVocabulary();\n  Dice<Counter> dice(counter);\n  G2<Dice<Counter>> g2(counter, dice);\n  g2.Precompute(4);\n\n  vector<size_t> gram {vocab.at(\"is\"),\n                       vocab.at(\"a\"),\n                       vocab.at(\"test\"),\n                       vocab.at(\"a\")};\n\n  const double g2Result = g2.Evaluate(gram);\n\n  // Manual result.\n  vector<size_t> isA {gram[0], gram[1]};\n  vector<size_t> testA {gram[2], gram[3]};\n  vector<size_t> isATest {gram[0],gram[1], gram[2]};\n  vector<size_t> a {gram[3]};\n  const double diceResult1 = dice.Evaluate(isA, testA);\n  const double diceResult2 = dice.Evaluate(isATest, a);\n  const double manualResult = (diceResult1 + diceResult2) / 2.0;\n  BOOST_REQUIRE_CLOSE(g2Result, manualResult, 1e-8);\n}\n\nBOOST_AUTO_TEST_CASE(G3Test)\n{\n  Corpus<string> corpus;\n  corpus.LoadString(text1);\n  Counter counter(corpus);\n  const auto& vocab = corpus.GetVocabulary();\n  PMI<Counter> pmi(counter);\n  G3<PMI<Counter>> g3(counter, pmi);\n  g3.Precompute(5);\n\n  vector<size_t> gram {vocab.at(\"is\"),\n                       vocab.at(\"a\"),\n                       vocab.at(\"test\"),\n                       vocab.at(\"a\"),\n                       vocab.at(\"test\")};\n\n  const double g3Result = g3.Evaluate(gram);\n\n  // Manual result.\n  vector<size_t> is {gram[0]};\n  vector<size_t> a {gram[1]};\n  vector<size_t> test {gram[2]};\n\n  const double pmiResult1 = pmi.Evaluate(is, a);\n  const double pmiResult2 = pmi.Evaluate(a, test);\n  const double pmiResult3 = pmi.Evaluate(test, a);\n  const double pmiResult4 = pmi.Evaluate(a, test);\n  const double manualResult =\n      (pmiResult1 + pmiResult2 + pmiResult3 + pmiResult4) / (5 - 1);\n\n  BOOST_REQUIRE_CLOSE(g3Result, manualResult, 1e-8);\n}\n\nBOOST_AUTO_TEST_CASE(G4Test)\n{\n  Corpus<string> corpus;\n  corpus.LoadString(text1);\n  Counter counter(corpus);\n  const auto& vocab = corpus.GetVocabulary();\n  Dice<Counter> dice(counter);\n  G4<Dice<Counter>> g4(counter, dice);\n  g4.Precompute(8);\n\n  vector<size_t> gram {vocab.at(\"is\"),\n                       vocab.at(\"a\"),\n                       vocab.at(\"test\"),\n                       vocab.at(\"a\"),\n                       vocab.at(\"test\")};\n\n  const double g4Result = g4.Evaluate(gram);\n\n  // Manual result.\n  vector<size_t> isATestA {gram[0], gram[1], gram[2], gram[3]};\n  vector<size_t> aTestATest {gram[1], gram[2], gram[3], gram[4]};\n\n  const double manualResult = dice.Evaluate(isATestA, aTestATest);\n\n  BOOST_REQUIRE_CLOSE(g4Result, manualResult, 1e-8);\n}\n\nBOOST_AUTO_TEST_CASE(G5Test)\n{\n  Corpus<string> corpus;\n  corpus.LoadString(text1);\n  Counter counter(corpus);\n  const auto& vocab = corpus.GetVocabulary();\n  Dice<Counter> dice(counter);\n  G5<Dice<Counter>> g5(counter, dice);\n  g5.Precompute(5);\n\n  vector<size_t> gram {vocab.at(\"is\"),\n                       vocab.at(\"a\"),\n                       vocab.at(\"test\"),\n                       vocab.at(\"a\")};\n\n  const double g5Result = g5.Evaluate(gram);\n\n  // Manual result.\n  vector<size_t> is {gram[0]};\n  vector<size_t> aTestA {gram[1], gram[2], gram[3]};\n  vector<size_t> isA {gram[0], gram[1]};\n  vector<size_t> testA {gram[2], gram[3]};\n  vector<size_t> isATest {gram[0], gram[1], gram[2]};\n  vector<size_t> a {gram[3]};\n\n  double manualResult = dice.Evaluate(is, aTestA) +\n                        dice.Evaluate(isA, testA) +\n                        dice.Evaluate(isATest, a);\n  manualResult /= 3;\n\n  BOOST_REQUIRE_CLOSE(g5Result, manualResult, 1e-8);\n}\n\nBOOST_AUTO_TEST_CASE(G6DiceTest)\n{\n  Corpus<string> corpus;\n  corpus.LoadString(text1);\n  Counter counter(corpus);\n  const auto& vocab = corpus.GetVocabulary();\n  Dice<Counter> dice(counter);\n  G6<Dice<Counter>> g6(counter, dice);\n  g6.Precompute(5);\n\n  vector<size_t> gram {vocab.at(\"is\"),\n                       vocab.at(\"a\"),\n                       vocab.at(\"test\"),\n                       vocab.at(\"a\")};\n\n  const double g6Result = g6.Evaluate(gram);\n\n  // Manual result.\n  vector<size_t> isA {gram[0], gram[1]};\n  vector<size_t> testA {gram[2], gram[3]};\n\n  const size_t n = gram.size();\n  const size_t countGram = counter.GetCounts(gram);\n  const size_t countBi = counter.GetCounts(isA) + counter.GetCounts(testA);\n  const double manualResult = (n * countGram) / countBi;\n\n  BOOST_REQUIRE_CLOSE(g6Result, manualResult, 1e-8);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "795a826cd9cd1124ba64242c6e4407c54bb80abd", "size": 7217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/yawiel/tests/eam_test.cpp", "max_stars_repo_name": "robertohueso/yawiel_colext", "max_stars_repo_head_hexsha": "09af45bee36243584c024038e8f6e79c078329dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-01T09:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-01T09:51:53.000Z", "max_issues_repo_path": "src/yawiel/tests/eam_test.cpp", "max_issues_repo_name": "robertohueso/yawiel_colext", "max_issues_repo_head_hexsha": "09af45bee36243584c024038e8f6e79c078329dc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/yawiel/tests/eam_test.cpp", "max_forks_repo_name": "robertohueso/yawiel_colext", "max_forks_repo_head_hexsha": "09af45bee36243584c024038e8f6e79c078329dc", "max_forks_repo_licenses": ["Apache-2.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.7529880478, "max_line_length": 75, "alphanum_fraction": 0.6587224609, "num_tokens": 2115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.640635841117624, "lm_q1q2_score": 0.5693707334445163}}
{"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": "#ifndef _TERMINATION_CRITERIA_HPP\n#define _TERMINATION_CRITERIA_HPP \n\n\n#include <cmath>\n#include <vector>\n#include <iostream>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/accumulators/statistics/rolling_mean.hpp>\n#include <boost/accumulators/statistics/rolling_variance.hpp>\n\nnamespace acc = boost::accumulators;\n\n/// parameters for the TerminationCriteria object\n/// this struct is useful to facilitate reading\n/// parameters from the command line or other sources\nstruct TerminationCriteriaParams {\n    TerminationCriteriaParams():\n        meanErrorThreshold(0.01),\n        maxErrorThreshold(0.1),\n        minVarianceInMeanErrorBetweenIterations(1e-10),\n        maxIterationCount(300),\n        minIterationCount(10),\n        trackProgressEveryNIterations(10){}\n    \n    /// Stop the algorithm once the mean error is *below* this amount\n    double meanErrorThreshold;\n    \n    /// Stop the algorithm once the max error is *below* this amount\n    double maxErrorThreshold;\n    \n    /// The mean error is calculated on each iteration.\n    /// Over a series of iterations, a rolling variance is calculated\n    /// for the mean error. If the variance becomes too small, this means\n    /// that the mean is no longer improving, so the algorithm should stop.\n    ///\n    /// Typically use a very small value like 1e-10\n    double minVarianceInMeanErrorBetweenIterations;\n    \n    /// the maximum number of iterations to run\n    int    maxIterationCount;\n    \n    /// the minimum number of iterations to run\n    int    minIterationCount;\n    \n    /// Print out the progress and stats every Nth iteration.\n    /// 0 means don't track progress.\n    int    trackProgressEveryNIterations;\n    \n};\n\n/// TerminationCirteria is used to evaluate when the ICP algorithm should stop\n/// Also evaluates other statistics about the algorighm's execution\nstruct TerminationCriteria {\n    typedef acc::accumulator_set< double, acc::features< acc::tag::min, acc::tag::max, acc::tag::mean, acc::tag::variance, acc::tag::count, acc::tag::rolling_mean, acc::tag::rolling_variance > > accumulator_type;\n    \n    /// constructor\n    TerminationCriteria(TerminationCriteriaParams tcp = TerminationCriteriaParams()):\n        m_tcp(tcp),\n        m_acc(new accumulator_type(acc::tag::rolling_window::window_size = m_tcp.minIterationCount)),\n        m_iterationMeanAcc(new accumulator_type(acc::tag::rolling_window::window_size = m_tcp.minIterationCount)){}\n    \n    /// operator() add a new error data point\n    ///\n    /// @param error the amount of error found in the data point\n    void operator()(double error){\n        BOOST_VERIFY(!boost::math::isnan(error));\n        (*m_acc)(error);\n    }\n    \n    /// Returns true if the termination criteria has been met\n    bool shouldTerminate(){\n        // should have run at least once, plus both the mean and max error should be below a threshold\n        bool shouldTerminate_b =\n                   (\n                      m_tcp.minIterationCount                            < acc::count(*m_iterationMeanAcc) // must meet minimum iteration count\n                   && acc::mean(*m_acc)                            < m_tcp.meanErrorThreshold              // the mean error should be sufficiently low\n                   && acc::extract_result< acc::tag::max >(*m_acc) < m_tcp.maxErrorThreshold               // the max error should be sufficiently low\n                   )\n                || (  acc::count(*m_iterationMeanAcc)              > m_tcp.maxIterationCount )             // don't exceed max iterations\n                || (\n                      m_tcp.minIterationCount                            < acc::count(*m_iterationMeanAcc) // must meet minimum iteration count\n                   && acc::rolling_variance(*m_iterationMeanAcc)   < m_tcp.minVarianceInMeanErrorBetweenIterations // if the optimization is having no effect (small rolling variance), terminate\n                   );\n        \n        if(m_tcp.trackProgressEveryNIterations && shouldTerminate_b) {\n\t\t\tstd::cout << \"\\n\\n>> Algorithm \" << description << \" complete. << Final Stats:\";\n\t\t\tPrintIterationStats();\n\t\t\tstd::cout << \"\\n\";\n\t\t}\n        \n        return shouldTerminate_b;\n    }\n\t\n    /// prints various stats about the collected error data for the most recent iteration\n\tvoid PrintIterationStats(){\n        if(m_tcp.trackProgressEveryNIterations) {\n            std::cout << \"\\n\"\n                  <<  \"iter: \"        << acc::count(*m_iterationMeanAcc)              << \"/\" << m_tcp.maxIterationCount\n\t\t\t\t  << \" Error\"\n                  << \" mean: \"        << acc::mean(*m_acc)                            << \"/\" << m_tcp.meanErrorThreshold\n                  << \" max: \"         << acc::extract_result< acc::tag::max >(*m_acc) << \"/\" << m_tcp.maxErrorThreshold\n                  << \" var: \"         << acc::variance(*m_acc)\n                  << \" rVarOfMean: \"  << acc::rolling_variance(*m_iterationMeanAcc)   << \"/\" << m_tcp.minVarianceInMeanErrorBetweenIterations\n                  << \" File: \"        << description                                  << \"\\n\";\n        }\n\t\t\n\t}\n    \n    /// resets accumulated statistics, not termination criteria\n    void nextIteration(){\n       double meanErrorForIteration = acc::mean(*m_acc);\n       BOOST_VERIFY(!boost::math::isnan(meanErrorForIteration));\n       (*m_iterationMeanAcc)(meanErrorForIteration);\n\t   if((acc::count(*m_iterationMeanAcc) % m_tcp.trackProgressEveryNIterations == 0)) PrintIterationStats();\n       m_acc.reset(new accumulator_type(acc::tag::rolling_window::window_size = m_tcp.minIterationCount));\n    }\n    \n    \n    TerminationCriteriaParams m_tcp;\n    std::string description;\n    \n    boost::shared_ptr<accumulator_type> m_acc;\n    boost::shared_ptr<accumulator_type> m_iterationMeanAcc;\n    \n    \n};\n\n#endif", "meta": {"hexsha": "3abf6ec53a8eba6aac7b6a18a79494d25bc80245", "size": 6037, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/TerminationCriteria.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/TerminationCriteria.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/TerminationCriteria.hpp", "max_forks_repo_name": "ahundt/cis", "max_forks_repo_head_hexsha": "bd55e8c77ec78994454247ffe7d67f537710a53f", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.7185185185, "max_line_length": 212, "alphanum_fraction": 0.640549942, "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5692534772578223}}
{"text": "// (C) Copyright Andrew Sutton 2007\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0 (See accompanying file\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\n\n//[closeness_centrality_example\n#include <iostream>\n#include <iomanip>\n\n#include <boost/graph/undirected_graph.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/graph/floyd_warshall_shortest.hpp>\n#include <boost/graph/closeness_centrality.hpp>\n#include <boost/graph/property_maps/constant_property_map.hpp>\n#include \"helper.hpp\"\n\nusing namespace std;\nusing namespace boost;\n\n// The Actor type stores the name of each vertex in the graph.\nstruct Actor\n{\n    string name;\n};\n\n// Declare the graph type and its vertex and edge types.\ntypedef undirected_graph<Actor> Graph;\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef graph_traits<Graph>::edge_descriptor Edge;\n\n// The name map provides an abstract accessor for the names of\n// each vertex. This is used during graph creation.\ntypedef property_map<Graph, string Actor::*>::type NameMap;\n\n// Declare a matrix type and its corresponding property map that\n// will contain the distances between each pair of vertices.\ntypedef exterior_vertex_property<Graph, int> DistanceProperty;\ntypedef DistanceProperty::matrix_type DistanceMatrix;\ntypedef DistanceProperty::matrix_map_type DistanceMatrixMap;\n\n// Declare the weight map so that each edge returns the same value.\ntypedef constant_property_map<Edge, int> WeightMap;\n\n// Declare a container and its corresponding property map that\n// will contain the resulting closeness centralities of each\n// vertex in the graph.\ntypedef boost::exterior_vertex_property<Graph, float> ClosenessProperty;\ntypedef ClosenessProperty::container_type ClosenessContainer;\ntypedef ClosenessProperty::map_type ClosenessMap;\n\nint\nmain(int argc, char *argv[])\n{\n    // Create the graph and a property map that provides access to[\n    // tha actor names.\n    Graph g;\n    NameMap nm(get(&Actor::name, g));\n\n    // Read the graph from standard input.\n    read_graph(g, nm, cin);\n\n    // Compute the distances between all pairs of vertices using\n    // the Floyd-Warshall algorithm. Note that the weight map is\n    // created so that every edge has a weight of 1.\n    DistanceMatrix distances(num_vertices(g));\n    DistanceMatrixMap dm(distances, g);\n    WeightMap wm(1);\n    floyd_warshall_all_pairs_shortest_paths(g, dm, weight_map(wm));\n\n    // Compute the closeness centrality for graph.\n    ClosenessContainer cents(num_vertices(g));\n    ClosenessMap cm(cents, g);\n    all_closeness_centralities(g, dm, cm);\n\n    // Print the closeness centrality of each vertex.\n    graph_traits<Graph>::vertex_iterator i, end;\n    for(tie(i, end) = vertices(g); i != end; ++i) {\n        cout << setw(12) << setiosflags(ios::left)\n             << g[*i].name << get(cm, *i) << endl;\n    }\n\n    return 0;\n}\n//]\n", "meta": {"hexsha": "b5aa4776b581e203e0432d16bfc7b007769856a7", "size": 2916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/closeness_centrality.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/closeness_centrality.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/closeness_centrality.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 33.9069767442, "max_line_length": 72, "alphanum_fraction": 0.7469135802, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5692534659954991}}
{"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": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/ccmath/div.hpp>\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n   check_result<std::div_t>(boost::math::ccmath::div(1, 1));\n   check_result<std::ldiv_t>(boost::math::ccmath::div(1l, 1l));\n   check_result<std::lldiv_t>(boost::math::ccmath::div(1ll, 1ll));\n}\n", "meta": {"hexsha": "c7fc17dfd4dfa94382004f38178c33e8645d3c10", "size": 527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_test/ccmath_div_incl_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/compile_test/ccmath_div_incl_test.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/compile_test/ccmath_div_incl_test.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 35.1333333333, "max_line_length": 68, "alphanum_fraction": 0.7210626186, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5692328972246684}}
{"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_LINEALGO__H_\n#define _PIMATH_LINEALGO__H_\n\n#include <boost/python.hpp>\n#include <ImathLineAlgo.h>\n#include <ImathLine.h>\n#include \"util.h\"\n\n/*\n * closestPoints, intersect: now return a tuple f the output values rather than\n * altering args.\n */\n\nnamespace pimath\n{\n\tnamespace bp = boost::python;\n\n\n\ttemplate<typename T>\n\tstruct LineAlgoBind\n\t{\n\t\ttypedef Imath::Line3<T> \tline_type;\n\t\ttypedef Imath::Vec3<T> \t\tvec3_type;\n\t\tLineAlgoBind()\n\t\t{\n\t\t\tvec3_type (*closestVertex)(\n\t\t\t\t\tconst vec3_type &, const vec3_type &, const vec3_type &,\n\t\t\t\t\tconst line_type & ) = &Imath::closestVertex;\n\n\t\t\tbp::def(\"closestPoints\", closestPoints);\n\t\t\tbp::def(\"intersect\", intersect);\n\t\t\tbp::def(\"closestVertex\", closestVertex);\n\t\t\tbp::def(\"rotatePoint\", &Imath::rotatePoint<T> );\n\t\t}\n\n\t\tstatic bp::object\n\t\tclosestPoints( const line_type & line1, const line_type & line2 )\n\t\t{\n\t\t\tvec3_type p1, p2;\n\t\t\treturn Imath::closestPoints( line1, line2, p1, p2 ) ?\n\t\t\t\t\t\tbp::make_tuple( p1, p2 ) : bp::object();\n\t\t}\n\n\t\tstatic bp::object\n\t\tintersect( const line_type & line, const vec3_type & v0,\n\t\t           const vec3_type & v1, const vec3_type & v2 )\n\t\t{\n\t\t\tvec3_type pt, bary;\n\t\t\tbool front;\n\t\t\treturn Imath::intersect( line, v0, v1, v2, pt, bary, front) ?\n\t\t\t\t\t\tbp::make_tuple( pt, bary, front ) : bp::object();\n\t\t}\n\n\t\tstatic vec3_type\n\t\trotatePoint( const vec3_type p, line_type l, T angle )\n\t\t{\n\t\t\treturn Imath::rotatePoint( p, l, angle );\n\t\t}\n\t};\n}\n\n#endif\n\n", "meta": {"hexsha": "a8ca54cbb6d259ab1f0187d15e9e38c1b86de2f6", "size": 3088, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/LineAlgo.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/LineAlgo.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/LineAlgo.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": 33.5652173913, "max_line_length": 82, "alphanum_fraction": 0.7020725389, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5692328854638885}}
{"text": "/*\n * Copyright Nick Thompson, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <cmath>\n#include <random>\n#include <benchmark/benchmark.h>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/math/special_functions/daubechies_scaling.hpp>\n#include <boost/math/interpolators/cubic_hermite.hpp>\n#include <boost/math/interpolators/detail/quintic_hermite_detail.hpp>\n#include <boost/math/interpolators/detail/septic_hermite_detail.hpp>\n\ndouble exponential(benchmark::IterationCount j)\n{\n    return std::pow(2, j);\n}\n\n\ntemplate<typename Real, int p>\nvoid DyadicGrid(benchmark::State & state)\n{\n    int j = state.range(0);\n    size_t s = 0;\n    for (auto _ : state)\n    {\n        auto v = boost::math::daubechies_scaling_dyadic_grid<Real, 4, 0>(j);\n        benchmark::DoNotOptimize(v[0]);\n        s = v.size();\n    }\n\n    state.counters[\"RAM\"] = s*sizeof(Real);\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK_TEMPLATE(DyadicGrid, double, 4)->DenseRange(3, 22, 1)->Unit(benchmark::kMillisecond)->Complexity(exponential);\n//BENCHMARK_TEMPLATE(DyadicGrid, double, 8)->DenseRange(3, 22, 1)->Unit(benchmark::kMillisecond)->Complexity(exponential);\n//BENCHMARK_TEMPLATE(DyadicGrid, double, 11)->DenseRange(3,22,1)->Unit(benchmark::kMillisecond)->Complexity(exponential);\n\nuint64_t s[2] = { 0x41, 0x29837592 };\n\nstatic inline uint64_t rotl(const uint64_t x, int k) {\n    return (x << k) | (x >> (64 - k));\n}\n\nuint64_t next(void) {\n    const uint64_t s0 = s[0];\n    uint64_t s1 = s[1];\n    const uint64_t result = s0 + s1;\n\n    s1 ^= s0;\n    s[0] = rotl(s0, 55) ^ s1 ^ (s1 << 14); // a, b\n    s[1] = rotl(s1, 36); // c\n\n    return result;\n}\n\ndouble uniform() {\n    return next()*(1.0/18446744073709551616.0);\n}\n\ntemplate<typename Real, int p>\nvoid ScalingEvaluation(benchmark::State & state)\n{\n    auto phi = boost::math::daubechies_scaling<Real, p>();\n    Real xmax = phi.support().second;\n    Real x = 0;\n    Real step = uniform()/2048;\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(phi(x));\n        x += step;\n        if (x > xmax) {\n            x = 0;\n            step = uniform()/2048;\n        }\n    }\n}\n\n\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 2);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 3);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 4);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 5);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 6);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 7);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 8);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 9);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 10);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 11);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 12);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 13);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 14);\nBENCHMARK_TEMPLATE(ScalingEvaluation, double, 15);\n\n\ntemplate<typename Real, int p>\nvoid ScalingConstructor(benchmark::State & state)\n{\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(boost::math::daubechies_scaling<Real, p>());\n    }\n}\n\nBENCHMARK_TEMPLATE(ScalingConstructor, float, 2)->Unit(benchmark::kMillisecond);\nBENCHMARK_TEMPLATE(ScalingConstructor, double, 2)->Unit(benchmark::kMillisecond);\nBENCHMARK_TEMPLATE(ScalingConstructor, long double, 2)->Unit(benchmark::kMillisecond);\n\nBENCHMARK_TEMPLATE(ScalingConstructor, float, 3)->Unit(benchmark::kMillisecond);\nBENCHMARK_TEMPLATE(ScalingConstructor, double, 3)->Unit(benchmark::kMillisecond);\nBENCHMARK_TEMPLATE(ScalingConstructor, long double, 3)->Unit(benchmark::kMillisecond);\n\nBENCHMARK_TEMPLATE(ScalingConstructor, float, 4)->Unit(benchmark::kMillisecond);\nBENCHMARK_TEMPLATE(ScalingConstructor, double, 4)->Unit(benchmark::kMillisecond);\nBENCHMARK_TEMPLATE(ScalingConstructor, long double, 4)->Unit(benchmark::kMillisecond);\n\nBENCHMARK_TEMPLATE(ScalingConstructor, float, 5)->Unit(benchmark::kMillisecond);\nBENCHMARK_TEMPLATE(ScalingConstructor, double, 5)->Unit(benchmark::kMillisecond);\nBENCHMARK_TEMPLATE(ScalingConstructor, long double, 5)->Unit(benchmark::kMillisecond);\n\nBENCHMARK_TEMPLATE(ScalingConstructor, float, 11)->Unit(benchmark::kMillisecond);\nBENCHMARK_TEMPLATE(ScalingConstructor, double, 11)->Unit(benchmark::kMillisecond);\nBENCHMARK_TEMPLATE(ScalingConstructor, long double, 11)->Unit(benchmark::kMillisecond);\n\ntemplate<typename Real>\nvoid CubicHermite(benchmark::State & state)\n{\n    using boost::math::interpolators::cubic_hermite;\n    auto n = state.range(0);\n    std::vector<Real> x(n);\n    std::vector<Real> y(n);\n    std::vector<Real> dydx(n);\n    std::random_device rd;\n    boost::random::uniform_real_distribution<Real> dis(Real(0), Real(1));\n    x[0] = dis(rd);\n    y[0] = dis(rd);\n    dydx[0] = dis(rd);\n    for (size_t i = 1; i < y.size(); ++i)\n    {\n        x[i] = x[i-1] + dis(rd);\n        y[i] = dis(rd);\n        dydx[i] = dis(rd);\n    }\n    Real x0 = x.front();\n    Real xf = x.back();\n\n    auto qh = cubic_hermite(std::move(x), std::move(y), std::move(dydx));\n    Real t = x0;\n    Real step = uniform()*(xf-x0)/2048;\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(qh(t));\n        t += step;\n        if (t >= xf)\n        {\n            t = x0;\n            step = uniform()*(xf-x0)/2048;\n        }\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK_TEMPLATE(CubicHermite, double)->RangeMultiplier(2)->Range(1<<8, 1<<20)->Complexity(benchmark::oLogN);\n\ntemplate<typename Real>\nvoid CardinalCubicHermite(benchmark::State & state)\n{\n    using boost::math::interpolators::detail::cardinal_cubic_hermite_detail;\n    auto n = state.range(0);\n    std::vector<Real> y(n);\n    std::vector<Real> dydx(n);\n    std::random_device rd;\n    boost::random::uniform_real_distribution<Real> dis(Real(0), Real(1));\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = uniform();\n        dydx[i] = uniform();\n    }\n\n    Real dx = Real(1)/Real(8);\n    Real x0 = 0;\n    Real xf = x0 + (y.size()-1)*dx;\n\n    auto qh = cardinal_cubic_hermite_detail(std::move(y), std::move(dydx), x0, dx);\n    Real x = x0;\n    Real step = uniform()*(xf-x0)/2048;\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(qh.unchecked_evaluation(x));\n        x += step;\n        if (x >= xf)\n        {\n            x = x0;\n            step = uniform()*(xf-x0)/2048;\n        }\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename Real>\nvoid CardinalCubicHermiteAOS(benchmark::State & state)\n{\n    auto n = state.range(0);\n    std::vector<std::array<Real, 2>> dat(n);\n    std::random_device rd;\n    boost::random::uniform_real_distribution<Real> dis(Real(0), Real(1));\n    for (size_t i = 0; i < dat.size(); ++i)\n    {\n        dat[i][0] = uniform();\n        dat[i][1] = uniform();\n    }\n\n    using boost::math::interpolators::detail::cardinal_cubic_hermite_detail_aos;\n    Real dx = Real(1)/Real(8);\n    Real x0 = 0;\n    Real xf = x0 + (dat.size()-1)*dx;\n    auto qh = cardinal_cubic_hermite_detail_aos(std::move(dat), x0, dx);\n    Real x = 0;\n    Real step = uniform()*(xf-x0)/2048;\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(qh.unchecked_evaluation(x));\n        x += step;\n        if (x >= xf)\n        {\n            x = x0;\n            step = uniform()*(xf-x0)/2048;\n        }\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK_TEMPLATE(CardinalCubicHermiteAOS, double)->RangeMultiplier(2)->Range(1<<8, 1<<21)->Complexity(benchmark::o1);\nBENCHMARK_TEMPLATE(CardinalCubicHermite, double)->RangeMultiplier(2)->Range(1<<8, 1<<21)->Complexity(benchmark::o1);\n\ntemplate<class Real>\nvoid SineEvaluation(benchmark::State& state)\n{\n    std::default_random_engine gen;\n    std::uniform_real_distribution<Real> x_dis(0, 3.14159);\n\n    Real x = x_dis(gen);\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(std::sin(x));\n        x += std::numeric_limits<Real>::epsilon();\n    }\n}\n\nBENCHMARK_TEMPLATE(SineEvaluation, float);\nBENCHMARK_TEMPLATE(SineEvaluation, double);\nBENCHMARK_TEMPLATE(SineEvaluation, long double);\n\ntemplate<class Real>\nvoid ExpEvaluation(benchmark::State& state)\n{\n    std::default_random_engine gen;\n    std::uniform_real_distribution<Real> x_dis(0, 3.14159);\n\n    Real x = x_dis(gen);\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(std::exp(x));\n        x += std::numeric_limits<Real>::epsilon();\n    }\n}\n\nBENCHMARK_TEMPLATE(ExpEvaluation, float);\nBENCHMARK_TEMPLATE(ExpEvaluation, double);\nBENCHMARK_TEMPLATE(ExpEvaluation, long double);\n\ntemplate<class Real>\nvoid PowEvaluation(benchmark::State& state)\n{\n    std::default_random_engine gen;\n    std::uniform_real_distribution<Real> x_dis(0, 3.14159);\n\n    Real x = x_dis(gen);\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(std::pow(x, x+1));\n        x += std::numeric_limits<Real>::epsilon();\n    }\n}\n\nBENCHMARK_TEMPLATE(PowEvaluation, float);\nBENCHMARK_TEMPLATE(PowEvaluation, double);\nBENCHMARK_TEMPLATE(PowEvaluation, long double);\n\n\ntemplate<typename Real>\nvoid CardinalQuinticHermite(benchmark::State & state)\n{\n    using boost::math::interpolators::detail::cardinal_quintic_hermite_detail;\n    auto n = state.range(0);\n    std::vector<Real> y(n);\n    std::vector<Real> dydx(n);\n    std::vector<Real> d2ydx2(n);\n    std::random_device rd;\n    boost::random::uniform_real_distribution<Real> dis(Real(0), Real(1));\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = uniform();\n        dydx[i] = uniform();\n        d2ydx2[i] = uniform();\n    }\n\n    Real dx = Real(1)/Real(8);\n    Real x0 = 0;\n    Real xf = x0 + (y.size()-1)*dx;\n\n    auto qh = cardinal_quintic_hermite_detail(std::move(y), std::move(dydx), std::move(d2ydx2), x0, dx);\n    Real x = 0;\n    Real step = uniform()*(xf-x0)/2048;\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(qh.unchecked_evaluation(x));\n        x += step;\n        if (x >= xf)\n        {\n            x = x0;\n            step = uniform()*(xf-x0)/2048;\n        }\n    }\n    state.SetComplexityN(state.range(0));\n}\n\ntemplate<typename Real>\nvoid CardinalQuinticHermiteAOS(benchmark::State & state)\n{\n    auto n = state.range(0);\n    std::vector<std::array<Real, 3>> dat(n);\n    std::random_device rd;\n    boost::random::uniform_real_distribution<Real> dis(Real(0), Real(1));\n    for (size_t i = 0; i < dat.size(); ++i)\n    {\n        dat[i][0] = uniform();\n        dat[i][1] = uniform();\n        dat[i][2] = uniform();\n    }\n\n    using boost::math::interpolators::detail::cardinal_quintic_hermite_detail_aos;\n    Real dx = Real(1)/Real(8);\n    Real x0 = 0;\n    Real xf = x0 + (dat.size()-1)*dx;\n    auto qh = cardinal_quintic_hermite_detail_aos(std::move(dat), x0, dx);\n    Real x = x0;\n    Real step = uniform()*(xf-x0)/2048;\n    for (auto _ : state) {\n        benchmark::DoNotOptimize(qh.unchecked_evaluation(x));\n        x += step;\n        if (x >= xf)\n        {\n            x = x0;\n            step = uniform()*(xf-x0)/2048;\n        }\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK_TEMPLATE(CardinalQuinticHermiteAOS, double)->RangeMultiplier(2)->Range(1<<8, 1<<22)->Complexity(benchmark::o1);\nBENCHMARK_TEMPLATE(CardinalQuinticHermite, double)->RangeMultiplier(2)->Range(1<<8, 1<<22)->Complexity(benchmark::o1);\n\ntemplate<typename Real>\nvoid SepticHermite(benchmark::State & state)\n{\n    using boost::math::interpolators::detail::septic_hermite_detail;\n    auto n = state.range(0);\n    std::vector<Real> x(n);\n    std::vector<Real> y(n);\n    std::vector<Real> dydx(n);\n    std::vector<Real> d2ydx2(n);\n    std::vector<Real> d3ydx3(n);\n    std::random_device rd;\n    boost::random::uniform_real_distribution<Real> dis(Real(0), Real(1));\n    Real x0 = dis(rd);\n    x[0] = x0;\n    for (size_t i = 1; i < n; ++i)\n    {\n        x[i] = x[i-1] + dis(rd);\n    }\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = dis(rd);\n        dydx[i] = dis(rd);\n        d2ydx2[i] = dis(rd);\n        d3ydx3[i] = dis(rd);\n    }\n\n    Real xf = x.back();\n\n    auto sh = septic_hermite_detail(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3));\n    Real t = x0;\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(sh(t));\n        t += xf/128;\n        if (t >= xf)\n        {\n            t = x0;\n        }\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK_TEMPLATE(SepticHermite, double)->RangeMultiplier(2)->Range(1<<8, 1<<20)->Complexity();\n\n\ntemplate<typename Real>\nvoid CardinalSepticHermite(benchmark::State & state)\n{\n    using boost::math::interpolators::detail::cardinal_septic_hermite_detail;\n    auto n = state.range(0);\n    std::vector<Real> y(n);\n    std::vector<Real> dydx(n);\n    std::vector<Real> d2ydx2(n);\n    std::vector<Real> d3ydx3(n);\n    std::random_device rd;\n    boost::random::uniform_real_distribution<Real> dis(Real(0), Real(1));\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = dis(rd);\n        dydx[i] = dis(rd);\n        d2ydx2[i] = dis(rd);\n        d3ydx3[i] = dis(rd);\n    }\n\n    Real dx = Real(1)/Real(8);\n    Real x0 = 0;\n    Real xf = x0 + (y.size()-1)*dx;\n\n    auto sh = cardinal_septic_hermite_detail(std::move(y), std::move(dydx), std::move(d2ydx2), std::move(d3ydx3), x0, dx);\n    Real x = 0;\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(sh.unchecked_evaluation(x));\n        x += xf/128;\n        if (x >= xf)\n        {\n            x = x0;\n        }\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK_TEMPLATE(CardinalSepticHermite, double)->RangeMultiplier(2)->Range(1<<8, 1<<20)->Complexity();\n\ntemplate<typename Real>\nvoid CardinalSepticHermiteAOS(benchmark::State & state)\n{\n    using boost::math::interpolators::detail::cardinal_septic_hermite_detail_aos;\n    auto n = state.range(0);\n    std::vector<std::array<Real, 4>> data(n);\n    std::random_device rd;\n    boost::random::uniform_real_distribution<Real> dis(Real(0), Real(1));\n    for (size_t i = 0; i < data.size(); ++i)\n    {\n        for (size_t j = 0; j < 4; ++j)\n        {\n            data[i][j] = dis(rd);\n        }\n    }\n\n    Real dx = Real(1)/Real(8);\n    Real x0 = 0;\n    Real xf = x0 + (data.size()-1)*dx;\n\n    auto sh = cardinal_septic_hermite_detail_aos(std::move(data), x0, dx);\n    Real x = 0;\n    for (auto _ : state)\n    {\n        benchmark::DoNotOptimize(sh.unchecked_evaluation(x));\n        x += xf/128;\n        if (x >= xf)\n        {\n            x = x0;\n        }\n    }\n    state.SetComplexityN(state.range(0));\n}\n\nBENCHMARK_TEMPLATE(CardinalSepticHermiteAOS, double)->RangeMultiplier(2)->Range(1<<8, 1<<20)->Complexity();\n\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "db28461300a1e9c4137a2a5706a59509787b72ea", "size": 14638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/example/daubechies_wavelets/bench.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-12T04:55:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T04:55:21.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/example/daubechies_wavelets/bench.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-13T08:54:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T17:25:14.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/example/daubechies_wavelets/bench.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-27T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:24:22.000Z", "avg_line_length": 29.8734693878, "max_line_length": 122, "alphanum_fraction": 0.6350594343, "num_tokens": 4332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5690656104302019}}
{"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//               Dem Bones - Skinning Decomposition Library                  //\n//         Copyright (c) 2019, Electronic Arts. All rights reserved.         //\n///////////////////////////////////////////////////////////////////////////////\n\n\n\n#include \"FbxReader.h\"\n#include \"LogMsg.h\"\n#include \"FbxShared.h\"\n#include <Eigen/Dense>\n#include <map>\n#include <DemBones/MatBlocks.h>\n\nusing namespace std;\nusing namespace Eigen;\n\n#define err(msgStr) {msg(1, msgStr); return false;}\n\nclass FbxSceneImporter: public FbxSceneShared {\npublic:\n\tMatrixXd v;\n\tvector<vector<int>> fv;\n\n\tvector<string> jointName;\n\tmap<string, string> parent;\n\tmap<string, VectorXd, less<string>, aligned_allocator<pair<const string, VectorXd>>> wT;\n\tmap<string, Matrix4d, less<string>, aligned_allocator<pair<const string, Matrix4d>>> bind, preMulInv;\n\tmap<string, Vector3i, less<string>, aligned_allocator<pair<const string, Vector3i>>> rotOrder;\n\tmap<string, Vector3d, less<string>, aligned_allocator<pair<const string, Vector3d>>> orient;\n\tmap<string, MatrixXd, less<string>, aligned_allocator<pair<const string, MatrixXd>>> m;\n\tmap<string, int> lockM;\n\tVectorXd lockW;\n\tbool hasKeyFrame;\n\n\t//http://help.autodesk.com/view/FBX/2019/ENU/?guid=FBX_Developer_Help_getting_started_your_first_fbx_sdk_program_html\n\tbool load(const VectorXd& fTime) {\n\t\t//Get mesh\n\t\tFbxMesh* pMesh=firstMesh(lScene->GetRootNode());\n\n\t\t//Scence mush have at least one mesh\n\t\tif (pMesh==NULL) err(\"Scene has no mesh.\\n\");\n\t\n\t\tint nV=(int)pMesh->GetControlPointsCount();\n\t\tFbxVector4* cp=pMesh->GetControlPoints();\n\t\tv.resize(3, nV);\n\t\tfor (int i=0; i<nV; i++) v.col(i)<<cp[i][0], cp[i][1], cp[i][2];\n\n\t\tFbxAMatrix gMat=pMesh->GetNode()->EvaluateGlobalTransform();\n\n\t\tint nFV=pMesh->GetPolygonCount();\n\t\tint* idx=pMesh->GetPolygonVertices();\n\n\t\tfv.resize(nFV);\n\t\tfor (int i=0; i<nFV; i++) {\n\t\t\tint* begin=idx+pMesh->GetPolygonVertexIndex(i);\n\t\t\tint* end=begin+pMesh->GetPolygonSize(i);\n\t\t\tfv[i].assign(begin, end);\n\t\t}\n\n\t\t//http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/index.html?url=cpp_ref/class_fbx_geometry_base.html,topicNumber=cpp_ref_class_fbx_geometry_base_html77b8b88d-2e98-42bc-8505-6c20a2debe66\n\t\tlockW=VectorXd::Zero(nV);\n\t\tif (pMesh->GetElementVertexColorCount()>0) {\n\t\t\tFbxGeometryElementVertexColor* leVtxc=pMesh->GetElementVertexColor(0);\n\t\t\tif (leVtxc->GetMappingMode()==FbxGeometryElement::eByPolygonVertex) {\n\t\t\t\tVectorXi slw=VectorXi::Zero(nV);\n\t\t\t\t\n\t\t\t\tswitch (leVtxc->GetReferenceMode()) {\n\t\t\t\t\tcase FbxGeometryElement::eDirect: {\n\t\t\t\t\t\tint count=0;\n\t\t\t\t\t\tfor (int i=0; i<nFV; i++) \n\t\t\t\t\t\t\tfor (int k=0; k!=fv[i].size(); k++) {\n\t\t\t\t\t\t\t\tint vid=fv[i][k];\n\t\t\t\t\t\t\t\tlockW(vid)+=grayScale(leVtxc->GetDirectArray().GetAt(count++));\n\t\t\t\t\t\t\t\tslw(vid)++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t} break;\n\t\t\t\t\tcase FbxGeometryElement::eIndexToDirect: {\n\t\t\t\t\t\tint count=0;\n\t\t\t\t\t\tfor (int i=0; i<nFV; i++)\n\t\t\t\t\t\t\tfor (int k=0; k!=fv[i].size(); k++) {\n\t\t\t\t\t\t\t\tint vid=fv[i][k];\n\t\t\t\t\t\t\t\tint id=leVtxc->GetIndexArray().GetAt(count++);\n\t\t\t\t\t\t\t\tlockW(vid)+=grayScale(leVtxc->GetDirectArray().GetAt(id));\n\t\t\t\t\t\t\t\tslw(vid)++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t} break;\n\t\t\t\t}\n\n\t\t\t\tfor (int i=0; i<nV; i++) \n\t\t\t\t\tif (slw(i)>0) lockW(i)/=(double)slw(i);\n\t\t\t}\n\t\t}\n\n\t\tjointName.clear();\n\t\tparent.clear();\n\t\twT.clear();\n\t\tbind.clear();\n\t\tpreMulInv.clear();\n\t\tm.clear();\n\t\tlockM.clear();\n\t\thasKeyFrame=false;\n\n\t\t//Get skinCluster\n\t\tFbxSkin* pSkin=firstSkin(pMesh);\n\t\tint nB=0;\n\n\t\t//Get skinning weights (if skinCluster exists)\n\t\tif (pSkin!=NULL) {\n\t\t\tnB=(int)pSkin->GetClusterCount();\n\n\t\t\t//Indexing by the order in the skinCluster\n\t\t\tjointName.resize(nB);\n\t\t\tfor (int j=0; j<nB; j++) jointName[j]=pSkin->GetCluster(j)->GetLink()->GetName();\n\t\n\t\t\tfor (int j=0; j<nB; j++) {\n\t\t\t\tFbxCluster* pCluster=pSkin->GetCluster(j);\n\t\t\t\t\n\t\t\t\tdouble* val=pCluster->GetControlPointWeights();\n\t\t\t\tint* idx=pCluster->GetControlPointIndices();\n\t\t\t\t\n\t\t\t\tint nj=pCluster->GetControlPointIndicesCount();\n\t\t\t\twT[jointName[j]]=VectorXd::Zero(nV);\n\t\t\t\tfor (int k=0; k<nj; k++) {\n\t\t\t\t\tif (idx[k]>nV) return false;\n\t\t\t\t\twT[jointName[j]](idx[k])=val[k];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int j=1; j<nB; j++) {\n\t\t\t\tFbxAMatrix mat1, mat2;\n\t\t\t\tpSkin->GetCluster(j-1)->GetTransformMatrix(mat1);\n\t\t\t\tpSkin->GetCluster(j)->GetTransformMatrix(mat2);\n\t\t\t\tif ((Map<Matrix4d>((double*)(mat1))-Map<Matrix4d>((double*)(mat2))).squaredNorm()>1e-10) err(\"Multiple bind poses.\\n\");\n\t\t\t}\n\t\t\tpSkin->GetCluster(0)->GetTransformMatrix(gMat);\t\t\t\n\t\t}\n\n\t\tMatrix4d gm=Map<Matrix4d>((double*)(gMat));\n\t\tv=(gm*v.colwise().homogeneous()).topRows<3>();\n\t\n\t\t// Load skeleton (if exists)\n\t\tvector<JointNode> jn(0);\n\t\ttravel(lScene->GetRootNode(), NULL, jn);\n\n\t\t// No joint\n\t\tif ((nB==0)&&(jn.size()==0)) return true;\n\n\t\tif ((nB!=0)&&(jn.size()!=nB)) err(\"Scene has more joints than skinCluster has: \"<<jn.size()<<\"/\"<<nB<<\".\\n\");\n\n\t\t// No skinCluster, indexing by the DFS travel order in scene\n\t\tif (nB==0) {\n\t\t\tnB=(int)jn.size();\n\t\t\tjointName.resize(nB);\n\t\t\tfor (int j=0; j<nB; j++) jointName[j]=jn[j].pNode->GetName();\n\t\t}\n\n\t\tfor (int j=0; j<nB; j++) {\n\t\t\tstring name=jn[j].pNode->GetName();\n\t\t\tparent[name]=(jn[j].pParentJoint==NULL)?\"\":jn[j].pParentJoint->GetName();\n\t\t\tbind[name]=Map<Matrix4d>((double*)(jn[j].pNode->EvaluateGlobalTransform()));\n\n\t\t\tEFbxRotationOrder lRotationOrder;\n\t\t\tjn[j].pNode->GetRotationOrder(FbxNode::eSourcePivot, lRotationOrder);\n\t\t\tswitch (lRotationOrder) {\n\t\t\t\tcase eEulerXYZ: rotOrder[name]=Vector3i(0, 1, 2); break;\n\t\t\t\tcase eEulerXZY: rotOrder[name]=Vector3i(0, 2, 1); break;\n\t\t\t\tcase eEulerYZX: rotOrder[name]=Vector3i(1, 2, 0); break;\n\t\t\t\tcase eEulerYXZ: rotOrder[name]=Vector3i(1, 0, 2); break;\n\t\t\t\tcase eEulerZXY: rotOrder[name]=Vector3i(2, 0, 1); break;\n\t\t\t\tcase eEulerZYX: rotOrder[name]=Vector3i(2, 1, 0); break;\n\t\t\t}\n\n\t\t\tFbxDouble3 oj=jn[j].pNode->PreRotation.Get();\n\t\t\torient[name]<<oj[0], oj[1], oj[2];\n\n\t\t\tif (jn[j].pNode->GetParent()!=jn[j].pParentJoint) {\n\t\t\t\tMatrix4d gp=Map<Matrix4d>((double*)(jn[j].pNode->GetParent()->EvaluateGlobalTransform()));\n\t\t\t\tif (jn[j].pParentJoint==NULL) preMulInv[name]=gp.inverse(); else {\n\t\t\t\t\tMatrix4d gjp=Map<Matrix4d>((double*)(jn[j].pParentJoint->EvaluateGlobalTransform()));\n\t\t\t\t\tpreMulInv[name]=gp.inverse()*gjp;\n\t\t\t\t}\n\t\t\t} else preMulInv[name]=Matrix4d::Identity();\n\n\t\t\tFbxProperty att=jn[j].pNode->FindProperty(\"demLock\", false);\n\t\t\tif (att.IsValid()&&(att.GetPropertyDataType()==FbxBoolDT)&&att.Get<bool>()) lockM[name]=1; else lockM[name]=0;\n\t\t}\n\n\t\tint nFr=(int)fTime.size();\n\t\tfor (int j=0; j<nB; j++) {\n\t\t\tif ((jn[j].pNode->LclRotation.GetCurveNode()!=NULL)||(jn[j].pNode->LclTranslation.GetCurveNode()!=NULL)) hasKeyFrame=true;\n\t\t\tstring name=jn[j].pNode->GetName();\n\t\t\tm[name].resize(4*nFr, 4);\n\t\t\tfor (int k=0; k<nFr; k++) {\n\t\t\t\tFbxTime tk;\n\t\t\t\ttk.SetSecondDouble(fTime(k));\n\t\t\t\tm[name].blk4(k, 0)=Map<Matrix4d>((double*)(jn[j].pNode->EvaluateGlobalTransform(tk)))*bind[name].inverse();\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\nprivate:\n\tstruct JointNode {\n\t\tFbxNode* pNode;\n\t\tFbxNode* pParentJoint;\n\t\tJointNode(FbxNode* pn=NULL, FbxNode* pp=NULL):pNode(pn), pParentJoint(pp) {}\n\t};\n\n\tvoid travel(FbxNode* pNode, FbxNode* pParentJoint, vector<JointNode>& jn) {\n\t\tfor (int i=0; i<pNode->GetNodeAttributeCount(); i++)\n\t\t\tif (pNode->GetNodeAttributeByIndex(i)->GetAttributeType()==FbxNodeAttribute::eSkeleton) {\n\t\t\t\tjn.push_back(JointNode(pNode, pParentJoint));\n\t\t\t\tpParentJoint=pNode;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tfor (int j=0; j<pNode->GetChildCount(); j++)\n\t\t\ttravel(pNode->GetChild(j), pParentJoint, jn);\n\t}\n\n\tdouble grayScale(const FbxColor& c) {\n\t\treturn 0.2989*c.mRed+0.5870*c.mGreen+0.1140*c.mBlue;\n\t}\n};\n\nbool readFBXs(const vector<string>& fileNames, DemBonesExt<double, float>& model) {\n\tif ((int)fileNames.size()!=model.nS) err(\"Wrong number of FBX files or ABC files have not been loaded.\\n\");\n\n\tmsg(1, \"Reading FBXs:\\n\");\n\n\tFbxSceneImporter importer;\n\n\tMatrixXd wd(0, 0);\n\tbool hasKeyFrame=false;\n\n\tfor (int s=0; s<model.nS; s++) {\n\t\tmsg(1, \"    \\\"\"<<fileNames[s]<<\"\\\"... \");\n\t\tif (!importer.open(fileNames[s])) err(\"Error on opening file.\\n\");\n\t\tint nFr=model.fStart(s+1)-model.fStart(s);\n\t\tif (!importer.load(model.fTime.segment(model.fStart(s), nFr))) return false;\n\n\t\tif (s==0) {\n\t\t\t//Init\n\t\t\tif (importer.v.cols()!=model.nV) err(\"Inconsistent geometry.\\n\");\n\t\t\tmodel.u.resize(model.nS*3, model.nV);\n\t\t\tmodel.u.block(0, 0, 3, model.nV)=importer.v;\n\t\t\tmodel.fv=importer.fv;\n\n\t\t\tmodel.nB=(int)importer.jointName.size();\n\t\t\tmodel.boneName=importer.jointName;\n\n\t\t\tmodel.parent.resize(model.nB);\n\t\t\tmodel.bind.resize(model.nS*4, model.nB*4);\n\t\t\tmodel.preMulInv.resize(model.nS*4, model.nB*4);\n\t\t\tmodel.rotOrder.resize(model.nS*3, model.nB);\n\t\t\tmodel.orient.resize(model.nS*3, model.nB);\n\t\t\tmodel.lockM.resize(model.nB);\n\n\t\t\tfor (int j=0; j<model.nB; j++) {\n\t\t\t\tstring nj=model.boneName[j];\n\t\t\t\t\n\t\t\t\tmodel.parent(j)=-1;\n\t\t\t\tfor (int k=0; k<model.nB; k++)\n\t\t\t\t\tif (model.boneName[k]==importer.parent[nj]) model.parent(j)=k;\n\t\t\t\n\t\t\t\tmodel.bind.blk4(s, j)=importer.bind[nj];\n\t\t\t\tmodel.preMulInv.blk4(s, j)=importer.preMulInv[nj];\n\t\t\t\tmodel.rotOrder.vec3(s, j)=importer.rotOrder[nj];\n\t\t\t\tmodel.orient.vec3(s, j)=importer.orient[nj];\n\t\t\t\tmodel.lockM(j)=importer.lockM[nj];\n\t\t\t}\n\n\t\t\tif (importer.wT.size()!=0) {\n\t\t\t\twd=MatrixXd::Zero(model.nB, model.nV);\n\t\t\t\tfor (int j=0; j<model.nB; j++) wd.row(j)=importer.wT[model.boneName[j]].transpose();\n\t\t\t}\n\n\t\t\tmodel.lockW=importer.lockW;\n\n\t\t\tmodel.m.resize(model.nF*4, model.nB*4);\n\t\t} else {\n\t\t\t//Merge\n\t\t\tif (importer.v.cols()!=model.nV) err(\"Inconsistent geometry.\\n\");\n\t\t\tmodel.u.block(s*3, 0, 3, model.nV)=importer.v;\n\t\t\tif (model.fv!=importer.fv) err(\"Inconsistent geometry.\\n\");\n\n\t\t\tif (model.nB!=importer.jointName.size()) err(\"Inconsistent joints set.\\n\");\n\n\t\t\tfor (int j=0; j<model.nB; j++) {\n\t\t\t\tstring nj=model.boneName[j];\n\n\t\t\t\tif (importer.parent.find(nj)==importer.parent.end()) err(\"Inconsistent joints set.\\n\");\n\t\t\t\tstring pName=(model.parent(j)==-1)?\"\":model.boneName[model.parent(j)];\n\t\t\t\tif (importer.parent[nj]!=pName) err(\"Inconsistent skeleton hierarchy.\\n\");\n\n\t\t\t\tif (importer.bind.find(nj)==importer.bind.end()) err(\"Inconsistent joints set.\\n\");\n\t\t\t\tmodel.bind.blk4(s, j)=importer.bind[nj];\n\t\t\t\tif (importer.preMulInv.find(nj)==importer.preMulInv.end()) err(\"Inconsistent joints set.\\n\");\n\t\t\t\tmodel.preMulInv.blk4(s, j)=importer.preMulInv[nj];\n\t\t\t\tif (importer.rotOrder.find(nj)==importer.rotOrder.end()) err(\"Inconsistent joints set.\\n\");\n\t\t\t\tmodel.rotOrder.vec3(s, j)=importer.rotOrder[nj];\n\t\t\t\tif (importer.orient.find(nj)==importer.orient.end()) err(\"Inconsistent joints set.\\n\");\n\t\t\t\tmodel.orient.vec3(s, j)=importer.orient[nj];\n\t\t\t\tif (model.lockM(j)!=importer.lockM[nj]) err(\"Inconsistent joint lock set.\\n\");\n\t\t\t}\n\n\t\t\tif (wd.rows()!=importer.wT.size()) err(\"Inconsistent skinningWeights.\\n\");\n\t\t\tif (wd.rows()!=0) for (int j=0; j<model.nB; j++) wd.col(j)+=importer.wT[model.boneName[j]];\n\t\t\tmodel.lockW+=importer.lockW;\n\t\t}\n\n\t\tfor (int j=0; j<model.nB; j++) model.m.block(s*4, j*4, nFr*4, 4)=importer.m[model.boneName[j]];\n\t\thasKeyFrame|=importer.hasKeyFrame;\n\t\t\n\t\tmsg(1, \"Done!\\n\");\n\t}\n\n\tmodel.w=(wd/model.nS).sparseView(1, 1e-20);\n\tmodel.lockW/=(double)model.nS;\n\tif (!hasKeyFrame) model.m.resize(0, 0);\n\n\tmsg(1, \"    \"<<model.nV<<\" vertices\");\n\tif (model.nB!=0) msg(1, \", \"<<model.nB<<\" joints found\");\n\tif (hasKeyFrame) msg(1, \", key frames found\");\n\tif (model.w.size()!=0) msg(1, \", skinning weights found\");\n\tmsg(1, \"\\n\");\n\n\treturn true;\n}\n\n#undef err\n", "meta": {"hexsha": "06e48abab9374eebddffd5cf9e1f81ca57e0012f", "size": 11437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/command/FbxReader.cpp", "max_stars_repo_name": "kamilisa/dem-bones", "max_stars_repo_head_hexsha": "1786704b0fa13874e1dfc28036d889b162e3b1b6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-03T23:49:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T06:31:03.000Z", "max_issues_repo_path": "src/command/FbxReader.cpp", "max_issues_repo_name": "kamilisa/dem-bones", "max_issues_repo_head_hexsha": "1786704b0fa13874e1dfc28036d889b162e3b1b6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/command/FbxReader.cpp", "max_forks_repo_name": "kamilisa/dem-bones", "max_forks_repo_head_hexsha": "1786704b0fa13874e1dfc28036d889b162e3b1b6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-16T00:43:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-16T00:43:11.000Z", "avg_line_length": 34.2425149701, "max_line_length": 200, "alphanum_fraction": 0.6434379645, "num_tokens": 3716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5690311124945494}}
{"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": "//------------------------------------------------------------------------------\n/// \\file Radix_tests.cpp\n/// \\author Ernest Yeung\n/// \\email  ernestyalumni@gmail.com\n/// \\ref https://en.wikipedia.org/wiki/Radix\n/// https://www.youtube.com/watch?v=NLKQEOgBAnw\n/// Algorithms: Bit Manipulation. HackerRank. Gayle Laakmann McDowell.\n/// \\details To run only the Bits unit tests, do this:\n/// ./Check --run_test=\"Algorithms/Bits\"\n/// \n/// Also, consider running the BooleanAlgebra_tests, as such:\n/// ./Check --run_test=\"Utilities/BooleanAlgebra_tests\"\n//------------------------------------------------------------------------------\n#include \"Algorithms/Bits/Masks.h\"\n#include \"Algorithms/Bits/Shift.h\"\n#include \"Cpp/Numerics/BitCast.h\"\n#include \"Cpp/Utilities/SuperBitSet.h\"\n#include \"Utilities/EndianConversions.h\"\n#include \"Utilities/ToHexString.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <cstdint>\n#include <iostream>\n#include <limits>\n\nusing Algorithms::Bits::clear_bit;\nusing Algorithms::Bits::is_bit_set_high;\nusing Algorithms::Bits::set_bit_high;\nusing Algorithms::Bits::logical_right_shift;\nusing Cpp::Numerics::bit_cast;\nusing Cpp::Utilities::SuperBitSet;\nusing Cpp::Utilities::number_of_bits_in_a_byte;\nusing Utilities::ToHexString;\nusing Utilities::to_big_endian;\nusing Utilities::to_little_endian;\n\nBOOST_AUTO_TEST_SUITE(Algorithms)\nBOOST_AUTO_TEST_SUITE(Bits)\nBOOST_AUTO_TEST_SUITE(NumericalRepresentation_tests)\n\n// cf. https://www.cs.utexas.edu/users/fussell/courses/cs429h/lectures/Lecture_2-429h.pdf\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(BinaryRepresentation)\n{\n  // Limits\n  {\n    std::cout << \"\\n\\n Unsigned limits \\n\";\n\n    std::cout << \"std::numeric_limits<uint8_t>::max(): \" <<\n      static_cast<unsigned int>(std::numeric_limits<uint8_t>::max()) << \"\\n\";\n        // 255\n    std::cout << \"std::numeric_limits<uint16_t>::max(): \" <<\n      std::numeric_limits<uint16_t>::max() << \"\\n\"; // 65535\n    std::cout << \"std::numeric_limits<uint32_t>::max(): \" <<\n      std::numeric_limits<uint32_t>::max() << \"\\n\"; // 4294967295\n    std::cout << \"std::numeric_limits<uint64_t>::max(): \" <<\n      std::numeric_limits<uint64_t>::max() << \"\\n\"; // 18446744073709551615\n\n    std::cout << \"\\n FloatingPoint limits \\n\";\n\n    std::cout << \"std::numeric_limits<float>::max(): \" <<\n      std::numeric_limits<float>::max() << \"\\n\";\n    std::cout << \"std::numeric_limits<double>::max(): \" <<\n      std::numeric_limits<double>::max() << \"\\n\";\n  }\n\n  {\n    std::cout << \"\\n\\n Signed limits \\n\";\n\n    std::cout << \"std::numeric_limits<int8_t>::max(): \" <<\n      static_cast<unsigned int>(std::numeric_limits<int8_t>::max()) << \"\\n\";\n        // 127\n    std::cout << \"std::numeric_limits<int16_t>::max(): \" <<\n      std::numeric_limits<int16_t>::max() << \"\\n\"; // 32767\n    std::cout << \"std::numeric_limits<int32_t>::max(): \" <<\n      std::numeric_limits<int32_t>::max() << \"\\n\"; // 2147483647\n    std::cout << \"std::numeric_limits<int64_t>::max(): \" <<\n      std::numeric_limits<int64_t>::max() << \"\\n\"; // 18446744073709551615\n\n    std::cout << \"std::numeric_limits<int8_t>::min(): \" <<\n      static_cast<int>(std::numeric_limits<int8_t>::min()) << \"\\n\";\n        // -128\n    std::cout << \"std::numeric_limits<int16_t>::min(): \" <<\n      std::numeric_limits<int16_t>::min() << \"\\n\"; // -32768\n    std::cout << \"std::numeric_limits<int32_t>::min(): \" <<\n      std::numeric_limits<int32_t>::min() << \"\\n\"; // -2147483648\n    std::cout << \"std::numeric_limits<int64_t>::min(): \" <<\n      std::numeric_limits<int64_t>::min() << \"\\n\"; // 18446744073709551615\n  }\n\n  // Examples\n  {\n    std::cout << \"\\n Examples of Binary Representations \\n\";\n\n    {\n      SuperBitSet<sizeof(uint16_t) * number_of_bits_in_a_byte> x {15213};\n      std::cout << \"15213_10 as binary: \" << x.to_string() << \"\\n\";\n    }\n  }\n\n}\n\n// cf. https://en.cppreference.com/w/cpp/language/integer_literal\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(IntegerLiteralBitsAsChars)\n{\n  {\n    const uint8_t au {0b00};\n    BOOST_TEST_REQUIRE(au == 0);\n\n    SuperBitSet<8> bits8 {au};\n    BOOST_TEST(bits8.to_string() == \"00000000\");\n\n    const char ac {0b00};\n    SuperBitSet<8> cbits8 {ac};\n    BOOST_TEST(cbits8.to_string() == \"00000000\");\n  } \n  {\n    const uint8_t au {0b01};\n    BOOST_TEST_REQUIRE(au == 1);\n\n    SuperBitSet<8> bits8 {au};\n    BOOST_TEST(bits8.to_string() == \"00000001\");\n\n    const char ac {0b01};\n    SuperBitSet<8> cbits8 {ac};\n    BOOST_TEST(cbits8.to_string() == \"00000001\");\n  } \n  {\n    const uint8_t au {0b10};\n    BOOST_TEST_REQUIRE(au == 2);\n\n    SuperBitSet<8> bits8 {au};\n    BOOST_TEST(bits8.to_string() == \"00000010\");\n\n    const char ac {0b10};\n    SuperBitSet<8> cbits8 {ac};\n    BOOST_TEST(cbits8.to_string() == \"00000010\");\n  } \n  {\n    const uint8_t au {0b11};\n    BOOST_TEST_REQUIRE(au == 3);\n\n    SuperBitSet<8> bits8 {au};\n    BOOST_TEST(bits8.to_string() == \"00000011\");\n\n    const char ac {0b11};\n    SuperBitSet<8> cbits8 {ac};\n    BOOST_TEST(cbits8.to_string() == \"00000011\");\n  } \n}\n\n// cf. https://www.youtube.com/watch?v=NLKQEOgBAnw\n// Algorithms: Bit Manipulation,  HackerRank with Gayle Laakmann McDowell.\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(BinaryAdditionCarriesOne)\n{\n  const uint8_t a {0b0101};\n  const uint8_t b {0b0011};\n  const uint8_t c {a + b};\n  SuperBitSet<8> c8 {c};\n  BOOST_TEST(c8.to_string() == \"00001000\");\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(TwosComplement)\n{\n  // cf. https://www.cs.utexas.edu/users/fussell/courses/cs429h/lectures/Lecture_3-429h.pdf\n  // \"Encoding Integers.\" \n  {\n    const int16_t x {15213};\n    const SuperBitSet<16> xbits16 {x};\n    BOOST_TEST(xbits16.to_string() == \"0011101101101101\");\n    ToHexString<int16_t> xh {x};\n\n    // *** stack smashing detected ***: terminated\n    // unknown location(0): fatal error: in \"Algorithms/Bits/NumericalRepresentation_tests/TwosComplement\": signal: SIGABRT (application abort requested)\n    //BOOST_TEST(xh() == \"6d3b\");\n    ToHexString<int16_t> be_xh {to_big_endian(xh)};\n    //BOOST_TEST(be_xh() == \"3b6d\");\n\n    const int16_t y {-15213};\n    const auto yu = bit_cast<uint16_t>(y);\n    const SuperBitSet<16> yubits16 {yu};\n    BOOST_TEST(yubits16.to_string() == \"1100010010010011\");\n    ToHexString<int16_t> yh {y};\n    //BOOST_TEST(yh() == \"93c4\");\n    ToHexString<int16_t> be_yh {to_big_endian(yh)};\n    //BOOST_TEST(be_yh() == \"c493\");\n  }\n\n  {\n    const int8_t a {18};\n    const auto au = bit_cast<uint8_t>(a);\n    SuperBitSet<8> aubits8 {au};\n    // Sign bit is 0 for positive.\n    BOOST_TEST(aubits8.to_string() == \"00010010\");\n  }\n  {\n    const int8_t a {-18};\n    const auto au = bit_cast<uint8_t>(a);\n    SuperBitSet<8> aubits8 {au};\n    // Sign bit is 0 for positive.\n    BOOST_TEST(aubits8.to_string() == \"11101110\");\n  }\n}\n\n// cf. http://sandbox.mc.edu/~bennet/cs110/tc/add.html\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(\n  TwosComplementBinaryAdditionWhenSumIsNotArithemticallyCorrect)\n{\n  // Overflow, no carryout (at sign bit). Sum is not correct.\n  {\n    const int8_t x {104};\n    const SuperBitSet<8> xbits8 {x};\n    BOOST_TEST(xbits8.to_string() == \"01101000\");\n    ToHexString<int8_t> xh {x};\n    //BOOST_TEST(xh() == \"68\");\n\n    const int8_t y {45};\n    const SuperBitSet<8> ybits8 {y};\n    BOOST_TEST(ybits8.to_string() == \"00101101\");\n    ToHexString<int8_t> yh {y};\n    //BOOST_TEST(yh() == \"2d\");\n\n    const auto z = x + y;\n    BOOST_TEST(sizeof(z) == 4);\n    const SuperBitSet<8> zbits8 {z};\n    BOOST_TEST(zbits8.to_string() == \"10010101\");\n    BOOST_TEST(zbits8.to_ulong() == 149);\n\n    // \"Wraps around\" to -128 and \"up\".\n    const int8_t z8 {-107};\n    const SuperBitSet<8> z8bits8 {bit_cast<uint8_t>(z8)};\n    BOOST_TEST(z8bits8.to_string() == \"10010101\");\n  }\n  // Overflow, with incidental carryout. Sum is not correct.\n  {\n    const int8_t x {-103};\n    const SuperBitSet<8> xbits8 {bit_cast<uint8_t>(x)};\n    BOOST_TEST(xbits8.to_string() == \"10011001\");\n    ToHexString<int8_t> xh {x};\n\n    // *** stack smashing detected ***: terminated\n    // unknown location(0): fatal error: in \"Algorithms/Bits/NumericalRepresentation_tests/TwosComplementBinaryAdditionWhenSumIsNotArithemticallyCorrect\": signal: SIGABRT (application abort requested) \n    //BOOST_TEST(xh() == \"99\");\n\n    const int8_t y {-69};\n    const SuperBitSet<8> ybits8 {bit_cast<uint8_t>(y)};\n    BOOST_TEST(ybits8.to_string() == \"10111011\");\n    ToHexString<int8_t> yh {y};\n\n    // *** stack smashing detected ***: terminated\n    // unknown location(0): fatal error: in \"Algorithms/Bits/NumericalRepresentation_tests/TwosComplementBinaryAdditionWhenSumIsNotArithemticallyCorrect\": signal: SIGABRT (application abort requested) \n    //BOOST_TEST(yh() == \"bb\");\n\n    const auto z = x + y;\n    BOOST_TEST(sizeof(z) == 4);\n    const SuperBitSet<32> zbits32 {bit_cast<uint32_t>(z)};\n    BOOST_TEST(zbits32.to_string() == \"11111111111111111111111101010100\");\n    BOOST_TEST(z == -172);\n\n    // \"Wraps around\" to -128 and \"up\".\n    const int8_t z8 {84};\n    const SuperBitSet<8> z8bits8 {bit_cast<uint8_t>(z8)};\n    BOOST_TEST(z8bits8.to_string() == \"01010100\");\n  }\n}\n\n// cf. https://www.youtube.com/watch?v=NLKQEOgBAnw\n// Algorithms: Bit Manipulation,  HackerRank with Gayle Laakmann McDowell.\n// This test breaks down step by step the algorithm Gayle described clearly that\n// also explains the name two's complement to get the additive inverse (i.e.\n// the negative) of a positive integer.\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(GetAdditiveInverseFromComplement)\n{\n  const int8_t x {18};\n  SuperBitSet<8> xbits8 {bit_cast<uint8_t>(x)};\n  BOOST_TEST(xbits8.to_string() == \"00010010\");\n\n  BOOST_TEST((~xbits8).to_string() == \"11101101\");\n\n  const int8_t not_x {~x};\n  SuperBitSet<8> not_xbits8 {bit_cast<uint8_t>(not_x)};\n  BOOST_TEST(not_xbits8.to_string() == \"11101101\");\n\n  const int8_t not_x_plus_1 {not_x + 1};\n  SuperBitSet<8> not_x_plus_1bits8 {bit_cast<uint8_t>(not_x_plus_1)};\n  BOOST_TEST(not_x_plus_1bits8.to_string() == \"11101110\");\n\n  const int8_t y {-18};\n  SuperBitSet<8> ybits8 {bit_cast<uint8_t>(y)};\n  BOOST_TEST(ybits8.to_string() == \"11101110\");\n  BOOST_TEST(ybits8.to_string() == not_x_plus_1bits8.to_string());\n}\n\n// cf. https://youtu.be/NLKQEOgBAnw?t=399\n// Logical right shift fills in zero for sign bit.\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(LogicalRightShiftOnNegativeNumbers)\n{\n  SuperBitSet<8> xbits8 {bit_cast<uint8_t>(logical_right_shift<int8_t>(23, 1))};\n  BOOST_TEST(xbits8.to_string() == \"00001011\");\n\n  int8_t y {-23};\n  SuperBitSet<8> ybits8 {bit_cast<uint8_t>(y)};\n  BOOST_TEST(ybits8.to_string() == \"11101001\");\n\n  SuperBitSet<8> zbits8 {bit_cast<uint8_t>(logical_right_shift<int8_t>(y, 1))};\n  BOOST_TEST(zbits8.to_string() == \"01110100\");\n}\n\n// cf. https://youtu.be/NLKQEOgBAnw?t=399\n// Arithmetic right shift shifts everything to the right including sign bit,\n// fills in sign bit with original sign bit.\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ArithmeticRightShiftOnNegativeNumbers)\n{\n  int8_t x {-23};\n  int8_t y {1};\n  // Works, but it warns. Narrowing conversion.\n  //int8_t z {x >> y};\n  //SuperBitSet<8> xbits8 {bit_cast<uint8_t>(z)};\n  //BOOST_TEST(xbits8.to_string() == \"11110100\");\n  {\n    int8_t x {-22};\n    SuperBitSet<8> xbits8 {bit_cast<uint8_t>(x)};\n    BOOST_TEST(xbits8.to_string() == \"11101010\");\n    // Works but it warns. Narrowing conversion.\n    //int8_t y {x >> 1};\n    //SuperBitSet<8> ybits8 {bit_cast<uint8_t>(y)};\n    //BOOST_TEST(ybits8.to_string() == \"11110101\");    \n  }\n}\n\n// cf. https://en.cppreference.com/w/cpp/language/operator_arithmetic\n// lhs << rhs\n// left shift of lhs by rhs bits.\n// lhs >> rhs\n// right shift of lhs by rhs bits\n// For built-in operators, lhs and rhs must both have integral or unscoped\n// enumeration type. Integral promotions performed on both operands.\n// Return type is type of left operand after integral promotions.\n// For unsigned a, value of a << b is value a * 2^b, reduced modulo 2^N, where\n// N is number of bits in return type (that is, bitwise left shift is performed\n// and bits that get shifted out of destination type are discarded).\n// For negative a, behavior of a << b is undefined.\n//\n// since C++14\n// For signed and non-negative a, if a*2^b representable in unsigned version\n// of return type, then taht value, converted to signed, is value of a << b\n// For negative a, value of a >> b is implementation-defined (in most\n// implementations, this performs arithmetic right shift, so result remains\n// negative)\n//\n// since C++20\n// a << b is unique value congrent to a * 2^b modulo 2^N where N is number of\n// bits in return type (that is bitwise left shift performed and bits that get\n// shifted out of destination type are discarded).\n// Value of a >> b is a/2^b, rounded down (i.e., right shift on signed a is\n// arithmetic right shift).\n\nBOOST_AUTO_TEST_SUITE(BitwiseShiftOperator_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(Examples)\n{\n  char c {0x10};\n  SuperBitSet<8> cbits8 {bit_cast<uint8_t>(c)};\n  BOOST_TEST(cbits8.to_string() == \"00010000\");\n\n  SuperBitSet<32> xbits32 {bit_cast<uint32_t>(c << 10)};\n  BOOST_TEST(\n    xbits32.to_string() == \"00000000000000000100000000000000\");\n  BOOST_TEST((c << 10) == 0x4000);\n\n  unsigned long long ull {0x123};\n  SuperBitSet<number_of_bits_in_a_byte * sizeof(unsigned long long)>\n    ullbits_ull {bit_cast<uint64_t>(ull)};\n  BOOST_TEST(\n    ullbits_ull.to_string() ==\n      \"0000000000000000000000000000000000000000000000000000000100100011\");\n\n  {\n    SuperBitSet<number_of_bits_in_a_byte * sizeof(unsigned long long)>\n      xbits_ull {bit_cast<uint64_t>(ull << 1)};\n\n    BOOST_TEST(\n      xbits_ull.to_string() ==\n        \"0000000000000000000000000000000000000000000000000000001001000110\");\n\n    BOOST_TEST(xbits_ull.to_ullong() == 0x246);\n  }\n  {\n    // overflow in unsigned\n    SuperBitSet<number_of_bits_in_a_byte * sizeof(unsigned long long)>\n      xbits_ull {bit_cast<uint64_t>(ull << 63)};\n\n    BOOST_TEST(\n      xbits_ull.to_string() ==\n        \"1000000000000000000000000000000000000000000000000000000000000000\");\n\n    BOOST_TEST(xbits_ull.to_ullong() == 0x8000000000000000);\n  }\n\n  // For negative a, value of a >> b in most implementations is arithmetic right\n  // shift, shifts everything to right including sign bit, fills in sign bit\n  // with original sign bit.\n  long long ll {-1000};\n  SuperBitSet<number_of_bits_in_a_byte * sizeof(long long)>\n    llbits_ll {bit_cast<uint64_t>(ll)};\n  BOOST_TEST(\n    llbits_ll.to_string() ==\n      \"1111111111111111111111111111111111111111111111111111110000011000\");\n\n  SuperBitSet<number_of_bits_in_a_byte * sizeof(long long)>\n    xbits_ll {bit_cast<uint64_t>(ll >> 1)};\n  BOOST_TEST(\n    xbits_ll.to_string() ==\n      \"1111111111111111111111111111111111111111111111111111111000001100\");\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(BitwiseLeftShiftOfNegativeNumbers)\n{\n  int8_t x {-5};\n  SuperBitSet<8> xbits8 {bit_cast<uint8_t>(x)};\n  // Indeed this is the \"two's complement\" of 00000101 = 5; take the complement\n  // and then add 1.\n  BOOST_TEST(xbits8.to_string() == \"11111011\");\n\n  // cf. https://en.cppreference.com/w/cpp/language/operator_arithmetic\n  // cppreference says this is undefined.\n  x << 1;\n\n  auto y {x << 1};\n\n  // std::cout << y << \"\\n\"; // -10\n\n  // template argument deduction/substitution failed.\n  // SuperBitSet<8> ybits8 {bit_cast<uint8_t>(x << 1)};\n  // SuperBitSet<8> ybits8 {bit_cast<int8_t>(x << 1)};\n  //SuperBitSet<16> ybits16 {bit_cast<uint16_t>(x << 1)};\n  //SuperBitSet<16> ybits16 {bit_cast<int16_t>(x << 1)};\n\n  SuperBitSet<32> ybits32 {bit_cast<uint32_t>(y)};\n\n  BOOST_TEST(ybits32.to_string() == \"11111111111111111111111111110110\");\n}\n\nBOOST_AUTO_TEST_SUITE_END() // BitwiseShiftOperator_tests\n\nBOOST_AUTO_TEST_SUITE(Masks_tests)\n\n// https://youtu.be/NLKQEOgBAnw?t=444\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(BitwiseAndToGetIthBit)\n{\n  int8_t x {44};\n\n  SuperBitSet<8> xbits8 {bit_cast<uint8_t>(x)};\n  BOOST_TEST(xbits8.to_string() == \"00101100\");\n\n  // (x & (1 << c)) != 0\n  BOOST_TEST((x & (1 << 5)) != 0);\n\n  BOOST_TEST((x & (1 << 7)) == 0);\n  BOOST_TEST((x & (1 << 6)) == 0);\n  BOOST_TEST((x & (1 << 4)) == 0);\n  BOOST_TEST((x & (1 << 1)) == 0);\n  BOOST_TEST((x & (1 << 0)) == 0);\n\n  BOOST_TEST((x & (1 << 3)) != 0);\n  BOOST_TEST((x & (1 << 2)) != 0);\n\n  BOOST_TEST(!is_bit_set_high(x, 0));\n  BOOST_TEST(!is_bit_set_high(x, 1));\n  BOOST_TEST(!is_bit_set_high(x, 4));\n  BOOST_TEST(!is_bit_set_high(x, 6));\n  BOOST_TEST(!is_bit_set_high(x, 7));\n\n  BOOST_TEST(is_bit_set_high(x, 2));\n  BOOST_TEST(is_bit_set_high(x, 3));\n  BOOST_TEST(is_bit_set_high(x, 5));\n\n  int8_t y {-44}; // 11010100\n\n  BOOST_TEST(is_bit_set_high(y, 2));\n  BOOST_TEST(is_bit_set_high(y, 4));\n  BOOST_TEST(is_bit_set_high(y, 6));\n  BOOST_TEST(is_bit_set_high(y, 7));\n\n  BOOST_TEST(!is_bit_set_high(y, 0));\n  BOOST_TEST(!is_bit_set_high(y, 1));\n  BOOST_TEST(!is_bit_set_high(y, 3));\n  BOOST_TEST(!is_bit_set_high(y, 5));\n}\n\n// https://youtu.be/NLKQEOgBAnw?t=466\n// Set ith bit, x | (1 << i)\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(BitwiseOrToSetIthBit)\n{\n  int8_t x {44};\n\n  BOOST_TEST(is_bit_set_high(x, 5));\n  x = set_bit_high(x, 5);\n  BOOST_TEST(is_bit_set_high(x, 5));\n\n  BOOST_TEST(!is_bit_set_high(x, 6));\n  x = set_bit_high(x, 6);\n  BOOST_TEST(is_bit_set_high(x, 6));\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ClearBitWithMaskWithAll1ButThatSpot)\n{\n  int8_t x {44};\n  BOOST_TEST(is_bit_set_high(x, 5));\n  x = clear_bit(x, 5);\n  BOOST_TEST(!is_bit_set_high(x, 5));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Masks_tests\n\nBOOST_AUTO_TEST_SUITE_END() // Radix_tests\nBOOST_AUTO_TEST_SUITE_END() // Bits\nBOOST_AUTO_TEST_SUITE_END() // Algorithms", "meta": {"hexsha": "0eab29d8d6069260e90e965297c05bb6ca3a802b", "size": 19426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Algorithms/Bits/Radix_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Algorithms/Bits/Radix_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Algorithms/Bits/Radix_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7753222836, "max_line_length": 201, "alphanum_fraction": 0.5990939977, "num_tokens": 5343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.5689977584016216}}
{"text": "// SPDX-License-Identifier: BSD-2-Clause\n\n#ifndef ROS_UTILS_HPP\n#define ROS_UTILS_HPP\n\n#include <Eigen/Dense>\n\n#include <ros/ros.h>\n#include <nav_msgs/Odometry.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/TransformStamped.h>\n\nnamespace hdl_graph_slam {\n\n/**\n * @brief convert Eigen::Matrix to geometry_msgs::TransformStamped\n * @param stamp            timestamp\n * @param pose             Eigen::Matrix to be converted\n * @param frame_id         tf frame_id\n * @param child_frame_id   tf child frame_id\n * @return converted TransformStamped\n */\nstatic geometry_msgs::TransformStamped matrix2transform(const ros::Time& stamp, const Eigen::Matrix4f& pose, const std::string& frame_id, const std::string& child_frame_id) {\n  Eigen::Quaternionf quat(pose.block<3, 3>(0, 0));\n  quat.normalize();\n  geometry_msgs::Quaternion odom_quat;\n  odom_quat.w = quat.w();\n  odom_quat.x = quat.x();\n  odom_quat.y = quat.y();\n  odom_quat.z = quat.z();\n\n  geometry_msgs::TransformStamped odom_trans;\n  odom_trans.header.stamp = stamp;\n  odom_trans.header.frame_id = frame_id;\n  odom_trans.child_frame_id = child_frame_id;\n\n  odom_trans.transform.translation.x = pose(0, 3);\n  odom_trans.transform.translation.y = pose(1, 3);\n  odom_trans.transform.translation.z = pose(2, 3);\n  odom_trans.transform.rotation = odom_quat;\n\n  return odom_trans;\n}\n\nstatic Eigen::Isometry3d pose2isometry(const geometry_msgs::Pose& pose) {\n  Eigen::Isometry3d mat = Eigen::Isometry3d::Identity();\n  mat.translation() = Eigen::Vector3d(pose.position.x, pose.position.y, pose.position.z);\n  mat.linear() = Eigen::Quaterniond(pose.orientation.w, pose.orientation.x, pose.orientation.y, pose.orientation.z).toRotationMatrix();\n  return mat;\n}\n\nstatic Eigen::Isometry3d tf2isometry(const tf::StampedTransform& trans) {\n  Eigen::Isometry3d mat = Eigen::Isometry3d::Identity();\n  mat.translation() = Eigen::Vector3d(trans.getOrigin().x(), trans.getOrigin().y(), trans.getOrigin().z());\n  mat.linear() = Eigen::Quaterniond(trans.getRotation().w(), trans.getRotation().x(), trans.getRotation().y(), trans.getRotation().z()).toRotationMatrix();\n  return mat;\n}\n\nstatic geometry_msgs::Pose isometry2pose(const Eigen::Isometry3d& mat) {\n  Eigen::Quaterniond quat(mat.linear());\n  Eigen::Vector3d trans = mat.translation();\n\n  geometry_msgs::Pose pose;\n  pose.position.x = trans.x();\n  pose.position.y = trans.y();\n  pose.position.z = trans.z();\n  pose.orientation.w = quat.w();\n  pose.orientation.x = quat.x();\n  pose.orientation.y = quat.y();\n  pose.orientation.z = quat.z();\n\n  return pose;\n}\n\nstatic Eigen::Isometry3d odom2isometry(const nav_msgs::OdometryConstPtr& odom_msg) {\n  const auto& orientation = odom_msg->pose.pose.orientation;\n  const auto& position = odom_msg->pose.pose.position;\n\n  Eigen::Quaterniond quat;\n  quat.w() = orientation.w;\n  quat.x() = orientation.x;\n  quat.y() = orientation.y;\n  quat.z() = orientation.z;\n\n  Eigen::Isometry3d isometry = Eigen::Isometry3d::Identity();\n  isometry.linear() = quat.toRotationMatrix();\n  isometry.translation() = Eigen::Vector3d(position.x, position.y, position.z);\n  return isometry;\n}\n\nstatic Eigen::Isometry2d odom2isometry2d(const nav_msgs::OdometryConstPtr& odom_msg) {\n  const auto& orientation = odom_msg->pose.pose.orientation;\n  const auto& position = odom_msg->pose.pose.position;\n\n  Eigen::Quaterniond quat;\n  quat.w() = orientation.w;\n  quat.x() = orientation.x;\n  quat.y() = orientation.y;\n  quat.z() = orientation.z;\n\n  Eigen::Vector3d ea = (quat.toRotationMatrix()).eulerAngles(2, 1, 0); \n  //std::cout << \"to ypr angles: \" << ea << std::endl;\n  //std::cout << \"yawss: \" << ea[0] << std::endl;\n\n  Eigen::Isometry2d isometry = Eigen::Isometry2d::Identity();\n  Eigen::Rotation2D<double> rot(ea[0]);\n  isometry.linear() = rot.toRotationMatrix();\n  //std::cout << \"rot1: \" << cos(ea[0]) << \" \" << -sin(ea[0]) << \" \" << sin(ea[0]) << \" \" << cos(ea[0]) << std::endl;\n  //std::cout << \"rot2: \" << isometry.linear() << std::endl;\n  isometry.translation() = Eigen::Vector2d(position.x, position.y);\n  //std::cout << \"tr: \" << isometry.translation() << std::endl;\n  //std::cout << \"iso: \" << isometry.matrix() << std::endl;\n  return isometry;\n}\n\n}  // namespace hdl_graph_slam\n\n#endif  // ROS_UTILS_HPP\n", "meta": {"hexsha": "0e9880ad82589038cc66df5bf5eba6b3a4bda948", "size": 4232, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hdl_graph_slam/ros_utils.hpp", "max_stars_repo_name": "Ronicasss/hdl_graph_slam", "max_stars_repo_head_hexsha": "75370587cb16278d36dd524bcc13d51bf9d7603d", "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/hdl_graph_slam/ros_utils.hpp", "max_issues_repo_name": "Ronicasss/hdl_graph_slam", "max_issues_repo_head_hexsha": "75370587cb16278d36dd524bcc13d51bf9d7603d", "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/hdl_graph_slam/ros_utils.hpp", "max_forks_repo_name": "Ronicasss/hdl_graph_slam", "max_forks_repo_head_hexsha": "75370587cb16278d36dd524bcc13d51bf9d7603d", "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.5630252101, "max_line_length": 174, "alphanum_fraction": 0.6949432892, "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038223, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5689977465433395}}
{"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": "/* ----------------------------------------------------------------------------\n * GTDynamics Copyright 2020, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n/**\n * @file  testDynamics.cpp\n * @brief Test calculations for statics.\n * @author Frank Dellaert\n */\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/base/numericalDerivative.h>\n\n#include <boost/bind.hpp>\n#include <cmath>\n\n#include \"gtdynamics/dynamics/Dynamics.h\"\n#include \"gtdynamics/universal_robot/RobotModels.h\"\n\nusing namespace gtdynamics;\nusing namespace gtsam;\n\nnamespace example {\nconstexpr double g = 9.8;\nconst Robot robot = gtdynamics::CreateRobotFromFile(\n    kSdfPath + std::string(\"/test/four_bar_linkage.sdf\"));\nVector3 gravity(0, 0, -g);\n}  // namespace example\n\nTEST(Dynamics, Coriolis) {\n  using namespace example;\n  auto inertia = robot.link(\"l1\")->inertiaMatrix();\n  Matrix6 actualH;\n  auto twist = (Vector(6) << 1, 2, 3, 4, 5, 6).finished();\n  const Vector6 expected =\n      gtsam::Pose3::adjointTranspose(twist, inertia * twist);\n  EXPECT(assert_equal(expected, Coriolis(inertia, twist, actualH), 1e-6));\n  Matrix6 numericalH = numericalDerivative11<Vector6, Vector6>(\n      boost::bind(&Coriolis, inertia, _1, boost::none), twist);\n  EXPECT(assert_equal(numericalH, actualH, 1e-6));\n}\n\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n", "meta": {"hexsha": "02276c9c18dae9f4fd703e376ba5396c6814ef50", "size": 1512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testDynamics.cpp", "max_stars_repo_name": "danbarla/GTDynamics", "max_stars_repo_head_hexsha": "0448b359aff9e0e784832666e4048ee01c8b082d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/testDynamics.cpp", "max_issues_repo_name": "danbarla/GTDynamics", "max_issues_repo_head_hexsha": "0448b359aff9e0e784832666e4048ee01c8b082d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/testDynamics.cpp", "max_forks_repo_name": "danbarla/GTDynamics", "max_forks_repo_head_hexsha": "0448b359aff9e0e784832666e4048ee01c8b082d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.24, "max_line_length": 80, "alphanum_fraction": 0.6507936508, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5689900600563269}}
{"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  Matrix3i m = Matrix3i::Random();\ncout << \"Here is the matrix m:\" << endl << m << endl;\ncout << \"Here are the coefficients on the main diagonal of m:\" << endl\n     << m.diagonal() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "4e218b97d6d1f6c8bc192ef45c837d13b8f921be", "size": 339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_diagonal.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_diagonal.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_diagonal.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": 19.9411764706, "max_line_length": 70, "alphanum_fraction": 0.6430678466, "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7371581684030621, "lm_q1q2_score": 0.5689707391608652}}
{"text": "//          Copyright Alain Miniussi 2014.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n// Authors: Alain Miniussi\n\n#include <vector>\n#include <iostream>\n\n#include <boost/mpi/communicator.hpp>\n#include <boost/mpi/collectives.hpp>\n#include <boost/mpi/environment.hpp>\n#include <boost/mpi/cartesian_communicator.hpp>\n\n#include <boost/test/minimal.hpp>\n\nnamespace mpi = boost::mpi;\n// Curly brace init make this useless, but\n//  - Need to support obsolete like g++ 4.3.x. for some reason\n//  - Can't conditionnaly compile with bjam (unless you find\n//  the doc, and read it, which would only make sense if you\n//  actually wan't to use bjam, which does not (make sense))\ntypedef mpi::cartesian_dimension cd;\n\nint test_main(int argc, char* argv[])\n{\n  mpi::environment  env;\n  mpi::communicator world;\n\n  if (world.size() != 24)  return -1;\n  mpi::cartesian_dimension dims[] = {cd(2, true), cd(3,true), cd(4,true)};\n  mpi::cartesian_communicator cart(world, mpi::cartesian_topology(dims));\n  for (int r = 0; r < cart.size(); ++r) {\n    cart.barrier();\n    if (r == cart.rank()) {\n      std::vector<int> c = cart.coordinates(r);\n      std::cout << \"rk :\" << r << \" coords: \"\n                << c[0] << ' ' << c[1] << ' ' << c[2] << '\\n';\n    }\n  }\n  return 0;\n}\n", "meta": {"hexsha": "8664cde1d50258a93a55218476d8142681a7eef4", "size": 1381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/mpi/example/cartesian_communicator.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/mpi/example/cartesian_communicator.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/mpi/example/cartesian_communicator.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 31.3863636364, "max_line_length": 74, "alphanum_fraction": 0.6444605358, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.5689707347039483}}
{"text": "// unit test file sinc.hpp for the special functions test suite\r\n\r\n//  (C) Copyright Hubert Holin 2003. Permission to copy, use, modify, sell and\r\n//  distribute this software is granted provided this copyright notice appears\r\n//  in all copies. This software is provided \"as is\" without express or implied\r\n//  warranty, and with no claim as to its suitability for any purpose.\r\n\r\n\r\n#include <functional>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <complex>\r\n\r\n\r\n#include <boost/math/special_functions/sinc.hpp>\r\n\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n\r\ntemplate<typename T>\r\nvoid    sinc_pi_test(const char * more_blurb)\r\n{\r\n    using    ::std::abs;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    using    ::boost::math::sinc_pi;\r\n    \r\n    \r\n    BOOST_MESSAGE(\"Testing sinc_pi in the real domain for \"\r\n        << more_blurb << \".\");\r\n    \r\n    BOOST_CHECK_PREDICATE(::std::less_equal<T>(), 2,\r\n        (\r\n            abs(sinc_pi<T>(static_cast<T>(0))-static_cast<T>(1)),\r\n            numeric_limits<T>::epsilon()\r\n        ));\r\n}\r\n\r\n\r\ntemplate<typename T>\r\nvoid    sinc_pi_complex_test(const char * more_blurb)\r\n{\r\n    using    ::std::abs;\r\n    using    ::std::sinh;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    using    ::boost::math::sinc_pi;\r\n    \r\n    \r\n    BOOST_MESSAGE(\"Testing sinc_pi in the complex domain for \"\r\n        << more_blurb << \".\");\r\n    \r\n    BOOST_CHECK_PREDICATE(::std::less_equal<T>(), 2,\r\n        (\r\n            abs(sinc_pi<T>(::std::complex<T>(0, 1))-\r\n                ::std::complex<T>(sinh(static_cast<T>(1)))),\r\n            numeric_limits<T>::epsilon()\r\n        ));\r\n}\r\n\r\n\r\nvoid    sinc_pi_manual_check()\r\n{\r\n    using    ::boost::math::sinc_pi;\r\n    \r\n    \r\n    BOOST_MESSAGE(\"sinc_pi\");\r\n    \r\n    for    (int i = 0; i <= 100; i++)\r\n    {\r\n        BOOST_MESSAGE( ::std::setw(15)\r\n                    << sinc_pi<float>(static_cast<float>(i-50)/\r\n                                                static_cast<float>(50))\r\n                    << ::std::setw(15)\r\n                    << sinc_pi<double>(static_cast<double>(i-50)/\r\n                                                static_cast<double>(50))\r\n                    << ::std::setw(15)\r\n                    << sinc_pi<long double>(static_cast<long double>(i-50)/\r\n                                                static_cast<long double>(50)));\r\n    }\r\n    \r\n    BOOST_MESSAGE(\" \");\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "fa82dcd5e978fda2c0f2b52218dcbddea14628aa", "size": 2412, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/sinc_test.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/sinc_test.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/sinc_test.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1011235955, "max_line_length": 80, "alphanum_fraction": 0.521973466, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5689707269664088}}
{"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\u00e4nkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef ITL_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": "//\n// Created by a.kiryanenko on 3/26/20.\n//\n\n#include \"../SpuUltraGraphAdapter.h\"\n#include \"../SpuUltraGraphProperty.h\"\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include \"GraphPerformanceTest.h\"\n\n\nusing namespace SPU_GRAPH;\nusing namespace boost;\n\n\ntypedef boost::adjacency_list <\n        boost::vecS, // \u043a\u0430\u043a \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u0432\u0435\u0440\u0448\u0438\u043d\u044b - \u0432 \u0432\u0435\u043a\u0442\u043e\u0440\u0435\n        boost::vecS, // \u043a\u0430\u043a \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u0440\u0435\u0431\u0440\u0430 \u0438\u0437 \u043a\u0430\u0436\u0434\u043e\u0439 \u0432\u0435\u0440\u0448\u0438\u043d\u044b - \u0432 \u0432\u0435\u043a\u0442\u043e\u0440\u0435\n        boost::directedS,\n        no_property,\n        property < edge_weight_t, int >\n> AdjacencyListGraph;\n\n\n\ntemplate <class G>\nvoid breadth_first_test(G &g) {\n    // \u0412\u044b\u043f\u043e\u043b\u043d\u044f\u044e \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u043f\u043e\u0438\u0441\u043a\u0430 \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443\n    breadth_first_search(g, 1, visitor(default_bfs_visitor()));\n}\n\n\nint main()\n{\n    cout << \"SpuUltraGraph performance test\" << endl;\n    cout << \"==========================================\" << endl;\n    GraphPerformanceTest<SpuUltraGraph> spu_graph_test(breadth_first_test, \"breadth_first_test_SpuUltraGraph.csv\");\n    spu_graph_test.is_mutable_test = false;\n    spu_graph_test.start();\n\n    cout << \"adjacency_list performance test\" << endl;\n    cout << \"==========================================\" << endl;\n    GraphPerformanceTest<AdjacencyListGraph> adjacency_list_test(breadth_first_test, \"breadth_first_test_adjacency_list.csv\");\n    adjacency_list_test.is_mutable_test = false;\n    adjacency_list_test.start();\n\n    cout << \"adjacency_matrix performance test\" << endl;\n    cout << \"==========================================\" << endl;\n    GraphPerformanceTest<AdjacencyMatrixGraph> adjacency_matrix_test(breadth_first_test, \"breadth_first_test_adjacency_matrix.csv\");\n    adjacency_matrix_test.is_mutable_test = false;\n    adjacency_matrix_test.end_vertices_cnt = 20000;\n    adjacency_matrix_test.start();\n    return 0;\n}", "meta": {"hexsha": "0f942e08b90e654b987b7b77c704f8703ce651df", "size": 1794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "performance_tests/breadth_first.cpp", "max_stars_repo_name": "kiryanenko/graph-api", "max_stars_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T19:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-29T19:42:34.000Z", "max_issues_repo_path": "performance_tests/breadth_first.cpp", "max_issues_repo_name": "kiryanenko/graph-api", "max_issues_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "performance_tests/breadth_first.cpp", "max_forks_repo_name": "kiryanenko/graph-api", "max_forks_repo_head_hexsha": "43436b98189db58587a7cf779293dac8f4b5e39a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2222222222, "max_line_length": 132, "alphanum_fraction": 0.6806020067, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5688759780058781}}
{"text": "#ifndef slic3r_Point_hpp_\n#define slic3r_Point_hpp_\n\n#include <myinit.h>\n#include <vector>\n#include <math.h>\n#include <boost/polygon/polygon.hpp>\n#include <string>\n\nnamespace Slic3r {\n\nclass Line;\nclass Point;\nclass Pointf;\ntypedef Point Vector;\ntypedef std::vector<Point> Points;\ntypedef std::vector<Point*> PointPtrs;\ntypedef std::vector<Pointf> Pointfs;\n\nclass Point\n{\n    public:\n    coord_t x;\n    coord_t y;\n    explicit Point(coord_t _x = 0, coord_t _y = 0): x(_x), y(_y) {};\n    bool operator==(const Point& rhs) const;\n    std::string wkt() const;\n    void scale(double factor);\n    void translate(double x, double y);\n    void rotate(double angle, Point* center);\n    bool coincides_with(const Point &point) const;\n    bool coincides_with(const Point* point) const;\n    int nearest_point_index(Points &points) const;\n    int nearest_point_index(PointPtrs &points) const;\n    Point* nearest_point(Points points) const;\n    double distance_to(const Point* point) const;\n    double distance_to(const Line* line) const;\n    double distance_to(const Line &line) const;\n    double ccw(const Point &p1, const Point &p2) const;\n    double ccw(const Point* p1, const Point* p2) const;\n    double ccw(const Line &line) const;\n    \n    #ifdef SLIC3RXS\n    void from_SV(SV* point_sv);\n    void from_SV_check(SV* point_sv);\n    SV* to_SV_ref();\n    SV* to_SV_clone_ref() const;\n    SV* to_SV_pureperl() const;\n    #endif\n};\n\nclass Point3 : public Point\n{\n    public:\n    coord_t z;\n    explicit Point3(coord_t _x = 0, coord_t _y = 0, coord_t _z = 0): Point(_x, _y), z(_z) {};\n};\n\nclass Pointf\n{\n    public:\n    coordf_t x;\n    coordf_t y;\n    explicit Pointf(coordf_t _x = 0, coordf_t _y = 0): x(_x), y(_y) {};\n    void scale(double factor);\n    void translate(double x, double y);\n    \n    #ifdef SLIC3RXS\n    bool from_SV(SV* point_sv);\n    SV* to_SV_pureperl() const;\n    #endif\n};\n\nclass Pointf3 : public Pointf\n{\n    public:\n    coordf_t z;\n    explicit Pointf3(coordf_t _x = 0, coordf_t _y = 0, coordf_t _z = 0): Pointf(_x, _y), z(_z) {};\n    void scale(double factor);\n    void translate(double x, double y, double z);\n};\n\n}\n\n// start Boost\nnamespace boost { namespace polygon {\n    template <>\n    struct geometry_concept<Point> { typedef point_concept type; };\n   \n    template <>\n    struct point_traits<Point> {\n        typedef coord_t coordinate_type;\n    \n        static inline coordinate_type get(const Point& point, orientation_2d orient) {\n            return (orient == HORIZONTAL) ? point.x : point.y;\n        }\n    };\n} }\n// end Boost\n\n#endif\n", "meta": {"hexsha": "8f3cec554a488c2ec187167c891fc25cf6b15878", "size": 2558, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "xs/src/Point.hpp", "max_stars_repo_name": "djeclipse25/Slic3r", "max_stars_repo_head_hexsha": "9c7cc484bccfbf6d6443e3e1889d7509ac59b34b", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-28T10:53:41.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-28T10:53:41.000Z", "max_issues_repo_path": "xs/src/Point.hpp", "max_issues_repo_name": "djeclipse25/Slic3r", "max_issues_repo_head_hexsha": "9c7cc484bccfbf6d6443e3e1889d7509ac59b34b", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xs/src/Point.hpp", "max_forks_repo_name": "djeclipse25/Slic3r", "max_forks_repo_head_hexsha": "9c7cc484bccfbf6d6443e3e1889d7509ac59b34b", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0784313725, "max_line_length": 98, "alphanum_fraction": 0.664190774, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5688759753242179}}
{"text": "/* test_geometric.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/geometric_distribution.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/math/distributions/geometric.hpp>\r\n#include <boost/numeric/conversion/cast.hpp>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::geometric_distribution<>\r\n#define BOOST_RANDOM_DISTRIBUTION_NAME geometric\r\n#define BOOST_MATH_DISTRIBUTION boost::math::geometric\r\n#define BOOST_RANDOM_ARG1_TYPE double\r\n#define BOOST_RANDOM_ARG1_NAME p\r\n#define BOOST_RANDOM_ARG1_DEFAULT 0.5\r\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(0.0001, 0.9999)\r\n#define BOOST_RANDOM_DISTRIBUTION_MAX boost::numeric_cast<int>(-5 / std::log(1-p))\r\n\r\n#include \"test_real_distribution.ipp\"\r\n", "meta": {"hexsha": "c8ff79a48cb4764aaa12aad8cc6cb142107bd42b", "size": 937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_geometric.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/random/test/test_geometric.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/random/test/test_geometric.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": 34.7037037037, "max_line_length": 83, "alphanum_fraction": 0.7780149413, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324611869563, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5688054869205855}}
{"text": "/**\r\n *  @file    UtilsTest.cpp\r\n *  @brief   Test the utility functions.\r\n *  @author  Francois Roy\r\n *  @date    12/01/2019\r\n */\r\n#include <catch2/catch.hpp>\r\n#include <Eigen/Core>\r\n#include \"utils/Utils.hpp\"\r\n\r\nnamespace\r\n{\r\n\r\n// true test\r\nbool all_close_true(){\r\n    Eigen::VectorXd u = Eigen::VectorXd::Constant(11, 1.2);\r\n    Eigen::VectorXd d = Eigen::VectorXd::Constant(11, 1.2);\r\n    return utils::all_close(u, d);\r\n}\r\n\r\n// false test\r\nbool all_close_false(){\r\n    Eigen::VectorXd u = Eigen::VectorXd::Constant(11, 1.2);\r\n    Eigen::VectorXd d = Eigen::VectorXd::Constant(11, 1.3);\r\n    return utils::all_close(u, d);\r\n}\r\n\r\n}  // namespace\r\n\r\nTEST_CASE( \"all_close are computed\", \"[all_close]\" )\r\n{\r\n    CHECK( all_close_true() );\r\n    CHECK_FALSE( all_close_false() );\r\n}\r\nTEST_CASE(\"Test linear_spaced\", \"[utils]\")\r\n{\r\n\tstd::vector<double> u = {0.0, 1.1, 2.2, 3.3};\r\n\tauto v = utils::linear_spaced<double>(0, 3.3, 4);\r\n\tfor(int i; i<u.size(); i++){\r\n        CHECK(v[i] == Approx(u[i]) );\r\n\t}\r\n}\r\n", "meta": {"hexsha": "99a1a28aaafb8dbbbeb0983cafe61ce507e575b3", "size": 1008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/utils/UtilsTest.cpp", "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": "tests/utils/UtilsTest.cpp", "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": "tests/utils/UtilsTest.cpp", "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": 23.4418604651, "max_line_length": 60, "alphanum_fraction": 0.5972222222, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.5688054852379197}}
{"text": "#ifndef BLOCKSVD_H\n#define BLOCKSVD_H\n\n#include \"clear/MyGraph.hpp\"\n\n#include <iostream>\n#include <vector>\n#include <numeric>\n#include <queue>\n#include <algorithm>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n\nusing namespace std;\nusing Eigen::MatrixXf;\nusing Eigen::MatrixXi;\n\ninline void blockSVD(Eigen::MatrixXf A, Eigen::MatrixXf Lnrm, Eigen::MatrixXf& Vl, Eigen::MatrixXf& sl)\n{\n\tMyGraph G(A);\n\tunsigned n = A.rows();\n\tG.findConnComps();\n\tvector<vector<unsigned>> ConnComps = G.getConnComps();\n\n\tMatrixXf V;\n\tV = MatrixXf::Zero(n,n);\n\tvector<double> s(n, 0.0);\n\t// cout << \"Number of connected components: \" << ConnComps.size() << endl;\n\n\tfor (unsigned cc = 0; cc < ConnComps.size(); ++cc){\n\t\tvector<unsigned> Comp = ConnComps[cc];\n\t\tunsigned CompSize = Comp.size();\n\t\tMatrixXf Lc;\n\t\tLc = MatrixXf::Zero(CompSize, CompSize);\n\t\tfor (unsigned i = 0; i < CompSize; ++i){\n\t\t\tfor (unsigned j = 0; j < CompSize; ++j){\n\t\t\t\tLc(i,j) = Lnrm(Comp[i], Comp[j]);\n\t\t\t}\n\t\t}\n\t\t// Compute SVD of this block\n\t\tEigen::JacobiSVD<MatrixXf> svd(Lc, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\t\tMatrixXf Vc = svd.matrixV();\n\t\tMatrixXf sc = svd.singularValues(); // a column vector of singular values in decreasing order\n\n\t\tfor (unsigned i = 0; i < CompSize; ++i){\n\t\t\tfor (unsigned j = 0; j < CompSize; ++j){\n\t\t\t\tV(Comp[i], Comp[j]) = Vc(i,j);\n\t\t\t}\n\t\t}\n\t\tfor (unsigned i = 0; i < CompSize; ++i){\n\t\t\ts[Comp[i]] = sc(i);\n\t\t}\n\t}\n\n\t// sort based on singular values (in decreasing order)\n\tvector<size_t> sorted_idx(s.size());\n\tstd::iota(sorted_idx.begin(), sorted_idx.end(), 0);\n\tstd::sort(sorted_idx.begin(), sorted_idx.end(),\n\t       [&s](size_t i1, size_t i2) {return s[i1] > s[i2];});\n\n\tsl = MatrixXf::Zero(n,1);\n\tVl = MatrixXf::Zero(n,n);\n\n\t// rearrange based on sorted index\n\tfor (unsigned i = 0 ; i < n ; ++i){\n\t\tunsigned k = sorted_idx[i];\n\t\tsl(i) = s[k];\n\t\tVl.col(i) = V.col(k);\n\t}\n}\n\n\n#endif ", "meta": {"hexsha": "1a5a2468a7ae7f5fd1031b50e17af2223e39d455", "size": 1924, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clear/blockSVD.hpp", "max_stars_repo_name": "NamDinhRobotics/clear-fusion", "max_stars_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:53.000Z", "max_issues_repo_path": "include/clear/blockSVD.hpp", "max_issues_repo_name": "NamDinhRobotics/clear-fusion", "max_issues_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/clear/blockSVD.hpp", "max_forks_repo_name": "NamDinhRobotics/clear-fusion", "max_forks_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0, "max_line_length": 103, "alphanum_fraction": 0.6418918919, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.5688054812697146}}
{"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": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE rationalClass\n#include <boost/test/unit_test.hpp>\n\n#include \"rational.h\"\n\nusing namespace ExactArithmetic;\nnamespace utf = boost::unit_test;\n\n// Test suite: arithmetic_operations\nBOOST_AUTO_TEST_SUITE(arithmetic_operations)\nBOOST_AUTO_TEST_CASE(addition)\n{\n  BOOST_CHECK_EQUAL(Rational(1, 3) + Rational(1, 3), Rational(2, 3));\n}\n\nBOOST_AUTO_TEST_CASE(subtraction)\n{\n  BOOST_CHECK_EQUAL(Rational(1, 3) - Rational(1, 3), Rational(0, 1));\n}\n\nBOOST_AUTO_TEST_CASE(multiplication)\n{\n  BOOST_CHECK_EQUAL(Rational(1, 3) * Rational(1, 3), Rational(1, 9));\n}\n\nBOOST_AUTO_TEST_CASE(division)\n{\n  BOOST_CHECK_EQUAL(Rational(1, 3) / Rational(1, 3), Rational(1, 1));\n}\nBOOST_AUTO_TEST_SUITE_END()\n// End of test suite: arithmetic operations\n\n// Test suite: constructors\nBOOST_AUTO_TEST_SUITE(constructors)\n\nBOOST_AUTO_TEST_CASE(default_constructor)\n{\n  // Test default constructor\n  Rational defaultConstructor;\n  BOOST_CHECK_EQUAL(defaultConstructor, Rational(0, 1));\n}\n\nBOOST_AUTO_TEST_CASE(two_thirds)\n{\n  // Test a num/denom constructor\n  Rational twoThirds(2, 3);\n  BOOST_CHECK_EQUAL(twoThirds, Rational(2, 3));\n}\n\nBOOST_AUTO_TEST_CASE(four_eight)\n{\n  // Test normalization\n  Rational fourEight(4, 8);\n  BOOST_CHECK_EQUAL(fourEight, Rational(1, 2));\n}\n\nBOOST_AUTO_TEST_CASE(integer_constructor)\n{\n  // Test integer constructor\n  Rational integerConstructor(4);\n  BOOST_CHECK_EQUAL(integerConstructor, Rational(4, 1));\n}\n\nBOOST_AUTO_TEST_CASE(double_constructor)\n{\n  // Test double constructor\n  Rational doubleConstructor(4.0);\n  BOOST_CHECK_EQUAL(doubleConstructor, Rational(4, 1));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n// End of test suite: constructors\n\n// Test suite: gcd\nBOOST_AUTO_TEST_SUITE(gcd)\nBOOST_AUTO_TEST_CASE(obvious)\n{\n  Rational veryBigRationalNumber(1000000000000000000, 2000000000000000000);\n  BOOST_CHECK_EQUAL(veryBigRationalNumber, Rational(1, 2));\n}\n\nBOOST_AUTO_TEST_CASE(random)\n{\n  Rational veryBigRationalNumber(98822773366119922, 22773399118822);\n  BOOST_CHECK_EQUAL(veryBigRationalNumber, Rational(49411386683059961, 11386699559411));\n}\nBOOST_AUTO_TEST_SUITE_END()\n// End of test suite: gcd\n\n\nBOOST_AUTO_TEST_SUITE(miscellaneous)\nBOOST_AUTO_TEST_CASE(abs_function)\n{\n  Rational negativeOneTwo(-1, 2);\n  BOOST_CHECK_EQUAL(Rational::abs(negativeOneTwo), Rational(1, 2));\n}\n\nBOOST_AUTO_TEST_CASE(negative)\n{\n  Rational negativeOneTwo(-1, 2);\n  Rational negativeOneTwoOnDenom(1, -2);\n  BOOST_CHECK_EQUAL(negativeOneTwo, Rational(-1, 2));\n  BOOST_CHECK_EQUAL(negativeOneTwoOnDenom, Rational(-1, 2));\n}\n\nBOOST_AUTO_TEST_CASE(negate_function)\n{\n  Rational negativeOneTwo(-1, 2);\n  Rational negativeOneTwoOnDenom(1, -2);\n\n  Rational oneTwo(1, 2);\n\n  BOOST_CHECK_EQUAL(Rational::negate(negativeOneTwo), Rational(1, 2));\n  BOOST_CHECK_EQUAL(Rational::negate(negativeOneTwoOnDenom), Rational(1, 2));\n  BOOST_CHECK_EQUAL(Rational::negate(oneTwo), Rational(-1, 2));\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "adcb042a0eff1698e19c072779ffa8c5204f9cc9", "size": 2951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_rational.cpp", "max_stars_repo_name": "Howard-HS/exact-arithmetic", "max_stars_repo_head_hexsha": "33eca65de71591c2bb49001d1342d5a25603ee16", "max_stars_repo_licenses": ["MIT"], "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_rational.cpp", "max_issues_repo_name": "Howard-HS/exact-arithmetic", "max_issues_repo_head_hexsha": "33eca65de71591c2bb49001d1342d5a25603ee16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_rational.cpp", "max_forks_repo_name": "Howard-HS/exact-arithmetic", "max_forks_repo_head_hexsha": "33eca65de71591c2bb49001d1342d5a25603ee16", "max_forks_repo_licenses": ["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.7983193277, "max_line_length": 88, "alphanum_fraction": 0.7804134192, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5688054807298178}}
{"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": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2006 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef quantlib_test_linear_least_squares_regression_hpp\n#define quantlib_test_linear_least_squares_regression_hpp\n\n#include <boost/test/unit_test.hpp>\n\n/* remember to document new and/or updated tests in the Doxygen\n   comment block of the corresponding class */\n\nclass LinearLeastSquaresRegressionTest {\n  public:\n    static void testRegression();\n    static void testMultiDimRegression();\n    static void test1dLinearRegression();\n    static boost::unit_test_framework::test_suite* suite();\n};\n\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2006 Klaus Spanderen\n Copyright (C) 2010 Slava Mazur\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include \"utilities.hpp\"\n#include <ql/math/functional.hpp>\n#include <ql/math/randomnumbers/rngtraits.hpp>\n#include <ql/math/linearleastsquaresregression.hpp>\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/bind.hpp>\n#include <boost/circular_buffer.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\nvoid LinearLeastSquaresRegressionTest::testRegression() {\n\n    BOOST_TEST_MESSAGE(\"Testing linear least-squares regression...\");\n\n    SavedSettings backup;\n\n    const Real tolerance = 0.05;\n\n    const Size nr=100000;\n    PseudoRandom::rng_type rng(PseudoRandom::urng_type(1234u));\n\n    std::vector<boost::function1<Real, Real> > v;\n    v.push_back(constant<Real, Real>(1.0));\n    v.push_back(QuantLib::identity<Real>());\n    v.push_back(square<Real>());\n    v.push_back(std::ptr_fun<Real, Real>(std::sin));\n\n    std::vector<boost::function1<Real, Real> > w(v);\n    w.push_back(square<Real>());\n\n    for (Size k=0; k<3; ++k) {\n        Size i;\n        const Real a[] = {rng.next().value,\n            rng.next().value,\n            rng.next().value,\n            rng.next().value};\n\n        std::vector<Real> x(nr), y(nr);\n        for (i=0; i<nr; ++i) {\n            x[i] = rng.next().value;\n\n            // regression in y = a_1 + a_2*x + a_3*x^2 + a_4*sin(x) + eps\n            y[i] =  a[0]*v[0](x[i]) + a[1]*v[1](x[i]) + a[2]*v[2](x[i])\n                + a[3]*v[3](x[i]) + rng.next().value;\n        }\n\n        LinearRegression m(x, y, v);\n\n        for (i=0; i<v.size(); ++i) {\n            if (m.standardErrors()[i] > tolerance) {\n                BOOST_ERROR(\"Failed to reproduce linear regression coef.\"\n                    << \"\\n    error:     \" << m.standardErrors()[i]\n                << \"\\n    tolerance: \" << tolerance);\n            }\n            if (std::fabs(m.coefficients()[i]-a[i]) > 3*m.standardErrors()[i]) {\n                BOOST_ERROR(\"Failed to reproduce linear regression coef.\"\n                    << \"\\n    calculated: \" << m.coefficients()[i]\n                << \"\\n    error:      \" << m.standardErrors()[i]\n                << \"\\n    expected:   \" << a[i]);\n            }\n        }\n\n        m = LinearRegression(x, y, w);\n\n        const Real ma[] = {m.coefficients()[0], m.coefficients()[1], \n            m.coefficients()[2]+m.coefficients()[4],\n            m.coefficients()[3]};\n        const Real err[] = {m.standardErrors()[0], m.standardErrors()[1],\n            std::sqrt( m.standardErrors()[2]*m.standardErrors()[2]\n        +m.standardErrors()[4]*m.standardErrors()[4]),\n            m.standardErrors()[3]};\n        for (i=0; i<v.size(); ++i) {\n            if (std::fabs(ma[i] - a[i]) > 3*err[i]) {\n                BOOST_ERROR(\"Failed to reproduce linear regression coef.\"\n                    << \"\\n    calculated: \" << ma[i]\n                << \"\\n    error:      \" << err[i]\n                << \"\\n    expected:   \" << a[i]);\n            }\n        }\n    }\n}\n\nnamespace {\n    Real f(const Array& a, Size i) {\n        return a[i];\n    }\n}\n\nvoid LinearLeastSquaresRegressionTest::testMultiDimRegression() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing multi-dimensional linear least-squares regression...\");\n\n    SavedSettings backup;\n\n    const Size nr=100000;\n    const Size dims = 4;\n    const Real tolerance = 0.01;\n    PseudoRandom::rng_type rng(PseudoRandom::urng_type(1234u));\n\n    std::vector<boost::function1<Real, Array> > v;\n    v.push_back(constant<Array, Real>(1.0));\n    for (Size i=0; i < dims; ++i) {\n        v.push_back(boost::bind(f, _1, i));\n    }\n\n    Array coeff(v.size());\n    for (Size i=0; i < v.size(); ++i) {\n        coeff[i] = rng.next().value;\n    }\n\n    std::vector<Real> y(nr, 0.0);\n    std::vector<Array> x(nr, Array(dims));\n    for (Size i=0; i < nr; ++i) {\n        for (Size j=0; j < dims; ++j) {\n            x[i][j] = rng.next().value;\n        }\n\n        for (Size j=0; j < v.size(); ++j) {\n            y[i] += coeff[j]*v[j](x[i]);\n        }\n        y[i] += rng.next().value;\n    }\n\n    LinearRegression m(x, y, v);\n\n    for (Size i=0; i < v.size(); ++i) {\n        if (m.standardErrors()[i] > tolerance) {\n            BOOST_ERROR(\"Failed to reproduce linear regression coef.\"\n                << \"\\n    error:     \" << m.standardErrors()[i]\n            << \"\\n    tolerance: \" << tolerance);\n        }\n\n        if (std::fabs(m.coefficients()[i]-coeff[i]) > 3*tolerance) {\n            BOOST_ERROR(\"Failed to reproduce linear regression coef.\"\n                << \"\\n    calculated: \" << m.coefficients()[i]\n            << \"\\n    error:      \" << m.standardErrors()[i]\n            << \"\\n    expected:   \" << coeff[i]);\n        }\n    }\n\n    // much simpler\n    LinearRegression m1(x, y, Real(1.0));\n\n    for (Size i=0; i < m1.dim(); ++i) {\n        if (m1.standardErrors()[i] > tolerance) {\n            BOOST_ERROR(\"Failed to reproduce linear regression coef.\"\n                << \"\\n    error:     \" << m1.standardErrors()[i]\n            << \"\\n    tolerance: \" << tolerance);\n        }\n\n        if (std::fabs(m1.coefficients()[i]-coeff[i]) > 3*tolerance) {\n            BOOST_ERROR(\"Failed to reproduce linear regression coef.\"\n                << \"\\n    calculated: \" << m1.coefficients()[i]\n            << \"\\n    error:      \" << m1.standardErrors()[i]\n            << \"\\n    expected:   \" << coeff[i]);\n        }\n    }\n}\n\nvoid LinearLeastSquaresRegressionTest::test1dLinearRegression() {\n\n    BOOST_TEST_MESSAGE(\"Testing 1D simple linear least-squares regression...\");\n\n    /* Example taken from the QuantLib-User list, see posting\n    * Multiple linear regression/weighted regression, Boris Skorodumov */\n\n    SavedSettings backup;\n\n    std::vector<Real> x(9),y(9);\n    x[0]=2.4; x[1]=1.8; x[2]=2.5; x[3]=3.0; \n    x[4]=2.1; x[5]=1.2; x[6]=2.0; x[7]=2.7; x[8]=3.6;\n\n    y[0]=7.8; y[1]=5.5; y[2]=8.0; y[3]=9.0;\n    y[4]=6.5; y[5]=4.0; y[6]=6.3; y[7]=8.4; y[8]=10.2;\n\n    std::vector<boost::function1<Real, Real> > v;\n    v.push_back(constant<Real, Real>(1.0));\n    v.push_back(QuantLib::identity<Real>());\n\n    LinearRegression m(x, y);\n\n    const Real tol = 0.0002;\n    const Real coeffExpected[]  = { 0.9448, 2.6853 };\n    const Real errorsExpected[] = { 0.3654, 0.1487 };\n\n    for (Size i=0; i < 2; ++i) {\n        if (std::fabs(m.standardErrors()[i]-errorsExpected[i]) > tol) {\n            BOOST_ERROR(\"Failed to reproduce linear regression standard errors\"\n                << \"\\n    calculated: \" << m.standardErrors()[i]\n            << \"\\n    expected:   \" << errorsExpected[i]                                          \n            << \"\\n    tolerance:  \" << tol);\n        }\n\n        if (std::fabs(m.coefficients()[i]-coeffExpected[i]) > tol) {\n            BOOST_ERROR(\"Failed to reproduce linear regression coef.\"\n                << \"\\n    calculated: \" << m.coefficients()[i]\n            << \"\\n    expected:   \" << coeffExpected[i]\n            << \"\\n    tolerance:  \" << tol);\n        }\n    }    \n\n    // an alternative container type \n    boost::circular_buffer<Real> cx(x.begin(), x.end()), cy(y.begin(), y.end());\n    LinearRegression m1(cx, cy);\n\n    for (Size i=0; i < 2; ++i) {\n        if (std::fabs(m1.standardErrors()[i]-errorsExpected[i]) > tol) {\n            BOOST_ERROR(\"Failed to reproduce linear regression standard errors\"\n                << \"\\n    calculated: \" << m1.standardErrors()[i]\n            << \"\\n    expected:   \" << errorsExpected[i]                                          \n            << \"\\n    tolerance:  \" << tol);\n        }\n\n        if (std::fabs(m1.coefficients()[i]-coeffExpected[i]) > tol) {\n            BOOST_ERROR(\"Failed to reproduce linear regression coef.\"\n                << \"\\n    calculated: \" << m1.coefficients()[i]\n            << \"\\n    expected:   \" << coeffExpected[i]\n            << \"\\n    tolerance:  \" << tol);\n        }\n    }    \n}\n\n\ntest_suite* LinearLeastSquaresRegressionTest::suite() {\n    test_suite* suite =\n        BOOST_TEST_SUITE(\"linear least squares regression tests\");\n    suite->add(QUANTLIB_TEST_CASE(\n        &LinearLeastSquaresRegressionTest::testRegression));\n    suite->add(QUANTLIB_TEST_CASE(\n        &LinearLeastSquaresRegressionTest::testMultiDimRegression));\n    suite->add(QUANTLIB_TEST_CASE(\n        &LinearLeastSquaresRegressionTest::test1dLinearRegression));\n    return suite;\n}\n\n\n#endif", "meta": {"hexsha": "a3667c968d802029a50ae98641eadf452aac234b", "size": 10644, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite/linearleastsquaresregression.hpp", "max_stars_repo_name": "markxio/Quantuccia", "max_stars_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2017-03-20T14:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T08:00:52.000Z", "max_issues_repo_path": "test-suite/linearleastsquaresregression.hpp", "max_issues_repo_name": "markxio/Quantuccia", "max_issues_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-04-02T14:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T05:31:12.000Z", "max_forks_repo_path": "test-suite/linearleastsquaresregression.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": 35.3621262458, "max_line_length": 98, "alphanum_fraction": 0.5754415633, "num_tokens": 2807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5688054750789465}}
{"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": "#include <geometry.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n#include <vector>\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(intersection)\n{\n  typedef tiny::MathTypes<float> MT;\n  typedef MT::vector3_type       V;\n  \n  {\n    geometry::Plane<V> const A = geometry::make_plane( V::make(0,0,1), -1.0);\n    geometry::Plane<V> const B = geometry::make_plane( V::make(0,1,0), -1.0);\n    geometry::Line<V>  const L = geometry::make_intersection(A,B);\n    \n    BOOST_CHECK_CLOSE( geometry::get_distance(L.point(), A), 0.0, 0.01f );\n    BOOST_CHECK_CLOSE( geometry::get_distance(L.point(), B), 0.0, 0.01f );\n    BOOST_CHECK_CLOSE( inner_prod(L.direction(), A.normal()), 0.0, 0.01f );\n    BOOST_CHECK_CLOSE( inner_prod(L.direction(), B.normal()), 0.0, 0.01f );\n    BOOST_CHECK_CLOSE( inner_prod(L.direction(), L.direction()), 1.0, 0.01f );\n  }\n\n  {\n    geometry::Plane<V> const A = geometry::make_plane( V::make(0,0,1), -1.0);\n    geometry::Plane<V> const B = geometry::make_plane( V::make(0,1,0), -1.0);\n    geometry::Plane<V> const C = geometry::make_plane( V::make(1,0,0), -1.0);\n    \n    V const p = geometry::make_intersection(A,B,C);\n    \n    BOOST_CHECK_CLOSE( geometry::get_distance(p, A), 0.0, 0.01f );\n    BOOST_CHECK_CLOSE( geometry::get_distance(p, B), 0.0, 0.01f );\n    BOOST_CHECK_CLOSE( geometry::get_distance(p, C), 0.0, 0.01f );\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "6bb638f0bc7125f1e24de4ffc89dfdb8ba935413", "size": 1566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_make_intersection/geometry_make_intersection.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_make_intersection/geometry_make_intersection.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_make_intersection/geometry_make_intersection.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3191489362, "max_line_length": 78, "alphanum_fraction": 0.6711366539, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.56875391661493}}
{"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": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/integral.hpp>\n#include <boost/hana/list/instance.hpp>\n#include <boost/hana/pair.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTEXPR_LAMBDA auto xs = list(int_<1>, int_<2>, int_<3>, int_<4>);\n    BOOST_HANA_CONSTANT_ASSERT(\n        span(xs, _ < int_<3>)\n        ==\n        pair(list(int_<1>, int_<2>), list(int_<3>, int_<4>))\n    );\n\n    BOOST_HANA_CONSTANT_ASSERT(\n        span(xs, _ < int_<0>)\n        ==\n        pair(list(), xs)\n    );\n\n    BOOST_HANA_CONSTANT_ASSERT(\n        span(xs, _ < int_<5>)\n        ==\n        pair(xs, list())\n    );\n    //! [main]\n}\n", "meta": {"hexsha": "2c3d8fdbf2d9730f4bab467fb155794f77157a32", "size": 914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/list/span.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/list/span.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/list/span.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0526315789, "max_line_length": 83, "alphanum_fraction": 0.6236323851, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.5687539028955471}}
{"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": "//==================================================================================================\n/*!\n\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#include <boost/simd/function/scalar/cot.hpp>\n#include <boost/simd/function/restricted.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/pio_2.hpp>\n#include <boost/simd/constant/pio_4.hpp>\n\nSTF_CASE_TPL (\" cot\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::cot;\n\n  using r_t = decltype(cot(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(cot(-bs::Zero<T>()), -bs::Inf<r_t>(), 0.5);\n  STF_ULP_EQUAL(cot(bs::Inf<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(cot(bs::Minf<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(cot(bs::Nan<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(cot(bs::Zero<T>()), bs::Inf<r_t>(), 0.5);\n#endif\n  STF_ULP_EQUAL(cot(-bs::Pio_2<T>()), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(cot(-bs::Pio_4<T>()), bs::Mone<r_t>(), 0.5);\n  STF_ULP_EQUAL(cot(bs::Pio_2<T>()), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(cot(bs::Pio_4<T>()), bs::One<r_t>(), 0.5);\n}\n\nSTF_CASE_TPL (\" cot restricted_\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::cot;\n\n  using r_t = decltype(cot(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(bs::restricted_(cot)(-bs::Zero<T>()), -bs::Inf<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(cot)(bs::Inf<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(cot)(bs::Minf<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(cot)(bs::Nan<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(cot)(bs::Zero<T>()), bs::Inf<r_t>(), 0.5);\n#endif\n  STF_ULP_EQUAL(bs::restricted_(cot)(-bs::Pio_2<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(cot)(-bs::Pio_4<T>()), bs::Mone<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(cot)(bs::Pio_2<T>()), bs::Nan<r_t>(), 0.5);\n  STF_ULP_EQUAL(bs::restricted_(cot)(bs::Pio_4<T>()), bs::One<r_t>(), 0.5);\n}\n", "meta": {"hexsha": "1629e8c8879dcc81b658323b9c295b970b17bfc1", "size": 2653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/cot.cpp", "max_stars_repo_name": "timblechmann/boost.simd", "max_stars_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "test/function/scalar/cot.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/scalar/cot.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 36.8472222222, "max_line_length": 100, "alphanum_fraction": 0.6125141349, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5686839899576056}}
{"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": "// Copyright 2012 Davide Anastasia\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/// \\file lab_test.cpp\n/// \\brief Unit test for LAB Colorspace\n/// \\author Davide Anastasia <davideanastasia@users.sourceforge.net>\n\n#include <boost/test/unit_test.hpp>\n\n#define TEST_CHECK_CLOSE(a, b) \\\n    BOOST_CHECK_CLOSE(a, b, 0.0005f)\n\n#include <iostream>\n#include <boost/gil/gil_all.hpp>\n#include <boost/gil/extension/toolbox/color_spaces/lab.hpp>\n\nusing namespace boost;\n\nBOOST_AUTO_TEST_SUITE(Lab_Test)\n\nBOOST_AUTO_TEST_CASE(Lab_to_XYZ_Test1)\n{\n    gil::lab32f_pixel_t lab_pixel(40.366198f, 53.354489f, 26.117702f);\n    gil::xyz32f_pixel_t xyz_pixel;\n\n    gil::color_convert(lab_pixel, xyz_pixel);\n\n    TEST_CHECK_CLOSE(static_cast<float>(xyz_pixel[0]), 0.197823f);\n    TEST_CHECK_CLOSE(static_cast<float>(xyz_pixel[1]), 0.114731f);\n    TEST_CHECK_CLOSE(static_cast<float>(xyz_pixel[2]), 0.048848f);\n}\n\nBOOST_AUTO_TEST_CASE(Lab_to_XYZ_Test2)\n{\n    gil::lab32f_pixel_t lab_pixel(50, 0, 0);\n    gil::xyz32f_pixel_t xyz_pixel;\n\n    gil::color_convert(lab_pixel, xyz_pixel);\n\n    TEST_CHECK_CLOSE(static_cast<float>(xyz_pixel[0]), 0.175064f);\n    TEST_CHECK_CLOSE(static_cast<float>(xyz_pixel[1]), 0.184187f);\n    TEST_CHECK_CLOSE(static_cast<float>(xyz_pixel[2]), 0.200548f);\n}\n\nBOOST_AUTO_TEST_CASE(XYZ_to_Lab_Test1)\n{\n    gil::lab32f_pixel_t lab_pixel;\n    gil::xyz32f_pixel_t xyz_pixel(0.085703f, 0.064716f, 0.147082f);\n\n    gil::color_convert(xyz_pixel, lab_pixel);\n\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[0]), 30.572438f);\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[1]), 23.4674f);\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[2]), -22.322275f);\n}\n\nBOOST_AUTO_TEST_CASE(RGB_to_Lab_Test1)\n{\n    gil::rgb32f_pixel_t rgb_pixel(0.75f, 0.5f, 0.25f);\n    gil::lab32f_pixel_t lab_pixel;\n\n    gil::color_convert(rgb_pixel, lab_pixel);\n\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[0]), 58.7767f);\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[1]), 18.5851f);\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[2]), 43.7975f);\n}\n\nBOOST_AUTO_TEST_CASE(RGB_to_Lab_Test2)\n{\n    gil::rgb32f_pixel_t rgb_pixel(1.f, 0.f, 0.f);\n    gil::lab32f_pixel_t lab_pixel;\n\n    gil::color_convert(rgb_pixel, lab_pixel);\n\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[0]), 53.2408f);\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[1]), 80.0925f);\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[2]), 67.2032f);\n}\n\nBOOST_AUTO_TEST_CASE(RGB_to_Lab_Test3)\n{\n    gil::rgb32f_pixel_t rgb_pixel(0.f, 1.f, 0.f);\n    gil::lab32f_pixel_t lab_pixel;\n\n    gil::color_convert(rgb_pixel, lab_pixel);\n\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[0]), 87.7347f);\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[1]), -86.1827f);\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[2]), 83.1793f);\n}\n\nBOOST_AUTO_TEST_CASE(RGB_to_Lab_Test4)\n{\n    gil::rgb32f_pixel_t rgb_pixel(0.f, 0.f, 1.f);\n    gil::lab32f_pixel_t lab_pixel;\n\n    gil::color_convert(rgb_pixel, lab_pixel);\n\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[0]), 32.2970f);\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[1]), 79.1875f);\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[2]), -107.8602f);\n}\n\nBOOST_AUTO_TEST_CASE(RGB_to_Lab_Test5)\n{\n    gil::rgb32f_pixel_t rgb_pixel(1.f, 1.f, 1.f);\n    gil::lab32f_pixel_t lab_pixel;\n\n    gil::color_convert(rgb_pixel, lab_pixel);\n\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[0]), 100.f);\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[1]), 0.f);\n    TEST_CHECK_CLOSE(static_cast<float>(lab_pixel[2]), 0.f);\n}\n\nBOOST_AUTO_TEST_CASE(Lab_to_RGB_Test1)\n{\n    gil::lab32f_pixel_t lab_pixel(75.f, 20.f, 40.f);\n    gil::rgb32f_pixel_t rgb_pixel;\n\n    gil::color_convert(lab_pixel, rgb_pixel);\n\n    TEST_CHECK_CLOSE(static_cast<float>(rgb_pixel[0]), 0.943240f);\n    TEST_CHECK_CLOSE(static_cast<float>(rgb_pixel[1]), 0.663990f);\n    TEST_CHECK_CLOSE(static_cast<float>(rgb_pixel[2]), 0.437893f);\n}\n\nBOOST_AUTO_TEST_CASE(Lab_to_RGB_Test2)\n{\n    gil::lab32f_pixel_t lab_pixel(100.f, 0.f, 0.f);\n    gil::rgb32f_pixel_t rgb_pixel;\n\n    gil::color_convert(lab_pixel, rgb_pixel);\n\n    TEST_CHECK_CLOSE(static_cast<float>(rgb_pixel[0]), 1.f);\n    TEST_CHECK_CLOSE(static_cast<float>(rgb_pixel[1]), 1.f);\n    TEST_CHECK_CLOSE(static_cast<float>(rgb_pixel[2]), 1.f);\n}\n\nBOOST_AUTO_TEST_CASE(Lab_to_RGB_Test3)\n{\n    gil::lab32f_pixel_t lab_pixel(56.8140f, -42.3665f, 10.6728f);\n    gil::rgb32f_pixel_t rgb_pixel;\n\n    gil::color_convert(lab_pixel, rgb_pixel);\n\n    TEST_CHECK_CLOSE(static_cast<float>(rgb_pixel[0]), 0.099999f);\n    TEST_CHECK_CLOSE(static_cast<float>(rgb_pixel[1]), 0.605568f);\n    TEST_CHECK_CLOSE(static_cast<float>(rgb_pixel[2]), 0.456662f);\n}\n\nBOOST_AUTO_TEST_CASE(Lab_to_RGB_Test4)\n{\n    gil::lab32f_pixel_t lab_pixel(50.5874f, 4.0347f, 50.5456f);\n    gil::rgb32f_pixel_t rgb_pixel;\n\n    gil::color_convert(lab_pixel, rgb_pixel);\n\n    TEST_CHECK_CLOSE(static_cast<float>(rgb_pixel[0]), 0.582705f);\n    TEST_CHECK_CLOSE(static_cast<float>(rgb_pixel[1]), 0.454891f);\n    TEST_CHECK_CLOSE(static_cast<float>(rgb_pixel[2]), 0.1f);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4f1d6329abb884e5f8a4a934774d1defb6947e6e", "size": 5196, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/gil/toolbox/test/lab_test.cpp", "max_stars_repo_name": "smart-make/boost", "max_stars_repo_head_hexsha": "46509a094f8a844eefd5bb8a0030b739a04d79e1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:55:56.000Z", "max_issues_repo_path": "libs/gil/toolbox/test/lab_test.cpp", "max_issues_repo_name": "smart-make/boost", "max_issues_repo_head_hexsha": "46509a094f8a844eefd5bb8a0030b739a04d79e1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/gil/toolbox/test/lab_test.cpp", "max_forks_repo_name": "smart-make/boost", "max_forks_repo_head_hexsha": "46509a094f8a844eefd5bb8a0030b739a04d79e1", "max_forks_repo_licenses": ["BSL-1.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.9285714286, "max_line_length": 70, "alphanum_fraction": 0.7403772132, "num_tokens": 1642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721303, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.568636799673826}}
{"text": "#include \"global.hpp\"\n#include \"util.hpp\"\n#include \"test_helpers.hpp\"\n\n#define BOOST_TEST_MODULE common_test\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(global_test)\n\nBOOST_AUTO_TEST_CASE(pi_test)\n{\n    BOOST_CHECK_SMALL( std::sin(pi), 1e-15);\n    BOOST_CHECK_EQUAL( std::sin(pi / 2), 1.0 );\n    BOOST_CHECK_EQUAL( std::cos(pi), -1.0 );\n}\n\nBOOST_AUTO_TEST_CASE(pow_int_test)\n{\n    BOOST_CHECK_EQUAL( pow_int(10, 5), 100000 );\n    BOOST_CHECK_EQUAL( pow_int(2u, 30), 1u<<30 );\n\n    /// test overflow protection\n    BOOST_CHECK_THROW( pow_int(-1u, 3), std::overflow_error);\n}\n\nBOOST_AUTO_TEST_CASE( scale_vector_test )\n{\n    std::vector<double> test= {1, 4, 3, 6, 3, 6};\n    scaleVectorBy(test, 2.0);\n\n    BOOST_CHECK_EQUAL(test[0], 2);\n    BOOST_CHECK_EQUAL(test[1], 4*2);\n    BOOST_CHECK_EQUAL(test[5], 6*2);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "fc44066ac3e05e9c775f7b74d605bc0ab0284921", "size": 856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/test/global_test.cpp", "max_stars_repo_name": "ngc92/branchedflowsim", "max_stars_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/test/global_test.cpp", "max_issues_repo_name": "ngc92/branchedflowsim", "max_issues_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/test/global_test.cpp", "max_forks_repo_name": "ngc92/branchedflowsim", "max_forks_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5263157895, "max_line_length": 61, "alphanum_fraction": 0.6974299065, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.5686367913479634}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix2d a, b, c; a << 1,2,3,4; b << 5,6,7,8;\nc.noalias() = a * b; // this computes the product directly to c\ncout << c << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "5e6deb0ebdee4f68b18879bf947012e465f09f67", "size": 613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_MatrixBase_noalias.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_MatrixBase_noalias.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_MatrixBase_noalias.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 25.5416666667, "max_line_length": 224, "alphanum_fraction": 0.6623164763, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5686367830221004}}
{"text": "// Copyright John Maddock 2006.\n// Copyright Paul A. Bristow 2007, 2009\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifdef _MSC_VER\n#  pragma warning(disable : 4127) // conditional expression is constant\n#  pragma warning(disable : 4512) // assignment operator could not be generated\n#  pragma warning(disable : 4756) // overflow in constant arithmetic\n// Constants are too big for float case, but this doesn't matter for test.\n#endif\n\n#include <boost/math/concepts/real_concept.hpp>\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/array.hpp>\n#include \"functor.hpp\"\n\n#include \"handle_test_result.hpp\"\n#include \"table_type.hpp\"\n\n#ifndef SC_\n#define SC_(x) static_cast<typename table_type<T>::type>(BOOST_JOIN(x, L))\n#endif\n\ntemplate <class Real, class T>\nvoid do_test_hermite(const T& data, const char* type_name, const char* test_name)\n{\n#if !(defined(ERROR_REPORTING_MODE) && !defined(HERMITE_FUNCTION_TO_TEST))\n   typedef Real                   value_type;\n\n   typedef value_type (*pg)(unsigned, value_type);\n#ifdef HERMITE_FUNCTION_TO_TEST\n   pg funcp = HERMITE_FUNCTION_TO_TEST;\n#elif defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::hermite<value_type>;\n#else\n   pg funcp = boost::math::hermite;\n#endif\n\n   boost::math::tools::test_result<value_type> result;\n\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n\n   //\n   // test hermite against data:\n   //\n   result = boost::math::tools::test_hetero<Real>(\n      data, \n      bind_func_int1<Real>(funcp, 0, 1), \n      extract_result<Real>(2));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"hermite\", test_name);\n\n   std::cout << std::endl;\n#endif\n}\n\ntemplate <class T>\nvoid test_hermite(T, const char* name)\n{\n   //\n   // The actual test data is rather verbose, so it's in a separate file\n   //\n   // The contents are as follows, each row of data contains\n   // three items, input value a, input value b and erf(a, b):\n   // \n#  include \"hermite.ipp\"\n\n   do_test_hermite<T>(hermite, name, \"Hermite Polynomials\");\n}\n\ntemplate <class T>\nvoid test_spots(T, const char* t)\n{\n   std::cout << \"Testing basic sanity checks for type \" << t << std::endl;\n   //\n   // basic sanity checks, tolerance is 100 epsilon:\n   // These spots were generated by MathCAD, precision is \n   // 14-16 digits.\n   //\n   T tolerance = (std::max)(boost::math::tools::epsilon<T>() * 100, static_cast<T>(1e-14));\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(0, static_cast<T>(1)), static_cast<T>(1.L), tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(1)), static_cast<T>(2.L), tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(2)), static_cast<T>(4.L), tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(10)), static_cast<T>(20), tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(100)), static_cast<T>(200), tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(1e6)), static_cast<T>(2e6), tolerance);\n   if(std::numeric_limits<T>::max_exponent >= std::numeric_limits<double>::max_exponent)\n   {\n      BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(1e307)), static_cast<T>(2e307), tolerance);\n      BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(99, static_cast<T>(100)), static_cast<T>(4.967223743011310E+227L), tolerance);\n   }\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(10, static_cast<T>(30)), static_cast<T>(5.896624628001300E+17L), tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(10, static_cast<T>(1000)), static_cast<T>(1.023976960161280E+33L), tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(10, static_cast<T>(10)), static_cast<T>(8.093278209760000E+12L), tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(10, static_cast<T>(-10)), static_cast<T>(8.093278209760000E+12L), tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(3, static_cast<T>(-10)), static_cast<T>(-7.880000000000000E+3L), tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(3, static_cast<T>(-1000)), static_cast<T>(-7.999988000000000E+9L), tolerance);\n   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(3, static_cast<T>(-1000000)), static_cast<T>(-7.999999999988000E+18L), tolerance);\n}\n\n", "meta": {"hexsha": "a724b7e63ff38dff5c91cb99bdc4a05ff6f6a6cf", "size": 4762, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/test/test_hermite.hpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/math/test/test_hermite.hpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/math/test/test_hermite.hpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 44.5046728972, "max_line_length": 135, "alphanum_fraction": 0.7091558169, "num_tokens": 1334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.5686367708761705}}
{"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": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2017, 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#include \"andreasenhugevolatilityinterpl.hpp\"\n#include \"utilities.hpp\"\n\n#include <ql/math/comparison.hpp>\n#include <ql/math/functional.hpp>\n#include <ql/math/interpolations/sabrinterpolation.hpp>\n#include <ql/math/optimization/bfgs.hpp>\n#include <ql/math/optimization/simplex.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/instruments/vanillaoption.hpp>\n#include <ql/instruments/barrieroption.hpp>\n#include <ql/time/daycounters/actual365fixed.hpp>\n#include <ql/models/equity/hestonmodel.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/processes/blackscholesprocess.hpp>\n#include <ql/pricingengines/vanilla/analytichestonengine.hpp>\n#include <ql/pricingengines/vanilla/fdblackscholesvanillaengine.hpp>\n#include <ql/pricingengines/barrier/fdblackscholesbarrierengine.hpp>\n#include <ql/termstructures/yield/zerocurve.hpp>\n#include <ql/termstructures/volatility/equityfx/hestonblackvolsurface.hpp>\n#include <ql/termstructures/volatility/equityfx/andreasenhugelocalvoladapter.hpp>\n#include <ql/termstructures/volatility/equityfx/andreasenhugevolatilityinterpl.hpp>\n#include <ql/termstructures/volatility/equityfx/andreasenhugevolatilityadapter.hpp>\n\n#include <boost/make_shared.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\nnamespace {\n\n    struct CalibrationData {\n        const Handle<Quote> spot;\n        Handle<YieldTermStructure> rTS, qTS;\n        AndreasenHugeVolatilityInterpl::CalibrationSet calibrationSet;\n    };\n\n    struct CalibrationResults {\n        AndreasenHugeVolatilityInterpl::CalibrationType calibrationType;\n        AndreasenHugeVolatilityInterpl::InterpolationType interpolationType;\n\n        Real maxError, avgError;\n        Real lvMaxError, lvAvgError;\n    };\n\n    CalibrationData AndreasenHugeExampleData() {\n        // This is the example market data from the original paper\n        // Andreasen J., Huge B., 2010. Volatility Interpolation\n        // https://ssrn.com/abstract=1694972\n\n        const Handle<Quote> spot(boost::make_shared<SimpleQuote>(2772.7));\n\n        const Time maturityTimes[] = {\n                  0.025, 0.101, 0.197, 0.274, 0.523, 0.772,\n                  1.769, 2.267, 2.784, 3.781, 4.778, 5.774\n            };\n\n        const Real raw[][13] = {\n            { 0.5131, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.3366, 0.3291, 0.0000, 0.0000 },\n            { 0.5864, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.3178, 0.3129, 0.3008, 0.0000 },\n            { 0.6597, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.3019, 0.2976, 0.2975, 0.0000 },\n            { 0.7330, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.2863, 0.2848, 0.2848, 0.0000 },\n            { 0.7697, 0.0000, 0.0000, 0.0000, 0.3262, 0.3079, 0.3001, 0.2843, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 0.8063, 0.0000, 0.0000, 0.0000, 0.3058, 0.2936, 0.2876, 0.2753, 0.2713, 0.2711, 0.2711, 0.2722, 0.2809 },\n            { 0.8430, 0.0000, 0.0000, 0.0000, 0.2887, 0.2798, 0.2750, 0.2666, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 0.8613, 0.3365, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 0.8796, 0.3216, 0.2906, 0.2764, 0.2717, 0.2663, 0.2637, 0.2575, 0.2555, 0.2580, 0.2585, 0.2611, 0.2693 },\n            { 0.8979, 0.3043, 0.2797, 0.2672, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 0.9163, 0.2880, 0.2690, 0.2578, 0.2557, 0.2531, 0.2519, 0.2497, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 0.9346, 0.2724, 0.2590, 0.2489, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 0.9529, 0.2586, 0.2488, 0.2405, 0.2407, 0.2404, 0.2411, 0.2418, 0.2410, 0.2448, 0.2469, 0.2501, 0.2584 },\n            { 0.9712, 0.2466, 0.2390, 0.2329, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 0.9896, 0.2358, 0.2300, 0.2253, 0.2269, 0.2284, 0.2299, 0.2347, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 1.0079, 0.2247, 0.2213, 0.2184, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 1.0262, 0.2159, 0.2140, 0.2123, 0.2142, 0.2173, 0.2198, 0.2283, 0.2275, 0.2322, 0.2384, 0.2392, 0.2486 },\n            { 1.0445, 0.2091, 0.2076, 0.2069, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 1.0629, 0.2056, 0.2024, 0.2025, 0.2039, 0.2074, 0.2104, 0.2213, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 1.0812, 0.2045, 0.1982, 0.1984, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 1.0995, 0.2025, 0.1959, 0.1944, 0.1962, 0.1988, 0.2022, 0.2151, 0.2161, 0.2219, 0.2269, 0.2305, 0.2399 },\n            { 1.1178, 0.1933, 0.1929, 0.1920, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 1.1362, 0.0000, 0.0000, 0.0000, 0.1902, 0.1914, 0.1950, 0.2091, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 1.1728, 0.0000, 0.0000, 0.0000, 0.1885, 0.1854, 0.1888, 0.2039, 0.2058, 0.2122, 0.2186, 0.2223, 0.2321 },\n            { 1.2095, 0.0000, 0.0000, 0.0000, 0.1867, 0.1811, 0.1839, 0.1990, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 },\n            { 1.2461, 0.0000, 0.0000, 0.0000, 0.1871, 0.1785, 0.1793, 0.1945, 0.0000, 0.2054, 0.2103, 0.2164, 0.2251 },\n            { 1.3194, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.1988, 0.2054, 0.2105, 0.2190 },\n            { 1.3927, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.1930, 0.2002, 0.2054, 0.2135 },\n            { 1.4660, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.1849, 0.1964, 0.2012, 0.0000 }\n        };\n\n        const DayCounter dc = Actual365Fixed();\n        const Date today = Date(1, March, 2010);\n\n        const Handle<YieldTermStructure> rTS(flatRate(today, 0.0, dc));\n        const Handle<YieldTermStructure> qTS(flatRate(today, 0.0, dc));\n\n        const Size nStrikes = LENGTH(raw);\n        const Size nMaturities = LENGTH(maturityTimes);\n\n        QL_REQUIRE(nMaturities == LENGTH(raw[1])-1, \"check raw data\");\n\n        AndreasenHugeVolatilityInterpl::CalibrationSet calibrationSet;\n\n        calibrationSet.reserve(std::count_if(\n            &raw[0][0], &raw[nStrikes-1][nMaturities]+1,\n            std::bind2nd(std::not_equal_to<Real>(), 0.0)) - nStrikes);\n\n        for (Size i=0; i < LENGTH(raw); ++i) {\n            const Real strike = spot->value()*raw[i][0];\n\n            for (Size j=1; j < LENGTH(raw[i]); ++j)\n                if (raw[i][j] > QL_EPSILON) {\n                    const Date maturity\n                        = today + Period(Size(365*maturityTimes[j-1]), Days);\n\n                    const Volatility impliedVol = raw[i][j];\n\n                    calibrationSet.push_back(std::make_pair(\n                        boost::make_shared<VanillaOption>(\n                            boost::make_shared<PlainVanillaPayoff>(\n                                (strike < spot->value())? Option::Put\n                                                        : Option::Call,\n                                strike),\n                            boost::make_shared<EuropeanExercise>(maturity)),\n                        boost::make_shared<SimpleQuote>(impliedVol))\n                    );\n                }\n        }\n\n        const CalibrationData data = { spot, rTS, qTS, calibrationSet};\n\n        return data;\n    }\n\n    void testAndreasenHugeVolatilityInterpolation(\n        const CalibrationData& data, const CalibrationResults& expected) {\n\n        SavedSettings backup;\n\n        const Handle<YieldTermStructure> rTS = data.rTS;\n        const Handle<YieldTermStructure> qTS = data.qTS;\n\n        const DayCounter dc = rTS->dayCounter();\n        const Date today = rTS->referenceDate();\n        Settings::instance().evaluationDate() = today;\n\n        const Handle<Quote> spot = data.spot;\n\n        AndreasenHugeVolatilityInterpl::CalibrationSet calibrationSet =\n            data.calibrationSet;\n\n        const boost::shared_ptr<AndreasenHugeVolatilityInterpl>\n            andreasenHugeVolInterplation(\n                boost::make_shared<AndreasenHugeVolatilityInterpl>(\n                    calibrationSet, spot, rTS, qTS,\n                    expected.interpolationType,\n                    expected.calibrationType));\n\n        const boost::tuple<Real, Real, Real> error =\n            andreasenHugeVolInterplation->calibrationError();\n\n        const Real maxError = error.get<1>();\n        const Real avgError = error.get<2>();\n\n        if (maxError > expected.maxError || avgError > expected.avgError) {\n            BOOST_FAIL(\"Failed to reproduce calibration error\"\n                       << \"\\n    max calibration error:     \" << maxError\n                       << \"\\n    average calibration error: \" << avgError\n                       << \"\\n    expected max error:        \" << expected.maxError\n                       << \"\\n    expected average error:    \" << expected.avgError);\n        }\n\n        const boost::shared_ptr<AndreasenHugeVolatilityAdapter> volatilityAdapter(\n            boost::make_shared<AndreasenHugeVolatilityAdapter>(\n                andreasenHugeVolInterplation));\n\n        const boost::shared_ptr<AndreasenHugeLocalVolAdapter> localVolAdapter(\n            boost::make_shared<AndreasenHugeLocalVolAdapter>(\n                andreasenHugeVolInterplation));\n\n        const boost::shared_ptr<GeneralizedBlackScholesProcess> localVolProcess(\n            boost::make_shared<GeneralizedBlackScholesProcess>(\n                spot, qTS, rTS,\n                Handle<BlackVolTermStructure>(volatilityAdapter),\n                Handle<LocalVolTermStructure>(localVolAdapter)));\n\n        Real lvAvgError = 0.0, lvMaxError = 0.0;\n        for (Size i=0, n=0; i < calibrationSet.size(); ++i) {\n\n            const boost::shared_ptr<VanillaOption> option =\n                calibrationSet[i].first;\n\n            const boost::shared_ptr<PlainVanillaPayoff> payoff =\n                boost::dynamic_pointer_cast<PlainVanillaPayoff>(\n                    option->payoff());\n            const Real strike = payoff->strike();\n            const Option::Type optionType = payoff->optionType();\n\n            const Time t = dc.yearFraction(today, option->exercise()->lastDate());\n\n            const Volatility expectedVol = calibrationSet[i].second->value();\n            const Volatility calculatedVol =\n                volatilityAdapter->blackVol(t, strike, true);\n\n            const Real diffVol = std::fabs(expectedVol - calculatedVol);\n            const Real tol = std::max(1e-10, 1.01*maxError);\n\n            if (diffVol > tol) {\n                BOOST_FAIL(\"Failed to reproduce calibration option price\"\n                           << \"\\n    calculated: \" << calculatedVol\n                           << \"\\n    expected:   \" << expectedVol\n                           << \"\\n    difference: \" << diffVol\n                           << \"\\n    tolerance:  \" << tol);\n            }\n\n            const boost::shared_ptr<PricingEngine> fdEngine(\n                boost::make_shared<FdBlackScholesVanillaEngine>(\n                    localVolProcess, std::max<Size>(30, Size(100*t)),\n                    200, 0, FdmSchemeDesc::Douglas(), true));\n\n            option->setPricingEngine(fdEngine);\n\n            const DiscountFactor discount = rTS->discount(t);\n            const Real fwd = spot->value()*qTS->discount(t)/discount;\n\n            const Volatility lvImpliedVol = blackFormulaImpliedStdDevLiRS(\n                optionType, strike, fwd, option->NPV(),\n                discount, 0.0, Null<Real>(), 1.0, 1e-12)/std::sqrt(t);\n\n            const Real lvError = std::fabs(lvImpliedVol - expectedVol);\n\n            lvMaxError = std::max(lvError, lvMaxError);\n\n            lvAvgError = (n*lvAvgError + lvError)/(n+1);\n\n            ++n;\n        }\n\n        if (lvMaxError > expected.lvMaxError || avgError > expected.lvAvgError) {\n            BOOST_FAIL(\"Failed to reproduce local volatility calibration error\"\n                       << \"\\n    max calibration error:     \" << lvMaxError\n                       << \"\\n    average calibration error: \" << lvAvgError\n                       << \"\\n    expected max error:        \" << expected.lvMaxError\n                       << \"\\n    expected average error:    \" << expected.lvAvgError);\n        }\n    }\n\n\n    CalibrationData BorovkovaExampleData() {\n        // see Svetlana Borovkova, Ferry J. Permana\n        // Implied volatility in oil markets\n        // http://www.researchgate.net/publication/46493859_Implied_volatility_in_oil_markets\n\n        const DayCounter dc = Actual365Fixed();\n        const Date today = Date(4, January, 2018);\n\n        const Handle<YieldTermStructure> rTS(flatRate(today, 0.025, dc));\n        const Handle<YieldTermStructure> qTS(flatRate(today, 0.085, dc));\n\n        Handle<Quote> spot(boost::make_shared<SimpleQuote>(100));\n\n        const Real b1 = 0.35;\n        const Real b2 = 0.03;\n        const Real b3 = 0.005;\n        const Real b4 = -0.02;\n        const Real b5 = -0.005;\n\n        const Real strikes[] = { 35, 50, 75, 100, 125, 150, 200, 300 };\n        const Size maturityMonths[] = { 1, 3, 6, 9, 12, 15, 18, 24};\n\n        AndreasenHugeVolatilityInterpl::CalibrationSet calibrationSet;\n\n        for (Size i=0; i < LENGTH(strikes); ++i) {\n            const Real strike = strikes[i];\n\n            for (Size j=0; j < LENGTH(maturityMonths); ++j) {\n                const Date maturityDate = today +\n                    Period(maturityMonths[j], Months);\n                const Time t = dc.yearFraction(today, maturityDate);\n\n                const Real fwd = spot->value()*qTS->discount(t)/rTS->discount(t);\n                const Real mn = std::log(fwd/strike)/std::sqrt(t);\n\n                const Volatility vol = b1 + b2*mn + b3*mn*mn + b4*t + b5*mn*t;\n\n                if (std::fabs(mn) < 3.71*vol) {\n\n                    calibrationSet.push_back(std::make_pair(\n                        boost::make_shared<VanillaOption>(\n                            boost::make_shared<PlainVanillaPayoff>(\n                                Option::Call, strike),\n                            boost::make_shared<EuropeanExercise>(maturityDate)),\n                        boost::make_shared<SimpleQuote>(vol)));\n                }\n            }\n        }\n\n        const CalibrationData data = { spot, rTS, qTS, calibrationSet};\n\n        return data;\n    }\n\n\n    CalibrationData arbitrageData() {\n\n        const DayCounter dc = Actual365Fixed();\n        const Date today = Date(4, January, 2018);\n\n        const Handle<YieldTermStructure> rTS(flatRate(today, 0.13, dc));\n        const Handle<YieldTermStructure> qTS(flatRate(today, 0.03, dc));\n\n        Handle<Quote> spot(boost::make_shared<SimpleQuote>(100));\n\n        const Real strikes[] = { 100, 100, 100, 150 };\n        const Size maturities[] = { 1, 3, 6, 6 };\n        const Volatility vols[] = { 0.25, 0.35, 0.05, 0.35 };\n        AndreasenHugeVolatilityInterpl::CalibrationSet calibrationSet;\n\n        for (Size i=0; i < LENGTH(strikes); ++i) {\n            const Real strike = strikes[i];\n            const Date maturityDate = today + Period(maturities[i], Months);\n            const Volatility vol = vols[i];\n\n            calibrationSet.push_back(std::make_pair(\n                boost::make_shared<VanillaOption>(\n                    boost::make_shared<PlainVanillaPayoff>(\n                        Option::Call, strike),\n                    boost::make_shared<EuropeanExercise>(maturityDate)),\n                boost::make_shared<SimpleQuote>(vol)));\n        }\n\n        const CalibrationData data = { spot, rTS, qTS, calibrationSet};\n\n        return data;\n    }\n}\n\n\nvoid AndreasenHugeVolatilityInterplTest::testAndreasenHugePut() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing Andreasen-Huge example with Put calibration...\");\n\n    const CalibrationData data = AndreasenHugeExampleData();\n\n    const CalibrationResults expected = {\n        AndreasenHugeVolatilityInterpl::Put,\n        AndreasenHugeVolatilityInterpl::CubicSpline,\n        0.0015, 0.00035,\n        0.0020, 0.00035\n    };\n\n    testAndreasenHugeVolatilityInterpolation(data, expected);\n}\n\nvoid AndreasenHugeVolatilityInterplTest::testAndreasenHugeCall() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing Andreasen-Huge example with Call calibration...\");\n\n    const CalibrationData data = AndreasenHugeExampleData();\n\n    const CalibrationResults expected = {\n        AndreasenHugeVolatilityInterpl::Call,\n        AndreasenHugeVolatilityInterpl::CubicSpline,\n        0.0015, 0.00035,\n        0.0015, 0.00035\n    };\n\n    testAndreasenHugeVolatilityInterpolation(data, expected);\n}\n\nvoid AndreasenHugeVolatilityInterplTest::testAndreasenHugeCallPut() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing Andreasen-Huge example with instantaneous \"\n         \"Call and Put calibration...\");\n\n    const CalibrationData data = AndreasenHugeExampleData();\n\n    const CalibrationResults expected = {\n        AndreasenHugeVolatilityInterpl::CallPut,\n        AndreasenHugeVolatilityInterpl::CubicSpline,\n        0.0015, 0.00035,\n        0.0015, 0.00035\n    };\n\n    testAndreasenHugeVolatilityInterpolation(data, expected);\n}\n\nvoid AndreasenHugeVolatilityInterplTest::testLinearInterpolation() {\n    BOOST_TEST_MESSAGE(\n        \"Testing Andreasen-Huge example with linear interpolation...\");\n\n    const CalibrationData data = AndreasenHugeExampleData();\n\n    const CalibrationResults expected = {\n        AndreasenHugeVolatilityInterpl::CallPut,\n        AndreasenHugeVolatilityInterpl::Linear,\n        0.0020, 0.00015,\n        0.0040, 0.00035\n    };\n\n    testAndreasenHugeVolatilityInterpolation(data, expected);\n}\n\nvoid AndreasenHugeVolatilityInterplTest::testPiecewiseConstantInterpolation() {\n    BOOST_TEST_MESSAGE(\n        \"Testing Andreasen-Huge example with piecewise constant interpolation...\");\n\n    const CalibrationData data = AndreasenHugeExampleData();\n\n    const CalibrationResults expected = {\n        AndreasenHugeVolatilityInterpl::CallPut,\n        AndreasenHugeVolatilityInterpl::PiecewiseConstant,\n        0.0025, 0.00025,\n        0.0040, 0.00035\n    };\n\n    testAndreasenHugeVolatilityInterpolation(data, expected);\n}\n\nvoid AndreasenHugeVolatilityInterplTest::testTimeDependentInterestRates() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing Andreasen-Huge volatility interpolation with \"\n        \"time dependent interest rates and dividend yield...\");\n\n    SavedSettings backup;\n\n    const CalibrationData data = AndreasenHugeExampleData();\n\n    const DayCounter dc = data.rTS->dayCounter();\n    const Date today = data.rTS->referenceDate();\n    Settings::instance().evaluationDate() = today;\n\n    using namespace boost::assign;\n    std::vector<Real> r, q;\n    r += 0.0167, 0.023, 0.03234, 0.034, 0.038, 0.042, 0.047, 0.053;\n    q += 0.01, 0.011, 0.013, 0.014, 0.02, 0.025, 0.067, 0.072;\n\n    std::vector<Date> dates;\n    dates += today,                     today + Period(41, Days),\n             today + Period(75, Days),  today + Period(165, Days),\n             today + Period(256, Days), today + Period(345, Days),\n             today + Period(524, Days), today + Period(2190, Days);\n\n    const Handle<YieldTermStructure> rTS(\n        boost::make_shared<ZeroCurve>(dates, r, dc));\n    const Handle<YieldTermStructure> qTS(\n        boost::make_shared<ZeroCurve>(dates, q, dc));\n\n    const CalibrationData origData = AndreasenHugeExampleData();\n    AndreasenHugeVolatilityInterpl::CalibrationSet calibrationSet =\n        origData.calibrationSet;\n\n    const Handle<Quote> spot = origData.spot;\n\n    const boost::shared_ptr<HestonModel> hestonModel(\n        boost::make_shared<HestonModel>(\n            boost::make_shared<HestonProcess>(\n                rTS, qTS, spot, 0.09, 2.0, 0.09, 0.4, -0.75)));\n\n    const boost::shared_ptr<PricingEngine> hestonEngine(\n        boost::make_shared<AnalyticHestonEngine>(\n            hestonModel,\n            AnalyticHestonEngine::AndersenPiterbarg,\n            AnalyticHestonEngine::Integration::discreteTrapezoid(128)));\n\n    for (Size i=0; i < calibrationSet.size(); ++i) {\n        const boost::shared_ptr<VanillaOption> option =\n            calibrationSet[i].first;\n\n        const boost::shared_ptr<PlainVanillaPayoff> payoff =\n            boost::dynamic_pointer_cast<PlainVanillaPayoff>(option->payoff());\n\n        const Real strike = payoff->strike();\n        const Option::Type optionType = payoff->optionType();\n\n        const Time t = dc.yearFraction(today, option->exercise()->lastDate());\n\n        const DiscountFactor discount = rTS->discount(t);\n        const Real fwd = spot->value()*qTS->discount(t)/discount;\n\n        option->setPricingEngine(hestonEngine);\n        const Real npv = option->NPV();\n\n        const Volatility impliedVol = blackFormulaImpliedStdDevLiRS(\n            optionType, strike, fwd, npv,\n            discount, 0.0, Null<Real>(), 1.0, 1e-12)/std::sqrt(t);\n\n        calibrationSet[i].second = boost::make_shared<SimpleQuote>(impliedVol);\n    }\n\n    CalibrationData irData = { spot, rTS, qTS, calibrationSet };\n\n    const CalibrationResults expected = {\n        AndreasenHugeVolatilityInterpl::CallPut,\n        AndreasenHugeVolatilityInterpl::CubicSpline,\n        0.0020, 0.0003,\n        0.0020, 0.0004\n    };\n\n    testAndreasenHugeVolatilityInterpolation(irData, expected);\n}\n\nvoid AndreasenHugeVolatilityInterplTest::testSingleOptionCalibration() {\n    BOOST_TEST_MESSAGE(\n        \"Testing Andreasen-Huge volatility interpolation with \"\n        \"a single option...\");\n\n    SavedSettings backup;\n\n    const DayCounter dc = Actual365Fixed();\n    const Date today = Date(4, January, 2018);\n\n    const Handle<YieldTermStructure> rTS(flatRate(today, 0.025, dc));\n    const Handle<YieldTermStructure> qTS(flatRate(today, 0.085, dc));\n\n    AndreasenHugeVolatilityInterpl::CalibrationSet calibrationSet;\n\n    const Real strike = 10.0;\n    const Volatility vol = 0.3;\n    const Date maturity = today + Period(1, Years);\n    Handle<Quote> spot(boost::make_shared<SimpleQuote>(strike));\n\n    calibrationSet.push_back(std::make_pair(\n        boost::make_shared<VanillaOption>(\n            boost::make_shared<PlainVanillaPayoff>(Option::Call, strike),\n            boost::make_shared<EuropeanExercise>(maturity)),\n        boost::make_shared<SimpleQuote>(vol)));\n\n    const AndreasenHugeVolatilityInterpl::InterpolationType interpl[] = {\n        AndreasenHugeVolatilityInterpl::Linear,\n        AndreasenHugeVolatilityInterpl::CubicSpline,\n        AndreasenHugeVolatilityInterpl::PiecewiseConstant\n    };\n\n    const AndreasenHugeVolatilityInterpl::CalibrationType calibrationType[] = {\n        AndreasenHugeVolatilityInterpl::Put,\n        AndreasenHugeVolatilityInterpl::Call,\n        AndreasenHugeVolatilityInterpl::CallPut\n    };\n\n    for (Size i=0; i < LENGTH(interpl); ++i)\n        for (Size j=0; j < LENGTH(calibrationType); ++j) {\n            const boost::shared_ptr<AndreasenHugeVolatilityInterpl>\n                andreasenHugeVolInterplation(\n                    boost::make_shared<AndreasenHugeVolatilityInterpl>(\n                        calibrationSet, spot, rTS, qTS,\n                        interpl[i], calibrationType[j], 50));\n\n            const boost::shared_ptr<AndreasenHugeVolatilityAdapter>\n                volatilityAdapter =\n                    boost::make_shared<AndreasenHugeVolatilityAdapter>(\n                        andreasenHugeVolInterplation);\n\n            const Volatility calculated =\n                volatilityAdapter->blackVol(maturity, strike);\n            const Volatility expected = vol;\n\n            if (std::fabs(calculated - expected) > 1e-4) {\n                BOOST_FAIL(\"Failed to reproduce single option calibration\"\n                           << \"\\n    calculated: \" << calculated\n                           << \"\\n    expected:   \" << expected);\n            }\n        }\n}\n\nvoid AndreasenHugeVolatilityInterplTest::testArbitrageFree() {\n    BOOST_TEST_MESSAGE(\n        \"Testing Andreasen-Huge volatility interpolation gives \"\n        \"arbitrage free prices...\");\n\n    SavedSettings backup;\n\n    CalibrationData data[] = { BorovkovaExampleData(), arbitrageData() };;\n\n    for (Size i=0; i < LENGTH(data); ++i) {\n        const Handle<Quote>& spot = data[i].spot;\n        const AndreasenHugeVolatilityInterpl::CalibrationSet& calibrationSet =\n            data[i].calibrationSet;\n\n        const Handle<YieldTermStructure>& rTS = data[i].rTS;\n        const Handle<YieldTermStructure>& qTS = data[i].qTS;\n\n        const DayCounter dc = rTS->dayCounter();\n        const Date today = rTS->referenceDate();\n\n        const boost::shared_ptr<AndreasenHugeVolatilityInterpl>\n            andreasenHugeVolInterplation(\n                boost::make_shared<AndreasenHugeVolatilityInterpl>(\n                    calibrationSet, spot, rTS, qTS,\n                    AndreasenHugeVolatilityInterpl::CubicSpline,\n                    AndreasenHugeVolatilityInterpl::CallPut, 5000));\n\n        const boost::shared_ptr<AndreasenHugeVolatilityAdapter> volatilityAdapter(\n            boost::make_shared<AndreasenHugeVolatilityAdapter>(\n                andreasenHugeVolInterplation));\n\n        for (Real m = -0.7; m < 0.7; m+=0.05) {\n\n            for (Size weeks=6; weeks < 52; ++weeks) {\n                const Date maturityDate = today + Period(weeks, Weeks);\n\n                const Time t = dc.yearFraction(today, maturityDate);\n\n                const Real fwd = spot->value()*qTS->discount(t)/rTS->discount(t);\n\n                // J. Gatheral, Arbitrage-free SVI volatility surfaces\n                // http://mfe.baruch.cuny.edu/wp-content/uploads/2013/01/OsakaSVI2012.pdf\n                const Real eps = 0.025;\n                const Real k  = fwd*std::exp(m);\n                const Real km = fwd*std::exp(m - eps);\n                const Real kp = fwd*std::exp(m + eps);\n\n                const Real w =\n                    volatilityAdapter->blackVariance(t, k, true);\n                const Real w_p =\n                    volatilityAdapter->blackVariance(t, kp, true);\n                const Real w_m =\n                    volatilityAdapter->blackVariance(t, km, true);\n\n                const Real w1 = (w_p - w_m)/(2*eps);\n                const Real w2 = (w_p + w_m - 2*w)/(eps*eps);\n\n                const Real g_k = square<Real>()(1-m*w1/(2*w))\n                    - w1*w1/4*(1/w + 0.25) + 0.5*w2;\n\n                if (g_k < 0) {\n                    BOOST_FAIL(\"No-arbitrage condition g_k >= 0 failed\"\n                               << \"\\n    strike:  \" << k\n                               << \"\\n    forward: \" << fwd\n                               << \"\\n    time:    \" << t\n                               << \"\\n    g_k:    \" << g_k);\n                }\n\n                const Real deltaT = 1.0/365.;\n                const Real fwdpt = spot->value()*\n                    qTS->discount(t+deltaT)/rTS->discount(t+deltaT);\n\n                const Real kpt = fwdpt*std::exp(m);\n                const Real w_pt =\n                    volatilityAdapter->blackVariance(t+deltaT, kpt, true);\n\n                const Real w_t = (w_pt - w)/deltaT;\n                if (w_t < -1e-8) {\n                    BOOST_FAIL(\"No-arbitrage condition w_t >= 0 failed\"\n                               << \"\\n    strike:  \" << k\n                               << \"\\n    forward: \" << fwd\n                               << \"\\n    time:    \" << t\n                               << \"\\n    w        \" << w\n                               << \"\\n    w_t:     \" << w_t);\n                }\n            }\n        }\n    }\n}\n\nvoid AndreasenHugeVolatilityInterplTest::testBarrierOptionPricing() {\n    BOOST_TEST_MESSAGE(\n        \"Testing Barrier option pricing with Andreasen-Huge \"\n         \"local volatility surface...\");\n\n    SavedSettings backup;\n\n    const DayCounter dc = Actual365Fixed();\n    const Date today = Date(4, January, 2018);\n\n    const Handle<YieldTermStructure> rTS(flatRate(today, 0.01, dc));\n    const Handle<YieldTermStructure> qTS(flatRate(today, 0.03, dc));\n\n    Handle<Quote> spot(boost::make_shared<SimpleQuote>(100));\n    const boost::shared_ptr<HestonModel> hestonModel(\n        boost::make_shared<HestonModel>(\n            boost::make_shared<HestonProcess>(\n                rTS, qTS, spot, 0.04, 2.0, 0.04, 0.4, -0.75)));\n\n    const boost::shared_ptr<BlackVolTermStructure> hestonVol =\n        boost::make_shared<HestonBlackVolSurface>(\n            Handle<HestonModel>(hestonModel));\n\n    const boost::shared_ptr<GeneralizedBlackScholesProcess>\n        dupireLocalVolProcess =\n            boost::make_shared<GeneralizedBlackScholesProcess>(\n                spot, qTS, rTS, Handle<BlackVolTermStructure>(hestonVol));\n\n    const Real strikes[] = { 25, 50, 75, 90, 100, 110, 125, 150, 200, 400};\n    const Size maturityMonths[] = { 1, 3, 6, 9, 12};\n\n    AndreasenHugeVolatilityInterpl::CalibrationSet calibrationSet;\n\n    for (Size i=0; i < LENGTH(strikes); ++i) {\n        const Real strike = strikes[i];\n\n        for (Size j=0; j < LENGTH(maturityMonths); ++j) {\n            const Date maturityDate = today + Period(maturityMonths[j], Months);\n            const Time t = dc.yearFraction(today, maturityDate);\n\n            const Volatility vol = hestonVol->blackVol(t, strike);\n\n            const Real mn = std::log(spot->value()/strike)/std::sqrt(t);\n\n            if (std::fabs(mn) < 3.07*vol) {\n                calibrationSet.push_back(std::make_pair(\n                    boost::make_shared<VanillaOption>(\n                        boost::make_shared<PlainVanillaPayoff>(\n                            Option::Call, strike),\n                        boost::make_shared<EuropeanExercise>(maturityDate)),\n                    boost::make_shared<SimpleQuote>(vol)));\n            }\n        }\n    }\n\n    const boost::shared_ptr<AndreasenHugeVolatilityInterpl>\n        andreasenHugeVolInterplation(\n            boost::make_shared<AndreasenHugeVolatilityInterpl>(\n                calibrationSet, spot, rTS, qTS));\n\n    const boost::shared_ptr<AndreasenHugeLocalVolAdapter> localVolAdapter(\n        boost::make_shared<AndreasenHugeLocalVolAdapter>(\n            andreasenHugeVolInterplation));\n\n    const boost::shared_ptr<GeneralizedBlackScholesProcess>\n        andreasenHugeLocalVolProcess =\n            boost::make_shared<GeneralizedBlackScholesProcess>(\n                spot, qTS, rTS,\n                Handle<BlackVolTermStructure>(hestonVol),\n                Handle<LocalVolTermStructure>(localVolAdapter));\n\n    const Real strike = 120.0;\n    const Real barrier=  80.0;\n    const Real rebate =   0.0;\n    const Date maturity = today + Period(1, Years);\n    const Barrier::Type barrierType = Barrier::DownOut;\n\n    BarrierOption barrierOption(barrierType, barrier, rebate,\n        boost::make_shared<PlainVanillaPayoff>(Option::Put, strike),\n        boost::make_shared<EuropeanExercise>(maturity));\n\n    barrierOption.setPricingEngine(\n        boost::make_shared<FdBlackScholesBarrierEngine>(\n            dupireLocalVolProcess, 50, 100, 0,\n            FdmSchemeDesc::Douglas(), true, 0.2));\n\n    const Real dupireNPV = barrierOption.NPV();\n\n    barrierOption.setPricingEngine(\n        boost::make_shared<FdBlackScholesBarrierEngine>(\n            andreasenHugeLocalVolProcess, 200, 400, 0,\n            FdmSchemeDesc::Douglas(), true, 0.25));\n\n    const Real andreasenHugeNPV = barrierOption.NPV();\n\n    const Real tol = 0.15;\n    const Real diff = std::fabs(andreasenHugeNPV - dupireNPV);\n\n    if (diff > tol) {\n        BOOST_FAIL(\"failed to reproduce barrier prices with Andreasen-Huge \"\n                \"local volatility surface\"\n                   << \"\\n    Andreasen-Huge price: \" << andreasenHugeNPV\n                   << \"\\n    Dupire formula price: \" << dupireNPV\n                   << \"\\n    diff:                 \" << diff\n                   << \"\\n    tolerance:            \" << tol);\n    }\n}\n\nnamespace {\n    std::pair<CalibrationData, std::vector<Real> > sabrData() {\n\n        const DayCounter dc = Actual365Fixed();\n        const Date today = Date(4, January, 2018);\n\n        const Real alpha = 0.15;\n        const Real beta = 0.8;\n        const Real nu = 0.5;\n        const Real rho = -0.48;\n        const Real forward = 0.03;\n        const Size maturityInYears = 20;\n\n        const Date maturityDate = today + Period(maturityInYears, Years);\n        const Time maturity = dc.yearFraction(today, maturityDate);\n\n        AndreasenHugeVolatilityInterpl::CalibrationSet calibrationSet;\n\n        const Real strikes[] = { 0.02, 0.025, 0.03, 0.035, 0.04, 0.05, 0.06 };\n\n        for (Size i=0; i < LENGTH(strikes); ++i) {\n            const Real strike = strikes[i];\n            const Volatility vol = sabrVolatility(\n               strike, forward, maturity, alpha, beta, nu, rho);\n\n            calibrationSet.push_back(std::make_pair(\n                boost::make_shared<VanillaOption>(\n                    boost::make_shared<PlainVanillaPayoff>(\n                        Option::Call, strike),\n                    boost::make_shared<EuropeanExercise>(maturityDate)),\n                boost::make_shared<SimpleQuote>(vol)));\n        }\n\n        const Handle<YieldTermStructure> rTS(flatRate(today, forward, dc));\n        const Handle<YieldTermStructure> qTS(flatRate(today, forward, dc));\n\n        Handle<Quote> spot(boost::make_shared<SimpleQuote>(forward));\n\n        const CalibrationData data = { spot, rTS, qTS, calibrationSet};\n\n        using namespace boost::assign;\n        std::vector<Real> parameter;\n        parameter += alpha, beta, nu, rho, forward, maturity;\n\n        return std::make_pair(data, parameter);\n    }\n}\n\nvoid AndreasenHugeVolatilityInterplTest::testPeterAndFabiensExample() {\n    BOOST_TEST_MESSAGE(\n        \"Testing Peter's and Fabien's SABR example...\");\n\n    // http://chasethedevil.github.io/post/andreasen-huge-extrapolation/\n\n    SavedSettings backup;\n\n    const std::pair<CalibrationData, std::vector<Real> > sd = sabrData();\n    const CalibrationData& data = sd.first;\n    const std::vector<Real>& parameter = sd.second;\n\n    const boost::shared_ptr<AndreasenHugeVolatilityInterpl>\n        andreasenHugeVolInterplation(\n            boost::make_shared<AndreasenHugeVolatilityInterpl>(\n                data.calibrationSet, data.spot, data.rTS, data.qTS));\n\n    const boost::shared_ptr<AndreasenHugeVolatilityAdapter> volAdapter(\n        boost::make_shared<AndreasenHugeVolatilityAdapter>(\n            andreasenHugeVolInterplation));\n\n    const Real alpha    = parameter[0];\n    const Real beta     = parameter[1];\n    const Real nu       = parameter[2];\n    const Real rho      = parameter[3];\n    const Real forward  = parameter[4];\n    const Time maturity = parameter[5];\n\n    for (Real strike = 0.02; strike < 0.06; strike+=0.001) {\n        const Volatility sabrVol = sabrVolatility(\n           strike, forward, maturity, alpha, beta, nu, rho);\n\n        const Volatility ahVol = volAdapter->blackVol(maturity, strike, true);\n\n        const Real tol = 0.0005;\n        const Real diff = std::fabs(sabrVol - ahVol);\n\n        if (boost::math::isnan(ahVol) || diff > 0.005) {\n            BOOST_FAIL(\"failed to reproduce SABR volatility with \"\n                    \"Andreasen-Huge interpolation\"\n                   << \"\\n    Andreasen-Huge vol: \" << ahVol\n                   << \"\\n    SABR volatility:    \" << sabrVol\n                   << \"\\n    diff:               \" << diff\n                   << \"\\n    tolerance:          \" << tol);\n        }\n    }\n}\n\nvoid AndreasenHugeVolatilityInterplTest::testDifferentOptimizers() {\n    BOOST_TEST_MESSAGE(\n        \"Testing different optimizer for Andreasen-Huge \"\n        \"volatility interpolation...\");\n\n    const CalibrationData& data = sabrData().first;\n\n    const boost::shared_ptr<OptimizationMethod> optimizationMethods[] = {\n        boost::make_shared<LevenbergMarquardt>(),\n        boost::make_shared<BFGS>(),\n        boost::make_shared<Simplex>(0.2)\n    };\n\n    for (Size i=0; i < LENGTH(optimizationMethods); ++i) {\n        const boost::shared_ptr<OptimizationMethod> optimizationMethod =\n            optimizationMethods[i];\n\n        const Real avgError = AndreasenHugeVolatilityInterpl(\n            data.calibrationSet,\n            data.spot,\n            data.rTS, data.qTS,\n            AndreasenHugeVolatilityInterpl::CubicSpline,\n            AndreasenHugeVolatilityInterpl::Call,\n            400,\n            Null<Real>(), Null<Real>(),\n            optimizationMethod).calibrationError().get<2>();\n\n        if (boost::math::isnan(avgError) || avgError > 0.0001) {\n            BOOST_FAIL(\"failed to calibrate Andreasen-Huge \"\n                    \"volatility interpolation with different optimizera\"\n                   << \"\\n    calibration error: \" << avgError);\n        }\n    }\n}\n\nvoid AndreasenHugeVolatilityInterplTest::testMovingReferenceDate() {\n    BOOST_TEST_MESSAGE(\n        \"Testing that reference date of adapter surface moves along with \"\n        \"evaluation date...\");\n\n    SavedSettings backup;\n\n    const Date today = Date(4, January, 2018);\n    Settings::instance().evaluationDate() = today;\n\n    const DayCounter dc = Actual365Fixed();\n    const Date maturity = today + Period(1, Months);\n\n    Handle<YieldTermStructure> ts(flatRate(0.04, dc));\n\n    const Real s0 = 100.0;\n    const Volatility impliedVol = 0.2;\n    const Handle<Quote> spot(boost::make_shared<SimpleQuote>(s0));\n\n    AndreasenHugeVolatilityInterpl::CalibrationSet calibrationSet(\n        1,\n        std::make_pair(\n            boost::make_shared<VanillaOption>(\n                boost::make_shared<PlainVanillaPayoff>(Option::Call, s0),\n                boost::make_shared<EuropeanExercise>(maturity)),\n            boost::make_shared<SimpleQuote>(impliedVol))\n    );\n\n    const boost::shared_ptr<AndreasenHugeVolatilityInterpl>\n        andreasenHugeVolInterplation(\n            boost::make_shared<AndreasenHugeVolatilityInterpl>(\n                calibrationSet, spot, ts, ts));\n\n\n    const Real tol = 1e-8;\n    const boost::shared_ptr<AndreasenHugeVolatilityAdapter> volatilityAdapter(\n        boost::make_shared<AndreasenHugeVolatilityAdapter>(\n            andreasenHugeVolInterplation, tol));\n\n    const boost::shared_ptr<AndreasenHugeLocalVolAdapter> localVolAdapter(\n        boost::make_shared<AndreasenHugeLocalVolAdapter>(\n            andreasenHugeVolInterplation));\n\n    const Date volRefDate = volatilityAdapter->referenceDate();\n    const Date localRefDate = localVolAdapter->referenceDate();\n\n    if (volRefDate != today || localRefDate != today)\n        BOOST_FAIL(\"reference dates should match today's date\"\n               << \"\\n    today                     : \" << today\n               << \"\\n    local vol reference date  : \" << localRefDate\n               << \"\\n    implied vol reference date: \" << volRefDate);\n\n    const Date modToday = Date(15, January, 2018);\n    Settings::instance().evaluationDate() = modToday;\n\n    const Date modVolRefDate = volatilityAdapter->referenceDate();\n    const Date modLocalRefDate = localVolAdapter->referenceDate();\n\n    if (modVolRefDate != modToday || modLocalRefDate != modToday)\n        BOOST_FAIL(\"reference dates should match modified today's date\"\n               << \"\\n    today                     : \" << modToday\n               << \"\\n    local vol reference date  : \" << modLocalRefDate\n               << \"\\n    implied vol reference date: \" << modVolRefDate);\n\n    // test update method\n    const Volatility modImpliedVol =\n        volatilityAdapter->blackVol(maturity, s0, true);\n\n    const Real diff = std::fabs(modImpliedVol - impliedVol);\n    if (diff > 10*tol)\n        BOOST_FAIL(\"modified implied vol should match direct calculation\"\n                << \"\\n    implied vol         : \" << impliedVol\n                << \"\\n    modified implied vol: \" << modImpliedVol\n                << \"\\n    difference          : \" << diff\n                << \"\\n    tolerance           : \" << tol);\n}\n\ntest_suite* AndreasenHugeVolatilityInterplTest::suite(SpeedLevel speed) {\n    test_suite* suite =\n        BOOST_TEST_SUITE(\"Andreasen-Huge volatility interpolation tests\");\n\n    suite->add(QUANTLIB_TEST_CASE(\n        &AndreasenHugeVolatilityInterplTest::testSingleOptionCalibration));\n    suite->add(QUANTLIB_TEST_CASE(\n        &AndreasenHugeVolatilityInterplTest::testArbitrageFree));\n    suite->add(QUANTLIB_TEST_CASE(\n        &AndreasenHugeVolatilityInterplTest::testPeterAndFabiensExample));\n    suite->add(QUANTLIB_TEST_CASE(\n        &AndreasenHugeVolatilityInterplTest::testDifferentOptimizers));\n    suite->add(QUANTLIB_TEST_CASE(\n        &AndreasenHugeVolatilityInterplTest::testMovingReferenceDate));\n\n    if (speed == Slow) {\n        suite->add(QUANTLIB_TEST_CASE(\n            &AndreasenHugeVolatilityInterplTest::testAndreasenHugePut));\n        suite->add(QUANTLIB_TEST_CASE(\n            &AndreasenHugeVolatilityInterplTest::testAndreasenHugeCall));\n        suite->add(QUANTLIB_TEST_CASE(\n            &AndreasenHugeVolatilityInterplTest::testAndreasenHugeCallPut));\n        suite->add(QUANTLIB_TEST_CASE(\n            &AndreasenHugeVolatilityInterplTest::testLinearInterpolation));\n        suite->add(QUANTLIB_TEST_CASE(\n            &AndreasenHugeVolatilityInterplTest::testPiecewiseConstantInterpolation));\n        suite->add(QUANTLIB_TEST_CASE(\n            &AndreasenHugeVolatilityInterplTest::testBarrierOptionPricing));\n        suite->add(QUANTLIB_TEST_CASE(\n            &AndreasenHugeVolatilityInterplTest::testTimeDependentInterestRates));\n    }\n    return suite;\n}\n\n", "meta": {"hexsha": "4437f7204206b0679fc6e7ac3d40ad9ee38ece6f", "size": 42341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/andreasenhugevolatilityinterpl.cpp", "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": "test-suite/andreasenhugevolatilityinterpl.cpp", "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": "test-suite/andreasenhugevolatilityinterpl.cpp", "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": 41.1077669903, "max_line_length": 119, "alphanum_fraction": 0.6111334168, "num_tokens": 11971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5686101402445276}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/module/core.hpp>\n#include <eve/module/core.hpp>\n#include <eve/module/math.hpp>\n#include <eve/module/elliptic.hpp>\n#include <boost/math/special_functions/ellint_rg.hpp>\n\n//==================================================================================================\n// Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of ellint_rg\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n\n  TTS_EXPR_IS( eve::ellint_rg(T(), T(), T())  , T);\n  TTS_EXPR_IS( eve::ellint_rg(v_t(), v_t(), v_t()), v_t);\n  TTS_EXPR_IS( eve::ellint_rg(T(), v_t(), v_t()), T);\n  TTS_EXPR_IS( eve::ellint_rg(v_t(), T(), v_t()), T);\n  TTS_EXPR_IS( eve::ellint_rg(v_t(), v_t(), T()), T);\n  TTS_EXPR_IS( eve::ellint_rg(T(), T(), v_t()), T);\n  TTS_EXPR_IS( eve::ellint_rg(v_t(), T(), T()), T);\n  TTS_EXPR_IS( eve::ellint_rg(T(), v_t(), T()), T);\n};\n\n//==================================================================================================\n// ellint_rg  tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of ellint_rg on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate( eve::test::randoms(0, 100.0)\n                             , eve::test::randoms(0, 100.0)\n                             , eve::test::randoms(0, 100.0))\n        )\n<typename T>(T const& x, T const& y, T const& z)\n{\n  using eve::detail::map;\n  using v_t = eve::element_type_t<T>;\n\n  TTS_ULP_EQUAL(eve::ellint_rg(x, y, z) , map([](auto e, auto f, auto g) -> v_t { return boost::math::ellint_rg(e, f, g); }, x, y, z), 11);\n};\n", "meta": {"hexsha": "0f9ec408d0a80ed16e5314e0429de940e9faaab7", "size": 2101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/elliptic/ellint_rg.cpp", "max_stars_repo_name": "clayne/eve", "max_stars_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/elliptic/ellint_rg.cpp", "max_issues_repo_name": "clayne/eve", "max_issues_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/elliptic/ellint_rg.cpp", "max_forks_repo_name": "clayne/eve", "max_forks_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1960784314, "max_line_length": 139, "alphanum_fraction": 0.4250356973, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5686101131594757}}
{"text": "/*******************************************************************************\nCopyright(c) 2015-2021 Parker Hannifin Corp. All rights reserved.\n\nMIT Licensed. See the included LICENSE.txt for a copy of the full MIT License.\n*******************************************************************************/\n#include \"mscl/MicroStrain/Wireless/SyncSamplingFormulas.h\"\n#include \"mscl/MicroStrain/SampleRate.h\"\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace mscl;\n\nBOOST_AUTO_TEST_SUITE(SyncSamplingFormulas_Test)\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_bytesPerSecond)\n{\n    SampleRate hz_1 = SampleRate::Hertz(1);\n    SampleRate hz_256 = SampleRate::Hertz(256);\n    SampleRate sec_10 = SampleRate::Seconds(10);\n\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::bytesPerSecond(hz_1, 4, 2), 8.0, 0.1);\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::bytesPerSecond(hz_1, 4, 4), 16.0, 0.1);\n    \n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::bytesPerSecond(hz_256, 4, 2), 2048.0, 0.1);\n\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::bytesPerSecond(sec_10, 4, 2), 0.8, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_maxBytesPerPacket)\n{\n    SampleRate hz_256 = SampleRate::Hertz(256);\n    SampleRate hz_512 = SampleRate::Hertz(512);\n    SampleRate sec_10 = SampleRate::Seconds(10);\n    WirelessTypes::CommProtocol lxrs = WirelessTypes::commProtocol_lxrs;\n\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxBytesPerPacket(hz_256, true, true, 1, lxrs), 32);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxBytesPerPacket(hz_256, true, false, 1, lxrs), 64);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxBytesPerPacket(hz_256, false, false, 1, lxrs), 96);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxBytesPerPacket(hz_512, true, true, 1, lxrs), 32);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxBytesPerPacket(hz_512, true, false, 1, lxrs), 48);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxBytesPerPacket(sec_10, true, false, 1, lxrs), 64);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_txPerGroup)\n{\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::txPerGroup(128.0, 200, 1), 1);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::txPerGroup(128.0, 400, 2), 1);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::txPerGroup(2.0, 400, 16), 1);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::txPerGroup(128.0, 2, 1), 64);\n\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::txPerGroup(2048.0, 64, 1), 32);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_txPerSecond)\n{\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::txPerSecond(1, 0), 0.0, 0.1);\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::txPerSecond(4, 1), 4.0, 0.1);\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::txPerSecond(16, 2), 8.0, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_slotSpacing)\n{\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::slotSpacing(WirelessTypes::commProtocol_lxrs), 8);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::slotSpacing(WirelessTypes::commProtocol_lxrsPlus), 4);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_maxTdmaAddress)\n{\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxTdmaAddress(4, 1, true, WirelessTypes::commProtocol_lxrs), 248);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxTdmaAddress(16, 2, true, WirelessTypes::commProtocol_lxrs), 120);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxTdmaAddress(128, 1, true, WirelessTypes::commProtocol_lxrs), 1);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxTdmaAddress(128, 1, false, WirelessTypes::commProtocol_lxrs), 8);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_percentBandwidth)\n{\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::percentBandwidth(0.0f, true, WirelessTypes::commProtocol_lxrs), 0.0, 0.1);\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::percentBandwidth(4.0f, true, WirelessTypes::commProtocol_lxrs), 3.128, 0.1);\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::percentBandwidth(8.0f, true, WirelessTypes::commProtocol_lxrs), 6.256, 0.1);\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::percentBandwidth(128.0f, true, WirelessTypes::commProtocol_lxrs), 100.097, 0.1);\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::percentBandwidth(128.0f, false, WirelessTypes::commProtocol_lxrs), 100.0, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_sampleDuration)\n{\n    SampleRate hz_1 = SampleRate::Hertz(1);\n    SampleRate hz_256 = SampleRate::Hertz(256);\n    SampleRate sec_10 = SampleRate::Seconds(10);\n\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::sampleDuration(200, hz_1), 200, 0.1);\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::sampleDuration(400, hz_256), 1.5625, 0.1);\n    BOOST_CHECK_CLOSE(SyncSamplingFormulas::sampleDuration(800, sec_10), 8000, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_bytesPerSweep)\n{\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::bytesPerSweep(2, 4), 8);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::bytesPerSweep(4, 8), 32);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_checkSamplingDelay)\n{\n    SampleRate hz_1 = SampleRate::Hertz(1);\n    SampleRate hz_256 = SampleRate::Hertz(256);\n\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::checkSamplingDelay(WirelessTypes::samplingMode_sync, hz_1, WirelessModels::node_gLink_10g), true);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::checkSamplingDelay(WirelessTypes::samplingMode_sync, hz_256, WirelessModels::node_tcLink_1ch), true);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::checkSamplingDelay(WirelessTypes::samplingMode_sync, hz_256, WirelessModels::node_shmLink), true);\n\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::checkSamplingDelay(WirelessTypes::samplingMode_sync, hz_256, WirelessModels::node_gLink_10g), false);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_slotsBetweenTx)\n{\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::slotsBetweenTx(2, 2), 1024);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::slotsBetweenTx(8, 2), 256);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::slotsBetweenTx(2, 8), 4096);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_canHaveSlot1)\n{\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::canHaveFirstSlot(WirelessModels::node_sgLink, 1), true);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::canHaveFirstSlot(WirelessModels::node_tcLink_1ch, 1), false);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::canHaveFirstSlot(WirelessModels::node_tcLink_1ch, 2), true);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_totalBytesPerBurst)\n{\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::totalBytesPerBurst(256, 2), 512);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::totalBytesPerBurst(20, 30), 600);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_maxDataBytesPerPacket)\n{\n    WirelessTypes::CommProtocol lxrs = WirelessTypes::commProtocol_lxrs;\n\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxBytesPerBurstPacket(20, true, lxrs), 80);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxBytesPerBurstPacket(256, true, lxrs), 0);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxBytesPerBurstPacket(20, false, lxrs), 80);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::maxBytesPerBurstPacket(256, false, lxrs), 0);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_totalNeededBurstTx)\n{\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::totalNeededBurstTx(200, 400), 1);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::totalNeededBurstTx(400, 20), 20);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_minTimeBetweenBursts)\n{\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::minTimeBetweenBursts(20, 2.0, true), 7);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::minTimeBetweenBursts(1, 0.5, true), 5);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::minTimeBetweenBursts(400, 2.0, false), 13);\n}\n\nBOOST_AUTO_TEST_CASE(SyncSamplingFormulas_burstTxPerSecond)\n{\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::burstTxPerSecond(4, 20, 2.0, true), 1);\n    BOOST_CHECK_EQUAL(SyncSamplingFormulas::burstTxPerSecond(4, 2, 2.0, true), 2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "5b4d08b302ba81db3da1339a72bb7126af570f5d", "size": 7688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MSCL_Unit_Tests/Test_SyncSamplingFormulas.cpp", "max_stars_repo_name": "offworld-projects/MSCL", "max_stars_repo_head_hexsha": "8388e97c92165e16c26c554aadf1e204ebcf93cf", "max_stars_repo_licenses": ["BSL-1.0", "OpenSSL", "MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2015-08-28T02:41:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:50:53.000Z", "max_issues_repo_path": "MSCL_Unit_Tests/Test_SyncSamplingFormulas.cpp", "max_issues_repo_name": "offworld-projects/MSCL", "max_issues_repo_head_hexsha": "8388e97c92165e16c26c554aadf1e204ebcf93cf", "max_issues_repo_licenses": ["BSL-1.0", "OpenSSL", "MIT"], "max_issues_count": 209.0, "max_issues_repo_issues_event_min_datetime": "2015-09-30T19:36:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T21:52:20.000Z", "max_forks_repo_path": "MSCL_Unit_Tests/Test_SyncSamplingFormulas.cpp", "max_forks_repo_name": "offworld-projects/MSCL", "max_forks_repo_head_hexsha": "8388e97c92165e16c26c554aadf1e204ebcf93cf", "max_forks_repo_licenses": ["BSL-1.0", "OpenSSL", "MIT"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2015-09-03T14:40:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T02:02:01.000Z", "avg_line_length": 47.4567901235, "max_line_length": 145, "alphanum_fraction": 0.7792663892, "num_tokens": 2309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5686094047414965}}
{"text": "// Copyright (c) 2018 Graphcore Ltd. All rights reserved.\n#define BOOST_TEST_MODULE MeshGridTest\n\n#include <boost/test/unit_test.hpp>\n#include <poplar/Engine.hpp>\n#include <poplibs_support/TestDevice.hpp>\n#include <poplin/MeshGrid.hpp>\n\n#include <vector>\nusing namespace poplibs_support;\n\nstruct TestCase {\n  poplar::Type type;\n  float left;\n  float right;\n  size_t count;\n  std::string name;\n  std::vector<float> values;\n};\n\nBOOST_AUTO_TEST_CASE(LinSpace) {\n  auto device = createTestDevice(TEST_TARGET);\n  poplar::Graph g(device.getTarget());\n\n  // Define some linspace arguments with expected result values:\n  std::vector<TestCase> testCases = {\n      {poplar::FLOAT, 11.f, 42.f, 2, \"two\", {11.f, 42.f}},\n      {poplar::FLOAT, -1.f, 1.f, 3, \"small\", {-1.f, 0.f, 1.f}},\n      {poplar::FLOAT,\n       10.f,\n       -10.f,\n       5,\n       \"backwards\",\n       {10.f, 5.f, 0.f, -5.f, -10.f}}};\n\n  poplar::program::Sequence prog;\n\n  for (auto c : testCases) {\n    auto var1 = poplin::linspace(g, c.type, c.left, c.right, c.count);\n    auto var2 = g.clone(c.type, var1);\n    g.setTileMapping(var2, 0);\n    prog.add(poplar::program::Copy(var1, var2));\n    g.createHostRead(c.name, var2);\n  }\n\n  poplar::Engine e(g, prog);\n  device.bind([&](const poplar::Device &d) {\n    e.load(d);\n    e.run();\n\n    for (auto c : testCases) {\n      std::vector<float> result(c.values.size(), 0.f);\n      e.readTensor(c.name, result.data(), result.data() + result.size());\n      for (auto i = 0u; i < result.size(); ++i) {\n        BOOST_CHECK_EQUAL(result.at(i), c.values.at(i));\n      }\n    }\n  });\n}\n\nBOOST_AUTO_TEST_CASE(MeshGrid) {\n  auto device = createTestDevice(TEST_TARGET);\n  poplar::Graph g(device.getTarget());\n\n  auto xCoords = poplin::linspace(g, poplar::FLOAT, -1.f, 1.f, 3);\n  auto yCoords = poplin::linspace(g, poplar::FLOAT, -2.f, 2.f, 2);\n  auto grids = poplin::meshgrid2d(g, xCoords, yCoords);\n\n  auto gridXOut = g.clone(poplar::FLOAT, grids.at(0));\n  auto gridYOut = g.clone(poplar::FLOAT, grids.at(1));\n  g.setTileMapping(gridXOut, 0);\n  g.setTileMapping(gridYOut, 0);\n\n  const auto rowsOut = 2u;\n  const auto colsOut = 3u;\n  BOOST_CHECK_EQUAL(gridXOut.shape()[0], rowsOut);\n  BOOST_CHECK_EQUAL(gridXOut.shape()[1], colsOut);\n  BOOST_CHECK_EQUAL(gridYOut.shape()[0], rowsOut);\n  BOOST_CHECK_EQUAL(gridYOut.shape()[1], colsOut);\n\n  poplar::program::Sequence prog = {\n      poplar::program::Copy(grids.at(0), gridXOut),\n      poplar::program::Copy(grids.at(1), gridYOut)};\n\n  g.createHostRead(\"xs\", gridXOut);\n  g.createHostRead(\"ys\", gridYOut);\n\n  poplar::Engine e(g, prog);\n  device.bind([&](const poplar::Device &d) {\n    e.load(d);\n    e.run();\n\n    // In Poplar, matrices will come back row major so these are\n    // the expected flat results:\n    const std::vector<float> correctXs = {-1.f, 0.f, 1.f, -1.f, 0.f, 1.f};\n    const std::vector<float> correctYs = {-2.f, -2.f, -2.f, 2.f, 2.f, 2.f};\n\n    std::vector<float> resultX(2 * 3);\n    e.readTensor(\"xs\", resultX.data(), resultX.data() + resultX.size());\n    for (auto i = 0u; i < resultX.size(); ++i) {\n      BOOST_CHECK_EQUAL(resultX.at(i), correctXs.at(i));\n    }\n\n    std::vector<float> resultY(2 * 3);\n    e.readTensor(\"ys\", resultY.data(), resultY.data() + resultY.size());\n    for (auto i = 0u; i < resultY.size(); ++i) {\n      BOOST_CHECK_EQUAL(resultY.at(i), correctYs.at(i));\n    }\n  });\n}\n", "meta": {"hexsha": "e29a2fa823e77c5a005dd3e92957c724dd5ae316", "size": 3354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/poplin/MeshGridTest.cpp", "max_stars_repo_name": "graphcore/poplibs", "max_stars_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:28.000Z", "max_issues_repo_path": "tests/poplin/MeshGridTest.cpp", "max_issues_repo_name": "giantchen2012/poplibs", "max_issues_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/poplin/MeshGridTest.cpp", "max_forks_repo_name": "giantchen2012/poplibs", "max_forks_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:32:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T14:58:45.000Z", "avg_line_length": 30.2162162162, "max_line_length": 75, "alphanum_fraction": 0.629397734, "num_tokens": 1054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5686031369265276}}
{"text": "// example_error_handling.cpp\r\n\r\n// Copyright Paul A. Bristow 2007, 2010.\r\n// Copyright John Maddock 2007.\r\n\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Note that 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// Optional macro definitions described in text below:\r\n//   #define BOOST_MATH_DOMAIN_ERROR_POLICY ignore_error\r\n//   #define BOOST_MATH_DOMAIN_ERROR_POLICY errno_on_error\r\n//   #define BOOST_MATH_DOMAIN_ERROR_POLICY is set to: throw_on_error\r\n\r\n//[error_handling_example\r\n/*`\r\nThe following example demonstrates the effect of\r\nsetting the macro BOOST_MATH_DOMAIN_ERROR_POLICY\r\nwhen an invalid argument is encountered.  For the\r\npurposes of this example, we'll pass a negative\r\ndegrees of freedom parameter to the student's t\r\ndistribution.\r\n\r\nSince we know that this is a single file program we could\r\njust add:\r\n\r\n   #define BOOST_MATH_DOMAIN_ERROR_POLICY ignore_error\r\n\r\nto the top of the source file to change the default policy\r\nto one that simply returns a NaN when a domain error occurs.\r\nAlternatively we could use:\r\n\r\n   #define BOOST_MATH_DOMAIN_ERROR_POLICY errno_on_error\r\n\r\nTo ensure the `::errno` is set when a domain error occurs\r\nas well as returning a NaN.\r\n\r\nThis is safe provided the program consists of a single\r\ntranslation unit /and/ we place the define /before/ any\r\n#includes.  Note that should we add the define after the includes\r\nthen it will have no effect!  A warning such as:\r\n\r\n[pre warning C4005: 'BOOST_MATH_OVERFLOW_ERROR_POLICY' : macro redefinition]\r\n\r\nis a certain sign that it will /not/ have the desired effect.\r\n\r\nWe'll begin our sample program with the needed includes:\r\n*/\r\n\r\n// Boost\r\n#include <boost/math/distributions/students_t.hpp>\r\n   using boost::math::students_t;  // Probability of students_t(df, t).\r\n\r\n// std\r\n#include <iostream>\r\n   using std::cout;\r\n   using std::endl;\r\n\r\n#include <stdexcept>\r\n   using std::exception;\r\n\r\n#include <cstddef>\r\n   // using ::errno\r\n\r\n/*`\r\nNext we'll define the program's main() to call the student's t\r\ndistribution with an invalid degrees of freedom parameter,\r\nthe program is set up to handle either an exception or a NaN:\r\n*/\r\n\r\nint main()\r\n{\r\n   cout << \"Example error handling using Student's t function. \" << endl;\r\n   cout << \"BOOST_MATH_DOMAIN_ERROR_POLICY is set to: \"\r\n      << BOOST_STRINGIZE(BOOST_MATH_DOMAIN_ERROR_POLICY) << endl;\r\n\r\n   double degrees_of_freedom = -1; // A bad argument!\r\n   double t = 10;\r\n\r\n   try\r\n   {\r\n      errno = 0; // Clear/reset.\r\n      students_t dist(degrees_of_freedom); // exception is thrown here if enabled.\r\n      double p = cdf(dist, t);\r\n      // Test for error reported by other means:\r\n      if((boost::math::isnan)(p))\r\n      {\r\n         cout << \"cdf returned a NaN!\" << endl;\r\n         if (errno != 0)\r\n         { // So errno has been set.\r\n           cout << \"errno is set to: \" << errno << endl;\r\n         }\r\n      }\r\n      else\r\n         cout << \"Probability of Student's t is \" << p << endl;\r\n   }\r\n   catch(const std::exception& e)\r\n   {\r\n      std::cout <<\r\n         \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\r\n   }\r\n   return 0;\r\n} // int main()\r\n\r\n/*`\r\n\r\nHere's what the program output looks like with a default build\r\n(one that *does throw exceptions*):\r\n\r\n[pre\r\nExample error handling using Student's t function.\r\nBOOST_MATH_DOMAIN_ERROR_POLICY is set to: throw_on_error\r\n\r\nMessage from thrown exception was:\r\n   Error in function boost::math::students_t_distribution<double>::students_t_distribution:\r\n   Degrees of freedom argument is -1, but must be > 0 !\r\n]\r\n\r\nAlternatively let's build with:\r\n\r\n   #define BOOST_MATH_DOMAIN_ERROR_POLICY ignore_error\r\n\r\nNow the program output is:\r\n\r\n[pre\r\nExample error handling using Student's t function.\r\nBOOST_MATH_DOMAIN_ERROR_POLICY is set to: ignore_error\r\ncdf returned a NaN!\r\n]\r\n\r\nAnd finally let's build with:\r\n\r\n   #define BOOST_MATH_DOMAIN_ERROR_POLICY errno_on_error\r\n\r\nWhich gives the output show errno:\r\n\r\n[pre\r\nExample error handling using Student's t function.\r\nBOOST_MATH_DOMAIN_ERROR_POLICY is set to: errno_on_error\r\ncdf returned a NaN!\r\nerrno is set to: 33\r\n]\r\n\r\n*/\r\n\r\n//] [error_handling_eg end quickbook markup]\r\n", "meta": {"hexsha": "3af058c831900e2a6fa2c24794bb99f4e9bf6d63", "size": 4397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/error_handling_example.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/math/example/error_handling_example.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/example/error_handling_example.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.119205298, "max_line_length": 92, "alphanum_fraction": 0.7009324539, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.8056321866478978, "lm_q1q2_score": 0.5686031352796788}}
{"text": "// Copyright 2014-2015 Josh Pieper, jjp@pobox.com.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"base/quaternion.h\"\n\n#include <fmt/format.h>\n\n#include <boost/test/auto_unit_test.hpp>\n\n#include \"base/euler.h\"\n\nnamespace {\nusing namespace mjmech;\ntypedef base::Euler Euler;\ntypedef base::Quaternion Quaternion;\ntypedef base::Point3D Point3D;\n\nvoid CheckVectorClose(const Point3D& lhs,\n                      double x, double y, double z) {\n  BOOST_CHECK_SMALL(lhs.x() - x, 1e-2);\n  BOOST_CHECK_SMALL(lhs.y() - y, 1e-2);\n  BOOST_CHECK_SMALL(lhs.z() - z, 1e-2);\n}\n}\n\nBOOST_AUTO_TEST_CASE(BasicQuaternion) {\n  Point3D v(10., 0., 0);\n\n  v = Quaternion::FromEuler(0, 0, M_PI_2).Rotate(v);\n  CheckVectorClose(v, 0, 10, 0);\n\n  v = Quaternion::FromEuler(0, 0, -M_PI_2).Rotate(v);\n  CheckVectorClose(v, 10, 0, 0);\n\n  v = Quaternion::FromEuler(0, M_PI_2, 0).Rotate(v);\n  CheckVectorClose(v, 0, 0, -10);\n\n  v = Quaternion::FromEuler(M_PI_2, 0, 0).Rotate(v);\n  CheckVectorClose(v, 0, 10, 0);\n\n  v = Quaternion::FromEuler(0, 0, M_PI_2).Rotate(v);\n  CheckVectorClose(v, -10, 0, 0);\n\n  v = Quaternion::FromEuler(0, M_PI_2, 0).Rotate(v);\n  CheckVectorClose(v, 0, 0, 10);\n\n  v = Quaternion::FromEuler(M_PI_2, 0, 0).Rotate(v);\n  CheckVectorClose(v, 0, -10, 0);\n\n  v = Quaternion::FromEuler(0, 0, M_PI_2).Rotate(v);\n  CheckVectorClose(v, 10, 0, 0);\n}\n\nnamespace {\nvoid CheckEuler(Euler euler_rad,\n                double roll_rad,\n                double pitch_rad,\n                double yaw_rad) {\n  BOOST_CHECK_SMALL(euler_rad.roll - roll_rad, 1e-5);\n  BOOST_CHECK_SMALL(euler_rad.pitch - pitch_rad, 1e-5);\n  BOOST_CHECK_SMALL(euler_rad.yaw - yaw_rad, 1e-5);\n}\n}\n\nBOOST_AUTO_TEST_CASE(QuaternionEulerAndBack) {\n  struct TestCase {\n    double roll_deg;\n    double pitch_deg;\n    double yaw_deg;\n  };\n\n  TestCase tests[] = {\n    {45, 0, 0},\n    {0, 45, 0},\n    {0, 0, 45},\n    {0, 90, 0},\n    {0, 90, 20},\n    {0, -90, 0},\n    {0, -90, -10},\n    {0, -90, 30},\n    {10, 20, 30},\n    {-30, 10, 20},\n  };\n\n  for (const auto& x: tests) {\n    BOOST_TEST_CONTEXT(fmt::format(\"{} {} {}\",\n                                   x.roll_deg, x.pitch_deg, x.yaw_deg)) {\n      Euler result_rad = Quaternion::FromEuler(\n          x.roll_deg / 180 * M_PI,\n          x.pitch_deg / 180 * M_PI,\n          x.yaw_deg / 180 * M_PI).euler_rad();\n      CheckEuler(result_rad,\n                 x.roll_deg / 180 * M_PI,\n                 x.pitch_deg / 180 *M_PI,\n                 x.yaw_deg / 180 * M_PI);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(QuaternionMultiply1) {\n  Quaternion x90 = Quaternion::FromEuler(0, M_PI_2, 0);\n  Quaternion xn90 = Quaternion::FromEuler(0, -M_PI_2, 0);\n  Quaternion y90 = Quaternion::FromEuler(M_PI_2, 0, 0);\n\n  Quaternion result = xn90 * y90 * x90;\n  Point3D vector(0, 1, 0);\n  vector = result.Rotate(vector);\n  CheckVectorClose(vector, -1, 0, 0);\n\n  Quaternion initial = Quaternion::FromEuler(0, 0, 0.5 * M_PI_2);\n  initial = Quaternion::FromEuler(0, 0, 0.5 * M_PI_2) * initial;\n  CheckEuler(initial.euler_rad(), 0, 0, M_PI_2);\n\n  initial = Quaternion::FromEuler(10 / 180. * M_PI, 0, 0) * initial;\n  vector = initial.Rotate(vector);\n  CheckVectorClose(vector, 0, -0.9848078, -0.17364818);\n  CheckEuler(initial.euler_rad(), 0, -10 / 180.0 * M_PI, M_PI_2);\n}\n", "meta": {"hexsha": "223b9fda2af0acf14e3a5a4bdef518657a439af0", "size": 3753, "ext": "cc", "lang": "C++", "max_stars_repo_path": "base/test/quaternion_test.cc", "max_stars_repo_name": "rkb-1/quad", "max_stars_repo_head_hexsha": "66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2017-01-18T15:12:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T08:28:11.000Z", "max_issues_repo_path": "base/test/quaternion_test.cc", "max_issues_repo_name": "rkb-1/quad", "max_issues_repo_head_hexsha": "66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-11T14:39:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T16:49:57.000Z", "max_forks_repo_path": "base/test/quaternion_test.cc", "max_forks_repo_name": "rkb-1/quad", "max_forks_repo_head_hexsha": "66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2021-01-11T09:48:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T16:20:35.000Z", "avg_line_length": 28.8692307692, "max_line_length": 75, "alphanum_fraction": 0.6373567812, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5686031253534557}}
{"text": "#ifndef QDOFS_HPP\n#define QDOFS_HPP\n\n#pragma once\n#include <Eigen/Core>\n#include <igl/edges.h>\n#include <igl/vertex_triangle_adjacency.h>\n#include <iostream>\n#include <set>\n\nclass QDofs {\npublic:\n\t// list of edges connected to given vertex\n\tstd::map<int, std::set<int>> vertex2edge;\n\tEigen::MatrixXd nodes;\n\nprivate:\n\tconst Eigen::MatrixXd &vertices_;\n\tconst Eigen::MatrixXi &triangles_;\n\tEigen::MatrixXi        edges_;\n\tEigen::MatrixXi        qdof_;\n\npublic:\n\t//! QDofs constructor\n\t//!\n\t//! @param[in] vertices a list of triangle vertices\n\t//! @param[in] triangles a list of triangles\n\tQDofs(const Eigen::MatrixXd &vertices,\n\t      const Eigen::MatrixXi &triangles)\n\t    : vertices_(vertices), triangles_(triangles) {\n\t\tset_quadraticDofs();\n\t}\n\n\tint get_dofs(Eigen::MatrixXi &qdof) const {\n\t\tqdof = qdof_;\n\t\treturn edges_.rows() + vertices_.rows();\n\t}\n\n\tEigen::MatrixXd get_vertices() const {\n\t\treturn vertices_;\n\t}\n\nprivate:\n\t//! Create matrix containing the global indices of the degrees of freedom\n\t//! associated to quadratic FEM. First numbers vertices and then edges.\n\t//! First three columns are vertices, the last three columns are the edges.\n\tvoid set_quadraticDofs() {\n\t\t// get list of mesh edges\n\t\tigl::edges(triangles_, edges_);\n\n\t\t// resize dof_ so it has right length and 6 columns\n\t\tqdof_.resize(triangles_.rows(), 6);\n\t\t// set frist 3 columns to match the vertices defining the triangles\n\t\tqdof_.block(0, 0, triangles_.rows(), 3) = triangles_;\n\n\t\tint Ne = edges_.rows();\n\t\tint Nv = vertices_.rows();\n\n\t\t// resize matrix with nodes coordinates\n\t\tnodes.resize(Ne + Nv, 3);\n\t\t// set first Nv rows to be the vertices\n\t\tnodes.block(0, 0, vertices_.rows(), 3) = vertices_;\n\n\t\t// get list of elements to which each vertex is connected\n\t\tstd::vector<std::vector<int>> VF;\n\t\tstd::vector<std::vector<int>> VFi;\n\t\tigl::vertex_triangle_adjacency(Nv, triangles_, VF, VFi);\n\n\t\t// traverse the edges\n\t\tfor (int i = 0; i < Ne; i++) {\n\t\t\t// get vertices attached to current edge\n\t\t\tauto edgevert = edges_.row(i);\n\n\t\t\t// add midpoint to matrix of nodes coordinates\n\t\t\tnodes.row(i + Nv) = (vertices_.row(edgevert(0)) + vertices_.row(edgevert(1))) / 2.;\n\n\t\t\t// get list of elements connect to those vertices\n\t\t\tauto tria_vert0 = VF[edgevert(0)];\n\t\t\tauto tria_vert1 = VF[edgevert(1)];\n\t\t\t// get list of local index of those vertices in said elements\n\t\t\tauto tria_vertid0 = VFi[edgevert(0)];\n\t\t\tauto tria_vertid1 = VFi[edgevert(1)];\n\t\t\t// traverse elements connected to first vertex\n\t\t\tfor (unsigned int k0 = 0; k0 < tria_vert0.size(); k0++) {\n\t\t\t\tauto tria0 = tria_vert0[k0];\n\t\t\t\t// traverse elements connected to second element\n\t\t\t\tfor (unsigned int k1 = 0; k1 < tria_vert1.size(); k1++) {\n\t\t\t\t\tauto tria1 = tria_vert1[k1];\n\t\t\t\t\t// if the elements match, it means we have found a triangle\n\t\t\t\t\t// that contains the current edge\n\t\t\t\t\tif (tria0 == tria1) {\n\t\t\t\t\t\tint id = tria_vertid0[k0] + tria_vertid1[k1];\n\t\t\t\t\t\t// fill the matrix dof_ accordingly\n\t\t\t\t\t\tif (id == 1) {\n\t\t\t\t\t\t\tqdof_(tria0, 3) = Nv + i;\n\t\t\t\t\t\t} // edge 0, dof 3\n\t\t\t\t\t\telse if (id == 3) {\n\t\t\t\t\t\t\tqdof_(tria0, 4) = Nv + i;\n\t\t\t\t\t\t} // edge 1, dof 4\n\t\t\t\t\t\telse if (id == 2) {\n\t\t\t\t\t\t\tqdof_(tria0, 5) = Nv + i;\n\t\t\t\t\t\t} // edge 2, dof 5\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tstd::cout << \" error!\" << std::endl;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} // end found element\n\n\t\t\t\t} //looping on second vertex\n\t\t\t}   //looping on first vertex\n\n\t\t\t// add edge to the vertex2edge vector\n\t\t\tfor (int k = 0; k < 2; k++) {\n\t\t\t\t// get set of each vertex\n\t\t\t\tauto auxset = vertex2edge.find(edgevert(k));\n\t\t\t\t// if vertex index is already there\n\t\t\t\tif (auxset != vertex2edge.end()) {\n\t\t\t\t\t// add it to its set\n\t\t\t\t\t(*auxset).second.insert((Nv + i));\n\t\t\t\t} else { // if not, create set\n\t\t\t\t\tstd::set<int> vset;\n\t\t\t\t\tvset.insert((Nv + i));\n\t\t\t\t\tvertex2edge.insert(std::pair<int, std::set<int>>(edgevert(k), vset));\n\t\t\t\t}\n\t\t\t}\n\n\t\t} // looping on edges\n\t}\n};\n#endif\n", "meta": {"hexsha": "74c7c4782b9434d2a86abf0778ed10fa1f2c9cc4", "size": 3866, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/dofs.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series3/2d-poissonqFEM/dofs.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series3/2d-poissonqFEM/dofs.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": 29.5114503817, "max_line_length": 86, "alphanum_fraction": 0.6430419038, "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143954, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5686031237517374}}
{"text": "\n\n#include <string>\n#include <iostream>\n#include <memory>\n#include <vector>\n\n#include <boost/random.hpp>\n\n#include <Eigen/Dense>\n\n#include \"Kernel.h\"\n#include \"GaussianProcess.h\"\n#include \"SparseGaussianProcess.h\"\n\n#include \"Likelihood.h\"\n#include \"SparseLikelihood.h\"\n\n#include \"GaussianProcessInference.h\"\n\n\ntypedef gpr::GaussianProcess<double> GaussianProcessType;\ntypedef GaussianProcessType::VectorType VectorType;\ntypedef GaussianProcessType::MatrixType MatrixType;\ntypedef GaussianProcessType::DiagMatrixType DiagMatrixType;\ntypedef GaussianProcessType::VectorListType VectorListType;\n\ntypedef gpr::GaussianProcessInference<double>    GaussianProcessInferenceType;\ntypedef GaussianProcessInferenceType::Pointer    GaussianProcessInferenceTypePointer;\ntypedef gpr::GaussianLogLikelihood<double>       LikelihoodType;\ntypedef LikelihoodType::Pointer                  LikelihoodTypePointer;\ntypedef gpr::GaussianExpKernel<double>           GaussianExpKernelType;\ntypedef GaussianExpKernelType::Pointer           GaussianExpKernelTypePointer;\ntypedef gpr::GaussianKernel<double>              GaussianKernelType;\ntypedef GaussianKernelType::Pointer              GaussianKernelTypePointer;\n\nvoid Test1(){\n    std::cout << \"Test 1: maximum gaussian log likelihood with gradient descent test ...\" << std::flush;\n    std::cout.precision(8);\n\n    // global parameters\n    unsigned n = 200;\n    double noise = 0.1;\n\n    // construct training data\n    auto f = [](double x)->double { return (0.5*std::sin(x+10*x) + std::sin(4*x))*x*x; };\n\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, noise);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n    double start = -5;\n    double stop = 10;\n    VectorType Xn = VectorType::Zero(n);\n    VectorType Yn = VectorType::Zero(n);\n    for(unsigned i=0; i<n; i++){\n        Xn[i] = start + i*(stop-start)/n;\n        Yn[i] = f(Xn[i])+r();\n    }\n\n\n    GaussianExpKernelTypePointer gk(new GaussianExpKernelType(1, 1));\n    GaussianProcessType::Pointer gp(new GaussianProcessType(gk));\n    //gp->DebugOn();\n    gp->SetSigma(noise);\n    for(unsigned i=0; i<n; i++){\n        gp->AddSample(VectorType::Constant(1,Xn[i]), VectorType::Constant(1,Yn[i]));\n    }\n\n\n\n    // setup likelihood\n    double step = 1e-1;\n    unsigned iterations = 100;\n\n    LikelihoodTypePointer lh(new LikelihoodType());\n    GaussianProcessInferenceTypePointer gpi(new GaussianProcessInferenceType(lh, gp, step, iterations));\n\n    bool exp_output = true;\n    gpi->Optimize(false, exp_output);\n\n\n    //std::cout << \"Parameters are: \";\n    GaussianProcessInferenceType::ParameterVectorType parameters = gpi->GetParameters();\n    for(unsigned i=0; i<parameters.size(); i++){\n        parameters[i] = std::exp(parameters[i]);\n        //std::cout << parameters[i] << \", \";\n    }\n    //std::cout << std::endl;\n\n\n    GaussianKernelTypePointer k(new GaussianKernelType(1,1));\n    k->SetParameters(parameters);\n    gp->SetKernel(k);\n\n\n    // evaluate error\n    double error = 0;\n    unsigned gt_n = 1000;\n    for(unsigned i=0; i<gt_n; i++){\n        double x = start + i*(stop-start)/gt_n;\n        double p = gp->Predict(VectorType::Constant(1,x))[0];\n        error += std::fabs(p-f(x));\n    }\n\n\n    if(error/gt_n > 2){\n        std::stringstream ss; ss<<error/gt_n; throw ss.str();\n    }\n    else{\n        std::cout << \"[passed]\" << std::endl;\n    }\n\n}\n\n\ntypedef gpr::SparseGaussianProcess<double> SparseGaussianProcessType;\n\nvoid Test2(){\n    std::cout << \"Test 2: maximum gaussian log likelihood on dense gp and prediction with sparse gp test ... \" << std::flush;\n    std::cout.precision(8);\n\n    // global parameters\n    unsigned n = 300;\n    unsigned m = 50;\n    double noise = 0.1;\n    double jitter = 0.1;\n\n    // construct training data\n    auto f = [](double x)->double { return (0.5*std::sin(x+10*x) + std::sin(4*x))*x*x; };\n\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, noise);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n    double start = -5;\n    double stop = 10;\n    VectorType Xn = VectorType::Zero(n);\n    VectorType Yn = VectorType::Zero(n);\n    for(unsigned i=0; i<n; i++){\n        Xn[i] = start + i*(stop-start)/n;\n        Yn[i] = f(Xn[i])+r();\n    }\n\n    std::vector<unsigned> indices;\n    for(unsigned i=0; i<n; i++){\n        indices.push_back(i);\n    }\n    std::random_shuffle(indices.begin(), indices.end());\n\n\n    // setup dense gaussian process\n    GaussianExpKernelTypePointer gk(new GaussianExpKernelType(1, 1));\n    GaussianProcessType::Pointer gp(new GaussianProcessType(gk));\n    gp->SetSigma(noise);\n\n    // setup sparse gaussian process\n    SparseGaussianProcessType::Pointer sgp(new SparseGaussianProcessType(gk));\n    sgp->SetSigma(noise);\n    sgp->SetJitter(jitter);\n\n    for(unsigned i=0; i<m; i++){\n        gp->AddSample(VectorType::Constant(1,Xn[indices[i]]), VectorType::Constant(1,Yn[indices[i]]));\n        sgp->AddInducingSample(VectorType::Constant(1,Xn[indices[i]]), VectorType::Constant(1,Yn[indices[i]]));\n    }\n    for(unsigned i=0; i<n; i++){\n        sgp->AddSample(VectorType::Constant(1,Xn[i]), VectorType::Constant(1,Yn[i]));\n    }\n\n\n\n    // setup likelihood\n    double step = 1e-1;\n    unsigned iterations = 100;\n\n    LikelihoodTypePointer lh(new LikelihoodType());\n    GaussianProcessInferenceTypePointer gpi(new GaussianProcessInferenceType(lh, gp, step, iterations));\n\n    bool exp_output = true;\n    gpi->Optimize(false, exp_output);\n\n\n\n    //std::cout << \"Parameters are: \";\n    GaussianProcessInferenceType::ParameterVectorType parameters = gpi->GetParameters();\n    for(unsigned i=0; i<parameters.size(); i++){\n        parameters[i] = std::exp(parameters[i]);\n        //std::cout << parameters[i] << \", \";\n    }\n    //std::cout << std::endl;\n\n\n    GaussianKernelTypePointer k(new GaussianKernelType(1,1));\n    k->SetParameters(parameters);\n    gp->SetKernel(k);\n    sgp->SetKernel(k);\n\n\n\n    // evaluate error\n    double dense_error = 0;\n    double sparse_error = 0;\n    unsigned gt_n = 1000;\n    for(unsigned i=0; i<gt_n; i++){\n        double x = start + i*(stop-start)/gt_n;\n        double pd = gp->Predict(VectorType::Constant(1,x))[0];\n        double ps = sgp->Predict(VectorType::Constant(1,x))[0];\n        dense_error += std::fabs(pd-f(x));\n        sparse_error += std::fabs(ps-f(x));\n    }\n\n\n    if(dense_error < sparse_error){\n        throw std::string(\"dense gp should result in a smaller error than the sparse gp\");\n    }\n    else{\n        std::cout << \"[passed]\" << std::endl;\n    }\n\n\n}\n\nvoid Test3(){\n    //std::cout << \"Test 3: maximum likelihood of periodic signal ...\" << std::flush;\n\n    // ground truth periodic variable\n    auto f = [](double x)->double { return 3.5*std::sin(1.3*x); };\n\n    double start = 0;\n    double stop = 5 * 2*M_PI; // full interval\n    unsigned n = 350;\n\n    //--------------------------------------------------------------------------------\n    // generating ground truth\n    VectorType Xn = VectorType::Zero(n);\n    VectorType Yn = VectorType::Zero(n);\n    for(unsigned i=0; i<n; i++){\n        Xn[i] = start + i*(stop-start)/n;\n        Yn[i] = f(Xn[i]);\n    }\n\n    //--------------------------------------------------------------------------------\n    // perform training\n    double noise = 0.01;\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, noise);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n    double interval_training_end = 2 * 2*M_PI; // interval to train\n    unsigned number_of_samples = 200;\n\n\n    typedef gpr::PeriodicKernel<double>\t\tKernelType;\n    typedef KernelType::Pointer KernelTypePointer;\n\n    KernelTypePointer k(new KernelType(1.5, 0.5, 4)); // scale, period, smoothness\n    GaussianProcessType::Pointer gp(new GaussianProcessType(k));\n    gp->SetSigma(noise); // noise\n\n    // add samples\n    double training_step_size = (interval_training_end - start) / number_of_samples;\n    for(unsigned i=0; i<number_of_samples; i++){\n        VectorType x(1);\n        x(0) = start + i*training_step_size;\n\n        VectorType y(1);\n        y(0) = f(x(0)) + r();\n\n        gp->AddSample(x, y);\n    }\n\n    //--------------------------------------------------------------------------------\n    // maximum likelihood\n    // setup likelihood\n    double step = 1e-1;\n    unsigned iterations = 300;\n    GaussianProcessInferenceType::BooleanVectorType bv;\n    bv.push_back(false);\n    bv.push_back(true);\n    bv.push_back(false);\n\n\n    LikelihoodTypePointer lh(new LikelihoodType());\n    GaussianProcessInferenceTypePointer gpi(new GaussianProcessInferenceType(lh, gp, step, iterations));\n    gpi->SetParametersToOptimize(bv);\n\n    bool exp_output = false;\n    gpi->Optimize2(true, exp_output);\n\n\n    std::cout << \"print \\\"Parameters are: \";\n    GaussianProcessInferenceType::ParameterVectorType parameters = gpi->GetParameters();\n    for(unsigned i=0; i<parameters.size(); i++){\n        if(exp_output) parameters[i] = std::exp(parameters[i]);\n        std::cout << parameters[i] << \", \";\n    }\n    std::cout << \"\\\"\" << std::endl;\n\n\n//    KernelTypePointer k(new KernelType(1,1,1));\n//    k->SetParameters(parameters);\n//    gp->SetKernel(k);\n\n\n\n    //--------------------------------------------------------------------------------\n    // predict full intervall\n    VectorType y_predict(n);\n    VectorType y(n);\n    for(unsigned i=0; i<n; i++){\n        VectorType x(1);\n        x(0) = Xn[i];\n        y(i) = Yn[i];\n        y_predict[i] = gp->Predict(x)(0);\n    }\n\n    double err = (y-y_predict).norm();\n    std::cout << \"print \\\"\" << err/y.rows() << \"\\\"\"<< std::endl;\n//    if(err>0.4){\n//        std::cout << \" [failed] with an error of \" << err << std::endl;\n//    }\n//    else{\n//        std::cout << \" [passed].\" << std::endl;\n//    }\n\n    return;\n    std::cout << \"import numpy as np\" << std::endl;\n    std::cout << \"import pylab as plt\" << std::endl;\n\n    // ground truth\n    //unsigned gt_n = 1000;\n    std::cout << \"x = np.array([\";\n    for(unsigned i=0; i<n; i++){\n        std::cout << Xn[i] << \", \";\n    }\n    std::cout << \"])\" << std::endl;\n    std::cout << \"y = np.array([\";\n    for(unsigned i=0; i<n; i++){\n        std::cout << f(Xn[i]) << \", \";\n    }\n    std::cout << \"])\" << std::endl;\n    std::cout << \"plt.plot(x,y)\" << std::endl;\n\n    // training\n    std::cout << \"x_train = np.array([\";\n    for(unsigned i=0; i<number_of_samples; i++){\n        std::cout << start + i*training_step_size << \", \";\n    }\n    std::cout << \"])\" << std::endl;\n    std::cout << \"y_train = np.array([\";\n    for(unsigned i=0; i<number_of_samples; i++){\n        std::cout << f(start + i*training_step_size ) + r()<< \", \";\n    }\n    std::cout << \"])\" << std::endl;\n    std::cout << \"plt.plot(x_train, y_train, '.k')\" << std::endl;\n\n    // dense prediction\n    double dense_error = 0;\n    std::cout << \"gp_y = np.array([\";\n    for(unsigned i=0; i<n; i++){\n        double p = gp->Predict(VectorType::Constant(1,Xn[i]))[0];\n        dense_error += std::fabs(p-f(Xn[i]));\n        std::cout << p << \", \";\n    }\n    std::cout << \"])\" << std::endl;\n    std::cout << \"plt.plot(x, gp_y, '-r')\" << std::endl;\n\n    std::cout << \"plt.show()\" << std::endl;\n}\n\nint main (int argc, char *argv[]){\n    //std::cout << \"Maximum likelihood test 2: \" << std::endl;\n    try{\n//        Test1();\n//        Test2();\n        Test3();\n    }\n    catch(std::string& s){\n        std::cout << \"[failed] Error: \" << s << std::endl;\n        return -1;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "9a83134842b2c187f211188ac05b8f9fd1b17b56", "size": 11721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/MaximumLikelihoodTest2.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/MaximumLikelihoodTest2.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/MaximumLikelihoodTest2.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": 30.4441558442, "max_line_length": 125, "alphanum_fraction": 0.5983277877, "num_tokens": 3125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5685289468920126}}
{"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// \u76f8\u673a\u5185\u53c2\nMat K = (Mat_<double>(3,3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\ntypedef vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VecVector3d;\n\nvoid find_feature_matches(\n  const Mat &img_1, const Mat &img_2,\n  std::vector<KeyPoint> &keypoints_1,\n  std::vector<KeyPoint> &keypoints_2,\n  std::vector<DMatch> &matches);\n\nvoid 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// \u50cf\u7d20\u5750\u6807\u8f6c\u76f8\u673a\u5f52\u4e00\u5316\u5750\u6807\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  // \u8bfb\u53d6\u56fe\u50cf\n  Mat img_1 = imread(\"../1.png\", CV_LOAD_IMAGE_COLOR);\n  Mat img_2 = imread(\"../2.png\", CV_LOAD_IMAGE_COLOR);\n  assert(img_1.data && img_2.data);\n  cout << \"\u8bfb\u53d6\u56fe\u50cf \u5b8c\u6210\uff01\" << endl;\n\n\n  // \u7279\u5f81\u70b9\u5339\u914d\n  cout << \"\u5f00\u59cb\u7279\u5f81\u70b9\u5339\u914d ......\" << endl;\n  vector<KeyPoint> keypoints_1, keypoints_2;\n  vector<DMatch> matches;\n  find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n  cout << \"\u7279\u5f81\u70b9\u5339\u914d \u5b8c\u6210\uff01 \u4e00\u5171\u627e\u5230\u4e86\" << matches.size() << \"\u7ec4\u5339\u914d\u70b9\" << endl << endl;\n  // for (DMatch m:matches) {\n  //   cout << keypoints_1[m.queryIdx].pt.x << \" \" << keypoints_1[m.queryIdx].pt.y << endl;\n  // }\n\n\n\n  // \u8bfb\u53d6\u6df1\u5ea6\u56fe\uff0c\u5efa\u7acb3D\u70b9\n  Mat img_depth_1 = imread(\"../1_depth.png\", CV_LOAD_IMAGE_UNCHANGED);\n  Mat img_depth_2 = imread(\"../2_depth.png\", CV_LOAD_IMAGE_UNCHANGED);\n\n  vector<Point3d> points_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 << \"\u5f00\u59cbSVD\u6c42\u89e3 ......\" << 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 << \"\u5f00\u59cbBA\u6c42\u89e3 ......\" << 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// \u6ce8\u610fpts2\u548cpts1\u987a\u5e8f\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    // --\u7b2c\u4e00\u6b65\uff1a\u68c0\u6d4bOriented Fast\u89d2\u70b9\u4f4d\u7f6e\n    detector->detect(img_1, keypoints_1);\n    detector->detect(img_2, keypoints_2);\n    cout << \"--\u7b2c\u4e00\u6b65\u5b8c\u6210\uff1a\u68c0\u6d4bOriented Fast\u89d2\u70b9\u4f4d\u7f6e\" << endl;\n\n    // --\u7b2c\u4e8c\u6b65\uff1a\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97BRIEF\u63cf\u8ff0\u5b50\n    descriptor->compute(img_1, keypoints_1, descriptors_1);\n    descriptor->compute(img_2, keypoints_2, descriptors_2);\n    cout << \"--\u7b2c\u4e8c\u6b65\u5b8c\u6210\uff1a\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97BRIEF\u63cf\u8ff0\u5b50\" << endl;\n\n    // -- \u7b2c\u4e09\u6b65\uff1a\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528Hamming\u8ddd\u79bb\n    vector<DMatch> match;\n    matcher->match(descriptors_1, descriptors_2, match);\n    cout << \"--\u7b2c\u4e09\u6b65\u5b8c\u6210\uff1a\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528Hamming\u8ddd\u79bb\" << endl;\n\n    // --\u7b2c\u56db\u6b65\uff1a\u5339\u914d\u70b9\u5bf9 \u7b5b\u9009\n    auto min_max = minmax_element(match.begin(), match.end(),\n                [] (const DMatch &m1, const DMatch &m2) {return m1.distance < m2.distance;});\n    double min_dist = min_max.first->distance;\n    double max_dist = min_max.second->distance;\n\n    for (int i=0; i<descriptors_1.rows; i++){\n        if(match[i].distance <= max(2*min_dist, 30.0)){\n            matches.push_back(match[i]);\n        }\n    }\n    cout << \"--\u7b2c\u56db\u6b65\u5b8c\u6210\uff1a\u5339\u914d\u70b9\u5bf9 \u7b5b\u9009\" << endl;\n}\n\n\n\n\n\n\nPoint2d pixel2cam(const Point2d &p) {\n  return Point2d\n    (\n      (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n      (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n    );\n}\n\n", "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 \"filters.h\"\r\n\r\n#include <Eigen/SVD>\r\n\r\nnamespace GPT::Filter\r\n{\r\n    void Contrast::apply(MatXd& img)\r\n    {\r\n        if (low < 0)\r\n            low = img.minCoeff();\r\n\r\n        if (high < 0)\r\n            high = img.maxCoeff();\r\n\r\n        img.array() = (img.array() - low) / (high - low); // Images are always in between 0 and 1\r\n\r\n        // To make sure\r\n        for (int64_t k = 0; k < img.size(); k++)\r\n        {\r\n            double& val = img.data()[k];\r\n            val = std::max<double>(0, val);\r\n            val = std::min<double>(1, val);\r\n        }\r\n    }\r\n    \r\n    /**************************************************************************/\r\n    /**************************************************************************/\r\n\r\n\tvoid Median::apply(MatXd& img)\r\n\t{\r\n        MatXd mat(img);\r\n\r\n        int64_t\r\n            radiusX = static_cast<int64_t>(0.5 * double(sizeX)),\r\n            radiusY = static_cast<int64_t>(0.5 * double(sizeY));\r\n\r\n        for (int64_t k = 0; k < mat.rows(); k++)\r\n            for (int64_t l = 0; l < mat.cols(); l++)\r\n            {\r\n                // Getting region\r\n                int64_t\r\n                    xo = std::max<int64_t>(l - radiusX, 0),\r\n                    yo = std::max<int64_t>(k - radiusY, 0),\r\n                    xf = std::min<int64_t>(l + radiusX + 1, mat.cols()),\r\n                    yf = std::min<int64_t>(k + radiusY + 1, mat.rows());\r\n\r\n                int64_t size = (yf - yo) * (xf - xo);\r\n\r\n                std::vector<double> vec;\r\n                vec.reserve(size);\r\n\r\n                for (int64_t y = yo; y < yf; y++)\r\n                    for (int64_t x = xo; x < xf; x++)\r\n                        vec.push_back(mat(y, x));\r\n\r\n                std::sort(vec.begin(), vec.end());\r\n\r\n                int64_t pos = static_cast<int64_t>(0.5 * double(vec.size()));\r\n                img(k, l) = vec.at(pos);\r\n            }\r\n\t}\r\n\r\n    /**************************************************************************/\r\n    /**************************************************************************/\r\n\r\n\tvoid CLAHE::apply(MatXd& img)\r\n\t{\r\n        const int64_t\r\n            nCols = img.cols(),\r\n            nRows = img.rows(),\r\n            tileArea = tileSizeX * tileSizeY,\r\n            TX = static_cast<int64_t>(std::ceil(double(nCols) / double(tileSizeX))),\r\n            TY = static_cast<int64_t>(std::ceil(double(nRows) / double(tileSizeY))),\r\n            NT = TX * TY;\r\n\r\n        double clipValue = clipLimit * tileArea / 256.0;\r\n\r\n        MatXd lut = MatXd::Zero(256, NT);\r\n\r\n        for (int64_t k = 0; k < nRows; k++)\r\n            for (int64_t l = 0; l < nCols; l++)\r\n            {\r\n                int64_t\r\n                    y = static_cast<int64_t>(k / double(tileSizeX)),\r\n                    x = static_cast<int64_t>(l / double(tileSizeY)),\r\n                    tid = y * TX + x;\r\n\r\n                int64_t id = static_cast<int64_t>(255.0 * img(k, l));\r\n                lut(id, tid)++;\r\n            }\r\n\r\n        // Normalization all look up tables\r\n        for (int64_t tid = 0; tid < NT; tid++)\r\n        {\r\n            // To avoid contrast differences at borders, let's clip the histogram\r\n            while (true)\r\n            {\r\n                double extra = 0.0;\r\n                for (int64_t r = 0; r < 256; r++)\r\n                    if (lut(r, tid) > clipValue)\r\n                    {\r\n                        extra += lut(r, tid) - clipValue;\r\n                        lut(r, tid) = clipValue;\r\n                    }\r\n\r\n                if (extra < 0.00001)\r\n                    break;\r\n\r\n                lut.col(tid).array() += extra / 256.0;\r\n            } \r\n\r\n            double norm = lut.col(tid).sum();\r\n            lut.col(tid).array() /= norm;\r\n\r\n            for (int64_t k = 1; k < 256; k++)\r\n                lut(k, tid) += lut(k - 1, tid);\r\n\r\n            double bot = lut.col(tid).minCoeff();\r\n            lut.col(tid).array() = (lut.col(tid).array() - bot) / (1.0 - bot);\r\n        }\r\n\r\n        // Applying clahe algorithm\r\n        for (int64_t k = 0; k < nRows; k++)\r\n            for (int64_t l = 0; l < nCols; l++)\r\n            {\r\n                // Determining tile\r\n                int64_t x = l / tileSizeX, y = k / tileSizeY;\r\n\r\n                double px = double(l) / tileSizeX - x,\r\n                    py = double(k) / tileSizeY - y;\r\n\r\n                int dx = round(px) == 1.0 ? 1 : -1,\r\n                    dy = round(py) == 1.0 ? 1 : -1;\r\n\r\n                // boundary conditions\r\n                if (y == 0 && dy == -1)\r\n                    dy = 0;\r\n\r\n                if (y == (TY - 1) && dy == 1)\r\n                    dy = 0;\r\n\r\n                if (x == 0 && dx == -1)\r\n                    dx = 0;\r\n\r\n                if (x == (TX - 1) && dx == 1)\r\n                    dx = 0;\r\n\r\n                // getting distance from tile's center\r\n                px = px > 0.5 ? px - 0.5 : 0.5 - px;\r\n                py = py > 0.5 ? py - 0.5 : 0.5 - py;\r\n\r\n                int64_t\r\n                    bin = static_cast<int64_t>(255.0 * img(k, l)),\r\n                    tid0 = (y + 0) * TX + (x + 0),\r\n                    tid1 = (y + 0) * TX + (x + dx),\r\n                    tid2 = (y + dy) * TX + (x + 0),\r\n                    tid3 = (y + dy) * TX + (x + dx);\r\n\r\n                double valx1 = (1.0 - px) * lut(bin, tid0) + px * (lut(bin, tid1));\r\n                double valx2 = (1.0 - px) * lut(bin, tid2) + px * (lut(bin, tid3));\r\n\r\n                img(k, l) = (1.0 - py) * valx1 + py * valx2;\r\n            }\r\n\t}\r\n\r\n    /**************************************************************************/\r\n    /**************************************************************************/\r\n\r\n    void SVD::importImages(const std::vector<MatXd>& vec)\r\n    {\r\n        denoised.resize(vec.size());\r\n        vImages.resize(vec.size());\r\n        std::copy(vec.begin(), vec.end(), vImages.begin());\r\n    }\r\n\r\n\tvoid SVD::run(bool &trigger)\r\n\t{\r\n        int64_t\r\n            maxFrames = vImages.size(),\r\n            width = vImages[0].cols(),\r\n            height = vImages[0].rows(),\r\n            rows = width * height;\r\n\r\n        // We will take the average over every rank approximated image for different slices\r\n        std::vector<float> counter(maxFrames, 0);\r\n\r\n        for (int64_t fr = 0; fr < maxFrames; fr++)\r\n            denoised[fr] = MatXd::Zero(height, width);\r\n\r\n        MatXd mat(rows, slice);\r\n        for (int64_t fr = 0; fr <= maxFrames - slice; fr++)\r\n        {\r\n            for (int64_t k = 0; k < slice; k++)\r\n                mat.col(k) = vImages[fr + k].reshaped();\r\n\r\n            Eigen::BDCSVD<MatXd> svd(mat, Eigen::ComputeThinU | Eigen::ComputeThinV);\r\n            MatXd U = svd.matrixU();\r\n            MatXd V = svd.matrixV().transpose();\r\n            const VecXd& S = svd.singularValues();\r\n\r\n\r\n            mat = S(0) * U.col(0) * V.row(0);\r\n\r\n            for (int64_t k = 1; k < rank; k++)\r\n                mat += S(k) * U.col(k) * V.row(k);\r\n\r\n\r\n            for (int64_t k = 0; k < slice; k++)\r\n            {\r\n                denoised[fr + k] += mat.col(k).reshaped();\r\n                counter[fr + k]++;\r\n            }\r\n\r\n            // In case we want to stop this function from outside\r\n            if (trigger)\r\n                return;\r\n        }\r\n\r\n        for (int64_t fr = 0; fr < maxFrames; fr++)\r\n            denoised[fr] /= counter[fr];\r\n\r\n    }\r\n\r\n    const MatXd& SVD::getImage(int64_t frame) { return denoised[frame]; }\r\n    \r\n    void SVD::updateImages(std::vector<MatXd>& vec)\r\n    {\r\n        assert(vec.size() == denoised.size());\r\n        std::copy(denoised.begin(), denoised.end(), vec.begin());\r\n    }\r\n}", "meta": {"hexsha": "6933396d1da160868d771ab2d6a2b4f148fa21cb", "size": 7640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Methods/src/filters.cpp", "max_stars_repo_name": "guilmont/GP-Tool", "max_stars_repo_head_hexsha": "4d19c32c55a37fa9ac62799c7d8466f6632a7351", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-14T06:47:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T13:41:01.000Z", "max_issues_repo_path": "Methods/src/filters.cpp", "max_issues_repo_name": "guilmont/GP-Tool", "max_issues_repo_head_hexsha": "4d19c32c55a37fa9ac62799c7d8466f6632a7351", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-06T15:21:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T15:21:11.000Z", "max_forks_repo_path": "Methods/src/filters.cpp", "max_forks_repo_name": "guilmont/GP-Tool", "max_forks_repo_head_hexsha": "4d19c32c55a37fa9ac62799c7d8466f6632a7351", "max_forks_repo_licenses": ["Apache-2.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.0735930736, "max_line_length": 98, "alphanum_fraction": 0.3837696335, "num_tokens": 1938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5685289311136473}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"Werk/Math/OrderStatistics.hpp\"\n\nBOOST_AUTO_TEST_SUITE(OrderStatisticsTest)\n\nBOOST_AUTO_TEST_CASE(TestEmpty) {\n\tWerk::OrderStatistics<double> s;\n\tBOOST_REQUIRE_EQUAL(s.count(),0);\n}\n\nBOOST_AUTO_TEST_CASE(TestBasic) {\n\tWerk::OrderStatistics<double> s;\n\ts.sample(5.0);\n    s.sample(1.0);\n    s.sample(3.0);\n    s.sample(4.0);\n    s.sample(2.0);\n\n    BOOST_REQUIRE_EQUAL(s.count(), 5);\n    BOOST_REQUIRE_EQUAL(s.min(), 1.0);\n    BOOST_REQUIRE_EQUAL(s.q1(), 2.0);\n    BOOST_REQUIRE_EQUAL(s.median(), 3.0);\n    BOOST_REQUIRE_EQUAL(s.q3(), 4.0);\n    BOOST_REQUIRE_EQUAL(s.max(), 5.0);\n\n    s.reset();\n    BOOST_REQUIRE_EQUAL(s.count(), 0);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "bdfc6dc150657c00a1513cc0edde1a30ddced91d", "size": 709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/WerkTest/Math/OrderStatistics.cpp", "max_stars_repo_name": "mish24/werk", "max_stars_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/WerkTest/Math/OrderStatistics.cpp", "max_issues_repo_name": "mish24/werk", "max_issues_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/WerkTest/Math/OrderStatistics.cpp", "max_forks_repo_name": "mish24/werk", "max_forks_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_forks_repo_licenses": ["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.6333333333, "max_line_length": 42, "alphanum_fraction": 0.6925246827, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5684943238540504}}
{"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_ILOGB_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ILOGB_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-ieee\n    This function object Extracts the value of the unbiased exponent from\n    the floating-point argument x, and returns it as a signed integer value.\n\n    @par Note:\n\n      - Formally, the unbiased exponent is the integral part of \\f$\\log_r|x|\\f$\n      as a signed integral value, for non-zero x, where r is\n      std::numeric_limits<T>::radix and T is the floating-point type of arg.\n\n      - In practice r = 2 for all supported platforms\n\n      - boost::simd::ilogb differ from std::ilogb in the return type that is always the\n        integer type associated to the input type and the limiting values (zero return zero\n        and the result is always greater than zero)\n\n      - for floating inputs nan and zero returns zero and +-inf return Valmax\n\n     @par Decorators\n\n       - std_ provides access to std::ilogb\n\n       - pedantic_ return FP_ILOGB0 and FP_ILOGBNAN for 0 and nan respectively,\n         but the return type is as in the regular call.\n\n    @par Header <boost/simd/function/ilogb.hpp>\n\n    @par Example:\n\n      @snippet ilogb.cpp ilogb\n\n    @par Possible output:\n\n      @snippet ilogb.txt ilogb\n\n  **/\n  as_integer_t<Value> ilogb(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/ilogb.hpp>\n#include <boost/simd/function/simd/ilogb.hpp>\n\n#endif\n", "meta": {"hexsha": "4d4b5b1e8c8e315f538efd738ac58c81181fdb25", "size": 1863, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/ilogb.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/ilogb.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/ilogb.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 29.5714285714, "max_line_length": 100, "alphanum_fraction": 0.6312399356, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5684943189785583}}
{"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    //====================\n    // Your code goes here\n    //====================\n  }  // end of loop over triangles\n  return KpMeshDataSet;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace QuasiInterpolation\n", "meta": {"hexsha": "13e76dbc20377c11486aa0290d70e4be7d34ffcf", "size": 1807, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/QuasiInterpolation/templates/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/templates/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/templates/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": 30.6271186441, "max_line_length": 76, "alphanum_fraction": 0.6734919757, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.5684943138497426}}
{"text": "/*\n * assessment.cpp\n *\n *  Created on: Mar 15, 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//libraries\n#include <Eigen/Eigen>\n\n//local\n#include \"almost_equal.tpp\"\n#include \"typedefs.hpp\"\n\nnamespace eig = Eigen;\nnamespace math {\n\nbool almost_equal(float a, float b) {\n\treturn almost_equal_absolute(a, b);\n}\n\nbool almost_equal(double a, double b) {\n\treturn almost_equal_absolute(a, b);\n}\n\nbool almost_equal(float a, float b, float tolerance) {\n\treturn almost_equal_absolute(a, b, tolerance);\n}\n\nbool almost_equal(float a, float b, double tolerance) {\n\treturn almost_equal_absolute(a, b, static_cast<float>(tolerance));\n}\n\nbool almost_equal(double a, double b, double tolerance) {\n\treturn almost_equal_absolute(a, b, tolerance);\n}\n\ntemplate bool almost_equal<float, float>(math::Vector2f a, math::Vector2f b, float tolerance);  // @formatter: off\ntemplate bool almost_equal<float, float>(math::Vector3f a, math::Vector3f b, float tolerance);\ntemplate bool almost_equal<float, float>(math::Matrix2f a, math::Matrix2f b, float tolerance);\ntemplate bool almost_equal<float, double>(math::Vector2f a, math::Vector2f b, double tolerance);\ntemplate bool almost_equal<float, double>(math::Vector3f a, math::Vector3f b, double tolerance);\ntemplate bool almost_equal<float, double>(math::Matrix2f a, math::Matrix2f b, double tolerance);\n\ntemplate bool almost_equal<float, float>(eig::MatrixXf matrix_a, eig::MatrixXf matrix_b, float tolerance);\ntemplate bool almost_equal<float, double>(eig::MatrixXf matrix_a, eig::MatrixXf matrix_b, double tolerance);\ntemplate bool almost_equal<double, double>(eig::MatrixXd matrix_a, eig::MatrixXd matrix_b, double tolerance);\ntemplate bool almost_equal_verbose<float, float>(eig::MatrixXf matrix_a, eig::MatrixXf matrix_b, float tolerance);\ntemplate bool almost_equal_verbose<float, double>(eig::MatrixXf matrix_a, eig::MatrixXf matrix_b, double tolerance);\ntemplate bool almost_equal_verbose<double, double>(eig::MatrixXd matrix_a, eig::MatrixXd matrix_b, double tolerance);\n\ntemplate bool almost_equal<math::Vector2f, float>(math::MatrixXv2f matrix_a, math::MatrixXv2f matrix_b,float tolerance);\ntemplate bool almost_equal<math::Vector2f, double>(math::MatrixXv2f matrix_a,math::MatrixXv2f matrix_b, double tolerance);\ntemplate bool almost_equal_verbose<math::Vector2f, float>(math::MatrixXv2f matrix_a, math::MatrixXv2f matrix_b,float tolerance);\ntemplate bool almost_equal_verbose<math::Vector2f, double>(math::MatrixXv2f matrix_a,math::MatrixXv2f matrix_b, double tolerance);\n\ntemplate bool almost_equal<math::Matrix2f, float>(math::MatrixXm2f matrix_a, math::MatrixXm2f matrix_b,float tolerance);\ntemplate bool almost_equal<math::Matrix2f, double>(math::MatrixXm2f matrix_a, math::MatrixXm2f matrix_b,double tolerance);\ntemplate bool almost_equal_verbose<math::Matrix2f, float>(math::MatrixXm2f matrix_a, math::MatrixXm2f matrix_b,float tolerance);\ntemplate bool almost_equal_verbose<math::Matrix2f, double>(math::MatrixXm2f matrix_a, math::MatrixXm2f matrix_b,double tolerance);\n\ntemplate bool almost_equal<float, float>(math::Tensor3f tensor_a, math::Tensor3f tensor_b, float tolerance);\ntemplate bool almost_equal<float, double>(math::Tensor3f tensor_a, math::Tensor3f tensor_b, double tolerance);\ntemplate bool almost_equal_verbose<float, float>(math::Tensor3f tensor_a, math::Tensor3f tensor_b, float tolerance);\ntemplate bool almost_equal_verbose<float, double>(math::Tensor3f tensor_a, math::Tensor3f tensor_b, double tolerance);\n\ntemplate bool almost_equal<math::Vector3f, float>(math::Tensor3v3f tensor_a, math::Tensor3v3f tensor_b, float tolerance);\ntemplate bool almost_equal<math::Vector3f, double>(math::Tensor3v3f tensor_a, math::Tensor3v3f tensor_b, double tolerance);\ntemplate bool almost_equal_verbose<math::Vector3f, float>(math::Tensor3v3f tensor_a, math::Tensor3v3f tensor_b, float tolerance);\ntemplate bool almost_equal_verbose<math::Vector3f, double>(math::Tensor3v3f tensor_a, math::Tensor3v3f tensor_b, double tolerance);\n\ntemplate bool almost_equal<math::Matrix3f, float>(math::Tensor3m3f tensor_a, math::Tensor3m3f tensor_b, float tolerance);\ntemplate bool almost_equal<math::Matrix3f, double>(math::Tensor3m3f tensor_a, math::Tensor3m3f tensor_b, double tolerance);\ntemplate bool almost_equal_verbose<math::Matrix3f, float>(math::Tensor3m3f tensor_a, math::Tensor3m3f tensor_b, float tolerance);\ntemplate bool almost_equal_verbose<math::Matrix3f, double>(math::Tensor3m3f tensor_a, math::Tensor3m3f tensor_b, double tolerance);  // @formatter: on\n\n}//namespace math\n\n", "meta": {"hexsha": "c12939d1b54bb54d51c872b29ef3b9d736573f8a", "size": 5134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/almost_equal.cpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/math/almost_equal.cpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/math/almost_equal.cpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 55.8043478261, "max_line_length": 150, "alphanum_fraction": 0.7874951305, "num_tokens": 1337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5684943072646451}}
{"text": "/******************************************************************************\n * Copyright (C) 2013 by Jerome Maye                                          *\n * jerome.maye@gmail.com                                                      *\n ******************************************************************************/\n\n#include \"aslam/calibration/functions/IncompleteGammaQFunction.h\"\n\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace aslam {\n  namespace calibration {\n\n/******************************************************************************/\n/* Constructors and Destructor                                                */\n/******************************************************************************/\n\n    IncompleteGammaQFunction::IncompleteGammaQFunction(double alpha) :\n        mAlpha(alpha) {\n    }\n\n    IncompleteGammaQFunction::IncompleteGammaQFunction(const\n        IncompleteGammaQFunction& other) :\n        mAlpha(other.mAlpha) {\n    }\n\n    IncompleteGammaQFunction& IncompleteGammaQFunction::operator = (const\n        IncompleteGammaQFunction& other) {\n      if (this != &other) {\n        mAlpha = other.mAlpha;\n      }\n      return *this;\n    }\n\n    IncompleteGammaQFunction::~IncompleteGammaQFunction() {\n    }\n\n/******************************************************************************/\n/* Stream operations                                                          */\n/******************************************************************************/\n\n    void IncompleteGammaQFunction::read(std::istream& stream) {\n    }\n\n    void IncompleteGammaQFunction::write(std::ostream& stream) const {\n      stream << \"alpha: \" << mAlpha;\n    }\n\n    void IncompleteGammaQFunction::read(std::ifstream& stream) {\n    }\n\n    void IncompleteGammaQFunction::write(std::ofstream& stream) const {\n    }\n\n/******************************************************************************/\n/* Accessors                                                                  */\n/******************************************************************************/\n\n    double IncompleteGammaQFunction::getValue(const VariableType& argument)\n        const {\n      return boost::math::gamma_q(mAlpha, argument);\n    }\n\n    double IncompleteGammaQFunction::getAlpha() const {\n      return mAlpha;\n    }\n\n    void IncompleteGammaQFunction::setAlpha(double alpha) {\n      mAlpha = alpha;\n    }\n\n  }\n}\n", "meta": {"hexsha": "baf8e49fbee88478d84593c1a0abe3de8ccabea7", "size": 2407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "incremental_calibration/src/functions/IncompleteGammaQFunction.cpp", "max_stars_repo_name": "ethz-asl/aslam_incremental_calibration", "max_stars_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-08-23T06:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T16:56:29.000Z", "max_issues_repo_path": "incremental_calibration/src/functions/IncompleteGammaQFunction.cpp", "max_issues_repo_name": "ethz-asl/aslam_incremental_calibration", "max_issues_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:02:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-14T16:02:18.000Z", "max_forks_repo_path": "incremental_calibration/src/functions/IncompleteGammaQFunction.cpp", "max_forks_repo_name": "ethz-asl/aslam_incremental_calibration", "max_forks_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2017-01-23T09:01:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T05:13:23.000Z", "avg_line_length": 32.9726027397, "max_line_length": 80, "alphanum_fraction": 0.4200249273, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5684943053017159}}
{"text": "/**\n * @file\n * @brief NPDE homework NonConformingCrouzeixRaviartFiniteElements code\n * @author Anian Ruoss\n * @date   18.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <gtest/gtest.h>\n#include <lf/base/base.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n\n#include <Eigen/Core>\n\n#include \"../crfespace.h\"\n#include \"../crl2errordirichletbvp.h\"\n\nusing namespace NonConformingCrouzeixRaviartFiniteElements;\n\nTEST(CRReferenceFiniteElement, RefEl) {\n  CRReferenceFiniteElement cr_ref_el;\n  EXPECT_TRUE(cr_ref_el.RefEl() == lf::base::RefEl::kTria());\n}\n\nTEST(CRReferenceFiniteElement, Degree) {\n  CRReferenceFiniteElement cr_ref_el;\n  EXPECT_EQ(cr_ref_el.Degree(), 1);\n}\n\nTEST(CRReferenceFiniteElement, NumRefShapeFunctions) {\n  CRReferenceFiniteElement cr_ref_el;\n  EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(), 3);\n  EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(0), 0);\n  EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(1), 1);\n  EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(2), 0);\n  EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(1, 0), 1);\n  EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(1, 1), 1);\n  EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(1, 2), 1);\n}\n\nTEST(CRReferenceFiniteElement, EvalReferenceShapeFunctions) {\n  CRReferenceFiniteElement cr_ref_el;\n\n  Eigen::MatrixXd ref_coords(2, 3);\n  ref_coords << 0, 1, 2, 3, 4, 5;\n\n  Eigen::MatrixXd ref_fun_evals(3, 3);\n  ref_fun_evals << -5, -7, -9, 5, 9, 13, 1, -1, -3;\n\n  EXPECT_EQ(cr_ref_el.EvalReferenceShapeFunctions(ref_coords), ref_fun_evals);\n}\n\nTEST(CRReferenceFiniteElement, GradientsReferenceShapeFunctions) {\n  CRReferenceFiniteElement cr_ref_el;\n\n  Eigen::MatrixXd ref_coords(2, 3);\n  ref_coords << 0, 1, 2, 3, 4, 5;\n\n  Eigen::MatrixXd ref_fun_grads(3, 6);\n  ref_fun_grads << 0, -2, 0, -2, 0, -2, 2, 2, 2, 2, 2, 2, -2, 0, -2, 0, -2, 0;\n\n  EXPECT_EQ(cr_ref_el.GradientsReferenceShapeFunctions(ref_coords),\n            ref_fun_grads);\n}\n\nTEST(CRReferenceFiniteElement, EvaluationNodes) {\n  CRReferenceFiniteElement cr_ref_el;\n\n  Eigen::MatrixXd eval_nodes(2, 3);\n  eval_nodes << .5, .5, 0, 0, .5, .5;\n\n  EXPECT_EQ(cr_ref_el.EvaluationNodes(), eval_nodes);\n}\n\nTEST(CRReferenceFiniteElement, NumEvaluationNodes) {\n  CRReferenceFiniteElement cr_ref_el;\n  EXPECT_EQ(cr_ref_el.NumEvaluationNodes(), 3);\n}\n\nTEST(CRReferenceFiniteElement, NodalValuesToDofs) {\n  CRReferenceFiniteElement cr_ref_el;\n\n  Eigen::MatrixXd nodvals(1, 3);\n  nodvals << 0, 1, 2;\n\n  EXPECT_EQ(cr_ref_el.NodalValuesToDofs(nodvals), nodvals);\n}\n\nTEST(CRFeSpace, Constructor) {\n  std::shared_ptr<lf::mesh::Mesh> mesh_ptr =\n      lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n  CRFeSpace fe_space(mesh_ptr);\n\n  EXPECT_EQ(fe_space.ShapeFunctionLayout(lf::base::RefEl::kSegment()), nullptr);\n  EXPECT_EQ(typeid(*(fe_space.ShapeFunctionLayout(lf::base::RefEl::kTria()))),\n            typeid(CRReferenceFiniteElement));\n  EXPECT_EQ(fe_space.ShapeFunctionLayout(lf::base::RefEl::kQuad()), nullptr);\n}\n\nTEST(NonConformingCrouzeixRaviartFiniteElements,\n     L2errorCRDiscretizationDirichletBVP) {\n  std::vector<double> l2_errors = {0.0227969, 0.00579489, 0.0014546923,\n                                   0.000364046};\n\n  // Loop over meshes\n  for (int i = 1; i <= 4; ++i) {\n    std::string mesh_file = CURRENT_SOURCE_DIR \"/../../meshes/refined_square\" +\n                            std::to_string(i) + \".msh\";\n\n    EXPECT_FLOAT_EQ(L2errorCRDiscretizationDirichletBVP(mesh_file),\n                    l2_errors[i - 1]);\n  }\n}\n", "meta": {"hexsha": "5092b7a93fb0f11d68b4be55fba304143508ec79", "size": 3454, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/NonConformingCrouzeixRaviartFiniteElements/templates/test/nonconformingcrouzeixraviartfiniteelements_test.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/NonConformingCrouzeixRaviartFiniteElements/templates/test/nonconformingcrouzeixraviartfiniteelements_test.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/NonConformingCrouzeixRaviartFiniteElements/templates/test/nonconformingcrouzeixraviartfiniteelements_test.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 30.0347826087, "max_line_length": 80, "alphanum_fraction": 0.7185871453, "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.568494302389153}}
{"text": "#include <unordered_set>\n#include <chrono>\n#include <random>\n#include <iostream>\n#include <stack>\n#include <complex>\n#include <utility>\n#include <vector>\n#include <cmath>\n#include <initializer_list>\n#include <sstream>\n#include <fstream>\n#include <unordered_map>\n#include <memory>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/SVD>\n", "meta": {"hexsha": "8e33f25c952d0a9d68401ab13632d7ca4e252d22", "size": 352, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/inculde/gch/headers.hpp", "max_stars_repo_name": "amitsingh19975/ML", "max_stars_repo_head_hexsha": "fbd79128f86cfbd8f09e16b0ca1ab5ab2deaa11b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/inculde/gch/headers.hpp", "max_issues_repo_name": "amitsingh19975/ML", "max_issues_repo_head_hexsha": "fbd79128f86cfbd8f09e16b0ca1ab5ab2deaa11b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inculde/gch/headers.hpp", "max_forks_repo_name": "amitsingh19975/ML", "max_forks_repo_head_hexsha": "fbd79128f86cfbd8f09e16b0ca1ab5ab2deaa11b", "max_forks_repo_licenses": ["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.5555555556, "max_line_length": 28, "alphanum_fraction": 0.75, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5684942955507318}}
{"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": "#include \"project/LinearRegression.hpp\"\n#include \"project/AutoregressiveModel.hpp\"\n#include \"project/ExponentialSmoothing.hpp\"\n#include <armadillo>\n#include <iostream>\n\nint main() {\n    \n    arma::arma_rng::set_seed_random();\n    arma::vec X = arma::randu(10, 1);\n    arma::vec y = X.col(0) + 2 * X.col(0) + 2;\n\n    \n    ExponentialSmoothing expsmth = ExponentialSmoothing(y, 0.2);\n    expsmth.fit();\n    std::cout<<expsmth.getWeigths()<<std::endl;\n\n    // AutoregressiveModel linreg = AutoregressiveModel(X, y, 3);\n    // linreg.fit(true);\n\n    // std::cout<<linreg.forecast(3)<<std::endl;\n    // std::cout<<linreg.getCoef()<<std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "afec1aff7e58891afb0b65bcc77a35af4d78128b", "size": 655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "haruspex-machine/ts-forecast-cpp", "max_stars_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-09T06:27:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T06:27:15.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "bklimowski/ts-forecast-cpp", "max_issues_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "bklimowski/ts-forecast-cpp", "max_forks_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1923076923, "max_line_length": 65, "alphanum_fraction": 0.6488549618, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5684821862331845}}
{"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#include \"pressure.hpp\"\n\n#include \"geometry/projection.hpp\"\n\n#include <Eigen/Geometry>\n\nnamespace neon::mechanics::solid\n{\nstd::pair<index_view, vector> pressure::external_force(std::int64_t const element,\n                                                       double const load_factor) const\n{\n    auto const node_view = node_indices(Eigen::all, element);\n\n    matrix3x const& X = coordinates->initial_configuration(node_view);\n\n    auto const pressure = interpolate_prescribed_load(load_factor);\n\n    // Perform the computation of the external load vector\n    matrix f_ext = -pressure\n                   * sf->quadrature().integrate(matrix::Zero(X.cols(), 3).eval(),\n                                                [&](auto const& femval, auto) -> matrix {\n                                                    auto const& [N, dN] = femval;\n\n                                                    matrix32 const jacobian = X * dN;\n\n                                                    auto const j = jacobian_determinant(jacobian);\n\n                                                    vector3 dx_dxi = jacobian.col(0);\n                                                    vector3 dx_deta = jacobian.col(1);\n\n                                                    vector3 normal = dx_dxi.cross(dx_deta).normalized();\n\n                                                    return N * normal.transpose() * j;\n                                                });\n\n    // Map the matrix back to a vector for the assembly operator\n    return {dof_indices(Eigen::all, element), Eigen::Map<matrix>(f_ext.data(), X.cols() * 3, 1)};\n}\n}\n", "meta": {"hexsha": "1b37980126e74bb633e899cfd3ee4ee25471db01", "size": 1617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mesh/mechanics/solid/boundary/pressure.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/mesh/mechanics/solid/boundary/pressure.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/mesh/mechanics/solid/boundary/pressure.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": 39.4390243902, "max_line_length": 104, "alphanum_fraction": 0.4792826221, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5684721296420445}}
{"text": "// Boost.Geometry\r\n// Unit Test\r\n\r\n// Copyright (c) 2018 Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\r\n\r\n// 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#define BOOST_GEOMETRY_NORMALIZE_LATITUDE\r\n\r\n#include <sstream>\r\n\r\n#include \"test_formula.hpp\"\r\n#include \"direct_meridian_cases.hpp\"\r\n\r\n#include <boost/geometry/srs/srs.hpp>\r\n#include <boost/geometry/formulas/vincenty_direct.hpp>\r\n#include <boost/geometry/formulas/meridian_direct.hpp>\r\n\r\ntemplate <typename Result, typename Expected, typename Reference>\r\nvoid check_meridian_direct(Result& result,\r\n                           Expected const& expected,\r\n                           Reference& reference,\r\n                           double reference_error)\r\n{\r\n    boost::geometry::math::normalize_spheroidal_coordinates\r\n        <\r\n            boost::geometry::radian,\r\n            double\r\n        >(result.lon2, result.lat2);\r\n\r\n    boost::geometry::math::normalize_spheroidal_coordinates\r\n        <\r\n            boost::geometry::radian,\r\n            double\r\n        >(reference.lon2, reference.lat2);\r\n\r\n    std::stringstream ss;\r\n    ss << \"(\" << result.lon2 * bg::math::r2d<double>()\r\n       << \" \" << result.lat2 * bg::math::r2d<double>() << \")\";\r\n\r\n    check_one(\"lon:\" + ss.str(), result.lon2, expected.lon, reference.lon2,\r\n              reference_error);\r\n    check_one(\"lat:\" + ss.str(), result.lat2, expected.lat, reference.lat2,\r\n              reference_error);\r\n    check_one(\"rev_az:\" + ss.str(), result.reverse_azimuth,\r\n              result.reverse_azimuth, reference.reverse_azimuth, reference_error);\r\n    check_one(\"red len:\" + ss.str(), result.reduced_length, result.reduced_length,\r\n              reference.reduced_length, 0.01);\r\n    check_one(\"geo scale:\" + ss.str(), result.geodesic_scale, result.geodesic_scale,\r\n              reference.geodesic_scale, 0.01);\r\n\r\n}\r\n\r\nvoid test_all(expected_results const& results)\r\n{\r\n    double const d2r = bg::math::d2r<double>();\r\n\r\n    double lon1_rad = results.p1.lon * d2r;\r\n    double lat1_rad = results.p1.lat * d2r;\r\n    coordinates expected_point;\r\n    expected_point.lon = results.p2.lon * d2r;\r\n    expected_point.lat = results.p2.lat * d2r;\r\n    double distance = results.distance;\r\n    bool direction = results.direction;\r\n\r\n    // WGS84\r\n    bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);\r\n\r\n    bg::formula::result_direct<double> vincenty_result;\r\n    bg::formula::result_direct<double> meridian_result;\r\n\r\n    typedef bg::formula::vincenty_direct<double, true, true, true, true> vi_t;\r\n    double vincenty_azimuth = direction ? 0.0 : bg::math::pi<double>();\r\n    vincenty_result = vi_t::apply(lon1_rad, lat1_rad, distance, vincenty_azimuth, spheroid);\r\n\r\n    {\r\n        typedef bg::formula::meridian_direct<double, true, true, true, true, 1> eli;\r\n        meridian_result = eli::apply(lon1_rad, lat1_rad, distance, direction, spheroid);\r\n        check_meridian_direct(meridian_result, expected_point, vincenty_result, 0.001);\r\n    }\r\n    {\r\n        typedef bg::formula::meridian_direct<double, true, true, true, true, 2> eli;\r\n        meridian_result = eli::apply(lon1_rad, lat1_rad, distance, direction, spheroid);\r\n        check_meridian_direct(meridian_result, expected_point, vincenty_result, 0.00001);\r\n    }\r\n    {\r\n        typedef bg::formula::meridian_direct<double, true, true, true, true, 3> eli;\r\n        meridian_result = eli::apply(lon1_rad, lat1_rad, distance, direction, spheroid);\r\n        check_meridian_direct(meridian_result, expected_point, vincenty_result, 0.00000001);\r\n    }\r\n    {\r\n        typedef bg::formula::meridian_direct<double, true, true, true, true, 4> eli;\r\n        meridian_result = eli::apply(lon1_rad, lat1_rad, distance, direction, spheroid);\r\n        check_meridian_direct(meridian_result, expected_point, vincenty_result, 0.00000001);\r\n    }\r\n    {\r\n        typedef bg::formula::meridian_direct<double, true, true, true, true, 5> eli;\r\n        meridian_result = eli::apply(lon1_rad, lat1_rad, distance, direction, spheroid);\r\n        check_meridian_direct(meridian_result, expected_point, vincenty_result, 0.00000000001);\r\n    }\r\n}\r\n\r\nint test_main(int, char*[])\r\n{\r\n    for (size_t i = 0; i < expected_size; ++i)\r\n    {\r\n        test_all(expected[i]);\r\n    }\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "c83927a711da0c362aa87a7ce621315881105f8e", "size": 4479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/formulas/direct_meridian.cpp", "max_stars_repo_name": "Talustus/boost_src", "max_stars_repo_head_hexsha": "ffe074de008f6e8c46ae1f431399cf932164287f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/geometry/test/formulas/direct_meridian.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "third_party/boost/libs/geometry/test/formulas/direct_meridian.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 38.6120689655, "max_line_length": 96, "alphanum_fraction": 0.6577361018, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5684279051915433}}
{"text": "// See LICENSE for license details.\n\n#include \"tetra.hpp\"\n\n#define CGAL_DISABLE_ROUNDING_MATH_CHECK\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Triangulation_3.h>\n#include <boost/iterator/transform_iterator.hpp>\n\nnamespace tetra\n{\n\nnamespace __detail {\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_3<K>      Triangulation;\ntypedef Triangulation::Point          Point;\ntypedef Triangulation::Locate_type    Locate_type;\n\nstatic Point vec2point(const Vec3d& v)\n{\n    return Point(v[0], v[1], v[2]);\n}\n\nstruct _Octagon_Impl\n{\n    _Octagon_Impl(const std::array<Vec3d, 8> &vertices);\n    const Triangulation T;\n};\n\n_Octagon_Impl::_Octagon_Impl(const std::array<Vec3d, 8> &vertices)\n    : T(boost::make_transform_iterator(vertices.begin(), vec2point),\n        boost::make_transform_iterator(vertices.end(), vec2point)) {}\n\nstatic bool contains(const _Octagon_Impl &oi, const Vec3d &v)\n{\n    Point p = vec2point(v);\n    Locate_type lt;\n    int li, lj;\n    oi.T.locate(p, lt, li, lj);\n    // Also accepts corners, edges of the polygon\n    return lt <= Triangulation::CELL;\n}\n\n} // namespace __detail\n\n\n// These are declared here because _Octagon_Impl is an imcomplete type in the header.\nOctagon::Octagon() = default;\nOctagon::~Octagon() = default;\nOctagon::Octagon(Octagon&& o) = default;\n\nOctagon::Octagon(const std::array<Vec3d, 8> &vertices)\n    : oi( std::make_unique<__detail::_Octagon_Impl>(vertices)) {}\n\nbool Octagon::contains(const Vec3d &p) const\n{\n    if (!oi)\n        throw std::runtime_error(\"contains() on empty octagon\");\n    return __detail::contains(*oi, p);\n}\n\nbool Octagon::contains(double x, double y, double z) const\n{\n    return contains({{x, y, z}});\n}\n\nvoid Octagon::operator=(Octagon o)\n{\n    swap(*this, o);\n}\n\nvoid swap(Octagon& a, Octagon& b) {\n    std::swap(a.oi, b.oi);\n}\n\n} // namespace tetra\n\n", "meta": {"hexsha": "3afa536c9302767ce2740817be5f18ad3191e00f", "size": 1901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tetra.cpp", "max_stars_repo_name": "hirschsn/tetra", "max_stars_repo_head_hexsha": "214dc5d761da49c7b60e190d25947ab579c56c93", "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": "tetra.cpp", "max_issues_repo_name": "hirschsn/tetra", "max_issues_repo_head_hexsha": "214dc5d761da49c7b60e190d25947ab579c56c93", "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": "tetra.cpp", "max_forks_repo_name": "hirschsn/tetra", "max_forks_repo_head_hexsha": "214dc5d761da49c7b60e190d25947ab579c56c93", "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": 24.0632911392, "max_line_length": 85, "alphanum_fraction": 0.7064702788, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.568427903376281}}
{"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": "//  Copyright (c) 2018-2019 Cem Bassoy\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Fraunhofer and Google in producing this work\n//  which started as a Google Summer of Code project.\n//\n//  And we acknowledge the support from all contributors.\n\n\n#include <iostream>\n#include <algorithm>\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"utility.hpp\"\n\nBOOST_AUTO_TEST_SUITE ( test_tensor_functions, * boost::unit_test::depends_on(\"test_tensor_contraction\") )\n\n\nusing test_types = zip<int,long,float,double,std::complex<float>>::with_t<boost::numeric::ublas::first_order, boost::numeric::ublas::last_order>;\n\n//using test_types = zip<int>::with_t<boost::numeric::ublas::first_order>;\n\n\nstruct fixture\n{\n\tusing extents_type = boost::numeric::ublas::shape;\n\tfixture()\n\t  : extents {\n\t      extents_type{1,1}, // 1\n\t      extents_type{1,2}, // 2\n\t      extents_type{2,1}, // 3\n\t      extents_type{2,3}, // 4\n\t      extents_type{2,3,1}, // 5\n\t      extents_type{4,1,3}, // 6\n\t      extents_type{1,2,3}, // 7\n\t      extents_type{4,2,3}, // 8\n\t      extents_type{4,2,3,5}} // 9\n\t{\n\t}\n\tstd::vector<extents_type> extents;\n};\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_prod_vector, value,  test_types, fixture )\n{\n\tusing namespace boost::numeric;\n\tusing value_type   = typename value::first_type;\n\tusing layout_type  = typename value::second_type;\n\tusing tensor_type  = ublas::tensor<value_type,layout_type>;\n\tusing vector_type  = typename tensor_type::vector_type;\n\n\n\tfor(auto const& n : extents){\n\n\t\tauto a = tensor_type(n, value_type{2});\n\n\t\tfor(auto m = 0u; m < n.size(); ++m){\n\n\t\t\tauto b = vector_type  (n[m], value_type{1} );\n\n\t\t\tauto c = ublas::prod(a, b, m+1);\n\n\t\t\tfor(auto i = 0u; i < c.size(); ++i)\n\t\t\t\tBOOST_CHECK_EQUAL( c[i] , value_type(n[m]) * a[i] );\n\n\t\t}\n\t}\n}\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_prod_matrix, value,  test_types, fixture )\n{\n\tusing namespace boost::numeric;\n\tusing value_type   = typename value::first_type;\n\tusing layout_type  = typename value::second_type;\n\tusing tensor_type  = ublas::tensor<value_type,layout_type>;\n\tusing matrix_type  = typename tensor_type::matrix_type;\n\n\n\tfor(auto const& n : extents) {\n\n\t\tauto a = tensor_type(n, value_type{2});\n\n\t\tfor(auto m = 0u; m < n.size(); ++m){\n\n\t\t\tauto b  = matrix_type  ( n[m], n[m], value_type{1} );\n\n\t\t\tauto c = ublas::prod(a, b, m+1);\n\n\t\t\tfor(auto i = 0u; i < c.size(); ++i)\n\t\t\t\tBOOST_CHECK_EQUAL( c[i] , value_type(n[m]) * a[i] );\n\n\t\t}\n\t}\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_prod_tensor_1, value,  test_types, fixture )\n{\n\tusing namespace boost::numeric;\n\tusing value_type   = typename value::first_type;\n\tusing layout_type  = typename value::second_type;\n\tusing tensor_type  = ublas::tensor<value_type,layout_type>;\n\n\t// left-hand and right-hand side have the\n\t// the same number of elements\n\n\tfor(auto const& na : extents) {\n\n\t\tauto a  = tensor_type( na, value_type{2} );\n\t\tauto b  = tensor_type( na, value_type{3} );\n\n\t\tauto const pa = a.rank();\n\n\t\t// the number of contractions is changed.\n\t\tfor( auto q = 0ul; q <= pa; ++q) { // pa\n\n\t\t\tauto phi = std::vector<std::size_t> ( q );\n\n\t\t\tstd::iota(phi.begin(), phi.end(), 1ul);\n\n\t\t\tauto c = ublas::prod(a, b, phi);\n\n\t\t\tauto acc = value_type(1);\n\t\t\tfor(auto i = 0ul; i < q; ++i)\n\t\t\t\tacc *= a.extents().at(phi.at(i)-1);\n\n\t\t\tfor(auto i = 0ul; i < c.size(); ++i)\n\t\t\t\tBOOST_CHECK_EQUAL( c[i] , acc * a[0] * b[0] );\n\n\t\t}\n\t}\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_prod_tensor_2, value,  test_types, fixture )\n{\n\tusing namespace boost::numeric;\n\tusing value_type   = typename value::first_type;\n\tusing layout_type  = typename value::second_type;\n\tusing tensor_type  = ublas::tensor<value_type,layout_type>;\n\n\n\tauto compute_factorial = [](auto const& p){\n\t\tauto f = 1ul;\n\t\tfor(auto i = 1u; i <= p; ++i)\n\t\t\tf *= i;\n\t\treturn f;\n\t};\n\n\tauto permute_extents = [](auto const& pi, auto const& na){\n\t\tauto nb = na;\n\t\tassert(pi.size() == na.size());\n\t\tfor(auto j = 0u; j < pi.size(); ++j)\n\t\t\tnb[pi[j]-1] = na[j];\n\t\treturn nb;\n\t};\n\n\n\t// left-hand and right-hand side have the\n\t// the same number of elements\n\n\tfor(auto const& na : extents) {\n\n\t\tauto a  = tensor_type( na, value_type{2} );\n\t\tauto const pa = a.rank();\n\n\n\t\tauto pi   = std::vector<std::size_t>(pa);\n\t\tauto fac = compute_factorial(pa);\n\t\tstd::iota( pi.begin(), pi.end(), 1 );\n\n\t\tfor(auto f = 0ul; f < fac; ++f)\n\t\t{\n\t\t\tauto nb = permute_extents( pi, na  );\n\t\t\tauto b  = tensor_type( nb, value_type{3} );\n\n\t\t\t// the number of contractions is changed.\n\t\t\tfor( auto q = 0ul; q <= pa; ++q) { // pa\n\n\t\t\t\tauto phia = std::vector<std::size_t> ( q );  // concatenation for a\n\t\t\t\tauto phib = std::vector<std::size_t> ( q );  // concatenation for b\n\n\t\t\t\tstd::iota(phia.begin(), phia.end(), 1ul);\n\t\t\t\tstd::transform(  phia.begin(), phia.end(), phib.begin(),\n\t\t\t\t                 [&pi] ( std::size_t i ) { return pi.at(i-1); } );\n\n\t\t\t\tauto c = ublas::prod(a, b, phia, phib);\n\n\t\t\t\tauto acc = value_type(1);\n\t\t\t\tfor(auto i = 0ul; i < q; ++i)\n\t\t\t\t\tacc *= a.extents().at(phia.at(i)-1);\n\n\t\t\t\tfor(auto i = 0ul; i < c.size(); ++i)\n\t\t\t\t\tBOOST_CHECK_EQUAL( c[i] , acc * a[0] * b[0] );\n\n\t\t\t}\n\n\t\t\tstd::next_permutation(pi.begin(), pi.end());\n\t\t}\n\t}\n}\n\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_inner_prod, value,  test_types, fixture )\n{\n\tusing namespace boost::numeric;\n\tusing value_type   = typename value::first_type;\n\tusing layout_type  = typename value::second_type;\n\tusing tensor_type  = ublas::tensor<value_type,layout_type>;\n\n\n\tfor(auto const& n : extents) {\n\n\t\tauto a  = tensor_type(n, value_type(2));\n\t\tauto b  = tensor_type(n, value_type(1));\n\n\t\tauto c = ublas::inner_prod(a, b);\n\t\tauto r = std::inner_product(a.begin(),a.end(), b.begin(),value_type(0));\n\n\t\tBOOST_CHECK_EQUAL( c , r );\n\n\t}\n}\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_norm, value,  test_types, fixture )\n{\n\tusing namespace boost::numeric;\n\tusing value_type   = typename value::first_type;\n\tusing layout_type  = typename value::second_type;\n\tusing tensor_type  = ublas::tensor<value_type,layout_type>;\n\n\n\tfor(auto const& n : extents) {\n\n\t\tauto a  = tensor_type(n);\n\n\t\tauto one = value_type(1);\n\t\tauto v = one;\n\t\tfor(auto& aa: a)\n\t\t\taa = v, v += one;\n\n\n\t\tauto c = ublas::inner_prod(a, a);\n\t\tauto r = std::inner_product(a.begin(),a.end(), a.begin(),value_type(0));\n\n\t\tauto r2 = ublas::norm( (a+a) / 2  );\n\n\t\tBOOST_CHECK_EQUAL( c , r );\n\t\tBOOST_CHECK_EQUAL( std::sqrt( c ) , r2 );\n\n\t}\n}\n\n\nBOOST_FIXTURE_TEST_CASE( test_tensor_real_imag_conj, fixture )\n{\n\tusing namespace boost::numeric;\n\tusing value_type   = float;\n\tusing complex_type = std::complex<value_type>;\n\tusing layout_type  = ublas::first_order;\n\n\tusing tensor_complex_type  = ublas::tensor<complex_type,layout_type>;\n\tusing tensor_type  = ublas::tensor<value_type,layout_type>;\n\n\tfor(auto const& n : extents) {\n\n\t\tauto a   = tensor_type(n);\n\t\tauto r0  = tensor_type(n);\n\t\tauto r00 = tensor_complex_type(n);\n\n\n\t\tauto one = value_type(1);\n\t\tauto v = one;\n\t\tfor(auto& aa: a)\n\t\t\taa = v, v += one;\n\n\t\ttensor_type b = (a+a) / value_type( 2 );\n\t\ttensor_type r1 = ublas::real( (a+a) / value_type( 2 )  );\n\t\tstd::transform(  b.begin(), b.end(), r0.begin(), [](auto const& l){ return std::real( l );  }   );\n\t\tBOOST_CHECK( r0 == r1 );\n\n\t\ttensor_type r2 = ublas::imag( (a+a) / value_type( 2 )  );\n\t\tstd::transform(  b.begin(), b.end(), r0.begin(), [](auto const& l){ return std::imag( l );  }   );\n\t\tBOOST_CHECK( r0 == r2 );\n\n\t\ttensor_complex_type r3 = ublas::conj( (a+a) / value_type( 2 )  );\n\t\tstd::transform(  b.begin(), b.end(), r00.begin(), [](auto const& l){ return std::conj( l );  }   );\n\t\tBOOST_CHECK( r00 == r3 );\n\n\t}\n\n\tfor(auto const& n : extents) {\n\n\n\n\n\t\tauto a   = tensor_complex_type(n);\n\n\t\tauto r00 = tensor_complex_type(n);\n\t\tauto r0  = tensor_type(n);\n\n\n\t\tauto one = complex_type(1,1);\n\t\tauto v = one;\n\t\tfor(auto& aa: a)\n\t\t\taa = v, v = v + one;\n\n\t\ttensor_complex_type b = (a+a) / complex_type( 2,2 );\n\n\n\t\ttensor_type r1 = ublas::real( (a+a) / complex_type( 2,2 )  );\n\t\tstd::transform(  b.begin(), b.end(), r0.begin(), [](auto const& l){ return std::real( l );  }   );\n\t\tBOOST_CHECK( r0 == r1 );\n\n\t\ttensor_type r2 = ublas::imag( (a+a) / complex_type( 2,2 )  );\n\t\tstd::transform(  b.begin(), b.end(), r0.begin(), [](auto const& l){ return std::imag( l );  }   );\n\t\tBOOST_CHECK( r0 == r2 );\n\n\t\ttensor_complex_type r3 = ublas::conj( (a+a) / complex_type( 2,2 )  );\n\t\tstd::transform(  b.begin(), b.end(), r00.begin(), [](auto const& l){ return std::conj( l );  }   );\n\t\tBOOST_CHECK( r00 == r3 );\n\n\n\n\t}\n\n\n\n}\n\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_outer_prod, value,  test_types, fixture )\n{\n\tusing namespace boost::numeric;\n\tusing value_type   = typename value::first_type;\n\tusing layout_type  = typename value::second_type;\n\tusing tensor_type  = ublas::tensor<value_type,layout_type>;\n\n\tfor(auto const& n1 : extents) {\n\t\tauto a  = tensor_type(n1, value_type(2));\n\t\tfor(auto const& n2 : extents) {\n\n\t\t\tauto b  = tensor_type(n2, value_type(1));\n\t\t\tauto c  = ublas::outer_prod(a, b);\n\n\t\t\tfor(auto const& cc : c)\n\t\t\t\tBOOST_CHECK_EQUAL( cc , a[0]*b[0] );\n\t\t}\n\t}\n}\n\n\n\ntemplate<class V>\nvoid init(std::vector<V>& a)\n{\n\tauto v = V(1);\n\tfor(auto i = 0u; i < a.size(); ++i, ++v){\n\t\ta[i] = v;\n\t}\n}\n\ntemplate<class V>\nvoid init(std::vector<std::complex<V>>& a)\n{\n\tauto v = std::complex<V>(1,1);\n\tfor(auto i = 0u; i < a.size(); ++i){\n\t\ta[i] = v;\n\t\tv.real(v.real()+1);\n\t\tv.imag(v.imag()+1);\n\t}\n}\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_trans, value,  test_types, fixture )\n{\n\tusing namespace boost::numeric;\n\tusing value_type   = typename value::first_type;\n\tusing layout_type  = typename value::second_type;\n\tusing tensor_type  = ublas::tensor<value_type,layout_type>;\n\n\tauto fak = [](auto const& p){\n\t\tauto f = 1ul;\n\t\tfor(auto i = 1u; i <= p; ++i)\n\t\t\tf *= i;\n\t\treturn f;\n\t};\n\n\tauto inverse = [](auto const& pi){\n\t\tauto pi_inv = pi;\n\t\tfor(auto j = 0u; j < pi.size(); ++j)\n\t\t\tpi_inv[pi[j]-1] = j+1;\n\t\treturn pi_inv;\n\t};\n\n\tfor(auto const& n : extents)\n\t{\n\t\tauto const p = n.size();\n\t\tauto const s = n.product();\n\t\tauto aref = tensor_type(n);\n\t\tauto v    = value_type{};\n\t\tfor(auto i = 0u; i < s; ++i, v+=1)\n\t\t\taref[i] = v;\n\t\tauto a    = aref;\n\n\n\t\tauto pi = std::vector<std::size_t>(p);\n\t\tstd::iota(pi.begin(), pi.end(), 1);\n\t\ta = ublas::trans( a, pi );\n\t\tBOOST_CHECK( a == aref  );\n\n\n\t\tauto const pfak = fak(p);\n\t\tauto i = 0u;\n\t\tfor(; i < pfak-1; ++i) {\n\t\t\tstd::next_permutation(pi.begin(), pi.end());\n\t\t\ta = ublas::trans( a, pi );\n\t\t}\n\t\tstd::next_permutation(pi.begin(), pi.end());\n\t\tfor(; i > 0; --i) {\n\t\t\tstd::prev_permutation(pi.begin(), pi.end());\n\t\t\tauto pi_inv = inverse(pi);\n\t\t\ta = ublas::trans( a, pi_inv );\n\t\t}\n\n\t\tBOOST_CHECK( a == aref  );\n\n\t}\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "64ecda396700431cb3fc0473e158dacfbb143c73", "size": 10936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/test/tensor/test_functions.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/ublas/test/tensor/test_functions.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/ublas/test/tensor/test_functions.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 24.0881057269, "max_line_length": 145, "alphanum_fraction": 0.62829188, "num_tokens": 3417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.568401064486697}}
{"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": "#include <gtest/gtest.h> \n#include \"../include/model.h\"\n#include \"../include/KalmanFilter.h\"\n#include \"../include/filterModel.h\"\n#include \"../include/mathWrapper/double.h\"\n#include \"../include/mathWrapper/eigen.h\"\n#include \"../include/mathWrapper/boost.h\"\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <math.h>\n#include \"../include/Eigen.h\" \n#include <iostream>\n\nTEST(discreteDiscreteKalmanFilter, test){\n\t\n\tint stateCount = 1;\n\tint sensorCount = 1;\n\tint initialTime = 0;\n\tvectorDouble initialEstimate(1);\n\tmatrixDouble initialCovariance(1);\n\n\tEigen::VectorXd x(1);x<<1;\t\n\tvectorEigen initialEstimateEigen(x);\n\tEigen::MatrixXd y(1,1);y<<1;\n\tmatrixEigen initialCovarianceEigen(y);\n\n\tboost::numeric::ublas::matrix<double> initialCovarianceBoost(1,1);\n\tinitialCovarianceBoost(0,0)=1;\n\tboost::numeric::ublas::vector<double> initialEstimateBoost(1);\n\tinitialEstimateBoost(0) = 1;\n\n\tEigen::VectorXd initialEstimateEigenSimple(1);initialEstimateEigenSimple<<1;\t\n\tEigen::MatrixXd initialCovarianceEigenSimple(1,1);initialCovarianceEigenSimple<<1;\n\n\tclass stateModel: public discreteModel<vectorDouble>{\n\t\tpublic:\n\t\t\tvectorDouble function(const vectorDouble & val, const int time) const override{\n\t\t\t\tvectorDouble result(val.getSystemValue() + 0.1);\n\t\t\t\treturn result;\n\t\t\t}\n\t};\n\tclass stateModelEigen: public discreteModel<vectorEigen>{\n\t\tEigen::VectorXd velocity;\n\t\tpublic:\n\t\t\tstateModelEigen(){\n\t\t\t\tEigen::VectorXd vel(1);vel<<0.1;\n\t\t\t\tvelocity = vel;\n\t\t\t}\n\t\t\tvectorEigen function(const vectorEigen & val, const int time) const override{\n\t\t\t\tvectorEigen result(val.getSystemValue() + velocity);\n\t\t\t\treturn result;\n\t\t\t}\n\t};\n\tclass stateModelBoost: public discreteModel<vectorBoost>{\n\t\tboost::numeric::ublas::vector<double> velocity;\n\t\tpublic:\n\t\t\tstateModelBoost(){\n\t\t\t\tboost::numeric::ublas::vector<double> vel(1);vel(0) = 0.1;\n\t\t\t\tvelocity = vel;\n\t\t\t}\n\t\t\tvectorBoost function(const vectorBoost & val, const int time) const override{\n\t\t\t\tvectorBoost result(val.getSystemValue() + velocity);\n\t\t\t\treturn result;\n\t\t\t}\n\t};\n\tclass stateModelEigenSimple: public discreteModel<Eigen::VectorXd>{\n\t\tEigen::VectorXd velocity;\n\t\tpublic:\n\t\t\tstateModelEigenSimple(){\n\t\t\t\tEigen::VectorXd vel(1);vel<< 0.1;\n\t\t\t\tvelocity = vel;\n\t\t\t}\n\t\t\tEigen::VectorXd function(const Eigen::VectorXd & val, const int time) const override{\n\t\t\t\treturn val + velocity;\n\t\t\t}\n\t};\n\n\n\n\n\tclass measurementModel: public discreteModel<vectorDouble>{\n\t\tpublic:\n\t\t\tvectorDouble function(const vectorDouble & val, const int time) const override{\n\t\t\t\tvectorDouble result(val.getSystemValue());\n\t\t\t\treturn result;\n\t\t\t}\n\t};\n\tclass measurementModelEigen: public discreteModel<vectorEigen>{\n\t\tpublic:\n\t\t\tvectorEigen function(const vectorEigen & val, const int time) const override{\n\t\t\t\tvectorEigen result(val.getSystemValue());\n\t\t\t\treturn result;\n\t\t\t}\n\t};\n\tclass measurementModelBoost: public discreteModel<vectorBoost>{\n\t\tpublic:\n\t\t\tvectorBoost function(const vectorBoost & val, const int time) const override{\n\t\t\t\tvectorBoost result(val.getSystemValue());\n\t\t\t\treturn result;\n\t\t\t}\n\t};\n\tclass measurementModelEigenSimple: public discreteModel<Eigen::VectorXd>{\n\t\tpublic:\n\t\t\tEigen::VectorXd function(const Eigen::VectorXd & val, const int time) const override{\n\t\t\t\treturn val;\n\t\t\t}\n\t};\n\n\n\n\n\n\tclass transitionJac: public jacobianDiscrete<vectorDouble,matrixDouble>{\n\t\tpublic:\n\t\t\tmatrixDouble function(const vectorDouble & val, int t){\n\t\t\t\treturn matrixDouble(1);\n\t\t\t}\n\t};\n\tclass measurementJac: public jacobianDiscrete<vectorDouble,matrixDouble>{\n\t\tpublic:\n\t\t\tmatrixDouble function(const vectorDouble & val, int t){\n\t\t\t\treturn matrixDouble(1);\n\t\t\t}\n\t};\n\tclass transitionJacEigen: public jacobianDiscrete<vectorEigen,matrixEigen>{\n\t\tEigen::MatrixXd v;\n\t\tpublic:\n\t\t\ttransitionJacEigen(){\n\t\t\t\tEigen::MatrixXd tmp(1,1);tmp<<1;\n\t\t\t\tv = tmp;\n\t\t\t}\n\n\t\t\tmatrixEigen function(const vectorEigen & val, int t){\n\t\t\t\treturn matrixEigen(v); \n\t\t\t}\n\t};\n\tclass measurementJacEigen: public jacobianDiscrete<vectorEigen,matrixEigen>{\n\t\tEigen::MatrixXd v;\n\t\tpublic:\n\t\t\tmeasurementJacEigen(){\n\t\t\t\tEigen::MatrixXd tmp(1,1);tmp<<1;\n\t\t\t\tv = tmp;\n\t\t\t}\n\n\t\t\tmatrixEigen function(const vectorEigen & val, int t){\n\t\t\t\treturn matrixEigen(v);\n\t\t\t}\n\t};\n\tclass transitionJacBoost: public jacobianDiscrete<vectorBoost,matrixBoost>{\n\t\tboost::numeric::ublas::matrix<double> v;\n\t\tpublic:\n\t\t\ttransitionJacBoost(){\n\t\t\t\tboost::numeric::ublas::matrix<double> tmp(1,1);tmp(0,0) = 1;\n\t\t\t\tv = tmp;\n\n\t\t\t}\n\n\t\t\tmatrixBoost function(const vectorBoost & val, int t){\n\t\t\t\treturn matrixBoost(v); \n\t\t\t}\n\t};\n\tclass measurementJacBoost: public jacobianDiscrete<vectorBoost,matrixBoost>{\n\t\tboost::numeric::ublas::matrix<double> v;\n\t\tpublic:\n\t\t\tmeasurementJacBoost(){\n\t\t\t\tboost::numeric::ublas::matrix<double> tmp(1,1);tmp(0,0) = 1;\n\t\t\t\tv = tmp;\n\t\t\t}\n\n\t\t\tmatrixBoost function(const vectorBoost & val, int t){\n\t\t\t\treturn matrixBoost(v);\n\t\t\t}\n\t};\n\tclass transitionJacEigenSimple: public jacobianDiscrete<Eigen::VectorXd,Eigen::MatrixXd>{\n\t\tEigen::MatrixXd v;\n\t\tpublic:\n\t\t\ttransitionJacEigenSimple(){\n\t\t\t\tEigen::MatrixXd tmp(1,1);tmp << 1;\n\t\t\t\tv = tmp;\n\n\t\t\t}\n\n\t\t\tEigen::MatrixXd function(const Eigen::VectorXd & val, int t){\n\t\t\t\treturn v; \n\t\t\t}\n\t};\n\tclass measurementJacEigenSimple: public jacobianDiscrete<Eigen::VectorXd,Eigen::MatrixXd>{\n\t\tEigen::MatrixXd v;\n\t\tpublic:\n\t\t\tmeasurementJacEigenSimple(){\n\t\t\t\tEigen::MatrixXd tmp(1,1);tmp<< 1;\n\t\t\t\tv = tmp;\n\t\t\t}\n\n\t\t\tEigen::MatrixXd function(const Eigen::VectorXd & val, int t){\n\t\t\t\treturn v;\n\t\t\t}\n\t};\n\n\n\n\n\tclass processNoise: public discreteNoiseCovariance<vectorDouble,matrixDouble>{\n\t\tmatrixDouble function(const vectorDouble &est,int t) override{\n\t\t\treturn matrixDouble(0.01);\n\t\t}\t\n\t\tmatrixDouble sqrt(const vectorDouble &est, int t) override{\n\t\t\treturn matrixDouble(0.1);\n\t\t}\n\t};\n\tclass sensorNoise: public discreteNoiseCovariance<vectorDouble,matrixDouble>{\n\t\tmatrixDouble function(const vectorDouble &est,int t) override{\n\t\t\treturn matrixDouble(0.01);\n\t\t}\t\n\t\tmatrixDouble sqrt(const vectorDouble &est, int t) override{\n\t\t\treturn matrixDouble(0.1);\n\t\t}\n\t};\n\tclass processNoiseEigen: public discreteNoiseCovariance<vectorEigen,matrixEigen>{\n\t\tEigen::MatrixXd v;\n\t\tEigen::MatrixXd v2;\n\t\tpublic:\n\t\tprocessNoiseEigen(){\n\t\t\tEigen::MatrixXd tmp(1,1);tmp<<0.01;\n\t\t\tEigen::MatrixXd tmp2(1,1);tmp2<<0.1;\n\t\t\tv = tmp;\n\t\t\tv2 = tmp2;\n\t\t}\n\t\tmatrixEigen function(const vectorEigen &est,int t) override{\n\t\t\treturn matrixEigen(v);\n\t\t}\t\n\t\tmatrixEigen sqrt(const vectorEigen &est, int t) override{\n\t\t\treturn matrixEigen(v2);\n\t\t}\n\t};\n\tclass sensorNoiseEigen: public discreteNoiseCovariance<vectorEigen,matrixEigen>{\n\t\tEigen::MatrixXd v;\n\t\tEigen::MatrixXd v2;\n\t\tpublic:\n\t\tsensorNoiseEigen(){\n\t\t\tEigen::MatrixXd tmp(1,1);tmp<<0.01;\n\t\t\tEigen::MatrixXd tmp2(1,1);tmp2<<0.1;\n\t\t\tv = tmp;\n\t\t\tv2 = tmp2;\n\t\t}\n\t\tmatrixEigen function(const vectorEigen &est, int t) override{\n\t\t\treturn matrixEigen(v);\n\t\t}\t\n\t\tmatrixEigen sqrt(const vectorEigen &est, int t) override{\n\t\t\treturn matrixEigen(v2);\n\t\t}\n\t};\n\tclass processNoiseBoost: public discreteNoiseCovariance<vectorBoost,matrixBoost>{\n\t\tboost::numeric::ublas::matrix<double> v;\n\t\tboost::numeric::ublas::matrix<double> v2;\n\t\tpublic:\n\t\tprocessNoiseBoost(){\n\t\t\tboost::numeric::ublas::matrix<double> tmp(1,1);tmp(0,0) = 0.01;\n\t\t\tboost::numeric::ublas::matrix<double> tmp2(1,1);tmp2(0,0) = 0.01;\n\t\t\tv = tmp;\n\t\t\tv2 = tmp2;\n\t\t}\n\t\tmatrixBoost function(const vectorBoost &est,int t) override{\n\t\t\treturn matrixBoost(v);\n\t\t}\t\n\t\tmatrixBoost sqrt(const vectorBoost &est, int t) override{\n\t\t\treturn matrixBoost(v2);\n\t\t}\n\t};\n\tclass sensorNoiseBoost: public discreteNoiseCovariance<vectorBoost,matrixBoost>{\n\t\tboost::numeric::ublas::matrix<double> v;\n\t\tboost::numeric::ublas::matrix<double> v2;\n\t\tpublic:\n\t\tsensorNoiseBoost(){\n\t\t\tboost::numeric::ublas::matrix<double> tmp(1,1);tmp(0,0) = 0.01;\n\t\t\tboost::numeric::ublas::matrix<double> tmp2(1,1);tmp2(0,0) = 0.01;\n\t\t\tv = tmp;\n\t\t\tv2 = tmp2;\n\t\t}\n\t\tmatrixBoost function(const vectorBoost &est,int t) override{\n\t\t\treturn matrixBoost(v);\n\t\t}\t\n\t\tmatrixBoost sqrt(const vectorBoost &est, int t) override{\n\t\t\treturn matrixBoost(v2);\n\t\t}\n\t};\n\tclass processNoiseEigenSimple: public discreteNoiseCovariance<Eigen::VectorXd,Eigen::MatrixXd>{\n\t\tEigen::MatrixXd v;\n\t\tEigen::MatrixXd v2;\n\t\tpublic:\n\t\tprocessNoiseEigenSimple(){\n\t\t\tEigen::MatrixXd tmp(1,1);tmp<< 0.01;\n\t\t\tEigen::MatrixXd tmp2(1,1);tmp2<<0.1;\n\t\t\tv = tmp;\n\t\t\tv2 = tmp2;\n\t\t}\n\t\tEigen::MatrixXd function(const Eigen::VectorXd &est,int t) override{\n\t\t\treturn v;\n\t\t}\t\n\t\tEigen::MatrixXd sqrt(const Eigen::VectorXd &est, int t) override{\n\t\t\treturn v2;\n\t\t}\n\t};\n\tclass sensorNoiseEigenSimple: public discreteNoiseCovariance<Eigen::VectorXd,Eigen::MatrixXd>{\n\t\tEigen::MatrixXd v;\n\t\tEigen::MatrixXd v2;\n\t\tpublic:\n\t\tsensorNoiseEigenSimple(){\n\t\t\tEigen::MatrixXd tmp(1,1);tmp<< 0.01;\n\t\t\tEigen::MatrixXd tmp2(1,1);tmp2<<0.1;\n\t\t\tv = tmp;\n\t\t\tv2 = tmp2;\n\t\t}\n\t\tEigen::MatrixXd function(const Eigen::VectorXd &est,int t) override{\n\t\t\treturn v; \n\t\t}\t\n\t\tEigen::MatrixXd sqrt(const Eigen::VectorXd &est, int t) override{\n\t\t\treturn v2;\n\t\t}\n\t};\n\t\n\t\n\tstateModel tm;\n\tmeasurementModel mm;\n\tprocessNoise pn;\n\tsensorNoise sn;\n\ttransitionJac tj;\n\tmeasurementJac mj;\t\n\tdiscreteDiscreteFilterModel<vectorDouble,matrixDouble> ddfm(&tm,&mm,&pn,&sn,&tj,&mj,stateCount,sensorCount);\n\n\tstateModelEigen tmEigen;\n\tmeasurementModelEigen mmEigen;\n\tprocessNoiseEigen pnEigen;\n\tsensorNoiseEigen snEigen;\n\ttransitionJacEigen tjEigen;\n\tmeasurementJacEigen mjEigen;\t\n\tdiscreteDiscreteFilterModel<vectorEigen,matrixEigen> ddfmEigen(&tmEigen,&mmEigen,&pnEigen,&snEigen,&tjEigen,&mjEigen,\n\t\tstateCount,sensorCount);\n\n\tstateModelBoost tmBoost;\n\tmeasurementModelBoost mmBoost;\n\tprocessNoiseBoost pnBoost;\n\tsensorNoiseBoost snBoost;\n\ttransitionJacBoost tjBoost;\n\tmeasurementJacBoost mjBoost;\t\n\tdiscreteDiscreteFilterModel<vectorBoost,matrixBoost> ddfmBoost(&tmBoost,&mmBoost,&pnBoost,&snBoost,&tjBoost,&mjBoost,\n\t\tstateCount,sensorCount);\n\n\tstateModelEigenSimple tmEigenSimple;\n\tmeasurementModelEigenSimple mmEigenSimple;\n\tprocessNoiseEigenSimple pnEigenSimple;\n\tsensorNoiseEigenSimple snEigenSimple;\n\ttransitionJacEigenSimple tjEigenSimple;\n\tmeasurementJacEigenSimple mjEigenSimple;\t\n\tdiscreteDiscreteFilterModel<Eigen::VectorXd,Eigen::MatrixXd> ddfmEigenSimple(&tmEigenSimple,&mmEigenSimple,\n\t\t&pnEigenSimple,&snEigenSimple,&tjEigenSimple,&mjEigenSimple,stateCount,sensorCount);\n\t\t\n\n\tdiscreteDiscreteKalmanFilter<vectorDouble,matrixDouble>\n\t\tfilter(initialTime, initialEstimate, initialCovariance, &ddfm);\n\n\tdiscreteDiscreteKalmanFilter<vectorEigen,matrixEigen>\n\t\tfilterEigen(initialTime, initialEstimateEigen, initialCovarianceEigen, &ddfmEigen);\n\n\tdiscreteDiscreteKalmanFilter<vectorBoost,matrixBoost>\n\t\tfilterBoost(initialTime, initialEstimateBoost, initialCovarianceBoost, &ddfmBoost);\n\n\tdiscreteDiscreteKalmanFilter<Eigen::VectorXd,Eigen::MatrixXd>\n\t\tfilterEigenSimple( initialTime, initialEstimateEigenSimple, initialCovarianceEigenSimple,\n\t\t\t&ddfmEigenSimple);\n\n\n\tfor(int i = 0; i < 10; i++){\n\t\tASSERT_NEAR(filter.getCurrentEstimate().getSystemValue(),filterEigen.getCurrentEstimate().getSystemValue()[0],1e-9);\n\t\tASSERT_NEAR(filter.getCurrentCovariance().getSystemValue(),\n\t\t\tfilterEigen.getCurrentCovariance().getSystemValue().coeff(0,0),1e-9);\n\t\tASSERT_NEAR(filter.getCurrentTime(),filterEigen.getCurrentTime(),1e-9);\n\n\t\tASSERT_NEAR(filter.getCurrentEstimate().getSystemValue(),filterBoost.getCurrentEstimate().getSystemValue()[0],1e-9);\n\t\tboost::numeric::ublas::matrix<double> tmp = filterBoost.getCurrentCovariance().getSystemValue();\n\t\tASSERT_NEAR(filter.getCurrentCovariance().getSystemValue(),tmp(0,0),1e-9);\n\t\tASSERT_NEAR(filter.getCurrentTime(),filterBoost.getCurrentTime(),1e-9);\n\n\n\t\tfilter.predict(1);\n\t\tfilterEigen.predict(1);\n\t\tfilterBoost.predict(1);\n\t\tfilterEigenSimple.predict(1);\n\t}\n\n\n\n\tfor(int i = 0; i < 10; i++){\n\t\tvectorDouble measurement(i);\t\n\t\tEigen::VectorXd tmp(1);tmp<<i;\n\t\tvectorEigen tmp2(tmp);\n\t\tboost::numeric::ublas::vector<double> tmpBoost(1);tmpBoost(0)=i;\n\t\tvectorBoost tmp2Boost(tmpBoost);\n\t\t\n\t\tdouble sk = 1*filter.getCurrentCovariance().getSystemValue()*1 + 0.01;\n\t\tdouble kk = filter.getCurrentCovariance().getSystemValue()*(1.0/sk);\n\t\tdouble curEst = filter.getCurrentEstimate().getSystemValue(); \n\n\t\tfilter.update(measurement);\n\t\tfilterEigen.update(tmp2);\n\t\tfilterBoost.update(tmp2Boost);\n\t\tfilterEigenSimple.update(tmp);\n\t\t\n\t\tASSERT_NEAR(filter.getCurrentEstimate().getSystemValue(),filterEigen.getCurrentEstimate().getSystemValue()[0],1e-9);\n\t\tASSERT_NEAR(filter.getCurrentEstimate().getSystemValue(),filterEigenSimple.getCurrentEstimate().coeff(0,0),1e-9);\n\t\tASSERT_NEAR(filter.getCurrentCovariance().getSystemValue(),\n\t\t\tfilterEigen.getCurrentCovariance().getSystemValue().coeff(0,0),1e-9);\n\t\tboost::numeric::ublas::matrix<double> t = filterBoost.getCurrentCovariance().getSystemValue();\n\t\tASSERT_NEAR(filter.getCurrentCovariance().getSystemValue(),t(0,0),1e-9);\n\t\tASSERT_NEAR(filter.getCurrentEstimate().getSystemValue(),filterBoost.getCurrentEstimate().getSystemValue()[0],1e-9);\n\t}\n}\n\nint main(int argc, char **argv){\n\ttesting::InitGoogleTest(&argc, argv);\n\treturn RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "ed4ea7015e67c0a975a37480ba8ca230cfed721a", "size": 13067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++_implementation/tests/tests3.cpp", "max_stars_repo_name": "mannyray/KalmanFilter", "max_stars_repo_head_hexsha": "c744b0ef8a004643b373fa4cfd1440f32d5725b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-08-12T04:47:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:00:09.000Z", "max_issues_repo_path": "c++_implementation/tests/tests3.cpp", "max_issues_repo_name": "mannyray/KalmanFilter", "max_issues_repo_head_hexsha": "c744b0ef8a004643b373fa4cfd1440f32d5725b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-27T00:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-27T02:03:37.000Z", "max_forks_repo_path": "c++_implementation/tests/tests3.cpp", "max_forks_repo_name": "mannyray/KalmanFilter", "max_forks_repo_head_hexsha": "c744b0ef8a004643b373fa4cfd1440f32d5725b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-02-03T09:05:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-18T15:22:08.000Z", "avg_line_length": 30.8912529551, "max_line_length": 118, "alphanum_fraction": 0.7342159639, "num_tokens": 3594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5683750733138432}}
{"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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00c3\u00a4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace mtl;\n\nstatic const int DIM =3;\nstatic const int NB  =4;\ntypedef dense2D<double, mat::parameters<tag::row_major,\n\t\t\t\t\t   mtl::index::c_index, mtl::fixed::dimensions< DIM, DIM> > > Mat3;\ntypedef mat::block_diagonal2D<Mat3> MatB;\n\nint main()\n{\n    double array[][3]={{1.0, 0.0, 5.5}, {0.0, 2.0, 4.0}, {0.0, 0.0, 3.0}};\n    Mat3 E3(array);\n\n    MatB Eb(NB*DIM, NB*DIM);\n\n    for(int i=0; i<NB; i++)\n\tEb.insert(i*DIM, (i+1)*DIM, E3) ;\n\n    mtl::io::tout << \"E3 = \\n\" << E3 << \"\\n\";  \n    mtl::io::tout << \"Eb = \\n\" << Eb << \"\\n\";   \n\n    MTL_THROW_IF((Eb(9, 9) != 1.0), mtl::unexpected_result());\n    MTL_THROW_IF((Eb(9, 10) != 0.0), mtl::unexpected_result());\n    \n    return 0;\n}\n\n", "meta": {"hexsha": "d22da7f57adaa1b3b467df13742ed709d6f8651e", "size": 1197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/block_diagonal2D_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/block_diagonal2D_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/block_diagonal2D_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 27.8372093023, "max_line_length": 94, "alphanum_fraction": 0.6165413534, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5683062485693635}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::survival::data::data::record.hpp                              //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_SURVIVAL_DATA_DATA_RECORDER_HPP_ER_2009\n#define BOOST_STATISTICS_SURVIVAL_DATA_DATA_RECORDER_HPP_ER_2009\n#include <ostream>\n#include <limits>\n#include <boost/operators.hpp>\n#include <boost/format.hpp>\n#include <boost/math/special_functions/fpclassify.hpp> //isinf\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/statistics/survival/constant.hpp>\n#include <boost/statistics/survival/data/data/event.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace survival{\nnamespace data{\n\n// Abstraction for entry time (t) and the failure time (rt). \n//\n// If not set during initialization, the failure time can be set later.\ntemplate<typename T>\nclass record : less_than_comparable<record<T> >{\nprotected:\n    typedef constant<T> const_;\npublic:\n    typedef T value_type;\n    record(); //inf,inf\n    record(value_type t); \n    record(value_type t, value_type rt);\n    // default copy/assign\n    void set_failure_time(value_type rt);\n    value_type entry_time()const;\n    value_type failure_time()const;\n\n    template<typename Archive>\n    void serialize(Archive & ar, const unsigned int version);\n\n    bool operator<(const record& other)const;\n    \nprotected:\n    value_type entry_time_;     //t\n    value_type failure_time_;   //rt\n};\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& out,const record<T>& r);\n    \ntemplate<typename T>\ntypename record<T>::value_type \ntime_since_entry(const record<T>& r, typename record<T>::value_type t);\n        \n// TODO is_at_risk\n    \ntemplate<typename T>    \nevent<T>  make_event(const record<T>& r, typename record<T>::value_type t);\n    \n    // Implementation //\n    \n// Construct\ntemplate<typename T> \nrecord<T>::record():entry_time_(const_::inf_),failure_time_(const_::inf_){}\n\ntemplate<typename T>\nrecord<T>::record(value_type t):entry_time_(t),failure_time_(const_::inf_){}\n\ntemplate<typename T>\nrecord<T>::record(value_type t,value_type rt)\n:entry_time_(t),failure_time_(rt){}\n\n// Assign\ntemplate<typename T>\nvoid record<T>::set_failure_time(value_type rt){\n    static const char* method = \"statistics::survival::record::set_failure_time(%1%)\";\n    if(math::isinf(this->failure_time_)){\n        this->failure_time_ = rt;\n    }else{\n        static const char* err = \" error : overriding failure time\";\n        throw exception(\n            format(method,rt).str(),\n            err,\n            *this\n        );\n    }\n}\n\ntemplate<typename T>\ntemplate<typename Archive>\nvoid record<T>::serialize(Archive & ar, const unsigned int version){\n    ar & entry_time_;\n    ar & failure_time_;\n} \n    \n// Access\n\ntemplate<typename T>\ntypename record<T>::value_type \nrecord<T>::entry_time()const{ return entry_time_; }\n\ntemplate<typename T>\ntypename record<T>::value_type \nrecord<T>::failure_time()const{ return failure_time_; }\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& out,const record<T>& r){\n    out << '(' <<  r.entry_time() << ',' << r.failure_time() << ')';\n    return out; \n}\n    \ntemplate<typename T>\nbool record<T>::operator<(const record<T>& other)const{\n    return ( (this->entry_time()) < other.entry_time() );\n}\n\ntemplate<typename T>\ntypename record<T>::value_type \ntime_since_entry(const record<T>& r, typename record<T>::value_type t)\n{\n    //Warning may be <0\n    return t-r.entry_time();\n}\n\n// TODO is_at_risk\n\ntemplate<typename T>    \nevent<T>  make_event(const record<T>& r, typename record<T>::value_type t){\n    static const char* fun = \"statistics::survival::make_event(%1%,%2)\";\n    typedef typename record<T>::value_type value_t;\n    value_t eps = math::tools::epsilon<T>();\n    value_t dt = time_since_entry(r,t); \n    if(dt>eps){\n        typedef event<T> result_type;\n        bool b = ( r.failure_time() <= dt );\n        value_t rt = b ? r.failure_time() : dt;\n        return result_type(b, rt);\n    }else{\n        static const char* err = \"error: time_since_entry = %1%\";\n        format f(fun); f%r%t;\n        std::string str = f.str();\n        f = format(err); f%dt; str+= f.str();\n        throw std::runtime_error( str );\n    }\n}    \n\n}// data                \n}// survival\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "b787948b816c2d05d41844241c788fdf0c9d631d", "size": 4729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "survival_data copy/boost/statistics/survival/data/data/record.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "survival_data copy/boost/statistics/survival/data/data/record.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "survival_data copy/boost/statistics/survival/data/data/record.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3141025641, "max_line_length": 86, "alphanum_fraction": 0.6354408966, "num_tokens": 1091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5682517407888347}}
{"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// \u6211\u4eec\u9996\u5148\u5305\u62ec\u6240\u6709\u5fc5\u8981\u7684deal.II\u5934\u6587\u4ef6\u548c\u4e00\u4e9bC++\u76f8\u5173\u7684\u6587\u4ef6\u3002\u5b83\u4eec\u4e2d\u7684\u6bcf\u4e00\u4e2a\u90fd\u5df2\u7ecf\u5728\u4ee5\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u8ba8\u8bba\u8fc7\u4e86\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u8fd9\u91cc\u5c31\u4e0d\u505a\u8be6\u7ec6\u4ecb\u7ecd\u4e86\u3002\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// \u6700\u540e\u8fd9\u548c\u4ee5\u524d\u7684\u6240\u6709\u7a0b\u5e8f\u4e00\u6837\u3002\n\nnamespace Step35 \n{ \n  using namespace dealii; \n// @sect3{Run time parameters}  \n\n// \u7531\u4e8e\u6211\u4eec\u7684\u65b9\u6cd5\u6709\u51e0\u4e2a\u53ef\u4ee5\u5fae\u8c03\u7684\u53c2\u6570\uff0c\u6211\u4eec\u628a\u5b83\u4eec\u653e\u5230\u4e00\u4e2a\u5916\u90e8\u6587\u4ef6\u4e2d\uff0c\u8fd9\u6837\u5c31\u53ef\u4ee5\u5728\u8fd0\u884c\u65f6\u786e\u5b9a\u5b83\u4eec\u3002\n\n// \u8fd9\u5c24\u5176\u5305\u62ec\u8f85\u52a9\u53d8\u91cf  $\\phi$  \u7684\u65b9\u7a0b\u8868\u8ff0\uff0c\u4e3a\u6b64\u6211\u4eec\u58f0\u660e\u4e00\u4e2a  <code>enum</code>  \u3002\u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u58f0\u660e\u4e00\u4e2a\u7c7b\uff0c\u5b83\u5c06\u8bfb\u53d6\u548c\u5b58\u50a8\u6211\u4eec\u7684\u7a0b\u5e8f\u8fd0\u884c\u6240\u9700\u7684\u6240\u6709\u53c2\u6570\u3002\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// \u5728\u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u58f0\u660e\u6240\u6709\u7684\u53c2\u6570\u3002\u8fd9\u65b9\u9762\u7684\u7ec6\u8282\u5df2\u7ecf\u5728\u5176\u4ed6\u5730\u65b9\u8ba8\u8bba\u8fc7\u4e86\uff0c\u4f8b\u5982\u5728  step-29  \u3002\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// \u5728\u4e0b\u4e00\u4e2a\u547d\u540d\u7a7a\u95f4\u4e2d\uff0c\u6211\u4eec\u58f0\u660e\u521d\u59cb\u548c\u8fb9\u754c\u6761\u4ef6\u3002\n\n  namespace EquationData \n  { \n\n// \u7531\u4e8e\u6211\u4eec\u9009\u62e9\u4e86\u4e00\u4e2a\u5b8c\u5168\u89e3\u8026\u7684\u516c\u5f0f\uff0c\u6211\u4eec\u5c06\u4e0d\u5229\u7528deal.II\u5904\u7406\u77e2\u91cf\u503c\u95ee\u9898\u7684\u80fd\u529b\u3002\u7136\u800c\uff0c\u6211\u4eec\u786e\u5b9e\u5e0c\u671b\u4e3a\u65b9\u7a0b\u6570\u636e\u4f7f\u7528\u4e00\u4e2a\u72ec\u7acb\u4e8e\u7ef4\u5ea6\u7684\u63a5\u53e3\u3002\u4e3a\u4e86\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u7684\u51fd\u6570\u5e94\u8be5\u80fd\u591f\u77e5\u9053\u6211\u4eec\u76ee\u524d\u5728\u54ea\u4e2a\u7a7a\u95f4\u5206\u91cf\u4e0a\u5de5\u4f5c\uff0c\u800c\u4e14\u6211\u4eec\u5e94\u8be5\u80fd\u591f\u6709\u4e00\u4e2a\u901a\u7528\u7684\u63a5\u53e3\u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002\u4e0b\u9762\u7684\u7c7b\u662f\u5728\u8fd9\u4e2a\u65b9\u5411\u4e0a\u7684\u4e00\u4e2a\u5c1d\u8bd5\u3002\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// \u6709\u4e86\u8fd9\u4e2a\u7c7b\u7684\u5b9a\u4e49\uff0c\u6211\u4eec\u58f0\u660e\u63cf\u8ff0\u901f\u5ea6\u548c\u538b\u529b\u7684\u8fb9\u754c\u6761\u4ef6\u7684\u7c7b\u3002\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// \u73b0\u5728\u662f\u7a0b\u5e8f\u7684\u4e3b\u7c7b\u3002\u5b83\u5b9e\u73b0\u4e86\u7eb3\u7ef4-\u65af\u6258\u514b\u65af\u65b9\u7a0b\u7684\u5404\u79cd\u7248\u672c\u7684\u6295\u5f71\u65b9\u6cd5\u3002\u8003\u8651\u5230\u4ecb\u7ecd\u4e2d\u7ed9\u51fa\u7684\u5b9e\u73b0\u7ec6\u8282\uff0c\u6240\u6709\u65b9\u6cd5\u548c\u6210\u5458\u53d8\u91cf\u7684\u540d\u79f0\u5e94\u8be5\u662f\u4e0d\u8a00\u81ea\u660e\u7684\u3002\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// \u63a5\u4e0b\u6765\u7684\u51e0\u4e2a\u7ed3\u6784\u548c\u51fd\u6570\u662f\u7528\u6765\u505a\u5404\u79cd\u5e76\u884c\u7684\u4e8b\u60c5\u3002\u5b83\u4eec\u9075\u5faa @ref threads \u4e2d\u89c4\u5b9a\u7684\u65b9\u6848\uff0c\u4f7f\u7528WorkStream\u7c7b\u3002\u6b63\u5982\u90a3\u91cc\u6240\u89e3\u91ca\u7684\uff0c\u8fd9\u9700\u8981\u6211\u4eec\u4e3a\u6bcf\u4e2a\u88c5\u914d\u5668\u58f0\u660e\u4e24\u4e2a\u7ed3\u6784\uff0c\u4e00\u4e2a\u662f\u6bcf\u4e2a\u4efb\u52a1\u7684\u6570\u636e\uff0c\u4e00\u4e2a\u662fscratch\u6570\u636e\u7ed3\u6784\u3002\u7136\u540e\uff0c\u8fd9\u4e9b\u7ed3\u6784\u88ab\u79fb\u4ea4\u7ed9\u7ec4\u88c5\u672c\u5730\u8d21\u732e\u7684\u51fd\u6570\uff0c\u5e76\u5c06\u8fd9\u4e9b\u672c\u5730\u8d21\u732e\u590d\u5236\u5230\u5168\u5c40\u5bf9\u8c61\u4e0a\u3002\n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4e00\u4e2a\u7279\u6b8a\u4e4b\u5904\u5728\u4e8e\uff0c\u6211\u4eec\u5e76\u4e0d\u662f\u53ea\u6709\u4e00\u4e2aDoFHandler\u5bf9\u8c61\u6765\u4ee3\u8868\u901f\u5ea6\u548c\u538b\u529b\uff0c\u800c\u662f\u4e3a\u8fd9\u4e24\u79cd\u53d8\u91cf\u4f7f\u7528\u5355\u72ec\u7684DoFHandler\u5bf9\u8c61\u3002\u5f53\u6211\u4eec\u60f3\u628a\u6d89\u53ca\u8fd9\u4e24\u4e2a\u53d8\u91cf\u7684\u6761\u6b3e\uff0c\u5982\u901f\u5ea6\u7684\u53d1\u6563\u548c\u538b\u529b\u7684\u68af\u5ea6\uff0c\u4e58\u4ee5\u5404\u81ea\u7684\u6d4b\u8bd5\u51fd\u6570\u65f6\uff0c\u6211\u4eec\u8981\u4e3a\u8fd9\u79cd\u4f18\u5316\u4ed8\u8d39\u3002\u5728\u8fd9\u6837\u505a\u7684\u65f6\u5019\uff0c\u6211\u4eec\u4e0d\u80fd\u53ea\u4f7f\u7528\u4e00\u4e2aFEValues\u5bf9\u8c61\uff0c\u800c\u662f\u9700\u8981\u4e24\u4e2a\uff0c\u800c\u4e14\u9700\u8981\u7528\u5355\u5143\u683c\u8fed\u4ee3\u5668\u6765\u521d\u59cb\u5316\u5b83\u4eec\uff0c\u8fd9\u4e9b\u5355\u5143\u683c\u8fed\u4ee3\u5668\u6307\u5411\u4e09\u89d2\u5f62\u4e2d\u7684\u540c\u4e00\u4e2a\u5355\u5143\u683c\uff0c\u4f46\u4e0d\u540c\u7684DoFHandlers\u3002\n\n// \u4e3a\u4e86\u5728\u5b9e\u8df5\u4e2d\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u58f0\u660e\u4e00\u4e2a \"\u540c\u6b65 \"\u8fed\u4ee3\u5668--\u4e00\u4e2a\u5185\u90e8\u7531\u51e0\u4e2a\uff08\u5728\u6211\u4eec\u7684\u4f8b\u5b50\u4e2d\u662f\u4e24\u4e2a\uff09\u8fed\u4ee3\u5668\u7ec4\u6210\u7684\u5bf9\u8c61\uff0c\u6bcf\u6b21\u540c\u6b65\u8fed\u4ee3\u5668\u5411\u524d\u79fb\u52a8\u4e00\u6b65\uff0c\u5185\u90e8\u5b58\u50a8\u7684\u6bcf\u4e2a\u8fed\u4ee3\u5668\u4e5f\u5411\u524d\u79fb\u52a8\u4e00\u6b65\uff0c\u4ece\u800c\u59cb\u7ec8\u4fdd\u6301\u540c\u6b65\u3002\u78b0\u5de7\u7684\u662f\uff0c\u6709\u4e00\u4e2adeal.II\u7c7b\u53ef\u4ee5\u4fc3\u8fdb\u8fd9\u79cd\u4e8b\u60c5\u3002\u8fd9\u91cc\u91cd\u8981\u7684\u662f\u8981\u77e5\u9053\uff0c\u5efa\u7acb\u5728\u540c\u4e00\u4e2a\u4e09\u89d2\u5f62\u4e0a\u7684\u4e24\u4e2aDoFHandler\u5bf9\u8c61\u5c06\u4ee5\u76f8\u540c\u7684\u987a\u5e8f\u8d70\u8fc7\u4e09\u89d2\u5f62\u7684\u5355\u5143\u3002\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// \u540c\u6837\u7684\u4e00\u822c\u5e03\u5c40\u4e5f\u9002\u7528\u4e8e\u4ee5\u4e0b\u5b9e\u73b0\u5e73\u6d41\u9879\u7ec4\u88c5\u7684\u7c7b\u548c\u51fd\u6570\u3002\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// \u6700\u540e\u51e0\u4e2a\u51fd\u6570\u5b9e\u73b0\u4e86\u6269\u6563\u89e3\u4ee5\u53ca\u8f93\u51fa\u7684\u540e\u5904\u7406\uff0c\u5305\u62ec\u8ba1\u7b97\u901f\u5ea6\u7684\u66f2\u7ebf\u3002\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// \u5728\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u53ea\u662f\u4ece\u4f5c\u4e3a\u53c2\u6570\u4f20\u9012\u7684 <code>Data_Storage</code> \u5bf9\u8c61\u4e2d\u8bfb\u53d6\u6240\u6709\u6570\u636e\uff0c\u9a8c\u8bc1\u6211\u4eec\u8bfb\u53d6\u7684\u6570\u636e\u662f\u5426\u5408\u7406\uff0c\u6700\u540e\uff0c\u521b\u5efa\u4e09\u89d2\u5f62\u5e76\u52a0\u8f7d\u521d\u59cb\u6570\u636e\u3002\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// \u521b\u5efa\u4e09\u89d2\u5f62\u7684\u65b9\u6cd5\uff0c\u5e76\u5c06\u5176\u7ec6\u5316\u5230\u6240\u9700\u7684\u6b21\u6570\u3002\u5728\u521b\u5efa\u4e09\u89d2\u5f62\u4e4b\u540e\uff0c\u5b83\u521b\u5efa\u4e86\u4e0e\u7f51\u683c\u76f8\u5173\u7684\u6570\u636e\uff0c\u5373\u5206\u914d\u81ea\u7531\u5ea6\u548c\u91cd\u65b0\u7f16\u53f7\uff0c\u5e76\u521d\u59cb\u5316\u6211\u4eec\u5c06\u4f7f\u7528\u7684\u77e9\u9635\u548c\u5411\u91cf\u3002\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// \u8be5\u65b9\u6cd5\u521b\u5efa\u5e38\u6570\u77e9\u9635\u5e76\u52a0\u8f7d\u521d\u59cb\u6570\u636e\u3002\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// \u5728\u8fd9\u7ec4\u65b9\u6cd5\u4e2d\uff0c\u6211\u4eec\u521d\u59cb\u5316\u4e86\u7a00\u758f\u6a21\u5f0f\u3001\u7ea6\u675f\u6761\u4ef6\uff08\u5982\u679c\u6709\u7684\u8bdd\uff09\u5e76\u7ec4\u88c5\u4e86\u4e0d\u4f9d\u8d56\u4e8e\u65f6\u95f4\u6b65\u957f\u7684\u77e9\u9635  <code>dt</code>  \u3002\u8bf7\u6ce8\u610f\uff0c\u5bf9\u4e8e\u62c9\u666e\u62c9\u65af\u77e9\u9635\u548c\u8d28\u91cf\u77e9\u9635\uff0c\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528\u5e93\u4e2d\u7684\u51fd\u6570\u6765\u505a\u8fd9\u4ef6\u4e8b\u3002\u56e0\u4e3a\u8fd9\u4e2a\u51fd\u6570\u7684\u6602\u8d35\u64cd\u4f5c--\u521b\u5efa\u4e24\u4e2a\u77e9\u9635--\u662f\u5b8c\u5168\u72ec\u7acb\u7684\uff0c\u6211\u4eec\u539f\u5219\u4e0a\u53ef\u4ee5\u628a\u5b83\u4eec\u6807\u8bb0\u4e3a\u53ef\u4ee5\u4f7f\u7528 Threads::new_task \u51fd\u6570\u8fdb\u884c%\u5e76\u884c\u5de5\u4f5c\u7684\u4efb\u52a1\u3002\u6211\u4eec\u4e0d\u4f1a\u5728\u8fd9\u91cc\u8fd9\u6837\u505a\uff0c\u56e0\u4e3a\u8fd9\u4e9b\u51fd\u6570\u5728\u5185\u90e8\u5df2\u7ecf\u88ab\u5e76\u884c\u5316\u4e86\uff0c\u7279\u522b\u662f\u7531\u4e8e\u5f53\u524d\u7684\u51fd\u6570\u5728\u6bcf\u4e2a\u7a0b\u5e8f\u8fd0\u884c\u4e2d\u53ea\u88ab\u8c03\u7528\u4e00\u6b21\uff0c\u6240\u4ee5\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u4e0d\u4f1a\u4ea7\u751f\u8d39\u7528\u3002\u7136\u800c\uff0c\u5fc5\u8981\u7684\u4fee\u6539\u5c06\u662f\u975e\u5e38\u76f4\u63a5\u7684\u3002\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//\u4f5c\u7528\u4e8e\u538b\u529b\u7a7a\u95f4\u7684\u77e9\u9635\u7684\u521d\u59cb\u5316\u4e0e\u4f5c\u7528\u4e8e\u901f\u5ea6\u7a7a\u95f4\u7684\u77e9\u9635\u76f8\u4f3c\u3002\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// \u5bf9\u4e8e\u68af\u5ea6\u7b97\u5b50\uff0c\u6211\u4eec\u4ece\u521d\u59cb\u5316\u7a00\u758f\u6a21\u5f0f\u548c\u538b\u7f29\u5b83\u5f00\u59cb\u3002\u8fd9\u91cc\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0c\u68af\u5ea6\u7b97\u5b50\u4ece\u538b\u529b\u7a7a\u95f4\u4f5c\u7528\u5230\u901f\u5ea6\u7a7a\u95f4\uff0c\u6240\u4ee5\u6211\u4eec\u5fc5\u987b\u5904\u7406\u4e24\u4e2a\u4e0d\u540c\u7684\u6709\u9650\u5143\u7a7a\u95f4\u3002\u4e3a\u4e86\u4fdd\u6301\u5faa\u73af\u7684\u540c\u6b65\uff0c\u6211\u4eec\u4f7f\u7528\u4e4b\u524d\u5b9a\u4e49\u7684\u522b\u540d\uff0c\u5373 <code>PairedIterators</code> and <code>IteratorPair</code>  \u3002\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// \u8fd9\u662f\u65f6\u95f4\u884c\u8fdb\u51fd\u6570\uff0c\u4ece <code>t_0</code> \u5f00\u59cb\uff0c\u4f7f\u7528\u65f6\u95f4\u6b65\u957f <code>dt</code> \u7684\u6295\u5f71\u6cd5\u5728\u65f6\u95f4\u4e0a\u524d\u8fdb\uff0c\u76f4\u5230 <code>T</code>  \u3002\n\n// \u5b83\u7684\u7b2c\u4e8c\u4e2a\u53c2\u6570 <code>verbose</code> \u8868\u793a\u8be5\u51fd\u6570\u662f\u5426\u5e94\u8be5\u8f93\u51fa\u5b83\u5728\u4efb\u4f55\u7279\u5b9a\u65f6\u523b\u6b63\u5728\u505a\u4ec0\u4e48\u7684\u4fe1\u606f\uff1a\u4f8b\u5982\uff0c\u5b83\u5c06\u8bf4\u660e\u6211\u4eec\u662f\u5426\u6b63\u5728\u8fdb\u884c\u6269\u6563\u3001\u6295\u5f71\u5b50\u6b65\u9aa4\uff1b\u66f4\u65b0\u524d\u7f6e\u6761\u4ef6\u5668\u7b49\u7b49\u3002\u6211\u4eec\u6ca1\u6709\u4f7f\u7528\u50cf\n// @code\n//    if (verbose) std::cout << \"something\";\n//  @endcode\n//  \u90a3\u6837\u7684\u4ee3\u7801\u6765\u5b9e\u73b0\u8fd9\u79cd\u8f93\u51fa\uff0c\u800c\u662f\u4f7f\u7528ConditionalOStream\u7c7b\u6765\u4e3a\u6211\u4eec\u505a\u8fd9\u4e2a\u3002\u8be5\u7c7b\u63a5\u53d7\u4e00\u4e2a\u8f93\u51fa\u6d41\u548c\u4e00\u4e2a\u6761\u4ef6\uff0c\u8be5\u6761\u4ef6\u8868\u660e\u4f60\u4f20\u9012\u7ed9\u5b83\u7684\u4e1c\u897f\u662f\u5426\u5e94\u8be5\u88ab\u4f20\u9012\u5230\u7ed9\u5b9a\u7684\u8f93\u51fa\u6d41\uff0c\u6216\u8005\u5e94\u8be5\u88ab\u5ffd\u7565\u3002\u8fd9\u6837\uff0c\u4e0a\u9762\u7684\u4ee3\u7801\u5c31\u53d8\u6210\u4e86\n//  @code\n//    verbose_cout << \"something\";\n//  @endcode\uff0c\u5e76\u4e14\u5728\u4efb\u4f55\u60c5\u51b5\u4e0b\u90fd\u4f1a\u505a\u6b63\u786e\u7684\u4e8b\u60c5\u3002\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// \u6269\u6563\u6b65\u9aa4\u7684\u5b9e\u73b0\u3002\u8bf7\u6ce8\u610f\uff0c\u6602\u8d35\u7684\u64cd\u4f5c\u662f\u51fd\u6570\u672b\u5c3e\u7684\u6269\u6563\u89e3\uff0c\u6211\u4eec\u5fc5\u987b\u4e3a\u6bcf\u4e2a\u901f\u5ea6\u5206\u91cf\u505a\u4e00\u6b21\u3002\u4e3a\u4e86\u52a0\u5feb\u8fdb\u5ea6\uff0c\u6211\u4eec\u5141\u8bb8\u4ee5%\u5e76\u884c\u65b9\u5f0f\u8fdb\u884c\uff0c\u4f7f\u7528 Threads::new_task \u51fd\u6570\uff0c\u786e\u4fdd <code>dim</code> \u7684\u6c42\u89e3\u90fd\u5f97\u5230\u5904\u7406\uff0c\u5e76\u88ab\u5b89\u6392\u5230\u53ef\u7528\u7684\u5904\u7406\u5668\u4e0a\uff1a\u5982\u679c\u4f60\u7684\u673a\u5668\u6709\u4e00\u4e2a\u4ee5\u4e0a\u7684\u5904\u7406\u5668\u6838\u5fc3\uff0c\u5e76\u4e14\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u5176\u4ed6\u90e8\u5206\u76ee\u524d\u6ca1\u6709\u4f7f\u7528\u8d44\u6e90\uff0c\u90a3\u4e48\u6269\u6563\u6c42\u89e3\u5c06\u4ee5%\u5e76\u884c\u65b9\u5f0f\u8fd0\u884c\u3002\u53e6\u4e00\u65b9\u9762\uff0c\u5982\u679c\u4f60\u7684\u7cfb\u7edf\u53ea\u6709\u4e00\u4e2a\u5904\u7406\u5668\u6838\u5fc3\uff0c\u90a3\u4e48\u4ee5%\u5e76\u884c\u65b9\u5f0f\u8fd0\u884c\u5c06\u662f\u4f4e\u6548\u7684\uff08\u56e0\u4e3a\u5b83\u5bfc\u81f4\u4e86\uff0c\u4f8b\u5982\uff0c\u7f13\u5b58\u62e5\u5835\uff09\uff0c\u4e8b\u60c5\u5c06\u88ab\u987a\u5e8f\u5730\u6267\u884c\u3002\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// \u4e0b\u9762\u7684\u51e0\u4e2a\u51fd\u6570\u662f\u5173\u4e8e\u96c6\u5408\u5e73\u6d41\u9879\u7684\uff0c\u5e73\u6d41\u9879\u662f\u6269\u6563\u6b65\u9aa4\u7684\u7cfb\u7edf\u77e9\u9635\u7684\u4e00\u90e8\u5206\uff0c\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u90fd\u4f1a\u53d1\u751f\u53d8\u5316\u3002\u5982\u4e0a\u6240\u8ff0\uff0c\u6211\u4eec\u5c06\u4f7f\u7528WorkStream\u7c7b\u548c\u6587\u4ef6\u6a21\u5757 @ref threads \u4e2d\u63cf\u8ff0\u7684\u5176\u4ed6\u8bbe\u65bd\uff0c\u5728\u6240\u6709\u5355\u5143\u4e0a\u5e73\u884c\u8fd0\u884c\u88c5\u914d\u5faa\u73af\u3002\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// \u8fd9\u5b9e\u73b0\u4e86\u6295\u5f71\u7684\u6b65\u9aa4\u3002\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// \u8fd9\u662f\u6295\u5f71\u6cd5\u7684\u538b\u529b\u66f4\u65b0\u6b65\u9aa4\u3002\u5b83\u5b9e\u73b0\u4e86\u8be5\u65b9\u6cd5\u7684\u6807\u51c6\u8868\u8ff0\uff0c\u5373\n//  @f[ p^{n+1} = p^n +\n//  \\phi^{n+1}, \n//  @f]\n//  \u6216\u65cb\u8f6c\u5f62\u5f0f\uff0c\u5373\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// \u8be5\u65b9\u6cd5\u7ed8\u5236\u4e86\u5f53\u524d\u7684\u89e3\u51b3\u65b9\u6848\u3002\u4e3b\u8981\u7684\u56f0\u96be\u662f\uff0c\u6211\u4eec\u60f3\u521b\u5efa\u4e00\u4e2a\u5355\u4e00\u7684\u8f93\u51fa\u6587\u4ef6\uff0c\u5176\u4e2d\u5305\u542b\u6240\u6709\u7684\u901f\u5ea6\u5206\u91cf\u3001\u538b\u529b\u4ee5\u53ca\u6d41\u52a8\u7684\u6da1\u5ea6\u7684\u6570\u636e\u3002\u53e6\u4e00\u65b9\u9762\uff0c\u901f\u5ea6\u548c\u538b\u529b\u5b58\u5728\u4e8e\u4e0d\u540c\u7684DoFHandler\u5bf9\u8c61\u4e2d\uff0c\u56e0\u6b64\u4e0d\u80fd\u7528\u4e00\u4e2aDataOut\u5bf9\u8c61\u5199\u5165\u540c\u4e00\u4e2a\u6587\u4ef6\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5fc5\u987b\u66f4\u52aa\u529b\u5730\u628a\u5404\u79cd\u6570\u636e\u653e\u5230\u4e00\u4e2aDoFHandler\u5bf9\u8c61\u4e2d\uff0c\u7136\u540e\u7528\u5b83\u6765\u9a71\u52a8\u56fe\u5f62\u8f93\u51fa\u3002\n\n// \u6211\u4eec\u4e0d\u4f1a\u5728\u8fd9\u91cc\u8be6\u7ec6\u8bf4\u660e\u8fd9\u4e2a\u8fc7\u7a0b\uff0c\u800c\u662f\u53c2\u8003  step-32  \uff0c\u90a3\u91cc\u4f7f\u7528\u4e86\u4e00\u4e2a\u7c7b\u4f3c\u7684\u7a0b\u5e8f\uff08\u5e76\u6709\u8bb0\u5f55\uff09\uff0c\u4e3a\u6240\u6709\u53d8\u91cf\u521b\u5efa\u4e00\u4e2a\u8054\u5408\u7684 DoFHandler \u5bf9\u8c61\u3002\n\n// \u6211\u4eec\u8fd8\u6ce8\u610f\u5230\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u5c06\u6da1\u5ea6\u4f5c\u4e3a\u4e00\u4e2a\u5355\u72ec\u7684\u51fd\u6570\u4e2d\u7684\u6807\u91cf\u6765\u8ba1\u7b97\uff0c\u4f7f\u7528 $L^2$ \u91cf\u7684\u6295\u5f71 $\\text{curl} u$ \u5230\u7528\u4e8e\u901f\u5ea6\u6210\u5206\u7684\u6709\u9650\u5143\u7a7a\u95f4\u3002\u4f46\u539f\u5219\u4e0a\uff0c\u6211\u4eec\u4e5f\u53ef\u4ee5\u4ece\u901f\u5ea6\u4e2d\u8ba1\u7b97\u51fa\u4e00\u4e2a\u70b9\u72b6\u91cf\uff0c\u5e76\u901a\u8fc7 step-29 \u548c step-33 \u4e2d\u8ba8\u8bba\u7684DataPostprocessor\u673a\u5236\u5b9e\u73b0\u3002\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// \u4e0b\u9762\u662f\u4e00\u4e2a\u8f85\u52a9\u51fd\u6570\uff0c\u901a\u8fc7\u5c06 $\\text{curl} u$ \u9879\u6295\u5f71\u5230\u7528\u4e8e\u901f\u5ea6\u5206\u91cf\u7684\u6709\u9650\u5143\u7a7a\u95f4\u6765\u8ba1\u7b97\u6da1\u5ea6\u3002\u8fd9\u4e2a\u51fd\u6570\u53ea\u6709\u5728\u6211\u4eec\u751f\u6210\u56fe\u5f62\u8f93\u51fa\u65f6\u624d\u4f1a\u88ab\u8c03\u7528\uff0c\u6240\u4ee5\u4e0d\u662f\u5f88\u9891\u7e41\uff0c\u56e0\u6b64\u6211\u4eec\u6ca1\u6709\u50cf\u5bf9\u5f85\u5176\u4ed6\u88c5\u914d\u51fd\u6570\u90a3\u6837\uff0c\u9ebb\u70e6\u5730\u4f7f\u7528WorkStream\u6982\u5ff5\u6765\u5e76\u884c\u5316\u5b83\u3002\u4e0d\u8fc7\uff0c\u5982\u679c\u9700\u8981\u7684\u8bdd\uff0c\u8fd9\u5e94\u8be5\u4e0d\u4f1a\u592a\u590d\u6742\u3002\u6b64\u5916\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u7684\u5b9e\u73b0\u53ea\u9002\u7528\u4e8e2D\uff0c\u6240\u4ee5\u5982\u679c\u4e0d\u662f\u8fd9\u79cd\u60c5\u51b5\uff0c\u6211\u4eec\u5c31\u653e\u5f03\u4e86\u3002\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// \u4e3b\u51fd\u6570\u770b\u8d77\u6765\u548c\u5176\u4ed6\u6240\u6709\u7684\u6559\u7a0b\u7a0b\u5e8f\u975e\u5e38\u76f8\u4f3c\uff0c\u6240\u4ee5\u8fd9\u91cc\u6ca1\u6709\u4ec0\u4e48\u53ef\u8bc4\u8bba\u7684\u3002\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 <Eigen/SVD>\n\n#include \"beta.h\"\n#include \"input_validation.h\"\n\nusing namespace Eigen;\n\n/*\nbeta = [clus_1, clus_2, ..., clus_c, loc_1, loc_2, ..., loc_r]\n*/\n\nVectorXd get_beta_extended(const VectorXd& beta) {\n  size_t m = beta.size();\n  VectorXd beta_ext(m + 1);\n  beta_ext[m] = 0;\n  for (size_t idx = 0; idx < m; idx++) {\n    beta_ext[idx] = beta[idx];\n  }\n  \n  return beta_ext;\n}\n\nvoid beta_description(const MatrixXi& x, const MatrixXi& y, const VectorXd& beta) {\n  check_x_y(x, y);\n  \n  size_t clusters = y.rows();\n  size_t loci = x.cols();\n  \n  for (size_t j = 0; j < clusters; j++) {\n    OUTPUT << \"clus_\" << (j+1) << \" \";\n  }\n  \n  for (size_t k = 0; k < (loci - 1); k++) {\n    if (k > 0) {\n      OUTPUT << \" \";\n    }\n    \n    OUTPUT << \"loc_\" << (k+1);    \n  }\n}\n\nMatrixXd beta_to_discrete_laplace_parameters(const MatrixXi& x, const MatrixXi& y, const VectorXd& beta) {\n  check_x_y(x, y);\n  \n  size_t clusters = y.rows();\n  size_t loci = x.cols();\n  \n  VectorXd beta_ext = get_beta_extended(beta);\n  MatrixXd pars(clusters, loci);\n  \n  for (size_t j = 0; j < clusters; j++) {\n    double b_j = beta_ext[j];\n    \n    for (size_t k = 0; k < loci; k++) {\n      double b_k = beta_ext[clusters + k];\n      double p = std::exp(b_j + b_k);\n      pars(j, k) = p;      \n    }\n  }\n  \n  return pars;\n}\n\n", "meta": {"hexsha": "d88ce4b0f7d2ff72a052158796a767b67d9513dc", "size": 1306, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/beta.cpp", "max_stars_repo_name": "mikldk/libdisclapmix2", "max_stars_repo_head_hexsha": "fd5097096094345fa83ac34ba98b14aa233cc00b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/beta.cpp", "max_issues_repo_name": "mikldk/libdisclapmix2", "max_issues_repo_head_hexsha": "fd5097096094345fa83ac34ba98b14aa233cc00b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/beta.cpp", "max_forks_repo_name": "mikldk/libdisclapmix2", "max_forks_repo_head_hexsha": "fd5097096094345fa83ac34ba98b14aa233cc00b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.40625, "max_line_length": 106, "alphanum_fraction": 0.5666156202, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5682517316796698}}
{"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": "/**\n * @file feedforward_network_test.cpp\n * @author Marcus Edel\n * @author Palash Ahuja\n *\n * Tests the feed forward network.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>\n#include <mlpack/methods/ann/activation_functions/tanh_function.hpp>\n\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n\n#include <mlpack/methods/ann/layer/bias_layer.hpp>\n#include <mlpack/methods/ann/layer/linear_layer.hpp>\n#include <mlpack/methods/ann/layer/base_layer.hpp>\n#include <mlpack/methods/ann/layer/dropout_layer.hpp>\n#include <mlpack/methods/ann/layer/binary_classification_layer.hpp>\n#include <mlpack/methods/ann/layer/dropconnect_layer.hpp>\n\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/performance_functions/mse_function.hpp>\n#include <mlpack/core/optimizers/rmsprop/rmsprop.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\nusing namespace mlpack::optimization;\n\nBOOST_AUTO_TEST_SUITE(FeedForwardNetworkTest);\n\n/**\n * Train and evaluate a vanilla network with the specified structure.\n */\ntemplate<\n    typename PerformanceFunction,\n    typename OutputLayerType,\n    typename PerformanceFunctionType,\n    typename MatType = arma::mat\n>\nvoid BuildVanillaNetwork(MatType& trainData,\n                         MatType& trainLabels,\n                         MatType& testData,\n                         MatType& testLabels,\n                         const size_t hiddenLayerSize,\n                         const size_t maxEpochs,\n                         const double classificationErrorThreshold)\n{\n  /*\n   * Construct a feed forward network with trainData.n_rows input nodes,\n   * hiddenLayerSize hidden nodes and trainLabels.n_rows output nodes. The\n   * network structure looks like:\n   *\n   *  Input         Hidden        Output\n   *  Layer         Layer         Layer\n   * +-----+       +-----+       +-----+\n   * |     |       |     |       |     |\n   * |     +------>|     +------>|     |\n   * |     |     +>|     |     +>|     |\n   * +-----+     | +--+--+     | +-----+\n   *             |             |\n   *  Bias       |  Bias       |\n   *  Layer      |  Layer      |\n   * +-----+     | +-----+     |\n   * |     |     | |     |     |\n   * |     +-----+ |     +-----+\n   * |     |       |     |\n   * +-----+       +-----+\n   */\n\n  LinearLayer<> inputLayer(trainData.n_rows, hiddenLayerSize);\n  BiasLayer<> inputBiasLayer(hiddenLayerSize);\n  BaseLayer<PerformanceFunction> inputBaseLayer;\n\n  LinearLayer<> hiddenLayer1(hiddenLayerSize, trainLabels.n_rows);\n  BiasLayer<> hiddenBiasLayer1(trainLabels.n_rows);\n  BaseLayer<PerformanceFunction> outputLayer;\n\n  OutputLayerType classOutputLayer;\n\n  auto modules = std::tie(inputLayer, inputBiasLayer, inputBaseLayer,\n                          hiddenLayer1, hiddenBiasLayer1, outputLayer);\n\n  FFN<decltype(modules), decltype(classOutputLayer), RandomInitialization,\n      PerformanceFunctionType> net(modules, classOutputLayer);\n\n  RMSprop<decltype(net)> opt(net, 0.01, 0.88, 1e-8,\n      maxEpochs * trainData.n_cols, 1e-18);\n\n  net.Train(trainData, trainLabels, opt);\n\n  MatType prediction;\n  net.Predict(testData, prediction);\n\n  size_t error = 0;\n  for (size_t i = 0; i < testData.n_cols; i++)\n  {\n    if (arma::sum(arma::sum(\n        arma::abs(prediction.col(i) - testLabels.col(i)))) == 0)\n    {\n      error++;\n    }\n  }\n\n  double classificationError = 1 - double(error) / testData.n_cols;\n  BOOST_REQUIRE_LE(classificationError, classificationErrorThreshold);\n}\n\n/**\n * Train the vanilla network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(VanillaNetworkTest)\n{\n  // Load the dataset.\n  arma::mat dataset;\n  data::Load(\"thyroid_train.csv\", dataset, true);\n\n  arma::mat trainData = dataset.submat(0, 0, dataset.n_rows - 4,\n      dataset.n_cols - 1);\n  arma::mat trainLabels = dataset.submat(dataset.n_rows - 3, 0,\n      dataset.n_rows - 1, dataset.n_cols - 1);\n\n  data::Load(\"thyroid_test.csv\", dataset, true);\n\n  arma::mat testData = dataset.submat(0, 0, dataset.n_rows - 4,\n      dataset.n_cols - 1);\n  arma::mat testLabels = dataset.submat(dataset.n_rows - 3, 0,\n      dataset.n_rows - 1, dataset.n_cols - 1);\n\n  // Vanilla neural net with logistic activation function.\n  // Because 92 percent of the patients are not hyperthyroid the neural\n  // network must be significant better than 92%.\n  BuildVanillaNetwork<LogisticFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n      (trainData, trainLabels, testData, testLabels, 8, 200, 0.1);\n\n  dataset.load(\"mnist_first250_training_4s_and_9s.arm\");\n\n  // Normalize each point since these are images.\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    dataset.col(i) /= norm(dataset.col(i), 2);\n\n  arma::mat labels = arma::zeros(1, dataset.n_cols);\n  labels.submat(0, labels.n_cols / 2, 0, labels.n_cols - 1).fill(1);\n\n  // Vanilla neural net with logistic activation function.\n  BuildVanillaNetwork<LogisticFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n      (dataset, labels, dataset, labels, 30, 30, 0.4);\n\n  // Vanilla neural net with tanh activation function.\n  BuildVanillaNetwork<TanhFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n    (dataset, labels, dataset, labels, 10, 30, 0.4);\n}\n\n/**\n * Train and evaluate a Dropout network with the specified structure.\n */\ntemplate<\n    typename PerformanceFunction,\n    typename OutputLayerType,\n    typename PerformanceFunctionType,\n    typename MatType = arma::mat\n>\nvoid BuildDropoutNetwork(MatType& trainData,\n                         MatType& trainLabels,\n                         MatType& testData,\n                         MatType& testLabels,\n                         const size_t hiddenLayerSize,\n                         const size_t maxEpochs,\n                         const double classificationErrorThreshold)\n{\n  /*\n   * Construct a feed forward network with trainData.n_rows input nodes,\n   * hiddenLayerSize hidden nodes and trainLabels.n_rows output nodes. The\n   * network structure looks like:\n   *\n   *  Input         Hidden        Dropout      Output\n   *  Layer         Layer         Layer        Layer\n   * +-----+       +-----+       +-----+       +-----+\n   * |     |       |     |       |     |       |     |\n   * |     +------>|     +------>|     +------>|     |\n   * |     |     +>|     |       |     |       |     |\n   * +-----+     | +--+--+       +-----+       +-----+\n   *             |\n   *  Bias       |\n   *  Layer      |\n   * +-----+     |\n   * |     |     |\n   * |     +-----+\n   * |     |\n   * +-----+\n   */\n\n  LinearLayer<> inputLayer(trainData.n_rows, hiddenLayerSize);\n  BiasLayer<> biasLayer(hiddenLayerSize);\n  BaseLayer<PerformanceFunction> hiddenLayer0;\n  DropoutLayer<> dropoutLayer0;\n\n  LinearLayer<> hiddenLayer1(hiddenLayerSize, trainLabels.n_rows);\n  BaseLayer<PerformanceFunction> outputLayer;\n\n  OutputLayerType classOutputLayer;\n\n  auto modules = std::tie(inputLayer, biasLayer, hiddenLayer0, dropoutLayer0,\n                          hiddenLayer1, outputLayer);\n\n  FFN<decltype(modules), decltype(classOutputLayer), RandomInitialization,\n      PerformanceFunctionType> net(modules, classOutputLayer);\n\n  RMSprop<decltype(net)> opt(net, 0.01, 0.88, 1e-8,\n      maxEpochs * trainData.n_cols, 1e-18);\n\n  net.Train(trainData, trainLabels, opt);\n\n  MatType prediction;\n  net.Predict(testData, prediction);\n\n  size_t error = 0;\n  for (size_t i = 0; i < testData.n_cols; i++)\n  {\n    if (arma::sum(arma::sum(\n        arma::abs(prediction.col(i) - testLabels.col(i)))) == 0)\n    {\n      error++;\n    }\n  }\n\n  double classificationError = 1 - double(error) / testData.n_cols;\n  BOOST_REQUIRE_LE(classificationError, classificationErrorThreshold);\n}\n\n/**\n * Train the dropout network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(DropoutNetworkTest)\n{\n  // Load the dataset.\n  arma::mat dataset;\n  data::Load(\"thyroid_train.csv\", dataset, true);\n\n  arma::mat trainData = dataset.submat(0, 0, dataset.n_rows - 4,\n      dataset.n_cols - 1);\n  arma::mat trainLabels = dataset.submat(dataset.n_rows - 3, 0,\n      dataset.n_rows - 1, dataset.n_cols - 1);\n\n  data::Load(\"thyroid_test.csv\", dataset, true);\n\n  arma::mat testData = dataset.submat(0, 0, dataset.n_rows - 4,\n      dataset.n_cols - 1);\n  arma::mat testLabels = dataset.submat(dataset.n_rows - 3, 0,\n      dataset.n_rows - 1, dataset.n_cols - 1);\n\n  // Vanilla neural net with logistic activation function.\n  // Because 92 percent of the patients are not hyperthyroid the neural\n  // network must be significant better than 92%.\n  BuildDropoutNetwork<LogisticFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n      (trainData, trainLabels, testData, testLabels, 4, 100, 0.1);\n\n  dataset.load(\"mnist_first250_training_4s_and_9s.arm\");\n\n  // Normalize each point since these are images.\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    dataset.col(i) /= norm(dataset.col(i), 2);\n\n  arma::mat labels = arma::zeros(1, dataset.n_cols);\n  labels.submat(0, labels.n_cols / 2, 0, labels.n_cols - 1).fill(1);\n\n  // Vanilla neural net with logistic activation function.\n  BuildDropoutNetwork<LogisticFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n      (dataset, labels, dataset, labels, 8, 30, 0.4);\n\n  // Vanilla neural net with tanh activation function.\n  BuildDropoutNetwork<TanhFunction,\n                      BinaryClassificationLayer,\n                      MeanSquaredErrorFunction>\n    (dataset, labels, dataset, labels, 8, 30, 0.4);\n}\n\n/**\n * Train and evaluate a DropConnect network(with a baselayer) with the\n * specified structure.\n */\ntemplate<\n    typename PerformanceFunction,\n    typename OutputLayerType,\n    typename PerformanceFunctionType,\n    typename MatType = arma::mat\n>\nvoid BuildDropConnectNetwork(MatType& trainData,\n                             MatType& trainLabels,\n                             MatType& testData,\n                             MatType& testLabels,\n                             const size_t hiddenLayerSize,\n                             const size_t maxEpochs,\n                             const double classificationErrorThreshold)\n{\n /*\n  *  Construct a feed forward network with trainData.n_rows input nodes,\n  *  hiddenLayerSize hidden nodes and trainLabels.n_rows output nodes. The\n  *  network struct that looks like:\n  *\n  *  Input         Hidden     DropConnect     Output\n  *  Layer         Layer         Layer        Layer\n  * +-----+       +-----+       +-----+       +-----+\n  * |     |       |     |       |     |       |     |\n  * |     +------>|     +------>|     +------>|     |\n  * |     |     +>|     |       |     |       |     |\n  * +-----+     | +--+--+       +-----+       +-----+\n  *             |\n  *  Bias       |\n  *  Layer      |\n  * +-----+     |\n  * |     |     |\n  * |     +-----+\n  * |     |\n  * +-----+\n  *\n  *\n  */\n  LinearLayer<> inputLayer(trainData.n_rows, hiddenLayerSize);\n  BiasLayer<> biasLayer(hiddenLayerSize);\n  BaseLayer<PerformanceFunction> hiddenLayer0;\n\n  LinearLayer<> hiddenLayer1(hiddenLayerSize, trainLabels.n_rows);\n  DropConnectLayer<decltype(hiddenLayer1)> dropConnectLayer0(hiddenLayer1);\n\n  BaseLayer<PerformanceFunction> outputLayer;\n\n  OutputLayerType classOutputLayer;\n\n  auto modules = std::tie(inputLayer, biasLayer, hiddenLayer0,\n                          dropConnectLayer0, outputLayer);\n\n  FFN<decltype(modules), decltype(classOutputLayer), RandomInitialization,\n              PerformanceFunctionType> net(modules, classOutputLayer);\n\n  RMSprop<decltype(net)> opt(net, 0.01, 0.88, 1e-8,\n      maxEpochs * trainData.n_cols, 1e-18);\n\n  net.Train(trainData, trainLabels, opt);\n\n  MatType prediction;\n  net.Predict(testData, prediction);\n\n  size_t error = 0;\n  for (size_t i = 0; i < testData.n_cols; i++)\n  {\n      if (arma::sum(arma::sum(\n          arma::abs(prediction.col(i) - testLabels.col(i)))) == 0)\n      {\n          error++;\n      }\n  }\n\n  double classificationError = 1 - double(error) / testData.n_cols;\n  BOOST_REQUIRE_LE(classificationError, classificationErrorThreshold);\n}\n\n/**\n * Train and evaluate a DropConnect network(with a linearlayer) with the\n * specified structure.\n */\ntemplate<\n    typename PerformanceFunction,\n    typename OutputLayerType,\n    typename PerformanceFunctionType,\n    typename MatType = arma::mat\n>\nvoid BuildDropConnectNetworkLinear(MatType& trainData,\n                                   MatType& trainLabels,\n                                   MatType& testData,\n                                   MatType& testLabels,\n                                   const size_t hiddenLayerSize,\n                                   const size_t maxEpochs,\n                                   const double classificationErrorThreshold)\n{\n /*\n  * Construct a feed forward network with trainData.n_rows input nodes,\n  * hiddenLayerSize hidden nodes and trainLabels.n_rows output nodes. The\n  * network struct that looks like:\n  *\n  * Input         Hidden       DropConnect     Output\n  * Layer         Layer          Layer         Layer\n  * +-----+       +-----+       +-----+       +-----+\n  * |     |       |     |       |     |       |     |\n  * |     +------>|     +------>|     +------>|     |\n  * |     |     +>|     |       |     |       |     |\n  * +-----+     | +--+--+       +-----+       +-----+\n  *             |\n  *  Bias       |\n  *  Layer      |\n  * +-----+     |\n  * |     |     |\n  * |     +-----+\n  * |     |\n  * +-----+\n  *\n  *\n  */\n  LinearLayer<> inputLayer(trainData.n_rows, hiddenLayerSize);\n  BiasLayer<> biasLayer(hiddenLayerSize);\n  BaseLayer<PerformanceFunction> hiddenLayer0;\n\n  DropConnectLayer<> dropConnectLayer0(hiddenLayerSize, trainLabels.n_rows);\n\n  BaseLayer<PerformanceFunction> outputLayer;\n\n  OutputLayerType classOutputLayer;\n  auto modules = std::tie(inputLayer, biasLayer, hiddenLayer0,\n                          dropConnectLayer0, outputLayer);\n\n  FFN<decltype(modules), decltype(classOutputLayer), RandomInitialization,\n              PerformanceFunctionType> net(modules, classOutputLayer);\n\n  RMSprop<decltype(net)> opt(net, 0.01, 0.88, 1e-8,\n      maxEpochs * trainData.n_cols, 1e-18);\n\n  net.Train(trainData, trainLabels, opt);\n\n  MatType prediction;\n  net.Predict(testData, prediction);\n\n  size_t error = 0;\n  for (size_t i = 0; i < testData.n_cols; i++)\n  {\n      if (arma::sum(arma::sum(\n          arma::abs(prediction.col(i) - testLabels.col(i)))) == 0)\n      {\n              error++;\n      }\n  }\n\n  double classificationError = 1 - double(error) / testData.n_cols;\n  BOOST_REQUIRE_LE(classificationError, classificationErrorThreshold);\n}\n/**\n * Train the dropconnect network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(DropConnectNetworkTest)\n{\n  // Load the dataset.\n  arma::mat dataset;\n  data::Load(\"thyroid_train.csv\", dataset, true);\n\n  arma::mat trainData = dataset.submat(0, 0, dataset.n_rows - 4,\n      dataset.n_cols - 1);\n  arma::mat trainLabels = dataset.submat(dataset.n_rows - 3, 0,\n      dataset.n_rows - 1, dataset.n_cols - 1);\n\n  data::Load(\"thyroid_test.csv\", dataset, true);\n\n  arma::mat testData = dataset.submat(0, 0, dataset.n_rows - 4,\n      dataset.n_cols - 1);\n  arma::mat testLabels = dataset.submat(dataset.n_rows - 3, 0,\n      dataset.n_rows - 1, dataset.n_cols - 1);\n\n  // Vanilla neural net with logistic activation function.\n  // Because 92 percent of the patients are not hyperthyroid the neural\n  // network must be significant better than 92%.\n  BuildDropConnectNetwork<LogisticFunction,\n                          BinaryClassificationLayer,\n                          MeanSquaredErrorFunction>\n      (trainData, trainLabels, testData, testLabels, 4, 100, 0.1);\n\n  BuildDropConnectNetworkLinear<LogisticFunction,\n                                BinaryClassificationLayer,\n                                MeanSquaredErrorFunction>\n      (trainData, trainLabels, testData, testLabels, 4, 100, 0.1);\n\n  dataset.load(\"mnist_first250_training_4s_and_9s.arm\");\n\n  // Normalize each point since these are images.\n  for (size_t i = 0; i < dataset.n_cols; ++i)\n    dataset.col(i) /= norm(dataset.col(i), 2);\n\n  arma::mat labels = arma::zeros(1, dataset.n_cols);\n  labels.submat(0, labels.n_cols / 2, 0, labels.n_cols - 1).fill(1);\n\n  // Vanilla neural net with logistic activation function.\n  BuildDropConnectNetwork<LogisticFunction,\n                          BinaryClassificationLayer,\n                          MeanSquaredErrorFunction>\n      (dataset, labels, dataset, labels, 8, 30, 0.4);\n\n\n  BuildDropConnectNetworkLinear<LogisticFunction,\n                                BinaryClassificationLayer,\n                                MeanSquaredErrorFunction>\n      (dataset, labels, dataset, labels, 8, 30, 0.4);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "e1412b462b064b8453ac3570816294b48b128d4a", "size": 16942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/feedforward_network_test.cpp", "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:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:16.000Z", "max_issues_repo_path": "src/mlpack/tests/feedforward_network_test.cpp", "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/tests/feedforward_network_test.cpp", "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.5485148515, "max_line_length": 77, "alphanum_fraction": 0.603234565, "num_tokens": 4205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5682076975286804}}
{"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": "\n#include \"rts_object_cost_grid_space_e.h\"\n\n#include \"cor_type/sources/math/vector2.h\"\n#include \"cor_data_structure/sources/ai/stack_decoder_tmpl_impl.h\"\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include \"cor_system/sources/thread_pool.h\"\n\n#include \"cocos2d.h\"\n\nnamespace cor\n{\n    namespace cocos2dx_converter\n    {\n        struct RtsObjectCostGridSpaceExperimentalItnl\n        {\n            \n        };\n        \n        RtsObjectCostGridSpaceExperimental::RtsObjectCostGridSpaceExperimental() : itnl(new RtsObjectCostGridSpaceExperimentalItnl())\n        {\n            \n        }\n        \n        RtsObjectCostGridSpaceExperimental::~RtsObjectCostGridSpaceExperimental()\n        {\n            \n        }\n\n        RString RtsObjectCostGridSpaceExperimental::run1(cocos2d::DrawNode* draw_node)\n        {\n            typedef boost::adjacency_list<boost::listS, boost::listS, boost::undirectedS,\r\n                type::Vector2F, boost::property<boost::edge_weight_t, RFloat> > Graph;\n\n            Graph g;\n\n            RStringStream s;\n\n            s << \"graph run 1\\n\";\n            \n            auto va = {\n                type::Vector2F(100.0f, 100.0f),\n                type::Vector2F(200.0f, 100.0f),\n                type::Vector2F(300.0f, 100.0f),\n                type::Vector2F(100.0f, 250.0f),\n                type::Vector2F(200.0f, 400.0f)\n            };\n\n            std::vector<Graph::vertex_descriptor> vda;\n\n            for(auto v: va)\n            {\n                auto vd = boost::add_vertex(g);\n\n                g[vd] = v;\n\n                vda.push_back(vd);\n            }\n\n            typedef std::pair<RInt32, RInt32> Pair;\n\n            auto ea = {\n                Pair(0, 1),\n                Pair(1, 2),\n                Pair(0, 3),\n                Pair(1, 3),\n                Pair(2, 3),\n                Pair(3, 4),\n                Pair(2, 4)\n            };\n\n            for(auto e : ea)\n            {\n                auto ed = boost::add_edge(vda[e.first], vda[e.second], g[vda[e.first]].distance(g[vda[e.second]]), g);\n            }\n\n            auto w = boost::get(boost::edge_weight, g);\n\n            auto vta = boost::vertices(g);\n            for(auto v = vta.first; v != vta.second; v++)\n            {\n                s << \"v \" << g[*v].x << \", \" << g[*v].y << \"\\n\";\n                auto ea = boost::out_edges(*v, g);\n                for(auto e = ea.first; e != ea.second; e++)\n                {\n                    s << \"e (\" << g[boost::source(*e, g)].x << \", \" << g[boost::source(*e, g)].y << \"), -> \" <<\n                        \"(\" << g[boost::target(*e, g)].x << \", \" << g[boost::target(*e, g)].y << \") = \" << boost::get(w, *e) << \"\\n\";\n\n                    draw_node->drawSegment(cocos2d::Vec2(g[boost::source(*e, g)].x, g[boost::source(*e, g)].y),\n                        cocos2d::Vec2(g[boost::target(*e, g)].x, g[boost::target(*e, g)].y), 1.0f,\n                        cocos2d::Color4F(1.0f, 0.0f, 0.0f, 1.0f));\n                }\n            }\n\n            std::map<Graph::vertex_descriptor, RFloat> vertex_cost_table;\n            std::map<Graph::vertex_descriptor, Graph::vertex_descriptor> vertex_parent_table;\n            struct State\n            {\n                Graph::vertex_descriptor vd;\n                RFloat cost;\n\n                State()\n                {\n                    vd = nullptr;\n                    cost = 0.0f;\n                }\n            };\n\n            typedef data_structure::InstantStackDecoderTmpl<RFloat, State> StackDecoder;\n\n            StackDecoder sd;\n\n            s << \"searching\" << \"\\n\";\n\n            sd.set_func([&](const State& state){\n                return state.cost;\n            }, [&](const State& state, std::function<void(const State&)> f){\n                auto ea = boost::out_edges(state.vd, g);\n                auto& src = g[state.vd];\n                for(auto e = ea.first; e != ea.second; e++)\n                {\n                    auto target_vd = boost::target(*e, g);\n                    auto& tgt = g[target_vd];\n                    auto cost = state.cost + src.distance(tgt);\n\n                    if(vertex_cost_table.find(target_vd) != vertex_cost_table.end())\n                    {\n                        if(vertex_cost_table[target_vd] <= cost)\n                        {\n                            continue;\n                        }\n                    }\n\n                    State st;\n                    vertex_cost_table[target_vd] = cost;\n                    vertex_parent_table[target_vd] = state.vd;\n                    st.vd = target_vd;\n                    st.cost = cost;\n\n                    s << \"(\" << g[target_vd].x << \", \" << g[target_vd].y << \"), \" << cost << \"\\n\";\n\n                    f(st);\n                }\n            }, [&](const State& state){\n                return state.vd == vda[4];\n            });\n\n\n            State first_state;\n            first_state.vd = vda[0];\n            vertex_cost_table[vda[0]] = 0.0f;\n            vertex_parent_table[vda[0]] = nullptr;\n            sd.push(first_state);\n\n            s << \"path\" << \"\\n\";\n            sd.search_first_n(1, [&](const State& state){\n                Graph::vertex_descriptor vd = state.vd;\n                while(vd)\n                {\n                    s << \"(\" << g[vd].x << \", \" << g[vd].y << \")\" << \"\\n\";\n\n                    vd = vertex_parent_table[vd];\n                }\n\n                return rtrue;\n            });\n\n            \n            return s.str();\n        }\n\n        RString RtsObjectCostGridSpaceExperimental::run2(cocos2d::Node* root_node, cocos2d::DrawNode* draw_node, Collision2dNodeSP collision, data_structure::CostGridSpaceSP cost_grid_space, RtsObjectGroupSP object_group)\n        {\n            auto cgs = std::make_shared<RtsObjectCostGridSpace>(collision, cost_grid_space, object_group);\n            cgs->set_wall_kind(2);\n\n            cgs->set_index_convert(type::Vector2F(10.0f, 10.0f), type::Vector2F(0.0f, 0.0f));\n\n            struct Character\n            {\n                type::Vector2F p;\n                cocos2d::Color4F c;\n                Collision2dNodeRef r;\n                RtsObjectSP o;\n                cocos2d::Node* n;\n\n                Character(RFloat x, RFloat y, RFloat r, RFloat g, RFloat b, RFloat a)\n                {\n                    p = type::Vector2F(x, y);\n                    c = cocos2d::Color4F(r, g, b, a);\n                }\n            };\n\n            RStringStream s;\n\n            Character ca[] = {\n                Character(50.0f, 50.0f, 1.0f, 0.0f, 0.0f, 1.0f),\n                Character(120.0f, 50.0f, 1.0f, 1.0f, 0.0f, 1.0f),\n                Character(200.0f, 50.0f, 1.0f, 0.0f, 1.0f, 1.0f),\n                Character(50.0f, 100.0f, 0.0f, 1.0f, 0.0f, 1.0f),\n                Character(200.0f, 200.0f, 0.0f, 1.0f, 1.0f, 1.0f)\n            };\n\n            s << \"test run2\";\n\n            std::vector<Collision2dNodeRef> refs;\n\n            auto vec_i_to_f = [](type::Vector2I vi){\n                return type::Vector2F(vi.x * 10.0f, vi.y * 10.0f);\n            };\n\n            auto vec_f_to_i = [](type::Vector2F vf){\n                return type::Vector2F(static_cast<RInt32>(vf.x / 10.0f + 0.5f), static_cast<RInt32>(vf.y / 10.0f + 0.5f));\n            };\n\n            \n\n            RSize sz = 30;\n\n            for(RSize i = 0; i < 10; i++)\n            {\n                auto ip = type::Vector2I(10, i + 5);\n                auto& cell = cost_grid_space->ref(ip);\n                cell.enter_cost = 2.0f;\n                //cell.passable = rfalse;\n            }\n\n            for(RSize i = 0; i < 7; i++)\n            {\n                auto ip = type::Vector2I(10 + i, 10);\n                auto& cell = cost_grid_space->ref(ip);\n                cell.enter_cost = 2.0f;\n                //cell.passable = rfalse;\n            }\n\n            for(RSize i = 0; i < sz; i++)\n            {\n                for(RSize j = 0; j < sz; j++)\n                {\n                    auto ip = type::Vector2I(j, i);\n                    auto vp = vec_i_to_f(ip);\n                    auto& cell = cost_grid_space->ref(ip);\n\n                    cocos2d::Node* n;\n                    if(cell.enter_cost < 1.5f)\n                    {\n                        //auto l = cocos2d::LayerColor::create(cocos2d::Color4B(127, 127, 127, 64), 10, 10);\n                        //l->setPosition(vp.x, vp.y);\n                        //\n                        //root_node->addChild(l);\n                        //\n                        //n = l;\n\n                        \n                    }\n                    else\n                    {\n                        auto l = cocos2d::LayerColor::create(cocos2d::Color4B(255, 255, 255, 127), 10, 10);\n                        l->setPosition(vp.x, vp.y);\n\n                        root_node->addChild(l);\n\n                        n = l;\n\n                        //\n                        auto r = collision->add_o_box(n, 0, type::Box2F(0, 0, 10, 10), [=](cocos2d::Node*, cocos2d::Node*){\n\n                        });\n                        refs.push_back(r);\n\n                        //\n                        auto o = object_group->create_object(r);\n                        o->set_kind(2);\n                        cgs->add(o);\n                    }\n\n\n                }\n            }\n\n            for(auto& c : ca)\n            {\n                auto n = cocos2d::LayerColor::create(cocos2d::Color4B(c.c), 10, 10);\n                n->setPosition(c.p.x, c.p.y);\n                c.n = n;\n                root_node->addChild(n);\n\n                //\n                auto r = collision->add_o_box(n, 0, type::Box2F(0, 0, 10, 10), [=](cocos2d::Node*, cocos2d::Node*){\n\n                });\n                c.r = r;\n                refs.push_back(r);\n\n                //\n                auto o = object_group->create_object(r);\n                o->set_kind(1);\n                c.o = o;\n                cgs->add(o);\n\n                //\n                auto ip = vec_f_to_i(c.p);\n                auto& cell = cost_grid_space->ref(ip);\n\n                \n            }\n\n            cgs->make_graph();\n\n            cgs->each_vertices([&](RtsObjectCostGridSpaceCellPtr cell){\n                //s << \"v (\" << cell->position.x << \", \" << cell->position.y << \")\" << \"\\n\";\n            });\n\n            cgs->each_edges([&](RtsObjectCostGridSpaceCellPtr source, RtsObjectCostGridSpaceCellPtr target, RFloat w){\n                //s << \"e s (\" << source->position.x << \", \" << source->position.y << \"), \" <<\n                //    \"t(\" << target->position.x << \", \" << target->position.y << \")\" << \", w \" << w << \"\\n\";\n\n                auto v0 = vec_i_to_f(source->position);\n                auto v1 = vec_i_to_f(target->position);\n                auto color = cocos2d::Color4F(1.0f, 0.0f, 0.0f, 1.0f);\n                if(source->wall || target->wall)\n                {\n                    color = cocos2d::Color4F(0.0f, 0.0f, 1.0f, 1.0f);\n                }\n\n                draw_node->drawSegment(cocos2d::Vec2(v0.x + 5.0f, v0.y + 5.0f), cocos2d::Vec2(v1.x + 5.0f, v1.y + 5.0f), 1.0f, color);\n            });\n\n            //cgs->each_cell([&](RtsObjectCostGridSpaceCellPtr cell){\n            //    auto l = static_cast<cocos2d::LayerColor*>(cell->root->a[0]->get_node_ref().get_node());\n            //    auto c = l->getColor();\n            //    auto a = l->getOpacity();\n            //    a /= 2;\n            //    auto nl = cocos2d::LayerColor::create(cocos2d::Color4B(c.r, c.g, c.b, a), 5, 5);\n            //    auto v0 = vec_i_to_f(cell->position);\n            //    nl->setPosition(v0.x, v0.y);\n\n            //    root_node->addChild(nl);\n            //});\n\n\n            return s.str();\n        }\n\n        RString RtsObjectCostGridSpaceExperimental::thread_run()\n        {\n            auto job_queue = std::make_shared<cor::system::JobQueue>();\r\n            auto thread_pool = std::make_shared<cor::system::ThreadPool>(job_queue, 8);\r\n\r\n            std::vector<cor::RInt32> a, b;\r\n\r\n            std::mutex m;\r\n\r\n            auto f = [&](cor::RInt32 n){\r\n                a.push_back(n);\r\n                auto na = std::make_shared<cor::RInt32>(n);\r\n                thread_pool->add_job([&b, &m, na](){\r\n                    //{\r\n                    //    std::lock_guard<std::mutex> l(m);\r\n                    //    cor::log_debug(\"thread \", *na.get());\r\n                    //}\r\n                    std::this_thread::sleep_for(std::chrono::milliseconds(1));\r\n                    *na.get() += 10;\r\n                    //{\r\n                    //    std::lock_guard<std::mutex> l(m);\r\n                    //    cor::log_debug(\"thread ed \", *na.get());\r\n                    //}\r\n                }, [&b, &m, na](){\r\n                    //{\r\n                    //    std::lock_guard<std::mutex> l(m);\r\n                    //    cor::log_debug(\"end \", *na.get());\r\n                    //}\r\n                    b.push_back(*na.get());\r\n                });\r\n            };\r\n\r\n            for(auto i = 0; i < 1000; i++)\r\n            {\r\n                f(i);\r\n            }\r\n\r\n            //cor::log_debug(\"pre step\");\r\n\r\n            while(!thread_pool->empty())\r\n            {\r\n                job_queue->step();\r\n                std::this_thread::sleep_for(std::chrono::milliseconds(10));\r\n            }\r\n\r\n            //cor::log_debug(\"post step\");\r\n\r\n            cor::RString sa, sb;\r\n\r\n            sa = cor::algorithm::join(a, \",\");\r\n            sb = cor::algorithm::join(b, \",\");\r\n\r\n            cor::log_debug(\"sa = \", sa, \", sb = \", sb);\r\n\n            return sb;\n        }\n    }\n}\n", "meta": {"hexsha": "29ed8cc9f95f5568bfd241cc97f64b6559877a90", "size": 13512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/cor_cocos2dx_converter/sources/rts/rts_object_cost_grid_space_e.cpp", "max_stars_repo_name": "rmake/cor-engine", "max_stars_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T09:55:02.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-10T03:42:23.000Z", "max_issues_repo_path": "libraries/cor_cocos2dx_converter/sources/rts/rts_object_cost_grid_space_e.cpp", "max_issues_repo_name": "rmake/cor-engine", "max_issues_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_issues_repo_licenses": ["MIT"], "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/cor_cocos2dx_converter/sources/rts/rts_object_cost_grid_space_e.cpp", "max_forks_repo_name": "rmake/cor-engine", "max_forks_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T02:30:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T06:56:49.000Z", "avg_line_length": 33.362962963, "max_line_length": 221, "alphanum_fraction": 0.4148164594, "num_tokens": 3448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5681111061287067}}
{"text": "//  GAMBIT: Global and Modular BSM Inference Tool\n//  *********************************************\n///  \\file\n///\n///  Prior object construction routines\n///  \n///\n///  *********************************************\n///\n///  Authors (add name and date if you modify):\n///   \n///  \\author Ben Farmer\n///          (benjamin.farmer@monash.edu.au)\n///  \\date 2013 Dec\n///\n///  \\author Gregory Martinez\n///          (gregory.david.martinez@gmail.com)\n///  \\date Feb 2014\n///\n///  *********************************************\n\n#ifndef PRIOR_GAUSSIAN_HPP\n#define PRIOR_GAUSSIAN_HPP\n\n#include <vector>\n#include <cmath>\n\n#include \"gambit/ScannerBit/cholesky.hpp\"\n#include \"gambit/ScannerBit/priors.hpp\"\n#include \"gambit/Utils/yaml_options.hpp\"\n\n#include <boost/math/special_functions/erf.hpp>\n   \nnamespace Gambit\n{\n    namespace Priors\n    {\n        // Gaussian prior. Takes covariance matrix as arguments\n        class Gaussian : public BasePrior\n        {\n        private:\n            std::vector <double> mean;\n            mutable Cholesky col;\n                \n        public: \n            // Constructor defined in gaussian.cpp\n            Gaussian(const std::vector<std::string>&, const Options&);\n            \n            // Transformation from unit interval to the Gaussian\n            void transform(const std::vector <double> &unitpars, std::unordered_map <std::string, double> &outputMap) const\n            {\n                std::vector<double> vec(unitpars.size());\n                \n                auto v_it = vec.begin();\n                for (auto elem_it = unitpars.begin(), elem_end = unitpars.end(); elem_it != elem_end; elem_it++, v_it++)\n                {\n                    *v_it = M_SQRT2*boost::math::erf_inv(2.0*(*elem_it) - 1.0); \n                }\n                \n                col.ElMult(vec);\n                \n                v_it = vec.begin();\n                auto m_it = mean.begin();\n                for (auto str_it = param_names.begin(), str_end = param_names.end(); str_it != str_end; str_it++)\n                {\n                    outputMap[*str_it] = *(v_it++) + *(m_it++);\n                }\n            }\n            \n            double operator()(const std::vector<double> &vec) const\n            {\n                    static double norm = std::log(2.0*Gambit::Scanner::pi()*Gambit::Scanner::pow<2>(col.DetSqrt()))/2.0;\n                    return -col.Square(vec, mean)/2.0 - norm;\n            }\n        };\n\n        LOAD_PRIOR(gaussian, Gaussian)\n    }\n}\n\n#endif\n", "meta": {"hexsha": "bb513f4830c37b71ae221775404497e70490b20e", "size": 2499, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ScannerBit/include/gambit/ScannerBit/priors/gaussian.hpp", "max_stars_repo_name": "aaronvincent/gambit_aaron", "max_stars_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-21T19:59:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-21T19:59:18.000Z", "max_issues_repo_path": "ScannerBit/include/gambit/ScannerBit/priors/gaussian.hpp", "max_issues_repo_name": "aaronvincent/gambit_aaron", "max_issues_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-10-06T14:03:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-06T11:53:54.000Z", "max_forks_repo_path": "ScannerBit/include/gambit/ScannerBit/priors/gaussian.hpp", "max_forks_repo_name": "aaronvincent/gambit_aaron", "max_forks_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4756097561, "max_line_length": 123, "alphanum_fraction": 0.4965986395, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5681110933064538}}
{"text": "#include <cassert>\r\n#include <cstdlib>\r\n#include <algorithm>\r\n#include <iostream>\r\n#include <random>\r\n#include <tuple>\r\n#include <vector>\r\n#include <boost/accumulators/accumulators.hpp>\r\n#include <boost/accumulators/statistics.hpp>\r\n#include <dSFMT.h>\r\n#include <windows.h>\r\n\r\nusing Number = double;\r\nusing Numbers = std::vector<Number>;\r\n\r\nclass LapTime {\r\n    using TimeIn100nsec = unsigned long long;\r\n    using Time = double;\r\n    static constexpr Time SecIn100nsec = 10000000;\r\npublic:\r\n    LapTime(void) : startTime_(now()) {\r\n        return;\r\n    }\r\n\r\n    virtual ~LapTime(void) = default;\r\n\r\n    Time GetElapsedTime(void) {\r\n        const auto endTime = now();\r\n        const auto duration = endTime - startTime_;\r\n        auto elapsedTime = static_cast<Time>(duration);\r\n        elapsedTime /= SecIn100nsec;\r\n        return elapsedTime;\r\n    }\r\n\r\nprivate:\r\n    TimeIn100nsec now(void) {\r\n        FILETIME timestamp;\r\n        GetSystemTimeAsFileTime(&timestamp);\r\n\r\n        TimeIn100nsec timeIn100nsec = timestamp.dwHighDateTime;\r\n        for(size_t i=0; i<sizeof(timestamp.dwLowDateTime); ++i) {\r\n            timeIn100nsec <<= 8;\r\n        }\r\n        timeIn100nsec += timestamp.dwLowDateTime;\r\n        return timeIn100nsec;\r\n    }\r\n\r\n    TimeIn100nsec startTime_ {0};\r\n};\r\n\r\nvoid generateNumbers(Numbers& v) {\r\n    LapTime laptime;\r\n\r\n    std::random_device seed_gen;\r\n    uint32_t seed = seed_gen();\r\n    dsfmt_t dsfmt;\r\n    dsfmt_init_gen_rand(&dsfmt, seed);\r\n\r\n    // dsfmt_fill_array_close_open takes size as int\r\n    const auto intSize = static_cast<int>(v.size());\r\n    assert(static_cast<decltype(v.size())>(intSize) == v.size());\r\n    dsfmt_fill_array_close_open(&dsfmt, v.data(), intSize);\r\n    std::cout << \"generateNumbers(dSFMT) \" << laptime.GetElapsedTime() << \"sec\\n\";\r\n}\r\n\r\nvoid generateNumbersStd(Numbers& v) {\r\n    LapTime laptime;\r\n    std::random_device seed_gen;\r\n    std::mt19937 engine(seed_gen());\r\n    std::uniform_real_distribution<Number> dist(0.0, 1.0);\r\n    std::for_each(v.begin(), v.end(), [&](auto& x) { x = dist(engine); });\r\n    std::cout << \"generateNumbers(std) \" << laptime.GetElapsedTime() << \"sec\\n\";\r\n}\r\n\r\nstd::tuple<Number, Number> accumulateNumbers(const Numbers& v, int loopSize) {\r\n    LapTime laptime;\r\n    using namespace boost::accumulators;\r\n    accumulator_set<Number, stats<tag::mean, tag::variance>> acc;\r\n    for(auto loopIndex = decltype(loopSize){0}; loopIndex < loopSize; ++loopIndex) {\r\n        std::for_each(v.begin(), v.end(), [&](const auto& x) { acc(x); });\r\n    }\r\n    std::cout << \"accumulateNumbers \" << laptime.GetElapsedTime() << \"sec\\n\";\r\n    return {mean(acc), variance(acc)};\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n    bool setSize = (argc > 2);\r\n\r\n    constexpr Numbers::size_type DefaultVecSize = 20000000ull;\r\n    auto vecSize = DefaultVecSize;\r\n    int loopSize = 1;\r\n\r\n    if (setSize) {\r\n        // vecSize must be shorter than INT_MAX\r\n        vecSize = static_cast<decltype(vecSize)>(std::atoi(argv[1]));\r\n        loopSize = std::atoi(argv[2]);\r\n    }\r\n\r\n    Numbers v(vecSize, 0.0);\r\n    std::cout << \"size: \" << vecSize << \" loop:\" << loopSize << \"\\n\";\r\n    if (setSize) {\r\n        generateNumbers(v);\r\n    } else {\r\n        generateNumbersStd(v);\r\n    }\r\n\r\n    const auto [mean, variance] = accumulateNumbers(v, loopSize);\r\n    std::cout << \"mean:\" << mean << \" variance:\" << variance << \"\\n\\n\";\r\n    return 0;\r\n}\r\n\r\n\r\n/*\r\nLocal Variables:\r\nmode: c++\r\ncoding: utf-8-dos\r\ntab-width: nil\r\nc-file-style: \"stroustrup\"\r\nEnd:\r\n*/\r\n", "meta": {"hexsha": "b421aec087822dd91e57537726ac4c0c32525c20", "size": 3514, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_optimize/cpp_optimize.cpp", "max_stars_repo_name": "zettsu-t/cPlusPlusFriend", "max_stars_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-04-15T00:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-10T05:11:14.000Z", "max_issues_repo_path": "cpp_optimize/cpp_optimize.cpp", "max_issues_repo_name": "zettsu-t/cPlusPlusFriend", "max_issues_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp_optimize/cpp_optimize.cpp", "max_forks_repo_name": "zettsu-t/cPlusPlusFriend", "max_forks_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T22:47:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-23T22:47:08.000Z", "avg_line_length": 29.041322314, "max_line_length": 85, "alphanum_fraction": 0.6192373364, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.5680706517175547}}
{"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": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// Multipolygon DP simplification example from the mailing list discussion\r\n// about the DP algorithm issue:\r\n// http://lists.osgeo.org/pipermail/ggl/2011-September/001533.html\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\nusing namespace boost::geometry;\r\n\r\nint main()\r\n{\r\n  typedef model::d2::point_xy<double> point_xy;\r\n\r\n  point_xy p1(0.0, 0.0);\r\n  point_xy p2(5.0, 0.0);\r\n\r\n  // 1) This is direct call to Pythagoras algo\r\n  typedef strategy::distance::pythagoras<point_xy, point_xy, double> strategy1_type;\r\n  strategy1_type strategy1;\r\n  strategy1_type ::calculation_type d1 = strategy1.apply(p1, p2);\r\n\r\n  // 2) This is what is effectively called by simplify\r\n  typedef strategy::distance::comparable::pythagoras<point_xy, point_xy, double> strategy2_type;\r\n  strategy2_type strategy2;\r\n  strategy2_type::calculation_type d2 = strategy2.apply(p1, p2);\r\n\r\n  return 0;  \r\n}\r\n", "meta": {"hexsha": "3b887d5e4773bb651a8deda4cee145864186bb08", "size": 1300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/example/ml02_distance_strategy.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/example/ml02_distance_strategy.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/example/ml02_distance_strategy.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1351351351, "max_line_length": 97, "alphanum_fraction": 0.7376923077, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5678925348477835}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// cross_validation::error::mean_abs_error.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_CROSS_VALIDATION_ERROR_MEAN_ABS_ERROR_HPP_ER_2009\n#define  BOOST_STATISTICS_DETAIL_CROSS_VALIDATION_ERROR_MEAN_ABS_ERROR_HPP_ER_2009\n#include <cmath>\n#include <boost/iterator/iterator_traits.hpp>\n#include <boost/range.hpp>\n#include <boost/vector_space/functional/l1_distance.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace cross_validation{\nnamespace error{\n\n    template<typename It,typename It1>\n    typename iterator_value<It>::type\n    mean_abs_error(\n        It b,\n        It e,\n        It1 b1\n    ){\n\n        typedef iterator_range<It>                          range_;\n        typedef typename iterator_difference<It>::type      diff_;\n        typedef iterator_range<It1>                         range1_;\n        typedef typename iterator_value<It>::type           val_;\n        typedef vector_space::template l1_distance<range_>   l1_;\n        \n        diff_ d = std::distance(b,e);\n        \n        l1_ l1(range_(b,e));\n        range1_ range1(\n            b1,\n            boost::next(\n                b1,\n                d\n            )\n        );\n        val_ res = l1(range1);\n        res /= static_cast<val_>(d);\n        res = sqrt( res );\n        return res;\n    };\n    \n}// error\n}// cross_validation\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "f9f3c9a0682e334b6c33d703f0e9205bbf2c302b", "size": 1947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cross_validation/boost/statistics/detail/cross_validation/error/mean_abs_error.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": "cross_validation/boost/statistics/detail/cross_validation/error/mean_abs_error.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": "cross_validation/boost/statistics/detail/cross_validation/error/mean_abs_error.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5689655172, "max_line_length": 82, "alphanum_fraction": 0.5151515152, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5678171638256689}}
{"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": "/**\n * @file\n * @brief Implementation of JacobianInverseGramian() test for geometry objects\n * @author Anian Ruoss\n * @date   2019-02-11 17:53:17\n * @copyright MIT License\n */\n\n#include \"check_jacobian_inverse_gramian.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Eigen>\n\nnamespace lf::geometry::test_utils {\n\nvoid checkJacobianInverseGramian(const lf::geometry::Geometry &geom,\n                                 const Eigen::MatrixXd &eval_points) {\n  const size_t num_points = eval_points.cols();\n  const size_t dim_local = geom.DimLocal();\n  const size_t dim_global = geom.DimGlobal();\n\n  Eigen::MatrixXd jacobians = geom.Jacobian(eval_points);\n  Eigen::MatrixXd jacInvGrams = geom.JacobianInverseGramian(eval_points);\n\n  EXPECT_EQ(jacInvGrams.rows(), dim_global)\n      << \"JacobianInverseGramian has \" << jacInvGrams.rows()\n      << \" rows instead of \" << dim_global;\n  EXPECT_EQ(jacInvGrams.cols(), num_points * dim_local)\n      << \"JacobianInverseGramian has \" << jacInvGrams.cols()\n      << \" cols instead of \" << num_points * dim_local;\n\n  for (int j = 0; j < num_points; ++j) {\n    Eigen::MatrixXd jacInvGram =\n        jacInvGrams.block(0, j * dim_local, dim_global, dim_local);\n    Eigen::MatrixXd jacobian =\n        jacobians.block(0, j * dim_local, dim_global, dim_local);\n\n    EXPECT_TRUE(jacInvGram.isApprox(\n        jacobian * (jacobian.transpose() * jacobian).inverse()))\n        << \"JacobianInverseGramian incorrect at point \" << eval_points.col(j);\n  }\n}\n\n}  // namespace lf::geometry::test_utils\n", "meta": {"hexsha": "c8357f84a97303280a039c2215e24242ce811c0a", "size": 1514, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/lf/geometry/test_utils/check_jacobian_inverse_gramian.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": "lib/lf/geometry/test_utils/check_jacobian_inverse_gramian.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": "lib/lf/geometry/test_utils/check_jacobian_inverse_gramian.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": 32.9130434783, "max_line_length": 78, "alphanum_fraction": 0.6842800528, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5678156863092196}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2010,2012 Jitse Niesen <jitse@maths.leeds.ac.uk>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"main.h\"\n#include <limits>\n#include <Eigen/Eigenvalues>\n\ntemplate<typename MatrixType> void schur(int size = MatrixType::ColsAtCompileTime)\n{\n  typedef typename ComplexSchur<MatrixType>::ComplexScalar ComplexScalar;\n  typedef typename ComplexSchur<MatrixType>::ComplexMatrixType ComplexMatrixType;\n\n  // Test basic functionality: T is triangular and A = U T U*\n  for(int counter = 0; counter < g_repeat; ++counter) {\n    MatrixType A = MatrixType::Random(size, size);\n    ComplexSchur<MatrixType> schurOfA(A);\n    VERIFY_IS_EQUAL(schurOfA.info(), Success);\n    ComplexMatrixType U = schurOfA.matrixU();\n    ComplexMatrixType T = schurOfA.matrixT();\n    for(int row = 1; row < size; ++row) {\n      for(int col = 0; col < row; ++col) {\n        VERIFY(T(row,col) == (typename MatrixType::Scalar)0);\n      }\n    }\n    VERIFY_IS_APPROX(A.template cast<ComplexScalar>(), U * T * U.adjoint());\n  }\n\n  // Test asserts when not initialized\n  ComplexSchur<MatrixType> csUninitialized;\n  VERIFY_RAISES_ASSERT(csUninitialized.matrixT());\n  VERIFY_RAISES_ASSERT(csUninitialized.matrixU());\n  VERIFY_RAISES_ASSERT(csUninitialized.info());\n\n  // Test whether compute() and constructor returns same result\n  MatrixType A = MatrixType::Random(size, size);\n  ComplexSchur<MatrixType> cs1;\n  cs1.compute(A);\n  ComplexSchur<MatrixType> cs2(A);\n  VERIFY_IS_EQUAL(cs1.info(), Success);\n  VERIFY_IS_EQUAL(cs2.info(), Success);\n  VERIFY_IS_EQUAL(cs1.matrixT(), cs2.matrixT());\n  VERIFY_IS_EQUAL(cs1.matrixU(), cs2.matrixU());\n\n  // Test maximum number of iterations\n  ComplexSchur<MatrixType> cs3;\n  cs3.setMaxIterations(ComplexSchur<MatrixType>::m_maxIterationsPerRow * size).compute(A);\n  VERIFY_IS_EQUAL(cs3.info(), Success);\n  VERIFY_IS_EQUAL(cs3.matrixT(), cs1.matrixT());\n  VERIFY_IS_EQUAL(cs3.matrixU(), cs1.matrixU());\n  cs3.setMaxIterations(1).compute(A);\n  VERIFY_IS_EQUAL(cs3.info(), size > 1 ? NoConvergence : Success);\n  VERIFY_IS_EQUAL(cs3.getMaxIterations(), 1);\n\n  MatrixType Atriangular = A;\n  Atriangular.template triangularView<StrictlyLower>().setZero();\n  cs3.setMaxIterations(1).compute(Atriangular); // triangular matrices do not need any iterations\n  VERIFY_IS_EQUAL(cs3.info(), Success);\n  VERIFY_IS_EQUAL(cs3.matrixT(), Atriangular.template cast<ComplexScalar>());\n  VERIFY_IS_EQUAL(cs3.matrixU(), ComplexMatrixType::Identity(size, size));\n\n  // Test computation of only T, not U\n  ComplexSchur<MatrixType> csOnlyT(A, false);\n  VERIFY_IS_EQUAL(csOnlyT.info(), Success);\n  VERIFY_IS_EQUAL(cs1.matrixT(), csOnlyT.matrixT());\n  VERIFY_RAISES_ASSERT(csOnlyT.matrixU());\n\n  if (size > 1 && size < 20)\n  {\n    // Test matrix with NaN\n    A(0,0) = std::numeric_limits<typename MatrixType::RealScalar>::quiet_NaN();\n    ComplexSchur<MatrixType> csNaN(A);\n    VERIFY_IS_EQUAL(csNaN.info(), NoConvergence);\n  }\n}\n\nvoid test_schur_complex()\n{\n  CALL_SUBTEST_1(( schur<Matrix4cd>() ));\n  CALL_SUBTEST_2(( schur<MatrixXcf>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4)) ));\n  CALL_SUBTEST_3(( schur<Matrix<std::complex<float>, 1, 1> >() ));\n  CALL_SUBTEST_4(( schur<Matrix<float, 3, 3, Eigen::RowMajor> >() ));\n\n  // Test problem size constructors\n  CALL_SUBTEST_5(ComplexSchur<MatrixXf>(10));\n}\n", "meta": {"hexsha": "67e4976216fa72389dba987736d8064816f33e7f", "size": 3558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/test/schur_complex.cpp", "max_stars_repo_name": "eundersander/bps-nav", "max_stars_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-03-15T01:49:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:17:14.000Z", "max_issues_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/test/schur_complex.cpp", "max_issues_repo_name": "eundersander/bps-nav", "max_issues_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-27T21:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T21:46:40.000Z", "max_forks_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/test/schur_complex.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": 38.6739130435, "max_line_length": 97, "alphanum_fraction": 0.7217537943, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.5678156817059588}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[equals\n//` Shows the predicate equals, which returns true if two geometries are spatially equal\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\n#include <boost/assign.hpp>\n\nint main()\n{\n    using boost::assign::tuple_list_of;\n\n    typedef boost::tuple<int, int> point;\n\n    boost::geometry::model::polygon<point> poly1, poly2;\n    boost::geometry::exterior_ring(poly1) = tuple_list_of(0, 0)(0, 5)(5, 5)(5, 0)(0, 0);\n    boost::geometry::exterior_ring(poly2) = tuple_list_of(5, 0)(0, 0)(0, 5)(5, 5)(5, 0);\n\n    std::cout \n        << \"polygons are spatially \" \n        << (boost::geometry::equals(poly1, poly2) ? \"equal\" : \"not equal\")\n        << std::endl;\n    \n    boost::geometry::model::box<point> box;\n    boost::geometry::assign_values(box, 0, 0, 5, 5);\n    \n    std::cout \n        << \"polygon and box are spatially \" \n        << (boost::geometry::equals(box, poly2) ? \"equal\" : \"not equal\")\n        << std::endl;\n    \n\n    return 0;\n}\n\n//]\n\n\n//[equals_output\n/*`\nOutput:\n[pre\npolygons are spatially equal\npolygon and box are spatially equal\n]\n*/\n//]\n", "meta": {"hexsha": "414aa38d35dbd8298eed8c2238dc37ef0d8fd77c", "size": 1559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/equals.cpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/equals.cpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/equals.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1451612903, "max_line_length": 88, "alphanum_fraction": 0.6664528544, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5678156788631998}}
{"text": "/* Boost numeric test of the adams-bashforth steppers test file\r\n\r\n Copyright 2013 Karsten Ahnert\r\n Copyright 2013-2015 Mario Mulansky\r\n\r\n Distributed under the Boost Software License, Version 1.0.\r\n (See accompanying file LICENSE_1_0.txt or\r\n copy at http://www.boost.org/LICENSE_1_0.txt)\r\n*/\r\n\r\n// disable checked iterator warning for msvc\r\n#include <boost/config.hpp>\r\n#ifdef BOOST_MSVC\r\n    #pragma warning(disable:4996)\r\n#endif\r\n\r\n#define BOOST_TEST_MODULE numeric_adams_bashforth\r\n\r\n#include <iostream>\r\n#include <cmath>\r\n\r\n#include <boost/array.hpp>\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <boost/mpl/vector.hpp>\r\n\r\n#include <boost/numeric/odeint.hpp>\r\n\r\nusing namespace boost::unit_test;\r\nusing namespace boost::numeric::odeint;\r\nnamespace mpl = boost::mpl;\r\n\r\ntypedef double value_type;\r\n\r\ntypedef boost::array< double , 2 > state_type;\r\n\r\n// harmonic oscillator, analytic solution x[0] = sin( t )\r\nstruct osc\r\n{\r\n    void operator()( const state_type &x , state_type &dxdt , const double t ) const\r\n    {\r\n        dxdt[0] = x[1];\r\n        dxdt[1] = -x[0];\r\n    }\r\n};\r\n\r\nBOOST_AUTO_TEST_SUITE( numeric_adams_bashforth_test )\r\n\r\n\r\n/* generic test for all adams bashforth steppers */\r\ntemplate< class Stepper >\r\nstruct perform_adams_bashforth_test\r\n{\r\n    void operator()( void )\r\n    {\r\n        Stepper stepper;\r\n        const int o = stepper.order()+1; //order of the error is order of approximation + 1\r\n\r\n        const state_type x0 = {{ 0.0 , 1.0 }};\r\n        state_type x1 = x0;\r\n        double t = 0.0;\r\n        double dt = 0.2;\r\n        // initialization, does a number of steps already to fill internal buffer, t is increased\r\n        stepper.initialize( osc() , x1 , t , dt );\r\n        double A = std::sqrt( x1[0]*x1[0] + x1[1]*x1[1] );\r\n        double phi = std::asin(x1[0]/A) - t;\r\n        // do a number of steps to fill the buffer with results from adams bashforth\r\n        for( size_t n=0 ; n < stepper.steps ; ++n )\r\n        {\r\n            stepper.do_step( osc() , x1 , t , dt );\r\n            t += dt;\r\n        }\r\n        // now we do the actual step\r\n        stepper.do_step( osc() , x1 , t , dt );\r\n        // only examine the error of the adams-bashforth step, not the initialization\r\n        const double f = 2.0 * std::abs( A*sin(t+dt+phi) - x1[0] ) / std::pow( dt , o ); // upper bound\r\n        \r\n        std::cout << o << \" , \" \r\n                  << Stepper::initializing_stepper_type::order_value+1 << \" , \"\r\n                  << f << std::endl;\r\n\r\n        /* as long as we have errors above machine precision */\r\n        while( f*std::pow( dt , o ) > 1E-16 )\r\n        {\r\n            x1 = x0;\r\n            t = 0.0;\r\n            stepper.initialize( osc() , x1 , t , dt );\r\n            A = std::sqrt( x1[0]*x1[0] + x1[1]*x1[1] );\r\n            phi = std::asin(x1[0]/A) - t;\r\n            // now we do the actual step\r\n            stepper.do_step( osc() , x1 , t , dt );\r\n            // only examine the error of the adams-bashforth step, not the initialization\r\n            std::cout << \"Testing dt=\" << dt << \" , \" << std::abs( A*sin(t+dt+phi) - x1[0] ) << std::endl;\r\n            BOOST_CHECK_LT( std::abs( A*sin(t+dt+phi) - x1[0] ) , f*std::pow( dt , o ) );\r\n            dt *= 0.5;\r\n        }\r\n    }\r\n};\r\n\r\ntypedef mpl::vector<\r\n    adams_bashforth< 2 , state_type > ,\r\n    adams_bashforth< 3 , state_type > ,\r\n    adams_bashforth< 4 , state_type > ,\r\n    adams_bashforth< 5 , state_type > ,\r\n    adams_bashforth< 6 , state_type > ,\r\n    adams_bashforth< 7 , state_type > ,\r\n    adams_bashforth< 8 , state_type >\r\n    > adams_bashforth_steppers;\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( adams_bashforth_test , Stepper, adams_bashforth_steppers )\r\n{\r\n    perform_adams_bashforth_test< Stepper > tester;\r\n    tester();\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "431ec2b7c0f12f71a862b204f3a3c736807606b5", "size": 3786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/test/numeric/adams_bashforth.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/test/numeric/adams_bashforth.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/test/numeric/adams_bashforth.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 32.0847457627, "max_line_length": 107, "alphanum_fraction": 0.5834653988, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.567815674259939}}
{"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 \u221e.\"\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": "// (C) Copyright 2007-2009 Andrew Sutton\r\n//\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0 (See accompanying file\r\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <iostream>\r\n#include <vector>\r\n\r\n#include <boost/graph/undirected_graph.hpp>\r\n#include <boost/graph/directed_graph.hpp>\r\n#include <boost/graph/floyd_warshall_shortest.hpp>\r\n#include <boost/graph/closeness_centrality.hpp>\r\n#include <boost/graph/exterior_property.hpp>\r\n#include <boost/graph/property_maps/constant_property_map.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\n\r\n// number of vertices in the graph\r\nstatic const unsigned N = 5;\r\n\r\ntemplate <typename Graph>\r\nstruct vertex_vector\r\n{\r\n    typedef graph_traits<Graph> traits;\r\n    typedef vector<typename traits::vertex_descriptor> type;\r\n};\r\n\r\ntemplate <typename Graph>\r\nvoid build_graph(Graph& g,\r\n                 typename vertex_vector<Graph>::type& v)\r\n{\r\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n\r\n    // add vertices\r\n    for(size_t i = 0; i < N; ++i) {\r\n        v[i] = add_vertex(g);\r\n    }\r\n\r\n    // add edges\r\n    add_edge(v[0], v[1], g);\r\n    add_edge(v[1], v[2], g);\r\n    add_edge(v[2], v[0], g);\r\n    add_edge(v[3], v[4], g);\r\n    add_edge(v[4], v[0], g);\r\n}\r\n\r\n\r\ntemplate <typename Graph>\r\nvoid test_undirected()\r\n{\r\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n    typedef typename graph_traits<Graph>::edge_descriptor Edge;\r\n\r\n    typedef exterior_vertex_property<Graph, double> CentralityProperty;\r\n    typedef typename CentralityProperty::container_type CentralityContainer;\r\n    typedef typename CentralityProperty::map_type CentralityMap;\r\n\r\n    typedef exterior_vertex_property<Graph, int> DistanceProperty;\r\n    typedef typename DistanceProperty::matrix_type DistanceMatrix;\r\n    typedef typename DistanceProperty::matrix_map_type DistanceMatrixMap;\r\n\r\n    typedef constant_property_map<Edge, int> WeightMap;\r\n\r\n    Graph g;\r\n    vector<Vertex> v(N);\r\n    build_graph(g, v);\r\n\r\n    CentralityContainer centralities(num_vertices(g));\r\n    DistanceMatrix distances(num_vertices(g));\r\n\r\n    CentralityMap cm(centralities, g);\r\n    DistanceMatrixMap dm(distances, g);\r\n\r\n    WeightMap wm(1);\r\n\r\n    floyd_warshall_all_pairs_shortest_paths(g, dm, weight_map(wm));\r\n    all_closeness_centralities(g, dm, cm);\r\n\r\n    BOOST_ASSERT(cm[v[0]] == double(1)/5);\r\n    BOOST_ASSERT(cm[v[1]] == double(1)/7);\r\n    BOOST_ASSERT(cm[v[2]] == double(1)/7);\r\n    BOOST_ASSERT(cm[v[3]] == double(1)/9);\r\n    BOOST_ASSERT(cm[v[4]] == double(1)/6);\r\n}\r\n\r\ntemplate <typename Graph>\r\nvoid test_directed()\r\n{\r\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n    typedef typename graph_traits<Graph>::edge_descriptor Edge;\r\n\r\n    typedef exterior_vertex_property<Graph, double> CentralityProperty;\r\n    typedef typename CentralityProperty::container_type CentralityContainer;\r\n    typedef typename CentralityProperty::map_type CentralityMap;\r\n\r\n    typedef exterior_vertex_property<Graph, int> DistanceProperty;\r\n    typedef typename DistanceProperty::matrix_type DistanceMatrix;\r\n    typedef typename DistanceProperty::matrix_map_type DistanceMatrixMap;\r\n\r\n    typedef constant_property_map<Edge, int> WeightMap;\r\n\r\n    Graph g;\r\n    vector<Vertex> v(N);\r\n    build_graph(g, v);\r\n\r\n    CentralityContainer centralities(num_vertices(g));\r\n    DistanceMatrix distances(num_vertices(g));\r\n\r\n    CentralityMap cm(centralities, g);\r\n    DistanceMatrixMap dm(distances, g);\r\n\r\n    WeightMap wm(1);\r\n\r\n    floyd_warshall_all_pairs_shortest_paths(g, dm, weight_map(wm));\r\n    all_closeness_centralities(g, dm, cm);\r\n\r\n    BOOST_ASSERT(cm[v[0]] == double(0));\r\n    BOOST_ASSERT(cm[v[1]] == double(0));\r\n    BOOST_ASSERT(cm[v[2]] == double(0));\r\n    BOOST_ASSERT(cm[v[3]] == double(1)/10);\r\n    BOOST_ASSERT(cm[v[4]] == double(0));\r\n}\r\n\r\nint\r\nmain(int, char *[])\r\n{\r\n    typedef undirected_graph<> Graph;\r\n    typedef directed_graph<> Digraph;\r\n\r\n    test_undirected<Graph>();\r\n    test_directed<Digraph>();\r\n}\r\n", "meta": {"hexsha": "81dad1a218118d519fc87f8abd8dfc1c5ddc0e3d", "size": 4075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/test/closeness_centrality.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/test/closeness_centrality.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": 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/graph/test/closeness_centrality.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": 30.1851851852, "max_line_length": 77, "alphanum_fraction": 0.6986503067, "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800692021119887, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5677059533968727}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"main.h\"\n#include <Eigen/QR>\n#include <Eigen/SVD>\n\ntemplate <typename MatrixType>\nvoid cod() {\n  typedef typename MatrixType::Index Index;\n\n  Index rows = internal::random<Index>(2, EIGEN_TEST_MAX_SIZE);\n  Index cols = internal::random<Index>(2, EIGEN_TEST_MAX_SIZE);\n  Index cols2 = internal::random<Index>(2, EIGEN_TEST_MAX_SIZE);\n  Index rank = internal::random<Index>(1, (std::min)(rows, cols) - 1);\n\n  typedef typename MatrixType::Scalar Scalar;\n  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime,\n                 MatrixType::RowsAtCompileTime>\n      MatrixQType;\n  MatrixType matrix;\n  createRandomPIMatrixOfRank(rank, rows, cols, matrix);\n  CompleteOrthogonalDecomposition<MatrixType> cod(matrix);\n  VERIFY(rank == cod.rank());\n  VERIFY(cols - cod.rank() == cod.dimensionOfKernel());\n  VERIFY(!cod.isInjective());\n  VERIFY(!cod.isInvertible());\n  VERIFY(!cod.isSurjective());\n\n  MatrixQType q = cod.householderQ();\n  VERIFY_IS_UNITARY(q);\n\n  MatrixType z = cod.matrixZ();\n  VERIFY_IS_UNITARY(z);\n\n  MatrixType t;\n  t.setZero(rows, cols);\n  t.topLeftCorner(rank, rank) =\n      cod.matrixT().topLeftCorner(rank, rank).template triangularView<Upper>();\n\n  MatrixType c = q * t * z * cod.colsPermutation().inverse();\n  VERIFY_IS_APPROX(matrix, c);\n\n  MatrixType exact_solution = MatrixType::Random(cols, cols2);\n  MatrixType rhs = matrix * exact_solution;\n  MatrixType cod_solution = cod.solve(rhs);\n  VERIFY_IS_APPROX(rhs, matrix * cod_solution);\n\n  // Verify that we get the same minimum-norm solution as the SVD.\n  JacobiSVD<MatrixType> svd(matrix, ComputeThinU | ComputeThinV);\n  MatrixType svd_solution = svd.solve(rhs);\n  VERIFY_IS_APPROX(cod_solution, svd_solution);\n\n  MatrixType pinv = cod.pseudoInverse();\n  VERIFY_IS_APPROX(cod_solution, pinv * rhs);\n}\n\ntemplate <typename MatrixType, int Cols2>\nvoid cod_fixedsize() {\n  enum {\n    Rows = MatrixType::RowsAtCompileTime,\n    Cols = MatrixType::ColsAtCompileTime\n  };\n  typedef typename MatrixType::Scalar Scalar;\n  int rank = internal::random<int>(1, (std::min)(int(Rows), int(Cols)) - 1);\n  Matrix<Scalar, Rows, Cols> matrix;\n  createRandomPIMatrixOfRank(rank, Rows, Cols, matrix);\n  CompleteOrthogonalDecomposition<Matrix<Scalar, Rows, Cols> > cod(matrix);\n  VERIFY(rank == cod.rank());\n  VERIFY(Cols - cod.rank() == cod.dimensionOfKernel());\n  VERIFY(cod.isInjective() == (rank == Rows));\n  VERIFY(cod.isSurjective() == (rank == Cols));\n  VERIFY(cod.isInvertible() == (cod.isInjective() && cod.isSurjective()));\n\n  Matrix<Scalar, Cols, Cols2> exact_solution;\n  exact_solution.setRandom(Cols, Cols2);\n  Matrix<Scalar, Rows, Cols2> rhs = matrix * exact_solution;\n  Matrix<Scalar, Cols, Cols2> cod_solution = cod.solve(rhs);\n  VERIFY_IS_APPROX(rhs, matrix * cod_solution);\n\n  // Verify that we get the same minimum-norm solution as the SVD.\n  JacobiSVD<MatrixType> svd(matrix, ComputeFullU | ComputeFullV);\n  Matrix<Scalar, Cols, Cols2> svd_solution = svd.solve(rhs);\n  VERIFY_IS_APPROX(cod_solution, svd_solution);\n}\n\ntemplate<typename MatrixType> void qr()\n{\n  using std::sqrt;\n  typedef typename MatrixType::Index Index;\n\n  Index rows = internal::random<Index>(2,EIGEN_TEST_MAX_SIZE), cols = internal::random<Index>(2,EIGEN_TEST_MAX_SIZE), cols2 = internal::random<Index>(2,EIGEN_TEST_MAX_SIZE);\n  Index rank = internal::random<Index>(1, (std::min)(rows, cols)-1);\n\n  typedef typename MatrixType::Scalar Scalar;\n  typedef typename MatrixType::RealScalar RealScalar;\n  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> MatrixQType;\n  MatrixType m1;\n  createRandomPIMatrixOfRank(rank,rows,cols,m1);\n  ColPivHouseholderQR<MatrixType> qr(m1);\n  VERIFY_IS_EQUAL(rank, qr.rank());\n  VERIFY_IS_EQUAL(cols - qr.rank(), qr.dimensionOfKernel());\n  VERIFY(!qr.isInjective());\n  VERIFY(!qr.isInvertible());\n  VERIFY(!qr.isSurjective());\n\n  MatrixQType q = qr.householderQ();\n  VERIFY_IS_UNITARY(q);\n\n  MatrixType r = qr.matrixQR().template triangularView<Upper>();\n  MatrixType c = q * r * qr.colsPermutation().inverse();\n  VERIFY_IS_APPROX(m1, c);\n\n  // Verify that the absolute value of the diagonal elements in R are\n  // non-increasing until they reach the singularity threshold.\n  RealScalar threshold =\n      sqrt(RealScalar(rows)) * numext::abs(r(0, 0)) * NumTraits<Scalar>::epsilon();\n  for (Index i = 0; i < (std::min)(rows, cols) - 1; ++i) {\n    RealScalar x = numext::abs(r(i, i));\n    RealScalar y = numext::abs(r(i + 1, i + 1));\n    if (x < threshold && y < threshold) continue;\n    if (!test_isApproxOrLessThan(y, x)) {\n      for (Index j = 0; j < (std::min)(rows, cols); ++j) {\n        std::cout << \"i = \" << j << \", |r_ii| = \" << numext::abs(r(j, j)) << std::endl;\n      }\n      std::cout << \"Failure at i=\" << i << \", rank=\" << rank\n                << \", threshold=\" << threshold << std::endl;\n    }\n    VERIFY_IS_APPROX_OR_LESS_THAN(y, x);\n  }\n\n  MatrixType m2 = MatrixType::Random(cols,cols2);\n  MatrixType m3 = m1*m2;\n  m2 = MatrixType::Random(cols,cols2);\n  m2 = qr.solve(m3);\n  VERIFY_IS_APPROX(m3, m1*m2);\n}\n\ntemplate<typename MatrixType, int Cols2> void qr_fixedsize()\n{\n  using std::sqrt;\n  using std::abs;\n  enum { Rows = MatrixType::RowsAtCompileTime, Cols = MatrixType::ColsAtCompileTime };\n  typedef typename MatrixType::Scalar Scalar;\n  typedef typename MatrixType::RealScalar RealScalar;\n  int rank = internal::random<int>(1, (std::min)(int(Rows), int(Cols))-1);\n  Matrix<Scalar,Rows,Cols> m1;\n  createRandomPIMatrixOfRank(rank,Rows,Cols,m1);\n  ColPivHouseholderQR<Matrix<Scalar,Rows,Cols> > qr(m1);\n  VERIFY_IS_EQUAL(rank, qr.rank());\n  VERIFY_IS_EQUAL(Cols - qr.rank(), qr.dimensionOfKernel());\n  VERIFY_IS_EQUAL(qr.isInjective(), (rank == Rows));\n  VERIFY_IS_EQUAL(qr.isSurjective(), (rank == Cols));\n  VERIFY_IS_EQUAL(qr.isInvertible(), (qr.isInjective() && qr.isSurjective()));\n\n  Matrix<Scalar,Rows,Cols> r = qr.matrixQR().template triangularView<Upper>();\n  Matrix<Scalar,Rows,Cols> c = qr.householderQ() * r * qr.colsPermutation().inverse();\n  VERIFY_IS_APPROX(m1, c);\n\n  Matrix<Scalar,Cols,Cols2> m2 = Matrix<Scalar,Cols,Cols2>::Random(Cols,Cols2);\n  Matrix<Scalar,Rows,Cols2> m3 = m1*m2;\n  m2 = Matrix<Scalar,Cols,Cols2>::Random(Cols,Cols2);\n  m2 = qr.solve(m3);\n  VERIFY_IS_APPROX(m3, m1*m2);\n  // Verify that the absolute value of the diagonal elements in R are\n  // non-increasing until they reache the singularity threshold.\n  RealScalar threshold =\n      sqrt(RealScalar(Rows)) * (std::abs)(r(0, 0)) * NumTraits<Scalar>::epsilon();\n  for (Index i = 0; i < (std::min)(int(Rows), int(Cols)) - 1; ++i) {\n    RealScalar x = numext::abs(r(i, i));\n    RealScalar y = numext::abs(r(i + 1, i + 1));\n    if (x < threshold && y < threshold) continue;\n    if (!test_isApproxOrLessThan(y, x)) {\n      for (Index j = 0; j < (std::min)(int(Rows), int(Cols)); ++j) {\n        std::cout << \"i = \" << j << \", |r_ii| = \" << numext::abs(r(j, j)) << std::endl;\n      }\n      std::cout << \"Failure at i=\" << i << \", rank=\" << rank\n                << \", threshold=\" << threshold << std::endl;\n    }\n    VERIFY_IS_APPROX_OR_LESS_THAN(y, x);\n  }\n}\n\n// This test is meant to verify that pivots are chosen such that\n// even for a graded matrix, the diagonal of R falls of roughly\n// monotonically until it reaches the threshold for singularity.\n// We use the so-called Kahan matrix, which is a famous counter-example\n// for rank-revealing QR. See\n// http://www.netlib.org/lapack/lawnspdf/lawn176.pdf\n// page 3 for more detail.\ntemplate<typename MatrixType> void qr_kahan_matrix()\n{\n  using std::sqrt;\n  using std::abs;\n  typedef typename MatrixType::Index Index;\n  typedef typename MatrixType::Scalar Scalar;\n  typedef typename MatrixType::RealScalar RealScalar;\n\n  Index rows = 300, cols = rows;\n\n  MatrixType m1;\n  m1.setZero(rows,cols);\n  RealScalar s = std::pow(NumTraits<RealScalar>::epsilon(), 1.0 / rows);\n  RealScalar c = std::sqrt(1 - s*s);\n  RealScalar pow_s_i(1.0); // pow(s,i)\n  for (Index i = 0; i < rows; ++i) {\n    m1(i, i) = pow_s_i;\n    m1.row(i).tail(rows - i - 1) = -pow_s_i * c * MatrixType::Ones(1, rows - i - 1);\n    pow_s_i *= s;\n  }\n  m1 = (m1 + m1.transpose()).eval();\n  ColPivHouseholderQR<MatrixType> qr(m1);\n  MatrixType r = qr.matrixQR().template triangularView<Upper>();\n\n  RealScalar threshold =\n      std::sqrt(RealScalar(rows)) * numext::abs(r(0, 0)) * NumTraits<Scalar>::epsilon();\n  for (Index i = 0; i < (std::min)(rows, cols) - 1; ++i) {\n    RealScalar x = numext::abs(r(i, i));\n    RealScalar y = numext::abs(r(i + 1, i + 1));\n    if (x < threshold && y < threshold) continue;\n    if (!test_isApproxOrLessThan(y, x)) {\n      for (Index j = 0; j < (std::min)(rows, cols); ++j) {\n        std::cout << \"i = \" << j << \", |r_ii| = \" << numext::abs(r(j, j)) << std::endl;\n      }\n      std::cout << \"Failure at i=\" << i << \", rank=\" << qr.rank()\n                << \", threshold=\" << threshold << std::endl;\n    }\n    VERIFY_IS_APPROX_OR_LESS_THAN(y, x);\n  }\n}\n\ntemplate<typename MatrixType> void qr_invertible()\n{\n  using std::log;\n  using std::abs;\n  typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;\n  typedef typename MatrixType::Scalar Scalar;\n\n  int size = internal::random<int>(10,50);\n\n  MatrixType m1(size, size), m2(size, size), m3(size, size);\n  m1 = MatrixType::Random(size,size);\n\n  if (internal::is_same<RealScalar,float>::value)\n  {\n    // let's build a matrix more stable to inverse\n    MatrixType a = MatrixType::Random(size,size*2);\n    m1 += a * a.adjoint();\n  }\n\n  ColPivHouseholderQR<MatrixType> qr(m1);\n  m3 = MatrixType::Random(size,size);\n  m2 = qr.solve(m3);\n  //VERIFY_IS_APPROX(m3, m1*m2);\n\n  // now construct a matrix with prescribed determinant\n  m1.setZero();\n  for(int i = 0; i < size; i++) m1(i,i) = internal::random<Scalar>();\n  RealScalar absdet = abs(m1.diagonal().prod());\n  m3 = qr.householderQ(); // get a unitary\n  m1 = m3 * m1 * m3;\n  qr.compute(m1);\n  VERIFY_IS_APPROX(absdet, qr.absDeterminant());\n  VERIFY_IS_APPROX(log(absdet), qr.logAbsDeterminant());\n}\n\ntemplate<typename MatrixType> void qr_verify_assert()\n{\n  MatrixType tmp;\n\n  ColPivHouseholderQR<MatrixType> qr;\n  VERIFY_RAISES_ASSERT(qr.matrixQR())\n  VERIFY_RAISES_ASSERT(qr.solve(tmp))\n  VERIFY_RAISES_ASSERT(qr.householderQ())\n  VERIFY_RAISES_ASSERT(qr.dimensionOfKernel())\n  VERIFY_RAISES_ASSERT(qr.isInjective())\n  VERIFY_RAISES_ASSERT(qr.isSurjective())\n  VERIFY_RAISES_ASSERT(qr.isInvertible())\n  VERIFY_RAISES_ASSERT(qr.inverse())\n  VERIFY_RAISES_ASSERT(qr.absDeterminant())\n  VERIFY_RAISES_ASSERT(qr.logAbsDeterminant())\n}\n\nvoid test_qr_colpivoting()\n{\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( qr<MatrixXf>() );\n    CALL_SUBTEST_2( qr<MatrixXd>() );\n    CALL_SUBTEST_3( qr<MatrixXcd>() );\n    CALL_SUBTEST_4(( qr_fixedsize<Matrix<float,3,5>, 4 >() ));\n    CALL_SUBTEST_5(( qr_fixedsize<Matrix<double,6,2>, 3 >() ));\n    CALL_SUBTEST_5(( qr_fixedsize<Matrix<double,1,1>, 1 >() ));\n  }\n\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( cod<MatrixXf>() );\n    CALL_SUBTEST_2( cod<MatrixXd>() );\n    CALL_SUBTEST_3( cod<MatrixXcd>() );\n    CALL_SUBTEST_4(( cod_fixedsize<Matrix<float,3,5>, 4 >() ));\n    CALL_SUBTEST_5(( cod_fixedsize<Matrix<double,6,2>, 3 >() ));\n    CALL_SUBTEST_5(( cod_fixedsize<Matrix<double,1,1>, 1 >() ));\n  }\n\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( qr_invertible<MatrixXf>() );\n    CALL_SUBTEST_2( qr_invertible<MatrixXd>() );\n    CALL_SUBTEST_6( qr_invertible<MatrixXcf>() );\n    CALL_SUBTEST_3( qr_invertible<MatrixXcd>() );\n  }\n\n  CALL_SUBTEST_7(qr_verify_assert<Matrix3f>());\n  CALL_SUBTEST_8(qr_verify_assert<Matrix3d>());\n  CALL_SUBTEST_1(qr_verify_assert<MatrixXf>());\n  CALL_SUBTEST_2(qr_verify_assert<MatrixXd>());\n  CALL_SUBTEST_6(qr_verify_assert<MatrixXcf>());\n  CALL_SUBTEST_3(qr_verify_assert<MatrixXcd>());\n\n  // Test problem size constructors\n  CALL_SUBTEST_9(ColPivHouseholderQR<MatrixXf>(10, 20));\n\n  CALL_SUBTEST_1( qr_kahan_matrix<MatrixXf>() );\n  CALL_SUBTEST_2( qr_kahan_matrix<MatrixXd>() );\n}\n", "meta": {"hexsha": "057bb014cf15ec94cb6d90a073caef9af0e1b8cf", "size": 12394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jni-build/jni/include/external/eigen_archive/test/qr_colpivoting.cpp", "max_stars_repo_name": "rcelebi/android-elfali", "max_stars_repo_head_hexsha": "4ea14a58a18356ef9e16aba2e7dae84c02afba12", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 680.0, "max_stars_repo_stars_event_min_datetime": "2016-12-03T14:38:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T04:06:45.000Z", "max_issues_repo_path": "jni-build/jni/include/external/eigen_archive/test/qr_colpivoting.cpp", "max_issues_repo_name": "rcelebi/android-elfali", "max_issues_repo_head_hexsha": "4ea14a58a18356ef9e16aba2e7dae84c02afba12", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2016-11-17T08:43:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-12T12:27:04.000Z", "max_forks_repo_path": "jni-build/jni/include/external/eigen_archive/test/qr_colpivoting.cpp", "max_forks_repo_name": "rcelebi/android-elfali", "max_forks_repo_head_hexsha": "4ea14a58a18356ef9e16aba2e7dae84c02afba12", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 250.0, "max_forks_repo_forks_event_min_datetime": "2016-12-05T10:37:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T21:26:55.000Z", "avg_line_length": 37.4441087613, "max_line_length": 173, "alphanum_fraction": 0.6782314023, "num_tokens": 3720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5677059515757993}}
{"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": "/* Boost test/pow.cpp\r\n * test the pow function\r\n *\r\n * Copyright Guillaume Melquiond 2002-2003\r\n * Permission to use, copy, modify, sell, and distribute this software\r\n * is hereby granted without fee provided that the above copyright notice\r\n * appears in all copies and that both that copyright notice and this\r\n * permission notice appear in supporting documentation.\r\n *\r\n * None of the above authors nor Polytechnic University make any\r\n * representation about the suitability of this software for any\r\n * purpose. It is provided \"as is\" without express or implied warranty.\r\n *\r\n * $Id: pow.cpp,v 1.3 2003/02/05 17:34:36 gmelquio Exp $\r\n */\r\n\r\n#include <boost/numeric/interval.hpp>\r\n#include <boost/test/minimal.hpp>\r\n\r\nbool test_pow(double al, double au, double bl, double bu, int p) {\r\n  typedef boost::numeric::interval<double> I;\r\n  I b = pow(I(al, au), p);\r\n  return b.lower() == bl && b.upper() == bu;\r\n}\r\n\r\nint test_main(int, char *[]) {\r\n  BOOST_TEST(test_pow(2, 3, 8, 27, 3));\r\n  BOOST_TEST(test_pow(2, 3, 16, 81, 4));\r\n  BOOST_TEST(test_pow(-3, 2, -27, 8, 3));\r\n  BOOST_TEST(test_pow(-3, 2, 0, 81, 4));\r\n  BOOST_TEST(test_pow(-3, -2, -27, -8, 3));\r\n  BOOST_TEST(test_pow(-3, -2, 16, 81, 4));\r\n\r\n  BOOST_TEST(test_pow(2, 4, 1./64, 1./8, -3));\r\n  BOOST_TEST(test_pow(2, 4, 1./256, 1./16, -4));\r\n  BOOST_TEST(test_pow(-4, -2, -1./8, -1./64, -3));\r\n  BOOST_TEST(test_pow(-4, -2, 1./256, 1./16, -4));\r\n\r\n  BOOST_TEST(test_pow(2, 3, 1, 1, 0));\r\n  BOOST_TEST(test_pow(-3, 2, 1, 1, 0));\r\n  BOOST_TEST(test_pow(-3, -2, 1, 1, 0));\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "c6fd297e35345ed448662f05bed39ea8923b5adf", "size": 1557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/test/pow.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/test/pow.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/test/pow.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6, "max_line_length": 74, "alphanum_fraction": 0.6416184971, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5677059448316332}}
{"text": "/*\n * @brief A general filter class. Replicates \"filt\" in Matlab\n * @author Jenna Reher (jreher@caltech.edu)\n */\n\n#ifndef SMOOTHING_HPP\n#define SMOOTHING_HPP\n\n#include <Eigen/Dense>\n#include <iostream>\n\nnamespace cassie_common_toolbox {\n\nclass ButterFilter\n{\npublic:\n    ButterFilter();\n    ButterFilter(Eigen::VectorXd &b, Eigen::VectorXd &a);\n    void reconfigure(Eigen::VectorXd &b, Eigen::VectorXd &a);\n    void update(double x_raw);\n    double getValue();\n    void reset();\n\nprivate:\n    long nb;\n    long na;\n    Eigen::VectorXd y_; // Array of previously filtered values\n    Eigen::VectorXd x_; // Array of raw values\n    Eigen::VectorXd b_; // filter coefficient\n    Eigen::VectorXd a_; // filter coefficient\n};\n\nclass MovingAverage\n{\npublic:\n    MovingAverage();\n    MovingAverage(int nSamples, int dim);\n    void reset();\n    void reconfigure(int nSamples, int dim);\n    void update(Eigen::VectorXd &raw);\n    Eigen::VectorXd getValue();\nprivate:\n    int nSamples;\n    int cur_index;\n    Eigen::MatrixXd array;\n};\n\n}\n\n#endif // SMOOTHING_HPP\n", "meta": {"hexsha": "865fdcde67ed0d29a2e57ea5ccd151c4b6340d88", "size": 1052, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cassie_common_toolbox/smoothing.hpp", "max_stars_repo_name": "jpreher/cassie_common_toolbox", "max_stars_repo_head_hexsha": "e01065a56e4a0a71607bfe412834a9a8b541fe28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-11T22:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-11T22:56:02.000Z", "max_issues_repo_path": "include/cassie_common_toolbox/smoothing.hpp", "max_issues_repo_name": "jpreher/cassie_common_toolbox", "max_issues_repo_head_hexsha": "e01065a56e4a0a71607bfe412834a9a8b541fe28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cassie_common_toolbox/smoothing.hpp", "max_forks_repo_name": "jpreher/cassie_common_toolbox", "max_forks_repo_head_hexsha": "e01065a56e4a0a71607bfe412834a9a8b541fe28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-04T21:22:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T21:22:53.000Z", "avg_line_length": 20.6274509804, "max_line_length": 62, "alphanum_fraction": 0.6853612167, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5677055664889596}}
{"text": "/*\n* compile with flags:   g++ test.cc tree_classifier.cc   -std=c++14 -larmadillo -I ../../include/\n* author: Yuzhen Liu\n* Date: 2019.5.8 17:35\n*/\n\n#include <iostream>\n#include <armadillo>\n#include <cmath>\n#include <stdlib.h>\n#include <datasets/datasets.h>\n#include <probalistic/naive_bayes.h>\n\nusing namespace std;\nusing namespace arma;\n\npair<umat, uvec> generate_data() {\n    int n_sample = 100;\n    int n_feature = 4;\n    umat x(n_feature, n_sample);    \n    uvec y(n_sample);\n\n    // generate n samples iteratively\n    srand((unsigned)time(NULL));\n    for(int i =0; i < n_sample; i++) {\n        x(0, i) = rand() % 10;\n        x(1, i) = rand() % 10 + 100;\n        x(2, i) = rand() % 10;\n        x(3, i) = rand() % 10;\n\n        if (x(0, i) <= 5 && x(1, i) > 105 && x(2, i) > 5 )  y(i) = 0;\n        else if (x(0, i) > 5 && x(1, i) == 106 && x(2, i) <= 5 && x(3, i) > 5)  y(i) = 1;\n        else if (x(0, i) <= 5 && x(1, i) <= 105 && x(2, i) < 5)  y(i) = 2;\n        else y(i) = 3;\n    }\n    return make_pair(x, y);\n}\n\n\nint main() {\n    pair<umat, uvec> p = generate_data();\n    mat x = conv_to<mat>::from(p.first);\n    uvec y = p.second;\n\n    Datasets dataset = Datasets(\"iris\");\n    mat x = dataset.x;\n    uvec y = conv_to<uvec>::from(dataset.y);\n\n\n    // Naive_Bayes bayes_classifier = Naive_Bayes();\n    // bayes_classifier.train(x, mat(0, 0), y);\n    // uvec res = bayes_classifier.predict(x, mat(0, 0));\n\n    uvec dis = res - y;\n    int count =0;\n    for (int i =0; i < dis.n_elem; i++) {\n        if (dis(i) == 0) count++;\n    }\n    // dis.print();\n    cout << \"The accuracy is: \" << (count * 100/ dis.n_elem) << \"%.\" << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "5dbbd161d3c379da83d3a692f51878873b5a2cce", "size": 1650, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/naive_bayes_test.cc", "max_stars_repo_name": "codestorm04/Machine_Learning_CPP", "max_stars_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-06-05T09:31:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T13:37:44.000Z", "max_issues_repo_path": "examples/naive_bayes_test.cc", "max_issues_repo_name": "codestorm04/Machine_Learning_CPP", "max_issues_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/naive_bayes_test.cc", "max_forks_repo_name": "codestorm04/Machine_Learning_CPP", "max_forks_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-11-15T04:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T15:59:30.000Z", "avg_line_length": 25.3846153846, "max_line_length": 97, "alphanum_fraction": 0.5248484848, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5676948274720123}}
{"text": "// Copyright 2004 The Trustees of Indiana University.\r\n\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  Authors: Douglas Gregor\r\n//           Andrew Lumsdaine\r\n#ifndef BOOST_GRAPH_RANDOM_LAYOUT_HPP\r\n#define BOOST_GRAPH_RANDOM_LAYOUT_HPP\r\n\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/random/uniform_int.hpp>\r\n#include <boost/random/uniform_01.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/type_traits/is_integral.hpp>\r\n#include <boost/mpl/if.hpp>\r\n\r\nnamespace boost {\r\n\r\ntemplate<typename Graph, typename PositionMap, typename Dimension, \r\n         typename RandomNumberGenerator>\r\nvoid\r\nrandom_graph_layout(const Graph& g, PositionMap position_map,\r\n                    Dimension minX, Dimension maxX, \r\n                    Dimension minY, Dimension maxY,\r\n                    RandomNumberGenerator& gen)\r\n{\r\n  typedef typename mpl::if_<is_integral<Dimension>,\r\n                            uniform_int<Dimension>,\r\n                            uniform_real<Dimension> >::type distrib_t;\r\n  typedef typename mpl::if_<is_integral<Dimension>,\r\n                            RandomNumberGenerator&,\r\n                            uniform_01<RandomNumberGenerator, Dimension> >\r\n    ::type gen_t;\r\n\r\n  gen_t my_gen(gen);\r\n  distrib_t x(minX, maxX);\r\n  distrib_t y(minY, maxY);\r\n  typename graph_traits<Graph>::vertex_iterator vi, vi_end;\r\n  for(tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {\r\n    position_map[*vi].x = x(my_gen);\r\n    position_map[*vi].y = y(my_gen);\r\n  }\r\n}\r\n\r\n} // end namespace boost\r\n\r\n#endif // BOOST_GRAPH_RANDOM_LAYOUT_HPP\r\n", "meta": {"hexsha": "1bf75f26741bdde48aeaf1c1994484ceb776374a", "size": 1694, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/graph/random_layout.hpp", "max_stars_repo_name": "dstrigl/mcotf", "max_stars_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-12-29T07:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T10:47:38.000Z", "max_issues_repo_path": "include/boost/graph/random_layout.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/graph/random_layout.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": 33.88, "max_line_length": 75, "alphanum_fraction": 0.6587957497, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.5676915174435984}}
{"text": "#include <memory>\n#include <vector>\n\n#include <Eigen/Core>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n\n#include <opengv/absolute_pose/CentralAbsoluteAdapter.hpp>\n#include <opengv/absolute_pose/methods.hpp>\n#include <opengv/sac/Ransac.hpp>\n#include <opengv/sac_problems/absolute_pose/AbsolutePoseSacProblem.hpp>\n\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\nTEST(OpengvPoseEstimation, KneipP3p) {\n  opengv::bearingVectors_t bearing_vectors;\n  opengv::points_t points;\n\n  points.push_back(opengv::point_t(0, -1, 5));\n  points.push_back(opengv::point_t(-1, 0, 0));\n  points.push_back(opengv::point_t(1, 0, 10));\n\n  bearing_vectors.push_back(opengv::bearingVector_t(0, -1, 6).normalized());\n  bearing_vectors.push_back(opengv::bearingVector_t(-1, 0, 1).normalized());\n  bearing_vectors.push_back(opengv::bearingVector_t(1, 0, 11).normalized());\n\n  opengv::absolute_pose::CentralAbsoluteAdapter adapter(\n      bearing_vectors, points);\n\n  opengv::transformations_t p3p_kneip_transformations;\n  p3p_kneip_transformations = opengv::absolute_pose::p3p_kneip(adapter);\n\n  CHECK_EQ(4u, p3p_kneip_transformations.size());\n\n  Eigen::Matrix<double, 3, 4> expected_transform;\n  expected_transform << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1;\n\n  const bool is_1st_guess_matching =\n      p3p_kneip_transformations[0].isApprox(expected_transform, 1e-10);\n  const bool is_2nd_guess_matching =\n      p3p_kneip_transformations[1].isApprox(expected_transform, 1e-10);\n  const bool is_3rd_guess_matching =\n      p3p_kneip_transformations[2].isApprox(expected_transform, 1e-10);\n  const bool is_4th_guess_matching =\n      p3p_kneip_transformations[3].isApprox(expected_transform, 1e-10);\n\n  EXPECT_TRUE(\n      is_1st_guess_matching || is_2nd_guess_matching || is_3rd_guess_matching ||\n      is_4th_guess_matching);\n}\n\nTEST(OpengvPoseEstimation, KneipP3pRansac) {\n  opengv::bearingVectors_t bearing_vectors;\n  opengv::points_t points;\n\n  points.push_back(opengv::point_t(0, -1, 0));\n  points.push_back(opengv::point_t(-1, 0, 0));\n  points.push_back(opengv::point_t(1, 0, 1));\n  points.push_back(opengv::point_t(1, 1, 8));\n\n  bearing_vectors.push_back(opengv::bearingVector_t(0, -1, 1).normalized());\n  bearing_vectors.push_back(opengv::bearingVector_t(-1, 0, 1).normalized());\n  bearing_vectors.push_back(opengv::bearingVector_t(1, 0, 2).normalized());\n  bearing_vectors.push_back(opengv::bearingVector_t(1, 1, 9).normalized());\n\n  opengv::absolute_pose::CentralAbsoluteAdapter adapter(\n      bearing_vectors, points);\n\n  opengv::sac::Ransac<\n      opengv::sac_problems::absolute_pose::AbsolutePoseSacProblem>\n      ransac;\n  std::shared_ptr<opengv::sac_problems::absolute_pose::AbsolutePoseSacProblem>\n      absposeproblem_ptr(\n          new opengv::sac_problems::absolute_pose::AbsolutePoseSacProblem(\n              adapter, opengv::sac_problems::absolute_pose::\n                           AbsolutePoseSacProblem::KNEIP));\n  ransac.sac_model_ = absposeproblem_ptr;\n  ransac.threshold_ = 1.0 - cos(atan(sqrt(2.0) * 0.5 / 800.0));\n  ransac.max_iterations_ = 50;\n\n  ransac.computeModel();\n  Eigen::Matrix<double, 3, 4> expected_transform;\n  expected_transform << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1;\n  EXPECT_NEAR_EIGEN(expected_transform, ransac.model_coefficients_, 1e-10);\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "f6c07a73b52906537ca8f938799ec24f7276861c", "size": 3342, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/geometric-vision-algorithms/test/test_pnp_pose_test.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "algorithms/geometric-vision-algorithms/test/test_pnp_pose_test.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "algorithms/geometric-vision-algorithms/test/test_pnp_pose_test.cc", "max_forks_repo_name": "AdronTech/maplab", "max_forks_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 661.0, "max_forks_repo_forks_event_min_datetime": "2017-11-28T07:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:06:29.000Z", "avg_line_length": 37.5505617978, "max_line_length": 80, "alphanum_fraction": 0.7432675045, "num_tokens": 1053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5676914994219667}}
{"text": "/*\n * Website:\n *      https://github.com/wo3kie/dojo\n *\n * Author:\n *      Lukasz Czerwinski\n *\n * Compilation:\n *      g++ --std=c++11 countBits.cpp -o countBits\n *\n * Usage:\n *      $ ./countBits\n */\n\n\n#include <cassert>\n#include <random>\n\n#include <boost/preprocessor/repetition/repeat.hpp>\n\nconstexpr int countBits8(unsigned char i){\n    return \n        i == 0\n        ? 0\n        : (i & 1) + countBits8(i / 2);\n}\n\n#define COUNT_BITS_CALCULATE(z, n, data) \\\n    countBits8(n),\n\nint countBits(\n    unsigned char const * begin, \n    unsigned char const * const end\n){\n    constexpr int bits[256] = {\n        BOOST_PP_REPEAT(256, COUNT_BITS_CALCULATE, \"\")\n    };\n\n    int result = 0;\n\n    for( ; begin != end; ++begin){\n        result += bits[ * begin ];\n    }\n\n    return result;\n}\n\ntemplate<typename T>\nint countBits(T const & t){\n    unsigned char const * const begin \n        = reinterpret_cast< unsigned char const * >( & t );\n\n    return countBits(begin, begin + sizeof(T));\n}\n\n\nint main(){\n    for(int i = 0; i < 256; ++i){\n        assert(countBits8(i) == __builtin_popcount(i));\n    }\n\n    for(int i = 0; i < 256; ++i){\n        assert(countBits(i) == __builtin_popcount(i));\n    }\n\n    for(int i = 0; i < 1e4; ++i){\n        int const random = std::rand();\n        assert(countBits(random) == __builtin_popcount(random));\n    }\n}\n\n", "meta": {"hexsha": "c8c6544fac4ee28bbd6101d3801de1bdbb63d716", "size": 1340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "countBits.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": "countBits.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": "countBits.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": 18.6111111111, "max_line_length": 64, "alphanum_fraction": 0.5664179104, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5675511244275802}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"math/point_typed.h\" // header to test\n\nusing namespace biosim;\n\nBOOST_AUTO_TEST_SUITE(suite_point_typed)\n\nBOOST_AUTO_TEST_CASE(point_typed_ctor) {\n  math::point p_data({1.0, 2.0, 3.0});\n  math::point_typed p(p_data);\n  BOOST_CHECK(p.get_type() == math::point_typed::coordinate_type::cartesian);\n  BOOST_CHECK(p.get_point() == p_data);\n\n  p = math::point_typed(p_data, math::point_typed::coordinate_type::cylindrical);\n  BOOST_CHECK(p.get_type() == math::point_typed::coordinate_type::cylindrical);\n  BOOST_CHECK(p.get_point() == p_data);\n}\n\nBOOST_AUTO_TEST_CASE(point_typed_cmp_operator) {\n  math::point p_cart({3.0, 4.0, 5.0});\n  math::point p_cart2({3.0, 4.0, 6.0});\n  math::point p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);\n  math::point p_cart_again = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)\n                                 .to_type(math::point_typed::coordinate_type::cartesian);\n  BOOST_CHECK(p_cart == p_cart);\n  BOOST_CHECK(p_cart == p_cart_again);\n  BOOST_CHECK(p_cart != p_cart2);\n  BOOST_CHECK(p_cart != p_cyl);\n}\n\nBOOST_AUTO_TEST_CASE(point_typed_convert) {\n  math::point p_cart({3.0, 4.0, 5.0});\n  math::point p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);\n  BOOST_CHECK(p_cyl[0] == 5.0);\n  BOOST_CHECK_CLOSE(p_cyl[1], 0.927295, 1e-3);\n  BOOST_CHECK(p_cyl[2] == 5.0);\n  math::point p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)\n                            .to_type(math::point_typed::coordinate_type::cartesian);\n  BOOST_CHECK_CLOSE(p_cart2[0], 3.0, 1e-3);\n  BOOST_CHECK_CLOSE(p_cart2[1], 4.0, 1e-3);\n  BOOST_CHECK(p_cart2[2] == 5.0);\n\n  p_cart = math::point({-3.0, 4.0, 5.0});\n  p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);\n  BOOST_CHECK(p_cyl[0] == 5.0);\n  BOOST_CHECK_CLOSE(p_cyl[1], 2.214297, 1e-3);\n  BOOST_CHECK(p_cyl[2] == 5.0);\n  p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)\n                .to_type(math::point_typed::coordinate_type::cartesian);\n  BOOST_CHECK_CLOSE(p_cart2[0], -3.0, 1e-3);\n  BOOST_CHECK_CLOSE(p_cart2[1], 4.0, 1e-3);\n  BOOST_CHECK(p_cart2[2] == 5.0);\n\n  p_cart = math::point({-3.0, -4.0, 5.0});\n  p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);\n  BOOST_CHECK(p_cyl[0] == 5.0);\n  BOOST_CHECK_CLOSE(p_cyl[1], -2.214297, 1e-3);\n  BOOST_CHECK(p_cyl[2] == 5.0);\n  p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)\n                .to_type(math::point_typed::coordinate_type::cartesian);\n  BOOST_CHECK_CLOSE(p_cart2[0], -3.0, 1e-3);\n  BOOST_CHECK_CLOSE(p_cart2[1], -4.0, 1e-3);\n  BOOST_CHECK(p_cart2[2] == 5.0);\n\n  p_cart = math::point({3.0, -4.0, 5.0});\n  p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);\n  BOOST_CHECK(p_cyl[0] == 5.0);\n  BOOST_CHECK_CLOSE(p_cyl[1], -0.927295, 1e-3);\n  BOOST_CHECK(p_cyl[2] == 5.0);\n  p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)\n                .to_type(math::point_typed::coordinate_type::cartesian);\n  BOOST_CHECK_CLOSE(p_cart2[0], 3.0, 1e-3);\n  BOOST_CHECK_CLOSE(p_cart2[1], -4.0, 1e-3);\n  BOOST_CHECK(p_cart2[2] == 5.0);\n\n  p_cart = math::point({0.0, 4.0, 5.0});\n  p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);\n  BOOST_CHECK(p_cyl[0] == 4.0);\n  BOOST_CHECK_CLOSE(p_cyl[1], 1.5708, 1e-3);\n  BOOST_CHECK(p_cyl[2] == 5.0);\n  p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)\n                .to_type(math::point_typed::coordinate_type::cartesian);\n  BOOST_CHECK_SMALL(p_cart2[0], 1e-5);\n  BOOST_CHECK_CLOSE(p_cart2[1], 4.0, 1e-3);\n  BOOST_CHECK(p_cart2[2] == 5.0);\n\n  p_cart = math::point({0.0, -4.0, 5.0});\n  p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);\n  BOOST_CHECK(p_cyl[0] == 4.0);\n  BOOST_CHECK_CLOSE(p_cyl[1], -1.5708, 1e-3);\n  BOOST_CHECK(p_cyl[2] == 5.0);\n  p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)\n                .to_type(math::point_typed::coordinate_type::cartesian);\n  BOOST_CHECK_SMALL(p_cart2[0], 1e-5);\n  BOOST_CHECK_CLOSE(p_cart2[1], -4.0, 1e-3);\n  BOOST_CHECK(p_cart2[2] == 5.0);\n\n  p_cart = math::point({0.0, 0.0, 5.0});\n  p_cyl = math::point_typed(p_cart).to_type(math::point_typed::coordinate_type::cylindrical);\n  BOOST_CHECK(p_cyl[0] == 0.0);\n  BOOST_CHECK(p_cyl[1] == 0.0);\n  BOOST_CHECK(p_cyl[2] == 5.0);\n  p_cart2 = math::point_typed(p_cyl, math::point_typed::coordinate_type::cylindrical)\n                .to_type(math::point_typed::coordinate_type::cartesian);\n  BOOST_CHECK_SMALL(p_cart2[0], 1e-5);\n  BOOST_CHECK_SMALL(p_cart2[1], 1e-5);\n  BOOST_CHECK(p_cart2[2] == 5.0);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "b2f28019298084080eba320d5546bb13163b8008", "size": 4934, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/point_typed.cpp", "max_stars_repo_name": "shze/biosim", "max_stars_repo_head_hexsha": "e9e6d97de0ccf8067e1db15980eb600389fff6ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/point_typed.cpp", "max_issues_repo_name": "shze/biosim", "max_issues_repo_head_hexsha": "e9e6d97de0ccf8067e1db15980eb600389fff6ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/point_typed.cpp", "max_forks_repo_name": "shze/biosim", "max_forks_repo_head_hexsha": "e9e6d97de0ccf8067e1db15980eb600389fff6ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0535714286, "max_line_length": 105, "alphanum_fraction": 0.6923388731, "num_tokens": 1747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.5675511206245988}}
{"text": "//####### Test module for rng_wrapper ####################################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"RNG wrapper\"\n\n//Will automatically define a main for this test\n #define BOOST_TEST_DYN_LINK\n\n#include <cstdint>\n#include <random>\n\n//Include Boost unit tests library\n#include <boost/test/unit_test.hpp>\n\n//Units choice. Not relevant here, but avoids compile-time warning\n#define PXRMP_USE_SI_UNITS\n#include \"rng_wrapper.hpp\"\n\nusing namespace picsar::multi_physics;\n\n// ------------- Tests --------------\n\n//***STL***\n\n//***Constructors\n\n//Test STL rng_wrapper constructors generic\ntemplate<typename T>\nvoid  rng_stl_wrapper_constructors(uint64_t seed)\n{\n    std::mt19937_64 rng{seed};\n\n    stl_rng_wrapper<T> wrp1{seed};\n    stl_rng_wrapper<T> wrp2(move(rng));\n\n    BOOST_CHECK_EQUAL( wrp1.unf(0.0,1.0), wrp2.unf(0.0,1.0));\n}\n\n//Test STL rng_wrapper constructors(double precision)\nBOOST_AUTO_TEST_CASE( rng_stl_wrapper_constructors_double )\n{\n    rng_stl_wrapper_constructors<double>(2391892344079);\n}\n\n//Test STL rng_wrapper constructors(single precision)\nBOOST_AUTO_TEST_CASE( rng_stl_wrapper_constructors_single )\n{\n    rng_stl_wrapper_constructors<float>(2391892344079);\n}\n\n//***Uniform distribution\n\n//Test STL rng_wrapper unf generic\ntemplate<typename T>\nvoid  rng_stl_wrapper_unf(uint64_t seed)\n{\n    stl_rng_wrapper<T> wrp{seed};\n    size_t how_many = 10000;\n    T a = static_cast<T>(-7.0);\n    T b = static_cast<T>(11.1);\n\n    for (size_t d = 0; d <= how_many; ++d){\n        T qq = wrp.unf(a,b);\n        BOOST_TEST( qq >= a);\n        BOOST_TEST( qq < b);\n    }\n}\n\n//Test STL rng_wrapper unf (double precision)\nBOOST_AUTO_TEST_CASE( rng_stl_wrapper_unf_double )\n{\n    rng_stl_wrapper_unf<double>(2391892344079);\n}\n\n//Test STL rng_wrapper unf (single precision)\nBOOST_AUTO_TEST_CASE( rng_stl_wrapper_unf_single )\n{\n    rng_stl_wrapper_unf<float>(2391892344079);\n}\n\n\n//Test STL rng_wrapper exp generic\ntemplate<typename T>\nvoid  rng_stl_wrapper_exp(uint64_t seed)\n{\n    stl_rng_wrapper<T> wrp{seed};\n    size_t how_many = 10000;\n    T l = static_cast<T>(1.0);\n\n    for (size_t d = 0; d <= how_many; ++d){\n        T qq = wrp.exp(l);\n        BOOST_TEST( qq >= 0.0);\n    }\n}\n\n\n//Test STL rng_wrapper exp (double precision)\nBOOST_AUTO_TEST_CASE( rng_stl_wrapper_exp_double )\n{\n    rng_stl_wrapper_exp<double>(2391892344079);\n}\n\n//Test STL rng_wrapper exp (single precision)\nBOOST_AUTO_TEST_CASE( rng_stl_wrapper_exp_single )\n{\n    rng_stl_wrapper_exp<float>(2391892344079);\n}\n\n//***Exponential distribution\n", "meta": {"hexsha": "45adf46e61cc134a287b759f89440e1656f6a815", "size": 2533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED_tests/test_rng_wrapper.cpp", "max_stars_repo_name": "thaisacs/PICSAR", "max_stars_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multi_physics/QED_tests/test_rng_wrapper.cpp", "max_issues_repo_name": "thaisacs/PICSAR", "max_issues_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multi_physics/QED_tests/test_rng_wrapper.cpp", "max_forks_repo_name": "thaisacs/PICSAR", "max_forks_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0272727273, "max_line_length": 74, "alphanum_fraction": 0.7058823529, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.5675511201336885}}
{"text": "#include <iostream>\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/io/ply_io.h>\n#include <pcl/point_cloud.h>\n#include <pcl/console/parse.h>\n#include <pcl/common/transforms.h>\n#include <pcl/visualization/pcl_visualizer.h>\n//#include <Eigen/Dense>\n//#include <Eigen/Core>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace pcl;\n\n// This function displays the help\nvoid showHelp(char * program_name)\n{\n\tstd::cout << std::endl;\n\tstd::cout << \"Usage: \" << program_name << \" cloud_filename.[pcd|ply]\" << std::endl;\n\tstd::cout << \"-h:  Show this help.\" << std::endl;\n}\n\n// This is the main function\nint main (int argc, char** argv)\n{\n// Show help\n\tif (pcl::console::find_switch (argc, argv, \"-h\") || pcl::console::find_switch (argc, argv, \"--help\")) \n\t{\n\t\tshowHelp (argv[0]);\n\t\treturn 0;\n\t}\n// Fetch point cloud filename in arguments | Works with PCD and PLY files\n\tstd::vector<int> filenames;\n\tbool file_is_pcd = false;\n\tfilenames = pcl::console::parse_file_extension_argument (argc, argv, \".ply\");\n\n\tif (filenames.size () != 1)  \n\t{\n\t\tfilenames = pcl::console::parse_file_extension_argument (argc, argv, \".pcd\");\n\t\tif (filenames.size () != 1) \n\t\t{\n\t\t\tshowHelp (argv[0]);\n\t\t\treturn -1;\n\t\t} \n\t\telse \n\t\t{\n\t\t\tfile_is_pcd = true;\n\t\t}\n\t}\n// Load file | Works with PCD and PLY files\n\tpcl::PointCloud<pcl::PointXYZ>::Ptr source_cloud (new pcl::PointCloud<pcl::PointXYZ> ());\n\tif (file_is_pcd) \n\t{\n\t\tif (pcl::io::loadPCDFile (argv[filenames[0]], *source_cloud) < 0)  \n\t\t{\n\t\t\tstd::cout << \"Error loading point cloud \" << argv[filenames[0]] << std::endl << std::endl;\n\t\t\tshowHelp (argv[0]);\n\t\t\treturn -1;\n\t\t}\n\t} \n\telse \n\t{\n\t\tif (pcl::io::loadPLYFile (argv[filenames[0]], *source_cloud) < 0)  \n\t\t{\n\t\t\tstd::cout << \"Error loading point cloud \" << argv[filenames[0]] << std::endl << std::endl;\n\t\t\tshowHelp (argv[0]);\n\t\t\treturn -1;\n\t\t}\n\t}\n\tcout<<\"Width of the cloud: \"<<source_cloud->width<<endl;\n\tcout<<\"Height of the cloud: \"<<source_cloud->height<<endl;\n\tint d=source_cloud->width;\n\tMatrixXf cloud_data(d,3);\n\tfor(int i=0;i<d;i++)\n\t{\n\t\tcloud_data(i,0) = source_cloud->points.at(i).x+2;  \n\t\tcloud_data(i,1) = source_cloud->points.at(i).y+2;  \n\t\tcloud_data(i,2) = source_cloud->points.at(i).z+2;  \n\t}\n\tcout<<cloud_data<<endl;\n//!! Create a point cloud containing part of the pointcloud data\n\tPointCloud<pcl::PointXYZ>::Ptr cloud_test (new PointCloud<pcl::PointXYZ>);\n\tcloud_test->width    = d;\n\tcloud_test->height   = 1;\n\tcloud_test->is_dense = false;\n\tcloud_test->points.resize (cloud_test->width * cloud_test->height);\n\tfor (size_t i = 0; i < cloud_test->points.size (); ++i)\n\t{\n\t\tcloud_test->points[i].x = source_cloud->points.at(i).x; \n\t\tcloud_test->points[i].y = source_cloud->points.at(i).y;  \n\t\tcloud_test->points[i].z = source_cloud->points.at(i).z;  \n\t}\n\tcout << \"Test \" << cloud_test->points.size () << \" data points:\"<< endl;\n\tfor (size_t i = 0; i < cloud_test->points.size (); ++i)\n\t{\n\t\tcout << \"    \" << cloud_test->points[i].x << \" \" <<cloud_test->points[i].y << \" \" << cloud_test->points[i].z << endl;\n\t}\n\t//cloud_data<< source_cloud->points;\n  /* Reminder: how transformation matrices work :\n\n           |-------> This column is the translation\n    | 1 0 0 x |  \\\n    | 0 1 0 y |   }-> The identity 3x3 matrix (no rotation) on the left\n    | 0 0 1 z |  /\n    | 0 0 0 1 |    -> We do not use this line (and it has to stay 0,0,0,1)\n\n    METHOD #1: Using a Matrix4f\n    This is the \"manual\" method, perfect to understand but error prone !\n  */\n\tEigen::Matrix4f transform_1 = Eigen::Matrix4f::Identity();\n// Define a rotation matrix (see https://en.wikipedia.org/wiki/Rotation_matrix)\n\tfloat theta = M_PI/4; // The angle of rotation in radians\n\ttransform_1 (0,0) = cos (theta);\n\ttransform_1 (0,1) = -sin(theta);\n\ttransform_1 (1,0) = sin (theta);\n\ttransform_1 (1,1) = cos (theta);\n  //    (row, column)\n\n  // Define a translation of 2.5 meters on the x axis.\n\ttransform_1 (0,3) = 2.5;\n  // Print the transformation\n\tprintf (\"Method #1: using a Matrix4f\\n\");\n\tstd::cout << transform_1 << std::endl;\n  /*  METHOD #2: Using a Affine3f\n    This method is easier and less error prone\n  */\n\tEigen::Affine3f transform_2 = Eigen::Affine3f::Identity();\n// Define a translation of 2.5 meters on the x axis.\n\ttransform_2.translation() << 2.5, 0.0, 0.0;\n// The same rotation matrix as before; theta radians arround Z axis\n\ttransform_2.rotate (Eigen::AngleAxisf (theta, Eigen::Vector3f::UnitZ()));\n// Print the transformation\n\tprintf (\"\\nMethod #2: using an Affine3f\\n\");\n\tstd::cout << transform_2.matrix() << std::endl;\n\n // Executing the transformation\n\tpcl::PointCloud<pcl::PointXYZ>::Ptr transformed_cloud (new pcl::PointCloud<pcl::PointXYZ> ());\n // You can either apply transform_1 or transform_2; they are the same\n\tpcl::transformPointCloud (*source_cloud, *transformed_cloud, transform_2);\n\n // Visualization\n\tprintf(  \"\\nPoint cloud colors :  white  = original point cloud\\n\"\n      \"                        red  = transformed point cloud\\n\");\n\tpcl::visualization::PCLVisualizer viewer (\"Matrix transformation example\");\n\n// Define R,G,B colors for the point cloud\n\tpcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source_cloud_color_handler (source_cloud, 255, 255, 255);\n// We add the point cloud to the viewer and pass the color handler\n\tviewer.addPointCloud (source_cloud, source_cloud_color_handler, \"original_cloud\");\n\n\tpcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> transformed_cloud_color_handler (transformed_cloud, 230, 20, 20); // Red\n\tviewer.addPointCloud (transformed_cloud, transformed_cloud_color_handler, \"transformed_cloud\");\n\t\n\tpcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> cloud_test_color_handler (cloud_test, 255, 20, 255);\n// We add the point cloud to the viewer and pass the color handler\n\tviewer.addPointCloud (cloud_test, cloud_test_color_handler, \"test_cloud\");\n\n\tviewer.addCoordinateSystem (0.1, 0);\n\tviewer.setBackgroundColor(0.05, 0.05, 0.05, 0); // Setting background to a dark grey\n\tviewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, \"original_cloud\");\n\tviewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, \"transformed_cloud\");\n\tviewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, \"test_cloud\");\n  //viewer.setPosition(800, 400); // Setting visualiser window position\n\n\twhile (!viewer.wasStopped ()) \n\t{ // Display the visualiser until 'q' key is pressed\n\t\tviewer.spinOnce ();\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "37124c50ed3252d6bea0c8c954fd4c4c1c12c4fd", "size": 6485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pcl_basic/src/matrix_transform.cpp", "max_stars_repo_name": "Kevin315/PCL_Research", "max_stars_repo_head_hexsha": "7e359b542fbe802c6430cbf9396bb39b550c8ff2", "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/pcl_basic/src/matrix_transform.cpp", "max_issues_repo_name": "Kevin315/PCL_Research", "max_issues_repo_head_hexsha": "7e359b542fbe802c6430cbf9396bb39b550c8ff2", "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/pcl_basic/src/matrix_transform.cpp", "max_forks_repo_name": "Kevin315/PCL_Research", "max_forks_repo_head_hexsha": "7e359b542fbe802c6430cbf9396bb39b550c8ff2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4855491329, "max_line_length": 137, "alphanum_fraction": 0.6868157286, "num_tokens": 1874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.5675511120368154}}
{"text": "#include <cmath>\n#include \"matplotlibcpp.h\"\nnamespace plt = matplotlibcpp;\n\n#ifdef WITH_EIGEN\n#include <Eigen/Dense>\n#endif\n\ntemplate <typename Vector>\nvoid get_data(Vector& x, Vector& y, Vector& err) {\n  // get number of data points\n  const unsigned n = x.size();\n  assert(y.size() == n && err.size() == n);\n\n  // compute data\n  for (unsigned i = 0; i < n; ++i) {\n    *(x.data() + i) = 1.0 * i / n;\n    *(y.data() + i) = sin(2.0 * M_PI * i / n);\n    *(err.data() + i) = exp(-0.1 * i);\n  }\n}\n\ntemplate <typename Vector>\nvoid plot(unsigned n) {\n  // get the data\n  Vector x(n), y(n), err(n);\n  get_data(x, y, err);\n\n  // plot errorbar plot\n  plt::errorbar(x, y, err);\n}\n\nint main() {\n  // create figure\n  plt::figure();\n\n  // plot with std::vector\n  plot<std::vector<double>>(10);\n\n  // plot with Eigen::VectorXd, if specified\n  #ifdef WITH_EIGEN\n  plot<Eigen::VectorXd>(13);\n  #endif\n\n  // show plot\n  plt::show();\n\n  return 0;\n}\n", "meta": {"hexsha": "227c32f2fa30d75a1524e678ff71a4f320fc4ddc", "size": 930, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/errorbar.cpp", "max_stars_repo_name": "LucaMac1/matplotlib-cpp", "max_stars_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/errorbar.cpp", "max_issues_repo_name": "LucaMac1/matplotlib-cpp", "max_issues_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/errorbar.cpp", "max_forks_repo_name": "LucaMac1/matplotlib-cpp", "max_forks_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6, "max_line_length": 50, "alphanum_fraction": 0.588172043, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.5675511115459049}}
{"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 <stan/math/prim/mat.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\nusing std::vector;\n\nTEST(ProbDistributionsMultiNormal,NotVectorized) {\n  Matrix<double,Dynamic,1> y(3,1);\n  y << 2.0, -2.0, 11.0;\n  Matrix<double,Dynamic,1> mu(3,1);\n  mu << 1.0, -1.0, 3.0;\n  Matrix<double,Dynamic,Dynamic> Sigma(3,3);\n  Sigma << 9.0, -3.0, 0.0,\n    -3.0,  4.0, 0.0,\n    0.0, 0.0, 5.0;\n  EXPECT_FLOAT_EQ(-11.73908, stan::math::multi_normal_log(y,mu,Sigma));\n}\n\nTEST(ProbDistributionsMultiNormal,Vectorized) {\n  vector< Matrix<double,Dynamic,1> > vec_y(2);\n  vector< Matrix<double,1,Dynamic> > vec_y_t(2);\n  Matrix<double,Dynamic,1> y(3);\n  Matrix<double,1,Dynamic> y_t(3);\n  y << 2.0, -2.0, 11.0;\n  vec_y[0] = y;\n  vec_y_t[0] = y;\n  y << 4.0, -2.0, 1.0;\n  vec_y[1] = y;\n  vec_y_t[1] = y;\n  y_t = y;\n  \n  vector< Matrix<double,Dynamic,1> > vec_mu(2);\n  vector< Matrix<double,1,Dynamic> > vec_mu_t(2);\n  Matrix<double,Dynamic,1> mu(3);\n  Matrix<double,1,Dynamic> mu_t(3);\n  mu << 1.0, -1.0, 3.0;\n  vec_mu[0] = mu;\n  vec_mu_t[0] = mu;\n  mu << 2.0, -1.0, 4.0;\n  vec_mu[1] = mu;\n  vec_mu_t[1] = mu;\n  mu_t = mu;\n  \n  Matrix<double,Dynamic,Dynamic> Sigma(3,3);\n  Sigma << 10.0, -3.0, 0.0,\n    -3.0,  5.0, 0.0,\n    0.0, 0.0, 5.0;\n    \n  //y and mu vectorized\n  EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::math::multi_normal_log(vec_y,vec_mu,Sigma));\n  EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::math::multi_normal_log(vec_y_t,vec_mu,Sigma));\n  EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::math::multi_normal_log(vec_y,vec_mu_t,Sigma));\n  EXPECT_FLOAT_EQ(-11.928077-6.5378327, stan::math::multi_normal_log(vec_y_t,vec_mu_t,Sigma));\n\n  //y vectorized\n  EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::math::multi_normal_log(vec_y,mu,Sigma));\n  EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::math::multi_normal_log(vec_y_t,mu,Sigma));\n  EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::math::multi_normal_log(vec_y,mu_t,Sigma));\n  EXPECT_FLOAT_EQ(-10.44027-6.537833, stan::math::multi_normal_log(vec_y_t,mu_t,Sigma));\n\n  //mu vectorized\n  EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::math::multi_normal_log(y,vec_mu,Sigma));\n  EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::math::multi_normal_log(y_t,vec_mu,Sigma));\n  EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::math::multi_normal_log(y,vec_mu_t,Sigma));\n  EXPECT_FLOAT_EQ(-6.26954-6.537833, stan::math::multi_normal_log(y_t,vec_mu_t,Sigma));\n}\nTEST(ProbDistributionsMultiNormal,Sigma) {\n  Matrix<double,Dynamic,1> y(2,1);\n  y << 2.0, -2.0;\n  Matrix<double,Dynamic,1> mu(2,1);\n  mu << 1.0, -1.0;\n  Matrix<double,Dynamic,Dynamic> Sigma(2,2);\n  Sigma << 9.0, -3.0, -3.0, 4.0;\n  EXPECT_NO_THROW (stan::math::multi_normal_log(y, mu, Sigma));\n\n  // non-symmetric\n  Sigma(0, 1) = -2.5;\n  EXPECT_THROW (stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n}\nTEST(ProbDistributionsMultiNormal,Mu) {\n  Matrix<double,Dynamic,1> y(3,1);\n  y << 2.0, -2.0, 11.0;\n  Matrix<double,Dynamic,1> mu(3,1);\n  mu << 1.0, -1.0, 3.0;\n  Matrix<double,Dynamic,Dynamic> Sigma(3,3);\n  Sigma << 9.0, -3.0, 0.0,\n    -3.0,  4.0, 0.0,\n    0.0, 0.0, 5.0;\n  EXPECT_NO_THROW (stan::math::multi_normal_log(y, mu, Sigma));\n\n  mu(0) = std::numeric_limits<double>::infinity();\n  EXPECT_THROW (stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n  mu(0) = -std::numeric_limits<double>::infinity();\n  EXPECT_THROW (stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n  mu(0) = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_THROW (stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n}\nTEST(ProbDistributionsMultiNormal,MultiNormalOneRow) {\n  Matrix<double,1,Dynamic> y(1,3);\n  y << 2.0, -2.0, 11.0;\n  Matrix<double,Dynamic,1> mu(3,1);\n  mu << 1.0, -1.0, 3.0;\n  Matrix<double,Dynamic,Dynamic> Sigma(3,3);\n  Sigma << 9.0, -3.0, 0.0,\n    -3.0,  4.0, 0.0,\n    0.0, 0.0, 5.0;\n  EXPECT_FLOAT_EQ(-11.73908, stan::math::multi_normal_log(y,mu,Sigma));\n}\n\nTEST(ProbDistributionsMultiNormal,SigmaMultiRow) {\n  Matrix<double,1,Dynamic> y(1,2);\n  y << 2.0, -2.0;\n  Matrix<double,Dynamic,1> mu(2,1);\n  mu << 1.0, -1.0;\n  Matrix<double,Dynamic,Dynamic> Sigma(2,2);\n  Sigma << 9.0, -3.0, -3.0, 4.0;\n  EXPECT_NO_THROW (stan::math::multi_normal_log(y, mu, Sigma));\n\n  // non-symmetric\n  Sigma(0, 1) = -2.5;\n  EXPECT_THROW (stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n  Matrix<double,Dynamic,1> z(2,1);\n  \n  // wrong dimensions\n  z << 2.0, -2.0;\n  EXPECT_THROW (stan::math::multi_normal_log(z, mu, Sigma), std::domain_error);\n}\nTEST(ProbDistributionsMultiNormal,MuMultiRow) {\n  Matrix<double,1,Dynamic> y(1,3);\n  y << 2.0, -2.0, 11.0;\n  Matrix<double,Dynamic,1> mu(3,1);\n  mu << 1.0, -1.0, 3.0;\n  Matrix<double,Dynamic,Dynamic> Sigma(3,3);\n  Sigma << 9.0, -3.0, 0.0,\n    -3.0,  4.0, 0.0,\n    0.0, 0.0, 5.0;\n  EXPECT_NO_THROW (stan::math::multi_normal_log(y, mu, Sigma));\n\n  mu(0) = std::numeric_limits<double>::infinity();\n  EXPECT_THROW (stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n  mu(0) = -std::numeric_limits<double>::infinity();\n  EXPECT_THROW (stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n  mu(0) = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_THROW (stan::math::multi_normal_log(y, mu, Sigma), std::domain_error);\n}\nTEST(ProbDistributionsMultiNormal,SizeMismatch) {\n  Matrix<double,1,Dynamic> y(1,3);\n  y << 2.0, -2.0, 11.0;\n  Matrix<double,Dynamic,1> mu(2,1);\n  mu << 1.0, -1.0;\n  Matrix<double,Dynamic,Dynamic> Sigma(2,3);\n  Sigma << 9.0, -3.0, 0.0,\n    -3.0,  4.0, 0.0;  \n  EXPECT_THROW(stan::math::multi_normal_log(y, mu, Sigma), std::invalid_argument);\n}\n\nTEST(ProbDistributionsMultiNormal, error_check) {\n  boost::random::mt19937 rng;\n  Matrix<double,Dynamic,1> mu(3,1);\n  mu << 2.0, \n    -2.0,\n    11.0;\n\n  Matrix<double,Dynamic,Dynamic> sigma(3,3);\n  sigma << 9.0, -3.0, 0.0,\n    -3.0,  4.0, 1.0,\n    0.0, 1.0, 3.0;\n  EXPECT_NO_THROW(stan::math::multi_normal_rng(mu, sigma,rng));\n\n  mu << stan::math::positive_infinity(), \n    -2.0,\n    11.0;\n  EXPECT_THROW(stan::math::multi_normal_rng(mu,sigma,rng),std::domain_error);\n\n  mu << 2.0, \n    -2.0,\n    11.0;\n  sigma << 9.0, -3.0, 0.0,\n    3.0,  4.0, 0.0,\n    -2.0, 1.0, 3.0;\n  EXPECT_THROW(stan::math::multi_normal_rng(mu,sigma,rng),std::domain_error);\n\n}\n\nTEST(ProbDistributionsMultiNormal, marginalOneChiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  Matrix<double,Dynamic,Dynamic> sigma(3,3);\n  sigma << 9.0, -3.0, 0.0,\n    -3.0,  4.0, 1.0,\n    0.0, 1.0, 3.0;\n  Matrix<double,Dynamic,1> mu(3,1);\n  mu << 2.0, \n    -2.0,\n    11.0;\n  int N = 10000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::normal_distribution<>dist (2.0,3.0);\n  boost::math::chi_squared mydist(K-1);\n\n  double loc[K - 1];\n  for(int i = 1; i < K; i++)\n    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));\n\n  int count = 0;\n  int bin [K];\n  double expect [K];\n  for(int i = 0 ; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N / K;\n  }\n  Eigen::VectorXd a(mu.rows());\n  while (count < N) {\n    a = stan::math::multi_normal_rng(mu,sigma,rng);\n    int i = 0;\n    while (i < K-1 && a(0) > loc[i]) \n      ++i;\n    ++bin[i];\n    count++;\n   }\n\n  double chi = 0;\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsMultiNormal, marginalTwoChiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  Matrix<double,Dynamic,Dynamic> sigma(3,3);\n  sigma << 9.0, -3.0, 0.0,\n    -3.0,  4.0, 1.0,\n    0.0, 1.0, 3.0;\n  Matrix<double,Dynamic,1> mu(3,1);\n  mu << 2.0, \n    -2.0,\n    11.0;\n  int N = 10000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::normal_distribution<>dist (-2.0,2.0);\n  boost::math::chi_squared mydist(K-1);\n\n  double loc[K - 1];\n  for(int i = 1; i < K; i++)\n    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));\n\n  int count = 0;\n  int bin [K];\n  double expect [K];\n  for(int i = 0 ; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N / K;\n  }\n  Eigen::VectorXd a(mu.rows());\n  while (count < N) {\n    a = stan::math::multi_normal_rng(mu,sigma,rng);\n    int i = 0;\n    while (i < K-1 && a(1) > loc[i]) \n      ++i;\n    ++bin[i];\n    count++;\n   }\n\n  double chi = 0;\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsMultiNormal, marginalThreeChiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  Matrix<double,Dynamic,Dynamic> sigma(3,3);\n  sigma << 9.0, -3.0, 0.0,\n    -3.0,  4.0, 1.0,\n    0.0, 1.0, 16.0;\n  Matrix<double,Dynamic,1> mu(3,1);\n  mu << 2.0, \n    -2.0,\n    11.0;\n  int N = 10000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::normal_distribution<>dist (11.0,4.0);\n  boost::math::chi_squared mydist(K-1);\n\n  double loc[K - 1];\n  for(int i = 1; i < K; i++)\n    loc[i - 1] = quantile(dist, i * std::pow(K, -1.0));\n\n  int count = 0;\n  int bin [K];\n  double expect [K];\n  for(int i = 0 ; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N / K;\n  }\n  Eigen::VectorXd a(mu.rows());\n  while (count < N) {\n    a = stan::math::multi_normal_rng(mu,sigma,rng);\n    int i = 0;\n    while (i < K-1 && a(2) > loc[i]) \n      ++i;\n    ++bin[i];\n    count++;\n   }\n\n  double chi = 0;\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(multiNormalRng, nonPosDefErrorTest) {\n  using stan::math::multi_normal_rng;\n  Eigen::MatrixXd S(2,2);\n  S << 0, 1, 1, 0;  // not pos definite\n  Eigen::VectorXd mu(2);\n  mu << 1, 2;\n  boost::random::mt19937 rng;\n  EXPECT_THROW(multi_normal_rng(mu, S, rng), std::domain_error);\n}\n", "meta": {"hexsha": "ca299b69863dff19abff953b0d8f0a7f9b399497", "size": 9771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/multi_normal_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/multi_normal_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/multi_normal_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.972392638, "max_line_length": 94, "alphanum_fraction": 0.6167229557, "num_tokens": 3850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5674624841428006}}
{"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": "#define BOOST_TEST_MODULE FourierTransformTest\n#include <boost/test/unit_test.hpp>\n\n// For IO\n#include <stdlib.h>\n#include <math.h>\n#include <cmath> \n#include <iostream>\n#include <unistd.h>\n\n// For measuring elapsed time\n#include <chrono>\n\n// For Random Float Generator\n#include <time.h>\n\n// For object under test\n#include \"nyquist-modulator.h\"\n#include \"fftw3.h\"\n\n#define DIFFERENCE_THRESHOLD 0.0001\n\n\n/**\n* Test NYQUIST MODULATOR\n* \n*/\nBOOST_AUTO_TEST_SUITE(NYQUIST_MODULATOR)\n\n\n/**\n* Generate random data (floats) Put it throguh IFFT.\n* Copy the time domain samples into FFT input buffer.\n* Execute and check the input and output are within a\n* threshold value.\n* \n*/\nBOOST_AUTO_TEST_CASE(ModToDemod)\n{\n    printf(\"\\nTesting Modulation to Demodulation...\\n\");\n    printf(\"\\nMdoulator:\\n\");\n\n    uint32_t nPoints = 512;\n    uint32_t symbolSize = nPoints*2;\n    //uint32_t prefixSize = 128;\n\n    // Setup random float generator\n    srand( (unsigned)time( NULL ) );\n\n    DoubleVec ifftOutput;\n    ifftOutput.resize(symbolSize);\n\n    DoubleVec modulatorOutput;\n    modulatorOutput.resize(symbolSize);\n\n    DoubleVec rxSignal;\n    rxSignal.resize(symbolSize*10);\n\n    uint32_t symbolStart = rand() % ((nPoints*2)*9);\n    printf(\"Random Symbol Start = %d\\n\",symbolStart);\n    \n    fftw_complex *demodulatorOutput;\n    demodulatorOutput = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * nPoints);\n \n    // Popilate ifft output double vec with random values\n    for (size_t i = 0; i < symbolSize; i++)\n    {\n        ifftOutput[i] = (double) rand()/RAND_MAX;\n    }\n\n    std::copy(ifftOutput.begin(), ifftOutput.begin()+symbolSize, modulatorOutput.begin());\n  \n    NyquistModulator modulator(nPoints, (fftw_complex *) &modulatorOutput);\n    NyquistModulator demodulator(nPoints, demodulatorOutput); \n\n    // Measure wall time of the modulator execution.\n    auto start = std::chrono::steady_clock::now();\n    // Modulate data, set prefix size to 0 as it is not used in this test\n    modulator.Modulate(modulatorOutput, 0);\n    auto end = std::chrono::steady_clock::now();\n \n    std::cout << \"Digital quadrature modulator elapsed time: \"\n        << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()\n        << \" ns\" << std::endl;\n\n    printf(\"\\nDemodulator:\\n\");\n\n    // basically it works like this:\n    //std::copy( src, src + size, dest );\n    std::copy( modulatorOutput.begin(), modulatorOutput.end(), rxSignal.begin()+symbolStart);\n\n    // Measure wall time of the fft execution.\n    start = std::chrono::steady_clock::now();\n    demodulator.Demodulate(rxSignal, symbolStart);\n    end = std::chrono::steady_clock::now();\n \n    std::cout << \"Digital quadrature demodulator elapsed time: \"\n        << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()\n        << \" ns\" << std::endl;\n\n\n    // Print input and output buffers\n    for (size_t i = 0; i < nPoints; i++)\n    {\n                \n        //printf(\"Real Sample: %lu %+9.5f Input to Modulator vs. %+9.5f Output of Demodulator\\n\",\n        //i, ifftOutput[(i*2)], demodulatorOutput[i][0]);\n\n        // Check if real and complex element match within defined precision.\n        BOOST_CHECK_MESSAGE( \n        (std::abs( ifftOutput[(i*2)] -  demodulatorOutput[i][0] ) <= DIFFERENCE_THRESHOLD ), \n        \"Values vary more than threshold! - Occured at index: \" << i );  \n        \n\n        //printf(\"Imag Sample: %lu %+9.5f Input to Modulator vs. %+9.5f Output of Demodulator\\n\",\n        //i, ifftOutput[(i*2)+1], demodulatorOutput[i][1]);\n\n        // Check if real and complex element match within defined precision.\n        BOOST_CHECK_MESSAGE( \n        (std::abs( ifftOutput[(i*2)+1] - demodulatorOutput[i][1] ) <= DIFFERENCE_THRESHOLD ), \n        \"Values vary more than threshold! - Occured at index: \" << i );  \n    \n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f40cf646d576cb233ef0e017acfd807747749f37", "size": 3851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/NyquistModulatorTest.cpp", "max_stars_repo_name": "krogk/ofdmlib", "max_stars_repo_head_hexsha": "7eddfdfde17624bf7674dda33ddc43b308c07765", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T10:44:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T14:20:05.000Z", "max_issues_repo_path": "test/unit/NyquistModulatorTest.cpp", "max_issues_repo_name": "krogk/ofdmlib", "max_issues_repo_head_hexsha": "7eddfdfde17624bf7674dda33ddc43b308c07765", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-11T12:50:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-11T12:51:02.000Z", "max_forks_repo_path": "test/unit/NyquistModulatorTest.cpp", "max_forks_repo_name": "krogk/ofdmlib", "max_forks_repo_head_hexsha": "7eddfdfde17624bf7674dda33ddc43b308c07765", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-03T14:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T14:56:19.000Z", "avg_line_length": 30.3228346457, "max_line_length": 97, "alphanum_fraction": 0.6600882888, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.567442627198944}}
{"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": "// Copyright (c) 2021 Fetullah Atas, Norwegian University of Life Sciences\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// Equations and logic parts of this code was based on ;\n// https://github.com/MPC-Berkeley/genesis_path_follower\n// Also refer to;\n// https://github.com/MPC-Berkeley/barc/wiki/Car-Model\n\n#ifndef VOX_NAV_CONTROL__MPC_CONTROLLER__MPC_CONTROLLER_CORE_HPP_\n#define VOX_NAV_CONTROL__MPC_CONTROLLER__MPC_CONTROLLER_CORE_HPP_\n\n#include <casadi/casadi.hpp>\n\n#include <vector>\n#include <memory>\n#include <chrono>\n#include <Eigen/Eigen>\n#include <vox_nav_control/common.hpp>\n\nnamespace vox_nav_control\n{\n  namespace mpc_controller_casadi\n  {\n\n/**\n * @brief CASADI based MOdel Predcitive Control for Ackermann Vehicle\n *\n */\n    class MPCControllerCasadiCore\n    {\n    public:\n      /**\n       * @brief structure for slack variables, these are used to relax input rate constraints\n       *\n       */\n      struct SlackVars\n      {\n        double sl_acc;\n        double sl_df;\n        SlackVars()\n        : sl_acc(0.0),\n          sl_df(0.0) {}\n      };\n\n      /**\n       * @brief result is passed as this struct\n       *\n       */\n      struct SolutionResult\n      {\n        // whether the found solution was optimal\n        bool is_optimal;\n        // Execution ime took by solver in milliseconds\n        int solve_time_ms;\n        // computed control input as result of optimal control\n        vox_nav_control::common::ControlInput control_input;\n        // actual states that are going to be achieved in the time horizon\n        std::vector<vox_nav_control::common::States> actual_computed_states;\n        SolutionResult()\n        : is_optimal(false),\n          solve_time_ms(0)\n        {}\n      };\n\n      /**\n       * @brief Construct a new MPCControllerCasadiCore object\n       *\n       * @param params\n       */\n      MPCControllerCasadiCore(vox_nav_control::common::Parameters params);\n\n      /**\n       * @brief Destroy the MPCControllerCasadiCore object\n       *\n       */\n      ~MPCControllerCasadiCore();\n\n      /**\n       * @brief state dynamcs constraints, control input\n       * constraints and boundries are defined through this function\n       *\n       */\n      void addConstraints();\n\n      /**\n       * @brief objective function and cost is defined with this function\n       *\n       */\n      void addCost();\n\n      /**\n       * @brief update the current states\n       *\n       * @param curr_states\n       */\n      void updateCurrentStates(vox_nav_control::common::States curr_states);\n\n      /**\n       * @brief update current refernce states in horizon\n       *\n       * @param reference_states\n       */\n      void updateReferences(std::vector<vox_nav_control::common::States> reference_states);\n\n      /**\n       * @brief update previous control input\n       *\n       * @param previous_control_input\n       */\n      void updatePreviousControlInput(vox_nav_control::common::ControlInput previous_control_input);\n\n      /**\n       * @brief initialize slack variables, mostly just equalizing them to zero\n       *\n       * @param initial_slack_vars\n       */\n      void initializeSlackVars(std::vector<SlackVars> initial_slack_vars);\n\n      /**\n       * @brief  initialize actual states, mostly just equalizing them to zero.\n       * These cannot be updated\n       * they are variables of optimal control problem itself\n       *\n       * @param initial_actual_states\n       */\n      void initializeActualStates(\n        std::vector<vox_nav_control::common::States> initial_actual_states);\n\n      /**\n     * @brief  initialize control inputs, mostly just equalizing them to zero. These cannot be updated\n     *  they are variables of optimal control problem itself\n     *\n     * @param initial_actual_control_inputs\n     */\n      void initializeActualControlInputs(\n        std::vector<vox_nav_control::common::ControlInput> initial_actual_control_inputs);\n\n      /**\n       * @brief solve the actual optiml control problem\n       *\n       * @return SolutionResult, includes resulting control inputs\n       * as well as optimal control variables; computed actual states\n       */\n      SolutionResult solve(const std::vector<vox_nav_control::common::Ellipsoid> & obstacles);\n\n    private:\n      std::shared_ptr<casadi::Opti> opti_;\n      // used to slice casadi matrixes\n      casadi::Slice slice_all_;\n      casadi::Matrix<double> Q;\n      casadi::Matrix<double> R;\n\n      casadi::MX u_prev_; // previous input: [u_{acc, -1}, u_{df, -1}]\n      casadi::MX z_curr_; // current state:  [x_0, y_0, psi_0, v_0]\n\n      // reference traj that we would like to follow\n      // First index corresponds to our desired state at timestep k+1:\n      // i.e. z_ref_[0,:] = z_{desired, 1}.\n      // second index selects the state element from [x_k, y_k, psi_k, v_k].\n      casadi::MX z_ref_;\n      casadi::MX x_ref_;\n      casadi::MX y_ref_;\n      casadi::MX psi_ref_;\n      casadi::MX v_ref_;\n\n      // Actual trajectory we will follow given the optimal solution.\n      // First index is the timestep k, i.e. self.z_dv[0,:] is z_0.\n      // It has N+1 timesteps since we go from z_0, ..., z_N.\n      // Second index is the state element, as detailed below.\n      casadi::MX z_dv_;\n      casadi::MX x_dv_;\n      casadi::MX y_dv_;\n      casadi::MX psi_dv_;\n      casadi::MX v_dv_;\n\n      // Control inputs used to achieve z_dv according to dynamics.\n      // First index is the timestep k, i.e. self.u_dv[0,:] is u_0.\n      // Second index is the input element as detailed below.\n      casadi::MX u_dv_;\n      casadi::MX acc_dv_;\n      casadi::MX df_dv_;\n\n      // Slack variables used to relax input rate constraints.\n      casadi::MX sl_dv_;\n      casadi::MX sl_acc_dv_;\n      casadi::MX sl_df_dv_;\n\n      // this will be updated through the constructor.\n      vox_nav_control::common::Parameters params_;\n\n      casadi::MX z_static_obs_;\n      casadi::MX x_static_obs_;\n      casadi::MX y_static_obs_;\n      casadi::MX a_static_obs_;\n      casadi::MX b_static_obs_;\n\n      casadi::MX z_dynamic_obs_;\n      casadi::MX x_dynamic_obs_;\n      casadi::MX y_dynamic_obs_;\n      casadi::MX a_dynamic_obs_;\n      casadi::MX b_dynamic_obs_;\n      casadi::MX yaw_dynamic_obs_;\n\n    };\n  } // namespace mpc_controller_casadi\n}  // namespace vox_nav_control\n\n#endif  // VOX_NAV_CONTROL__MPC_CONTROLLER__MPC_CONTROLLER_CORE_HPP_\n", "meta": {"hexsha": "a79b75805d97d65b9e06a21678c364db2ed6b6b7", "size": 6845, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vox_nav_control/include/vox_nav_control/mpc_controller_casadi/mpc_controller_casadi_core.hpp", "max_stars_repo_name": "NMBURobotics/vox_nav", "max_stars_repo_head_hexsha": "7d71c97166ce57680bf2e637cca7c745d55b045a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2021-06-03T08:46:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:07:09.000Z", "max_issues_repo_path": "vox_nav_control/include/vox_nav_control/mpc_controller_casadi/mpc_controller_casadi_core.hpp", "max_issues_repo_name": "NMBURobotics/vox_nav", "max_issues_repo_head_hexsha": "7d71c97166ce57680bf2e637cca7c745d55b045a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-06-06T01:17:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T10:01:53.000Z", "max_forks_repo_path": "vox_nav_control/include/vox_nav_control/mpc_controller_casadi/mpc_controller_casadi_core.hpp", "max_forks_repo_name": "NMBURobotics/vox_nav", "max_forks_repo_head_hexsha": "7d71c97166ce57680bf2e637cca7c745d55b045a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2021-06-03T08:46:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T00:57:51.000Z", "avg_line_length": 31.1136363636, "max_line_length": 102, "alphanum_fraction": 0.6530314098, "num_tokens": 1628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5674315913531846}}
{"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// QuickBook Example\n\n// Copyright (c) 2015, Oracle and/or its affiliates\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n//[is_valid_failure\n//` Checks whether a geometry is valid and, if not valid, checks if it could be fixed by bg::correct; if so bg::correct is called on the geometry\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n/*<-*/ #include \"create_svg_one.hpp\" /*->*/\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<double> point_type;\n    typedef boost::geometry::model::polygon<point_type> polygon_type;\n\n    polygon_type poly;\n    boost::geometry::read_wkt(\"POLYGON((0 0,0 10,10 10,10 0),(0 0,9 2,9 1,0 0),(0 0,2 9,1 9,0 0))\", poly);\n\n    std::cout << \"original geometry: \" << boost::geometry::dsv(poly) << std::endl;\n    boost::geometry::validity_failure_type failure;\n    bool valid = boost::geometry::is_valid(poly, failure);\n\n    // if the invalidity is only due to lack of closing points and/or wrongly oriented rings, then bg::correct can fix it\n    bool could_be_fixed = (failure == boost::geometry::failure_not_closed\n                           || boost::geometry::failure_wrong_orientation);\n    std::cout << \"is valid? \" << (valid ? \"yes\" : \"no\") << std::endl;\n    if (! valid)\n    {\n        std::cout << \"can boost::geometry::correct remedy invalidity? \" << (could_be_fixed ? \"possibly yes\" : \"no\") << std::endl;\n        if (could_be_fixed)\n        {\n            boost::geometry::correct(poly);\n            std::cout << \"after correction: \" << (boost::geometry::is_valid(poly) ? \"valid\" : \"still invalid\") << std::endl;\n            std::cout << \"corrected geometry: \" << boost::geometry::dsv(poly) << std::endl;\n        }\n    }\n    /*<-*/ create_svg(\"is_valid_failure_example.svg\", poly); /*->*/\n    return 0;\n}\n\n//]\n\n//[is_valid_failure_output\n/*`\nOutput:\n[pre\noriginal geometry: (((0, 0), (0, 10), (10, 10), (10, 0)), ((0, 0), (9, 2), (9, 1), (0, 0)), ((0, 0), (2, 9), (1, 9), (0, 0)))\nis valid? no\ncan boost::geometry::correct remedy invalidity? possibly yes\nafter correction: valid\ncorrected geometry: (((0, 0), (0, 10), (10, 10), (10, 0), (0, 0)), ((0, 0), (9, 1), (9, 2), (0, 0)), ((0, 0), (2, 9), (1, 9), (0, 0)))\n\n[$img/algorithms/is_valid_failure_example.png]\n\n]\n\n*/\n//]\n", "meta": {"hexsha": "f566e23a226d62b7efda2fc3c7c6a3640f8a6619", "size": 2508, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/is_valid_failure.cpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "doc/src/examples/algorithms/is_valid_failure.cpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T01:39:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:18:40.000Z", "max_forks_repo_path": "doc/src/examples/algorithms/is_valid_failure.cpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 36.347826087, "max_line_length": 145, "alphanum_fraction": 0.6271929825, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.5674070286757896}}
{"text": "\n// BLAS level 2\n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <iostream>\n#include <boost/numeric/bindings/atlas/cblas1.hpp>\n#include <boost/numeric/bindings/atlas/cblas2.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include \"utils.h\" \n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::cout;\nusing std::endl; \n\ntypedef ublas::vector<double> vct_t;\ntypedef ublas::matrix<double, ublas::row_major> rm_t;\ntypedef ublas::matrix<double, ublas::column_major> cm_t;\n\nint main() {\n\n  cout << endl; \n\n  vct_t vx (2);\n  vct_t vy (4); \n\n  // row major matrix\n  rm_t rm (4, 2);\n  init_m (rm, kpp (1)); \n  print_m (rm, \"row major matrix m\"); \n  cout << endl; \n\n  atlas::set (1., vx);\n  print_v (vx, \"vx\"); \n  cout << endl; \n\n  // vy = m vx\n  atlas::gemv (CblasNoTrans, 1.0, rm, vx, 0.0, vy);\n  print_v (vy, \"vy = m vx\"); \n  cout << endl; \n\n  atlas::set (1., vy); \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // vx = m^T vy\n  atlas::gemv (CblasTrans, 1.0, rm, vy, 0.0, vx);\n  print_v (vx, \"vx = m^T vy\"); \n  cout << endl; \n\n  cout << endl; \n\n  // column major matrix\n  cm_t cm (4, 2);\n  init_m (cm, kpp (1)); \n  print_m (cm, \"column major matrix m\"); \n  cout << endl; \n\n  atlas::set (1., vx);\n  print_v (vx, \"vx\"); \n  cout << endl; \n\n  // vy = m vx\n  atlas::gemv (CblasNoTrans, 1.0, cm, vx, 0.0, vy);\n  print_v (vy, \"vy = m vx\"); \n  cout << endl; \n\n  atlas::set (1., vy); \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // vx = m^T vy\n  atlas::gemv (CblasTrans, 1.0, cm, vy, 0.0, vx);\n  print_v (vx, \"vx = m^T vy\"); \n  cout << endl; \n\n}\n", "meta": {"hexsha": "8ca8c513b3724ca9a4b824ef57ec02a91631f9a9", "size": 1711, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_matr2.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_matr2.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_matr2.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 20.8658536585, "max_line_length": 57, "alphanum_fraction": 0.6084161309, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.56739671685453}}
{"text": "// Copyright John Maddock 2014\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#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp> // Boost.Test\n#include <boost/test/results_collector.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/fusion/include/tuple.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\n#include <tuple>\n#endif\n\n#include <iostream>\n#include <iomanip>\n   using std::cout;\n   using std::endl;\n   using std::setprecision;\n\n#include <boost/math/tools/roots.hpp>\n\n//\n// We'll use cbrt as an example:\n//\nstruct cbtr_functor_1\n{\n   cbtr_functor_1(double x) : m_target(x) {}\n   double operator()(double x)\n   {\n      return x * x * x - m_target;\n   }\nprivate:\n   double m_target;\n};\n\nstruct cbtr_functor_2a\n{\n   cbtr_functor_2a(double x) : m_target(x) {}\n   std::pair<double, double> operator()(double x)\n   {\n      return std::make_pair(x * x * x - m_target, 3 * x * x);\n   }\nprivate:\n   double m_target;\n};\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\nstruct cbtr_functor_2b\n{\n   cbtr_functor_2b(double x) : m_target(x) {}\n   std::tuple<double, double> operator()(double x)\n   {\n      return std::tuple<double, double>(x * x * x - m_target, 3 * x * x);\n   }\nprivate:\n   double m_target;\n};\n#endif\nstruct cbtr_functor_2c\n{\n   cbtr_functor_2c(double x) : m_target(x) {}\n   boost::tuple<double, double> operator()(double x)\n   {\n      return boost::tuple<double, double>(x * x * x - m_target, 3 * x * x);\n   }\nprivate:\n   double m_target;\n};\nstruct cbtr_functor_2d\n{\n   cbtr_functor_2d(double x) : m_target(x) {}\n   boost::fusion::tuple<double, double> operator()(double x)\n   {\n      return boost::fusion::tuple<double, double>(x * x * x - m_target, 3 * x * x);\n   }\nprivate:\n   double m_target;\n};\n\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\nstruct cbtr_functor_3b\n{\n   cbtr_functor_3b(double x) : m_target(x) {}\n   std::tuple<double, double, double> operator()(double x)\n   {\n      return std::tuple<double, double, double>(x * x * x - m_target, 3 * x * x, 6 * x);\n   }\nprivate:\n   double m_target;\n};\n#endif\nstruct cbtr_functor_3c\n{\n   cbtr_functor_3c(double x) : m_target(x) {}\n   boost::tuple<double, double, double> operator()(double x)\n   {\n      return boost::tuple<double, double, double>(x * x * x - m_target, 3 * x * x, 6 * x);\n   }\nprivate:\n   double m_target;\n};\nstruct cbtr_functor_3d\n{\n   cbtr_functor_3d(double x) : m_target(x) {}\n   boost::fusion::tuple<double, double, double> operator()(double x)\n   {\n      return boost::fusion::tuple<double, double, double>(x * x * x - m_target, 3 * x * x, 6 * x);\n   }\nprivate:\n   double m_target;\n};\n\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n   double x = 27;\n   double expected = 3;\n   double result;\n   double tolerance = std::numeric_limits<double>::epsilon() * 5;\n   std::pair<double, double> p;\n   //\n   // Start by trying the unary functors, bisect first:\n   //\n   cbtr_functor_1 f1(x);\n   boost::math::tools::eps_tolerance<double> t(std::numeric_limits<double>::digits - 1);\n   p = boost::math::tools::bisect(f1, 0.0, x, t);\n   result = (p.first + p.second) / 2;\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n   //\n   // bracket_and_solve_root:\n   //\n   boost::uintmax_t max_iter = boost::math::policies::get_max_root_iterations<boost::math::policies::policy<> >();\n   p = boost::math::tools::bracket_and_solve_root(f1, x, 2.0, true, t, max_iter);\n   result = (p.first + p.second) / 2;\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n   //\n   // toms748_solve:\n   //\n   max_iter = boost::math::policies::get_max_root_iterations<boost::math::policies::policy<> >();\n   p = boost::math::tools::toms748_solve(f1, 0.0, x, t, max_iter);\n   result = (p.first + p.second) / 2;\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n\n#ifndef BOOST_NO_CXX11_LAMBDAS\n   //\n   // Now try again with C++11 lambda's\n   //\n   p = boost::math::tools::bisect([x](double z){ return z * z * z - x; }, 0.0, x, t);\n   result = (p.first + p.second) / 2;\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n   //\n   // bracket_and_solve_root:\n   //\n   max_iter = boost::math::policies::get_max_root_iterations<boost::math::policies::policy<> >();\n   p = boost::math::tools::bracket_and_solve_root([x](double z){ return z * z * z - x; }, x, 2.0, true, t, max_iter);\n   result = (p.first + p.second) / 2;\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n   //\n   // toms748_solve:\n   //\n   max_iter = boost::math::policies::get_max_root_iterations<boost::math::policies::policy<> >();\n   p = boost::math::tools::toms748_solve([x](double z){ return z * z * z - x; }, 0.0, x, t, max_iter);\n   result = (p.first + p.second) / 2;\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#endif\n\n   cbtr_functor_2a f2(x);\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\n   cbtr_functor_2b f3(x);\n#endif\n   cbtr_functor_2c f4(x);\n   cbtr_functor_2d f5(x);\n\n   //\n   // Binary Functors - newton_raphson_iterate - test each possible tuple type:\n   //\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\n   result = boost::math::tools::newton_raphson_iterate(f2, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n   result = boost::math::tools::newton_raphson_iterate(f3, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#endif\n   result = boost::math::tools::newton_raphson_iterate(f4, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n   result = boost::math::tools::newton_raphson_iterate(f5, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n   //\n   // And again but with lambdas:\n   //\n#ifndef BOOST_NO_CXX11_LAMBDAS\n   result = boost::math::tools::newton_raphson_iterate([x](double z){ return std::make_pair(z * z * z - x, 3 * z * z); }, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\n   result = boost::math::tools::newton_raphson_iterate([x](double z){ return std::make_tuple(z * z * z - x, 3 * z * z); }, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#endif\n   result = boost::math::tools::newton_raphson_iterate([x](double z){ return boost::tuple<double, double>(z * z * z - x, 3 * z * z); }, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n   result = boost::math::tools::newton_raphson_iterate([x](double z){ return boost::fusion::tuple<double, double>(z * z * z - x, 3 * z * z); }, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#endif\n\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\n   cbtr_functor_3b f6(x);\n#endif\n   cbtr_functor_3c f7(x);\n   cbtr_functor_3d f8(x);\n\n   //\n   // Ternary functors:\n   //\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\n   result = boost::math::tools::halley_iterate(f6, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#endif\n   result = boost::math::tools::halley_iterate(f7, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n   result = boost::math::tools::halley_iterate(f8, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#ifndef BOOST_NO_CXX11_LAMBDAS\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\n   result = boost::math::tools::halley_iterate([x](double z){ return std::make_tuple(z * z * z - x, 3 * z * z, 6 * z); }, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#endif\n   result = boost::math::tools::halley_iterate([x](double z){ return boost::tuple<double, double, double>(z * z * z - x, 3 * z * z, 6 * z); }, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n   result = boost::math::tools::halley_iterate([x](double z){ return boost::fusion::tuple<double, double, double>(z * z * z - x, 3 * z * z, 6 * z); }, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#endif\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\n   result = boost::math::tools::schroder_iterate(f6, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#endif\n   result = boost::math::tools::schroder_iterate(f7, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n   result = boost::math::tools::schroder_iterate(f8, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#ifndef BOOST_NO_CXX11_LAMBDAS\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\n   result = boost::math::tools::schroder_iterate([x](double z){ return std::make_tuple(z * z * z - x, 3 * z * z, 6 * z); }, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#endif\n   result = boost::math::tools::schroder_iterate([x](double z){ return boost::tuple<double, double, double>(z * z * z - x, 3 * z * z, 6 * z); }, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n   result = boost::math::tools::schroder_iterate([x](double z){ return boost::fusion::tuple<double, double, double>(z * z * z - x, 3 * z * z, 6 * z); }, x, 0.0, x, std::numeric_limits<double>::digits - 1);\n   BOOST_CHECK_CLOSE_FRACTION(expected, result, tolerance);\n#endif\n} // BOOST_AUTO_TEST_CASE( test_main )\n\n", "meta": {"hexsha": "60543f92a5f56ce9dfca62715ed4fbe8a4ba0f62", "size": 9956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/test_root_finding_concepts.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/test/test_root_finding_concepts.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T08:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-06T20:49:05.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/test/test_root_finding_concepts.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 39.0431372549, "max_line_length": 205, "alphanum_fraction": 0.6825030133, "num_tokens": 3090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5673967081686059}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2010,2012 Jitse Niesen <jitse@maths.leeds.ac.uk>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"main.h\"\n#include <limits>\n#include <Eigen/Eigenvalues>\n\ntemplate<typename MatrixType> void verifyIsQuasiTriangular(const MatrixType& T)\n{\n  typedef typename MatrixType::Index Index;\n\n  const Index size = T.cols();\n  typedef typename MatrixType::Scalar Scalar;\n\n  // Check T is lower Hessenberg\n  for(int row = 2; row < size; ++row) {\n    for(int col = 0; col < row - 1; ++col) {\n      VERIFY(T(row,col) == Scalar(0));\n    }\n  }\n\n  // Check that any non-zero on the subdiagonal is followed by a zero and is\n  // part of a 2x2 diagonal block with imaginary eigenvalues.\n  for(int row = 1; row < size; ++row) {\n    if (T(row,row-1) != Scalar(0)) {\n      VERIFY(row == size-1 || T(row+1,row) == 0);\n      Scalar tr = T(row-1,row-1) + T(row,row);\n      Scalar det = T(row-1,row-1) * T(row,row) - T(row-1,row) * T(row,row-1);\n      VERIFY(4 * det > tr * tr);\n    }\n  }\n}\n\ntemplate<typename MatrixType> void schur(int size = MatrixType::ColsAtCompileTime)\n{\n  // Test basic functionality: T is quasi-triangular and A = U T U*\n  for(int counter = 0; counter < g_repeat; ++counter) {\n    MatrixType A = MatrixType::Random(size, size);\n    RealSchur<MatrixType> schurOfA(A);\n    VERIFY_IS_EQUAL(schurOfA.info(), MySuccess);\n    MatrixType U = schurOfA.matrixU();\n    MatrixType T = schurOfA.matrixT();\n    verifyIsQuasiTriangular(T);\n    VERIFY_IS_APPROX(A, U * T * U.transpose());\n  }\n\n  // Test asserts when not initialized\n  RealSchur<MatrixType> rsUninitialized;\n  VERIFY_RAISES_ASSERT(rsUninitialized.matrixT());\n  VERIFY_RAISES_ASSERT(rsUninitialized.matrixU());\n  VERIFY_RAISES_ASSERT(rsUninitialized.info());\n  \n  // Test whether compute() and constructor returns same result\n  MatrixType A = MatrixType::Random(size, size);\n  RealSchur<MatrixType> rs1;\n  rs1.compute(A);\n  RealSchur<MatrixType> rs2(A);\n  VERIFY_IS_EQUAL(rs1.info(), MySuccess);\n  VERIFY_IS_EQUAL(rs2.info(), MySuccess);\n  VERIFY_IS_EQUAL(rs1.matrixT(), rs2.matrixT());\n  VERIFY_IS_EQUAL(rs1.matrixU(), rs2.matrixU());\n\n  // Test maximum number of iterations\n  RealSchur<MatrixType> rs3;\n  rs3.setMaxIterations(RealSchur<MatrixType>::m_maxIterationsPerRow * size).compute(A);\n  VERIFY_IS_EQUAL(rs3.info(), MySuccess);\n  VERIFY_IS_EQUAL(rs3.matrixT(), rs1.matrixT());\n  VERIFY_IS_EQUAL(rs3.matrixU(), rs1.matrixU());\n  if (size > 2) {\n    rs3.setMaxIterations(1).compute(A);\n    VERIFY_IS_EQUAL(rs3.info(), NoConvergence);\n    VERIFY_IS_EQUAL(rs3.getMaxIterations(), 1);\n  }\n\n  MatrixType Atriangular = A;\n  Atriangular.template triangularView<StrictlyLower>().setZero(); \n  rs3.setMaxIterations(1).compute(Atriangular); // triangular matrices do not need any iterations\n  VERIFY_IS_EQUAL(rs3.info(), MySuccess);\n  VERIFY_IS_APPROX(rs3.matrixT(), Atriangular); // approx because of scaling...\n  VERIFY_IS_EQUAL(rs3.matrixU(), MatrixType::Identity(size, size));\n\n  // Test computation of only T, not U\n  RealSchur<MatrixType> rsOnlyT(A, false);\n  VERIFY_IS_EQUAL(rsOnlyT.info(), MySuccess);\n  VERIFY_IS_EQUAL(rs1.matrixT(), rsOnlyT.matrixT());\n  VERIFY_RAISES_ASSERT(rsOnlyT.matrixU());\n\n  if (size > 2 && size < 20)\n  {\n    // Test matrix with NaN\n    A(0,0) = std::numeric_limits<typename MatrixType::Scalar>::quiet_NaN();\n    RealSchur<MatrixType> rsNaN(A);\n    VERIFY_IS_EQUAL(rsNaN.info(), NoConvergence);\n  }\n}\n\nvoid test_schur_real()\n{\n  CALL_SUBTEST_1(( schur<Matrix4f>() ));\n  CALL_SUBTEST_2(( schur<MatrixXd>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4)) ));\n  CALL_SUBTEST_3(( schur<Matrix<float, 1, 1> >() ));\n  CALL_SUBTEST_4(( schur<Matrix<double, 3, 3, Eigen::RowMajor> >() ));\n\n  // Test problem size constructors\n  CALL_SUBTEST_5(RealSchur<MatrixXf>(10));\n}\n", "meta": {"hexsha": "c8c6f94157dbafcdd8dae31c821de01b303c0acb", "size": 4013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "A4-paper-sheet-detection-and-cropping/Header_files/eigen/test/schur_real.cpp", "max_stars_repo_name": "satvik007/Scanner_OP", "max_stars_repo_head_hexsha": "c146f67e3851cd537d62989842abfee7d34de2c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A4-paper-sheet-detection-and-cropping/Header_files/eigen/test/schur_real.cpp", "max_issues_repo_name": "satvik007/Scanner_OP", "max_issues_repo_head_hexsha": "c146f67e3851cd537d62989842abfee7d34de2c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A4-paper-sheet-detection-and-cropping/Header_files/eigen/test/schur_real.cpp", "max_forks_repo_name": "satvik007/Scanner_OP", "max_forks_repo_head_hexsha": "c146f67e3851cd537d62989842abfee7d34de2c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-10T10:14:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T10:14:27.000Z", "avg_line_length": 35.5132743363, "max_line_length": 97, "alphanum_fraction": 0.6947420882, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5673967045127118}}
{"text": "#include \"MoonMotionSimulator.h\"\n\n#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>\n\n__BEGIN_LIBRARIES_DISABLE_WARNINGS\n#include <boost/math/common_factor_rt.hpp>\n\n#include <numeric>\n__END_LIBRARIES_DISABLE_WARNINGS\n\nnamespace AdventOfCode\n{\nnamespace Year2019\n{\nnamespace Day12\n{\n\n\nMoon::Moon(Vector3D pos)\n    : pos{std::move(pos)}\n    , vel{0, 0, 0}\n{\n\n}\n\nbool Moon::isAxisMatching(const Moon& other, size_t axisIndex) const\n{\n    return pos[axisIndex] == other.pos[axisIndex] && vel[axisIndex] == other.vel[axisIndex];\n}\n\nMoonMotionSimulator::MoonMotionSimulator(std::vector<Moon> moons)\n    : m_initialMoons{std::move(moons)}\n{\n    reset();\n}\n\nvoid MoonMotionSimulator::simulate(unsigned numSteps)\n{\n    for (size_t i = 0; i < numSteps; ++i)\n    {\n        step();\n    }\n}\n\nvoid MoonMotionSimulator::simulateUntilRepetition()\n{\n    std::vector<unsigned long long> individualAxisResults;\n\n    for (int axisIndex = 0; axisIndex <= 2; ++axisIndex)\n    {\n        reset();\n\n        simulateAxisUntilRepetition(axisIndex);\n\n        individualAxisResults.push_back(getNumSteps());\n    }\n\n    m_numSteps = std::accumulate(individualAxisResults.cbegin(), individualAxisResults.cend(), 1ull, [](auto total, auto current)\n                                    {\n                                        return boost::math::lcm(total, current);\n                                    });\n}\n\nint MoonMotionSimulator::getTotalEnergy() const\n{\n    return std::accumulate(m_moons.cbegin(), m_moons.cend(), 0, [](int total, const Moon& moon)\n                            {\n                                return total + (moon.pos.cwiseAbs().sum() * moon.vel.cwiseAbs().sum());\n                            });\n}\n\nunsigned long long MoonMotionSimulator::getNumSteps() const\n{\n    return m_numSteps;\n}\n\nvoid MoonMotionSimulator::step()\n{\n    ++m_numSteps;\n    applyAllGravity();\n    applyAllVelocity();\n}\n\nvoid MoonMotionSimulator::applyAllGravity()\n{\n    for (auto firstMoonIter = m_moons.begin(); firstMoonIter != m_moons.end(); ++firstMoonIter)\n    {\n        for (auto secondMoonIter = std::next(firstMoonIter); secondMoonIter != m_moons.end(); ++secondMoonIter)\n        {\n            applyGravity(*firstMoonIter, *secondMoonIter);\n        }\n    }\n}\n\nvoid MoonMotionSimulator::applyAllVelocity()\n{\n    for (auto& moon : m_moons)\n    {\n        moon.pos += moon.vel;\n    }\n}\n\nvoid MoonMotionSimulator::simulateAxisUntilRepetition(size_t axisIndex)\n{\n    while (true)\n    {\n        step();\n\n        bool isRepeat = std::equal(m_moons.cbegin(), m_moons.cend(), m_initialMoons.cbegin(), [axisIndex](const auto& lhs, const auto& rhs)\n                                    {\n                                        return lhs.isAxisMatching(rhs, axisIndex);\n                                    });\n\n        if (isRepeat)\n        {\n            break;\n        }\n    }\n}\n\nvoid MoonMotionSimulator::reset()\n{\n    m_numSteps = 0;\n    m_moons = m_initialMoons;\n}\n\nvoid MoonMotionSimulator::applyGravity(Moon& firstMoon, Moon& secondMoon)\n{\n    for (int axisIndex = 0; axisIndex <= 2; ++axisIndex)\n    {\n        int& firstMoonPositionCoordinate = firstMoon.pos[axisIndex];\n        int& secondMoonPositionCoordinate = secondMoon.pos[axisIndex];\n\n        int& firstMoonVelocityCoordinate = firstMoon.vel[axisIndex];\n        int& secondMoonVelocityCoordinate = secondMoon.vel[axisIndex];\n\n        pullCloser(firstMoonPositionCoordinate, secondMoonPositionCoordinate, firstMoonVelocityCoordinate, secondMoonVelocityCoordinate);\n    }\n}\n\nvoid MoonMotionSimulator::pullCloser(int p1, int p2, int& v1, int& v2)\n{\n    if (p1 < p2)\n    {\n        ++v1;\n        --v2;\n    }\n    else if (p1 > p2)\n    {\n        --v1;\n        ++v2;\n    }\n}\n\n}\n}\n}\n", "meta": {"hexsha": "8f2b10554fff2ad14e94ff9d19cb41f7a58da070", "size": 3709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AdventOfCode2019/Day12-TheNBodyProblem/MoonMotionSimulator.cpp", "max_stars_repo_name": "dbartok/advent-of-code-cpp", "max_stars_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AdventOfCode2019/Day12-TheNBodyProblem/MoonMotionSimulator.cpp", "max_issues_repo_name": "dbartok/advent-of-code-cpp", "max_issues_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AdventOfCode2019/Day12-TheNBodyProblem/MoonMotionSimulator.cpp", "max_forks_repo_name": "dbartok/advent-of-code-cpp", "max_forks_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4746835443, "max_line_length": 139, "alphanum_fraction": 0.6128336479, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.567377433770171}}
{"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\u00e9 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": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/module/core.hpp>\n#include <eve/module/polynomial.hpp>\n#include <cmath>\n#include <array>\n#include <vector>\n#include <boost/math/special_functions/chebyshev.hpp>\n\n\n//==================================================================================================\n//== Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of tchebeval on wide\"\n        , eve::test::simd::ieee_reals\n\n        )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  using i_t = eve::as_integer_t<v_t>;\n  TTS_EXPR_IS( eve::tchebeval(T(), T())  , T);\n  TTS_EXPR_IS( eve::tchebeval(T(), T(), T())  , T);\n  TTS_EXPR_IS( eve::tchebeval(T(), T(), T())  , T);\n  TTS_EXPR_IS( eve::tchebeval(T(), v_t(), v_t())  , T);\n  TTS_EXPR_IS( eve::tchebeval(T(), v_t(), int())  , T);\n  TTS_EXPR_IS( eve::tchebeval(T(), v_t(), i_t())  , T);\n  TTS_EXPR_IS( eve::tchebeval(v_t(), v_t(), v_t()), v_t);\n\n};\n\n//==================================================================================================\n//== tchebeval tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of tchebeval on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::ramp(0.0))\n        )\n<typename T>(T const& a0)\n{\n  using eve::tchebeval;\n  using eve::fma;\n  using eve::pedantic;\n  using eve::numeric;\n  using eve::one;\n  using v_t = eve::element_type_t<T>;\n  //============================================================================\n  //== variadic\n  //============================================================================\n  std::vector<v_t> c1{1};\n  std::vector<v_t> c2{1, 2};\n  std::vector<v_t> c3{1, 2, 3};\n  auto bcl1 = [c1](auto x)->v_t{return boost::math::chebyshev_clenshaw_recurrence(c1.data(), c1.size(), x);};\n  auto bcl2 = [c2](auto x)->v_t{return boost::math::chebyshev_clenshaw_recurrence(c2.data(), c2.size(), x);};\n  auto bcl3 = [c3](auto x)->v_t{return boost::math::detail::unchecked_chebyshev_clenshaw_recurrence(c3.data(), c3.size(), v_t(-1), v_t(1), v_t(x));};\n\n  TTS_EQUAL(tchebeval(a0), T(0));\n  TTS_EQUAL(tchebeval(a0, 1.0), T(0.5));\n  TTS_EQUAL(tchebeval(a0, 1.0),    map(bcl1, a0));\n  TTS_EQUAL(tchebeval(a0, 1.0, 2.0), map(bcl2, a0));\n  TTS_EQUAL(tchebeval(a0, 1.0, 2.0, 3.0), map(bcl3, a0));\n  TTS_ULP_EQUAL(tchebeval(0.0, 1.0, 2.0, 3.0), bcl3(0.0), 0.5);\n\n  TTS_EQUAL((tchebeval)(a0), T(0));\n  TTS_EQUAL((tchebeval)(a0, c1), T(0.5));\n  TTS_EQUAL((tchebeval)(a0, c2),  map(bcl2, a0));\n  TTS_EQUAL((tchebeval)(a0, c3),  map(bcl3, a0));\n  TTS_ULP_EQUAL((tchebeval)(v_t(0.24), c3),  bcl3(v_t(0.24)), 2.0);\n  TTS_ULP_EQUAL((tchebeval)(v_t(0.24), v_t(-1), v_t(1), c3),  bcl3(v_t(0.24)), 0.5);\n  TTS_ULP_EQUAL((tchebeval)(v_t(-0.24), v_t(-1), v_t(1), c3),  bcl3(v_t(-0.24)), 0.5);\n  TTS_ULP_EQUAL((tchebeval)(v_t(0.70), v_t(-1), v_t(1), c3),  bcl3(v_t(0.70)), 0.5);\n  TTS_ULP_EQUAL((tchebeval)(v_t(-0.70), v_t(-1), v_t(1), c3),  bcl3(v_t(-0.70)), 2.0);\n\n\n};\n", "meta": {"hexsha": "028819df2e642875e0cff72a5a187d31f29fc424", "size": 3401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/polynomial/tchebeval.cpp", "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": "test/unit/module/polynomial/tchebeval.cpp", "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": "test/unit/module/polynomial/tchebeval.cpp", "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": 41.4756097561, "max_line_length": 149, "alphanum_fraction": 0.4827991767, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5673678543327006}}
{"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": "\ufeff/*\n * @Author: Han\n * @Date: 2018-05-05 20:49:29\n * \u76f8\u673a\u4fe1\u606f\n */\n#include <base/camera.h>\n\n#include <Eigen/Geometry>\n\nnamespace h2o {\nFrameCamera::FrameCamera() {\n    cid_ = INVALID_INDEX;\n    iid_ = INVALID_INDEX;\n    size_ = Vector2i(-1, -1);\n    K = Matrix3d::Zero();\n    R = Matrix3d::Zero();\n    C = Vector3d::Zero();\n    P = Matrix34d::Zero();\n}\nFrameCamera::FrameCamera(uint32_t cid, uint32_t iid, int width, int height, double delta, double f, double x0,\n                         double y0, const Vector3d &r, const Vector3d &X) {\n    cid_ = cid;\n    iid_ = iid;\n    size_(0) = width;\n    size_(1) = height;\n\n    K(0, 0) = f / delta;\n    K(1, 1) = f / delta;\n    double u0 = (width - 1) / 2.0 + x0 / delta;\n    double v0 = (height - 1) / 2.0 - y0 / delta;\n\n    K(0, 1) = 0.0;\n    K(0, 2) = u0;\n\n    K(1, 0) = 0.0;\n    K(1, 2) = v0;\n\n    K(2, 0) = 0.0;\n    K(2, 1) = 0.0;\n    K(2, 2) = 1.0;\n\n    double angle = r.norm();\n    Vector3d axis = r.normalized();\n    Matrix3d Rpg = Eigen::AngleAxisd(angle, axis).toRotationMatrix();\n    Matrix3d R_x = Eigen::AngleAxisd(M_PI, Vector3d::UnitX()).toRotationMatrix();\n    R = Rpg * R_x;\n    R.transposeInPlace();\n\n    C = X;\n    Vector3d t = -R * C;\n    P << R, t;\n    P = K * P;\n}\nFrameCamera::~FrameCamera() {}\n} // namespace h2o\n", "meta": {"hexsha": "173d817b8a12b2f15532faf1cd2c67e3b9959c87", "size": 1277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/base/camera.cpp", "max_stars_repo_name": "mmrwizard/RenderMatch-1", "max_stars_repo_head_hexsha": "a427138e6823675eaa76c693bc31a28566b4dcd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/base/camera.cpp", "max_issues_repo_name": "mmrwizard/RenderMatch-1", "max_issues_repo_head_hexsha": "a427138e6823675eaa76c693bc31a28566b4dcd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base/camera.cpp", "max_forks_repo_name": "mmrwizard/RenderMatch-1", "max_forks_repo_head_hexsha": "a427138e6823675eaa76c693bc31a28566b4dcd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-12T08:19:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-12T08:19:14.000Z", "avg_line_length": 22.8035714286, "max_line_length": 110, "alphanum_fraction": 0.5411119812, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5673678201644196}}
{"text": "#include <boost/math/interpolators/cubic_b_spline.hpp>\n", "meta": {"hexsha": "802422cbc8aeb87add3fccbb2c964a2836422fe9", "size": 55, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_interpolators_cubic_b_spline.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_interpolators_cubic_b_spline.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_interpolators_cubic_b_spline.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.5, "max_line_length": 54, "alphanum_fraction": 0.8363636364, "num_tokens": 15, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181876, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5673672884555111}}
{"text": "#include <stdlib.h>\n#include <math.h>\n#include <stdint.h>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmisleading-indentation\"\n#include <Eigen/Core>\n#pragma GCC diagnostic pop\n\nstruct Aligned {\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n#ifndef M_PI\n#define M_PI            3.14159265358979323846\n#define M_SQRT2         1.41421356237309504880\n#define M_SQRT1_2       0.707106781186547524401\n#endif\n\n#ifdef __SSE2__\n#include <emmintrin.h>\n#endif\n\n#define TEMPLATE template<typename T>\n#define INNER static inline\n#ifdef _MSC_VER\n#define PURE\n#define CONST\n#define RESTRICT\n#else\n#define PURE __attribute__((pure))\n#define CONST __attribute__((const))\n#define RESTRICT __restrict__\n#endif\n\ntypedef unsigned long ulong; // __attribute((aligned(16)));\n\n#ifndef BLOCK_SIZE\n#define BLOCK_SIZE 256\n#endif\n\n#include \"vectors.hpp\"\n\n#ifdef FORCE_SINGLE\n#define v2df v2sf\n#endif\n\nINNER void\ndisable_denormals()\n{\n\t#if __SSE2__\n\t_mm_setcsr(_mm_getcsr() | 0x8040);\n\t#endif\n}\n\n#define LIMIT(v,l,u) ((v)<(l)?(l):((v)>(u)?(u):(v)))\n#define DB2LIN(x) ((x) > -90 ? pow(10, (x) * 0.05) : 0)\n\n/* frequency to rads/sec (angular frequency) */\n#define ANGULAR(fc, fs)     (2 * M_PI / (fs) * (fc))\n#define ANGULAR_LIM(fc, fs) (2 * M_PI / (fs) * LIMIT((fc), 1, (fs)/2))\n\n/* via http://www.rgba.org/articles/sfrand/sfrand.htm */\nINNER float\nwhitenoise(unsigned int &mirand)\n{\n\tunion either {\n\t\tfloat f;\n\t\tunsigned int i;\n\t} white;\n\tmirand *= 16807;\n\twhite.i = (mirand & 0x007FFFFF) | 0x40000000;\n\treturn white.f - 3;\n}\n\ntypedef enum {\n\tFILT_PEAKING,\n\tFILT_LOWSHELF,\n\tFILT_HIGHSHELF,\n\tFILT_LOWPASS,\n\tFILT_HIGHPASS,\n\tFILT_ALLPASS,\n\tFILT_BANDPASS,\n\tFILT_BANDPASS_2,\n\tFILT_NOTCH,\n\tFILT_GAIN\n} filter_t;\n", "meta": {"hexsha": "8ff8a5d0ce1f460735a819b1f34f5c73fcf99edf", "size": 1686, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/util.hpp", "max_stars_repo_name": "notwa/crap", "max_stars_repo_head_hexsha": "fe81ca33f7940a98321d9efce5bc43f400016955", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T00:03:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-27T00:03:28.000Z", "max_issues_repo_path": "include/util.hpp", "max_issues_repo_name": "notwa/crap", "max_issues_repo_head_hexsha": "fe81ca33f7940a98321d9efce5bc43f400016955", "max_issues_repo_licenses": ["MIT"], "max_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.hpp", "max_forks_repo_name": "notwa/crap", "max_forks_repo_head_hexsha": "fe81ca33f7940a98321d9efce5bc43f400016955", "max_forks_repo_licenses": ["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.1590909091, "max_line_length": 70, "alphanum_fraction": 0.7099644128, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623015, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.567367270501108}}
{"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": "\n#include <NTL/lzz_pXFactoring.h>\n#include <NTL/lzz_pEXFactoring.h>\n\nNTL_CLIENT\n\nint main()\n{\n   zz_p::init(17);\n\n   zz_pX P;\n   BuildIrred(P, 10);\n\n   zz_pE::init(P);\n\n   zz_pEX f, g, h;\n\n   random(f, 20);\n   SetCoeff(f, 20);\n\n   random(h, 20);\n\n   g = MinPolyMod(h, f);\n\n   if (deg(g) < 0) Error(\"bad zz_pEXTest (1)\");\n   if (CompMod(g, h, f) != 0)\n      Error(\"bad zz_pEXTest (2)\");\n\n\n   \n   vec_pair_zz_pEX_long v;\n\n   long i;\n   for (i = 0; i < 5; i++) {\n      long n = RandomBnd(20)+1;\n      cerr << n << \" \";\n\n      random(f, n);\n      SetCoeff(f, n);\n\n      v = CanZass(f);\n\n      g = mul(v);\n      if (f != g) cerr << \"oops1\\n\";\n\n      long i;\n      for (i = 0; i < v.length(); i++)\n         if (!DetIrredTest(v[i].a))\n            Error(\"bad zz_pEXTest (3)\");\n\n\n   }\n\n   cerr << \"\\n\";\n\n   cerr << \"zz_pEXTest OK\\n\";\n}\n", "meta": {"hexsha": "820778a75600c5febdedb1534410bd81316f3c70", "size": 827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/tests/lzz_pEXTest.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RUNETag/WinNTL/tests/lzz_pEXTest.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/tests/lzz_pEXTest.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.2586206897, "max_line_length": 47, "alphanum_fraction": 0.4800483676, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.56733324829483}}
{"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": "// (C) Copyright Andrew Sutton 2007\r\n//\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0 (See accompanying file\r\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[scaled_closeness_centrality_example\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\n#include <boost/graph/undirected_graph.hpp>\r\n#include <boost/graph/exterior_property.hpp>\r\n#include <boost/graph/floyd_warshall_shortest.hpp>\r\n#include <boost/graph/closeness_centrality.hpp>\r\n#include \"helper.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\n\r\n// This template struct provides a generic version of a \"scaling\"\r\n// closeness measure. Specifically, this implementation divides\r\n// the number of vertices in the graph by the sum of geodesic\r\n// distances of each vertex. This measure allows customization\r\n// of the distance type, result type, and even the underlying\r\n// divide operation.\r\ntemplate <typename Graph,\r\n          typename Distance,\r\n          typename Result,\r\n          typename Divide = divides<Result> >\r\nstruct scaled_closeness_measure\r\n{\r\n    typedef Distance distance_type;\r\n    typedef Result result_type;\r\n\r\n    Result operator ()(Distance d, const Graph& g)\r\n    {\r\n        if(d == numeric_values<Distance>::infinity()) {\r\n            return numeric_values<Result>::zero();\r\n        }\r\n        else {\r\n            return div(Result(num_vertices(g)), Result(d));\r\n        }\r\n    }\r\n    Divide div;\r\n};\r\n\r\n// The Actor type stores the name of each vertex in the graph.\r\nstruct Actor\r\n{\r\n    std::string name;\r\n};\r\n\r\n// Declare the graph type and its vertex and edge types.\r\ntypedef undirected_graph<Actor> Graph;\r\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\r\ntypedef graph_traits<Graph>::edge_descriptor Edge;\r\n\r\n// The name map provides an abstract accessor for the names of\r\n// each vertex. This is used during graph creation.\r\ntypedef property_map<Graph, string Actor::*>::type NameMap;\r\n\r\n// Declare a matrix type and its corresponding property map that\r\n// will contain the distances between each pair of vertices.\r\ntypedef exterior_vertex_property<Graph, int> DistanceProperty;\r\ntypedef DistanceProperty::matrix_type DistanceMatrix;\r\ntypedef DistanceProperty::matrix_map_type DistanceMatrixMap;\r\n\r\n// Declare the weight map so that each edge returns the same value.\r\ntypedef constant_property_map<Edge, int> WeightMap;\r\n\r\n// Declare a container and its corresponding property map that\r\n// will contain the resulting closeness centralities of each\r\n// vertex in the graph.\r\ntypedef boost::exterior_vertex_property<Graph, float> ClosenessProperty;\r\ntypedef ClosenessProperty::container_type ClosenessContainer;\r\ntypedef ClosenessProperty::map_type ClosenessMap;\r\n\r\nint\r\nmain(int argc, char *argv[])\r\n{\r\n    // Create the graph and a property map that provides access\r\n    // to the actor names.\r\n    Graph g;\r\n    NameMap nm(get(&Actor::name, g));\r\n\r\n    // Read the graph from standard input.\r\n    read_graph(g, nm, cin);\r\n\r\n    // Compute the distances between all pairs of vertices using\r\n    // the Floyd-Warshall algorithm. Note that the weight map is\r\n    // created so that every edge has a weight of 1.\r\n    DistanceMatrix distances(num_vertices(g));\r\n    DistanceMatrixMap dm(distances, g);\r\n    WeightMap wm(1);\r\n    floyd_warshall_all_pairs_shortest_paths(g, dm, weight_map(wm));\r\n\r\n    // Create the scaled closeness measure.\r\n    scaled_closeness_measure<Graph, int, float> m;\r\n\r\n    // Compute the degree centrality for graph\r\n    ClosenessContainer cents(num_vertices(g));\r\n    ClosenessMap cm(cents, g);\r\n    all_closeness_centralities(g, dm, cm, m);\r\n\r\n    // Print the scaled closeness centrality of each vertex.\r\n    graph_traits<Graph>::vertex_iterator i, end;\r\n    for(boost::tie(i, end) = vertices(g); i != end; ++i) {\r\n        cout << setw(12) << setiosflags(ios::left)\r\n             << g[*i].name << get(cm, *i) << endl;\r\n    }\r\n\r\n    return 0;\r\n}\r\n//]\r\n", "meta": {"hexsha": "072187f886e6367dfe4762434847d686fc927051", "size": 3941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/graph/example/scaled_closeness_centrality.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/graph/example/scaled_closeness_centrality.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/graph/example/scaled_closeness_centrality.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": 34.2695652174, "max_line_length": 73, "alphanum_fraction": 0.7056584623, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5673287765754839}}
{"text": "#include <boost/test/test_case_template.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <vmath/functions.hpp>\n#include \"type_lists.hpp\"\n\nBOOST_AUTO_TEST_SUITE(functions)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(pi, T, float_types) {\n\tBOOST_CHECK_CLOSE(static_cast<T>(vmath::PI), static_cast<T>(3.14159265358979323846), 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(equals, T, float_types) {\n\tBOOST_CHECK(vmath::equals(static_cast<T>(1.2), static_cast<T>(1.2)));\n\tBOOST_CHECK(!vmath::equals(static_cast<T>(1.2), static_cast<T>(1.3)));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(equals_specify_ulp, T, float_types) {\n\tBOOST_CHECK(vmath::equals(static_cast<T>(1.2), static_cast<T>(1.2), 3));\n\tBOOST_CHECK(!vmath::equals(static_cast<T>(1.2), static_cast<T>(1.3), 3));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(degrees_to_radians, T, float_types) {\n\tBOOST_CHECK_SMALL(vmath::radians(static_cast<T>(0.0)), static_cast<T>(1e-7));\n\tBOOST_CHECK_CLOSE(vmath::radians(static_cast<T>(180.0)), static_cast<T>(vmath::PI), 1e-4f);\n\tBOOST_CHECK_CLOSE(vmath::radians(static_cast<T>(23.5)), static_cast<T>(0.410152374), 1e-4f);\n\tBOOST_CHECK_CLOSE(vmath::radians(static_cast<T>(985.0)), static_cast<T>(17.1914921), 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(radians_to_degrees, T, float_types) {\n\tBOOST_CHECK_SMALL(vmath::degrees(static_cast<T>(0.0)), static_cast<T>(1e-7));\n\tBOOST_CHECK_CLOSE(vmath::degrees(static_cast<T>(vmath::PI)), static_cast<T>(180.0), 1e-4f);\n\tBOOST_CHECK_CLOSE(vmath::degrees(static_cast<T>(0.345)), static_cast<T>(19.76704393), 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(clamp, T, float_types) {\n\tBOOST_CHECK_CLOSE(vmath::clamp(static_cast<T>(1.2), static_cast<T>(1.5), static_cast<T>(2.0)), static_cast<T>(1.5), 1e-4f);\n\tBOOST_CHECK_CLOSE(vmath::clamp(static_cast<T>(1.5), static_cast<T>(1.5), static_cast<T>(2.0)), static_cast<T>(1.5), 1e-4f);\n\tBOOST_CHECK_CLOSE(vmath::clamp(static_cast<T>(1.75), static_cast<T>(1.5), static_cast<T>(2.0)), static_cast<T>(1.75), 1e-4f);\n\tBOOST_CHECK_CLOSE(vmath::clamp(static_cast<T>(2.0), static_cast<T>(1.5), static_cast<T>(2.0)), static_cast<T>(2.0), 1e-4f);\n\tBOOST_CHECK_CLOSE(vmath::clamp(static_cast<T>(2.2), static_cast<T>(1.5), static_cast<T>(2.0)), static_cast<T>(2.0), 1e-4f);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(lerp, T, float_types) {\n\tBOOST_CHECK_CLOSE(vmath::lerp(static_cast<T>(1.0), static_cast<T>(2.0), static_cast<T>(0.0)), static_cast<T>(1.0), 1e-4f);\n\tBOOST_CHECK_CLOSE(vmath::lerp(static_cast<T>(1.0), static_cast<T>(2.0), static_cast<T>(1.0)), static_cast<T>(2.0), 1e-4f);\n\tBOOST_CHECK_CLOSE(vmath::lerp(static_cast<T>(1.0), static_cast<T>(2.0), static_cast<T>(0.5)), static_cast<T>(1.5), 1e-4f);\n\tBOOST_CHECK_CLOSE(vmath::lerp(static_cast<T>(1.2), static_cast<T>(3.4), static_cast<T>(0.34)), static_cast<T>(1.948), 1e-4f);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6cc32e0119ad1f9086ec224774af274266fd2c9c", "size": 2783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/functions.cpp", "max_stars_repo_name": "ChasingCarrots/vmath", "max_stars_repo_head_hexsha": "06cc93e0d3d152306dbd63b60fa7cc4761f331bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-15T13:56:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-15T13:56:26.000Z", "max_issues_repo_path": "test/functions.cpp", "max_issues_repo_name": "kernan/math", "max_issues_repo_head_hexsha": "6c28e7e731a2ea47a7b66b5dd4170283e84f1e02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T19:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T21:19:58.000Z", "max_forks_repo_path": "test/functions.cpp", "max_forks_repo_name": "kernan/vmath", "max_forks_repo_head_hexsha": "6c28e7e731a2ea47a7b66b5dd4170283e84f1e02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-06T21:00:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-06T21:00:34.000Z", "avg_line_length": 53.5192307692, "max_line_length": 126, "alphanum_fraction": 0.7344592167, "num_tokens": 915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5673287672718541}}
{"text": "/**\n * @file shortest_path.cc\n *\n * Implement the BGL shortest path algorithm wrappers.\n */\n\n/*\n * David Gleich\n * 19 April 2006\n */\n\n/*\n * 18 April 2007\n * Added src/dst vertex pairs to all the calls to allow partial searches.\n * Corrected small documentation bugs.\n *\n * 9 July 2007\n * Switched to simple_csr_matrix graph type\n */\n\n#include \"include/matlab_bgl.h\"\n\n#include <yasmic/simple_csr_matrix_as_graph.hpp>\n#include <yasmic/iterator_utility.hpp>\n\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <yasmic/boost_mod/bellman_ford_shortest_paths.hpp>\n#include <boost/graph/dag_shortest_paths.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <yasmic/boost_mod/floyd_warshall_shortest.hpp>\n\n#include \"visitor_macros.hpp\"\n#include \"stop_visitors.hpp\"\n#include \"libmbgl_util.hpp\"\n\nstruct stop_dijkstra {}; // stop dijkstra exception\n\nint dijkstra_sp(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    mbglIndex src, mbglIndex dst, /* problem data */\n    double* d, mbglIndex *pred, double dinf)\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    if (dst == nverts) {\n        dijkstra_shortest_paths(g, src, distance_inf(dinf).predecessor_map(pred).distance_map(d));\n    } else {\n        try {\n            dijkstra_shortest_paths(g, src,\n                distance_inf(dinf).predecessor_map(pred).distance_map(d).\n                visitor(make_dijkstra_visitor(\n                            stop_search_on_vertex_target(dst, stop_dijkstra(), on_discover_vertex()))));\n        } catch (stop_dijkstra) {}\n    }\n\n    return (0);\n}\n\ntemplate <class Graph>\nstruct c_dijkstra_visitor\n{\n    dijkstra_visitor_funcs_t *vis;\n\n    VISITOR_VERTEX_FUNC(initialize_vertex, stop_dijkstra)\n    VISITOR_VERTEX_FUNC(examine_vertex, stop_dijkstra)\n    VISITOR_VERTEX_FUNC(discover_vertex, stop_dijkstra)\n    VISITOR_VERTEX_FUNC(finish_vertex, stop_dijkstra)\n\n    VISITOR_EDGE_FUNC(examine_edge, stop_dijkstra)\n    VISITOR_EDGE_FUNC(edge_relaxed, stop_dijkstra)\n    VISITOR_EDGE_FUNC(edge_not_relaxed, stop_dijkstra)\n\n};\n\nint dijkstra_sp_visitor(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    mbglIndex src, /* problem data */\n    double* d, mbglIndex *pred,\n    double dinf, dijkstra_visitor_funcs_t vis)\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    c_dijkstra_visitor<crs_weighted_graph> visitor_impl;\n    visitor_impl.vis = &vis;\n\n    try\n    {\n        dijkstra_shortest_paths(g, src, distance_inf(dinf).predecessor_map(pred).distance_map(d).visitor(visitor_impl));\n    }\n    catch (stop_dijkstra)\n    {\n    }\n\n    return (0);\n}\n\nstruct stop_bellman_ford {}; // stop bellman_ford exception\n\nint bellman_ford_sp(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    mbglIndex src, mbglIndex dst, /* problem data */\n    double* d, mbglIndex *pred, double dinf)\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    if (dst == nverts) {\n        bellman_ford_shortest_paths(g,\n            root_vertex(src).distance_inf(dinf).predecessor_map(pred).distance_map(d));\n    } else {\n        try {\n            bellman_ford_shortest_paths(g,\n                root_vertex(src).distance_inf(dinf).predecessor_map(pred).distance_map(d).\n                visitor(make_bellman_visitor(\n                            stop_search_on_vertex_target(dst, stop_bellman_ford(), on_discover_vertex()))));\n        } catch (stop_bellman_ford) {}\n    }\n\n    return (0);\n}\n\ntemplate <class Graph>\nstruct c_bellman_ford_visitor\n{\n    bellman_ford_visitor_funcs_t *vis;\n\n    VISITOR_VERTEX_FUNC(initialize_vertex, stop_bellman_ford)\n\n    VISITOR_EDGE_FUNC(examine_edge, stop_bellman_ford)\n    VISITOR_EDGE_FUNC(edge_relaxed, stop_bellman_ford)\n    VISITOR_EDGE_FUNC(edge_not_relaxed, stop_bellman_ford)\n    VISITOR_EDGE_FUNC(edge_minimized, stop_bellman_ford)\n    VISITOR_EDGE_FUNC(edge_not_minimized, stop_bellman_ford)\n};\n\nint bellman_ford_sp_visitor(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    mbglIndex src,  /* problem data */\n    double* d, mbglIndex *pred, double dinf,\n    bellman_ford_visitor_funcs_t vis)\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    c_bellman_ford_visitor<crs_weighted_graph> visitor_impl;\n    visitor_impl.vis = &vis;\n\n    try\n    {\n        bellman_ford_shortest_paths(g,\n            root_vertex(src).distance_inf(dinf).predecessor_map(pred).distance_map(d).visitor(visitor_impl));\n    }\n    catch (stop_bellman_ford)\n    {\n    }\n\n    return (0);\n}\n\nstruct stop_dag {}; // stop dag exception\n\nint dag_sp(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    mbglIndex src, mbglIndex dst, /* problem data */\n    double* d, mbglIndex *pred, double dinf)\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    if (dst == nverts) {\n        dag_shortest_paths(g, src,\n            distance_inf(dinf).predecessor_map(pred).distance_map(d));\n    } else {\n        try {\n            dag_shortest_paths(g, src,\n                distance_inf(dinf).predecessor_map(pred).distance_map(d).\n                visitor(make_dijkstra_visitor(\n                    stop_search_on_vertex_target(dst, stop_dag(), on_discover_vertex()))));\n        } catch (stop_dag) {}\n    }\n\n    return (0);\n}\n\nint johnson_all_sp(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    double* D, double dinf)\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    row_matrix<double> Dmat(D,nverts,nverts);\n\n    bool rval = johnson_all_pairs_shortest_paths(g, Dmat,\n\t\tdistance_inf(dinf).distance_combine(std::plus<double>()));\n\n\tif (rval == true)\n\t{\n\t\treturn (0);\n\t}\n\n\t// else, there was an error\n\treturn (-1);\n}\n\nint floyd_warshall_all_sp(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    double* D, double dinf,\n    mbglIndex* pred)\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    row_matrix<double> Dmat(D,nverts,nverts);\n    bool rval = false;\n    if (!pred) {\n        rval = floyd_warshall_all_pairs_shortest_paths(g,\n            Dmat, distance_inf(dinf).distance_combine(std::plus<double>()));\n    } else {\n        row_matrix<mbglIndex> Pmat(pred,nverts,nverts);\n        //rval = floyd_warshall_all_pairs_shortest_paths(g,\n        //    Dmat, distance_inf(dinf).distance_combine(std::plus<double>()).predecessor_map(Pmat));\n        // making this call is ridiculous, but otherwise, it won't pick up the right type!\n        rval = floyd_warshall_all_pairs_shortest_paths(g, Dmat, Pmat, get(edge_weight,g),\n            std::less<double>(),std::plus<double>(),dinf,0.0);\n    }\n\n\tif (rval == true)\n\t{\n\t\treturn (0);\n\t}\n\n\t// else, there was an error\n\treturn (-1);\n}\n\n", "meta": {"hexsha": "0c4735181ae6f112fc404ffe25b7cf407257a322", "size": 7819, "ext": "cc", "lang": "C++", "max_stars_repo_path": "2A/Graphes/TPs/matlab_bgl/libmbgl/shortest_path.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/shortest_path.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/shortest_path.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": 30.0730769231, "max_line_length": 120, "alphanum_fraction": 0.6976595473, "num_tokens": 2081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5673287626200392}}
{"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 <boost/multiprecision/cpp_int.hpp>\n#include <string>\n#include <iostream>\n\nusing namespace std;\nusing namespace boost::multiprecision;\n\nusing big_int = cpp_int;\n// using rational = cpp_rational;\n\n\nint main()\n{\n    big_int i;\n    cout << \"Enter an arbitrary large integer number: \" << endl;\n    cin >> i;\n\n    cout << \"You entered:\\n\" << i << endl;\n    cout << \"i * 2 = \" << i * 2 << endl;\n    cout << \"i / i = \" << i / i << endl;\n}\n", "meta": {"hexsha": "f3d28a300c4f1e83076ce1d05a46c3021969f8bc", "size": 440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lab28/2 - multiprecision.cpp", "max_stars_repo_name": "uiowa-cs-3210-0001/cs3210-labs", "max_stars_repo_head_hexsha": "d6263d719a45257ba056a1ead7cc3dd428d377f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-24T14:04:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-24T14:04:45.000Z", "max_issues_repo_path": "lab28/2 - multiprecision.cpp", "max_issues_repo_name": "uiowa-cs-3210-0001/cs3210-labs", "max_issues_repo_head_hexsha": "d6263d719a45257ba056a1ead7cc3dd428d377f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-24T18:32:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-28T04:10:28.000Z", "max_forks_repo_path": "lab28/2 - multiprecision.cpp", "max_forks_repo_name": "uiowa-cs-3210-0001/cs3210-labs", "max_forks_repo_head_hexsha": "d6263d719a45257ba056a1ead7cc3dd428d377f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-07T00:28:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-07T00:28:20.000Z", "avg_line_length": 20.0, "max_line_length": 64, "alphanum_fraction": 0.5977272727, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5673164082976462}}
{"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": "// This is an interactive demo, so feel free to change the code and click the 'Run' button.\n\n// This simple program uses the mlpack::neighbor::NeighborSearch object\n// to find the nearest neighbor of each point in a dataset using the L1 metric,\n// and then print the index of the neighbor and the distance of it to stdout.\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/neighbor_search/neighbor_search.hpp>\n#include <armadillo>\n#include <iostream>\n\nusing namespace mlpack;\nusing namespace mlpack::neighbor; // NeighborSearch and NearestNeighborSort\nusing namespace mlpack::metric; // ManhattanDistance\nusing namespace mlpack::ann;\n\nint main() {\n    std::cout << \"MLPack Example \" << std::endl;\n    // Load the data from data.csv (hard-coded).  Use CLI for simple command-line\n    // parameter handling.\n    arma::mat data(\"0.339406815,0.843176636,0.472701471; \\\n                  0.212587646,0.351174901,0.81056695;  \\\n                  0.160147626,0.255047893,0.04072469;  \\\n                  0.564535197,0.943435462,0.597070812\");\n    data = data.t();\n    std::cout << data << std::endl;\n\n    // Use templates to specify that we want a NeighborSearch object which uses\n    // the Manhattan distance.\n    NeighborSearch<NearestNeighborSort, ManhattanDistance> nn(data);\n\n    // Create the object we will store the nearest neighbors in.\n    arma::Mat<size_t> neighbors;\n    arma::mat distances; // We need to store the distance too.\n\n    // Compute the neighbors.\n    nn.Search(1, neighbors, distances);\n\n    // Write each neighbor and distance using Log.\n    for (size_t i = 0; i < neighbors.n_elem; ++i) {\n        std::cout << \"Nearest neighbor of point \" << i << \" is point \"\n                  << neighbors[i] << \" and the distance is \" << distances[i] << \".\" << std::endl;\n    }\n\n    /// next step\n    // Load the training set and testing set.\n    arma::mat trainData;\n    data::Load(\"/Users/zachbortoff/Downloads/mlpack/build/thyroid_train.csv\", trainData, true);\n    arma::mat testData;\n    data::Load(\"/Users/zachbortoff/Downloads/mlpack/build/thyroid_test.csv\", testData, true);\n    // Split the labels from the training set and testing set respectively.\n    arma::mat trainLabels = trainData.row(trainData.n_rows - 1);\n    arma::mat testLabels = testData.row(testData.n_rows - 1);\n    trainData.shed_row(trainData.n_rows - 1);\n    testData.shed_row(testData.n_rows - 1);\n    // Initialize the network.\n    FFN<> model;\n    model.Add<Linear<> >(trainData.n_rows, 8);\n    model.Add<SigmoidLayer<> >();\n    model.Add<Linear<> >(8, 3);\n    model.Add<LogSoftMax<> >();\n    // Train the model.\n    model.Train(trainData, trainLabels);\n    // Use the Predict method to get the predictions.\n    arma::mat predictionTemp;\n    model.Predict(testData, predictionTemp);\n    /*\n      Since the predictionsTemp is of dimensions (3 x number_of_data_points)\n      with continuous values, we first need to reduce it to a dimension of\n      (1 x number_of_data_points) with scalar values, to be able to compare with\n      testLabels.\n      The first step towards doing this is to create a matrix of zeros with the\n      desired dimensions (1 x number_of_data_points).\n      In predictionsTemp, the 3 dimensions for each data point correspond to the\n      probabilities of belonging to the three possible classes.\n    */\n    arma::mat prediction = arma::zeros<arma::mat>(1, predictionTemp.n_cols);\n    // Find index of max prediction for each data point and store in \"prediction\"\n    for (size_t i = 0; i < predictionTemp.n_cols; ++i)\n    {\n        // we add 1 to the max index, so that it matches the actual test labels.\n        prediction(i) = arma::as_scalar(arma::find(\n                arma::max(predictionTemp.col(i)) == predictionTemp.col(i), 1)) + 1;\n    }\n    /*\n      Compute the error between predictions and testLabels,\n      now that we have the desired predictions.\n    */\n    size_t correct = arma::accu(prediction == testLabels);\n    double classificationError = 1 - double(correct) / testData.n_cols;\n    // Print out the classification error for the testing dataset.\n    std::cout << \"Classification Error for the Test set: \" << classificationError << std::endl;\n\n    return 0;\n}", "meta": {"hexsha": "5b1877375ab2f84aaee7a81ab4eccff478f18625", "size": 4276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/mlpack_test.cpp", "max_stars_repo_name": "zborffs/Delta", "max_stars_repo_head_hexsha": "b2efa9fe1cc2138656f4d7964ccdbbbfcebba639", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-03T09:34:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T09:34:54.000Z", "max_issues_repo_path": "test/mlpack_test.cpp", "max_issues_repo_name": "zborffs/Delta", "max_issues_repo_head_hexsha": "b2efa9fe1cc2138656f4d7964ccdbbbfcebba639", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/mlpack_test.cpp", "max_forks_repo_name": "zborffs/Delta", "max_forks_repo_head_hexsha": "b2efa9fe1cc2138656f4d7964ccdbbbfcebba639", "max_forks_repo_licenses": ["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.0824742268, "max_line_length": 97, "alphanum_fraction": 0.6800748363, "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5672518333988837}}
{"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": "//==================================================================================================\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_ACOSH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACOSH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-hyperbolic\n    Function object implementing acosh capabilities\n\n    Returns the hyperbolic cosine argument: \\f$\\log(x+\\sqrt{x^2-1})\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type @c T\n\n    @code\n    T r = acosh(x);\n    @endcode\n\n    @see log, sqrt, cosh, dec\n\n  **/\n  Value acosh(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acosh.hpp>\n#include <boost/simd/function/simd/acosh.hpp>\n\n#endif\n", "meta": {"hexsha": "1b60e800a0fc0f46ca7bd650d1848a3e93764967", "size": 1006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acosh.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/acosh.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/acosh.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.8636363636, "max_line_length": 100, "alphanum_fraction": 0.5685884692, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5672518193543536}}
{"text": "#ifndef icvPrimitiveTensorData_hxx\r\n#define icvPrimitiveTensorData_hxx\r\n\r\n#include \"OpenICV/Core/icvDataObject.h\"\r\n\r\n#include <vector>\r\n#include <cstdarg>\r\n#include <boost/static_assert.hpp>\r\n#include <boost/type_traits/is_pod.hpp>\r\n\r\nnamespace icv { namespace data\r\n{\r\n    enum icvTensorIndexOrder\r\n    {\r\n        FromFirst, // Index from leftmost, i.e. the last index is contiguous, i.e. row major, i.e. lexicographical\r\n        FromLast,  // Index from rightmost, i.e. the first index is contiguous, i.e column major, i.e. colexicographical\r\n    };\r\n\r\n    template<typename ElemT, icvTensorIndexOrder IndexOrder = FromFirst>\r\n    class icvPrimitiveTensorData : public icv::core::icvDataObject\r\n    {\r\n    private:\r\n        BOOST_STATIC_ASSERT_MSG(boost::is_pod<ElemT>::value, \"icvPrimitiveTensorData only support POD types\");\r\n\r\n    public:\r\n        icvPrimitiveTensorData(const std::vector<IndexType>& shape) :_shape(shape) {}\r\n\r\n        IndexType GetSize() const\r\n        { \r\n            IndexType total = 1;\r\n            for (auto count : _shape)\r\n                total *= count;\r\n            return total;\r\n        }\r\n        const std::vector<IndexType>& GetShape() const { return _shape; }\r\n\r\n        virtual void Reserve() ICV_OVERRIDE { if (!_data) _data = new ElemT[GetSize()]; }\r\n        virtual void Dispose() ICV_OVERRIDE { if (_data) delete[] _data; _data = ICV_NULLPTR; }\r\n\r\n        void Reshape(const std::vector<IndexType>& shape) { throw \"Not Implemented yet!\"; }\r\n        \r\n        virtual Uint64 GetActualMemorySize() ICV_OVERRIDE\r\n        {\r\n            if (_data) return sizeof(ElemT) * GetSize();\r\n            else return 0;\r\n        }\r\n\r\n        // TODO: Not implemented yet\r\n        virtual void Serialize(std::stringstream& out, const uint32_t& version) const { throw \"Not implemented yet!\"; }\r\n        virtual void Deserialize(std::stringstream& in, const uint32_t& version) { throw \"Not implemented yet!\"; }\r\n        \r\n        virtual icv::core::icvDataObject* DeepCopy() ICV_OVERRIDE\r\n        {\r\n            icvPrimitiveTensorData<ElemT, IndexOrder>* copy = new icvPrimitiveTensorData<ElemT, IndexOrder>(_shape);\r\n            copy->_sourceTime = _sourceTime;\r\n            copy->Reserve(); std::copy(_data, _data + GetSize(), copy->_data);\r\n            return copy;\r\n        }\r\n\r\n        ElemT & At(const std::vector<IndexType>& index)\r\n        {\r\n            if (index.size() != _shape.size())\r\n                ICV_THROW_MESSAGE(\"Input indices for At() should have the same length with the shape of tensor\");\r\n                // TODO: return an iterator if length of index is smaller than shape\r\n\r\n            IndexType tidx = 0;\r\n            if (IndexOrder == FromFirst)\r\n                for (IndexType i = 0; i < index.size(); i++)\r\n                    tidx = tidx * _shape[i] + index[i];\r\n            else\r\n            {\r\n                for (IndexType i = index.size() - 1; i > 0; i--) // Avoid overflow of i\r\n                    tidx = tidx * _shape[i] + index[i];\r\n                tidx = tidx * _shape[0] + index[0];\r\n            }\r\n\r\n            return _data[tidx];\r\n        }\r\n\r\n        const ElemT & At(const std::vector<IndexType>& index) const\r\n        {\r\n            return const_cast<icvPrimitiveTensorData&>(*this).At(index);\r\n        }\r\n\r\n        // Note: use 'u' literal when calling this function\r\n        template<typename... T>\r\n        ElemT & At(T... indices)\r\n        {\r\n            std::vector<IndexType> ids{ indices... };\r\n            return At(ids);\r\n        }\r\n\r\n        template<typename... T>\r\n        const ElemT & At(T... indices) const\r\n        {\r\n            return const_cast<icvPrimitiveTensorData&>(*this).At(indices...);\r\n        }\r\n\r\n        virtual std::string Print() ICV_OVERRIDE\r\n        {\r\n            throw \"Not implemented yet!\";\r\n        }\r\n\r\n    protected:\r\n        std::vector<IndexType> _shape;\r\n        ElemT* _data = ICV_NULLPTR;\r\n    };\r\n\r\n    #define _ICV_DECLARE_TENSOR_DATA(type) typedef icvPrimitiveTensorData<type> icv##type##TensorData;\r\n    ICV_BASIC_TYPES_TEMPLATE(_ICV_DECLARE_TENSOR_DATA);\r\n    #undef _ICV_DECLARE_TENSOR_DATA\r\n\r\n    // Common uses\r\n    typedef icvPrimitiveTensorData<IndexType> icvIndexTensorData;\r\n    typedef icvPrimitiveTensorData<int>       icvIntTensorData;\r\n    typedef icvPrimitiveTensorData<double>    icvDoubleTensorData;\r\n}}\r\n\r\n#endif // icvPrimitiveTensorData_hxx\r\n", "meta": {"hexsha": "25ff18042036e206212ce49c88b3d93be0684ee6", "size": 4387, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "Branch/Include/OpenICV/Basis/icvPrimitiveTensorData.hxx", "max_stars_repo_name": "Tsinghua-OpenICV/OpenICV", "max_stars_repo_head_hexsha": "37bf88122414d0c766491460248f61fa1a9fd78c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-12-17T08:17:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T03:13:10.000Z", "max_issues_repo_path": "Branch/Include/OpenICV/Basis/icvPrimitiveTensorData.hxx", "max_issues_repo_name": "Tsinghua-OpenICV/OpenICV", "max_issues_repo_head_hexsha": "37bf88122414d0c766491460248f61fa1a9fd78c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Branch/Include/OpenICV/Basis/icvPrimitiveTensorData.hxx", "max_forks_repo_name": "Tsinghua-OpenICV/OpenICV", "max_forks_repo_head_hexsha": "37bf88122414d0c766491460248f61fa1a9fd78c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-12-17T08:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T15:53:57.000Z", "avg_line_length": 36.5583333333, "max_line_length": 121, "alphanum_fraction": 0.5910645088, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.5671909123561841}}
{"text": "/*\n(***********************************************************************)\n(*                                                                     *)\n(* The ACME project                                                    *)\n(*                                                                     *)\n(* Copyright (c) 2020-2021, Davide Stocco and Enrico Bertolazzi.       *)\n(*                                                                     *)\n(* The ACME project and its components are supplied under the terms of *)\n(* the open source BSD 2-Clause License. The contents of the ACME      *)\n(* project and its components may not be copied or disclosed except in *)\n(* accordance with the terms of the BSD 2-Clause License.              *)\n(*                                                                     *)\n(* URL: https://opensource.org/licenses/BSD-2-Clause                   *)\n(*                                                                     *)\n(*    Davide Stocco                                                    *)\n(*    Department of Industrial Engineering                             *)\n(*    University of Trento                                             *)\n(*    e-mail: davide.stocco@unitn.it                                   *)\n(*                                                                     *)\n(*    Enrico Bertolazzi                                                *)\n(*    Department of Industrial Engineering                             *)\n(*    University of Trento                                             *)\n(*    e-mail: enrico.bertolazzi@unitn.it                               *)\n(*                                                                     *)\n(***********************************************************************)\n*/\n\n// TEST 8 - POINT/VECTOR TRANSFORMATION\n\n#include <fstream>\n#include <iostream>\n#include <string>\n\n#include <Eigen/Geometry>\n\n#include \"acme.hh\"\n#include \"acme_aabb.hh\"\n#include \"acme_intersection.hh\"\n#include \"acme_triangle.hh\"\n#include \"acme_utils.hh\"\n\nusing namespace acme;\n\n// Main function\nint main()\n{\n  // Initialize point and vector\n  point point_tmp(0.0, 0.0, 1.0);\n  vec3 vector_tmp(0.0, 0.0, 1.0);\n\n  // Initialize rotation matrix\n  affine transformation = translate(0.0, 0.0, -1.0) * angleaxis(PI / 2, UNITX_VEC3);\n\n  // Transform objects\n  point mov_point(point_tmp);\n  vec3 mov_vector(vector_tmp);\n  mov_point.transform(transformation);\n  acme::transform(mov_vector, transformation);\n\n  // Transform objects back\n  point ground_point(mov_point);\n  vec3 ground_vector(mov_vector);\n  ground_point.transform(transformation.inverse());\n  acme::transform(ground_vector, transformation.inverse());\n\n  // Display results\n  std::cout\n      << std::endl\n      << \"TEST 8 - POINT/VECTOR TRANSFORMATION\" << std::endl\n      << std::endl\n      << \"Point  (ground) = \" << point_tmp << std::endl\n      << \"Vector (ground) = \" << vector_tmp << std::endl\n      << std::endl\n      << \"Point  (moving frame) = \" << mov_point << std::endl\n      << \"Vector (moving frame) = \" << mov_vector << std::endl\n      << std::endl\n      << \"Point  (back to ground) = \" << ground_point << std::endl\n      << \"Vector (back to ground) = \" << ground_vector << std::endl\n      << std::endl\n      << \"TEST 8: Completed\" << std::endl;\n\n  // Exit the program\n  return 0;\n}\n", "meta": {"hexsha": "d4a7288d388f1583015b45c2f41ea79ee64b42a0", "size": 3332, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/acme-test8.cc", "max_stars_repo_name": "StoccoDavide/ddd", "max_stars_repo_head_hexsha": "673a96628dc0aa606e86252f1daf4611d9a83486", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-16T09:17:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T09:17:10.000Z", "max_issues_repo_path": "tests/acme-test8.cc", "max_issues_repo_name": "StoccoDavide/ddd", "max_issues_repo_head_hexsha": "673a96628dc0aa606e86252f1daf4611d9a83486", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/acme-test8.cc", "max_forks_repo_name": "StoccoDavide/ddd", "max_forks_repo_head_hexsha": "673a96628dc0aa606e86252f1daf4611d9a83486", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-24T08:06:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-24T08:06:28.000Z", "avg_line_length": 39.2, "max_line_length": 84, "alphanum_fraction": 0.4462785114, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5671909119146739}}
{"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 <boost/test/unit_test.hpp>\n#include <iostream>\n\n#include \"ssmkit/distribution/gaussian.hpp\"\n\n#define STR_EXPAND(tok) #tok\n#define STR(tok) STR_EXPAND(tok)\n\nusing namespace ssmkit;\n\nBOOST_AUTO_TEST_SUITE(distribution_gausian);\n\n// Number of Monte-Carlo runs \nconstexpr int mc_n = 500000;\n\nBOOST_AUTO_TEST_CASE(mc_test_random_default_pdf) {\n  // testing distribution with default constructor\n\n  constexpr int dimension = 8;\n  // 8-dimensional Gaussian distribution with zero mean identity covariance\n  distribution::Gaussian pdf(dimension);\n  \n  // set random seed\n  random::setRandomSeed();\n  \n  // sampling large number of random variables from distribution\n  arma::mat samples(dimension, mc_n);\n  samples.each_col([&pdf](arma::vec &col) { col = pdf.random(); });\n  // Calculating sample mean\n  auto mc_mean = arma::sum(samples, 1) / mc_n;\n  // Calculating sample covariance\n  auto mc_covariance = arma::cov(samples.t());\n\n  // check if sample mean is close to zero\n  BOOST_CHECK(arma::approx_equal(mc_mean, arma::zeros<arma::vec>(dimension),\n                                 \"absdiff\", 0.01));\n  // check if sample covariance is close to identity\n  BOOST_CHECK(arma::approx_equal(mc_covariance,\n                                 arma::eye<arma::mat>(dimension, dimension),\n                                 \"absdiff\", 0.01));\n}\n\nBOOST_AUTO_TEST_CASE(mc_test_random_arbitary_pdf) {\n  // testing distribution with given mean and covariance\n\n  // construction distribution\n  constexpr int dimension = 2;\n  arma::vec mean{89, 16};\n  arma::mat chol{{10, 1}, {0, 2}};\n  arma::mat covariance = chol.t() * chol;\n  distribution::Gaussian pdf(mean, covariance);\n  \n  // set random seed\n  random::setRandomSeed();\n\n  // sampling large number of random variables from distribution\n  arma::mat samples(dimension, mc_n);\n  samples.each_col([&pdf](arma::vec &col) { col = pdf.random(); });\n  // Calculating sample mean\n  auto mc_mean = arma::sum(samples, 1) / mc_n;\n  // Calculating sample covariance\n  auto mc_covariance = arma::cov(samples.t());\n\n  // check if sample mean is close to the given mean\n  BOOST_CHECK(arma::approx_equal(mean, mc_mean, \"absdiff\", 0.1));\n  // check if sample covariance is close to given covariance\n  BOOST_CHECK(arma::approx_equal(covariance, mc_covariance, \"absdiff\", 0.5));\n}\n\nBOOST_AUTO_TEST_CASE(likelihood_test) {\n  // check the likelihood function using precomputed data\n  arma::mat rvs;\n  arma::mat ln;\n  arma::mat ln5;\n  arma::mat lnm;\n  arma::mat lnc;\n\n  BOOST_REQUIRE(rvs.load(STR(SOURCE_DIR) \"/test/data/gaussian/rvs.csv\"));\n  BOOST_REQUIRE(ln.load(STR(SOURCE_DIR) \"/test/data/gaussian/ln.csv\"));\n  BOOST_REQUIRE(ln5.load(STR(SOURCE_DIR) \"/test/data/gaussian/ln5.csv\"));\n  BOOST_REQUIRE(lnm.load(STR(SOURCE_DIR) \"/test/data/gaussian/lnm.csv\"));\n  BOOST_REQUIRE(lnc.load(STR(SOURCE_DIR) \"/test/data/gaussian/lnc.csv\"));\n\n  distribution::Gaussian pdf(3);\n  arma::mat ln_test(size(ln));\n  auto it_ln_test = ln_test.begin();\n  rvs.each_col([&pdf, &it_ln_test](arma::vec &col) {\n    *it_ln_test++ = pdf.likelihood(col);\n  });\n  BOOST_CHECK(arma::approx_equal(ln, ln_test, \"absdiff\", 0.001));\n\n  pdf.parameterize(arma::zeros<arma::vec>(3), arma::eye<arma::mat>(3, 3) * 5.0);\n  arma::mat ln5_test(size(ln5));\n  auto it_ln5_test = ln5_test.begin();\n  rvs.each_col([&pdf, &it_ln5_test](arma::vec &col) {\n    *it_ln5_test++ = pdf.likelihood(col);\n  });\n  BOOST_CHECK(arma::approx_equal(ln5, ln5_test, \"absdiff\", 0.001));\n\n  pdf.parameterize({1, 2, 3}, arma::eye<arma::mat>(3, 3) * 5.0);\n  arma::mat lnm_test(size(lnm));\n  auto it_lnm_test = lnm_test.begin();\n  rvs.each_col([&pdf, &it_lnm_test](arma::vec &col) {\n    *it_lnm_test++ = pdf.likelihood(col);\n  });\n  BOOST_CHECK(arma::approx_equal(lnm, lnm_test, \"absdiff\", 0.001));\n\n  arma::mat chol{{1, 1, 1}, {0, 1, 1}, {0, 0, 1}};\n  arma::mat covariance = chol.t() * chol;\n  pdf.parameterize(arma::zeros<arma::vec>(3), covariance);\n  arma::mat lnc_test(size(lnc));\n  auto it_lnc_test = lnc_test.begin();\n  rvs.each_col([&pdf, &it_lnc_test](arma::vec &col) {\n    *it_lnc_test++ = pdf.likelihood(col);\n  });\n  BOOST_CHECK(arma::approx_equal(lnc, lnc_test, \"absdiff\", 0.001));\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "cc679c969ded404af5896bd73aee2c7a7f5dcc80", "size": 4181, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distribution/gaussian.cpp", "max_stars_repo_name": "vahid-bastani/ssmpack", "max_stars_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-08T09:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-10T06:46:55.000Z", "max_issues_repo_path": "test/distribution/gaussian.cpp", "max_issues_repo_name": "vahidbas/ssmkit", "max_issues_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/distribution/gaussian.cpp", "max_forks_repo_name": "vahidbas/ssmkit", "max_forks_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:46:08.000Z", "avg_line_length": 34.8416666667, "max_line_length": 80, "alphanum_fraction": 0.6845252332, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5671889057468464}}
{"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": "#include \"stdafx.h\"\r\n#include \"qmath.h\"\r\n#include \"config.h\"\r\n\r\n// each test module could contain no more then one 'main' file with init function defined\r\n// alternatively you could define init function yourself\r\n#include <boost/test/unit_test.hpp>\r\n\r\n// These are sample tests that show the different features of the framework\r\n\r\nusing namespace math;\r\n\r\nnamespace {\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(SQRT)\r\n{\r\n\t{\r\n\t\tfloat a = 4.f;\r\n\t\tfloat b = sqrt(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, 2.f));\r\n\t}\r\n\r\n\t{\r\n\t\tdouble a = 4.0;\r\n\t\tdouble b = sqrt(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, 2.0));\r\n\t}\r\n\r\n\t{\r\n\t\tvec2f a(4.f, 16.f);\r\n\t\tvec2f b = sqrt(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, vec2f(2.f, 4.f)));\r\n\t}\r\n\r\n\t{\r\n\t\tvec3f a(4.f, 16.f, 25.f);\r\n\t\tvec3f b = sqrt(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, vec3f(2.f, 4.f, 5.f)));\r\n\t}\r\n\r\n\t{\r\n\t\tvec4f a(4.f, 16.f, 25.f, 36.f);\r\n\t\tvec4f b = sqrt(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, vec4f(2.f, 4.f, 5.f ,6.f)));\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(SQRT_FAST)\r\n{\r\n\t{\r\n\t\tfloat a = 4.f;\r\n\t\tfloat b = sqrt<float, fast>(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, 2.f, 0.005f));\r\n\t}\r\n\r\n\t{\r\n\t\tdouble a = 4.0;\r\n\t\tdouble b = sqrt<double, fast>(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, 2.0, 0.005));\r\n\t}\r\n\r\n\t{\r\n\t\tvec2f a(4.f, 16.f);\r\n\t\tvec2f b = sqrt<float, fast>(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, vec2f(2.f, 4.f), 0.005f));\r\n\t}\r\n\r\n\t{\r\n\t\tvec3f a(4.f, 16.f, 25.f);\r\n\t\tvec3f b = sqrt<float, fast>(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, vec3f(2.f, 4.f, 5.f), 0.005f));\r\n\t}\r\n\r\n\t{\r\n\t\tvec4f a(4.f, 16.f, 25.f, 36.f);\r\n\t\tvec4f b = sqrt<float, fast>(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, vec4f(2.f, 4.f, 5.f ,6.f), 0.005f));\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(INV_SQRT)\r\n{\r\n\t{\r\n\t\tfloat a = 4.f;\r\n\t\tfloat b = inv_sqrt(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, 0.5f));\r\n\t}\r\n\r\n\t{\r\n\t\tdouble a = 4.0;\r\n\t\tdouble b = inv_sqrt(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, 0.5));\r\n\t}\r\n\r\n\t{\r\n\t\tvec2f a(4.f, 16.f);\r\n\t\tvec2f b = inv_sqrt(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, vec2f(0.5f, 0.25f)));\r\n\t}\r\n\r\n\t{\r\n\t\tvec3f a(4.f, 16.f, 25.f);\r\n\t\tvec3f b = inv_sqrt(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, vec3f(0.5f, 0.25f, 0.2f)));\r\n\t}\r\n\r\n\t{\r\n\t\tvec4f a(4.f, 16.f, 25.f, 36.f);\r\n\t\tvec4f b = inv_sqrt(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, vec4f(0.5f, 0.25f, 0.2f, 1.f / 6.f)));\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(INV_SQRT_FAST)\r\n{\r\n\t{\r\n\t\tfloat a = 4.f;\r\n\t\tfloat b = inv_sqrt<float, fast>(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, 0.5f, 0.001f));\r\n\t}\r\n\r\n\t{\r\n\t\tdouble a = 4.0;\r\n\t\tdouble b = inv_sqrt<double, fast>(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, 0.5, 0.001));\r\n\t}\r\n\r\n\t{\r\n\t\tvec2f a(4.f, 16.f);\r\n\t\tvec2f b = inv_sqrt<float, fast>(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, vec2f(0.5f, 0.25f), 0.001f));\r\n\t}\r\n\r\n\t{\r\n\t\tvec3f a(4.f, 16.f, 25.f);\r\n\t\tvec3f b = inv_sqrt<float, fast>(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, vec3f(0.5f, 0.25f, 0.2f), 0.001f));\r\n\t}\r\n\r\n\t{\r\n\t\tvec4f a(4.f, 16.f, 25.f, 36.f);\r\n\t\tvec4f b = inv_sqrt<float, fast>(a);\r\n\r\n\t\tBOOST_CHECK(equals(b, vec4f(0.5f, 0.25f, 0.2f, 1.f / 6.f), 0.001f));\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(POSITIVE_ZERO)\r\n{\r\n\t{\r\n\t\t{\r\n\t\t\tstd::stringstream str;\r\n\t\t\tstr << -0.f;\r\n\t\t\tBOOST_CHECK(str.str() == \"-0\");\r\n\t\t}\r\n\t\t{\r\n\t\t\tstd::stringstream str;\r\n\t\t\tstr << positive_zero(-0.f);\r\n\t\t\tBOOST_CHECK(str.str() == \"0\");\r\n\t\t}\r\n\t\t{\r\n\t\t\tstd::stringstream str;\r\n\t\t\tstr << positive_zero(0.f);\r\n\t\t\tBOOST_CHECK(str.str() == \"0\");\r\n\t\t}\r\n\t\t{\r\n\t\t\tstd::stringstream str;\r\n\t\t\tstr << positive_zero(-7.f);\r\n\t\t\tBOOST_CHECK(str.str() == \"-7\");\r\n\t\t}\r\n\t\t{\r\n\t\t\tstd::stringstream str;\r\n\t\t\tstr << positive_zero(7.f);\r\n\t\t\tBOOST_CHECK(str.str() == \"7\");\r\n\t\t}\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ABS_SGN)\r\n{\r\n\tfloat a = -1.f;\r\n\tfloat b = math::abs(a);\r\n\r\n\tBOOST_CHECK(equals(b, -a));\r\n\tBOOST_CHECK(sgn(a) == a);\r\n\tBOOST_CHECK(sgn(b) == b);\r\n\r\n\tdouble c = -12123412.187246;\r\n\tdouble d = abs(c);\r\n\r\n\tBOOST_CHECK(equals(d, -c));\r\n\tBOOST_CHECK(sgn(d) == 1);\r\n\tBOOST_CHECK(sgn(c) == -1);\r\n\r\n\tint e = -10;\r\n\tint f = abs(e);\r\n\r\n\tBOOST_CHECK(equals(f, -e));\r\n\tBOOST_CHECK(sgn(e) == -1);\r\n\tBOOST_CHECK(sgn(f) == 1);\r\n\r\n\tint64_t g = -129381094710288L;\r\n\tint64_t h = math::abs(g);\r\n\r\n\tBOOST_CHECK(equals(h, -g));\r\n\tBOOST_CHECK(sgn(g) == -1);\r\n\tBOOST_CHECK(sgn(h) == 1);\r\n\r\n\tvec2f a2(0.f, -1.f);\r\n\tvec2f b2 = abs(a2);\r\n\r\n\tBOOST_CHECK(equals(b2, -a2));\r\n\tBOOST_CHECK(sgn(a2) == a2);\r\n\tBOOST_CHECK(sgn(b2) == b2);\r\n\r\n\tvec3f a3(0.f, -1.f, -1.f);\r\n\tvec3f b3 = abs(a3);\r\n\r\n\tBOOST_CHECK(equals(b3, -a3));\r\n\tBOOST_CHECK(sgn(a3) == a3);\r\n\tBOOST_CHECK(sgn(b3) == b3);\r\n\r\n\tvec4f a4(0.f, -1.f, 0.0f, -1.f);\r\n\tvec4f b4 = abs(a4);\r\n\r\n\tBOOST_CHECK(equals(b4, -a4));\r\n\tBOOST_CHECK(sgn(a4) == a4);\r\n\tBOOST_CHECK(sgn(b4) == b4);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(INVERSE_TRANSPOSE)\r\n{\r\n\t{\r\n\t\tfloat a = 10.f;\r\n\t\tfloat b = inverse(a);\r\n\t\tBOOST_CHECK(equals(b, 0.1f, math::epsilon<float>()));\r\n\t}\r\n\r\n\t{\r\n\t\tdouble a = 10.f;\r\n\t\tdouble b = inverse(a);\r\n\t\tdouble c = 0.1;\r\n\t\tBOOST_CHECK(equals(b, c));\r\n\t}\r\n\t\r\n\t{\r\n\t\tmat3f a;\r\n\t\ta.set_row(0, vec3f(1.f, 1.f, 1.f));\r\n\t\ta.set_row(1, vec3f(2.f, 3.f, 2.f));\r\n\t\ta.set_row(2, vec3f(4.f, 5.f, 6.f));\r\n\r\n\t\tmat3f b = inverse(a);\r\n\t\t\r\n\t\tBOOST_CHECK(equals(b.get_row(0), vec3f(4.f, -0.5f, -0.5f), math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(b.get_row(1), vec3f(-2.f, 1.f, 0.f), math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(b.get_row(2), vec3f(-1.f, -0.5f, 0.5f), math::epsilon<float>()));\r\n\r\n\t\tmat3f c = transposed(a);\r\n\r\n\t\tBOOST_CHECK(equals(c.get_row(0), vec3f(1.f, 2.f, 4.f), math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(c.get_row(1), vec3f(1.f, 3.f, 5.f), math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(c.get_row(2), vec3f(1.f, 2.f, 6.f), math::epsilon<float>()));\r\n\r\n\t}\r\n\r\n\t{\r\n\t\tmat4f a;\r\n\t\ta.set_row(0, vec4f(1.f, 2.f, 2.f, 1.f));\r\n\t\ta.set_row(1, vec4f(2.f, 1.f, 2.f, 1.f));\r\n\t\ta.set_row(2, vec4f(2.f, 2.f, 1.f, 2.f));\r\n\t\ta.set_row(3, vec4f(1.f, 1.f, 2.f, 1.f));\r\n\r\n\t\tmat4f b = inverse(a);\r\n\r\n\t\tBOOST_CHECK(equals(b.get_row(0), vec4f(0.f, 1.f, 0.f, -1.f), math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(b.get_row(1), vec4f(1.f, 0.f, 0.f, -1.f), math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(b.get_row(2), vec4f(0.f, 0.f, -0.33333333f, 0.66666666f), math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(b.get_row(3), vec4f(-1.f, -1.f, 0.66666666f, 1.66666666f), math::epsilon<float>()));\r\n\r\n\t\tmat4f c = transposed(a);\r\n\r\n\t\tBOOST_CHECK(equals(c.get_row(0), vec4f(1.f, 2.f, 2.f, 1.f), math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(c.get_row(1), vec4f(2.f, 1.f, 2.f, 1.f), math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(c.get_row(2), vec4f(2.f, 2.f, 1.f, 2.f), math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(c.get_row(3), vec4f(1.f, 1.f, 2.f, 1.f), math::epsilon<float>()));\r\n\t}\r\n\r\n\t{\r\n\t\tquatf a(0,1,1,1);\r\n\t\tquatf b = inverse(a);\r\n\t\tquatf c(0,-1,-1,1);\r\n\t\tBOOST_CHECK(equals(b, c));\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(NORMALIZE)\r\n{\r\n\t{\r\n\t\t vec2f c(3.f, 4.f);\r\n\t\t vec2f d = normalized(c);\r\n\t\t BOOST_CHECK(equals(d, vec2f(0.6f, 0.8f)));\r\n\t}\r\n\t{\r\n\t\t vec3f c(0.f, 3.f, 4.f);\r\n\t\t vec3f d = normalized(c);\r\n\t\t BOOST_CHECK(equals(d, vec3f(0.0f, 0.6f, 0.8f)));\r\n\t}\r\n\t{\r\n\t\t vec4f c(0.f, 3.f, 4.f, 0.f);\r\n\t\t vec4f d = normalized(c);\r\n\t\t BOOST_CHECK(equals(d, vec4f(0.0f, 0.6f, 0.8f, 0.0f)));\r\n\t}\r\n\t{\r\n\t\t quatf a;\r\n\t\t quatf b = normalized(a);\r\n\t\t BOOST_CHECK(equals(b, quatf()));\r\n\r\n\t\t //quatf c(kPI, kPI, kPI, 1.f);\r\n\t\t //quatf d = normalized(c);\r\n\t\t //BOOST_CHECK(equals(d, quatf()));\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(NORMALIZE_FAST)\r\n{\r\n\t{\r\n// \t\tvec2f a;\r\n// \t\tvec2f b = normalized<float, fast>(a);\r\n// \t\tBOOST_CHECK(equals(b, vec2f(), 0.001f));\r\n\r\n\t\tvec2f c(3.f, 4.f);\r\n\t\tvec2f d = normalized<float, fast>(c);\r\n\t\tBOOST_CHECK(equals(d, vec2f(0.6f, 0.8f), 0.005f));\r\n\t}\r\n\t{\r\n\t\tvec3f c(0.f, 3.f, 4.f);\r\n\t\tvec3f d = normalized<float, fast>(c);\r\n\t\tBOOST_CHECK(equals(d, vec3f(0.0f, 0.6f, 0.8f), 0.005f));\r\n\t}\r\n\t{\r\n\t\tvec4f c(0.f, 3.f, 4.f, 0.f);\r\n\t\tvec4f d = normalized<float, fast>(c);\r\n\t\tBOOST_CHECK(equals(d, vec4f(0.0f, 0.6f, 0.8f, 0.0f), 0.005f));\r\n\t}\r\n\t{\r\n\t\tquatf a;\r\n\t\tquatf b = normalized<float, fast>(a);\r\n\t\tBOOST_CHECK(equals(b, quatf(), 0.005f));\r\n\r\n\t\t//quatf c(kPI, kPI, kPI, 1.f);\r\n\t\t//quatf d = normalized(c);\r\n\t\t//BOOST_CHECK(equals(d, quatf()));\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(DOT)\r\n{\r\n\t{\r\n\t\t vec2f a(1.f, 2.f);\r\n\t\t vec2f b(3.f, 4.f); \r\n\t\t float c = dot(a, b);\r\n\t\t BOOST_CHECK(equals(c, 11.f));\r\n\t}\r\n\t{\r\n\t\t vec3f a(1.f, 2.f, 3.f);\r\n\t\t vec3f b(4.f, 5.f, 6.f);\r\n\t\t float c = dot(a, b);\r\n\t\t BOOST_CHECK(equals(c, 32.f));\r\n\t}\r\n\t{\r\n\t\t vec4f a(1.f, 2.f, 3.f, 4.f);\r\n\t\t vec4f b(5.f, 6.f, 7.f, 8.f);\r\n\t\t float c = dot(a, b);\r\n\t\t BOOST_CHECK(equals(c, 70.f));\r\n\t}\t\r\n}\r\nBOOST_AUTO_TEST_CASE(CROSS)\r\n{\r\n\t{\r\n\t\t vec2f a;\r\n\t\t vec2f b;\r\n\t\t float c = cross(a, b);\r\n\t\t BOOST_CHECK(equals(c, 0.f));\r\n\t}\r\n\t{\r\n\t\t vec3f a;\r\n\t\t vec3f b;\r\n\t\t vec3f c = cross(a, b);\r\n\t\t BOOST_CHECK(equals(b, vec3f()));\r\n\t}\r\n\t{\r\n\t\t vec4f a;\r\n\t\t vec4f b;\r\n\t\t vec4f c; \r\n\t\t vec4f d = cross(a, b, c);\r\n\t\t BOOST_CHECK(equals(d, vec4f()));\r\n\t}\t\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(DISTANCE)\r\n{\r\n\t{\r\n\t\t vec2f a;\r\n\t\t vec2f b;\r\n\t\t float c = distance(a, b);\r\n\t\t float d = distance_sq(a, b);\r\n\t\t BOOST_CHECK(equals(c, 0.f, math::epsilon<float>()));\r\n\t\t BOOST_CHECK(equals(d, 0.f, math::epsilon<float>()));\r\n\t}\r\n\t{\r\n\t\tvec2f a(0.32f, 0);\r\n\t\tvec2f b(0, 0.12f);\r\n\t\tfloat c = distance(a, b);\r\n\t\tfloat d = distance_sq(a, b);\r\n\t\tBOOST_CHECK(equals(c, 0.341760129f, math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(d, 0.116799995f, math::epsilon<float>()));\r\n\t}\r\n\t{\r\n\t\t vec3f a;\r\n\t\t vec3f b;\r\n\t\t float c = distance(a, b);\r\n\t\t float d = distance_sq(a, b);\r\n\t\t BOOST_CHECK(equals(c, 0.f, math::epsilon<float>()));\r\n\t\t BOOST_CHECK(equals(d, 0.f, math::epsilon<float>()));\r\n\t}\r\n\t{\r\n\t\tvec3f a(0.32f, 0, 0);\r\n\t\tvec3f b(0, 0.12f, 0);\r\n\t\tfloat c = distance(a, b);\r\n\t\tfloat d = distance_sq(a, b);\r\n\t\tBOOST_CHECK(equals(c, 0.341760129f, math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(d, 0.116799995f, math::epsilon<float>()));\r\n\t}\r\n\t{\r\n\t\t vec4f a;\r\n\t\t vec4f b;\r\n\t\t float c = distance(a, b);\r\n\t\t float d = distance_sq(a, b);\r\n\t\t BOOST_CHECK(equals(c, 0.f, math::epsilon<float>()));\r\n\t\t BOOST_CHECK(equals(d, 0.f, math::epsilon<float>()));\r\n\t}\r\n\t{\r\n\t\tvec4f a(0.32f, 0, 0, 0);\r\n\t\tvec4f b(0, 0.12f, 0, 0);\r\n\t\tfloat c = distance(a, b);\r\n\t\tfloat d = distance_sq(a, b);\r\n\t\tBOOST_CHECK(equals(c, 0.341760129f, math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(d, 0.116799995f, math::epsilon<float>()));\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(LENGTH)\r\n{\r\n\t{\r\n\t\tvec2f a;\r\n\t\tfloat c = length(a);\r\n\t\tfloat d = length_sq(a);\r\n\t\tBOOST_CHECK(equals(c, 0.f, math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(d, 0.f, math::epsilon<float>()));\r\n\t}\r\n\t{\r\n\t\tvec2f a(0.32f, 0);\r\n\t\tfloat c = length(a);\r\n\t\tfloat d = length_sq(a);\r\n\t\tBOOST_CHECK(equals(c, 0.32f, math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(d, 0.1024f, math::epsilon<float>()));\r\n\t}\r\n\t{\r\n\t\tvec3f a;\r\n\t\tfloat c = length(a);\r\n\t\tfloat d = length_sq(a);\r\n\t\tBOOST_CHECK(equals(c, 0.f, math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(d, 0.f, math::epsilon<float>()));\r\n\t}\r\n\t{\r\n\t\tvec3f a(0.32f, 0, 0);\r\n\t\tfloat c = length(a);\r\n\t\tfloat d = length_sq(a);\r\n\t\tBOOST_CHECK(equals(c, 0.32f, math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(d, 0.1024f, math::epsilon<float>()));\r\n\t}\r\n\t{\r\n\t\tvec4f a;\r\n\t\tfloat c = length(a);\r\n\t\tfloat d = length_sq(a);\r\n\t\tBOOST_CHECK(equals(c, 0.f, math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(d, 0.f, math::epsilon<float>()));\r\n\t}\r\n\t{\r\n\t\tvec4f a(0.32f, 0, 0, 0);\r\n\t\tfloat c = length(a);\r\n\t\tfloat d = length_sq(a);\r\n\t\tBOOST_CHECK(equals(c, 0.32f, math::epsilon<float>()));\r\n\t\tBOOST_CHECK(equals(d, 0.1024f, math::epsilon<float>()));\r\n\t}\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(DISTANCE_FAST)\r\n{\r\n\t{\r\n\t\tvec2f a;\r\n\t\tvec2f b;\r\n\t\tfloat c = distance<float, fast>(a, b);\r\n\t\tBOOST_CHECK(equals(c, 0.f, 0.005f));\r\n\t}\r\n\t{\r\n\t\tvec2f a(0.32f, 0);\r\n\t\tvec2f b(0, 0.12f);\r\n\t\tfloat c = distance<float, fast>(a, b);\r\n\t\tBOOST_CHECK(equals(c, 0.341760129f, 0.005f));\r\n\t}\r\n\t{\r\n\t\tvec3f a;\r\n\t\tvec3f b;\r\n\t\tfloat c = distance<float, fast>(a, b);\r\n\t\tBOOST_CHECK(equals(c, 0.f, 0.005f));\r\n\t}\r\n\t{\r\n\t\tvec3f a(0.32f, 0, 0);\r\n\t\tvec3f b(0, 0.12f, 0);\r\n\t\tfloat c = distance<float, fast>(a, b);\r\n\t\tBOOST_CHECK(equals(c, 0.341760129f, 0.005f));\r\n\t}\r\n\t{\r\n\t\tvec4f a;\r\n\t\tvec4f b;\r\n\t\tfloat c = distance<float, fast>(a, b);\r\n\t\tBOOST_CHECK(equals(c, 0.f, 0.005f));\r\n\t}\r\n\t{\r\n\t\tvec4f a(0.32f, 0, 0, 0);\r\n\t\tvec4f b(0, 0.12f, 0, 0);\r\n\t\tfloat c = distance<float, fast>(a, b);\r\n\t\tBOOST_CHECK(equals(c, 0.341760129f, 0.005f));\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(LENGTH_FAST)\r\n{\r\n\t{\r\n\t\tvec2f a;\r\n\t\tfloat c = length<float, fast>(a);\r\n\t\tBOOST_CHECK(equals(c, 0.f, 0.005f));\r\n\t}\r\n\t{\r\n\t\tvec2f a(0.32f, 0);\r\n\t\tfloat c = length<float, fast>(a);\r\n\t\tBOOST_CHECK(equals(c, 0.32f, 0.005f));\r\n\t}\r\n\t{\r\n\t\tvec3f a;\r\n\t\tfloat c = length<float, fast>(a);\r\n\t\tBOOST_CHECK(equals(c, 0.f, 0.005f));\r\n\t}\r\n\t{\r\n\t\tvec3f a(0.32f, 0, 0);\r\n\t\tfloat c = length<float, fast>(a);\r\n\t\tBOOST_CHECK(equals(c, 0.32f, 0.005f));\r\n\t}\r\n\t{\r\n\t\tvec4f a;\r\n\t\tfloat c = length<float, fast>(a);\r\n\t\tBOOST_CHECK(equals(c, 0.f, 0.005f));\r\n\t}\r\n\t{\r\n\t\tvec4f a(0.32f, 0, 0, 0);\r\n\t\tfloat c = length<float, fast>(a);\r\n\t\tBOOST_CHECK(equals(c, 0.32f, 0.005f));\r\n\t}\r\n}\r\n\r\n\r\n}\r\n", "meta": {"hexsha": "611ee8f42ccf1aef22dae7cd982e5ac9f9075c06", "size": 12765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qmath/test/test_func_common.cpp", "max_stars_repo_name": "jeanleflambeur/silkopter", "max_stars_repo_head_hexsha": "cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T16:47:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T08:32:04.000Z", "max_issues_repo_path": "qmath/test/test_func_common.cpp", "max_issues_repo_name": "jeanlemotan/silkopter", "max_issues_repo_head_hexsha": "cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 42.0, "max_issues_repo_issues_event_min_datetime": "2017-02-11T11:15:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T16:00:44.000Z", "max_forks_repo_path": "qmath/test/test_func_common.cpp", "max_forks_repo_name": "jeanleflambeur/silkopter", "max_forks_repo_head_hexsha": "cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-10-15T05:46:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-11T17:40:36.000Z", "avg_line_length": 21.3105175292, "max_line_length": 106, "alphanum_fraction": 0.5602036819, "num_tokens": 5024, "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": "#include <random>\n#include <map>\n#include <tuple>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <gtest/gtest.h>\n#include <mpi.h>\n\n#include \"tasktorrent/tasktorrent.hpp\"\n\nusing namespace std;\nusing namespace ttor;\nusing namespace Eigen;\n\ntypedef SparseMatrix<double> SpMat;\n\nint VERB = 0;\n\nSpMat random_SpMat(int n, double p, int seed)\n{\n    default_random_engine gen;\n    gen.seed(seed);\n    uniform_real_distribution<double> dist(0.0, 1.0);\n    vector<Triplet<double>> triplets;\n    for (int i = 0; i < n; ++i)\n    {\n        for (int j = 0; j < n; ++j)\n        {\n            auto v_ij = dist(gen);\n            if (v_ij < p)\n            {\n                triplets.push_back(Triplet<double>(i, j, v_ij));\n            }\n        }\n    }\n    SpMat A(n, n);\n    A.setFromTriplets(triplets.begin(), triplets.end());\n    return A;\n}\n\nPermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> random_perm(int n, int seed)\n{\n    PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> perm(n);\n    perm.setIdentity();\n    default_random_engine gen;\n    gen.seed(seed);\n    std::shuffle(perm.indices().data(), perm.indices().data() + perm.indices().size(), gen);\n    return perm;\n}\n\nSpMat random_dag(int n, double p, int seed)\n{\n    SpMat A = random_SpMat(n, p, seed).triangularView<StrictlyLower>();\n    auto P = random_perm(n, seed);\n    return P.transpose() * A * P;\n}\n\nvoid test(int n_threads, int n, double p) {\n\n    // Create a random dag\n    SpMat G = random_dag(n, p, n * p + 2020);\n\n    const int rank = comm_rank();\n    const int n_ranks = comm_size();\n    default_random_engine gen;\n    gen.seed(n * p + 2021);\n\n    // Assign tasks to ranks\n    vector<int> task_2_rank(n, 0);\n    std::uniform_int_distribution<> dist1(0, n_ranks-1);\n    for(int i = 0; i < n; i++) task_2_rank[i] = dist1(gen);\n \n    // Decide if header or header+body\n    vector<int> msg_kind(n, 0);\n    std::uniform_int_distribution<> dist2(0, 1);\n    for(int i = 0; i < n; i++) msg_kind[i] = dist2(gen);\n\n    // Count in_deps\n    vector<int> in_degree(n, 0);\n    for (int k = 0; k < G.outerSize(); ++k) {\n        for (SpMat::InnerIterator it(G, k); it; ++it) {\n            in_degree[it.row()]++;\n        }\n    }\n\n    Communicator comm(MPI_COMM_WORLD, VERB);\n    Threadpool tp(n_threads, &comm, VERB);\n    Taskflow<int> tf(&tp, VERB);\n\n    vector<int> buff_recv(n, 0);\n    vector<int> task_ran(n, 0);\n    vector<int> large_order_check(n * n, 0);\n\n    auto am = comm.make_large_active_msg(\n                [&](int& source, int& dest) {\n                    EXPECT_NE(task_2_rank.at(source), rank);\n                    EXPECT_EQ(task_2_rank.at(dest), rank);\n                    EXPECT_EQ(large_order_check.at(source * n + dest), 1);\n                    tf.fulfill_promise(dest);\n                },\n                [&](int& source, int& dest) {\n                    EXPECT_NE(task_2_rank.at(source), rank);\n                    EXPECT_EQ(task_2_rank.at(dest), rank);\n                    EXPECT_EQ(large_order_check.at(source * n + dest), 0);\n                    large_order_check[source * n + dest] = 1;\n                    return &buff_recv[source]; // We're receiving 0 elements\n                },\n                [&](int& source, int& dest){\n                    EXPECT_EQ(task_2_rank.at(source), rank);\n                    EXPECT_NE(task_2_rank.at(dest), rank);\n                });\n\n    auto am_large = comm.make_active_msg(\n                [&](int& source, int& dest) {\n                    EXPECT_NE(task_2_rank.at(source), rank);\n                    EXPECT_EQ(task_2_rank.at(dest), rank);\n                    tf.fulfill_promise(dest);\n                });\n\n    tf.set_mapping([&](int k) {\n        EXPECT_EQ(task_2_rank.at(k), rank);\n        return (k % n_threads);\n    })\n    .set_indegree([&](int k) {\n        EXPECT_EQ(task_2_rank.at(k), rank);\n        return std::max(1, in_degree[k]);\n    })\n    .set_task([&](int k) {\n        EXPECT_EQ(task_2_rank.at(k), rank);\n        EXPECT_EQ(task_ran[k], 0);\n        task_ran[k] ++;\n        for (SpMat::InnerIterator it(G, k); it; ++it)\n        {\n            int other = it.row();\n            int dest = task_2_rank.at(other);\n            if(dest == rank) {\n                tf.fulfill_promise(other);\n            } else {\n                if(msg_kind.at(k) == 0) {\n                    am->send(dest, k, other);\n                } else {\n                    auto v = view<int>();\n                    am_large->send_large(dest, v, k, other);\n                }\n            }\n        }\n    });\n\n    for (int i = 0; i < n; i++) {\n        if(in_degree[i] == 0 && task_2_rank.at(i) == rank) {\n            tf.fulfill_promise(i);\n        }\n    }\n\n    tp.join();\n\n    MPI_Barrier(MPI_COMM_WORLD);\n\n    for (int i = 0; i < n; i++) {\n        if(task_2_rank.at(i) == rank) {\n            EXPECT_EQ(task_ran[i], 1);\n        }\n    }\n}\n\nclass DagProblemTest : public ::testing::Test, public ::testing::WithParamInterface<tuple<int, int, double>> {};\n\nTEST_P(DagProblemTest, MixedTwoSteps) {\n    int n_threads;\n    int n;\n    double p;\n    std::tie(n_threads, n, p) = GetParam();\n    test(n_threads, n, p);\n}\n\nINSTANTIATE_TEST_SUITE_P(\n    DagProblem, DagProblemTest,\n    ::testing::Combine(\n        ::testing::Values(1, 2, 4),\n        ::testing::Values(1, 3, 5, 7, 9, 15, 20, 100, 1000),\n        ::testing::Values(0.0, 0.001, 0.01, 0.1, 0.2)\n    )\n);\n\nint main(int argc, char **argv)\n{\n    ::testing::InitGoogleTest(&argc, argv);\n\n    int req = MPI_THREAD_FUNNELED;\n    int prov = -1;\n\n    MPI_Init_thread(NULL, NULL, req, &prov);\n\n    assert(prov == req);\n\n    if (argc >= 2)\n    {\n        VERB = atoi(argv[1]);\n    }\n\n    if (VERB > 0)\n        printf(\"VERB = %d\\n\", VERB);\n\n    const int return_flag = RUN_ALL_TESTS();\n\n    MPI_Finalize();\n\n    return return_flag;\n}\n", "meta": {"hexsha": "5ea117299093b2b1b5133c6fef18f3e71c7aa685", "size": 5754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/mpi/random_graph_test.cpp", "max_stars_repo_name": "qyz96/tasktorrent", "max_stars_repo_head_hexsha": "4418d83da7de657363ac99ee263602794a0b97a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2019-09-29T19:33:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:48:40.000Z", "max_issues_repo_path": "tests/mpi/random_graph_test.cpp", "max_issues_repo_name": "qyz96/tasktorrent", "max_issues_repo_head_hexsha": "4418d83da7de657363ac99ee263602794a0b97a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-11T18:14:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T22:32:56.000Z", "max_forks_repo_path": "tests/mpi/random_graph_test.cpp", "max_forks_repo_name": "qyz96/tasktorrent", "max_forks_repo_head_hexsha": "4418d83da7de657363ac99ee263602794a0b97a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-10-22T06:40:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T08:17:39.000Z", "avg_line_length": 27.4, "max_line_length": 112, "alphanum_fraction": 0.5359749739, "num_tokens": 1580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5671889006070784}}
{"text": "#define CATCH_CONFIG_ENABLE_BENCHMARKING\n#include \"catch.hpp\"\n\n#include <BoostUnitDefinitions/Units.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/type_traits/function_traits.hpp>\n\n#include <libUncertainty/correlation.hpp>\n#include <libUncertainty/propagate.hpp>\n#include <libUncertainty/uncertain.hpp>\n#include <libUncertainty/utils.hpp>\n// clang-format off\n#include <uncertainties/ureal.hpp>\n#include <uncertainties/impl.hpp>\n#include <uncertainties/io.hpp>\n#include <uncertainties/math.hpp>\n// clang-format on\n/**\n * This file is used for developement. As new classes are created, small tests\n * are written here so that we can try to compile and use them.\n */\n\nusing namespace boost::units;\nusing namespace libUncertainty;\n\nTEST_CASE(\"Memory Usage\")\n{\n  CHECK( sizeof( uncertain<double> ) == 2*sizeof(double) );\n  CHECK( sizeof( add_id<uncertain<double>> ) == 2*sizeof(double)+sizeof(size_t) );\n  CHECK( sizeof( uncertainties::udouble ) > sizeof(uncertain<double>));\n  CHECK( sizeof( uncertainties::udouble ) > sizeof(add_id<uncertain<double>>));\n}\n\nTEST_CASE(\"Bencharmks\", \"[.][benchmarks]\")\n{\n  SECTION(\"Error Propagation\")\n  {\n    auto              f = [](double x, double y, double z) { return sin(x) * cos(y) * tan(z); };\n    uncertain<double> x(M_PI / 2, 0.01), y(M_PI, 0.01), z(M_PI / 4, 0.01);\n    BENCHMARK(\"Normal Call\")\n    {\n      return f(x.nominal(), y.nominal(), z.nominal());\n    };\n    BENCHMARK(\"Error Propagation w/o Correlations\")\n    {\n      return basic_error_propagator::propagate_error(f, x, y, z);\n    };\n\n    auto u = basic_error_propagator::propagate_error(f, x, y, z);\n    CHECK(u.nominal() == Approx(-1));\n    CHECK(u.uncertainty() == Approx(0.0202028));\n  }\n\n  SECTION(\"uncertainties-cpp comparison\")\n  {\n    SECTION(\"uncertainties-cpp calculations\")\n    {\n      uncertainties::udouble alpha(0.200, 0.003), gamma(0.100, 0.001);\n      BENCHMARK(\"Solid angle\")\n      {\n        return 2 * M_PI * (1 - uncertainties::cos(alpha / 2));\n      };\n      uncertainties::udouble Omega = 2 * M_PI * (1 - uncertainties::cos(alpha / 2));\n      std::stringstream      out;\n      out << Omega;\n\n      CHECK(out.str() == \"(3.14 \u00b1 0.09)e-2\");\n    }\n    SECTION(\"libUncertainty calculations\")\n    {\n      uncertain<double> alpha(.200, 0.003), gamma(0.100, 0.001);\n      BENCHMARK(\"Solid angle\")\n      {\n        return basic_error_propagator::propagate_error([](double alpha) { return 2 * M_PI * (1 - cos(alpha / 2)); }, alpha);\n      };\n      auto              Omega = basic_error_propagator::propagate_error([](double alpha) { return 2 * M_PI * (1 - cos(alpha / 2)); }, alpha);\n      std::stringstream out;\n      out << Omega;\n      CHECK(out.str() == \"0.0313898 +/- 0.000947941\");\n      out.str(\"\");\n      out << Omega.normalize();\n      CHECK(out.str() == \"0.0314 +/- 0.0009\");\n    }\n  }\n}\n", "meta": {"hexsha": "b4ba861064c7a5c971fcae53da66a63d2ded5677", "size": 2824, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/CatchTests/benchmarks.cpp", "max_stars_repo_name": "CD3/libUncertainty", "max_stars_repo_head_hexsha": "b7220cf1ae56032cdc806be41daca2fe1ab43dcb", "max_stars_repo_licenses": ["MIT"], "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/CatchTests/benchmarks.cpp", "max_issues_repo_name": "CD3/libUncertainty", "max_issues_repo_head_hexsha": "b7220cf1ae56032cdc806be41daca2fe1ab43dcb", "max_issues_repo_licenses": ["MIT"], "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/CatchTests/benchmarks.cpp", "max_forks_repo_name": "CD3/libUncertainty", "max_forks_repo_head_hexsha": "b7220cf1ae56032cdc806be41daca2fe1ab43dcb", "max_forks_repo_licenses": ["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.8372093023, "max_line_length": 141, "alphanum_fraction": 0.6377478754, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5671889006070784}}
{"text": "#include <iostream>\r\n#include <fstream>\r\n\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n\r\n#define USE_PERIODIC_FFT\r\n#include <imgproc/derivative_gradient.hpp>\r\n#include <imgproc/susan.hpp>\r\n#include <imgproc/rcmg.hpp>\r\n#include <imgproc/quadratureG2.hpp>\r\n#include <imgproc/quadratureS.hpp>\r\n#include <imgproc/quadratureSF.hpp>\r\n#include <imgproc/quadratureLGF.hpp>\r\n#include <imgproc/pc_sqf.hpp>\r\n#include <imgproc/pc_lgf.hpp>\r\n#include <imgproc/pc_matlab.hpp>\r\n#include <imgproc/laplace.hpp>\r\n#include <imgproc/image_operator.hpp>\r\n#include <utility/matlab_helpers.hpp>\r\n\r\n#include <boost/filesystem.hpp>\r\n#include <boost/algorithm/string.hpp>  \r\n#include <boost/format.hpp>\r\n\r\nusing namespace lsfm;\r\nusing namespace std;\r\nnamespace fs = boost::filesystem;\r\n\r\nconstexpr int runs = 1;\r\n\r\nconstexpr int ENTRY_SQR = 1;\r\nconstexpr int ENTRY_RGB = 2; \r\nconstexpr int ENTRY_NO_3 = 4;\r\nconstexpr int ENTRY_NO_5 = 8;\r\n\r\ntypedef double FT;\r\n\r\nconstexpr FT mag_th = static_cast<FT>(0.05);\r\n\r\nstruct Entry {\r\n    Entry() {}\r\n\r\n    Entry(const cv::Ptr<QuadratureI<uchar, double, double, double, double>>& fi, const cv::Ptr<QuadratureI<uchar, double, double, double, double>>& g, const cv::Ptr<QuadratureI<uchar, double, double, double, double>>& f, const std::string& b)\r\n        : filter(fi), gt(g), ft(f), name(b) {}\r\n   \r\n    \r\n    cv::Ptr<QuadratureI<uchar, double, double, double, double>> filter, gt, ft;\r\n    std::string name;\r\n\r\n    inline double phaseError(const cv::Mat src) {\r\n        filter->process(src);\r\n        ft->process(src);\r\n        cv::Mat p = filter->phase().clone();\r\n        p.setTo(0, ft->energy() < ft->energyThreshold(0.05));\r\n        //showMat(\"phase org\", abs(p));\r\n        gt->process(src);\r\n        cv::Mat pgt = gt->phase().clone();\r\n        pgt.setTo(0, ft->energy() < ft->energyThreshold(0.05));\r\n        //showMat(\"phase diff\", abs(p - pgt));\r\n        //cvWaitKey();\r\n        return sum(abs(p - pgt))[0] / p.size().area();\r\n    }\r\n\r\n};\r\n\r\nvoid parseFolder(const fs::path &folder, std::vector<fs::path> &files) {\r\n    fs::directory_iterator end_iter;\r\n    for_each(fs::directory_iterator(folder), fs::directory_iterator(), [&files](const fs::path& file) {\r\n        if (fs::is_regular_file(file))\r\n        {\r\n            std::string ext = file.extension().generic_string();\r\n            boost::algorithm::to_lower(ext);\r\n            if (ext == \".jpg\" || ext == \".png\") {\r\n                files.push_back(file);\r\n            }\r\n        }\r\n        if (fs::is_directory(file))\r\n            parseFolder(file, files);\r\n    });\r\n}\r\n\r\ndouble processError(Entry &e, const fs::path& path) {\r\n    std::cout << \"processing \" << e.name << \"...\";\r\n    std::vector<fs::path> files;\r\n    parseFolder(path, files);\r\n\r\n    double ret = 0;\r\n    int count = 0;\r\n    std::for_each(files.begin(), files.end(), [&](const fs::path& file) {\r\n        \r\n        cv::Mat src = cv::imread(file.generic_string());\r\n        cv::cvtColor(src, src, CV_BGR2GRAY);\r\n        if (src.empty())\r\n        {\r\n            cout << \"Can not open \" << file.generic_string() << endl;\r\n            return;\r\n        }\r\n        \r\n        ret += e.phaseError(src);\r\n        ++count;\r\n        \r\n    });\r\n    ret /= count;\r\n    std::cout << ret << std::endl;\r\n    return ret;\r\n}\r\n\r\nint main(int argc, char** argv)\r\n{  \r\n    fs::path path = \"../../images/MDB/MiddEval3-Q\";\r\n\r\n    cv::Ptr<QuadratureI<uchar, double, double, double, double>> gt(new QuadratureSF<uchar, FT>(1, 2, 1.2));\r\n    cv::Ptr<QuadratureI<uchar, double, double, double, double>> ft(new QuadratureS<uchar, FT, FT>(1, 2, 3, 1.2));\r\n        \r\n    std::vector<Entry> filter;\r\n   \r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 3, 1.2), gt, ft, \"SQF Po (3x3)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 5, 1.2), gt, ft, \"SQF Po (5x5)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 7, 1.2), gt, ft, \"SQF Po (7x7)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 9, 1.2), gt, ft, \"SQF Po (9x9)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 11, 1.2), gt, ft, \"SQF Po (11x11)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 13, 1.2), gt, ft, \"SQF Po (13x13)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 15, 1.2), gt, ft, \"SQF Po (15x15)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 17, 1.2), gt, ft, \"SQF Po (17x17)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 19, 1.2), gt, ft, \"SQF Po (19x19)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 31, 1.2), gt, ft, \"SQF Po (31x31)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 63, 1.2), gt, ft, \"SQF Po (63x63)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 127, 1.2), gt, ft, \"SQF Po (127x127)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 255, 1.2), gt, ft, \"SQF Po (255x255)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 511, 1.2), gt, ft, \"SQF Po (511x511)\"));\r\n    filter.push_back(Entry(new QuadratureS<uchar, FT, FT>(1, 2, 749, 1.2), gt, ft, \"SQF Po (749x749)\"));\r\n    \r\n    \r\n    int rows = filter.size() + 1;\r\n    int cols = 2;\r\n    std::vector<std::vector<std::string>> table;\r\n    table.resize(rows);\r\n    for_each(table.begin(), table.end(), [&](std::vector<std::string> &col) {\r\n        col.resize(cols);\r\n    });\r\n\r\n    table[0][0] = \"Method\";\r\n    table[0][1] = \"Error\";\r\n    \r\n    int row = 1;\r\n    for_each(filter.begin(), filter.end(), [&](Entry &e) {\r\n        table[row++][0] = e.name;\r\n    });\r\n    \r\n    row = 1;\r\n    for_each(filter.begin(), filter.end(), [&](Entry &e) {\r\n        table[row++][1] = boost::str(boost::format(\"%.3f\") % (processError(e, path)));\r\n    });\r\n\r\n    std::ofstream ofs;\r\n    ofs.open(\"phase_error.csv\");\r\n\r\n    for_each(table.begin(), table.end(), [&](const std::vector<std::string> &col) {\r\n        for_each(col.begin(), col.end(), [&](const std::string &cell) {\r\n            std::cout << cell << \"\\t\";\r\n            ofs << cell << \";\";\r\n        });\r\n        std::cout << std::endl;\r\n        ofs << std::endl;\r\n    });\r\n\r\n    ofs.close();\r\n\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "974261361a7bfdc42286270f7cc5b755bccf4587", "size": 6236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "evaluation/old/phase_dc.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/phase_dc.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/phase_dc.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.0462427746, "max_line_length": 243, "alphanum_fraction": 0.5763309814, "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095495, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5671888847304439}}
{"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": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/bindings/rr.hpp>\n#include <boost/test/included/prg_exec_monitor.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/tools/test.hpp>\n#include <fstream>\n\n#include <boost/math/tools/test_data.hpp>\n\nusing namespace boost::math::tools;\nusing namespace std;\n\nboost::math::tuple<boost::math::ntl::RR, boost::math::ntl::RR> \n   tgamma_ratio(const boost::math::ntl::RR& a, const boost::math::ntl::RR& delta)\n{\n   if(delta > a)\n      throw std::domain_error(\"\");\n   boost::math::ntl::RR tg = boost::math::tgamma(a);\n   boost::math::ntl::RR r1 = tg / boost::math::tgamma(a + delta);\n   boost::math::ntl::RR r2 = tg / boost::math::tgamma(a - delta);\n   if((r1 > (std::numeric_limits<float>::max)()) || (r2 > (std::numeric_limits<float>::max)()))\n      throw std::domain_error(\"\");\n\n   return boost::math::make_tuple(r1, r2);\n}\n\nboost::math::ntl::RR tgamma_ratio2(const boost::math::ntl::RR& a, const boost::math::ntl::RR& b)\n{\n   return boost::math::tgamma(a) / boost::math::tgamma(b);\n}\n\n\nint cpp_main(int argc, char*argv [])\n{\n   boost::math::ntl::RR::SetPrecision(1000);\n   boost::math::ntl::RR::SetOutputPrecision(40);\n\n   parameter_info<boost::math::ntl::RR> arg1, arg2;\n   test_data<boost::math::ntl::RR> data;\n\n   bool cont;\n   std::string line;\n\n   if((argc >= 2) && (strcmp(argv[1], \"--ratio\") == 0))\n   {\n      std::cout << \"Welcome.\\n\"\n         \"This program will generate spot tests for the function tgamma_ratio(a, b)\\n\\n\";\n\n      do{\n         if(0 == get_user_parameter_info(arg1, \"a\"))\n            return 1;\n         if(0 == get_user_parameter_info(arg2, \"b\"))\n            return 1;\n         data.insert(&tgamma_ratio2, 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   else\n   {\n      std::cout << \"Welcome.\\n\"\n         \"This program will generate spot tests for the function tgamma_delta_ratio(a, delta)\\n\\n\";\n\n      do{\n         if(0 == get_user_parameter_info(arg1, \"a\"))\n            return 1;\n         if(0 == get_user_parameter_info(arg2, \"delta\"))\n            return 1;\n         data.insert(&tgamma_ratio, 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\n   std::cout << \"Enter name of test data file [default=tgamma_ratio_data.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"tgamma_ratio_data.ipp\";\n   std::ofstream ofs(line.c_str());\n   ofs << std::scientific;\n   write_code(ofs, data, \"tgamma_ratio_data\");\n   \n   return 0;\n}\n\n\n", "meta": {"hexsha": "7300c7dd0488b3e3387b954a26313a85901584a6", "size": 2965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/tgamma_ratio_data.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T08:33:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-12T06:14:54.000Z", "max_issues_repo_path": "libs/math/tools/tgamma_ratio_data.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "libs/math/tools/tgamma_ratio_data.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-17T15:37:11.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-10T14:06:31.000Z", "avg_line_length": 30.2551020408, "max_line_length": 99, "alphanum_fraction": 0.6084317032, "num_tokens": 840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5670825269213106}}
{"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": "#include <functional>\n#include <gazebo/gazebo.hh>\n#include <gazebo/physics/physics.hh>\n#include <gazebo/common/common.hh>\n#include <ignition/math/Vector3.hh>\n#include <ros/ros.h>\n#include <rocket/FiveThrustCommand.h>\n#include <atom_esp_joy/joydata.h>\n\n#include <boost/bind.hpp>\n#include <gazebo/common/common.hh>\n#include <gazebo/common/PID.hh>\n#include <gazebo/gazebo.hh>\n#include <gazebo/physics/physics.hh>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Twist.h>\n#include <gazebo_msgs/ModelStates.h>\n#include <nav_msgs/Odometry.h>\n#include <ros/ros.h>\n#include <stdio.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/transform_datatypes.h>\n#include <std_srvs/Empty.h>\n\n#include <geometry_msgs/Vector3.h> \n//#include <tf/Quaternion.h>\n\nusing gazebo::common::PID;\nusing gazebo::common::Time;\n\n/*\nOnly for reference\n\n    private: void joystate_cb(const atom_esp_joy::joydata::ConstPtr& _joy_data_msg)\n    {\n\tthis->joy_data = *_joy_data_msg;\n        this->addaccel_center = this->joy_data.S;\n        \n      this->addaccel_side_1 = this->addaccel_center - this->joy_data.X;\n      this->addaccel_side_2 = this->addaccel_center + this->joy_data.X;\n      this->addaccel_side_3 = this->addaccel_center - this->joy_data.Y;\n      this->addaccel_side_4 = this->addaccel_center + this->joy_data.Y;   \n    \n\tROS_INFO_THROTTLE(5,\"Joy msg received! %f %f\", (float)this->joy_data.S, this->addaccel_center);\n    }\n\n*/\n\nclass _PID\n{\n\t//public:\n\t//_PID(double _P, double _I, double _D);\n\t//void Update_Param(double _P, double _I, double _D);\n\t//void Reset();\n\t//double Update(double err, double dt);\n\n\tprivate:\n\tdouble integral_error;\n\tdouble last_error;\n\tdouble p, i , d;\n\n\tpublic: _PID(double _P, double _I, double _D){p=_P; i=_I; d=_D;integral_error=0;last_error=0;}\n\tpublic: void Update_Param(double _P, double _I, double _D){p=_P; i=_I; d=_D; this->Reset();}\n\tpublic: double Update(double err, double dt)\n\t{\n\t\t \n\t\tfloat error_derivative = (err - last_error)/dt;\n\t\n\t\tintegral_error += err*dt; \n\n\t\treturn (err*p + error_derivative*d + integral_error*i);\n\n\t}\n\tpublic: void Reset()\n\t{\n\t\tintegral_error = 0;\n\t\tlast_error = 0;\n\t}\n\t\n\n\t\n};\n\ngeometry_msgs::Vector3 g_target_pos;//(0,0,0.2);\nnav_msgs::Odometry g_input_odom;\ngeometry_msgs::Vector3 g_pid_param_top,  g_pid_param_side,  g_pid_param_front; //(500,0,0);\n//double intError = 0; // PID interative error\n//float errorPlast = 0;\nros::Time last_time;\t\nrocket::FiveThrustCommand g_LastReqThrust;\n\n_PID pid_center(150, 0.2, 1);\n_PID pid_side(35, 0.01, 2);\n_PID pid_front(35, 0.01, 2);\n\t\nvoid calculateReqThrust(const nav_msgs::Odometry *odom, const geometry_msgs::Vector3 *targetPos, rocket::FiveThrustCommand *reqThrust)\n{\n\t// probably will need PID trying with P only\n        //static gazebo::common::PID pid_center(40,25,15,10, 0.1, 500, 10 );\n        //static gazebo::common::PID pid_side(40,25,15,10, 0.1, 500, 10 );\n        //static gazebo::common::PID pid_front(40,25,15,10, 0.1, 500, 10 );\n\n        float center_thrust,\n\tright_plus_thrust, // opposite has to be applied\n\tright_minus_thrust,\n        front_plus_thrust,\n\tfront_minus_thrust;\n\n        float right_plus_pos  = odom->pose.pose.position.x;\n        float front_plus_pos  = odom->pose.pose.position.y;\n        float center_plus_pos = odom->pose.pose.position.z;\n\n        float right_vel  = odom->twist.twist.linear.x;\n        float front_vel  = odom->twist.twist.linear.y;\n        float center_vel = odom->twist.twist.linear.z;\n\n        tf::Quaternion q(odom->pose.pose.orientation.x , odom->pose.pose.orientation.y, odom->pose.pose.orientation.z, odom->pose.pose.orientation.w);\n\tdouble roll, pitch, yaw;\n\ttf::Matrix3x3(q).getRPY(roll, pitch, yaw);\n\n\tROS_INFO_THROTTLE(1, \"%2.3f, %2.3f, %2.3f, %2.3f, %2.3f, %2.3f\", roll, pitch, yaw, right_vel, front_vel, center_vel); \n\n        float right_plus_target  = targetPos->x;\n        float front_plus_target  = targetPos->y;\n        float center_plus_target = targetPos->z;\n\t//gazebo::common::Time\n\tros::Time curr_time = ros::Time::now();\n\n\n// https://www.ode-wiki.org/wiki/index.php?title=HOWTO_thrust_control_logic\n// Owen Jones\n\tconst ignition::math::Vector3<double> LOOKAHEAD(0.0f, 0.0f, /*(odom->twist.twist.linear.z>=0?1:-1)*/g_pid_param_top.x);\n\tconst ignition::math::Vector3<double> SENSITIVITY(0.0f, 0.0f, g_pid_param_top.y);\n\n\tignition::math::Vector3<double> future_pose(0.0f, 0.0f, 0.0f);\n\tignition::math::Vector3<double> current_pose(odom->pose.pose.position.x, odom->pose.pose.position.y, odom->pose.pose.position.z);\n\tignition::math::Vector3<double> target_pose(targetPos->x, targetPos->y, targetPos->z);\n\tignition::math::Vector3<double> current_vel(odom->twist.twist.linear.x, odom->twist.twist.linear.y, odom->twist.twist.linear.z);\n\tignition::math::Vector3<double> applicable_force(0.0f, 0.0f, 0.0f);\n\n\tfuture_pose = current_pose + LOOKAHEAD * current_vel;\n\tapplicable_force = (future_pose - target_pose) * SENSITIVITY;\n\tg_LastReqThrust.thrust_center = applicable_force.Z();\n         \n\t//float errorP = center_plus_target - center_plus_pos;\n        \n\tfloat dt = (curr_time-last_time).toSec();\n\n\t//g_LastReqThrust.thrust_center = pid_center.Update(errorP, dt);\n\n        g_LastReqThrust.thrust_center = g_LastReqThrust.thrust_center > 0 ? g_LastReqThrust.thrust_center : 0 ;\n        g_LastReqThrust.thrust_center = g_LastReqThrust.thrust_center > g_pid_param_top.z ? g_pid_param_top.z : g_LastReqThrust.thrust_center ;\n        \n\tcenter_thrust = g_LastReqThrust.thrust_center; \n\n\n\t//roll applicable_force.Y(); //\n\tg_LastReqThrust.thrust_side_1 = pid_front.Update(-roll, dt);\n\tg_LastReqThrust.thrust_side_2 = -g_LastReqThrust.thrust_side_1; //pid_front.Update(roll, dt);\n\n        g_LastReqThrust.thrust_side_1 = g_LastReqThrust.thrust_side_1 > 0 ? g_LastReqThrust.thrust_side_1 : 0 ;\n        g_LastReqThrust.thrust_side_2 = g_LastReqThrust.thrust_side_2 > 0 ? g_LastReqThrust.thrust_side_2 : 0 ;\n\n\t//pitch // applicable_force.X(); //\n\tg_LastReqThrust.thrust_side_3 = pid_side.Update(-pitch, dt);\n\tg_LastReqThrust.thrust_side_4 = -g_LastReqThrust.thrust_side_3 ;//pid_side.Update(pitch, dt);\n\n        g_LastReqThrust.thrust_side_3 = g_LastReqThrust.thrust_side_3 > 0 ? g_LastReqThrust.thrust_side_3 : 0 ;\n        g_LastReqThrust.thrust_side_4 = g_LastReqThrust.thrust_side_4 > 0 ? g_LastReqThrust.thrust_side_4 : 0 ;\n\t\n\tg_LastReqThrust.thrust_side_1 = g_LastReqThrust.thrust_side_1 < 20 ? g_LastReqThrust.thrust_side_1 : 20; \n\tg_LastReqThrust.thrust_side_2 = g_LastReqThrust.thrust_side_2 < 20 ? g_LastReqThrust.thrust_side_2: 20; \n\tg_LastReqThrust.thrust_side_3 = g_LastReqThrust.thrust_side_3 < 20 ? g_LastReqThrust.thrust_side_3 : 20;  \n\tg_LastReqThrust.thrust_side_4 = g_LastReqThrust.thrust_side_4 < 20 ? g_LastReqThrust.thrust_side_4 :20;\n \t\n        *reqThrust = g_LastReqThrust;\n\tlast_time = curr_time;\n\t//errorPlast = errorP;\n\n\t\n/*\n        ros::Time curr_time = ros::Time::now();\n\t//nav_msgs::Odometry odom;\n\t//odom->header.stamp = curr_time;\n\t//odom->header.frame_id = \"odom\";\n\n\t// set the position\n\todom->pose.pose.position.x, y, z\n\todom->pose.pose.orientation.x , y, z, w \n\t// set the velocity\n\t//odom->child_frame_id = this->model->GetName();\n\t// set the twists\n\todom->twist.twist.linear.x, y, z \n        odom->twist.twist.angular.x, y, z \n*/\n}\n\nvoid target_pos_cb(const geometry_msgs::Vector3 _target_pos)\n{\n\tg_target_pos = _target_pos;\n        ROS_INFO(\"target received\");\n}\n\n\nvoid pidparam_top_cb(const geometry_msgs::Vector3 _pid_param)\n{\n\tg_pid_param_top = _pid_param;\n\tpid_center.Update_Param(g_pid_param_top.x, g_pid_param_top.y, g_pid_param_top.z);\n\t//pid_side.Update_Param(g_pid_param.x, g_pid_param.z, g_pid_param.y);\n\t//pid_front.Update_Param(g_pid_param.x, g_pid_param.z, g_pid_param.y);\n\tpid_side.Reset();\n\tpid_front.Reset();\n\t//intError = 0;\n\t//errorPlast = 0;\n\tlast_time = ros::Time::now();\t\n        g_LastReqThrust.thrust_center = 0;\n\tg_LastReqThrust.thrust_side_1 = 0;\n\tg_LastReqThrust.thrust_side_2 = 0;\n\tg_LastReqThrust.thrust_side_3 = 0;\n\tg_LastReqThrust.thrust_side_4 = 0;\n\n        std_srvs::Empty resetWorldSrv;\n\tros::service::call(\"/gazebo/reset_world\", resetWorldSrv);\n\t//reset worls and pos to the bot\n        ROS_INFO(\"pid params received\");\n}\n\n\nvoid pidparam_front_cb(const geometry_msgs::Vector3 _pid_param)\n{\n\tg_pid_param_front = _pid_param;\n\t//pid_center.Update_Param(g_pid_param.x, g_pid_param.z, g_pid_param.y);\n\t//pid_side.Update_Param(g_pid_param.x, g_pid_param.z, g_pid_param.y);\n\tpid_front.Update_Param(g_pid_param_front.x, g_pid_param_front.y, g_pid_param_front.z);\n\tpid_center.Reset();\n\tpid_side.Reset();\n\t//intError = 0;\n\t//errorPlast = 0;\n\tlast_time = ros::Time::now();\t\n        g_LastReqThrust.thrust_center = 0;\n\tg_LastReqThrust.thrust_side_1 = 0;\n\tg_LastReqThrust.thrust_side_2 = 0;\n\tg_LastReqThrust.thrust_side_3 = 0;\n\tg_LastReqThrust.thrust_side_4 = 0;\n\n        //std_srvs::Empty resetWorldSrv;\n\t//ros::service::call(\"/gazebo/reset_world\", resetWorldSrv);\n\t//reset worls and pos to the bot\n        ROS_INFO(\"pid params received\");\n}\n\n\nvoid pidparam_side_cb(const geometry_msgs::Vector3 _pid_param)\n{\n\tg_pid_param_side = _pid_param;\n\t//pid_center.Update_Param(g_pid_param.x, g_pid_param.z, g_pid_param.y);\n\tpid_side.Update_Param(g_pid_param_side.x, g_pid_param_side.y, g_pid_param_side.z);\n\t//pid_front.Update_Param(g_pid_param.x, g_pid_param.z, g_pid_param.y);\n\tpid_center.Reset();\n\tpid_front.Reset();\n\n        pidparam_front_cb(_pid_param);\n\t//intError = 0;\n\t//errorPlast = 0;\n\tlast_time = ros::Time::now();\t\n        g_LastReqThrust.thrust_center = 0;\n\tg_LastReqThrust.thrust_side_1 = 0;\n\tg_LastReqThrust.thrust_side_2 = 0;\n\tg_LastReqThrust.thrust_side_3 = 0;\n\tg_LastReqThrust.thrust_side_4 = 0;\n\n        std_srvs::Empty resetWorldSrv;\n\tros::service::call(\"/gazebo/reset_world\", resetWorldSrv);\n\t//reset worls and pos to the bot\n        ROS_INFO(\"pid params received\");\n}\n\n\nvoid odom_cb(const nav_msgs::Odometry _input_odom)\n{\n\n\tg_input_odom = _input_odom;\n\tROS_INFO_THROTTLE(10, \"odom received\");\n\n}\n\nint main(int argc, char **argv)\n{\n \n  ros::init(argc, argv, \"rocket_stabilization_node\");\n  ROS_INFO(\"stabilization control -> starting up...\");\n\n  g_target_pos.x = 0;\n  g_target_pos.y = 0;\n  g_target_pos.z = 20;\n\n  g_pid_param_top.x = 0.10;\n  g_pid_param_top.y = 0.10;\n  g_pid_param_top.z = 80.0;\n\n  ros::NodeHandle nh_;\n  \n  ros::Rate loop_rate(100);\n \n  ros::Subscriber target_sub = nh_.subscribe(\"rocket_target_pos\", 100, target_pos_cb); \n \n  ros::Subscriber odom_sub = nh_.subscribe(\"/odom\", 100, odom_cb); \n  \n  ros::Subscriber pidparam_top_sub = nh_.subscribe(\"rocket_pid_param_top\", 10, pidparam_top_cb); \n  ros::Subscriber pidparam_side_sub = nh_.subscribe(\"rocket_pid_param_side\", 10, pidparam_side_cb); \n  //ros::Subscriber pidparam_front_sub = nh_.subscribe(\"rocket_pid_param_front\", 10, pidparam_front_cb); \n\n         \n  ros::Publisher rocket_5_thrusts_pub = nh_.advertise<rocket::FiveThrustCommand>(\"rocket_stabilization_control\", 100);\n\n  // setRightForce(center+(X))\n  // setFrontForce(center+(Y))\n  // setAltitudeForce(center) \n  \n  while(ros::ok())\n  {\n    \trocket::FiveThrustCommand five_thrusts;\n        calculateReqThrust(&g_input_odom, &g_target_pos, &five_thrusts);\n\trocket_5_thrusts_pub.publish(five_thrusts);\n\n\tros::spinOnce();\n\t\n        loop_rate.sleep();\n\n  }\n\n}\n\n\n\n", "meta": {"hexsha": "7b18b8e2f1a1abdd6f013df0394b35a3c675f1fd", "size": 11231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_workspace/src/rocket/src/auto_stabilization.cpp", "max_stars_repo_name": "PassionForRobotics/SpaceX-First-Landing", "max_stars_repo_head_hexsha": "395ec32754ba3f6fa9dab4b917f42d8e7da79cf4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_workspace/src/rocket/src/auto_stabilization.cpp", "max_issues_repo_name": "PassionForRobotics/SpaceX-First-Landing", "max_issues_repo_head_hexsha": "395ec32754ba3f6fa9dab4b917f42d8e7da79cf4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_workspace/src/rocket/src/auto_stabilization.cpp", "max_forks_repo_name": "PassionForRobotics/SpaceX-First-Landing", "max_forks_repo_head_hexsha": "395ec32754ba3f6fa9dab4b917f42d8e7da79cf4", "max_forks_repo_licenses": ["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.4255952381, "max_line_length": 150, "alphanum_fraction": 0.724156353, "num_tokens": 3444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5670825098991957}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2019 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#include \"../performance_test.hpp\"\n#if defined(TEST_CPP_BIN_FLOAT)\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#endif\n\nvoid test34()\n{\n#ifdef TEST_CPP_BIN_FLOAT\n   test<boost::multiprecision::number<boost::multiprecision::cpp_bin_float<500> > >(\"cpp_bin_float\", 500);\n#endif\n}\n", "meta": {"hexsha": "4f3429f50e36d8acd06ca80d0196bcc4ad8fa3a9", "size": 536, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/performance_test_files/test34.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/performance/performance_test_files/test34.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/multiprecision/performance/performance_test_files/test34.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": 31.5294117647, "max_line_length": 106, "alphanum_fraction": 0.6735074627, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5670824992840513}}
{"text": "//Link to Boost\n#define BOOST_TEST_DYN_LINK\n\n//VERY IMPORTANT - include this last\n//#include <boost/test/included/unit_test.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"test.h\"\n#include \"../InfiniteRoots.h\"\nusing namespace std::literals::complex_literals;\n\n// test suite\nBOOST_FIXTURE_TEST_SUITE(InfiniteRoots_suite, SimpleTestFixture, * utf::label(\"InfiniteRoots\"))\n\nBOOST_DATA_TEST_CASE(twoRoots_test, bdata::random(0, 8) ^ bdata::random(2, 8) ^ bdata::xrange(20), diffLM, M, index)\n{\n    int L =  2 * M + diffLM;\n    int m = 2;\n    InfiniteRoots ir(L, M);\n    std::vector<var_t>& roots = ir.getRoot(m);\n    var_t r1 = 2.0L * L / var_t(3.0L + L - 2.0L * M, sqrt(3.0L + L - 2.0L * M));\n    var_t r2 = 2.0L * L / var_t(3.0L + L - 2.0L * M, -sqrt(3.0L + L - 2.0L * M));\n    BOOST_TEST(std::abs(roots[0] - std::conj(roots[1])) < EPS);\n    BOOST_TEST(std::abs(roots[0].real() - r1.real()) < EPS);\n    BOOST_TEST(abs(abs(roots[0].imag()) - abs(r1.imag())) < EPS);\n}\n\nBOOST_DATA_TEST_CASE(moreThanTwoRoots_test, bdata::random(0, 8) ^ bdata::random(3, 16) ^ bdata::xrange(20), diffLM, M, index)\n{\n    int L = 2 * M + diffLM;\n    int m = random64(M - 2) + 2;\n    InfiniteRoots ir(L, M);\n    std::vector<var_t>& roots = ir.getRoot(m);\n    int R = L - 2 * M + 2 * m;\n    std::cout <<\"L=\" << L << \", M=\" << M << \", roots=\" << roots << std::endl;\n    for (int i = 0; i < m; i++) {\n        var_t res = roots[i] * (elem_t)R - 2.0L * L;\n        for (int j = 0; j < m; j++) {\n            if (j == i) continue;\n            res += 2.0L * roots[i] * roots[j] / (roots[i] - roots[j]);\n        }\n        BOOST_TEST_INFO(\"m=\" << m << \", i=\" << i);\n        BOOST_TEST(std::abs(res) < 1e-8);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "8ce008e991bd85e9335f47e03405a36c8b0edebd", "size": 1713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/InfiniteRootsTests.cpp", "max_stars_repo_name": "gaolichen/bethesolver", "max_stars_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/InfiniteRootsTests.cpp", "max_issues_repo_name": "gaolichen/bethesolver", "max_issues_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/InfiniteRootsTests.cpp", "max_forks_repo_name": "gaolichen/bethesolver", "max_forks_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6875, "max_line_length": 125, "alphanum_fraction": 0.5720957385, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.567082498184652}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include \"fputils/log_space_matrix_multiply.hpp\"\n#include \"test_case.hpp\"\n\nusing fputils::Matrix ;\n\nbool operator==( Matrix const& left, Matrix const& right ) {\n\tif( left.size1() != right.size1() || left.size2() != right.size2() ) {\n\t\treturn false ;\n\t}\n\t\n\tfor( std::size_t i = 0; i < left.size1(); ++i ) {\n\t\tfor( std::size_t j = 0; j < left.size2(); ++j ) {\n\t\t\tif( left( i, j ) != right( i, j )) {\n\t\t\t\treturn false ;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true ;\n}\n\nbool operator!=( Matrix const& left, Matrix const& right ) {\n\treturn !(left == right ) ;\n}\n\nAUTO_TEST_CASE( test_log_space_matrix_multiply ) {\n\tstd::cerr << \"test_log_space_matrix_multiply...\\n\" ;\n\tusing fputils::ConstantMatrix ;\n\ttypedef std::pair< Matrix, Matrix > P ;\n\tstd::vector< P > multiplicands ;\n\tstd::vector< Matrix > expected_results ;\n\t\n\t// multiply 1x1 matrices\n\tmultiplicands.push_back(\n\t\tP(\n\t\t\tConstantMatrix( 1, 1, 0.0 ),\n\t\t\tConstantMatrix( 1, 1, 0.0 )\n\t\t)\n\t) ;\n\t\n\texpected_results.push_back( ConstantMatrix( 1, 1, 0.0 ) ) ;\n\n\tmultiplicands.push_back(\n\t\tP(\n\t\t\tConstantMatrix( 1, 1, 0.0 ),\n\t\t\tConstantMatrix( 1, 1, 1.0 )\n\t\t)\n\t) ;\n\t\n\texpected_results.push_back( ConstantMatrix( 1, 1, 1.0 ) ) ;\n\n\tmultiplicands.push_back(\n\t\tP(\n\t\t\tConstantMatrix( 1, 1, 1.0 ),\n\t\t\tConstantMatrix( 1, 1, 0.0 )\n\t\t)\n\t) ;\n\t\n\texpected_results.push_back( ConstantMatrix( 1, 1, 1.0 ) ) ;\n\n\tmultiplicands.push_back(\n\t\tP(\n\t\t\tConstantMatrix( 1, 1, 1.0 ),\n\t\t\tConstantMatrix( 1, 1, 1.0 )\n\t\t)\n\t) ;\n\t\n\texpected_results.push_back( ConstantMatrix( 1, 1, 2.0 ) ) ;\n\t\n\t// multiply 1x2 by 2x1 matrices\n\tmultiplicands.push_back(\n\t\tP(\n\t\t\tConstantMatrix( 1, 2, 0.0 ),\n\t\t\tConstantMatrix( 2, 1, 0.0 )\n\t\t)\n\t) ;\n\t\n\texpected_results.push_back( ConstantMatrix( 1, 1, std::log( 2.0 ))) ;\n\n\tmultiplicands.push_back(\n\t\tP(\n\t\t\tConstantMatrix( 1, 2, 0.0 ),\n\t\t\tConstantMatrix( 2, 1, 1.0 )\n\t\t)\n\t) ;\n\t\n\texpected_results.push_back( ConstantMatrix( 1, 1, std::log( 2.0 ) + 1.0 )) ;\n\n\tmultiplicands.push_back(\n\t\tP(\n\t\t\tConstantMatrix( 1, 2, 1.0 ),\n\t\t\tConstantMatrix( 2, 1, 0.0 )\n\t\t)\n\t) ;\n\t\n\texpected_results.push_back( ConstantMatrix( 1, 1, std::log( 2.0 ) + 1.0 )) ;\n\n\tmultiplicands.push_back(\n\t\tP(\n\t\t\tConstantMatrix( 1, 2, 1.0 ),\n\t\t\tConstantMatrix( 2, 1, 1.0 )\n\t\t)\n\t) ;\n\t\n\texpected_results.push_back( ConstantMatrix( 1, 1, std::log( 2.0 ) + 2.0 )) ;\n\t\n\t// multiply 2x2 by 2x2 matrices\n\tmultiplicands.push_back(\n\t\tP(\n\t\t\tConstantMatrix( 2, 2, 0.0 ),\n\t\t\tConstantMatrix( 2, 2, 0.0 )\n\t\t)\n\t) ;\n\t\n\texpected_results.push_back( ConstantMatrix( 2, 2, std::log( 2.0 ))) ;\n\n\tmultiplicands.push_back(\n\t\tP(\n\t\t\tConstantMatrix( 2, 2, 0.0 ),\n\t\t\tConstantMatrix( 2, 2, 1.0 )\n\t\t)\n\t) ;\n\t\n\texpected_results.push_back( ConstantMatrix( 2, 2, std::log( 2.0 ) + 1.0 )) ;\n\n\tmultiplicands.push_back(\n\t\tP(\n\t\t\tConstantMatrix( 2, 2, 1.0 ),\n\t\t\tConstantMatrix( 2, 2, 0.0 )\n\t\t)\n\t) ;\n\t\n\texpected_results.push_back( ConstantMatrix( 2, 2, std::log( 2.0 ) + 1.0 )) ;\n\n\tmultiplicands.push_back(\n\t\tP(\n\t\t\tConstantMatrix( 2, 2, 1.0 ),\n\t\t\tConstantMatrix( 2, 2, 1.0 )\n\t\t)\n\t) ;\n\t\n\texpected_results.push_back( ConstantMatrix( 2, 2, std::log( 2.0 ) + 2.0 )) ;\n\t\n\tassert( multiplicands.size() == expected_results.size() ) ;\n\tfor( std::size_t i = 0; i < multiplicands.size(); ++i ) {\n\t\tstd::cerr << \"Test case \" << i+1 << \" of \" << multiplicands.size() << \"...\\n\" ;\n\t\tMatrix m = fputils::log_space_matrix_multiply( multiplicands[i].first, multiplicands[i].second ) ;\n\t\tif( m != expected_results[i] ) {\n\t\t\tstd::cerr << \"Multiplying\\n  \" << multiplicands[i].first << \"\\n  by\\n\" << multiplicands[i].second << \",\\n\" ;\n\t\t\tstd::cerr << \"Expected:\\n  \" << expected_results[i] << \"\\n  but got\\n\" << m << \".\\n\" ;\n\t\t}\n\t\tTEST_ASSERT( m == expected_results[i] ) ;\n\t}\n}\n", "meta": {"hexsha": "f6dd866c300de2a3e2114cf9acd6639d2839fc90", "size": 3927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fputils/test/test_log_multiply_exp.cpp", "max_stars_repo_name": "gavinband/bingwa", "max_stars_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "fputils/test/test_log_multiply_exp.cpp", "max_issues_repo_name": "gavinband/bingwa", "max_issues_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "fputils/test/test_log_multiply_exp.cpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9451219512, "max_line_length": 111, "alphanum_fraction": 0.6172650879, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.567082498184652}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    int n; cin >> n;\n    cpp_int ans = 0;\n    vector<cpp_int> v(5, 0);\n    for (int i = 0; i < n; i++) {\n        string s; cin >> s;\n        if (s[0] == 'M') v[0]++;\n        if (s[0] == 'A') v[1]++;\n        if (s[0] == 'R') v[2]++;\n        if (s[0] == 'C') v[3]++;\n        if (s[0] == 'H') v[4]++;\n    }\n    for (int i = 0; i < 3; i++) {\n        for (int j = i + 1; j < 4; j++) {\n            for (int k = j + 1; k < 5; k++) {\n                ans += v[i] * v[j] * v[k];\n            }\n        }\n    }\n    cout << ans << endl;\n}\n", "meta": {"hexsha": "13cc487e936b8299c633f0a798a13d069f6e47bc", "size": 719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc089/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/abc089/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/abc089/c/main.cpp", "max_forks_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_forks_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7931034483, "max_line_length": 45, "alphanum_fraction": 0.4116828929, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5670824939764791}}
{"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/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_LOGSPACE_ADD_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_LOGSPACE_ADD_HPP_INCLUDED\n\n#ifndef BOOST_SIMD_NO_NANS\n#include <boost/simd/function/scalar/is_nan.hpp>\n#endif\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/scalar/exp.hpp>\n#include <boost/simd/function/scalar/log1p.hpp>\n#include <boost/simd/function/scalar/max.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( logspace_add_\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      A0 tmp = -bs::abs(a0-a1);\n      A0 r = bs::max(a0,a1)+bs::log1p(bs::exp(tmp));\n    #ifndef BOOST_SIMD_NO_NANS\n      return is_nan(tmp) ? a0+a1 : r;\n    #else\n      return r;\n    #endif\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "dd76de0c86143d66a178d141cd40b7ac871d1123", "size": 1604, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/logspace_add.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/scalar/function/logspace_add.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/logspace_add.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8461538462, "max_line_length": 100, "alphanum_fraction": 0.5698254364, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5670677585323989}}
{"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": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE CISHW1Test\n\n// system includes\n#include <boost/test/unit_test.hpp>\n#include <exception>\n#include <unistd.h>\n#include <boost/math/constants/constants.hpp>\n#include <iostream>\n#include <vector>\n#include <boost/bind.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n\n// local includes\n#include \"matrixOperations.hpp\"\n#include \"parsePA1_2.hpp\"\n#include \"PivotCalibration.hpp\"\n#include \"PointEstimation.hpp\"\n#include \"PA1_2_DataConstants.hpp\"\n#include \"DistortionCalibration.hpp\"\n\nstatic const bool debug = false;\nstatic const double tolerance = 0.01l;\n\n/// @todo The unit test requires a symlink from the executable folder to the location of the PA1-2 data folder, fix this using CMake.\n\n\ntemplate<typename T>\nbool isWithinTolerance(const T& result, const T& groundTruth, double toleranceVal = tolerance){\n    return (result.isApprox(groundTruth,toleranceVal) || (result - groundTruth).norm() < toleranceVal);\n}\n\nBOOST_AUTO_TEST_SUITE(cisPA2test)\n\nBOOST_AUTO_TEST_CASE(BernsteinTest)\n{\n\n    // Testing\n    double test = boost::math::binomial_coefficient<double>(3, 1);\n    if(debug) std::cout << \"\\n\\nbinomial coefficient test is \" << test << std::endl;\n    double a=5.0;\n    int b=3;\n    int c=1;\n    double Btest = BersteinPolynomial(a, b, c);\n    if(debug) std::cout << \"\\n\\nBtest is \" << Btest << std::endl;\n\n    Eigen::MatrixXd test2(1,3);\n    test2 << 0, 0.5, 1;\n    Eigen::MatrixXd TestF = FMatrix(test2);\n    if(debug) std::cout << \"\\n\\nF is \" << TestF.transpose() << std::endl;\n    //std::cout << \"\\n\\nThe size of F is \" << TestF.rows() << \"x\" << TestF.cols() <<std::endl;\n\n    // 1-D Unit Test\n    // A uniform distortion is applied to a set of points (y=x^2)\n    // The expected result is that UndistortedUnitTest is about equal to the GroundTruth\n    int max = 100;\n    int min = 0;\n    Eigen::VectorXd X = Eigen::VectorXd::LinSpaced(max+1,min,max);\n    Eigen::VectorXd Y = 2*X;\n    Eigen::MatrixXd Y3distorted = Eigen::MatrixXd::Zero(X.size(),3);\n    Eigen::MatrixXd X3GroundTruth = Eigen::MatrixXd::Zero(X.size(),3);\n    Y3distorted.col(0) = Y;\n    X3GroundTruth.col(0) = X;\n    Eigen::Vector3d minCorner;\n    Eigen::Vector3d maxCorner;\n    \n    Eigen::MatrixXd undistorted = correctDistortion(Y3distorted, Y3distorted, X3GroundTruth, minCorner, maxCorner);\n    if(debug) std::cout << \"\\n\\nUnitTestUndistorted\\n\\n\" << undistorted << \"\\n\\nGroundTruth\\n\\n\" << X3GroundTruth;\n    BOOST_CHECK(isWithinTolerance(undistorted,X3GroundTruth));\n\n}\n    \ntemplate<typename T>\nvoid CompareFrames(std::string file, const T& f1, const T& f2){\n    double frameTolerance = 2.0;\n    auto f1b = f1.begin();\n    auto f2b = f2.begin();\n    for(;f1b!=f1.end(); ++f1b, ++f2b){\n        auto f11b = f1b->begin();\n        auto f22b = f2b->begin();\n        for(;f11b != f1b->end(); ++f11b, ++f22b){\n            bool isWithinToleranceB = isWithinTolerance(*f11b, *f22b, frameTolerance);\n            BOOST_CHECK(isWithinToleranceB);\n            if(!isWithinToleranceB){\n                std::cout << \"\\n\\n\" << file << \" outside of tolerances! check these values:\\n\\n\" << *f11b << \"\\n\\n\";\n                \n            }\n        }\n        \n    }\n    \n}\n    \nvoid CompareOutputFiles(std::string filenamePrefix){\n    \n    DataSource pclp;\n    DataSource pclpOut;\n    const bool required = true;\n    // optional == not required == false\n    const bool optional = false;\n    // check if the user supplied a full path, if not assemble a path\n    // from the default paths and the defualt prefix/suffix combos\n    assemblePathIfFullPathNotSupplied(relativeOutputDataPath,filenamePrefix,dataFileNameSuffix_output1       ,pclpOut.output1Path      ,required);\n    assemblePathIfFullPathNotSupplied(relativeOutputDataPath,filenamePrefix,dataFileNameSuffix_output2       ,pclpOut.output2Path      ,required);\n    assemblePathIfFullPathNotSupplied(relativeDataPath,filenamePrefix,dataFileNameSuffix_output1       ,pclp.output1Path      ,required);\n    assemblePathIfFullPathNotSupplied(relativeDataPath,filenamePrefix,dataFileNameSuffix_output2       ,pclp.output2Path      ,required);\n    \n    \n    AlgorithmData ad;\n    loadPointCloudFromFile(pclp.output1Path       ,ad.output1                    ,debug);\n    loadPointCloudFromFile(pclp.output2Path       ,ad.output2                    ,debug);\n    \n    AlgorithmData adOut;\n    loadPointCloudFromFile(pclpOut.output1Path       ,adOut.output1                    ,debug);\n    loadPointCloudFromFile(pclpOut.output2Path       ,adOut.output2                    ,debug);\n    \n    //AlgorithmData adOut = initAlgorithmData(relativeOutputDataPath,filenamePrefix);\n    //AlgorithmData ad = initAlgorithmData(relativeDataPath, filenamePrefix);\n    \n    CompareFrames(relativeOutputDataPath + filenamePrefix + dataFileNameSuffix_output1, adOut.output1.frames, ad.output1.frames);\n    CompareFrames(relativeOutputDataPath + filenamePrefix + dataFileNameSuffix_output2, adOut.output2.frames, ad.output2.frames);\n}\n \n/// unit test output of all debug files\nBOOST_AUTO_TEST_CASE(EMPivotCalibrationResults)\n{\n    CompareOutputFiles(pa2debuga);\n    CompareOutputFiles(pa2debugb);\n    CompareOutputFiles(pa2debugc);\n    CompareOutputFiles(pa2debugd);\n    CompareOutputFiles(pa2debuge);\n    CompareOutputFiles(pa2debugf);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "02c0f5b9e0d6bdcb4b8b112131fd886e0ee48b72", "size": 5319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cisHW2test.cpp", "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": "test/cisHW2test.cpp", "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": "test/cisHW2test.cpp", "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": 38.8248175182, "max_line_length": 146, "alphanum_fraction": 0.6903553299, "num_tokens": 1381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.5669337694927756}}
{"text": "#include <blitzml/dataset/dataset.h>\n\n#include <cmath>\n\nnamespace BlitzML {\n\nvalue_t Column::l2_norm() const {\n  return sqrt(l2_norm_sq());\n}\n\n\nvalue_t Column::l2_norm_sq_centered() const {\n  value_t mean_value = this->mean();\n  value_t ret = l2_norm_sq() - mean_value * mean_value * length();\n  if (ret <= 0) {\n    return 0.;\n  }\n  return ret;\n}\n\n\nvalue_t Column::l2_norm_centered() const {\n  return sqrt(l2_norm_sq_centered());\n};\n\n\nvoid Dataset::contiguous_submatrix_multiply(\n    const std::vector<value_t> &values, value_t* result,\n    index_t first_column_submatrix, index_t end_column_submatrix) const {\n\n  index_t j, result_ind;\n  for (j = first_column_submatrix, result_ind = 0;\n       j < end_column_submatrix; ++j, ++result_ind) {\n    result[result_ind] = column(j)->inner_product(values);\n  }\n}\n\n\n} // namespace BlitzML\n\n", "meta": {"hexsha": "f51903a894444d26e128f0873170003338f3bb33", "size": 833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dataset/dataset.cpp", "max_stars_repo_name": "vlad17/BlitzML", "max_stars_repo_head_hexsha": "f13e089acf7435416bec17e87e5b3130426fc2cd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dataset/dataset.cpp", "max_issues_repo_name": "vlad17/BlitzML", "max_issues_repo_head_hexsha": "f13e089acf7435416bec17e87e5b3130426fc2cd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dataset/dataset.cpp", "max_forks_repo_name": "vlad17/BlitzML", "max_forks_repo_head_hexsha": "f13e089acf7435416bec17e87e5b3130426fc2cd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3170731707, "max_line_length": 73, "alphanum_fraction": 0.6974789916, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5668983999886105}}
{"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": "#include <Eigen/Core>\n#include <ceres/ceres.h>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n\n#include <ceres-error-terms/generic-prior-error-term.h>\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\nclass PriorErrorTerms : public ::testing::Test {\n public:\n  static constexpr int VectorDim = 9;\n\n  static constexpr int PriorBlockSize = 3;\n  static constexpr int PriorBlockIndex = 4;\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n protected:\n  virtual void SetUp() {\n    prior_mean_ << 1, 2, 3, 4, 5, 6, 7, 8, -3;\n    block_prior_mean_ = prior_mean_.segment<PriorBlockSize>(PriorBlockIndex);\n\n    current_value_ = prior_mean_;\n    covariance_matrix_.setIdentity();\n    block_covariance_matrix_ =\n        covariance_matrix_.block<PriorBlockSize, PriorBlockSize>(\n            PriorBlockIndex, PriorBlockIndex);\n  }\n\n  void addResidual();\n  void addMoreGenericResidual();\n  void solve();\n\n  ceres::Problem problem_;\n  ceres::Solver::Summary summary_;\n  Eigen::Matrix<double, VectorDim, 1> prior_mean_;\n  Eigen::Matrix<double, VectorDim, VectorDim> covariance_matrix_;\n\n  Eigen::Matrix<double, PriorBlockSize, 1> block_prior_mean_;\n  Eigen::Matrix<double, PriorBlockSize, PriorBlockSize>\n      block_covariance_matrix_;\n\n  Eigen::Matrix<double, VectorDim, 1> current_value_;\n};\n\nvoid PriorErrorTerms::addResidual() {\n  ceres::CostFunction* cost_function =\n      new ceres_error_terms::GenericPriorErrorTerm<VectorDim, PriorBlockIndex,\n                                                   PriorBlockSize>(\n          block_prior_mean_, block_covariance_matrix_);\n  problem_.AddResidualBlock(cost_function, NULL, current_value_.data());\n}\n\nvoid PriorErrorTerms::solve() {\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_SCHUR;\n  options.minimizer_progress_to_stdout = false;\n  options.parameter_tolerance = 1e-20;\n  options.gradient_tolerance = 1e-20;\n  options.function_tolerance = 1e-20;\n  options.max_num_iterations = 1e3;\n  ceres::Solve(options, &problem_, &summary_);\n\n  LOG(INFO) << summary_.BriefReport() << std::endl;\n  LOG(INFO) << summary_.message << std::endl;\n}\n\nTEST_F(PriorErrorTerms, TestGenericPriorErrorTermZeroCost) {\n  addResidual();\n  solve();\n\n  EXPECT_EQ(summary_.initial_cost, 0.0);\n  EXPECT_EQ(summary_.final_cost, 0.0);\n  EXPECT_EQ(summary_.iterations.size(), 1u);\n}\n\nTEST_F(PriorErrorTerms, TestGenericPriorErrorTermOptimization) {\n  current_value_.segment<PriorBlockSize>(PriorBlockIndex).setRandom();\n  current_value_.segment<PriorBlockSize>(PriorBlockIndex) *= 1000.0;\n\n  addResidual();\n  solve();\n\n  EXPECT_NEAR_EIGEN(current_value_, prior_mean_, 1e-10);\n  EXPECT_LT(summary_.final_cost, 1e-10);\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "a2515f5e2d6b31e17fac41f93c07aaba35e749fc", "size": 2725, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/ceres-error-terms/test/test_generic_prior_error_term.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "algorithms/ceres-error-terms/test/test_generic_prior_error_term.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "algorithms/ceres-error-terms/test/test_generic_prior_error_term.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": 30.2777777778, "max_line_length": 78, "alphanum_fraction": 0.7390825688, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5668680501606398}}
{"text": "// Copyright \u00a9 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": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n//\r\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <string>\r\n\r\n\r\n#include <geometry_test_common.hpp>\r\n\r\n#include <boost/geometry/algorithms/distance.hpp>\r\n#include <boost/geometry/domains/gis/io/wkt/read_wkt.hpp>\r\n\r\n#include <boost/geometry/strategies/strategies.hpp>\r\n\r\n\r\n#include <boost/geometry/multi/algorithms/distance.hpp>\r\n#include <boost/geometry/multi/geometries/multi_point.hpp>\r\n#include <boost/geometry/multi/geometries/multi_linestring.hpp>\r\n#include <boost/geometry/multi/geometries/multi_polygon.hpp>\r\n#include <boost/geometry/domains/gis/io/wkt/read_wkt_multi.hpp>\r\n\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/adapted/c_array.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\r\n#include <test_common/test_point.hpp>\r\n\r\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\r\n\r\n\r\ntemplate <typename Geometry1, typename Geometry2>\r\nvoid test_distance(std::string const& wkt1, std::string const& wkt2, double expected)\r\n{\r\n    Geometry1 g1;\r\n    Geometry2 g2;\r\n    bg::read_wkt(wkt1, g1);\r\n    bg::read_wkt(wkt2, g2);\r\n    typename bg::default_distance_result<Geometry1, Geometry2>::type d = bg::distance(g1, g2);\r\n\r\n    BOOST_CHECK_CLOSE(d, expected, 0.0001);\r\n}\r\n\r\ntemplate <typename Geometry1, typename Geometry2, typename Strategy>\r\nvoid test_distance(Strategy const& strategy, std::string const& wkt1,\r\n                   std::string const& wkt2, double expected)\r\n{\r\n    Geometry1 g1;\r\n    Geometry2 g2;\r\n    bg::read_wkt(wkt1, g1);\r\n    bg::read_wkt(wkt2, g2);\r\n    typename bg::default_distance_result<Geometry1, Geometry2>::type d = bg::distance(g1, g2, strategy);\r\n\r\n    BOOST_CHECK_CLOSE(d, expected, 0.0001);\r\n}\r\n\r\n\r\ntemplate <typename P>\r\nvoid test_2d()\r\n{\r\n    typedef bg::model::multi_point<P> mp;\r\n    typedef bg::model::multi_linestring<bg::model::linestring<P> > ml;\r\n    test_distance<P, P>(\"POINT(0 0)\", \"POINT(1 1)\", sqrt(2.0));\r\n    test_distance<P, mp>(\"POINT(0 0)\", \"MULTIPOINT((1 1),(1 0),(0 2))\", 1.0);\r\n    test_distance<mp, P>(\"MULTIPOINT((1 1),(1 0),(0 2))\", \"POINT(0 0)\", 1.0);\r\n    test_distance<mp, mp>(\"MULTIPOINT((1 1),(1 0),(0 2))\", \"MULTIPOINT((2 2),(2 3))\", sqrt(2.0));\r\n    test_distance<P, ml>(\"POINT(0 0)\", \"MULTILINESTRING((1 1,2 2),(1 0,2 0),(0 2,0 3))\", 1.0);\r\n    test_distance<ml, P>(\"MULTILINESTRING((1 1,2 2),(1 0,2 0),(0 2,0 3))\", \"POINT(0 0)\", 1.0);\r\n    test_distance<ml, mp>(\"MULTILINESTRING((1 1,2 2),(1 0,2 0),(0 2,0 3))\", \"MULTIPOINT((0 0),(1 1))\", 0.0);\r\n\r\n    // Test with a strategy\r\n    bg::strategy::distance::pythagoras<P, P> pyth;\r\n    test_distance<P, P>(pyth, \"POINT(0 0)\", \"POINT(1 1)\", sqrt(2.0));\r\n    test_distance<P, mp>(pyth, \"POINT(0 0)\", \"MULTIPOINT((1 1),(1 0),(0 2))\", 1.0);\r\n    test_distance<mp, P>(pyth, \"MULTIPOINT((1 1),(1 0),(0 2))\", \"POINT(0 0)\", 1.0);\r\n}\r\n\r\n\r\ntemplate <typename P>\r\nvoid test_3d()\r\n{\r\n    typedef bg::model::multi_point<P> mp;\r\n    test_distance<P, P>(\"POINT(0 0 0)\", \"POINT(1 1 1)\", sqrt(3.0));\r\n    test_distance<P, mp>(\"POINT(0 0 0)\", \"MULTIPOINT((1 1 1),(1 0 0),(0 1 2))\", 1.0);\r\n    test_distance<mp, mp>(\"MULTIPOINT((1 1 1),(1 0 0),(0 0 2))\", \"MULTIPOINT((2 2 2),(2 3 4))\", sqrt(3.0));\r\n}\r\n\r\n\r\ntemplate <typename P1, typename P2>\r\nvoid test_mixed()\r\n{\r\n    typedef bg::model::multi_point<P1> mp1;\r\n    typedef bg::model::multi_point<P2> mp2;\r\n\r\n    test_distance<P1, P2>(\"POINT(0 0)\", \"POINT(1 1)\", sqrt(2.0));\r\n\r\n    test_distance<P1, mp1>(\"POINT(0 0)\", \"MULTIPOINT((1 1),(1 0),(0 2))\", 1.0);\r\n    test_distance<P1, mp2>(\"POINT(0 0)\", \"MULTIPOINT((1 1),(1 0),(0 2))\", 1.0);\r\n    test_distance<P2, mp1>(\"POINT(0 0)\", \"MULTIPOINT((1 1),(1 0),(0 2))\", 1.0);\r\n    test_distance<P2, mp2>(\"POINT(0 0)\", \"MULTIPOINT((1 1),(1 0),(0 2))\", 1.0);\r\n\r\n    // Test automatic reversal\r\n    test_distance<mp1, P1>(\"MULTIPOINT((1 1),(1 0),(0 2))\", \"POINT(0 0)\", 1.0);\r\n    test_distance<mp1, P2>(\"MULTIPOINT((1 1),(1 0),(0 2))\", \"POINT(0 0)\", 1.0);\r\n    test_distance<mp2, P1>(\"MULTIPOINT((1 1),(1 0),(0 2))\", \"POINT(0 0)\", 1.0);\r\n    test_distance<mp2, P2>(\"MULTIPOINT((1 1),(1 0),(0 2))\", \"POINT(0 0)\", 1.0);\r\n\r\n    // Test multi-multi using different point types for each\r\n    test_distance<mp1, mp2>(\"MULTIPOINT((1 1),(1 0),(0 2))\", \"MULTIPOINT((2 2),(2 3))\", sqrt(2.0));\r\n\r\n    // Test with a strategy\r\n    using namespace bg::strategy::distance;\r\n\r\n    test_distance<P1, P2>(pythagoras<P1, P2>(), \"POINT(0 0)\", \"POINT(1 1)\", sqrt(2.0));\r\n\r\n    test_distance<P1, mp1>(pythagoras<P1, P1>(), \"POINT(0 0)\", \"MULTIPOINT((1 1),(1 0),(0 2))\", 1.0);\r\n    test_distance<P1, mp2>(pythagoras<P1, P2>(), \"POINT(0 0)\", \"MULTIPOINT((1 1),(1 0),(0 2))\", 1.0);\r\n    test_distance<P2, mp1>(pythagoras<P2, P1>(), \"POINT(0 0)\", \"MULTIPOINT((1 1),(1 0),(0 2))\", 1.0);\r\n    test_distance<P2, mp2>(pythagoras<P2, P2>(), \"POINT(0 0)\", \"MULTIPOINT((1 1),(1 0),(0 2))\", 1.0);\r\n\r\n    // Most interesting: reversal AND a strategy (note that the stategy must be reversed automatically\r\n    test_distance<mp1, P1>(pythagoras<P1, P1>(), \"MULTIPOINT((1 1),(1 0),(0 2))\", \"POINT(0 0)\", 1.0);\r\n    test_distance<mp1, P2>(pythagoras<P1, P2>(), \"MULTIPOINT((1 1),(1 0),(0 2))\", \"POINT(0 0)\", 1.0);\r\n    test_distance<mp2, P1>(pythagoras<P2, P1>(), \"MULTIPOINT((1 1),(1 0),(0 2))\", \"POINT(0 0)\", 1.0);\r\n    test_distance<mp2, P2>(pythagoras<P2, P2>(), \"MULTIPOINT((1 1),(1 0),(0 2))\", \"POINT(0 0)\", 1.0);\r\n}\r\n\r\n\r\n\r\nint test_main( int , char* [] )\r\n{\r\n    test_2d<boost::tuple<float, float> >();\r\n    test_2d<bg::model::d2::point_xy<float> >();\r\n    test_2d<bg::model::d2::point_xy<double> >();\r\n\r\n    test_3d<boost::tuple<float, float, float> >();\r\n    test_3d<bg::model::point<double, 3, bg::cs::cartesian> >();\r\n\r\n    test_mixed<bg::model::d2::point_xy<float>, bg::model::d2::point_xy<double> >();\r\n\r\n#ifdef HAVE_TTMATH\r\n    test_2d<bg::model::d2::point_xy<ttmath_big> >();\r\n    test_mixed<bg::model::d2::point_xy<ttmath_big>, bg::model::d2::point_xy<double> >();\r\n#endif\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "2838ec524a5c83bf877a76c55ca372b1f63bf351", "size": 6311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/multi/algorithms/multi_distance.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/geometry/test/multi/algorithms/multi_distance.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/geometry/test/multi/algorithms/multi_distance.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7947019868, "max_line_length": 109, "alphanum_fraction": 0.6262082079, "num_tokens": 2283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5668680451901768}}
{"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": "// Copyright (c) 2022 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#pragma once\n#include <Eigen/Core>\n\nnamespace pyinterp {\n\ntemplate <typename T>\nusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\ntemplate <typename T>\nusing Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\n}  // namespace pyinterp", "meta": {"hexsha": "4c1de753f4c9f6ef2bf5f76b83b8b1d6c1aed9bd", "size": 400, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/eigen.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/eigen.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/eigen.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": 25.0, "max_line_length": 64, "alphanum_fraction": 0.7225, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.566868028598893}}
{"text": "#include \"clock.h\"\n#include <boost/format.hpp>\n#include <sstream>\n\nnamespace date_independent {\n    using namespace std;\n    using namespace boost;\n\n    clock::clock(const int hour, const int minute){\n        #define cx_minperday 60*24\n        \n        time_in_minutes = hour*60 + minute;\n        time_in_minutes %= cx_minperday;\n        if(time_in_minutes < 0)\n            time_in_minutes += cx_minperday; \n    }\n\n    clock clock::at(const int hour, const int minute){\n        return clock(hour, minute);\n    }\n\n    clock clock::plus(int minute){\n        return clock(0, time_in_minutes + minute);\n    }\n\n    clock::operator std::string() const {\n        stringstream stream;\n        stream << format(\"%02d:%02d\") % int(time_in_minutes/60) % (time_in_minutes%60);\n        return stream.str();\n    }\n}  // namespace date_independent\n", "meta": {"hexsha": "808b50623692cc60c1f6cb1267c7628f5cb67dd2", "size": 833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "clock/clock.cpp", "max_stars_repo_name": "mapa17/Exercism-cpp", "max_stars_repo_head_hexsha": "6f61c33dbe96c1e580d5b98bfc36ca2f59adea60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clock/clock.cpp", "max_issues_repo_name": "mapa17/Exercism-cpp", "max_issues_repo_head_hexsha": "6f61c33dbe96c1e580d5b98bfc36ca2f59adea60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clock/clock.cpp", "max_forks_repo_name": "mapa17/Exercism-cpp", "max_forks_repo_head_hexsha": "6f61c33dbe96c1e580d5b98bfc36ca2f59adea60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.03125, "max_line_length": 87, "alphanum_fraction": 0.6254501801, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370423, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5667911356557215}}
{"text": "/*=============================================================================\r\n    Copyright (c) 1998-2003 Joel de Guzman\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//  The calculator using a simple virtual machine and compiler.\r\n//\r\n//  Ported to v1.5 from the original v1.0 code by JDG\r\n//  [ JDG 9/18/2002 ]\r\n//\r\n////////////////////////////////////////////////////////////////////////////\r\n#include <boost/spirit/include/classic_core.hpp>\r\n#include <iostream>\r\n#include <vector>\r\n#include <string>\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\nusing namespace std;\r\nusing namespace BOOST_SPIRIT_CLASSIC_NS;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  The VMachine\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\nenum ByteCodes\r\n{\r\n    OP_NEG,     //  negate the top stack entry\r\n    OP_ADD,     //  add top two stack entries\r\n    OP_SUB,     //  subtract top two stack entries\r\n    OP_MUL,     //  multiply top two stack entries\r\n    OP_DIV,     //  divide top two stack entries\r\n    OP_INT,     //  push constant integer into the stack\r\n    OP_RET      //  return from the interpreter\r\n};\r\n\r\nclass vmachine\r\n{\r\npublic:\r\n                vmachine(unsigned stackSize = 1024)\r\n                :   stack(new int[stackSize]),\r\n                    stackPtr(stack) {}\r\n                ~vmachine() { delete [] stack; }\r\n    int         top() const { return stackPtr[-1]; };\r\n    void        execute(int code[]);\r\n\r\nprivate:\r\n\r\n    int*        stack;\r\n    int*        stackPtr;\r\n};\r\n\r\nvoid\r\nvmachine::execute(int code[])\r\n{\r\n    int const*  pc = code;\r\n    bool        running = true;\r\n    stackPtr = stack;\r\n\r\n    while (running)\r\n    {\r\n        switch (*pc++)\r\n        {\r\n            case OP_NEG:\r\n                stackPtr[-1] = -stackPtr[-1];\r\n                break;\r\n\r\n            case OP_ADD:\r\n                stackPtr--;\r\n                stackPtr[-1] += stackPtr[0];\r\n                break;\r\n\r\n            case OP_SUB:\r\n                stackPtr--;\r\n                stackPtr[-1] -= stackPtr[0];\r\n                break;\r\n\r\n            case OP_MUL:\r\n                stackPtr--;\r\n                stackPtr[-1] *= stackPtr[0];\r\n                break;\r\n\r\n            case OP_DIV:\r\n                stackPtr--;\r\n                stackPtr[-1] /= stackPtr[0];\r\n                break;\r\n\r\n            case OP_INT:\r\n                // Check stack overflow here!\r\n                *stackPtr++ = *pc++;\r\n                break;\r\n\r\n            case OP_RET:\r\n                running = false;\r\n                break;\r\n        }\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  The Compiler\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\nstruct push_int\r\n{\r\n    push_int(vector<int>& code_)\r\n    : code(code_) {}\r\n\r\n    void operator()(char const* str, char const* /*end*/) const\r\n    {\r\n        using namespace std;\r\n        int n = strtol(str, 0, 10);\r\n        code.push_back(OP_INT);\r\n        code.push_back(n);\r\n        cout << \"push\\t\" << int(n) << endl;\r\n    }\r\n\r\n    vector<int>& code;\r\n};\r\n\r\nstruct push_op\r\n{\r\n    push_op(int op_, vector<int>& code_)\r\n    : op(op_), code(code_) {}\r\n\r\n    void operator()(char const*, char const*) const\r\n    {\r\n        code.push_back(op);\r\n\r\n        switch (op) {\r\n\r\n            case OP_NEG:\r\n                cout << \"neg\\n\";\r\n                break;\r\n\r\n            case OP_ADD:\r\n                cout << \"add\\n\";\r\n                break;\r\n\r\n            case OP_SUB:\r\n                cout << \"sub\\n\";\r\n                break;\r\n\r\n            case OP_MUL:\r\n                cout << \"mul\\n\";\r\n                break;\r\n\r\n            case OP_DIV:\r\n                cout << \"div\\n\";\r\n                break;\r\n        }\r\n    }\r\n\r\n    int op;\r\n    vector<int>& code;\r\n};\r\n\r\ntemplate <typename GrammarT>\r\nstatic bool\r\ncompile(GrammarT const& calc, char const* expr)\r\n{\r\n    cout << \"\\n/////////////////////////////////////////////////////////\\n\\n\";\r\n\r\n    parse_info<char const*>\r\n        result = parse(expr, calc, space_p);\r\n\r\n    if (result.full)\r\n    {\r\n        cout << \"\\t\\t\" << expr << \" Parses OK\\n\\n\\n\";\r\n        calc.code.push_back(OP_RET);\r\n        return true;\r\n    }\r\n    else\r\n    {\r\n        cout << \"\\t\\t\" << expr << \" Fails parsing\\n\";\r\n        cout << \"\\t\\t\";\r\n        for (int i = 0; i < (result.stop - expr); i++)\r\n            cout << \" \";\r\n        cout << \"^--Here\\n\\n\\n\";\r\n        return false;\r\n    }\r\n}\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Our calculator grammar\r\n//\r\n////////////////////////////////////////////////////////////////////////////\r\nstruct calculator : public grammar<calculator>\r\n{\r\n    calculator(vector<int>& code_)\r\n    : code(code_) {}\r\n\r\n    template <typename ScannerT>\r\n    struct definition\r\n    {\r\n        definition(calculator const& self)\r\n        {\r\n            integer =\r\n                lexeme_d[ (+digit_p)[push_int(self.code)] ]\r\n                ;\r\n\r\n            factor =\r\n                    integer\r\n                |   '(' >> expression >> ')'\r\n                |   ('-' >> factor)[push_op(OP_NEG, self.code)]\r\n                |   ('+' >> factor)\r\n                ;\r\n\r\n            term =\r\n                factor\r\n                >> *(   ('*' >> factor)[push_op(OP_MUL, self.code)]\r\n                    |   ('/' >> factor)[push_op(OP_DIV, self.code)]\r\n                    )\r\n                    ;\r\n\r\n            expression =\r\n                term\r\n                >> *(   ('+' >> term)[push_op(OP_ADD, self.code)]\r\n                    |   ('-' >> term)[push_op(OP_SUB, self.code)]\r\n                    )\r\n                    ;\r\n        }\r\n\r\n        rule<ScannerT> expression, term, factor, integer;\r\n\r\n        rule<ScannerT> const&\r\n        start() const { return expression; }\r\n    };\r\n\r\n    vector<int>& code;\r\n};\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Main program\r\n//\r\n////////////////////////////////////////////////////////////////////////////\r\nint\r\nmain()\r\n{\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"\\t\\tA simple virtual machine...\\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    vmachine    mach;       //  Our virtual machine\r\n    vector<int> code;       //  Our VM code\r\n    calculator  calc(code); //  Our parser\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        code.clear();\r\n        if (compile(calc, str.c_str()))\r\n        {\r\n            mach.execute(&*code.begin());\r\n            cout << \"\\n\\nresult = \" << mach.top() << \"\\n\\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": "73eea522e673c616f2a3ea18669926a02fefaaac", "size": 7299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/spirit/classic/example/fundamental/more_calculators/vmachine_calc.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/more_calculators/vmachine_calc.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/more_calculators/vmachine_calc.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": 26.4456521739, "max_line_length": 80, "alphanum_fraction": 0.3695026716, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5667911356557215}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2008-2009 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 \"main.h\"\r\n#include <Eigen/Geometry>\r\n#include <Eigen/LU>\r\n#include <Eigen/SVD>\r\n\r\ntemplate<typename Scalar> void eulerangles(void)\r\n{\r\n  typedef Matrix<Scalar,3,3> Matrix3;\r\n  typedef Matrix<Scalar,3,1> Vector3;\r\n  typedef Quaternion<Scalar> Quaternionx;\r\n  typedef AngleAxis<Scalar> AngleAxisx;\r\n\r\n  Scalar a = internal::random<Scalar>(-Scalar(M_PI), Scalar(M_PI));\r\n  Quaternionx q1;\r\n  q1 = AngleAxisx(a, Vector3::Random().normalized());\r\n  Matrix3 m;\r\n  m = q1;\r\n\r\n  #define VERIFY_EULER(I,J,K, X,Y,Z) { \\\r\n    Vector3 ea = m.eulerAngles(I,J,K); \\\r\n    VERIFY_IS_APPROX(m,  Matrix3(AngleAxisx(ea[0], Vector3::Unit##X()) * AngleAxisx(ea[1], Vector3::Unit##Y()) * AngleAxisx(ea[2], Vector3::Unit##Z()))); \\\r\n  }\r\n  VERIFY_EULER(0,1,2, X,Y,Z);\r\n  VERIFY_EULER(0,1,0, X,Y,X);\r\n  VERIFY_EULER(0,2,1, X,Z,Y);\r\n  VERIFY_EULER(0,2,0, X,Z,X);\r\n\r\n  VERIFY_EULER(1,2,0, Y,Z,X);\r\n  VERIFY_EULER(1,2,1, Y,Z,Y);\r\n  VERIFY_EULER(1,0,2, Y,X,Z);\r\n  VERIFY_EULER(1,0,1, Y,X,Y);\r\n\r\n  VERIFY_EULER(2,0,1, Z,X,Y);\r\n  VERIFY_EULER(2,0,2, Z,X,Z);\r\n  VERIFY_EULER(2,1,0, Z,Y,X);\r\n  VERIFY_EULER(2,1,2, Z,Y,Z);\r\n}\r\n\r\nvoid test_geo_eulerangles()\r\n{\r\n  for(int i = 0; i < g_repeat; i++) {\r\n    CALL_SUBTEST_1( eulerangles<float>() );\r\n    CALL_SUBTEST_2( eulerangles<double>() );\r\n  }\r\n}\r\n", "meta": {"hexsha": "192cbb3c5c2cd7d613e9ab571a0a41818ff260ca", "size": 1651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen/test/geo_eulerangles.cpp", "max_stars_repo_name": "trondkr/tools", "max_stars_repo_head_hexsha": "ffd1c812b63229e4d5048192488b72d34e5f2901", "max_stars_repo_licenses": ["MIT"], "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/geo_eulerangles.cpp", "max_issues_repo_name": "trondkr/tools", "max_issues_repo_head_hexsha": "ffd1c812b63229e4d5048192488b72d34e5f2901", "max_issues_repo_licenses": ["MIT"], "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/geo_eulerangles.cpp", "max_forks_repo_name": "trondkr/tools", "max_forks_repo_head_hexsha": "ffd1c812b63229e4d5048192488b72d34e5f2901", "max_forks_repo_licenses": ["MIT"], "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": 30.0181818182, "max_line_length": 156, "alphanum_fraction": 0.6420351302, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.566791133102947}}
{"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": "#include <math_lib/line_3d.h>\n\n#include <gtest/gtest.h>\n\n#include <boost/qvm/vec_operations.hpp>\n\nusing namespace pagoda;\n\nTEST(Line3D, when_using_default_constructor_should_create_the_x_axis)\n{\n\tLine3D<float> l;\n\tASSERT_TRUE(l.GetPoint() == (Vec3F{0, 0, 0}));\n\tASSERT_TRUE(l.GetSupportVector() == (Vec3F{1, 0, 0}));\n}\n\nTEST(Line3D, when_using_point_direction_constructor_should_create_the_respective_line)\n{\n\tLine3D<float> l(Vec3F{1, 2, 3}, Vec3F{0, 1, 0});\n\tASSERT_TRUE(l.GetPoint() == (Vec3F{1, 2, 3}));\n\tASSERT_TRUE(l.GetSupportVector() == (Vec3F{0, 1, 0}));\n}\n\nTEST(Line3D, when_using_two_points_static_constructor_should_create_the_respective_line)\n{\n\tLine3D<float> l = Line3D<float>::FromTwoPoints(Vec3F{1, 2, 3}, Vec3F{3, 2, 3});\n\tASSERT_TRUE(l.GetPoint() == (Vec3F{1, 2, 3}));\n\tASSERT_TRUE(l.GetSupportVector() == (Vec3F{1, 0, 0}));\n}\n\nTEST(Line3D, when_comparing_two_equal_lines_should_evaluate_to_equal)\n{\n\tLine3D<float> l1;\n\tLine3D<float> l2(Vec3F{0, 0, 0}, Vec3F{1, 0, 0});\n\tASSERT_TRUE(l1 == l2);\n\tASSERT_FALSE(l1 != l2);\n}\n\nTEST(Line3D, when_comparing_two_different_lines_should_evaluate_to_not_equal)\n{\n\tLine3D<float> l1(Vec3F{0, 0, 0}, Vec3F{1, 1, 0});\n\tLine3D<float> l2(Vec3F{0, 0, 0}, Vec3F{1, 0, 0});\n\tASSERT_FALSE(l1 == l2);\n\tASSERT_TRUE(l1 != l2);\n}\n", "meta": {"hexsha": "27a2f3744e44f701b9a4f7580886d48db9e45968", "size": 1272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit_tests/math_lib/line_3d.cpp", "max_stars_repo_name": "diegoarjz/selector", "max_stars_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T17:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-12T14:37:27.000Z", "max_issues_repo_path": "tests/unit_tests/math_lib/line_3d.cpp", "max_issues_repo_name": "diegoarjz/selector", "max_issues_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47.0, "max_issues_repo_issues_event_min_datetime": "2019-05-27T15:24:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T17:54:54.000Z", "max_forks_repo_path": "tests/unit_tests/math_lib/line_3d.cpp", "max_forks_repo_name": "diegoarjz/selector", "max_forks_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2666666667, "max_line_length": 88, "alphanum_fraction": 0.713836478, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5667395917352291}}
{"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": "/*===================================================================\r\n\r\nThe Medical Imaging Interaction Toolkit (MITK)\r\n\r\nCopyright (c) German Cancer Research Center,\r\nDivision of Medical and Biological Informatics.\r\nAll rights reserved.\r\n\r\nThis software is distributed WITHOUT ANY WARRANTY; without\r\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\r\nA PARTICULAR PURPOSE.\r\n\r\nSee LICENSE.txt or http://www.mitk.org for details.\r\n\r\n===================================================================*/\r\n\r\n#include \"mitkCommandLineParser.h\"\r\n#include \"mitkImage.h\"\r\n#include \"mitkImageStatisticsCalculator.h\"\r\n#include \"mitkIOUtil.h\"\r\n#include <iostream>\r\n#include <usAny.h>\r\n#include <fstream>\r\n#include <itkImageRegionConstIterator.h>\r\n#include \"mitkImageAccessByItk.h\"\r\n#include <boost/accumulators/accumulators.hpp>\r\n#include <boost/accumulators/statistics/stats.hpp>\r\n#include <boost/accumulators/statistics/mean.hpp>\r\n#include <boost/accumulators/statistics/variance.hpp>\r\n#include <boost/accumulators/statistics/min.hpp>\r\n#include <boost/accumulators/statistics/max.hpp>\r\n#include <boost/accumulators/statistics/count.hpp>\r\n#include <boost/accumulators/statistics/moment.hpp>\r\n#include <mitkImageMaskGenerator.h>\r\n#include <mitkIgnorePixelMaskGenerator.h>\r\n\r\nstruct statistics_res{\r\n    double mean, variance, min, max, count, moment;\r\n};\r\n\r\nvoid printstats(statistics_res s)\r\n{\r\n    std::cout << \"mean: \" << s.mean << std::endl\r\n              << \"variance: \" << s.variance << std::endl\r\n              << \"min: \" << s.min << std::endl\r\n              << \"max: \" << s.max << std::endl\r\n              << \"count: \" << s.count << std::endl\r\n              << \"moment: \" << s.moment << std::endl;\r\n}\r\n\r\ntemplate < typename TPixel, unsigned int VImageDimension >\r\nvoid get_statistics_boost(itk::Image<TPixel, VImageDimension>* itkImage, statistics_res& res){\r\n    typedef itk::Image<TPixel, VImageDimension> ImageType;\r\n\r\n    itk::ImageRegionConstIterator<ImageType> it(itkImage, itkImage->GetLargestPossibleRegion());\r\n\r\n    TPixel currentPixel;\r\n    int ctr=0;\r\n    double sum=0;\r\n\r\n    boost::accumulators::accumulator_set<double, boost::accumulators::stats<\r\n            boost::accumulators::tag::mean,\r\n            boost::accumulators::tag::variance,\r\n            boost::accumulators::tag::min,\r\n            boost::accumulators::tag::max,\r\n            boost::accumulators::tag::count,\r\n            boost::accumulators::tag::moment<2>> > acc;\r\n\r\n    for (it.GoToBegin(); !it.IsAtEnd(); ++it)\r\n    {\r\n        acc(it.Get());\r\n//        currentPixel = it.Get();\r\n//        sum+=currentPixel;\r\n//        ctr+=1;\r\n    }\r\n\r\n//    res.mean=(double)sum/(double)ctr;\r\n    res.mean = boost::accumulators::mean(acc);\r\n    res.variance = boost::accumulators::variance(acc);\r\n    res.min = boost::accumulators::min(acc);\r\n    res.max = boost::accumulators::max(acc);\r\n    res.count = boost::accumulators::count(acc);\r\n    res.moment = boost::accumulators::moment<2>(acc);\r\n\r\n    std::cout << \"sum: \" << sum << \" N: \" <<  ctr << \" mean: \" << res.mean << std::endl;\r\n}\r\n\r\nint main( int argc, char* argv[] )\r\n{\r\n    mitkCommandLineParser parser;\r\n\r\n    parser.setTitle(\"Extract Image Statistics\");\r\n    parser.setCategory(\"Preprocessing Tools\");\r\n    parser.setDescription(\"\");\r\n    parser.setContributor(\"MBI\");\r\n\r\n    parser.setArgumentPrefix(\"--\", \"-\");\r\n    parser.addArgument(\"help\", \"h\", mitkCommandLineParser::String, \"Help:\", \"Show this help text\");\r\n    parser.addArgument(\"input\", \"i\", mitkCommandLineParser::InputFile, \"Input:\", \"input image\", us::Any(),false);\r\n    parser.addArgument(\"mask\", \"m\", mitkCommandLineParser::InputFile, \"Mask:\", \"mask image / roi image denotin area on which statistics are calculated\", us::Any(),true);\r\n    parser.addArgument(\"out\", \"o\", mitkCommandLineParser::OutputFile, \"Output\", \"output file (default: filenameOfRoi.nrrd_statistics.txt)\", us::Any());\r\n\r\n    std::cout << \"test....\" << std::endl;\r\n\r\n    std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);\r\n    std::cout << \"parsedArgs.size()= \" << parsedArgs.size() << std::endl;\r\n    if (parsedArgs.size()==0 || parsedArgs.count(\"help\") || parsedArgs.count(\"h\"))\r\n    {\r\n      std::cout << \"\\n\\n MiniApp Description: \\nCalculates statistics on the supplied image using given mask.\" << endl;\r\n      std::cout << \"Output is written to the designated output file in this order:\" << endl;\r\n      std::cout << \"Mean, Standard Deviation, RMS, Max, Min, Number of Voxels, Volume [mm3]\" << endl;\r\n      std::cout << \"\\n\\n Parameters:\"<< endl;\r\n      std::cout << parser.helpText();\r\n      return EXIT_SUCCESS;\r\n    }\r\n\r\n\r\n    // Parameters:\r\n    bool ignoreZeroValues = false;\r\n    unsigned int timeStep = 0;\r\n\r\n    std::string inputImageFile = us::any_cast<std::string>(parsedArgs[\"input\"]);\r\n    mitk::Image::Pointer maskImage;\r\n    if (parsedArgs.count(\"mask\") || parsedArgs.count(\"m\"))\r\n    {\r\n        std::string maskImageFile = us::any_cast<std::string>(parsedArgs[\"mask\"]);\r\n        maskImage = mitk::IOUtil::LoadImage(maskImageFile);\r\n    }\r\n\r\n    std::string outFile;\r\n    if (parsedArgs.count(\"out\") || parsedArgs.count(\"o\") )\r\n      outFile = us::any_cast<std::string>(parsedArgs[\"out\"]);\r\n    else\r\n      outFile = inputImageFile + \"_statistics.txt\";\r\n\r\n    // Load image and mask\r\n    mitk::Image::Pointer inputImage = mitk::IOUtil::LoadImage(inputImageFile);\r\n\r\n    // Calculate statistics\r\n    mitk::ImageStatisticsCalculator::StatisticsContainer::Pointer statisticsStruct;\r\n    mitk::ImageStatisticsCalculator::Pointer calculator = mitk::ImageStatisticsCalculator::New();\r\n    try\r\n    {\r\n      calculator->SetInputImage(inputImage);\r\n      if (parsedArgs.count(\"mask\") || parsedArgs.count(\"m\"))\r\n      {\r\n          mitk::ImageMaskGenerator::Pointer imgMask = mitk::ImageMaskGenerator::New();\r\n          imgMask->SetImageMask(maskImage);\r\n          imgMask->SetTimeStep(timeStep);\r\n          calculator->SetMask(imgMask.GetPointer());\r\n      }\r\n      else\r\n      {\r\n          calculator->SetMask(nullptr);\r\n      }\r\n\r\n    }\r\n    catch( const itk::ExceptionObject& e)\r\n    {\r\n      MITK_ERROR << \"Statistic Calculation Failed - ITK Exception:\" << e.what();\r\n      return -1;\r\n    }\r\n\r\n\r\n    if (ignoreZeroValues)\r\n    {\r\n        // TODO, cannot have more than one mask, using ignore pixel value will override the image mask :-c\r\n        mitk::IgnorePixelMaskGenerator::Pointer ignorePixelMask = mitk::IgnorePixelMaskGenerator::New();\r\n        ignorePixelMask->SetInputImage(inputImage);\r\n        ignorePixelMask->SetTimeStep(timeStep);\r\n        ignorePixelMask->SetIgnoredPixelValue(0);\r\n        calculator->SetMask(ignorePixelMask.GetPointer());\r\n    }\r\n\r\n    std::cout << \"calculating statistics itk: \" << std::endl;\r\n    try\r\n    {\r\n        statisticsStruct = calculator->GetStatistics(timeStep);\r\n    }\r\n    catch ( mitk::Exception& e)\r\n    {\r\n      MITK_ERROR<< \"MITK Exception: \" << e.what();\r\n      return -1;\r\n    }\r\n\r\n\r\n    // Calculate Volume\r\n    double volume = 0;\r\n    const mitk::BaseGeometry *geometry = inputImage->GetGeometry();\r\n    if ( geometry != NULL )\r\n    {\r\n      const mitk::Vector3D &spacing = inputImage->GetGeometry()->GetSpacing();\r\n      volume = spacing[0] * spacing[1] * spacing[2] * (double) statisticsStruct->GetN();\r\n    }\r\n\r\n    // Write Results to file\r\n    std::ofstream output;\r\n    output.open(outFile.c_str());\r\n    output << statisticsStruct->GetMean() << \" , \";\r\n    output << statisticsStruct->GetStd() << \" , \";\r\n    output << statisticsStruct->GetRMS() << \" , \";\r\n    output << statisticsStruct->GetMax() << \" , \";\r\n    output << statisticsStruct->GetMin() << \" , \";\r\n    output << statisticsStruct->GetN() << \" , \";\r\n    output << volume << \"\\n\";\r\n\r\n    output.flush();\r\n    output.close();\r\n\r\n    std::cout << \"calculating statistics boost: \" << std::endl;\r\n\r\n    statistics_res res;\r\n    AccessByItk_n(inputImage, get_statistics_boost, (res));\r\n\r\n    printstats(res);\r\n\r\n    return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "60aff83400800237c59b2742072b574b05154f8e", "size": 7978, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/DiffusionImaging/MiniApps/ImageStatisticsMiniApp.cpp", "max_stars_repo_name": "liu3xing3long/MITK-2016.11", "max_stars_repo_head_hexsha": "385c506f9792414f40337e106e13d5fd61aa3ccc", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Modules/DiffusionImaging/MiniApps/ImageStatisticsMiniApp.cpp", "max_issues_repo_name": "liu3xing3long/MITK-2016.11", "max_issues_repo_head_hexsha": "385c506f9792414f40337e106e13d5fd61aa3ccc", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/DiffusionImaging/MiniApps/ImageStatisticsMiniApp.cpp", "max_forks_repo_name": "liu3xing3long/MITK-2016.11", "max_forks_repo_head_hexsha": "385c506f9792414f40337e106e13d5fd61aa3ccc", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4292237443, "max_line_length": 170, "alphanum_fraction": 0.6227124593, "num_tokens": 1898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5667309702217254}}
{"text": "//==================================================================================================\n/*\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n//! [aligned_input_range]\n#include <boost/simd/range/aligned_input_range.hpp>\n#include <boost/simd/memory/allocator.hpp>\n#include <boost/simd/function/sum.hpp>\n#include <boost/simd/pack.hpp>\n#include <iostream>\n#include <vector>\n\nint main()\n{\n  std::vector<float, boost::simd::allocator<float>> x{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};\n\n  boost::simd::pack<float> r{0};\n  auto pr = boost::simd::aligned_input_range(x);\n  for(auto const& e : pr) r += e;\n\n  std::cout << \"Sum of [1 ... 16] is \" << boost::simd::sum(r) << std::endl;\n\n  return 0;\n}\n//! [aligned_input_range]\n", "meta": {"hexsha": "9ac8fdb05932ccbf8e579da48a935c48956ab185", "size": 954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/aligned_input_range.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "test/doc/aligned_input_range.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/doc/aligned_input_range.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 31.8, "max_line_length": 100, "alphanum_fraction": 0.5387840671, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.566730963819741}}
{"text": "// Copyright 2019 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_fill_weighted_profile\n\n#include <boost/format.hpp>\n#include <boost/histogram.hpp>\n#include <cassert>\n#include <iostream>\n#include <sstream>\n\nint main() {\n  using namespace boost::histogram;\n  using namespace boost::histogram::literals; // _c suffix creates compile-time numbers\n\n  // make 2D weighted profile\n  auto h = make_weighted_profile(axis::integer<>(0, 2), axis::integer<>(0, 2));\n\n  // The mean is computed from the values marked with the sample() helper function.\n  // Weights can be passed as well. The `sample` and `weight` arguments can appear in any\n  // order, but they must be the first or last arguments.\n  h(0, 0, sample(1));            // sample goes to cell (0, 0); weight is 1\n  h(0, 0, sample(2), weight(3)); // sample goes to cell (0, 0); weight is 3\n  h(1, 0, sample(3));            // sample goes to cell (1, 0); weight is 1\n  h(1, 0, sample(4));            // sample goes to cell (1, 0); weight is 1\n  h(0, 1, sample(5));            // sample goes to cell (1, 0); weight is 1\n  h(0, 1, sample(6));            // sample goes to cell (1, 0); weight is 1\n  h(1, 1, weight(4), sample(7)); // sample goes to cell (1, 1); weight is 4\n  h(weight(5), sample(8), 1, 1); // sample goes to cell (1, 1); weight is 5\n\n  std::ostringstream os;\n  for (auto&& x : indexed(h)) {\n    const auto i = x.index(0_c);\n    const auto j = x.index(1_c);\n    const auto m = x->value();    // weighted mean\n    const auto v = x->variance(); // estimated variance of weighted mean\n    os << boost::format(\"index %i,%i mean %.1f variance %.1f\\n\") % i % j % m % v;\n  }\n\n  std::cout << os.str() << std::flush;\n\n  assert(os.str() == \"index 0,0 mean 1.8 variance 0.5\\n\"\n                     \"index 1,0 mean 3.5 variance 0.5\\n\"\n                     \"index 0,1 mean 5.5 variance 0.5\\n\"\n                     \"index 1,1 mean 7.6 variance 0.5\\n\");\n}\n\n//]\n", "meta": {"hexsha": "767bfad86122b1539f65c29ca55e5e097616287a", "size": 2045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/histogram/examples/guide_fill_weighted_profile.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 188.0, "max_stars_repo_stars_event_min_datetime": "2019-02-08T14:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T08:37:05.000Z", "max_issues_repo_path": "libs/histogram/examples/guide_fill_weighted_profile.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 186.0, "max_issues_repo_issues_event_min_datetime": "2016-05-05T14:01:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-20T22:38:43.000Z", "max_forks_repo_path": "libs/histogram/examples/guide_fill_weighted_profile.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2019-02-09T16:16:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T20:24:36.000Z", "avg_line_length": 39.3269230769, "max_line_length": 89, "alphanum_fraction": 0.6063569682, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7122321964553658, "lm_q1q2_score": 0.5666933162354836}}
{"text": "//  (C) Copyright 2006 Eric Niebler, Olivier Gygi\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/random.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/weighted_variance.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    // lazy weighted_variance\n    accumulator_set<int, stats<tag::weighted_variance(lazy)>, int> acc1;\n\n    acc1(1, weight = 2);    //  2\n    acc1(2, weight = 3);    //  6\n    acc1(3, weight = 1);    //  3\n    acc1(4, weight = 4);    // 16\n    acc1(5, weight = 1);    //  5\n\n    // weighted_mean = (2+6+3+16+5) / (2+3+1+4+1) = 32 / 11 = 2.9090909090909090909090909090909\n\n    BOOST_CHECK_EQUAL(5u, count(acc1));\n    BOOST_CHECK_CLOSE(2.9090909, weighted_mean(acc1), 1e-5);\n    BOOST_CHECK_CLOSE(10.1818182, weighted_moment<2>(acc1), 1e-5);\n    BOOST_CHECK_CLOSE(1.7190083, weighted_variance(acc1), 1e-5);\n\n    accumulator_set<int, stats<tag::weighted_variance>, int> acc2;\n\n    acc2(1, weight = 2);\n    acc2(2, weight = 3);\n    acc2(3, weight = 1);\n    acc2(4, weight = 4);\n    acc2(5, weight = 1);\n\n    BOOST_CHECK_EQUAL(5u, count(acc2));\n    BOOST_CHECK_CLOSE(2.9090909, weighted_mean(acc2), 1e-5);\n    BOOST_CHECK_CLOSE(1.7190083, weighted_variance(acc2), 1e-5);\n\n    // check lazy and immediate variance with random numbers\n\n    // two random number generators\n    boost::lagged_fibonacci607 rng;\n    boost::normal_distribution<> mean_sigma(0,1);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal(rng, mean_sigma);\n\n    accumulator_set<double, stats<tag::weighted_variance(lazy)>, double > acc_lazy;\n    accumulator_set<double, stats<tag::weighted_variance>, double > acc_immediate;\n\n    for (std::size_t i=0; i<10000; ++i)\n    {\n        double value = normal();\n        acc_lazy(value, weight = rng());\n        acc_immediate(value, weight = rng());\n    }\n\n    BOOST_CHECK_CLOSE(1., weighted_variance(acc_lazy), 1.);\n    BOOST_CHECK_CLOSE(1., weighted_variance(acc_immediate), 1.);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"weighted_variance test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n", "meta": {"hexsha": "9c19aed6aefc47766712b081a7d7119b2a82cb79", "size": 2751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/accumulators/test/weighted_variance.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/accumulators/test/weighted_variance.cpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/accumulators/test/weighted_variance.cpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5487804878, "max_line_length": 113, "alphanum_fraction": 0.6510359869, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5666933113754372}}
{"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_LDEXP_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_LDEXP_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing ldexp capabilities\n\n    The function multiply a floating entry \\f$x\\f$\n    by \\f$2^{n}\\f$\n\n    @ref cardinal_of the types of x and n must be identical\n\n    @par Semantic:\n\n    @code\n    T r = ldexp(x,n);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = x*pow(2, n);\n    @endcode\n\n  **/\n  const boost::dispatch::functor<tag::ldexp_> ldexp = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/ldexp.hpp>\n#include <boost/simd/function/simd/ldexp.hpp>\n\n#endif\n", "meta": {"hexsha": "9556146dad2825dc72d512a31524344b192fd697", "size": 1107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/ldexp.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/ldexp.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/ldexp.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.14, "max_line_length": 100, "alphanum_fraction": 0.5654923216, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5666933065153908}}
{"text": "// Copyright \u00a9 2016-2021 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n\n#include <boost/math/special_functions/fpclassify.hpp> // isnan\n#include <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\u00edkelihood 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": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Alpha_shape_3.h>\n#include <CGAL/Alpha_shape_cell_base_3.h>\n#include <CGAL/Alpha_shape_vertex_base_3.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n\n#include <fstream>\n#include <vector>\n\n#include <boost/unordered_set.hpp>\n#include <boost/unordered_map.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Gt;\n\ntypedef CGAL::Alpha_shape_vertex_base_3<Gt>          Vb;\ntypedef CGAL::Alpha_shape_cell_base_3<Gt>            Fb;\ntypedef CGAL::Triangulation_data_structure_3<Vb,Fb>  Tds;\ntypedef CGAL::Delaunay_triangulation_3<Gt,Tds>       Triangulation_3;\ntypedef CGAL::Alpha_shape_3<Triangulation_3>         Alpha_shape_3;\n\ntypedef Gt::Point_3                                  Point;\ntypedef Alpha_shape_3::Alpha_iterator                Alpha_iterator;\n\nint main()\n{\n  std::vector<Point> points;\n\n//read input\n  std::ifstream is(\"data/bunny_5000\");\n  int n;\n  is >> n;\n  double x, y, z;\n  for (int i=0;i<n;++i)\n  {\n    is >> x >> y >> z;\n    points.push_back( Point(x, y, z) );\n  }\n\n  std::cerr << points.size() << \" points read.\\n\";\n// compute alpha shape\n  Alpha_shape_3 as(points.begin(), points.end());\n  Alpha_shape_3::NT alpha_solid = as.find_alpha_solid();\n  as.set_alpha(alpha_solid);\n\n  std::cerr << \"alpha_solid = \" << alpha_solid << \"\\n\";\n  std::cerr << as.number_of_solid_components() << \" number of solid components\\n\";\n\n// collect alpha-shape facets accessible from the infinity\n  // marks the cells that are in the same component as the infinite vertex by flooding\n  boost::unordered_set< Alpha_shape_3::Cell_handle > marked_cells;\n  std::vector< Alpha_shape_3::Cell_handle > queue;\n  queue.push_back( as.infinite_cell() );\n\n  while(!queue.empty())\n  {\n    Alpha_shape_3::Cell_handle back = queue.back();\n    queue.pop_back();\n\n    if ( !marked_cells.insert(back).second ) continue; //already visited\n\n    for (int i=0; i<4; ++i)\n    {\n      if (as.classify(Alpha_shape_3::Facet(back, i))==Alpha_shape_3::EXTERIOR &&\n          marked_cells.count(back->neighbor(i))==0)\n        queue.push_back( back->neighbor(i) );\n    }\n  }\n\n  // filter regular facets to restrict them to those adjacent to a marked cell\n  std::vector< Alpha_shape_3::Facet > regular_facets;\n  as.get_alpha_shape_facets(std::back_inserter( regular_facets ), Alpha_shape_3::REGULAR );\n\n  std::vector<Alpha_shape_3::Facet> filtered_regular_facets;\n  for(Alpha_shape_3::Facet f : regular_facets)\n  {\n    if ( marked_cells.count(f.first)==1 )\n      filtered_regular_facets.push_back(f);\n    else\n    {\n      f = as.mirror_facet(f);\n      if ( marked_cells.count(f.first)==1 )\n        filtered_regular_facets.push_back(f);\n    }\n  }\n\n// dump into OFF format\n  // assign an id per vertex\n  boost::unordered_map< Alpha_shape_3::Vertex_handle, std::size_t> vids;\n  points.clear();\n\n  for(Alpha_shape_3::Facet f : filtered_regular_facets)\n  {\n    for (int i=1;i<4; ++i)\n    {\n      Alpha_shape_3::Vertex_handle vh = f.first->vertex((f.second+i)%4);\n      if (vids.insert( std::make_pair(vh, points.size()) ).second)\n        points.push_back( vh->point() );\n    }\n  }\n\n  // writing\n  std::ofstream output(\"out.off\");\n  output << \"OFF\\n \" << points.size() << \" \" << filtered_regular_facets.size() << \" 0\\n\";\n  std::copy(points.begin(), points.end(), std::ostream_iterator<Point>(output, \"\\n\"));\n  for(const Alpha_shape_3::Facet& f : filtered_regular_facets)\n  {\n    output << 3;\n\n    for (int i=0;i<3; ++i)\n    {\n      Alpha_shape_3::Vertex_handle vh = f.first->vertex( as.vertex_triple_index(f.second, i) );\n      output << \" \" << vids[vh];\n    }\n    output << \"\\n\";\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "f12c5233acb3f1ae95d7495641eb45eafb2e4213", "size": 3646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Alpha_shapes_3/examples/Alpha_shapes_3/visible_alpha_shape_facets_to_OFF.cpp", "max_stars_repo_name": "brucerennie/cgal", "max_stars_repo_head_hexsha": "314b94aafa9b08a1d086accd2cadff1aae1b57a9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Alpha_shapes_3/examples/Alpha_shapes_3/visible_alpha_shape_facets_to_OFF.cpp", "max_issues_repo_name": "brucerennie/cgal", "max_issues_repo_head_hexsha": "314b94aafa9b08a1d086accd2cadff1aae1b57a9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Alpha_shapes_3/examples/Alpha_shapes_3/visible_alpha_shape_facets_to_OFF.cpp", "max_forks_repo_name": "brucerennie/cgal", "max_forks_repo_head_hexsha": "314b94aafa9b08a1d086accd2cadff1aae1b57a9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 30.3833333333, "max_line_length": 95, "alphanum_fraction": 0.6684037301, "num_tokens": 1030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5666307060515731}}
{"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": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\ntemplate <int ROWS>\nusing VecNd = Eigen::Matrix<double, ROWS, 1>;\n\ntemplate <int ROWS, int COLS>\nusing MatNd = Eigen::Matrix<double, ROWS, COLS>;\n\ntemplate <int ROWS>\nusing VecNf = Eigen::Matrix<float, ROWS, 1>;\n\ntemplate <int ROWS, int COLS>\nusing MatNf = Eigen::Matrix<float, ROWS, COLS>;\n\nusing VecXd = Eigen::VectorXd;\nusing MatXd = Eigen::MatrixXd;\n\nusing VecXf = Eigen::VectorXf;\nusing MatXf = Eigen::MatrixXf;\n\ntemplate <int ROWS>\nusing SquareMatNd = Eigen::Matrix<double, ROWS, ROWS>;\n\ntemplate <typename Eig>\nusing StdVector = std::vector<Eig, Eigen::aligned_allocator<Eig>>;\n\nnamespace jcc {\nusing Vec1 = VecNd<1>;\nusing Vec2 = Eigen::Vector2d;\nusing Vec3 = Eigen::Vector3d;\nusing Vec4 = Eigen::Vector4d;\nusing Vec5 = VecNd<5>;\nusing Vec6 = VecNd<6>;\n\nusing Vec1f = VecNf<1>;\nusing Vec2f = Eigen::Vector2f;\nusing Vec3f = Eigen::Vector3f;\nusing Vec4f = Eigen::Vector4f;\nusing Vec5f = VecNf<5>;\nusing Vec6f = VecNf<6>;\n\nusing Vec2i = Eigen::Matrix<int, 2, 1>;\nusing Vec3i = Eigen::Matrix<int, 3, 1>;\nusing Vec4i = Eigen::Matrix<int, 4, 1>;\n\n}  // namespace jcc\n", "meta": {"hexsha": "4bea9a6745fb148052ae0d7c90a547103dd69607", "size": 1134, "ext": "hh", "lang": "C++", "max_stars_repo_path": "eigen.hh", "max_stars_repo_name": "jpanikulam/experiments", "max_stars_repo_head_hexsha": "be36319a89f8baee54d7fa7618b885edb7025478", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-14T11:40:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-14T11:40:28.000Z", "max_issues_repo_path": "eigen.hh", "max_issues_repo_name": "jpanikulam/experiments", "max_issues_repo_head_hexsha": "be36319a89f8baee54d7fa7618b885edb7025478", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-04-18T13:54:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T20:04:17.000Z", "max_forks_repo_path": "eigen.hh", "max_forks_repo_name": "jpanikulam/experiments", "max_forks_repo_head_hexsha": "be36319a89f8baee54d7fa7618b885edb7025478", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-24T03:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-24T03:45:47.000Z", "avg_line_length": 22.68, "max_line_length": 66, "alphanum_fraction": 0.7072310406, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5666306911200161}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <utility>\n#include <cmath>\n#include <boost/test/minimal.hpp>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\nusing namespace std;  \nusing namespace mtl;  \n   \n\ntemplate <typename Vector, typename Matrix>\nclass f_ftor\n{\n    typedef typename Collection<Vector>::value_type value_type;\n\n  public:\n    /// Arguments: each stock's ROI, the aimed ROI, the Langrange factor and the covariance\n    f_ftor(const Vector& rv, value_type r, value_type lg, const Matrix& S) \n      : rv(rv), r(r), lg(lg), S(S) {}\n\n    value_type operator()(const Vector& pi) const\n    {\n\tVector S_pi(S * pi);\n\treturn lg * sq(sum(pi) - 1) + lg * sq(dot(pi, rv) - r) + trans(pi) * S_pi;\n    }\n    value_type sq(value_type x) const { return x * x; }\n\n  private:\n    Vector      rv;\n    value_type  r, lg;\n    Matrix      S;\n};\n\n\ntemplate <typename Vector, typename Matrix>\nclass grad_f_ftor\n{\n    typedef typename Collection<Vector>::value_type value_type;\n\n  public:\n    /// Arguments: each stock's ROI, the aimed ROI, the Langrange factor and the covariance\n    grad_f_ftor(const Vector& rv, value_type r, value_type lg, const Matrix& S) \n      : rv(rv), onev(size(rv), 1), r(r), lg(lg), S(S) {}\n\n    Vector operator()(const Vector& pi) const\n    {\n\tvalue_type f1= 2.0 * lg * (sum(pi) - 1), f2= 2.0 * lg * (dot(pi, rv) - r);\n\treturn Vector(f1 * onev + f2 * rv + 2.0 * S * pi);\n    }\n\n  private:\n    Vector      rv, onev;\n    value_type  r, lg;\n    Matrix      S;\n};\n\n\ntemplate <typename Vector, typename Matrix>\nclass portfolio_optimizer\n{\n    typedef typename Collection<Vector>::value_type value_type;\n    \n  public:\n    /// Arguments: each stock's ROI, the aimed ROI and the covariance\n    portfolio_optimizer(const Vector& rv, value_type r, const Matrix& S) \n      : s(size(rv) + 2), A(s, s), b(s, value_type(0))\n    {\n\tunsigned s2= size(rv);\n\tA[irange(s2)][irange(s2)]= S; A[irange(s2)][s2]= Vector(s2, 1); A[irange(s2)][s2+1]= rv;\n\tA[s2][irange(s2)]= trans(Vector(s2, 1)); A[irange(s2, s)][irange(s2, s)]= 0;\n\tA[s2+1][irange(s2)]= trans(rv);\n\n\tb[s2]= 1; b[s2+1]= r;\n\tcout << \"A is\\n\" << A << \"\\nb is \" << b << '\\n';\n    }\n\n    Vector operator()() const {\treturn clone(lu_solve(A, b)[irange(s-2)]); }\n\n  private:\n\n    unsigned    s;\n    Matrix      A;\n    Vector      b;\n };\n\n\n\nint test_main(int, char**)\n{\n    using namespace mtl;\n\n    dense_vector<double>       pi(4, 0.25), rv(4);\n    rv= 1.03, 1.14, 1.05, 1.08;\n\n    dense2D<double>            S(4, 4);\n#if 1\n    S= 1.0, 0.1, 0.3, -0.2,\n\t0.1, 1., -0.4, 0.7,\n\t0.3, -0.4, 1., 0.4,\n\t-0.2, 0.7, 0.4, 1.;\n#else\n    S= 1.0, 0.1, 0.3, 0.2,\n\t0.1, 1., 0.4, 0.7,\n\t0.3, 0.4, 1., 0.4,\n\t0.2, 0.7, 0.4, 1.;\n#endif\n\n    const double lagrange= 10000.0;\n    f_ftor< dense_vector<double>, dense2D<double> >  f(rv, 1.09, lagrange, S);\n    cout << \"f(pi) is \" << f(pi) << '\\n';\n\n    grad_f_ftor< dense_vector<double>, dense2D<double> >  grad_f(rv, 1.09, lagrange, S);\n    cout << \"grad_f(pi) is \" << grad_f(pi) << '\\n';\n    \n    portfolio_optimizer< dense_vector<double>, dense2D<double> >  opt(rv, 1.09, S);\n    dense_vector<double>       pi_opt(opt()); \n    cout << \"Optimal portfolio is \" << pi_opt << \"\\n\";\n\n    std::cout<< \"Sum of pi is \" << sum(pi_opt) << \"\\n\";\n    std::cout<< \"Overall ROI is \" << dot(pi_opt, rv) << \"\\n\";\n    std::cout<< \"Variance is \" << dot(pi_opt, dense_vector<double>(S * pi_opt)) << \"\\n\";\n\n#if 1\n    std::cout<< \"Sum of pi is \" << sum(pi) << \"\\n\";\n    std::cout<< \"Overall ROI is \" << dot(pi, rv) << \"\\n\";\n    std::cout<< \"Variance is \" << dot(pi, dense_vector<double>(S * pi)) << \"\\n\";\n\n    itl::cyclic_iteration<double> iter(grad_f(pi), 1000, 0, 1e-5, 10);\n    quasi_newton(pi, f, grad_f, itl::armijo<>(), itl::sr1(), iter);\n    iter.error_code();    \n\n    std::cout<< \"pi= \" << pi << \"\\n\";\n    std::cout<< \"grad_f(pi)= \" << grad_f(pi) << \"\\n\";\n\n    std::cout<< \"Sum of pi is \" << sum(pi) << \"\\n\";\n    std::cout<< \"Overall ROI is \" << dot(pi, rv) << \"\\n\";\n    std::cout<< \"Variance is \" << dot(pi, dense_vector<double>(S * pi)) << \"\\n\";\n#endif\n\n    return 0;\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "39001db3bcf89a210f1417ca77316d7a0273ea0a", "size": 4518, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/portfolio_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/experimental/portfolio_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/experimental/portfolio_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": 26.4210526316, "max_line_length": 94, "alphanum_fraction": 0.5838866755, "num_tokens": 1525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5666253789847463}}
{"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_ROUND_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ROUND_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing round capabilities\n\n    round(x,n) rounds aways from 0 to n digits:\n\n    @par semantic:\n    For any given value @c x of type @c T and integer n :\n\n    @code\n    T r = round(x{, n});\n    @endcode\n\n    is equivalent to\n\n    @code\n    T r = round(x*exp10(n))*exp10(-n);\n    @endcode\n\n    @par Note:\n\n    n default to 0,\n\n    - n > 0: round to n digits to the right of the decimal point.\n\n    - n = 0: round to the nearest integer.\n\n    - n < 0: round to n digits to the left of the decimal point.\n\n    aways from 0 means that half integer values are rounded to the nearest\n    integer of greatest absolute value\n\n    The current rounding mode has no effect.\n\n    - If x is \\f$\\pm\\infty\\f$ or \\f$\\pm0\\f$, it is returned, unmodified\n    - If arg is a NaN, a NaN is returned\n  **/\n  Value round(Value const & v0);\n\n  //@overload\n  Value round(Value const & x, IntegerValue const &n);\n} }\n#endif\n\n#include <boost/simd/function/scalar/round.hpp>\n#include <boost/simd/function/simd/round.hpp>\n\n#endif\n", "meta": {"hexsha": "74dcafd3f7d3730281a1b9f5b16bbf5e7dc4ba31", "size": 1610, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/round.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/round.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/round.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.0298507463, "max_line_length": 100, "alphanum_fraction": 0.5931677019, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.5666253744948884}}
{"text": "//\n// Created by kerail on 14.07.16.\n//\n#include <iostream>\n#include <map>\n#include <vector>\n#include <algorithm>\n\n#include <boost/function.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include \"geom/SO3.hpp\"\n\ntypedef boost::multiprecision::cpp_dec_float_100 float_100;\ntypedef Eigen::Matrix<float_100, 3, 3> Matrix3f100;\ntypedef SO3<float_100> ReferenceSO3Impl;\n\ntypedef std::vector<Eigen::Vector3d> Vector3dList;\ntypedef std::vector<Matrix3f100> Matrix3f100List;\ntypedef std::map<std::string, Matrix3f100List> Matrix3f100ListMap;\ntypedef std::map<std::string, Vector3dList> Vector3dListMap;\n\nusing std::cout;\nusing std::endl;\n\nclass AbstractTestSO3 {\n public:\n  AbstractTestSO3(const Eigen::Vector3d &v) { }\n  virtual Matrix3f100 getMatrix() = 0;\n  static std::string name();\n};\n\n//class ReferenceSO3: public AbstractTestSO3 {\n// public:\n//  ReferenceSO3(const Eigen::Vector3d &v) : AbstractTestSO3(v), m_so3(v.cast<float_100>()) { }\n//  virtual Matrix3f100 getMatrix() {\n//    return m_so3.getQuaternion().toRotationMatrix();\n//  }\n//  static std::string name() {\n//    return \"Reference\";\n//  }\n//  ReferenceSO3Impl m_so3;\n//};\n//\n//class ReferenceSO3: public AbstractTestSO3 {\n// public:\n//  ReferenceSO3(const Eigen::Vector3d &v) : AbstractTestSO3(v) {\n//    Eigen::Matrix<float_100, 3, 1> axis = v.cast<float_100>();\n//    float_100 angle = axis.norm();\n//    if (angle > 0) {\n//      axis /= angle;\n//    }\n//    m_aa = Eigen::AngleAxis<float_100>(angle, axis);\n//  }\n//  virtual Matrix3f100 getMatrix() {\n//    return m_aa.toRotationMatrix();\n//  }\n//  static std::string name() {\n//    return \"Reference\";\n//  }\n//  Eigen::AngleAxis<float_100> m_aa;\n//};\nclass ReferenceSO3: public AbstractTestSO3 {\n public:\n  ReferenceSO3(const Eigen::Vector3d &v) : AbstractTestSO3(v) {\n    Eigen::Matrix<float_100, 3, 1> axis = v.cast<float_100>();\n    float_100 angle = axis.norm();\n    if (angle > 0) {\n      axis /= angle;\n    }\n    m_aa = Eigen::AngleAxis<float_100>(angle, axis);\n  }\n  virtual Matrix3f100 getMatrix() {\n    return Eigen::Quaternion<float_100>(m_aa).toRotationMatrix();\n  }\n  static std::string name() {\n    return \"Reference\";\n  }\n  Eigen::AngleAxis<float_100> m_aa;\n};\n\nclass TestMySO3Direct: public AbstractTestSO3 {\n public:\n  TestMySO3Direct(const Eigen::Vector3d &v) : AbstractTestSO3(v), m_so3(v) { }\n  virtual Matrix3f100 getMatrix() {\n    return m_so3.getMatrix().cast<float_100>();\n  }\n\n  static std::string name() {\n    return \"My.Direct\";\n  }\n  SO3d m_so3;\n};\n\nclass TestMySO3Quat: public AbstractTestSO3 {\n public:\n  TestMySO3Quat(const Eigen::Vector3d &v) : AbstractTestSO3(v), m_so3(double(v.cast<float_100>().norm()),\n                                                                      v.cast<float_100>().norm() > 0\n                                                                      ? v.cast<float_100>().normalized().cast<double>()\n                                                                      : v) { }\n  virtual Matrix3f100 getMatrix() {\n    return m_so3.getQuaternion().toRotationMatrix().cast<float_100>();\n  }\n  static std::string name() {\n    return \"My.Quater\";\n  }\n\n  SO3d m_so3;\n};\n\nclass TestAngleAxisSO3: public AbstractTestSO3 {\n public:\n  TestAngleAxisSO3(const Eigen::Vector3d &v)\n      : AbstractTestSO3(v), m_aa(v.norm(),\n                                 v.norm() > 0 ? v.normalized().cast<double>()\n                                              : v) { }\n  virtual Matrix3f100 getMatrix() {\n    return m_aa.toRotationMatrix().cast<float_100>();\n  }\n\n  static std::string name() {\n    return \"Eigen.AA\";\n  }\n  Eigen::AngleAxisd m_aa;\n};\n\ntemplate<size_t TEST_COUNT, class Reference, class... T>\nclass PrecisionTests;\n\ntemplate<size_t TEST_COUNT, class Reference, class T, class... Ts>\nclass PrecisionTests<TEST_COUNT, Reference, T, Ts...>: public PrecisionTests<TEST_COUNT, Reference, Ts...> {\n  BOOST_STATIC_ASSERT(std::is_base_of<AbstractTestSO3, T>::value);\n public:\n  void run() {\n    PrecisionTests<TEST_COUNT, Reference, Ts...>::run();\n    Vector3dListMap::const_iterator tests_it = getTests().begin();\n    const Matrix3f100ListMap &refMap = getReferences();\n    for (; tests_it != getTests().end(); ++tests_it) {\n      Matrix3f100ListMap::const_iterator refIt = refMap.find(tests_it->first);\n      cout << T::name() << \"\\t\" << tests_it->first;\n      runTests(tests_it->second, refIt->second);\n      cout << endl;\n    }\n  };\n protected:\n  void runTests(const Vector3dList &v, const Matrix3f100List &references) {\n    std::vector<float_100> errors(v.size());\n#pragma omp parallel for shared(v, errors)\n    for (size_t i = 0; i < v.size(); ++i) {\n      Eigen::Vector3d coeffs(v[i]);\n      T so3(coeffs);\n      errors[i] = matrixDiff(references[i], so3.getMatrix());\n    }\n    float_100 avg, stdDev, stdDevSq, maxErr, minErr;\n    calcMetrics(errors, avg, stdDevSq, minErr, maxErr);\n    std::cout << \"\\t\" << avg << \"\\t\" << sqrt(stdDevSq)\n    << \"\\t\" << minErr << \"\\t\" << maxErr;\n  };\n\n  const Vector3dListMap &getTests() {\n    return PrecisionTests<TEST_COUNT, Reference, Ts...>::getTests();\n  }\n  const Matrix3f100ListMap &getReferences() {\n    return PrecisionTests<TEST_COUNT, Reference, Ts...>::getReferences();\n  }\n\n private :\n  float_100 matrixDiff(const Matrix3f100 &a, const Matrix3f100 &b, const uint8_t type = 2) {\n    switch (type) {\n      case 0:\n        return (a - b).lpNorm<Eigen::Infinity>();\n      case 1:\n        return (a - b).lpNorm<1>();\n      case 2:\n      default:\n        return (a - b).norm();\n    }\n  }\n  void calcMetrics(const std::vector<float_100> &v,\n                   float_100 &avg, float_100 &stdDev,\n                   float_100 &minErr, float_100 &maxErr\n  ) {\n    BOOST_ASSERT(v.size() > 0);\n    float_100 sum = 0;\n    float_100 divider = 1 / float_100(v.size());\n    minErr = v[0];\n    maxErr = v[0];\n    for (size_t i = 0; i < v.size(); ++i) {\n      sum += v[i];\n      minErr = std::min<float_100>(v[i], minErr);\n      maxErr = std::max<float_100>(v[i], maxErr);\n    }\n    sum *= divider;\n    avg = sum;\n\n    sum = 0;\n    for (size_t i = 0; i < v.size(); ++i) {\n      float_100 t = (v[i] - avg);\n      sum += t * t;\n    }\n    sum *= divider;\n    stdDev = sum;\n  }\n};\n\ntemplate<size_t TEST_COUNT, class Reference>\nclass PrecisionTests<TEST_COUNT, Reference> {\n  BOOST_STATIC_ASSERT(TEST_COUNT > 0);\n public:\n  void run() {\n    generateTests();\n    calculateReference();\n    std::cout << \"Method\\tTest\\tAVG Error\\tStdDev Err\\tMin Error\\tMax Error\" << endl;\n  };\n protected:\n\n  const Vector3dListMap &getTests() {\n    return m_tests;\n  }\n  const Matrix3f100ListMap &getReferences() {\n    return m_referenceResults;\n  }\n\n private:\n  void generateTests() {\n    cout << \"Generation of Tests\" << endl;\n    m_tests.insert(std::make_pair(\"USUAL\", Vector3dList(TEST_COUNT)));\n    m_tests.insert(std::make_pair(\"ZERO15\", Vector3dList(TEST_COUNT)));\n    m_tests.insert(std::make_pair(\"ZERO18\", Vector3dList(TEST_COUNT)));\n    m_tests.insert(std::make_pair(\"ZERO22\", Vector3dList(TEST_COUNT)));\n    Vector3dListMap::iterator usualIt = m_tests.find(\"USUAL\");\n    Vector3dListMap::iterator zero15It = m_tests.find(\"ZERO15\");\n    Vector3dListMap::iterator zero18It = m_tests.find(\"ZERO18\");\n    Vector3dListMap::iterator zero22It = m_tests.find(\"ZERO22\");\n\n#pragma omp parallel for shared(usualIt, zero15It, zero18It, zero22It)\n    for (size_t i = 0; i < TEST_COUNT; ++i) {\n      Eigen::Vector3d rnd = Eigen::Vector3d::Random();\n      rnd.normalize();\n      rnd *= M_PI * 2;\n      usualIt->second[i] = rnd;\n      zero15It->second[i] = rnd * 1e-15;\n      zero18It->second[i] = rnd * 1e-18;\n      zero22It->second[i] = rnd * 1e-22;\n    }\n  }\n\n  void calculateReference() {\n    cout << \"Calculation of precise reference\" << endl;\n    for (Vector3dListMap::iterator it = m_tests.begin(); it != m_tests.end(); it++) {\n      cout << \"\\tTest: \" << it->first << endl;\n      m_referenceResults.insert(make_pair(it->first, Matrix3f100List(TEST_COUNT)));\n      Matrix3f100ListMap::iterator vIt = m_referenceResults.find(it->first);\n#pragma omp parallel for shared(vIt, it)\n      for (size_t i = 0; i < TEST_COUNT; ++i) {\n        Eigen::Vector3d coeffs(it->second[i]);\n        Reference so3Ref(coeffs);\n        vIt->second[i] = so3Ref.getMatrix();\n      }\n    }\n\n  }\n\n  Matrix3f100ListMap m_referenceResults;\n  Vector3dListMap m_tests;\n};\n\nint main() {\n  PrecisionTests<size_t(1000000), ReferenceSO3, TestMySO3Direct, TestMySO3Quat, TestAngleAxisSO3>\n      testMachine;\n  testMachine.run();\n}\n\n", "meta": {"hexsha": "6ed36eec12649bffe6917db6fad27994d7c7fa12", "size": 8481, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geom/test/test_so3_precision.cpp", "max_stars_repo_name": "kerail/Daisu", "max_stars_repo_head_hexsha": "d028dd44bf94c3a94897b508beae4efc384bffd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geom/test/test_so3_precision.cpp", "max_issues_repo_name": "kerail/Daisu", "max_issues_repo_head_hexsha": "d028dd44bf94c3a94897b508beae4efc384bffd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geom/test/test_so3_precision.cpp", "max_forks_repo_name": "kerail/Daisu", "max_forks_repo_head_hexsha": "d028dd44bf94c3a94897b508beae4efc384bffd0", "max_forks_repo_licenses": ["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.9525547445, "max_line_length": 119, "alphanum_fraction": 0.6301143733, "num_tokens": 2423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5665074427652865}}
{"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 <fstream>\n#include <vector>\n#include <string>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include \"Day2.hpp\"\n\nint run_day2(std::vector<int> &values, int noun, int verb);\n\nvoid day2() {\n\tstd::ifstream inputFile(\"Data/Day2.txt\");\n\tstd::string line;\n\tstd::getline(inputFile, line);\n\n\tstd::vector<std::string> strings;\n\tboost::split(strings, line, boost::is_any_of(\",\"), boost::token_compress_on);\n\n\tstd::vector<int> numbersOriginal;\n\n\t//std::transform(strings.begin(), strings.end(), std::back_inserter(numbers), [](const std::string& str) { return std::stoi(str); });\n\tstd::transform(strings.begin(), strings.end(), std::back_inserter(numbersOriginal), &boost::lexical_cast<int, std::string>);\n\n\tstd::vector<int> numbers(numbersOriginal.size());\n\n\t// PART 1\n\t//std::copy(numbersOriginal.begin(), numbersOriginal.end(), numbers.begin());\n\t//int result = run_day2(numbers, 12, 2);\n\n\t// PART 2\n\tint nounPlusVerb = 0;\n\tfor (int noun = 0; noun <= 99; ++noun) {\n\t\tfor (int verb = 0; verb <= 99; ++verb) {\n\t\t\tstd::copy(numbersOriginal.begin(), numbersOriginal.end(), numbers.begin());\n\t\t\tint result = run_day2(numbers, noun, verb);\n\t\t\tif (result == 19690720) {\n\t\t\t\tnounPlusVerb = 100 * noun + verb;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (nounPlusVerb != 0) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tstd::cout << \"RESULT: \" << nounPlusVerb << std::endl;\n}\n\nint run_day2(std::vector<int> &values, int noun, int verb) {\n\t// Replacing values\n\tvalues[1] = noun;\n\tvalues[2] = verb;\n\n\t//int index = 0;\n\t//for (auto number = values.begin(); values != values.end(); ++number) {\n\t//\tstd::cout << *number;\n\t//\tif (index % 4 == 3) {\n\t//\t\tstd::cout << std::endl;\n\t//\t}\n\t//\telse {\n\t//\t\tstd::cout << \" \";\n\t//\t}\n\t//\tindex++;\n\t//}\n\n\tint cursorPosition = 0;\n\tint opcode = values[cursorPosition * 4];\n\twhile (opcode != 99) {\n\t\tint opcode = values[cursorPosition * 4];\n\n\t\tif (opcode == 99)\n\t\t\tbreak;\n\n\t\tint leftPosition = values[(cursorPosition * 4) + 1];\n\t\tint rightPosition = values[(cursorPosition * 4) + 2];\n\t\tint targetPosition = values[(cursorPosition * 4) + 3];\n\n\t\tswitch (opcode)\n\t\t{\n\t\tcase 1:\n\t\t\tvalues[targetPosition] = values[leftPosition] + values[rightPosition];\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tvalues[targetPosition] = values[leftPosition] * values[rightPosition];\n\t\t\tbreak;\n\t\tcase 99:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tcursorPosition++;\n\t}\n\n\t//index = 0;\n\t//for (auto number = values.begin(); number != values.end(); ++number) {\n\t//\tstd::cout << *number;\n\t//\tif (index % 4 == 3) {\n\t//\t\tstd::cout << std::endl;\n\t//\t}\n\t//\telse {\n\t//\t\tstd::cout << \" \";\n\t//\t}\n\t//\tindex++;\n\t//}\n\n\t//std::cout << std::endl << std::endl << std::endl << values[0];\n\n\tstd::cout << \"noun: \" << noun << \" verb: \" << verb << \" => \" << values[0] << std::endl;\n\n\treturn values[0];\n}\n", "meta": {"hexsha": "1c8065dbd65cf3f2fbf0d90ea9f25467741f2c9e", "size": 2759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AdventOfCode2019/Src/Day2.cpp", "max_stars_repo_name": "Epono/AdventOfCode2019", "max_stars_repo_head_hexsha": "d035b8943a7e9b96491ed7a499e98101c08256c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AdventOfCode2019/Src/Day2.cpp", "max_issues_repo_name": "Epono/AdventOfCode2019", "max_issues_repo_head_hexsha": "d035b8943a7e9b96491ed7a499e98101c08256c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AdventOfCode2019/Src/Day2.cpp", "max_forks_repo_name": "Epono/AdventOfCode2019", "max_forks_repo_head_hexsha": "d035b8943a7e9b96491ed7a499e98101c08256c1", "max_forks_repo_licenses": ["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.201754386, "max_line_length": 134, "alphanum_fraction": 0.6121783255, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5663472750616875}}
{"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": "/* test_chi_squared_distribution.cpp\n *\n * Copyright Steven Watanabe 2011\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * $Id$\n *\n */\n\n#include <boost/random/chi_squared_distribution.hpp>\n#include <limits>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::chi_squared_distribution<>\n#define BOOST_RANDOM_ARG1 n\n#define BOOST_RANDOM_ARG1_DEFAULT 1.0\n#define BOOST_RANDOM_ARG1_VALUE 7.5\n\n#define BOOST_RANDOM_DIST0_MIN 0\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\n#define BOOST_RANDOM_DIST1_MIN 0\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\n#define BOOST_RANDOM_DIST2_MIN 0\n#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<double>::infinity)()\n\n#define BOOST_RANDOM_TEST1_PARAMS\n#define BOOST_RANDOM_TEST1_MIN 0.0\n#define BOOST_RANDOM_TEST1_MAX 100.0\n\n#define BOOST_RANDOM_TEST2_PARAMS (10000.0)\n#define BOOST_RANDOM_TEST2_MIN 100.0\n\n#include \"test_distribution.ipp\"\n", "meta": {"hexsha": "1df9f7e61f7bc069db635d19c31ba98991e27311", "size": 1041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_chi_squared_distribution.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/random/test/test_chi_squared_distribution.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/random/test/test_chi_squared_distribution.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 29.7428571429, "max_line_length": 75, "alphanum_fraction": 0.8107588857, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5662864013639348}}
{"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//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <Eigen/Core>\n#include \"genfile/Error.hpp\"\n#include \"components/HaplotypeFrequencyComponent/HaplotypeFrequencyLogLikelihood.hpp\"\n#include \"config/config.hpp\"\n#include \"test_case.hpp\"\n\nusing std::log ;\n\nAUTO_TEST_CASE( test_haplotype_frequency_loglikelihood_value ) {\n\ttypedef Eigen::MatrixXd Matrix ;\n\ttypedef Eigen::VectorXd Vector ;\n\t\n\tdouble const tolerance = 0.0000000000001 ;\n\t\n\tMatrix table( 3, 3 ) ;\n\n\t{\n\t\ttable <<\n\t\t\t1,\t0,\t0,\n\t\t\t0,\t0,\t0,\n\t\t\t0,\t0,\t0 ;\n\n\t\tHaplotypeFrequencyLogLikelihood ll( table ) ;\n\n\t\tVector params( 3 ) ;\n\t\tparams << 0.0, 0.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), log( 1.0 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -2.0 * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ;\n\t\tparams << 0.2, 0.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 / 0.8 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -( 2.0 / ( 0.8 * 0.8 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ;\n\t\tparams << 0.0, 0.2, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 / 0.8 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -( 2.0 / ( 0.8 * 0.8 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ;\n\t\tparams << 0.0, 0.0, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 / 0.8 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -( 2.0 / ( 0.8 * 0.8 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ;\n\t\tparams << 0.2, 0.2, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 / 0.6 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -( 2.0 / ( 0.6 * 0.6 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ;\n\t\tparams << 0.2, 0.0, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 / 0.6 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -( 2.0 / ( 0.6 * 0.6 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ;\n\t\tparams << 0.0, 0.2, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 / 0.6 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -( 2.0 / ( 0.6 * 0.6 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ;\n\t\tparams << 0.2, 0.2, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_CLOSE( ll.get_value_of_function(), 2.0 * log( 0.4 ), tolerance ) ;\n\t\tBOOST_CHECK_SMALL( ( ll.get_value_of_first_derivative() - Vector::Constant( 3, -2.0 / 0.4 ) ).array().abs().maxCoeff(), tolerance ) ;\n\t\tBOOST_CHECK_SMALL( ( ll.get_value_of_second_derivative() - ( -( 2.0 / ( 0.4 * 0.4 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ).array().abs().maxCoeff(), tolerance ) ;\n\t\tparams << 1.0, 0.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -std::numeric_limits< double >::infinity() ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -Matrix::Constant( 3, 3, std::numeric_limits< double >::infinity() ) ) ;\n\t\tparams << 0.0, 1.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -std::numeric_limits< double >::infinity() ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -Matrix::Constant( 3, 3, std::numeric_limits< double >::infinity() ) ) ;\n\t\tparams << 0.0, 0.0, 1.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -std::numeric_limits< double >::infinity() ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -\tMatrix::Constant( 3, 3, std::numeric_limits< double >::infinity() ) ) ;\n\t}\n\n\t{\n\t\ttable <<\n\t\t\t0,\t0,\t0,\n\t\t\t0,\t0,\t0,\n\t\t\t0,\t0,\t1 ;\n\n\t\tHaplotypeFrequencyLogLikelihood ll( table ) ;\n\n\t\tVector params( 3 ) ;\n\t\tparams << 0.0, 0.0, 1.0 ;\n\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), log( 1.0 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -2.0 * Vector::Unit( 3, 2 ) * Vector::Unit( 3, 2 ).transpose() ) ;\n\t\tparams << 0.0, 0.0, 0.8 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.8 ) ;\n\t\tparams << 0.2, 0.0, 0.8 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.8 ) ;\n\t\tparams << 0.0, 0.2, 0.8 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.8 ) ;\n\t\tparams << 0.2, 0.0, 0.6 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.6 ) ;\n\t\tparams << 0.0, 0.2, 0.6 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.6 ) ;\n\t\tparams << 0.2, 0.2, 0.6 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.6 ) ;\n\t\tparams << 0.2, 0.2, 0.4 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_CLOSE( ll.get_value_of_function(), 2.0 * log( 0.4 ), tolerance ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.4 ) ;\n\t\tparams << 0.0, 0.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -std::numeric_limits< double >::infinity() )) ;\n\t\tparams << 1.0, 0.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t\tparams << 0.0, 1.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t}\n\n\t{\n\t\ttable <<\n\t\t\t0,\t0,\t1,\n\t\t\t0,\t0,\t0,\n\t\t\t0,\t0,\t0 ;\n\n\t\tHaplotypeFrequencyLogLikelihood ll( table ) ;\n\n\t\tVector params( 3 ) ;\n\t\tparams << 1.0, 0.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), log( 1.0 ) ) ;\n\t\tparams << 0.8, 0.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tparams << 0.8, 0.2, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tparams << 0.8, 0.0, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tparams << 0.6, 0.2, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tparams << 0.6, 0.0, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tparams << 0.6, 0.2, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tparams << 0.4, 0.2, 0.4 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_CLOSE( ll.get_value_of_function(), 2.0 * log( 0.4 ), tolerance ) ;\n\t\tparams << 0.0, 0.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t\tparams << 0.0, 1.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t\tparams << 0.0, 0.0, 1.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t}\n\n\t{\n\t\ttable <<\n\t\t\t0,\t0,\t0,\n\t\t\t0,\t0,\t0,\n\t\t\t1,\t0,\t0 ;\n\n\t\tHaplotypeFrequencyLogLikelihood ll( table ) ;\n\n\t\tVector params( 3 ) ;\n\t\tparams << 0.0, 1.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), log( 1.0 ) ) ;\n\t\tparams << 0.0, 0.8, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tparams << 0.2, 0.8, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tparams << 0.0, 0.8, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tparams << 0.2, 0.6, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tparams << 0.0, 0.6, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tparams << 0.2, 0.6, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tparams << 0.4, 0.4, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_CLOSE( ll.get_value_of_function(), 2.0 * log( 0.4 ), tolerance ) ;\n\t\tparams << 0.0, 0.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t\tparams << 1.0, 0.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t\tparams << 0.0, 0.0, 1.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t}\n\n\t{\n\t\ttable <<\n\t\t\t0,\t0,\t0,\n\t\t\t0,\t0,\t0,\n\t\t\t1,\t0,\t0 ;\n\n\t\tHaplotypeFrequencyLogLikelihood ll( table ) ;\n\n\t\tVector params( 3 ) ;\n\t\tparams << 0.0, 1.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), log( 1.0 ) ) ;\n\t\tparams << 0.0, 0.8, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tparams << 0.2, 0.8, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tparams << 0.0, 0.8, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ;\n\t\tparams << 0.2, 0.6, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tparams << 0.0, 0.6, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tparams << 0.2, 0.6, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ;\n\t\tparams << 0.4, 0.4, 0.2 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_CLOSE( ll.get_value_of_function(), 2.0 * log( 0.4 ), tolerance ) ;\n\t\tparams << 0.0, 0.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t\tparams << 1.0, 0.0, 0.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t\tparams << 0.0, 0.0, 1.0 ;\n\t\tll.evaluate_at( params ) ;\n\t\tBOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ;\n\t}\n}\n\nnamespace {\n\tvoid test_haplotype_frequency_estimation( Eigen::MatrixXd const& genotypes, Eigen::VectorXd const& expected ) {\n\t\tHaplotypeFrequencyLogLikelihood ll( genotypes ) ;\n\t\tstd::cerr << \"test_haplotype_frequency_estimation: genotypes: \" << genotypes\n\t\t\t<< \"\\nexpected: \" << expected << \"\\n\" ;\n\t\tstd::cerr << \"     got: \" << ll.get_MLE_by_EM() << \".\\n\" ;\n\t\tBOOST_CHECK_SMALL( ( ll.get_MLE_by_EM() - expected ).maxCoeff(), 0.000000000001 ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_haplotype_frequency_exceptions ) {\n\t{\n\t\tEigen::MatrixXd\tgenotypes = Eigen::MatrixXd::Zero( 3, 3 ) ;\n\t\tBOOST_CHECK_THROW( { HaplotypeFrequencyLogLikelihood ll( genotypes ) ; }, genfile::BadArgumentError ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_single_person_haplotype_frequency_estimation ) {\n\tEigen::MatrixXd\tgenotypes( 3, 3 ) ;\n\tEigen::VectorXd params( 3 ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 0, 0 ) = 1 ;\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 0, 1 ) = 1 ;\n\tparams(0) = 0.5 ;\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 0, 2 ) = 1 ;\n\tparams(0) = 1 ;\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 1, 0 ) = 1 ;\n\tparams(1) = 0.5 ;\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 1, 1 ) = 1 ;\n\t// both SNPs heterozygores; half a chance of AB_ab and half of Ab_aB\n\tparams(0) = 0.25 ;\n\tparams(1) = 0.25 ;\n\tparams(2) = 0.25 ;\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 1, 2 ) = 1 ;\n\tparams(0) = 0.5 ;\n\tparams(2) = 0.5 ;\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 2, 0 ) = 1 ;\n\tparams(1) = 1 ;\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 2, 1 ) = 1 ;\n\tparams(1) = 0.5 ;\n\tparams(2) = 0.5 ;\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 2, 2 ) = 1 ;\n\tparams(2) = 1 ;\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n}\n\nAUTO_TEST_CASE( test_N_person_haplotype_frequency_estimation ) {\n\tEigen::MatrixXd\tgenotypes( 3, 3 ) ;\n\tEigen::VectorXd params( 3 ) ;\n\n\tfor( std::size_t N = 1; N < 10; ++N ) {\n\t\tgenotypes.setZero() ; params.setZero() ;\n\t\tgenotypes( 0, 0 ) = 1 ;\n\t\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\t\tgenotypes.setZero() ; params.setZero() ;\n\t\tgenotypes( 0, 1 )= N ;\n\t\tparams(0) = 0.5 ;\n\t\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\t\tgenotypes.setZero() ; params.setZero() ;\n\t\tgenotypes( 0, 2 )= N ;\n\t\tparams(0) = 1 ;\n\t\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\t\tgenotypes.setZero() ; params.setZero() ;\n\t\tgenotypes( 1, 0 )= N ;\n\t\tparams(1) = 0.5 ;\n\t\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\t\tgenotypes.setZero() ; params.setZero() ;\n\t\tgenotypes( 1, 1 )= N ;\n\t\t// both SNPs heterozygores; half a chance of AB_ab and half of Ab_aB\n\t\tparams(0) = 0.25 ;\n\t\tparams(1) = 0.25 ;\n\t\tparams(2) = 0.25 ;\n\t\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\t\tgenotypes.setZero() ; params.setZero() ;\n\t\tgenotypes( 1, 2 )= N ;\n\t\tparams(0) = 0.5 ;\n\t\tparams(2) = 0.5 ;\n\t\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\t\tgenotypes.setZero() ; params.setZero() ;\n\t\tgenotypes( 2, 0 )= N ;\n\t\tparams(1) = 1 ;\n\t\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\t\tgenotypes.setZero() ; params.setZero() ;\n\t\tgenotypes( 2, 1 )= N ;\n\t\tparams(1) = 0.5 ;\n\t\tparams(2) = 0.5 ;\n\t\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\t\tgenotypes.setZero() ; params.setZero() ;\n\t\tgenotypes( 2, 2 )= N ;\n\t\tparams(2) = 1 ;\n\t\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_2_person_haplotype_frequency_estimation ) {\n\tEigen::MatrixXd\tgenotypes( 3, 3 ) ;\n\tEigen::VectorXd params( 3 ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 0, 0 ) = 1 ;\n\tgenotypes( 2, 1 ) = 1 ;\n\tparams(1) = 0.25 ;\n\tparams(2) = 0.25 ;\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 2, 2 ) = 1 ;\n\tgenotypes( 2, 1 ) = 1 ;\n\tparams(1) = 0.25 ;\n\tparams(2) = 0.75 ;\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 2, 2 ) = 1 ;\n\tgenotypes( 1, 0 ) = 1 ;\n\tparams(1) = 0.25 ;\n\tparams(2) = 0.5 ;\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n\n\tgenotypes.setZero() ; params.setZero() ;\n\tgenotypes( 2, 2 ) = 1 ;\n\tgenotypes( 1, 1 ) = 1 ;\n\tparams(0) = 0.125 ;\n\tparams(1) = 0.125 ;\n\tparams(2) = 0.5 + ( 0.25 * 0.5 );\n\ttest_haplotype_frequency_estimation( genotypes, params ) ;\n}\n", "meta": {"hexsha": "bdeb3e5e881a36792aa46c6024ff003ca27730d8", "size": 17407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/HaplotypeFrequencyComponent/test/test_haplotype_frequency_loglikelihood.cpp", "max_stars_repo_name": "CreRecombinase/qctool", "max_stars_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "components/HaplotypeFrequencyComponent/test/test_haplotype_frequency_loglikelihood.cpp", "max_issues_repo_name": "CreRecombinase/qctool", "max_issues_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "components/HaplotypeFrequencyComponent/test/test_haplotype_frequency_loglikelihood.cpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8329519451, "max_line_length": 202, "alphanum_fraction": 0.6535876372, "num_tokens": 6105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5662256570308317}}
{"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/*!\n * \\file\n**/\n#ifndef BOOST_SIMD_TOOLBOX_IEEE_FUNCTIONS_ULPDIST_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_IEEE_FUNCTIONS_ULPDIST_HPP_INCLUDED\n#include <boost/simd/include/functor.hpp>\n#include <boost/dispatch/include/functor.hpp>\n\n/*!\n * \\ingroup boost_simd_ieee\n * \\defgroup boost_simd_ieee_ulpdist ulpdist\n *\n * \\par Description\n * Returns ulp distance of the two values.\n * \\par\n * \\arg If the common type is integer it is the same as \\c dist\n * \\arg If the common type is floating point the ulpdist is is computed,\n * by the above described method\n * \\par\n * It is often difficult to  answer to the following question:\n * \\arg are these two floating computations results similar enough?\n * \\par\n * The ulpdist is a way to answer which is tuned for relative errors estimations\n * and peculiarly adapted to cope with the limited bits accuracy of floating point\n * representations.\n * The method is the following:\n * \\par\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 * Return the absolute difference of these normalized numbers\n * divided by the rounding error Eps\n * \\par\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 * This means 2^-23 for floats and 2^-52 for double\n * \\arg For instance if two floating numbers (of same type) have an ulpdist of\n * zero that means that their floating representation are identical.\n * \\arg Generally equality up to 0.5 ulp is the best that one can wish beyond\n * strict equality.\n * \\arg Typically if a double is compared to the float 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 * \\par\n * The ulpdist is also roughly equivalent to the number of representable\n * floating points values between two given floating points values.\n * \\par\n * \\arg  \\c ulpdist(1.0,1+Eps\\<double\\>())==0.5\n * \\arg  \\c ulpdist(1.0,1+Eps\\<double\\>()/2)==0.0\n * \\arg  \\c ulpdist(1.0,1-Eps\\<double\\>()/2)==0.25\n * \\arg  \\c ulpdist(1.0,1-Eps\\<double\\>())==0.5\n * \\arg  \\c ulpdist(double(Pi\\<float\\>()),Pi\\<double\\>())==9.84293e+07\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/ulpdist.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class A0>\n *     meta::call<tag::ulpdist_(A0,A0)>::type\n *     ulpdist(const A0 & a0,const A0 & a1);\n * }\n * \\endcode\n *\n * \\param a0 the first parameter of ulpdist\n * \\param a1 the second parameter of ulpdist\n *\n * \\return a value of the common type of the parameters\n *\n * \\par Notes\n * In SIMD mode, this function acts elementwise on the inputs vectors elements\n * \\par\n *\n**/\n\nnamespace boost { namespace simd { namespace tag\n  {\n    /*!\n     * \\brief Define the tag ulpdist_ of functor ulpdist\n     *        in namespace boost::simd::tag for toolbox boost.simd.ieee\n    **/\n    struct ulpdist_ : ext::elementwise_<ulpdist_> { typedef ext::elementwise_<ulpdist_> parent; };\n  }\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::ulpdist_, ulpdist, 2)\n} }\n\n#endif\n\n// modified by jt the 25/12/2010\n", "meta": {"hexsha": "69c91f336927e8e3861826412ed32e15f782c574", "size": 3789, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/ieee/include/boost/simd/toolbox/ieee/functions/ulpdist.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/ieee/include/boost/simd/toolbox/ieee/functions/ulpdist.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/ieee/include/boost/simd/toolbox/ieee/functions/ulpdist.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": 36.0857142857, "max_line_length": 98, "alphanum_fraction": 0.6690419636, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5662029389206342}}
{"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(\"\u8a08\u7b97\u6642\u9593 = %.14f\uff08\u79d2\uff09\\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": "// Copyright (c) 2017 Graphcore Ltd. All rights reserved.\n#define BOOST_TEST_MODULE RangeTest\n#include <boost/test/unit_test.hpp>\n#include <poplin/ConvUtil.hpp>\n#include <vector>\n\nnamespace std {\nostream &operator<<(ostream &s, const pair<unsigned, unsigned> &p) {\n  s << '<' << p.first << ',' << p.second << '>';\n  return s;\n}\n} // namespace std\n\nstatic poplin::ConvParams makeParams(unsigned stride, unsigned kernelSize,\n                                     unsigned paddingLower,\n                                     unsigned paddingUpper,\n                                     unsigned inputSize) {\n  poplin::ConvParams params{\n      poplar::FLOAT,            // data type,\n      1,                        // batch size\n      {inputSize, inputSize},   // input size\n      {kernelSize, kernelSize}, // kernel size\n      1,                        // input channels\n      1,                        // output channels\n      1                         // conv groups\n  };\n  params.inputTransform.paddingLower = {paddingLower, paddingLower};\n  params.inputTransform.paddingUpper = {paddingUpper, paddingUpper};\n  params.outputTransform.stride = {stride, stride};\n  return params;\n}\n\nBOOST_AUTO_TEST_CASE(inputRangeTest) {\n  // No stride, no padding\n  const auto params1 = makeParams(1, 3, 0, 0, 10);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 0, params1), 0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 1, 0, params1), 1U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 1, params1), 1U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 7, 2, params1), 9U);\n\n  // Stride = 2, no padding\n  const auto params2 = makeParams(2, 3, 0, 0, 10);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 1, 0, params2), 2U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 3, 2, params2), 8U);\n\n  // Stride 1, padding lower=1, padding upper=0\n  const auto params3 = makeParams(1, 3, 1, 0, 10);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 0, params3), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 1, params3), 0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 2, params3), 1U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 8, 1, params3), 8U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 8, 2, params3), 9U);\n\n  // Stride 1, padding lower=2, padding upper=0\n  const auto params4 = makeParams(1, 3, 2, 0, 10);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 0, params4), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 1, params4), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 2, params4), 0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 9, 1, params4), 8U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 9, 2, params4), 9U);\n\n  // Stride 2, padding lower=1, padding upper=0\n  const auto params5 = makeParams(2, 3, 1, 0, 10);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 0, params5), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 1, params5), 0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 2, params5), 1U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 4, 1, params5), 8U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 4, 2, params5), 9U);\n\n  // Stride 2, padding lower=2, padding upper=0\n  const auto params6 = makeParams(2, 3, 2, 0, 10);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 0, params6), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 1, params6), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 2, params6), 0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 4, 1, params6), 7U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 4, 2, params6), 8U);\n\n  // Stride 2, padding lower=4, padding upper=0\n  const auto params7 = makeParams(2, 3, 4, 0, 10);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 0, params7), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 1, params7), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 2, params7), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 1, 0, params7), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 1, 1, params7), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 1, 2, params7), 0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 5, 1, params7), 7U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 5, 2, params7), 8U);\n\n  // Stride 1, padding lower=1, padding upper=1\n  const auto params8 = makeParams(1, 3, 1, 1, 10);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 0, params8), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 1, params8), 0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 2, params8), 1U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 9, 1, params8), 9U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 9, 2, params8), ~0U);\n\n  // Stride 2, padding lower=1, padding upper=2\n  const auto params9 = makeParams(2, 3, 1, 2, 10);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 0, params9), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 1, params9), 0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 2, params9), 1U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 4, 1, params9), 8U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 4, 2, params9), 9U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 5, 0, params9), 9U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 5, 1, params9), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 5, 2, params9), ~0U);\n\n  // Stride 3, padding lower=2, padding upper=2\n  const auto params10 = makeParams(3, 3, 2, 2, 10);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 0, params10), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 1, params10), ~0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 0, 2, params10), 0U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 3, 1, params10), 8U);\n  BOOST_CHECK_EQUAL(poplin::getInputIndex(0, 3, 2, params10), 9U);\n}\n\nstd::pair<unsigned, unsigned>\ngetOutputDim(unsigned inDimY, unsigned inDimX, unsigned kernelSizeY,\n             unsigned kernelSizeX, const std::vector<unsigned> &stride,\n             const std::vector<unsigned> &paddingLower,\n             const std::vector<unsigned> &paddingUpper) {\n  poplin::ConvParams params{\n      poplar::FLOAT,              // data type,\n      1,                          // batch size\n      {inDimY, inDimX},           // input size\n      {kernelSizeY, kernelSizeX}, // kernel size\n      1,                          // input channels\n      1,                          // output channels\n      1                           // conv groups\n  };\n  params.inputTransform.paddingLower = paddingLower;\n  params.inputTransform.paddingUpper = paddingUpper;\n  params.outputTransform.stride = stride;\n  return {params.getOutputSize(0), params.getOutputSize(1)};\n}\n\nBOOST_AUTO_TEST_CASE(outputDimTest) {\n\n  BOOST_CHECK_EQUAL(getOutputDim(10, 10, 3, 3, {1, 1}, {0, 0}, {0, 0}),\n                    std::make_pair(8u, 8u));\n\n  BOOST_CHECK_EQUAL(getOutputDim(10, 10, 2, 2, {1, 1}, {0, 0}, {0, 0}),\n                    std::make_pair(9u, 9u));\n\n  BOOST_CHECK_EQUAL(getOutputDim(10, 10, 3, 3, {1, 1}, {1, 1}, {0, 0}),\n                    std::make_pair(9u, 9u));\n\n  BOOST_CHECK_EQUAL(getOutputDim(10, 10, 3, 3, {1, 1}, {0, 0}, {2, 2}),\n                    std::make_pair(10u, 10u));\n\n  BOOST_CHECK_EQUAL(getOutputDim(10, 10, 3, 3, {1, 1}, {3, 3}, {2, 2}),\n                    std::make_pair(13u, 13u));\n\n  BOOST_CHECK_EQUAL(getOutputDim(10, 10, 3, 3, {2, 2}, {3, 3}, {2, 2}),\n                    std::make_pair(7u, 7u));\n\n  BOOST_CHECK_EQUAL(getOutputDim(10, 10, 3, 3, {1, 2}, {3, 3}, {2, 2}),\n                    std::make_pair(13u, 7u));\n\n  BOOST_CHECK_EQUAL(getOutputDim(10, 12, 3, 5, {1, 1}, {0, 1}, {0, 2}),\n                    std::make_pair(8u, 11u));\n\n  BOOST_CHECK_EQUAL(getOutputDim(4, 4, 3, 3, {2, 1}, {0, 0}, {1, 0}),\n                    std::make_pair(2u, 2u));\n\n  BOOST_CHECK_EQUAL(getOutputDim(4, 4, 3, 3, {3, 3}, {0, 1}, {1, 0}),\n                    std::make_pair(1u, 1u));\n}\n", "meta": {"hexsha": "486468c6cdeff5432b94a440140e79f8f978c488", "size": 7735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/poplin/RangeTest.cpp", "max_stars_repo_name": "graphcore/poplibs", "max_stars_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:28.000Z", "max_issues_repo_path": "tests/poplin/RangeTest.cpp", "max_issues_repo_name": "giantchen2012/poplibs", "max_issues_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/poplin/RangeTest.cpp", "max_forks_repo_name": "giantchen2012/poplibs", "max_forks_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:32:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T14:58:45.000Z", "avg_line_length": 45.7692307692, "max_line_length": 74, "alphanum_fraction": 0.6376212023, "num_tokens": 2698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5660176636962541}}
{"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": "\n#pragma once\n\n#include <Eigen/Dense>\n\nnamespace Tools {\n\tnamespace Math {\n\t\ttemplate <typename T, int R, int C>\n\t\tusing Matrix = Eigen::Matrix<T, R, C>;\n\n\t\ttemplate <typename T>\n\t\tusing Matrix2 = Matrix<T, 2, 2>;\n\t\ttemplate <typename T>\n\t\tusing Matrix3 = Matrix<T, 3, 3>;\n\t\ttemplate <typename T>\n\t\tusing Matrix4 = Matrix<T, 4, 4>;\n\n\t\ttemplate <typename T>\n\t\tusing MatrixX = Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\n\t\ttemplate <typename T, int R>\n\t\tusing Vector = Matrix<T, R, 1>;\n\n\t\ttemplate <typename T>\n\t\tusing Vector2 = Vector<T, 2>;\n\t\ttemplate <typename T>\n\t\tusing Vector3 = Vector<T, 3>;\n\t\ttemplate <typename T>\n\t\tusing Vector4 = Vector<T, 4>;\n\n\t\ttemplate <typename T>\n\t\tusing VectorX = Vector<T, Eigen::Dynamic>;\n\t}\n}\n\n", "meta": {"hexsha": "3fd6856785da111f71f817581d2d82046125199b", "size": 729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Tools/Math/Matrix.hpp", "max_stars_repo_name": "NaokiTakahashi12/OpenHumanoidController", "max_stars_repo_head_hexsha": "ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-23T06:21:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-23T06:21:47.000Z", "max_issues_repo_path": "src/Tools/Math/Matrix.hpp", "max_issues_repo_name": "NaokiTakahashi12/hc-early", "max_issues_repo_head_hexsha": "ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T00:17:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-09T23:00:43.000Z", "max_forks_repo_path": "src/Tools/Math/Matrix.hpp", "max_forks_repo_name": "NaokiTakahashi12/OpenHumanoidController", "max_forks_repo_head_hexsha": "ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.25, "max_line_length": 60, "alphanum_fraction": 0.6556927298, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5660176569067525}}
{"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": "//transfer skeleton pose to actuator angle\n\n#include <ros/ros.h>\n#include <stdlib.h>\n#include <iostream>\n#include <vector>\n#include <math.h>\n#include <ros/package.h>\n#include <tf/transform_broadcaster.h>\n#include <stdio.h>\n#include <geometry_msgs/Point.h>\n#include <boost/shared_ptr.hpp>\n#include <realtime_tools/realtime_buffer.h>\n#include <realtime_tools/realtime_publisher.h>\n#include \"skeleton/JointMsg.h\"\n#include <xm_arm_msgs/xm_ArmSerialDatagram.h>\n\nusing namespace std;\nros::Publisher     arm_serial_pub_;\nros::Subscriber    skeleton_state_sub_;\nfloat joint_angle[4];\nfloat act_angle[4];\n\n\nvoid transfromjointtomotor()\n{//need change!\n    act_angle[0]=1.5*(-joint_angle[0]+joint_angle[1]-joint_angle[2])*180/3.1415+220;\n    act_angle[1]=1.5*(-2.1628*joint_angle[0]-joint_angle[1])*180/3.1415+300;\n    act_angle[2]=1.5*(joint_angle[0]-joint_angle[1]-joint_angle[2])*180/3.1415+260;\n    act_angle[3]=200-120*joint_angle[3];\n//act_angle[3]=100;\n}\n\ngeometry_msgs::Point rotate(float angle,geometry_msgs::Point Point)\n{\n  geometry_msgs::Point feedback;\n  feedback.x=Point.x;\n  feedback.y=Point.y*cos(angle)-Point.z*sin(angle);\n  feedback.z=Point.y*sin(angle)+Point.z*cos(angle);\n\n  return feedback;\n}\n\n\nvoid publishArmCommand(const u_int8_t func,\n                                         const u_int8_t jnt_id,\n                                         const float    jnt_pos)\n{\n    xm_arm_msgs::xm_ArmSerialDatagramPtr datagram_ptr =\n        boost::make_shared<xm_arm_msgs::xm_ArmSerialDatagram>();\n    datagram_ptr->sender = 0x03;\n    datagram_ptr->receiver = jnt_id + 0x2B;\n    datagram_ptr->data.resize(5, 0);\n    u_int8_t *data_ptr = datagram_ptr->data.data();\n    data_ptr[0] = func;\n    *(float *)(data_ptr + 1) = jnt_pos;\n    arm_serial_pub_.publish(datagram_ptr);\n}\n\nvoid transfer_skeleton_motor(const skeleton::JointMsg::ConstPtr &msg)\n\n{  \n   std::vector<geometry_msgs::Point> skeletonPoints;\n   skeletonPoints= msg->joints;\n   \n  geometry_msgs::Point point1= skeletonPoints[0];\n   geometry_msgs::Point point2= skeletonPoints[1];\n    geometry_msgs::Point point3= skeletonPoints[2];\n\n//ROS_INFO(\"I heard: %f \\r\\n\", point1.x);\nif (point1.x>5000) \n  {\n  ROS_INFO(\"initialize failed ,please check you standing pose!!!\");\n  return ;\n  }\nif(point1.x<0)\n {\n  ROS_INFO(\"initialize failed ,please check you standing pose!!!\");\n  return ;\n }\n\nfloat x1,y1,z1,x2,y2,z2,x3,y3,z3,l1,l2;\nfloat angle1,angle2,angle3,angle4;\nfloat sum2;\nx1=point1.x;\nx2=point2.x;\nx3=point3.x;\ny1=point1.y;\ny2=point2.y;\ny3=point3.y;\nz1=point1.z;\nz2=point2.z;\nz3=point3.z;\n\nl1=sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1));\nl2=sqrt((x3-x2)*(x3-x2)+(y3-y2)*(y3-y2)+(z3-z2)*(z3-z2));\n\nif((x2-x1)<0) {\nROS_INFO(\"ALERT:\u3000sorry, angle2 out of range, please move your body~~\");\nreturn;\n}\n//angle2 range is ok\nangle2=asin((x2-x1)/l1);\n//sum2=pow((x2-x1)/l1,2)+pow((z1-z2)/l1,2)+pow((y2-y1)/l1,2);\n//printf(\"sum2: >>>>>>>>>>>>>>>    %f\",sum2);\nif((y2-y1)<0){\nROS_INFO(\"ALERT:\u3000sorry again, angle out of range, please move your body~~\");\nreturn;\n}\n\nif((z1-z2)<0){\nROS_INFO(\"ALERT:\u3000sorry again again, angle out of range, please move your body~~\");\nreturn;\n}\n//angle1 range is ok\n//angle1=acos((y2-y1)/(l1*cos(angle2)));\n//need change here\nif((z1-z2)>(y2-y1))\n{\n  angle1=asin((z1-z2)/(l1*cos(angle2)));\n}\nelse angle1=acos((y2-y1)/(l1*cos(angle2)));\n//angle1=(asin((z1-z2)/(l1*cos(angle2)))+acos((y2-y1)/(l1*cos(angle2))))/2;\n//>>>>>>>>>>>>>>>rotate transmission>>>>>>>>>>>>>>>>>\npoint1=rotate(angle1,point1);\npoint2=rotate(angle1,point2);\npoint3=rotate(angle1,point3);\nx1=point1.x;\nx2=point2.x;\nx3=point3.x;\ny1=point1.y;\ny2=point2.y;\ny3=point3.y;\nz1=point1.z;\nz2=point2.z;\nz3=point3.z;\n//angle4 is ready!!!!!\nangle4=acos(((x3-x2)*(x2-x1)+(y3-y2)*(y2-y1)+(z3-z2)*(z2-z1))/(l1*l2));\n\n//>>>>>>>>>>>>>>>>>calculate angle3>>>>>>>>>>>>>>>>>>>\nfloat d_long,d_short;\nfloat mark;\nd_long=l2*sin(angle4);\nd_short=abs(x3*(-cos(angle2))+y3*sin(angle2)+x1*cos(angle2)-y1*sin(angle2));\nangle3=asin(d_short/d_long);\n\nmark=-cos(angle2)*(x3-x1)+sin(angle2)*(y3-y1);\n\nif(mark>0) angle3=-angle3;\n//angle3 is ready!!!!!\n\n\nROS_INFO(\"I heard joint1:%f ;joint2:%f ; joint3:%f ;joint4:%f  \\r\\n\",angle1,angle2,angle3,angle4);\njoint_angle[0]=angle1;\njoint_angle[1]=angle2;\njoint_angle[2]=angle3;\njoint_angle[3]=angle4;\n\n//transmit from joint_angle to motor_angle\n\ntransfromjointtomotor();\nfor(size_t i =0;i<3;i++)\n{ \n  if (act_angle[i]<1) act_angle[i]=1;\n  if(act_angle[i]>359)act_angle[i]=359;\n}\nprintf(\">>>>>>>>>>act_angle:>>>>>>>>>> motor1:  %f , motor2:  %f  , motor3: %f,motor4: %f\", act_angle[0],act_angle[1],act_angle[2],act_angle[3]);\n\n  for(size_t i=0;i<4;i++)\n  {\n   publishArmCommand(0x01,i, act_angle[i]);\n   //delay func\n   boost::this_thread::sleep( boost::posix_time::milliseconds(5) ); //\u5355\u4f4d\u662f\u6beb\u79d2\n  }\n\n}\n\n\n\n\n//main func\nint main( int argc, char**argv)\n{\n    ros::init(argc,argv,\"skeleton_send_node\");\n    ros::NodeHandle nh;\n\nfor(size_t i=0; i<4; i++)  \n  {\n  joint_angle[i]=0;\n  }\n\n    arm_serial_pub_ = nh.advertise<xm_arm_msgs::xm_ArmSerialDatagram>(\n        \"xm_arm_serial/send_arm_command\", 1000);\n    \n   skeleton_state_sub_=nh.subscribe(\"skeleton_msg\", 1000,\n        transfer_skeleton_motor);\n\nros::spin();\n\nreturn 0;\n\n}\n", "meta": {"hexsha": "89f1aca88b40c25bc3c0a4eab3a0d9975034f1ac", "size": 5186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/skeleton_send_node/src/skeleton_send_node.cpp", "max_stars_repo_name": "brucechenssfireinthehole/DosuBot_pkg", "max_stars_repo_head_hexsha": "986f263ab79174215725fd9b0693ae2076963de7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-15T02:15:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-15T02:15:05.000Z", "max_issues_repo_path": "src/skeleton_send_node/src/skeleton_send_node.cpp", "max_issues_repo_name": "brucechenssfireinthehole/DosuBot_pkg", "max_issues_repo_head_hexsha": "986f263ab79174215725fd9b0693ae2076963de7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/skeleton_send_node/src/skeleton_send_node.cpp", "max_forks_repo_name": "brucechenssfireinthehole/DosuBot_pkg", "max_forks_repo_head_hexsha": "986f263ab79174215725fd9b0693ae2076963de7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-25T15:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-25T15:44:35.000Z", "avg_line_length": 25.5467980296, "max_line_length": 145, "alphanum_fraction": 0.6656382568, "num_tokens": 1745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5660176427030618}}
{"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\uff01 # 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": "#include \"InputFileOperator.h\"\n#include \"CommandLineHandlers/SingleCommandLineHandler.h\"\n#include \"NumberOperator.h\"\n#include <boost/algorithm/string/trim.hpp>\n\nUSING_NAMESPACE(std);\nUSING_NAMESPACE(clu);\n\nclass RoundOperator : public NumberOperator\n{\npublic:\n\tRoundOperator(int value) : m_value(value)\n\t{\n\t}\n\n\tvirtual bool OnNumberRead(double number)\n\t{\n\t\tlong roundedNumber = (number > 0.0) ? (long)(number) : (long)(number)-1;\n\n\t\tlong reminder = roundedNumber % m_value;\n\t\troundedNumber -= reminder;\n\t\tif (abs(reminder) >= (m_value / 2))\n\t\t{\n\t\t\tif (number > 0)\n\t\t\t\troundedNumber += m_value;\n\t\t\telse\n\t\t\t\troundedNumber -= m_value;\n\t\t}\n\n\t\tm_OutputHandler->OutputInteger(roundedNumber);\n\t\treturn true;\n\t}\n\nprotected:\n\tlong m_value;\n};\n\nREGISTER_SINGLE_INTEGER(\"round\", RoundOperator)->SetHelp(\"Round       - Round up to the nearest\");\n", "meta": {"hexsha": "a1a95428c0820c6572d01c1345ff78d54fb137e4", "size": 834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "clu/Operators/RoundOperator.cpp", "max_stars_repo_name": "ShaiRoitman/clu", "max_stars_repo_head_hexsha": "c8816455a78ed70d1885fa23f6442d1d2a823a16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clu/Operators/RoundOperator.cpp", "max_issues_repo_name": "ShaiRoitman/clu", "max_issues_repo_head_hexsha": "c8816455a78ed70d1885fa23f6442d1d2a823a16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-01-10T18:37:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-15T07:11:46.000Z", "max_forks_repo_path": "clu/Operators/RoundOperator.cpp", "max_forks_repo_name": "ShaiRoitman/clu", "max_forks_repo_head_hexsha": "c8816455a78ed70d1885fa23f6442d1d2a823a16", "max_forks_repo_licenses": ["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.3846153846, "max_line_length": 98, "alphanum_fraction": 0.7146282974, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5659808410784554}}
{"text": "/**\n * @file quasiinterpolation_test.cc\n * @brief NPDE exam QuasiInterpolation code\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 <gtest/gtest.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <memory>\n#include <utility>\n\nnamespace QuasiInterpolation::test {\n\nTEST(QuasiInterpolation, findKp) {\n  std::shared_ptr<const lf::mesh::Mesh> mesh_p =\n      lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n  lf::mesh::utils::CodimMeshDataSet<\n      std::pair<const lf::mesh::Entity *, unsigned int>>\n      KpMeshDataSet = findKp(mesh_p);\n\n  unsigned int vertexIndex = 9;       // 8\n  unsigned int localVertexIndex = 1;  // 0\n  unsigned int triangleIndex = 12;    // 11\n\n  const lf::mesh::Entity *vertex = mesh_p->EntityByIndex(2, vertexIndex);\n  std::pair<const lf::mesh::Entity *, unsigned int> Kp = KpMeshDataSet(*vertex);\n\n  EXPECT_EQ(localVertexIndex, Kp.second);\n  EXPECT_NE(Kp.first, nullptr);\n  if (Kp.first != nullptr) {\n    EXPECT_EQ(triangleIndex, mesh_p->Index(*Kp.first));\n  }\n}\n\nTEST(QuasiInterpolation, quasiInterpolate) {\n  std::shared_ptr<const lf::mesh::Mesh> mesh_p =\n      lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n  lf::uscalfe::FeSpaceLagrangeO1<double> fe_space(mesh_p);\n\n  // For polynomials of degree 1, the quasi projection yields the exact result\n  auto f = [](Eigen::Vector2d x) -> double {\n    return 1.5 * x(0) - 2.0 * x(1) + 0.5;\n  };\n  lf::mesh::utils::MeshFunctionGlobal mf(f);\n\n  Eigen::VectorXd coefficients =\n      QuasiInterpolation::quasiInterpolate(fe_space, mf);\n  Eigen::VectorXd coefficients_ref = lf::fe::NodalProjection(fe_space, mf);\n\n  double tol = 1.0e-12;\n  double error = (coefficients - coefficients_ref).lpNorm<Eigen::Infinity>();\n  ASSERT_NEAR(0.0, error, tol);\n}\n\n}  // namespace QuasiInterpolation::test\n", "meta": {"hexsha": "97c3c32c29867d53c6d0767ef39453c5d9371d95", "size": 1949, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/QuasiInterpolation/templates/test/quasiinterpolation_test.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/QuasiInterpolation/templates/test/quasiinterpolation_test.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/QuasiInterpolation/templates/test/quasiinterpolation_test.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 30.453125, "max_line_length": 80, "alphanum_fraction": 0.7008722422, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.565980839638854}}
{"text": "/*! \\file 2d_bezier.cpp\n  \\brief Simple 2D plot using bezier curves.\n  \\author Jacob Voytko and Paul A. Bristow\n  \\date 2007\n*/\n\n// Copyright (C) Jacob Voytko 2007\n// Copyright Paul A. Bristow 2009\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Example of using SVG plot bezier option showing smoothing effect when using a limited number of data-points.\n\n#include <boost/svg_plot/svg_2d_plot.hpp>\nusing namespace boost::svg;\n\n#include <map>\n // using std::map;\n#include <cmath>\n  // using std::sin;\n  // using std::cos;\n\n// sin and cos functions.\ndouble f(double x)\n{\n  return std::sin(x);\n}\n\ndouble g(double x)\n{\n  return std::cos(x);\n}\n\nint main()\n{\n  std::map<double, double> sin_data;\n  std::map<double, double> cos_data;\n\n  const double interval = 3.14159265 / 8.; // pi/8 - between values, too few for a smooth plot.\n\n  for(double i = 0; i <= 10.; i += interval)\n  {\n    sin_data[i] = f(i);\n    cos_data[i] = g(i);\n  }\n\n  svg_2d_plot my_plot;\n\n  // Size/scale settings.\n  my_plot.size(700, 500)\n    .x_range(-.5, 10.5)\n    .y_range(-1.1, 1.1);  // Ensure that 1.0 and -1.0 are visible.\n\n  // Text settings.\n  my_plot.title(\"Plot of sin and cos functions\")\n    .title_font_size(29)\n    .x_label(\"X Axis Units\")\n    .y_major_labels_side(-1)\n    .y_major_grid_on(true);\n\n  // Commands.\n  my_plot.legend_on(true) // To show a legend box.\n    .plot_window_on(true)\n    .x_label_on(true);\n\n  // Color settings.\n  my_plot.background_color(svg_color(67, 111, 69))  // Color specified using RGB values.\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) // Color specified using SVG named colors.\n    .y_major_grid_color(grey);\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(25)\n    .y_num_minor_ticks(5);\n\n  // legend settings.\n  my_plot.legend_title_font_size(15);\n\n  my_plot.plot(sin_data, \"Sin(x)\").line_on(true)\n    .shape(circlet).size(5).fill_color(yellow);\n\n  my_plot.plot(cos_data, \"Cos(x)\")\n    .line_color(blue)\n    .bezier_on(true)\n    .shape(square).size(5).fill_color(red);\n\n  // Note the slightly smoother curve for the cosine curve using bezier_on, compared to the line_on option.\n\n  my_plot.write(\"./2d_bezier.svg\");\n\n  return 0;\n} // int main()\n\n\n", "meta": {"hexsha": "9a0446e2749fe151507d408403e9d2d4b036c423", "size": 2629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/2d_bezier.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_bezier.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_bezier.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 24.3425925926, "max_line_length": 111, "alphanum_fraction": 0.6801065044, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389325, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.5659808179292518}}
{"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": "// __BEGIN_LICENSE__\n//  Copyright (c) 2006-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NASA Vision Workbench is licensed under the Apache License,\n//  Version 2.0 (the \"License\"); you may not use this file except in\n//  compliance with the License. You may obtain a copy of the License at\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n// __END_LICENSE__\n\n\n#include <gtest/gtest_VW.h>\n#include <vw/Math/Functors.h>\n#include <boost/random.hpp>\n\nusing namespace vw;\nusing namespace vw::math;\n\nstatic const double DELTA = 1e-5;\n\nTEST(Accumulators, CDF_cauchy) {\n  boost::mt19937 random_gen(42);\n  boost::cauchy_distribution<double> cauchy(35,80);\n  boost::variate_generator<boost::mt19937&,\n    boost::cauchy_distribution<double> > generator(random_gen, cauchy);\n\n  { // Default settings\n    CDFAccumulator<double> cdf;\n    for ( uint16 i = 0; i < 50000; i++ )\n      cdf( generator() );\n\n    EXPECT_NEAR( cdf.median(), 35.0, 2.0 );\n    EXPECT_NEAR( cdf.first_quartile(), -45, 4.0 );\n    EXPECT_NEAR( cdf.third_quartile(), 115, 4.0 );\n  }\n  { // More quantiles == more precision\n    CDFAccumulator<double> cdf(2000,500);\n    for ( uint16 i = 0; i < 50000; i++ )\n      cdf( generator() );\n\n    EXPECT_NEAR( cdf.median(), 35.0, 1.0 );\n    EXPECT_NEAR( cdf.first_quartile(), -45, 2.0 );\n    EXPECT_NEAR( cdf.third_quartile(), 115, 2.0 );\n  }\n}\n\nTEST(Accumulators, CDF_triangular) {\n  boost::mt19937 random_gen(42);\n  boost::triangle_distribution<double> triangular(10,60,80);\n  boost::variate_generator<boost::mt19937&,\n    boost::triangle_distribution<double> > generator(random_gen, triangular);\n\n  { // Default settings\n    CDFAccumulator<double> cdf;\n    for ( uint16 i = 0; i < 50000; i++ )\n      cdf( generator() );\n\n    EXPECT_NEAR( cdf.median(), 51.833, 1.0 );\n    EXPECT_NEAR( cdf.first_quartile(), 39.6, 2.0 );\n    EXPECT_NEAR( cdf.third_quartile(), 61.3, 2.0 );\n    EXPECT_NEAR( cdf.approximate_mean(), 50, 1.0 );\n    EXPECT_NEAR( cdf.approximate_mean(0.05), 50, 0.5 );\n    EXPECT_NEAR( cdf.approximate_stddev(), 14.7196, 2.0 );\n    EXPECT_NEAR( cdf.approximate_stddev(0.05), 14.7196, 1.0 );\n  }\n  { // More quantiles == more precision\n    CDFAccumulator<double> cdf(2000,500);\n    for ( uint16 i = 0; i < 50000; i++ )\n      cdf( generator() );\n\n    EXPECT_NEAR( cdf.median(), 51.833, 0.5 );\n    EXPECT_NEAR( cdf.first_quartile(), 39.6, 1.0 );\n    EXPECT_NEAR( cdf.third_quartile(), 61.3, 1.0 );\n    EXPECT_NEAR( cdf.approximate_mean(), 50, 0.5 );\n    EXPECT_NEAR( cdf.approximate_mean(0.05), 50, 0.25 );\n    EXPECT_NEAR( cdf.approximate_stddev(), 14.7196, 3.0 );\n    EXPECT_NEAR( cdf.approximate_stddev(0.05), 14.7196, 0.5 );\n  }\n}\n\nTEST(Accumulators, Median) {\n  MedianAccumulator<double> median;\n\n  boost::mt19937 random_gen(42);\n  boost::cauchy_distribution<double> cauchy(35,80);\n  boost::variate_generator<boost::mt19937&,\n    boost::cauchy_distribution<double> > generator(random_gen, cauchy);\n\n  for ( uint16 i = 0; i < 50000; i++ )\n    median( generator() );\n\n  EXPECT_NEAR( median.value(), 35.0, 1.5 );\n}\n\nTEST(Accumulators, CDF_Merge ) {\n  boost::mt19937 random_gen(42);\n  boost::normal_distribution<double> norm1(0, 3);\n  boost::normal_distribution<double> norm2(5, 3);\n  boost::variate_generator<boost::mt19937&, boost::normal_distribution<double> > generator1( random_gen, norm1 );\n  boost::variate_generator<boost::mt19937&, boost::normal_distribution<double> > generator2( random_gen, norm2 );\n\n  CDFAccumulator<double> cdf1, cdf2, cdf3;\n  // 1 will only see gen1 .. but will later be merged with 2.\n  // 2 will only see gen2\n  // 3 is our control and sees both gen1 and gen2;\n  for ( size_t i = 0; i < 50000; i++ ) {\n    double sample1 = generator1(), sample2 = generator2();\n    cdf1( sample1 );\n    cdf2( sample2 );\n    cdf3( sample1 );\n    cdf3( sample2 );\n  }\n\n  cdf1.update();\n  cdf2.update();\n  cdf3.update();\n  cdf1(cdf2);\n\n  EXPECT_NEAR( cdf1.median(), cdf3.median(), 0.01 );\n  EXPECT_NEAR( cdf1.first_quartile(), cdf3.first_quartile(), 0.01 );\n  EXPECT_NEAR( cdf1.third_quartile(), cdf3.third_quartile(), 0.01 );\n  EXPECT_NEAR( cdf1.approximate_mean(),\n               cdf3.approximate_mean(), 0.01 );\n}\n", "meta": {"hexsha": "c06464621a1311989a00b142ec97cd28762b7141", "size": 4580, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/vw/Math/tests/TestAccumulators.cxx", "max_stars_repo_name": "dshean/visionworkbench", "max_stars_repo_head_hexsha": "d5bb23f8146ceee0a05ba7c1472c95b7a8f5fcc4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-02-04T20:08:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-07T05:07:13.000Z", "max_issues_repo_path": "src/vw/Math/tests/TestAccumulators.cxx", "max_issues_repo_name": "CVandML/visionworkbench", "max_issues_repo_head_hexsha": "c432442b1e806961b4b7eb15d73051ebb08f1d6b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vw/Math/tests/TestAccumulators.cxx", "max_forks_repo_name": "CVandML/visionworkbench", "max_forks_repo_head_hexsha": "c432442b1e806961b4b7eb15d73051ebb08f1d6b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-26T00:44:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T00:44:27.000Z", "avg_line_length": 34.696969697, "max_line_length": 113, "alphanum_fraction": 0.6783842795, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5659763144235402}}
{"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": "//=======================================================================\r\n// Copyright 2008\r\n// Author: Matyas W Egyhazy\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 <iostream>\r\n#include <vector>\r\n#include <fstream>\r\n#include <set>\r\n#include <ctime>\r\n\r\n#include <boost/assert.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/random.hpp>\r\n#include <boost/timer.hpp>\r\n#include <boost/integer_traits.hpp>\r\n#include <boost/graph/adjacency_matrix.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/simple_point.hpp>\r\n#include <boost/graph/metric_tsp_approx.hpp>\r\n#include <boost/graph/graphviz.hpp>\r\n\r\n// TODO: Integrate this into the test system a little better. We need to run\r\n// the test with some kind of input file.\r\n\r\ntemplate<typename PointType>\r\nstruct cmpPnt\r\n{\r\n    bool operator()(const boost::simple_point<PointType>& l,\r\n                    const boost::simple_point<PointType>& r) const\r\n    { return (l.x > r.x); }\r\n};\r\n\r\n//add edges to the graph (for each node connect it to all other nodes)\r\ntemplate<typename VertexListGraph, typename PointContainer,\r\n    typename WeightMap, typename VertexIndexMap>\r\nvoid connectAllEuclidean(VertexListGraph& g,\r\n                        const PointContainer& points,\r\n                        WeightMap wmap,            // Property maps passed by value\r\n                        VertexIndexMap vmap,       // Property maps passed by value\r\n                        int /*sz*/)\r\n{\r\n    using namespace boost;\r\n    using namespace std;\r\n    typedef typename graph_traits<VertexListGraph>::edge_descriptor Edge;\r\n    typedef typename graph_traits<VertexListGraph>::vertex_iterator VItr;\r\n\r\n    Edge e;\r\n    bool inserted;\r\n\r\n    pair<VItr, VItr> verts(vertices(g));\r\n    for (VItr src(verts.first); src != verts.second; src++)\r\n    {\r\n        for (VItr dest(src); dest != verts.second; dest++)\r\n        {\r\n            if (dest != src)\r\n            {\r\n                double weight(sqrt(pow(\r\n                    static_cast<double>(points[vmap[*src]].x -\r\n                        points[vmap[*dest]].x), 2.0) +\r\n                    pow(static_cast<double>(points[vmap[*dest]].y -\r\n                        points[vmap[*src]].y), 2.0)));\r\n\r\n                boost::tie(e, inserted) = add_edge(*src, *dest, g);\r\n\r\n                wmap[e] = weight;\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n}\r\n\r\n// Create a randomly generated point\r\n// scatter time execution\r\nvoid testScalability(unsigned numpts)\r\n{\r\n    using namespace boost;\r\n    using namespace std;\r\n\r\n    typedef adjacency_matrix<undirectedS, no_property,\r\n        property <edge_weight_t, double,\r\n        property<edge_index_t, int> > > Graph;\r\n    typedef graph_traits<Graph>::vertex_descriptor Vertex;\r\n    typedef graph_traits <Graph>::edge_descriptor Edge;\r\n    typedef property_map<Graph, edge_weight_t>::type WeightMap;\r\n    typedef set<simple_point<double>, cmpPnt<double> > PointSet;\r\n    typedef vector< Vertex > Container;\r\n\r\n    boost::mt19937 rng(time(0));\r\n    uniform_real<> range(0.01, (numpts * 2));\r\n    variate_generator<boost::mt19937&, uniform_real<> >\r\n        pnt_gen(rng, range);\r\n\r\n    PointSet points;\r\n    simple_point<double> pnt;\r\n\r\n    while (points.size() < numpts)\r\n    {\r\n        pnt.x = pnt_gen();\r\n        pnt.y = pnt_gen();\r\n        points.insert(pnt);\r\n    }\r\n\r\n    Graph g(numpts);\r\n    WeightMap weight_map(get(edge_weight, g));\r\n    vector<simple_point<double> > point_vec(points.begin(), points.end());\r\n\r\n    connectAllEuclidean(g, point_vec, weight_map, get(vertex_index, g), numpts);\r\n\r\n    Container c;\r\n    timer t;\r\n    double len = 0.0;\r\n\r\n    // Run the TSP approx, creating the visitor on the fly.\r\n    metric_tsp_approx(g, make_tsp_tour_len_visitor(g, back_inserter(c), len, weight_map));\r\n\r\n    cout << \"Number of points: \" << num_vertices(g) << endl;\r\n    cout << \"Number of edges: \" << num_edges(g) << endl;\r\n    cout << \"Length of tour: \" << len << endl;\r\n    cout << \"Elapsed: \" << t.elapsed() << endl;\r\n}\r\n\r\ntemplate <typename PositionVec>\r\nvoid checkAdjList(PositionVec v)\r\n{\r\n    using namespace std;\r\n    using namespace boost;\r\n\r\n    typedef adjacency_list<listS, listS, undirectedS> Graph;\r\n    typedef graph_traits<Graph>::vertex_descriptor Vertex;\r\n    typedef graph_traits <Graph>::edge_descriptor Edge;\r\n    typedef vector<Vertex> Container;\r\n    typedef map<Vertex, std::size_t> VertexIndexMap;\r\n    typedef map<Edge, double> EdgeWeightMap;\r\n    typedef associative_property_map<VertexIndexMap> VPropertyMap;\r\n    typedef associative_property_map<EdgeWeightMap> EWeightPropertyMap;\r\n    typedef graph_traits<Graph>::vertex_iterator VItr;\r\n\r\n    Container c;\r\n    EdgeWeightMap w_map;\r\n    VertexIndexMap v_map;\r\n    VPropertyMap v_pmap(v_map);\r\n    EWeightPropertyMap w_pmap(w_map);\r\n\r\n    Graph g(v.size());\r\n\r\n    //create vertex index map\r\n    VItr vi, ve;\r\n    int idx(0);\r\n    for (boost::tie(vi, ve) = vertices(g); vi != ve; ++vi)\r\n    {\r\n        Vertex v(*vi);\r\n        v_pmap[v] = idx;\r\n        idx++;\r\n    }\r\n\r\n    connectAllEuclidean(g, v, w_pmap,\r\n        v_pmap, v.size());\r\n\r\n    metric_tsp_approx_from_vertex(g,\r\n        *vertices(g).first,\r\n        w_pmap,\r\n        v_pmap,\r\n        tsp_tour_visitor<back_insert_iterator<Container > >\r\n        (back_inserter(c)));\r\n\r\n    cout << \"adj_list\" << endl;\r\n    for (Container::iterator itr = c.begin(); itr != c.end(); ++itr) {\r\n        cout << v_map[*itr] << \" \";\r\n    }\r\n    cout << endl << endl;\r\n\r\n    c.clear();\r\n}\r\n\r\nstatic void usage()\r\n{\r\n    using namespace std;\r\n    cerr << \"To run this program properly please place a \"\r\n         << \"file called graph.txt\"\r\n         << endl << \"into the current working directory.\" << endl\r\n         << \"Each line of this file should be a coordinate specifying the\"\r\n         << endl << \"location of a vertex\" << endl\r\n         << \"For example: \" << endl << \"1,2\" << endl << \"20,4\" << endl\r\n         << \"15,7\" << endl << endl;\r\n}\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n   using namespace boost;\r\n   using namespace std;\r\n\r\n    typedef vector<simple_point<double> > PositionVec;\r\n    typedef adjacency_matrix<undirectedS, no_property,\r\n        property <edge_weight_t, double> > Graph;\r\n    typedef graph_traits<Graph>::vertex_descriptor Vertex;\r\n    typedef graph_traits <Graph>::edge_descriptor Edge;\r\n    typedef vector<Vertex> Container;\r\n    typedef property_map<Graph, edge_weight_t>::type WeightMap;\r\n    typedef property_map<Graph, vertex_index_t>::type VertexMap;\r\n\r\n    // Make sure that the the we can parse the given file.\r\n    if(argc < 2) {\r\n        usage();\r\n        // return -1;\r\n        return 0;\r\n    }\r\n\r\n    // Open the graph file, failing if one isn't given on the command line.\r\n    ifstream fin(argv[1]);\r\n    if (!fin)\r\n    {\r\n        usage();\r\n        // return -1;\r\n        return 0;\r\n    }\r\n\r\n   string line;\r\n   PositionVec position_vec;\r\n\r\n   int n(0);\r\n   while (getline(fin, line))\r\n   {\r\n       simple_point<double> vertex;\r\n\r\n       size_t idx(line.find(\",\"));\r\n       string xStr(line.substr(0, idx));\r\n       string yStr(line.substr(idx + 1, line.size() - idx));\r\n\r\n       vertex.x = lexical_cast<double>(xStr);\r\n       vertex.y = lexical_cast<double>(yStr);\r\n\r\n       position_vec.push_back(vertex);\r\n       n++;\r\n   }\r\n\r\n   fin.close();\r\n\r\n   Container c;\r\n   Graph g(position_vec.size());\r\n   WeightMap weight_map(get(edge_weight, g));\r\n   VertexMap v_map = get(vertex_index, g);\r\n\r\n   connectAllEuclidean(g, position_vec, weight_map, v_map, n);\r\n\r\n   metric_tsp_approx_tour(g, back_inserter(c));\r\n\r\n   for (vector<Vertex>::iterator itr = c.begin(); itr != c.end(); ++itr)\r\n   {\r\n       cout << *itr << \" \";\r\n   }\r\n   cout << endl << endl;\r\n\r\n   c.clear();\r\n\r\n   checkAdjList(position_vec);\r\n\r\n   metric_tsp_approx_from_vertex(g, *vertices(g).first,\r\n       get(edge_weight, g), get(vertex_index, g),\r\n       tsp_tour_visitor<back_insert_iterator<vector<Vertex> > >\r\n       (back_inserter(c)));\r\n\r\n   for (vector<Vertex>::iterator itr = c.begin(); itr != c.end(); ++itr)\r\n   {\r\n       cout << *itr << \" \";\r\n   }\r\n   cout << endl << endl;\r\n\r\n   c.clear();\r\n\r\n   double len(0.0);\r\n   try {\r\n       metric_tsp_approx(g, make_tsp_tour_len_visitor(g, back_inserter(c), len, weight_map));\r\n   }\r\n   catch (const bad_graph& e) {\r\n       cerr << \"bad_graph: \" << e.what() << endl;\r\n       return -1;\r\n   }\r\n\r\n   cout << \"Number of points: \" << num_vertices(g) << endl;\r\n   cout << \"Number of edges: \" << num_edges(g) << endl;\r\n   cout << \"Length of Tour: \" << len << endl;\r\n\r\n   int cnt(0);\r\n   pair<Vertex,Vertex> triangleEdge;\r\n   for (vector<Vertex>::iterator itr = c.begin(); itr != c.end();\r\n       ++itr, ++cnt)\r\n   {\r\n       cout << *itr << \" \";\r\n\r\n       if (cnt == 2)\r\n       {\r\n           triangleEdge.first = *itr;\r\n       }\r\n       if (cnt == 3)\r\n       {\r\n           triangleEdge.second = *itr;\r\n       }\r\n   }\r\n   cout << endl << endl;\r\n   c.clear();\r\n\r\n   testScalability(1000);\r\n\r\n   // if the graph is not fully connected then some of the\r\n   // assumed triangle-inequality edges may not exist\r\n   remove_edge(edge(triangleEdge.first, triangleEdge.second, g).first, g);\r\n\r\n    // Make sure that we can actually trap incomplete graphs.\r\n    bool caught = false;\r\n    try {\r\n        double len = 0.0;\r\n        metric_tsp_approx(g, make_tsp_tour_len_visitor(g, back_inserter(c), len, weight_map));\r\n    }\r\n    catch (const bad_graph& e) { caught = true; }\r\n    BOOST_ASSERT(caught);\r\n\r\n   return 0;\r\n}\r\n", "meta": {"hexsha": "b1d849985a1809d9b31b2c47eee7f1ecfc323c45", "size": 9647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/test/metric_tsp_approx.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/test/metric_tsp_approx.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": 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/graph/test/metric_tsp_approx.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 29.6830769231, "max_line_length": 95, "alphanum_fraction": 0.5889913963, "num_tokens": 2303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5659763033893518}}
{"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": "#include <random>\n#include <limits>\n#include <iostream>\n#include <boost/test/unit_test.hpp>\n#include \"algorithms/math/least_common_multiple.hpp\"\n\nBOOST_AUTO_TEST_SUITE(TestLeastCommonMultiple)\n\nBOOST_AUTO_TEST_CASE(numbers) {\n    BOOST_CHECK(Algo::Math::LeastCommonMultiple::Find(1, 1) == 1);\n    BOOST_CHECK(Algo::Math::LeastCommonMultiple::Find(5, 1) == 5);\n    BOOST_CHECK(Algo::Math::LeastCommonMultiple::Find(5, 15) == 15);\n    BOOST_CHECK(Algo::Math::LeastCommonMultiple::Find(6, 8) == 24);\n    BOOST_CHECK(Algo::Math::LeastCommonMultiple::Find(761457, 614573) == 467970912861);\n}\n\nBOOST_AUTO_TEST_CASE(random_numbers) {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n\n    std::uniform_int_distribution<int> valuesDist(1, 100);\n    for (int i = 0; i < 100; ++i) {\n        const uint64_t first = static_cast<uint64_t>(valuesDist(gen));\n        const uint64_t second = static_cast<uint64_t>(valuesDist(gen));\n\n        const auto result = Algo::Math::LeastCommonMultiple::Find(first, second);\n        const auto resultNaive =\n                Algo::Math::LeastCommonMultiple::FindNaive(first, second);\n\n        if (result != resultNaive)\n        {\n            std::cout << first << \" and \" << second << \": \" <<\n                         result << \" vs \" << resultNaive << std::endl;\n            BOOST_FAIL(\"Different results!\");\n            return;\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "dbdd8242adab89387655839289a143ae848ab790", "size": 1405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/math/test_least_common_multiple.cpp", "max_stars_repo_name": "iamantony/CppNotes", "max_stars_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T14:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T09:51:43.000Z", "max_issues_repo_path": "test/algorithms/math/test_least_common_multiple.cpp", "max_issues_repo_name": "iamantony/CppNotes", "max_issues_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T07:38:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-02T11:00:58.000Z", "max_forks_repo_path": "test/algorithms/math/test_least_common_multiple.cpp", "max_forks_repo_name": "iamantony/CppNotes", "max_forks_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-11T14:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T08:53:50.000Z", "avg_line_length": 34.2682926829, "max_line_length": 87, "alphanum_fraction": 0.6448398577, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5659762981892684}}
{"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\ufffd-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": "/*\n Copyright (C) 2020 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include \"toplevelfixture.hpp\"\n\n#include <qle/models/exactbachelierimpliedvolatility.hpp>\n\n#include <ql/pricingengines/blackformula.hpp>\n\n#include <boost/make_shared.hpp>\n#include <boost/test/unit_test.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace boost::unit_test_framework;\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(ExactBachelierImpliedVolatilityTest)\n\nBOOST_AUTO_TEST_CASE(testExactBachelierImpliedVolatility) {\n\n    BOOST_TEST_MESSAGE(\"Testing exact Bachelier implied volatility...\");\n\n    Real tolerance = 1E-4; // percent, i.e. we test for 1E-6 relative error\n    Real forward = 0.05;   // fix the forward, only the difference forward - strike matters\n\n    for (Real strikeSpread = -0.10; strikeSpread < 0.10 + 1E-5; strikeSpread += 0.001) {\n        Real strike = forward + strikeSpread;\n        for (Real vol = 0.0; vol < 0.02 + 1E-5; vol += 0.001) {\n            for (Real tte = 0.001; tte < 51.0; tte += 0.1) {\n                Real stdDev = std::sqrt(tte) * vol;\n                Real call = bachelierBlackFormula(Option::Call, strike, forward, stdDev);\n                Real put = bachelierBlackFormula(Option::Put, strike, forward, stdDev);\n                if (std::abs(call) < 1E-12 || std::abs(put) < 1E-12)\n                    continue;\n                Real impliedVolCall = exactBachelierImpliedVolatility(Option::Call, strike, forward, tte, call);\n                Real impliedVolPut = exactBachelierImpliedVolatility(Option::Put, strike, forward, tte, put);\n                BOOST_CHECK_CLOSE(vol, impliedVolCall, tolerance);\n                BOOST_CHECK_CLOSE(vol, impliedVolPut, tolerance);\n            }\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "57744ad4ebda75fd4de1509b09976164aa1f0680", "size": 2527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/exactbachelierimpliedvolatility.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/test/exactbachelierimpliedvolatility.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/test/exactbachelierimpliedvolatility.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 39.484375, "max_line_length": 112, "alphanum_fraction": 0.7067669173, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5659145575595866}}
{"text": "//\n// Created by kellerberrin on 13/12/19.\n//\n\n#include \"kpl_asrv.h\"\n\n#include \"kel_distribution.h\"\n\n#include <boost/math/distributions/gamma.hpp>\n\nnamespace kel = kellerberrin;\n\n\nnamespace kpl = kellerberrin::phylogenetic;\n\n\nvoid kpl::ASRV::clear() {\n\n  // Rate homogeneity is the default\n  _invar_model = false;\n  _ratevar_fixed = false;\n  _pinvar_fixed = false;\n  _ratevar_ptr = std::make_shared<double>(1.0);\n  _pinvar_ptr = std::make_shared<double>(0.0);\n  _num_categ = 1;\n  recalcASRV();\n\n}\n\n\n\n\n\nvoid kpl::ASRV::recalcASRV() {\n  // This implementation assumes discrete gamma among-site rate heterogeneity\n  // using a _num_categ category discrete gamma distribution with equal category\n  // probabilities and Gamma density with mean 1.0 and variance _rate_var.\n  // If _invar_model is true, then rate probs will sum to 1 - _pinvar rather than 1\n  // and the mean rate will be 1/(1 - _pinvar) rather than 1; the rest of the invariable\n  // sites component of the model is handled outside the ASRV class.\n\n  // _num_categ, _rate_var, and _pinvar must all have been assigned in order to compute rates and probs\n  if ((not _ratevar_ptr) || (_num_categ == 0) || (not _pinvar_ptr) ) {\n\n    return;\n\n  }\n\n  double pinvar = *_pinvar_ptr;\n  assert(pinvar >= 0.0);\n  assert(pinvar <  1.0);\n\n  assert(_num_categ > 0);\n\n  double equal_prob = 1.0 /_num_categ;\n  double mean_rate_variable_sites = 1.0;\n\n  if (_invar_model) {\n\n    mean_rate_variable_sites = 1.0 / (1.0 - pinvar);\n\n  }\n\n  _rates.assign(_num_categ, mean_rate_variable_sites);\n  _probs.assign(_num_categ, equal_prob);\n\n  double rate_variance = *_ratevar_ptr;\n  assert(rate_variance >= 0.0);\n\n  if (_num_categ == 1 || rate_variance == 0.0)\n    return;\n\n  double alpha = 1.0/rate_variance;\n  double beta = rate_variance;\n\n// #define USE_BOOST  1 // Check the timing between the two gamma distribution functions.\n#ifdef USE_BOOST\n  boost::math::gamma_distribution<> my_gamma(alpha, beta);\n  boost::math::gamma_distribution<> my_gamma_plus(alpha + 1.0, beta);\n#else\n  kel::GammaDistribution k_gamma(alpha, beta);\n  kel::GammaDistribution k_gamma_plus(alpha + 1.0, beta);\n#endif\n\n  double cum_upper        = 0.0;\n  double cum_upper_plus   = 0.0;\n  double upper            = 0.0;\n  double cum_prob         = 0.0;\n\n  for (unsigned i = 1; i <= _num_categ; ++i) {\n\n    double cum_lower_plus       = cum_upper_plus;\n    double cum_lower            = cum_upper;\n    cum_prob                    += equal_prob;\n\n    if (i < _num_categ) {\n\n#ifdef USE_BOOST\n      upper                   = boost::math::quantile(my_gamma, cum_prob);\n      cum_upper_plus          = boost::math::cdf(my_gamma_plus, upper);\n      cum_upper               = boost::math::cdf(my_gamma, upper);\n#else\n      upper                   = k_gamma.quantile(cum_prob);\n      cum_upper_plus          = k_gamma_plus.cdf(upper);\n      cum_upper               = k_gamma.cdf(upper);\n#endif\n    }\n    else {\n      cum_upper_plus          = 1.0;\n      cum_upper               = 1.0;\n    }\n\n    double numer                = cum_upper_plus - cum_lower_plus;\n    double denom                = cum_upper - cum_lower;\n    double r_mean               = (denom > 0.0 ? (alpha*beta*numer/denom) : 0.0);\n    _rates[i-1]        = r_mean*mean_rate_variable_sites;\n  }\n\n}", "meta": {"hexsha": "e55a65b22e0d5bacf5a0e97bc70154174b436d2b", "size": 3262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kpl_phylogenetic/kpl_asrv.cpp", "max_stars_repo_name": "kellerberrin/OSM_Gene_Cpp", "max_stars_repo_head_hexsha": "4ec4d1244f3f1b16213cf05f0056d8e5f85d68c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-09T16:24:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T16:24:06.000Z", "max_issues_repo_path": "kpl_phylogenetic/kpl_asrv.cpp", "max_issues_repo_name": "kellerberrin/KGL_Gene", "max_issues_repo_head_hexsha": "f8e6c14b8b2009d82d692b28354561b5f0513c5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kpl_phylogenetic/kpl_asrv.cpp", "max_forks_repo_name": "kellerberrin/KGL_Gene", "max_forks_repo_head_hexsha": "f8e6c14b8b2009d82d692b28354561b5f0513c5e", "max_forks_repo_licenses": ["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.4117647059, "max_line_length": 103, "alphanum_fraction": 0.6446965052, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5659145310700485}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nGeneralizedEigenSolver<MatrixXf> ges;\nMatrixXf A = MatrixXf::Random(4,4);\nMatrixXf B = MatrixXf::Random(4,4);\nges.compute(A, B);\ncout << \"The (complex) numerators of the generalzied eigenvalues are: \" << ges.alphas().transpose() << endl;\ncout << \"The (real) denominatore of the generalzied eigenvalues are: \" << ges.betas().transpose() << endl;\ncout << \"The (complex) generalzied eigenvalues are (alphas./beta): \" << ges.eigenvalues().transpose() << endl;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "43ca3acbe5e03ddd9b5bfdb49f5c7caa1ec96a59", "size": 989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_GeneralizedEigenSolver.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_GeneralizedEigenSolver.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_GeneralizedEigenSolver.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9032258065, "max_line_length": 224, "alphanum_fraction": 0.7007077856, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5658552199605672}}
{"text": "#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\n#include <iostream>\n#include <string>\n#include <complex>\n\nnamespace client{\n  template <typename Iterator>\n    bool parse_complex(Iterator first, Iterator last, std::complex<double>& c){\n      using boost::spirit::qi::double_;\n      using boost::spirit::qi::_1;\n      using boost::spirit::qi::phrase_parse;\n      using boost::spirit::ascii::space;\n      using boost::phoenix::ref;\n\n      double rN = 0.0;\n      double iN = 0.0;\n      bool r = phrase_parse(first, last,\n          (\n            '(' >> double_[ref(rN) = _1] >> -(',' >> double_[ref(iN) = _1]) >> ')'\n            | double_[ref(rN) = _1]\n          ),\n          space);\n\n      if(!r || first != last) // fail if we did not get a full match\n        return false;\n      c = std::complex<double>(rN, iN);\n      return r;\n    }\n}\n\nint main(){\n  std::string str;\n  while(getline(std::cin, str)){\n    if(str.empty() || str[0] == 'q' || str[0] == 'Q')\n      break;\n\n    std::complex<double> c;\n    if(client::parse_complex(str.begin(), str.end(), c)){\n      std::cout << \"Parsing succeeded\\n\" << \"got: \" << c << std::endl;\n    }\n    else{\n      std::cout << \"Parsing failed\\n\";\n    }\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "f141dbb9092b327992940849a32eb838529da2e8", "size": 1343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/qi/complex_number.cpp", "max_stars_repo_name": "2858199552/parser", "max_stars_repo_head_hexsha": "da05013dbc080ade3eec6af7bbfa017c3e0b4b9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-08T12:37:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-21T17:32:08.000Z", "max_issues_repo_path": "examples/qi/complex_number.cpp", "max_issues_repo_name": "2858199552/parser", "max_issues_repo_head_hexsha": "da05013dbc080ade3eec6af7bbfa017c3e0b4b9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/qi/complex_number.cpp", "max_forks_repo_name": "2858199552/parser", "max_forks_repo_head_hexsha": "da05013dbc080ade3eec6af7bbfa017c3e0b4b9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T05:20:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T05:20:41.000Z", "avg_line_length": 25.8269230769, "max_line_length": 82, "alphanum_fraction": 0.5711094564, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.5658552170367933}}
{"text": "// This source file should check the imported headers and do the simple things,\n// like querying library version. It doesn't intended to do some lengthy work\n// or running library tests - just only check that package is properly created.\n// See docs for details:\n// https://docs.conan.io/en/latest/creating_packages/getting_started.html#the-test-package-folder\n#include <boost/simd/pack.hpp>\n#include <boost/date_time.hpp>\n#include <iostream>\n\nnamespace bs = boost::simd;\n\nint main()\n{\n    using namespace boost::date_time;\n    bs::pack<float,4> p{1.f,2.f,3.f,4.f};\n    std::cout << \"Boost.SIMD test from README.md : \" << p + 10*p << \"\\n\";\n    std::cout << \"Boost.date_time interop test: \" << boost::gregorian::date(2021, Aug, 4) << \"\\n\";\n    return 0;\n}\n", "meta": {"hexsha": "ddf7bb1fb383ad8b09a89dd8db66a4bf682c6006", "size": 755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "recipes/procxx-boost-ext-simd/all/test_package/test_package.cpp", "max_stars_repo_name": "rockandsalt/conan-center-index", "max_stars_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 562.0, "max_stars_repo_stars_event_min_datetime": "2019-09-04T12:23:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:41:43.000Z", "max_issues_repo_path": "recipes/procxx-boost-ext-simd/all/test_package/test_package.cpp", "max_issues_repo_name": "rockandsalt/conan-center-index", "max_issues_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9799.0, "max_issues_repo_issues_event_min_datetime": "2019-09-04T12:02:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:45.000Z", "max_forks_repo_path": "recipes/procxx-boost-ext-simd/all/test_package/test_package.cpp", "max_forks_repo_name": "rockandsalt/conan-center-index", "max_forks_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1126.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T11:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T16:43:38.000Z", "avg_line_length": 37.75, "max_line_length": 98, "alphanum_fraction": 0.6940397351, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5658342029216035}}
{"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": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace polyfem {\nnamespace autogen {\nvoid q_nodes_2d(const int q, Eigen::MatrixXd &val);\n\nvoid q_basis_value_2d(const int q, const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val);\n\nvoid q_grad_basis_value_2d(const int q, const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val);\n\n\nvoid q_nodes_3d(const int q, Eigen::MatrixXd &val);\n\nvoid q_basis_value_3d(const int q, const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val);\n\nvoid q_grad_basis_value_3d(const int q, const int local_index, const Eigen::MatrixXd &uv, Eigen::MatrixXd &val);\n\n\n\nstatic const int MAX_Q_BASES = 3;\n\n}}\n", "meta": {"hexsha": "6b08c2377e38f678b19ecc7a69fedb53e7b65807", "size": 671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/autogen/auto_q_bases.hpp", "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/autogen/auto_q_bases.hpp", "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/autogen/auto_q_bases.hpp", "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": 26.84, "max_line_length": 112, "alphanum_fraction": 0.7585692996, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5658341977258048}}
{"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": "// Copyright (C) 2018 Thanaphon Chavengsaksongkram <as12production@gmail.com>, He Sun <he.sun@ed.ac.uk>\n// This file is subject to the license terms in the LICENSE file\n// found in the top-level directory of this distribution.\n\n#ifndef GSPARSE_UNDIRECTEDGRAPH_HPP\n#define GSPARSE_UNDIRECTEDGRAPH_HPP\n\n#include <Eigen/Sparse>  \n#include <Eigen/Dense>\n\n#include <exception>  // For exception handling\n#include <sstream>    // For exception messages\n#include <string>     \n#include <vector>\n#include <map>\n#include <cstddef>   // size_t definition\n#include <cmath>     \n#include <memory>    // Shared_ptr\n\n#include \"Config.hpp\"\n#include \"Interface/Graph.hpp\"\n#include \"Interface/GraphReader.hpp\"\n\n/* TODO:\n    // Support move operator. Review Eigen documentation.\n*/\n\nnamespace gSparse\n{\n    //! An Undirected Graph class\n    /*!\n        This class provides a multiple representation of an Undirected, Simple graph. \n    */\n\tclass UndirectedGraph : public IGraph\n\t{\n\tpublic:\n\t\t//! Graph data type should not be copied by value\n\t\tUndirectedGraph(const UndirectedGraph & graph)  = delete;  \n        /*{\n            // Call assignment operator\n            *this = graph; \n        }*/\n        //! Graph data type should not be copied by value / reassigne due to Eigen data type\n\t\tUndirectedGraph & operator=(const UndirectedGraph & rhs) = delete;\n        /*{\n            if (this != &rhs)\n            {            \n                // Perform expensive copy on these matrix\n                this->_adjMatrix = rhs._adjMatrix;\n                this->_degMatrix = rhs._degMatrix;\n                this->_incidentMatrix = rhs._incidentMatrix;\n                this->_weightMatrix = rhs._weightMatrix;\n                this->_laplacianMatrix = rhs._laplacianMatrix;\n                this->_edges = rhs._edges;\n                this->_weights = rhs._weights;\n                this->_edgeCount = rhs._edgeCount;\n                this->_nodeCount = rhs._nodeCount;\n            }\n            return *this;\n        }*/\n\n\t\t//! A constructor to initialize graph based on GraphReader\n        /*!\n        \\param DataReader: A subclass of IGraphReader which provides an interface to read external data.\n        */\n\t\tUndirectedGraph(const gSparse::GraphReader & DataReader)\n\t\t{\n\t\t\tif (DataReader == nullptr)\n\t\t\t{\n\t\t\t\tthrow std::invalid_argument(\"UndirectedGraph: DataReader must not be NULL\");\n\t\t\t}\n\t\t\tDataReader->Read(_edges, _weights);\n\t\t\t//Initialize the graph system. \n\t\t\t_initializeSystem();\n\t\t}\n\n\t\t//! A constructor to initialize graph based from Edge data. Weight sets to one.\n        /*!\n        \\param Edges: An Eigen Matrix containing Edge List.\n        */\n\t\tUndirectedGraph(const gSparse::EdgeMatrix & Edges) :_edges(Edges)\n\t\t{\n\t\t\t_weights = gSparse::PrecisionMatrix::Ones(Edges.rows(), 1);\n\t\t\t_initializeSystem();\n\t\t}\n        //! A constructor to initialize graph based from Edge data. Weight sets to one.\n        /*!\n        \\param Edges: An Eigen Matrix containing Edge List.\n        \\param Weights: An Eigen Matrix containing associated Weights.\n        */\n\t\tUndirectedGraph(const gSparse::EdgeMatrix & Edges,\n\t\t\tconst gSparse::PrecisionRowMatrix & Weights) :\n\t\t\t_edges(Edges),\n\t\t\t_weights(Weights)\n\t\t{\n\t\t\t_initializeSystem();\n\t\t}\n        //! Return Graph's Adjancency Matrix\n\t\tvirtual inline const gSparse::SparsePrecisionMatrix & GetAdjacentMatrix() const { return _adjMatrix; }\n\t\t//! Return Graph's Incident Matrix\n        virtual inline const gSparse::SparsePrecisionMatrix & GetIncidentMatrix() const { return _incidentMatrix; }\n\t\t//! Return Graph's Degree Matrix\n        virtual inline const gSparse::SparsePrecisionMatrix & GetDegreeMatrix() const { return _degMatrix; }\n\t\t//! Return Graph's Weight Matrix\n        virtual inline const gSparse::SparsePrecisionMatrix & GetWeightMatrix() const { return _weightMatrix; }\n\t\t//! Return Graph's Laplacian Matrix\n        virtual inline const gSparse::SparsePrecisionMatrix &  GetLaplacianMatrix() const { return _laplacianMatrix; }\n\t\t//! Return Graph's Edge List Matrix\n        virtual inline const gSparse::EdgeMatrix & GetEdgeList() const { return _edges; }\n\t\t//! Return Graph's Weight List Matrix\n        virtual inline const gSparse::PrecisionRowMatrix & GetWeightList() const { return _weights; }\n        //! Return the number of Edges in the Graph\n\t\tvirtual inline std::size_t GetEdgeCount() const { return _edgeCount; }\n\t\t//! Return the number of Nodes in the Graph\n        virtual inline std::size_t GetNodeCount() const { return _nodeCount; }\n        // A destructor\n\t\tvirtual ~UndirectedGraph() = default;\n\tprotected:\n\t\tgSparse::SparsePrecisionMatrix _adjMatrix;        //!< adjacency matrix representation\n\t\tgSparse::SparsePrecisionMatrix _degMatrix;        //!< degree matrix representation\n\t\tgSparse::SparsePrecisionMatrix _incidentMatrix;   //!< incident matrix representation\n\t\tgSparse::SparsePrecisionMatrix _weightMatrix;     //!< weight matrix representation\n        gSparse::SparsePrecisionMatrix _laplacianMatrix;  //!< laplacian matrix representation\n\n\t\tgSparse::EdgeMatrix _edges;                        //!< edge list\n\t\tgSparse::PrecisionRowMatrix _weights;                 //!< weight list\n\n\t\tstd::size_t _edgeCount;                            //!< count of edges\n\t\tstd::size_t _nodeCount;                            //!< number of vertices\n\tprivate:\n        //! Private function to perform validate and build graph representations\n\t\tvirtual inline void _initializeSystem()\n\t\t{\n            #ifndef NDEBUG\n                // Enable input check only in DEBUG build\n                // Some of the checks are expensive such as checking minCoeff with O(n) runtime.\n\t\t\t    _validateInput(); \n            #endif\n\t\t\t_initializeMatrixSystem();\n\t\t}\n        //! validate preconditions\n\t\tvoid inline _validateInput()\n\t\t{\n\t\t\t//There are more edges than weights\n\t\t\tif (_edges.rows() != _weights.rows())\n\t\t\t{\n\t\t\t\tstd::stringstream ss;\n\t\t\t\tss << \"UndirectedGraph: Edges.rows(): \" << _edges.rows() << \" =/= Weights.rows() \" << _weights.rows() << std::endl;\n\t\t\t\tthrow std::invalid_argument(ss.str());\n\t\t\t}\n\t\t\tif (_edges.cols() != 2)\n\t\t\t{\n\t\t\t\tstd::stringstream ss;\n\t\t\t\tss << \"UndirectedGraph: Edges.cols(): must equal to two\" << std::endl;\n\t\t\t\tthrow std::invalid_argument(ss.str());\n\t\t\t}\n\t\t\tif (_weights.minCoeff() < 0)\n\t\t\t{\n\t\t\t\tstd::stringstream ss;\n\t\t\t\tss << \"UndirectedGraph: Weights must be greater than zero\" << std::endl;\n\t\t\t\tthrow std::invalid_argument(ss.str());\n\t\t\t}\n\t\t}\n\t\t//! Private function to create graph representation from edge and weight list\n\t\tvoid inline _initializeMatrixSystem()\n\t\t{\n\t\t\t//Calculate counts\n\t\t\t_nodeCount = static_cast<std::size_t>(std::max(_edges.leftCols(1).maxCoeff(), _edges.rightCols(1).maxCoeff()) + 1);\n\t\t\t_edgeCount = _edges.rows();\n\n\t\t\t// Building Sparse Symmetric Adjacency Metric\n\t\t\tstd::vector<Eigen::Triplet<gSparse::PRECISION>> adjacentList;\n\t\t\tstd::vector<Eigen::Triplet<gSparse::PRECISION>> incidentList;\n\t\t\tstd::vector<Eigen::Triplet<gSparse::PRECISION>> weightList;\n\t\t\tadjacentList.reserve(_edgeCount * 2);\n\t\t\tincidentList.reserve(_edgeCount * 2);\n\t\t\tweightList.reserve(_edgeCount);\n\n            // Vectorized Zero \n\t\t\tEigen::VectorXd degVector = Eigen::VectorXd::Zero(_nodeCount);\n            \n\t\t\tfor (std::size_t i = 0; i != _edgeCount; ++i)\n\t\t\t{\n\t\t\t\tstd::size_t r = static_cast<std::size_t>(_edges(i, 0));\n\t\t\t\tstd::size_t c = static_cast<std::size_t>(_edges(i, 1));\n\n\t\t\t\t//adjacent matrix\n\t\t\t\tadjacentList.push_back(Eigen::Triplet<gSparse::PRECISION>(r, c, _weights(i, 0)));\n\t\t\t\tadjacentList.push_back(Eigen::Triplet<gSparse::PRECISION>(c, r, _weights(i, 0)));\n\n\t\t\t\t//degree matrix\n\t\t\t\tdegVector(r) += _weights(i, 0);\n\t\t\t\tdegVector(c) += _weights(i, 0);\n\n\t\t\t\t//incident matrix\n\t\t\t\tif (r != c)\n\t\t\t\t{\n\t\t\t\t\tincidentList.push_back(Eigen::Triplet<gSparse::PRECISION>(i, r, 1));\n\t\t\t\t\tincidentList.push_back(Eigen::Triplet<gSparse::PRECISION>(i, c, -1));\n\t\t\t\t}\n\t\t\t\t//Weight matrix\n\t\t\t\tweightList.push_back(Eigen::Triplet<gSparse::PRECISION>(i, i, _weights(i)));\n\t\t\t}\n\t\t\t// Create adj matrix\n\t\t\t_adjMatrix = gSparse::SparsePrecisionMatrix(_nodeCount, _nodeCount);\n\t\t\t_adjMatrix.setFromTriplets(adjacentList.begin(), adjacentList.end());\n\t\t\t\n\t\t\t\n\t\t\tstd::vector<Eigen::Triplet<gSparse::PRECISION>> degreeList;\n\t\t\tdegreeList.reserve(degVector.size());\n\t\t\tfor (int i = 0; i != degVector.size(); ++i)\n\t\t\t{\n\t\t\t\tdegreeList.push_back(Eigen::Triplet<gSparse::PRECISION>(i, i, degVector(i)));\n\t\t\t}\n\t\t\t//Create degree matrix\n\t\t\t_degMatrix = gSparse::SparsePrecisionMatrix(_nodeCount, _nodeCount);\n\t\t\t_degMatrix.setFromTriplets(degreeList.begin(), degreeList.end());\n\n\t\t\t//Create incident matrix\n\t\t\t_incidentMatrix = gSparse::SparsePrecisionMatrix(_edgeCount, _nodeCount);\n\t\t\t_incidentMatrix.setFromTriplets(incidentList.begin(), incidentList.end());\n\t\t\t//Create weight matrix\n\t\t\t_weightMatrix = gSparse::SparsePrecisionMatrix(_edgeCount, _edgeCount);\n\t\t\t_weightMatrix.setFromTriplets(weightList.begin(), weightList.end());\n            //Create Laplacian matrix\n            _laplacianMatrix = _degMatrix - _adjMatrix; \n\t\t\t\n\t\t}\n\t};\n}\n\n#endif\n", "meta": {"hexsha": "39fa391647a9d7a4e414a01b2c7e0eea5802e422", "size": 9015, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gSparse/UndirectedGraph.hpp", "max_stars_repo_name": "As-12/gSparse", "max_stars_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T09:38:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:03:55.000Z", "max_issues_repo_path": "include/gSparse/UndirectedGraph.hpp", "max_issues_repo_name": "As-12/gSparse", "max_issues_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gSparse/UndirectedGraph.hpp", "max_forks_repo_name": "As-12/gSparse", "max_forks_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-11T13:03:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T13:03:58.000Z", "avg_line_length": 38.6909871245, "max_line_length": 119, "alphanum_fraction": 0.664448142, "num_tokens": 2242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5658118575788117}}
{"text": "#include <functional>\n#include <gazebo/gazebo.hh>\n#include <gazebo/physics/physics.hh>\n#include <gazebo/common/common.hh>\n\n#include <boost/thread.hpp>\n#include <boost/thread/mutex.hpp>\n#include <ros/callback_queue.h>\n#include <ros/subscribe_options.h>\n\n#include <ignition/math.hh>\n#include <ignition/math/Vector3.hh>\n\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/Wrench.h>\n\n#include <ros/ros.h>\n#include \"std_msgs/String.h\"\n\n#include \"fdcl/common_types.hpp\"\n#include \"fdcl/ros_utils.hpp\"\n#include \"fdcl/matrix_utils.hpp\"\n\n\nnamespace igm = ignition::math;\n\n\nnamespace gazebo\n{\n\nclass UavControlPlugin : public ModelPlugin\n{\n\npublic: \n    void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf)\n    {\n        this->world = _model->GetWorld();\n        this->model = _model;\n\n        this->link_name = _sdf->GetElement(\"bodyName\")->Get<std::string>();\n        this->link = _model->GetLink(this->link_name);\n\n        // Listen to the update event. This event is broadcast every\n        // simulation iteration.\n        this->update_connection = event::Events::ConnectWorldUpdateBegin( \\\n            std::bind(&UavControlPlugin::update, this));\n\n        // Start the ROS subscriber.\n        this->topic_name = _sdf->GetElement(\"topicName\")->Get<std::string>();\n        this->sub_fm = this->n.subscribe(this->topic_name, 1, \\\n            UavControlPlugin::update_fm);\n    }\n\n\n    void update(void)\n    {\n        no_msg_counter++;\n        if (no_msg_counter > 100)\n        {\n            this->reset_uav();\n\n            if (!print_reset_message)\n            {\n                std::cout << ros::Time::now()\n                    << \": no new force messages, resetting UAV ..\" \n                    << std::endl;\n                print_reset_message = true;\n            }\n            return;\n        }\n\n        // Both must be in world frame.\n        this->calculate_force();\n        this->link->SetForce(this->force);\n        this->link->SetTorque(this->M_out);\n    }\n\n\n    void calculate_force(void)\n    {\n        this->update_uav_rotation();\n\n        fdcl::Vector3 force_body;\n        this->ignition_to_eigen(this->f, force_body);\n\n        fdcl::Vector3 force_world = this->R * force_body;\n        this->eigen_to_ignition(force_world, this->force);\n\n        fdcl::Vector3 M_body;\n        this->ignition_to_eigen(this->M, M_body);\n\n        fdcl::Vector3 M_world = this->R * M_body;\n        this->eigen_to_ignition(M_world, this->M_out);\n    }\n\n\n    void update_uav_rotation(void)\n    {\n        ignition::math::Pose3d pose = this->link->WorldPose();\n        ignition::math::Quaterniond q = pose.Rot();\n\n        fdcl::Vector3 q13(q.X(), q.Y(), q.Z());\n        double q4 = q.W();\n\n        fdcl::Matrix3 hat_q = fdcl::hat(q13);\n        this->R = eye3 + 2 * q4 * hat_q + 2 * hat_q * hat_q;\n    }\n\n\n    static void update_fm(const geometry_msgs::Wrench::ConstPtr& msg)\n    {\n\n        f[0] = msg->force.x;\n        f[1] = msg->force.y;\n        f[2] = msg->force.z;\n\n        M[0] = msg->torque.x;\n        M[1] = msg->torque.y;\n        M[2] = msg->torque.z;\n\n        no_msg_counter = 0;\n        print_reset_message = false;\n    }\n\n\n    void reset_uav(void)\n    {\n        this->link->SetForce(zero_fM);\n        this->link->SetTorque(zero_fM);\n    }\n\n\n    void ignition_to_eigen(\n        const ignition::math::Vector3d input, fdcl::Vector3 &output\n    )\n    {\n        output(0) = input[0];\n        output(1) = input[1];\n        output(2) = input[2];\n    } \n\n\n    void eigen_to_ignition(\n        const fdcl::Vector3 input, ignition::math::Vector3d &output\n    )\n    {\n        output[0] = input(0);\n        output[1] = input(1);\n        output[2] = input(2);\n    }\n\n\nprivate:\n    ros::Time t0 = ros::Time::now();\n\n    physics::ModelPtr model;\n    physics::WorldPtr world;\n    physics::LinkPtr link;\n\n    std::string link_name;\n    std::string topic_name;\n    \n    event::ConnectionPtr update_connection;\n    ros::Subscriber sub_fm; \n    ros::NodeHandle n;\n\n    static igm::Vector3d M;\n    igm::Vector3d M_out;\n    static igm::Vector3d f;\n\n    fdcl::Matrix3 R = fdcl::Matrix3::Identity();\n    igm::Vector3d force = igm::Vector3d::Zero;\n\n    static int no_msg_counter;\n    static bool print_reset_message;\n    \n    const igm::Vector3d zero_fM = igm::Vector3d::Zero;\n    const fdcl::Matrix3 eye3 = fdcl::Matrix3::Identity();\n};\n\n\n// Register this plugin with the simulator.\nGZ_REGISTER_MODEL_PLUGIN(UavControlPlugin)\n\n\n}  // End of namespace gazebo.\n\nigm::Vector3d gazebo::UavControlPlugin::f = igm::Vector3d::Zero;\nigm::Vector3d gazebo::UavControlPlugin::M = igm::Vector3d::Zero;\nint gazebo::UavControlPlugin::no_msg_counter = 0;\nbool gazebo::UavControlPlugin::print_reset_message = false;\n\n", "meta": {"hexsha": "7eae05d68889aed8da9012d8d15a055167285990", "size": 4675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/uav_plugins/src/control_plugin.cpp", "max_stars_repo_name": "fdcl-gwu/uav_simulator", "max_stars_repo_head_hexsha": "a31855babfe633ae326ecb36c4ff714066cdb269", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2021-02-11T08:26:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T00:41:12.000Z", "max_issues_repo_path": "src/uav_plugins/src/control_plugin.cpp", "max_issues_repo_name": "fdcl-gwu/uav_simulator", "max_issues_repo_head_hexsha": "a31855babfe633ae326ecb36c4ff714066cdb269", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-29T05:23:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T13:15:17.000Z", "max_forks_repo_path": "src/uav_plugins/src/control_plugin.cpp", "max_forks_repo_name": "fdcl-gwu/uav_simulator", "max_forks_repo_head_hexsha": "a31855babfe633ae326ecb36c4ff714066cdb269", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-03-17T13:03:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T00:41:20.000Z", "avg_line_length": 24.2227979275, "max_line_length": 77, "alphanum_fraction": 0.6051336898, "num_tokens": 1275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5658118472900447}}
{"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": "#define BOOST_TEST_MODULE \"test_periodic_gaussian_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/forcefield/local/PeriodicGaussianPotential.hpp>\n#include <mjolnir/math/constants.hpp>\n\nBOOST_AUTO_TEST_CASE(PeriodicGaussian_double)\n{\n    using real_type = double;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-6;\n    constexpr real_type   pi = mjolnir::math::constants<real_type>::pi();\n    const real_type e  = 2.0;\n    const real_type w  = 1.0;\n    const real_type r0 = 3.0;\n\n    mjolnir::PeriodicGaussianPotential<real_type> gaussian(e, w, r0);\n\n    const real_type x_min = -2 * pi;\n    const real_type x_max =  2 * pi;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + dx * i;\n        const real_type pot1 = gaussian.potential(x + h);\n        const real_type pot2 = gaussian.potential(x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = gaussian.derivative(x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(PeriodicGaussian_float)\n{\n    using real_type = float;\n    constexpr std::size_t N = 100;\n    constexpr real_type   h = 1e-3;\n    constexpr real_type   pi = mjolnir::math::constants<real_type>::pi();\n    const real_type e  = 2.0;\n    const real_type w  = 1.0;\n    const real_type r0 = 3.0;\n\n    mjolnir::PeriodicGaussianPotential<real_type> gaussian(e, w, r0);\n\n    const real_type x_min = -2 * pi;\n    const real_type x_max =  2 * pi;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + dx * i;\n        const real_type pot1 = gaussian.potential(x + h);\n        const real_type pot2 = gaussian.potential(x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = gaussian.derivative(x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n    }\n}\n", "meta": {"hexsha": "d5f0c20bbf65d74e278803abc7117a901a9ad1f4", "size": 2083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_periodic_gaussian_potential.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/core/test_periodic_gaussian_potential.cpp", "max_issues_repo_name": "yutakasi634/Mjolnir", "max_issues_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T11:41:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T10:01:38.000Z", "max_forks_repo_path": "test/core/test_periodic_gaussian_potential.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0895522388, "max_line_length": 73, "alphanum_fraction": 0.6481036966, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5657217821227614}}
{"text": "#include \"optimization.h\"\n\n#include \"angleAxisReprojectionError.hpp\"\n#include \"quaternionReprojectionError.hpp\"\n#include \"matrixReprojectionError.hpp\"\n\n#include <ceres/ceres.h>\n\n#include <chrono>\n#include <algorithm>\n\n#include <Eigen/Geometry>\n\nusing namespace std::chrono;\n\nnamespace roto\n{\nnamespace\n{\ntemplate<typename RotationType> void setupProblem(ceres::Problem& problem, const MeasuredScene<RotationType>& measurements, OptimizedScene<RotationType>& parameters);\ntemplate<> void setupProblem(ceres::Problem& problem, const MeasuredScene<AngleAxisRotation>& measurements, OptimizedScene<AngleAxisRotation>& parameters)\n{\n  addAngleAxisReprojectionError(problem, measurements, parameters);\n}\ntemplate<> void setupProblem(ceres::Problem& problem, const MeasuredScene<QuaternionRotation>& measurements, OptimizedScene<QuaternionRotation>& parameters)\n{\n  addQuaternionReprojectionError(problem, measurements, parameters);\n}\ntemplate<> void setupProblem(ceres::Problem& problem, const MeasuredScene<MatrixRotation>& measurements, OptimizedScene<MatrixRotation>& parameters)\n{\n  addMatrixReprojectionError(problem, measurements, parameters);\n}\n\ntemplate<typename RotationType> void print(const RotationType& expectedRotation, const RotationType& initialRotation, const RotationType& optimizedRotation);\ntemplate<> void print(const AngleAxisRotation& expectedRotation, const AngleAxisRotation& initialRotation, const AngleAxisRotation& optimizedRotation)\n{\n  std::cout << \"Initial: \" << initialRotation(0) << \" -> Expected: \" << expectedRotation(0) << \" Optimized: \" << optimizedRotation(0) << std::endl;\n  std::cout << \"Initial: \" << initialRotation(1) << \" -> Expected: \" << expectedRotation(1) << \" Optimized: \" << optimizedRotation(1) << std::endl;\n  std::cout << \"Initial: \" << initialRotation(2) << \" -> Expected: \" << expectedRotation(2) << \" Optimized: \" << optimizedRotation(2) << std::endl;\n  std::cout << \"-----------------------------------------\" << std::endl;\n}\ntemplate<> void print(const QuaternionRotation& expectedRotation, const QuaternionRotation& initialRotation, const QuaternionRotation& optimizedRotation)\n{\n  std::cout << \"Initial: \" << initialRotation.x() << \" -> Expected: \" << expectedRotation.x() << \" Optimized: \" << optimizedRotation.x() << std::endl;\n  std::cout << \"Initial: \" << initialRotation.y() << \" -> Expected: \" << expectedRotation.y() << \" Optimized: \" << optimizedRotation.y() << std::endl;\n  std::cout << \"Initial: \" << initialRotation.z() << \" -> Expected: \" << expectedRotation.z() << \" Optimized: \" << optimizedRotation.z() << std::endl;\n  std::cout << \"Initial: \" << initialRotation.w() << \" -> Expected: \" << expectedRotation.w() << \" Optimized: \" << optimizedRotation.w() << std::endl;\n  std::cout << \"-----------------------------------------\" << std::endl;\n}\ntemplate<> void print(const MatrixRotation& expectedRotation, const MatrixRotation& initialRotation, const MatrixRotation& optimizedRotation)\n{\n  std::cout << \"Initial: \" << initialRotation.row(0) << \" -> Expected: \" << expectedRotation.row(0) << \" Optimized: \" << optimizedRotation.row(0) << std::endl;\n  std::cout << \"Initial: \" << initialRotation.row(1) << \" -> Expected: \" << expectedRotation.row(1) << \" Optimized: \" << optimizedRotation.row(1) << std::endl;\n  std::cout << \"Initial: \" << initialRotation.row(2) << \" -> Expected: \" << expectedRotation.row(2) << \" Optimized: \" << optimizedRotation.row(2) << std::endl;\n  std::cout << \"-----------------------------------------\" << std::endl;\n}\n\ntemplate<typename RotationType> void printErrorStatistics(const std::vector<Camera<RotationType> >& expectedParameters, const std::vector<RotationType>& optimizedRotations);\ntemplate<> void printErrorStatistics(const std::vector<Camera<AngleAxisRotation> >& expectedParameters, const std::vector<AngleAxisRotation>& optimizedRotations)\n{\n  assert(expectedParameters.size() == optimizedRotations.size());\n\n  Eigen::Array3d meanErrorCoeffwise(0., 0., 0.);\n  Eigen::Array3d maxErrorCoeffwise(0., 0., 0.);\n  for(int i = 0; i < expectedParameters.size(); i++)\n  {\n    const Eigen::Array3d error = (expectedParameters.at(i).pose.rotation - optimizedRotations.at(i)).array();\n    meanErrorCoeffwise += error;\n    maxErrorCoeffwise = maxErrorCoeffwise.max(error);\n  }\n  meanErrorCoeffwise /= expectedParameters.size();\n\n  std::cout << \"Parameter error statistics: \" << std::endl;\n  std::cout << \"Mean error:\" << meanErrorCoeffwise << std::endl;\n  std::cout << \"Max error:\" << maxErrorCoeffwise << std::endl;\n}\ntemplate<> void printErrorStatistics(const std::vector<Camera<QuaternionRotation> >& expectedParameters, const std::vector<QuaternionRotation>& optimizedRotations)\n{\n  assert(expectedParameters.size() == optimizedRotations.size());\n\n  Eigen::Array4d meanErrorCoeffwise(0., 0., 0., 0.);\n  Eigen::Array4d maxErrorCoeffwise(0., 0., 0., 0.);\n  for(int i = 0; i < expectedParameters.size(); i++)\n  {\n    const Eigen::Array4d error = (expectedParameters.at(i).pose.rotation.coeffs() - optimizedRotations.at(i).coeffs()).array().abs();\n    meanErrorCoeffwise += error;\n    maxErrorCoeffwise = maxErrorCoeffwise.max(error);\n  }\n  meanErrorCoeffwise /= expectedParameters.size();\n\n  std::cout << \"Parameter error statistics: \" << std::endl;\n  std::cout << \"Mean error:\" << std::endl << meanErrorCoeffwise << std::endl;\n  std::cout << \"Max error:\" << std::endl << maxErrorCoeffwise << std::endl;\n}\ntemplate<> void printErrorStatistics(const std::vector<Camera<MatrixRotation> >& expectedParameters, const std::vector<MatrixRotation>& optimizedRotations)\n{\n  assert(expectedParameters.size() == optimizedRotations.size());\n\n  Eigen::Array<double, 3, 3> meanErrorCoeffwise = MatrixRotation::Zero();\n  Eigen::Array<double, 3, 3> maxErrorCoeffwise = MatrixRotation::Zero();\n  for(int i = 0; i < expectedParameters.size(); i++)\n  {\n    Eigen::Array<double, 3, 3> error = (expectedParameters.at(i).pose.rotation - optimizedRotations.at(i));\n    meanErrorCoeffwise += error.abs();\n    maxErrorCoeffwise = maxErrorCoeffwise.max(error.abs());\n  }\n  meanErrorCoeffwise /= expectedParameters.size();\n\n  std::cout << \"Parameter error statistics: \" << std::endl;\n  std::cout << \"Mean error:\" << std::endl << meanErrorCoeffwise << std::endl;\n  std::cout << \"Max error:\" << std::endl << maxErrorCoeffwise << std::endl;\n}\n\ntemplate<typename RotationType>\ndouble optimizeImpl(const MeasuredScene<RotationType>& measurements, OptimizedScene<RotationType>& parameters)\n{\n  auto initialParameters = parameters;\n\n  /*\n   *  1. Setup problem\n   */\n  ceres::Problem problem;\n  setupProblem(problem, measurements, parameters);\n\n  /*\n   *  2. Solve problem\n   */\n  ceres::Solver::Options options;\n  options.minimizer_progress_to_stdout = true;\n  options.max_num_iterations = 100;\n  options.function_tolerance = 1e-15;\n  ceres::Solver::Summary summary;\n\n  steady_clock::time_point t1 = steady_clock::now();\n  ceres::Solve(options, &problem, &summary);\n  steady_clock::time_point t2 = steady_clock::now();\n  duration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n  std::cout << \"It took me \" << time_span.count() << \" seconds.\" << std::endl;\n\n  /*\n   *  3. Output report\n   */\n\n  std::cout << summary.FullReport() << std::endl;\n  std::cout << \"First 10 cameras: \" << std::endl;\n  auto n = std::min(10lu,measurements.cameras.size());\n  for(int i = 0; i < n ; i++)\n  {\n    print(measurements.cameras.at(i).pose.rotation, initialParameters.rotation.at(i), parameters.rotation.at(i));\n  }\n  printErrorStatistics(measurements.cameras, parameters.rotation);\n\n  return time_span.count();\n}\n} // namespace\n\ntemplate<> double optimize(const MeasuredScene<AngleAxisRotation>& measurements, OptimizedScene<AngleAxisRotation>& parameters)\n{\n  return optimizeImpl(measurements, parameters);\n}\ntemplate<> double optimize(const MeasuredScene<QuaternionRotation>& measurements, OptimizedScene<QuaternionRotation>& parameters)\n{\n  return optimizeImpl(measurements, parameters);\n}\ntemplate<> double optimize(const MeasuredScene<MatrixRotation>& measurements, OptimizedScene<MatrixRotation>& parameters)\n{\n  return optimizeImpl(measurements, parameters);\n}\n} //namespace roto\n", "meta": {"hexsha": "855bb806a43fe3a1402611cc478aa74ca88ae50a", "size": 8150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimization.cpp", "max_stars_repo_name": "klosteraner/rotation-optimization", "max_stars_repo_head_hexsha": "d5cbe4df2a28d4949fafa4843f1a951338bacacf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/optimization.cpp", "max_issues_repo_name": "klosteraner/rotation-optimization", "max_issues_repo_head_hexsha": "d5cbe4df2a28d4949fafa4843f1a951338bacacf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimization.cpp", "max_forks_repo_name": "klosteraner/rotation-optimization", "max_forks_repo_head_hexsha": "d5cbe4df2a28d4949fafa4843f1a951338bacacf", "max_forks_repo_licenses": ["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.9411764706, "max_line_length": 173, "alphanum_fraction": 0.7068711656, "num_tokens": 2004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5657217730545426}}
{"text": "\n#include \"DataStructures.h\"\n#include \"IncompressibleFluid.h\"\n#include \"IncompressibleLibrary.h\"\n#include \"math.h\"\n#include \"MatrixMath.h\"\n#include \"PolyMath.h\"\n#include <Eigen/Core>\n\nnamespace CoolProp {\n\n/// A thermophysical property provider for all properties\n/**\nThis fluid instance is populated using an entry from a JSON file and uses\nsimplified polynomial and exponential functions to calculate thermophysical\nand transport properties.\n*/\n//IncompressibleFluid::IncompressibleFluid();\n\nvoid IncompressibleFluid::validate() {\n    return;\n    // TODO: Implement validation function\n\n    // u and s have to be of the polynomial type!\n    //throw NotImplementedError(\"TODO\");\n}\n\nbool IncompressibleFluid::is_pure() {\n    if (density.coeffs.cols() == 1) return true;\n    return false;\n}\n\n/// Base exponential function\ndouble IncompressibleFluid::baseExponential(IncompressibleData data, double y, double ybase) {\n    Eigen::VectorXd coeffs = makeVector(data.coeffs);\n    size_t r = coeffs.rows(), c = coeffs.cols();\n    if (strict && (r != 3 || c != 1))\n        throw ValueError(format(\"%s (%d): You have to provide a 3,1 matrix of coefficients, not  (%d,%d).\", __FILE__, __LINE__, r, c));\n    return exp((double)(coeffs[0] / ((y - ybase) + coeffs[1]) - coeffs[2]));\n}\n/// Base exponential function with logarithmic term\ndouble IncompressibleFluid::baseLogexponential(IncompressibleData data, double y, double ybase) {\n    Eigen::VectorXd coeffs = makeVector(data.coeffs);\n    size_t r = coeffs.rows(), c = coeffs.cols();\n    if (strict && (r != 3 || c != 1))\n        throw ValueError(format(\"%s (%d): You have to provide a 3,1 matrix of coefficients, not  (%d,%d).\", __FILE__, __LINE__, r, c));\n    return exp(\n      (double)(log((double)(1.0 / ((y - ybase) + coeffs[0]) + 1.0 / ((y - ybase) + coeffs[0]) / ((y - ybase) + coeffs[0]))) * coeffs[1] + coeffs[2]));\n}\n\ndouble IncompressibleFluid::basePolyOffset(IncompressibleData data, double y, double z) {\n    size_t r = data.coeffs.rows(), c = data.coeffs.cols();\n    double offset = 0.0;\n    double in = 0.0;\n    Eigen::MatrixXd coeffs;\n    if (r > 0 && c > 0) {\n        offset = data.coeffs(0, 0);\n        if (r == 1 && c > 1) {  // row vector -> function of z\n            coeffs = Eigen::MatrixXd(data.coeffs.block(0, 1, r, c - 1));\n            in = z;\n        } else if (r > 1 && c == 1) {  // column vector -> function of y\n            coeffs = Eigen::MatrixXd(data.coeffs.block(1, 0, r - 1, c));\n            in = y;\n        } else {\n            throw ValueError(format(\"%s (%d): You have to provide a vector (1D matrix) of coefficients, not  (%d,%d).\", __FILE__, __LINE__, r, c));\n        }\n        return poly.evaluate(coeffs, in, 0, offset);\n    }\n    throw ValueError(format(\"%s (%d): You have to provide a vector (1D matrix) of coefficients, not  (%d,%d).\", __FILE__, __LINE__, r, c));\n}\n\n/// Density as a function of temperature, pressure and composition.\ndouble IncompressibleFluid::rho(double T, double p, double x) {\n    switch (density.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.evaluate(density.coeffs, T, x, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n            return baseExponential(density, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n            return baseLogexponential(density, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n            return exp(poly.evaluate(density.coeffs, T, x, 0, 0, Tbase, xbase));\n        case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n            return basePolyOffset(density, T, x);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\", __FILE__,\n                                    __LINE__, density.type));\n        default:\n            throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\", __FILE__, __LINE__, density.type));\n    }\n}\n\n/// Heat capacities as a function of temperature, pressure and composition.\ndouble IncompressibleFluid::c(double T, double p, double x) {\n    switch (specific_heat.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            //throw NotImplementedError(\"Here you should implement the polynomial.\");\n            return poly.evaluate(specific_heat.coeffs, T, x, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\", __FILE__,\n                                    __LINE__, specific_heat.type));\n        default:\n            throw ValueError(format(\"%s (%d): There is no predefined way to use this function type \\\"[%d]\\\" for specific heat.\", __FILE__, __LINE__,\n                                    specific_heat.type));\n    }\n}\n\n/// Viscosity as a function of temperature, pressure and composition.\ndouble IncompressibleFluid::visc(double T, double p, double x) {\n    switch (viscosity.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.evaluate(viscosity.coeffs, T, x, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n            return baseExponential(viscosity, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n            return baseLogexponential(viscosity, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n            return exp(poly.evaluate(viscosity.coeffs, T, x, 0, 0, Tbase, xbase));\n        case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n            return basePolyOffset(viscosity, T, x);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\", __FILE__,\n                                    __LINE__, viscosity.type));\n        default:\n            throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\", __FILE__, __LINE__, viscosity.type));\n    }\n}\n/// Thermal conductivity as a function of temperature, pressure and composition.\ndouble IncompressibleFluid::cond(double T, double p, double x) {\n    switch (conductivity.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.evaluate(conductivity.coeffs, T, x, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n            return baseExponential(conductivity, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n            return baseLogexponential(conductivity, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n            return exp(poly.evaluate(conductivity.coeffs, T, x, 0, 0, Tbase, xbase));\n        case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n            return basePolyOffset(conductivity, T, x);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\", __FILE__,\n                                    __LINE__, conductivity.type));\n        default:\n            throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\", __FILE__, __LINE__, conductivity.type));\n    }\n}\n/// Saturation pressure as a function of temperature and composition.\ndouble IncompressibleFluid::psat(double T, double x) {\n    if (T <= this->TminPsat) return 0.0;\n    switch (p_sat.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.evaluate(p_sat.coeffs, T, x, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n            return baseExponential(p_sat, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n            return baseLogexponential(p_sat, T, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n            return exp(poly.evaluate(p_sat.coeffs, T, x, 0, 0, Tbase, xbase));\n        case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n            return basePolyOffset(p_sat, T, x);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\", __FILE__,\n                                    __LINE__, p_sat.type));\n        default:\n            throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\", __FILE__, __LINE__, p_sat.type));\n    }\n}\n/// Freezing temperature as a function of pressure and composition.\ndouble IncompressibleFluid::Tfreeze(double p, double x) {\n    switch (T_freeze.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.evaluate(T_freeze.coeffs, p, x, 0, 0, 0.0, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n            return baseExponential(T_freeze, x, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n            return baseLogexponential(T_freeze, x, 0.0);\n        case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n            return exp(poly.evaluate(T_freeze.coeffs, p, x, 0, 0, 0.0, xbase));\n        case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n            return basePolyOffset(T_freeze, p, x);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\", __FILE__,\n                                    __LINE__, T_freeze.type));\n        default:\n            throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\", __FILE__, __LINE__, T_freeze.type));\n    }\n}\n\n/* Below are direct calculations of the derivatives. Nothing\n * special is going on, we simply use the polynomial class to\n * derive the different functions with respect to temperature.\n */\n/// Partial derivative of density with respect to temperature at constant pressure and composition\ndouble IncompressibleFluid::drhodTatPx(double T, double p, double x) {\n    switch (density.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.derivative(density.coeffs, T, x, 0, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\", __FILE__,\n                                    __LINE__, density.type));\n        default:\n            throw ValueError(\n              format(\"%s (%d): There is no predefined way to use this function type \\\"[%d]\\\" for density.\", __FILE__, __LINE__, density.type));\n    }\n}\n/// Partial derivative of entropy\n//  with respect to temperature at constant pressure and composition\n//  integrated in temperature\ndouble IncompressibleFluid::dsdTatPxdT(double T, double p, double x) {\n    switch (specific_heat.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.integral(specific_heat.coeffs, T, x, 0, -1, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\", __FILE__,\n                                    __LINE__, specific_heat.type));\n        default:\n            throw ValueError(\n              format(\"%s (%d): There is no predefined way to use this function type \\\"[%d]\\\" for entropy.\", __FILE__, __LINE__, specific_heat.type));\n    }\n}\n/// Partial derivative of enthalpy\n//  with respect to temperature at constant pressure and composition\n//  integrated in temperature\ndouble IncompressibleFluid::dhdTatPxdT(double T, double p, double x) {\n    switch (specific_heat.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.integral(specific_heat.coeffs, T, x, 0, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\", __FILE__,\n                                    __LINE__, specific_heat.type));\n        default:\n            throw ValueError(\n              format(\"%s (%d): There is no predefined way to use this function type \\\"[%d]\\\" for entropy.\", __FILE__, __LINE__, specific_heat.type));\n    }\n}\n\n/// Mass fraction conversion function\n/** If the fluid type is mass-based, it does not do anything. Otherwise,\n *  it converts the mass fraction to the required input. */\ndouble IncompressibleFluid::inputFromMass(double T, double x) {\n    if (this->xid == IFRAC_PURE) {\n        return _HUGE;\n    } else if (this->xid == IFRAC_MASS) {\n        return x;\n    } else {\n        throw NotImplementedError(\"Mass composition conversion has not been implemented.\");\n        //switch (mass2input.type) {\n        //    case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n        //        return poly.evaluate(mass2input.coeffs, T, x, 0, 0, 0.0, 0.0); // TODO: make sure Tbase and xbase are defined in the correct way\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n        //        return baseExponential(mass2input, x, 0.0);\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n        //        return baseLogexponential(mass2input, x, 0.0);\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n        //        return exp(poly.evaluate(mass2input.coeffs, T, x, 0, 0, 0.0, 0.0)); // TODO: make sure Tbase and xbase are defined in the correct way\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n        //        return basePolyOffset(mass2input, T, x);\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n        //        throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,mass2input.type));\n        //        break;\n        //    default:\n        //        throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\",__FILE__,__LINE__,mass2input.type));\n        //        break;\n        //}\n        //return _HUGE;\n    }\n}\n\n/// Volume fraction conversion function\n/** If the fluid type is volume-based, it does not do anything. Otherwise,\n *  it converts the volume fraction to the required input. */\ndouble IncompressibleFluid::inputFromVolume(double T, double x) {\n    if (this->xid == IFRAC_PURE) {\n        return _HUGE;\n    } else if (this->xid == IFRAC_VOLUME) {\n        return x;\n    } else {\n        throw NotImplementedError(\"Volume composition conversion has not been implemented.\");\n        //switch (volume2input.type) {\n        //    case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n        //        return poly.evaluate(volume2input.coeffs, T, x, 0, 0, 0.0, 0.0); // TODO: make sure Tbase and xbase are defined in the correct way\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n        //        return baseExponential(volume2input, x, 0.0);\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n        //        return baseLogexponential(volume2input, x, 0.0);\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n        //        return exp(poly.evaluate(volume2input.coeffs, T, x, 0, 0, 0.0, 0.0)); // TODO: make sure Tbase and xbase are defined in the correct way\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n        //        return basePolyOffset(volume2input, T, x);\n        //        break;\n        //    case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n        //        throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,volume2input.type));\n        //        break;\n        //    default:\n        //        throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\",__FILE__,__LINE__,volume2input.type));\n        //        break;\n        //}\n        //return _HUGE;\n    }\n}\n\n/// Mole fraction conversion function\n/** If the fluid type is mole-based, it does not do anything. Otherwise,\n *  it converts the mole fraction to the required input. */\ndouble IncompressibleFluid::inputFromMole(double T, double x) {\n    if (this->xid == IFRAC_PURE) {\n        return _HUGE;\n    } else if (this->xid == IFRAC_MOLE) {\n        return x;\n    } else {\n        throw NotImplementedError(\"Mole composition conversion has not been implemented.\");\n        /*\n        switch (mole2input.type) {\n            case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n                return poly.evaluate(mole2input.coeffs, T, x, 0, 0, 0.0, 0.0); // TODO: make sure Tbase and xbase are defined in the correct way\n                break;\n            case IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL:\n                return baseExponential(mole2input, x, 0.0);\n                break;\n            case IncompressibleData::INCOMPRESSIBLE_LOGEXPONENTIAL:\n                return baseLogexponential(mole2input, x, 0.0);\n                break;\n            case IncompressibleData::INCOMPRESSIBLE_EXPPOLYNOMIAL:\n                return exp(poly.evaluate(mole2input.coeffs, T, x, 0, 0, 0.0, 0.0)); // TODO: make sure Tbase and xbase are defined in the correct way\n                break;\n            case IncompressibleData::INCOMPRESSIBLE_POLYOFFSET:\n                return basePolyOffset(mole2input, T, x);\n                break;\n            case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n                throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\",__FILE__,__LINE__,mole2input.type));\n                break;\n            default:\n                throw ValueError(format(\"%s (%d): Your function type \\\"[%d]\\\" is unknown.\",__FILE__,__LINE__,mole2input.type));\n                break;\n        }\n        return _HUGE;\n        */\n    }\n}\n\n/* Some functions can be inverted directly, those are listed\n * here. It is also possible to solve for other quantities, but\n * that involves some more sophisticated processing and is not\n * done here, but in the backend, T(h,p) for example.\n */\n/// Temperature as a function of density, pressure and composition.\ndouble IncompressibleFluid::T_rho(double Dmass, double p, double x) {\n    double d_raw = Dmass;  // No changes needed, no reference values...\n    switch (density.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.solve_limits(density.coeffs, x, d_raw, Tmin, Tmax, 0, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\", __FILE__,\n                                    __LINE__, specific_heat.type));\n        default:\n            throw ValueError(format(\"%s (%d): There is no predefined way to use this function type \\\"[%d]\\\" for inverse density.\", __FILE__, __LINE__,\n                                    specific_heat.type));\n    }\n}\n/// Temperature as a function of heat capacities as a function of temperature, pressure and composition.\ndouble IncompressibleFluid::T_c(double Cmass, double p, double x) {\n    double c_raw = Cmass;  // No changes needed, no reference values...\n    switch (specific_heat.type) {\n        case IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL:\n            return poly.solve_limits(specific_heat.coeffs, x, c_raw, Tmin, Tmax, 0, 0, 0, Tbase, xbase);\n        case IncompressibleData::INCOMPRESSIBLE_NOT_SET:\n            throw ValueError(format(\"%s (%d): The function type is not specified (\\\"[%d]\\\"), are you sure the coefficients have been set?\", __FILE__,\n                                    __LINE__, specific_heat.type));\n        default:\n            throw ValueError(format(\"%s (%d): There is no predefined way to use this function type \\\"[%d]\\\" for inverse specific heat.\", __FILE__,\n                                    __LINE__, specific_heat.type));\n    }\n}\n\n/*\n * Some more functions to provide a single implementation\n * of important routines.\n * We start with the check functions that can validate input\n * in terms of pressure p, temperature T and composition x.\n */\n/// Check validity of temperature input.\n/** Compares the given temperature T to the result of a\n *  freezing point calculation. This is not necessarily\n *  defined for all fluids, default values do not cause errors. */\nbool IncompressibleFluid::checkT(double T, double p, double x) {\n    if (Tmin <= 0.) throw ValueError(\"Please specify the minimum temperature.\");\n    if (Tmax <= 0.) throw ValueError(\"Please specify the maximum temperature.\");\n    if ((Tmin > T) || (T > Tmax)) throw ValueError(format(\"Your temperature %f is not between %f and %f.\", T, Tmin, Tmax));\n    double TF = 0.0;\n    if (T_freeze.type != IncompressibleData::INCOMPRESSIBLE_NOT_SET) TF = Tfreeze(p, x);\n    if (T < TF) throw ValueError(format(\"Your temperature %f is below the freezing point of %f.\", T, TF));\n    return true;\n}\n\n/// Check validity of pressure input.\n/** Compares the given pressure p to the saturation pressure at\n *  temperature T and throws and exception if p is lower than\n *  the saturation conditions.\n *  The default value for psat is -1 yielding true if psat\n *  is not redefined in the subclass.\n *  */\nbool IncompressibleFluid::checkP(double T, double p, double x) {\n    double ps = 0.0;\n    if (p_sat.type != IncompressibleData::INCOMPRESSIBLE_NOT_SET) ps = psat(T, x);\n    if (p < 0.0) throw ValueError(format(\"You cannot use negative pressures: %f < %f. \", p, 0.0));\n    if (ps > 0.0 && p < ps) throw ValueError(format(\"Equations are valid for liquid phase only: %f < %f (psat). \", p, ps));\n    return true;\n}\n\n/// Check validity of composition input.\n/** Compares the given composition x to a stored minimum and\n *  maximum value. Enforces the redefinition of xmin and\n *  xmax since the default values cause an error. */\nbool IncompressibleFluid::checkX(double x) {\n    if (xmin < 0.0 || xmin > 1.0) throw ValueError(\"Please specify the minimum concentration between 0 and 1.\");\n    if (xmax < 0.0 || xmax > 1.0) throw ValueError(\"Please specify the maximum concentration between 0 and 1.\");\n    if ((xmin > x) || (x > xmax)) throw ValueError(format(\"Your composition %f is not between %f and %f.\", x, xmin, xmax));\n    return true;\n}\n\n} /* namespace CoolProp */\n\n// Testing still needs to be enhanced.\n/* Below, I try to carry out some basic tests for both 2D and 1D\n * polynomials as well as the exponential functions for vapour\n * pressure etc.\n */\n#ifdef ENABLE_CATCH\n#    include <math.h>\n#    include <iostream>\n#    include <catch2/catch_all.hpp>\n#    include \"TestObjects.h\"\n\nEigen::MatrixXd makeMatrix(const std::vector<double>& coefficients) {\n    //IncompressibleClass::checkCoefficients(coefficients,18);\n    std::vector<std::vector<double>> matrix;\n    std::vector<double> tmpVector;\n\n    tmpVector.clear();\n    tmpVector.push_back(coefficients[0]);\n    tmpVector.push_back(coefficients[6]);\n    tmpVector.push_back(coefficients[11]);\n    tmpVector.push_back(coefficients[15]);\n    matrix.push_back(tmpVector);\n\n    tmpVector.clear();\n    tmpVector.push_back(coefficients[1] * 100.0);\n    tmpVector.push_back(coefficients[7] * 100.0);\n    tmpVector.push_back(coefficients[12] * 100.0);\n    tmpVector.push_back(coefficients[16] * 100.0);\n    matrix.push_back(tmpVector);\n\n    tmpVector.clear();\n    tmpVector.push_back(coefficients[2] * 100.0 * 100.0);\n    tmpVector.push_back(coefficients[8] * 100.0 * 100.0);\n    tmpVector.push_back(coefficients[13] * 100.0 * 100.0);\n    tmpVector.push_back(coefficients[17] * 100.0 * 100.0);\n    matrix.push_back(tmpVector);\n\n    tmpVector.clear();\n    tmpVector.push_back(coefficients[3] * 100.0 * 100.0 * 100.0);\n    tmpVector.push_back(coefficients[9] * 100.0 * 100.0 * 100.0);\n    tmpVector.push_back(coefficients[14] * 100.0 * 100.0 * 100.0);\n    tmpVector.push_back(0.0);\n    matrix.push_back(tmpVector);\n\n    tmpVector.clear();\n    tmpVector.push_back(coefficients[4] * 100.0 * 100.0 * 100.0 * 100.0);\n    tmpVector.push_back(coefficients[10] * 100.0 * 100.0 * 100.0 * 100.0);\n    tmpVector.push_back(0.0);\n    tmpVector.push_back(0.0);\n    matrix.push_back(tmpVector);\n\n    tmpVector.clear();\n    tmpVector.push_back(coefficients[5] * 100.0 * 100.0 * 100.0 * 100.0 * 100.0);\n    tmpVector.push_back(0.0);\n    tmpVector.push_back(0.0);\n    tmpVector.push_back(0.0);\n    matrix.push_back(tmpVector);\n\n    tmpVector.clear();\n    return CoolProp::vec_to_eigen(matrix).transpose();\n}\n\nTEST_CASE(\"Internal consistency checks and example use cases for the incompressible fluids\", \"[IncompressibleFluids]\") {\n    bool PRINT = false;\n    std::string tmpStr;\n    std::vector<double> tmpVector;\n    std::vector<std::vector<double>> tmpMatrix;\n\n    SECTION(\"Test case for \\\"SylthermXLT\\\" by Dow Chemicals\") {\n\n        std::vector<double> cRho;\n        cRho.push_back(+1.1563685145E+03);\n        cRho.push_back(-1.0269048032E+00);\n        cRho.push_back(-9.3506079577E-07);\n        cRho.push_back(+1.0368116627E-09);\n        CoolProp::IncompressibleData density;\n        density.type = CoolProp::IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL;\n        density.coeffs = CoolProp::vec_to_eigen(cRho);\n\n        std::vector<double> cHeat;\n        cHeat.push_back(+1.1562261074E+03);\n        cHeat.push_back(+2.0994549103E+00);\n        cHeat.push_back(+7.7175381057E-07);\n        cHeat.push_back(-3.7008444051E-20);\n        CoolProp::IncompressibleData specific_heat;\n        specific_heat.type = CoolProp::IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL;\n        specific_heat.coeffs = CoolProp::vec_to_eigen(cHeat);\n\n        std::vector<double> cCond;\n        cCond.push_back(+1.6121957379E-01);\n        cCond.push_back(-1.3023781944E-04);\n        cCond.push_back(-1.4395238766E-07);\n        CoolProp::IncompressibleData conductivity;\n        conductivity.type = CoolProp::IncompressibleData::INCOMPRESSIBLE_POLYNOMIAL;\n        conductivity.coeffs = CoolProp::vec_to_eigen(cCond);\n\n        std::vector<double> cVisc;\n        cVisc.push_back(+1.0337654989E+03);\n        cVisc.push_back(-4.3322764383E+01);\n        cVisc.push_back(+1.0715062356E+01);\n        CoolProp::IncompressibleData viscosity;\n        viscosity.type = CoolProp::IncompressibleData::INCOMPRESSIBLE_EXPONENTIAL;\n        viscosity.coeffs = CoolProp::vec_to_eigen(cVisc);\n\n        CoolProp::IncompressibleFluid XLT;\n        XLT.setName(\"XLT\");\n        XLT.setDescription(\"SylthermXLT\");\n        XLT.setReference(\"Dow Chemicals data sheet\");\n        XLT.setTmax(533.15);\n        XLT.setTmin(173.15);\n        XLT.setxmax(0.0);\n        XLT.setxmin(0.0);\n        XLT.setTminPsat(533.15);\n\n        XLT.setTbase(0.0);\n        XLT.setxbase(0.0);\n\n        /// Setters for the coefficients\n        XLT.setDensity(density);\n        XLT.setSpecificHeat(specific_heat);\n        XLT.setViscosity(viscosity);\n        XLT.setConductivity(conductivity);\n        //XLT.setPsat(parse_coefficients(fluid_json, \"saturation_pressure\", false));\n        //XLT.setTfreeze(parse_coefficients(fluid_json, \"T_freeze\", false));\n        //XLT.setVolToMass(parse_coefficients(fluid_json, \"volume2mass\", false));\n        //XLT.setMassToMole(parse_coefficients(fluid_json, \"mass2mole\", false));\n\n        /// A function to check coefficients and equation types.\n        //XLT.validate();\n        double acc = 0.0001;\n        double val = 0;\n        double res = 0;\n\n        // Prepare the results and compare them to the calculated values\n        double T = 273.15 + 50;\n        double p = 10e5;\n        double x = 0.0;\n\n        // Compare density\n        val = 824.4615702148608;\n        res = XLT.rho(T, p, x);\n        {\n            CAPTURE(T);\n            CAPTURE(val);\n            CAPTURE(res);\n            CHECK(check_abs(val, res, acc));\n        }\n\n        // Compare cp\n        val = 1834.7455527670554;\n        res = XLT.c(T, p, x);\n        {\n            CAPTURE(T);\n            CAPTURE(val);\n            CAPTURE(res);\n            CHECK(check_abs(val, res, acc));\n        }\n\n        // Check property functions\n        CHECK_THROWS(XLT.s(T, p, x));\n        CHECK_THROWS(XLT.h(T, p, x));\n        CHECK_THROWS(XLT.u(T, p, x));\n\n        // Compare v\n        val = 0.0008931435169681835;\n        res = XLT.visc(T, p, x);\n        {\n            CAPTURE(T);\n            CAPTURE(val);\n            CAPTURE(res);\n            CHECK(check_abs(val, res, acc));\n        }\n\n        // Compare l\n        val = 0.10410086156049088;\n        res = XLT.cond(T, p, x);\n        {\n            CAPTURE(T);\n            CAPTURE(val);\n            CAPTURE(res);\n            CHECK(check_abs(val, res, acc));\n        }\n    }\n\n    SECTION(\"Test case for Methanol from SecCool\") {\n\n        CoolProp::IncompressibleFluid CH3OH = CoolProp::get_incompressible_fluid(\"CH3OH\");\n\n        // Prepare the results and compare them to the calculated values\n        double acc = 0.0001;\n        double T = 273.15 + 10;\n        double p = 10e5;\n        double x = 0.25;\n        double expected = 0;\n        double actual = 0;\n\n        // Compare density\n        expected = 963.2886528091547;\n        actual = CH3OH.rho(T, p, x);\n        {\n            CAPTURE(T);\n            CAPTURE(p);\n            CAPTURE(x);\n            CAPTURE(expected);\n            CAPTURE(actual);\n            CHECK(check_abs(expected, actual, acc));\n        }\n\n        // Compare cp\n        expected = 3993.9748117022423;\n        actual = CH3OH.c(T, p, x);\n        {\n            CAPTURE(T);\n            CAPTURE(p);\n            CAPTURE(x);\n            CAPTURE(expected);\n            CAPTURE(actual);\n            CHECK(check_abs(expected, actual, acc));\n        }\n\n        // Check property functions\n        CHECK_THROWS(CH3OH.s(T, p, x));\n        CHECK_THROWS(CH3OH.h(T, p, x));\n        CHECK_THROWS(CH3OH.u(T, p, x));\n\n        // Compare v\n        expected = 0.0023970245009602097;\n        actual = CH3OH.visc(T, p, x) / 1e3;\n        {\n            CAPTURE(T);\n            CAPTURE(p);\n            CAPTURE(x);\n            CAPTURE(expected);\n            CAPTURE(actual);\n            std::string errmsg = CoolProp::get_global_param_string(\"errstring\");\n            CAPTURE(errmsg);\n            CHECK(check_abs(expected, actual, acc));\n        }\n\n        // Compare conductivity\n        expected = 0.44791148414693727;\n        actual = CH3OH.cond(T, p, x);\n        {\n            CAPTURE(T);\n            CAPTURE(p);\n            CAPTURE(x);\n            CAPTURE(expected);\n            CAPTURE(actual);\n            std::string errmsg = CoolProp::get_global_param_string(\"errstring\");\n            CAPTURE(errmsg);\n            CHECK(check_abs(expected, actual, acc));\n        }\n\n        // Compare Tfreeze\n        expected = -20.02 + 273.15;  // 253.1293105454671;\n        actual = CH3OH.Tfreeze(p, x);\n        {\n            CAPTURE(T);\n            CAPTURE(p);\n            CAPTURE(x);\n            CAPTURE(expected);\n            CAPTURE(actual);\n            std::string errmsg = CoolProp::get_global_param_string(\"errstring\");\n            CAPTURE(errmsg);\n            CHECK(check_abs(expected, actual, acc));\n        }\n    }\n}\n\n#endif /* ENABLE_CATCH */\n", "meta": {"hexsha": "9cdd4323186a18d2962b1cd3b6223c8617837977", "size": 31681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Backends/Incompressible/IncompressibleFluid.cpp", "max_stars_repo_name": "friederikeboehm/CoolProp", "max_stars_repo_head_hexsha": "44325d9e6abd9e6f88f428720f4f64a0c1962784", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Backends/Incompressible/IncompressibleFluid.cpp", "max_issues_repo_name": "friederikeboehm/CoolProp", "max_issues_repo_head_hexsha": "44325d9e6abd9e6f88f428720f4f64a0c1962784", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Backends/Incompressible/IncompressibleFluid.cpp", "max_forks_repo_name": "friederikeboehm/CoolProp", "max_forks_repo_head_hexsha": "44325d9e6abd9e6f88f428720f4f64a0c1962784", "max_forks_repo_licenses": ["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.0654338549, "max_line_length": 183, "alphanum_fraction": 0.6297465358, "num_tokens": 8152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5656689118758256}}
{"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": "#include <freefloating_gazebo/hydro_link.h>\n#include <Eigen/Geometry>\n\nnamespace ffg\n{\n\n\nEigen::Matrix3d skew(const Eigen::Vector3d &v)\n{\n  Eigen::Matrix3d out;\n  out << 0, -v[2], v[1], v[2], 0, -v[0], -v[1], v[0], 0;\n  return out;\n}\n\nEigen::Vector3d HydroLink::buoyancyForce(double surface_distance)\n{\n  Eigen::Vector3d force(0,0,buoyancy_force);\n\n  if(surface_distance > -buoyancy_limit)\n  {\n    if(surface_distance > buoyancy_limit)\n      force *= 0;\n    else\n      force *= cos(M_PI/4.*(surface_distance/buoyancy_limit + 1));\n  }\n  return force;\n}\n\nEigen::Vector6d HydroLink::hydroDynamicForce(Eigen::Vector6d &vel)\n{\n  Eigen::Vector6d force(Eigen::Vector6d::Zero());\n\n  // filter velocity\n  if(has_added_mass)\n    vel_filter.filter(vel);\n\n  // damping part\n  if(has_lin_damping)\n    force = -lin_damping.cwiseProduct(vel);\n  if(has_quad_damping)\n    force -= quad_damping.cwiseProduct(vel.cwiseProduct(vel.cwiseAbs()));\n\n  // added mass part\n  if(has_added_mass)\n  {\n    const Eigen::Vector6d acc = (vel - vel_prev)/dt;\n    force -= added_mass * acc;\n\n    // added Coriolis\n    Eigen::Matrix6d Cor;\n    const Eigen::Vector6d A = added_mass * vel;\n    const Eigen::Matrix3d Sa = -1 * skew(A.head<3>());\n    Cor << Eigen::Matrix3d::Zero(), Sa, Sa, skew(-A.tail<3>());\n    force -= Cor * vel;\n\n    vel_prev = vel;\n  }\n  return force;\n}\n\n}\n\n", "meta": {"hexsha": "1b6401ab6cf651e572019cfebd2805f86be02df5", "size": 1342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hydro_link.cpp", "max_stars_repo_name": "MLouedec/freefloating_gazebo", "max_stars_repo_head_hexsha": "c8201da08822a0be2740a4fd8970f1ff9de8e837", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hydro_link.cpp", "max_issues_repo_name": "MLouedec/freefloating_gazebo", "max_issues_repo_head_hexsha": "c8201da08822a0be2740a4fd8970f1ff9de8e837", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hydro_link.cpp", "max_forks_repo_name": "MLouedec/freefloating_gazebo", "max_forks_repo_head_hexsha": "c8201da08822a0be2740a4fd8970f1ff9de8e837", "max_forks_repo_licenses": ["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.3015873016, "max_line_length": 73, "alphanum_fraction": 0.6549925484, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.565579795495047}}
{"text": "// BSD 3-Clause License\n// Copyright (c) 2021 The Trustees of the University of Pennsylvania. All Rights Reserved\n// Authors:\n// J. Diego Caporale <jdcap@seas.upenn.edu>\n\n/* Basic PD Control example script demonstrating how to use the mjbots_control_loop to 3 motors. The functions to implement are\n * CalcTorques and PrepareLog. In this example we send a PD control torques and log the motor information.\n * Also, an implementation that uses Eigen conversions.\n */\n\n#include \"kodlab_mjbots_sdk/mjbots_control_loop.h\"\n#include \"kodlab_mjbots_sdk/joint_moteus.h\"\n#include \"ManyMotorLog.hpp\"\n#include \"kodlab_mjbots_sdk/lcm_subscriber.h\"\n#include <sys/mman.h>\n#include <limits>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nclass Joints3DoF : public kodlab::mjbots::MjbotsControlLoop<ManyMotorLog> {\n  using MjbotsControlLoop::MjbotsControlLoop;\n  void CalcTorques() override {\n    std::vector<float> torques(num_motors_, 0);\n\n    if (num_motors_==3){\n      Eigen::Vector3f leg_pos_des;\n      leg_pos_des<<1-M_PI_2,2,0;\n      Eigen::Vector3f positions  = Eigen::Map<Eigen::VectorXf,Eigen::Unaligned> ( robot_->GetJointPositions().data(), num_motors_);\n      Eigen::Vector3f velocities = Eigen::Map<Eigen::VectorXf,Eigen::Unaligned> (robot_->GetJointVelocities().data(), num_motors_);\n      float kp = 100;\n      float kd = 1;\n      Eigen::VectorXf tau = kp*(leg_pos_des-positions) + kd*(Eigen::Vector3f::Zero()-velocities);\n\n      Eigen::VectorXf::Map(&torques[0], num_motors_) = tau;\n    }\n    else{\n      std::cout<<\"Wrong number of motors\"<<std::endl;\n    }\n\n    robot_->SetTorques(torques);   \n  }\n\n  void PrepareLog() override {\n    for (int servo = 0; servo < num_motors_; servo++) {\n      log_data_.positions[servo]  = robot_->GetJointPositions()[servo];\n      log_data_.velocities[servo] = robot_->GetJointVelocities()[servo];\n      log_data_.modes[servo] = static_cast<int>(robot_->GetJointModes()[servo]);\n      log_data_.torques[servo] = robot_->GetJointTorqueCmd()[servo];\n    }\n    for (int servo = num_motors_; servo < 13; servo++) {\n      log_data_.positions[servo] = 0;\n      log_data_.velocities[servo] = 0;\n      log_data_.modes[servo] = 0;\n      log_data_.torques[servo] = 0;\n    }\n  }\n};\n\nint main(int argc, char **argv) {\n\n  //Setup joints\n  std::vector<kodlab::mjbots::JointMoteus> joints;\n  joints.emplace_back(100, 4, 1, -1.3635165,    1,  1);\n  joints.emplace_back(101, 4,-1,  2.688,  5.0/3.0,  1);\n  joints.emplace_back(108, 4, 1, -0.4674585,    1,  1);\n\n  // Define robot options\n  kodlab::mjbots::ControlLoopOptions options;\n  options.log_channel_name = \"motor_data\";\n  options.frequency = 1000;\n  options.realtime_params.main_cpu = 3;\n  options.realtime_params.can_cpu  = 2;\n  options.parallelize_control_loop = true; \n\n  // Create control loop\n  Joints3DoF control_loop(joints, options);\n\n  // Starts the loop, and then join it\n  control_loop.Start();\n  control_loop.Join();\n  return 0;\n}\n", "meta": {"hexsha": "10bf632abae26903bc5dee8f8cc3a649c4afb65a", "size": 2917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/leg_3DoF_example.cpp", "max_stars_repo_name": "KodlabPenn/kodlab_mjbots_sdk", "max_stars_repo_head_hexsha": "a5151b39b09a175dcb506a07203fc2400ccb76de", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-02-12T21:56:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T18:50:00.000Z", "max_issues_repo_path": "examples/leg_3DoF_example.cpp", "max_issues_repo_name": "KodlabPenn/kodlab_mjbots_sdk", "max_issues_repo_head_hexsha": "a5151b39b09a175dcb506a07203fc2400ccb76de", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-10T01:08:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T01:08:05.000Z", "max_forks_repo_path": "examples/leg_3DoF_example.cpp", "max_forks_repo_name": "KodlabPenn/kodlab_mjbots_sdk", "max_forks_repo_head_hexsha": "a5151b39b09a175dcb506a07203fc2400ccb76de", "max_forks_repo_licenses": ["BSD-3-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.1445783133, "max_line_length": 131, "alphanum_fraction": 0.6972917381, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.565579789855344}}
{"text": "#include \"shot_detector.h\"\n\n#include <cmath>\n#include <string>\n#include <opencv/cv.hpp>\n#include <boost/log/trivial.hpp>\n\nusing namespace std;\nusing namespace cv;\n\nnamespace vrs {\nnamespace components {\n\nnamespace shot_detector {\nbool shot_bound(const Mat &curr_frame, const Mat &prev_frame,\n\t\tdouble threshold) {\n\t//\u8f6c\u6362\u4e3aHSV\u76f4\u65b9\u56fe\n\tMat hsv1, hsv2;\n\tbool is_shot_bound = false;\n\t//\u5982\u6709\u6709\u5fc5\u8981\u5219\u8fdb\u884c\u7f29\u653e\n\tif (curr_frame.cols < FRAME_WIDTH) {\n\t\tresize(curr_frame, curr_frame,\n\t\t\t\tSize(FRAME_WIDTH,\n\t\t\t\t\t\tround(\n\t\t\t\t\t\t\t\t(FRAME_WIDTH\n\t\t\t\t\t\t\t\t\t\t/ static_cast<float>(curr_frame.cols))\n\t\t\t\t\t\t\t\t\t\t* static_cast<float>(curr_frame.rows))));\n\t}\n\tif (prev_frame.cols < FRAME_WIDTH) {\n\t\tresize(prev_frame, prev_frame,\n\t\t\t\tSize(FRAME_WIDTH,\n\t\t\t\t\t\tround(FRAME_WIDTH / static_cast<float>(prev_frame.cols))\n\t\t\t\t\t\t\t\t* static_cast<float>(prev_frame.rows)));\n\t}\n\n\t//\u8f6c\u6362\u5230HSV(HSV \u4e3a\u8272\u76f8\uff0c\u9971\u548c\u5ea6\uff0c\u660e\u5ea6) \u300a\u56fe\u50cf\u5904\u7406\u3001\u5206\u6790\u4e0e\u673a\u5668\u89c6\u89c9\u300bP27\n\tcvtColor(curr_frame, hsv1, CV_BGR2HSV);\n\tcvtColor(prev_frame, hsv2, CV_BGR2HSV);\n\n\t//\u8ba1\u7b97hsv\u76f4\u65b9\u56fe\n\tint hbins = 16, sbins = 16, vbins = 16;\n\tint hist_size[] = { hbins, sbins, vbins };\n\t//hue(\u8272\u8c03)\u3001saturation(\u9971\u548c\u5ea6),value(\u503c)\u8303\u56f4\u53d8\u5316\n\tfloat hranges[] = { 0, 180 }, sranges[] = { 0, 256 },\n\t\t\tvranges[] = { 0, 256 };\n\tconst float *ranges[] = { hranges, sranges, vranges };\n\tMatND hist1, hist2;\n\tint channels[] = { 0, 1, 2 };\n\tbool b_uniform = true, b_accumulate = false;\n\n\tcalcHist(&hsv1, 1, channels, Mat(), hist1, 3, hist_size, ranges, b_uniform,\n\t\t\tb_accumulate);\n\tcalcHist(&hsv2, 1, channels, Mat(), hist2, 3, hist_size, ranges, b_uniform,\n\t\t\tb_accumulate);\n\n\tnormalize(hist1, hist1, 1, 0, NORM_L1, -1, Mat());\n\tnormalize(hist2, hist2, 1, 0, NORM_L1, -1, Mat());\n\n\t//\u5bf9\u6bd4\u76f4\u65b9\u56fe\n\tdouble d_corr = compareHist(hist1, hist2, CV_COMP_INTERSECT);\n\tis_shot_bound = d_corr < threshold;\n\tBOOST_LOG_TRIVIAL(debug)<< \"\u5bf9\u6bd4\u5f97\u5206=\" << d_corr;\n\tBOOST_LOG_TRIVIAL(debug)<< \"\u662f\u5426\u627e\u5230\u4e00\u4e2a\u955c\u5934?=\" << is_shot_bound;\n\treturn is_shot_bound;\n}\n}\n\n}\n}\n", "meta": {"hexsha": "e883cee943886d19d73ee3565d46a5640cdf9cb9", "size": 1871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "base_engine/src/components/shot_detector/shot_detector.cpp", "max_stars_repo_name": "AiPratice/VideoAnalysisEngine", "max_stars_repo_head_hexsha": "e6aa67e5b0d08d6b3ae1b63988982ef31e60bf7a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2018-09-12T10:04:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T12:07:53.000Z", "max_issues_repo_path": "base_engine/src/components/shot_detector/shot_detector.cpp", "max_issues_repo_name": "AiPratice/VideoAnalysisTool", "max_issues_repo_head_hexsha": "e6aa67e5b0d08d6b3ae1b63988982ef31e60bf7a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-24T03:37:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-24T03:37:28.000Z", "max_forks_repo_path": "base_engine/src/components/shot_detector/shot_detector.cpp", "max_forks_repo_name": "AiPratice/VideoAnalysisTool", "max_forks_repo_head_hexsha": "e6aa67e5b0d08d6b3ae1b63988982ef31e60bf7a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-09-12T10:04:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T12:47:07.000Z", "avg_line_length": 26.7285714286, "max_line_length": 76, "alphanum_fraction": 0.680384821, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571774, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5655797867444659}}
{"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 \u0413\u043b\u0430\u0432\u043d\u044b\u0439 \u043c\u043e\u0434\u0443\u043b\u044c \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b\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/// \u041c\u0438\u043b\u043b\u0438\u0441\u0435\u043a\u0443\u043d\u0434\u044b \u0432 \u0444\u043e\u0440\u043c\u0430\u0442\u0435 \u0434\u0440\u043e\u0431\u043d\u043e\u0433\u043e \u0447\u0438\u0441\u043b\u0430.\nusing d_milliseconds = duration<double, milliseconds::period>;\n\n/// \u041c\u0430\u0441\u0441\u0438\u0432 \u0441 \u0431\u0430\u0437\u043e\u0432\u044b\u043c\u0438 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438 (\u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u043f\u0435\u0440\u0432\u043e\u0433\u043e \u044d\u0442\u0430\u043f\u0430 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u0430).\nusing FirstStepResult = vector<size_t>;\n\n/// \u041c\u0430\u0441\u0441\u0438\u0432 \u0441 \u043d\u0430\u0439\u0434\u0435\u043d\u043d\u044b\u043c\u0438 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438 \u0432 \u0445\u043e\u0434\u0435 \u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f \u0432\u0442\u043e\u0440\u043e\u0433\u043e \u044d\u0442\u0430\u043f\u0430 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u0430.\nusing SecondStepResult = vector<uint64_t>;\n\n/// \u0412\u044b\u0432\u0435\u0441\u0442\u0438 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u043c\u043e\u0435 \u043a\u043e\u043d\u0442\u0435\u0439\u043d\u0435\u0440\u0430 (\u0433\u0434\u0435 \u0435\u0441\u0442\u044c begin \u0438 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 \u0411\u0435\u043d\u0447\u043c\u0430\u0440\u043a.\n * @param func \u0412\u044b\u043f\u043e\u043b\u043d\u044f\u0435\u043c\u0430\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u044f.\n * @param args \u0410\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u044b \u0432\u044b\u043f\u043e\u043b\u043d\u044f\u0435\u043c\u043e\u0439 \u0444\u0443\u043d\u043a\u0446\u0438\u0438.\n * @return \u0420\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u044f \u0438 \u0432\u0440\u0435\u043c\u044f \u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u0438.\n */\ntemplate <typename Result, typename Function, typename... Args>\npair<double, Result> timeBenchmark(const Function& func, const Args&... args)\n{\n    Result calc;\n\n    // \u043d\u0430\u0447\u0438\u043d\u0430\u0435\u043c \u0441\u0447\u0438\u0442\u0430\u0442\u044c \u0432\u0440\u0435\u043c\u044f\n    auto start = steady_clock::now();\n\n    // \u0447\u0442\u043e-\u0442\u043e \u0432\u044b\u0447\u0438\u0441\u043b\u044f\u0435\u043c\n    calc = func(args...);\n\n    // \u0437\u0430\u043a\u0430\u043d\u0447\u0438\u0432\u0430\u0435\u043c \u0441\u0447\u0438\u0442\u0430\u0442\u044c \u0432\u0440\u0435\u043c\u044f\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/// \u0417\u0430\u043f\u0438\u0441\u044c \u0434\u0430\u043d\u043d\u044b\u0445 \u0432 \u0444\u0430\u0439\u043b.\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 \u041f\u0435\u0440\u0432\u044b\u0439 \u044d\u0442\u0430\u043f \u043c\u043e\u0434\u0438\u0446\u0438\u0444\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u0433\u043e \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0433\u043e \u043f\u043e\u0438\u0441\u043a\u0430 \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b.\n * @details\n * \u041a\u043b\u0430\u0441\u0441\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u043c\u0435\u0442\u043e\u0434 - \u0440\u0435\u0448\u0435\u0442\u043e \u042d\u0440\u0430\u0442\u043e\u0441\u0444\u0435\u043d\u0430.\n * \u041f\u043e\u0438\u0441\u043a \u0432 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b\u0435 [2; n]\n * @param n \u0412\u0435\u0440\u0445\u043d\u044f\u044f \u0433\u0440\u0430\u043d\u0438\u0446\u0430 \u043f\u043e\u0438\u0441\u043a\u0430 \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b.\n * @return \u041c\u0430\u0441\u0441\u0438\u0432 \u0441 \u0431\u0430\u0437\u043e\u0432\u044b\u043c\u0438 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438.\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        // \u0435\u0441\u043b\u0438 \u043d\u0435\u043f\u043e\u043c\u0435\u0447\u0435\u043d\u043d\u043e\u0435 \u043f\u0440\u043e\u0441\u0442\u043e\u0435 \u0447\u0438\u0441\u043b\u043e\n        if (!range[i])\n        {\n            basePrime.push_back(i);\n            // \u043f\u043e\u043c\u0435\u0442\u0438\u043c \u0434\u0440\u0443\u0433\u0438\u0435 \u0447\u0438\u0441\u043b\u0430 \u043d\u0430 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u0438 \u0448\u0430\u0433\u0430 i \u043a\u0430\u043a \u0441\u043e\u0441\u0442\u0430\u0432\u043d\u044b\u0435\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 \u0412\u0442\u043e\u0440\u043e\u0439 \u044d\u0442\u0430\u043f \u043c\u043e\u0434\u0438\u0444\u0438\u0446\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u0433\u043e \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0433\u043e \u043f\u043e\u0438\u0441\u043a\u0430 \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b.\n * @param i_begin \u041d\u0430\u0447\u0430\u043b\u044c\u043d\u044b\u0439 \u0438\u043d\u0434\u0435\u043a\u0441 \u043f\u043e\u0438\u0441\u043a\u0430\n * @param i_end \u041a\u043e\u043d\u0435\u0447\u043d\u044b\u0439 \u0438\u043d\u0434\u0435\u043a\u0441 \u043f\u043e\u0438\u0441\u043a\u0430\n * @param basePrime \u041c\u0430\u0441\u0441\u0438\u0432 \u0441 \u0431\u0430\u0437\u043e\u0432\u044b\u043c\u0438 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438\n * @return \u041c\u0430\u0441\u0441\u0438\u0432 \u0441 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438, \u043d\u0430\u0439\u0434\u0435\u043d\u043d\u044b\u0435 \u0432 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0435 \u043e\u0442 (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 \u0412\u0442\u043e\u0440\u043e\u0439 \u044d\u0442\u0430\u043f \u043c\u043e\u0434\u0438\u0444\u0438\u0446\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u0433\u043e \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0433\u043e \u043f\u043e\u0438\u0441\u043a\u0430 \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b \u0432 \u043f\u043e\u043b\u043d\u043e\u043c \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0435.\n * @param[in] i_begin \u041d\u0430\u0447\u0430\u043b\u044c\u043d\u044b\u0439 \u0438\u043d\u0434\u0435\u043a\u0441 \u043f\u043e\u0438\u0441\u043a\u0430\n * @param[in] i_end \u041a\u043e\u043d\u0435\u0447\u043d\u044b\u0439 \u0438\u043d\u0434\u0435\u043a\u0441 \u043f\u043e\u0438\u0441\u043a\u0430\n * @param[in] basePrime \u041c\u0430\u0441\u0441\u0438\u0432 \u0441 \u0431\u0430\u0437\u043e\u0432\u044b\u043c\u0438 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438\n * @param[in] basePrimeBegin \u041d\u0430\u0447\u0430\u043b\u044c\u043d\u044b\u0439 \u0438\u043d\u0434\u0435\u043a\u0441 \u043c\u0430\u0441\u0441\u0438\u0432\u0430 \u0441 \u0431\u0430\u0437\u043e\u0432\u044b\u043c\u0438 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438\n * @param[in] basePrimeEnd \u041a\u043e\u043d\u0435\u0447\u043d\u044b\u0439 \u0438\u043d\u0434\u0435\u043a\u0441 \u043c\u0430\u0441\u0441\u0438\u0432\u0430 \u0441 \u0431\u0430\u0437\u043e\u0432\u044b\u043c\u0438 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438\n * @param[out] fullRange \u041f\u043e\u043b\u043d\u044b\u0439 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d \u0447\u0438\u0441\u0435\u043b, \u0433\u0434\u0435 0 - \u043f\u0440\u043e\u0441\u0442\u043e\u0435, 1 - \u0441\u043e\u0441\u0442\u0430\u0432\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e.\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 \u0412\u0442\u043e\u0440\u043e\u0439 \u044d\u0442\u0430\u043f \u043c\u043e\u0434\u0438\u0444\u0438\u0446\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u0433\u043e \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0433\u043e \u043f\u043e\u0438\u0441\u043a\u0430 \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b \u0432 \u043f\u043e\u043b\u043d\u043e\u043c \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0435 \u043f\u043e \u043e\u0434\u043d\u043e\u043c\u0443 \u043f\u0440\u043e\u0441\u0442\u043e\u043c\u0443 \u0447\u0438\u0441\u043b\u0443.\n * @param[in] i_begin \u041d\u0430\u0447\u0430\u043b\u044c\u043d\u044b\u0439 \u0438\u043d\u0434\u0435\u043a\u0441 \u043f\u043e\u0438\u0441\u043a\u0430\n * @param[in] i_end \u041a\u043e\u043d\u0435\u0447\u043d\u044b\u0439 \u0438\u043d\u0434\u0435\u043a\u0441 \u043f\u043e\u0438\u0441\u043a\u0430\n * @param[in] prime \u041f\u0440\u043e\u0441\u0442\u043e\u0435 \u0447\u0438\u0441\u043b\u043e\n * @param[out] fullRange \u041f\u043e\u043b\u043d\u044b\u0439 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d \u0447\u0438\u0441\u0435\u043b, \u0433\u0434\u0435 0 - \u043f\u0440\u043e\u0441\u0442\u043e\u0435, 1 - \u0441\u043e\u0441\u0442\u0430\u0432\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e.\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/// \u041f\u0430\u0440\u0430\u043b\u043b\u0435\u043b\u044c\u043d\u0430\u044f \u0434\u0435\u043a\u043e\u043c\u043f\u043e\u0437\u0438\u0446\u0438\u044f \u043f\u043e \u0434\u0430\u043d\u043d\u044b\u043c.\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    // \u0420\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 - \u043c\u0430\u0441\u0441\u0438\u0432 \u0441 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438 \u0438\u0437 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0430 \u043e\u0442 (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/// \u041f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u0430\u044f \u0434\u0435\u043a\u043e\u043c\u043f\u043e\u0437\u0438\u0446\u0438\u044f \u043d\u0430\u0431\u043e\u0440\u0430 \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b.\nSecondStepResult seqDecompositionByBasePrime(const uint64_t begin,\n                                             const uint64_t n,\n                                             const FirstStepResult &basePrime\n                                             )\n{\n    const auto diff = n - begin;\n    // \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d \u0447\u0438\u0441\u0435\u043b (begin, n]\n    // 1  - \u0435\u0441\u043b\u0438 \u0441\u043e\u0441\u0442\u0430\u0432\u043d\u043e\u0435\n    // 0 - \u0435\u0441\u043b\u0438 \u043f\u0440\u043e\u0441\u0442\u043e\u0435\n    vector<uint8_t> fullRange(diff, 0);\n\n    // \u0420\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 - \u043c\u0430\u0441\u0441\u0438\u0432 \u0441 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438 \u0438\u0437 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0430 \u043e\u0442 (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/// \u041f\u0430\u0440\u0430\u043b\u043b\u0435\u043b\u044c\u043d\u0430\u044f \u0434\u0435\u043a\u043e\u043c\u043f\u043e\u0437\u0438\u0446\u0438\u044f \u043d\u0430\u0431\u043e\u0440\u0430 \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b.\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    // \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d \u0447\u0438\u0441\u0435\u043b (begin, n]\n    // 1  - \u0435\u0441\u043b\u0438 \u0441\u043e\u0441\u0442\u0430\u0432\u043d\u043e\u0435\n    // 0 - \u0435\u0441\u043b\u0438 \u043f\u0440\u043e\u0441\u0442\u043e\u0435\n    vector<uint8_t> fullRange(diff, 0);\n\n    // \u0420\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 - \u043c\u0430\u0441\u0441\u0438\u0432 \u0441 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438 \u0438\u0437 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0430 \u043e\u0442 (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/// \u041f\u0430\u0440\u0430\u043b\u043b\u0435\u043b\u044c\u043d\u044b\u0439 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0441 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435\u043c 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    // \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d \u0447\u0438\u0441\u0435\u043b (begin, n]\n    // 1  - \u0435\u0441\u043b\u0438 \u0441\u043e\u0441\u0442\u0430\u0432\u043d\u043e\u0435\n    // 0 - \u0435\u0441\u043b\u0438 \u043f\u0440\u043e\u0441\u0442\u043e\u0435\n    vector<uint8_t> fullRange(diff, 0);\n\n    // \u0420\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 - \u043c\u0430\u0441\u0441\u0438\u0432 \u0441 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438 \u0438\u0437 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0430 \u043e\u0442 (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    // \u043e\u0436\u0438\u0434\u0430\u0435\u043c \u0432\u0441\u0435 \u043f\u043e\u0442\u043e\u043a\u0438 \u0432 \u043f\u0443\u043b\u0435\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/// \u041f\u0430\u0440\u0430\u043b\u043b\u0435\u043b\u044c\u043d\u044b\u0439 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0441 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435\u043c 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    // \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d \u0447\u0438\u0441\u0435\u043b (begin, n]\n    // 1  - \u0435\u0441\u043b\u0438 \u0441\u043e\u0441\u0442\u0430\u0432\u043d\u043e\u0435\n    // 0 - \u0435\u0441\u043b\u0438 \u043f\u0440\u043e\u0441\u0442\u043e\u0435\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                // \u0440\u0430\u0437\u0431\u043b\u043e\u043a\u0438\u0440\u0443\u0435\u043c \u043c\u044c\u044e\u0442\u0435\u043a\u0441, \u0442\u0430\u043a \u043a\u0430\u043a \u043f\u0435\u0440\u0435\u0441\u0442\u0430\u043b\u0438 \u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c\n                // \u0441 \u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0435\u043c\u044b\u043c \u0440\u0435\u0441\u0443\u0440\u0441\u043e\u043c (\u0438\u043d\u0434\u0435\u043a\u0441)\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    // \u0420\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 - \u043c\u0430\u0441\u0441\u0438\u0432 \u0441 \u043f\u0440\u043e\u0441\u0442\u044b\u043c\u0438 \u0447\u0438\u0441\u043b\u0430\u043c\u0438 \u0438\u0437 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0430 \u043e\u0442 (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    // \u041f\u0435\u0440\u0432\u044b\u0439 \u0448\u0430\u0433.\n    const auto firstStepRes = timeBenchmark<FirstStepResult>(getBasePrimeBySieveOfEratosthenes, sqrtN);\n    cout << \"> First step: \" << firstStepRes.first << \" ms\" << endl;\n    writeToFile(\"firstStep.txt\", firstStepRes.second);\n\n    // \u041f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u0430\u044f \u0434\u0435\u043a\u043e\u043c\u043f\u043e\u0437\u0438\u0446\u0438\u044f \u043f\u043e \u0434\u0430\u043d\u043d\u044b\u043c\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    // \u041f\u0430\u0440\u0430\u043b\u043b\u0435\u043b\u044c\u043d\u0430\u044f \u0434\u0435\u043a\u043e\u043c\u043f\u043e\u0437\u0438\u0446\u0438\u044f \u043f\u043e \u0434\u0430\u043d\u043d\u044b\u043c: threadCount \u043f\u043e\u0442\u043e\u043a\u043e\u0432\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    // \u041f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u0430\u044f \u0434\u0435\u043a\u043e\u043c\u043f\u043e\u0437\u0438\u0446\u0438\u044f \u043d\u0430\u0431\u043e\u0440\u0430 \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b\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    // \u041f\u0430\u0440\u0430\u043b\u043b\u0435\u043b\u044c\u043d\u0430\u044f \u0434\u0435\u043a\u043e\u043c\u043f\u043e\u0437\u0438\u0446\u0438\u044f \u043d\u0430\u0431\u043e\u0440\u0430 \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b: threadCount \u043f\u043e\u0442\u043e\u043a\u043e\u0432\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    // \u0421 \u043f\u0440\u0438\u043c\u0435\u043d\u0435\u043d\u0438\u0435\u043c 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    // \u041f\u0443\u043b \u043f\u043e\u0442\u043e\u043a\u043e\u0432\n    doParThreadPool();\n\n    // \u0421 \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u044b\u043c \u043f\u0435\u0440\u0435\u0431\u043e\u0440\u043e\u043c \u043f\u0440\u043e\u0441\u0442\u044b\u0445 \u0447\u0438\u0441\u0435\u043b\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": "//\n//  Copyright (c) 2000-2002\n//  Joerg Walter, Mathias Koch\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  GeNeSys mbH & Co. KG in producing this work.\n//\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main () {\n    using namespace boost::numeric::ublas;\n    vector<double> v1 (3), v2 (3);\n    for (unsigned i = 0; i < (std::min) (v1.size (), v2.size ()); ++ i)\n        v1 (i) = v2 (i) = i;\n\n    std::cout << v1 + v2 << std::endl;\n    std::cout << v1 - v2 << std::endl;\n}\n\n", "meta": {"hexsha": "8b42d0659c91157d686c1fd23072c8f3d054bf4b", "size": 690, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/numeric/ublas/doc/samples/vector_binary.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/vector_binary.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/vector_binary.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": 26.5384615385, "max_line_length": 71, "alphanum_fraction": 0.6202898551, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5655643497775091}}
{"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": "#ifndef _ROBOLAND_COMMAND_TOOLS_HH_\n#define _ROBOLAND_COMMAND_TOOLS_HH_\n\n#include <Eigen/Dense>\n\n#include <array>\n\nusing namespace std;\n\nnamespace roboland {\n\nnamespace tools {\n\nclass BSpline\n{\npublic:\n  class Exception : public std::exception\n  {\n  private:\n    string msg;\n  public:\n    Exception(const string msg):\n      msg(\"Exception in spline: \" + msg)\n    {\n    }\n\n\n    const char *what() const noexcept override\n    {\n      return msg.data();\n    }\n  };\n\n  typedef Eigen::Matrix<double, 1, 5> Coeffs;\n  typedef Eigen::Matrix<double, 5, 1> CoeffsCompl;\n\n  struct Point\n  {\n    Point() = default;\n    Point(const double x,\n          const double y);\n\n    bool operator==(const BSpline::Point &other) const;\n    double x;\n    double y;\n    double getSlope(const BSpline::Point &other) const;\n  };\n\n  struct Spline\n  {\n    Spline() = default;\n    Spline(const array<Point, 3> &points,\n           const double s_i_1);\n    Spline(const array<BSpline::Point, 2> &init_point,\n           const double s_i_1);\n\n    double start_x;\n    double end_x;\n    array<Point, 3> points;\n    array<double, 4> control_points;\n\n    int isInRange(const double x) const;\n    double scaleX(const double x) const;\n    void calculateControlPoints(const double s_i_1);\n    double getValue(const double x) const;\n    double getDerValue(const double x) const;\n    double get2DerValue(const double x) const;\n    bool validSpline() const;\n    string getRangeStr() const;\n  };\n\n  BSpline() = default;\n  BSpline(const vector<BSpline::Point> &initial_points,\n               const float min_thr=INFINITY,\n               const float max_thr=INFINITY,\n               const float slope_thr=INFINITY);\n  BSpline::Spline createSpline(const array<Point, 4> &points);\n\n  int addPoint(const Point &point);\n  double getValue(const double x) const;\n  double getDerValue(const double x) const;\n  double get2DerValue(const double x) const;\n  void erase(const double x);\n  void eraseUpper(const double x);\n  bool isInRange(const double x) const;\nprivate:\n  vector<Spline> splines;\n  double min;\n  double max;\n  double min_thr;\n  double max_thr;\n  double slope_thr;\n\n  static CoeffsCompl getCoeffsCompl(const double x);\n  static CoeffsCompl getDerCoeffsCompl(const double x);\n};\n\ndouble radianRound(double theta);\n\n} // namespace tools\n\n} // namespace roboland\n\n#endif /* _ROBOLAND_COMMAND_TOOLS_HH_ */\n", "meta": {"hexsha": "a13fd88b112e9184ac38ed42c3b63a04e58643a1", "size": 2360, "ext": "hh", "lang": "C++", "max_stars_repo_path": "ROS/commons/tools/include/tools/tools.hh", "max_stars_repo_name": "cxdcxd/NAVbot", "max_stars_repo_head_hexsha": "8068e7ca596708f1fbfc63b1f6f944b85dee0953", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-11T18:40:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-11T18:40:25.000Z", "max_issues_repo_path": "ROS/commons/tools/include/tools/tools.hh", "max_issues_repo_name": "cxdcxd/NAVbot", "max_issues_repo_head_hexsha": "8068e7ca596708f1fbfc63b1f6f944b85dee0953", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ROS/commons/tools/include/tools/tools.hh", "max_forks_repo_name": "cxdcxd/NAVbot", "max_forks_repo_head_hexsha": "8068e7ca596708f1fbfc63b1f6f944b85dee0953", "max_forks_repo_licenses": ["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.4761904762, "max_line_length": 62, "alphanum_fraction": 0.6805084746, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5655392090730132}}
{"text": "\n#include <boost/property_map/dynamic_property_map.hpp>\n#include <boost/config.hpp>\n#include <boost/graph/graphml.hpp>\n#include \"include_and_types.cpp\"\n#include \"my_pearce.cpp\"\n#include \"my_nuutila.cpp\"\n#include \"my_tarjan.cpp\"\n#include \"my_pearce_not_recursive.cpp\"\n#include <boost/timer/timer.hpp>\n#include <iostream>\n#include <vector>\n#include <stack>\n#include <boost/graph/strong_components.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/config.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n\n\n#include <boost/graph/erdos_renyi_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n\nusing namespace boost;\n\ntypedef boost::erdos_renyi_iterator<boost::minstd_rand, Graph> ERGen;\n\ntemplate <class Result1, class Result2>\nbool compare_results(const Result1 r1, const Result2 r2){\n    if (r1.size() != r2.size())\n        return false;\n    int maxVal=0;\n    int minVal=0;\n    for(int i=0; i!=r1.size(); i++){\n        maxVal = std::max(maxVal, r1[i]);\n        minVal = std::min(minVal, r2[i]);\n    }\n    minVal-=1;\n    maxVal+=1;\n    int comp[maxVal];\n    for (int i=0; i != maxVal; i++)\n        comp[i]=minVal;\n\n    for (int i = 0; i != r1.size(); i++){\n        if (comp[r1[i]]==minVal) {\n            for (int j = 0; j < i; j++) {\n                if (r1[i] != r1[j] && r2[i] == r2[j])\n                    return false;\n            }\n            comp[r1[i]] = r2[i];\n        }\n        if (comp[r1[i]]!=r2[i]){\n            return false;\n        }\n    }\n    return true;\n}\n\nstd::vector<int> correct_nuutila_root(std::vector<int> vec){\n    bool ok = false;\n    while(!ok){\n        ok = true;\n        for(int i=0; i<vec.size(); i++){\n            if(vec[i] != i && vec[i]!= vec[vec[i]]){\n                vec[i]=vec[vec[i]];\n                ok=false;\n            }\n        }\n    }\n    return vec;\n}\nint main(int, char*[])\n{\n    /*\n    typedef std::pair<int, int> Edge;\n    const int num_nodes = 8;\n    enum nodes { A, B, C, D, E, F, G, H, I, L, M, N};\n    char name[] = \"ABCDEFGHILMN\";\n\n    Edge edge_array[] = { Edge(A, B),\n                          Edge(B, C), Edge(B, H),\n                          Edge(C, D), Edge(C, G),\n                          Edge(D, E),\n                          Edge(E, F), Edge(E, C),\n                          Edge(G, F), Edge(G, D),\n                          Edge(H, A), Edge(H, G),\n                          Edge(I, L),\n                          Edge(M, N), Edge(N, M)\n    };\n    int num_arcs = sizeof(edge_array) / sizeof(Edge);\n    Graph g(edge_array, edge_array + num_arcs, num_nodes);\n    std::cout << \"A directed graph:\" << std::endl;\n    print_graph(g,name);\n    std::cout << std::endl;\n    */\n\n    dynamic_properties dp;\n    minstd_rand gen;\n    // Create graph with 100 nodes and edges with probability 0.05\n    int nodes= 30;\n    Graph g(ERGen(gen, nodes, 0.05), ERGen(), nodes);\n\n    write_graphml(std::cout, g, dp, true);\n\n\n\n    // Tarjan's algorithm over the given graph\n    std::cout << \"Tarjan\\t\\t\" << std::flush;\n    TarjanClass<typeInt, typeInt, typeInt, typeBool, typeBool, typeInt> tarjan(&g);\n    std::vector<int>* component = tarjan.tarjan_scc();\n\n    // Nuutila's algorithm over the given graph\n    std::cout << \"Nuutila\\t\\t\" << std::flush;\n    NuutilaClass<typeInt, typeInt, typeBool> nuutila(&g);\n    std::vector<int>* root_nuutila = nuutila.nuutila_scc();\n\n    // Pearce's recursive algorithm over the given graph\n    std::cout << \"Pearce\\t\\t\" << std::flush;\n    PearceClass<typeInt> pearce(&g);\n    std::vector<int>* rindex = pearce.pearce_scc();\n\n    // Pearce's non recursive algorithm over the given graph\n    std::cout << \"PearceNR\\t\\t\" << std::flush;\n    PearceNR <typeBool, typeInt> pearcenr(&g);\n    std::vector<int>* rindexNR = pearcenr.pearce_not_recursive_scc();\n\n    /*std::cout << \"Pearce_NR\\t\" << std::flush;\n    std::vector<int> rindex_not_recursive(num_vertices(g));\n    int num_pearce_not_recursive = pearce_not_recursive_scc(g, make_iterator_property_map(rindex_not_recursive.begin(), get(vertex_index, g)));\n    */\n    std::vector<int> bgl_component(num_vertices(g)), discover_time(num_vertices(g));\n    std::vector<default_color_type> bgl_color(num_vertices(g));\n    std::vector<Vertex> bgl_root(num_vertices(g));\n    int num_bgl = strong_components(g,\n                                make_iterator_property_map(bgl_component.begin(), get(vertex_index, g)),\n                                root_map(make_iterator_property_map(bgl_root.begin(), get(vertex_index, g))).\n                                        color_map(make_iterator_property_map(bgl_color.begin(), get(vertex_index, g))).\n                                        discover_time_map(make_iterator_property_map(discover_time.begin(), get(vertex_index, g))));\n\n    std::cout << \"Number of components: bgl:\"<< num_bgl << std::endl;\n    //std::cout << \"Total number of components: \" << num << std::endl;\n\n\n    std::cout << \"No\" << \"\\t->\\tBgl\\tTa\\tNu\\tPe\\tPeNr\" << std::endl;\n    for (int i = 0; i != (*component).size(); ++i){\n        std::cout << i << \"\\t->\\t\"<< bgl_component[i] << \"\\t\" << (*component)[i] << \"\\t\" << (*root_nuutila)[i] << \"\\t\" << (*rindex)[i] << \"\\t\" << (*rindexNR)[i] << std::endl;\n    }\n    return 0;\n}\n\n\n", "meta": {"hexsha": "61bd97a0317bfcaf417e604a5c131038ad3213b6", "size": 5262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "phisco/advance_algorithms_project", "max_stars_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T13:46:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-28T16:42:31.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "phisco/advance_algorithms_project", "max_issues_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "phisco/advance_algorithms_project", "max_forks_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3921568627, "max_line_length": 174, "alphanum_fraction": 0.5756366401, "num_tokens": 1457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5655391984867575}}
{"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 <boost/program_options.hpp>\n\n#include <iostream>\n#include <string>\n\n#include \"spf/graph.h\"\n#include \"spf/web_socket_rpc.h\"\n\nnamespace po = boost::program_options;\n\nusing namespace spf;\n\nvoid run(std::string const& host, unsigned short port) {\n  WebSocketRpc service{host, port};\n  Graph g{service};\n  g.addVertex(); g.addVertex(); g.addVertex(); g.addVertex();\n  g.addVertex(); g.addVertex();\n  g.setEdge(0, 1, 7); g.setEdge(0, 2, 9); g.setEdge(0, 5, 14);\n  g.setEdge(1, 0, 7); g.setEdge(1, 2, 10); g.setEdge(1, 3, 15);\n  g.setEdge(2, 0, 9); g.setEdge(2, 1, 10); g.setEdge(2, 5, 2);\n  g.setEdge(3, 1, 15); g.setEdge(3, 2, 11); g.setEdge(3, 4, 6);\n  g.setEdge(4, 3, 6); g.setEdge(4, 5, 9);\n  g.setEdge(5, 0, 14); g.setEdge(5, 2, 2); g.setEdge(5, 4, 9);\n\n  auto path = g.path(0, 4);\n\n  std::cout << \"Path: \";\n  for (Id id: path) std::cout << id << ' ';\n  std::cout << '\\n';\n}\n\nvoid async_run(std::string const& host, unsigned short port) {\n  WebSocketRpc service{host, port};\n  Graph g{service};\n\n  auto add_error = [](Id, auto error) {\n    if (error) std::cout << error.what() << '\\n';\n  };\n  g.addVertex(add_error); g.addVertex(add_error); g.addVertex(add_error);\n  g.addVertex(add_error); g.addVertex(add_error); g.addVertex(add_error);\n\n  auto set_error = [](auto error) {\n    if (error) std::cout << error.what() << '\\n';\n  };\n  g.setEdge(0, 1, 7, set_error);\n  g.setEdge(0, 2, 9, set_error);\n  g.setEdge(0, 5, 14, set_error);\n  g.setEdge(1, 0, 7, set_error);\n  g.setEdge(1, 2, 10, set_error);\n  g.setEdge(1, 3, 15, set_error);\n  g.setEdge(2, 0, 9, set_error);\n  g.setEdge(2, 1, 10, set_error);\n  g.setEdge(2, 5, 2, set_error);\n  g.setEdge(3, 1, 15, set_error);\n  g.setEdge(3, 2, 11, set_error);\n  g.setEdge(3, 4, 6, set_error);\n  g.setEdge(4, 3, 6, set_error);\n  g.setEdge(4, 5, 9, set_error);\n  g.setEdge(5, 0, 14, set_error);\n  g.setEdge(5, 2, 2, set_error);\n  g.setEdge(5, 4, 9, set_error);\n\n  g.path(0, 4, [](auto path, auto error) {\n    if (!error) {\n      std::cout << \"Path: \";\n      for (Id id: path) std::cout << id << ' ';\n      std::cout << '\\n';\n    } else {\n      std::cout << error.what() << '\\n';\n    }\n  });\n}\n\nint main(int argc, char* argv[]) {\n  bool async{false};\n  std::string host{\"localhost\"};\n  unsigned short port{8080};\n\n  po::options_description args(\"Using\");\n  args.add_options()\n    (\"help\", \"produce help message\")\n    (\"async\", po::value<bool>(&async)->default_value(false), \"asynchronous client\")\n    (\"host\", po::value<std::string>(&host)->default_value(\"localhost\"), \"host to connect\")\n    (\"port\", po::value<unsigned short>(&port)->default_value(8080), \"port to connect\");\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, args), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n      std::cout << args << \"\\n\";\n      return 1;\n  }\n\n  if (async) {\n    async_run(host, port);\n  } else {\n    run(host, port);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "5c74f072d0785309b4aef56c1c8d24f5235f275c", "size": 2897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "bonewell/libspfclient", "max_stars_repo_head_hexsha": "a23201d020cd42db698c42661bb21e2c85a1dafe", "max_stars_repo_licenses": ["MIT"], "max_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": "bonewell/libspfclient", "max_issues_repo_head_hexsha": "a23201d020cd42db698c42661bb21e2c85a1dafe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T19:00:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-31T16:56:33.000Z", "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "bonewell/libspfclient", "max_forks_repo_head_hexsha": "a23201d020cd42db698c42661bb21e2c85a1dafe", "max_forks_repo_licenses": ["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.1262135922, "max_line_length": 90, "alphanum_fraction": 0.5995857784, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5655229069132801}}
{"text": "\n// BLAS level 2\n// benchmarks \n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n//#define USE_STD_VECTOR\n//#define BOUNDED 100*100\n\n//#define PRINT\n//#define PRINT_M\n\n//#define MODIFY\n\n#include <stddef.h>\n#include <iostream>\n#include <boost/numeric/bindings/atlas/cblas1.hpp>\n#include <boost/numeric/bindings/atlas/cblas2.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_symmetric.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#ifdef USE_STD_VECTOR\n#include <vector>\n#include <boost/numeric/bindings/traits/std_vector.hpp> \n#endif \n#include <boost/timer.hpp>\n#include \"utils.h\" \n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::cout;\nusing std::cin;\nusing std::endl; \n\ntypedef double real_t; \n\n#ifdef USE_STD_VECTOR\ntypedef std::vector<real_t> storage_t; \n#else\n#ifndef BOUNDED \ntypedef ublas::unbounded_array<real_t> storage_t; \n#else\ntypedef ublas::bounded_array<real_t, BOUNDED> storage_t; \n#endif \n#endif \n\ntypedef ublas::vector<real_t, storage_t> vct_t;\n\ntypedef ublas::matrix<real_t, ublas::column_major, storage_t> cm_t;\ntypedef ublas::matrix<real_t, ublas::row_major, storage_t> rm_t;\n\ntypedef ublas::symmetric_adaptor<cm_t, ublas::upper> ucsa_t; \ntypedef ublas::symmetric_adaptor<cm_t, ublas::lower> lcsa_t; \ntypedef ublas::symmetric_adaptor<rm_t, ublas::upper> ursa_t; \ntypedef ublas::symmetric_adaptor<rm_t, ublas::lower> lrsa_t; \n\ntypedef ublas::symmetric_matrix<\n  real_t, ublas::upper, ublas::column_major\n> ucsymm_t; \ntypedef ublas::symmetric_matrix<\n  real_t, ublas::lower, ublas::column_major\n> lcsymm_t; \ntypedef ublas::symmetric_matrix<\n  real_t, ublas::upper, ublas::row_major\n> ursymm_t; \ntypedef ublas::symmetric_matrix<\n  real_t, ublas::lower, ublas::row_major\n> lrsymm_t; \n\n#ifdef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \nusing ublas::prod; \n#endif \n\n////////////////////////////////////////////////////\n// general matrix: gemv()\n\ntemplate <typename M>\nvoid bench_gemv (size_t n, size_t runs, char* msg) {\n\n  cout << msg << endl; \n\n  vct_t x (n);\n  atlas::set (1., x);\n  vct_t y (n); \n\n  M a (n, n);\n  init_symm (a); \n#ifdef PRINT_M\n  print_m (a, \"a\");\n  cout << endl; \n#endif \n\n  boost::timer (t); \n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    a (0, 2) = r; \n    a (2, 0) = r; \n#endif \n    atlas::gemv (a, x, y);\n#ifdef PRINT\n    print_v (y, \"y\"); \n#endif\n  } \n  cout << \"  gemv:        \" << t.elapsed() << endl;  \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    a (0, 2) = r; \n    a (2, 0) = r; \n#endif \n    atlas::gemv (CblasTrans, 1., a, x, 0., y);\n#ifdef PRINT\n    print_v (y, \"y\"); \n#endif\n  } \n  cout << \"  gemv trans:  \" << t.elapsed() << endl;  \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    a (0, 2) = r; \n    a (2, 0) = r; \n#endif \n    y = prod (a, x);\n#ifdef PRINT\n    print_v (y, \"y\"); \n#endif \n  }\n  cout << \"  = prod:      \" << t.elapsed() << endl; \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    a (0, 2) = r; \n    a (2, 0) = r; \n#endif \n    y.assign (prod (a, x));\n#ifdef PRINT\n    print_v (y, \"y\"); \n#endif\n  } \n  cout << \"  assign prod: \" << t.elapsed() << endl; \n  cout << endl; \n}\n\n\n/////////////////////////////////////////////////////////\n// symmetric adaptor: symv()\n\ntemplate <typename M, typename SA>\nvoid bench_symv (size_t n, size_t runs, char* msg) {\n\n  cout << msg << endl; \n\n  vct_t x (n);\n  atlas::set (1., x);\n  vct_t y (n); \n\n  M a (n, n);\n  SA sa (a); \n  init_symm (sa, 'l'); \n#ifdef PRINT_M\n  print_m (sa, \"sa\"); \n  cout << endl; \n  print_m (a, \"a\"); \n  cout << endl; \n#endif \n\n  boost::timer (t); \n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    sa (0, 2) = r; \n#endif \n    atlas::symv (sa, x, y);\n#ifdef PRINT\n    print_v (y, \"y\"); \n#endif\n  } \n  cout << \"  symv:        \" << t.elapsed() << endl;  \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    sa (0, 2) = r; \n#endif \n    y = prod (sa, x);\n#ifdef PRINT\n    print_v (y, \"y\"); \n#endif \n  }\n  cout << \"  = prod:      \" << t.elapsed() << endl; \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    sa (0, 2) = r; \n#endif \n    y.assign (prod (sa, x));\n#ifdef PRINT\n    print_v (y, \"y\"); \n#endif\n  } \n  cout << \"  assign prod: \" << t.elapsed() << endl; \n  cout << endl; \n}\n\n\n/////////////////////////////////////////////////////////\n// symmetric matrix: spmv()\n\ntemplate <typename SM>\nvoid bench_spmv (size_t n, size_t runs, char* msg) {\n\n  cout << msg << endl; \n\n  vct_t x (n);\n  atlas::set (1., x);\n  vct_t y (n); \n\n  SM sa (n, n);\n  init_symm (sa, 'l'); \n#ifdef PRINT_M\n  cout << sa << endl;\n  cout << endl; \n#endif \n\n  boost::timer (t); \n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    sa (0, 2) = r; \n#endif \n    atlas::spmv (sa, x, y);\n#ifdef PRINT\n    print_v (y, \"y\"); \n#endif\n  } \n  cout << \"  spmv:        \" << t.elapsed() << endl;  \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    sa (0, 2) = r; \n#endif \n    y = prod (sa, x);\n#ifdef PRINT\n    print_v (y, \"y\"); \n#endif \n  }\n  cout << \"  = prod:      \" << t.elapsed() << endl; \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    sa (0, 2) = r; \n#endif \n    y.assign (prod (sa, x));\n#ifdef PRINT\n    print_v (y, \"y\"); \n#endif\n  } \n  cout << \"  assign prod: \" << t.elapsed() << endl; \n  cout << endl; \n}\n\n\n//////////////////////////////////////////////////////\nint main() {\n\n  cout << endl; \n\n  size_t n, r; \n  cout << \"n -> \"; \n  cin >> n;\n  cout << \"r -> \";\n  cin >> r;  \n  cout << endl; \n\n  bench_gemv<rm_t> (n, r, \"row major\"); \n  bench_gemv<cm_t> (n, r, \"column major\"); \n\n  bench_symv<rm_t, ursa_t> (n, r, \"symmetric ad, row, upper\"); \n  bench_symv<rm_t, lrsa_t> (n, r, \"symmetric ad, row, lower\"); \n  bench_symv<cm_t, ucsa_t> (n, r, \"symmetric ad, column, upper\"); \n  bench_symv<cm_t, lcsa_t> (n, r, \"symmetric ad, column, lower\"); \n\n  bench_spmv<ursymm_t> (n, r, \"symmetric, row, upper\"); \n  bench_spmv<lrsymm_t> (n, r, \"symmetric, row, lower\"); \n  bench_spmv<ucsymm_t> (n, r, \"symmetric, column, upper\"); \n  bench_spmv<lcsymm_t> (n, r, \"symmetric, column, lower\"); \n\n}\n", "meta": {"hexsha": "108f1154730c2f0980349b5f7af55b77f055fc00", "size": 6313, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libs/numeric/bindings/atlas/ublas_matr2_bench.cc", "max_stars_repo_name": "inducer/boost-numeric-bindings", "max_stars_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "libs/numeric/bindings/atlas/ublas_matr2_bench.cc", "max_issues_repo_name": "inducer/boost-numeric-bindings", "max_issues_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/bindings/atlas/ublas_matr2_bench.cc", "max_forks_repo_name": "inducer/boost-numeric-bindings", "max_forks_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 21.1137123746, "max_line_length": 67, "alphanum_fraction": 0.5708854744, "num_tokens": 2193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.5654971676834457}}
{"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#include \"headers/Sphere.hpp\"\n#include \"headers/Object.hpp\"\n#include \"headers/Hittable.hpp\"\n#include <armadillo>\n#include <vector>\n\nusing namespace arma;\nusing namespace std;\n\nSphere::Sphere() {\n}\n\nSphere::Sphere(vec esfera){\n    \n    mat transf;\n    vec kd, ks;\n    \n    transf << esfera(11) << esfera(12) << esfera(13) << esfera(14) << endr\n\t   << esfera(15) << esfera(16) << esfera(17) << esfera(18) << endr \n           << esfera(19) << esfera(20) << esfera(21) << esfera(22) << endr\n           << 0 << 0 << 0 << 1;\n\t\n    setTransf(transf);\n    \n    this->centro << esfera(0) << esfera(1) << esfera(2) << 1;\n    this->centro = transf * centro;\n    this->centro.shed_row(3);\n\t\n    this->raio = esfera(3);\t\n    \n    kd << esfera(4) << esfera(5) << esfera(6);\n    ks << esfera(7) << esfera(8) << esfera(9);\n    \n    setKd(kd);\n    setKs(ks);\n        \n    setP(esfera(10));\n\t\n    this->min = this->centro - this->raio;\n    this->max = this->centro + this->raio;\n        \n    setTipo(0);\n}\n\nbool Sphere::colide(const vec &d, double &T, const vec &origem){\n    double a, b, c, delta, x, xx;\n\t\n    a = dot(origem-d,origem-d);\n    b = 2*dot(origem-d, this->centro - origem);\n    c = dot(this->centro - origem, this->centro - origem) - (this->raio * this->raio);\n\t\n    delta = (b*b) - (4 * a * c);\n\n    if (delta>=0){\n\tx  = (-b + sqrt(delta)) / (2 * a);\n\txx = (-b - sqrt(delta)) / (2 * a);\n\t    \n\tif (x < xx) { \n            T=x; \n        }\n\t\n        else { \n            T=xx; \n        } \n\t    \n        return true;\n    }\n\t  \n    else { \n        return false; \n    }\n}  \n\n", "meta": {"hexsha": "41b415563b70bd6705df45d30453c55a18996fb7", "size": 1566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "raytracing/Sphere.cpp", "max_stars_repo_name": "arthurflor/RayTracing", "max_stars_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-19T09:38:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T02:04:22.000Z", "max_issues_repo_path": "raytracing/Sphere.cpp", "max_issues_repo_name": "arthurflor23/ray-tracing", "max_issues_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "raytracing/Sphere.cpp", "max_forks_repo_name": "arthurflor23/ray-tracing", "max_forks_repo_head_hexsha": "8deedf33446bed259d8f7e2895024fd1300eb439", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.88, "max_line_length": 86, "alphanum_fraction": 0.4980842912, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5654306120482179}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_id_2.h>\n#include <CGAL/boost/graph/graph_traits_Delaunay_triangulation_2.h>\n\n#include <CGAL/boost/graph/dijkstra_shortest_paths.h>\n#include <boost/graph/filtered_graph.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point;\n\ntypedef CGAL::Triangulation_vertex_base_with_id_2<K> Tvb;\ntypedef CGAL::Triangulation_face_base_2<K> Tfb;\ntypedef CGAL::Triangulation_data_structure_2<Tvb,Tfb> Tds;\ntypedef CGAL::Delaunay_triangulation_2<K, Tds> Triangulation;\n\n// consider finite vertices and edges.\n\ntemplate <typename T>\nstruct Is_finite {\n\n  const T* t_;\n\n  Is_finite()\n    : t_(NULL)\n  {}\n\n  Is_finite(const T& t)\n    : t_(&t)\n  { }\n\n  template <typename VertexOrEdge>\n  bool operator()(const VertexOrEdge& voe) const {\n    return ! t_->is_infinite(voe);\n  }\n};\n\ntypedef Is_finite<Triangulation> Filter;\ntypedef boost::filtered_graph<Triangulation,Filter,Filter> Finite_triangulation;\ntypedef boost::graph_traits<Finite_triangulation>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<Finite_triangulation>::vertex_iterator vertex_iterator;\n\n\nint\nmain(int,char*[])\n{\n  Triangulation t;\n  Filter is_finite(t);\n  Finite_triangulation ft(t, is_finite, is_finite);\n\n  t.insert(Point(0,0));\n  t.insert(Point(1,0));\n  t.insert(Point(0.2,0.2));\n  t.insert(Point(0,1));\n  t.insert(Point(0,2));\n\n  vertex_iterator vit, ve;\n  // associate indices to the vertices\n  int index = 0;\n  for(boost::tie(vit,ve)=boost::vertices(ft); vit!=ve; ++vit ){\n    vertex_descriptor  vd = *vit;\n    vd->id()= index++;\n  }\n\n  typedef boost::property_map<Triangulation, boost::vertex_index_t>::type VertexIdPropertyMap;\n  VertexIdPropertyMap vertex_index_pmap = get(boost::vertex_index, ft);\n\n  // Dijkstra's shortest path needs property maps for the predecessor and distance\n  std::vector<vertex_descriptor> predecessor(boost::num_vertices(ft));\n  boost::iterator_property_map<std::vector<vertex_descriptor>::iterator, VertexIdPropertyMap>\n    predecessor_pmap(predecessor.begin(), vertex_index_pmap);\n\n  std::vector<double> distance(boost::num_vertices(ft));\n  boost::iterator_property_map<std::vector<double>::iterator, VertexIdPropertyMap>\n    distance_pmap(distance.begin(), vertex_index_pmap);\n\n  vertex_descriptor source =  *boost::vertices(ft).first;\n  std::cout << \"\\nStart dijkstra_shortest_paths at \" << source->point() << std::endl;\n\n  boost::dijkstra_shortest_paths(ft, source ,\n\t\t\t\t distance_map(distance_pmap)\n\t\t\t\t .predecessor_map(predecessor_pmap));\n\n  for(boost::tie(vit,ve)=boost::vertices(ft); vit!=ve; ++vit ){\n    vertex_descriptor vd = *vit;\n    std::cout << vd->point() << \" [\" << vd->id() << \"] \";\n    std::cout << \" has distance = \"  << get(distance_pmap,vd) << \" and predecessor \";\n    vd = get(predecessor_pmap,vd);\n    std::cout << vd->point() << \" [\" << vd->id() << \"]\\n\";\n  }\n  return 0;\n}\n", "meta": {"hexsha": "0a3d0d7b5c7e56ebaa5df706463cddc4b2a25cf6", "size": 2996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/BGL/examples/BGL_triangulation_2/dijkstra_with_internal_properties.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/BGL/examples/BGL_triangulation_2/dijkstra_with_internal_properties.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/BGL/examples/BGL_triangulation_2/dijkstra_with_internal_properties.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2150537634, "max_line_length": 94, "alphanum_fraction": 0.7309746328, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5654306098670097}}
{"text": "\n/*\nfragmentLengthModel.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 \"fragmentLengthModel.h\"\n#include <math.h>\n#include <fstream>\n#include <sstream>\n\n#include \"boost/math/constants/constants.hpp\"\n#include <boost/filesystem.hpp>\n\nGaussianFragmentLengthModel::GaussianFragmentLengthModel() {}\n\nGaussianFragmentLengthModel::GaussianFragmentLengthModel(double mean_in, double sd_in) {\n\n\tmean = mean_in;\n\tsd = sd_in;\n\tvar = pow(sd, 2);\n\n\tnorm_const = 1/(sd*sqrt(2*boost::math::constants::pi<double>()));\n\n\tcout << \"[\" << getLocalTime() << \"] Using Gaussian fragment length distribution with parameters: Mean=\" << mean << \" and SD=\" << sd << endl;\n\n}\n\nGaussianFragmentLengthModel::GaussianFragmentLengthModel(map<uint,uint> fragment_lengths) {\n\n\tpair<double,double> parameters = estimateParameters(fragment_lengths);\n\n\tmean = parameters.first;\n\tsd = 1.4826 * parameters.second;\n\n\tvar = pow(sd, 2);\n\tnorm_const = 1/(sd*sqrt(2*boost::math::constants::pi<double>()));\n\n\tcout << \"[\" << getLocalTime() << \"] Using Gaussian fragment length distribution with parameters: Mean=\" << mean << \" and SD=\" << sd << endl;\n}\n\n\ndouble GaussianFragmentLengthModel::pmf(uint fragment_length) {\n\n\treturn norm_const * exp(-(pow((double) fragment_length - mean, 2)/(2*var)));\n}\n\ntemplate <typename DataType>\ndouble GaussianFragmentLengthModel::estimateMedian(map<DataType,uint> observations) {\n\n\tint observation_count = 0;\n\n\tfor (typename map<DataType,uint>::iterator observation_iter = observations.begin(); observation_iter != observations.end(); observation_iter++) {\n\n\t\tobservation_count += observation_iter->second;\n\t}\n\n\tassert(observation_count > 0);\n\n\t// Find median observation index for uneven observation number and first median observation for even observation number\n\tint median_observation_idx;\n\n\tif (observation_count % 2 == 0) {\n\n\t\tmedian_observation_idx = (int) round((double) observation_count/2.0);\n\n\t} else {\n\n\t\tmedian_observation_idx = (int) ceil((double) observation_count/2.0);\n\t}\n\n\t// Iterate to median observation index\n\ttypename map<DataType,uint>::iterator observation_iter = observations.begin();\n\tint observation_count_running = observation_iter->second;\n\n\twhile (observation_count_running < median_observation_idx) {\n\n\t\tobservation_iter++;\n\t\tobservation_count_running += observation_iter->second;\n\t} \n\n\tif (observation_count % 2 == 0 and observation_count_running == median_observation_idx) {\n\n\t\tDataType median = observation_iter->first; \n\t\tobservation_iter++; \n\t\tassert(observation_iter != observations.end());\n\t\tmedian += observation_iter->first; \n\t\treturn (double) median / 2;\n\n\t} else {\n\n\t\tassert(observation_count_running >= median_observation_idx);\n\n\t\treturn (double) observation_iter->first; \n\t}\n}\n\npair<double,double> GaussianFragmentLengthModel::estimateParameters(map<uint,uint> fragment_lengths) {\n\n\tdouble median = estimateMedian(fragment_lengths);\n\n\tmap<double,uint> abs_distances;\n\tint observation_count = 0;\n\n\tfor (map<uint,uint>::iterator fragment_lengths_iter = fragment_lengths.begin(); fragment_lengths_iter != fragment_lengths.end(); fragment_lengths_iter++) {\n\n\t\tassert(fragment_lengths_iter->first > 0);\n\t\tobservation_count += fragment_lengths_iter->second;\n\n\t\tdouble distance = abs((double) fragment_lengths_iter->first - median); \n\n\t\tif (abs_distances.count(distance) == 0) {\n\n\t\t\tabs_distances[distance] = fragment_lengths_iter->second;\n\n\t\t} else {\n\n\t\t\tabs_distances[distance] += fragment_lengths_iter->second;\n\n\t\t}\t\n\t}\n\n\tdouble median_abs_deviation = estimateMedian(abs_distances);\n\n\tif (observation_count < 10000) {\n\n\t\tcout << \"\\n[\" << getLocalTime() << \"] WARNING: Only \" << observation_count << \" observation(s) were used for estimation of the fragment length distribution!\\n\" << endl;\n\t}\n\n\tcout << \"[\" << getLocalTime() << \"] Estimated fragment length \\\"median\\\"=\" << median << \" and \\\"median absolute deviation\\\"=\" << median_abs_deviation << \" using \" << observation_count << \" observations\" << endl;\n\n\treturn pair<double,double> (median, median_abs_deviation);\n}\n\nEmpiricalFragmentLengthModel::EmpiricalFragmentLengthModel(string distribution_filename) {\n\n\tassert(boost::filesystem::exists(distribution_filename));  \n\n\tifstream distribution_file(distribution_filename.c_str());\n    assert(distribution_file.is_open());\n    \n    string distribution_line;    \n    \n    uint fragment_length;\n    double probability;\n    uint line_count = 0;\n\n    while (getline(distribution_file, distribution_line)) {\n\n    \tline_count++;\n        stringstream linestream(distribution_line);\n\n\t    // Read the integers using the operator >>\n\t    linestream >> fragment_length >> probability;\n\n\t    assert(distribution.count(fragment_length) == 0);\n\t    distribution[fragment_length] = probability;\n    }\n\n    cout << \"[\" << getLocalTime() << \"] Loaded empirical fragment length distribution containing \" << line_count << \" fragment length values - the remaining will have point-zero probability \" << endl;\n}\n\ndouble EmpiricalFragmentLengthModel::pmf(uint fragment_length) {\n\n\tif (distribution.count(fragment_length)) {\n\n\t\treturn distribution[fragment_length];\n\t\n\t} else {\n\n\t\treturn 0;\n\t}\n}\n", "meta": {"hexsha": "db851d592fc7bdd615e77c107feff6e0d719a9df", "size": 6233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fragmentLengthModel.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/fragmentLengthModel.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/fragmentLengthModel.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.6395939086, "max_line_length": 212, "alphanum_fraction": 0.7453874539, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5654306075650016}}
{"text": "#include \"CrtbpSystem.hpp\"\n#include <assert.h>\n#include <boost/numeric/odeint.hpp>\n#include <iostream>\n\nstruct push_back_state_and_time\n{\n\tstd::vector<state_type> &m_states;\n\tstd::vector<double> &m_times;\n\n\tpush_back_state_and_time(std::vector<state_type> &states,\n\t\t\t\t\t\t\t\t\t\t\t\t\t std::vector<double> &times)\n\t\t\t: m_states(states), m_times(times)\n\t{\n\t}\n\n\tvoid operator()(const state_type &x, double t)\n\t{\n\t\tm_states.push_back(x);\n\t\tm_times.push_back(t);\n\t}\n};\n\nint main()\n{\n\tusing namespace boost::numeric::odeint;\n\n\tCrtbpSystem sys(0.012);\n\tsize_t steps;\n\tstate_type x(6);\n\tx[0] = 0.8;\n\tx[1] = 0.0;\n\tx[2] = 0.0;\n\tx[3] = 0.0;\n\tx[4] = 0.7;\n\tx[5] = 0.0;\n\n\tstd::vector<state_type> x_vec;\n\tstd::vector<double> times;\n\n\tsteps =\n\t\t\tintegrate(sys, x, 0.0, 20.0, 0.1, push_back_state_and_time(x_vec, times));\n\n\t/* output */\n\tfor (size_t i = 0; i <= steps; i++) {\n\t\tstd::cout << x_vec[i][0] << ' ' << x_vec[i][1] << ' ' << x_vec[i][2]\n\t\t\t\t\t\t\t<< '\\n';\n\t}\n  return 0;\n}\n", "meta": {"hexsha": "225f06223c15d5ae6cf05c818be20a393949de7f", "size": 957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_integration.cpp", "max_stars_repo_name": "rjpower4/crtbp-cpp", "max_stars_repo_head_hexsha": "bebd53edb014a46964e68bb33e8940977b2b766d", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_integration.cpp", "max_issues_repo_name": "rjpower4/crtbp-cpp", "max_issues_repo_head_hexsha": "bebd53edb014a46964e68bb33e8940977b2b766d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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_integration.cpp", "max_forks_repo_name": "rjpower4/crtbp-cpp", "max_forks_repo_head_hexsha": "bebd53edb014a46964e68bb33e8940977b2b766d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-26T07:06:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-26T07:06:49.000Z", "avg_line_length": 18.7647058824, "max_line_length": 77, "alphanum_fraction": 0.6154649948, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.565430602840187}}
{"text": "#include \"../src/streamingcc_include/util.h\"\n#define BOOST_TEST_MODULE ClassTest\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/unit_test.hpp>\n#include <random>\n#include <map>\n#include <iostream>\n#include <vector>\n\nusing namespace streamingcc::util;\n\nBOOST_AUTO_TEST_CASE(util_Test) {\n  std::vector<int> vec = {6, 2, 7, 4, 5, 1, 3};\n  int median = CalcMedian(vec);\n  BOOST_CHECK(median == 4);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "75cc9c81198b5e066e3446352b924bcbf1947c51", "size": 417, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/util_test.cc", "max_stars_repo_name": "jiecchen/StreamingCC", "max_stars_repo_head_hexsha": "34547a16239735771341a5bb202204b71c6d1fa2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-10-24T12:35:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T04:46:40.000Z", "max_issues_repo_path": "tests/util_test.cc", "max_issues_repo_name": "jiecchen/StreamingCC", "max_issues_repo_head_hexsha": "34547a16239735771341a5bb202204b71c6d1fa2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-18T13:46:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T13:46:35.000Z", "max_forks_repo_path": "tests/util_test.cc", "max_forks_repo_name": "jiecchen/StreamingCC", "max_forks_repo_head_hexsha": "34547a16239735771341a5bb202204b71c6d1fa2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-06-25T03:56:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-07T08:49:14.000Z", "avg_line_length": 11.2702702703, "max_line_length": 47, "alphanum_fraction": 0.6954436451, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5654199331885965}}
{"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// \u540c\u6837\uff0c\u524d\u51e0\u4e2ainclude\u6587\u4ef6\u5df2\u7ecf\u77e5\u9053\u4e86\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u4f1a\u5bf9\u5b83\u4eec\u8fdb\u884c\u8bc4\u8bba\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/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// \u8fd9\u4e2a\u662f\u65b0\u7684\u3002\u6211\u4eec\u60f3\u4ece\u78c1\u76d8\u4e0a\u8bfb\u53d6\u4e00\u4e2a\u4e09\u89d2\u56fe\uff0c\u505a\u8fd9\u4e2a\u7684\u7c7b\u5728\u4e0b\u9762\u7684\u6587\u4ef6\u4e2d\u58f0\u660e\u3002\n\n#include <deal.II/grid/grid_in.h> \n\n// \u6211\u4eec\u5c06\u4f7f\u7528\u4e00\u4e2a\u5706\u5f62\u57df\uff0c\u800c\u63cf\u8ff0\u5176\u8fb9\u754c\u7684\u5bf9\u8c61\u6765\u81ea\u8fd9\u4e2a\u6587\u4ef6\u3002\n\n#include <deal.II/grid/manifold_lib.h> \n\n// \u8fd9\u662fC++ ...\n\n#include <fstream> \n#include <iostream> \n\n// \u6700\u540e\uff0c\u8fd9\u5728\u4ee5\u524d\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u4e86\u3002\n\nusing namespace dealii; \n// @sect3{The <code>Step5</code> class template}  \n\n// \u4e3b\u7c7b\u5927\u90e8\u5206\u548c\u524d\u9762\u7684\u4f8b\u5b50\u4e00\u6837\u3002\u6700\u660e\u663e\u7684\u53d8\u5316\u662f\u5220\u9664\u4e86 <code>make_grid</code> \u51fd\u6570\uff0c\u56e0\u4e3a\u73b0\u5728\u521b\u5efa\u7f51\u683c\u662f\u5728 <code>run</code> \u51fd\u6570\u4e2d\u5b8c\u6210\u7684\uff0c\u5176\u4f59\u529f\u80fd\u90fd\u5728 <code>setup_system</code> \u4e2d\u3002\u9664\u6b64\u4ee5\u5916\uff0c\u4e00\u5207\u90fd\u548c\u4ee5\u524d\u4e00\u6837\u3002\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// \u5728  step-4  \u4e2d\uff0c\u6211\u4eec\u5c55\u793a\u4e86\u5982\u4f55\u4f7f\u7528\u975e\u6052\u5b9a\u8fb9\u754c\u503c\u548c\u53f3\u624b\u8fb9\u3002 \u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u60f3\u5728\u692d\u5706\u7b97\u5b50\u4e2d\u4f7f\u7528\u4e00\u4e2a\u53ef\u53d8\u7cfb\u6570\u6765\u4ee3\u66ff\u3002\u7531\u4e8e\u6211\u4eec\u6709\u4e00\u4e2a\u53ea\u53d6\u51b3\u4e8e\u7a7a\u95f4\u4e2d\u7684\u70b9\u7684\u51fd\u6570\uff0c\u6211\u4eec\u53ef\u4ee5\u505a\u5f97\u66f4\u7b80\u5355\u4e00\u4e9b\uff0c\u4f7f\u7528\u4e00\u4e2a\u666e\u901a\u7684\u51fd\u6570\u800c\u4e0d\u662f\u7ee7\u627f\u81eaFunction\u3002\n\n// \u8fd9\u662f\u5bf9\u5355\u70b9\u7684\u7cfb\u6570\u51fd\u6570\u7684\u5b9e\u73b0\u3002\u5982\u679c\u4e0e\u539f\u70b9\u7684\u8ddd\u79bb\u5c0f\u4e8e0.5\uff0c\u6211\u4eec\u8ba9\u5b83\u8fd4\u56de20\uff0c\u5426\u5219\u8fd4\u56de1\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u548c\u4ee5\u524d\u4e00\u6837\u3002\n\ntemplate <int dim> \nStep5<dim>::Step5() \n  : fe(1) \n  , dof_handler(triangulation) \n{} \n\n//  @sect4{Step5::setup_system}  \n\n// \u8fd9\u662f\u524d\u9762\u4f8b\u5b50\u4e2d\u7684\u51fd\u6570 <code>make_grid</code> \uff0c\u51cf\u53bb\u4e86\u751f\u6210\u7f51\u683c\u7684\u90e8\u5206\u3002\u5176\u4ed6\u4e00\u5207\u90fd\u6ca1\u6709\u53d8\u5316\u3002\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// \u548c\u524d\u9762\u7684\u4f8b\u5b50\u4e00\u6837\uff0c\u8fd9\u4e2a\u51fd\u6570\u5728\u529f\u80fd\u4e0a\u6ca1\u6709\u592a\u5927\u53d8\u5316\uff0c\u4f46\u4ecd\u6709\u4e00\u4e9b\u4f18\u5316\uff0c\u6211\u4eec\u5c06\u5c55\u793a\u8fd9\u4e9b\u4f18\u5316\u3002\u5bf9\u6b64\uff0c\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0c\u5982\u679c\u4f7f\u7528\u9ad8\u6548\u7684\u6c42\u89e3\u5668\uff08\u5982\u9884\u8bbe\u6761\u4ef6\u7684CG\u65b9\u6cd5\uff09\uff0c\u7ec4\u88c5\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u4f1a\u82b1\u8d39\u76f8\u5f53\u7684\u65f6\u95f4\uff0c\u4f60\u5e94\u8be5\u8003\u8651\u5728\u67d0\u4e9b\u5730\u65b9\u4f7f\u7528\u4e00\u5230\u4e24\u4e2a\u4f18\u5316\u3002\n\n// \u8be5\u51fd\u6570\u7684\u524d\u51e0\u90e8\u5206\u4e0e\u4e4b\u524d\u5b8c\u5168\u6ca1\u6709\u53d8\u5316\u3002\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// \u63a5\u4e0b\u6765\u662f\u5bf9\u6240\u6709\u5355\u5143\u7684\u5178\u578b\u5faa\u73af\uff0c\u4ee5\u8ba1\u7b97\u5c40\u90e8\u8d21\u732e\uff0c\u7136\u540e\u5c06\u5b83\u4eec\u8f6c\u79fb\u5230\u5168\u5c40\u77e9\u9635\u548c\u5411\u91cf\u4e2d\u3002\u4e0e step-4 \u76f8\u6bd4\uff0c\u8fd9\u90e8\u5206\u7684\u552f\u4e00\u53d8\u5316\u662f\u6211\u4eec\u5c06\u4f7f\u7528\u4e0a\u9762\u5b9a\u4e49\u7684 <code>coefficient()</code> \u51fd\u6570\u6765\u8ba1\u7b97\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u7684\u7cfb\u6570\u503c\u3002\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// \u6709\u4e86\u8fd9\u6837\u6784\u5efa\u7684\u77e9\u9635\uff0c\u6211\u4eec\u518d\u6b21\u4f7f\u7528\u96f6\u8fb9\u754c\u503c\u3002\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// \u6c42\u89e3\u8fc7\u7a0b\u770b\u8d77\u6765\u53c8\u548c\u524d\u9762\u7684\u4f8b\u5b50\u5dee\u4e0d\u591a\u3002\u7136\u800c\uff0c\u6211\u4eec\u73b0\u5728\u5c06\u4f7f\u7528\u4e00\u4e2a\u9884\u8bbe\u6761\u4ef6\u7684\u5171\u8f6d\u68af\u5ea6\u7b97\u6cd5\u3002\u505a\u51fa\u8fd9\u79cd\u6539\u53d8\u5e76\u4e0d\u96be\u3002\u4e8b\u5b9e\u4e0a\uff0c\u6211\u4eec\u552f\u4e00\u9700\u8981\u6539\u53d8\u7684\u662f\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u4f5c\u4e3a\u9884\u5904\u7406\u7a0b\u5e8f\u7684\u5bf9\u8c61\u3002\u6211\u4eec\u5c06\u4f7f\u7528SSOR\uff08\u5bf9\u79f0\u8fde\u7eed\u8fc7\u5ea6\u653e\u677e\uff09\uff0c\u653e\u677e\u7cfb\u6570\u4e3a1.2\u3002\u4e3a\u6b64\uff0c <code>SparseMatrix</code> \u7c7b\u6709\u4e00\u4e2a\u51fd\u6570\u53ef\u4ee5\u505a\u4e00\u4e2aSSOR\u6b65\u9aa4\uff0c\u6211\u4eec\u9700\u8981\u628a\u8fd9\u4e2a\u51fd\u6570\u7684\u5730\u5740\u548c\u5b83\u5e94\u8be5\u4f5c\u7528\u7684\u77e9\u9635\uff08\u4e5f\u5c31\u662f\u8981\u53cd\u8f6c\u7684\u77e9\u9635\uff09\u4ee5\u53ca\u677e\u5f1b\u56e0\u5b50\u6253\u5305\u6210\u4e00\u4e2a\u5bf9\u8c61\u3002 <code>PreconditionSSOR</code> \u7c7b\u4e3a\u6211\u4eec\u505a\u4e86\u8fd9\u4e2a\u3002(  <code>PreconditionSSOR</code>  \u7c7b\u9700\u8981\u4e00\u4e2a\u6a21\u677f\u53c2\u6570\uff0c\u8868\u793a\u5b83\u5e94\u8be5\u5de5\u4f5c\u7684\u77e9\u9635\u7c7b\u578b\u3002\u9ed8\u8ba4\u503c\u662f <code>SparseMatrix@<double@></code> \uff0c\u8fd9\u6b63\u662f\u6211\u4eec\u5728\u8fd9\u91cc\u9700\u8981\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u53ea\u9700\u575a\u6301\u4f7f\u7528\u9ed8\u8ba4\u503c\uff0c\u4e0d\u5728\u89d2\u62ec\u53f7\u4e2d\u6307\u5b9a\u4efb\u4f55\u4e1c\u897f\u3002)\n\n// \u8bf7\u6ce8\u610f\uff0c\u5728\u76ee\u524d\u7684\u60c5\u51b5\u4e0b\uff0cSSOR\u7684\u8868\u73b0\u5e76\u4e0d\u6bd4\u5176\u4ed6\u5927\u591a\u6570\u9884\u5904\u7406\u7a0b\u5e8f\u597d\u591a\u5c11\uff08\u5c3d\u7ba1\u6bd4\u6ca1\u6709\u9884\u5904\u7406\u597d\uff09\u3002\u5728\u4e0b\u4e00\u4e2a\u6559\u7a0b\u7a0b\u5e8f  step-6  \u7684\u7ed3\u679c\u90e8\u5206\uff0c\u5c06\u5bf9\u4e0d\u540c\u7684\u9884\u5904\u7406\u8fdb\u884c\u7b80\u8981\u6bd4\u8f83\u3002\n\n// \u6709\u4e86\u8fd9\u4e2a\uff0c\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\u5c31\u5f88\u7b80\u5355\u4e86\uff1a\u6211\u4eec\u73b0\u5728\u4f7f\u7528\u6211\u4eec\u58f0\u660e\u7684\u9884\u5904\u7406\u7a0b\u5e8f\uff0c\u800c\u4e0d\u662f\u4e4b\u524d\u521b\u5efa\u7684 <code>PreconditionIdentity</code> \u5bf9\u8c61\uff0cCG\u6c42\u89e3\u5668\u5c06\u4e3a\u6211\u4eec\u5b8c\u6210\u5176\u4f59\u7684\u5de5\u4f5c\u3002\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// \u5c06\u8f93\u51fa\u5199\u5165\u6587\u4ef6\u7684\u65b9\u6cd5\u4e0e\u4e0a\u4e00\u4e2a\u6559\u7a0b\u4e2d\u7684\u57fa\u672c\u76f8\u540c\u3002\u552f\u4e00\u4e0d\u540c\u7684\u662f\uff0c\u6211\u4eec\u73b0\u5728\u9700\u8981\u4e3a\u6bcf\u4e2a\u7ec6\u5316\u5468\u671f\u6784\u5efa\u4e00\u4e2a\u4e0d\u540c\u7684\u6587\u4ef6\u540d\u3002\n\n// \u8fd9\u4e2a\u51fd\u6570\u4ee5VTU\u683c\u5f0f\u5199\u5165\u8f93\u51fa\uff0c\u8fd9\u662fVTK\u683c\u5f0f\u7684\u4e00\u4e2a\u53d8\u79cd\uff0c\u56e0\u4e3a\u5b83\u538b\u7f29\u4e86\u6570\u636e\uff0c\u6240\u4ee5\u9700\u8981\u66f4\u5c11\u7684\u78c1\u76d8\u7a7a\u95f4\u3002\u5f53\u7136\uff0c\u5982\u679c\u4f60\u5e0c\u671b\u4f7f\u7528\u4e00\u4e2a\u4e0d\u7406\u89e3VTK\u6216VTU\u7684\u53ef\u89c6\u5316\u7a0b\u5e8f\uff0cDataOut\u7c7b\u8fd8\u652f\u6301\u8bb8\u591a\u5176\u4ed6\u683c\u5f0f\u3002\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// \u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\uff0c\u5012\u6570\u7b2c\u4e8c\u4ef6\u4e8b\u662f\u5bf9 <code>run()</code> \u51fd\u6570\u7684\u5b9a\u4e49\u3002\u4e0e\u4e4b\u524d\u7684\u7a0b\u5e8f\u4e0d\u540c\uff0c\u6211\u4eec\u5c06\u5728\u4e00\u4e2a\u7f51\u683c\u5e8f\u5217\u4e0a\u8fdb\u884c\u8ba1\u7b97\uff0c\u5728\u6bcf\u6b21\u8fed\u4ee3\u540e\u90fd\u4f1a\u8fdb\u884c\u5168\u5c40\u7ec6\u5316\u3002\u56e0\u6b64\uff0c\u8be5\u51fd\u6570\u75316\u4e2a\u5468\u671f\u7684\u5faa\u73af\u7ec4\u6210\u3002\u5728\u6bcf\u4e2a\u5faa\u73af\u4e2d\uff0c\u6211\u4eec\u9996\u5148\u6253\u5370\u5faa\u73af\u7f16\u53f7\uff0c\u7136\u540e\u51b3\u5b9a\u5982\u4f55\u5904\u7406\u7f51\u683c\u3002\u5982\u679c\u8fd9\u4e0d\u662f\u7b2c\u4e00\u4e2a\u5468\u671f\uff0c\u6211\u4eec\u5c31\u7b80\u5355\u5730\u5bf9\u73b0\u6709\u7684\u7f51\u683c\u8fdb\u884c\u4e00\u6b21\u5168\u5c40\u7cbe\u70bc\u3002\u7136\u800c\uff0c\u5728\u8fd0\u884c\u8fd9\u4e9b\u5faa\u73af\u4e4b\u524d\uff0c\u6211\u4eec\u5fc5\u987b\u5148\u751f\u6210\u4e00\u4e2a\u7f51\u683c\u3002\n\n// \u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u5df2\u7ecf\u4f7f\u7528\u4e86 <code>GridGenerator</code> \u7c7b\u4e2d\u7684\u4e00\u4e9b\u51fd\u6570\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u60f3\u4ece\u4e00\u4e2a\u5b58\u50a8\u5355\u5143\u7684\u6587\u4ef6\u4e2d\u8bfb\u53d6\u7f51\u683c\uff0c\u8fd9\u4e2a\u6587\u4ef6\u53ef\u80fd\u6765\u81ea\u5176\u4ed6\u4eba\uff0c\u4e5f\u53ef\u80fd\u662f\u4e00\u4e2a\u7f51\u683c\u751f\u6210\u5de5\u5177\u7684\u4ea7\u7269\u3002\n\n// \u4e3a\u4e86\u4ece\u6587\u4ef6\u4e2d\u8bfb\u53d6\u7f51\u683c\uff0c\u6211\u4eec\u751f\u6210\u4e00\u4e2a\u6570\u636e\u7c7b\u578b\u4e3aGridIn\u7684\u5bf9\u8c61\uff0c\u5e76\u5c06\u4e09\u89d2\u5256\u5206\u4e0e\u4e4b\u76f8\u5173\u8054\uff08\u4e5f\u5c31\u662f\u8bf4\uff0c\u5f53\u6211\u4eec\u8981\u6c42\u5b83\u8bfb\u53d6\u6587\u4ef6\u65f6\uff0c\u6211\u4eec\u544a\u8bc9\u5b83\u8981\u586b\u5145\u6211\u4eec\u7684\u4e09\u89d2\u5256\u5206\u5bf9\u8c61\uff09\u3002\u7136\u540e\u6211\u4eec\u6253\u5f00\u76f8\u5e94\u7684\u6587\u4ef6\uff0c\u7528\u6587\u4ef6\u4e2d\u7684\u6570\u636e\u521d\u59cb\u5316\u4e09\u89d2\u5256\u5206\u3002\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// \u6211\u4eec\u73b0\u5728\u60f3\u8bfb\u53d6\u8be5\u6587\u4ef6\u3002\u4f46\u662f\uff0c\u8f93\u5165\u6587\u4ef6\u53ea\u9488\u5bf9\u4e8c\u7ef4\u4e09\u89d2\u56fe\uff0c\u800c\u8fd9\u4e2a\u51fd\u6570\u662f\u4e00\u4e2a\u4efb\u610f\u7ef4\u5ea6\u7684\u6a21\u677f\u3002\u7531\u4e8e\u8fd9\u53ea\u662f\u4e00\u4e2a\u6f14\u793a\u7a0b\u5e8f\uff0c\u6211\u4eec\u4e0d\u4f1a\u4e3a\u4e0d\u540c\u7684\u7ef4\u5ea6\u4f7f\u7528\u4e0d\u540c\u7684\u8f93\u5165\u6587\u4ef6\uff0c\u800c\u662f\u5728\u4e0d\u5728\u4e8c\u7ef4\u7684\u60c5\u51b5\u4e0b\u8fc5\u901f\u6740\u6b7b\u6574\u4e2a\u7a0b\u5e8f\u3002\u5f53\u7136\uff0c\u7531\u4e8e\u4e0b\u9762\u7684\u4e3b\u51fd\u6570\u5047\u5b9a\u6211\u4eec\u662f\u5728\u4e8c\u7ef4\u7a7a\u95f4\u5de5\u4f5c\uff0c\u6211\u4eec\u53ef\u4ee5\u8df3\u8fc7\u8fd9\u4e2a\u68c0\u67e5\uff0c\u5728\u8fd9\u4e2a\u7248\u672c\u7684\u7a0b\u5e8f\u4e2d\uff0c\u4e0d\u4f1a\u6709\u4efb\u4f55\u4e0d\u826f\u5f71\u54cd\u3002\n\n// \u4e8b\u5b9e\u8bc1\u660e\uff0c90%\u4ee5\u4e0a\u7684\u7f16\u7a0b\u9519\u8bef\u90fd\u662f\u65e0\u6548\u7684\u51fd\u6570\u53c2\u6570\uff0c\u5982\u65e0\u6548\u7684\u6570\u7ec4\u5927\u5c0f\u7b49\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u6574\u4e2adeal.II\u4e2d\u5927\u91cf\u4f7f\u7528\u65ad\u8a00\u6765\u6355\u6349\u6b64\u7c7b\u9519\u8bef\u3002\u4e3a\u6b64\uff0c <code>Assert</code> \u5b8f\u662f\u4e00\u4e2a\u5f88\u597d\u7684\u9009\u62e9\uff0c\u56e0\u4e3a\u5b83\u786e\u4fdd\u4f5c\u4e3a\u7b2c\u4e00\u4e2a\u53c2\u6570\u7684\u6761\u4ef6\u662f\u6709\u6548\u7684\uff0c\u5982\u679c\u4e0d\u662f\uff0c\u5c31\u629b\u51fa\u4e00\u4e2a\u5f02\u5e38\uff08\u5b83\u7684\u7b2c\u4e8c\u4e2a\u53c2\u6570\uff09\uff0c\u901a\u5e38\u4f1a\u7ec8\u6b62\u7a0b\u5e8f\uff0c\u5e76\u7ed9\u51fa\u9519\u8bef\u53d1\u751f\u7684\u4f4d\u7f6e\u548c\u539f\u56e0\u7684\u4fe1\u606f\u3002\u5173\u4e8e @p Assert \u5b8f\u7684\u5177\u4f53\u4f5c\u7528\uff0c\u53ef\u4ee5\u5728 @ref Exceptions \"\u5f02\u5e38\u6587\u6863\u6a21\u5757 \"\u4e2d\u627e\u5230\u66f4\u8be6\u7ec6\u7684\u8ba8\u8bba\uff09\u3002\u8fd9\u901a\u5e38\u4f1a\u5927\u5927\u51cf\u5c11\u53d1\u73b0\u7f16\u7a0b\u9519\u8bef\u7684\u65f6\u95f4\uff0c\u6211\u4eec\u53d1\u73b0\u65ad\u8a00\u662f\u5feb\u901f\u7f16\u7a0b\u7684\u5b9d\u8d35\u624b\u6bb5\u3002\n\n// \u53e6\u4e00\u65b9\u9762\uff0c\u5982\u679c\u4f60\u60f3\u505a\u5927\u7684\u8ba1\u7b97\uff0c\u6240\u6709\u8fd9\u4e9b\u68c0\u67e5\uff08\u76ee\u524d\u5e93\u4e2d\u6709\u8d85\u8fc710000\u4e2a\uff09\u4e0d\u5e94\u8be5\u4f7f\u7a0b\u5e8f\u592a\u6162\u3002\u4e3a\u6b64\uff0c <code>Assert</code> \u5b8f\u53ea\u5728\u8c03\u8bd5\u6a21\u5f0f\u4e0b\u4f7f\u7528\uff0c\u5982\u679c\u5728\u4f18\u5316\u6a21\u5f0f\u4e0b\u5219\u6269\u5c55\u4e3a\u96f6\u3002\u56e0\u6b64\uff0c\u5f53\u4f60\u5728\u5c0f\u95ee\u9898\u4e0a\u6d4b\u8bd5\u4f60\u7684\u7a0b\u5e8f\u5e76\u8fdb\u884c\u8c03\u8bd5\u65f6\uff0c\u65ad\u8a00\u4f1a\u544a\u8bc9\u4f60\u95ee\u9898\u51fa\u5728\u54ea\u91cc\u3002\u4e00\u65e6\u4f60\u7684\u7a0b\u5e8f\u7a33\u5b9a\u4e86\uff0c\u4f60\u53ef\u4ee5\u5173\u95ed\u8c03\u8bd5\uff0c\u7a0b\u5e8f\u5c06\u5728\u6ca1\u6709\u65ad\u8a00\u7684\u60c5\u51b5\u4e0b\u4ee5\u6700\u5927\u901f\u5ea6\u8fd0\u884c\u4f60\u7684\u5b9e\u9645\u8ba1\u7b97\u3002\u66f4\u51c6\u786e\u5730\u8bf4\uff1a\u901a\u8fc7\u5728\u4f18\u5316\u6a21\u5f0f\u4e0b\u7f16\u8bd1\u4f60\u7684\u7a0b\u5e8f\uff0c\u5173\u95ed\u5e93\u4e2d\u7684\u6240\u6709\u68c0\u67e5\uff08\u8fd9\u4e9b\u68c0\u67e5\u53ef\u4ee5\u9632\u6b62\u4f60\u7528\u9519\u8bef\u7684\u53c2\u6570\u8c03\u7528\u51fd\u6570\uff0c\u4ece\u6570\u7ec4\u4e2d\u8d70\u51fa\u6765\uff0c\u7b49\u7b49\uff09\uff0c\u901a\u5e38\u53ef\u4ee5\u4f7f\u7a0b\u5e8f\u7684\u8fd0\u884c\u901f\u5ea6\u63d0\u9ad8\u56db\u500d\u5de6\u53f3\u3002\u5373\u4f7f\u4f18\u5316\u540e\u7684\u7a0b\u5e8f\u6027\u80fd\u66f4\u9ad8\uff0c\u6211\u4eec\u4ecd\u7136\u5efa\u8bae\u5728\u8c03\u8bd5\u6a21\u5f0f\u4e0b\u5f00\u53d1\uff0c\u56e0\u4e3a\u5b83\u5141\u8bb8\u5e93\u81ea\u52a8\u53d1\u73b0\u8bb8\u591a\u5e38\u89c1\u7684\u7f16\u7a0b\u9519\u8bef\u3002\u5bf9\u4e8e\u90a3\u4e9b\u60f3\u5c1d\u8bd5\u7684\u4eba\u6765\u8bf4\u3002\u4ece\u8c03\u8bd5\u6a21\u5f0f\u5207\u6362\u5230\u4f18\u5316\u6a21\u5f0f\u7684\u65b9\u6cd5\u662f\u7528<code>make release</code>\u547d\u4ee4\u91cd\u65b0\u7f16\u8bd1\u4f60\u7684\u7a0b\u5e8f\u3002\u73b0\u5728 <code>make</code> \u7a0b\u5e8f\u7684\u8f93\u51fa\u5e94\u8be5\u5411\u4f60\u8868\u660e\uff0c\u8be5\u7a0b\u5e8f\u73b0\u5728\u662f\u4ee5\u4f18\u5316\u6a21\u5f0f\u7f16\u8bd1\u7684\uff0c\u4ee5\u540e\u4e5f\u4f1a\u88ab\u94fe\u63a5\u5230\u5df2\u7ecf\u4e3a\u4f18\u5316\u6a21\u5f0f\u7f16\u8bd1\u7684\u5e93\u3002\u4e3a\u4e86\u5207\u6362\u56de\u8c03\u8bd5\u6a21\u5f0f\uff0c\u53ea\u9700\u7528  <code>make debug</code>  \u547d\u4ee4\u91cd\u65b0\u7f16\u8bd1\u3002\n\n  Assert(dim == 2, ExcInternalError()); \n\n// ExcInternalError\u662f\u4e00\u4e2a\u5168\u5c40\u5b9a\u4e49\u7684\u5f02\u5e38\uff0c\u6bcf\u5f53\u51fa\u73b0\u4e25\u91cd\u7684\u9519\u8bef\u65f6\u5c31\u4f1a\u629b\u51fa\u3002\u901a\u5e38\uff0c\u4eba\u4eec\u5e0c\u671b\u4f7f\u7528\u66f4\u5177\u4f53\u7684\u5f02\u5e38\uff0c\u7279\u522b\u662f\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u5982\u679c <code>dim</code> \u4e0d\u7b49\u4e8e2\uff0c\u4eba\u4eec\u5f53\u7136\u4f1a\u5c1d\u8bd5\u505a\u5176\u4ed6\u4e8b\u60c5\uff0c\u4f8b\u5982\u4f7f\u7528\u5e93\u51fd\u6570\u521b\u5efa\u4e00\u4e2a\u7f51\u683c\u3002\u7ec8\u6b62\u7a0b\u5e8f\u901a\u5e38\u4e0d\u662f\u4e00\u4e2a\u597d\u4e3b\u610f\uff0c\u65ad\u8a00\u5b9e\u9645\u4e0a\u53ea\u5e94\u8be5\u7528\u4e8e\u4e0d\u5e94\u8be5\u53d1\u751f\u7684\u7279\u6b8a\u60c5\u51b5\uff0c\u4f46\u7531\u4e8e\u7a0b\u5e8f\u5458\u3001\u7528\u6237\u6216\u5176\u4ed6\u4eba\u7684\u611a\u8822\u800c\u53ef\u80fd\u53d1\u751f\u3002\u4e0a\u9762\u7684\u60c5\u51b5\u5e76\u4e0d\u662f\u5bf9Assert\u7684\u5de7\u5999\u4f7f\u7528\uff0c\u4f46\u662f\u518d\u6b21\u5f3a\u8c03\uff1a\u8fd9\u662f\u4e00\u4e2a\u6559\u7a0b\uff0c\u4e5f\u8bb8\u503c\u5f97\u5c55\u793a\u4e00\u4e0b\u4ec0\u4e48\u662f\u4e0d\u5e94\u8be5\u505a\u7684\uff0c\u6bd5\u7adf\u3002\n\n// \u6240\u4ee5\uff0c\u5982\u679c\u6211\u4eec\u901a\u8fc7\u4e86\u65ad\u8a00\uff0c\u6211\u4eec\u5c31\u77e5\u9053dim==2\uff0c\u73b0\u5728\u6211\u4eec\u5c31\u53ef\u4ee5\u771f\u6b63\u5730\u8bfb\u53d6\u7f51\u683c\u3002\u5b83\u7684\u683c\u5f0f\u662fUCD\uff08\u975e\u7ed3\u6784\u5316\u5355\u5143\u6570\u636e\uff09\uff08\u5c3d\u7ba1\u60ef\u4f8b\u662f\u4f7f\u7528UCD\u6587\u4ef6\u7684\u540e\u7f00 <code>inp</code> \uff09\u3002\n\n  grid_in.read_ucd(input_file); \n\n// \u5982\u679c\u4f60\u60f3\u4f7f\u7528\u5176\u4ed6\u8f93\u5165\u683c\u5f0f\uff0c\u4f60\u5fc5\u987b\u4f7f\u7528\u5176\u4ed6 <code>grid_in.read_xxx</code> \u51fd\u6570\u4e4b\u4e00\u3002(\u53c2\u89c1  <code>GridIn</code>  \u7c7b\u7684\u6587\u6863\uff0c\u4ee5\u4e86\u89e3\u76ee\u524d\u652f\u6301\u54ea\u4e9b\u8f93\u5165\u683c\u5f0f)\u3002\n\n// \u6587\u4ef6\u4e2d\u7684\u7f51\u683c\u63cf\u8ff0\u4e86\u4e00\u4e2a\u5706\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5fc5\u987b\u4f7f\u7528\u4e00\u4e2a\u6d41\u5f62\u5bf9\u8c61\uff0c\u544a\u8bc9\u4e09\u89d2\u8ba1\u7b97\u5728\u7ec6\u5316\u7f51\u683c\u65f6\u5c06\u8fb9\u754c\u4e0a\u7684\u65b0\u70b9\u653e\u5728\u54ea\u91cc\u3002\u4e0e step-1 \u4e0d\u540c\u7684\u662f\uff0c\u7531\u4e8eGridIn\u4e0d\u77e5\u9053\u57df\u7684\u8fb9\u754c\u662f\u5706\u5f62\u7684\uff08\u4e0e GridGenerator::hyper_shell) \u4e0d\u540c\u7684\u662f\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u521b\u5efa\u4e09\u89d2\u7f51\u683c\u540e\u660e\u786e\u5730\u5c06\u6d41\u5f62\u9644\u52a0\u5230\u8fb9\u754c\u4e0a\uff0c\u4ee5\u4fbf\u5728\u7ec6\u5316\u7f51\u683c\u65f6\u83b7\u5f97\u6b63\u786e\u7684\u7ed3\u679c\u3002\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// \u73b0\u5728\u6211\u4eec\u6709\u4e86\u4e00\u4e2a\u786e\u5b9a\u7684\u7f51\u683c\uff0c\u6211\u4eec\u5199\u4e00\u4e9b\u8f93\u51fa\uff0c\u505a\u6240\u6709\u6211\u4eec\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u5df2\u7ecf\u770b\u5230\u7684\u4e8b\u60c5\u3002\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// \u4e3b\u51fd\u6570\u770b\u8d77\u6765\u548c\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u7684\u51fd\u6570\u5dee\u4e0d\u591a\uff0c\u6240\u4ee5\u6211\u4eec\u5c31\u4e0d\u8fdb\u4e00\u6b65\u8bc4\u8bba\u4e86\u3002\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": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file Rotation.hpp\n/// \\brief Header file for a rotation matrix class.\n/// \\details Light weight rotation class, intended to be fast, and not to provide\n///          unnecessary functionality.\n///\n/// \\author Sean Anderson\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n///\n/// A note on EIGEN_MAKE_ALIGNED_OPERATOR_NEW (Sean Anderson, as of May 23, 2013)\n/// (also see http://eigen.tuxfamily.org/dox-devel/group__TopicStructHavingEigenMembers.html)\n///\n/// Fortunately, Eigen::Matrix3d and Eigen::Vector3d are NOT 16-byte vectorizable,\n/// therefore this class should not require alignment, and can be used normally in STL.\n///\n/// To inform others of the issue, classes that include *fixed-size vectorizable Eigen types*,\n/// see http://eigen.tuxfamily.org/dox-devel/group__TopicFixedSizeVectorizable.html,\n/// must include the above macro! Furthermore, special considerations must be taken if\n/// you want to use them in STL containers, such as std::vector or std::map.\n/// The macro overloads the dynamic \"new\" operator so that it generates\n/// 16-byte-aligned pointers, this MUST be in the public section of the header!\n///\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef LGM_ROTATION_HPP\n#define LGM_ROTATION_HPP\n\n#include <Eigen/Dense>\n\nnamespace lgmath {\nnamespace so3 {\n\nclass Rotation\n{\n public:\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Default constructor\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Rotation();\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Copy constructor.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Rotation(const Rotation&) = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Move constructor.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Rotation(Rotation&& C) = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Copy constructor (from Eigen)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Rotation(const Eigen::Matrix3d& C);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor. The rotation will be C_ba = vec2rot(aaxis_ab)\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  // explicit because we want operator*(Eigen::Vector3d) and operator*(this) --- ambiguous\n  explicit Rotation(const Eigen::Vector3d& aaxis_ab, unsigned int numTerms = 0);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Constructor. The rotation will be C_ba = vec2rot(aaxis_ab), aaxis_ab must be 3x1\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  // explicit because we want operator*(Eigen::Vector3d) and operator*(this) --- ambiguous\n  explicit Rotation(const Eigen::VectorXd& aaxis_ab);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Destructor.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  ~Rotation() = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Copy assignment operator.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Rotation& operator=(const Rotation&) = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Move assignment operator.  Manually implemented as Eigen doesn't support moving.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Rotation& operator=(Rotation&& C) = default;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Gets the underlying rotation matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  const Eigen::Matrix3d& matrix() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get the corresponding Lie algebra (axis-angle) using the logarithmic map\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::Vector3d vec() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Get the inverse (transpose) matrix\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Rotation inverse() const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Reproject the rotation matrix back onto SO(3). Setting force to false triggers\n  ///        a conditional reproject that only happens if the determinant is of the rotation\n  ///        matrix is poor; this is more efficient than always performing it.\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  void reproject(bool force = true);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief In-place right-hand side multiply C_rhs\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Rotation& operator*=(const Rotation& C_rhs);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Right-hand side multiply C_rhs\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Rotation operator*(const Rotation& C_rhs) const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief In-place right-hand side multiply this matrix by the inverse of C_rhs\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Rotation& operator/=(const Rotation& C_rhs);\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Right-hand side multiply this matrix by the inverse of C_rhs\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Rotation operator/(const Rotation& C_rhs) const;\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// \\brief Right-hand side multiply this matrix by the point vector p_a\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::Vector3d operator*(const Eigen::Ref<const Eigen::Vector3d>& p_a) const;\n\n private:\n\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  /// Rotation matrix from a to b\n  //////////////////////////////////////////////////////////////////////////////////////////////\n  Eigen::Matrix3d C_ba_;\n\n};\n\n} // so3\n} // lgmath\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief print transformation\n//////////////////////////////////////////////////////////////////////////////////////////////\nstd::ostream& operator<<(std::ostream& out, const lgmath::so3::Rotation& T);\n\n#endif // LGM_ROTATION_HPP\n", "meta": {"hexsha": "942b16229534d27ab3ee4981ecc5924f35f11c38", "size": 7951, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lgmath/so3/Rotation.hpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "include/lgmath/so3/Rotation.hpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "include/lgmath/so3/Rotation.hpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 52.6556291391, "max_line_length": 96, "alphanum_fraction": 0.3356810464, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.565393678295053}}
{"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": "#define BOOST_TEST_MODULE example\n#include <boost/test/included/unit_test.hpp>\n\n//____________________________________________________________________________//\n\n#include <cmath>\n\nBOOST_AUTO_TEST_CASE( test )\n{\n    double res = std::sin( 45. ); // sin 45 radians is actually ~ 0.85, sin 45 degrees is ~0.707\n\n    BOOST_WARN_MESSAGE( res < 0.71, \"sin(45){\" << res << \"} is > 0.71. Arg is not in radian?\" );\n}\n\n//____________________________________________________________________________//\n", "meta": {"hexsha": "d6c9bd4114bccba977dc48bc5af52f1bda0c6f11", "size": 490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/test/doc/src/examples/example38.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "libs/test/doc/src/examples/example38.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "libs/test/doc/src/examples/example38.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 30.625, "max_line_length": 96, "alphanum_fraction": 0.7489795918, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.5653936597512607}}
{"text": "#pragma once\n#include <iostream>\n#include <boost/math/common_factor_rt.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <chrono>\n\n#include \"globals.hpp\"\n#include \"gcd_algorithms.hpp\"\n\n//the Test_Suite namespace contains functions that aid in\n//verifying the correctness of gcd algorithms as well as\n//testing the performance of generic gcd routines\nnamespace Test_Suite{\n\t\n\t//these functions make sure that the gcd algorithms are correct\n\ttemplate <typename IntegerType=TestType> bool Check_Algorithm_Validity(IntegerType(*fun)(IntegerType, IntegerType));\n\ttemplate <typename IntegerType> bool Check_Answer_Validity(IntegerType num1, IntegerType num2, IntegerType answer);\n\t\n\t//utility\n\ttemplate <typename IntegerType=TestType> boost::random::uniform_int_distribution<IntegerType> Get_Specified_Bit_Length_Distribution(int bit_length);\n\t\n};\n\n//these functions make sure that the gcd algorithms are correct\ntemplate <typename IntegerType> bool Test_Suite::Check_Algorithm_Validity(IntegerType(*fun)(IntegerType, IntegerType)){\n\tint fail_rate=0;\n\t\n\tIntegerType a;\n\tIntegerType b;\n\t\n\t//test some edge cases\n\ta=1; b=1;\n\tfail_rate+= !Check_Answer_Validity(a,b,fun(a,b));\n\t\n\ta=1; b=0;\n\tfail_rate+= !Check_Answer_Validity(a,b,fun(a,b));\n\t\n\ta=0; b=1;\n\tfail_rate+= !Check_Answer_Validity(a,b,fun(a,b));\n\t\n\ta=0; b=0;\n\tfail_rate+= !Check_Answer_Validity(a,b,fun(a,b));\n\t\n\t\n\t//test different sized bit numbers\n\tstatic boost::random::mt19937 gen(std::time(0));\n\tboost::random::uniform_int_distribution<IntegerType> dist;\n\tfor (int i = 0; i < constant::number_of_tests_per_bit_length; ++i){\n\t\t\n\t\t//6 bit test\n\t\tdist = Get_Specified_Bit_Length_Distribution(6);\n\t\ta=dist(gen); b=dist(gen);\n\t\tfail_rate+= !Check_Answer_Validity(a,b,fun(a,b));\n\t\t\n\t\t//14 bit test\n\t\tdist = Get_Specified_Bit_Length_Distribution(14);\n\t\ta=dist(gen); b=dist(gen);\n\t\tfail_rate+= !Check_Answer_Validity(a,b,fun(a,b));\n\n\t\t//22 bit test\n\t\tdist = Get_Specified_Bit_Length_Distribution(22);\n\t\ta=dist(gen); b=dist(gen);\n\t\tfail_rate+= !Check_Answer_Validity(a,b,fun(a,b));\n\t\t\n\t\t//30 bit test\n\t\tdist = Get_Specified_Bit_Length_Distribution(30);\n\t\ta=dist(gen); b=dist(gen);\n\t\tfail_rate+= !Check_Answer_Validity(a,b,fun(a,b));\n\t}\n\t\n\t\n\t\n\tbool failed = false;\n\tif (fail_rate > 0){failed = true;}\n\treturn failed;\n}\ntemplate <typename IntegerType> bool Test_Suite::Check_Answer_Validity(IntegerType a, IntegerType b, IntegerType d){\n\t\n\t//This is mostly bennett's implementation, but I added a bit to check for possible issues\n\tusing namespace std;\n\t\n\t//avoid a floating point error\n\tif (a == 0 && b == 0){\n\t\tif (d == 0){\n\t\t\treturn true;\n\t\t}\n\t\telse{\n\t\t\tstd::cerr << \"gcd(0,0) should be 0\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tIntegerType r1, r2, d1, d2, p1, p2;\n\t\n\tr1 = a%d;\n\tr2 = b%d;\n\td1 = a/d;\n\td2 = b/d;\n\tp1 = d1*d;\n\tp2 = d2*d;\n\n\tif (r1 != 0) {\n\t\tcerr<< \"Error \" << a << \"/\" << d << \" = \" << d1 << \" R \" << r1 << endl;\n\t\tcerr << \"The remainder should be 0  but is \" << r1 << endl;\n\n\t\treturn false;\n\t}\n\n\tif (r2 != 0) {\n\t\tcerr<< \"Error \" << b << \"/\" << d << \" = \" << d2 << \" R \" << r2 << endl;\n\t\tcerr << \"The remainder should be 0  but is \" << r2 << endl;\n\n\t\treturn false;\n\t}\n\n\tif (p1 != a) {\n\t\tcerr << \"Error, the proposed GCD is \" << d << \" but (\" \n\t\t<< a << \"/\" << d << \") * \" << d << \"  = \" <<  p1 << endl;\n\t\tcerr << \"    and \" << p1 << \" !=  \" << a << endl;\n\t\treturn false;\n\t}\n\t\n\tif (p2 != b) {\n\t\tcerr << \"Error, the proposed GCD is \" << d << \" but (\" \n\t\t<< b << \"/\" << d << \") * \" << d << \"  = \" <<  p2 << endl;\n\t\tcerr << \"    and \" << p2 << \" !=  \" << b << endl;\n\t\treturn false;\n\t}\n\t\n\t//I also want to make sure that I'm getting the same answer as boost\n\tIntegerType boost_answer = boost::math::gcd(a,b);\n\tif (d != boost_answer){\n\t\tcerr << \"the answer is \" << d << \", but boost got \" << boost_answer << endl;\n\t\treturn false;\n\t}\n\t\n\treturn true;\n}\n\n//utility\ntemplate <typename IntegerType> boost::random::uniform_int_distribution<IntegerType> Test_Suite::Get_Specified_Bit_Length_Distribution(int bit_length){\n\tIntegerType min = pow(2,bit_length-1);\n\tIntegerType max = pow(2,bit_length)-1;\n\treturn boost::random::uniform_int_distribution<IntegerType>(min,max);\n}\n\n\n\n\n", "meta": {"hexsha": "ba78c6eef692245b86eaadb767aee190f3d1ab20", "size": 4187, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/code/scratch/old_repos/edinboro/CSCI-385/GCD-Test-Suite/src/code/test_suite.hpp", "max_stars_repo_name": "luxe/CodeLang-compiler", "max_stars_repo_head_hexsha": "78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T07:43:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T13:12:32.000Z", "max_issues_repo_path": "source/code/scratch/old_repos/edinboro/CSCI-385/GCD-Test-Suite/src/code/test_suite.hpp", "max_issues_repo_name": "luxe/CodeLang-compiler", "max_issues_repo_head_hexsha": "78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 371.0, "max_issues_repo_issues_event_min_datetime": "2019-05-16T15:23:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-04T15:45:27.000Z", "max_forks_repo_path": "source/code/scratch/old_repos/edinboro/CSCI-385/GCD-Test-Suite/src/code/test_suite.hpp", "max_forks_repo_name": "UniLang/compiler", "max_forks_repo_head_hexsha": "c338ee92994600af801033a37dfb2f1a0c9ca897", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-08-22T17:37:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T07:15:32.000Z", "avg_line_length": 27.7284768212, "max_line_length": 151, "alphanum_fraction": 0.6598996895, "num_tokens": 1257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.5653936560441313}}
{"text": "#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <pcl/visualization/cloud_viewer.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/filters/voxel_grid.h>\n#include <Eigen/Dense>\n#include <math.h>\n#include <algorithm>\n\n/**\n *  \u6700\u521d\u7684lineTracking\n * \n * \n*/\n\nusing namespace std;\n\nconst float fx = 760.4862674784594;\nconst float fy = 761.4971958529285;\nconst float cx = 631.6715834996345;\nconst float cy = 329.3054436037627;\nconst int imgWidth = 1280;\nconst int imgHeight = 720;\nconst float y = 129.5585;\n\n\ninline void getXY(int u,int v,cv::Point2f& xy){\n    xy.x = fy * y/(v-cy);\n    xy.y = -(u-cx)*xy.x/fx;\n}\n\nvoid getLineworld(vector<cv::Point2f>& vIn,vector<cv::Point2f>& vOut){\n    for(vector<cv::Point2f>::iterator in = vIn.begin();in!=vIn.end();++in){\n        cv::Point2f out;\n//        out.x = fy*y/(in->y-cy);\n//        out.y = -(in->x-cx)*out.x/fx;\n//        vOut.push_back(out);\n        getXY(in->x,in->y,out);\n        vOut.push_back(out);\n\n    }\n}\n\nvoid image2PointCloud(vector<cv::Point2f> uv,pcl::PointCloud<pcl::PointXYZ>::Ptr cloud){\n    int lastX =  fy * y/(uv[0].y-cy);\n    int lastY = -(uv[0].x-cx)*lastX/fx;;\n    for(auto p2:uv){\n        pcl::PointXYZ point;\n        // in camera frame  y=const z=fy * y/(v-cy) x=(u-cx)*z/fx\n        // but in world frame z = y x = z y = -x\n        point.x = fy * y/(p2.y-cy);\n        point.y = -(p2.x-cx)*point.x/fx;\n        point.z = 2;\n        if(abs(point.y - lastY)>10)\n            continue;\n        cloud->push_back(point);\n        lastY = point.y;\n    }\n}\n\nenum LineState{Right=0,Left,None,Both};\n\nEigen::Vector3f fixCurve(pcl::PointCloud<pcl::PointXYZ>::Ptr xy){\n    int size = xy->size();\n    Eigen::Matrix<float,Eigen::Dynamic,3> Y;\n    Eigen::Matrix<float,Eigen::Dynamic,1> X;\n    for(int i = 0;i<xy->points.size();++i){\n        Y(i,0) = std::pow(xy->points[i].y,2);Y(i,1) = xy->points[i].y;Y(i,2) = 1;\n        X(i,0) = xy->points[i].x;\n    }\n    return (X.transpose()*X).inverse()*X.transpose()*Y;\n}\n//void calculateCurve(pcl::PointCloud<pcl::PointXYZ>::Ptr xyLeft,pcl::PointCloud<pcl::PointXYZ>::Ptr xyRight,LineState flag){\n//    Eigen::Vector3f params;\n//    if()\n//}\n\nfloat getOffset(int vline,int begin,int end){\n    float offset=0;\n    for(int i = begin;i<end;++i){\n        cv::Point2f point;\n        getXY(vline,i,point);\n        offset += point.y;\n    }\n    return offset/(end-begin);\n}\n\nvoid getMiddleLine(const pcl::PointCloud<pcl::PointXYZ>::Ptr left,const pcl::PointCloud<pcl::PointXYZ>::Ptr right,pcl::PointCloud<pcl::PointXYZ>::Ptr middle){\n\n//    int size = left->size()>right->size() ? right->size():left->size();\n    bool lbigthanr = left->size()>right->size() ? 1:0;\n    int ir = 0;\n    int il = 0;\n    if(lbigthanr){\n        while(abs(left->points[il].x-right->points[ir].x)>20){\n            il++;\n        }\n    } else{\n        while(abs(left->points[il].x-right->points[ir].x)>20){\n            ir++;\n        }\n    }\n    for(ir,il; il<left->size()&&ir<right->size();++ir,++il){\n        if(abs(left->points[il].x-right->points[ir].x)>10\n            && abs(left->points[il].y -left->points[il-1].y)>5\n               && abs(right->points[ir].y -right->points[ir-1].y)>5)\n            continue;\n        pcl::PointXYZ point;\n        point.x = (left->points[il].x+right->points[ir].x)/2;\n        point.y = (left->points[il].y+right->points[ir].y)/2;\n        point.z = (left->points[il].z+right->points[ir].z)/2;\n        middle->push_back(point);\n    }\n}\n\n\nvoid test(){\n    cv::Mat frame = cv::imread(\"./calib/image/distort.png\");\n    cv::Mat gray;\n    cv::cvtColor(frame,gray,CV_RGBA2GRAY);\n    cv::Mat binary;\n    cv::threshold(gray,binary,0,255,CV_THRESH_OTSU);\n    cv::erode(binary,binary,cv::Mat(),cv::Point(-1,-1),2);\n    cv::imshow(\"show\",binary);\n    cv::waitKey(0);\n}\nvoid test1(){\n    cv::Mat mat = cv::imread(\"./calib/image/42.png\");\n    if(mat.data){\n        cv::imshow(\"test\",mat);\n        cv::waitKey(0);\n        cv::Point2f uv1(656,674);\n        cv::Point2f uv2(656,533);\n        cv::Point2f uv3(1098,533);\n        vector<cv::Point2f> uv{uv1,uv2,uv3};\n        vector<cv::Point2f> xy;\n        getLineworld(uv,xy);\n        for(auto p:xy){\n            cout<<p<<endl;\n        }\n    }\n}\nvoid test2(){\n    /** 1.get the picture **/\n    cv::Mat frame = cv::imread(\"./calib/image/51.png\");\n    if(!frame.data){\n        cerr<<\"the frame doesn't exist\"<<endl;\n        return;\n    }\n    /** 2.turn the picture to binary **/\n    cv::Mat gray;\n    cv::cvtColor(frame,gray,CV_RGB2GRAY);\n    cv::Mat binary;\n    cv::threshold(gray,binary,0,255,CV_THRESH_OTSU);\n//    cv::erode(binary,binary,cv::Mat(),cv::Point(-1,-1),2);\n    cv::imshow(\"show\",binary);\n    cv::waitKey(0);\n\n    /** 3.calculate the two side point **/\n    int vline = binary.cols/2;  // vertical line\n    int pline = binary.rows*2/3-20; // parallel line\n    vector<cv::Point2f> uvRight;\n    vector<cv::Point2f> uvLeft;\n    LineState flag;\n    // right side\n    for(int i = pline;i<binary.rows-1;++i){\n        uchar* data = binary.ptr<uchar>(i);\n        for(int j = vline;j<binary.cols-1;++j){\n            if(data[j]==255&&data[j+1]==0){ // white to black\n                data[j] = 150;\n                data[j+1] = 150;\n                data[j+2] = 150;\n                data[j+3] = 150;\n                data[j+4] = 150;\n                data[j+5] = 150;\n                data[j+6] = 150;\n                data[j+7] = 150;\n                data[j+8] = 150;\n                data[j+9] = 150;\n                data[j+10] = 150;\n                uvRight.push_back(cv::Point2f(j,i));\n                break;\n            }\n        }\n    }\n    // left side\n    for(int i = pline;i<binary.rows-1;++i){\n        uchar* data = binary.ptr<uchar>(i);\n        for(int j = vline;j>0;--j){\n            if(data[j]==255&&data[j-1]==0){ // white to black\n                data[j] = 150;\n                data[j-1] = 150;\n                data[j-2] = 150;\n                data[j-3] = 150;\n                data[j-4] = 150;\n                data[j-5] = 150;\n                data[j-6] = 150;\n                data[j-7] = 150;\n                data[j-8] = 150;\n                data[j-9] = 150;\n                data[j-10] = 150;\n                uvLeft.push_back(cv::Point2f(j,i));\n                break;\n            }\n        }\n    }\n    if(uvLeft.size()>0&&uvRight.size()>0){\n        flag = Both;\n    }\n    else if(uvLeft.size()>0){\n        flag = Left;\n    }\n    else if(uvRight.size()>0){\n        flag = Right;\n    }\n    else{\n        flag = Both;\n    }\n//    cout<<cv::mean(uvLeft)<<endl;\n//    cout<<uvLeft<<endl;\n//    cout<<\"******************\"<<endl;\n//    std::sort(uvLeft.begin(),uvLeft.end(),[](const cv::Point2f& p1,const cv::Point2f& p2){return p1.x>p2.x;});\n    cout<<uvLeft<<endl;\n    /** show the gray boundary **/\n    cv::imshow(\"show\",binary);\n    cv::waitKey(0);\n    cv::destroyAllWindows();\n\n\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1(new pcl::PointCloud<pcl::PointXYZ>());\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2(new pcl::PointCloud<pcl::PointXYZ>());\n    pcl::PointCloud<pcl::PointXYZ>::Ptr middle(new pcl::PointCloud<pcl::PointXYZ>());\n    pcl::PointCloud<pcl::PointXYZ>::Ptr average(new pcl::PointCloud<pcl::PointXYZ>());\n    image2PointCloud(uvRight,cloud1);\n    image2PointCloud(uvLeft,cloud2);\n    pcl::copyPointCloud(*cloud1,*middle);\n//    for(int i =0 ;i<middle->size();++i){\n//        middle->points[i].y = 0;\n//    }\n    getMiddleLine(cloud1,cloud2,average);\n//    float offset = getOffset(vline,pline,binary.rows-10);\n//    cout<<offset<<endl;\n\n\n    pcl::visualization::PCLVisualizer viewer(\"line\");\n    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source1(cloud1,255,0,0);\n    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source2(cloud2,0,255,0);\n    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source3(middle,255,255,255);\n    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source4(average,0,0,255);\n    viewer.addPointCloud<pcl::PointXYZ>(cloud1,source1,\"cloud1\");\n    viewer.addPointCloud<pcl::PointXYZ>(cloud2,source2,\"cloud2\");\n    viewer.addPointCloud<pcl::PointXYZ>(middle,source3,\"cloud3\");\n    viewer.addPointCloud<pcl::PointXYZ>(average,source4,\"cloud4\");\n    viewer.addCoordinateSystem(300,0,0,0);\n//    for(auto p:*middle){\n//        cout<<p<<endl;\n//    }\n    viewer.spin();\n}\n\nvoid test3(){\n    /** 1.get the picture **/\n    cv::VideoCapture cap  = cv::VideoCapture(\"\");\n    if(cap.isOpened()){\n        cv::Mat frame  = cap.read();\n \n        /** 2.turn the picture to binary **/\n        cv::Mat gray;\n        cv::cvtColor(frame,gray,CV_RGB2GRAY);\n        cv::Mat binary;\n        cv::threshold(gray,binary,0,255,CV_THRESH_OTSU);\n    //    cv::erode(binary,binary,cv::Mat(),cv::Point(-1,-1),2);\n        // cv::imshow(\"show\",binary);\n        // cv::waitKey(0);\n\n        /** 3.calculate the two side point **/\n        int vline = binary.cols/2;  // vertical line\n        int pline = binary.rows*2/3-20; // parallel line\n        vector<cv::Point2f> uvRight;\n        vector<cv::Point2f> uvLeft;\n        LineState flag;\n        // right side\n        for(int i = pline;i<binary.rows-1;++i){\n            uchar* data = binary.ptr<uchar>(i);\n            for(int j = vline;j<binary.cols-1;++j){\n                if(data[j]==255&&data[j+1]==0){ // white to black\n                    data[j] = 150;\n                    data[j+1] = 150;\n                    data[j+2] = 150;\n                    data[j+3] = 150;\n                    data[j+4] = 150;\n                    data[j+5] = 150;\n                    data[j+6] = 150;\n                    data[j+7] = 150;\n                    data[j+8] = 150;\n                    data[j+9] = 150;\n                    data[j+10] = 150;\n                    uvRight.push_back(cv::Point2f(j,i));\n                    break;\n                }\n            }\n        }\n        // left side\n        for(int i = pline;i<binary.rows-1;++i){\n            uchar* data = binary.ptr<uchar>(i);\n            for(int j = vline;j>0;--j){\n                if(data[j]==255&&data[j-1]==0){ // white to black\n                    data[j] = 150;\n                    data[j-1] = 150;\n                    data[j-2] = 150;\n                    data[j-3] = 150;\n                    data[j-4] = 150;\n                    data[j-5] = 150;\n                    data[j-6] = 150;\n                    data[j-7] = 150;\n                    data[j-8] = 150;\n                    data[j-9] = 150;\n                    data[j-10] = 150;\n                    uvLeft.push_back(cv::Point2f(j,i));\n                    break;\n                }\n            }\n        }\n        if(uvLeft.size()>0&&uvRight.size()>0){\n            flag = Both;\n        }\n        else if(uvLeft.size()>0){\n            flag = Left;\n        }\n        else if(uvRight.size()>0){\n            flag = Right;\n        }\n        else{\n            flag = Both;\n        }\n    //    cout<<cv::mean(uvLeft)<<endl;\n    //    cout<<uvLeft<<endl;\n    //    cout<<\"******************\"<<endl;\n    //    std::sort(uvLeft.begin(),uvLeft.end(),[](const cv::Point2f& p1,const cv::Point2f& p2){return p1.x>p2.x;});\n        cout<<uvLeft<<endl;\n        /** show the gray boundary **/\n        cv::imshow(\"show\",binary);\n        cv::waitKey(0);\n        cv::destroyAllWindows();\n\n\n        pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1(new pcl::PointCloud<pcl::PointXYZ>());\n        pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2(new pcl::PointCloud<pcl::PointXYZ>());\n        pcl::PointCloud<pcl::PointXYZ>::Ptr middle(new pcl::PointCloud<pcl::PointXYZ>());\n        pcl::PointCloud<pcl::PointXYZ>::Ptr average(new pcl::PointCloud<pcl::PointXYZ>());\n        image2PointCloud(uvRight,cloud1);\n        image2PointCloud(uvLeft,cloud2);\n        pcl::copyPointCloud(*cloud1,*middle);\n    //    for(int i =0 ;i<middle->size();++i){\n    //        middle->points[i].y = 0;\n    //    }\n        getMiddleLine(cloud1,cloud2,average);\n    //    float offset = getOffset(vline,pline,binary.rows-10);\n    //    cout<<offset<<endl;\n\n\n        pcl::visualization::PCLVisualizer viewer(\"line\");\n        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source1(cloud1,255,0,0);\n        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source2(cloud2,0,255,0);\n        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source3(middle,255,255,255);\n        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source4(average,0,0,255);\n        viewer.addPointCloud<pcl::PointXYZ>(cloud1,source1,\"cloud1\");\n        viewer.addPointCloud<pcl::PointXYZ>(cloud2,source2,\"cloud2\");\n        viewer.addPointCloud<pcl::PointXYZ>(middle,source3,\"cloud3\");\n        viewer.addPointCloud<pcl::PointXYZ>(average,source4,\"cloud4\");\n        viewer.addCoordinateSystem(300,0,0,0);\n    //    for(auto p:*middle){\n    //        cout<<p<<endl;\n    //    }\n        viewer.spin();\n    }\n    \n}\n\n\n\nint main(){\n\n    test3();\n\n    return 0;\n}\n\n\n//int main() {\n//\n//    /** get the video **/\n//    cv::VideoCapture cap = cv::VideoCapture(\"\");\n//    cv::Mat frame = cv::imread(\"./calib/image/50.png\");\n//    cap.set(CV_CAP_PROP_FRAME_WIDTH, imgWidth);\n//    cap.set(CV_CAP_PROP_FRAME_HEIGHT, imgWidth);\n//    LineState flag;\n//    pcl::visualization::PCLVisualizer viewer(\"line\");\n//    while (cap.isOpened()) {\n//        /** get frame and turn to binary **/\n//        cv::Mat frame;\n//        cap.read(frame);\n//        cv::Mat gray;\n//        cv::cvtColor(frame, gray, CV_RGB2GRAY);\n//        cv::Mat binary;\n//        cv::threshold(gray, binary, 0, 255, CV_THRESH_OTSU);\n//        cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);\n//        cv::imshow(\"show\", binary);\n//        cv::waitKey(0);\n//\n//        /** get point of two side **/\n//        int vline = binary.cols / 2;\n//        int pline = binary.rows * 2 / 3 - 20;\n//        vector<cv::Point2f> uvRight;\n//        vector<cv::Point2f> uvLeft;\n//        // right side\n//        for (int i = pline; i < binary.rows - 1; ++i) {\n//            uchar *data = binary.ptr<uchar>(i);\n//            for (int j = vline; j < binary.cols - 1; ++j) {\n//                if (data[j] == 255 && data[j + 1] == 0) {\n//                    data[j] = 150;\n//                    data[j + 1] = 150;\n//                    data[j + 2] = 150;\n//                    data[j + 3] = 150;\n//                    data[j + 4] = 150;\n//                    data[j + 5] = 150;\n//                    data[j + 6] = 150;\n//                    data[j + 7] = 150;\n//                    data[j + 8] = 150;\n//                    data[j + 9] = 150;\n//                    data[j + 10] = 150;\n//                    uvRight.push_back(cv::Point2f(j, i));\n//                    break;\n//\n//                }\n//            }\n//        }\n//        // left side\n//        for (int i = pline; i < binary.rows - 1; ++i) {\n//            uchar *data = binary.ptr<uchar>(i);\n//            for (int j = vline; j > 0; --j) {\n//                if (data[j] == 255 && data[j - 1] == 0) {\n//                    data[j] = 150;\n//                    data[j - 1] = 150;\n//                    data[j - 2] = 150;\n//                    data[j - 3] = 150;\n//                    data[j - 4] = 150;\n//                    data[j - 5] = 150;\n//                    data[j - 6] = 150;\n//                    data[j - 7] = 150;\n//                    data[j - 8] = 150;\n//                    data[j - 9] = 150;\n//                    data[j - 10] = 150;\n//                    uvLeft.push_back(cv::Point2f(j, i));\n//                    break;\n//                }\n//            }\n//        }\n//        if(uvLeft.size()>0&&uvRight.size()>0){\n//            flag = Both;\n//        }\n//        else if(uvLeft.size()>0){\n//            flag = Left;\n//        }\n//        else if(uvRight.size()>0){\n//            flag = Right;\n//        }\n//        else{\n//            flag = Both;\n//        }\n//\n//        /** show the boundary **/\n//        cv::imshow(\"show\", binary);\n//        cv::waitKey(0);\n//\n//        /** visualization **/\n//        pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1(new pcl::PointCloud<pcl::PointXYZ>());\n//        pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2(new pcl::PointCloud<pcl::PointXYZ>());\n//        image2PointCloud(uvRight, cloud1);\n//        image2PointCloud(uvLeft, cloud2);\n//        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source1(cloud1, 255, 0, 0);\n//        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source2(cloud2, 255, 255, 0);\n//        viewer.addPointCloud<pcl::PointXYZ>(cloud1, source1, \"cloud1\");\n//        viewer.addPointCloud<pcl::PointXYZ>(cloud2, source2, \"cloud2\");\n//        viewer.addCoordinateSystem(1000, 0, 0, 0);\n//        viewer.spin();\n//\n//    }\n//    return 0;\n//}", "meta": {"hexsha": "1b1e09b9cbbde21f29183665a01b97de2f17bbee", "size": 16725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lineTrack-2/src/lineTrack_pc_v1.0.cpp", "max_stars_repo_name": "GuoPingPan/LinearTracking_Huawei", "max_stars_repo_head_hexsha": "499e16448081421766df66614551750c1cb71a1d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lineTrack-2/src/lineTrack_pc_v1.0.cpp", "max_issues_repo_name": "GuoPingPan/LinearTracking_Huawei", "max_issues_repo_head_hexsha": "499e16448081421766df66614551750c1cb71a1d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lineTrack-2/src/lineTrack_pc_v1.0.cpp", "max_forks_repo_name": "GuoPingPan/LinearTracking_Huawei", "max_forks_repo_head_hexsha": "499e16448081421766df66614551750c1cb71a1d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0631364562, "max_line_length": 158, "alphanum_fraction": 0.5060089686, "num_tokens": 4802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.6187804478040617, "lm_q1q2_score": 0.5653651653970437}}
{"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": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\r\n//\r\n// Distributed under the Boost Software License, Version 1.0\r\n// See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt\r\n//\r\n// See http://boostorg.github.com/compute for more information.\r\n//---------------------------------------------------------------------------//\r\n\r\n#define BOOST_TEST_MODULE TestPartition\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <boost/compute/system.hpp>\r\n#include <boost/compute/functional.hpp>\r\n#include <boost/compute/command_queue.hpp>\r\n#include <boost/compute/algorithm/partition.hpp>\r\n#include <boost/compute/algorithm/partition_copy.hpp>\r\n#include <boost/compute/algorithm/is_partitioned.hpp>\r\n#include <boost/compute/container/vector.hpp>\r\n\r\n#include \"check_macros.hpp\"\r\n#include \"context_setup.hpp\"\r\n\r\nnamespace bc = boost::compute;\r\n\r\nBOOST_AUTO_TEST_CASE(partition_float_vector)\r\n{\r\n    bc::vector<float> vector(context);\r\n    vector.push_back(1.0f, queue);\r\n    vector.push_back(2.0f, queue);\r\n    vector.push_back(-1.0f, queue);\r\n    vector.push_back(-2.0f, queue);\r\n    vector.push_back(3.0f, queue);\r\n    vector.push_back(4.0f, queue);\r\n    vector.push_back(-3.0f, queue);\r\n    vector.push_back(-4.0f, queue);\r\n\r\n    // verify is_partitioned()\r\n    BOOST_VERIFY(bc::is_partitioned(vector.begin(),\r\n                                    vector.end(),\r\n                                    bc::signbit_<float>(),\r\n                                    queue) == false);\r\n\r\n    // partition by signbit\r\n    bc::vector<float>::iterator iter = bc::partition(vector.begin(),\r\n                                                     vector.end(),\r\n                                                     bc::signbit_<float>(),\r\n                                                     queue);\r\n    queue.finish();\r\n    BOOST_VERIFY(iter == vector.begin() + 4);\r\n    BOOST_CHECK_LT(vector[0], 0.0f);\r\n    BOOST_CHECK_LT(vector[1], 0.0f);\r\n    BOOST_CHECK_LT(vector[2], 0.0f);\r\n    BOOST_CHECK_LT(vector[3], 0.0f);\r\n    BOOST_CHECK_GT(vector[4], 0.0f);\r\n    BOOST_CHECK_GT(vector[5], 0.0f);\r\n    BOOST_CHECK_GT(vector[6], 0.0f);\r\n    BOOST_CHECK_GT(vector[7], 0.0f);\r\n\r\n    // verify is_partitioned()\r\n    BOOST_VERIFY(bc::is_partitioned(vector.begin(),\r\n                                    vector.end(),\r\n                                    bc::signbit_<float>(),\r\n                                    queue) == true);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(partition_small_vector)\r\n{\r\n    bc::vector<float> vector(context);\r\n    bc::partition(vector.begin(), vector.end(), bc::signbit_<float>(), queue);\r\n\r\n    vector.push_back(1.0f, queue);\r\n    bc::partition(vector.begin(), vector.end(), bc::signbit_<float>(), queue);\r\n    CHECK_RANGE_EQUAL(float, 1, vector, (1.0f));\r\n\r\n    vector.push_back(-1.0f, queue);\r\n    bc::partition(vector.begin(), vector.end(), bc::signbit_<float>(), queue);\r\n    CHECK_RANGE_EQUAL(float, 2, vector, (-1.0f, 1.0f));\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "a8955113909dd94d4b3436f7d5caba62478b32ef", "size": 3074, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_partition.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_partition.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/compute/test/test_partition.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 37.0361445783, "max_line_length": 80, "alphanum_fraction": 0.559856864, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5652912140816387}}
{"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": "#ifndef STAN_MATH_PRIM_SCAL_PROB_POISSON_LCDF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_POISSON_LCDF_HPP\n\n#include <stan/math/prim/scal/meta/is_constant_struct.hpp>\n#include <stan/math/prim/scal/meta/partials_return_type.hpp>\n#include <stan/math/prim/scal/meta/operands_and_partials.hpp>\n#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_less.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/fun/multiply_log.hpp>\n#include <stan/math/prim/scal/fun/gamma_q.hpp>\n#include <stan/math/prim/scal/fun/lgamma.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cmath>\n#include <limits>\n\nnamespace stan {\n  namespace math {\n\n    template <typename T_n, typename T_rate>\n    typename return_type<T_rate>::type\n    poisson_lcdf(const T_n& n, const T_rate& lambda) {\n      static const char* function(\"poisson_lcdf\");\n      typedef typename stan::partials_return_type<T_n, T_rate>::type\n        T_partials_return;\n\n      if (!(stan::length(n) && stan::length(lambda)))\n        return 0.0;\n\n      T_partials_return P(0.0);\n\n      check_not_nan(function, \"Rate parameter\", lambda);\n      check_nonnegative(function, \"Rate parameter\", lambda);\n      check_consistent_sizes(function,\n                             \"Random variable\", n,\n                             \"Rate parameter\", lambda);\n\n      scalar_seq_view<T_n> n_vec(n);\n      scalar_seq_view<T_rate> lambda_vec(lambda);\n      size_t size = max_size(n, lambda);\n\n      using std::log;\n      using std::exp;\n\n      operands_and_partials<T_rate> ops_partials(lambda);\n\n      // Explicit return for extreme values\n      // The gradients are technically ill-defined, but treated as neg infinity\n      for (size_t i = 0; i < stan::length(n); i++) {\n        if (value_of(n_vec[i]) < 0)\n          return ops_partials.build(negative_infinity());\n      }\n\n      for (size_t i = 0; i < size; i++) {\n        // Explicit results for extreme values\n        // The gradients are technically ill-defined, but treated as zero\n        if (value_of(n_vec[i]) == std::numeric_limits<int>::max())\n          continue;\n\n        const T_partials_return n_dbl = value_of(n_vec[i]);\n        const T_partials_return lambda_dbl = value_of(lambda_vec[i]);\n        const T_partials_return log_Pi = log(gamma_q(n_dbl + 1, lambda_dbl));\n\n        P += log_Pi;\n\n        if (!is_constant_struct<T_rate>::value)\n          ops_partials.edge1_.partials_[i] += -exp(n_dbl * log(lambda_dbl)\n                                                   - lambda_dbl\n                                                   - lgamma(n_dbl + 1)\n                                                   - log_Pi);\n      }\n      return ops_partials.build(P);\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "7362f3164f8cd63f3105068ef83ab2703d005243", "size": 3010, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/poisson_lcdf.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/poisson_lcdf.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/poisson_lcdf.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.265060241, "max_line_length": 79, "alphanum_fraction": 0.6485049834, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162774, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5652243859320074}}
{"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 (c) 2013-2014 Mageswaran.D <mageswaran1989@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#include <iostream>\n#include <string>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/interop/opencv/core.hpp>\n#include <boost/compute/interop/opencv/highgui.hpp>\n#include <boost/compute/utility/source.hpp>\n\n#include <boost/program_options.hpp>\n\nnamespace compute = boost::compute;\nnamespace po = boost::program_options;\n\n// Create naive optical flow program\nconst char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE (\n    const sampler_t sampler = CLK_ADDRESS_CLAMP_TO_EDGE;\n\n    __kernel void optical_flow (\n                                read_only\n                                image2d_t current_image,\n                                read_only image2d_t previous_image,\n                                write_only image2d_t optical_flow,\n                                const float scale,\n                                const float offset,\n                                const float lambda,\n                                const float threshold )\n    {\n        int2 coords = (int2)(get_global_id(0), get_global_id(1));\n        float4 current_pixel    = read_imagef(current_image,\n                                              sampler,\n                                              coords);\n        float4 previous_pixel   = read_imagef(previous_image,\n                                              sampler,\n                                              coords);\n        int2 x1     = (int2)(offset, 0.f);\n        int2 y1     = (int2)(0.f, offset);\n\n        //get the difference\n        float4 curdif = previous_pixel - current_pixel;\n\n        //calculate the gradient\n        //Image 2 first\n        float4 gradx = read_imagef(previous_image,\n                                   sampler,\n                                   coords+x1) -\n                       read_imagef(previous_image,\n                                   sampler,\n                                   coords-x1);\n        //Image 1\n        gradx += read_imagef(current_image,\n                             sampler,\n                             coords+x1) -\n                 read_imagef(current_image,\n                             sampler,\n                             coords-x1);\n        //Image 2 first\n        float4 grady = read_imagef(previous_image,\n                                   sampler,\n                                   coords+y1) -\n                       read_imagef(previous_image,\n                                   sampler,\n                                   coords-y1);\n        //Image 1\n        grady += read_imagef(current_image,\n                             sampler,\n                             coords+y1) -\n                 read_imagef(current_image,\n                             sampler,\n                             coords-y1);\n\n        float4 sqr = (gradx*gradx) + (grady*grady) +\n                     (float4)(lambda,lambda, lambda, lambda);\n        float4 gradmag = sqrt(sqr);\n\n        ///////////////////////////////////////////////////\n        float4 vx = curdif * (gradx / gradmag);\n        float vxd = vx.x;//assumes greyscale\n\n        //format output for flowrepos, out(-x,+x,-y,+y)\n        float2 xout = (float2)(fmax(vxd,0.f),fabs(fmin(vxd,0.f)));\n        xout *= scale;\n        ///////////////////////////////////////////////////\n        float4 vy = curdif*(grady/gradmag);\n        float vyd = vy.x;//assumes greyscale\n\n        //format output for flowrepos, out(-x,+x,-y,+y)\n        float2 yout = (float2)(fmax(vyd,0.f),fabs(fmin(vyd,0.f)));\n        yout *= scale;\n        ///////////////////////////////////////////////////\n\n        float4 out = (float4)(xout, yout);\n        float cond = (float)isgreaterequal(length(out), threshold);\n        out *= cond;\n\n        write_imagef(optical_flow, coords, out);\n    }\n);\n\n// This example shows how to read two images or use camera\n// with OpenCV, transfer the frames to the GPU,\n// and apply a naive optical flow algorithm\n// written in OpenCL\nint main(int argc, char *argv[])\n{\n    // setup the command line arguments\n    po::options_description desc;\n    desc.add_options()\n            (\"help\",  \"show available options\")\n            (\"camera\", po::value<int>()->default_value(-1),\n                                 \"if not default camera, specify a camera id\")\n            (\"image1\", po::value<std::string>(), \"path to image file 1\")\n            (\"image2\", po::value<std::string>(), \"path to image file 2\");\n\n    // Parse the command lines\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    //check the command line arguments\n    if(vm.count(\"help\"))\n    {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    //OpenCV variables\n    cv::Mat previous_cv_image;\n    cv::Mat current_cv_image;\n    cv::VideoCapture cap; //OpenCV camera handle\n\n    //check for image paths\n    if(vm.count(\"image1\") && vm.count(\"image2\"))\n    {\n        // Read image 1 with OpenCV\n        previous_cv_image = cv::imread(vm[\"image1\"].as<std::string>(),\n                                       CV_LOAD_IMAGE_COLOR);\n        if(!previous_cv_image.data){\n            std::cerr << \"Failed to load image\" << std::endl;\n            return -1;\n        }\n\n        // Read image 2 with opencv\n        current_cv_image = cv::imread(vm[\"image2\"].as<std::string>(),\n                                      CV_LOAD_IMAGE_COLOR);\n        if(!current_cv_image.data){\n            std::cerr << \"Failed to load image\" << std::endl;\n            return -1;\n        }\n    }\n    else //by default use camera\n    {\n        //open camera\n        cap.open(vm[\"camera\"].as<int>());\n        // read first frame\n        cap >> previous_cv_image;\n        if(!previous_cv_image.data){\n            std::cerr << \"failed to capture frame\" << std::endl;\n            return -1;\n        }\n\n        // read second frame\n        cap >> current_cv_image;\n        if(!current_cv_image.data){\n            std::cerr << \"failed to capture frame\" << std::endl;\n            return -1;\n        }\n\n    }\n\n    // Get default device and setup context\n    compute::device gpu = compute::system::default_device();\n    compute::context context(gpu);\n    compute::command_queue queue(context, gpu);\n\n    // Convert image to BGRA (OpenCL requires 16-byte aligned data)\n    cv::cvtColor(previous_cv_image, previous_cv_image, CV_BGR2BGRA);\n    cv::cvtColor(current_cv_image, current_cv_image, CV_BGR2BGRA);\n\n    // Transfer image to gpu\n    compute::image2d dev_previous_image =\n            compute::opencv_create_image2d_with_mat(\n                previous_cv_image, compute::image2d::read_write, queue\n                );\n    // Transfer image to gpu\n    compute::image2d dev_current_image =\n            compute::opencv_create_image2d_with_mat(\n                current_cv_image, compute::image2d::read_write, queue\n                );\n\n    // Create output image\n    compute::image2d dev_output_image(\n                context,\n                dev_previous_image.width(),\n                dev_previous_image.height(),\n                dev_previous_image.format(),\n                compute::image2d::write_only\n                );\n\n    compute::program optical_program =\n            compute::program::create_with_source(source, context);\n    optical_program.build();\n\n    // create flip kernel and set arguments\n    compute::kernel optical_kernel(optical_program, \"optical_flow\");\n    float scale = 10;\n    float offset = 1;\n    float lambda = 0.0025;\n    float threshold = 1.0;\n\n    optical_kernel.set_arg(0, dev_previous_image);\n    optical_kernel.set_arg(1, dev_current_image);\n    optical_kernel.set_arg(2, dev_output_image);\n    optical_kernel.set_arg(3, scale);\n    optical_kernel.set_arg(4, offset);\n    optical_kernel.set_arg(5, lambda);\n    optical_kernel.set_arg(6, threshold);\n\n    // run flip kernel\n    size_t origin[2] = { 0, 0 };\n    size_t region[2] = { dev_previous_image.width(),\n                         dev_previous_image.height() };\n    queue.enqueue_nd_range_kernel(optical_kernel, 2, origin, region, 0);\n\n    //check for image paths\n    if(vm.count(\"image1\") && vm.count(\"image2\"))\n    {\n        // show host image\n        cv::imshow(\"Previous Frame\", previous_cv_image);\n        cv::imshow(\"Current Frame\", current_cv_image);\n\n        // show gpu image\n        compute::opencv_imshow(\"filtered image\", dev_output_image, queue);\n\n        // wait and return\n        cv::waitKey(0);\n    }\n    else\n    {\n        char key = '\\0';\n        while(key != 27) //check for escape key\n        {\n            cap >> current_cv_image;\n\n            // Convert image to BGRA (OpenCL requires 16-byte aligned data)\n            cv::cvtColor(current_cv_image, current_cv_image, CV_BGR2BGRA);\n\n            // Update the device image memory with current frame data\n            compute::opencv_copy_mat_to_image(previous_cv_image,\n                                              dev_previous_image,\n                                              queue);\n            compute::opencv_copy_mat_to_image(current_cv_image,\n                                              dev_current_image,\n                                              queue);\n\n            // Run the kernel on the device\n            queue.enqueue_nd_range_kernel(optical_kernel, 2, origin, region, 0);\n\n            // Show host image\n            cv::imshow(\"Previous Frame\", previous_cv_image);\n            cv::imshow(\"Current Frame\", current_cv_image);\n\n            // Show GPU image\n            compute::opencv_imshow(\"filtered image\", dev_output_image, queue);\n\n            // Copy current frame container to previous frame container\n            current_cv_image.copyTo(previous_cv_image);\n\n            // wait\n            key = cv::waitKey(10);\n        }\n\n    }\n    return 0;\n}\n", "meta": {"hexsha": "c50e6c1f61fd7e271b46c969f23cd59b47ffd6b8", "size": 10257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/compute/example/opencv_optical_flow.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/compute/example/opencv_optical_flow.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/compute/example/opencv_optical_flow.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 35.491349481, "max_line_length": 80, "alphanum_fraction": 0.5268597056, "num_tokens": 2149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5651164386566734}}
{"text": "/*! ------------------------------------------------------------------------- *\n * \\author Joey Dumont                  <joey.dumont@gmail.com>               *\n * \\since 2018-07-24                                                          *\n *                                                                            *\n * Outputs a 10x10 matrix with random complex numbers in a human-readable     *\n * format.                                                                    *\n * --------------------------------------------------------------------------*/\n\n#include <armadillo>\n\nint main(int argc, char* argv[])\n{\n  arma::cx_mat rand_cx_mat = arma::randu<arma::cx_mat>(10,10);\n  rand_cx_mat.save(\"rand_test.txt\", arma::raw_ascii);\n  return 0;\n}\n", "meta": {"hexsha": "6ed301226fa6d6d4fa1a1c70e658ca2267b7e8c9", "size": 749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "assets/posts/read-c-format-complex-numbers-with-numpy/complex_arma_data.cpp", "max_stars_repo_name": "joeydumont/joeydumont.github.io", "max_stars_repo_head_hexsha": "f62672427b265d87f754ac95ba54708dd7bd046c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets/posts/read-c-format-complex-numbers-with-numpy/complex_arma_data.cpp", "max_issues_repo_name": "joeydumont/joeydumont.github.io", "max_issues_repo_head_hexsha": "f62672427b265d87f754ac95ba54708dd7bd046c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assets/posts/read-c-format-complex-numbers-with-numpy/complex_arma_data.cpp", "max_forks_repo_name": "joeydumont/joeydumont.github.io", "max_forks_repo_head_hexsha": "f62672427b265d87f754ac95ba54708dd7bd046c", "max_forks_repo_licenses": ["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.0588235294, "max_line_length": 79, "alphanum_fraction": 0.3217623498, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5651164337015689}}
{"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": "#include <Eigen/Core>\n#include <iostream>\nusing namespace std;\nusing namespace Eigen;\n\ntemplate<typename Derived>\nconst Reshaped<const Derived>\nreshape_helper(const MatrixBase<Derived>& m, int rows, int cols)\n{\n  return Reshaped<const Derived>(m.derived(), rows, cols);\n}\n\nint main(int, char**)\n{\n  MatrixXd m(3, 4);\n  m << 1, 4, 7, 10,\n       2, 5, 8, 11,\n       3, 6, 9, 12;\n  cout << m << endl;\n  Ref<const MatrixXd> n = reshape_helper(m, 2, 6);\n  cout << \"Matrix m is:\" << endl << m << endl;\n  cout << \"Matrix n is:\" << endl << n << endl;\n}\n", "meta": {"hexsha": "18fb45454de20474dce470f50d83454b2e85c157", "size": 545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/eigen/doc/examples/class_Reshaped.cpp", "max_stars_repo_name": "Krissmedt/imprunko", "max_stars_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2111.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:48:14.000Z", "max_issues_repo_path": "tools/eigen/doc/examples/class_Reshaped.cpp", "max_issues_repo_name": "Krissmedt/imprunko", "max_issues_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 131.0, "max_issues_repo_issues_event_min_datetime": "2019-02-18T10:56:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:07:00.000Z", "max_forks_repo_path": "tools/eigen/doc/examples/class_Reshaped.cpp", "max_forks_repo_name": "Krissmedt/imprunko", "max_forks_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:22:01.000Z", "avg_line_length": 22.7083333333, "max_line_length": 64, "alphanum_fraction": 0.6165137615, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5651164319432698}}
{"text": "// BernoulliDistribution.hpp\r\n//\r\n// (C) Datasim Education BV  2009\r\n\r\n#pragma once\r\n\r\n#include <boost/math/distributions.hpp>\r\n\r\nusing namespace System;\r\n\r\nnamespace Wrapper \r\n{\r\n\t// Wrapper for the boost::math::bernoulli_distribution class\r\n\t// We use the .NET naming conventions instead of the original C++ name\r\n\tpublic ref class BernoulliDistribution\r\n\t{\r\n\tprivate:\r\n\t\t// The wrapped native class (only pointers to native classes can be a C++/CLI class datamember)\r\n\t\tboost::math::bernoulli_distribution<>* m_distribution;\r\n\r\n\tpublic:\r\n\t\t// Default constructor\r\n\t\tBernoulliDistribution();\r\n\r\n\t\t// Constructor with value\r\n\t\tBernoulliDistribution(double value);\r\n\r\n\t\t// Finaliser (called by garbage collector or destructor)\r\n\t\t!BernoulliDistribution();\r\n\r\n\t\t// Destructor (Dispose)\r\n\t\t~BernoulliDistribution();\r\n\r\n\t\t// Get the success fraction\r\n\t\tdouble SuccessFraction();\r\n\r\n\t\t// Get the native object\r\n\t\tboost::math::bernoulli_distribution<>* GetNative();\r\n\t};\r\n}\r\n", "meta": {"hexsha": "71606eef9ae60c8bd3b6ee665c84b5a8327b988d", "size": 970, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI Interop Test (Chi-Squared)/Wrapper/BernoulliDistribution.hpp", "max_stars_repo_name": "jdm7dv/financial", "max_stars_repo_head_hexsha": "673a552d58751643dbca0ba633aeff119eda107d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T06:54:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T06:54:08.000Z", "max_issues_repo_path": "windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI Interop Test (Chi-Squared)/Wrapper/BernoulliDistribution.hpp", "max_issues_repo_name": "jdm7dv/financial", "max_issues_repo_head_hexsha": "673a552d58751643dbca0ba633aeff119eda107d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "windows/CsForFinancialMarketsPart2/Chapters20+21+22+23/Demos - CLI-CS Interop with Excel/CLI Interop Test (Chi-Squared)/Wrapper/BernoulliDistribution.hpp", "max_forks_repo_name": "jdm7dv/financial", "max_forks_repo_head_hexsha": "673a552d58751643dbca0ba633aeff119eda107d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-19T19:27:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T06:26:06.000Z", "avg_line_length": 23.6585365854, "max_line_length": 98, "alphanum_fraction": 0.7092783505, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.565116422033061}}
{"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 * @example types/test/position_test.cc\n */\n#include <boost/test/unit_test.hpp>\n#include <usml/types/types.h>\n#include <iostream>\n\nBOOST_AUTO_TEST_SUITE(position_test)\n\nusing namespace boost::unit_test;\nusing namespace usml::types;\n\n/**\n * @ingroup types_test\n * @{\n */\n\n/**\n * Compare the earth's radius at specific latitudes to known values.\n * Generate errors if values differ by more that 1E-6 percent.\n *\n * @xref WGS 84 IMPLEMENTATION MANUAL, Version 2.4, 1998.\n *       See http://www.dqts.net/wgs84.htm for more information.\n */\nBOOST_AUTO_TEST_CASE( earth_radius_test ) {\n    cout << \"=== position_test: earth_radius_test ===\" << endl;\n\n    double radius90 = 6399593.62578493 ;\n    double radius45 = 6378101.030201019 ;\n    double radius00 = 6356752.314245179 ;\n\n    wposition::compute_earth_radius(90.0);\n    cout << \"earth_radius at 90.0 latitude: \"\n         << wposition::earth_radius << endl;\n    BOOST_CHECK_CLOSE( wposition::earth_radius, radius90, 1e-6 );\n\n    wposition::compute_earth_radius(45.0);\n    cout << \"earth_radius at 45.0 latitude: \"\n         << wposition::earth_radius << endl;\n    BOOST_CHECK_CLOSE( wposition::earth_radius, radius45, 1e-6 );\n\n    wposition::compute_earth_radius(0.0);\n    cout << \"earth_radius at  0.0 latitude: \"\n         << wposition::earth_radius << endl;\n    BOOST_CHECK_CLOSE( wposition::earth_radius, radius00, 1e-6 );\n}\n\n/**\n * Compute the dot product between set of vectors at different latitudes\n * and a vector pointing due north.  If correct, the dots products\n * should correspond to the angles defined by the latitudes of\n * the original points.\n *\n * Generate errors if values differ by more that 1E-6 percent.\n */\nBOOST_AUTO_TEST_CASE( dot_test ) {\n    cout << \"=== position_test: dot_test ===\" << endl;\n\n    // define a series of lat/long points on earth\n\n    wposition points(10);\n    for ( int n=0; n < 10; ++n ) {\n        points.latitude( n, 0, 10.0*n );\n        points.longitude( n, 0, 90.0+10.0*n );\n    }\n\n    // dot this with vector through the north pole\n\n    wposition1 north( 90.0, 0.0 );\n    matrix<double> angle( 10, 1 );\n    points.dotnorm( north, angle );\n    angle = to_degrees( acos(angle) );\n\n    // check the answer\n\n    for ( int n=0; n < 10; ++n ) {\n        double analytic = 90.0 - 10.0 * n ;\n        cout << \"angle=\" << angle(n,0) << \" analytic=\" << analytic << endl;\n        BOOST_CHECK_CLOSE( angle(n,0), analytic, 1e-6 );\n    }\n}\n\n/**\n * Compute the dot product between a vector at different latitudes\n * and a vector pointing due north.  If correct, the dots products\n * should correspond to the angles defined by the latitudes of\n * the original points.\n *\n * Generate errors if values differ by more that 1E-6 percent.\n */\nBOOST_AUTO_TEST_CASE( dot1_test ) {\n    cout << \"=== position_test: dot1_test ===\" << endl;\n\n    // define a series of lat/long points on earth\n\n    wposition1 point ;\n    for ( int n=0; n < 10; ++n ) {\n        point.latitude( 10.0*n );\n        point.longitude( 90.0+10.0*n );\n\n        // dot this with vector through the north pole\n\n        wposition1 north( 90.0, 0.0 );\n        double angle = point.dotnorm( north );\n        angle = to_degrees( acos(angle) );\n\n        // check the answer\n\n        double analytic = 90.0 - 10.0 * n ;\n        cout << \"angle=\" << angle << \" analytic=\" << analytic << endl;\n        BOOST_CHECK_CLOSE( angle, analytic, 1e-6 );\n    }\n}\n\n/**\n * Compute the straight line distance between a wposition vector\n * at different latitudes and the point 40N 45E. The results are\n * compared to the analytic solution\n * <pre>\n *          distance^2 = 2 R^2 ( 1-cos(40-latitude) )\n * </pre>\n * Generate errors if values differ by more that 1E-6 meters.  The one\n * expection to this accuracy is the case where distance is almost zero.\n * In that case, the calculation accuracy is limited to 0.02 meters.\n */\nBOOST_AUTO_TEST_CASE( distance_test ) {\n    cout << \"=== position_test: distance_test ===\" << endl;\n\n    // define a series of lat/long points on earth\n\n    wposition points(10);\n    for ( int n=0; n < 10; ++n ) {\n        points.latitude( n, 0, 10.0*n );\n        points.longitude( n, 0, 45.0 );\n    }\n\n    // compute the distance to some point on earth\n\n    wposition1 origin( 40.0, 45.0 );\n    matrix<double> distance( 10, 1 );\n    points.distance( origin, distance );\n\n    // check the answer\n    // distance^2 = 2 R^2 ( 1-cos(angle) )\n\n    for ( int n=0; n < 10; ++n ) {\n        double analytic = wposition::earth_radius\n            * sqrt( 2.0 * ( 1.0 - cos( to_radians(40.0-10.0*n) ) ) );\n        cout << \"distance=\" << distance(n,0) << \" analytic=\" << analytic << endl;\n        if ( analytic > 1e-6 ) {\n            BOOST_CHECK_CLOSE( distance(n,0), analytic, 1e-10 );\n        } else {\n            BOOST_CHECK_SMALL( distance(n,0)-analytic, 0.1 );\n        }\n    }\n}\n\n/**\n * Compute the straight line distance between a series of wposition1 vectors\n * at different latitudes and the point 40N 45E. The results are compared\n * to the analytic solution\n * <pre>\n *          distance^2 = 2 R^2 ( 1-cos(40-latitude) )\n * </pre>\n * Generate errors if values differ by more that 1E-6 meters.  The one\n * expection to this accuracy is the case where distance is almost zero.\n * In that case, the calculation accuracy is limited to 0.02 meters.\n */\nBOOST_AUTO_TEST_CASE( distance1_test ) {\n    cout << \"=== position_test: distance1_test ===\" << endl;\n\n    // define a series of lat/long points on earth\n\n    wposition1 point ;\n    for ( int n=0; n < 10; ++n ) {\n        point.latitude( 10.0*n );\n        point.longitude( 45.0 );\n\n        // compute the distance to some point on earth\n\n        wposition1 origin( 40.0, 45.0 );\n        double distance = point.distance( origin );\n\n        // check the answer\n        // distance^2 = 2 R^2 ( 1-cos(angle) )\n\n        double analytic = wposition::earth_radius\n            * sqrt( 2.0 * ( 1.0 - cos( to_radians(40.0-10.0*n) ) ) );\n        cout << \"distance=\" << distance << \" analytic=\" << analytic << endl;\n        if ( analytic > 1e-6 ) {\n            BOOST_CHECK_CLOSE( distance, analytic, 1e-10 );\n        } else {\n            BOOST_CHECK_SMALL( distance-analytic, 0.1 );\n        }\n    }\n}\n\n/**\n * Compute the great circle range and bearing between JFK and LAX airports.\n * Based on the \"Worked Examples\" in Aviation Formulary.\n * Requires an earth radius based on the definition where\n * 1 nmi = 1 min latitude = 1852.0 meters. Generate errors if values differ\n * from Williams' answers, in radians, by more that 1e-4%\n *\n * The process is then reversed to predict the location of JFK using this\n * range and bearing from LAX.  Those answers are required to be within\n * 1e-10% of the true location for JFK.\n *\n * @xref E. Williams, \"Aviation Formulary V1.43\",\n * http://williams.best.vwh.net/avform.htm , July 2010.\n */\nBOOST_AUTO_TEST_CASE( gc_range_test ) {\n    cout << \"=== position_test: gc_range_test ===\" << endl;\n    double orig_radius = wposition::earth_radius ;\n    wposition::earth_radius =  180.0/M_PI*60.0*1852.0 ; // radius used in Aviation Formulary.\n\n    // compute range and bearing from LAX to JFK\n\n    wposition1 jfk( 40.0 + 38.0/60.0, -(73.0 + 47.0/60.0) ) ;\n    wposition1 lax( 33.0 + 57.0/60.0, -(118.0 + 24.0/60.0) ) ;\n\n    double range, bearing ;\n    range = lax.gc_range( jfk, &bearing ) ;\n\n    cout << \"LAX to JFK: range = \" << (range/wposition::earth_radius) << \" rad bearing = \" << bearing << \" rad\" << endl ;\n    cout << \"LAX to JFK: range = \" << (range/1852.0) << \" nmi bearing = \" << to_degrees(bearing) << \" deg\" << endl ;\n\n    BOOST_CHECK_CLOSE( range/wposition::earth_radius, 0.623585, 1e-4 );\n    BOOST_CHECK_CLOSE( bearing, 1.150035, 1e-4 );\n\n    // reverse the process by computing location at this range/bearing from LAX\n\n    wposition1 unk( lax, range, bearing ) ;\n    cout << \"JFK: \" << jfk.latitude() << \"N \" << -jfk.longitude() << \"W\" << endl ;\n    cout << \"UNK: \" << unk.latitude() << \"N \" << -unk.longitude() << \"W\" << endl ;\n\n    BOOST_CHECK_CLOSE( unk.latitude(), jfk.latitude(), 1e-10 );\n    BOOST_CHECK_CLOSE( unk.longitude(), jfk.longitude(), 1e-10 );\n\n    wposition::earth_radius = orig_radius ;\n}\n\n/// @}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3b70b4ea76136329257d32aa9c7f875a21e2ebba", "size": 8179, "ext": "cc", "lang": "C++", "max_stars_repo_path": "types/test/position_test.cc", "max_stars_repo_name": "fraclipe/UnderSeaModelingLibrary", "max_stars_repo_head_hexsha": "52ef9dd03c7cbe548749e4527190afe7668ff4e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-07T14:48:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T14:48:22.000Z", "max_issues_repo_path": "types/test/position_test.cc", "max_issues_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_issues_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "types/test/position_test.cc", "max_forks_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_forks_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2479674797, "max_line_length": 121, "alphanum_fraction": 0.6273383054, "num_tokens": 2347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5651111112066945}}
{"text": "#ifndef POLYNOMIAL_H_\n#define POLYNOMIAL_H_\n\n#include <Eigen/Core>\n#include <Eigen/QR>\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\n\n// Evaluate a polynomial.\ndouble polyeval(const VectorXd & coeffs, double x);\n// Fit a polynomial.\nVectorXd polyfit(const VectorXd & xvals, const VectorXd & yvals, int order);\n\n#endif\n", "meta": {"hexsha": "c8a5150dfcbc667d4478093151190ee55fde50a4", "size": 319, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "polyfit/include/polynomial.hpp", "max_stars_repo_name": "Horki/CarND-MPC-Quizzes", "max_stars_repo_head_hexsha": "236dc2f99a0f641efcbe8eac9cf4aa7e8db06a69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "polyfit/include/polynomial.hpp", "max_issues_repo_name": "Horki/CarND-MPC-Quizzes", "max_issues_repo_head_hexsha": "236dc2f99a0f641efcbe8eac9cf4aa7e8db06a69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "polyfit/include/polynomial.hpp", "max_forks_repo_name": "Horki/CarND-MPC-Quizzes", "max_forks_repo_head_hexsha": "236dc2f99a0f641efcbe8eac9cf4aa7e8db06a69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9375, "max_line_length": 76, "alphanum_fraction": 0.7554858934, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5651111076159455}}
{"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": "//------------------------------------------------------------------------------\n// \\file BitsStream_test.cpp\n//------------------------------------------------------------------------------\n#include \"Utilities/BitsStream.h\"\n\n#include \"Cpp/Utilities/SuperBitSet.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n#include <limits>\n#include <string>\n// https://stackoverflow.com/questions/20731/how-do-you-clear-a-stringstream-variable\n\nusing Cpp::Utilities::SuperBitSet;\nusing Utilities::BitsStream;\n\nBOOST_AUTO_TEST_SUITE(Utilities)\nBOOST_AUTO_TEST_SUITE(BitsStream_tests)\n\n// cf. https://stackoverflow.com/questions/34588650/uint128-t-does-not-name-a-type\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(__Uint128_tExists)\n{\n  BOOST_TEST(sizeof(__uint128_t) == 16);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(DemonstrateMinus0In1sComplement)\n{\n  SuperBitSet<16> bits {BitsStream::minus_0_1s_complement};\n  BOOST_TEST(bits.to_string() == \"1111111111111111\");\n  BOOST_TEST(bits.to_ulong() == 65535);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // BitsStream_tests\nBOOST_AUTO_TEST_SUITE_END() // Utilities\n", "meta": {"hexsha": "35cb247d9ae342980fac88fd5ed8fe66a6a52035", "size": 1376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Utilities/BitsStream_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Utilities/BitsStream_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Utilities/BitsStream_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2820512821, "max_line_length": 85, "alphanum_fraction": 0.511627907, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.5651111036326281}}
{"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\u00e9\n    if(deformation == 0) {\n        ret <<\n            1, 0,\n            0, 1;\n    }\n    // Conique : pas de moyen simple d'\u00e9viter la singularit\u00e9\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\u00e9rique\n    else if(deformation == 5) { // Sph\u00e9rique, coordonn\u00e9es tournantes (singularit\u00e9 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\u00e8re, sans singularit\u00e9\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": "// unit test file asinh.hpp for the special functions test suite\r\n\r\n//  (C) Copyright Hubert Holin 2003. Permission to copy, use, modify, sell and\r\n//  distribute this software is granted provided this copyright notice appears\r\n//  in all copies. This software is provided \"as is\" without express or implied\r\n//  warranty, and with no claim as to its suitability for any purpose.\r\n\r\n\r\n#include <functional>\r\n#include <iomanip>\r\n#include <iostream>\r\n\r\n\r\n#include <boost/math/special_functions/asinh.hpp>\r\n\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n\r\ntemplate<typename T>\r\nT    asinh_error_evaluator(T x)\r\n{\r\n    using    ::std::abs;\r\n    using    ::std::sinh;\r\n    using    ::std::cosh;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    using    ::boost::math::asinh;\r\n    \r\n    \r\n    static T const    epsilon = numeric_limits<float>::epsilon();\r\n    \r\n    T                y = sinh(x);\r\n    T                z = asinh(y);\r\n    \r\n    T                absolute_error = abs(z-x);\r\n    T                relative_error = absolute_error*cosh(x);\r\n    T                scaled_error = relative_error/epsilon;\r\n    \r\n    return(scaled_error);\r\n}\r\n\r\n\r\ntemplate<typename T>\r\nvoid    asinh_test(const char * more_blurb)\r\n{\r\n    BOOST_MESSAGE(\"Testing asinh in the real domain for \"\r\n        << more_blurb << \".\");\r\n    \r\n    for    (int i = 0; i <= 100; i++)\r\n    {\r\n        T    x = static_cast<T>(i-50)/static_cast<T>(5);\r\n        \r\n        BOOST_CHECK_PREDICATE(::std::less_equal<T>(), 2,\r\n            (\r\n                asinh_error_evaluator(x),\r\n                static_cast<T>(4)\r\n            ));\r\n    }\r\n}\r\n\r\n\r\nvoid    asinh_manual_check()\r\n{\r\n    BOOST_MESSAGE(\"asinh\");\r\n    \r\n    for    (int i = 0; i <= 100; i++)\r\n    {\r\n        float        xf = static_cast<float>(i-50)/static_cast<float>(5);\r\n        double       xd = static_cast<double>(i-50)/static_cast<double>(5);\r\n        long double  xl =\r\n                static_cast<long double>(i-50)/static_cast<long double>(5);\r\n        \r\n        BOOST_MESSAGE(  ::std::setw(15)\r\n                     << asinh_error_evaluator(xf)\r\n                     << ::std::setw(15)\r\n                     << asinh_error_evaluator(xd)\r\n                     << ::std::setw(15)\r\n                     << asinh_error_evaluator(xl));\r\n    }\r\n    \r\n    BOOST_MESSAGE(\" \");\r\n}\r\n\r\n", "meta": {"hexsha": "2a78ccc0f4b900dbb6d3f519ff35d877eb9d7fc7", "size": 2315, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/asinh_test.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/asinh_test.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/asinh_test.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9186046512, "max_line_length": 80, "alphanum_fraction": 0.5282937365, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5650445895821651}}
{"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 * @file laxwendroffscheme.cc\n * @brief NPDE homework \"LaxWendroffScheme\" code\n * @author Oliver Rietmann\n * @date 29.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"laxwendroffscheme.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace LaxWendroffScheme {\n\nnamespace Constant {\nconstexpr double e = 2.71828182845904523536;\nconstexpr double pi = 3.14159265358979323846;\n}  // namespace Constant\n\nconstexpr double Square(double x) { return x * x; }\n\n/**\n * @brief Computes the right-hand side according to the Lax-Wendroff scheme.\n * @param mu mu^(k-1) (i.e. mu at timestep k-1)\n * @param gamma tau / h, where tau = timestep size and h = spatial meshwidth\n * @return mu^(k) (i.e. mu at timestep k)\n */\n/* SAM_LISTING_BEGIN_0 */\nEigen::VectorXd LaxWendroffRhs(const Eigen::VectorXd &mu, double gamma) {\n  int N = mu.size();\n  Eigen::VectorXd result(N);\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return result;\n}\n\nEigen::VectorXd solveLaxWendroff(const Eigen::VectorXd &u0, double T,\n                                 unsigned int M) {\n  double gamma = 1.0 / Constant::e;\n  Eigen::VectorXd mu = u0;\n  // Main timestepping loop\n  for (int j = 0; j < M; ++j) mu = LaxWendroffRhs(mu, gamma);\n  return mu;\n}\n\n/* SAM_LISTING_END_0 */\n\n/* SAM_LISTING_BEGIN_2 */\n// Build spatial grid\nEigen::VectorXd getXValues(double T, unsigned int M) {\n  double tau = T / M;\n  double h = Constant::e * tau;\n  int j_max = (int)(std::ceil((3.0 * T + 1.0) / h) + 0.5);\n  int j_min = (int)(std::floor(-3.0 * T / h) - 0.5);\n  unsigned int N = j_max - j_min + 1;\n  return Eigen::VectorXd::LinSpaced(N, j_min * h, j_max * h);\n}\nEigen::VectorXd numexpLaxWendroffRP(const Eigen::VectorXi &M) {\n  const double T = 1.0;\n  const int M_size = M.size();\n  Eigen::VectorXd error(M_size);\n  // Initial values for the Riemann problem\n  auto u_initial = [](double x) { return 0.0 <= x ? 1.0 : 0.0; };\n  // Exact solution \\prbeqref{eq:solrp} at time $T = 1.0$\n  auto u_exact = [](double x) {\n    return (x <= 1.0) ? 0.0 : ((Constant::e <= x) ? 1.0 : std::log(x));\n  };\n  //====================\n  // Your code goes here\n  //====================\n  return error;\n}\n/* SAM_LISTING_END_2 */\n\n/**\n * @brief Evaluates the discrete function u at position x by linear\n * interpolation\n * @param u descrete function values at spatial positions y\n * @param y vector of same length as u, representing the nodes of u\n * @return best linear interpolation of u at spacial position x\n */\ndouble eval(const Eigen::VectorXd &u, const Eigen::VectorXd &y, double x) {\n  int N = y.size();\n  double a = y(0);\n  double b = y(N - 1);\n\n  if (x <= a) return u(0);\n  if (b <= x) return u(N - 1);\n\n  double lambda = (x - a) / (b - a);\n  int k0 = (int)(lambda * (N - 1));\n  int k1 = k0 + 1;\n\n  lambda = (x - y(k0)) / (y(k1) - y(k0));\n  return lambda * u(k1) + (1.0 - lambda) * u(k0);\n}\n\n/* SAM_LISTING_BEGIN_9 */\ndouble smoothU0(double x) {\n  return (x < 0.0)\n             ? 0.0\n             : ((1.0 < x) ? 1.0 : Square(std::sin(0.5 * Constant::pi * x)));\n}\nEigen::VectorXd referenceSolution(const Eigen::VectorXd &x) {\n  double T = 1.0;\n  // Reference solution on a very fine mesh\n  unsigned int M = 3200;\n\n  Eigen::VectorXd y = getXValues(T, M);\n  Eigen::VectorXd u0 = y.unaryExpr(&smoothU0);\n  Eigen::VectorXd u = solveLaxWendroff(u0, T, M);\n  int N = x.size();\n  Eigen::VectorXd u_ref(N);\n  // The vector u is larger than u_ref. Use eval() from above the \"evaluate\" u\n  // at the positions x(i) and thus obtain the reference solution u_ref.\n  //====================\n  // Your code goes here\n  //====================\n  return u_ref;\n}\n/* SAM_LISTING_END_9 */\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::VectorXd numexpLaxWendroffSmoothU0(const Eigen::VectorXi &M) {\n  const double T = 1.0;\n  const int M_size = M.size();\n  Eigen::VectorXd error(M_size);\n\n  //====================\n  // Your code goes here\n  //====================\n  return error;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_7 */\nEigen::VectorXd solveGodunov(const Eigen::VectorXd &u0, double T,\n                             unsigned int M) {\n  double tau = T / M;\n  double h = Constant::e * tau;\n  unsigned int N = u0.size();\n  Eigen::VectorXd mu = u0;\n\n  //====================\n  // Your code goes here\n  //====================\n  return mu;\n}\n\n/* SAM_LISTING_END_7 */\n\n/* SAM_LISTING_BEGIN_8 */\nEigen::VectorXd numexpGodunovSmoothU0(const Eigen::VectorXi &M) {\n  const double T = 1.0;\n  const int M_size = M.size();\n  Eigen::VectorXd error(M_size);\n\n  //====================\n  // Your code goes here\n  //====================\n  return error;\n}\n/* SAM_LISTING_END_8 */\n\n}  // namespace LaxWendroffScheme\n", "meta": {"hexsha": "effc7b5b71f90662e306f0c7fbdaed24ebcc946e", "size": 4649, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/LaxWendroffScheme/templates/laxwendroffscheme.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/LaxWendroffScheme/templates/laxwendroffscheme.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/LaxWendroffScheme/templates/laxwendroffscheme.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 27.3470588235, "max_line_length": 78, "alphanum_fraction": 0.5992686599, "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.5650445764375202}}
{"text": "/*\n * utilities_trapz_test.cpp Test fixtures for the trapz function\n *\n * Author:                   Tom Clark (thclark @ github)\n *\n * Copyright (c) 2016-9 Octue Ltd. All Rights Reserved.\n *\n */\n\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\n#include \"utilities/trapz.h\"\n\n\nusing namespace utilities;\n\n\nclass TrapzTest : public ::testing::Test {};\n\n\nTEST_F(TrapzTest, test_colwise_trapz_1_row) {\n\n    // Test that zeros are returned when trying to colwise integrate an array with 1 row\n    Eigen::ArrayXXf integrand(1,4);\n    integrand << 1, 2, 6, 9;\n    Eigen::ArrayXXf integral_correct(1,4);\n    integral_correct<< 0, 0, 0, 0;\n    Eigen::ArrayXXf integral = trapz(integrand);\n    EXPECT_EQ(integral.matrix(), integral_correct.matrix());\n\n}\n\n\nTEST_F(TrapzTest, test_colwise_trapz_2_rows) {\n\n    // Test that uniform spaced integration works on an array with 2 rows\n    Eigen::ArrayXXf integrand(2,4);\n    integrand << 1, 2, 6, 9,\n        3, 1, 7, 2;\n    Eigen::ArrayXXf integral_correct(1,4);\n    integral_correct << 2, 1.5, 6.5, 5.5;\n    Eigen::ArrayXXf integral = trapz(integrand);\n    EXPECT_EQ(integral.matrix(), integral_correct.matrix());\n\n}\n\n\nTEST_F(TrapzTest, test_colwise_trapz_3_rows) {\n\n    // Test that uniform spaced integration works on an array with 3 rows\n    Eigen::ArrayXXf integrand(3,4);\n    integrand << 1, 2, 6, 9,\n                 3, 1, 7, 2,\n                 4, 8, 3, 1;\n    Eigen::ArrayXXf integral_correct(1,4);\n    integral_correct << 5.5, 6, 11.5, 7;\n    Eigen::ArrayXXf integral = trapz(integrand);\n    EXPECT_EQ(integral.matrix(), integral_correct.matrix());\n\n}\n\n\nTEST_F(TrapzTest, test_colwise_nonuniform_trapz) {\n\n    // Test that non-uniform spacing works with an n x 1 spacing array\n    Eigen::ArrayXXf spacing(3, 1);\n    spacing << 2,\n               5,\n               7;\n    Eigen::ArrayXXf integrand(3,4);\n    integrand << 1, 2, 6, 9,\n                 3, 1, 7, 2,\n                 4, 8, 3, 1;\n    Eigen::ArrayXXf integral_correct(1,4);\n    integral_correct << 13, 13.5, 29.5, 19.5;\n    Eigen::ArrayXXf integral(1,4);\n    trapz(integral, spacing, integrand);\n    EXPECT_EQ(integral.matrix(), integral_correct.matrix());\n\n}\n", "meta": {"hexsha": "f671cdbae4c74bd187d5452ad887bcca9a139d18", "size": 2161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/utilities_trapz_test.cpp", "max_stars_repo_name": "octue/es-flow", "max_stars_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_stars_repo_licenses": ["Intel", "MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-01-07T13:55:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T16:30:03.000Z", "max_issues_repo_path": "test/unit/utilities_trapz_test.cpp", "max_issues_repo_name": "octue/es-flow", "max_issues_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_issues_repo_licenses": ["Intel", "MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-09-04T10:40:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-02T10:13:25.000Z", "max_forks_repo_path": "test/unit/utilities_trapz_test.cpp", "max_forks_repo_name": "octue/es-flow", "max_forks_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_forks_repo_licenses": ["Intel", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3536585366, "max_line_length": 88, "alphanum_fraction": 0.6372049977, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.564881315006272}}
{"text": "/*******\nedit_distance: STL and Boost compatible edit distance functions for C++\n\nCopyright (c) 2013 Erik Erlandson\n\nAuthor:  Erik Erlandson <erikerlandson@yahoo.com>\n\nDistributed under the Boost Software License, Version 1.0.\nSee accompanying file LICENSE or copy at\nhttp://www.boost.org/LICENSE_1_0.txt\n*******/\n\n#include <iostream>\n\n// get the edit_distance() function\n#include <boost/algorithm/sequence/edit_distance.hpp>\nusing boost::algorithm::sequence::edit_distance;\n\nint main(int argc, char** argv) {\n    char const* str1 = \"hello, world.\";\n    char const* str2 = \"Hello World!\";\n\n    // Obtain the cost of minimal edit sequence to transform str1 --> str2.\n    // The default cost function defines the cost of insertion, deletion and substitution to be 1.  Elements that are equal cost 0.\n    // The distance should be 7\n    // delete 'h', insert 'H'\n    // delete ','\n    // delete 'w', insert 'W'\n    // delete '.', insert \"!\"\n    unsigned dist = edit_distance(str1, str2);\n    std::cout << \"The edit distance between \\\"\" << str1 << \"\\\" and \\\"\" << str2 << \"\\\" = \" << dist << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "b5f2c172b5bccbd80b1f55e77cb7fd9388e3e5c6", "size": 1109, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/edit_distance_example.cpp", "max_stars_repo_name": "libkeiser/edit_distance", "max_stars_repo_head_hexsha": "9a6b3bd2b0b52e503960834da3599bee0dee868d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-10-22T05:25:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T14:03:12.000Z", "max_issues_repo_path": "example/edit_distance_example.cpp", "max_issues_repo_name": "libkeiser/edit_distance", "max_issues_repo_head_hexsha": "9a6b3bd2b0b52e503960834da3599bee0dee868d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-01-23T20:26:59.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-23T20:26:59.000Z", "max_forks_repo_path": "example/edit_distance_example.cpp", "max_forks_repo_name": "libkeiser/edit_distance", "max_forks_repo_head_hexsha": "9a6b3bd2b0b52e503960834da3599bee0dee868d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-27T04:38:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-27T04:38:41.000Z", "avg_line_length": 31.6857142857, "max_line_length": 131, "alphanum_fraction": 0.6636609558, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.5648796051215462}}
{"text": "/**\n * @file gradientflow_main.cc\n * @brief NPDE homework GradientFlow code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n#include \"gradientflow.h\"\n\nconst static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n                                       Eigen::DontAlignCols, \", \", \"\\n\");\n\nint main() {\n  double T = 0.1;\n  double lambda = 10.0;\n  int N = 10000;\n  std::cout << \"T = \" << T << \", lambda = \" << lambda << std::endl;\n\n  Eigen::Vector2d d(1.0, 0.0);\n  Eigen::Vector2d y0(1.0, 0.0);\n  std::vector<Eigen::VectorXd> Y =\n      GradientFlow::solveGradientFlow(d, lambda, y0, T, N);\n  std::cout << \"Final value (exact): \" << Y.back().transpose().format(CSVFormat)\n            << std::endl;\n\n  double exact = Y.back()(0);\n  Eigen::VectorXi N_list(6);\n  N_list << 10, 20, 40, 80, 160, 320;\n  std::cout << \"Error table:\\n\";\n  std::cout << \"N\\terror norm\" << std::endl;\n  for (int i = 0; i < N_list.size(); ++i) {\n    std::vector<Eigen::VectorXd> Y =\n        GradientFlow::solveGradientFlow(d, lambda, y0, T, N_list(i));\n    double approx = Y.back()(0);\n    std::cout << N << \"\\t\" << std::abs(approx - exact) << \"\\t\" << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "7d4bca70518cc8f4f6cc8edee10057f9e9d0216b", "size": 1278, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/GradientFlow/templates/gradientflow_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/GradientFlow/templates/gradientflow_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/GradientFlow/templates/gradientflow_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7826086957, "max_line_length": 80, "alphanum_fraction": 0.5821596244, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.5648796011871643}}
{"text": "//=======================================================================\n// Copyright (c) 2015\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file frequent-directions.cpp\n * @brief frequent_directions binnary\n * @author Tomasz Strozak\n * @version 1.0\n * @date 2015-07-13\n */\n\n#include \"paal/sketch/frequent_directions.hpp\"\n#include \"paal/utils/functors.hpp\"\n#include \"paal/utils/irange.hpp\"\n#include \"paal/utils/print_collection.hpp\"\n#include \"paal/utils/read_rows.hpp\"\n#include \"paal/utils/system_message.hpp\"\n\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/program_options.hpp>\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\nnamespace utils = paal::utils;\nnamespace po = boost::program_options;\nusing coordinate_t = double;\nusing matrix_t = boost::numeric::ublas::matrix<coordinate_t>;\nusing fd_t = paal::frequent_directions<matrix_t>;\n\nstruct params {\n    size_t m_sketch_rows;\n    size_t m_sketch_compress_size;\n    //TODO\n    //unsigned m_nthread;\n    size_t m_row_buffer_size;\n    bool m_compress_at_end;\n};\n\nvoid m_main(po::variables_map const &vm, params const &p,\n            std::istream &input_stream, std::ostream &output_stream) {\n    fd_t fd_sketch;\n\n    std::vector<std::vector<coordinate_t>> row_buffer;\n    row_buffer.reserve(p.m_row_buffer_size);\n\n    auto ignore_bad_row = [&](std::string const &bad_line) {\n        utils::warning(\"following line will be ignored cause of bad format: \", bad_line);\n        return true;\n    };\n\n    std::size_t rows_count;\n    std::size_t columns_count;\n    if (vm.count(\"model_in\")) {\n        std::ifstream ifs(vm[\"model_in\"].as<std::string>());\n        boost::archive::binary_iarchive ia(ifs);\n        ia >> fd_sketch;\n        auto sketch = fd_sketch.get_sketch().first;\n        rows_count = sketch.size1();\n        columns_count = sketch.size2();\n    }\n    else {\n        paal::read_rows_first_row_size<coordinate_t>\n            (input_stream, row_buffer, p.m_row_buffer_size, ignore_bad_row);\n\n        if(row_buffer.empty()) {\n            utils::failure(\"Empty input data\");\n        }\n\n        rows_count = p.m_sketch_rows;\n        columns_count = boost::size(row_buffer.front());\n        if(vm.count(\"sketch_compress_size\")) {\n            fd_sketch = paal::make_frequent_directions<coordinate_t>(rows_count, columns_count, p.m_sketch_compress_size);\n        }\n        else {\n            fd_sketch = paal::make_frequent_directions<coordinate_t>(rows_count, columns_count);\n        }\n\n        fd_sketch.update_range(row_buffer);\n    }\n\n    while (input_stream.good()) {\n        row_buffer.clear();\n        paal::read_rows<coordinate_t>\n            (input_stream, row_buffer, columns_count, p.m_row_buffer_size, ignore_bad_row);\n        fd_sketch.update_range(row_buffer);\n    }\n\n    if (p.m_compress_at_end) {\n        fd_sketch.compress();\n    }\n\n    auto sketch = fd_sketch.get_sketch().first;\n    boost::numeric::ublas::matrix_range<matrix_t> sketch_range (sketch,\n         boost::numeric::ublas::range(0, fd_sketch.get_sketch().second),\n         boost::numeric::ublas::range(0, columns_count));\n    paal::print_matrix(output_stream, sketch_range, \" \");\n    output_stream << std::endl;\n\n    if (vm.count(\"model_out\")) {\n        std::ofstream ofs(vm[\"model_out\"].as<std::string>());\n        boost::archive::binary_oarchive oa(ofs);\n        oa << fd_sketch;\n    }\n\n}\n\nint main(int argc, char** argv) {\n    params p{};\n\n    po::options_description desc(\"Frequent-directions - \\n\"\\\n            \"suite for a matrix sketching using Singular Value Decomposition\\n\\nUsage:\\n\"\\\n            \"This command will read data from standard input and write computed sketch to standard output:\\n\"\\\n            \"\\tfrequent-directions --sketch_rows numer_of_sketch_rows\\n\\n\"\\\n            \"If you want to read data from an input_file and write computed sketch to an output_file you can use following command:\\n\"\\\n            \"\\tfrequent-directions --input input_file --output output_file -r rows\\n\\n\"\\\n            \"If you want to change compress_size and save model you can use following command:\\n\"\\\n            \"\\tfrequent-directions -i input_file -r rows -s compress_size --model_out model\\n\\n\"\\\n            \"Then if you want to use this model and add additional data:\\n\"\\\n            \"\\tfrequent-directions -i input_file --model_in model\\n\\n\"\\\n            \"Options description\");\n\n    desc.add_options()\n        (\"help,h\", \"help message\")\n        (\"input,i\", po::value<std::string>(), \"path to the file with input data in csv format with space as delimiter, \"\\\n                \"(default read from standart input)\")\n        (\"output,o\", po::value<std::string>(), \"path to the file with result sketch matrix, only nonzero rows are printed, \"\\\n                \"(default write to standart output)\")\n        (\"sketch_rows,r\", po::value<std::size_t>(&p.m_sketch_rows), \"number of sketch rows\")\n        (\"sketch_compress_size,s\", po::value<size_t>(&p.m_sketch_compress_size), \"sketch compress size, \"\\\n                \"(default is half of number of sketch rows)\")\n        (\"model_in\", po::value<std::string>(), \"read the sketch model from this file\")\n        (\"model_out\", po::value<std::string>(), \"write the sketch model to this file\")\n        (\"final_compress\", po::value<bool>(&p.m_compress_at_end)->default_value(true),\n                \"determine if sketch will be compressed after update all data, \"\\\n                \"compression in the final phase is necessary to fulfill sketch approximation ratios\")\n    //TODO\n    //    (\"nthread,n\", po::value<unsigned>(&p.m_nthread)->default_value(std::thread::hardware_concurrency()),\n    //          \"number of threads (default = number of cores)\")\n        (\"row_buffer_size\", po::value<std::size_t>(&p.m_row_buffer_size)->default_value(100000),\n                  \"size of row buffer (default value = 100000)\")\n    ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    auto param_is_set_explicitly = [&vm] (const std::string &param_name) {\n        return vm.count(param_name) > 0 && !vm[param_name].defaulted();\n    };\n\n    if (vm.count(\"help\")) {\n        utils::info(desc);\n        return EXIT_SUCCESS;\n    }\n\n    auto error_with_usage = [&] (const std::string &message) {\n        utils::failure(message, \"\\n\", desc);\n    };\n\n    if (vm.count(\"model_in\") == 0 && vm.count(\"sketch_rows\") == 0) {\n        error_with_usage(\"Input model sketch or number of sketch rows was not set\");\n    }\n\n    if (vm.count(\"model_in\")) {\n        auto ignored = [&](std::string const & param) {\n            if (param_is_set_explicitly(param)) {\n                utils::warning(\"parameter \", param, \" was set, but model_in is used, param \", param, \" is discarded\");\n            }\n        };\n        ignored(\"sketch_rows\");\n        ignored(\"sketch_compress_size\");\n    }\n\n    if (p.m_row_buffer_size <= 0) {\n        error_with_usage(\"Size of row buffer must be positive\");\n    }\n\n    std::ifstream ifs;\n    if (vm.count(\"input\")) {\n        ifs.open(vm[\"input\"].as<std::string>());\n    }\n\n    std::ofstream ofs;\n    if (vm.count(\"output\")) {\n        ofs.open(vm[\"output\"].as<std::string>());\n    }\n\n    m_main(vm, p,\n           vm.count(\"input\") ? ifs : std::cin,\n           vm.count(\"output\") ? ofs : std::cout);\n\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "0f4c1a1d467a28662f1363f4d90dadc6919c625b", "size": 7643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bin/frequent-directions.cpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/frequent-directions.cpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/frequent-directions.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 37.1019417476, "max_line_length": 135, "alphanum_fraction": 0.6282873217, "num_tokens": 1828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059707450325, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5648756027211422}}
{"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": "#include \"main.h\"\r\n#include <Eigen/MPRealSupport>\r\n#include <Eigen/LU>\r\n#include <Eigen/Eigenvalues>\r\n#include <sstream>\r\n\r\nusing namespace mpfr;\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\nvoid test_mpreal_support()\r\n{\r\n  // set precision to 256 bits (double has only 53 bits)\r\n  mpreal::set_default_prec(256);\r\n  typedef Matrix<mpreal,Eigen::Dynamic,Eigen::Dynamic> MatrixXmp;\r\n\r\n  std::cerr << \"epsilon =         \" << NumTraits<mpreal>::epsilon() << \"\\n\";\r\n  std::cerr << \"dummy_precision = \" << NumTraits<mpreal>::dummy_precision() << \"\\n\";\r\n  std::cerr << \"highest =         \" << NumTraits<mpreal>::highest() << \"\\n\";\r\n  std::cerr << \"lowest =          \" << NumTraits<mpreal>::lowest() << \"\\n\";\r\n\r\n  for(int i = 0; i < g_repeat; i++) {\r\n    int s = Eigen::internal::random<int>(1,100);\r\n    MatrixXmp A = MatrixXmp::Random(s,s);\r\n    MatrixXmp B = MatrixXmp::Random(s,s);\r\n    MatrixXmp S = A.adjoint() * A;\r\n    MatrixXmp X;\r\n    \r\n    // Basic stuffs\r\n    VERIFY_IS_APPROX(A.real(), A);\r\n    VERIFY(Eigen::internal::isApprox(A.array().abs2().sum(), A.squaredNorm()));\r\n    VERIFY_IS_APPROX(A.array().exp(),         exp(A.array()));\r\n    VERIFY_IS_APPROX(A.array().abs2().sqrt(), A.array().abs());\r\n    VERIFY_IS_APPROX(A.array().sin(),         sin(A.array()));\r\n    VERIFY_IS_APPROX(A.array().cos(),         cos(A.array()));\r\n    \r\n\r\n    // Cholesky\r\n    X = S.selfadjointView<Lower>().llt().solve(B);\r\n    VERIFY_IS_APPROX((S.selfadjointView<Lower>()*X).eval(),B);\r\n\r\n    // partial LU\r\n    X = A.lu().solve(B);\r\n    VERIFY_IS_APPROX((A*X).eval(),B);\r\n\r\n    // symmetric eigenvalues\r\n    SelfAdjointEigenSolver<MatrixXmp> eig(S);\r\n    VERIFY_IS_EQUAL(eig.info(), Success);\r\n    VERIFY_IS_APPROX((S.selfadjointView<Lower>() * eig.eigenvectors()),\r\n                      eig.eigenvectors() * eig.eigenvalues().asDiagonal());\r\n  }\r\n  \r\n  {\r\n    MatrixXmp A(8,3); A.setRandom();\r\n    // test output (interesting things happen in this code)\r\n    std::stringstream stream;\r\n    stream << A;\r\n  }\r\n}\r\n\r\nextern \"C\" {\r\n#include \"mpreal/dlmalloc.c\"\r\n}\r\n#include \"mpreal/mpreal.cpp\"\r\n", "meta": {"hexsha": "709a2039d47e75dd14a04845c09ea147167a7a82", "size": 2086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen/unsupported/test/mpreal_support.cpp", "max_stars_repo_name": "trondkr/tools", "max_stars_repo_head_hexsha": "ffd1c812b63229e4d5048192488b72d34e5f2901", "max_stars_repo_licenses": ["MIT"], "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/unsupported/test/mpreal_support.cpp", "max_issues_repo_name": "trondkr/tools", "max_issues_repo_head_hexsha": "ffd1c812b63229e4d5048192488b72d34e5f2901", "max_issues_repo_licenses": ["MIT"], "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/unsupported/test/mpreal_support.cpp", "max_forks_repo_name": "trondkr/tools", "max_forks_repo_head_hexsha": "ffd1c812b63229e4d5048192488b72d34e5f2901", "max_forks_repo_licenses": ["MIT"], "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": 32.0923076923, "max_line_length": 85, "alphanum_fraction": 0.5963566635, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "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": "//\n// Created by lei on 4/21/19.\n//\n\n#include \"tgo.hpp\"\n#include \"topography.hpp\"\n\n#include <armadillo>\n#include <nlopt.hpp>\n#include <fmt/format.h>\n#include <functional>\n\nusing namespace std::placeholders;\n\nOptimizeResult::OptimizeResult(const arma::vec &xl,\n                               const arma::vec &fl,\n                               double x, double f) :\n        xl(xl), funl(fl), x(x), f(f) {}\n\nTGO *TGO::pThis = nullptr;\n\nTGO::TGO(std::function<double(double)> functor,\n         int nsample, int nk,\n         double xmin, double xmax, double xtol) :\n        functor_(std::move(functor)),\n        nsample_(nsample),\n        nk_(nk),\n        xmin_(xmin),\n        xmax_(xmax),\n        xtol_(xtol) { \n    pThis = this;\n}\n\n\ndouble TGO::func_nlopt(const std::vector<double> &x,\n                       std::vector<double> &grad,\n                       void *f_data) {\n    if (pThis == nullptr) {\n        exit(-1);\n    }\n    double fev = pThis->functor_(x[0]);\n    if (!grad.empty()) {\n        grad[0] = approx_grad(x[0], fev, epsilon_);\n    }\n    return fev;\n}\n\n\ndouble TGO::approx_grad(double x, double f, double epsilon) {\n    if (pThis == nullptr) {\n        exit(-1);\n    }\n    double fev = pThis->functor_(x + epsilon);\n    double grad = (fev - f) / epsilon;\n    return grad;\n}\n\n\nOptimizeResult TGO::optimize() {\n    arma::vec x = arma::linspace(xmin_, xmax_, nsample_);\n    arma::vec fev(nsample_);\n    for (auto i = 0; i < nsample_; ++i) {\n        fev(i) = functor_(x(i));\n    }\n    Topography topo(x, fev, nk_);\n    std::vector<double> min_pool = topo.minimize_pool();\n    std::vector<double> x_local, f_local;\n\n    nlopt::opt opt(nlopt::LD_SLSQP, 1);\n    std::vector<double> lb{xmin_}, ub{xmax_};\n    opt.set_min_objective(func_nlopt, nullptr);\n    opt.set_lower_bounds(lb);\n    opt.set_upper_bounds(ub);\n    opt.set_xtol_abs(xtol_);\n    for (auto x0 : min_pool) {\n        std::vector<double> xl{x0};\n        double fl = 1.0e20;\n        try {\n            nlopt::result result = opt.optimize(xl, fl);\n        } catch (std::runtime_error &err) {\n            fmt::print(\"{}\\n\", err.what());\n        }\n        x_local.push_back(xl[0]);\n        f_local.push_back(fl);\n    }\n    int num_minimal = x_local.size();\n    arma::vec xl(&x_local[0], num_minimal, false, true);\n    arma::vec fl(&f_local[0], num_minimal, false, true);\n    int ind_best = arma::index_min(fl);\n    double x_best = xl(ind_best);\n    double f_best = fl(ind_best);\n    OptimizeResult result(xl, fl, x_best, f_best);\n    return result;\n}\n", "meta": {"hexsha": "fe2523ee262fb9fdcbf3b9e70e69c8daeac9e290", "size": 2514, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tgo.cc", "max_stars_repo_name": "pan3rock/tgo1d-cxx", "max_stars_repo_head_hexsha": "9553b48279c918e0f19ca3a22538caf1a2eff296", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tgo.cc", "max_issues_repo_name": "pan3rock/tgo1d-cxx", "max_issues_repo_head_hexsha": "9553b48279c918e0f19ca3a22538caf1a2eff296", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tgo.cc", "max_forks_repo_name": "pan3rock/tgo1d-cxx", "max_forks_repo_head_hexsha": "9553b48279c918e0f19ca3a22538caf1a2eff296", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4631578947, "max_line_length": 61, "alphanum_fraction": 0.568814638, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.564875586066269}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/optimization/optimization_agglomerate_vector.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_agglomerate_vector);\n\nBOOST_AUTO_TEST_CASE(test_case)\n{\n  typedef ublas::vector<size_t>       idx_vector_type;\n  typedef ublas::vector<double>       vector_type;\n\n  idx_vector_type new2old;\n  idx_vector_type old2new;\n\n  old2new.resize(10,false);\n  new2old.resize(10,false);\n\n  old2new( 2 ) = 0 ;\n  old2new( 4 ) = 1 ;\n  old2new( 6 ) = 2 ;\n  old2new( 9 ) = 3 ;\n  old2new( 1 ) = 4 ;\n  old2new( 3 ) = 5 ;\n  old2new( 8 ) = 6 ;\n  old2new( 0 ) = 7 ;\n  old2new( 5 ) = 8 ;\n  old2new( 7 ) = 9 ;\n\n  new2old( 0 ) = 2 ;\n  new2old( 1 ) = 4 ;\n  new2old( 2 ) = 6 ;\n  new2old( 3 ) = 9 ;\n  new2old( 4 ) = 1 ;\n  new2old( 5 ) = 3 ;\n  new2old( 6 ) = 8 ;\n  new2old( 7 ) = 0 ;\n  new2old( 8 ) = 5 ;\n  new2old( 9 ) = 7 ;\n\n\n  vector_type x_a;\n  vector_type x_b;\n  vector_type x;\n  x.resize(10,false);\n\n  x_a.resize(4,false);\n  x_b.resize(6,false);\n\n  x_a(0) = 1.0;\n  x_a(1) = 2.0;\n  x_a(2) = 3.0;\n  x_a(3) = 4.0;\n\n  x_b(0) = 5.0;\n  x_b(1) = 6.0;\n  x_b(2) = 7.0;\n  x_b(3) = 8.0;\n  x_b(4) = 9.0;\n  x_b(5) = 10.0;\n\n  x.clear();\n\n  OpenTissue::math::optimization::agglomerate_vector( x_a, x_b, new2old, x);\n\n  double tol = 0.01;\n\n  BOOST_CHECK_CLOSE( double( x( 2 ) ), double( x_a(0) ), tol );\n  BOOST_CHECK_CLOSE( double( x( 4 ) ), double( x_a(1) ), tol );\n  BOOST_CHECK_CLOSE( double( x( 6 ) ), double( x_a(2) ), tol );\n  BOOST_CHECK_CLOSE( double( x( 9 ) ), double( x_a(3) ), tol );\n  BOOST_CHECK_CLOSE( double( x( 1 ) ), double( x_b(0) ), tol );\n  BOOST_CHECK_CLOSE( double( x( 3 ) ), double( x_b(1) ), tol );\n  BOOST_CHECK_CLOSE( double( x( 8 ) ), double( x_b(2) ), tol );\n  BOOST_CHECK_CLOSE( double( x( 0 ) ), double( x_b(3) ), tol );\n  BOOST_CHECK_CLOSE( double( x( 5 ) ), double( x_b(4) ), tol );\n  BOOST_CHECK_CLOSE( double( x( 7 ) ), double( x_b(5) ), tol );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "fe9fa367f891dce4a64a6d4caadbc82f466e117f", "size": 2453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/agglomerate_vector/src/unit_agglomerate_vector.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/agglomerate_vector/src/unit_agglomerate_vector.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/agglomerate_vector/src/unit_agglomerate_vector.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 26.376344086, "max_line_length": 78, "alphanum_fraction": 0.6416632695, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5648755839447677}}
{"text": "//\r\n// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n\r\n#include <OpenTissue/core/math/math_basic_types.h>\r\n#include <OpenTissue/collision/gjk/gjk_voronoi_simplex_solver_policy.h>\r\n#include <OpenTissue/collision/gjk/gjk_compute_closest_points.h>\r\n#include <OpenTissue/collision/gjk/gjk_support_functors.h>\r\n\r\n\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <OpenTissue/utility/utility_push_boost_filter.h>\r\n#include <boost/test/auto_unit_test.hpp>\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\r\n\r\n#include <cmath>\r\n\r\nusing namespace OpenTissue;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_collision_gjk_compute_closest_points);\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(case_by_case_testing)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n\r\n  typedef math_types::quaternion_type                      quaternion_type;\r\n  typedef math_types::vector3_type                         vector3_type;\r\n  typedef math_types::real_type                            real_type;\r\n  typedef math_types::coordsys_type                        transformation_type;\r\n  typedef math_types::value_traits                         value_traits;\r\n\r\n  OpenTissue::gjk::VoronoiSimplexSolverPolicy const simplex_solver_policy = OpenTissue::gjk::VoronoiSimplexSolverPolicy();\r\n\r\n  OpenTissue::gjk::Sphere<math_types> const supportA;\r\n  OpenTissue::gjk::Sphere<math_types> const supportB;\r\n\r\n  size_t    const max_iterations       = 100u;\r\n  real_type const absolute_tolerance   = boost::numeric_cast<real_type>(10e-6);\r\n  real_type const relative_tolerance   = boost::numeric_cast<real_type>(10e-6);\r\n  real_type const stagnation_tolerance = boost::numeric_cast<real_type>(10e-15);\r\n\r\n  // Two unit-spheres placed ontop of each other\r\n  {\r\n    transformation_type transformA;\r\n    transformation_type transformB;\r\n\r\n    vector3_type a;\r\n    vector3_type b;\r\n    size_t iterations     = 0u;\r\n    size_t status         = 0u;\r\n    real_type distance    = value_traits::infinity();\r\n\r\n\r\n    transformA.T().clear();\r\n    transformA.Q().identity();\r\n    transformB.T().clear();\r\n    transformB.Q().identity();\r\n\r\n    OpenTissue::gjk::compute_closest_points(\r\n      transformA\r\n      , supportA\r\n      , transformB\r\n      , supportB\r\n      , a\r\n      , b\r\n      , distance\r\n      , iterations\r\n      , status\r\n      , absolute_tolerance\r\n      , relative_tolerance\r\n      , stagnation_tolerance\r\n      , max_iterations\r\n      , simplex_solver_policy\r\n      );\r\n\r\n\r\n    real_type true_distance = length( transformA.T() - transformB.T() ) - value_traits::two();\r\n\r\n    std::cout << \"\\tstatus = \" << OpenTissue::gjk::get_status_message(status) << std::endl;\r\n    std::cout << \"\\tdistance = \" << distance << std::endl;\r\n    std::cout << \"\\titerations = \" << iterations << std::endl;\r\n    std::cout << \"\\ttrue distance = \" << true_distance << std::endl;\r\n\r\n  }\r\n  // Two unit-spheres overlapping but both placed on the x-axis\r\n  {\r\n    transformation_type transformA;\r\n    transformation_type transformB;\r\n\r\n    vector3_type a;\r\n    vector3_type b;\r\n    size_t iterations     = 0u;\r\n    size_t status         = 0u;\r\n    real_type distance    = value_traits::infinity();\r\n\r\n\r\n    transformA.T().clear();\r\n    transformA.Q().identity();\r\n    transformA.T()(0) = -1.5;\r\n    transformB.T().clear();\r\n    transformB.Q().identity();\r\n\r\n    OpenTissue::gjk::compute_closest_points(\r\n      transformA\r\n      , supportA\r\n      , transformB\r\n      , supportB\r\n      , a\r\n      , b\r\n      , distance\r\n      , iterations\r\n      , status\r\n      , absolute_tolerance\r\n      , relative_tolerance\r\n      , stagnation_tolerance\r\n      , max_iterations\r\n      , simplex_solver_policy\r\n      );\r\n\r\n    real_type true_distance = length( transformA.T() - transformB.T() ) - value_traits::two();\r\n\r\n    std::cout << \"\\tstatus = \" << OpenTissue::gjk::get_status_message(status) << std::endl;\r\n    std::cout << \"\\tdistance = \" << distance << std::endl;\r\n    std::cout << \"\\titerations = \" << iterations << std::endl;\r\n    std::cout << \"\\ttrue distance = \" << true_distance << std::endl;\r\n  }\r\n  // Two unit-spheres exactly touching in one point (= one intersection point) and but both placed on the x-axis\r\n  {\r\n    transformation_type transformA;\r\n    transformation_type transformB;\r\n\r\n    vector3_type a;\r\n    vector3_type b;\r\n    size_t iterations     = 0u;\r\n    size_t status         = 0u;\r\n    real_type distance    = value_traits::infinity();\r\n\r\n\r\n    transformA.T().clear();\r\n    transformA.Q().identity();\r\n    transformA.T()(0) = -2.0;\r\n    transformB.T().clear();\r\n    transformB.Q().identity();\r\n\r\n    OpenTissue::gjk::compute_closest_points(\r\n      transformA\r\n      , supportA\r\n      , transformB\r\n      , supportB\r\n      , a\r\n      , b\r\n      , distance\r\n      , iterations\r\n      , status\r\n      , absolute_tolerance\r\n      , relative_tolerance\r\n      , stagnation_tolerance\r\n      , max_iterations\r\n      , simplex_solver_policy\r\n      );\r\n\r\n\r\n    real_type true_distance = length( transformA.T() - transformB.T() ) - value_traits::two();\r\n\r\n    std::cout << \"\\tstatus = \" << OpenTissue::gjk::get_status_message(status) << std::endl;\r\n    std::cout << \"\\tdistance = \" << distance << std::endl;\r\n    std::cout << \"\\titerations = \" << iterations << std::endl;\r\n    std::cout << \"\\ttrue distance = \" << true_distance << std::endl;\r\n\r\n  }\r\n  // Two unit-spheres non-overlapping but both placed on the x-axis\r\n  {\r\n    transformation_type transformA;\r\n    transformation_type transformB;\r\n\r\n    vector3_type a;\r\n    vector3_type b;\r\n    size_t iterations     = 0u;\r\n    size_t status         = 0u;\r\n    real_type distance    = value_traits::infinity();\r\n\r\n\r\n    transformA.T().clear();\r\n    transformA.Q().identity();\r\n    transformA.T()(0) = -2.5;\r\n    transformB.T().clear();\r\n    transformB.Q().identity();\r\n\r\n    OpenTissue::gjk::compute_closest_points(\r\n      transformA\r\n      , supportA\r\n      , transformB\r\n      , supportB\r\n      , a\r\n      , b\r\n      , distance\r\n      , iterations\r\n      , status\r\n      , absolute_tolerance\r\n      , relative_tolerance\r\n      , stagnation_tolerance\r\n      , max_iterations\r\n      , simplex_solver_policy\r\n      );\r\n\r\n\r\n    real_type true_distance = length( transformA.T() - transformB.T() ) - value_traits::two();\r\n\r\n    std::cout << \"\\tstatus = \" << OpenTissue::gjk::get_status_message(status) << std::endl;\r\n    std::cout << \"\\tdistance = \" << distance << std::endl;\r\n    std::cout << \"\\titerations = \" << iterations << std::endl;\r\n    std::cout << \"\\ttrue distance = \" << true_distance << std::endl;\r\n  }\r\n\r\n\r\n\r\n}\r\n\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(random_test)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n\r\n  typedef math_types::quaternion_type                      quaternion_type;\r\n  typedef math_types::vector3_type                         vector3_type;\r\n  typedef math_types::real_type                            real_type;\r\n  typedef math_types::coordsys_type                        transformation_type;\r\n  typedef math_types::value_traits                         value_traits;\r\n\r\n  typedef OpenTissue::gjk::Simplex<vector3_type>           simplex_type;\r\n\r\n\r\n  OpenTissue::gjk::VoronoiSimplexSolverPolicy const simplex_solver_policy = OpenTissue::gjk::VoronoiSimplexSolverPolicy();\r\n\r\n  OpenTissue::gjk::Sphere<math_types> const supportA;\r\n  OpenTissue::gjk::Sphere<math_types> const supportB;\r\n\r\n  size_t    const max_iterations       = 100u;\r\n  real_type const absolute_tolerance   = boost::numeric_cast<real_type>(10e-6);\r\n  real_type const relative_tolerance   = boost::numeric_cast<real_type>(10e-10);\r\n  real_type const stagnation_tolerance = boost::numeric_cast<real_type>(0.0);\r\n\r\n  for(size_t i=0;i<100u;++i)\r\n  {\r\n    transformation_type transformA;\r\n    transformation_type transformB;\r\n\r\n    quaternion_type Q;\r\n    vector3_type a;\r\n    vector3_type b;\r\n    size_t iterations     = 0u;\r\n    size_t status         = 0u;\r\n    real_type distance    = value_traits::infinity();\r\n\r\n\r\n    OpenTissue::math::random( transformA.T(), -2.0, 2.0 );\r\n    OpenTissue::math::random( transformB.T(), -2.0, 2.0 );\r\n    Q.random();\r\n    transformA.Q() = OpenTissue::math::unit ( Q );\r\n    Q.random();\r\n    transformB.Q() = OpenTissue::math::unit ( Q );\r\n\r\n    OpenTissue::gjk::compute_closest_points(\r\n      transformA\r\n      , supportA\r\n      , transformB\r\n      , supportB\r\n      , a\r\n      , b\r\n      , distance\r\n      , iterations\r\n      , status\r\n      , absolute_tolerance\r\n      , relative_tolerance\r\n      , stagnation_tolerance\r\n      , max_iterations\r\n      , simplex_solver_policy\r\n      );\r\n\r\n    real_type true_distance = length( transformA.T() - transformB.T() ) - value_traits::two();\r\n\r\n    if(  true_distance > absolute_tolerance )\r\n    {\r\n      BOOST_CHECK_CLOSE( true_distance, distance, 0.05 );\r\n\r\n      BOOST_CHECK( status != OpenTissue::gjk::ABSOLUTE_CONVERGENCE );            // Would indicate penetration\r\n      BOOST_CHECK( status != OpenTissue::gjk::INTERSECTION );                    // Would indicate penetration\r\n      BOOST_CHECK( status != OpenTissue::gjk::ITERATING );                       // Would indicate internal error in GJK\r\n      BOOST_CHECK( status != OpenTissue::gjk::EXCEEDED_MAX_ITERATIONS_LIMIT );   // Would indicate internal error in GJK\r\n      BOOST_CHECK( status != OpenTissue::gjk::NON_DESCEND_DIRECTION );           // Would indicate internal error in GJK\r\n      //BOOST_CHECK( status != OpenTissue::gjk::RELATIVE_CONVERGENCE );          // Would indicate convergence to positive distance\r\n      //BOOST_CHECK( status != OpenTissue::gjk::SIMPLEX_EXPANSION_FAILED );      // Would indicate convergence to positive distance\r\n      //BOOST_CHECK( status != OpenTissue::gjk::STAGNATION );                    // Would indicate convergence to positive distance\r\n      //BOOST_CHECK( status != OpenTissue::gjk::LOWER_ERROR_BOUND_CONVERGENCE ); // Would indicate convergence to positive distance\r\n    }\r\n    else\r\n    {\r\n      BOOST_CHECK( 0.0 <= distance );\r\n      BOOST_CHECK( distance < absolute_tolerance );\r\n\r\n      BOOST_CHECK( status != OpenTissue::gjk::STAGNATION );                     // Can only occur in case of positive distance\r\n      BOOST_CHECK( status != OpenTissue::gjk::LOWER_ERROR_BOUND_CONVERGENCE );  // Can only occur in case of positive distance\r\n      BOOST_CHECK( status != OpenTissue::gjk::RELATIVE_CONVERGENCE );           // Can only occur in case of positive distance\r\n      BOOST_CHECK( status != OpenTissue::gjk::SIMPLEX_EXPANSION_FAILED );       // Can only occur in case of positive distance\r\n      BOOST_CHECK( status != OpenTissue::gjk::ITERATING );                      // Would indicate internal error in GJK\r\n      BOOST_CHECK( status != OpenTissue::gjk::EXCEEDED_MAX_ITERATIONS_LIMIT );  // Would indicate internal error in GJK\r\n      BOOST_CHECK( status != OpenTissue::gjk::NON_DESCEND_DIRECTION );          // Would indicate internal error in GJK\r\n      //BOOST_CHECK( status != OpenTissue::gjk::ABSOLUTE_CONVERGENCE );         // Indicates penetration\r\n      //BOOST_CHECK( status != OpenTissue::gjk::INTERSECTION );                 // Indicates penetration\r\n    }\r\n\r\n    OpenTissue::gjk::compute_closest_points(\r\n      transformA\r\n      , supportA\r\n      , transformB\r\n      , supportB\r\n      , a\r\n      , b\r\n      , distance\r\n      , status\r\n      );\r\n\r\n    if(  true_distance > absolute_tolerance )\r\n    {\r\n      BOOST_CHECK_CLOSE( true_distance, distance, 0.05 );\r\n\r\n      BOOST_CHECK( status != OpenTissue::gjk::ABSOLUTE_CONVERGENCE );            // Would indicate penetration\r\n      BOOST_CHECK( status != OpenTissue::gjk::INTERSECTION );                    // Would indicate penetration\r\n      BOOST_CHECK( status != OpenTissue::gjk::ITERATING );                       // Would indicate internal error in GJK\r\n      BOOST_CHECK( status != OpenTissue::gjk::EXCEEDED_MAX_ITERATIONS_LIMIT );   // Would indicate internal error in GJK\r\n      BOOST_CHECK( status != OpenTissue::gjk::NON_DESCEND_DIRECTION );           // Would indicate internal error in GJK\r\n      //BOOST_CHECK( status != OpenTissue::gjk::RELATIVE_CONVERGENCE );          // Would indicate convergence to positive distance\r\n      //BOOST_CHECK( status != OpenTissue::gjk::SIMPLEX_EXPANSION_FAILED );      // Would indicate convergence to positive distance\r\n      //BOOST_CHECK( status != OpenTissue::gjk::STAGNATION );                    // Would indicate convergence to positive distance\r\n      //BOOST_CHECK( status != OpenTissue::gjk::LOWER_ERROR_BOUND_CONVERGENCE ); // Would indicate convergence to positive distance\r\n    }\r\n    else\r\n    {\r\n      BOOST_CHECK( 0.0 <= distance );\r\n      BOOST_CHECK( distance < absolute_tolerance );\r\n\r\n      BOOST_CHECK( status != OpenTissue::gjk::STAGNATION );                     // Can only occur in case of positive distance\r\n      BOOST_CHECK( status != OpenTissue::gjk::LOWER_ERROR_BOUND_CONVERGENCE );  // Can only occur in case of positive distance\r\n      BOOST_CHECK( status != OpenTissue::gjk::RELATIVE_CONVERGENCE );           // Can only occur in case of positive distance\r\n      BOOST_CHECK( status != OpenTissue::gjk::SIMPLEX_EXPANSION_FAILED );       // Can only occur in case of positive distance\r\n      BOOST_CHECK( status != OpenTissue::gjk::ITERATING );                      // Would indicate internal error in GJK\r\n      BOOST_CHECK( status != OpenTissue::gjk::EXCEEDED_MAX_ITERATIONS_LIMIT );  // Would indicate internal error in GJK\r\n      BOOST_CHECK( status != OpenTissue::gjk::NON_DESCEND_DIRECTION );          // Would indicate internal error in GJK\r\n      //BOOST_CHECK( status != OpenTissue::gjk::ABSOLUTE_CONVERGENCE );         // Indicates penetration\r\n      //BOOST_CHECK( status != OpenTissue::gjk::INTERSECTION );                 // Indicates penetration\r\n    }\r\n  }\r\n}\r\n\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(cylinder_test)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n\r\n  typedef math_types::quaternion_type                      quaternion_type;\r\n  typedef math_types::vector3_type                         vector3_type;\r\n  typedef math_types::real_type                            real_type;\r\n  typedef math_types::coordsys_type                        transformation_type;\r\n  typedef math_types::value_traits                         value_traits;\r\n\r\n  typedef OpenTissue::gjk::Simplex<vector3_type>           simplex_type;\r\n\r\n  OpenTissue::gjk::VoronoiSimplexSolverPolicy const simplex_solver_policy = OpenTissue::gjk::VoronoiSimplexSolverPolicy();\r\n\r\n  // We let the cylinder move around the sphere in a fixed distance. Thus\r\n  // we always know the closest point by construction.\r\n  OpenTissue::gjk::Sphere<math_types> const supportA;\r\n  OpenTissue::gjk::Cylinder<math_types> const supportB;\r\n\r\n  size_t    const max_iterations       = 1000u;\r\n  real_type const absolute_tolerance   = boost::numeric_cast<real_type>(0.0);\r\n  real_type const relative_tolerance   = boost::numeric_cast<real_type>(10e-10); // Don't be to over agressive!\r\n  real_type const stagnation_tolerance = boost::numeric_cast<real_type>(0.0);\r\n\r\n  real_type rad_x = value_traits::zero();\r\n  real_type rad_z = value_traits::zero();\r\n\r\n  for(size_t i=0;i<100u;++i)\r\n  {\r\n    transformation_type transformA;\r\n    transformation_type transformB;\r\n\r\n    quaternion_type Qx,Qz;\r\n    vector3_type a;\r\n    vector3_type b;\r\n    size_t iterations     = 0u;\r\n    size_t status         = 0u;\r\n    real_type distance    = value_traits::infinity();\r\n\r\n    // Place sphere at origin\r\n    transformA.T().clear();\r\n    transformA.Q().identity();\r\n\r\n    // Place cylinder a fixed distance away from sphere\r\n    transformB.T().clear();\r\n    transformB.Q().identity();\r\n\r\n    // Minimum distance between sphere and cylinder is fixed by design\r\n\r\n    // The unrotated cloest points\r\n    vector3_type tst_a = vector3_type(1.0, 0.0, 0.0);\r\n    vector3_type tst_b = vector3_type(1.1, 0.0, 0.0);\r\n\r\n    // Apply some rotation to the cylinder, which does not alter the closest points\r\n    Qx.Rx( rad_x );\r\n    Qz.Rz( rad_z );\r\n    rad_x += value_traits::pi()/100.0;\r\n    rad_z += value_traits::pi()/100.0;\r\n\r\n    transformB.Q() = prod( Qz, prod( Qx , transformB.Q() ));\r\n    transformB.T() = Qz.rotate( vector3_type( 2.1, 0.0, 0.0 ) );\r\n\r\n    // Update closest points with rotation\r\n    tst_a = Qz.rotate(tst_a);\r\n    tst_b = Qz.rotate(tst_b);\r\n\r\n    OpenTissue::gjk::compute_closest_points(\r\n      transformA\r\n      , supportA\r\n      , transformB\r\n      , supportB\r\n      , a\r\n      , b\r\n      , distance\r\n      , iterations\r\n      , status\r\n      , absolute_tolerance\r\n      , relative_tolerance\r\n      , stagnation_tolerance\r\n      , max_iterations\r\n      , simplex_solver_policy\r\n      );\r\n\r\n    // Test if closest distance was correct\r\n    BOOST_CHECK_CLOSE( 0.1, distance, 0.01 );\r\n\r\n    // Test if status code was as expected\r\n      BOOST_CHECK( status != OpenTissue::gjk::ABSOLUTE_CONVERGENCE );            // Would indicate penetration\r\n      BOOST_CHECK( status != OpenTissue::gjk::INTERSECTION );                    // Would indicate penetration\r\n      BOOST_CHECK( status != OpenTissue::gjk::ITERATING );                       // Would indicate internal error in GJK\r\n      BOOST_CHECK( status != OpenTissue::gjk::EXCEEDED_MAX_ITERATIONS_LIMIT );   // Would indicate internal error in GJK\r\n      BOOST_CHECK( status != OpenTissue::gjk::NON_DESCEND_DIRECTION );           // Would indicate internal error in GJK\r\n      //BOOST_CHECK( status != OpenTissue::gjk::RELATIVE_CONVERGENCE );          // Would indicate convergence to positive distance\r\n      //BOOST_CHECK( status != OpenTissue::gjk::SIMPLEX_EXPANSION_FAILED );      // Would indicate convergence to positive distance\r\n      //BOOST_CHECK( status != OpenTissue::gjk::STAGNATION );                    // Would indicate convergence to positive distance\r\n      //BOOST_CHECK( status != OpenTissue::gjk::LOWER_ERROR_BOUND_CONVERGENCE ); // Would indicate convergence to positive distance\r\n\r\n    // Test if closest points make sense\r\n    BOOST_CHECK( fabs(a(0) - tst_a(0)) < 10e-6 );\r\n    BOOST_CHECK( fabs(a(1) - tst_a(1)) < 10e-6 );\r\n    BOOST_CHECK( fabs(a(2) - tst_a(2)) < 10e-6 );\r\n\r\n    BOOST_CHECK( fabs(b(0) - tst_b(0)) < 10e-6 );\r\n    BOOST_CHECK( fabs(b(1) - tst_b(1)) < 10e-6 );\r\n    BOOST_CHECK( fabs(b(2) - tst_b(2)) < 10e-6 );\r\n  }\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "2498e64fdbff6932e86faf5ac62a362d5e7b3086", "size": 18552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/collision/gjk/closest_points/src/unit_closest_points.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/collision/gjk/closest_points/src/unit_closest_points.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/collision/gjk/closest_points/src/unit_closest_points.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 39.0568421053, "max_line_length": 132, "alphanum_fraction": 0.6375592928, "num_tokens": 4494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.5648755672898941}}
{"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": "//\n// Libor Novak\n// 04/12/2017\n//\n// Various kinds of statistics on the accumulators - to find out if it will gives us some interesting extra\n// information.\n//\n\n#include <caffe/caffe.hpp>\n#include \"caffe/util/bbtxt.hpp\"\n\n// This code only works with OpenCV!\n#ifdef USE_OPENCV\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <algorithm>\n#include <iosfwd>\n#include <memory>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n\nnamespace {\n\n    class Hist2D\n    {\n    public:\n\n        Hist2D (double xmin, double xmax, double ymin, double ymax, int num_bins)\n            : xmin(xmin), xmax(xmax), ymin(ymin), ymax(ymax),\n              xspread(xmax-xmin), yspread(ymax-ymin),\n              hist(num_bins, num_bins, CV_64FC1, cv::Scalar(0)),\n              counts(num_bins, num_bins, CV_64FC1, cv::Scalar(0))\n        {\n        }\n\n        void addEntry (double x, double y, double weight=1.0)\n        {\n            int col = std::round((x - this->xmin) / this->xspread * hist.cols);\n            int row = std::round((y - this->ymin) / this->yspread * hist.rows);\n\n            if (col >= 0 && row >= 0 && col < hist.cols && row < hist.rows)\n            {\n                hist.at<double>(row, col) += weight;\n                counts.at<double>(row, col) += 1.0;\n            }\n            else\n            {\n                std::cout << \"Out of bounds: \" << x << \", \" << y << \" => \" << col << \", \" << row << std::endl;\n            }\n        }\n\n        cv::Mat normalized ()\n        {\n            cv::Mat hist_norm; this->hist.copyTo(hist_norm);\n            double m; cv::minMaxLoc(hist_norm, 0, &m);\n\n            hist_norm *= 1.0 / m;\n\n            return hist_norm;\n        }\n\n        cv::Mat countNormalized ()\n        {\n            cv::Mat hist_norm;\n            cv::divide(this->hist, this->counts, hist_norm);\n            return hist_norm;\n        }\n\n        cv::Mat countNormalizedNormalized ()\n        {\n            cv::Mat hist_norm;\n            cv::divide(this->hist, this->counts, hist_norm);\n\n            double m; cv::minMaxLoc(hist_norm, 0, &m);\n            hist_norm *= 1.0 / m;\n\n            return hist_norm;\n        }\n\n        friend std::ostream& operator<< (std::ostream& os, const Hist2D &h);\n\n\n        // --------------------------------------- PUBLIC MEMBERS ---------------------------------------- //\n        double xmin, xmax, ymin, ymax;\n        double xspread, yspread;\n        cv::Mat hist;\n        cv::Mat counts;\n        int total;\n    };\n\n\n    std::ostream& operator<< (std::ostream& os, const Hist2D &h)\n    {\n        os << h.hist;\n        return os;\n    }\n\n\n    std::vector<Hist2D> hist_wh_neg;\n    std::vector<Hist2D> hist_tl_neg;\n    std::vector<Hist2D> hist_br_neg;\n    std::vector<Hist2D> hist_wh_pos;\n    std::vector<Hist2D> hist_tl_pos;\n    std::vector<Hist2D> hist_br_pos;\n\n    std::vector<Hist2D> hist_wh_car_g_bb;\n    std::vector<Hist2D> hist_wh_notcar_g_bb;\n\n}\n\n\n/**\n * @brief Wraps the input layer into a vector of cv::Mat so we could assign data to it more easily\n * @param input_layer Pointer to the net input layer blob\n * @param input_channels Vector of cv::Mat, which will be assigned\n */\nvoid wrapInputLayer (caffe::Blob<float>* input_layer, std::vector<cv::Mat> &out_input_channels)\n{\n    out_input_channels.clear();\n\n    int height = input_layer->shape(2);\n    int width  = input_layer->shape(3);\n\n    float* input_data = input_layer->mutable_cpu_data();\n\n    for (int i = 0; i < input_layer->shape(1); ++i)\n    {\n        cv::Mat channel(height, width, CV_32FC1, input_data);\n        out_input_channels.push_back(channel);\n        input_data += width * height;\n    }\n}\n\n\nvoid histogramOfCoords (caffe::Blob<float> *output, int a, const std::string &name, const std::vector<BB2D> &gt_bbs)\n{\n    // Build probabilistic target (ground truth) accumulator - we need it to determine positive and negative\n    // pixels\n    static std::map<std::string, std::pair<double, double>> size_bounds;\n    static std::map<std::string, double> scales;\n    if (size_bounds.size() == 0)\n    {\n        // WARNING! These are size bounds for \"macc_0.3_r2_x2_to_x16\"!!\n        size_bounds.insert(std::make_pair(\"acc_x2\", std::make_pair(22.25, 55.5)));\n        size_bounds.insert(std::make_pair(\"acc_x4\", std::make_pair(44.5, 111.0)));\n        size_bounds.insert(std::make_pair(\"acc_x8\", std::make_pair(89.0, 222.0)));\n        size_bounds.insert(std::make_pair(\"acc_x16\", std::make_pair(178.0, 444.0)));\n        scales.insert(std::make_pair(\"acc_x2\", 2.0));\n        scales.insert(std::make_pair(\"acc_x4\", 4.0));\n        scales.insert(std::make_pair(\"acc_x8\", 8.0));\n        scales.insert(std::make_pair(\"acc_x16\", 16.0));\n    }\n    cv::Mat acc_gt_prob(output->shape(2), output->shape(3), CV_32FC1, cv::Scalar(0.0f));\n    for (const BB2D &gt_bb: gt_bbs)\n    {\n        double size = std::max(gt_bb.width(), gt_bb.height());\n        if (size > size_bounds[name].first && size < size_bounds[name].second)\n        {\n            // This ground truth should be detected by this accumulator\n            cv::Point2d co = gt_bb.center();\n            cv::circle(acc_gt_prob, cv::Point(co.x/scales[name], co.y/scales[name]), 3, cv::Scalar(1.0f), -1);\n        }\n    }\n\n//    cv::imshow(\"gt acc \" + std::to_string(a), acc_gt_prob);\n\n\n    float *data_output = output->mutable_cpu_data();\n\n    // 2D bounding box\n    cv::Mat acc_prob(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 0));\n    cv::Mat acc_xmin(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 1));\n    cv::Mat acc_ymin(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 2));\n    cv::Mat acc_xmax(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 3));\n    cv::Mat acc_ymax(output->shape(2), output->shape(3), CV_32FC1, data_output+output->offset(0, 4));\n\n//    cv::imshow(\"detected acc \" + std::to_string(a), acc_prob);\n\n    // Extract detected boxes - only extract local maxima from 3x3 neighborhood\n    for (int i = 0; i < acc_prob.rows; ++i)\n    {\n        for (int j = 0; j < acc_prob.cols; ++j)\n        {\n            float label = acc_gt_prob.at<float>(i, j);\n\n            double w = acc_xmax.at<float>(i, j) - acc_xmin.at<float>(i, j);\n            double h = acc_ymax.at<float>(i, j) - acc_ymin.at<float>(i, j);\n\n            if (label > 0.0f)\n            {\n                // This is a positive pixel\n                hist_wh_pos[a].addEntry(w, h);\n                hist_tl_pos[a].addEntry(acc_xmin.at<float>(i, j), acc_ymin.at<float>(i, j));\n                hist_br_pos[a].addEntry(acc_xmax.at<float>(i, j), acc_ymax.at<float>(i, j));\n                hist_wh_car_g_bb[a].addEntry(w, h, 1.0);\n                hist_wh_notcar_g_bb[a].addEntry(w, h, 0.0);\n            }\n            else\n            {\n                // This is a background pixel\n                hist_wh_neg[a].addEntry(w, h);\n                hist_tl_neg[a].addEntry(acc_xmin.at<float>(i, j), acc_ymin.at<float>(i, j));\n                hist_br_neg[a].addEntry(acc_xmax.at<float>(i, j), acc_ymax.at<float>(i, j));\n                hist_wh_car_g_bb[a].addEntry(w, h, 0.0);\n                hist_wh_notcar_g_bb[a].addEntry(w, h, 1.0);\n            }\n        }\n    }\n}\n\n\nvoid computeStatistics (const std::string &path_image, const std::shared_ptr<caffe::Net<float>> &net,\n                        const std::map<std::string, std::vector<BB2D>> &gt_bbs_list)\n{\n    caffe::Blob<float>* input_layer  = net->input_blobs()[0];\n\n    std::vector<cv::Mat> input_channels;\n\n    // Read the image\n    cv::Mat image = cv::imread(path_image, CV_LOAD_IMAGE_COLOR);\n    // Convert to zero mean and unit variance\n    cv::Mat imagef; image.convertTo(imagef, CV_32FC3);\n    imagef -= cv::Scalar(128.0f, 128.0f, 128.0f);\n    imagef *= 1.0f/128.0f;\n\n    // Ground truth bounding boxes\n    std::vector<BB2D> gt_bbs;\n    auto gt_bbsi = gt_bbs_list.find(path_image);\n    if (gt_bbsi == gt_bbs_list.end())\n    {\n        LOG(WARNING) << \"No ground truth for image '\" << path_image << \"'\";\n    }\n    else\n    {\n        gt_bbs = (*gt_bbsi).second;\n    }\n\n\n    // Reshape the network\n    input_layer->Reshape(1, input_layer->shape(1), imagef.rows, imagef.cols);\n    net->Reshape();\n\n    // Prepare the cv::Mats for input\n    wrapInputLayer(input_layer, input_channels);\n    // Copy the image to the input layer of the network\n    cv::split(imagef, input_channels);\n\n    net->Forward();\n\n    // For each accumulator\n    for (int a = 0; a < net->output_blobs().size(); ++a)\n    {\n        histogramOfCoords(net->output_blobs()[a], a, net->blob_names()[net->output_blob_indices()[a]], gt_bbs);\n    }\n\n//    cv::imshow(\"image\", image);\n//    cv::waitKey(0);\n}\n\n\nvoid runStatisticsComputation (const std::string &path_prototxt, const std::string &path_caffemodel,\n                               const std::string &path_image_list, const std::string &path_gt_bbtxt,\n                               const std::string &path_out)\n{\n#ifdef CPU_ONLY\n    caffe::Caffe::set_mode(caffe::Caffe::CPU);\n#else\n    caffe::Caffe::set_mode(caffe::Caffe::GPU);\n#endif\n\n    // Create network and load trained weights from caffemodel file\n    auto net = std::make_shared<caffe::Net<float>>(path_prototxt, caffe::TEST);\n    net->CopyTrainedLayersFrom(path_caffemodel);\n\n    caffe::Blob<float>* input_layer  = net->input_blobs()[0];\n    caffe::Blob<float>* output_layer = net->output_blobs()[0];\n\n    CHECK_EQ(net->num_inputs(), 1) << \"Network should have exactly one input.\";\n    CHECK_EQ(input_layer->shape(1), 3) << \"Input layer must have 3 channels.\";\n    CHECK_EQ(output_layer->shape(1), 5) << \"Unsupported network, only 5 channels!\";\n\n    std::ifstream infile(path_image_list.c_str());\n    CHECK(infile) << \"Unable to open image list TXT file '\" << path_image_list << \"'!\";\n    std::string line;\n\n    // Load ground truth\n    std::map<std::string, std::vector<BB2D>> gt_bbs_list = readBBTXTFile(path_gt_bbtxt);\n\n\n    for (int i = 0; i < net->output_blobs().size(); ++i)\n    {\n        hist_wh_neg.emplace_back(0, 2, 0, 2, 200);\n        hist_tl_neg.emplace_back(-1, 1, -1, 1, 200);\n        hist_br_neg.emplace_back(0, 2, 0, 2, 200);\n        hist_wh_pos.emplace_back(0, 2, 0, 2, 200);\n        hist_tl_pos.emplace_back(-1, 1, -1, 1, 200);\n        hist_br_pos.emplace_back(0, 2, 0, 2, 200);\n        hist_wh_car_g_bb.emplace_back(0, 2, 0, 2, 200);\n        hist_wh_notcar_g_bb.emplace_back(0, 2, 0, 2, 200);\n    }\n\n\n    // -- RUN THE DETECTOR ON EACH IMAGE -- //\n    while (std::getline(infile, line))\n    {\n        LOG(INFO) << line;\n        CHECK(boost::filesystem::exists(line)) << \"Image '\" << line << \"' not found!\";\n\n        // Detect bbs on the image\n        computeStatistics(line, net, gt_bbs_list);\n    }\n\n\n    for (int i = 0; i < net->output_blobs().size(); ++i)\n    {\n//        {\n//            std::vector<cv::Mat> chs_tl;\n//            chs_tl.push_back(cv::Mat::zeros(hist_tl_pos[i].hist.size(), CV_64FC1));\n//            chs_tl.push_back(hist_tl_pos[i].normalized());\n//            chs_tl.push_back(hist_tl_neg[i].normalized());\n//            cv::line(chs_tl[0], cv::Point(chs_tl[0].cols/2,0), cv::Point(chs_tl[0].cols/2, chs_tl[0].rows), cv::Scalar(0.5), 2);\n//            cv::line(chs_tl[0], cv::Point(0,chs_tl[0].rows/2), cv::Point(chs_tl[0].cols, chs_tl[0].rows/2), cv::Scalar(0.5), 2);\n//            cv::Mat comb_tl; cv::merge(chs_tl, comb_tl);\n//            cv::imshow(\"Normalized tl histogram \" + std::to_string(i), comb_tl);\n//            cv::imwrite(path_out + \"/hist_tl_\" + net->blob_names()[net->output_blob_indices()[i]] + \".png\", comb_tl*255);\n//        }\n\n//        {\n//            std::vector<cv::Mat> chs_br;\n//            chs_br.push_back(cv::Mat::zeros(hist_br_pos[i].hist.size(), CV_64FC1));\n//            chs_br.push_back(hist_br_pos[i].normalized());\n//            chs_br.push_back(hist_br_neg[i].normalized());\n//            cv::line(chs_br[0], cv::Point(chs_br[0].cols/2,0), cv::Point(chs_br[0].cols/2, chs_br[0].rows), cv::Scalar(0.5));\n//            cv::line(chs_br[0], cv::Point(0,chs_br[0].rows/2), cv::Point(chs_br[0].cols, chs_br[0].rows/2), cv::Scalar(0.5));\n//            cv::Mat comb_br; cv::merge(chs_br, comb_br);\n//            cv::imshow(\"Normalized br histogram \" + std::to_string(i), comb_br);\n//            cv::imwrite(path_out + \"/hist_br_\" + net->blob_names()[net->output_blob_indices()[i]] + \".png\", comb_br*255);\n//        }\n\n        {\n            // P(BB|CAR_GT) WxH\n            std::vector<cv::Mat> chs;\n            chs.push_back(cv::Mat::zeros(hist_wh_pos[i].hist.size(), CV_64FC1));\n            chs.push_back(hist_wh_pos[i].normalized());\n            chs.push_back(hist_wh_neg[i].normalized());\n            cv::line(chs[0], cv::Point(chs[0].cols/2,0), cv::Point(chs[0].cols/2, chs[0].rows), cv::Scalar(0.5));\n            cv::line(chs[0], cv::Point(0,chs[0].rows/2), cv::Point(chs[0].cols, chs[0].rows/2), cv::Scalar(0.5));\n            cv::line(chs[0], cv::Point(0,0), cv::Point(chs[0].cols, chs[0].rows), cv::Scalar(0.5));\n            cv::Mat comb_wh; cv::merge(chs, comb_wh);\n//            cv::imshow(\"P(BB|CAR_GT) WxH \" + std::to_string(i), comb_wh);\n            cv::imwrite(path_out + \"/hist_wh_bb_g_car_notcar_\" + net->blob_names()[net->output_blob_indices()[i]] + \".png\", comb_wh*255);\n        }\n\n        {\n            // P(CAR_GT|BB) WxH\n            std::vector<cv::Mat> chs;\n            chs.push_back(cv::Mat::zeros(hist_wh_car_g_bb[i].hist.size(), CV_64FC1));\n            chs.push_back(hist_wh_car_g_bb[i].countNormalized());\n            chs.push_back(cv::Mat::zeros(hist_wh_car_g_bb[i].hist.size(), CV_64FC1));\n            cv::line(chs[0], cv::Point(chs[0].cols/2,0), cv::Point(chs[0].cols/2, chs[0].rows), cv::Scalar(0.5));\n            cv::line(chs[0], cv::Point(0,chs[0].rows/2), cv::Point(chs[0].cols, chs[0].rows/2), cv::Scalar(0.5));\n            cv::line(chs[0], cv::Point(0,0), cv::Point(chs[0].cols, chs[0].rows), cv::Scalar(0.5));\n            cv::Mat comb_cf; cv::merge(chs, comb_cf);\n//            cv::imshow(\"P(CAR_GT|BB) WxH \" + std::to_string(i), comb_cf);\n            cv::imwrite(path_out + \"/hist_wh_car_g_bb_\" + net->blob_names()[net->output_blob_indices()[i]] + \".png\", comb_cf*255);\n        }\n\n        {\n            // P(NOT_CAR_GT|BB) WxH\n            std::vector<cv::Mat> chs;\n            chs.push_back(cv::Mat::zeros(hist_wh_car_g_bb[i].hist.size(), CV_64FC1));\n            chs.push_back(cv::Mat::zeros(hist_wh_car_g_bb[i].hist.size(), CV_64FC1));\n            chs.push_back(hist_wh_notcar_g_bb[i].countNormalized());\n            cv::line(chs[0], cv::Point(chs[0].cols/2,0), cv::Point(chs[0].cols/2, chs[0].rows), cv::Scalar(0.5));\n            cv::line(chs[0], cv::Point(0,chs[0].rows/2), cv::Point(chs[0].cols, chs[0].rows/2), cv::Scalar(0.5));\n            cv::line(chs[0], cv::Point(0,0), cv::Point(chs[0].cols, chs[0].rows), cv::Scalar(0.5));\n            cv::Mat comb_cf; cv::merge(chs, comb_cf);\n//            cv::imshow(\"P(NOT_CAR_GT|BB) WxH \" + std::to_string(i), comb_cf);\n            cv::imwrite(path_out + \"/hist_wh_notcar_g_bb_\" + net->blob_names()[net->output_blob_indices()[i]] + \".png\", comb_cf*255);\n        }\n\n    }\n\n//    cv::waitKey();\n}\n\n\n\n// -----------------------------------------------  MAIN  ------------------------------------------------ //\n\nstruct ProgramArguments\n{\n    std::string path_prototxt;\n    std::string path_caffemodel;\n    std::string path_image_list;\n    std::string path_gt_bbtxt;\n    std::string path_out;\n};\n\n\n/**\n * @brief Parses arguments of the program\n */\nvoid parseArguments (int argc, char** argv, ProgramArguments &pa)\n{\n    try {\n        po::options_description desc(\"Arguments\");\n        desc.add_options()\n            (\"help\", \"Print help\")\n            (\"prototxt\", po::value<std::string>(&pa.path_prototxt)->required(),\n             \"Model file of the network (*.prototxt)\")\n            (\"caffemodel\", po::value<std::string>(&pa.path_caffemodel)->required(),\n             \"Weight file of the network (*.caffemodel)\")\n            (\"image_list\", po::value<std::string>(&pa.path_image_list)->required(),\n             \"Path to a TXT file with paths to the images to be tested\")\n            (\"gt_bbtxt\", po::value<std::string>(&pa.path_gt_bbtxt)->required(),\n             \"Path to a BBTXT file with ground truth annotation for the images in image list\")\n            (\"path_out\", po::value<std::string>(&pa.path_out)->required(),\n             \"Path to the output folder\")\n        ;\n\n        po::positional_options_description positional;\n        positional.add(\"prototxt\", 1);\n        positional.add(\"caffemodel\", 1);\n        positional.add(\"image_list\", 1);\n        positional.add(\"gt_bbtxt\", 1);\n        positional.add(\"path_out\", 1);\n\n\n        // Parse the input arguments\n        po::variables_map vm;\n        po::store(po::command_line_parser(argc, argv).options(desc).positional(positional).run(), vm);\n\n        if (vm.count(\"help\")) {\n            std::cout << \"Usage: ./macc_statistics path/f.prototxt path/f.caffemodel path/image_list.txt path/out/folder\\n\";\n            std::cout << desc;\n            exit(EXIT_SUCCESS);\n        }\n\n        po::notify(vm);\n\n        if (!boost::filesystem::exists(pa.path_prototxt))\n        {\n            std::cerr << \"ERROR: File '\" << pa.path_prototxt << \"' does not exist!\" << std::endl;\n            exit(EXIT_FAILURE);\n        }\n        if (!boost::filesystem::exists(pa.path_caffemodel))\n        {\n            std::cerr << \"ERROR: File '\" << pa.path_caffemodel << \"' does not exist!\" << std::endl;\n            exit(EXIT_FAILURE);\n        }\n        if (!boost::filesystem::exists(pa.path_image_list))\n        {\n            std::cerr << \"ERROR: File '\" << pa.path_image_list << \"' does not exist!\" << std::endl;\n            exit(EXIT_FAILURE);\n        }\n        if (!boost::filesystem::exists(pa.path_gt_bbtxt))\n        {\n            std::cerr << \"ERROR: File '\" << pa.path_gt_bbtxt << \"' does not exist!\" << std::endl;\n            exit(EXIT_FAILURE);\n        }\n        if (not boost::filesystem::exists(pa.path_out))\n        {\n            std::cerr << \"ERROR: Output folder '\" << pa.path_out << \"' does not exist!\" << std::endl;\n            exit(EXIT_FAILURE);\n        }\n    }\n    catch(std::exception& e)\n    {\n        std::cerr << e.what() << \"\\n\";\n        exit(EXIT_FAILURE);\n    }\n}\n\n\nint main (int argc, char** argv)\n{\n    FLAGS_logtostderr = 1;\n    FLAGS_minloglevel = ::google::INFO;\n    ::google::InitGoogleLogging(argv[0]);\n\n    ProgramArguments pa;\n    parseArguments(argc, argv, pa);\n\n\n    runStatisticsComputation(pa.path_prototxt, pa.path_caffemodel, pa.path_image_list, pa.path_gt_bbtxt, pa.path_out);\n\n\n    return EXIT_SUCCESS;\n}\n\n\n#else\nint main(int argc, char** argv) {\n    LOG(FATAL) << \"This example requires OpenCV; compile with USE_OPENCV.\";\n}\n#endif  // USE_OPENCV\n", "meta": {"hexsha": "d9d2952eb4155baff3624e102d8b379651578458", "size": 18896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "caffe/examples/ln/macc_statistics.cpp", "max_stars_repo_name": "wuzzh/master_thesis_code", "max_stars_repo_head_hexsha": "6eca474ed3cae673afde010caef338cf7349f839", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 206.0, "max_stars_repo_stars_event_min_datetime": "2017-05-24T15:19:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T02:49:41.000Z", "max_issues_repo_path": "caffe/examples/ln/macc_statistics.cpp", "max_issues_repo_name": "qiaohaijun/master_thesis_code", "max_issues_repo_head_hexsha": "6eca474ed3cae673afde010caef338cf7349f839", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2017-06-21T06:07:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-06T12:45:15.000Z", "max_forks_repo_path": "caffe/examples/ln/macc_statistics.cpp", "max_forks_repo_name": "qiaohaijun/master_thesis_code", "max_forks_repo_head_hexsha": "6eca474ed3cae673afde010caef338cf7349f839", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 69.0, "max_forks_repo_forks_event_min_datetime": "2017-06-27T09:00:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T05:05:44.000Z", "avg_line_length": 37.4178217822, "max_line_length": 137, "alphanum_fraction": 0.5757832345, "num_tokens": 5444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.56476952264443}}
{"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": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <cmath>\n#include <algorithm>\n#include <sstream>\n#include <Eigen/Eigenvalues>\n#include <unsupported/Eigen/MatrixFunctions>\n#include \"BitUtility.h\"\n#include \"StateGenerator.h\"\n#include \"ScriptGenerator.h\"\n#include \"Spectrum.h\"\n#include \"NormCalculator.h\"\n#include \"otoc.h\"\n\nusing namespace std;\n\nstruct Options {\n    int L = -1;\n    int M = -1;\n    f_type N = std::numeric_limits<f_type>::infinity();\n    f_type beta = std::numeric_limits<f_type>::infinity();\n    f_type bt = std::numeric_limits<f_type>::infinity();\n    f_type tMin;\n    f_type tMax;\n    f_type tSteps;\n    std::string W;\n    std::string V;\n    std::string Op;\n    char ComputeNorm = 0;\n    char ExcludeZeroStates = 0;\n    char Parts = 1;\n    f_type alpha = 1.0;\n    f_type sigma = 0.0;\n};\n\nvoid TestBlockMatrixExp() {\n    IOperator* op = IOperator::Create(\"XXXZ\");\n    int L = 11;\n    int N = 13;\n    BlockMatrix res(L);\n    op->ToMatrixN(L, N, res);\n    Stopwatch watch;\n    BlockMatrix exp1 = res.exp();\n    std::cout << \"elapsed: \" << watch.Elapsed() << std::endl;\n\n    Matrix mat = res.matrix();\n    watch.Start();\n    Matrix exp2 = mat.exp();\n    std::cout << \"elapsed: \" << watch.Elapsed() << std::endl;\n\n    std::cout << \"norm=\" << exp2.norm() << std::endl;\n    std::cout << \"diff=\" << (exp1.matrix() - exp2).norm() << std::endl;\n\n    delete op;\n}\n\nvoid TestMatrixExp() {\n    DilatationOperator ham;\n    int L = 13;\n    int M = 6;\n    f_type N = 10;\n    f_type beta = 0.9;\n    int size = StateCollection::Inst()->StateNumber(L, M);\n    Matrix res(size, size);\n    ham.ToMatrixN(L, M, N, beta, res);\n    \n    Stopwatch watch;\n/*    watch.Start();\n    std::vector<var_t> v1;\n    for (f_type t = 0.0; t <= 10; t += 0.5) {\n        std::cout << \"t=\" << t << \" \";\n        var_t z(0, -t);\n        Matrix exp1 = (res * z).exp();\n        v1.push_back(exp1.trace());\n    }\n\n    std::cout << endl;\n    std::cout << \"v1=\" << v1 << std::endl;\n\n    std::cout << \"time used:\" << watch.Stop() << \" seconds.\" << std::endl << std::endl;;*/\n\n    watch.Start();\n    Eigen::ComplexEigenSolver<Matrix> solver(res, true);\n    Eigen::ArrayXcd diag = solver.eigenvalues().array();\n//    Vector diag = solver.eigenvalues();\n    Matrix V = solver.eigenvectors();\n    Matrix Vinv = V.inverse();\n\n//    std::cout << \"diag=\" << diag << std::endl;\n    std::vector<var_t> v2;\n    std::cout << \"initial time= \" << watch.Elapsed() << std::endl;\n\n    for (f_type t = 0.0; t <= 10; t += 0.5) {\n        std::cout << \"t=\" << t << \" \";\n        var_t z(0, -t);\n        Matrix exp2 = V * (diag * z).exp().matrix().asDiagonal() * Vinv;\n//        Matrix exp2 = V * (diag.array() * z).exp().matrix().asDiagonal() * Vinv;\n//        std::cout << \"(diag*z).exp()=\" << (diag * z).exp() << std::endl;\n        v2.push_back(exp2.trace());\n    }\n    std::cout << std::endl;\n    std::cout << \"v2=\" << v2 << std::endl;\n\n    std::cout << \"time used:\" << watch.Stop() << \" seconds.\" << std::endl;\n}\n\nvoid TestOtoc() {\n    int L = 4;\n    int M = -1;\n    f_type N = 17.0;\n    f_type beta = 0.9;\n    f_type b = 0.5;\n    OtocParameters params = {\"XZ\", \"ZX\", L, M, N, beta, b, 1};\n    std::cout << \"test otoc\" << std::endl;\n    IOtoc* otoc = IOtoc::Create(params);\n    otoc->Init();\n    std::cout << \"finished initialization...\" << std::endl;\n    for (int i = 0; i < 10; i++) {\n        std::cout << i << ' ' << otoc->Compute((f_type)i) << std::endl;\n    }\n}\n\nvoid TestForAnything() {\n    Matrix m;\n    std::cout << m.rows() << \" \" << m.cols() << std::endl;\n}\n\nvoid TestOp() {\n    FourFieldOperator ffp(\"XZXZ\");\n    TraceState ts;\n    ts.AddTrace(SingleTrace(\"ZXZX\"));\n    MixState ms;\n    ffp.ApplyOn(ts, ms);\n    std::cout << ms << std::endl;\n}\n\nvoid TestNormCalculator() {\n    StateGenerator generator;\n    generator.GenerateAllStates();\n    generator.InitStateCollection(StateCollection::Inst());\n\n    SingleTrace trace(\"ZZXX\");\n    TraceState ts;\n    ts.AddTrace(trace);\n    BruteForceCalculator calc;\n    PowerSeries<i64> res = calc.Calculate(ts, ts);\n    for (int i = 0; i <= res.HighestOrder(); i++) {\n        std::cout << res.Coef(i) << \" \";\n    }\n    std::cout << std::endl;\n}\n\nvoid TestNormCalculator2() {\n    StateGenerator generator;\n    generator.GenerateAllStates();\n    generator.InitStateCollection(StateCollection::Inst());\n    std::cout << \"init done\" << std::endl;\n    /*    StateId id(0, 0);\n    std::cout << StateCollection::Inst()->GetState(id) << std::endl;*/\n\n    SingleTrace trace(\"ZZ\");\n    SingleTrace trace2(\"ZZXX\");\n    SingleTrace trace3(\"ZZXZZX\");\n    trace.Normalize();\n    trace2.Normalize();\n    trace3.Normalize();\n    TraceState ts;\n    ts.AddTrace(trace);\n    ts.AddTrace(trace2);\n    ts.QuickNormalize();\n    TraceState ts2;\n    ts2.AddTrace(trace3);\n    RecursiveNormCalculator calc;\n    PowerSeries<nType> res = calc.Calculate(ts, ts2);\n    std::cout << \"<\" << trace << \"^\" << trace << \">=\";\n    std::cout << res << std::endl;\n\n    BruteForceCalculator calc2;\n    PowerSeries<nType> res2 = calc2.Calculate(ts, ts2);\n    std::cout << \"res=\" << res2 << std::endl;\n}\n\nvoid ComputeOtoc(OtocParameters params, f_type tMin, f_type tMax, int steps, bool parts = false) {\n    string rootFolder = \"\";\n    ScriptGenerator gen(rootFolder);\n    gen.SaveOtoc(params, tMin, tMax, steps, parts);\n}\n\nvoid GenerateHamMatrix(int L, int M)\n{\n    string rootFolder = \"\";\n    ScriptGenerator gen(rootFolder);\n    if (M >= 0 && M <= L) {\n        gen.SaveHamMatrix(L, M);\n        gen.SaveStates(L, M);\n    }\n    else {\n        for (int i = 0; i <= L; i++) {\n            gen.SaveHamMatrix(L, i);\n            gen.SaveStates(L, i);\n        }\n    }\n}\n\nvoid GenerateOpMatrix(std::string opStr, int L, int M = -1)\n{\n    string rootFolder = \"\";\n    ScriptGenerator gen(rootFolder);\n    if (M >= 0) {\n        gen.SaveOpMatrix(opStr, L, M);\n    } else {\n        IOperator* op = dynamic_cast<ISimpleOperator*>(IOperator::Create(opStr));\n        if (!op->MagnonFixed()) {\n            gen.SaveOpMatrix(opStr, L);\n        }\n        else {\n            for (int m = 0; m <= L; m++) {\n                gen.SaveOpMatrix(opStr, L, m);\n            }\n        }\n        delete op;\n    }\n}\n\nvoid GenerateNormMatrix(int L, int M, bool su)\n{\n    string rootFolder = \"\";\n    ScriptGenerator gen(rootFolder);\n    if (M < 0) {\n        if (su) {\n            gen.SaveNormToDataFile2(L);\n        }\n        else {\n            gen.SaveNormToDataFile(L);\n        }\n        return;\n    }\n    if (su) {\n        gen.SaveNormToDataFile2(L, M);\n    }\n    else {\n        gen.SaveNormToDataFile(L, M);\n    }\n}\n\nvoid ComputeSpectrum(int L, int M, int N, f_type beta)\n{\n    string rootFolder = \"\";\n    ScriptGenerator gen(rootFolder);\n    if (M >= 0) {\n        gen.SaveSpectrum(L, M, N, beta);\n    }\n    else {\n        for (int i = 0; i <= L; i++) {\n            gen.SaveSpectrum(L, i, N, beta);\n        }\n    }\n}\n\nstd::vector<std::string> optionDesc {\n    \"-L <integer number>\", \"Length of spin chain, 2 <= L <= \" + ToString(MAX_BIT_TO_GENERATE),\n    \"-M <integer number>\", \"Number of magnons.\",\n    \"-N <real number>\", \"Rank of SU(N) color group. In general it's integer but could be real.\",\n    \"-b <real number>\", \"The beta parameter of beta-deformed N=4 SYM.\",\n    \"-bt <real number>\", \"The reciprocal of temperature.\",\n    \"-tmin <real number>\", \"The initial time of OTOC.\",\n    \"-tmax <real number>\", \"The final time of OTOC.\",\n    \"-tstep <integer number>\", \"Number of steps go from initial time to final time.\",\n    \"-o <string>\", \"The operator to generate matrix for. The values can be NTr, NTrX, \", \n    \" \", \"or any two-letter or four-letter string built out of X and Z.\",\n    \" \", \"NTr indicates the operator counts number of traces;\",\n    \" \", \"NTrX indicates the operator counts number of traces containing X;\",\n    \" \", \"XZ indicates the trace operator Tr(X d/dZ); XZXZ indicates the operator Tr(XZ d/dX d/dZ)\",\n    \"-W <string>\", \"The W operator of OTOC. Its scope of values are the same as -o option.\",\n    \"-V <string>\", \"The V operator of OTOC. Its scope of values are the same as -o option.\",\n    \"-n\", \"The option only used in 'otoc' command. If not spefied, the norm matrix will be computed;\",\n    \" \", \"otherwise, the norm matrix will be loaded form local files generated by 'norm' command\",\n    \"-nozero\", \"If the option is specified, zero energy states is excluded in C(t) computation.\",\n    \"-alpha <real number>\", \"The alpha parameter of the OTOC regularization\",\n    \"-sigma <real number>\", \"The sigma parameter of the OTOC regularization\"\n};\n\nvoid DisplayOptions() {\n    std::cout << \"General Options:\" << std::endl;\n    for (size_t i = 0; i < optionDesc.size(); i += 2) {\n        std::cout << \"  \" << std::left << std::setfill(' ') << std::setw(25) << optionDesc[i];\n        std::cout << \"\\t\\t\" << optionDesc[i + 1] << std::endl;\n    }\n}\n\nstd::vector<std::string> exampleDesc {\n    \"Generate Hamiltonian matrix and trace states for L=4, M=2\",                         // 1\n    \"Generate all Hamiltonian matrix and trace states for L=4\",                          // 2\n    \"Generate norm matrix for L=4, M=2\",                                //  3\n    \"Generate all norm matrix for L=4\",                                 // 4\n    \"Compute energy spectrum for L=4, M=2, N=17, beta=0.9\",             // 5\n    \"Generate matrix for operator counting traces containing X for L=4\",\n    \"Compute OTOC for W=Tr(Xd/dZ), V=Tr(Zd/dX), L=4, N=5, beta=0.9, beta of temperature=0.5,\\n \\\n\\t\\tand time run from 0.0 to 5.0 with step size 0.1. Note that to run the example one needs\\n\\\n\\t\\tto run \\\"otoc norm - L 4\\\" first to generate all norm matrices for L = 4 and then copy the\\n \\\n\\t\\tgenerated files to otocdata folder\",\n    \"Compute OTOC for W=Tr(XZ d/dX d/dZ), V=Tr(ZX d/dX d/dZ), L=4, M=2, beta=0.9, beta of temperature=0.5,\\n \\\n\\t\\tand N=Infinity. As -n option is specified, it will compute norm matrix rather than load it from local files.\",\n    \"Compute C(t) for W=Tr(XX d/dX d/dZ), V=Tr(ZZ d/dZ d/dX), L=4, N=5. Zero energy states are excluded.\",\n    \"Compute C(t) for W=Tr(XX d/dX d/dZ), V=Tr(ZZ d/dZ d/dX), L=4, N=5. With regularization parameters alpha=0.5 and sigma=0.25.\",\n    \"Example of computing OTOC for composite operators. Currently, addition (+), substraction(-) , \\n\\\n\\t\\tmultiplication(*), and exponentiate (exp), and normal ordered (~) are supported. No division (/) \\n\\\n\\t\\tand space is allowd in the expression. Complex number should write in the form (real,imag).\",\n};\n\nstd::vector<std::string> examples {\n    \"otoc ham -L 4 -M 2\",                       // 1\n    \"otoc ham -L 4\",                            // 2\n    \"otoc norm -L 4 -M 2\",                      // 3\n    \"otoc norm -L 4\",                           // 4\n    \"otoc spec -L 4 -M 2 -N 17 -b 0.9\",         // 5\n    \"otoc operator -o NTrX -L 4\",                          // 6\n    \"otoc otoc -W XZ -V ZX -L 4 -N 5 -b 0.9 -bt 0.5 -tmin 0.0 -tmax 5.0 -tstep 50\",\n    \"otoc otoc -W XZXZ -V XZXZ -L 4 -M 2 -b 0.9 -bt 0.5 -tmin 0.0 -tmax 5.0 -tstep 50 -n\",\n    \"otoc otoc -W XXXZ -V ZZZX -L 4 -N 5 -b 0.9 -bt 0.5 -tmin 0.0 -tmax 5.0 -tstep 50 -nozero\",\n    \"otoc otoc -W XXXZ -V ZZZX -alpha 0.5 -sigma 0.25 -L 4 -N 5 -b 0.9 -bt 0.5 -tmin 0.0 -tmax 5.0 -tstep 50\",\n    \"otoc otoc -W -0.2*exp(0.2*XXXZ+0.3*XZ)+(0.3,-0.5) -V ~(-XZXZ+0.5*ZZZX-0.2*ZX) -L 4 -N 5 -b 0.9 -bt 0.5 -tmin 0.0 -tmax 5.0 -tstep 50\",\n};\n\nvoid DisplayExample() {\n    std::cout << \"Examples:\" << std::endl;\n    for (int i = 0; i < examples.size(); i++) {\n        std::cout << \"  Example \" << i + 1 << \":\\t\" << exampleDesc[i] << std::endl;\n        std::cout << \"\\t\\t\\t\" << examples[i] << std::endl << std::endl;\n    }\n}\n\nstd::vector<std::string> commands{ \"ham\", \"norm\", \"spec\", \"operator\", \"otoc\" };\n\nvoid DisplayHelp() {\n    std::cout << \"Usage:\\n  otoc <command> [options]\" << std::endl << std::endl;\n    std::cout << \"Commands:\" << std::endl;\n\n    std::vector<std::string> commandDesc {\n        \"Generate and save Hamiltonian matrix and trace states.\",\n        \"Compute and save spectrum of Hamiltonian.\",\n        \"Generate and save norm matrix of trace states.\",\n        \"Generate and save matrix of operators.\",\n        \"Compute and save out-of-time-order correlator.\"\n    };\n\n    \n    for (int i = 0; i < commands.size(); i++) {\n        std::cout << \"  \" << std::left << std::setfill(' ') << std::setw(25) << commands[i];\n        std::cout << \"\\t\\t\" << commandDesc[i] << std::endl;\n    }\n\n    std::cout << std::endl;\n    DisplayOptions();\n\n    std::cout << std::endl;\n    DisplayExample();\n}\n\nstd::vector<string> Tokenize(std::string str, char seperator) {\n    std::vector<std::string> ret;\n    stringstream ss(str);\n    std::string token;\n    while (getline(ss, token, seperator)) {\n        ret.push_back(token);\n    }\n\n    return ret;\n}\n\nvoid InitStates(int maxL) {\n    StateGenerator generator(maxL);\n    generator.GenerateAllStates();\n    generator.InitStateCollection(StateCollection::Inst());\n}\n\nint main(int argc, char* argv[]) {\n    if (argc < 2) {\n        DisplayHelp();\n        return -1;\n    }\n\n    std::string command = argv[1];\n    if (command == \"test\") {\n        InitStates(16);\n//        TestForAnything();\n//        TestOtoc();\n        //TestOp();\n//        TestMatrixExp();\n        TestBlockMatrixExp();\n        return 0;\n    }\n\n    if (std::find(commands.begin(), commands.end(), command) == commands.end()) {\n        DisplayHelp();\n        return -1;\n    }\n\n    Options options;\n    bool displayHelp = false;\n\n    for (int i = 2; i < argc; i++) {\n        string cmd = argv[i];\n        if (cmd == \"-L\") {\n            // \n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            string val = argv[i];\n            options.L = ToExpression(val, -1.0L);\n        }\n        else if (cmd == \"-M\") {\n            // \n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            string val = argv[i];\n            options.M = ToExpression(val, -1);\n        }\n        else if (cmd == \"-N\") {\n            // \n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            string val = argv[i];\n            options.N = ToExpression(val, -1.0);\n        }\n        else if (cmd == \"-b\") {\n            // \n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            string val = argv[i];\n            options.beta = ToExpression(val, 1000000.0);\n            beta_nsym = options.beta;\n        }\n        else if (cmd == \"-bt\") {\n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            string val = argv[i];\n            options.bt = ToExpression(val, options.bt);\n            inverseTempeture = options.bt;\n        }\n        else if (cmd == \"-tmax\") {\n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            string val = argv[i];\n            options.tMax = ToExpression(val, options.tMax);\n        }\n        else if (cmd == \"-tmin\") {\n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            string val = argv[i];\n            options.tMin = ToExpression(val, options.tMin);\n        }\n        else if (cmd == \"-tstep\") {\n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            string val = argv[i];\n            options.tSteps = ToExpression(val, options.tSteps);\n        } else if (cmd == \"-o\") {\n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            options.Op = argv[i];\n        }\n        else if (cmd == \"-W\") {\n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            options.W = argv[i];\n        }\n        else if (cmd == \"-V\") {\n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            options.V = argv[i];\n        }\n        else if (cmd == \"-alpha\") {\n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            options.alpha = ToExpression(argv[i], options.alpha);\n        }\n        else if (cmd == \"-sigma\") {\n            i++;\n            if (i >= argc) {\n                displayHelp = true;\n                break;\n            }\n            options.sigma = ToExpression(argv[i], options.sigma);;\n        }\n        else if (cmd == \"-n\") {\n            options.ComputeNorm = 1;\n        }\n        else if (cmd == \"-nozero\") {\n            options.ExcludeZeroStates = 1;\n        }\n//        else if (cmd == \"-parts\") {\n//            options.Parts = 1;\n //       }\n        else {\n            std::cerr << \"invalid option \" << cmd << std::endl;\n            return -1;\n        }\n    }\n\n    if (displayHelp) {\n        DisplayHelp();\n        return -1;\n    }\n\n    if (options.L > MAX_BIT_TO_GENERATE || options.L <= 1 || options.M > options.L || options.M < -1) {\n        displayHelp = true;\n    }\n\n    if (options.N < 1) {\n        displayHelp = true;\n    }\n\n    if (displayHelp) {\n        DisplayHelp();\n        return -1;\n    }\n\n    Stopwatch watch;\n    watch.Start();\n    LOG(\"Initializing trace states...\", Verbos);\n    InitStates(options.L);\n\n    try {\n        if (command == commands[0]) {\n            GenerateHamMatrix(options.L, options.M);\n        }\n        else if (command == commands[1]) {\n            GenerateNormMatrix(options.L, options.M, true);\n        }\n        else if (command == commands[2]) {\n            ComputeSpectrum(options.L, options.M, options.N, options.beta);\n        }\n        else if (command == commands[3]) {\n            GenerateOpMatrix(options.Op, options.L, options.M);\n        }\n        else if (command == commands[4]) {\n            OtocParameters params = { options.W, options.V, options.L, options.M, options.N,\n                options.beta, options.bt, options.ComputeNorm, options.ExcludeZeroStates,\n                options.alpha, options.sigma };\n            ComputeOtoc(params, options.tMin, options.tMax, options.tSteps, options.Parts);\n        }\n\n        LOG(\"The task is completed in \" << watch.Stop() << \" seconds.\", Info);\n    }\n    catch (OtocException& ex){\n        LOG(ex.what(), Error);\n        LOG(\"Elapsed time: \" << watch.Stop() << \" seconds.\", Info);\n    }\n}\n", "meta": {"hexsha": "d725f5874f3e1ca1b76b5b1f030d3237b0b09f10", "size": 18679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "gaolichen/otoc4n4sym", "max_stars_repo_head_hexsha": "b504f9eb6efdf52567b3655a2caff6238559ba64", "max_stars_repo_licenses": ["MIT"], "max_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": "gaolichen/otoc4n4sym", "max_issues_repo_head_hexsha": "b504f9eb6efdf52567b3655a2caff6238559ba64", "max_issues_repo_licenses": ["MIT"], "max_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": "gaolichen/otoc4n4sym", "max_forks_repo_head_hexsha": "b504f9eb6efdf52567b3655a2caff6238559ba64", "max_forks_repo_licenses": ["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.6057529611, "max_line_length": 139, "alphanum_fraction": 0.5213876546, "num_tokens": 5247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.5647649489105097}}
{"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": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_basic_types.h>\n#include <OpenTissue/core/geometry/geometry_compute_volume_length_quality_measure.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_geometry_util_compute_volume_length_quality_measure);\n\n  BOOST_AUTO_TEST_CASE(case_by_case_testing)\n  {\n    using std::sqrt;\n\n    typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n    typedef math_types::vector3_type                         vector3_type;\n    typedef math_types::real_type                            real_type;\n\n    real_type tol = 0.0001;\n\n\n\n    {\n      // semi regular\n      vector3_type p0(-1,-1, 0);\n      vector3_type p1( 1,-1, 0);\n      vector3_type p2( 0, 1, 0);\n      vector3_type p3( 0, 0, 2);\n      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);\n      std::cout << quality << std::endl;\n\n      BOOST_CHECK_CLOSE( quality, 0.975423, tol);\n    }\n    {\n      // close to flat\n      vector3_type p0(-1,-1, 0);\n      vector3_type p1( 1,-1, 0);\n      vector3_type p2( 0, 1, 0);\n      vector3_type p3( 0, 0, 0.01);\n      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);\n      std::cout << quality << std::endl;\n      BOOST_CHECK_CLOSE( quality, 0.0465344, tol);\n    }\n    {\n      // flat but still a simplex\n      vector3_type p0(-1,-1, 0);\n      vector3_type p1( 1,-1, 0);\n      vector3_type p2( 0, 1, 0);\n      vector3_type p3( 0, 0, 0);\n      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);\n      std::cout << quality << std::endl;\n      BOOST_CHECK_CLOSE( quality, 0.0, tol);\n    }\n    {\n      // flat but no longer a simplex - quad-like\n      vector3_type p0(-1,-1, 0);\n      vector3_type p1( 1,-1, 0);\n      vector3_type p2( 0, 1, 0);\n      vector3_type p3( 1, 1, 0);\n      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);\n      std::cout << quality << std::endl;\n      BOOST_CHECK_CLOSE( quality, 0.0, tol);\n    }\n    {\n      // inverted\n      vector3_type p0(-1,-1, 0);\n      vector3_type p1( 1,-1, 0);\n      vector3_type p2( 0, 1, 0);\n      vector3_type p3( 0, 0, -1);\n      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);\n      std::cout << quality << std::endl;\n      BOOST_CHECK_CLOSE( quality, 0.865855, tol);\n    }\n    {\n      // degenerate 2 nodes\n      vector3_type p0(-1,-1, 0);\n      vector3_type p1( 1,-1, 0);\n      vector3_type p2( 0, 1, 0);\n      vector3_type p3( 0, 1, 0);\n      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);\n      std::cout << quality << std::endl;\n      BOOST_CHECK_CLOSE( quality, 0.0, tol);\n    }\n    {\n      // degenerate 3 nodes\n      vector3_type p0(-1,-1, 0);\n      vector3_type p1( 0, 1, 0);\n      vector3_type p2( 0, 1, 0);\n      vector3_type p3( 0, 1, 0);\n      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);\n      std::cout << quality << std::endl;\n      BOOST_CHECK_CLOSE( quality, 0.0, tol);\n    }\n    {\n      // degenerate 4 nodes\n      vector3_type p0(-1,-1, 0);\n      vector3_type p1( 0, 1, 0);\n      vector3_type p2( 0, 1, 0);\n      vector3_type p3( 0, 1, 0);\n      real_type quality = OpenTissue::geometry::compute_volume_length_quality_measure(p0,p1,p2,p3);\n      std::cout << quality << std::endl;\n      BOOST_CHECK_CLOSE( quality, 0.0, tol);\n    }\n\n  }\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "e11e96a1337503e153baa6da2da28bfaa9fcc9bc", "size": 3986, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/geometry/compute_volume_length_quality_measure/src/unit_compute_volume_length_quality_measure.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/geometry/compute_volume_length_quality_measure/src/unit_compute_volume_length_quality_measure.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/geometry/compute_volume_length_quality_measure/src/unit_compute_volume_length_quality_measure.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 34.0683760684, "max_line_length": 99, "alphanum_fraction": 0.643753136, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5647479569029702}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <geometry_test_common.hpp>\n\n#include <boost/concept_check.hpp>\n\n#include <boost/geometry/extensions/gis/geographic/strategies/vincenty.hpp>\n\n#include <boost/geometry/strategies/strategies.hpp>\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <test_common/test_point.hpp>\n\n#ifdef HAVE_TTMATH\n#  include <boost/geometry/extensions/contrib/ttmath_stub.hpp>\n#endif\n\n\n\ntemplate <typename P1, typename P2>\nvoid test_vincenty(double lon1, double lat1, double lon2, double lat2, double expected_km)\n{\n    // Set radius type, but for integer coordinates we want to have floating point radius type\n    typedef typename bg::promote_floating_point\n        <\n            typename bg::coordinate_type<P1>::type\n        >::type rtype;\n\n    typedef bg::strategy::distance::vincenty<rtype> vincenty_type;\n\n    BOOST_CONCEPT_ASSERT(\n        (\n            bg::concept::PointDistanceStrategy<vincenty_type, P1, P2>)\n        );\n\n    vincenty_type vincenty;\n    typedef typename bg::strategy::distance::services::return_type<vincenty_type, P1, P2>::type return_type;\n\n\n    P1 p1, p2;\n\n    bg::assign_values(p1, lon1, lat1);\n    bg::assign_values(p2, lon2, lat2);\n\n    BOOST_CHECK_CLOSE(vincenty.apply(p1, p2), return_type(1000.0) * return_type(expected_km), 0.001);\n}\n\ntemplate <typename P1, typename P2>\nvoid test_all()\n{\n    test_vincenty<P1, P2>(0, 89, 1, 80, 1005.1535769); // sub-polar\n    test_vincenty<P1, P2>(4, 52, 4, 52, 0.0); // no point difference\n    test_vincenty<P1, P2>(4, 52, 3, 40, 1336.039890); // normal case\n}\n\ntemplate <typename P>\nvoid test_all()\n{\n    test_all<P, P>();\n}\n\nint test_main(int, char* [])\n{\n\n    //test_all<float[2]>();\n    //test_all<double[2]>();\n    test_all<bg::model::point<int, 2, bg::cs::geographic<bg::degree> > >();\n    test_all<bg::model::point<float, 2, bg::cs::geographic<bg::degree> > >();\n    test_all<bg::model::point<double, 2, bg::cs::geographic<bg::degree> > >();\n\n#if defined(HAVE_TTMATH)\n    test_all<bg::model::point<ttmath::Big<1,4>, 2, bg::cs::geographic<bg::degree> > >();\n    test_all<bg::model::point<ttmath_big, 2, bg::cs::geographic<bg::degree> > >();\n#endif\n\n\n    return 0;\n}\n", "meta": {"hexsha": "a11dfd6407006d3cdf56290c476241212328f62f", "size": 2778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/extensions/test/gis/latlong/vincenty.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "libs/geometry/extensions/test/gis/latlong/vincenty.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "libs/geometry/extensions/test/gis/latlong/vincenty.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 30.1956521739, "max_line_length": 108, "alphanum_fraction": 0.6954643629, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5646642605779333}}
{"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": "#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/vector_proxy.hpp>\n \n//#include <iostream>\n \nnamespace ublas = boost::numeric::ublas;\n \nint main(int argc, char ** argv)\n{\n    ublas::matrix<double> M(3, 3, 1);\n    ublas::identity_matrix<double> I(3);\n    ublas::zero_matrix<double> Z(3);\n    ublas::scalar_matrix<double> S(2, 3);\n \n    for (size_t idxRow = 0; idxRow < M.size1(); idxRow++)\n    {\n        for (size_t idxCol = 0; idxCol < M.size2(); idxCol++)\n        {\n            M(idxRow, idxCol) = 3 * idxRow + idxCol;\n        }\n    }\n \n    std::cout << \"M: \" << M << std::endl;\n    std::cout << ublas::row(M, 0) << std::endl;\n    std::cout << ublas::inner_prod(ublas::row(M, 0), ublas::row(M, 1)) << std::endl;\n    std::cout << ublas::project(ublas::row(M, 1), ublas::range(0, 2)) << std::endl;\n \n    getchar();\n \n    return 0;\n}", "meta": {"hexsha": "c570aa8c8a2699152846da54b6492d8b1b465f19", "size": 940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/boost/ublas_matrix.cpp", "max_stars_repo_name": "Aithosa/Notes", "max_stars_repo_head_hexsha": "c20f2b96af498571e08cd71ce4a0fde8b8cf772c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-12-25T13:34:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-03T05:02:18.000Z", "max_issues_repo_path": "C++/boost/ublas_matrix.cpp", "max_issues_repo_name": "Aithosa/Notes", "max_issues_repo_head_hexsha": "c20f2b96af498571e08cd71ce4a0fde8b8cf772c", "max_issues_repo_licenses": ["MIT"], "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++/boost/ublas_matrix.cpp", "max_forks_repo_name": "Aithosa/Notes", "max_forks_repo_head_hexsha": "c20f2b96af498571e08cd71ce4a0fde8b8cf772c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-25T22:48:31.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-25T22:48:31.000Z", "avg_line_length": 28.4848484848, "max_line_length": 84, "alphanum_fraction": 0.5882978723, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5645901936530695}}
{"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": "#include \"CppUnitTest.h\"\n#include \"UnitTestAux.h\"\n#include \"../BVP/Utils/AuxUtils.h\"\n#include \"..\\BVP\\Problems\\NonAutonomousTroeschProblem.h\"\n#include \"..\\BVP\\Problems\\NonAutonomousOscillatingProblem.h\"\n#include \"..\\BVP\\FunctionApproximation\\PointSimple.h\"\n#include \"..\\BVP\\MultipleShooting\\HybridMultipleShootingComponent.h\"\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"../BVP/FunctionApproximation/InitialCondition.h\"\n\nusing namespace auxutils;\n\nusing namespace UnitTestAux;\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\ntypedef float_50_noet numTypeMp;\ntypedef double numType;\n\nnamespace GeneralTest\n{\n\tTEST_CLASS(NonAutonomousProblemsTest)\n\t{\n\tpublic:\n\t\t\n\t\t//TEST_METHOD(NonAutonomousTroeschProblemDoubleMultimpeShooting)\n\t\t//{\n\t\t//\tNonAutonomousTroeschProblem<numType> tpf(20);\n\t\t//\tPointSimple<numType> ptLeft;\n\t\t//\tptLeft.Argument  = 0;\n\t\t//\tptLeft.Value  = 0;\n\n\t\t//\tPointSimple<numType> ptRight;\n\t\t//\tptRight.Argument  = 1;\n\t\t//\tptRight.Value  = 1;\n\n\t\t//\tHybridMultipleShootingComponent<numType> HMSComp(tpf);\n\n\t\t//\tbool succeeded;\n\t\t//\tstd::vector<InitCondition<numType>> solution = HMSComp.Run(ptLeft, ptRight, 0.0001, succeeded, 0.1);\n\n\t\t//\tauxutils::SaveToMapleFile(solution, \"f:\\\\NonAutoTroeschProblem.txt\", true);\n\n\t\t//}\n\n\t\tTEST_METHOD(StandardNonAutonomousOscilatingProblemMultimpeShootingDouble)\n\t\t{\n\t\t\t NonAutonomousOscillatingProblem<numType> problem;\n   \t\t\t StandardOscillatinProblemMultipleShoothingTest<numType, NonAutonomousOscillatingProblem<numType>>(problem);\n\t\t}\n\t};\n}", "meta": {"hexsha": "0eb00be0696ab8f5ba51cf9a065ffed1861a77a0", "size": 1527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Software/GeneralTest/NonAutonomousProblemsTest.cpp", "max_stars_repo_name": "imathsoft/MathSoftDevelopment", "max_stars_repo_head_hexsha": "4c449f6e378a942cfc39081739ba4c0aa2dce4de", "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": "Software/GeneralTest/NonAutonomousProblemsTest.cpp", "max_issues_repo_name": "imathsoft/MathSoftDevelopment", "max_issues_repo_head_hexsha": "4c449f6e378a942cfc39081739ba4c0aa2dce4de", "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": "Software/GeneralTest/NonAutonomousProblemsTest.cpp", "max_forks_repo_name": "imathsoft/MathSoftDevelopment", "max_forks_repo_head_hexsha": "4c449f6e378a942cfc39081739ba4c0aa2dce4de", "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": 29.9411764706, "max_line_length": 114, "alphanum_fraction": 0.7701375246, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5645901881167289}}
{"text": "#include <iostream>\n#include <vector>\n#include <cassert>\n#include <map>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/max_cardinality_matching.hpp>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;\n\nvoid testcase()\n{\n  int n, c, f;\n  std::cin >> n >> c >> f;\n  assert(n >= 2 && n <= 400 && n % 2 == 0);\n  assert(c >= 1 && c <= 100);\n  assert(f >= 0);\n\n  std::map<std::string, int> ids_by_c;\n  std::vector<std::vector<int>> cs_by_student(n);\n  std::vector<std::vector<bool>> student_masks_by_c;\n  for (int i = 0; i < n; i++)\n  {\n    std::vector<int> &cs_this_student = cs_by_student.at(i);\n    for (int j = 0; j < c; j++)\n    {\n      std::string c_name;\n      std::cin >> c_name;\n      assert(c_name.size() <= 20);\n      if (ids_by_c.count(c_name) == 0)\n      {\n        ids_by_c.insert(std::make_pair(c_name, ids_by_c.size()));\n        student_masks_by_c.emplace_back(std::vector<bool>(n, false));\n      }\n      int c_id = ids_by_c.at(c_name);\n\n      cs_this_student.push_back(c_id);\n      student_masks_by_c.at(c_id).at(i) = true;\n    }\n  }\n\n  Graph G(n);\n  for (int i = 0; i < n; i++)\n  {\n    for (int j = i + 1; j < n; j++)\n    {\n      int overlap_count_lower_bound = 0;\n      for (auto c_id : cs_by_student.at(i))\n      {\n        if (student_masks_by_c.at(c_id).at(j))\n        {\n          overlap_count_lower_bound++;\n        }\n        if (overlap_count_lower_bound > f)\n        {\n          break;\n        }\n      }\n\n      if (overlap_count_lower_bound > f)\n      {\n        boost::add_edge(i, j, G);\n      }\n    }\n  }\n\n  std::vector<Graph::vertex_descriptor> mate(n);\n  bool success = boost::checked_edmonds_maximum_cardinality_matching(G, &mate[0]);\n  assert(success);\n\n  bool all_matched = true;\n  for (auto its = boost::vertices(G); its.first != its.second; its.first++)\n  {\n    if (mate[*its.first] == Graph::null_vertex())\n    {\n      all_matched = false;\n    }\n  }\n\n  std::cout << (all_matched ? \"not optimal\" : \"optimal\") << \"\\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": "1b55427a1f7cf1af9cdcafb2a681201e52cf1dea", "size": 2145, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-04/buddy-selection/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/buddy-selection/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/buddy-selection/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8191489362, "max_line_length": 82, "alphanum_fraction": 0.5696969697, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5645797545572308}}
{"text": "#include \"pgo_toy_example.h\"\n\n#include <ros/ros.h>\n\n#include <geometry_msgs/Point.h>\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n\n#include <Eigen/Dense>\n\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/optimizable_graph.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/solver.h>\n#include <g2o/core/robust_kernel_impl.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <g2o/types/slam3d/types_slam3d.h>\n\n#include <iostream>\n#include <vector>\n\n// prev poses (gray sphere).\nvisualization_msgs::MarkerArray prev_nodes;\n\n// prev edges (gray line).\nvisualization_msgs::MarkerArray prev_edges;\n\n// optimized poses (black sphere).\nvisualization_msgs::MarkerArray opt_nodes;\n\n// optimized edges (black line).\nvisualization_msgs::MarkerArray opt_edges;\n\n// text arrays.\nvisualization_msgs::MarkerArray texts;\n\n// Position of the first node.\ndouble xinit, yinit, zinit;\n\n/// \\brief Set the pose graph nodes for ROS visualization.\n/// \\param[in] toy Pointer to PGOToyExample instance.\n/// \\param[out] nodes Marker array of pose graph nodes.\n/// \\param[in] ns Namespace.\n/// \\param[in] id Unique node id.\n/// \\param[in] rgba Color information.\n/// \\param[in] is_opt_node Boolean of optimized nodes.\nvoid SetNodeForROS(PGOToyExample* toy, visualization_msgs::MarkerArray& nodes,\n              std::string ns, int id, Vec4 rgba, bool is_opt_node)\n{\n  visualization_msgs::Marker node;\n  node.header.frame_id = \"world\";\n  node.header.stamp = ros::Time::now();\n  node.ns = ns;\n  node.id = id;\n  node.type = visualization_msgs::Marker::SPHERE;\n  node.scale.x = node.scale.y = node.scale.z = 0.2;\n  node.color.r = rgba[0]; node.color.g = rgba[1]; node.color.b = rgba[2]; node.color.a = rgba[3];\n\n  if(!is_opt_node) {\n    Quaternion q = (Quaternion)toy->GetOriginalPoses()[id].rotation();\n\n    node.pose.position.x = toy->GetOriginalPoses()[id].translation()[0];\n    node.pose.position.y = toy->GetOriginalPoses()[id].translation()[1];\n    node.pose.position.z = toy->GetOriginalPoses()[id].translation()[2];\n    node.pose.orientation.x = q.x();\n    node.pose.orientation.y = q.y();\n    node.pose.orientation.z = q.z();\n    node.pose.orientation.w = q.w();\n\n    if(node.pose.orientation.w < 0) {\n      node.pose.orientation.x *= -1;\n      node.pose.orientation.y *= -1;\n      node.pose.orientation.z *= -1;\n      node.pose.orientation.w *= -1;\n    }\n    nodes.markers.push_back(node);\n  }\n  else {\n    g2o::VertexSE3Expmap* vtx = static_cast<g2o::VertexSE3Expmap*>(toy->GetOptimizer()->vertex(id));\n    Isometry opt_poses = vtx->estimate();\n    Quaternion q = (Quaternion)opt_poses.rotation();\n\n    // First node.\n    if(id==0) {\n      xinit = opt_poses.translation()[0];\n      yinit = opt_poses.translation()[1];\n      zinit = opt_poses.translation()[2];\n\n      node.pose.position.x = 0;\n      node.pose.position.y = 0;\n      node.pose.position.z = 0;\n    }\n\n    node.pose.position.x = opt_poses.translation()[0]-xinit;\n    node.pose.position.y = opt_poses.translation()[1]-yinit;\n    node.pose.position.z = opt_poses.translation()[2]-zinit;\n\n    node.pose.orientation.x = q.x();\n    node.pose.orientation.y = q.y();\n    node.pose.orientation.z = q.z();\n    node.pose.orientation.w = q.w();\n\n    if(node.pose.orientation.w < 0) {\n      node.pose.orientation.x *= -1;\n      node.pose.orientation.y *= -1;\n      node.pose.orientation.z *= -1;\n      node.pose.orientation.w *= -1;\n    }\n    nodes.markers.push_back(node);\n\n    visualization_msgs::Marker opt_node_text;\n    opt_node_text.header.frame_id = \"world\";\n    opt_node_text.header.stamp = ros::Time();\n    opt_node_text.ns = \"opt_node_text\";\n    opt_node_text.id = id;\n    opt_node_text.type = visualization_msgs::Marker::TEXT_VIEW_FACING;\n    opt_node_text.action = visualization_msgs::Marker::ADD;\n    opt_node_text.scale.z = 0.1;\n    opt_node_text.color.r =0.0; opt_node_text.color.g = 0.0; opt_node_text.color.b = 0.0; opt_node_text.color.a = 1.0;\n    opt_node_text.pose.position.x = node.pose.position.x;\n    opt_node_text.pose.position.y = node.pose.position.y;\n    opt_node_text.pose.position.z = node.pose.position.z+0.2;\n    std::string txt = \"x\" + std::to_string(id);\n    opt_node_text.text = txt;\n    texts.markers.push_back(opt_node_text);\n  }\n}\n\n/// \\brief Set the pose graph edge for ROS visualization.\n/// \\param[in] toy Pointer to PGOToyExample instance.\n/// \\param[out] edges Marker array of pose graph edges.\n/// \\param[in] ns Namespace.\n/// \\param[in] id Unique edge id.\n/// \\param[in] start Start pose node.\n/// \\param[in] end End pose node.\n/// \\param[in] rgba Color information.\n/// \\param[in] is_opt_edge Boolean of optimized edges.\nvoid SetEdgeForROS(PGOToyExample* toy, visualization_msgs::MarkerArray& edges,\n             std::string ns, int id, int start, int end, Vec4 rgba, bool is_opt_edge)\n{\n  visualization_msgs::Marker edge;\n  edge.header.frame_id = \"world\";\n  edge.header.stamp = ros::Time::now();\n  edge.ns = ns;\n  edge.id = id;\n  edge.type = visualization_msgs::Marker::LINE_LIST;\n  edge.color.r = rgba[0]; edge.color.g = rgba[1]; edge.color.b = rgba[2]; edge.color.a = rgba[3];\n  edge.pose.orientation.w = 1.0;\n  edge.scale.x = 0.01;\n\n  if(!is_opt_edge) {\n    geometry_msgs::Point p1;\n    p1.x = toy->GetOriginalPoses()[start].translation()[0];\n    p1.y = toy->GetOriginalPoses()[start].translation()[1];\n    p1.z = toy->GetOriginalPoses()[start].translation()[2];\n    edge.points.push_back(p1);\n\n    geometry_msgs::Point p2;\n    p2.x = toy->GetOriginalPoses()[end].translation()[0];\n    p2.y = toy->GetOriginalPoses()[end].translation()[1];\n    p2.z = toy->GetOriginalPoses()[end].translation()[2];\n    edge.points.push_back(p2);\n\n    edges.markers.push_back(edge);\n\n    visualization_msgs::Marker prev_edge_text;\n    prev_edge_text.header.frame_id = \"world\";\n    prev_edge_text.header.stamp = ros::Time();\n    prev_edge_text.ns = \"prev_edge_text\";\n    prev_edge_text.id = id;\n    prev_edge_text.type = visualization_msgs::Marker::TEXT_VIEW_FACING;\n    prev_edge_text.action = visualization_msgs::Marker::ADD;\n    prev_edge_text.scale.z = 0.1;\n    prev_edge_text.color.r = rgba[0]; prev_edge_text.color.g = rgba[1]; prev_edge_text.color.b = rgba[2]; prev_edge_text.color.a = rgba[3];\n    prev_edge_text.pose.position.x = (p1.x+p2.x)/2.;\n    prev_edge_text.pose.position.y = (p1.y+p2.y)/2.;\n    prev_edge_text.pose.position.z = (p1.z+p2.z)/2. + 0.1;\n    std::string txt = \"zhat\" + std::to_string(start) + std::to_string(end);\n    prev_edge_text.text = txt;\n    texts.markers.push_back(prev_edge_text);\n  }\n  else {\n    g2o::VertexSE3Expmap* prev_vtx = static_cast<g2o::VertexSE3Expmap*>(toy->GetOptimizer()->vertex(start));\n    g2o::VertexSE3Expmap* curr_vtx = static_cast<g2o::VertexSE3Expmap*>(toy->GetOptimizer()->vertex(end));\n    Isometry prev_opt_poses = prev_vtx->estimate();\n    Isometry curr_opt_poses = curr_vtx->estimate();\n\n    // First opt_node.\n    if(start == 0) {\n      xinit = prev_opt_poses.translation()[0];\n      yinit = prev_opt_poses.translation()[1];\n      zinit = prev_opt_poses.translation()[2];\n    }\n\n    geometry_msgs::Point p1;\n    p1.x = prev_opt_poses.translation()[0] -xinit;\n    p1.y = prev_opt_poses.translation()[1] -yinit;\n    p1.z = prev_opt_poses.translation()[2] -zinit;\n    edge.points.push_back(p1);\n\n    geometry_msgs::Point p2;\n    p2.x = curr_opt_poses.translation()[0] -xinit;\n    p2.y = curr_opt_poses.translation()[1] -yinit;\n    p2.z = curr_opt_poses.translation()[2] -zinit;\n    edge.points.push_back(p2);\n\n    edges.markers.push_back(edge);\n\n    visualization_msgs::Marker opt_edge_text;\n    opt_edge_text.header.frame_id = \"world\";\n    opt_edge_text.header.stamp = ros::Time();\n    opt_edge_text.ns = \"opt_edge_text\";\n    opt_edge_text.id = id;\n    opt_edge_text.type = visualization_msgs::Marker::TEXT_VIEW_FACING;\n    opt_edge_text.action = visualization_msgs::Marker::ADD;\n    opt_edge_text.scale.z = 0.1;\n    opt_edge_text.color.r = 0.0; opt_edge_text.color.g = 0.0; opt_edge_text.color.b = 0.0; opt_edge_text.color.a = 1.0;\n    opt_edge_text.pose.position.x = (p1.x+p2.x)/2.;\n    opt_edge_text.pose.position.y = (p1.y+p2.y)/2.;\n    opt_edge_text.pose.position.z = (p1.z+p2.z)/2. + 0.1;\n    std::string txt = \"z\" + std::to_string(start) + std::to_string(end);\n    opt_edge_text.text = txt;\n    texts.markers.push_back(opt_edge_text);\n  }\n\n}\n\n\nint main(int argc, char **argv) {\n  ros::init(argc,argv,\"pgo_toy_example\");\n  ros::NodeHandle nh, priv_nh(\"~\");\n\n  // Set the publishers.\n  ros::Publisher opt_node_pub = nh.advertise<visualization_msgs::MarkerArray>(\"opt_nodes\",1);\n  ros::Publisher opt_edge_pub = nh.advertise<visualization_msgs::MarkerArray>(\"opt_edges\",1);\n  ros::Publisher prev_node_pub = nh.advertise<visualization_msgs::MarkerArray>(\"prev_nodes\",1);\n  ros::Publisher prev_edge_pub = nh.advertise<visualization_msgs::MarkerArray>(\"prev_edges\",1);\n  ros::Publisher text_pub = nh.advertise<visualization_msgs::MarkerArray>(\"texts\",1);\n\n  int _rate, _iter;\n  priv_nh.param(\"loop_rate\", _rate, 5);  // loop rate [Hz].\n  priv_nh.param(\"iteration\", _iter, 20); // iteration of optimization.\n\n  // Create a PGO toy example instance.\n  PGOToyExample* toy = new PGOToyExample(true);\n\n  while(ros::ok()) {\n    // Set the loop speed [hz].\n    ros::Rate loop_rate(_rate);\n\n    // Reset the instance every iteration finished.\n    toy->Reset();\n    int num_poses = toy->GetOriginalPosesSize();\n    int count = 0;\n\n    while(count < _iter) {\n      // Set previous nodes and edges.\n      for(int i=0; i<num_poses; i++) {\n        SetNodeForROS(toy, prev_nodes, \"prev_nodes\", i, Vec4(0.0, 0.0, 0.0, 0.25), false);\n      }\n      for(int i=1; i<num_poses; i++) {\n        SetEdgeForROS(toy, prev_edges, \"prev_edges\", i, i-1, i, Vec4(0.0, 0.0, 0.0, 0.25), false);\n      }\n      SetEdgeForROS(toy, opt_edges, \"prev_edges\", 16, 5, 11, Vec4(0.0, 0.0, 0.0, 0.25), false);\n      SetEdgeForROS(toy, opt_edges, \"prev_edges\", 17, 3, 14, Vec4(0.0, 0.0, 0.0, 0.25), false);\n\n      // Set optimized poses and edges.\n      for(int i=0; i<num_poses; i++) {\n        SetNodeForROS(toy, prev_nodes, \"opt_nodes\", i, Vec4(0.0, 0.0, 0.0, 1.0), true);\n      }\n      for(int i=1; i<num_poses; i++) {\n        SetEdgeForROS(toy, opt_edges, \"opt_edges\", i, i-1, i, Vec4(0.0, 0.0, 0.0, 1), true);\n      }\n      SetEdgeForROS(toy, opt_edges, \"opt_edges\", 16, 5, 11, Vec4(0.0, 0.0, 0.0, 1), true);\n      SetEdgeForROS(toy, opt_edges, \"opt_edges\", 17, 3, 14, Vec4(0.0, 0.0, 0.0, 1), true);\n\n      // Set the text message marker.\n      visualization_msgs::Marker text;\n      text.header.frame_id = \"world\";\n      text.header.stamp = ros::Time();\n      text.ns = \"text\";\n      text.id = 0;\n      text.type = visualization_msgs::Marker::TEXT_VIEW_FACING;\n      text.action = visualization_msgs::Marker::ADD;\n      text.scale.z = 0.1;\n      text.color.r = 0.0; text.color.g = 0.0; text.color.b = 0.0; text.color.a = 1.0;\n      text.pose.position.y = 0.5;\n      text.pose.position.z = 1.0;\n      std::string comment = \"[PGO toy example using g2o]\\n\\nPose: SE3Quat\\nVertex: VertexSE3Expmap\\nEdge: EdgeSE3Expmap\\nInformation Matrix: Random\\n\\nBlack: Current Estimated Poses\\nGray: Previous Poses\";\n      text.text = comment;\n      texts.markers.push_back(text);\n\n      // Set the count message marker.\n      visualization_msgs::Marker count_text;\n      count_text.header.frame_id = \"world\";\n      count_text.header.stamp = ros::Time();\n      count_text.ns = \"count_text\";\n      count_text.id = 0;\n      count_text.type = visualization_msgs::Marker::TEXT_VIEW_FACING;\n      count_text.action = visualization_msgs::Marker::ADD;\n      count_text.scale.z = 0.1;\n      count_text.color.r = 0.0; count_text.color.g = 0.0; count_text.color.b = 0.0; count_text.color.a = 1.0;\n      count_text.pose.position.y = 0.5;\n      count_text.pose.position.z = 2.0;\n      std::string counttxt = \"Iteration: \" + std::to_string(count);\n      count_text.text = counttxt;\n      texts.markers.push_back(count_text);\n\n      // Publish to /texts\n      text_pub.publish(texts);\n\n      // Publish to /prev_edges\n      prev_edge_pub.publish(prev_edges);\n\n      // Publish to /opt_nodes\n      opt_node_pub.publish(opt_nodes);\n\n      // Publish to /opt_edges\n      opt_edge_pub.publish(opt_edges);\n\n      // Publish to /prev_nodes\n      prev_node_pub.publish(prev_nodes);\n\n      // Control the loop speed.\n      loop_rate.sleep();\n\n      // Do pose graph optimization (one time per each loop for visualization).\n      toy->GetOptimizer()->optimize(1);\n\n      // Add plus one count.\n      count += 1;\n    }\n\n    std::cout << std::endl;\n\n    // Clear pose graph.\n    prev_edges.markers.clear();\n    opt_nodes.markers.clear();\n    prev_nodes.markers.clear();\n    texts.markers.clear();\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "89f2f3b2e82acfab04d752a85305ca4f64a3d6d7", "size": 12780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pgo_toy_example_node.cpp", "max_stars_repo_name": "edward0im/pgo_toy_example", "max_stars_repo_head_hexsha": "6473b37f55a739f81faa80cf43e42be2ff3bd9f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-25T08:00:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T02:14:09.000Z", "max_issues_repo_path": "src/pgo_toy_example_node.cpp", "max_issues_repo_name": "edward0im/pgo_toy_example", "max_issues_repo_head_hexsha": "6473b37f55a739f81faa80cf43e42be2ff3bd9f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pgo_toy_example_node.cpp", "max_forks_repo_name": "edward0im/pgo_toy_example", "max_forks_repo_head_hexsha": "6473b37f55a739f81faa80cf43e42be2ff3bd9f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-22T08:44:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-17T08:47:38.000Z", "avg_line_length": 36.936416185, "max_line_length": 205, "alphanum_fraction": 0.6679186228, "num_tokens": 3635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5644946486758255}}
{"text": "#include <boost/numeric/odeint/stepper/adams_bashforth_moulton.hpp>\n", "meta": {"hexsha": "154b752c29fdbc7710d3bd8434dd22126c3259bb", "size": 68, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_numeric_odeint_stepper_adams_bashforth_moulton.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_numeric_odeint_stepper_adams_bashforth_moulton.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_numeric_odeint_stepper_adams_bashforth_moulton.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 34.0, "max_line_length": 67, "alphanum_fraction": 0.8529411765, "num_tokens": 21, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5644946486758255}}
{"text": "/**\n * @file hpt_test.cpp\n *\n * Tests for the hyper-parameter tuning module.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n\n#include <mlpack/core/cv/metrics/mse.hpp>\n#include <mlpack/core/cv/metrics/accuracy.hpp>\n#include <mlpack/core/cv/simple_cv.hpp>\n#include <mlpack/core/hpt/cv_function.hpp>\n#include <mlpack/core/hpt/fixed.hpp>\n#include <mlpack/core/hpt/hpt.hpp>\n#include <mlpack/core/optimizers/grid_search/grid_search.hpp>\n#include <mlpack/core/optimizers/gradient_descent/gradient_descent.cpp>\n#include <mlpack/methods/lars/lars.hpp>\n#include <mlpack/methods/logistic_regression/logistic_regression.hpp>\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace mlpack::cv;\nusing namespace mlpack::data;\nusing namespace mlpack::hpt;\nusing namespace mlpack::optimization;\nusing namespace mlpack::regression;\n\nBOOST_AUTO_TEST_SUITE(HPTTest);\n\n/**\n * Test CVFunction runs cross-validation in according with specified fixed\n * arguments and passed parameters.\n */\nBOOST_AUTO_TEST_CASE(CVFunctionTest)\n{\n  arma::mat xs = arma::randn(5, 100);\n  arma::vec beta = arma::randn(5, 1);\n  arma::rowvec ys = beta.t() * xs + 0.1 * arma::randn(1, 100);\n\n  SimpleCV<LARS, MSE> cv(0.2, xs, ys);\n\n  bool transposeData = true;\n  bool useCholesky = false;\n  double lambda1 = 1.0;\n  double lambda2 = 2.0;\n\n  FixedArg<bool, 1> fixedUseCholesky{useCholesky};\n  FixedArg<double, 3> fixedLambda1{lambda2};\n  CVFunction<decltype(cv), LARS, 4, FixedArg<bool, 1>, FixedArg<double, 3>>\n      cvFun(cv, 0.0, 0.0, fixedUseCholesky, fixedLambda1);\n\n  double expected = cv.Evaluate(transposeData, useCholesky, lambda1, lambda2);\n  arma::vec parameters(2);\n  parameters(0) = transposeData;\n  parameters(1) = lambda1;\n  double actual = cvFun.Evaluate(parameters);\n\n  BOOST_REQUIRE_CLOSE(expected, actual, 1e-5);\n}\n\n/**\n * This class provides the interface of CV classes, but really implements a\n * simple quadratic function of three variables.\n */\ntemplate<typename MLAlgorithm,\n         typename Metric = void,\n         typename MatType = void,\n         typename PredictionsType = void,\n         typename WeightsType = void>\nclass QuadraticFunction\n{\n public:\n  QuadraticFunction(double a,\n                    double b,\n                    double c,\n                    double d,\n                    double xMin = 0.0,\n                    double yMin = 0.0,\n                    double zMin = 0.0) :\n      a(a), b(b), c(c), d(d), xMin(xMin), yMin(yMin), zMin(zMin) {}\n\n  double Evaluate(double x, double y, double z)\n  {\n    return a * pow(x - xMin, 2)  + b * pow(y - yMin, 2) + c * pow(z - zMin, 2)\n        + d;\n  }\n\n  // Declaring and defining it just in order to provide the same interface as\n  // other CV classes.\n  MLAlgorithm Model()\n  {\n    return MLAlgorithm();\n  }\n\n private:\n  double a, b, c, d, xMin, yMin, zMin;\n};\n\n/**\n * Test CVFunction approximates gradient in the expected way.\n */\nBOOST_AUTO_TEST_CASE(CVFunctionGradientTest)\n{\n  double a = 1.0;\n  double b = -1.5;\n  double c = 2.5;\n  double d = 3.0;\n  QuadraticFunction<LARS> lf(a, b, c, d);\n\n  double relativeDelta = 0.01;\n  double minDelta = 0.001;\n  CVFunction<decltype(lf), LARS, 3> cvFun(lf, relativeDelta, minDelta);\n\n  double x = 0.0;\n  double y = -1.0;\n  double z = 2.0;\n  arma::mat gradient;\n  cvFun.Gradient(arma::vec(\"0.0 -1.0 2.0\"), gradient);\n\n  double xDelta = minDelta;\n  double yDelta = relativeDelta * abs(y);\n  double zDelta = relativeDelta * abs(z);\n\n  double aproximateXPartialDerivative = a * (2 * x + xDelta);\n  double aproximateYPartialDerivative = b * (2 * y + yDelta);\n  double aproximateZPartialDerivative = c * (2 * z + zDelta);\n\n  BOOST_REQUIRE_EQUAL(gradient.n_elem, 3);\n  BOOST_REQUIRE_CLOSE(gradient(0), aproximateXPartialDerivative, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(1), aproximateYPartialDerivative, 1e-5);\n  BOOST_REQUIRE_CLOSE(gradient(2), aproximateZPartialDerivative, 1e-5);\n}\n\n\nvoid InitProneToOverfittingData(arma::mat& xs,\n                                arma::rowvec& ys,\n                                double& validationSize)\n{\n  // Total number of data points.\n  size_t N = 10;\n  // Total number of features (all except the first one are redundant).\n  size_t M = 5;\n\n  arma::rowvec data = arma::linspace<arma::rowvec>(0.0, 10.0, N);\n  xs = data;\n  for (size_t i = 2; i <= M; ++i)\n    xs = arma::join_cols(xs, arma::pow(data, i));\n\n  // Responses that approximately follow the function y = 2 * x. Adding noise to\n  // avoid having a polynomial of degree 1 that exactly fits the points.\n  ys = 2 * data + 0.05 * arma::randn(1, N);\n\n  validationSize = 0.3;\n}\n\ntemplate<typename T1, typename T2>\nvoid FindLARSBestLambdas(arma::mat& xs,\n                         arma::rowvec& ys,\n                         double& validationSize,\n                         bool transposeData,\n                         bool useCholesky,\n                         const T1& lambda1Set,\n                         const T2& lambda2Set,\n                         double& bestLambda1,\n                         double& bestLambda2,\n                         double& bestObjective)\n{\n  SimpleCV<LARS, MSE> cv(validationSize, xs, ys);\n\n  bestObjective = std::numeric_limits<double>::max();\n\n  for (double lambda1 : lambda1Set)\n    for (double lambda2 : lambda2Set)\n    {\n      double objective =\n          cv.Evaluate(transposeData, useCholesky, lambda1, lambda2);\n      if (objective < bestObjective)\n      {\n        bestObjective = objective;\n        bestLambda1 = lambda1;\n        bestLambda2 = lambda2;\n      }\n    }\n}\n\n /**\n * Test grid-search optimization leads to the best parameters from the specified\n * ones.\n */\nBOOST_AUTO_TEST_CASE(GridSearchTest)\n{\n  arma::mat xs;\n  arma::rowvec ys;\n  double validationSize;\n  InitProneToOverfittingData(xs, ys, validationSize);\n\n  bool transposeData = true;\n  bool useCholesky = false;\n  arma::vec lambda1Set(\"0 0.001 0.01 0.1 1.0 10.0 100.0\");\n  std::array<double, 4> lambda2Set{{0.0, 0.05, 0.5, 5.0}};\n\n  double expectedLambda1, expectedLambda2, expectedObjective;\n  FindLARSBestLambdas(xs, ys, validationSize, transposeData, useCholesky,\n      lambda1Set, lambda2Set, expectedLambda1, expectedLambda2,\n      expectedObjective);\n\n  SimpleCV<LARS, MSE> cv(validationSize, xs, ys);\n  CVFunction<decltype(cv), LARS, 4, FixedArg<bool, 0>, FixedArg<bool, 1>>\n      cvFun(cv, 0.0, 0.0, {transposeData}, {useCholesky});\n\n  IncrementPolicy policy(true);\n  DatasetMapper<IncrementPolicy, double> datasetInfo(policy, 2);\n  for (double lambda1 : lambda1Set)\n    datasetInfo.MapString<size_t>(lambda1, 0);\n  for (double lambda2 : lambda2Set)\n    datasetInfo.MapString<size_t>(lambda2, 1);\n\n  GridSearch optimizer;\n  arma::mat actualParameters;\n  double actualObjective =\n      optimizer.Optimize(cvFun, actualParameters, datasetInfo);\n\n  BOOST_REQUIRE_CLOSE(expectedObjective, actualObjective, 1e-5);\n  BOOST_REQUIRE_CLOSE(expectedLambda1, actualParameters(0, 0), 1e-5);\n  BOOST_REQUIRE_CLOSE(expectedLambda2, actualParameters(1, 0), 1e-5);\n}\n\n/**\n * Test HyperParameterTuner.\n */\nBOOST_AUTO_TEST_CASE(HPTTest)\n{\n  arma::mat xs;\n  arma::rowvec ys;\n  double validationSize;\n  InitProneToOverfittingData(xs, ys, validationSize);\n\n  bool transposeData = true;\n  bool useCholesky = false;\n  arma::vec lambda1Set(\"0 0.001 0.01 0.1 1.0 10.0 100.0\");\n  arma::vec lambda2Set(\"0.0 0.05 0.5 5.0\");\n\n  double expectedLambda1, expectedLambda2, expectedObjective;\n  FindLARSBestLambdas(xs, ys, validationSize, transposeData, useCholesky,\n      lambda1Set, lambda2Set, expectedLambda1, expectedLambda2,\n      expectedObjective);\n\n  double actualLambda1, actualLambda2;\n  HyperParameterTuner<LARS, MSE, SimpleCV, GridSearch>\n      hpt(validationSize, xs, ys);\n  std::tie(actualLambda1, actualLambda2) = hpt.Optimize(Fixed(transposeData),\n      Fixed(useCholesky), lambda1Set, lambda2Set);\n\n  BOOST_REQUIRE_CLOSE(expectedObjective, hpt.BestObjective(), 1e-5);\n  BOOST_REQUIRE_CLOSE(expectedLambda1, actualLambda1, 1e-5);\n  BOOST_REQUIRE_CLOSE(expectedLambda2, actualLambda2, 1e-5);\n\n  /* Checking that the model provided by the hyper-parameter tuner shows the\n   * same performance. */\n  size_t validationFirstColumn = round(xs.n_cols * (1.0 - validationSize));\n  arma::mat validationXs = xs.cols(validationFirstColumn, xs.n_cols - 1);\n  arma::rowvec validationYs = ys.cols(validationFirstColumn, ys.n_cols - 1);\n  double objective = MSE::Evaluate(hpt.BestModel(), validationXs, validationYs);\n  BOOST_REQUIRE_CLOSE(expectedObjective, objective, 1e-5);\n}\n\n/**\n * Test HyperParamterTuner maximizes Accuracy rather than minimizes it.\n */\nBOOST_AUTO_TEST_CASE(HPTMaximizationTest)\n{\n  // Initializing a linearly separable dataset.\n  arma::mat xs = arma::linspace<arma::rowvec>(0.0, 10.0, 50);\n  arma::Row<size_t> ys = arma::join_rows(arma::zeros<arma::Row<size_t>>(25),\n      arma::ones<arma::Row<size_t>>(25));\n\n  // We will train and validate on the same dataset.\n  double validationSize = 0.5;\n  arma::mat doubledXs = arma::join_rows(xs, xs);\n  arma::Row<size_t> doubledYs = arma::join_rows(ys, ys);\n\n  // Defining lambdas to choose from. Zero should be preferred since big lambdas\n  // are likely to restrict capabilities of logistic regression.\n  arma::vec lambdas(\"0 1e12\");\n\n  // Making sure that the assumption above is true.\n  SimpleCV<LogisticRegression<>, Accuracy>\n      cv(validationSize, doubledXs, doubledYs);\n  BOOST_REQUIRE_GT(cv.Evaluate(0.0), cv.Evaluate(1e12));\n\n  HyperParameterTuner<LogisticRegression<>, Accuracy, SimpleCV>\n      hpt(validationSize, doubledXs, doubledYs);\n\n  double actualLambda;\n  std::tie(actualLambda) = hpt.Optimize(lambdas);\n\n  BOOST_REQUIRE_CLOSE(hpt.BestObjective(), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(actualLambda, 0.0, 1e-5);\n}\n\n/**\n * Test HyperParameterTuner works with GradientDescent.\n */\nBOOST_AUTO_TEST_CASE(HPTGradientDescentTest)\n{\n  // Constructor arguments for the fake CV function (QuadraticFunction).\n  double a = 1.0;\n  double b = -1.5;\n  double c = 2.5;\n  double d = 3.0;\n\n  // Optimal values for three \"hyper-parameters\".\n  double xMin = 1.5;\n  double yMin = 0.0;\n  double zMin = -2.0;\n\n  // We pass LARS just because some ML algorithm should be passed. We pass MSE\n  // to tell HyperParameterTuner that the objective function (QuadraticFunction)\n  // should be minimized.\n  HyperParameterTuner<LARS, MSE, QuadraticFunction, GradientDescent>\n      hpt(a, b, c, d, xMin, yMin, zMin);\n\n  // Setting GradientDescent to find more close solution to the optimal one.\n  hpt.Optimizer().StepSize() = 0.1;\n  hpt.Optimizer().Tolerance() = 1e-15;\n\n  // Always using the same small increase of arguments in calculation of partial\n  // derivatives.\n  hpt.RelativeDelta() = 0.0;\n  hpt.MinDelta() = 1e-10;\n\n  // We will try to find optimal values only for two \"hyper-parameters\".\n  double x0 = 3.0;\n  double y = yMin;\n  double z0 = -3.0;\n\n  double xOptimized, zOptimized;\n  std::tie(xOptimized, zOptimized) = hpt.Optimize(x0, Fixed(y), z0);\n  BOOST_REQUIRE_CLOSE(xOptimized, xMin, 1e-4);\n  BOOST_REQUIRE_CLOSE(zOptimized, zMin, 1e-4);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "eec9944dc4dc7d5043fb3a050562991379ccd8d0", "size": 11230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/hpt_test.cpp", "max_stars_repo_name": "chigur/mlpack", "max_stars_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-02T21:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T21:10:55.000Z", "max_issues_repo_path": "src/mlpack/tests/hpt_test.cpp", "max_issues_repo_name": "chigur/mlpack", "max_issues_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/hpt_test.cpp", "max_forks_repo_name": "chigur/mlpack", "max_forks_repo_head_hexsha": "aff1eda03b7c279acb6d3e660d5c5a6f697d3735", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3631123919, "max_line_length": 80, "alphanum_fraction": 0.6869100623, "num_tokens": 3219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5644946486758255}}
{"text": "/*\n * Copyright 2013-2015 Raphael Bost\n *\n * This file is part of ciphermed.\n\n *  ciphermed is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n * \n *  ciphermed is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n * \n *  You should have received a copy of the GNU General Public License\n *  along with ciphermed.  If not, see <http://www.gnu.org/licenses/>. 2\n *\n */\n\n#include <iostream>\n#include <math/num_th_alg.hh>\n#include <util/util.hh>\n#include <NTL/ZZ.h>\n\nusing namespace std;\n\nstatic void test_fact_generation(size_t m_bits)\n{\n    mpz_class m = 0;\n    mpz_setbit(m.get_mpz_t(),m_bits);\n\n    \n    mpz_class p;\n\n    gmp_randstate_t randstate;\n    gmp_randinit_default(randstate);\n    gmp_randseed_ui(randstate,time(NULL));\n\n    ScopedTimer *t = new ScopedTimer(\"Test factorization generation\");\n    std::vector<mpz_class> fact = gen_rand_prime_with_factorization(m,&p,randstate,25);\n    delete t;\n    \n    cout << \"Prime generated is \\n\" << p << endl;\n    cout << \"Factors:\\n\";\n    \n    for (size_t i = 0; i < fact.size(); i++) {\n        cout << fact[i] << endl;\n    }\n    \n    cout << \"\\n\" << m_bits << \" bits queried\\n\";\n    cout << \"p is \" << mpz_sizeinbase(p.get_mpz_t(),2) << \" bits\" << endl;\n}\n\nstatic void test_simple_safe_prime(size_t n_bits)\n{\n    gmp_randstate_t randstate;\n    gmp_randinit_default(randstate);\n    gmp_randseed_ui(randstate,time(NULL));\n    ScopedTimer *t;\n\n    /*\n    t = new ScopedTimer(\"Test simple safe prime\");\n    mpz_class p = simple_safe_prime_gen(n_bits,randstate,25);\n    delete t;\n    \n    cout << \"Prime generated is \\n\" << 2*p+1 << endl;\n    cout << \"\\n\" << n_bits << \" bits queried\\n\";\n    cout << \"p is \" << mpz_sizeinbase(p.get_mpz_t(),2) << \" bits\" << endl;\n*/\n    cout << \"\\n\\nWith NTL:\" << endl;\n    \n    t = new ScopedTimer(\"NTL safe prime\");\n    NTL::ZZ q = NTL::GenGermainPrime_ZZ(n_bits+1);\n    delete t;\n    cout << \"Prime generated is \\n\" << q << endl;\n    cout << \"q is \" << NTL::NumBits(q) << \" bits\" << endl;\n\n    mpz_class r;\n    t = new ScopedTimer(\"Our safe prime\");\n    gen_germain_prime(r,n_bits,randstate);\n    delete t;\n    cout << \"Prime generated is \\n\" << r << endl;\n    cout << \"q is \" <<mpz_sizeinbase(r.get_mpz_t(),2) << \" bits\" << endl;\n\n}\n\nint main()\n{\n//    test_fact_generation(512);\n    test_simple_safe_prime(512);\n    \n    return 0;\n}", "meta": {"hexsha": "47eef6df0e0eb433053757980ce3230f14e2face", "size": 2684, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Source/math/test_algo.cc", "max_stars_repo_name": "TarekIbnZiad/CryptoImg", "max_stars_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-05T18:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T07:33:10.000Z", "max_issues_repo_path": "Source/math/test_algo.cc", "max_issues_repo_name": "TarekIbnZiad/CryptoImg", "max_issues_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/math/test_algo.cc", "max_forks_repo_name": "TarekIbnZiad/CryptoImg", "max_forks_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-11T00:32:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T23:35:20.000Z", "avg_line_length": 28.5531914894, "max_line_length": 87, "alphanum_fraction": 0.640461997, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.564494648107448}}
{"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": "#ifndef SEQUENTIAL_LINE_SEARCH_PREFERENCE_REGRESSOR_HPP\n#define SEQUENTIAL_LINE_SEARCH_PREFERENCE_REGRESSOR_HPP\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <sequential-line-search/preference.hpp>\n#include <sequential-line-search/regressor.hpp>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace sequential_line_search\n{\n    /// \\brief Class for performing regression based on preference data.\n    ///\n    /// \\details See [Chu+, ICML 2005; Brochu+, NIPS 2007].\n    class PreferenceRegressor : public Regressor\n    {\n    public:\n        PreferenceRegressor(const Eigen::MatrixXd&         X,\n                            const std::vector<Preference>& D,\n                            const bool                     use_map_hyperparams          = false,\n                            const double                   default_kernel_signal_var    = 0.500,\n                            const double                   default_kernel_length_scale  = 0.500,\n                            const double                   default_noise_level          = 0.005,\n                            const double                   kernel_hyperparams_prior_var = 0.250,\n                            const double                   btl_scale                    = 0.010,\n                            const unsigned                 num_map_estimation_iters     = 100,\n                            const KernelType               kernel_type = KernelType::ArdMatern52Kernel);\n\n        double PredictMu(const Eigen::VectorXd& x) const override;\n        double PredictSigma(const Eigen::VectorXd& x) const override;\n\n        Eigen::VectorXd PredictMuDerivative(const Eigen::VectorXd& x) const override;\n        Eigen::VectorXd PredictSigmaDerivative(const Eigen::VectorXd& x) const override;\n\n        const bool m_use_map_hyperparams;\n\n        /// \\brief Find the data point that is likely to have the largest value from the so-far observed data points.\n        Eigen::VectorXd FindArgMax() const;\n\n        // Data\n        Eigen::MatrixXd         m_X;\n        std::vector<Preference> m_D;\n\n        /// \\brief Noise level hyperparameter\n        ///\n        /// \\details This value is either derived by the MAP estimation or copied from the default values\n        double m_noise_hyperparam;\n\n        /// \\brief Kernel hyperparameters\n        ///\n        /// \\details These values are either derived by the MAP estimation or copied from the default values\n        Eigen::VectorXd m_kernel_hyperparams;\n\n        /// \\brief Kernel matrix calculated in the MAP estimation procedure.\n        Eigen::MatrixXd m_K;\n\n        /// \\brief Kernel matrix stored as a Cholesky-decomposed form.\n        Eigen::LLT<Eigen::MatrixXd> m_K_llt;\n\n        // IO\n        void DampData(const std::string& dir_path, const std::string& prefix = \"\") const;\n\n        // Getter\n        const Eigen::MatrixXd& GetLargeX() const override { return m_X; }\n        const Eigen::VectorXd& GetSmallY() const override { return m_y; }\n\n        const Eigen::VectorXd& GetKernelHyperparams() const override { return m_kernel_hyperparams; }\n        double                 GetNoiseHyperparam() const override { return m_noise_hyperparam; }\n\n        // Default hyperparameters; when MAP is enabled, they are used as initial guesses.\n        const double m_default_kernel_signal_var;\n        const double m_default_kernel_length_scale;\n        const double m_default_noise_level;\n\n        /// \\brief Variance of the prior distribution. Used only when MAP is enabled.\n        const double m_kernel_hyperparams_prior_var;\n\n        /// \\brief Scale parameter in the BTL model\n        const double m_btl_scale;\n\n    private:\n        /// \\brief Goodness values derived by the MAP estimation.\n        Eigen::VectorXd m_y;\n\n        void PerformMapEstimation(const unsigned num_iters);\n    };\n} // namespace sequential_line_search\n\n#endif // SEQUENTIAL_LINE_SEARCH_PREFERENCE_REGRESSOR_HPP\n", "meta": {"hexsha": "27f36720d38e3d70650ffbc7b3d28468477a2c36", "size": 3921, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sequential-line-search/preference-regressor.hpp", "max_stars_repo_name": "yuki-koyama/sequential-line-search", "max_stars_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-03-12T13:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T20:28:04.000Z", "max_issues_repo_path": "include/sequential-line-search/preference-regressor.hpp", "max_issues_repo_name": "yuki-koyama/sequential-line-search", "max_issues_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T23:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T03:52:42.000Z", "max_forks_repo_path": "include/sequential-line-search/preference-regressor.hpp", "max_forks_repo_name": "yuki-koyama/sequential-line-search", "max_forks_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-06-12T17:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T11:13:03.000Z", "avg_line_length": 42.6195652174, "max_line_length": 117, "alphanum_fraction": 0.6256057128, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5644647759225014}}
{"text": "/**\n * @file tests/ann_dist_test.cpp\n * @author Atharva Khandait\n * @author Nishant Kumar\n *\n * Tests the ann distributions.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/dists/bernoulli_distribution.hpp>\n#include <mlpack/methods/ann/dists/normal_distribution.hpp>\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\n#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(ANNDistTest);\n\n/**\n * Simple bernoulli distribution module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleBernoulliDistributionTest)\n{\n  arma::mat param = arma::mat(\"1 1 0\");\n  BernoulliDistribution<> module(param, false);\n\n  arma::mat sample = module.Sample();\n  // As the probabilities are [1, 1, 0], the bernoulli samples should be\n  // [1, 1, 0] as well.\n  CheckMatrices(param, sample);\n}\n\n/**\n * Jacobian bernoulli distribution module test when we don't apply logistic.\n */\nBOOST_AUTO_TEST_CASE(JacobianBernoulliDistributionTest)\n{\n  for (size_t i = 0; i < 5; ++i)\n  {\n    const size_t targetElements = math::RandInt(2, 1000);\n\n    arma::mat param;\n    param.randn(targetElements, 1);\n\n    arma::mat target;\n    target.randn(targetElements, 1);\n\n    BernoulliDistribution<> module(param, false);\n\n    const double perturbation = 1e-6;\n    double outputA, outputB, original;\n    arma::mat jacobianA, jacobianB;\n\n    // Initialize the jacobian matrix.\n    jacobianA = arma::zeros(targetElements, 1);\n\n    for (size_t j = 0; j < targetElements; ++j)\n    {\n      original = module.Probability()(j);\n      module.Probability()(j) = original - perturbation;\n      outputA = module.LogProbability(target);\n      module.Probability()(j) = original + perturbation;\n      outputB = module.LogProbability(target);\n      module.Probability()(j) = original;\n      outputB -= outputA;\n      outputB /= 2 * perturbation;\n      jacobianA(j) = outputB;\n    }\n\n    module.LogProbBackward(target, jacobianB);\n    BOOST_REQUIRE_LE(arma::max(arma::max(arma::abs(jacobianA - jacobianB))),\n        1e-5);\n  }\n}\n\n/**\n * Jacobian bernoulli distribution module test when we apply logistic.\n */\nBOOST_AUTO_TEST_CASE(JacobianBernoulliDistributionLogisticTest)\n{\n  for (size_t i = 0; i < 5; ++i)\n  {\n    const size_t targetElements = math::RandInt(2, 1000);\n\n    arma::mat param;\n    param.randn(targetElements, 1);\n\n    arma::mat target;\n    target.randn(targetElements, 1);\n\n    BernoulliDistribution<> module(param);\n\n    const double perturbation = 1e-6;\n    double outputA, outputB, original;\n    arma::mat jacobianA, jacobianB;\n\n    // Initialize the jacobian matrix.\n    jacobianA = arma::zeros(targetElements, 1);\n\n    for (size_t j = 0; j < targetElements; ++j)\n    {\n      original = module.Logits()(j);\n      module.Logits()(j) = original - perturbation;\n      LogisticFunction::Fn(module.Logits(), module.Probability());\n      outputA = module.LogProbability(target);\n      module.Logits()(j) = original + perturbation;\n      LogisticFunction::Fn(module.Logits(), module.Probability());\n      outputB = module.LogProbability(target);\n      module.Logits()(j) = original;\n      LogisticFunction::Fn(module.Logits(), module.Probability());\n      outputB -= outputA;\n      outputB /= 2 * perturbation;\n      jacobianA(j) = outputB;\n    }\n\n    module.LogProbBackward(target, jacobianB);\n    BOOST_REQUIRE_LE(arma::max(arma::max(arma::abs(jacobianA - jacobianB))),\n        3e-5);\n  }\n}\n\n/**\n * Normal Distribution module test.\n */\nBOOST_AUTO_TEST_CASE(NormalDistributionTest)\n{\n  arma::vec mu = {1.1, 1.2, 1.5, 1.7};\n  arma::vec sigma = {0.1, 0.11, 0.5, 0.23};\n\n  ann::NormalDistribution<> normalDist(mu, sigma);\n\n  arma::vec x = {1.05, 1.1, 1.7, 2.5};\n\n  arma::vec prob;\n  normalDist.LogProbability(x, prob);\n\n  // Testing output of log probability for some random mu, sigma and x.\n  BOOST_REQUIRE_CLOSE(prob[0], 1.2586464, 1e-3);\n  BOOST_REQUIRE_CLOSE(prob[1], 0.8751131, 1e-3);\n  BOOST_REQUIRE_CLOSE(prob[2], -0.30579138, 1e-3);\n  BOOST_REQUIRE_CLOSE(prob[3], -5.498411, 1e-3);\n\n  arma::vec dmu, dsigma;\n  normalDist.ProbBackward(x, dmu, dsigma);\n\n  // Testing output of dmu and dsigma for some random mu, sigma and x.\n  BOOST_REQUIRE_CLOSE(dmu[0], -17.603287, 1e-3);\n  BOOST_REQUIRE_CLOSE(dsigma[0], -26.40487, 1e-3);\n  BOOST_REQUIRE_CLOSE(dmu[1], -19.827663, 1e-3);\n  BOOST_REQUIRE_CLOSE(dsigma[1], -3.7852707, 1e-3);\n  BOOST_REQUIRE_CLOSE(dmu[2], 0.5892323, 1e-3);\n  BOOST_REQUIRE_CLOSE(dsigma[2], -1.2373875, 1e-3);\n  BOOST_REQUIRE_CLOSE(dmu[3], 0.061901994, 1e-3);\n  BOOST_REQUIRE_CLOSE(dsigma[3], 0.19751444, 1e-3);\n}\n\n/**\n * Jacobian Normal Distribution module test for mean.\n */\nBOOST_AUTO_TEST_CASE(JacobianNormalDistributionMeanTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t targetElements = math::RandInt(2, 1000);\n\n    arma::mat mu;\n    mu.randn(targetElements, 1);\n\n    arma::mat sigma;\n    sigma.randu(targetElements, 1);\n\n    arma::mat x;\n    x.randn(targetElements, 1);\n\n    NormalDistribution<> module(mu, sigma);\n\n    const double perturbation = 1e-6;\n    arma::mat output, outputA, outputB, jacobianA, jacobianB;\n\n    // Initialize the jacobian matrix.\n    module.Probability(x, output);\n    jacobianA = arma::zeros(x.n_elem, output.n_elem);\n\n    for (size_t j = 0; j < x.n_elem; ++j)\n    {\n      double original = module.Mean()(j);\n      module.Mean()(j) = original - perturbation;\n      module.Probability(x, outputA);\n      module.Mean()(j) = original + perturbation;\n      module.Probability(x, outputB);\n      module.Mean()(j) = original;\n\n      outputB -= outputA;\n      outputB /= 2 * perturbation;\n      jacobianA.row(j) = outputB.t();\n    }\n\n    // Initialize the derivative parameter.\n    arma::mat deriv = arma::zeros(output.n_rows, output.n_cols);\n\n    // Share the derivative parameter.\n    arma::mat derivTemp = arma::mat(deriv.memptr(), deriv.n_rows, deriv.n_cols,\n        false, false);\n\n    // Initialize the jacobian matrix.\n    jacobianB = arma::zeros(mu.n_elem, output.n_elem);\n\n    for (size_t k = 0; k < derivTemp.n_elem; ++k)\n    {\n      deriv.zeros();\n      derivTemp(k) = 1;\n\n      arma::mat deltaMu, deltaSigma;\n      module.ProbBackward(x, deltaMu, deltaSigma);\n\n      jacobianB.col(k) = deltaMu % deriv;\n    }\n\n    BOOST_REQUIRE_LE(arma::max(arma::max(arma::abs(jacobianA - jacobianB))),\n        5e-3);\n  }\n}\n\n/**\n * Jacobian Normal Distribution module test for standard deviation.\n */\nBOOST_AUTO_TEST_CASE(JacobianNormalDistributionStandardDeviationTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t targetElements = math::RandInt(2, 1000);\n\n    arma::mat mu;\n    mu.randn(targetElements, 1);\n\n    arma::mat sigma;\n    sigma.randu(targetElements, 1);\n\n    arma::mat x;\n    x.randn(targetElements, 1);\n\n    NormalDistribution<> module(mu, sigma);\n\n    const double perturbation = 1e-6;\n    arma::mat output, outputA, outputB, jacobianA, jacobianB;\n\n    // Initialize the jacobian matrix.\n    module.Probability(x, output);\n    jacobianA = arma::zeros(x.n_elem, output.n_elem);\n\n    for (size_t j = 0; j < x.n_elem; ++j)\n    {\n      double original = module.StandardDeviation()(j);\n      module.StandardDeviation()(j) = original - perturbation;\n      module.Probability(x, outputA);\n      module.StandardDeviation()(j) = original + perturbation;\n      module.Probability(x, outputB);\n      module.StandardDeviation()(j) = original;\n\n      outputB -= outputA;\n      outputB /= 2 * perturbation;\n      jacobianA.row(j) = outputB.t();\n    }\n\n    // Initialize the derivative parameter.\n    arma::mat deriv = arma::zeros(output.n_rows, output.n_cols);\n\n    // Share the derivative parameter.\n    arma::mat derivTemp = arma::mat(deriv.memptr(), deriv.n_rows, deriv.n_cols,\n        false, false);\n\n    // Initialize the jacobian matrix.\n    jacobianB = arma::zeros(sigma.n_elem, output.n_elem);\n\n    for (size_t k = 0; k < derivTemp.n_elem; ++k)\n    {\n      deriv.zeros();\n      derivTemp(k) = 1;\n\n      arma::mat deltaMu, deltaSigma;\n      module.ProbBackward(x, deltaMu, deltaSigma);\n\n      jacobianB.col(k) = deltaSigma % deriv;\n    }\n\n    BOOST_REQUIRE_LE(arma::max(arma::max(arma::abs(jacobianA - jacobianB))),\n        5e-3);\n  }\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "702414759a4c83c02e88cf0f9fcefded53658ca3", "size": 8550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/ann_dist_test.cpp", "max_stars_repo_name": "birm/mlpack", "max_stars_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-29T17:39:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-16T23:36:01.000Z", "max_issues_repo_path": "src/mlpack/tests/ann_dist_test.cpp", "max_issues_repo_name": "birm/mlpack", "max_issues_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/ann_dist_test.cpp", "max_forks_repo_name": "birm/mlpack", "max_forks_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2178217822, "max_line_length": 79, "alphanum_fraction": 0.6661988304, "num_tokens": 2449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5644647709885048}}
{"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": "#define BOOST_TEST_MODULE pcraster geo average_filter\n#include <boost/test/unit_test.hpp>\n#include \"geo_averagefilter.h\"\n#include \"geo_filterengine.h\"\n\n\nBOOST_AUTO_TEST_CASE(test)\n{\n  using namespace geo;\n\n  //  1  2  3  4  5\n  //  6  7  8  9 10\n  // 11 12 13 14 15\n  // 16 17 MV 19 20\n  // 21 22 23 24 25\n\n  {\n    // Create source raster.\n    SimpleRaster<double> source(5, 5);\n    source.cell(0, 0) = 1;\n    source.cell(0, 1) = 2;\n    source.cell(0, 2) = 3;\n    source.cell(0, 3) = 4;\n    source.cell(0, 4) = 5;\n    source.cell(1, 0) = 6;\n    source.cell(1, 1) = 7;\n    source.cell(1, 2) = 8;\n    source.cell(1, 3) = 9;\n    source.cell(1, 4) = 10;\n    source.cell(2, 0) = 11;\n    source.cell(2, 1) = 12;\n    source.cell(2, 2) = 13;\n    source.cell(2, 3) = 14;\n    source.cell(2, 4) = 15;\n    source.cell(3, 0) = 16;\n    source.cell(3, 1) = 17;\n    pcr::setMV(source.cell(3, 2));\n    source.cell(3, 3) = 19;\n    source.cell(3, 4) = 20;\n    source.cell(4, 0) = 21;\n    source.cell(4, 1) = 22;\n    source.cell(4, 2) = 23;\n    source.cell(4, 3) = 24;\n    source.cell(4, 4) = 25;\n\n    // Filter for calculating average within kernel.\n    SimpleRaster<double> weights(3, 3, 1.0);\n    AverageFilter filter(weights);\n\n    // Destination raster.\n    SimpleRaster<double> destination(5, 5);\n\n    FilterEngine<double, double> engine(source, filter, destination);\n    engine.calc();\n\n    BOOST_CHECK(destination.cell(0, 0) == 4.0);\n    BOOST_CHECK(destination.cell(0, 1) == 4.5);\n    BOOST_CHECK(destination.cell(0, 2) == 5.5);\n    BOOST_CHECK(destination.cell(0, 3) == 6.5);\n    BOOST_CHECK(destination.cell(0, 4) == 7.0);\n\n    BOOST_CHECK(destination.cell(1, 0) == 6.5);\n    BOOST_CHECK(destination.cell(1, 1) == 7.0);\n    BOOST_CHECK(destination.cell(1, 2) == 8.0);\n    BOOST_CHECK(destination.cell(1, 3) == 9.0);\n    BOOST_CHECK(destination.cell(1, 4) == 9.5);\n\n    BOOST_CHECK(destination.cell(2, 0) == 11.5);\n    BOOST_CHECK(destination.cell(2, 1) == 11.25);\n    BOOST_CHECK(destination.cell(2, 2) == 12.375);\n    BOOST_CHECK(destination.cell(2, 3) == 13.5);\n    BOOST_CHECK(destination.cell(2, 4) == 14.5);\n\n\n    BOOST_CHECK(destination.cell(3, 0) == 16.5);\n    BOOST_CHECK(destination.cell(3, 1) == 16.875);\n    BOOST_CHECK(pcr::isMV(destination.cell(3, 2)));\n    BOOST_CHECK(destination.cell(3, 3) == 19.125);\n    BOOST_CHECK(destination.cell(3, 4) == 19.5);\n\n    BOOST_CHECK(destination.cell(4, 0) == 19.0);\n    BOOST_CHECK(destination.cell(4, 1) == 19.8);\n    BOOST_CHECK(destination.cell(4, 2) == 21);\n    BOOST_CHECK(destination.cell(4, 3) == 22.2);\n    BOOST_CHECK(destination.cell(4, 4) == 22);\n  }\n\n  {\n    // Create raster:\n    // MV MV MV\n    // MV MV  6\n    // MV MV MV\n    SimpleRaster<double> source(3, 3);\n    pcr::setMV(source.cell(0, 0));\n    pcr::setMV(source.cell(0, 1));\n    pcr::setMV(source.cell(0, 2));\n    pcr::setMV(source.cell(1, 0));\n    pcr::setMV(source.cell(1, 1));\n    source.cell(1, 2) = 6.0;\n    pcr::setMV(source.cell(2, 0));\n    pcr::setMV(source.cell(2, 1));\n    pcr::setMV(source.cell(2, 2));\n\n    // Filter for calculating average within kernel.\n    SimpleRaster<double> weights(3, 3, 1.0);\n    AverageFilter filter(weights);\n\n    // Destination raster.\n    SimpleRaster<double> destination(3, 3);\n\n    FilterEngine<double, double> engine(source, filter, destination);\n    engine.calc();\n\n    BOOST_CHECK(pcr::isMV(destination.cell(0, 0)));\n    BOOST_CHECK(pcr::isMV(destination.cell(0, 1)));\n    BOOST_CHECK(pcr::isMV(destination.cell(0, 2)));\n    BOOST_CHECK(pcr::isMV(destination.cell(1, 0)));\n    BOOST_CHECK(pcr::isMV(destination.cell(1, 1)));\n    BOOST_CHECK(destination.cell(1, 2) == 6.0);\n    BOOST_CHECK(pcr::isMV(destination.cell(2, 0)));\n    BOOST_CHECK(pcr::isMV(destination.cell(2, 1)));\n    BOOST_CHECK(pcr::isMV(destination.cell(2, 2)));\n  }\n\n  {\n    // Create raster:\n    // MV MV MV\n    // MV MV  6\n    // MV MV MV\n    SimpleRaster<double> source(3, 3);\n    pcr::setMV(source.cell(0, 0));\n    pcr::setMV(source.cell(0, 1));\n    pcr::setMV(source.cell(0, 2));\n    pcr::setMV(source.cell(1, 0));\n    pcr::setMV(source.cell(1, 1));\n    source.cell(1, 2) = 6.0;\n    pcr::setMV(source.cell(2, 0));\n    pcr::setMV(source.cell(2, 1));\n    pcr::setMV(source.cell(2, 2));\n\n    // Calculate average values for current and cell to the right.\n    // 0 0 0\n    // 0 1 1\n    // 0 0 0\n    SimpleRaster<double> weights(3, 3, 0.0);\n    weights.cell(1, 1) = 1.0;\n    weights.cell(1, 2) = 1.0;\n    AverageFilter filter(weights);\n\n    // Destination raster.\n    SimpleRaster<double> destination(3, 3);\n\n    FilterEngine<double, double> engine(source, filter, destination);\n    engine.calc();\n\n    BOOST_CHECK(pcr::isMV(destination.cell(0, 0)));\n    BOOST_CHECK(pcr::isMV(destination.cell(0, 1)));\n    BOOST_CHECK(pcr::isMV(destination.cell(0, 2)));\n    BOOST_CHECK(pcr::isMV(destination.cell(1, 0)));\n    BOOST_CHECK(pcr::isMV(destination.cell(1, 1)));\n    BOOST_CHECK(destination.cell(1, 2) == 6.0);\n    BOOST_CHECK(pcr::isMV(destination.cell(2, 0)));\n    BOOST_CHECK(pcr::isMV(destination.cell(2, 1)));\n    BOOST_CHECK(pcr::isMV(destination.cell(2, 2)));\n  }\n}\n", "meta": {"hexsha": "54bdb62f2f726ddfc1a4479dd882c8410ea04a4c", "size": 5095, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_averagefiltertest.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_averagefiltertest.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_averagefiltertest.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5089820359, "max_line_length": 69, "alphanum_fraction": 0.6111874387, "num_tokens": 1775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5642917570517557}}
{"text": "#include <iostream>\n#include <chrono>\n#include <FreeImage.h>\n#include <Eigen/Core>\n\n#define WIDTH 1920\n#define HEIGHT 1080\n#define BITS_PER_PIXEL 24\n#define OUTPUT_FILE \"output.png\"\n\nusing namespace std;\ntypedef FIBITMAP Image;\ntypedef RGBQUAD Colour;\n\nint main() {\n    FreeImage_Initialise();\n\n    Image * image = FreeImage_Allocate(WIDTH, HEIGHT, BITS_PER_PIXEL);\n    if (!image) exit(EXIT_FAILURE);\n\n    Colour colour{0,0,0,1};\n\n    auto start = chrono::steady_clock::now();\n\n\n    //\n    // INSERT IMAGE RENDERING CODE HERE!\n    //\n\n    Eigen::MatrixXf m = Eigen::MatrixXf::Random(HEIGHT, WIDTH);\n\n    for (unsigned int y = 0; y < HEIGHT; ++y)\n        for (unsigned int x = 0; x < WIDTH; ++x)\n        {\n            colour.rgbRed   = m(y,x) * 255;\n            colour.rgbGreen = m(y,x) * 255;\n            colour.rgbBlue  = m(y,x) * 255;\n            FreeImage_SetPixelColor(image, x, y, &colour);\n        }\n\n    //\n    // REPLACE THE IMAGE RENDERING CODE ABOVE!\n    //\n\n\n    auto end = chrono::steady_clock::now();\n    auto diff = end - start;\n    cout << \"Render time = \" << chrono::duration <double, milli> (diff).count() / 1000.0 << \"s\" << endl;\n\n    if (FreeImage_Save(FIF_PNG, image, OUTPUT_FILE, 0))\n        cout << \"Image saved!\" << endl;\n\n    FreeImage_DeInitialise();\n    exit(EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "37dd9d819f0bf64a3acb128d36388b9c2fe1f4e4", "size": 1303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "darrenmothersele/hiq-template2", "max_stars_repo_head_hexsha": "2e4cd627294e5816d27ad2c763679f7b8f60288a", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "darrenmothersele/hiq-template2", "max_issues_repo_head_hexsha": "2e4cd627294e5816d27ad2c763679f7b8f60288a", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "darrenmothersele/hiq-template2", "max_forks_repo_head_hexsha": "2e4cd627294e5816d27ad2c763679f7b8f60288a", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2678571429, "max_line_length": 104, "alphanum_fraction": 0.6055257099, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5642917570517556}}
{"text": "/**\n * Test for the KalmanFilter class with 1D projectile motion.\n *\n * @author: Hayk Martirosyan\n * @date: 2014.11.15\n */\n#include <ros/ros.h>\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include \"kalman.hpp\"\n\n#include <people_msgs/PositionMeasurement.h>\n#include <visualization_msgs/Marker.h>\n\ntemplate <typename T> std::string tostr(const T& t)\n{\n    std::ostringstream os; os<<t; return os.str();\n}\n\nstatic std::string fixed_frame = \"odom\";\n\nclass KalmanTracker{\nprivate:\n    ros::Rate r;\n    ros::Subscriber person_pos_sub;\n    ros::Publisher markers_pub,text_pub,estimate_pos_pub;\n    ros::NodeHandle nh1;\n    ros::Time start,now;\n    Eigen::VectorXd x,y;\n    Eigen::MatrixXd A; // System dynamics matrix\n    Eigen::MatrixXd C; // Output matrix\n    Eigen::MatrixXd Q; // Process noise covariance\n    Eigen::MatrixXd R; // Measurement noise covariance\n    Eigen::MatrixXd P; // Estimate error covariance\n    KalmanFilter estimate_X,estimate_Y;\n    int n; // Number of states\n    int m; // Number of measurements\n    int init_f,update_f;\n    double dt; // Time step\n    double t; // Time\npublic:\n    KalmanTracker(ros::NodeHandle nh):\n    nh1(nh),r(10),n(3),m(1),dt(1.0/10),init_f(0)\n    {\n        x = Eigen::VectorXd(n);\n        y = Eigen::VectorXd(n);\n        A = Eigen::MatrixXd(n,n);\n        C = Eigen::MatrixXd(m,n);\n        Q = Eigen::MatrixXd(n,n);\n        R = Eigen::MatrixXd(m,m);\n        P = Eigen::MatrixXd(n,n);\n        // Discrete LTI projectile motion, measuring position only\n        A << 1, dt, 1/2*dt*dt, 0, 1, dt, 0, 0, 1;\n        C << 1, 0, 0;\n        // Reasonable covariance matrices\n        Q << .05, .05, .0, .05, .05, .0, .0, .0, .0;\n        R << 5;\n        P << .1, .1, .1, .1, 10000, 10, .1, 10, 100;\n        estimate_X=KalmanFilter(dt,A, C, Q, R, P);\n        estimate_Y=KalmanFilter(dt,A, C, Q, R, P);\n        estimate_X.init(0,x);\n        estimate_Y.init(0,y);\n        //start = now = ros::Time::now();\n        person_pos_sub = nh1.subscribe(\"filter_measurement\",1,&KalmanTracker::msgCallback_PeopleTracker, this);\n        markers_pub = nh1.advertise<visualization_msgs::Marker>(\"filter_marker\", 20);//Output of KF\n        estimate_pos_pub = nh1.advertise<people_msgs::PositionMeasurement>(\"estimate_pos\", 20);\n        //text_pub = nh1.advertise<visualization_msgs::Marker>(\"tracking_text\", 20);\n        //estimate_pos_pub = nh1.advertise<geometry_msgs::PoseStamped>(\"human_pose\", 20);\n\n        std::cout << \"A: \\n\" << A << std::endl;\n        std::cout << \"C: \\n\" << C << std::endl;\n        std::cout << \"Q: \\n\" << Q << std::endl;\n        std::cout << \"R: \\n\" << R << std::endl;\n        std::cout << \"P: \\n\" << P << std::endl;\n  }\n\n    void msgCallback_PeopleTracker(const people_msgs::PositionMeasurement::ConstPtr& msg )\n    {\n        if(msg->initialization == 1){\n        // Best guess of initial states\n            std::cout<<\"---Initialization---\"<<std::endl;\n            //start = now = ros::Time::now();\n            x <<msg->pos.x, 0.0, 0.0;\n            estimate_X.init(t,x);\n            y << msg->pos.y, 0.0, 0.0;\n            estimate_Y.init(t,y);\n            init_f=1;\n        }\n        else if(init_f==1){\n            //now = ros::Time::now();\n            std::cout<<\"Update position\"<<std::endl;\n            Eigen::VectorXd z(m);\n            z <<msg->pos.x;\n            estimate_X.update(z);\n            z <<msg->pos.y;\n            estimate_Y.update(z);\n        }\n\n        //std::cout <<\"x_hat=\" << estimate_X.state().transpose()<<std::endl;\n        //std::cout <<\"y_hat=\" << estimate_Y.state().transpose()<<std::endl;\n\n        visualization_msgs::Marker m;\n        m.header.stamp = ros::Time::now();\n        m.header.frame_id = fixed_frame;\n        m.type = m.SPHERE;\n        m.scale.x = .6;\n        m.scale.y = .6;\n        m.scale.z = .6;\n        m.color.a = 0.2;\n        m.color.g = 0.5;\n        m.pose.position.x = estimate_X.state()[0];\n        m.pose.position.y = estimate_Y.state()[0];\n\n        people_msgs::PositionMeasurement estimate_pos;\n        estimate_pos.header.stamp = ros::Time::now();\n        estimate_pos.header.frame_id = fixed_frame;\n        estimate_pos.name = \"tracking\";\n        estimate_pos.pos.x = estimate_X.state()[0];\n        estimate_pos.pos.y = estimate_Y.state()[0];\n        estimate_pos.pos.z = 0;\n        //std::cout<<estimate_X.cov()<<std::endl;\n        estimate_pos.covariance[0] = (estimate_X.cov()(0,0)+estimate_Y.cov()(0,0))/2;\n        estimate_pos.covariance[1] = 0.0;\n        estimate_pos.covariance[2] = 0.0;\n        estimate_pos.covariance[3] = 0.0;\n        estimate_pos.covariance[4] = (estimate_X.cov()(1,1)+estimate_Y.cov()(1,1))/2;\n        estimate_pos.covariance[5] = 0.0;\n        estimate_pos.covariance[6] = 0.0;\n        estimate_pos.covariance[7] = 0.0;\n        estimate_pos.covariance[8] = (estimate_X.cov()(2,2)+estimate_Y.cov()(2,2))/2;\n\n        if(init_f==1){\n            markers_pub.publish(m);\n            estimate_pos_pub.publish(estimate_pos);\n        }\n    //r.sleep();\n    }\n};\n\n// \u8cfc\u8aad\u8005\u30ce\u30fc\u30c9\u306e\u30e1\u30a4\u30f3\u95a2\u6570\nint main(int argc, char **argv)\n{\n    // \u30ce\u30fc\u30c9\u540d\u306e\u521d\u671f\u5316\n    ros::init(argc, argv, \"person_tracking_filter_kalman\");\n    // ROS\u30b7\u30b9\u30c6\u30e0\u3068\u306e\u901a\u4fe1\u306e\u305f\u3081\u306e\u30ce\u30fc\u30c9\u306e\u30cf\u30f3\u30c9\u30eb\u3092\u5ba3\u8a00\n    ros::NodeHandle nh;\n    KalmanTracker kt(nh);\n    ros::spin();\n    return 0;\n}\n", "meta": {"hexsha": "2331b16a7e9addee9d081136dab879b268948ef2", "size": 5243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/person_tracking_kalman/src/person_tracking_filter_kalman_node.cpp", "max_stars_repo_name": "ayuguchi/gazed_object_identification_robot", "max_stars_repo_head_hexsha": "c06a49e405fa7c8a05ea6c4540b2a34b4aeca243", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/person_tracking_kalman/src/person_tracking_filter_kalman_node.cpp", "max_issues_repo_name": "ayuguchi/gazed_object_identification_robot", "max_issues_repo_head_hexsha": "c06a49e405fa7c8a05ea6c4540b2a34b4aeca243", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/person_tracking_kalman/src/person_tracking_filter_kalman_node.cpp", "max_forks_repo_name": "ayuguchi/gazed_object_identification_robot", "max_forks_repo_head_hexsha": "c06a49e405fa7c8a05ea6c4540b2a34b4aeca243", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T15:47:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T15:47:50.000Z", "avg_line_length": 34.4934210526, "max_line_length": 111, "alphanum_fraction": 0.5761968339, "num_tokens": 1540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5642917560713078}}
{"text": "\n\n#include <iostream>\n#include <chrono>\n#include <math.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main ()\n{\n    VectorXd vec1;\n\n    // Testing Eigen matrix\n    // Copied from: https://gitlab.com/libeigen/eigen/-/blob/master/doc/examples/QuickStart_example.cpp \n\n    auto tsim1 = std::chrono::high_resolution_clock::now();\n    \n    MatrixXd m(2,2); // matrix composed by doubles.\n    m(0,0) = 3;\n    m(1,0) = 2.5;\n    m(0,1) = -1;\n    m(1,1) = m(1,0) + m(0,1);\n    cout << m << endl;\n\n    VectorXd v(2);\n    v(0) = 4;\n    v(1) = v(0) - 1;\n    cout << \"Here is the vector v:\\n\" << v << endl;\n\n    cout << \"Here is the vector v:\\n\" << v << endl;\n\n    auto tsim2 = chrono::high_resolution_clock::now();\n    chrono::duration<double, milli> elapsed_time = tsim2 - tsim1;\n    cout << \"measure time: \" << elapsed_time.count() << endl;\n  \n    return 0;\n}", "meta": {"hexsha": "dc8943bd22ebf2ef82ca63dcdcf262d3563d18aa", "size": 900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mainprograms/mainEigenTest.cpp", "max_stars_repo_name": "jjssobrinho/FemCourseEigenClass2021", "max_stars_repo_head_hexsha": "25f35e9ce32d92057151b15ee5e9c2fa7db0db4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-12T13:21:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T13:21:51.000Z", "max_issues_repo_path": "mainprograms/mainEigenTest.cpp", "max_issues_repo_name": "Kauehenrik/FemCourseEigenClass2021", "max_issues_repo_head_hexsha": "d4927d92b541fdd2b2aa1fa424a413dd561ae96e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-16T12:36:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-16T12:36:07.000Z", "max_forks_repo_path": "mainprograms/mainEigenTest.cpp", "max_forks_repo_name": "Kauehenrik/FemCourseEigenClass2021", "max_forks_repo_head_hexsha": "d4927d92b541fdd2b2aa1fa424a413dd561ae96e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2021-04-26T13:53:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T03:12:36.000Z", "avg_line_length": 22.5, "max_line_length": 104, "alphanum_fraction": 0.59, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5642917560713077}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <shz/math/frustum.hpp>\n\n\nBOOST_AUTO_TEST_CASE(frustumConstructors)\n{\n    shz::math::matrix<shz::math::f32, 4, 4> projection;\n\tshz::math::frustum<shz::math::f32> f;\n    \n    projection = shz::math::matrix<shz::math::f32, 4, 4> ::ortho(-1, 1, -1, 1, 0.1f, 100.f);\n\n    f.generate_planes_from_projection(projection);\n    \n    BOOST_CHECK(f.num_planes == 6);\n}", "meta": {"hexsha": "cb10ff0bbbaf9d1dcc4310604b43978a68406298", "size": 401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Math/frustum_tests.cpp", "max_stars_repo_name": "TraxNet/ShadingZenCpp", "max_stars_repo_head_hexsha": "46860da3249900259941bf64f4a46347500b65fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-04-30T15:41:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-28T05:47:18.000Z", "max_issues_repo_path": "tests/Math/frustum_tests.cpp", "max_issues_repo_name": "TraxNet/ShadingZenCpp", "max_issues_repo_head_hexsha": "46860da3249900259941bf64f4a46347500b65fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Math/frustum_tests.cpp", "max_forks_repo_name": "TraxNet/ShadingZenCpp", "max_forks_repo_head_hexsha": "46860da3249900259941bf64f4a46347500b65fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7333333333, "max_line_length": 92, "alphanum_fraction": 0.6658354115, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5642917458850867}}
{"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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\n\ntemplate <typename Matrix>\nvoid test(Matrix& A, const char* name)\n{\n    using mtl::Collection;\n    A.change_dim(5, 5); A= 0.0;\n    {\n\tmtl::mat::inserter<Matrix>   ins(A);\n\tins[0][0] << 7; ins[1][1] << 8; ins[1][3] << 2; ins[1][4] << 3;\n\tins[2][2] << 2; ins[3][3] << 4; ins[4][4] << 9;\n     }\n    \n    cout << name << \"\\nA is set to \\n\" << A;\n    invert_diagonal(A);\n    \n    cout << \"\\nAfter inverting the diagonal, it is: \\n\" << A;\n    MTL_THROW_IF(std::abs(A[0][0] - 1.0 / 7.0) > 0.0001, mtl::runtime_error(\"Wrong value after inverting diagonal!\"));\n    MTL_THROW_IF(std::abs(A[1][3] - 2.0) > 0.0001, mtl::runtime_error(\"Wrong value after inverting diagonal!\"));\n\n}\n\nint main(int, char**)\n{\n    mtl::dense2D<double>                                                dr;\n    mtl::dense2D<double, mtl::mat::parameters<mtl::col_major> >      dc;\n    mtl::morton_dense<double, mtl::recursion::morton_z_mask>            mzd;\n    mtl::morton_dense<double, mtl::recursion::doppled_2_row_mask>       d2r;\n    mtl::compressed2D<double>                                           cr;\n    mtl::compressed2D<double, mtl::mat::parameters<mtl::col_major> > cc;\n\n    test(dr, \"Dense row major\");\n    test(dc, \"Dense column major\");\n    test(mzd, \"Morton Z-order\");\n    test(d2r, \"Hybrid 2 row-major\");\n    test(cr, \"Compressed row major\");\n    test(cc, \"Compressed column major\");\n\n    return 0;\n}\n", "meta": {"hexsha": "eae3c192d5ce17b5d01955e8534d33dc72cff33b", "size": 1907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/invert_diagonal_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/invert_diagonal_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/invert_diagonal_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.8793103448, "max_line_length": 118, "alphanum_fraction": 0.5988463555, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.5642628142918029}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2017, Massachusetts Institute of Technology,\n * Cambridge, MA 02139\n * All Rights Reserved\n * Authors: Luca Carlone, et al. (see THANKS for the full author list)\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n/**\n * @file   testParallelPlaneRegularTangentSpaceFactor.cpp\n * @brief  test ParallelPlaneRegularTangentSpaceFactor\n * @author Antoni Rosinol Vidal\n */\n\n#include <algorithm>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <random>\n\n#include <gtsam/base/numericalDerivative.h>\n#include <boost/assign/std/vector.hpp>\n#include <boost/bind.hpp>\n\n#include <gtsam/geometry/OrientedPlane3.h>\n#include <gtsam/geometry/Point3.h>\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/slam/PriorFactor.h>\n\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n\n#include \"kimera-vio/factors/ParallelPlaneRegularFactor.h\"\n#include \"kimera-vio/factors/PointPlaneFactor.h\"\n\nusing namespace std;\nusing namespace gtsam;\n\nstatic const double tol = 1e-5;\nstatic const double der_tol = 1e-5;\n\n/**\n * Test that error does give the right result when it is zero.\n */\nTEST(testParallelPlaneRegularTangentSpaceFactor, ErrorIsZero) {\n  /// Plane keys.\n  Key plane_key_1(1);\n  Key plane_key_2(2);\n\n  /// Noise model for cosntraint between the two planes.\n  noiseModel::Diagonal::shared_ptr parallel_plane_noise =\n      noiseModel::Diagonal::Sigmas(Vector3(0.1, 0.1, 0.1));\n\n  /// Parallelism constraint between Plane 1 and Plane 2.\n  ParallelPlaneRegularTangentSpaceFactor factor(plane_key_1, plane_key_2,\n                                                parallel_plane_noise);\n\n  /// Planes.\n  OrientedPlane3 plane_1(0.1, 0.1, 0.9, 0.9);\n  OrientedPlane3 plane_2(0.1, 0.1, 0.9, 0.1);\n\n  /// Calculate error.\n  Vector error = factor.evaluateError(plane_1, plane_2);\n\n  /// Expected error.\n  Vector2 expected_error = Vector2::Constant(0.0);\n\n  ASSERT_TRUE(assert_equal(expected_error, error, tol));\n}\n\n/**\n * Test that error does give the right result when it is not zero.\n */\nTEST(testParallelPlaneRegularTangentSpaceFactor, ErrorOtherThanZero) {\n  /// Plane keys.\n  Key plane_key_1(1);\n  Key plane_key_2(2);\n\n  /// Noise model for cosntraint between the two planes.\n  noiseModel::Diagonal::shared_ptr parallel_plane_noise =\n      noiseModel::Diagonal::Sigmas(Vector3(0.1, 0.1, 0.1));\n\n  /// Parallelism constraint between Plane 1 and Plane 2.\n  ParallelPlaneRegularTangentSpaceFactor factor(plane_key_1, plane_key_2,\n                                                parallel_plane_noise);\n\n  /// Planes.\n  OrientedPlane3 plane_1(0.0, 0.0, 1.0, 0.9);\n  OrientedPlane3 plane_2(0.1, 0.1, 0.9, 0.1);\n\n  /// Calculate error.\n  Vector error = factor.evaluateError(plane_1, plane_2);\n\n  /// Expected error.\n  Vector2 expected_error;\n  expected_error << 0.109764, -0.109764;\n\n  ASSERT_TRUE(assert_equal(expected_error, error, tol));\n}\n\n/**\n * Test that analytical jacobians equal numerical ones.\n *\n */\nTEST(testParallelPlaneRegularTangentSPaceFactor, Jacobians) {\n  /// Plane keys.\n  Key plane_key_1(1);\n  Key plane_key_2(2);\n\n  /// Noise model for cosntraint between the two planes.\n  noiseModel::Diagonal::shared_ptr parallel_plane_noise =\n      noiseModel::Diagonal::Sigmas(Vector3(0.1, 0.1, 0.1));\n\n  /// Parallelism constraint between Plane 1 and Plane 2.\n  ParallelPlaneRegularTangentSpaceFactor factor(plane_key_1, plane_key_2,\n                                                parallel_plane_noise);\n\n  /// Planes.\n  OrientedPlane3 plane_1(0.3, 0.2, 1.9, 0.9);\n  OrientedPlane3 plane_2(0.1, 0.1, 0.9, 0.1);\n\n  // Use the factor to calculate the Jacobians\n  gtsam::Matrix H1Actual, H2Actual;\n  factor.evaluateError(plane_1, plane_2, H1Actual, H2Actual);\n\n  // Calculate numerical derivatives\n  Matrix H1Expected =\n      numericalDerivative21<Vector, OrientedPlane3, OrientedPlane3>(\n          boost::bind(&ParallelPlaneRegularTangentSpaceFactor::evaluateError,\n                      &factor, _1, _2, boost::none, boost::none),\n          plane_1, plane_2, der_tol);\n\n  Matrix H2Expected =\n      numericalDerivative22<Vector, OrientedPlane3, OrientedPlane3>(\n          boost::bind(&ParallelPlaneRegularTangentSpaceFactor::evaluateError,\n                      &factor, _1, _2, boost::none, boost::none),\n          plane_1, plane_2, der_tol);\n\n  // Verify the Jacobians are correct\n  ASSERT_TRUE(assert_equal(H1Expected, H1Actual, tol));\n  ASSERT_TRUE(assert_equal(H2Expected, H2Actual, tol));\n}\n\n/**\n * Test that optimization works.\n * A plane and a landmark with prior factors, and a second plane constrained\n * together with the first plane using the ParallelPlaneRegularTangentSpace\n * factor.\n *\n *              Prior                      +-------+    +-+\n *               +-+                       | Lmk 1 +----+ | Prior\n *               +-+        Parallelism    +---+---+    +-+\n *                |           factor           |\n *            +---+---+        +-+         +---+---+\n *            |Plane 1+--------+ +---------+Plane 2|\n *            +-------+        +-+         +-------+\n *\n */\nTEST(testParallelPlaneRegularTangentSpaceFactor, PlaneOptimization) {\n  NonlinearFactorGraph graph;\n\n  /// Keys\n  Key landmark_key = 1;\n  Key plane_key_1 = 2;\n  Key plane_key_2 = 3;\n\n  /// Shared noise for all landmarks.\n  noiseModel::Diagonal::shared_ptr prior_noise =\n      noiseModel::Diagonal::Sigmas(Vector3(0.1, 0.1, 0.1));\n\n  Point3 priorMeanLandmark1(0.0, 0.0, 0.0);\n  // TODO change for push_back or add.\n  graph.emplace_shared<PriorFactor<Point3> >(landmark_key, priorMeanLandmark1,\n                                             prior_noise);\n\n  OrientedPlane3 priorMeanPlane1(0.0, 0.0, 1.0, 1.0);\n  graph.emplace_shared<PriorFactor<OrientedPlane3> >(\n      plane_key_1, priorMeanPlane1, prior_noise);\n\n  /// Shared noise for all constraints between landmarks and planes.\n  noiseModel::Isotropic::shared_ptr regularity_noise =\n      noiseModel::Isotropic::Sigma(1, 0.5);\n\n  /// Plane 2 to landmark.\n  graph.emplace_shared<PointPlaneFactor>(landmark_key, plane_key_2,\n                                         regularity_noise);\n\n  /// Noise model for cosntraint between the two planes.\n  noiseModel::Diagonal::shared_ptr parallel_plane_noise =\n      noiseModel::Diagonal::Sigmas(Vector2(0.1, 0.1));\n\n  /// Parallelism constraint between Plane 1 and Plane 2.\n  graph.emplace_shared<ParallelPlaneRegularTangentSpaceFactor>(\n      plane_key_1, plane_key_2, parallel_plane_noise);\n\n  // graph.print(\"\\nFactor Graph:\\n\");\n\n  Values initial;\n  initial.insert(landmark_key, Point3(0.0, 0.2, 0.1));\n  initial.insert(plane_key_1, OrientedPlane3(0.1, 0.1, 0.9, 0.9));\n  initial.insert(plane_key_2, OrientedPlane3(0.1, 0.1, 0.8, 0.1));\n\n  // GaussianFactorGraph gfg = *graph.linearize(initial);\n  // gfg.print(\"\\nFactor Graph:\\n\");\n\n  GaussNewtonParams params;\n  // params.setVerbosity(\"LINEAR\");\n  params.setMaxIterations(20);\n  params.setRelativeErrorTol(-std::numeric_limits<double>::max());\n  // params.setErrorTol(-std::numeric_limits<double>::max());\n  params.setAbsoluteErrorTol(-std::numeric_limits<double>::max());\n\n  Values result = GaussNewtonOptimizer(graph, initial, params).optimize();\n  // Values result = LevenbergMarquardtOptimizer(graph, initial,\n  // params).optimize();\n\n  Values expected;\n  expected.insert(landmark_key, priorMeanLandmark1);\n  expected.insert(plane_key_1, priorMeanPlane1);\n  expected.insert(plane_key_2, OrientedPlane3(0.0, 0.0, 1.0, 0.0));\n\n  ASSERT_TRUE(assert_equal(expected, result, tol));\n}\n", "meta": {"hexsha": "a74ecc8976e6d6fe9eba06d40c884f91439ef48f", "size": 7693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testParallelPlaneRegularTangentSpaceFactor.cpp", "max_stars_repo_name": "RongzhiW/Kimera-VIO", "max_stars_repo_head_hexsha": "7eff66bfdf02c2d63c5d464959a6b83d213e1082", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-12T19:45:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T19:45:04.000Z", "max_issues_repo_path": "tests/testParallelPlaneRegularTangentSpaceFactor.cpp", "max_issues_repo_name": "RongzhiW/Kimera-VIO", "max_issues_repo_head_hexsha": "7eff66bfdf02c2d63c5d464959a6b83d213e1082", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/testParallelPlaneRegularTangentSpaceFactor.cpp", "max_forks_repo_name": "RongzhiW/Kimera-VIO", "max_forks_repo_head_hexsha": "7eff66bfdf02c2d63c5d464959a6b83d213e1082", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T06:00:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-12T06:00:55.000Z", "avg_line_length": 34.0398230088, "max_line_length": 80, "alphanum_fraction": 0.664500195, "num_tokens": 2085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5642628059324343}}
{"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": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\nusing namespace std;\nint main()\n{\n  // For a more realistic example set size to 1000 or larger\n  const int size = 8, N = size * size;\n\n  //typedef mtl::dense2D<double>  matrix_type;\n  typedef mtl::compressed2D<double>  matrix_type;\n  matrix_type                      A(N, N), dr(5,5);\n\n  laplacian_setup(A, size, size);\n\n  dr= 1,  1,  1,   0,  0,\n      1, -1, -2,   0,  0,\n      1, -2,  1,   0,  0,\n      0,  0,  0, -10,  0,\n      0,  0,  0,   0, 22;\n\n  itl::pc::diagonal<matrix_type>     P(A), Pb(dr);\n  mtl::dense_vector<double>          x(N, 1.0), b(N), xb(5, 1.0), bb(5);\n  mtl::dense_vector<complex<double> > xz(5,complex<double>(1.0, 0.0)), bz(5);\n\n  bb= dr * xb;\n  xb= 0;\n  \n  b= A * x;\n  x= 0;\n\n  itl::cyclic_iteration<double> iter(b, 500, 1.e-6, 0.0, 1);\n  qmr(A, x, b, P, P, iter);\n  std::cout<< \"x=\" << x << \"\\n\";\n\n  itl::cyclic_iteration<double> iterb(bb, 500, 1.e-6, 0.0, 1);\n  qmr(dr, xb, bb, Pb, Pb, iterb);\n  std::cout<< \"xb=\" << xb << \"\\n\";\n\n  return 0;\n}\n\n\n", "meta": {"hexsha": "52e523638e7ecbf371c6b3b5406eb32ef8c611e5", "size": 1491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/qmr_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/qmr_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/qmr_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": 26.625, "max_line_length": 94, "alphanum_fraction": 0.5848423877, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021788, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5642537514945887}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_CCMATH_LOGB_HPP\n#define BOOST_MATH_CCMATH_LOGB_HPP\n\n#include <cmath>\n#include <limits>\n#include <type_traits>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n#include <boost/math/ccmath/frexp.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/abs.hpp>\n\nnamespace boost::math::ccmath {\n\nnamespace detail {\n\n// The value of the exponent returned by std::logb is always 1 less than the exponent returned by \n// std::frexp because of the different normalization requirements: for the exponent e returned by std::logb, \n// |arg*r^-e| is between 1 and r (typically between 1 and 2), but for the exponent e returned by std::frexp, \n// |arg*2^-e| is between 0.5 and 1. \ntemplate <typename T>\ninline constexpr T logb_impl(T arg) noexcept\n{\n    int exp = 0;\n    boost::math::ccmath::frexp(arg, &exp);\n\n    return exp - 1;\n}\n\n} // Namespace detail\n\ntemplate <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>\ninline constexpr Real logb(Real arg) noexcept\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(arg))\n    {\n        return boost::math::ccmath::abs(arg) == Real(0) ? -std::numeric_limits<Real>::infinity() :\n               boost::math::ccmath::isinf(arg) ? std::numeric_limits<Real>::infinity() :\n               boost::math::ccmath::isnan(arg) ? std::numeric_limits<Real>::quiet_NaN() :\n               boost::math::ccmath::detail::logb_impl(arg);\n    }\n    else\n    {\n        using std::logb;\n        return logb(arg);\n    }\n}\n\ntemplate <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>\ninline constexpr double logb(Z arg) noexcept\n{\n    return boost::math::ccmath::logb(static_cast<double>(arg));\n}\n\ninline constexpr float logbf(float arg) noexcept\n{\n    return boost::math::ccmath::logb(arg);\n}\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline constexpr long double logbl(long double arg) noexcept\n{\n    return boost::math::ccmath::logb(arg);\n}\n#endif\n\n} // Namespaces\n\n#endif // BOOST_MATH_CCMATH_LOGB_HPP\n", "meta": {"hexsha": "1b0c165bccad7278b28e09ece9b2f54ef05f5d62", "size": 2260, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/logb.hpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "include/boost/math/ccmath/logb.hpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "include/boost/math/ccmath/logb.hpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 30.1333333333, "max_line_length": 109, "alphanum_fraction": 0.7039823009, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5642537382552149}}
{"text": "/* test_uniform_int_distribution.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/uniform_int_distribution.hpp>\r\n#include <limits>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::uniform_int_distribution<>\r\n#define BOOST_RANDOM_ARG1 a\r\n#define BOOST_RANDOM_ARG2 b\r\n#define BOOST_RANDOM_ARG1_DEFAULT 0\r\n#define BOOST_RANDOM_ARG2_DEFAULT 0x7fffffff\r\n#define BOOST_RANDOM_ARG1_VALUE 100\r\n#define BOOST_RANDOM_ARG2_VALUE 250\r\n\r\n#define BOOST_RANDOM_DIST0_MIN 0\r\n#define BOOST_RANDOM_DIST0_MAX 0x7fffffff\r\n#define BOOST_RANDOM_DIST1_MIN 100\r\n#define BOOST_RANDOM_DIST1_MAX 0x7fffffff\r\n#define BOOST_RANDOM_DIST2_MIN 100\r\n#define BOOST_RANDOM_DIST2_MAX 250\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS (0, 9)\r\n#define BOOST_RANDOM_TEST1_MIN 0\r\n#define BOOST_RANDOM_TEST1_MAX 9\r\n\r\n#define BOOST_RANDOM_TEST2_PARAMS (10, 19)\r\n#define BOOST_RANDOM_TEST2_MIN 10\r\n#define BOOST_RANDOM_TEST2_MAX 19\r\n\r\n#include \"test_distribution.ipp\"\r\n\r\n#define BOOST_RANDOM_UNIFORM_INT boost::random::uniform_int_distribution\r\n\r\n#include \"test_uniform_int.ipp\"\r\n", "meta": {"hexsha": "227a0b31050a5a8db32daa1984dacef8fd052fd6", "size": 1232, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_uniform_int_distribution.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/random/test/test_uniform_int_distribution.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/random/test/test_uniform_int_distribution.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 28.6511627907, "max_line_length": 76, "alphanum_fraction": 0.8035714286, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5642537266332518}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2005, 2006, 2007, 2008, 2009, 2017 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#include \"piecewiseyieldcurve.hpp\"\n#include \"utilities.hpp\"\n#include <ql/cashflows/iborcoupon.hpp>\n#include <ql/termstructures/globalbootstrap.hpp>\n#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>\n#include <ql/termstructures/yield/ratehelpers.hpp>\n#include <ql/termstructures/yield/bondhelpers.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/calendars/japan.hpp>\n#include <ql/time/calendars/weekendsonly.hpp>\n#include <ql/time/calendars/jointcalendar.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/time/daycounters/thirty360.hpp>\n#include <ql/time/imm.hpp>\n#include <ql/time/asx.hpp>\n#include <ql/indexes/ibor/euribor.hpp>\n#include <ql/indexes/ibor/usdlibor.hpp>\n#include <ql/indexes/ibor/jpylibor.hpp>\n#include <ql/indexes/bmaindex.hpp>\n#include <ql/indexes/indexmanager.hpp>\n#include <ql/instruments/forwardrateagreement.hpp>\n#include <ql/instruments/makevanillaswap.hpp>\n#include <ql/math/interpolations/linearinterpolation.hpp>\n#include <ql/math/interpolations/loginterpolation.hpp>\n#include <ql/math/interpolations/backwardflatinterpolation.hpp>\n#include <ql/math/interpolations/cubicinterpolation.hpp>\n#include <ql/math/interpolations/convexmonotoneinterpolation.hpp>\n#include <ql/math/comparison.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/utilities/dataformatters.hpp>\n#include <ql/pricingengines/bond/discountingbondengine.hpp>\n#include <ql/pricingengines/swap/discountingswapengine.hpp>\n#include <iomanip>\n#include <map>\n#include <string>\n#include <vector>\n#include <boost/assign/list_of.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\nusing boost::assign::list_of;\nusing boost::assign::map_list_of;\nusing std::map;\nusing std::vector;\nusing std::string;\n\nnamespace piecewise_yield_curve_test {\n\n    struct Datum {\n        Integer n;\n        TimeUnit units;\n        Rate rate;\n    };\n\n    struct BondDatum {\n        Integer n;\n        TimeUnit units;\n        Integer length;\n        Frequency frequency;\n        Rate coupon;\n        Real price;\n    };\n\n    Datum depositData[] = {\n        { 1, Weeks,  4.559 },\n        { 1, Months, 4.581 },\n        { 2, Months, 4.573 },\n        { 3, Months, 4.557 },\n        { 6, Months, 4.496 },\n        { 9, Months, 4.490 }\n    };\n\n    Datum fraData[] = {\n        { 1, Months, 4.581 },\n        { 2, Months, 4.573 },\n        { 3, Months, 4.557 },\n        { 6, Months, 4.496 },\n        { 9, Months, 4.490 }\n    };\n\n    Datum immFutData[] = {\n        { 1, Months, 4.581 },\n        { 2, Months, 4.573 },\n        { 3, Months, 4.557 }\n    };\n\n    Datum asxFutData[] = {\n        { 1, Months, 4.581 },\n        { 2, Months, 4.573 },\n        { 3, Months, 4.557 }\n    };\n\n    Datum swapData[] = {\n        {  1, Years, 4.54 },\n        {  2, Years, 4.63 },\n        {  3, Years, 4.75 },\n        {  4, Years, 4.86 },\n        {  5, Years, 4.99 },\n        {  6, Years, 5.11 },\n        {  7, Years, 5.23 },\n        {  8, Years, 5.33 },\n        {  9, Years, 5.41 },\n        { 10, Years, 5.47 },\n        { 12, Years, 5.60 },\n        { 15, Years, 5.75 },\n        { 20, Years, 5.89 },\n        { 25, Years, 5.95 },\n        { 30, Years, 5.96 }\n    };\n\n    BondDatum bondData[] = {\n        {  6, Months, 5, Semiannual, 4.75, 101.320 },\n        {  1, Years,  3, Semiannual, 2.75, 100.590 },\n        {  2, Years,  5, Semiannual, 5.00, 105.650 },\n        {  5, Years, 11, Semiannual, 5.50, 113.610 },\n        { 10, Years, 11, Semiannual, 3.75, 104.070 }\n    };\n\n    Datum bmaData[] = {\n        {  1, Years, 67.56 },\n        {  2, Years, 68.00 },\n        {  3, Years, 68.25 },\n        {  4, Years, 68.50 },\n        {  5, Years, 68.81 },\n        {  7, Years, 69.50 },\n        { 10, Years, 70.44 },\n        { 15, Years, 71.69 },\n        { 20, Years, 72.69 },\n        { 30, Years, 73.81 }\n    };\n\n    struct CommonVars {\n        // global variables\n        Calendar calendar;\n        Natural settlementDays;\n        Date today, settlement;\n        BusinessDayConvention fixedLegConvention;\n        Frequency fixedLegFrequency;\n        DayCounter fixedLegDayCounter;\n        Natural bondSettlementDays;\n        DayCounter bondDayCounter;\n        BusinessDayConvention bondConvention;\n        Real bondRedemption;\n        Frequency bmaFrequency;\n        BusinessDayConvention bmaConvention;\n        DayCounter bmaDayCounter;\n\n        Size deposits, fras, immFuts, asxFuts, swaps, bonds, bmas;\n        std::vector<ext::shared_ptr<SimpleQuote> > rates, fraRates,\n                                                     immFutPrices, asxFutPrices,\n                                                     prices, fractions;\n        std::vector<ext::shared_ptr<RateHelper> > instruments, fraHelpers,\n                                                    immFutHelpers, asxFutHelpers,\n                                                    bondHelpers, bmaHelpers;\n        std::vector<Schedule> schedules;\n        ext::shared_ptr<YieldTermStructure> termStructure;\n\n        // cleanup\n        SavedSettings backup;\n        IndexHistoryCleaner cleaner;\n\n        // setup\n        CommonVars() {\n            // data\n            calendar = TARGET();\n            settlementDays = 2;\n            today = calendar.adjust(Date::todaysDate());\n            Settings::instance().evaluationDate() = today;\n            settlement = calendar.advance(today,settlementDays,Days);\n            fixedLegConvention = Unadjusted;\n            fixedLegFrequency = Annual;\n            fixedLegDayCounter = Thirty360();\n            bondSettlementDays = 3;\n            bondDayCounter = ActualActual();\n            bondConvention = Following;\n            bondRedemption = 100.0;\n            bmaFrequency = Quarterly;\n            bmaConvention = Following;\n            bmaDayCounter = ActualActual();\n\n            deposits = LENGTH(depositData);\n            fras = LENGTH(fraData);\n            immFuts = LENGTH(immFutData);\n            asxFuts = LENGTH(asxFutData);\n            swaps = LENGTH(swapData);\n            bonds = LENGTH(bondData);\n            bmas = LENGTH(bmaData);\n\n            // market elements\n            rates =\n                std::vector<ext::shared_ptr<SimpleQuote> >(deposits+swaps);\n            fraRates = std::vector<ext::shared_ptr<SimpleQuote> >(fras);\n            immFutPrices = std::vector<ext::shared_ptr<SimpleQuote> >(immFuts);\n            asxFutPrices = std::vector<ext::shared_ptr<SimpleQuote> >(asxFuts);\n            prices = std::vector<ext::shared_ptr<SimpleQuote> >(bonds);\n            fractions = std::vector<ext::shared_ptr<SimpleQuote> >(bmas);\n            for (Size i=0; i<deposits; i++) {\n                rates[i] = ext::make_shared<SimpleQuote>(\n                                    depositData[i].rate/100);\n            }\n            for (Size i=0; i<swaps; i++) {\n                rates[i+deposits] = ext::make_shared<SimpleQuote>(\n                                       swapData[i].rate/100);\n            }\n            for (Size i=0; i<fras; i++) {\n                fraRates[i] = ext::make_shared<SimpleQuote>(\n                                        fraData[i].rate/100);\n            }\n            for (Size i = 0; i<bonds; i++) {\n                prices[i] = ext::make_shared<SimpleQuote>(\n                                          bondData[i].price);\n            }\n            for (Size i = 0; i<immFuts; i++) {\n                immFutPrices[i] = ext::make_shared<SimpleQuote>(\n                    100.0 - immFutData[i].rate);\n            }\n            for (Size i = 0; i<asxFuts; i++) {\n                asxFutPrices[i] = ext::make_shared<SimpleQuote>(\n                    100.0 - asxFutData[i].rate);\n            }\n            for (Size i = 0; i<bmas; i++) {\n                fractions[i] = ext::make_shared<SimpleQuote>(\n                                        bmaData[i].rate/100);\n            }\n\n            // rate helpers\n            instruments =\n                std::vector<ext::shared_ptr<RateHelper> >(deposits+swaps);\n            fraHelpers = std::vector<ext::shared_ptr<RateHelper> >(fras);\n            immFutHelpers = std::vector<ext::shared_ptr<RateHelper> >(immFuts);\n            asxFutHelpers = std::vector<ext::shared_ptr<RateHelper> >();\n            bondHelpers = std::vector<ext::shared_ptr<RateHelper> >(bonds);\n            schedules = std::vector<Schedule>(bonds);\n            bmaHelpers = std::vector<ext::shared_ptr<RateHelper> >(bmas);\n\n            ext::shared_ptr<IborIndex> euribor6m(new Euribor6M);\n            for (Size i=0; i<deposits; i++) {\n                Handle<Quote> r(rates[i]);\n                instruments[i] = ext::shared_ptr<RateHelper>(new\n                    DepositRateHelper(r,\n                                      ext::make_shared<Euribor>(\n                                          depositData[i].n*depositData[i].units)));\n            }\n            for (Size i=0; i<swaps; i++) {\n                Handle<Quote> r(rates[i+deposits]);\n                instruments[i+deposits] = ext::shared_ptr<RateHelper>(new\n                    SwapRateHelper(r, swapData[i].n*swapData[i].units,\n                                   calendar,\n                                   fixedLegFrequency, fixedLegConvention,\n                                   fixedLegDayCounter, euribor6m));\n            }\n\n\n#ifdef QL_USE_INDEXED_COUPON\n            bool useIndexedFra = false;\n#else\n            bool useIndexedFra = true;\n#endif\n\n            ext::shared_ptr<IborIndex> euribor3m(new Euribor3M());\n            for (Size i=0; i<fras; i++) {\n                Handle<Quote> r(fraRates[i]);\n                fraHelpers[i] = ext::shared_ptr<RateHelper>(new\n                    FraRateHelper(r, fraData[i].n, fraData[i].n + 3,\n                                  euribor3m->fixingDays(),\n                                  euribor3m->fixingCalendar(),\n                                  euribor3m->businessDayConvention(),\n                                  euribor3m->endOfMonth(),\n                                  euribor3m->dayCounter(),\n                                  Pillar::LastRelevantDate,\n                                  Date(),\n                                  useIndexedFra));\n            }\n            Date immDate = Date();\n            for (Size i = 0; i<immFuts; i++) {\n                Handle<Quote> r(immFutPrices[i]);\n                immDate = IMM::nextDate(immDate, false);\n                // if the fixing is before the evaluation date, we\n                // just jump forward by one future maturity\n                if (euribor3m->fixingDate(immDate) <\n                    Settings::instance().evaluationDate())\n                    immDate = IMM::nextDate(immDate, false);\n                immFutHelpers[i] = ext::shared_ptr<RateHelper>(new\n                    FuturesRateHelper(r, immDate, euribor3m, Handle<Quote>(),\n                                      Futures::IMM));\n            }\n            Date asxDate = Date();\n            for (Size i = 0; i<asxFuts; i++) {\n                Handle<Quote> r(asxFutPrices[i]);\n                asxDate = ASX::nextDate(asxDate, false);\n                // if the fixing is before the evaluation date, we\n                // just jump forward by one future maturity\n                if (euribor3m->fixingDate(asxDate) <\n                    Settings::instance().evaluationDate())\n                    asxDate = ASX::nextDate(asxDate, false);\n                if (euribor3m->fixingCalendar().isBusinessDay(asxDate))\n                    asxFutHelpers.push_back(ext::shared_ptr<RateHelper>(new\n                        FuturesRateHelper(r, asxDate, euribor3m,\n                                          Handle<Quote>(), Futures::ASX)));\n            }\n\n            for (Size i=0; i<bonds; i++) {\n                Handle<Quote> p(prices[i]);\n                Date maturity =\n                    calendar.advance(today, bondData[i].n, bondData[i].units);\n                Date issue =\n                    calendar.advance(maturity, -bondData[i].length, Years);\n                std::vector<Rate> coupons(1, bondData[i].coupon/100.0);\n                schedules[i] = Schedule(issue, maturity,\n                                        Period(bondData[i].frequency),\n                                        calendar,\n                                        bondConvention, bondConvention,\n                                        DateGeneration::Backward, false);\n                bondHelpers[i] = ext::shared_ptr<RateHelper>(new\n                    FixedRateBondHelper(p,\n                                        bondSettlementDays,\n                                        bondRedemption, schedules[i],\n                                        coupons, bondDayCounter,\n                                        bondConvention,\n                                        bondRedemption, issue));\n            }\n        }\n    };\n\n\n    template <class T, class I, template<class C> class B>\n    void testCurveConsistency(CommonVars& vars,\n                              const I& interpolator = I(),\n                              Real tolerance = 1.0e-9) {\n\n        vars.termStructure = ext::shared_ptr<YieldTermStructure>(new\n            PiecewiseYieldCurve<T,I,B>(vars.settlement, vars.instruments,\n                                       Actual360(),\n                                       interpolator));\n\n        RelinkableHandle<YieldTermStructure> curveHandle;\n        curveHandle.linkTo(vars.termStructure);\n\n        // check deposits\n        for (Size i=0; i<vars.deposits; i++) {\n            Euribor index(depositData[i].n*depositData[i].units,curveHandle);\n            Rate expectedRate  = depositData[i].rate/100,\n                 estimatedRate = index.fixing(vars.today);\n            if (std::fabs(expectedRate-estimatedRate) > tolerance) {\n                BOOST_ERROR(\n                    depositData[i].n << \" \"\n                    << (depositData[i].units == Weeks ? \"week(s)\" : \"month(s)\")\n                    << \" deposit:\"\n                    << std::setprecision(8)\n                    << \"\\n    estimated rate: \" << io::rate(estimatedRate)\n                    << \"\\n    expected rate:  \" << io::rate(expectedRate));\n            }\n        }\n\n        // check swaps\n        ext::shared_ptr<IborIndex> euribor6m(new Euribor6M(curveHandle));\n        for (Size i=0; i<vars.swaps; i++) {\n            Period tenor = swapData[i].n*swapData[i].units;\n\n            VanillaSwap swap = MakeVanillaSwap(tenor, euribor6m, 0.0)\n                .withEffectiveDate(vars.settlement)\n                .withFixedLegDayCount(vars.fixedLegDayCounter)\n                .withFixedLegTenor(Period(vars.fixedLegFrequency))\n                .withFixedLegConvention(vars.fixedLegConvention)\n                .withFixedLegTerminationDateConvention(vars.fixedLegConvention);\n\n            Rate expectedRate = swapData[i].rate/100,\n                 estimatedRate = swap.fairRate();\n            Spread error = std::fabs(expectedRate-estimatedRate);\n            if (error > tolerance) {\n                BOOST_ERROR(\n                    swapData[i].n << \" year(s) swap:\\n\"\n                    << std::setprecision(8)\n                    << \"\\n estimated rate: \" << io::rate(estimatedRate)\n                    << \"\\n expected rate:  \" << io::rate(expectedRate)\n                    << \"\\n error:          \" << io::rate(error)\n                    << \"\\n tolerance:      \" << io::rate(tolerance));\n            }\n        }\n\n        // check bonds\n        vars.termStructure = ext::shared_ptr<YieldTermStructure>(new\n            PiecewiseYieldCurve<T,I,B>(vars.settlement, vars.bondHelpers,\n                                       Actual360(),\n                                       interpolator));\n        curveHandle.linkTo(vars.termStructure);\n\n        for (Size i=0; i<vars.bonds; i++) {\n            Date maturity = vars.calendar.advance(vars.today,\n                                                  bondData[i].n,\n                                                  bondData[i].units);\n            Date issue = vars.calendar.advance(maturity,\n                                               -bondData[i].length,\n                                               Years);\n            std::vector<Rate> coupons(1, bondData[i].coupon/100.0);\n\n            FixedRateBond bond(vars.bondSettlementDays, 100.0,\n                               vars.schedules[i], coupons,\n                               vars.bondDayCounter, vars.bondConvention,\n                               vars.bondRedemption, issue);\n\n            ext::shared_ptr<PricingEngine> bondEngine(\n                                      new DiscountingBondEngine(curveHandle));\n            bond.setPricingEngine(bondEngine);\n\n            Real expectedPrice = bondData[i].price,\n                 estimatedPrice = bond.cleanPrice();\n            Real error = std::fabs(expectedPrice-estimatedPrice);\n            if (error > tolerance) {\n                BOOST_ERROR(io::ordinal(i+1) << \" bond failure:\" <<\n                            std::setprecision(8) <<\n                            \"\\n  estimated price: \" << estimatedPrice <<\n                            \"\\n  expected price:  \" << expectedPrice <<\n                            \"\\n  error:           \" << error);\n            }\n        }\n\n        // check FRA\n        vars.termStructure = ext::shared_ptr<YieldTermStructure>(new\n            PiecewiseYieldCurve<T,I>(vars.settlement, vars.fraHelpers,\n                                     Actual360(),\n                                     interpolator));\n        curveHandle.linkTo(vars.termStructure);\n\n#ifdef QL_USE_INDEXED_COUPON\n        bool useIndexedFra = false;\n#else\n        bool useIndexedFra = true;\n#endif\n\n        ext::shared_ptr<IborIndex> euribor3m(new Euribor3M(curveHandle));\n        for (Size i=0; i<vars.fras; i++) {\n            Date start =\n                vars.calendar.advance(vars.settlement,\n                                      fraData[i].n,\n                                      fraData[i].units,\n                                      euribor3m->businessDayConvention(),\n                                      euribor3m->endOfMonth());\n            BOOST_REQUIRE(fraData[i].units == Months);\n            Date end = vars.calendar.advance(vars.settlement, 3 + fraData[i].n, Months,\n                                             euribor3m->businessDayConvention(),\n                                             euribor3m->endOfMonth());\n\n            ForwardRateAgreement fra(start, end, Position::Long,\n                                     fraData[i].rate/100, 100.0,\n                                     euribor3m, curveHandle,\n                                     useIndexedFra);\n            Rate expectedRate = fraData[i].rate/100,\n                 estimatedRate = fra.forwardRate();\n            if (std::fabs(expectedRate-estimatedRate) > tolerance) {\n                BOOST_ERROR(io::ordinal(i+1) << \" FRA failure:\" <<\n                            std::setprecision(8) <<\n                            \"\\n  estimated rate: \" << io::rate(estimatedRate) <<\n                            \"\\n  expected rate:  \" << io::rate(expectedRate));\n            }\n        }\n\n        // check immFuts\n        vars.termStructure = ext::shared_ptr<YieldTermStructure>(new\n            PiecewiseYieldCurve<T, I>(vars.settlement, vars.immFutHelpers,\n            Actual360(),\n            interpolator));\n        curveHandle.linkTo(vars.termStructure);\n\n        Date immStart = Date();\n        for (Size i = 0; i<vars.immFuts; i++) {\n            immStart = IMM::nextDate(immStart, false);\n            // if the fixing is before the evaluation date, we\n            // just jump forward by one future maturity\n            if (euribor3m->fixingDate(immStart) <\n                Settings::instance().evaluationDate())\n                immStart = IMM::nextDate(immStart, false);\n            Date end = vars.calendar.advance(immStart, 3, Months,\n                euribor3m->businessDayConvention(),\n                euribor3m->endOfMonth());\n\n            ForwardRateAgreement immFut(immStart, end, Position::Long,\n                immFutData[i].rate / 100, 100.0,\n                euribor3m, curveHandle);\n            Rate expectedRate = immFutData[i].rate / 100,\n                estimatedRate = immFut.forwardRate();\n            if (std::fabs(expectedRate - estimatedRate) > tolerance) {\n                BOOST_ERROR(io::ordinal(i + 1) << \" IMM futures failure:\" <<\n                    std::setprecision(8) <<\n                    \"\\n  estimated rate: \" << io::rate(estimatedRate) <<\n                    \"\\n  expected rate:  \" << io::rate(expectedRate));\n            }\n        }\n\n        // check asxFuts\n        vars.termStructure = ext::shared_ptr<YieldTermStructure>(new\n            PiecewiseYieldCurve<T, I>(vars.settlement, vars.asxFutHelpers,\n            Actual360(),\n            interpolator));\n        curveHandle.linkTo(vars.termStructure);\n\n        Date asxStart = Date();\n        for (Size i = 0; i<vars.asxFuts; i++) {\n            asxStart = ASX::nextDate(asxStart, false);\n            // if the fixing is before the evaluation date, we\n            // just jump forward by one future maturity\n            if (euribor3m->fixingDate(asxStart) <\n                Settings::instance().evaluationDate())\n                asxStart = ASX::nextDate(asxStart, false);\n            if (euribor3m->fixingCalendar().isHoliday(asxStart))\n                continue;\n            Date end = vars.calendar.advance(asxStart, 3, Months,\n                euribor3m->businessDayConvention(),\n                euribor3m->endOfMonth());\n\n            ForwardRateAgreement asxFut(asxStart, end, Position::Long,\n                asxFutData[i].rate / 100, 100.0,\n                euribor3m, curveHandle);\n            Rate expectedRate = asxFutData[i].rate / 100,\n                estimatedRate = asxFut.forwardRate();\n            if (std::fabs(expectedRate - estimatedRate) > tolerance) {\n                BOOST_ERROR(io::ordinal(i + 1) << \" ASX futures failure:\" <<\n                    std::setprecision(8) <<\n                    \"\\n  estimated rate: \" << io::rate(estimatedRate) <<\n                    \"\\n  expected rate:  \" << io::rate(expectedRate));\n            }\n        }\n\n    // end checks\n    }\n\n    template <class T, class I, template<class C> class B>\n    void testBMACurveConsistency(CommonVars& vars,\n                                 const I& interpolator = I(),\n                                 Real tolerance = 1.0e-9) {\n\n        // re-adjust settlement\n        vars.calendar = JointCalendar(BMAIndex().fixingCalendar(),\n                                      USDLibor(3*Months).fixingCalendar(),\n                                      JoinHolidays);\n        vars.today = vars.calendar.adjust(Date::todaysDate());\n        Settings::instance().evaluationDate() = vars.today;\n        vars.settlement =\n            vars.calendar.advance(vars.today,vars.settlementDays,Days);\n\n\n        Handle<YieldTermStructure> riskFreeCurve(\n            ext::shared_ptr<YieldTermStructure>(\n                        new FlatForward(vars.settlement, 0.04, Actual360())));\n\n        ext::shared_ptr<BMAIndex> bmaIndex(new BMAIndex);\n        ext::shared_ptr<IborIndex> liborIndex(\n                                        new USDLibor(3*Months,riskFreeCurve));\n        for (Size i=0; i<vars.bmas; ++i) {\n            Handle<Quote> f(vars.fractions[i]);\n            vars.bmaHelpers[i] = ext::shared_ptr<RateHelper>(\n                      new BMASwapRateHelper(f, bmaData[i].n*bmaData[i].units,\n                                            vars.settlementDays,\n                                            vars.calendar,\n                                            Period(vars.bmaFrequency),\n                                            vars.bmaConvention,\n                                            vars.bmaDayCounter,\n                                            bmaIndex,\n                                            liborIndex));\n        }\n\n        Weekday w = vars.today.weekday();\n        Date lastWednesday =\n            (w >= 4) ? vars.today - (w - 4) : vars.today + (4 - w - 7);\n        Date lastFixing = bmaIndex->fixingCalendar().adjust(lastWednesday);\n        bmaIndex->addFixing(lastFixing, 0.03);\n\n        vars.termStructure = ext::shared_ptr<YieldTermStructure>(new\n            PiecewiseYieldCurve<T,I,B>(vars.today, vars.bmaHelpers,\n                                       Actual360(),\n                                       interpolator));\n\n        RelinkableHandle<YieldTermStructure> curveHandle;\n        curveHandle.linkTo(vars.termStructure);\n\n        // check BMA swaps\n        ext::shared_ptr<BMAIndex> bma(new BMAIndex(curveHandle));\n        ext::shared_ptr<IborIndex> libor3m(new USDLibor(3*Months,\n                                                          riskFreeCurve));\n        for (Size i=0; i<vars.bmas; i++) {\n            Period tenor = bmaData[i].n*bmaData[i].units;\n\n            Schedule bmaSchedule =\n                MakeSchedule().from(vars.settlement)\n                              .to(vars.settlement+tenor)\n                              .withFrequency(vars.bmaFrequency)\n                              .withCalendar(bma->fixingCalendar())\n                              .withConvention(vars.bmaConvention)\n                              .backwards();\n            Schedule liborSchedule =\n                MakeSchedule().from(vars.settlement)\n                              .to(vars.settlement+tenor)\n                              .withTenor(libor3m->tenor())\n                              .withCalendar(libor3m->fixingCalendar())\n                              .withConvention(libor3m->businessDayConvention())\n                              .endOfMonth(libor3m->endOfMonth())\n                              .backwards();\n\n\n            BMASwap swap(BMASwap::Payer, 100.0,\n                         liborSchedule, 0.75, 0.0,\n                         libor3m, libor3m->dayCounter(),\n                         bmaSchedule, bma, vars.bmaDayCounter);\n            swap.setPricingEngine(ext::shared_ptr<PricingEngine>(\n              new DiscountingSwapEngine(libor3m->forwardingTermStructure())));\n\n            Real expectedFraction = bmaData[i].rate/100,\n                 estimatedFraction = swap.fairLiborFraction();\n            Real error = std::fabs(expectedFraction-estimatedFraction);\n            if (error > tolerance) {\n                BOOST_ERROR(bmaData[i].n << \" year(s) BMA swap:\\n\"\n                            << std::setprecision(8)\n                            << \"\\n estimated libor fraction: \" << estimatedFraction\n                            << \"\\n expected libor fraction:  \" << expectedFraction\n                            << \"\\n error:          \" << error\n                            << \"\\n tolerance:      \" << tolerance);\n            }\n        }\n    }\n\n    // Used to check that the exception message contains the expected message string, expMsg.\n    struct ExpErrorPred {\n\n        explicit ExpErrorPred(const string& msg) : expMsg(msg) {}\n\n        bool operator()(const Error& ex) {\n            string errMsg(ex.what());\n            if (errMsg.find(expMsg) == string::npos) {\n                BOOST_TEST_MESSAGE(\"Error expected to contain: '\" << expMsg << \"'.\");\n                BOOST_TEST_MESSAGE(\"Actual error is: '\" << errMsg << \"'.\");\n                return false;\n            } else {\n                return true;\n            }\n        }\n\n        string expMsg;\n    };\n\n}\n\n\nvoid PiecewiseYieldCurveTest::testLogCubicDiscountConsistency() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing consistency of piecewise-log-cubic discount curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n\n    testCurveConsistency<Discount,LogCubic,IterativeBootstrap>(\n        vars,\n        LogCubic(CubicInterpolation::Spline, true,\n                 CubicInterpolation::SecondDerivative, 0.0,\n                 CubicInterpolation::SecondDerivative, 0.0));\n    testBMACurveConsistency<Discount,LogCubic,IterativeBootstrap>(\n        vars,\n        LogCubic(CubicInterpolation::Spline, true,\n                 CubicInterpolation::SecondDerivative, 0.0,\n                 CubicInterpolation::SecondDerivative, 0.0));\n}\n\nvoid PiecewiseYieldCurveTest::testLogLinearDiscountConsistency() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing consistency of piecewise-log-linear discount curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n\n    testCurveConsistency<Discount,LogLinear,IterativeBootstrap>(vars);\n    testBMACurveConsistency<Discount,LogLinear,IterativeBootstrap>(vars);\n}\n\nvoid PiecewiseYieldCurveTest::testLinearDiscountConsistency() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing consistency of piecewise-linear discount curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n\n    testCurveConsistency<Discount,Linear,IterativeBootstrap>(vars);\n    testBMACurveConsistency<Discount,Linear,IterativeBootstrap>(vars);\n}\n\nvoid PiecewiseYieldCurveTest::testLinearZeroConsistency() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing consistency of piecewise-linear zero-yield curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n\n    testCurveConsistency<ZeroYield,Linear,IterativeBootstrap>(vars);\n    testBMACurveConsistency<ZeroYield,Linear,IterativeBootstrap>(vars);\n}\n\nvoid PiecewiseYieldCurveTest::testSplineZeroConsistency() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing consistency of piecewise-cubic zero-yield curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n\n    testCurveConsistency<ZeroYield,Cubic,IterativeBootstrap>(\n                   vars,\n                   Cubic(CubicInterpolation::Spline, true,\n                         CubicInterpolation::SecondDerivative, 0.0,\n                         CubicInterpolation::SecondDerivative, 0.0));\n    testBMACurveConsistency<ZeroYield,Cubic,IterativeBootstrap>(\n                   vars,\n                   Cubic(CubicInterpolation::Spline, true,\n                         CubicInterpolation::SecondDerivative, 0.0,\n                         CubicInterpolation::SecondDerivative, 0.0));\n}\n\nvoid PiecewiseYieldCurveTest::testLinearForwardConsistency() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing consistency of piecewise-linear forward-rate curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n\n    testCurveConsistency<ForwardRate,Linear,IterativeBootstrap>(vars);\n    testBMACurveConsistency<ForwardRate,Linear,IterativeBootstrap>(vars);\n}\n\nvoid PiecewiseYieldCurveTest::testFlatForwardConsistency() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing consistency of piecewise-flat forward-rate curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n\n    testCurveConsistency<ForwardRate,BackwardFlat,IterativeBootstrap>(vars);\n    testBMACurveConsistency<ForwardRate,BackwardFlat,IterativeBootstrap>(vars);\n}\n\nvoid PiecewiseYieldCurveTest::testSplineForwardConsistency() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing consistency of piecewise-cubic forward-rate curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n\n    testCurveConsistency<ForwardRate,Cubic,IterativeBootstrap>(\n                   vars,\n                   Cubic(CubicInterpolation::Spline, true,\n                         CubicInterpolation::SecondDerivative, 0.0,\n                         CubicInterpolation::SecondDerivative, 0.0));\n    testBMACurveConsistency<ForwardRate,Cubic,IterativeBootstrap>(\n                   vars,\n                   Cubic(CubicInterpolation::Spline, true,\n                         CubicInterpolation::SecondDerivative, 0.0,\n                         CubicInterpolation::SecondDerivative, 0.0));\n}\n\nvoid PiecewiseYieldCurveTest::testConvexMonotoneForwardConsistency() {\n    BOOST_TEST_MESSAGE(\n        \"Testing consistency of convex monotone forward-rate curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n    testCurveConsistency<ForwardRate,ConvexMonotone,IterativeBootstrap>(vars);\n\n    testBMACurveConsistency<ForwardRate,ConvexMonotone,\n                            IterativeBootstrap>(vars);\n}\n\n\nvoid PiecewiseYieldCurveTest::testLocalBootstrapConsistency() {\n    BOOST_TEST_MESSAGE(\n        \"Testing consistency of local-bootstrap algorithm...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n    testCurveConsistency<ForwardRate,ConvexMonotone,LocalBootstrap>(\n                                              vars, ConvexMonotone(), 1.0e-6);\n    testBMACurveConsistency<ForwardRate,ConvexMonotone,LocalBootstrap>(\n                                              vars, ConvexMonotone(), 1.0e-7);\n}\n\n\nvoid PiecewiseYieldCurveTest::testObservability() {\n\n    BOOST_TEST_MESSAGE(\"Testing observability of piecewise yield curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n\n    vars.termStructure = ext::shared_ptr<YieldTermStructure>(\n       new PiecewiseYieldCurve<Discount,LogLinear>(vars.settlementDays,\n                                                   vars.calendar,\n                                                   vars.instruments,\n                                                   Actual360()));\n    Flag f;\n    f.registerWith(vars.termStructure);\n\n    for (Size i=0; i<vars.deposits+vars.swaps; i++) {\n        Time testTime =\n            Actual360().yearFraction(vars.settlement,\n                                     vars.instruments[i]->pillarDate());\n        DiscountFactor discount = vars.termStructure->discount(testTime);\n        f.lower();\n        vars.rates[i]->setValue(vars.rates[i]->value()*1.01);\n        if (!f.isUp())\n            BOOST_FAIL(\"Observer was not notified of underlying rate change\");\n        if (vars.termStructure->discount(testTime,true) == discount)\n            BOOST_FAIL(\"rate change did not trigger recalculation\");\n        vars.rates[i]->setValue(vars.rates[i]->value()/1.01);\n    }\n\n    vars.termStructure->maxDate();\n    f.lower();\n    Settings::instance().evaluationDate() =\n        vars.calendar.advance(vars.today,15,Days);\n    if (!f.isUp())\n        BOOST_FAIL(\"Observer was not notified of date change\");\n\n    f.lower();\n    Settings::instance().evaluationDate() = vars.today;\n    if (f.isUp())\n        BOOST_FAIL(\"Observer was notified of date change\"\n                   \" without an intervening recalculation\");\n}\n\n\nvoid PiecewiseYieldCurveTest::testLiborFixing() {\n\n    BOOST_TEST_MESSAGE(\n        \"Testing use of today's LIBOR fixings in swap curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n\n    std::vector<ext::shared_ptr<RateHelper> > swapHelpers(vars.swaps);\n    ext::shared_ptr<IborIndex> euribor6m(new Euribor6M);\n\n    for (Size i=0; i<vars.swaps; i++) {\n        Handle<Quote> r(vars.rates[i+vars.deposits]);\n        swapHelpers[i] = ext::shared_ptr<RateHelper>(new\n            SwapRateHelper(r, Period(swapData[i].n, swapData[i].units),\n                           vars.calendar,\n                           vars.fixedLegFrequency, vars.fixedLegConvention,\n                           vars.fixedLegDayCounter, euribor6m));\n    }\n\n    vars.termStructure = ext::shared_ptr<YieldTermStructure>(new\n        PiecewiseYieldCurve<Discount,LogLinear>(vars.settlement,\n                                                swapHelpers,\n                                                Actual360()));\n\n    Handle<YieldTermStructure> curveHandle =\n        Handle<YieldTermStructure>(vars.termStructure);\n\n    ext::shared_ptr<IborIndex> index(new Euribor6M(curveHandle));\n    for (Size i=0; i<vars.swaps; i++) {\n        Period tenor = swapData[i].n*swapData[i].units;\n\n        VanillaSwap swap = MakeVanillaSwap(tenor, index, 0.0)\n            .withEffectiveDate(vars.settlement)\n            .withFixedLegDayCount(vars.fixedLegDayCounter)\n            .withFixedLegTenor(Period(vars.fixedLegFrequency))\n            .withFixedLegConvention(vars.fixedLegConvention)\n            .withFixedLegTerminationDateConvention(vars.fixedLegConvention);\n\n        Rate expectedRate = swapData[i].rate/100,\n             estimatedRate = swap.fairRate();\n        Real tolerance = 1.0e-9;\n        if (std::fabs(expectedRate-estimatedRate) > tolerance) {\n            BOOST_ERROR(\"before LIBOR fixing:\\n\"\n                        << swapData[i].n << \" year(s) swap:\\n\"\n                        << std::setprecision(8)\n                        << \"    estimated rate: \"\n                        << io::rate(estimatedRate) << \"\\n\"\n                        << \"    expected rate:  \"\n                        << io::rate(expectedRate));\n        }\n    }\n\n    Flag f;\n    f.registerWith(vars.termStructure);\n    f.lower();\n\n    index->addFixing(vars.today, 0.0425);\n\n    if (!f.isUp())\n        BOOST_ERROR(\"Observer was not notified of rate fixing\");\n\n    for (Size i=0; i<vars.swaps; i++) {\n        Period tenor = swapData[i].n*swapData[i].units;\n\n        VanillaSwap swap = MakeVanillaSwap(tenor, index, 0.0)\n            .withEffectiveDate(vars.settlement)\n            .withFixedLegDayCount(vars.fixedLegDayCounter)\n            .withFixedLegTenor(Period(vars.fixedLegFrequency))\n            .withFixedLegConvention(vars.fixedLegConvention)\n            .withFixedLegTerminationDateConvention(vars.fixedLegConvention);\n\n        Rate expectedRate = swapData[i].rate/100,\n             estimatedRate = swap.fairRate();\n        Real tolerance = 1.0e-9;\n        if (std::fabs(expectedRate-estimatedRate) > tolerance) {\n            BOOST_ERROR(\"after LIBOR fixing:\\n\"\n                        << swapData[i].n << \" year(s) swap:\\n\"\n                        << std::setprecision(8)\n                        << \"    estimated rate: \"\n                        << io::rate(estimatedRate) << \"\\n\"\n                        << \"    expected rate:  \"\n                        << io::rate(expectedRate));\n        }\n    }\n}\n\nvoid PiecewiseYieldCurveTest::testJpyLibor() {\n    BOOST_TEST_MESSAGE(\n        \"Testing bootstrap over JPY LIBOR swaps...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n\n    vars.today = Date(4, October, 2007);\n    Settings::instance().evaluationDate() = vars.today;\n\n    vars.calendar = Japan();\n    vars.settlement =\n        vars.calendar.advance(vars.today,vars.settlementDays,Days);\n\n    // market elements\n    vars.rates = std::vector<ext::shared_ptr<SimpleQuote> >(vars.swaps);\n    for (Size i=0; i<vars.swaps; i++) {\n        vars.rates[i] = ext::make_shared<SimpleQuote>(\n                                       swapData[i].rate/100);\n    }\n\n    // rate helpers\n    vars.instruments = std::vector<ext::shared_ptr<RateHelper> >(vars.swaps);\n\n    ext::shared_ptr<IborIndex> index(new JPYLibor(6*Months));\n    for (Size i=0; i<vars.swaps; i++) {\n        Handle<Quote> r(vars.rates[i]);\n        vars.instruments[i] = ext::shared_ptr<RateHelper>(\n           new SwapRateHelper(r, swapData[i].n*swapData[i].units,\n                              vars.calendar,\n                              vars.fixedLegFrequency, vars.fixedLegConvention,\n                              vars.fixedLegDayCounter, index));\n    }\n\n    vars.termStructure = ext::shared_ptr<YieldTermStructure>(\n        new PiecewiseYieldCurve<Discount,LogLinear>(\n                                       vars.settlement, vars.instruments,\n                                       Actual360()));\n\n    RelinkableHandle<YieldTermStructure> curveHandle;\n    curveHandle.linkTo(vars.termStructure);\n\n    // check swaps\n    ext::shared_ptr<IborIndex> jpylibor6m(new JPYLibor(6*Months,curveHandle));\n    for (Size i=0; i<vars.swaps; i++) {\n        Period tenor = swapData[i].n*swapData[i].units;\n\n        VanillaSwap swap = MakeVanillaSwap(tenor, jpylibor6m, 0.0)\n            .withEffectiveDate(vars.settlement)\n            .withFixedLegDayCount(vars.fixedLegDayCounter)\n            .withFixedLegTenor(Period(vars.fixedLegFrequency))\n            .withFixedLegConvention(vars.fixedLegConvention)\n            .withFixedLegTerminationDateConvention(vars.fixedLegConvention)\n            .withFixedLegCalendar(vars.calendar)\n            .withFloatingLegCalendar(vars.calendar);\n\n        Rate expectedRate = swapData[i].rate/100,\n             estimatedRate = swap.fairRate();\n        Spread error = std::fabs(expectedRate-estimatedRate);\n        Real tolerance = 1.0e-9;\n\n        if (error > tolerance) {\n            BOOST_ERROR(swapData[i].n << \" year(s) swap:\\n\"\n                        << std::setprecision(8)\n                        << \"\\n estimated rate: \" << io::rate(estimatedRate)\n                        << \"\\n expected rate:  \" << io::rate(expectedRate)\n                        << \"\\n error:          \" << io::rate(error)\n                        << \"\\n tolerance:      \" << io::rate(tolerance));\n        }\n    }\n}\n\nnamespace piecewise_yield_curve_test {\n\n    template <class T, class I>\n    void testCurveCopy(CommonVars& vars,\n                       const I& interpolator = I()) {\n\n        PiecewiseYieldCurve<T,I> curve(vars.settlement, vars.instruments,\n                                       Actual360(),\n                                       interpolator);\n        // necessary to trigger bootstrap\n        curve.recalculate();\n\n        typedef typename T::template curve<I>::type base_curve;\n\n        base_curve copiedCurve = curve;\n\n        // the two curves should be the same.\n        Time t = 2.718;\n        Rate r1 = curve.zeroRate(t, Continuous);\n        Rate r2 = copiedCurve.zeroRate(t, Continuous);\n        if (!close(r1, r2)) {\n            BOOST_ERROR(\"failed to link original and copied curve\");\n        }\n\n        for (Size i=0; i<vars.rates.size(); ++i) {\n            vars.rates[i]->setValue(vars.rates[i]->value() + 0.001);\n        }\n\n        // now the original curve should have changed; the copied\n        // curve should not.\n        Rate r3 = curve.zeroRate(t, Continuous);\n        Rate r4 = copiedCurve.zeroRate(t, Continuous);\n        if (close(r1, r3)) {\n            BOOST_ERROR(\"failed to modify original curve\");\n        }\n        if (!close(r2,r4)) {\n            BOOST_ERROR(\n                    \"failed to break link between original and copied curve\");\n        }\n    }\n\n}\n\n\nvoid PiecewiseYieldCurveTest::testDiscountCopy() {\n    BOOST_TEST_MESSAGE(\"Testing copying of discount curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n    testCurveCopy<Discount,LogLinear>(vars);\n}\n\nvoid PiecewiseYieldCurveTest::testForwardCopy() {\n    BOOST_TEST_MESSAGE(\"Testing copying of forward-rate curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n    testCurveCopy<ForwardRate,BackwardFlat>(vars);\n}\n\nvoid PiecewiseYieldCurveTest::testZeroCopy() {\n    BOOST_TEST_MESSAGE(\"Testing copying of zero-rate curve...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n    testCurveCopy<ZeroYield,Linear>(vars);\n}\n\nvoid PiecewiseYieldCurveTest::testSwapRateHelperLastRelevantDate() {\n    BOOST_TEST_MESSAGE(\"Testing SwapRateHelper last relevant date...\");\n\n    SavedSettings backup;\n    Settings::instance().evaluationDate() = Date(22, Dec, 2016);\n    Date today = Settings::instance().evaluationDate();\n\n    Handle<YieldTermStructure> flat3m(\n        ext::make_shared<FlatForward>(today, Handle<Quote>(ext::make_shared<SimpleQuote>(0.02)), Actual365Fixed()));\n    ext::shared_ptr<IborIndex> usdLibor3m = ext::make_shared<USDLibor>(3 * Months, flat3m);\n\n    // note that the calendar should be US+UK here actually, but technically it should also work with\n    // the US calendar only\n    ext::shared_ptr<RateHelper> helper = ext::make_shared<SwapRateHelper>(\n        0.02, 50 * Years, UnitedStates(), Semiannual, ModifiedFollowing, Thirty360(), usdLibor3m);\n\n    PiecewiseYieldCurve<Discount, LogLinear> curve(today, std::vector<ext::shared_ptr<RateHelper> >(1, helper),\n                                                   Actual365Fixed());\n    BOOST_CHECK_NO_THROW(curve.discount(1.0));\n}\n\nvoid PiecewiseYieldCurveTest::testBadPreviousCurve() {\n    BOOST_TEST_MESSAGE(\"Testing bootstrap starting from bad guess...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    SavedSettings backup;\n\n    Datum data[] = {\n        {  1, Weeks,  -0.003488 },\n        {  2, Weeks,  -0.0033 },\n        {  6, Months, -0.00339 },\n        {  2, Years,  -0.00336 },\n        {  8, Years,   0.00302 },\n        { 50, Years,   0.01185 }\n    };\n\n    std::vector<ext::shared_ptr<RateHelper> > helpers;\n    ext::shared_ptr<Euribor> euribor1m(new Euribor1M);\n    for (Size i=0; i<LENGTH(data); ++i) {\n        helpers.push_back(\n           ext::make_shared<SwapRateHelper>(data[i].rate,\n                                              Period(data[i].n, data[i].units),\n                                              TARGET(), Monthly, Unadjusted,\n                                              Thirty360(), euribor1m));\n    }\n\n    Date today = Date(12, October, 2017);\n    Date test_date = Date(16, December, 2016);\n\n    Settings::instance().evaluationDate() = today;\n\n    ext::shared_ptr<YieldTermStructure> curve =\n        ext::make_shared<PiecewiseYieldCurve<ForwardRate, BackwardFlat> >(\n                                            test_date, helpers, Actual360());\n\n    // force bootstrap on today's date, so we have a previous curve...\n    curve->discount(1.0);\n\n    // ...then move to a date where the previous curve is a bad guess.\n    Settings::instance().evaluationDate() = test_date;\n\n    RelinkableHandle<YieldTermStructure> h;\n    h.linkTo(curve);\n\n    ext::shared_ptr<Euribor1M> index = ext::make_shared<Euribor1M>(h);\n    for (Size i=0; i<LENGTH(data); i++) {\n        Period tenor = data[i].n*data[i].units;\n\n        VanillaSwap swap = MakeVanillaSwap(tenor, index, 0.0)\n            .withFixedLegDayCount(Thirty360())\n            .withFixedLegTenor(Period(1, Months))\n            .withFixedLegConvention(Unadjusted);\n        swap.setPricingEngine(ext::make_shared<DiscountingSwapEngine>(h));\n\n        Rate expectedRate = data[i].rate,\n             estimatedRate = swap.fairRate();\n        Spread error = std::fabs(expectedRate-estimatedRate);\n        Real tolerance = 1.0e-9;\n        if (error > tolerance) {\n            BOOST_ERROR(tenor << \" swap:\\n\"\n                        << std::setprecision(8)\n                        << \"\\n estimated rate: \" << io::rate(estimatedRate)\n                        << \"\\n expected rate:  \" << io::rate(expectedRate)\n                        << \"\\n error:          \" << io::rate(error)\n                        << \"\\n tolerance:      \" << io::rate(tolerance));\n        }\n    }\n}\n\nvoid PiecewiseYieldCurveTest::testConstructionWithExplicitBootstrap() {\n\n    BOOST_TEST_MESSAGE(\"Testing that construction with an explicit bootstrap succeeds...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    CommonVars vars;\n\n    // With an explicit IterativeBootstrap object\n    typedef PiecewiseYieldCurve<ForwardRate, Linear, IterativeBootstrap> PwLinearForward;\n    ext::shared_ptr<YieldTermStructure> yts = \n        ext::make_shared<PwLinearForward>(\n            vars.settlement, vars.instruments, Actual360(), Linear(),\n            PwLinearForward::bootstrap_type());\n\n    // Check anything to show that the construction succeeded\n    BOOST_CHECK_NO_THROW(yts->discount(1.0, true));\n\n    // With an explicit LocalBootstrap object\n    typedef PiecewiseYieldCurve<ForwardRate, ConvexMonotone, LocalBootstrap> PwCmForward;\n    yts = ext::make_shared<PwCmForward>(\n        vars.settlement, vars.instruments, Actual360(), ConvexMonotone(), \n        PwCmForward::bootstrap_type());\n\n    BOOST_CHECK_NO_THROW(yts->discount(1.0, true));\n}\n\nvoid PiecewiseYieldCurveTest::testLargeRates() {\n    BOOST_TEST_MESSAGE(\"Testing bootstrap with large input rates...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    SavedSettings backup;\n\n    Datum data[] = {\n        {  1, Weeks,  2.418633 },\n        {  2, Weeks,  1.361540 },\n        {  3, Weeks,  1.195362 },\n        {  1, Months, 0.829009 }\n    };\n\n    std::vector<ext::shared_ptr<RateHelper> > helpers;\n    for (Size i=0; i<LENGTH(data); ++i) {\n        helpers.push_back(\n           ext::make_shared<DepositRateHelper>(data[i].rate,\n                                               Period(data[i].n, data[i].units),\n                                               0, WeekendsOnly(), Following,\n                                               false, Actual360()));\n    }\n\n    Date today = Date(12, October, 2017);\n\n    Settings::instance().evaluationDate() = today;\n\n    Real accuracy = Null<Real>(); // use the default\n    Real minValue = Null<Real>(); // use the default\n    Real maxValue = 3.0;          // override\n\n    typedef PiecewiseYieldCurve<ForwardRate, BackwardFlat> PiecewiseCurve;\n    ext::shared_ptr<YieldTermStructure> curve =\n        ext::make_shared<PiecewiseCurve>(\n                                  today, helpers, Actual360(), BackwardFlat(),\n                                  PiecewiseCurve::bootstrap_type(accuracy, minValue, maxValue));\n\n    // force bootstrap and check it worked\n    curve->discount(0.01);\n    BOOST_CHECK_NO_THROW(curve->discount(0.01));\n}\n\nnamespace piecewise_yield_curve_test {\n    // helper classes for testGlobalBootstrap() below:\n\n    // functor returning the additional error terms for the cost function\n    struct additionalErrors {\n        explicit additionalErrors(\n            const std::vector<ext::shared_ptr<BootstrapHelper<YieldTermStructure> > >&\n                additionalHelpers)\n        : additionalHelpers(additionalHelpers) {}\n        std::vector<ext::shared_ptr<BootstrapHelper<YieldTermStructure> > > additionalHelpers;\n        Array operator()() {\n            Array errors(5);\n            Real a = additionalHelpers[0]->impliedQuote();\n            Real b = additionalHelpers[6]->impliedQuote();\n            for (Size k = 0; k < 5; ++k) {\n                errors[k] = (5.0 - k) / 6.0 * a + (1.0 + k) / 6.0 * b -\n                            additionalHelpers[1 + k]->impliedQuote();\n            }\n            return errors;\n        }\n    };\n\n    // functor returning additional dates used in the bootstrap\n    struct additionalDates {\n        std::vector<Date> operator()() {\n            Date settl = TARGET().advance(Settings::instance().evaluationDate(), 2 * Days);\n            std::vector<Date> dates;\n            for (Size i = 0; i < 5; ++i)\n                dates.push_back(TARGET().advance(settl, (1 + i) * Months));\n            return dates;\n        }\n    };\n}\n\nvoid PiecewiseYieldCurveTest::testGlobalBootstrap() {\n\n    BOOST_TEST_MESSAGE(\"Testing global bootstrap...\");\n\n    using namespace piecewise_yield_curve_test;\n\n    SavedSettings backup;\n\n    Date today(26, Sep, 2019);\n    Settings::instance().evaluationDate() = today;\n\n    // market rates\n    Real refMktRate[] = {-0.373,   -0.388,   -0.402,   -0.418,   -0.431,  -0.441,   -0.45,\n                         -0.457,   -0.463,   -0.469,   -0.461,   -0.463,  -0.479,   -0.4511,\n                         -0.45418, -0.439,   -0.4124,  -0.37703, -0.3335, -0.28168, -0.22725,\n                         -0.1745,  -0.12425, -0.07746, 0.0385,   0.1435,  0.17525,  0.17275,\n                         0.1515,   0.1225,   0.095,    0.0644};\n\n    // expected outputs\n    Date refDate[] = {\n        Date(31, Mar, 2020), Date(30, Apr, 2020), Date(29, May, 2020), Date(30, Jun, 2020),\n        Date(31, Jul, 2020), Date(31, Aug, 2020), Date(30, Sep, 2020), Date(30, Oct, 2020),\n        Date(30, Nov, 2020), Date(31, Dec, 2020), Date(29, Jan, 2021), Date(26, Feb, 2021),\n        Date(31, Mar, 2021), Date(30, Sep, 2021), Date(30, Sep, 2022), Date(29, Sep, 2023),\n        Date(30, Sep, 2024), Date(30, Sep, 2025), Date(30, Sep, 2026), Date(30, Sep, 2027),\n        Date(29, Sep, 2028), Date(28, Sep, 2029), Date(30, Sep, 2030), Date(30, Sep, 2031),\n        Date(29, Sep, 2034), Date(30, Sep, 2039), Date(30, Sep, 2044), Date(30, Sep, 2049),\n        Date(30, Sep, 2054), Date(30, Sep, 2059), Date(30, Sep, 2064), Date(30, Sep, 2069)};\n\n    Real refZeroRate[] = {-0.00373354, -0.00381005, -0.00387689, -0.00394124, -0.00407706, -0.00413633, -0.00411935,\n                          -0.00416370, -0.00420557, -0.00424431, -0.00427824, -0.00430977, -0.00434401, -0.00445243,\n                          -0.00448506, -0.00433690, -0.00407401, -0.00372752, -0.00330050, -0.00279139, -0.00225477,\n                          -0.00173422, -0.00123688, -0.00077237,  0.00038554,  0.00144248,  0.00175995,  0.00172873,\n                           0.00150782,  0.00121145,  0.000933912, 0.000628946};\n\n    // build ql helpers\n    std::vector<ext::shared_ptr<RateHelper> > helpers;\n    ext::shared_ptr<IborIndex> index = ext::make_shared<Euribor>(6 * Months);\n\n    helpers.push_back(ext::make_shared<DepositRateHelper>(\n        refMktRate[0] / 100.0, 6 * Months, 2, TARGET(), ModifiedFollowing, true, Actual360()));\n\n    for (Size i = 0; i < 12; ++i) {\n        helpers.push_back(\n            ext::make_shared<FraRateHelper>(refMktRate[1 + i] / 100.0, (i + 1) * Months, index));\n    }\n\n    Size swapTenors[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 20, 25, 30, 35, 40, 45, 50};\n    for (Size i = 0; i < 19; ++i) {\n        helpers.push_back(ext::make_shared<SwapRateHelper>(refMktRate[13 + i] / 100.0,\n                                                           swapTenors[i] * Years, TARGET(), Annual,\n                                                           ModifiedFollowing, Thirty360(), index));\n    }\n\n    // global bootstrap constraints\n    std::vector<ext::shared_ptr<BootstrapHelper<YieldTermStructure> > > additionalHelpers;\n\n    // set up the additional rate helpers we need in the cost function\n    for (Size i = 0; i < 7; ++i) {\n        additionalHelpers.push_back(\n            ext::make_shared<FraRateHelper>(-0.004, (12 + i) * Months, index));\n    }\n\n    // build curve with additional dates and constraints using a global bootstrapper\n    typedef PiecewiseYieldCurve<SimpleZeroYield, Linear, GlobalBootstrap> Curve;\n    ext::shared_ptr<Curve> curve = ext::make_shared<Curve>(\n        2, TARGET(), helpers, Actual365Fixed(), std::vector<Handle<Quote> >(), std::vector<Date>(),\n        Linear(),\n        Curve::bootstrap_type(additionalHelpers, additionalDates(),\n                              additionalErrors(additionalHelpers), 1.0e-12));\n    curve->enableExtrapolation();\n\n    // check expected pillar dates\n    for (Size i = 0; i < LENGTH(refDate); ++i) {\n        BOOST_CHECK_EQUAL(refDate[i], helpers[i]->pillarDate());\n    }\n\n    // check expected zero rates\n    for (Size i = 0; i < LENGTH(refZeroRate); ++i) {\n        // 0.01 basis points tolerance\n        BOOST_CHECK_SMALL(std::fabs(refZeroRate[i] - curve->zeroRate(refDate[i], Actual360(), Continuous).rate()),\n                          1E-6);\n    }\n}\n\n/* This test attempts to build an ARS collateralised in USD curve as of 25 Sep 2019. Using the default \n   IterativeBootstrap with no retries, the yield curve building fails. Allowing retries, it expands the min and max \n   bounds and passes.\n*/\nvoid PiecewiseYieldCurveTest::testIterativeBootstrapRetries() {\n\n    BOOST_TEST_MESSAGE(\"Testing iterative bootstrap with retries...\");\n\n    SavedSettings backup;\n\n    Date asof(25, Sep, 2019);\n    Settings::instance().evaluationDate() = asof;\n    Actual365Fixed tsDayCounter;\n\n    // USD discount curve built out of FedFunds OIS swaps.\n    vector<Date> usdCurveDates = list_of\n        (Date(25, Sep, 2019))\n        (Date(26, Sep, 2019))\n        (Date(8, Oct, 2019))\n        (Date(16, Oct, 2019))\n        (Date(22, Oct, 2019))\n        (Date(30, Oct, 2019))\n        (Date(2, Dec, 2019))\n        (Date(31, Dec, 2019))\n        (Date(29, Jan, 2020))\n        (Date(2, Mar, 2020))\n        (Date(31, Mar, 2020))\n        (Date(29, Apr, 2020))\n        (Date(29, May, 2020))\n        (Date(1, Jul, 2020))\n        (Date(29, Jul, 2020))\n        (Date(31, Aug, 2020))\n        (Date(30, Sep, 2020));\n\n    vector<DiscountFactor> usdCurveDfs = list_of\n        (1.000000000)\n        (0.999940837)\n        (0.999309357)\n        (0.998894646)\n        (0.998574816)\n        (0.998162528)\n        (0.996552511)\n        (0.995197584)\n        (0.993915264)\n        (0.992530008)\n        (0.991329696)\n        (0.990179606)\n        (0.989005698)\n        (0.987751691)\n        (0.986703371)\n        (0.985495036)\n        (0.984413446);\n\n    Handle<YieldTermStructure> usdYts(ext::make_shared<InterpolatedDiscountCurve<LogLinear> >(\n        usdCurveDates, usdCurveDfs, tsDayCounter));\n\n    // USD/ARS forward points\n    Handle<Quote> arsSpot(ext::make_shared<SimpleQuote>(56.881));\n    map<Period, Real> arsFwdPoints = map_list_of\n        (1 * Months, 8.5157)\n        (2 * Months, 12.7180)\n        (3 * Months, 17.8310)\n        (6 * Months, 30.3680)\n        (9 * Months, 45.5520)\n        (1 * Years, 60.7370);\n\n    // Create the FX swap rate helpers for the ARS in USD curve.\n    vector<ext::shared_ptr<RateHelper> > instruments;\n    for (map<Period, Real>::const_iterator it = arsFwdPoints.begin(); it != arsFwdPoints.end(); ++it) {\n        Handle<Quote> arsFwd(ext::make_shared<SimpleQuote>(it->second));\n        instruments.push_back(ext::make_shared<FxSwapRateHelper>(arsFwd, arsSpot, it->first, 2,\n            UnitedStates(), Following, false, true, usdYts));\n    }\n\n    // Create the ARS in USD curve with the default IterativeBootstrap.\n    typedef PiecewiseYieldCurve<Discount, LogLinear, IterativeBootstrap> LLDFCurve;\n    ext::shared_ptr<YieldTermStructure> arsYts = ext::make_shared<LLDFCurve>(asof, instruments, tsDayCounter);\n\n    // USD/ARS spot date. The date on which we check the ARS discount curve.\n    Date spotDate(27, Sep, 2019);\n\n    // Check that the ARS in USD curve throws by requesting a discount factor.\n    using piecewise_yield_curve_test::ExpErrorPred;\n    BOOST_CHECK_EXCEPTION(arsYts->discount(spotDate), Error,\n        ExpErrorPred(\"1st iteration: failed at 1st alive instrument\"));\n\n    // Create the ARS in USD curve with an IterativeBootstrap allowing for 4 retries.\n    IterativeBootstrap<LLDFCurve> ib(Null<Real>(), Null<Real>(), Null<Real>(), 5);\n    arsYts = ext::make_shared<LLDFCurve>(asof, instruments, tsDayCounter, ib);\n    \n    // Check that the ARS in USD curve builds and populate the spot ARS discount factor.\n    DiscountFactor spotDfArs = 1.0;\n    BOOST_REQUIRE_NO_THROW(spotDfArs = arsYts->discount(spotDate));\n\n    // Additional dates and discount factors used in the final check i.e. that calculated 1Y FX forward equals input.\n    Date oneYearFwdDate(28, Sep, 2020);\n    DiscountFactor spotDfUsd = usdYts->discount(spotDate);\n    DiscountFactor oneYearDfUsd = usdYts->discount(oneYearFwdDate);\n\n    // Given that the ARS in USD curve builds, check that the 1Y USD/ARS forward rate is as expected.\n    DiscountFactor oneYearDfArs = arsYts->discount(oneYearFwdDate);\n    Real calcFwd = (spotDfArs * arsSpot->value() / oneYearDfArs) / (spotDfUsd / oneYearDfUsd);\n    Real expFwd = arsSpot->value() + arsFwdPoints.at(1 * Years);\n    BOOST_CHECK_SMALL(calcFwd - expFwd, 1e-10);\n}\n\ntest_suite* PiecewiseYieldCurveTest::suite() {\n\n    test_suite* suite = BOOST_TEST_SUITE(\"Piecewise yield curve tests\");\n\n    // unstable\n    //suite->add(QUANTLIB_TEST_CASE(\n    //             &PiecewiseYieldCurveTest::testLogCubicDiscountConsistency));\n    suite->add(QUANTLIB_TEST_CASE(\n                 &PiecewiseYieldCurveTest::testLogLinearDiscountConsistency));\n    suite->add(QUANTLIB_TEST_CASE(\n                 &PiecewiseYieldCurveTest::testLinearDiscountConsistency));\n\n    suite->add(QUANTLIB_TEST_CASE(\n                 &PiecewiseYieldCurveTest::testLinearZeroConsistency));\n    suite->add(QUANTLIB_TEST_CASE(\n                 &PiecewiseYieldCurveTest::testSplineZeroConsistency));\n\n    suite->add(QUANTLIB_TEST_CASE(\n                 &PiecewiseYieldCurveTest::testLinearForwardConsistency));\n    suite->add(QUANTLIB_TEST_CASE(\n                 &PiecewiseYieldCurveTest::testFlatForwardConsistency));\n    // unstable\n    //suite->add(QUANTLIB_TEST_CASE(\n    //             &PiecewiseYieldCurveTest::testSplineForwardConsistency));\n\n    suite->add(QUANTLIB_TEST_CASE(\n             &PiecewiseYieldCurveTest::testConvexMonotoneForwardConsistency));\n    suite->add(QUANTLIB_TEST_CASE(\n             &PiecewiseYieldCurveTest::testLocalBootstrapConsistency));\n\n    suite->add(QUANTLIB_TEST_CASE(&PiecewiseYieldCurveTest::testObservability));\n    suite->add(QUANTLIB_TEST_CASE(&PiecewiseYieldCurveTest::testLiborFixing));\n\n    suite->add(QUANTLIB_TEST_CASE(&PiecewiseYieldCurveTest::testJpyLibor));\n\n    suite->add(QUANTLIB_TEST_CASE(&PiecewiseYieldCurveTest::testDiscountCopy));\n    suite->add(QUANTLIB_TEST_CASE(&PiecewiseYieldCurveTest::testForwardCopy));\n    suite->add(QUANTLIB_TEST_CASE(&PiecewiseYieldCurveTest::testZeroCopy));\n\n    suite->add(QUANTLIB_TEST_CASE(\n               &PiecewiseYieldCurveTest::testSwapRateHelperLastRelevantDate));\n\n    if (IborCoupon::usingAtParCoupons()) {\n        // This regression test didn't work with indexed coupons anyway.\n        suite->add(QUANTLIB_TEST_CASE(\n               &PiecewiseYieldCurveTest::testBadPreviousCurve));\n    }\n\n    suite->add(QUANTLIB_TEST_CASE(&PiecewiseYieldCurveTest::testConstructionWithExplicitBootstrap));\n    suite->add(QUANTLIB_TEST_CASE(&PiecewiseYieldCurveTest::testLargeRates));\n\n#ifndef QL_USE_INDEXED_COUPON\n    suite->add(QUANTLIB_TEST_CASE(&PiecewiseYieldCurveTest::testGlobalBootstrap));\n#endif\n\n    suite->add(QUANTLIB_TEST_CASE(&PiecewiseYieldCurveTest::testIterativeBootstrapRetries));\n\n    return suite;\n}\n", "meta": {"hexsha": "f6b6f508438122f93a1e87f18b8da53d5a2ffd84", "size": 62237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/piecewiseyieldcurve.cpp", "max_stars_repo_name": "jacobleehowes/QuantLib", "max_stars_repo_head_hexsha": "18670c6a54a6ad8e0dfb85948a012742f5a0c791", "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": "test-suite/piecewiseyieldcurve.cpp", "max_issues_repo_name": "jacobleehowes/QuantLib", "max_issues_repo_head_hexsha": "18670c6a54a6ad8e0dfb85948a012742f5a0c791", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite/piecewiseyieldcurve.cpp", "max_forks_repo_name": "jacobleehowes/QuantLib", "max_forks_repo_head_hexsha": "18670c6a54a6ad8e0dfb85948a012742f5a0c791", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-10T00:45:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T00:45:58.000Z", "avg_line_length": 40.4136363636, "max_line_length": 117, "alphanum_fraction": 0.5728746566, "num_tokens": 15155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5642467106409886}}
{"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": "#include \"rsa_face_detection.hpp\"\n#include \"gpu_nms.hpp\"\n#include <Eigen/LU>\n#include <Eigen/Dense>\n#include <chrono>\n\nusing milli = std::chrono::milliseconds;\nstatic bool comp(const struct faceLandmark & a, const struct faceLandmark & b){\n\treturn a.score > b.score;\n}\n\nstatic Eigen::MatrixXd findNonreflectiveSimilarity(const cv::Point2f uv[], const cv::Point2f xy[])\n{\n    Eigen::MatrixXd X(10, 4);\n    Eigen::MatrixXd U(10, 1);\n    for (int i = 0; i < 5; i++) {\n        X(i, 0) = xy[i].x;\n        X(i, 1) = xy[i].y;\n        X(i, 2) = 1.0;\n        X(i, 3) = 0.0;\n        X(i + 5, 0) = xy[i].y;\n        X(i + 5, 1) = -xy[i].x;\n        X(i + 5, 2) = 0.0;\n        X(i + 5, 3) = 1.0;\n\n        U(i, 0) = uv[i].x;\n        U(i + 5, 0) = uv[i].y;\n    }\n\n    Eigen::MatrixXd r = X.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(U);\n    double sc = r(0, 0);\n    double ss = r(1, 0);\n    double tx = r(2, 0);\n    double ty = r(3, 0);\n\n    Eigen::MatrixXd Tinv(3, 3);\n    Tinv(0, 0) = sc;\n    Tinv(0, 1) = -ss;\n    Tinv(0, 2) = 0.0;\n    Tinv(1, 0) = ss;\n    Tinv(1, 1) = sc;\n    Tinv(1, 2) = 0.0;\n    Tinv(2, 0) = tx;\n    Tinv(2, 1) = ty;\n    Tinv(2, 2) = 1.0;\n    Eigen::MatrixXd T = Tinv.inverse();\n    T(0, 2) = 0.0;\n    T(1, 2) = 0.0;\n    T(2, 2) = 1.0;\n    return T;\n}\n\nstatic cv::Mat getSimilarityTransform(const cv::Point2f uv[], const cv::Point2f xy[])\n{\n\tEigen::MatrixXd trans1 = findNonreflectiveSimilarity(uv, xy);\n\tcv::Point2f xyNew[5];\n\n\tfor (int i = 0; i < 5; ++i) {\n\t\txyNew[i].x = -xy[i].x;\n\t\txyNew[i].y = xy[i].y;\n\t}\n\n\tEigen::MatrixXd trans2r = findNonreflectiveSimilarity(uv, xyNew);\n\n\tEigen::MatrixXd TreflectY(3, 3);\n\tTreflectY(0, 0) = -1.0;\n\tTreflectY(0, 1) = 0.0;\n\tTreflectY(0, 2) = 0.0;\n\tTreflectY(1, 0) = 0.0;\n\tTreflectY(1, 1) = 1.0;\n\tTreflectY(1, 2) = 0.0;\n\tTreflectY(2, 0) = 0.0;\n\tTreflectY(2, 1) = 0.0;\n\tTreflectY(2, 2) = 1.0;\n\n\tEigen::MatrixXd trans2 = trans2r * TreflectY;\n\tEigen::MatrixXd trans1Inv = trans1.inverse();\n\tEigen::MatrixXd trans2Inv = trans2.inverse();\n\tfor (int i = 0; i < trans1Inv.rows() - 1; ++i) {\n\t\ttrans1Inv(i, trans1.cols() - 1) = 0;\n\t\ttrans2Inv(i, trans1.cols() - 1) = 0;\n\t}\n\ttrans1(trans1Inv.rows() - 1, trans1.cols() - 1) = 1;\n\ttrans2(trans2Inv.rows() - 1, trans1.cols() - 1) = 1;\n\n\tEigen::MatrixXd matrixUv(5, 3),matrixXy(5, 3);\n\tfor (int i = 0; i < 5; ++i) {\n\t\tmatrixUv(i, 0) = uv[i].x;\n\t\tmatrixUv(i, 1) = uv[i].y;\n\t\tmatrixUv(i, 2) = 1;\n\t\tmatrixXy(i, 0) = xy[i].x;\n\t\tmatrixXy(i, 1) = xy[i].y;\n\t\tmatrixXy(i, 2) = 1;\n\t}\n\n\tEigen::MatrixXd trans1_block = trans1.block<3, 2>(0, 0);\n\tEigen::MatrixXd trans2_block = trans2.block<3, 2>(0, 0);\n\n\tdouble norm1 = (matrixUv * trans1_block - matrixXy.block<5, 2>(0, 0)).norm();\n\tdouble norm2 = (matrixUv * trans2_block - matrixXy.block<5, 2>(0, 0)).norm();\n\n\tcv::Mat M(2, 3, CV_64F);\n\tdouble* m = M.ptr<double>();\n\n\tif(norm1 <= norm2){\n\t\tm[0] = trans1Inv(0, 0);\n\t\tm[1] = trans1Inv(1, 0);\n\t\tm[2] = trans1Inv(2, 0);\n\t\tm[3] = trans1Inv(0, 1);\n\t\tm[4] = trans1Inv(1, 1);\n\t\tm[5] = trans1Inv(2, 1);\n\t}\n\telse{\n\t\tm[0] = trans2Inv(0, 0);\n\t\tm[1] = trans2Inv(1, 0);\n\t\tm[2] = trans2Inv(2, 0);\n\t\tm[3] = trans2Inv(0, 1);\n\t\tm[4] = trans2Inv(1, 1);\n\t\tm[5] = trans2Inv(2, 1);\n\t}\n\treturn M;\n}\n\nstatic void getTripPoints(std::vector<cv::Point2f> &dstRect, cv::Point2f srcKeyPoint[])\n{\n    cv::Point2f dstKeyPoint[5];\n    dstKeyPoint[0] = cv::Point2f(0.2, 0.2);\n    dstKeyPoint[1] = cv::Point2f(0.8, 0.2);\n    dstKeyPoint[2] = cv::Point2f(0.5, 0.5);\n    dstKeyPoint[3] = cv::Point2f(0.3, 0.75);\n    dstKeyPoint[4] = cv::Point2f(0.7, 0.75);\n\n    cv::Mat warpMat = getSimilarityTransform(srcKeyPoint, dstKeyPoint);\n    std::vector<cv::Point2f> srcRect;\n    srcRect.push_back(cv::Point2f(0.5, 0.5));\n    srcRect.push_back(cv::Point2f(0, 0));\n    srcRect.push_back(cv::Point2f(1.0, 0));\n    for (int h = 0; h < 3; h++) {\n        dstRect[h].x = srcRect[h].x * warpMat.ptr<double>(0)[0] + \\\n                        srcRect[h].y *warpMat.ptr<double>(0)[1] + \\\n                        warpMat.ptr<double>(0)[2];\n        dstRect[h].y = srcRect[h].x * warpMat.ptr<double>(1)[0] + \\\n                        srcRect[h].y *warpMat.ptr<double>(1)[1] + \\\n                        warpMat.ptr<double>(1)[2];\n    }\n\n}\n\nRsaFaceDetector::RsaFaceDetector(unsigned int gpuId, \\\n        const std::string & sfnNet, const std::string & sfnWeight, \\\n        const std::string & rsaNet, const std::string & rsaWeight, \\\n        const std::string & lrnNet, const std::string & lrnWeight)\n        :gpuId_(gpuId),\n        sfnNetDef_(sfnNet), sfnNetWeight_(sfnWeight),\n        rsaNetDef_(rsaNet), rsaNetWeight_(rsaWeight),\n        lrnNetDef_(lrnNet), lrnNetWeight_(lrnWeight)\n{\n    caffe::Caffe::set_mode(caffe::Caffe::GPU);\n    caffe::Caffe::SetDevice(gpuId_);\n\n    sfnNet_.reset(new caffe::Net<float>(sfnNet, caffe::TEST));\n    sfnNet_->CopyTrainedLayersFrom(sfnWeight);\n\n    rsaNet_.reset(new caffe::Net<float>(rsaNet, caffe::TEST));\n    rsaNet_->CopyTrainedLayersFrom(rsaWeight);\n\n    lrnNet_.reset(new caffe::Net<float>(lrnNet, caffe::TEST));\n    lrnNet_->CopyTrainedLayersFrom(lrnWeight);\n\n    inputLayer_ = sfnNet_->input_blobs()[0];            //sfn\u4eba\u8138\u50cf\u7d20\u5927\u5c0f\u9884\u6d4b\u7f51\u7edc\u8f93\u5165\u63a5\u53e3\n    rsaInputLayer_ = rsaNet_->input_blobs()[0];         //rsa\u7f51\u7edc \n    lrnInputLayer_ = lrnNet_->input_blobs()[0];         //lrn\u7f51\u7edc\n\n    anchorBoxLen_.push_back(ANCHOR_BOX[2] - ANCHOR_BOX[0]);\n    anchorBoxLen_.push_back(ANCHOR_BOX[3] - ANCHOR_BOX[1]);\n\n    threshScore_ = THRESH_SCORE;\n    stride_ = STRIDE;\n    anchorCenter_ = ANCHOR_CENTER;\n\n    for (int i = 5; i >= 1 ; i--)\n        scale_.push_back(i);\n}\n\nvoid RsaFaceDetector::sfnProcess_(const cv::Mat &image)\n{\n    int width = image.cols;\n    int height = image.rows;\n    int channels = image.channels();\n\n    if (width > height) {       // \u4ee5\u6700\u957f\u8fb9\u4e3a\u57fa\u51c6\uff0c\u7b49\u6bd4\u4f8b\u7f29\u653e\u56fe\u50cf\n        resizeFactor_ = static_cast<double>(width) / static_cast<double>(MAX_IMG);\n        height = static_cast<int>(MAX_IMG / static_cast<float>(width) * height);\n        width = MAX_IMG;\n    } else {\n        resizeFactor_ = static_cast<double>(height) / static_cast<double>(MAX_IMG);\n        width = static_cast<int>(MAX_IMG / static_cast<float>(height) * width);\n        height = MAX_IMG;\n    }\n\n    cv::Size inputGeometry(width, height);\n\n    inputLayer_->Reshape(1, channels, height, width);       //\u4e3a\u56fe\u7247\u8f93\u5165\u521b\u5efablob\uff0c\u5206\u914d\u5185\u5b58\n    sfnNet_->Reshape();                                     //\u524d\u5411\u4f20\u64ad\u4e4b\u524d\uff0creshape\u7f51\u7edc\n    float *inputData = inputLayer_->mutable_cpu_data();     //\u8bfb\u5199\u8bbf\u95eecpu data\n\n    inputChannels_.clear();\n    for (int i = 0; i < inputLayer_->channels(); i++) {\n        cv::Mat channel(height, width, CV_32FC1, (void*)inputData); //\u5c06RGB\u6bcf\u4e2a\u901a\u9053\u7684\u56fe\u50cf\u6570\u636e\u548cblob\u6570\u636e\u5728\u5185\u5b58\u4e2d\u4f4d\u7f6e\u76f8\u5bf9\u5e94\n        inputChannels_.push_back(channel);\n        inputData += width * height;\n    }\n\n    cv::Mat imgResized;\n    if (image.size() != inputGeometry)\n        cv::resize(image, imgResized, inputGeometry);\n    else\n        imgResized = image;\n\n    cv::Mat imgFloat;\n    imgResized.convertTo(imgFloat, CV_32FC3);\n    cv::Mat meanMat(inputGeometry, CV_32FC3, cv::Scalar(127.0, 127.0, 127.0));  //\u4e2d\u7070\u8272\u5747\u503c\n    cv::Mat imgNormalized;\n    cv::subtract(imgFloat, meanMat, imgNormalized);                 //\u56fe\u50cf\u6570\u636e\u51cf\u53bb\u5747\u503c\n    cv::split(imgNormalized, inputChannels_);                       //\u5c06\u591a\u901a\u9053\u7684\u5355\u4e2a\u56fe\u50cf\u5206\u79bb\u6210\u5355\u4e2a\u901a\u9053\u7684\u591a\u4e2a\u56fe\u50cf\uff0c\u5e76\u5206\u522b\u4f20\u5165caffe\u4e2d\n\n    CHECK (reinterpret_cast<float*> (inputChannels_.at(0).data) == \\\n             sfnNet_->input_blobs()[0]->cpu_data()) \\\n            << \"Input channels aren't wrapping the input layer of the network.\";\n\n    sfnNet_->Forward();\n    sfnNetOutput_ = sfnNet_->output_blobs()[0];\n}\n\n/* \n* \u5c06sfn\u7f51\u7edc\u5f97\u5230\u7684featureMap\u591a\u6b21\u9001\u8fdbrsa\u7f51\u7edc\u8fdb\u884c\u7f29\u653e\uff0c\u7136\u540e\u5f97\u5230\u4e0d\u540csize\u7684feature\n */\nvoid RsaFaceDetector::rsaProcess_()\n{\n    std::shared_ptr<caffe::Blob<float>> transFeatmapOri(new caffe::Blob<float>);\n    transFeatmapOri->CopyFrom(*sfnNetOutput_, false, true);         //\u4ece\u4e0a\u4e00\u4e2asfn\u7f51\u7edc\u62f7\u8d1d\u51fa\u8f93\u51fa\n    transFeatMaps_.push_back(transFeatmapOri);\n\n    int diffCnt;\n    std::shared_ptr<caffe::Blob<float>> transFeatmap(new caffe::Blob<float>);\n    std::shared_ptr<caffe::Blob<float>> inFeatmap(new caffe::Blob<float>);\n\n    for (int i = 1; i < scale_.size(); i++) {                       //\u5bf9featureMap\u505a5\u6b21\u5faa\u73af\n        int diffCnt = scale_[i - 1] - scale_[i];\n        inFeatmap->CopyFrom(*(transFeatMaps_[i - 1]), false, true);\n        for (int j = 0; j < diffCnt; j++) {                         //\u53ea\u8fdb\u884c\u4e00\u6b21\u524d\u5411\u4f20\u9012\n            rsaInputLayer_->CopyFrom(*inFeatmap, false, true);\n            rsaNet_->Reshape();\n            rsaNet_->Forward();\n            inFeatmap->CopyFrom(*rsaNet_->output_blobs()[0], false, true);\n        }\n        transFeatMaps_.push_back(std::shared_ptr<caffe::Blob<float>>(new caffe::Blob<float>));\n        //\u5c06\u6bcf\u6b21rsa\u7f51\u7edc\u7f29\u653e\u7684featureMap\u8fdb\u884c\u4fdd\u5b58\n        //\u5e76\u4e14\u6bcf\u4e00\u6b21featureMap\u8fdb\u884crsa\u5f97\u5230\u7684\u7ed3\u679c\u90fd\u662f\u4e0b\u4e00\u6b21rsa\u7684\u8f93\u5165\n        transFeatMaps_[transFeatMaps_.size() - 1]->CopyFrom(*rsaNet_->output_blobs()[0], false, true);  \n    }\n}\n\nvoid RsaFaceDetector::lrnProcess_(facesLandmarkPerImg & faceResult)\n{\n    std::vector<std::vector<cv::Point2f>> ptsAll;\n    std::vector<std::vector<double>> rectsAll;\n    std::vector<float> validScoreAll;\n    boost::shared_ptr<caffe::Blob<float> > blobRpnCls;      //\u6ce8\u610f\u8fd9\u4e2a\u4e0d\u662fstd::shared_ptr\n    boost::shared_ptr<caffe::Blob<float> > blobRpnReg;\n\n    for (int i = 0; i < transFeatMaps_.size(); i++) {\n        lrnInputLayer_->CopyFrom(*transFeatMaps_[i], false, true);\n        lrnNet_->Reshape();\n        lrnNet_->Forward();\n        blobRpnCls = lrnNet_->blob_by_name(\"rpn_cls\");\n        blobRpnReg = lrnNet_->blob_by_name(\"rpn_reg\");\n\n        int fmwidth = blobRpnCls->shape(3);\n        int fmheight = blobRpnCls->shape(2);\n\n        std::vector<float> validScore;\n        validScore.clear();\n        std::vector<std::vector<int>> validIndex;\n        validIndex.clear();\n        for (int x = 0; x < fmwidth; x++) {\n            for (int y = 0; y < fmheight; y++) {\n                if (blobRpnCls->data_at(0, 0, y, x) > threshScore_) {\n                    std::vector<int> index(2);\n                    index[0] = x;\n                    index[1] = y;\n                    validIndex.push_back(index);\n                    validScore.push_back(blobRpnCls->data_at(0, 0, y, x));\n                    validScoreAll.push_back(blobRpnCls->data_at(0, 0, y, x));\n                }\n            }\n        }\n\n        /* 5\u4e2a\u5173\u952e\u70b9\u7684\u83b7\u53d6\u548c\u5904\u7406 */\n        std::vector<std::vector<cv::Point2f>> ptsOut(validIndex.size(), std::vector<cv::Point2f>(5, cv::Point2f(0, 0)));\n        std::vector<std::vector<double>> rects(validIndex.size(), std::vector<double>(4, 0.0));\n        for (int j = 0; j < validIndex.size(); j++) {\n            std::vector<float> anchorCenterNow(2);\n            anchorCenterNow[0] = validIndex[j][0] * stride_ + anchorCenter_;        //??????\n            anchorCenterNow[1] = validIndex[j][1] * stride_ + anchorCenter_;        //??????\n            for (int h = 0; h < 5; h++) {\n                float anchorPointNowX = anchorCenterNow[0] + *(ANCHOR_PTS + h*2) * anchorBoxLen_[0];\n                float anchorPointNowY = anchorCenterNow[1] + *(ANCHOR_PTS + h*2 + 1) * anchorBoxLen_[0];\n                float ptsDeltaX = blobRpnReg->data_at(0, 2*h, validIndex[j][1], validIndex[j][0]) * anchorBoxLen_[0];\n                float ptsDeltaY = blobRpnReg->data_at(0, 2*h + 1, validIndex[j][1], validIndex[j][0]) * anchorBoxLen_[0];\n                ptsOut[j][h].x = ptsDeltaX + anchorPointNowX;\n                ptsOut[j][h].y = ptsDeltaY + anchorPointNowY;\n            }\n\n            std::vector<cv::Point2f> dstRect(3, cv::Point2f(0, 0));\n            cv::Point2f srcFivePoint[5];\n            for (int h = 0; h < 5; h++) \n                srcFivePoint[h] = ptsOut[j][h];\n            getTripPoints(dstRect, srcFivePoint);\n            double scaleDouble = pow(2, scale_[i] - 5);\n            double rectWidth = sqrt(pow((dstRect[1].x - dstRect[2].x), 2) + \\\n                                    pow((dstRect[1].y -dstRect[2].y), 2));\n            rects[j][0] = round((dstRect[0].x - rectWidth/2) / scaleDouble * resizeFactor_);\n            rects[j][1] = round((dstRect[0].y - rectWidth/2) / scaleDouble * resizeFactor_);\n            rects[j][2] = round((dstRect[0].x + rectWidth/2) / scaleDouble * resizeFactor_);\n            rects[j][3] = round((dstRect[0].y + rectWidth/2) / scaleDouble * resizeFactor_);\n\n            rectsAll.push_back(rects[j]);\n\n            for (int h = 0; h < 5; h++) {\n                ptsOut[j][h].x = round(ptsOut[j][h].x / scaleDouble * resizeFactor_);\n                ptsOut[j][h].y = round(ptsOut[j][h].y / scaleDouble * resizeFactor_);\n            }\n            ptsAll.push_back(ptsOut[j]);\n        }\n    }\n\n    transFeatMaps_.clear();\n    if (!ptsAll.empty()) {\n        float *boxes = new float[ptsAll.size() * 5];\n        int *keep = new int[ptsAll.size() * 5];\n        facesLandmarkPerImg faces;\n\n        for (int i = 0; i < ptsAll.size(); i++) {\n            struct faceLandmark faceTmp;\n            faceTmp.bbox = rectsAll[i];\n            faceTmp.keyPoints = ptsAll[i];\n            faceTmp.score = validScoreAll[i];\n            faces.push_back(faceTmp);\n        }\n        std::sort(faces.begin(), faces.end(), comp);    //\u6392\u5e8f\n        for (int i = 0; i < faces.size(); i++) {\n            boxes[i*5 + 0] = faces[i].bbox[0];\n            boxes[i*5 + 1] = faces[i].bbox[1];\n            boxes[i*5 + 2] = faces[i].bbox[2];\n            boxes[i*5 + 3] = faces[i].bbox[3];\n            boxes[i*5 + 4] = faces[i].score;\n        }\n        int numOut;\n        _nms(keep, &numOut, boxes, faces.size(), 5, NMS_THRESH, gpuId_);\n        for (int i = 0; i < numOut; i++)\n            faceResult.push_back(faces[*(keep + i)]);\n        delete [] boxes;\n        delete [] keep;\n    }\n}\n\nfacesLandmarkPerImg RsaFaceDetector::detect_(cv::Mat image)\n{\n\tauto start_sfn = std::chrono::high_resolution_clock::now();\n    sfnProcess_(image);\n\tauto end_sfn = std::chrono::high_resolution_clock::now();\n\tauto start_rsa = std::chrono::high_resolution_clock::now();\n    rsaProcess_();\n\tauto end_rsa = std::chrono::high_resolution_clock::now();\n    facesLandmarkPerImg faces;\n\tauto start_lrn = std::chrono::high_resolution_clock::now();\n    lrnProcess_(faces);\n\tauto end_lrn = std::chrono::high_resolution_clock::now();\n\t// std::cout << \"sfn took \" << std::chrono::duration_cast<milli>(end_sfn - start_sfn).count() << \" ms\\n\";\n\t// std::cout << \"rsa took \" << std::chrono::duration_cast<milli>(end_rsa - start_rsa).count() << \" ms\\n\";\n\t// std::cout << \"lrn took \" << std::chrono::duration_cast<milli>(end_lrn - start_lrn).count() << \" ms\\n\";\n    return faces;\n}", "meta": {"hexsha": "ffc3f122e5ee917b8a0f178904c307cfb2e0e92f", "size": 14380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rsa_face_detection.cpp", "max_stars_repo_name": "ZhouKai90/RSA_face_detection", "max_stars_repo_head_hexsha": "9ea05884006f740c09f97271435413c0bc45cbb3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-12T05:04:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-12T05:04:53.000Z", "max_issues_repo_path": "src/rsa_face_detection.cpp", "max_issues_repo_name": "ZhouKai90/RSA_face_detection", "max_issues_repo_head_hexsha": "9ea05884006f740c09f97271435413c0bc45cbb3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rsa_face_detection.cpp", "max_forks_repo_name": "ZhouKai90/RSA_face_detection", "max_forks_repo_head_hexsha": "9ea05884006f740c09f97271435413c0bc45cbb3", "max_forks_repo_licenses": ["Apache-2.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.4479166667, "max_line_length": 121, "alphanum_fraction": 0.578581363, "num_tokens": 4855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.564246689161956}}
{"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 <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"funnels/utils.hh\"\n\n#include \"funnels/distances.hh\"\n#include \"funnels/dynamics.hh\"\n#include \"funnels/funnels.hh\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace funnels;\nusing namespace lyapunov;\n\nvoid test_dist(){\n  \n  Matrix3d M;\n  M(0,0) = 1.;\n  M(1,1) = 2.;\n  M(2,2) = 3.;\n  \n  VectorXd v(3);\n  v(0)=11.;\n  v(1)=12.;\n  v(2)=13.;\n  \n  partial_so2_dist_t my_dist;\n  std::cout << my_dist.cp_Mv(M, v) << std::endl;\n  std::cout << my_dist.cp_vM(v, M) << std::endl;\n  std::cout << my_dist.cp_vv(v, v) << std::endl;\n  std::cout << my_dist.cp_MM(M, M) << std::endl;\n}\n\nvoid test_dyn(){\n  \n  kinematic_2d_sys_t my_sys;\n  VectorXd u(2);\n  VectorXd t(10);\n  MatrixXd x(4,10);\n  \n  t.setLinSpaced(10, 0., 10.);\n  u(0)=1.;\n  u(1)=1.33;\n  x(0,0) = -5.55;\n  x(1,0) = 6.55;\n  \n  \n  my_sys.compute(x,u,t);\n  \n  std::cout << x << std::endl;\n  std::cout << u << std::endl;\n  std::cout << t << std::endl;\n  \n}\n\nvoid test_funnel1(){\n  \n  std::cout << \"funnel 1\" << std::endl;\n  \n  clock_ta_t &ctrl_clk = utils_ext::clock_map.create_and_get(\"c_t\");\n  clock_ta_t &lcl_clk = utils_ext::clock_map.create_and_get(\"c_h\");\n\n  kinematic_2d_sys_t my_dyn;\n  partial_so2_dist_t my_dist;\n\n  MatrixXd P(my_dyn._dimx, my_dyn._dimx);\n  for (size_t i=0; i<my_dyn._dimx; i++){\n    P(i,i) = (double) i+1.;\n  }\n\n  fixed_ellipsoidal_lyap_t my_lyap(P, 0.5, my_dist);\n  \n  process_t &my_proc = utils_ext::process_map.create_and_get(\"proc_0\");\n  \n  // Init\n  Vector4d x0;\n  Vector2d u0;\n  x0(0) = 0.;\n  x0(1) = 2.;\n  u0(0) = 1.1;\n  u0(1) = 0.66;\n  const double t0=0., t1=10.;\n  \n  funnel_t<fixed_ellipsoidal_lyap_t<partial_so2_dist_t>, kinematic_2d_sys_t>\n      my_fun(100, \"fun_0\", my_proc, my_dyn, P, 0.5, my_dist);\n  \n  my_fun.compute(x0, t0, t1, u0);\n  \n  std::cout << my_fun.x() << std::endl;\n  std::cout << my_fun.u() << std::endl;\n  std::cout << my_fun.t() << std::endl;\n  \n}\n\nvoid test_funnel_sys(){\n  \n  std::cout << \"funnel sys\" << std::endl;\n  \n  using fun_t = funnel_t<fixed_ellipsoidal_lyap_t<partial_so2_dist_t>,\n      kinematic_2d_sys_t>;\n  \n  using fun_ptr_t = shared_ptr<fun_t>;\n  \n  clock_ta_t &ctrl_clk = utils_ext::clock_map[\"c_t\"];\n  clock_ta_t &lcl_clk = utils_ext::clock_map[\"c_h\"];\n  \n  kinematic_2d_sys_t my_dyn;\n  partial_so2_dist_t my_dist;\n  \n  MatrixXd P(my_dyn._dimx, my_dyn._dimx);\n  for (size_t i=0; i<my_dyn._dimx; i++){\n    P(i,i) = (double) 1.;\n  }\n  \n  fixed_ellipsoidal_lyap_t my_lyap(P, 0.5, my_dist);\n  \n  process_t &my_proc = utils_ext::process_map[\"proc_0\"];\n  \n  // Init\n  Vector4d x0, x1;\n  Vector2d u0, u1;\n  x0(0) = -1.; x1(0) =  0.;\n  x0(1) =  0.; x1(1) = -1.;\n  u0(0) = 1.; u0(0) = 1.1;\n  u0(1) = 0.66; u0(1) = 0.66;\n  const double t0=0., t1=10.;\n  \n  fun_ptr_t my_fun0_0 = make_shared<fun_t>(100, \"fun_0_0\", my_proc, my_dyn, P,\n      0.5,\n      my_dist);\n  \n  fun_ptr_t my_fun1_0 = make_shared<fun_t>(100, \"fun_1_0\", my_proc, my_dyn,\n      2.*P,\n      0.5, my_dist);\n  \n  fun_ptr_t my_fun1_1 = make_shared<fun_t>(100, \"fun_1_1\", my_proc, my_dyn,\n      4.*P, 0.5, my_dist);\n  \n  my_fun0_0->compute(x0, t0, t1, u0);\n  my_fun1_0->compute(x1, t0, t1, u1);\n  \n  fun_t::set_parent(my_fun1_0, my_fun1_1);\n  \n  std::cout << my_fun0_0.use_count() << \" ; \" << my_fun1_0.use_count()\n      << \" ; \" << my_fun1_1.use_count() << std::endl;\n  \n  \n  \n}\n\n\n\n\nint main() {\n  \n  test_dist();\n  test_dyn();\n  test_funnel1();\n  test_funnel_sys();\n  \n  return 0;\n}", "meta": {"hexsha": "91d12247eee1c04d90d3ec0836acf20e368689d2", "size": 3434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "schlepil/funnels_cpp", "max_stars_repo_head_hexsha": "fa1f9084a168abfbdf594c4eca6b0f26d33b9258", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "schlepil/funnels_cpp", "max_issues_repo_head_hexsha": "fa1f9084a168abfbdf594c4eca6b0f26d33b9258", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "schlepil/funnels_cpp", "max_forks_repo_head_hexsha": "fa1f9084a168abfbdf594c4eca6b0f26d33b9258", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9390243902, "max_line_length": 78, "alphanum_fraction": 0.6109493302, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5642168275683155}}
{"text": "// Copyright Oleg Maximenko 2014.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n// See http://github.com/svgpp/svgpp for library home page.\n\n#pragma once\n\n#include <svgpp/definitions.hpp>\n#include <svgpp/utility/gil/common.hpp>\n#include <boost/gil/channel_algorithm.hpp>\n#include <boost/gil/color_base_algorithm.hpp>\n\nnamespace svgpp \n{ \n\nnamespace gil_detail \n{\n\nnamespace gil = boost::gil;\n\ntemplate<class BlendModeTag, class ChannelValue>\nstruct blend_channel_fn;\n\ntemplate<class ChannelValue>\nstruct blend_alpha_fn;\n\n// TODO: default implementation for non-8 bit channels\n// TODO: clamp_channels is not needed for premultiplied values\n\n// For signed channels we call unsigned analog, converting forward and back\ntemplate<class BlendModeTag>\nstruct blend_channel_fn<BlendModeTag, boost::int8_t>\n{\n  boost::int8_t operator()(boost::int8_t channel_a, boost::int8_t channel_b, boost::int8_t alpha_a, boost::int8_t alpha_b) const\n  {\n    typedef gil::detail::channel_convert_to_unsigned<boost::int8_t> to_unsigned;\n    typedef gil::detail::channel_convert_from_unsigned<boost::int8_t> from_unsigned;\n    blend_channel_fn<BlendModeTag, boost::uint8_t> converter_unsigned;\n    return from_unsigned()(converter_unsigned(\n      to_unsigned()(channel_a), to_unsigned()(channel_b), to_unsigned()(alpha_a), to_unsigned()(alpha_b)));\n  }\n};\n\n// normal\tcr = (1 - alpha_a) * channel_b + channel_a\ntemplate<>\nstruct blend_channel_fn<tag::value::normal, boost::uint8_t>\n{\n  boost::uint8_t operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8(((255 - alpha_a) * channel_b) / 255 + channel_a);\n  }\n};\n\n// multiply\tcr = (1-alpha_a)*channel_b + (1-alpha_b)*channel_a + channel_a*channel_b\ntemplate<>\nstruct blend_channel_fn<tag::value::multiply, boost::uint8_t>\n{\n  boost::uint8_t operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8(((255 - alpha_a) * channel_b + (255 - alpha_b) * channel_a + channel_a * channel_b) / 255);\n  }\n};\n\n// screen\tcr = channel_b + channel_a - channel_a * channel_b\ntemplate<>\nstruct blend_channel_fn<tag::value::screen, boost::uint8_t>\n{\n  boost::uint8_t operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8(channel_b + channel_a - channel_a * channel_b / 255);\n  }\n};\n\n// darken\tcr = Min ((1 - alpha_a) * channel_b + channel_a, (1 - alpha_b) * channel_a + channel_b)\ntemplate<>\nstruct blend_channel_fn<tag::value::darken, boost::uint8_t>\n{\n  boost::uint8_t operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8(std::min((255 - alpha_a) * channel_b / 255 + channel_a, (255 - alpha_b) * channel_a / 255 + channel_b));\n  }\n};\n\n// lighten\tcr = Max ((1 - alpha_a) * channel_b + channel_a, (1 - alpha_b) * channel_a + channel_b)\ntemplate<>\nstruct blend_channel_fn<tag::value::lighten, boost::uint8_t>\n{\n  boost::uint8_t operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8(std::max((255 - alpha_a) * channel_b / 255 + channel_a, (255 - alpha_b) * channel_a / 255 + channel_b));\n  }\n};\n\n// qr = 1 - (1-alpha_a)*(1-alpha_b)\ntemplate<>\nstruct blend_alpha_fn<boost::uint8_t>\n{\n  boost::uint8_t operator()(int alpha_a, int alpha_b) const\n  {\n    return clamp_channel_bits8(255 - (255 - alpha_a) * (255 - alpha_b) / 255);\n  }\n};\n\n} // namespace gil_detail \n\nnamespace gil_utility \n{\n  \ntemplate<class BlendModeTag>\nstruct blend_pixel\n{\n  template<class Color>\n  Color operator()(const Color & pixa, const Color & pixb) const \n  {\n    namespace gil = boost::gil;\n\n    typename gil::color_element_type<Color, gil::alpha_t>::type \n      alpha_a = gil::get_color(pixa, gil::alpha_t()),\n      alpha_b = gil::get_color(pixb, gil::alpha_t());\n\n    Color result;\n\n    gil::get_color(result, gil::red_t()) \n      = gil_detail::blend_channel_fn<BlendModeTag, typename gil::color_element_type<Color, gil::red_t>::type>()(\n        gil::get_color(pixa, gil::red_t()), gil::get_color(pixb, gil::red_t()),\n        alpha_a, alpha_b);\n\n    gil::get_color(result, gil::green_t()) \n      = gil_detail::blend_channel_fn<BlendModeTag, typename gil::color_element_type<Color, gil::green_t>::type>()(\n        gil::get_color(pixa, gil::green_t()), gil::get_color(pixb, gil::green_t()),\n        alpha_a, alpha_b);\n\n    gil::get_color(result, gil::blue_t()) \n      = gil_detail::blend_channel_fn<BlendModeTag, typename gil::color_element_type<Color, gil::blue_t>::type>()(\n        gil::get_color(pixa, gil::blue_t()), gil::get_color(pixb, gil::blue_t()),\n        alpha_a, alpha_b);\n\n    gil::get_color(result, gil::alpha_t()) = \n      gil_detail::blend_alpha_fn<typename gil::color_element_type<Color, gil::alpha_t>::type>()(alpha_a, alpha_b);\n\n    return result;\n  }\n};\n\n}}\n", "meta": {"hexsha": "c8ac18a11d5b305b40c7204ea9b59115284ff7ac", "size": 4938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/svgpp/utility/gil/blend.hpp", "max_stars_repo_name": "RichardCory/svgpp", "max_stars_repo_head_hexsha": "801e0142c61c88cf2898da157fb96dc04af1b8b0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 428.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:25:47.000Z", "max_issues_repo_path": "include/svgpp/utility/gil/blend.hpp", "max_issues_repo_name": "andrew2015/svgpp", "max_issues_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T14:32:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T16:55:11.000Z", "max_forks_repo_path": "include/svgpp/utility/gil/blend.hpp", "max_forks_repo_name": "andrew2015/svgpp", "max_forks_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2015-05-19T04:56:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:42:50.000Z", "avg_line_length": 33.3648648649, "max_line_length": 135, "alphanum_fraction": 0.7095990279, "num_tokens": 1393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5642039742195474}}
{"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": "#include \"Lsh.hpp\"\n#include \"ExpressionMatrixSubset.hpp\"\n#include \"SimilarPairs.hpp\"\n#include \"timestamp.hpp\"\nusing namespace ChanZuckerberg;\nusing namespace ExpressionMatrix2;\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <chrono>\n#include \"fstream.hpp\"\n\n\n\nLsh::Lsh(\n    const string& name,             // Name prefix for memory mapped files.\n    const ExpressionMatrixSubset& expressionMatrixSubset,\n    size_t lshCount,                // Number of LSH hyperplanes\n    uint32_t seed                   // Seed to generate LSH hyperplanes.\n    )\n{\n    // Store the Info object.\n    info.createNew(name + \"-Info\");\n    info->lshCount = lshCount;\n    info->cellCount = expressionMatrixSubset.cellCount();\n\n    // Generate the LSH vectors.\n    cout << timestamp << \"Generating LSH vectors.\" << endl;\n    generateLshVectors(expressionMatrixSubset.geneCount(), lshCount, seed);\n\n    // Compute cell signatures.\n    cout << timestamp << \"Computing cell LSH signatures.\" << endl;\n    computeCellLshSignatures(name, expressionMatrixSubset);\n\n    // Compute the similarity table.\n    // This is a look up table indexed by the number of mismatching bits.\n    // Each entry contgains the similarity corresponding to that number\n    // of mismatching bits.\n    computeSimilarityTable();\n}\n\n\n\n// Access an existing Lsh object.\nLsh::Lsh(\n    const string& name              // Name prefix for memory mapped files.\n    )\n{\n    // Access the memory mapped data.\n    info.accessExistingReadOnly(name + \"-Info\");\n    signatures.accessExistingReadOnly(name + \"-Signatures\");\n\n    // Compute the number of 64 bit words in each cell signature.\n    signatureWordCount = (lshCount()-1)/64 + 1;\n\n    // Compute the similarity table.\n    // This is a look up table indexed by the number of mismatching bits.\n    // Each entry contgains the similarity corresponding to that number\n    // of mismatching bits.\n    computeSimilarityTable();\n}\n\n\n// Generate the LSH vectors.\nvoid Lsh::generateLshVectors(\n    size_t geneCount,\n    size_t lshCount,                // Number of LSH hyperplanes\n    uint32_t seed                   // Seed to generate LSH hyperplanes.\n)\n{\n    // Prepare to generate normally vector distributed components.\n    using RandomSource = boost::mt19937;\n    using NormalDistribution = boost::normal_distribution<>;\n    RandomSource randomSource(seed);\n    NormalDistribution normalDistribution;\n    boost::variate_generator<RandomSource, NormalDistribution> normalGenerator(randomSource, normalDistribution);\n\n    // Allocate space for the LSH vectors.\n    lshVectors.resize(geneCount, vector<double>(lshCount, 0.));\n\n    // Sum of the squares of the components of each of the LSH vectors.\n    vector<double> normalizationFactor(lshCount, 0.);\n\n\n\n    // Loop over genes.\n    for(size_t geneId = 0; geneId<geneCount; geneId++) {\n\n        // For this gene, generate the components of all the LSH vectors.\n        for(size_t lshVectorId = 0; lshVectorId<lshCount; lshVectorId++) {\n\n            const double x = normalGenerator();\n            lshVectors[geneId][lshVectorId] = x;\n\n            // Update the sum of squares for this LSH vector.\n            normalizationFactor[lshVectorId] += x*x;\n        }\n    }\n\n    // Normalize each of the LSH vectors.\n    for(auto& f: normalizationFactor) {\n        f = 1. / sqrt(f);\n    }\n    for(size_t geneId = 0; geneId<geneCount; geneId++) {\n        for(size_t lshVectorId = 0; lshVectorId<lshCount; lshVectorId++) {\n            lshVectors[geneId][lshVectorId] *= normalizationFactor[lshVectorId];\n        }\n    }\n\n}\n\n\n\n// Compute the LSH signatures of all cells in the cell set we are using.\nvoid Lsh::computeCellLshSignatures(\n    const string& name,             // Name prefix for memory mapped files.\n    const ExpressionMatrixSubset& expressionMatrixSubset)\n{\n    // Get the number of LSH vectors.\n    CZI_ASSERT(!lshVectors.empty());\n    const size_t lshCount = info->lshCount;\n\n    // Compute the number of 64 bit words in each cell signature.\n    signatureWordCount = (lshCount-1)/64 + 1;\n\n    // Get the number of genes and cells in the gene set and cell set we are using.\n    const auto geneCount = expressionMatrixSubset.geneCount();\n    const auto cellCount = expressionMatrixSubset.cellCount();\n    CZI_ASSERT(lshVectors.size() == geneCount);\n\n    // Compute the sum of the components of each lsh vector.\n    // It is needed below to compute the contribution of the\n    // expression counts that are zero.\n    vector<double> lshVectorsSums(lshCount, 0.);\n    for(GeneId localGeneId=0; localGeneId!=geneCount; localGeneId++) {\n        const auto& v = lshVectors[localGeneId]; // Components of all LSH vectors for this gene.\n        CZI_ASSERT(v.size() == lshCount);\n        for(size_t i=0; i<lshCount; i++) {\n            lshVectorsSums[i] += v[i];\n        }\n    }\n\n    // Initialize the cell signatures.\n    cout << timestamp << \"Initializing cell LSH signatures.\" << endl;\n    signatures.createNew(name + \"-Signatures\", cellCount*signatureWordCount);\n\n    // Vector to contain, for a single cell, the scalar products of the shifted\n    // expression vector for the cell with all of the LSH vectors.\n    vector<double> scalarProducts(lshCount);\n\n\n\n    // Loop over all the cells in the cell set we are using.\n    // The CellId is local to the cell set we are using.\n    const CellId messageFrequency = CellId(1.e7 / double(lshCount));\n    cout << timestamp << \"Computation of cell LSH signatures begins.\" << endl;\n    const auto t0 = std::chrono::steady_clock::now();\n    for(CellId localCellId=0; localCellId<cellCount; localCellId++) {\n        if((localCellId % messageFrequency) == 0) {\n            cout << timestamp << \"Working on cell \" << localCellId << \" of \" << cellCount << endl;\n        }\n\n        // Compute the mean of the expression vector for this cell.\n        const ExpressionMatrixSubset::Sum& sum = expressionMatrixSubset.sums[localCellId];\n        const double mean = sum.sum1 / double(geneCount);\n\n        // If U is one of the LSH vectors, we need to compute the scalar product\n        // s = X*U, where X is the cell expression vector, shifted to zero mean:\n        // X = x - mean,\n        // mean = sum(x)/geneCount (computed above).\n        // We get:\n        // s = (x-mean)*U = x*U - mean*U = x*U - mean*sum(U)\n        // We computed sum(U) above and stored it in lshVectorSums for\n        // each of the LSH vectors.\n        // Initialize the scalar products for this cell\n        // with all of the LSH vectors to -mean*sum(U).\n        for(size_t i=0; i<lshCount; i++) {\n            scalarProducts[i] = -mean * lshVectorsSums[i];\n        }\n\n        // Now add to each scalar product the x*U portion.\n        // For performance, the loop over genes is outside,\n        // which gives better memory locality.\n        // Add the contributions of the non-zero expression counts for this cell.\n        for(const auto& p : expressionMatrixSubset.cellExpressionCounts[localCellId]) {\n            const GeneId localGeneId = p.first;\n            const double count = double(p.second);\n\n            // Add the contribution of this gene to the scalar products.\n            const auto& v = lshVectors[localGeneId];\n            CZI_ASSERT(v.size() == lshCount);\n            for(size_t i=0; i<lshCount; i++) {\n                scalarProducts[i] += count * v[i];\n            }\n        }\n\n        // Set to 1 the signature bits corresponding to positive scalar products.\n        BitSetPointer cellSignature = getSignature(localCellId);\n        for(size_t i=0; i<lshCount; i++) {\n            if(scalarProducts[i]>0.) {\n                cellSignature.set(i);\n            }\n        }\n\n    }\n    const auto t1 = std::chrono::steady_clock::now();\n    cout << timestamp << \"Computation of cell LSH signatures ends.\" << endl;\n    const size_t nonZeroExpressionCount = expressionMatrixSubset.totalExpressionCounts();\n    cout << \"Processed \" << nonZeroExpressionCount << \" non-zero expression counts for \";\n    cout << geneCount << \" genes and \" << cellCount << \" cells.\" << endl;\n    cout << \"Average number of expression counts per cell  is \" << double(nonZeroExpressionCount) / double(cellCount) << endl;\n    cout << \"Average expression matrix sparsity is \" <<\n        double(nonZeroExpressionCount) / (double(geneCount) * double(cellCount)) << endl;\n    const double t01 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0)).count());\n    cout << \"Computation of LSH cell signatures took \" << t01 << \"s.\" << endl;\n    cout << \"    Seconds per cell \" << t01 / cellCount << endl;\n    cout << \"    Seconds per non-zero expression matrix entry \" << t01/double(nonZeroExpressionCount) << endl;\n    cout << \"    Seconds per inner loop iteration \" << t01 / (double(nonZeroExpressionCount) * double(lshCount)) << endl;\n    cout << \"    Gflop/s \" << 2. * 1e-9 * double(nonZeroExpressionCount) * double(lshCount) / t01 << endl;\n\n}\n\n\n\n// Compute the similarity (cosine of the angle) corresponding to each number of mismatching bits.\nvoid Lsh::computeSimilarityTable()\n{\n    // Initialize the similarity table.\n    similarityTable.resize(lshCount() + 1);\n\n    // Loop over all possible numbers of mismatching bits.\n    for(size_t mismatchingBitCount = 0;\n        mismatchingBitCount <= lshCount(); mismatchingBitCount++) {\n\n        // Compute the angle between the vectors corresponding to\n        // this number of mismatching bits.\n        const double angle = double(mismatchingBitCount) *\n            boost::math::double_constants::pi / double(lshCount());\n\n        // The cosine of the angle is the similarity for\n        // this number of mismatcning bits.\n        CZI_ASSERT(mismatchingBitCount < similarityTable.size());\n        similarityTable[mismatchingBitCount] = std::cos(angle);\n    }\n\n}\n\n\n// Compute the LSH similarity between two cells,\n// specified by their ids local to the cell set used by this Lsh object.\ndouble Lsh::computeCellSimilarity(CellId localCellId0, CellId localCellId1)\n{\n    // Access the LSH signatures for the two cells.\n    const BitSetPointer signature0 = getSignature(localCellId0);\n    const BitSetPointer signature1 = getSignature(localCellId1);\n\n    // Count the number of bits where the signatures of these two cells disagree.\n    const size_t mismatchingBitCount = countMismatches(signature0, signature1);\n\n    // Return the similarity corresponding to this number of mismatching bits.\n    return similarityTable[mismatchingBitCount];\n}\nsize_t Lsh::computeMismatchCount(CellId localCellId0, CellId localCellId1)\n{\n    // Access the LSH signatures for the two cells.\n    const BitSetPointer signature0 = getSignature(localCellId0);\n    const BitSetPointer signature1 = getSignature(localCellId1);\n\n    // Count the number of bits where the signatures of these two cells disagree.\n    return countMismatches(signature0, signature1);\n}\n\n\n\n// Write to a csv file statistics of the cell LSH signatures..\nvoid Lsh::writeSignatureStatistics(const string& csvFileName)\n{\n    ofstream csv(csvFileName);\n    writeSignatureStatistics(csv);\n}\nvoid Lsh::writeSignatureStatistics(ostream& csv)\n{\n    csv << \"Bit,Set,Unset,Total\\n\";\n\n    for(size_t i = 0; i < info->lshCount; i++) {\n\n        // Count the number of cells that have this bit set.\n        size_t setCount = 0;\n        for(CellId cellId = 0; cellId < info->cellCount; cellId++) {\n            if(getSignature(cellId).get(i)) {\n                ++setCount;\n            }\n        }\n        const size_t unsetCount = info->cellCount - setCount;\n\n        csv << i << \",\" << setCount << \",\" << unsetCount << \",\" << info->cellCount << \"\\n\";\n\n    }\n\n}\n\n\nvoid Lsh::remove()\n{\n    signatures.remove();\n    info.remove();\n}\n\n", "meta": {"hexsha": "0316da965f2ca379429fc4878161c134398e4ec5", "size": 11820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Lsh.cpp", "max_stars_repo_name": "iosonofabio/ExpressionMatrix2", "max_stars_repo_head_hexsha": "a6fc6938fe857fe1bd6a9200071957691295ba3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lsh.cpp", "max_issues_repo_name": "iosonofabio/ExpressionMatrix2", "max_issues_repo_head_hexsha": "a6fc6938fe857fe1bd6a9200071957691295ba3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lsh.cpp", "max_forks_repo_name": "iosonofabio/ExpressionMatrix2", "max_forks_repo_head_hexsha": "a6fc6938fe857fe1bd6a9200071957691295ba3c", "max_forks_repo_licenses": ["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.8846153846, "max_line_length": 126, "alphanum_fraction": 0.6634517766, "num_tokens": 2832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5642039643437208}}
{"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 \"io.h\"\n#include \"params.h\"\n\nusing namespace std;\nusing namespace NTL;\n\nvoid PrintDoubleTab(const unsigned int N, RR_t const * const Tab)\n{\n\n\n    cout << \"[\";\n    for(unsigned int j=0; j<N; j++)\n    {\n        cout << ((long double)Tab[j]) << \"    \";\n    }\n    cout << \"]\" << endl;\n}\n\nvoid PrintDoubleMatrix(const unsigned int N, const RR_t Tab[2*N0][2*N0])\n{\n\n    for(unsigned int j=0; j<N; j++)\n    {\n        PrintDoubleTab(N,Tab[j]);\n    }\n    cout << endl;\n}\n\n\nvoid PrintIntTab(const unsigned int N, long int const * const Tab)\n{\n\n\n    cout << \"[\";\n    for(unsigned int j=0; j<N; j++)\n    {\n        cout << Tab[j] << \" \";\n    }\n    cout << \"]\" << endl;\n    cout << endl;\n}\n\n\nvoid PrintFFT(CC_t const * const f_fft)\n{\n    unsigned int i;\n    cout << \"[\";\n    for(i=0; i<N0; i++)\n    {\n        cout << (f_fft[i]).real() << \"+ I*\" << (f_fft[i]).imag() << \"\t\";\n    }\n    cout << \"]\" << endl;\n}\n", "meta": {"hexsha": "c50ae5c8dc779160a00774c092df0edf3c7a2fa8", "size": 1081, "ext": "cc", "lang": "C++", "max_stars_repo_path": "NTRU-PEKS/io.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": "io.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/io.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": 16.890625, "max_line_length": 72, "alphanum_fraction": 0.5282146161, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5641745156143545}}
{"text": "//  Copyright (c) 2014 Hartmut Kaiser\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// This is the third in a series of examples demonstrating the development of a\n// fully distributed solver for a simple 1D heat distribution problem.\n//\n// This example takes the code from example one and introduces a partitioning\n// of the 1D grid into groups of grid partitions which are handled at the same time.\n// The purpose is to be able to control the amount of work performed. The\n// example is still fully serial, no parallelization is performed.\n//\n// The only difference to 1d_stencil_3 is that this example uses OpenMP for\n// parallelizing the inner loop.\n\n//#include <boost/cstdint.hpp>\n//#include <boost/program_options.hpp>\n//#include <boost/chrono.hpp>\n\n#include <vector>\n#include <cstdlib>\n\n///////////////////////////////////////////////////////////////////////////////\n// Timer with nanosecond resolution\n/*inline int now()\n{\n    boost::chrono::nanoseconds ns =\n        boost::chrono::steady_clock::now().time_since_epoch();\n    return static_cast<int>(ns.count());\n}*/\n\n///////////////////////////////////////////////////////////////////////////////\ndouble k = 0.5;     // heat transfer coefficient\ndouble dt = 1.;     // time step\ndouble dx = 1.;     // grid spacing\n\ninline int idx(int i, int size)\n{\n    return (int(i) < 0) ? (i + size) % size : i % size;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Our partition_data data type\nstruct partition_data\n{\n    partition_data(int size = 0)\n      : data_(size)\n    {}\n\n    partition_data(int size, double initial_value)\n      : data_(size)\n    {\n        double base_value = double(initial_value * size);\n        for (int i = 0; i != size; ++i)\n            data_[i] = base_value + double(i);\n    }\n\n    double& operator[](int idx) { return data_[idx]; }\n    double operator[](int idx) const { return data_[idx]; }\n\n    int size() const { return data_.size(); }\n\nprivate:\n    std::vector<double> data_;\n};\n/*\nstd::ostream& operator<<(std::ostream& os, partition_data const& c)\n{\n    os << \"{\";\n    for (int i = 0; i != c.size(); ++i)\n    {\n        if (i != 0)\n            os << \", \";\n        os << c[i];\n    }\n    os << \"}\";\n    return os;\n}*/\n\n///////////////////////////////////////////////////////////////////////////////\nstruct stepper\n{\n    // Our data for one time step\n    typedef partition_data partition;\n    typedef std::vector<partition> space;\n\n    // Our operator\n    static double heat(double left, double middle, double right)\n    {\n        return middle + (k*dt/dx*dx) * (left - 2*middle + right);\n    }\n\n    // The partitioned operator, it invokes the heat operator above on all\n    // elements of a partition.\n    static partition_data heat_part(partition_data const& left,\n        partition_data const& middle, partition_data const& right)\n    {\n        int size = middle.size();\n        partition_data next(size);\n\n        next[0] = heat(left[size-1], middle[0], middle[1]);\n\n        //# pragma omp parallel for\n        for (int i = 1; i < int(size-1); ++i)\n            next[i] = heat(middle[i-1], middle[i], middle[i+1]);\n\n        next[size-1] = heat(middle[size-2], middle[size-1], right[0]);\n\n        return next;\n    }\n\n    // do all the work on 'np' partitions, 'nx' data points each, for 'nt'\n    // time steps\n    space do_work(int np, int nx, int nt)\n    {\n        // U[t][i] is the state of position i at time t.\n        std::vector<space> U(2);\n        for (space& s: U)\n            s.resize(np);\n\n        // Initial conditions: f(0, i) = i\n        for (int i = 0; i != np; ++i)\n            U[0][i] = partition_data(nx, double(i));\n\n        // Actual time step loop\n        for (int t = 0; t != nt; ++t)\n        {\n            space const& current = U[t % 2];\n            space& next = U[(t + 1) % 2];\n\n# pragma omp parallel\n# pragma omp single\n            {\n                for (int i = 0; i < np; ++i) {\n# pragma omp task untied\n                    next[i] = heat_part(current[idx(i-1, np)], current[i], current[idx(i+1, np)]);\n                }\n#pragma omp taskwait\n            }\n        }\n\n        // Return the solution at time-step 'nt'.\n        return U[nt % 2];\n    }\n};\n\n//int hpx_main(boost::program_options::variables_map& vm)\nint main(int argc, char* argv[])\n{\n    int np = 20;// Number of partitions.\n    int nx = 1000000;   // Number of grid points.\n    int nt = 100;   // Number of steps.\n\n    // Create the stepper object\n    stepper step;\n\n    // Measure execution time.\n//    int t = now();\n\n    // Execute nt time steps on nx grid points and print the final solution.\n    stepper::space solution = step.do_work(np, nx, nt);\n\n//    for (int i = 0; i != np; ++i)\n//        std::cout << \"U[\" << i << \"] = \" << solution[i] << std::endl;\n\n//    int elapsed = now() - t;\n//    std::cout << \"Elapsed time: \" << elapsed / 1e9 << \" [s]\" << std::endl;\n\n    return 0;\n}\n/*\nint main(int argc, char* argv[])\n{\n    namespace po = boost::program_options;\n\n    po::options_description desc_commandline;\n    desc_commandline.add_options()\n        (\"results\", \"print generated results (default: false)\")\n        (\"nx\", po::value<int>()->default_value(10),\n         \"Local x dimension (of each partition)\")\n        (\"nt\", po::value<int>()->default_value(45),\n         \"Number of time steps\")\n        (\"np\", po::value<int>()->default_value(10),\n         \"Number of partitions\")\n        (\"k\", po::value<double>(&k)->default_value(0.5),\n         \"Heat transfer coefficient (default: 0.5)\")\n        (\"dt\", po::value<double>(&dt)->default_value(1.0),\n         \"Timestep unit (default: 1.0[s])\")\n        (\"dx\", po::value<double>(&dx)->default_value(1.0),\n         \"Local x dimension\")\n    ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc_commandline), vm);\n    po::notify(vm);\n\n    return hpx_main(vm);\n}*/\n", "meta": {"hexsha": "8dfa05f5ff40f1824a214206b8a3f509e5dbb546", "size": 5971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/omp/tests/src/1d_stencil_3_omp.cpp", "max_stars_repo_name": "tianyi93/hpxMP_mirror", "max_stars_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-07-16T14:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T11:25:09.000Z", "max_issues_repo_path": "examples/omp/tests/src/1d_stencil_3_omp.cpp", "max_issues_repo_name": "tianyi93/hpxMP_mirror", "max_issues_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-06-18T14:59:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-16T20:43:57.000Z", "max_forks_repo_path": "examples/omp/tests/src/1d_stencil_3_omp.cpp", "max_forks_repo_name": "tianyi93/hpxMP_mirror", "max_forks_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T18:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-21T11:17:28.000Z", "avg_line_length": 29.855, "max_line_length": 98, "alphanum_fraction": 0.553508625, "num_tokens": 1511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5641368286590438}}
{"text": "//===------------------------------------------------------------*- C++ -*-===//\n///\n/// \\brief \u77e9\u9635\u3002\n///\n/// \\sa [Eigen: Getting started](https://eigen.tuxfamily.org/dox/GettingStarted.html)\n/// \\sa [Eigen: The Matrix class](https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html)\n///\n/// \\version 2021-10-20\n/// \\since 2021-10-20\n/// \\authors zhengrr\n/// \\copyright Unlicense\n///\n//===----------------------------------------------------------------------===//\n\n#include <type_traits>\n\n#include <Eigen/Dense>    // \u7a20\u5bc6\u77e9\u9635\n#include <gtest/gtest.h>\n\n/// \\brief \u77e9\u9635\u6a21\u677f\u3002\n/// \\details\n/// ```{.cpp}\n/// Matrix <\n///     typename Scalar,                               // \u77e9\u9635\u6761\u76ee\u7684\u6807\u91cf\u7c7b\u578b\uff0c\u5982 `int`\u3001`float` \u7b49\u3002\n///     int RowsAtCompileTime,                         // \u5728\u7f16\u8bd1\u671f\u786e\u5b9a\u7684\u56fa\u5b9a\u77e9\u9635\u884c\u6570\u3002\u4f7f\u7528 `Dynamic` \u8868\u793a\u77e9\u9635\u884c\u6570\u5728\u8fd0\u884c\u671f\u52a8\u6001\u8bbe\u7f6e\u3002\n///     int ColsAtCompileTime,                         // \u5728\u7f16\u8bd1\u671f\u786e\u5b9a\u7684\u56fa\u5b9a\u77e9\u9635\u5217\u6570\u3002\u4f7f\u7528 `Dynamic` \u8868\u793a\u77e9\u9635\u5217\u6570\u5728\u8fd0\u884c\u671f\u52a8\u6001\u8bbe\u7f6e\u3002\n///     int Options = 0,                               // \u9009\u9879\u3002\n///     int MaxRowsAtCompileTime = RowsAtCompileTime,  // \u5bf9\u4e8e\u65e0\u6cd5\u786e\u5b9a\u5177\u4f53\u5927\u5c0f\uff0c\u4f46\u53ef\u4ee5\u786e\u5b9a\u5927\u5c0f\u4e0a\u9650\u7684\u77e9\u9635\uff0c\u53ef\u4ee5\u8bbe\u5b9a\u6b64\u4e8c\u503c\uff0c\n///     int MaxColsAtCompileTime = ColsAtCompileTime   // \u4ee5\u8f83\u5927\u7684\u56fa\u5b9a\u77e9\u9635\u6765\u5b58\u50a8\u8f83\u5c0f\u7684\u52a8\u6001\u77e9\u9635\uff0c\u907f\u514d\u77e9\u9635\u7684\u52a8\u6001\u5185\u5b58\u5206\u914d\u3002\n/// >;\n/// ```\nTEST(Matrix, MatrixTemplate)\n{\n    SUCCEED();\n}\n\n/// \\brief \u4fbf\u4e8e\u4f7f\u7528\u7684\u5185\u7f6e\u7c7b\u578b\u522b\u540d\u3002\n/// \\details\n/// ```{.cpp}\n/// MatrixNt    = Matrix<type, N, N>  // \u65b9\u9635\u3002\n/// VectorNt    = Matrix<type, N, 1>  // \u5217\u5411\u91cf\u3002\n/// RowVectorNt = Matrix<type, 1, N>  // \u884c\u5411\u91cf\u3002\n/// ```\n/// \u5176\u4e2d `type` \u4e3a `int`\u3001`float`\u3001`double`\u3001`std::complex<float>` \u6216 `std::complex<double>`\uff1b  \n/// `N` \u4e3a `2`\u3001`3`\u3001`4` \u6216 `X`\uff08\u8868\u793a `Dynamic`\uff09\u3002\nTEST(Matrix, ConvenienceTypedefs)\n{\n    static_assert(std::is_same_v<\n                  Eigen::Matrix2i,\n                  Eigen::Matrix<int, 2, 2>\n    >);\n    static_assert(std::is_same_v<\n                  Eigen::Vector4f,\n                  Eigen::Matrix<float, 4, 1>\n    >);\n    static_assert(std::is_same_v<\n                  Eigen::RowVectorXd,\n                  Eigen::Matrix<double, 1, Eigen::Dynamic>\n    >);\n}\n\n/// \\brief \u56fa\u5b9a\u5927\u5c0f\u77e9\u9635\u548c\u52a8\u6001\u5927\u5c0f\u77e9\u9635\u5bf9\u6bd4\u3002\n/// \\details\n/// \u7ecf\u9a8c\u6cd5\u5219\uff1a\n/// *   \u5bf9\u4e8e `size()` < ~16 \u7684\u77e9\u9635\u91c7\u7528\u56fa\u5b9a\u5927\u5c0f\u77e9\u9635\u3001\u5728\u6808\u4e0a\u5206\u914d\u5185\u5b58\uff0c\n///     \u8fd9\u53ef\u4ee5\u907f\u514d\u52a8\u6001\u5185\u5b58\u5206\u914d\u548c\u5c55\u5f00\u5faa\u73af\u3001\u5e76\u63d0\u4f9b\u66f4\u4e25\u683c\u7684\u7c7b\u578b\u68c0\u67e5\uff0c\u4f46\u4e5f\u4f1a\u589e\u52a0\u7f16\u8bd1\u65f6\u95f4\u3001\u589e\u5927\u7a0b\u5e8f\u4f53\u79ef\uff1b\n/// *   \u5bf9\u4e8e ~32 < `size()` \u7684\u77e9\u9635\u91c7\u7528\u52a8\u6001\u5927\u5c0f\u77e9\u9635\u3001\u5728\u5806\u4e0a\u5206\u914d\u5185\u5b58\uff0c\n///     \u6b64\u65f6\u8be5\u7c7b\u77e9\u9635\u7684\u6027\u80fd\u52a3\u52bf\u53d8\u5f97\u53ef\u4ee5\u5ffd\u7565\u4e0d\u8ba1\uff0c\u800c\u4e14\u53ef\u4ee5\u907f\u514d\u6808\u6ea2\u51fa\u3002\nTEST(Matrix, FixedVsDynamicSize)\n{\n    SUCCEED();\n}\n\n/// \\brief \u9ed8\u8ba4\u6784\u9020\u3002\nTEST(Matrix, DefaultConstructors)\n{\n    Eigen::Matrix3i fixMat;  // \u5728\u6808\u4e0a\u5206\u914d `int[3*3]` \u7684\u7a7a\u95f4\uff0c\u5c1a\u672a\u521d\u59cb\u5316\n    Eigen::MatrixXi dynMat;  // \u5c1a\u672a\u5206\u914d\u7a7a\u95f4\uff0c\u5c1a\u672a\u521d\u59cb\u5316\n\n    Eigen::Vector3i fixVec;  // \u5728\u6808\u4e0a\u5206\u914d `int[3*1]` \u7684\u7a7a\u95f4\uff0c\u5c1a\u672a\u521d\u59cb\u5316\n    Eigen::VectorXi dynVec;  // \u5c1a\u672a\u5206\u914d\u7a7a\u95f4\uff0c\u5c1a\u672a\u521d\u59cb\u5316\n}\n\n/// \\brief \u5c3a\u5bf8\u6784\u9020\u3002\nTEST(Matrix, SizedConstructors)\n{\n    Eigen::Matrix3i fixMat {3, 3};  // \u5728\u6808\u4e0a\u5206\u914d `int[3*3]` \u7684\u7a7a\u95f4\uff0c\u5c1a\u672a\u521d\u59cb\u5316\uff1b\u4e3a\u7edf\u4e00\u63a5\u53e3\u800c\u5141\u8bb8\u5197\u4f59\u7684\u5c3a\u5bf8\u53c2\u6570\n    Eigen::MatrixXi dynMat {3, 3};  // \u5728\u5806\u4e0a\u5206\u914d `new int[3*3]` \u7684\u7a7a\u95f4\uff0c\u5c1a\u672a\u521d\u59cb\u5316\n\n    Eigen::Vector3i fixVec {3};  // \u5728\u6808\u4e0a\u5206\u914d `int[3*1]` \u7684\u7a7a\u95f4\uff0c\u5c1a\u672a\u521d\u59cb\u5316\uff1b\u4e3a\u7edf\u4e00\u63a5\u53e3\u800c\u5141\u8bb8\u5197\u4f59\u7684\u5c3a\u5bf8\u53c2\u6570\n    Eigen::VectorXi dynVec {3};  // \u5728\u5806\u4e0a\u5206\u914d `new int[3*1]` \u7684\u7a7a\u95f4\uff0c\u5c1a\u672a\u521d\u59cb\u5316\n}\n\n/// \\brief \u521d\u59cb\u5316\u6784\u9020\u3002\nTEST(Matrix, InitializedConstructors)\n{\n    Eigen::Matrix3i fixMat {  // \u5728\u6808\u4e0a\u5206\u914d `int[3*3]` \u7684\u7a7a\u95f4\uff0c\u5e76\u8fdb\u884c\u521d\u59cb\u5316\n        {11, 12, 13},\n        {21, 22, 23},\n        {31, 32, 33}\n    };\n\n    Eigen::MatrixXi dynMat {  // \u5728\u5806\u4e0a\u5206\u914d `new int[3*3]` \u7684\u7a7a\u95f4\uff0c\u5e76\u8fdb\u884c\u521d\u59cb\u5316\n        {11, 12, 13},\n        {21, 22, 23},\n        {31, 32, 33}\n    };\n\n    Eigen::Vector3i fixRawVec {{11, 12, 13}};  // \u5728\u6808\u4e0a\u5206\u914d `int[1*3]` \u7684\u7a7a\u95f4\uff0c\u5e76\u8fdb\u884c\u521d\u59cb\u5316\n    Eigen::Vector3i fixRawVec2 {11, 12, 13};   // \u5728\u4e0d\u5f15\u8d77\u6b67\u4e49\u7684\u60c5\u51b5\u4e0b\uff0c\u56fa\u5b9a\u5927\u5c0f\u5411\u91cf\u7684\u5185\u5c42\u5927\u62ec\u53f7\u53ef\u4ee5\u7701\u7565\n\n    Eigen::VectorXi dynRawVec {{11, 12, 13}};  // \u5728\u5806\u4e0a\u5206\u914d `new int[1*3]` \u7684\u7a7a\u95f4\uff0c\u5e76\u8fdb\u884c\u521d\u59cb\u5316\n\n    Eigen::Vector3i fixColVec {{11}, {21}, {31}};  // \u5728\u6808\u4e0a\u5206\u914d `int[3*1]` \u7684\u7a7a\u95f4\uff0c\u5e76\u8fdb\u884c\u521d\u59cb\u5316\n    Eigen::Vector3i fixColVec2 {{11, 21, 31}};     // \u5217\u77e9\u9635\u7684\u521d\u59cb\u5316\u6784\u9020\u53ef\u4ee5\u9690\u5f0f\u8f6c\u7f6e\n    Eigen::Vector3i fixColVec3 {11, 21, 31};       // \u5728\u4e0d\u5f15\u8d77\u6b67\u4e49\u7684\u60c5\u51b5\u4e0b\uff0c\u56fa\u5b9a\u5927\u5c0f\u5411\u91cf\u7684\u5185\u5c42\u5927\u62ec\u53f7\u53ef\u4ee5\u7701\u7565\n\n    Eigen::VectorXi dynColVec {{11}, {21}, {31}};  // \u5728\u5806\u4e0a\u5206\u914d `new int[3*1]` \u7684\u7a7a\u95f4\uff0c\u5e76\u8fdb\u884c\u521d\u59cb\u5316\n    Eigen::VectorXi dynColVec2 {{11, 21, 31}};     // \u5217\u77e9\u9635\u7684\u521d\u59cb\u5316\u6784\u9020\u53ef\u4ee5\u9690\u5f0f\u8f6c\u7f6e\n}\n\n/// \\brief \u8d4b\u503c\u53d6\u503c\u3002\nTEST(Matrix, SetGet)\n{\n    Eigen::Matrix3i mat;\n    mat << 1, 2, 3,\n           4, 5, 6,\n           7, 8, 9;\n    EXPECT_EQ(mat(0), 1);\n    EXPECT_EQ(mat(0, 0), 1);\n\n    Eigen::Vector3i vec;\n    vec << 1, 2, 3;\n    EXPECT_EQ(vec(0), 1);\n    EXPECT_EQ(vec[0], 1);\n}\n", "meta": {"hexsha": "de199c5197988a4e923868437ba6ed236e2e20cd", "size": 4110, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rrEigen/Core/matrix.cpp", "max_stars_repo_name": "afoolsbag/rrCnCxx", "max_stars_repo_head_hexsha": "1e673bd4edac43d8406a0c726138cba194d17f48", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-20T01:14:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T15:39:32.000Z", "max_issues_repo_path": "rrEigen/Core/matrix.cpp", "max_issues_repo_name": "afoolsbag/rrCnCxx", "max_issues_repo_head_hexsha": "1e673bd4edac43d8406a0c726138cba194d17f48", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rrEigen/Core/matrix.cpp", "max_forks_repo_name": "afoolsbag/rrCnCxx", "max_forks_repo_head_hexsha": "1e673bd4edac43d8406a0c726138cba194d17f48", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0, "max_line_length": 100, "alphanum_fraction": 0.5501216545, "num_tokens": 1873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5641368217880118}}
{"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": "#include \"opttmp/vectorization/register_tiling.hpp\"\n#include \"parameters.hpp\"\n#include <Vc/Vc>\n#include <boost/align/aligned_allocator.hpp>\n#include <iostream>\n#include <omp.h>\n#include <vector>\n\nusing reg_arr =\n    opttmp::vectorization::register_array<Vc::double_v, REG_BLOCKING>;\nusing align = boost::alignment::aligned_allocator<double, 64>;\n\nAUTOTUNE_EXPORT void scale(std::vector<double, align> &a,\n                           std::vector<double, align> &b, double q) {\n\n  omp_set_num_threads(KERNEL_OMP_THREADS);\n  // std::cout << \"KERNEL_OMP_THREADS: \" << KERNEL_OMP_THREADS << std::endl;\n\n  // not kept in registers for unknown reasons\n  const Vc::double_v q_vec = q;\n  // std::cout << \"q_vec: \" << q_vec << std::endl;\n  const size_t N = a.size();\n#pragma omp parallel for\n  for (size_t i = 0; i < N; i += REG_BLOCKING * Vc::double_v::size()) {\n    // vector_aligned leads to crash?\n    reg_arr temp(&b[i], Vc::flags::element_aligned);\n    temp = q_vec * temp;\n    temp.memstore(&a[i], Vc::flags::element_aligned);\n    // a[i] = q * b[i];\n  }\n}\n", "meta": {"hexsha": "70ec1ffde067d607dafc3c811df8cabbad312d88", "size": 1053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/stream_kernel/scale.cpp", "max_stars_repo_name": "DavidPfander-UniStuttgart/AutoTuneTMP", "max_stars_repo_head_hexsha": "f5fb836778b04c2ab0fbcc4d36c466e577e96e65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-11-06T15:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T20:25:50.000Z", "max_issues_repo_path": "examples/stream_kernel/scale.cpp", "max_issues_repo_name": "DavidPfander-UniStuttgart/AutoTuneTMP", "max_issues_repo_head_hexsha": "f5fb836778b04c2ab0fbcc4d36c466e577e96e65", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-01-25T21:25:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T17:35:27.000Z", "max_forks_repo_path": "examples/stream_kernel/scale.cpp", "max_forks_repo_name": "DavidPfander-UniStuttgart/AutoTuneTMP", "max_forks_repo_head_hexsha": "f5fb836778b04c2ab0fbcc4d36c466e577e96e65", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T11:05:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-15T11:05:43.000Z", "avg_line_length": 32.90625, "max_line_length": 76, "alphanum_fraction": 0.6638176638, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.564059553975192}}
{"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": "// Copyright 2016 Arizona Board of Regents. See README.md and LICENSE for more.\n\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <ctime>\n\n#include <boost/random.hpp>\n#include <boost/generator_iterator.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"nanocube.h\"\n#include \"nanocube_traversals.h\"\n#include \"debug.h\"\n#include \"test_utils.h\"\n\nint atoi(const std::string &s) { return atoi(s.c_str()); }\ndouble atof(const std::string &s) { return atof(s.c_str()); }\n\n// convert lat,lon to quad tree address\nint64_t loc2addr(double lat, double lon, int qtreeLevel)\n{\n    double xd = (lon + M_PI) / (2.0 * M_PI);\n    double yd = (log(tan(M_PI / 4.0 + lat / 2.0)) + M_PI) / (2.0 * M_PI);\n    //cout << lat << \" \" << lon << \" \" << endl;\n    int x = xd * (1 << qtreeLevel), y = yd * (1 << qtreeLevel);\n\n    int64_t z = 0; // z gets the resulting Morton Number.\n\n    for (int i = 0; i < sizeof(x) * 8; i++) // unroll for more speed...\n    {\n        z |= (x & 1U << i) << i | (y & 1U << i) << (i + 1);\n    }\n\n    return z;\n}\n\n\nint main(int argc, char **argv)\n{\n    using namespace boost::gregorian;\n    using namespace boost::posix_time;\n\n    ifstream is(argv[1]);\n    std::cout << \"Data file: \" << argv[1] << std::endl;\n    string s;\n\n    int qtreeLevel = 15;\n    int dim3Level = 16;\n\n    vector<int> schema = {qtreeLevel*2, dim3Level};\n    // use a quadtree\n    //Nanocube<int> nc({qtreeLevel, qtreeLevel, 16});\n    Nanocube<int> nc(schema);\n\n    vector<pair<int,int> > dataarray;\n\n    int i = 0;\n\n    clock_t begin = clock();\n\n    while (std::getline(is, s)) {\n        vector<string> output;\n        boost::split(output,s,boost::is_any_of(\"\\t\"));\n        if (output.size() != 5) {\n            cerr << \"Bad line:\" << s << endl;\n            continue;\n        }\n        if (atof(output[2]) < -85.0511 || atof(output[2]) > 85.0511) {\n            cerr << \"Invalid latitude: \" << output[2] << \" (should be in [-85.0511, 85.0511])\" << endl;\n            continue;\n        }\n\n        string year = output[1].substr(0, 4), \n               month = output[1].substr(5, 2), \n               day = output[1].substr(8, 2),\n               hour = output[1].substr(11, 2), \n               minute = output[1].substr(14, 2), \n               sec = output[1].substr(17, 2);\n\n        ptime d(date(atoi(year), atoi(month), atoi(day)), hours(atoi(hour)) + minutes(atoi(minute)) + seconds(atoi(sec)));\n\n        ptime beg_of_time(date(2000, 1, 1));\n\n        double lat = atof(output[2]) * M_PI / 180.0, lon = atof(output[3]) * M_PI / 180.0;\n        // turn (x,y) into an address of the quadtree\n        // Interleave bits\n        int64_t z = loc2addr(lat, lon, qtreeLevel);\n\n        int total_seconds = (d - beg_of_time).total_seconds();\n        int t = total_seconds / 3600 / 24;\n\n\n        nc.insert(1, {z, t});\n        dataarray.push_back({z,t});\n\n        if (++i % 10000 == 0) {\n            {\n                //ofstream os(\"brightkite.nc\");\n                //nc.write_to_binary_stream(os);\n            }\n            //nc.report_size();\n            cout << i << endl;\n        }\n    }\n\n    clock_t end = clock();\n    double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;\n    cout << \"Running time: \" << elapsed_secs << endl;\n\n    /**************************************************/\n    // Test\n    /**************************************************/\n    int n_regions = 10;\n    for (int l=0; l<n_regions; ++l) {\n        vector<pair<int64_t, int64_t> > region = random_region(schema);\n        int rq = ortho_range_query(nc, region);\n        int count = 0;\n        for(int dlength = 0; dlength < dataarray.size(); dlength++) {\n            if( (dataarray[dlength].first > region[0].first && \n                        dataarray[dlength].first < region[0].second) && \n                    (dataarray[dlength].second > region[1].first &&\n                     dataarray[dlength].second < region[1].second) ) {\n                count ++;\n            }\n        }\n        cout << \"Query from Nanocubea: \"<< rq << \" | Linear scan: \" << count << endl;\n    }\n\n    /**************************************************/\n    // Save\n    /**************************************************/\n\n    {\n        //nc.content_compact();\n        //ofstream os(\"brightkite.nc\");\n        //nc.write_to_binary_stream(os);\n    }\n\n    // std::string s(\"2001-10-9\"); //2001-October-09\n    // date d(from_simple_string(s));\n}\n", "meta": {"hexsha": "d895dcd02cf903b617238134b9dde0097c7d98c5", "size": 4492, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_brightkite.cc", "max_stars_repo_name": "cscheid/nanocube2", "max_stars_repo_head_hexsha": "c544d853e399ac95194e93020c34f570ce596642", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-11-04T17:13:57.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-24T17:50:22.000Z", "max_issues_repo_path": "src/tests/test_brightkite.cc", "max_issues_repo_name": "cscheid/nanocube2", "max_issues_repo_head_hexsha": "c544d853e399ac95194e93020c34f570ce596642", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_brightkite.cc", "max_forks_repo_name": "cscheid/nanocube2", "max_forks_repo_head_hexsha": "c544d853e399ac95194e93020c34f570ce596642", "max_forks_repo_licenses": ["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.9793103448, "max_line_length": 122, "alphanum_fraction": 0.5155832591, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5640595488641651}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <vector>\n#include <limits>\n\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\n\nTEST(ProbDistributionsCategorical, Categorical) {\n  Matrix<double, Dynamic, 1> theta(3, 1);\n  theta << 0.3, 0.5, 0.2;\n  EXPECT_FLOAT_EQ(-1.203973, stan::math::categorical_log(1, theta));\n  EXPECT_FLOAT_EQ(-0.6931472, stan::math::categorical_log(2, theta));\n}\nTEST(ProbDistributionsCategorical, Propto) {\n  Matrix<double, Dynamic, 1> theta(3, 1);\n  theta << 0.3, 0.5, 0.2;\n  EXPECT_FLOAT_EQ(0.0, stan::math::categorical_log<true>(1, theta));\n  EXPECT_FLOAT_EQ(0.0, stan::math::categorical_log<true>(2, theta));\n}\n\nTEST(ProbDistributionsCategorical, VectorInt) {\n  Matrix<double, Dynamic, 1> theta(3, 1);\n  theta << 0.3, 0.5, 0.2;\n  std::vector<int> xs0;\n  EXPECT_FLOAT_EQ(0.0, stan::math::categorical_log(xs0, theta));\n\n  std::vector<int> xs(3);\n  xs[0] = 1;\n  xs[1] = 3;\n  xs[2] = 1;\n\n  EXPECT_FLOAT_EQ(log(0.3) + log(0.2) + log(0.3),\n                  stan::math::categorical_log(xs, theta));\n}\n\nusing stan::math::categorical_log;\n\nTEST(ProbDistributionsCategorical, error) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  double inf = std::numeric_limits<double>::infinity();\n\n  unsigned int n = 1;\n  unsigned int N = 3;\n  Matrix<double, Dynamic, 1> theta(N, 1);\n  theta << 0.3, 0.5, 0.2;\n\n  EXPECT_NO_THROW(categorical_log(N, theta));\n  EXPECT_NO_THROW(categorical_log(n, theta));\n  EXPECT_NO_THROW(categorical_log(2, theta));\n  EXPECT_THROW(categorical_log(N + 1, theta), std::domain_error);\n  EXPECT_THROW(categorical_log(0, theta), std::domain_error);\n\n  theta(0) = nan;\n  EXPECT_THROW(categorical_log(n, theta), std::domain_error);\n  theta(0) = inf;\n  EXPECT_THROW(categorical_log(n, theta), std::domain_error);\n  theta(0) = -inf;\n  EXPECT_THROW(categorical_log(n, theta), std::domain_error);\n  theta(0) = -1;\n  theta(1) = 1;\n  theta(2) = 0;\n  EXPECT_THROW(categorical_log(n, theta), std::domain_error);\n\n  std::vector<int> ns(3);\n  ns[0] = 3;\n  ns[1] = 2;\n  ns[2] = 3;\n  EXPECT_THROW(categorical_log(ns, theta), std::domain_error);\n\n  theta << 0.3, 0.5, 0.2;\n  EXPECT_NO_THROW(categorical_log(ns, theta));\n  ns[1] = -1;\n  EXPECT_THROW(categorical_log(ns, theta), std::domain_error);\n\n  ns[1] = 1;\n  ns[2] = 12;\n  EXPECT_THROW(categorical_log(ns, theta), std::domain_error);\n}\n\nTEST(ProbDistributionsCategorical, error_check) {\n  boost::random::mt19937 rng;\n\n  Matrix<double, Dynamic, Dynamic> theta(3, 1);\n  theta << 0.15, 0.45, 0.50;\n\n  EXPECT_THROW(stan::math::categorical_rng(theta, rng), std::domain_error);\n}\n\nTEST(ProbDistributionsCategorical, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n\n  int N = 10000;\n  Matrix<double, Dynamic, Dynamic> theta(3, 1);\n  theta << 0.15, 0.45, 0.40;\n  int K = theta.rows();\n  boost::math::chi_squared mydist(K - 1);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> loc(theta.rows(), 1);\n  for (int i = 0; i < theta.rows(); i++)\n    loc(i) = 0;\n\n  for (int i = 0; i < theta.rows(); i++) {\n    for (int j = i; j < theta.rows(); j++)\n      loc(j) += theta(i);\n  }\n\n  int count = 0;\n  int bin[K];\n  double expect[K];\n  for (int i = 0; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N * theta(i);\n  }\n\n  while (count < N) {\n    int a = stan::math::categorical_rng(theta, rng);\n    bin[a - 1]++;\n    count++;\n  }\n\n  double chi = 0;\n\n  for (int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n", "meta": {"hexsha": "6d2525ae541e636c9441b2e44dbaf18cda16c92b", "size": 3579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/mat/prob/categorical_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/prim/mat/prob/categorical_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/prim/mat/prob/categorical_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.320610687, "max_line_length": 75, "alphanum_fraction": 0.6473875384, "num_tokens": 1205, "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": "//  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/*!\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_ACOTPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACOTPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the inverse cotangent in pi multiples.\n\n\n    @par Header <boost/simd/function/acotpi.hpp>\n\n    @par Note\n\n      For every parameter of floating type `acotpi(x)`\n      returns the arc @c r in the interval  \\f$[0, 1[\\f$ such\n      that <tt>cotpi(r) == x</tt>.\n\n    @see acot, acotd, cotpi\n\n\n    @par Example:\n\n      @snippet acotpi.cpp acotpi\n\n    @par Possible output:\n\n      @snippet acotpi.txt acotpi\n\n  **/\n  IEEEValue acotpi(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acotpi.hpp>\n#include <boost/simd/function/simd/acotpi.hpp>\n\n#endif\n", "meta": {"hexsha": "a655526a3a645e608c210702065fbe85018f3c01", "size": 1191, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acotpi.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/acotpi.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/acotpi.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.3529411765, "max_line_length": 100, "alphanum_fraction": 0.5818639798, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5639801972509891}}
{"text": "#include \"element.h\"\r\n\r\n#include <Eigen/Eigen>\r\n\r\n\r\nElement::Element(const Eigen::MatrixXd& V, const Eigen::VectorXi& indices, const Eigen::VectorXi& faces)\r\n: _indices(indices), _faces(faces)\r\n{\r\n\t_X = extract(V);\r\n}\r\n\r\nElement::~Element()\r\n{\r\n\r\n}\r\n\r\ndouble Element::getEnergy() const\r\n{\r\n\treturn _energy;\r\n}\r\n\r\nconst Eigen::VectorXi& Element::getVertices() const\r\n{\r\n\treturn _indices;\r\n}\r\n\r\n/////////////////////////////////////////////////////\r\n\r\nvoid Element::addGradient(Eigen::MatrixXd& G) const\r\n{\r\n\tconst int32_t n = (int32_t)_indices.size();\r\n\tfor (int32_t i = 0; i < n; i++)\r\n\t{\r\n\t\tG.row(_indices[i]) += _G.row(i);\r\n\t}\r\n}\r\n\r\nvoid Element::addHessian(Eigen::MatrixXd& H) const\r\n{\r\n\tconst int32_t n = (int32_t)_indices.size();\r\n\tfor (int32_t i = 0; i < n; i++)\r\n\t{\r\n\t\tH.row(_indices[i]) += _H.row(i);\r\n\t}\r\n}\r\n\r\n\r\nvoid Element::addFiniteGradient(Eigen::MatrixXd& G) const\r\n{\r\n\tconst int32_t n = (int32_t)_indices.size();\r\n\tfor (int32_t i = 0; i < n; i++)\r\n\t{\r\n\t\tG.row(_indices[i]) += _fG.row(i);\r\n\t}\r\n}\r\n\r\n\r\nvoid Element::colorFaces(const Eigen::Vector3d& rgb, Eigen::MatrixXd& C) const\r\n{\r\n\tfor (int i = 0; i < _faces.size(); i++)\r\n\t{\r\n\t\tC.row(_faces[i]) = rgb;\r\n\t}\r\n}\r\n\r\n/////////////////////////////////////////////////////\r\n\r\nEigen::MatrixXd Element::extract(const Eigen::MatrixXd& V)\r\n{\r\n\tconst int32_t n = (int32_t)_indices.size();\r\n\tEigen::MatrixXd x = Eigen::MatrixXd::Zero(n, 3);\r\n\tfor (int32_t i = 0; i < n; i++)\r\n\t{\r\n\t\tx.row(i) = V.row(_indices[i]);\r\n\t}\r\n\treturn x;\r\n}\r\n\r\n", "meta": {"hexsha": "3371af665bf6fb017841a78b76bc87e5c4f836c8", "size": 1490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/element.cpp", "max_stars_repo_name": "AngryLizard/BendyPrint", "max_stars_repo_head_hexsha": "78334d07f7f14cb46cd1bf6a51fc8554a61052e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/element.cpp", "max_issues_repo_name": "AngryLizard/BendyPrint", "max_issues_repo_head_hexsha": "78334d07f7f14cb46cd1bf6a51fc8554a61052e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/element.cpp", "max_forks_repo_name": "AngryLizard/BendyPrint", "max_forks_repo_head_hexsha": "78334d07f7f14cb46cd1bf6a51fc8554a61052e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8607594937, "max_line_length": 105, "alphanum_fraction": 0.5577181208, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5639801866939167}}
{"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 \u7d50\u679c: \" << KF->compute(y, dt).transpose() << std::endl;\n        \n        /** !Output.\n         * @brief KF Result \u7d50\u679c:  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": "// This scripts runs the simulations with two populations (Section 6.1)\n\n#include <src/algorithms/neal2_algorithm.h>\n#include <src/algorithms/semihdp_sampler.h>\n#include <src/collectors/file_collector.h>\n#include <src/collectors/memory_collector.h>\n#include <src/includes.h>\n#include <src/utils/rng.h>\n\n#include <Eigen/Dense>\n#include <stan/math/prim.hpp>\n#include <vector>\n\n#include \"utils.hpp\"\n\nusing Eigen::MatrixXd;\n\nstd::vector<MatrixXd> simulate_data(double m1, double s1, double m2, double s2,\n                                    double w1, double m3, double s3, double m4,\n                                    double s4, double w2, int n1, int n2) {\n  auto& rng = bayesmix::Rng::Instance().get();\n  std::vector<MatrixXd> out(2);\n  out[0] = MatrixXd::Zero(n1, 1);\n  out[1] = MatrixXd::Zero(n2, 1);\n\n  for (int i = 0; i < n1; i++) {\n    if (stan::math::uniform_rng(0, 1, rng) < w1) {\n      out[0](i, 0) = stan::math::normal_rng(m1, s1, rng);\n    } else {\n      out[0](i, 0) = stan::math::normal_rng(m2, s2, rng);\n    }\n  }\n\n  for (int i = 0; i < n2; i++) {\n    if (stan::math::uniform_rng(0, 1, rng) < w2) {\n      out[1](i, 0) = stan::math::normal_rng(m3, s3, rng);\n    } else {\n      out[1](i, 0) = stan::math::normal_rng(m4, s4, rng);\n    }\n  }\n  return out;\n}\n\nint main() {\n  // Scenario I\n  std::vector<MatrixXd> data1 = simulate_data(0.0, 1.0, 5.0, 1.0, 0.5, 0.0,\n                                              1.0, 5.0, 1.0, 0.5, 100, 100);\n\n  // Scenario II\n  std::vector<MatrixXd> data2 = simulate_data(5.0, 0.6, 10.0, 0.6, 0.9, 5.0,\n                                              0.6, 0.0, 0.6, 0.1, 100, 100);\n\n  // Scenario III\n  std::vector<MatrixXd> data3 = simulate_data(0.0, 1.0, 5.0, 1.0, 0.8, 0.0,\n                                              1.0, 5.0, 1.0, 0.2, 100, 100);\n\n  // data1[1] = data1[0];\n\n  run_semihdp(data1,\n              \"/home/mario/PhD/exchangeability/semihdp-scripts/\"\n              \"new_chains/s1e1_v2.recordio\",\n              \"/Users/marioberaha/research/bnp/semihdp/semihdp-scripts/semihdp_params.asciipb\");\n  run_semihdp(data2,\n              \"/home/mario/PhD/exchangeability/semihdp-scripts/\"\n              \"new_chains/s1e2_v2.recordio\",\n              \"/Users/marioberaha/research/bnp/semihdp/semihdp-scripts/semihdp_params.asciipb\");\n  run_semihdp(data3,\n              \"/home/mario/PhD/exchangeability/semihdp-scripts/\"\n              \"new_chains/s1e3_v2.recordio\",\n              \"/Users/marioberaha/research/bnp/semihdp/semihdp-scripts/semihdp_params.asciipb\");\n}", "meta": {"hexsha": "47db3ae5d9e6a0e0a36e18357b7bbca83bbbda97", "size": 2508, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "run_simulation1.cpp", "max_stars_repo_name": "mberaha/semihdp-scripts", "max_stars_repo_head_hexsha": "fbf5e9c97644096357912c05bb8b4d7715d01b9e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "run_simulation1.cpp", "max_issues_repo_name": "mberaha/semihdp-scripts", "max_issues_repo_head_hexsha": "fbf5e9c97644096357912c05bb8b4d7715d01b9e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "run_simulation1.cpp", "max_forks_repo_name": "mberaha/semihdp-scripts", "max_forks_repo_head_hexsha": "fbf5e9c97644096357912c05bb8b4d7715d01b9e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.323943662, "max_line_length": 96, "alphanum_fraction": 0.5733652313, "num_tokens": 867, "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\u2080 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": "//  Copyright 2020 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#include <iostream>\n#include <benchmark/benchmark.h>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/multiprecision/integer.hpp>\n#include <boost/random.hpp>\n#include <cmath>\n\n#include <immintrin.h>\n\nusing namespace boost::multiprecision;\nusing namespace boost::random;\n\ntemplate <class Integer>\nBOOST_MP_CXX14_CONSTEXPR Integer sqrt_old(const Integer& x, Integer& r)\n{\n   //\n   // This is slow bit-by-bit integer square root, see for example\n   // http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_.28base_2.29\n   // There are better methods such as http://hal.inria.fr/docs/00/07/28/54/PDF/RR-3805.pdf\n   // and http://hal.inria.fr/docs/00/07/21/13/PDF/RR-4475.pdf which should be implemented\n   // at some point.\n   //\n   Integer s = 0;\n   if (x == 0)\n   {\n      r = 0;\n      return s;\n   }\n   int g = msb(x);\n   if (g == 0)\n   {\n      r = 1;\n      return s;\n   }\n\n   Integer t = 0;\n   r         = x;\n   g /= 2;\n   bit_set(s, g);\n   bit_set(t, 2 * g);\n   r = x - t;\n   --g;\n   do\n   {\n      t = s;\n      t <<= g + 1;\n      bit_set(t, 2 * g);\n      if (t <= r)\n      {\n         bit_set(s, g);\n         r -= t;\n      }\n      --g;\n   } while (g >= 0);\n   return s;\n}\n\ntemplate <class Integer>\nBOOST_MP_CXX14_CONSTEXPR Integer sqrt_old(const Integer& x)\n{\n   Integer r(0);\n   return sqrt_old(x, r);\n}\n\ntemplate <class T>\nstd::tuple<std::vector<T>, std::vector<T> >& get_test_vector(unsigned bits)\n{\n   static std::map<unsigned, std::tuple<std::vector<T>, std::vector<T> > > data;\n\n   std::tuple<std::vector<T>, std::vector<T> >& result = data[bits];\n\n   if (std::get<0>(result).size() == 0)\n   {\n      mt19937                     mt;\n      uniform_int_distribution<T> ui(T(1) << (bits - 1), T(1) << bits);\n\n      std::vector<T>& a = std::get<0>(result);\n      std::vector<T>& b = std::get<1>(result);\n\n      for (unsigned i = 0; i < 1000; ++i)\n      {\n         a.push_back(ui(mt));\n         b.push_back(0);\n      }\n   }\n   return result;\n}\n\ntemplate <class T>\nstd::vector<T>& get_test_vector_a(unsigned bits)\n{\n   return std::get<0>(get_test_vector<T>(bits));\n}\ntemplate <class T>\nstd::vector<T>& get_test_vector_b(unsigned bits)\n{\n   return std::get<1>(get_test_vector<T>(bits));\n}\n\ntemplate <typename T>\nstatic void BM_sqrt_old(benchmark::State& state)\n{\n   int                         bits = state.range(0);\n\n   std::vector<T>& a = get_test_vector_a<T>(bits);\n   std::vector<T>& b = get_test_vector_b<T>(bits);\n\n   for (auto _ : state)\n   {\n      for (unsigned i = 0; i < a.size(); ++i)\n         b[i] = sqrt_old(a[i]);\n   }\n   state.SetComplexityN(bits);\n}\n\ntemplate <typename T>\nstatic void BM_sqrt_current(benchmark::State& state)\n{\n   int bits = state.range(0);\n\n   std::vector<T>& a = get_test_vector_a<T>(bits);\n   std::vector<T>& b = get_test_vector_b<T>(bits);\n\n   for (auto _ : state)\n   {\n      for (unsigned i = 0; i < a.size(); ++i)\n         b[i] = sqrt(a[i]);\n   }\n   state.SetComplexityN(bits);\n}\n\nconstexpr unsigned lower_range = 512;\nconstexpr unsigned upper_range = 1 << 15;\n\nBENCHMARK_TEMPLATE(BM_sqrt_old, cpp_int)->RangeMultiplier(2)->Range(lower_range, upper_range)->Unit(benchmark::kMillisecond)->Complexity();\nBENCHMARK_TEMPLATE(BM_sqrt_current, cpp_int)->RangeMultiplier(2)->Range(lower_range, upper_range)->Unit(benchmark::kMillisecond)->Complexity();\nBENCHMARK_TEMPLATE(BM_sqrt_current, mpz_int)->RangeMultiplier(2)->Range(lower_range, upper_range)->Unit(benchmark::kMillisecond)->Complexity();\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "6dd6413ca7ec288fb9ee219248e93f54e37056c3", "size": 3716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/sqrt_bench.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/libs/multiprecision/performance/sqrt_bench.cpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/libs/multiprecision/performance/sqrt_bench.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 25.6275862069, "max_line_length": 143, "alphanum_fraction": 0.6262109795, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.563927043085487}}
{"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": "//! \\file examples/Arrangement_on_surface_2/circular_line_arc.cpp\n// Using the circular line arc traits.\n\n#include <CGAL/Cartesian.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/MP_Float.h>\n#include <CGAL/Algebraic_kernel_for_circles_2_2.h>\n#include <CGAL/intersections.h>\n#include <CGAL/Circular_kernel_2.h>\n#include <CGAL/Arr_circular_line_arc_traits_2.h>\n#include <CGAL/Arrangement_2.h>\n#include <CGAL/Arr_naive_point_location.h>\n#include <boost/variant.hpp>\n\n#include <CGAL/Random.h>\n\n\ntypedef CGAL::Quotient<CGAL::MP_Float>                      NT;\ntypedef CGAL::Cartesian<NT>                                 Linear_k;\ntypedef CGAL::Algebraic_kernel_for_circles_2_2<NT>          Algebraic_k;\ntypedef CGAL::Circular_kernel_2<Linear_k,Algebraic_k>       Circular_k;\n\ntypedef Circular_k::Point_2                                 Point_2;\ntypedef Circular_k::Circle_2                                Circle_2;\ntypedef Circular_k::Circular_arc_2                          Circular_arc_2;\ntypedef Circular_k::Line_arc_2                              Line_arc_2;\n\ntypedef boost::variant< Circular_arc_2, Line_arc_2>         Arc_2;\ntypedef std::vector< Arc_2>                                 ArcContainer;\n\ntypedef CGAL::Arr_circular_line_arc_traits_2<Circular_k>    Traits;\n\ntypedef CGAL::Arrangement_2<Traits>                         Arrangement;\ntypedef CGAL::Arr_naive_point_location<Arrangement>         Point_location;\n\nint main() {\n  CGAL::Random generatorOfgenerator;\n  int random_seed = generatorOfgenerator.get_int(0, 123456);\n  std::cout << \"random_seed = \" << random_seed << std::endl;\n  CGAL::Random theRandom(random_seed);\n  int random_max = 128;\n  int random_min = -128;\n  ArcContainer ac;\n  int x1, y1, x2, y2;\n\n  for (int i = 0; i < 10; i++) {\n    x1 = theRandom.get_int(random_min,random_max);\n    y1 = theRandom.get_int(random_min,random_max);\n    do{\n      x2 = theRandom.get_int(random_min,random_max);\n      y2 = theRandom.get_int(random_min,random_max);\n    } while((x1 == x2) && (y1 == y2));\n\n    std::cout << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << std::endl;\n    boost::variant< Circular_arc_2, Line_arc_2 > v =\n      Line_arc_2(Point_2(x1,y1), Point_2(x2,y2));\n    ac.push_back( v);\n  }\n\n  for (int i = 0; i < 10; i++) {\n    do{\n      x1 = theRandom.get_int(random_min,random_max);\n      y1 = theRandom.get_int(random_min,random_max);\n    }\n    while(x1==0 && y1==0);\n    boost::variant< Circular_arc_2, Line_arc_2 > v =\n      Circle_2( Point_2(x1,y1), x1*x1 + y1*y1);\n    ac.push_back(v);\n  }\n\n  Arrangement arr;\n  Point_location _pl(arr);\n  for (ArcContainer::const_iterator it = ac.begin(); it != ac.end(); ++it) {\n    //insert(arr,_pl,*it);\n    insert(arr, *it, _pl);\n  };\n\n  return 0;\n}\n", "meta": {"hexsha": "1e7854b7482671b86a57047f958fead137de9fce", "size": 2725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Arrangement_on_surface_2/examples/Arrangement_on_surface_2/circular_line_arcs.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": "Arrangement_on_surface_2/examples/Arrangement_on_surface_2/circular_line_arcs.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": "Arrangement_on_surface_2/examples/Arrangement_on_surface_2/circular_line_arcs.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.0625, "max_line_length": 76, "alphanum_fraction": 0.6388990826, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5639214968313453}}
{"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": "//==============================================================================\n//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/combinatorial/include/functions/cnp.hpp>\n\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/functions/splat.hpp>\n\n\nNT2_TEST_CASE_TPL ( cnp_real,  NT2_SIMD_REAL_TYPES)\n{\n  using nt2::cnp;\n  using nt2::tag::cnp_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef native<T,ext_t>                  vT;\n\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(cnp(nt2::Inf<vT>(), nt2::Inf<vT>()), nt2::Nan<vT>(), 0);\n  NT2_TEST_ULP_EQUAL(cnp(nt2::Nan<vT>(), nt2::Nan<vT>()), nt2::Nan<vT>(), 0);\n#endif\n  NT2_TEST_ULP_EQUAL(cnp(nt2::splat<vT>(10),nt2::splat<vT>(1)), nt2::splat<vT>(10), 0);\n  NT2_TEST_ULP_EQUAL(cnp(nt2::splat<vT>(10),nt2::splat<vT>(2)), nt2::splat<vT>(45), 0);\n  NT2_TEST_ULP_EQUAL(cnp(nt2::splat<vT>(10),nt2::splat<vT>(8)), nt2::splat<vT>(45), 0);\n  NT2_TEST_ULP_EQUAL(cnp(nt2::splat<vT>(2),nt2::splat<vT>(1)), nt2::splat<vT>(2), 0);\n  NT2_TEST_ULP_EQUAL(cnp(nt2::splat<vT>(2),nt2::splat<vT>(2)), nt2::splat<vT>(1), 0);\n  NT2_TEST_ULP_EQUAL(cnp(nt2::One<vT>(), nt2::One<vT>()), nt2::One<vT>(), 0);\n  NT2_TEST_ULP_EQUAL(cnp(nt2::Zero<vT>(), nt2::Zero<vT>()), nt2::One<vT>(), 0);\n}\n", "meta": {"hexsha": "a8a06047dd54a2cbdf1d51346b990c7ef1a86a7e", "size": 2087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/combinatorial/unit/simd/cnp.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/combinatorial/unit/simd/cnp.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/combinatorial/unit/simd/cnp.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 43.4791666667, "max_line_length": 87, "alphanum_fraction": 0.6185912793, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.5638776792263798}}
{"text": "/*\n * MultipolyCloser.cpp\n *\n *  Created on: Jan 14, 2016\n *      Author: jcassidy\n */\n\n#include <array>\n#include \"LatLon.h\"\n#include \"MultipolyCloser.hpp\"\n\n#include <boost/range/algorithm.hpp>\n\n#include <boost/math/constants/constants.hpp>\n\nusing namespace std;\n\n\n/// Convenience function for cosine in degrees\nfloat cosd(float theta){ return cos(boost::math::constants::two_pi<float>()/360.0f*theta); }\n\n\ntemplate<std::size_t I>struct CompareTupleElement\n{\n\ttemplate<typename T>static const T& extract(const T& t){ return t; }\n\ttemplate<typename... Types>static const tuple_element<I,tuple<Types...>>& extract(const tuple<Types...>& t){ return get<I>(t); }\n\n\ttemplate<typename T,typename U>bool operator()(const T& lhs,const U& rhs) const\n\t{\n\t\treturn extract(lhs) < extract(rhs);\n\t}\n};\n\n\n/** Computes the distance (metres) from a point to the north/east/south/west bounds (in that order)\n * \t\t@param\t\tp\t\tThe point to compute\n * \t\t@param\t\tbounds\tThe latlon bounds (SW, NE corners)\n */\n\narray<float,4> MultipolyCloser::distanceToBounds(LatLon p) const\n{\n\tfloat cosphi=cosd(p.lat);\n\treturn array<float,4>\n\t{\n\t\tmetresPerDegreeLat*fabs(m_bounds.second.lat - p.lat),\t\t\t// north edge\n\t\tmetresPerDegreeLat*fabs((m_bounds.second.lon - p.lon)*cosphi),\t// east edge\n\t\tmetresPerDegreeLat*fabs(m_bounds.first.lat - p.lat),\t\t\t\t// south edge\n\t\tmetresPerDegreeLat*fabs((m_bounds.first.lon - p.lon)*cosphi)\t\t// west edge\n\t};\n}\n\n\n\n/** Closes the end of a poly to the specified boundary.\n * \t\t@param\t\tp \t\tThe point to close\n * \t\t@param\t\twhich\tThe boundary to close to\n * \t\t@param\t\tbounds\tThe (min,max) bounds\n */\n\nLatLon MultipolyCloser::closeToBoundary(LatLon p,CompassCardinal which) const\n{\n\tswitch(which)\n\t{\n\t\tcase CompassCardinal::N:\treturn(LatLon(m_bounds.second.lat,p.lon));\n\t\tcase CompassCardinal::E: \treturn(LatLon(p.lat,m_bounds.second.lon));\n\t\tcase CompassCardinal::S: \treturn(LatLon(m_bounds.first.lat,p.lon));\n\t\tcase CompassCardinal::W:\treturn(LatLon(p.lat,m_bounds.first.lon));\n\t}\n\n\tthrow std::logic_error(\"closeToBoundary: invalid boundary requested\");\n}\n\n\n\n\n/** Computes the nearest point on the boundary */\n\nMultipolyCloser::EdgePoint MultipolyCloser::nearestPointOnEdge(LatLon p) const\n{\n\tarray<float,4> dToBounds = distanceToBounds(p);\n\tconst auto nearestBound = boost::min_element(dToBounds,CompareTupleElement<0>());\n\n\tCompassCardinal edge(nearestBound-dToBounds.begin());\n\n\tLatLon pBound = closeToBoundary(p,edge);\n\n\tfloat ew=m_bounds.second.lon-m_bounds.first.lon;\n\tfloat ns=m_bounds.second.lat-m_bounds.first.lat;\n\n\tfloat cwd=0;\t\t// clockwise distance around bounds from NW\n\n\tswitch(edge)\n\t{\n\t\tcase CompassCardinal::N: cwd=pBound.lon-m_bounds.first.lon; break;\n\t\tcase CompassCardinal::E: cwd=ew+m_bounds.second.lat-pBound.lat; break;\n\t\tcase CompassCardinal::S: cwd=ew+ns+m_bounds.second.lon-pBound.lon; break;\n\t\tcase CompassCardinal::W: cwd=2*ew+ns+pBound.lat-m_bounds.first.lat; break;\n\t}\n\n\treturn { pBound, *nearestBound, edge, cwd };\n}\n\n\n\nLatLon MultipolyCloser::corner(CompassIntercardinal c) const\n{\n\tswitch(c)\n\t{\n\t\tcase CompassIntercardinal::NE: return m_bounds.second;\n\t\tcase CompassIntercardinal::SE: return LatLon(m_bounds.first.lat,m_bounds.second.lon);\n\t\tcase CompassIntercardinal::SW: return m_bounds.first;\n\t\tcase CompassIntercardinal::NW: return LatLon(m_bounds.second.lat,m_bounds.first.lon);\n\t}\n\n\tthrow std::logic_error(\"corner called with an invalid intercardinal point\");\n}\n\n\n\n/** Returns clockwise \"distance\" (dlat+dlon along bounds) from NW to corner point\n */\n\nfloat MultipolyCloser::cornerCWDistance(CompassIntercardinal c) const\n{\n\tfloat ew=m_bounds.second.lon-m_bounds.first.lon;\n\tfloat ns=m_bounds.second.lat-m_bounds.first.lat;\n\n\tswitch(c)\n\t{\n\tcase CompassIntercardinal::NE: return ew;\n\tcase CompassIntercardinal::SE: return ew+ns;\n\tcase CompassIntercardinal::SW: return 2.0f*ew+ns;\n\tcase CompassIntercardinal::NW: return 0.0f;\n\t}\n\tthrow std::logic_error(\"cornerCWDistance: invalid intercardinal point\");\n}\n\n\n\n/** Returns clockwise \"distance\" (dlat+dlon along bounds) from NW to corner point\n */\n\nfloat cornerCWDistance(CompassPrincipal p,pair<LatLon,LatLon> bounds)\n{\n\tunsigned u = unsigned(p);\n\tif((u%2)!=1)\n\t\tthrow std::logic_error(\"cornerCWDistance: invalid compass principal point\");\n\treturn cornerCWDistance(CompassIntercardinal(u>>1),bounds);\n}\n\n\n\n/** Joins a set of ways end-to-end, and closes to the boundary where they terminate at a boundary.\n * Returns a vector of pair<vector,bool>. The bool indicates if the way way originally closed (ie. did not need bounding points added to close)\n *\n */\n\nMultipolyCloser::MultipolyCloser(const OSMDatabase& db,const vector<const OSMWay*>& ways) :\n\t\tm_db(db),\n\t\tm_ways(ways),\n\t\tm_bounds(db.bounds()),\n\t\tm_wsAdded(ways.size(),false),\n\t\tm_waySegments(ways.size())\n{\n\t////// Extract polygons and form list of endpoints\n\n\tfor(unsigned i=0;i<ways.size();++i)\n\t{\n\t\t// extract the polygons\n\t\tWaySegment& ws = m_waySegments[i] = WaySegment(m_db, m_ways[i], i);\n\n\t\t// insert endpoints into list\n\t\tm_endpoints.push_back(Endpoint { &ws, ws.nodeRefFirst(), true,  i});\n\t\tm_endpoints.push_back(Endpoint { &ws, ws.nodeRefLast(),  false, i});\n\t}\n\n\tmatchEndpointsByNodeID();\n\tcloseEndpointsToBoundary();\n\tcloseAroundBoundary();\n\tbuildLoops();\n}\n\n\nvoid MultipolyCloser::matchEndpointsByNodeID()\n{\n\tm_endpoints.sort(Endpoint::NodeIDOrder());\n\tlist<Endpoint>::iterator l=m_endpoints.begin(),m,u=m_endpoints.begin();\n\n\twhile(l != m_endpoints.end())\n\t{\n\t\t// advance u until it is a different node ID\n\t\tunsigned d;\n\t\tfor(d=1,u++; u != m_endpoints.end() && Endpoint::NodeIDEqual(*u,*l); ++u,++d)\n\t\t\t{}\n\n\t\tif (d > 2)\n\t\t\tcout << \"Not sure what to do where >2 points match!\" << endl;\n\t\telse if (d == 2)\n\t\t{\n\t\t\tm = l;\n\t\t\tm++;\n\t\t\tif (l->waySegment == m->waySegment)\t\t// segment closes itself\n\t\t\t{\n\t\t\t\tl->waySegment->linkSelf();\n\t\t\t\tcout << \"Way \" << l->way << \" closes itself\" << endl;\n\n\t\t\t\tm_endpoints.erase(l,u);\n\t\t\t}\n\t\t\telse\t\t\t\t\t\t// end of way l->way -> start of way m->way\n\t\t\t{\n\t\t\t\t// ordering choice: endpoints before startpoints (==> l is end || both are starts)\n\t\t\t\tassert(!l->isWayFirst || m->isWayFirst);\n\n\t\t\t\tif (!l->isWayFirst && m->isWayFirst)\t\t// normal case: l is an end, m is a start\n\t\t\t\t{\n\t\t\t\t\tcout << \" INFO: Connecting ways \" << setw(3) << l->way << \" and \" << setw(3) << m->way << endl;\n\t\t\t\t\tl->waySegment->append(m->waySegment);\n\t\t\t\t}\n\t\t\t\telse if (l->isWayFirst == m->isWayFirst)\t// abnormal: start-start or end-end connection\n\t\t\t\t{\n\t\t\t\t\t// l startpoint ==> m startpoint due to ordering choice (endpoints order before startpoints)\n\n\t\t\t\t\tcout << \"  WARNING: Orientation change between ways \" << setw(3) << l->way << \" and \" << setw(3) << m->way;\n\t\t\t\t\tif (l->isWayFirst)\n\t\t\t\t\t\tcout << \" (start->start connection)\" << endl;\n\t\t\t\t\telse\n\t\t\t\t\t\tcout << \" (  end->end   connection)\" << endl;\n\n\t\t\t\t\t// each must have space to link at either next or prev\n\t\t\t\t\tassert(!l->waySegment->hasNext() || !l->waySegment->hasPrev());\n\t\t\t\t\tassert(!m->waySegment->hasNext() || !m->waySegment->hasPrev());\n\n\t\t\t\t\tif (l->isWayFirst)\n\t\t\t\t\t{\n\t\t\t\t\t\tl->waySegment->reverse(true);\n\t\t\t\t\t\tl->waySegment->append(m->waySegment);\n\t\t\t\t\t\tcout << \"         : Reversing way \" << setw(3) << l->way << endl;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tm->waySegment->reverse(true);\n\t\t\t\t\t\tl->waySegment->prepend(m->waySegment);\n\t\t\t\t\t\tcout << \"         : Reversing way \" << setw(3) << m->way << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tassert(false);\t// impossible case\n\n\t\t\t\tm_endpoints.erase(l,u);\n\t\t\t}\n\t\t}\n\t\telse if (d == 1)\n\t\t\tcout << \"Segment terminal \" << l->way << \" \" << (l->isWayFirst ? \"start\":\"end\") << \"  is lonely\" << endl;\n\n\t\tl=u;\t\t\t// u is past-the-end, so points to next endpoint\n\t}\n}\n\nvoid MultipolyCloser::closeEndpointsToBoundary()\n{\n\t////// Map unresolved terminals (points where segments start/end at boundary)\n\tif(m_endpoints.size())\n\t\tcout << \"Unresolved terminals with bounds \" << m_bounds.first.lat << ',' << m_bounds.first.lon << \"  \" << m_bounds.second.lat << ',' << m_bounds.second.lon << \": \" << endl;\n\telse\n\t\tcout << \"All terminals resolved\" << endl;\n\n\tfor(auto it = m_endpoints.begin(); it != m_endpoints.end();)\n\t{\n\t\tassert(it->way != -1U);\n\t\tassert(m_ways[it->way]);\n\n\t\tLatLon p = it->pos();\n\t\tauto res = nearestPointOnEdge(p);\n\n\t\t// create new boundary point at edge\n\t\tBoundaryPointSegment bps(res.edge,res.p,res.edgeDistance,res.cwDistance,it->isWayFirst);\n\n\t\tLatLon pEdge = bps.first();\n\n\t\tcout << \"  Segment \" << setw(3) << it->way << \" \" << (it->isWayFirst ? \"starts\":\"ends  \") << \" at \" << p.lat << ',' << p.lon << endl;\n\t\tcout << \"    Boundary point \" << pEdge.lat << \",\" << pEdge.lon << \" (\" << bps.m_edgeDistance << \"m from \" << bps.m_location << \")\" << endl;\n\n\t\tif (bps.m_edgeDistance < m_maxBoundaryDistance)\n\t\t{\n\t\t\tauto newIt = m_boundpoints.insert(m_boundpoints.begin(),bps);\n\t\t\tif (it->isWayFirst)\n\t\t\t\tnewIt->append(it->waySegment);\n\t\t\telse\n\t\t\t\tnewIt->prepend(it->waySegment);\n\n\t\t\tm_endpoints.erase(it++);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcout << \"WARNING: Distance too far to edge (maxBoundaryDistance=\" << m_maxBoundaryDistance << \")\" << endl;\n\t\t\tit++;\n\t\t}\n\t}\n}\n\nvoid MultipolyCloser::closeAroundBoundary()\n{\n\t// sort boundary points in clockwise order\n\tm_boundpoints.sort(BoundaryPointSegment::OrientedOrder(m_dir));\n\n\t// insert corner points as needed\n\tint delta = m_dir == CW ? 2 : -2;\n\tint edgeToCorner = m_dir == CW ? 1 : -1;\t\t// value to add to edge to get the corner after the edge\n\tCompassPrincipal currentCorner(CompassPrincipal::NW);\n\n\tlist<BoundaryPointSegment>::iterator it=m_boundpoints.begin();\n\n\t// put the NW corner in\n\tm_boundpoints.insert(it,BoundaryPointSegment(currentCorner,corner(currentCorner),cornerCWDistance(currentCorner)));\n\tcurrentCorner=currentCorner+delta;\n\n\twhile(it != m_boundpoints.end() || currentCorner != CompassPrincipal::NW)\n\t{\n\t\tif (it == m_boundpoints.end())\n\t\t\tcout << \"Done with boundary points, currently at \" << currentCorner << \" corner\" << endl;\n\t\telse\n\t\t\tcout << \"Boundary point is on \" << it->m_location << \" edge, looking at \" << currentCorner << \" corner\" << endl;\n\n\t\tfor(; currentCorner != CompassPrincipal::NW && (it == m_boundpoints.end() || (it->m_location+edgeToCorner != currentCorner)); currentCorner=currentCorner+delta)\n\t\t{\n\t\t\tm_boundpoints.insert(it,BoundaryPointSegment(currentCorner,corner(currentCorner),cornerCWDistance(currentCorner)));\n\t\t}\n\n\t\tif (it != m_boundpoints.end())\n\t\t{\n\t\t\t++it;\n\t\t\tif (it != m_boundpoints.end())\n\t\t\t\tcout << \"Moving to point on \" << it->m_location << \" edge\" << endl;\n\t\t}\n\t}\n\n\tcout << \"Boundary points: \" << endl;\n\tfor(const auto bp : m_boundpoints)\n\t\tcout << bp << endl;\n\n\t// advance to the first endpoint\n\tSegment* last=nullptr;\n\tfor(it = m_boundpoints.begin(); it != m_boundpoints.end() && !it->isEnd(); ++it){}\n\n\t// make connections around edge\n\tfor(; it != m_boundpoints.end(); ++it)\n\t{\n\t\tif (it->isStart())\n\t\t{\n\t\t\tif (last)\t\t\t\t\t// hit start of segment -> prepend last segment to it\n\t\t\t{\n\t\t\t\tcout << \"INFO: Prepending to \" << *it << endl;\n\t\t\t\tif (!it->prepend(last))\n\t\t\t\t\tcout << \"ERROR: Failed to prepend!\" << endl;\n\t\t\t\tlast=nullptr;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcout << \"WARNING: Found a segment start but no curve currently being processed (incorrect orientation?)\" << endl;\n\t\t\t\tcout << \"       : \" << *it << endl;\n\t\t\t}\n\t\t}\n\t\telse if (it->isEnd())\n\t\t{\n\t\t\tif (last)\n\t\t\t{\n\t\t\t\tcout << \"WARNING: Found a segment end while traversing boundary, but there is already a segment being processed\" << endl;\n\t\t\t\tcout << \"       : \" << *it << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcout << \"INFO: Picked up new endpoint \" << *it << endl;\n\t\t\t\tlast=&(*it);\n\t\t\t}\n\t\t}\n\t\telse if (last)\n\t\t{\n\t\t\tcout << \"INFO: Traversing boundary point \" << *it << \" and appending\" << endl;\n\t\t\tif (last->append(&(*it)))\n\t\t\t\tlast = &(*it);\n\t\t\telse\n\t\t\t\tcout << \"ERROR: Failed to add!\" << endl;\n\t\t}\n\t\telse\n\t\t\tcout << \"INFO: Skipping corner point \" << *it << endl;\n\t}\n\n\tcout << \"Continuing through north to get last startpoints\" << endl;\n\n\t// finish off last few connections (must be startpoints or would have been)\n\tfor(it = m_boundpoints.begin(); it != m_boundpoints.end() && !it->isEnd(); ++it)\n\t{\n\t\tif (it->isStart())\n\t\t{\n\t\t\tif (last)\t\t\t\t\t// hit start of segment -> prepend last segment to it\n\t\t\t{\n\t\t\t\tcout << \"INFO: Prepending to \" << *it << endl;\n\t\t\t\tif (!it->prepend(last))\n\t\t\t\t\tcout << \"ERROR: Failed to prepend!\" << endl;\n\t\t\t\tlast=nullptr;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcout << \"WARNING: Found a segment start but no curve currently being processed (incorrect orientation?)\" << endl;\n\t\t\t\tcout << \"       : \" << *it << endl;\n\t\t\t}\n\t\t}\n\t\telse if (last)\n\t\t{\n\t\t\tcout << \"INFO: Traversing boundary point \" << *it << \" and appending\" << endl;\n\t\t\tif (last->append(&(*it)))\n\t\t\t\tlast = &(*it);\n\t\t\telse\n\t\t\t\tcout << \"ERROR: Failed to add!\" << endl;\n\t\t}\n\t\telse\n\t\t\tcout << \"INFO: Skipping corner point \" << *it << endl;\n\t}\n}\n\nvoid MultipolyCloser::buildLoops()\n{\n\tm_loops.clear();\n\tm_wsAdded.clear();\n\tm_wsAdded.resize(m_waySegments.size(),false);\n\n\t// build loop entries serially\n\tcout << \"Building loop indices\" << endl;\n\tfor(unsigned i=0;i<m_waySegments.size();++i)\n\t{\n\t\tif (m_wsAdded.at(i))\n\t\t\tcontinue;\n\n\t\tcout << \"checking segment \" << i << endl;\n\n\t\tif (m_waySegments[i].isMemberOfClosedLoop())\n\t\t{\n\t\t\tfor(const Segment* s=&m_waySegments[i]; s != nullptr; s=s->nextEndingAt(&m_waySegments[i]))\n\t\t\t{\n\t\t\t\tif (const WaySegment* ws = dynamic_cast<const WaySegment*>(s))\n\t\t\t\t{\n\t\t\t\t\tif (m_wsAdded.at(ws->index()))\n\t\t\t\t\t\tcout << \"WARNING: Way segment \" << ws->index() << \" multiple inclusion\" << endl;\n\t\t\t\t\tm_wsAdded[ws->index()] = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tm_loops.push_back(&m_waySegments[i]);\n\t\t}\n\t\telse\n\t\t\tcout << \"WARNING: Segment \" << i << \" is not part of a closed loop\" << endl;\n\t}\n}\n\nvector<pair<vector<LatLon>,bool>> MultipolyCloser::loops(Boundedness b) const\n{\n\tcout << \" Constructing return loops\" << endl;\n\n\tvector<pair<vector<LatLon>,bool>> o;\n\tvector<LatLon> loop;\n\tbool bounded;\n\n\tfor(const Segment* l : m_loops)\n\t{\n\t\tloop.clear();\n\t\tbounded=true;\n\t\tfor(const Segment* s=l; s != nullptr; s=s->nextEndingAt(l))\n\t\t{\n\t\t\ts->add(loop);\n\t\t\tif (dynamic_cast<const BoundaryPointSegment*>(s))\n\t\t\t\tbounded=false;\n\t\t}\n\t\tif (b == All || (b==Unbounded && !bounded) || (b==Bounded && bounded) )\n\t\t\to.emplace_back(std::move(loop),bounded);\n\t}\n\treturn o;\n}\n\n\n", "meta": {"hexsha": "7ab161cfdbb50df4ba6e9c04ece2860fe005cdb3", "size": 14123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MultipolyCloser.cpp", "max_stars_repo_name": "jeffreycassidy/osm2bin", "max_stars_repo_head_hexsha": "7a6751d1a5045d8fb260aaa723ae85da193b4c93", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-10-31T01:33:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T08:04:51.000Z", "max_issues_repo_path": "MultipolyCloser.cpp", "max_issues_repo_name": "jeffreycassidy/osm2bin", "max_issues_repo_head_hexsha": "7a6751d1a5045d8fb260aaa723ae85da193b4c93", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MultipolyCloser.cpp", "max_forks_repo_name": "jeffreycassidy/osm2bin", "max_forks_repo_head_hexsha": "7a6751d1a5045d8fb260aaa723ae85da193b4c93", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-06-14T05:05:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-11T05:56:39.000Z", "avg_line_length": 29.48434238, "max_line_length": 174, "alphanum_fraction": 0.6531898322, "num_tokens": 4019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5638434605090249}}
{"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": "#include <cfloat>\n#include <boost/format.hpp>\n#include \"Utils.h\"\n\nbool build_even_motion_relative_time_samples(float           i_relative_shutter_open,\n\t\tfloat           i_relative_shutter_close,\n\t\tAlembic::Abc::uint8_t          i_motion_sample_count,\n\t\tFloatContainer& o_earlier_sampling_time_vector,\n\t\tFloatContainer& o_later_sampling_time_vector)\n{\n\tif (i_motion_sample_count<2)\n\t\treturn false;\n\tfloat shutter_delta = (i_relative_shutter_close - i_relative_shutter_open)/(i_motion_sample_count-1);\n\tif (shutter_delta < FLT_EPSILON)\n\t\treturn false;\n\to_earlier_sampling_time_vector.clear();\n\to_later_sampling_time_vector.clear();\n\tfor (Alembic::Abc::uint8_t sample_index=0;sample_index<i_motion_sample_count;sample_index++)\n\t{\n\t\tfloat time_sample  = i_relative_shutter_open + sample_index * shutter_delta;\n\t\tstd::cout << boost::format(\"time_sample = %1%\") % time_sample << std::endl;\n\t\tif (time_sample>=0.0f)\n\t\t\to_later_sampling_time_vector.push_back(time_sample);\n\t\telse\n\t\t\to_earlier_sampling_time_vector.push_back(time_sample);\n\t}\n\treturn true;\n\n}\n\n// == Emacs ================\n// -------------------------\n// Local variables:\n// tab-width: 4\n// indent-tabs-mode: t\n// c-basic-offset: 4\n// end:\n//\n// == vi ===================\n// -------------------------\n// Format block\n// ex:ts=4:sw=4:expandtab\n// -------------------------\n", "meta": {"hexsha": "c2d6f7e084ba38403cdc12069eea694724948910", "size": 1330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dev/abc2ass_separate_schema/Utils.cpp", "max_stars_repo_name": "nyue/SegmentedInterpolativeMotionBlurAlembic", "max_stars_repo_head_hexsha": "1f02ff5516b6e114410b5977885133bb4b5bb490", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-28T23:33:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-28T23:33:00.000Z", "max_issues_repo_path": "dev/abc2ass_separate_schema/Utils.cpp", "max_issues_repo_name": "nyue/SegmentedInterpolativeMotionBlurAlembic", "max_issues_repo_head_hexsha": "1f02ff5516b6e114410b5977885133bb4b5bb490", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dev/abc2ass_separate_schema/Utils.cpp", "max_forks_repo_name": "nyue/SegmentedInterpolativeMotionBlurAlembic", "max_forks_repo_head_hexsha": "1f02ff5516b6e114410b5977885133bb4b5bb490", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-10T11:49:02.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-10T11:49:02.000Z", "avg_line_length": 30.2272727273, "max_line_length": 102, "alphanum_fraction": 0.6804511278, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.563704889170085}}
{"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": "/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */\n\n#include \"dsp/MathUtilities.h\"\n\n#include <cmath>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(TestMathUtilities)\n\nBOOST_AUTO_TEST_CASE(round)\n{\n    BOOST_CHECK_EQUAL(MathUtilities::round(0.5), 1.0);\n    BOOST_CHECK_EQUAL(MathUtilities::round(0.49), 0.0);\n    BOOST_CHECK_EQUAL(MathUtilities::round(0.99), 1.0);\n    BOOST_CHECK_EQUAL(MathUtilities::round(0.01), 0.0);\n    BOOST_CHECK_EQUAL(MathUtilities::round(0.0), 0.0);\n    BOOST_CHECK_EQUAL(MathUtilities::round(100.0), 100.0);\n    BOOST_CHECK_EQUAL(MathUtilities::round(-0.2), 0.0);\n    BOOST_CHECK_EQUAL(MathUtilities::round(-0.5), -1.0);\n    BOOST_CHECK_EQUAL(MathUtilities::round(-0.99), -1.0);\n    BOOST_CHECK_EQUAL(MathUtilities::round(-1.0), -1.0);\n    BOOST_CHECK_EQUAL(MathUtilities::round(-1.1), -1.0);\n    BOOST_CHECK_EQUAL(MathUtilities::round(-1.5), -2.0);\n}\n\nBOOST_AUTO_TEST_CASE(mean)\n{\n    BOOST_CHECK_EQUAL(MathUtilities::mean(0, 0), 0);\n    double d0[] = { 0, 4, 3, -1 };\n    BOOST_CHECK_EQUAL(MathUtilities::mean(d0, 4), 1.5);\n    double d1[] = { -2.6 };\n    BOOST_CHECK_EQUAL(MathUtilities::mean(d1, 1), -2.6);\n    std::vector<double> v;\n    v.push_back(0);\n    v.push_back(4);\n    v.push_back(3);\n    v.push_back(-1);\n    BOOST_CHECK_EQUAL(MathUtilities::mean(v, 0, 4), 1.5);\n    BOOST_CHECK_EQUAL(MathUtilities::mean(v, 1, 2), 3.5);\n    BOOST_CHECK_EQUAL(MathUtilities::mean(v, 3, 1), -1);\n    BOOST_CHECK_EQUAL(MathUtilities::mean(v, 3, 0), 0);\n}\n\nBOOST_AUTO_TEST_CASE(sum)\n{\n    BOOST_CHECK_EQUAL(MathUtilities::sum(0, 0), 0);\n    double d0[] = { 0, 4, 3, -1 };\n    BOOST_CHECK_EQUAL(MathUtilities::sum(d0, 4), 6);\n    double d1[] = { -2.6 };\n    BOOST_CHECK_EQUAL(MathUtilities::sum(d1, 1), -2.6);\n}\n\nBOOST_AUTO_TEST_CASE(median)\n{\n    BOOST_CHECK_EQUAL(MathUtilities::median(0, 0), 0);\n    double d0[] = { 0, 4, 3, -1 };\n    BOOST_CHECK_EQUAL(MathUtilities::median(d0, 4), 1.5);\n    double d1[] = { 0, 4, 3, -1, -1 };\n    BOOST_CHECK_EQUAL(MathUtilities::median(d1, 5), 0);\n    double d2[] = { 1.0, -2.0 };\n    BOOST_CHECK_EQUAL(MathUtilities::median(d2, 2), -0.5);\n    double d3[] = { -2.6 };\n    BOOST_CHECK_EQUAL(MathUtilities::median(d3, 1), -2.6);\n}\n\nBOOST_AUTO_TEST_CASE(princarg)\n{\n    BOOST_CHECK_EQUAL(MathUtilities::princarg(M_PI), M_PI);\n    BOOST_CHECK_EQUAL(MathUtilities::princarg(-M_PI), M_PI);\n    BOOST_CHECK_EQUAL(MathUtilities::princarg(2 * M_PI), 0.0);\n    BOOST_CHECK_EQUAL(MathUtilities::princarg(5 * M_PI), M_PI);\n    BOOST_CHECK_EQUAL(MathUtilities::princarg(1.0), 1.0);\n    BOOST_CHECK_EQUAL(MathUtilities::princarg(-1.0), -1.0);\n    BOOST_CHECK_EQUAL(MathUtilities::princarg(-10.0), -10.0 + 4 * M_PI);\n}\n\nBOOST_AUTO_TEST_CASE(isPowerOfTwo)\n{\n    BOOST_CHECK_EQUAL(MathUtilities::isPowerOfTwo(0), false);\n    BOOST_CHECK_EQUAL(MathUtilities::isPowerOfTwo(1), true);\n    BOOST_CHECK_EQUAL(MathUtilities::isPowerOfTwo(-2), false);\n    BOOST_CHECK_EQUAL(MathUtilities::isPowerOfTwo(2), true);\n    BOOST_CHECK_EQUAL(MathUtilities::isPowerOfTwo(3), false);\n    BOOST_CHECK_EQUAL(MathUtilities::isPowerOfTwo(12), false);\n    BOOST_CHECK_EQUAL(MathUtilities::isPowerOfTwo(16), true);\n}\n\nBOOST_AUTO_TEST_CASE(nextPowerOfTwo)\n{\n    BOOST_CHECK_EQUAL(MathUtilities::nextPowerOfTwo(0), 1);\n    BOOST_CHECK_EQUAL(MathUtilities::nextPowerOfTwo(1), 1);\n    BOOST_CHECK_EQUAL(MathUtilities::nextPowerOfTwo(-2), 1);\n    BOOST_CHECK_EQUAL(MathUtilities::nextPowerOfTwo(2), 2);\n    BOOST_CHECK_EQUAL(MathUtilities::nextPowerOfTwo(3), 4);\n    BOOST_CHECK_EQUAL(MathUtilities::nextPowerOfTwo(12), 16);\n    BOOST_CHECK_EQUAL(MathUtilities::nextPowerOfTwo(16), 16);\n}\n\nBOOST_AUTO_TEST_CASE(previousPowerOfTwo)\n{\n    BOOST_CHECK_EQUAL(MathUtilities::previousPowerOfTwo(0), 1);\n    BOOST_CHECK_EQUAL(MathUtilities::previousPowerOfTwo(1), 1);\n    BOOST_CHECK_EQUAL(MathUtilities::previousPowerOfTwo(-2), 1);\n    BOOST_CHECK_EQUAL(MathUtilities::previousPowerOfTwo(2), 2);\n    BOOST_CHECK_EQUAL(MathUtilities::previousPowerOfTwo(3), 2);\n    BOOST_CHECK_EQUAL(MathUtilities::previousPowerOfTwo(12), 8);\n    BOOST_CHECK_EQUAL(MathUtilities::previousPowerOfTwo(16), 16);\n}\n\nBOOST_AUTO_TEST_CASE(nearestPowerOfTwo)\n{\n    BOOST_CHECK_EQUAL(MathUtilities::nearestPowerOfTwo(0), 1);\n    BOOST_CHECK_EQUAL(MathUtilities::nearestPowerOfTwo(1), 1);\n    BOOST_CHECK_EQUAL(MathUtilities::nearestPowerOfTwo(-2), 1);\n    BOOST_CHECK_EQUAL(MathUtilities::nearestPowerOfTwo(2), 2);\n    BOOST_CHECK_EQUAL(MathUtilities::nearestPowerOfTwo(3), 4);\n    BOOST_CHECK_EQUAL(MathUtilities::nearestPowerOfTwo(11), 8);\n    BOOST_CHECK_EQUAL(MathUtilities::nearestPowerOfTwo(12), 16);\n    BOOST_CHECK_EQUAL(MathUtilities::nearestPowerOfTwo(16), 16);\n}\n\nBOOST_AUTO_TEST_CASE(factorial)\n{\n    BOOST_CHECK_EQUAL(MathUtilities::factorial(-10), 0.0);\n    BOOST_CHECK_EQUAL(MathUtilities::factorial(0), 1.0);\n    BOOST_CHECK_EQUAL(MathUtilities::factorial(1), 1.0);\n    BOOST_CHECK_EQUAL(MathUtilities::factorial(2), 2.0);\n    BOOST_CHECK_EQUAL(MathUtilities::factorial(3), 6.0);\n    BOOST_CHECK_EQUAL(MathUtilities::factorial(4), 24.0);\n\n    // Too big for an int, hence double return value from factorial\n    BOOST_CHECK_EQUAL(MathUtilities::factorial(20), 2432902008176640000.0);\n}\n\nBOOST_AUTO_TEST_CASE(gcd)\n{\n    BOOST_CHECK_EQUAL(MathUtilities::gcd(1, 1), 1);\n    BOOST_CHECK_EQUAL(MathUtilities::gcd(2, 1), 1);\n    BOOST_CHECK_EQUAL(MathUtilities::gcd(2, 3), 1);\n    BOOST_CHECK_EQUAL(MathUtilities::gcd(4, 2), 2);\n    BOOST_CHECK_EQUAL(MathUtilities::gcd(18, 24), 6);\n    BOOST_CHECK_EQUAL(MathUtilities::gcd(27, 18), 9);\n    BOOST_CHECK_EQUAL(MathUtilities::gcd(18, 36), 18);\n    BOOST_CHECK_EQUAL(MathUtilities::gcd(37, 18), 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n", "meta": {"hexsha": "4a2ceff792349f13ebe683279dbde3f5c2c023c5", "size": 5765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/TestMathUtilities.cpp", "max_stars_repo_name": "cannam/constant-q-cpp", "max_stars_repo_head_hexsha": "7ac84048e3e43c433d88e12d221af15e50f41591", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2016-02-03T16:12:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T08:27:55.000Z", "max_issues_repo_path": "test/TestMathUtilities.cpp", "max_issues_repo_name": "cannam/constant-q-cpp", "max_issues_repo_head_hexsha": "7ac84048e3e43c433d88e12d221af15e50f41591", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-01-10T01:12:30.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-28T09:34:42.000Z", "max_forks_repo_path": "test/TestMathUtilities.cpp", "max_forks_repo_name": "cannam/constant-q-cpp", "max_forks_repo_head_hexsha": "7ac84048e3e43c433d88e12d221af15e50f41591", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T21:50:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T08:27:56.000Z", "avg_line_length": 37.4350649351, "max_line_length": 78, "alphanum_fraction": 0.7172593235, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5637048796084936}}
{"text": "#include <boost/ut.hpp>\n#include <random>\n#include <scistats/bayesian/bootstrap.h>\n#include <scistats/bayesian/theorem.h>\n#include <scistats/descriptive/mean.h>\n#include <vector>\n\nint main() {\n    using namespace boost::ut;\n    using namespace scistats;\n\n    test(\"Bayes Theorem\") = [&] {\n        // Bayes theorem\n        double p_hypothesis = 0.2;\n        double likelihood = 0.8;\n        double p_evidence = 0.6;\n        expect(bayes_theorem(likelihood, p_hypothesis, p_evidence) == 0.26_d);\n    };\n\n    test(\"Bootstrap\") = [&] {\n        int i = 0;\n        auto generate_i_values = [&]() { return i++; };\n\n        auto v = bootstrap(generate_i_values, 1000);\n        expect(sum(v) == 499500_i);\n    };\n\n    return 0;\n}\n", "meta": {"hexsha": "63b5eec34362f8d1d8979be97d08b177672d1f93", "size": 721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit_tests/ut_bayesian.cpp", "max_stars_repo_name": "alandefreitas/scistats", "max_stars_repo_head_hexsha": "6f20e47b5a8d6f82aa56991889395f12955e5384", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-28T21:47:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T22:39:05.000Z", "max_issues_repo_path": "tests/unit_tests/ut_bayesian.cpp", "max_issues_repo_name": "alandefreitas/scistats", "max_issues_repo_head_hexsha": "6f20e47b5a8d6f82aa56991889395f12955e5384", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/unit_tests/ut_bayesian.cpp", "max_forks_repo_name": "alandefreitas/scistats", "max_forks_repo_head_hexsha": "6f20e47b5a8d6f82aa56991889395f12955e5384", "max_forks_repo_licenses": ["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.0333333333, "max_line_length": 78, "alphanum_fraction": 0.6019417476, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.7154239957834734, "lm_q1q2_score": 0.5637048772638985}}
{"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//\u8f6c\u6362\u6210\u4e8c\u8fdb\u5236\u4e32\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//\u8fd9\u91cc\u7528XOR\u53ef\u4ee5\u4ee3\u66ffOR\uff0c\u56e0\u4e3a\u8fd0\u7b97\u8868\u8fbe\u5f0f\u51b3\u5b9a\u4e86\u4e24\u4e2a\u52a0\u6570\u4e0d\u53ef\u80fd\u540c\u65f6\u4e3a1\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": "// Copyright (c) 2018-2021 FRC Team 3512. All Rights Reserved.\n\n#include \"controllers/DrivetrainController.hpp\"\n\n#include <algorithm>\n#include <cmath>\n\n#include <Eigen/QR>\n#include <frc/RobotController.h>\n#include <frc/controller/LinearQuadraticRegulator.h>\n#include <frc/geometry/Pose2d.h>\n#include <frc/system/NumericalJacobian.h>\n#include <frc/system/plant/DCMotor.h>\n#include <frc/system/plant/LinearSystemId.h>\n#include <frc/trajectory/TrajectoryGenerator.h>\n#include <frc/trajectory/constraint/DifferentialDriveVelocitySystemConstraint.h>\n#include <wpi/MathExtras.h>\n\nusing namespace frc3512;\nusing namespace frc3512::Constants;\nusing namespace frc3512::Constants::Drivetrain;\n\nfrc::LinearSystem<2, 2, 2> DrivetrainController::m_plant =\n    frc::LinearSystemId::IdentifyDrivetrainSystem(\n        Constants::Drivetrain::kLinearV, Constants::Drivetrain::kLinearA,\n        Constants::Drivetrain::kAngularV, Constants::Drivetrain::kAngularA);\n\nDrivetrainController::DrivetrainController(const std::array<double, 5>& Qelems,\n                                           const std::array<double, 2>& Relems,\n                                           units::second_t dt) {\n    m_localY.setZero();\n    m_globalY.setZero();\n    Reset();\n\n    Eigen::Matrix<double, 10, 1> x0;\n    x0.setZero();\n    x0(State::kLeftVelocity, 0) = 1e-9;\n    x0(State::kRightVelocity, 0) = 1e-9;\n    Eigen::Matrix<double, 10, 1> x1;\n    x1.setZero();\n    x1(State::kLeftVelocity, 0) = 1;\n    x1(State::kRightVelocity, 0) = 1;\n    Eigen::Matrix<double, 2, 1> u0;\n    u0.setZero();\n\n    Eigen::Matrix<double, 5, 5> A0 =\n        frc::NumericalJacobianX<10, 10, 2>(Dynamics, x0, u0).block<5, 5>(0, 0);\n    Eigen::Matrix<double, 5, 5> A1 =\n        frc::NumericalJacobianX<10, 10, 2>(Dynamics, x1, u0).block<5, 5>(0, 0);\n    m_B =\n        frc::NumericalJacobianU<10, 10, 2>(Dynamics, x0, u0).block<5, 2>(0, 0);\n\n    m_K0 = frc::LinearQuadraticRegulator<5, 2>(A0, m_B, Qelems, Relems, dt).K();\n    m_K1 = frc::LinearQuadraticRegulator<5, 2>(A1, m_B, Qelems, Relems, dt).K();\n}\n\nvoid DrivetrainController::Enable() { m_isEnabled = true; }\n\nvoid DrivetrainController::Disable() { m_isEnabled = false; }\n\nbool DrivetrainController::IsEnabled() const { return m_isEnabled; }\n\nvoid DrivetrainController::SetWaypoints(\n    const std::vector<frc::Pose2d>& waypoints) {\n    frc::DifferentialDriveKinematics kinematics{kWidth};\n    frc::DifferentialDriveVelocitySystemConstraint constraint{m_plant,\n                                                              kinematics, 8_V};\n    frc::TrajectoryConfig config{kMaxV, kMaxA};\n    config.AddConstraint(constraint);\n\n    std::lock_guard lock(m_trajectoryMutex);\n    m_goal = waypoints.back();\n    m_trajectory =\n        frc::TrajectoryGenerator::GenerateTrajectory(waypoints, config);\n}\n\nbool DrivetrainController::AtGoal() const {\n    frc::Pose2d ref{units::meter_t{m_r(State::kX, 0)},\n                    units::meter_t{m_r(State::kY, 0)},\n                    units::radian_t{m_r(State::kHeading, 0)}};\n    return m_goal == ref && m_atReferences;\n}\n\nvoid DrivetrainController::SetMeasuredLocalOutputs(\n    units::radian_t heading, units::meter_t leftPosition,\n    units::meter_t rightPosition) {\n    m_localY << heading.to<double>(), leftPosition.to<double>(),\n        rightPosition.to<double>();\n}\n\nvoid DrivetrainController::SetMeasuredGlobalOutputs(\n    units::meter_t x, units::meter_t y, units::radian_t heading,\n    units::meter_t leftPosition, units::meter_t rightPosition,\n    units::radians_per_second_t angularVelocity) {\n    m_globalY << x.to<double>(), y.to<double>(), heading.to<double>(),\n        leftPosition.to<double>(), rightPosition.to<double>(),\n        angularVelocity.to<double>();\n}\n\nfrc::LinearSystem<2, 2, 2> DrivetrainController::GetPlant() const {\n    return m_plant;\n}\n\nconst Eigen::Matrix<double, 5, 1>& DrivetrainController::GetReferences() const {\n    return m_nextR;\n}\n\nconst Eigen::Matrix<double, 10, 1>& DrivetrainController::GetStates() const {\n    return m_observer.Xhat();\n}\n\nEigen::Matrix<double, 2, 1> DrivetrainController::GetInputs() const {\n    return m_cappedU;\n}\n\nconst Eigen::Matrix<double, 3, 1>& DrivetrainController::GetOutputs() const {\n    return m_localY;\n}\n\nEigen::Matrix<double, 3, 1> DrivetrainController::EstimatedLocalOutputs()\n    const {\n    return LocalMeasurementModel(m_observer.Xhat(),\n                                 Eigen::Matrix<double, 2, 1>::Zero());\n}\n\nEigen::Matrix<double, 6, 1> DrivetrainController::EstimatedGlobalOutputs()\n    const {\n    return GlobalMeasurementModel(m_observer.Xhat(),\n                                  Eigen::Matrix<double, 2, 1>::Zero());\n}\n\nvoid DrivetrainController::Update(units::second_t dt,\n                                  units::second_t elapsedTime) {\n    frc::Trajectory::State ref;\n    {\n        std::lock_guard lock(m_trajectoryMutex);\n        ref = m_trajectory.Sample(elapsedTime);\n    }\n\n    auto [vlRef, vrRef] =\n        ToWheelVelocities(ref.velocity, ref.curvature, kWidth);\n\n    positionLogger.Log(elapsedTime, m_observer.Xhat(State::kX),\n                       m_observer.Xhat(State::kY),\n                       ref.pose.Translation().X().to<double>(),\n                       ref.pose.Translation().Y().to<double>(),\n                       m_localY(LocalOutput::kLeftPosition, 0),\n                       m_localY(LocalOutput::kRightPosition, 0),\n                       m_observer.Xhat(State::kLeftPosition),\n                       m_observer.Xhat(State::kRightPosition),\n                       m_odometer.GetPose().Translation().X().to<double>(),\n                       m_odometer.GetPose().Translation().Y().to<double>());\n\n    angleLogger.Log(elapsedTime, m_localY(LocalOutput::kHeading),\n                    m_observer.Xhat(State::kHeading),\n                    ref.pose.Rotation().Radians().to<double>(),\n                    m_observer.Xhat(State::kAngularVelocityError));\n    velocityLogger.Log(elapsedTime, m_observer.Xhat(State::kLeftVelocity),\n                       m_observer.Xhat(State::kRightVelocity),\n                       m_nextR(State::kLeftVelocity, 0),\n                       m_nextR(State::kRightVelocity, 0), vlRef.to<double>(),\n                       vrRef.to<double>());\n    voltageLogger.Log(elapsedTime, m_cappedU(Input::kLeftVoltage, 0),\n                      m_cappedU(Input::kRightVoltage, 0),\n                      m_observer.Xhat(State::kLeftVoltageError),\n                      m_observer.Xhat(State::kRightVoltageError),\n                      frc::RobotController::GetInputVoltage());\n    errorCovLogger.Log(\n        elapsedTime, m_observer.P(State::kX, State::kX),\n        m_observer.P(State::kY, State::kY),\n        m_observer.P(State::kHeading, State::kHeading),\n        m_observer.P(State::kLeftVelocity, State::kLeftVelocity),\n        m_observer.P(State::kRightVelocity, State::kRightVelocity),\n        m_observer.P(State::kLeftPosition, State::kLeftPosition),\n        m_observer.P(State::kRightPosition, State::kRightPosition),\n        m_observer.P(State::kLeftVoltageError, State::kLeftVoltageError),\n        m_observer.P(State::kRightVoltageError, State::kRightVoltageError),\n        m_observer.P(State::kAngularVelocityError,\n                     State::kAngularVelocityError));\n\n    m_odometer.Update(units::radian_t{m_localY(LocalOutput::kHeading)},\n                      units::meter_t{m_localY(LocalOutput::kLeftPosition)},\n                      units::meter_t{m_localY(LocalOutput::kRightPosition)});\n    m_observer.Correct(m_cappedU, m_localY);\n\n    m_nextR << ref.pose.Translation().X().to<double>(),\n        ref.pose.Translation().Y().to<double>(),\n        ref.pose.Rotation().Radians().to<double>(), vlRef.to<double>(),\n        vrRef.to<double>();\n\n    // Compute feedforward\n    Eigen::Matrix<double, 5, 1> rdot = (m_nextR - m_r) / dt.to<double>();\n    Eigen::Matrix<double, 10, 1> rAugmented;\n    rAugmented.block<5, 1>(0, 0) = m_r;\n    rAugmented.block<5, 1>(5, 0).setZero();\n    Eigen::Matrix<double, 2, 1> uff = m_B.householderQr().solve(\n        rdot - Dynamics(rAugmented, Eigen::Matrix<double, 2, 1>::Zero())\n                   .block<5, 1>(0, 0));\n\n    if (m_isEnabled) {\n        m_cappedU = Controller(m_observer.Xhat(), m_nextR) + uff;\n    } else {\n        m_cappedU = Eigen::Matrix<double, 2, 1>::Zero();\n    }\n    ScaleCapU(&m_cappedU);\n\n    Eigen::Matrix<double, 5, 1> error =\n        m_r - m_observer.Xhat().block<5, 1>(0, 0);\n    m_atReferences = std::abs(error(0, 0)) < kPositionTolerance &&\n                     std::abs(error(1, 0)) < kPositionTolerance &&\n                     std::abs(error(2, 0)) < kAngleTolerance &&\n                     std::abs(error(3, 0)) < kVelocityTolerance &&\n                     std::abs(error(4, 0)) < kVelocityTolerance;\n\n    m_r = m_nextR;\n    m_observer.Predict(m_cappedU, dt);\n\n    if (ref.pose == m_goal) {\n        Disable();\n    } else {\n        Enable();\n    }\n}\n\nvoid DrivetrainController::Reset() {\n    m_observer.Reset();\n    m_r.setZero();\n    m_nextR.setZero();\n    m_cappedU.setZero();\n}\n\nvoid DrivetrainController::Reset(const frc::Pose2d& initialPose) {\n    m_observer.Reset();\n\n    Eigen::Matrix<double, 10, 1> xHat;\n    xHat(0, 0) = initialPose.Translation().X().to<double>();\n    xHat(1, 0) = initialPose.Translation().Y().to<double>();\n    xHat(2, 0) = initialPose.Rotation().Radians().to<double>();\n    xHat.block<7, 1>(3, 0).setZero();\n    m_observer.SetXhat(xHat);\n\n    m_r.setZero();\n    m_nextR.setZero();\n    m_cappedU.setZero();\n}\n\nEigen::Matrix<double, 2, 1> DrivetrainController::Controller(\n    const Eigen::Matrix<double, 10, 1>& x,\n    const Eigen::Matrix<double, 5, 1>& r) {\n    double kx = m_K0(0, 0);\n    double ky0 = m_K0(0, 1);\n    double kvpos0 = m_K0(0, 3);\n    double kvneg0 = m_K0(1, 3);\n    double ky1 = m_K1(0, 1);\n    double ktheta1 = m_K1(0, 2);\n    double kvpos1 = m_K1(0, 3);\n\n    double v = (x(State::kLeftVelocity, 0) + x(State::kRightVelocity, 0)) / 2.0;\n    double sqrtAbsV = std::sqrt(std::abs(v));\n\n    Eigen::Matrix<double, 2, 5> K;\n    K(0, 0) = kx;\n    K(0, 1) = (ky0 + (ky1 - ky0) * sqrtAbsV) * wpi::sgn(v);\n    K(0, 2) = ktheta1 * sqrtAbsV;\n    K(0, 3) = kvpos0 + (kvpos1 - kvpos0) * sqrtAbsV;\n    K(0, 4) = kvneg0 - (kvpos1 - kvpos0) * sqrtAbsV;\n    K(1, 0) = kx;\n    K(1, 1) = -K(0, 1);\n    K(1, 2) = -K(0, 2);\n    K(1, 3) = K(0, 4);\n    K(1, 4) = K(0, 3);\n\n    Eigen::Matrix<double, 2, 1> uError;\n    uError << x(State::kLeftVoltageError, 0), x(State::kRightVoltageError, 0);\n\n    Eigen::Matrix<double, 5, 5> inRobotFrame =\n        Eigen::Matrix<double, 5, 5>::Identity();\n    inRobotFrame(0, 0) = std::cos(x(2, 0));\n    inRobotFrame(0, 1) = std::sin(x(2, 0));\n    inRobotFrame(1, 0) = -std::sin(x(2, 0));\n    inRobotFrame(1, 1) = std::cos(x(2, 0));\n\n    Eigen::Matrix<double, 5, 1> error = r - x.block<5, 1>(0, 0);\n    error(State::kHeading, 0) = NormalizeAngle(error(State::kHeading, 0));\n    return K * inRobotFrame * error;\n}\n\nEigen::Matrix<double, 10, 1> DrivetrainController::Dynamics(\n    const Eigen::Matrix<double, 10, 1>& x,\n    const Eigen::Matrix<double, 2, 1>& u) {\n    // constexpr auto motors = frc::DCMotor::MiniCIM(3);\n\n    // constexpr units::dimensionless_t Glow = 15.32;  // Low gear ratio\n    // constexpr units::dimensionless_t Ghigh = 7.08;  // High gear ratio\n    // constexpr auto r = 0.0746125_m;                 // Wheel radius\n    // constexpr auto m = 63.503_kg;                   // Robot mass\n    // constexpr auto J = 5.6_kg_sq_m;                 // Robot moment of\n    // inertia\n\n    // constexpr auto C1 =\n    //     -1.0 * Ghigh * Ghigh * motors.Kt / (motors.Kv * motors.R * r * r);\n    // constexpr auto C2 = Ghigh * motors.Kt / (motors.R * r);\n    // constexpr auto k1 = (1 / m + rb * rb / J);\n    // constexpr auto k2 = (1 / m - rb * rb / J);\n\n    Eigen::Matrix<double, 4, 2> B;\n    B.block<2, 2>(0, 0) = m_plant.B();\n    B.block<2, 2>(2, 0).setZero();\n    Eigen::Matrix<double, 4, 7> A;\n    A.block<2, 2>(0, 0) = m_plant.A();\n\n    A.block<2, 2>(2, 0).setIdentity();\n    A.block<4, 2>(0, 2).setZero();\n    A.block<4, 2>(0, 4) = B;\n    A.block<4, 1>(0, 6) << 0, 0, 1, -1;\n\n    double v = (x(State::kLeftVelocity, 0) + x(State::kRightVelocity, 0)) / 2.0;\n\n    Eigen::Matrix<double, 10, 1> result;\n    result(0, 0) = v * std::cos(x(State::kHeading, 0));\n    result(1, 0) = v * std::sin(x(State::kHeading, 0));\n    result(2, 0) = ((x(State::kRightVelocity, 0) - x(State::kLeftVelocity, 0)) /\n                    (2.0 * rb))\n                       .to<double>();\n    result.block<4, 1>(3, 0) = A * x.block<7, 1>(3, 0) + B * u;\n    result.block<3, 1>(7, 0).setZero();\n    return result;\n}\n\nEigen::Matrix<double, 3, 1> DrivetrainController::LocalMeasurementModel(\n    const Eigen::Matrix<double, 10, 1>& x,\n    const Eigen::Matrix<double, 2, 1>& u) {\n    static_cast<void>(u);\n\n    Eigen::Matrix<double, 3, 1> y;\n    y << x(State::kHeading, 0), x(State::kLeftPosition, 0),\n        x(State::kRightPosition, 0);\n    return y;\n}\n\nEigen::Matrix<double, 6, 1> DrivetrainController::GlobalMeasurementModel(\n    const Eigen::Matrix<double, 10, 1>& x,\n    const Eigen::Matrix<double, 2, 1>& u) {\n    static_cast<void>(u);\n\n    Eigen::Matrix<double, 6, 1> y;\n    y.block<3, 1>(0, 0) = x.block<3, 1>(0, 0);\n    y(3, 0) = x(State::kLeftPosition, 0);\n    y(4, 0) = x(State::kRightPosition, 0);\n    y(5, 0) = (x(State::kRightVelocity, 0) - x(State::kLeftVelocity, 0)) /\n              (2.0 * rb.to<double>());\n    return y;\n}\n\nvoid DrivetrainController::ScaleCapU(Eigen::Matrix<double, 2, 1>* u) {\n    bool outputCapped =\n        std::abs((*u)(0, 0)) > 12.0 || std::abs((*u)(1, 0)) > 12.0;\n\n    if (outputCapped) {\n        *u *= 12.0 / u->lpNorm<Eigen::Infinity>();\n    }\n}\n", "meta": {"hexsha": "200a830459c188ec1577c9e5e30e50ea8f3c140a", "size": 13676, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main/cpp/controllers/DrivetrainController.cpp", "max_stars_repo_name": "frc3512/Robot-2019", "max_stars_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-05T01:06:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T15:18:49.000Z", "max_issues_repo_path": "src/main/cpp/controllers/DrivetrainController.cpp", "max_issues_repo_name": "frc3512/Robot-2019", "max_issues_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main/cpp/controllers/DrivetrainController.cpp", "max_forks_repo_name": "frc3512/Robot-2019", "max_forks_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T16:21:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-14T16:21:42.000Z", "avg_line_length": 37.6749311295, "max_line_length": 80, "alphanum_fraction": 0.6044164961, "num_tokens": 4201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.563646385370425}}
{"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": "/* ----------------------------------------------------------------------------\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#pragma once\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/Splines>\n#include \"mader_types.hpp\"\n\nvoid CPs2TrajAndPwp(std::vector<Eigen::Vector3d> &q, std::vector<mt::state> &traj, mt::PieceWisePol &solution_, int N, int p,\n                    int num_pol, Eigen::RowVectorXd &knots, double dc);\n\nEigen::Spline3d findInterpolatingBsplineNormalized(const std::vector<double> &times,\n                                                   const std::vector<Eigen::Vector3d> &positions);", "meta": {"hexsha": "7c488d439d606212dfef333e5685b6728cf84ea7", "size": 871, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mader/include/bspline_utils.hpp", "max_stars_repo_name": "shubham-shahh/mader", "max_stars_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 222.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T01:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:46:02.000Z", "max_issues_repo_path": "mader/include/bspline_utils.hpp", "max_issues_repo_name": "shubham-shahh/mader", "max_issues_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-02-18T15:19:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T14:19:54.000Z", "max_forks_repo_path": "mader/include/bspline_utils.hpp", "max_forks_repo_name": "shubham-shahh/mader", "max_forks_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T01:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T22:46:04.000Z", "avg_line_length": 45.8421052632, "max_line_length": 125, "alphanum_fraction": 0.5683122847, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5635679003024777}}
{"text": "/*\n * \n * Copyright (c) Karl Meerbergen 2008\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_PTSV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_PTSV_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/static_assert.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 tridiagonal symmetric or Hermitian positive definite matrix\n    //\n    /////////////////////////////////////////////////////////////////////\n\n    /*\n     * ptsv() computes the solution to a system of linear equations\n     * A*X = B, where A is an N-by-N Hermitian positive definite tridiagonal\n     * matrix, and X and B are N-by-NRHS matrices.\n     *\n     * A is factored as A = L*D*L**T, and the factored form of A is then\n     * used to solve the system of equations.\n     */\n\n    namespace detail {\n\n      inline \n      void ptsv ( int const n, int const nrhs,\n                 float* d, float* e, float* b, int const ldb, int* info) \n      {\n        LAPACK_SPTSV (&n, &nrhs, d, e, b, &ldb, info);\n      }\n\n      inline \n      void ptsv ( int const n, int const nrhs,\n                 double* d, double* e, double* b, int const ldb, int* info) \n      {\n        LAPACK_DPTSV (&n, &nrhs, d, e, b, &ldb, info);\n      }\n\n      inline \n      void ptsv ( int const n, int const nrhs,\n                 float* d, traits::complex_f* e, traits::complex_f* b, int const ldb, \n                 int* info) \n      {\n        LAPACK_CPTSV (&n, &nrhs, d, traits::complex_ptr(e), traits::complex_ptr(b), &ldb, info);\n      }\n\n      inline \n      void ptsv ( int const n, int const nrhs,\n                 double* d, traits::complex_d* e, traits::complex_d* b, int const ldb, \n                 int* info) \n      {\n        LAPACK_ZPTSV (&n, &nrhs, d, traits::complex_ptr(e), traits::complex_ptr(b), &ldb, info);\n      }\n\n    }\n\n    template <typename D, typename E, typename B>\n    inline int ptsv( D& d, E& e, B& b ) {\n      int const n = traits::vector_size(d) ;\n      assert( n==traits::vector_size(e)+1 ) ;\n      assert( n==traits::matrix_num_rows(b) ) ;\n\n      int info ;\n      detail::ptsv( n, traits::matrix_num_columns (b)\n                  , traits::vector_storage(d)\n                  , traits::vector_storage(e)\n                  , traits::matrix_storage(b)\n                  , traits::leading_dimension(b)\n                  , &info\n                  ) ;\n      return info ;\n    } // ptsv()\n\n\n    /*\n     * pttrf() computes the L * D * L^H factorization of a Hermitian\n     * positive definite tridiagonal matrix A.  The factorization may also\n     * be regarded as having the form A = U^H * D *U.\n     */\n\n    namespace detail {\n\n      inline \n      void pttrf ( int const n, float* d, float* e, int* info) {\n        LAPACK_SPTTRF ( &n, d, e, info) ;\n      }\n\n      inline \n      void pttrf ( int const n, double* d, double* e, int* info) {\n        LAPACK_DPTTRF ( &n, d, e, info);\n      }\n\n      inline \n      void pttrf ( int const n, float* d, traits::complex_f* e, int* info) \n      {\n        LAPACK_CPTTRF ( &n, d, traits::complex_ptr(e), info);\n      }\n\n      inline \n      void pttrf ( int const n, double* d, traits::complex_d* e, int* info) \n      {\n        LAPACK_ZPTTRF ( &n, d, traits::complex_ptr(e), info);\n      }\n\n    }\n\n    template <typename D, typename E>\n    inline\n    int pttrf (D& d, E& e) {\n      int const n = traits::vector_size (d);\n      assert (n == traits::vector_size (e) + 1);\n      int info; \n      detail::pttrf ( n, traits::vector_storage(d), traits::vector_storage(e), &info);\n      return info; \n    }\n\n\n    /*\n     * pttrs() solves a tridiagonal system of the form\n     *   A * X = B\n     * using the factorization A = U^H * D * U or A = L * D * L^H computed by pttrf().\n     * D is a diagonal matrix specified in the vector D, U (or L) is a unit\n     * bidiagonal matrix whose superdiagonal (subdiagonal) is specified in\n     * the vector E, and X and B are N by NRHS matrices.\n     */\n\n    namespace detail {\n\n      inline \n      void pttrs (char const uplo, int const n, int const nrhs,\n                  float const* d, float const* e, float* b, int const ldb, int* info) \n      {\n        LAPACK_SPTTRS (&n, &nrhs, d, e, b, &ldb, info);\n      }\n\n      inline \n      void pttrs (char const uplo, int const n, int const nrhs,\n                  double const* d, double const* e, double* b, int const ldb, int* info) \n      {\n        LAPACK_DPTTRS (&n, &nrhs, d, e, b, &ldb, info);\n      }\n\n      inline \n      void pttrs (char const uplo, int const n, int const nrhs,\n                  float const* d, \n                  traits::complex_f const* e, \n                  traits::complex_f* b, int const ldb, int* info) \n      {\n        LAPACK_CPTTRS (&uplo, &n, &nrhs, d, \n                       traits::complex_ptr (e), \n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline \n      void pttrs (char const uplo, int const n, int const nrhs,\n                  double const* d, \n                  traits::complex_d const* e, \n                  traits::complex_d* b, int const ldb, int* info) \n      {\n        LAPACK_ZPTTRS (&uplo, &n, &nrhs, d, \n                       traits::complex_ptr (e), \n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n    }\n\n    template <typename D, typename E, typename MatrB>\n    inline\n    int pttrs (char uplo, D const& d, E const& e, MatrB& b) {\n      int const n = traits::vector_size (d);\n      assert (n == traits::vector_size (e) + 1);\n      assert (n == traits::matrix_num_rows (b));\n      \n      int info; \n      detail::pttrs (uplo, n, traits::matrix_num_columns (b),\n                     traits::vector_storage (d), \n                     traits::vector_storage (e), \n                     traits::matrix_storage (b), \n                     traits::leading_dimension (b), \n                     &info);\n      return info; \n    } // pttrs()\n\n  }\n\n}}}\n\n#endif \n", "meta": {"hexsha": "ff1b1c81c42802f1dbbe63a25e99861064bc7d5b", "size": 6380, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/ptsv.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/ptsv.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/ptsv.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": 30.380952381, "max_line_length": 96, "alphanum_fraction": 0.5369905956, "num_tokens": 1747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5635678944467621}}
{"text": "/**********************************************************************************************************************\nThis file is part of the Control Toolbox (https://adrlab.bitbucket.io/ct), copyright by ETH Zurich, Google Inc.\nAuthors:  Michael Neunert, Markus Giftthaler, Markus St\u00e4uble, Diego Pardo, Farbod Farshidian\nLicensed under Apache2 license (see LICENSE file in main directory)\n**********************************************************************************************************************/\n\n#pragma once\n\n\n#include <Eigen/Dense>\n#include <ct/core/core.h>\n#include \"Quadrotor.hpp\"\n\n\nnamespace ct {\nnamespace models {\n\nclass QuadrotorLinear : public ct::core::LinearSystem<quadrotor::nStates, quadrotor::nControls>\n{\npublic:\n    typedef ct::core::StateVector<quadrotor::nStates> state_vector_t;\n    typedef ct::core::ControlVector<quadrotor::nControls> control_vector_t;\n\n    typedef Eigen::Matrix<double, quadrotor::nStates, quadrotor::nStates> state_matrix_t;\n    typedef Eigen::Matrix<double, quadrotor::nStates, quadrotor::nControls> state_control_matrix_t;\n\n\n    virtual QuadrotorLinear* clone() const override { return new QuadrotorLinear(*this); }\n    virtual const state_matrix_t& getDerivativeState(const state_vector_t& x,\n        const control_vector_t& u,\n        const ct::core::Time t = 0.0) override\n    {\n        A_ = A_quadrotor(x, u);\n        return A_;\n    }\n\n    virtual const state_control_matrix_t& getDerivativeControl(const state_vector_t& x,\n        const control_vector_t& u,\n        const ct::core::Time t = 0.0) override\n    {\n        B_ = B_quadrotor(x, u);\n        return B_;\n    }\n\nprivate:\n    state_matrix_t A_;\n    state_control_matrix_t B_;\n};\n}\n}\n", "meta": {"hexsha": "a76680206a5610da57d5045b0c22349c2aba1d98", "size": 1704, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/ct/ct_models/include/ct/models/Quadrotor/QuadrotorLinear.hpp", "max_stars_repo_name": "Ewpratten/frc_971_mirror", "max_stars_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "third_party/ct/ct_models/include/ct/models/Quadrotor/QuadrotorLinear.hpp", "max_issues_repo_name": "Ewpratten/frc_971_mirror", "max_issues_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/ct/ct_models/include/ct/models/Quadrotor/QuadrotorLinear.hpp", "max_forks_repo_name": "Ewpratten/frc_971_mirror", "max_forks_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4117647059, "max_line_length": 119, "alphanum_fraction": 0.6167840376, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834646, "lm_q2_score": 0.6893056295505784, "lm_q1q2_score": 0.5635586951449476}}
{"text": "#ifdef _DEBUG\n#include \"../../../library/src/debug_template.hpp\"\n#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__)\n#else\n#define DMP(...) ((void)0)\n#endif\n\n#include <cassert>\n#include <cstdio>\n#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <vector>\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\nusing dec_float = boost::multiprecision::number<boost::multiprecision::cpp_dec_float<10>>;\n\nusing namespace std;\nusing lint = long long;\nconstexpr int INF = 1010101010;\nconstexpr lint LINF = 1LL << 60;\nstruct init {\n    init() {\n        cin.tie(nullptr);\n        ios::sync_with_stdio(false);\n        cout << fixed << setprecision(10);\n    }\n} init_;\n\nint main() {\n\n    dec_float X, Y, R;\n    cin >> X >> Y >> R;\n\n    int l = (int)ceil(X - R), r = (int)floor(X + R);\n\n    lint ans = 0;\n    for (int i = l; i <= r; i++) {\n        dec_float p = sqrt(R * R - abs(X - i) * abs(X - i));\n        ans += (int)floor(Y + p) - (int)ceil(Y - p) + 1;\n    }\n\n    cout << ans << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "9bece8db89742b55e66127151200076bde17b9d9", "size": 1022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ABC/ABC191/D.cpp", "max_stars_repo_name": "rajyan/AtCoder", "max_stars_repo_head_hexsha": "2c1187994016d4c19b95489d2f2d2c0eab43dd8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-01T17:13:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-01T17:13:44.000Z", "max_issues_repo_path": "ABC/ABC191/D.cpp", "max_issues_repo_name": "rajyan/AtCoder", "max_issues_repo_head_hexsha": "2c1187994016d4c19b95489d2f2d2c0eab43dd8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ABC/ABC191/D.cpp", "max_forks_repo_name": "rajyan/AtCoder", "max_forks_repo_head_hexsha": "2c1187994016d4c19b95489d2f2d2c0eab43dd8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2916666667, "max_line_length": 90, "alphanum_fraction": 0.5900195695, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5635586847085012}}
{"text": "#include \"TestScheme.h\"\n\n#include <NTL/BasicThreadPool.h>\n#include <NTL/RR.h>\n#include <NTL/ZZ.h>\n#include <cstdlib>\n#include <iostream>\n#include <string>\n\n#include \"Cipher.h\"\n#include \"CZZ.h\"\n#include \"EvaluatorUtils.h\"\n#include \"NumUtils.h\"\n#include \"Params.h\"\n#include \"PubKey.h\"\n#include \"Scheme.h\"\n#include \"SchemeAlgo.h\"\n#include \"SchemeAux.h\"\n#include \"SecKey.h\"\n#include \"StringUtils.h\"\n#include \"TimeUtils.h\"\n\nusing namespace NTL;\n\n//-----------------------------------------\n\nvoid TestScheme::testEncodeBatch(long logN, long logq, long precisionBits, long logSlots) {\n\tcout << \"!!! START TEST ENCODE BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tCZZ* mvec = EvaluatorUtils::evaluateRandomVals(slots, precisionBits);\n\t//-----------------------------------------\n\ttimeutils.start(\"Encrypt batch\");\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\ttimeutils.stop(\"Encrypt batch\");\n\t//-----------------------------------------\n\ttimeutils.start(\"Decrypt batch\");\n\tCZZ* dvec = scheme.decrypt(secretKey, cipher);\n\ttimeutils.stop(\"Decrypt batch\");\n\t//-----------------------------------------\n\tStringUtils::showcompare(mvec, dvec, slots, \"val\");\n\t//-----------------------------------------\n\tcout << \"!!! END TEST ENCODE BATCH !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testConjugateBatch(long logN, long logq, long precisionBits, long logSlots) {\n\tcout << \"!!! START TEST CONJUGATE BATCH !!!\" << endl;\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tCZZ* mvec = EvaluatorUtils::evaluateRandomVals(slots, precisionBits);\n\tCZZ* mvecconj = new CZZ[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmvecconj[i] = mvec[i].conjugate();\n\t}\n\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\ttimeutils.start(\"Conjugate batch\");\n\tCipher cconj = scheme.conjugate(cipher);\n\ttimeutils.stop(\"Conjugate batch\");\n\n\tCZZ* dvecconj = scheme.decrypt(secretKey, cconj);\n\n\tStringUtils::showcompare(mvecconj, dvecconj, slots, \"conj\");\n\n\tcout << \"!!! END TEST CONJUGATE BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testimultBatch(long logN, long logq, long precisionBits, long logSlots) {\n\tcout << \"!!! START TEST i MULTIPLICATION BATCH !!!\" << endl;\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tCZZ* mvec = EvaluatorUtils::evaluateRandomVals(slots, precisionBits);\n\tCZZ* imvec = new CZZ[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\timvec[i].r = -mvec[i].i;\n\t\timvec[i].i = mvec[i].r;\n\t}\n\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\ttimeutils.start(\"Multiplication by i batch\");\n\tCipher icipher = scheme.imult(cipher, precisionBits);\n\ttimeutils.stop(\"Multiplication by i batch\");\n\n\tCZZ* idvec = scheme.decrypt(secretKey, icipher);\n\n\tStringUtils::showcompare(imvec, idvec, slots, \"imult\");\n\n\tcout << \"!!! END TEST i MULTIPLICATION BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testRotateByPo2Batch(long logN, long logq, long precisionBits, long rotlogSlots, long logSlots, bool isLeft) {\n\tcout << \"!!! START TEST ROTATE BY POWER OF 2 BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tlong rotSlots = (1 << rotlogSlots);\n\tCZZ* mvec = EvaluatorUtils::evaluateRandomVals(slots, precisionBits);\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\t//-----------------------------------------\n\tif(isLeft) {\n\t\ttimeutils.start(\"Left Rotate by power of 2 batch\");\n\t\tscheme.leftRotateByPo2AndEqual(cipher, rotlogSlots);\n\t\ttimeutils.stop(\"Left Rotate by power of 2 batch\");\n\t} else {\n\t\ttimeutils.start(\"Right Rotate by power of 2 batch\");\n\t\tscheme.rightRotateByPo2AndEqual(cipher, rotlogSlots);\n\t\ttimeutils.stop(\"Right Rotate by power of 2 batch\");\n\t}\n\t//-----------------------------------------\n\tCZZ* dvec = scheme.decrypt(secretKey, cipher);\n\tif(isLeft) {\n\t\tEvaluatorUtils::leftRotateAndEqual(mvec, slots, rotSlots);\n\t} else {\n\t\tEvaluatorUtils::rightRotateAndEqual(mvec, slots, rotSlots);\n\t}\n\tStringUtils::showcompare(mvec, dvec, slots, \"val\");\n\t//-----------------------------------------\n\tcout << \"!!! END TEST ROTATE BY POWER OF 2 BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testRotateBatch(long logN, long logq, long precisionBits, long rotSlots, long logSlots, bool isLeft) {\n\tcout << \"!!! START TEST ROTATE BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tCZZ* mvec = EvaluatorUtils::evaluateRandomVals(slots, precisionBits);\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\t//-----------------------------------------\n\tif(isLeft) {\n\t\ttimeutils.start(\"Left rotate batch\");\n\t\tscheme.leftRotateAndEqual(cipher, rotSlots);\n\t\ttimeutils.stop(\"Left rotate batch\");\n\t} else {\n\t\ttimeutils.start(\"Right rotate batch\");\n\t\tscheme.rightRotateAndEqual(cipher, rotSlots);\n\t\ttimeutils.stop(\"Right rotate batch\");\n\t}\n\t//-----------------------------------------\n\tCZZ* dvec = scheme.decrypt(secretKey, cipher);\n\tif(isLeft) {\n\t\tEvaluatorUtils::leftRotateAndEqual(mvec, slots, rotSlots);\n\t} else {\n\t\tEvaluatorUtils::rightRotateAndEqual(mvec, slots, rotSlots);\n\t}\n\tStringUtils::showcompare(mvec, dvec, slots, \"val\");\n\t//-----------------------------------------\n\tcout << \"!!! END TEST ROTATE BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testSlotsSum(long logN, long logq, long precisionBits, long logSlots) {\n\tcout << \"!!! START TEST SLOTS SUM !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = (1 << logSlots);\n\tCZZ* mvec = EvaluatorUtils::evaluateRandomVals(slots, precisionBits);\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\t//-----------------------------------------\n\ttimeutils.start(\"slots sum\");\n\talgo.partialSlotsSumAndEqual(cipher, slots);\n\ttimeutils.stop(\"slots sum\");\n\t//-----------------------------------------\n\tCZZ* dvec = scheme.decrypt(secretKey, cipher);\n\tCZZ msum = CZZ();\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmsum += mvec[i];\n\t}\n\tStringUtils::showcompare(msum, dvec, slots, \"slotsum\");\n\t//-----------------------------------------\n\tcout << \"!!! END TEST SLOTS SUM !!!\" << endl;\n}\n\n\n//-----------------------------------------\n\nvoid TestScheme::testPowerOf2Batch(long logN, long logq, long precisionBits, long logDegree, long logSlots) {\n\tcout << \"!!! START TEST POWER OF 2 BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tCZZ* mvec = new CZZ[slots];\n\tCZZ* mpow = new CZZ[slots];\n\n\tCZZ** mpows = new CZZ*[logDegree + 1];\n\tfor (long i = 0; i < logDegree + 1; ++i) {\n\t\tmpows[i] = new CZZ[slots];\n\t}\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tRR angle = random_RR();\n\t\tRR mr = cos(angle * 2 * Pi);\n\t\tRR mi = sin(angle * 2 * Pi);\n\t\tmvec[i] = EvaluatorUtils::evaluateVal(mr, mi, precisionBits);\n\t\tmpow[i] = EvaluatorUtils::evaluatePow2(mr, mi, logDegree, precisionBits);\n\t\tfor (int j = 0; j < logDegree + 1; ++j) {\n\t\t\tmpows[j][i] = EvaluatorUtils::evaluatePow2(mr, mi, j, precisionBits);\n\t\t}\n\t}\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\t//-----------------------------------------\n\ttimeutils.start(\"Power of 2 batch\");\n\tCipher cpow = algo.powerOf2(cipher, precisionBits, logDegree);\n\ttimeutils.stop(\"Power of 2 batch\");\n\n\t//-----------------------------------------\n\tCZZ* dpow = scheme.decrypt(secretKey, cpow);\n\tStringUtils::showcompare(mpow, dpow, slots, \"pow\");\n\t//-----------------------------------------\n\tcout << \"!!! END TEST POWER OF 2 BATCH !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testPowerBatch(long logN, long logq, long precisionBits, long degree, long logSlots) {\n\tcout << \"!!! START TEST POWER BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tCZZ* mvec = new CZZ[slots];\n\tCZZ* mpow = new CZZ[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tRR angle = random_RR();\n\t\tRR mr = cos(angle * 2 * Pi);\n\t\tRR mi = sin(angle * 2 * Pi);\n\t\tmvec[i] = EvaluatorUtils::evaluateVal(mr, mi, precisionBits);\n\t\tmpow[i] = EvaluatorUtils::evaluatePow(mr, mi, degree, precisionBits);\n\t}\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\t//-----------------------------------------\n\ttimeutils.start(\"Power batch\");\n\tCipher cpow = algo.power(cipher, precisionBits, degree);\n\ttimeutils.stop(\"Power batch\");\n\t//-----------------------------------------\n\tCZZ* dpow = scheme.decrypt(secretKey, cpow);\n\tStringUtils::showcompare(mpow, dpow, slots, \"pow\");\n\t//-----------------------------------------\n\tcout << \"!!! END TEST POWER BATCH !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testProdOfPo2Batch(long logN, long logq, long precisionBits, long logDegree, long logSlots) {\n\tcout << \"!!! START TEST PROD OF POWER OF 2 BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tSetNumThreads(4);\n\tlong slots = 1 << logSlots;\n\tlong degree = 1 << logDegree;\n\tCipher* cvec = new Cipher[degree];\n\tCZZ** mvec = new CZZ*[degree];\n\tfor (long i = 0; i < degree; ++i) {\n\t\tmvec[i] = new CZZ[slots];\n\t}\n\tCZZ* pvec = new CZZ[slots];\n\tfor (long i = 0; i < degree; ++i) {\n\t\tfor (long j = 0; j < slots; ++j) {\n\t\t\tmvec[i][j] = EvaluatorUtils::evaluateRandomCircleVal(precisionBits);\n\t\t}\n\t}\n\tfor (long j = 0; j < slots; ++j) {\n\t\tpvec[j] = mvec[0][j];\n\t\tfor (long i = 1; i < degree; ++i) {\n\t\t\tpvec[j] *= mvec[i][j];\n\t\t\tpvec[j] >>= precisionBits;\n\t\t}\n\t}\n\tfor (long i = 0; i < degree; ++i) {\n\t\tcvec[i] = scheme.encrypt(mvec[i], slots);\n\t}\n\t//-----------------------------------------\n\ttimeutils.start(\"Product of power of 2 batch\");\n\tCipher cprod = algo.prodOfPo2(cvec, precisionBits, logDegree);\n\ttimeutils.stop(\"Product of power of 2 batch\");\n\t//-----------------------------------------\n\tCZZ* dvec = scheme.decrypt(secretKey, cprod);\n\tStringUtils::showcompare(pvec, dvec, slots, \"prod\");\n\t//-----------------------------------------\n\tcout << \"!!! END TEST PROD OF POWER OF 2 BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testProdBatch(long logN, long logq, long precisionBits, long degree, long logSlots) {\n\tcout << \"!!! START TEST PROD BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tSetNumThreads(4);\n\tlong slots = 1 << logSlots;\n\tCipher* cvec = new Cipher[degree];\n\tCZZ** mvec = new CZZ*[degree];\n\tfor (long i = 0; i < degree; ++i) {\n\t\tmvec[i] = new CZZ[slots];\n\t}\n\tCZZ* pvec = new CZZ[slots];\n\tfor (long i = 0; i < degree; ++i) {\n\t\tfor (long j = 0; j < slots; ++j) {\n\t\t\tmvec[i][j] = EvaluatorUtils::evaluateRandomCircleVal(precisionBits);\n\t\t}\n\t}\n\tfor (long j = 0; j < slots; ++j) {\n\t\tpvec[j] = mvec[0][j];\n\t\tfor (long i = 1; i < degree; ++i) {\n\t\t\tpvec[j] *= mvec[i][j];\n\t\t\tpvec[j] >>= precisionBits;\n\t\t}\n\t}\n\tfor (long i = 0; i < degree; ++i) {\n\t\tcvec[i] = scheme.encrypt(mvec[i], slots);\n\t}\n\t//-----------------------------------------\n\ttimeutils.start(\"Product batch\");\n\tCipher cprod = algo.prod(cvec, precisionBits, degree);\n\ttimeutils.stop(\"Product batch\");\n\t//-----------------------------------------\n\tCZZ* dvec = scheme.decrypt(secretKey, cprod);\n\tStringUtils::showcompare(pvec, dvec, slots, \"prod\");\n\t//-----------------------------------------\n\tcout << \"!!! END TEST PROD BATCH !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testInverseBatch(long logN, long logq, long precisionBits, long invSteps, long logSlots) {\n\tcout << \"!!! START TEST INVERSE BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tCZZ* mvec = new CZZ[slots];\n\tCZZ* minv = new CZZ[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tRR angle = random_RR() / 20;\n\t\tRR mr = cos(angle * 2 * Pi);\n\t\tRR mi = sin(angle * 2 * Pi);\n\t\tmvec[i] = EvaluatorUtils::evaluateVal(1 - mr, -mi, precisionBits);\n\t\tminv[i] = EvaluatorUtils::evaluateInverse(mr, mi, precisionBits);\n\t}\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\t//-----------------------------------------\n\ttimeutils.start(\"Inverse batch\");\n\tCipher cinv = algo.inverse(cipher, precisionBits, invSteps);\n\ttimeutils.stop(\"Inverse batch\");\n\t//-----------------------------------------\n\tCZZ* dinv = scheme.decrypt(secretKey, cinv);\n\tStringUtils::showcompare(minv, dinv, slots, \"inv\");\n\t//-----------------------------------------\n\tcout << \"!!! END TEST INVERSE BATCH !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testLogarithmBatch(long logN, long logq, long precisionBits, long degree, long logSlots) {\n\tcout << \"!!! START TEST LOGARITHM BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tCZZ* mvec = new CZZ[slots];\n\tCZZ* mlog = new CZZ[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tdouble mr = (double)rand() / RAND_MAX / 20;\n\t\tdouble mi = (double)rand() / RAND_MAX / 20;\n\t\tmvec[i] = EvaluatorUtils::evaluateVal(mr, mi, precisionBits);\n\t\tmlog[i] = EvaluatorUtils::evaluateLogarithm(1 + mr, mi, precisionBits);\n\t}\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\t//-----------------------------------------\n\ttimeutils.start(LOGARITHM + \" batch\");\n\tCipher clog = algo.function(cipher, LOGARITHM, precisionBits, degree);\n\ttimeutils.stop(LOGARITHM + \" batch\");\n\t//-----------------------------------------\n\tCZZ* dlog = scheme.decrypt(secretKey, clog);\n\tStringUtils::showcompare(mlog, dlog, slots, LOGARITHM);\n\t//-----------------------------------------\n\tcout << \"!!! END TEST LOGARITHM BATCH !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testExponentBatch(long logN, long logq, long precisionBits, long degree, long logSlots) {\n\tcout << \"!!! START TEST EXPONENT BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tCZZ* mvec = new CZZ[slots];\n\tCZZ* mexp = new CZZ[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tRR mr = random_RR();\n\t\tRR mi = random_RR();\n\t\tmvec[i] = EvaluatorUtils::evaluateVal(mr, mi, precisionBits);\n\t\tmexp[i] = EvaluatorUtils::evaluateExponent(mr, mi, precisionBits);\n\t}\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\t//-----------------------------------------\n\ttimeutils.start(EXPONENT + \" batch\");\n\tCipher cexp = algo.function(cipher, EXPONENT, precisionBits, degree);\n\ttimeutils.stop(EXPONENT + \" batch\");\n\t//-----------------------------------------\n\tCZZ* dexp = scheme.decrypt(secretKey, cexp);\n\tStringUtils::showcompare(mexp, dexp, slots, EXPONENT);\n\t//-----------------------------------------\n\tcout << \"!!! END TEST EXPONENT BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testExponentBatchLazy(long logN, long logq, long precisionBits, long degree, long logSlots) {\n\tcout << \"!!! START TEST EXPONENT LAZY !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tCZZ* mvec = new CZZ[slots];\n\tCZZ* mexp = new CZZ[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tRR mr = random_RR();\n\t\tRR mi = random_RR();\n\t\tmvec[i] = EvaluatorUtils::evaluateVal(mr, mi, precisionBits);\n\t\tmexp[i] = EvaluatorUtils::evaluateExponent(mr, mi, precisionBits);\n\t}\n\tEvaluatorUtils::leftShiftAndEqual(mexp, slots, precisionBits);\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\t//-----------------------------------------\n\ttimeutils.start(EXPONENT + \" lazy\");\n\tCipher cexp = algo.functionLazy(cipher, EXPONENT, precisionBits, degree);\n\ttimeutils.stop(EXPONENT + \" lazy\");\n\t//-----------------------------------------\n\tCZZ* dexp = scheme.decrypt(secretKey, cexp);\n\tStringUtils::showcompare(mexp, dexp, slots, EXPONENT);\n\t//-----------------------------------------\n\tcout << \"!!! END TEST EXPONENT LAZY !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testSigmoidBatch(long logN, long logq, long precisionBits, long degree, long logSlots) {\n\tcout << \"!!! START TEST SIGMOID BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tCZZ* mvec = new CZZ[slots];\n\tCZZ* msig = new CZZ[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tRR mr = random_RR();\n\t\tRR mi = random_RR();\n\t\tmvec[i] = EvaluatorUtils::evaluateVal(mr, mi, precisionBits);\n\t\tmsig[i] = EvaluatorUtils::evaluateSigmoid(mr, mi, precisionBits);\n\t}\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\t//-----------------------------------------\n\ttimeutils.start(SIGMOID + \" batch\");\n\tCipher csig = algo.function(cipher, SIGMOID, precisionBits, degree);\n\ttimeutils.stop(SIGMOID + \" batch\");\n\t//-----------------------------------------\n\tCZZ* dsig = scheme.decrypt(secretKey, csig);\n\tStringUtils::showcompare(msig, dsig, slots, SIGMOID);\n\t//-----------------------------------------\n\tcout << \"!!! END TEST SIGMOID BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testSigmoidBatchLazy(long logN, long logq, long precisionBits, long degree, long logSlots) {\n\tcout << \"!!! START TEST SIGMOID LAZY !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tlong slots = 1 << logSlots;\n\tCZZ* mvec = new CZZ[slots];\n\tCZZ* msig = new CZZ[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tRR mr = random_RR();\n\t\tRR mi = random_RR();\n\t\tmvec[i] = EvaluatorUtils::evaluateVal(mr, mi, precisionBits);\n\t\tmsig[i] = EvaluatorUtils::evaluateSigmoid(mr, mi, precisionBits);\n\t}\n\tEvaluatorUtils::leftShiftAndEqual(msig, slots, precisionBits);\n\tCipher cipher = scheme.encrypt(mvec, slots);\n\t//-----------------------------------------\n\ttimeutils.start(SIGMOID + \" lazy\");\n\tCipher csig = algo.functionLazy(cipher, SIGMOID, precisionBits, degree);\n\ttimeutils.stop(SIGMOID + \" lazy\");\n\t//-----------------------------------------\n\tCZZ* dsig = scheme.decrypt(secretKey, csig);\n\tStringUtils::showcompare(msig, dsig, slots, SIGMOID);\n\t//-----------------------------------------\n\tcout << \"!!! END TEST SIGMOID LAZY !!!\" << endl;\n}\n\n//-----------------------------------------\n\nvoid TestScheme::testFFTBatch(long logN, long logq, long precisionBits, long logSlots, long logfftdim) {\n\tcout << \"!!! START TEST FFT BATCH !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tSetNumThreads(8);\n\t//-----------------------------------------\n\tlong fftdim = 1 << logfftdim;\n\tlong slots = 1 << logSlots;\n\tCZZ** mvec1 = new CZZ*[slots];\n\tCZZ** mvec2 = new CZZ*[slots];\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmvec1[i] = EvaluatorUtils::evaluateRandomVals(fftdim, precisionBits);\n\t\tmvec2[i] = EvaluatorUtils::evaluateRandomVals(fftdim, precisionBits);\n\t}\n\n\tCipher* cvec1 = new Cipher[fftdim];\n\tCipher* cvec2 = new Cipher[fftdim];\n\tfor (long j = 0; j < fftdim; ++j) {\n\t\tCZZ* mvals1 = new CZZ[slots];\n\t\tCZZ* mvals2\t= new CZZ[slots];\n\t\tfor (long i = 0; i < slots; ++i) {\n\t\t\tmvals1[i] = mvec1[i][j];\n\t\t\tmvals2[i] = mvec2[i][j];\n\t\t}\n\t\tcvec1[j] = scheme.encrypt(mvals1, slots);\n\t\tcvec2[j] = scheme.encrypt(mvals2, slots);\n\t\tdelete[] mvals1;\n\t\tdelete[] mvals2;\n\t}\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tNumUtils::fft(mvec1[i], fftdim, schemeaux);\n\t\tNumUtils::fft(mvec2[i], fftdim, schemeaux);\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tmvec1[i][j] *= mvec2[i][j];\n\t\t\tmvec1[i][j] >>= precisionBits;\n\t\t}\n\t\tNumUtils::fftInv(mvec1[i], fftdim, schemeaux);\n\t}\n\t//-----------------------------------------\n\ttimeutils.start(\"ciphers fft 1 batch\");\n\talgo.fft(cvec1, fftdim);\n\ttimeutils.stop(\"ciphers fft 1 batch\");\n\t//-----------------------------------------\n\ttimeutils.start(\"ciphers fft 2 batch\");\n\talgo.fft(cvec2, fftdim);\n\ttimeutils.stop(\"ciphers fft 2 batch\");\n\t//-----------------------------------------\n\ttimeutils.start(\"ciphers hadamard mult batch\");\n\talgo.multModSwitchAndEqualVec(cvec1, cvec2, precisionBits, fftdim);\n\ttimeutils.stop(\"ciphers hadamard mult batch\");\n\t//-----------------------------------------\n\tdelete[] cvec2;\n\t//-----------------------------------------\n\ttimeutils.start(\"ciphers fft inverse batch\");\n\talgo.fftInv(cvec1, fftdim);\n\ttimeutils.stop(\"ciphers fft inverse batch\");\n\t//-----------------------------------------\n\tCZZ** dvec1 = new CZZ*[fftdim];\n\tfor (long j = 0; j < fftdim; ++j) {\n\t\tdvec1[j] = scheme.decrypt(secretKey, cvec1[j]);\n\t}\n\tfor (long i = 0; i < slots; ++i) {\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tStringUtils::showcompare(mvec1[i][j], dvec1[j][i], \"fft\");\n\t\t}\n\t}\n\t//-----------------------------------------\n\tcout << \"!!! END TEST FFT BATCH !!!\" << endl;\n}\n\nvoid TestScheme::testFFTBatchLazy(long logN, long logq, long precisionBits, long logSlots, long logfftdim) {\n\tcout << \"!!! START TEST FFT BATCH LAZY !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tSetNumThreads(8);\n\t//-----------------------------------------\n\tlong fftdim = 1 << logfftdim;\n\tlong slots = 1 << logSlots;\n\tCZZ** mvec1 = new CZZ*[slots];\n\tCZZ** mvec2 = new CZZ*[slots];\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tmvec1[i] = EvaluatorUtils::evaluateRandomVals(fftdim, precisionBits);\n\t\tmvec2[i] = EvaluatorUtils::evaluateRandomVals(fftdim, precisionBits);\n\t}\n\n\tCipher* cvec1 = new Cipher[fftdim];\n\tCipher* cvec2 = new Cipher[fftdim];\n\tfor (long j = 0; j < fftdim; ++j) {\n\t\tCZZ* mvals1 = new CZZ[slots];\n\t\tCZZ* mvals2\t= new CZZ[slots];\n\t\tfor (long i = 0; i < slots; ++i) {\n\t\t\tmvals1[i] = mvec1[i][j];\n\t\t\tmvals2[i] = mvec2[i][j];\n\t\t}\n\t\tcvec1[j] = scheme.encrypt(mvals1, slots);\n\t\tcvec2[j] = scheme.encrypt(mvals2, slots);\n\t\tdelete[] mvals1;\n\t\tdelete[] mvals2;\n\t}\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tNumUtils::fft(mvec1[i], fftdim, schemeaux);\n\t\tNumUtils::fft(mvec2[i], fftdim, schemeaux);\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tmvec1[i][j] *= mvec2[i][j];\n\t\t\tmvec1[i][j] >>= precisionBits;\n\t\t}\n\t\tNumUtils::fftInvLazy(mvec1[i], fftdim, schemeaux);\n\t}\n\t//-----------------------------------------\n\ttimeutils.start(\"ciphers fft 1\");\n\talgo.fft(cvec1, fftdim);\n\ttimeutils.stop(\"ciphers fft 1\");\n\t//-----------------------------------------\n\ttimeutils.start(\"ciphers fft 2\");\n\talgo.fft(cvec2, fftdim);\n\ttimeutils.stop(\"ciphers fft 2\");\n\t//-----------------------------------------\n\ttimeutils.start(\"ciphers hadamard mult\");\n\talgo.multModSwitchAndEqualVec(cvec1, cvec2, precisionBits, fftdim);\n\ttimeutils.stop(\"ciphers hadamard mult\");\n\t//-----------------------------------------\n\tdelete[] cvec2;\n\t//-----------------------------------------\n\ttimeutils.start(\"ciphers fft inverse lazy\");\n\talgo.fftInvLazy(cvec1, fftdim);\n\ttimeutils.stop(\"ciphers fft inverse lazy\");\n\t//-----------------------------------------\n\tCZZ** dvec1 = new CZZ*[fftdim];\n\tfor (long j = 0; j < fftdim; ++j) {\n\t\tdvec1[j] = scheme.decrypt(secretKey, cvec1[j]);\n\t}\n\tfor (long i = 0; i < slots; ++i) {\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tStringUtils::showcompare(mvec1[i][j], dvec1[j][i], \"fft\");\n\t\t}\n\t}\n\t//-----------------------------------------\n\tcout << \"!!! END TEST FFT BATCH LAZY !!!\" << endl;\n}\n\nvoid TestScheme::testFFTBatchLazyMultipleHadamard(long logN, long logq, long precisionBits, long logSlots, long logfftdim, long logHdim) {\n\tcout << \"!!! START TEST FFT BATCH LAZY MULTIPLE HADAMARD !!!\" << endl;\n\t//-----------------------------------------\n\tTimeUtils timeutils;\n\tParams params(logN, logq);\n\tSecKey secretKey(params);\n\tPubKey publicKey(params, secretKey);\n\tSchemeAux schemeaux(logN);\n\tScheme scheme(params, publicKey, schemeaux);\n\tSchemeAlgo algo(scheme);\n\t//-----------------------------------------\n\tSetNumThreads(8);\n\t//-----------------------------------------\n\tlong fftdim = 1 << logfftdim;\n\tlong hdim = 1 << logHdim;\n\tlong slots = 1 << logSlots;\n\tCZZ*** mvecs = new CZZ**[hdim];\n\tCipher** cvecs = new Cipher*[hdim];\n\tfor (long h = 0; h < hdim; ++h) {\n\t\tmvecs[h] = new CZZ*[slots];\n\n\t\tfor (long i = 0; i < slots; ++i) {\n\t\t\tmvecs[h][i] = EvaluatorUtils::evaluateRandomVals(fftdim, precisionBits);\n\t\t}\n\n\t\tcvecs[h] = new Cipher[fftdim];\n\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tCZZ* mvals = new CZZ[slots];\n\t\t\tfor (long i = 0; i < slots; ++i) {\n\t\t\t\tmvals[i] = mvecs[h][i][j];\n\t\t\t}\n\t\t\tcvecs[h][j] = scheme.encrypt(mvals, slots);\n\t\t\tdelete[] mvals;\n\t\t}\n\t\tfor (long i = 0; i < slots; ++i) {\n\t\t\tNumUtils::fft(mvecs[h][i], fftdim, schemeaux);\n\t\t}\n\t}\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tfor (long s = logHdim - 1; s >= 0; --s) {\n\t\t\t\tlong spow = 1 << s;\n\t\t\t\tfor (long h = 0; h < spow; ++h) {\n\t\t\t\t\tmvecs[h][i][j] *= mvecs[h+spow][i][j];\n\t\t\t\t\tmvecs[h][i][j] >>= precisionBits;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (long i = 0; i < slots; ++i) {\n\t\tNumUtils::fftInvLazy(mvecs[0][i], fftdim, schemeaux);\n\t}\n\n\tfor (long h = 1; h < hdim; ++h) {\n\t\tfor (long i = 0; i < slots; ++i) {\n\t\t\tdelete[] mvecs[h][i];\n\t\t}\n\t\tdelete[] mvecs[h];\n\t}\n\n\tfor (long h = 0; h < hdim; ++h) {\n\t\ttimeutils.start(\"ciphers fft\");\n\t\talgo.fft(cvecs[h], fftdim);\n\t\ttimeutils.stop(\"ciphers fft\");\n\t}\n\tfor (long s = logHdim - 1; s >= 0; --s) {\n\t\tlong spow = 1 << s;\n\t\tfor (long h = 0; h < spow; ++h) {\n\t\t\ttimeutils.start(\"ciphers hadamard mult\");\n\t\t\talgo.multModSwitchAndEqualVec(cvecs[h], cvecs[h+spow], precisionBits, fftdim);\n\t\t\ttimeutils.stop(\"ciphers hadamard mult\");\n\t\t\tdelete[] cvecs[h+spow];\n\t\t}\n\t}\n\n\ttimeutils.start(\"ciphers fft inverse lazy\");\n\talgo.fftInvLazy(cvecs[0], fftdim);\n\ttimeutils.stop(\"ciphers fft inverse lazy\");\n\n\t//-----------------------------------------\n\tCZZ** dvec = new CZZ*[fftdim];\n\tfor (long j = 0; j < fftdim; ++j) {\n\t\tdvec[j] = scheme.decrypt(secretKey, cvecs[0][j]);\n\t}\n\tfor (long i = 0; i < slots; ++i) {\n\t\tfor (long j = 0; j < fftdim; ++j) {\n\t\t\tStringUtils::showcompare(mvecs[0][i][j], dvec[j][i], \"fft\");\n\t\t}\n\t}\n\t//-----------------------------------------\n\tcout << \"!!! END TEST FFT BATCH LAZY MULTIPLE HADAMARD !!!\" << endl;\n}\n", "meta": {"hexsha": "da9d7d207533ac3d4a5b962f617a221c17286464", "size": 29540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TestScheme.cpp", "max_stars_repo_name": "K-miran/HELR", "max_stars_repo_head_hexsha": "c94951f2691d55defc82f95d3144c831eb6c8796", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:56:15.000Z", "max_issues_repo_path": "src/TestScheme.cpp", "max_issues_repo_name": "yuejiayang/HELR", "max_issues_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-25T02:54:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-09T10:48:39.000Z", "max_forks_repo_path": "src/TestScheme.cpp", "max_forks_repo_name": "yuejiayang/HELR", "max_forks_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-01-20T13:31:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T02:20:39.000Z", "avg_line_length": 34.7938751472, "max_line_length": 138, "alphanum_fraction": 0.5650304672, "num_tokens": 8067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5635586558886433}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/MedianFilter.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass HPSS\n{\npublic:\n  using ArrayXXd = Eigen::ArrayXXd;\n  using ArrayXXcd = Eigen::ArrayXXcd;\n  using ArrayXcd = Eigen::ArrayXcd;\n\n  enum HPSSMode { kClassic, kCoupled, kAdvanced };\n\n  HPSS(index maxFFTSize, index maxHSize)\n      : mMaxH(maxFFTSize / 2 + 1, maxHSize),\n        mMaxV(maxFFTSize / 2 + 1, maxHSize),\n        mMaxBuf(maxFFTSize / 2 + 1, maxHSize)\n  {\n    mMaxH.setZero();\n    mMaxV.setZero();\n    mMaxBuf.setZero();\n  }\n\n  void init(index nBins, index hSize)\n  {\n    using namespace Eigen;\n    assert(hSize % 2);\n    assert(nBins <= mMaxBuf.rows());\n    assert(hSize <= mMaxBuf.cols());\n\n    mH = mMaxH.block(0, 0, nBins, hSize);\n    mV = mMaxV.block(0, 0, nBins, hSize);\n    mBuf = mMaxBuf.block(0, 0, nBins, hSize);\n    mH.setZero();\n    mV.setZero();\n    mBuf.setZero();\n\n    mHFilters = std::vector<MedianFilter>(asUnsigned(nBins));\n    for (index i = 0; i < nBins; i++) { mHFilters[asUnsigned(i)].init(hSize); }\n    mInitialized = true;\n  }\n\n  void processFrame(const ComplexVectorView in, ComplexMatrixView out,\n                    index vSize, index hSize, index mode, double hThresholdX1,\n                    double hThresholdY1, double hThresholdX2,\n                    double hThresholdY2, double pThresholdX1,\n                    double pThresholdY1, double pThresholdX2,\n                    double pThresholdY2)\n  {\n    using namespace Eigen;\n    assert(mInitialized);\n\n    index    h2 = (hSize - 1) / 2;\n    index    v2 = (vSize - 1) / 2;\n    index    nBins = in.size();\n    ArrayXcd frame = _impl::asEigen<Array>(in);\n    ArrayXd  mag = frame.abs().real();\n\n    mV.block(0, 0, nBins, hSize - 1) = mV.block(0, 1, nBins, hSize - 1);\n    mH.block(0, 0, nBins, hSize - 1) = mH.block(0, 1, nBins, hSize - 1);\n    mBuf.block(0, 0, nBins, hSize - 1) = mBuf.block(0, 1, nBins, hSize - 1);\n\n    ArrayXd padded = ArrayXd::Zero(2 * vSize + nBins);\n    ArrayXd resultV = ArrayXd::Zero(padded.size());\n    ArrayXd tmp = ArrayXd::Zero(padded.size());\n\n    padded.segment(v2, nBins) = mag;\n    mVFilter.init(vSize);\n    for (index i = 0; i < padded.size(); i++)\n    { tmp(i) = mVFilter.processSample(padded(i)); }\n    mV.block(0, hSize - 1, nBins, 1) = tmp.segment(v2 * 3, nBins);\n    mBuf.block(0, hSize - 1, nBins, 1) = frame;\n    ArrayXd tmpRow = ArrayXd::Zero(2 * hSize);\n    for (index i = 0; i < nBins; i++)\n    { mH(i, h2 + 1) = mHFilters[asUnsigned(i)].processSample(mag(i)); }\n    ArrayXXcd result(nBins, 3);\n    ArrayXd   harmonicMask = ArrayXd::Ones(nBins);\n    ArrayXd   percussiveMask = ArrayXd::Ones(nBins);\n    ArrayXd   residualMask =\n        mode == kAdvanced ? ArrayXd::Ones(nBins) : ArrayXd::Zero(nBins);\n    switch (mode)\n    {\n    case kClassic: {\n      ArrayXd HV = mH.col(0) + mV.col(0);\n      ArrayXd mult = (1.0 / HV.max(epsilon));\n      harmonicMask = (mH.col(0) * mult);\n      percussiveMask = (mV.col(0) * mult);\n      break;\n    }\n    case kCoupled: {\n      harmonicMask = ((mH.col(0) / mV.col(0)) >\n                      makeThreshold(nBins, hThresholdX1, hThresholdY1,\n                                    hThresholdX2, hThresholdY2))\n                         .cast<double>();\n      percussiveMask = 1 - harmonicMask;\n      break;\n    }\n    case kAdvanced: {\n      harmonicMask = ((mH.col(0) / mV.col(0)) >\n                      makeThreshold(nBins, hThresholdX1, hThresholdY1,\n                                    hThresholdX2, hThresholdY2))\n                         .cast<double>();\n      percussiveMask = ((mV.col(0) / mH.col(0)) >\n                        makeThreshold(nBins, pThresholdX1, pThresholdY1,\n                                      pThresholdX2, pThresholdY2))\n                           .cast<double>();\n      residualMask = residualMask * (1 - harmonicMask);\n      residualMask = residualMask * (1 - percussiveMask);\n      ArrayXd maskNorm =\n          (1. / (harmonicMask + percussiveMask + residualMask)).max(epsilon);\n      harmonicMask = harmonicMask * maskNorm;\n      percussiveMask = percussiveMask * maskNorm;\n      residualMask = residualMask * maskNorm;\n      break;\n    }\n    }\n    result.col(0) = mBuf.col(0) * harmonicMask.min(1.0);\n    result.col(1) = mBuf.col(0) * percussiveMask.min(1.0);\n    result.col(2) = mBuf.col(0) * residualMask.min(1.0);\n    out = _impl::asFluid(result);\n  }\n  bool initialized() { return mInitialized; }\n\nprivate:\n  Eigen::ArrayXd makeThreshold(index nBins, double x1, double y1, double x2,\n                               double y2)\n  {\n    using namespace Eigen;\n    ArrayXd threshold = ArrayXd::Ones(nBins);\n    index   kneeStart = static_cast<index>(std::floor(x1 * nBins));\n    index   kneeEnd = static_cast<index>(std::floor(x2 * nBins));\n    index   kneeLength = kneeEnd - kneeStart;\n    threshold.segment(0, kneeStart) =\n        ArrayXd::Constant(kneeStart, 10).pow(y1 / 20.0);\n    threshold.segment(kneeStart, kneeLength) =\n        ArrayXd::Constant(kneeLength, 10)\n            .pow(ArrayXd::LinSpaced(kneeLength, y1, y2) / 20.0);\n    threshold.segment(kneeEnd, nBins - kneeEnd) =\n        ArrayXd::Constant(nBins - kneeEnd, 10).pow(y2 / 20.0);\n    return threshold;\n  }\n\n  std::vector<MedianFilter> mHFilters;\n  MedianFilter              mVFilter;\n\n  ArrayXXd  mMaxH;\n  ArrayXXd  mMaxV;\n  ArrayXXcd mMaxBuf;\n  ArrayXXd  mV;\n  ArrayXXd  mH;\n  ArrayXXcd mBuf;\n  bool      mInitialized{false};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "8f36e09bacbde4fcebce7b8abbae549f2dd4925e", "size": 6025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/HPSS.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/public/HPSS.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/public/HPSS.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 34.6264367816, "max_line_length": 79, "alphanum_fraction": 0.6082987552, "num_tokens": 1796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5635156900250742}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      Montebruck O, Gill E. Satellite Orbits, Springer, 2000.\n *\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <boost/test/unit_test.hpp>\n\n#include \"tudat/astro/basic_astro/unitConversions.h\"\n#include \"tudat/basics/testMacros.h\"\n\n#include \"tudat/astro/basic_astro/geodeticCoordinateConversions.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_geodetic_coordinate_conversions )\n\nBOOST_AUTO_TEST_CASE( testGeodeticCoordinateConversions )\n{\n    using namespace coordinate_conversions;\n    using namespace unit_conversions;\n\n    // Expected Cartesian state, Montenbruck & Gill (2000) Exercise 5.3.\n    const Eigen::Vector3d testCartesianPosition( 1917032.190, 6029782.349, -801376.113 );\n\n    // Expected Cartesian state, Montenbruck & Gill (2000) Exercise 5.3.\n    const Eigen::Vector3d testGeodeticPosition( -63.667,\n                                                convertDegreesToRadians( -7.26654999 ),\n                                                convertDegreesToRadians( 72.36312094 ) );\n\n    // Central body characteristics (WGS84 Earth ellipsoid).\n    const double flattening = 1.0 / 298.257223563;\n    const double equatorialRadius = 6378137.0;\n\n    // Test conversion to geodetic coordinates.\n    {\n        // Calculate geodetic position.\n        const Eigen::Vector3d calculatedGeodeticPosition =\n                convertCartesianToGeodeticCoordinates(\n                    testCartesianPosition, equatorialRadius, flattening, 1.0E-4 );\n\n        // Compare per coefficients (different tolerances).\n        BOOST_CHECK_SMALL( calculatedGeodeticPosition.x( ) - testGeodeticPosition.x( ), 1.0E-4 );\n        BOOST_CHECK_SMALL( calculatedGeodeticPosition.y( ) - testGeodeticPosition.y( ), 1.0E-10 );\n        BOOST_CHECK_SMALL( calculatedGeodeticPosition.z( ) - testGeodeticPosition.z( ), 1.0E-10 );\n    }\n\n    // Test separate functions for altitude and geodetic latitude.\n    {\n        // Calculate altitude and geodetic latitude using dedicated functions.\n        const double directAltitude = calculateAltitudeOverOblateSpheroid(\n                    testCartesianPosition, equatorialRadius, flattening, 1.0E-4 );\n        const double directGeodeticLatitude = calculateGeodeticLatitude(\n                    testCartesianPosition, equatorialRadius, flattening, 1.0E-4 );\n\n        // Compare values.\n        BOOST_CHECK_SMALL( directAltitude - testGeodeticPosition.x( ), 1.0E-4 );\n        BOOST_CHECK_SMALL( directGeodeticLatitude - testGeodeticPosition.y( ), 1.0E-10 );\n    }\n\n    // Test conversions from geodetic coordinates to cartesian position.\n    {\n        const Eigen::Vector3d calculateCartesianPosition =\n                convertGeodeticToCartesianCoordinates(\n                    testGeodeticPosition, equatorialRadius, flattening  );\n\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                    calculateCartesianPosition, testCartesianPosition, 1.0E-9 );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "60457412cc1d809e534cd951073b115d84f1df06", "size": 3454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/astro/basic_astro/unitTestGeodeticCoordinateConversions.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/astro/basic_astro/unitTestGeodeticCoordinateConversions.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/astro/basic_astro/unitTestGeodeticCoordinateConversions.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": 38.3777777778, "max_line_length": 98, "alphanum_fraction": 0.6939779965, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5635073884587545}}
{"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": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2013-2015 Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include <rokko/rokko.hpp>\n#include <rokko/utility/frank_matrix.hpp>\n#include <boost/foreach.hpp>\n#define BOOST_TEST_MODULE test_solver\n#ifndef BOOST_TEST_DYN_LINK\n#include <boost/test/included/unit_test.hpp>\n#else\n#include <boost/test/unit_test.hpp>\n#endif\n\ntemplate<typename MATRIX_MAJOR>\nvoid test(int dim, std::string const& name) {\n  rokko::serial_dense_solver solver(name);\n  solver.initialize(boost::unit_test::framework::master_test_suite().argc,\n                    boost::unit_test::framework::master_test_suite().argv);\n  rokko::localized_matrix<double, MATRIX_MAJOR> mat(dim, dim);\n  rokko::frank_matrix::generate(mat);\n  rokko::localized_vector<double> eigval(dim);\n  rokko::localized_matrix<double, MATRIX_MAJOR> eigvec(dim, dim);\n\n  solver.diagonalize(mat, eigval, eigvec);\n  \n  double sum = 0;\n  for(int i = 0; i < dim; ++i) sum += eigval[i];\n  BOOST_CHECK_CLOSE(sum, dim * (dim+1) * 0.5, 10e-5);\n  \n  rokko::frank_matrix::generate(mat);\n  for (int i = 0; i < dim; ++i) {\n    double w = eigvec.col(i).transpose() * mat * eigvec.col(i);\n    BOOST_CHECK_CLOSE(w, eigval[i], 10e-5);\n  }\n\n  solver.finalize();\n}\n\nBOOST_AUTO_TEST_CASE(test_solver) {\n  const int dim = 100;\n  std::cout << \"dimension = \" << dim << std::endl;\n\n  std::vector<std::string> names;\n  int argc = boost::unit_test::framework::master_test_suite().argc;\n  if (argc == 1) {\n    names = rokko::serial_dense_solver::solvers();\n  } else {\n    for (int num=1; num < argc; ++num) {\n      names.push_back(boost::unit_test::framework::master_test_suite().argv[num]);\n    }\n  }\n\n  BOOST_FOREACH(std::string name, names) {\n    std::cout << \"solver = \" << name << std::endl;\n    std::cout << \"  test for row major\" << std::endl;\n    test<rokko::matrix_row_major>(dim, name);\n    std::cout << \"  test for column major\" << std::endl;\n    test<rokko::matrix_col_major>(dim, name);\n  }\n}\n", "meta": {"hexsha": "a1776cce809290457da17da19096c7a92d54dfbc", "size": 2327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/diagonalize/frank.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/diagonalize/frank.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/diagonalize/frank.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7246376812, "max_line_length": 82, "alphanum_fraction": 0.6377309841, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5634415771409499}}
{"text": "// Copyright (C) 2017 Minhyuk Sung <mhsung@cs.stanford.edu>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n//\n\n#include \"LibiglMesh.h\"\n#include <Eigen/Geometry>\n#include <utils/utils.h>\n\n\n// Mesh processing.\nDEFINE_bool(centerize, false, \"\");\nDEFINE_bool(flip_x, false, \"\");\nDEFINE_bool(flip_y, false, \"\");\nDEFINE_bool(flip_z, false, \"\");\nDEFINE_string(translation, \"\", \"(tx, ty, tz)\");\nDEFINE_string(rotation, \"\", \"(rx, ry, rz)\");\nDEFINE_string(transformation, \"\", \"(rx, ry, rz, tx, ty, tz)\");\nDEFINE_string(inverse_transformation, \"\", \"(rx, ry, rz, tx, ty, tz)\");\nDEFINE_bool(normalize_height, false, \"\");\n\n// Point set processing.\nDEFINE_bool(sample_points, false, \"\");\nDEFINE_bool(with_normals, false, \"\");\nDEFINE_int32(num_sample_points, 1024, \"\");\nDEFINE_bool(normalize_point_set, false, \"\");\nDEFINE_bool(centerize_point_set, false, \"\");\nDEFINE_string(out_point_set_center, \"\", \"\");\nDEFINE_bool(pca_align_point_set, false, \"\");\nDEFINE_string(out_pca_transformation, \"\", \"\");\n\n\nvoid LibiglMesh::mesh_processing() {\n  bool mesh_modified = false;\n\n  // Centerize.\n  if (FLAGS_centerize) {\n    V_ = V_.rowwise() - center_.transpose();\n    mesh_modified = true;\n  }\n\n  // Mesh flipping.\n  if (FLAGS_flip_x) { V_.col(0) = -V_.col(0); mesh_modified = true; }\n  if (FLAGS_flip_y) { V_.col(1) = -V_.col(1); mesh_modified = true; }\n  if (FLAGS_flip_z) { V_.col(2) = -V_.col(2); mesh_modified = true; }\n\n  if (FLAGS_translation != \"\") {\n    std::vector<std::string> strs = Utils::split_string(FLAGS_translation);\n    CHECK_EQ(strs.size(), 3);\n    Vector3d t;\n    for (int i = 0; i < 3; ++i) t[i] = std::stod(strs[i]);\n    translate_mesh(V_, t);\n    mesh_modified = true;\n  }\n\n  if (FLAGS_rotation != \"\") {\n    std::vector<std::string> strs = Utils::split_string(FLAGS_rotation);\n    CHECK_EQ(strs.size(), 3);\n    Matrix3d R = Matrix3d::Identity();\n    for (int i = 0; i < 3; ++i) {\n      const double angle = std::stod(strs[i]) / 180.0 * M_PI;\n      const AngleAxisd axis_R(angle, Vector3d::Unit(i));\n      R = axis_R.toRotationMatrix() * R;\n    }\n    const Eigen::Matrix<double, Dynamic, 3>& V_temp = V_;\n    V_ = (R * V_temp.transpose()).transpose();\n    mesh_modified = true;\n  }\n\n  if (FLAGS_transformation != \"\") {\n    std::vector<std::string> strs = Utils::split_string(FLAGS_transformation);\n    CHECK_EQ(strs.size(), 6);\n    Vector3d r, t;\n    for (int i = 0; i < 3; ++i) r[i] = std::stod(strs[0 + i]);\n    for (int i = 0; i < 3; ++i) t[i] = std::stod(strs[3 + i]);\n    transform_mesh(V_, r, t);\n    mesh_modified = true;\n  }\n\n  if (FLAGS_inverse_transformation != \"\") {\n    std::vector<std::string> strs = Utils::split_string(\n        FLAGS_inverse_transformation);\n    CHECK_EQ(strs.size(), 6);\n    Vector3d r, t;\n    for (int i = 0; i < 3; ++i) r[i] = std::stod(strs[0 + i]);\n    for (int i = 0; i < 3; ++i) t[i] = std::stod(strs[3 + i]);\n    inverse_transform_mesh(V_, r, t);\n    mesh_modified = true;\n  }\n\n  if (FLAGS_normalize_height) {\n    const double height = V_.col(1).maxCoeff() - V_.col(1).minCoeff();\n    CHECK_GT(height, 1.0E-6);\n    V_ /= height;\n  }\n\n  if (mesh_modified) {\n    update_bounding_box();\n    renderer_->set_mesh(V_, F_);\n    renderer_->set_scene_pos(center_.cast<float>(), (float)radius_);\n  }\n}\n\nvoid LibiglMesh::point_set_processing() {\n  if (FLAGS_sample_points) {\n    sample_points_on_mesh(FLAGS_num_sample_points, FLAGS_with_normals);\n  }\n\n  if (FLAGS_normalize_point_set) {\n    normalize_points();\n  }\n\n  if (FLAGS_centerize_point_set ||\n      FLAGS_out_point_set_center != \"\") {\n    compute_point_set_center_and_area(\n        FLAGS_out_point_set_center, FLAGS_centerize_point_set);\n  }\n\n  if (FLAGS_pca_align_point_set) {\n    pca_align_points(FLAGS_out_pca_transformation);\n  }\n}\n\nvoid LibiglMesh::processing() {\n  mesh_processing();\n  point_set_processing();\n}\n", "meta": {"hexsha": "47b13b6b9c73218324673e779ea69323616141d7", "size": 3958, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LibiglMesh.cc", "max_stars_repo_name": "mhsung/libigl-renderer", "max_stars_repo_head_hexsha": "b119f66946b43d989da31ccbf6929aaa7ec4e9aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-05-13T16:45:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:46:00.000Z", "max_issues_repo_path": "src/LibiglMesh.cc", "max_issues_repo_name": "mhsung/libigl-renderer", "max_issues_repo_head_hexsha": "b119f66946b43d989da31ccbf6929aaa7ec4e9aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-20T09:04:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T09:11:58.000Z", "max_forks_repo_path": "src/LibiglMesh.cc", "max_forks_repo_name": "mhsung/libigl-renderer", "max_forks_repo_head_hexsha": "b119f66946b43d989da31ccbf6929aaa7ec4e9aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-18T08:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T08:31:00.000Z", "avg_line_length": 30.4461538462, "max_line_length": 78, "alphanum_fraction": 0.649823143, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5634415696618476}}
{"text": "#include \"Polynomial.h\"\n#include <Eigen/Core>\n#include <random>\n#include \"testUtil.h\"\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\ntemplate <typename CoefficientType>\nvoid testIntegralAndDerivative() {\n  VectorXd coefficients = VectorXd::Random(5);\n  Polynomial<CoefficientType> poly(coefficients);\n  Polynomial<CoefficientType> third_derivative = poly.derivative(3);\n  Polynomial<CoefficientType> third_derivative_check = poly.derivative().derivative().derivative();\n  valuecheck(third_derivative.getCoefficients(), third_derivative_check.getCoefficients(), 1e-14);\n\n  Polynomial<CoefficientType> tenth_derivative = poly.derivative(10);\n  valuecheck(tenth_derivative.getCoefficients(), VectorXd::Zero(1), 1e-14);\n\n  Polynomial<CoefficientType> integral = poly.integral(0.0);\n  Polynomial<CoefficientType> poly_back = integral.derivative();\n  valuecheck(poly_back.getCoefficients(), poly.getCoefficients(), 1e-14);\n}\n\ntemplate <typename CoefficientType>\nvoid testOperators() {\n  int max_num_coefficients = 6;\n  int num_tests = 10;\n  default_random_engine generator;\n  std::uniform_int_distribution<> int_distribution(1, max_num_coefficients);\n  uniform_real_distribution<double> uniform;\n\n  for (int i = 0; i < num_tests; ++i) {\n    VectorXd coeff1 = VectorXd::Random(int_distribution(generator));\n    Polynomial<CoefficientType> poly1(coeff1);\n\n    VectorXd coeff2 = VectorXd::Random(int_distribution(generator));\n    Polynomial<CoefficientType> poly2(coeff2);\n\n    double scalar = uniform(generator);\n\n    Polynomial<CoefficientType> sum = poly1 + poly2;\n    Polynomial<CoefficientType> difference = poly2 - poly1;\n    Polynomial<CoefficientType> product = poly1 * poly2;\n    Polynomial<CoefficientType> poly1_plus_scalar = poly1 + scalar;\n    Polynomial<CoefficientType> poly1_minus_scalar = poly1 - scalar;\n    Polynomial<CoefficientType> poly1_scaled = poly1 * scalar;\n    Polynomial<CoefficientType> poly1_div = poly1 / scalar;\n\n    double t = uniform(generator);\n    valuecheck(sum.value(t), poly1.value(t) + poly2.value(t), 1e-8);\n    valuecheck(difference.value(t), poly2.value(t) - poly1.value(t), 1e-8);\n    valuecheck(product.value(t), poly1.value(t) * poly2.value(t), 1e-8);\n    valuecheck(poly1_plus_scalar.value(t), poly1.value(t) + scalar, 1e-8);\n    valuecheck(poly1_minus_scalar.value(t), poly1.value(t) - scalar, 1e-8);\n    valuecheck(poly1_scaled.value(t), poly1.value(t) * scalar, 1e-8);\n    valuecheck(poly1_div.value(t), poly1.value(t) / scalar, 1e-8);\n  }\n}\n\ntemplate <typename CoefficientType>\nvoid testRoots() {\n  int max_num_coefficients = 6;\n  int num_tests = 50;\n  default_random_engine generator;\n  std::uniform_int_distribution<> int_distribution(1, max_num_coefficients);\n\n  for (int i = 0; i < num_tests; ++i) {\n    VectorXd coeffs = VectorXd::Random(int_distribution(generator));\n    Polynomial<CoefficientType> poly(coeffs);\n    auto roots = poly.roots();\n    valuecheck(roots.rows(), poly.getDegree());\n    for (int i = 0; i < roots.size(); i++) {\n      auto value = poly.value(roots[i]);\n      valuecheck(std::abs(value), 0.0, 1e-8);\n    }\n  }\n}\n\nint main(int argc, char **argv) {\n\n  testIntegralAndDerivative<double>();\n  testOperators<double>();\n  testRoots<double>();\n  cout << \"test passed\" << endl;\n  return 0;\n}\n", "meta": {"hexsha": "f18fc7d17382451b92fac6e5095475b48100c9f7", "size": 3276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solvers/polynomial/test/testPolynomial.cpp", "max_stars_repo_name": "jacob-izr/drake", "max_stars_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solvers/polynomial/test/testPolynomial.cpp", "max_issues_repo_name": "jacob-izr/drake", "max_issues_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/polynomial/test/testPolynomial.cpp", "max_forks_repo_name": "jacob-izr/drake", "max_forks_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.808988764, "max_line_length": 99, "alphanum_fraction": 0.7289377289, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.7248702880639792, "lm_q1q2_score": 0.563441566802687}}
{"text": "#include \"advent.hpp\"\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <scn/scn.h>\n#include <tuple>\n\n#include <Eigen/Core>\n\nusing std::pair;\nusing std::ifstream;\nusing std::string;\nusing std::vector;\nusing Eigen::Array;\n\n\nauto day13(int argc, char** argv) -> int\n{\n    if (argc < 2) {\n        fmt::print(\"Error: no input.\");\n        return 1;\n    }\n\n    ifstream infile(argv[1]); // NOLINT\n    string line;\n\n    i64 x{0};\n    i64 y{0};\n    vector<pair<i64, i64>> points;\n    while (std::getline(infile, line)) { // NOLINT\n        if (line.empty()) { break; }\n        scn::scan(std::string(line), \"{},{}\", y, x);\n        points.emplace_back(x, y);\n    }\n    for (auto [a, b] : points) {\n        x = std::max(x, a);\n        y = std::max(y, b);\n    }\n    Array<i64, -1, -1> paper = decltype(paper)::Zero(x+1, y+1);\n    vector<pair<char, i64>> folds;\n\n    vector<string> tokens;\n    while(std::getline(infile, line)) { // NOLINT \n        tokens.clear();\n        util::tokenize(line, '=', tokens);\n        folds.emplace_back(tokens[0].back(), std::stoi(tokens[1]));\n    }\n\n    for (auto [a, b] : points) {\n        paper(a, b) = 1;\n    }\n\n    using Eigen::all;\n    using Eigen::seqN;\n\n    x = paper.rows();\n    y = paper.cols();\n\n    i64 part1{-1};\n    for (auto [c, v] : folds) {\n        auto b = paper.block(0, 0, x, y);\n        if (c == 'x') {\n            b(all, seqN(0, v)) += b(all, seqN(v+1, b.cols()-v-1)).rowwise().reverse();\n            y = v;\n        }\n        if (c == 'y') {\n            b(seqN(0, v), all) += b(seqN(v+1, b.rows()-v-1), all).colwise().reverse();\n            x = v;\n        }\n        if (part1 == -1) { part1 = (paper.block(0, 0, x, y) > 0).count(); }\n    }\n    auto b = paper.block(0, 0, x, y);\n    b = (b > 1).select(1, b);\n    for (i64 i = 0; i < x; ++i) { // NOLINT\n        for (i64 j = 0; j < y; ++j) { // NOLINT\n            auto c = b(i, j) == 1 ? '#' : ' ';\n            fmt::print(\"{} \", c);\n        }\n        fmt::print(\"\\n\");\n    }\n    fmt::print(\"part 1: {}\\n\", part1);\n\n    return 0;\n}\n", "meta": {"hexsha": "88e118c4a5c17132a4e80463c88b55814eb490d1", "size": 2054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/day13.cpp", "max_stars_repo_name": "foolnotion/aoc2021", "max_stars_repo_head_hexsha": "e2bbcd8cab2a1a7b9922694daff7d289a905c133", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/day13.cpp", "max_issues_repo_name": "foolnotion/aoc2021", "max_issues_repo_head_hexsha": "e2bbcd8cab2a1a7b9922694daff7d289a905c133", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/day13.cpp", "max_forks_repo_name": "foolnotion/aoc2021", "max_forks_repo_head_hexsha": "e2bbcd8cab2a1a7b9922694daff7d289a905c133", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-29T23:05:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T23:05:48.000Z", "avg_line_length": 23.6091954023, "max_line_length": 86, "alphanum_fraction": 0.4732229796, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.5634415558020223}}
{"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": "//==================================================================================================\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_SMALLESTPOSVAL_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_SMALLESTPOSVAL_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Smallestposval Smallestposval (function template)\n\n  Generates the least non zero, non denormal, positive value.\n\n  @headerref{<boost/simd/constant/smallestposval.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Smallestposval();\n      @endcode\n\n  2.  @code\n      template<typename T> T Smallestposval( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T that evaluates to the smallest positive, non-denormal value of\n  type @c T.\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n  A value of type @c as_integer_t<T> that evaluates to\n\n  | Type            | double                        | float         | Integral        |\n  |:----------------|:------------------------------|---------------|-----------------|\n  | **Values**      |   2.225073858507201e-308      | 1.1754944e-38 |  1              |\n\n  @par Requirements\n  - **T** models Value\n**/\n\n#include <boost/simd/constant/scalar/smallestposval.hpp>\n#include <boost/simd/constant/simd/smallestposval.hpp>\n\n#endif\n", "meta": {"hexsha": "305edf138dd5a7acd3ad66f69878b099807a0a98", "size": 1858, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/smallestposval.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/smallestposval.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/smallestposval.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 33.1785714286, "max_line_length": 100, "alphanum_fraction": 0.5113024758, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5633482771460928}}
{"text": "// Copyright (C) 2017 Minhyuk Sung <mhsung@cs.stanford.edu>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n//\n\n#include \"LibiglMesh.h\"\n\n#include <Eigen/Geometry>\n#include <utils/utils.h>\n\n\nvoid LibiglMesh::normalize_mesh(MatrixXd& _V) {\n  const auto bb_min = _V.colwise().minCoeff();\n  const auto bb_max = _V.colwise().maxCoeff();\n  const auto center = 0.5 * (bb_max + bb_min);\n  const double bbox_diagonal = (bb_max - bb_min).norm();\n  CHECK_GT(bbox_diagonal, 1.0E-6);\n\n  // Move center to (0,0,0).\n  _V = _V.rowwise() - center;\n\n  // Scale to bounding box diagonal 1.\n  _V /= bbox_diagonal;\n}\n\nvoid LibiglMesh::translate_mesh(MatrixXd& _V, const Vector3d& _t) {\n  _V = _V.rowwise() + _t.transpose();\n}\n\nvoid LibiglMesh::transform_mesh(\n    MatrixXd& _V, const Vector3d& _r, const Vector3d& _t) {\n  const double kZeroTol = 1.0e-6;\n\n  double angle = _r.norm();\n  Vector3d axis;\n  if (std::abs(angle) < kZeroTol) {\n    angle = 0.0;\n    axis = Vector3d::UnitX();\n  } else {\n    axis = _r.normalized();\n  }\n  AngleAxisd rotation(angle, axis);\n  const Matrix3d R = rotation.toRotationMatrix();\n\n  Affine3d T = Affine3d::Identity();\n  T.prerotate(R);\n  T.pretranslate(_t);\n\n  const Eigen::Matrix<double, Dynamic, 3>& V_temp = _V;\n  _V = (T * V_temp.transpose()).transpose();\n}\n\nvoid LibiglMesh::inverse_transform_mesh(\n    MatrixXd& _V, const Vector3d& _r, const Vector3d& _t) {\n  const double kZeroTol = 1.0e-6;\n\n  double angle = _r.norm();\n  Vector3d axis;\n  if (std::abs(angle) < kZeroTol) {\n    angle = 0.0;\n    axis = Vector3d::UnitX();\n  } else {\n    axis = _r.normalized();\n  }\n  AngleAxisd rotation(angle, axis);\n  const Matrix3d R = rotation.toRotationMatrix();\n\n  Affine3d T_inv = Affine3d::Identity();\n  T_inv.prerotate(R);\n  T_inv.pretranslate(_t);\n  const Affine3d T = T_inv.inverse();\n\n  const Eigen::Matrix<double, Dynamic, 3>& V_temp = _V;\n  _V = (T * V_temp.transpose()).transpose();\n}\n\n/*\nvoid LibiglMesh::transform_mesh(const std::string& _filename) {\n  Matrix4d mat;\n  if (!Utils::read_eigen_matrix_from_file(_filename, &mat)) {\n    return;\n  }\n\n  Affine3d T(mat);\n  Matrix<double, Dynamic, 3> V_copy = V_;\n  V_ = (T * V_copy.transpose()).transpose();\n\n  update_bounding_box();\n  if (renderer_ == nullptr) {\n    LOG(WARNING) << \"Renderer is not set\";\n  } else {\n    renderer_->set_mesh(V_, F_);\n    renderer_->set_scene_pos(center_.cast<float>(), (float)radius_);\n  }\n}\n*/\n\n", "meta": {"hexsha": "f2b1d05ef0bd8a0099e14ae069e8284e18cbf641", "size": 2546, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/mesh_processing.cc", "max_stars_repo_name": "mhsung/libigl-renderer", "max_stars_repo_head_hexsha": "b119f66946b43d989da31ccbf6929aaa7ec4e9aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-05-13T16:45:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:46:00.000Z", "max_issues_repo_path": "src/mesh_processing.cc", "max_issues_repo_name": "mhsung/libigl-renderer", "max_issues_repo_head_hexsha": "b119f66946b43d989da31ccbf6929aaa7ec4e9aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-20T09:04:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T09:11:58.000Z", "max_forks_repo_path": "src/mesh_processing.cc", "max_forks_repo_name": "mhsung/libigl-renderer", "max_forks_repo_head_hexsha": "b119f66946b43d989da31ccbf6929aaa7ec4e9aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-18T08:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T08:31:00.000Z", "avg_line_length": 25.46, "max_line_length": 78, "alphanum_fraction": 0.6626080126, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5633482771460928}}
{"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_MEANOF_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MEANOF_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing meanof capabilities\n\n    Computes the mean of its parameter avoiding overflow.\n\n    @par semantic:\n    For any given value @c x and @c y of type @c T:\n\n    @code\n    T r = meanof(x, y);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = (x+y)/2;\n    @endcode\n\n    @par Note:\n    Take care that for integers the value returned can differ by one unit\n    from \\c ceil((a+b)/2.0) or \\c floor((a+b)/2.0), but is always one of\n    the two values.\n\n    @see average\n\n  **/\n  Value meanof(Value const& x, Value const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/meanof.hpp>\n#include <boost/simd/function/simd/meanof.hpp>\n\n#endif\n", "meta": {"hexsha": "ef1343a3d25e5fae002bf92abd469b68bb139086", "size": 1254, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/meanof.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/meanof.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/meanof.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.2222222222, "max_line_length": 100, "alphanum_fraction": 0.5765550239, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5633482740434104}}
{"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": "// Copyright Louis Dionne 2013-2016\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/for_each.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/mult.hpp>\n#include <boost/hana/negate.hpp>\n#include <boost/hana/plus.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <string>\n#include <vector>\nnamespace hana = boost::hana;\n\n\nint main() {\n\n{\n\n//! [operators]\nBOOST_HANA_CONSTANT_CHECK(hana::int_c<1> + hana::int_c<3> == hana::int_c<4>);\n\n// Mixed-type operations are supported, but only when it involves a\n// promotion, and not a conversion that could be lossy.\nBOOST_HANA_CONSTANT_CHECK(hana::size_c<3> * hana::ushort_c<5> == hana::size_c<15>);\nBOOST_HANA_CONSTANT_CHECK(hana::llong_c<15> == hana::int_c<15>);\n//! [operators]\n\n}{\n\n//! [times_loop_unrolling]\nstd::string s;\nfor (char c = 'x'; c <= 'z'; ++c)\n    hana::int_<5>::times([&] { s += c; });\n\nBOOST_HANA_RUNTIME_CHECK(s == \"xxxxxyyyyyzzzzz\");\n//! [times_loop_unrolling]\n\n}{\n\n//! [times_higher_order]\nstd::string s;\nBOOST_HANA_CONSTEXPR_LAMBDA auto functions = hana::make_tuple(\n    [&] { s += \"x\"; },\n    [&] { s += \"y\"; },\n    [&] { s += \"z\"; }\n);\nhana::for_each(functions, hana::int_<5>::times);\nBOOST_HANA_RUNTIME_CHECK(s == \"xxxxxyyyyyzzzzz\");\n//! [times_higher_order]\n\n}{\n\n//! [from_object]\nstd::string s;\nfor (char c = 'x'; c <= 'z'; ++c)\n    hana::int_c<5>.times([&] { s += c; });\n\nBOOST_HANA_RUNTIME_CHECK(s == \"xxxxxyyyyyzzzzz\");\n//! [from_object]\n\n}{\n\n//! [times_with_index_runtime]\nstd::vector<int> v;\nhana::int_<5>::times.with_index([&](auto index) { v.push_back(index); });\n\nBOOST_HANA_RUNTIME_CHECK(v == std::vector<int>{0, 1, 2, 3, 4});\n//! [times_with_index_runtime]\n\n//! [times_with_index_compile_time]\nconstexpr auto xs = hana::tuple_c<int, 0, 1, 2>;\nhana::int_<3>::times.with_index([xs](auto index) {\n    BOOST_HANA_CONSTANT_CHECK(xs[index] == index);\n});\n//! [times_with_index_compile_time]\n\n}{\n\n//! [literals]\nusing namespace hana::literals; // contains the _c suffix\n\nBOOST_HANA_CONSTANT_CHECK(1234_c == hana::llong_c<1234>);\nBOOST_HANA_CONSTANT_CHECK(-1234_c == hana::llong_c<-1234>);\nBOOST_HANA_CONSTANT_CHECK(1_c + (3_c * 4_c) == hana::llong_c<1 + (3 * 4)>);\n//! [literals]\n\n}{\n\n//! [integral_c]\nBOOST_HANA_CONSTANT_CHECK(hana::integral_c<int, 2> == hana::int_c<2>);\nstatic_assert(decltype(hana::integral_c<int, 2>)::value == 2, \"\");\n//! [integral_c]\n\n}\n\n}\n", "meta": {"hexsha": "c86c81cd73f1065835f06df23ce65517c22334f8", "size": 2569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.62.0/libs/hana/example/integral_constant.cpp", "max_stars_repo_name": "sita1999/arangodb", "max_stars_repo_head_hexsha": "6a4f462fa209010cd064f99e63d85ce1d432c500", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2016-03-04T15:44:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T11:06:25.000Z", "max_issues_repo_path": "3rdParty/boost/1.62.0/libs/hana/example/integral_constant.cpp", "max_issues_repo_name": "lipper/arangodb", "max_issues_repo_head_hexsha": "66ea1fd4946668192e3f0d1060f0844f324ad7b8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2016-02-29T17:59:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-05T04:59:26.000Z", "max_forks_repo_path": "3rdParty/boost/1.62.0/libs/hana/example/integral_constant.cpp", "max_forks_repo_name": "lipper/arangodb", "max_forks_repo_head_hexsha": "66ea1fd4946668192e3f0d1060f0844f324ad7b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-11-02T09:37:09.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-05T06:38:49.000Z", "avg_line_length": 25.1862745098, "max_line_length": 83, "alphanum_fraction": 0.6753600623, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.5633229988925524}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Vector3d v(1,2,3);\nv.array() += 3;\nv.array() -= 2;\ncout << v << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "686b5c4abc55b221762f4809621c2892a5d78ebb", "size": 221, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_array.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_array.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_array.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.0, "max_line_length": 22, "alphanum_fraction": 0.6244343891, "num_tokens": 70, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.563271503863721}}
{"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": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// Polygon Overlay Example\r\n\r\n#include <fstream>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\n#include <boost/foreach.hpp>\r\n\r\n\r\n#include <boost/geometry/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/geometries/adapted/c_array.hpp>\r\n\r\n#if defined(HAVE_SVG)\r\n#  include <boost/geometry/io/svg/svg_mapper.hpp>\r\n#endif\r\n\r\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\r\n\r\n\r\nint main(void)\r\n{\r\n    namespace bg = boost::geometry;\r\n\r\n    typedef bg::model::d2::point_xy<double> point_2d;\r\n    typedef bg::model::polygon<point_2d> polygon_2d;\r\n\r\n\r\n#if defined(HAVE_SVG)\r\n    std::ofstream stream(\"05_a_intersection_polygon_example.svg\");\r\n    bg::svg_mapper<point_2d> svg(stream, 500, 500);\r\n#endif\r\n\r\n    // Define a polygons and fill the outer rings.\r\n    polygon_2d a;\r\n    {\r\n        const double c[][2] = {\r\n            {160, 330}, {60, 260}, {20, 150}, {60, 40}, {190, 20}, {270, 130}, {260, 250}, {160, 330}\r\n        };\r\n        bg::assign_points(a, c);\r\n    }\r\n    bg::correct(a);\r\n    std::cout << \"A: \" << bg::dsv(a) << std::endl;\r\n\r\n    polygon_2d b;\r\n    {\r\n        const double c[][2] = {\r\n            {300, 330}, {190, 270}, {150, 170}, {150, 110}, {250, 30}, {380, 50}, {380, 250}, {300, 330}\r\n        };\r\n        bg::assign_points(b, c);\r\n    }\r\n    bg::correct(b);\r\n    std::cout << \"B: \" << bg::dsv(b) << std::endl;\r\n#if defined(HAVE_SVG)\r\n    svg.add(a);\r\n    svg.add(b);\r\n\r\n    svg.map(a, \"opacity:0.6;fill:rgb(0,255,0);\");\r\n    svg.map(b, \"opacity:0.6;fill:rgb(0,0,255);\");\r\n#endif\r\n\r\n\r\n    // Calculate interesection(s)\r\n    std::vector<polygon_2d> intersection;\r\n    bg::intersection(a, b, intersection);\r\n\r\n    std::cout << \"Intersection of polygons A and B\" << std::endl;\r\n    BOOST_FOREACH(polygon_2d const& polygon, intersection)\r\n    {\r\n        std::cout << bg::dsv(polygon) << std::endl;\r\n#if defined(HAVE_SVG)\r\n        svg.map(polygon, \"opacity:0.5;fill:none;stroke:rgb(255,0,0);stroke-width:6\");\r\n#endif\r\n    }\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "3ed7ed12bab77e0f6482d773f7f6ee05caa6a318", "size": 2510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/example/05_a_overlay_polygon_example.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/example/05_a_overlay_polygon_example.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/example/05_a_overlay_polygon_example.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 27.8888888889, "max_line_length": 105, "alphanum_fraction": 0.6147410359, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5631685295273229}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <unordered_map>\n#include <Eigen/Dense>\n#include \"../include/model.h\"\n#include \"../include/optimizer.h\"\n#include \"../datasets/include/mnist.h\"\n#include <matplotlibcpp.h>\n\nusing namespace Eigen;\nnamespace plt = matplotlibcpp;\n\nint main()\n{\n    using std::cout;\n    using std::endl;\n    using std::unordered_map;\n    using std::vector;\n    using namespace MyDL;\n\n    // ----------------------\n    // parameters\n    // ----------------------\n    int num_iters = 6000;        // \u4eca\u5f8c\u306e\u305f\u3081\u306b\u3001\u3053\u306e\u8fba\u306e\u5024\u3092JSON\u7b49\u304b\u3089\u8aad\u307f\u8fbc\u3081\u308b\u4ed5\u7d44\u307f\u3092\u4f5c\u308b(=>\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0\u306e\u5b9f\u88c5\u304c\u6b63\u3057\u3051\u308c\u3070\u3001\u30d1\u30e9\u30e1\u30fc\u30bf\u306f\u8a2d\u5b9a\u30d5\u30a1\u30a4\u30eb\u3067\u7ba1\u7406)\n    double learning_rate = 0.05; // \u6d6e\u52d5\u5c0f\u6570\u70b9\u3067\u5ba3\u8a00\u3059\u308b\u3053\u3068\u3002\u3046\u3063\u304b\u308aint\u578b\u306b\u3059\u308b\u30680\u306b\u306a\u308b\u306e\u3067\u3001\u52fe\u914d\u304c\u66f4\u65b0\u3067\u304d\u306a\u3044\n\n    int batch_size = 100;\n    int input_size = 28 * 28;\n    int hidden_size = 50;\n    int output_size = 10;\n\n    // ----------------------\n    // Data Loader\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    // ----------------------\n    // DNN\n    // ----------------------\n    TwoLayerMLP model(input_size, hidden_size, output_size);\n\n    // ----------------------\n    // Optimizer\n    // ----------------------\n\n    // SGD optimizer(0.05);\n    // Momentum optimizer(0.01, 0.99);\n    // AdaGrad optimizer(0.001);\n    // RMSprop optimizer(0.001, 0.999);\n    Adam optimizer(0.001, 0.9, 0.999);\n\n    // ----------------------\n    // \u30c7\u30fc\u30bf\u683c\u7d0d\u7528\n    // ----------------------\n    vector<MatrixXd> inputs, loss, val_inputs;\n    unordered_map<string, MatrixXd> grads;\n    double accuracy;\n    // ----------------------\n    // For Visualization\n    // ----------------------\n    vector<double> loss_history(num_iters), accuracy_history(num_iters / 10);\n    vector<int> loss_counter(num_iters), accuracy_counter(num_iters / 10);\n\n    // ----------------------\n    // Learning Loop\n    // ----------------------\n    for (int i = 0; i < num_iters; i++)\n    {\n        mnist.next_train(train_X, train_y);\n        inputs.push_back(train_X);\n        // inputs.push_back(train_y);\n\n        // Back Propagation\n        grads = model.gradient(inputs, train_y);\n\n        // Update Prameters\n        optimizer.update(model.params, grads);\n\n        // Loss Calculation\n        loss = model.loss(inputs, train_y);\n        loss_history[i] = loss[0](0);\n        loss_counter[i] = i;\n\n        cout << \"iter\" << i << \" loss: \" << loss[0] << endl;\n\n        if (i % 10 == 0)\n        {\n            mnist.next_test(test_X, test_y);\n            val_inputs.push_back(test_X);\n            // val_inputs.push_back(test_y);\n            accuracy = model.accuracy(val_inputs, test_y);\n            cout << \"accuracy: \" << accuracy << endl;\n            val_inputs.clear();\n            accuracy_history[i / 10] = accuracy;\n            accuracy_counter[i / 10] = i / 10;\n        }\n\n        inputs.clear();\n    }\n\n    return 0;\n}", "meta": {"hexsha": "a3537c1326fb131d314db9c6f5f46db89ef5ff16", "size": 3031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/train_two_layer_mlp.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/train_two_layer_mlp.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/train_two_layer_mlp.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0648148148, "max_line_length": 102, "alphanum_fraction": 0.5357967667, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5631584586649493}}
{"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": "\ufeff// ConsoleApplication1.cpp : \u6b64\u6587\u4ef6\u5305\u542b \"main\" \u51fd\u6570\u3002\u7a0b\u5e8f\u6267\u884c\u5c06\u5728\u6b64\u5904\u5f00\u59cb\u5e76\u7ed3\u675f\u3002\r\n#include <iostream>\r\nusing namespace std;\r\n#include <ctime>\r\n// Eigen \u90e8\u5206\r\n#include <Eigen/Core>\r\n//\u6620\u5165Cholesky\r\n#include <Eigen/Cholesky>\r\n// \u7a20\u5bc6\u77e9\u9635\u7684\u4ee3\u6570\u8fd0\u7b97\uff08\u9006\uff0c\u7279\u5f81\u503c\u7b49\uff09\r\n#include <Eigen/Sparse>\r\n#include <Eigen/Dense>\r\nusing namespace Eigen;     // \u6539\u6210\u8fd9\u6837\u4ea6\u53ef 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    // \u89e3\u65b9\u7a0b\r\n    // \u6211\u4eec\u6c42\u89e3 A * x = b \u8fd9\u4e2a\u65b9\u7a0b\r\n    // \u76f4\u63a5\u6c42\u9006\u81ea\u7136\u662f\u6700\u76f4\u63a5\u7684\uff0c\u4f46\u662f\u6c42\u9006\u8fd0\u7b97\u91cf\u5927\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(); // \u8ba1\u65f6\r\n    //Cholesky \u89e3\u65b9\u7a0b\r\n\r\n\r\n    // \u76f4\u63a5\u6c42\u9006\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\u5206\u89e3colPivHouseholderQr()\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\u5206\u89e3fullPivHouseholderQr()\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\u5206\u89e3 \u8981\u6c42\u77e9\u9635A\u6b63\u5b9a\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\u5206\u89e3  \u8981\u6c42\u77e9\u9635A\u6b63\u6216\u8d1f\u534a\u5b9a\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\u5206\u89e3 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\u5206\u89e3\uff08fullPivLu()\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// \u8fd0\u884c\u7a0b\u5e8f: Ctrl + F5 \u6216\u8c03\u8bd5 >\u201c\u5f00\u59cb\u6267\u884c(\u4e0d\u8c03\u8bd5)\u201d\u83dc\u5355\r\n// \u8c03\u8bd5\u7a0b\u5e8f: F5 \u6216\u8c03\u8bd5 >\u201c\u5f00\u59cb\u8c03\u8bd5\u201d\u83dc\u5355\r\n\r\n// \u5165\u95e8\u4f7f\u7528\u6280\u5de7: \r\n//   1. \u4f7f\u7528\u89e3\u51b3\u65b9\u6848\u8d44\u6e90\u7ba1\u7406\u5668\u7a97\u53e3\u6dfb\u52a0/\u7ba1\u7406\u6587\u4ef6\r\n//   2. \u4f7f\u7528\u56e2\u961f\u8d44\u6e90\u7ba1\u7406\u5668\u7a97\u53e3\u8fde\u63a5\u5230\u6e90\u4ee3\u7801\u7ba1\u7406\r\n//   3. \u4f7f\u7528\u8f93\u51fa\u7a97\u53e3\u67e5\u770b\u751f\u6210\u8f93\u51fa\u548c\u5176\u4ed6\u6d88\u606f\r\n//   4. \u4f7f\u7528\u9519\u8bef\u5217\u8868\u7a97\u53e3\u67e5\u770b\u9519\u8bef\r\n//   5. \u8f6c\u5230\u201c\u9879\u76ee\u201d>\u201c\u6dfb\u52a0\u65b0\u9879\u201d\u4ee5\u521b\u5efa\u65b0\u7684\u4ee3\u7801\u6587\u4ef6\uff0c\u6216\u8f6c\u5230\u201c\u9879\u76ee\u201d>\u201c\u6dfb\u52a0\u73b0\u6709\u9879\u201d\u4ee5\u5c06\u73b0\u6709\u4ee3\u7801\u6587\u4ef6\u6dfb\u52a0\u5230\u9879\u76ee\r\n//   6. \u5c06\u6765\uff0c\u82e5\u8981\u518d\u6b21\u6253\u5f00\u6b64\u9879\u76ee\uff0c\u8bf7\u8f6c\u5230\u201c\u6587\u4ef6\u201d>\u201c\u6253\u5f00\u201d>\u201c\u9879\u76ee\u201d\u5e76\u9009\u62e9 .sln \u6587\u4ef6\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 \"EdgeOperations2d.h\"\n\n#include <wmtk/TriMesh.h>\n#include <wmtk/utils/VectorUtils.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <wmtk/ExecutionScheduler.hpp>\n\nusing namespace Edge2d;\nusing namespace wmtk;\n\nauto renew = [](auto& m, auto op, auto& tris) {\n    auto edges = m.new_edges_after(tris);\n    auto optup = std::vector<std::pair<std::string, TriMesh::Tuple>>();\n    for (auto& e : edges) optup.emplace_back(op, e);\n    return optup;\n};\n\nauto edge_locker = [](auto& m, const auto& e, int task_id) -> bool {\n    return m.try_set_edge_mutex_two_ring(e, task_id);\n};\n\ndouble EdgeOperations2d::compute_edge_cost_collapse_ar(const TriMesh::Tuple& t, double L) const\n{\n    double l = (vertex_attrs[t.vid(*this)].pos - vertex_attrs[t.switch_vertex(*this).vid(*this)].pos).norm();\n    if (l < (4. / 5.) * L) return ((4. / 5.) * L - l);\n    return -1;\n}\ndouble EdgeOperations2d::compute_edge_cost_split_ar(const TriMesh::Tuple& t, double L) const\n{\n    double l = (vertex_attrs[t.vid(*this)].pos - vertex_attrs[t.switch_vertex(*this).vid(*this)].pos).norm();\n    if (l > (4. / 3.) * L) return (l - (4. / 3.) * L);\n    return -1;\n}\n\ndouble EdgeOperations2d::compute_vertex_valence_ar(const TriMesh::Tuple& t) const\n{\n    std::vector<std::pair<TriMesh::Tuple, int>> valences(3);\n    valences[0] = std::make_pair(t, get_one_ring_tris_for_vertex(t).size());\n    auto t2 = t.switch_vertex(*this);\n    valences[1] = std::make_pair(t2, get_one_ring_tris_for_vertex(t2).size());\n    auto t3 = (t.switch_edge(*this)).switch_vertex(*this);\n    valences[2] = std::make_pair(t3, get_one_ring_tris_for_vertex(t3).size());\n\n    if ((t.switch_face(*this)).has_value()) {\n        auto t4 = (((t.switch_face(*this)).value()).switch_edge(*this)).switch_vertex(*this);\n        valences.emplace_back(t4, get_one_ring_tris_for_vertex(t4).size());\n    }\n    double cost_before_swap = 0.0;\n    double cost_after_swap = 0.0;\n\n    // check if it's internal vertex or bondary vertex\n    // navigating starting one edge and getting back to the start\n\n    for (int i = 0; i < valences.size(); i++) {\n        TriMesh::Tuple vert = valences[i].first;\n        int val = 6;\n        auto one_ring_edges = get_one_ring_edges_for_vertex(vert);\n        for (auto edge : one_ring_edges) {\n            if (is_boundary_edge(edge)) {\n                val = 4;\n                break;\n            }\n        }\n        cost_before_swap += (double)(valences[i].second - val) * (valences[i].second - val);\n        cost_after_swap +=\n            (i < 2) ? (double)(valences[i].second - 1 - val) * (valences[i].second - 1 - val)\n                    : (double)(valences[i].second + 1 - val) * (valences[i].second + 1 - val);\n    }\n    return (cost_before_swap - cost_after_swap);\n}\n\nstd::vector<double> EdgeOperations2d::average_len_valen()\n{\n    double average_len = 0.0;\n    double average_valen = 0.0;\n    auto edges = get_edges();\n    auto verts = get_vertices();\n    double maxlen = std::numeric_limits<double>::min();\n    double maxval = std::numeric_limits<double>::min();\n    double minlen = std::numeric_limits<double>::max();\n    double minval = std::numeric_limits<double>::max();\n    for (auto& loc : edges) {\n        double currentlen =\n            (vertex_attrs[loc.vid(*this)].pos - vertex_attrs[loc.switch_vertex(*this).vid(*this)].pos).norm();\n        average_len += currentlen;\n        if (maxlen < currentlen) maxlen = currentlen;\n        if (minlen > currentlen) minlen = currentlen;\n    }\n    average_len /= edges.size();\n    for (auto& loc : verts) {\n        double currentval = get_one_ring_edges_for_vertex(loc).size();\n        average_valen += currentval;\n        if (maxval < currentval) maxval = currentval;\n        if (minval > currentval) minval = currentval;\n    }\n    average_valen /= verts.size();\n    int cnt = 0;\n    std::vector<double> rtn{average_len, maxlen, minlen, average_valen, maxval, minval};\n    return rtn;\n}\n\nstd::vector<TriMesh::Tuple> Edge2d::EdgeOperations2d::new_edges_after_swap(\n    const TriMesh::Tuple& t) const\n{\n    std::vector<TriMesh::Tuple> new_edges;\n    std::vector<size_t> one_ring_fid;\n\n    new_edges.push_back(t.switch_edge(*this));\n    new_edges.push_back((t.switch_face(*this).value()).switch_edge(*this));\n    new_edges.push_back((t.switch_vertex(*this)).switch_edge(*this));\n    new_edges.push_back(((t.switch_vertex(*this)).switch_face(*this).value()).switch_edge(*this));\n    return new_edges;\n}\n\nbool EdgeOperations2d::collapse_remeshing(double L)\n{\n    auto collect_all_ops = std::vector<std::pair<std::string, Tuple>>();\n    for (auto& loc : get_edges()) collect_all_ops.emplace_back(\"edge_collapse\", loc);\n\n    auto setup_and_execute = [&](auto executor) {\n        executor.renew_neighbor_tuples = renew;\n        executor.priority = [&](auto& m, auto _, auto& e) {\n            return -m.compute_edge_cost_collapse_ar(e, L);\n        };\n        executor.lock_vertices = edge_locker;\n\n        executor.is_weight_up_to_date = [](auto& m, auto& ele) {\n            auto& [val, op, e] = ele;\n            if (val > 0) return false; // priority is negated.\n            return true;\n        };\n        executor(*this, collect_all_ops);\n    };\n    if (NUM_THREADS > 0) {\n        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kSeq>();\n        setup_and_execute(executor);\n    } else {\n        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kPartition>();\n        setup_and_execute(executor);\n    }\n\n    return true;\n}\nbool EdgeOperations2d::split_remeshing(double L)\n{\n    auto collect_all_ops = std::vector<std::pair<std::string, Tuple>>();\n    for (auto& loc : get_edges()) collect_all_ops.emplace_back(\"edge_split\", loc);\n\n    auto setup_and_execute = [&](auto executor) {\n        executor.num_threads = NUM_THREADS;\n\n        executor.lock_vertices = edge_locker;\n\n        executor.renew_neighbor_tuples = renew;\n        executor.priority = [&](auto& m, auto _, auto& e) {\n            return m.compute_edge_cost_split_ar(e, L);\n        };\n        executor.is_weight_up_to_date = [](auto& m, auto& ele) {\n            auto& [val, op, e] = ele;\n            if (val < 0) return false;\n            return true;\n        };\n        executor(*this, collect_all_ops);\n    };\n    if (NUM_THREADS > 0) {\n        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kSeq>();\n        setup_and_execute(executor);\n    } else {\n        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kPartition>();\n        setup_and_execute(executor);\n    }\n\n    return true;\n}\n\n\nbool EdgeOperations2d::swap_remeshing()\n{\n    auto collect_all_ops = std::vector<std::pair<std::string, Tuple>>();\n    for (auto& loc : get_edges()) collect_all_ops.emplace_back(\"edge_swap\", loc);\n\n    auto setup_and_execute = [&](auto executor) {\n        executor.renew_neighbor_tuples = renew;\n        executor.priority = [](auto& m, auto op, const Tuple& e) {\n            return m.compute_vertex_valence_ar(e);\n        };\n        executor.lock_vertices = edge_locker;\n        executor.is_weight_up_to_date = [](auto& m, auto& ele) {\n            auto& [val, _, e] = ele;\n            auto val_energy = (m.compute_vertex_valence_ar(e));\n            return (val_energy > 1e-5);\n        };\n        executor(*this, collect_all_ops);\n    };\n    if (NUM_THREADS > 0) {\n        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kSeq>();\n        setup_and_execute(executor);\n    } else {\n        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kPartition>();\n        setup_and_execute(executor);\n    }\n\n    return true;\n}\ndouble area(EdgeOperations2d& m, std::array<TriMesh::Tuple, 3>& verts)\n{\n    return ((m.vertex_attrs[verts[0].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos)\n                .cross(m.vertex_attrs[verts[1].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos))\n               .norm() /\n           2.0;\n};\n\nEigen::Vector3d normal(EdgeOperations2d& m, std::array<TriMesh::Tuple, 3>& verts)\n{\n    return ((m.vertex_attrs[verts[0].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos)\n                .cross(m.vertex_attrs[verts[1].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos))\n        .normalized();\n}\n\nEigen::Vector3d EdgeOperations2d::tangential_smooth(const Tuple& t)\n{\n    auto one_ring_tris = get_one_ring_tris_for_vertex(t);\n    if (one_ring_tris.size() < 2) return vertex_attrs[t.vid(*this)].pos;\n    Eigen::Vector3d after_smooth = smooth(t);\n    // get normal and area of each face\n    auto area = [](auto& m, auto& verts) {\n        return ((m.vertex_attrs[verts[0].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos)\n                    .cross(m.vertex_attrs[verts[1].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos))\n                   .norm() /\n               2.0;\n    };\n    auto normal = [](auto& m, auto& verts) {\n        return ((m.vertex_attrs[verts[0].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos)\n                    .cross(m.vertex_attrs[verts[1].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos))\n            .normalized();\n    };\n    auto w0 = 0.0;\n    Eigen::Vector3d n0(0.0, 0.0, 0.0);\n    for (auto& e : one_ring_tris) {\n        auto verts = oriented_tri_vertices(e);\n        w0 += area(*this, verts);\n        n0 += area(*this, verts) * normal(*this, verts);\n    }\n    n0 /= w0;\n    after_smooth += n0 * n0.transpose() * (vertex_attrs[t.vid(*this)].pos - after_smooth);\n    return after_smooth;\n}\n\n\nbool EdgeOperations2d::adaptive_remeshing(double L, int iterations, int sm)\n{\n    std::vector<double> avg_lens, max_lens, min_lens;\n    std::vector<double> avg_valens, max_vals, min_vals;\n    int cnt = 0;\n    auto properties = average_len_valen();\n    while ((properties[0] - L) * (properties[0] - L) > 1e-8 && cnt < iterations) {\n        cnt++;\n        avg_lens.push_back(properties[0]);\n        avg_valens.push_back(properties[3]);\n        max_lens.push_back(properties[1]);\n        max_vals.push_back(properties[4]);\n        min_lens.push_back(properties[2]);\n        min_vals.push_back(properties[5]);\n\n        // split\n        split_remeshing(L);\n        // collpase\n        collapse_remeshing(L);\n\n        // swap edges\n        swap_remeshing();\n        // smoothing\n        auto vertices = get_vertices();\n        if (sm == 0) {\n            for (auto& loc : vertices) vertex_attrs[loc.vid(*this)].pos = smooth(loc);\n        } else\n            for (auto& loc : vertices) vertex_attrs[loc.vid(*this)].pos = tangential_smooth(loc);\n\n        assert(check_mesh_connectivity_validity());\n        consolidate_mesh();\n        properties = average_len_valen();\n    }\n    wmtk::logger().info(\"avg edge len after each remesh is: \");\n    wmtk::vector_print(avg_lens);\n    wmtk::logger().info(\"max edge len after each remesh is: \");\n    wmtk::vector_print(max_lens);\n    wmtk::logger().info(\"min edge len after each remesh is: \");\n    wmtk::vector_print(min_lens);\n\n\n    wmtk::logger().info(\"avg valence after each remesh is: \");\n    wmtk::vector_print(avg_valens);\n    wmtk::logger().info(\"max valence after each remesh is: \");\n    wmtk::vector_print(max_vals);\n    wmtk::logger().info(\"min valence after each remesh is: \");\n    wmtk::vector_print(min_vals);\n    return true;\n}", "meta": {"hexsha": "ff22040cd1055c542c151504eb5d86f0197c7806", "size": 11220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "attic/EdgeOperations2d/AdaptiveRemeshing.cpp", "max_stars_repo_name": "wildmeshing/wildmeshing-toolkit", "max_stars_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T08:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:19:41.000Z", "max_issues_repo_path": "attic/EdgeOperations2d/AdaptiveRemeshing.cpp", "max_issues_repo_name": "wildmeshing/wildmeshing-toolkit", "max_issues_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 86.0, "max_issues_repo_issues_event_min_datetime": "2021-12-03T01:46:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T19:33:17.000Z", "max_forks_repo_path": "attic/EdgeOperations2d/AdaptiveRemeshing.cpp", "max_forks_repo_name": "wildmeshing/wildmeshing-toolkit", "max_forks_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-26T08:29:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T22:10:42.000Z", "avg_line_length": 37.525083612, "max_line_length": 110, "alphanum_fraction": 0.6259358289, "num_tokens": 3025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5631584423131855}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/algorithm.h>\n#include <CGAL/Random.h>\n#include <CGAL/Timer.h>\n\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/random.hpp>\n\n\n#include <cassert>\n#include <iostream>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n\ntypedef CGAL::Triangulation_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 CDT::Point          Point;\n\ntypedef CGAL::Creator_uniform_2<double, Point>             Creator;\ntypedef CGAL::Random_points_in_square_2<Point, Creator> Point_generator;\n\n\nint main(int argc,char** argv )\n{\n  int n_segments=100000;\n  if (argc==2) n_segments=atoi(argv[1]);\n  \n  \n  CGAL::Random rand(0);\n  std::vector<Point> point_set;\n  point_set.reserve(2*n_segments);\n  \n  CGAL::cpp11::copy_n(Point_generator(1,rand), 2*n_segments,std::back_inserter(point_set));\n\n  std::cout << point_set.size()/2  << \" segments\" << std::endl;\n  \n  CDT cdt;\n\n  CGAL::Timer time;\n  time.start();\n  cdt.insert( point_set.begin(),point_set.end() );\n  time.stop();\n  \n  std::cout << \"Inserting points in \" << time.time() << std::endl;\n  time.reset();\n  \n  std::vector<CDT::Vertex_handle> vertex_handles;\n  vertex_handles.reserve(2*n_segments);\n  \n  for (CDT::Finite_vertices_iterator vit=cdt.finite_vertices_begin(),\n                                     vit_end=cdt.finite_vertices_end();vit!=vit_end;++vit)\n  {\n    vertex_handles.push_back(vit);\n  }\n  \n  boost::rand48 random;\n  boost::random_number_generator<boost::rand48> rng(random);\n  std::random_shuffle(vertex_handles.begin(),vertex_handles.end(),rng);\n  \n  time.start();\n  for (int i=0;i<n_segments;++i){\n    cdt.insert_constraint( vertex_handles[2*i],vertex_handles[2*i+1] );\n  }\n  time.stop();\n  \n  std::cout << \"Adding constraints in \" << time.time() << std::endl;\n  \n  std::cout << cdt.number_of_vertices()-static_cast<unsigned>(2*n_segments) << \" intersection points\\n\";\n  \n  return 0;\n}\n", "meta": {"hexsha": "6075b23de803fba421d64bc187d2434daaccf3c4", "size": 2362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Triangulation_2/benchmark/Triangulation_2/CDT_with_intersection_2.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/Triangulation_2/benchmark/Triangulation_2/CDT_with_intersection_2.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/Triangulation_2/benchmark/Triangulation_2/CDT_with_intersection_2.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": 30.2820512821, "max_line_length": 104, "alphanum_fraction": 0.6943268417, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.5631584368137875}}
{"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": "\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <limits>\n\n#include <boost/multiprecision/integer.hpp>\n\n#include <fc/uint128.hpp>\n\nusing fc::uint128_t;\n\nuint8_t find_msb( const uint128_t& u )\n{\n   uint64_t x;\n   uint8_t places;\n   x      = (u.lo ? u.lo : 1);\n   places = (u.hi ?   64 : 0);\n   x      = (u.hi ? u.hi : x);\n   return uint8_t( boost::multiprecision::detail::find_msb(x) + places );\n}\n\nuint64_t maybe_sqrt( uint64_t x )\n{\n   if( x <= 1 )\n      return 0;\n   assert( x <= std::numeric_limits< uint64_t >::max()/2 );\n\n   uint8_t n = uint8_t( boost::multiprecision::detail::find_msb(x) );\n   uint8_t b = n&1;\n   uint64_t y = x + (uint64_t(1) << (n-(1-b)));\n   y = y >> ((n >> 1)+b+1);\n   return y;\n}\n\nuint64_t approx_sqrt( const uint128_t& x )\n{\n   if( (x.lo == 0) && (x.hi == 0) )\n      return 0;\n\n   uint8_t msb_x = find_msb(x);\n   uint8_t msb_z = msb_x >> 1;\n\n   uint128_t msb_x_bit = uint128_t(1) << msb_x;\n   uint64_t  msb_z_bit = uint64_t (1) << msb_z;\n\n   uint128_t mantissa_mask = msb_x_bit - 1;\n   uint128_t mantissa_x = x & mantissa_mask;\n   uint64_t mantissa_z_hi = (msb_x & 1) ? msb_z_bit : 0;\n   uint64_t mantissa_z_lo = (mantissa_x >> (msb_x - msb_z)).lo;\n   uint64_t mantissa_z = (mantissa_z_hi | mantissa_z_lo) >> 1;\n   uint64_t result = msb_z_bit | mantissa_z;\n\n   return result;\n}\n\nint main( int argc, char** argv, char** envp )\n{\n   uint128_t x = 0;\n   while( true )\n   {\n      uint64_t y = approx_sqrt(x);\n      std::cout << std::string(x) << \" \" << y << std::endl;\n      //uint128_t new_x = x + (x >> 10) + 1;\n      uint128_t new_x = x + (x / 1000) + 1;\n      if( new_x < x )\n         break;\n      x = new_x;\n   }\n   return 0;\n}\n", "meta": {"hexsha": "c8d3360f7a4a188db749450b7374576c99a43b7e", "size": 1675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "programs/util/test_sqrt.cpp", "max_stars_repo_name": "dls-cipher/smoked", "max_stars_repo_head_hexsha": "59e7264d63debb446602dcbc34f3251298ece07d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2189.0, "max_stars_repo_stars_event_min_datetime": "2016-04-02T21:49:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:31:07.000Z", "max_issues_repo_path": "programs/util/test_sqrt.cpp", "max_issues_repo_name": "dls-cipher/smoked", "max_issues_repo_head_hexsha": "59e7264d63debb446602dcbc34f3251298ece07d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2798.0, "max_issues_repo_issues_event_min_datetime": "2016-04-11T18:01:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T23:05:39.000Z", "max_forks_repo_path": "programs/util/test_sqrt.cpp", "max_forks_repo_name": "dls-cipher/smoked", "max_forks_repo_head_hexsha": "59e7264d63debb446602dcbc34f3251298ece07d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 908.0, "max_forks_repo_forks_event_min_datetime": "2016-03-23T18:26:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T21:43:27.000Z", "avg_line_length": 23.2638888889, "max_line_length": 73, "alphanum_fraction": 0.5832835821, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.563108165450152}}
{"text": "#include <iostream>\n#include <boost/math/common_factor.hpp>\n\nint main()\n{\n\tboost::uint32_t x = 250000;\n\tboost::uint32_t y = 5000000;\n\t\n\tstd::cout << \"lcm(\" << x << \", \" << y << \") == \" << boost::math::lcm<boost::uint32_t>(x, y) << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "8cbee163dac999ae9cf23d055216ec8136f303bd", "size": 256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/math/boost_lcm.cpp", "max_stars_repo_name": "mbr0wn/snippets", "max_stars_repo_head_hexsha": "f8cc86d73cf3373348135be26c6478798a639a21", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/math/boost_lcm.cpp", "max_issues_repo_name": "mbr0wn/snippets", "max_issues_repo_head_hexsha": "f8cc86d73cf3373348135be26c6478798a639a21", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/math/boost_lcm.cpp", "max_forks_repo_name": "mbr0wn/snippets", "max_forks_repo_head_hexsha": "f8cc86d73cf3373348135be26c6478798a639a21", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6923076923, "max_line_length": 106, "alphanum_fraction": 0.578125, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5631081638500038}}
{"text": "/* Copyright \u00a9 2019 Apple Inc. All rights reserved.\n *\n * Use of this source code is governed by a BSD-3-clause license that can\n * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n */\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <vector>\n#include <random>\n\n#include <boost/gil/gil_all.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nnamespace turi {\nnamespace one_shot_object_detection {\nnamespace data_augmentation {\n\nclass Line {\npublic:\n  /* Equation of Line from two points */\n  Line(Eigen::Vector3f P1, Eigen::Vector3f P2);\n  bool side_of_line(size_t x, size_t y);\n\nprivate:\n  float m_a, m_b, m_c; // ax + by + c = 0\n};\n\n/* Returns true if (x,y) is inside a quadrilateral \n * defined by corners, where corners are in cyclic \n * order from top right to bottom left.\n */\nbool is_in_quadrilateral(size_t x, size_t y, \n  const std::vector<Eigen::Vector3f> &corners);\n\n/* mask is an image with all pixels set to black and\n * mask_complement is an image with all pixels set to white.\n * This function colors the pixels inside the convex quadrilateral defined by\n * corners with white for the mask and black for the mask_complement.\n */\nvoid color_quadrilateral(const boost::gil::rgba8_image_t::view_t &transformed_view, \n                         const std::vector<Eigen::Vector3f> &corners);\n\n} // data_augmentation\n} // one_shot_object_detection\n} // turi\n", "meta": {"hexsha": "f361244858d5081ed447ab7a129dfd9d54f9e78e", "size": 1417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/unity/toolkits/object_detection/one_shot_object_detection/util/quadrilateral_geometry.hpp", "max_stars_repo_name": "jolinlaw/turicreate", "max_stars_repo_head_hexsha": "6b2057dc29533da225d18138e93cc15680eea85d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/unity/toolkits/object_detection/one_shot_object_detection/util/quadrilateral_geometry.hpp", "max_issues_repo_name": "jolinlaw/turicreate", "max_issues_repo_head_hexsha": "6b2057dc29533da225d18138e93cc15680eea85d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unity/toolkits/object_detection/one_shot_object_detection/util/quadrilateral_geometry.hpp", "max_forks_repo_name": "jolinlaw/turicreate", "max_forks_repo_head_hexsha": "6b2057dc29533da225d18138e93cc15680eea85d", "max_forks_repo_licenses": ["BSD-3-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.34, "max_line_length": 86, "alphanum_fraction": 0.721947777, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.5631025118424576}}
{"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": "#include <boost/math/special_functions.hpp>\n#include <cassert>\n\ntemplate <class T>\nvoid check_float_inputs(T value) {\n    assert(!boost::math::isinf(value));\n    assert(!boost::math::isnan(value));\n\n    if (boost::math::signbit(value)) {\n        value = boost::math::changesign(value);\n    }\n\n    // ...\n    assert(value + (std::numeric_limits<T>::epsilon)() >= static_cast<T>(0));\n} // check_float_inputs\n\nint main() {\n    check_float_inputs(0.0);\n    check_float_inputs(-110.0f);\n    check_float_inputs(-11.0l);\n\n    // Shall fail the `!boost::math::isinf(value)` assertion\n    //check_float_inputs((std::numeric_limits<double>::max)() * 2.0);\n\n\n    // Shall fail the `!boost::math::isnan(value)` assertion\n    //check_float_inputs(std::sqrt(-1.0));\n}\n", "meta": {"hexsha": "4f1efac1f20bd034ab65fb29ece8ed1ba1019c0e", "size": 754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Chapter12/04_math/main.cpp", "max_stars_repo_name": "apolukhin/boost-cookbook", "max_stars_repo_head_hexsha": "912e36f38b9b1da93b03ae7afd19fcec0900aa83", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 313.0, "max_stars_repo_stars_event_min_datetime": "2017-05-28T15:30:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T12:32:40.000Z", "max_issues_repo_path": "Chapter12/04_math/main.cpp", "max_issues_repo_name": "apolukhin/boost-cookbook", "max_issues_repo_head_hexsha": "912e36f38b9b1da93b03ae7afd19fcec0900aa83", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-12-07T06:46:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T07:55:32.000Z", "max_forks_repo_path": "Chapter12/04_math/main.cpp", "max_forks_repo_name": "apolukhin/boost-cookbook", "max_forks_repo_head_hexsha": "912e36f38b9b1da93b03ae7afd19fcec0900aa83", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2017-05-28T16:47:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T10:04:55.000Z", "avg_line_length": 26.0, "max_line_length": 77, "alphanum_fraction": 0.6445623342, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.563080563677178}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <string.h>\n#include <chrono>\n#include <ctime>\n#include <iostream>\n#include <cmath>\n#include <cfloat>\n\n#include <posit/posit>\n#include <boost/range/combine.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include \"defines.hpp\"\n#include \"batch.hpp\"\n#include \"utils.hpp\"\n\nusing namespace std;\nusing namespace sw::unum;\nusing boost::multiprecision::cpp_dec_float_100;\n\ncpp_dec_float_100 decimal_accuracy(cpp_dec_float_100 exact, cpp_dec_float_100 computed) {\n        if (boost::math::isnan(exact) || boost::math::isnan(computed) ||\n            (boost::math::sign(exact) != boost::math::sign(computed))) {\n                return std::numeric_limits<cpp_dec_float_100>::quiet_NaN();\n        } else if (exact == computed) {\n                return std::numeric_limits<cpp_dec_float_100>::infinity();\n        } else if ((exact == std::numeric_limits<cpp_dec_float_100>::infinity() &&\n                    computed != std::numeric_limits<cpp_dec_float_100>::infinity()) ||\n                   (exact != std::numeric_limits<cpp_dec_float_100>::infinity() &&\n                    computed == std::numeric_limits<cpp_dec_float_100>::infinity()) || (exact == 0 && computed != 0) ||\n                   (exact != 0 && computed == 0)) {\n                return -std::numeric_limits<cpp_dec_float_100>::infinity();\n        } else {\n                return -log10(abs(log10(computed / exact)));\n        }\n}\n\nvoid writeBenchmark(PairHMMFloat<cpp_dec_float_100> &pairhmm_dec50, PairHMMFloat<float> &pairhmm_float,\n                    PairHMMPosit &pairhmm_posit, DebugValues<posit<NBITS, ES> > &hw_debug_values, std::string filename,\n                    bool printDate, bool overwrite) {\n        time_t t = chrono::system_clock::to_time_t(chrono::system_clock::now());\n\n        ofstream outfile(filename, ios::out);\n        if (printDate)\n                outfile << endl << ctime(&t) << endl << \"===================\" << endl;\n\n        auto dec_values = pairhmm_dec50.debug_values.items;\n        auto float_values = pairhmm_float.debug_values.items;\n        auto posit_values = pairhmm_posit.debug_values.items;\n        auto hw_values = hw_debug_values.items;\n\n        outfile << \"name,dE_f,dE_p,dE_hw,log(abs(dE_f)),log(abs(dE_p)),log(abs(dE_hw)),E,E_f,E_p,E_hw,da_F,da_P,da_HW\"\n                << endl;\n        for (int i = 0; i < dec_values.size(); i++) {\n                cpp_dec_float_100 E, E_f, E_p, E_hw, dE_f, dE_p, dE_hw;\n                cpp_dec_float_100 da_F, da_P, da_HW; // decimal accuracies\n\n                string name = dec_values[i].name;\n                E = dec_values[i].value;\n\n                auto E_f_entry = std::find_if(float_values.begin(), float_values.end(), find_entry(name));\n                E_f = E_f_entry->value;\n\n                auto E_p_entry = std::find_if(posit_values.begin(), posit_values.end(), find_entry(name));\n                E_p = E_p_entry->value;\n\n                auto E_hw_entry = std::find_if(hw_values.begin(), hw_values.end(), find_entry(name));\n                E_hw = E_hw_entry->value;\n\n                if (name != E_f_entry->name || name != E_p_entry->name || name != E_hw_entry->name) {\n                        cout << \"Error: mismatching names! Could not find name '\" << E_f_entry->name << endl;\n                }\n\n                da_F = decimal_accuracy(E, E_f);\n                da_P = decimal_accuracy(E, E_p);\n                da_HW = decimal_accuracy(E, E_hw);\n\n                if (E == 0) {\n                        dE_f = 0;\n                        dE_p = 0;\n                        dE_hw = 0;\n                } else {\n                        dE_f = (E_f - E) / E;\n                        dE_p = (E_p - E) / E;\n                        dE_hw = (E_hw - E) / E;\n                }\n\n                // Relative error values\n                outfile << name << \",\";\n                outfile << setprecision(100) << fixed << dE_f << \",\" << dE_p << \",\" << dE_hw << \",\" << flush;\n                outfile << setprecision(100) << fixed << log10(abs(dE_f)) << \",\" << log10(abs(dE_p)) << \",\" << log10(abs(dE_hw)) << \",\" << flush;\n                outfile << setprecision(100) << fixed << E << \",\" << E_f << \",\" << E_p << \",\" << E_hw << \",\" << flush;\n                outfile << setprecision(100) << fixed << da_F << \",\" << da_P << \",\" << da_HW << endl << flush;\n        }\n        outfile.close();\n}\n\nvoid print_batch_info(t_batch& batch) {\n        DEBUG_PRINT(\"X:%d, PX:%d, PBPX:%d, Y:%d, PY:%d\\n\",\n                    batch.init.x_size,\n                    batch.init.x_padded,\n                    batch.init.x_bppadded,\n                    batch.init.y_size,\n                    batch.init.y_padded\n                    );\n}\n\n// padded read size\nint px(int x, int y) {\n        if (py(y) > PES)     // if feedback fifo is used\n        {\n                if (x <= PES) // and x is equal or smaller than number of PES\n                {\n                        x = PES + 1; // x will be no. PES + 1, +1 is due to delay in the feedback fifo path\n                }\n        } else          // feedback fifo is not used\n        {\n                if (x < PES) // x is smaller than no. PES\n                {\n                        x = PES; // pad x to be equal to no. PES\n                }\n        }\n        return (x);\n}\n\nint pbp(int x) {\n        return ((x / BASE_STEPS + (x % BASE_STEPS != 0)) * BASE_STEPS);\n}\n\n// padded haplotype size\nint py(int y) {\n        // divide Y by PES and round up and multiply:\n        return ((y / PES + (y % PES != 0)) * PES);\n}\n\nt_workload *gen_workload(unsigned long pairs, unsigned long fixedX, unsigned long fixedY) {\n        DEBUG_PRINT(\"Generating workload for %d pairs, with X=%d and Y=%d\\n\", (int) pairs, (int) fixedX, (int) fixedY);\n        t_workload *workload = (t_workload *) malloc(sizeof(t_workload));\n\n        if (fixedY < fixedX) {\n                //printf(\"Haplotype cannot be smaller than read.\\n\");\n                //exit(EXIT_FAILURE);\n        }\n\n        workload->pairs = pairs;\n\n        if (workload->pairs % PIPE_DEPTH != 0) {\n                printf(\"Number of pairs must be an integer multiple of %d.\\n\", PIPE_DEPTH);\n                exit(EXIT_FAILURE);\n        }\n\n        workload->batches = pairs / PIPE_DEPTH;\n\n        // Allocate memory\n        workload->hapl = (uint32_t *) malloc(workload->pairs * sizeof(uint32_t));\n        workload->read = (uint32_t *) malloc(workload->pairs * sizeof(uint32_t));\n        workload->bx = (uint32_t *) malloc(workload->batches * sizeof(uint32_t));\n        workload->by = (uint32_t *) malloc(workload->batches * sizeof(uint32_t));\n        workload->bbytes = (size_t *) malloc(workload->batches * sizeof(size_t));\n        workload->cups = 0;\n\n        for (int i = 0; i < workload->pairs; i++) {\n                workload->hapl[i] = fixedY;\n                workload->read[i] = fixedX;\n                workload->cups += fixedY * fixedX;\n        }\n\n        // Set batch info\n        DEBUG_PRINT(\"Batch \u2551 MAX X \u2551 MAX Y \u2551 Passes \u2551\\n\");\n        DEBUG_PRINT(\"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\\n\");\n\n        for (int b = 0; b < workload->pairs / PIPE_DEPTH; b++) {\n                int xmax = 0;\n                int ymax = 0;\n                for (int p = 0; p < PIPE_DEPTH; p++) {\n                        if (workload->read[b * PIPE_DEPTH + p] > xmax) {\n                                xmax = workload->read[b * PIPE_DEPTH + p];\n                        }\n                        if (workload->hapl[b * PIPE_DEPTH + p] > ymax) {\n                                ymax = workload->hapl[b * PIPE_DEPTH + p];\n                        }\n                }\n                workload->bx[b] = xmax;\n                workload->by[b] = ymax;\n\n                DEBUG_PRINT(\"%5d \u2551 %5d \u2551 %5d \u2551 %6d \u2551\\n\", b, xmax, ymax, PASSES(ymax));\n        }\n\n        return (workload);\n} // gen_workload\n\nvoid copyProbBytes(t_probs& probs, uint8_t bytesArray[]) {\n        int pos = 0;\n        for(int i = 0; i < 8; i++) {\n                bytesArray[pos++] = probs.p[i].x[0];\n                bytesArray[pos++] = probs.p[i].x[1];\n                bytesArray[pos++] = probs.p[i].x[2];\n                bytesArray[pos++] = probs.p[i].x[3];\n        }\n}\n\nint roundToMultiple(int toRound, int multiple) {\n    toRound += multiple / 2;\n    return toRound - (toRound%multiple);\n}\n\n// From: https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c\nstd::string randomBasepairs(int len) {\n    auto randchar = []() -> char\n    {\n        const char charset[] = \"ACTG\";\n        const size_t max_index = sizeof(charset) - 1;\n        return charset[rand() % max_index];\n    };\n    std::string str(len, 0);\n    std::generate_n(str.begin(), len, randchar);\n\n    return str;\n}\n", "meta": {"hexsha": "a7438080eccff5ccd630954d47e2da75242a647d", "size": 8745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sw/src/utils.cpp", "max_stars_repo_name": "lvandam/pairhmm_posit_hdl_arrow", "max_stars_repo_head_hexsha": "428e935d1f3cb78d881ec590cfcc1f85806c4589", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-01T10:25:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-01T10:25:43.000Z", "max_issues_repo_path": "sw/src/utils.cpp", "max_issues_repo_name": "lvandam/pairhmm_posit_hdl_arrow", "max_issues_repo_head_hexsha": "428e935d1f3cb78d881ec590cfcc1f85806c4589", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sw/src/utils.cpp", "max_forks_repo_name": "lvandam/pairhmm_posit_hdl_arrow", "max_forks_repo_head_hexsha": "428e935d1f3cb78d881ec590cfcc1f85806c4589", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T10:42:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-05T09:10:13.000Z", "avg_line_length": 39.2152466368, "max_line_length": 145, "alphanum_fraction": 0.5175528874, "num_tokens": 2227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5630805586163696}}
{"text": "#ifndef EXAMPLE_HANDCRAFTED_HPP\r\n#define EXAMPLE_HANDCRAFTED_HPP\r\n\r\n// Copyright Abel Sinkovics (abel@sinkovics.hu)  2012.\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 <double_number.hpp>\r\n\r\n#include <boost/mpl/int.hpp>\r\n#include <boost/mpl/times.hpp>\r\n#include <boost/mpl/eval_if.hpp>\r\n#include <boost/mpl/minus.hpp>\r\n#include <boost/mpl/plus.hpp>\r\n#include <boost/mpl/less.hpp>\r\n\r\ntypedef boost::mpl::int_<11> val;\r\n\r\nstruct fib\r\n{\r\n  typedef fib type;\r\n\r\n  template <class N>\r\n  struct impl;\r\n\r\n  template <class N>\r\n  struct apply :\r\n    boost::mpl::eval_if<\r\n      typename boost::mpl::less<N, boost::mpl::int_<2> >::type,\r\n      boost::mpl::int_<1>,\r\n      impl<N>\r\n    >\r\n  {};\r\n};\r\n\r\ntemplate <class N>\r\nstruct fib::impl :\r\n  boost::mpl::plus<\r\n    typename fib::apply<\r\n      typename boost::mpl::minus<N, boost::mpl::int_<1> >::type\r\n    >::type,\r\n    typename fib::apply<\r\n      typename boost::mpl::minus<N, boost::mpl::int_<2> >::type\r\n    >::type\r\n  >\r\n{};\r\n\r\nstruct fact\r\n{\r\n  typedef fact type;\r\n\r\n  template <class N>\r\n  struct impl;\r\n\r\n  template <class N>\r\n  struct apply :\r\n    boost::mpl::eval_if<\r\n      typename boost::mpl::less<N, boost::mpl::int_<1> >::type,\r\n      boost::mpl::int_<1>,\r\n      impl<N>\r\n    >\r\n  {};\r\n};\r\n\r\ntemplate <class N>\r\nstruct fact::impl :\r\n  boost::mpl::times<\r\n    N,\r\n    typename fact::apply<\r\n      typename boost::mpl::minus<N, boost::mpl::int_<1> >::type\r\n    >::type\r\n  >\r\n{};\r\n\r\nstruct times4\r\n{\r\n  typedef times4 type;\r\n\r\n  template <class N>\r\n  struct apply : double_number<typename double_number<N>::type> {};\r\n};\r\n\r\nstruct times11\r\n{\r\n  typedef times11 type;\r\n\r\n  template <class N>\r\n  struct apply : boost::mpl::times<N, val> {};\r\n};\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "90f6cc2d7226d69416aa4fb2f96a0cbb524e597b", "size": 1847, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/meta_hs/example_handcrafted.hpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/meta_hs/example_handcrafted.hpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/meta_hs/example_handcrafted.hpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 19.6489361702, "max_line_length": 68, "alphanum_fraction": 0.6053059015, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5630805530598136}}
{"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 <iostream>\n#include <vector>\n\n#include <boost/random.hpp>\n#include <Eigen/Dense>\n\n#include <algorithm>\n\n#include <bitset>\n#include <iomanip>\n\n#include <state-observation/observer/extended-kalman-filter.hpp>\n#include <state-observation/observer/linear-kalman-filter.hpp>\n\n#include <boost/utility/binary.hpp>\n#include <state-observation/tools/probability-law-simulation.hpp>\n\ndouble testExtendedKalmanFilter()\n{\n  /// the number of samples\n  const static stateObservation::Index kmax = 1000;\n\n  /// define the type of the extended Kalman filter\n  typedef stateObservation::ExtendedKalmanFilter ekf;\n\n  /// instanciation of the extended Kalman filter\n  static ekf f(4, 3, 1);\n\n  /// The functor that describes the dynamics of the state\n  /// and the measurement\n  class KalmanFunctor : public stateObservation::DynamicalSystemFunctorBase\n  {\n\n  public:\n    /// Constructor\n    KalmanFunctor()\n    {\n      s_ = f.stateVectorRandom() * 0.1;\n      m_ = f.measureVectorRandom() * 0.1;\n      t_ = f.stateVectorRandom();\n      n_ = f.measureVectorRandom();\n      a_ = f.getAmatrixRandom() * 0.6;\n      c_ = f.getCmatrixRandom();\n    }\n\n    /// The dynamics of the state xk1=f(xk,u,k)\n    virtual ekf::StateVector stateDynamics(const ekf::StateVector & xk,\n                                           const ekf::InputVector & u,\n                                           stateObservation::TimeIndex k)\n    {\n      (void)k; // unused\n      (void)u; // unused\n\n      ekf::StateVector xk1;\n\n      xk1 = a_ * xk + cos(10 * (xk.transpose() * xk)[0]) * s_ + t_ + (u.transpose() * u)(0, 0) * s_;\n      return xk1;\n    }\n\n    /// The dynamics of the state yk=h(xk,u,k)\n    virtual ekf::MeasureVector measureDynamics(const ekf::StateVector & xk,\n                                               const ekf::InputVector & u,\n                                               stateObservation::TimeIndex k)\n    {\n      (void)k; // unused\n      (void)u; // unused\n\n      ekf::MeasureVector yk;\n      yk = c_ * xk + cos(10 * (xk.transpose() * xk)[0]) * m_ + n_;\n      return yk;\n    }\n\n    virtual stateObservation::Index getStateSize() const\n    {\n      return f.getStateSize();\n    }\n\n    virtual stateObservation::Index getInputSize() const\n    {\n      return f.getInputSize();\n    }\n\n    virtual stateObservation::Index getMeasurementSize() const\n    {\n      return f.getMeasureSize();\n    }\n\n  private:\n    /// containers for the vectors and matrices\n    ekf::StateVector s_;\n    ekf::StateVector t_;\n    ekf::MeasureVector m_;\n    ekf::MeasureVector n_;\n\n    ekf::Amatrix a_;\n    ekf::Cmatrix c_;\n  };\n\n  /// containers for the state, the measurements and the input\n  ekf::StateVector xk[kmax + 1];\n  ekf::MeasureVector yk[kmax];\n  ekf::InputVector uk[kmax + 1];\n\n  /// the standard deviation matrix to generate the gaussian noise\n  ekf::Rmatrix r1 = f.getRmatrixRandom() * 0.01;\n  ekf::Qmatrix q1 = f.getQmatrixRandom() * 0.01;\n\n  /// instanciate the functor\n  KalmanFunctor func;\n\n  { /// Construction of the sequence of states measurements and inputs\n\n    /// initializations\n    ekf::StateVector x = f.stateVectorZero();\n    xk[0] = x;\n    uk[0] = f.inputVectorRandom();\n\n    for(stateObservation::Index k = 1; k <= kmax; ++k)\n    {\n      /// generation of random inputs\n      uk[k] = f.inputVectorRandom();\n\n      /// generation of Gaussian white noises\n      ekf::StateVector v = stateObservation::tools::ProbabilityLawSimulation::getGaussianMatrix(f.stateVectorZero(), q1,\n                                                                                                f.getStateSize(), 1);\n\n      ekf::MeasureVector w = stateObservation::tools::ProbabilityLawSimulation::getGaussianMatrix(\n          f.measureVectorZero(), r1, f.getMeasureSize());\n\n      /// the dynamics is executed here\n      xk[k] = x = func.stateDynamics(x, uk[k - 1], k - 1) + v;\n      yk[k - 1] = func.measureDynamics(x, uk[k], k) + w;\n    }\n  }\n\n  /// set the functor of the extended Kalman filter\n  f.setFunctor(&func);\n\n  /// generation of a random initial estimation of the state\n  ekf::StateVector xh = f.stateVectorRandom();\n\n  /// set the initial state of the estimator\n  f.setState(xk[0], 0);\n\n  /// set the covariance matrix of the initial estimation error\n  ekf::Pmatrix p = f.getPmatrixZero();\n  for(unsigned i = 0; i < f.getStateSize(); ++i)\n  {\n    p(i, i) = xh[i];\n  }\n  p = p * p.transpose();\n  f.setStateCovariance(p);\n\n  /// the covariance matrices for the process noise and the measurements noise\n  ekf::Rmatrix r(r1 * r1.transpose());\n  ekf::Qmatrix q(q1 * q1.transpose());\n\n  /// set the covariance matrices for the extended Kalman filter\n  f.setR(r);\n  f.setQ(q);\n\n  /// set initial input\n  f.setInput(uk[0], 0);\n\n  /// set the derivation step for the finite difference method\n  ekf::StateVector dx = f.stateVectorConstant(1) * 1e-8;\n\n  stateObservation::Index i;\n  for(i = 1; i <= kmax; ++i)\n  {\n    /// give the measurements and the inputs at instant i to the ekf\n    f.setMeasurement(yk[i - 1], i);\n    f.setInput(uk[i], i);\n\n    /// obtain jacobians by finite differences method\n    ekf::Amatrix a = f.getAMatrixFD(dx);\n    ekf::Cmatrix c = f.getCMatrixFD(dx);\n\n    /// set the jacobians to the ekf\n    f.setA(a);\n    f.setC(c);\n\n    /// get the estimation of the state at instant i;\n    xh = f.getEstimatedState(i);\n  }\n\n  ekf::StateVector error = xh - xk[kmax];\n\n  return error.norm();\n}\n\ndouble testExtendedKalmanFilterLTV()\n{\n  const static stateObservation::TimeIndex kmax = 1000;\n\n  typedef stateObservation::ExtendedKalmanFilter ekf;\n\n  static ekf f(4, 3, 1);\n\n  struct KalmanFunctorLTV : public stateObservation::DynamicalSystemFunctorBase\n  {\n\n  public:\n    KalmanFunctorLTV()\n    {\n      s_ = f.stateVectorRandom();\n      n_ = f.measureVectorRandom();\n\n      for(stateObservation::Index i = 0; i <= kmax; ++i)\n      {\n        a.push_back(f.getAmatrixRandom() * 0.5);\n        c.push_back(f.getCmatrixRandom());\n      }\n    }\n\n    virtual ekf::StateVector stateDynamics(const ekf::StateVector & x,\n                                           const ekf::InputVector & u,\n                                           stateObservation::TimeIndex k)\n    {\n      ekf::StateVector xk1;\n      stateObservation::TimeIndex kk = std::min(k, kmax);\n      xk1 = a[kk] * x + (u.transpose() * u)(0, 0) * s_;\n\n      return xk1;\n    }\n\n    virtual ekf::MeasureVector measureDynamics(const ekf::StateVector & x,\n                                               const ekf::InputVector & u,\n                                               stateObservation::TimeIndex k)\n    {\n      (void)k; // unused\n      (void)u; // unused\n\n      ekf::MeasureVector yk;\n      stateObservation::TimeIndex kk = std::min(k, kmax);\n      yk = c[kk] * x + (u.transpose() * u)(0, 0) * n_;\n      return yk;\n    }\n\n    virtual stateObservation::Index getStateSize() const\n    {\n      return f.getStateSize();\n    }\n\n    virtual stateObservation::Index getInputSize() const\n    {\n      return f.getInputSize();\n    }\n\n    virtual stateObservation::Index getMeasurementSize() const\n    {\n      return f.getMeasureSize();\n    }\n\n    std::vector<ekf::Amatrix, Eigen::aligned_allocator<ekf::Amatrix>> a;\n    std::vector<ekf::Cmatrix, Eigen::aligned_allocator<ekf::Cmatrix>> c;\n\n  private:\n    ekf::StateVector s_;\n    ekf::MeasureVector n_;\n  };\n\n  KalmanFunctorLTV func;\n\n  f.setFunctor(&func);\n\n  ekf::StateVector xk[kmax + 1];\n  ekf::MeasureVector yk[kmax];\n  ekf::InputVector uk[kmax + 1];\n\n  ekf::StateVector x = f.stateVectorZero();\n\n  boost::lagged_fibonacci1279 gen_;\n\n  ekf::Rmatrix r1 = f.getRmatrixRandom() * 0.01;\n\n  ekf::Qmatrix q1 = f.getQmatrixRandom() * 0.01;\n\n  ekf::Rmatrix r(r1 * r1.transpose());\n  ekf::Qmatrix q(q1 * q1.transpose());\n\n  xk[0] = x;\n  uk[0] = f.inputVectorRandom();\n\n  for(stateObservation::Index k = 1; k <= kmax; ++k)\n  {\n    ekf::StateVector v(f.stateVectorZero());\n    for(unsigned i = 0; i < f.getStateSize(); ++i)\n    {\n      boost::normal_distribution<> g(0, 1);\n      v[i] = g(gen_);\n    }\n    v = q1 * v;\n\n    ekf::MeasureVector w(f.measureVectorZero());\n    for(unsigned i = 0; i < f.getMeasureSize(); ++i)\n    {\n      boost::normal_distribution<> g(0, 1);\n      w[i] = g(gen_);\n    }\n    w = r1 * w;\n\n    uk[k] = f.inputVectorRandom();\n\n    x = func.stateDynamics(x, uk[k - 1], k - 1) + v;\n\n    xk[k] = x;\n    yk[k - 1] = func.measureDynamics(x, uk[k], k) + w;\n  }\n\n  ekf::StateVector xh = f.stateVectorRandom();\n\n  f.setState(xh, 0);\n\n  ekf::Pmatrix p = f.getPmatrixZero();\n\n  for(unsigned i = 0; i < f.getStateSize(); ++i)\n  {\n    p(i, i) = xh[i];\n  }\n  p = p * p.transpose();\n\n  f.setStateCovariance(p);\n\n  f.setR(r);\n  f.setQ(q);\n\n  f.setInput(uk[0], 0);\n\n  for(unsigned i = 0; i < f.getStateSize(); ++i)\n  {\n    p(i, i) = xh[i];\n  }\n  p = p * p.transpose();\n\n  ekf::StateVector dx = f.stateVectorConstant(1) * 1e-8;\n\n  stateObservation::Index i;\n  for(i = 1; i <= kmax; ++i)\n  {\n    f.setMeasurement(yk[i - 1], i);\n    f.setInput(uk[i], i);\n\n    ekf::Amatrix a = f.getAMatrixFD(dx);\n    ekf::Cmatrix c = f.getCMatrixFD(dx);\n\n    f.setA(a);\n    f.setC(c);\n\n    xh = f.getEstimatedState(i);\n  }\n\n  ekf::StateVector error = xh - xk[kmax];\n\n  return error.norm();\n}\n\ndouble testExtendedKalmanFilterZeroInput()\n{\n  const static stateObservation::Index kmax = 1000;\n\n  typedef stateObservation::ExtendedKalmanFilter ekf;\n\n  static ekf f(4, 3);\n\n  class KalmanFunctor : public stateObservation::DynamicalSystemFunctorBase\n  {\n\n  public:\n    KalmanFunctor()\n    {\n      m_ = f.measureVectorRandom() * 0.1;\n      s_ = f.stateVectorRandom() * 0.1;\n      t_ = f.stateVectorRandom();\n      n_ = f.measureVectorRandom();\n    }\n\n    virtual ekf::StateVector stateDynamics(const ekf::StateVector & x,\n                                           const ekf::InputVector & u,\n                                           stateObservation::TimeIndex k)\n    {\n      (void)k; // unused\n      (void)u; // unused\n\n      ekf::StateVector xk1;\n      xk1 = a_ * x + cos(10 * (x.transpose() * x)[0]) * s_ + t_;\n      return xk1;\n    }\n\n    virtual ekf::MeasureVector measureDynamics(const ekf::StateVector & x,\n                                               const ekf::InputVector & u,\n                                               stateObservation::TimeIndex k)\n    {\n      (void)k; // unused\n      (void)u; // unused\n\n      ekf::MeasureVector yk;\n      yk = c_ * x + cos(10 * (x.transpose() * x)[0]) * m_ + n_;\n      return yk;\n    }\n\n    void setA(const ekf::Amatrix & a)\n    {\n      a_ = a;\n    }\n\n    void setC(const ekf::Cmatrix & c)\n    {\n      c_ = c;\n    }\n\n    virtual stateObservation::Index getStateSize() const\n    {\n      return f.getStateSize();\n    }\n\n    virtual stateObservation::Index getInputSize() const\n    {\n      return f.getInputSize();\n    }\n\n    virtual stateObservation::Index getMeasurementSize() const\n    {\n      return f.getMeasureSize();\n    }\n\n  private:\n    ekf::StateVector s_;\n    ekf::StateVector t_;\n    ekf::MeasureVector m_;\n    ekf::MeasureVector n_;\n\n    ekf::Amatrix a_;\n    ekf::Cmatrix c_;\n  };\n\n  KalmanFunctor func;\n\n  func.setA(f.getAmatrixRandom() * 0.5);\n  func.setC(f.getCmatrixRandom());\n\n  f.setFunctor(&func);\n\n  ekf::StateVector xk[kmax + 1];\n  ekf::MeasureVector yk[kmax];\n  ekf::InputVector u = f.inputVectorZero();\n\n  ekf::StateVector x = f.stateVectorZero();\n\n  boost::lagged_fibonacci1279 gen_;\n\n  ekf::Rmatrix r1 = f.getRmatrixRandom() * 0.01;\n\n  ekf::Qmatrix q1 = f.getQmatrixRandom() * 0.01;\n\n  ekf::Rmatrix r(r1 * r1.transpose());\n  ekf::Qmatrix q(q1 * q1.transpose());\n\n  xk[0] = x;\n\n  for(stateObservation::Index k = 1; k <= kmax; ++k)\n  {\n    ekf::StateVector v(f.stateVectorZero());\n    for(unsigned i = 0; i < f.getStateSize(); ++i)\n    {\n      boost::normal_distribution<> g(0, 1);\n      v[i] = g(gen_);\n    }\n    v = q1 * v;\n\n    ekf::MeasureVector w(f.measureVectorZero());\n    for(unsigned i = 0; i < f.getMeasureSize(); ++i)\n    {\n      boost::normal_distribution<> g(0, 1);\n      w[i] = g(gen_);\n    }\n    w = r1 * w;\n\n    x = func.stateDynamics(x, u, k - 1) + v;\n\n    xk[k] = x;\n    yk[k - 1] = func.measureDynamics(x, u, k) + w;\n  }\n\n  ekf::StateVector xh = f.stateVectorRandom();\n\n  f.setState(xk[0], 0);\n\n  ekf::Pmatrix p = f.getPmatrixZero();\n\n  f.setStateCovariance(p);\n\n  f.setR(r);\n  f.setQ(q);\n\n  for(unsigned i = 0; i < f.getStateSize(); ++i)\n  {\n    p(i, i) = xh[i];\n  }\n  p = p * p.transpose();\n\n  ekf::StateVector dx = f.stateVectorConstant(1) * 1e-8;\n\n  stateObservation::Index i;\n  for(i = 1; i <= kmax; ++i)\n  {\n    f.setMeasurement(yk[i - 1], i);\n\n    ekf::Amatrix a = f.getAMatrixFD(dx);\n    ekf::Cmatrix c = f.getCMatrixFD(dx);\n\n    f.setA(a);\n    f.setC(c);\n    xh = f.getEstimatedState(i);\n  }\n\n  ekf::StateVector error = xh - xk[kmax];\n\n  return error.norm();\n}\n\ndouble testKalmanFilter()\n{\n\n  typedef stateObservation::LinearKalmanFilter filter;\n\n  filter f(4, 3, 2);\n  Eigen::Matrix<double, 4, 4> a;\n\n  a << -0.6785714, 0.1156463, 0.4392517, 0.2863946, 0.0865306, -0.0273810, 0.3355102, 0.0184150, -0.4172789, -0.2036735,\n      -0.4434014, -0.2666667, 0.4200680, 0.5387075, 0.4883673, -0.6598639;\n\n  filter::Bmatrix b = f.getBmatrixRandom();\n  filter::Cmatrix c = f.getCmatrixRandom();\n  filter::Dmatrix d = f.getDmatrixRandom();\n\n  const stateObservation::Index kmax = 1000;\n\n  filter::StateVector xk[kmax + 1];\n  filter::MeasureVector yk[kmax];\n  filter::InputVector uk[kmax + 1];\n\n  filter::StateVector x = f.stateVectorZero();\n\n  xk[0] = x;\n\n  filter::Rmatrix r1 = f.getRmatrixRandom() * 0.01;\n\n  filter::Qmatrix q1 = f.getQmatrixRandom() * 0.01;\n\n  filter::Rmatrix r(r1 * r1.transpose());\n  filter::Qmatrix q(q1 * q1.transpose());\n\n  uk[0] = f.inputVectorRandom();\n\n  boost::lagged_fibonacci1279 gen_;\n  for(stateObservation::Index k = 1; k <= kmax; ++k)\n  {\n\n    filter::StateVector v = f.stateVectorZero();\n    for(unsigned i = 0; i < f.getStateSize(); ++i)\n    {\n      boost::normal_distribution<> g(0, 1);\n      v[i] = g(gen_);\n    }\n    v = q1 * v;\n\n    filter::MeasureVector w = f.measureVectorZero();\n    for(unsigned i = 0; i < f.getMeasureSize(); ++i)\n    {\n      boost::normal_distribution<> g(0, 1);\n      w[i] = g(gen_);\n    }\n    w = r1 * w;\n\n    uk[k] = f.inputVectorRandom();\n\n    xk[k] = x = a * x + v + b * uk[k - 1];\n    yk[k - 1] = c * x + w + d * uk[k];\n  }\n\n  filter::StateVector xh = f.stateVectorRandom();\n\n  f.setState(xh, 0);\n\n  filter::Pmatrix p = f.getPmatrixZero();\n\n  for(unsigned i = 0; i < f.getStateSize(); ++i)\n  {\n    p(i, i) = xh[i];\n  }\n  p = p * p.transpose();\n\n  f.setStateCovariance(p);\n\n  f.setA(a);\n  f.setB(b);\n  f.setC(c);\n  f.setD(d);\n\n  f.setR(r);\n  f.setQ(q);\n\n  f.setInput(uk[0], 0);\n\n  stateObservation::Index i;\n  for(i = 1; i <= kmax; ++i)\n  {\n    f.setMeasurement(yk[i - 1], i);\n    f.setInput(uk[i], i);\n  }\n\n  filter::StateVector error = f.getEstimatedState(kmax) - xk[kmax];\n\n  return error.norm();\n}\n\ndouble testKalmanFilterZeroInput()\n{\n  typedef stateObservation::LinearKalmanFilter filter;\n\n  filter f(4, 3);\n  Eigen::Matrix<double, 4, 4> a;\n\n  a << -0.6785714, 0.1156463, 0.4392517, 0.2863946, 0.0865306, -0.0273810, 0.3355102, 0.0184150, -0.4172789, -0.2036735,\n      -0.4434014, -0.2666667, 0.4200680, 0.5387075, 0.4883673, -0.598639;\n\n  filter::Bmatrix b = f.getBmatrixRandom();\n  filter::Cmatrix c = f.getCmatrixRandom();\n  filter::Dmatrix d = f.getDmatrixRandom();\n\n  const stateObservation::Index kmax = 1000;\n\n  filter::StateVector xk[kmax + 1];\n  filter::MeasureVector yk[kmax];\n\n  filter::StateVector x = f.stateVectorZero();\n\n  xk[0] = x;\n\n  boost::lagged_fibonacci1279 gen_;\n\n  filter::Rmatrix r1 = f.getRmatrixRandom() * 0.01;\n\n  filter::Qmatrix q1 = f.getQmatrixRandom() * 0.01;\n\n  filter::Rmatrix r(r1 * r1.transpose());\n  filter::Qmatrix q(q1 * q1.transpose());\n\n  filter::InputVector u = f.inputVectorZero();\n\n  for(stateObservation::Index k = 1; k <= kmax; ++k)\n  {\n\n    filter::StateVector v = f.stateVectorZero();\n    for(unsigned i = 0; i < f.getStateSize(); ++i)\n    {\n      boost::normal_distribution<> g(0, 1);\n      v[i] = g(gen_);\n    }\n    v = q1 * v;\n\n    filter::MeasureVector w = f.measureVectorZero();\n    for(unsigned i = 0; i < f.getMeasureSize(); ++i)\n    {\n      boost::normal_distribution<> g(0, 1);\n      w[i] = g(gen_);\n    }\n    w = r1 * w;\n\n    xk[k] = x = a * x + v;\n    yk[k - 1] = c * x + w;\n  }\n\n  filter::StateVector xh = f.stateVectorRandom();\n\n  f.setState(xh, 0);\n\n  filter::Pmatrix p = f.getPmatrixZero();\n\n  for(unsigned i = 0; i < f.getStateSize(); ++i)\n  {\n    p(i, i) = xh[i];\n  }\n  p = p * p.transpose();\n\n  f.setStateCovariance(p);\n\n  f.setA(a);\n  f.setB(b);\n  f.setC(c);\n  f.setD(d);\n\n  f.setR(r);\n  f.setQ(q);\n\n  stateObservation::Index i;\n\n  for(i = 1; i <= kmax; ++i)\n  {\n    f.setMeasurement(yk[i - 1], i);\n  }\n\n  filter::StateVector error = f.getEstimatedState(kmax) - xk[kmax];\n\n  return error.norm();\n}\n\nint main()\n{\n  short exit = 0;\n  double error;\n  std::cout << \"Starting\" << std::endl;\n\n  if((error = testKalmanFilter()) < 0.1)\n  {\n    std::cout << \"Test Kalman filter SUCCEEDED: estimationError = \" << error << std::endl;\n  }\n  else\n  {\n    exit = exit | BOOST_BINARY(1);\n    std::cout << \"Test Kalman filter FAILED: estimationError = \" << error << std::endl;\n  }\n  if((error = testKalmanFilterZeroInput()) < 0.1)\n  {\n    std::cout << \"Test Kalman filter (zero input) SUCCEEDED: estimationError = \" << error << std::endl;\n  }\n  else\n  {\n    exit = exit | BOOST_BINARY(10);\n    std::cout << \"Test Kalman filter (zero input) FAILED: estimationError = \" << error << std::endl;\n  }\n  if((error = testExtendedKalmanFilter()) < 0.1)\n  {\n    std::cout << \"Test extended Kalman filter SUCCEEDED: estimationError = \" << error << std::endl;\n  }\n  else\n  {\n    exit = exit | BOOST_BINARY(100);\n    std::cout << \"Test extended Kalman filter FAILED: estimationError = \" << error << std::endl;\n  }\n  if((error = testExtendedKalmanFilterLTV()) < 0.1)\n  {\n    std::cout << \"Test extended Kalman filter (LTV) SUCCEEDED: estimationError = \" << error << std::endl;\n  }\n  else\n  {\n    exit = exit | BOOST_BINARY(1000);\n    std::cout << \"Test extended Kalman filter (LTV) FAILED: estimationError = \" << error << std::endl;\n  }\n  if((error = testExtendedKalmanFilterZeroInput()) < 0.1)\n  {\n    std::cout << \"Test extended Kalman filter (zero input) SUCCEEDED: estimationError = \" << error << std::endl;\n  }\n  else\n  {\n    exit = exit | BOOST_BINARY(10000);\n    std::cout << \"Test extended Kalman filter (zero input) FAILED: estimationError = \" << error << std::endl\n              << std::endl;\n  }\n\n  std::cout << \"Test exit code \" << std::bitset<16>(exit) << std::endl;\n\n  return exit;\n}\n", "meta": {"hexsha": "1680d25c131cb2a043791142c960b8fb8f1c83b9", "size": 18570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit-testings/test-kalman-filter.cpp", "max_stars_repo_name": "jrl-umi3218/state-observation", "max_stars_repo_head_hexsha": "bd4f1b7e64a0a3b393f63f69219c061200793d35", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-11-01T16:10:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T00:03:46.000Z", "max_issues_repo_path": "unit-testings/test-kalman-filter.cpp", "max_issues_repo_name": "mehdi-benallegue/state-observation", "max_issues_repo_head_hexsha": "cfc703a52380bd15065801f5d87baba4bbb506ce", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-10-18T09:06:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T04:22:09.000Z", "max_forks_repo_path": "unit-testings/test-kalman-filter.cpp", "max_forks_repo_name": "mehdi-benallegue/state-observation", "max_forks_repo_head_hexsha": "cfc703a52380bd15065801f5d87baba4bbb506ce", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-06-19T09:00:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T06:14:51.000Z", "avg_line_length": 24.2428198433, "max_line_length": 120, "alphanum_fraction": 0.5918686053, "num_tokens": 5771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5630805416988273}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n\n#include <vsnakes/utils.h>\n#include <vsnakes/vsnakes.h>\n\nnamespace\n{\nstd::vector<Eigen::Vector2i> generateInitialAnchors(int rows = 64, int cols = 64, int numAnchors = 8)\n{\n    const auto center = cols / 2;\n    const auto delta = rows / numAnchors;\n\n    std::vector<Eigen::Vector2i> anchors;\n\n    for (int aidx = 0; aidx < numAnchors; ++aidx)\n    {\n        Eigen::Vector2i anchor =\n            (aidx % 2 == 0) ? Eigen::Vector2i{center - 5, aidx * delta} : Eigen::Vector2i{center + 5, aidx * delta};\n        anchors.push_back(std::move(anchor));\n    }\n\n    return anchors;\n}\n\nEigen::MatrixXf generateEnergyMap(int rows = 64, int cols = 64)\n{\n    Eigen::MatrixXf energyMap(rows, cols);\n\n    const int half = cols / 2;\n\n    for (int i = 0; i < rows; ++i)\n    {\n        for (int j = 0; j < half; ++j)\n        {\n            energyMap(i, j) = static_cast<float>(cols - j);\n        }\n\n        for (int j = half; j < cols; ++j)\n        {\n            energyMap(i, j) = static_cast<float>(cols - half + 1 + j);\n        }\n    }\n\n    return energyMap;\n}\n\n}  // namespace\n\nint main(int argc, char* argv[])\n{\n    /// TODO: Allow passing a set of anchor and an image for the optimization\n\n    // Inputs for the optimization\n    const int rows = 64;\n    const int cols = 64;\n    const int numAnchors = 8;\n    const auto spacing = 8;\n\n    const std::vector<Eigen::Vector2i> anchors = generateInitialAnchors(rows, cols, numAnchors);\n    const Eigen::MatrixXf energyMap = generateEnergyMap(rows, cols);\n\n    const auto optimizedAnchors = vsnakes::optimizeAnchorsFirstOrder(0.001f, 1.f, spacing, 200, anchors, energyMap);\n\n    vsnakes::printAnchors(\"Initial\", anchors);\n    vsnakes::printAnchors(\"Optimized\", optimizedAnchors);\n}", "meta": {"hexsha": "da75b177f682482f95b4e92fab6b30b40dba16cf", "size": 1752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/apps/optimize_anchors.cpp", "max_stars_repo_name": "gipeto/viterbi-snakes", "max_stars_repo_head_hexsha": "32d0295bbb467b6a74992cf836906b8d59be3ebd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/apps/optimize_anchors.cpp", "max_issues_repo_name": "gipeto/viterbi-snakes", "max_issues_repo_head_hexsha": "32d0295bbb467b6a74992cf836906b8d59be3ebd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/apps/optimize_anchors.cpp", "max_forks_repo_name": "gipeto/viterbi-snakes", "max_forks_repo_head_hexsha": "32d0295bbb467b6a74992cf836906b8d59be3ebd", "max_forks_repo_licenses": ["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.1492537313, "max_line_length": 116, "alphanum_fraction": 0.6170091324, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7122321964553656, "lm_q1q2_score": 0.5630411452306626}}
{"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": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"test_stats\"\n\n#include <boost/test/unit_test.hpp>\n#include \"nanocv/math/abs.hpp\"\n#include \"nanocv/math/stats.hpp\"\n#include \"nanocv/math/random.hpp\"\n\nnamespace test\n{\n        using namespace ncv;\n\n        void check_stats(double avg, double var, size_t count)\n        {\n                ncv::stats_t<double> stats;\n                ncv::random_t<double> rgen(-var, +var);\n\n                // generate random values\n                std::vector<double> values;\n                for (size_t i = 0; i < count; i ++)\n                {\n                        values.push_back(avg + rgen());\n\n                        stats(*values.rbegin());\n                }\n\n                // check count\n                BOOST_CHECK_EQUAL(stats.count(), count);\n\n                // check range\n                BOOST_CHECK_GE(stats.min(), avg - var);\n                BOOST_CHECK_LE(stats.max(), avg + var);\n\n                // check average\n                BOOST_CHECK_GE(stats.avg(), avg - var);\n                BOOST_CHECK_LE(stats.avg(), avg + var);\n\n                // check variance\n                BOOST_CHECK_GE(stats.var(), 0.0);\n                BOOST_CHECK_LE(std::sqrt(stats.var()), var);\n\n                // check sum\n                BOOST_CHECK_LE(math::abs(stats.sum() - std::accumulate(values.begin(), values.end(), 0.0)), 1e-8);\n        }\n}\n\nBOOST_AUTO_TEST_CASE(test_stats)\n{\n        test::check_stats(0.03, 0.005, 32);\n        test::check_stats(1.03, 13.005, 37);\n        test::check_stats(-0.54, 0.105, 13);\n        test::check_stats(-7.03, 10.005, 11);\n}\n", "meta": {"hexsha": "2701d08bd85cac85102426af14462b43217d6964", "size": 1604, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_stats.cpp", "max_stars_repo_name": "0x0all/nanocv", "max_stars_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_stats.cpp", "max_issues_repo_name": "0x0all/nanocv", "max_issues_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_stats.cpp", "max_forks_repo_name": "0x0all/nanocv", "max_forks_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T02:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-02T02:41:37.000Z", "avg_line_length": 29.7037037037, "max_line_length": 114, "alphanum_fraction": 0.5162094763, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5630260424897188}}
{"text": "/*\n * @file\n * @author University of Warwick\n * @version 1.0\n *\n * @section LICENSE\n *\n * @section DESCRIPTION\n *\n * Unit Tests for the methods of the Pyramid class\n */\n\n\n#define BOOST_TEST_MODULE Pyramid\n#include <boost/test/unit_test.hpp>\n#include <boost/test/output_test_stream.hpp>\n#include <stdexcept>\n\n#include \"Pyramid.h\"\n#include \"EuclideanPoint.h\"\n\nusing namespace cupcfd::geometry::shapes;\nnamespace euc = cupcfd::geometry::euclidean;\nnamespace utf = boost::unit_test;\n\n// === Constructor ===\n// Test 1: Create a QuadPyramid\nBOOST_AUTO_TEST_CASE(constructor_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double, 3> p1(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double, 3> p2(0.0, 10.0, 0.0);\n\teuc::EuclideanPoint<double, 3> p3(10.0, 10.0, 0.0);\n\teuc::EuclideanPoint<double, 3> p4(10.0, 0.0, 0.0);\n\n\teuc::EuclideanPoint<double, 3> apex(5.0, 5.0, 5.0);\n\n\tQuadrilateral3D<double> base(p1, p2, p3, p4);\n\tPyramid<Quadrilateral3D<double>, double> shape(apex, base);\n\n\tBOOST_CHECK_EQUAL(shape.apex.cmp[0], 5.0);\n\tBOOST_CHECK_EQUAL(shape.apex.cmp[1], 5.0);\n\tBOOST_CHECK_EQUAL(shape.apex.cmp[2], 5.0);\n\n\tBOOST_CHECK_EQUAL(shape.base.vertices[0].cmp[0], 0.0);\n\tBOOST_CHECK_EQUAL(shape.base.vertices[0].cmp[1], 0.0);\n\tBOOST_CHECK_EQUAL(shape.base.vertices[0].cmp[2], 0.0);\n\n\tBOOST_CHECK_EQUAL(shape.base.vertices[1].cmp[0], 0.0);\n\tBOOST_CHECK_EQUAL(shape.base.vertices[1].cmp[1], 10.0);\n\tBOOST_CHECK_EQUAL(shape.base.vertices[1].cmp[2], 0.0);\n\n\tBOOST_CHECK_EQUAL(shape.base.vertices[2].cmp[0], 10.0);\n\tBOOST_CHECK_EQUAL(shape.base.vertices[2].cmp[1], 10.0);\n\tBOOST_CHECK_EQUAL(shape.base.vertices[2].cmp[2], 0.0);\n\n\tBOOST_CHECK_EQUAL(shape.base.vertices[3].cmp[0], 10.0);\n\tBOOST_CHECK_EQUAL(shape.base.vertices[3].cmp[1], 0.0);\n\tBOOST_CHECK_EQUAL(shape.base.vertices[3].cmp[2], 0.0);\n}\n\n// === isPointInside ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(isPointInside_test1, * utf::tolerance(0.00001))\n{\n\n}\n\n// === getVolume ===\n// Test 1: Compute Volume of Pyramid\nBOOST_AUTO_TEST_CASE(getVolume_test1, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double, 3> p1(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double, 3> p2(0.0, 10.0, 0.0);\n\teuc::EuclideanPoint<double, 3> p3(10.0, 10.0, 0.0);\n\teuc::EuclideanPoint<double, 3> p4(10.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double, 3> apex(5.0, 5.0, 5.0);\n\n\tQuadrilateral3D<double> base(p1, p2, p3, p4);\n\tPyramid<Quadrilateral3D<double>, double> shape(apex, base);\n\n\tdouble volume = shape.getVolume();\n\n\tBOOST_TEST(volume == 166.666667);\n}\n\n// Test 2: Compute Volume of Oblique Pyramid\nBOOST_AUTO_TEST_CASE(getVolume_test2, * utf::tolerance(0.00001))\n{\n\teuc::EuclideanPoint<double, 3> p1(0.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double, 3> p2(0.0, 10.0, 0.0);\n\teuc::EuclideanPoint<double, 3> p3(10.0, 10.0, 0.0);\n\teuc::EuclideanPoint<double, 3> p4(10.0, 0.0, 0.0);\n\teuc::EuclideanPoint<double, 3> apex(2.7, 3.7, 8.9);\n\n\tQuadrilateral3D<double> base(p1, p2, p3, p4);\n\tPyramid<Quadrilateral3D<double>, double> shape(apex, base);\n\n\tdouble volume = shape.getVolume();\n\n\tBOOST_TEST(volume == 296.666667);\n}\n", "meta": {"hexsha": "54e521b94e7a2bc34b860eb992d6448de5205d48", "size": 3030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/geometry/shapes/implementation/component/PyramidTests.cpp", "max_stars_repo_name": "thorbenlouw/CUP-CFD", "max_stars_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T10:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T14:43:19.000Z", "max_issues_repo_path": "tests/geometry/shapes/implementation/component/PyramidTests.cpp", "max_issues_repo_name": "thorbenlouw/CUP-CFD", "max_issues_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T15:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T14:27:28.000Z", "max_forks_repo_path": "tests/geometry/shapes/implementation/component/PyramidTests.cpp", "max_forks_repo_name": "thorbenlouw/CUP-CFD", "max_forks_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T15:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T15:24:24.000Z", "avg_line_length": 29.7058823529, "max_line_length": 68, "alphanum_fraction": 0.700990099, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.563026025895122}}
{"text": "#include \"fib_matrix.h\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n\nusing namespace boost::multiprecision;\nusing uint2048_t = number<cpp_int_backend<2048, 2048, unsigned_magnitude, unchecked, void>>;\n\nint main(int argc, char *argv[])\n{\n    const char* fname = (argc > 1)? argv[1] : \"fib.txt\";\n    std::ifstream f(fname);\n    if (f.good()) {\n        std::cout << \"reading from \" << fname << \"\\n\";\n        uint2048_t n;\n\n        std::string expected;\n        while (f >> n >> expected) {\n            auto r = fib(n);\n            std::ostringstream os;\n            os << r;\n            if (os.str() != expected) {\n                std::cout << n\n                          << \"\\n got unexpected result \" << r\n                          << \"\\n expected              \" << expected << \"\\n\";\n            }\n        }\n    } else {\n        std::cout << \"unable to open \" << fname << \"\\n\";\n    }\n    return 0;\n}\n\n", "meta": {"hexsha": "bf6ff243cf5f1b821dd17ee01bff17410325e58b", "size": 958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lesson_03/fib_compare.cpp", "max_stars_repo_name": "andreyc2018/otus_algorithms", "max_stars_repo_head_hexsha": "d7fc3e683c6c47caed787176a2c1580701bf2044", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lesson_03/fib_compare.cpp", "max_issues_repo_name": "andreyc2018/otus_algorithms", "max_issues_repo_head_hexsha": "d7fc3e683c6c47caed787176a2c1580701bf2044", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lesson_03/fib_compare.cpp", "max_forks_repo_name": "andreyc2018/otus_algorithms", "max_forks_repo_head_hexsha": "d7fc3e683c6c47caed787176a2c1580701bf2044", "max_forks_repo_licenses": ["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.3714285714, "max_line_length": 92, "alphanum_fraction": 0.496868476, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5630260247724512}}
{"text": "/**\n * fit test\n * @author Tobias Weber <tweber@ill.fr>\n * @date 28-aug-20\n * @license GPLv3, see 'LICENSE' file\n *\n * g++-10 -std=c++20 -I.. -o fit1 fit1.cpp ../libs/log.cpp -lMinuit2 -lpthread\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021  Tobias WEBER (Institut Laue-Langevin (ILL),\n *                          Grenoble, France).\n * Copyright (C) 2015-2017  Tobias WEBER (Technische Universitaet Muenchen\n *                          (TUM), Garching, Germany).\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n * ----------------------------------------------------------------------------\n */\n\n#define BOOST_TEST_MODULE Fit Test\n#include <boost/test/included/unit_test.hpp>\nnamespace test = boost::unit_test;\nnamespace testtools = boost::test_tools;\n\n\n#include \"libs/fit.h\"\n#include \"libs/maths.h\"\n\n\nusing t_types_real = std::tuple<double, float>;\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_expr_real, t_real, t_types_real)\n{\n\tt_real amp = 1.;\n\tt_real freq = 2*tl2::pi<t_real>;\n\tt_real offs = 12.;\n\n\tstd::vector<t_real> xs, ys, yerrs;\n\tfor(t_real x=0.; x<1.; x+=0.05)\n\t{\n\t\txs.push_back(x);\n\t\tys.push_back(amp*std::sin(freq*x) + offs);\n\t\tyerrs.push_back(0.1);\n\t}\n\n\tauto func = [](t_real x, t_real amp, t_real freq, t_real offs)\n\t{\n\t\treturn amp*std::sin(freq*x) + offs;\n\t};\n\n\tstd::vector<std::string> params{{\"amp\", \"freq\", \"offs\"}};\n\tstd::vector<t_real> vals{{amp*t_real{1.2}, freq*t_real{0.8}, offs*t_real{0.9}}};\n\tstd::vector<t_real> errs{{0.5, 0.1, 1.}};\n\tstd::vector<bool> fixed{false, false, false};\n\t\n\tbool ok = tl2::fit<t_real, 4>(func, xs, ys, yerrs, params, vals, errs, &fixed);\n\n\tBOOST_TEST(ok);\n\tBOOST_TEST(tl2::equals<t_real>(vals[0], amp, 1e-3));\n\tBOOST_TEST(tl2::equals<t_real>(vals[1], freq, 1e-3));\n\tBOOST_TEST(tl2::equals<t_real>(vals[2], offs, 1e-3));\n}\n", "meta": {"hexsha": "b4f07a57325cc8468c93d7645d42ab722e8a7831", "size": 2392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/fit1.cpp", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittests/fit1.cpp", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/fit1.cpp", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 32.3243243243, "max_line_length": 81, "alphanum_fraction": 0.6283444816, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5630260207378132}}
{"text": "#include \"easing/easing.hpp\"\n#include \"interpolation/interpolation.hpp\"\n#include <boost/process.hpp>\n#include <iostream>\n#include <string>\n#define FMT_HEADER_ONLY\n#include <fmt/format.h>\n\nstatic void plot(const std::string &plot_name,\n                 const std::string &points_data_path,\n                 const std::string &output_png_path, bool is_dynamic) {\n  boost::process::opstream write;\n  boost::filesystem::path command(\"/usr/local/bin/gnuplot\");\n  boost::process::child plot(command, boost::process::std_in = write);\n\n  write << \"set terminal png\\n\";\n  write << fmt::format(\"unset key\\n\");\n  write << fmt::format(\"set output \\\"{}\\\"\\n\", output_png_path);\n  write << fmt::format(\"set xlabel \\\"{}\\\"\\n\", \"axis-x\");\n  write << fmt::format(\"set ylabel \\\"{}\\\"\\n\", \"axis-y\");\n  write << fmt::format(\"set xrange {}\\n\", \"[0:1]\");\n  write << fmt::format(\"set yrange {}\\n\", is_dynamic ? \"[-0.5:1.5]\" : \"[0:1]\");\n  write << fmt::format(\"plot \\\"{}\\\" with points pt 7 lc 1,\", points_data_path);\n\n  write.flush();\n  write.pipe().close();\n  plot.wait();\n  std::cout << plot_name << \" was done, exit code: \" << plot.exit_code()\n            << std::endl;\n}\n\ntemplate <typename F>\nstatic void\nplot(const std::string &plot_name, const std::string &points_data_path,\n     const std::string &output_png_path, F easing, bool is_dynamic = false) {\n  std::vector<float> xs(101), ys(101);\n  for (int i = 0; i <= 100; i++) {\n    xs[i] = i * 0.01f;\n    ys[i] = interpolation::lerp(0.0f, 1.0f, easing(xs[i]));\n  }\n  std::ofstream points_file(points_data_path);\n  for (int i = 0; i <= 100; i++) {\n    points_file << xs[i] << \" \" << ys[i] << \"\\n\";\n  }\n  points_file.close();\n\n  plot(plot_name, points_data_path, output_png_path, is_dynamic);\n}\n\ntemplate <typename T>\nstatic void plot(const std::string &type_name, bool is_dynamic = false) {\n  plot(fmt::format(\"{} in plot\", type_name),\n       fmt::format(\"data/{}_in.dat\", type_name),\n       fmt::format(\"data/{}_in.png\", type_name), T::in, is_dynamic);\n  plot(fmt::format(\"{} out plot\", type_name),\n       fmt::format(\"data/{}_out.dat\", type_name),\n       fmt::format(\"data/{}_out.png\", type_name), T::out, is_dynamic);\n  plot(fmt::format(\"{} in-out plot\", type_name),\n       fmt::format(\"data/{}_inout.dat\", type_name),\n       fmt::format(\"data/{}_inout.png\", type_name), T::inout, is_dynamic);\n}\n\nint main() {\n  plot(\"linear plot\", \"data/linear.dat\", \"data/linear.png\",\n       easing::linear<float>);\n  plot(\"ease in plot\", \"data/ease_in.dat\", \"data/ease_in.png\",\n       easing::ease_in<float>);\n  plot(\"ease out plot\", \"data/ease_out.dat\", \"data/ease_out.png\",\n       easing::ease_out<float>);\n  plot(\"ease inout plot\", \"data/ease_inout.dat\", \"data/ease_inout.png\",\n       easing::ease_inout<float>);\n\n  plot<easing::ease<easing::sine<float>, float>>(\"sine\");\n  plot<easing::ease<easing::quad<float>, float>>(\"quad\");\n  plot<easing::ease<easing::cubic<float>, float>>(\"cubic\");\n  plot<easing::ease<easing::quart<float>, float>>(\"quart\");\n  plot<easing::ease<easing::quint<float>, float>>(\"quint\");\n  plot<easing::ease<easing::expo<float>, float>>(\"expo\");\n  plot<easing::ease<easing::circ<float>, float>>(\"circ\");\n  plot<easing::ease<easing::back<float>, float>>(\"back\", true);\n  plot<easing::ease<easing::elastic<float>, float>>(\"elastic\", true);\n  plot<easing::ease<easing::bounce<float>, float>>(\"bounce\");\n  return 0;\n}\n", "meta": {"hexsha": "4bb04e48310aa502c9b6d9c2bd4ac7bc8b9036e6", "size": 3356, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/easing/main.cpp", "max_stars_repo_name": "mnrn/game-memo", "max_stars_repo_head_hexsha": "8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/easing/main.cpp", "max_issues_repo_name": "mnrn/game-memo", "max_issues_repo_head_hexsha": "8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/easing/main.cpp", "max_forks_repo_name": "mnrn/game-memo", "max_forks_repo_head_hexsha": "8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4823529412, "max_line_length": 79, "alphanum_fraction": 0.6328963051, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.5630141243153418}}
{"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": "//  (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#define BOOST_TEST_MODULE condition_number_test\n\n#include <cmath>\n#include <limits>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/lambert_w.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/math/tools/condition_numbers.hpp>\n\nusing std::abs;\nusing boost::math::constants::half;\nusing boost::math::constants::ln_two;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::math::tools::summation_condition_number;\nusing boost::math::tools::evaluation_condition_number;\n\ntemplate<class Real>\nvoid test_summation_condition_number()\n{\n    Real tol = 1000*std::numeric_limits<float>::epsilon();\n    auto cond = summation_condition_number<Real>();\n    // I've checked that the condition number increases with max_n,\n    // and that the computed sum gets more accurate with increasing max_n.\n    // But the CI system would die with more terms.\n    Real max_n = 10000;\n    for (Real n = 1; n < max_n; n += 2)\n    {\n        cond += 1/n;\n        cond -= 1/(n+1);\n    }\n\n    BOOST_CHECK_CLOSE_FRACTION(cond.sum(), ln_two<Real>(), tol);\n    BOOST_TEST(cond() > 14);\n}\n\ntemplate<class Real>\nvoid test_exponential_sum()\n{\n    using std::exp;\n    using std::abs;\n    Real eps = std::numeric_limits<float>::epsilon();\n    for (Real x = -20; x <= -1; x += 0.5)\n    {\n        auto cond = summation_condition_number<Real>(1);\n        size_t n = 1;\n        Real term = x;\n        while(n++ < 1000)\n        {\n            cond += term;\n            term *= (x/n);\n        }\n        BOOST_CHECK_CLOSE_FRACTION(exp(x), cond.sum(), eps*cond());\n        BOOST_CHECK_CLOSE_FRACTION(exp(2*abs(x)), cond(), eps*cond());\n    }\n}\n\n\n\ntemplate<class Real>\nvoid test_evaluation_condition_number()\n{\n    using std::abs;\n    using std::log;\n    using std::sqrt;\n    using std::exp;\n    using std::sin;\n    using std::tan;\n    Real tol = sqrt(std::numeric_limits<Real>::epsilon());\n\n    auto f1 = [](auto x) { return log(x); };\n    for (Real x = 1.125; x < 8; x += 0.125)\n    {\n        Real cond = evaluation_condition_number(f1, x);\n        BOOST_CHECK_CLOSE_FRACTION(cond, 1/log(x), tol);\n    }\n\n    auto f2 = [](auto x) { return exp(x); };\n    for (Real x = 1.125; x < 8; x += 0.125)\n    {\n        Real cond = evaluation_condition_number(f2, x);\n        BOOST_CHECK_CLOSE_FRACTION(cond, x, tol);\n    }\n\n    auto f3 = [](auto x) { return sin(x); };\n    for (Real x = 1.125; x < 8; x += 0.125)\n    {\n        Real cond = evaluation_condition_number(f3, x);\n        BOOST_CHECK_CLOSE_FRACTION(cond, abs(x/tan(x)), tol);\n    }\n\n    // Test a function which right differentiable:\n    using boost::math::constants::e;\n    auto f4 = [](Real x) { return boost::math::lambert_w0(x); };\n    Real cond = evaluation_condition_number(f4, -1/e<Real>());\n    if (std::is_same_v<Real, float>)\n    {\n        BOOST_CHECK_GE(cond, 30);\n    }\n    else\n    {\n        BOOST_CHECK_GE(cond, 4900);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(numerical_differentiation_test)\n{\n    test_summation_condition_number<float>();\n    test_summation_condition_number<cpp_bin_float_50>();\n    test_evaluation_condition_number<float>();\n    test_evaluation_condition_number<double>();\n    test_evaluation_condition_number<long double>();\n    test_evaluation_condition_number<cpp_bin_float_50>();\n    test_exponential_sum<double>();\n}\n", "meta": {"hexsha": "2adb9be279ccecb7d91afd90d6d2c72e4b015809", "size": 3608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/test/condition_number_test.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/math/test/condition_number_test.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/math/test/condition_number_test.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 29.3333333333, "max_line_length": 74, "alphanum_fraction": 0.6521618625, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.5630141072203256}}
{"text": "#include \"ilp/eisenbrand_weismantel.hpp\"\n#include \"ilp/detail/debug.hpp\"\n#include \"ilp/detail/bellman_ford.hpp\"\n\n#include <iostream>\n#include <stack>\n#include <algorithm>\n\n#include <boost/graph/properties.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/named_function_params.hpp>\n\n// original boost header:\n//#include <boost/graph/bellman_ford_shortest_paths.hpp>\n\n// modified boost header:\n//#include \"ilp/detail/boost/bellman_ford_shortest_paths.hpp\"\n\nnamespace ilp\n{\n    EWDigraph::EWDigraph(const ilp::ilp_task& ilpTask) : DigraphAdaptor{ilpTask}\n    {\n        detail::debug_log(\"building EW digraph ...\");\n    }\n\n    bool EWDigraph::populate_condition(const cvector<int>& b,\n                                       const cvector<int>& p,\n                                       int bound) const\n    {\n        double dot_product_lhs = b.dot(p);\n        double dot_product_rhs = b.dot(b);\n        double coeff = dot_product_lhs / dot_product_rhs;\n        if (coeff > 1.0)\n        {\n            coeff = 1.0;\n        }\n\n        for (int i = 0; i < ilpTask.A.rows(); ++i)\n        {\n            auto b_val = static_cast<double>(b(i, 0));\n            double b_val_cut = b_val * coeff;\n            double p_val = p(i, 0);\n            if (std::abs(p_val - b_val_cut) > bound)\n            {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    void EWDigraph::populate_from(VertexDescriptor vertex,\n                                  int bound)\n    {\n        std::stack<VertexDescriptor> populated;\n        populated.push(vertex);\n\n        while (!populated.empty())\n        {\n            auto current_vertex = populated.top();\n            auto current_point = this->m_base[current_vertex].point;\n            populated.pop();\n\n            // iterate over A's columns\n            for (index_t i = 0; i != ilpTask.A.cols(); i++)\n            {\n                const cvector<int>& column = ilpTask.A.col(i);\n                current_point += column;\n\n                if (populate_condition(ilpTask.b, current_point, bound))\n                {\n                    // try to insert and get descriptor of a new or an existing vertex\n                    auto[new_vertex, is_new] = this->add_vertex(current_point);\n\n                    if (new_vertex == current_vertex)\n                    {\n                        continue;\n                    }\n\n                    // insert the new edge to the graph\n                    this->add_edge(current_vertex,\n                                   new_vertex,\n                                   EdgeProperty{-1 * ilpTask.c(i), static_cast<int>(i)}\n                    );\n\n                    // save the vertex descriptor for later recursive call of the populate function\n                    if (is_new)\n                    {\n                        populated.push(new_vertex);\n                    }\n                }\n\n                current_point -= column;\n            }\n        }\n    }\n\n    void EWDigraph::populate_graph()\n    {\n        const index_t m = ilpTask.A.rows();\n        const index_t n = ilpTask.A.cols();\n        const int delta = ilpTask.A.lpNorm<Eigen::Infinity>();\n        const int bound = 2 * static_cast<int>(m) * delta;\n\n        this->start = this->add_vertex(cvector<int>::Zero(m, 1)).first;\n        this->m_base[start].distance = 0;\n\n        populate_from(start, bound);\n\n        auto b_it = m_points_set.find(ilpTask.b);\n        this->bIsFeasible = (b_it != m_points_set.end());\n        if (bIsFeasible)\n        {\n            this->end = b_it->second;\n        }\n    }\n\n    ilp_solution eisenbrand_weismantel(const ilp_task& ilpTask)\n    {\n        const index_t m = ilpTask.A.rows();\n        const index_t n = ilpTask.A.cols();\n\n        ilp_solution result;\n        result.x = cvector<int>::Zero(n, 1);\n\n        ilp::EWDigraph graph{ilpTask};\n\n        {\n            graph.populate_graph();\n        }\n\n        result.is_feasible = graph.is_feasible();\n        if (result.is_feasible)\n        {\n            ilp::detail::debug_log(\"feasible\");\n\n/*            {\n                result.is_bounded = bellman_ford_shortest_paths(\n                        graph.m_base,\n                        num_vertices(graph.m_base),\n                        predecessor_map(get(&VertexProperty::predecessor, graph.m_base))\n                                .distance_map(get(&VertexProperty::distance, graph.m_base))\n                                .weight_map(get(&EdgeProperty::weight, graph.m_base))\n                );\n            }*/\n\n            {\n                result.is_bounded = ilp::detail::bellman_ford(graph.start,\n                                                              graph.m_base);\n            }\n\n            if (result.is_bounded)\n            {\n                VertexDescriptor vd = graph.end;\n                result.c_result = -1 * graph.m_base[vd].distance;\n\n                while (vd != graph.start)\n                {\n                    const auto& vertex = graph.m_base[vd];\n                    EdgeDescriptor ed = boost::edge(vertex.predecessor, vd, graph.m_base).first;\n                    const auto& edge = graph.m_base[ed];\n                    result.x(edge.column, 0) += 1;\n\n                    vd = vertex.predecessor;\n                }\n\n            }\n        }\n\n        return result;\n    }\n\n} // namespace ilp\n", "meta": {"hexsha": "42a445eb5a8036b6c275aa1624082074314202cd", "size": 5335, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eisenbrand_weismantel.cpp", "max_stars_repo_name": "pazamelin/ILP_algorithms", "max_stars_repo_head_hexsha": "5ca55f37a2e276d112124a5d02ef7ce686aa20f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/eisenbrand_weismantel.cpp", "max_issues_repo_name": "pazamelin/ILP_algorithms", "max_issues_repo_head_hexsha": "5ca55f37a2e276d112124a5d02ef7ce686aa20f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eisenbrand_weismantel.cpp", "max_forks_repo_name": "pazamelin/ILP_algorithms", "max_forks_repo_head_hexsha": "5ca55f37a2e276d112124a5d02ef7ce686aa20f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6609195402, "max_line_length": 99, "alphanum_fraction": 0.4999062793, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5629975980379734}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <cmath>\n#include <cfloat>\n#include <cstdint>\n#include <limits>\n#include <type_traits>\n#include <boost/math/ccmath/fpclassify.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\ntemplate <typename T>\nvoid test()\n{\n    if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    {\n        static_assert(boost::math::ccmath::fpclassify(std::numeric_limits<T>::quiet_NaN()) == FP_NAN);\n    }\n\n    static_assert(boost::math::ccmath::fpclassify(T(0)) == FP_ZERO);\n    static_assert(boost::math::ccmath::fpclassify(std::numeric_limits<T>::infinity()) == FP_INFINITE);\n    static_assert(boost::math::ccmath::fpclassify((std::numeric_limits<T>::min)() / T(2)) == FP_SUBNORMAL);\n    static_assert(boost::math::ccmath::fpclassify(T(1)) == FP_NORMAL);\n}\n\n#ifndef BOOST_MATH_NO_CONSTEXPR_DETECTION\nint main()\n{\n    test<float>();\n    test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test<long double>();\n    #endif\n    \n    #if defined(BOOST_HAS_FLOAT128) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\n    test<boost::multiprecision::float128>();\n    #endif\n\n    return 0;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "f109b224b9d5871c0a314d9d71d5cbed7f1e365e", "size": 1400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_fpclassify_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/ccmath_fpclassify_test.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/ccmath_fpclassify_test.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 26.4150943396, "max_line_length": 107, "alphanum_fraction": 0.7042857143, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5629975926550298}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EVecPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <smooth/compat/autodiff.hpp>\n\n#include \"smooth/feedback/ocp_flatten.hpp\"\n\nconstexpr auto DT = smooth::diff::Type::Autodiff;\n// constexpr auto DT = smooth::diff::Type::Numerical;\n\n#include \"ocp.hpp\"\n\nTEST(OcpFlatten, Basic)\n{\n  std::srand(10);\n\n  const auto t1 = smooth::feedback::test_ocp_derivatives<DT>(ocp_test, 5);\n  ASSERT_TRUE(t1);\n\n  const auto xl = []<typename T>(const T & t) -> smooth::CastT<T, OcpTest::X> {\n    const Eigen::Vector<T, Nx> vel{1, 2, 3};\n    return smooth::exp<smooth::CastT<T, OcpTest::X>>(t * vel);\n  };\n  const auto ul = []<typename T>(const T & t) -> smooth::CastT<T, OcpTest::U> {\n    const Eigen::Vector<T, Nu> vel{1, 2};\n    return smooth::exp<smooth::CastT<T, OcpTest::U>>(t * vel);\n  };\n\n  // test twice to catch allocation/compression issues (first call allocates)\n  auto ocp_flat  = smooth::feedback::flatten_ocp(ocp_test, xl, ul);\n  const auto t2a = smooth::feedback::test_ocp_derivatives<DT>(ocp_flat, 5);\n  ASSERT_TRUE(t2a);\n\n  const auto t2b = smooth::feedback::test_ocp_derivatives<DT>(ocp_flat, 5);\n  ASSERT_TRUE(t2b);\n}\n", "meta": {"hexsha": "24427fd83c01f1ed5332bda669e3f719205a0e2b", "size": 2408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_ocp_flatten.cpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_ocp_flatten.cpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_ocp_flatten.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": 38.8387096774, "max_line_length": 81, "alphanum_fraction": 0.7230066445, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5629975822465448}}
{"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 <boost/iterator/zip_iterator.hpp>\n#include <vector>\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::Point                                             Point;\ntypedef Delaunay::Vertex_handle                                     Vertex_handle;\n\nint main()\n{\n\n  std::vector<unsigned> indices;\n  indices.push_back(0);\n  indices.push_back(1);\n  indices.push_back(2);\n  indices.push_back(3);\n  indices.push_back(4);\n  indices.push_back(5);  \n  \n  std::vector<Point> points;\n  points.push_back(Point(0,0));\n  points.push_back(Point(1,0));\n  points.push_back(Point(0,1));\n  points.push_back(Point(1,47));\n  points.push_back(Point(2,2));\n  points.push_back(Point(-1,0));\n\n  \n  \n  Delaunay T;\n  T.insert( boost::make_zip_iterator(boost::make_tuple( points.begin(),indices.begin() )),\n            boost::make_zip_iterator(boost::make_tuple( points.end(),indices.end() ) )  );\n\n  CGAL_assertion( T.number_of_vertices() == 6 );\n  \n  \n  // check that the info was correctly set.\n\n  for (Vertex_handle v : T.finite_vertex_handles())\n    if( points[ v->info() ] != v->point() ){\n      std::cerr << \"Error different info\" << std::endl;\n      exit(EXIT_FAILURE);\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "884f4d9d23ccf331450c4be9d366f0ddffe25fce", "size": 1601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/Triangulation_2/info_insert_with_zip_iterator_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/examples/Triangulation_2/info_insert_with_zip_iterator_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/examples/Triangulation_2/info_insert_with_zip_iterator_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": 30.7884615385, "max_line_length": 90, "alphanum_fraction": 0.6627108057, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5629975822465448}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <opencv2/opencv.hpp>\n#include <dlib/matrix.h>\n\nusing namespace std;\nusing namespace cv;\nusing namespace dlib;\n\nmatrix<double> getColMatrix( string filename ) {\n    FileStorage fs( filename, FileStorage::READ );\n    if( !fs.isOpened() ){\n        cout << \"File not found : \" << filename << endl;\n        return ones_matrix<double>(1, 1); \n    }\n    FileNode features = fs[\"features\"];\n    int num_points = features.size()*2;\n    matrix<double> p( num_points, 1 );\n    FileNodeIterator it_start = features.begin();\n    FileNodeIterator it_end = features.end(); \n    std::vector<double> x_points, y_points;\n    for( ; it_start != it_end; ++it_start ){\n        double x = (double)(*it_start)[\"x\"];\n        double y = (double)(*it_start)[\"y\"];\n        x_points.push_back( x );\n        y_points.push_back( y );\n    }\n    x_points.insert( x_points.end(), y_points.begin(), y_points.end() );\n    fs.release();\n\n    return mat(x_points);;\n}\n\nint main ( int argc, char *argv[] ) {\n    matrix<double> points_pool, mean_matrix;\n    int num_shape = atoi(argv[1]);\n    bool init = true;\n    // Initialize Points pool\n    for( int i = 1; i <= num_shape; ++i ){\n        string l_filename = \"./dataset/\"+to_string(i)+\"L.yaml\"; \n        string r_filename = \"./dataset/\"+to_string(i)+\"R.yaml\"; \n        matrix<double> l_p = getColMatrix( l_filename );\n        matrix<double> r_p = getColMatrix( r_filename );\n        bool found_left = points_pool.nr() == l_p.nr();\n        bool found_right = points_pool.nr() == r_p.nr();\n        if( init ){\n            points_pool = join_rows( points_pool, l_p );\n            init = false;\n        }\n        else {\n            if( found_left )\n                points_pool = join_rows( points_pool, l_p );\n\n            if( found_right )\n                points_pool = join_rows( points_pool, r_p );\n        }\n        \n    }\n\n    int pool_nr = points_pool.nr();\n    int pool_nc = points_pool.nc();\n    std::vector<double> mean_vector;\n    for( int i = 0; i < pool_nr; ++i ){\n        mean_vector.push_back( sum_cols( rowm( points_pool, i )/pool_nc ) );\n    }\n\n    // Writing MeanShape\n    string fn = \"./dataset/meanShape.yaml\";\n    FileStorage fs( fn, FileStorage::WRITE );\n    fs << \"filename\" << fn;\n\n    mean_matrix = mat( mean_vector );\n    std::vector<Point2f> p_store;\n    matrix<Point2f> mean_point;\n    fs << \"features\" << \"[\";\n    for( int i = 0; i < mean_matrix.nr()/2; ++i ){\n            fs << \"{:\";\n            fs << \"p\" << i << \"x\" << (int)mean_matrix(i) << \"y\" << (int)mean_matrix(i+68); \n            fs << \"}\";\n        Point2f p( mean_matrix(i),  mean_matrix(i+68) );\n        p_store.push_back( p );\n    }\n    fs << \"]\";\n    mean_point = mat( p_store );\n    cout << mean_matrix << endl;\n    cout << mean_point << endl;\n    return 0;\n}\n", "meta": {"hexsha": "8e50d551af5e6b9c14934d1ca6b9aff923ed8ce4", "size": 2828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "face2yaml/src/meanShape.cpp", "max_stars_repo_name": "adadesions/trainingJackson", "max_stars_repo_head_hexsha": "ac17bbd7155b6f04c28662ff1007ee28b73aacfc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "face2yaml/src/meanShape.cpp", "max_issues_repo_name": "adadesions/trainingJackson", "max_issues_repo_head_hexsha": "ac17bbd7155b6f04c28662ff1007ee28b73aacfc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "face2yaml/src/meanShape.cpp", "max_forks_repo_name": "adadesions/trainingJackson", "max_forks_repo_head_hexsha": "ac17bbd7155b6f04c28662ff1007ee28b73aacfc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4222222222, "max_line_length": 91, "alphanum_fraction": 0.5693069307, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5629975818891424}}
{"text": "//\n//  Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n\n#include <boost/numeric/ublas/tensor.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include \"utility.hpp\"\n\nBOOST_AUTO_TEST_SUITE(test_tensor_static_arithmetic_operations)\n\nusing double_extended = boost::multiprecision::cpp_bin_float_double_extended;\n\nusing test_types = zip<int,float,double_extended>::with_t<boost::numeric::ublas::layout::first_order, boost::numeric::ublas::layout::last_order>;\n\nstruct fixture\n{\n    template<size_t... N>\n    using extents_type = boost::numeric::ublas::extents<N...>;\n\n    fixture() = default;\n\n    std::tuple<\n        extents_type<1,1>,   // 1\n        extents_type<2,3>,   // 2\n        extents_type<4,1,3>,  // 3\n        extents_type<4,2,3>,  // 4\n        extents_type<4,2,3,5>   // 5\n    > extents;\n\n};\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_binary_arithmetic_operations, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n\n    auto check = [](auto const& /*unused*/, auto& e)\n    { \n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type,extents_type,layout_type>;\n        auto t  = tensor_type ();\n        auto t2 = tensor_type ();\n        auto r  = tensor_type ();\n        auto v  = value_type  {};\n\n        std::iota(t.begin(), t.end(), v);\n        std::iota(t2.begin(), t2.end(), v+2);\n\n        r = t + t + t + t2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 3*t(i) + t2(i) );\n\n\n        r = t2 / (t+3) * (t+1) - t2; // r = ( t2/ ((t+3)*(t+1)) ) - t2\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), t2(i) / (t(i)+3)*(t(i)+1) - t2(i) );\n\n        r = 3+t2 / (t+3) * (t+1) * t - t2; // r = 3+( t2/ ((t+3)*(t+1)*t) ) - t2\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 3+t2(i) / (t(i)+3)*(t(i)+1)*t(i) - t2(i) );\n\n        r = t2 - t + t2 - t;\n\n        for(auto i = 0ul; i < r.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 4 );\n\n\n        r = tensor_type (1) + tensor_type (1);\n\n        for(auto i = 0ul; i < r.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 2 );\n\n        r = t * t * t * t2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), t(i)*t(i)*t(i)*t2(i) );\n\n        r = (t2/t2) * (t2/t2);\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 1 );\n    };\n\n    for_each_in_tuple(extents,check);\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_unary_arithmetic_operations, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n\n    auto check = [](auto const& /*unused*/, auto& e)\n    {\n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type,extents_type,layout_type>;\n        auto t  = tensor_type ();\n        auto t2 = tensor_type ();\n        auto v  = value_type  {};\n\n        std::iota(t.begin(), t.end(), v);\n        std::iota(t2.begin(), t2.end(), v+2);\n\n        tensor_type r1 = t + 2 + t + 2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r1(i), 2*t(i) + 4 );\n\n        tensor_type r2 = 2 + t + 2 + t;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r2(i), 2*t(i) + 4 );\n\n        tensor_type r3 = (t-2) + (t-2);\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r3(i), 2*t(i) - 4 );\n\n        tensor_type r4 = (t*2) * (3*t);\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r4(i), 2*3*t(i)*t(i) );\n\n        tensor_type r5 = (t2*2) / (2*t2) * t2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r5(i), (t2(i)*2) / (2*t2(i)) * t2(i) );\n\n        tensor_type r6 = (t2/2+1) / (2/t2+1) / t2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r6(i), (t2(i)/2+1) / (2/t2(i)+1) / t2(i) );\n\n    };\n\n    for_each_in_tuple(extents,check);\n}\n\n\n\n\n\nBOOST_FIXTURE_TEST_CASE_TEMPLATE( test_tensor_assign_arithmetic_operations, value,  test_types, fixture)\n{\n    namespace ublas = boost::numeric::ublas;\n    using value_type  = typename value::first_type;\n    using layout_type = typename value::second_type;\n\n\n    auto check = [](auto const& /*unused*/, auto& e)\n    {\n        using extents_type = std::decay_t<decltype(e)>;\n        using tensor_type = ublas::tensor_static<value_type,extents_type,layout_type>;\n        auto t  = tensor_type ();\n        auto t2 = tensor_type ();\n        auto r  = tensor_type ();\n        auto v  = value_type  {};\n\n        std::iota(t.begin(), t.end(), v);\n        std::iota(t2.begin(), t2.end(), v+2);\n\n        r  = t + 2;\n        r += t;\n        r += 2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 2*t(i) + 4 );\n\n        r  = 2 + t;\n        r += t;\n        r += 2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 2*t(i) + 4 );\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 2*t(i) + 4 );\n\n        r = (t-2);\n        r += t;\n        r -= 2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 2*t(i) - 4 );\n\n        r  = (t*2);\n        r *= 3;\n        r *= t;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), 2*3*t(i)*t(i) );\n\n        r  = (t2*2);\n        r /= 2;\n        r /= t2;\n        r *= t2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), (t2(i)*2) / (2*t2(i)) * t2(i) );\n\n        r  = (t2/2+1);\n        r /= (2/t2+1);\n        r /= t2;\n\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( r(i), (t2(i)/2+1) / (2/t2(i)+1) / t2(i) );\n\n        tensor_type q = -r;\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( q(i), -r(i) );\n\n        tensor_type p = +r;\n        for(auto i = 0ul; i < t.size(); ++i)\n            BOOST_CHECK_EQUAL ( p(i), r(i) );\n    };\n\n    for_each_in_tuple(extents,check);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "71e1447adc35d4c241b934a1e4738c4bf8e21779", "size": 6665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_static_operators_arithmetic.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_static_operators_arithmetic.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_static_operators_arithmetic.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": 27.4279835391, "max_line_length": 145, "alphanum_fraction": 0.5215303826, "num_tokens": 2138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6791786991753931, "lm_q1q2_score": 0.5629975815317395}}
{"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": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestNormalDistribution\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/algorithm/count_if.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/random/default_random_engine.hpp>\n#include <boost/compute/random/normal_distribution.hpp>\n#include <boost/compute/lambda.hpp>\n\n#include \"context_setup.hpp\"\n\nBOOST_AUTO_TEST_CASE(normal_distribution_doctest)\n{\n    using boost::compute::lambda::_1;\n\n    boost::compute::vector<float> vec(10, context);\n\n//! [generate]\n// initialize the default random engine\nboost::compute::default_random_engine engine(queue);\n\n// setup the normal distribution to produce floats centered at 5\nboost::compute::normal_distribution<float> distribution(5.0f, 1.0f);\n\n// generate the random values and store them to 'vec'\ndistribution.generate(vec.begin(), vec.end(), engine, queue);\n//! [generate]\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "98570e430fde1fb2dcd248a35724c7577ac71a06", "size": 1435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_normal_distribution.cpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "test/test_normal_distribution.cpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_normal_distribution.cpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3720930233, "max_line_length": 79, "alphanum_fraction": 0.6857142857, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5629975650255054}}
{"text": "\n#include <boost/test/unit_test.hpp>\n#include <Eigen/Dense>\n\n#include \"../src/KRAverager.hpp\"\n\n#include \"utils/log.hpp\"\n\nBOOST_AUTO_TEST_SUITE(kr_averager_tests)\n    BOOST_AUTO_TEST_CASE(cis_averager) {\n        TEST_MESSAGE(\"cis_averager\");\n\n        KRAveragerCis averager(3.0);\n        Eigen::VectorXd ks(3);\n        Eigen::VectorXd rs(3);\n\n        ks << 1.0, 1.5, 4.0;\n        rs << 2.0, 2.5, 5.0;\n\n        averager.add_force_constant_vector(ks, rs);\n        double r_cis = averager.get_range_cis();\n        double k_cis = averager.get_force_constant_cis();\n\n        BOOST_CHECK_EQUAL(r_cis, 2.25);\n        BOOST_CHECK_EQUAL(k_cis, 1.25);\n\n\n\n    }\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "84c2865c0f449a7d04d226cd1b4a8ecdb91ddfa2", "size": 678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/KRAverager.cpp", "max_stars_repo_name": "AFriemann/LowCarb", "max_stars_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/KRAverager.cpp", "max_issues_repo_name": "AFriemann/LowCarb", "max_issues_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-15T13:57:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-15T13:57:26.000Z", "max_forks_repo_path": "test/KRAverager.cpp", "max_forks_repo_name": "AFriemann/LowCarb", "max_forks_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8709677419, "max_line_length": 57, "alphanum_fraction": 0.6430678466, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5629892752473828}}
{"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": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/matrix/comparison.hpp>\n#include <fcppt/math/matrix/output.hpp>\n#include <fcppt/math/matrix/row.hpp>\n#include <fcppt/math/matrix/static.hpp>\n#include <fcppt/math/matrix/transpose.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_matrix_transpose\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tint,\n\t\t2,\n\t\t3\n\t>\n\tmatrix_type;\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tint,\n\t\t3,\n\t\t2\n\t>\n\ttransposed_matrix_type;\n\n\ttransposed_matrix_type const transposed(\n\t\tfcppt::math::matrix::transpose(\n\t\t\tmatrix_type(\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t1, 2, 3\n\t\t\t\t),\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t4, 5, 6\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\ttransposed,\n\t\ttransposed_matrix_type(\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t1, 4\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t2, 5\n\t\t\t),\n\t\t\tfcppt::math::matrix::row(\n\t\t\t\t3, 6\n\t\t\t)\n\t\t)\n\t);\n}\n", "meta": {"hexsha": "7f3cbc691b249c7d2902d028ee0767c439e114de", "size": 1393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/matrix/transpose.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/matrix/transpose.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/matrix/transpose.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0821917808, "max_line_length": 61, "alphanum_fraction": 0.6934673367, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.562954588769448}}
{"text": "#pragma once\r\n#ifndef TYPEDEF_HPP\r\n#define TYPEDEF_HPP\r\n\r\n#define EIGEN_NO_DEBUG\r\n\r\n// extern - Eigen\r\n#include <Eigen/Dense>\r\n\r\ntypedef Eigen::Matrix<double,3,1> Vec3d;\r\ntypedef Eigen::Matrix<double,Eigen::Dynamic,1> VecXd;\r\ntypedef Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> MatXd;\r\n\r\n#endif\r\n", "meta": {"hexsha": "f4ff808bcea8bb88af1b51ece6e70c4394105b9c", "size": 304, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/util/typedef.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/util/typedef.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/util/typedef.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": 20.2666666667, "max_line_length": 67, "alphanum_fraction": 0.7335526316, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5629545794326226}}
{"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": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/Novelty.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass NoveltyFeature\n{\n\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n\n  NoveltyFeature(index maxKernelSize, index maxFilterSize)\n      : mFilterBufferStorage(maxFilterSize), mNovelty(maxKernelSize)\n  {}\n\n  void init(index kernelSize, index filterSize, index nDims)\n  {\n    assert(kernelSize % 2);\n    mNovelty.init(kernelSize, nDims);\n    mFilterBuffer = mFilterBufferStorage.segment(0, filterSize);\n    mFilterBuffer.setZero();\n  }\n\n  double processFrame(const RealVectorView input)\n  {\n    double novelty = mNovelty.processFrame(_impl::asEigen<Eigen::Array>(input));\n    index  filterSize = mFilterBuffer.size();\n\n    if (filterSize > 1)\n    {\n      mFilterBuffer.segment(0, filterSize - 1) =\n          mFilterBuffer.segment(1, filterSize - 1);\n    }\n\n    mFilterBuffer(filterSize - 1) = novelty;\n\n    return mFilterBuffer.mean();\n  }\n\nprivate:\n  ArrayXd mFilterBuffer;\n  ArrayXd mFilterBufferStorage;\n  Novelty mNovelty;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "6590c9631a4feef2a1610480b70ad70ab341ed5b", "size": 1605, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/NoveltyFeature.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/NoveltyFeature.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/NoveltyFeature.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4761904762, "max_line_length": 80, "alphanum_fraction": 0.7289719626, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5628244373561728}}
{"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": "/***************************************************************************\n *   Copyright (C) 2007 by BEEKHOF, Fokko                                  *\n *   fpbeekhof@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 *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************/\n\n#include <limits>\n#include <climits>\n#include <cassert>\n#include <utility>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n#include \"../base/stl_cmath.h\"\n\n#include \"../base/use_omp.h\"\n#include \"../../omptl/omptl_algorithm\"\n#include \"../../omptl/omptl_numeric\"\n\n#include \"../base/Functors\"\n#include \"../base/CyclicBuffer\"\n\n#include \"../math/ContainerOps.h\"\n\nnamespace cvmlcpp\n{\n\nnamespace detail\n{\n\ntemplate <typename T, typename U>\nT round_cast_(const U &u, std::tr1::true_type)\n{\n\treturn static_cast<T>(u);\n}\n\ntemplate <typename T, typename U>\nT round_cast_(const U &u, std::tr1::false_type)\n{\n\treturn static_cast<T>(u + ((u>=0)?U(0.5):U(-0.5)) );\n}\n\n} // end namespace detail\n\ntemplate <typename T, typename U>\nT round_cast(const U &u)\n{\n\treturn detail::round_cast_<T, U>(u, std::tr1::is_floating_point<T>());\n}\n\nnamespace detail\n{\n\ntemplate <typename T>\nT log2_(T n, std::tr1::false_type)\n{\n\tassert(n > 0);\n\tconst std::size_t N = CHAR_BIT*sizeof(T);\n\n\tT result = 0;\n\tfor (std::size_t i = 1; i < N; ++i)\n\t{\n\t\tconst std::size_t M = N-i;\n\t\tif ( n >= (std::size_t(1) << M) )\n\t\t{\n\t\t\tn >>= M;\n\t\t\tresult |= M;\n\t\t}\n\t}\n\n\treturn result;\n}\n\ntemplate <typename T>\nT log2_(const T &n, std::tr1::true_type)\n{\n#ifdef _HAVE_TR1_CMATH\n\tusing std::tr1::log2;\n\treturn log2(n);\n#else\n\tusing std::log;\n\treturn log(n) / log(2.0);\n#endif\n}\n\n} // end namespace detail\n\ntemplate <typename T>\nT log2(const T n)\n{\n\tassert(n > T(0)); // Bogus user input ?\n\treturn detail::log2_(n, std::tr1::is_floating_point<T>());\n}\n\ntemplate <typename T>\nT factorial(const T &x)\n{\n\t// Check user input\n\tassert(x >= 0);\n\n\tstatic std::size_t ntop = 12;\n\tconst std::size_t cache_size = 32;\n\tstatic T cache[cache_size] = {\n\t1, 1, 2, 6, 24, 120, 720, 5040,\n\t40320, 362880, 3628800, 39916800, 479001600};\n\n#ifdef _HAVE_TR1_CMATH\n\tassert(x == std::tr1::round(x));\n#endif\n\n\tif (x >= T(cache_size))\n\t{\n\t\t#ifdef _HAVE_TR1_CMATH\n \t\treturn std::tr1::round(std::tr1::tgamma(x+1.0));\n\t\t#else\n\t\tassert(ntop > 0);\n\t\tT v = cache[ntop-1];\n\t\tstd::size_t part1 = round_cast<std::size_t>(std::min(T(cache_size), x));\n\t\tfor (std::size_t i = ntop+1; i < part1; ++i)\n\t\t{\n\t\t\tv *= static_cast<T>(i);\n\t\t\tcache[i] = v;\n\t\t}\n\t\tntop = part1;\n\n\t\t// Non-cached part\n\t\tfor (T i = part1+1; i < x; ++i)\n\t\t\tv *= static_cast<T>(i);\n\n\t\treturn v;\n\t\t#endif\n\t}\n\n\twhile (x > ntop)\n\t{\n\t\tcache[ntop] = cache[ntop-1u] * ntop;\n\t\t++ntop;\n\t}\n\tassert(ntop >= x);\n\n#ifdef _HAVE_TR1_CMATH\n\treturn cache[std::tr1::lround(x)];\n#else\n\treturn cache[round_cast<std::size_t>(x)];\n#endif\n}\n\n// Function gcd adapted from wikipedia: http://en.wikipedia.org/wiki/Binary_GCD_algorithm\nnamespace detail\n{\n\ntemplate <bool is_integer = false>\nstruct GCD\n{\n\t// euclidean based implementation\n\ttemplate <typename T>\n\tstatic const T gcd(T u, T v)\n\t{\n\t\tassert(u >= 0);\n\t\tassert(v >= 0);\n\n\t\tusing std::floor;\n\t\tu = floor(u+T(0.5));\n\t\tv = floor(v+T(0.5));\n\n\t\tusing std::max;\n\t\tif (u < 1 || v < 1) // in case one is zero\n\t\t\tmax(u, v);\n\n\t\twhile (u > T(0.5)) // take care of roundoff problems\n\t\t{\n\t\t\tconst T t = u;\n\t\t\tusing std::floor;\n\t\t\tu = floor(v - floor(v / u)*u + T(0.5)); // modulus\n\t\t\tv = t;\n\t\t}\n\t\tassert(floor(v) == v);\n\n\t\treturn v;\n\t}\n};\n\ntemplate <>\nstruct GCD<true>\n{\n\t// Function gcd adapted from wikipedia: http://en.wikipedia.org/wiki/Binary_GCD_algorithm\n\ttemplate <typename T>\n\tstatic const T gcd(T u, T v)\n\t{\n\t\t// Use this function only for integers\n\t\tassert(std::tr1::is_integral<T>::value);\n\n\t\t/* GCD(0,x) := x */\n\t\tif (u == 0 || v == 0)\n\t\t\treturn u | v;\n\n\t\t/* Let shift := lg K, where K is the greatest power of 2\n\t\tdividing both u and v. */\n\t\tT shift = 0;\n\t\tfor (; ((u | v) & 1) == 0; ++shift)\n\t\t{\n\t\t\tu >>= 1;\n\t\t\tv >>= 1;\n\t\t}\n\n\t\twhile ((u & 1) == 0)\n\t\t\tu >>= 1;\n\n\t\t/* From here on, u is always odd. */\n\t\tassert(u & 1);\n\t\tdo {\n\t\t\twhile ((v & 1) == 0)  /* Loop X */\n\t\t\t\tv >>= 1;\n\n\t\t\t/* Now u and v are both odd, so diff(u, v) is even.\n\t\t\tLet u = min(u, v), v = diff(u, v)/2. */\n\t\t\tif (u < v)\n\t\t\t\tv -= u;\n\t\t\telse\n\t\t\t{\n\t\t\t\tconst T diff = u - v;\n\t\t\t\tu = v;\n\t\t\t\tv = diff;\n\t\t\t}\n\t\t\tv >>= 1;\n\t\t} while (v != 0);\n\n\t\treturn u << shift;\n\t}\n};\n\n}\n\ntemplate <typename T>\nT gcd(const T u, const T v)\n{\n\treturn detail::GCD<std::tr1::is_integral<T>::value>::gcd(u, v);\n}\n\nnamespace detail\n{\n\ntemplate <bool is_integer = false>\nstruct Binomial\n{\n\ttemplate <typename T>\n\tstatic const T binomial(const T n, const T k)\n\t{\n\t\t//return factorial(n) / (factorial(k) * factorial(n-k));\n\t\tif (n == k)\n\t\t\treturn 1;\n\t\tif (n == k+1)\n\t\t\treturn n;\n\n\t\t// Factors\n\t\tassert(k < n);\n\t\tstd::vector<T> ns(n-k), ks(n-k-1);\n\t\tassert(ks.size() >= 1);\n\t\tfor (T i = 0; i < n-k; ++i)\n\t\t\tns[i] = k+1+i;\n\t\tfor (T i = 2; i <= n-k; ++i)\n\t\t\tks[i-2] = i;\n\n\t\t// Simplify\n\t\tfor (std::size_t i = 0; i < ks.size(); ++i)\n\t\t{\n\t\t\tif (ks[i] > 1)\n\t\t\t{\n\t\t\t\tfor (std::size_t j = 0; j < ns.size(); ++j)\n\t\t\t\t\tif (ns[j] > 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst T d = gcd(ns[j], ks[i]);\n//\t\t\t\t\t\tassert( (ks[i] % d) == 0 );\n//\t\t\t\t\t\tassert( (ns[j] % d) == 0 );\n\t\t\t\t\t\tks[i] /= d;\n\t\t\t\t\t\tns[j] /= d;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// After simplification, denominator is one\n\t\tassert(std::abs(std::accumulate(ks.begin(), ks.end(), T(1), std::multiplies<T>()) - T(1)) < 0.001);\n\n\t\t// Final division not needed, denominator is one\n\t\treturn std::accumulate(ns.begin(), ns.end(), T(1), std::multiplies<T>());\n\t}\n};\n\ntemplate <>\nstruct Binomial<true>\n{\n\ttemplate <typename T>\n\tstatic const T binomial(const T n, T k)\n\t{\n\t\tenum {N, K, RESULT};\n\t\tconst T CACHE_SIZE = 29;\n\t\tstatic std::vector<std::vector<std::tr1::array<T, 3> > > cache;\n\n\t\t// Init cache if needed\n\t\tif (cache.empty())\n\t\t{\n\t\t\tcache.resize(CACHE_SIZE);\n\t\t\tfor (T i = 0; i < CACHE_SIZE; ++i)\n\t\t\t{\n\t\t\t\tcache[i].resize(CACHE_SIZE);\n\t\t\t\tfor (T j = 0; j < CACHE_SIZE; ++j)\n\t\t\t\t\tstd::fill(cache[i][j].begin(), cache[i][j].end(), 0);\n\t\t\t}\n\t\t}\n\n\t\t// Check in cache\n\t\tconst T cn = n % CACHE_SIZE;\n\t\tconst T ck = k % CACHE_SIZE;\n\t\tif ( (cache[cn][ck][N] == n) && (cache[cn][ck][K] == k) )\n\t\t\treturn cache[cn][ck][RESULT];\n\n\n\t\t/*\n\t\t * General approach:\n\t\t *      n!       prod(k+1:n)\n\t\t * ---------- = ----------\n\t\t * (n-k)! k!      (n-k)!\n\t\t * Then factor out GCD's to try to avoid overflow\n\t\t */\n\t\tassert (k <= n);\n\n\t\t// Optimize for complexity, binomial is symmetric for\n\t\t// k or n-k, but selecting the largest of the 2 leads to\n\t\t// less terms in the sequences.\n\t\tk = std::max(k, n-k);\n\n\t\t// Simple cases that lead to complex indices below\n\t\tif (n == k)\n\t\t\treturn 1;\n\t\tif (n == k+1)\n\t\t\treturn n;\n\n\t\t// Factors\n\t\tassert(k < n);\n\t\tstd::vector<T> ns(n-k), ks(n-k-1);\n\t\tassert(ks.size() >= 1);\n\t\tfor (T i = 0; i < n-k; ++i)\n\t\t\tns[i] = k+1+i;\n\t\tfor (T i = 2; i <= n-k; ++i)\n\t\t\tks[i-2] = i;\n\n\t\t// Simplify\n\t\tfor (std::size_t i = 0; i < ks.size(); ++i)\n\t\t{\n\t\t\tif (ks[i] > 1)\n\t\t\t{\n\t\t\t\tfor (std::size_t j = 0; j < ns.size(); ++j)\n\t\t\t\t\tif (ns[j] > 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst T d = gcd(ns[j], ks[i]);\n\t\t\t\t\t\tassert( (ks[i] % d) == 0 );\n\t\t\t\t\t\tassert( (ns[j] % d) == 0 );\n\t\t\t\t\t\tks[i] /= d;\n\t\t\t\t\t\tns[j] /= d;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// After simplification, denominator is one\n\t\tassert(std::accumulate(ks.begin(), ks.end(), T(1), std::multiplies<T>()) == T(1));\n\n\t\t// Final division not needed, denominator is one\n\t\tconst T result = std::accumulate(ns.begin(), ns.end(), T(1), std::multiplies<T>());\n\t\t\t\t// / std::accumulate(ks.begin(), ks.end(), T(1), std::multiplies<T>());\n\n\t\t// keep result in cache\n\t\tcache[cn][ck][RESULT] = result;\n\n\t\treturn result;\n\t}\n};\n\n}\n\ntemplate <typename T>\nT binomial(const T n, const T k)\n{\n\t// verify user input\n\tassert(n >= k);\n\treturn detail::Binomial<std::tr1::is_integral<T>::value>::binomial(n, k);\n}\n\ntemplate <typename T>\nT binopmf(const std::size_t n, const std::size_t k, const T p)\n{\n\tBOOST_STATIC_ASSERT(!std::numeric_limits<T>::is_integer);\n\tassert(n >= k);\n\tassert(p >= 0);\n\tassert(p <= 1);\n\tusing std::pow;\n\n\tconst std::size_t max_bits_needed_for_binomial = (n+1)/2 * (log2(n)+1);\n\n\tconst T binomial_n_k = (max_bits_needed_for_binomial < CHAR_BIT * sizeof(std::size_t) ) ?\n\t\tbinomial(n, k) : // fast integer binomial\n\t\tbinomial(T(n), T(k));  // FP binomial, no overflow\n\n\treturn binomial_n_k * pow(p, T(k)) * pow( T(1)-p, T(n-k) );\n}\n\ntemplate <typename T>\nT binocdf(const std::size_t n, const std::size_t k, const T p)\n{\n\tBOOST_STATIC_ASSERT(!std::numeric_limits<T>::is_integer);\n\tassert(n >= k);\n\tassert(p >= 0);\n\tassert(p <= 1);\n\n\tT bin = 1;\n\tT result = 0;\n\tT pk = 1;\n\tusing std::pow;\n\tT pnk = pow(T(1)-p, T(n));\n\tfor (std::size_t i = 0; i < k; ++i)\n\n\t{\n\t\tresult += T(bin) * pk * pnk;\n\t\t//const T g = gcd(n-i, i+1);\n\t\tbin *= (n-i);  //((n-i) / g);\n\t\tbin /= (i+1);  //((i+1) / g);\n//\t\tassert(bin == binomial(n, i+1)); // can be triggered by numerical issues\n\t\tpk  *= p;\n\t\tpnk /= T(1)-p;\n\t}\n\tresult += bin * pk * pnk;\n\n\treturn result;\n}\n\ntemplate <typename T, typename U>\nstd::size_t binocdfinv(const T p_arg, const std::size_t n, const U p)\n{\n\tBOOST_STATIC_ASSERT(!std::numeric_limits<T>::is_integer);\n\tassert(n > 0);\n\n\tassert(p_arg >= 0.0);\n\tassert(p_arg <= 1.0);\n\n\tassert(p >= 0.0);\n\tassert(p <= 1.0);\n\n\tstd::size_t result = 0;\n\tT cdf = binopmf(0, n, p);\n\twhile ( (cdf < p_arg) && (result < n) )\n\t{\n\t\t++result;\n\t\tcdf += binopmf(result, n, p);\n\t}\n\tassert(result <= n);\n\treturn result;\n}\n\n#ifdef __GXX_EXPERIMENTAL_CXX0X__\ntemplate <typename T>\nT qfunc(const T x) { return T(0.5) * std::erfc(x / std::sqrt(T(2))); }\n#endif\n\n/**\n * Simple Statistics\n */\n\nnamespace detail\n{\n\ntemplate <typename T>\ntypename T::value_type modulus_(const T &x, std::tr1::false_type)\n{\n\ttypedef typename T::value_type VT;\n\tconst VT rv = omptl::transform_accumulate(x.begin(), x.end(), VT(0),\n\t\t\t\t\t\tcvmlcpp::Square<VT>());\n\t\n\treturn round_cast<VT>(std::sqrt(rv));\n}\n\ntemplate <typename T>\nT modulus_arithmic_(const T &x, std::tr1::true_type)\n{\n\treturn x;\n}\n\ntemplate <typename T>\nT modulus_arithmic_(const T &x, std::tr1::false_type)\n{\n\tusing std::abs;\n\treturn abs(x);\n}\n\ntemplate <typename T>\nT modulus_(const T &x, std::tr1::true_type)\n{\n\treturn modulus_arithmic_(x, std::tr1::is_unsigned<T>());\n}\n\n} // end namespace detail\n\ntemplate <typename T>\ntypename ValueType<T>::value_type modulus(const T &x)\n{\n\treturn round_cast<typename ValueType<T>::value_type>\n\t\t(detail::modulus_(x, std::tr1::is_arithmetic<T>()));\n}\n/*\ntemplate <typename Iterator, typename T>\ntypename promote_trait1<T>::value_type average(Iterator begin, Iterator end, const T init)\n{\n\ttypedef typename promote_trait1<T>::value_type R;\n\tconst typename std::iterator_traits<Iterator>::difference_type\n\t\tn = std::distance(begin, end);\n\tassert(n >= 0);\n\n\tif (n == 0)\n\t\treturn R(init);\n\n\treturn R(omptl::accumulate(begin, end, init)) / static_cast<R>(n);\n}\n*/\n/*\ntemplate <typename Iterator, typename T>\nT median(Iterator begin, Iterator end, const T init)\n{\n\tif (std::distance(begin, end) < 1)\n\t\treturn init;\n\tstd::vector<T> data(std::distance(begin, end));\n\tstd::copy(begin, end, data.begin());\n\tomptl::sort(data.begin(), data.end());\n\treturn init + *(data.begin() + data.size() / 2u);\n}\n*/\nnamespace detail\n{\n\ntemplate <typename T>\nclass Variance_\n{\n\tpublic:\n\t\ttypedef T value_type;\n\t\ttypedef T result_type;\n\n\t\tVariance_(const T mean = T(0)) : mean_(mean) {}\n\n\t\tT operator()(const T &elem) const\n\t\t{\n\t\t\treturn std::pow(elem - mean_, T(2));\n\t\t}\n\n\tprivate:\n\t\tconst T mean_;\n};\n\n} // end namespace detail\n/*\ntemplate <typename Iterator, typename T, typename U>\ntypename promote_trait1<T>::value_type variance(Iterator begin, Iterator end, const T mean, const U init)\n{\n\ttypedef typename promote_trait1<T>::value_type R;\n\tconst typename std::iterator_traits<Iterator>::difference_type\n\t\tn = std::distance(begin, end);\n\tassert(n >= 0);\n\n\tif (n < 2)\n\t\treturn init;\n\n\tif (mean == T(0))\n\t\treturn R(init) +\n\t\t\tR(omptl::transform_accumulate(begin,end,T(0),Square<T>()))\n\t\t\t// ----------------------------------------------\n\t\t\t\t\t/ static_cast<R>(n-1);\n\n\tdetail::Variance_<T> var((mean));\n\treturn R(init) + R(omptl::transform_accumulate(begin, end, T(0), var))\n\t\t\t// ----------------------------------------------\n\t\t\t\t\t/ static_cast<R>(n-1);\n}\n*/\ntemplate <typename Iterator, typename T>\ntypename promote_trait1<T>::value_type variance(Iterator begin, Iterator end, const T init)\n{\n\treturn variance(begin, end, average(begin, end, T(0)), init);\n}\n\ntemplate <typename Iterator, typename T>\ntypename promote_trait1<T>::value_type deviation(Iterator begin, Iterator end, const T init)\n{\n\treturn init + std::sqrt(variance(begin, end, T(0), init));\n}\n\ntemplate <typename Iterator, typename T, typename U>\ntypename promote_trait1<T>::value_type deviation(Iterator begin, Iterator end, const T mean, const U init)\n{\n\treturn init + std::sqrt(variance(begin, end, mean, U(0)));\n}\n\n/*\ntemplate <typename Iterator, typename T>\nT generalizedGaussianShape(Iterator begin, Iterator end,\n\t\t\t   const T avg, const T init)\n{\n\tconst typename std::iterator_traits<Iterator>::difference_type\n\t\tn = std::distance(begin, end);\n\tassert(n >= 0);\n\n\tif (n < 2)\n\t\treturn init;\n\n\tconst T lut [] = {\n\t\t0.0000000e+00, 1.3426932e-03, 1.1876961e-02, 3.5319079e-02,\n\t\t6.7911558e-02, 1.0500095e-01, 1.4333004e-01, 1.8099448e-01,\n\t\t2.1699493e-01, 2.5087260e-01, 2.8247508e-01, 3.1181684e-01,\n\t\t3.3899861e-01, 3.6416155e-01, 3.8746151e-01, 4.0905505e-01,\n\t\t4.2909201e-01, 4.4771200e-01, 4.6504301e-01, 4.8120124e-01,\n\t\t4.9629158e-01, 5.1040840e-01, 5.2363643e-01, 5.3605172e-01,\n\t\t5.4772256e-01, 5.5871029e-01, 5.6907008e-01, 5.7885162e-01,\n\t\t5.8809974e-01, 5.9685492e-01, 6.0515382e-01, 6.1302967e-01,\n\t\t6.2051264e-01, 6.2763020e-01, 6.3440738e-01, 6.4086703e-01,\n\t\t6.4703005e-01, 6.5291558e-01, 6.5854121e-01, 6.6392307e-01,\n\t\t6.6907603e-01, 6.7401380e-01, 6.7874902e-01, 6.8329340e-01,\n\t\t6.8765777e-01, 6.9185215e-01, 6.9588588e-01, 6.9976761e-01,\n\t\t7.0350541e-01, 7.0710678e-01, 7.1057873e-01, 7.1392780e-01,\n\t\t7.1716011e-01, 7.2028138e-01, 7.2329696e-01, 7.2621189e-01,\n\t\t7.2903089e-01, 7.3175837e-01, 7.3439853e-01, 7.3695527e-01,\n\t\t7.3943229e-01, 7.4183308e-01, 7.4416092e-01, 7.4641892e-01,\n\t\t7.4861001e-01, 7.5073697e-01, 7.5280242e-01, 7.5480885e-01,\n\t\t7.5675862e-01, 7.5865396e-01, 7.6049699e-01, 7.6228974e-01,\n\t\t7.6403410e-01, 7.6573191e-01, 7.6738490e-01, 7.6899471e-01,\n\t\t7.7056292e-01, 7.7209102e-01, 7.7358045e-01, 7.7503256e-01,\n\t\t7.7644865e-01, 7.7782996e-01, 7.7917769e-01, 7.8049297e-01,\n\t\t7.8177687e-01, 7.8303045e-01, 7.8425468e-01, 7.8545054e-01,\n\t\t7.8661892e-01, 7.8776070e-01, 7.8887673e-01, 7.8996780e-01,\n\t\t7.9103468e-01, 7.9207813e-01, 7.9309885e-01, 7.9409752e-01,\n\t\t7.9507481e-01, 7.9603134e-01, 7.9696773e-01, 7.9788456e-01 };\n\n\tconst detail::Variance_<T> var;\n\tif (avg != 0.0)\n\t{\n\t\t// Must substract mean ...\n\t\tstd::vector<T> zeroMeanData( (std::distance(begin, end)) );\n\t\tomptl::transform(begin, end, zeroMeanData.begin(),\n\t\t\t\t std::bind2nd(std::plus<T>(), -avg) );\n\n\t\tconst T sig = std::sqrt(\n\t\t\tomptl::transform_accumulate(zeroMeanData.begin(),\n\t\t\t\t\t    zeroMeanData.end(), T(0), var)\n\t\t\t// ----------------------------------------------\n\t\t\t\t\t/ static_cast<T>(n-1) );\n\n\t\tconst T mean_abs =\n\t\t\tomptl::transform_accumulate(zeroMeanData.begin(),\n\t\t\t\t\t\t    zeroMeanData.end(), T(0),\n\t\t\t\t std::ptr_fun( ( (T(*)(T))std::abs) ) )\n\t\t\t// ----------------------------------------------\n\t\t\t\t\t/ static_cast<T>(n);\n\n\t\tconst T* pos = std::lower_bound(lut, lut+100, mean_abs/sig );\n\n\t\treturn init + T(std::distance(lut, pos)) * 0.02;\n\t}\n\n\t// Avg == 0.0; faster calculation\n\n\tconst T sig =std::sqrt(\n\t\t\tomptl::transform_accumulate(begin, end, T(0), var)\n\t\t// ----------------------------------------------\n\t\t\t\t/ static_cast<T>(n-1) );\n\n\tconst T mean_abs =\n\t\tomptl::transform_accumulate(begin, end, T(0),\n\t\t\t\t\t    std::ptr_fun( (T(*)(T))std::abs ) )\n\t\t// ----------------------------------------------\n\t\t\t\t/ static_cast<T>(n);\n\n\tconst T* pos = std::lower_bound(lut, lut+100, mean_abs/sig );\n\n\treturn init + T(std::distance(lut, pos)) * 0.02;\n}\n*/\ntemplate <typename Iterator, typename T>\nT generalizedGaussianShape(Iterator begin, Iterator end, const T init)\n{\n\treturn generalizedGaussianShape(begin, end,\n\t\t\t\t\taverage(begin, end, T(0)), init);\n}\n\n/*\n * Creative optimalization.\n * No idea if this is supposed to work\n */\n\nnamespace detail\n{\n\ntemplate <class T>\nstruct OptimizationUpdater;\n\ntemplate <bool value_is_arithmetic, bool result_is_arithmetic>\nstruct OptimizationUpdater_\n{\n\ttemplate <class value_type, class result_type>\n\tstatic bool update(value_type &low,  value_type &dLow,  result_type &fLow,//  value_type &bLow,\n\t\t\t   value_type &high, value_type &dHigh, result_type &fHigh,// value_type &bHigh,\n\t\t\t   const value_type &x, const value_type &dx, const result_type &fx)\n\t{\n\t\tassert(dLow * dHigh <= 0);\n\t\tif (dx*dLow > 0) // same sign ?\n\t\t{\n\t\t\tassert (x >= low);\n\t\t\tassert(dx * dHigh <= 0); // need opposing signs\n\t\t\tlow  = x;\n\t\t\tdLow = dx;\n\t\t\tfLow = fx;\n//\t\t\tbLow  = fLow - dLow  * low;\n\t\t}\n\t\telse if (dx*dHigh > 0)\n\t\t{\n\t\t\tassert (x <= high);\n\t\t\tassert(dx * dLow <= 0); // need opposing signs\n\t\t\thigh  = x;\n\t\t\tdHigh = dx;\n\t\t\tfHigh = fx;\n//\t\t\tbHigh = fHigh - dHigh * high;\n\t\t}\n\t\telse\n\t\t{\n/*\t\t\tstd::cout << std::scientific;\n\t\t\tif (!(dx == 0))\n\t\t\t{\n\t\t\t\tstd::cout << low << \" \" << x << \" \" << high << std::endl;\n\t\t\t\tstd::cout << dLow << \" \" << dx << \" \" << dHigh << std::endl;\n\t\t\t}\n*/\n\t\t\tassert(dx == 0);\n\n/*\t\t\t// just in case\n\t\t\thigh  = low  = x;\n\t\t\tdHigh = dLow = dx;\n\t\t\tfHigh = fLow = fx;\n*/\n\t\t\treturn false; // derivative zero --> optimum found\n\t\t}\n\t\tassert(dLow * dHigh <= 0); // need opposing signs\n\n\t\treturn true;\n\t}\n\n};\n\ntemplate <>\nstruct OptimizationUpdater_<false, false>\n{\n\ttemplate <class value_type, class result_type>\n\tstatic bool update(value_type &low,  value_type &dLow,  result_type &fLow,//  value_type &bLow,\n\t\t\t   value_type &high, value_type &dHigh, result_type &fHigh,// value_type &bHigh,\n\t\t\t   const value_type &x, const value_type &dx, const result_type &fx)\n\t{\n\t\ttypedef typename value_type::value_type VT;\n\t\tstd::size_t n = 0;\n\t\tfor (std::size_t i = 0; i < low.size(); ++i)\n\t\t{\n\t\t\tif (OptimizationUpdater< VT >::\n\t\t\t    update(low[i], dLow[i], fLow[i],// bLow[i],\n\t\t\t\t   high[i], dHigh[i], fHigh[i],// bHigh[i],\n\t\t\t\t   x[i], dx[i], fx[i]))\n\t\t\t\t++n;\n\t\t}\n\n\t\t// Update considered successful if at least one parameter was updated\n\t\treturn n > 0;\n\t}\n};\n\ntemplate <>\nstruct OptimizationUpdater_<true, false>\n{\n\ttemplate <class value_type, class result_type>\n\tstatic bool update(value_type &low,  value_type &dLow,  result_type &fLow,//  value_type &bLow,\n\t\t\t   value_type &high, value_type &dHigh, result_type &fHigh,// value_type &bHigh,\n\t\t\t   const value_type &x, const value_type &dx, const result_type &fx)\n\t{\n\t\ttypedef typename value_type::value_type VT;\n\t\tstd::size_t n = 0;\n\t\tfor (std::size_t i = 0; i < low.size(); ++i)\n\t\t{\n\t\t\tif (OptimizationUpdater< VT >::\n\t\t\t    update(low, dLow, fLow[i],// bLow,\n\t\t\t\t   high, dHigh, fHigh[i],// bHigh,\n\t\t\t\t   x, dx, fx[i]))\n\t\t\t\t++n;\n\t\t}\n\n\t\t// Update considered successful if at least one parameter was updated\n\t\treturn n > 0;\n\t}\n};\n\ntemplate <>\nstruct OptimizationUpdater_<false, true>\n{\n\ttemplate <class value_type, class result_type>\n\tstatic bool update(value_type &low,  value_type &dLow,  result_type &fLow,//  value_type &bLow,\n\t\t\t   value_type &high, value_type &dHigh, result_type &fHigh,// value_type &bHigh,\n\t\t\t   const value_type &x, const value_type &dx, const result_type &fx)\n\t{\n\t\ttypedef typename value_type::value_type VT;\n\t\tstd::size_t n = 0;\n\t\tfor (std::size_t i = 0; i < low.size(); ++i)\n\t\t{\n\t\t\tif (OptimizationUpdater< VT >::\n\t\t\t    update(low[i], dLow[i], fLow,// bLow[i],\n\t\t\t\t   high[i], dHigh[i], fHigh,// bHigh[i],\n\t\t\t\t   x[i], dx[i], fx))\n\t\t\t\t++n;\n\t\t}\n\n\t\t// Update considered successful if at least one parameter was updated\n\t\treturn n > 0;\n\t}\n};\n\ntemplate <class T>\nstruct OptimizationUpdater\n{\n\ttemplate <class value_type, class result_type>\n\tstatic bool update(value_type &low,  value_type &dLow,  result_type &fLow,//  value_type &bLow,\n\t\t\t   value_type &high, value_type &dHigh, result_type &fHigh,// value_type &bHigh,\n\t\t\t   const value_type &x, const value_type &dx, const result_type &fx)\n\t{\n\t\treturn OptimizationUpdater_<\tstd::tr1::is_arithmetic< value_type>::value,\n\t\t\t\t\t\tstd::tr1::is_arithmetic<result_type>::value >::\n\t\t\t    update(low, dLow, fLow,/* bLow,*/ high, dHigh, fHigh,/* bHigh,*/ x, dx, fx);\n\t}\n};\n\n} // end namespace detail\n\ntemplate <class Function, class Derivative>\ntypename Function::value_type optimize(const Function &f, const Derivative &d,\n\t\ttypename Function::value_type low,\n\t\ttypename Function::value_type high,\n\t\tconst std::size_t N)\n{\n\ttypedef typename Function  :: value_type  value_type;\n\ttypedef typename Derivative::result_type result_type;\n\n\t// Calculate derivatives in end points\n\tvalue_type dLow  = d(low);  if (dLow  == 0) return low;\n\tvalue_type dHigh = d(high); if (dHigh == 0) return high;\n\n\tvalue_type x = (low + high) / value_type(2);\n\tassert(dLow * dHigh < 0); // need opposing signs\n\tif (!(dLow * dHigh < 0)) // Invalid input, actually\n\t\treturn x;\n\n\tresult_type fLow  = f(low);\n\tresult_type fHigh = f(high);\n\n//\tvalue_type bLow  = fLow  - dLow  * low;\n//\tvalue_type bHigh = fHigh - dHigh * high;\n/*\tstd::cout << \"INIT\" << std::endl;\n\tstd::cout << \"low: \" << low << std::endl;\n\tstd::cout << \"dLow: \" << dLow << std::endl;\n\tstd::cout << \"fLow: \" << fLow << std::endl;\n//\tstd::cout << \"bLow: \" << bLow << std::endl;\n\tstd::cout << \"high: \" << high << std::endl;\n\tstd::cout << \"dHigh: \" << dHigh << std::endl;\n\tstd::cout << \"fHigh: \" << fHigh << std::endl;\n//\tstd::cout << \"bHigh: \" << bHigh << std::endl;\n \tstd::cout << std::endl;\n*/\n\tfor (std::size_t i = 0; i < N; ++i)\n\t{\n\t\tassert(dLow * dHigh <= 0); // need opposing signs\n\n\t\t// find two lines y = d*x + b\n\n\t\t// find intersection point of derivatives as\n\t\t// estimation of center, find derivative at center\n\t\t//x = (bHigh - bLow) / (dLow - dHigh);\n\t\tx = (low + high) / value_type(2);\n\t\tassert(low <= x);\n\t\tassert(x <= high);\n\t\tconst result_type fx = f(x);\n\t\tconst  value_type dx = d(x);\n/*\t\tstd::cout << \"x: \" << x << std::endl;\n\t\tstd::cout << \"fx: \" << fx << std::endl;\n\t\tstd::cout << \"dx: \" << dx << std::endl;\n*/\n\t\tif (!detail::OptimizationUpdater< value_type >::\n\t\t    update(low, dLow, fLow,/* bLow,*/ high, dHigh, fHigh,/* bHigh,*/ x, dx, fx))\n\t\t{\n\t\t\t// No parameters updated, derivative zero --> optimum found\n\t\t\tbreak;\n\t\t}\n/*\t\tstd::cout << \"low: \" << low << std::endl;\n\t\tstd::cout << \"dLow: \" << dLow << std::endl;\n\t\tstd::cout << \"fLow: \" << fLow << std::endl;\n//\t\tstd::cout << \"bLow: \" << bLow << std::endl;\n\t\tstd::cout << \"high: \" << high << std::endl;\n\t\tstd::cout << \"dHigh: \" << dHigh << std::endl;\n\t\tstd::cout << \"fHigh: \" << fHigh << std::endl;\n//\t\tstd::cout << \"bHigh: \" << bHigh << std::endl;\n\t\tstd::cout << std::endl;\n*/\n\t}\n\treturn x;\n}\n\ntemplate <class Function>\ntypename Function::value_type optimize(const Function &f,\n\t\t\ttypename Function::value_type low,\n\t\t\ttypename Function::value_type high,\n\t\t\tconst std::size_t N)\n{\n\treturn optimize(f, Derivative<Function>(f), low, high, N);\n}\n\n\n/*\n * Newton-Raphson\n */\n\ntemplate <class Function, class Derivative>\nbool doNewtonRaphson(const Function &f, const Derivative &d,\n\t\t\ttypename Function::value_type &x, const std::size_t N)\n{\n\ttypedef typename Function::value_type value_type;\n\ttypedef typename ValueType<value_type>::value_type T;\n\tCyclicBuffer<T> values((16u));\n\n\tvalue_type dx = value_type(T(1));\n\tT m = T(0);\n\tvalue_type fx = f(x);\n\n\tvalue_type oldx [2] = {x, x};\n\tvalue_type avgx = x;\n\n\tvalue_type best = x;\n\tvalue_type lowest = fx;\n\n\t// Start loop, terminate on convergence or hopelessness\n\tfor (std::size_t i = 0u; i < N; ++i)\n\t{\n// std::cout << i << \" X: \" << x << \" f(x): \" << fx << \" df(x): \" << d(x)\n// \t<< \" dx: \" << dx << \" avg: \" << values.avg() << std::endl;\n\n\t\tif (modulus(fx) == T(0))\n\t\t\treturn true;\n\n\t\t// The method 2nd-order, i.e. error should be quadratic. Hence,\n\t\t// the updates to x should reduce at 2nd order as well, and thus\n\t\t// allways be smaller than previous updates, at least on\n\t\t// average.\n\t\t// Convergence is reached when the updates no longer become\n\t\t// smaller and smaller. To have a meaningful average value,\n\t\t// run at least \"values.capacity()\" times.\n\t\tif ( (i > values.capacity()) && (values.avg() <= m) )\n\t\t\tbreak;\n\n\t\tvalues.add(m);\t\t\t// Add metric _after_ comparison\n\n\t\t// Compute standard Newton-Raphson, but avoid divide-by-zero.\n\t\tvalue_type next = x - dx; \t// if df==0, repeat previous\n\t\tconst value_type df = d(x);\t// Compute derivative\n\t\tif (modulus(df) > T(0))\t\t// Not reliable for Vectors...\n\t\t\tnext = x - fx / df;\n\n\t\t// Select best option of standard Newton-Raphson and\n\t\t// bisection of previous values.\n\t\tvalue_type fnext = f(next);\n\t\tconst value_type favgx = f(avgx);\n\t\tif (modulus(favgx) < modulus(fnext))\n\t\t{\n\t\t\tnext = avgx;\n\t\t\tfnext= favgx;\n\t\t}\n\n\t\tdx   = next - x;\t\t// Displacement\n\t\tavgx = (oldx[0] + oldx[1]) / T(2); // bisection of previous\n\t\toldx[i%2u] = x;\n\t\tx    = next;\n\t\tfx   = fnext;\n\t\tm    = modulus(dx);\t\t// Quality metric = abs(update)\n\n\t\t// Select best result.\n\t\tif (modulus(fx) < modulus(lowest))\n\t\t{\n\t\t\tbest   = x;\n\t\t\tlowest = fx;\n\t\t}\n\t}\n\tx = best;\n\n\treturn (values.avg() <= m); // Converged or ran out of iterations ?\n}\n\ntemplate <class Function>\nbool doNewtonRaphson(const Function &f, typename Function::value_type &x,\n\t\t\tconst std::size_t N)\n{\n\treturn doNewtonRaphson(f, Derivative<Function>(f), x, N);\n}\n\ntemplate <class Function, class Derivative>\nbool doNewtonRaphson(const Function &f, const Derivative &d,\n\t\t\ttypename Function::value_type &x,\n\t\t\tconst typename Function::value_type low,\n\t\t\tconst typename Function::value_type high,\n\t\t\tconst std::size_t N)\n{\n\ttypedef typename Function::value_type value_type;\n\ttypedef typename ValueType<value_type>::value_type T;\n\n\t// Make sure x1 < x2\n\tvalue_type xl = std::min(low, high);\n\tvalue_type xh = std::max(low, high);\n\n\tif ( (xl > x) || (x > xh) )\n\t\tx = (xl + xh) / T(2);\n\n\tCyclicBuffer<T> values((16u));\n\n\tT m = T(0);\n\tvalue_type dx\t= T(0);\n\tvalue_type fx\t= f(x);\n\tvalue_type fl\t= f(xl);\n\tvalue_type fh\t= f(xh);\n\n\tvalue_type oldx [2] = {x, x};\n\tvalue_type avgx = x;\n\n\tvalue_type best = x;\n\tvalue_type lowest = fx;\n\n\t// Start loop, terminate on convergence or hopelessness\n\tfor (std::size_t i = 0u; i < N; ++i)\n\t{\n// std::cout << i << \" X: \" << x << \" f(x): \" << fx << \" df(x): \" << d(x)\n// \t<< \" dx: \" << dx << \" avg: \" << values.avg()\n// \t<< \" [\" << xl << \", \" << xh << \"]\"<< std::endl;\n\n\t\tif (modulus(fx) == T(0)) // Jackpot ?\n\t\t\treturn true;\n\n\t\t// The method 2nd-order, i.e. error should be quadratic. Hence,\n\t\t// the updates to x should reduce at 2nd order as well, and thus\n\t\t// allways be smaller than previous updates, at least on\n\t\t// average.\n\t\t// Convergence is reached when the updates no longer become\n\t\t// smaller and smaller. To have a meaningful average value,\n\t\t// run at least \"values.capacity()\" times.\n\t\tif ( (i > values.capacity()) && (values.avg() <= m) )\n\t\t\tbreak;\n\n\t\tvalues.add(m);\t\t// Add metric _after_ comparison\n\n\t\tT next = x + dx;\n\t\tconst value_type df = d(x);\n\n\t\tif (modulus(df) > T(0)) // Not reliable for Vectors...\n\t\t\tnext = x - fx / df;\n\t\tnext = clamp(next, xl, xh);\n\n\t\t// Select an alternative option as best of\n\t\t// bi-section of range and bisection of previous values.\n\t\tvalue_type fnext = f(next);\n\t\tvalue_type alternative  = (xh + xl) / T(2); // bisect of range\n\t\tvalue_type falternative = f(alternative);\n\n// std::cout << \"\\t next: \" << next << \" middle: \" << alternative << \" avgx \" <<\n// \tavgx << \" fnext \"<< fnext << \" falternative \" << falternative <<\n// \t\" favg \" << favgx << std::endl;\n\n\t\tconst value_type favgx = f(avgx); // bisect of previous values\n\t\tif (modulus(favgx) < modulus(falternative))\n\t\t{\n\t\t\talternative = avgx;\n\t\t\tfalternative= favgx;\n\t\t}\n\n\t\t// Select best option of standard Newton-Raphson and alternative\n\t\tif ( !((xl <= next) && (next <= xh)) ||\n\t\t      (modulus(falternative) < modulus(fnext)) )\n\t\t{\n\t\t\tnext = alternative;\n\t\t\tfnext= falternative;\n\t\t}\n\n\t\tdx\t= next - x;\t\t// Displacement\n\t\tm\t= modulus(dx);\t\t// Quality metric = abs(update)\n\t\tavgx = (oldx[0] + oldx[1]) / T(2); // bisection of previous\n\t\toldx[i%2u] = x;\n\t\tx\t= next;\t\t\t// Update position\n\t\tfx\t= fnext;\t\t// Update function value\n\n\t\t// Try to reduce the range such that the function has one\n\t\t// end-point below zero and one above zero.\n\t\tif (fl * fx < T(0))\n\t\t{\n\t\t\txh = x;\n\t\t\tfh = fx;\n\t\t}\n\t\tif (fh * fx < T(0))\n\t\t{\n\t\t\txl = x;\n\t\t\tfl = fx;\n\t\t}\n\n\t\t// Select the best option\n\t\tif (modulus(fx) < modulus(lowest))\n\t\t{\n\t\t\tbest   = x;\n\t\t\tlowest = fx;\n\t\t}\n\t}\n\tx = best;\n\n\treturn (values.avg() <= m);  // Converged or ran out of iterations ?\n}\n\ntemplate <class Function>\nbool doNewtonRaphson(const Function &f, typename Function::value_type &x,\n\t\t\tconst typename Function::value_type low,\n\t\t\tconst typename Function::value_type high,\n\t\t\tconst std::size_t N)\n{\n\treturn doNewtonRaphson(f, Derivative<Function>(f),\n\t\t\t\tx, low, high, N);\n}\n\n\ntemplate <class Function>\nvoid doRungeKutta(const Function &f,\n\t\tconst typename Function::value_type t0,\n\t\tconst typename Function::value_type tN,\n\t\tconst std::size_t N,\n\t\tconst typename Function::value_type y0,\n\t\tstd::vector<typename Function::value_type> &y)\n{\n\tassert(tN > t0); // Bogus user input ?\n\n\ttypedef typename Function::value_type T;\n\tassert(std::tr1::is_floating_point<T>::value); // Float types only.\n\n\ty.clear();\n\ty.reserve(N+1u); // Ensure 1 memory alloc only\n\n\t// \"physical\" spacing between two nodes\n\tconst T h = (tN - t0) / static_cast<T>(N);\n\n\tassert(T(0.5) * h > T(0.)); // Numerically still stable ?\n\n\ty.push_back(y0);          // initial condition\n        for (std::size_t i = 0u; i < N; ++i)\n        {\n\t\tassert(i == y.size() - 1u);\n\n\t\tconst T t_n\t= t0 + static_cast<T>(i+1u) * h;\n\t\tconst T halfH\t= T(0.5) * h;\n\n\t\tconst T k1 = f(t_n,           y[i]);\n\t\tconst T k2 = f(t_n + halfH,   y[i] + halfH * k1);\n\t\tconst T k3 = f(t_n + halfH,   y[i] + halfH * k2);\n\t\tconst T k4 = f(t_n + h,       y[i] + h * k3);\n\n\t\ty.push_back(y[i] + h / T(6) * (k1 + T(2)*k2 + T(2)*k3 + k4));\n        }\n\tassert(y.size() == N+1u);\n}\n\n/*\ntemplate <template <typename Tm, std::size_t D, typename Aux> class Array_t,\n\t  typename T, typename A>\nvoid identity_matrix(Array_t<T, 2u, A> &m, const std::size_t N)\n{\n\ttypedef array_traits<Array_t, T, 2u, A>\tAT;\n\n\tconst std::size_t sz [] = {N, N};\n\tAT::resize(m, sz);\n\tomptl::fill(m.begin(), m.end(), T(0));\n#ifdef _OPENMP\n\t#pragma omp parallel for\n#endif\n\tfor (int i = 0; i < int(N); ++i)\n\t\tm[i][i] = T(1);\n}\n*/\n\n/*\n * Adapated from:\n * http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?LU_Matrix_Inversion\n *\n * Matrix inversion routine.\n * Uses lu_factorize and lu_substitute in uBLAS to invert a matrix\n */\n\ntemplate<class T, class F, class A>\nbool invert(boost::numeric::ublas::matrix<T, F, A>& m)\n{\n \tnamespace ublas = boost::numeric::ublas;\n\n \t// create a working copy of the input\n \tublas::matrix<T> a(m);\n\n \t// create a permutation matrix for the LU-factorization\n \tublas::permutation_matrix<std::size_t> pm(a.size1());\n\n \t// perform LU-factorization\n \tif (ublas::lu_factorize(a, pm)) // returns zero on success\n\t\treturn false;\n\n\t// create identity_matrix matrix of \"inverse\"\n \tm.assign(ublas::identity_matrix<T>(a.size1()));\n\n \t// backsubstitute to get the inverse\n \tublas::lu_substitute(a, pm, m);\n\n \treturn true;\n}\n/*\ntemplate <template <typename Tm, std::size_t D, typename Aux> class Array_t,\n\t  typename T, typename A>\nbool invert(Array_t<T, 2u, A> &m)\n{\n\ttypedef Array_t<T, 2u, A> Matrix_t;\n\ttypedef array_traits<Array_t, T, 2u, A>\tAT;\n\n\t// Must be NxN matrix\n\tif (AT::shape(m)[Y] != AT::shape(m)[X])\n\t\treturn false;\n\n\tconst std::size_t dim = AT::shape(m)[X];\n\tif (dim == 0)\n\t\treturn true;\n\n\t// Load identity_matrix\n\tMatrix_t inv;\n\tcvmlcpp::identity_matrix(inv, dim);\n\tassert(AT::shape(inv)[X] == dim);\n\tassert(AT::shape(inv)[Y] == dim);\n\n\tfor (std::size_t x = 0; x < dim; ++x)\n\t{\n\t\t// Scale\n\t\tif (m[x][x] == T(0))\n\t\t\treturn false;\n\n\t\tconst T scale = T(1) / m[x][x];\n\t\tm[x][x] = T(1);\n\n#ifdef _OPENMP\n\t\t#pragma omp parallel for\n#endif\n\t\tfor (int y = x+1; y < int(dim); ++y)\n\t\t\tm[x][y]   *= scale;\n#ifdef _OPENMP\n\t\t#pragma omp parallel for\n#endif\n\t\tfor (int y = 0; y < int(dim); ++y)\n\t\t\tinv[x][y] *= scale;\n\n\t\t// Sweep\n#ifdef _OPENMP\n\t\t#pragma omp parallel for\n#endif\n\t\tfor (int xx = x+1; xx < int(dim); ++xx)\n\t\t{\n\t\t\tconst T factor = m[xx][x];\n\t\t\tif (factor == T(0))\n\t\t\t\tcontinue;\n\n\t\t\tm[xx][x] = T(0);\n\t\t\tfor (std::size_t yy = x+1; yy < dim; ++yy)\n\t\t\t{\n\t\t\t\tassert(x >= 0);\n\t\t\t\tassert(xx>= 0);\n\t\t\t\tassert(yy >= 0);\n\t\t\t\tassert(x < dim);\n\t\t\t\tassert(std::size_t(xx)< dim);\n\t\t\t\tassert(yy < dim);\n\t\t\t\t  m[xx][yy] -= factor *   m[x][yy];\n\t\t\t}\n\t\t\tfor (std::size_t yy = 0;   yy < dim; ++yy)\n\t\t\t{\n\t\t\t\tassert(x >= 0);\n\t\t\t\tassert(xx>= 0);\n\t\t\t\tassert(yy >= 0);\n\t\t\t\tassert(x < dim);\n\t\t\t\tassert(std::size_t(xx)< dim);\n\t\t\t\tassert(yy < dim);\n\t\t\t\tinv[xx][yy] -= factor * inv[x][yy];\n\t\t\t}\n\t\t}\n\t}\n\n\tassert(dim > 0);\n\tfor (long int x = dim - 1; x >= 0; --x)\n\t{\n\t\t// Sweep\n#ifdef _OPENMP\n\t\t#pragma omp parallel for\n#endif\n\t\tfor (int xx = x-1; xx >= 0; --xx)\n\t\t{\n\t\t\tconst T factor = m[xx][x];\n\t\t\tif (factor == T(0))\n\t\t\t\tcontinue;\n\n\t\t\tm[xx][x] = T(0);\n\t\t\tfor (std::size_t y = x+1; y < dim; ++y)\n\t\t\t{\n\t\t\t\tassert(x >= 0);\n\t\t\t\tassert(xx>= 0);\n\t\t\t\tassert(y >= 0);\n\t\t\t\tassert(x < D);\n\t\t\t\tassert(xx< D);\n\t\t\t\tassert(y < D);\n\t\t\t\tm[xx][y] -= factor *   m[x][y];\n\t\t\t}\n\t\t\tfor (std::size_t y = 0;   y < dim; ++y)\n\t\t\t{\n\t\t\t\tassert(x >= 0);\n\t\t\t\tassert(xx>= 0);\n\t\t\t\tassert(y >= 0);\n\t\t\t\tassert(x < D);\n\t\t\t\tassert(xx< D);\n\t\t\t\tassert(y < D);\n\t\t\t\tinv[xx][y] -= factor * inv[x][y];\n\t\t\t}\n\t\t}\n\t}\n\n\tm.swap(inv);\n\n\treturn true;\n}\n*/\ntemplate <template <typename Tm, std::size_t D, typename Aux> class Array_t,\n\t  typename T, typename A>\nvoid transpose(Array_t<T, 2u, A> &m)\n{\n\ttypedef array_traits<Array_t, T, 2u, A>\tAT;\n\tconst std::size_t ext [] = {AT::shape(m)[Y], AT::shape(m)[X]};\n\n\tif ( (AT::size(m) == 0) || (ext[X] == 0) || (ext[Y] == 0) )\n\t\treturn;\n\n\tstd::vector<bool> todo(AT::size(m), true);\n\ttodo[0] = false;\n\n\ttypename std::vector<bool>::const_iterator next;\n\tT temp = *AT::begin(m);\n\twhile ( (next=std::find(todo.begin(), todo.end(), true)) != todo.end())\n\t{\n\t\tusing std::swap;\n\t\tstd::size_t src  = next - todo.begin();\n\n\t\tstd::size_t x1 = src / AT::shape(m)[Y];\n\t\tstd::size_t y1 = src % AT::shape(m)[Y];\n\t\tswap(x1, y1);\n\t\tstd::size_t dest = x1 * ext[Y] + y1;\n\t\ttemp = *(AT::begin(m) + src);\n\t\tif (src == dest)\n\t\t\ttodo[dest] = false;\n\t\telse\n\t\t{\n\t\t\twhile (  todo[dest] )\n\t\t\t{\n\t\t\t\ttypename AT::iterator destIt = AT::begin(m);\n\t\t\t\tstd::advance(destIt, dest);\n\n\t\t\t\tswap(temp, *destIt);\n\t\t\t\ttodo[dest] = false;\n\t\t\t\tsrc = dest;\n\t\t\t\tstd::size_t x = src / AT::shape(m)[Y];\n\t\t\t\tstd::size_t y = src % AT::shape(m)[Y];\n\t\t\t\tswap(x, y);\n\t\t\t\tdest = x * ext[Y] + y;\n\t\t\t}\n\t\t}\n\t}\n\n\tAT::resize(m, ext);\n\n// \tfor (std::size_t i = 0u; i < ext[1]; ++i)\n// \tfor (std::size_t j = 0u; j < ext[0]; ++j)\n// \t\tr[i][j] = static_cast<T>(m[j][i]);\n// \tr.swap(m);\n}\n\nnamespace detail\n{\n\ntemplate <template <typename Tm, std::size_t Dm, typename A> class Array_t,\n\t  typename Ta, typename Aux, class XVector_t, class YVector_t>\nbool leastSquaresFit_ublas(const Array_t<Ta, 2, Aux> &A, const YVector_t &y,\n\t\t     XVector_t &x)\n{\n\t// Copy to ublas matrix: A\n\tboost::numeric::ublas::matrix<Ta> A2 (A.extents()[X], A.extents()[Y]);\n\tfor (std::size_t i = 0; i < A2.size1 (); ++i)\n\tfor (std::size_t j = 0; j < A2.size2 (); ++j)\n\t\tA2(i, j) = A[i][j];\n\n\t// transposeA A^T\n\tconst boost::numeric::ublas::matrix<Ta> At =\n\t\tboost::numeric::ublas::trans(A2);\n\n\t// Multiply, before invert: A^T A\n\tboost::numeric::ublas::matrix<Ta> AtAinv = //At * A2;\n\t\tboost::numeric::ublas::prod(At, A2);\n\n/*\n\tstd::cout << \"AtA\" << std::endl;\n\tfor (std::size_t i = 0u; i < AtAinv.size1(); ++i)\n\t{\n\t\tfor (std::size_t j = 0u; j < AtAinv.size2(); ++j)\n\t    \t\tstd::cout << AtAinv(i,j) << \" \";\n\t\tstd::cout << std::endl;\n\t}\n\tstd::cout << std::endl;\n*/\n\n\t// Invert: (A^T A)^{-1}\n\tif (!invert(AtAinv))\n\t\treturn false;\n\n/*\n\tstd::cout << \"AtAinv\" << std::endl;\n\tfor (std::size_t i = 0u; i < AtAinv.size1(); ++i)\n\t{\n\t\tfor (std::size_t j = 0u; j < AtAinv.size2(); ++j)\n\t    \t\tstd::cout << AtAinv(i,j) << \" \";\n\t\tstd::cout << std::endl;\n\t}\n\tstd::cout << std::endl;\n*/\n\n\t// Copy observation vector\n\tboost::numeric::ublas::vector<Ta> y2 (y.size());\n\tfor (std::size_t i = 0; i < y2.size (); ++ i)\n\t\ty2(i) = y[i];\n\n\t// x = (A^T A)^{-1} * At * y2;\n\tconst boost::numeric::ublas::matrix<Ta> AtAinvAt  =\n\t\tboost::numeric::ublas::prod(AtAinv, At);\n\tconst boost::numeric::ublas::vector<Ta> x2 =\n\t\tboost::numeric::ublas::prod(AtAinvAt, y2);\n\n\tassert(x.size() == x2.size());\n\tfor (std::size_t i = 0; i < x.size (); ++ i)\n\t\tx[i] = x2(i);\n}\n\ntemplate <template <typename Tm, std::size_t Dm, typename A> class Array_t,\n\t  typename Ta, typename Aux, class XVector_t, class YVector_t>\nbool leastSquaresFit_cvmlcpp(const Array_t<Ta, 2, Aux> &A, const YVector_t &y,\n\t\t     XVector_t &x)\n{\n\ttypedef array_traits<Array_t, Ta, 2u, Aux> AT;\n/*\n\tstd::cout << \"A\" << std::endl;\n\tfor (std::size_t i = 0u; i < A.extents()[X]; ++i)\n\t{\n\t\tfor (std::size_t j = 0u; j < A.extents()[Y]; ++j)\n\t    \t\tstd::cout << A[i][j] << \" \";\n\t\tstd::cout << std::endl;\n\t}\n\tstd::cout << std::endl;\n*/\n\tArray_t<Ta, 2, Aux> At = AT::copy_of(A);\n\ttranspose(At);\n\n\tArray_t<Ta, 2, Aux> AtAinv; // = At * A;\n\tmat_mat_mult(At, A, AtAinv);\n/*\n\tstd::cout << \"AtA\" << std::endl;\n\tfor (std::size_t i = 0u; i < AtAinv.extents()[X]; ++i)\n\t{\n\t\tfor (std::size_t j = 0u; j < AtAinv.extents()[Y]; ++j)\n\t    \t\tstd::cout << AtAinv[i][j] << \" \";\n\t\tstd::cout << std::endl;\n\t}\n\tstd::cout << std::endl;\n*/\n\tif (!invert(AtAinv))\n\t\treturn false;\n/*\n\tstd::cout << \"AtAinv\" << std::endl;\n\tfor (std::size_t i = 0u; i < AtAinv.extents()[X]; ++i)\n\t{\n\t\tfor (std::size_t j = 0u; j < AtAinv.extents()[Y]; ++j)\n\t    \t\tstd::cout << AtAinv[i][j] << \" \";\n\t\tstd::cout << std::endl;\n\t}\n\tstd::cout << std::endl;\n*/\n\n\tArray_t<Ta, 2, Aux> AtAinvAt;\n\tmat_mat_mult(AtAinv, At, AtAinvAt);\n/*\tstd::cout << \"B\" << std::endl;\n\tfor (std::size_t i = 0u; i < B.extents()[X]; ++i)\n\t{\n\t\tfor (std::size_t j = 0u; j < B.extents()[Y]; ++j)\n\t    \t\tstd::cout << B[i][j] << \" \";\n\t\tstd::cout << std::endl;\n\t}\n\tstd::cout << std::endl;\n\n\tstd::cout << \"Y\" << std::endl;\n\tfor (std::size_t i = 0u; i < y.size(); ++i)\n\t\tstd::cout << y[i] << \" \";\n\tstd::cout << std::endl;\n*/\n\tmat_vec_mult(AtAinvAt, y, x);\n\n\treturn true;\n}\n\n} // end namespace detail\n\ntemplate <template <typename Tm, std::size_t Dm, typename A> class Array_t,\n\t  typename Ta, typename Aux, class XVector_t, class YVector_t>\nbool leastSquaresFit(const Array_t<Ta, 2, Aux> &A, const YVector_t &y,\n\t\t     XVector_t &x)\n{\n\t//return detail::leastSquaresFit_ublas(A, y, x);\n\treturn detail::leastSquaresFit_cvmlcpp(A, y, x);\n}\n\n/*\n * The bits about the hungarian matching algorithm WAS part of\n * \"the Stanford GraphBase (c) Stanford University 1993\"\n * In accordance to the Stanford GraphBase license, this notice is here\n * to inform you that it is NO LONGER part of that library, and this file\n * has a different name than the one the original code was in, because the\n * code has been modified.\n */\n\nnamespace detail\n{\n\n// Subtract column minima in order to start with lots of zeroes\ntemplate <template <typename Tm, std::size_t D, typename Aux> class Matrix_type,\n\ttypename T, typename A>\nvoid to_zero(Matrix_type<T, 2, A> &aa)\n{\n\ttypedef array_traits<Matrix_type, T, 2, A> AT;\n\tconst std::size_t m = AT::shape(aa)[0];\n\tconst std::size_t n = AT::shape(aa)[1];\n\n\t#ifdef _OPENMP\n\t#pragma omp parallel for\n\t#endif\n\tfor (int l = 0; l < int(n); ++l)\n\t{\n\t\tT s = aa[0][l];\n\t\tfor (std::size_t k = 1; k < m; ++k)\n\t\t\ts = std::min(aa[k][l], s);\n\t\tif (s != 0)\n\t\t\tfor (std::size_t k = 0; k < m; ++k)\n\t\t\t\taa[k][l] -= s;\n\t}\n}\n\n\ntemplate <template <typename Tm, std::size_t D, typename Aux> class Matrix_type,\n\ttypename T, typename A>\nvoid hungarian( const Matrix_type<T, 2, A> &aa,\n\t\tstd::vector<std::ptrdiff_t> &col_mate,\n\t\tstd::vector<std::ptrdiff_t> &row_mate)\n{\n//\tprintf(\"1\\n\");\n\ttypedef array_traits<Matrix_type, T, 2, A> AT;\n\n\t/* number of rows and columns desired */\n\tconst std::size_t m = AT::shape(aa)[0];\n\tconst std::size_t n = AT::shape(aa)[1];\n\n\tcol_mate.resize(m);\n\trow_mate.resize(n);\n\tstd::vector<std::ptrdiff_t> parent_row(n);\n\tstd::vector<std::ptrdiff_t> unchosen_row(m);\n\tstd::vector<T> row_dec(m);\n\tstd::vector<T> col_inc(n);\n\tstd::vector<T> slack(n);\n\tstd::vector<std::ptrdiff_t> slack_row(n);\n\n\tstd::fill(row_mate  .begin(), row_mate  .end(), -1);\n\tstd::fill(col_inc   .begin(), col_inc   .end(),  0);\n\tstd::fill(parent_row.begin(), parent_row.end(), -1);\n\tstd::fill(slack     .begin(), slack     .end(), std::numeric_limits<T>::max());\n//\tprintf(\"2\\n\");\n\n\t/*\n\t * The algorithm operates in stages, where each stage terminates\n\t * when we are able to increase the number of matched elements.\n\t *\n\t * The first stage is different from the others; it simply goes through\n\t * the matrix and looks for zeroes, matching as many rows and columns\n\t * as it can. This stage also initializes table entries that will be\n\t * useful in later stages.\n\t */\n\n\t// total number of nodes in the forest\n\tstd::size_t t = 0; /* the forest starts out empty */\n\n\tfor (std::size_t k = 0; k < m; ++k)\n\t{\n\t\t// the minimum entry of row $k$\n\t\tconst T s = *std::min_element(aa[k].begin(), aa[k].end());\n\n\t\trow_dec[k] = s;\n\t\tfor (std::size_t l = 0; l < n; ++l)\n\t\t\tif ( (s==aa[k][l]) && (row_mate[l]<0))\n\t\t\t{\n\t\t\t\tcol_mate[k]=l;\n\t\t\t\trow_mate[l]=k;\n\t\t\t\tgoto row_done;\n\t\t\t}\n\t\tcol_mate[k]=-1; // k unmatched\n\t\tunchosen_row[t++]=k;\n//\t\tprintf(\"  node %ld: unmatched row %ld\\n\",t,k);\n\t\trow_done:;\n\t\tassert(t <= unchosen_row.size());\n\t}\n//\tprintf(\"3\\n\");\n\n\tif (t==0)\n\t\treturn;\n\tstd::size_t unmatched = t;\n\twhile(unmatched > 0)\n\t{\n\t\tstd::ptrdiff_t k; /* the current row of interest */\n\t\tstd::ptrdiff_t l; /* the current column of interest */\n\t\t/* the current matrix element of interest */\n\n\t\tT s;\n//\t\tprintf(\"4\\n\");\n\n//\t\tstd::size_t q = 0;\n\t\twhile (1)\n\t\t{\n\t\t\tfor (std::size_t q = 0; q < t; ++q)\n\t\t\t{\n//\t\t\t\tprintf(\"5\\n\");\n\t\t\t\t// Explore node |q| of the forest;\n\t\t\t\t// if the matching can be increased, |goto breakthru|\n\t\t\t\tassert(q < m);\n\t\t\t\tk = unchosen_row[q];\n//\t\t\t\tconst T s = row_dec[k];\n\t\t\t\ts = row_dec[k];\n\t\t\t\tfor (l = 0; l < std::ptrdiff_t(n); ++l)\n\t\t\t\t{\n//\t\t\t\t\tprintf(\"6\\n\");\n\t\t\t\t\tif (slack[l])\n\t\t\t\t\t{\n\t\t\t\t\t\tconst T del = aa[k][l] - s + col_inc[l];\n\t\t\t\t\t\tif (del < slack[l])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (del==0)\n\t\t\t\t\t\t\t{ /* we found a new zero */\n\t\t\t\t\t\t\t\tif (row_mate[l]<0)\n\t\t\t\t\t\t\t\t\tgoto breakthru;\n\t\t\t\t\t\t\t\tslack[l] = 0; /* this column will now be chosen */\n\t\t\t\t\t\t\t\tparent_row[l] = k;\n//\t\t\t\t\t\t\t\tprintf(\"  node %ld: row %ld==col %ld--row %ld\\n\", t,row_mate[l],l,k);\n\t\t\t\t\t\t\t\tassert(t < m);\n\t\t\t\t\t\t\t\tunchosen_row[t++] = row_mate[l];\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\tslack[l] = del;\n\t\t\t\t\t\t\t\tslack_row[l] = k;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n//\t\t\tfprintf(stderr, \"7\\n\");\n\n\t\t\t// Introduce a new zero into the matrix by modifying |row_dec| and\n\t\t\t// |col_inc|; if the matching can be increased, |goto breakthru|\n\t\t\t/*T*/ s = std::numeric_limits<T>::max();\n\t\t\tfor (std::size_t i = 0; i < n; ++i)\n\t\t\t\tif (slack[i] != 0)\n\t\t\t\t\ts = std::min(slack[i], s);\n\t\t\tassert(t <= unchosen_row.size());\n\t\t\tfor (std::size_t q = 0; q < t; ++q) {\n//\t\t\t\tfprintf(stderr, \"unchosen_row[%ld] = %ld\\n\", q, unchosen_row[q]);\n\t\t\t\tassert(unchosen_row[q] >= 0);\n\t\t\t\tassert(unchosen_row[q] < std::ptrdiff_t(row_dec.size()));\n\t\t\t\trow_dec[unchosen_row[q]] += s;\n\t\t\t}\n\t\t\tfor (/*std::size_t*/ l = 0; l < std::ptrdiff_t(n); ++l)\n\t\t\t{\n//\t\t\t\tfprintf(stderr, \"8\\n\");\n\t\t\t\tif (slack[l])\n\t\t\t\t{\n\t\t\t\t\t// column $l$ is not chosen\n\t\t\t\t\tslack[l] -= s;\n\t\t\t\t\tif (slack[l]==0)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Look at a new zero, and |goto breakthru| with\n\t\t\t\t\t\t// |col_inc| up to date if there's a breakthrough\n\t\t\t\t\t\tk = slack_row[l];\n//\t\t\t\t\t\tfprintf(stderr, \" Decreasing uncovered elements by %ld produces zero at [%ld,%ld]\\n\", s,k,l);\n\t\t\t\t\t\tif (row_mate[l]<0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor (std::size_t j=l+1; j<n; ++j)\n\t\t\t\t\t\t\t\tif (slack[j] == 0)\n\t\t\t\t\t\t\t\t\tcol_inc[j] += s;\n\t\t\t\t\t\t\tgoto breakthru;\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\t// not a breakthrough, but the forest continues to grow\n\t\t\t\t\t\t\tparent_row[l]=k;\n//\t\t\t\t\t\t\tfprintf(stderr, \"  node %ld: row %ld==col %ld--row %ld\\n\", t,row_mate[l],l,k);\n\t\t\t\t\t\t\tunchosen_row[t++]=row_mate[l];\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\tcol_inc[l]+=s;\n\t\t\t}\n\t\t}\n\n\t\tbreakthru:\n//\t\tfprintf(stderr, \"9\\n\");\n\t\t// Update the matching by pairing row $k$ with column $l$\n\t\twhile (1)\n\t\t{\n//\t\t\tfprintf(stderr, \"10\\n\");\n\t\t\tconst std::ptrdiff_t j = col_mate[k];\n\t\t\tcol_mate[k]=l;\n\t\t\trow_mate[l]=k;\n//\t\t\tfprintf(stderr, \" rematching col %ld==row %ld\\n\",l,k);\n\t\t\tif (j < 0)\n\t\t\t\tbreak;\n\t\t\tk = parent_row[j];\n\t\t\tl = j;\n\t\t}\n\n//\t\tfprintf(stderr, \"11\\n\");\n\t\tassert(unmatched > 0);\n\t\tif(--unmatched == 0)\n\t\t\tbreak;\n\t\tassert(unmatched > 0);\n\n//\t\tfprintf(stderr, \"12\\n\");\n\n\t\t/*\n\t\t *  get_ready_for_another_stage\n\t\t */\n\t\tstd::fill(parent_row.begin(), parent_row.end(), -1);\n\t\tstd::fill(slack     .begin(), slack     .end(), std::numeric_limits<T>::max());\n\t\tt = 0;\n\t\tfor (std::size_t i = 0; i < m; ++i)\n\t\t\tif (col_mate[i] < 0)\n\t\t\t{\n\t\t\t\tunchosen_row[t++] = i;\n//\t\t\t\tfprintf(stderr, \"  node %ld: unmatched row %ld\\n\",t,k);\n\t\t\t}\n\t}\n//\tfprintf(stderr, \"done!\\n\");\n}\n\n} // end namespace detail\n\n\n/*\n * Interfacing.\n * A few nitty-gritty details still need to be handled: Our algorithm\n * is not symmetric between rows and columns, and it works only for $m\\le n$;\n * so we will transpose the matrix when $m>n$. Furthermore, our\n * algorithm minimizes, but we actually want it to maximize (except\n * when |compl| is nonzero).\n *\n * Hence, we want to make the following transformations to the data\n * before processing it with the algorithm developed above.\n */\n/*\ntemplate <template <typename Tm, std::size_t D, typename Aux> class Matrix_type,\n\ttypename T, typename A>\nvoid find_matching(Matrix_type<T, 2, A> &costs,\n\t\t   std::vector<std::pair<std::size_t, std::size_t> > &matches,\n\t\t   const bool minimize_costs, const bool heuristic)\n{\n\ttypedef array_traits<Matrix_type, T, 2, A> AT;\n\n\tmatches.clear();\n\tstd::vector<std::ptrdiff_t> a_mate, b_mate;\n\n\tconst std::size_t m = AT::shape(costs)[0];\n\tconst std::size_t n = AT::shape(costs)[1];\n\n\tconst bool transposed = m > n;\n\tif (transposed)\n\t\ttranspose(costs);\n\n\tif (!minimize_costs)\n\t{\n\t\tconst T max_cost = *omptl::max_element(costs.begin(), costs.end());\n\t\tomptl::transform(costs.begin(), costs.end(), costs.begin(),\n\t\t\t\t\tstd::bind1st(std::minus<T>(), max_cost));\n\t}\n\n\tif ( heuristic && (m == n) )\n\t\tdetail::to_zero(costs);\n//fprintf(stderr, \"GO!\\n\");\n\tdetail::hungarian(costs, a_mate, b_mate);\n\n\tif (transposed)\n\t\ta_mate.swap(b_mate);\n\n\tassert(a_mate.size() <= b_mate.size());\n\tfor (std::size_t a = 0; a < a_mate.size(); ++a)\n\t\tif (a_mate[a] >= 0)\n\t\t{\n\t\t\t// Check reprociatability\n\t\t\tassert(b_mate[a_mate[a]] == std::ptrdiff_t(a));\n\t\t\tmatches.push_back( std::make_pair(a, a_mate[a]) );\n\t\t}\n}\n*/\n} // end namespace cvmlcpp\n", "meta": {"hexsha": "843575dcd976e1d51e81ffacaa75655e38cae829", "size": 48027, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/cvmlcpp/math/Math.hpp", "max_stars_repo_name": "TanayGahlot/ToolpathGenerator", "max_stars_repo_head_hexsha": "a10aabfc704dd88d348c20b95072fe9cdd4bb383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-04-02T12:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T18:43:46.000Z", "max_issues_repo_path": "src/lib/cvmlcpp/math/Math.hpp", "max_issues_repo_name": "TanayGahlot/ToolpathGenerator", "max_issues_repo_head_hexsha": "a10aabfc704dd88d348c20b95072fe9cdd4bb383", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2015-12-04T04:58:01.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-07T06:43:57.000Z", "max_forks_repo_path": "src/lib/cvmlcpp/math/Math.hpp", "max_forks_repo_name": "TanayGahlot/ToolpathGenerator", "max_forks_repo_head_hexsha": "a10aabfc704dd88d348c20b95072fe9cdd4bb383", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-12-05T21:13:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T04:29:15.000Z", "avg_line_length": 25.9886363636, "max_line_length": 106, "alphanum_fraction": 0.5942490682, "num_tokens": 16037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7371581684030624, "lm_q1q2_score": 0.5628082927471589}}
{"text": "/*=============================================================================\n    Copyright (c) 2002-2003 Joel de Guzman\n    http://spirit.sourceforge.net/\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///////////////////////////////////////////////////////////////////////////////\n//\n//  A parser for a real number parser that parses thousands separated numbers\n//  with at most two decimal places and no exponent. This is discussed in the\n//  \"Numerics\" chapter in the Spirit User's Guide.\n//\n//  [ JDG 12/16/2003 ]\n//\n///////////////////////////////////////////////////////////////////////////////\n#include <boost/spirit/include/classic_core.hpp>\n#include <boost/spirit/include/classic_assign_actor.hpp>\n#include <iostream>\n#include <string>\n\n///////////////////////////////////////////////////////////////////////////////\nusing namespace std;\nusing namespace BOOST_SPIRIT_CLASSIC_NS;\n\ntemplate <typename T>\nstruct ts_real_parser_policies : public ureal_parser_policies<T>\n{\n    //  These policies can be used to parse thousand separated\n    //  numbers with at most 2 decimal digits after the decimal\n    //  point. e.g. 123,456,789.01\n\n    typedef uint_parser<int, 10, 1, 2>  uint2_t;\n    typedef uint_parser<T, 10, 1, -1>   uint_parser_t;\n    typedef int_parser<int, 10, 1, -1>  int_parser_t;\n\n    //////////////////////////////////  2 decimal places Max\n    template <typename ScannerT>\n    static typename parser_result<uint2_t, ScannerT>::type\n    parse_frac_n(ScannerT& scan)\n    { return uint2_t().parse(scan); }\n\n    //////////////////////////////////  No exponent\n    template <typename ScannerT>\n    static typename parser_result<chlit<>, ScannerT>::type\n    parse_exp(ScannerT& scan)\n    { return scan.no_match(); }\n\n    //////////////////////////////////  No exponent\n    template <typename ScannerT>\n    static typename parser_result<int_parser_t, ScannerT>::type\n    parse_exp_n(ScannerT& scan)\n    { return scan.no_match(); }\n\n    //////////////////////////////////  Thousands separated numbers\n    template <typename ScannerT>\n    static typename parser_result<uint_parser_t, ScannerT>::type\n    parse_n(ScannerT& scan)\n    {\n        typedef typename parser_result<uint_parser_t, ScannerT>::type RT;\n        static uint_parser<unsigned, 10, 1, 3> uint3_p;\n        static uint_parser<unsigned, 10, 3, 3> uint3_3_p;\n        if (RT hit = uint3_p.parse(scan))\n        {\n            T n;\n            typedef typename ScannerT::iterator_t iterator_t;\n            iterator_t save = scan.first;\n            while (match<> next = (',' >> uint3_3_p[assign_a(n)]).parse(scan))\n            {\n                hit.value((hit.value() * 1000) + n);\n                scan.concat_match(hit, next);\n                save = scan.first;\n            }\n            scan.first = save;\n            return hit;\n\n            // Note: On erroneous input such as \"123,45\", the result should\n            // be a partial match \"123\". 'save' is used to makes sure that\n            // the scanner position is placed at the last *valid* parse\n            // position.\n        }\n        return scan.no_match();\n    }\n};\n\nreal_parser<double, ts_real_parser_policies<double> > const\n    ts_real_p = real_parser<double, ts_real_parser_policies<double> >();\n\n////////////////////////////////////////////////////////////////////////////\n//\n//  Main program\n//\n////////////////////////////////////////////////////////////////////////////\nint\nmain()\n{\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    cout << \"\\t\\tA real number parser that parses thousands separated\\n\";\n    cout << \"\\t\\tnumbers with at most two decimal places and no exponent...\\n\\n\";\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n\n    cout << \"Give me a number.\\n\";\n    cout << \"Type [q or Q] to quit\\n\\n\";\n\n    string str;\n    double n;\n    while (getline(cin, str))\n    {\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\n            break;\n\n        if (parse(str.c_str(), ts_real_p[assign_a(n)]).full)\n        {\n            cout << \"-------------------------\\n\";\n            cout << \"Parsing succeeded\\n\";\n            cout << str << \" Parses OK: \" << endl;\n            cout << \"n=\" << n << endl;\n            cout << \"-------------------------\\n\";\n        }\n        else\n        {\n            cout << \"-------------------------\\n\";\n            cout << \"Parsing failed\\n\";\n            cout << \"-------------------------\\n\";\n        }\n    }\n\n    cout << \"Bye... :-) \\n\\n\";\n    return 0;\n}\n\n\n", "meta": {"hexsha": "1b84e05bfc56de34d29bc99fd5bfaac3e0d31c32", "size": 4735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/spirit/classic/example/fundamental/thousand_separated.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/spirit/classic/example/fundamental/thousand_separated.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/spirit/classic/example/fundamental/thousand_separated.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": 35.3358208955, "max_line_length": 81, "alphanum_fraction": 0.4863780359, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.562756063670998}}
{"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 <iostream>\n#include <Eigen/Dense>\n#include \"../simple_lib/include/simple_layer.h\"\n\nusing namespace Eigen;\n\nint main(){\n    using std::cout;\n    using std::endl;\n    using namespace MyDL;\n\n    MatrixXd x = MatrixXd::Zero(2,2);\n    MatrixXd y = MatrixXd::Zero(2,2);\n    MatrixXd z, dx, dy;\n    MatrixXd dout = MatrixXd::Ones(2, 2);\n\n    x << 1, 2,\n         3, 4;\n    y << 2, 2,\n         3, 3;\n\n    MulLayer mul;\n\n    z = mul.forward(x, y);\n    mul.backward(dout, dx, dy);\n\n    cout << \"--- forward ---\" << endl;\n    cout << z << endl;\n\n    cout << \"--- backward ---\" << endl;\n    cout << dx << endl;\n    cout << dy << endl;\n\n    return 0;\n}", "meta": {"hexsha": "32fdd2557138f0ce57edd66bd28e11ea2e88e803", "size": 647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch5/mul_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": "ch5/mul_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": "ch5/mul_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": 18.4857142857, "max_line_length": 47, "alphanum_fraction": 0.5285935085, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579722, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5626153731650542}}
{"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\u00f3n 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\u00e9 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\u00f3 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\u00edtulo 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#include <algorithm>\n#include <boost/lambda/lambda.hpp>\n#include <graphic/sampler.h>\n\nnamespace graphic {\n\nvoid Sampler::add_sample(math::scalar time, math::matrix<4,4> const &m)\n{\n\tsample s;\n\ts.time = time;\n\ts.transform = m;\n\ts.translation.set(m.ij[3][0], m.ij[3][1], m.ij[3][2]);\n\ts.rotation.set_unit(m);\n\n\tif (samples_.size()) {\n\t\tsamples_.back().rotation_interpolator.setup(samples_.back().rotation, s.rotation);\n\t}\n\n\tsamples_.push_back(s);\n}\n\nmath::matrix<4,4> Sampler::get(math::scalar time) const {\n\tif (time <= samples_.front().time) return samples_.front().transform;\n\tif (time >= samples_.back().time) return samples_.back().transform;\n\n\tusing namespace boost::lambda;\n\tsamples_type::const_iterator it = std::lower_bound(samples_.begin(), samples_.end(), sample(time), &_1 ->* &sample::time < &_2 ->* &sample::time);\n\n\tmath::scalar k = (time - (it - 1)->time) / (it->time - (it - 1)->time);\n\tmath::scalar inv_k = 1.0f - k;\n\n\tmath::matrix<4,4> m;\n\tm.rotation((it - 1)->rotation_interpolator.interpolate(k));\n\tm.translate((it - 1)->translation * inv_k + it->translation * k);\n\treturn m;\n}\n\n}\n\n", "meta": {"hexsha": "b78c6fcb414f80bdda85a57283ba8c92d710d172", "size": 1102, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/graphic/sampler.cc", "max_stars_repo_name": "mnvl/scratch", "max_stars_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T11:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-15T11:55:32.000Z", "max_issues_repo_path": "src/graphic/sampler.cc", "max_issues_repo_name": "mnvl/scratch", "max_issues_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graphic/sampler.cc", "max_forks_repo_name": "mnvl/scratch", "max_forks_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8780487805, "max_line_length": 147, "alphanum_fraction": 0.667876588, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5625835822773535}}
{"text": "//=======================================================================\n// Copyright 2012 David Doria\n// Authors: David Doria\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 <iostream>\n#include <boost/array.hpp>\n#include <boost/graph/grid_graph.hpp>\n\nint main(int argc, char* argv[])\n{\n  // A 2D grid graph\n  typedef boost::grid_graph<2> GraphType;\n\n  // Create a 5x5 graph\n  const unsigned int dimension = 5;\n  boost::array<std::size_t, 2> lengths = { { dimension, dimension } };\n  GraphType graph(lengths);\n\n  // Get the index map of the grid graph\n  typedef boost::property_map<GraphType, boost::vertex_index_t>::const_type indexMapType;\n  indexMapType indexMap(get(boost::vertex_index, graph));\n\n  // Create a float for every node in the graph\n  boost::vector_property_map<float, indexMapType> dataMap(num_vertices(graph), indexMap);\n\n  // Associate the value 2.0 with the node at position (0,1) in the grid\n  boost::graph_traits<GraphType>::vertex_descriptor v = { { 0, 1 } };\n  put(dataMap, v, 2.0f);\n\n  // Get the data at the node at position (0,1) in the grid\n  float retrieved = get(dataMap, v);\n  std::cout << \"Retrieved value: \" << retrieved << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "8b40351aad6bf73b98e5a34e80eb83551dc67acf", "size": 1379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/grid_graph_properties.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/grid_graph_properties.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/grid_graph_properties.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": 33.6341463415, "max_line_length": 89, "alphanum_fraction": 0.6308919507, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5625511188925539}}
{"text": "#ifndef _INTERPOLATOR_HPP_\n#define _INTERPOLATOR_HPP_\n\n#include <iostream>\n#include <iomanip>\n#include <complex>\n#include <cmath>\n#include <Eigen/Dense>\n#include <eigen3/Eigen/Dense>\n\nnamespace eco_tracker {\n\n\tvoid getInterpFourier(const int& filter_width,\n\t\t\t\t\t\t  const int& filter_height,\n\t\t\t\t\t\t  Eigen::MatrixXcf& interp1_fs,\n\t\t\t\t\t\t  Eigen::MatrixXcf& interp2_fs, \n\t\t\t\t\t\t  float a);\n\n    Eigen::MatrixXcf CubicSplineFourier(Eigen::MatrixXcf f, float a);\n} // namespace eco_tracker\n\n#endif", "meta": {"hexsha": "d2bdbd96bff942edbfc0e78f8c33f76f3a0413f5", "size": 491, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "app/inc/interpolator.hpp", "max_stars_repo_name": "lygbuaa/eco_tracker", "max_stars_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-04-20T05:38:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T06:30:41.000Z", "max_issues_repo_path": "app/inc/interpolator.hpp", "max_issues_repo_name": "lygbuaa/eco_tracker", "max_issues_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-06T11:12:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-10T11:27:12.000Z", "max_forks_repo_path": "app/inc/interpolator.hpp", "max_forks_repo_name": "lygbuaa/eco_tracker", "max_forks_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-12T03:47:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T06:44:17.000Z", "avg_line_length": 22.3181818182, "max_line_length": 69, "alphanum_fraction": 0.7250509165, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5625102098576139}}
{"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": "/*\n  Test program for MatPlot\n\n  Dag Lindbo, dag@csc.kth.se\n*/\n\n#include \"matplot.h\"\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nnamespace ublas = boost::numeric::ublas;\ntypedef ublas::vector<double> Vector;\ntypedef ublas::matrix<double> Matrix;\n\nusing namespace std;\nusing namespace matplot;\n\n// parameters for 2D plot\nconst int NN = 40;\nconst double t_low = 0;\nconst double t_upp = 5;\nconst double dt = (t_upp-t_low)/(NN-1);\n\n// parameters for 3D stuff\nconst int Nx = 200;\nconst int Ny = 250;\nconst double x_low = -2.5;\nconst double x_upp = 1.5;\nconst double y_low = -2.5;\nconst double y_upp = 2.5;\nconst double dx = (x_upp-x_low)/(Nx-1);\nconst double dy = (y_upp-y_low)/(Ny-1);\n\n#define G(x,y) exp(-(x*x+y*y))*sin(x)*cos(y);\n\n// parameters for quiver plot\nconst int NNx = 20;\nconst int NNy = 37;\nconst double xx_low = 0;\nconst double xx_upp = 1;\nconst double yy_low = 0;\nconst double yy_upp = 1.5;\nconst double dxx = (xx_upp-xx_low)/(NNx-1);\nconst double dyy = (yy_upp-yy_low)/(NNy-1);\n\nint main(void)\n{\n  int i, j;\n\n  // EXAMPLE: Plot_2D =======================================\n  Vector x1(NN);\n  Vector y1(NN);\n  Vector x2(NN);\n  Vector y2(NN);\n\n  double t = t_low;\n\n  for (i=0; i<NN; i++)\n    {\n      x1(i) = cos(t)*t;\n      y1(i) = sin(t);\n      x2(i) = sin(t)*t+1;\n      y2(i) = cos(t)*(0.1-t);\n      t+=dt;\n    }\n\n  Plot2D_VTK p_2d(\"x(t)\", \"y(t)\", 800, 600);\n\n  double color1[3] =\n    { 0.0, 0.0, 1.0 };\n  double color2[3] =\n    { 1.0, 0.0, 0.0 };\n\n  p_2d.plot(x1, y1, color1, \"-\");\n  p_2d.plot(x2, y2, color2, \".-\");\n  p_2d.show();\n  //p_2d.draw_to_png(\"plot_2d.png\");\n\n  // EXAMPLE: Contour =======================================\n\n  Vector x(Nx);\n  Vector y(Ny);\n  Matrix z(Nx, Ny);\n\n  for (i=0; i<Nx; i++)\n    x(i) = x_low+i*dx;\n\n  for (i=0; i<Ny; i++)\n    y(i) = y_low + i*dy;\n\n  for (i=0; i<Nx; i++)\n    for (j=0; j<Ny; j++)\n      z(i, j) = G(x(i),y(j));\n\n  Contour_VTK p_cont(800, 600);\n  p_cont.contour(x, y, z, true, 20);\n  //p_cont.contour_to_file(x,y,z,true,20,\"contours.png\");\n\n  // EXAMPLE: Surf ==========================================\n\n  double cam[3] =\n    { -15.0, 10.0, 12.0 };\n  double focal[3] =\n    { 0, 0, 0 };\n  Surf_VTK p_surf(800, 600);\n  //p_surf.surf(x,y,z);\n  //p_surf.surf(x,y,z,false);\n  p_surf.surf(x, y, z, true, cam, focal);\n  //p_surf.surf_to_file(x,y,z,true,\"surf.png\",cam,focal);\n\n  // Example: Quiver ========================================\n  Vector xx(NNx);\n  Vector yy(NNy);\n  Matrix u(NNx, NNy);\n  Matrix v(NNx, NNy);\n\n  for (i=0; i<NNx; i++)\n    xx(i) = xx_low+i*dxx;\n\n  for (i=0; i<NNy; i++)\n    yy(i) = yy_low + i*dyy;\n\n  for (i=0; i<NNx; i++)\n    for (j=0; j<NNy; j++)\n      {\n   \tu(i, j) = -yy(j);\n   \tv(i, j) = xx(i);\n      }\n\n  Quiver_VTK p_quiver(800, 600);\n  p_quiver.quiver(xx, yy, u, v, 0.1);\n  //p_quiver.quiver_to_file(xx,yy,u,v,0.1,\"quiver.png\");\n\n  return 0;\n}\n", "meta": {"hexsha": "b836d0fa719b754c440b3f08d7683b381b6cd9c1", "size": 2870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gamess/libqc/src/contrib/matplot/ublas/examples_ublas.cpp", "max_stars_repo_name": "andremirt/v_cond", "max_stars_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "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": "gamess/libqc/src/contrib/matplot/ublas/examples_ublas.cpp", "max_issues_repo_name": "andremirt/v_cond", "max_issues_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "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": "gamess/libqc/src/contrib/matplot/ublas/examples_ublas.cpp", "max_forks_repo_name": "andremirt/v_cond", "max_forks_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "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.9489051095, "max_line_length": 61, "alphanum_fraction": 0.5442508711, "num_tokens": 1088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5625101932015337}}
{"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": "#include \"stdafx.h\"\r\n#include <catch.hpp>\r\n#include <boost/spirit/home/x3.hpp>\r\n#include <boost/fusion/adapted/std_pair.hpp>\r\n\r\n#include <iostream>\r\n#include <map>\r\n\r\nusing namespace boost::spirit::x3;\r\n\r\nnamespace\r\n{\r\n\r\nstruct hundreds_ : symbols<unsigned>\r\n{\r\n\thundreds_()\r\n\t{\r\n\t\t// DSEL w/ operator ()\r\n\t\tadd\r\n\t\t\t(\"C\", 100)\r\n\t\t\t(\"CC\", 200)\r\n\t\t\t(\"CCC\", 300)\r\n\t\t\t(\"CD\", 400)\r\n\t\t\t(\"D\", 500)\r\n\t\t\t(\"DC\", 600)\r\n\t\t\t(\"DCC\", 700)\r\n\t\t\t(\"DCCC\", 800)\r\n\t\t\t(\"CM\", 900)\r\n\t\t\t;\r\n\t}\r\n\r\n} hundreds;\r\n\r\nstruct tens_ : symbols<unsigned>\r\n{\r\n\ttens_()\r\n\t{\r\n\t\tadd\r\n\t\t(\"X\", 10)\r\n\t\t\t(\"XX\", 20)\r\n\t\t\t(\"XXX\", 30)\r\n\t\t\t(\"XL\", 40)\r\n\t\t\t(\"L\", 50)\r\n\t\t\t(\"LX\", 60)\r\n\t\t\t(\"LXX\", 70)\r\n\t\t\t(\"LXXX\", 80)\r\n\t\t\t(\"XC\", 90)\r\n\t\t\t;\r\n\t}\r\n\r\n} tens;\r\n\r\nstruct ones_ : symbols<unsigned>\r\n{\r\n\tones_()\r\n\t{\r\n\t\tadd\r\n\t\t(\"I\", 1)\r\n\t\t\t(\"II\", 2)\r\n\t\t\t(\"III\", 3)\r\n\t\t\t(\"IV\", 4)\r\n\t\t\t(\"V\", 5)\r\n\t\t\t(\"VI\", 6)\r\n\t\t\t(\"VII\", 7)\r\n\t\t\t(\"VIII\", 8)\r\n\t\t\t(\"IX\", 9)\r\n\t\t\t;\r\n\t}\r\n\r\n} ones;\r\n\r\n}\r\n\r\nnamespace roman_parser\r\n{\r\n\r\nauto set_zero = [&](auto& ctx) { _val(ctx) = 0; };\r\nauto add1000 = [&](auto& ctx) { _val(ctx) += 1000; };\r\nauto add = [&](auto& ctx) { _val(ctx) += _attr(ctx); };\r\n\r\nrule<class roman, unsigned> const roman = \"roman\";\r\n\r\nauto const roman_def =\r\neps[set_zero]\t\t// eps is epsilon (empty) parser\r\n>>\r\n(\r\n\t-(+lit('M')[add1000])\r\n\t>> -hundreds[add]\r\n\t>> -tens[add]\r\n\t>> -ones[add]\r\n\t)\r\n\t;\r\n\r\nBOOST_SPIRIT_DEFINE(roman);\r\n} // parser\r\n\r\n\r\nTEST_CASE(\"a roman parser\")\r\n{\r\n\tSECTION(\"parse\")\r\n\t{\r\n\t\tstd::string input = \"XI\";\r\n\r\n\t\tunsigned result = 0;\r\n\r\n\t\tauto first = input.begin(); \r\n\t\tauto last = input.end();\r\n\r\n\t\tbool rc = phrase_parse(first, last, roman_parser::roman, space, result);\r\n\r\n\t\tCHECK(rc);\r\n\t\tCHECK(result == 11);\r\n\t}\r\n}", "meta": {"hexsha": "abe8289812f5908c7c40bf751c5f5a176094bdc8", "size": 1672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "programming/compiler/ex/spirit_roman_parser.cpp", "max_stars_repo_name": "laxtools/article", "max_stars_repo_head_hexsha": "8bd5a4c080475b6306610a91fe0405de08302a87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "programming/compiler/ex/spirit_roman_parser.cpp", "max_issues_repo_name": "laxtools/article", "max_issues_repo_head_hexsha": "8bd5a4c080475b6306610a91fe0405de08302a87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "programming/compiler/ex/spirit_roman_parser.cpp", "max_forks_repo_name": "laxtools/article", "max_forks_repo_head_hexsha": "8bd5a4c080475b6306610a91fe0405de08302a87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-08T22:59:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T22:59:38.000Z", "avg_line_length": 14.6666666667, "max_line_length": 75, "alphanum_fraction": 0.5029904306, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5624168639344547}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"utils/normalizations.h\"\n#include \"inputs/minmax.h\"\n#include \"inputs/zmaxnorm.h\"\n#include \"inputs/znorm.h\"\n#include \"inputs/column.h\"\n#include \"utils/algorithms.hpp\"\n#include <boost/range/algorithm/sort.hpp>\n\nBOOST_AUTO_TEST_CASE(test_znorm)\n{\n    const std::vector<double> test_data(std::begin(data_mapstd), std::end(data_mapstd));\n    auto after_norm{utils::z_normalization(test_data)};\n    BOOST_TEST_REQUIRE(after_norm.size() == test_data.size());\n    BOOST_TEST_REQUIRE(after_norm.size() == utils::size(expected_first_mapstd));\n    std::vector<double> expected(std::begin(expected_first_mapstd), std::end(expected_first_mapstd));\n    boost::sort(after_norm);\n    boost::sort(expected);\n    auto ex_begin = std::begin(expected);\n    for (auto n_begin = std::begin(after_norm); n_begin != std::end(after_norm); ++n_begin, ++ex_begin) {\n        BOOST_TEST(round_cmp(*n_begin, *ex_begin, 0.0001), \"value after the norm \"<<*n_begin<<\" != expected \"<<*ex_begin);\n    }\n\n}\n\nBOOST_AUTO_TEST_CASE(test_minmax_norm)\n{\n    const std::vector<double> test_data(std::begin(min_max_data), std::end(min_max_data));\n    double min_val = PsY[0]; \n    double max_val = PsY[1];\n    auto after_norm = utils::min_max_normalization(test_data, min_val, max_val);\n    auto found = std::none_of(std::begin(after_norm), std::end(after_norm), \n                        [min_val, max_val](auto v)\n                        {\n                            return v < min_val || v > max_val;\n                        }\n                    );\n    BOOST_TEST_REQUIRE(found, \n            \"we don't expect to have any value after norm that is less than \"\n            <<min_val<<\" or larger than \"<<max_val);\n    BOOST_TEST_REQUIRE(after_norm.size() == utils::size(expected_first), \n            \"the size of the norm output \"<<after_norm.size()<<\" not the same as the size \"<<\n            utils::size(expected_first)<<\" that we are expecting\");\n    std::vector<double> expected(std::begin(expected_first), std::end(expected_first));\n    boost::sort(after_norm);\n    boost::sort(expected);\n    auto expect_begin = std::begin(expected);\n    for (auto norm_begin = std::begin(after_norm); norm_begin != std::end(after_norm); ++norm_begin, ++expect_begin) {\n        BOOST_TEST(round_cmp(*norm_begin, *expect_begin, 0.0001), \"value for \"<<*norm_begin<<\" != expected \"<<*expect_begin);\n    }\n}\nBOOST_AUTO_TEST_CASE(test_minmax_norm_second)\n{\n    const std::vector<double> test_data(std::begin(min_max_data), std::end(min_max_data));\n    double min_val = PsY2[0]; \n    double max_val = PsY2[1];\n    auto after_norm = utils::min_max_normalization(test_data, min_val, max_val);\n    auto found = std::none_of(std::begin(after_norm), std::end(after_norm), \n                        [min_val, max_val](auto v)\n                        {\n                            return v < min_val || v > max_val;\n                        }\n                    );\n    BOOST_TEST_REQUIRE(found, \n            \"we don't expect to have any value after norm that is less than \"\n            <<min_val<<\" or larger than \"<<max_val);\n    BOOST_TEST_REQUIRE(after_norm.size() == utils::size(expected_second), \n            \"the size of the norm output \"<<after_norm.size()<<\" not the same as the size \"<<\n            utils::size(expected_second)<<\" that we are expecting\");\n    std::vector<double> expected(std::begin(expected_second), std::end(expected_second));\n    boost::sort(after_norm);\n    boost::sort(expected);\n    auto expect_begin = std::begin(expected);\n    for (auto norm_begin = std::begin(after_norm); norm_begin != std::end(after_norm); ++norm_begin, ++expect_begin) {\n        BOOST_TEST(round_cmp(*norm_begin, *expect_begin, 0.0001), \"value for \"<<*norm_begin<<\" != expected \"<<*expect_begin);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_max_norm)\n{\n    const std::vector<double> test_data(std::begin(data_zmax), std::end(data_zmax));\n    auto after_norm{utils::max_normalization(test_data)};\n    BOOST_TEST_REQUIRE(after_norm.size() == test_data.size());\n    BOOST_TEST_REQUIRE(after_norm.size() == utils::size(expected_zmax));\n    std::vector<double> expected(std::begin(expected_zmax), std::end(expected_zmax));\n    auto f = std::all_of(std::begin(after_norm), std::end(after_norm), [](auto val) {\n                return val >= 0 && val <= 1;\n            }\n    );\n    BOOST_TEST_REQUIRE(f, \"we have value that is bigger than 1 or smaller than 0\");\n    //return;\n    boost::sort(after_norm);\n    boost::sort(expected);\n    auto ex_begin = std::begin(expected);\n    for (auto n_begin = std::begin(after_norm); n_begin != std::end(after_norm); ++n_begin, ++ex_begin) {\n        BOOST_TEST(round_cmp(*n_begin, *ex_begin, 0.0001), \"value after the norm \"<<*n_begin<<\" != expected \"<<*ex_begin);\n    }\n}\nBOOST_AUTO_TEST_CASE(test_nan_issue)\n{\n    const std::vector<double> test_data(std::begin(column_values), std::end(column_values));\n    auto after_norm{utils::min_max_normalization(test_data, 0, 1)};\n    BOOST_TEST(std::none_of(std::begin(after_norm), std::end(after_norm), [](auto val) {\n                        if (std::isnan(val) || std::isinf(val)) {\n                            BOOST_TEST(false, \"value \"<<val<<\" is not valid\");\n                            return true;\n                        }\n                        return false;\n                    }\n            )\n    );\n}\n\n", "meta": {"hexsha": "56e486838f3ce3a0194ba9d4f6a1b39daa3dcf73", "size": 5362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/utils/ut/test_normalization.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/ut/test_normalization.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/ut/test_normalization.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": 47.0350877193, "max_line_length": 125, "alphanum_fraction": 0.6290563223, "num_tokens": 1272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624586752075, "lm_q2_score": 0.7185944046238982, "lm_q1q2_score": 0.5624168635131871}}
{"text": "//\n// Created by keszocze on 10.10.18.\n//\n\n#include <error_rate.hpp>\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <catch2/catch.hpp>\n#include <cudd/cplusplus/cuddObj.hh>\n#include <cudd_helpers.hpp>\n#include <simple.hpp>\n#include <from_papers.hpp>\n#include <worst_case_error.hpp>\n#include <average_case_error.hpp>\n#include <worst_case_relative_error.hpp>\n\n#include <iostream>\n\n\nTEST_CASE(\"Trivial Error Rate Test\") {\n    Cudd mgr(2);\n\n    mgr.pushVariableName(\"x\");\n    mgr.pushVariableName(\"y\");\n    mgr.pushVariableName(\"z\");\n\n    std::vector<std::string> varnames = {\"x\",\"y\",\"z\"};\n    std::vector<std::string> funnames = {\"and\", \"and_hat\"};\n\n    BDD x = mgr.bddVar(0);\n    BDD y = mgr.bddVar(1);\n    BDD z = mgr.bddVar(2);\n\n\n    BDD and_bdd = x*y*z;\n\n    BDD and_approx_bdd = and_bdd.Constrain(y);\n\n    std::vector<BDD> funs{and_bdd, and_approx_bdd};\n\n//    abo::util::dump_dot(mgr,funs[0],varnames,funnames[0]);\n//\n//    abo::util::dump_dot(mgr,funs, varnames, funnames);\n\n    REQUIRE(1.0 / 8.0 == abo::error_metrics::error_rate(mgr,and_bdd,and_approx_bdd));\n\n    and_approx_bdd = and_approx_bdd.Constrain(x);\n\n    REQUIRE(3.0 / 8.0 == abo::error_metrics::error_rate(mgr,and_bdd,and_approx_bdd));\n\n    and_approx_bdd = and_approx_bdd.Constrain(z);\n\n    REQUIRE(7.0 / 8.0 == abo::error_metrics::error_rate(mgr,and_bdd,and_approx_bdd));\n\n\n}\n\n\n/**\n * @brief Hardcoded example from the 2016 ASP-DAC paper by Soeken et al.\n */\nTEST_CASE(\"Example 3 from ASP-DAC 2016 paper\") {\n    Cudd mgr(2);\n\n    std::vector<BDD> fun = abo::example_bdds::example3(mgr);\n\n//    abo::util::dump_dot(mgr,fun,{\"x_1\", \"x_2\"},{\"d_0\", \"d_1\", \"d_2\", \"d_3\", \"d_4\"});\n\n\n\n    boost::multiprecision::uint256_t max_error = abo::error_metrics::get_max_value(mgr, fun);\n\n    REQUIRE(13 == max_error);\n\n}\n\nTEST_CASE(\"Trivial worst_case_error\") {\n    Cudd mgr(2);\n\n    std::vector<BDD> zero_fun{mgr.bddZero(), mgr.bddZero()};\n    std::vector<BDD> one_fun{mgr.bddOne(), mgr.bddOne()};\n\n\n//    std::cout << abo::error_metrics::worst_case_error(mgr, zero_fun, one_fun);\n\n}\n\n\nTEST_CASE(\"Generic OR constraint error rate test\"){\n\n\n    constexpr size_t n = 30;\n\n    Cudd mgr(n);\n\n    BDD or_bdd = abo::example_bdds::or_bdd(mgr,n);\n\n    // TODO Methoden f\u00fcr die generische Erzeugung von AND, OR, XOR etc. BDDs erzeugen\n\n    for (size_t i = 0; i < n; i++) {\n        or_bdd = or_bdd + mgr.bddVar(i);\n    }\n\n\n    BDD or_pos_approx_bdd = or_bdd;\n    BDD or_neg_approx_bdd = or_bdd;\n\n    REQUIRE(0 == abo::error_metrics::error_rate(mgr, or_bdd,or_pos_approx_bdd));\n    REQUIRE(0 == abo::error_metrics::error_rate(mgr, or_bdd,or_neg_approx_bdd));\n\n    for (size_t i = 0; i < n; i++) {\n        or_pos_approx_bdd = or_pos_approx_bdd.Constrain(mgr.bddVar(i));\n        or_neg_approx_bdd = or_neg_approx_bdd.Constrain(!mgr.bddVar(i));\n\n        double expected_error = double((1L << (i+1)) - 1) / double(1L << n);\n\n\n        auto computed_error = abo::error_metrics::error_rate(mgr, or_bdd,or_neg_approx_bdd);\n\n//        std::cout << \"i=\" << i << \"\\texpected error=\" << expected_error <<\"\\tcomputed error=\" << computed_error << \"\\n\";\n        REQUIRE(expected_error == computed_error);\n        REQUIRE(1.0 / double(1L << n) ==  abo::error_metrics::error_rate(mgr, or_bdd,or_pos_approx_bdd));\n    }\n\n\n}\n\n\n\nTEST_CASE(\"Generic AND constraint error rate test\"){\n\n\n    constexpr size_t n = 20;\n\n    Cudd mgr(n);\n\n    BDD and_bdd = abo::example_bdds::and_bdd(mgr,n);\n\n    BDD and_pos_approx_bdd = and_bdd;\n    BDD and_neg_approx_bdd = and_bdd;\n\n    REQUIRE(0 == abo::error_metrics::error_rate(mgr, and_bdd,and_pos_approx_bdd));\n    REQUIRE(0 == abo::error_metrics::error_rate(mgr, and_bdd,and_neg_approx_bdd));\n\n    for (size_t i = 0; i < n; i++) {\n        and_pos_approx_bdd = and_pos_approx_bdd.Constrain(mgr.bddVar(i));\n        and_neg_approx_bdd = and_pos_approx_bdd.Constrain(!mgr.bddVar(i));\n        double expected_error = double((1L << (i+1)) - 1) / double(1L << n);\n\n        // TODO sinnvolles overloads, so dsas man keine d\u00e4mlichen ein-bdd vektoren mehr bauen muss\n\n        auto computed_error = abo::error_metrics::error_rate(mgr, and_bdd,and_pos_approx_bdd);\n\n//        std::cout << \"i=\" << i << \"\\texpected error=\" << expected_error <<\"\\tcomputed error=\" << computed_error << \"\\n\";\n        REQUIRE(expected_error == computed_error);\n        REQUIRE(expected_error == abo::error_metrics::error_rate(mgr,and_bdd,and_neg_approx_bdd));\n    }\n\n\n}\n\n\nTEST_CASE(\"Trivial average case error\") {\n\n    const size_t n = 3;\n    Cudd mgr(n);\n\n    std::vector<BDD> zero({mgr.bddZero(), mgr.bddZero()});\n    std::vector<BDD> one({mgr.bddOne(), mgr.bddOne()});\n\n    REQUIRE(abo::error_metrics::average_case_error(mgr, one, zero) == 3);\n}\n\nstatic void check_wcr_values(Cudd &mgr, const std::vector<BDD> &f,\n                             const std::vector<BDD> &g, long desired_wcr) {\n    auto f_ = f;\n    auto g_ = g;\n\n    // equalize function sizes (is necessary for the error metrics)\n    while (f_.size() < g_.size()) f_.push_back(mgr.bddZero());\n    while (g_.size() < f_.size()) g_.push_back(mgr.bddZero());\n\n    double bin_search = abo::error_metrics::wcre_search(mgr, f, g);\n    REQUIRE(desired_wcr == bin_search);\n\n    auto ran_search = abo::error_metrics::wcre_randomized_search(mgr, f, g);\n    REQUIRE(desired_wcr * ran_search.second == ran_search.first);\n\n    auto symbolic = abo::error_metrics::wcre_symbolic_division(mgr, f, g);\n    REQUIRE(desired_wcr == symbolic);\n\n    auto add = abo::error_metrics::wcre_symbolic_division(mgr, f, g);\n    REQUIRE(desired_wcr == add);\n}\n\nTEST_CASE(\"Simple worst case relative error metrics\") {\n    Cudd mgr(256);\n    auto f1 = abo::util::number_to_bdds(mgr, 1);\n\n    // check some static values\n    for (long f2val : {0, 1, 5, 21, 1232345}) {\n        auto f2 = abo::util::number_to_bdds(mgr, f2val + 1);\n        check_wcr_values(mgr, f1, f2, f2val);\n    }\n\n    // check division by zero not occuring\n    check_wcr_values(mgr, abo::util::number_to_bdds(mgr, 0), f1, 1);\n\n    // division is performed\n    check_wcr_values(mgr, abo::util::number_to_bdds(mgr, 3),\n                     abo::util::number_to_bdds(mgr, 18), 5);\n}\n", "meta": {"hexsha": "a95a222e5c12330feabb83368535bb568fe1dceb", "size": 6114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/error_metrics_test.cpp", "max_stars_repo_name": "keszocze/abo", "max_stars_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/error_metrics_test.cpp", "max_issues_repo_name": "keszocze/abo", "max_issues_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/error_metrics_test.cpp", "max_forks_repo_name": "keszocze/abo", "max_forks_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T14:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T14:50:31.000Z", "avg_line_length": 28.7042253521, "max_line_length": 122, "alphanum_fraction": 0.6542361793, "num_tokens": 1899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.5624168519319914}}
{"text": "#include \"stdafx.h\"\r\n#include \"qmath.h\"\r\n#include \"config.h\"\r\n\r\n// each test module could contain no more then one 'main' file with init function defined\r\n// alternatively you could define init function yourself\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <vector>\r\n\r\n// These are sample tests that show the different features of the framework\r\n\r\nusing namespace math;\r\n\r\nnamespace \r\n{\r\n\r\ntemplate<typename T>\r\nvoid testQuat()\r\n{\r\n\t{\r\n\t\tquat<T> a;\r\n\t\tBOOST_CHECK(a.x == 0.f && a.y == 0.f && a.z == 0.f && a.w == 1.f);\r\n\t}\r\n\r\n\t{\r\n\t\tquat<T> a(1, 2, 3, 4);\r\n\t\tBOOST_CHECK(a.x == 1 && a.y == 2 && a.z == 3 && a.w == 4);\r\n\t}\r\n\r\n\t{\r\n\t\tquat<T> a(quat<T>(1, 2, 3, 4));\r\n\t\tBOOST_CHECK(a.x == 1 && a.y == 2 && a.z == 3 && a.w == 4);\r\n\t}\r\n\r\n\t{\r\n\t\tfor (uint32_t i = 0; i < 360; i++)\r\n\t\t{\r\n\t\t\tquat<T> a;\r\n\t\t\ta.set_from_angle_axis(radians((T)i), vec3<T>(1, 0, 0));\r\n\t\t\tquat<T> b = quat_axis_x(radians((T)i));\r\n\t\t\tBOOST_CHECK(equals(a, b));\r\n#ifdef TEST_AGAINST_EIGEN\r\n\r\n\t\t\tEigen::AngleAxis<T> _aa(radians((T)i), Eigen::Matrix<T, 3, 1>(1, 0, 0));\r\n\t\t\tEigen::Quaternion<T> _a(_aa);\r\n\t\t\tBOOST_CHECK(_a.x() == a.x && _a.y() == a.y && _a.z() == a.z && _a.w() == a.w);\r\n\r\n#endif\r\n\t\t}\r\n\t}\r\n\t{\r\n\t\tfor (uint32_t i = 0; i < 360; i++)\r\n\t\t{\r\n\t\t\tquat<T> a;\r\n\t\t\ta.set_from_angle_axis(radians((T)i), vec3<T>(0, 1, 0));\r\n\t\t\tquat<T> b = quat_axis_y(radians((T)i));\r\n\t\t\tBOOST_CHECK(equals(a, b));\r\n#ifdef TEST_AGAINST_EIGEN\r\n\r\n\t\t\tEigen::AngleAxis<T> _aa(radians((T)i), Eigen::Matrix<T, 3, 1>(0, 1, 0));\r\n\t\t\tEigen::Quaternion<T> _a(_aa);\r\n\t\t\tBOOST_CHECK(_a.x() == a.x && _a.y() == a.y && _a.z() == a.z && _a.w() == a.w);\r\n\r\n#endif\r\n\t\t}\r\n\t}\r\n\t{\r\n\t\tfor (uint32_t i = 0; i < 360; i++)\r\n\t\t{\r\n\t\t\tquat<T> a;\r\n\t\t\ta.set_from_angle_axis(radians((T)i), vec3<T>(0, 0, 1));\r\n\t\t\tquat<T> b = quat_axis_z(radians((T)i));\r\n\t\t\tBOOST_CHECK(equals(a, b));\r\n#ifdef TEST_AGAINST_EIGEN\r\n\r\n\t\t\tEigen::AngleAxis<T> _aa(radians((T)i), Eigen::Matrix<T, 3, 1>(0, 0, 1));\r\n\t\t\tEigen::Quaternion<T> _a(_aa);\r\n\t\t\tBOOST_CHECK(_a.x() == a.x && _a.y() == a.y && _a.z() == a.z && _a.w() == a.w);\r\n\r\n#endif\r\n\t\t}\r\n\t}\r\n\t{\r\n\t\tvec3<T> right(1, 0, 0);\r\n\t\tquat<T> a = quat_axis_z(radians(T(90.0)));\r\n\t\tmat3<T> m = a.get_as_mat3();\r\n\t\tvec3<T> up = rotate(a, right);\r\n\t\tBOOST_CHECK(equals(up, vec3<T>(0, 1, 0), T(0.001)));\r\n\r\n#ifdef TEST_AGAINST_EIGEN\r\n\r\n\t\tEigen::Matrix<T, 3, 1> _right(1, 0, 0);\r\n\t\tEigen::AngleAxis<T> _aa(radians(90.f), Eigen::Matrix<T, 3, 1>(0, 0, 1));\r\n\t\tEigen::Quaternion<T> _q(_aa);\r\n\t\tEigen::Matrix<T, 3, 3> _m(_q);\r\n\t\tEigen::Matrix<T, 3, 1> _up = _q * _right;\r\n\t\tBOOST_CHECK(_up.isApprox(Eigen::Matrix<T, 3, 1>(0, 1, 0), T(0.001)));\r\n\r\n#endif\r\n\t}\r\n\r\n\r\n\t{\r\n\t\t//test Euler constructors\r\n\t\tvec3<T> tv = normalized(vec3<T>(1, 1, 1));\r\n\r\n\t\t// ms temporarily disable these long tests \r\n\t\t//return;\r\n\r\n\t\tstd::vector<quat<T>> quatAxisX(360);\r\n\t\tstd::vector<quat<T>> quatAxisY(360);\r\n\t\tstd::vector<quat<T>> quatAxisZ(360);\r\n\t\tfor (int i = 0; i < 360; i+=5)\r\n\t\t{\r\n\t\t\tT angle = radians((T)i);\r\n\t\t\tquatAxisX[i].set_from_angle_axis(angle, vec3<T>(1, 0, 0));\r\n\t\t\tquatAxisY[i].set_from_angle_axis(angle, vec3<T>(0, 1, 0));\r\n\t\t\tquatAxisZ[i].set_from_angle_axis(angle, vec3<T>(0, 0, 1));\r\n\t\t}\r\n\r\n\t\t//ZXY = Y * X * Z\r\n\r\n\t\tquat<T> aX = quatAxisX[32];\r\n\t\tquat<T> aY = quatAxisY[32];\r\n\t\tquat<T> aZ = quatAxisZ[32];\r\n\r\n\t\t// \tquat<T> aXYZ = aZ * aY * aX;\r\n\r\n\t\t//test Euler setters getters\r\n\t\tfor (int anglex = 0; anglex < 360; anglex += 15)\r\n\t\t{\r\n\t\t\tvec3<T> angles;\r\n\t\t\tangles.x = radians((T)anglex);\r\n\t\t\tquat<T> aX = quatAxisX[anglex];\r\n\r\n\t\t\tprintf(\"\\ntesting X = %d\", anglex);\r\n\t\t\tfor (int angley = 0; angley < 360; angley += 15)\r\n\t\t\t{\r\n\t\t\t\tangles.y = radians((T)angley);\r\n\t\t\t\tquat<T> aY = quatAxisY[angley];\r\n\r\n\t\t\t\tquat<T> aYX = aX * aY;\r\n\t\t\t\tquat<T> aXY = aY * aX;\r\n\r\n\t\t\t\tfor (int anglez = 0; anglez < 360; anglez += 15)\r\n\t\t\t\t{\r\n\t\t\t\t\tangles.z = radians((T)anglez);\r\n\t\t\t\t\t//printf(\"\\ntesting (%d, %d, %d)\", anglex, angley, anglez);\r\n\t\t\t\t\tquat<T> aZ = quatAxisZ[anglez];\r\n\r\n\t\t\t\t\tquat<T> aXYZ = aYX*aZ;\r\n\t\t\t\t\tquat<T> aXZY = aX * aZ * aY;\r\n\t\t\t\t\tquat<T> aYXZ = aXY * aZ;\r\n\t\t\t\t\tquat<T> aYZX = aY * aZ * aX;\r\n\t\t\t\t\tquat<T> aZXY = aZ * aYX;\r\n\t\t\t\t\tquat<T> aZYX = aZ * aXY;\r\n\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquat<T> a;\r\n\t\t\t\t\t\ta.set_from_euler_xyz(angles);\r\n\t\t\t\t\t\tif (!equals(aXYZ, a))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tBOOST_CHECK(is_one(length(a), T(0.00001)));\r\n\t\t\t\t\t\t\tvec3<T> v1 = rotate(aXYZ, tv);\r\n\t\t\t\t\t\t\tvec3<T> v2 = rotate(a, tv);\r\n\t\t\t\t\t\t\tBOOST_CHECK(equals(v1, v2, T(0.001)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquat<T> a;\r\n\t\t\t\t\t\ta.set_from_euler_xzy(angles);\r\n\t\t\t\t\t\tif (!equals(aXZY, a))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tBOOST_CHECK(is_one(length(a), T(0.00001)));\r\n\t\t\t\t\t\t\tvec3<T> v1 = rotate(aXZY, tv);\r\n\t\t\t\t\t\t\tvec3<T> v2 = rotate(a, tv);\r\n\t\t\t\t\t\t\tBOOST_CHECK(equals(v1, v2, T(0.001)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquat<T> a;\r\n\t\t\t\t\t\ta.set_from_euler_yxz(angles);\r\n\t\t\t\t\t\tif (!equals(aYXZ, a))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tBOOST_CHECK(is_one(length(a), T(0.00001)));\r\n\t\t\t\t\t\t\tvec3<T> v1 = rotate(aYXZ, tv);\r\n\t\t\t\t\t\t\tvec3<T> v2 = rotate(a, tv);\r\n\t\t\t\t\t\t\tBOOST_CHECK(equals(v1, v2, T(0.001)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquat<T> a;\r\n\t\t\t\t\t\ta.set_from_euler_yzx(angles);\r\n\t\t\t\t\t\tif (!equals(aYZX, a))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tBOOST_CHECK(is_one(length(a), T(0.00001)));\r\n\t\t\t\t\t\t\tvec3<T> v1 = rotate(aYZX, tv);\r\n\t\t\t\t\t\t\tvec3<T> v2 = rotate(a, tv);\r\n\t\t\t\t\t\t\tBOOST_CHECK(equals(v1, v2, T(0.001)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquat<T> a;\r\n\t\t\t\t\t\ta.set_from_euler_zxy(angles);\r\n\t\t\t\t\t\tif (!equals(aZXY, a))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tBOOST_CHECK(is_one(length(a), T(0.00001)));\r\n\t\t\t\t\t\t\tvec3<T> v1 = rotate(aZXY, tv);\r\n\t\t\t\t\t\t\tvec3<T> v2 = rotate(a, tv);\r\n\t\t\t\t\t\t\tBOOST_CHECK(equals(v1, v2, T(0.001)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquat<T> a;\r\n\t\t\t\t\t\ta.set_from_euler_zyx(angles);\r\n\t\t\t\t\t\tif (!equals(aZYX, a))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tBOOST_CHECK(is_one(length(a), T(0.00001)));\r\n\t\t\t\t\t\t\tvec3<T> v1 = rotate(aZYX, tv);\r\n\t\t\t\t\t\t\tvec3<T> v2 = rotate(a, tv);\r\n\t\t\t\t\t\t\tBOOST_CHECK(equals(v1, v2, T(0.001)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//test Euler setters getters\r\n\t\tfor (int anglex = 0; anglex < 360; anglex += 15)\r\n\t\t{\r\n\t\t\tvec3<T> angles;\r\n\t\t\tangles.x = radians((T)anglex);\r\n\t\t\tquat<T> aX = quatAxisX[anglex];\r\n\r\n\t\t\tprintf(\"\\ntesting X = %d\", anglex);\r\n\t\t\tfor (int angley = 0; angley < 360; angley += 15)\r\n\t\t\t{\r\n\t\t\t\tangles.y = radians((T)angley);\r\n\t\t\t\tquat<T> aY = quatAxisY[angley];\r\n\r\n\t\t\t\tquat<T> aYX = aX * aY;\r\n\t\t\t\tquat<T> aXY = aY * aX;\r\n\r\n\t\t\t\tfor (int anglez = 0; anglez < 360; anglez += 15)\r\n\t\t\t\t{\r\n\t\t\t\t\tangles.z = radians((T)anglez);\r\n\t\t\t\t\t//printf(\"\\ntesting (%d, %d, %d)\", anglex, angley, anglez);\r\n\t\t\t\t\tquat<T> aZ = quatAxisZ[anglez];\r\n\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquat<T> a;\r\n\t\t\t\t\t\ta.set_from_euler_xyz(angles);\r\n\t\t\t\t\t\tvec3<T> angles2;\r\n\t\t\t\t\t\ta.get_as_euler_xyz(angles2);\r\n\t\t\t\t\t\tif (!equals(angles, angles2))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tquat<T> a2;\r\n\t\t\t\t\t\t\ta2.set_from_euler_xyz(angles2);\r\n\t\t\t\t\t\t\tvec3<T> v1 = rotate(aYX * aZ, tv);\r\n\t\t\t\t\t\t\tvec3<T> v2 = rotate(a, tv);\r\n\t\t\t\t\t\t\tvec3<T> v3 = rotate(a2, tv);\r\n\t\t\t\t\t\t\tBOOST_CHECK(equals(v1, v2, T(0.001)) && equals(v2, v3, T(0.001)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquat<T> a;\r\n\t\t\t\t\t\ta.set_from_euler_xzy(angles);\r\n\t\t\t\t\t\tvec3<T> angles2;\r\n\t\t\t\t\t\ta.get_as_euler_xzy(angles2);\r\n\t\t\t\t\t\tif (!equals(angles, angles2))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tquat<T> a2;\r\n\t\t\t\t\t\t\ta2.set_from_euler_xzy(angles2);\r\n\t\t\t\t\t\t\tvec3<T> v1 = rotate(aX * aZ * aY, tv);\r\n\t\t\t\t\t\t\tvec3<T> v2 = rotate(a, tv);\r\n\t\t\t\t\t\t\tvec3<T> v3 = rotate(a2, tv);\r\n\t\t\t\t\t\t\tBOOST_CHECK(equals(v1, v2, T(0.001)) && equals(v2, v3, T(0.001)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquat<T> a;\r\n\t\t\t\t\t\ta.set_from_euler_yxz(angles);\r\n\t\t\t\t\t\tvec3<T> angles2;\r\n\t\t\t\t\t\ta.get_as_euler_yxz(angles2);\r\n\t\t\t\t\t\tif (!equals(angles, angles2))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tquat<T> a2;\r\n\t\t\t\t\t\t\ta2.set_from_euler_yxz(angles2);\r\n\t\t\t\t\t\t\tvec3<T> v1 = rotate(aXY * aZ, tv);\r\n\t\t\t\t\t\t\tvec3<T> v2 = rotate(a, tv);\r\n\t\t\t\t\t\t\tvec3<T> v3 = rotate(a2, tv);\r\n\t\t\t\t\t\t\tBOOST_CHECK(equals(v1, v2, T(0.001)) && equals(v2, v3, T(0.001)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquat<T> a;\r\n\t\t\t\t\t\ta.set_from_euler_yzx(angles);\r\n\t\t\t\t\t\tvec3<T> angles2;\r\n\t\t\t\t\t\ta.get_as_euler_yzx(angles2);\r\n\t\t\t\t\t\tif (!equals(angles, angles2))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tquat<T> a2;\r\n\t\t\t\t\t\t\ta2.set_from_euler_yzx(angles2);\r\n\t\t\t\t\t\t\tvec3<T> v1 = rotate(aY * aZ * aX, tv);\r\n\t\t\t\t\t\t\tvec3<T> v2 = rotate(a, tv);\r\n\t\t\t\t\t\t\tvec3<T> v3 = rotate(a2, tv);\r\n\t\t\t\t\t\t\tBOOST_CHECK(equals(v1, v2, T(0.001)) && equals(v2, v3, T(0.001)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquat<T> a;\r\n\t\t\t\t\t\ta.set_from_euler_zxy(angles);\r\n\t\t\t\t\t\tvec3<T> angles2;\r\n\t\t\t\t\t\ta.get_as_euler_zxy(angles2);\r\n\t\t\t\t\t\tif (!equals(angles, angles2))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tquat<T> a2;\r\n\t\t\t\t\t\t\ta2.set_from_euler_zxy(angles2);\r\n\t\t\t\t\t\t\tvec3<T> v1 = rotate(aZ * aYX, tv);\r\n\t\t\t\t\t\t\tvec3<T> v2 = rotate(a, tv);\r\n\t\t\t\t\t\t\tvec3<T> v3 = rotate(a2, tv);\r\n\t\t\t\t\t\t\tBOOST_CHECK(equals(v1, v2, T(0.001)) && equals(v2, v3, T(0.001)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquat<T> a;\r\n\t\t\t\t\t\ta.set_from_euler_zyx(angles);\r\n\t\t\t\t\t\tvec3<T> angles2;\r\n\t\t\t\t\t\ta.get_as_euler_zyx(angles2);\r\n\t\t\t\t\t\tif (!equals(angles, angles2))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tquat<T> a2;\r\n\t\t\t\t\t\t\ta2.set_from_euler_zyx(angles2);\r\n\t\t\t\t\t\t\tvec3<T> v1 = rotate(aZ * aXY, tv);\r\n\t\t\t\t\t\t\tvec3<T> v2 = rotate(a, tv);\r\n\t\t\t\t\t\t\tvec3<T> v3 = rotate(a2, tv);\r\n\t\t\t\t\t\t\tBOOST_CHECK(equals(v1, v2, T(0.001)) && equals(v2, v3, T(0.001)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(TESTQUAT)\r\n{\r\n\ttestQuat<float>();\r\n\ttestQuat<double>();\r\n}\r\n\r\n}\r\n", "meta": {"hexsha": "347bb401b044b7ae94fb97ddbb305b41b85ed3ac", "size": 9256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qmath/test/test_quat.cpp", "max_stars_repo_name": "jeanleflambeur/silkopter", "max_stars_repo_head_hexsha": "cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T16:47:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T08:32:04.000Z", "max_issues_repo_path": "qmath/test/test_quat.cpp", "max_issues_repo_name": "jeanlemotan/silkopter", "max_issues_repo_head_hexsha": "cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 42.0, "max_issues_repo_issues_event_min_datetime": "2017-02-11T11:15:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T16:00:44.000Z", "max_forks_repo_path": "qmath/test/test_quat.cpp", "max_forks_repo_name": "jeanleflambeur/silkopter", "max_forks_repo_head_hexsha": "cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-10-15T05:46:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-11T17:40:36.000Z", "avg_line_length": 25.2896174863, "max_line_length": 90, "alphanum_fraction": 0.5122082973, "num_tokens": 3432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933535169629, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5624054042735972}}
{"text": "#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\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/**\n * @brief Check coefficients P->H, H->P\n *\n * @param polar_basis\n * @param hermite_basis\n */\ntemplate <typename H, typename P>\nvoid test1(const P& polar_basis, const H& hermite_basis)\n{\n  Polar2Hermite<P, H> P2H(polar_basis, hermite_basis);\n  P2H.exportmat(\"p2h.hdf5\");\n  unsigned int N = polar_basis.n_dofs();\n\n  std::vector<double> C(N, 1);\n\n  //  C[N-1] = 1.0;\n  std::vector<double> Ch(N, 0);\n  std::vector<double> Cb(N, 0);\n\n  P2H.to_hermite(Ch, C);\n  P2H.to_polar(Cb, Ch);\n\n  cout << setw(5) << \"index\" << setw(20) << \"c\" << setw(20) << \"T(P->H) T(H->P) c\" << setw(20)\n       << \"error\" << endl;\n  for (unsigned int i = 0; i < N; ++i) {\n    cout << setw(5) << i << \"\\t\" << setw(20) << Cb[i] << setw(20) << C[i] << setw(20)\n         << setprecision(6) << scientific << std::abs(Cb[i] - C[i]) << endl;\n  }\n  cout << \"finished\\n\";\n}\n\n/**\n * @brief Polar -> Hermite, evaluate at different points\n *\n * @param polar_basis\n * @param hermite_basis\n */\ntemplate <typename H, typename P>\nvoid test2(const P& polar_basis, const H& hermite_basis)\n{\n  Polar2Hermite<P, H> P2H(polar_basis, hermite_basis);\n\n  /*\n   *  Initialize polar coefficients\n   */\n  const unsigned int N = polar_basis.n_dofs();\n  // std::vector<double> C(N, 0);\n  // auto elem = SpectralBasisFactoryKS::make_elem(0, K-1, TRIG::COS);\n  // unsigned int idx = polar_basis.get_dof_index(elem.get_id());\n  // exp(-0.5 r^2)\n  // C[idx] = 1.0;\n\n  // if (idx  >= 2)\n  //   C[idx-2] = 1.0;\n  std::vector<double> C(N, 1.0);\n\n  /*\n   * Compute hermite coefficients\n   */\n  std::vector<double> Ch(N);\n  P2H.to_hermite(Ch, C);\n\n  // // output\n  // std::ofstream fout(\"transformed-coefficients\");\n  // for (size_t i = 0; i < Ch.size(); ++i) {\n  //   fout << Ch[i] << endl;\n  // }\n  // fout.close();\n\n  /*\n   * CHECK: do the hermite and polar series expansion match at evaluation\n   * points?\n   */\n  {\n    auto evalH = [&](const std::vector<double>& c, double x, double y) {\n      auto itc = c.begin();\n      double val = 0;\n      for (auto it = hermite_basis.begin(); it != hermite_basis.end(); ++it, ++itc) {\n        val += it->evaluate_weighted(x, y) * (*itc);\n      }\n      return val;\n    };\n\n    auto evalB = [&](const std::vector<double>& c, double phi, double r) {\n      auto itc = c.begin();\n      double val = 0;\n      for (auto it = polar_basis.begin(); it != polar_basis.end(); ++it, ++itc) {\n        val += it->evaluate_weighted(phi, r) * (*itc);\n      }\n      return val;\n    };\n\n    double r = 0.1;\n    const int n = 40;\n    for (int i = 0; i < n; ++i) {\n      double phi = 2 * PI * i / (n + 1);\n      double x = r * cos(phi);\n      double y = r * sin(phi);\n\n      const double fB = evalB(C, phi, r);\n      const double fH = evalH(Ch, x, y);\n      cout << setprecision(6) << scientific << setw(20) << fB << \"\\t\" << setw(20) << fH << \"\\t\"\n           << setw(20) << std::abs(fB - fH) << endl;\n    }\n    r = 2.5;\n    cout << \"r = \" << r << endl;\n    for (int i = 0; i < n; ++i) {\n      double phi = 2 * PI * i / (n + 1);\n      double x = r * cos(phi);\n      double y = r * sin(phi);\n\n      const double fB = evalB(C, phi, r);\n      const double fH = evalH(Ch, x, y);\n      cout << setprecision(6) << scientific << setw(20) << fB << \"\\t\" << setw(20) << fH << \"\\t\"\n           << setw(20) << std::abs(fB - fH) << endl;\n    }\n  }\n}\n\nint main(int argc, char* argv[])\n{\n  int K;\n  po::options_description options(\"options\");\n  options.add_options()\n      (\"help\", \"show help message\")\n      (\"nK,K\", po::value<int>(&K)->default_value(10), \"K\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  cout << \"using \\n\\tK: \" << K << \"\\n\";\n\n  if (vm.count(\"help\")) {\n    cout << options << \"\\n\";\n    return 0;\n  }\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  typedef typename SpectralBasisFactoryHN::basis_type hermite_basis_t;\n  hermite_basis_t hermite_basis;\n  SpectralBasisFactoryHN::create(hermite_basis, K, 2);\n  SpectralBasisFactoryHN::write_basis_descriptor(hermite_basis, \"hermite_basis.desc\");\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 1: (P->H) -> (H->P) show coefficients\\n\";\n  test1(polar_basis, hermite_basis);\n\n  cout << \"\\n--------------------\\n\";\n  cout << \"Test 2: (P->H) and compare evaluation at point of c_H, c_P\\n\";\n  test2(polar_basis, hermite_basis);\n\n  return 0;\n}\n", "meta": {"hexsha": "fb1bcf7c0149fed0db0645c427daefcc23267c7a", "size": 5354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/polar2hermite/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/polar2hermite/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/polar2hermite/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": 28.9405405405, "max_line_length": 95, "alphanum_fraction": 0.6004856182, "num_tokens": 1705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5624053982360667}}
{"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 <ceres/jet.h>\n#include <ceres/rotation.h>\n#include <geometry/camera.h>\n#include <gmock/gmock.h>\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <random>\n#include <unsupported/Eigen/AutoDiff>\n\nclass FunctionFixture : public ::testing::Test {\n public:\n  /* Evaluates the following function :\n   *\n   * f = a * exp( b - c * log( d * (e/x - f)^2 ) )\n   *\n   * Decomposed as follows :\n   *\n   * f1 = a * exp(x)\n   * f2 = b - c * log(x)\n   * f3 = d * x^2\n   * f4 = e/x - f\n   * f = f1(f2(f3(f4))) */\n\n  struct F1 : public geometry::Functor<1, 1, 1> {\n    template <class T>\n    static void Apply(const T* in, const T* p, T* out) {\n      out[0] = p[0] * exp(in[0]);\n    }\n    template <class T, bool COMP_PARAM>\n    static void ForwardDerivatives(const T* in, const T* p, T* out,\n                                   T* jacobian) {\n      jacobian[0] = p[0] * exp(in[0]);\n      if (COMP_PARAM) {\n        jacobian[1] = exp(in[0]);\n      }\n      Apply(in, p, out);\n    }\n  };\n  struct F2 : public geometry::Functor<1, 2, 1> {\n    template <class T>\n    static void Apply(const T* in, const T* p, T* out) {\n      out[0] = p[0] - p[1] * log(in[0]);\n    }\n    template <class T, bool COMP_PARAM>\n    static void ForwardDerivatives(const T* in, const T* p, T* out,\n                                   T* jacobian) {\n      jacobian[0] = -p[1] / in[0];\n      if (COMP_PARAM) {\n        jacobian[1] = T(1.0);\n        jacobian[2] = -log(in[0]);\n      }\n      Apply(in, p, out);\n    }\n  };\n  struct F3 : public geometry::Functor<1, 1, 1> {\n    template <class T>\n    static void Apply(const T* in, const T* p, T* out) {\n      out[0] = p[0] * in[0] * in[0];\n    }\n    template <class T, bool COMP_PARAM>\n    static void ForwardDerivatives(const T* in, const T* p, T* out,\n                                   T* jacobian) {\n      jacobian[0] = T(2.0) * p[0] * in[0];\n      if (COMP_PARAM) {\n        jacobian[1] = in[0] * in[0];\n      }\n      Apply(in, p, out);\n    }\n  };\n  struct F4 : public geometry::Functor<1, 2, 1> {\n    template <class T>\n    static void Apply(const T* in, const T* p, T* out) {\n      out[0] = p[0] / in[0] - p[1];\n    }\n    template <class T, bool COMP_PARAM>\n    static void ForwardDerivatives(const T* in, const T* p, T* out,\n                                   T* jacobian) {\n      jacobian[0] = -p[0] / (in[0] * in[0]);\n      if (COMP_PARAM) {\n        jacobian[1] = T(1.0) / in[0];\n        jacobian[2] = -T(1.0);\n      }\n      Apply(in, p, out);\n    }\n  };\n};\n\nTEST_F(FunctionFixture, EvaluatesCorrectly) {\n  double in[] = {1.0};\n\n  /* Parameters needs to be stored in the order of evaluation :\n   * params f4 |params f3 | params f2 | params f1 */\n  double parameters[] = {4.0, 2.0, 3.0, 1.0, 2.0, 3.0};\n  double evaluated = 0;\n  geometry::ComposeFunctions<double, F1, F2, F3, F4>(in, parameters,\n                                                     &evaluated);\n\n  const double expected =\n      3.0 * exp(1.0 - 2.0 * log(3.0 * std::pow(4.0 / in[0] - 2.0, 2)));\n  ASSERT_NEAR(expected, evaluated, 1e-20);\n}\n\nTEST_F(FunctionFixture, EvaluatesDerivativesCorrectly) {\n  double in[] = {1.0};\n\n  /* Parameters needs to be stored in the order of evaluation :\n   * params f4 |params f3 | params f2 | params f1 */\n  double parameters[] = {4.0, 2.0, 3.0, 1.0, 2.0, 3.0};\n  double evaluated = 0;\n  double jacobian[7];\n  geometry::ComposeForwardDerivatives<double, true, F1, F2, F3, F4>(\n      in, parameters, &evaluated, &jacobian[0]);\n\n  const double expected =\n      3.0 * exp(1.0 - 2.0 * log(3.0 * std::pow(4.0 / in[0] - 2.0, 2)));\n  ASSERT_NEAR(expected, evaluated, 1e-20);\n\n  /* Jacobian ordering : d_input | d_parameters */\n  typedef Eigen::AutoDiffScalar<VecXd> AScalar;\n  VecX<AScalar> eval_adiff(1);\n  eval_adiff(0).value() = in[0];\n  eval_adiff(0).derivatives() = VecXd::Unit(7, 0);\n  VecX<AScalar> parameters_adiff(6);\n  for (int i = 0; i < 6; ++i) {\n    parameters_adiff[i].value() = parameters[i];\n    parameters_adiff[i].derivatives() = VecXd::Unit(7, i + 1);\n  }\n\n  AScalar evaluated_addif;\n  geometry::ComposeFunctions<AScalar, F1, F2, F3, F4>(\n      eval_adiff.data(), parameters_adiff.data(), &evaluated_addif);\n  for (int i = 0; i < 7; ++i) {\n    ASSERT_NEAR(evaluated_addif.derivatives()(i), jacobian[i], 1e-20);\n  }\n}\n\nclass PoseFixture : public ::testing::Test {\n public:\n  const double point[3] = {1.0, 2.0, 3.0};\n  const double rt[6] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6};\n};\n\nTEST_F(PoseFixture, EvaluatesCorrectly) {\n  double transformed[3] = {0., 0., 0.};\n\n  /* Parameters order : angle_axis | pose_center */\n  geometry::PoseFunctor::Forward(point, rt, transformed);\n\n  /* Use Ceres as groundtruth */\n  const double pt[3] = {\n      point[0] - rt[geometry::PoseFunctor::Tx],\n      point[1] - rt[geometry::PoseFunctor::Ty],\n      point[2] - rt[geometry::PoseFunctor::Tz],\n  };\n  const double Rt[3] = {-rt[geometry::PoseFunctor::Rx],\n                        -rt[geometry::PoseFunctor::Ry],\n                        -rt[geometry::PoseFunctor::Rz]};\n  double expected[] = {1., 1., 1.};\n  ceres::AngleAxisRotatePoint(Rt, pt, expected);\n\n  for (int i = 0; i < 3; ++i) {\n    ASSERT_NEAR(expected[i], transformed[i], 1e-15);\n  }\n}\n\nTEST_F(PoseFixture, EvaluatesAllDerivativesCorrectly) {\n  typedef Eigen::AutoDiffScalar<VecXd> AScalar;\n\n  VecX<AScalar> point_adiff(3);\n  constexpr int size = 9;\n\n  /* Autodifferentaied as a reference */\n  for (int i = 0; i < 3; ++i) {\n    point_adiff(i).value() = point[i];\n    point_adiff(i).derivatives() = VecXd::Unit(size, i);\n  }\n  VecX<AScalar> rt_adiff(6);\n  for (int i = 0; i < 6; ++i) {\n    rt_adiff[i].value() = rt[i];\n    rt_adiff[i].derivatives() = VecXd::Unit(size, 3 + i);\n  }\n  VecX<AScalar> expected_adiff(3);\n  geometry::PoseFunctor::Forward(point_adiff.data(), rt_adiff.data(),\n                                 expected_adiff.data());\n\n  /* Analytic version */\n  double transformed[] = {0., 0., 0.};\n  double jacobian[size * 3];\n  geometry::PoseFunctor::ForwardDerivatives<double, true>(\n      &point[0], &rt[0], &transformed[0], &jacobian[0]);\n\n  for (int i = 0; i < 3; ++i) {\n    for (int j = 0; j < size; ++j) {\n      ASSERT_NEAR(expected_adiff(i).derivatives()(j), jacobian[i * size + j],\n                  1e-15);\n    }\n  }\n}\n\nTEST_F(PoseFixture, EvaluatesPointDerivativesCorrectly) {\n  typedef Eigen::AutoDiffScalar<VecXd> AScalar;\n\n  VecX<AScalar> point_adiff(3);\n\n  /* Autodifferentaied as a reference */\n  for (int i = 0; i < 3; ++i) {\n    point_adiff(i).value() = point[i];\n    point_adiff(i).derivatives() = VecXd::Unit(3, i);\n  }\n  VecX<AScalar> rt_adiff(6);\n  for (int i = 0; i < 6; ++i) {\n    rt_adiff[i].value() = rt[i];\n    rt_adiff[i].derivatives() = Vec3d::Zero();\n  }\n  VecX<AScalar> expected_adiff(3);\n  geometry::PoseFunctor::Forward(point_adiff.data(), rt_adiff.data(),\n                                 expected_adiff.data());\n\n  /* Analytic version */\n  double transformed[] = {0., 0., 0.};\n  double jacobian[9];\n  geometry::PoseFunctor::ForwardDerivatives<double, false>(\n      &point[0], &rt[0], &transformed[0], &jacobian[0]);\n\n  for (int i = 0; i < 3; ++i) {\n    for (int j = 0; j < 3; ++j) {\n      ASSERT_NEAR(expected_adiff(i).derivatives()(j), jacobian[i * 3 + j],\n                  1e-15);\n    }\n  }\n}\n\nclass CameraDerivativesFixture : public ::testing::Test {\n public:\n  CameraDerivativesFixture() {\n    distortion.resize(2);\n    distortion << -0.1, 0.03;\n    distortion_brown.resize(5);\n    distortion_brown << -0.1, 0.03, 0.001, 0.001, 0.002;\n    distortion_fisheye.resize(4);\n    distortion_fisheye << -0.1, 0.03, 0.001, 0.005;\n    distortion_fisheye62.resize(8);\n    distortion_fisheye62 << -0.1, 0.03, 0.001, 0.005, 0.02, 0.001, 0.0007,\n        -0.01;\n    distortion_radial << 0.1, 0.03;\n    principal_point << 0.1, -0.05;\n\n    for (int i = 0; i < 3; ++i) {\n      point_adiff[i].value() = point[i] = (i + 1) / 10.0;\n    }\n  }\n\n  template <class MAT>\n  void RunJacobianEval(const geometry::Camera& camera,\n                       geometry::ProjectionType projection, MAT* jacobian) {\n    const VecXd camera_params = camera.GetParametersValues();\n    const int size_params = 3 + camera_params.size();\n\n    // Prepare Eigen's Autodiff structures\n    for (int i = 0; i < 3; ++i) {\n      point_adiff[i].derivatives() = VecXd::Unit(size_params, i);\n    }\n    camera_adiff.resize(camera_params.size());\n    for (int i = 0; i < camera_params.size(); ++i) {\n      camera_adiff(i).value() = camera_params(i);\n      camera_adiff(i).derivatives() = VecXd::Unit(size_params, 3 + i);\n    }\n\n    // Run project with Autodiff types to get expected jacobian\n    geometry::Dispatch<geometry::ProjectFunction>(\n        projection, point_adiff, camera_adiff.data(), projection_expected);\n\n    // Analytical derivatives\n    geometry::Dispatch<geometry::ProjectDerivativesFunction>(\n        projection, point, camera_params.data(), projected, jacobian->data());\n  }\n\n  template <class MAT>\n  void CheckJacobian(const MAT& jacobian, int size_params) {\n    const double eps = 1e-12;\n    for (int i = 0; i < 2; ++i) {\n      for (int j = 0; j < size_params; ++j) {\n        ASSERT_NEAR(projection_expected[i].derivatives()(j), jacobian(i, j),\n                    eps);\n      }\n      ASSERT_NEAR(projection_expected[i].value(), projected[i], eps);\n    }\n  }\n\n  const double focal{0.4};\n  const double new_ar{0.9};\n\n  VecXd distortion;\n  VecXd distortion_brown;\n  VecXd distortion_fisheye;\n  VecXd distortion_fisheye62;\n  Vec2d distortion_radial;\n  Vec2d principal_point;\n\n  double point[3];\n  typedef Eigen::AutoDiffScalar<VecXd> AScalar;\n  AScalar point_adiff[3];\n  VecX<AScalar> camera_adiff;\n\n  AScalar projection_expected[2];\n  double projected[2];\n};\n\nTEST_F(CameraDerivativesFixture, ComputePerspectiveAnalyticalDerivatives) {\n  const geometry::Camera camera =\n      geometry::Camera::CreatePerspectiveCamera(focal, -0.1, 0.01);\n\n  const VecXd camera_params = camera.GetParametersValues();\n  const int size_params = 3 + camera_params.size();\n\n  Eigen::Matrix<double, 2, 6, Eigen::RowMajor> jacobian;\n  RunJacobianEval(camera, geometry::ProjectionType::PERSPECTIVE, &jacobian);\n  CheckJacobian(jacobian, size_params);\n}\n\nTEST_F(CameraDerivativesFixture, ComputeFisheyeAnalyticalDerivatives) {\n  const geometry::Camera camera =\n      geometry::Camera::CreateFisheyeCamera(focal, -0.1, 0.01);\n\n  const VecXd camera_params = camera.GetParametersValues();\n  const int size_params = 3 + camera_params.size();\n\n  Eigen::Matrix<double, 2, 6, Eigen::RowMajor> jacobian;\n  RunJacobianEval(camera, geometry::ProjectionType::FISHEYE, &jacobian);\n  CheckJacobian(jacobian, size_params);\n}\n\nTEST_F(CameraDerivativesFixture, ComputeFisheyeOpencvAnalyticalDerivatives) {\n  const geometry::Camera camera = geometry::Camera::CreateFisheyeOpencvCamera(\n      focal, new_ar, principal_point, distortion_fisheye);\n\n  const VecXd camera_params = camera.GetParametersValues();\n  const int size_params = 3 + camera_params.size();\n\n  Eigen::Matrix<double, 2, 11, Eigen::RowMajor> jacobian;\n  RunJacobianEval(camera, geometry::ProjectionType::FISHEYE_OPENCV, &jacobian);\n  CheckJacobian(jacobian, size_params);\n}\n\nTEST_F(CameraDerivativesFixture, ComputeFisheye62AnalyticalDerivatives) {\n  const geometry::Camera camera = geometry::Camera::CreateFisheye62Camera(\n      focal, 1.0, principal_point, distortion_fisheye62);\n\n  const VecXd camera_params = camera.GetParametersValues();\n  const int size_params = 3 + camera_params.size();\n\n  Eigen::Matrix<double, 2, 15, Eigen::RowMajor> jacobian;\n  RunJacobianEval(camera, geometry::ProjectionType::FISHEYE62, &jacobian);\n  CheckJacobian(jacobian, size_params);\n}\n\nTEST_F(CameraDerivativesFixture, ComputeRadialAnalyticalDerivatives) {\n  const geometry::Camera camera = geometry::Camera::CreateRadialCamera(\n      focal, 1.0, principal_point, distortion_radial);\n\n  const VecXd camera_params = camera.GetParametersValues();\n  const int size_params = 3 + camera_params.size();\n\n  Eigen::Matrix<double, 2, 9, Eigen::RowMajor> jacobian;\n  RunJacobianEval(camera, geometry::ProjectionType::RADIAL, &jacobian);\n  CheckJacobian(jacobian, size_params);\n}\n\nTEST_F(CameraDerivativesFixture, ComputeSimpleRadialAnalyticalDerivatives) {\n  const geometry::Camera camera = geometry::Camera::CreateSimpleRadialCamera(\n      focal, 1.0, principal_point, distortion_radial[0]);\n\n  const VecXd camera_params = camera.GetParametersValues();\n  const int size_params = 3 + camera_params.size();\n\n  Eigen::Matrix<double, 2, 8, Eigen::RowMajor> jacobian;\n  RunJacobianEval(camera, geometry::ProjectionType::SIMPLE_RADIAL, &jacobian);\n  CheckJacobian(jacobian, size_params);\n}\n\nTEST_F(CameraDerivativesFixture, ComputeBrownAnalyticalDerivatives) {\n  const geometry::Camera camera = geometry::Camera::CreateBrownCamera(\n      focal, new_ar, principal_point, distortion_brown);\n\n  const VecXd camera_params = camera.GetParametersValues();\n  const int size_params = 3 + camera_params.size();\n\n  Eigen::Matrix<double, 2, 12, Eigen::RowMajor> jacobian;\n  RunJacobianEval(camera, geometry::ProjectionType::BROWN, &jacobian);\n  CheckJacobian(jacobian, size_params);\n}\n\nTEST_F(CameraDerivativesFixture, ComputeSphericalAnalyticalDerivatives) {\n  const geometry::Camera camera = geometry::Camera::CreateSphericalCamera();\n\n  const VecXd camera_params = camera.GetParametersValues();\n  const int size_params = 3;\n\n  Eigen::Matrix<double, 2, 3, Eigen::RowMajor> jacobian;\n  RunJacobianEval(camera, geometry::ProjectionType::SPHERICAL, &jacobian);\n  CheckJacobian(jacobian, size_params);\n}\n\nTEST_F(CameraDerivativesFixture, ComputeDualAnalyticalDerivatives) {\n  const geometry::Camera camera = geometry::Camera::Camera::CreateDualCamera(\n      0.5, focal, distortion[0], distortion[1]);\n\n  const VecXd camera_params = camera.GetParametersValues();\n  const int size_params = 3 + camera_params.size();\n\n  Eigen::Matrix<double, 2, 7, Eigen::RowMajor> jacobian;\n  RunJacobianEval(camera, geometry::ProjectionType::DUAL, &jacobian);\n  CheckJacobian(jacobian, size_params);\n}\n", "meta": {"hexsha": "c5e5dbd5ed3ba04535e6961b097ceb7129c7bc99", "size": 13943, "ext": "cc", "lang": "C++", "max_stars_repo_path": "opensfm/src/geometry/test/camera_functions_test.cc", "max_stars_repo_name": "lioncorpo/sfm.lion-judge-corporation", "max_stars_repo_head_hexsha": "95fb11bff263c3faab62269cc907eec18b527e22", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2535.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T17:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:12:43.000Z", "max_issues_repo_path": "opensfm/src/geometry/test/camera_functions_test.cc", "max_issues_repo_name": "Pandinosaurus/OpenSfM", "max_issues_repo_head_hexsha": "b892ba9fd5e7fd6c7a9e3c81edddca80f71c1cd5", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 752.0, "max_issues_repo_issues_event_min_datetime": "2015-01-11T22:15:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:23:47.000Z", "max_forks_repo_path": "extractor/mapping/OpenSfM/opensfm/src/geometry/test/camera_functions_test.cc", "max_forks_repo_name": "LukasBommes/PV-Hawk", "max_forks_repo_head_hexsha": "af07a5e5690326837d1e9b26bdbb32f5582e89fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 780.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T15:06:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T20:47:26.000Z", "avg_line_length": 33.5168269231, "max_line_length": 79, "alphanum_fraction": 0.6440507782, "num_tokens": 4317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6959583313396338, "lm_q1q2_score": 0.5623811095544485}}
{"text": "//=======================================================================\n// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file generalised_assignment_long_test.cpp\n * @brief\n * @author Piotr Wygocki\n * @version 1.0\n * @date 2013-02-15\n */\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/read_gen_ass.hpp\"\n#include \"test_utils/get_test_dir.hpp\"\n#include \"test_utils/system.hpp\"\n\n#include \"paal/data_structures/components/components_replace.hpp\"\n#include \"paal/data_structures/metric/basic_metrics.hpp\"\n#include \"paal/iterative_rounding/generalised_assignment/generalised_assignment.hpp\"\n#include \"paal/utils/assign_updates.hpp\"\n#include \"paal/utils/parse_file.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n\nusing namespace paal::ir;\nusing namespace paal;\n\ntemplate <typename Machines, typename JobsToMachines, typename Times,\n        typename MachineBounds, typename Jobs>\nvoid check_result(IRResult result, const Machines & machines,\n        const JobsToMachines & jobs_to_machines, const Times & times,\n        const MachineBounds & machines_bounds, const Jobs & jobs, int opt) {\n\n    BOOST_CHECK(result.first == lp::OPTIMAL);\n\n    std::vector<int> machines_load(machines.size(), 0);\n    for (auto jm : jobs_to_machines) {\n        LOGLN(\"job \" << jm.first << \" assigned to machine \" << jm.second);\n        machines_load[jm.second] += times(jm.first, jm.second);\n    }\n    double approximation_ratio = 1.;\n    for (int m : machines) {\n        BOOST_CHECK(machines_load[m] <= 2 * machines_bounds[m]);\n        assign_max(approximation_ratio, double(machines_load[m]) / double(machines_bounds[m]));\n    }\n\n    for (int j : jobs) {\n        BOOST_CHECK(jobs_to_machines.find(j) != jobs_to_machines.end());\n    }\n    BOOST_CHECK(std::abs(std::round(*(result.second))-*(result.second)) < 1e-6);\n    int c = std::round(*(result.second));\n    LOGLN(\"cost \" << c);\n    BOOST_CHECK(c <= opt);\n    LOGLN(std::setprecision(10) << \"APPROXIMATION RATIO: \" << approximation_ratio << \" cost / opt = \" << double(c) / double(opt));\n}\n\nBOOST_AUTO_TEST_CASE(generalised_assignment_long) {\n    std::string test_dir = paal::system::get_test_data_dir(\"GENERALISED_ASSIGNMENT\");\n    using paal::system::build_path;\n\n    parse(build_path(test_dir, \"gapopt.txt\"), [&](const std::string & fname, std::istream & is_test_cases) {\n        int opt;\n        int number_of_cases;\n\n        is_test_cases >> number_of_cases;\n\n        LOGLN(fname << \" \" << number_of_cases);\n        std::ifstream ifs(build_path(test_dir, \"/cases/\" + fname + \".txt\"));\n        assert(ifs.good());\n\n        int num;\n        ifs >> num;\n        assert(num == number_of_cases);\n        for(int i = 0; i < number_of_cases; ++i) {\n            is_test_cases >> opt;\n            LOGLN(\"case \" << i << \" opt \" << opt);\n\n            paal::M costs;\n            paal::M times;\n            std::vector<int> machines_bounds;\n            boost::integer_range<int> machines(0,0);\n            boost::integer_range<int> jobs(0,0);\n            paal::read_gen_ass(ifs, costs, times, machines_bounds, machines, jobs);\n            auto Tf = [&](int i){return machines_bounds[i];};\n            {\n                LOGLN(\"Unlimited relaxations\");\n                std::unordered_map<int, int> jobs_to_machines;\n                auto result = generalised_assignment_iterative_rounding(\n                    machines.begin(), machines.end(),\n                    jobs.begin(), jobs.end(),\n                    costs, times, Tf, std::inserter(jobs_to_machines, jobs_to_machines.begin()));\n                check_result(result, machines, jobs_to_machines, times, machines_bounds, jobs, opt);\n            }\n            {\n                LOGLN(\"Relaxations limit = 1/iter\");\n                std::unordered_map<int, int> jobs_to_machines;\n                ir::ga_ir_components<> comps;\n                auto components =\n                    paal::data_structures::replace<ir::RelaxationsLimit>(\n                        ir::relaxations_limit_condition(), comps);\n                auto result = generalised_assignment_iterative_rounding(\n                    machines.begin(), machines.end(),\n                    jobs.begin(), jobs.end(),\n                    costs, times, Tf, std::inserter(jobs_to_machines, jobs_to_machines.begin()),\n                    components);\n                check_result(result, machines, jobs_to_machines, times, machines_bounds, jobs, opt);\n            }\n        }\n        int MAX_LINE = 256;\n        char buf[MAX_LINE];\n        is_test_cases.getline(buf, MAX_LINE);\n    });\n}\n", "meta": {"hexsha": "4583e91808e5f8c66e2e9bde7d2bd18d1eec6bb4", "size": 4800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/iterative_rounding/generalised_assignment/generalised_assignment_long_test.cpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/iterative_rounding/generalised_assignment/generalised_assignment_long_test.cpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/iterative_rounding/generalised_assignment/generalised_assignment_long_test.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 39.0243902439, "max_line_length": 130, "alphanum_fraction": 0.60375, "num_tokens": 1096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5623811031207606}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <geometry_test_common.hpp>\n\n#include <boost/concept_check.hpp>\n\n#include <boost/geometry/extensions/gis/geographic/strategies/andoyer.hpp>\n\n#include <boost/geometry/strategies/strategies.hpp>\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <test_common/test_point.hpp>\n\n#ifdef HAVE_TTMATH\n#  include <boost/geometry/extensions/contrib/ttmath_stub.hpp>\n#endif\n\n\n\ntemplate <typename P1, typename P2>\nvoid test_andoyer(double lon1, double lat1, double lon2, double lat2, double expected_km)\n{\n    // Set radius type, but for integer coordinates we want to have floating point radius type\n    typedef typename bg::promote_floating_point\n        <\n            typename bg::coordinate_type<P1>::type\n        >::type rtype;\n\n    typedef bg::strategy::distance::andoyer<rtype> andoyer_type;\n\n    BOOST_CONCEPT_ASSERT\n        ( \n            (bg::concept::PointDistanceStrategy<andoyer_type, P1, P2>) \n        );\n\n    andoyer_type andoyer;\n    typedef typename bg::strategy::distance\n        ::services::return_type<andoyer_type, P1, P2>::type return_type;\n\n\n    P1 p1, p2;\n\n    bg::assign_values(p1, lon1, lat1);\n    bg::assign_values(p2, lon2, lat2);\n\n    BOOST_CHECK_CLOSE(andoyer.apply(p1, p2), return_type(1000.0 * expected_km), 0.001);\n}\n\ntemplate <typename P1, typename P2>\nvoid test_all()\n{\n    test_andoyer<P1, P2>(0, 90, 1, 80, 1116.814237); // polar\n    test_andoyer<P1, P2>(4, 52, 4, 52, 0.0); // no point difference\n    test_andoyer<P1, P2>(4, 52, 3, 40, 1336.039890); // normal case\n\n    /* SQL Server gives:\n        1116.82586908528, 0, 1336.02721932545\n\n       with:\nSELECT 0.001 * geography::STGeomFromText('POINT(0 90)', 4326).STDistance(geography::STGeomFromText('POINT(1 80)', 4326))\nunion SELECT 0.001 * geography::STGeomFromText('POINT(4 52)', 4326).STDistance(geography::STGeomFromText('POINT(4 52)', 4326))\nunion SELECT 0.001 * geography::STGeomFromText('POINT(4 52)', 4326).STDistance(geography::STGeomFromText('POINT(3 40)', 4326))\n     */\n}\n\ntemplate <typename P>\nvoid test_all()\n{\n    test_all<P, P>();\n}\n\nint test_main(int, char* [])\n{\n    //test_all<float[2]>();\n    //test_all<double[2]>();\n    test_all<bg::model::point<int, 2, bg::cs::geographic<bg::degree> > >();\n    test_all<bg::model::point<float, 2, bg::cs::geographic<bg::degree> > >();\n    test_all<bg::model::point<double, 2, bg::cs::geographic<bg::degree> > >();\n\n#if defined(HAVE_TTMATH)\n    test_all<bg::model::point<ttmath::Big<1,4>, 2, bg::cs::geographic<bg::degree> > >();\n    test_all<bg::model::point<ttmath_big, 2, bg::cs::geographic<bg::degree> > >();\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "80e971bc2cae85bab2e26775e5408813e33ea14f", "size": 3226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/extensions/test/gis/latlong/andoyer.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "libs/geometry/extensions/test/gis/latlong/andoyer.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "libs/geometry/extensions/test/gis/latlong/andoyer.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 32.26, "max_line_length": 126, "alphanum_fraction": 0.6924984501, "num_tokens": 994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5623810993628119}}
{"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": "/* Cam Mannett 2020\n *\n * See LICENSE file\n */\n\n#include \"malbolge/math/ipow.hpp\"\n#include \"malbolge/traits.hpp\"\n\n#include \"test_helpers.hpp\"\n\n#include <boost/mp11.hpp>\n\n#include <utility>\n\nusing namespace malbolge;\n\nBOOST_AUTO_TEST_SUITE(ipow_suite)\n\nBOOST_AUTO_TEST_CASE(squares)\n{\n    using data_set = std::tuple<\n        std::pair<traits::integral_constant<0u>,  traits::integral_constant<1u>>,\n        std::pair<traits::integral_constant<1u>,  traits::integral_constant<2u>>,\n        std::pair<traits::integral_constant<2u>,  traits::integral_constant<4u>>,\n        std::pair<traits::integral_constant<3u>,  traits::integral_constant<8u>>,\n        std::pair<traits::integral_constant<4u>,  traits::integral_constant<16u>>,\n        std::pair<traits::integral_constant<10u>, traits::integral_constant<1024u>>\n    >;\n\n    auto f = [](auto expo, auto result) {\n        constexpr auto r = math::ipow<std::uint32_t, 2u, decltype(expo)::value>();\n        BOOST_CHECK_EQUAL(r, decltype(result)::value);\n    };\n\n    test::data_set(f, data_set{});\n}\n\nBOOST_AUTO_TEST_CASE(cubes)\n{\n    using data_set = std::tuple<\n        std::pair<traits::integral_constant<0u>,  traits::integral_constant<1u>>,\n        std::pair<traits::integral_constant<1u>,  traits::integral_constant<3u>>,\n        std::pair<traits::integral_constant<2u>,  traits::integral_constant<9u>>,\n        std::pair<traits::integral_constant<3u>,  traits::integral_constant<27u>>,\n        std::pair<traits::integral_constant<4u>,  traits::integral_constant<81u>>,\n        std::pair<traits::integral_constant<10u>, traits::integral_constant<59049u>>\n    >;\n\n    auto f = [](auto expo, auto result) {\n        constexpr auto r = math::ipow<std::uint32_t, 3u, decltype(expo)::value>();\n        BOOST_CHECK_EQUAL(r, decltype(result)::value);\n    };\n\n    test::data_set(f, data_set{});\n}\n\nBOOST_AUTO_TEST_CASE(cubes_runtime)\n{\n    auto f = [](auto expo, auto result) {\n        const auto r = math::ipow<std::uint32_t>(3u, expo);\n        BOOST_CHECK_EQUAL(r, result);\n    };\n\n    test::data_set(\n        f,\n        {\n            std::tuple{0u, 1u},\n            std::tuple{1u, 3u},\n            std::tuple{2u, 9u},\n            std::tuple{3u, 27u},\n            std::tuple{4u, 81u},\n            std::tuple{10u, 59049u},\n        }\n    );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "04e41ed99f5ef069691736ebcf568d5b2cb4689c", "size": 2314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/ipow_test.cpp", "max_stars_repo_name": "cmannett85/malbolge", "max_stars_repo_head_hexsha": "a3216af7b029d1b942af1dd3678d43fbb5d3c017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-13T12:34:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T12:34:27.000Z", "max_issues_repo_path": "test/math/ipow_test.cpp", "max_issues_repo_name": "cmannett85/malbolge", "max_issues_repo_head_hexsha": "a3216af7b029d1b942af1dd3678d43fbb5d3c017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T07:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-22T15:30:20.000Z", "max_forks_repo_path": "test/math/ipow_test.cpp", "max_forks_repo_name": "cmannett85/malbolge", "max_forks_repo_head_hexsha": "a3216af7b029d1b942af1dd3678d43fbb5d3c017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-13T12:34:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T12:34:30.000Z", "avg_line_length": 29.6666666667, "max_line_length": 84, "alphanum_fraction": 0.6369922213, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5623743227399102}}
{"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": "#ifndef CUAUV_SIM_GEOMETRY_H\n#define CUAUV_SIM_GEOMETRY_H\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace cuauv {\nnamespace fishbowl {\n\n/**\n * sphere_sphere_sweep calculates the normalized first and second times of\n * intersection of two spheres. The times are expressed in terms of the given\n * positions, and are as if the distances traveled by the spheres were covered\n * in unit time.\n * @param ar Radius of the first sphere.\n * @param ax0 Previous position of the first sphere.\n * @param ax1 Current position of the first sphere.\n * @param br Radius of the second sphere.\n * @param bx0 Previous position of the second sphere.\n * @param bx1 Current position of the second sphere.\n * @param t0 Will hold the (normalized) time of the first intersection, if any.\n *           If no intersection occurs, the value is undefined.\n * @param t1 Will hold the time of the second intersection.\n * @returns True iff an intersection occurs.\n * @see http://www.gamasutra.com/view/feature/131790/simple_intersection_tests_for_games.php?page=2\n */\nbool sphere_sphere_sweep(double ar, const Eigen::Vector3d& ax0, const Eigen::Vector3d& ax1,\n                         double br, const Eigen::Vector3d& bx0, const Eigen::Vector3d& bx1,\n                         double& t0, double& t1);\n\ndouble line_distance(const Eigen::Vector3d& x0, const Eigen::Vector3d& x1, const Eigen::Vector3d& x);\n\n/**\n * swing_twist decomposes a quaternion into swing and twist components.  The\n * swing twist component is a rotation around the twist axis, while the swing\n * component is a rotation around a direction vector perpendicular to the twist\n * axis.\n * The original quaternion q = swing * twist.\n * @param q The quaternion to decompose.\n * @param vt The twist axis.\n * @param swing The swing component of the rotation.\n * @param twist The twist component of the rotation.\n * @see http://www.alinenormoyle.com/weblog/?p=726.\n * @see \"Swing-twist decomposition in Clifford algebra\" (Dobrowolski, 2015).\n */\nvoid swing_twist(const Eigen::Quaterniond& q, const Eigen::Vector3d& vt,\n                 Eigen::Quaterniond& swing, Eigen::Quaterniond& twist);\n\nEigen::Vector3d quat_to_euler(Eigen::Quaterniond q);\nEigen::Quaterniond euler_to_quat(double h, double p, double r);\n\n} // namespace fishbowl\n} // namespace cuauv\n\n#endif // CUAUV_SIM_GEOMETRY_H\n", "meta": {"hexsha": "0e1f26882d3c9625b3b5856344060f5f6dd2ec2a", "size": 2331, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fishbowl/geometry.hpp", "max_stars_repo_name": "cuauv/software", "max_stars_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T18:04:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T09:04:02.000Z", "max_issues_repo_path": "fishbowl/geometry.hpp", "max_issues_repo_name": "cuauv/software", "max_issues_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-03T05:13:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-03T06:19:39.000Z", "max_forks_repo_path": "fishbowl/geometry.hpp", "max_forks_repo_name": "cuauv/software", "max_forks_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T17:29:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T14:15:12.000Z", "avg_line_length": 41.625, "max_line_length": 101, "alphanum_fraction": 0.7323037323, "num_tokens": 574, "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   Copyright (C) 2015-2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#include <cmath>\n#include <gtest/gtest.h>\n#include <boost/math/differentiation/autodiff.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"ising/mp_wrapper.hpp\"\n#include \"ising/free_energy/common.hpp\"\n#include \"ising/free_energy/square.hpp\"\n\nusing namespace boost::multiprecision;\nusing namespace ising::free_energy;\n\nTEST(IsingFreeEnergy, Square0) {\n  typedef double real_t;\n  auto Jx = convert<real_t>(\"1.5\");\n  auto Jy = convert<real_t>(\"2.5\");\n  auto t = convert<real_t>(\"2\");\n  auto beta = boost::math::differentiation::make_fvar<real_t, 2>(1 / t);\n  auto f = square::infinite(Jx, Jy, beta);\n  double eps = 1e-12;\n  EXPECT_DOUBLE_EQ(-4.0007112633153277, free_energy(f, beta));\n  EXPECT_DOUBLE_EQ(-3.9941706779898838, energy(f, beta));\n  EXPECT_DOUBLE_EQ(0.024138928587813167, specific_heat(f, beta));\n}\n", "meta": {"hexsha": "adffed2a36d97e9998248fe7a7874624fdb74024", "size": 1452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ising/free_energy/square_gt.cpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "ising/free_energy/square_gt.cpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "ising/free_energy/square_gt.cpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3, "max_line_length": 75, "alphanum_fraction": 0.741046832, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.6513548578981939, "lm_q1q2_score": 0.5623743125562698}}
{"text": "/**\n */\n#ifndef __POLYNOMIAL_FILTERING_HPP\n#define __POLYNOMIAL_FILTERING_HPP\n\n#include <cmath>\n#include <iostream>\n#include <string>\n#include <exception>\n#include <tuple>\n\nnamespace polynomialfiltering {\n\n\tclass PolynomialFilteringException : public std::exception {\n\tprotected:\n\t\tstd::string message;\n\tpublic:\n\t\tPolynomialFilteringException() :\n\t\t\tmessage(\"Polynomial Filtering Exception: \") {}\n\n\n\t\tvirtual const char* what() const throw() {\n\t\t\treturn message.c_str();\n\t\t}\n\t};\n\n\tclass ValueError : public PolynomialFilteringException {\n\tpublic:\n\t\tValueError(std::string message) {\n\t\t\tthis->message += message;\n\t\t}\n\n\t};\n\n\tclass EigenException : public PolynomialFilteringException {\n\tpublic:\n\t\tEigenException(std::string where) {\n\t\t\tthis->message += \"Fatai Eigen Exception; \" + where;\n\t\t}\n\t};\n\n}\n\n#undef  eigen_assert\n#define eigen_assert(X) do { if(!(X)) throw ::polynomialfiltering::EigenException(#X); } while(false);\n\n#include <Eigen/Dense>\n#include <gsl/gsl_cdf.h>\n\nusing namespace Eigen;\nnamespace polynomialfiltering {\n\n\ttypedef VectorXd RealVector;\n\ttypedef MatrixXd RealMatrix;\n\ttypedef Matrix<double, 1, 1> RealVector1;\n\ttypedef Matrix<double, 2, 1> RealVector2;\n\ttypedef Matrix<double, 3, 1> RealVector3;\n\ttypedef Matrix<double, 4, 1> RealVector4;\n\ttypedef Matrix<double, 5, 1> RealVector5;\n\ttypedef Matrix<double, 6, 1> RealVector6;\n\ttypedef Matrix<double, 7, 1> RealVector7;\n\ttypedef Matrix<double, 8, 1> RealVector8;\n\ttypedef Matrix<double, 9, 1> RealVector9;\n\ttypedef Matrix<double, 10, 1> RealVector10;\n    typedef Matrix<double, 11, 1> RealVector11;\n    typedef Matrix<double, 12, 1> RealVector12;\n    typedef Matrix<double, 13, 1> RealVector13;\n    typedef Matrix<double, 14, 1> RealVector14;\n    typedef Matrix<double, 15, 1> RealVector15;\n    typedef Matrix<double, 16, 1> RealVector16;\n    typedef Matrix<double, 17, 1> RealVector17;\n    typedef Matrix<double, 18, 1> RealVector18;\n    typedef Matrix<double, 19, 1> RealVector19;\n\ttypedef Matrix<double, 1, 1> RealMatrix1;\n\ttypedef Matrix<double, 2, 2> RealMatrix2;\n\ttypedef Matrix<double, 3, 3> RealMatrix3;\n\ttypedef Matrix<double, 4, 4> RealMatrix4;\n\ttypedef Matrix<double, 5, 5> RealMatrix5;\n\ttypedef Matrix<double, 6, 6> RealMatrix6;\n\ttypedef Matrix<double, 7, 7> RealMatrix7;\n\ttypedef Matrix<double, 8, 8> RealMatrix8;\n\ttypedef Matrix<double, 9, 9> RealMatrix9;\n\ttypedef Matrix<double, 10, 10> RealMatrix10;\n\n\n\tusing std::shared_ptr;\n\n\tinline void NOOP() {} // Used to delete lines such as std::vector (Python list) initializations\n\n\tinline int integerCast(Index a) {\n\t\treturn static_cast<int>(a);\n\t}\n\n\tinline int min(int a, int b) {\n\t\treturn std::min(a, b);\n\t}\n\n\tinline int min(int a, Index b) {\n\t\treturn std::min(a, static_cast<int>(b));\n\t}\n\n\tinline int min(Index a, int b) {\n\t\treturn std::min(b, static_cast<int>(a));\n\t}\n\n\tinline double min(double a, double b) {\n\t\treturn std::min(a, b);\n\t}\n\n\tinline double max(double a, double b) {\n\t\treturn std::max(a, b);\n\t}\n\n\tinline RealMatrix copy(const RealMatrix& m) {\n\t\treturn m;\n\t}\n\n\t// wrapper to match Python eye syntax for square matrices\n\tinline RealMatrix identity(Index N) {\n\t\treturn MatrixXd::Identity(N, N);\n\t}\n\n\tinline RealMatrix ones(Index N, Index M = 1) {\n\t\treturn MatrixXd::Constant(N, M, 1.0);\n\t}\n\n\tinline RealVector diag(const RealMatrix& m) {\n\t\treturn m.diagonal();\n\t}\n\n\tinline RealMatrix diag(const RealVector& v) {\n\t\treturn v.asDiagonal();\n\t}\n\n\tinline RealMatrix sqrt(const RealMatrix& m) {\n\t\treturn m.array().sqrt();\n\t}\n\n\t// inline RealVector sqrt(const RealVector& v) {\n\t// \treturn v.array().sqrt();\n\t// }\n\n\tinline RealMatrix zeros(Index N, Index M = 1) {\n\t\treturn MatrixXd::Constant(N, M, 0.0);\n\t}\n\n\tinline RealMatrix solve(const RealMatrix& A, const RealMatrix& B) {\n\t\treturn A.ldlt().solve(B); //  A.colPivHouseholderQr().solve(B); // A.completeOrthogonalDecomposition().solve(B); // \n\t}\n\n\tinline RealMatrix inv(const RealMatrix& M) {\n\t\treturn M.inverse();\n\t}\n\n\tinline RealMatrix transpose(const RealMatrix& M) {\n\t\treturn M.transpose();\n\t}\n\n\tinline RealMatrix operator+(const RealMatrix& m, double x) {\n\t\treturn m.array() + x;\n\t}\n\n\tinline RealMatrix operator-(const RealMatrix& m, double x) {\n\t\treturn m.array() - x;\n\t}\n\n\tinline RealMatrix arrayTimes(const RealMatrix& a, const RealMatrix& b) {\n\t\treturn a.array() * b.array();\n\t}\n\n\tinline double arrayTimes(double a, double b) {\n\t\treturn a * b;\n\t}\n\n\tinline RealMatrix arrayDivide(const RealMatrix& a, const RealMatrix& b) {\n\t\treturn a.array() / b.array();\n\t}\n\n\tinline double sqrt(double x) {\n\t\treturn ::sqrt(x);\n\t}\n\n\tinline double cos(double x) {\n\t\treturn ::cos(x);\n\t}\n\n\tinline double sin(double x) {\n\t\treturn ::sin(x);\n\t}\n\n\tinline double atan(double x) {\n\t\treturn ::atan(x);\n\t}\n\n\tinline double pow(double x, double p) {\n\t\treturn ::pow(x, p);\n\t}\n\n\tinline double atan2(double x, double y) {\n\t\treturn ::atan2(x, y);\n\t}\n\n\tinline RealMatrix atan(RealMatrix A) {\n\t\treturn A.array().atan();\n\t}\n\n\tinline RealMatrix atan2(RealMatrix A, RealMatrix B) {\n\t\tRealMatrix O(A.rows(), A.cols());\n\t\tfor (int c = 0; c < A.cols(); c++) {\n\t\t\tfor (int r = 0; r < A.rows(); r++) {\n\t\t\t\tO(r,c) = ::atan2(A(r,c), B(r,c));\n\t\t\t}\n\t\t}\n\t\treturn O;\n\t}\n\n\tinline RealMatrix cos(RealMatrix A) {\n\t\treturn A.array().cos();\n\t}\n\t\n\tinline RealMatrix sin(RealMatrix A) {\n\t\treturn A.array().sin();\n\t}\n\t\n\tinline RealMatrix pow(RealMatrix A, double p) {\n\t\tRealMatrix O(A.rows(), A.cols());\n\t\tfor (int c = 0; c < A.cols(); c++) {\n\t\t\tfor (int r = 0; r < A.rows(); r++) {\n\t\t\t\tO(r,c) = ::pow(A(r,c), p );\n\t\t\t}\n\t\t}\n\t\treturn O;\n\t}\n\n\tinline long len(const RealMatrix& a) {\n\t\treturn (long) (a.rows() * a.cols());\n\t}\n\n\tinline long len(const RealVector& a) {\n\t\treturn (long) (a.size());\n\t}\n\n\tinline RealVector test() {\n\t\treturn Map<RowVectorXd>(new double[3] { 1, 2, 3 }, 3);\n\t}\n\n\tinline double chi2Cdf(double chi, int df) {\n\t\treturn gsl_cdf_chisq_P(chi, df);\n\t}\n\n\tinline double chi2Ppf(double p, int df) {\n\t\treturn gsl_cdf_chisq_Pinv(1.0 - p, df);\n\t}\n\n\tinline double fdistCdf(double chi, int df1, int df2) {\n\t\treturn gsl_cdf_fdist_P(chi, df1, df2);\n\t}\n\n\tinline double fdistPpf(double p, int df1, int df2) {\n\t\treturn gsl_cdf_fdist_Pinv(1.0 - p, df1, df2);\n\t}\n}\n\n\n#endif // __POLYNOMIAL_\n", "meta": {"hexsha": "db52cb507630a3a56f41fe63f12cd9ba4ef0799c", "size": 6129, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Cpp/Eigen/include/polynomialfiltering/PolynomialFilteringEigen.hpp", "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/include/polynomialfiltering/PolynomialFilteringEigen.hpp", "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/include/polynomialfiltering/PolynomialFilteringEigen.hpp", "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": 23.0413533835, "max_line_length": 118, "alphanum_fraction": 0.6738456518, "num_tokens": 1807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5623273111957935}}
{"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/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2011 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <iostream>\n#include <utility> // std::move\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n\n#include \"dune/grid/onedgrid.hh\"\n#include \"dune/grid/onedgrid/onedgridfactory.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 \"fem/istlinterface.hh\"\n#include \"linalg/umfpack_solve.hh\"\n#include \"linalg/triplet.hh\"\n#include \"io/gnuplot.hh\"\n#include \"utilities/kaskopt.hh\"\n\nusing namespace Kaskade;\n#include \"atp.hh\"\n\nint main(int argc, char *argv[])\n  {\n  using namespace boost::fusion;\n\n  std::cout << \"Start atp transfer tutorial program\" << std::endl;\n\n  boost::timer::cpu_timer totalTimer;\n\n  int verbosity = 1;\n  bool dump = true; \n  std::unique_ptr<boost::property_tree::ptree> pt = getKaskadeOptions(argc, argv, verbosity, dump);\n\n  int  direct = 1,\n       refinements = getParameter(pt, \"refinement\", 5),\n       order =  getParameter(pt, \"order\", 2);\n  double fsign = static_cast<double>(getParameter(pt, \"sign\", -1.0));\n  int graphicalOutput= getParameter(pt, \"graphicalOutput\", 1);\n\n  std::cout << \"refinements of original mesh : \" << refinements << std::endl;\n  std::cout << \"discretization order         : \" << order << std::endl;\n\n  std::cout << \"fsign = \" << fsign << \"\\n\";\n\n\n  //   one-dimensional space: dim=1\n  int const dim=1;    \n  using Grid = Dune::OneDGrid;\n  using LeafView = Grid::LeafGridView;\n  // construction of finite element space for the scalar solution T\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<VariableDescription<0,1,0> >;\n  using VarSetDesc = VariableSetDescription<Spaces,VariableDescriptions>;\n  using Functional = ATPFunctional<double,VarSetDesc>;\n  using Assembler = VariationalFunctionalAssembler<LinearizationAt<Functional> >;\n  using CoefficientVectors = VarSetDesc::CoefficientVectorRepresentation<0,1>::type;\n  constexpr int nvars = ATPFunctional<double,VarSetDesc>::AnsatzVars::noOfVariables;\n  constexpr int neq = ATPFunctional<double,VarSetDesc>::TestVars::noOfVariables;\n\n  Dune::GridFactory<Grid> factory;\n\n  // point (in case of dimension>1: vertex) coordinates v[0]\n  Dune::FieldVector<double,dim> v; \n  v[0]=-3; factory.insertVertex(v);\n  v[0]=0; factory.insertVertex(v);\n  v[0]=3; factory.insertVertex(v);\n  std::vector<unsigned int> vid(2);\n  Dune::GeometryType gt(Dune::GeometryType::simplex,dim);\n  vid[0]=0; vid[1]=1; factory.insertElement(gt,vid);\n  vid[0]=1; vid[1]=2; factory.insertElement(gt,vid);\n  // interval defined by 2 point indices\n  std::unique_ptr<Grid> grid( factory.createGrid() ) ;\n  // the coarse grid will be refined refinements times\n  grid->globalRefine(refinements);\n  // some information on the refined mesh\n  std::cout << \"Grid: \" << grid->size(1) << \" points \" << std::endl;\n  // a gridmanager is constructed \n  // as connector between geometric and algebraic information\n  GridManager<Grid> gridManager(std::move(grid));   \n\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  VarSetDesc varSetDesc(spaces,{ \"T\" });\n  Functional F(fsign);\n  Assembler assembler(gridManager,spaces);\n  VarSetDesc::VariableSet x(varSetDesc);\n  VarSetDesc::VariableSet dx(varSetDesc);\n\n  // set nnz to the number of structural nonzero elements of the matrix to be assembled below\n  size_t  nnz = assembler.nnz(0,neq,0,nvars,false);\n  size_t  size = varSetDesc.degreesOfFreedom(0,nvars);\n  AssembledGalerkinOperator<Assembler,0,neq,0,nvars> A(assembler);\n  MatrixAsTriplet<double> triplet(nnz);\n      \n  std::vector<double> rhs(size), sol(size);\n  \n  int k=0;\n  L2Norm l2Norm;\n  double norm_dx, norm_rhs;\n  x=0;\n  \n  std::cout << std::endl << \"Newton iteration starts:\" << std::endl <<\n            \"iter   ||correction||            ||F||  assemble time  linsolve time\"\n            << std::endl;\n\n// begin of ordinary Newton iteration loop\n  do \n  {\n    boost::timer::cpu_timer assembTimer;\n    assembler.assemble(linearization(F,x));\n\tdouble assembleTime = (double)(assembTimer.elapsed().user)/1e9;\n    triplet = A.get<MatrixAsTriplet<double> >();\n    //     for (k=0; k< nnz; k++)\n    //       {\n    //         printf(\"%3d %3d %e\\n\", triplet.ridx[k], triplet.cidx[k], triplet.data[k]);\n    //       }\n    boost::timer::cpu_timer directTimer;\n    Factorization<double> *matrix = 0;\n    matrix = new UMFFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);\n    assembler.toSequence(0,neq,rhs.begin());\n    for (int l=0; l<rhs.size(); ++l) assert(std::isfinite(rhs[l]));\n    matrix->solve(rhs,sol);\n    double solveTime = (double)(directTimer.elapsed().user)/1e9;\n    delete matrix;\n    for (int l=0; l<sol.size(); ++l) assert(std::isfinite(sol[l]));\n    dx.read(sol.begin());\n    dx *= -1;\n    x += dx;\n    norm_dx=l2Norm(component<0>(dx));\n    VarSetDesc::VariableSet tmp(dx);\n    tmp.read(rhs.begin());\n    norm_rhs=l2Norm(component<0>(tmp));\n    std::cout << std::setw(4) << k+1 << \"  \" \n              << std::setw(15) << std::setprecision(5) << std::scientific << norm_dx << \"  \"  \n              << std::setw(15) << norm_rhs << \"  \" << std::setprecision(3);\n    std::cout.unsetf(std::ios::fixed | std::ios::scientific);\n    std::cout << std::fixed << std::setw(6) << \"       \" << std::setprecision(3)\n              << assembleTime << \"s        \" << std::setw(6) << solveTime << \"s \" << std::endl;\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    // char fname[6];\n    // IoOptions options;\n    // options.outputType = IoOptions::ascii;\n    // LeafView leafView = gridManager.grid().leafGridView();\n    // sprintf(fname,\"atp_%#02d\",k);\n    // writeVTKFile(x,fname,options,order);\n    if ( graphicalOutput!=0 )\n    {\n      IoOptions gnuplotOptions{};\n      std::string empty;\n      std::string s = \"names.gnuplotinfo.\" + getParameter(pt, \"gnuplotinfo\", empty);\n      gnuplotOptions.info = static_cast<IoOptions::Info>(getParameter(pt,s,0));\n      writeGnuplotFile(x,\"function\",gnuplotOptions);\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 leafView = gridManager.grid().leafGridView();\n    //  writeAMIRAFile(leafView,varSetDesc,x,\"atp\",options);\n    //StopSnippet6\n    k ++;\n  }\n  while ( norm_dx > 1.0e-5 );\n\n  std::cout << \"total computing time: \" << boost::timer::format(totalTimer.elapsed()) << \"\\n\";\n  std::cout << \"End atp transfer tutorial program\" << std::endl;\n}\n", "meta": {"hexsha": "ab87f09338b9c04cf5de234a4c7c4585ee680537", "size": 8001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/artificial_1d_testProblem/atp.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/artificial_1d_testProblem/atp.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/artificial_1d_testProblem/atp.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.671875, "max_line_length": 99, "alphanum_fraction": 0.6212973378, "num_tokens": 2171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.7090191399336401, "lm_q1q2_score": 0.5623272924502767}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[boost_range_filtered\r\n//` Shows how to use a Boost.Geometry linestring, filtered by Boost.Range adaptor\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/linestring.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_range/filtered.hpp>\r\n\r\nstruct not_two\r\n{\r\n    template <typename P>\r\n    bool operator()(P const& p) const\r\n    {\r\n        return boost::geometry::get<1>(p) != 2;\r\n    }\r\n};\r\n\r\n\r\nint main()\r\n{\r\n    typedef boost::geometry::model::d2::point_xy<int> xy;\r\n    boost::geometry::model::linestring<xy> line;\r\n    line.push_back(xy(0, 0));\r\n    line.push_back(xy(1, 1));\r\n    line.push_back(xy(2, 2));\r\n    line.push_back(xy(3, 1));\r\n    line.push_back(xy(4, 0));\r\n    line.push_back(xy(5, 1));\r\n    line.push_back(xy(6, 2));\r\n    line.push_back(xy(7, 1));\r\n    line.push_back(xy(8, 0));\r\n    \r\n    using boost::adaptors::filtered;\r\n    std::cout \r\n        << boost::geometry::length(line) << std::endl\r\n        << boost::geometry::length(line | filtered(not_two())) << std::endl\r\n        << boost::geometry::dsv(line | filtered(not_two())) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n//[boost_range_filtered_output\r\n/*`\r\nOutput:\r\n[pre\r\n11.3137\r\n9.65685\r\n((0, 0), (1, 1), (3, 1), (4, 0), (5, 1), (7, 1), (8, 0))\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "ce67f9736cd088f65fd7a59660bf5356379bf1af", "size": 1676, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/geometries/adapted/boost_range/filtered.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/geometry/doc/src/examples/geometries/adapted/boost_range/filtered.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/geometry/doc/src/examples/geometries/adapted/boost_range/filtered.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7846153846, "max_line_length": 82, "alphanum_fraction": 0.6247016706, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.562327289956363}}
{"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// \u672c\u6559\u7a0b\u7684\u5927\u90e8\u5206\u5185\u5bb9\u662f\u5bf9  step-15  \u7684\u5b8c\u5168\u590d\u5236\u3002\u56e0\u6b64\uff0c\u4e3a\u4e86\u7b80\u6d01\u8d77\u89c1\uff0c\u5e76\u4fdd\u6301\u5bf9\u8fd9\u91cc\u6240\u5b9e\u73b0\u7684\u53d8\u5316\u7684\u5173\u6ce8\uff0c\u6211\u4eec\u5c06\u53ea\u8bb0\u5f55\u65b0\u7684\u5185\u5bb9\uff0c\u5e76\u7b80\u5355\u5730\u6307\u51fa\u54ea\u4e9b\u90e8\u5206\u7684\u4ee3\u7801\u662f\u5bf9\u4ee5\u524d\u5185\u5bb9\u7684\u91cd\u590d\u3002\n\n//  @sect3{Include files}  \n\n// \u672c\u6559\u7a0b\u4e2d\u5305\u542b\u4e86\u51e0\u4e2a\u65b0\u7684\u5934\u6587\u4ef6\u3002\u7b2c\u4e00\u4e2a\u662f\u63d0\u4f9bParameterAcceptor\u7c7b\u7684\u58f0\u660e\u7684\u6587\u4ef6\u3002\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// \u8fd9\u662f\u7b2c\u4e8c\u4e2a\uff0c\u8fd9\u662f\u4e00\u4e2a\u5305\u7f57\u4e07\u8c61\u7684\u5934\uff0c\u5b83\u5c06\u4f7f\u6211\u4eec\u80fd\u591f\u5728\u8fd9\u6bb5\u4ee3\u7801\u4e2d\u7eb3\u5165\u81ea\u52a8\u533a\u5206\uff08AD\uff09\u529f\u80fd\u3002\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// \u800c\u63a5\u4e0b\u6765\u7684\u4e09\u4e2a\u63d0\u4f9b\u4e86\u4e00\u4e9b\u4f7f\u7528\u901a\u7528 MeshWorker::mesh_loop() \u6846\u67b6\u7684\u591a\u7ebf\u7a0b\u80fd\u529b\u3002\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// \u7136\u540e\uff0c\u6211\u4eec\u4e3a\u8fd9\u4e2a\u7a0b\u5e8f\u6253\u5f00\u4e00\u4e2a\u547d\u540d\u7a7a\u95f4\uff0c\u50cf\u4ee5\u524d\u7684\u7a0b\u5e8f\u4e00\u6837\uff0c\u5c06dealii\u547d\u540d\u7a7a\u95f4\u4e2d\u7684\u6240\u6709\u4e1c\u897f\u5bfc\u5165\u5176\u4e2d\u3002\n\nnamespace Step72 \n{ \n  using namespace dealii; \n// @sect3{The <code>MinimalSurfaceProblemParameters</code> class}  \n\n// \u5728\u672c\u6559\u7a0b\u4e2d\uff0c\u6211\u4eec\u5c06\u5b9e\u73b0\u4e09\u79cd\u4e0d\u540c\u7684\u65b9\u6cd5\u6765\u7ec4\u88c5\u7ebf\u6027\u7cfb\u7edf\u3002\u5176\u4e2d\u4e00\u79cd\u53cd\u6620\u4e86\u6700\u521d\u5728 step-15 \u4e2d\u63d0\u4f9b\u7684\u624b\u5de5\u5b9e\u73b0\uff0c\u800c\u53e6\u5916\u4e24\u79cd\u5219\u4f7f\u7528\u4f5c\u4e3aTrilinos\u6846\u67b6\u7684\u4e00\u90e8\u5206\u63d0\u4f9b\u7684Sacado\u81ea\u52a8\u5fae\u5206\u5e93\u3002\n\n// \u4e3a\u4e86\u65b9\u4fbf\u5728\u4e09\u79cd\u5b9e\u73b0\u4e4b\u95f4\u8fdb\u884c\u5207\u6362\uff0c\u6211\u4eec\u6709\u8fd9\u4e2a\u975e\u5e38\u57fa\u672c\u7684\u53c2\u6570\u7c7b\uff0c\u5b83\u53ea\u6709\u4e24\u4e2a\u53ef\u914d\u7f6e\u7684\u9009\u9879\u3002\n\n  class MinimalSurfaceProblemParameters : public ParameterAcceptor \n  { \n  public: \n    MinimalSurfaceProblemParameters(); \n\n// \u9009\u62e9\u8981\u4f7f\u7528\u7684\u914d\u65b9\u548c\u76f8\u5e94\u7684AD\u6846\u67b6\u3002\n\n// - formulation = 0 : \u65e0\u8f85\u52a9\u6267\u884c\uff08\u5168\u624b\u5de5\u7ebf\u6027\u5316\uff09\u3002\n\n// - \u914d\u65b9 = 1 : \u6709\u9650\u5143\u6b8b\u5dee\u7684\u81ea\u52a8\u7ebf\u6027\u5316\u3002\n\n// - formulation = 2 : \u4f7f\u7528\u53d8\u91cf\u516c\u5f0f\u81ea\u52a8\u8ba1\u7b97\u6709\u9650\u5143\u6b8b\u5dee\u548c\u7ebf\u6027\u5316\u3002\n\n    unsigned int formulation = 0; \n\n// \u7ebf\u6027\u7cfb\u7edf\u6b8b\u5dee\u7684\u6700\u5927\u53ef\u63a5\u53d7\u516c\u5dee\u3002\u6211\u4eec\u5c06\u770b\u5230\uff0c\u4e00\u65e6\u6211\u4eec\u4f7f\u7528AD\u6846\u67b6\uff0c\u88c5\u914d\u65f6\u95f4\u5c31\u4f1a\u53d8\u5f97\u5f88\u660e\u663e\uff0c\u6240\u4ee5\u6211\u4eec\u5c06 step-15 \u4e2d\u9009\u62e9\u7684\u516c\u5dee\u63d0\u9ad8\u4e86\u4e00\u4e2a\u6570\u91cf\u7ea7\u3002\u8fd9\u6837\uff0c\u8ba1\u7b97\u5c31\u4e0d\u4f1a\u82b1\u8d39\u592a\u957f\u65f6\u95f4\u6765\u5b8c\u6210\u3002\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// \u8be5\u7c7b\u6a21\u677f\u4e0e  step-15  \u4e2d\u7684\u5185\u5bb9\u57fa\u672c\u76f8\u540c\u3002\u8be5\u7c7b\u7684\u552f\u4e00\u529f\u80fd\u53d8\u5316\u662f\uff1a\u3002\n\n// - run()\u51fd\u6570\u73b0\u5728\u63a5\u6536\u4e24\u4e2a\u53c2\u6570\uff1a\u4e00\u4e2a\u662f\u9009\u62e9\u91c7\u7528\u54ea\u79cd\u88c5\u914d\u65b9\u5f0f\uff0c\u4e00\u4e2a\u662f\u5141\u8bb8\u7684\u6700\u7ec8\u6b8b\u5dee\u7684\u516c\u5dee\uff0c\u4ee5\u53ca\n\n// - \u73b0\u5728\u6709\u4e09\u4e2a\u4e0d\u540c\u7684\u88c5\u914d\u51fd\u6570\u6765\u5b9e\u73b0\u7ebf\u6027\u7cfb\u7edf\u7684\u4e09\u79cd\u88c5\u914d\u65b9\u6cd5\u3002\u6211\u4eec\u5c06\u5728\u540e\u9762\u63d0\u4f9b\u5173\u4e8e\u8fd9\u4e9b\u7684\u7ec6\u8282\u3002\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//\u5e94\u7528\u4e8e\u8be5\u95ee\u9898\u7684\u8fb9\u754c\u6761\u4ef6\u6ca1\u6709\u53d8\u5316\u3002\n\n  template <int dim> \n  class BoundaryValues : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n  }; \n\n  template <int dim> \n  double BoundaryValues<dim>::value(const Point<dim> &p, \n                                    const unsigned int /*component*/) const \n  { \n    return std::sin(2 * numbers::PI * (p[0] + p[1])); \n  } \n// @sect3{The <code>MinimalSurfaceProblem</code> class implementation}  \n// @sect4{MinimalSurfaceProblem::MinimalSurfaceProblem}  \n\n// \u5bf9\u7c7b\u7684\u6784\u9020\u51fd\u6570\u6ca1\u6709\u505a\u4efb\u4f55\u4fee\u6539\u3002\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// \u8bbe\u7f6e\u7c7b\u6570\u636e\u7ed3\u6784\u7684\u51fd\u6570\u6ca1\u6709\u4efb\u4f55\u53d8\u5316\uff0c\u5373DoFHandler\u3001\u5e94\u7528\u4e8e\u95ee\u9898\u7684\u60ac\u6302\u8282\u70b9\u7ea6\u675f\u4ee5\u53ca\u7ebf\u6027\u7cfb\u7edf\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::setup_system(const bool initial_step) \n  { \n    if (initial_step) \n      { \n        dof_handler.distribute_dofs(fe); \n        current_solution.reinit(dof_handler.n_dofs()); \n\n        hanging_node_constraints.clear(); \n        DoFTools::make_hanging_node_constraints(dof_handler, \n                                                hanging_node_constraints); \n        hanging_node_constraints.close(); \n      } \n\n    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// \u6c47\u7f16\u51fd\u6570\u662f\u672c\u6559\u7a0b\u7684\u6709\u8da3\u8d21\u732e\u3002assemble_system_unassisted()\u65b9\u6cd5\u5b9e\u73b0\u4e86\u4e0e step-15 \u4e2d\u8be6\u8ff0\u7684\u5b8c\u5168\u76f8\u540c\u7684\u88c5\u914d\u51fd\u6570\uff0c\u4f46\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u4f7f\u7528 MeshWorker::mesh_loop() \u51fd\u6570\u6765\u591a\u7ebf\u7a0b\u88c5\u914d\u8fc7\u7a0b\u3002\u8fd9\u6837\u505a\u7684\u539f\u56e0\u5f88\u7b80\u5355\u3002\u5f53\u4f7f\u7528\u81ea\u52a8\u5206\u5316\u65f6\uff0c\u6211\u4eec\u77e5\u9053\u4f1a\u6709\u4e00\u4e9b\u989d\u5916\u7684\u8ba1\u7b97\u5f00\u9500\u4ea7\u751f\u3002\u4e3a\u4e86\u51cf\u8f7b\u8fd9\u79cd\u6027\u80fd\u635f\u5931\uff0c\u6211\u4eec\u5e0c\u671b\u5c3d\u53ef\u80fd\u591a\u5730\u5229\u7528\uff08\u5bb9\u6613\u83b7\u5f97\u7684\uff09\u8ba1\u7b97\u8d44\u6e90\u3002 MeshWorker::mesh_loop() \u7684\u6982\u5ff5\u4f7f\u8fd9\u6210\u4e3a\u4e00\u4e2a\u76f8\u5bf9\u7b80\u5355\u7684\u4efb\u52a1\u3002\u540c\u65f6\uff0c\u4e3a\u4e86\u516c\u5e73\u6bd4\u8f83\uff0c\u6211\u4eec\u9700\u8981\u5bf9\u5728\u8ba1\u7b97\u6b8b\u5dee\u6216\u5176\u7ebf\u6027\u5316\u65f6\u4e0d\u4f7f\u7528\u4efb\u4f55\u63f4\u52a9\u7684\u5b9e\u73b0\u505a\u540c\u6837\u7684\u4e8b\u60c5\u3002( MeshWorker::mesh_loop() \u51fd\u6570\u9996\u5148\u5728 step-12 \u548c step-16 \u4e2d\u8ba8\u8bba\uff0c\u5982\u679c\u4f60\u60f3\u9605\u8bfb\u5b83\u7684\u8bdd\u3002)\n\n// \u5b9e\u73b0\u591a\u7ebf\u7a0b\u6240\u9700\u7684\u6b65\u9aa4\u5728\u8fd9\u4e09\u4e2a\u51fd\u6570\u4e2d\u662f\u76f8\u540c\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u5229\u7528assemble_system_unassisted()\u51fd\u6570\u7684\u673a\u4f1a\uff0c\u91cd\u70b9\u8ba8\u8bba\u591a\u7ebf\u7a0b\u672c\u8eab\u3002\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() \u5e0c\u671b\u6211\u4eec\u63d0\u4f9b\u4e24\u4e2a\u793a\u8303\u6027\u7684\u6570\u636e\u7ed3\u6784\u3002\u7b2c\u4e00\u4e2a\uff0c`ScratchData`\uff0c\u662f\u7528\u6765\u5b58\u50a8\u6240\u6709\u8981\u5728\u7ebf\u7a0b\u95f4\u91cd\u590d\u4f7f\u7528\u7684\u5927\u6570\u636e\u3002`CopyData`\u5c06\u4fdd\u5b58\u6765\u81ea\u6bcf\u4e2a\u5355\u5143\u7684\u5bf9\u7ebf\u6027\u7cfb\u7edf\u7684\u8d21\u732e\u3002\u8fd9\u4e9b\u72ec\u7acb\u7684\u77e9\u9635-\u5411\u91cf\u5bf9\u5fc5\u987b\u6309\u987a\u5e8f\u7d2f\u79ef\u5230\u5168\u5c40\u7ebf\u6027\u7cfb\u7edf\u4e2d\u3002\u7531\u4e8e\u6211\u4eec\u4e0d\u9700\u8981 MeshWorker::ScratchData \u548c MeshWorker::CopyData \u7c7b\u5df2\u7ecf\u63d0\u4f9b\u7684\u4e1c\u897f\uff0c\u6240\u4ee5\u6211\u4eec\u4f7f\u7528\u8fd9\u4e9b\u786e\u5207\u7684\u7c7b\u5b9a\u4e49\u6765\u89e3\u51b3\u6211\u4eec\u7684\u95ee\u9898\u3002\u8bf7\u6ce8\u610f\uff0c\u6211\u4eec\u53ea\u9700\u8981\u4e00\u4e2a\u5c40\u90e8\u77e9\u9635\u3001\u5c40\u90e8\u53f3\u624b\u5411\u91cf\u548c\u5355\u5143\u81ea\u7531\u5ea6\u7d22\u5f15\u5411\u91cf\u7684\u5355\u4e2a\u5b9e\u4f8b--\u56e0\u6b64 MeshWorker::CopyData \u7684\u4e09\u4e2a\u6a21\u677f\u53c2\u6570\u90fd\u662f`1`\u3002\n\n    using ScratchData = MeshWorker::ScratchData<dim>; \n    using CopyData    = MeshWorker::CopyData<1, 1, 1>; \n\n// \u6211\u4eec\u8fd8\u9700\u8981\u77e5\u9053\u6211\u4eec\u5728\u88c5\u914d\u8fc7\u7a0b\u4e2d\u8981\u5904\u7406\u7684\u8fed\u4ee3\u5668\u7684\u7c7b\u578b\u3002\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u6211\u4eec\u53ea\u8981\u6c42\u7f16\u8bd1\u5668\u4f7f\u7528decltype()\u6307\u5b9a\u5668\u4e3a\u6211\u4eec\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\uff0c\u77e5\u9053\u6211\u4eec\u5c06\u5728\u7531  @p dof_handler.  \u62e5\u6709\u7684\u6d3b\u52a8\u5355\u5143\u4e0a\u8fed\u4ee3\u3002\n    using CellIteratorType = decltype(dof_handler.begin_active()); \n\n// \u5728\u8fd9\u91cc\u6211\u4eec\u521d\u59cb\u5316\u793a\u4f8b\u7684\u6570\u636e\u7ed3\u6784\u3002\u56e0\u4e3a\u6211\u4eec\u77e5\u9053\u6211\u4eec\u9700\u8981\u8ba1\u7b97\u5f62\u72b6\u51fd\u6570\u68af\u5ea6\u3001\u52a0\u6743\u96c5\u5404\u5e03\u548c\u56db\u5206\u4f4d\u70b9\u5728\u5b9e\u7a7a\u95f4\u7684\u4f4d\u7f6e\uff0c\u6240\u4ee5\u6211\u4eec\u628a\u8fd9\u4e9b\u6807\u5fd7\u4f20\u7ed9\u7c7b\u7684\u6784\u9020\u51fd\u6570\u3002\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// \u73b0\u5728\u6211\u4eec\u5b9a\u4e49\u4e00\u4e2alambda\u51fd\u6570\uff0c\u5b83\u5c06\u5728\u4e00\u4e2a\u5355\u5143\u683c\u4e0a\u6267\u884c\u88c5\u914d\u3002\u4e09\u4e2a\u53c2\u6570\u662f\u7531\u4e8e\u6211\u4eec\u5c06\u4f20\u9012\u7ed9\u8be5\u6700\u7ec8\u8c03\u7528\u7684\u53c2\u6570\uff0c\u5c06\u88ab MeshWorker::mesh_loop(), \u6240\u671f\u671b\u7684\u53c2\u6570\u3002\u6211\u4eec\u8fd8\u6355\u83b7\u4e86 @p this \u6307\u9488\uff0c\u8fd9\u610f\u5473\u7740\u6211\u4eec\u5c06\u53ef\u4ee5\u8bbf\u95ee \"this\"\uff08\u5373\u5f53\u524d\u7684`MinimalSurfaceProblem<dim>`\uff09\u7c7b\u5b9e\u4f8b\uff0c\u4ee5\u53ca\u5b83\u7684\u79c1\u6709\u6210\u5458\u6570\u636e\uff08\u56e0\u4e3alambda\u51fd\u6570\u88ab\u5b9a\u4e49\u5728MinimalSurfaceProblem<dim>\u65b9\u6cd5\u4e2d\uff09\u3002\n\n// \u5728\u51fd\u6570\u7684\u9876\u90e8\uff0c\u6211\u4eec\u521d\u59cb\u5316\u4e86\u4f9d\u8d56\u4e8e\u6b63\u5728\u6267\u884c\u5de5\u4f5c\u7684\u5355\u5143\u7684\u6570\u636e\u7ed3\u6784\u3002\u8bf7\u6ce8\u610f\uff0c\u91cd\u65b0\u521d\u59cb\u5316\u7684\u8c03\u7528\u5b9e\u9645\u4e0a\u8fd4\u56de\u4e86\u4e00\u4e2aFEValues\u5bf9\u8c61\u7684\u5b9e\u4f8b\uff0c\u8be5\u5bf9\u8c61\u88ab\u521d\u59cb\u5316\u5e76\u5b58\u50a8\u5728`scratch_data`\u5bf9\u8c61\u4e2d\uff08\u56e0\u6b64\uff0c\u88ab\u91cd\u590d\u4f7f\u7528\uff09\u3002\n\n// \u540c\u6837\u5730\uff0c\u6211\u4eec\u4ece MeshWorker::mesh_loop() \u63d0\u4f9b\u7684`copy_data`\u5b9e\u4f8b\u4e2d\u83b7\u5f97\u672c\u5730\u77e9\u9635\u3001\u672c\u5730RHS\u5411\u91cf\u548c\u672c\u5730\u5355\u5143\u683cDoF\u6307\u6570\u7684\u522b\u540d\u3002\u7136\u540e\u6211\u4eec\u521d\u59cb\u5316\u5355\u5143\u683c\u7684DoF\u6307\u6570\uff0c\u56e0\u4e3a\u6211\u4eec\u77e5\u9053\u672c\u5730\u77e9\u9635\u548c\u5411\u91cf\u7684\u5927\u5c0f\u5df2\u7ecf\u6b63\u786e\u3002\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// \u5bf9\u4e8e\u725b\u987f\u65b9\u6cd5\uff0c\u6211\u4eec\u9700\u8981\u95ee\u9898\u88ab\u7ebf\u6027\u5316\u7684\u90a3\u4e00\u70b9\u7684\u89e3\u7684\u68af\u5ea6\u3002\n\n// \u4e00\u65e6\u6211\u4eec\u6709\u4e86\u8fd9\u4e2a\u68af\u5ea6\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u7528\u901a\u5e38\u7684\u65b9\u6cd5\u5bf9\u8fd9\u4e2a\u5355\u5143\u8fdb\u884c\u88c5\u914d\u3002 \u4e0e step-15 \u7684\u4e00\u4e2a\u5c0f\u533a\u522b\u662f\uff0c\u6211\u4eec\u4f7f\u7528\u4e86\uff08\u76f8\u5f53\u65b9\u4fbf\u7684\uff09\u57fa\u4e8e\u8303\u56f4\u7684\u5faa\u73af\u6765\u8fed\u4ee3\u6240\u6709\u7684\u6b63\u4ea4\u70b9\u548c\u81ea\u7531\u5ea6\u3002\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() \u8981\u6c42\u7684\u7b2c\u4e8c\u4e2alambda\u51fd\u6570\u662f\u4e00\u4e2a\u6267\u884c\u7d2f\u79ef\u5168\u5c40\u7ebf\u6027\u7cfb\u7edf\u4e2d\u7684\u5c40\u90e8\u8d21\u732e\u7684\u4efb\u52a1\u3002\u8fd9\u6b63\u662f\u8fd9\u4e2a\u51fd\u6570\u6240\u505a\u7684\uff0c\u5b9e\u73b0\u7684\u7ec6\u8282\u5728\u524d\u9762\u5df2\u7ecf\u770b\u5230\u8fc7\u3002\u9700\u8981\u8ba4\u8bc6\u7684\u4e3b\u8981\u4e00\u70b9\u662f\uff0c\u5c40\u90e8\u8d21\u732e\u88ab\u5b58\u50a8\u5728\u4f20\u5165\u8be5\u51fd\u6570\u7684`copy_data`\u5b9e\u4f8b\u4e2d\u3002\u8fd9\u4e2a`copy_data`\u5728 @a \u5bf9`cell_worker`\u7684\u4e00\u4e9b\u8c03\u7528\u4e2d\u5df2\u7ecf\u88ab\u586b\u6ee1\u4e86\u6570\u636e\u3002\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// \u6211\u4eec\u5df2\u7ecf\u6709\u4e86\u6240\u6709\u9700\u8981\u7684\u51fd\u6570\u5b9a\u4e49\uff0c\u6240\u4ee5\u73b0\u5728\u6211\u4eec\u8c03\u7528 MeshWorker::mesh_loop() \u6765\u6267\u884c\u5b9e\u9645\u7684\u88c5\u914d\u3002 \u6211\u4eec\u4f20\u9012\u4e00\u4e2a\u6807\u5fd7\u4f5c\u4e3a\u6700\u540e\u7684\u53c2\u6570\uff0c\u8bf4\u660e\u6211\u4eec\u53ea\u60f3\u5bf9\u5355\u5143\u683c\u8fdb\u884c\u88c5\u914d\u3002\u5728\u5185\u90e8\uff0c MeshWorker::mesh_loop() \u7136\u540e\u5c06\u53ef\u7528\u7684\u5de5\u4f5c\u5206\u914d\u7ed9\u4e0d\u540c\u7684\u7ebf\u7a0b\uff0c\u6709\u6548\u5730\u5229\u7528\u5f53\u4eca\u51e0\u4e4e\u6240\u6709\u7684\u5904\u7406\u5668\u6240\u63d0\u4f9b\u7684\u591a\u6838\u3002\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// \u6700\u540e\uff0c\u6b63\u5982\u5728  step-15  \u4e2d\u6240\u505a\u7684\u90a3\u6837\uff0c\u6211\u4eec\u4ece\u7cfb\u7edf\u4e2d\u79fb\u9664\u60ac\u7a7a\u7684\u8282\u70b9\uff0c\u5e76\u5bf9\u5b9a\u4e49\u725b\u987f\u66f4\u65b0\u7684\u7ebf\u6027\u7cfb\u7edf\u5e94\u7528\u96f6\u8fb9\u754c\u503c  $\\delta u^n$  \u3002\n\n    hanging_node_constraints.condense(system_matrix); \n    hanging_node_constraints.condense(system_rhs); \n\n    std::map<types::global_dof_index, double> boundary_values; \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             Functions::ZeroFunction<dim>(), \n                                             boundary_values); \n    MatrixTools::apply_boundary_values(boundary_values, \n                                       system_matrix, \n                                       newton_update, \n                                       system_rhs); \n  } \n// @sect5{Assembly via differentiation of the residual vector}  \n\n// \u6b63\u5982\u4ecb\u7ecd\u4e2d\u6240\u8ff0\uff0c\u6211\u4eec\u9700\u8981\u4e3a\u7b2c\u4e8c\u79cd\u65b9\u6cd5\u505a\u7684\u662f\u5b9e\u73b0 $F(U)^K$ \u5355\u5143\u5bf9\u6b8b\u5dee\u5411\u91cf\u7684\u5c40\u90e8\u8d21\u732e\uff0c\u7136\u540e\u8ba9AD\u673a\u5668\u5904\u7406\u5982\u4f55\u8ba1\u7b97\u5b83\u7684\u5bfc\u6570 $J(U)_{ij}^K=\\frac{\\partial F(U)^K_i}{\\partial U_j}$ \u3002\n\n// \u5bf9\u4e8e\u4e0b\u9762\u7684\u5185\u5bb9\uff0c\u8bf7\u8bb0\u4f4f\uff0c\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//  \u5176\u4e2d $u(\\mathbf x)=\\sum_j U_j \\varphi_j(\\mathbf x)$  \u3002\n\n// \u6211\u4eec\u6765\u770b\u770b\u8fd9\u5728\u5b9e\u8df5\u4e2d\u662f\u5982\u4f55\u5b9e\u73b0\u7684\u3002\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// \u6211\u4eec\u5c06\u5229\u7528  step-71  \u4e2d\u6240\u793a\u7684\u6280\u672f\uff0c\u9884\u5148\u5b9a\u4e49\u6211\u4eec\u8981\u4f7f\u7528\u7684AD\u6570\u636e\u7ed3\u6784\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u9009\u62e9\u8f85\u52a9\u7c7b\uff0c\u5b83\u5c06\u4f7f\u7528Sacado\u5411\u524d\u81ea\u52a8\u5fae\u5206\u7c7b\u578b\u81ea\u52a8\u8ba1\u7b97\u6709\u9650\u5143\u6b8b\u5dee\u7684\u7ebf\u6027\u5316\u3002\u8fd9\u4e9b\u6570\u5b57\u7c7b\u578b\u53ef\u4ee5\u53ea\u7528\u6765\u8ba1\u7b97\u4e00\u9636\u5bfc\u6570\u3002\u8fd9\u6b63\u662f\u6211\u4eec\u60f3\u8981\u7684\uff0c\u56e0\u4e3a\u6211\u4eec\u77e5\u9053\u6211\u4eec\u5c06\u53ea\u5bf9\u6b8b\u5dee\u8fdb\u884c\u7ebf\u6027\u5316\uff0c\u8fd9\u610f\u5473\u7740\u6211\u4eec\u53ea\u9700\u8981\u8ba1\u7b97\u4e00\u9636\u5bfc\u6570\u3002\u8ba1\u7b97\u7684\u8fd4\u56de\u503c\u5c06\u662f`double`\u7c7b\u578b\u3002\n\n// \u6211\u4eec\u8fd8\u9700\u8981\u4e00\u4e2a\u63d0\u53d6\u5668\u6765\u68c0\u7d22\u4e00\u4e9b\u4e0e\u95ee\u9898\u7684\u73b0\u573a\u89e3\u51b3\u65b9\u6848\u6709\u5173\u7684\u6570\u636e\u3002\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// \u6709\u4e86\u8fd9\u4e2a\uff0c\u8ba9\u6211\u4eec\u5b9a\u4e49lambda\u51fd\u6570\uff0c\u5b83\u5c06\u88ab\u7528\u6765\u8ba1\u7b97\u5355\u5143\u683c\u5bf9\u96c5\u5404\u5e03\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u8d21\u732e\u3002\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// \u6211\u4eec\u73b0\u5728\u8981\u521b\u5efa\u5e76\u521d\u59cb\u5316\u4e00\u4e2aAD\u8f85\u52a9\u7c7b\u7684\u5b9e\u4f8b\u3002\u8981\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u6211\u4eec\u9700\u8981\u6307\u5b9a\u6709\u591a\u5c11\u4e2a\u81ea\u53d8\u91cf\u548c\u56e0\u53d8\u91cf\u3002\u81ea\u53d8\u91cf\u5c06\u662f\u6211\u4eec\u7684\u89e3\u5411\u91cf\u6240\u5177\u6709\u7684\u5c40\u90e8\u81ea\u7531\u5ea6\u7684\u6570\u91cf\uff0c\u5373\u79bb\u6563\u5316\u89e3\u5411\u91cf $u (\\mathbf{x})|_K = \\sum\\limits_{j} U^K_i \\varphi_j(\\mathbf{x})$ \u7684\u6bcf\u5143\u7d20\u8868\u793a\u4e2d\u7684\u6570\u5b57 $j$ \uff0c\u5b83\u8868\u793a\u6bcf\u4e2a\u6709\u9650\u5143\u7d20\u6709\u591a\u5c11\u4e2a\u89e3\u7cfb\u6570\u3002\u5728deal.II\u4e2d\uff0c\u8fd9\u7b49\u4e8e FiniteElement::dofs_per_cell. \uff0c\u81ea\u53d8\u91cf\u7684\u6570\u91cf\u5c06\u662f\u6211\u4eec\u8981\u5f62\u6210\u7684\u5c40\u90e8\u6b8b\u5dee\u5411\u91cf\u7684\u6761\u76ee\u6570\u3002\u5728\u8fd9\u4e2a\u7279\u5b9a\u7684\u95ee\u9898\u4e2d\uff08\u5c31\u50cf\u8bb8\u591a\u5176\u4ed6\u91c7\u7528[\u6807\u51c6Galerkin\u65b9\u6cd5](https:en.wikipedia.org/wiki/Galerkin_method)\u7684\u95ee\u9898\u4e00\u6837\uff09\uff0c\u5c40\u90e8\u6c42\u89e3\u7cfb\u6570\u7684\u6570\u91cf\u4e0e\u5c40\u90e8\u6b8b\u5dee\u65b9\u7a0b\u7684\u6570\u91cf\u76f8\u7b26\u3002\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// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5c06\u89e3\u51b3\u65b9\u6848\u7684\u503c\u544a\u77e5\u5e2e\u52a9\u5668\uff0c\u5373\u6211\u4eec\u5e0c\u671b\u7ebf\u6027\u5316\u7684 $U_j$ \u7684\u5b9e\u9645\u503c\u3002\u7531\u4e8e\u8fd9\u662f\u5728\u6bcf\u4e2a\u5143\u7d20\u4e0a\u5355\u72ec\u8fdb\u884c\u7684\uff0c\u6211\u4eec\u5fc5\u987b\u4ece\u5168\u5c40\u89e3\u51b3\u65b9\u6848\u5411\u91cf\u4e2d\u63d0\u53d6\u89e3\u51b3\u65b9\u6848\u7684\u7cfb\u6570\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u6211\u4eec\u5c06\u6240\u6709\u8fd9\u4e9b\u7cfb\u6570 $U_j$ \uff08\u5176\u4e2d $j$ \u662f\u4e00\u4e2a\u5c40\u90e8\u81ea\u7531\u5ea6\uff09\u5b9a\u4e49\u4e3a\u8fdb\u5165\u5411\u91cf $F(U)^{K}$ \uff08\u56e0\u679c\u51fd\u6570\uff09\u8ba1\u7b97\u7684\u81ea\u53d8\u91cf\u3002\n//\u7136\u540e\uff0c\n//\u6211\u4eec\u5c31\u5f97\u5230\u4e86\u7531\u53ef\u81ea\u52a8\u5fae\u5206\u7684\u6570\u5b57\u8868\u793a\u7684\u81ea\u7531\u5ea6\u503c\u7684\u5b8c\u6574\u96c6\u5408\u3002\u5bf9\u8fd9\u4e9b\u53d8\u91cf\u8fdb\u884c\u7684\u64cd\u4f5c\u4ece\u8fd9\u4e00\u70b9\u5f00\u59cb\u88abAD\u5e93\u8ddf\u8e2a\uff0c\u76f4\u5230\u5bf9\u8c61\u8d85\u51fa\u8303\u56f4\u3002\u6240\u4ee5\u6b63\u662f\u8fd9\u4e9b\u53d8\u91cf <em>  </em> \uff0c\u6211\u4eec\u5c06\u5bf9\u5176\u8ba1\u7b97\u6b8b\u5dee\u9879\u7684\u5bfc\u6570\u3002\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// \u7136\u540e\u6211\u4eec\u505a\u4e00\u4e9b\u7279\u5b9a\u95ee\u9898\u7684\u4efb\u52a1\uff0c\u9996\u5148\u662f\u6839\u636e \"\u654f\u611f \"\u7684AD\u81ea\u7531\u5ea6\u503c\u8ba1\u7b97\u6240\u6709\u6570\u503c\u3001\uff08\u7a7a\u95f4\uff09\u68af\u5ea6\u7b49\u3002\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u8981\u68c0\u7d22\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u7684\u89e3\u68af\u5ea6\u3002\u8bf7\u6ce8\u610f\uff0c\u73b0\u5728\u89e3\u68af\u5ea6\u5bf9\u81ea\u7531\u5ea6\u503c\u5f88\u654f\u611f\uff0c\u56e0\u4e3a\u5b83\u4eec\u4f7f\u7528 @p ADNumberType \u4f5c\u4e3a\u6807\u91cf\u7c7b\u578b\uff0c @p dof_values_ad \u77e2\u91cf\u63d0\u4f9b\u5c40\u90e8\u81ea\u7531\u5ea6\u503c\u3002\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// \u6211\u4eec\u58f0\u660e\u7684\u4e0b\u4e00\u4e2a\u53d8\u91cf\u5c06\u5b58\u50a8\u5355\u5143\u683c\u6b8b\u4f59\u5411\u91cf\u8d21\u732e\u3002\u8fd9\u662f\u76f8\u5f53\u4e0d\u8a00\u81ea\u660e\u7684\uff0c\u9664\u4e86\u4e00\u4e2a<b>very important</b>\u7684\u7ec6\u8282\u3002\u8bf7\u6ce8\u610f\uff0c\u5411\u91cf\u4e2d\u7684\u6bcf\u4e2a\u6761\u76ee\u90fd\u662f\u624b\u5de5\u521d\u59cb\u5316\u7684\uff0c\u6570\u503c\u4e3a0\u3002\u8fd9\u662f\u4e00\u4e2a <em> \u5f3a\u70c8\u63a8\u8350\u7684 </em> \u505a\u6cd5\uff0c\u56e0\u4e3a\u4e00\u4e9bAD\u5e93\u4f3c\u4e4e\u6ca1\u6709\u5b89\u5168\u5730\u521d\u59cb\u5316\u8fd9\u4e9b\u6570\u5b57\u7c7b\u578b\u7684\u5185\u90e8\u6570\u636e\u7ed3\u6784\u3002\u4e0d\u8fd9\u6837\u505a\u53ef\u80fd\u4f1a\u5bfc\u81f4\u4e00\u4e9b\u975e\u5e38\u96be\u4ee5\u7406\u89e3\u6216\u68c0\u6d4b\u7684\u9519\u8bef\uff08\u611f\u8c22\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u4f5c\u8005\u51fa\u4e8e\u4e00\u822c\u7684\u574f\u7ecf\u9a8c\u800c\u63d0\u5230\u8fd9\u4e00\u70b9\uff09\u3002\u56e0\u6b64\uff0c\u51fa\u4e8e\u8c28\u614e\u8003\u8651\uff0c\u503c\u5f97\u660e\u786e\u5730\u5c06\u521d\u59cb\u503c\u5f52\u96f6\u3002\u5728\u8fd9\u4e4b\u540e\uff0c\u9664\u4e86\u7b26\u53f7\u7684\u6539\u53d8\uff0c\u6b8b\u5dee\u96c6\u770b\u8d77\u6765\u548c\u6211\u4eec\u4e4b\u524d\u770b\u5230\u7684\u5355\u5143\u683cRHS\u5411\u91cf\u5dee\u4e0d\u591a\u3002\u6211\u4eec\u5728\u6240\u6709\u6b63\u4ea4\u70b9\u4e0a\u5faa\u73af\uff0c\u786e\u4fdd\u7cfb\u6570\u73b0\u5728\u901a\u8fc7\u4f7f\u7528\u6b63\u786e\u7684`ADNumberType'\u6765\u7f16\u7801\u5b83\u5bf9\uff08\u654f\u611f\u7684\uff09\u6709\u9650\u5143DoF\u503c\u7684\u4f9d\u8d56\u6027\uff0c\u6700\u540e\u6211\u4eec\u7ec4\u88c5\u6b8b\u5dee\u5411\u91cf\u7684\u7ec4\u4ef6\u3002\u4e3a\u4e86\u5b8c\u5168\u6e05\u695a\uff0c\u6709\u9650\u5143\u5f62\u72b6\u51fd\u6570\uff08\u53ca\u5176\u68af\u5ea6\u7b49\uff09\u4ee5\u53ca \"JxW \"\u503c\u4ecd\u7136\u662f\u6807\u91cf\u503c\uff0c\u4f46\u6bcf\u4e2a\u6b63\u4ea4\u70b9\u7684 @p coeff \u548c @p old_solution_gradients \u662f\u4ee5\u72ec\u7acb\u53d8\u91cf\u8ba1\u7b97\u7684\u3002\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// \u4e00\u65e6\u6211\u4eec\u8ba1\u7b97\u51fa\u5b8c\u6574\u7684\u5355\u5143\u683c\u6b8b\u5dee\u5411\u91cf\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5c06\u5176\u6ce8\u518c\u5230\u8f85\u52a9\u7c7b\u3002\n\n// \u6b64\u540e\uff0c\u6211\u4eec\u5728\u8bc4\u4f30\u70b9\u8ba1\u7b97\u6b8b\u5dee\u503c\uff08\u57fa\u672c\u4e0a\u662f\u4ece\u6211\u4eec\u5df2\u7ecf\u8ba1\u7b97\u51fa\u6765\u7684\u4e1c\u897f\u4e2d\u63d0\u53d6\u51fa\u771f\u5b9e\u7684\u503c\uff09\u548c\u5b83\u4eec\u7684Jacobian\uff08\u6bcf\u4e2a\u6b8b\u5dee\u5206\u91cf\u76f8\u5bf9\u4e8e\u6240\u6709\u5355\u5143DoF\u7684\u7ebf\u6027\u5316\uff09\u3002\u4e3a\u4e86\u7ec4\u88c5\u6210\u5168\u5c40\u7ebf\u6027\u7cfb\u7edf\uff0c\u6211\u4eec\u5fc5\u987b\u5c0a\u91cd\u6b8b\u5dee\u548cRHS\u8d21\u732e\u4e4b\u95f4\u7684\u7b26\u53f7\u5dee\u5f02\u3002\u5bf9\u4e8e\u725b\u987f\u65b9\u6cd5\uff0c\u53f3\u624b\u8fb9\u7684\u5411\u91cf\u9700\u8981\u7b49\u4e8e*\u8d1f\u7684\u6b8b\u5dee\u5411\u91cf\u3002\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// \u8be5\u51fd\u6570\u7684\u5269\u4f59\u90e8\u5206\u7b49\u4e8e\u6211\u4eec\u4e4b\u524d\u7684\u5185\u5bb9\u3002\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// \u5728\u8fd9\u7b2c\u4e09\u79cd\u65b9\u6cd5\u4e2d\uff0c\u6211\u4eec\u5c06\u6b8b\u5dee\u548c\u96c5\u5404\u5e03\u4f5c\u4e3a\u5c40\u90e8\u80fd\u91cf\u51fd\u6570\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//  \u7684\u7b2c\u4e00\u548c\u7b2c\u4e8c\u5bfc\u6570\u6765\u8ba1\u7b97\uff0c\u80fd\u91cf\u5bc6\u5ea6\u7531\n//  @f[\n//    \\Psi \\left( u \\right) = \\sqrt{1+|\\nabla u|^{2}} .\n//  @f]\u7ed9\u51fa\u3002\n\n// \u6211\u4eec\u518d\u6765\u770b\u770b\u8fd9\u662f\u5982\u4f55\u505a\u5230\u7684\u3002\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// \u5728\u8fd9\u4e2a\u88c5\u914d\u8fc7\u7a0b\u7684\u5b9e\u73b0\u4e2d\uff0c\u6211\u4eec\u9009\u62e9\u4e86\u8f85\u52a9\u7c7b\uff0c\u5b83\u5c06\u4f7f\u7528\u5d4c\u5957\u7684Sacado\u524d\u5411\u81ea\u52a8\u5fae\u5206\u7c7b\u578b\u81ea\u52a8\u8ba1\u7b97\u6b8b\u5dee\u53ca\u5176\u4ece\u5355\u5143\u8d21\u732e\u5230\u80fd\u91cf\u51fd\u6570\u7684\u7ebf\u6027\u5316\u3002\u6240\u9009\u7684\u6570\u5b57\u7c7b\u578b\u53ef\u4ee5\u7528\u6765\u8ba1\u7b97\u7b2c\u4e00\u548c\u7b2c\u4e8c\u5bfc\u6570\u3002\u6211\u4eec\u9700\u8981\u8fd9\u6837\u505a\uff0c\u56e0\u4e3a\u6b8b\u5dee\u5b9a\u4e49\u4e3a\u52bf\u80fd\u5bf9DoF\u503c\u7684\u654f\u611f\u6027\uff08\u5373\u5176\u68af\u5ea6\uff09\u3002\u7136\u540e\u6211\u4eec\u9700\u8981\u5c06\u6b8b\u5dee\u7ebf\u6027\u5316\uff0c\u8fd9\u610f\u5473\u7740\u5fc5\u987b\u8ba1\u7b97\u52bf\u80fd\u7684\u4e8c\u9636\u5bfc\u6570\u3002\u4f60\u53ef\u80fd\u60f3\u628a\u8fd9\u4e0e\u4e4b\u524d\u51fd\u6570\u4e2d\u4f7f\u7528\u7684 \"ADHelper \"\u7684\u5b9a\u4e49\u8fdb\u884c\u6bd4\u8f83\uff0c\u5728\u90a3\u91cc\u6211\u4eec\u4f7f\u7528 `Differentiation::AD::ResidualLinearization<Differentiation::AD::NumberTypes::sacado_dfad,double>`. \u3002\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// \u7136\u540e\u8ba9\u6211\u4eec\u518d\u6b21\u5b9a\u4e49lambda\u51fd\u6570\uff0c\u5bf9\u4e00\u4e2a\u5355\u5143\u8fdb\u884c\u79ef\u5206\u3002\n\n// \u4e3a\u4e86\u521d\u59cb\u5316\u8f85\u52a9\u7c7b\u7684\u5b9e\u4f8b\uff0c\u6211\u4eec\u73b0\u5728\u53ea\u9700\u8981\u9884\u5148\u77e5\u9053\u81ea\u53d8\u91cf\u7684\u6570\u91cf\uff08\u5373\u4e0e\u5143\u7d20\u89e3\u5411\u91cf\u76f8\u5173\u7684\u81ea\u7531\u5ea6\u6570\u91cf\uff09\u3002\u8fd9\u662f\u56e0\u4e3a\u7531\u80fd\u91cf\u51fd\u6570\u4ea7\u751f\u7684\u4e8c\u9636\u5bfc\u6570\u77e9\u9635\u5fc5\u7136\u662f\u5e73\u65b9\u7684\uff08\u987a\u4fbf\u8bf4\u4e00\u4e0b\uff0c\u4e5f\u662f\u5bf9\u79f0\u7684\uff09\u3002\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// \u518d\u4e00\u6b21\uff0c\u6211\u4eec\u5c06\u6240\u6709\u7684\u5355\u5143\u683cDoFs\u503c\u6ce8\u518c\u5230\u5e2e\u52a9\u5668\u4e2d\uff0c\u7136\u540e\u63d0\u53d6\u8fd9\u4e9b\u503c\u7684 \"\u654f\u611f \"\u53d8\u4f53\uff0c\u7528\u4e8e\u540e\u7eed\u5fc5\u987b\u533a\u5206\u7684\u64cd\u4f5c--\u5176\u4e2d\u4e4b\u4e00\u662f\u8ba1\u7b97\u89e3\u51b3\u65b9\u6848\u7684\u68af\u5ea6\u3002\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// \u6211\u4eec\u63a5\u4e0b\u6765\u521b\u5efa\u4e00\u4e2a\u53d8\u91cf\u6765\u5b58\u50a8\u7535\u6c60\u7684\u603b\u80fd\u91cf\u3002\u6211\u4eec\u518d\u4e00\u6b21\u5f3a\u8c03\uff0c\u6211\u4eec\u660e\u786e\u5730\u5bf9\u8fd9\u4e2a\u503c\u8fdb\u884c\u96f6\u521d\u59cb\u5316\uff0c\u4ece\u800c\u786e\u4fdd\u8fd9\u4e2a\u8d77\u59cb\u503c\u7684\u6570\u636e\u7684\u5b8c\u6574\u6027\u3002\n\n// \u6211\u4eec\u7684\u76ee\u7684\u662f\u8ba1\u7b97\u7ec6\u80de\u603b\u80fd\u91cf\uff0c\u5b83\u662f\u5185\u90e8\u80fd\u91cf\uff08\u7531\u4e8e\u53f3\u624b\u51fd\u6570\uff0c\u901a\u5e38\u662f $U$ \u7684\u7ebf\u6027\uff09\u548c\u5916\u90e8\u80fd\u91cf\u7684\u603b\u548c\u3002\u5728\u8fd9\u79cd\u7279\u6b8a\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u6ca1\u6709\u5916\u90e8\u80fd\u91cf\uff08\u4f8b\u5982\uff0c\u6765\u81ea\u6e90\u9879\u6216\u8bfa\u4f0a\u66fc\u8fb9\u754c\u6761\u4ef6\uff09\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u5173\u6ce8\u5185\u90e8\u80fd\u91cf\u90e8\u5206\u3002\n\n// \u4e8b\u5b9e\u4e0a\uff0c\u8ba1\u7b97 $E(U)^K$ \u51e0\u4e4e\u662f\u5fae\u4e0d\u8db3\u9053\u7684\uff0c\u53ea\u9700\u8981\u4ee5\u4e0b\u51e0\u884c\u3002\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// \u5728\u6211\u4eec\u8ba1\u7b97\u51fa\u8fd9\u4e2a\u5355\u5143\u7684\u603b\u80fd\u91cf\u540e\uff0c\u6211\u4eec\u5c06\u628a\u5b83\u6ce8\u518c\u5230\u5e2e\u52a9\u5668\u4e0a\u3002 \u5728\u6b64\u57fa\u7840\u4e0a\uff0c\u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u8ba1\u7b97\u51fa\u6240\u9700\u7684\u6570\u91cf\uff0c\u5373\u6b8b\u5dee\u503c\u548c\u5b83\u4eec\u5728\u8bc4\u4f30\u70b9\u7684\u96c5\u5404\u5e03\u7cfb\u6570\u3002\u548c\u4ee5\u524d\u4e00\u6837\uff0c\u725b\u987f\u7684\u53f3\u624b\u8fb9\u9700\u8981\u662f\u6b8b\u5dee\u7684\u8d1f\u6570\u3002\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// \u4e0e\u524d\u4e24\u4e2a\u51fd\u6570\u4e00\u6837\uff0c\u51fd\u6570\u7684\u5269\u4f59\u90e8\u5206\u4e0e\u4e4b\u524d\u4e00\u6837\u3002\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// \u89e3\u7b97\u51fd\u6570\u4e0e  step-15  \u4e2d\u4f7f\u7528\u7684\u76f8\u540c\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::solve() \n  { \n    SolverControl            solver_control(system_rhs.size(), \n                                 system_rhs.l2_norm() * 1e-6); \n    SolverCG<Vector<double>> solver(solver_control); \n\n    PreconditionSSOR<SparseMatrix<double>> preconditioner; \n    preconditioner.initialize(system_matrix, 1.2); \n\n    solver.solve(system_matrix, newton_update, system_rhs, preconditioner); \n\n    hanging_node_constraints.distribute(newton_update); \n\n    const double alpha = determine_step_length(); \n    current_solution.add(alpha, newton_update); \n  } \n// @sect4{MinimalSurfaceProblem::refine_mesh}  \n\n//\u81ea step-15 \u4ee5\u6765\uff0c\u5728\u7f51\u683c\u7ec6\u5316\u7a0b\u5e8f\u548c\u9002\u5e94\u6027\u7f51\u683c\u4e4b\u95f4\u7684\u89e3\u51b3\u65b9\u6848\u7684\u8f6c\u79fb\u65b9\u9762\u6ca1\u6709\u4efb\u4f55\u53d8\u5316\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::refine_mesh() \n  { \n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n\n    KellyErrorEstimator<dim>::estimate( \n      dof_handler, \n      QGauss<dim - 1>(fe.degree + 1), \n      std::map<types::boundary_id, const Function<dim> *>(), \n      current_solution, \n      estimated_error_per_cell); \n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    estimated_error_per_cell, \n                                                    0.3, \n                                                    0.03); \n\n    triangulation.prepare_coarsening_and_refinement(); \n    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// \u8fb9\u754c\u6761\u4ef6\u7684\u9009\u62e9\u4ecd\u7136\u4e0e step-15 \u76f8\u540c ...\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// ...\u5c31\u50cf\u5728\u6c42\u89e3\u8fed\u4ee3\u8fc7\u7a0b\u4e2d\u7528\u6765\u8ba1\u7b97\u6b8b\u5dee\u7684\u51fd\u6570\u4e00\u6837\u3002\u5982\u679c\u771f\u7684\u9700\u8981\uff0c\u6211\u4eec\u53ef\u4ee5\u7528\u80fd\u91cf\u51fd\u6570\u7684\u5fae\u5206\u6765\u4ee3\u66ff\u5b83\uff0c\u4f46\u662f\u4e3a\u4e86\u7b80\u5355\u8d77\u89c1\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u53ea\u662f\u7b80\u5355\u5730\u590d\u5236\u6211\u4eec\u5728 step-15 \u4e2d\u5df2\u7ecf\u6709\u7684\u4e1c\u897f\u3002\n\n  template <int dim> \n  double MinimalSurfaceProblem<dim>::compute_residual(const double alpha) const \n  { \n    Vector<double> residual(dof_handler.n_dofs()); \n\n    Vector<double> evaluation_point(dof_handler.n_dofs()); \n    evaluation_point = current_solution; \n    evaluation_point.add(alpha, newton_update); \n\n    const QGauss<dim> quadrature_formula(fe.degree + 1); \n    FEValues<dim>     fe_values(fe, \n                            quadrature_formula, \n                            update_gradients | update_quadrature_points | \n                              update_JxW_values); \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    Vector<double>              cell_residual(dofs_per_cell); \n    std::vector<Tensor<1, dim>> gradients(n_q_points); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        cell_residual = 0; \n        fe_values.reinit(cell); \n\n        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// \u975e\u7ebf\u6027\u8fed\u4ee3\u7a0b\u5e8f\u7684\u6b65\u957f\uff08\u6216\u6b20\u677e\u7cfb\u6570\uff09\u7684\u9009\u62e9\u4ecd\u7136\u56fa\u5b9a\u5728  step-15  \u4e2d\u9009\u62e9\u548c\u8ba8\u8bba\u7684\u503c\u3002\n\n  template <int dim> \n  double MinimalSurfaceProblem<dim>::determine_step_length() const \n  { \n    return 0.1; \n  } \n\n//  @sect4{MinimalSurfaceProblem::output_results}  \n\n// \u4ece`run()`\u8c03\u7528\u7684\u6700\u540e\u4e00\u4e2a\u51fd\u6570\u4ee5\u56fe\u5f62\u5f62\u5f0f\u8f93\u51fa\u5f53\u524d\u7684\u89e3\u51b3\u65b9\u6848\uff08\u548c\u725b\u987f\u66f4\u65b0\uff09\uff0c\u4f5c\u4e3aVTU\u6587\u4ef6\u3002\u5b83\u4e0e\u4e4b\u524d\u6559\u7a0b\u4e2d\u4f7f\u7528\u7684\u5b8c\u5168\u76f8\u540c\u3002\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::output_results( \n    const unsigned int refinement_cycle) const \n  { \n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(current_solution, \"solution\"); \n    data_out.add_data_vector(newton_update, \"update\"); \n    data_out.build_patches(); \n\n    const std::string filename = \n      \"solution-\" + Utilities::int_to_string(refinement_cycle, 2) + \".vtu\"; \n    std::ofstream output(filename); \n    data_out.write_vtu(output); \n  } \n// @sect4{MinimalSurfaceProblem::run}  \n\n// \u5728\u8fd0\u884c\u51fd\u6570\u4e2d\uff0c\u5927\u90e8\u5206\u5185\u5bb9\u4e0e\u6700\u521d\u5728  step-15  \u4e2d\u5b9e\u73b0\u7684\u76f8\u540c\u3002\u552f\u4e00\u53ef\u4ee5\u89c2\u5bdf\u5230\u7684\u53d8\u5316\u662f\uff0c\u6211\u4eec\u73b0\u5728\u53ef\u4ee5\uff08\u901a\u8fc7\u53c2\u6570\u6587\u4ef6\uff09\u9009\u62e9\u7cfb\u7edf\u6b8b\u5dee\u7684\u6700\u7ec8\u53ef\u63a5\u53d7\u7684\u516c\u5dee\u662f\u4ec0\u4e48\uff0c\u5e76\u4e14\u6211\u4eec\u53ef\u4ee5\u9009\u62e9\u6211\u4eec\u5e0c\u671b\u5229\u7528\u7684\u88c5\u914d\u65b9\u6cd5\u3002\u4e3a\u4e86\u4f7f\u7b2c\u4e8c\u4e2a\u9009\u62e9\u660e\u786e\uff0c\u6211\u4eec\u5411\u63a7\u5236\u53f0\u8f93\u51fa\u4e00\u4e9b\u4fe1\u606f\uff0c\u8868\u660e\u9009\u62e9\u3002\u7531\u4e8e\u6211\u4eec\u5bf9\u6bd4\u8f83\u4e09\u79cd\u65b9\u6cd5\u4e2d\u6bcf\u4e00\u79cd\u7684\u88c5\u914d\u65f6\u95f4\u611f\u5174\u8da3\uff0c\u6211\u4eec\u8fd8\u6dfb\u52a0\u4e86\u4e00\u4e2a\u8ba1\u65f6\u5668\uff0c\u8ddf\u8e2a\u88c5\u914d\u8fc7\u7a0b\u4e2d\u6240\u82b1\u8d39\u7684\u65f6\u95f4\u3002\u6211\u4eec\u8fd8\u8ddf\u8e2a\u4e86\u89e3\u51b3\u7ebf\u6027\u7cfb\u7edf\u6240\u9700\u7684\u65f6\u95f4\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u5c06\u8fd9\u4e9b\u6570\u5b57\u4e0e\u901a\u5e38\u9700\u8981\u6700\u957f\u65f6\u95f4\u6267\u884c\u7684\u90a3\u90e8\u5206\u4ee3\u7801\u8fdb\u884c\u5bf9\u6bd4\u3002\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// \u6700\u540e\u662f\u4e3b\u51fd\u6570\u3002\u5b83\u9075\u5faa\u5927\u591a\u6570\u5176\u4ed6\u4e3b\u51fd\u6570\u7684\u65b9\u6848\uff0c\u4f46\u6709\u4e24\u4e2a\u660e\u663e\u7684\u4f8b\u5916\u3002\n\n// - \u6211\u4eec\u8c03\u7528 Utilities::MPI::MPI_InitFinalize \uff0c\u4ee5\u4fbf\uff08\u901a\u8fc7\u4e00\u4e2a\u9690\u85cf\u7684\u9ed8\u8ba4\u53c2\u6570\uff09\u8bbe\u7f6e\u4f7f\u7528\u591a\u7ebf\u7a0b\u4efb\u52a1\u6267\u884c\u7684\u7ebf\u7a0b\u6570\u3002\n\n// - \u6211\u4eec\u8fd8\u6709\u51e0\u884c\u4e13\u95e8\u7528\u4e8e\u8bfb\u53d6\u6216\u521d\u59cb\u5316\u7528\u6237\u5b9a\u4e49\u7684\u53c2\u6570\uff0c\u8fd9\u4e9b\u53c2\u6570\u5c06\u5728\u7a0b\u5e8f\u6267\u884c\u8fc7\u7a0b\u4e2d\u88ab\u8003\u8651\u3002\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) 2011  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n#include \"tester.h\"\r\n#include <dlib/svm.h>\r\n#include <dlib/data_io.h>\r\n#include \"create_iris_datafile.h\"\r\n#include <vector>\r\n#include <sstream>\r\n\r\nnamespace  \r\n{\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n    dlib::logger dlog(\"test.svm_multiclass_trainer\");\r\n\r\n\r\n    class test_svm_multiclass_trainer : public tester\r\n    {\r\n        /*!\r\n            WHAT THIS OBJECT REPRESENTS\r\n                This object represents a unit test.  When it is constructed\r\n                it adds itself into the testing framework.\r\n        !*/\r\n    public:\r\n        test_svm_multiclass_trainer (\r\n        ) :\r\n            tester (\r\n                \"test_svm_multiclass_trainer\",       // the command line argument name for this test\r\n                \"Run tests on the svm_multiclass_linear_trainer stuff.\", // the command line argument description\r\n                0                     // the number of command line arguments for this test\r\n            )\r\n        {\r\n        }\r\n\r\n\r\n        template <typename sample_type>\r\n        void run_test()\r\n        {\r\n            print_spinner();\r\n\r\n            typedef typename sample_type::value_type::second_type scalar_type;\r\n\r\n            std::vector<sample_type> samples;\r\n            std::vector<scalar_type> labels;\r\n\r\n            load_libsvm_formatted_data(\"iris.scale\",samples, labels);\r\n\r\n            DLIB_TEST(samples.size() == 150);\r\n            DLIB_TEST(labels.size() == 150);\r\n\r\n            typedef sparse_linear_kernel<sample_type> kernel_type;\r\n            svm_multiclass_linear_trainer<kernel_type> trainer;\r\n            trainer.set_c(100);\r\n\r\n            randomize_samples(samples, labels);\r\n            matrix<double> cv = cross_validate_multiclass_trainer(trainer, samples, labels, 4);\r\n\r\n            dlog << LINFO << \"confusion matrix: \\n\" << cv;\r\n            const scalar_type cv_accuracy = sum(diag(cv))/sum(cv);\r\n            dlog << LINFO << \"cv accuracy: \" << cv_accuracy;\r\n            DLIB_TEST(cv_accuracy > 0.97);\r\n\r\n\r\n\r\n\r\n            {\r\n                print_spinner();\r\n                typedef matrix<scalar_type,0,1> dsample_type;\r\n                std::vector<dsample_type> dsamples = sparse_to_dense(samples);\r\n                DLIB_TEST(dsamples.size() == 150);\r\n\r\n                typedef linear_kernel<dsample_type> kernel_type;\r\n                svm_multiclass_linear_trainer<kernel_type> trainer;\r\n                trainer.set_c(100);\r\n\r\n                cv = cross_validate_multiclass_trainer(trainer, dsamples, labels, 4);\r\n\r\n                dlog << LINFO << \"dense confusion matrix: \\n\" << cv;\r\n                const scalar_type cv_accuracy = sum(diag(cv))/sum(cv);\r\n                dlog << LINFO << \"dense cv accuracy: \" << cv_accuracy;\r\n                DLIB_TEST(cv_accuracy > 0.97);\r\n            }\r\n\r\n        }\r\n\r\n\r\n\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            print_spinner();\r\n            create_iris_datafile();\r\n\r\n            run_test<std::map<unsigned int, double> >();\r\n            run_test<std::map<unsigned int, float> >();\r\n            run_test<std::vector<std::pair<unsigned int, float> > >();\r\n            run_test<std::vector<std::pair<unsigned long, double> > >();\r\n        }\r\n    };\r\n\r\n    test_svm_multiclass_trainer a;\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "1d66e79bc0bdd22eefd8e5b5214bf8c42ceadc34", "size": 3405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dlib/test/svm_multiclass_linear.cpp", "max_stars_repo_name": "cpearce/HARM", "max_stars_repo_head_hexsha": "1e629099bbaa0203b19fe9007a71d9ab9c938be0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-10-11T18:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-11T18:37:52.000Z", "max_issues_repo_path": "src/dlib/test/svm_multiclass_linear.cpp", "max_issues_repo_name": "wsgan001/HARM", "max_issues_repo_head_hexsha": "1e629099bbaa0203b19fe9007a71d9ab9c938be0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-27T22:58:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-28T04:46:52.000Z", "max_forks_repo_path": "src/dlib/test/svm_multiclass_linear.cpp", "max_forks_repo_name": "wsgan001/HARM", "max_forks_repo_head_hexsha": "1e629099bbaa0203b19fe9007a71d9ab9c938be0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-19T06:15:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-02T11:11:57.000Z", "avg_line_length": 31.2385321101, "max_line_length": 114, "alphanum_fraction": 0.5580029369, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5622427094717733}}
{"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": "#pragma once\n#include \"dofs.hpp\"\n#include <Eigen/Core>\n#include <igl/boundary_facets.h>\n#include <igl/colon.h>\n#include <igl/setdiff.h>\n#include <igl/unique.h>\n\n//! Finds the boundary and interior vertices, and evaluates\n//! the function g on the boundary vertices.\n//!\n//! @param[out] u should be of size <number of vertices>. At the end:\n//!             u(index) = g(vertices(index))  for each boundary index.\n//! @param[out] interiorDofs the list of dofs that are not on the boundary.\n//! @param[in]  quadraticDofs\n//! @param[in]  g the boundary value function g.\nvoid setDirichletBoundary(Eigen::VectorXd &u,\n                          Eigen::VectorXi &interiorDofs,\n                          const QDofs &    quadraticDofs,\n                          const std::function<double(double, double)> &g) {\n\t//get dofs\n\tEigen::MatrixXi qdof;\n\tint             N = quadraticDofs.get_dofs(qdof);\n\n\t// Find boundary edges\n\tEigen::MatrixXi boundaryEdges;\n\tEigen::MatrixXi triangles = qdof.block(0, 0, qdof.rows(), 3);\n\tigl::boundary_facets(triangles, boundaryEdges);\n\n\t// Find dof indices corresponding to boundary edges\n\tEigen::VectorXi boundaryEdgeIndices(boundaryEdges.rows());\n\tauto            edgemap = quadraticDofs.vertex2edge;\n\tfor (int k = 0; k < boundaryEdges.rows(); k++) {\n\t\tauto edge = boundaryEdges.row(k);\n\t\tauto v0   = edge(0);\n\t\tauto v1   = edge(1);\n\t\t// get edges connected to these vertices\n\t\tauto edgesv0 = (*edgemap.find(v0)).second;\n\t\tauto edgesv1 = (*edgemap.find(v1)).second;\n\t\t// traverse them and find edge (intersection)\n\t\tfor (auto e0 : edgesv0) {\n\t\t\tfor (auto e1 : edgesv1) {\n\t\t\t\tif (e0 == e1) { //found edge!\n\t\t\t\t\t// mark as boundary\n\t\t\t\t\tboundaryEdgeIndices(k) = e0;\n\t\t\t\t\tbreak;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Find boundary vertices\n\tEigen::VectorXi boundaryVertexIndices, IA, IC;\n\tigl::unique(boundaryEdges, boundaryVertexIndices, IA, IC);\n\n\t// set boundary data\n\tauto nodes = quadraticDofs.nodes;\n\tfor (int i = 0; i < boundaryVertexIndices.size(); ++i) {\n\t\tconst int   index = boundaryVertexIndices(i);\n\t\tconst auto &x     = nodes.row(index);\n\t\tu(index)          = g(x(0), x(1));\n\t}\n\n\t// Combine this information to get boundary dofs\n\tEigen::VectorXi boundaryDofs(boundaryEdges.rows() + boundaryVertexIndices.rows());\n\tboundaryDofs << boundaryVertexIndices, boundaryEdgeIndices;\n\t// Get interior dofs\n\tEigen::VectorXi allIndices;\n\tigl::colon<int>(0, N - 1, allIndices);\n\tigl::setdiff(allIndices, boundaryDofs, interiorDofs, IA);\n}\n", "meta": {"hexsha": "36eab905da18bf9895931764f9692c18a5ec36e5", "size": 2460, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/dirichlet_boundary.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series3/2d-poissonqFEM/dirichlet_boundary.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series3/2d-poissonqFEM/dirichlet_boundary.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.698630137, "max_line_length": 83, "alphanum_fraction": 0.662195122, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.5622426959525143}}
{"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": "#include <boost/math/special_functions/ellint_rj.hpp>\n", "meta": {"hexsha": "55227ee43b163f35a0dd7ce1f4d386c928a80923", "size": 54, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_special_functions_ellint_rj.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_special_functions_ellint_rj.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_special_functions_ellint_rj.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 27.0, "max_line_length": 53, "alphanum_fraction": 0.8333333333, "num_tokens": 14, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5622310964284616}}
{"text": "#include <igl/copyleft/marching_cubes.h>\n#include <igl/signed_distance.h>\n#include <igl/read_triangle_mesh.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <Eigen/Core>\n#include <iostream>\n\n#include \"tutorial_shared_path.h\"\n\nint main(int argc, char * argv[])\n{\n  using namespace Eigen;\n  using namespace std;\n  using namespace igl;\n  MatrixXi F;\n  MatrixXd V;\n  // Read in inputs as double precision floating point meshes\n  read_triangle_mesh(\n      TUTORIAL_SHARED_PATH \"/armadillo.obj\",V,F);\n  // number of vertices on the largest side\n  const int s = 50;\n  const RowVector3d Vmin = V.colwise().minCoeff();\n  const RowVector3d Vmax = V.colwise().maxCoeff();\n  const double h = (Vmax-Vmin).maxCoeff()/(double)s;\n  const RowVector3i res = (s*((Vmax-Vmin)/(Vmax-Vmin).maxCoeff())).cast<int>();\n  // create grid\n  cout<<\"Creating grid...\"<<endl;\n  MatrixXd GV(res(0)*res(1)*res(2),3);\n  for(int zi = 0;zi<res(2);zi++)\n  {\n    const auto lerp = [&](const int di, const int d)->double\n      {return Vmin(d)+(double)di/(double)(res(d)-1)*(Vmax(d)-Vmin(d));};\n    const double z = lerp(zi,2);\n    for(int yi = 0;yi<res(1);yi++)\n    {\n      const double y = lerp(yi,1);\n      for(int xi = 0;xi<res(0);xi++)\n      {\n        const double x = lerp(xi,0);\n        GV.row(xi+res(0)*(yi + res(1)*zi)) = RowVector3d(x,y,z);\n      }\n    }\n  }\n  // compute values\n  cout<<\"Computing distances...\"<<endl;\n  VectorXd S,B;\n  {\n    VectorXi I;\n    MatrixXd C,N;\n    signed_distance(GV,V,F,SIGNED_DISTANCE_TYPE_PSEUDONORMAL,S,I,C,N);\n    // Convert distances to binary inside-outside data --> aliasing artifacts\n    B = S;\n    for_each(B.data(),B.data()+B.size(),[](double& b){b=(b>0?1:(b<0?-1:0));});\n  }\n  cout<<\"Marching cubes...\"<<endl;\n  MatrixXd SV,BV;\n  MatrixXi SF,BF;\n  igl::copyleft::marching_cubes(S,GV,res(0),res(1),res(2),SV,SF);\n  igl::copyleft::marching_cubes(B,GV,res(0),res(1),res(2),BV,BF);\n\n  cout<<R\"(Usage:\n'1'  Show original mesh.\n'2'  Show marching cubes contour of signed distance.\n'3'  Show marching cubes contour of indicator function.\n)\";\n  igl::opengl::glfw::Viewer viewer;\n  viewer.data().set_mesh(SV,SF);\n  viewer.callback_key_down =\n    [&](igl::opengl::glfw::Viewer & viewer, unsigned char key, int mod)->bool\n    {\n      switch(key)\n      {\n        default:\n          return false;\n        case '1':\n          viewer.data().clear();\n          viewer.data().set_mesh(V,F);\n          break;\n        case '2':\n          viewer.data().clear();\n          viewer.data().set_mesh(SV,SF);\n          break;\n        case '3':\n          viewer.data().clear();\n          viewer.data().set_mesh(BV,BF);\n          break;\n      }\n      viewer.data().set_face_based(true);\n      return true;\n    };\n  viewer.launch();\n}\n", "meta": {"hexsha": "e9f85c817f02000918ec69d02792571623e4649e", "size": 2715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/tutorial/705_MarchingCubes/main.cpp", "max_stars_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_stars_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 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": "isometric-deformation/ext/libigl/tutorial/705_MarchingCubes/main.cpp", "max_issues_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_issues_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 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": "isometric-deformation/ext/libigl/tutorial/705_MarchingCubes/main.cpp", "max_forks_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_forks_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 29.1935483871, "max_line_length": 79, "alphanum_fraction": 0.6051565378, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5622310947727216}}
{"text": "#include <iostream>\n#include <unordered_set>\n\n#include <Spectra/MatOp/SparseSymMatProd.h>\n#include <Spectra/SymEigsSolver.h>\n#include <boost/dynamic_bitset.hpp>\n\n#include \"edlib/Basis/BasisFull.hpp\"\n#include \"edlib/Basis/BasisFullZ2.hpp\"\n#include \"edlib/Basis/ToOriginalBasis.hpp\"\n#include \"edlib/EDP/ConstructSparseMat.hpp\"\n#include \"edlib/Op/NodeMV.hpp\"\n\n#include \"utils.hpp\"\n#include \"XXZ.hpp\"\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\nusing namespace Eigen;\nusing namespace edlib;\n\nconstexpr uint32_t MAX_N = 14;\n\ntemplate<typename UINT>\nclass OpenTFI\n{\nprivate:\n\tconst edlib::AbstractBasis<UINT>& basis_;\n\tdouble J_;\n\tdouble h_;\n\t\npublic:\n\tOpenTFI(const edlib::AbstractBasis<UINT>& basis, double J, double h)\n\t\t: basis_{basis}, J_{J}, h_{h}\n\t{\n\t}\n\n\tstd::map<int, double> getCol(UINT n) const\n\t{\n\t\tstd::map<int, double> m;\n\t\tconst uint32_t N = basis_.getN();\n\n\t\tUINT a = basis_.getNthRep(n);\n\t\tconst boost::dynamic_bitset<> bs(N, a);\n\n\t\tfor(uint32_t i = 0; i < N-1; ++i)\n\t\t{\n\t\t\tint zz = (1-2*bs[i])*(1-2*bs[i+1]);\n\n\t\t\tm[n] += -J_*zz;\n\t\t\t\n\t\t\tUINT s = a;\n\t\t\ts ^= basis_.mask({i});\n\n\t\t\tint bidx;\n\t\t\tdouble coeff;\n\n\t\t\tstd::tie(bidx, coeff) = basis_.hamiltonianCoeff(s, n);\n\t\t\t\n\t\t\tif(bidx >= 0)\n\t\t\t{\n\t\t\t\tm[bidx] += -h_*coeff;\n\t\t\t}\n\t\t}\n\t\treturn m;\n\t}\n\n\tstd::map<int, double> operator()(UINT n) const \n\t{\n\t\treturn getCol(n);\n\t}\n};\n\n\nTEST_CASE(\"Test BasisFull and BasisFullZ2 using the transverse field Ising model\", \"[basisfull]\")\n{\n\tdouble h = 0.5;\n\tfor(int N = 4; N <= MAX_N; N += 2)\n\t{\n\t\tBasisFull<uint32_t> basisFull(N);\n\t\tBasisFullZ2<uint32_t> basisFullP(N, 1);\n\t\tBasisFullZ2<uint32_t> basisFullM(N, -1);\n\n\t\tauto hamFull = OpenTFI(basisFull, 1.0, h);\n\t\tauto hamFullP = OpenTFI(basisFullP, 1.0, h);\n\t\tauto hamFullM = OpenTFI(basisFullM, 1.0, h);\n\n\t\t\n\t\tVectorXd evFull;\n\t\tVectorXd evFullP;\n\t\tVectorXd evFullM;\n\n\t\t{\n\t\t\tconst auto dim = basisFull.getDim();\n\n\t\t\tNodeMV mv(dim, 0, dim, hamFull);\n\n\t\t\tSpectra::SymEigsSolver<double, Spectra::SMALLEST_ALGE, NodeMV> eigs(&mv, 2, 6);\n\t\t\teigs.init();\n\t\t\teigs.compute(10000, 1e-12, Spectra::SMALLEST_ALGE);\n\t\t\tif(eigs.info() != Spectra::SUCCESSFUL)\n\t\t\t\tREQUIRE(false);\n\t\t\tevFull = eigs.eigenvalues();\n\t\t}\n\n\t\t{\n\t\t\tconst auto dim = basisFullP.getDim();\n\n\t\t\tNodeMV mv(dim, 0, dim, hamFullP);\n\n\t\t\tSpectra::SymEigsSolver<double, Spectra::SMALLEST_ALGE, NodeMV> eigs(&mv, 2, 6);\n\t\t\teigs.init();\n\t\t\teigs.compute(10000, 1e-12, Spectra::SMALLEST_ALGE);\n\t\t\tif(eigs.info() != Spectra::SUCCESSFUL)\n\t\t\t\tREQUIRE(false);\n\t\t\tevFullP = eigs.eigenvalues();\n\t\t}\n\n\t\t{\n\t\t\tconst auto dim = basisFullM.getDim();\n\n\t\t\tNodeMV mv(dim, 0, dim, hamFullM);\n\n\t\t\tSpectra::SymEigsSolver<double, Spectra::SMALLEST_ALGE, NodeMV> eigs(&mv, 2, 6);\n\t\t\teigs.init();\n\t\t\teigs.compute(10000, 1e-12, Spectra::SMALLEST_ALGE);\n\t\t\tif(eigs.info() != Spectra::SUCCESSFUL)\n\t\t\t\tREQUIRE(false);\n\t\t\tevFullM = eigs.eigenvalues();\n\t\t}\n\t\tusing Catch::WithinAbs;\n\t\tREQUIRE_THAT(evFull(0), WithinAbs(evFullP(0), 1e-8));\n\t\tREQUIRE_THAT(evFull(1), WithinAbs(evFullM(0), 1e-8));\n\t}\n}\n", "meta": {"hexsha": "bc3563aaa1beed7c33c12255c6bd703f69b36a35", "size": 2971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_basisfull.cpp", "max_stars_repo_name": "chaeyeunpark/ExactDiagonalization", "max_stars_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T08:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:47:05.000Z", "max_issues_repo_path": "tests/test_basisfull.cpp", "max_issues_repo_name": "chaeyeunpark/ExactDiagonalization", "max_issues_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T19:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T19:02:14.000Z", "max_forks_repo_path": "tests/test_basisfull.cpp", "max_forks_repo_name": "chaeyeunpark/ExactDiagonalization", "max_forks_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-22T18:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T18:59:11.000Z", "avg_line_length": 21.6861313869, "max_line_length": 97, "alphanum_fraction": 0.6610568832, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162774, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5622310898771063}}
{"text": "/*\n * exprtk_expression.hpp\n *\n *  Created on: Jul 6, 2015\n *      Author: dimitar\n */\n\n#include \"expression.hpp\"\n#include <exprtk/exprtk.hpp>\n#include \"context.hpp\"\n#include <list>\n#include <boost/noncopyable.hpp>\n#include <boost/lexical_cast.hpp>\n#include <cmath>\n\n#ifndef EXPRTK_EXPRESSION_HPP_\n#define EXPRTK_EXPRESSION_HPP_\n\nnamespace kaluun {\n\nnamespace exprtk{\n\ntemplate<class Context>\nstruct expression : public boost::noncopyable{\n\ttypedef double \t\t\t\t\t\t\t\t\t\tresult_type;\n\ttypedef ::exprtk::symbol_table<result_type> \t\tsymbol_table_t;\n\ttypedef ::exprtk::expression<result_type> \t\t\texpression_t;\n\ttypedef ::exprtk::parser<result_type> \t\t\t\tparser_t;\n\n\tstruct variable_function: public ::exprtk::ifunction<result_type> , boost::noncopyable {\n\t\tconst std::string&\t\t\t\tvariable_;\n\t\tContext*\t\t\t\t\t\tcontext_;\n\n\t\tvariable_function(const std::string& variable): ::exprtk::ifunction<result_type>(0), variable_(variable), context_(nullptr) { }\n\t\tinline void set_context(Context* target){\n\t\t\tcontext_ = target;\n\t\t}\n\t\tinline result_type operator()() {\n\t\t\tif(context_ != NULL)\n\t\t\t\treturn boost::lexical_cast<result_type>(context_->operator[](variable_).to_string());\n\t\t\telse\n\t\t\t\tthrow std::logic_error(\"context has not been set\");\n\t\t}\n\t};\n\n\tstruct unknown_symbol_resolver_helper: public parser_t::unknown_symbol_resolver , boost::noncopyable {\n\t\tstd::unordered_set<std::string>& operands_;\n\n\t\tunknown_symbol_resolver_helper(std::unordered_set<std::string>& operands):operands_(operands){}\n\t\tvirtual bool process(const std::string& unknown_symbol, usr_symbol_type& st, result_type & default_value, std::string& error_message) {\n\t\t\tst = e_usr_variable_type;\n\t\t\tdefault_value = 13;\n\t\t\terror_message = \"\";\n\t\t\toperands_.insert(unknown_symbol);\n\t\t\treturn true;\n\t\t}\n\t};\n\n\tsymbol_table_t \t\t\t\t\t\t\tsymbol_table_;\n\texpression_t \t\t\t\t\t\t\texpression_;\n\tstd::list<variable_function>\t\t\tfunctors_;\n\tstd::unordered_set<std::string> \t\tvariables_;\n\n\texpression() {\n\t\texpression_.register_symbol_table(symbol_table_);\n\t}\n\n\tstd::string operator()(Context& ctx) {\n\t\tfor(auto itFunc = functors_.begin(); itFunc != functors_.end(); itFunc++)\n\t\t\titFunc->set_context(&ctx);\n\t\texpression::result_type res = expression_.value();\n\t\treturn boost::lexical_cast<std::string>(res);\n\t}\n\n\ttemplate<class Holder>\n\tstatic void parse(Holder expression_string, expression& expr) {\n\t\tunknown_symbol_resolver_helper \t\tresolver(expr.variables_);\n\t\texpression::parser_t \t\t\t\t\tparser;\n\t\texpression_t \t\t\t\t\t\texpression1;\n\t\tsymbol_table_t \t\t\t\t\t\tsymbol_table1;\n\n\t\texpression1.register_symbol_table(symbol_table1);\n\t\tparser.enable_unknown_symbol_resolver(&resolver);\n\n\t\tparser.compile(std::string(expression_string), expression1); //first run\n\t\tfor(auto it = expr.variables_.begin(); it != expr.variables_.end(); it++){\n\t\t\texpr.functors_.emplace_back(*it);\n\t\t\texpr.symbol_table_.add_function(*it, expr.functors_.back());\n\t\t}\n\t\tparser.disable_unknown_symbol_resolver();\n\t\tparser.compile(expression_string, expr.expression_);\n\t}\n\n\tstatic void parse(const std::string& expression_string, expression& expr) {\n\t\tunknown_symbol_resolver_helper \t\tresolver(expr.variables_);\n\t\texpression::parser_t \t\t\t\t\tparser;\n\t\texpression_t \t\t\t\t\t\texpression1;\n\t\tsymbol_table_t \t\t\t\t\t\tsymbol_table1;\n\n\t\texpression1.register_symbol_table(symbol_table1);\n\t\tparser.enable_unknown_symbol_resolver(&resolver);\n\n\t\tparser.compile(expression_string, expression1); //first run\n\t\tfor(auto it = expr.variables_.begin(); it != expr.variables_.end(); it++){\n\t\t\texpr.functors_.emplace_back(*it);\n\t\t\texpr.symbol_table_.add_function(*it, expr.functors_.back());\n\t\t}\n\t\tparser.disable_unknown_symbol_resolver();\n\t\tparser.compile(expression_string, expr.expression_);\n\t}\n\n};\n\ntemplate<class Context>\nstruct condition : public boost::noncopyable{\n\ttypedef double \t\t\t\t\t\t\t\t\t\tresult_type;\n\ttypedef ::exprtk::symbol_table<result_type> \t\tsymbol_table_t;\n\ttypedef ::exprtk::expression<result_type> \t\t\texpression_t;\n\ttypedef ::exprtk::parser<result_type> \t\t\t\tparser_t;\n\n\tstruct variable_function: public ::exprtk::ifunction<result_type> , boost::noncopyable{\n\t\tconst std::string&\t\t\t\tvariable_;\n\t\tContext*\t\t\t\t\t\tcontext_;\n\n\t\tvariable_function(const std::string& variable): ::exprtk::ifunction<result_type>(0), variable_(variable), context_(nullptr) { }\n\n\t\tinline void set_context(Context* target){\n\t\t\tcontext_ = target;\n\t\t}\n\t\tinline result_type operator()() {\n\t\t\tif(context_ != NULL)\n\t\t\t\treturn std::stod(context_->operator[](variable_).to_string());\n\t\t\telse\n\t\t\t\tthrow std::logic_error(\"context has not been set\");\n\t\t}\n\t};\n\n\tstruct unknown_symbol_resolver_helper: public parser_t::unknown_symbol_resolver , boost::noncopyable {\n\t\tstd::unordered_set<std::string>& operands_;\n\n\t\tunknown_symbol_resolver_helper(std::unordered_set<std::string>& operands):operands_(operands){}\n\t\tvirtual bool process(const std::string& unknown_symbol, usr_symbol_type& st, result_type & default_value, std::string& error_message) {\n\t\t\tst = e_usr_variable_type;\n\t\t\tdefault_value = 13;\n\t\t\terror_message = \"\";\n\t\t\toperands_.insert(unknown_symbol);\n\t\t\treturn true;\n\t\t}\n\t};\n\n\tsymbol_table_t \t\t\t\t\t\t\tsymbol_table_;\n\texpression_t \t\t\t\t\t\t\texpression_;\n\tstd::list<variable_function>\t\t\tfunctors_;\n\tstd::unordered_set<std::string> \t\tvariables_;\n\n\tcondition() {\n\t\texpression_.register_symbol_table(symbol_table_);\n\t}\n\n\tbool operator()(Context& ctx) {\n\t\tfor(auto itFunc = functors_.begin(); itFunc != functors_.end(); itFunc++)\n\t\t\titFunc->set_context(&ctx);\n\t\treturn expression_.operator bool();\n\t}\n\n\ttemplate<class Holder>\n\tstatic void parse(Holder expression_string, condition& expr) {\n\t\tunknown_symbol_resolver_helper \t\tresolver(expr.variables_);\n\t\tcondition::parser_t \t\t\t\tparser;\n\t\texpression_t \t\t\t\t\t\texpression1;\n\t\tsymbol_table_t \t\t\t\t\t\tsymbol_table1;\n\n\t\texpression1.register_symbol_table(symbol_table1);\n\t\tparser.enable_unknown_symbol_resolver(&resolver);\n\n\t\tparser.compile(std::string(expression_string), expression1); //first run\n\t\tfor(auto it = expr.variables_.begin(); it != expr.variables_.end(); it++){\n\t\t\t//variable_function functor(expr, *it);\n\t\t\texpr.functors_.emplace_back(*it);\n\t\t\texpr.symbol_table_.add_function(*it, expr.functors_.back());\n\t\t}\n\t\tparser.disable_unknown_symbol_resolver();\n\t\tparser.compile(expression_string, expr.expression_);\n\t}\n\n\tstatic void parse(const std::string& expression_string, condition& expr) {\n\t\tunknown_symbol_resolver_helper \t\tresolver(expr.variables_);\n\t\tcondition::parser_t \t\t\t\tparser;\n\t\texpression_t \t\t\t\t\t\texpression1;\n\t\tsymbol_table_t \t\t\t\t\t\tsymbol_table1;\n\n\t\texpression1.register_symbol_table(symbol_table1);\n\t\tparser.enable_unknown_symbol_resolver(&resolver);\n\n\t\tparser.compile(expression_string, expression1); //first run\n\t\tfor(auto it = expr.variables_.begin(); it != expr.variables_.end(); it++){\n\t\t\t//variable_function functor(expr, *it);\n\t\t\texpr.functors_.emplace_back(*it);\n\t\t\texpr.symbol_table_.add_function(*it, expr.functors_.back());\n\t\t}\n\t\tparser.disable_unknown_symbol_resolver();\n\t\tparser.compile(expression_string, expr.expression_);\n\t}\n\n}; } }\n\n#endif /* EXPRTK_EXPRESSION_HPP_ */\n", "meta": {"hexsha": "b5be64be3feef731a1e8081899bc25eaf735f91d", "size": 6996, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kaluun/exprtk_expression.hpp", "max_stars_repo_name": "dimitarm/kaluun", "max_stars_repo_head_hexsha": "1fd73fafcc2853f9cd2cebbc08dafef93e17ea28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-09T10:36:20.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-14T02:41:43.000Z", "max_issues_repo_path": "kaluun/exprtk_expression.hpp", "max_issues_repo_name": "dimitarm/kaluun", "max_issues_repo_head_hexsha": "1fd73fafcc2853f9cd2cebbc08dafef93e17ea28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kaluun/exprtk_expression.hpp", "max_forks_repo_name": "dimitarm/kaluun", "max_forks_repo_head_hexsha": "1fd73fafcc2853f9cd2cebbc08dafef93e17ea28", "max_forks_repo_licenses": ["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.6346153846, "max_line_length": 137, "alphanum_fraction": 0.739565466, "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5622310792580053}}
{"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": "//    |  /           |\n//    ' /   __| _` | __|  _ \\   __|\n//    . \\  |   (   | |   (   |\\__ \\.\n//   _|\\_\\_|  \\__,_|\\__|\\___/ ____/\n//                   Multi-Physics\n//\n//  License:\t\t BSD License\n//\t\t\t\t\t Kratos default license: kratos/license.txt\n//\n//  Main authors:    Michael Andre, https://github.com/msandre\n//\n\n// System includes\n\n// External includes\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n// Project includes\n#include \"utilities/geometrical_sensitivity_utility.h\"\n#include \"utilities/math_utils.h\"\n\nnamespace Kratos\n{\n\nGeometricalSensitivityUtility::GeometricalSensitivityUtility(const JacobianType& rJ, const ShapeFunctionsLocalGradientType& rDN_De)\n: mrJ(rJ), mrDN_De(rDN_De)\n{\n    KRATOS_TRY;\n\n    Initialize();\n    \n    KRATOS_CATCH(\"\");\n}\n\nvoid GeometricalSensitivityUtility::Initialize()\n{\n    KRATOS_TRY;\n\n    KRATOS_ERROR_IF(mrJ.size1() != mrJ.size2()) << \"Non-square Jacobian matrix.\" << std::endl;\n\n    KRATOS_ERROR_IF(mrJ.size2() != mrDN_De.size2())\n        << \"Jacobian local-coordinates size (\" << mrJ.size2()\n        << \") != shape function local-coordinates size(\" << mrDN_De.size2()\n        << \").\" << std::endl;\n\n    mCofactorJ = MathUtils<double>::CofactorMatrix(mrJ);\n    mDetJ = MathUtils<double>::DetMat(mrJ);\n\n    KRATOS_CATCH(\"\");\n}\n\nvoid GeometricalSensitivityUtility::CalculateSensitivity(ShapeParameter Deriv, double& rDetJ_Deriv, ShapeFunctionsGradientType& rDN_DX_Deriv) const\n{\n    KRATOS_TRY;\n\n    rDetJ_Deriv = CalculateDeterminantOfJacobianSensitivity(Deriv);\n\n    MatrixType cofactorJ_deriv = CalculateCofactorOfJacobianSensitivity(Deriv);\n    if (rDN_DX_Deriv.size1() != mrDN_De.size1() || rDN_DX_Deriv.size2() != mCofactorJ.size1())\n        rDN_DX_Deriv.resize(mrDN_De.size1(), mCofactorJ.size1());\n    noalias(rDN_DX_Deriv) = (1.0 / mDetJ) * prod(mrDN_De, trans(cofactorJ_deriv));\n    rDN_DX_Deriv += -(rDetJ_Deriv / (mDetJ * mDetJ)) * prod(mrDN_De, trans(mCofactorJ));\n\n    KRATOS_CATCH(\"\");\n}\n\ndouble GeometricalSensitivityUtility::CalculateDeterminantOfJacobianSensitivity(ShapeParameter Deriv) const\n{\n    return inner_prod(\n        row(mCofactorJ, Deriv.Direction),\n        row(mrDN_De, Deriv.NodeIndex));\n}\n\nGeometricalSensitivityUtility::MatrixType GeometricalSensitivityUtility::CalculateCofactorOfJacobianSensitivity(\n    ShapeParameter Deriv) const\n{\n    KRATOS_TRY;\n    MatrixType result(mrJ.size1(), mrJ.size2());\n\n    IndirectArrayType ia3(mrDN_De.size1());\n    for (std::size_t k = 0; k < ia3.size(); ++k)\n        ia3[k] = k;\n\n    for (unsigned i = 0; i < mrJ.size1(); ++i)\n    {\n        if (i == Deriv.Direction)\n        {\n            // Here the derivative is automatically zero.\n            for (unsigned j = 0; j < mrJ.size2(); ++j)\n                result(i, j) = 0.0;\n        }\n        else\n        {\n            // Decrement the coordinate index if it's greater than the deleted row.\n            IndexType i_coord_sub = (Deriv.Direction > i) ? Deriv.Direction - 1 : Deriv.Direction;\n            for (unsigned j = 0; j < mrJ.size2(); ++j)\n            {\n#ifdef KRATOS_USE_AMATRIX   // This macro definition is for the migration period and to be removed afterward please do not use it \n\t\t\t\tDenseVector<std::size_t> ia1(mrJ.size1() - 1), ia2(mrJ.size2() - 1);\n#else\n\t\t\t\tIndirectArrayType ia1(mrJ.size1() - 1), ia2(mrJ.size2() - 1);\n#endif // ifdef KRATOS_USE_AMATRIX\n\n                // Construct the Jacobian submatrix structure for the first minor.\n                unsigned i_sub = 0;\n                for (unsigned k = 0; k < mrJ.size1(); ++k)\n                    if (k != i)\n                        ia1(i_sub++) = k;\n\n                unsigned j_sub = 0;\n                for (unsigned k = 0; k < mrJ.size2(); ++k)\n                    if (k != j)\n                        ia2(j_sub++) = k;\n\n                const SubMatrixType sub_jacobian(mrJ, ia1, ia2);\n                const MatrixType cofactor_sub_jacobian = MathUtils<double>::CofactorMatrix(sub_jacobian);\n\n                // Construct the corresponding shape function local gradients\n                // submatrix.\n                const SubMatrixType sub_DN_De(mrDN_De, ia3, ia2);\n\n                const double first_minor_deriv = inner_prod(\n                    row(cofactor_sub_jacobian, i_coord_sub),\n                    row(sub_DN_De, Deriv.NodeIndex));\n\n                result(i, j) = ((i + j) % 2) ? -first_minor_deriv : first_minor_deriv;\n            }\n        }\n    }\n\n    return result;\n    KRATOS_CATCH(\"\");\n}\n\n} /* namespace Kratos.*/\n", "meta": {"hexsha": "e7acd87ef67007a7231b463232cb9e4cc33f8c8f", "size": 4473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kratos/utilities/geometrical_sensitivity_utility.cpp", "max_stars_repo_name": "ma6yu/Kratos", "max_stars_repo_head_hexsha": "02380412f8a833a2cdda6791e1c7f9c32e088530", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-30T19:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T19:40:47.000Z", "max_issues_repo_path": "kratos/utilities/geometrical_sensitivity_utility.cpp", "max_issues_repo_name": "ma6yu/Kratos", "max_issues_repo_head_hexsha": "02380412f8a833a2cdda6791e1c7f9c32e088530", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2019-10-07T12:06:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T08:48:33.000Z", "max_forks_repo_path": "kratos/utilities/geometrical_sensitivity_utility.cpp", "max_forks_repo_name": "ma6yu/Kratos", "max_forks_repo_head_hexsha": "02380412f8a833a2cdda6791e1c7f9c32e088530", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-12T08:51:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-12T08:51:24.000Z", "avg_line_length": 32.8897058824, "max_line_length": 147, "alphanum_fraction": 0.6103286385, "num_tokens": 1255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5621337126775672}}
{"text": "#pragma once\n\n#include <boost/range.hpp>\n#include <math/Vec.hpp>\n#include <OpenGLES/ES2/gl.h>\n#include <renderer/Camera.hpp>\n#include <renderer/Renderable.hpp>\n\nstruct Vertex {\n\tGLfloat pos[3];\n\tGLfloat tex[2];\n\n\tVec4 get_pos() const { return Vec4(pos[0], pos[1], pos[2], 1.0f); }\n};\n\nnamespace detail {\n\tstruct ApplyTransformAndProject {\n\t\tApplyTransformAndProject(Camera const * camera, Matrix<4, 4, float> * M) :\n\t\t\tcamera_(camera), M_(M) { }\n\n\t\tVec2 operator () (Vertex const & v) const {\n\t\t\treturn camera_->project_to_device_independent(v.get_pos() *  *M_);\n\t\t}\n\n\t\tprivate:\n\t\t\tCamera const * camera_;\n\t\t\tMatrix<4, 4, float> * M_;\n\t};\n}\n\ntemplate <class Iterator>\ninline Rectangle<float> get_bounding_rectangle(Camera const & camera, Renderable::FrameType const & f, Iterator begin, Iterator end) {\n\tfloat F[] = {\n\t\tf[0][0], f[0][1], f[0][2], 0,\n\t\tf[1][0], f[1][1], f[1][2], 0,\n\t\t\t  0,       0,       1, 0,\n\t\tf[2][0], f[2][1], f[2][2], 1\n\t};\n\n\tMatrix<4, 4, float> M(F);\n\n\treturn get_bounding_rectangle(begin, end, detail::ApplyTransformAndProject(&camera, &M));\n}\n\ntemplate <class Container>\ninline Rectangle<float> get_bounding_rectangle(Camera const & camera, Renderable::FrameType const & f, Container const & container) {\n\treturn get_bounding_rectangle(camera, f, boost::begin(container), boost::end(container));\n}\n", "meta": {"hexsha": "1230dbdfb38eea35cc52c0c2041c9b7d42cdab38", "size": 1323, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "renderer/Vertex.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": "renderer/Vertex.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": "renderer/Vertex.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": 27.0, "max_line_length": 134, "alphanum_fraction": 0.671957672, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5619880808004496}}
{"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": "#include \"matplotlibcpp.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\nnamespace plt = matplotlibcpp;\n\nint main() {\n\n  Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(200, 0, 6);\n  Eigen::VectorXd y, z;\n\n  // y = exp(sin(x)), z = exp(cos(z))\n  y = x.array().sin().exp().matrix();\n  z = x.array().cos().exp().matrix();\n\n  plt::figure();\n\n  plt::loglog(x, y, \"tab:red\");\n  plt::loglog(x, z, \"tab:blue\", {{\"linestyle\", \"--\"}});\n\n  plt::xlabel(\"Time in lecture\");\n  plt::ylabel(\"Student confusion\");\n\n  plt::grid();\n  plt::savefig(\"eigen.pdf\");\n  // plt::show(); // show the figure instead of saving it\n}\n", "meta": {"hexsha": "fc38629c607bc9e1e6abd7e45842044d2fc7d330", "size": 600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/small.cpp", "max_stars_repo_name": "LucaMac1/matplotlib-cpp", "max_stars_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/small.cpp", "max_issues_repo_name": "LucaMac1/matplotlib-cpp", "max_issues_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/small.cpp", "max_forks_repo_name": "LucaMac1/matplotlib-cpp", "max_forks_repo_head_hexsha": "2d56975b1c2dd6f96061685b520f7a552a5f8adf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4285714286, "max_line_length": 60, "alphanum_fraction": 0.595, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5619443338963149}}
{"text": "#include <iostream>\n\n#include \"datastructures/Queue.h\"\n#include \"parallel/ThreadPoolExecutor.h\"\n#include \"datastructures/FibonacciHeap.h\"\n#include \"datastructures/Heap.h\"\n\n#include <array>\n#include <queue>\n#include <ctime>\n#include <cstdlib>\n#include <chrono>\n#include <vector>\n\n#include <boost/heap/fibonacci_heap.hpp>\n\n\nusing namespace std::chrono;\n\nusing data_type = int;\n\nvoid testStdQueue(std::vector<int>& arr, data_type& data, int push_threshold) {\n    std::queue<data_type> std_q;\n    for(int i = 0; i< arr.size(); i++) {\n        int r = arr[i];\n        if(r < push_threshold) {\n            std_q.push(data);\n        } else {\n            size_t size = std_q.size();\n            if( size > 0) {\n                data_type a = std_q.front();\n                std_q.pop();\n            }\n        }\n    }\n}\n\nvoid testMyQueue(std::vector<int>& arr, data_type& data, int push_threshold) {\n\n    Queue<data_type,20> q;\n    for(int i = 0; i< arr.size(); i++) {\n        int r = arr[i];\n        if(r < push_threshold) {\n            q.push(data);\n        } else {\n            size_t size = q.size();\n            if( size > 0) {\n                data_type a = q.front();\n                q.pop();\n            }\n        }\n    }\n}\n\n\nvoid testMyFibonacci(std::vector<int>& arr, data_type& data, int push_threshold) {\n\n    FibonacciHeap<int> q;\n    for(int i = 0; i< arr.size(); i++) {\n        int r = arr[i];\n        if(r < push_threshold) {\n            q.push(r);\n        } else {\n            size_t size = q.size();\n            if( size > 0) {\n                data_type a = q.top();\n                q.pop();\n            }\n        }\n    }\n}\n\nvoid testStdPrioQueu(std::vector<int>& arr, data_type& data, int push_threshold) {\n\n    std::priority_queue<int, std::vector<int>, std::greater<int>> q;\n    for(int i = 0; i< arr.size(); i++) {\n        int r = arr[i];\n        if(r < push_threshold) {\n            q.push(r);\n        } else {\n            size_t size = q.size();\n            if( size > 0) {\n                data_type a = q.top();\n                q.pop();\n            }\n        }\n    }\n}\n\n\nvoid testMyPrioQueu(std::vector<int>& arr, data_type& data, int push_threshold) {\n\n    Heap<int> q;\n    for(int i = 0; i< arr.size(); i++) {\n        int r = arr[i];\n        if(r < push_threshold) {\n            q.push(r);\n        } else {\n            size_t size = q.size();\n            if( size > 0) {\n                data_type a = q.top();\n                q.pop();\n            }\n        }\n    }\n}\n\nvoid testBoostFibonacciHeap(std::vector<int>& arr, data_type& data, int push_threshold) {\n    boost::heap::fibonacci_heap<int> q;\n    for(int i = 0; i< arr.size(); i++) {\n        int r = arr[i];\n        if(r < push_threshold) {\n            q.push(r);\n        } else {\n            size_t size = q.size();\n            if( size > 0) {\n                data_type a = q.top();\n                q.pop();\n            }\n        }\n    }\n}\n\nvoid ValidateFibonacciHeap(std::vector<int>& arr, data_type& data, int push_threshold) {\n    std::priority_queue<int, std::vector<int>, std::greater<int>> q;\n    Heap<int> q2;\n    for(int i = 0; i< arr.size(); i++) {\n        int r = arr[i];\n        if(r < push_threshold) {\n            q.push(r);\n            q2.push(r);\n        } else {\n            size_t size = q.size();\n            if( size > 0) {\n                data_type a = q.top();\n                if(a != q2.top()) {\n                    std::cout << \"WRONG\" << std::endl;\n                }\n                q.pop();\n                q2.pop();\n\n            }\n        }\n    }\n    std::cout << \"Validated\" << std::endl;\n}\n\nint timeIt(std::function<void()> f){\n    milliseconds start = duration_cast< milliseconds >(\n            system_clock::now().time_since_epoch()\n    );\n    f();\n    milliseconds end = duration_cast< milliseconds >(\n            system_clock::now().time_since_epoch()\n    );\n    return (end - start).count();\n}\n\nvoid threadPoolQueusTest() {\n    int N = 5000000;\n    // Should be between 1 and 100;\n    int push_threshold = 80;\n    data_type data;\n\n    std::vector<int>  arr;\n    std::srand(std::time(nullptr));\n    for(int i = 0; i< N; i++) {\n        arr.push_back(std::rand() % 100);\n    }\n\n    std::function<void()> test_std_queue = std::bind(testStdQueue, arr, data, push_threshold);\n    std::function<void()> test_my_queue = std::bind(testMyQueue, arr, data, push_threshold);\n    std::function<void()> test_std_prioqueue = std::bind(testStdPrioQueu, arr, data, push_threshold);\n    std::function<void()> test_my_prioqueue = std::bind(testStdPrioQueu, arr, data, push_threshold);\n    std::function<void()> test_my_fibonacciHeap = std::bind(testMyFibonacci, arr, data, push_threshold);\n    std::function<void()> test_boost_fibonacciHeap = std::bind(testBoostFibonacciHeap, arr, data, push_threshold);\n\n    ThreadPoolExecutor<int> tpe(1);\n\n    //std::future<int> f1 = tpe.execute(std::bind(timeIt, test_std_queue));\n    //std::future<int> f2 = tpe.execute(std::bind(timeIt, test_my_queue));\n    std::future<int> f3 = tpe.execute(std::bind(timeIt, test_std_prioqueue));\n    std::future<int> f4 = tpe.execute(std::bind(timeIt, test_my_prioqueue));\n    std::future<int> f5 = tpe.execute(std::bind(timeIt, test_my_fibonacciHeap));\n    std::future<int> f6 = tpe.execute(std::bind(timeIt, test_boost_fibonacciHeap));\n    tpe.join();\n    //std::cout << \"STD QUEUE: \" << f1.get() << std::endl;\n    //std::cout << \"MY QUEUE: \" << f2.get() << std::endl;\n    std::cout << \"STD PRIO QUEUE: \" << f3.get() << std::endl;\n    std::cout << \"MY HEAP: \" << f4.get() << std::endl;\n    std::cout << \"FIBONACCI HEAP: \" << f5.get()  << std::endl;\n    std::cout << \"BOOST FIBONACCI HEAP: \" << f6.get()  << std::endl;\n}\n\nint main() {\n  threadPoolQueusTest();\n\n\n\n\n    return 0;\n}\n", "meta": {"hexsha": "62a451bb292860d3672f990c79e80be8c1543c03", "size": 5741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Matthiaas/C-Utils", "max_stars_repo_head_hexsha": "9aa7c6073efe5754c4d5cb694a132807d7c6132f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T11:03:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-15T11:03:17.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "Matthiaas/cpp-utils", "max_issues_repo_head_hexsha": "9aa7c6073efe5754c4d5cb694a132807d7c6132f", "max_issues_repo_licenses": ["Apache-2.0"], "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": "Matthiaas/cpp-utils", "max_forks_repo_head_hexsha": "9aa7c6073efe5754c4d5cb694a132807d7c6132f", "max_forks_repo_licenses": ["Apache-2.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.2807881773, "max_line_length": 114, "alphanum_fraction": 0.529001916, "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5619443296784579}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2020 Tinko Bartels, Berlin, Germany.\n\n// Contributed and/or modified by Tinko Bartels,\n//   as part of Google Summer of Code 2020 program.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <array>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/approximate.hpp>\n#include <boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/expression_tree.hpp>\n\ntemplate <typename CalculationType>\nvoid test_all()\n{\n    using bg::detail::generic_robust_predicates::_1;\n    using bg::detail::generic_robust_predicates::_2;\n    using bg::detail::generic_robust_predicates::_3;\n    using bg::detail::generic_robust_predicates::_4;\n    using bg::detail::generic_robust_predicates::sum;\n    using bg::detail::generic_robust_predicates::difference;\n    using bg::detail::generic_robust_predicates::product;\n    using bg::detail::generic_robust_predicates::max;\n    using bg::detail::generic_robust_predicates::abs;\n    using bg::detail::generic_robust_predicates::post_order;\n    using bg::detail::generic_robust_predicates::approximate_value;\n    using bg::detail::generic_robust_predicates::get_approx;\n    using bg::detail::generic_robust_predicates::approximate_interim;\n    using ct = CalculationType;\n    ct r1 = approximate_value<sum<_1, _2>, ct>(\n            std::array<ct, 2>{1.0, 2.0});\n    BOOST_CHECK_EQUAL(3.0, r1);\n    ct r2 = approximate_value<max<abs<_1>, abs<_2>>, ct>(\n            std::array<ct, 2>{-10.0, 2.0});\n    BOOST_CHECK_EQUAL(10.0, r2);\n\n    using expression = product\n        <\n            difference<_1, _2>,\n            difference<_3, _4>\n        >;\n    using evals = post_order<expression>;\n    std::array<ct, boost::mp11::mp_size<evals>::value> r;\n    std::array<ct, 4> input {5.0, 3.0, 2.0, 8.0};\n    approximate_interim<evals, evals, ct>(r, input);\n    ct r3 = get_approx<evals, typename expression::left, ct>(r, input);\n    BOOST_CHECK_EQUAL(2.0, r3);\n    ct r4 = get_approx<evals, typename expression::right, ct>(r, input);\n    BOOST_CHECK_EQUAL(-6.0, r4);\n    ct r5 = get_approx<evals, expression, ct>(r, input);\n    BOOST_CHECK_EQUAL(-12.0, r5);\n}\n\n\nint test_main(int, char* [])\n{\n    test_all<double>();\n    return 0;\n}\n", "meta": {"hexsha": "a7a4b764872d5b0b6ede8d15088f7bc1f7ff0a1c", "size": 2478, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/generic_robust_predicates/approximate.cpp", "max_stars_repo_name": "BoostGSoC20/geometry", "max_stars_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T20:30:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T08:14:05.000Z", "max_issues_repo_path": "extensions/test/generic_robust_predicates/approximate.cpp", "max_issues_repo_name": "Srutip04/geometry", "max_issues_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extensions/test/generic_robust_predicates/approximate.cpp", "max_forks_repo_name": "Srutip04/geometry", "max_forks_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:22:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:43:59.000Z", "avg_line_length": 36.9850746269, "max_line_length": 110, "alphanum_fraction": 0.7050040355, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5619443296784579}}
{"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_ULP_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ULP_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing ulp capabilities\n\n    Returns the ulp distance to the nearest (distinct) element of the same type.\n\n    @par Semantic:\n\n    @code\n    T r = ulp(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = min(x-prev(x), next(x)-x)/Eps<T>();\n    @endcode\n\n    @par Note\n    ulp stands for Unit in the Last Place.\n\n    @see ulpdist, eps, Eps\n\n  **/\n  Value ulp(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/ulp.hpp>\n#include <boost/simd/function/simd/ulp.hpp>\n\n#endif\n", "meta": {"hexsha": "e33b43a68327b0a9900e7fa72f7f0a20a7c9e79e", "size": 1093, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/ulp.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/ulp.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/ulp.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 21.431372549, "max_line_length": 100, "alphanum_fraction": 0.559926807, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5619443286930396}}
{"text": "#include <stdio.h>\r\n#include <iostream>\r\n#include \"dbscan.h\"\r\n\r\n#include <dlib/clustering.h>\r\n#include <dlib/matrix.h>\r\n#include \"plot.h\"\r\n#include <experimental/filesystem>\r\n#include <utility>\r\n#include <unordered_map>\r\nnamespace fs = std::experimental::filesystem;\r\n\r\nconst std::vector<std::string> data_names{\r\n    \"dataset0.csv\"\r\n    //, \"dataset1.csv\",\r\n    //\"dataset2.csv\", \"dataset3.csv\",\r\n    //\"dataset4.csv\", \"dataset5.csv\"\r\n};\r\n\r\nconst std::vector<std::string> colors{\"black\", \"red\", \"blue\", \"green\",\r\n                \"cyan\", \"yellow\", \"brown\", \"magenta\", \"gray\", \"chartreuse\", \"honeydew\"};\r\n\r\nusing DataType = double;\r\nusing Coords = std::vector<DataType>;\r\nusing PointCoords = std::pair<Coords, Coords>;\r\nusing Clusters = std::unordered_map<int, PointCoords>;\r\n\r\n\r\n\r\n\r\nvoid PlotClusters(const Clusters& clusters,\r\n                 const std::string& name,\r\n                 const std::string& file_name) {\r\n    \r\n    \r\n    plotcpp::Plot plt;\r\n    plt.SetTerminal(\"png\");\r\n    plt.SetOutput(file_name);\r\n    plt.SetTitle(name);\r\n    plt.SetXLabel(\"x\");\r\n    plt.SetYLabel(\"y\");\r\n    plt.SetAutoscale();\r\n    plt.GnuplotCommand(\"set grid\");\r\n    auto draw_state = plt.StartDraw2D<Coords::const_iterator>();\r\n    for (const auto& cluster : clusters) {\r\n        std::stringstream params;\r\n        if(cluster.first == -1) continue;\r\n        params << \"lc rgb '\" << colors[cluster.first] << \"'pt 7\";\r\n        plt.AddDrawing(draw_state,\r\n                        plotcpp::Points(\r\n                        cluster.second.first.cbegin(), cluster.second.first.cend(),\r\n                        cluster.second.second.cbegin(),\r\n                        std::to_string(static_cast<size_t>(cluster.first)) + \" cls\", params.str()));    \r\n                        \r\n    }\r\n    \r\n    plt.EndDraw2D(draw_state);\r\n    plt.Flush();\r\n}\r\n\r\n//For debug here:\r\n/*\r\nvoid printResults(vector<Point>& points, int num_points)\r\n{\r\n    int i = 0;\r\n    printf(\"Number of points: %u\\n\"\r\n        \" x     y   cluster_id\\n\"\r\n        \"-----------------------------\\n\"\r\n        , num_points);\r\n    while (i < num_points)\r\n    {\r\n          printf(\"%5.2lf %5.2lf %d\\n\",\r\n                 points[i].x,\r\n                 points[i].y,\r\n                 points[i].clusterID);\r\n          ++i;\r\n    }\r\n}\r\n*/\r\n\r\n\r\nint main(int argc, char** argv)\r\n{    \r\n    if(argc > 3){\r\n    auto base_dir = fs::path(argv[1]);\r\n    const double epsilon = atof(argv[2]);\r\n    const double minimum_points = atoi(argv[3]);\r\n    for(auto & dataset : data_names ) {\r\n        auto dataset_name = base_dir / dataset;\r\n\r\n        if (fs::exists(dataset_name)){\r\n        std::ifstream file(dataset_name);\r\n        dlib::matrix<DataType> data;\r\n        file >> data;\r\n        vector<Point> points;\r\n        for ( int i = 0; i < data.nr(); i++){\r\n            points.emplace_back(data(i, 1), data(i, 2), UNCLASSIFIED);\r\n        }\r\n\r\n        Clusters clusters;\r\n        DBSCAN ds(minimum_points, epsilon, points);\r\n        ds.run();\r\n        \r\n        \r\n        for (const auto& point : ds.m_points){\r\n            \r\n            clusters[point.clusterID].first.push_back(point.x);\r\n            clusters[point.clusterID].second.push_back(point.y);\r\n            //For debug here:\r\n            //std::cout << point.clusterID << point.x << point.y << std::endl;\r\n         }\r\n        \r\n        //std::cout << \" file name is: \"<< dataset_name << \"\\n\\n\\n\";\r\n        //printResults(ds.m_points, ds.getTotalPointSize());  //for debug here\r\n        //std::cout << \"\\n\\n\\n\";\r\n        //std::cout <<__LINE__ << std::endl << std::endl;\r\n        PlotClusters(clusters, \"DBSCAN clustering\", \"../results/\" +  dataset + \"-dbscans.png\");\r\n       }\r\n      else{\r\n        std::cerr << \"Dataset file \" << dataset_name << \"missed. Please provide in the correct form.\\n\";\r\n      }\r\n     }      \r\n    }\r\n    else {\r\n        std::cerr <<\" Please provide the data's folder!!!\\n\\n\";\r\n    }\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "4b456d7e8d93eb7c0289fc4d541c24517642455c", "size": 3917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "mukoedo1993/DBSCAN_algorithm", "max_stars_repo_head_hexsha": "dfcca5d84806f3570430f759aeb2b46c96a6f630", "max_stars_repo_licenses": ["MIT"], "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": "mukoedo1993/DBSCAN_algorithm", "max_issues_repo_head_hexsha": "dfcca5d84806f3570430f759aeb2b46c96a6f630", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-30T06:25:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-29T23:13:34.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "mukoedo1993/DBSCAN_algorithm", "max_forks_repo_head_hexsha": "dfcca5d84806f3570430f759aeb2b46c96a6f630", "max_forks_repo_licenses": ["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.3643410853, "max_line_length": 105, "alphanum_fraction": 0.5297421496, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.5618831335760455}}
{"text": "#ifndef __BLACKSCHOLES_H\n#define __BLACKSCHOLES_H\n\n#include <iostream>\n#include <cmath>\n#include <armadillo>\n\n\nnamespace bsc{\n        \n        class BlackScholes{\n\n        private:\n                double S_;\n                double K_;\n                double r_;\n                double T_;\n\n        public:\n                BlackScholes(double S_,double K_,double r_,double T_);\n                double OptionEurop(double);\n                double OptionVega(double);\n\n        \n};\n\n\n}\n\n\n#endif ", "meta": {"hexsha": "6a919897ac5157947b58ce2c5a449041dfb2f8c9", "size": 490, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/blackscholes.hpp", "max_stars_repo_name": "NicolasMakaroff/implied-volatility-learning", "max_stars_repo_head_hexsha": "907dfe4496be35708881f7b40c1b543a8574d649", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/blackscholes.hpp", "max_issues_repo_name": "NicolasMakaroff/implied-volatility-learning", "max_issues_repo_head_hexsha": "907dfe4496be35708881f7b40c1b543a8574d649", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-28T11:36:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-21T14:01:12.000Z", "max_forks_repo_path": "src/blackscholes.hpp", "max_forks_repo_name": "NicolasMakaroff/implied-volatility-learning", "max_forks_repo_head_hexsha": "907dfe4496be35708881f7b40c1b543a8574d649", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-27T17:47:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-27T17:47:36.000Z", "avg_line_length": 15.8064516129, "max_line_length": 70, "alphanum_fraction": 0.5204081633, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5618831290208797}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#include <rw/math/Vector3D.hpp>\n\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n\nusing namespace rw::math;\n\nTEST (Vector3D, MiscTest)\n{\n    const Vector3D<> v1 (1.0, 2.0, 3.0);\n    const Vector3D<> v2 (v1);\n    const Vector3D<> v3 = v1 + v2;\n    const Vector3D<> v4 = Vector3D<> (2.0, 4.0, 6.0);\n    EXPECT_EQ ((v3 - v4).normInf (), 0);\n\n    const Vector3D<> v5 (3.0, 4.0, 5.0);\n    const Vector3D<> v5_norm = normalize (v5);\n    EXPECT_LT (fabs (v5_norm.norm2 () - 1), 1e-15);\n\n    const double len = v5.norm2 ();\n    EXPECT_LT (fabs (v5_norm (0) - v5 (0) / len), 1e-15);\n    EXPECT_LT (fabs (v5_norm (1) - v5 (1) / len), 1e-15);\n    (fabs (v5_norm (2) - v5 (2) / len) < 1e-15);\n\n    Vector3D<> v6;\n    v6 (0) = len;\n    EXPECT_EQ (v6 (0), len);\n\n    const Vector3D< std::string > vs1 (\"x1\", \"y1\", \"z1\");\n\n    EXPECT_EQ (vs1[0], \"x1\");\n    EXPECT_EQ (vs1[1], \"y1\");\n    EXPECT_EQ (vs1[2], \"z1\");\n\n    EXPECT_EQ (cross (v1, v2).normInf (), 0);\n\n    const Vector3D< double > vd (1.1, 5.51, -10.3);\n    const Vector3D< int > vi = cast< int > (vd);\n    EXPECT_EQ (vi (0), 1);\n    EXPECT_EQ (vi (1), 5);\n    EXPECT_EQ (vi (2), -10);\n\n    /* Test comparison operators operator== and operator!= */\n    const Vector3D< double > comp1 (1.1, -2.2, 3.3);\n    const Vector3D< double > comp2 (1.1, -2.2, 3.3);\n    EXPECT_TRUE (comp1 == comp2);\n    EXPECT_TRUE (!(comp1 != comp2));\n    const Vector3D< double > comp3 (1.1, 2.2, -3.3);\n    EXPECT_TRUE (comp1 != comp3);\n    EXPECT_TRUE (!(comp1 == comp3));\n}\n\nTEST (Vector3D, scalarOperatorTest)\n{\n    Vector3D<> obj (3, 3, 3);\n\n    auto test1 = obj * 2;\n    auto test2 = 2 * obj;\n    auto test3 = obj / 2;\n    auto test4 = 2 / obj;\n    auto test5 = obj.elemAdd(2);\n    auto test7 = obj.elemSubtract(2);\n    auto test9 = obj;\n    test9 *= 2;\n    auto test10 = obj;\n    test10 /= 2;\n    for (size_t i = 0; i < obj.size (); i++) {\n        EXPECT_DOUBLE_EQ (test1[i], 6.0);\n        EXPECT_DOUBLE_EQ (test2[i], 6.0);\n        EXPECT_DOUBLE_EQ (test3[i], 3.0 / 2.0);\n        EXPECT_DOUBLE_EQ (test4[i], 2.0 / 3.0);\n        EXPECT_DOUBLE_EQ (test5[i], 5.0);\n        EXPECT_DOUBLE_EQ (test7[i], 1.0);\n        EXPECT_DOUBLE_EQ (test9[i], 6.0);\n        EXPECT_DOUBLE_EQ (test10[i], 3.0 / 2.0);\n    }\n}\n\nTEST (Vector3D, Vector3DOperatorTest)\n{\n    Vector3D<> obj1 (3, 3, 3);\n    Vector3D<> obj2 (2, 2, 2);\n\n    auto test1 = obj1.elemMultiply(obj2);\n    auto test2 = obj1.elemDivide(obj2);\n    auto test3 = obj1 + obj2;\n    auto test4 = obj1 - obj2;\n    auto test7 = obj1;\n    test7 += obj2;\n    auto test8 = obj1;\n    test8 -= obj2;\n\n    for (size_t i = 0; i < obj1.size (); i++) {\n        EXPECT_DOUBLE_EQ (test1[i], 6.0);\n        EXPECT_DOUBLE_EQ (test2[i], 3.0 / 2.0);\n        EXPECT_DOUBLE_EQ (test3[i], 5.0);\n        EXPECT_DOUBLE_EQ (test4[i], 1.0);\n        EXPECT_DOUBLE_EQ (test7[i], 5.0);\n        EXPECT_DOUBLE_EQ (test8[i], 1.0);\n    }\n}\n\nTEST (Vector3D, EigenOperatorTest)\n{\n    Vector3D<> obj1 (3, 3, 3);\n    Eigen::Vector3d obj2 (2, 2, 2);\n\n    auto test1  = obj1.elemMultiply(obj2);\n    auto test2  = obj1.elemDivide(obj2);\n    auto test3  = obj1 + obj2;\n    auto test3x = obj2 + obj1;\n    auto test4  = obj1 - obj2;\n    auto test4x = obj2 - obj1;\n    auto test7 = obj1;\n    test7 += obj2;\n    auto test8 = obj1;\n    test8 -= obj2;\n\n    for (size_t i = 0; i < obj1.size (); i++) {\n        EXPECT_DOUBLE_EQ (test1[i], 6.0);\n        EXPECT_DOUBLE_EQ (test2[i], 3.0 / 2.0);\n        EXPECT_DOUBLE_EQ (test3[i], 5.0);\n        EXPECT_DOUBLE_EQ (test3x[i], 5.0);\n        EXPECT_DOUBLE_EQ (test4[i], 1.0);\n        EXPECT_DOUBLE_EQ (test4x[i], -1.0);\n        EXPECT_DOUBLE_EQ (test7[i], 5.0);\n        EXPECT_DOUBLE_EQ (test8[i], 1.0);\n    }\n\n    EXPECT_TRUE (obj1 != obj2);\n    EXPECT_TRUE (obj2 != obj1);\n    EXPECT_FALSE (obj1 == obj2);\n    EXPECT_FALSE (obj2 == obj1);\n    obj2 = obj1.e();\n    EXPECT_TRUE (obj1 == obj2);\n    EXPECT_TRUE (obj2 == obj1);\n    EXPECT_FALSE (obj1 != obj2);\n    EXPECT_FALSE (obj2 != obj1);\n}\n\nTEST (Vector3D, ComparisonTest)\n{\n    const Vector3D< double > comp1 (1.1, -2.2, 3.3);\n    auto comp2 = comp1;\n    auto comp3 = -comp1;\n    EXPECT_TRUE (comp1 == comp2);\n    EXPECT_FALSE (comp1 != comp2);\n    EXPECT_TRUE (comp1 != comp3);\n    EXPECT_FALSE (comp1 == comp3);\n}\n\nTEST (Vector3D, MathOperators)\n{\n    Vector3D<> obj1 (1, 2, 3);\n    Vector3D<> obj2 (3, 2, 1);\n\n    auto test1 = obj1.cross (obj2);\n    auto test2 = obj1.dot (obj2);\n    auto test3 = obj1.normalize ();\n\n    EXPECT_EQ (obj1.e ().cross (obj2.e ()), test1);\n    EXPECT_EQ (obj1.e ().dot (obj2.e ()), test2);\n    EXPECT_EQ (test3.norm2 (), 1.0);\n    EXPECT_EQ (test3 * obj1.norm2 (), obj1);\n}\n", "meta": {"hexsha": "bbabd010f1b2ff241f383de3e0362d3227691e2c", "size": 5481, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RobWork/gtest/math/Vector3DTest.cpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/gtest/math/Vector3DTest.cpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/gtest/math/Vector3DTest.cpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9508196721, "max_line_length": 82, "alphanum_fraction": 0.571246123, "num_tokens": 1856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5618831046282405}}
{"text": "/*! \\file demo_2d_bezier.cpp\n\\brief Simple 2D plot of trig functions,\ncontrived to show optionally\n  using Bezier for curves,\n  data-points markers,\n  lines joining data-points,\nand \n  legend identifying point marks and/or lines.\n\n  A few color, widths and shapes options are demonstrated,\n  to produce a somewhat lurid effect.\n\n  Demonstrates that the legend marks line only shown if a dataset is plotted with a line joining points,\n  and a data-point value marker is only shown if marker shapes are used,\n  and not if the shape == none.\n*/\n\n// Copyright Paul A. Bristow 2018\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/svg_plot/svg_2d_plot.hpp>\n// using namespace boost::svg;\n// Very convenient to allow easy access to colors and other items.\n\n#include <map>\n// using std::map;\n#include <cmath>\n//using std::sin;\n//using std::cos;\n//using std::tan;\n\ndouble f(double x)\n{\n  return std::sin(x);\n}\n\ndouble g(double x)\n{\n  return std::cos(x);\n}\n\ndouble h(double x)\n{\n  return std::tan(x);\n}\n\nint main()\n{\n\n  using namespace boost::svg; // Very convenient to allow easy access to colors and many other items.\n\n  std::map<double, double> sin_data, cos_data, tan_data, sincos_data;\n\n  double step = 3.14159265 / 8.;  // Interval between function data-points.\n\n  // Generate some trigonmetric data to plot.\n  for(double i = 0; i <= 10.; i += step)\n  {\n    sin_data[i] = f(i); // sin\n    cos_data[i] = g(i); // cos\n    tan_data[i] = h(i); // tan\n    sincos_data[i] = std::sin(g(i)); // sincos\n } // for i\n\n  svg_2d_plot my_plot; // Data structure to hold the plot.\n\n  // Size/scale settings.\n  my_plot.size(700, 500) // SVG image size (pixel).\n    .x_range(-0.5, 10.5) // Range of x and y axes,  \n    .y_range(-1.1, 1.1); // chosen to ensure that the maxima and minimax \n                         // are not just on the edge of the plot window.\n\n  // Text settings.\n  my_plot.title(\"Plot of sin, cos &#x26; tan and sincos functions\")\n    // Note: for ampersand must use Unicode &#x26; because it is a reserved symbol in SVG XML.\n    // Search engines will provide Unicodes by querying \"Unicode ampersand\"\n    // at sites like https://unicode.org/, \n    // http://www.fileformat.info/info/unicode/char/0026/index.htm and others.\n    .title_font_size(28)\n    .x_label(\"x Axis Units\")\n    .y_major_labels_side(left)\n    .y_major_grid_on(true);\n\n  // Layout options:\n  my_plot.legend_on(true) // Want a legend box.\n    .plot_window_on(true) // want a plot window with axis labels etc outside.\n    .x_label_on(true) // Label X-axis ticks with their values.\n    //.y_label_on(false)  // false is default.\n    ;\n\n  // Plot color settings.\n  // (Note use of chaining to add settings).\n  my_plot\n    .background_color(darkgreen)\n    .legend_background_color(lightgray)\n    .legend_border_color(black)\n    .plot_background_color(lightgoldenrodyellow)\n    .title_color(white)\n    .y_major_grid_color(black);\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(25)\n    .y_num_minor_ticks(5);\n\n  // Legend settings.\n  my_plot.legend_title_font_size(15)\n    .legend_title(\"Legend\");\n\n  my_plot.plot(sin_data, \"sin(x)\")\n    .line_on(true) // Line joining data-points, using default color black.\n    .shape(circlet) // and circle marker showing data-points.\n    .size(10) // Size (diameter pixels) of circlet data-point marker.\n    .fill_color(yellow) // Outline is default black and centre yellow.\n  // Default is no bezier.  Note angularity at the minima and maxima.\n    ;\n\n  my_plot.plot(cos_data, \"cos(x)\")\n    .line_color(blue) // Defaults to showing line, but not in legend.\n    .line_on(true) // Needed to show in the legend.\n    .line_width(1) // thinner line.\n    .shape(square) // Center of square has the data-point coordinate.\n    .size(5)\n    .fill_color(red)  // Center of square.\n    ;\n\n  my_plot.plot(tan_data, \"tan(x)\")\n    .line_on(false)  // No line joining points.\n    .shape(cone) // bottom point of cone has the coordinate of the data point.\n    .size(5).fill_color(blue); // Just show data-point markers.\n\n  my_plot.plot(sincos_data, \"sincos(x)\")\n    .line_on(true)  // Just line joining points.\n    .line_color(purple)\n    .line_width(0.5)\n    .bezier_on(true) // Note smoother at the minima and maxima.\n    .shape(none) ; // NO data-point markers (and only shows a line in the legend).\n\n  my_plot.write(\"demo_2d_bezier.svg\"); // Final plot.\n\n  std::cout << \"demo_2d_bezier plot written to \" << \"demo_2d_bezier.svg\" << std::endl;\n  return 0;\n} // int main()\n\n", "meta": {"hexsha": "45ee1c4d7ca2b33429c0d97f05549885677421e9", "size": 4809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_2d_bezier.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_2d_bezier.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_2d_bezier.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": 30.8269230769, "max_line_length": 104, "alphanum_fraction": 0.6805988771, "num_tokens": 1320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.5618831038936516}}
{"text": "#pragma once\n/*!\t\\file\treal.hpp\n\t\\brief\tReal classes declarations.\n\t\\author\tGarth Santor\n\t\\date\t2021-10-29\n\t\\copyright\tGarth Santor, Trinh Han\n\n=============================================================\nDeclarations of the Real classes derived from Operand.  Includes\nthe subclasses Pi and E.\n\n\n=============================================================\nRevision History\n-------------------------------------------------------------\n\nVersion 2021.10.26\n\tC++ 20 validated\n\nVersion 2019.11.05\n\tC++ 17 cleanup\n\nVersion 2014.10.29\n\tC++ 11 refactor.\n\tSwitched value_type to boost::multiprecision::cpp_dec_float_100\n\nVersion 2012.11.13\n\tC++ 11 cleanup\n\nVersion 2010.11.09\n\tSwitched boost::shared_ptr<> to std::shared_ptr<>.\n\tAdded TOKEN_PTR_TYPE macro.\n\nVersion 2009.11.25\n\tAlpha release.\n\n=============================================================\n\nCopyright Garth Santor/Trinh Han\n\nThe copyright to the computer program(s) herein\nis the property of Garth Santor/Trinh Han, Canada.\nThe program(s) may be used and/or copied only with\nthe written permission of Garth Santor/Trinh Han\nor in accordance with the terms and conditions\nstipulated in the agreement/contract under which\nthe program(s) have been supplied.\n=============================================================*/\n\n#include <ee/operand.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\n\n\n/*! Real number token. */\nclass Real : public Operand {\npublic:\n\tDEF_POINTER_TYPE(Real)\n\tusing value_type = boost::multiprecision::number<boost::multiprecision::cpp_dec_float<1000, int32_t, void>>;\nprivate:\n\tvalue_type\tvalue_;\npublic:\n\tReal(value_type value = value_type(0)) : value_(value) { }\n\t[[nodiscard]] value_type\tvalue() const { return value_; };\n\t[[nodiscard]] string_type\tstr() const override;\n};\n\n\n/*! Pi constant token. */\nclass Pi : public Real {\npublic:\n\tPi() : Real(boost::math::constants::pi<value_type>()) { }\n};\n\n\n/*! Euler constant token. */\nclass E : public Real {\npublic:\n\tE() : Real(boost::math::constants::e<value_type>()) { }\n};\n", "meta": {"hexsha": "c0413fff0c3440d67d60d20564b95ab7cc9229ff", "size": 2059, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ee21/common/inc/ee/real.hpp", "max_stars_repo_name": "ygor-rezende/Expression-Evaluator", "max_stars_repo_head_hexsha": "52868ff11ce72a4ae6fa9a4052005c02f8485b3c", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ee21/common/inc/ee/real.hpp", "max_issues_repo_name": "ygor-rezende/Expression-Evaluator", "max_issues_repo_head_hexsha": "52868ff11ce72a4ae6fa9a4052005c02f8485b3c", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ee21/common/inc/ee/real.hpp", "max_forks_repo_name": "ygor-rezende/Expression-Evaluator", "max_forks_repo_head_hexsha": "52868ff11ce72a4ae6fa9a4052005c02f8485b3c", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4197530864, "max_line_length": 109, "alphanum_fraction": 0.6289460903, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5618285933320029}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"file_manage.h\"\n#include \"decision_tree.h\"\n#include \"model_selection.h\"\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n\tMatrixXd features;\n\tVectorXd labels;\n\n\tread_csv(\"data/iris.csv\", features, labels, 150, 5);\n\t//read_csv(\"data/seeds.csv\", features, labels, 210, 8);\n\n\tDecisionTree model;\n\tmodel.fit(features, labels);\n\tmodel.printTree();\n\n\tdouble accuracy = evaluate_model(model, features, labels, 5);\n\tcout << \"Model accuracy : \" << accuracy << endl;\n\n\treturn 0;\n}", "meta": {"hexsha": "b4079f80dabbadcb2d9e13e939d256c186d36cbd", "size": 531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "stnamjef/decision_tree_classifier", "max_stars_repo_head_hexsha": "0f6f4009784fc9cfd8e485b7168eac67640b07d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "stnamjef/decision_tree_classifier", "max_issues_repo_head_hexsha": "0f6f4009784fc9cfd8e485b7168eac67640b07d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "stnamjef/decision_tree_classifier", "max_forks_repo_head_hexsha": "0f6f4009784fc9cfd8e485b7168eac67640b07d5", "max_forks_repo_licenses": ["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.24, "max_line_length": 62, "alphanum_fraction": 0.7156308851, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5617478069513762}}
{"text": "#ifndef GQ_CHARACTERIZE_H\n#define GQ_CHARACTERIZE_H\n\n#include <Eigen/Eigen>\n#include <cfloat>\n#include <iostream>\n#include <string>\n\n#include \"geometry.hpp\"\n\nenum GQ_TYPE {UNKNOWN = 0,\n              ELLIPSOID,\n              ONE_SHEET_HYPERBOLOID,\n              TWO_SHEET_HYPERBOLOID,\n              ELLIPTIC_CONE,\n              ELLIPTIC_PARABOLOID,\n              HYPERBOLIC_PARABOLOID,\n              ELLIPTIC_CYL,\n              HYPERBOLIC_CYL,\n              PARABOLIC_CYL};\n\nconst std::vector<std::string> _gq_names = {\"UNKNOWN\",\n                                            \"ELLIPSOID\",\n                                            \"ONE_SHEET_HYPERBOLOID\",\n                                            \"TWO_SHEET_HYPERBOLOID\",\n                                            \"ELLIPTIC_CONE\",\n                                            \"ELLIPTIC_PARABOLOID\",\n                                            \"HYPERBOLIC_PARABOLOID\",\n                                            \"ELLIPTIC_CYL\",\n                                            \"HYPERBOLIC_CYL\",\n                                            \"PARABOLIC_CYL\"};\n\nextern const std::vector<std::string> _gq_names;\n\nclass GQ_Characterize{\n\nprotected:\n  // coefficients of the GQ\n  double A_,B_,C_,D_,E_,F_,G_,H_,J_,K_;\n  // the cannonical GQ type\n  GQ_TYPE type;\n  // translation from the canoncial GQ to final GQ\n  Vector3d translation;\n  // rotation matrix from canonical GQ to final GQ\n  double rotation_mat[9];\n  // gq transform\n  Transform transform_;\n\n  // tolerance used to determine\n  // if matrix determinant should be considered zero\n  const double gq_tol = 1e-6;\n  const double equivalence_tol = 1e-8;\n\n\npublic:\n  // Constructor\n  // Characterizes a general quadratic (GQ) equation of the form:\n  // A x^2 + B y^2 + C z^2 + D xy + E yz + F xz + G x + H y + J z + K = 0\n  // into a special quadratic (SQ) with a transformation\n  GQ_Characterize(double A, double B, double C,\n                  double D, double E, double F,\n                  double G, double H, double J,\n                  double K);\n\n  // GQ type accessor\n  GQ_TYPE get_type() { return type; }\n\nprotected:\n  // reduces GQ coefficients to 2nd order terms, a constant, and a transformation\n  // to the original origntation when needed\n  void make_canonical();\n\n  // this method reduces a complex GQ to a geometrically equivalent\n  // and more CAD-friendly form if appropriate\n  void reduce_type();\n\n  // determines GQ type based on characteristic parameters\n  GQ_TYPE find_type(int rt, int rf, int del, int s, int d);\n};\n\n#endif\n", "meta": {"hexsha": "cb24cd883ada8a405a42f7e9a402fbfc64ad26a5", "size": 2544, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GQ_Characterize.hpp", "max_stars_repo_name": "gonuke/mcnp2cad", "max_stars_repo_head_hexsha": "18bd8b6f70ed02cb8bb8cb5e34f8e5eef6af494a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-09-11T08:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T09:10:01.000Z", "max_issues_repo_path": "GQ_Characterize.hpp", "max_issues_repo_name": "gonuke/mcnp2cad", "max_issues_repo_head_hexsha": "18bd8b6f70ed02cb8bb8cb5e34f8e5eef6af494a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-01-24T18:21:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T11:30:23.000Z", "max_forks_repo_path": "GQ_Characterize.hpp", "max_forks_repo_name": "gonuke/mcnp2cad", "max_forks_repo_head_hexsha": "18bd8b6f70ed02cb8bb8cb5e34f8e5eef6af494a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2015-01-31T19:25:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-29T13:58:29.000Z", "avg_line_length": 31.0243902439, "max_line_length": 81, "alphanum_fraction": 0.5672169811, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.561747805936154}}
{"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            // \u52fe\u914d\u5909\u5316\u306e\u5927\u304d\u304b\u3063\u305f\u30d1\u30e9\u30e1\u30fc\u30bf\u306e\u4e8c\u4e57\u5e73\u65b9\u6839\u3067\u5272\u308b \u2192 \u8981\u306f\u52fe\u914d\u306e\u7d76\u5bfe\u5024\u304c\u5927\u304d\u304b\u3063\u305f\u30d1\u30e9\u30e1\u30fc\u30bf\u306e\u66f4\u65b0\u5e45\u3092\u5c0f\u3055\u304f\u3059\u308b\u3068\u3044\u3046\u3053\u3068\n            // \u203b \u53b3\u5bc6\u306b\u306f\u52fe\u914d\u306e\u7d76\u5bfe\u5024\u3067\u5272\u3063\u3066\u3044\u308b\u308f\u3051\u3067\u306f\u306a\u3044(\u76f4\u524d\u306e\u5185\u90e8\u72b6\u614b\u306b\u52a0\u7b97\u3057\u3066\u5e73\u65b9\u6839\u3092\u53d6\u3063\u3066\u3044\u308b)\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            // \u52fe\u914d\u5909\u5316\u306e\u5927\u304d\u304b\u3063\u305f\u30d1\u30e9\u30e1\u30fc\u30bf\u306e\u4e8c\u4e57\u5e73\u65b9\u6839\u3067\u5272\u308b \u2192 \u8981\u306f\u52fe\u914d\u306e\u7d76\u5bfe\u5024\u304c\u5927\u304d\u304b\u3063\u305f\u30d1\u30e9\u30e1\u30fc\u30bf\u306e\u66f4\u65b0\u5e45\u3092\u5c0f\u3055\u304f\u3059\u308b\u3068\u3044\u3046\u3053\u3068\n            // \u203b \u53b3\u5bc6\u306b\u306f\u52fe\u914d\u306e\u7d76\u5bfe\u5024\u3067\u5272\u3063\u3066\u3044\u308b\u308f\u3051\u3067\u306f\u306a\u3044(\u76f4\u524d\u306e\u5185\u90e8\u72b6\u614b\u306b\u52a0\u7b97\u3057\u3066\u5e73\u65b9\u6839\u3092\u53d6\u3063\u3066\u3044\u308b)\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\u306e\u5185\u90e8\u72b6\u614bh\u3092\u6307\u6570\u79fb\u52d5\u5e73\u5747\u306b\u7f6e\u304d\u63db\u3048\u305f\u3082\u306e\u304cRMSprop -> \u6307\u6570\u79fb\u52d5\u5e73\u5747\u306e\u6e1b\u8870\u7387(\u5e73\u6ed1\u5316\u4fc2\u6570)\u304cdecay_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\u306e\u5185\u90e8\u72b6\u614bh\u3092\u6307\u6570\u79fb\u52d5\u5e73\u5747\u306b\u7f6e\u304d\u63db\u3048\u305f\u3082\u306e\u304cRMSprop -> \u6307\u6570\u79fb\u52d5\u5e73\u5747\u306e\u6e1b\u8870\u7387(\u5e73\u6ed1\u5316\u4fc2\u6570)\u304cdecay_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": "/*\n * NormalVectorsFilter.hpp\n *\n *  Created on: May 05, 2015\n *      Author: Peter Fankhauser, Martin Wermelinger\n *   Institute: ETH Zurich, ANYbotics\n */\n\n#pragma once\n\n#include <filters/filter_base.h>\n#include <grid_map_core/grid_map_core.hpp>\n\n#include <Eigen/Core>\n#include <string>\n\nnamespace grid_map {\n\n/*!\n * Compute the normal vectors of a layer in a map.\n */\ntemplate <typename T>\nclass NormalVectorsFilter : public filters::FilterBase<T> {\n public:\n  /*!\n   * Constructor\n   */\n  NormalVectorsFilter();\n\n  /*!\n   * Destructor.\n   */\n  virtual ~NormalVectorsFilter();\n\n  /*!\n   * Configures the filter from parameters on the Parameter Server\n   */\n  virtual bool configure();\n\n  /*!\n   * Compute the normal vectors of a layer in a map and\n   * saves it as additional grid map layer.\n   * @param mapIn grid map containing the layer for which the normal vectors are computed for.\n   * @param mapOut grid map containing mapIn and the new layers for the normal vectors.\n   */\n  virtual bool update(const T& mapIn, T& mapOut);\n\n private:\n  /*!\n   * Estimate the normal vector at each point of the input layer by using points within a circle of specified radius.\n   *\n   * The eigen decomposition of the covariance matrix (3x3) of all data points is used to establish the normal direction.\n   * Four cases can be identified when the eigenvalues are ordered in ascending order:\n   *    1) The data is in a cloud -> all eigenvalues are non-zero\n   *    2) The data is on a plane -> The first eigenvalue is zero\n   *    3) The data is on a line -> The first two eigenvalues are zero.\n   *    4) The data is in one point -> All eigenvalues are zero\n   *\n   * Only case 1 & 2 provide enough information the establish a normal direction.\n   * The degenerate cases (3 or 4) are identified by checking if the second eigenvalue is zero.\n   *\n   * The numerical threshold (1e-8) for the eigenvalue being zero is given by the accuracy of the decomposition, as reported by Eigen:\n   * https://eigen.tuxfamily.org/dox/classEigen_1_1SelfAdjointEigenSolver.html\n   *\n   * Finally, the sign normal vector is correct to be in the same direction as the user defined \"normal vector positive axis\"\n   *\n   * @param map: grid map containing the layer for which the normal vectors are computed for.\n   * @param inputLayer: Layer the normal vector should be computed for.\n   * @param outputLayersPrefix: Output layer name prefix.\n   */\n  void computeWithArea(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix);\n\n  void computeWithRaster(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix);\n\n  enum class Method { Area, Raster };\n\n  Method method_;\n\n  //! Radius of submap for normal vector estimation.\n  double estimationRadius_;\n\n  //! Normal vector positive axis.\n  Eigen::Vector3d normalVectorPositiveAxis_;\n\n  //! Input layer name.\n  std::string inputLayer_;\n\n  //! Output layer name.\n  std::string outputLayersPrefix_;\n};\n\n}  // namespace grid_map\n", "meta": {"hexsha": "c5f605808a520822b51dc0792b41356feef49288", "size": 3001, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_map_filters/include/grid_map_filters/NormalVectorsFilter.hpp", "max_stars_repo_name": "mktk1117/grid_map", "max_stars_repo_head_hexsha": "1ee4c5dd78d029f4ef7e209c4080e57e18b081fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-11T16:47:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T16:47:52.000Z", "max_issues_repo_path": "grid_map_filters/include/grid_map_filters/NormalVectorsFilter.hpp", "max_issues_repo_name": "mktk1117/grid_map", "max_issues_repo_head_hexsha": "1ee4c5dd78d029f4ef7e209c4080e57e18b081fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_filters/include/grid_map_filters/NormalVectorsFilter.hpp", "max_forks_repo_name": "mktk1117/grid_map", "max_forks_repo_head_hexsha": "1ee4c5dd78d029f4ef7e209c4080e57e18b081fb", "max_forks_repo_licenses": ["BSD-3-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.2688172043, "max_line_length": 134, "alphanum_fraction": 0.7150949683, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5616814751162187}}
{"text": "\n#include <Eigen/Dense>\n#include <vector>\n\n#include \"TestsCatchRequire.h\"\n#include \"../core/NeuralNetwork.h\"\n\nTEST_CASE(\"NeuralNetwork can be initialised\", \"[NeuralNetwork]\") {\n    // create a basic layout 2 inputs, 2 nodes in the 1st layer 1 in the 2nd\n    int nodes[3] = { 2, 2, 1};\n    std::vector<int> layout(&nodes[0], &nodes[0]+3);\n\n    SECTION(\"Creating a network with valid parameters\") {\n        REQUIRE_NOTHROW(NeuralNetwork(layout, \"step\"));\n    }\n\n    SECTION(\"Creating a network with sigmoid function\") {\n        REQUIRE_NOTHROW(NeuralNetwork(layout, \"sigmoid\"));\n    }\n\n    SECTION(\"Creating a network with invalid function\") {\n        REQUIRE_THROWS(NeuralNetwork(layout, \"somefunc\"));\n    }\n\n    SECTION(\"Creating a network without a random seed\") {\n        REQUIRE_NOTHROW(NeuralNetwork(layout, \"step\", false));\n    }\n}\n\nTEST_CASE(\"Testing NeuralNetwork feedForward\", \"[NeuralNetwork]\") {\n\n    SECTION(\"Check feedForward with valid parameters\") {\n        int nodes[3] = { 3, 2, 1};\n        std::vector<int> layout(&nodes[0], &nodes[0]+3);\n\n        NeuralNetwork ann(layout, \"step\", false);\n\n        Eigen::MatrixXd input(1, 3);\n        input << 1, 1, 1;\n\n        Eigen::MatrixXd output = ann.feedForward(input);\n\n        REQUIRE(output.value() == 0);\n    }\n\n    SECTION(\"Check feedForward with multiple outputs\") {\n        int nodes[3] = { 3, 2, 2};\n        std::vector<int> layout(&nodes[0], &nodes[0]+3);\n\n        NeuralNetwork ann(layout, \"sigmoid\", false);\n\n        Eigen::MatrixXd input(1, 3);\n        input << 1, 1, 1;\n        \n        Eigen::MatrixXd output = ann.feedForward(input);\n\n        REQUIRE(output(0, 0) == Approx(0.276810));\n        REQUIRE(output(1, 0) == Approx(0.757047));\n    }\n\n    SECTION(\"Check feedForward single perceptron\") {\n        int nodes[2] = { 2, 1};\n        std::vector<int> layout(&nodes[0], &nodes[0]+2);\n\n        NeuralNetwork ann(layout, \"sigmoid\", false);\n\n        Eigen::MatrixXd input(1, 2);\n        input << 1, 1;\n\n        Eigen::MatrixXd output = ann.feedForward(input);\n        REQUIRE(output.value() == Approx(0.16148));\n    }\n\n    SECTION(\"Check feedForward with multiple inputs\", \"[NeuralNetwork]\") {\n        int nodes[3] = { 2, 2, 1 };\n        std::vector<int> layout(&nodes[0], &nodes[0]+3);\n\n        NeuralNetwork ann(layout, \"sigmoid\", false);\n\n        Eigen::MatrixXd input(4, 2);\n        input << 1, 1,\n                 0, 1,\n                 1, 0,\n                 0, 0;\n\n        Eigen::MatrixXd output = ann.feedForward(input);\n        REQUIRE(output.size() == 4);\n\n        Eigen::MatrixXd expectedResult(1, 4);\n        expectedResult << 0.36363, 0.323174, 0.350235, 0.30499;\n        REQUIRE(output.size() == expectedResult.size());\n\n        for (int i=0; i < output.cols(); ++i) {\n            for (int j=0; j < output.rows(); ++j) {\n                REQUIRE(output(j, i) == Approx(expectedResult(j, i)));\n            }\n        }\n\n    }\n\n\n}\n\nTEST_CASE(\"Testing NeuralNetwork backPropagate\", \"[NeuralNetwork]\") {\n    // create a basic layout 2 inputs, 2 nodes in the 1st layer 1 in the 2nd\n\n    SECTION(\"Check backprop with normal input\", \"[NeuralNetwork]\") {\n        int nodes[3] = { 3, 2, 1};\n        std::vector<int> layout(&nodes[0], &nodes[0]+3);\n\n        NeuralNetwork ann(layout, \"sigmoid\", false);\n\n        Eigen::MatrixXd input(1, 3);\n        input << 1, 1, 1;\n        \n        Eigen::VectorXd actual(1);\n        actual << 1;\n\n        Eigen::MatrixXd output = ann.feedForward(input);\n\n        REQUIRE(output.size() == 1);\n        REQUIRE(output.value() == Approx(0.27681));\n\n        REQUIRE_NOTHROW(ann.backPropagate(output, actual));\n    }\n\n    SECTION(\"Check backprop with two outputs\", \"[NeuralNetwork]\") {\n        int nodes[3] = { 3, 2, 2};\n        std::vector<int> layout(&nodes[0], &nodes[0]+3);\n\n        NeuralNetwork ann(layout, \"sigmoid\", false);\n\n        Eigen::MatrixXd input(1, 3);\n        input << 1, 1, 1;\n        \n        Eigen::MatrixXd output = ann.feedForward(input);\n\n        REQUIRE(output.cols() == 1);\n        REQUIRE(output.rows() == 2);\n\n        REQUIRE(output(0, 0) == Approx(0.276810));\n        REQUIRE(output(1, 0) == Approx(0.757047));\n\n        Eigen::MatrixXd actual(2, 1);\n        actual << 1, 1;\n\n        REQUIRE_NOTHROW(ann.backPropagate(output, actual));\n    }\n}\n\nTEST_CASE(\"Testing NeuralNetwork multiple inputs\", \"[NeuralNetwork]\") {\n    int nodes[3] = { 3, 3, 1 };\n    std::vector<int> layout(&nodes[0], &nodes[0]+3);\n    NeuralNetwork ann(layout, \"sigmoid\", false);\n\n    Eigen::MatrixXd input(4, 3);\n    input << 1, 1, 1,\n             1, 1, 0,\n             1, 0, 1,\n             1, 0, 0;\n\n    Eigen::MatrixXd output = ann.feedForward(input);\n    REQUIRE(output.cols() == 4);\n    REQUIRE(output.rows() == 1);\n\n    Eigen::MatrixXd expectedResult(1, 4);\n    expectedResult << 0.39573, 0.64993, 0.29571, 0.48559;\n\n    REQUIRE(output.cols() == expectedResult.cols());\n    REQUIRE(output.rows() == expectedResult.rows());\n\n    for (int i=0; i < output.cols(); ++i) {\n        for (int j=0; j < output.rows(); ++j) {\n            REQUIRE(output(j, i) == Approx(expectedResult(j, i)));\n        }\n    }\n\n    Eigen::MatrixXd actual(1, 4);\n    actual << 0, 1, 1, 0;\n\n    REQUIRE_NOTHROW(ann.backPropagate(output, actual));\n}\n\nTEST_CASE(\"Testing NeuralNetwork training\", \"[NeuralNetwork]\") {\n    int nodes[3] = { 3, 3, 1 };\n    std::vector<int> layout(&nodes[0], &nodes[0]+3);\n\n    NeuralNetwork ann(layout, \"sigmoid\", false);\n\n    Eigen::MatrixXd input(4, 3);\n    input << 1, 1, 1,\n             1, 1, 0,\n             1, 0, 1,\n             1, 0, 0;\n\n    Eigen::MatrixXd actual(1, 4);\n    actual << 0, 1, 1, 0;\n\n    REQUIRE_NOTHROW(ann.train(input, actual, 5000, 1));\n\n    Eigen::MatrixXd example(1, 3);\n    example << 1, 0, 0;\n\n    Eigen::MatrixXd output = ann.feedForward(example);\n    REQUIRE(output.value() == Approx(0.0328009245));\n}\n", "meta": {"hexsha": "9e5aa89cd05ac3d19412865015708f6ae604cc6a", "size": 5842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/NeuralNetworkTest.cpp", "max_stars_repo_name": "samueljackson92/cynapse", "max_stars_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/NeuralNetworkTest.cpp", "max_issues_repo_name": "samueljackson92/cynapse", "max_issues_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-10-09T16:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-30T07:06:21.000Z", "max_forks_repo_path": "src/test/NeuralNetworkTest.cpp", "max_forks_repo_name": "samueljackson92/cynapse", "max_forks_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2222222222, "max_line_length": 76, "alphanum_fraction": 0.5660732626, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5616642318915396}}
{"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 \u0141o\u015b <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": "\n#ifdef _MAIN_\n\n#else\n#include <armadillo>\n#include \"../core/UAmoeba.hpp\"\n#ifdef _ALGEBRA_TOOLS_\n#else\n#include \"../core/algebraTools.hpp\"\n#endif\n#ifdef _AMOEBA_INIT_\n#else\n#include \"../core/amoebaParam.cpp\"\n#endif\n\n#endif\n\nusing namespace arma;\n\n\ntemplate<typename T>\nvoid serialSolver(const AmoebaParam<T> amoebaParam)\n{\n\n\tarma_rng::set_seed_random();\n\n\tvector<vec> newGuess;\n\n\tnewGuess.resize(amoebaParam.nGridPoints);\n\tfor(int i=0; i<amoebaParam.nGridPoints; ++i)\n\t{\n\t\tnewGuess[i] = randu<vec>(amoebaParam.lieDimension);\n\t}\n\n\tUAmoeba* amoeba = new UAmoeba(amoebaParam.maxAmoebaIters,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tamoebaParam.nGridPoints,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tamoebaParam.precision,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tamoebaParam.matSize,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tamoebaParam.lieDimension,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tamoebaParam.basis);\n\n\tamoeba->solver(newGuess, amoebaParam.startBoundary, amoebaParam.endBoundary);\n\tamoeba->curvePrint();\n\n}\n", "meta": {"hexsha": "852dcd9484726744d3f49a880e6d617012461625", "size": 889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/serialSolver.cpp", "max_stars_repo_name": "Swaddle/qGeod", "max_stars_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solvers/serialSolver.cpp", "max_issues_repo_name": "Swaddle/qGeod", "max_issues_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solvers/serialSolver.cpp", "max_forks_repo_name": "Swaddle/qGeod", "max_forks_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3260869565, "max_line_length": 78, "alphanum_fraction": 0.6974128234, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5616399546413628}}
{"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.\u00c5^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*\u00c5^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*\u00c5^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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00c3\u00a4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace std;\nusing namespace mtl;\n\ntemplate <typename Matrix>\nvoid init_data(Matrix& T)\n{\n    for (unsigned i= 0; i < num_rows(T); i++)\n\tfor (unsigned j= 0; j < num_cols(T); j++)\n\t    T[i][j]= i + j + 2; // add 2 because i and j are zero-based\n}\n\ntemplate <typename Matrix, typename Vector>\nvoid w_semblance(const Matrix& T, Vector& semb, int nwin, int lwin, int linc)\n{\n    int nsamp= num_rows(T), ntr= num_cols(T);\n    dense_vector<double> sumsqr(nsamp), sqrsum(nsamp);\n\n    for (int i= 0; i < nsamp; i++) {\n\tsumsqr[i]= unary_dot(T[i][iall]);\n\tsqrsum[i]= square(sum(T[i][iall]));\n    }\n    \n    for (int i= 1, ll= 0; i <= nwin; i++, ll+= linc) {\n\tint kkend= ll + kkend > nsamp ? nsamp - ll : lwin;\n\tirange r(ll, kkend);\n\tdouble sumsq= sum(sumsqr[r]),\n\t       sumampsq= sum(sqrsum[r]),\n\t       value= ntr * sumsq;\n\tsemb[i]= value != 0.0 ? sumampsq / value : 0.0;\n    }\n}\n\n\nint main() \n{\n    //int nsamples= 30001, ntrc= 2000;\n    int nsamples= 8, ntrc= 6;\n\n    dense2D<float> traces(nsamples, ntrc);\n    init_data(traces);\n    // cout << \"T is\\n\" << traces;\n\n    dense_vector<double> semb(nsamples/2 + 1, 0.0);\n    int lwin= 5, linc= 2, nwin= size(semb) - linc;\n    w_semblance(traces, semb, nwin, lwin, linc);\n    \n    cout << \"Semblance is \" << semb << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "150bd66821fa21c2ab36e88f5e10b2fbb5e3df2f", "size": 1790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/semblance_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/experimental/semblance_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/experimental/semblance_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 27.1212121212, "max_line_length": 94, "alphanum_fraction": 0.6212290503, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5616228396037107}}
{"text": "#include \"Polynomial.h\"\n\n#include <complex>\n#include <iostream>\n\n#define BOOST_TEST_MODULE Polynomial\n#include <boost/test/included/unit_test.hpp>\n\nusing namespace std;\nusing namespace Storage_B::Polynomials;\n\n// 0 degree polynomial\nBOOST_AUTO_TEST_CASE(zero_degree)\n{\n  Polynomial<double> p0(42.0);\n\n  BOOST_CHECK(p0.degree() == 0);\n  BOOST_CHECK(p0[0] == 42.0);\n  BOOST_CHECK(p0(0.123) == 42.0);\n}\n\n// first degree polynomial\nBOOST_AUTO_TEST_CASE(first_degree)\n{\n  Polynomial<double> p1(0.0, 1);\n  p1[0] = -1.0;\n  p1[1] = 1.0;\n\n  BOOST_CHECK(p1.degree() == 1);\n  BOOST_CHECK(p1(0.0) == -1.0);\n  BOOST_CHECK(p1(1.0) == 0.0);\n  BOOST_CHECK(p1(2.0) == 1.0);\n  BOOST_CHECK(p1(-1.0) == -2.0);\n}\n\n// second degree polynomial\nBOOST_AUTO_TEST_CASE(second_degree)\n{\n  double c[3] ;\n\n  c[0] = 2.0 ;\n  c[1] = -1.0;\n  c[2] = 3.0 ;\n\n  Polynomial<double> p2(c, 2) ;\n  \n  BOOST_CHECK(p2.degree() == 2);\n  BOOST_CHECK(p2(0.0) == 2.0);\n  BOOST_CHECK(p2(1.0) == 4.0);\n  BOOST_CHECK(p2(2.0) == 12.0);\n}\n\n// third degree polynomial\nBOOST_AUTO_TEST_CASE(third_degree)\n{\n  vector<float> c;\n\n  c.push_back(-1.0);\n  c.push_back(1.0);\n  c.push_back(-2.0);\n  c.push_back(3.0);\n\n  Polynomial<float> p3(c);\n  \n  BOOST_CHECK(p3.degree() == 3);\n  BOOST_CHECK(p3(0.0) == -1.0);\n  BOOST_CHECK(p3(1.0) == 1.0);\n  BOOST_CHECK(p3(-1.0) == -7.0);\n}\n\n// increment degree\nBOOST_AUTO_TEST_CASE(increment_degree)\n{\n  double c[3] ;\n\n  c[0] = 2.0 ;\n  c[1] = -1.0;\n  c[2] = 3.0 ;\n\n  Polynomial<double> p(c, 2) ;\n\n  BOOST_CHECK(p.degree() == 2);\n\n  p.IncrementDegree(12.0);\n\n  BOOST_CHECK(p.degree() == 3);\n  BOOST_CHECK(p[0] == 2);\n  BOOST_CHECK(p[1] == -1.0);\n  BOOST_CHECK(p[2] == 3.0);\n  BOOST_CHECK(p[3] == 12.0);\n}\n\n// decrement degree\nBOOST_AUTO_TEST_CASE(decrement_degree)\n{\n  double c[3] ;\n\n  c[0] = 2.0 ;\n  c[1] = -1.0;\n  c[2] = 3.0 ;\n\n  Polynomial<double> p(c, 2);\n\n  BOOST_CHECK(p.degree() == 2);\n\n  auto val = p.DecrementDegree();\n\n  BOOST_CHECK(p.degree() == 1);\n  BOOST_CHECK(p[0] == 2);\n  BOOST_CHECK(p[1] == -1.0);\n  BOOST_CHECK(val == 3.0);\n}\n\n// complex polynomial\nBOOST_AUTO_TEST_CASE(complex_poly)\n{\n  Polynomial<complex<double> > p;\n  p[0] = 1.0;\n  p.IncrementDegree(0.0);\n  p.IncrementDegree(1.0);\n\n  BOOST_CHECK(p.degree() == 2);\n  BOOST_CHECK(p(1.0i) == 0.0);\n  \n  p.IncrementDegree();\n\n  BOOST_CHECK(p.degree() == 3);\n  BOOST_CHECK(p[3] == 0.0);\n\n  p[3] = 2.0 - 3.0i;\n  complex<double> result = p(2.0 + 1.0i);\n\n  BOOST_CHECK(result.real() == 41);\n  BOOST_CHECK(result.imag() == 20);\n}\n\n// Evaluate\nBOOST_AUTO_TEST_CASE(derivative)\n{\n  vector<double> c;\n\n  c.push_back(2.0) ;\n  c.push_back(-1.0);\n  c.push_back(3.0) ;\n  Polynomial<double> f(c);\n\n  c.clear();\n  c.push_back(f[1]);\n  c.push_back(2.0 * f[2]);\n  Polynomial<double> fprime(c);\n\n  double x = 42.0;\n \n  auto res = f.eval(x);\n\n  BOOST_CHECK(res.first == f(x)); // y = f(x) \n  BOOST_CHECK(res.second == fprime(x)); // dy/dx = f'(x)\n}\n", "meta": {"hexsha": "66210d4ea08ada7bfe8b0e0bfdc969a182863aee", "size": 2875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test.cpp", "max_stars_repo_name": "jachappell/Polynomial", "max_stars_repo_head_hexsha": "c53aa8b2e9228e081fe02b6608175646b6ff0254", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-02-17T17:02:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-11T19:05:29.000Z", "max_issues_repo_path": "tests/test.cpp", "max_issues_repo_name": "jachappell/Polynomial", "max_issues_repo_head_hexsha": "c53aa8b2e9228e081fe02b6608175646b6ff0254", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test.cpp", "max_forks_repo_name": "jachappell/Polynomial", "max_forks_repo_head_hexsha": "c53aa8b2e9228e081fe02b6608175646b6ff0254", "max_forks_repo_licenses": ["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.0817610063, "max_line_length": 56, "alphanum_fraction": 0.6100869565, "num_tokens": 1066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5616228245023748}}
{"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": "//==================================================================================================\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_CORRECT_FMA_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_CORRECT_FMA_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-arithmetic\n    Function object function implementing correct_fma\n\n    Computes the \"correct\" fused multiply/add of its parameter: this is perhaps not that you need\n    if speed is needed more than accuracy (this remark is hardware dependent).\n\n    @par semantic:\n    For any given value @c x, @c y, @c z of type @c T:\n\n    @code\n    T r = correct_fma(x, y, z);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = x*y+z;\n    @endcode\n\n    but is only rounded once and with no intermediate overflow.\n\n    @par Notes:\n    - For integers x*y+z is always performed in 2-complement wraping.\n\n    - For floating points numbers, the correct fused multiply add is computed,\n    meaning the computation of x*y+z with only one rounding operation.\n    This operation may be very expensive on architectures where this\n    functionality is not hardware provided.\n\n    - @c correct_fma is in fact a transitory function which ensures\n    strict @ref fma capabilities, i.e. only one rounding operation and no undue\n    overflow in intermediate computations.\n\n    - If you are using this function on an architecture without @ref fma\n    and are sure that overflow is not a problem\n    you may define BOOST_SIMD_DONT_CARE_CORRECT_FMA_OVERFLOW for better\n    performance.\n\n    - @c correct_fma is never used internally in boost.simd.\n\n    @par Decorators\n      std_ for floating entries calls std::fma but does not guarantee performances...\n\n    @see  fma, fms fnma, fnms\n**/\n     Value correct_fma(Value const& v0, Value const& v1, Value const& v2);\n} }\n#endif\n\n#include <boost/simd/function/scalar/correct_fma.hpp>\n#include <boost/simd/function/simd/correct_fma.hpp>\n\n#endif\n", "meta": {"hexsha": "d19cff7e27bd4e31bd2af44f2e7bc11027327c3b", "size": 2245, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/correct_fma.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/correct_fma.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/correct_fma.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": 31.1805555556, "max_line_length": 100, "alphanum_fraction": 0.6623608018, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5615635743018168}}
{"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    // \u5206\u522b\u662f\u6b8b\u5dee\uff0cq\uff0ct\u7684\u7ef4\u5ea6\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\u662f[0,0,0,1,x,y,z]\n  virtual bool Evaluate(double const* const* parameters, double* residuals, double** jacobians) const {\n    // \u9ed8\u8ba4\u5df2\u7ecf\u5f52\u4e00\u5316\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// \u5f03\u7528\n// \u7cbe\u5ea6\u4e0d\u9ad8\uff0c\u800c\u4e14\u8017\u65f6\n// Z\u662fR*Sigma_i*RT\u5bf9\u674e\u4ee3\u6570\u7684\u96c5\u53ef\u6bd4\u77e9\u9635\uff0c\u6765\u81ea\u4e8ed2d-ndt\uff0c\u5177\u4f53\u5982\u4f55\u8ba1\u7b97\uff0c\u6211\u4e0d\u6e05\u695a\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\u662f[0,0,0,1,x,y,z]\n  virtual bool Evaluate(double const* const* parameters, double* residuals, double** jacobians) const {\n    // \u9ed8\u8ba4\u5df2\u7ecf\u5f52\u4e00\u5316\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// \u6b63\u5e38\u5de5\u4f5c\uff0c\u4f46\u7cbe\u5ea6\u5e76\u4e0d\u662f\u7279\u522b\u7684\u9ad8\n// TODO \u5220\u9664\u65e0\u6548\u4ee3\u7801\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\u662f[0,0,0,1,x,y,z]\n  virtual bool Evaluate(double const* const* parameters, double* residuals, double** jacobians) const {\n    // \u9ed8\u8ba4\u5df2\u7ecf\u5f52\u4e00\u5316\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": "#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <ceres/ceres.h>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n#include <maplab-common/pose_types.h>\n#include <maplab-common/quaternion-math.h>\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\n#include \"ceres-error-terms/parameterization/pose-param-jpl.h\"\n\nstruct CostFunctor {\n  explicit CostFunctor(const pose::Transformation& reference)\n      : reference_(reference) {}\n  template <typename T>\n  bool operator()(const T* const x, T* residual) const {\n    typedef kindr::minimal::RotationQuaternionTemplate<T> QuaternionT;\n\n    // x is currently passed from x.coeffs() Eigen function that returns\n    // (x, y, z, w) JPL convention so we need to map it first to Eigen\n    // Quaternion and then construct a kindr quaternion on top\n    const Eigen::Map<const Eigen::Quaternion<T>> current_rot(x);\n    const Eigen::Map<const Eigen::Matrix<T, 3, 1>> current_pos(x + 4);\n    Eigen::Map<Eigen::Matrix<T, 6, 1>> error(residual);\n\n    QuaternionT error_quaternion = common::signedQuaternionProductHamilton(\n        QuaternionT(current_rot),\n        QuaternionT(\n            reference_.getRotation().inverse().toImplementation().cast<T>()));\n\n    error.head(3) = Eigen::Matrix<T, 3, 1>(\n        T(2.0) * error_quaternion.x(), T(2.0) * error_quaternion.y(),\n        T(2.0) * error_quaternion.z());\n    error.tail(3) = current_pos - reference_.getPosition().cast<T>();\n\n    return true;\n  }\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n private:\n  pose::Transformation reference_;\n};\n\nTEST(JplPoseParameterization, SimpleMinimization) {\n  // Initial state values.\n  pose::Quaternion x_rot(1, 0, 0, 0);\n  pose::Position3D x_pos(1, 3.7, 0);\n  // Create contiguous pose memory.\n  Eigen::Matrix<double, 7, 1> x_pose;\n  x_pose << x_rot.toImplementation().coeffs(), x_pos;\n\n  // Reference transformation the solver should arrive at.\n  pose::Quaternion reference_rot(sqrt(2) / 2, sqrt(2) / 2, 0, 0);\n  pose::Position3D reference_pos(0.2, -0.3, 0.7);\n  pose::Transformation reference(reference_pos, reference_rot);\n\n  ceres::Problem problem;\n  ceres::CostFunction* cost_function =\n      new ceres::AutoDiffCostFunction<CostFunctor, 6, 7>(\n          new CostFunctor(reference));\n  problem.AddResidualBlock(cost_function, NULL, x_pose.data());\n  ceres::LocalParameterization* pose_parameterization =\n      new ceres_error_terms::JplPoseParameterization;\n  problem.SetParameterization(x_pose.data(), pose_parameterization);\n\n  ceres::Solver::Options options;\n  options.minimizer_progress_to_stdout = false;\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n\n  pose::Quaternion out_rot(\n      Eigen::Map<Eigen::Quaternion<double>>(x_pose.head(4).data()));\n  Eigen::Vector3d out_pos(x_pose.tail(3));\n  EXPECT_NEAR_KINDR_QUATERNION(out_rot, reference_rot, 1e-6);\n  EXPECT_NEAR_EIGEN(out_pos, reference_pos, 1e-10);\n  LOG(INFO) << summary.BriefReport() << std::endl;\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "e131c192ca0252228924df9b9adbb4c372fc80d2", "size": 3007, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/ceres-error-terms/test/test_pose_parameterization_test.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "algorithms/ceres-error-terms/test/test_pose_parameterization_test.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "algorithms/ceres-error-terms/test/test_pose_parameterization_test.cc", "max_forks_repo_name": "AdronTech/maplab", "max_forks_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 661.0, "max_forks_repo_forks_event_min_datetime": "2017-11-28T07:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:06:29.000Z", "avg_line_length": 36.2289156627, "max_line_length": 78, "alphanum_fraction": 0.716661124, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5615367005157438}}
{"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": "#define OPENCV_DISABLE_EIGEN_TENSOR_SUPPORT\n\n#include <unistd.h>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/eigen.hpp>\n#include \"image_segmentation_utils.h\"\n#include <getopt.h>\n\nusing namespace cv;\n\n\nint main(int argc, char *argv[]) {\n\tint o;\n\tchar* imagePath;\n\tint numNodes = 5000;\n\tchar* outputPath;\n    std::string logFile;\n    bool log_file_is_set = false;\n\tint option_idx;\n\n\tstruct option long_options[] = {\n        {\"input\", required_argument, NULL, 'i'},\n        {\"pixel\", required_argument, NULL, 'n'},\n        {\"output\", required_argument, NULL, 'o'},\n        {\"log\", required_argument, NULL, 'l'},\n    };\n\n\tif (argc == 1) {\n\t\tprintf(\"Usage: image_segmentation <command>\\n\\nCommands:\\n  -i --input <path>\\tInput file path\\n\"\n\t\t\t\t\"  -n --pixel <num_pixels>\\tNumber of pixels of the output picture (5000 by default)\\n\"\n\t\t\t\t\"  -o --output <path>\\tOutput file path (prefer .bmp extension to avoid opencv bug)\\n\"\n\t\t\t\t\"  -l --log <path>\\tLog file path \\n\");\n\t\treturn 0;\n\t}\n    const char *optstring = \"i:n:o:l:h\";\n    while ((o = getopt_long(argc, argv, optstring, long_options, &option_idx)) != -1) {\n        switch (o) {\n            case 'i':\n\t\t\t\timagePath = optarg;\n                break;\n            case 'n':\n                numNodes = atoi(optarg);\n\t\t\t\tbreak;\n            case 'o':\n\t\t\t\toutputPath = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'l':\n\t\t\t\tlog_file_is_set = true;\n\t\t\t\tlogFile = optarg;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprintf(\"Usage: image_segmentation <command>\\n\\nCommands:\\n  -i --input <path>\\tInput file path\\n\"\n\t\t\t\t\t\t\"  -n --pixel <num_pixels>\\tNumber of pixels of the output picture (5000 by default)\\n\"\n\t\t\t\t\t\t\"  -o --output <path>\\tOutput file path (prefer .bmp extension to avoid opencv bug)\\n\"\n\t\t\t\t\t\t\"  -l --log <path>\\tLog file path \\n\");\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\tMat image = imread(imagePath, 0);\n\tdouble lambda = 3.0;\n\n\t/* Scaling the picture */\n\tdouble scale = std::sqrt(numNodes / (double) (image.rows * image.cols));\n\tMat scaled_image;\n\tSize scaled_size = Size(std::round(scale * image.cols), std::round(scale * image.rows));\n\tresize(image, scaled_image, Size(), scale, scale);\n\n\tint numPixels = scaled_image.rows * scaled_image.cols;\n\tDenseMatrix I;\n\tcv2eigen(scaled_image, I);\n\n\t/* Rescale the value of each pixel between [0, 1] */\n\tI.array() = I.array() / 256.0;\n\tDenseMatrix unary_cost;\n\tSparseMatrix binary_cost;\n\n\tdouble sigma = 0.1;\n\tdouble b = 0.6;\n\tdouble f1 = 0.2;\n\tdouble f2 = 0.2;\n\n\tget_unary_cost(I, sigma, b, f1, f2, unary_cost);\n\tget_binary_cost(I, binary_cost); /* Actually calculating round(lambda * W) in this so we can get the \n\t\t\t\t\t\t\t\t\t  * binary cost directly */\n\n\tunary_cost.array() = unary_cost.array().round();\n\n\tSparseMatrix _A;\n\tDenseVector _b;\n\tget_A_b_from_cost(unary_cost, binary_cost, _A, _b);\n\n\tprintf(\"Finished generating matrices, starting algorithm\\n\");\n\tSolution sol;\n\tDenseVector x0 = DenseVector::Zero(_b.rows());\n\tLPboxADMMsolver solver;\n\tsolver.ADMM_bqp_unconstrained_init();\n\n\tif (log_file_is_set) {\n\t\tsolver.set_log_file(logFile);\n\t\tprintf(\"Writing log output to %s\\n\", logFile.c_str());\n\t}\n\tsolver.ADMM_bqp_unconstrained_legacy(_A.cols(), _A, _b, x0, sol);\n\tprintf(\"Algorithm finishes, saving picture\\n\");\n\n\t/* Reshape the solution to fit the size of the image */\n\tDenseMatrix reshaped_mat = Eigen::Map<DenseMatrix>(sol.x_sol->data(), I.rows(), I.cols());\n\n\t/* Setting the location with value 1 to be white */\n\tDenseIntMatrix r_mat = (reshaped_mat.array() >= 0.5).matrix().cast<int>() * 255;\n\tMat res_mat(r_mat.rows(), r_mat.cols(), CV_8UC1);\n\teigen2cv(r_mat, res_mat);\n\timwrite(outputPath, res_mat);\n\n\tdelete sol.best_sol;\n\tdelete sol.x_sol;\n\tdelete sol.y1;\n\tdelete sol.y2;\n\treturn 1;\n}\n", "meta": {"hexsha": "ba5807ee75d230ce941716d3bec88953166d03ad", "size": 3698, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/demo/image_segmentation.cpp", "max_stars_repo_name": "xiaogaogaoxiao/Lpbox-ADMM", "max_stars_repo_head_hexsha": "8bce0b996a5c369b87ca5a6b0ff80aac36c6daa3", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/demo/image_segmentation.cpp", "max_issues_repo_name": "xiaogaogaoxiao/Lpbox-ADMM", "max_issues_repo_head_hexsha": "8bce0b996a5c369b87ca5a6b0ff80aac36c6daa3", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/demo/image_segmentation.cpp", "max_forks_repo_name": "xiaogaogaoxiao/Lpbox-ADMM", "max_forks_repo_head_hexsha": "8bce0b996a5c369b87ca5a6b0ff80aac36c6daa3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-16T04:13:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-06T13:14:11.000Z", "avg_line_length": 30.3114754098, "max_line_length": 102, "alphanum_fraction": 0.6600865333, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117812622842, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5614850214537265}}
{"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": "/*    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 *      Melman, J. Propagate software, J.C.P.Melman@tudelft.nl, 2010.\n *      NASA, Goddard Spaceflight Center. Orbit Determination Toolbox (ODTBX), NASA - GSFC Open\n *          Source Software, http://opensource.gsfc.nasa.gov/projects/ODTBX/, last accessed:\n *          31st January, 2012.\n *      ESA, GTOP Toolbox, http://www.esa.int/gsp/ACT/doc/INF/Code/globopt/GTOPtoolbox.rar.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/keplerPropagator.h\"\n\n#include <Eigen/Core>\n\n#include <map>\n#include <limits>\n\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n#include \"Tudat/Basics/testMacros.h\"\n\n#include \"Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Basics/basicTypedefs.h\"\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/keplerPropagatorTestData.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/keplerPropagator.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace orbital_element_conversions;\n\n//! Test 1: Comparison of propagateKeplerOrbit() output with benchmark data from (Melman, 2010).\nBOOST_AUTO_TEST_CASE( testPropagateKeplerOrbit_Eccentric_Melman )\n{\n    // Load benchmark data.\n    // This data originates from J. Melman and is generated by the software package Propagate.\n\n    // Create propagation history map for benchmark data to be stored in.\n    PropagationHistory benchmarkKeplerPropagationHistory = getMelmanBenchmarkData( );\n\n    // Propagate to final state in Keplerian elements.\n    Eigen::Vector6d computedFinalStateInKeplerianElements\n            = propagateKeplerOrbit(\n                benchmarkKeplerPropagationHistory.begin( )->second,\n                benchmarkKeplerPropagationHistory.rbegin( )->first -\n                benchmarkKeplerPropagationHistory.begin( )->first,\n                getMelmanEarthGravitationalParameter( ) );\n\n    // Check that computed results match expected results.\n    BOOST_CHECK_CLOSE_FRACTION(\n                benchmarkKeplerPropagationHistory.rbegin( )->second( 5 ),\n                basic_mathematics::computeModulo( computedFinalStateInKeplerianElements( 5 ),\n                                                  2.0 * mathematical_constants::PI ), 1.0e-8 );\n}\n\n//! Test 2: Comparison of kepprop2b() test output from (GSFC, 2012) using modulo option.\nBOOST_AUTO_TEST_CASE( testPropagateKeplerOrbit_Eccentric_kepprop2b_modulo )\n{\n    // Create expected propagation history.\n    PropagationHistory expectedPropagationHistory = getODTBXBenchmarkData( );\n\n    // Set Earth gravitational parameter [m^3 s^-2].\n    const double earthGravitationalParameter = 398600.4415e9;\n\n    // Set time step for ODTBX benchmark data.\n    const double timeStep = 8640.0;\n\n    // Compute propagation history.\n    PropagationHistory computedPropagationHistory;\n    computedPropagationHistory[ 0.0 ] = expectedPropagationHistory[ 0.0 ];\n\n    for ( unsigned int i = 1; i < expectedPropagationHistory.size( ); i++ )\n    {\n        computedPropagationHistory[ static_cast< double >( i ) * timeStep ]\n                = propagateKeplerOrbit(\n                    computedPropagationHistory[ static_cast< double >( i - 1 ) * timeStep ],\n                    timeStep, earthGravitationalParameter  );\n\n        computedPropagationHistory[ static_cast< double >( i ) * timeStep ]( 5 )\n                = basic_mathematics::computeModulo(\n                    computedPropagationHistory[ static_cast< double >( i ) * timeStep ]( 5 ),\n                    2.0 * mathematical_constants::PI );\n\n        // Check that computed results match expected results.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                    computedPropagationHistory[ static_cast< double >( i ) * timeStep ],\n                    expectedPropagationHistory[ static_cast< double >( i ) * timeStep ],\n                    1.0e-13 );\n    }\n}\n\n//! Test 3: Comparison of kepprop2b() test output from (GSFC, 2012), propagating backwards.\nBOOST_AUTO_TEST_CASE( testPropagateKeplerOrbit_Eccentric_kepprop2b_backwards )\n{\n    // Create expected propagation history.\n    PropagationHistory expectedPropagationHistory = getODTBXBenchmarkData( );\n\n    // Set Earth gravitational parameter [m^3 s^-2].\n    const double earthGravitationalParameter = 398600.4415e9;\n\n    // Set time step for ODTBX benchmark data.\n    const double timeStep = 8640.0;\n\n    // Compute propagation history.\n    PropagationHistory computedPropagationHistory;\n    computedPropagationHistory[ 10.0 * 8640.0 ] = expectedPropagationHistory[ 10.0 * 8640.0 ];\n\n    for ( int i = expectedPropagationHistory.size( ) - 2; i >= 0; i-- )\n    {\n        computedPropagationHistory[ static_cast< double >( i ) * timeStep ]\n                = propagateKeplerOrbit(\n                    computedPropagationHistory[ static_cast< double >( i + 1 ) * timeStep ],\n                    -timeStep, earthGravitationalParameter );\n\n        computedPropagationHistory[ static_cast< double >( i ) * timeStep ]( 5 )\n                = basic_mathematics::computeModulo(\n                    computedPropagationHistory[ static_cast< double >( i ) * timeStep ]( 5 ),\n                    2.0 * mathematical_constants::PI );\n\n        // Check that computed results match expected results.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                    computedPropagationHistory[ static_cast< double >( i ) * timeStep ],\n                    expectedPropagationHistory[ static_cast< double >( i ) * timeStep ],\n                    1.0e-13 );\n    }\n}\n\n//! Test 4: Comparison of hyperbolic kepler propagation with that of GTOP.\nBOOST_AUTO_TEST_CASE( testPropagateKeplerOrbit_hyperbolic_GTOP )\n{\n    // Load the expected propagation history.\n    PropagationHistory expectedPropagationHistory = getGTOPBenchmarkData( );\n\n    // Set the time step for the GTOP benchmark data to 100 days.\n    const double timeStep = 86400.0 * 100.0;\n\n    // Compute propagation history.\n    PropagationHistory computedPropagationHistory;\n    computedPropagationHistory[ 0.0 ] = expectedPropagationHistory[ 0.0 ];\n\n    for ( unsigned int i = 1; i < expectedPropagationHistory.size( ); i++ )\n    {\n        // Compute next entry.\n        computedPropagationHistory[ static_cast< double >( i ) * timeStep ] =\n                propagateKeplerOrbit(\n                    computedPropagationHistory[ static_cast< double >( i - 1 ) * timeStep ],\n                    timeStep, getGTOPGravitationalParameter( ) );\n\n        // Check that computed results match expected results.\n        BOOST_CHECK_CLOSE_FRACTION(\n                    computedPropagationHistory[ static_cast< double >( i ) * timeStep ]( 5 ),\n                    expectedPropagationHistory[ static_cast< double >( i ) * timeStep ]( 5 ),\n                    1.0e-15 );\n    }\n}\n\n//! Test 5: Unit test that failed on versions that caused the old modulo function to crash.\nBOOST_AUTO_TEST_CASE( testPropagateKeplerOrbit_FunctionFailingOnOldModuloFunction )\n{\n    // Set expected true anomaly.\n    const double expectedTrueAnomaly = -3.1245538487052089;\n\n    // Set the propagation time.\n    const double propagationTime = 8651869.8944624383;\n\n    // Set the gravitational parameter (of the Sun).\n    const double gravitationalParameter = 1.32712428e20;\n\n    // Set initial Keplerian elements.\n    Eigen::Vector6d keplerElements;\n    keplerElements << 56618890355.593132, 0.99961601437304082, 1.0238269559089248,\n            3.1526292818328812, 1.5807574453453865, 3.1478950321924795;\n\n    // Propagate Keplerian elements.\n    keplerElements = propagateKeplerOrbit(\n                keplerElements, propagationTime, gravitationalParameter );\n\n    // Check that computed results match expected results.\n    BOOST_CHECK_CLOSE_FRACTION( keplerElements( trueAnomalyIndex ),\n                                expectedTrueAnomaly,\n                                1.0e-15 );\n}\n\n//! Test 6. Propagation test using ODTBX test Kepler elements.\nBOOST_AUTO_TEST_CASE( testMeanAnomalyAgainstMeanMotion )\n{\n    std::vector< double > doubleErrors;\n    // Test using double parameters.\n    {\n        double gravitationalParameter = 398600.4415e9;\n        Eigen::Vector6d initialStateInKeplerianElements;\n\n        initialStateInKeplerianElements << 42165.3431351313e3, 0.26248354351331, 0.30281462522101,\n                4.71463172847351, 4.85569272927819, 2.37248926702153;\n        double timeStep = 600.0;\n        double meanMotion = std::sqrt( gravitationalParameter /\n                                       std::pow( initialStateInKeplerianElements( 0 ), 3.0 ) );\n\n        double initialMeanAnomaly = convertEccentricAnomalyToMeanAnomaly(\n                    convertTrueAnomalyToEccentricAnomaly(\n                        initialStateInKeplerianElements( 5 ), initialStateInKeplerianElements( 1 ) ),\n                    initialStateInKeplerianElements( 1 ) );\n\n        double propagationTime, propagatedMeanAnomaly;\n\n        Eigen::Vector6d propagatedKeplerElements;\n\n\n        for( int i = -25; i < 26; i++ )\n        {\n            propagationTime = static_cast< double >( i ) * timeStep;\n            propagatedKeplerElements = propagateKeplerOrbit(\n                        initialStateInKeplerianElements, propagationTime, gravitationalParameter );\n            propagatedMeanAnomaly = convertEccentricAnomalyToMeanAnomaly(\n                        convertTrueAnomalyToEccentricAnomaly(\n                            propagatedKeplerElements( 5 ), initialStateInKeplerianElements( 1 ) ),\n                        initialStateInKeplerianElements( 1 ) );\n            doubleErrors.push_back( meanMotion * propagationTime - ( propagatedMeanAnomaly - initialMeanAnomaly ) );\n        }\n    }\n\n    std::vector< double > longDoubleErrors;\n    // Test using long double parameters.\n    {\n        long double gravitationalParameter = 398600.4415e9L;\n        Eigen::Matrix< long double, 6, 1 > initialStateInKeplerianElements;\n\n        initialStateInKeplerianElements << 42165.3431351313e3L, 0.26248354351331L, 0.30281462522101L,\n                4.71463172847351L, 4.85569272927819L, 2.37248926702153L;\n        long double timeStep = 600.0L;\n        long double meanMotion = std::sqrt( gravitationalParameter /\n                                            ( initialStateInKeplerianElements( 0 ) *\n                                              initialStateInKeplerianElements( 0 ) *\n                                              initialStateInKeplerianElements( 0 ) ) );\n\n        long double initialMeanAnomaly = convertEccentricAnomalyToMeanAnomaly< long double >(\n                    convertTrueAnomalyToEccentricAnomaly< long double >(\n                        initialStateInKeplerianElements( 5 ), initialStateInKeplerianElements( 1 ) ),\n                    initialStateInKeplerianElements( 1 ) );\n\n        long double propagationTime, propagatedMeanAnomaly;\n\n        Eigen::Matrix< long double, 6, 1 > propagatedKeplerElements;\n\n\n        for( int i = -25; i < 26; i++ )\n        {\n            propagationTime = static_cast< long double >( i ) * timeStep;\n\n            propagatedKeplerElements = propagateKeplerOrbit< long double >(\n                        initialStateInKeplerianElements, propagationTime, gravitationalParameter );\n            propagatedMeanAnomaly = convertEccentricAnomalyToMeanAnomaly< long double >(\n                        convertTrueAnomalyToEccentricAnomaly< long double >(\n                            propagatedKeplerElements( 5 ), initialStateInKeplerianElements( 1 ) ),\n                        initialStateInKeplerianElements( 1 ) );\n\n            longDoubleErrors.push_back( static_cast< double >(\n                                            meanMotion * propagationTime -\n                                            ( propagatedMeanAnomaly - initialMeanAnomaly ) ) );\n        }\n    }\n\n    for( unsigned int i = 0; i < doubleErrors.size( ); i++ )\n    {\n        BOOST_CHECK_SMALL( std::fabs( static_cast< double >( longDoubleErrors.at( i ) ) ),\n                           static_cast< double >( 5.0 * std::numeric_limits< long double >::epsilon( ) ) );\n        BOOST_CHECK_SMALL( std::fabs( static_cast< double >( doubleErrors.at( i ) ) ),\n                           static_cast< double >( 5.0 * std::numeric_limits< double >::epsilon( ) ) );\n    }\n}\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "cb2430248b6454e56cfc9962cf993e91b55c71dc", "size": 12933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestKeplerPropagator.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestKeplerPropagator.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestKeplerPropagator.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2910958904, "max_line_length": 116, "alphanum_fraction": 0.6609448697, "num_tokens": 3036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5614089443916888}}
{"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": "#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <iostream>\n#include <random> // Requires C++ 11\n\n#include <SymGEigsSolver.h>\n#include <MatOp/SparseSymMatProd.h>\n#include <MatOp/SparseRegularInverse.h>\n\nusing namespace Spectra;\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\ntypedef Eigen::MatrixXd Matrix;\ntypedef Eigen::VectorXd Vector;\ntypedef Eigen::SparseMatrix<double> SpMatrix;\n\n// Generate random sparse matrix\nSpMatrix sprand(int size, double prob = 0.5)\n{\n    SpMatrix mat(size, size);\n    std::default_random_engine gen;\n    gen.seed(0);\n    std::uniform_real_distribution<double> distr(-1.0, 1.0);\n    for(int i = 0; i < size; i++)\n    {\n        for(int j = 0; j < size; j++)\n        {\n            if(distr(gen) < prob)\n                mat.insert(i, j) = distr(gen);\n        }\n    }\n    return mat;\n}\n\nvoid gen_sparse_data(int n, SpMatrix& A, SpMatrix& B)\n{\n    // Eigen solver only uses the lower triangle of A,\n    // so we don't need to make A symmetric here.\n    A = sprand(n, 0.1);\n    B = A.transpose() * A;\n    // To make sure B is positive definite\n    for(int i = 0; i < n; i++)\n        B.coeffRef(i, i) += 0.1;\n}\n\n\n\ntemplate <int SelectionRule>\nvoid run_test(const SpMatrix& A, const SpMatrix& B, int k, int m, bool allow_fail = false)\n{\n    typedef SparseSymMatProd<double> OpType;\n    typedef SparseRegularInverse<double> BOpType;\n    OpType op(A);\n    BOpType Bop(B);\n    SymGEigsSolver<double, SelectionRule, OpType, BOpType, GEIGS_REGULAR_INVERSE> eigs(&op, &Bop, k, m);\n    eigs.init();\n    int nconv = eigs.compute(100); // maxit = 100 to reduce running time for failed cases\n    int niter = eigs.num_iterations();\n    int nops  = eigs.num_operations();\n\n    if(allow_fail)\n    {\n        if( eigs.info() != SUCCESSFUL )\n        {\n            WARN( \"FAILED on this test\" );\n            std::cout << \"nconv = \" << nconv << std::endl;\n            std::cout << \"niter = \" << niter << std::endl;\n            std::cout << \"nops  = \" << nops  << std::endl;\n            return;\n        }\n    } else {\n        INFO( \"nconv = \" << nconv );\n        INFO( \"niter = \" << niter );\n        INFO( \"nops  = \" << nops );\n        REQUIRE( eigs.info() == SUCCESSFUL );\n    }\n\n    Vector evals = eigs.eigenvalues();\n    Matrix evecs = eigs.eigenvectors();\n\n    Matrix resid = A.template selfadjointView<Eigen::Lower>() * evecs -\n                   B.template selfadjointView<Eigen::Lower>() * evecs * evals.asDiagonal();\n    const double err = resid.array().abs().maxCoeff();\n\n    INFO( \"||AU - BUD||_inf = \" << err );\n    REQUIRE( err == Approx(0.0) );\n}\n\nvoid run_test_sets(const SpMatrix& A, const SpMatrix& B, int k, int m)\n{\n    SECTION( \"Largest Magnitude\" )\n    {\n        run_test<LARGEST_MAGN>(A, B, k, m);\n    }\n    SECTION( \"Largest Value\" )\n    {\n        run_test<LARGEST_ALGE>(A, B, k, m);\n    }\n    SECTION( \"Smallest Magnitude\" )\n    {\n        run_test<SMALLEST_MAGN>(A, B, k, m, true);\n    }\n    SECTION( \"Smallest Value\" )\n    {\n        run_test<SMALLEST_ALGE>(A, B, k, m);\n    }\n    SECTION( \"Both Ends\" )\n    {\n        run_test<BOTH_ENDS>(A, B, k, m);\n    }\n}\n\nTEST_CASE(\"Generalized eigensolver of sparse symmetric real matrix [10x10]\", \"[geigs_sym]\")\n{\n    std::srand(123);\n\n    // Eigen solver only uses the lower triangle\n    SpMatrix A, B;\n    gen_sparse_data(10, A, B);\n    int k = 3;\n    int m = 6;\n\n    run_test_sets(A, B, k, m);\n}\n\nTEST_CASE(\"Generalized eigensolver of sparse symmetric real matrix [100x100]\", \"[geigs_sym]\")\n{\n    std::srand(123);\n\n    // Eigen solver only uses the lower triangle\n    SpMatrix A, B;\n    gen_sparse_data(100, A, B);\n    int k = 10;\n    int m = 20;\n\n    run_test_sets(A, B, k, m);\n}\n\n// Too time-consuming\n/*\nTEST_CASE(\"Generalized eigensolver of sparse symmetric real matrix [1000x1000]\", \"[geigs_sym]\")\n{\n    std::srand(123);\n\n    // Eigen solver only uses the lower triangle\n    SpMatrix A, B;\n    gen_sparse_data(1000, A, B);\n    int k = 20;\n    int m = 50;\n\n    run_test_sets(A, B, k, m);\n}\n*/\n", "meta": {"hexsha": "f656afd3fcc5c45ae2671c827d159a56a9866776", "size": 3979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/spectra/test/SymGEigsRegInv.cpp", "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": "libraries/spectra/test/SymGEigsRegInv.cpp", "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": "libraries/spectra/test/SymGEigsRegInv.cpp", "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": 25.5064102564, "max_line_length": 104, "alphanum_fraction": 0.5928625283, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5613717300738882}}
{"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 Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/integral.hpp>\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/list/instance.hpp>\n#include <boost/hana/monoid/laws.hpp>\nusing namespace boost::hana;\n\n\nint main() {\n    BOOST_HANA_CONSTANT_ASSERT(zero<Integral> == int_<0>);\n    BOOST_HANA_CONSTANT_ASSERT(plus(int_<3>, int_<4>) == int_<3 + 4>);\n    BOOST_HANA_CONSTEXPR_ASSERT(plus(int_<3>, 4) == 3 + 4);\n    BOOST_HANA_CONSTEXPR_ASSERT(plus(3, int_<4>) == 3 + 4);\n\n    BOOST_HANA_CONSTEXPR_ASSERT(Monoid::laws::check(list(\n        int_<1>, short_<2>, long_<3>, ullong<4>, 5, 6ull\n    )));\n}\n", "meta": {"hexsha": "eaceed9631c727da5a58bbd0f42063702316036c", "size": 750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/integral/monoid.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "test/integral/monoid.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/integral/monoid.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0, "max_line_length": 78, "alphanum_fraction": 0.7, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5612892578224774}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <string>\n#include <map>\n#include <cmath>\n#include <cassert>\n#include <boost/function.hpp>\n#include <Eigen/Core>\n#include \"genfile/SingleSNPGenotypeProbabilities.hpp\"\n#include \"components/SNPSummaryComponent/GenotypeFrequencyTestCallComparer.hpp\"\n#include \"metro/likelihood/Multinomial.hpp\"\n#include \"metro/likelihood/ProductOfMultinomials.hpp\"\n#include \"metro/rBF.hpp\"\n\n#define GENOTYPE_FREQUENCY_TEST_CALL_COMPARER_DEBUG 0\n\nnamespace {\n\ttypedef Eigen::VectorXd Vector ;\n\ttypedef Eigen::MatrixXd Matrix ;\n\ttypedef metro::likelihood::Multinomial< double, Vector, Matrix > Multinomial ;\n\ttypedef metro::likelihood::ProductOfMultinomials< double, Vector, Matrix > ProductOfIndependentMultinomials ;\n}\n\nGenotypeFrequencyTestCallComparer::GenotypeFrequencyTestCallComparer():\n\tm_threshhold( 0.9 ),\n \tm_chi_squared( 2.0 )\n{}\n\nvoid GenotypeFrequencyTestCallComparer::compare(\n\tEigen::MatrixXd const& left,\n\tEigen::MatrixXd const& right,\n\tCallback callback\n) const {\n\t// Make table of counts\n\tassert( left.rows() == right.rows() ) ;\n\tassert( left.cols() == 3 ) ;\n\tassert( right.cols() == 3 ) ;\n\n\tstd::size_t const N = left.rows() ;\n\t\n\tMatrix table = Matrix::Zero( 2, 3 ) ;\n\n\tfor( std::size_t i = 0; i < N; ++i ) {\n\t\tfor( int g = 0; g < 3; ++g ) {\n\t\t\tif( left( i, g ) > m_threshhold ) {\n\t\t\t\t++table( 0, g ) ;\n\t\t\t\tbreak ;\n\t\t\t}\n\t\t}\n\n\t\tfor( int g = 0; g < 3; ++g ) {\n\t\t\tif( right( i, g ) > m_threshhold ) {\n\t\t\t\t++table( 1, g ) ;\n\t\t\t\tbreak ;\n\t\t\t}\n\t\t}\n\t}\n\n\tProductOfIndependentMultinomials alt_model( table ) ;\n\tMultinomial null_model( table.row(0) + table.row(1) ) ;\n\n\tnull_model.evaluate_at( null_model.get_MLE() ) ;\n\talt_model.evaluate_at( alt_model.get_MLE() ) ;\n\n\tdouble likelihood_ratio_statistic = 2.0 * ( alt_model.get_value_of_function() - null_model.get_value_of_function() ) ;\n\tdouble p_value = std::numeric_limits< double >::quiet_NaN() ;\n\tif( likelihood_ratio_statistic != likelihood_ratio_statistic || likelihood_ratio_statistic < 0.0 ) {\n\t\tlikelihood_ratio_statistic = std::numeric_limits< double >::quiet_NaN() ;\n\t}\n\telse {\n\t\tp_value = boost::math::cdf(\n\t\t\tboost::math::complement(\n\t\t\t\tm_chi_squared,\n\t\t\t\tlikelihood_ratio_statistic\n\t\t\t)\n\t\t) ;\n\t}\n\t\n#if GENOTYPE_FREQUENCY_TEST_CALL_COMPARER_DEBUG\n\tstd::cerr << \"Table is:\\n\" << table << \".\\n\" ;\n#endif\n\n\tcallback( \"likelihood_ratio_test_statistic\", likelihood_ratio_statistic ) ;\n\tcallback( \"pvalue\", p_value ) ;\n\tcallback( \"lambda=60/rBF\", metro::compute_rBF( table, 60 )) ;\n}\n", "meta": {"hexsha": "4d2e6b73cc01f03153666989668eeb872feac9a8", "size": 2654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/SNPSummaryComponent/src/GenotypeFrequencyTestCallComparer.cpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "components/SNPSummaryComponent/src/GenotypeFrequencyTestCallComparer.cpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "components/SNPSummaryComponent/src/GenotypeFrequencyTestCallComparer.cpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1648351648, "max_line_length": 119, "alphanum_fraction": 0.701582517, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461008, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5612892561156148}}
{"text": "#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n#include \"helpers.hpp\"\n#include <Eigen/Dense>\n#include <celerite2/celerite2.h>\n\nusing namespace celerite2::test;\nusing namespace celerite2::core;\n\nTEMPLATE_LIST_TEST_CASE(\"check the results of factor\", \"[factor]\", TestKernels) {\n  SETUP_TEST(50);\n\n  Vector d;\n  LowRank W;\n  Matrix K, S;\n  to_dense(x, c, a, U, V, K);\n\n  // Brute force the Cholesky factorization\n  Eigen::LDLT<Matrix> LDLT(K);\n  Eigen::MatrixXd matrixL = LDLT.matrixL();\n\n  SECTION(\"general\") {\n    // Do the Cholesky using celerite\n    int flag = factor(x, c, a, U, V, d, W, S);\n    REQUIRE(flag == 0);\n\n    // Reconstruct the L matrix\n    Matrix UWT;\n    to_dense(x, c, Eigen::VectorXd::Ones(N), U, W, UWT);\n    UWT.triangularView<Eigen::StrictlyUpper>().setConstant(0.0);\n\n    // Check that the lower triangle is correct\n    double resid = (matrixL - UWT).array().abs().maxCoeff();\n    REQUIRE(resid < 1e-12);\n\n    // Check that the diagonal is correct\n    double diag_resid = (LDLT.vectorD() - d).array().abs().maxCoeff();\n    REQUIRE(diag_resid < 1e-12);\n  }\n\n  SECTION(\"no grad\") {\n    // Do the Cholesky using celerite\n    int flag = factor(x, c, a, U, V, d, W);\n    REQUIRE(flag == 0);\n\n    // Reconstruct the L matrix\n    Matrix UWT;\n    to_dense(x, c, Eigen::VectorXd::Ones(N), U, W, UWT);\n    UWT.triangularView<Eigen::StrictlyUpper>().setConstant(0.0);\n\n    // Check that the lower triangle is correct\n    double resid = (matrixL - UWT).array().abs().maxCoeff();\n    REQUIRE(resid < 1e-12);\n\n    // Check that the diagonal is correct\n    double diag_resid = (LDLT.vectorD() - d).array().abs().maxCoeff();\n    REQUIRE(diag_resid < 1e-12);\n  }\n\n  SECTION(\"inplace\") {\n    // Do the Cholesky using celerite\n    int flag = factor(x, c, a, U, V, a, V, S);\n    REQUIRE(flag == 0);\n\n    // Reconstruct the L matrix\n    Matrix UWT;\n    to_dense(x, c, Eigen::VectorXd::Ones(N), U, V, UWT);\n    UWT.triangularView<Eigen::StrictlyUpper>().setConstant(0.0);\n\n    // Check that the lower triangle is correct\n    double resid = (matrixL - UWT).array().abs().maxCoeff();\n    REQUIRE(resid < 1e-12);\n\n    // Check that the diagonal is correct\n    double diag_resid = (LDLT.vectorD() - a).array().abs().maxCoeff();\n    REQUIRE(diag_resid < 1e-12);\n  }\n}\n", "meta": {"hexsha": "de2401c25aa0897a45977e1424de170ec627bbfd", "size": 2263, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/test/test_factor.cpp", "max_stars_repo_name": "jacksonloper/celerite2", "max_stars_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-10-10T02:43:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:59:21.000Z", "max_issues_repo_path": "c++/test/test_factor.cpp", "max_issues_repo_name": "jacksonloper/celerite2", "max_issues_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T18:50:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T10:33:04.000Z", "max_forks_repo_path": "c++/test/test_factor.cpp", "max_forks_repo_name": "jacksonloper/celerite2", "max_forks_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-11-09T18:12:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T20:20:59.000Z", "avg_line_length": 28.6455696203, "max_line_length": 81, "alphanum_fraction": 0.637207247, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.5612892408566954}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// accumulator::statistics::proportion_less_than.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_STATISTICS_DETAIL_ACCUMULATOR_STATISTICS_PROPORTION_LESS_THAN_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_ACCUMULATOR_STATISTICS_PROPORTION_LESS_THAN_HPP_ER_2009\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/apply.hpp>\n#include <boost/parameter/binding.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/parameters/accumulator.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n\n#include <boost/statistics/detail/accumulator/statistics/count_less_than.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace accumulator{\n\nnamespace impl\n{\n\n    template<typename T>\n    class proportion_less_than : public boost::accumulators::accumulator_base\n    {\n        typedef boost::accumulators::dont_care dont_care_;\n        typedef tag::count_less_than tag_m_;\n        typedef boost::accumulators::tag::count tag_n_;\n        typedef boost::accumulators::tag::accumulator tag_acc_;\n\n        public:\n    \n        typedef T result_type;\n\n        proportion_less_than(dont_care_){}\n        \n        void operator()(dont_care_)const{}\n\n        template<typename Args>\n        result_type result(const Args& args) const\n        {\n            typedef boost::parameter::binding<Args,tag_acc_> bind_;\n            typedef typename bind_::type cref_;\n            cref_ acc = args[boost::accumulators::accumulator];\n            T res =  boost::accumulators::extract_result<tag_m_>( acc );\n            res /= static_cast<T>(\n                boost::accumulators::extract_result<tag_n_>( acc )\n            );\n            return res;\n        }\n    };\n\n}//impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::proportion_less_than\nnamespace tag\n{\n    struct proportion_less_than\n      : boost::accumulators::depends_on<\n        boost::accumulators::tag::count,\n        tag::count_less_than\n    >\n    {\n      typedef statistics::detail::accumulator::\n      \timpl::proportion_less_than<boost::mpl::_1> impl;\n    };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::proportion_less_than\nnamespace extract\n{\n\n  \ttemplate<typename AccSet>\n  \ttypename boost::mpl::apply<\n    \tAccSet,\n        statistics::detail::accumulator::tag::proportion_less_than\n\t>::type::result_type\n  \tproportion_less_than(AccSet const& acc){\n    \ttypedef statistics::detail::accumulator\n        \t::tag::proportion_less_than the_tag;\n    \treturn boost::accumulators::extract_result<the_tag>(acc);\n  \t}\n\n}\n\nusing extract::proportion_less_than;\n\n}// accumulator\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "6548f2f766b978c07a87b6657d299a68e4d76415", "size": 3415, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "detail/accumulator/boost/statistics/detail/accumulator/statistics/proportion_less_than.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "detail/accumulator/boost/statistics/detail/accumulator/statistics/proportion_less_than.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "detail/accumulator/boost/statistics/detail/accumulator/statistics/proportion_less_than.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1553398058, "max_line_length": 87, "alphanum_fraction": 0.6149341142, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5612047052135896}}
{"text": "/*\n* compile with flags:   g++ test.cc tree_classifier.cc   -std=c++14 -larmadillo -I ../../include/\n* author: Yuzhen Liu\n* Date: 2019.5.8 17:35\n*/\n\n#include <iostream>\n#include <armadillo>\n#include <cmath>\n#include <trees/treenode.h>\n#include <trees/tree_classifier.h>\n#include <trees/random_forest.h>\n#include <trees/cart.h>\n#include <trees/gradient_boosting_dt.h>\n#include <stdlib.h>\n#include <datasets/datasets.h>\n\nusing namespace std;\nusing namespace arma;\n\npair<umat, uvec> generate_data() {\n    int n_sample = 100;\n    int n_feature = 4;\n    umat x(n_feature, n_sample);    \n    uvec y(n_sample);\n\n    // generate n samples iteratively\n    srand((unsigned)time(NULL));\n    for(int i =0; i < n_sample; i++) {\n        x(0, i) = rand() % 10;\n        x(1, i) = rand() % 10 + 100;\n        x(2, i) = rand() % 10;\n        x(3, i) = rand() % 10;\n\n        if (x(0, i) <= 5 && x(1, i) > 105 && x(2, i) > 5 )  y(i) = 0;\n        else if (x(0, i) > 5 && x(1, i) == 106 && x(2, i) <= 5 && x(3, i) > 5)  y(i) = 1;\n        else if (x(0, i) <= 5 && x(1, i) <= 105 && x(2, i) < 5)  y(i) = 2;\n        else y(i) = 3;\n    }\n    return make_pair(x, y);\n}\n\n\nint main() {\n    // pair<umat, uvec> p = generate_data();\n    // umat x = p.first;\n    // uvec y = p.second;\n    // x.print();\n    // y.print();    \n\n    /*******************************\n    * Tree classifier testing\n    *******************************/\n    // Tree_Classifier tree_classifier = Tree_Classifier(20/*max_depth=10, max_entropy=1.0*/);\n    // tree_classifier.train(x, y);\n    // uvec res = tree_classifier.predict(x);\n    // cout << \"=======================================\\n\";\n    // res.print();\n    // cout << \"=======================================\\n\";\n    // uvec dis = res - y;\n    // int count = 0;\n    // for (int i =0; i < dis.n_elem; i++) {\n    //     count += dis(i) == 0 ? 1 : 0;\n    // }\n    // cout << (float)count / dis.n_elem <<endl;\n\n\n\n\n    /******************************\n     * random forest tesitng\n    *******************************/\n    // Random_Forest rf(50, 3, 0.7, 1);\n    // rf.train(x, y);\n    // uvec res = rf.predict(x);\n\n    // cout << \"=======================================\\n\";\n    // res.print();\n    // cout << \"=======================================\\n\";\n\n    // uvec dis = res - y;\n    // int count = 0;\n    // for (int i =0; i < dis.n_elem; i++) {\n    //     count += dis(i) == 0 ? 1 : 0;\n    // }\n    // cout << (float)count / dis.n_elem <<endl;\n\n\n\n    /*******************************\n    * cart regression testing\n    *******************************/    \n    // Datasets dataset = Datasets(\"boston\");\n    // mat x = dataset.x;\n    // vec y = dataset.y;\n    // Cart_Regression cart(100);\n    // cart.train(x, y);\n    // vec res = cart.predict(x);\n    // join_rows(res, y).print();\n    // vec dis = res - y;\n    // // dis.print();\n    // cout << \"The standard deviation is: \" << stddev(dis) << endl;\n\n\n\n    /*******************************\n    * GBDT testing\n    *******************************/    \n    Datasets dataset = Datasets(\"boston\");\n    mat x = dataset.x;\n    vec y = dataset.y;\n    Gradient_Boosting_DT gbdt(6, 0.8, 80);\n    gbdt.train(x, y);\n    vec res = gbdt.predict(x);\n    join_rows(res, y).print();\n    vec dis = res - y;\n    // dis.print();\n    cout << \"The standard deviation is: \" << stddev(dis) << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "f657f612d659147407841aac45d6df53e84e74e4", "size": 3340, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/trees_test.cc", "max_stars_repo_name": "codestorm04/Machine_Learning_CPP", "max_stars_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-06-05T09:31:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T13:37:44.000Z", "max_issues_repo_path": "examples/trees_test.cc", "max_issues_repo_name": "codestorm04/Machine_Learning_CPP", "max_issues_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/trees_test.cc", "max_forks_repo_name": "codestorm04/Machine_Learning_CPP", "max_forks_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-11-15T04:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T15:59:30.000Z", "avg_line_length": 27.1544715447, "max_line_length": 97, "alphanum_fraction": 0.447005988, "num_tokens": 1005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5612047045747622}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2010 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if !defined(RELATIVE_RATE_DISTRIBUTION_HPP)\n#define RELATIVE_RATE_DISTRIBUTION_HPP\n\n#if defined(_MSC_VER)\n#\tpragma warning(disable: 4267)\t// warning about loss of data when converting size_t to int\n#endif\n\n#include <cmath>\n#include \"ncl/nxsdefs.h\"\n\n#include <boost/shared_ptr.hpp>\n#include <boost/format.hpp>\n\n#include \"subset_proportions.hpp\"\n#include \"dirichlet_distribution.hpp\"\n\nnamespace phycas\n{\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tThis is the distribution of a relative rates vector X = (x1, x2, ..., xn) when the vector Y = (p1 x1, p2 x2, ..., pn xn) ~ Dirichlet(c1, c2, ..., cn). It is\n|\tuseful as a prior for relative rates of subsets in a partition model, where the coefficients p1, p2, ..., pn are the relative sizes of the subsets.\n*/\nclass RelativeRateDistribution : public DirichletDistribution\n\t{\n\tpublic:\n\t\t\t\t\t\t\t\t\t\t\tRelativeRateDistribution();\n\t\t\t\t\t\t\t\t\t\t\tRelativeRateDistribution(const std::vector<double> & params, const double_vect_t & coeffs);\n                        \t\t\t\t\tRelativeRateDistribution(const RelativeRateDistribution & other);\n\t\tvirtual\t\t\t\t\t\t\t\t~RelativeRateDistribution() {}\n\n        RelativeRateDistribution * \t\t\tcloneAndSetLot(Lot * other) const;\n        RelativeRateDistribution * \t\t\tClone() const;\n\n\t\tvirtual std::string \t\t\t\t\t\tGetDistributionName() const;\n\t\tvirtual std::string \t\t\t\t\t\tGetDistributionDescription() const;\n\t\tstd::string                                 GetDescriptionForPython() const;\n\t\tvirtual std::vector<double>\t\t\t\t\tGetMean() const;\n\t\tvirtual std::vector<double> \t\t\t\tGetVar() const;\n\t\tvirtual std::vector<double> \t\t\t\tGetStdDev() const;\n\t\tvirtual std::vector<double>\t\t\t\t\tSample() const;\n\t\tvirtual double\t\t\t\t\t\t\t\tApproxCDF(const std::vector<double> &x, unsigned nsamples = 10000) const;\n\t\tvirtual double\t\t\t\t\t\t\t\tGetLnPDF(const std::vector<double> &x) const;\n\t\tvirtual double\t\t\t\t\t\t\t\tGetRelativeLnPDF(const std::vector<double> &x) const;\n\t\tvirtual void \t\t\t\t\t\t\t\tSetMeanAndVariance(const std::vector<double> &m, const std::vector<double> &v);\n\t\t// virtual void \t\t\t\t\t\t\t\tSetCoefficients(const std::vector<double> & coeff);\n\t\tvirtual unsigned\t\t\t\t\t\t\tGetNParams() const;\n#\t\tif defined(PYTHON_ONLY)\n\t\t//void\t\t\t\t\t\t\t\tAltSetMeanAndVariance(std::vector<double> m, std::vector<double> v);\n\t\tdouble_vect_t\t\t\t\t\t\tGetVarCovarMatrix();\n#\t\tendif\n\n        void                                setSubsetProportions(SubsetProportionsShPtr subset_proportions);\n\n    private:\n\n\t\tunsigned\t\t\t\t\t\t\tdim;                    /**< The dimension, which equals the number of parameters (used to initialze the coefficients) */\n        SubsetProportionsShPtr              _subset_proportions;    /**< The coefficients used to weight the relative rates */\n\t\tdouble\t\t\t\t\t\t\t\tsum_params;             /**< The sum of the dirichlet parameters stored in the data member `dirParams', which is provided by the base class */\n\t};\n\ntypedef boost::shared_ptr<RelativeRateDistribution> RelativeRateDistributionShPtr;\n\n} // namespace phycas\n\n#endif\n", "meta": {"hexsha": "f00c68d4f0392d15abca33bc704e545654eac4ee", "size": 4517, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/relative_rate_distribution.hpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/relative_rate_distribution.hpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/relative_rate_distribution.hpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 52.523255814, "max_line_length": 164, "alphanum_fraction": 0.5831303963, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650248, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5612046969306477}}
{"text": "#include <boost/program_options.hpp>\n#include <iostream>\n#include <random>\n\nnamespace po = boost::program_options;\n\nusing Options = std::tuple<int, double, double, size_t>;\n\nOptions get_options(int argc, char* argv[]);\n\nint main(int argc, char* argv[]) {\n    int n;\n    double a, b;\n    size_t seed;\n    std::tie(n, a, b, seed) = get_options(argc, argv);\n\n    std::mt19937 engine(seed);\n    std::uniform_real_distribution<double> distr(a, b);\n    for (int i = 0; i < n; ++i)\n        std::cout << distr(engine) << std::endl;\n\n    return 0;\n}\n\nOptions get_options(int argc, char* argv[]) {\n    const int default_n {1};\n    const double default_a {0.0};\n    const double default_b {1.0};\n    int n;\n    double a, b;\n    size_t seed;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (\"help\", \"produce help message\")\n        (\"n\", po::value<int>(&n)->default_value(default_n),\n         \"number of random values to generate\")\n        (\"a\", po::value<double>(&a)->default_value(default_a),\n         \"minimum value\")\n        (\"b\", po::value<double>(&b)->default_value(default_b),\n         \"maximum value\")\n        (\"seed\", po::value<size_t>(&seed), \"seed to use\")\n    ;\n    po::positional_options_description pos_desc;\n    pos_desc.add(\"n\", -1);\n\n    po::variables_map vm;        \n    po::store(po::command_line_parser(argc, argv)\n                  .options(desc).positional(pos_desc).run(), vm);\n    po::notify(vm);    \n\n    if (vm.count(\"help\")) {\n        std::cout << desc << std::endl;\n        std::exit(0);\n    }\n\n    if (!vm.count(\"seed\")) {\n        std::random_device device;\n        seed = device();\n    }\n    return std::make_tuple(n, a, b, seed);\n}\n", "meta": {"hexsha": "8bd450d56dce5c6af02e1514a5451930345c1b70", "size": 1686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Boost/ProgramOptions/random_default.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/Boost/ProgramOptions/random_default.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/Boost/ProgramOptions/random_default.cpp", "max_forks_repo_name": "gjbex/Scientific-C-", "max_forks_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 27.1935483871, "max_line_length": 65, "alphanum_fraction": 0.5860023725, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7879312031126511, "lm_q1q2_score": 0.5611899618229448}}
{"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": "// tests\n\n//local headers\n#include \"exception_assert.h\"\n#include \"math.h\"\n#include \"test.h\"\n\n//third party headers\n#include <boost/math/special_functions/binomial.hpp>\n#include \"boost/multiprecision/cpp_int.hpp\"\n\n//standard headers\n#include <cstdint>\n#include <iostream>\n#include <vector>\n\n\nTEST(test_get_mid)\n{\n    std::cout << \"Testing get_mid<T>()\\n\";\n\n    EXCEPTION_ASSERT_MSG(get_mid<int>(-1,-1) == -1, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_mid<int>(-1,0) == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_mid<int>(0,-1) == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_mid<int>(1,0) == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_mid<int>(0,1) == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_mid<int>(1,1) == 1, \"test failed\");\n\n    EXCEPTION_ASSERT_MSG(get_mid<int>(-4,-2) == -3, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_mid<int>(4,2) == 3, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_mid<int>(5,2) == 3, \"test failed\");\n\n    EXCEPTION_ASSERT_MSG(get_mid<double>(5.0,2.0) < 3.51, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_mid<double>(5.0,2.0) > 3.49, \"test failed\");\n\n    // overflow test\n    EXCEPTION_ASSERT_MSG(get_mid<std::uint32_t>(\n        std::numeric_limits<std::uint32_t>::max(),\n        std::numeric_limits<std::uint32_t>::max() - 2) ==\n        std::numeric_limits<std::uint32_t>::max() - 1,\n        \"test failed\");\n} TEST_END()\n\nTEST(test_sqrt_integral)\n{\n    std::cout << \"Testing sqrt_integral<T>()\\n\";\n\n    EXCEPTION_ASSERT_MSG(sqrt_integral<int>(-1) == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(sqrt_integral<int>(0) == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(sqrt_integral<int>(1) == 1, \"test failed\");\n    EXCEPTION_ASSERT_MSG(sqrt_integral<int>(2) == 1, \"test failed\");\n    EXCEPTION_ASSERT_MSG(sqrt_integral<int>(3) == 1, \"test failed\");\n    EXCEPTION_ASSERT_MSG(sqrt_integral<int>(4) == 2, \"test failed\");\n    EXCEPTION_ASSERT_MSG(sqrt_integral<int>(5) == 2, \"test failed\");\n    EXCEPTION_ASSERT_MSG(sqrt_integral<int>(6) == 2, \"test failed\");\n    EXCEPTION_ASSERT_MSG(sqrt_integral<int>(7) == 2, \"test failed\");\n    EXCEPTION_ASSERT_MSG(sqrt_integral<int>(8) == 2, \"test failed\");\n    EXCEPTION_ASSERT_MSG(sqrt_integral<int>(9) == 3, \"test failed\");\n\n    EXCEPTION_ASSERT_MSG(sqrt_integral<std::uint32_t>(10000) == 100, \"test failed\");\n    EXCEPTION_ASSERT_MSG(sqrt_integral<std::uint32_t>(123456789) == 11111, \"test failed\");\n\n    EXCEPTION_ASSERT_MSG(sqrt_integral<std::uint16_t>(65535) == 255, \"test failed\");\n    EXCEPTION_ASSERT_MSG(sqrt_integral<std::uint32_t>(4294967295ul) == 65535, \"test failed\");\n} TEST_END()\n\nTEST(test_get_primes_up_to)\n{\n    std::cout << \"Testing get_primes_up_to()\\n\";\n\n    std::vector<std::uint16_t> primes_to_300{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,\n        37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109,\n        113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,\n        199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293};\n\n    std::vector<std::uint16_t> primes_to_200_test{get_primes_up_to(200)};\n    std::vector<std::uint16_t> primes_to_300_test{get_primes_up_to(300)};\n    std::vector<std::uint16_t> primes_to_400_test{get_primes_up_to(400)};\n\n    EXCEPTION_ASSERT_MSG(primes_to_300 != primes_to_200_test, \"test failed\");\n    EXCEPTION_ASSERT_MSG(primes_to_300 == primes_to_300_test, \"test failed\");\n    EXCEPTION_ASSERT_MSG(primes_to_300 != primes_to_400_test, \"test failed\");\n\n    EXCEPTION_ASSERT_MSG(get_primes_up_to(0).size() == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_primes_up_to(1).size() == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_primes_up_to(2).size() == 1, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_primes_up_to(2)[0] == 2, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_primes_up_to(3).size() == 2, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_primes_up_to(3)[0] == 2, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_primes_up_to(3)[1] == 3, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_primes_up_to(4).size() == 2, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_primes_up_to(4)[0] == 2, \"test failed\");\n    EXCEPTION_ASSERT_MSG(get_primes_up_to(4)[1] == 3, \"test failed\");\n} TEST_END()\n\nTEST(test_prime_factors)\n{\n    std::cout << \"Testing prime_factors<T>()\\n\";\n\n    auto rebuild_num_f{\n            [](const std::vector<uint16_t> &primes) -> std::uint16_t\n            {\n                if (primes.size() == 0)\n                    return 0;\n\n                std::uint16_t result{1};\n\n                for (const auto prime : primes)\n                    result *= prime;\n\n                return result;\n            }\n        };\n\n    // factorization is complete (can reconstruct original number)\n    for (std::uint16_t i{0}; i < 200; ++i)\n        EXCEPTION_ASSERT_MSG(rebuild_num_f(prime_factors<std::uint16_t>(i)) == i, \"test failed\");\n\n    // prime factors are actually primes\n    std::vector<std::uint16_t> primes_to_150{get_primes_up_to(150)};\n    std::vector<std::uint16_t> prime_factors_300{prime_factors<std::uint16_t>(300)};\n\n    for (const auto factor : prime_factors_300)\n        EXCEPTION_ASSERT_MSG(std::find(primes_to_150.begin(), primes_to_150.end(), factor) != primes_to_150.end(), \"test failed\");\n} TEST_END()\n\nTEST(test_n_choose_k)\n{\n    std::cout << \"Testing n_choose_k<T>()\\n\";\n\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(-1,-1, true) == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(-1,0, true) == 0, \"test failed\");\n\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(0,-1, true) == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(0,0, true) == 1, \"test failed\");\n\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(1,0, true) == 1, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(1,1, true) == 1, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(1,2, true) == 0, \"test failed\");\n\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(2,-1, true) == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(2,0, true) == 1, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(2,1, true) == 2, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(2,2, true) == 1, \"test failed\");\n\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(10,1, true) == 10, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(10,2, true) == 45, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(10,3, true) == 120, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(10,4, true) == 210, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(10,5, true) == 252, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(10,6, true) == 210, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(10,7, true) == 120, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(10,8, true) == 45, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(10,9, true) == 10, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<int>(10,10, true) == 1, \"test failed\");\n\n    // numerical limits\n    using boost::multiprecision::cpp_int;\n    cpp_int bigint_limit = (cpp_int{1} << 650) - 1;\n    std::size_t bigint_size = 650/8 + (650 % 8 ? 1 : 0);\n    cpp_int bigint;\n\n    // std::uint16_t\n    EXCEPTION_ASSERT_MSG(n_choose_k<std::uint16_t>(18,9, true) != 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<std::uint16_t>(19,9, true) == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(bin_coeff_get_max_k(sizeof(std::uint16_t)) == 9, \"test failed\");\n\n    // valid 'n' is below max size\n    bigint = n_choose_k_impl<cpp_int>(18, 9, bigint_limit, bigint_size, true);\n    EXCEPTION_ASSERT_MSG(bigint <= std::numeric_limits<std::uint16_t>::max(), \"test failed\");\n\n    // invalid 'n' is above max size\n    bigint = n_choose_k_impl<cpp_int>(19, 9, bigint_limit, bigint_size, true);\n    EXCEPTION_ASSERT_MSG(bigint > std::numeric_limits<std::uint16_t>::max(), \"test failed\");\n\n\n    // std::uint32_t\n    EXCEPTION_ASSERT_MSG(n_choose_k<std::uint32_t>(34,17, true) != 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<std::uint32_t>(35,17, true) == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(bin_coeff_get_max_k(sizeof(std::uint32_t)) == 17, \"test failed\");\n\n    // valid 'n' is below max size\n    bigint = n_choose_k_impl<cpp_int>(34, 17, bigint_limit, bigint_size, true);\n    EXCEPTION_ASSERT_MSG(bigint <= std::numeric_limits<std::uint32_t>::max(), \"test failed\");\n\n    // invalid 'n' is above max size\n    bigint = n_choose_k_impl<cpp_int>(35, 17, bigint_limit, bigint_size, true);\n    EXCEPTION_ASSERT_MSG(bigint > std::numeric_limits<std::uint32_t>::max(), \"test failed\");\n\n\n    // std::uint64_t\n    EXCEPTION_ASSERT_MSG(n_choose_k<std::uint64_t>(67,33, true) != 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k<std::uint64_t>(68,34, true) == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(bin_coeff_get_max_k(sizeof(std::uint64_t)) == 33, \"test failed\");\n\n    // valid 'n' is below max size\n    bigint = n_choose_k_impl<cpp_int>(67, 33, bigint_limit, bigint_size, true);\n    EXCEPTION_ASSERT_MSG(bigint <= std::numeric_limits<std::uint64_t>::max(), \"test failed\");\n\n    // invalid 'n' is above max size\n    bigint = n_choose_k_impl<cpp_int>(68, 34, bigint_limit, bigint_size, true);\n    EXCEPTION_ASSERT_MSG(bigint > std::numeric_limits<std::uint64_t>::max(), \"test failed\");\n\n\n    using boost::multiprecision::uint128_t;\n    using boost::multiprecision::uint256_t;\n    using boost::multiprecision::uint512_t;\n\n    // uint128_t\n    uint128_t a1 = n_choose_k_impl<uint128_t>(131, 65, std::numeric_limits<uint128_t>::max(), 128/8, true);\n    uint128_t a2 = n_choose_k_impl<uint128_t>(132, 66, std::numeric_limits<uint128_t>::max(), 128/8, true);\n    EXCEPTION_ASSERT_MSG(a1 != 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(a2 == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(bin_coeff_get_max_k(128/8) == 65, \"test failed\");\n\n    // valid 'n' is below max size\n    bigint = n_choose_k_impl<cpp_int>(131, 65, bigint_limit, bigint_size, true);\n    EXCEPTION_ASSERT_MSG(bigint <= std::numeric_limits<uint128_t>::max(), \"test failed\");\n\n    // invalid 'n' is above max size\n    bigint = n_choose_k_impl<cpp_int>(132, 66, bigint_limit, bigint_size, true);\n    EXCEPTION_ASSERT_MSG(bigint > std::numeric_limits<uint128_t>::max(), \"test failed\");\n\n\n    // uint256_t\n    uint256_t b1 = n_choose_k_impl<uint256_t>(260, 130, std::numeric_limits<uint256_t>::max(), 256/8, true);\n    uint256_t b2 = n_choose_k_impl<uint256_t>(261, 130, std::numeric_limits<uint256_t>::max(), 256/8, true);\n    EXCEPTION_ASSERT_MSG(b1 != 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(b2 == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(bin_coeff_get_max_k(256/8) == 130, \"test failed\");\n\n    // valid 'n' is below max size\n    bigint = n_choose_k_impl<cpp_int>(260, 130, bigint_limit, bigint_size, true);\n    EXCEPTION_ASSERT_MSG(bigint <= std::numeric_limits<uint256_t>::max(), \"test failed\");\n\n    // invalid 'n' is above max size\n    bigint = n_choose_k_impl<cpp_int>(261, 130, bigint_limit, bigint_size, true);\n    EXCEPTION_ASSERT_MSG(bigint > std::numeric_limits<uint256_t>::max(), \"test failed\");\n\n\n    // uint512_t\n    uint512_t c1 = n_choose_k_impl<uint512_t>(516, 258, std::numeric_limits<uint512_t>::max(), 512/8, true);\n    uint512_t c2 = n_choose_k_impl<uint512_t>(517, 258, std::numeric_limits<uint512_t>::max(), 512/8, true);\n    EXCEPTION_ASSERT_MSG(c1 != 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(c2 == 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(bin_coeff_get_max_k(512/8) == 258, \"test failed\");\n\n    // valid 'n' is below max size\n    bigint = n_choose_k_impl<cpp_int>(516, 258, bigint_limit, bigint_size, true);\n    EXCEPTION_ASSERT_MSG(bigint <= std::numeric_limits<uint512_t>::max(), \"test failed\");\n\n    // invalid 'n' is above max size\n    bigint = n_choose_k_impl<cpp_int>(517, 258, bigint_limit, bigint_size, true);\n    EXCEPTION_ASSERT_MSG(bigint > std::numeric_limits<uint512_t>::max(), \"test failed\");\n\n\n    // cpp_int with 600 bits\n    // test that bin_coeff_get_max_k() returns a value k such that k + 1 will fail\n    cpp_int limit600 = (cpp_int{1} << 600) - 1;\n    std::size_t max_expected_k = bin_coeff_get_max_k(600/8 + (600 % 8 ? 1 : 0));\n    cpp_int r = n_choose_k_impl<cpp_int>((max_expected_k + 1)*2, (max_expected_k + 1), limit600, 600/8 + (600 % 8 ? 1 : 0), true);\n    EXCEPTION_ASSERT_MSG(r == 0, \"test failed\");\n\n\n    // maximum input value exceeded\n    using boost::multiprecision::cpp_int;\n    cpp_int limit = (cpp_int{1} << std::size_t{80000}) - 1;\n    cpp_int x = n_choose_k_impl<cpp_int>(cpp_int{200000}, cpp_int{100000}, limit, std::size_t{10000}, true);\n    EXCEPTION_ASSERT_MSG(x == 0, \"test failed\");\n} TEST_END()\n\nTEST(test_n_choose_k_bwrap)\n{\n    std::cout << \"Testing n_choose_k_bwrap()\\n\";\n\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(0,0) == 1, \"test failed\");\n\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(1,0) == 1, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(1,1) == 1, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(1,2) == 0, \"test failed\");\n\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(2,0) == 1, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(2,1) == 2, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(2,2) == 1, \"test failed\");\n\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(10,1) == 10, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(10,2) == 45, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(10,3) == 120, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(10,4) == 210, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(10,5) == 252, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(10,6) == 210, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(10,7) == 120, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(10,8) == 45, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(10,9) == 10, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(10,10) == 1, \"test failed\");\n\n    // numerical limits\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(33,16) != 0, \"test failed\");\n    EXCEPTION_ASSERT_MSG(n_choose_k_bwrap(34,16) == 0, \"test failed\");\n\n    double fp_result_good = boost::math::binomial_coefficient<double>(33, 16);\n    double fp_result_overflow = boost::math::binomial_coefficient<double>(34, 16);\n\n    EXCEPTION_ASSERT_MSG(fp_result_good <= std::numeric_limits<std::int32_t>::max(), \"test failed\");\n    EXCEPTION_ASSERT_MSG(fp_result_overflow > std::numeric_limits<std::int32_t>::max(), \"test failed\");\n} TEST_END()\n\nvoid run_tests()\n{\n    test_get_mid();\n    test_sqrt_integral();\n    test_get_primes_up_to();\n    test_prime_factors();\n    test_n_choose_k();\n    test_n_choose_k_bwrap();\n}\n", "meta": {"hexsha": "356c24740df8161c8a411200a3ee142aabc0a4a0", "size": 14570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sources/test.cpp", "max_stars_repo_name": "UkoeHB/bin-coeff-integral", "max_stars_repo_head_hexsha": "603683f60e22ac8f796df0e549b9fb96fe6d5d0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sources/test.cpp", "max_issues_repo_name": "UkoeHB/bin-coeff-integral", "max_issues_repo_head_hexsha": "603683f60e22ac8f796df0e549b9fb96fe6d5d0c", "max_issues_repo_licenses": ["MIT"], "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/test.cpp", "max_forks_repo_name": "UkoeHB/bin-coeff-integral", "max_forks_repo_head_hexsha": "603683f60e22ac8f796df0e549b9fb96fe6d5d0c", "max_forks_repo_licenses": ["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.9621451104, "max_line_length": 130, "alphanum_fraction": 0.6827041867, "num_tokens": 4324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.5611899565027438}}
{"text": "#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"xtensor/xarray.hpp\"\n#include \"xtensor/xio.hpp\"\n#include \"xtensor/xview.hpp\"\n#include \"xtensor/xaxis_slice_iterator.hpp\"\n#include \"xtensor/xadapt.hpp\"\n\n#define H5_USE_XTENSOR\n#include <highfive/H5Easy.hpp>\n#include <highfive/H5Group.hpp>\n\n#include <algorithm>\n#include <map>\n\n\n// #include <bits/stdc++.h> \n// #include <boost/algorithm/string.hpp> \n\nusing namespace std;\nusing namespace xt;\n\nstruct Sum\n{\n   void operator()(const xarray<int>& a) { sum += xt::sum(a)(); }\n   int sum {0};\n};\n\ntemplate <typename T> \nvoid print_shape(xt::xarray<T>& a){\n    const auto& s = a.shape();\n    std::copy(s.cbegin(), s.cend(), std::ostream_iterator<double>(std::cout, \" \"));\n}\n\nint main(int argc, char** argv) {\n    xarray<int> a = {{{1, 2, 3, 4},\n                  {5, 6, 7, 8},\n                  {9, 10, 11, 12}},\n                 {{13, 14, 15, 16},\n                  {17, 18, 19, 20},\n                  {21, 22, 23, 24}}};\n\n    auto iter = axis_slice_begin(a, 0);\n    auto end = axis_slice_end(a, 0);\n\n    cout << \"print 1 \" << endl;\n    auto print = [](const xarray<int>& a) {cout << a;};\n    std::for_each(iter, end, print);\n    \n    // iter = axis_slice_begin(a, 0);\n    // Sum s1 = std::for_each(iter, end, Sum());\n    // cout << endl << \"Sum is \" << s1.sum << endl;\n\n    cout << \"print 2\" << endl;\n    const auto& s = a.shape();\n    std::copy(s.cbegin(), s.cend(), std::ostream_iterator<double>(std::cout, \" \"));\n\n    xarray<int> b = {{1, 2, 3, 4},\n                    {5, 6, 7, 8}};\n    cout << xt::col(b, 0) << endl;\n    xt::col(b, 0) = xt::xarray<int>({6, 7});\n    cout << xt::col(b, 0) << endl;\n\n    vector<int> tmp {12, 13};\n    vector<size_t> shape = {2};\n    xt::col(b, 0) = xt::adapt(tmp, shape);\n    cout << xt::col(b, 0) << endl;\n\n\tcout << \"begin experiment 3\" << endl;\n\tstd::vector<size_t> shape3d = {2, 4, 4};\n\txt::xarray<int> array3d(shape3d, 0);\n    // auto v2 = xt::view(array3d, xt::all() , xt::all(), 1);\n    // auto v2 = xt::view(array3d, 1, xt::all(), xt::range(1, 3));\n\n\t// auto v2 = xt::view(array3d, xt::all(), xt::all(), 1); // failed\n\tauto v2 = xt::view(array3d, 0, xt::all(), xt::all()); // OK\n    // auto v2 = xt::view(array3d, xt::all(), xt::all(), xt::range(0, 1)); // OK\n    // auto v2 = xt::view(array3d, xt::all(), xt::range(1, 3), xt::all()); // OK\n    // auto v2 = xt::view(array3d, 0, xt::all(), xt::range(1, 3));\n    cout << v2.dimension() << endl;\n\tv2(0, 0) = 1;\n\tv2 = 3;\n    cout << v2 << endl;\n\tstd::vector<size_t> shape2d = {4, 2};\n\txt::xarray<int> array2d(shape2d, 0);\n\tarray2d = v2;\n    cout << array2d << endl;\n\tcout << \"end experiment 3\" << endl;\n\n\n\n    xarray<double> a1 = {{0., 1., 2.}, {3., 4., 5.}};\n    double b1 = 1.2;\n    auto tr = view(a1, 0, all());\n    tr = b1;\n    a1(0, 0) = 12.0;\n    cout << tr << endl;\n\n\t// a map of xarray\n    using arr2d_t = xt::xarray<double>; \n    std::map<std::string, arr2d_t > data_map;\n    vector<string> field_keys = {\"Sumw2\", \"Sumw\"};\n    long unsigned int n_bins = 2;\n    long unsigned int n_variations = 3;\n    for(auto field_key: field_keys) {\n        data_map[field_key] = xt::xarray<double>::from_shape({n_bins, n_variations});\n    }\n\tcout << data_map[\"Sumw2\"] << endl;\n\tdata_map[\"Sumw2\"](0, 0) = 12.0;\n\tcout << data_map[\"Sumw2\"] << endl;\n\n\tcout << \"start 5 \" << endl;\n\tint icc = 12;\n\tcout << icc++ << endl;\n\tcout << icc << endl;\n\tcout << ++icc << endl;\n\tcout << icc << endl;\n\tcout << \"end 5 \" << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "958f59a1dbae17feb36ce17d6e9e0d8edc0add72", "size": 3472, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/test/test_xtensor.cxx", "max_stars_repo_name": "xju2/yodf5", "max_stars_repo_head_hexsha": "2a2b7fb66fdeb56eb6cf0a8ec016204ac2e6fbb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/test_xtensor.cxx", "max_issues_repo_name": "xju2/yodf5", "max_issues_repo_head_hexsha": "2a2b7fb66fdeb56eb6cf0a8ec016204ac2e6fbb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/test_xtensor.cxx", "max_forks_repo_name": "xju2/yodf5", "max_forks_repo_head_hexsha": "2a2b7fb66fdeb56eb6cf0a8ec016204ac2e6fbb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 85, "alphanum_fraction": 0.5406105991, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5611899565027438}}
{"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 John Maddock 2007.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include \"required_defines.hpp\"\n\n#include \"performance_measure.hpp\"\n\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/array.hpp>\n\n#define T double\n#include \"../test/ibeta_data.ipp\"\n#include \"../test/ibeta_int_data.ipp\"\n#include \"../test/ibeta_large_data.ipp\"\n#include \"../test/ibeta_small_data.ipp\"\n\ntemplate <std::size_t N>\ndouble ibeta_evaluate2(const boost::array<boost::array<T, 7>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::ibeta(data[i][0], data[i][1], data[i][2]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(ibeta_test, \"ibeta\")\n{\n   double result = ibeta_evaluate2(ibeta_data);\n   result += ibeta_evaluate2(ibeta_int_data);\n   result += ibeta_evaluate2(ibeta_large_data);\n   result += ibeta_evaluate2(ibeta_small_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(ibeta_data) \n      + sizeof(ibeta_int_data) \n      + sizeof(ibeta_large_data)\n      + sizeof(ibeta_small_data)) / sizeof(ibeta_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble ibeta_inv_evaluate2(const boost::array<boost::array<T, 7>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::ibeta_inv(data[i][0], data[i][1], data[i][5]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(ibeta_inv_test, \"ibeta_inv\")\n{\n   double result = ibeta_inv_evaluate2(ibeta_data);\n   result += ibeta_inv_evaluate2(ibeta_int_data);\n   result += ibeta_inv_evaluate2(ibeta_large_data);\n   result += ibeta_inv_evaluate2(ibeta_small_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(ibeta_data) \n      + sizeof(ibeta_int_data) \n      + sizeof(ibeta_large_data)\n      + sizeof(ibeta_small_data)) / sizeof(ibeta_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble ibeta_invab_evaluate2(const boost::array<boost::array<T, 7>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n   {\n      //std::cout << \"ibeta_inva(\" << data[i][1] << \",\" << data[i][2] << \",\" << data[i][5] << \");\" << std::endl;\n      result += boost::math::ibeta_inva(data[i][1], data[i][2], data[i][5]);\n      //std::cout << \"ibeta_invb(\" << data[i][0] << \",\" << data[i][2] << \",\" << data[i][5] << \");\" << std::endl;\n      result += boost::math::ibeta_invb(data[i][0], data[i][2], data[i][5]);\n      //std::cout << \"ibetac_inva(\" << data[i][1] << \",\" << data[i][2] << \",\" << data[i][6] << \");\" << std::endl;\n      result += boost::math::ibetac_inva(data[i][1], data[i][2], data[i][6]);\n      //std::cout << \"ibetac_invb(\" << data[i][0] << \",\" << data[i][2] << \",\" << data[i][6] << \");\" << std::endl;\n      result += boost::math::ibetac_invb(data[i][0], data[i][2], data[i][6]);\n   }\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(ibeta_test, \"ibeta_invab\")\n{\n   double result = ibeta_invab_evaluate2(ibeta_data);\n   result += ibeta_invab_evaluate2(ibeta_int_data);\n   result += ibeta_invab_evaluate2(ibeta_large_data);\n   result += ibeta_invab_evaluate2(ibeta_small_data);\n\n   consume_result(result);\n   set_call_count(\n      4 * (sizeof(ibeta_data) \n      + sizeof(ibeta_int_data) \n      + sizeof(ibeta_large_data)\n      + sizeof(ibeta_small_data)) / sizeof(ibeta_data[0]));\n}\n\n#ifdef TEST_CEPHES\n\nextern \"C\" {\n\ndouble incbet(double a, double b, double x);\ndouble incbi(double a, double b, double y);\n\n}\n\ntemplate <std::size_t N>\ndouble ibeta_evaluate_cephes(const boost::array<boost::array<T, 7>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += incbet(data[i][0], data[i][1], data[i][2]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(ibeta_test, \"ibeta-cephes\")\n{\n   double result = ibeta_evaluate_cephes(ibeta_data);\n   result += ibeta_evaluate_cephes(ibeta_int_data);\n   result += ibeta_evaluate_cephes(ibeta_large_data);\n   result += ibeta_evaluate_cephes(ibeta_small_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(ibeta_data) \n      + sizeof(ibeta_int_data) \n      + sizeof(ibeta_large_data)\n      + sizeof(ibeta_small_data)) / sizeof(ibeta_data[0]));\n}\n\ntemplate <std::size_t N>\ndouble ibeta_inv_evaluate_cephes(const boost::array<boost::array<T, 7>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += incbi(data[i][0], data[i][1], data[i][5]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(ibeta_inv_test, \"ibeta_inv-cephes\")\n{\n   double result = ibeta_inv_evaluate_cephes(ibeta_data);\n   result += ibeta_inv_evaluate_cephes(ibeta_int_data);\n   result += ibeta_inv_evaluate_cephes(ibeta_large_data);\n   result += ibeta_inv_evaluate_cephes(ibeta_small_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(ibeta_data) \n      + sizeof(ibeta_int_data) \n      + sizeof(ibeta_large_data)\n      + sizeof(ibeta_small_data)) / sizeof(ibeta_data[0]));\n}\n\n#endif\n\n#ifdef TEST_GSL\n//\n// This test segfaults inside GSL....\n//\n\n#include <gsl/gsl_sf.h>\n\ntemplate <std::size_t N>\ndouble ibeta_evaluate_gsl(const boost::array<boost::array<T, 7>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += gsl_sf_beta_inc(data[i][0], data[i][1], data[i][2]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(ibeta_test, \"ibeta-gsl\")\n{\n   double result = ibeta_evaluate_gsl(ibeta_data);\n   result += ibeta_evaluate_gsl(ibeta_int_data);\n   result += ibeta_evaluate_gsl(ibeta_large_data);\n   result += ibeta_evaluate_gsl(ibeta_small_data);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(ibeta_data) \n      + sizeof(ibeta_int_data) \n      + sizeof(ibeta_large_data)\n      + sizeof(ibeta_small_data)) / sizeof(ibeta_data[0]));\n}\n\n#endif\n\n", "meta": {"hexsha": "a9a33e1de4d25cbeb9e15b86ed1e785335e75d54", "size": 5789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/performance/test_ibeta.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T17:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-22T17:17:41.000Z", "max_issues_repo_path": "libs/math/performance/test_ibeta.cpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/performance/test_ibeta.cpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T05:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T05:20:43.000Z", "avg_line_length": 30.1510416667, "max_line_length": 113, "alphanum_fraction": 0.6655726378, "num_tokens": 1714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.6513548578981939, "lm_q1q2_score": 0.5611671026091094}}
{"text": "/**\n * This file contains headers of all the files (and other 3rd party libraries) for the zaamath library.\n */\n\n#ifndef PROMETHEUS_MATH_HPP\n#define PROMETHEUS_MATH_HPP\n\n#include <Eigen/Dense> // Matrix/linear algebra library\n#include \"highfive/H5Easy.hpp\" // HDF5 header-only library\n#include \"stats/stats.hpp\" // probability distributions library\n#include \"hypothesis_testing.hpp\" // implementation of various hypothesis tests for Eigen objects\n#include \"summary_statistics.hpp\" // implementation of several useful summary statistics functions for Eigen objects\n#include \"optimization.hpp\" // implementation of stochastic optimization algorithms for Eigen objects\n#include \"stopwatch.hpp\" // implementation of a stopwatch class for benchmarking and analysis purposes\n\n#endif //PROMETHEUS_MATH_HPP\n", "meta": {"hexsha": "0c71207f258f3b2bfc8c29c2b43b0902a4148d82", "size": 799, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tools/math/math.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/math.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/math.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.0, "max_line_length": 116, "alphanum_fraction": 0.8035043805, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.561167099177294}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::survival::model::models::meta_failure_distribution.hpp        //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_SURVIVAL_MODEL_MODELS_META_FAILURE_DISTRIBUTION_HPP_ER_2009\n#define BOOST_STATISTICS_SURVIVAL_MODEL_MODELS_META_FAILURE_DISTRIBUTION_HPP_ER_2009\n#include <cmath>\n#include <boost/statistics/model/wrap/aggregate/model_covariate_parameter.hpp>\n#include <boost/standard_distribution/distributions/exponential.hpp>\n#include <boost/statistics/survival/data/meta/failure_distribution.hpp>\n#include <boost/statistics/survival/model/models/exponential/model.hpp>\n\nnamespace boost{\nnamespace statistics{\n\nnamespace survival{\nnamespace data{\n    \n    template<typename T>\n    struct meta_failure_distribution< survival::model::exponential::model<T> >{\n        typedef survival::model::exponential::model<T> model_;\n        typedef math::exponential_distribution<T> type;\n        \n        template<typename X,typename P>\n        static type make(\n            boost::statistics::model::model_covariate_parameter_<model_,X,P> mcp\n        ){\n            T lambda = model_::log_rate(\n                mcp.covariate(),\n                mcp.parameter()\n            );\n            lambda = exp( lambda );\n            return type(\n                lambda\n            );\n        }        \n    };\n\n\n\n}// data\n}// survival\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "ddb6ebf1ff288bd2b1b32c2a611adce5d0eefb42", "size": 1814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "survival_model copy/boost/statistics/survival/model/models/exponential/meta_failure_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": "survival_model copy/boost/statistics/survival/model/models/exponential/meta_failure_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": "survival_model copy/boost/statistics/survival/model/models/exponential/meta_failure_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": 37.0204081633, "max_line_length": 84, "alphanum_fraction": 0.5810363837, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5611646605333971}}
{"text": "/*\n * This file is part of the ProVANT simulator project.\n * Licensed under the terms of the MIT open source license. More details at\n * https://github.com/Guiraffo/ProVANT-Simulator/blob/master/LICENSE.md\n */\n/**\n * @file integrator_tests.cpp\n * @brief This file contains the tests of the Integrator class.\n *\n * @author J\u00fanio Eduardo de Morais Aquino\n */\n\n#include \"provant_simulator_math_utils/integrator.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Eigen>\n\n#include <memory>\n\nclass IntegratorTest : public ::testing::Test\n{\nprotected:\n  void SetUp() override\n  {\n    defaultIntegrator.reset(new Integrator<double>(1.0));\n\n    lineIntegrator.reset(new Integrator<double>(1.0));\n    lineIntegrator->update(0.0);\n    lineIntegrator->update(1.0);\n    lineIntegrator->update(2.0);\n    lineIntegrator->update(3.0);\n    lineIntegrator->update(4.0);\n    lineIntegrator->update(5.0);\n\n    nonZeroInitialValueIntegrator.reset(new Integrator<double>(1.0, 10.0));\n\n    zero << 0,0,0,0;\n    vectorIntegrator.reset(new Integrator<Eigen::Vector4d>(1.0, zero, zero));\n  }\n\n  void TearDown() override\n  {\n    defaultIntegrator.release();\n    lineIntegrator.release();\n    nonZeroInitialValueIntegrator.release();\n    vectorIntegrator.release();\n  }\n\n  std::unique_ptr<Integrator<double>> defaultIntegrator;\n  std::unique_ptr<Integrator<double>> lineIntegrator;\n  std::unique_ptr<Integrator<double>> nonZeroInitialValueIntegrator;\n  std::unique_ptr<Integrator<Eigen::Vector4d>> vectorIntegrator;\n  Eigen::Vector4d zero;\n};\n\nTEST_F(IntegratorTest, InitializesStepTime)\n{\n  ASSERT_DOUBLE_EQ(1.0, defaultIntegrator->stepTime());\n  ASSERT_DOUBLE_EQ(1.0, vectorIntegrator->stepTime());\n}\n\nTEST_F(IntegratorTest, InitializesInitialValue)\n{\n  ASSERT_DOUBLE_EQ(0.0, defaultIntegrator->value());\n  ASSERT_DOUBLE_EQ(10.0, nonZeroInitialValueIntegrator->value());\n\n  ASSERT_TRUE(vectorIntegrator->value().isApprox(zero));\n}\n\nTEST_F(IntegratorTest, IsInitiallyZero)\n{\n  ASSERT_DOUBLE_EQ(0.0, defaultIntegrator->value());\n  ASSERT_DOUBLE_EQ(0.0, defaultIntegrator->previousValue());\n\n  Eigen::Vector4d zero;\n  zero << 0, 0, 0, 0;\n  ASSERT_TRUE(vectorIntegrator->value().isApprox(zero));\n}\n\nTEST_F(IntegratorTest, UpdatesInitialValue)\n{\n  defaultIntegrator->setInitialValue(10.0);\n  ASSERT_DOUBLE_EQ(10.0, defaultIntegrator->initialValue());\n}\n\nTEST_F(IntegratorTest, CanReset)\n{\n  lineIntegrator->reset();\n\n  ASSERT_DOUBLE_EQ(lineIntegrator->initialValue(), lineIntegrator->value());\n  ASSERT_DOUBLE_EQ(0.0, lineIntegrator->previousValue());\n\n  nonZeroInitialValueIntegrator->reset();\n  ASSERT_DOUBLE_EQ(10.0, nonZeroInitialValueIntegrator->value());\n  ASSERT_DOUBLE_EQ(0.0, nonZeroInitialValueIntegrator->previousValue());\n\n  Eigen::Vector4d sample;\n  sample << 1, 1, 1, 1;\n  vectorIntegrator->update(sample);\n  vectorIntegrator->reset();\n  ASSERT_TRUE(vectorIntegrator->value().isApprox(zero));\n}\n\nTEST_F(IntegratorTest, UpdatesPreviousValue)\n{\n  ASSERT_DOUBLE_EQ(0.0, defaultIntegrator->previousValue());\n\n  defaultIntegrator->update(1.0);\n  ASSERT_DOUBLE_EQ(1.0, defaultIntegrator->previousValue());\n  defaultIntegrator->update(2.0);\n  ASSERT_DOUBLE_EQ(2.0, defaultIntegrator->previousValue());\n  defaultIntegrator->update(3.0);\n  ASSERT_DOUBLE_EQ(3.0, defaultIntegrator->previousValue());\n  defaultIntegrator->update(4.0);\n  ASSERT_DOUBLE_EQ(4.0, defaultIntegrator->previousValue());\n  defaultIntegrator->update(5.0);\n  ASSERT_DOUBLE_EQ(5.0, defaultIntegrator->previousValue());\n}\n\nTEST_F(IntegratorTest, VectorUpdatesPreviousValue)\n{\n  Eigen::Vector4d sample;\n  sample << 1, 1, 1, 1;\n\n  vectorIntegrator->update(sample);\n  ASSERT_TRUE(vectorIntegrator->previousValue().isApprox(sample));\n}\n\nTEST_F(IntegratorTest, ReturnsIntegralValue)\n{\n  ASSERT_DOUBLE_EQ(0.5, defaultIntegrator->update(1.0));\n  ASSERT_DOUBLE_EQ(2.0, defaultIntegrator->update(2.0));\n  ASSERT_DOUBLE_EQ(4.5, defaultIntegrator->update(3.0));\n  ASSERT_DOUBLE_EQ(8.0, defaultIntegrator->update(4.0));\n  ASSERT_DOUBLE_EQ(12.5, defaultIntegrator->update(5.0));\n}\n\nTEST_F(IntegratorTest, VectorReturnsIntegralValue)\n{\n  Eigen::Vector4d sample, res;\n  sample << 1, 1, 1, 1;\n  res << 0.5, 0.5, 0.5, 0.5;\n\n  ASSERT_TRUE(vectorIntegrator->update(sample).isApprox(res));\n}\n\nTEST_F(IntegratorTest, UpdatesIntegralValue)\n{\n  ASSERT_DOUBLE_EQ(0.5, defaultIntegrator->update(1.0));\n  ASSERT_DOUBLE_EQ(0.5, defaultIntegrator->value());\n  ASSERT_DOUBLE_EQ(2.0, defaultIntegrator->update(2.0));\n  ASSERT_DOUBLE_EQ(2.0, defaultIntegrator->value());\n  ASSERT_DOUBLE_EQ(4.5, defaultIntegrator->update(3.0));\n  ASSERT_DOUBLE_EQ(4.5, defaultIntegrator->value());\n  ASSERT_DOUBLE_EQ(8.0, defaultIntegrator->update(4.0));\n  ASSERT_DOUBLE_EQ(8.0, defaultIntegrator->value());\n  ASSERT_DOUBLE_EQ(12.5, defaultIntegrator->update(5.0));\n  ASSERT_DOUBLE_EQ(12.5, defaultIntegrator->value());\n}\n\nTEST_F(IntegratorTest, VectorUpdatesIntegralValue)\n{\n  Eigen::Vector4d sample, res;\n  sample << 1, 1, 1, 1;\n  res << 0.5, 0.5, 0.5, 0.5;\n\n  vectorIntegrator->update(sample);\n  ASSERT_TRUE(vectorIntegrator->value().isApprox(res));\n}\n\nTEST_F(IntegratorTest, DecreasingLineIntegral)\n{\n  ASSERT_DOUBLE_EQ(0.0, defaultIntegrator->value());\n\n  ASSERT_DOUBLE_EQ(-0.5, defaultIntegrator->update(-1.0));\n  ASSERT_DOUBLE_EQ(-2.0, defaultIntegrator->update(-2.0));\n  ASSERT_DOUBLE_EQ(-4.5, defaultIntegrator->update(-3.0));\n  ASSERT_DOUBLE_EQ(-8.0, defaultIntegrator->update(-4.0));\n  ASSERT_DOUBLE_EQ(-12.5, defaultIntegrator->update(-5.0));\n}\n\nTEST_F(IntegratorTest, NonZeroStartValueIntegralTest)\n{\n  ASSERT_DOUBLE_EQ(10.0, nonZeroInitialValueIntegrator->value());\n\n  ASSERT_DOUBLE_EQ(9.5, nonZeroInitialValueIntegrator->update(-1.0));\n  ASSERT_DOUBLE_EQ(8, nonZeroInitialValueIntegrator->update(-2.0));\n  ASSERT_DOUBLE_EQ(5.5, nonZeroInitialValueIntegrator->update(-3.0));\n  ASSERT_DOUBLE_EQ(2.0, nonZeroInitialValueIntegrator->update(-4.0));\n  ASSERT_DOUBLE_EQ(-2.5, nonZeroInitialValueIntegrator->update(-5.0));\n}\n\nTEST_F(IntegratorTest, VariyingLineTest)\n{\n  ASSERT_DOUBLE_EQ(0.5, defaultIntegrator->update(1.0));\n  ASSERT_DOUBLE_EQ(2.0, defaultIntegrator->update(2.0));\n  ASSERT_DOUBLE_EQ(4.5, defaultIntegrator->update(3.0));\n  ASSERT_DOUBLE_EQ(8.0, defaultIntegrator->update(4.0));\n  ASSERT_DOUBLE_EQ(12.5, defaultIntegrator->update(5.0));\n  ASSERT_DOUBLE_EQ(17.0, defaultIntegrator->update(4.0));\n  ASSERT_DOUBLE_EQ(20.5, defaultIntegrator->update(3.0));\n  ASSERT_DOUBLE_EQ(23.0, defaultIntegrator->update(2.0));\n  ASSERT_DOUBLE_EQ(24.5, defaultIntegrator->update(1.0));\n  ASSERT_DOUBLE_EQ(25.0, defaultIntegrator->update(0.0));\n  ASSERT_DOUBLE_EQ(24.5, defaultIntegrator->update(-1.0));\n  ASSERT_DOUBLE_EQ(23.0, defaultIntegrator->update(-2.0));\n  ASSERT_DOUBLE_EQ(20.5, defaultIntegrator->update(-3.0));\n  ASSERT_DOUBLE_EQ(17.0, defaultIntegrator->update(-4.0));\n  ASSERT_DOUBLE_EQ(12.5, defaultIntegrator->update(-5.0));\n  ASSERT_DOUBLE_EQ(7.0, defaultIntegrator->update(-6.0));\n  ASSERT_DOUBLE_EQ(0.5, defaultIntegrator->update(-7.0));\n  ASSERT_DOUBLE_EQ(-7.0, defaultIntegrator->update(-8.0));\n}\n\nTEST_F(IntegratorTest, ConstantZeroTest)\n{\n  ASSERT_DOUBLE_EQ(0.0, defaultIntegrator->update(0.0));\n  ASSERT_DOUBLE_EQ(0.0, defaultIntegrator->update(0.0));\n  ASSERT_DOUBLE_EQ(0.0, defaultIntegrator->update(0.0));\n  ASSERT_DOUBLE_EQ(0.0, defaultIntegrator->update(0.0));\n  ASSERT_DOUBLE_EQ(0.0, defaultIntegrator->update(0.0));\n}\n\nTEST_F(IntegratorTest, VectorIntegral)\n{\n  Eigen::Vector4d sample, res;\n  sample << 1, 1, -1, -1;\n  res << 0.5, 0.5, -0.5, -0.5;\n\n  ASSERT_TRUE(vectorIntegrator->update(sample).isApprox(res));\n  \n  sample << 2.0, 2.0, -2.0, -2.0;\n  res << 2.0, 2.0, -2.0, -2.0;\n  ASSERT_TRUE(vectorIntegrator->update(sample).isApprox(res));\n\n  sample << 3.0, 3.0, -3.0, -3.0;\n  res << 4.5, 4.5, -4.5, -4.5;\n  ASSERT_TRUE(vectorIntegrator->update(sample).isApprox(res));\n    \n  sample << 4.0, 4.0, -4.0, -4.0;\n  res << 8.0, 8.0, -8.0, -8.0;\n  ASSERT_TRUE(vectorIntegrator->update(sample).isApprox(res));\n  \n  sample << 5.0, 5.0, -5.0, -5.0;\n  res << 12.5, 12.5, -12.5, -12.5;\n  ASSERT_TRUE(vectorIntegrator->update(sample).isApprox(res));\n}\n\nint main(int argc, char** argv)\n{\n  ::testing::InitGoogleTest(&argc, argv);\n  try\n  {\n    return RUN_ALL_TESTS();\n  }\n  catch (const std::exception& e)\n  {\n    std::cerr << \"Unhandled excpetion with message: \" << e.what() << std::endl;\n    return -1;\n  }\n}\n", "meta": {"hexsha": "0a26bcd6dd9eebaed1f344cd31d3cecc5f646281", "size": 8327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "provant_simulator_utils/provant_simulator_math_utils/tests/integrator_test.cpp", "max_stars_repo_name": "Guiraffo/ProVANT_Simulator", "max_stars_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "provant_simulator_utils/provant_simulator_math_utils/tests/integrator_test.cpp", "max_issues_repo_name": "Guiraffo/ProVANT_Simulator", "max_issues_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "provant_simulator_utils/provant_simulator_math_utils/tests/integrator_test.cpp", "max_forks_repo_name": "Guiraffo/ProVANT_Simulator", "max_forks_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6615969582, "max_line_length": 79, "alphanum_fraction": 0.7308754654, "num_tokens": 2560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.5611316444599468}}
{"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*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2014-2019 Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include <rokko/eigen3.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <gtest/gtest.h>\n\nTEST(matrix, major) {\n  int dim = 3;\n\n  // M = 1 2 3\n  //     4 5 6\n  //     7 8 9\n\n  Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> M0(dim,dim); // row major\n  M0 << 1,2,3,4,5,6,7,8,9;\n  std::cout << M0 << std::endl;\n  ASSERT_EQ(M0(0,0),1.0);\n  ASSERT_EQ(M0(0,1),2.0);\n  ASSERT_EQ(M0(1,0),4.0);\n  double* ptr0 = &M0(0,0);\n  ASSERT_EQ(*(ptr0 + 1), 2.0); // row major\n  ASSERT_EQ((M0.row(0))(1), 2.0);\n  ASSERT_EQ((M0.col(0))(1), 4.0);\n\n  Eigen::MatrixXd M1(dim,dim); // column major\n  M1 << 1,2,3,4,5,6,7,8,9;\n  std::cout << M1 << std::endl;\n  ASSERT_EQ(M1(0,0),1.0);\n  ASSERT_EQ(M1(0,1),2.0);\n  ASSERT_EQ(M1(1,0),4.0);\n  double* ptr1 = &M1(0,0);\n  ASSERT_EQ(*(ptr1 + 1), 4.0); // column major\n  ASSERT_EQ((M1.row(0))(1), 2.0);\n  ASSERT_EQ((M1.col(0))(1), 4.0);\n\n  boost::numeric::ublas::matrix<double> M2(dim,dim); // row major\n  for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) M2(i,j) = M0(i,j);\n  std::cout << M2 << std::endl;\n  ASSERT_EQ(M2(0,0),1.0);\n  ASSERT_EQ(M2(0,1),2.0);\n  ASSERT_EQ(M2(1,0),4.0);\n  double* ptr2 = &M2(0,0);\n  ASSERT_EQ(*(ptr2 + 1), 2.0); // row major\n\n  boost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> M3(dim,dim); // column major\n  for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) M3(i,j) = M0(i,j);\n  std::cout << M3 << std::endl;\n  ASSERT_EQ(M3(0,0),1.0);\n  ASSERT_EQ(M3(0,1),2.0);\n  ASSERT_EQ(M3(1,0),4.0);\n  double* ptr3 = &M3(0,0);\n  ASSERT_EQ(*(ptr3 + 1), 4.0); // column major\n\n  Eigen::MatrixXd M4(dim, dim); // column major\n  for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) M4(i,j) = M0(i,j);\n  std::cout << M4 << std::endl;\n  ASSERT_EQ(M4(0,0),1.0);\n  ASSERT_EQ(M4(0,1),2.0);\n  ASSERT_EQ(M4(1,0),4.0);\n  double* ptr4 = &M4(0,0);\n  ASSERT_EQ(*(ptr4 + 1), 4.0); // column major\n}\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "f9e18b70b99b24ed5c349d03c90921c796e0208f", "size": 2498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/generate_matrix/matrix_major.cpp", "max_stars_repo_name": "t-sakashita/rokko", "max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z", "max_issues_repo_path": "test/generate_matrix/matrix_major.cpp", "max_issues_repo_name": "t-sakashita/rokko", "max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 514.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z", "max_forks_repo_path": "test/generate_matrix/matrix_major.cpp", "max_forks_repo_name": "t-sakashita/rokko", "max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z", "avg_line_length": 31.6202531646, "max_line_length": 105, "alphanum_fraction": 0.5556445156, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5611059045315986}}
{"text": "//\n// Copyright (c) 2012 Juan Palacios juan.palacios.puyana@gmail.com\n// This file is part of minimathlibs.\n// Subject to the BSD 2-Clause License \n// - see < http://opensource.org/licenses/BSD-2-Clause>\n//\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE TestTranslation3D\n#include <boost/test/unit_test.hpp>\n#include <vector>\n#include <numeric>\n#include <functional>\n#include \"minimath/translation3d.hpp\"\n#include \"minimath/point3d.hpp\"\n\nnamespace\n{\nusing namespace minimath;\n}\n\nBOOST_AUTO_TEST_SUITE(TestTranslation3D)\n\nBOOST_AUTO_TEST_CASE(testInstantiation)\n{\n    translation3d<double> displ1, displ2;\n}\n\nBOOST_AUTO_TEST_CASE(testDefaultEquality)\n{\n    BOOST_CHECK(translation3d<double>() == translation3d<double>());\n}\n\nBOOST_AUTO_TEST_CASE(testCopyConstruction)\n{\n    translation3d<double> displ1;\n    translation3d<double> displ2(displ1);\n    BOOST_CHECK(displ1==displ2);\n}\n\nBOOST_AUTO_TEST_CASE(testAssignment)\n{\n    translation3d<double> displ1, displ2;\n    displ2 = displ1;\n    BOOST_CHECK(displ1==displ2);\n}\n\nBOOST_AUTO_TEST_CASE(testNullTranslation) \n{\n    pointxyzd p(11, 22, 33);\n    BOOST_CHECK(pointxyzd(11,22,33) == translation3d<double>()*p);\n}\n\nBOOST_AUTO_TEST_CASE(testTranslatePoint) \n{\n    for (int i = 0; i < 100; ++i)\n    {\n        pointxyzd p(11, 22, 33);\n        translation3d<double> t1(pointxyzd(i, i, i));\n        BOOST_CHECK(pointxyzd(11+i, 22+i, 33+i) == t1*p);\n        translation3d<double> t2(pointxyzd(-i, -i, -i));\n        BOOST_CHECK(pointxyzd(11-i, 22-i, 33-i) == t2*p);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(testCompoundTranslation)\n{\n    // make a vector of many translations\n    std::vector<translation3d<double> > v;\n    int sum = 0;\n    for (int i = 0; i<10; ++i)\n    {\n        sum += i;\n        v.push_back(translation3d<double>(pointxyzd(i,i,i)));\n    }\n    // multiply all the translations together\n    translation3d<double> t = std::accumulate(v.begin(), v.end(),\n                                              translation3d<double>(), \n                                              std::multiplies<translation3d<double> >());\n    BOOST_CHECK(pointxyzd(sum, sum, sum) == t*pointxyzd());\n}\n\nBOOST_AUTO_TEST_CASE(testInverse)\n{\n    translation3d<double> t0(pointxyzd(1., 2., 3.));\n    BOOST_CHECK(t0.inverse() == translation3d<double>(pointxyzd(-1., -2., -3.)));\n}\nBOOST_AUTO_TEST_CASE(testInvert)\n{\n    translation3d<double> t0(pointxyzd(1., 2., 3.));\n    t0.invert();\n    BOOST_CHECK(t0 == translation3d<double>(pointxyzd(-1., -2., -3.)));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7ca82ee6eb45e23176c701037a350220b4f1583b", "size": 2514, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestTranslation3D.cpp", "max_stars_repo_name": "XPsoud/minimathlibs", "max_stars_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-20T13:54:46.000Z", "max_issues_repo_path": "tests/TestTranslation3D.cpp", "max_issues_repo_name": "XPsoud/minimathlibs", "max_issues_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/TestTranslation3D.cpp", "max_forks_repo_name": "XPsoud/minimathlibs", "max_forks_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T15:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:04:57.000Z", "avg_line_length": 26.4631578947, "max_line_length": 89, "alphanum_fraction": 0.6638822593, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.5611058960413393}}
{"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<iostream>\n#define EIGEN_USE_MKL_ALL\n#include <Eigen/Eigenvalues> \n#include\"numerics.hpp\"\n#include\"reddm.hpp\"\n#include\"tpoperators.hpp\"\n#include \"files.hpp\"\n#include\"FTLanczos.hpp\"\nusing namespace Many_Body;\n    using Mat= Operators::Mat;\nint main(int argc, char *argv[])\n{\n    size_t M{};\n  size_t L{};\n  double t0{};\n  double omega{};\n  double gamma{};\n   bool PB{};\n    double mean= 0.5*omega*L*M;\n  double beta=22.;\n\n  try\n  {\n    options_description desc{\"Options\"};\n    desc.add_options()\n      (\"help,h\", \"Help screen\")\n      (\"L\", value(&L)->default_value(4), \"L\")\n      (\"M\", value(&M)->default_value(2), \"M\")\n      (\"t\", value(&t0)->default_value(1.), \"t0\")\n      (\"gam\", value(&gamma)->default_value(1.), \"gamma\")\n      (\"omg\", value(&omega)->default_value(1.), \"omega\");\n   (\"pb\", value(&PB)->default_value(true), \"PB\");\n\n\n    variables_map vm;\n    store(parse_command_line(argc, argv, desc), vm);\n    notify(vm);\n\n    if (vm.count(\"help\"))\n      {std::cout << desc << '\\n'; return 0;}\n    else{\n      if (vm.count(\"L\"))\n      {      std::cout << \"L: \" << vm[\"L\"].as<size_t>() << '\\n';\n\t\n      }\n     if (vm.count(\"M,m\"))\n      {\n\tstd::cout << \"M: \" << vm[\"M\"].as<size_t>() << '\\n';\n\t\n      }\n      if (vm.count(\"t\"))\n      {\n\tstd::cout << \"t0: \" << vm[\"t\"].as<double>() << '\\n';\t\n      }\n       if (vm.count(\"omg\"))\n      {\n\tstd::cout << \"omega: \" << vm[\"omg\"].as<double>() << '\\n';\n      }\n       if (vm.count(\"gam\"))\n      {\n\tstd::cout << \"gamma: \" << vm[\"gam\"].as<double>() << '\\n';\n      }\n                    if (vm.count(\"pb\"))\n      {\n\tstd::cout << \"PB: \" << vm[\"pb\"].as<bool>() << '\\n';\n      }\n    }\n  }\n  catch (const error &ex)\n  {\n    std::cerr << ex.what() << '\\n';\n    return 0;\n  }\n\n     \n\n  \n  double T=1./beta;\n   using HolsteinBasis= TensorProduct<ElectronBasis, PhononBasis>;\n        PhononBasis g2{ 2, 1};\n  ElectronBasis e( L, 1);\n\n  \n  PhononBasis ph(L, M);\n\n  HolsteinBasis TP(e, ph);\n\n\n        Mat E1=Operators::EKinOperatorL(TP, e, t0, PB);\n       Mat Ebdag=Operators::BosonCOperator(TP, ph, gamma, PB);\n       std::cout<< \"dim \"<< TP.dim<< std::endl;\n       Mat Eb=Operators::BosonDOperator(TP, ph, gamma, PB);\n       Mat Eph=Operators::NumberOperator(TP, ph, omega,  PB);\n      \n      //Mat E=Operators::NumberOperatore(TP, e, 1, PB);\n      //    std::cout<< HH << std::endl;\n      Eigen::VectorXd eigenVals(TP.dim);\n       \tMat H=E1+Eph +Ebdag + Eb;\n\tauto O=Operators::NumberOperator(TP, ph, omega,  PB);\n\tstd::vector<Mat> v{H, O};\n       //       auto HH=Eigen::MatrixXd(H);\n\n      auto ev=Eigen::VectorXd(H.rows());\n      //    diagMat(HH, ev);\n\n\n\tauto o=LTLM(H, v, T, 10);\n\n\n  \n\t           std::cout<< \"for beta/mean = \" << beta << std::endl;\n       for(auto& l: o)\n   \t{std::cout<< l <<std::endl; }\n  \n  return 0;\n}\n\n", "meta": {"hexsha": "a256354bbc44ab8c84df231a729e2fbc58a00744", "size": 2770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/holstLTLM.cpp", "max_stars_repo_name": "jansendavid/many-body-lib", "max_stars_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/holstLTLM.cpp", "max_issues_repo_name": "jansendavid/many-body-lib", "max_issues_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/holstLTLM.cpp", "max_forks_repo_name": "jansendavid/many-body-lib", "max_forks_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4745762712, "max_line_length": 66, "alphanum_fraction": 0.5180505415, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5610605563598613}}
{"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": "/**\n * @file odesolve.cc\n * @brief NPDE homework ODESolve code\n * @author ?, Philippe Peter\n * @date 18.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"odesolve.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n#include \"../../../lecturecodes/helperfiles/polyfit.h\"\n\nnamespace ODESolve {\n\n/* SAM_LISTING_BEGIN_2 */\ndouble TestCvpExtrapolatedEuler() {\n  double conv_rate;\n  double T = 1.0;\n  double y0 = 0.0;\n  auto f = [](double y) -> double { return 1.0 + y * y; };\n\n  // TODO : tabulate the values of the error corresponding to\n  // \\tilde{\\psi}, where \\psi is the explicit Euler method.\n  // return the empirical convergence rate using polyfit.\n  // Hint: first define a lambda for \\psi. Then use psitilde to obtain a\n  // suitable input for odeintequi.\n\n  // ===================\n  // Your code goes here\n  // ===================\n  return conv_rate;\n}\n\n/* SAM_LISTING_BEGIN_4 */\nstd::pair<std::vector<double>, std::vector<double>> SolveTangentIVP() {\n  auto f = [](double y) -> double { return 1.0 + y * y; };\n  double y0 = 0.0;\n\n  // TODO: run the adaptive integration algorithm\n  // ===================\n  // Your code goes here\n  // ===================\n  // dummy vectors (if size 0, the plotting script crashes)\n  std::vector<double> t(10, 0.0);\n  std::vector<double> Y(10, 1.0);\n  return {t, Y};\n}\n/* SAM_LISTING_END_4 */\n\n}  // namespace ODESolve\n", "meta": {"hexsha": "41635fd6902c1a0caff4b303ffbd9d9f0ea750bd", "size": 1400, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ODESolve/templates/odesolve.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/ODESolve/templates/odesolve.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/ODESolve/templates/odesolve.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 25.0, "max_line_length": 72, "alphanum_fraction": 0.6207142857, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5610286799519744}}
{"text": "#ifndef POINT_TYPE_HPP_\n#define POINT_TYPE_HPP_\n\n#include <Eigen/Dense>\n#include <iostream>\n\n#define POINT3D                                                  \\\n  union EIGEN_ALIGN16 {                                          \\\n    float data[3];                                               \\\n    struct {                                                     \\\n      float x;                                                   \\\n      float y;                                                   \\\n      float z;                                                   \\\n    };                                                           \\\n  };                                                             \\\n  inline Eigen::Map<Eigen::Vector3f> point() {                   \\\n    return (Eigen::Vector3f::Map(data));                         \\\n  }                                                              \\\n  inline const Eigen::Map<const Eigen::Vector3f> point() const { \\\n    return (Eigen::Vector3f::Map(data));                         \\\n  }\n\nnamespace point_type {\n//\u4e09\u7ef4\u70b9\nstruct EIGEN_ALIGN16 Point3f {\n  POINT3D;  //\u70b9\u5750\u6807\n\n  Point3f() = default;\n  explicit Point3f(const float x_, const float y_, const float z_)\n      : x(x_), y(y_), z(z_) {}\n  explicit Point3f(const Eigen::Vector3f& point) { this->point() = point; }\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\ninline std::ostream& operator<<(std::ostream& os, const Point3f& p) {\n  os << \"(\" << p.x << \", \" << p.y << \", \" << p.z << \")\";\n  return os;\n}\n}  // namespace point_type\n\n#endif", "meta": {"hexsha": "e04802f8899986c5ca833b142438d2e1fbf176bb", "size": 1527, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Surface/Surface/point_type.hpp", "max_stars_repo_name": "trainsn/ParticleVis", "max_stars_repo_head_hexsha": "5da10d594f6c306c93ae044d5d1ff2dd5f9ff607", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-24T10:32:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T10:32:46.000Z", "max_issues_repo_path": "Surface/Surface/point_type.hpp", "max_issues_repo_name": "trainsn/ParticleVis", "max_issues_repo_head_hexsha": "5da10d594f6c306c93ae044d5d1ff2dd5f9ff607", "max_issues_repo_licenses": ["MIT"], "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/Surface/point_type.hpp", "max_forks_repo_name": "trainsn/ParticleVis", "max_forks_repo_head_hexsha": "5da10d594f6c306c93ae044d5d1ff2dd5f9ff607", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T10:32:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T10:32:47.000Z", "avg_line_length": 36.3571428571, "max_line_length": 75, "alphanum_fraction": 0.3759004584, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5610286674621328}}
{"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@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/ext/std/integral_constant.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/range.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/type.hpp>\n\n#include <sstream>\n#include <string>\n#include <type_traits>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [foldl]\nauto to_string = [](auto x) {\n    return static_cast<std::ostringstream const&>(std::ostringstream{} << x).str();\n};\n\nauto show = [=](auto x, auto y) {\n    return \"(\" + to_string(x) + \" + \" + to_string(y) + \")\";\n};\n\nBOOST_HANA_RUNTIME_CHECK(\n    foldl(make<Tuple>(2, \"3\", '4'), \"1\", show) == \"(((1 + 2) + 3) + 4)\"\n);\n//! [foldl]\n\n}{\n\n//! [foldl1]\nauto to_string = [](auto x) {\n    return static_cast<std::ostringstream const&>(std::ostringstream{} << x).str();\n};\n\nauto show = [=](auto x, auto y) {\n    return \"(\" + to_string(x) + \" + \" + to_string(y) + \")\";\n};\n\nBOOST_HANA_RUNTIME_CHECK(\n    foldl1(make<Tuple>(1, \"2\", '3'), show) == \"((1 + 2) + 3)\"\n);\n//! [foldl1]\n\n}{\n\n//! [foldr]\nauto to_string = [](auto x) {\n    return static_cast<std::ostringstream const&>(std::ostringstream{} << x).str();\n};\n\nauto show = [=](auto x, auto y) {\n    return \"(\" + to_string(x) + \" + \" + to_string(y) + \")\";\n};\n\nBOOST_HANA_RUNTIME_CHECK(\n    foldr(make<Tuple>(1, \"2\", '3'), \"4\", show) == \"(1 + (2 + (3 + 4)))\"\n);\n//! [foldr]\n\n}{\n\n//! [foldrM]\nBOOST_HANA_CONSTEXPR_LAMBDA auto safediv = [](auto x, auto y) {\n    return eval_if(y == int_<0>,\n        always(nothing),\n        [=](auto _) { return just(_(x) / y); }\n    );\n};\n\nBOOST_HANA_CONSTANT_CHECK(\n    foldrM<Maybe>(tuple_c<int, 1000, 8, 4>, int_<2>, safediv)\n        ==\n    just(int_<1000> / (int_<8> / (int_<4> / int_<2>)))\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    foldrM<Maybe>(tuple_c<int, 1000, 8, 4>, int_<0>, safediv)\n        ==\n    nothing\n);\n//! [foldrM]\n\n}{\n\n//! [foldr1]\nauto to_string = [](auto x) {\n    return static_cast<std::ostringstream const&>(std::ostringstream{} << x).str();\n};\n\nauto show = [=](auto x, auto y) {\n    return \"(\" + to_string(x) + \" + \" + to_string(y) + \")\";\n};\n\nBOOST_HANA_RUNTIME_CHECK(\n    foldr1(make<Tuple>(1, \"2\", '3'), show) == \"(1 + (2 + 3))\"\n);\n//! [foldr1]\n\n}{\n\n//! [for_each]\nstd::stringstream ss;\nfor_each(make<Tuple>(0, '1', \"234\", 5.5), [&](auto x) {\n    ss << x << ' ';\n});\n\nBOOST_HANA_RUNTIME_CHECK(ss.str() == \"0 1 234 5.5 \");\n//! [for_each]\n\n}{\n\n//! [length]\nBOOST_HANA_CONSTANT_CHECK(length(make<Tuple>()) == size_t<0>);\nBOOST_HANA_CONSTANT_CHECK(length(make<Tuple>(1, '2', 3.0)) == size_t<3>);\n\nBOOST_HANA_CONSTANT_CHECK(length(nothing) == size_t<0>);\nBOOST_HANA_CONSTANT_CHECK(length(just('x')) == size_t<1>);\n//! [length]\n\n}{\n\n//! [size]\nBOOST_HANA_CONSTANT_CHECK(size(make<Tuple>()) == size_t<0>);\nBOOST_HANA_CONSTANT_CHECK(size(make<Tuple>(1, '2', 3.0)) == size_t<3>);\n\nBOOST_HANA_CONSTANT_CHECK(size(nothing) == size_t<0>);\nBOOST_HANA_CONSTANT_CHECK(size(just('x')) == size_t<1>);\n//! [size]\n\n}{\n\n//! [maximum]\nBOOST_HANA_CONSTANT_CHECK(\n    maximum(tuple_c<int, -1, 0, 2, -4, 6, 9>) == int_<9>\n);\n//! [maximum]\n//!\n}{\n\n//! [minimum]\nBOOST_HANA_CONSTANT_CHECK(\n    minimum(tuple_c<int, -1, 0, 2, -4, 6, 9>) == int_<-4>\n);\n//! [minimum]\n\n}{\n\n//! [product]\nBOOST_HANA_CONSTANT_CHECK(\n    product(range(int_<1>, int_<6>)) == int_<1 * 2 * 3 * 4 * 5>\n);\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    product(make<Tuple>(1, int_<3>, long_<-5>, 9)) == 1 * 3 * -5 * 9\n);\n//! [product]\n\n}{\n\n//! [sum]\nBOOST_HANA_CONSTANT_CHECK(\n    sum(range(int_<1>, int_<6>)) == int_<1 + 2 + 3 + 4 + 5>\n);\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    sum(make<Tuple>(1, int_<3>, long_<-5>, 9)) == 1 + 3 - 5 + 9\n);\n//! [sum]\n\n}{\n\n//! [unpack]\nauto cheap_tie = [](auto& ...vars) {\n    return partial(flip(unpack), [&vars...](auto ...values) {\n        // Using an initializer list sequences the assignments.\n        int dummy[] = {((vars = values), 0)...};\n        (void)dummy;\n    });\n};\nint a = 0;\nchar b = '\\0';\ndouble c = 0;\n\ncheap_tie(a, b, c)(make<Tuple>(1, '2', 3.3));\nBOOST_HANA_RUNTIME_CHECK(a == 1 && b == '2' && c == 3.3);\n//! [unpack]\n\n}{\n\n//! [fuse]\nBOOST_HANA_CONSTEXPR_LAMBDA auto add = [](auto x, auto y) {\n    return x + y;\n};\n\n// Would be `boost::fusion::make_fused(add)` in Boost.Fusion.\nBOOST_HANA_CONSTEXPR_LAMBDA auto add_seq = fuse(add);\n\nBOOST_HANA_CONSTEXPR_CHECK(add_seq(make<Tuple>(1, 2)) == add(1, 2));\n//! [fuse]\n\n}{\n\n//! [count_if]\nusing namespace literals;\nBOOST_HANA_CONSTEXPR_LAMBDA auto odd = [](auto x) {\n    return x % 2_c != 0_c;\n};\n\nconstexpr auto types = tuple_t<int, char, long, short, char, double>;\nconstexpr auto ints = tuple_c<int, 1, 2, 3>;\n\nBOOST_HANA_CONSTANT_CHECK(count_if(ints, odd) == size_t<2>);\n\nBOOST_HANA_CONSTANT_CHECK(count_if(types, trait<std::is_floating_point>) == size_t<1>);\nBOOST_HANA_CONSTANT_CHECK(count_if(types, _ == type<char>) == size_t<2>);\nBOOST_HANA_CONSTANT_CHECK(count_if(types, _ == type<void>) == size_t<0>);\n//! [count_if]\n\n}{\n\n//! [count]\nconstexpr auto types = tuple_t<int, char, long, short, char, double>;\nconstexpr auto ints = tuple_c<int, 1, 2, 3, 2, 2, 4, 2>;\n\nBOOST_HANA_CONSTANT_CHECK(count(ints, int_<2>) == size_t<4>);\nBOOST_HANA_CONSTEXPR_CHECK(count(ints, 2) == 4);\nBOOST_HANA_CONSTANT_CHECK(count(types, type<char>) == size_t<2>);\n//! [count]\n\n}{\n\n//!\u00a0[maximum_by]\nBOOST_HANA_CONSTEXPR_LAMBDA auto size = [](auto xs, auto ys) {\n    return length(xs) < length(ys);\n};\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    maximum_by(size, make<Tuple>(make<Tuple>(),\n                                 make<Tuple>(1, '2'),\n                                 make<Tuple>(3.3, nullptr, 4)))\n    ==\n    make<Tuple>(3.3, nullptr, 4)\n);\n//! [maximum_by]\n\n}{\n\n//!\u00a0[minimum_by]\nBOOST_HANA_CONSTEXPR_LAMBDA auto size = [](auto xs, auto ys) {\n    return length(xs) < length(ys);\n};\n\nBOOST_HANA_CONSTANT_CHECK(\n    minimum_by(size, make<Tuple>(make<Tuple>(),\n                                 make<Tuple>(1, '2'),\n                                 make<Tuple>(3.3, nullptr, 4)))\n    ==\n    make<Tuple>()\n);\n//! [minimum_by]\n\n}\n\n}\n", "meta": {"hexsha": "2b2d32ea806a2139e00acf6cf78bbfe589cbd3c1", "size": 6246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/foldable.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/foldable.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/foldable.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4676258993, "max_line_length": 87, "alphanum_fraction": 0.5983029139, "num_tokens": 1961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.721743206297598, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.5610108903354806}}
{"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": "#include <gtest/gtest.h>\n\n#include \"mfem.hpp\"\nusing namespace mfem;\n\n#include <iostream>\n#include <fstream>\n#include <random>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"../include/mymfem/mybilinearform.hpp\"\n#include \"../include/mymfem/utilities.hpp\"\n\n#include \"../include/core/config.hpp\"\n#include \"../include/stokes/assembly.hpp\"\n\n\n// test velocity coefficient\nclass TestVelocityCoeff : public VectorCoefficient\n{\npublic:\n    TestVelocityCoeff () : VectorCoefficient (2) {}\n\n    void Eval (Vector& v, ElementTransformation& T,\n               const IntegrationPoint& ip)\n    {\n        Vector transip(2);\n        T.Transform(ip, transip);\n        v = velocity(transip);\n    }\n\n    Vector velocity (const Vector& x) const\n    {\n        Vector v(2);\n        v(0) = x(0);\n        v(1) = -x(1);\n        return v;\n    }\n};\n\nTEST(RStokes, vshape_test1)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"ref_tri_elem\";\n    Mesh mesh(mesh_file.c_str());\n    assert(mesh.GetNE() == 1);\n\n    int deg = 1;\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(deg, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    Vector true_v(2);\n    true_v(0) = +3;\n    true_v(1) = -2;\n    VectorConstantCoefficient vCoeff(true_v);\n    GridFunction vFn(R_space);\n    vFn.ProjectCoefficient(vCoeff);\n\n    int j=0; // only 1 element in the mesh\n    {\n        const FiniteElement *fe = R_space->GetFE(j);\n        ElementTransformation *trans\n                = R_space->GetElementTransformation(j);\n\n        Array<int> vdofs;\n        Vector fe_dofs(fe->GetDof());\n        R_space->GetElementVDofs(j, vdofs);\n        get_dofs(vFn, vdofs, fe_dofs);\n\n        const IntegrationRule *ir = &IntRules.Get(fe->GetGeomType(), 2);\n        DenseMatrix vshape(fe->GetDof(),2);\n        for (int i = 0; i < ir->GetNPoints(); i++)\n        {\n            const IntegrationPoint &ip = ir->IntPoint(i);\n            trans->SetIntPoint(&ip);\n            fe->CalcVShape(*trans, vshape);\n\n            Vector v(2);\n            vshape.MultTranspose(fe_dofs, v);\n\n            double TOL = 1E-10;\n            v -= true_v;\n            ASSERT_LE(v.Norml2(), TOL);\n        }\n    }\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\nTEST(RStokes, gradvshape_test1)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"ref_tri_elem\";\n    Mesh mesh(mesh_file.c_str());\n    assert(mesh.GetNE() == 1);\n\n    int deg = 1;\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(deg, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    Vector true_v(2);\n    true_v(0) = +3;\n    true_v(1) = -2;\n    VectorConstantCoefficient vCoeff(true_v);\n    GridFunction vFn(R_space);\n    vFn.ProjectCoefficient(vCoeff);\n\n    int j=0; // only 1 element in the mesh\n    {\n        const FiniteElement *fe = R_space->GetFE(j);\n        ElementTransformation *trans\n                = R_space->GetElementTransformation(j);\n\n        Array<int> vdofs;\n        Vector fe_dofs(fe->GetDof());\n        R_space->GetElementVDofs(j, vdofs);\n        get_dofs(vFn, vdofs, fe_dofs);\n\n        const IntegrationRule *ir = &IntRules.Get(fe->GetGeomType(), 0);\n        DenseTensor gradvshape(2,2,fe->GetDof());\n        for (int i = 0; i < ir->GetNPoints(); i++)\n        {\n            const IntegrationPoint &ip = ir->IntPoint(i);\n            trans->SetIntPoint(&ip);\n            fe->CalcGradVShape(*trans, gradvshape);\n\n            DenseMatrix gradu(2,2);\n            gradu = 0.0;\n            for (int k=0; k<fe->GetDof(); k++) {\n                gradu.Add(fe_dofs(k), gradvshape(k));\n            }\n\n            double TOL = 1E-10;\n            ASSERT_LE(gradu.FNorm(), TOL);\n        }\n    }\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\nTEST(RStokes, gradvshape_test2)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"ref_tri_elem\";\n    Mesh mesh(mesh_file.c_str());\n    assert(mesh.GetNE() == 1);\n\n    int deg = 3;\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(deg, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    TestVelocityCoeff vCoeff;\n    GridFunction vFn(R_space);\n    vFn.ProjectCoefficient(vCoeff);\n\n    DenseMatrix true_gradu(2,2);\n    true_gradu = 0.0;\n    true_gradu(0,0) = 1;\n    true_gradu(1,1) = -1;\n\n    int j=0; // only 1 element in the mesh\n    {\n        const FiniteElement *fe = R_space->GetFE(j);\n        ElementTransformation *trans\n                = R_space->GetElementTransformation(j);\n\n        Array<int> vdofs;\n        Vector fe_dofs(fe->GetDof());\n        R_space->GetElementVDofs(j, vdofs);\n        get_dofs(vFn, vdofs, fe_dofs);\n\n        const IntegrationRule *ir = &IntRules.Get(fe->GetGeomType(), 2);\n        DenseTensor gradvshape(2,2,fe->GetDof());\n        for (int i = 0; i < ir->GetNPoints(); i++)\n        {\n            const IntegrationPoint &ip = ir->IntPoint(i);\n            trans->SetIntPoint(&ip);\n            fe->CalcGradVShape(*trans, gradvshape);\n\n            DenseMatrix gradu(2,2);\n            gradu = 0.0;\n            for (int k=0; k<fe->GetDof(); k++) {\n                gradu.Add(fe_dofs(k), gradvshape(k));\n            }\n\n            double TOL = 1E-10;\n            gradu -= true_gradu;\n            ASSERT_LE(gradu.FNorm(), TOL);\n        }\n    }\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\nTEST(Stokes, VectorFEDiffusion_test1)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"tri_elem1\";\n    Mesh mesh(mesh_file.c_str());\n    assert(mesh.GetNE() == 1);\n\n    Array<int> ess_bdr_marker;\n    ess_bdr_marker.SetSize(mesh.bdr_attributes.Max());\n    ess_bdr_marker = 1;\n\n    GridFunction *gdum = nullptr; // dummy\n\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(0, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    mymfem::MyBilinearForm *diffusion_form\n            = new mymfem::MyBilinearForm(R_space);\n    diffusion_form->MyAddDomainIntegrator\n            (new mymfem::DiffusionIntegrator);\n    diffusion_form->MyAssemble(gdum);\n    diffusion_form->Finalize();\n    SparseMatrix *diffusion_buf = diffusion_form->LoseMat();\n    delete diffusion_form;\n    DenseMatrix &diffusion = *(diffusion_buf->ToDenseMatrix());\n\n    DenseMatrix true_diffusion(diffusion.NumRows(), diffusion.NumCols());\n    true_diffusion = 0.0;\n    true_diffusion(0,0) =  0.5;\n    true_diffusion(0,1) = -0.5;\n    true_diffusion(0,2) = -0.5;\n\n    true_diffusion(1,0) = -0.5;\n    true_diffusion(1,1) =  0.5;\n    true_diffusion(1,2) =  0.5;\n\n    true_diffusion(2,0) = -0.5;\n    true_diffusion(2,1) =  0.5;\n    true_diffusion(2,2) =  0.5;\n\n    //true_diffusion.Print();\n    //diffusion.Print();\n\n    double TOL = 1E-10;\n    diffusion -= true_diffusion;\n    ASSERT_LE(diffusion.FNorm(), TOL);\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\nTEST(Stokes, VectorFEDiffusionConsistencySymmetry_test1)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"tri_elem1\";\n    Mesh mesh(mesh_file.c_str());\n\n    Array<int> ess_bdr_marker;\n    ess_bdr_marker.SetSize(mesh.bdr_attributes.Max());\n    ess_bdr_marker = 1;\n\n    GridFunction *gdum = nullptr; // dummy\n\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(0, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    mymfem::MyBilinearForm *diffusionCons_form\n            = new mymfem::MyBilinearForm(R_space);\n    diffusionCons_form->MyAddFaceIntegrator\n            (new mymfem::DiffusionConsistencyIntegrator);\n    diffusionCons_form->MyAssemble(gdum);\n    diffusionCons_form->Finalize();\n    SparseMatrix *diffusionCons_buf = diffusionCons_form->LoseMat();\n    delete diffusionCons_form;\n    DenseMatrix &diffusionCons = *(diffusionCons_buf->ToDenseMatrix());\n\n    mymfem::MyBilinearForm *diffusionSymm_form\n            = new mymfem::MyBilinearForm(R_space);\n    diffusionSymm_form->MyAddFaceIntegrator\n            (new mymfem::DiffusionSymmetryIntegrator);\n    diffusionSymm_form->MyAssemble(gdum);\n    diffusionSymm_form->Finalize();\n    SparseMatrix *diffusionSymm_buf = diffusionSymm_form->LoseMat();\n    delete diffusionSymm_form;\n    DenseMatrix &diffusionSymm = *(diffusionSymm_buf->ToDenseMatrix());\n\n    DenseMatrix true_diffusion(diffusionCons.NumRows(),\n                               diffusionCons.NumCols());\n    true_diffusion = 0.0;\n    true_diffusion(0,0) = -0.5;\n    true_diffusion(0,1) = +0.5;\n    true_diffusion(0,2) = +0.5;\n\n    true_diffusion(1,0) = +0.5;\n    true_diffusion(1,1) = -0.5;\n    true_diffusion(1,2) = -0.5;\n\n    true_diffusion(2,0) = +0.5;\n    true_diffusion(2,1) = -0.5;\n    true_diffusion(2,2) = -0.5;\n\n    //true_diffusion.Print();\n    //diffusion.Print();\n\n    double TOL = 1E-10;\n    diffusionCons -= true_diffusion;\n    diffusionSymm -= true_diffusion;\n    ASSERT_LE(diffusionCons.FNorm(), TOL);\n    ASSERT_LE(diffusionSymm.FNorm(), TOL);\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\nTEST(Stokes, VectorFEDiffusionPenalty_test1)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"tri_elem1\";\n    Mesh mesh(mesh_file.c_str());\n\n    Array<int> ess_bdr_marker;\n    ess_bdr_marker.SetSize(mesh.bdr_attributes.Max());\n    ess_bdr_marker = 1;\n\n    GridFunction *gdum = nullptr; // dummy\n\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(0, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    mymfem::MyBilinearForm *diffusionPen_form\n            = new mymfem::MyBilinearForm(R_space);\n    diffusionPen_form->MyAddFaceIntegrator\n            (new mymfem::DiffusionPenaltyIntegrator(1.0));\n    diffusionPen_form->MyAssemble(gdum);\n    diffusionPen_form->Finalize();\n    SparseMatrix *diffusionCons_buf = diffusionPen_form->LoseMat();\n    delete diffusionPen_form;\n    DenseMatrix &diffusionPen= *(diffusionCons_buf->ToDenseMatrix());\n\n    DenseMatrix true_diffusion(diffusionPen.NumRows(),\n                               diffusionPen.NumCols());\n    true_diffusion = 0.0;\n    true_diffusion(0,0) = 5./6;\n    true_diffusion(0,1) = -7./12;\n    true_diffusion(0,2) = 1./6;\n\n    true_diffusion(1,0) = -7./12;\n    true_diffusion(1,1) = 13./12;\n    true_diffusion(1,2) = -5./12;\n\n    true_diffusion(2,0) = 1./6;\n    true_diffusion(2,1) = -5./12;\n    true_diffusion(2,2) = 11./6;\n\n    //true_diffusion.Print();\n    //diffusionPen.Print();\n\n    double TOL = 1E-10;\n    diffusionPen -= true_diffusion;\n    ASSERT_LE(diffusionPen.FNorm(), TOL);\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\n\nTEST(Stokes, VectorFEDiffusion_test2)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"test_mesh1\";\n    Mesh mesh(mesh_file.c_str());\n    \n    Array<int> ess_bdr_marker;\n    ess_bdr_marker.SetSize(mesh.bdr_attributes.Max());\n    ess_bdr_marker = 1;\n    \n    GridFunction *gdum = nullptr; // dummy\n    \n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(0, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n            \n    mymfem::MyBilinearForm *diffusion_form\n            = new mymfem::MyBilinearForm(R_space);\n    diffusion_form->MyAddDomainIntegrator\n            (new mymfem::DiffusionIntegrator);\n    diffusion_form->MyAssemble(gdum);\n    diffusion_form->Finalize();\n    SparseMatrix *diffusion_buf = diffusion_form->LoseMat();\n    delete diffusion_form;\n    DenseMatrix &diffusion = *(diffusion_buf->ToDenseMatrix());\n\n    DenseMatrix true_diffusion(diffusion.NumRows(), diffusion.NumCols());\n    true_diffusion = 0.0;\n    true_diffusion(0,0) =  2;\n    true_diffusion(0,1) = -1;\n    true_diffusion(0,2) = -1;\n    true_diffusion(0,3) = -1;\n    true_diffusion(0,4) = -1;\n\n    true_diffusion(1,0) = -1;\n    true_diffusion(1,1) =  1;\n    true_diffusion(1,2) =  1;\n\n    true_diffusion(2,0) = -1;\n    true_diffusion(2,1) =  1;\n    true_diffusion(2,2) =  1;\n\n    true_diffusion(3,0) = -1;\n    true_diffusion(3,3) =  1;\n    true_diffusion(3,4) =  1;\n\n    true_diffusion(4,0) = -1;\n    true_diffusion(4,3) =  1;\n    true_diffusion(4,4) =  1;\n\n    //true_diffusion.Print();\n    //diffusion.Print();\n\n    double TOL = 1E-10;\n    diffusion -= true_diffusion;\n    ASSERT_LE(diffusion.FNorm(), TOL);\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\nTEST(Stokes, VectorFEDiffusionConsistencySymmetry_test2)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"test_mesh1\";\n    Mesh mesh(mesh_file.c_str());\n\n    Array<int> ess_bdr_marker;\n    ess_bdr_marker.SetSize(mesh.bdr_attributes.Max());\n    ess_bdr_marker = 1;\n\n    GridFunction *gdum = nullptr; // dummy\n\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(0, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    mymfem::MyBilinearForm *diffusionCons_form\n            = new mymfem::MyBilinearForm(R_space);\n    diffusionCons_form->MyAddFaceIntegrator\n            (new mymfem::DiffusionConsistencyIntegrator);\n    diffusionCons_form->MyAssemble(gdum);\n    diffusionCons_form->Finalize();\n    SparseMatrix *diffusionCons_buf = diffusionCons_form->LoseMat();\n    delete diffusionCons_form;\n    DenseMatrix &diffusionCons = *(diffusionCons_buf->ToDenseMatrix());\n\n    mymfem::MyBilinearForm *diffusionSymm_form\n            = new mymfem::MyBilinearForm(R_space);\n    diffusionSymm_form->MyAddFaceIntegrator\n            (new mymfem::DiffusionSymmetryIntegrator);\n    diffusionSymm_form->MyAssemble(gdum);\n    diffusionSymm_form->Finalize();\n    SparseMatrix *diffusionSymm_buf = diffusionSymm_form->LoseMat();\n    delete diffusionSymm_form;\n    DenseMatrix &diffusionSymm = *(diffusionSymm_buf->ToDenseMatrix());\n\n    DenseMatrix true_diffusion(diffusionCons.NumRows(),\n                               diffusionCons.NumCols());\n    true_diffusion = 0.0;\n\n    true_diffusion(1,0) = +1;\n    true_diffusion(1,1) = -1;\n    true_diffusion(1,2) = -1;\n\n    true_diffusion(2,0) = +1;\n    true_diffusion(2,1) = -1;\n    true_diffusion(2,2) = -1;\n\n    true_diffusion(3,0) = +1;\n    true_diffusion(3,3) = -1;\n    true_diffusion(3,4) = -1;\n\n    true_diffusion(4,0) = +1;\n    true_diffusion(4,3) = -1;\n    true_diffusion(4,4) = -1;\n\n    //true_diffusion.Print();\n    //diffusionCons.Print();\n    //diffusionSymm.Print();\n\n    double TOL = 1E-10;\n    diffusionCons -= true_diffusion;\n    ASSERT_LE(diffusionCons.FNorm(), TOL);\n\n    true_diffusion.Transpose();\n    diffusionSymm -= true_diffusion;\n    ASSERT_LE(diffusionSymm.FNorm(), TOL);\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\n\nTEST(Stokes, consistency_quad_elem)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"ref_quad_elem\";\n    Mesh mesh(mesh_file.c_str());\n\n    GridFunction *gdum = nullptr; // dummy\n\n    int deg = 2;\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(deg, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    Vector true_v(2);\n    true_v(0) = +3;\n    true_v(1) = -2;\n    //VectorConstantCoefficient vCoeff(true_v);\n    TestVelocityCoeff vCoeff;\n    GridFunction v(R_space);\n    v.ProjectCoefficient(vCoeff);\n\n    mymfem::MyBilinearForm *diffusion_form\n            = new mymfem::MyBilinearForm(R_space);\n    diffusion_form->MyAddDomainIntegrator\n            (new mymfem::DiffusionIntegrator);\n    diffusion_form->MyAddFaceIntegrator\n            (new mymfem::DiffusionConsistencyIntegrator);\n    diffusion_form->MyAddFaceIntegrator\n            (new mymfem::DiffusionSymmetryIntegrator);\n    diffusion_form->MyAddFaceIntegrator\n            (new mymfem::DiffusionPenaltyIntegrator(1.0));\n    diffusion_form->MyAssemble(gdum);\n    diffusion_form->Finalize();\n    SparseMatrix *diffusion = diffusion_form->LoseMat();\n    delete diffusion_form;\n\n    // Diffusion * V\n    Vector buf1(R_space->GetTrueVSize());\n    diffusion->Mult(v, buf1);\n\n    // Right-hand side\n    Vector buf2(R_space->GetTrueVSize());\n    LinearForm bdryDiffusion_form(R_space);\n    bdryDiffusion_form.AddBdrFaceIntegrator\n            (new mymfem::BdryDiffusionConsistencyIntegrator(vCoeff));\n    bdryDiffusion_form.AddBdrFaceIntegrator\n            (new mymfem::BdryDiffusionPenaltyIntegrator(vCoeff, 1.0));\n    bdryDiffusion_form.Assemble();\n    buf2 = bdryDiffusion_form.GetData();\n\n    double TOL = 1E-10;\n    buf1 -= buf2;\n    ASSERT_LE(buf1.Norml2(), TOL);\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\nTEST(Stokes, consistency_tri_elem)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"ref_tri_elem\";\n    Mesh mesh(mesh_file.c_str());\n\n    GridFunction *gdum = nullptr; // dummy\n\n    int deg = 2;\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(deg, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    Vector true_v(2);\n    true_v(0) = +3;\n    true_v(1) = -2;\n    //VectorConstantCoefficient vCoeff(true_v);\n    TestVelocityCoeff vCoeff;\n    GridFunction vFn(R_space);\n    vFn.ProjectCoefficient(vCoeff);\n\n    mymfem::MyBilinearForm *diffusion_form\n            = new mymfem::MyBilinearForm(R_space);\n    diffusion_form->MyAddDomainIntegrator\n            (new mymfem::DiffusionIntegrator);\n    diffusion_form->MyAddFaceIntegrator\n            (new mymfem::DiffusionConsistencyIntegrator);\n    diffusion_form->MyAddFaceIntegrator\n            (new mymfem::DiffusionSymmetryIntegrator);\n    diffusion_form->MyAddFaceIntegrator\n            (new mymfem::DiffusionPenaltyIntegrator(1.0));\n    diffusion_form->MyAssemble(gdum);\n    diffusion_form->Finalize();\n    SparseMatrix *diffusion = diffusion_form->LoseMat();\n    delete diffusion_form;\n\n    // Diffusion * V\n    Vector buf1(R_space->GetTrueVSize());\n    diffusion->Mult(vFn, buf1);\n\n    // Right-hand side\n    Vector buf2(R_space->GetTrueVSize());\n    LinearForm bdryDiffusion_form(R_space);\n    bdryDiffusion_form.AddBdrFaceIntegrator\n            (new mymfem::BdryDiffusionConsistencyIntegrator(vCoeff));\n    bdryDiffusion_form.AddBdrFaceIntegrator\n            (new mymfem::BdryDiffusionPenaltyIntegrator(vCoeff, 1.0));\n    bdryDiffusion_form.Assemble();\n    buf2 = bdryDiffusion_form.GetData();\n\n    double TOL = 1E-10;\n    buf1 -= buf2;\n    ASSERT_LE(buf1.Norml2(), TOL);\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\n\n// End of file\n", "meta": {"hexsha": "a05c1bd7485121e8d3ac8a497d621c8fe960875b", "size": 18641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_stokes.cpp", "max_stars_repo_name": "pratyuksh/NumHypSys", "max_stars_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_stokes.cpp", "max_issues_repo_name": "pratyuksh/NumHypSys", "max_issues_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_stokes.cpp", "max_forks_repo_name": "pratyuksh/NumHypSys", "max_forks_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4022082019, "max_line_length": 73, "alphanum_fraction": 0.6448151923, "num_tokens": 5275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.560940640178846}}
{"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": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Suites\n#include <boost/test/unit_test.hpp>\n #include\"basis.hpp\"\n#include\"operators.hpp\"\n#include\"timeev.hpp\"\n#include\"diag.hpp\"\n#include \"files.hpp\"\nusing namespace boost::unit_test;\nusing boost::unit_test_framework::test_suite;\nusing namespace Many_Body;\nBOOST_AUTO_TEST_SUITE(timeevesting)\nBOOST_AUTO_TEST_CASE(timeev)\n{\n  {\n  size_t numberOfSteps=10;\n   const size_t L=4;\n   ElectronBasis<L> e(2);\n   //std::cout << e << std::endl;\n   // Eigen::MatrixXd AA = Eigen::MatrixXd::Random(e.dim, e.dim);\n   // \t Eigen::MatrixXd H = AA + AA.transpose();\n        Operators::Mat H= Operators::NumberOperator(e)+Operators::EKinOperator(e);\n   Eigen::VectorXcd inistate(e.dim);\n  \n   inistate.setZero();\n   inistate[0]=1;\n   Eigen::VectorXd eigenVals(e.dim);\n\n   Operators::Mat O(e.dim, e.dim);\n    O.setZero();\n    O.coeffRef(1, 1)=0.5;\n    O.coeffRef(2, 2)=0.5;\n    \n    // HAmiltonian =H\n   Eigen::MatrixXd HH=Eigen::MatrixXd(H);\n   // Eigen::MatrixXd HH2=Eigen::MatrixXd(H);\n\n   \n   \n   \n   Many_Body::diag(HH, eigenVals);\n\n   double dt= 5;\n\n\t\n\n   Eigen::MatrixXcd evExp=TimeEv::EigenvalExponent(eigenVals, dt);\n   Eigen::MatrixXcd cEVec=HH.cast<std::complex<double>>();\n   Eigen::VectorXd outputTime(numberOfSteps);\n   Eigen::VectorXd outputVals(numberOfSteps);\n       Eigen::VectorXd outputVals2(numberOfSteps);\n       Eigen::VectorXcd newIn=inistate;\n              Eigen::VectorXcd newIn2=inistate;\n           for (size_t i = 0; i < numberOfSteps; ++i)\n       {\n\n       \t TimeEv::timeev_exact(newIn, cEVec, evExp);\n  \t TimeEv::timeev_lanzcos(newIn2, H, 3, dt); \n  \t std::complex<double> c=(newIn.adjoint()*(O*newIn))(0);\n  \t std::complex<double> c2=(newIn2.adjoint()*(O*newIn2))(0);\n\n  \t\t\t// \toutputVals(i)=real(c);\n  \t\t\t// \toutputVals2(i)=real(c2);\n        \t\t// outputTime(i)=i*dt;\n\t \n  \t BOOST_CHECK(std::abs(real(c2)-real(c))<Many_Body::err);\n        }\n     \n      // Many_Body::ToFile(outputTime, outputVals, \"timetestexact.dat\", numberOfSteps);\n      // Many_Body::ToFile(outputTime, outputVals2, \"timetestexact2.dat\", numberOfSteps);\n     // Eigen::VectorXd q(numberOfSteps);\n       }\n\n\t   {\n  size_t numberOfSteps=2;\n   const size_t L=4;\n   ElectronBasis<L> e(2);\n   // Operators::Mat H= Operators::NumberOperator(e)+Operators::EKinOperator(e);\n   //std::cout << e << std::endl;\n   //   Eigen::MatrixXd HH=Eigen::MatrixXd(H);\n    Eigen::MatrixXcd AA = Eigen::MatrixXcd::Random(e.dim, e.dim);\n   Eigen::MatrixXcd H = AA.adjoint()*AA;\nEigen::MatrixXcd HH=Eigen::MatrixXcd(H);\n   Eigen::VectorXcd inistate=Eigen::VectorXcd::Random(e.dim);\n   inistate=inistate/inistate.norm();\n  \n   Eigen::VectorXd eigenVals(e.dim);\n   // Eigen::MatrixXcd BB = Eigen::MatrixXcd::Random(e.dim, e.dim);\n   // Eigen::MatrixXcd B = BB.adjoint()*BB;\n  Operators::Mat B(e.dim, e.dim);\n    B.setZero();\n    B.coeffRef(1, 1)=0.5;\n    B.coeffRef(2, 2)=0.5;\n    \n\n    //Eigen::MatrixXcd HH=Eigen::MatrixXcd(H);\n\n\n   \n   \n   \n   Many_Body::diag(HH, eigenVals);\n\n   double dt= 5;\n\n\t   Eigen::MatrixXcd cEVec=HH.cast<std::complex<double>>();\n\n   Eigen::MatrixXcd evExp=TimeEv::EigenvalExponent(eigenVals, dt);\n\n   Eigen::VectorXd outputTime(numberOfSteps);\n   Eigen::VectorXd outputVals(numberOfSteps);\n   Eigen::VectorXd outputVals2(numberOfSteps);\n   Eigen::VectorXcd newIn=inistate;\n   Eigen::VectorXcd newIn2=inistate;\n           for (size_t i = 0; i < numberOfSteps; ++i)\n       {\n\n       \t TimeEv::timeev_exact(newIn, cEVec, evExp);\n\t TimeEv::timeev_lanzcos(newIn2, H, e.dim, dt); \n\t std::complex<double> c=(newIn.adjoint()*(B*newIn))(0);\n\t std::complex<double> c2=(newIn2.adjoint()*(B*newIn2))(0);\n\n\t \t BOOST_CHECK(std::abs(real(c2)-real(c))<0.001);\n        }\n\n       }\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n// EOF\n\n\n", "meta": {"hexsha": "a096b865456ae17e6fe404d12d1b39bc75f11219", "size": 3746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarkdir/timeevtest.cpp", "max_stars_repo_name": "jansendavid/many-body-lib", "max_stars_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmarkdir/timeevtest.cpp", "max_issues_repo_name": "jansendavid/many-body-lib", "max_issues_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarkdir/timeevtest.cpp", "max_forks_repo_name": "jansendavid/many-body-lib", "max_forks_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9552238806, "max_line_length": 89, "alphanum_fraction": 0.6489588895, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.6584174871563662, "lm_q1q2_score": 0.560940615622937}}
{"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": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//! \\file\r\n//!\\brief Tests for the hyperbolic arccosine function of (fixed_point) for a small digit range.\r\n\r\n#include <cmath>\r\n\r\n#define BOOST_TEST_MODULE test_negatable_func_hyperbolic_arccosine_small\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_func_hyperbolic_arccosine_small)\r\n{\r\n  typedef boost::fixed_point::negatable<7, -24> fixed_point_type;\r\n  typedef fixed_point_type::float_type          float_point_type;\r\n\r\n  const fixed_point_type tol = ldexp(fixed_point_type(1), fixed_point_type::resolution + 4);\r\n\r\n  using std::acosh;\r\n\r\n  // Check positive arguments.\r\n  for(int i = 0; i < 16; ++i)\r\n  {\r\n    const fixed_point_type x = acosh(1 + (fixed_point_type(i) / fixed_point_type(3.1415926535897932385L)));\r\n    const float_point_type y = acosh(1 + (float_point_type(i) / float_point_type(3.1415926535897932385L)));\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n  }\r\n\r\n  fixed_point_type x;\r\n  float_point_type y;\r\n\r\n  // Check a positive argument clost to 1.\r\n  x = acosh(1 + (1 / (fixed_point_type(97) / 10)));\r\n  y = acosh(1 + (1 / (float_point_type(97) / 10)));\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n\r\n  // Check an invalid zero argument.\r\n  x = acosh(0);\r\n  y = float_point_type(0);\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n\r\n  // Check an invalid argument that lies between 0 < x < 1.\r\n  x = acosh(fixed_point_type(1) / 2);\r\n  y = float_point_type(0);\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n}\r\n", "meta": {"hexsha": "9b4b85665d6f73fcfba38d53d6cc87cbac3e45a0", "size": 1975, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_func_hyperbolic_arccosine_small.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_func_hyperbolic_arccosine_small.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_func_hyperbolic_arccosine_small.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4745762712, "max_line_length": 108, "alphanum_fraction": 0.6840506329, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.5608999609716876}}
{"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 \"conex/cone_program.h\"\n#include \"conex/constraint.h\"\n#include \"conex/dense_lmi_constraint.h\"\n#include \"conex/linear_constraint.h\"\n#include \"conex/test/test_util.h\"\n#include <Eigen/Dense>\n\nusing DenseMatrix = Eigen::MatrixXd;\n\nnamespace conex {\nvoid TestSDP(int i) {\n  SolverConfiguration config;\n  int n = 300;\n  int m = 50;\n  auto constraints2 = GetRandomDenseMatrices(n, m);\n\n  DenseMatrix affine2 = Eigen::MatrixXd::Identity(n, n);\n  DenseLMIConstraint LMI{n, constraints2, affine2};\n\n  Program prog(m);\n  DenseMatrix y(m, 1);\n  prog.AddConstraint(LMI);\n\n  auto b = GetFeasibleObjective(&prog);\n  Solve(b, prog, config, y.data());\n}\n}  // namespace conex\n\nint main() {\n  for (int i = 0; i < 1; i++) {\n    conex::TestSDP(i);\n  }\n  return 0;\n}\n", "meta": {"hexsha": "59c609997f07c74693232ba3396921b678d5dcb2", "size": 754, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/test/profile_sdp.cc", "max_stars_repo_name": "ToyotaResearchInstitute/conex", "max_stars_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T08:02:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T21:53:22.000Z", "max_issues_repo_path": "conex/test/profile_sdp.cc", "max_issues_repo_name": "frankpermenter/conex", "max_issues_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/test/profile_sdp.cc", "max_forks_repo_name": "frankpermenter/conex", "max_forks_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T16:02:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T11:25:46.000Z", "avg_line_length": 21.5428571429, "max_line_length": 56, "alphanum_fraction": 0.6896551724, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5608606195679579}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <Eigen/Core>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/eigen/matrix.hpp>\n#include <boost/numeric/bindings/blas/level3.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/bindings/conj.hpp>\n#include \"print.hpp\"\n#include \"random.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\nint main(int argc, char *argv[]) {\n  {\n    typedef std::complex<double> complex;\n    typedef ublas::matrix<complex, ublas::column_major> matrix;\n    typedef matrix::size_type size_type;\n    rand_normal<complex>::reset();\n    size_type m=6, k=7, n=8;\n    matrix A(m, k);\n    matrix B(k, n);\n    matrix C(m, n);\n    for (size_type j=0; j<k; ++j)\n      for (size_type i=0; i<m; ++i) \n \tA(i, j)=rand_normal<complex>::get();\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<k; ++i) \n \tB(i, j)=rand_normal<complex>::get();\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<m; ++i) \n \tC(i, j)=rand_normal<complex>::get();\n    matrix A_t(ublas::trans(A));\n    matrix B_t(ublas::trans(B));\n    matrix A_h(ublas::conj(A_t));\n    matrix B_h(ublas::conj(B_t));\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::gemm(alpha, A, B, beta, C2);\n    matrix C3(C);\n    blas::gemm(alpha, blas::trans(A_t), blas::trans(B_t), beta, C3);\n    matrix C4(C);\n    blas::gemm(alpha, blas::conj(A_h), blas::conj(B_h), beta, C4);\n    std::cout << \"testing boost::ublas containers\\n\"\n     \t      << \"using ublas:\\n\" << print_mat(C1) << '\\n'\n     \t      << \"using blas:\\n\" << print_mat(C2) << '\\n'\n     \t      << \"using blas (transposed):\\n\" << print_mat(C3) << '\\n'\n     \t      << \"using blas (hermitian transposed):\\n\" << print_mat(C4) << '\\n'\n\t      << '\\n';\n  }\n  {\n    typedef std::complex<double> complex;\n    typedef Eigen::Matrix<complex, Eigen::Dynamic, Eigen::Dynamic> matrix;\n    typedef int size_type;\n    rand_normal<complex>::reset();\n    size_type m=6, k=7, n=8;\n    matrix A(m, k);\n    matrix B(k, n);\n    matrix C(m, n);\n    for (size_type j=0; j<k; ++j)\n      for (size_type i=0; i<m; ++i) \n \tA(i, j)=rand_normal<complex>::get();\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<k; ++i) \n \tB(i, j)=rand_normal<complex>::get();\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<m; ++i) \n \tC(i, j)=rand_normal<complex>::get();\n    matrix A_t(A.transpose());\n    matrix B_t(B.transpose());\n    matrix A_h(A.adjoint());\n    matrix B_h(B.adjoint());\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::gemm(alpha, A, B, beta, C2);\n    matrix C3(C);\n    blas::gemm(alpha, blas::trans(A_t), blas::trans(B_t), beta, C3);\n    matrix C4(C);\n    blas::gemm(alpha, blas::conj(A_h), blas::conj(B_h), beta, C4);\n    std::cout << \"testing Eigen containers\\n\"\n     \t      << \"using Eigen:\\n\" << print_mat(C1) << '\\n'\n     \t      << \"using blas:\\n\" << print_mat(C2) << '\\n'\n     \t      << \"using blas (transposed):\\n\" << print_mat(C3) << '\\n'\n     \t      << \"using blas (hermitian transposed):\\n\" << print_mat(C4) << '\\n'\n    \t      << '\\n';\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "4348761e0ae4f55cc0bb247d083d397fada69e91", "size": 3406, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/gemm.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/gemm.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/gemm.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4791666667, "max_line_length": 78, "alphanum_fraction": 0.5910158544, "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5608606017276804}}
{"text": "#include <blitz/tinyvec-et.h>\n#include <blitz/tinymat.h>\n\nusing namespace blitz;\n\ntemplate<typename T>\nvoid optimizationSink(T&);\n\nvoid foo()\n{\n    TinyMatrix<float,3,3> A;\n    TinyVector<float,3> b, c;\n\n    optimizationSink(A);\n    optimizationSink(b);\n\n    c = product(A,b);\n\n    optimizationSink(c);\n}\n\n", "meta": {"hexsha": "a4d0707f6a0aa6fe7885654cfb98a2c122638c30", "size": 306, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/tiny3.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/tiny3.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/tiny3.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.9090909091, "max_line_length": 29, "alphanum_fraction": 0.6633986928, "num_tokens": 81, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5608147768714576}}
{"text": "/* test_fisher_f_distribution.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/fisher_f_distribution.hpp>\r\n#include <limits>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::fisher_f_distribution<>\r\n#define BOOST_RANDOM_ARG1 m\r\n#define BOOST_RANDOM_ARG2 n\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1.0\r\n#define BOOST_RANDOM_ARG2_DEFAULT 1.0\r\n#define BOOST_RANDOM_ARG1_VALUE 7.5\r\n#define BOOST_RANDOM_ARG2_VALUE 0.25\r\n\r\n#define BOOST_RANDOM_DIST0_MIN 0.0\r\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST1_MIN 0.0\r\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST2_MIN 0.0\r\n#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<double>::infinity)()\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS (1.0, 2.1)\r\n#define BOOST_RANDOM_TEST2_PARAMS (10.0, 10.0)\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "4c8eeae17a12d7e65b358d4bee181f5a65e7fd74", "size": 1078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_fisher_f_distribution.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/random/test/test_fisher_f_distribution.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/random/test/test_fisher_f_distribution.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 31.7058823529, "max_line_length": 73, "alphanum_fraction": 0.7764378479, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5608147707734893}}
{"text": "//=======================================================================\n// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file local_search_multi_solution_test.cpp\n * @brief this is implementation using lagrangian relaxation and c++11 lambdas\n * @author Piotr Wygocki\n * @version 1.0\n * @date 2013-02-04\n */\n\n#include \"test_utils/logger.hpp\"\n\n#include \"paal/local_search/local_search.hpp\"\n#include \"paal/local_search/search_components.hpp\"\n#include \"paal/data_structures/combine_iterator.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <vector>\n#include <string>\n#include <cstdlib>\n#include <iomanip>\n\nusing namespace paal;\n\nstruct value_diff {\n    value_diff(double &value, double diff) : m_value(value), m_diff(diff) {}\n\n    double &m_value;\n    double m_diff;\n};\n\nstruct make_value_diff {\n    value_diff operator()(double &value, double diff) const {\n        return value_diff{ value, diff };\n    }\n};\n\nBOOST_AUTO_TEST_CASE(local_search_multi_lamdas_first_improving_test) {\n    typedef double SolutionElement;\n    typedef std::vector<SolutionElement> Solution;\n    typedef SolutionElement Move;\n    const int DIM = 3;\n    const double LOWER_BOUND = 0.;\n    const double UPPER_BOUND = 1.;\n\n    // creating local search\n    const std::vector<double> neighb{ .1, -.1, .01, -.01, .001, -.001 };\n    std::vector<double> neighbCut(neighb.size());\n    double G{ 1 };\n\n    // components for vector\n    auto f = [&](Solution & x) {\n        double &x1(x[0]), &x2(x[1]), &x3(x[2]);\n        return x1 * x2 + x2 * x3 + x3 * x1 - 3 * x1 * x2 * x3 +\n               G * (2 - (x1 + x2 + x3));\n    };\n\n    auto normalize = [ = ](SolutionElement el) {\n        return std::min(std::max(el, LOWER_BOUND), UPPER_BOUND);\n    };\n\n    auto getMoves = [&](Solution & s) {\n        auto b = data_structures::make_combine_iterator(make_value_diff{}, s,\n                                                        neighb);\n        return boost::make_iterator_range(b, decltype(b) {});\n    };\n\n    auto gain = [&](Solution & s, value_diff vd) {\n        auto old = vd.m_value;\n        auto val = f(s);\n        vd.m_value = normalize(vd.m_value + vd.m_diff);\n        auto valMove = f(s);\n        vd.m_value = old;\n        return valMove - val - 1e-6;\n    };\n\n    auto commit = [&](Solution &, value_diff vd) {\n        vd.m_value = normalize(vd.m_value + vd.m_diff);\n        return true;\n    };\n\n    auto ls = [ = ](Solution & x) {\n        x = { .3, .3, .3 };\n        first_improving(\n            x, local_search::make_search_components(getMoves, gain, commit));\n    };\n\n    // components for G.\n    std::vector<double> neighbCutG(neighb.size());\n    std::vector<double> x(DIM, 0);\n    first_improving(\n        x, local_search::make_search_components(getMoves, gain, commit));\n    double best = f(x);\n\n    auto getMovesG = [&](const double g)->const std::vector<double> & {\n        for (int j : paal::irange(neighb.size())) {\n            neighbCutG[j] = neighb[j] + g;\n        }\n        return neighbCutG;\n    };\n\n    auto gainG = [&](double, double g) {\n        std::vector<double> x(DIM, 0);\n        auto old = G;\n        G = g;\n        ls(x);\n        auto newRes = f(x);\n        G = old;\n        return best - newRes - 1e-6;\n    };\n\n    auto commitG = [&](double & s, double u) {\n        assert(G == s);\n        s = u;\n        best = f(x);\n        return true;\n    };\n\n    first_improving(\n        G, local_search::make_search_components(getMovesG, gainG, commitG));\n\n    ls(x);\n\n    // printing\n    LOG(std::setprecision(10));\n    LOGLN(\"G = \" << G);\n    G = 0;\n    LOG(\"f(\");\n    LOG_COPY_RANGE_DEL(x, \",\");\n    // TODO it would be interesting how G depends on starting point ( (0.3, 0.3,\n    // 0.3) now)\n    LOGLN(\") = \\t\" << f(x));\n    LOGLN(\"approximation \" << 2. / f(x));\n}\n", "meta": {"hexsha": "6ed2e3e6606c62bc617594a98bfe30af9a495b3b", "size": 3996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/local_search/local_search_lambdas_langrange_relax_test.cpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/local_search/local_search_lambdas_langrange_relax_test.cpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/local_search/local_search_lambdas_langrange_relax_test.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 28.1408450704, "max_line_length": 80, "alphanum_fraction": 0.5605605606, "num_tokens": 1061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5608147663736383}}
{"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": "//==============================================================================\n//         Copyright 2015 J.T. Lapreste\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/exponential/include/functions/significants.hpp>\n\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <boost/simd/sdk/simd/io.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <complex>\n#include <nt2/sdk/complex/complex.hpp>\n#include <nt2/sdk/complex/dry.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <nt2/include/functions/splat.hpp>\n\n\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n\n\nNT2_TEST_CASE_TPL ( significants,  NT2_SIMD_REAL_TYPES)\n{\n  using nt2::significants;\n  using nt2::tag::significants_;\n  using boost::simd::native;\n  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;\n  typedef std::complex<T> cT;\n  typedef native<cT,ext_t>                cvT;\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_ULP_EQUAL(significants(nt2::Inf<cvT>(), 1), nt2::Inf<cvT>(), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::Minf<cvT>(), 1), nt2::Minf<cvT>(), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::Nan<cvT>(), 1), nt2::Nan<cvT>(), 0.5);\n#endif\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<cvT>(cT(25.34)),  1), nt2::splat<cvT>(30), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<cvT>(cT(25.34)),  2), nt2::splat<cvT>(25), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<cvT>(cT(25.34)),  3), nt2::splat<cvT>(25.3), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<cvT>(cT(25.34)),  4), nt2::splat<cvT>(25.34), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<cvT>(cT(-25.34)), 1), nt2::splat<cvT>(-30), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<cvT>(cT(-25.34)), 2), nt2::splat<cvT>(-25), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<cvT>(cT(-25.34)), 3), nt2::splat<cvT>(-25.3), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(nt2::splat<cvT>(cT(-25.34)), 4), nt2::splat<cvT>(-25.34), 0.5);\n}\n", "meta": {"hexsha": "77741a3ea5540c3466a331f19c1e8f38a822c13d", "size": 2559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/exponential/unit/simd/significants.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/type/complex/exponential/unit/simd/significants.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/type/complex/exponential/unit/simd/significants.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 44.8947368421, "max_line_length": 97, "alphanum_fraction": 0.6557248925, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.560750204551561}}
{"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": "#ifndef MATHTOOLBOX_SOM_HPP\n#define MATHTOOLBOX_SOM_HPP\n\n#include <Eigen/Core>\n#include <memory>\n\nnamespace mathtoolbox\n{\n    class DataNormalizer;\n\n    class Som\n    {\n    public:\n        /// \\param data An n-by-m matrix representing m data points lying in an n-dimensional space.\n        ///\n        /// \\param latent_num_dims The dimensionality of the latent (map) space. It should be either 1 or 2.\n        Som(const Eigen::MatrixXd& data,\n            const int              latent_num_dims      = 2,\n            const int              resolution           = 10,\n            const double           init_var             = 0.50,\n            const double           min_var              = 0.01,\n            const double           var_decreasing_speed = 20.0,\n            const bool             normalize_data       = true);\n\n        const Eigen::MatrixXd& GetLatentSpaceNodePositions() const { return m_latent_node_positions; }\n        const Eigen::MatrixXd& GetLatentSpaceDataPositions() const { return m_Z; }\n\n        Eigen::MatrixXd GetDataSpaceNodePositions() const;\n\n        void Step();\n\n    private:\n        const int m_latent_num_dims;\n        const int m_resolution;\n\n        const double m_init_var;\n        const double m_min_var;\n        const double m_var_decreasing_speed;\n\n        const bool m_normalize_data;\n\n        /// \\brief Grid node positions in the latent space.\n        const Eigen::MatrixXd m_latent_node_positions;\n\n        int m_iter_count;\n\n        /// \\brief Observed data points.\n        Eigen::MatrixXd m_X;\n\n        /// \\brief Vector values on grid nodes.\n        Eigen::MatrixXd m_Y;\n\n        /// \\brief Embeded data points.\n        Eigen::MatrixXd m_Z;\n\n        std::shared_ptr<const DataNormalizer> m_data_normalizer;\n\n        /// \\brief Perform normalization for the current data.\n        void NormalizeData();\n\n        /// \\brief Perform initialization.\n        ///\n        /// \\details Currently, only the random initialization strategy is implemented.\n        void PerformInitialization();\n    };\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_SOM_HPP\n", "meta": {"hexsha": "7af846e5151c1be9581a1a185dc60f31978478fd", "size": 2094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/som.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/som.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/som.hpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 30.347826087, "max_line_length": 108, "alphanum_fraction": 0.6079274117, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.560750197806294}}
{"text": "#include <Ziran/CS/Util/RandomNumber.h>\n#include <Eigen/Geometry>\n#include <chrono>\n#include <math.h>\n\nnamespace ZIRAN {\n\ntemplate <class T>\nRandomNumber<T>::RandomNumber(unsigned s)\n    : generator(s)\n{\n}\ntemplate <class T>\nRandomNumber<T>::~RandomNumber()\n{\n}\n\ntemplate <class T>\nvoid RandomNumber<T>::resetSeed(T s)\n{\n    generator.seed(s);\n}\n\ntemplate <class T>\nvoid RandomNumber<T>::resetSeedUsingTime()\n{\n    auto s = std::chrono::high_resolution_clock::now().time_since_epoch().count();\n    generator.seed(s);\n}\n\ntemplate <class T>\nT RandomNumber<T>::randReal()\n{\n    std::uniform_real_distribution<T> distribution((T)0, (T)1);\n    return distribution(generator);\n}\n\ntemplate <class T>\nT RandomNumber<T>::randReal(T a, T b)\n{\n    std::uniform_real_distribution<T> distribution(a, b);\n    return distribution(generator);\n}\n\ntemplate <class T>\nint RandomNumber<T>::randInt(int a, int b)\n{\n    std::uniform_int_distribution<> distribution(a, b);\n    return distribution(generator);\n}\n\ntemplate <class T>\ntemplate <int d, int flags>\nVector<T, d> RandomNumber<T>::randInBox(const Eigen::Matrix<T, d, 1, flags, d, 1>& min_corner, const Eigen::Matrix<T, d, 1, flags, d, 1>& max_corner)\n{\n    Vector<T, d> r;\n    for (int i = 0; i < d; i++)\n        r(i) = randReal(min_corner(i), max_corner(i));\n    return r;\n}\n\ntemplate <class T>\ntemplate <int d>\nVector<T, d> RandomNumber<T>::randomBarycentricWeights()\n{\n    Vector<T, d> r;\n    T sum;\n    do {\n        sum = 0;\n        for (int i = 0; i < d - 1; i++) {\n            r(i) = randReal();\n            sum += r(i);\n        }\n    } while (sum > 1);\n    r(d - 1) = 1 - sum;\n    return r;\n}\n\ntemplate <class T>\ntemplate <int d, int flags>\nVector<T, d> RandomNumber<T>::randInBall(const Eigen::Matrix<T, d, 1, flags, d, 1>& center, T radius)\n{\n    Vector<T, d> min_corner = center.array() - radius;\n    Vector<T, d> max_corner = center.array() + radius;\n\n    Vector<T, d> r;\n    do {\n        r = randInBox(min_corner, max_corner);\n    } while ((r - center).squaredNorm() > radius * radius);\n    return r;\n}\n\ntemplate <class T>\nvoid RandomNumber<T>::randRotation(Matrix<T, 2, 2>& R)\n{\n    T theta = randReal(0, 2 * M_PI);\n    T c = std::cos(theta);\n    T s = std::sin(theta);\n    R << c, -s, s, c;\n}\n\ntemplate <class T>\nvoid RandomNumber<T>::randRotation(Matrix<T, 3, 3>& R)\n{\n    std::normal_distribution<T> n;\n    Eigen::Quaternion<T> q(n(generator), n(generator), n(generator), n(generator));\n    q.normalize();\n    R = q.toRotationMatrix();\n}\n\ntemplate <class T, class Derived>\nstatic void fillHelper(RandomNumber<T>& rand, Eigen::DenseBase<Derived>& x, T a, T b)\n{\n    for (typename Derived::Index i = 0; i < x.size(); i++)\n        x(i) = rand.randReal(a, b);\n}\n\ntemplate <class T, class T2>\nstatic std::enable_if_t<std::is_arithmetic<T2>::value> fillHelper(RandomNumber<T>& rand, T2& x, T a, T b)\n{\n    x = rand.randReal(a, b);\n}\n\ntemplate <class T>\ntemplate <class T2>\nvoid RandomNumber<T>::fill(T2& x, T a, T b)\n{\n    fillHelper(*this, x, a, b);\n}\n\ntemplate <class T, class Derived>\nstatic void fillIntHelper(RandomNumber<T>& rand, Eigen::DenseBase<Derived>& x, int a, int b)\n{\n    for (typename Derived::Index i = 0; i < x.size(); i++)\n        x(i) = rand.randInt(a, b);\n}\n\ntemplate <class T, class T2>\nstatic std::enable_if_t<std::is_arithmetic<T2>::value> fillIntHelper(RandomNumber<T>& rand, T2& x, int a, int b)\n{\n    x = rand.randInt(a, b);\n}\n\ntemplate <class T>\ntemplate <class T2>\nvoid RandomNumber<T>::fillInt(T2& x, int a, int b)\n{\n    fillIntHelper(*this, x, a, b);\n}\n\ntemplate Eigen::Matrix<double, 2, 1, 0, 2, 1> RandomNumber<double>::randInBall<2, 0>(Eigen::Matrix<double, 2, 1, 0, 2, 1> const&, double);\ntemplate Eigen::Matrix<double, 2, 1, 0, 2, 1> RandomNumber<double>::randInBall<2, 2>(Eigen::Matrix<double, 2, 1, 2, 2, 1> const&, double);\ntemplate Eigen::Matrix<double, 3, 1, 0, 3, 1> RandomNumber<double>::randInBox<3, 0>(Eigen::Matrix<double, 3, 1, 0, 3, 1> const&, Eigen::Matrix<double, 3, 1, 0, 3, 1> const&);\ntemplate Eigen::Matrix<double, 3, 1, 0, 3, 1> RandomNumber<double>::randInBall<3, 0>(Eigen::Matrix<double, 3, 1, 0, 3, 1> const&, double);\ntemplate Eigen::Matrix<double, 3, 1, 0, 3, 1> RandomNumber<double>::randInBall<3, 2>(Eigen::Matrix<double, 3, 1, 2, 3, 1> const&, double);\ntemplate Eigen::Matrix<double, 3, 1, 0, 3, 1> RandomNumber<double>::randomBarycentricWeights<3>();\ntemplate Eigen::Matrix<float, 2, 1, 0, 2, 1> RandomNumber<float>::randInBall<2, 0>(Eigen::Matrix<float, 2, 1, 0, 2, 1> const&, float);\ntemplate Eigen::Matrix<float, 2, 1, 0, 2, 1> RandomNumber<float>::randInBall<2, 2>(Eigen::Matrix<float, 2, 1, 2, 2, 1> const&, float);\ntemplate Eigen::Matrix<float, 2, 1, 0, 2, 1> RandomNumber<float>::randInBox<2, 0>(Eigen::Matrix<float, 2, 1, 0, 2, 1> const&, Eigen::Matrix<float, 2, 1, 0, 2, 1> const&);\ntemplate Eigen::Matrix<float, 3, 1, 0, 3, 1> RandomNumber<float>::randInBall<3, 0>(Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, float);\ntemplate Eigen::Matrix<float, 3, 1, 0, 3, 1> RandomNumber<float>::randInBall<3, 2>(Eigen::Matrix<float, 3, 1, 2, 3, 1> const&, float);\ntemplate Eigen::Matrix<float, 3, 1, 0, 3, 1> RandomNumber<float>::randInBox<3, 0>(Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, Eigen::Matrix<float, 3, 1, 0, 3, 1> const&);\ntemplate Eigen::Matrix<float, 3, 1, 0, 3, 1> RandomNumber<float>::randomBarycentricWeights<3>();\ntemplate Vector<double, 2> RandomNumber<double>::randInBox<2, 0>(Eigen::Matrix<double, 2, 1, 0, 2, 1> const&, Eigen::Matrix<double, 2, 1, 0, 2, 1> const&);\ntemplate class RandomNumber<double>;\ntemplate class RandomNumber<float>;\ntemplate void RandomNumber<double>::fill<double>(double&, double, double);\ntemplate void RandomNumber<float>::fill<float>(float&, float, float);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 2, 1, 0, 2, 1>>(Eigen::Matrix<double, 2, 1, 0, 2, 1>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 3, 1, 0, 3, 1>>(Eigen::Matrix<double, 3, 1, 0, 3, 1>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, -1, -1, 0, -1, -1>>(Eigen::Matrix<double, -1, -1, 0, -1, -1>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 2, -1, 0, 2, -1>>(Eigen::Matrix<double, 2, -1, 0, 2, -1>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 2, 2, 0, 2, 2>>(Eigen::Matrix<double, 2, 2, 0, 2, 2>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 3, -1, 0, 3, -1>>(Eigen::Matrix<double, 3, -1, 0, 3, -1>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 3, 3, 0, 3, 3>>(Eigen::Matrix<double, 3, 3, 0, 3, 3>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 3, 2, 0, 3, 2>>(Eigen::Matrix<double, 3, 2, 0, 3, 2>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 4, 2, 0, 4, 2>>(Eigen::Matrix<double, 4, 2, 0, 4, 2>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 4, 3, 0, 4, 3>>(Eigen::Matrix<double, 4, 3, 0, 4, 3>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 8, 2, 0, 8, 2>>(Eigen::Matrix<double, 8, 2, 0, 8, 2>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 7, 3, 0, 7, 3>>(Eigen::Matrix<double, 7, 3, 0, 7, 3>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 8, 3, 0, 8, 3>>(Eigen::Matrix<double, 8, 3, 0, 8, 3>&, double, double);\ntemplate void RandomNumber<double>::fill<Eigen::Matrix<double, 26, 3, 0, 26, 3>>(Eigen::Matrix<double, 26, 3, 0, 26, 3>&, double, double);\ntemplate void RandomNumber<double>::fillInt<Eigen::Matrix<double, 2, 2, 0, 2, 2>>(Eigen::Matrix<double, 2, 2, 0, 2, 2>&, int, int);\ntemplate void RandomNumber<double>::fillInt<Eigen::Matrix<double, 3, 3, 0, 3, 3>>(Eigen::Matrix<double, 3, 3, 0, 3, 3>&, int, int);\n\ntemplate void RandomNumber<float>::fill<Eigen::Array<float, 10000, 1, 0, 10000, 1>>(Eigen::Array<float, 10000, 1, 0, 10000, 1>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, 3, 1, 0, 3, 1>>(Eigen::Matrix<float, 3, 1, 0, 3, 1>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, 3, 2, 0, 3, 2>>(Eigen::Matrix<float, 3, 2, 0, 3, 2>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, -1, 1, 0, -1, 1>>(Eigen::Matrix<float, -1, 1, 0, -1, 1>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, 1, 1, 0, 1, 1>>(Eigen::Matrix<float, 1, 1, 0, 1, 1>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, 2, 1, 0, 2, 1>>(Eigen::Matrix<float, 2, 1, 0, 2, 1>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, 2, 2, 0, 2, 2>>(Eigen::Matrix<float, 2, 2, 0, 2, 2>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, 3, 3, 0, 3, 3>>(Eigen::Matrix<float, 3, 3, 0, 3, 3>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, 4, 2, 0, 4, 2>>(Eigen::Matrix<float, 4, 2, 0, 4, 2>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, 4, 3, 0, 4, 3>>(Eigen::Matrix<float, 4, 3, 0, 4, 3>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, 8, 2, 0, 8, 2>>(Eigen::Matrix<float, 8, 2, 0, 8, 2>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, 8, 3, 0, 8, 3>>(Eigen::Matrix<float, 8, 3, 0, 8, 3>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, 7, 3, 0, 7, 3>>(Eigen::Matrix<float, 7, 3, 0, 7, 3>&, float, float);\ntemplate void RandomNumber<float>::fill<Eigen::Matrix<float, 26, 3, 0, 26, 3>>(Eigen::Matrix<float, 26, 3, 0, 26, 3>&, float, float);\ntemplate void RandomNumber<float>::fillInt<Eigen::Matrix<float, 2, 2, 0, 2, 2>>(Eigen::Matrix<float, 2, 2, 0, 2, 2>&, int, int);\ntemplate void RandomNumber<float>::fillInt<Eigen::Matrix<float, 3, 3, 0, 3, 3>>(Eigen::Matrix<float, 3, 3, 0, 3, 3>&, int, int);\n} // namespace ZIRAN\n", "meta": {"hexsha": "bba110948473abb420a38530f882a2e572713a37", "size": 10009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lib/Ziran/CS/Util/RandomNumber.cpp", "max_stars_repo_name": "NTForked/ziran2019", "max_stars_repo_head_hexsha": "35742ac3ab1ae42cf2bbe8761fd7c8e630a638c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73.0, "max_stars_repo_stars_event_min_datetime": "2019-11-06T13:33:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T15:54:50.000Z", "max_issues_repo_path": "Lib/Ziran/CS/Util/RandomNumber.cpp", "max_issues_repo_name": "NTForked/ziran2019", "max_issues_repo_head_hexsha": "35742ac3ab1ae42cf2bbe8761fd7c8e630a638c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-06-24T21:19:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T19:37:53.000Z", "max_forks_repo_path": "Lib/Ziran/CS/Util/RandomNumber.cpp", "max_forks_repo_name": "NTForked/ziran2019", "max_forks_repo_head_hexsha": "35742ac3ab1ae42cf2bbe8761fd7c8e630a638c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2019-11-07T07:15:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-06T10:40:39.000Z", "avg_line_length": 49.3054187192, "max_line_length": 174, "alphanum_fraction": 0.6525127385, "num_tokens": 3644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5607501928350779}}
{"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); // \u5de6\u8fba\u306fauto\u3067\u554f\u984c\u306a\u3057\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; // \u57fa\u5e95\u30af\u30e9\u30b9\u306e\u30dd\u30a4\u30f3\u30bf\u306e\u30b3\u30f3\u30c6\u30ca\u3092\u7528\u610f\u3059\u308b\n    vector<shared_ptr<BaseLayer>> layers; // \u57fa\u5e95\u30af\u30e9\u30b9\u306e\u30dd\u30a4\u30f3\u30bf\u306e\u30b3\u30f3\u30c6\u30ca\u3092\u7528\u610f\u3059\u308b\n    map<string, unique_ptr<BaseLayer>> layers_map;\n    // \u62bd\u8c61\u30af\u30e9\u30b9\u306e\u30dd\u30a4\u30f3\u30bf\u306b\u683c\u7d0d\u3059\u308b\u306e\u3067\u3001unique_ptr\u3068\u3057\u3066\u306fBaseLayer\u306b\u683c\u7d0d\n    // unique_ptr<BaseLayer> p_layer1(new AddLayer()); // C++11\u3067\u306fmake_unique\u304c\u5b58\u5728\u3057\u306a\u3044\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); // \u30b5\u30a4\u30ba\u3092\u5165\u529b\u3059\u308b\u3088\u3046\u306b\u3057\u3066\u307f\u308b\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\u306e\u6d3e\u751f\u30af\u30e9\u30b9(Add)\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\n    // layers.push_back(std::move(p_layer2)); // Layer\u306e\u6d3e\u751f\u30af\u30e9\u30b9(Mul)\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\n    // layers.push_back(std::move(p_layer3)); // Layer\u306e\u6d3e\u751f\u30af\u30e9\u30b9(ReLU)\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\n    // layers.push_back(std::move(p_layer4)); // Layer\u306e\u6d3e\u751f\u30af\u30e9\u30b9(Sigmoid)\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\n    // layers.push_back(std::move(p_layer5)); // Layer\u306e\u6d3e\u751f\u30af\u30e9\u30b9(Affine)\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\n    // layers.push_back(std::move(p_layer6)); // Layer\u306e\u6d3e\u751f\u30af\u30e9\u30b9(SoftmaxWithLoss)\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\n\n    layers.push_back(p_layer1); // Layer\u306e\u6d3e\u751f\u30af\u30e9\u30b9(Add)\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\n    layers.push_back(p_layer2); // Layer\u306e\u6d3e\u751f\u30af\u30e9\u30b9(Mul)\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\n    layers.push_back(p_layer3); // Layer\u306e\u6d3e\u751f\u30af\u30e9\u30b9(ReLU)\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\n    layers.push_back(p_layer4); // Layer\u306e\u6d3e\u751f\u30af\u30e9\u30b9(Sigmoid)\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\n    layers.push_back(p_layer5); // Layer\u306e\u6d3e\u751f\u30af\u30e9\u30b9(Affine)\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\n    layers.push_back(p_layer6); // Layer\u306e\u6d3e\u751f\u30af\u30e9\u30b9(SoftmaxWithLoss)\u306e\u30dd\u30a4\u30f3\u30bf\u3092\u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\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); // \u30b3\u30f3\u30c6\u30ca\u306b\u683c\u7d0d\u3057\u305fLayer\u306e\u30a2\u30c9\u30ec\u30b9\u304b\u3089\u3001\u30e1\u30f3\u30d0\u95a2\u6570\u3092\u547c\u3073\u51fa\u3057(\u30dd\u30ea\u30e2\u30fc\u30d5\u30a3\u30ba\u30e0)\n\n        cout << outputs[0] << endl;\n    }\n\n    // Affine\u30ec\u30a4\u30e4\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u66f4\u65b0\u3067\u304d\u308b\u306e\u304b\u78ba\u8a8d\u3057\u305f\u3044\u306e\u3067\u3001backward\u306e\u51e6\u7406\u3092\u8d70\u3089\u305b\u305f\u5f8c\u306b\u3001\n    // grads\u306e\u5185\u5bb9\u3092\u52a0\u3048\u308b\u3068\u3044\u3046\u51e6\u7406\u3092\u3057\u3001\u305d\u306e\u51e6\u7406\u306e\u524d\u5f8c\u3067\u30d1\u30e9\u30e1\u30fc\u30bf\u306e\u5185\u5bb9\u304c\u5909\u5316\u3057\u3066\u3044\u308b\u304b\u3092\u78ba\u8a8d\u3059\u308b\u3002\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    // \u5225\u306e\u30b9\u30b3\u30fc\u30d7\u3067\u30a2\u30af\u30bb\u30b9\u3057\u305f\u3068\u304d\u306b\u66f4\u65b0\u3055\u308c\u3066\u3044\u308b\u304b\uff1f\n    if (auto re_affine = std::dynamic_pointer_cast<MyDL::Affine>(layers[4]))\n    {\n        cout << \"--- after update ---\" << endl; // \u5185\u90e8\u3067\u51e6\u7406\u3057\u306a\u3044\u3068\u3001affine\u304c\u5ba3\u8a00\u3055\u308c\u3066\u3044\u306a\u3044\u3001\u3068\u306a\u308b\u3002\u30b9\u30b3\u30fc\u30d7\u5916\uff1f\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": "/* Copyright (c) 2016, the Cap authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#define BOOST_TEST_MODULE TestPostProcessor\n\n#include \"main.cc\"\n\n#include <cap/post_processor.h>\n#include <cap/utils.h>\n#include <boost/format.hpp>\n#include <boost/foreach.hpp>\n#include <boost/test/unit_test.hpp>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\nBOOST_AUTO_TEST_CASE(test_compute_energy)\n{\n  // We need to use a large tolerance because the error increases at each time\n  // step.\n  double const tolerance = 1e-6;\n\n  double const pi = M_PI;\n  double const initial_time = 0.0;\n  double const final_time = 2.0 * pi;\n  std::size_t const n = 10001;\n  std::vector<double> time(n);\n  std::vector<double> power(n);\n\n  // INITIALIZE SOLUTION\n  for (std::size_t i = 0; i < n; ++i)\n  {\n    time[i] = initial_time +\n              static_cast<double>(i) / (n - 1) * (final_time - initial_time);\n    power[i] = std::cos(time[i]);\n  }\n\n  // COMPUTE ENERGY\n  std::vector<double> energy(n);\n  cap::compute_energy(time, power, energy);\n\n  // CHECK THE ANSWER\n  std::vector<double> exact(n);\n  std::vector<double> error(n);\n  exact[0] = 0.0;\n  for (std::size_t i = 0; i < n; ++i)\n  {\n    exact[i] = std::sin(time[i]);\n    error[i] = energy[i] - exact[i];\n    BOOST_REQUIRE(std::abs(error[i]) < tolerance);\n  }\n}\n", "meta": {"hexsha": "881dcddcbeaf64ab927247820b94c86d0c6553c9", "size": 1516, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/test/test_postprocessor.cc", "max_stars_repo_name": "waffle-iron/Cap", "max_stars_repo_head_hexsha": "c3e1f585177211bdd5b8cd4637291d659738eb41", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/test/test_postprocessor.cc", "max_issues_repo_name": "waffle-iron/Cap", "max_issues_repo_head_hexsha": "c3e1f585177211bdd5b8cd4637291d659738eb41", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/test/test_postprocessor.cc", "max_forks_repo_name": "waffle-iron/Cap", "max_forks_repo_head_hexsha": "c3e1f585177211bdd5b8cd4637291d659738eb41", "max_forks_repo_licenses": ["BSD-3-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.6949152542, "max_line_length": 78, "alphanum_fraction": 0.6675461741, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5607198295304827}}
{"text": "/*\n * Copyright (C) 2018 Swift Navigation Inc.\n * Contact: Swift Navigation <dev@swiftnav.com>\n *\n * This source is subject to the license found in the file 'LICENSE' which must\n * be distributed together with this source. All other rights reserved.\n *\n * THIS CODE AND INFORMATION IS PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY KIND,\n * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.\n */\n\n#include \"covariance_functions/distance_metrics.h\"\n#include \"test_utils.h\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n#include <iostream>\n#include <vector>\n\nnamespace albatross {\n\nTEST(test_distance_metrics, test_euclidean_distance) {\n\n  Eigen::VectorXd x(3);\n  Eigen::VectorXd y(3);\n  EuclideanDistance dist;\n\n  x << 1., 1., 1.;\n  y << 1., 1., 2.;\n  EXPECT_DOUBLE_EQ(dist(x, y), 1.);\n\n  x << 1., 1., 1.;\n  y << 2., 2., 2.;\n  EXPECT_DOUBLE_EQ(dist(x, y), sqrt(3.));\n\n  x << 2., 2., 2.;\n  y << 2., 2., 2.;\n  EXPECT_DOUBLE_EQ(dist(x, y), 0.);\n}\n\nTEST(test_distance_metrics, test_radial_distance) {\n\n  Eigen::VectorXd x(3);\n  Eigen::VectorXd y(3);\n  RadialDistance dist;\n\n  x << 0., 0., 1.;\n  y << 0., 0., 1.;\n  EXPECT_DOUBLE_EQ(dist(x, y), 0.);\n\n  x << 0., 0., 1.;\n  y << 0., 1., 0.;\n  EXPECT_DOUBLE_EQ(dist(x, y), 0.);\n\n  x << 0., 1., 1.;\n  y << 1., 0., 0.;\n  EXPECT_DOUBLE_EQ(dist(x, y), sqrt(2.) - 1.);\n}\n\nTEST(test_distance_metrics, test_angular_distance) {\n\n  Eigen::VectorXd x(3);\n  Eigen::VectorXd y(3);\n  AngularDistance dist;\n\n  x << 0., 0., 1.;\n  y << 0., 0., 1.;\n  EXPECT_DOUBLE_EQ(dist(x, y), 0.);\n\n  x << 0., 0., 1.;\n  y << 0., 0., -1.;\n  EXPECT_DOUBLE_EQ(dist(x, y), M_PI);\n\n  x << 0., 0., 1.;\n  y << 0., 1., 0.;\n  EXPECT_DOUBLE_EQ(dist(x, y), M_PI / 2.);\n}\n\nTEST(test_distance_metrics, test_distance_matrix) {\n\n  const auto points = random_spherical_points(10);\n\n  EuclideanDistance dist;\n\n  const auto dist_matrix = distance_matrix(dist, points);\n  EXPECT_EQ(dist_matrix.rows(), points.size());\n  EXPECT_EQ(dist_matrix.cols(), points.size());\n}\n\n} // namespace albatross\n", "meta": {"hexsha": "a64d27a4849fc39d81ac70bbe743b91ecf4bd7d0", "size": 2096, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/test_distance_metrics.cc", "max_stars_repo_name": "akleeman/albatross", "max_stars_repo_head_hexsha": "f89bf4c20e35b71ea4d89260dc981b1a2363d41b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_distance_metrics.cc", "max_issues_repo_name": "akleeman/albatross", "max_issues_repo_head_hexsha": "f89bf4c20e35b71ea4d89260dc981b1a2363d41b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_distance_metrics.cc", "max_forks_repo_name": "akleeman/albatross", "max_forks_repo_head_hexsha": "f89bf4c20e35b71ea4d89260dc981b1a2363d41b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7826086957, "max_line_length": 79, "alphanum_fraction": 0.6402671756, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5606864339168911}}
{"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": "//\n// boost/radix/detail/bits.hpp\n//\n// Copyright (c) Chris Glover, 2017-2018\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#ifndef BOOST_RADIX_DETAIL_BITS_HPP\n#define BOOST_RADIX_DETAIL_BITS_HPP\n\n#include <boost/radix/common.hpp>\n\n#include <boost/integer/common_factor.hpp>\n#include <boost/integer/static_log2.hpp>\n\nnamespace boost { namespace radix {\nnamespace detail {\n\ntemplate <std::size_t Bits>\nstruct bits_lcm\n{\n    typedef typename boost::integer::static_lcm<Bits, 8> type;\n    BOOST_STATIC_CONSTANT(std::size_t, value = type::value);\n};\n\n} // namespace detail\n\nnamespace bits {\n\ntemplate <std::size_t AlphabetSize>\nstruct from_alphabet_size\n{\n    BOOST_STATIC_CONSTANT(\n        std::size_t, value = boost::static_log2<AlphabetSize>::value);\n};\n\ntemplate <std::size_t Bits>\nstruct to_alphabet_size\n{\n    BOOST_STATIC_CONSTANT(\n        std::size_t, value = 1 << Bits);\n};\n\ntemplate <std::size_t Bits>\nstruct to_packed_segment_size\n{\n    BOOST_STATIC_CONSTANT(\n        std::size_t, value = detail::bits_lcm<Bits>::value / 8);\n};\n\ntemplate <std::size_t Bits>\nstruct to_unpacked_segment_size\n{\n    BOOST_STATIC_CONSTANT(\n        std::size_t, value = detail::bits_lcm<Bits>::value / Bits);\n};\n\n} // namespace bits\n}} // namespace boost::radix\n\n#endif // BOOST_RADIX_DETAIL_BITS_HPP\n", "meta": {"hexsha": "cf760930bc727e5838e725750bba2dcbdd85d2a1", "size": 1399, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/radix/detail/bits.hpp", "max_stars_repo_name": "cdglove/boost.radix", "max_stars_repo_head_hexsha": "39626a1a76eb33ce9bd43b3957f1a39678943a30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T20:27:16.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-11T20:27:16.000Z", "max_issues_repo_path": "include/boost/radix/detail/bits.hpp", "max_issues_repo_name": "cdglove/boost.radix", "max_issues_repo_head_hexsha": "39626a1a76eb33ce9bd43b3957f1a39678943a30", "max_issues_repo_licenses": ["BSL-1.0"], "max_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/radix/detail/bits.hpp", "max_forks_repo_name": "cdglove/boost.radix", "max_forks_repo_head_hexsha": "39626a1a76eb33ce9bd43b3957f1a39678943a30", "max_forks_repo_licenses": ["BSL-1.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.859375, "max_line_length": 79, "alphanum_fraction": 0.7255182273, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5606847003967194}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n//  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": "//\n// Created by przestaw on 16.12.2020.\n//\n#include <boost/test/unit_test.hpp>\n#include <gpuclassifier/GPUCalculateClassP.hpp>\n\nBOOST_AUTO_TEST_SUITE(nbc4gpu_TestSuite)\n\nBOOST_AUTO_TEST_SUITE(ClassPropability_TestSuite)\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size0) {\n  boost::compute::device device = boost::compute::system::default_device();\n  boost::compute::context context(device);\n  boost::compute::command_queue queue(context, device);\n\n  nbc4gpu::GPUCalculateClassP<float>::Statistics stats = {};\n  BOOST_CHECK_THROW((nbc4gpu::GPUCalculateClassP<float>(stats, 1, queue)),\n                    nbc4gpu::error::ZeroValuesProvided);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_MismatchSize) {\n  boost::compute::device device = boost::compute::system::default_device();\n  boost::compute::context context(device);\n  boost::compute::command_queue queue(context, device);\n\n  nbc4gpu::GPUCalculateClassP<float>::Statistics stats = {{1, 1}};\n  nbc4gpu::GPUCalculateClassP<float> classifier(stats, 0, queue);\n  BOOST_CHECK_THROW(classifier({1, 2, 3, 4}), nbc4gpu::error::MismatchedSize);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size1_1) {\n  boost::compute::device device = boost::compute::system::default_device();\n  boost::compute::context context(device);\n  boost::compute::command_queue queue(context, device);\n\n  nbc4gpu::GPUCalculateClassP<float>::Statistics stats = {{1, 1}};\n  nbc4gpu::GPUCalculateClassP<float> classifier(stats, 0, queue);\n  // P = 1/(sqr(2*pi) * sqr(var)) * exp(-((x-avg)^2 / 2*var))\n\n  // P = 1/(sqr(2*pi) * 1) * exp(-((1-1)^2 / 2*1)) = 0.3989... * exp(0)  =\n  // 0.3989\n  BOOST_CHECK_CLOSE(classifier.operator()({1}), 0.3989, 0.1);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({0}), 0.2419, 0.1);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({2}), 0.2419, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size1_2) {\n  boost::compute::device device = boost::compute::system::default_device();\n  boost::compute::context context(device);\n  boost::compute::command_queue queue(context, device);\n\n  nbc4gpu::GPUCalculateClassP<float>::Statistics stats = {{2, 5}};\n  nbc4gpu::GPUCalculateClassP<float> classifier(stats, 0, queue);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({1}), 0.161449, 0.1);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({2}), 0.178429, 0.1);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({0}), 0.119605, 0.1);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({3}), 0.161449, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size4_1) {\n  boost::compute::device device = boost::compute::system::default_device();\n  boost::compute::context context(device);\n  boost::compute::command_queue queue(context, device);\n\n  nbc4gpu::GPUCalculateClassP<float>::Statistics stats = {\n      {2, 1}, {2, 1}, {2, 1}, {2, 1}};\n  nbc4gpu::GPUCalculateClassP<float> classifier(stats, 0, queue);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({1, 0, 2, 3}), 0.001261597, 0.1);\n  BOOST_CHECK_CLOSE(classifier.operator()({0, 1, 2, 3}), 0.001261597, 0.1);\n  BOOST_CHECK_CLOSE(classifier.operator()({3, 1, 0, 2}), 0.001261597, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size4_2) {\n  boost::compute::device device = boost::compute::system::default_device();\n  boost::compute::context context(device);\n  boost::compute::command_queue queue(context, device);\n\n  nbc4gpu::GPUCalculateClassP<float>::Statistics stats = {\n      {2, 5}, {2, 3}, {0.15, 4}, {3.5, 1.5}};\n  nbc4gpu::GPUCalculateClassP<float> classifier(stats, 0, queue);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({1, 2, 0, 3}), 0.002217, 0.1);\n  BOOST_CHECK_CLOSE(classifier.operator()({2.5, 3, 0.5, 4}), 0.001998, 0.1);\n  BOOST_CHECK_CLOSE(classifier.operator()({1, 1, 1, 1}), 0.00023274, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size0_double) {\n  boost::compute::device device = boost::compute::system::default_device();\n  boost::compute::context context(device);\n  boost::compute::command_queue queue(context, device);\n\n  nbc4gpu::GPUCalculateClassP<double>::Statistics stats = {};\n  BOOST_CHECK_THROW((nbc4gpu::GPUCalculateClassP<double>(stats, 1.0, queue)),\n                    nbc4gpu::error::ZeroValuesProvided);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_MismatchSize_double) {\n  boost::compute::device device = boost::compute::system::default_device();\n  boost::compute::context context(device);\n  boost::compute::command_queue queue(context, device);\n\n  nbc4gpu::GPUCalculateClassP<double>::Statistics stats = {{1, 1}};\n  nbc4gpu::GPUCalculateClassP<double> classifier(stats, 0, queue);\n  BOOST_CHECK_THROW(classifier({1, 2, 3, 4}), nbc4gpu::error::MismatchedSize);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size1_1_double) {\n  boost::compute::device device = boost::compute::system::default_device();\n  boost::compute::context context(device);\n  boost::compute::command_queue queue(context, device);\n\n  nbc4gpu::GPUCalculateClassP<double>::Statistics stats = {{1, 1}};\n  nbc4gpu::GPUCalculateClassP<double> classifier(stats, 0, queue);\n  // P = 1/(sqr(2*pi) * sqr(var)) * exp(-((x-avg)^2 / 2*var))\n\n  // P = 1/(sqr(2*pi) * 1) * exp(-((1-1)^2 / 2*1)) = 0.3989... * exp(0)  =\n  // 0.3989\n  BOOST_CHECK_CLOSE(classifier.operator()({1}), 0.3989, 0.1);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({0}), 0.2419, 0.1);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({2}), 0.2419, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size1_2_double) {\n  boost::compute::device device = boost::compute::system::default_device();\n  boost::compute::context context(device);\n  boost::compute::command_queue queue(context, device);\n\n  nbc4gpu::GPUCalculateClassP<double>::Statistics stats = {{2, 5}};\n  nbc4gpu::GPUCalculateClassP<double> classifier(stats, 0, queue);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({1}), 0.161449, 0.1);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({2}), 0.178429, 0.1);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({0}), 0.119605, 0.1);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({3}), 0.161449, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size4_1_double) {\n  boost::compute::device device = boost::compute::system::default_device();\n  boost::compute::context context(device);\n  boost::compute::command_queue queue(context, device);\n\n  nbc4gpu::GPUCalculateClassP<double>::Statistics stats = {\n      {2, 1}, {2, 1}, {2, 1}, {2, 1}};\n  nbc4gpu::GPUCalculateClassP<double> classifier(stats, 0, queue);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({1, 0, 2, 3}), 0.001261597, 0.1);\n  BOOST_CHECK_CLOSE(classifier.operator()({0, 1, 2, 3}), 0.001261597, 0.1);\n  BOOST_CHECK_CLOSE(classifier.operator()({3, 1, 0, 2}), 0.001261597, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(PrecalulatedTest_Size4_2_double) {\n  boost::compute::device device = boost::compute::system::default_device();\n  boost::compute::context context(device);\n  boost::compute::command_queue queue(context, device);\n\n  nbc4gpu::GPUCalculateClassP<double>::Statistics stats = {\n      {2, 5}, {2, 3}, {0.15, 4}, {3.5, 1.5}};\n  nbc4gpu::GPUCalculateClassP<double> classifier(stats, 0, queue);\n\n  BOOST_CHECK_CLOSE(classifier.operator()({1, 2, 0, 3}), 0.002217, 0.1);\n  BOOST_CHECK_CLOSE(classifier.operator()({2.5, 3, 0.5, 4}), 0.001998, 0.1);\n  BOOST_CHECK_CLOSE(classifier.operator()({1, 1, 1, 1}), 0.00023274, 0.1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "a93745860c5f1ec8128c71b396141360ba4118b1", "size": 7194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gpuTest/calc_p_test.cpp", "max_stars_repo_name": "przestaw/nbc4gpu", "max_stars_repo_head_hexsha": "641945ac3974ec9df78a4217ebd133576791c58a", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/gpuTest/calc_p_test.cpp", "max_issues_repo_name": "przestaw/nbc4gpu", "max_issues_repo_head_hexsha": "641945ac3974ec9df78a4217ebd133576791c58a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/gpuTest/calc_p_test.cpp", "max_forks_repo_name": "przestaw/nbc4gpu", "max_forks_repo_head_hexsha": "641945ac3974ec9df78a4217ebd133576791c58a", "max_forks_repo_licenses": ["BSD-3-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.1899441341, "max_line_length": 78, "alphanum_fraction": 0.7114261885, "num_tokens": 2276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.560501131495252}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/included/unit_test.hpp>\n#include \"bayesian/graph.hpp\"\n#include \"bayesian/inference/rejection_sampling.hpp\"\n\nBOOST_AUTO_TEST_CASE( rejection_sampling_standard )\n{\n    bn::graph_t graph;\n    auto const vertex_1 = graph.add_vertex();\n    auto const vertex_2 = graph.add_vertex();\n    auto const vertex_3 = graph.add_vertex();\n    auto const vertex_4 = graph.add_vertex();\n    auto const vertex_5 = graph.add_vertex();\n    auto edge_12 = graph.add_edge(vertex_1, vertex_2);\n    auto edge_13 = graph.add_edge(vertex_1, vertex_3);\n    auto edge_24 = graph.add_edge(vertex_2, vertex_4);\n    auto edge_25 = graph.add_edge(vertex_2, vertex_5);\n    auto edge_35 = graph.add_edge(vertex_3, vertex_5);\n\n    {\n        vertex_1->selectable_num = 2;\n        vertex_1->cpt.assign({}, vertex_1);\n\n        bn::condition_t const cond;\n        vertex_1->cpt[cond].second = {0.5, 0.5};\n    }\n    {\n        vertex_2->selectable_num = 2;\n        vertex_2->cpt.assign({vertex_1}, vertex_2);\n\n        bn::condition_t const cond_0 = {{vertex_1, 0}};\n        bn::condition_t const cond_1 = {{vertex_1, 1}};\n        vertex_2->cpt[cond_0].second = {0.8, 0.2};\n        vertex_2->cpt[cond_1].second = {0.1, 0.9};\n    }\n    {\n        vertex_3->selectable_num = 2;\n        vertex_3->cpt.assign({vertex_1}, vertex_3);\n\n        bn::condition_t const cond_0 = {{vertex_1, 0}};\n        bn::condition_t const cond_1 = {{vertex_1, 1}};\n        vertex_3->cpt[cond_0].second = {0.7, 0.3};\n        vertex_3->cpt[cond_1].second = {0.4, 0.6};\n    }\n    {\n        vertex_4->selectable_num = 2;\n        vertex_4->cpt.assign({vertex_2}, vertex_4);\n\n        bn::condition_t const cond_0 = {{vertex_2, 0}};\n        bn::condition_t const cond_1 = {{vertex_2, 1}};\n        vertex_4->cpt[cond_0].second = {0.6, 0.4};\n        vertex_4->cpt[cond_1].second = {0.1, 0.9};\n    }\n    {\n        vertex_5->selectable_num = 2;\n        vertex_5->cpt.assign({vertex_2, vertex_3}, vertex_5);\n\n        bn::condition_t const cond_00 = {{vertex_2, 0}, {vertex_3, 0}};\n        bn::condition_t const cond_01 = {{vertex_2, 0}, {vertex_3, 1}};\n        bn::condition_t const cond_10 = {{vertex_2, 1}, {vertex_3, 0}};\n        bn::condition_t const cond_11 = {{vertex_2, 1}, {vertex_3, 1}};\n        vertex_5->cpt[cond_00].second = {0.1, 0.9};\n        vertex_5->cpt[cond_01].second = {0.2, 0.8};\n        vertex_5->cpt[cond_10].second = {0.3, 0.7};\n        vertex_5->cpt[cond_11].second = {0.4, 0.6};\n    }\n\n    bn::inference::rejection_sampling func(graph);\n    auto const result = func({{vertex_4,1}, {vertex_1, 0}});\n\n    BOOST_CHECK_CLOSE(result.at(vertex_2)[0][0], 0.62, 10);\n    BOOST_CHECK_CLOSE(result.at(vertex_2)[0][1], 0.38, 10);\n}\n", "meta": {"hexsha": "73799c0937834b80b1680b77568d217a4da916ac", "size": 2712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/bayesian/test/rejection_sampling.cpp", "max_stars_repo_name": "godai0519/BayesianNetwork-Inference", "max_stars_repo_head_hexsha": "ab72b5fe96f1b648a98b8b659c4cafcfe96d8204", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-06-05T07:25:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T19:43:20.000Z", "max_issues_repo_path": "libs/bayesian/test/rejection_sampling.cpp", "max_issues_repo_name": "godai0519/BayesianNetwork", "max_issues_repo_head_hexsha": "ab72b5fe96f1b648a98b8b659c4cafcfe96d8204", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2015-02-09T12:32:19.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T09:08:17.000Z", "max_forks_repo_path": "libs/bayesian/test/rejection_sampling.cpp", "max_forks_repo_name": "godai0519/BayesianNetwork-Inference", "max_forks_repo_head_hexsha": "ab72b5fe96f1b648a98b8b659c4cafcfe96d8204", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2016-08-14T13:47:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-18T09:33:18.000Z", "avg_line_length": 36.6486486486, "max_line_length": 71, "alphanum_fraction": 0.616519174, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5605011217740266}}
{"text": "#include <stdlib.h>\n#include <vector>\n#include <stdint.h>\n#include <iostream>\n//#include <boost/range.hpp>\n#include <algorithm>\n#include <boost/range/irange.hpp>\n//#include <boost/range/algorithm.hpp>\n#include <boost/range/adaptors.hpp>\n#include <random>\n#include <qs.hpp>\n#include <stack>\n#include \"PredictableRandomGenerator.hpp\"\n\n\nvoid printList( const std::vector< int64_t > & list, const char * text = \"\" )\n{\n    std::cout << text;\n    \n    for( int64_t i = 0; i < list.size(); ++i )\n    {\n        std::cout << list[i] << \" \";\n    }\n\n    printf( \"\\n\\n\" );\n}\n\nvoid printList( const std::vector< int64_t > & list, const std::vector< int64_t > & pivots, const int64_t to_swap, const char * text = \"\" )\n{\n    std::cout << text;\n    \n    for( int64_t i = 0; i < list.size(); ++i )\n    {\n        auto iter = std::find( std::begin(pivots), std::end(pivots), i);\n        if( iter != std::end(pivots) )\n        {\n            std::cout << \"[\" << list[i] << \"],\";\n        }\n        else if( i == to_swap )\n        {\n            std::cout << \"{\" << list[i] << \"},\";\n        }\n        else\n            std::cout << list[i] << \",\";\n    }\n\n    printf( \"\\n\\n\" );\n}\n\nvoid printPivots( const std::vector< int64_t > & arr, const std::vector< int64_t > & pivots )\n{\n    std::cout << \"PivotValues=\";\n    \n    for( auto & pivot : pivots ) {\n        std::cout << arr[pivot] << \",\";\n    }\n    \n    std::cout << \"\\n\\n\";\n}\n\nint64_t Number_of_comparisons = 0;\nint64_t Number_of_swaps = 0;\n\ninline std::vector<int64_t> sort_pivots( std::vector<int64_t> & arr, int64_t start, int64_t end, std::vector<int64_t> && pivots )\n{\n    std::sort( std::begin( pivots ), std::end( pivots ) );\n   \n    std::vector<int64_t> new_pivots;\n    new_pivots.reserve( pivots.size() );\n\n    int64_t first_pivot = start;\n    for( auto p : pivots )\n    {\n        new_pivots.push_back( first_pivot );\n\n        std::swap( arr[p], arr[first_pivot]);\n\n        ++first_pivot;\n    }\n    \n    Number_of_swaps += first_pivot - start;\n\n    auto iter = std::begin( arr ) + start;\n    \n    std::sort( iter, iter + pivots.size() );\n    \n    return new_pivots;\n}\n\nstatic std::random_device rd; // obtain a random number from hardware\nstatic std::mt19937 gen(rd()); // seed the generator\n\n\ninline std::vector< int64_t > get_pivot( std::vector< int64_t > & arr, int64_t l, int64_t r, int64_t n )\n{\n    RandomNumberStream prg(n);\n\n    //std::uniform_int_distribution<> distr(l, r); // define the range\n\n    if( abs(r-l) < n ) {\n        n = round( (abs(r-l)) / 2 );\n    }\n    \n    std::vector< int64_t > pivots;\n    pivots.reserve(n);\n\n    for( int64_t i = 0; i < n; ++i )\n    {\n        while( true ) {\n            auto new_pivot = prg.RandomInteger(l,r);//distr(gen);\n            auto iter = std::find( std::begin( pivots ), std::end( pivots ), new_pivot );\n            \n            if( iter != std::end( pivots ) ) continue;\n            \n            pivots.push_back( new_pivot );\n            break;\n        }\n    }\n    \n    // sorting part\n    pivots = sort_pivots( arr, l, r, std::move(pivots) );\n\n    //printPivots( arr, pivots );\n    \n    return pivots;\n}\n\ninline std::vector< bool > less_or_equal( const std::vector< int64_t > & arr, const std::vector<int64_t> & pivots, const int64_t value )\n{\n    std::vector< bool > output( pivots.size() + 1, true );\n\n    int64_t index = 0;\n\n    for( const auto p : pivots ) {\n        const auto res = arr[p] >= value;\n\n        if( res ) break;\n\n        output[index++] = res;\n    }\n\n    Number_of_comparisons += index;\n    \n    return output;\n}\n\ninline std::vector< bool > greater( const std::vector< int64_t > & arr, const std::vector<int64_t> & pivots, const int64_t value )\n{\n    std::vector< bool > output( pivots.size() + 1, true );\n\n    int64_t index = pivots.size();\n    \n    for( const auto p : pivots | boost::adaptors::reversed ) {\n        const auto res = arr[p] < value;\n        \n        // since all the pivot values are sorted, thus if value greater \n        // then last pivot implies that for the remaining pivots it also greater\n        if( res ) break;\n        \n        output[index--] = res;\n    }\n\n    Number_of_comparisons += pivots.size() - index;\n\n    return output;\n}\n\n// TODO: cover with test\ninline int64_t identify_new_sector( const std::vector< int64_t > & arr, const std::vector<int64_t> & pivots, const int64_t value )\n{\n    const auto lq = less_or_equal( arr, pivots, value );\n    const auto gt = greater( arr, pivots, value );\n\n    int64_t index = 0;\n\n    for( const auto l : lq | boost::adaptors::indexed(0) )\n    {\n        const auto idx = l.index();\n\n        if( l.value() && gt[index] )\n        {\n            index = idx;\n            break;\n        } \n    }\n\n    return index;\n}\n\nstd::vector<int64_t> general_partition( std::vector<int64_t> & arr, int64_t l, int64_t r, std::vector<int64_t> & pivots )\n{\n    for( const auto i : boost::irange<int64_t>( l + pivots.size()-1, r+1 ) )\n    {\n        const auto iter = std::find( std::begin( pivots ), std::end( pivots ), i );\n\n        if( iter != std::end( pivots ) )\n            continue;\n        \n        const auto new_sector = identify_new_sector( arr, pivots, arr[i] );\n\n        // check if value already in right sector\n        if( new_sector == pivots.size() )\n            continue;\n\n        int64_t new_i = i;\n        for( const auto sector : boost::irange<int64_t>( new_sector, pivots.size() ) | boost::adaptors::reversed )\n        {\n            auto & pivot( pivots[sector] );\n\n            if( new_i > sector+1 )\n            {\n                std::swap( arr[ pivot + 1 ], arr[new_i] );\n                Number_of_swaps++;\n            }\n\n            std::swap( arr[ pivot ], arr[ pivot + 1 ] );\n            Number_of_swaps++;\n            \n            new_i = pivot;\n            pivot += 1;\n        }\n    }\n    \n    return std::move( pivots );\n}\n\ninline int64_t find_value_sector( const std::vector<int64_t> & pivots, int64_t value_position )\n{\n    auto pivot_iter = std::find_if( std::begin(pivots), std::end(pivots), [value_position]( const auto & pivot ) \n        {\n            return pivot > value_position;\n        } );\n\n    return pivot_iter - std::begin(pivots) + ( pivot_iter == std::end(pivots) ? 1 : 0 );\n}\n\ninline void sort_pivots2( std::vector<int64_t> & arr, int64_t start, int64_t end, std::vector<int64_t> & pivots )\n{\n    std::sort( std::begin( pivots ), std::end( pivots ) );\n   \n    std::vector< int64_t > values;\n    values.reserve( pivots.size() );\n\n    for( const auto p : pivots ) {\n        values.push_back( arr[p] );\n    }\n\n    std::sort( std::begin( values ), std::end( values ) );\n    \n    for( auto entry : values | boost::adaptors::indexed(0) )\n    {\n        arr[pivots[entry.index()]] = entry.value();\n    }    \n}\n\ninline std::vector< int64_t > get_pivot2( std::vector< int64_t > & arr, int64_t l, int64_t r, int64_t n )\n{\n    std::uniform_int_distribution<> distr(l, r); // define the range\n\n    if( abs(r-l) < n ) {\n        //std::cout << \"Changed \" << n << \" to \" << abs(r-l) << std::endl;  \n        n = round( (abs(r-l)) / 2 );\n    }\n    \n    std::vector< int64_t > pivots;\n    pivots.reserve(n);\n\n    for( int64_t i = 0; i < n; ++i )\n    {\n        while( true ) {\n            auto new_pivot = distr(gen);\n\n            auto iter = std::find( std::begin( pivots ), std::end( pivots ), new_pivot );            \n            if( iter != std::end( pivots ) ) continue;\n            \n            auto iter2 = std::find( std::begin( pivots ), std::end( pivots ), new_pivot+1 );\n            if( iter2 != std::end( pivots ) ) continue;\n\n            auto iter3 = std::find( std::begin( pivots ), std::end( pivots ), new_pivot-1 );\n            if( iter3 != std::end( pivots ) ) continue;\n\n            pivots.push_back( new_pivot );\n            break;\n        }\n    }\n    \n    // sorting part\n    sort_pivots2( arr, l, r, pivots );\n    \n    return pivots;\n}\n\nstd::vector<int64_t> general_partition2( std::vector<int64_t> & arr, int64_t l, int64_t r, std::vector<int64_t> & pivots )\n{\n    int64_t i = l;\n    int64_t pivot_boundary = 0;\n    int64_t pivot_id = 0;\n    int64_t after_pivot = -1;\n    int64_t prev_pivot = -1;\n\n    for( auto & pivot : pivots ) { \n        \n        const auto pivot_value = arr[pivot];\n        \n        while( i < pivot )\n        {\n            if( arr[i] > pivot_value )\n            {                \n                if( pivot-1 > pivot_boundary )\n                {\n                    std::swap( arr[pivot], arr[pivot-1] );\n                    std::swap( arr[i], arr[pivot] );\n                    // updating pivot\n                    pivot -= 1;\n                }\n                else\n                {\n                    std::swap( arr[i], arr[pivot] );\n                    // updating pivot\n                    pivot -= 1;\n                }\n            }\n            else if( pivot_id != 0 )\n            {\n                std::swap( arr[after_pivot++], arr[i] );\n            }\n\n            ++i;\n        }\n\n        if( pivot_id != 0 )\n        {\n            std::swap( arr[prev_pivot], arr[after_pivot-1] );\n            pivots[pivot_id] = after_pivot-1;\n        }\n\n        prev_pivot = pivot;\n\n        after_pivot = pivot+1;\n        pivot_boundary = pivot+1;\n        pivot_id += 1;        \n    }\n\n    return std::move( pivots );\n}\n\nvoid __quicksort( std::vector< int64_t > & arr, int64_t l, int64_t r, int64_t num_pivots )\n{\n    if( l >= r ) return;\n\n    if( l + 1 == r )\n    {\n        if( arr[r] < arr[l] )\n            std::swap(arr[r], arr[l]);\n\n        return;\n    }\n\n    if( abs(r-l) <= 10 ) {\n        std::sort( std::begin( arr )+l, std::begin( arr )+r+1 );\n        return;\n    }\n\n    auto pivots = get_pivot( arr, l, r, num_pivots );\n\n    pivots = general_partition( arr, l, r, pivots );\n    \n    for( const auto pivot : pivots )\n    {\n        __quicksort(arr, l, pivot - 1, num_pivots);\n        l = pivot + 1;\n    }\n\n    __quicksort(arr, pivots.back()+1, r, num_pivots);\n}\n\nstruct stack_node {\n    int64_t l;\n    int64_t r;\n};\n\nstd::pair<int64_t,int64_t> quicksort( std::vector< int64_t > & arr, int64_t num_pivots )\n{\n    Number_of_comparisons = 0;\n    Number_of_swaps = 0;\n\n    std::stack< stack_node > stck;\n    stck.push( stack_node{0, static_cast<int64_t>(arr.size() - 1) } );\n\n    while( !stck.empty() ) \n    {\n        auto sn = stck.top();\n        stck.pop();\n\n        int64_t l = sn.l;\n        int64_t r = sn.r;\n        \n        if( abs(r-l) <= 10 ) {\n            std::sort( std::begin( arr )+l, std::begin( arr )+r+1 );\n            continue;\n        }\n\n        auto pivots = get_pivot( arr, l, r, num_pivots );    \n        pivots = general_partition( arr, l, r, pivots );\n\n        for( const auto pivot : pivots )\n        {\n            stck.push( stack_node{l, pivot - 1} );\n\n            l = pivot + 1;\n        }\n\n        stck.push( stack_node{pivots.back()+1, r} );     \n    }\n\n    return std::make_pair( Number_of_comparisons, Number_of_swaps ); \n}\n\nstd::vector<int64_t> general_partition3( std::vector<int64_t> & arr, int64_t l, int64_t r, std::vector<int64_t> & pivots )\n{\n    int64_t current_pivot_index = 0;\n    \n    for( auto & pivot : pivots )\n    {\n        const auto pivot_value = arr[pivot];\n        \n        int64_t low_boundary = l;\n        \n        auto start_position = ( pivot-16 <= low_boundary ? low_boundary : pivot-16 );\n        \n        int64_t new_left_pivot_position = -1;\n        \n        // checking elements on left side of the pivot\n        for( int64_t i = start_position; i < pivot; ++i )\n        {\n            if( arr[i] > pivot_value && new_left_pivot_position == -1 )\n                new_left_pivot_position = i;\n            else\n                new_left_pivot_position = -1;\n        }\n        \n        int64_t high_boundary = r;\n        if( current_pivot_index+1 < pivots.size() )\n        {\n            high_boundary = pivots[current_pivot_index+1];\n        }\n        \n        auto end_position = ( pivot+16 >= high_boundary ? high_boundary : pivot+16 );\n\n        int64_t new_right_pivot_position = -1;\n                \n        // checking elements on left side of the pivot\n        for( int64_t i = pivot+1; i < end_position; ++i )\n        {\n            if( arr[i] <= pivot_value && new_right_pivot_position == -1 )\n                new_right_pivot_position = i;\n            else\n                new_right_pivot_position = -1;\n        }\n        \n        if( new_left_pivot_position >= new_right_pivot_position && new_left_pivot_position != -1 )\n        {\n            std::swap(arr[new_left_pivot_position], arr[pivot]);\n            pivot = new_left_pivot_position;\n        }\n        else if( new_right_pivot_position != -1 ){\n            std::swap(arr[new_right_pivot_position], arr[pivot]);\n            pivot = new_left_pivot_position;\n        }\n        \n        ++current_pivot_index;\n        \n        printPivots( arr, pivots );\n        //printList( arr, pivots );\n    }\n    \n    return std::move( pivots );\n}\n\n// void quicksort( std::vector< int64_t > & arr, int64_t num_pivots )\n// {\n//     if( arr.size() <= 1 )\n//         return;\n\n//     __quicksort(arr, 0, arr.size() - 1, num_pivots );\n// }\n\n\n/* TODO:\n Problems:\n 1. unknown crash on linux\n 2. implementation is slow as hell\n \n Tasks:\n 1. Support visual studio\n 2. Test coverage - DONE\n 2.1. I will set up project - DONE\n 3. Fix bug on linux - DONE\n 4. Improve performance( mainly for paper ) - PARTIALLY DONE\n 5. Implement counting of number swaps and comparisons\n 6. Vargring to check all the cache misses\n 7. Maybe dynamic pivoting would be interesting\n \n Aral TODO: Tasks - [1, 4 ]\n Rustam TODO: Tasks - [2.1, 3, 4 ]\n \n */", "meta": {"hexsha": "4dda8da670911d603256cf67b7a079c4d64c70f2", "size": 13551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/qs.cpp", "max_stars_repo_name": "rabdumalikov/multipivot_quicksort", "max_stars_repo_head_hexsha": "9bf97fa7e3b8ef78c2a835bb9b58de28cfa82643", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/qs.cpp", "max_issues_repo_name": "rabdumalikov/multipivot_quicksort", "max_issues_repo_head_hexsha": "9bf97fa7e3b8ef78c2a835bb9b58de28cfa82643", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qs.cpp", "max_forks_repo_name": "rabdumalikov/multipivot_quicksort", "max_forks_repo_head_hexsha": "9bf97fa7e3b8ef78c2a835bb9b58de28cfa82643", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7278106509, "max_line_length": 139, "alphanum_fraction": 0.5335399602, "num_tokens": 3847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5605011217740266}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nMatrix<float,2,3> m = Matrix<float,2,3>::Random();\nMatrix2f y = Matrix2f::Random();\ncout << \"Here is the matrix m:\" << endl << m << endl;\ncout << \"Here is the matrix y:\" << endl << y << endl;\nMatrix<float,3,2> x = m.fullPivLu().solve(y);\nif((m*x).isApprox(y))\n{\n  cout << \"Here is a solution x to the equation mx=y:\" << endl << x << endl;\n}\nelse\n  cout << \"The equation mx=y does not have any solution.\" << endl;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "59a38eb949fd36f07a27eed0bc4363f40eb1aec8", "size": 946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_FullPivLU_solve.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_FullPivLU_solve.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_FullPivLU_solve.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0285714286, "max_line_length": 224, "alphanum_fraction": 0.6575052854, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.560498529068324}}
{"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": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#include <simd_test.hpp>\n#include <boost/simd/function/sincospi.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/std.hpp>\n\n\nnamespace bs = boost::simd;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], c[N], s[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(2*i)/N : -T(2*i)/N;\n    std::tie(s[i], c[i])= bs::sincospi(a1[i]) ;\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t ss (&s[0], &s[0]+N);\n  p_t cc (&c[0], &c[0]+N);\n  p_t ss1, cc1;\n  std::tie(ss1, cc1)= bs::sincospi(aa1) ;\n  STF_ULP_EQUAL(ss1, ss, 0.5);\n  STF_ULP_EQUAL(cc1, cc, 0.5);\n}\n\nSTF_CASE_TPL(\"Check sincospi on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid testr(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], c[N], s[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = ((i%2) ? T(i) : -T(i))*T(0.25)/N;\n    std::tie(s[i], c[i])= bs::restricted_(bs::sincospi)(a1[i]);\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t ss (&s[0], &s[0]+N);\n  p_t cc (&c[0], &c[0]+N);\n  p_t ss1, cc1;\n  std::tie(ss1, cc1)= bs::restricted_(bs::sincospi)(aa1);\n\n  STF_ULP_EQUAL(ss1, ss,0.5);\n  STF_ULP_EQUAL(cc1, cc,0.5);\n}\n\nSTF_CASE_TPL(\"Check restricted sincospi on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  testr<T, N>($);\n  testr<T, N/2>($);\n  testr<T, N*2>($);\n}\n", "meta": {"hexsha": "fc69042202cd11cae662ff8ad68dced94fe66616", "size": 1884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/sincospi.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "test/function/simd/sincospi.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/simd/sincospi.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 24.4675324675, "max_line_length": 100, "alphanum_fraction": 0.5180467091, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5604985196670366}}
{"text": "/* Boost numeric test of the adams-bashforth-moulton steppers test file\r\n\r\n Copyright 2013 Karsten Ahnert\r\n Copyright 2013-2015 Mario Mulansky\r\n\r\n Distributed under the Boost Software License, Version 1.0.\r\n (See accompanying file LICENSE_1_0.txt or\r\n copy at http://www.boost.org/LICENSE_1_0.txt)\r\n*/\r\n\r\n// disable checked iterator warning for msvc\r\n#include <boost/config.hpp>\r\n#ifdef BOOST_MSVC\r\n    #pragma warning(disable:4996)\r\n#endif\r\n\r\n#define BOOST_TEST_MODULE numeric_adams_bashforth_moulton\r\n\r\n#include <iostream>\r\n#include <cmath>\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <boost/mpl/vector.hpp>\r\n\r\n#include <boost/numeric/odeint.hpp>\r\n\r\nusing namespace boost::unit_test;\r\nusing namespace boost::numeric::odeint;\r\nnamespace mpl = boost::mpl;\r\n\r\ntypedef double value_type;\r\n\r\ntypedef value_type state_type;\r\n\r\n\r\n// simple time-dependent rhs, analytic solution x = 0.5*t^2\r\nstruct simple_rhs\r\n{\r\n    void operator()( const state_type& x , state_type &dxdt , const double t ) const\r\n    {\r\n        dxdt = t;\r\n    }\r\n};\r\n\r\nBOOST_AUTO_TEST_SUITE( numeric_abm_time_dependent_test )\r\n\r\n\r\n/* generic test for all adams bashforth moulton steppers */\r\ntemplate< class Stepper >\r\nstruct perform_abm_time_dependent_test\r\n{\r\n    void operator()( void )\r\n    {\r\n        Stepper stepper;\r\n        const int o = stepper.order()+1; //order of the error is order of approximation + 1\r\n\r\n        const state_type x0 = 0.0;\r\n        state_type x1 = x0;\r\n        double t = 0.0;\r\n        double dt = 0.1;\r\n        const int steps = 10;\r\n\r\n        integrate_n_steps( boost::ref(stepper) , simple_rhs(), x1 , t , dt , steps );\r\n        BOOST_CHECK_LT( std::abs( 0.5 - x1 ) , std::pow( dt , o ) );\r\n    }\r\n};\r\n\r\ntypedef mpl::vector<\r\n    adams_bashforth_moulton< 2 , state_type > ,\r\n    adams_bashforth_moulton< 3 , state_type > ,\r\n    adams_bashforth_moulton< 4 , state_type > ,\r\n    adams_bashforth_moulton< 5 , state_type > ,\r\n    adams_bashforth_moulton< 6 , state_type > ,\r\n    adams_bashforth_moulton< 7 , state_type > ,\r\n    adams_bashforth_moulton< 8 , state_type >\r\n    > adams_bashforth_moulton_steppers;\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( abm_time_dependent_test , Stepper, adams_bashforth_moulton_steppers )\r\n{\r\n    perform_abm_time_dependent_test< Stepper > tester;\r\n    tester();\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "7061c17b33d56e34ded118f9455b381f54b17689", "size": 2325, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/test/numeric/abm_time_dependent.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/test/numeric/abm_time_dependent.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/test/numeric/abm_time_dependent.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 27.0348837209, "max_line_length": 101, "alphanum_fraction": 0.6864516129, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.5604985170176137}}
{"text": "#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN\n#include <math.h>\n#include <doctest/doctest.h>\n#include <Eigen/Dense>\n#include <dynkin/dynkin.hpp>\n\n#define DEG2RAD M_PI/180.0f\n\nTEST_CASE(\"Single frame translation\"){\n    using namespace dynkin;\n    Eigen::Vector3d expected;\n\n    Frame f1 = create_frame();\n    f1->position() << 1, 1, 1;\n    f1->set_attitude({0,0,90*DEG2RAD});\n\n    Transform t = transform(nullptr, f1);\n\n    expected << 1, 1, 1;\n    CHECK(t.HTM.translation().isApprox(expected));\n\n    t = transform(f1, nullptr);\n\n    expected << -1, 1, -1;\n    CHECK(t.HTM.translation().isApprox(expected));\n}\n\nTEST_CASE(\"Single frame position\"){\n    using namespace dynkin;\n    Eigen::Vector3d expected;\n\n    Frame f1 = create_frame();\n    f1->position() << 1, 1, 1;\n    f1->set_attitude({90*DEG2RAD,0,90*DEG2RAD});\n\n    Transform t = transform(nullptr, f1);\n\n    expected << 1, 1, 1;\n    CHECK(t.apply_position({0,0,0}).isApprox(expected));\n\n    expected << 1, 2, 1;\n    CHECK(t.apply_position({1,0,0}).isApprox(expected));\n\n    expected << 1, 1, 2;\n    CHECK(t.apply_position({0,1,0}).isApprox(expected));\n\n    expected << 2, 1, 1;\n    CHECK(t.apply_position({0,0,1}).isApprox(expected));\n}\n\nTEST_CASE(\"Single frame vector\"){\n    using namespace dynkin;\n    Eigen::Vector3d expected;\n\n    Frame f1 = create_frame();\n    f1->position() << 1, 1, 1;\n    f1->set_attitude({0,90*DEG2RAD,90*DEG2RAD});\n\n    Transform t = transform(nullptr, f1);\n\n    expected << 0, 0, 0;\n    CHECK(t.apply_vector({0,0,0}).isApprox(expected));\n\n    expected << 0, 0, -1;\n    CHECK(t.apply_vector({1,0,0}).isApprox(expected));\n\n    expected << -1, 0, 0;\n    CHECK(t.apply_vector({0,1,0}).isApprox(expected));\n\n    expected << 0, 1, 0;\n    CHECK(t.apply_vector({0,0,1}).isApprox(expected));\n}\n\nTEST_CASE(\"Single frame wrench\"){\n    using namespace dynkin;\n    Eigen::Vector6d expected, wrench;\n\n    Frame f1 = create_frame();\n    f1->position() << 1, 1, 1;\n    f1->set_attitude({0,90*DEG2RAD,90*DEG2RAD});\n\n    Transform t = transform(nullptr, f1);\n\n    expected << 0, 0, -1, -1, 1, 0;\n    wrench << 1, 0, 0, 0, 0, 0;\n    CHECK(t.apply_wrench(wrench).isApprox(expected));\n}\n\nTEST_CASE(\"Single frame HTM inverse\"){\n    using namespace dynkin;\n\n    Frame f1 = create_frame();\n    f1->position() << 124,-343,-13;\n    f1->set_attitude({27*DEG2RAD,49*DEG2RAD,62*DEG2RAD});\n\n    Transform t = transform(nullptr, f1);\n    Transform t_ = transform(f1, nullptr);\n\n    CHECK(t.HTM.isApprox(t_.inverse().HTM));\n}\n\nTEST_CASE(\"Single frame velocity\"){\n    using namespace dynkin;\n    Eigen::Vector6d expected;\n\n    Frame f1 = create_frame();\n    f1->position() << 1, 1, 1;\n    f1->set_attitude({0,90*DEG2RAD,90*DEG2RAD});\n    f1->linear_velocity() << 1, 0, 0;\n    f1->angular_velocity() << 0, 0, 1;\n\n    expected << 1, 0, 0, 0, 0, 1;\n    CHECK(f1->get_twist().isApprox(expected));\n}\n\nTEST_CASE(\"Chained frame velocity\"){\n    using namespace dynkin;\n    Eigen::Vector6d expected;\n\n    Frame f1 = create_frame();\n    f1->set_attitude({0,0,90*DEG2RAD});\n    f1->angular_velocity() << 0, 0, 1;\n\n    Frame f2 = f1->create_child();\n    f2->position() << 1, 1, 0;\n    f2->linear_velocity() << 1, 0, 0;\n    f2->angular_velocity() << 1, 0, 0;\n\n    expected << 0, 1, 0, 1, 0, 1;\n    CHECK(f2->get_twist().isApprox(expected));\n}\n\nTEST_CASE(\"Test inertia constructor\"){\n    using namespace dynkin;\n    using namespace dynkin::rigidbody;\n    CHECK_THROWS_AS(generalized_inertia_matrix(-1, {1, 1, 1}), std::invalid_argument);\n    CHECK_THROWS_AS(generalized_inertia_matrix(1, {-1, 1, 1}), std::invalid_argument);\n\n    Eigen::Matrix6d expected = Eigen::Matrix6d::Identity();\n\n    CHECK(generalized_inertia_matrix(1, {1,1,1}).isApprox(expected));\n}\n\nTEST_CASE(\"Test generalized coordinates\"){\n    using namespace dynkin;\n    using namespace dynkin::rigidbody;\n\n    RigidBody rb = RigidBody(generalized_inertia_matrix(1, {1,1,1}));\n    rb.origin->position() << 1,2,3;\n    rb.origin->set_attitude({0,1,1});\n    Eigen::Vector6d pose = rb.generalized_coordinates();\n\n    Eigen::Vector6d expected;\n    expected << 1,2,3,0,1,1;\n\n    CHECK(pose.isApprox(expected));\n}\n\nTEST_CASE(\"Test generalized velocities\"){\n    using namespace dynkin;\n    using namespace dynkin::rigidbody;\n\n    RigidBody rb = RigidBody(generalized_inertia_matrix(1, {1,1,1}));\n    rb.origin->position() << 1,1,1;\n    rb.origin->set_attitude({M_PI_2, 0, M_PI_2});\n    rb.origin->linear_velocity() << 1, 2, 3;\n    rb.origin->angular_velocity() << 0, 0, 1;\n    Eigen::Vector6d vel = rb.generalized_velocities();\n\n    Eigen::Vector6d expected;\n    expected << 3, 1, 2, 0, -1, 0;\n\n    CHECK(vel.isApprox(expected));\n}\n\nTEST_CASE(\"Test Coriolis-Centripetal acceleration with CoG offset\"){\n    using namespace dynkin;\n    using namespace dynkin::rigidbody;\n\n    RigidBody rb = RigidBody(\n        generalized_inertia_matrix(1, {1,1,1}),\n        {1, 0, 0}\n    );\n    rb.origin->angular_velocity() << 0, 0, 1;\n\n    Eigen::Vector6d expected;\n    expected << 1, 0, 0, 0, 0, 0;\n\n    CHECK_EQ(rb.acceleration(Eigen::Vector6d::Zero()), expected);\n}\n\nTEST_CASE(\"Test Coriolis-Centripetal acceleration due to linear velocity\"){\n    using namespace dynkin;\n    using namespace dynkin::rigidbody;\n\n    RigidBody rb = RigidBody(generalized_inertia_matrix(1, {1,1,1}));\n    rb.origin->linear_velocity() << 1, 0, 0;\n    rb.origin->angular_velocity() << 0, 0, 1;\n\n    Eigen::Vector6d expected;\n    expected << 0, -1, 0, 0, 0, 0;\n\n    CHECK_EQ(rb.acceleration(Eigen::Vector6d::Zero()), expected);\n}\n\nTEST_CASE(\"Test acceleration -> wrench\"){\n    using namespace dynkin;\n    using namespace dynkin::rigidbody;\n\n    RigidBody rb = RigidBody(generalized_inertia_matrix(1, {1,1,1}));\n    Eigen::Vector6d wrench = Eigen::Vector6d::Ones();\n    Eigen::Vector6d acc = rb.acceleration(wrench);\n\n    CHECK_EQ(acc, Eigen::Vector6d::Ones());\n\n\n    rb.CoG->position() << 1, 0, 0;\n    acc = rb.acceleration(wrench);\n    Eigen::Vector6d expected;\n    expected << 1, 1, 3, 1, 2, 0;\n\n    CHECK_EQ(acc, expected);\n\n\n    Eigen::Vector6d f = rb.wrench(acc);\n    CHECK_EQ(wrench, f);\n\n}\n\nTEST_CASE(\"Test wrench -> acceleration\"){\n    using namespace dynkin;\n    using namespace dynkin::rigidbody;\n\n    RigidBody rb = RigidBody(generalized_inertia_matrix(1, {1,1,1}));\n    Eigen::Vector6d acc = Eigen::Vector6d::Ones();\n    Eigen::Vector6d wrench = rb.wrench(acc);\n\n    CHECK_EQ(wrench, Eigen::Vector6d::Ones());\n\n\n    rb.CoG->position() << 1, 0, 0;\n    wrench = rb.wrench(acc);\n    Eigen::Vector6d expected;\n    expected << 1, 2, 0, 1, 1, 3;\n\n    CHECK_EQ(wrench, expected);\n\n\n    Eigen::Vector6d a = rb.acceleration(wrench);\n    CHECK_EQ(acc, a);\n\n}", "meta": {"hexsha": "0f40f341a8eff2639b5612583d17dd7d1964b368", "size": 6614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tests.cpp", "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": "test/tests.cpp", "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": "test/tests.cpp", "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": 26.246031746, "max_line_length": 86, "alphanum_fraction": 0.6419715754, "num_tokens": 2132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5604924261542126}}
{"text": "#include \"generate_edges.hpp\"\n#include \"partial_shuffle.hpp\"\n#include <algorithm>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n#include <random>\n#include <unordered_set>\n\nnamespace {\n\nstruct indexed_vec2 {\n    indexed_vec2(size_t index, const sssp::vec2& pos) : index(index), x(pos.x), y(pos.y) {}\n    size_t index;\n    double x;\n    double y;\n};\n\n} // namespace\n\nBOOST_GEOMETRY_REGISTER_POINT_2D(indexed_vec2, double, boost::geometry::cs::cartesian, x, y)\n\nvoid sssp::generate_uniform_edges(int seed,\n                                  double edge_probability,\n                                  const edge_cost_fn& edge_cost,\n                                  graph& graph,\n                                  const node_map<vec2>& positions) {\n    std::mt19937 rng(seed);\n\n#if 0\n    // This is the naive n*(n-1) steps algorithm. Each possible edge is considered\n    // using a simple Bernulli(p) distribution.\n    std::bernoulli_distribution allow_edge(edge_probability);\n    for (size_t source = 0; source < graph.node_count(); ++source) {\n        for (size_t destination = 0; destination < graph.node_count(); ++destination) {\n            if (destination != source && allow_edge(rng)) {\n                graph.add_edge(source, destination, edge_cost(line(positions[source], positions[destination])));\n            }\n        }\n    }\n#else\n    // An more efficient variant is to draw for each node k ~ Binom(n-1, p), and then\n    // generate edges to k random other nodes.\n    std::binomial_distribution<size_t> edge_count_dist(graph.node_count() - 1, edge_probability);\n    node_map<size_t> destinations = graph.make_node_map([](size_t i) { return i; });\n    for (size_t source = 0; source < graph.node_count(); ++source) {\n        size_t edge_count = edge_count_dist(rng);\n        partial_shuffle(destinations.begin(), destinations.begin() + edge_count + 1, destinations.end(), rng);\n        for (size_t i = 0; i < edge_count; ++i) {\n            size_t destination;\n            if (destinations[i] == source) {\n                // Note that I shuffled k+1 elements above, for exactly this case. If one of the\n                // randomly chosen edges is the source itself I use the (k+1)th element.\n                destination = destinations[edge_count];\n            } else {\n                destination = destinations[i];\n            }\n            graph.add_edge(source, destination, edge_cost(line(positions[source], positions[destination])));\n        }\n    }\n#endif\n}\n\nvoid sssp::generate_planar_edges(int seed,\n                                 double edge_probability,\n                                 const edge_cost_fn& edge_cost,\n                                 graph& graph,\n                                 const node_map<vec2>& positions) {\n    using namespace boost::geometry;\n\n    std::mt19937 rng(seed);\n    std::binomial_distribution<size_t> edge_count_dist(graph.node_count() - 1, edge_probability);\n\n    boost::geometry::index::rtree<indexed_vec2, index::quadratic<16>> points;\n    for (size_t i = 0; i < positions.size(); ++i) {\n        points.insert(indexed_vec2(i, positions[i]));\n    }\n\n    boost::geometry::index::rtree<line, index::quadratic<16>> lines;\n    std::vector<indexed_vec2> result;\n\n    for (size_t source = 0; source < graph.node_count(); ++source) {\n        int edge_count = static_cast<int>(edge_count_dist(rng));\n        if (edge_count > 0) {\n            result.clear();\n            // I find the 2 * edge_count closest nodes and pick edge_count random from them.\n            points.query(index::nearest(indexed_vec2(-1, positions[source]), edge_count * 2),\n                         std::back_inserter(result));\n            std::shuffle(result.begin(), result.end(), rng);\n            int done = 0;\n            for (const auto& dest : result) {\n                if (done >= edge_count) {\n                    break;\n                }\n                if (dest.index == source) {\n                    continue;\n                }\n                line candidate(positions[source], positions[dest.index]);\n                auto line_endings_unequal = [&](const line& l) {\n                    return l.start != candidate.start && l.end != candidate.start && l.start != candidate.end &&\n                           l.end != candidate.end;\n                };\n                if (lines.qbegin(index::intersects(candidate) && index::satisfies(line_endings_unequal)) ==\n                    lines.qend()) {\n                    graph.add_edge(source, dest.index, edge_cost(candidate));\n                    lines.insert(candidate);\n                    done += 1;\n                }\n            }\n        }\n    }\n}\n\nint sssp::y_bucket(int layers, double y) {\n    BOOST_ASSERT(layers >= 1);\n    BOOST_ASSERT(0.0 <= y && y <= 1.0);\n    // The std::min is just for the rare case that some y is exactly 1.\n    return std::min(static_cast<int>(std::floor(y * layers)), layers - 1);\n}\n\nvoid sssp::generate_layered_edges(int seed,\n                                  double edge_probability,\n                                  int layers,\n                                  const edge_cost_fn& edge_cost,\n                                  graph& graph,\n                                  const node_map<vec2>& positions) {\n    std::mt19937 rng(seed);\n\n    std::vector<std::vector<size_t>> buckets(layers);\n    for (size_t n = 0; n < graph.node_count(); ++n) {\n        buckets[y_bucket(layers, positions[n].y)].emplace_back(n);\n    }\n\n    for (size_t source = 0; source < graph.node_count(); ++source) {\n        std::vector<size_t> destinations;\n        int source_bucket = y_bucket(layers, positions[source].y);\n        if (source_bucket > 0) {\n            destinations.insert(\n                destinations.end(), buckets[source_bucket - 1].begin(), buckets[source_bucket - 1].end());\n        }\n        if (source_bucket < layers - 1) {\n            destinations.insert(\n                destinations.end(), buckets[source_bucket + 1].begin(), buckets[source_bucket + 1].end());\n        }\n        size_t edge_count = std::binomial_distribution<size_t>(destinations.size(), edge_probability)(rng);\n        partial_shuffle(destinations.begin(), destinations.begin() + edge_count, destinations.end(), rng);\n        for (size_t i = 0; i < edge_count; ++i) {\n            graph.add_edge(source, destinations[i], edge_cost(line(positions[source], positions[destinations[i]])));\n        }\n    }\n}\n\nvoid sssp::generate_kronecker_graph(int seed,\n                                    std::vector<double> matrix,\n                                    int k,\n                                    const edge_cost_fn& edge_cost,\n                                    graph& graph,\n                                    node_map<vec2>& positions) {\n    std::mt19937 rng(seed);\n\n    size_t start_size = 1;\n    while (start_size * start_size != matrix.size()) {\n        BOOST_ASSERT(start_size * start_size < matrix.size());\n        start_size += 1;\n    }\n\n    size_t final_size = 1;\n    for (int i = 0; i < k; ++i) {\n        final_size *= start_size;\n    }\n\n    positions.resize(final_size, vec2(0.0, 0.0));\n    for (size_t n = 0; n < final_size; ++n) {\n        graph.add_node();\n    }\n\n    std::vector<double> matrix_prefix_sum(matrix.size());\n    matrix_prefix_sum[0] = matrix[0];\n    for (int i = 1; i < matrix.size(); ++i) {\n        matrix_prefix_sum[i] = matrix_prefix_sum[i - 1] + matrix[i];\n    }\n\n    // The matrix can be interpret as parameters of a poisson binomial distribution\n    // The Kronecker product multiplies the expected values:\n    // Consider: M = [a b; c d] and M' = [a' b'; c' d'].\n    // The Kronecker product leads to [aM' bM'; cM' dM'], therefore the new sum is\n    // sum(aM') + sum(bM') + sum(cM') + sum(dM') = (a + b + c + d) * sum(M') = sum(M) * sum(M').\n    double edges_expected_value = std::pow(matrix_prefix_sum.back(), k);\n    // Now the poisson bionmial distribution can be apprximated well by a poisson distribution if\n    // the probabilites are very low (this is given here due to the nature of potentiation of lots of\n    // probabilities).\n    size_t edges = std::poisson_distribution<size_t>(edges_expected_value)(rng);\n\n    std::uniform_real_distribution<double> cell_dist(0.0, matrix_prefix_sum.back());\n    std::unordered_set<size_t> used_cells;\n    int tries = 0;\n    for (size_t e = 0; e < edges; ++e) {\n        // Sample the cell for the edge\n        size_t cell = 0;\n        size_t granularity = 1;\n        for (int i = 0; i < k; ++i) {\n            double value = cell_dist(rng);\n            size_t index = std::distance(matrix_prefix_sum.begin(),\n                                         std::lower_bound(matrix_prefix_sum.begin(), matrix_prefix_sum.end(), value));\n            if (index == matrix_prefix_sum.size()) {\n                // This should not happen, but could happen due to double inaccuracies\n                index = matrix_prefix_sum.size() - 1;\n            }\n            cell += index * granularity;\n            granularity *= start_size * start_size;\n        }\n        size_t u = cell / final_size;\n        size_t v = cell % final_size;\n        if (u == v || used_cells.find(cell) != used_cells.end()) {\n            tries += 1;\n            if (tries < 30) {\n                // Try again\n                e -= 1;\n                continue;\n            } else {\n                // Throw this edge away\n                continue;\n            }\n        }\n        tries = 0;\n        used_cells.insert(cell);\n        graph.add_edge(u, v, edge_cost(line(vec2(0.0, 0.0), vec2(0.0, 0.0))));\n    }\n}\n", "meta": {"hexsha": "eed874ab4d07304dcda2b372648d414ba3649606", "size": 9570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generate_edges.cpp", "max_stars_repo_name": "kaini/sssp-simulation", "max_stars_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "generate_edges.cpp", "max_issues_repo_name": "kaini/sssp-simulation", "max_issues_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_issues_repo_licenses": ["MIT"], "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_edges.cpp", "max_forks_repo_name": "kaini/sssp-simulation", "max_forks_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_forks_repo_licenses": ["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.7903930131, "max_line_length": 118, "alphanum_fraction": 0.5597701149, "num_tokens": 2188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5604924001777996}}
{"text": "#include <Eigen/Dense>\n#include <algorithm>\n#include <vector>\n\nint atom(int ao_index);\nint indexOf(std::vector<std::string> my_list, std::string element);\nbool list_contains(std::vector<std::string>  my_list, std::string element);\nstd::string orb(int ao_index, std::vector<std::string> orbital_types);\nint ao_index(int atom_p, std::string orb_p, std::vector<std::string>  orbital_types);\nfloat chi_on_atom(std::string o1, std::string o2, std::string o3, std::vector<std::string> p_orbitals,double dipole);\nEigen::MatrixXd fast_fock_matrix(Eigen::MatrixXd hamiltonian, Eigen::MatrixXd interaction, Eigen::MatrixXd rho,double dipole);\nint main(void);\n", "meta": {"hexsha": "3e73c7607ac6c588a7f7cb631a6603f35cb98984", "size": 649, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fock_fast/fock_fast.hpp", "max_stars_repo_name": "MolSSI-Education/qm_2019_sss_6", "max_stars_repo_head_hexsha": "48b2a8229bd09ab61f7e50530a39acfc081f47b1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fock_fast/fock_fast.hpp", "max_issues_repo_name": "MolSSI-Education/qm_2019_sss_6", "max_issues_repo_head_hexsha": "48b2a8229bd09ab61f7e50530a39acfc081f47b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T20:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-31T05:09:01.000Z", "max_forks_repo_path": "fock_fast/fock_fast.hpp", "max_forks_repo_name": "MolSSI-Education/qm_2019_sss_6", "max_forks_repo_head_hexsha": "48b2a8229bd09ab61f7e50530a39acfc081f47b1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2019-07-23T20:14:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-31T03:47:36.000Z", "avg_line_length": 49.9230769231, "max_line_length": 126, "alphanum_fraction": 0.7657935285, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5604923895974515}}
{"text": "#pragma once\n#include <armadillo>\n\nclass LinearRegression\n{\nprotected:\n    arma::mat X;\n    arma::vec Y, coef;\n    bool fit_intercept;\n\npublic:\n    LinearRegression(arma::mat &x, arma::vec &y);\n    void fit(bool fit_intercept);\n    arma::vec predict(arma::mat &X_pred);\n    arma::vec getCoef() const { return coef; }\n    //~LinearRegression();\n};\n", "meta": {"hexsha": "c5be43d687517a582c0a1a0384b9a5c2bef6a05e", "size": 347, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/project/LinearRegression.hpp", "max_stars_repo_name": "haruspex-machine/ts-forecast-cpp", "max_stars_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-09T06:27:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T06:27:15.000Z", "max_issues_repo_path": "include/project/LinearRegression.hpp", "max_issues_repo_name": "bklimowski/ts-forecast-cpp", "max_issues_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/project/LinearRegression.hpp", "max_forks_repo_name": "bklimowski/ts-forecast-cpp", "max_forks_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2777777778, "max_line_length": 49, "alphanum_fraction": 0.6541786744, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5604906305889604}}
{"text": "//\n// Created by michaelpollind on 1/11/18.\n//\n\n#ifndef QSYS_SIMULATOR_H\n#define QSYS_SIMULATOR_H\n\n#include <Godot.hpp>\n#include <Reference.hpp>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <complex>\n#include <random>\n#include <vector>\n#include <map>\n\nclass Simulator : public godot::GodotScript<godot::Reference>{\n    GODOT_CLASS(Simulator)\n\nprivate:\n    Eigen::MatrixXcd _hamiltonian;\n    Eigen::MatrixXcd _propagator;\n    Eigen::VectorXcd _psi0;\n    Eigen::VectorXcd _currentState;\n    std::vector<double> _probabilityDensity;\n    void _setPropagator(Eigen::MatrixXcd arr);\n    double _time;\n    int _size;\n    int _result;\n    int _sampleProbabilityDensity();\n    Eigen::MatrixXcd _getPOVM(std::map<int, int>);\n    std::default_random_engine _gen;\n\npublic:\n    Simulator();\n    void _init();\n    void _setSize(const int size);\n    void _setHamiltonian(godot::PoolVector2Array arr);\n    void _setPsi0(godot::PoolVector2Array arr);\n    void _runOneStep(float delta);\n\tint _getCurrentStateSize();\n\tint _getPropagatorRows();\n\tint _getPropagatorCols();\n    float _getTime();\n\n    godot::String _getErrorMessage();\n    godot::PoolRealArray _getProbabilityDensity();\n    godot::PoolVector2Array _getHamiltonian();\n    godot::PoolVector2Array _getPsi0();\n    int _measure();\n    godot::PoolVector2Array _getCurrentState();\n    godot::PoolVector2Array _getPropagator();\n\n    static void _register_methods();\n};\n\n#endif //QSYS_SIMULATOR_H\n", "meta": {"hexsha": "88b07e4fe8bd939223ef02ebd8fcb7d8e6bc5919", "size": 1465, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "library/include/simulator.hpp", "max_stars_repo_name": "aarongrisez/Qsys", "max_stars_repo_head_hexsha": "c95cc5a997fd4afcbafef2b7eb994e80c4f6bd8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "library/include/simulator.hpp", "max_issues_repo_name": "aarongrisez/Qsys", "max_issues_repo_head_hexsha": "c95cc5a997fd4afcbafef2b7eb994e80c4f6bd8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-10-18T01:58:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-23T01:42:13.000Z", "max_forks_repo_path": "library/include/simulator.hpp", "max_forks_repo_name": "aarongrisez/Qsys", "max_forks_repo_head_hexsha": "c95cc5a997fd4afcbafef2b7eb994e80c4f6bd8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-11T04:29:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-12T19:48:52.000Z", "avg_line_length": 25.2586206897, "max_line_length": 62, "alphanum_fraction": 0.7290102389, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5604906247058093}}
{"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": "// Copyright Nick Thompson 2017.\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_TEST_MAIN\n\n#include <boost/test/unit_test.hpp>\n#include <boost/math/special_functions/legendre.hpp>\n#include <boost/math/special_functions/legendre_stieltjes.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\n\nusing boost::math::legendre_stieltjes;\nusing boost::math::legendre_p;\nusing boost::multiprecision::cpp_bin_float_quad;\n\n\ntemplate<class Real>\nvoid test_legendre_stieltjes()\n{\n    std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\n    using std::sqrt;\n    using std::abs;\n    using boost::math::constants::third;\n    using boost::math::constants::half;\n\n    Real tol = std::numeric_limits<Real>::epsilon();\n    legendre_stieltjes<Real> ls1(1);\n    legendre_stieltjes<Real> ls2(2);\n    legendre_stieltjes<Real> ls3(3);\n    legendre_stieltjes<Real> ls4(4);\n    legendre_stieltjes<Real> ls5(5);\n    legendre_stieltjes<Real> ls8(8);\n    Real x = -1;\n    while(x <= 1)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(ls1(x), x, tol);\n        BOOST_CHECK_CLOSE_FRACTION(ls1.prime(x), 1, tol);\n\n        Real p2 = legendre_p(2, x);\n        BOOST_CHECK_CLOSE_FRACTION(ls2(x), p2 - 2/static_cast<Real>(5), tol);\n        BOOST_CHECK_CLOSE_FRACTION(ls2.prime(x), 3*x, tol);\n\n        Real p3 = legendre_p(3, x);\n        BOOST_CHECK_CLOSE_FRACTION(ls3(x), p3 - 9*x/static_cast<Real>(14), 100*tol);\n        BOOST_CHECK_CLOSE_FRACTION(ls3.prime(x), 15*x*x*half<Real>() -3*half<Real>()-9/static_cast<Real>(14), 100*tol);\n\n        Real p4 = legendre_p(4, x);\n        //-20P_2(x)/27 + 14P_0(x)/891\n        Real E4 = p4 - 20*p2/static_cast<Real>(27) + 14/static_cast<Real>(891);\n        BOOST_CHECK_CLOSE_FRACTION(ls4(x), E4, 250*tol);\n        BOOST_CHECK_CLOSE_FRACTION(ls4.prime(x), 35*x*(9*x*x -5)/static_cast<Real>(18), 250*tol);\n\n        Real p5 = legendre_p(5, x);\n        Real E5 = p5 - 35*p3/static_cast<Real>(44) + 135*x/static_cast<Real>(12584);\n        BOOST_CHECK_CLOSE_FRACTION(ls5(x), E5, 29000*tol);\n        Real E5prime = (315*(123 + 143*x*x*(11*x*x-9)))/static_cast<Real>(12584);\n        BOOST_CHECK_CLOSE_FRACTION(ls5.prime(x), E5prime, 29000*tol);\n        x += 1/static_cast<Real>(1 << 9);\n    }\n\n    // Test norm:\n    // E_1 = x\n    Real expected_norm_sq = 2*third<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(expected_norm_sq, ls1.norm_sq(), tol);\n\n    // E_2 = P[sub 2](x) - 2P[sup 0](x)/5\n    expected_norm_sq = 2/static_cast<Real>(5) + 8/static_cast<Real>(25);\n    BOOST_CHECK_CLOSE_FRACTION(expected_norm_sq, ls2.norm_sq(), tol);\n\n    // E_3 = P[sub 3](x) - 9P[sub 1]/14\n    expected_norm_sq = 2/static_cast<Real>(7) + 9*9*2*third<Real>()/static_cast<Real>(14*14);\n    BOOST_CHECK_CLOSE_FRACTION(expected_norm_sq, ls3.norm_sq(), tol);\n\n    // E_4 = P[sub 4](x) -20P[sub 2](x)/27 + 14P[sub 0](x)/891\n    expected_norm_sq = static_cast<Real>(2)/static_cast<Real>(9) + static_cast<Real>(20*20*2)/static_cast<Real>(27*27*5) + 14*14*2/static_cast<Real>(891*891);\n    BOOST_CHECK_CLOSE_FRACTION(expected_norm_sq, ls4.norm_sq(), tol);\n\n    // E_5 = P[sub 5](x) - 35P[sub 3](x)/44 + 135P[sub 1](x)/12584\n    expected_norm_sq = 2/static_cast<Real>(11) + (35*35/static_cast<Real>(44*44))*(2/static_cast<Real>(7)) + (135*135/static_cast<Real>(12584*12584))*2*third<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(expected_norm_sq, ls5.norm_sq(), tol);\n\n    // Only zero of E1 is 0:\n    std::vector<Real> zeros = ls1.zeros();\n    BOOST_CHECK(zeros.size() == 1);\n    BOOST_CHECK_SMALL(zeros[0], tol);\n    BOOST_CHECK_SMALL(ls1(zeros[0]), tol);\n\n    zeros = ls2.zeros();\n    BOOST_CHECK(zeros.size() == 1);\n    BOOST_CHECK_CLOSE_FRACTION(zeros[0], sqrt(3/static_cast<Real>(5)), tol);\n    BOOST_CHECK_SMALL(ls2(zeros[0]), tol);\n\n    zeros = ls3.zeros();\n    BOOST_CHECK(zeros.size() == 2);\n    BOOST_CHECK_SMALL(zeros[0], tol);\n    BOOST_CHECK_CLOSE_FRACTION(zeros[1], sqrt(6/static_cast<Real>(7)), tol);\n\n\n    zeros = ls4.zeros();\n    BOOST_CHECK(zeros.size() == 2);\n    Real expected = sqrt( (55 - 2*sqrt(static_cast<Real>(330)))/static_cast<Real>(11) )/static_cast<Real>(3);\n    BOOST_CHECK_CLOSE_FRACTION(zeros[0], expected, tol);\n\n    expected = sqrt( (55 + 2*sqrt(static_cast<Real>(330)))/static_cast<Real>(11) )/static_cast<Real>(3);\n    BOOST_CHECK_CLOSE_FRACTION(zeros[1], expected, 10*tol);\n\n\n    zeros = ls5.zeros();\n    BOOST_CHECK(zeros.size() == 3);\n    BOOST_CHECK_SMALL(zeros[0], tol);\n\n    expected = sqrt( ( 195 - sqrt(static_cast<Real>(6045)) )/static_cast<Real>(286));\n    BOOST_CHECK_CLOSE_FRACTION(zeros[1], expected, tol);\n\n    expected = sqrt( ( 195 + sqrt(static_cast<Real>(6045)) )/static_cast<Real>(286));\n    BOOST_CHECK_CLOSE_FRACTION(zeros[2], expected, tol);\n\n\n    for (size_t i = 6; i < 50; ++i)\n    {\n        legendre_stieltjes<Real> En(i);\n        zeros = En.zeros();\n        for(auto const & zero : zeros)\n        {\n            BOOST_CHECK_SMALL(En(zero), 50*tol);\n        }\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(LegendreStieltjesZeros)\n{\n    test_legendre_stieltjes<double>();\n    test_legendre_stieltjes<long double>();\n    test_legendre_stieltjes<cpp_bin_float_quad>();\n    //test_legendre_stieltjes<boost::multiprecision::cpp_bin_float_100>();\n}\n", "meta": {"hexsha": "80e6e832c190e95a065b54a81bc86ded551734d2", "size": 5365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/math/test/legendre_stieltjes_test.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "deps/src/boost_1_65_1/libs/math/test/legendre_stieltjes_test.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "deps/src/boost_1_65_1/libs/math/test/legendre_stieltjes_test.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 37.7816901408, "max_line_length": 166, "alphanum_fraction": 0.6637465051, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5604906115589284}}
{"text": "#include <emp-tool-tg/emp-tool/emp-tool.h>\n#include <boost/program_options.hpp>\n#include <boost/format.hpp>\n#include \"tinygarble/program_interface.h\"\n#include \"tinygarble/program_interface_sh.h\"\n#include \"tinygarble/TinyGarble_config.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nvoid millionaire(auto TGPI){\t\n\n\tuint64_t bit_width = 64;\n    int64_t a = 0, b = 0;\n\t\n\tcout << \"Input wealth: \";\n    if (TGPI->party == ALICE){\n        cin >> a;\n        cout << \"ALICE's wealth: $\" << a << endl;\n    }\n    else{\n        cin >> b;\n        cout << \"BOB's wealth: $\" << b << endl;\n    }\n    \n    auto a_x = TGPI->TG_int_init(ALICE, bit_width, a);\n    auto b_x = TGPI->TG_int_init(BOB, bit_width, b);\n\n    TGPI->gen_input_labels();\n\n    TGPI->retrieve_input_labels(a_x, ALICE, bit_width);\n    TGPI->retrieve_input_labels(b_x, BOB, bit_width);\n\n    auto res_x = TGPI->TG_int(1);\n    TGPI->lt(res_x, a_x, b_x, bit_width);\n    int64_t res = TGPI->reveal(res_x, 1, false);\n\n#if !SEC_SH\n    if (TGPI->party == BOB) //authenticated garbling allows only evaluator to compute the result\n#endif\n        if (res == 1) cout << \"BOB is richer\" << endl;\n        else cout << \"ALICE is richer\" << endl;\n\n\tTGPI->clear_TG_int(a_x);\n\tTGPI->clear_TG_int(b_x);\n\tTGPI->clear_TG_int(res_x);\n\t\n\tdelete TGPI;\n}\n\nint main(int argc, char** argv) {\n\tint party = 1, port = 1234;\n\tstring netlist_address;\n\tstring server_ip;\n\t\n\tpo::options_description desc{\"Yao's Millionair's Problem \\nAllowed options\"};\n\tdesc.add_options()  //\n\t(\"help,h\", \"produce help message\")  //\n\t(\"party,k\", po::value<int>(&party)->default_value(1), \"party id: 1 for garbler, 2 for evaluator\")  //\n\t(\"port,p\", po::value<int>(&port)->default_value(1234), \"socket port\")  //\n\t(\"server_ip,s\", po::value<string>(&server_ip)->default_value(\"127.0.0.1\"), \"server's IP.\")\n\t(\"sh\", \"semi-honest setting (default is malicious)\");\n\t\n\tpo::variables_map vm;\n\ttry {\n\t\tpo::parsed_options parsed = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run();\n\t\tpo::store(parsed, vm);\n\t\tif (vm.count(\"help\")) {\n\t\t\tcout << desc << endl;\n\t\t\treturn 0;\n\t\t}\n\t\tpo::notify(vm);\n\t}catch (po::error& e) {\n\t\tcout << \"ERROR: \" << e.what() << endl << endl;\n\t\tcout << desc << endl;\n\t\treturn -1;\n\t}\n\t\t\n\tNetIO* io = new NetIO(party==ALICE ? nullptr:server_ip.c_str(), port, true);\n\tio->set_nodelay();\n\t\n\tTinyGarblePI_SH* TGPI_SH;\n\tTinyGarblePI* TGPI; \n\t\n\tif (vm.count(\"sh\")){\n\t\tcout << \"testing program interface in semi-honest setting\" << endl;\n\t\tTGPI_SH = new TinyGarblePI_SH(io, party);\n\t\tio->flush();\n\t\tmillionaire(TGPI_SH);\t\t\n\t}\n\telse {\n\t\tcout << \"Millionair's Problem in malicious setting\" << endl;\n\t\tTGPI = new TinyGarblePI(io, party, 192, 64);\n\t\tio->flush();\n\t\tmillionaire(TGPI);\n\t}\n\t\n\tdelete io;\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "3c22c28c3c6c91678fa467225dcd51fea7d0ad4c", "size": 2761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exec/millionaire.cpp", "max_stars_repo_name": "zghodsi/TinyGarble2.0", "max_stars_repo_head_hexsha": "aa0c8a56848ee3f6d2354988028ec715d5e73e25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exec/millionaire.cpp", "max_issues_repo_name": "zghodsi/TinyGarble2.0", "max_issues_repo_head_hexsha": "aa0c8a56848ee3f6d2354988028ec715d5e73e25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exec/millionaire.cpp", "max_forks_repo_name": "zghodsi/TinyGarble2.0", "max_forks_repo_head_hexsha": "aa0c8a56848ee3f6d2354988028ec715d5e73e25", "max_forks_repo_licenses": ["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.068627451, "max_line_length": 107, "alphanum_fraction": 0.6396233249, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5604883437376771}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE TestExtrema\n#include <boost/test/unit_test.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/algorithm/copy.hpp>\n#include <boost/compute/algorithm/iota.hpp>\n#include <boost/compute/algorithm/max_element.hpp>\n#include <boost/compute/algorithm/min_element.hpp>\n#include <boost/compute/algorithm/minmax_element.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/iterator/transform_iterator.hpp>\n\n#include \"context_setup.hpp\"\n\nBOOST_AUTO_TEST_CASE(int_min_max)\n{\n    int data[] = { 9, 15, 1, 4 };\n    boost::compute::vector<int> vector(data, data + 4);\n\n    boost::compute::vector<int>::iterator min_iter =\n        boost::compute::min_element(vector.begin(), vector.end());\n    BOOST_CHECK(min_iter == vector.begin() + 2);\n    BOOST_CHECK_EQUAL(*min_iter, 1);\n\n    boost::compute::vector<int>::iterator max_iter =\n        boost::compute::max_element(vector.begin(), vector.end());\n    BOOST_CHECK(max_iter == vector.begin() + 1);\n    BOOST_CHECK_EQUAL(*max_iter, 15);\n}\n\nBOOST_AUTO_TEST_CASE(iota_min_max)\n{\n    boost::compute::vector<int> vector(5000);\n\n    // fill with 0 -> 4999\n    boost::compute::iota(vector.begin(), vector.end(), 0);\n\n    boost::compute::vector<int>::iterator min_iter =\n        boost::compute::min_element(vector.begin(), vector.end());\n    BOOST_CHECK(min_iter == vector.begin());\n    BOOST_CHECK_EQUAL(*min_iter, 0);\n\n    boost::compute::vector<int>::iterator max_iter =\n        boost::compute::max_element(vector.begin(), vector.end());\n    BOOST_CHECK(max_iter == vector.end() - 1);\n    BOOST_CHECK_EQUAL(*max_iter, 4999);\n\n    min_iter =\n        boost::compute::min_element(\n            vector.begin() + 1000,\n            vector.end() - 1000\n        );\n    BOOST_CHECK(min_iter == vector.begin() + 1000);\n    BOOST_CHECK_EQUAL(*min_iter, 1000);\n\n    max_iter =\n        boost::compute::max_element(\n            vector.begin() + 1000,\n            vector.end() - 1000\n        );\n    BOOST_CHECK(max_iter == vector.begin() + 3999);\n    BOOST_CHECK_EQUAL(*max_iter, 3999);\n\n    // fill with -2500 -> 2499\n    boost::compute::iota(vector.begin(), vector.end(), -2500);\n    min_iter =\n        boost::compute::min_element(vector.begin(), vector.end());\n    BOOST_CHECK(min_iter == vector.begin());\n    BOOST_CHECK_EQUAL(*min_iter, -2500);\n\n    max_iter =\n        boost::compute::max_element(vector.begin(), vector.end());\n    BOOST_CHECK(max_iter == vector.end() - 1);\n    BOOST_CHECK_EQUAL(*max_iter, 2499);\n}\n\n// uses max_element() and length() to find the longest 2d vector\nBOOST_AUTO_TEST_CASE(max_vector_length)\n{\n    float data[] = { -1.5f, 3.2f,\n                     10.0f, 0.0f,\n                     -4.2f, 2.0f,\n                     0.0f, 0.5f,\n                     1.9f, 1.9f };\n    boost::compute::vector<boost::compute::float2_> vector(\n        reinterpret_cast<boost::compute::float2_ *>(data),\n        reinterpret_cast<boost::compute::float2_ *>(data) + 5\n    );\n\n    // find length of the longest vector\n    typedef boost::compute::transform_iterator<\n                boost::compute::vector<boost::compute::float2_>::iterator,\n                boost::compute::length<boost::compute::float2_>\n            > length_transform_iter;\n\n    length_transform_iter max_iter =\n        boost::compute::max_element(\n            boost::compute::make_transform_iterator(\n                vector.begin(),\n                boost::compute::length<boost::compute::float2_>()\n            ),\n            boost::compute::make_transform_iterator(\n                vector.end(),\n                boost::compute::length<boost::compute::float2_>()\n            )\n        );\n    BOOST_CHECK(\n        max_iter == boost::compute::make_transform_iterator(\n                        vector.begin() + 1,\n                        boost::compute::length<boost::compute::float2_>()\n                    )\n    );\n    BOOST_CHECK(max_iter.base() == vector.begin() + 1);\n    BOOST_CHECK_EQUAL(*max_iter, float(10.0));\n\n    // find length of the shortest vector\n    length_transform_iter min_iter =\n        boost::compute::min_element(\n            boost::compute::make_transform_iterator(\n                vector.begin(),\n                boost::compute::length<boost::compute::float2_>()\n            ),\n            boost::compute::make_transform_iterator(\n                vector.end(),\n                boost::compute::length<boost::compute::float2_>()\n            )\n        );\n    BOOST_CHECK(\n        min_iter == boost::compute::make_transform_iterator(\n                        vector.begin() + 3,\n                        boost::compute::length<boost::compute::float2_>()\n                    )\n    );\n    BOOST_CHECK(min_iter.base() == vector.begin() + 3);\n    BOOST_CHECK_EQUAL(*min_iter, float(0.5));\n}\n\n// uses max_element() and popcount() to find the value with the most 1 bits\nBOOST_AUTO_TEST_CASE(max_bits_set)\n{\n    using boost::compute::uint_;\n\n    uint_ data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    boost::compute::vector<uint_> vector(data, data + 10);\n\n    boost::compute::vector<uint_>::iterator iter =\n        boost::compute::max_element(\n            boost::compute::make_transform_iterator(\n                vector.begin(),\n                boost::compute::popcount<uint_>()\n            ),\n            boost::compute::make_transform_iterator(\n                vector.end(),\n                boost::compute::popcount<uint_>()\n            )\n        ).base();\n\n    BOOST_CHECK(iter == vector.begin() + 7);\n    BOOST_CHECK_EQUAL(uint_(*iter), uint_(7));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a7cadbb9cf76cb5b4809306b29c7559a4ec7754d", "size": 6027, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_extrema.cpp", "max_stars_repo_name": "roshanr95/compute", "max_stars_repo_head_hexsha": "377e509acd16af466cdb133d70e2dcd525ec1a87", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_extrema.cpp", "max_issues_repo_name": "roshanr95/compute", "max_issues_repo_head_hexsha": "377e509acd16af466cdb133d70e2dcd525ec1a87", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_extrema.cpp", "max_forks_repo_name": "roshanr95/compute", "max_forks_repo_head_hexsha": "377e509acd16af466cdb133d70e2dcd525ec1a87", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-09T15:56:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-09T15:56:37.000Z", "avg_line_length": 34.6379310345, "max_line_length": 79, "alphanum_fraction": 0.5921685747, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.560488343737677}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#include <boost/compute/core.hpp>\n#include <boost/compute/closure.hpp>\n#include <boost/compute/algorithm/copy_if.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/random/default_random_engine.hpp>\n#include <boost/compute/random/uniform_int_distribution.hpp>\n#include <boost/compute/random/uniform_real_distribution.hpp>\n\n#include \"perf.hpp\"\n\nnamespace compute = boost::compute;\n\nvoid test_copy_if_odd(compute::command_queue &queue)\n{\n    // create input and output vectors on the device\n    const compute::context &context = queue.get_context();\n    compute::vector<int> input(PERF_N, context);\n    compute::vector<int> output(PERF_N, context);\n\n    // generate random numbers between 1 and 10\n    compute::default_random_engine rng(queue);\n    compute::uniform_int_distribution<int> d(1, 10);\n    d.generate(input.begin(), input.end(), rng, queue);\n\n    BOOST_COMPUTE_FUNCTION(bool, is_odd, (int x),\n    {\n        return x & 1;\n    });\n\n    perf_timer t;\n    for(size_t trial = 0; trial < PERF_TRIALS; trial++){\n        t.start();\n        compute::vector<int>::iterator i = compute::copy_if(\n            input.begin(), input.end(), output.begin(), is_odd, queue\n        );\n        queue.finish();\n        t.stop();\n\n        float ratio = float(std::distance(output.begin(), i)) / PERF_N;\n        if(PERF_N > 1000 && (ratio < 0.45f || ratio > 0.55f)){\n            std::cerr << \"error: ratio is \" << ratio << std::endl;\n            std::cerr << \"error: ratio should be around 45-55%\" << std::endl;\n        }\n    }\n    std::cout << \"time: \" << t.min_time() / 1e6 << \" ms\" << std::endl;\n}\n\nvoid test_copy_if_in_sphere(compute::command_queue &queue)\n{\n    using boost::compute::float4_;\n\n    // create input and output vectors on the device\n    const compute::context &context = queue.get_context();\n    compute::vector<float4_> input_points(PERF_N, context);\n    compute::vector<float4_> output_points(PERF_N, context);\n\n    // generate random numbers in a cube\n    float radius = 5.0f;\n    compute::default_random_engine rng(queue);\n    compute::uniform_real_distribution<float> d(-radius, +radius);\n    d.generate(\n        compute::make_buffer_iterator<float>(input_points.get_buffer(), 0),\n        compute::make_buffer_iterator<float>(input_points.get_buffer(), PERF_N * 4),\n        rng,\n        queue\n    );\n\n    // predicate which returns true if the point lies within the sphere\n    BOOST_COMPUTE_CLOSURE(bool, is_in_sphere, (float4_ point), (radius),\n    {\n        // ignore fourth component\n        point.w = 0;\n\n        return length(point) < radius;\n    });\n\n    perf_timer t;\n    for(size_t trial = 0; trial < PERF_TRIALS; trial++){\n        t.start();\n        compute::vector<float4_>::iterator i = compute::copy_if(\n            input_points.begin(),\n            input_points.end(),\n            output_points.begin(),\n            is_in_sphere,\n            queue\n        );\n        queue.finish();\n        t.stop();\n\n        float ratio = float(std::distance(output_points.begin(), i)) / PERF_N;\n        if(PERF_N > 1000 && (ratio < 0.5f || ratio > 0.6f)){\n            std::cerr << \"error: ratio is \" << ratio << std::endl;\n            std::cerr << \"error: ratio should be around 50-60%\" << std::endl;\n        }\n    }\n    std::cout << \"time: \" << t.min_time() / 1e6 << \" ms\" << std::endl;\n}\n\nint main(int argc, char *argv[])\n{\n    perf_parse_args(argc, argv);\n\n    // setup context and queue for the default device\n    boost::compute::device device = boost::compute::system::default_device();\n    boost::compute::context context(device);\n    boost::compute::command_queue queue(context, device);\n    std::cout << \"device: \" << device.name() << std::endl;\n\n    test_copy_if_odd(queue);\n\n    return 0;\n}\n", "meta": {"hexsha": "75be0c31955252239b2c22eaefcbbee2c14fb2ff", "size": 4179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perf/perf_copy_if.cpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "perf/perf_copy_if.cpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perf/perf_copy_if.cpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9756097561, "max_line_length": 84, "alphanum_fraction": 0.6094759512, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5604883392964484}}
{"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 \"exception.hh\"\n#include \"network.hh\"\n#include \"timer.hh\"\n\n#include <Eigen/Dense>\n#include <iostream>\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 = 4;\n\nvoid program_body( const unsigned int num_iterations, const float epsilon )\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  srand( 0 );\n\n  /* construct neural network on heap */\n  auto nn = make_unique<Network<float, batch_size, input_size, 4, 64, 1>>();\n  nn->initializeWeightsRandomly();\n\n  srand( 10 );\n  /* initialize inputs */\n  Matrix<float, batch_size, input_size> input = Matrix<float, batch_size, input_size>::Random();\n\n  /* forward prop */\n  nn->apply( input );\n\n  /* print */\n  const IOFormat CleanFmt( 4, 0, \", \", \"\\n\", \"[\", \"]\" );\n  cout << \"input:\" << endl << input.format( CleanFmt ) << endl << endl;\n  nn->print();\n\n  vector<unsigned int> gradientLayerNums;\n  vector<unsigned int> gradientWeightNums;\n\n  unsigned int numLayers = nn->getNumLayers();\n\n  for ( unsigned int layerNum = 0; layerNum < numLayers; layerNum++ ) {\n    cout << \"Layer \" << layerNum << \"\\n\";\n    const unsigned int input_size_ = nn->getLayerInputSize( layerNum );\n    const unsigned int output_size_ = nn->getLayerOutputSize( layerNum );\n    cout << \" input size: \" << input_size_ << \" -> \"\n         << \"output_size: \" << output_size_ << endl\n         << endl;\n\n    unsigned int numParams = nn->getNumParams( layerNum );\n    vector<float> gradients( numParams, 0 );\n\n    /* numerical gradient computation */\n    for ( unsigned int paramNum = 0; paramNum < numParams; paramNum++ ) {\n      float gradient = nn->calculateNumericalGradient( input, layerNum, paramNum, epsilon );\n      gradients[paramNum] = gradient;\n    }\n\n    cout << \"  weightGradients \";\n    for ( unsigned int paramNum = 0; paramNum < numParams; paramNum++ ) {\n      if ( paramNum % output_size_ == 0 )\n        cout << endl << \"   \";\n      if ( paramNum == input_size_ * output_size_ ) {\n        cout << endl;\n        cout << \"  biasGradients\" << endl << \"   \";\n      }\n      cout << gradients[paramNum] << \" \";\n    }\n    cout << endl << endl << endl;\n  }\n\n  // Code to generate random no. of such gradients\n  (void)num_iterations;\n  // for ( unsigned int i = 0; i < num_iterations; i++ ) {\n  //   unsigned int layerNum = rand() % numLayers;\n  //   gradientLayerNums.emplace_back( layerNum );\n  //   unsigned int numParams = nn->getNumParams( layerNum );\n  //   gradientWeightNums.emplace_back( rand() % numParams );\n  // }\n\n  // for ( unsigned int i = 0; i < num_iterations; i++ ) {\n  //   float gradient = nn->calculateNumericalGradient( input, gradientLayerNums[i], gradientWeightNums[i], epsilon\n  //   ); cout << \"Iteration \" << i << \":\\n\"\n  //        << \"  Layer \" << gradientLayerNums[i] << \"\\n\"\n  //        << \"  Weight \" << gradientWeightNums[i] << \"\\n\"\n  //        << \"  Gradient \" << gradient << \"\\n\\n\\n\\n\";\n  // }\n}\n\nint main( int argc, char* argv[] )\n{\n  try {\n    if ( argc <= 0 ) {\n      abort();\n    }\n\n    if ( argc != 3 ) {\n      cerr << \"Usage: \" << argv[0] << \" NUM_ITERATIONS EPSILON\\n\";\n      return EXIT_FAILURE;\n    }\n\n    program_body( stoi( argv[1] ), stof( argv[2] ) );\n\n    return EXIT_SUCCESS;\n  } catch ( const exception& e ) {\n    cerr << e.what() << \"\\n\";\n    return EXIT_FAILURE;\n  }\n}\n", "meta": {"hexsha": "5cc5ba7cb414d14d2cecbd5050be93864a21b3a4", "size": 3579, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/frontend/back_propagation_numerical.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/back_propagation_numerical.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/back_propagation_numerical.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": 30.5897435897, "max_line_length": 115, "alphanum_fraction": 0.6099469125, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6893056040203136, "lm_q1q2_score": 0.5603140037601302}}
{"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": "/* Boost libs/numeric/odeint/examples/openmp/lorenz_ensemble_simple.cpp\n\n Copyright 2013 Karsten Ahnert\n Copyright 2013 Mario Mulansky\n Copyright 2013 Pascal Germroth\n\n Parallelized Lorenz ensembles\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 <omp.h>\n#include <vector>\n#include <iostream>\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/external/openmp/openmp.hpp>\n#include \"point_type.hpp\"\n\nusing namespace std;\n\ntypedef vector<double> vector_type;\ntypedef point<double, 3> point_type;\ntypedef vector<point_type> state_type;\n\nconst double sigma = 10.0;\nconst double b = 8.0 / 3.0;\n\nstruct sys_func {\n    const vector_type &R;\n    sys_func( const vector_type &_R ) : R( _R ) { }\n\n    void operator()( const state_type &x , state_type &dxdt , double t ) const {\n        const size_t n = x.size();\n#       pragma omp parallel for\n        for(size_t i = 0 ; i < n ; i++) {\n            const point_type &xi = x[i];\n            point_type &dxdti = dxdt[i];\n            dxdti[0] = -sigma * (xi[0] - xi[1]);\n            dxdti[1] = R[i] * xi[0] - xi[1] - xi[0] * xi[2];\n            dxdti[2] = -b * xi[2] + xi[0] * xi[1];\n        }\n    }\n};\n\n\nint main() {\n    using namespace boost::numeric::odeint;\n\n    const size_t n = 1024;\n    vector_type R(n);\n    const double Rmin = 0.1, Rmax = 50.0;\n#   pragma omp parallel for\n    for(size_t i = 0 ; i < n ; i++)\n        R[i] = Rmin + (Rmax - Rmin) / (n - 1) * i;\n\n    state_type X(n, point_type(10, 10, 10));\n\n    typedef runge_kutta4<\n        state_type, double,\n        state_type, double,\n        openmp_range_algebra\n    > stepper;\n\n    const double t_max = 10.0, dt = 0.01;\n\n    integrate_const(\n        stepper(),\n        sys_func(R), X,\n        0.0, t_max, dt\n    );\n\n    copy( X.begin(), X.end(), ostream_iterator<point_type>(cout, \"\\n\") );\n\n    return 0;\n}\n", "meta": {"hexsha": "a145c8158de5d600132899bc7c2629f452fa0a2b", "size": 1940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/examples/openmp/lorenz_ensemble_simple.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/openmp/lorenz_ensemble_simple.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/openmp/lorenz_ensemble_simple.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": 24.8717948718, "max_line_length": 80, "alphanum_fraction": 0.6118556701, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5603139964488507}}
{"text": "/**\n * MIT License\n *\n * Copyright (c) 2018 Prabhsimran Singh\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n#pragma once\n\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n#include \"functions.hpp\"\n#include \"layers.hpp\"\n#include \"lstm/network.hpp\"\n\nnamespace nn {\n\nstruct LSTMState {\n    // hidden state\n    MatrixXf h;\n    // cell state\n    MatrixXf c;\n};\n\nclass LSTMCell {\n  private:\n    int batch_size;\n    int hidden_size;\n    int embedding_dim;\n\n    Dense i2h;\n    Dense h2h;\n\n  protected:\n    LSTMState state;\n\n    friend class LSTMNetwork;\n\n  public:\n    explicit LSTMCell(const int &, const int &, const int &);\n\n    MatrixXf &operator()(const MatrixXf &);\n\n    MatrixXf &forward(const MatrixXf &);\n\n    // MatrixXf backward(const MatrixXf &, const MatrixXf &);\n};\n\n/**\n * LSTMCell Constructor.\n * \n * @param hidden_size the size of the hidden state and cell state.\n * @param batch_size the size of batch used during training (for vectorization purposes).\n */\nLSTMCell::LSTMCell(const int &hidden_size, const int &embedding_dim, const int &batch_size)\n    : i2h(Dense(embedding_dim, 4 * hidden_size)), h2h(Dense(hidden_size, 4 * hidden_size)) {\n\n    this->hidden_size = hidden_size;\n    this->embedding_dim = embedding_dim;\n    this->batch_size = batch_size;\n\n    this->state = LSTMState{MatrixXf(batch_size, hidden_size).setRandom() * F::glorot_uniform(batch_size, hidden_size),\n                            MatrixXf(batch_size, hidden_size).setRandom() * F::glorot_uniform(batch_size, hidden_size)};\n}\n\nMatrixXf &LSTMCell::operator()(const MatrixXf &xt) {\n    return forward(xt);\n}\n\n/**\n * LSTMCell Forward Pass.\n * \n * @param xt the input vector at time-step t.\n * @returns the next hidden state for input into next lstm layer.\n */\nMatrixXf &LSTMCell::forward(const MatrixXf &xt) {\n    // i2h + h2h = [it_pre, ft_pre, ot_pre, x_pre]\n    MatrixXf preactivations = i2h(xt) + h2h(state.h);\n    // all pre sigmoid gates chunk\n    MatrixXf pre_sigmoid_chunk = preactivations.block(0, 0, batch_size, 3 * hidden_size);\n    // compute sigmoid on gates chunk\n    MatrixXf all_gates = F::sigmoid(pre_sigmoid_chunk);\n    // compute c_in (x_transform) i.e. information vector\n    MatrixXf x_pre = preactivations.block(0, 3 * hidden_size, batch_size, hidden_size);\n    MatrixXf x_transform = F::tanh(x_pre);\n    // single out all the gates\n    MatrixXf it = all_gates.block(0, 0, batch_size, hidden_size);\n    MatrixXf ft = all_gates.block(0, hidden_size, batch_size, hidden_size);\n    MatrixXf ot = all_gates.block(0, 2 * hidden_size, batch_size, hidden_size);\n    // update cell state\n    MatrixXf c_forget = ft.cwiseProduct(state.c);\n    MatrixXf c_input = it.cwiseProduct(x_transform);\n    state.c = c_forget + c_input;\n    // compute next hidden state\n    MatrixXf c_transform = F::tanh(state.c);\n    state.h = ot.cwiseProduct(c_transform);\n    return state.h;\n}\n\n/**\n * LSTMCell Backward Pass.\n * \n * @param inputs the input vector given at time-step t.\n * @param gradients the gradients from upper layers computed using chain rule.\n * @returns the output i.e. the hidden state at time-step t.\n */\n// MatrixXf LSTMCell::backward(const MatrixXf &inputs, const MatrixXf &gradients) {\n// }\n} // namespace nn", "meta": {"hexsha": "57addc1cbf72ccf1b2ba452ebf1f552c180f515c", "size": 4298, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lstm/cell.hpp", "max_stars_repo_name": "pskrunner14/lstm-from-scratch", "max_stars_repo_head_hexsha": "df61ded892ae7ef576a0c7cc572f6375dd13c99b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-18T04:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T09:48:40.000Z", "max_issues_repo_path": "include/lstm/cell.hpp", "max_issues_repo_name": "pskrunner14/lstm-from-scratch", "max_issues_repo_head_hexsha": "df61ded892ae7ef576a0c7cc572f6375dd13c99b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-23T06:59:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-23T06:59:28.000Z", "max_forks_repo_path": "include/lstm/cell.hpp", "max_forks_repo_name": "pskrunner14/lstm-from-scratch", "max_forks_repo_head_hexsha": "df61ded892ae7ef576a0c7cc572f6375dd13c99b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-02T00:16:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T01:39:40.000Z", "avg_line_length": 33.0615384615, "max_line_length": 120, "alphanum_fraction": 0.7105630526, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5602705521712996}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include \"toplevelfixture.hpp\"\n#include <boost/test/unit_test.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <qle/quotes/logquote.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\nusing QuantExt::LogQuote;\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(LogQuoteTest)\n\nBOOST_AUTO_TEST_CASE(testLogQuote) {\n\n    BOOST_TEST_MESSAGE(\"Testing QuantExt::LogQuote...\");\n    boost::shared_ptr<SimpleQuote> quote(new QuantLib::SimpleQuote(1.0));\n    Handle<Quote> qh(quote);\n    Handle<Quote> logQuote(boost::shared_ptr<Quote>(new LogQuote(qh)));\n\n    BOOST_CHECK_EQUAL(logQuote->value(), std::log(quote->value()));\n\n    quote->setValue(2.0);\n    BOOST_CHECK_EQUAL(logQuote->value(), std::log(quote->value()));\n\n    quote->setValue(3.0);\n    BOOST_CHECK_EQUAL(logQuote->value(), std::log(quote->value()));\n\n    quote->setValue(123.0);\n    BOOST_CHECK_EQUAL(logQuote->value(), std::log(quote->value()));\n\n    // LogQuote should throw when a negative value is set\n    BOOST_CHECK_THROW(quote->setValue(-1.0), std::exception);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n", "meta": {"hexsha": "dbe5647e91793ee5fdeaf9097ca7b727a203acc8", "size": 1906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/logquote.cpp", "max_stars_repo_name": "PiotrSiejda/Engine", "max_stars_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantExt/test/logquote.cpp", "max_issues_repo_name": "PiotrSiejda/Engine", "max_issues_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/test/logquote.cpp", "max_forks_repo_name": "PiotrSiejda/Engine", "max_forks_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T02:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T02:04:10.000Z", "avg_line_length": 32.3050847458, "max_line_length": 73, "alphanum_fraction": 0.7565582371, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5602705466052204}}
{"text": "#pragma once\n\n#include <ros/ros.h>\n#include <string>\n#include <Eigen/Core>\n#include \"inekf_msgs/KinematicsArray.h\"\n#include \"sensor_msgs/JointState.h\"\n\n#include <iostream>\n#include <fstream>\n\n// forward kinematics from FROST\n#include \"kin/H_Body_to_FrontLeftFoot.h\"\n#include \"kin/H_Body_to_FrontRightFoot.h\"\n#include \"kin/H_Body_to_HindLeftFoot.h\"\n#include \"kin/H_Body_to_HindRightFoot.h\"\n#include \"kin/Jb_Body_to_FrontLeftFoot.h\"\n#include \"kin/Jb_Body_to_FrontRightFoot.h\"\n#include \"kin/Jb_Body_to_HindLeftFoot.h\"\n#include \"kin/Jb_Body_to_HindRightFoot.h\"\n\n#include <lcm/lcm-cpp.hpp>\n\nnamespace cheetah_inekf_ros {\n  template <unsigned int ENCODER_DIM>\n  class KinematicsPublisher {\n  public:\n\n    KinematicsPublisher(ros::NodeHandle n) : n_(n) {\n      // Create private node handle\n      ros::NodeHandle nh(\"~\");\n      std::string joint_state_topic, kinematics_topic;\n      nh.param<std::string>(\"joint_state_topic\", joint_state_topic, \"joint_states\");\n      nh.param<std::string>(\"kinematics_topic\", kinematics_topic, \"kinematics\");\n      nh.param<std::string>(\"imu_frame_id\", imu_frame_id_, \"imu_frame_id\");\n      joint_state_sub_ = nh.subscribe(joint_state_topic, 1000, &KinematicsPublisher::joint_state_ros_callback, this);\n      kinematic_pub_ = n_.advertise<inekf_msgs::KinematicsArray>(kinematics_topic, 10);\n      double encoder_std, kinematic_prior_orientation_std, kinematic_prior_position_std;\n      nh.param<double>(\"encoder_std\", encoder_std, 0.0174533); // 1 deg std\n      nh.param<double>(\"kinematic_prior_orientation_std\", kinematic_prior_orientation_std, 0.174533); // 10 deg std\n      nh.param<double>(\"kinematic_prior_position_std\", kinematic_prior_position_std, 0.05); // 5cm std\n\n      cov_encoders_ = encoder_std*encoder_std*Eigen::Matrix<double,ENCODER_DIM,ENCODER_DIM>::Identity(); \n      cov_prior_ = Eigen::Matrix<double,6,6>::Identity();\n      cov_prior_.block<3,3>(0,0) = kinematic_prior_orientation_std*kinematic_prior_orientation_std*Eigen::Matrix<double,3,3>::Identity();\n      cov_prior_.block<3,3>(3,3) = kinematic_prior_position_std*kinematic_prior_position_std*Eigen::Matrix<double,3,3>::Identity();\n      \n      \n    }\n\n    ~KinematicsPublisher(){\n      \n    }\n\n\n    static inekf_msgs::KinematicsArray callback_handler(std_msgs::Header & header,  const Eigen::Matrix<double, ENCODER_DIM, 1> & encoders,\n                                                        const Eigen::Matrix<double, ENCODER_DIM, ENCODER_DIM> & cov_encoder,\n                                                        const Eigen::Matrix<double, 6,6> & cov_prior) {\n      inekf_msgs::Kinematics front_left_foot, front_right_foot, hind_left_foot, hind_right_foot;\n      \n      Eigen::Matrix<double,3,1> p_offset; p_offset << 0, -0.02, 0; // TODO: tune\n      Eigen::Matrix<double,4,4> H_offset = Eigen::Matrix<double,4,4>::Identity();\n      H_offset.block<3,1>(0,3) = p_offset;\n      \n      Eigen::Matrix<double,4,4> H_FL = H_Body_to_FrontLeftFoot(encoders)*H_offset;\n      Eigen::Matrix<double,4,4> H_FR = H_Body_to_FrontRightFoot(encoders)*H_offset;\n      Eigen::Matrix<double,4,4> H_HL = H_Body_to_HindLeftFoot(encoders)*H_offset;\n      Eigen::Matrix<double,4,4> H_HR = H_Body_to_HindRightFoot(encoders)*H_offset;\n      \n      Eigen::Quaternion<double> q_FL(H_FL.block<3,3>(0,0)); q_FL.normalize();\n      Eigen::Quaternion<double> q_FR(H_FR.block<3,3>(0,0)); q_FR.normalize();\n      Eigen::Quaternion<double> q_HL(H_HL.block<3,3>(0,0)); q_HL.normalize();\n      Eigen::Quaternion<double> q_HR(H_HR.block<3,3>(0,0)); q_HR.normalize();\n                  \n      Eigen::Matrix<double,6,ENCODER_DIM> J_FL = Jb_Body_to_FrontLeftFoot(encoders); // body manipulator Jacobian\n      Eigen::Matrix<double,6,ENCODER_DIM> J_FR = Jb_Body_to_FrontRightFoot(encoders); // body manipulator Jacobian\n      Eigen::Matrix<double,6,ENCODER_DIM> J_HL = Jb_Body_to_HindLeftFoot(encoders); // body manipulator Jacobian\n      Eigen::Matrix<double,6,ENCODER_DIM> J_HR = Jb_Body_to_HindRightFoot(encoders); // body manipulator Jacobian\n\n      \n      Eigen::Matrix<double,6,6> cov_FL = J_FL * cov_encoder * J_FL.transpose() + cov_prior;\n      Eigen::Matrix<double,6,6> cov_FR = J_FR * cov_encoder * J_FR.transpose() + cov_prior;\n      Eigen::Matrix<double,6,6> cov_HL = J_HL * cov_encoder * J_HL.transpose() + cov_prior;\n      Eigen::Matrix<double,6,6> cov_HR = J_HR * cov_encoder * J_HR.transpose() + cov_prior;\n      \n      front_left_foot.id = 1;\n      front_left_foot.pose.pose.orientation.w = q_FL.w();\n      front_left_foot.pose.pose.orientation.x = q_FL.x();\n      front_left_foot.pose.pose.orientation.y = q_FL.y();\n      front_left_foot.pose.pose.orientation.z = q_FL.z();\n      front_left_foot.pose.pose.position.x = H_FL(0,3);\n      front_left_foot.pose.pose.position.y = H_FL(1,3);\n      front_left_foot.pose.pose.position.z = H_FL(2,3);\n      for (int i=0; i<6; ++i) {\n        for (int j=0; j<6; ++j) {\n          front_left_foot.pose.covariance[i*6+j] = cov_FL(i,j);\n        }\n      }\n      front_right_foot.id = 0;\n      front_right_foot.pose.pose.orientation.w = q_FR.w();\n      front_right_foot.pose.pose.orientation.x = q_FR.x();\n      front_right_foot.pose.pose.orientation.y = q_FR.y();\n      front_right_foot.pose.pose.orientation.z = q_FR.z();\n      front_right_foot.pose.pose.position.x = H_FR(0,3);\n      front_right_foot.pose.pose.position.y = H_FR(1,3);\n      front_right_foot.pose.pose.position.z = H_FR(2,3);\n      for (int i=0; i<6; ++i) {\n        for (int j=0; j<6; ++j) {\n          front_right_foot.pose.covariance[i*6+j] = cov_FR(i,j);\n        }\n      }\n\n      hind_left_foot.id = 3;\n      hind_left_foot.pose.pose.orientation.w = q_HL.w();\n      hind_left_foot.pose.pose.orientation.x = q_HL.x();\n      hind_left_foot.pose.pose.orientation.y = q_HL.y();\n      hind_left_foot.pose.pose.orientation.z = q_HL.z();\n      hind_left_foot.pose.pose.position.x = H_HL(0,3);\n      hind_left_foot.pose.pose.position.y = H_HL(1,3);\n      hind_left_foot.pose.pose.position.z = H_HL(2,3);\n      for (int i=0; i<6; ++i) {\n        for (int j=0; j<6; ++j) {\n          hind_left_foot.pose.covariance[i*6+j] = cov_HL(i,j);\n        }\n      }\n\n\n      hind_right_foot.id = 2;\n      hind_right_foot.pose.pose.orientation.w = q_HR.w();\n      hind_right_foot.pose.pose.orientation.x = q_HR.x();\n      hind_right_foot.pose.pose.orientation.y = q_HR.y();\n      hind_right_foot.pose.pose.orientation.z = q_HR.z();\n      hind_right_foot.pose.pose.position.x = H_HR(0,3);\n      hind_right_foot.pose.pose.position.y = H_HR(1,3);\n      hind_right_foot.pose.pose.position.z = H_HR(2,3);\n      for (int i=0; i<6; ++i) {\n        for (int j=0; j<6; ++j) {\n          hind_right_foot.pose.covariance[i*6+j] = cov_HR(i,j);\n        }\n      }\n\n      inekf_msgs::KinematicsArray kinematics_msg;\n      kinematics_msg.frames.push_back(front_right_foot);\n      kinematics_msg.frames.push_back(front_left_foot);\n      kinematics_msg.frames.push_back(hind_right_foot);\n      kinematics_msg.frames.push_back(hind_left_foot);\n      // kinematic_pub_.publish(kinematics_msg);\n\n      // std::ofstream fLogCSV;\n      // fLogCSV.open(\"/media/curly_ssd_justin/code/minicheetah-perception/fk_log.csv\", std::ios::app);\n      // fLogCSV<<front_right_foot.pose.pose.position.x<<\",\"<<front_right_foot.pose.pose.position.y<<\",\"<<front_right_foot.pose.pose.position.z<<\",\"\\\n      // <<front_left_foot.pose.pose.position.x<<\",\"<<front_left_foot.pose.pose.position.y<<\",\"<<front_left_foot.pose.pose.position.z<<\",\"\\\n      // <<hind_right_foot.pose.pose.position.x<<\",\"<<hind_right_foot.pose.pose.position.y<<\",\"<<hind_right_foot.pose.pose.position.z<<\",\"\\\n      // <<hind_left_foot.pose.pose.position.x<<\",\"<<hind_left_foot.pose.pose.position.y<<\",\"<<hind_left_foot.pose.pose.position.z<<\"\\n\";\n      // fLogCSV.flush();\n      // fLogCSV.close();\n      \n      return kinematics_msg;\n      \n    }\n\n    \n    \n    \n  private:\n    ros::NodeHandle n_;\n    ros::Subscriber joint_state_sub_;\n    ros::Publisher kinematic_pub_;\n\n\n    \n    std::string imu_frame_id_;\n    //const unsigned int encoder_dim_;\n    Eigen::Matrix<double,ENCODER_DIM,ENCODER_DIM> cov_encoders_;\n    Eigen::Matrix<double,6,6> cov_prior_;\n\n    void joint_state_ros_callback(const sensor_msgs::JointState::ConstPtr msg) {\n      std_msgs::Header header = msg->header;\n      header.frame_id = imu_frame_id_;\n      Eigen::Matrix<double,ENCODER_DIM,1> encoders;\n      for (int i=0; i<ENCODER_DIM; ++i) {\n        encoders(i) = msg->position[i];\n      }\n      auto kinematics_msg =  callback_handler(header, encoders, cov_encoders_, cov_prior_);\n      kinematic_pub_.publish(kinematics_msg);\n\n    }\n    \n  }; \n  \n}\n", "meta": {"hexsha": "207625f5d237de269cbe7394402dbae8243fbaf1", "size": 8618, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cheetah_inekf_ros/KinematicsPublisher.hpp", "max_stars_repo_name": "UMich-CURLY/cheetah_inekf_ros", "max_stars_repo_head_hexsha": "a5c709ff29df161c1907b243999ff5b9b3161179", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-14T21:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T13:49:26.000Z", "max_issues_repo_path": "include/cheetah_inekf_ros/KinematicsPublisher.hpp", "max_issues_repo_name": "UMich-CURLY/cheetah_inekf_ros", "max_issues_repo_head_hexsha": "a5c709ff29df161c1907b243999ff5b9b3161179", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cheetah_inekf_ros/KinematicsPublisher.hpp", "max_forks_repo_name": "UMich-CURLY/cheetah_inekf_ros", "max_forks_repo_head_hexsha": "a5c709ff29df161c1907b243999ff5b9b3161179", "max_forks_repo_licenses": ["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.8854166667, "max_line_length": 149, "alphanum_fraction": 0.6741703411, "num_tokens": 2385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5602705413237885}}
{"text": "#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <boost/range/algorithm.hpp>\n#include <boost/integer/common_factor_rt.hpp>\n#define MAX 100000000\n\nusing namespace std;\n\nint A, B;\n\nint main()\n{\n    while (cin >> A >> B)\n    {\n        if (abs(A - B) % 2 == 0)\n        {\n            cout << abs(A - B) / 2 + min(A, B) << endl;\n        }\n        else\n        {\n            cout << \"IMPOSSIBLE\" << endl;\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "582756dde2863b61b46805363aef0c438fa231da", "size": 504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc135_a/Main.cpp", "max_stars_repo_name": "mizo0203/atcoder", "max_stars_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abc135_a/Main.cpp", "max_issues_repo_name": "mizo0203/atcoder", "max_issues_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "abc135_a/Main.cpp", "max_forks_repo_name": "mizo0203/atcoder", "max_forks_repo_head_hexsha": "56c06ccd111e3c36c7cfde4ae0753a8552f93728", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.2580645161, "max_line_length": 55, "alphanum_fraction": 0.5238095238, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5602705412289063}}
{"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": "\ufeff/*\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": "#ifndef NETWORK\r\n#define NETWORK\r\n\r\n#include <vector>\r\n#include <iostream>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <boost/function.hpp>\r\n\r\nusing namespace boost::numeric::ublas;\r\n\r\n\r\ntypedef boost::function<vector<double>* (const vector<double>&)> Function;\r\n\r\n\r\nclass Network\r\n{\r\n\tdouble\t\t\t\t\t\t\t\t\t\t\t\tlearningRate;\r\n\tint \t\t\t\t\t\t\t\t\t\t\t\t\tnbLayers;\r\n\tstd::vector<vector<double>*>\terrors;\r\n\tstd::vector<vector<double>*>\tinputs;\r\n\tstd::vector<vector<double>*>\toutputs;\r\n\tstd::vector<matrix<double>*>\tweights;\r\n\tstd::vector<vector<double>*>\tbiases;\r\n\r\n\tstd::vector<Function*>\t\t\t\tfunctions;\r\n\tstd::vector<Function*>\t\t\t\tderivates;\r\n\r\npublic:\r\n\tNetwork(const std::vector<int>&, double=0.01);\r\n\tvirtual ~Network();\r\n\r\n\tvoid\t\t\t\t\t\tfit(matrix<double>&, matrix<double>&, const int=100);\r\n\tvector<double> \t*predict(const vector<double>&);\r\n\r\n\tfriend std::ostream& operator<<(std::ostream&, const Network&);\r\n\r\nprivate:\r\n\r\n\tvoid \t\t\t\t\t\tinitializeNetwork(const std::vector<int>&);\r\n\tvoid \t\t\t\t\t\tupdateWeights(vector<double>*, vector<double>*);\r\n\tvector<double> \t*feedForward(const vector<double>&);\r\n\tvector<double> \t*row2vec(const matrix_row<matrix<double> >&) const;\r\n\r\n\tstatic vector<double>\t*sigmoid(const vector<double>&);\r\n\tstatic vector<double> *sigmoidPrime(const vector<double>&);\r\n\tstatic vector<double>\t*identity(const vector<double>&);\r\n\tstatic vector<double>\t*identityPrime(const vector<double>&);\r\n};\r\n\r\n#endif\r\n", "meta": {"hexsha": "af478f217ae2ab13cc154fa09c18d57b8fe5de71", "size": 1460, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Network.hpp", "max_stars_repo_name": "amstuta/cpp_neural_network", "max_stars_repo_head_hexsha": "e664cd15a7119b418f4fb35775ab510d6b7655a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-19T22:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:48:43.000Z", "max_issues_repo_path": "Network.hpp", "max_issues_repo_name": "amstuta/cpp_neural_network", "max_issues_repo_head_hexsha": "e664cd15a7119b418f4fb35775ab510d6b7655a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Network.hpp", "max_forks_repo_name": "amstuta/cpp_neural_network", "max_forks_repo_head_hexsha": "e664cd15a7119b418f4fb35775ab510d6b7655a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0769230769, "max_line_length": 75, "alphanum_fraction": 0.6849315068, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.560267475540335}}
{"text": "#include <ayla/geometry/intersection.hpp>\n#include <ayla/geometry/vector.hpp>\n\n#include <glm/gtx/rotate_vector.hpp>\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE( ayla )\nBOOST_AUTO_TEST_SUITE( intersection ) \n\nBOOST_AUTO_TEST_CASE( ray_aab_intersection ) {\n\tAxisAlignedBox aab( glm::vec3( 0.0, 0.0, 0.0 ), 5.0, 5.0, 5.0 );\n\tFloat d;\n\t\n\tfor (int i = -5; i < 5; i++) {\n\t\tRay ray( glm::vec3( 0.0, 0.0, 0.0 ), glm::normalize(glm::vec3( i, 1.0, 0.0 )) );\n\t\tBOOST_CHECK( ayla::intersection::rayAab( ray, aab, d ) );\n\t}\n\t\n\tfor (int i = -5; i < 5; i++) {\n\t\tRay ray(glm::vec3(0.0, 5.1, 0.0), glm::normalize(glm::vec3(i, 1.0, 0.0)));\n\t\tBOOST_CHECK( ! ayla::intersection::rayAab( ray, aab, d ) );\n\t}\n\n\tRay rayA( glm::vec3( 0.0, 6.0, 0.0 ), glm::vec3( 1.0, 0.0, 0.0)  );\n\tBOOST_CHECK( ! ayla::intersection::rayAab( rayA, aab, d ) );\n\t\n\tRay rayB(glm::vec3(0.0, 6.0, 0.0), glm::normalize(glm::vec3(1.0, -1.0, 0.0)));\n\tBOOST_CHECK( ayla::intersection::rayAab( rayB, aab, d ) );\n\t\n\tRay rayC(glm::vec3(10.0, 10.0, 10.0), glm::normalize(glm::vec3(-1.0, -1.0, -1.0)));\n\tBOOST_CHECK(  ayla::intersection::rayAab( rayC, aab, d ) );\n}\n\nBOOST_AUTO_TEST_CASE( ray_box_intersection ) { \n\tBox box(glm::vec3(0.0, 0.0, 0.0), 5.0, 5.0, 5.0);\n\tFloat d;\n\t\n\tRigidTransform transform = RigidTransform::getIdentity();\n\t\n\t// Testing first when the Box is aligned. Then rotating 90 degrees around the Y axis.\n\tfor (int k = 0; k < 3; k++) {\n\t\tfor (int i = -5; i < 5; i++) {\n\t\t\tRay ray(glm::vec3(0.0, 0.0, 0.0), glm::normalize(glm::vec3(i, 1.0, 0.0)));\n\t\t\tBOOST_CHECK( ayla::intersection::rayBox( ray, box, d ) );\n\t\t}\n\n\t\tfor (int i = -5; i < 5; i++) {\n\t\t\tRay ray(glm::vec3(0.0, 5.1, 0.0), glm::normalize(glm::vec3(i, 1.0, 0.0)));\n\t\t\tBOOST_CHECK( ! ayla::intersection::rayBox( ray, box, d ) );\n\t\t}\n\n\t\tRay rayA( glm::vec3( 0.0, 6.0, 0.0 ), glm::vec3( 1.0, 0.0, 0.0)  );\n\t\tBOOST_CHECK( ! ayla::intersection::rayBox( rayA, box, d ) );\n\n\t\tRay rayB(glm::vec3(0.0, 6.0, 0.0), glm::normalize(glm::vec3(1.0, -1.0, 0.0)));\n\t\tBOOST_CHECK( ayla::intersection::rayBox( rayB, box, d ) );\n\n\t\tRay rayC(glm::vec3(10.0, 10.0, 10.0), glm::normalize(glm::vec3(-1.0, -1.0, -1.0)));\n\t\tBOOST_CHECK(  ayla::intersection::rayBox( rayC, box, d ) );\n\t\t\n\t\ttransform.rotate( glm::pi<Float>() / 2.0f, glm::vec3( 0.0, 1.0, 0.0 ) );\n\t\tbox.rotateBase( transform.getRotationMatrix() );\n\t}\n\n\ttransform.rotate(glm::pi<Float>() / 4.0f, glm::vec3(0.0, 1.0, 0.0));\n\tbox.rotateBase( transform.getRotationMatrix() );\n\t\n\tRay rayA( glm::vec3( 5.0, 5.0, 5.0 ), glm::vec3( 1.0, 0.0, 0.0 ) );\n\tBOOST_CHECK( ! ayla::intersection::rayBox( rayA, box, d ) );\n}\n\nBOOST_AUTO_TEST_CASE( ray_sphere_intersection ) { \n\tSphere sphere( glm::vec3( 0.0, 0.0, 0.0 ), 10.0 );\n\tFloat d;\n\t\n\tfor (int i = 0; i < 10; i++) {\n\t\tRay ray(glm::vec3(20.0, i, 0.0), glm::vec3(-1.0, 0.0, 0.0));\n\t\tBOOST_CHECK(ayla::intersection::raySphere( ray, sphere, d));\n\t}\n\t\n\tfor (int i = -10; i < 10; i++) {\n\t\tfor (int j = -10; j < 10; j++) {\n\t\t\t//inside out\n\t\t\tRay rayA(glm::vec3(0.0, 0.0, 0.0), glm::normalize(glm::vec3(i, j, 10.0)));\n\t\t\tRay rayB(glm::vec3(0.0, 0.0, 0.0), glm::normalize(glm::vec3(i, 10.0, j)));\n\t\t\tRay rayC(glm::vec3(0.0, 0.0, 0.0), glm::normalize(glm::vec3(10.0, i, j)));\n\t\t\tBOOST_CHECK( ayla::intersection::raySphere(rayA, sphere, d ) );\n\t\t\tBOOST_CHECK( ayla::intersection::raySphere(rayB, sphere, d ) );\n\t\t\tBOOST_CHECK( ayla::intersection::raySphere(rayC, sphere, d ) );\n\t\t\n\t\t\t//outside in\n\t\t\tRay rayD(glm::vec3(i, j, 10.0), glm::normalize(-glm::vec3(i, j, 10.0)));\n\t\t\tRay rayE(glm::vec3(i, 10.0, j), glm::normalize(-glm::vec3(i, 10.0, j)));\n\t\t\tRay rayF(glm::vec3(10.0, i, j), glm::normalize(-glm::vec3(10.0, i, j)));\n\t\t\tBOOST_CHECK( ayla::intersection::raySphere(rayD, sphere, d ) );\n\t\t\tBOOST_CHECK( ayla::intersection::raySphere(rayE, sphere, d ) );\n\t\t\tBOOST_CHECK( ayla::intersection::raySphere(rayF, sphere, d ) );\n\t\t\n\t\t\t//so if we change the ray direction it shouldn't intersect\n\t\t\tRay rayG(glm::vec3(i, j, 11.0), glm::normalize(glm::vec3(i, j, 10.0)));\n\t\t\tRay rayH(glm::vec3(i, 11.0, j), glm::normalize(glm::vec3(i, 10.0, j)));\n\t\t\tRay rayI(glm::vec3(11.0, i, j), glm::normalize(glm::vec3(10.0, i, j)));\n\t\t\tBOOST_CHECK( ! ayla::intersection::raySphere(rayG, sphere, d ) );\n\t\t\tBOOST_CHECK( ! ayla::intersection::raySphere(rayH, sphere, d ) );\n\t\t\tBOOST_CHECK( ! ayla::intersection::raySphere(rayI, sphere, d ) );\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE( ray_plane_intersection ) {\n\t// XZ plane\n\tPlane plane( glm::vec3( 0.0, 1.0, 0.0 ), 0.0 );\n\tFloat d;\n\t\n\tfor (int i = 0; i < 10; i++) {\n\t\tfor (int j = 0; j < 10; j++) {\n\t\t\tRay ray(glm::vec3(i, 10.0, j), glm::normalize(-glm::vec3(i, 10.0, j)));\n\t\t\tBOOST_CHECK(ayla::intersection::rayPlane(ray, plane, d));\n\n\t\t\tRay another(glm::vec3(i, 10.0, j), glm::normalize(glm::vec3(i, 10.0, j)));\n\t\t\tBOOST_CHECK(!ayla::intersection::rayPlane(another, plane, d));\n\t\t}\n\t}\n\t\n\t//parallel to the plane\n\tfor (int i = 1; i < 10; i++) {\n\t\tfor (int j = 1; j < 10; j++) {\n\t\t\tRay parallel(glm::vec3(0.0, 1.0, 0.0), glm::normalize(glm::vec3(i, 0.0, j)));\n\t\t\tBOOST_CHECK(!ayla::intersection::rayPlane(parallel, plane, d));\n\t\t}\n\t}\n\t\n\t//inside the plane\n\tfor (int i = 1; i < 10; i++) {\n\t\tfor (int j = 1; j < 10; j++) {\n\t\t\tRay inside(glm::vec3(0.0, 0.0, 0.0), glm::normalize(glm::vec3(i, 0.0, j)));\n\t\t\tBOOST_CHECK(ayla::intersection::rayPlane(inside, plane, d));\n\t\t}\n\t}\n\t\n\tPlane rotatedPlane(glm::normalize(glm::vec3( 1.0, 1.0, 0.0 )), 0.0);\n\t\n\tglm::vec3 offset(1.0, 0.0, 1.0);\n\tfor (int j = 0; j < 10; j++ ) {\n\t\tglm::vec3 position = glm::vec3( 10.0, 10.0, 0.0 ) + offset;\n\t\tRay ray(  position, glm::normalize(-position) );\n\t\tBOOST_CHECK( ayla::intersection::rayPlane( ray, rotatedPlane, d ) );\n\t\t\n\t\tRay another( position, glm::normalize(position) );\n\t\tBOOST_CHECK( ! ayla::intersection::rayPlane( another, rotatedPlane, d ) );\n\t\t\n\t\toffset = glm::rotate<Float>(offset, glm::pi<Float>() / 8.0f, glm::vec3(1.0, 1.0, 0.0));\n\t}\n\t\n\t//parallel to the plane\n\tRay parallel( glm::vec3( 1.0, 1.0, 0.0 ), glm::normalize(glm::vec3( 1.0, 0.0, 1.0 )) );\n\tfor (int i = 1; i < 8; i++) {\n\t\tBOOST_CHECK( ! ayla::intersection::rayPlane( parallel, rotatedPlane, d ) );\n\t\tglm::vec3 rotatedDirection = glm::rotate<Float>(parallel.getDirection(), glm::pi<Float>() / 4.0f, glm::vec3(1.0, 1.0, 0.0));\n\t\tparallel.setDirection( rotatedDirection );\n\t}\n\t\n\t//inside the plane\n\tRay inside( glm::vec3( 0.0, 0.0, 0.0 ), glm::normalize(glm::vec3( 1.0, 0.0, 1.0 )) );\n\tfor (int i = 1; i < 8; i++) {\n\t\tBOOST_CHECK( ayla::intersection::rayPlane( inside, rotatedPlane, d ) );\n\t\tglm::vec3 rotatedDirection = glm::rotate<Float>(inside.getDirection(), glm::pi<Float>() / 4.0f, glm::vec3(1.0, 1.0, 0.0));\n\t\tinside.setDirection( rotatedDirection );\n\t}\n\t\n\t//Not in the origin\n}\n\nBOOST_AUTO_TEST_CASE( sphere_aab_intersection ) {\n\tSphere sphere( glm::vec3( 0.0, 0.0, 0.0 ), 10.0 );\n\t\n\tfor (int i = -11; i <= 11; i++) {\n\t\tAxisAlignedBox aab( glm::vec3( i, 0.0, 0.0 ), 1.0, 1.0, 1.0 );\n\t\tBOOST_CHECK( ayla::intersection::sphereAab( sphere, aab ) );\n\t}\n\t\n\t{\n\t\tAxisAlignedBox aab( glm::vec3( 0.0, 0.0, 0.0 ), 1.0, 1.0, 1.0 );\n\t\tfor (int i = 0; i < 10; i++) {\n\t\t\tSphere sphere( glm::vec3( 1.0 + cos( glm::pi<Float>()/4.0f), (0.1 * i) + sin( glm::pi<Float>()/4.0f), 0.0 ), 1.0  );\n\t\t\tBOOST_CHECK( ayla::intersection::sphereAab( sphere, aab ) );\n\t\t}\n\t}\n\t\n\t{\n\t\tAxisAlignedBox aab( glm::vec3( 0.0, 0.0, 0.0 ), 1.0, 1.0, 1.0 );\n\t\tfor (int i = -10; i < 10; i++) {\n\t\t\tSphere sphereA( glm::vec3( i, 2.0, 0.0 ), 0.5 );\n\t\t\tSphere sphereB( glm::vec3( 2.0, i, 0.0 ), 0.5 );\n\t\t\tSphere sphereC( glm::vec3( 0.0, 2.0, i ), 0.5 );\n\t\t\t\n\t\t\tBOOST_CHECK( ! ayla::intersection::sphereAab( sphereA, aab ) );\n\t\t\tBOOST_CHECK( ! ayla::intersection::sphereAab( sphereB, aab ) );\n\t\t\tBOOST_CHECK( ! ayla::intersection::sphereAab( sphereC, aab ) );\n\t\t}\n\t}\n\t\n\t{\n\t\tAxisAlignedBox aab( glm::vec3( 0.0, 0.0, 0.0 ), 10.0, 10.0, 10.0 );\n\t\tSphere contained( glm::vec3( 1.0, 0.0, 1.0 ), 1.0 );\n\t\tSphere containing( glm::vec3( 0.0, 1.0, 2.0 ), 100.0 );\n\t\t\n\t\tBOOST_CHECK( ayla::intersection::sphereAab( contained, aab) );\n\t\tBOOST_CHECK( ayla::intersection::sphereAab( containing, aab ) );\n\t}\n}\n\nBOOST_AUTO_TEST_CASE( triangle_line_segment_intersection ) {\n\tTriangle triangle(glm::vec3( 3.0, 0.0, 0.0 ), glm::vec3( 0.0, 4.0, 0.0 ), glm::vec3( 0.0, 0.0, 0.0 ));\n\t\n\t{\n\t\tLineSegment axisX( glm::vec3( -5.0, 4.0, 0.0 ), glm::vec3( 5.0, 4.0, 0.0 ) );\n\t\tLineSegment axisY( glm::vec3( 3.0, -5.0, 0.0 ), glm::vec3( 3.0, 5.0, 0.0 ) );\n\t\tLineSegment axisZ( glm::vec3( 0.0, 0.0, -5.0 ), glm::vec3( 0.0, 0.0, 5.0 ) );\n\t\tLineSegment segment( glm::vec3( 3.0, 4.0, 0.0 ), glm::vec3( 0.0, 0.0, 0.0 ) );\n\t\tLineSegment contained( glm::vec3( 0.1, 0.1, 0.0 ), glm::vec3( 0.2, 0.2, 0.0 ) );\n\t\tLineSegment inEdge( glm::vec3( 0.0, 0.0, 0.0 ), glm::vec3( 4.0, 0.0, 0.0 ) );\n\t\tglm::vec3 intersectionPoint;\n\t\t\n\t\tBOOST_CHECK( ayla::intersection::triangleLineSegment(triangle, segment) );\n\t\tBOOST_CHECK( ayla::intersection::triangleLineSegment(triangle, contained) );\n\t\tBOOST_CHECK( ayla::intersection::triangleLineSegment(triangle, inEdge ) );\n\t\t\n\t\tBOOST_CHECK( ayla::intersection::triangleLineSegment( triangle, axisX, intersectionPoint ) );\n\t\tBOOST_CHECK( ayla::epsilonEqual( intersectionPoint, glm::vec3( 0.0, 4.0, 0.0 ) ) );\n\t\t\n\t\tBOOST_CHECK( ayla::intersection::triangleLineSegment( triangle, axisY, intersectionPoint ) );\n\t\tBOOST_CHECK( ayla::epsilonEqual( intersectionPoint, glm::vec3( 3.0, 0.0, 0.0 ) ) );\n\t\t\n\t\tBOOST_CHECK( ayla::intersection::triangleLineSegment( triangle, axisZ, intersectionPoint ) );\n\t\tBOOST_CHECK( ayla::epsilonEqual( intersectionPoint, glm::vec3( 0.0, 0.0, 0.0 ) ) );\n\t}\n}\n\nBOOST_AUTO_TEST_CASE( plane_line_segment_intersection ) {\n\tPlane planeXZ( glm::vec3( 0.0, 1.0, 0.0 ), 0.0 );\n\t\n\tLineSegment contained( glm::vec3( 1.0, 0.0, 1.0 ) , glm::vec3( -1.0, 0.0, -2.0 ) );\n\tLineSegment parallel( glm::vec3( 1.0, 1.0, 1.0 ), glm::vec3( -1.0, 1.0, -2.0 ) );\n\tglm::vec3 intersectionPoint;\n\t\n\tBOOST_CHECK( ayla::intersection::planeLineSegment( planeXZ, contained, intersectionPoint ) );\n\tBOOST_CHECK( ayla::epsilonEqual( intersectionPoint, glm::vec3( 1.0, 0.0, 1.0 ) ) );\n\t\n\tBOOST_CHECK( ! ayla::intersection::planeLineSegment( planeXZ, parallel, intersectionPoint ) );\n\t\n\tfor (int i = -10; i < 10; i++) {\n\t\tfor (int j = -10; j < 10; j++) {\n\t\t\tLineSegment segment( glm::vec3( i, 10.0, j ), glm::vec3( 0.0, -1.0, 0.0 ) );\n\t\t\tBOOST_CHECK( ayla::intersection::planeLineSegment( planeXZ, segment, intersectionPoint ) );\n\t\t\n\t\t\tLineSegment pColliding( glm::vec3( 0.0, 0.0, 0.0 ) , glm::vec3( i, -1.0, j ) );\n\t\t\tBOOST_CHECK( ayla::intersection::planeLineSegment( planeXZ, pColliding, intersectionPoint ) );\n\t\t\tBOOST_CHECK( ayla::epsilonEqual( intersectionPoint, pColliding.getP() ) );\n\t\t\n\t\t\tLineSegment qColliding( glm::vec3( i, 1.0, j ), glm::vec3( 0.0, 0.0, 0.0 ) );\n\t\t\tBOOST_CHECK( ayla::intersection::planeLineSegment( planeXZ, qColliding, intersectionPoint ) );\n\t\t\tBOOST_CHECK( ayla::epsilonEqual( intersectionPoint, qColliding.getQ() ) );\n\t\t}\n\t}\t\n}\n\nBOOST_AUTO_TEST_CASE( aab_line_segment_intersection ) {\n\tAxisAlignedBox aab( glm::vec3( 0.0, 0.0, 0.0 ), 10.0, 10.0, 10.0 );\n\t\n\tfor (int i = -10; i < 10; i++) { \n\t\tfor (int j = -10; j < 10; j++) {\n\t\t\tLineSegment inwards( glm::vec3( i, 20.0, j ), glm::vec3( 0.0, 0.0, 0.0 ) );\n\t\t\tBOOST_CHECK( ayla::intersection::aabLineSegment( aab, inwards ) );\n\t\t\n\t\t\tLineSegment outwards( glm::vec3( i, 11.0, j ), glm::vec3( 2*i, 22.0, 2*j ) );\n\t\t\tBOOST_CHECK( ! ayla::intersection::aabLineSegment( aab, outwards ) );\n\t\t}\n\t}\n\t\n\tLineSegment parallel( glm::vec3( 20.0, 0.0, 0.0 ), glm::vec3( 20.0, 10.0, 0.0 ) );\n\tLineSegment contained( glm::vec3( -3.0, 0.0, 0.0 ), glm::vec3( 3.0, 0.0, 0.0 ) );\n\tLineSegment collidesVertex( glm::vec3( 20.0, 0.0, 10.0 ), glm::vec3( 0.0, 20.0, 10.0 ) );\n\tLineSegment collidesEdgeA( glm::vec3( 20.0, 0.0, 0.0 ), glm::vec3( 0.0, 20.0, 0.0 ) );\n\tLineSegment collidesEdgeB( glm::vec3( 20.0, 0.0, 0.0 ), glm::vec3( 0.0, 0.0, 20.0 ) );\n\tLineSegment collidesEdgeC( glm::vec3( 0.0, 20.0, 0.0 ), glm::vec3( 0.0, 0.0, 20.0 ) );\n\t\n\tBOOST_CHECK( ! ayla::intersection::aabLineSegment( aab, parallel ) );\n\tBOOST_CHECK( ayla::intersection::aabLineSegment( aab, contained ) );\n\tBOOST_CHECK( ayla::intersection::aabLineSegment( aab, collidesVertex ) );\n\tBOOST_CHECK( ayla::intersection::aabLineSegment( aab, collidesEdgeA ) );\n\tBOOST_CHECK( ayla::intersection::aabLineSegment( aab, collidesEdgeB ) );\n\tBOOST_CHECK( ayla::intersection::aabLineSegment( aab, collidesEdgeC ) );\t\n}\n\nBOOST_AUTO_TEST_CASE( aab_plane_intersection ) {\n\tAxisAlignedBox aab( glm::vec3( 0.0, 0.0, 0.0 ), 10.0, 10.0, 10.0 );\n\t\n\tglm::vec3 normal( 0.0, 1.0, 0.0 );\n\tfor (int i = 0; i < 10; i++) {\n\t\tPlane plane( normal, 0.0 );\n\t\tBOOST_CHECK( ayla::intersection::aabPlane( aab, plane ) );\n\t\t\n\t\tnormal = glm::rotate<Float>( normal, glm::pi<Float>()/6.0f, glm::vec3( 1.0f, 0.0f, 0.0 ) );\n\t}\n\t\n\tPlane parallelToFace( glm::vec3( 0.0, 1.0, 0.0 ), 11.0 );\n\tPlane containsFace( glm::vec3( 0.0, 1.0, 0.0 ), 10.0 );\n\tPlane containsEdge( glm::normalize(glm::vec3( 1.0f, 1.0f, 0.0f )), sqrt(2.0f) * 10.0f );\n\tPlane farAway( glm::normalize(glm::vec3( 2.0, 3.3, -5.0 )), 100.0 );\n\t\n\tBOOST_CHECK( ! ayla::intersection::aabPlane( aab, parallelToFace ) );\n\tBOOST_CHECK( ayla::intersection::aabPlane( aab, containsFace ) );\n\tBOOST_CHECK( ayla::intersection::aabPlane( aab, containsEdge ) );\n\tBOOST_CHECK( ! ayla::intersection::aabPlane( aab, farAway ) );\n}\n\nBOOST_AUTO_TEST_CASE( aab_triangle_intersection ) { \n\tAxisAlignedBox aab( glm::vec3( 0.0f, 0.0f, 0.0f ), 10.0f, 10.0f, 10.0f );\n\t\n\tglm::vec3 direction( 1.0f, 0.0f, 0.0f );\n\t\n\tfor (int i = 0; i < 10; i++) {\n\t\tglm::vec3 origin( 0.0f, 11.0f, 0.0f );\n\t\tTriangle tri( origin, origin + direction * 10.0f, glm::vec3( 0.0f, 0.0f, 0.0f ) );\n\t\tBOOST_CHECK( ayla::intersection::aabTriangle( aab, tri ) );\n\t\tdirection = glm::rotate<Float>( direction, glm::pi<Float>() / 6.0f, glm::vec3( 0.0f, 1.0f, 0.0f ) );\n\t}\n\t\n\tTriangle contained( glm::vec3( -3.0f, 0.0f, 0.0f ), glm::vec3( 2.0f, 5.0f, -3.0f ), glm::vec3( 3.0f, 2.0f, 3.0f ) );\n\tTriangle perpendicularToFaceOut( glm::vec3( 12.0f, 0.0f, 0.0f ), glm::vec3( 20.0f, 0.0f, 0.0f ), glm::vec3( 13.0f, 5.0f, 0.0f ) );\n\tTriangle perpendicularToFaceIn( glm::vec3( 7.0f, 0.0f, 0.0f ), glm::vec3( 15.0f, 0.0f, 0.0f ), glm::vec3( 9.0f, 5.0f, 0.0f ) );\n\tTriangle parallelToFace( glm::vec3( 12.0f, 0.0f, 10.0f ), glm::vec3( 12.0f, 0.0f, -10.0f ), glm::vec3( 12.0f, 5.0f, 0.0f ) );\n\tTriangle containedFace( glm::vec3( 10.0f, 0.0f, -5.0f ), glm::vec3( 10.0f, 0.0f, 5.0f ), glm::vec3( 10.0f, 5.0f, 0.0f ) );\n\tTriangle containsFace( glm::vec3( 10.0f, -10.0f, -50.0f ), glm::vec3( 10.0f, -10.0f, 50.0f ), glm::vec3( 10.0f, 50.0f, 0.0f ) );\n\tTriangle collidingVertex( glm::vec3( 10.0f, 10.0f, 0.0f ), glm::vec3( 20.0f, 10.0f, 0.0f ), glm::vec3( 20.0f, 20.0f, 0.0f ) );\n\tTriangle collidingEdge( glm::vec3( 10.0f, -10.0f, -50.0f ), glm::vec3( 10.0f, -10.0f, 50.0f ), glm::vec3( 0.0f, -50.0f, 0.0f ) );\n\t\n\tBOOST_CHECK( ayla::intersection::aabTriangle( aab, contained ) );\n\tBOOST_CHECK( ! ayla::intersection::aabTriangle( aab, perpendicularToFaceOut ) );\n\tBOOST_CHECK( ayla::intersection::aabTriangle( aab, perpendicularToFaceIn ) );\n\tBOOST_CHECK( ! ayla::intersection::aabTriangle( aab, parallelToFace ) );\n\tBOOST_CHECK( ayla::intersection::aabTriangle( aab, containedFace ) );\n\tBOOST_CHECK( ayla::intersection::aabTriangle( aab, containsFace ) );\n\tBOOST_CHECK( ayla::intersection::aabTriangle( aab, collidingVertex ) );\n\tBOOST_CHECK( ayla::intersection::aabTriangle( aab, collidingEdge ) );\n\t\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nBOOST_AUTO_TEST_SUITE_END()\n\n\n", "meta": {"hexsha": "d65a7f5d1ebb0af4c71de31416c82ab5e5d25ef3", "size": 15467, "ext": "cc", "lang": "C++", "max_stars_repo_path": "epoch/ayla/tests/intersection.cc", "max_stars_repo_name": "oprogramadorreal/vize", "max_stars_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T14:36:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T07:44:54.000Z", "max_issues_repo_path": "epoch/ayla/tests/intersection.cc", "max_issues_repo_name": "oprogramadorreal/vize", "max_issues_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "epoch/ayla/tests/intersection.cc", "max_forks_repo_name": "oprogramadorreal/vize", "max_forks_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-04-01T01:22:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T13:06:09.000Z", "avg_line_length": 43.6920903955, "max_line_length": 131, "alphanum_fraction": 0.622874507, "num_tokens": 6492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.560267475540335}}
{"text": "/* test_lognormal_distribution.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/lognormal_distribution.hpp>\r\n#include <limits>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::lognormal_distribution<>\r\n#define BOOST_RANDOM_ARG1 m\r\n#define BOOST_RANDOM_ARG2 s\r\n#define BOOST_RANDOM_ARG1_DEFAULT 0.0\r\n#define BOOST_RANDOM_ARG2_DEFAULT 1.0\r\n#define BOOST_RANDOM_ARG1_VALUE 7.5\r\n#define BOOST_RANDOM_ARG2_VALUE 0.25\r\n\r\n#define BOOST_RANDOM_DIST0_MIN 0.0\r\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST1_MIN 0.0\r\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST2_MIN 0.0\r\n#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<double>::infinity)()\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS (-100.0)\r\n#define BOOST_RANDOM_TEST1_MAX 1\r\n\r\n#define BOOST_RANDOM_TEST2_PARAMS (100.0)\r\n#define BOOST_RANDOM_TEST2_MIN 1\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "ae8236edb821f820972efc1e363731036980bdbf", "size": 1144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_lognormal_distribution.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/random/test/test_lognormal_distribution.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/random/test/test_lognormal_distribution.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 30.9189189189, "max_line_length": 74, "alphanum_fraction": 0.7832167832, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5602674645889321}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <geometry_test_common.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <boost/geometry/algorithms/assign.hpp>\n\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/strategies/geographic/distance_andoyer.hpp>\n#include <boost/geometry/strategies/geographic/distance_vincenty.hpp>\n#include <boost/geometry/extensions/gis/latlong/latlong.hpp>\n\n#include <test_common/test_point.hpp>\n\n\n\nint test_main(int, char* [])\n{\n    using namespace bg::strategy::distance;\n\n    bg::model::ll::point<bg::degree> paris;\n    paris.lat(bg::dms<bg::north>(48, 52, 0));\n    paris.lon(bg::dms<bg::east>(2, 19, 59));\n\n    bg::model::ll::point<bg::degree> amsterdam;\n    amsterdam.lat(bg::dms<bg::north>(52, 22, 23));\n    amsterdam.lon(bg::dms<bg::east>(4, 53, 32));\n\n    bg::model::ll::point<bg::radian> paris_rad, amsterdam_rad;\n    transform(amsterdam, amsterdam_rad);\n    transform(paris, paris_rad);\n\n    // Distance paris-amsterdam is about 430 km\n    double expected = 429.984 * 1000.0;\n    double tolerance = 0.001;\n\n    // Combinations deg-deg, rad-rad, deg-rad, rad-de\n    BOOST_CHECK_CLOSE(distance(paris, amsterdam), expected, tolerance);\n    BOOST_CHECK_CLOSE(distance(paris_rad, amsterdam_rad), expected, tolerance);\n    BOOST_CHECK_CLOSE(distance(paris, amsterdam_rad), expected, tolerance);\n    BOOST_CHECK_CLOSE(distance(paris_rad, amsterdam), expected, tolerance);\n\n    // With specified strategy\n    vincenty<double> the_strategy;\n    BOOST_CHECK_CLOSE(distance(paris, amsterdam, the_strategy), expected, tolerance);\n    BOOST_CHECK_CLOSE(distance(paris_rad, amsterdam_rad, the_strategy), expected, tolerance);\n    BOOST_CHECK_CLOSE(distance(paris, amsterdam_rad, the_strategy), expected, tolerance);\n    BOOST_CHECK_CLOSE(bg::distance(paris_rad, amsterdam, the_strategy), expected, tolerance);\n\n\n    // Distance point-linestring, linestring-point...\n    bg::model::ll::point<bg::degree> barcelona(\n        bg::latitude<>(bg::dms<bg::north>(41, 23)),\n        bg::longitude<>(bg::dms<bg::east>(2, 11))\n        );\n\n    bg::model::linestring<bg::model::ll::point<bg::degree> > ab;\n    ab.push_back(amsterdam);\n    ab.push_back(barcelona);\n\n    // Distance paris to line amsteram-barcelona is about 113 km\n    expected = 113.168 * 1000.0;\n\n    BOOST_CHECK_CLOSE(distance(ab, paris), expected, tolerance);\n    BOOST_CHECK_CLOSE(distance(paris, ab), expected, tolerance);\n    BOOST_CHECK_CLOSE(distance(paris, ab, the_strategy), expected, tolerance);\n    BOOST_CHECK_CLOSE(distance(ab, paris, the_strategy), expected, tolerance);\n\n    // line-type in degrees, point-type in radians (supported since new distance-strategy approach)\n    BOOST_CHECK_CLOSE(distance(ab, paris_rad, the_strategy), expected, tolerance);\n\n    return 0;\n}\n", "meta": {"hexsha": "acbc765185d555792284ba120ad1a430e3153aca", "size": 3334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/gis/latlong/distance_mixed.cpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/test/gis/latlong/distance_mixed.cpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/test/gis/latlong/distance_mixed.cpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 38.3218390805, "max_line_length": 99, "alphanum_fraction": 0.7231553689, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5602674536375288}}
{"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": "/**\n * @ file norms.cc\n * @ brief NPDE homework PointEvaluationRhs code\n * @ author Christian Mitsch, Liaowang Huang (refactoring)\n * @ date 22/03/2019, 06/01/2020 (refactoring)\n * @ copyright Developed at ETH Zurich\n */\n\n#include \"pointevaluationrhs_norms.h\"\n\n#include <cmath>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\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/quad/quad.h>\n#include <lf/uscalfe/uscalfe.h>\n\nnamespace PointEvaluationRhs {\n\n/* SAM_LISTING_BEGIN_1 */\ndouble computeL2normLinearFE(const lf::assemble::DofHandler &dofh,\n                             const Eigen::VectorXd &mu) {\n  double result = 0.0;\n  //====================\n  // Your code goes here\n  //====================\n  return result;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\ndouble computeH1seminormLinearFE(const lf::assemble::DofHandler &dofh,\n                                 const Eigen::VectorXd &mu) {\n  // calculate stiffness matrix by using the already existing local assembler\n  // LinearFELaplaceElementMatrix\n  double result = 0.0;\n  //====================\n  // Your code goes here\n  //====================\n  return result;\n}\n/* SAM_LISTING_END_2 */\n\nEigen::MatrixXd MassLocalMatrixAssembler::Eval(const lf::mesh::Entity &entity) {\n  Eigen::MatrixXd result;\n  //====================\n  // Your code goes here\n  //====================\n  return result;\n}\n\n}  // namespace PointEvaluationRhs\n", "meta": {"hexsha": "2be86defa6f095f686c981468d9b1e474581a863", "size": 1484, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/PointEvaluationRhs/templates/pointevaluationrhs_norms.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/PointEvaluationRhs/templates/pointevaluationrhs_norms.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/PointEvaluationRhs/templates/pointevaluationrhs_norms.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5862068966, "max_line_length": 80, "alphanum_fraction": 0.6300539084, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.5602055493312842}}
{"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": "#include <stan/math/prim/arr.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <vector>\n\nTEST(MathFunctions, inverse_softmax_exception) {\n  std::vector<double> simplex(2);\n  std::vector<double> y(3);\n  EXPECT_THROW(stan::math::inverse_softmax<std::vector<double> >(simplex, y),\n               std::invalid_argument);\n}\n\nTEST(MathFunctions, inverse_softmax) {\n  std::vector<double> simplex(2);\n  std::vector<double> y(2);\n\n  simplex[0] = 0.2;\n  simplex[1] = 0.8;\n\n  stan::math::inverse_softmax(simplex, y);\n  EXPECT_FLOAT_EQ(log(0.2), y[0]);\n  EXPECT_FLOAT_EQ(log(0.8), y[1]);\n}\n\nTEST(MathFunctions, inverse_softmax_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  std::vector<double> simplex(2);\n  std::vector<double> y(2);\n\n  simplex[0] = nan;\n  simplex[1] = nan;\n\n  stan::math::inverse_softmax(simplex, y);\n  EXPECT_PRED1(boost::math::isnan<double>, y[0]);\n\n  EXPECT_PRED1(boost::math::isnan<double>, y[1]);\n}\n", "meta": {"hexsha": "ff28557ba340d1f842a716998b5fb7942eae1cb3", "size": 992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/arr/fun/inverse_softmax_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/prim/arr/fun/inverse_softmax_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/prim/arr/fun/inverse_softmax_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8, "max_line_length": 77, "alphanum_fraction": 0.6844758065, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.5602055415276299}}
{"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": "#include <boost/random/piecewise_linear_distribution.hpp>\n", "meta": {"hexsha": "b6c41ad42f7b5074d615a3d2d9ca62c750b39a43", "size": 58, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_random_piecewise_linear_distribution.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_random_piecewise_linear_distribution.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_random_piecewise_linear_distribution.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 29.0, "max_line_length": 57, "alphanum_fraction": 0.8620689655, "num_tokens": 11, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5601596801952319}}
{"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 \u00a9 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": "#define _USE_MATH_DEFINES\n#include <Eigen/Dense>\n#include <Eigen/Geometry> \n#include <limits>\n#include <RansacLib/ransac.h>\n\n#include <time.h> \n#include <cmath>\n#include <iostream>\n#include <numeric>\n#include \"radialpose.h\"\n#include \"misc/ransac_estimator.h\"\n#include \"misc/unit_test_misc.h\"\n\nbool test_simple_ransac_no_outliers() {\n\tMatrix<double, 2, Dynamic> x;\n\tMatrix<double, 3, Dynamic> X;\n\tCamera pose_gt;\n\n\tstd::vector<double> params2 = { -0.12, 0.034 };\n\n\tlarsson_iccv19::Solver<2, 0, true> estimator;\n\n\tgenerate_scene_and_image(100, 2, 20, 70, false, &pose_gt, &x, &X, 1.0);\n\tadd_rational_distortion(params2, 2, 0, &pose_gt, &x);\n\tadd_focal(2000.0, &pose_gt, &x);\n\tadd_noise(0.5, &x);\n\n\tRansacEstimator<larsson_iccv19::Solver<2, 0, true>> solver(x, X, estimator);\n\n\transac_lib::LORansacOptions options;\n\toptions.squared_inlier_threshold_ = 4;\n\n\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\tstd::vector<Camera>,\n\t\tRansacEstimator<larsson_iccv19::Solver<2, 0, true>>> lomsac;\n\transac_lib::RansacStatistics ransac_stats;\n\n\tCamera best_model;\n\tint num_ransac_inliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\tstd::cout << \"   ... LOMSAC found \" << num_ransac_inliers\n\t\t<< \" inliers in \" << ransac_stats.num_iterations\n\t\t<< \" iterations with an inlier ratio of \"\n\t\t<< ransac_stats.inlier_ratio << std::endl;\n\n\treturn (ransac_stats.inlier_ratio > 0.99);\n}\n\n\nbool test_simple_ransac_some_outliers() {\n\tMatrix<double, 2, Dynamic> x;\n\tMatrix<double, 3, Dynamic> X;\n\tCamera pose_gt;\n\n\tstd::vector<double> params2 = { -0.12, 0.034 };\n\n\tlarsson_iccv19::Solver<2, 0, true> estimator;\n\n\tgenerate_scene_and_image(100, 2, 20, 70, false, &pose_gt, &x, &X, 1.0);\n\tadd_rational_distortion(params2, 2, 0, &pose_gt, &x);\n\tadd_focal(2000.0, &pose_gt, &x);\n\tadd_noise(1.0, &x);\n\n\tfor (int i = 0; i < 20; ++i) {\n\t\tVector2d n; n.setRandom(); n *= 0.2 * pose_gt.focal;\n\t\tx.col(i) += n;\n\t}\n\n\tRansacEstimator<larsson_iccv19::Solver<2, 0, true>> solver(x, X, estimator);\n\n\transac_lib::LORansacOptions options;\n\toptions.squared_inlier_threshold_ = 4;\n\t\n\transac_lib::LocallyOptimizedMSAC<Camera,\n\t\tstd::vector<Camera>,\n\t\tRansacEstimator<larsson_iccv19::Solver<2, 0, true>>> lomsac;\n\transac_lib::RansacStatistics ransac_stats;\n\n\tCamera best_model;\n\tint num_ransac_inliers = lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n\n\tstd::cout << \"   ... LOMSAC found \" << num_ransac_inliers\n\t\t<< \" inliers in \" << ransac_stats.num_iterations\n\t\t<< \" iterations with an inlier ratio of \"\n\t\t<< ransac_stats.inlier_ratio << std::endl;\n\t\n\treturn (ransac_stats.inlier_ratio > .79);\n}\n\n\nint main() {\n\tstd::cout << \"Running tests...\\n\\n\";\n\tsrand((unsigned int)time(0));\n\t//srand(2.0);\n\n\tint passed = 0;\n\tint num_tests = 0;\n\n\tTEST(test_simple_ransac_no_outliers);\n\tTEST(test_simple_ransac_some_outliers);\n\n}", "meta": {"hexsha": "dca79677d479e3e6107e2e03ec23448ccb3232cf", "size": 2812, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ransac_test.cc", "max_stars_repo_name": "vlarsson/radialpose", "max_stars_repo_head_hexsha": "e620fc208f573820ade6a6fe321731d0f3eb082d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T02:48:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:28:29.000Z", "max_issues_repo_path": "ransac_test.cc", "max_issues_repo_name": "vlarsson/radialpose", "max_issues_repo_head_hexsha": "e620fc208f573820ade6a6fe321731d0f3eb082d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T16:16:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T19:39:41.000Z", "max_forks_repo_path": "ransac_test.cc", "max_forks_repo_name": "vlarsson/radialpose", "max_forks_repo_head_hexsha": "e620fc208f573820ade6a6fe321731d0f3eb082d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-11-04T21:38:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T20:41:11.000Z", "avg_line_length": 27.3009708738, "max_line_length": 92, "alphanum_fraction": 0.7115931721, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.560043553672222}}
{"text": "#include \"gtest/gtest.h\"\n#include <armadillo>\n#include \"libsvm_runner.h\"\n#include \"svm_basic.h\"\n#include \"two_e_svm_post.h\"\n#include \"two_e_svm_pre.h\"\n#include \"svm_utils.h\"\n\nusing namespace arma;\n\nTEST(SVMUtilsT7est, SqrtInvOfMatrix) {\n\tdouble epsilon = 0.05;\n\tmat A;\n\tA << 3 << 4 << 4 << endr\n\t\t\t<< 1 << 3 << 4 << endr\n\t\t\t<< 5 << 3 << 2 <<endr\n\t\t\t<< 4 << 7 << 4 << endr\n\t\t\t<< 8 << 9 << 4;\n\tA = cov(A);\n\tarma::mat sqrtInv;\n\tSvmUtils::sqrtInvMat(A, sqrtInv);\n\tASSERT_LT(abs(arma::norm(sqrtInv * sqrtInv * A) - 1), epsilon);\n}\n\nTEST(TwoESVMTest, TestPreprocessor) {\n\tSVMConfiguration svm_config;\n\tdouble epsilon = 0.05;\n\tmat posMat, negMat, SqrtInv;\n\tposMat << 1.3 << 1.5 << endr << 2.0 << 2.3 << endr << 3.0 << 4.0;\n\tnegMat << 0.2 << 0.4 << endr << 0.1 << 0.3 << endr << 0.2 << 0.5;\n\n\tvec TrainingTarget;\n\tTrainingTarget << 1 << 1 << 1 << -1 << -1 << -1;\n\n\tsvm_config.setPrediction(false); // training model\n\tsvm_config.data = arma::join_vert(posMat, negMat);\n\tsvm_config.target = TrainingTarget;\n\n\tTwoeSVMPreprocessor two_e_pre_runner;\n\ttwo_e_pre_runner.processRequest(svm_config);\n\tarma::mat my_cov = cov(posMat) + cov(negMat);\n\tSvmUtils::sqrtInvMat(my_cov, SqrtInv);\n\tASSERT_LT(abs(arma::norm(two_e_pre_runner.cov0InvSqrt - SqrtInv)), epsilon);\n}\n\n\nTEST(TwoESVMTest, TestAll) {\n\tSVMConfiguration svm_config;\n\tmat TrainingMatrix;\n\tTrainingMatrix << 0.2 << 0.4 << endr << 0.1 << 0.3 << endr << 0.2 << 0.5\n\t\t\t<< endr << 1.3 << 1.5 << endr << 2.0 << 2.3 << endr << 3.0 << 4.0;\n\n\tvec TrainingTarget;\n\tTrainingTarget << -1 << -1 << -1 << 1 << 1 << 1;\n\n\tmat A;\n\tA << -1 << -1 << endr << -0.5 << -0.5 << endr << 2 << 1.5 << endr << 3 << 3;\n\n\tsvm_config.setPrediction(false); // training model\n\tsvm_config.data = TrainingMatrix;\n\tsvm_config.target = TrainingTarget;\n\tLibSVMRunner lib_svm_runner;\n\n\tTwoeSVMPreprocessor two_e_pre_runner;\n\tTwoeSVMPostprocessor two_e_post_runner;\n\n\ttwo_e_pre_runner.processRequest(svm_config);\n\tlib_svm_runner.processRequest(svm_config);\n\ttwo_e_post_runner.processRequest(svm_config);\n\n\tsvm_config.setPrediction(true);\n\tsvm_config.data = A;\n\ttwo_e_pre_runner.processRequest(svm_config);\n\tlib_svm_runner.processRequest(svm_config);\n\n\tASSERT_EQ(-1.0, svm_config.result[0]);\n\tASSERT_EQ(-1.0, svm_config.result[1]);\n\tASSERT_EQ(1.0, svm_config.result[2]);\n\tASSERT_EQ(1.0, svm_config.result[3]);\n}\n\n", "meta": {"hexsha": "cc888d4769563cddf8cdd4b5b5fe4e6c1005961f", "size": 2317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cpp/svm/2_e_test.cpp", "max_stars_repo_name": "gmum/gmum.r", "max_stars_repo_head_hexsha": "fdf76abffb803cfffca7a33cbb319e06cfcf73d3", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-05-04T08:36:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-29T09:22:09.000Z", "max_issues_repo_path": "tests/cpp/svm/2_e_test.cpp", "max_issues_repo_name": "gmum/gmum.r", "max_issues_repo_head_hexsha": "fdf76abffb803cfffca7a33cbb319e06cfcf73d3", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": 112.0, "max_issues_repo_issues_event_min_datetime": "2015-04-30T15:28:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-22T15:48:27.000Z", "max_forks_repo_path": "tests/cpp/svm/2_e_test.cpp", "max_forks_repo_name": "gmum/gmum.r", "max_forks_repo_head_hexsha": "fdf76abffb803cfffca7a33cbb319e06cfcf73d3", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2015-05-10T06:18:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T02:24:06.000Z", "avg_line_length": 28.256097561, "max_line_length": 77, "alphanum_fraction": 0.6689684937, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.5599652149516405}}
{"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": "#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <orx/geometry/GeometryUtil.h>\n\n#include \"HelperFunctions.h\"\n\nusing namespace ORUtils;\nusing namespace orx;\n\n//#################### TESTS ####################\n\ntypedef boost::mpl::list<double,float> TS;\n\nBOOST_AUTO_TEST_SUITE(test_GeometryUtil)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_dual_quat_to_pose, T, TS)\n{\n  DualQuaternion<T> dq = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,1), T(M_PI_2));\n\n  SE3Pose pose = GeometryUtil::dual_quat_to_pose(dq);\n  Vector3f t = pose.GetT();\n  Vector3f r = GeometryUtil::to_rotation_vector(pose.GetR());\n\n  BOOST_CHECK_SMALL(length(t), 1e-4f);\n  BOOST_CHECK_SMALL(length(r - Vector3f(0,0,(float)M_PI_2)), 1e-4f);\n  BOOST_CHECK(DualQuaternion<T>::close(GeometryUtil::pose_to_dual_quat<T>(pose), dq));\n}\n\nBOOST_AUTO_TEST_CASE(test_estimate_rigid_transform)\n{\n  Eigen::Matrix3f P;\n  P(0,0) = 1; P(0,1) = 0; P(0,2) = 0;\n  P(1,0) = 0; P(1,1) = 1; P(1,2) = 0;\n  P(2,0) = 0; P(2,1) = 0; P(2,2) = 1;\n\n  Eigen::Matrix3f Q;\n  Q(0,0) = 1; Q(0,1) = 1; Q(0,2) = 0;\n  Q(1,0) = 0; Q(1,1) = 1; Q(1,2) = 0;\n  Q(2,0) = 1; Q(2,1) = 0; Q(2,2) = 0;\n\n  Eigen::Matrix4f M = GeometryUtil::estimate_rigid_transform(P, Q);\n\n  for(int i = 0; i < 3; ++i)\n  {\n    BOOST_CHECK_SMALL((M * P.col(i).homogeneous() - Q.col(i).homogeneous()).norm(), 1e-4f);\n  }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_find_best_hypothesis, T, TS)\n{\n  // Generate increasingly-large clusters of rotated poses around the z axis at 0, PI/2, PI and 3*PI/2 radians.\n  const double rotThreshold = 20 * M_PI / 180;\n  const float transThreshold = 0.05f;\n  const Vector3<T> up(0,0,1);\n\n  std::map<std::string,SE3Pose> inputPoses;\n  size_t id = 0;\n  for(float i = 0.0f; i < 4.0f; ++i)\n  {\n    for(float j = -i; j <= i; ++j)\n    {\n      float angle = static_cast<float>(i * M_PI_2 + j * M_PI / 180);\n      inputPoses.insert(std::make_pair(\n        boost::lexical_cast<std::string>(id++),\n        GeometryUtil::dual_quat_to_pose(DualQuaternion<T>::from_rotation(up, angle))\n      ));\n    }\n  }\n\n  // Find the best hypothesis from these poses, and check that it is one of the poses around 3*PI/2.\n  std::vector<SE3Pose> inliersForBestHypothesis;\n  int bestHypothesisID = boost::lexical_cast<int>(GeometryUtil::find_best_hypothesis(inputPoses, inliersForBestHypothesis, rotThreshold, transThreshold));\n  BOOST_CHECK_GT(bestHypothesisID, 1 + 3 + 5);\n\n  // Check that blending the inliers for the best hypothesis together gives the 3*PI/2 pose.\n  SE3Pose refinedPose = GeometryUtil::blend_poses(inliersForBestHypothesis);\n  BOOST_CHECK(DualQuaternion<T>::close(GeometryUtil::pose_to_dual_quat<T>(refinedPose), DualQuaternion<T>::from_rotation(up, T(3 * M_PI_2))));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_pose_to_dual_quat, T, TS)\n{\n  Vector3<T> r(0,T(M_PI_4),0);\n  Vector3<T> t(3,4,5);\n  SE3Pose pose;\n  pose.SetT(t.toFloat());\n  pose.SetR(GeometryUtil::to_rotation_matrix<T,float>(r));\n\n  DualQuaternion<T> dq = GeometryUtil::pose_to_dual_quat<T>(pose);\n\n  BOOST_CHECK_SMALL(length(dq.get_rotation() - r), T(1e-4f));\n  BOOST_CHECK_SMALL(length(dq.get_translation() - t), T(1e-4f));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_poses_are_similar, T, TS)\n{\n  const double rotThreshold = 20 * M_PI / 180;\n  const float transThreshold = 0.05f;\n\n  DualQuaternion<T> r1 = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,1), 0.0f);\n  DualQuaternion<T> r2 = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,1), 19 * (float)M_PI / 180);\n  DualQuaternion<T> r3 = DualQuaternion<T>::from_rotation(Vector3<T>(0,0,1), 21 * (float)M_PI / 180);\n\n  BOOST_CHECK(GeometryUtil::poses_are_similar(GeometryUtil::dual_quat_to_pose(r1), GeometryUtil::dual_quat_to_pose(r2), rotThreshold, transThreshold));\n  BOOST_CHECK(!GeometryUtil::poses_are_similar(GeometryUtil::dual_quat_to_pose(r1), GeometryUtil::dual_quat_to_pose(r3), rotThreshold, transThreshold));\n  BOOST_CHECK(GeometryUtil::poses_are_similar(GeometryUtil::dual_quat_to_pose(r2), GeometryUtil::dual_quat_to_pose(r3), rotThreshold, transThreshold));\n\n  DualQuaternion<T> t1 = DualQuaternion<T>::from_translation(Vector3<T>(0,0,0));\n  DualQuaternion<T> t2 = DualQuaternion<T>::from_translation(Vector3<T>(0.04f,0,0));\n  DualQuaternion<T> t3 = DualQuaternion<T>::from_translation(Vector3<T>(0.06f,0,0));\n\n  BOOST_CHECK(GeometryUtil::poses_are_similar(GeometryUtil::dual_quat_to_pose(t1), GeometryUtil::dual_quat_to_pose(t2), rotThreshold, transThreshold));\n  BOOST_CHECK(!GeometryUtil::poses_are_similar(GeometryUtil::dual_quat_to_pose(t1), GeometryUtil::dual_quat_to_pose(t3), rotThreshold, transThreshold));\n  BOOST_CHECK(GeometryUtil::poses_are_similar(GeometryUtil::dual_quat_to_pose(t2), GeometryUtil::dual_quat_to_pose(t3), rotThreshold, transThreshold));\n\n  DualQuaternion<T> t1r1 = t1 * r1, t1r3 = t1 * r3, t2r2 = t2 * r2, t3r1 = t3 * r1, t3r3 = t3 * r3;\n\n  BOOST_CHECK(GeometryUtil::poses_are_similar(GeometryUtil::dual_quat_to_pose(t1r1), GeometryUtil::dual_quat_to_pose(t2r2), rotThreshold, transThreshold));\n  BOOST_CHECK(!GeometryUtil::poses_are_similar(GeometryUtil::dual_quat_to_pose(t1r1), GeometryUtil::dual_quat_to_pose(t1r3), rotThreshold, transThreshold));\n  BOOST_CHECK(!GeometryUtil::poses_are_similar(GeometryUtil::dual_quat_to_pose(t1r1), GeometryUtil::dual_quat_to_pose(t3r1), rotThreshold, transThreshold));\n  BOOST_CHECK(!GeometryUtil::poses_are_similar(GeometryUtil::dual_quat_to_pose(t1r1), GeometryUtil::dual_quat_to_pose(t3r3), rotThreshold, transThreshold));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_to_rotation_matrix, T, TS)\n{\n  const T TOL = static_cast<T>(1e-4);\n\n  Matrix3<T> I;\n  I.setIdentity();\n  check_close(GeometryUtil::to_rotation_matrix(Vector3<T>(T(0))), I, TOL);\n\n  Vector3<T> r(static_cast<T>(M_PI) / 4.0f, 0.0f, 0.0f);\n  const T root2inv = static_cast<T>(1.0 / sqrt(2.0));\n  Matrix3<T> R(T(1), T(0), T(0), T(0), root2inv, root2inv, T(0), -root2inv, root2inv);\n  check_close(GeometryUtil::to_rotation_matrix(r), R, TOL);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_to_rotation_vector, T, TS)\n{\n  const T TOL = static_cast<T>(1e-4);\n\n  Matrix3<T> I;\n  I.setIdentity();\n  check_close(GeometryUtil::to_rotation_vector(I), Vector3<T>(T(0)), TOL);\n\n  const T root2inv = static_cast<T>(1.0 / sqrt(2.0));\n  Matrix3<T> R(T(1), T(0), T(0), T(0), root2inv, root2inv, T(0), -root2inv, root2inv);\n  Vector3<T> r(static_cast<T>(M_PI) / 4.0f, 0.0f, 0.0f);\n  check_close(GeometryUtil::to_rotation_vector(R), r, TOL);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "2bc44941a0cf5ed134ca5d97e572138aa52ad057", "size": 6504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/orx/test_GeometryUtil.cpp", "max_stars_repo_name": "torrvision/spaint", "max_stars_repo_head_hexsha": "9cac8100323ea42fe439f66407b832b88f72d2fd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 197.0, "max_stars_repo_stars_event_min_datetime": "2015-10-01T07:23:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:02:31.000Z", "max_issues_repo_path": "tests/unit/orx/test_GeometryUtil.cpp", "max_issues_repo_name": "torrvision/spaint", "max_issues_repo_head_hexsha": "9cac8100323ea42fe439f66407b832b88f72d2fd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2016-03-26T13:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T09:13:49.000Z", "max_forks_repo_path": "tests/unit/orx/test_GeometryUtil.cpp", "max_forks_repo_name": "torrvision/spaint", "max_forks_repo_head_hexsha": "9cac8100323ea42fe439f66407b832b88f72d2fd", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2015-10-03T07:14:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T08:58:18.000Z", "avg_line_length": 41.6923076923, "max_line_length": 156, "alphanum_fraction": 0.7201722017, "num_tokens": 2187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5599569674634408}}
{"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_LOG1P_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_LOG1P_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/function/simd/divides.hpp>\n#include <boost/simd/function/simd/is_nez.hpp>\n#include <boost/simd/function/simd/log.hpp>\n#include <boost/simd/function/simd/minus.hpp>\n#include <boost/simd/function/simd/minusone.hpp>\n#include <boost/simd/function/simd/oneplus.hpp>\n#include <boost/simd/function/simd/seladd.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/function/simd/if_else.hpp>\n#include <boost/simd/function/simd/is_equal.hpp>\n#endif\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n\n  BOOST_DISPATCH_OVERLOAD ( log1p_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator()( const A0& a0) BOOST_NOEXCEPT\n    {\n      A0 u = oneplus(a0);\n      A0 r = seladd(is_nez(u),\n                    log(u),\n                    (a0-minusone(u))/u); // cancels errors with IEEE arithmetic\n#ifndef BOOST_SIMD_NO_INFINITIES\n      r = if_else(is_equal(u, Inf<A0>()),u, r);\n#endif\n      return r;\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "3a403f50c1cb402e2867c64600fa7f9deafef2bc", "size": 1808, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/function/log1p.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/log1p.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/log1p.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2857142857, "max_line_length": 100, "alphanum_fraction": 0.5973451327, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5599486668320672}}
{"text": "\n\n//#define _DEBUG\n#define _U_AMOEBA_\n\n#ifdef _U_AMOEBA_\n#include \"amoeba.hpp\"\n\n#ifdef _ALGEBRA_TOOLS_\n#else\n#include \"algebraTools.hpp\"\n#endif\n\n#ifdef _WEIGHTED_MAT_\n#else\n#include \"weightedMat.hpp\"\n#endif\n\n#ifdef _LIE_ALGEBRA_\n#else\n#include \"lieAlgebra.cpp\"\n#endif\n\n#include <iostream>\n#include <cmath>\n#include <cstdlib>\n#include <complex>\n#include <armadillo>\n\nusing namespace algebraTools;\nusing std::vector;\nusing std::ofstream;\nusing std::complex;\n\nusing namespace arma;\n\n//dimension\nclass UAmoeba: public Amoeba<vec, cx_mat>\n{\npublic:\n    UAmoeba(long maxIters,\n            int nGridPoints,\n            double precision,\n            int matSize,\n            int lieDimension,\n            vector<weightedMat> *lieBasis)\n    : Amoeba<vec, cx_mat>( maxIters,  nGridPoints,  precision)\n    {\n\n        //int matSize = number of rows in matrix\n        //int lieDimension = number of basis vectors in lie algebra\n        //int nGridPoints = number of guess points for the amoeba routine\n\n        /*\n          to do replace with parameter object\n        */\n        this->matSize = matSize;\n        this->basis = lieBasis;\n        this->gridSize = 1000;\n        this->gridSizeOld = 1000;\n        this->halfGridSize = 500;\n        this->h = (1 / static_cast<double>(gridSize));\n        this->idMat = eye<cx_mat>(matSize,matSize);\n        this->lieDimension = lieDimension;\n        this->globalEnergyOld = 10000000;\n\n    }\n\n    ~UAmoeba();\n\n    //Pauli pauliBasis;\n    void curvePrint(vec bestVector);\n    void curvePrint();\n\n    void newBoundary(cx_mat& newBound);\n    void curveSeeder(vector<vec> &newGuess, int nGridPoints, cx_mat sU);\n    double getEnergy();\n    virtual cx_mat curveFunc(vec kVector);\n    virtual double objectFunc(cx_mat A);\n\nprotected:\n    vector<weightedMat> *basis;\n\n    int matSize;\n    int gridSize, halfGridSize, gridSizeOld;\n    int lieDimension;\n\n    cx_double imagI = cx_double(0.0, 1.0);\n\n    double globalEnergyOld;\n    double globalEnergy;\n    double h;\n\n    cx_mat idMat;\n\n    ofstream kFile;\n    //ofstream eFile;\n    ofstream xFile;\n\n    //function describing the geodesic equations\n    virtual void amoebaEnergy();\n    virtual void amoebaRestart();\n\n    cx_mat matrixExp(vec &K, double scalar);\n\n    double cost(int index);\n    double invCost(int index);\n\n    double energyExtra(cx_mat A, cx_mat B);\n    void lieFunction(vec &kVector);\n    void curveCorrect(cx_mat &A, vec &v);\n};\n\n#include \"UAmoeba.cpp\"\n#endif\n", "meta": {"hexsha": "20df5fdf024f6ce9f00868143507c6f51fd20a3d", "size": 2448, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/UAmoeba.hpp", "max_stars_repo_name": "Swaddle/qGeod", "max_stars_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/UAmoeba.hpp", "max_issues_repo_name": "Swaddle/qGeod", "max_issues_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/UAmoeba.hpp", "max_forks_repo_name": "Swaddle/qGeod", "max_forks_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1034482759, "max_line_length": 73, "alphanum_fraction": 0.6605392157, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.5599486621903119}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_CCMATH_ROUND_HPP\n#define BOOST_MATH_CCMATH_ROUND_HPP\n\n#include <cmath>\n#include <type_traits>\n#include <stdexcept>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n#include <boost/math/ccmath/abs.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/modf.hpp>\n\nnamespace boost::math::ccmath {\n\nnamespace detail {\n\n// Computes the nearest integer value to arg (in floating-point format), \n// rounding halfway cases away from zero, regardless of the current rounding mode.\ntemplate <typename T>\ninline constexpr T round_impl(T arg) noexcept\n{\n    T iptr = 0;\n    const T x = boost::math::ccmath::modf(arg, &iptr);\n    constexpr T half = T(1)/2;\n\n    if(x >= half && iptr > 0)\n    {\n        return iptr + 1;\n    }\n    else if(boost::math::ccmath::abs(x) >= half && iptr < 0)\n    {\n        return iptr - 1;\n    }\n    else\n    {\n        return iptr;\n    }\n}\n\ntemplate <typename ReturnType, typename T>\ninline constexpr ReturnType int_round_impl(T arg)\n{\n    const T rounded_arg = round_impl(arg);\n\n    if(rounded_arg > static_cast<T>((std::numeric_limits<ReturnType>::max)()))\n    {\n        if constexpr (std::is_same_v<ReturnType, long long>)\n        {\n            throw std::domain_error(\"Rounded value cannot be represented by a long long type without overflow\");\n        }\n        else\n        {\n            throw std::domain_error(\"Rounded value cannot be represented by a long type without overflow\");\n        }\n    }\n    else\n    {\n        return static_cast<ReturnType>(rounded_arg);\n    }\n}\n\n} // Namespace detail\n\ntemplate <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>\ninline constexpr Real round(Real arg) noexcept\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(arg))\n    {\n        return boost::math::ccmath::abs(arg) == Real(0) ? arg :\n               boost::math::ccmath::isinf(arg) ? arg :\n               boost::math::ccmath::isnan(arg) ? arg :\n               boost::math::ccmath::detail::round_impl(arg);\n    }\n    else\n    {\n        using std::round;\n        return round(arg);\n    }\n}\n\ntemplate <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>\ninline constexpr double round(Z arg) noexcept\n{\n    return boost::math::ccmath::round(static_cast<double>(arg));\n}\n\ninline constexpr float roundf(float arg) noexcept\n{\n    return boost::math::ccmath::round(arg);\n}\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline constexpr long double roundl(long double arg) noexcept\n{\n    return boost::math::ccmath::round(arg);\n}\n#endif\n\ntemplate <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>\ninline constexpr long lround(Real arg)\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(arg))\n    {\n        return boost::math::ccmath::abs(arg) == Real(0) ? 0l :\n               boost::math::ccmath::isinf(arg) ? 0l :\n               boost::math::ccmath::isnan(arg) ? 0l :\n               boost::math::ccmath::detail::int_round_impl<long>(arg);\n    }\n    else\n    {\n        using std::lround;\n        return lround(arg);\n    }\n}\n\ntemplate <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>\ninline constexpr long lround(Z arg)\n{\n    return boost::math::ccmath::lround(static_cast<double>(arg));\n}\n\ninline constexpr long lroundf(float arg)\n{\n    return boost::math::ccmath::lround(arg);\n}\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline constexpr long lroundl(long double arg)\n{\n    return boost::math::ccmath::lround(arg);\n}\n#endif\n\ntemplate <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>\ninline constexpr long long llround(Real arg)\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(arg))\n    {\n        return boost::math::ccmath::abs(arg) == Real(0) ? 0ll :\n               boost::math::ccmath::isinf(arg) ? 0ll :\n               boost::math::ccmath::isnan(arg) ? 0ll :\n               boost::math::ccmath::detail::int_round_impl<long long>(arg);\n    }\n    else\n    {\n        using std::llround;\n        return llround(arg);\n    }\n}\n\ntemplate <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>\ninline constexpr long llround(Z arg)\n{\n    return boost::math::ccmath::llround(static_cast<double>(arg));\n}\n\ninline constexpr long long llroundf(float arg)\n{\n    return boost::math::ccmath::llround(arg);\n}\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline constexpr long long llroundl(long double arg)\n{\n    return boost::math::ccmath::llround(arg);\n}\n#endif\n\n} // Namespaces\n\n#endif // BOOST_MATH_CCMATH_ROUND_HPP\n", "meta": {"hexsha": "5c8c80eb9fa9c0e6b76a133cf108c4fd258d6acd", "size": 4736, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/round.hpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "include/boost/math/ccmath/round.hpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "include/boost/math/ccmath/round.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": 26.7570621469, "max_line_length": 112, "alphanum_fraction": 0.6619510135, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5599486519068025}}
{"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": "//\n// Copyright 2012 Chung-Lin Wen, Davide Anastasia\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#ifndef BOOST_GIL_EXTENSION_TOOLBOX_COLOR_SPACES_XYZ_HPP\n#define BOOST_GIL_EXTENSION_TOOLBOX_COLOR_SPACES_XYZ_HPP\n\n#include <boost/gil/color_convert.hpp>\n#include <boost/gil/detail/mp11.hpp>\n#include <boost/gil/typedefs.hpp>\n\nnamespace boost {\nnamespace gil {\n\n/// \\addtogroup ColorNameModel\n/// \\{\nnamespace xyz_color_space {\n/// \\brief x Color Component\nstruct x_t {};\n/// \\brief y Color Component\nstruct y_t {};\n/// \\brief z Color Component\nstruct z_t {};\n} // namespace xyz_color_space\n/// \\}\n\n/// \\ingroup ColorSpaceModel\nusing xyz_t = mp11::mp_list<xyz_color_space::x_t, xyz_color_space::y_t,\n                            xyz_color_space::z_t>;\n\n/// \\ingroup LayoutModel\nusing xyz_layout_t = layout<xyz_t>;\n\nBOOST_GIL_DEFINE_ALL_TYPEDEFS(32f, float32_t, xyz)\n\n/// \\ingroup ColorConvert\n/// \\brief RGB to XYZ\n/// <a\n/// href=\"http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html\">Link</a>\n/// \\note rgb_t is assumed to be sRGB D65\ntemplate <> struct default_color_converter_impl<rgb_t, xyz_t> {\nprivate:\n  BOOST_FORCEINLINE\n  float32_t inverse_companding(float32_t sample) const {\n    if (sample > 0.04045f) {\n      return powf(((sample + 0.055f) / 1.055f), 2.4f);\n    } else {\n      return (sample / 12.92f);\n    }\n  }\n\npublic:\n  template <typename P1, typename P2>\n  void operator()(const P1 &src, P2 &dst) const {\n    using namespace xyz_color_space;\n\n    float32_t red(inverse_companding(\n        channel_convert<float32_t>(get_color(src, red_t()))));\n    float32_t green(inverse_companding(\n        channel_convert<float32_t>(get_color(src, green_t()))));\n    float32_t blue(inverse_companding(\n        channel_convert<float32_t>(get_color(src, blue_t()))));\n\n    get_color(dst, x_t()) =\n        red * 0.4124564f + green * 0.3575761f + blue * 0.1804375f;\n    get_color(dst, y_t()) =\n        red * 0.2126729f + green * 0.7151522f + blue * 0.0721750f;\n    get_color(dst, z_t()) =\n        red * 0.0193339f + green * 0.1191920f + blue * 0.9503041f;\n  }\n};\n\n/// \\ingroup ColorConvert\n/// \\brief XYZ to RGB\ntemplate <> struct default_color_converter_impl<xyz_t, rgb_t> {\nprivate:\n  BOOST_FORCEINLINE\n  float32_t companding(float32_t sample) const {\n    if (sample > 0.0031308f) {\n      return (1.055f * powf(sample, 1.f / 2.4f) - 0.055f);\n    } else {\n      return (12.92f * sample);\n    }\n  }\n\npublic:\n  template <typename P1, typename P2>\n  void operator()(const P1 &src, P2 &dst) const {\n    using namespace xyz_color_space;\n\n    // Note: ideally channel_convert should be compiled out, because xyz_t\n    // is float32_t natively only\n    float32_t x(channel_convert<float32_t>(get_color(src, x_t())));\n    float32_t y(channel_convert<float32_t>(get_color(src, y_t())));\n    float32_t z(channel_convert<float32_t>(get_color(src, z_t())));\n\n    get_color(dst, red_t()) =\n        channel_convert<typename color_element_type<P2, red_t>::type>(\n            companding(x * 3.2404542f + y * -1.5371385f + z * -0.4985314f));\n    get_color(dst, green_t()) =\n        channel_convert<typename color_element_type<P2, green_t>::type>(\n            companding(x * -0.9692660f + y * 1.8760108f + z * 0.0415560f));\n    get_color(dst, blue_t()) =\n        channel_convert<typename color_element_type<P2, blue_t>::type>(\n            companding(x * 0.0556434f + y * -0.2040259f + z * 1.0572252f));\n  }\n};\n\n} // namespace gil\n} // namespace boost\n\n#endif // BOOST_GIL_EXTENSION_TOOLBOX_COLOR_SPACES_XYZ_HPP\n", "meta": {"hexsha": "2dc36dbcf4cf86a7a2b19d5bead52ac497c7a168", "size": 3616, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/extension/toolbox/color_spaces/xyz.hpp", "max_stars_repo_name": "sdebionne/gil-reformated", "max_stars_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/gil/extension/toolbox/color_spaces/xyz.hpp", "max_issues_repo_name": "sdebionne/gil-reformated", "max_issues_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/gil/extension/toolbox/color_spaces/xyz.hpp", "max_forks_repo_name": "sdebionne/gil-reformated", "max_forks_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1724137931, "max_line_length": 84, "alphanum_fraction": 0.6808628319, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.559948645265052}}
{"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 \u22c9 R3\n *\n * Memory layout\n * -------------\n * Group:    x y z qx qy qz qw\n * Tangent:  vx vy vz \u03a9x \u03a9y \u03a9z\n *\n * Lie group Matrix form\n * ---------------------\n * [ R T ]\n * [ 0 1 ]\n *\n * where R \u2208 SO(3) and T = [x y z] \u2208 R3\n *\n * Lie algebra Matrix form\n * -----------------------\n * [  0 -\u03a9z  \u03a9y vx]\n * [  \u03a9z  0 -\u03a9x vy]\n * [ -\u03a9y \u03a9x   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 < \u03a9x \u03a9y \u03a9z <= 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": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/data_structures/array/pascals_triangle.hpp\"\n\nBOOST_AUTO_TEST_SUITE(TestPascalTriangles)\n\nBOOST_AUTO_TEST_CASE(invalid_row_num)\n{\n    const std::vector<std::vector<int>> expected;\n    BOOST_CHECK(expected == Algo::DS::Array::PascalsTriangle::Generate(-1));\n    BOOST_CHECK(expected == Algo::DS::Array::PascalsTriangle::Generate(0));\n}\n\nBOOST_AUTO_TEST_CASE(valid_row_num)\n{\n    {\n        const std::vector<std::vector<int>> expected = {{1}};\n        BOOST_CHECK(expected == Algo::DS::Array::PascalsTriangle::Generate(1));\n    }\n\n    {\n        const std::vector<std::vector<int>> expected = {\n            {1},\n            {1, 1}\n        };\n\n        BOOST_CHECK(expected == Algo::DS::Array::PascalsTriangle::Generate(2));\n    }\n\n    {\n        const std::vector<std::vector<int>> expected = {\n            {1},\n            {1, 1},\n            {1, 2, 1}\n        };\n\n        BOOST_CHECK(expected == Algo::DS::Array::PascalsTriangle::Generate(3));\n    }\n\n    {\n        const std::vector<std::vector<int>> expected = {\n            {1},\n            {1, 1},\n            {1, 2, 1},\n            {1, 3, 3, 1}\n        };\n\n        BOOST_CHECK(expected == Algo::DS::Array::PascalsTriangle::Generate(4));\n    }\n\n    {\n        const std::vector<std::vector<int>> expected = {\n            {1},\n            {1, 1},\n            {1, 2, 1},\n            {1, 3, 3, 1},\n            {1, 4, 6, 4, 1}\n        };\n\n        BOOST_CHECK(expected == Algo::DS::Array::PascalsTriangle::Generate(5));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(rowgen_invalid_row_num) {\n    const std::vector<int> expected;\n    BOOST_CHECK(expected == Algo::DS::Array::PascalsTriangle::GenerateRow(-1));\n    BOOST_CHECK(expected == Algo::DS::Array::PascalsTriangle::GenerateRow(-85));\n}\n\nBOOST_AUTO_TEST_CASE(rowgen_valid_row_num) {\n    {\n        const std::vector<int> expected = {1};\n        BOOST_CHECK(expected ==\n                    Algo::DS::Array::PascalsTriangle::GenerateRow(0));\n    }\n\n    {\n        const std::vector<int> expected = {1, 1};\n        BOOST_CHECK(expected ==\n                    Algo::DS::Array::PascalsTriangle::GenerateRow(1));\n    }\n\n    {\n        const std::vector<int> expected = {1, 2, 1};\n        BOOST_CHECK(expected ==\n                    Algo::DS::Array::PascalsTriangle::GenerateRow(2));\n    }\n\n    {\n        const std::vector<int> expected = {1, 4, 6, 4, 1};\n        BOOST_CHECK(expected ==\n                    Algo::DS::Array::PascalsTriangle::GenerateRow(4));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4e0d7618fdd58299179828726e1f29761b4b0dd3", "size": 2525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/data_structures/array/test_pascals_triangle.cpp", "max_stars_repo_name": "iamantony/CppNotes", "max_stars_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T14:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T09:51:43.000Z", "max_issues_repo_path": "test/algorithms/data_structures/array/test_pascals_triangle.cpp", "max_issues_repo_name": "iamantony/CppNotes", "max_issues_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T07:38:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-02T11:00:58.000Z", "max_forks_repo_path": "test/algorithms/data_structures/array/test_pascals_triangle.cpp", "max_forks_repo_name": "iamantony/CppNotes", "max_forks_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-11T14:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T08:53:50.000Z", "avg_line_length": 26.3020833333, "max_line_length": 80, "alphanum_fraction": 0.5524752475, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.5599355180423091}}
{"text": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <math/rev/scal/fun/nan_util.hpp>\n#include <math/rev/scal/util.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/zeta.hpp>\n\nTEST(AgradRev, digamma) {\n  AVAR a = 0.5;\n  AVAR f = digamma(a);\n  EXPECT_FLOAT_EQ(boost::math::digamma(0.5), f.val());\n\n  AVEC x = createAVEC(a);\n  VEC grad_f;\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(4.9348022005446793094, grad_f[0]);\n}\n\nnamespace {\nstruct digamma_fun {\n  template <typename T0>\n  inline T0 operator()(const T0& arg1) const {\n    return digamma(arg1);\n  }\n};\n}  // namespace\n\nTEST(AgradRev, digamma_NaN) {\n  digamma_fun digamma_;\n  test_nan(digamma_, false, true);\n}\n\nTEST(AgradRev, check_varis_on_stack_10) {\n  AVAR a = 0.5;\n  test::check_varis_on_stack(stan::math::digamma(a));\n}\n", "meta": {"hexsha": "d49658b46836b6b2620117739b0a4e5e9eb6a2cb", "size": 836, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/rev/scal/fun/digamma_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/rev/scal/fun/digamma_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/rev/scal/fun/digamma_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5945945946, "max_line_length": 54, "alphanum_fraction": 0.7045454545, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5598874324084333}}
{"text": "/*\n * Copyright 2020 \u00a9 Centre Interdisciplinaire de d\u00e9veloppement en Cartographie des Oc\u00e9ans (CIDCO), Tous droits r\u00e9serv\u00e9s\n */\n\n/* \n * File:   CartesianToGeodeticConversionTest.hpp\n * Author: jordan\n */\n\n#ifndef CARTESIANTOGEODETICCONVERSIONTEST_HPP\n#define CARTESIANTOGEODETICCONVERSIONTEST_HPP\n\n#include \"catch.hpp\"\n#include <Eigen/Dense>\n#include \"../src/Position.hpp\"\n#include \"../src/math/CartesianToGeodeticFukushima.hpp\"\n#include \"../src/math/CoordinateTransform.hpp\"\n#include \"../src/utils/Constants.hpp\"\n\nTEST_CASE(\"Center of the Earth Degenerate Cases of Cartesian To Geodetic Conversion Test\") {\n    double latitudeEps = 1e-9;\n    double longitudeEps = 1e-9;\n    double altitudeEps = 1e-6;\n\n    unsigned int numberOfIterations = 1;\n    CartesianToGeodeticFukushima cart2geo(numberOfIterations);\n\n    // Begin center of earth test\n    Position centerOfEarth(0, 0.0, 0.0, 0.0);\n\n    Eigen::Vector3d centerOfEarthTRF;\n    CoordinateTransform::getPositionECEF(centerOfEarthTRF, centerOfEarth);\n\n\n    Position testCenterOfEarthPosition(0,0.0,0.0,0.0);\n    cart2geo.ecefToLongitudeLatitudeElevation(centerOfEarthTRF, testCenterOfEarthPosition);\n\n    REQUIRE(std::abs(testCenterOfEarthPosition.getLatitude() - centerOfEarth.getLatitude()) < latitudeEps);\n    REQUIRE(std::abs(testCenterOfEarthPosition.getLongitude() - centerOfEarth.getLongitude()) < longitudeEps);\n    REQUIRE(std::abs(testCenterOfEarthPosition.getEllipsoidalHeight() - centerOfEarth.getEllipsoidalHeight()) < altitudeEps);\n}\n\nTEST_CASE(\"Equator Degenerate Cases of Cartesian To Geodetic Conversion Test\") {\n\n    double longitudeEpsilon = 1e-12;\n    double latitudeEpsilon = 1e-12;\n\n    int longitudeIncrement = 1;\n\n    bool testFail = false;\n\n    Position p(0,0.0,0.0,0.0);\n    Eigen::Vector3d pTRF;\n    Position testPosition(0,0.0,0.0,0.0); // must be equal to p in order for test to pass\n\n    unsigned int numberOfIterations = 1;\n    CartesianToGeodeticFukushima cart2geo(numberOfIterations);\n\n    for (int longitude = -180; longitude <= 180; longitude += longitudeIncrement) {\n        if (testFail) {\n            break;\n        }\n\n        p.setLatitude(0.0);\n        p.setLongitude(longitude);\n        p.setEllipsoidalHeight(0);\n\n        CoordinateTransform::getPositionECEF(pTRF, p);\n\n        cart2geo.ecefToLongitudeLatitudeElevation(pTRF, testPosition);\n\n        if (std::abs(longitude - testPosition.getLongitude()) > longitudeEpsilon) {\n            testFail = true;\n        }\n\n        if (std::abs(0.0 - testPosition.getLatitude()) > latitudeEpsilon) {\n            testFail = true;\n        }\n    }\n\n    if (testFail) {\n        std::cout << \"Equator degenerate case for Cartesian To Geodetic conversion test:\" << std::endl;\n        std::cout << \"What is expected:\" << std::endl;\n        std::cout << p << std::endl;\n        std::cout << \"What is obtained:\" << std::endl;\n        std::cout << testPosition << std::endl;\n    }\n\n}\n\nTEST_CASE(\"North and South Pole Degenerate Cases of Cartesian To Geodetic Conversion Test\") {\n\n    double latitudeEps = 1e-9;\n    double longitudeEps = 1e-9;\n    double altitudeEps = 1e-6;\n\n    unsigned int numberOfIterations = 1;\n    CartesianToGeodeticFukushima cart2geo(numberOfIterations);\n\n    // Begin north pole test\n    Position northPole(0, 90.0, 0.0, 0);\n\n    Eigen::Vector3d northPoleTRF;\n    CoordinateTransform::getPositionECEF(northPoleTRF, northPole);\n\n\n    Position testNorthPolePosition(0,0.0,0.0,0.0);\n    cart2geo.ecefToLongitudeLatitudeElevation(northPoleTRF, testNorthPolePosition);\n\n    REQUIRE(std::abs(testNorthPolePosition.getLatitude() - northPole.getLatitude()) < latitudeEps);\n    REQUIRE(std::abs(testNorthPolePosition.getLongitude() - northPole.getLongitude()) < longitudeEps);\n    REQUIRE(std::abs(testNorthPolePosition.getEllipsoidalHeight() - northPole.getEllipsoidalHeight()) < altitudeEps);\n\n    // Begin south pole test\n    Position southPole(0, -90.0, 0.0, 0);\n\n    Eigen::Vector3d southPoleTRF;\n    CoordinateTransform::getPositionECEF(southPoleTRF, southPole);\n\n    Position testSouthPolePosition(0,0.0,0.0,0.0);\n    cart2geo.ecefToLongitudeLatitudeElevation(southPoleTRF, testSouthPolePosition);\n\n    REQUIRE(std::abs(testSouthPolePosition.getLatitude() - southPole.getLatitude()) < latitudeEps);\n    REQUIRE(std::abs(testSouthPolePosition.getLongitude() - southPole.getLongitude()) < longitudeEps);\n    REQUIRE(std::abs(testSouthPolePosition.getEllipsoidalHeight() - southPole.getEllipsoidalHeight()) < altitudeEps);\n\n}\n\nTEST_CASE(\"Cartesian To Geodetic Conversion Test\") {\n\n    double longitudeEpsilon = 1e-13;\n    double latitudeEpsilon = 1e-13;\n    double heightEpsilon = 1e-7;\n\n    std::cout << std::setprecision(15) << std::endl;\n\n    unsigned int numberOfIterations = 2;\n    CartesianToGeodeticFukushima cart2geo(numberOfIterations);\n\n    int longitudeIncrement = 2;\n    int latitudeIncrement = 2;\n    int heightIncrement = 50;\n\n    double a = M_PI_2;\n\n    if (a > M_PI_2) {\n        std::cout << \"a > PI/2\" << std::endl;\n    }\n    if (-a < -M_PI_2) {\n        std::cout << \"-a < -PI/2\" << std::endl;\n    }\n\n    bool testFail = false;\n\n\n    Position p(0,0.0,0.0,0.0);\n    Eigen::Vector3d pTRF;\n    Position testPosition(0,0.0,0.0,0.0);\n\n    for (int longitude = -180; longitude <= 180; longitude += longitudeIncrement) {\n        if (testFail) {\n            break;\n        }\n\n        for (int latitude = -89; latitude <= 89; latitude += latitudeIncrement) {\n            if (testFail) {\n                break;\n            }\n\n            for (int height = -1000; height <= 1000; height += heightIncrement) {\n                if (testFail) {\n                    break;\n                }\n\n                p.setLatitude(latitude);\n                p.setLongitude(longitude);\n                p.setEllipsoidalHeight(height);\n\n                CoordinateTransform::getPositionECEF(pTRF, p);\n\n                cart2geo.ecefToLongitudeLatitudeElevation(pTRF, testPosition);\n\n                if (std::abs(testPosition.getLatitude() - latitude) > latitudeEpsilon) {\n                    std::cout << \"Latitude mismatch for cartesian to geodetic conversion\" << std::endl;\n                    std::cout << testPosition.getLatitude() << \" should be \" << latitude << std::endl;\n                    testFail = true;\n                }\n\n                if (std::abs(testPosition.getLongitude() - longitude) > longitudeEpsilon) {\n                    std::cout << \"Longitude mismatch for cartesian to geodetic conversion\" << std::endl;\n                    std::cout << testPosition.getLongitude() << \" should be \" << longitude << std::endl;\n                    testFail = true;\n                }\n\n                if (std::abs(testPosition.getEllipsoidalHeight() - height) > heightEpsilon) {\n                    std::cout << \"Height mismatch for cartesian to geodetic conversion\" << std::endl;\n                    std::cout << testPosition.getEllipsoidalHeight() << \" should be \" << height << std::endl;\n                    testFail = true;\n                }\n            } // height\n        } // latitude\n    } // longitude\n\n    if (testFail) {\n        std::cout << \"Cartesian To Geodetic Conversion Test Failure:\" << std::endl;\n        std::cout << \"Expected position:\" << std::endl;\n        std::cout << p << std::endl;\n        std::cout << \"What is obtained:\" << std::endl;\n        std::cout << testPosition << std::endl;\n    }\n\n    REQUIRE(!testFail);\n}\n\nTEST_CASE(\"test the ecef conversion to longitude latitude elevation\")\n{\n    Position result(0,0.0,0.0,0.0);\n    Eigen::Vector3d ecefPosition(0.0,0.0,0.0);\n    CartesianToGeodeticFukushima convertTest(0);\n    convertTest.ecefToLongitudeLatitudeElevation(ecefPosition,result);\n    REQUIRE(abs(result.getLatitude()-(0.0*R2D))<1e-10);\n    REQUIRE(abs(result.getLongitude()-(0.0*R2D))<1e-10);\n    REQUIRE(abs(result.getEllipsoidalHeight()-(0.0))<1e-10);\n    ecefPosition(0) = 0.0;\n    ecefPosition(1) = 0.0;\n    ecefPosition(2) = 1.0;\n    convertTest.ecefToLongitudeLatitudeElevation(ecefPosition,result);\n    REQUIRE(abs(result.getLatitude()-(M_PI_2*R2D))<1e-10);\n    REQUIRE(abs(result.getLongitude()-(0.0*R2D))<1e-10);\n    REQUIRE(abs(result.getEllipsoidalHeight()-(1-(a_wgs84*(std::sqrt(1-e2_wgs84)))))<1e-10);\n    ecefPosition(0) = 0.0;\n    ecefPosition(1) = 0.0;\n    ecefPosition(2) = -1.0;\n    convertTest.ecefToLongitudeLatitudeElevation(ecefPosition,result);\n    REQUIRE(abs(result.getLatitude()-(-M_PI_2*R2D))<1e-10);\n    REQUIRE(abs(result.getLongitude()-(0.0*R2D))<1e-10);\n    REQUIRE(abs(result.getEllipsoidalHeight()-(1-(a_wgs84*(std::sqrt(1-e2_wgs84)))))<1e-10);\n}\n\n#endif /* CARTESIANTOGEODETICCONVERSIONTEST_HPP */\n\n", "meta": {"hexsha": "734bf7e30ceebc73b99500a741f73e0ce13757ae", "size": 8613, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/CartesianToGeodeticConversionTest.hpp", "max_stars_repo_name": "JordanMcManus/MBES-lib", "max_stars_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T14:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T06:44:37.000Z", "max_issues_repo_path": "test/CartesianToGeodeticConversionTest.hpp", "max_issues_repo_name": "JordanMcManus/MBES-lib", "max_issues_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T13:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T19:44:23.000Z", "max_forks_repo_path": "test/CartesianToGeodeticConversionTest.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": 35.5909090909, "max_line_length": 125, "alphanum_fraction": 0.6528503425, "num_tokens": 2355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959545, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5598874273902092}}
{"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": "#include <crave/SystemC.hpp>\n#include <crave/ConstrainedRandom.hpp>\n#include <systemc.h>\n#include <boost/timer.hpp>\n\nusing crave::rand_obj;\nusing crave::randv;\nusing sc_dt::sc_bv;\nusing sc_dt::sc_uint;\n\nstruct ALU12 : public rand_obj {\n  randv< sc_bv<2> >  op ;\n  randv< sc_uint<12> > a, b ;\n\n  ALU12()\n  : op(this), a(this), b(this)\n  {\n    constraint ( (op() != 0x0) || ( 4095 >= a() + b() ) );\n    constraint ( (op() != 0x1) || ((4095 >= a() - b()) && (b() <= a()) ) );\n    constraint ( (op() != 0x2) || ( 4095 >= a() * b() ) );\n    constraint ( (op() != 0x3) || ( b() != 0        ) );\n  }\n\n  friend std::ostream & operator<< (std::ostream & o, ALU12 const & alu) \n  {\n    o << alu.op \n      << ' ' << alu.a\n      << ' ' << alu.b\n      ;\n    return o;\n  }\n};\n\nint sc_main (int argc, char** argv)\n{\n  boost::timer timer;\n  ALU12 c;\n  c.next();\n  std::cout << \"first: \" << timer.elapsed() << \"\\n\";\n  for (int i=0; i<1000; ++i) {\n    c.next();\n  }\n  std::cout << \"complete: \" << timer.elapsed() << \"\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "43770f3dcb080422a5c30d56a5204dc1e674bd4e", "size": 1018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ALU/ALU12.cpp", "max_stars_repo_name": "agra-uni-bremen/crave-bundle", "max_stars_repo_head_hexsha": "70082a8a62a43f7a6683cb3e0b2bc23c39eaf938", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-05-11T02:47:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T12:02:53.000Z", "max_issues_repo_path": "examples/ALU/ALU12.cpp", "max_issues_repo_name": "agra-uni-bremen/crave-bundle", "max_issues_repo_head_hexsha": "70082a8a62a43f7a6683cb3e0b2bc23c39eaf938", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ALU/ALU12.cpp", "max_forks_repo_name": "agra-uni-bremen/crave-bundle", "max_forks_repo_head_hexsha": "70082a8a62a43f7a6683cb3e0b2bc23c39eaf938", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-05-15T16:15:05.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-30T19:10:37.000Z", "avg_line_length": 22.1304347826, "max_line_length": 75, "alphanum_fraction": 0.5009823183, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5598874173537605}}
{"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": "// Maximum Subarray\n#include <iostream>\n#include <string>\n#include <array>\n#include <vector>\n#include <deque>\n#include <list>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <cassert>\n#define BOOST_TEST_MODULE Maximum Subarray\n#include <boost/test/included/unit_test.hpp>\n\nusing namespace std;\n\n\nclass Solution {\npublic:\n    int maxSubArray(vector<int>& nums) {\n        int max_ending_here = nums[0];\n        int max_so_far = nums[0];\n        for (auto it=next(nums.cbegin()); it!=nums.cend(); ++it) {\n            max_ending_here = max(*it, max_ending_here + *it);\n            max_so_far = max(max_ending_here, max_so_far);\n        }\n        return max_so_far;\n\n    }\n};\n\n\nBOOST_AUTO_TEST_CASE( my_test )\n{\n    Solution s;\n    vector<int> coll = {-2,1,-3,4,-1,2,1,-5,4};\n    BOOST_TEST( 6 == s.maxSubArray( coll ));\n}\n", "meta": {"hexsha": "4a84136135c4939c2dbac6011b8c3588c5943aee", "size": 950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "leetcode/src/lc53.cpp", "max_stars_repo_name": "andelf/codeplay", "max_stars_repo_head_hexsha": "de148cc48f5c1d436978b14876ee1c871e692e11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-10T04:01:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-10T08:31:17.000Z", "max_issues_repo_path": "leetcode/src/lc53.cpp", "max_issues_repo_name": "andelf/codeplay", "max_issues_repo_head_hexsha": "de148cc48f5c1d436978b14876ee1c871e692e11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "leetcode/src/lc53.cpp", "max_forks_repo_name": "andelf/codeplay", "max_forks_repo_head_hexsha": "de148cc48f5c1d436978b14876ee1c871e692e11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1111111111, "max_line_length": 66, "alphanum_fraction": 0.6526315789, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.5598715385322893}}
{"text": "#include \"ros/ros.h\"\n#include \"std_msgs/Float64.h\"\n#include <iostream>\n#include <Eigen/Dense>\n\nEigen::MatrixXd m(3,3);\nEigen::Vector3d r;\nEigen::Vector3d v;\n\nros::Subscriber yaw_sub;\nros::Subscriber pitch_sub;\nros::Subscriber roll_sub;\nros::Publisher motor1_pub;\nros::Publisher motor2_pub;\nros::Publisher motor3_pub;\ndouble yaw_control_effort, pitch_control_effort, roll_control_effort;\n/**\n * This tutorial demonstrates simple receipt of messages over the ROS system.\n */\n\nvoid matrixInit(void)\n{\n\n  m << -2,-1.732,1,\n-2,0,-2,\n-2,1.732,1;\n}\n\nvoid yawCallback(const std_msgs::Float64& control_effort_input)\n{\t\n     yaw_control_effort = control_effort_input.data;\n  \n\n}\n\nvoid pitchCallback(const std_msgs::Float64& control_effort_input)\n{\n     pitch_control_effort = control_effort_input.data;\n\n}\n\nvoid rollCallback(const std_msgs::Float64& control_effort_input)\n{\n     roll_control_effort = control_effort_input.data;\n\n}\n\nvoid controlCallback(const ros::TimerEvent& event)\n{\n     v(0) = yaw_control_effort;\n     v(1) = pitch_control_effort;\n     v(2) = roll_control_effort;\n     r = m*v;\n\n     std_msgs::Float64 motor1_control_effort,motor2_control_effort,motor3_control_effort;\n     motor1_control_effort.data = r(0);\n     motor2_control_effort.data = r(1);\n     motor3_control_effort.data = r(2);\n     motor1_pub.publish(motor1_control_effort);\n     motor2_pub.publish(motor2_control_effort);\n     motor3_pub.publish(motor3_control_effort);\n     //ROS_INFO(\"published rpy control_effort: roll=%f pitch=%f yaw=%f\", r(0), r(1), r(2));\n     \n}\n\nint main(int argc, char **argv)\n{\n  matrixInit();\n\n\n  ros::init(argc, argv, \"velo_transformer\");\n\n  ros::NodeHandle n;\n\n  ros::Timer timer1 = n.createTimer(ros::Duration(0.01), controlCallback);\n  yaw_sub = n.subscribe(\"/ballbot_yaw/control_effort\", 1000, yawCallback);\n  pitch_sub = n.subscribe(\"/ballbot_pitch/control_effort\", 1000, pitchCallback);\n  roll_sub = n.subscribe(\"/ballbot_roll/control_effort\", 1000, rollCallback);\n  motor1_pub = n.advertise<std_msgs::Float64>(\"/ballbot/joint0_vel_cmd\", 1000);\n  motor2_pub = n.advertise<std_msgs::Float64>(\"/ballbot/joint1_vel_cmd\", 1000);\n  motor3_pub = n.advertise<std_msgs::Float64>(\"/ballbot/joint2_vel_cmd\", 1000);\n  ros::spin();\n\n  return 0;\n}\n", "meta": {"hexsha": "dbdcf7e7f8b9dab29e9d389be3b686c71bb0a807", "size": 2243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ballbot_plugin/src/velo_transformer.cpp", "max_stars_repo_name": "63445538/Ballbot_gazebo", "max_stars_repo_head_hexsha": "2526b25ca8ddda23fa6ef60e45d1152eb4c334c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-08-17T04:42:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-01T01:41:43.000Z", "max_issues_repo_path": "ballbot_plugin/src/velo_transformer.cpp", "max_issues_repo_name": "63445538/Ballbot_gazebo", "max_issues_repo_head_hexsha": "2526b25ca8ddda23fa6ef60e45d1152eb4c334c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ballbot_plugin/src/velo_transformer.cpp", "max_forks_repo_name": "63445538/Ballbot_gazebo", "max_forks_repo_head_hexsha": "2526b25ca8ddda23fa6ef60e45d1152eb4c334c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-30T03:35:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T03:35:40.000Z", "avg_line_length": 26.0813953488, "max_line_length": 91, "alphanum_fraction": 0.7316094516, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.5597800568590984}}
{"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/*  \u4e0b\u9762\u4e24\u4e2a\u51fd\u6570\u7684\u4f5c\u7528\u662f\u628a\u6570\u5b57\u6216\u8005\u6570\u7ec4\u8f6c\u4e3a\u53ef\u7528\u4e8e\u8fd0\u7b97\u64cd\u4f5c\u7684vector\n *  \u56e0\u4e3a\u5f53\u52a0\u5bc6\u548c\u89e3\u5bc6\u8fc7\u540e\uff0c\u6700\u540e\u8fde\u7eed\u7684n\u4e2a0\u4f1a\u88ab\u9690\u85cf\n *  \u4f8b\u5982[2 2 0 0]\u2192[2 2], [0 0 0 0]\u2192[]\n *  []\u8f6c\u4e3along\u8f93\u51fa\u65f6\u4f1a\u51fa\u9519\uff0c\u6240\u4ee5\u5728\u672b\u5c3e\u52a0\u4e0a1\u4f7f\u5f970\u53ef\u4ee5\u6b63\u786e\u5730\u88ab\u63d0\u53d6\u51fa\u6765\n */\n\n// \u6570\u5b57\u8f6c\u4e3a\u53ef\u7528\u4e8e\u8fd0\u7b97\u64cd\u4f5c\u7684vector\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// \u6570\u7ec4\u8f6c\u4e3a\u53ef\u7528\u4e8e\u8fd0\u7b97\u64cd\u4f5c\u7684vector\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// \u56db\u5219\u8fd0\u7b97\u5168\u540c\u6001\u89e3\u5bc6\uff08\u53ea\u5b9e\u73b0\u4e86\u6570\u5b57\u4f5c\u4e3a\u8fd0\u7b97\u7b26\u7684\u89e3\u5bc6\uff0c\u6570\u7ec4\u4f5c\u4e3a\u8fd0\u7b97\u7b26\u7684\u6709\u5f85\u4fee\u7f2e\uff09\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// \u5168\u540c\u6001\u52a0\u6cd5\nCtxt FHE_Add(Ctxt Ea, Ctxt Eb)\n{\n\tCtxt ctSum = Ea;\n\tctSum += Eb;\n\treturn ctSum;\n}\n\n// \u5168\u540c\u6001\u4e58\u6cd5\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// \u89e3\u5bc6\u5224\u65ad\u4e58\u6570\u4e2d\u662f\u5426\u67090\uff0c\u5982\u679c\u662f\uff0c\u5219\u8fd4\u56de0\u7684\u5bc6\u6587\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// \u5168\u540c\u6001\u51cf\u6cd5\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// \u5168\u540c\u6001\u9664\u6cd5\nCtxt FHE_Div(Ctxt Ea, Ctxt Eb, long p,\n\t\t\t const FHEPubKey& publicKey, const FHESecKey& secretKey)\n{\n\tint quotient = 0;  // \u521d\u59cb\u5316\u5546quotient\u4e3a0\n\tZZX ptMul, ptMul2, ptSub, ptSum, ptEa, ptEb;\n\n\t/* \u5224\u65ad\u601d\u8def\uff08\u8bbe\u88ab\u9664\u6570\u548c\u9664\u6570\u4e3aop1\u548cop2\uff09\uff1a\n\t * 1. op2=0\u65f6\uff0c\u8f93\u51fa\"Error: Invalid Denominator.\"\uff0c\u5426\u5219\u7ee7\u7eed\n\t * 2. op1=0\u65f6\uff0c\u8fd4\u56de0\u7684\u5bc6\u6587\uff0c\u5426\u5219\u7ee7\u7eed\n\t * 3. \u5224\u65adop1\u548cop2\u662f\u5426\u540c\u53f7,\u53ef\u7528op1\u00b7op2\u662f\u5426\u4e3a\u6b63\u6765\u5224\u65ad\n\t *    3-1. \u540c\u53f7: \u5f53op1=0\u65f6\u8df3\u51fa\u5faa\u73af\uff0c\u5426\u5219\n\t *               sub=op1-op2\uff0c\u5982\u679csub\u548cop1\u540c\u53f7(op1\u548cop2\u540c\u4e3a\u8d1f\u6570\u7684\u65f6\u5019sub\u4e5f\u662f\u8d1f\u6570)\u5219quotient\u9012\u589e\u4e14op1=sub\uff0c\u5426\u5219\u8df3\u51fa\u5faa\u73af\n\t *    3-2. \u5f02\u53f7: \u5f53op1=0\u65f6\u8df3\u51fa\u5faa\u73af\uff0c\u5426\u5219\n\t *               sum=op1+op2(\u56e0\u4e3a\u662f\u5f02\u53f7)\uff0c\u5982\u679csum\u548cop1\u540c\u53f7\u5219quotient\u9012\u51cf(\u5f02\u53f7\u76f8\u9664\u7ed3\u679c\u4e3a\u8d1f\u6570)\u4e14op1=sum\uff0c\u5426\u5219\u8df3\u51fa\u5faa\u73af        \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// \u4e24\u64cd\u4f5c\u6570\u540c\u53f7\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// \u4e24\u64cd\u4f5c\u6570\u5f02\u53f7 \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;    // \u786e\u5b9a\u7cfb\u6570\n\tlong p = 1021; // \u6a21\u91cf\uff0c\u5b9a\u4e49\u8d85\u8fc7p/2\u7684\u6570\u4e3a\u8d1f\u6570\uff0c\u8d1f\u6570\u7684\u771f\u503cx=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// \u751f\u6210\u516c\u94a5\n\tFHESecKey secretKey(context);\n\tconst FHEPubKey& publicKey = secretKey;\n\tsecretKey.GenSecKey(w);\n\n\t// \u521d\u59cb\u5316\u5bc6\u6587\n\tCtxt Ea(publicKey);\n\tCtxt Eb(publicKey);\n\n\t/* Test: \u8f93\u5165\u4e24\u4e2a\u4e0d\u5168\u4e3a0\u7684\u6570\uff0c\u8f93\u51fa\u56db\u5219\u8fd0\u7b97\u7ed3\u679c\uff0c\u8f93\u5165\u4e24\u4e2a0\u53ef\u9000\u51fa\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// Copyright 2019 Mateusz Loskot <mateusz at loskot dot net>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#include <boost/gil.hpp>\n#include <boost/gil/extension/numeric/convolve.hpp>\n\n#include <tuple>\n#include <type_traits>\n\n#define BOOST_TEST_MODULE test_ext_numeric_colvolve_2d\n#include \"unit_test.hpp\"\n#include \"unit_test_utility.hpp\"\n#include \"test_fixture.hpp\"\n#include \"core/image/test_fixture.hpp\"\n\nnamespace gil = boost::gil;\nnamespace fixture = boost::gil::test::fixture;\n\nBOOST_AUTO_TEST_SUITE(convolve_1d)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(image_1x1_kernel_1x1_identity, Image, fixture::image_types)\n{\n    auto const img = fixture::create_image<Image>(1, 1, 7);\n    Image img_out(img);\n\n    using pixel_t = typename Image::value_type;\n    using channel_t = typename gil::channel_type<pixel_t>::type;\n    auto const kernel = fixture::create_kernel<channel_t>({1});\n    gil::detail::convolve_1d<pixel_t>(const_view(img_out), kernel, view(img_out));\n\n    // 1x1 kernel reduces convolution to multiplication\n    BOOST_TEST(gil::const_view(img).front() == gil::const_view(img_out).front());\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(image_1x1_kernel_3x3_identity, Image, fixture::image_types)\n{\n    auto const img = fixture::create_image<Image>(1, 1, 7);\n    Image img_out(img);\n\n    using pixel_t = typename Image::value_type;\n    using channel_t = typename gil::channel_type<pixel_t>::type;\n    auto const kernel = fixture::create_kernel<channel_t>({0, 0, 0, 0, 1, 0, 0, 0, 0});\n    gil::detail::convolve_1d<pixel_t>(const_view(img_out), kernel, view(img_out));\n\n    BOOST_TEST(gil::const_view(img).front() == gil::const_view(img_out).front());\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(image_3x3_kernel_3x3_identity, Image, fixture::image_types)\n{\n    using pixel_t = typename Image::value_type;\n    using channel_t = typename gil::channel_type<pixel_t>::type;\n    auto const img = fixture::generate_image<Image>(3, 3, fixture::random_value<channel_t>{});\n    Image img_out(img);\n\n    auto const kernel = fixture::create_kernel<channel_t>({0, 0, 0, 0, 1, 0, 0, 0, 0});\n    gil::detail::convolve_1d<pixel_t>(const_view(img_out), kernel, view(img_out));\n\n    BOOST_TEST(gil::equal_pixels(gil::const_view(img), gil::const_view(img_out)));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(image_5x5_kernel_3x3_identity, Image, fixture::image_types)\n{\n    using pixel_t = typename Image::value_type;\n    using channel_t = typename gil::channel_type<pixel_t>::type;\n    auto const img = fixture::generate_image<Image>(5, 5, fixture::random_value<channel_t>{});\n    Image img_out(img);\n\n    auto const kernel = fixture::create_kernel<channel_t>({0, 0, 0, 0, 1, 0, 0, 0, 0});\n    gil::detail::convolve_1d<pixel_t>(const_view(img_out), kernel, view(img_out));\n    // TODO: Test different boundary options\n\n    BOOST_TEST(gil::equal_pixels(gil::const_view(img), gil::const_view(img_out)));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d12fc9ac4c978de6f2d620f608cc5adf5a2f4e71", "size": 3000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/gil/test/extension/numeric/convolve.cpp", "max_stars_repo_name": "btzy/boost-1.72.0-mirror", "max_stars_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-01T03:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T03:04:05.000Z", "max_issues_repo_path": "libs/gil/test/extension/numeric/convolve.cpp", "max_issues_repo_name": "btzy/boost-1.72.0-mirror", "max_issues_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/gil/test/extension/numeric/convolve.cpp", "max_forks_repo_name": "btzy/boost-1.72.0-mirror", "max_forks_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5, "max_line_length": 94, "alphanum_fraction": 0.7346666667, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.5597623156504934}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2009 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 \"main.h\"\r\n#include <Eigen/Geometry>\r\n\r\ntemplate<typename Scalar,int Size> void homogeneous(void)\r\n{\r\n  /* this test covers the following files:\r\n     Homogeneous.h\r\n  */\r\n\r\n  typedef Matrix<Scalar,Size,Size> MatrixType;\r\n  typedef Matrix<Scalar,Size,1, ColMajor> VectorType;\r\n\r\n  typedef Matrix<Scalar,Size+1,Size> HMatrixType;\r\n  typedef Matrix<Scalar,Size+1,1> HVectorType;\r\n\r\n  typedef Matrix<Scalar,Size,Size+1>   T1MatrixType;\r\n  typedef Matrix<Scalar,Size+1,Size+1> T2MatrixType;\r\n  typedef Matrix<Scalar,Size+1,Size> T3MatrixType;\r\n\r\n  VectorType v0 = VectorType::Random(),\r\n             ones = VectorType::Ones();\r\n\r\n  HVectorType hv0 = HVectorType::Random();\r\n\r\n  MatrixType m0 = MatrixType::Random();\r\n\r\n  HMatrixType hm0 = HMatrixType::Random();\r\n\r\n  hv0 << v0, 1;\r\n  VERIFY_IS_APPROX(v0.homogeneous(), hv0);\r\n  VERIFY_IS_APPROX(v0, hv0.hnormalized());\r\n\r\n  hm0 << m0, ones.transpose();\r\n  VERIFY_IS_APPROX(m0.colwise().homogeneous(), hm0);\r\n  VERIFY_IS_APPROX(m0, hm0.colwise().hnormalized());\r\n  hm0.row(Size-1).setRandom();\r\n  for(int j=0; j<Size; ++j)\r\n    m0.col(j) = hm0.col(j).head(Size) / hm0(Size,j);\r\n  VERIFY_IS_APPROX(m0, hm0.colwise().hnormalized());\r\n\r\n  T1MatrixType t1 = T1MatrixType::Random();\r\n  VERIFY_IS_APPROX(t1 * (v0.homogeneous().eval()), t1 * v0.homogeneous());\r\n  VERIFY_IS_APPROX(t1 * (m0.colwise().homogeneous().eval()), t1 * m0.colwise().homogeneous());\r\n\r\n  T2MatrixType t2 = T2MatrixType::Random();\r\n  VERIFY_IS_APPROX(t2 * (v0.homogeneous().eval()), t2 * v0.homogeneous());\r\n  VERIFY_IS_APPROX(t2 * (m0.colwise().homogeneous().eval()), t2 * m0.colwise().homogeneous());\r\n\r\n  VERIFY_IS_APPROX((v0.transpose().rowwise().homogeneous().eval()) * t2,\r\n                    v0.transpose().rowwise().homogeneous() * t2);\r\n                    m0.transpose().rowwise().homogeneous().eval();\r\n  VERIFY_IS_APPROX((m0.transpose().rowwise().homogeneous().eval()) * t2,\r\n                    m0.transpose().rowwise().homogeneous() * t2);\r\n\r\n  T3MatrixType t3 = T3MatrixType::Random();\r\n  VERIFY_IS_APPROX((v0.transpose().rowwise().homogeneous().eval()) * t3,\r\n                    v0.transpose().rowwise().homogeneous() * t3);\r\n  VERIFY_IS_APPROX((m0.transpose().rowwise().homogeneous().eval()) * t3,\r\n                    m0.transpose().rowwise().homogeneous() * t3);\r\n\r\n  // test product with a Transform object\r\n  Transform<Scalar, Size, Affine> aff;\r\n  Transform<Scalar, Size, AffineCompact> caff;\r\n  Transform<Scalar, Size, Projective> proj;\r\n  Matrix<Scalar, Size, Dynamic>   pts;\r\n  Matrix<Scalar, Size+1, Dynamic> pts1, pts2;\r\n\r\n  aff.affine().setRandom();\r\n  proj = caff = aff;\r\n  pts.setRandom(Size,internal::random<int>(1,20));\r\n  \r\n  pts1 = pts.colwise().homogeneous();\r\n  VERIFY_IS_APPROX(aff  * pts.colwise().homogeneous(), (aff  * pts1).colwise().hnormalized());\r\n  VERIFY_IS_APPROX(caff * pts.colwise().homogeneous(), (caff * pts1).colwise().hnormalized());\r\n  VERIFY_IS_APPROX(proj * pts.colwise().homogeneous(), (proj * pts1));\r\n  \r\n  VERIFY_IS_APPROX((aff  * pts1).colwise().hnormalized(),  aff  * pts);\r\n  VERIFY_IS_APPROX((caff * pts1).colwise().hnormalized(), caff * pts);\r\n  \r\n  pts2 = pts1;\r\n  pts2.row(Size).setRandom();\r\n  VERIFY_IS_APPROX((aff  * pts2).colwise().hnormalized(), aff  * pts2.colwise().hnormalized());\r\n  VERIFY_IS_APPROX((caff * pts2).colwise().hnormalized(), caff * pts2.colwise().hnormalized());\r\n  VERIFY_IS_APPROX((proj * pts2).colwise().hnormalized(), (proj * pts2.colwise().hnormalized().colwise().homogeneous()).colwise().hnormalized());\r\n}\r\n\r\nvoid test_geo_homogeneous()\r\n{\r\n  for(int i = 0; i < g_repeat; i++) {\r\n    CALL_SUBTEST_1(( homogeneous<float,1>() ));\r\n    CALL_SUBTEST_2(( homogeneous<double,3>() ));\r\n    CALL_SUBTEST_3(( homogeneous<double,8>() ));\r\n  }\r\n}\r\n", "meta": {"hexsha": "a7955cd3fb60fe3ee427c3f69627a931ee25c265", "size": 4126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen/test/geo_homogeneous.cpp", "max_stars_repo_name": "subond/tools", "max_stars_repo_head_hexsha": "05b93e6c78eab65ef6587e684303b12c686a3480", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigen/test/geo_homogeneous.cpp", "max_issues_repo_name": "subond/tools", "max_issues_repo_head_hexsha": "05b93e6c78eab65ef6587e684303b12c686a3480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen/test/geo_homogeneous.cpp", "max_forks_repo_name": "subond/tools", "max_forks_repo_head_hexsha": "05b93e6c78eab65ef6587e684303b12c686a3480", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-04T15:41:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T15:41:53.000Z", "avg_line_length": 39.6730769231, "max_line_length": 146, "alphanum_fraction": 0.6548715463, "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059560743422, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.559762314193787}}
{"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": "#include <cmath>\n#include <cstdint>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <random>\n#include <stdexcept>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include <Eigen/Geometry>\n#include <common_robotics_utilities/math.hpp>\n#include <common_robotics_utilities/path_processing.hpp>\n#include <common_robotics_utilities/print.hpp>\n#include <common_robotics_utilities/simple_astar_search.hpp>\n#include <common_robotics_utilities/simple_graph.hpp>\n#include <common_robotics_utilities/simple_graph_search.hpp>\n#include <common_robotics_utilities/simple_knearest_neighbors.hpp>\n#include <common_robotics_utilities/simple_prm_planner.hpp>\n#include <common_robotics_utilities/simple_rrt_planner.hpp>\n#include <common_robotics_utilities/zlib_helpers.hpp>\n\n#include <gtest/gtest.h>\n\nnamespace common_robotics_utilities\n{\nnamespace planning_test\n{\nusing TestMap = Eigen::Matrix<char, Eigen::Dynamic, Eigen::Dynamic>;\nusing Waypoint = std::pair<ssize_t, ssize_t>;\nusing WaypointAllocator = std::allocator<Waypoint>;\nusing WaypointVector = std::vector<Waypoint, WaypointAllocator>;\nusing WaypointPlanningTree = simple_rrt_planner::PlanningTree<Waypoint>;\n\nbool WaypointsEqual(const Waypoint& first, const Waypoint& second)\n{\n  return (first.first == second.first && first.second == second.second);\n}\n\nstruct WaypointEqualer\n{\n  bool operator()(const Waypoint& first, const Waypoint& second) const\n  {\n    return WaypointsEqual(first, second);\n  }\n};\n\nstruct WaypointHasher\n{\n  size_t operator()(const Waypoint& waypoint) const\n  {\n    std::size_t hash_val = 0;\n    common_robotics_utilities::utility::hash_combine(\n        hash_val, waypoint.first, waypoint.second);\n    return hash_val;\n  }\n};\n\ndouble WaypointDistance(const Waypoint& start, const Waypoint& end)\n{\n  const double delta_rows = static_cast<double>(end.first - start.first);\n  const double delta_cols = static_cast<double>(end.second - start.second);\n  return std::sqrt((delta_rows * delta_rows) + (delta_cols * delta_cols));\n}\n\nWaypoint InterpolateWaypoint(\n    const Waypoint& start, const Waypoint& end, const double ratio)\n{\n  const double real_ratio = utility::ClampValueAndWarn(ratio, 0.0, 1.0);\n  const double delta_rows = static_cast<double>(end.first - start.first);\n  const double delta_cols = static_cast<double>(end.second - start.second);\n  const double raw_interp_rows = delta_rows * real_ratio;\n  const double raw_interp_cols = delta_cols * real_ratio;\n  const ssize_t interp_row\n      = start.first + static_cast<ssize_t>(std::round(raw_interp_rows));\n  const ssize_t interp_col\n      = start.second + static_cast<ssize_t>(std::round(raw_interp_cols));\n  return Waypoint(interp_row, interp_col);\n}\n\nWaypointVector ResampleWaypoints(const WaypointVector& waypoints)\n{\n  return path_processing::ResamplePath<Waypoint>(\n      waypoints, 0.5, WaypointDistance, InterpolateWaypoint);\n}\n\nvoid DrawEnvironment(const TestMap& environment)\n{\n  std::cout << environment << std::endl;\n}\n\nvoid SetCell(TestMap& map, const ssize_t row, const ssize_t col, const char val)\n{\n  if (map(row, col) != '#')\n  {\n    map(row, col) = val;\n  }\n}\n\nvoid DrawPaths(\n    const TestMap& environment,\n    const WaypointVector& starts,\n    const WaypointVector& goals,\n    const std::vector<WaypointVector>& paths)\n{\n  TestMap working_copy = environment;\n  for (const auto& path : paths)\n  {\n    if (path.size() > 0)\n    {\n      SetCell(working_copy, path.at(0).first, path.at(0).second, '+');\n      for (size_t idx = 1; idx < path.size(); idx++)\n      {\n        const Waypoint& previous = path.at(idx - 1);\n        const Waypoint& current = path.at(idx);\n        const auto edge_path = ResampleWaypoints({previous, current});\n        for (const auto& state : edge_path)\n        {\n          const char current_val = working_copy(state.first, state.second);\n          if (current_val != '+')\n          {\n            SetCell(working_copy, state.first, state.second, '-');\n          }\n        }\n        SetCell(working_copy, current.first, current.second, '+');\n      }\n    }\n  }\n  for (const auto& start : starts)\n  {\n    SetCell(working_copy, start.first, start.second, 'S');\n  }\n  for (const auto& goal : goals)\n  {\n    SetCell(working_copy, goal.first, goal.second, 'G');\n  }\n  DrawEnvironment(working_copy);\n}\n\nvoid DrawPath(\n    const TestMap& environment,\n    const WaypointVector& starts,\n    const WaypointVector& goals,\n    const WaypointVector& path)\n{\n  return DrawPaths(environment, starts, goals, {path});\n}\n\nTestMap MakeTestMap(\n    const std::string& test_map_string, const ssize_t rows, const ssize_t cols)\n{\n  if (static_cast<ssize_t>(test_map_string.size()) != (rows * cols))\n  {\n    throw std::invalid_argument(\"test_map_string is the wrong size\");\n  }\n  TestMap test_map(rows, cols);\n  memcpy(test_map.data(), test_map_string.data(),\n         test_map_string.size() * sizeof(char));\n  test_map.transposeInPlace();\n  return test_map;\n}\n\nbool CheckWaypointCollisionFree(const TestMap& map, const Waypoint& waypoint)\n{\n  return (map(waypoint.first, waypoint.second) != '#');\n}\n\nbool CheckEdgeCollisionFree(\n    const TestMap& map, const Waypoint& start, const Waypoint& end,\n    const double step_size)\n{\n  const double distance = WaypointDistance(start, end);\n  const double raw_num_intervals = distance / step_size;\n  const int32_t num_states\n      = std::max(static_cast<int32_t>(std::ceil(raw_num_intervals)), 1);\n  for (int32_t state = 0; state <= num_states; state++)\n  {\n    const double interpolation_ratio\n        = static_cast<double>(state) / static_cast<double>(num_states);\n    const Waypoint interpolated\n        = InterpolateWaypoint(start, end, interpolation_ratio);\n    if (!CheckWaypointCollisionFree(map, interpolated))\n    {\n      return false;\n    }\n  }\n  return true;\n}\n\ntemplate<typename PRNG>\nWaypointVector SmoothWaypoints(\n    const WaypointVector& waypoints,\n    const std::function<bool(const Waypoint&, const Waypoint&)>& check_edge_fn,\n    PRNG& prng)\n{\n  // Parameters for shortcut smoothing\n  const uint32_t max_iterations = 100;\n  const uint32_t max_failed_iterations = 100;\n  const uint32_t max_backtracking_steps = 1;\n  const double max_shortcut_fraction = 0.5;\n  const double resample_shortcuts_interval = 0.5;\n  const bool check_for_marginal_shortcuts = false;\n  return path_processing::ShortcutSmoothPath<PRNG, Waypoint>(\n      waypoints, max_iterations, max_failed_iterations, max_backtracking_steps,\n      max_shortcut_fraction, resample_shortcuts_interval,\n      check_for_marginal_shortcuts, check_edge_fn, WaypointDistance,\n      InterpolateWaypoint, prng);\n}\n\nvoid DrawRoadmap(\n    const TestMap& environment,\n    const simple_graph::Graph<Waypoint>& roadmap)\n{\n  TestMap working_copy = environment;\n  const auto& roadmap_nodes = roadmap.GetNodesImmutable();\n  for (const auto& roadmap_node : roadmap_nodes)\n  {\n    const std::vector<simple_graph::GraphEdge>& out_edges\n        = roadmap_node.GetOutEdgesImmutable();\n    for (const simple_graph::GraphEdge& edge : out_edges)\n    {\n      const Waypoint& self\n          = roadmap.GetNodeImmutable(edge.GetFromIndex()).GetValueImmutable();\n      const Waypoint& other\n          = roadmap.GetNodeImmutable(edge.GetToIndex()).GetValueImmutable();\n      const auto edge_path = ResampleWaypoints({self, other});\n      for (const auto& waypoint : edge_path)\n      {\n        const char current_val = working_copy(waypoint.first, waypoint.second);\n        if (current_val != '+')\n        {\n          SetCell(working_copy, waypoint.first, waypoint.second, '-');\n        }\n      }\n      SetCell(working_copy, self.first, self.second, '+');\n      SetCell(working_copy, other.first, other.second, '+');\n    }\n  }\n  DrawEnvironment(working_copy);\n}\n\nWaypointVector GenerateAllPossible8ConnectedChildren(\n    const Waypoint& waypoint)\n{\n  return WaypointVector{\n      Waypoint(waypoint.first - 1, waypoint.second - 1),\n      Waypoint(waypoint.first - 1, waypoint.second),\n      Waypoint(waypoint.first - 1, waypoint.second + 1),\n      Waypoint(waypoint.first, waypoint.second - 1),\n      Waypoint(waypoint.first, waypoint.second + 1),\n      Waypoint(waypoint.first + 1, waypoint.second - 1),\n      Waypoint(waypoint.first + 1, waypoint.second),\n      Waypoint(waypoint.first + 1, waypoint.second + 1)};\n}\n\ntemplate<typename PRNG>\nWaypoint SampleWaypoint(const TestMap& map, PRNG& rng)\n{\n  std::uniform_int_distribution<ssize_t> row_dist(1, map.rows() - 1);\n  std::uniform_int_distribution<ssize_t> col_dist(1, map.rows() - 1);\n  return Waypoint(row_dist(rng), col_dist(rng));\n}\n\nGTEST_TEST(PlanningTest, Test)\n{\n  const std::string test_env_raw = \"####################\"\n                                   \"#                  #\"\n                                   \"#  ####            #\"\n                                   \"#  ####    #####   #\"\n                                   \"#  ####    #####   #\"\n                                   \"#          #####   #\"\n                                   \"#          #####   #\"\n                                   \"#                  #\"\n                                   \"#      #########   #\"\n                                   \"#     ##########   #\"\n                                   \"#    ###########   #\"\n                                   \"#   ############   #\"\n                                   \"#                  #\"\n                                   \"#                  #\"\n                                   \"#    ##            #\"\n                                   \"#    ##   ######## #\"\n                                   \"#    ##   ######## #\"\n                                   \"#    ##   ######## #\"\n                                   \"#                  #\"\n                                   \"####################\";\n  const TestMap test_env = MakeTestMap(test_env_raw, 20, 20);\n  std::cout << \"Planning environment\" << std::endl;\n  DrawEnvironment(test_env);\n  const int64_t prng_seed = 42;\n  std::mt19937_64 prng(prng_seed);\n  const WaypointVector keypoints\n      = {Waypoint(1, 1), Waypoint(18, 18), Waypoint(7, 13), Waypoint(9, 5)};\n  // Bind helper functions used by multiple planners\n  const std::function<bool(const Waypoint&)> check_state_validity_fn\n      = [&] (const Waypoint& waypoint)\n  {\n    return CheckWaypointCollisionFree(test_env, waypoint);\n  };\n  const std::function<bool(const Waypoint&, const Waypoint&)>\n      check_edge_validity_fn = [&] (const Waypoint& start, const Waypoint& end)\n  {\n    // We check both forward and backward because rounding in the waypoint\n    // interpolation can create edges that are valid in only one direction.\n    return (CheckEdgeCollisionFree(test_env, start, end, 0.5) &&\n            CheckEdgeCollisionFree(test_env, end, start, 0.5));\n  };\n  const std::function<Waypoint(void)> state_sampling_fn = [&] (void)\n  {\n    return SampleWaypoint(test_env, prng);\n  };\n  // Functions to check planning results\n  const std::function<void(const WaypointVector&)> check_path =\n      [&] (const WaypointVector& path)\n  {\n    ASSERT_GE(static_cast<int32_t>(path.size()), 2);\n    for (size_t idx = 1; idx < path.size(); idx++)\n    {\n      // We check both forward and backward because rounding in the waypoint\n      // interpolation can create edges that are valid in only one direction.\n      const bool forward_valid =\n          check_edge_validity_fn(path.at(idx - 1), path.at(idx));\n      const bool backward_valid =\n          check_edge_validity_fn(path.at(idx), path.at(idx - 1));\n      const bool edge_valid = forward_valid && backward_valid;\n      ASSERT_TRUE(edge_valid);\n    }\n  };\n  const std::function<void(\n      const TestMap&, const WaypointVector&,\n      const WaypointVector&, const WaypointVector&)> check_plan =\n      [&] (const TestMap& environment, const WaypointVector& starts,\n           const WaypointVector& goals,\n           const WaypointVector& path)\n  {\n    DrawPath(environment, starts, goals, path);\n    std::cout << \"Checking raw path\" << std::endl;\n    check_path(path);\n    const auto smoothed_path =\n        SmoothWaypoints(path, check_edge_validity_fn, prng);\n    std::cout << \"Checking smoothed path\" << std::endl;\n    check_path(smoothed_path);\n    const auto resampled_path = ResampleWaypoints(smoothed_path);\n    std::cout << \"Checking resampled path\" << std::endl;\n    check_path(resampled_path);\n  };\n  // RRT and BiRRT parameters\n  const double rrt_step_size = 3.0;\n  const double rrt_goal_bias = 0.1;\n  const double rrt_timeout = 5.0;\n  const double birrt_tree_sampling_bias = 0.5;\n  const double birrt_p_switch_trees = 0.25;\n  // Make RRT helpers\n  auto rrt_nearest_neighbors_fn\n      = simple_rrt_planner\n          ::MakeKinematicLinearRRTNearestNeighborsFunction<Waypoint>(\n              WaypointDistance, false);\n  auto rrt_extend_fn\n      = simple_rrt_planner::MakeKinematicRRTExtendPropagationFunction<Waypoint>(\n          WaypointDistance, InterpolateWaypoint, check_edge_validity_fn,\n          rrt_step_size);\n  auto rrt_connect_fn\n      = simple_rrt_planner\n          ::MakeKinematicRRTConnectPropagationFunction<Waypoint>(\n              WaypointDistance, InterpolateWaypoint, check_edge_validity_fn,\n              rrt_step_size);\n  auto birrt_nearest_neighbors_fn\n      = simple_rrt_planner\n          ::MakeKinematicLinearBiRRTNearestNeighborsFunction<Waypoint>(\n              WaypointDistance, false);\n  auto birrt_extend_fn\n      = simple_rrt_planner\n          ::MakeKinematicBiRRTExtendPropagationFunction<Waypoint>(\n              WaypointDistance, InterpolateWaypoint, check_edge_validity_fn,\n              rrt_step_size);\n  auto birrt_connect_fn\n      = simple_rrt_planner\n          ::MakeKinematicBiRRTConnectPropagationFunction<Waypoint>(\n              WaypointDistance, InterpolateWaypoint, check_edge_validity_fn,\n              rrt_step_size);\n  // Build a roadmap on the environment\n  const size_t K = 5;\n  const int64_t roadmap_size = 100;\n  const std::function<bool(const int64_t)> roadmap_termination_fn\n      = [] (const int64_t current_roadmap_size)\n  {\n    return (current_roadmap_size >= roadmap_size);\n  };\n  simple_graph::Graph<Waypoint> roadmap;\n  simple_prm_planner::GrowRoadMap<Waypoint>(\n      roadmap, state_sampling_fn, WaypointDistance, check_state_validity_fn,\n      check_edge_validity_fn, roadmap_termination_fn, K, false, true, false);\n  ASSERT_TRUE(roadmap.CheckGraphLinkage());\n  std::cout << \"Roadmap built\" << std::endl;\n  simple_prm_planner::UpdateRoadMapEdges<Waypoint>(\n      roadmap, check_edge_validity_fn, WaypointDistance, false);\n  ASSERT_TRUE(roadmap.CheckGraphLinkage());\n  std::cout << \"Roadmap updated\" << std::endl;\n  // Test graph pruning\n  const std::unordered_set<int64_t> nodes_to_prune = {10, 20, 30, 40, 50, 60};\n  const auto serial_pruned_roadmap\n      = roadmap.MakePrunedCopy(nodes_to_prune, false);\n  ASSERT_TRUE(serial_pruned_roadmap.CheckGraphLinkage());\n  const auto parallel_pruned_roadmap\n      = roadmap.MakePrunedCopy(nodes_to_prune, true);\n  ASSERT_TRUE(parallel_pruned_roadmap.CheckGraphLinkage());\n  DrawRoadmap(test_env, roadmap);\n  // Serialize & load & check the roadmap\n  serialization::Serializer<Waypoint> serialize_waypoint_fn\n      = [] (const Waypoint& wp, std::vector<uint8_t>& serialization_buffer)\n  {\n    return serialization::SerializePair<ssize_t, ssize_t>(\n        wp, serialization_buffer, serialization::SerializeMemcpyable<ssize_t>,\n        serialization::SerializeMemcpyable<ssize_t>);\n  };\n  serialization::Deserializer<Waypoint> deserialize_waypoint_fn\n      = [] (const std::vector<uint8_t>& deserialization_buffer,\n            const uint64_t starting_offset)\n  {\n    return serialization::DeserializePair<ssize_t, ssize_t>(\n        deserialization_buffer, starting_offset,\n        serialization::DeserializeMemcpyable<ssize_t>,\n        serialization::DeserializeMemcpyable<ssize_t>);\n  };\n  std::vector<uint8_t> buffer;\n  simple_graph::Graph<Waypoint>::Serialize(\n      roadmap, buffer, serialize_waypoint_fn);\n  const std::string temp_file = \"/tmp/temp_planning_test_roadmap.rmp\";\n  zlib_helpers::CompressAndWriteToFile(buffer, temp_file);\n  const std::vector<uint8_t> load_buffer\n      = zlib_helpers::LoadFromFileAndDecompress(temp_file);\n  ASSERT_EQ(buffer.size(), load_buffer.size());\n  const auto loaded = simple_graph::Graph<Waypoint>::Deserialize(\n                        load_buffer, 0, deserialize_waypoint_fn);\n  const simple_graph::Graph<Waypoint>& loaded_roadmap = loaded.Value();\n  ASSERT_EQ(roadmap.Size(), loaded_roadmap.Size());\n  std::cout << \"Old roadmap nodes: \" << roadmap.Size() << \"\\n\"\n            << \"Old roadmap binary size: \" << buffer.size() << \"\\n\"\n            << \"New roadmap nodes: \" << loaded_roadmap.Size() << \"\\n\"\n            << \"New roadmap binary size: \" << load_buffer.size() << std::endl;\n  for (size_t idx = 0; idx < loaded_roadmap.Size(); idx++)\n  {\n    const auto& old_node = roadmap.GetNodeImmutable(static_cast<int64_t>(idx));\n    const auto& new_node\n        = loaded_roadmap.GetNodeImmutable(static_cast<int64_t>(idx));\n    const Waypoint& old_waypoint = old_node.GetValueImmutable();\n    const Waypoint& new_waypoint = new_node.GetValueImmutable();\n    ASSERT_EQ(old_waypoint.first, new_waypoint.first);\n    ASSERT_EQ(old_waypoint.second, new_waypoint.second);\n    const auto& old_in_edges = old_node.GetInEdgesImmutable();\n    const auto& new_in_edges = new_node.GetInEdgesImmutable();\n    ASSERT_EQ(old_in_edges.size(), new_in_edges.size());\n    for (size_t edx = 0; edx < new_in_edges.size(); edx++)\n    {\n      const auto& old_edge = old_in_edges.at(edx);\n      const auto& new_edge = new_in_edges.at(edx);\n      ASSERT_EQ(old_edge.GetFromIndex(), new_edge.GetFromIndex());\n      ASSERT_EQ(old_edge.GetToIndex(), new_edge.GetToIndex());\n    }\n    const auto& old_out_edges = old_node.GetOutEdgesImmutable();\n    const auto& new_out_edges = new_node.GetOutEdgesImmutable();\n    ASSERT_EQ(old_out_edges.size(), new_out_edges.size());\n    for (size_t edx = 0; edx < new_out_edges.size(); edx++)\n    {\n      const auto& old_edge = old_out_edges.at(edx);\n      const auto& new_edge = new_out_edges.at(edx);\n      ASSERT_EQ(old_edge.GetFromIndex(), new_edge.GetFromIndex());\n      ASSERT_EQ(old_edge.GetToIndex(), new_edge.GetToIndex());\n    }\n  }\n  std::cout << \"Loaded Roadmap\" << std::endl;\n  DrawRoadmap(test_env, loaded_roadmap);\n  // Run planning tests\n  for (size_t sdx = 0; sdx < keypoints.size(); sdx++)\n  {\n    for (size_t gdx = 0; gdx < keypoints.size(); gdx++)\n    {\n      if (sdx != gdx)\n      {\n        // Get start & goal waypoints\n        const Waypoint& start = keypoints.at(sdx);\n        const Waypoint& goal = keypoints.at(gdx);\n        // Plan with PRM\n        std::cout << \"PRM Path (\" << print::Print(start) << \" to \"\n                  << print::Print(goal) << \")\" << std::endl;\n        const auto path = simple_prm_planner::QueryPath<Waypoint>(\n            {start}, {goal}, loaded_roadmap, WaypointDistance,\n            check_edge_validity_fn, K, false, true, false, true).Path();\n        check_plan(test_env, {start}, {goal}, path);\n        // Plan with Lazy-PRM\n        std::cout << \"Lazy-PRM Path (\" << print::Print(start) << \" to \"\n                  << print::Print(goal) << \")\" << std::endl;\n        const auto lazy_path = simple_prm_planner::LazyQueryPath<Waypoint>(\n            {start}, {goal}, loaded_roadmap, WaypointDistance,\n            check_edge_validity_fn, K, false, true, false, true).Path();\n        check_plan(test_env, {start}, {goal}, lazy_path);\n        // Plan with A*\n        std::cout << \"A* Path (\" << print::Print(start) << \" to \"\n                  << print::Print(goal) << \")\" << std::endl;\n        const auto astar_path\n            = simple_astar_search::PerformAstarSearch<\n                Waypoint, WaypointVector, WaypointHasher, WaypointEqualer>(\n                    start, goal, GenerateAllPossible8ConnectedChildren,\n                    check_edge_validity_fn, WaypointDistance, WaypointDistance,\n                    true).Path();\n        check_plan(test_env, {start}, {goal}, astar_path);\n        // Plan with RRT-Extend\n        std::cout << \"RRT-Extend Path (\" << print::Print(start) << \" to \"\n                  << print::Print(goal) << \")\" << std::endl;\n        const auto rrt_sample_fn\n            = simple_rrt_planner::MakeStateAndGoalsSamplingFunction<Waypoint>(\n                state_sampling_fn, {goal}, rrt_goal_bias, prng);\n        const simple_rrt_planner::CheckGoalReachedFunction<Waypoint>\n            rrt_goal_reached_fn = [&] (const Waypoint& state)\n        {\n          return WaypointsEqual(goal, state);\n        };\n        WaypointPlanningTree rrt_extend_tree;\n        rrt_extend_tree.emplace_back(\n            simple_rrt_planner::SimpleRRTPlannerState<Waypoint>(start));\n        const auto rrt_extend_path\n            = simple_rrt_planner::RRTPlanSinglePath<\n                Waypoint, Waypoint, WaypointVector>(\n                    rrt_extend_tree, rrt_sample_fn, rrt_nearest_neighbors_fn,\n                    rrt_extend_fn, {}, rrt_goal_reached_fn, {},\n                    simple_rrt_planner\n                        ::MakeRRTTimeoutTerminationFunction(rrt_timeout))\n                        .Path();\n        check_plan(test_env, {start}, {goal}, rrt_extend_path);\n        // Plan with RRT-Connect\n        std::cout << \"RRT-Connect Path (\" << print::Print(start) << \" to \"\n                  << print::Print(goal) << \")\" << std::endl;\n        WaypointPlanningTree rrt_connect_tree;\n        rrt_connect_tree.emplace_back(\n            simple_rrt_planner::SimpleRRTPlannerState<Waypoint>(start));\n        const auto rrt_connect_path\n            = simple_rrt_planner::RRTPlanSinglePath<\n                Waypoint, Waypoint, WaypointVector>(\n                    rrt_connect_tree, rrt_sample_fn, rrt_nearest_neighbors_fn,\n                    rrt_connect_fn, {}, rrt_goal_reached_fn, {},\n                    simple_rrt_planner\n                        ::MakeRRTTimeoutTerminationFunction(rrt_timeout))\n                        .Path();\n        check_plan(test_env, {start}, {goal}, rrt_connect_path);\n        // Plan with BiRRT-Extend\n        std::cout << \"BiRRT-Extend Path (\" << print::Print(start) << \" to \"\n                  << print::Print(goal) << \")\" << std::endl;\n        const simple_rrt_planner::StatesConnectedFunction<Waypoint>\n            birrt_states_connected_fn\n                = [] (const Waypoint& first, const Waypoint& second, const bool)\n        {\n          return WaypointsEqual(first, second);\n        };\n        WaypointPlanningTree birrt_extend_start_tree;\n        birrt_extend_start_tree.emplace_back(\n            simple_rrt_planner::SimpleRRTPlannerState<Waypoint>(start));\n        WaypointPlanningTree birrt_extend_goal_tree;\n        birrt_extend_goal_tree.emplace_back(\n            simple_rrt_planner::SimpleRRTPlannerState<Waypoint>(goal));\n        const auto birrt_extent_path\n            = simple_rrt_planner::BiRRTPlanSinglePath<\n                std::mt19937_64, Waypoint, WaypointVector>(\n                    birrt_extend_start_tree, birrt_extend_goal_tree,\n                    state_sampling_fn, birrt_nearest_neighbors_fn,\n                    birrt_extend_fn, {}, birrt_states_connected_fn, {},\n                    birrt_tree_sampling_bias, birrt_p_switch_trees,\n                    simple_rrt_planner\n                        ::MakeBiRRTTimeoutTerminationFunction(rrt_timeout),\n                    prng).Path();\n        check_plan(test_env, {start}, {goal}, birrt_extent_path);\n        // Plan with BiRRT-Connect\n        std::cout << \"BiRRT-Connect Path (\" << print::Print(start) << \" to \"\n                  << print::Print(goal) << \")\" << std::endl;\n        WaypointPlanningTree birrt_connect_start_tree;\n        birrt_connect_start_tree.emplace_back(\n            simple_rrt_planner::SimpleRRTPlannerState<Waypoint>(start));\n        WaypointPlanningTree birrt_connect_goal_tree;\n        birrt_connect_goal_tree.emplace_back(\n            simple_rrt_planner::SimpleRRTPlannerState<Waypoint>(goal));\n        const auto birrt_connect_path\n            = simple_rrt_planner::BiRRTPlanSinglePath<\n                std::mt19937_64, Waypoint, WaypointVector>(\n                    birrt_connect_start_tree, birrt_connect_goal_tree,\n                    state_sampling_fn, birrt_nearest_neighbors_fn,\n                    birrt_connect_fn, {}, birrt_states_connected_fn, {},\n                    birrt_tree_sampling_bias, birrt_p_switch_trees,\n                    simple_rrt_planner\n                        ::MakeBiRRTTimeoutTerminationFunction(rrt_timeout),\n                    prng).Path();\n        check_plan(test_env, {start}, {goal}, birrt_connect_path);\n      }\n    }\n  }\n  // Plan with PRM\n  const WaypointVector starts = {keypoints.at(0), keypoints.at(1)};\n  const WaypointVector goals = {keypoints.at(2), keypoints.at(3)};\n  std::cout << \"Multi start/goal PRM Path (\" << print::Print(starts) << \" to \"\n            << print::Print(goals) << \")\" << std::endl;\n  const auto path = simple_prm_planner::QueryPath<Waypoint>(\n      starts, goals, loaded_roadmap, WaypointDistance, check_edge_validity_fn,\n      K, false, true, false).Path();\n  check_plan(test_env, starts, goals, path);\n}\n}  // namespace planning_test\n}  // namespace common_robotics_utilities\n\nint main(int argc, char** argv)\n{\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "4f0b8408da021785f6cff48473dc5defb00ad281", "size": 25354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/planning_test.cpp", "max_stars_repo_name": "calderpg/common_robotics_utilities", "max_stars_repo_head_hexsha": "8b1c06dd45b283f8234c6a4d565bcb7078d1a851", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-10-15T19:04:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T01:35:16.000Z", "max_issues_repo_path": "test/planning_test.cpp", "max_issues_repo_name": "calderpg/common_robotics_utilities", "max_issues_repo_head_hexsha": "8b1c06dd45b283f8234c6a4d565bcb7078d1a851", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-18T19:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-21T15:08:21.000Z", "max_forks_repo_path": "test/planning_test.cpp", "max_forks_repo_name": "calderpg/common_robotics_utilities", "max_forks_repo_head_hexsha": "8b1c06dd45b283f8234c6a4d565bcb7078d1a851", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-10-17T21:12:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-18T03:53:47.000Z", "avg_line_length": 41.2931596091, "max_line_length": 80, "alphanum_fraction": 0.6492466672, "num_tokens": 6090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5597200268164432}}
{"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": "\n#include <boost/test/unit_test.hpp>\n#include \"collision.h\"\n\nBOOST_AUTO_TEST_SUITE (test_collision)\n\nBOOST_AUTO_TEST_CASE (test_sphere_line_collision_1)\n{\n\tmath::sphere<2> sph;\n\tsph.centre.set(10, 10);\n\tsph.radius = 1;\n\n\tmath::line<2> l;\n\tl.A.set(-100, 0);\n\tl.B.set(100, 0);\n\n\tmath::contact_info<2> ci;\n\tmath::collide(l, sph, math::vec<2>(-2, -1), ci);\n\n\tBOOST_REQUIRE (ci.happened == true);\n\tBOOST_REQUIRE (math::abs(ci.time - 9.0f) < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_CASE (test_sphere_line_collision_2)\n{\n\tmath::sphere<2> sph;\n\tsph.centre.set(10, 0.5f);\n\tsph.radius = 1;\n\n\tmath::line<2> l;\n\tl.A.set(0, 0);\n\tl.B.set(0, 1);\n\n\tmath::contact_info<2> ci;\n\tmath::collide(l, sph, math::vec<2>(-1, 0), ci);\n\n\tBOOST_REQUIRE(ci.happened == true);\n\tBOOST_REQUIRE(math::abs(ci.time - 9.0f) < math::EPSILON);\n\tBOOST_REQUIRE((ci.position - math::vec<2>(0, 0.5f)).length_sq() < math::EPSILON);\n\tBOOST_REQUIRE((ci.normal - math::vec<2>(1, 0)).length_sq() < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_CASE (test_sphere_line_collision_3)\n{\n\tmath::line<2> l;\n\tl.A.set(1, -10);\n\tl.B.set(1, 10);\n\n\tmath::sphere<2> s;\n\ts.centre.set(10, 10);\n\ts.radius = 1;\n\n\tmath::contact_info<2> ci;\n\tmath::collide(l, s, math::vec<2>(-1, -1), ci);\n\n\tBOOST_REQUIRE ((ci.position - math::vec<2>(1, 2)).length() < math::EPSILON);\n\tBOOST_REQUIRE ((ci.time - 8) < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_CASE (test_sphere_obb_collision_1)\n{\n\tmath::obb<2> obb;\n\tobb.origin.set(0, 0);\n\tobb.tangent.set(1, 0);\n\tobb.normal.set(0, 1);\n\n\tmath::sphere<2> sph;\n\tsph.centre.set(0.5, 10);\n\tsph.radius = 1;\n\n\tmath::contact_info<2> ci;\n\tmath::collide(obb, sph, math::vec<2>(0, -1), ci);\n\n\tBOOST_REQUIRE ((ci.position - math::vec<2>(0.5, 1)).length() < math::EPSILON);\n\tBOOST_REQUIRE ((ci.normal - math::vec<2>(0, 1)).length() < math::EPSILON);\n\tBOOST_REQUIRE (math::abs(ci.time - 8) < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_CASE (test_sphere_obb_collision_2)\n{\n\tmath::obb<2> obb;\n\tobb.origin.set(0, 0);\n\tobb.tangent.set(1, 0);\n\tobb.normal.set(0, 1);\n\n\tmath::sphere<2> sph;\n\tsph.centre.set(10, 0.5f);\n\tsph.radius = 1;\n\n\tmath::contact_info<2> ci;\n\n\tmath::collide(obb, sph, math::vec<2>(-1.0f, -0.01f), ci);\n\n\tBOOST_REQUIRE ((ci.position - math::vec<2>(1, 0.42f)).length() < math::EPSILON);\n\tBOOST_REQUIRE ((ci.normal - math::vec<2>(1, 0)).length() < math::EPSILON);\n\tBOOST_REQUIRE ((ci.time - 8) < math::EPSILON);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a53365ce77692de83f61b008c61f7ab98ad0f373", "size": 2375, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/math/test_collision.cc", "max_stars_repo_name": "mnvl/scratch", "max_stars_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T11:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-15T11:55:32.000Z", "max_issues_repo_path": "src/math/test_collision.cc", "max_issues_repo_name": "mnvl/scratch", "max_issues_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/test_collision.cc", "max_forks_repo_name": "mnvl/scratch", "max_forks_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.75, "max_line_length": 82, "alphanum_fraction": 0.6534736842, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5597177326003087}}
{"text": "/* test_cauchy_distribution.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/cauchy_distribution.hpp>\r\n#include <limits>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::cauchy_distribution<>\r\n#define BOOST_RANDOM_ARG1 a\r\n#define BOOST_RANDOM_ARG2 b\r\n#define BOOST_RANDOM_ARG1_DEFAULT 0.0\r\n#define BOOST_RANDOM_ARG2_DEFAULT 1.0\r\n#define BOOST_RANDOM_ARG1_VALUE 7.5\r\n#define BOOST_RANDOM_ARG2_VALUE 0.25\r\n\r\n#define BOOST_RANDOM_DIST0_MIN -(std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST1_MIN -(std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST2_MIN -(std::numeric_limits<double>::infinity)()\r\n#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<double>::infinity)()\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS (-100000.0, 0.000001)\r\n#define BOOST_RANDOM_TEST2_PARAMS (100000.0, 0.000001)\r\n#define BOOST_RANDOM_TEST1_MAX 0.0\r\n#define BOOST_RANDOM_TEST2_MIN 0.0\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "dc26280f9773fa1258703b7e665bdb055a2c8f85", "size": 1280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_cauchy_distribution.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/random/test/test_cauchy_distribution.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/random/test/test_cauchy_distribution.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 35.5555555556, "max_line_length": 74, "alphanum_fraction": 0.778125, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5597012734506684}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <boost/math/special_functions/gegenbauer.hpp>\n#include <eve/function/gegenbauer.hpp>\n#include <eve/function/diff/gegenbauer.hpp>\n\n//==================================================================================================\n//== Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of gegenbauer on wide\"\n        , eve::test::simd::ieee_reals\n\n        )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  using wi_t = eve::as_integer_t<T>;\n  using i_t  = eve::as_integer_t<v_t>;\n  TTS_EXPR_IS( eve::gegenbauer(i_t(), T(), T())  , T);\n  TTS_EXPR_IS( eve::gegenbauer(wi_t(), T(), T())  , T);\n  TTS_EXPR_IS( eve::gegenbauer(i_t(), T(), v_t())  , T);\n  TTS_EXPR_IS( eve::gegenbauer(wi_t(), T(), v_t())  , T);\n};\n\n//==================================================================================================\n//== gegenbauer tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of gegenbauer on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::between(0.0, 1.0), eve::test::as_integer(eve::test::ramp(0)))\n        )\n  <typename T, typename I>(T const& a0,I const & i0)\n{\n  using v_t = eve::element_type_t<T>;\n  v_t l = v_t(-3)/v_t(8);\n  auto eve__gegenbauerv  =  [l](auto n, auto x) { return eve::gegenbauer(n, l, x); };\n  for(unsigned int n=0; n < 5; ++n)\n  {\n    auto boost_gegenbauer =  [&](auto i, auto) { return boost::math::gegenbauer(n, l, a0.get(i)); };\n    TTS_ULP_EQUAL(eve__gegenbauerv(n, a0), T(boost_gegenbauer), 180);\n  }\n  auto boost_gegenbauerv =  [&](auto i, auto) { return boost::math::gegenbauer(i0.get(i), l, a0.get(i)); };\n  TTS_ULP_EQUAL(eve__gegenbauerv(i0    , a0), T(boost_gegenbauerv), 180);\n  for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n  {\n    auto boost_gegenbauer2 =  [&](auto i, auto) { return boost::math::gegenbauer(i0.get(i), l, a0.get(j)); };\n    TTS_ULP_EQUAL(eve__gegenbauerv(i0 , a0.get(j)), T(boost_gegenbauer2), 180);\n  }\n  for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n  {\n    for(unsigned int n=0; n < eve::cardinal_v<T>; ++n)\n    {\n      TTS_ULP_EQUAL(eve__gegenbauerv(i0.get(j) , a0.get(n)), v_t(boost::math::gegenbauer(i0.get(j), l, a0.get(n))), 180);\n    }\n  }\n};\n\n\n//==================================================================================================\n//== gegenbauer diff  tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of gegenbauer diff on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::between(0.0, 1.0), eve::test::as_integer(eve::test::ramp(0)))\n        )\n  <typename T, typename I>(T const& a0,I const & i0)\n{\n   using v_t = eve::element_type_t<T>;\n  v_t l = v_t(-3)/v_t(8);\n   auto eve__gegenbauerv  =  [l](auto n, auto x) { return eve::diff( eve::gegenbauer)(n, l, x); };\n  for(unsigned int n=0; n < 5; ++n)\n  {\n    auto boost_gegenbauer =  [&](auto i, auto) { return boost::math::gegenbauer_derivative(n, l, a0.get(i), 1u); };\n    TTS_ULP_EQUAL(eve__gegenbauerv(n, a0), T(boost_gegenbauer), 180);\n  }\n  auto boost_gegenbauerv =  [&](auto i, auto) { return boost::math::gegenbauer_derivative(i0.get(i), l, a0.get(i), 1u); };\n  TTS_ULP_EQUAL(eve__gegenbauerv(i0    , a0), T(boost_gegenbauerv), 180);\n  for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n  {\n    auto boost_gegenbauer2 =  [&](auto i, auto) { return boost::math::gegenbauer_derivative(i0.get(i), l, a0.get(j), 1u); };\n    TTS_ULP_EQUAL(eve__gegenbauerv(i0 , a0.get(j)), T(boost_gegenbauer2), 180);\n  }\n  for(unsigned int j=0; j < eve::cardinal_v<T>; ++j)\n  {\n    for(unsigned int n=0; n < eve::cardinal_v<T>; ++n)\n    {\n      TTS_ULP_EQUAL(eve__gegenbauerv(i0.get(j) , a0.get(n)), v_t(boost::math::gegenbauer_derivative(i0.get(j), l, a0.get(n), 1u)), 180);\n    }\n }\n};\n", "meta": {"hexsha": "3ee9dd2eadae08ecc8f21b1f85eb3cd82c796b70", "size": 4322, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/polynomial/gegenbauer.cpp", "max_stars_repo_name": "leha-bot/eve", "max_stars_repo_head_hexsha": "30e7a7f6bcc5cf524a6c2cc624234148eee847be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/polynomial/gegenbauer.cpp", "max_issues_repo_name": "leha-bot/eve", "max_issues_repo_head_hexsha": "30e7a7f6bcc5cf524a6c2cc624234148eee847be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/polynomial/gegenbauer.cpp", "max_forks_repo_name": "leha-bot/eve", "max_forks_repo_head_hexsha": "30e7a7f6bcc5cf524a6c2cc624234148eee847be", "max_forks_repo_licenses": ["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.5567010309, "max_line_length": 136, "alphanum_fraction": 0.5113373438, "num_tokens": 1296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5597012734506683}}
{"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": "#include \"pow.h\"\r\n\r\n#include <cmath>\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace std;\r\n\r\nnamespace\r\n{\r\n\tfloat expf4to1(float x)\r\n\t{\r\n\t\t__declspec(align(16)) float v[4];\r\n\t\t_mm_store_ps(v, expf4(_mm_set1_ps(x)));\r\n\t\treturn v[0];\r\n\t}\r\n\r\n\tfloat expf8to1(float x)\r\n\t{\r\n\t\t__declspec(align(32)) float v[8];\r\n\t\t_mm256_store_ps(v, expf8(_mm256_set1_ps(x)));\r\n\t\treturn v[0];\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(Expf)\r\n{\r\n\tconst float tolerance = 0.001f;\r\n\r\n\tconst float args[] = { 0.01f, 0.1f, 0.5f, 1.0f, 2.0f, 5.0f };\r\n\tfor (float arg : args)\r\n\t{\r\n\t\tBOOST_CHECK_CLOSE(expf4to1( arg), exp( arg), tolerance);\r\n\t\tBOOST_CHECK_CLOSE(expf4to1(-arg), exp(-arg), tolerance);\r\n\t\tBOOST_CHECK_CLOSE(expf8to1( arg), exp( arg), tolerance);\r\n\t\tBOOST_CHECK_CLOSE(expf8to1(-arg), exp(-arg), tolerance);\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(Expf4_Fullness)\r\n{\r\n\tconst float x = 0.1f;\r\n\r\n\t__declspec(align(16)) float v[4];\r\n\t_mm_store_ps(v, expf4(_mm_set1_ps(x)));\r\n\r\n\tfor (size_t i = 1; i != 4; ++i)\r\n\t\tBOOST_CHECK_EQUAL(v[0], v[i]);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(Expf8_Fullness)\r\n{\r\n\tconst float x = 0.1f;\r\n\r\n\t__declspec(align(32)) float v[8];\r\n\t_mm256_store_ps(v, expf8(_mm256_set1_ps(x)));\r\n\r\n\tfor (size_t i = 1; i != 8; ++i)\r\n\t\tBOOST_CHECK_EQUAL(v[0], v[i]);\r\n}", "meta": {"hexsha": "09377d33d383dd25cca8288f79373a28218293c4", "size": 1265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "render/RenderTest/TestExp.cpp", "max_stars_repo_name": "don-reba/colors-visualization", "max_stars_repo_head_hexsha": "fe3937087be79715307127591a06f38b4647254f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "render/RenderTest/TestExp.cpp", "max_issues_repo_name": "don-reba/colors-visualization", "max_issues_repo_head_hexsha": "fe3937087be79715307127591a06f38b4647254f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "render/RenderTest/TestExp.cpp", "max_forks_repo_name": "don-reba/colors-visualization", "max_forks_repo_head_hexsha": "fe3937087be79715307127591a06f38b4647254f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.737704918, "max_line_length": 63, "alphanum_fraction": 0.6418972332, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5596376568279045}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/test_data.hpp>\n#include <fstream>\n#include \"mp_t.hpp\"\n\nusing namespace boost::math::tools;\n\nstruct beta_data_generator\n{\n   mp_t operator()(mp_t a, mp_t b)\n   {\n      if(a < b)\n         throw std::domain_error(\"\");\n      // very naively calculate spots:\n      mp_t g1, g2, g3;\n      int s1, s2, s3;\n      g1 = boost::math::lgamma(a, &s1);\n      g2 = boost::math::lgamma(b, &s2);\n      g3 = boost::math::lgamma(a+b, &s3);\n      g1 += g2 - g3;\n      g1 = exp(g1);\n      g1 *= s1 * s2 * s3;\n      return g1;\n   }\n};\n\n\nint main()\n{\n   parameter_info<mp_t> arg1, arg2;\n   test_data<mp_t> data;\n\n   std::cout << \"Welcome.\\n\"\n      \"This program will generate spot tests for the beta function:\\n\"\n      \"  beta(a, b)\\n\\n\";\n\n   bool cont;\n   std::string line;\n\n   do{\n      get_user_parameter_info(arg1, \"a\");\n      get_user_parameter_info(arg2, \"b\");\n      data.insert(beta_data_generator(), 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=beta_data.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"beta_data.ipp\";\n   std::ofstream ofs(line.c_str());\n   ofs << std::scientific << std::setprecision(40);\n   write_code(ofs, data, \"beta_data\");\n\n   return 0;\n}\n", "meta": {"hexsha": "b1765ac7e5ff0d4a82c9361a5cbe3fa6a75519ba", "size": 1741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/math/tools/beta_data.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/libs/math/tools/beta_data.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/libs/math/tools/beta_data.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 25.6029411765, "max_line_length": 71, "alphanum_fraction": 0.6105686387, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5596376554006561}}
{"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": "#ifndef POLYVEC_DERIV_TEST_IS_INCLUDED\n#define POLYVEC_DERIV_TEST_IS_INCLUDED\n\n#include <cstring>\n#include <iomanip>\n#include <iostream>\n\n#include <Eigen/Core>\n\nnamespace polyvec{\n  \nnamespace derivtest {\n//\n// Finite difference test\n//\n\ninline void\nrun(const Eigen::VectorXd &state, const Eigen::VectorXd &delta,\n    std::function<Eigen::VectorXd(const Eigen::VectorXd &)> eval,\n    std::function<Eigen::VectorXd(const Eigen::VectorXd &)> eval_jacobian,\n    std::ostream &cout = std::cout, int n_halving = 5, double h = 0.5) {\n  char dump[4096];\n  double diff0(0), diff1(0);\n\n  cout << std::setw(8) << \"n\" << std::setw(16) << \"DIFF0\" << std::setw(16)\n       << \"DIFF1\" << std::endl;\n\n  Eigen::VectorXd value0 = eval(state);\n  for (int ih = 0; ih < n_halving; ++ih) {\n    h /= 2.;\n\n    Eigen::VectorXd hdelta = h * delta;\n    Eigen::VectorXd value1exact = eval(state + hdelta);\n\n    eval(state);\n    Eigen::VectorXd linear_correction = eval_jacobian(hdelta);\n    Eigen::VectorXd value1lin = value0 + linear_correction;\n\n    double diff0new = (value0 - value1exact).norm();\n    double diff1new = (value1lin - value1exact).norm();\n    sprintf(dump, \"%8d %8.4e(%4.1f) %8.4e(%4.1f)  \\n\", ih, diff0new,\n            diff0 / diff0new, diff1new, diff1 / diff1new);\n    cout << dump;\n    cout.flush();\n    diff0 = diff0new;\n    diff1 = diff1new;\n  }\n} // All done\n\ninline void\nrun(const Eigen::VectorXd &state, const Eigen::VectorXd &delta,\n    std::function<Eigen::VectorXd(const Eigen::VectorXd &)> eval,\n    std::function<Eigen::VectorXd(const Eigen::VectorXd &)> eval_jacobian,\n    std::function<Eigen::VectorXd(const Eigen::VectorXd &)> eval_hessian,\n    std::ostream &cout = std::cout, int n_halving = 5, double h = 0.5) {\n  char dump[4096];\n  double diff0(0), diff1(0), diff2(0);\n\n  cout << std::setw(8) << \"n\" << std::setw(16) << \"DIFF0\" << std::setw(16)\n       << \"DIFF1\" << std::setw(16) << \"DIFF2\\n\";\n\n  Eigen::VectorXd value0 = eval(state);\n  for (int ih = 0; ih < n_halving; ++ih) {\n    h /= 2.;\n\n    Eigen::VectorXd hdelta = h * delta;\n    Eigen::VectorXd value1exact = eval(state + hdelta);\n\n    eval(state);\n    Eigen::VectorXd value1lin = value0 + eval_jacobian(hdelta);\n    Eigen::VectorXd value1quad = value1lin + 0.5 * eval_hessian(hdelta);\n\n    double diff0new = (value0 - value1exact).norm();\n    double diff1new = (value1lin - value1exact).norm();\n    double diff2new = (value1quad - value1exact).norm();\n    sprintf(dump, \"%8d %8.4e(%4.0f) %8.4e(%4.0f)  %8.4e(%4.0f)  \\n\", ih,\n            diff0new, diff0 / diff0new, diff1new, diff1 / diff1new, diff2new,\n            diff2 / diff2new);\n    cout << dump;\n    cout.flush();\n    diff0 = diff0new;\n    diff1 = diff1new;\n    diff2 = diff2new;\n  }\n} // All done\n\n} // namespace derivtest\n} // namespace polyvec\n\n#endif /* CONTRIB_DERIV_TEST_IS_INCLUDED */\n", "meta": {"hexsha": "879bf7d2d8aca4b9e8b410e792b2f01c31ec024e", "size": 2815, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/polyvec/utils/deriv_test.hpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "include/polyvec/utils/deriv_test.hpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "include/polyvec/utils/deriv_test.hpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 30.9340659341, "max_line_length": 77, "alphanum_fraction": 0.636589698, "num_tokens": 884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5596376501064616}}
{"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 * Copyright (C) tkornuta, IBM Corporation 2015-2019\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file tensor_test.cpp\n * \\brief Contains program for testing of tensors/Eigen map.\n * \\author tkornuta\n * \\date Feb 17, 2016\n */\n\n#include <iostream>\n#include <iomanip>\n\n#include <sys/time.h>\n\n#include <types/MatrixTypes.hpp>\n#include <types/TensorTypes.hpp>\n\n#include <fstream>\n// Include headers that implement a archive in simple text format\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n\n#include <boost/archive/xml_iarchive.hpp>\n#include <boost/archive/xml_oarchive.hpp>\n\n\nusing namespace Eigen;\nusing namespace std;\n\n\n/*\nEigen Concatenation\nHorizontally:\n\nMatrixXd C(A.rows(), A.cols()+B.cols());\nC << A, B;\n\nVertically:\n\nMatrixXd D(A.rows()+B.rows(), A.cols());\nD << A,\n     B;\n */\n\n/*!\n * \\brief Program for testing tensors/Eigen map\n * \\author tkornuta\n * @param[in] argc Number of parameters (not used).\n * @param[in] argv List of parameters (not used).\n * @return (not used).\n */\nint main(int argc, char* argv[]) {\n\t// Default sizes of matrices.\n\tconst size_t N = 2;\n\tconst size_t M = 3;\n\tconst size_t K = 4;\n\n\t// Create new tensor.\n\tmic::types::TensorXd t0({N, M});\n\tt0.enumerate();\n\tstd::cout << \"t0 = \" << t0 << std::endl;\n\tfor(size_t row=0; row<N; row++) {\n\t\tfor(size_t col=0; col<M; col++)\n\t\t\tstd::cout << \" t0(\" << row << \",\" << col << \") = \" << t0({row,col});\n\t\tstd::cout << std::endl;\n\t}//: for\n\n\n\t// Create new tensor.\n\tmic::types::TensorXd t1({N*M*K});\n\tt1.enumerate();\n\t// Different methods of setting the new value of data.\n\tt1({2}) = 33.1;\n\tt1(4) = 55;\n\tdouble* data = t1.data();\n\tdata[10] = 1000.1;\n\tstd::cout << \"t1 = \" << t1 << std::endl;\n\n\t// Conservative resize - with keeping the old values. Number of elements must remained unchanged!\n\tt1.conservativeResize({N, M, K});\n\tt1({2,2,2}) = 222.1;\n\tt1(5) = 666;\n\tstd::cout << \"resized t1 = \" << t1 << std::endl;\n\n\t// Get access to elements one by one.\n\tstd::cout << \"Printing elements one by one (getIndex): \";\n\tfor(size_t k=0; k<K; k++)\n\t\tfor(size_t m=0; m<M; m++)\n\t\t\tfor(size_t n=0; n<N; n++) {\n\t\t\t\tdouble d = t1({n,m,k});\n\t\t\t\tstd::cout << d << \", \";\n\t\t\t}//: for\n\tstd::cout << std::endl;\n\n\tstd::cout << \"Printing elements one by one: \";\n\tfor(size_t k=0; k<t1.size(); k++){\n\t\tdouble d = t1(k);\n\t\tstd::cout << d << \", \";\n\t}//: for\n\tstd::cout << std::endl;\n\n\n\t// Resize and change the total number of elements.\n\tt1.resize({4,4,4,4});\n\tt1.enumerate();\n\tstd::cout << \"resized t1 = \" << t1 << std::endl;\n\n\t// Get a subtensor.\n\tmic::types::TensorXd t2 = t1.block({{0,3},{0},{0},{0,1}});\n\tstd::cout << \"subtensor t2 = \" << t2 << std::endl;\n\n\t// Flatten both tensors.\n\tt1.flatten();\n\tstd::cout << \"flattened t1 = \" << t1 << std::endl;\n\tt2.flatten();\n\tstd::cout << \"flattened t2 = \" << t2 << std::endl;\n\n\t// Concatenate tensors - add t2 two times.\n\tt1.concatenate({t2,t2});\n\tstd::cout << \" t1 concatenated with {t2,t2} = \" << t1 << std::endl;\n\tt1.resize({3,2});\n\tstd::cout << \" t1 resized to {3, 2} = \" << t1 << std::endl;\n\n\t// Map 2D tensor to matrix.\n\tmic::types::Matrix<double> mat = t1;\n\tstd::cout << \"matrix from tensor = \\n\" <<  mat << std::endl;\n\tmat *= 2;\n\tstd::cout << \"matrix *2 = \\n\" <<  mat << std::endl;\n\n\t// Map matrix to 2D tensor.\n\tmic::types::TensorXd t4 = mat;\n\tstd::cout << \"tensor from matrix = \" << t4 << std::endl;\n\n\n\t// Tensor pointer.\n\tmic::types::TensorXfPtr ten_ptr (new mic::types::TensorXf({N, M, K}));\n\tten_ptr->enumerate();\n\tstd::cout << \"Pointer to tensor = \" << *ten_ptr << std::endl;\n\n} //: main\n\n", "meta": {"hexsha": "f1a87ea42dd2fa41635253f57a798af7846919a0", "size": 4064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/tensor_test.cpp", "max_stars_repo_name": "kant/mi-algorithms", "max_stars_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/tensor_test.cpp", "max_issues_repo_name": "kant/mi-algorithms", "max_issues_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/tensor_test.cpp", "max_forks_repo_name": "kant/mi-algorithms", "max_forks_repo_head_hexsha": "7e510577f57cb5e7d36c9d2506b61395739b0bef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-30T09:51:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T09:51:14.000Z", "avg_line_length": 26.2193548387, "max_line_length": 98, "alphanum_fraction": 0.6213090551, "num_tokens": 1243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.5596376440239366}}
{"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": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// This file is manually converted from PROJ4\n\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Geometry Library by Barend Gehrels (Geodan, Amsterdam)\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#ifndef BOOST_GEOMETRY_PROJECTIONS_PJ_TSFN_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_PJ_TSFN_HPP\n\n\n#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>\n\nnamespace boost { namespace geometry { namespace projections {\nnamespace detail {\n\n    /* determine small t */\n    inline double pj_tsfn(double phi, double sinphi, double e)\n    {\n        sinphi *= e;\n        return (tan (.5 * (HALFPI - phi)) /\n           pow((1. - sinphi) / (1. + sinphi), .5 * e));\n    }\n\n} // namespace detail\n}}} // namespace boost::geometry::projections\n#endif\n", "meta": {"hexsha": "b46ab87ebf6aef0748a37012a22fafc274465b1b", "size": 2268, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/gis/projections/impl/pj_tsfn.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "boost/geometry/extensions/gis/projections/impl/pj_tsfn.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "boost/geometry/extensions/gis/projections/impl/pj_tsfn.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 41.2363636364, "max_line_length": 79, "alphanum_fraction": 0.746031746, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5596358977185056}}
{"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": "#define BOOST_TEST_MODULE literals\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"exprtest.hpp\"\n\nEXPRTEST(literal1, \"1.234\",    1.234)\nEXPRTEST(literal2, \"4.2e2\",    420)\nEXPRTEST(literal3, \"5e-01\",    0.5)\nEXPRTEST(literal4, \"-3\",      -3)\nEXPRTEST(literal5, \"pi\",       boost::math::constants::pi<double>())\nEXPRTEST(literal6, \"epsilon\",  std::numeric_limits<double>::epsilon())\nEXPRTEST(literal9, \"e\",        boost::math::constants::e<double>())\n", "meta": {"hexsha": "80647b2d654b0277baf7fad345b76de34d753a6a", "size": 476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/literals.cpp", "max_stars_repo_name": "fweik/boost_matheval", "max_stars_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/literals.cpp", "max_issues_repo_name": "fweik/boost_matheval", "max_issues_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/literals.cpp", "max_forks_repo_name": "fweik/boost_matheval", "max_forks_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6153846154, "max_line_length": 70, "alphanum_fraction": 0.6890756303, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5594864186189193}}
{"text": "/*\n * ex8.cpp\n *\n * \t\\brief     Eigth exercise\n *  \\details   This class reads graph-data and computes the so-called Steiner-tree for it\n *  \\author    Julia Baumbach\n *  \\date      30.06.2017\n */\n\n#include \"Steiner.h\"\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <boost/program_options.hpp>\n\nusing namespace std;\nusing namespace boost::program_options;\n\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 i) {\n\tfor (int prime : result) {\n\t\tif ((i % prime) == 0 || prime/2 >= i) {\n\t\t\treturn true;\n\t\t}\n\t}return 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 */\nvector<int> computePrimes(int upperBound){\n\tvector<int> result;\n\tresult.push_back(2);\n\tfor(int i = 3; i < upperBound; i++){\n\t\tif(!hasDivisor(result, i)){\n\t\t\tresult.push_back(i);\n\t\t}\n\t}\n\treturn result;\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\n * \\return EXIT_SUCCESS if program exited correctly, otherwise EXIT_FAILURE\n */\nint main(int argc, char* argv[]){\n\toptions_description desc(\"\");\n\n\tdesc.add_options()\n\t\t(\"help,h\", \"Help screen\")\n\t    (\"startnodes,s\", value<vector<int> >()->multitoken(), \"Indizes of the start nodes\")\n\t\t(\"filename,f\", value<string>(), \"Filename for the graph\");\n\n\tcommand_line_parser parser{argc, argv};\n\tparser.options(desc).allow_unregistered().style(\n\t      command_line_style::default_style |\n\t      command_line_style::allow_slash_for_short);\n\tparsed_options parsed_options = parser.run();\n\n\tvariables_map variables;\n\tstore(parsed_options, variables);\n\tnotify(variables);\n\n\tif (variables.count(\"help\")){\n\t\tcout << desc << endl;\n\t}\n\tif(variables.count(\"filename\") == 0){\n\t\tcerr << \"Please enter a file name!\" << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tvector<int> startNodes;\n\tif(variables.count(\"startnode\") == 0){\n\t\tcout << \"Set default start node 2\" << endl;\n\t\tstartNodes.push_back(2);\n\t}else{\n\t\tstartNodes = variables[\"startnode\"].as<vector<int> >();\n\t}\n\n\tifstream infile;\n\tinfile.open(variables[\"filename\"].as<string>(), ios::in);\n\tif (!infile){\n\t\tcout << \"File could not be opened.\" << endl;\n\t\treturn 1;\n\t}\n\n\n\tstring line;\n\tstringstream s;\n\tunsigned int numberVertices;\n\tunsigned int numberEdges;\n\n\t//Read first line\n\tif (getline(infile, line)){\n\t\ts.str(line);\n\t\ts >> numberVertices >> numberEdges;\n\t\t//Number of vertices is one more than the real number of vertices for storing all the vertices correctly (it's 1-based)\n\t\tnumberVertices++;\n\t} else {\n\t\tcerr << \"Empty file. Exit program\" << endl;\n\t\treturn 1;\n\t}\n\n\t//Reading the edge data\n\tEdges edges;\n\tWeightMap weights;\n\tint startEdge;\n\tint endEdge;\n\tint weight;\n\n\twhile (getline(infile, line)){\n\t\tif (!line.empty()){\n\t\t\ts.clear();\n\t\t\ts.str(line);\n\t\t\ts >> startEdge >> endEdge >> weight;\n\t\t\tedges.push_back(make_pair(startEdge, endEdge));\n\t\t\tweights.push_back(weight);\n\t\t}\n\t}\n\tinfile.close();\n\n\t//Solve the Steiner Problem for the given graph and given start nodes\n\tSteiner mySteiner(numberVertices, edges, weights, computePrimes(numberVertices));\n\n\tEdges result;\n\tint minObjValue = INT_MAX;\n\tint minStartNode;\n\n\tfor(int startNode : startNodes){\n\t\tEdges temp_result = mySteiner.solveSteiner(startNode);\n\t\tif (mySteiner.getObjectiveValue() < minObjValue){\n\t\t\tminObjValue = mySteiner.getObjectiveValue();\n\t\t\tresult = temp_result;\n\t\t\tminStartNode = startNode;\n\t\t}\n\t}\n\n\t//print results\n\tcout << \"Minimal spanning tree is computed for starting node \" << minStartNode << endl;\n\n\tcout << \"Its edges of the minimal spanning tree are: \" << endl;\n\tfor(pair<int, int> result_pair : result){\n\t\tcout << result_pair.first << \" \" << result_pair.second << endl;\n\t}\n\n\tcout << \"The objective value of the minimal spanning tree is \" << minObjValue << endl;\n\n\treturn EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "f31d4c073140e45f0f4f6e2bd6fa1a7dc3902bbb", "size": 3997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Julia/ex8/src/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": "Julia/ex8/src/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": "Julia/ex8/src/ex8.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 25.1383647799, "max_line_length": 121, "alphanum_fraction": 0.6872654491, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.559486414031408}}
{"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": "#include \"drake/math/jacobian.h\"\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"drake/common/autodiff.h\"\n#include \"drake/common/eigen_types.h\"\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n#include \"drake/math/autodiff_gradient.h\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nnamespace drake {\nnamespace math {\nnamespace {\n\ntemplate <typename Derived>\n// TODO(#2274) Fix NOLINTNEXTLINE(runtime/references).\nvoid FillWithNumbersIncreasingFromZero(Eigen::MatrixBase<Derived>& matrix) {\n  for (Eigen::Index i = 0; i < matrix.size(); i++) {\n    matrix(i) = i;\n  }\n}\n\nclass AutodiffJacobianTest : public ::testing::Test {};\n\nTEST_F(AutodiffJacobianTest, QuadraticForm) {\n  using Eigen::Matrix3d;\n  using Eigen::Vector3d;\n\n  Matrix3d A;\n  FillWithNumbersIncreasingFromZero(A);\n\n  // Work around GCC 5.4 Wshadow bug; the bug is fixed as of GCC 6.1.\n  // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67273.\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wshadow\"\n  auto quadratic_form = [&](const auto& x) {\n#pragma GCC diagnostic pop\n    using Scalar = typename std::remove_reference<decltype(x)>::type::Scalar;\n    return (x.transpose() * A.cast<Scalar>().eval() * x).eval();\n  };\n\n  Vector3d x;\n  FillWithNumbersIncreasingFromZero(x);\n  auto jac_chunk_size_default = jacobian(quadratic_form, x);\n  auto jac_chunk_size_1 = jacobian<1>(quadratic_form, x);\n  auto jac_chunk_size_3 = jacobian<3>(quadratic_form, x);\n  auto jac_chunk_size_6 = jacobian<6>(quadratic_form, x);\n\n  // Ensure that chunk size has no effect on output type.\n  static_assert(std::is_same<decltype(jac_chunk_size_default),\n                             decltype(jac_chunk_size_1)>::value,\n                \"jacobian output type mismatch\");\n  static_assert(std::is_same<decltype(jac_chunk_size_default),\n                             decltype(jac_chunk_size_3)>::value,\n                \"jacobian output type mismatch\");\n  static_assert(std::is_same<decltype(jac_chunk_size_default),\n                             decltype(jac_chunk_size_6)>::value,\n                \"jacobian output type mismatch\");\n\n  // Ensure that the results are the same.\n  EXPECT_TRUE(jac_chunk_size_default == jac_chunk_size_1);\n  EXPECT_TRUE(jac_chunk_size_default == jac_chunk_size_3);\n  EXPECT_TRUE(jac_chunk_size_default == jac_chunk_size_6);\n\n  // Ensure that value is correct.\n  auto value_expected = quadratic_form(x);\n  auto value = autoDiffToValueMatrix(jac_chunk_size_default);\n  EXPECT_TRUE(CompareMatrices(value_expected, value, 1e-12,\n                              MatrixCompareType::absolute));\n\n  // Ensure that Jacobian is correct.\n  auto jac = autoDiffToGradientMatrix(jac_chunk_size_default);\n  auto jac_expected = (x.transpose() * (A + A.transpose())).eval();\n  EXPECT_TRUE(\n      CompareMatrices(jac_expected, jac, 1e-12, MatrixCompareType::absolute));\n}\n\nclass AutoDiffHessianTest : public ::testing::Test {};\n\n// Example: quadratic function\n// (A x + b)^T C (D x + e)\n// from http://www.ee.ic.ac.uk/hp/staff/dmb/matrix/calculus.html#Hessian.\nTEST_F(AutoDiffHessianTest, QuadraticFunction) {\n  using Eigen::MatrixXd;\n  using Eigen::VectorXd;\n  using Eigen::Index;\n\n  Index n = 4;\n  Index m = 5;\n\n  MatrixXd A(n, m);\n  VectorXd b(n);\n  MatrixXd C(n, n);\n  MatrixXd D(n, m);\n  VectorXd e(n);\n\n  FillWithNumbersIncreasingFromZero(A);\n  FillWithNumbersIncreasingFromZero(b);\n  FillWithNumbersIncreasingFromZero(C);\n  FillWithNumbersIncreasingFromZero(D);\n  FillWithNumbersIncreasingFromZero(e);\n\n  // Work around GCC 5.4 Wshadow bug; the bug is fixed as of GCC 6.1.\n  // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67273.\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wshadow\"\n  auto quadratic_function = [&](const auto& x) {\n#pragma GCC diagnostic pop\n    using Scalar = typename std::remove_reference<decltype(x)>::type::Scalar;\n    return ((A.cast<Scalar>() * x + b.cast<Scalar>()).transpose() *\n            C.cast<Scalar>() * (D.cast<Scalar>() * x + e.cast<Scalar>()))\n        .eval();\n  };\n\n  VectorXd x(m);\n  FillWithNumbersIncreasingFromZero(x);\n\n  auto hess_chunk_size_default = hessian(quadratic_function, x);\n  auto hess_chunk_size_2_4 = hessian<2, 4>(quadratic_function, x);\n\n  // Ensure that chunk size has no effect on output type.\n  static_assert(std::is_same<decltype(hess_chunk_size_default),\n                             decltype(hess_chunk_size_2_4)>::value,\n                \"hessian output type mismatch\");\n\n  // Ensure that the results are the same.\n  EXPECT_TRUE(hess_chunk_size_default == hess_chunk_size_2_4);\n\n  // Ensure that value is correct.\n  auto value_expected = quadratic_function(x);\n  auto value_autodiff = autoDiffToValueMatrix(hess_chunk_size_default);\n  auto value = autoDiffToValueMatrix(value_autodiff);\n  EXPECT_TRUE(CompareMatrices(value_expected, value, 1e-12,\n                              MatrixCompareType::absolute));\n\n  // Ensure that the two ways of computing the Jacobian from AutoDiff match.\n  auto jac_autodiff = autoDiffToGradientMatrix(hess_chunk_size_default);\n  auto jac1 = autoDiffToValueMatrix(jac_autodiff);\n  auto jac2 = autoDiffToGradientMatrix(value_autodiff);\n  EXPECT_TRUE(jac1 == jac2);\n\n  // Ensure that the Jacobian is correct.\n  auto jac_expected = ((A * x + b).transpose() * C * D +\n                       (D * x + e).transpose() * C.transpose() * A)\n                          .eval();\n  EXPECT_TRUE(\n      CompareMatrices(jac_expected, jac1, 1e-12, MatrixCompareType::absolute));\n\n  // Ensure that the Hessian is correct.\n  auto hess_expected =\n      (A.transpose() * C * D + D.transpose() * C.transpose() * A).eval();\n  auto hess = autoDiffToGradientMatrix(jac_autodiff);\n  EXPECT_TRUE(\n      CompareMatrices(hess_expected, hess, 1e-12, MatrixCompareType::absolute));\n}\n\n}  // namespace\n}  // namespace math\n}  // namespace drake\n", "meta": {"hexsha": "52c37c8f19b7d4ec5674b9503f58e27b9eb346dc", "size": 5810, "ext": "cc", "lang": "C++", "max_stars_repo_path": "math/test/jacobian_test.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "math/test/jacobian_test.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/test/jacobian_test.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 35.6441717791, "max_line_length": 80, "alphanum_fraction": 0.6989672978, "num_tokens": 1486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5594864094438964}}
{"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// \u0417\u0430\u0434\u0430\u0435\u043c \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u044b \u043a\u0432\u0430\u0434\u0440\u0430\u0442\u0430\n\tvector<vec2> p = placePolyOnEdge(calcRegularPolygon(n, vec2(0), 1, 0), 0);\n\n\t// \u0412\u044b\u0441\u0447\u0438\u0442\u044b\u0432\u0430\u0435\u043c \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u044b \u043f\u0440\u044f\u043c\u043e\u0443\u0433\u043e\u043b\u044c\u043d\u043e\u0433\u043e \u0442\u0440\u0435\u0443\u0433\u043e\u043b\u044c\u043d\u0438\u043a\u0430, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043b\u0435\u0436\u0438\u0442 \u0441\u0432\u043e\u0435\u0439 \u0433\u0438\u043f\u043e\u0442\u0435\u043d\u0443\u0437\u043e\u0439 \u043d\u0430 \u043e\u0441\u0438 X, \u0441 \u0443\u0433\u043b\u043e\u043c alpha \u043f\u0440\u0438 \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u0438\u0438\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// \u0420\u0438\u0441\u0443\u0435\u043c \u043a\u0432\u0430\u0434\u0440\u0430\u0442\n\tdraw_poly(fromMas(space, p), depth);\n\n\t// \u0421\u0442\u0440\u043e\u0438\u043c \u043f\u0440\u043e\u0441\u0442\u0440\u0430\u043d\u0441\u0442\u0432\u043e, \u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u043d\u0430\u0445\u043e\u0434\u0438\u0442\u0441\u044f \u043d\u0430 \u0432\u0435\u0440\u0445\u043d\u0435\u0439 \u0441\u0442\u043e\u0440\u043e\u043d\u0435 \u043a\u0432\u0430\u0434\u0440\u0430\u0442\u0430\n\tspace2 tr_line = makeLine2(p[m+1], p[m]);\n\n\t// \u041f\u0435\u0440\u0435\u0432\u043e\u0434\u0438\u043c \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u044b \u0442\u0440\u0435\u0443\u0433\u043e\u043b\u044c\u043d\u0438\u043a\u0430 \u043a \u044d\u0442\u043e\u043c\u0443 \u043f\u0440\u043e\u0441\u0442\u0440\u0430\u043d\u0441\u0442\u0432\u0443\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// \u0421\u0442\u0440\u043e\u0438\u043c \u043f\u0440\u043e\u0441\u0442\u0440\u0430\u043d\u0441\u0442\u0432\u0430, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043d\u0430\u0445\u043e\u0434\u044f\u0442\u0441\u044f \u043d\u0430 \u043e\u0431\u043e\u0438\u0445 \u043a\u0430\u0442\u0435\u0442\u0430\u0445 \u044d\u0442\u043e\u0433\u043e \u0442\u0440\u0435\u0443\u0433\u043e\u043b\u044c\u043d\u0438\u043a\u0430\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// \u0412\u044b\u0445\u043e\u0434\u0438\u043c \u0438\u0437 \u0440\u0435\u043a\u0443\u0440\u0441\u0438\u0438, \u0435\u0441\u043b\u0438 \u043e\u0434\u043d\u0430 \u0438\u0437 \u043e\u0441\u0435\u0439 (\u0430\u043d\u0430\u043b\u043e\u0433\u0438\u0447\u043d\u043e \u0438 \u0441\u0442\u043e\u0440\u043e\u043d\u0430 \u043a\u0432\u0430\u0434\u0440\u0430\u0442\u0430) \u0438\u043c\u0435\u0435\u0442 \u0434\u043b\u0438\u043d\u0443 \u043c\u0435\u043d\u044c\u0448\u0435, \u0447\u0435\u043c 2\n\tif (isTerminate(space.i, depth))\n\t\treturn;\n\n\tauto sp = getFractalSpaces(space, draw_poly, draw_triangle, depth);\n\n\t// \u0420\u0435\u043a\u0443\u0440\u0441\u0438\u0432\u043d\u043e \u0441\u0442\u0440\u043e\u0438\u043c \u0434\u0435\u0440\u0435\u0432\u043e \u0432 \u044d\u0442\u0438\u0445 \u043f\u0440\u043e\u0441\u0442\u0440\u0430\u043d\u0441\u0442\u0432\u0430\u0445\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// \u0421\u0447\u0438\u0442\u0430\u0435\u043c \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0438\u0432\u0430\u044e\u0449\u0438\u0439 \u043f\u0440\u044f\u043c\u043e\u0443\u0433\u043e\u043b\u044c\u043d\u0438\u043a \u0443 \u0444\u0440\u0430\u043a\u0442\u0430\u043b\u0430 \u0438 \u0441\u0438\u0441\u0442\u0435\u043c\u0443 \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442, \u043a\u043e\u0442\u043e\u0440\u0440\u0430\u044f \u0431\u0443\u0434\u0435\u0442 \u0438\u0434\u0435\u0430\u043b\u044c\u043d\u043e \u0441\u043c\u043e\u0442\u0440\u0435\u0442\u044c \u043d\u0430 \u0444\u0440\u0430\u043a\u0442\u0430\u043b \u0432\u043c\u0435\u0441\u0442\u0435 \u0441 \u0433\u0440\u0430\u043d\u0438\u0446\u0430\u043c\u0438\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// \u0418\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0438\u0440\u0443\u0435\u043c \u0432\u0441\u0435 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f\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// \u0418\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0438\u0440\u0443\u0435\u043c \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442 \u0438 \u0438\u043d\u0442\u0435\u0440\u043f\u043e\u043b\u044f\u0446\u0438\u044e\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// \u041e\u0441\u043d\u043e\u0432\u043d\u043e\u0439 \u0446\u0438\u043a\u043b \u0440\u0438\u0441\u043e\u0432\u0430\u043d\u0438\u044f\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// \u0421\u0435\u0442\u043a\u0430 \u0438 \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u044b \u043d\u0430 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0438-\u043e\u0431\u044a\u044f\u0441\u043d\u0435\u043d\u0438\u0438\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// \u0418\u043d\u0442\u0435\u0440\u043f\u043e\u043b\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u0430\u044f \u0441\u0438\u0441\u0442\u0435\u043c\u0430 \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\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// \u0421\u0430\u043c \u043f\u0440\u043e\u0446\u0435\u0441\u0441 \u0440\u0438\u0441\u043e\u0432\u0430\u043d\u0438\u044f \u0444\u0440\u0430\u043a\u0442\u0430\u043b\u0430\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// \u0420\u0438\u0441\u0443\u0435\u043c \u0432\u0441\u0435 \u0442\u0435\u043a\u0443\u0449\u0438\u0435 \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\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// \u0420\u0438\u0441\u0443\u0435\u043c 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// \u041d\u0430\u0447\u0430\u043b\u044c\u043d\u044b\u0435 \u0440\u0430\u0441\u0447\u0435\u0442\u044b\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// \u0426\u0438\u043a\u043b \u0440\u0430\u0441\u0447\u0435\u0442\u043e\u0432\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// \u041f\u043e\u0434\u0445\u043e\u0434 \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u043f\u043e\u043b\u0438\u043d\u043e\u043c\u043e\u0432 \u041b\u0430\u0433\u0440\u0430\u043d\u0436\u0430 \u0438 \u0432\u043e\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0438 \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u0432 \u0441\u0442\u0435\u043f\u0435\u043d\u044c\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// \u041f\u043e\u0434\u0445\u043e\u0434 \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u044f\u0434\u0435\u0440\u043d\u044b\u0445 \u0444\u0443\u043d\u043a\u0446\u0438\u0439 \u0438 \u0432\u043e\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0438 \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u0432 \u0441\u0442\u0435\u043f\u0435\u043d\u044c\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// \u0420\u0430\u0441\u0447\u0435\u0442 \u043e\u043a\u043d\u0430 \u0432\u0438\u0434\u0438\u043c\u043e\u0441\u0442\u0438 \u0438 \u0440\u0430\u0437\u043c\u0435\u0440\u0430 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f\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// \u0418\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0438\u0440\u0443\u0435\u043c \u0432\u0441\u0435 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f\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// \u0426\u0438\u043a\u043b \u0440\u0438\u0441\u043e\u0432\u0430\u043d\u0438\u044f\n\tfor (int i = 0; i < counts.size(); i++) {\n\t\t//img.setViewPort(counts[i]);\n\n\t\t// \u0420\u0438\u0441\u0443\u0435\u043c \u0441\u0435\u0442\u043a\u0443\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// \u0420\u0438\u0441\u0443\u0435\u043c \u0432\u0441\u0435 \u0442\u0435\u043a\u0443\u0449\u0438\u0435 \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\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": "/* ----------------------------------------------------------------------------\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   testGaussianFactor.cpp\n *  @brief  Unit tests for Linear Factor\n *  @author Christian Potthast\n *  @author Frank Dellaert\n **/\n\n#include <tests/smallExample.h>\n#include <gtsam/nonlinear/Symbol.h>\n#include <gtsam/nonlinear/Ordering.h>\n#include <gtsam/linear/GaussianConditional.h>\n#include <gtsam/base/Matrix.h>\n#include <gtsam/base/Testable.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/assign/std/list.hpp> // for operator +=\n#include <boost/assign/std/set.hpp>\n#include <boost/assign/std/map.hpp> // for insert\nusing namespace boost::assign;\n\n#include <iostream>\n\nusing namespace std;\nusing namespace gtsam;\n\n// Convenience for named keys\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\nstatic SharedDiagonal\n\tsigma0_1 = noiseModel::Isotropic::Sigma(2,0.1), sigma_02 = noiseModel::Isotropic::Sigma(2,0.2),\n\tconstraintModel = noiseModel::Constrained::All(2);\n\n//const Key kx1 = X(1), kx2 = X(2), kl1 = L(1); // FIXME: throws exception\n\n/* ************************************************************************* */\nTEST( GaussianFactor, linearFactor )\n{\n\tconst Key kx1 = X(1), kx2 = X(2), kl1 = L(1);\n  Ordering ordering; ordering += kx1,kx2,kl1;\n\n  Matrix I = eye(2);\n\tVector b = Vector_(2, 2.0, -1.0);\n\tJacobianFactor expected(ordering[kx1], -10*I,ordering[kx2], 10*I, b, noiseModel::Unit::Create(2));\n\n\t// create a small linear factor graph\n\tGaussianFactorGraph fg = example::createGaussianFactorGraph(ordering);\n\n\t// get the factor kf2 from the factor graph\n\tJacobianFactor::shared_ptr lf =\n\t    boost::dynamic_pointer_cast<JacobianFactor>(fg[1]);\n\n\t// check if the two factors are the same\n\tEXPECT(assert_equal(expected,*lf));\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactor, getDim )\n{\n\tconst Key kx1 = X(1), kx2 = X(2), kl1 = L(1);\n\t// get a factor\n  Ordering ordering; ordering += kx1,kx2,kl1;\n  GaussianFactorGraph fg = example::createGaussianFactorGraph(ordering);\n\tGaussianFactor::shared_ptr factor = fg[0];\n\n\t// get the size of a variable\n\tsize_t actual = factor->getDim(factor->find(ordering[kx1]));\n\n\t// verify\n\tsize_t expected = 2;\n\tEXPECT_LONGS_EQUAL(expected, actual);\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactor, error )\n{\n\tconst Key kx1 = X(1), kx2 = X(2), kl1 = L(1);\n\t// create a small linear factor graph\n  Ordering ordering; ordering += kx1,kx2,kl1;\n  GaussianFactorGraph fg = example::createGaussianFactorGraph(ordering);\n\n\t// get the first factor from the factor graph\n\tGaussianFactor::shared_ptr lf = fg[0];\n\n\t// check the error of the first factor with noisy config\n\tVectorValues cfg = example::createZeroDelta(ordering);\n\n\t// calculate the error from the factor kf1\n\t// note the error is the same as in testNonlinearFactor\n\tdouble actual = lf->error(cfg);\n\tDOUBLES_EQUAL( 1.0, actual, 0.00000001 );\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactor, matrix )\n{\n\tconst Key kx1 = X(1), kx2 = X(2), kl1 = L(1);\n\t// create a small linear factor graph\n  Ordering ordering; ordering += kx1,kx2,kl1;\n  GaussianFactorGraph fg = example::createGaussianFactorGraph(ordering);\n\n\t// get the factor kf2 from the factor graph\n\t//GaussianFactor::shared_ptr lf = fg[1]; // NOTE: using the older version\n\tVector b2 = Vector_(2, 0.2, -0.1);\n\tMatrix I = eye(2);\n  // render with a given ordering\n  Ordering ord;\n  ord += kx1,kx2;\n\tJacobianFactor::shared_ptr lf(new JacobianFactor(ord[kx1], -I, ord[kx2], I, b2, sigma0_1));\n\n\t// Test whitened version\n\tMatrix A_act1; Vector b_act1;\n\tboost::tie(A_act1,b_act1) = lf->matrix(true);\n\n\tMatrix A1 = Matrix_(2,4,\n\t\t\t-10.0,  0.0, 10.0,  0.0,\n\t\t\t000.0,-10.0,  0.0, 10.0 );\n\tVector b1 = Vector_(2, 2.0, -1.0);\n\n\tEQUALITY(A_act1,A1);\n\tEQUALITY(b_act1,b1);\n\n\t// Test unwhitened version\n\tMatrix A_act2; Vector b_act2;\n\tboost::tie(A_act2,b_act2) = lf->matrix(false);\n\n\n\tMatrix A2 = Matrix_(2,4,\n\t\t\t-1.0,  0.0, 1.0,  0.0,\n\t\t\t000.0,-1.0,  0.0, 1.0 );\n\t//Vector b2 = Vector_(2, 2.0, -1.0);\n\n\tEQUALITY(A_act2,A2);\n\tEQUALITY(b_act2,b2);\n\n\t// Ensure that whitening is consistent\n\tboost::shared_ptr<noiseModel::Gaussian> model = lf->get_model();\n\tmodel->WhitenSystem(A_act2, b_act2);\n\tEQUALITY(A_act1, A_act2);\n\tEQUALITY(b_act1, b_act2);\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactor, matrix_aug )\n{\n\tconst Key kx1 = X(1), kx2 = X(2), kl1 = L(1);\n\t// create a small linear factor graph\n  Ordering ordering; ordering += kx1,kx2,kl1;\n  GaussianFactorGraph fg = example::createGaussianFactorGraph(ordering);\n\n\t// get the factor kf2 from the factor graph\n\t//GaussianFactor::shared_ptr lf = fg[1];\n\tVector b2 = Vector_(2, 0.2, -0.1);\n\tMatrix I = eye(2);\n  // render with a given ordering\n  Ordering ord;\n  ord += kx1,kx2;\n\tJacobianFactor::shared_ptr lf(new JacobianFactor(ord[kx1], -I, ord[kx2], I, b2, sigma0_1));\n\n\n\t// Test unwhitened version\n\tMatrix Ab_act1;\n\tAb_act1 = lf->matrix_augmented(false);\n\n\tMatrix Ab1 = Matrix_(2,5,\n\t\t\t-1.0,  0.0, 1.0,  0.0,  0.2,\n\t\t\t00.0,- 1.0, 0.0,  1.0, -0.1 );\n\n\tEQUALITY(Ab_act1,Ab1);\n\n\t// Test whitened version\n\tMatrix Ab_act2;\n\tAb_act2 = lf->matrix_augmented(true);\n\n\tMatrix Ab2 = Matrix_(2,5,\n\t\t   -10.0,  0.0, 10.0,  0.0,  2.0,\n\t\t\t00.0, -10.0,  0.0, 10.0, -1.0 );\n\n\tEQUALITY(Ab_act2,Ab2);\n\n\t// Ensure that whitening is consistent\n\tboost::shared_ptr<noiseModel::Gaussian> model = lf->get_model();\n\tmodel->WhitenInPlace(Ab_act1);\n\tEQUALITY(Ab_act1, Ab_act2);\n}\n\n/* ************************************************************************* */\n// small aux. function to print out lists of anything\ntemplate<class T>\nvoid print(const list<T>& i) {\n\tcopy(i.begin(), i.end(), ostream_iterator<T> (cout, \",\"));\n\tcout << endl;\n}\n\n/* ************************************************************************* */\nTEST( GaussianFactor, size )\n{\n\t// create a linear factor graph\n\tconst Key kx1 = X(1), kx2 = X(2), kl1 = L(1);\n  Ordering ordering; ordering += kx1,kx2,kl1;\n  GaussianFactorGraph fg = example::createGaussianFactorGraph(ordering);\n\n\t// get some factors from the graph\n\tboost::shared_ptr<GaussianFactor> factor1 = fg[0];\n\tboost::shared_ptr<GaussianFactor> factor2 = fg[1];\n\tboost::shared_ptr<GaussianFactor> factor3 = fg[2];\n\n\tEXPECT_LONGS_EQUAL(1, factor1->size());\n\tEXPECT_LONGS_EQUAL(2, factor2->size());\n\tEXPECT_LONGS_EQUAL(2, factor3->size());\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "f5419b7ff76173c2d955a22b2350a3d6b0745c09", "size": 7044, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testGaussianFactor.cpp", "max_stars_repo_name": "sdmiller/gtsam_pcl", "max_stars_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T07:02:44.000Z", "max_issues_repo_path": "tests/testGaussianFactor.cpp", "max_issues_repo_name": "sdmiller/gtsam_pcl", "max_issues_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/testGaussianFactor.cpp", "max_forks_repo_name": "sdmiller/gtsam_pcl", "max_forks_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T12:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:02:48.000Z", "avg_line_length": 30.7598253275, "max_line_length": 99, "alphanum_fraction": 0.60959682, "num_tokens": 2052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.5594863972478246}}
{"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#include <Eigen/Dense>\n\n#include <basalt/utils/image.h>\n\n#include \"gtest/gtest.h\"\n#include \"test_utils.h\"\n\nvoid setImageData(uint16_t *imageArray, int size) {\n  double norm = RAND_MAX;\n  norm /= (double)std::numeric_limits<uint16_t>::max();\n\n  for (int i = 0; i < size; i++) {\n    imageArray[i] = (unsigned char)(rand() / norm);\n  }\n}\n\nTEST(Pattern, ImageInterp) {\n  Eigen::Vector2d offset(231.234242, 123.23424);\n\n  basalt::ManagedImage<uint16_t> img(640, 480);\n  setImageData(img.ptr, img.size());\n\n  Eigen::Vector3d vg = img.interpGrad(offset);\n\n  Eigen::Matrix<double, 1, 2> J = vg.tail<2>();\n\n  // std::cerr << \"vg\\n\" << vg << std::endl;\n\n  test_jacobian(\n      \"d_val_d_p\", J,\n      [&](const Eigen::Vector2d &x) {\n        Eigen::Matrix<double, 1, 1> res;\n        Eigen::Vector2d p1 = offset + x;\n        res[0] = img.interpGrad(p1)[0];\n        return res;\n      },\n      Eigen::Vector2d::Zero(), 1.0);\n}\n\nTEST(Image, ImageInterpolate) {\n  Eigen::Vector2i offset(231, 123);\n\n  basalt::ManagedImage<uint16_t> img(640, 480);\n  setImageData(img.ptr, img.size());\n\n  double eps = 1e-12;\n  double threshold = 1e-8;\n\n  {\n    Eigen::Vector2i pi = offset;\n    Eigen::Vector2d pd = pi.cast<double>() + Eigen::Vector2d(eps, eps);\n\n    uint16_t val1 = img(pi);\n    double val2 = img.interp(pd);\n    double val3 = img.interpGrad(pd)[0];\n\n    EXPECT_LE(std::abs(val2 - val1), threshold);\n    EXPECT_FLOAT_EQ(val2, val3);\n  }\n\n  {\n    Eigen::Vector2i pi = offset;\n    Eigen::Vector2d pd = pi.cast<double>() + Eigen::Vector2d(eps, eps);\n\n    uint16_t val1 = img(pi);\n    double val2 = img.interp(pd);\n    double val3 = img.interpGrad(pd)[0];\n\n    EXPECT_LE(std::abs(val2 - val1), threshold);\n    EXPECT_FLOAT_EQ(val2, val3);\n  }\n\n  {\n    Eigen::Vector2i pi = offset + Eigen::Vector2i(1, 0);\n    Eigen::Vector2d pd = pi.cast<double>() + Eigen::Vector2d(-eps, eps);\n\n    uint16_t val1 = img(pi);\n    double val2 = img.interp(pd);\n    double val3 = img.interpGrad(pd)[0];\n\n    EXPECT_LE(std::abs(val2 - val1), threshold);\n    EXPECT_FLOAT_EQ(val2, val3);\n  }\n\n  {\n    Eigen::Vector2i pi = offset + Eigen::Vector2i(0, 1);\n    Eigen::Vector2d pd = pi.cast<double>() + Eigen::Vector2d(eps, -eps);\n\n    uint16_t val1 = img(pi);\n    double val2 = img.interp(pd);\n    double val3 = img.interpGrad(pd)[0];\n\n    EXPECT_LE(std::abs(val2 - val1), threshold);\n    EXPECT_FLOAT_EQ(val2, val3);\n  }\n\n  {\n    Eigen::Vector2i pi = offset + Eigen::Vector2i(1, 1);\n    Eigen::Vector2d pd = pi.cast<double>() + Eigen::Vector2d(-eps, -eps);\n\n    uint16_t val1 = img(pi);\n    double val2 = img.interp(pd);\n    double val3 = img.interpGrad(pd)[0];\n\n    EXPECT_LE(std::abs(val2 - val1), threshold);\n    EXPECT_FLOAT_EQ(val2, val3);\n  }\n}\n\nTEST(Image, ImageInterpolateGrad) {\n  Eigen::Vector2i offset(231, 123);\n\n  basalt::ManagedImage<uint16_t> img(640, 480);\n  setImageData(img.ptr, img.size());\n\n  Eigen::Vector2d pd = offset.cast<double>() + Eigen::Vector2d(0.4, 0.34345);\n\n  Eigen::Vector3d valGrad = img.interpGrad<double>(pd);\n  Eigen::Matrix<double, 1, 2> J = valGrad.tail<2>();\n\n  test_jacobian(\n      \"d_res_d_x\", J,\n      [&](const Eigen::Vector2d &x) {\n        return Eigen::Matrix<double, 1, 1>(img.interp<double>(pd + x));\n      },\n      Eigen::Vector2d::Zero(), 1);\n}\n", "meta": {"hexsha": "e1f1375ef3f65a2ab2fb028d2bf50d3bbf25bf9d", "size": 3249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/test_image.cpp", "max_stars_repo_name": "Quitino/Non-LinearFactor-VIOSLAM", "max_stars_repo_head_hexsha": "84edc472c4e10905c823f1c9717e94487c0f7ce6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-06T07:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-06T07:56:14.000Z", "max_issues_repo_path": "test/src/test_image.cpp", "max_issues_repo_name": "maxee1900/basalt-mirror", "max_issues_repo_head_hexsha": "f958a7480de35420479defaa829b6aa0c8a31b26", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/src/test_image.cpp", "max_forks_repo_name": "maxee1900/basalt-mirror", "max_forks_repo_head_hexsha": "f958a7480de35420479defaa829b6aa0c8a31b26", "max_forks_repo_licenses": ["BSD-3-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.1860465116, "max_line_length": 77, "alphanum_fraction": 0.6183441059, "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5593220410704463}}
{"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": "/*\n * DIPlib 3.0\n * This file contains the definition of SeparateFilter().\n *\n * (c)2017, Cris Luengo.\n * Based on original DIPlib code: (c)1995-2014, Delft University of Technology.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"diplib.h\"\n#include \"diplib/linear.h\"\n#include \"diplib/pixel_table.h\"\n\n#if defined(__GNUG__) || defined(__clang__)\n// For this file, turn off -Wsign-conversion, Eigen is really bad at this!\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-conversion\"\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#if __GNUC__ >= 7\n#pragma GCC diagnostic ignored \"-Wint-in-bool-context\"\n#endif\n#if __GNUC__ >= 9\n#pragma GCC diagnostic ignored \"-Wdeprecated-copy\"\n#endif\n#endif\n\n#include <Eigen/SVD>\n\nnamespace dip {\n\nnamespace {\n\ntemplate< typename T > // T is either dfloat or dcomplex\nvoid dip__SeparateFilter(\n      Image& filter,\n      std::vector< dfloat >& out,\n      dip::uint nPixels,\n      dip::uint length\n) {\n   constexpr bool isComplex = std::is_same< T, dcomplex >::value;\n   using Matrix = Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic >;\n   using Vector = Eigen::Matrix< T, Eigen::Dynamic, 1 >;\n   // Make a matrix out of `filter` that has `nPixel` rows and `length` columns\n   Eigen::Map< Matrix > matrix( static_cast< T* >( filter.Origin() ),\n                                static_cast< Eigen::Index >( nPixels ),\n                                static_cast< Eigen::Index >( length ));\n   // Compute SVD\n   Eigen::JacobiSVD< Matrix > svd( matrix, Eigen::ComputeThinU | Eigen::ComputeThinV );\n   // Expect all but first singular value to be close to 0. If not, it's not separable, and we return {}.\n   auto S = svd.singularValues();\n   dfloat s1 = S( 0 );\n   dfloat s2 = S( 1 );\n   dfloat tolerance = 1e-7 * static_cast< dfloat >( std::max( nPixels, length )) * std::abs( s1 );\n   //std::cout << \"s1 = \" << s1 << \", s2 = \" << s2 << \", tol = \" << tolerance << std::endl;\n   if( s2 > tolerance ) {\n      // Not separable!\n      return;\n   }\n   // 1D filter is first column of V -- write V into 1D filter buffer\n   out.resize( length * ( isComplex ? 2 : 1 ));\n   Eigen::Map< Vector > oneDFilter( reinterpret_cast< T* >( out.data() ), static_cast< Eigen::Index >( length ));\n   oneDFilter = svd.matrixV().col( 0 );\n   // The ndims-1--dimensional remainder is the first column of U * singular value --\n   // write U * s1 back into input image, we'll use fewer pixels than before\n   Eigen::Map< Vector > remainder( static_cast< T* >( filter.Origin() ),\n                                   static_cast< Eigen::Index >( nPixels ));\n   remainder = svd.matrixU().col( 0 ) * s1;\n}\n\n} // namespace\n\nOneDimensionalFilterArray SeparateFilter( Image const& c_in ) {\n   DIP_THROW_IF( !c_in.IsForged(), E::IMAGE_NOT_FORGED );\n   DIP_THROW_IF( !c_in.IsScalar(), E::IMAGE_NOT_SCALAR );\n   dip::uint ndims = c_in.Dimensionality();\n   DIP_THROW_IF( ndims < 1, E::DIMENSIONALITY_NOT_SUPPORTED );\n   OneDimensionalFilterArray out( ndims );\n   // Complex data is handled a little differently from real data\n   bool isComplex = c_in.DataType().IsComplex();\n   // Copy the input image, we will need it as a scratch pad\n   Image filter = Convert( c_in, isComplex ? DT_DCOMPLEX : DT_DFLOAT ); // Filter is DFLOAT or DCOMPLEX and has normal strides\n   DIP_ASSERT( filter.HasNormalStrides() );\n   UnsignedArray sizes = filter.Sizes();\n   dip::uint nPixels = sizes.product();\n   // Shave dimensions off the filter from the end\n   while( ndims > 1 ) {\n      dip::uint dim = ndims - 1; // Current dimension\n      dip::uint length = sizes[ dim ]; // Number of pixels in 1D filter for this dimension\n      if( length > 1 ) {\n         nPixels /= length; // Number of pixels in remainder\n         if( isComplex ) {\n            dip__SeparateFilter< dcomplex >( filter, out[ dim ].filter, nPixels, length );\n            out[ dim ].isComplex = true;\n         } else {\n            dip__SeparateFilter< dfloat >( filter, out[ dim ].filter, nPixels, length );\n         }\n         if( out[ dim ].filter.empty() ) {\n            return {}; // The filter is not separable\n         }\n      }\n      // else: the output filter will have size 0, and we continue as usual.\n      --ndims;\n   }\n   out[ 0 ].filter.resize( nPixels * ( isComplex ? 2 : 1 ));\n   std::copy( static_cast< dfloat* >( filter.Origin() ),\n              static_cast< dfloat* >( filter.Origin() ) + nPixels * ( isComplex ? 2 : 1 ), // for complex data, copy two values per pixel\n              out[ 0 ].filter.data() );\n   out[ 0 ].isComplex = isComplex;\n   return out;\n}\n\n\n} // namespace dip\n\n\n#ifdef DIP__ENABLE_DOCTEST\n#include \"doctest.h\"\n#include \"diplib/statistics.h\"\n//#include \"diplib/timer.h\"\n\nDOCTEST_TEST_CASE(\"[DIPlib] testing the filter separation\") {\n   dip::Image delta3D( { 30, 30, 30 }, 1, dip::DT_SFLOAT );\n   delta3D.Fill( 0 );\n   delta3D.At( 15, 15, 15 ) = 1;\n\n   auto rectPt = dip::PixelTable( \"rectangular\", { 10, 11, 5 } );\n   dip::Image rect = dip::Convert( rectPt.AsImage(), dip::DT_UINT8 );\n   //dip::Timer timer;\n   dip::OneDimensionalFilterArray rect1 = dip::SeparateFilter( rect );\n   //timer.Stop();\n   //std::cout << \"Separating filter: \" << timer << std::endl;\n   DOCTEST_REQUIRE( rect1.size() == 3 );\n   DOCTEST_CHECK( rect1[ 0 ].filter.size() == 10 );\n   DOCTEST_CHECK( rect1[ 1 ].filter.size() == 11 );\n   DOCTEST_CHECK( rect1[ 2 ].filter.size() == 5 );\n   //timer.Reset();\n   //dip::Image tmp1 = dip::SeparableConvolution( delta3D, rect1 );\n   //timer.Stop();\n   //std::cout << \"Apply separated filter: \" << timer << std::endl;\n   //timer.Reset();\n   //dip::Image tmp2 = dip::GeneralConvolution( delta3D, rect );\n   //timer.Stop();\n   //std::cout << \"Apply full filter: \" << timer << std::endl;\n   //DOCTEST_CHECK( dip::All( tmp1 == tmp2 ).As< bool >() );\n   bool correct = true;\n   for( dip::uint ii = 0; ii < 3; ++ii ) {\n      for( auto v : rect1[ ii ].filter ) {\n         if( doctest::Approx( v ) != rect1[ ii ].filter[ 0 ] ) {\n            correct = false;\n         }\n      }\n   }\n   DOCTEST_CHECK( correct );\n   dip::dfloat product = rect1[ 0 ].filter[ 0 ] * rect1[ 1 ].filter[ 0 ] * rect1[ 2 ].filter[ 0 ];\n   DOCTEST_CHECK( product == doctest::Approx( 1.0 ));\n\n   auto circPt = dip::PixelTable( \"elliptic\", { 10, 11, 5 } );\n   dip::Image circ = dip::Convert( circPt.AsImage(), dip::DT_UINT8 );\n   //timer.Reset();\n   dip::OneDimensionalFilterArray circ1 = dip::SeparateFilter( circ );\n   //timer.Stop();\n   //std::cout << \"Separating filter: \" << timer << std::endl;\n   DOCTEST_CHECK( circ1.size() == 0 );\n\n   //timer.Reset();\n   dip::Image gaussRes = dip::GaussFIR( delta3D, { 3, 2, 3 }, { 1, 0, 2 } );\n   //timer.Stop();\n   //std::cout << \"Compute Gaussian: \" << timer << std::endl;\n   dip::Image gauss = gaussRes.Cropped( { 3 * 6 + 1, 2 * 6 + 1, 3 * 6 + 1 } );\n   //timer.Reset();\n   dip::OneDimensionalFilterArray gauss1 = dip::SeparateFilter( gauss );\n   //timer.Stop();\n   //std::cout << \"Separating filter: \" << timer << std::endl;\n   DOCTEST_REQUIRE( gauss1.size() == 3 );\n   //timer.Reset();\n   dip::Image tmp3 = dip::SeparableConvolution( delta3D, gauss1 );\n   //timer.Stop();\n   //std::cout << \"Apply separated filter: \" << timer << std::endl;\n   //timer.Reset();\n   //tmp2 = dip::GeneralConvolution( delta3D, gauss );\n   //timer.Stop();\n   //std::cout << \"Apply full filter: \" << timer << std::endl;\n   tmp3 -= gaussRes;\n   auto m = dip::MaximumAndMinimum( tmp3 );\n   DOCTEST_CHECK( m.Minimum() > -1e-5 );\n   DOCTEST_CHECK( m.Maximum() < 1e-5 );\n}\n\n#endif // DIP__ENABLE_DOCTEST\n", "meta": {"hexsha": "f7cade8e5d2fefd43a380063235da23ff2861af7", "size": 8024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/linear/separate_filter.cpp", "max_stars_repo_name": "slokhorst/diplib", "max_stars_repo_head_hexsha": "6e0f420243fd4e84888b5a5c25f805570fafd36d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/linear/separate_filter.cpp", "max_issues_repo_name": "slokhorst/diplib", "max_issues_repo_head_hexsha": "6e0f420243fd4e84888b5a5c25f805570fafd36d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linear/separate_filter.cpp", "max_forks_repo_name": "slokhorst/diplib", "max_forks_repo_head_hexsha": "6e0f420243fd4e84888b5a5c25f805570fafd36d", "max_forks_repo_licenses": ["Apache-2.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.92039801, "max_line_length": 137, "alphanum_fraction": 0.6235044865, "num_tokens": 2334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5593035254861839}}
{"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 << \"    |\u0421|_F             = \" << norm_F( C.get() ) << std::endl;\r\n        //std::cout << \"    |L|_F             = \" << norm_F( C_fac.get() ) << std::endl;\r\n        //std::cout << \"    |\u0421|_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": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2019 - 2021 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n// Config files\n\n#include <SAMRAI_config.h>\n\n// Headers for basic libMesh objects\n#include <libmesh/boundary_info.h>\n#include <libmesh/boundary_mesh.h>\n#include <libmesh/mesh.h>\n#include <libmesh/mesh_generation.h>\n#include <libmesh/mesh_refinement.h>\n\n// Headers for application-specific algorithm/data structure objects\n#include <ibtk/AppInitializer.h>\n#include <ibtk/FEMapping.h>\n#include <ibtk/IBTKInit.h>\n#include <ibtk/QuadratureCache.h>\n#include <ibtk/libmesh_utilities.h>\n\n// Set up application namespace declarations\n#include <boost/multi_array.hpp>\n\n#include <ibamr/app_namespaces.h>\n\n#include \"../tests.h\"\n\n// Verify that FEMapping and descendants output the same values as libMesh::FEMap.\nusing key_type = quadrature_key_type;\n\ntemplate <int dim, int spacedim>\nvoid\ntest_cube(LibMeshInit& init,\n          FEMapping<dim, spacedim>& jc_1,\n          FEMapping<dim, spacedim>& jc_2,\n          FEMapping<dim - 1, spacedim>& jc_boundary,\n          const key_type key)\n{\n    const auto elem_type = std::get<0>(key);\n\n    FEMapCache map_cache(dim);\n    QuadratureCache quad_cache(dim);\n\n    ReplicatedMesh mesh(init.comm(), dim);\n    if (dim == 2)\n        MeshTools::Generation::build_square(mesh, 10, 10, 0.0, 0.5, 0.0, 2.0, elem_type);\n    else if (dim == 3)\n        MeshTools::Generation::build_cube(mesh, 10, 10, 10, 0.0, 0.5, 0.0, 0.25, 0.0, 8.0, elem_type);\n    else\n        TBOX_ASSERT(false);\n\n    // check that we get the same thing with both calculators and libMesh's general code:\n    jc_1.reinit(*mesh.active_local_elements_begin());\n    const std::vector<double>& JxW = jc_1.getJxW();\n    for (const double jxw : JxW) plog << std::setprecision(12) << jxw << '\\n';\n\n    double volume = 0;\n    double volume_2 = 0;\n    for (auto elem_iter = mesh.active_local_elements_begin(); elem_iter != mesh.active_local_elements_end();\n         ++elem_iter)\n    {\n        FEMap& fe_map = map_cache[key];\n        QBase& quad = quad_cache[key];\n        fe_map.compute_map(dim, quad.get_weights(), *elem_iter, false);\n        // all computed JxW values should agree\n        jc_1.reinit(*elem_iter);\n        jc_2.reinit(*elem_iter);\n        const std::vector<double>& JxW = jc_1.getJxW();\n        const std::vector<double>& JxW_2 = jc_2.getJxW();\n        const std::vector<double>& JxW_3 = fe_map.get_JxW();\n        for (unsigned int i = 0; i < JxW.size(); ++i)\n        {\n            TBOX_ASSERT(std::abs(JxW[i] - JxW_2[i]) < 1e-14 * std::max(1.0, std::abs(JxW[i])));\n            TBOX_ASSERT(std::abs(JxW[i] - JxW_3[i]) < 1e-14 * std::max(1.0, std::abs(JxW[i])));\n        }\n        volume += std::accumulate(JxW.begin(), JxW.end(), 0.0);\n        volume_2 += std::accumulate(JxW_2.begin(), JxW_2.end(), 0.0);\n    }\n    TBOX_ASSERT(std::abs(volume - volume_2) < 1e-15 * volume);\n    plog << \"volume is \" << volume << '\\n';\n\n    // also test the surface mesh:\n    {\n        BoundaryMesh boundary_mesh(mesh.comm(), mesh.mesh_dimension() - 1);\n        BoundaryInfo& boundary_info = mesh.get_boundary_info();\n        boundary_info.sync(boundary_mesh);\n        boundary_mesh.prepare_for_use();\n        TBOX_ASSERT(boundary_mesh.spatial_dimension() == mesh.mesh_dimension());\n        TBOX_ASSERT(boundary_mesh.mesh_dimension() == mesh.mesh_dimension() - 1);\n\n        FEMapCache boundary_map_cache(dim - 1);\n        QuadratureCache boundary_quad_cache(dim - 1);\n\n        for (auto elem_iter = boundary_mesh.active_local_elements_begin();\n             elem_iter != boundary_mesh.active_local_elements_end();\n             ++elem_iter)\n        {\n            key_type boundary_key = key;\n            std::get<0>(boundary_key) = (*elem_iter)->type();\n\n            FEMap& fe_map = boundary_map_cache[boundary_key];\n            QBase& quad = boundary_quad_cache[boundary_key];\n            fe_map.compute_map(dim - 1, quad.get_weights(), *elem_iter, false);\n            // all computed JxW values should agree\n            jc_boundary.reinit(*elem_iter);\n            const std::vector<double>& JxW = jc_boundary.getJxW();\n            const std::vector<double>& JxW_2 = fe_map.get_JxW();\n            for (unsigned int i = 0; i < JxW.size(); ++i)\n            {\n                TBOX_ASSERT(std::abs(JxW[i] - JxW_2[i]) < 1e-14 * std::max(1.0, std::abs(JxW[i])));\n            }\n        }\n    }\n}\n\ntemplate <int dim, int spacedim>\nvoid\ntest_circle(LibMeshInit& init,\n            FEMapping<dim, spacedim>& jc_1,\n            FEMapping<dim, spacedim>& jc_2,\n            FEMapping<dim - 1, spacedim>& jc_boundary,\n            const int n_refines,\n            const key_type key)\n{\n    const auto elem_type = std::get<0>(key);\n\n    FEMapCache map_cache(dim);\n    QuadratureCache quad_cache(dim);\n\n    const double radius = 1.0;\n    ReplicatedMesh mesh(init.comm(), dim);\n    MeshTools::Generation::build_sphere(mesh, radius, n_refines, elem_type);\n\n    // Ensure nodes on the surface are on the analytic boundary.\n    MeshBase::element_iterator el_end = mesh.elements_end();\n    for (MeshBase::element_iterator el = mesh.elements_begin(); el != el_end; ++el)\n    {\n        Elem* const elem = *el;\n        for (unsigned int side = 0; side < elem->n_sides(); ++side)\n        {\n            const bool at_mesh_bdry = !elem->neighbor_ptr(side);\n            if (!at_mesh_bdry) continue;\n            for (unsigned int k = 0; k < elem->n_nodes(); ++k)\n            {\n                if (!elem->is_node_on_side(k, side)) continue;\n                Node& n = elem->node_ref(k);\n                n = radius * n.unit();\n            }\n        }\n    }\n    mesh.prepare_for_use();\n\n    // check that we get the same thing with both calculators and libMesh's general code:\n    jc_1.reinit(*mesh.active_local_elements_begin());\n    const std::vector<double>& JxW = jc_1.getJxW();\n    for (const double jxw : JxW) plog << std::setprecision(12) << jxw << '\\n';\n\n    double volume = 0;\n    double volume_2 = 0;\n    for (auto elem_iter = mesh.active_local_elements_begin(); elem_iter != mesh.active_local_elements_end();\n         ++elem_iter)\n    {\n        FEMap& fe_map = map_cache[key];\n        QBase& quad = quad_cache[key];\n        fe_map.compute_map(dim, quad.get_weights(), *elem_iter, false);\n        // all computed JxW values should agree\n        jc_1.reinit(*elem_iter);\n        jc_2.reinit(*elem_iter);\n        const std::vector<double>& JxW = jc_1.getJxW();\n        const std::vector<double>& JxW_2 = jc_2.getJxW();\n        const std::vector<double>& JxW_3 = fe_map.get_JxW();\n        for (unsigned int i = 0; i < JxW.size(); ++i)\n        {\n            TBOX_ASSERT(std::abs(JxW[i] - JxW_2[i]) < 1e-14 * std::max(1.0, std::abs(JxW[i])));\n            TBOX_ASSERT(std::abs(JxW[i] - JxW_3[i]) < 1e-14 * std::max(1.0, std::abs(JxW[i])));\n        }\n        volume += std::accumulate(JxW.begin(), JxW.end(), 0.0);\n        volume_2 += std::accumulate(JxW_2.begin(), JxW_2.end(), 0.0);\n    }\n    TBOX_ASSERT(std::abs(volume - volume_2) < 1e-15 * volume);\n    plog << \"volume is \" << volume << '\\n';\n\n    // also test the surface mesh:\n    {\n        BoundaryMesh boundary_mesh(mesh.comm(), mesh.mesh_dimension() - 1);\n        BoundaryInfo& boundary_info = mesh.get_boundary_info();\n        boundary_info.sync(boundary_mesh);\n        boundary_mesh.prepare_for_use();\n        TBOX_ASSERT(boundary_mesh.spatial_dimension() == mesh.mesh_dimension());\n        TBOX_ASSERT(boundary_mesh.mesh_dimension() == mesh.mesh_dimension() - 1);\n\n        FEMapCache boundary_map_cache(dim - 1);\n        QuadratureCache boundary_quad_cache(dim - 1);\n\n        for (auto elem_iter = boundary_mesh.active_local_elements_begin();\n             elem_iter != boundary_mesh.active_local_elements_end();\n             ++elem_iter)\n        {\n            key_type boundary_key = key;\n            std::get<0>(boundary_key) = (*elem_iter)->type();\n\n            FEMap& fe_map = boundary_map_cache[boundary_key];\n            QBase& quad = boundary_quad_cache[boundary_key];\n            fe_map.compute_map(dim - 1, quad.get_weights(), *elem_iter, false);\n            // all computed JxW values should agree\n            jc_boundary.reinit(*elem_iter);\n            const std::vector<double>& JxW = jc_boundary.getJxW();\n            const std::vector<double>& JxW_2 = fe_map.get_JxW();\n            for (unsigned int i = 0; i < JxW.size(); ++i)\n            {\n                TBOX_ASSERT(std::abs(JxW[i] - JxW_2[i]) < 1e-14 * std::max(1.0, std::abs(JxW[i])));\n            }\n        }\n    }\n}\n\nint\nmain(int argc, char** argv)\n{\n    // Initialize IBAMR and libraries. Deinitialization is handled by this object as well.\n    IBTKInit ibtk_init(argc, argv, MPI_COMM_WORLD);\n    LibMeshInit& init = ibtk_init.getLibMeshInit();\n\n    {\n        Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, \"IB.log\");\n\n        Pointer<Database> input_db = app_initializer->getInputDatabase();\n\n        unsigned int test_n = 1;\n        {\n            plog << \"Test \" << test_n << \": TRI3 square\" << std::endl;\n            const key_type key(TRI3, QGAUSS, THIRD, true);\n            Tri3Mapping jac_calc_1(key, FEUpdateFlags::update_JxW);\n            FELagrangeMapping<2> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(EDGE2, QGAUSS, THIRD, true);\n            FELagrangeMapping<1, 2> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_cube(init, jac_calc_1, jac_calc_2, jac_calc_b, key);\n            ++test_n;\n        }\n\n        {\n            plog << \"Test \" << test_n << \": TRI3 square\" << std::endl;\n            const key_type key(TRI3, QGAUSS, THIRD, true);\n            Tri3Mapping jac_calc_1(key, FEUpdateFlags::update_JxW);\n            FELagrangeMapping<2> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(EDGE2, QGAUSS, THIRD, true);\n            FELagrangeMapping<1, 2> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_cube(init, jac_calc_1, jac_calc_2, jac_calc_b, key);\n            ++test_n;\n        }\n\n        {\n            plog << \"Test \" << test_n << \": TRI6 square\" << std::endl;\n            const key_type key(TRI6, QGAUSS, FIFTH, true);\n            Tri6Mapping jac_calc_1(key, FEUpdateFlags::update_JxW);\n            FELagrangeMapping<2> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(EDGE2, QGAUSS, FIFTH, true);\n            FELagrangeMapping<1, 2> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_cube(init, jac_calc_1, jac_calc_2, jac_calc_b, key);\n            ++test_n;\n        }\n\n        {\n            plog << \"Test \" << test_n << \": TRI6 square\" << std::endl;\n            const key_type key(TRI6, QGAUSS, FIFTH, true);\n            Tri6Mapping jac_calc_1(key, FEUpdateFlags::update_JxW);\n            FELagrangeMapping<2> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(EDGE2, QGAUSS, FIFTH, true);\n            FELagrangeMapping<1, 2> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_cube(init, jac_calc_1, jac_calc_2, jac_calc_b, key);\n            ++test_n;\n        }\n\n        {\n            plog << \"Test \" << test_n << \": Quad4 square\" << std::endl;\n            const key_type key(QUAD4, QGAUSS, THIRD, true);\n            Quad4Mapping jac_calc_1(key, FEUpdateFlags::update_JxW);\n            FELagrangeMapping<2> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(EDGE2, QGAUSS, THIRD, true);\n            FELagrangeMapping<1, 2> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_cube(init, jac_calc_1, jac_calc_2, jac_calc_b, key);\n            ++test_n;\n        }\n\n        {\n            plog << \"Test \" << test_n << \": Quad4 circle\" << std::endl;\n            const key_type key(QUAD4, QGAUSS, THIRD, true);\n            Quad4Mapping jac_calc_1(key, FEUpdateFlags::update_JxW);\n            FELagrangeMapping<2> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(EDGE2, QGAUSS, THIRD, true);\n            FELagrangeMapping<1, 2> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_circle(init, jac_calc_1, jac_calc_2, jac_calc_b, 5, key);\n            ++test_n;\n        }\n\n        {\n            plog << \"Test \" << test_n << \": Quad9 square\" << std::endl;\n            const key_type key(QUAD9, QGAUSS, FOURTH, true);\n            Quad9Mapping jac_calc_1(key, FEUpdateFlags::update_JxW);\n            FELagrangeMapping<2> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(EDGE3, QGAUSS, FOURTH, true);\n            FELagrangeMapping<1, 2> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_cube(init, jac_calc_1, jac_calc_2, jac_calc_b, key);\n            ++test_n;\n        }\n\n        {\n            plog << \"Test \" << test_n << \": Quad9 circle\" << std::endl;\n            const key_type key(QUAD9, QGAUSS, FOURTH, true);\n            Quad9Mapping jac_calc_1(key, FEUpdateFlags::update_JxW);\n            FELagrangeMapping<2> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(EDGE3, QGAUSS, FOURTH, true);\n            FELagrangeMapping<1, 2> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_circle(init, jac_calc_1, jac_calc_2, jac_calc_b, 4, key);\n            ++test_n;\n        }\n\n        {\n            plog << \"Test \" << test_n << \": TET4 cube\" << std::endl;\n            const key_type key(TET4, QGAUSS, THIRD, true);\n            Tet4Mapping jac_calc_1(key, FEUpdateFlags::update_JxW);\n            FELagrangeMapping<3> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(TRI3, QGAUSS, THIRD, true);\n            FELagrangeMapping<2, 3> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_cube(init, jac_calc_1, jac_calc_2, jac_calc_b, key);\n            ++test_n;\n        }\n\n        {\n            plog << \"Test \" << test_n << \": HEX8 square\" << std::endl;\n            const key_type key(HEX8, QGAUSS, THIRD, true);\n            // HEX8 doesn't have a custom calculator yet\n            FELagrangeMapping<3> jac_calc_1(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            FELagrangeMapping<3> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(QUAD4, QGAUSS, THIRD, true);\n            FELagrangeMapping<2, 3> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_cube(init, jac_calc_1, jac_calc_2, jac_calc_b, key);\n            ++test_n;\n        }\n\n        {\n            plog << \"Test \" << test_n << \": HEX8 circle\" << std::endl;\n            const key_type key(HEX8, QGAUSS, THIRD, true);\n            // HEX8 doesn't have a custom calculator yet\n            FELagrangeMapping<3> jac_calc_1(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            FELagrangeMapping<3> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(QUAD4, QGAUSS, THIRD, true);\n            FELagrangeMapping<2, 3> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_circle(init, jac_calc_1, jac_calc_2, jac_calc_b, 4, key);\n            ++test_n;\n        }\n\n        {\n            plog << \"Test \" << test_n << \": HEX27 square\" << std::endl;\n            const key_type key(HEX27, QGAUSS, FOURTH, true);\n            // HEX27 doesn't have a custom calculator yet\n            FELagrangeMapping<3> jac_calc_1(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            FELagrangeMapping<3> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(QUAD9, QGAUSS, FOURTH, true);\n            FELagrangeMapping<2, 3> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_cube(init, jac_calc_1, jac_calc_2, jac_calc_b, key);\n            ++test_n;\n        }\n\n        {\n            plog << \"Test \" << test_n << \": HEX27 circle\" << std::endl;\n            const key_type key(HEX27, QGAUSS, FOURTH, true);\n            // HEX27 doesn't have a custom calculator yet\n            FELagrangeMapping<3> jac_calc_1(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            FELagrangeMapping<3> jac_calc_2(key, std::get<0>(key), FEUpdateFlags::update_JxW);\n            const key_type boundary_key(QUAD9, QGAUSS, FOURTH, true);\n            FELagrangeMapping<2, 3> jac_calc_b(boundary_key, std::get<0>(boundary_key), FEUpdateFlags::update_JxW);\n            test_circle(init, jac_calc_1, jac_calc_2, jac_calc_b, 2, key);\n            ++test_n;\n        }\n    }\n} // main\n", "meta": {"hexsha": "3347db93580ecf5cf99920a994bf3259b106eb6a", "size": 17366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/IBTK/jacobian_calc_01.cpp", "max_stars_repo_name": "akashdhruv/IBAMR", "max_stars_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 264.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T12:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:10:37.000Z", "max_issues_repo_path": "tests/IBTK/jacobian_calc_01.cpp", "max_issues_repo_name": "akashdhruv/IBAMR", "max_issues_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1057.0, "max_issues_repo_issues_event_min_datetime": "2015-04-27T04:27:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:14:59.000Z", "max_forks_repo_path": "tests/IBTK/jacobian_calc_01.cpp", "max_forks_repo_name": "drwells/IBAMR", "max_forks_repo_head_hexsha": "0ceda3873405a35da4888c99e7d2b24d132f9071", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 126.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T15:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T21:59:50.000Z", "avg_line_length": 44.6426735219, "max_line_length": 115, "alphanum_fraction": 0.6068755039, "num_tokens": 4951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.55922297402563}}
{"text": "#include <boost/mp11/mpl.hpp>\n#include <type_traits>\n\ntemplate <int I>\nusing int_ = std::integral_constant<int, I>;\n\nusing namespace boost::mp11;\n\ntemplate <typename Sequence, typename Value>\nstruct index_of_impl\n{\n\tusing index = mp_find<Sequence, Value>;\n\tusing size = mp_size<Sequence>;\n\tusing index_smaller_than_size = mp_less<index, size>;\n\tusing type = mp_if<index_smaller_than_size, index, int_<-1>>;\n};\n\ntemplate <typename Sequence, typename Value>\nusing index_of = typename index_of_impl<Sequence, Value>::type;\n\nint main()\n{\n\tusing l = mp_list_c<int, 5, 2, 3, 1, 4>;\n\n\tconstexpr int r1 = index_of<l, int_<3>>::value;\n\tstatic_assert(r1 == 2);\n\n\tconstexpr int r2 = index_of<l, int_<6>>::value;\n\tstatic_assert(r2 == -1);\n}\n", "meta": {"hexsha": "a9304e2cd440e9351966cca74c8df4a1362279da", "size": 729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "04_mp11_with_values/main.cpp", "max_stars_repo_name": "BorisSchaeling/boost-meta-programming-2020", "max_stars_repo_head_hexsha": "1bb70e88070953daa4bc19f91f891b43583df06e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "04_mp11_with_values/main.cpp", "max_issues_repo_name": "BorisSchaeling/boost-meta-programming-2020", "max_issues_repo_head_hexsha": "1bb70e88070953daa4bc19f91f891b43583df06e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "04_mp11_with_values/main.cpp", "max_forks_repo_name": "BorisSchaeling/boost-meta-programming-2020", "max_forks_repo_head_hexsha": "1bb70e88070953daa4bc19f91f891b43583df06e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5161290323, "max_line_length": 63, "alphanum_fraction": 0.7201646091, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5592229609699237}}
{"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": "// Copyright (c) 2015-2018, CNRS\n// Authors: Justin Carpentier <jcarpent@laas.fr>\n\n#ifndef __multicontact_api_geometry_ellipsoid_hpp__\n#define __multicontact_api_geometry_ellipsoid_hpp__\n\n#include <Eigen/Dense>\n#include <iostream>\n\n#include \"multicontact-api/geometry/fwd.hpp\"\n\nnamespace multicontact_api {\nnamespace geometry {\ntemplate <typename _Scalar, int _dim, int _Options>\nstruct Ellipsoid {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  typedef _Scalar Scalar;\n  enum { dim = _dim };\n  enum { Options = _Options };\n\n  typedef Eigen::Matrix<Scalar, dim, dim, Options> Matrix;\n  typedef Eigen::Matrix<Scalar, dim, 1, Options> Vector;\n\n  Ellipsoid(const Matrix& A, const Vector& center) : m_A(A), m_center(center) {}\n\n  Scalar lhsValue(const Vector& point) const { return (m_A * (point - m_center)).norm(); }\n\n  const Matrix& A() const { return m_A; }\n  Matrix& A() { return m_A; }\n  const Vector& center() const { return m_center; }\n  Vector& center() { return m_center; }\n\n  void disp(std::ostream& os) const {\n    os << \"A:\\n\" << m_A << std::endl << \"center: \" << m_center.transpose() << std::endl;\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const Ellipsoid& E) {\n    E.disp(os);\n    return os;\n  }\n\n protected:\n  /// \\brief\n  Matrix m_A;\n\n  /// \\brief Center of the ellipsoid expressed in the global frame.\n  Vector m_center;\n};\n}  // namespace geometry\n}  // namespace multicontact_api\n\n#endif  // ifndef __multicontact_api_geometry_ellipsoid_hpp__\n", "meta": {"hexsha": "ba4a596c99c74c6422b993f1014aff8e8633a9f0", "size": 1463, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/multicontact-api/geometry/ellipsoid.hpp", "max_stars_repo_name": "proyan/multicontact-api", "max_stars_repo_head_hexsha": "3ff225a2a114044dda07ee9d933dc060a96cc359", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-23T11:55:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T11:55:53.000Z", "max_issues_repo_path": "include/multicontact-api/geometry/ellipsoid.hpp", "max_issues_repo_name": "proyan/multicontact-api", "max_issues_repo_head_hexsha": "3ff225a2a114044dda07ee9d933dc060a96cc359", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2020-03-13T13:28:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:23:27.000Z", "max_forks_repo_path": "include/multicontact-api/geometry/ellipsoid.hpp", "max_forks_repo_name": "proyan/multicontact-api", "max_forks_repo_head_hexsha": "3ff225a2a114044dda07ee9d933dc060a96cc359", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T13:52:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T06:53:58.000Z", "avg_line_length": 27.6037735849, "max_line_length": 90, "alphanum_fraction": 0.7019822283, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5592082931684123}}
{"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": "// Copyright (c) 2012-2015 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"big_int.h\"\n\n#include \"bn_helpers.h\"\n#include <boost/test/unit_test.hpp>\n\n#include \"script/int_serialization.h\"\n#include \"script/interpreter.h\"\n#include \"script/script_flags.h\"\n#include \"taskcancellation.h\"\n\n#include \"config.h\"\n#include <vector>\n\nusing namespace std;\n\nusing frame_type = vector<uint8_t>;\nusing stack_type = vector<frame_type>;\n\nusing bsv::bint;\n\nconstexpr auto min64{std::numeric_limits<int64_t>::min() + 1};\nconstexpr auto max64{std::numeric_limits<int64_t>::max()};\n\nBOOST_AUTO_TEST_SUITE(bn_op_tests)\n\nBOOST_AUTO_TEST_CASE(bint_unary_ops)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    using polynomial = vector<int>;\n    using test_args = tuple<int64_t, polynomial, opcodetype, polynomial>;\n    // clang-format off\n    vector<test_args> test_data = {\n        {0, {-2}, OP_1ADD, {-1}},\n        {0, {-1}, OP_1ADD, {0}},\n        {0, {0}, OP_1ADD, {1}},\n        {0, {1}, OP_1ADD, {2}},\n        {max64, {1, 0}, OP_1ADD, {1, 1}},\n        {max64, {1, 1}, OP_1ADD, {1, 2}},\n\n        {0, {-1}, OP_1SUB, {-2}},\n        {0, {0}, OP_1SUB, {-1}},\n        {0, {1}, OP_1SUB, {0}},\n        {0, {2}, OP_1SUB, {1}},\n        {min64, {1, 0}, OP_1SUB, {1, -1}},\n        \n        {0, {-1}, OP_NEGATE, {1}},\n        {0, {0}, OP_NEGATE, {0}},\n        {0, {1}, OP_NEGATE, {-1}},\n        {max64, {1, 0}, OP_NEGATE, {-1, 0}},\n        {max64, {1, 1}, OP_NEGATE, {-1, -1}},\n        {min64, {1, 0}, OP_NEGATE, {-1, 0}},\n        {min64, {1, -1}, OP_NEGATE, {-1, 1}},\n      \n        {0, {-1}, OP_ABS, {1}},\n        {0, {0}, OP_ABS, {0}},\n        {0, {1}, OP_ABS, {1}},\n        {max64, {1, 1}, OP_ABS, {1, 1}},\n        {min64, {1, 1}, OP_ABS, {-1, -1}},\n        \n        {0, {-1}, OP_NOT, {0}},\n        {0, {0}, OP_NOT, {1}},\n        {0, {1}, OP_NOT, {0}},\n        {max64, {1, 1}, OP_NOT, {0}},\n        {min64, {1, 1}, OP_NOT, {0}},\n        \n        {0, {-1}, OP_0NOTEQUAL, {1}},\n        {0, {0}, OP_0NOTEQUAL, {0}},\n        {0, {1}, OP_0NOTEQUAL, {1}},\n        {max64, {1, 1}, OP_0NOTEQUAL, {1}},\n        {min64, {1, 1}, OP_0NOTEQUAL, {1}},\n    };\n    // clang-format on\n\n    for(const auto [n, arg_poly, op_code, exp_poly] : test_data)\n    {\n        const bint bn{n};\n\n        vector<uint8_t> args;\n        args.push_back(OP_PUSHDATA1);\n\n        const bint arg = polynomial_value(begin(arg_poly), end(arg_poly), bn);\n        const auto arg_serialized{arg.serialize()};\n        args.push_back(arg_serialized.size());\n        copy(begin(arg_serialized), end(arg_serialized), back_inserter(args));\n\n        args.push_back(op_code);\n\n        CScript script(args.begin(), args.end());\n\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n        ScriptError error;\n        auto source = task::CCancellationSource::Make();\n        LimitedStack stack(UINT32_MAX);\n        const auto status =\n            EvalScript(config, false, source->GetToken(), stack, script, flags,\n                       BaseSignatureChecker{}, &error);\n        BOOST_CHECK_EQUAL(true, status.value());\n        BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, error);\n        BOOST_CHECK_EQUAL(1, stack.size());\n        const auto frame = stack.front();\n        const auto actual =\n            frame.empty() ? bint{0} \n                          : bsv::bint::deserialize(frame.GetElement());\n        const bint expected =\n            polynomial_value(begin(exp_poly), end(exp_poly), bn);\n        BOOST_CHECK_EQUAL(expected, actual);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(bint_binary_ops)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    using polynomial = vector<int>;\n    using test_args =\n        tuple<int64_t, polynomial, polynomial, opcodetype, polynomial>;\n    vector<test_args> test_data = {\n        {max64, {1, 1}, {1, 1}, OP_ADD, {2, 2}},\n        {max64, {1, 1, 1}, {1, 0, 0}, OP_ADD, {2, 1, 1}},\n        {min64, {1, 0, 0}, {1, 0, 0}, OP_ADD, {2, 0, 0}},\n        {max64, {-1, 0, 0}, {1, 0, 0}, OP_ADD, {0}},\n        {min64, {1, 0, 0}, {-1, 0, 0}, OP_ADD, {0}},\n\n        {max64, {2, 0, 0}, {1, 0, 0}, OP_SUB, {1, 0, 0}},\n\n        {max64, {1, 0}, {1, 0}, OP_MUL, {1, 0, 0}},\n\n        {max64, {1, 0, 0}, {1, 0}, OP_DIV, {1, 0}},\n\n        {max64, {1, 0, 0}, {1, 0}, OP_MOD, {0}},\n        {max64, {1, 1, 1}, {1, 0}, OP_MOD, {1}},\n        {max64, {1, 1, 1, 1}, {1, 1, 0}, OP_MOD, {1, 1}},\n\n        {max64, {1, 0, 0}, {1, 0, 0}, OP_BOOLAND, {1}},\n        {max64, {1, 0, 0}, {0}, OP_BOOLAND, {0}},\n        {max64, {0}, {1, 0, 0}, OP_BOOLAND, {0}},\n        {max64, {0}, {0}, OP_BOOLAND, {0}},\n\n        {max64, {1, 0, 0}, {1, 0, 0}, OP_BOOLOR, {1}},\n        {max64, {1, 0, 0}, {0}, OP_BOOLOR, {1}},\n        {max64, {0}, {1, 0, 0}, OP_BOOLOR, {1}},\n        {max64, {0}, {0}, OP_BOOLOR, {0}},\n\n        {max64, {1, 0, 0}, {1, 0, 0}, OP_NUMEQUAL, {1}},\n        {max64, {1, 0, 0}, {-1, 0, 0}, OP_NUMEQUAL, {0}},\n        {max64, {1, 0, 0}, {2, 0, 0}, OP_NUMEQUAL, {0}},\n\n        {max64, {1, 0, 0}, {1, 0, 0}, OP_NUMNOTEQUAL, {0}},\n        {max64, {-1, 0, 0}, {1, 0, 0}, OP_NUMNOTEQUAL, {1}},\n\n        {max64, {-1, 0, 0}, {1, 0, 0}, OP_LESSTHAN, {1}},\n        {max64, {1, 0, 0}, {1, 0, 0}, OP_LESSTHAN, {0}},\n        {max64, {-1, 0, 0}, {-1, 0, 0}, OP_LESSTHAN, {0}},\n        {max64, {1, 0, 0}, {-1, 0, 0}, OP_LESSTHAN, {0}},\n\n        {max64, {-1, 0, 0}, {1, 0, 0}, OP_LESSTHANOREQUAL, {1}},\n        {max64, {1, 0, 0}, {1, 0, 0}, OP_LESSTHANOREQUAL, {1}},\n        {max64, {-1, 0, 0}, {-1, 0, 0}, OP_LESSTHANOREQUAL, {1}},\n        {max64, {1, 0, 0}, {-1, 0, 0}, OP_LESSTHANOREQUAL, {0}},\n\n        {max64, {1, 0, 0}, {-1, 0, 0}, OP_GREATERTHAN, {1}},\n        {max64, {1, 0, 0}, {1, 0, 0}, OP_GREATERTHAN, {0}},\n        {max64, {-1, 0, 0}, {-1, 0, 0}, OP_GREATERTHAN, {0}},\n        {max64, {-1, 0, 0}, {1, 0, 0}, OP_GREATERTHAN, {0}},\n\n        {max64, {-1, 0, 0}, {1, 0, 0}, OP_GREATERTHANOREQUAL, {0}},\n        {max64, {1, 0, 0}, {1, 0, 0}, OP_GREATERTHANOREQUAL, {1}},\n        {max64, {-1, 0, 0}, {-1, 0, 0}, OP_GREATERTHANOREQUAL, {1}},\n        {max64, {1, 0, 0}, {-1, 0, 0}, OP_GREATERTHANOREQUAL, {1}},\n\n        {max64, {-1, 0, 0}, {1, 0, 0}, OP_MIN, {-1, 0, 0}},\n        {max64, {1, 0, 0}, {-1, 0, 0}, OP_MIN, {-1, 0, 0}},\n\n        {max64, {-1, 0, 0}, {1, 0, 0}, OP_MAX, {1, 0, 0}},\n        {max64, {1, 0, 0}, {-1, 0, 0}, OP_MAX, {1, 0, 0}},\n    };\n\n    for(const auto [n, arg_0_poly, arg_1_poly, op_code, exp_poly] : test_data)\n    {\n        LimitedStack stack(UINT32_MAX);\n\n        const bint bn{n};\n        vector<uint8_t> args;\n\n        args.push_back(OP_PUSHDATA1);\n        const bint arg1 =\n            polynomial_value(begin(arg_0_poly), end(arg_0_poly), bn);\n        const auto arg1_serialized{arg1.serialize()};\n        args.push_back(arg1_serialized.size());\n        copy(begin(arg1_serialized), end(arg1_serialized), back_inserter(args));\n\n        args.push_back(OP_PUSHDATA1);\n        const bint arg2 =\n            polynomial_value(begin(arg_1_poly), end(arg_1_poly), bn);\n        const auto arg2_serialized{arg2.serialize()};\n        args.push_back(arg2_serialized.size());\n        copy(begin(arg2_serialized), end(arg2_serialized), back_inserter(args));\n\n        args.push_back(op_code);\n\n        CScript script(args.begin(), args.end());\n\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n        ScriptError error;\n        auto source = task::CCancellationSource::Make();\n        const auto status =\n            EvalScript(config, true, source->GetToken(), stack, script, flags,\n                       BaseSignatureChecker{}, &error);\n        BOOST_CHECK_EQUAL(true, status.value());\n        BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, error);\n        BOOST_CHECK_EQUAL(1, stack.size());\n        const auto frame = stack.front();\n        const auto actual =\n            frame.empty() ? bint{0}\n                          : bsv::bint::deserialize(frame.GetElement());\n        bint expected = polynomial_value(begin(exp_poly), end(exp_poly), bn);\n        BOOST_CHECK_EQUAL(expected, actual);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(bint_ternary_ops)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    using polynomial = vector<int>;\n    using test_args = tuple<int64_t, polynomial, polynomial, polynomial,\n                            opcodetype, polynomial>;\n    vector<test_args> test_data = {\n        {0, {-1}, {0}, {2}, OP_WITHIN, {0}}, // too low\n        {0, {0}, {0}, {2}, OP_WITHIN, {1}},  // lower boundary\n        {0, {1}, {0}, {2}, OP_WITHIN, {1}},  // in-between\n        {0, {2}, {0}, {2}, OP_WITHIN, {0}},  // upper boundary\n        {0, {4}, {0}, {2}, OP_WITHIN, {0}},  // too high\n\n        {max64, {1, -1}, {1, 0}, {1, 2}, OP_WITHIN, {0}}, // too low\n        {max64, {1, 0}, {1, 0}, {1, 2}, OP_WITHIN, {1}},  // lower boundary\n        {max64, {1, 1}, {1, 0}, {1, 2}, OP_WITHIN, {1}},  // in-between\n        {max64, {1, 2}, {1, 0}, {1, 2}, OP_WITHIN, {0}},  // upper boundary\n        {max64, {1, 4}, {1, 0}, {1, 2}, OP_WITHIN, {0}},  // too high\n\n        {max64, {2, -1}, {2, 0}, {2, 2}, OP_WITHIN, {0}}, // too low\n        {max64, {2, 0}, {2, 0}, {2, 2}, OP_WITHIN, {1}},  // lower boundary\n        {max64, {2, 1}, {2, 0}, {2, 2}, OP_WITHIN, {1}},  // in-between\n        {max64, {2, 2}, {2, 0}, {2, 2}, OP_WITHIN, {0}},  // upper boundary\n        {max64, {2, 4}, {2, 0}, {2, 2}, OP_WITHIN, {0}},  // too high\n    };\n\n    for(const auto [n, arg_0_poly, arg_1_poly, arg_2_poly, op_code, exp_poly] :\n        test_data)\n    {\n        LimitedStack stack(UINT32_MAX);\n\n        const bint bn{n};\n        vector<uint8_t> args;\n\n        args.push_back(OP_PUSHDATA1);\n        const bint arg1 =\n            polynomial_value(begin(arg_0_poly), end(arg_0_poly), bn);\n        const auto arg1_serialized{arg1.serialize()};\n        args.push_back(arg1_serialized.size());\n        copy(begin(arg1_serialized), end(arg1_serialized), back_inserter(args));\n\n        args.push_back(OP_PUSHDATA1);\n        const bint arg2 =\n            polynomial_value(begin(arg_1_poly), end(arg_1_poly), bn);\n        const auto arg2_serialized{arg2.serialize()};\n        args.push_back(arg2_serialized.size());\n        copy(begin(arg2_serialized), end(arg2_serialized), back_inserter(args));\n\n        args.push_back(OP_PUSHDATA1);\n        const bint arg3 =\n            polynomial_value(begin(arg_2_poly), end(arg_2_poly), bn);\n        const auto arg3_serialized{arg3.serialize()};\n        args.push_back(arg3_serialized.size());\n        copy(begin(arg3_serialized), end(arg3_serialized), back_inserter(args));\n\n        args.push_back(op_code);\n\n        CScript script(args.begin(), args.end());\n\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n        ScriptError error;\n        auto source = task::CCancellationSource::Make();\n        const auto status =\n            EvalScript(config, true, source->GetToken(), stack, script, flags,\n                       BaseSignatureChecker{}, &error);\n        BOOST_CHECK_EQUAL(true, status.value());\n        BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, error);\n        BOOST_CHECK_EQUAL(1, stack.size());\n        const auto frame = stack.front();\n        const auto actual =\n            frame.empty() ? bint{0}\n                          : bsv::bint::deserialize(frame.GetElement());\n        bint expected = polynomial_value(begin(exp_poly), end(exp_poly), bn);\n        BOOST_CHECK_EQUAL(expected, actual);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(bint_bint_numequalverify)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    using polynomial = vector<int>;\n    using test_args =\n        tuple<int64_t, polynomial, polynomial, opcodetype, polynomial>;\n    vector<test_args> test_data = {\n        {max64, {1, 1}, {1, 1}, OP_NUMEQUALVERIFY, {0}},\n        {max64, {1, 0, 0}, {1, 0, 0}, OP_NUMEQUALVERIFY, {0}},\n        {max64, {1, 0, 0}, {-1, 0, 0}, OP_NUMEQUALVERIFY, {0}},\n        {max64, {2, 0, 0}, {-1, 0, 0}, OP_NUMEQUALVERIFY, {0}},\n    };\n\n    for(const auto [n, arg_0_poly, arg_1_poly, op_code, exp_poly] : test_data)\n    {\n        LimitedStack stack(UINT32_MAX);\n\n        const bint bn{n};\n        vector<uint8_t> args;\n\n        args.push_back(OP_PUSHDATA1);\n        const bint arg1 =\n            polynomial_value(begin(arg_0_poly), end(arg_0_poly), bn);\n        const auto arg1_serialized{arg1.serialize()};\n        args.push_back(arg1_serialized.size());\n        copy(begin(arg1_serialized), end(arg1_serialized), back_inserter(args));\n\n        args.push_back(OP_PUSHDATA1);\n        const bint arg2 =\n            polynomial_value(begin(arg_1_poly), end(arg_1_poly), bn);\n        const auto arg2_serialized{arg2.serialize()};\n        args.push_back(arg2_serialized.size());\n        copy(begin(arg2_serialized), end(arg2_serialized), back_inserter(args));\n\n        args.push_back(op_code);\n\n        CScript script(args.begin(), args.end());\n\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n        ScriptError error;\n        auto source = task::CCancellationSource::Make();\n        const auto status =\n            EvalScript(config, true, source->GetToken(), stack, script, flags,\n                       BaseSignatureChecker{}, &error);\n        if(status.value())\n        {\n            BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, error);\n            BOOST_CHECK(stack.empty());\n        }\n        else\n        {\n            BOOST_CHECK_EQUAL(SCRIPT_ERR_NUMEQUALVERIFY, error);\n            BOOST_CHECK_EQUAL(1, stack.size());\n            auto frame = stack.front();\n            auto actual =\n                frame.empty()\n                    ? bint{0}\n                    : bsv::bint::deserialize(frame.GetElement());\n            bint expected =\n                polynomial_value(begin(exp_poly), end(exp_poly), bn);\n            BOOST_CHECK_EQUAL(expected, actual);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(operands_too_large)\n{\n    GlobalConfig& config = GlobalConfig::GetConfig();\n    using test_args = tuple<int, int, opcodetype, bool, ScriptError>;\n    const auto max_arg_len{ MAX_SCRIPT_NUM_LENGTH_AFTER_GENESIS };\n\n    // set policy for script size, stack memory usage and max number length in scripts \n    // to default after genesis\n    config.SetMaxScriptSizePolicy(0);\n    config.SetMaxStackMemoryUsage(0, 0);\n    config.SetMaxScriptNumLengthPolicy(max_arg_len);\n\n    // clang-format off\n    vector<test_args> test_data = {\n    {max_arg_len,   max_arg_len,   OP_ADD, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_ADD, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_ADD, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_ADD, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_SUB, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_SUB, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_SUB, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_SUB, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_MUL, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_MUL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_MUL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_MUL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_DIV, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_DIV, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_DIV, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_DIV, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_MOD, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_MOD, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_MOD, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_MOD, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_BOOLAND, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_BOOLAND, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_BOOLAND, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_BOOLAND, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_BOOLOR, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_BOOLOR, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_BOOLOR, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_BOOLOR, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_NUMEQUAL, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_NUMEQUAL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_NUMEQUAL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_NUMEQUAL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_NUMNOTEQUAL, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_NUMNOTEQUAL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_NUMNOTEQUAL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_NUMNOTEQUAL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_LESSTHAN, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_LESSTHAN, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_LESSTHAN, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_LESSTHAN, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_LESSTHANOREQUAL, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_LESSTHANOREQUAL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_LESSTHANOREQUAL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_LESSTHANOREQUAL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_GREATERTHAN, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_GREATERTHAN, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_GREATERTHAN, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_GREATERTHAN, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_GREATERTHANOREQUAL, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_GREATERTHANOREQUAL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_GREATERTHANOREQUAL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_GREATERTHANOREQUAL, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_MIN, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_MIN, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_MIN, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_MIN, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len,   OP_MAX, true,  SCRIPT_ERR_OK},\n    {max_arg_len + 1, max_arg_len,   OP_MAX, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len,   max_arg_len + 1, OP_MAX, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    {max_arg_len + 1, max_arg_len + 1, OP_MAX, false, SCRIPT_ERR_SCRIPTNUM_OVERFLOW},\n    };\n    // clang-format on\n\n    for (const auto [arg0_size, arg1_size, op_code, exp_status,\n        exp_script_error] : test_data)\n    {\n        LimitedStack stack(UINT32_MAX);\n\n        vector<uint8_t> arg0(arg0_size, 42);\n        vector<uint8_t> arg1(arg1_size, 69);\n\n        CScript script = CScript() << arg0 << arg1 << op_code;\n\n        const auto flags{ SCRIPT_UTXO_AFTER_GENESIS };\n        ScriptError error;\n        auto source = task::CCancellationSource::Make();\n        const auto status =\n            EvalScript(config, false, source->GetToken(), stack, script, flags,\n                BaseSignatureChecker{}, &error);\n        BOOST_CHECK_EQUAL(exp_status, status.value());\n        BOOST_CHECK_EQUAL(exp_script_error, error);\n        BOOST_CHECK_EQUAL(status.value() ? 1 : 2, stack.size());\n    }\n}\n\nBOOST_AUTO_TEST_CASE(op_bin2num)\n{\n    const Config& config = GlobalConfig::GetConfig();\n    // clang-format off\n    vector<tuple<vector<uint8_t>, vector<uint8_t>>> test_data = {\n        { {}, {}},\n        { {0x1}, {0x1}},               // +1\n        { {0x7f}, {0x7f}},             // +127 \n        { {0x80, 0x0}, {0x80, 0x0}},   // +128\n        { {0xff, 0x0}, {0xff, 0x0}},   // 255\n        { {0x81}, {0x81}},             // -1\n        { {0xff}, {0xff}},             // -127 \n        { {0x80, 0x80}, {0x80, 0x80}}, // -128\n        { {0xff, 0x80}, {0xff, 0x80}}, // -255\n        { {0x1, 0x0}, {0x1}},           // should be 0x1 for +1\n        { {0x7f, 0x80}, {0xff}},        // should be 0xff for -127\n        { {0x1, 0x2, 0x3, 0x4, 0x5}, {0x1, 0x2, 0x3, 0x4, 0x5}} // invalid range?\n    };\n    // clang-format on\n    for(auto& [ip, op] : test_data)\n    {\n        LimitedStack stack(UINT32_MAX);\n        vector<uint8_t> args;\n\n        args.push_back(OP_PUSHDATA1);\n        args.push_back(ip.size());\n        copy(begin(ip), end(ip), back_inserter(args));\n\n        args.push_back(OP_BIN2NUM);\n\n        CScript script(args.begin(), args.end());\n\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n        ScriptError error;\n        const auto status = EvalScript(\n            config, false, task::CCancellationSource::Make()->GetToken(), stack,\n            script, flags, BaseSignatureChecker{}, &error);\n\n        BOOST_CHECK_EQUAL(true, status.value());\n        BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, error);\n        BOOST_CHECK_EQUAL(1, stack.size());\n        BOOST_CHECK_EQUAL(op.size(), stack.front().size());\n        BOOST_CHECK_EQUAL_COLLECTIONS(begin(stack.front()), end(stack.front()), begin(op),\n                                      end(op));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(op_num2bin)\n{\n    const Config& config = GlobalConfig::GetConfig();\n    // clang-format off\n    vector<tuple<vector<uint8_t>, \n                 vector<uint8_t>,\n                 bool,\n                 ScriptError,\n                 vector<uint8_t>>> test_data = {\n\n        { {}, {}, true, SCRIPT_ERR_OK, {}},\n        { {}, {0x0}, true, SCRIPT_ERR_OK, {}},\n        { {}, {0x1}, true, SCRIPT_ERR_OK, {0x0}},\n        { {}, {0x2}, true, SCRIPT_ERR_OK, {0x0, 0x0}},\n        { {0x0}, {0x0}, true, SCRIPT_ERR_OK, {}},\n        { {0x0}, {0x1}, true, SCRIPT_ERR_OK, {0x0}},\n        { {0x0}, {0x2}, true, SCRIPT_ERR_OK, {0x0, 0x0}},\n        { {0x1}, {0x1}, true, SCRIPT_ERR_OK, { 0x1}},\n        { {0x1, 0x2}, {0x2}, true, SCRIPT_ERR_OK, { 0x1, 0x2}},\n        { {0x1, 0x2, 0x3}, {0x3}, true, SCRIPT_ERR_OK, { 0x1, 0x2, 0x3}},\n        { {0x1, 0x2, 0x3, 0x4}, {0x4}, true, SCRIPT_ERR_OK, { 0x1, 0x2, 0x3, 0x4}},\n        { {0x1, 0x2, 0x3, 0x4, 0x5}, {0x5}, true, SCRIPT_ERR_OK, { 0x1, 0x2, 0x3, 0x4, 0x5}},\n        \n        // 0x0 used as padding\n        { {0x1}, {0x2}, true, SCRIPT_ERR_OK, {0x1, 0x0}},\n        { {0x2}, {0x2}, true, SCRIPT_ERR_OK, {0x2, 0x0}},\n\n        // -ve numbers \n        { {0x81}, {0x1}, true, SCRIPT_ERR_OK, {0x81}},          \n        { {0x81}, {0x2}, true, SCRIPT_ERR_OK, {0x1, 0x80}},     \n        { {0x81}, {0x3}, true, SCRIPT_ERR_OK, {0x1, 0x0, 0x80}},\n\n        // -ve length\n        { {0x1}, {0x81}, false, SCRIPT_ERR_PUSH_SIZE, {0x1}},\n\n        // requested length to short\n        { {0x1}, {}, false, SCRIPT_ERR_IMPOSSIBLE_ENCODING, {0x1}},\n        { {0x1}, {0x0}, false, SCRIPT_ERR_IMPOSSIBLE_ENCODING, {0x1}},\n        { {0x1, 0x2}, {0x1}, false, SCRIPT_ERR_IMPOSSIBLE_ENCODING, { 0x1, 0x2}},\n\n    };\n    // clang-format on\n    for(auto& [arg1, arg2, exp_status, exp_error, op] : test_data)\n    {\n        LimitedStack stack(UINT32_MAX);\n        vector<uint8_t> args;\n\n        args.push_back(OP_PUSHDATA1);\n        args.push_back(arg1.size());\n        copy(begin(arg1), end(arg1), back_inserter(args));\n\n        args.push_back(OP_PUSHDATA1);\n        args.push_back(arg2.size());\n        copy(begin(arg2), end(arg2), back_inserter(args));\n\n        args.push_back(OP_NUM2BIN);\n\n        CScript script(args.begin(), args.end());\n\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n        ScriptError error;\n        const auto status = EvalScript(\n            config, false, task::CCancellationSource::Make()->GetToken(), stack,\n            script, flags, BaseSignatureChecker{}, &error);\n\n        BOOST_CHECK_EQUAL(exp_status, status.value());\n        BOOST_CHECK_EQUAL(exp_error, error);\n        BOOST_CHECK_EQUAL_COLLECTIONS(begin(stack.front()), end(stack.front()), begin(op),\n                                      end(op));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(op_depth)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    const vector<size_t> test_data = {0, 1, 20'000};\n    for(const auto i : test_data)\n    {\n        LimitedStack stack(UINT32_MAX);\n        vector<uint8_t> args(i, OP_0);\n\n        args.push_back(OP_DEPTH);\n\n        CScript script(args.begin(), args.end());\n\n        const auto cancellation_source{task::CCancellationSource::Make()};\n        const auto token{cancellation_source->GetToken()};\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS | SCRIPT_GENESIS};\n        ScriptError error;\n        const auto status = EvalScript(config, true, token, stack, script,\n                                       flags, BaseSignatureChecker{}, &error);\n\n        BOOST_CHECK_EQUAL(true, status.value());\n        BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, error);\n        BOOST_CHECK_EQUAL(i + 1, stack.size());\n        vector<uint8_t> op;\n        bsv::serialize<int>(i, back_inserter(op));\n        BOOST_CHECK_EQUAL_COLLECTIONS(begin(stack.at(i)), end(stack.at(i)), begin(op),\n                                      end(op));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(op_size)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    using polynomial = vector<int>;\n    using test_args = tuple<int64_t, polynomial>;\n    vector<test_args> test_data = {\n        {2, {1, 1}},\n        {max64, {1, 1} },\n    };\n\n    for(const auto [n, arg_poly] : test_data)\n    {\n        const bint bn{n};\n\n        vector<uint8_t> args;\n        args.push_back(OP_PUSHDATA1);\n\n        const bint arg = polynomial_value(begin(arg_poly), end(arg_poly), bn);\n        const auto arg_serialized{arg.serialize()};\n        args.push_back(arg_serialized.size());\n        copy(begin(arg_serialized), end(arg_serialized), back_inserter(args));\n\n        args.push_back(OP_SIZE);\n\n        CScript script(args.begin(), args.end());\n\n        const auto cancellation_source{task::CCancellationSource::Make()};\n        const auto token{cancellation_source->GetToken()};\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n        ScriptError error;\n        LimitedStack stack(UINT32_MAX);\n        const auto status = EvalScript(config, false, token, stack, script,\n                                       flags, BaseSignatureChecker{}, &error);\n\n        BOOST_CHECK_EQUAL(true, status.value());\n        BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, error);\n        BOOST_CHECK_EQUAL(2, stack.size());\n        const auto expected{stack.front().size()};\n        const auto actual{bsv::deserialize(begin(stack.at(1)), end(stack.at(1)))};\n        BOOST_CHECK_EQUAL(expected, actual);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(op_pick)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    using test_args = tuple<opcodetype, size_t>;\n    vector<test_args> test_data = {\n        {OP_0, 2},\n        {OP_1, 1},\n        {OP_2, 0},\n    };\n\n    for(const auto [op_code, i] : test_data)\n    {\n        vector<uint8_t> args;\n        args.push_back(OP_0);\n        args.push_back(OP_1);\n        args.push_back(OP_2);\n        args.push_back(op_code);\n        args.push_back(OP_PICK);\n\n        CScript script(args.begin(), args.end());\n\n        const auto cancellation_source{task::CCancellationSource::Make()};\n        const auto token{cancellation_source->GetToken()};\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n        ScriptError error;\n        LimitedStack stack(UINT32_MAX);\n        const auto status = EvalScript(config, false, token, stack, script,\n                                       flags, BaseSignatureChecker{}, &error);\n\n        BOOST_CHECK_EQUAL(true, status.value());\n        BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, error);\n        BOOST_CHECK_EQUAL(4, stack.size());\n        if(op_code == OP_2)\n            BOOST_CHECK(stack.at(3).empty());\n        else\n            BOOST_CHECK_EQUAL(stack.at(i).front(), stack.at(3).front());\n    }\n}\n\nBOOST_AUTO_TEST_CASE(op_roll)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    vector<opcodetype> test_data{\n        OP_0,\n        OP_1,\n        OP_2,\n    };\n\n    for(const auto op_code : test_data)\n    {\n        vector<uint8_t> args;\n        args.push_back(OP_0);\n        args.push_back(OP_1);\n        args.push_back(OP_2);\n        args.push_back(op_code);\n        args.push_back(OP_ROLL);\n\n        CScript script(args.begin(), args.end());\n\n        const auto cancellation_source{task::CCancellationSource::Make()};\n        const auto token{cancellation_source->GetToken()};\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n        ScriptError error;\n        LimitedStack stack(UINT32_MAX);\n        const auto status = EvalScript(config, false, token, stack, script,\n                                       flags, BaseSignatureChecker{}, &error);\n\n        BOOST_CHECK_EQUAL(true, status.value());\n        BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, error);\n        BOOST_CHECK_EQUAL(3, stack.size());\n\n        if(op_code == OP_0)\n        {\n            BOOST_CHECK_EQUAL(2, stack.at(2).front());\n            BOOST_CHECK_EQUAL(1, stack.at(1).front());\n            BOOST_CHECK(stack.at(0).empty());\n        }\n        else if(op_code == OP_1)\n        {\n            BOOST_CHECK_EQUAL(1, stack.at(2).front());\n            BOOST_CHECK_EQUAL(2, stack.at(1).front());\n            BOOST_CHECK(stack.at(0).empty());\n        }\n        else if(op_code == OP_2)\n        {\n            BOOST_CHECK(stack.at(2).empty());\n            BOOST_CHECK_EQUAL(2, stack.at(1).front());\n            BOOST_CHECK_EQUAL(1, stack.at(0).front());\n        }\n        else\n            BOOST_CHECK(false);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(op_split)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    using data = vector<uint8_t>;\n    using test_args = tuple<size_t, opcodetype, data, data>;\n    // clang-format off\n    vector<test_args> test_data = \n    {\n        {0, OP_0, {}, {0, 1}},\n        {1, {OP_1}, {0}, {1}},\n        {2, {OP_2}, {0, 1}, {}},\n    };\n    // clang-format on\n\n    for (const auto [i, pos, lhs, rhs] : test_data) {\n        vector<uint8_t> args;\n        args.push_back(0x2);\n        args.push_back(0x0);\n        args.push_back(0x1);\n        args.push_back(pos);\n\n        args.push_back(OP_SPLIT);\n\n        CScript script(args.begin(), args.end());\n\n        const auto cancellation_source{task::CCancellationSource::Make()};\n        const auto token{cancellation_source->GetToken()};\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n        ScriptError error;\n        LimitedStack stack(UINT32_MAX);\n        const auto status = EvalScript(config, false, token, stack, script,\n                                       flags, BaseSignatureChecker{}, &error);\n\n        BOOST_CHECK_EQUAL(true, status.value());\n        BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, error);\n        BOOST_CHECK_EQUAL(2, stack.size());\n        BOOST_CHECK_EQUAL(2 - i, stack.at(1).size());\n        BOOST_CHECK_EQUAL_COLLECTIONS(begin(stack.at(1)), end(stack.at(1)),\n                                      begin(rhs), end(rhs));\n        BOOST_CHECK_EQUAL(i, stack.front().size());\n        BOOST_CHECK_EQUAL_COLLECTIONS(begin(stack.front()), end(stack.front()),\n                                      begin(lhs), end(lhs));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(op_lshift)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    using test_args = tuple<opcodetype, vector<uint8_t>>;\n    // clang-format off\n    vector<test_args> test_data = \n    {\n        {OP_0, {0x0, 0x1}},\n        {OP_1, {0x0, 0x2}},\n        {OP_2, {0x0, 0x4}},\n        {OP_8, {0x1, 0x0}},\n        {OP_16, {0x0, 0x0}},\n    };\n    // clang-format on\n\n    for(const auto [pos, expected] : test_data)\n    {\n        vector<uint8_t> args;\n        args.push_back(0x2);\n        args.push_back(0x0);\n        args.push_back(0x1);\n        args.push_back(pos);\n\n        args.push_back(OP_LSHIFT);\n\n        CScript script(args.begin(), args.end());\n\n        const auto cancellation_source{task::CCancellationSource::Make()};\n        const auto token{cancellation_source->GetToken()};\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n        ScriptError error;\n        LimitedStack stack(UINT32_MAX);\n        const auto status = EvalScript(config, false, token, stack, script,\n                                       flags, BaseSignatureChecker{}, &error);\n\n        BOOST_CHECK_EQUAL(true, status.value());\n        BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, error);\n        BOOST_CHECK_EQUAL(1, stack.size());\n        BOOST_CHECK_EQUAL(2, stack.front().size());\n        BOOST_CHECK_EQUAL_COLLECTIONS(begin(stack.front()), end(stack.front()),\n                                      begin(expected), end(expected));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(op_rshift)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    using test_args = tuple<opcodetype, vector<uint8_t>>;\n    // clang-format off\n    vector<test_args> test_data = \n    {\n        {OP_0, {0x80, 0x0}},\n        {OP_1, {0x40, 0x0}},\n        {OP_2, {0x20, 0x0}},\n        {OP_8, {0x0, 0x80}},\n        {OP_16, {0x0, 0x0}},\n    };\n    // clang-format on\n\n    for(const auto [pos, expected] : test_data)\n    {\n        vector<uint8_t> args;\n        args.push_back(0x2);\n        args.push_back(0x80);\n        args.push_back(0x0);\n        args.push_back(pos);\n\n        args.push_back(OP_RSHIFT);\n\n        CScript script(args.begin(), args.end());\n\n        const auto cancellation_source{task::CCancellationSource::Make()};\n        const auto token{cancellation_source->GetToken()};\n        const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n        ScriptError error;\n        LimitedStack stack(UINT32_MAX);\n        const auto status = EvalScript(config, false, token, stack, script,\n                                       flags, BaseSignatureChecker{}, &error);\n\n        BOOST_CHECK_EQUAL(true, status.value());\n        BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, error);\n        BOOST_CHECK_EQUAL(1, stack.size());\n        BOOST_CHECK_EQUAL(2, stack.front().size());\n        BOOST_CHECK_EQUAL_COLLECTIONS(begin(stack.front()), end(stack.front()),\n                                      begin(expected), end(expected));\n    }\n}\n\nnamespace\n{\n    const vector<uint8_t> failure = {};\n    const vector<uint8_t> success = {1};\n\n    struct equality_checker : BaseSignatureChecker\n    {\n        bool CheckSig(const std::vector<uint8_t>& scriptsig,\n                      const std::vector<uint8_t>& pubkey,\n                      const CScript&,\n                      bool enabledSighashForkid) const override\n        {\n            return scriptsig == pubkey;\n        }\n\n        bool CheckLockTime(const CScriptNum&) const override { return true; }\n        bool CheckSequence(const CScriptNum&) const override { return true; }\n    };\n}\n\nBOOST_AUTO_TEST_CASE(op_checksig)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    using test_args =\n        tuple<opcodetype, opcodetype, bool, ScriptError, vector<uint8_t>>;\n    // clang-format off\n    vector<test_args> test_data = \n    {\n        // signature, pub_key, exp_status, exp_error, \n        {OP_1, OP_1, true, SCRIPT_ERR_OK, success },\n        {OP_1, OP_2, true, SCRIPT_ERR_OK, failure }\n    };\n    // clang-format on\n\n    for(const auto [signature, pub_key, exp_status, exp_error, exp_stack_top] :\n        test_data)\n    {\n        vector<uint8_t> args;\n\n        args.push_back(signature);\n        args.push_back(pub_key);\n        args.push_back(OP_CHECKSIG);\n\n        const CScript script(args.begin(), args.end());\n\n        uint32_t flags{};\n        ScriptError error;\n        LimitedStack stack(UINT32_MAX);\n        const equality_checker checker;\n        const auto status = EvalScript(\n            config, false, task::CCancellationSource::Make()->GetToken(), stack,\n            script, flags, checker, &error);\n\n        BOOST_CHECK_EQUAL(exp_status, status.value());\n        BOOST_CHECK_EQUAL(exp_error, error);\n        BOOST_CHECK_EQUAL(1, stack.size());\n        const auto stack_0{stack.at(0)};\n        BOOST_CHECK_EQUAL_COLLECTIONS(begin(stack_0), end(stack_0),\n                                      begin(exp_stack_top), end(exp_stack_top));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(op_checkmultisig)\n{\n    const Config& config = GlobalConfig::GetConfig();\n\n    using test_args = tuple<int, vector<opcodetype>, int, vector<opcodetype>,\n                            bool, ScriptError, vector<uint8_t>>;\n    // clang-format off\n    vector<test_args> test_data = \n    {\n        // n_signatures, signatures, \n        // n_public_keys, public_keys, \n        // exp_status, exp_error, top_stack_value \n\n        // Success True\n        {1, {OP_1}, 1, {OP_1}, true, SCRIPT_ERR_OK, success },\n        {1, {OP_1}, 2, {OP_1, OP_16}, true, SCRIPT_ERR_OK, success },\n        {1, {OP_1}, 2, {OP_16, OP_1}, true, SCRIPT_ERR_OK, success },\n\n        {2, {OP_1, OP_2}, 2, {OP_1, OP_2}, true, SCRIPT_ERR_OK, success },\n\n        {2, {OP_1, OP_2}, 3, {OP_16, OP_1, OP_2}, true, SCRIPT_ERR_OK, success},\n        {2, {OP_1, OP_2}, 3, {OP_1, OP_16, OP_2}, true, SCRIPT_ERR_OK, success},\n        {2, {OP_1, OP_2}, 3, {OP_1, OP_2, OP_16}, true, SCRIPT_ERR_OK, success},\n\n        {2, {OP_1, OP_2}, 4, {OP_16, OP_1, OP_16, OP_2}, true, SCRIPT_ERR_OK, success},\n\n        // Success false\n        {1, {OP_1}, 1, {OP_16}, true, SCRIPT_ERR_OK, failure},\n\n        {2, {OP_1, OP_2}, 2, {OP_1, OP_16}, true, SCRIPT_ERR_OK, failure},\n        {2, {OP_1, OP_2}, 2, {OP_16, OP_2}, true, SCRIPT_ERR_OK, failure},\n        {2, {OP_1, OP_2}, 2, {OP_2, OP_1}, true, SCRIPT_ERR_OK, failure},\n        \n        // Fails \n        {2, {OP_1, OP_2}, 1, {OP_1}, false, SCRIPT_ERR_SIG_COUNT, failure},\n        {-1, {OP_1}, 1, {OP_1}, false, SCRIPT_ERR_SIG_COUNT, failure},\n        {1, {OP_1}, -1, {OP_1}, false, SCRIPT_ERR_PUBKEY_COUNT, failure},\n    };\n    // clang-format on\n\n    for(const auto [n_sigs, signatures, n_pub_keys, public_keys, exp_status,\n                    exp_error, exp_stack_top] : test_data)\n    {\n        vector<uint8_t> args{OP_0}; // historic bug start with OP_0\n\n        reverse_copy(begin(signatures), end(signatures), back_inserter(args));\n        args.push_back(1);\n        args.push_back(n_sigs);\n\n        reverse_copy(begin(public_keys), end(public_keys), back_inserter(args));\n        args.push_back(1);\n        args.push_back(n_pub_keys);\n\n        args.push_back(OP_CHECKMULTISIG);\n\n        const CScript script(args.begin(), args.end());\n\n        uint32_t flags{};\n        ScriptError error;\n        LimitedStack stack(UINT32_MAX);\n        const equality_checker checker;\n        const auto status = EvalScript(\n            config, false, task::CCancellationSource::Make()->GetToken(), stack,\n            script, flags, checker, &error);\n\n        BOOST_CHECK_EQUAL(exp_status, status.value());\n        BOOST_CHECK_EQUAL(exp_error, error);\n        BOOST_CHECK_EQUAL(\n            exp_status ? 1 : signatures.size() + public_keys.size() + 3,\n            stack.size());\n        const auto stack_0{stack.at(0)};\n        BOOST_CHECK_EQUAL_COLLECTIONS(begin(stack_0), end(stack_0),\n                                      begin(exp_stack_top), end(exp_stack_top));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(op_rshift_far)\n{\n    constexpr vector<uint8_t>::size_type size{INT32_MAX / 8};\n    std::vector<uint8_t> data(size + 1l, 0x0);\n    data[0] = 0x80;\n\n    auto source = task::CCancellationSource::Make();\n    LimitedStack stack = LimitedStack({data}, INT64_MAX);\n    const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n    ScriptError err;\n    const auto r =\n        EvalScript(GlobalConfig::GetConfig(), true, source->GetToken(), stack,\n                   CScript() << (size * 8) + 7 << OP_RSHIFT, flags,\n                   BaseSignatureChecker{}, &err);\n    BOOST_CHECK(r.value());\n    BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, err);\n    const auto top = stack.front();\n    const auto values = top.GetElement();\n    const auto it{find_if(begin(values), end(values),\n                          [](const auto n) { return n != 0; })};\n    BOOST_CHECK_EQUAL(distance(begin(values), it), values.size() - 1);\n    BOOST_CHECK_EQUAL(1, values[values.size() - 1]);\n}\n\nBOOST_AUTO_TEST_CASE(op_lshift_far)\n{\n    constexpr vector<uint8_t>::size_type size{INT32_MAX / 8};\n    std::vector<uint8_t> data(size + 1l, 0x0);\n    data[size] = 0x1;\n\n    auto source = task::CCancellationSource::Make();\n    LimitedStack stack = LimitedStack({data}, INT64_MAX);\n    const auto flags{SCRIPT_UTXO_AFTER_GENESIS};\n    ScriptError err;\n    const auto r =\n        EvalScript(GlobalConfig::GetConfig(), true, source->GetToken(), stack,\n                   CScript() << (size * 8) + 7 << OP_LSHIFT, flags,\n                   BaseSignatureChecker{}, &err);\n    BOOST_CHECK(r.value());\n    BOOST_CHECK_EQUAL(SCRIPT_ERR_OK, err);\n    const auto top = stack.front();\n    const auto values = top.GetElement();\n    const auto it{find_if(begin(values), end(values),\n                          [](const auto n) { return n != 0; })};\n    BOOST_CHECK_EQUAL(distance(begin(values), it), 0);\n    BOOST_CHECK_EQUAL(0x80, values[0]);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "8492a9f835276d18c1cd9f0d53b715ef53204c4b", "size": 41584, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/bn_op_tests.cpp", "max_stars_repo_name": "bxlkm1/yulecoin", "max_stars_repo_head_hexsha": "3605faf2ff2e3c7bd381414613fc5c0234ad2936", "max_stars_repo_licenses": ["OML"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-08-02T02:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T15:51:48.000Z", "max_issues_repo_path": "src/test/bn_op_tests.cpp", "max_issues_repo_name": "bxlkm1/yulecoin", "max_issues_repo_head_hexsha": "3605faf2ff2e3c7bd381414613fc5c0234ad2936", "max_issues_repo_licenses": ["OML"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/bn_op_tests.cpp", "max_forks_repo_name": "bxlkm1/yulecoin", "max_forks_repo_head_hexsha": "3605faf2ff2e3c7bd381414613fc5c0234ad2936", "max_forks_repo_licenses": ["OML"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T02:50:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T03:21:38.000Z", "avg_line_length": 38.3616236162, "max_line_length": 100, "alphanum_fraction": 0.5937620239, "num_tokens": 12081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5592082774667901}}
{"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\u0301rez-Taboada, C.W. Oosterlee,\n        The Stochastic Collocation Monte Carlo Sampler: Highly efficient\n        sampling from \u201cexpensive\u201d 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": "#pragma once\n\n#include \"RRCoord.hpp\"\n#include \"utils/basic_maths.hpp\"\n#include \"utils/SPLDefs.hpp\"\n#include \"types/boostSerializationEigenTypes.hpp\"\n#include <Eigen/Eigen>\n\nstruct AbsCoord {\n   AbsCoord(float x, float y, float theta) : vec(x, y, theta) {\n      var.setZero();\n      var(0, 0) = SQUARE(FULL_FIELD_LENGTH);\n      var(1, 1) = SQUARE(FULL_FIELD_WIDTH);\n      var(2, 2) = SQUARE(M_PI);\n      weight = 1.0;\n   }\n\n   AbsCoord() : vec(0, 0, 0) {\n      var.setZero();\n      var(0, 0) = SQUARE(FULL_FIELD_LENGTH);\n      var(1, 1) = SQUARE(FULL_FIELD_WIDTH);\n      var(2, 2) = SQUARE(M_PI);\n      weight = 1.0;\n   }\n\n   Eigen::Vector3f vec;\n   Eigen::Matrix<float, 3, 3> var;\n   float weight;\n\n   const float x() const {\n      return vec[0];\n   }\n\n   float &x() {\n      return vec[0];\n   }\n\n   const float y() const {\n      return vec[1];\n   }\n\n   float &y() {\n      return vec[1];\n   }\n\n   const float theta() const {\n      return vec[2];\n   }\n\n   float &theta() {\n      return vec[2];\n   }\n\n   float getVar(int m, int n) const {\n      return var(m,n);\n   }\n   \n   bool operator== (const AbsCoord &other) const {\n      return vec == other.vec;\n   }\n\n   template<class Archive>\n   void serialize(Archive &ar, const unsigned int file_version) {\n      ar & vec;\n      ar & var;\n   }\n   \n   /**\n    * This assumes that the AbsCoord is already in robot relative coordinates, this will simply\n    * convert it to polar coords.\n    */\n   RRCoord convertToRobotRelative(void) const {\n      return RRCoord(sqrtf(vec.x()*vec.x() + vec.y()*vec.y()), atan2f(vec.y(), vec.x()), 0.0f);\n   }\n   \n   RRCoord convertToRobotRelative(const AbsCoord &robotPose) const {\n      float xdiff = x() - robotPose.x();\n      float ydiff = y() - robotPose.y();\n      float distance = sqrtf(xdiff*xdiff + ydiff*ydiff);\n      \n      float angle = atan2(ydiff, xdiff);\n      float rrHeading = normaliseTheta(angle - robotPose.theta());\n      \n      return RRCoord(distance, rrHeading, 0.0f);\n   }\n   \n   AbsCoord convertToRobotRelativeCartesian(const AbsCoord &robotPose) const {\n      RRCoord rrCoord = convertToRobotRelative(robotPose);\n      return AbsCoord(\n            rrCoord.distance() * cos(rrCoord.heading()), \n            rrCoord.distance() * sin(rrCoord.heading()),\n            0.0f);\n   }\n};\n", "meta": {"hexsha": "61a38960b825902d9fb49c4427ee9fd1cdba76d5", "size": 2278, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/External/unsw/unsw/types/AbsCoord.hpp", "max_stars_repo_name": "pedrohsreis/boulos", "max_stars_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T18:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T17:47:07.000Z", "max_issues_repo_path": "src/Core/External/unsw/unsw/types/AbsCoord.hpp", "max_issues_repo_name": "pedrohsreis/boulos", "max_issues_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-08T18:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-19T21:41:16.000Z", "max_forks_repo_path": "src/Core/External/unsw/unsw/types/AbsCoord.hpp", "max_forks_repo_name": "pedrohsreis/boulos", "max_forks_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-09-11T17:19:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-30T16:43:56.000Z", "avg_line_length": 23.9789473684, "max_line_length": 95, "alphanum_fraction": 0.5913081651, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5592082694588524}}
{"text": "/**\n * @file\n * @brief NPDE homework ResidualErrorEstimator Tests\n * @author Ralf Hiptmair\n * @date July 2021\n * @copyright Developed at SAM, ETH Zurich\n */\n\n#include \"../residualerrorestimator.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <iostream>\n\nnamespace REE::test {\n\nTEST(REE, TwoTriangleMesh) {\n  /* Macros available in the Google test framework:\n     EXPECT_EQ(x,y), EXPECT_NE(x,y), EXPECT_LT(x,y), EXPECT_LE(x,y),\n     EXPECT_GT(x,y), EXPECT_GE(x,y) EXPECT_STREQ(x,y), EXPECT_STRNE(x,y) -> for\n     C-strings only ! EXPECT_NEAR(x,y,abs_tol) All testing macros can output a\n     message by a trailing << ....\n   */\n  using size_type = lf::base::size_type;\n  using glb_idx_t = lf::assemble::glb_idx_t;\n  using coord_t = Eigen::Vector2d;\n\n  // Build a mesh with two triangles\n  // Create helper object: mesh factory\n  std::shared_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory_ptr =\n      std::make_shared<lf::mesh::hybrid2d::MeshFactory>(2);\n  // Generate nodes of the mesh\n  // clang-format off\n  std::array<std::array<double, 2>, 4> node_coord{\n  std::array<double, 2>({0 , 0 }),\n  std::array<double, 2>({0.5 , 0 }),\n  std::array<double, 2>({0.5 , 0.5 }),\n  std::array<double, 2>({0 , 0.5 })};\n  // clang-format on\n  // Add nodes to the mesh via the MeshFactory object\n  for (const auto& node : node_coord) {\n    mesh_factory_ptr->AddPoint(coord_t({node[0], node[1]}));\n  }\n  // Add plain triangles to the mesh, defined by their vertex nodes.\n  // Since no particular geometry is specified, the triangles are assumed to\n  // have straght edges.\n  mesh_factory_ptr->AddEntity(lf::base::RefEl::kTria(),\n                              std::vector<size_type>({0, 1, 2}),\n                              std::unique_ptr<lf::geometry::Geometry>(nullptr));\n  mesh_factory_ptr->AddEntity(lf::base::RefEl::kTria(),\n                              std::vector<size_type>({0, 2, 3}),\n                              std::unique_ptr<lf::geometry::Geometry>(nullptr));\n  // Get a pointer to the coarsest mesh\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = mesh_factory_ptr->Build();\n\n  // Print information about the coarsest mesh\n  std::cout << \"\\t Coarsest mesh for demonstration run\\n\";\n  lf::mesh::utils::PrintInfo(std::cout, *mesh_p, 100);\n\n  std::function<double(Eigen::Vector2d)> alpha =\n      [](Eigen::Vector2d x) -> double {\n    return ((x[0] - x[1]) > 0) ? 1.0 / 3.0 : 1.0 / 7.0;\n  };\n\n  auto f = [](Eigen::Vector2d x) -> double { return (1.0); };\n\n  // Defining the discretized boundary value problem including the\n  // finite-element space\n  const dataDiscreteBVP disc_bvp(mesh_p, alpha, f);\n\n  // Fix a finite element function for testing\n  Eigen::VectorXd mu(4);\n  mu(0) = 1;\n  mu(1) = 0;\n  mu(2) = 1;\n  mu(3) = 0;\n\n  // Compute edge contributions\n  lf::mesh::utils::CodimMeshDataSet<double> ed_res{edgeResiduals(disc_bvp, mu)};\n\n  // Values of the jump residual for the five edges of the mesh\n  std::array<double, 5> vals({0.0, 2.721088435374150, 0.0, 0.0, 0.0});\n  for (const lf::mesh::Entity* edge : mesh_p->Entities(1)) {\n    EXPECT_NEAR(ed_res(*edge), vals[mesh_p->Index(*edge)], 1.0E-6);\n  }\n}\n\nTEST(REE, ZeroEdgeResioduals) {\n  // Obtain test mesh\n  std::shared_ptr<lf::mesh::Mesh> mesh_p =\n      lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n  // Defining the discretized boundary value problem including the\n  // finite-element space\n  std::function<double(Eigen::Vector2d)> alpha =\n      [](Eigen::Vector2d x) -> double { return 1.0; };\n  auto f = [](Eigen::Vector2d) -> double { return 1.0; };\n  const dataDiscreteBVP disc_bvp(mesh_p, alpha, f);\n  // A simple linear function\n  auto lin_fun = [](Eigen::Vector2d x) -> double {\n    return 2.0 * x[0] + x[1] + 1.0;\n  };\n  // Sample nodal values\n  lf::mesh::utils::MeshFunctionGlobal mf_lin(lin_fun);\n  Eigen::VectorXd mu =\n      lf::fe::NodalProjection(*disc_bvp.pwlinfespace_p_, mf_lin);\n  // Compute edge contributions\n  lf::mesh::utils::CodimMeshDataSet<double> ed_res{edgeResiduals(disc_bvp, mu)};\n  // All edge residual should vanish\n  for (const lf::mesh::Entity* edge : mesh_p->Entities(1)) {\n    EXPECT_NEAR(ed_res(*edge), 0.0, 1.0E-6);\n  }\n}\n\n}  // namespace REE::test\n", "meta": {"hexsha": "3fc34c8529ab6a94b805cd72322253509a74223e", "size": 4162, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ResidualErrorEstimator/templates/test/residualerrorestimator_test.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T10:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T10:59:19.000Z", "max_issues_repo_path": "homeworks/ResidualErrorEstimator/templates/test/residualerrorestimator_test.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/ResidualErrorEstimator/templates/test/residualerrorestimator_test.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": 35.8793103448, "max_line_length": 80, "alphanum_fraction": 0.6482460356, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5590502998680714}}
{"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 <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n  Eigen::ArrayXf v(6);\n  v << 1, 2, 3, 4, 5, 6;\n  cout << \"v.head(3) =\" << endl << v.head(3) << endl << endl;\n  cout << \"v.tail<3>() = \" << endl << v.tail<3>() << endl << endl;\n  v.segment(1,4) *= 2;\n  cout << \"after 'v.segment(1,4) *= 2', v =\" << endl << v << endl;\n}\n", "meta": {"hexsha": "4a0b02342435c4c71094b42cb5e90907d311c483", "size": 348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_BlockOperations_vector.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_BlockOperations_vector.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_BlockOperations_vector.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 23.2, "max_line_length": 66, "alphanum_fraction": 0.5, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.5590502877207044}}
{"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": "#ifndef ROTATION_HPP\n#define ROTATION_HPP\n\n/**\n\t@file rotation.hpp\n\tUtilities for reference frame rotations\n\n\t@brief Common tools for expressing and converting rotations.\n*/\n\n#include <Eigen/Dense>\n\nnamespace Rot {\n\nvoid R_to_euler(const Eigen::Matrix3d& R, Eigen::Vector3d& e);\n\nvoid euler_to_R(const Eigen::Vector3d& e, Eigen::Matrix3d& R);\n\nvoid quat_to_R(const Eigen::Vector4d& q, Eigen::Matrix3d& R);\n\nvoid quat_to_euler(const Eigen::Vector4d& q, Eigen::Vector3d& e);\n\nvoid euler_to_quat(const Eigen::Vector3d& e, Eigen::Vector4d& q);\n\nvoid axis_to_quat(const Eigen::Vector3d& aa, Eigen::Vector4d& q);\n\nvoid quat_to_axis(const Eigen::Vector4d& q, Eigen::Vector3d& aa);\n\nvoid compose_quats(const Eigen::Vector4d& p, const Eigen::Vector4d q, Eigen::Vector4d& o);\n\nvoid invert_quat(Eigen::Vector4d& q);\n\ndouble rad_to_deg(double th);\n\ndouble deg_to_rad(double th);\n\ndouble wrap_to_2pi(double th);\n\ndouble wrap_to_pi(double th);\n}\n\n#endif // ROTATION_HPP\n", "meta": {"hexsha": "da315550fc8774fc287c8c66f7cb62d75ef54d58", "size": 956, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/utils/rotation.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/utils/rotation.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/utils/rotation.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": 22.2325581395, "max_line_length": 90, "alphanum_fraction": 0.7510460251, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581194449494, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5589737393651542}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <boost/simd/algorithm.hpp>\n#include <boost/simd/function/load.hpp>\n#include <boost/simd/memory/allocator.hpp>\n#include <boost/simd/pack.hpp>\n\nint main()\n{\n  int size = 16;\n  std::vector<float, boost::simd::allocator<float>> data0(size);\n  std::vector<float, boost::simd::allocator<float>> data1(size);\n  std::vector<float, boost::simd::allocator<float>> res(size);\n\n  for (int i = 0; i < size; ++i) {\n    data0[i] = i;\n    data1[i] = i * 2;\n  }\n\n  //! [scalar-loop]\n  for (int i = 0; i < size; ++i) {\n    res[i] = data0[i] + data1[i];\n  }\n  //! [scalar-loop]\n\n  //! [sse2-simd-loop]\n  std::size_t card_sse = 4;\n  for (int i = 0; i < size; i += card_sse) {\n    __m128 v0_sse = _mm_load_ps(&data0[i]);\n    __m128 v1_sse = _mm_load_ps(&data1[i]);\n    __m128 r_sse  = _mm_add_ps(v0_sse, v1_sse);\n\n    _mm_store_ps(&res[i], r_sse);\n  }\n  //! [sse2-simd-loop]\n\n  //! [avx-simd-loop]\n  std::size_t card_avx = 8;\n  for (int i = 0; i < size; i += card_avx) {\n    __m256 v0_avx = _mm256_load_ps(&data0[i]);\n    __m256 v1_avx = _mm256_load_ps(&data1[i]);\n    __m256 r_avx  = _mm256_add_ps(v0_avx, v1_avx);\n\n    _mm256_store_ps(&res[i], r_avx);\n  }\n  //! [avx-simd-loop]\n\n  //! [vmx-simd-loop]\n  std::size_t card_vmx = 4;\n  for (int i = 0; i < size; i += card_vmx) {\n    vector float v0_ibm = vec_ld(i, &data0[0]);\n    vector float v1_ibm = vec_ld(i, &data1[0]);\n    vector float r_ibm  = vec_add(v0_ibm, v1_ibm);\n\n    vec_st(r_ibm, i, &res[0]);\n  }\n  //! [vmx-simd-loop]\n\n  //! [bs-simd-loop]\n  for (int i = 0; i < size; i += boost::simd::pack<float>::static_size) {\n    boost::simd::pack<float> v0(&data0[i]), v1(&data1[i]);\n    bs::aligned_store(v0 + v1, &res[i]);\n  }\n  //! [bs-simd-loop]\n\n  //! [bs-simd-transform]\n  boost::simd::transform(&data[0], &data[0] + size, &data1[0], &res[0], boost::simd::plus);\n//! [bs-simd-transform]\n\n#if __cplusplus >= 201402L\n  //! [bs-simd-transform-14]\n  boost::simd::transform(&data[0], &data[0] + size, &data1[0], &res[0],\n                         [](auto const& a, auto const& b) { return a + b; });\n//! [bs-simd-transform-14]\n#endif\n\n  return 0;\n}\n", "meta": {"hexsha": "66d428e3f78fe8499a75f453af8f30a795c9f687", "size": 2128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/addvector.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "doc/examples/addvector.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/examples/addvector.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 26.6, "max_line_length": 91, "alphanum_fraction": 0.5878759398, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5589737307043278}}
{"text": "#include <Eigen/Core>\n#include <catch2/catch.hpp>\n#include \"ear/common/helpers/eigen_helpers.hpp\"\n\nusing namespace ear;\n\nTEST_CASE(\"interp\") {\n  // x lower than xp(0)\n  REQUIRE(interp(-1.0, Eigen::Vector3d{0.0, 1.0, 5.0},\n                 Eigen::Vector3d{0.0, 1.0, 3.0}) == 0.0);\n  // x equal to xp(0)\n  REQUIRE(interp(0.0, Eigen::Vector3d{0.0, 1.0, 5.0},\n                 Eigen::Vector3d{0.0, 1.0, 3.0}) == 0.0);\n  // x between xp(0) and xp(-1)\n  REQUIRE(interp(0.5, Eigen::Vector3d{0.0, 1.0, 5.0},\n                 Eigen::Vector3d{0.0, 1.0, 3.0}) == 0.5);\n  // x equal to xp(-1)\n  REQUIRE(interp(5.0, Eigen::Vector3d{0.0, 1.0, 5.0},\n                 Eigen::Vector3d{0.0, 1.0, 3.0}) == 3.0);\n  // x higher than xp(-1)\n  REQUIRE(interp(10.0, Eigen::Vector3d{0.0, 1.0, 5.0},\n                 Eigen::Vector3d{0.0, 1.0, 3.0}) == 3.0);\n}\n\nTEST_CASE(\"copy_vector\") {\n  std::vector<bool> b{false, true, false};\n  auto b_eigen_exp = Eigen::Array<bool, 3, 1>{false, true, false};\n\n  auto b_eigen = copy_vector<Eigen::Array<bool, Eigen::Dynamic, 1>>(b);\n  auto b_eigen_sz = copy_vector<Eigen::Array<bool, 3, 1>>(b);\n\n  REQUIRE((b_eigen == b_eigen_exp).all());\n  REQUIRE((b_eigen_sz == b_eigen_exp).all());\n}\n\nTEST_CASE(\"mask_write\") {\n  Eigen::Vector3d out = Eigen::Vector3d::Zero();\n  std::vector<bool> mask{false, true, true};\n  Eigen::Vector2d values(2.0, 5.0);\n  Eigen::Vector3d expected(0.0, 2.0, 5.0);\n\n  mask_write(out, mask, values);\n\n  REQUIRE(out == expected);\n}\n", "meta": {"hexsha": "b76ffe6689b06142926d2e8b449383ce519141be", "size": 1464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/eigen_helpers_tests.cpp", "max_stars_repo_name": "valnoel/libear", "max_stars_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/eigen_helpers_tests.cpp", "max_issues_repo_name": "valnoel/libear", "max_issues_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/eigen_helpers_tests.cpp", "max_forks_repo_name": "valnoel/libear", "max_forks_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8260869565, "max_line_length": 71, "alphanum_fraction": 0.5922131148, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5589737307043278}}
{"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 \u00edn 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 \u7231\u5b66\u4e60\u7684\u5154\u5b50 on 2020/4/14.\n//  Copyright \u00a9 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// \u57fa\u7840\u5b9a\u4e49\ntypedef model::d2::point_xy<double> Point;\ntypedef model::polygon<Point> Polygon;\ntypedef model::linestring<Point> LineString;\n\n\n// \u5c01\u88c5\u83b7\u5f97\u5168\u90e8\u70b9\u7684\u51fd\u6570\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//\u4e3b\u8981\u5305\u542b\u6ce8\u518c\u591a\u8fb9\u5f62\u3001\u8f6c\u5316\u591a\u8fb9\u5f62\nclass GeometryProcess{\npublic:\n    /*\n     \u6570\u7ec4\u8f6c\u5316\u4e3a\u591a\u8fb9\u5f62\n     */\n    static void convertPoly(vector<vector<double>> poly, Polygon &Poly){\n        // \u7a7a\u96c6\u7684\u60c5\u51b5\n        if(poly.size()==0){\n            read_wkt(\"POLYGON(())\", Poly);\n            return;\n        }\n        // \u9996\u5148\u5168\u90e8\u8f6c\u5316\u4e3awkt\u683c\u5f0f\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        // \u7136\u540e\u8bfb\u53d6\u5230Poly\u4e2d\n        read_wkt(wkt_poly, Poly);\n    };\n    /*\n     \u901a\u8fc7for each point\u904d\u5386\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    // \u83b7\u5f97vector<list<VectorPoints>>\u7684\u591a\u8fb9\u5f62\uff08\u5e76\u975e\u5168\u90e8\u70b9\uff09\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    // \u83b7\u5f97\u67d0\u4e2a\u96c6\u5408\u5bf9\u8c61\u7684\u5168\u90e8\u70b9\n    static void getGemotryPoints(Polygon poly,VectorPoints &temp_points){\n        for_each_point(poly, AllPoint<Point>(&temp_points));\n    };\n};\n\n// \u5305\u542b\u5904\u7406\u51fd\u6570\nclass PackingAssistant{\npublic:\n    /*\n     \u83b7\u5f97Inner Fit Rectangle\n     */\n    static void getIFR(VectorPoints polygon,double container_width,double container_length,VectorPoints &IFR){\n        // \u521d\u59cb\u53c2\u6570\uff0c\u83b7\u5f97\u591a\u8fb9\u5f62\u7279\u5f81\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\u5177\u4f53\u8ba1\u7b97\uff08\u4ece\u5de6\u4e0a\u89d2\u987a\u65f6\u9488\u8ba1\u7b97\uff09\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     \u79fb\u52a8\u67d0\u4e2a\u591a\u8fb9\u5f62\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     \u79fb\u52a8\u591a\u8fb9\u5f62\u5230\u67d0\u4e2a\u4f4d\u7f6e\uff08\u53c2\u8003\u70b9\uff09\n     */\n    static void slideToPosition(VectorPoints &polygon,vector<double> target_pt){\n        vector<double> refer_pt;\n        getReferPt(polygon,refer_pt);\n        cout<<\"\u591a\u8fb9\u5f62\";\n        PrintAssistant::print2DVector(polygon,true);\n        cout<<\"\u53c2\u8003\u70b9:\"<<refer_pt[0]<<\",\"<<refer_pt[1]<<endl;\n        cout<<\"\u76ee\u6807\u70b9:\"<<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     \u83b7\u5f97\u591a\u8fb9\u5f62\u7684\u6240\u6709\u7684\u8fb9\u754c\u60c5\u51b5min_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     \u904d\u5386\u83b7\u5f97\u4e00\u4e2a\u591a\u8fb9\u5f62\u7684\u6700\u5de6\u4fa7\u70b9\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     \u4ec5\u4ec5\u83b7\u5f97\u6700\u53f3\u4fa7\u70b9\uff0c\u540c\u6837\u4e3a\u9006\u65f6\u9488\u5904\u7406\uff08\u7528\u4e8e\u5224\u65ad\u662f\u9017\u8d85\u51fa\u754c\u9650\uff09\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     \u4ec5\u4ec5\u83b7\u5f97\u53c2\u8003\u70b9\uff0c\u662f\u7b2c\u4e00\u4e2aTop\u4f4d\u7f6e\uff0c\u9700\u8981\u9006\u65f6\u9488\u5904\u7406\uff08NFP\u4e3a\u9006\u65f6\u9488\uff09\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     \u4ec5\u4ec5\u83b7\u5f97\u5e95\u90e8\u4f4d\u7f6e\uff08\u7528\u4e8eNFP\u8ba1\u7b97\uff09\uff0c\u662f\u7b2c\u4e00\u4e2aBottom\u4f4d\u7f6e\uff0c\u9700\u8981\u9006\u65f6\u9488\u5904\u7406\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     \u83b7\u5f97\u591a\u8fb9\u5f62\u7684\u8fb9\u754c\u56db\u4e2a\u70b9\uff0cborder_points\u6709left bottom right top\u56db\u4e2a\u70b9\n     \u6682\u65f6\u4e0d\u8003\u8651\u53c2\u8003\u70b9\uff0c\u53c2\u8003\u70b9\u7edf\u4e00\u9006\u65f6\u9488\u65cb\u8f6c\u7b2c\u4e00\u4e2a\u6700\u4e0a\u65b9\u7684\u70b9\n     */\n    static void getBorder(VectorPoints polygon,VectorPoints &border_points){\n        // \u589e\u52a0\u8fb9\u754c\u7684\u51e0\u4e2a\u70b9\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        // \u904d\u5386\u6240\u6709\u7684\u70b9\uff0c\u5206\u522b\u5224\u65ad\u662f\u5426\u8d85\u51fa\u754c\u9650\n        int poly_size=(int)polygon.size();\n        for(int i=poly_size-1;i>=0;i--){\n            // \u5de6\u4fa7\u70b9\u5224\u65ad\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            // \u4e0b\u4fa7\u70b9\u5224\u65ad\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            // \u53f3\u4fa7\u70b9\u5224\u65ad\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            // \u4e0a\u4fa7\u70b9\u5224\u65ad\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    // \u5224\u65ad\u4e24\u4e2a\u591a\u8fb9\u5f62\u662f\u5426\u91cd\u53e0\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    // \u83b7\u5f97\u4e24\u4e2a\u591a\u8fb9\u5f62\u7684\u91cd\u53e0\u60c5\u51b5\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        // \u83b7\u5f97\u91cd\u53e0\u60c5\u51b5\n        deque<Polygon> output;\n        intersection(Poly1, Poly2, output);\n        \n        // \u904d\u5386\u8ba1\u7b97\u91cd\u53e0\u9762\u79ef\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    // \u83b7\u5f97List\u5bf9\u8c61\u7684\u5168\u90e8\u91cd\u53e0\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    // \u83b7\u5f97\u5f53\u524d\u6392\u6837\u7684\u5bbd\u5ea6\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// \u83b7\u5f97NFP\nclass NFPAssistant{\nprotected:\n    csv::Reader nfp_result;\n    int poly_num;\n    int orientation_num;\n    vector<VectorPoints> NPFs; // \u5b58\u50a8\u5168\u90e8\u7684NFP\uff0c\u6309\u884c\u5b58\u50a8\npublic:\n    /*\n     \u9884\u52a0\u8f7d\u5168\u90e8\u7684NFP\uff0c\u76f4\u63a5\u8f6c\u5316\u5230NFP\u4e2d\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<<\"\u52a0\u8f7d\u5168\u90e8NFP\"<<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     \u8bfb\u53d6NFP\u7684\u786e\u5b9a\u884c\u6570\uff0ci\u4e3a\u56fa\u5b9a\u5f62\u72b6\uff0cj\u4e3a\u975e\u56fa\u5b9a\u5f62\u72b6,oi/oj\u4e3a\u5f62\u72b6\n     */\n    void getNFP(int i,int j, int oi, int oj, VectorPoints poly_j ,VectorPoints &nfp){\n        // \u83b7\u5f97\u539f\u59cb\u7684NFP\n        int row_num= i*192+j*16+oi*4+oj;\n        nfp=NPFs[row_num];\n        // \u5c06NFP\u79fb\u5230\u76ee\u6807\u4f4d\u7f6e\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// \u5904\u7406\u591a\u4e2a\u591a\u8fb9\u5f62\u7684\u5173\u7cfb\nclass PolygonsOperator{\npublic:\n    // \u8ba1\u7b97\u591a\u8fb9\u5f62\u7684\u5dee\u96c6\u5408\n    static void polysDifference(list<Polygon> &feasible_region, Polygon sub_region){\n        // \u9010\u4e00\u904d\u5386\u6c42\u89e3\u91cd\u53e0\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        // \u5c06\u65b0\u7684Output\u5168\u90e8\u8f93\u5165\u8fdb\u53bb\n        feasible_region.clear();\n        copy(new_feasible_region.begin(), new_feasible_region.end(), back_inserter(feasible_region));\n    }\n    // \u9010\u4e00\u904d\u5386\u6c42\u5dee\u96c6\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\u548c\u4e00\u4e2aPoly\u7684\u5dee\u96c6\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\u548cList\u4e4b\u95f4\u7684\u4ea4\u96c6\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    // \u5224\u65ad\u67d0\u4e2aList\u662f\u5426\u4e3a\u7a7a\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    // \u8ba1\u7b97\u591a\u8fb9\u5f62\u7684\u4ea4\u96c6\n    void polysUnion(){\n        // \u6d4b\u8bd5\u57fa\u7840\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\u6570\u7ec4\u7684\u589e\u957f\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     \u5c06\u4e0d\u53ef\u884c\u8f6c\u5316\u4e3a\u53ef\u884c\n     */\n    static void convertToFeasible(Polygon new_item,Polygon item){\n        // \u786e\u8ba4\u6240\u6709\u7684\u70b9\n        VectorPoints all_points;\n        VectorPoints new_all_points;\n        GeometryProcess::getGemotryPoints(item,all_points);\n        // \u5224\u65ad\u70b9\u662f\u5426\u91cd\u53e0\u4e86\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            // \u9996\u5148\u5224\u65ad\u5782\u76f4\u60c5\u51b5\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                // \u5224\u65ad\u975e\u5782\u76f4\u60c5\u51b5\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 * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearfeelementmatrix.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix<double, 4, 4> MyLinearFEElementMatrix::Eval(\n    const lf::mesh::Entity &cell) {\n  // Topological type of the cell\n  const lf::base::RefEl ref_el{cell.RefEl()};\n\n  // Obtain the vertex coordinates of the cell, which completely\n  // describe its shape.\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n  // Matrix storing corner coordinates in its columns\n  auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n  // Matrix for returning element matrix\n  Eigen::Matrix<double, 4, 4> elem_mat;\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return elem_mat;\n}\n/* SAM_LISTING_END_1 */\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "9d5b285c8937240dfec94d7de5e7e20a2c63b889", "size": 1107, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/templates/mylinearfeelementmatrix.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ElementMatrixComputation/templates/mylinearfeelementmatrix.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ElementMatrixComputation/templates/mylinearfeelementmatrix.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 26.3571428571, "max_line_length": 64, "alphanum_fraction": 0.6937669377, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872019117029, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.5589231705266209}}
{"text": "\n// BLAS level 2\n// benchmarks \n\n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n//#define USE_STD_VECTOR\n//#define BOUNDED 100*100\n\n//#define PRINT\n//#define PRINT_M\n\n//#define MODIFY\n\n#include <stddef.h>\n#include <iostream>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/symmetric.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#ifdef USE_STD_VECTOR\n#include <vector>\n#include <boost/numeric/bindings/std/vector.hpp> \n#endif \n#include <boost/timer.hpp>\n#include \"utils.h\" \n\nnamespace ublas = boost::numeric::ublas;\nnamespace blas = boost::numeric::bindings::blas;\n\nusing std::cout;\nusing std::cin;\nusing std::endl; \n\ntypedef double real_t; \n\n#ifdef USE_STD_VECTOR\ntypedef std::vector<real_t> storage_t; \n#else\n#ifndef BOUNDED \ntypedef ublas::unbounded_array<real_t> storage_t; \n#else\ntypedef ublas::bounded_array<real_t, BOUNDED> storage_t; \n#endif \n#endif \n\ntypedef ublas::vector<real_t, storage_t> vct_t;\n\ntypedef ublas::matrix<real_t, ublas::column_major, storage_t> cm_t;\ntypedef ublas::matrix<real_t, ublas::row_major, storage_t> rm_t;\n\ntypedef ublas::symmetric_adaptor<cm_t, ublas::upper> ucsa_t; \ntypedef ublas::symmetric_adaptor<cm_t, ublas::lower> lcsa_t; \ntypedef ublas::symmetric_adaptor<rm_t, ublas::upper> ursa_t; \ntypedef ublas::symmetric_adaptor<rm_t, ublas::lower> lrsa_t; \n\ntypedef ublas::symmetric_matrix<\n  real_t, ublas::upper, ublas::column_major\n> ucsymm_t; \ntypedef ublas::symmetric_matrix<\n  real_t, ublas::lower, ublas::column_major\n> lcsymm_t; \ntypedef ublas::symmetric_matrix<\n  real_t, ublas::upper, ublas::row_major\n> ursymm_t; \ntypedef ublas::symmetric_matrix<\n  real_t, ublas::lower, ublas::row_major\n> lrsymm_t; \n\n////////////////////////////////////////////////////\n// general matrix: gemv()\n\ntemplate <typename M>\nvoid bench_gemv (size_t n, size_t runs, const char* msg) {\n\n  cout << msg << endl; \n\n  vct_t x (n);\n  blas::set (1., x);\n  vct_t y (n); \n\n  M a (n, n);\n  init_symm (a); \n#ifdef PRINT_M\n  print_m (a, \"a\");\n  cout << endl; \n#endif \n\n  boost::timer (t); \n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    a (0, 2) = r; \n    a (2, 0) = r; \n#endif \n    blas::gemv ( 1.0, a, x, 0.0, y);\n#ifdef PRINT\n    std::cout << \"y \" << bindings::noop( y ) << std::endl;\n#endif\n  } \n  cout << \"  gemv:        \" << t.elapsed() << endl;  \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    a (0, 2) = r; \n    a (2, 0) = r; \n#endif \n    blas::gemv ( 1., bindings::trans(a), x, 0., y );\n#ifdef PRINT\n    std::cout << \"y \" << bindings::noop( y ) << std::endl;\n#endif\n  } \n  cout << \"  gemv trans:  \" << t.elapsed() << endl;  \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    a (0, 2) = r; \n    a (2, 0) = r; \n#endif \n    y = prod (a, x);\n#ifdef PRINT\n    std::cout << \"y \" << bindings::noop( y ) << std::endl;\n#endif \n  }\n  cout << \"  = prod:      \" << t.elapsed() << endl; \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    a (0, 2) = r; \n    a (2, 0) = r; \n#endif \n    y.assign (prod (a, x));\n#ifdef PRINT\n    std::cout << \"y \" << bindings::noop( y ) << std::endl;\n#endif\n  } \n  cout << \"  assign prod: \" << t.elapsed() << endl; \n  cout << endl; \n}\n\n\n/////////////////////////////////////////////////////////\n// symmetric adaptor: symv()\n\ntemplate <typename M, typename SA>\nvoid bench_symv (size_t n, size_t runs, const char* msg) {\n\n  cout << msg << endl; \n\n  vct_t x (n);\n  blas::set (1., x);\n  vct_t y (n); \n\n  M a (n, n);\n  SA sa (a); \n  init_symm (sa, 'l'); \n#ifdef PRINT_M\n  print_m (sa, \"sa\"); \n  cout << endl; \n  print_m (a, \"a\"); \n  cout << endl; \n#endif \n\n  boost::timer (t); \n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    sa (0, 2) = r; \n#endif \n    blas::symv ( 1., sa, x, 0., y);\n#ifdef PRINT\n    std::cout << \"y \" << bindings::noop( y ) << std::endl;\n#endif\n  } \n  cout << \"  symv:        \" << t.elapsed() << endl;  \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    sa (0, 2) = r; \n#endif \n    y = prod (sa, x);\n#ifdef PRINT\n    std::cout << \"y \" << bindings::noop( y ) << std::endl;\n#endif \n  }\n  cout << \"  = prod:      \" << t.elapsed() << endl; \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    sa (0, 2) = r; \n#endif \n    y.assign (prod (sa, x));\n#ifdef PRINT\n    std::cout << \"y \" << bindings::noop( y ) << std::endl;\n#endif\n  } \n  cout << \"  assign prod: \" << t.elapsed() << endl; \n  cout << endl; \n}\n\n\n/////////////////////////////////////////////////////////\n// symmetric matrix: spmv()\n\ntemplate <typename SM>\nvoid bench_spmv (size_t n, size_t runs, const char* msg) {\n\n  cout << msg << endl; \n\n  vct_t x (n);\n  blas::set (1., x);\n  vct_t y (n); \n\n  SM sa (n, n);\n  init_symm (sa, 'l'); \n#ifdef PRINT_M\n  cout << sa << endl;\n  cout << endl; \n#endif \n\n  boost::timer (t); \n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    sa (0, 2) = r; \n#endif \n    blas::spmv ( 1.0, sa, x, 0.0, y);\n#ifdef PRINT\n    std::cout << \"y \" << bindings::noop( y ) << std::endl;\n#endif\n  } \n  cout << \"  spmv:        \" << t.elapsed() << endl;  \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    sa (0, 2) = r; \n#endif \n    y = prod (sa, x);\n#ifdef PRINT\n    std::cout << \"y \" << bindings::noop( y ) << std::endl;\n#endif \n  }\n  cout << \"  = prod:      \" << t.elapsed() << endl; \n\n  t.restart(); \n  for (size_t r = 0; r < runs; ++r) {\n#ifdef MODIFY\n    sa (0, 2) = r; \n#endif \n    y.assign (prod (sa, x));\n#ifdef PRINT\n    std::cout << \"y \" << bindings::noop( y ) << std::endl;\n#endif\n  } \n  cout << \"  assign prod: \" << t.elapsed() << endl; \n  cout << endl; \n}\n\n\n//////////////////////////////////////////////////////\nint main (int argc, char **argv) {\n  size_t n = 0, r = 0;\n  if (argc > 1) {\n    n = atoi(argv [1]);\n  }\n  if (argc > 2) {\n    r = atoi(argv [2]);\n  }\n\n  cout << endl; \n\n  if (n <= 0) {\n    cout << \"n -> \";\n    cin >> n;\n  }\n  if (r <= 0) {\n    cout << \"r -> \";\n    cin >> r;\n  }\n  cout << endl; \n\n  bench_gemv<rm_t> (n, r, \"row major\"); \n  bench_gemv<cm_t> (n, r, \"column major\"); \n\n  bench_symv<rm_t, ursa_t> (n, r, \"symmetric ad, row, upper\"); \n  bench_symv<rm_t, lrsa_t> (n, r, \"symmetric ad, row, lower\"); \n  bench_symv<cm_t, ucsa_t> (n, r, \"symmetric ad, column, upper\"); \n  bench_symv<cm_t, lcsa_t> (n, r, \"symmetric ad, column, lower\"); \n\n  bench_spmv<ursymm_t> (n, r, \"symmetric, row, upper\"); \n  bench_spmv<lrsymm_t> (n, r, \"symmetric, row, lower\"); \n  bench_spmv<ucsymm_t> (n, r, \"symmetric, column, upper\"); \n  bench_spmv<lcsymm_t> (n, r, \"symmetric, column, lower\"); \n\n}\n", "meta": {"hexsha": "2958e0fc019c3f1166959977885af25abbd87a0a", "size": 6772, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_matr2_bench.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_matr2_bench.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_matr2_bench.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": 22.2032786885, "max_line_length": 67, "alphanum_fraction": 0.5565564087, "num_tokens": 2359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5588716908757004}}
{"text": "/* -*- mode: c++; coding: utf-8-unix; -*- \n * graph-test.cc\n * Created by Satoshi Yukawa on 26 July 2017.\n * Copyright 2017 Satoshi Yukawa. All rights reserved. \n */\n\n\n#include <iostream>\n/*\n  boost library\u3092\u3064\u304b\u3046\n   http://www.boost.org/ \u306eboost library\u304c\u5fc5\u8981\n */\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n\nint main(int argc, char* argv[]){\n  // \u5ba3\u8a00\n  //typedef boost::adjacency_list<boost::vecS,boost::listS,boost::undirectedS> Graph;\n  typedef boost::adjacency_list<boost::vecS,boost::vecS,boost::undirectedS> Graph;\n  Graph G;\n  int num=6;\n  int component[num];\n\n\n  // \u521d\u671f\u5316\n  for(int i=0;i<num;i++){\n    component[i] = 0;\n  }\n  // edge\u3092graph\u306b\u8ffd\u52a0\u3002\n  boost::add_edge(0,1,G); // 0\u30681\u304c\u3064\u306a\u304c\u3063\u3066\u308b\n  boost::add_edge(0,2,G); // 0\u30681\u304c\u3064\u306a\u304c\u3063\u3066\u308b\n  boost::add_edge(0,3,G); // 0\u30681\u304c\u3064\u306a\u304c\u3063\u3066\u308b\n  boost::add_edge(0,4,G); // 0\u30681\u304c\u3064\u306a\u304c\u3063\u3066\u308b\n  boost::add_edge(0,5,G); // 0\u30681\u304c\u3064\u306a\u304c\u3063\u3066\u308b\n  boost::add_edge(2,4,G); // 2\u30684\u304c\u3064\u306a\u304c\u3063\u3066\u308b\n  boost::add_edge(1,4,G); // 1\u30684\u304c\u3064\u306a\u304c\u3063\u3066\u308b\n  boost::add_edge(1,2,G); // 1\u30684\u304c\u3064\u306a\u304c\u3063\u3066\u308b\n  boost::add_edge(2,5,G); // 1\u30684\u304c\u3064\u306a\u304c\u3063\u3066\u308b\n  boost::add_edge(2,3,G); // 1\u30684\u304c\u3064\u306a\u304c\u3063\u3066\u308b\n  boost::add_edge(4,3,G); // 1\u30684\u304c\u3064\u306a\u304c\u3063\u3066\u308b\n  boost::add_edge(4,5,G); // 1\u30684\u304c\u3064\u306a\u304c\u3063\u3066\u308b\n  \n  // \u5168vertex\u6570\u306e\u51fa\u529b\n  std::cout << \"total vertex \" << boost::num_vertices(G) << \"\\n\";\n  \n  // \u3064\u306a\u304c\u308a\u5177\u5408\u306e\u89e3\u6790\n  int cluster = boost::connected_components(G,&component[0]);\n  std::cout << \"# of clusters \" << cluster << '\\n'; // \u30af\u30e9\u30b9\u30bf\u30fc\u6570\n  for(int i=0;i<boost::num_vertices(G);i++){\n    std::cout << i << \" \" << component[i] << '\\n'; \n  }\n\n// clear vertex 0  \n  boost::clear_vertex(0,G);\n  /*\n \u3053\u3053\u3067\u3064\u304b\u3063\u3066\u308bVertexList(\u30c6\u30f3\u30d7\u30ec\u30fc\u30c8\u4e8c\u3064\u76ee)\u3092vecS\u3067\u6301\u3064\u30bf\u30a4\u30d7\u3060\u3068\u3001\u9802\u70b9\u3092\u524a\u9664\u3059\u308b\u3068\u3001\n \u9802\u70b9\u756a\u53f7\u304c\u524d\u306b\u8a70\u3081\u3089\u308c\u308b\u306e\u3067\u3001\u3042\u3068\u306e\u756a\u53f7\u3068\u5b9f\u969b\u306e\u9802\u70b9\u3068\u306e\u5bfe\u5fdc\u95a2\u4fc2\u304c\u4e0d\u660e\u306b\u306a\u308b\u3002\n \u4e0a\u8a18\u3001clear_vertex\u306f\u3001\u7e4b\u304c\u3063\u3066\u3044\u308bedge\u304c\u6d88\u3055\u308c\u308b\u306e\u3067\u3001\u4e00\u898b\u76ee\u7684\u306b\u5408\u81f4\u3057\u3066\u3044\u308b\u3088\u3046\u306b\u898b\u3048\u308b\u304c\u3001\n \u524a\u9664\u3067\u304d\u306a\u3044\u306e\u3067\u3001\u5b64\u7acb\u3057\u305fvertex\u304c\u6b8b\u308a\u3001\u300c\u7269\u7406\u7684\u306b\u7e4b\u304c\u3063\u3066\u3044\u306a\u3044\u30dc\u30f3\u30c9\u300d\u3068\n   \u300c\u5207\u308c\u3066\u3057\u307e\u3063\u305f\u30dc\u30f3\u30c9\u300d\u306e\u533a\u5225\u304c\u3067\u304d\u306a\u3044\u3002\n   \u5b64\u7acbvertex(\u4eca\u4f7f\u3044\u305f\u3044\u30e2\u30c7\u30eb\u3067\u306f\u30dc\u30f3\u30c9)\u3092\u751f\u6b7b\u3067\u533a\u5225\u3059\u308b\u305f\u3081\u306b\u306f\u3001\n   \u5225\u306e\u7269\u7406\u91cf\u3092\u898b\u306a\u3044\u3068\u3044\u3051\u306a\u3044\u3002\n   \n   \n   VertexList\u3092listS\u3067\u6301\u3064\u3068\u3059\u308b\u3068\u3001\u6570\u5b57\u3092\u76f4\u63a5\u5165\u308c\u3066add_edge\u3067\u304d\u306a\u3044\u3002\n   http://d.hatena.ne.jp/eagle_raptor/20111221/1324478088\n   \n     */\n//  boost::remove_vertex(0,G);\n\n    // \u5168vertex\u6570\u306e\u51fa\u529b\n  std::cout << \"total vertex \" << boost::num_vertices(G) << \"\\n\";\n\n  // \u3064\u306a\u304c\u308a\u5177\u5408\u306e\u89e3\u6790\n  cluster = boost::connected_components(G,&component[0]);\n  std::cout << \"# of clusters \" << cluster << '\\n'; // \u30af\u30e9\u30b9\u30bf\u30fc\u6570\n  for(int i=0;i<num;i++){\n    std::cout << i << \" \" << component[i] << '\\n';\n  }\n  \n  return 0;\n}\n", "meta": {"hexsha": "6b3e28deb249aee5acb012d18f781dcf4262bbcf", "size": 2307, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-test.cc", "max_stars_repo_name": "stsykw/tiny-codes", "max_stars_repo_head_hexsha": "a25db6ed53a79c89eee9156081e5ee0e191a484f", "max_stars_repo_licenses": ["MIT"], "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-test.cc", "max_issues_repo_name": "stsykw/tiny-codes", "max_issues_repo_head_hexsha": "a25db6ed53a79c89eee9156081e5ee0e191a484f", "max_issues_repo_licenses": ["MIT"], "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-test.cc", "max_forks_repo_name": "stsykw/tiny-codes", "max_forks_repo_head_hexsha": "a25db6ed53a79c89eee9156081e5ee0e191a484f", "max_forks_repo_licenses": ["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.7951807229, "max_line_length": 85, "alphanum_fraction": 0.651928912, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5588716827622173}}
{"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": "#ifndef STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_RNG_HPP\n#define STAN_MATH_PRIM_MAT_PROB_CATEGORICAL_LOGIT_RNG_HPP\n\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/mat/err/check_simplex.hpp>\n#include <stan/math/prim/mat/fun/cumulative_sum.hpp>\n#include <stan/math/prim/mat/fun/softmax.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n\nnamespace stan {\n  namespace math {\n    /**\n     * Return a draw from a Categorical distribution given a\n     * a vector of unnormalized log probabilities and a psuedo-random\n     * number generator.\n     *\n     * This is a convenience wrapper around\n     * <code>categorical_rng(softmax(beta), rng)</code>.\n     *\n     * @tparam RNG Type of pseudo-random number generator.\n     * @param beta Vector of unnormalized log probabilities.\n     * @param rng Pseudo-random number generator.\n     * @return Categorical random variate\n     */\n    template <class RNG>\n    inline int\n    categorical_logit_rng(const Eigen::VectorXd& beta,\n                          RNG& rng) {\n      using boost::variate_generator;\n      using boost::uniform_01;\n\n      static const char* function(\"categorical_logit_rng\");\n\n      check_finite(function, \"Log odds parameter\", beta);\n\n      variate_generator<RNG&, uniform_01<> >\n        uniform01_rng(rng, uniform_01<>());\n      Eigen::VectorXd theta = softmax(beta);\n      Eigen::VectorXd index = cumulative_sum(theta);\n\n      double c = uniform01_rng();\n      int b = 0;\n      while (c > index(b))\n        b++;\n      return b + 1;\n    }\n  }\n}\n#endif\n", "meta": {"hexsha": "44a0ae5164f24e85cb1667ac36c772f9520e8a46", "size": 1626, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/categorical_logit_rng.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/categorical_logit_rng.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/categorical_logit_rng.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2692307692, "max_line_length": 69, "alphanum_fraction": 0.6814268143, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5588384457986826}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main() {\n  ArrayXXf a(2, 2);\n  ArrayXXf b(2, 2);\n  a << 1, 2,\n      3, 4;\n  b << 5, 6,\n      7, 8;\n  cout << \"a * b = \" << endl << a * b << endl;\n}\n", "meta": {"hexsha": "f572fae8d6468a45ff25c259da2efa84b76a3d77", "size": 241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/Tutorial_ArrayClass_mult.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_mult.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_mult.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": 15.0625, "max_line_length": 46, "alphanum_fraction": 0.510373444, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.558838440283988}}
{"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 <iostream>\n\n#include <Eigen/Sparse>\n\n#include <gtest/gtest.h>\n\n#include \"tbb/blocked_range.h\"\n#include \"tbb/parallel_for.h\"\n#include \"tbb/parallel_reduce.h\"\n\n#include \"Integrator.h\"\n#include \"LevelSet.h\"\n#include \"ScalarGrid.h\"\n#include \"Transform.h\"\n#include \"Utilities.h\"\n#include \"VectorGrid.h\"\n\nusing namespace FluidSim3D;\n\nclass AnalyticalPoissonSolver\n{\npublic:\n    AnalyticalPoissonSolver(const Transform& xform, const Vec3i& size) \n\t\t: myXform(xform) \n\t{\n\t\tmyPoissonGrid = ScalarGrid<float>(myXform, size, 0);\n\t}\n\n    template <typename RHS, typename Solution>\n\tdouble solve(const RHS& rhsFunction, const Solution& solutionFunction);\n\nprivate:\n    Transform myXform;\n    ScalarGrid<float> myPoissonGrid;\n};\n\ntemplate <typename RHS, typename Solution>\ndouble AnalyticalPoissonSolver::solve(const RHS& rhsFuction, const Solution& solutionFunction)\n{\n    UniformGrid<int> solvableCells(myPoissonGrid.size(), -1);\n\n    int solutionDOFCount = 0;\n\n    Vec3i gridSize = myPoissonGrid.size();\n\n    forEachVoxelRange(Vec3i::Zero(), gridSize, [&](const Vec3i& cell) { solvableCells(cell) = solutionDOFCount++; });\n\n    std::vector<Eigen::Triplet<double>> sparseMatrixElements;\n\n    VectorXd rhsVector = VectorXd::Zero(solutionDOFCount);\n\n    double dx = myPoissonGrid.dx();\n\tdouble coeff = std::pow(dx, 2);\n\n\t{\n\t\ttbb::enumerable_thread_specific<std::vector<Eigen::Triplet<double>>> parallelSparseElements;\n\t\ttbb::parallel_for(tbb::blocked_range<int>(0, solvableCells.voxelCount()), [&](const tbb::blocked_range<int>& range)\n\t\t{\n        \tauto& localSparseElements = parallelSparseElements.local();\n\n\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t{\n\t\t\t\tVec3i cell = solvableCells.unflatten(cellIndex);\n\t\t\t\tint row = solvableCells(cell);\n\n\t\t\t\tassert(row >= 0);\n\n\t\t\t\t// Build RHS\n\t\t\t\tVec3d gridPoint = Vec3d(myPoissonGrid.indexToWorld(cell.cast<double>()));\n\n\t\t\t\trhsVector(row) = -coeff * rhsFuction(gridPoint);\n\n\t\t\t\tfor (auto axis : {0, 1, 2})\n\t\t\t\t\tfor (auto direction : {0, 1})\n\t\t\t\t\t{\n\t\t\t\t\t\tVec3i adjacentCell = cellToCell(cell, axis, direction);\n\n\t\t\t\t\t\t// Bounds check. Use analytical solution for Dirichlet condition.\n\t\t\t\t\t\tif ((direction == 0 && adjacentCell[axis] < 0) || (direction == 1 && adjacentCell[axis] >= gridSize[axis]))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tVec3d adjacentPoint = Vec3d(myPoissonGrid.indexToWorld(adjacentCell.cast<double>()));\n\t\t\t\t\t\t\trhsVector(row) += solutionFunction(adjacentPoint);\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\t// If neighbouring cell is solvable, it should have an entry in the system\n\t\t\t\t\t\t\tint adjacentRow = solvableCells(adjacentCell);\n\t\t\t\t\t\t\tassert(adjacentRow >= 0);\n\n\t\t\t\t\t\t\tlocalSparseElements.emplace_back(row, adjacentRow, -1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tlocalSparseElements.emplace_back(row, row, 6);\n\t\t\t}\n\t\t});\n\n\t\tmergeLocalThreadVectors(sparseMatrixElements, parallelSparseElements);\n\t}\n\n    SparseMatrix sparseMatrix(solutionDOFCount, solutionDOFCount);\n    sparseMatrix.setFromTriplets(sparseMatrixElements.begin(), sparseMatrixElements.end());\n\n    Eigen::ConjugateGradient<Eigen::SparseMatrix<double>, Eigen::Upper | Eigen::Lower> solver;\n    solver.compute(sparseMatrix);\n\n    if (solver.info() != Eigen::Success)\n    {\n        return -1;\n    }\n\n    VectorXd solutionVector = solver.solve(rhsVector);\n\n    if (solver.info() != Eigen::Success)\n    {\n        return -1;\n    }\n\n\tdouble error = tbb::parallel_reduce(tbb::blocked_range<int>(0, solvableCells.voxelCount()), double(0),\n\t\t\t\t\t[&](const tbb::blocked_range<int>& range, double error) -> double\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tVec3i cell = solvableCells.unflatten(cellIndex);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tint row = solvableCells(cell);\n\n\t\t\t\t\t\t\tassert(row >= 0);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tVec3d gridPoint = myPoissonGrid.indexToWorld(cell.cast<double>());\n\t\t\t\t\t\t\tdouble localError = fabs(solutionVector(row) - solutionFunction(gridPoint));\n\t\t\t\t\t\t\terror = std::max(error, localError);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn error;\n\t\t\t\t\t},\n\t\t\t\t\t[](double a, double b) -> double {\n\t\t\t\t\t\treturn std::max(a, b);\n\t\t\t\t\t});\n\n    return error;\n}\n\nTEST(ANALYTICAL_POISSON_SOLVER_TEST, CONVERGENCE_TEST)\n{\n\tauto rhs = [](const Vec3d& pos) -> double\n\t{\n\t\treturn 3. * std::exp(-pos[0] - pos[1] - pos[2]);\n\t};\n\n\tauto solution = [](const Vec3d& pos) -> double\n\t{\n\t\treturn std::exp(-pos[0] - pos[1] - pos[2]);\n\t};\n\n    const int startGrid = 4;\n    const int endGrid = startGrid * int(pow(2, 4));\n\t\n    std::vector<double> errors;\n    for (int gridSize = startGrid; gridSize < endGrid; gridSize *= 2)\n    {\n        double dx = PI / double(gridSize);\n\t\tVec3d origin = Vec3d::Zero();\n\t\tVec3i size = Vec3i::Constant(int(std::round(PI / dx)));\n\t\tTransform xform(dx, origin);\n\n\t\tAnalyticalPoissonSolver solver(xform, size);\n\t\tdouble error = solver.solve(rhs, solution);\n\n\t    errors.push_back(error);\n        EXPECT_GT(error, 0.);\n\t}\n\n    for (int errorIndex = 1; errorIndex < errors.size(); ++errorIndex)\n    {\n        double errorRatio = errors[errorIndex - 1] / errors[errorIndex];\n        EXPECT_GT(errorRatio, 4.);\n    }\n}", "meta": {"hexsha": "7e8104ea2bfc622ad7caadb14b98088250554b54", "size": 5052, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "UnitTests/AnalyticalPoissonSolverTests.cpp", "max_stars_repo_name": "rgoldade/3dFluidSimulation", "max_stars_repo_head_hexsha": "680d84429e73e26671a52e1a725b1b76ec4ef0db", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T16:47:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-30T01:31:09.000Z", "max_issues_repo_path": "UnitTests/AnalyticalPoissonSolverTests.cpp", "max_issues_repo_name": "rgoldade/3dFluidSimulation", "max_issues_repo_head_hexsha": "680d84429e73e26671a52e1a725b1b76ec4ef0db", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UnitTests/AnalyticalPoissonSolverTests.cpp", "max_forks_repo_name": "rgoldade/3dFluidSimulation", "max_forks_repo_head_hexsha": "680d84429e73e26671a52e1a725b1b76ec4ef0db", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3820224719, "max_line_length": 117, "alphanum_fraction": 0.6646872526, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5588038010897156}}
{"text": "/*\nBSD 3-Clause License\n\nCopyright (c) 2021 Jack Miles Hunt\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#define BOOST_TEST_MODULE HashingTests\n\n#include <utility>\n\n#include <boost/test/included/unit_test.hpp>\n\n#include <CPPUtils/Algorithms/Hashing.hpp>\n\nusing namespace CPPUtils::Algorithms;\n\nBOOST_AUTO_TEST_SUITE(HashingTestSuite)\n\nBOOST_AUTO_TEST_CASE(CantorHashTest) {\n    BOOST_CHECK_EQUAL(cantorHash(0, 0), 0);\n    BOOST_CHECK_EQUAL(cantorHash(0, 1), 2);\n    BOOST_CHECK_EQUAL(cantorHash(0, 2), 5);\n    BOOST_CHECK_EQUAL(cantorHash(0, 3), 9);\n\n    BOOST_CHECK_EQUAL(cantorHash(1, 0), 1);\n    BOOST_CHECK_EQUAL(cantorHash(1, 1), 4);\n    BOOST_CHECK_EQUAL(cantorHash(1, 2), 8);\n    BOOST_CHECK_EQUAL(cantorHash(1, 3), 13);\n\n    BOOST_CHECK_EQUAL(cantorHash(2, 0), 3);\n    BOOST_CHECK_EQUAL(cantorHash(2, 1), 7);\n    BOOST_CHECK_EQUAL(cantorHash(2, 2), 12);\n    BOOST_CHECK_EQUAL(cantorHash(2, 3), 18);\n\n    BOOST_CHECK_EQUAL(cantorHash(3, 0), 6);\n    BOOST_CHECK_EQUAL(cantorHash(3, 1), 11);\n    BOOST_CHECK_EQUAL(cantorHash(3, 2), 17);\n    BOOST_CHECK_EQUAL(cantorHash(3, 3), 24);\n}\n\nBOOST_AUTO_TEST_CASE(InverseCantorHashTest) {\n    BOOST_CHECK(inverseCantorHash(0) == std::make_pair<int>(0, 0));\n    BOOST_CHECK(inverseCantorHash(2) == std::make_pair<int>(0, 1));\n    BOOST_CHECK(inverseCantorHash(5) == std::make_pair<int>(0, 2));\n    BOOST_CHECK(inverseCantorHash(9) == std::make_pair<int>(0, 3));\n\n    BOOST_CHECK(inverseCantorHash(1) == std::make_pair<int>(1, 0));\n    BOOST_CHECK(inverseCantorHash(4) == std::make_pair<int>(1, 1));\n    BOOST_CHECK(inverseCantorHash(8) == std::make_pair<int>(1, 2));\n    BOOST_CHECK(inverseCantorHash(13) == std::make_pair<int>(1, 3));\n\n    BOOST_CHECK(inverseCantorHash(3) == std::make_pair<int>(2, 0));\n    BOOST_CHECK(inverseCantorHash(7) == std::make_pair<int>(2, 1));\n    BOOST_CHECK(inverseCantorHash(12) == std::make_pair<int>(2, 2));\n    BOOST_CHECK(inverseCantorHash(18) == std::make_pair<int>(2, 3));\n\n    BOOST_CHECK(inverseCantorHash(6) == std::make_pair<int>(3, 0));\n    BOOST_CHECK(inverseCantorHash(11) == std::make_pair<int>(3, 1));\n    BOOST_CHECK(inverseCantorHash(17) == std::make_pair<int>(3, 2));\n    BOOST_CHECK(inverseCantorHash(24) == std::make_pair<int>(3, 3));\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "fae27981d4fe51f8e69f482adf44c00a0a17d63a", "size": 3679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/Algorithms/Hashing.cpp", "max_stars_repo_name": "JackHunt/CPPUtils", "max_stars_repo_head_hexsha": "e086a257d8d2ebffaa3ca0bb6e3e9baafe98edb8", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Algorithms/Hashing.cpp", "max_issues_repo_name": "JackHunt/CPPUtils", "max_issues_repo_head_hexsha": "e086a257d8d2ebffaa3ca0bb6e3e9baafe98edb8", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Algorithms/Hashing.cpp", "max_forks_repo_name": "JackHunt/CPPUtils", "max_forks_repo_head_hexsha": "e086a257d8d2ebffaa3ca0bb6e3e9baafe98edb8", "max_forks_repo_licenses": ["BSD-3-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.3370786517, "max_line_length": 78, "alphanum_fraction": 0.7461266649, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.5587687228797431}}
{"text": "/*\n * An OpenMP snippet.\n *\n * USAGE (GCC):\n *    g++ -fopenmp -c time.cc\n *    g++ -fopenmp time.o\n *\n * In order to use N cores, the shell environment variable OMP_NUM_THREADS\n * should be set (at execution time not at compilation time):\n *    export OMP_NUM_THREADS=N\n *\n * For instance,\n *    export OMP_NUM_THREADS=2\n *    ./time\n * will use 2 cores.\n */\n\n#include <iostream>\n#include <cmath>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <omp.h>\n\nstatic const int N = 20;              // Number of integrate to compute\nstatic const int CHUNKSIZE = 1;       // Defines the chunk size as 1 contiguous iteration\nstatic const double DELTA = 0.00000001;\n\n//////////////////////////////////////////\n\n// Compute exact value of F(x) = x\u00b3/3\ndouble F(double x) {\n    return pow(x, 3) / 3.0;\n}\n\n// Numerical computation of F(x) : integ[a,b] x\u00b2 dx\ndouble num_F(double b) {\n    double a = 0.0;\n    double y = 0.0;\n\n    for(double x=a ; x<b ; x+=DELTA) {\n        y += x * x * DELTA;\n    }\n\n    return y;\n}\n\n//////////////////////////////////////////\n\nvoid print_tab(const double (& t)[N])\n{\n    for(int i=0 ; i<N ; i++) {\n        std::cout << std::fixed;\n        std::cout << \"num_F(\" << i << \") = \" << t[i] << \" - F(\" << i << \") = \" << F(i) << std::endl;\n    }\n}\n\n//////////////////////////////////////////\n\nint main()\n{\n    double x[N], y[N];\n\n    // Init x and y\n    for(int i=0 ; i<N ; i++) {\n        x[i] = i;\n        y[i] = 0;\n    }\n\n    boost::posix_time::ptime start_time = boost::posix_time::microsec_clock::local_time();\n    double omp_start_time = omp_get_wtime();\n\n    // Forks off the threads\n    #pragma omp parallel\n    {\n        // Starts the work sharing construct (static / dynamic)\n        #pragma omp for schedule(dynamic, CHUNKSIZE)\n        for(int i = 0 ; i < N ; i++)\n            y[i] = num_F(x[i]);\n    }\n\n    boost::posix_time::ptime end_time = boost::posix_time::microsec_clock::local_time();\n    boost::posix_time::time_duration delta_time = end_time - start_time;\n    double omp_end_time = omp_get_wtime();\n    double omp_delta_time = omp_end_time - omp_start_time;\n\n    // Print y\n    print_tab(y);\n\n    // Print delta_time\n    std::cerr << \"boost : \" << delta_time << std::endl;\n    std::cerr << \"omp   : \" << omp_delta_time << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "cd407de423d9cd5e1a7ae728193a230a61ed66e4", "size": 2294, "ext": "cc", "lang": "C++", "max_stars_repo_path": "openmp/TO_CHECK/time_vs_clock/time/time.cc", "max_stars_repo_name": "jeremiedecock/snippets", "max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z", "max_issues_repo_path": "openmp/TO_CHECK/time_vs_clock/time/time.cc", "max_issues_repo_name": "jeremiedecock/snippets", "max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z", "max_forks_repo_path": "openmp/TO_CHECK/time_vs_clock/time/time.cc", "max_forks_repo_name": "jeremiedecock/snippets", "max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z", "avg_line_length": 24.4042553191, "max_line_length": 100, "alphanum_fraction": 0.5492589364, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5587687101448914}}
{"text": "//==============================================================================\n//         Copyright 2015 J.T. Lapreste\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <nt2/include/functions/significants.hpp>\n\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/functor/meta/call.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/relation.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <complex>\n#include <nt2/sdk/complex/complex.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/nan.hpp>\n\nNT2_TEST_CASE_TPL ( significants,  BOOST_SIMD_REAL_TYPES)\n{\n\n  using nt2::significants;\n  using nt2::tag::significants_;\n  typedef std::complex<T> cT;\n\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n  NT2_TEST_EQUAL(significants(nt2::Inf<cT>(), 1), nt2::Inf<cT>());\n  NT2_TEST_EQUAL(significants(nt2::Minf<cT>(), 1), nt2::Minf<cT>());\n  NT2_TEST_EQUAL(significants(nt2::Nan<cT>(), 1), nt2::Nan<cT>());\n#endif\n  NT2_TEST_ULP_EQUAL(significants(cT(0), 1), cT(0), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(cT(25.34), 1), cT(30), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(cT(25.34), 2), cT(25), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(cT(25.34), 3), cT(25.3), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(cT(25.34), 4), cT(25.34), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(cT(-25.34), 1), cT(-30), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(cT(-25.34), 2), cT(-25), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(cT(-25.34), 3), cT(-25.3), 0.5);\n  NT2_TEST_ULP_EQUAL(significants(cT(-25.34), 4), cT(-25.34), 0.5);\n}\n\n", "meta": {"hexsha": "94979f2a21f14a016ff7003e9e7e914a74a2ee41", "size": 1936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/exponential/unit/scalar/significants.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/type/complex/exponential/unit/scalar/significants.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/type/complex/exponential/unit/scalar/significants.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 40.3333333333, "max_line_length": 80, "alphanum_fraction": 0.6373966942, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.5587687019822832}}
{"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": "/*\n * Copyright Nick Thompson, 2019\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <boost/math/interpolators/cardinal_quintic_b_spline.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\nusing boost::math::interpolators::cardinal_quintic_b_spline;\n\ntemplate<class Real>\nvoid test_constant()\n{\n    Real c = 7.5;\n    Real t0 = 0;\n    Real h = Real(1)/Real(16);\n    size_t n = 513;\n    std::vector<Real> v(n, c);\n    std::pair<Real, Real> left_endpoint_derivatives{0, 0};\n    std::pair<Real, Real> right_endpoint_derivatives{0, 0};\n    auto qbs = cardinal_quintic_b_spline<Real>(v.data(), v.size(), t0, h, left_endpoint_derivatives, right_endpoint_derivatives);\n\n    size_t i = 0;\n    while (i < n) {\n      Real t = t0 + i*h;\n      CHECK_ULP_CLOSE(c, qbs(t), 3);\n      CHECK_MOLLIFIED_CLOSE(Real(0), qbs.prime(t), 400*std::numeric_limits<Real>::epsilon());\n      CHECK_MOLLIFIED_CLOSE(Real(0), qbs.double_prime(t), 60000*std::numeric_limits<Real>::epsilon());\n      ++i;\n    }\n\n    i = 0;\n    while (i < n - 1) {\n      Real t = t0 + i*h + h/2;\n      CHECK_ULP_CLOSE(c, qbs(t), 5);\n      CHECK_MOLLIFIED_CLOSE(Real(0), qbs.prime(t), 600*std::numeric_limits<Real>::epsilon());\n      CHECK_MOLLIFIED_CLOSE(Real(0), qbs.double_prime(t), 30000*std::numeric_limits<Real>::epsilon());\n      t = t0 + i*h + h/4;\n      CHECK_ULP_CLOSE(c, qbs(t), 4);\n      CHECK_MOLLIFIED_CLOSE(Real(0), qbs.prime(t), 600*std::numeric_limits<Real>::epsilon());\n      CHECK_MOLLIFIED_CLOSE(Real(0), qbs.double_prime(t), 10000*std::numeric_limits<Real>::epsilon());\n      ++i;\n    }\n}\n\ntemplate<class Real>\nvoid test_constant_estimate_derivatives()\n{\n    Real c = 7.5;\n    Real t0 = 0;\n    Real h = Real(1)/Real(16);\n    size_t n = 513;\n    std::vector<Real> v(n, c);\n    auto qbs = cardinal_quintic_b_spline<Real>(v.data(), v.size(), t0, h);\n\n    size_t i = 0;\n    while (i < n) {\n      Real t = t0 + i*h;\n      CHECK_ULP_CLOSE(c, qbs(t), 3);\n      CHECK_MOLLIFIED_CLOSE(Real(0), qbs.prime(t), 1200*std::numeric_limits<Real>::epsilon());\n      CHECK_MOLLIFIED_CLOSE(Real(0), qbs.double_prime(t), 200000*std::numeric_limits<Real>::epsilon());\n      ++i;\n    }\n\n    i = 0;\n    while (i < n - 1) {\n      Real t = t0 + i*h + h/2;\n      CHECK_ULP_CLOSE(c, qbs(t), 8);\n      CHECK_MOLLIFIED_CLOSE(Real(0), qbs.prime(t), 1200*std::numeric_limits<Real>::epsilon());\n      CHECK_MOLLIFIED_CLOSE(Real(0), qbs.double_prime(t), 80000*std::numeric_limits<Real>::epsilon());\n      t = t0 + i*h + h/4;\n      CHECK_ULP_CLOSE(c, qbs(t), 5);\n      CHECK_MOLLIFIED_CLOSE(Real(0), qbs.prime(t), 1200*std::numeric_limits<Real>::epsilon());\n      CHECK_MOLLIFIED_CLOSE(Real(0), qbs.double_prime(t), 38000*std::numeric_limits<Real>::epsilon());\n      ++i;\n    }\n}\n\n\ntemplate<class Real>\nvoid test_linear()\n{\n    using std::abs;\n    Real m = 8.3;\n    Real b = 7.2;\n    Real t0 = 0;\n    Real h = Real(1)/Real(16);\n    size_t n = 512;\n    std::vector<Real> y(n);\n    for (size_t i = 0; i < n; ++i) {\n      Real t = i*h;\n      y[i] = m*t + b;\n    }\n    std::pair<Real, Real> left_endpoint_derivatives{m, 0};\n    std::pair<Real, Real> right_endpoint_derivatives{m, 0};\n    auto qbs = cardinal_quintic_b_spline<Real>(y.data(), y.size(), t0, h, left_endpoint_derivatives, right_endpoint_derivatives);\n\n    size_t i = 0;\n    while (i < n) {\n      Real t = t0 + i*h;\n      if (!CHECK_ULP_CLOSE(m*t+b, qbs(t), 3)) {\n          std::cerr << \"  Problem at t = \" << t << \"\\n\";\n      }\n      if(!CHECK_MOLLIFIED_CLOSE(m, qbs.prime(t), 100*abs(m*t+b)*std::numeric_limits<Real>::epsilon())) {\n          std::cerr << \"  Problem at t = \" << t << \"\\n\";\n      }\n      if(!CHECK_MOLLIFIED_CLOSE(0, qbs.double_prime(t), 10000*abs(m*t+b)*std::numeric_limits<Real>::epsilon())) {\n          std::cerr << \"  Problem at t = \" << t << \"\\n\";\n      }\n      ++i;\n    }\n\n    i = 0;\n    while (i < n - 1) {\n      Real t = t0 + i*h + h/2;\n      if(!CHECK_ULP_CLOSE(m*t+b, qbs(t), 4)) {\n          std::cerr << \"  Problem at t = \" << t << \"\\n\";\n      }\n      CHECK_MOLLIFIED_CLOSE(m, qbs.prime(t), 1500*std::numeric_limits<Real>::epsilon());\n      t = t0 + i*h + h/4;\n      if(!CHECK_ULP_CLOSE(m*t+b, qbs(t), 4)) {\n          std::cerr << \"  Problem at t = \" << t << \"\\n\";\n      }\n      CHECK_MOLLIFIED_CLOSE(m, qbs.prime(t), 3000*std::numeric_limits<Real>::epsilon());\n      ++i;\n    }\n}\n\ntemplate<class Real>\nvoid test_linear_estimate_derivatives()\n{\n    using std::abs;\n    Real m = 8.3;\n    Real b = 7.2;\n    Real t0 = 0;\n    Real h = Real(1)/Real(16);\n    size_t n = 512;\n    std::vector<Real> y(n);\n    for (size_t i = 0; i < n; ++i) {\n      Real t = i*h;\n      y[i] = m*t + b;\n    }\n\n    auto qbs = cardinal_quintic_b_spline<Real>(y.data(), y.size(), t0, h);\n\n    size_t i = 0;\n    while (i < n) {\n      Real t = t0 + i*h;\n      if (!CHECK_ULP_CLOSE(m*t+b, qbs(t), 3)) {\n          std::cerr << \"  Problem at t = \" << t << \"\\n\";\n      }\n      if(!CHECK_MOLLIFIED_CLOSE(m, qbs.prime(t), 100*abs(m*t+b)*std::numeric_limits<Real>::epsilon())) {\n          std::cerr << \"  Problem at t = \" << t << \"\\n\";\n      }\n      if(!CHECK_MOLLIFIED_CLOSE(0, qbs.double_prime(t), 20000*abs(m*t+b)*std::numeric_limits<Real>::epsilon())) {\n          std::cerr << \"  Problem at t = \" << t << \"\\n\";\n      }\n      ++i;\n    }\n\n    i = 0;\n    while (i < n - 1) {\n      Real t = t0 + i*h + h/2;\n      if(!CHECK_ULP_CLOSE(m*t+b, qbs(t), 5)) {\n          std::cerr << \"  Problem at t = \" << t << \"\\n\";\n      }\n      CHECK_MOLLIFIED_CLOSE(m, qbs.prime(t), 1500*std::numeric_limits<Real>::epsilon());\n      t = t0 + i*h + h/4;\n      if(!CHECK_ULP_CLOSE(m*t+b, qbs(t), 4)) {\n          std::cerr << \"  Problem at t = \" << t << \"\\n\";\n      }\n      CHECK_MOLLIFIED_CLOSE(m, qbs.prime(t), 3000*std::numeric_limits<Real>::epsilon());\n      ++i;\n    }\n}\n\n\ntemplate<class Real>\nvoid test_quadratic()\n{\n    Real a = Real(1)/Real(16);\n    Real b = -3.5;\n    Real c = -9;\n    Real t0 = 0;\n    Real h = Real(1)/Real(16);\n    size_t n = 513;\n    std::vector<Real> y(n);\n    for (size_t i = 0; i < n; ++i) {\n      Real t = i*h;\n      y[i] = a*t*t + b*t + c;\n    }\n    Real t_max = t0 + (n-1)*h;\n    std::pair<Real, Real> left_endpoint_derivatives{b, 2*a};\n    std::pair<Real, Real> right_endpoint_derivatives{2*a*t_max + b, 2*a};\n\n    auto qbs = cardinal_quintic_b_spline<Real>(y, t0, h, left_endpoint_derivatives, right_endpoint_derivatives);\n\n    size_t i = 0;\n    while (i < n) {\n      Real t = t0 + i*h;\n      CHECK_ULP_CLOSE(a*t*t + b*t + c, qbs(t), 3);\n      ++i;\n    }\n\n    i = 0;\n    while (i < n -1) {\n      Real t = t0 + i*h + h/2;\n      if(!CHECK_ULP_CLOSE(a*t*t + b*t + c, qbs(t), 5)) {\n          std::cerr << \"  Problem at abscissa t = \" << t << \"\\n\";\n      }\n\n      t = t0 + i*h + h/4;\n      if (!CHECK_ULP_CLOSE(a*t*t + b*t + c, qbs(t), 5)) {\n          std::cerr << \"  Problem abscissa t = \" << t << \"\\n\";\n      }\n      ++i;\n    }\n}\n\n\ntemplate<class Real>\nvoid test_quadratic_estimate_derivatives()\n{\n    Real a = Real(1)/Real(16);\n    Real b = -3.5;\n    Real c = -9;\n    Real t0 = 0;\n    Real h = Real(1)/Real(16);\n    size_t n = 513;\n    std::vector<Real> y(n);\n    for (size_t i = 0; i < n; ++i) {\n      Real t = i*h;\n      y[i] = a*t*t + b*t + c;\n    }\n    auto qbs = cardinal_quintic_b_spline<Real>(y, t0, h);\n\n    size_t i = 0;\n    while (i < n) {\n      Real t = t0 + i*h;\n      CHECK_ULP_CLOSE(a*t*t + b*t + c, qbs(t), 3);\n      ++i;\n    }\n\n    i = 0;\n    while (i < n -1) {\n      Real t = t0 + i*h + h/2;\n      if(!CHECK_ULP_CLOSE(a*t*t + b*t + c, qbs(t), 10)) {\n          std::cerr << \"  Problem at abscissa t = \" << t << \"\\n\";\n      }\n\n      t = t0 + i*h + h/4;\n      if (!CHECK_ULP_CLOSE(a*t*t + b*t + c, qbs(t), 6)) {\n          std::cerr << \"  Problem abscissa t = \" << t << \"\\n\";\n      }\n      ++i;\n    }\n}\n\n\nint main()\n{\n    test_constant<double>();\n    test_constant<long double>();\n\n    test_constant_estimate_derivatives<double>();\n    test_constant_estimate_derivatives<long double>();\n\n    test_linear<float>();\n    test_linear<double>();\n    test_linear<long double>();\n\n    test_linear_estimate_derivatives<double>();\n    test_linear_estimate_derivatives<long double>();\n\n    test_quadratic<double>();\n    test_quadratic<long double>();\n\n    test_quadratic_estimate_derivatives<double>();\n    test_quadratic_estimate_derivatives<long double>();\n\n\n    #ifdef BOOST_HAS_FLOAT128\n        test_constant<float128>();\n        test_linear<float128>();\n        test_linear_estimate_derivatives<float128>();\n    #endif\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "31b9fd9100acd2b87b792d8e41389095b60ca336", "size": 8760, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/cardinal_quintic_b_spline_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "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/test/cardinal_quintic_b_spline_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T08:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-06T20:49:05.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/test/cardinal_quintic_b_spline_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 29.4949494949, "max_line_length": 129, "alphanum_fraction": 0.5613013699, "num_tokens": 2860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5587678430556865}}
{"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: \u222b 1\n    vol += n.dot(a)/6.;\n    // centroid via divergence theorem and midpoint quadrature: \u222b 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": "#ifndef NN_BASIS_FUNCTION_H\n#define NN_BASIS_FUNCTION_H\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n#include <mlpack/methods/ann/loss_functions/mean_squared_error.hpp>\n#include <armadillo>\n#include <json.hpp>\n#include <robotics/basis_functions.hpp>\n\nnamespace hsmm {\n\n    typedef mlpack::ann::FFN<mlpack::ann::MeanSquaredError<>,\n            mlpack::ann::RandomInitialization> NNmodel;\n\n    class ScalarNNBasis : public robotics::ScalarBasisFun {\n        public:\n            ScalarNNBasis(arma::ivec hidden_units_per_layer, int njoints);\n\n            ScalarNNBasis(nlohmann::json &stream);\n\n            NNmodel& getNeuralNet() const;\n\n            // Takes into account also the input and output layers.\n            int getNumberLayers() const;\n\n            std::pair<arma::mat, arma::vec> getOutputLayerParams() const;\n\n            void setNeuralNet(NNmodel &neural_net);\n\n            arma::vec eval(double t) const;\n\n            // TODO.\n            arma::vec deriv(double time, unsigned int order) const;\n\n            unsigned int dim() const;\n\n            nlohmann::json to_stream() const;\n\n            ~ScalarNNBasis() = default;\n\n        private:\n            arma::ivec hidden_units_per_layer_;\n            mlpack::ann::Linear<>* output_layer_ = nullptr;\n            mutable NNmodel neural_net_;\n            int neural_net_outputs_;\n    };\n\n};\n\n#endif\n", "meta": {"hexsha": "4e186e8f4f07954f6c446c2f0e27260c0b63f0af", "size": 1482, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/NN_basis_function.hpp", "max_stars_repo_name": "DiegoAE/BOSD", "max_stars_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T05:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:14:31.000Z", "max_issues_repo_path": "include/NN_basis_function.hpp", "max_issues_repo_name": "DiegoAE/BOSD", "max_issues_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T15:29:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T10:14:54.000Z", "max_forks_repo_path": "include/NN_basis_function.hpp", "max_forks_repo_name": "DiegoAE/BOSD", "max_forks_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T07:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T07:44:09.000Z", "avg_line_length": 27.4444444444, "max_line_length": 74, "alphanum_fraction": 0.6484480432, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5587114210667549}}
{"text": "#include \"ValueWithError.hpp\"\n#include \"precompiled.hpp\"\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wglobal-constructors\"\n#endif // __clang__\n\n#if defined __GNUC__ \\\n            && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) ) \\\n            && !defined __clang__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n\nusing namespace error_propagation;\n\nnamespace {\n\n  typedef ValueWithError<double> VD;\n  using boost::math::pow;\n\n  const double D_EPS             = std::numeric_limits<double>::epsilon();\n  const double D_LARGE_EPS       = 1000.0 * std::numeric_limits<double>::epsilon();\n\n  const double half_pi           = boost::math::constants::half_pi<double>();\n  const double pi                = boost::math::constants::pi<double>();\n  const double e                 = boost::math::constants::e<double>();\n  const double ln_two            = boost::math::constants::ln_two<double>();\n  const double ln_ten            = boost::math::constants::ln_ten<double>();\n  const double one_div_root_two  = boost::math::constants::one_div_root_two<double>();\n  const double root_two          = boost::math::constants::root_two<double>();\n  const double three_quarters_pi = boost::math::constants::three_quarters_pi<double>();\n  const double quarter_pi        = boost::math::constants::pi<double>() / 4.0;\n  const double one_div_root_pi   = boost::math::constants::one_div_root_pi<double>();\n  const double two_div_root_pi   = boost::math::constants::one_div_root_pi<double>() * 2.0;\n  const double euler             = boost::math::constants::euler<double>();\n\n  struct Fixture\n  {\n    Fixture()\n      :\n      pvMinus(-2.0,4.0),\n      pvPlus(2.0,4.0)\n    {}\n\n    const VD pvMinus, pvPlus, pvZero;\n  };\n\n} // anonymous namespace\n\nBOOST_FIXTURE_TEST_SUITE(Test_ValueWithError_MathOverloads,Fixture)\n\nBOOST_AUTO_TEST_SUITE(_expm1)\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  VD pv(1.0,2.0);\n  VD result = expm1(pv);\n  BOOST_CHECK_CLOSE(result.GetValue(),e - 1.0,D_LARGE_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(),2.0 * e,D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  VD pv(0.0,2.0);\n  VD result = expm1(pv);\n  BOOST_CHECK_SMALL(result.GetValue(),D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(),2.0,D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(negative)\n{\n  VD pv(-1.0,2.0);\n  VD result = expm1(pv);\n  BOOST_CHECK_CLOSE(result.GetValue(),1.0 / e - 1.0,D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(),2.0 / e,D_EPS);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // _expm1\n\nBOOST_AUTO_TEST_SUITE(_exp2)\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  VD pv(1.0,2.0);\n  VD result = exp2(pv);\n  BOOST_CHECK_CLOSE(result.GetValue(),2.0,D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(),ln_two * 2.0 * 2.0,D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  VD pv(0.0,2.0);\n  VD result = exp2(pv);\n  BOOST_CHECK_CLOSE(result.GetValue(), 1.0, D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), ln_two*2.0, D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(negative)\n{\n  VD pv(-1.0,2.0);\n  VD result = exp2(pv);\n  BOOST_CHECK_CLOSE(result.GetValue(),0.5,D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), ln_two * 0.5 * 2.0, D_EPS);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // _exp2\n\nBOOST_AUTO_TEST_SUITE(_log2)\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  VD val(2.0,2.0);\n  VD result = log2(val);\n  BOOST_CHECK_CLOSE(result.GetValue(),1.0,D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), 1.0 / ln_two, D_LARGE_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  VD val(0.0,2.0);\n  VD result = log2(val);\n  BOOST_CHECK(boost::math::isinf(result.GetValue()));\n  BOOST_CHECK(boost::math::isinf(result.GetError()));\n}\n\nBOOST_AUTO_TEST_CASE(negative)\n{\n  VD val(-2.0,2.0);\n  VD result = log2(val);\n  BOOST_CHECK(boost::math::isnan(result.GetValue()));\n  BOOST_CHECK_CLOSE(result.GetError(), 0.5 / ln_two * 2.0, D_EPS);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // _log2\n\nBOOST_AUTO_TEST_SUITE(_log1p)\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  VD val(1.0,2.0);\n  VD result = log1p(val);\n  BOOST_CHECK_CLOSE(result.GetValue(),ln_two,D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), 1.0, D_LARGE_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(negative_special_case)\n{\n  // -1.0 is special\n  VD val(-1.0,2.0);\n  VD result = log1p(val);\n  BOOST_CHECK(boost::math::isinf(result.GetValue()));\n  BOOST_CHECK(boost::math::isinf(result.GetError()));\n}\n\nBOOST_AUTO_TEST_CASE(negative)\n{\n  VD val(-3.0,2.0);\n  VD result = log1p(val);\n  BOOST_CHECK(boost::math::isnan(result.GetValue()));\n  BOOST_CHECK_CLOSE(result.GetError(), 1.0 , D_EPS);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // _log1p\n\nBOOST_AUTO_TEST_SUITE(_asinh)\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  VD val(1.0,2.0);\n  VD result = asinh(val);\n  BOOST_CHECK_CLOSE(result.GetValue(), std::log(1.0 + root_two), D_LARGE_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), 1.0 / root_two * 2.0, D_LARGE_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  VD val(0.0,2.0);\n  VD result = asinh(val);\n  BOOST_CHECK_SMALL(result.GetValue(),D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(),2.0,D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(negative)\n{\n  VD val(-1.0,2.0);\n  VD result = asinh(val);\n  BOOST_CHECK_CLOSE(result.GetValue(),std::log(-1.0 + root_two),D_LARGE_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), 1.0 / root_two * 2.0 ,D_LARGE_EPS);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // _asinh\n\nBOOST_AUTO_TEST_SUITE(_acosh)\n\nBOOST_AUTO_TEST_CASE(positive_special_plus_one)\n{\n  VD val(1.0,2.0);\n  VD result = acosh(val);\n  BOOST_CHECK_SMALL(result.GetValue(), D_EPS);\n  BOOST_CHECK(boost::math::isinf(result.GetError()));\n}\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  VD val(2.0,3.0);\n  VD result = acosh(val);\n  BOOST_CHECK_CLOSE(result.GetValue(), std::log( 2.0 + std::sqrt(3.0) ), D_LARGE_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), 1.0 / std::sqrt(3.0) * 3.0, D_LARGE_EPS);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // _acosh\n\nBOOST_AUTO_TEST_SUITE(_atanh)\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  VD val(0.5,2.0);\n  VD result = atanh(val);\n  BOOST_CHECK_CLOSE(result.GetValue(), 0.5 * std::log(3.0), D_LARGE_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), 4.0/3.0 * 2.0, D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(positive_one_special)\n{\n  VD val(1.0,2.0);\n  VD result = atanh(val);\n  BOOST_CHECK(boost::math::isinf(result.GetValue()));\n  BOOST_CHECK(boost::math::isinf(result.GetError()));\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  VD val(0.0,2.0);\n  VD result = atanh(val);\n  BOOST_CHECK_SMALL(result.GetValue(), D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), 2.0, D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(negative)\n{\n  VD val(-0.5,2.0);\n  VD result = atanh(val);\n  BOOST_CHECK_CLOSE(result.GetValue(), -0.5 * std::log(3.0), D_LARGE_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), 4.0/3.0 * 2.0, D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(negative_one_special)\n{\n  VD val(-1.0,2.0);\n  VD result = atanh(val);\n  BOOST_CHECK(boost::math::isinf(result.GetValue()));\n  BOOST_CHECK(boost::math::isinf(result.GetError()));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // _atanh\n\nBOOST_AUTO_TEST_SUITE(_cbrt)\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  VD val(1.0,2.0);\n  VD result = cbrt(val);\n  BOOST_CHECK_CLOSE(result.GetValue(), 1.0, D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), 1.0 / 3.0 * 2.0, D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  VD val(0.0,2.0);\n  VD result = cbrt(val);\n  BOOST_CHECK_SMALL(result.GetValue(),D_EPS);\n  BOOST_CHECK(boost::math::isinf(result.GetError()));\n}\n\nBOOST_AUTO_TEST_CASE(negative)\n{\n  VD val(-1.0,2.0);\n  VD result = cbrt(val);\n  BOOST_CHECK_CLOSE(result.GetValue(), -1.0, D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), 1.0 / 3.0 * 2.0 , D_EPS);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // _cbrt\n\nBOOST_AUTO_TEST_SUITE(_erf)\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  VD val(0.2,2.0);\n  VD result = erf(val);\n  // Taken from Abramowitz and Stegun, 9th Dover printing, Table 7.1 page 310\n  BOOST_CHECK_CLOSE(result.GetValue(), 0.2227025892, 1e-8);\n  BOOST_CHECK_CLOSE(result.GetError(), two_div_root_pi * std::exp(-0.04) * 2.0 , D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  VD val(0.0,2.0);\n  VD result = erf(val);\n  BOOST_CHECK_SMALL(result.GetValue(), D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), two_div_root_pi * 2.0, D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(negative)\n{\n  VD val(-0.2,2.0);\n  VD result = erf(val);\n  // Taken from Abramowitz and Stegun, 9th Dover printing, Table 7.1 page 310\n  // and changed sign\n  BOOST_CHECK_CLOSE(result.GetValue(), -0.2227025892, 1e-8);\n  BOOST_CHECK_CLOSE(result.GetError(),  two_div_root_pi * std::exp(-0.04) * 2.0 , D_EPS);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // _erf\n\nBOOST_AUTO_TEST_SUITE(_erfc)\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  VD val(0.2,2.0);\n  VD result = erfc(val);\n  // Taken from Abramowitz and Stegun, 9th Dover printing, Table 7.1 page 310\n  BOOST_CHECK_CLOSE(result.GetValue(), 1.0 - 0.2227025892, 1e-8);\n  BOOST_CHECK_CLOSE(result.GetError(), two_div_root_pi * std::exp(-0.04) * 2.0 , D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  VD val(0.0,2.0);\n  VD result = erfc(val);\n  BOOST_CHECK_CLOSE(result.GetValue(), 1.0 , D_EPS);\n  BOOST_CHECK_CLOSE(result.GetError(), two_div_root_pi * 2.0, D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(negative)\n{\n  VD val(-0.2,2.0);\n  VD result = erfc(val);\n  // Taken from Abramowitz and Stegun, 9th Dover printing, Table 7.1 page 310\n  // and changed sign\n  BOOST_CHECK_CLOSE(result.GetValue(), 1.0 + 0.2227025892, 1e-8);\n  BOOST_CHECK_CLOSE(result.GetError(), two_div_root_pi * std::exp(-0.04) * 2.0 , D_EPS);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // _erfc\n\nBOOST_AUTO_TEST_SUITE(_hypot)\n\nBOOST_AUTO_TEST_SUITE(x_y_pv)\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  VD x(3.0,1.0);\n  VD y(4.0,2.0);\n  VD result = hypot(x,y);\n  BOOST_CHECK_CLOSE(result.GetValue(), 5.0, D_LARGE_EPS );\n  BOOST_CHECK_CLOSE(result.GetError(), 1.0 / 25.0 * std::hypot(3.0 * 1.0, 4.0 * 2.0), D_LARGE_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  VD x(0.0,1.0);\n  VD y(0.0,2.0);\n  VD result = hypot(x,y);\n  BOOST_CHECK_CLOSE(result.GetValue(), 0.0 , D_EPS);\n  BOOST_CHECK(boost::math::isnan(result.GetError()));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // x_y_positive\n\nBOOST_AUTO_TEST_SUITE(x_pv_y_double)\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  VD x(3.0,1.0);\n  double y = 4.0;\n  VD result = hypot(x,y);\n  BOOST_CHECK_CLOSE(result.GetValue(), 5.0, D_EPS );\n  BOOST_CHECK_CLOSE(result.GetError(), 1.0 / 25.0 * 3.0 * 1.0, D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  VD x(0.0,1.0);\n  double y = 0.0;\n  VD result = hypot(x,y);\n  BOOST_CHECK_CLOSE(result.GetValue(), 0.0, D_EPS);\n  BOOST_CHECK(boost::math::isnan(result.GetError()));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // x_pv_y_double\n\nBOOST_AUTO_TEST_SUITE(x_double_y_pv)\n\nBOOST_AUTO_TEST_CASE(positive)\n{\n  double x = 4.0;\n  VD y(3.0,1.0);\n  VD result = hypot(x,y);\n  BOOST_CHECK_CLOSE(result.GetValue(), 5.0, D_EPS );\n  BOOST_CHECK_CLOSE(result.GetError(), 1.0 / 25.0 * 3.0 * 1.0, D_EPS);\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  double x = 0.0;\n  VD y(0.0,1.0);\n  VD result = hypot(x,y);\n  BOOST_CHECK_CLOSE(result.GetValue(), 0.0, D_EPS);\n  BOOST_CHECK(boost::math::isnan(result.GetError()));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // x_double_y_pv\n\nBOOST_AUTO_TEST_SUITE_END() // _hypot\n\nBOOST_AUTO_TEST_SUITE(_tgamma)\n\nBOOST_AUTO_TEST_CASE(positive_integer)\n{\n  VD x(4.0,1.0);\n  VD result = tgamma(x);\n  BOOST_CHECK_CLOSE(result.GetValue(), 6.0, D_EPS ); // gamma(n) = factorial(n-1) = 4*3*2*1: see Abramowitz & Stegun p. 255\n  BOOST_CHECK_CLOSE(result.GetError(), (-euler + 1.0 + 0.5 + 1.0/3.0) * 6.0 * x.GetError(), D_LARGE_EPS); // psi(n) * gamma(n), psi(n): see Abramowitz & Stegun p. 258\n}\n\nBOOST_AUTO_TEST_CASE(positive_fractional)\n{\n  VD x(0.5,1.0);\n  VD result = tgamma(x);\n  BOOST_CHECK_CLOSE(result.GetValue(), 1.772453850905516, D_EPS ); // tabulated gamma(1/2): see Abramowitz & Stegun p. 3\n  BOOST_CHECK_CLOSE(result.GetError(), std::abs((-euler - 2.0*ln_two) * 1.772453850905516 * x.GetError()), D_LARGE_EPS); // psi(1/2): see Abramowitz & Stegun p. 258\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  VD x(0.0,1.0);\n  VD result = tgamma(x);\n  BOOST_CHECK(boost::math::isinf(result.GetValue()));\n  BOOST_CHECK(boost::math::isinf(result.GetError()));\n}\n\nBOOST_AUTO_TEST_CASE(negative_integer)\n{\n  VD x(-1.0,1.0);\n  VD result = tgamma(x);\n  BOOST_CHECK(boost::math::isnan(result.GetValue()));\n  BOOST_CHECK(boost::math::isnan(result.GetError()));\n}\n\nBOOST_AUTO_TEST_CASE(negative_fractional)\n{\n  VD x(-0.5,1.0);\n  VD result = tgamma(x);\n  // An error threshold of 1e-8 used here as tabulated value for Gamma(3/2) is available from Abramowitz to 10 digits precision only. This test should pass with the given precision on a 32bit system.\n  BOOST_CHECK_CLOSE(result.GetValue(), (pi/std::sin(-half_pi)) / 0.8862269254 , 1e-8 ); // tabulated Gamma(3/2), see Abramowitz & Stegun p. 255, reflection formula: Gamma(z)*Gamma(1-z) = pi*csc(pi*z)\n  BOOST_CHECK_CLOSE(result.GetError(), std::abs(((-euler - 2.0*ln_two)-1/(-0.5)) * ((pi/std::sin(-half_pi))/0.8862269254) * x.GetError()), 1e-8); // psi(1/2), recurrence formula psi(1+z) = psi(z) + 1/z, see Abramowitz & Stegun p. 258\n}\n\nBOOST_AUTO_TEST_SUITE_END() // _tgamma\n\nBOOST_AUTO_TEST_SUITE(_lgamma)\n\nBOOST_AUTO_TEST_CASE(positive_integer)\n{\n  VD x(4.0,1.0);\n  VD result = lgamma(x);\n  BOOST_CHECK_CLOSE(result.GetValue(), std::log(6.0), D_EPS ); // gamma(n) = factorial(n-1) = 4*3*2*1, see Abramowitz & Stegun p. 255\n  BOOST_CHECK_CLOSE(result.GetError(), (-euler + 1.0 + 0.5 + 1.0/3.0) * x.GetError(), D_LARGE_EPS); // psi(n), see Abramowitz & Stegun p. 258\n}\n\nBOOST_AUTO_TEST_CASE(positive_fractional)\n{\n  VD x(0.5,1.0);\n  VD result = lgamma(x);\n  BOOST_CHECK_CLOSE(result.GetValue(), std::log(1.772453850905516), D_EPS ); // tabulated gamma(1/2), see Abramowitz & Stegun p. 3\n  BOOST_CHECK_CLOSE(result.GetError(), std::abs((-euler - 2.0*ln_two) * x.GetError()), D_EPS); // psi(1/2), see Abramowitz & Stegun p. 258\n}\n\nBOOST_AUTO_TEST_CASE(zero)\n{\n  VD x(0.0,1.0);\n  VD result = lgamma(x);\n  BOOST_CHECK(boost::math::isinf(result.GetValue()));\n  BOOST_CHECK(boost::math::isinf(result.GetError()));\n}\n\nBOOST_AUTO_TEST_CASE(negative_integer)\n{\n  VD x(-1.0,1.0);\n  VD result = lgamma(x);\n  BOOST_CHECK(boost::math::isinf(result.GetValue())); // TODO: lgamma and tgamma specifications do not match in linux c++ standard library libstdc++.so.6.0.17 from gcc-4.7, check this with 4.8.\n  BOOST_CHECK(boost::math::isnan(result.GetError()));\n}\n\nBOOST_AUTO_TEST_CASE(negative_fractional)\n{\n  VD x(-0.5,1.0);\n  VD result = lgamma(x);\n  // An error threshold of 1e-8 used here as tabulated value for Gamma(3/2) is available from Abramowitz to 10 digits precision only. This test should pass with the given precision on a 32bit system.\n  BOOST_CHECK_CLOSE(result.GetValue(), std::log(std::abs((pi/std::sin(-half_pi)) / 0.8862269254)) , 1e-8 ); // tabulated Gamma(3/2), see Abramowitz & Stegun p. 255, reflection formula: Gamma(z)*Gamma(1-z) = pi*csc(pi*z)\n  BOOST_CHECK_CLOSE(result.GetError(), std::abs(((-euler - 2.0*ln_two)-1/(-0.5)) * x.GetError()), 1e-8); // psi(1/2), recurrence formula psi(1+z) = psi(z) + 1/z, see Abramowitz & Stegun p. 258\n}\n\nBOOST_AUTO_TEST_SUITE_END() // _lgamma\n\nBOOST_AUTO_TEST_SUITE_END() // Test_MathOverloads\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif // __clang__\n\n#if defined __GNUC__ \\\n            && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) ) \\\n            && !defined __clang__\n#pragma GCC diagnostic pop\n#endif\n\n", "meta": {"hexsha": "50fb5e10d6e20b5f3fbd38d703c7137d483c23e7", "size": 15136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Test_ValueWithError_math_overloads_cpp11.cpp", "max_stars_repo_name": "t-b/value-with-error", "max_stars_repo_head_hexsha": "ede8325d3572ac53601d0d7aabc09518850c8455", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-07T10:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T01:09:50.000Z", "max_issues_repo_path": "tests/Test_ValueWithError_math_overloads_cpp11.cpp", "max_issues_repo_name": "t-b/value-with-error", "max_issues_repo_head_hexsha": "ede8325d3572ac53601d0d7aabc09518850c8455", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Test_ValueWithError_math_overloads_cpp11.cpp", "max_forks_repo_name": "t-b/value-with-error", "max_forks_repo_head_hexsha": "ede8325d3572ac53601d0d7aabc09518850c8455", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8304761905, "max_line_length": 233, "alphanum_fraction": 0.6952299154, "num_tokens": 4867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5586676640325918}}
{"text": "//\n// Created by Pascal Hav\u00e9 on 2019-08-13.\n//\n\n#ifndef LIBKRIGING_LINEARREGRESSION_HPP\n#define LIBKRIGING_LINEARREGRESSION_HPP\n\n#include <armadillo>\n\n#include \"libKriging/libKriging_exports.h\"\n\n/** Basic linear regression\n * @ingroup Regression\n */\nclass LinearRegression {\n public:\n  /** Trivial constructor */\n  LIBKRIGING_EXPORT LinearRegression();\n\n  [[nodiscard]] const arma::colvec& coef() const { return m_coef; };\n  [[nodiscard]] const double& sig2() const { return m_sig2; };\n  [[nodiscard]] const arma::colvec& stderrest() const { return m_stderrest; };\n\n  /** True linear regression computation\n   * has to find s such that y ~= X * s\n   * The accuracy may be evaluated using the returned standard error\n   *\n   * @param y : rhs vector of size n\n   * @param X : matrix of size n * m\n   */\n  LIBKRIGING_EXPORT void fit(const arma::vec& y, const arma::mat& X);\n\n  LIBKRIGING_EXPORT std::tuple<arma::colvec, arma::colvec> predict(const arma::mat& X);\n\n private:\n  arma::colvec m_coef;\n  double m_sig2{};\n  arma::colvec m_stderrest;\n};\n\n#endif  // LIBKRIGING_LINEARREGRESSION_HPP\n", "meta": {"hexsha": "446518f7e106a93c280bd7e400493ff6a2c32487", "size": 1088, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/include/libKriging/LinearRegression.hpp", "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/include/libKriging/LinearRegression.hpp", "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/include/libKriging/LinearRegression.hpp", "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": 25.9047619048, "max_line_length": 87, "alphanum_fraction": 0.7049632353, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5586676640325918}}
{"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": "#ifndef STAN_MATH_PRIM_SCAL_PROB_NORMAL_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_NORMAL_RNG_HPP\n\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template <class RNG>\n    inline double\n    normal_rng(double mu,\n               double sigma,\n               RNG& rng) {\n      using boost::variate_generator;\n      using boost::normal_distribution;\n\n      static const char* function(\"normal_rng\");\n\n      check_finite(function, \"Location parameter\", mu);\n      check_not_nan(function, \"Location parameter\", mu);\n      check_positive(function, \"Scale parameter\", sigma);\n      check_not_nan(function, \"Scale parameter\", sigma);\n\n      variate_generator<RNG&, normal_distribution<> >\n        norm_rng(rng, normal_distribution<>(mu, sigma));\n      return norm_rng();\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "cbd930b549bfc0c5221c7999819f98e6a242bf0d", "size": 1186, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/normal_rng.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/normal_rng.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/normal_rng.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4102564103, "max_line_length": 61, "alphanum_fraction": 0.7192242833, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5586625880151938}}
{"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": "#ifndef SEQUENTIAL_LINE_SEARCH_GAUSSIAN_PROCESS_REGRESSOR_HPP\n#define SEQUENTIAL_LINE_SEARCH_GAUSSIAN_PROCESS_REGRESSOR_HPP\n\n#include <Eigen/Core>\n#include <sequential-line-search/regressor.hpp>\n\nnamespace sequential_line_search\n{\n    class GaussianProcessRegressor : public Regressor\n    {\n    public:\n        /// \\details Hyperparameters will be set via MAP estimation.\n        GaussianProcessRegressor(const Eigen::MatrixXd& X,\n                                 const Eigen::VectorXd& y,\n                                 const KernelType       kernel_type = KernelType::ArdMatern52Kernel);\n\n        /// \\details Specified hyperparameters will be used.\n        GaussianProcessRegressor(const Eigen::MatrixXd& X,\n                                 const Eigen::VectorXd& y,\n                                 const Eigen::VectorXd& kernel_hyperparams,\n                                 double                 noise_hyperparam,\n                                 const KernelType       kernel_type = KernelType::ArdMatern52Kernel);\n\n        double PredictMu(const Eigen::VectorXd& x) const override;\n        double PredictSigma(const Eigen::VectorXd& x) const override;\n\n        Eigen::VectorXd PredictMuDerivative(const Eigen::VectorXd& x) const override;\n        Eigen::VectorXd PredictSigmaDerivative(const Eigen::VectorXd& x) const override;\n\n        // Can be derived after MAP\n        Eigen::MatrixXd m_K_y;\n        Eigen::MatrixXd m_K_y_inv;\n\n        // Getter\n        const Eigen::MatrixXd& GetLargeX() const override { return m_X; }\n        const Eigen::VectorXd& GetSmallY() const override { return m_y; }\n\n        const Eigen::VectorXd& GetKernelHyperparams() const override { return m_kernel_hyperparams; }\n        double                 GetNoiseHyperparam() const override { return m_noise_hyperparam; }\n\n    private:\n        void PerformMapEstimation();\n\n        /// \\brief Data points.\n        Eigen::MatrixXd m_X;\n\n        /// \\brief Values on data points.\n        Eigen::VectorXd m_y;\n\n        /// \\brief Kernel hyperparameters\n        ///\n        /// \\details Derived from MAP or specified directly.\n        Eigen::VectorXd m_kernel_hyperparams;\n\n        /// \\brief A hyperparameter about noise level of ARD.\n        ///\n        /// \\details Derived from MAP or specified directly.\n        double m_noise_hyperparam;\n    };\n} // namespace sequential_line_search\n\n#endif // SEQUENTIAL_LINE_SEARCH_GAUSSIAN_PROCESS_REGRESSOR_HPP\n", "meta": {"hexsha": "d07e5f39b91b4cb704e3e02c85ed83459f67ea49", "size": 2437, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sequential-line-search/gaussian-process-regressor.hpp", "max_stars_repo_name": "yuki-koyama/sequential-line-search", "max_stars_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-03-12T13:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T20:28:04.000Z", "max_issues_repo_path": "include/sequential-line-search/gaussian-process-regressor.hpp", "max_issues_repo_name": "yuki-koyama/sequential-line-search", "max_issues_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T23:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T03:52:42.000Z", "max_forks_repo_path": "include/sequential-line-search/gaussian-process-regressor.hpp", "max_forks_repo_name": "yuki-koyama/sequential-line-search", "max_forks_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-06-12T17:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T11:13:03.000Z", "avg_line_length": 38.6825396825, "max_line_length": 101, "alphanum_fraction": 0.6372589249, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.5586583035062418}}
{"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": "\n// BLAS level 2\n// TNT arrays\n\n#include <iostream>\n#include <boost/numeric/bindings/atlas/cblas1.hpp>\n#include <boost/numeric/bindings/atlas/cblas2.hpp>\n#include <boost/numeric/bindings/traits/tnt.hpp>\n#include \"utils.h\"\n#include \"tnt_utils.h\"\n\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::cout;\nusing std::endl; \n\n#ifndef F_FORTRAN\ntypedef TNT::Array1D<double> vct_t;\ntypedef TNT::Array2D<double> matr_t;\n#else\ntypedef TNT::Fortran_Array1D<double> vct_t;\ntypedef TNT::Fortran_Array2D<double> matr_t;\n#endif \n\nint main() {\n\n  cout << endl; \n\n  vct_t vx (2);\n  atlas::set (1., vx);\n  print_v (vx, \"vx\"); \n  vct_t vy (3); \n  atlas::set (0., vy); \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  matr_t m (3, 2);\n  init_m (m, kpp (1)); \n  print_m (m, \"m\"); \n  cout << endl; \n\n  atlas::gemv (CblasNoTrans, 1.0, m, vx, 0.0, vy);\n  print_v (vy, \"m vx\"); \n\n  atlas::gemv (m, vx, vy);\n  print_v (vy, \"m vx\"); \n  cout << endl; \n\n  atlas::set (0, vx); \n  atlas::set (1, vy); \n  atlas::gemv (CblasTrans, 1.0, m, vy, 0.0, vx);\n  print_v (vx, \"m^T vy\"); \n  cout << endl; \n\n  atlas::set (1, vy); \n  atlas::gemv (CblasNoTrans, 1.0, m, vx, 1.0, vy);\n  print_v (vy, \"vy + m vx\"); \n  cout << endl; \n\n  atlas::set (1, vy); \n  atlas::gemv (CblasNoTrans, 2.0, m, vx, 0.5, vy);\n  print_v (vy, \"0.5 vy + 2.0 m vx\"); \n  cout << endl; \n\n}\n", "meta": {"hexsha": "3eb8a5ca214b92f9a17ddb60f7116606de81e073", "size": 1328, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/tnt2.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/tnt2.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/tnt2.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 20.1212121212, "max_line_length": 50, "alphanum_fraction": 0.6016566265, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5586582916000093}}
{"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": "//\n// Created by Bart\u0142omiej Boczek on 30/10/2019.\n//\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE vector\n\n#include <boost/test/unit_test.hpp>\n#include \"heap.h\"\n\ntemplate<typename T, typename cmp_class>\nvoid heap<T, cmp_class>::swap(int a, int b) {\n    T tmp = data[a];\n    data[a] = data[b];\n    data[b] = tmp;\n}\n\ntemplate<typename T, typename cmp_class>\nvoid heap<T, cmp_class>::heap_up(int idx) {\n    int parent = idx / 2;\n    if (idx == 1) return;\n    if (cmp_class::is_first_better(data[idx], data[parent])) {\n        swap(idx, parent);\n        heap_up(parent);\n    }\n}\n\ntemplate<typename T, typename cmp_class>\nvoid heap<T, cmp_class>::heap_down(int idx) {\n    int best = idx;\n    int left = idx * 2;\n    int right = left + 1;\n    if (left <= data.size()-1 && cmp_class::is_first_better(data[left], data[best]))\n        best = left;\n    if (right <= data.size()-1 && cmp_class::is_first_better(data[right], data[best]))\n        best = right;\n    if (best == idx) return;\n    else {\n        swap(best, idx);\n        heap_down(best);\n    }\n}\n\ntemplate<typename T, typename cmp_class>\nheap<T, cmp_class>::heap() {\n    data.push_back(T());\n}\n\ntemplate<typename T, typename cmp_class>\nvoid heap<T, cmp_class>::push(const T &elem) {\n    data.push_back(elem);\n    heap_up(data.size() - 1);\n}\n\ntemplate<typename T, typename cmp_class>\nvoid heap<T, cmp_class>::pop() {\n    data[1] = data.back();\n    data.pop_back();\n    heap_down(1);\n}\n\ntemplate<typename T, typename cmp_class>\nint heap<T, cmp_class>::size() {\n    return data.size() - 1;\n}\n\ntemplate<typename T, typename cmp_class>\nbool heap<T, cmp_class>::empty() {\n    return 0 == size();\n}\n\ntemplate<typename T, typename cmp_class>\nT &heap<T, cmp_class>::top() {\n    return data[1];\n}\n\nstruct cmp_int {\n    static bool is_first_better(int a, int b) { return a < b; }\n};\n\nBOOST_AUTO_TEST_CASE(test_heap_size) {\n    heap<int, cmp_int> pq;\n    pq.push(2);\n    pq.push(5);\n    pq.push(7);\n    pq.push(1);\n    pq.push(0);\n    BOOST_CHECK(pq.size() == 5);\n}\n\nBOOST_AUTO_TEST_CASE(test_heap_empty) {\n    heap<int, cmp_int> pq;\n    BOOST_CHECK(pq.empty());\n    pq.push(2);\n    BOOST_CHECK(!pq.empty());\n}\n\nBOOST_AUTO_TEST_CASE(test_heap_sort) {\n    heap<int, cmp_int> pq;\n    int ordered[] = {0,1,2,5,7};\n    pq.push(2);\n    pq.push(5);\n    pq.push(7);\n    pq.push(1);\n    pq.push(0);\n    for (int i=0; i<5; i++){\n        BOOST_CHECK(ordered[i] == pq.top());\n        pq.pop();\n    }\n}", "meta": {"hexsha": "dc30fbd8ef409eaf2736468a753ba1cd0e631ed2", "size": 2436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "heap/heap.cpp", "max_stars_repo_name": "boczekbartek/algorithms_and_data_structures_cpp", "max_stars_repo_head_hexsha": "c0c9a9cd24747c7645c0572685bd9fe34eaa02c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "heap/heap.cpp", "max_issues_repo_name": "boczekbartek/algorithms_and_data_structures_cpp", "max_issues_repo_head_hexsha": "c0c9a9cd24747c7645c0572685bd9fe34eaa02c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "heap/heap.cpp", "max_forks_repo_name": "boczekbartek/algorithms_and_data_structures_cpp", "max_forks_repo_head_hexsha": "c0c9a9cd24747c7645c0572685bd9fe34eaa02c6", "max_forks_repo_licenses": ["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.3486238532, "max_line_length": 86, "alphanum_fraction": 0.6153530378, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7577943822145997, "lm_q1q2_score": 0.5586143144436525}}
{"text": "/*******\nedit_distance: STL and Boost compatible edit distance functions for C++\n\nCopyright (c) 2013 Erik Erlandson\n\nAuthor:  Erik Erlandson <erikerlandson@yahoo.com>\n\nDistributed under the Boost Software License, Version 1.0.\nSee accompanying file LICENSE or copy at\nhttp://www.boost.org/LICENSE_1_0.txt\n*******/\n\n#include <iostream>\n\n// get the edit_distance() function\n#include <boost/algorithm/sequence/edit_distance.hpp>\nusing boost::algorithm::sequence::edit_distance;\nusing namespace boost::algorithm::sequence::parameter;\n\n\n// define a custom cost function where insertion or deletion of space costs nothing\nstruct cost_free_space {\n    // edit_distance uses cost_type to store cost values internally\n    // you can define it smaller to save space, or define it as\n    // floating point to support non-integer costs, etc.\n\n    // cost_type is inferred from the return values of cost functions if not defined explicitly\n    typedef unsigned cost_type;\n\n    // inserting or deleting a space is free:\n    unsigned insertion(char c) const { return (c == ' ') ? 0 : 1; }\n    unsigned deletion(char c) const { return (c == ' ') ? 0 : 1; }\n\n    // replacing one char with another costs 1\n    // (equal elements always incur zero cost)\n    unsigned substitution(char c, char d) const { return 1; }\n\n    // Defining substitution() is optional if substitution is compile-time disabled (the default).\n    // To enable, pass the optional _substitution=boost::true_type(), or _substitution=<bool-value>\n};\n\nint main(int argc, char** argv) {\n    char const* str1 = \" so   many spaces     \";\n    char const* str2 = \"    so many   spaces \";\n\n    // with custom \"free space\" cost function, the distance should be zero:\n    // here we also enable substitution\n    unsigned dist = edit_distance(str1, str2, _cost = cost_free_space(), _substitution = true);\n    std::cout << \"The edit distance between \\\"\" << str1 << \"\\\" and \\\"\" << str2 << \"\\\" = \" << dist << \"\\n\";    \n\n    return 0;\n}\n", "meta": {"hexsha": "e7fbfc9c56ba9ee4f3c91e2075df648e80395675", "size": 1974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/edit_distance_cost_example.cpp", "max_stars_repo_name": "libkeiser/edit_distance", "max_stars_repo_head_hexsha": "9a6b3bd2b0b52e503960834da3599bee0dee868d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-10-22T05:25:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T14:03:12.000Z", "max_issues_repo_path": "example/edit_distance_cost_example.cpp", "max_issues_repo_name": "libkeiser/edit_distance", "max_issues_repo_head_hexsha": "9a6b3bd2b0b52e503960834da3599bee0dee868d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-01-23T20:26:59.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-23T20:26:59.000Z", "max_forks_repo_path": "example/edit_distance_cost_example.cpp", "max_forks_repo_name": "libkeiser/edit_distance", "max_forks_repo_head_hexsha": "9a6b3bd2b0b52e503960834da3599bee0dee868d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-27T04:38:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-27T04:38:41.000Z", "avg_line_length": 37.2452830189, "max_line_length": 110, "alphanum_fraction": 0.6930091185, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5586143107549641}}
{"text": "//\r\n// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n\r\n#include <OpenTissue/core/math/math_basic_types.h>\r\n#include <OpenTissue/collision/gjk/gjk_simplex.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <OpenTissue/utility/utility_push_boost_filter.h>\r\n#include <boost/test/auto_unit_test.hpp>\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\r\n\r\n#include <cmath>\r\n\r\nusing namespace OpenTissue;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_collision_gjk_simplex);\r\n\r\nBOOST_AUTO_TEST_CASE(simplex_testing)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n  typedef math_types::vector3_type                         vector3_type;\r\n  typedef math_types::real_type                            real_type;\r\n\r\n  typedef OpenTissue::gjk::Simplex<vector3_type>  simplex_type;\r\n\r\n  vector3_type const not_in_simplex = vector3_type(1.5, 5.0, 1.0);\r\n\r\n\r\n  simplex_type S;\r\n\r\n  // Vertify that simplex have been initialized correctly as being empty and ``zeroed''\r\n  BOOST_CHECK( S.m_bitmask == 0u );\r\n  for(size_t i=0u; i<4; ++i)\r\n  {\r\n    BOOST_CHECK( S.m_w[0] == 0.0 );\r\n    for(size_t j=0u; j<3; ++j)\r\n    {\r\n      BOOST_CHECK( S.m_v[i](j) == 0.0 );\r\n      BOOST_CHECK( S.m_a[i](j) == 0.0 );\r\n      BOOST_CHECK( S.m_b[i](j) == 0.0 );\r\n    }\r\n  }\r\n\r\n  // Vertify how different query methods behave on an empty Simplex\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( not_in_simplex, S ) );\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_full_simplex(S) );\r\n\r\n  BOOST_CHECK( OpenTissue::gjk::dimension(S) == 0u );\r\n\r\n  int bit_A    = 0;\r\n  size_t idx_A = 0;\r\n  BOOST_CHECK_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A ), std::invalid_argument );\r\n\r\n  int bit_B    = 0;\r\n  size_t idx_B = 0;\r\n  BOOST_CHECK_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B ), std::invalid_argument );\r\n\r\n  int bit_C    = 0;\r\n  size_t idx_C = 0;\r\n  BOOST_CHECK_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ), std::invalid_argument );\r\n\r\n  // Next try to insert one simplex vertex into the simplex\r\n\r\n  vector3_type const p1 = vector3_type(1.0, 0.0, 0.0);\r\n  vector3_type const a1 = vector3_type(1.0, 1.0, 0.0);\r\n  vector3_type const b1 = vector3_type(1.0, 0.0, 1.0);\r\n\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::add_point_to_simplex( p1, a1, b1, S ) );\r\n\r\n  // Verify how differnt query method works on a 1-simplex\r\n  BOOST_CHECK( !OpenTissue::gjk::is_full_simplex(S) );\r\n  BOOST_CHECK( OpenTissue::gjk::dimension(S) == 1u );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A ) );\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  BOOST_CHECK_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B ), std::logic_error );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  bit_C  = 0xFFFF;\r\n  idx_C  = 0xFFFF;\r\n  BOOST_CHECK_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ), std::logic_error );\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( not_in_simplex, S ) );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p1, S )             );\r\n\r\n  // Next try to insert one more simplex vertex into the simplex\r\n\r\n  vector3_type const p2 = vector3_type(2.0, 0.5, 1.0);\r\n  vector3_type const a2 = vector3_type(2.0, 1.0, 7.0);\r\n  vector3_type const b2 = vector3_type(2.0, 0.5, 1.0);\r\n\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::add_point_to_simplex( p2, a2, b2, S ) );\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_full_simplex(S) );\r\n  BOOST_CHECK( OpenTissue::gjk::dimension(S) == 2u );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A ) );\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B ) );\r\n\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  BOOST_CHECK( bit_B == 2 );\r\n  BOOST_CHECK( idx_B == 1 );\r\n  BOOST_CHECK( S.m_v[idx_B] == p2 );\r\n  BOOST_CHECK( S.m_a[idx_B] == a2 );\r\n  BOOST_CHECK( S.m_b[idx_B] == b2 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  bit_C  = 0xFFFF;\r\n  idx_C  = 0xFFFF;\r\n  BOOST_CHECK_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ), std::logic_error );\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( not_in_simplex, S ) );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p1, S )             );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p2, S )             );\r\n\r\n\r\n  // Insert one more simplex vertex\r\n\r\n  vector3_type const p3 = vector3_type(2.3, 7.5, 1.2);\r\n  vector3_type const a3 = vector3_type(2.1, 1.1, 2.3);\r\n  vector3_type const b3 = vector3_type(2.2, 2.5, 0.1);\r\n\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::add_point_to_simplex( p3, a3, b3, S ) );\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_full_simplex(S) );\r\n  BOOST_CHECK( OpenTissue::gjk::dimension(S) == 3u );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A ) );\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B ) );\r\n\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  BOOST_CHECK( bit_B == 2 );\r\n  BOOST_CHECK( idx_B == 1 );\r\n  BOOST_CHECK( S.m_v[idx_B] == p2 );\r\n  BOOST_CHECK( S.m_a[idx_B] == a2 );\r\n  BOOST_CHECK( S.m_b[idx_B] == b2 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  bit_C  = 0xFFFF;\r\n  idx_C  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ) );\r\n\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  BOOST_CHECK( bit_B == 2 );\r\n  BOOST_CHECK( idx_B == 1 );\r\n  BOOST_CHECK( S.m_v[idx_B] == p2 );\r\n  BOOST_CHECK( S.m_a[idx_B] == a2 );\r\n  BOOST_CHECK( S.m_b[idx_B] == b2 );\r\n\r\n  BOOST_CHECK( bit_C == 4 );\r\n  BOOST_CHECK( idx_C == 2 );\r\n  BOOST_CHECK( S.m_v[idx_C] == p3 );\r\n  BOOST_CHECK( S.m_a[idx_C] == a3 );\r\n  BOOST_CHECK( S.m_b[idx_C] == b3 );\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( not_in_simplex, S ) );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p1, S )             );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p2, S )             );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p3, S )             );\r\n\r\n\r\n  // Insert one more vertex then we have a full simplex\r\n\r\n  vector3_type const p4 = vector3_type(1.3, 1.5, 1.2);\r\n  vector3_type const a4 = vector3_type(1.1, 1.1, 1.3);\r\n  vector3_type const b4 = vector3_type(1.2, 1.5, 1.1);\r\n\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::add_point_to_simplex( p4, a4, b4, S ) );\r\n\r\n  BOOST_CHECK( OpenTissue::gjk::is_full_simplex(S) );\r\n  BOOST_CHECK( OpenTissue::gjk::dimension(S) == 4u );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A ) );\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B ) );\r\n\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  BOOST_CHECK( bit_B == 2 );\r\n  BOOST_CHECK( idx_B == 1 );\r\n  BOOST_CHECK( S.m_v[idx_B] == p2 );\r\n  BOOST_CHECK( S.m_a[idx_B] == a2 );\r\n  BOOST_CHECK( S.m_b[idx_B] == b2 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  bit_C  = 0xFFFF;\r\n  idx_C  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ) );\r\n\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  BOOST_CHECK( bit_B == 2 );\r\n  BOOST_CHECK( idx_B == 1 );\r\n  BOOST_CHECK( S.m_v[idx_B] == p2 );\r\n  BOOST_CHECK( S.m_a[idx_B] == a2 );\r\n  BOOST_CHECK( S.m_b[idx_B] == b2 );\r\n\r\n  BOOST_CHECK( bit_C == 4 );\r\n  BOOST_CHECK( idx_C == 2 );\r\n  BOOST_CHECK( S.m_v[idx_C] == p3 );\r\n  BOOST_CHECK( S.m_a[idx_C] == a3 );\r\n  BOOST_CHECK( S.m_b[idx_C] == b3 );\r\n\r\n  BOOST_CHECK( S.m_v[3] == p4 );\r\n  BOOST_CHECK( S.m_a[3] == a4 );\r\n  BOOST_CHECK( S.m_b[3] == b4 );\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( not_in_simplex, S ) );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p1, S )             );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p2, S )             );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p3, S )             );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p4, S )             );\r\n\r\n  // Test what happens if we try to insert five vertices into the simplex\r\n\r\n  vector3_type const p5 = vector3_type(2.3, 2.5, 2.2);\r\n  vector3_type const a5 = vector3_type(2.1, 2.1, 2.3);\r\n  vector3_type const b5 = vector3_type(2.2, 2.5, 2.1);\r\n\r\n  BOOST_CHECK_THROW( OpenTissue::gjk::add_point_to_simplex( p5, a5, b5, S ), std::logic_error );\r\n\r\n  // Now let us erase one of the simplex vertices\r\n\r\n  S.m_bitmask = S.m_bitmask & ~bit_B;\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_full_simplex(S) );\r\n  BOOST_CHECK( OpenTissue::gjk::dimension(S) == 3u );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A ) );\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B ) );\r\n\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  BOOST_CHECK( bit_B == 4 );\r\n  BOOST_CHECK( idx_B == 2 );\r\n  BOOST_CHECK( S.m_v[idx_B] == p3 );\r\n  BOOST_CHECK( S.m_a[idx_B] == a3 );\r\n  BOOST_CHECK( S.m_b[idx_B] == b3 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  bit_C  = 0xFFFF;\r\n  idx_C  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ) );\r\n\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  BOOST_CHECK( bit_B == 4 );\r\n  BOOST_CHECK( idx_B == 2 );\r\n  BOOST_CHECK( S.m_v[idx_B] == p3 );\r\n  BOOST_CHECK( S.m_a[idx_B] == a3 );\r\n  BOOST_CHECK( S.m_b[idx_B] == b3 );\r\n\r\n  BOOST_CHECK( bit_C == 8 );\r\n  BOOST_CHECK( idx_C == 3 );\r\n  BOOST_CHECK( S.m_v[idx_C] == p4 );\r\n  BOOST_CHECK( S.m_a[idx_C] == a4 );\r\n  BOOST_CHECK( S.m_b[idx_C] == b4 );\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( not_in_simplex, S ) );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p1, S )             );\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( p2, S )             );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p3, S )             );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p4, S )             );\r\n\r\n  // Let us erase one more simplex\r\n\r\n  S.m_bitmask = S.m_bitmask & ~bit_B;\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_full_simplex(S) );\r\n  BOOST_CHECK( OpenTissue::gjk::dimension(S) == 2u );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A ) );\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B ) );\r\n\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  BOOST_CHECK( bit_B == 8 );\r\n  BOOST_CHECK( idx_B == 3 );\r\n  BOOST_CHECK( S.m_v[idx_B] == p4 );\r\n  BOOST_CHECK( S.m_a[idx_B] == a4 );\r\n  BOOST_CHECK( S.m_b[idx_B] == b4 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  bit_C  = 0xFFFF;\r\n  idx_C  = 0xFFFF;\r\n  BOOST_CHECK_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ), std::logic_error );\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( not_in_simplex, S ) );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p1, S )             );\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( p2, S )             );\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( p3, S )             );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p4, S )             );\r\n\r\n\r\n  // Insert a new simplex vertex\r\n\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::add_point_to_simplex( p5, a5, b5, S ) );\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_full_simplex(S) );\r\n  BOOST_CHECK( OpenTissue::gjk::dimension(S) == 3u );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A ) );\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B ) );\r\n\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  BOOST_CHECK( bit_B == 2 );\r\n  BOOST_CHECK( idx_B == 1 );\r\n  BOOST_CHECK( S.m_v[idx_B] == p5 );\r\n  BOOST_CHECK( S.m_a[idx_B] == a5 );\r\n  BOOST_CHECK( S.m_b[idx_B] == b5 );\r\n\r\n  bit_A  = 0xFFFF;\r\n  idx_A  = 0xFFFF;\r\n  bit_B  = 0xFFFF;\r\n  idx_B  = 0xFFFF;\r\n  bit_C  = 0xFFFF;\r\n  idx_C  = 0xFFFF;\r\n  BOOST_CHECK_NO_THROW( OpenTissue::gjk::get_used_indices( S.m_bitmask, idx_A, bit_A, idx_B, bit_B, idx_C, bit_C ) );\r\n\r\n  BOOST_CHECK( bit_A == 1 );\r\n  BOOST_CHECK( idx_A == 0 );\r\n  BOOST_CHECK( S.m_v[idx_A] == p1 );\r\n  BOOST_CHECK( S.m_a[idx_A] == a1 );\r\n  BOOST_CHECK( S.m_b[idx_A] == b1 );\r\n\r\n  BOOST_CHECK( bit_B == 2 );\r\n  BOOST_CHECK( idx_B == 1 );\r\n  BOOST_CHECK( S.m_v[idx_B] == p5 );\r\n  BOOST_CHECK( S.m_a[idx_B] == a5 );\r\n  BOOST_CHECK( S.m_b[idx_B] == b5 );\r\n\r\n  BOOST_CHECK( bit_C == 8 );\r\n  BOOST_CHECK( idx_C == 3 );\r\n  BOOST_CHECK( S.m_v[idx_C] == p4 );\r\n  BOOST_CHECK( S.m_a[idx_C] == a4 );\r\n  BOOST_CHECK( S.m_b[idx_C] == b4 );\r\n\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( not_in_simplex, S ) );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p1, S )             );\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( p2, S )             );\r\n  BOOST_CHECK( !OpenTissue::gjk::is_point_in_simplex( p3, S )             );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p4, S )             );\r\n  BOOST_CHECK(  OpenTissue::gjk::is_point_in_simplex( p5, S )             );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "f33cd228f14b38302a54387086b6c2311f749e9f", "size": 16980, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/collision/gjk/simplex/src/unit_simplex.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/collision/gjk/simplex/src/unit_simplex.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/collision/gjk/simplex/src/unit_simplex.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 34.2338709677, "max_line_length": 138, "alphanum_fraction": 0.6313309776, "num_tokens": 5865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.5586143056920686}}
{"text": "#include <iostream>\r\n#include <boost/math/common_factor_rt.hpp>\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\nint main() {\r\n\tint a, b;\r\n\twhile (cin >> a >> b) {\r\n\t\tint Ngcd = gcd(a, b);\r\n\t\tint Nlcm = lcm(a, b);\r\n\t\tcout << Ngcd << \" \" << Nlcm << endl;\r\n\t}\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "3de5f295a62e83b64369788977fcc127dea55acf", "size": 280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AIZU ONLINE JUDGE/0005.cpp", "max_stars_repo_name": "vow256/codes", "max_stars_repo_head_hexsha": "8ae972132b77ad9813328df7801df685ea87f9f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AIZU ONLINE JUDGE/0005.cpp", "max_issues_repo_name": "vow256/codes", "max_issues_repo_head_hexsha": "8ae972132b77ad9813328df7801df685ea87f9f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AIZU ONLINE JUDGE/0005.cpp", "max_forks_repo_name": "vow256/codes", "max_forks_repo_head_hexsha": "8ae972132b77ad9813328df7801df685ea87f9f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6666666667, "max_line_length": 43, "alphanum_fraction": 0.5678571429, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5586053529630445}}
{"text": "// Copyright 2011-2012 Renato Tegon Forti\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// -----------------------------------------------------------------------------\n// This example shows how implement a work quee (thread pool) to work with\n// Boost.Application using Boost.Asio.\n//\n// The result will be printed on CTRL-C (Stop) signal\n// -----------------------------------------------------------------------------\n\n#define BOOST_ALL_DYN_LINK\n#define BOOST_LIB_DIAGNOSTIC\n\n#include <boost/asio.hpp>\n#include <boost/thread.hpp>\n#include <boost/application.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/bind.hpp>\n\n#include <iostream>\n#include <math.h>\n\n#include \"work_queue.hpp\"\n\nusing namespace std;\nusing namespace boost;\n\n// worker class that calculate gaussian blur\n// http://en.wikipedia.org/wiki/Gaussian_blur\ntemplate< int kernelRadius = 3> \nstruct gaussian_blur\n{\n   typedef boost::function< void (vector< vector<double> >) > callback;\n\n   gaussian_blur(const callback& cb)\n      : callback_(cb)\n   {\n   }\n\n   void operator()()\n   {\n      boost::timer::cpu_timer timer;\n\n      kernel2d_ = produce_gaussian_kernel(kernelRadius);\n      \n      boost::timer::cpu_times const elapsed_times(timer.elapsed());\n\n      std::cout \n         << \"gaussian_blur takes:\" \n         <<  format(elapsed_times, 9) \n         << \", for size: \" \n         << kernelRadius \n         << std::endl;\n\n      callback_(kernel2d_);\n   }\n\nprotected:\n\n   double gaussian (double x, double mu, double sigma)\n   {\n      return exp( -(((x-mu)/(sigma))*((x-mu)/(sigma)))/2.0 );\n   }\n\n   vector< vector<double> > produce_gaussian_kernel (int internalKernelRadius) \n   {\n      // get kernel matrix\n      vector< vector<double> > kernel2d ( 2*internalKernelRadius+1, vector<double>(2*internalKernelRadius+1) );\n\n      // determine sigma\n      double sigma = internalKernelRadius/2.;\n\n      // fill values\n      double sum = 0;\n      for (int row = 0; row < kernel2d.size(); row++)\n      {\n         for (int col = 0; col < kernel2d[row].size(); col++) \n         {\n            kernel2d[row][col] = gaussian(row, internalKernelRadius, sigma) * gaussian(col, internalKernelRadius, sigma);\n            sum += kernel2d[row][col];\n         }\n      }\n\n      // normalize kernel, or the image becomes dark \n      for (int row = 0; row < kernel2d.size(); row++)\n         for (int col = 0; col < kernel2d[row].size(); col++)\n            kernel2d[row][col] /= sum;\n\n      return kernel2d;\n   }\n\nprivate:\n\n   callback callback_;\n   vector< vector<double> > kernel2d_;\n};\n\n// application class\nclass myapp : work_queue<0> \n{\npublic: \n\n   myapp(application::context& context)\n      : context_(context)\n   {\n   }\n   \n   void add_result(vector< vector<double> > kernel2d)\n   {\n      boost::lock_guard<boost::mutex> lock(mutex_);\n\n      task_count_++;\n\n      result_.push_back(kernel2d);\n\n      if(task_count_== 3)\n      {\n         cout << \"all tasks are completed, waiting ctrl-c to display the results...\" << endl;\n      }\n   }\n\n   int operator()()\n   {\n      // your application logic here!\n      task_count_ = 0;\n\n      //our tasks\n      add_task(gaussian_blur<3>( boost::bind( &myapp::add_result, this, _1 ))); \n      add_task(gaussian_blur<6>( boost::bind( &myapp::add_result, this, _1 ))); \n      add_task(gaussian_blur<9>( boost::bind( &myapp::add_result, this, _1 ))); \n     \n      context_.find<application::wait_for_termination_request>()->wait();\n\n      return 0;\n   }\n   \n   bool stop()\n   {\n      std::cout << \"Result...\" << std::endl;\n\n      for(int i = 0; i < result_.size(); ++i)\n      {\n         cout << i << \" : -----------------------\" << std::endl;\n\n         vector< vector<double> > & kernel2d = result_[i];\n\n         for (int row = 0; row < kernel2d.size(); row++) \n         {\n            for (int col = 0; col < kernel2d[row].size(); col++)\n            {\n               cout << setprecision(5) << fixed << kernel2d[row][col] << \" \";\n            }\n            cout << endl;\n         }\n      }\n\n      return 1;\n   }\n\nprivate:\n\n   boost::mutex mutex_;  \n   vector< vector< vector<double> > > result_;\n\n   int task_count_;\n\n   application::context& context_;\n   \n}; // myapp \n\nint main(int argc, char *argv[])\n{\n   BOOST_APPLICATION_FEATURE_SELECT\n\n   application::context app_context;\n   myapp app(app_context);\n   \n   application::handler<>::callback cb \n      = boost::bind(&myapp::stop, &app);\n\n   app_context.insert<application::termination_handler>(\n      make_shared<application::termination_handler_default_behaviour>(cb));\n      \n   return application::launch<application::common>(app, app_context);\n}\n\n", "meta": {"hexsha": "18a91e574d9c8fb17c0961070c847d4a508bd1f4", "size": 4706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/Boost.Application/example/work_queue/work_queue.cpp", "max_stars_repo_name": "hbccdf/network-core", "max_stars_repo_head_hexsha": "37cbf03829bffd9c0903a1e755ce1f96f46e3dfa", "max_stars_repo_licenses": ["MIT"], "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.Application/example/work_queue/work_queue.cpp", "max_issues_repo_name": "hbccdf/network-core", "max_issues_repo_head_hexsha": "37cbf03829bffd9c0903a1e755ce1f96f46e3dfa", "max_issues_repo_licenses": ["MIT"], "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.Application/example/work_queue/work_queue.cpp", "max_forks_repo_name": "hbccdf/network-core", "max_forks_repo_head_hexsha": "37cbf03829bffd9c0903a1e755ce1f96f46e3dfa", "max_forks_repo_licenses": ["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.8994708995, "max_line_length": 121, "alphanum_fraction": 0.5830854229, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5585934727680051}}
{"text": "#include <benchmark/benchmark.h>\n#include <Eigen/Dense>\n\ntemplate <typename T> void BM_GEMM(benchmark::State& state) {\n  // Perform setup here\n  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> A = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Random(state.range(0), state.range(0));\n  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> B = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Random(state.range(0), state.range(0));\n  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> C = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Random(state.range(0), state.range(0));\n  for (auto _ : state) {\n    // This code gets timed\n    C = A*B;\n    benchmark::DoNotOptimize(C);\n  }\n}\n\nint main(int argc, char** argv) {\n\n  //Small size benchmarks (8 -> 256)\n  benchmark::RegisterBenchmark(\"GEMM_double\", BM_GEMM<double>)\n\t->RangeMultiplier(2)->Range(8, 256);\n\n  benchmark::Initialize(&argc, argv);\n  benchmark::RunSpecifiedBenchmarks();\n}\n", "meta": {"hexsha": "b1ea3e046151e4c0235d3be4236a1bb75f724226", "size": 937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark_eigen.cpp", "max_stars_repo_name": "pdrocaldeira/libfsmc", "max_stars_repo_head_hexsha": "9d828666c2dab8f185846242e314b08800043ecf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark_eigen.cpp", "max_issues_repo_name": "pdrocaldeira/libfsmc", "max_issues_repo_head_hexsha": "9d828666c2dab8f185846242e314b08800043ecf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2020-11-11T14:20:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T20:26:43.000Z", "max_forks_repo_path": "benchmark_eigen.cpp", "max_forks_repo_name": "pdrocaldeira/libfsmc", "max_forks_repo_head_hexsha": "9d828666c2dab8f185846242e314b08800043ecf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-12T12:41:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-12T12:41:35.000Z", "avg_line_length": 37.48, "max_line_length": 144, "alphanum_fraction": 0.6862326574, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5585934680011525}}
{"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": "// This file copyright 2021 by J\u00e9r\u00f4me Pl\u00fbt <plut.jerome@gmail.org>,\n// licensed under the MIT license <https://opensource.org/licenses/MIT>.\n#include <Eigen/Dense>\n#include <stdlib.h>\n#define BOOST_BIND_GLOBAL_PLACEHOLDERS\n#include <igl/copyleft/cgal/mesh_boolean.h>\n#include <igl/copyleft/cgal/minkowski_sum.h>\n#include <igl/copyleft/cgal/piecewise_constant_winding_number.h>\n#include <igl/offset_surface.h>\n#include <igl/decimate.h>\n#include <igl/loop.h>\n#include <igl/centroid.h>\n#include <igl/swept_volume.h>\n// #include <igl/embree/reorient_facets_raycast.h>\n#include <igl/copyleft/cgal/intersect_with_half_space.h>\n#include <boost/bind/bind.hpp>\n\nusing namespace boost::placeholders;\nusing namespace Eigen;\n\ntypedef Matrix<double,Dynamic,3> VertexMatrix;\ntypedef Matrix<int,Dynamic,3> FaceMatrix;\ntypedef double vec3d[3];\ntypedef double mat3d[3][3];\n\n// typedef Matrix<double, Dynamic, 3, RowMajor> vertices_t;\n// typedef Matrix<int, Dynamic, 3, RowMajor> faces_t;\n\n// Eigen::IOFormat CommaInitFmt(32, DontAlignCols, \", \", \", \", \"\", \"\", \" << \", \";\");\n\nstruct Mesh {/*\u00ab\u00ab*/\n\tMatrixXd v;\n\tMatrixXi f;\n//   Matrix<double,Dynamic,3> v;\n//   Matrix<int,Dynamic,3> f;\n  Mesh(): v(), f() { }\n  Mesh(int nv, int nf, const double *mv, const int *mf, int d = 3):\n\t\t\tv(nv, 3), f(nf, d) {\n    for(int i = 0; i < nv; i++) {\n      for(int j = 0; j < 3; j++) {\n\t\t\t\tv(i, j) = mv[3*i+j];\n      }\n    }\n    for(int i = 0; i < nf; i++) {\n      for(int j = 0; j < d; j++) {\n\tf(i, j) = mf[d*i+j]-1;\n      }\n    };\n  };\n};/*\u00bb\u00bb*/\n\nvoid to_jl(Mesh m, int *nv, int *nf, double **mv, int **mf) {/*\u00ab\u00ab*/\n  // sets mv to zero in case of failure\n  *nv = m.v.rows();\n  *nf = m.f.rows();\n  *mv = (double *) malloc(3*(*nv)*sizeof(double));\n  if(*mv == 0) {\n    return;\n  }\n  *mf = (int *) malloc(3* (*nf)*sizeof(int));\n  if(*mf == 0) {\n    free(*mv);\n    *mv = 0;\n    return;\n  }\n  for(int i = 0; i < *nv; i++) {\n    for(int j = 0; j < 3; j++) {\n      (*mv)[3*i+j] = m.v(i, j);\n    }\n  }\n  for(int i = 0; i < *nf; i++) {\n    for(int j = 0; j < 3; j++) {\n      (*mf)[3*i+j] = 1 + m.f(i,j);\n    }\n  }\n}/*\u00bb\u00bb*/\n\nextern \"C\" {\nint mesh_boolean(/*\u00ab\u00ab*/\n  int op,\n  int nv1, int nf1, const double *mv1, const int *mf1,\n  int nv2, int nf2, const double *mv2, const int *mf2,\n  int *nv3, int *nf3, double **mv3, int **mf3, int **index) {\n\n\n  Mesh m1(nv1, nf1, mv1, mf1),\n       m2(nv2, nf2, mv2, mf2),\n       m3;\n  VectorXi j;\n  igl::copyleft::cgal::mesh_boolean(m1.v,m1.f,m2.v,m2.f,\n  igl::MeshBooleanType(op), m3.v,m3.f, j);\n\n  *index = (int *) malloc(m3.f.rows()*sizeof(int));\n  if (*index == 0) {\n    return -1;\n  }\n  for(int i = 0; i < m3.f.rows(); i++) {\n    (*index)[i] = j(i)+1;\n  }\n  to_jl(m3, nv3, nf3, mv3, mf3);\n  if(*mv3 == 0) {\n    free(*index);\n    return -1;\n  }\n  return 0;\n}/*\u00bb\u00bb*/\nint minkowski_sum(/*\u00ab\u00ab*/\n  int nv1, int nf1, const double *mv1, const int *mf1,\n  int nv2, int nf2, const double *mv2, const int *mf2, int dim2,\n  int *nv3, int *nf3, double **mv3, int **mf3, int **index) {\n\n  Mesh m1(nv1, nf1, mv1, mf1),\n       m2(nv2, nf2, mv2, mf2, dim2),\n       m3;\n  MatrixXi j;\n// \tstd::cout << \"mesh m1: \"\n// \t\t<< m1.v.rows() << \" vertices:\\n\" << m1.v << \"\\n\"\n// \t\t<< m1.f.rows() << \" faces:\\n\" << m1.f << \"\\n\\n\";\n// \tstd::cout << \"mesh m2: \"\n// \t\t<< m2.v.rows() << \" vertices:\\n\" << m2.v << \"\\n\"\n// \t\t<< m2.f.rows() << \" faces:\\n\" << m2.f << \"\\n\\n\";\n  igl::copyleft::cgal::minkowski_sum(m1.v,m1.f,m2.v,m2.f, true,\n  \tm3.v,m3.f, j);\n// \tstd::cout << \"mesh m3: \"\n// \t\t<< m3.v.rows() << \" vertices:\\n\" << m3.v << \"\\n\"\n// \t\t<< m3.f.rows() << \" faces:\\n\" << m3.f << \"\\n\\n\";\n// \tstd::cout << \"j has \" << j.rows() << \" rows:\\n\"  << j << \"\\n\";\n\n\tint n3 = m3.f.rows();\n  *index = (int *) malloc(2*n3*sizeof(int));\n  if (*index == 0) {\n    return -1;\n  }\n  for(int i = 0; i < n3; i++) {\n    (*index)[i] = j(i,0)+1;\n\t\t(*index)[i+n3] = j(i,1)+1;\n  }\n  to_jl(m3, nv3, nf3, mv3, mf3);\n  if(*mv3 == 0) {\n    free(*index);\n    return -1;\n  }\n  return 0;\n}/*\u00bb\u00bb*/\n\nint mesh_is_pwn(int nv, int nf, const double *mv, const int *mf) {\n  Mesh m(nv, nf, mv, mf);\n  return (int)igl::copyleft::cgal::piecewise_constant_winding_number(m.v, m.f);\n}\n\nint offset_surface(/*\u00ab\u00ab*/\n\tint nv, int nf, const double *mv, const int *mf,\n\tdouble level, int grid,\n\tint *nvout, int *nfout, double **mvout, int **mfout) {\n\n\tMesh m(nv, nf, mv, mf), mout;\n\tMatrixXd GV;\n\tMatrixXi side;\n\tMatrixXd S;\n\n\tigl::offset_surface(m.v, m.f, level, grid,\n\t\tigl::SignedDistanceType::SIGNED_DISTANCE_TYPE_DEFAULT,\n\t\tmout.v, mout.f, GV, side, S);\n\n\tto_jl(mout, nvout, nfout, mvout, mfout);\n\tif(*mvout == 0) {\n\t\treturn -1;\n\t}\n\treturn 0;\n}/*\u00bb\u00bb*/\nint decimate(int nv, int nf, const double *mv, const int *mf, int faces,/*\u00ab\u00ab*/\n\tint *nvout, int *nfout, double **mvout, int **mfout, int **index) {\n\tMesh m(nv, nf, mv, mf), mout;\n\tVectorXi fidx, vidx;\n\tigl::decimate(m.v, m.f, faces,\n\t\tmout.v, mout.f, fidx, vidx);\n\n  *index = (int *) malloc(fidx.rows()*sizeof(int));\n  if (*index == 0) {\n    return -1;\n  }\n  for(int i = 0; i < fidx.rows(); i++) {\n    (*index)[i] = fidx(i)+1;\n  }\n\tto_jl(mout, nvout, nfout, mvout, mfout);\n\tif(*mvout == 0) {\n\t\tfree(*index);\n\t\treturn -1;\n\t}\n\treturn 0;\n}/*\u00bb\u00bb*/\nint loop(int nv, int nf, const double *mv, const int *mf, int n,/*\u00ab\u00ab*/\n\tint *nvout, int *nfout, double **mvout, int **mfout) {\n\tMesh m(nv, nf, mv, mf), mout;\n\tVectorXi fidx, vidx;\n\n\tigl::loop(m.v, m.f, mout.v, mout.f, n);\n\n\tto_jl(mout, nvout, nfout, mvout, mfout);\n\treturn 0;\n}/*\u00bb\u00bb*/\n// int reorient_facets_raycast(int nv, int nf, const double *mv, const int *mf,/*\u00ab\u00ab*/\n// \tint **mfout, int **flipped) {\n// \tMesh m(nv, nf, mv, mf);\n// \tMatrixXd mfo;\n// \tVectorXi fl;\n// \n// \tigl::embree:reorient_facets_raycast(m.v, m.f, mfo, fl);\n//   *mfout = (int *) malloc(3*nf*sizeof(int));\n//   if(*mfout == 0) {\n//     return -1;\n//   }\n// \t*flipped = (int *) malloc(nf*sizeof(int));\n// \tif(*flipped == 0) {\n// \t\tfree(mfout);\n// \t\treturn -1;\n// \t}\n//   for(int i = 0; i < nf; i++) {\n//     for(int j = 0; j < 3; j++) {\n//       (*mfout)[3*i+j] = 1 + m.f(i, j);\n//     }\n// \t\t(*flipped)[i] = fl[i];\n//   }\n// \treturn 0;\n// }/*\u00bb\u00bb*/\ndouble centroid_and_volume(int nv, int nf, const double *mv, const int *mf,\n\tvec3d *c) {\n\tMesh m(nv, nf, mv, mf);\n\tVector3d cen;\n\tdouble vol;\n\n\tigl::centroid(m.v, m.f, cen, vol);\n\tstd::cout << \"centroid = \" << cen << \"\\n\";\n\t(*c)[0] = cen(0); (*c)[1] = cen(1); (*c)[2] = cen(2);\n\treturn vol;\n}\n\nint intersect_with_half_space(int nv, int nf, /*\u00ab\u00ab*/\n\tconst double *mv, const int *mf,\n\tconst vec3d *p, const vec3d *n,\n\tint *nvout, int *nfout, double **mvout, int **mfout, int **index) {\n\tMesh m(nv, nf, mv, mf), mout;\n\tVector3d vp (*p);\n\tVector3d vn (*n);\n\tVectorXi fidx;\n\n\tigl::copyleft::cgal::intersect_with_half_space(m.v, m.f, vp, vn,\n\t\tmout.v, mout.f, fidx);\n\n  *index = (int *) malloc(fidx.rows()*sizeof(int));\n  if (*index == 0) {\n    return -1;\n  }\n  for(int i = 0; i < fidx.rows(); i++) {\n    (*index)[i] = fidx(i)+1;\n  }\n\tto_jl(mout, nvout, nfout, mvout, mfout);\n\tif(*mvout == 0) {\n\t\tfree(*index);\n\t\treturn -1;\n\t}\n\treturn 0;\n}/*\u00bb\u00bb*/\nint swept_volume(int nv, int nf, const double *mv, const int *mf,\n\tvoid (*ctransform)(double, mat3d*, vec3d*),\n\tsize_t steps, size_t gridres, double isolevel,\n\tint *nvout, int *nfout, double **mvout, int **mfout) {\n\n\tMesh m(nv, nf, mv, mf), mout;\n\tstd::function<Eigen::Affine3d(const double)> f(\n\t\t[ctransform] (double t) {\n\t\tmat3d a; vec3d b;\n\t\tctransform(t, &a, &b);\n\t\tEigen::Affine3d m;\n\t\tm.linear() = Map<Matrix3d>(&a[0][0], 3, 3);\n\t\tm.translation() = Map<Vector3d>(&b[0], 3);\n\t\treturn m;\n\t});\n\tigl::swept_volume(m.v, m.f, f, steps, gridres, isolevel, mout.v, mout.f);\n\tto_jl(mout, nvout, nfout, mvout, mfout);\n\tif(*mvout == 0) {\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\n}\n\n// vim: noet ts=2 sw=2 fmr=\u00ab\u00ab,\u00bb\u00bb:\n", "meta": {"hexsha": "053cdfcb39e43c4d8e76e61a785fd36efc4153bf", "size": 7674, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "I/IGLWrap/iglwrap/iglwrap.cpp", "max_stars_repo_name": "sharanry/Yggdrasil", "max_stars_repo_head_hexsha": "d89cb4ffdc8e96ad39b6242b3574c59561c1b546", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T22:41:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T03:35:17.000Z", "max_issues_repo_path": "I/IGLWrap/iglwrap/iglwrap.cpp", "max_issues_repo_name": "sharanry/Yggdrasil", "max_issues_repo_head_hexsha": "d89cb4ffdc8e96ad39b6242b3574c59561c1b546", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2176.0, "max_issues_repo_issues_event_min_datetime": "2018-12-20T07:05:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:39:20.000Z", "max_forks_repo_path": "I/IGLWrap/iglwrap/iglwrap.cpp", "max_forks_repo_name": "sharanry/Yggdrasil", "max_forks_repo_head_hexsha": "d89cb4ffdc8e96ad39b6242b3574c59561c1b546", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 455.0, "max_forks_repo_forks_event_min_datetime": "2018-09-27T21:28:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T06:27:44.000Z", "avg_line_length": 26.4620689655, "max_line_length": 85, "alphanum_fraction": 0.5577273912, "num_tokens": 2965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.5585662009770105}}
{"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 <stdio.h>\n#include <math.h>\n#include <iostream>\n#include <Eigen/Eigen>\n\n#include \"NeuralNetwork.h\"\n\nusing namespace Eigen;\n\n/*\n * Class AffineLayer\n *\n * @desript A kind of Neural Network Layer.\n */\nNeuralNetwork::~NeuralNetwork()\n{\n  NNLayer *tmp;\n  for(NNLayer *layer = top_layer; layer != NULL; )\n    {\n      tmp = layer->getNext();\n      delete layer;\n      layer = tmp;\n    }\n}\n\nvoid NeuralNetwork::createNewLayer(int innum, int outnum, bool is_last, Matrix<float, Dynamic, Dynamic> *default_w)\n{\n  NNLayer *new_affine;\n  NNLayer *activation;\n\n  new_affine = new AffineLayer(innum, outnum, default_w);\n\n  if (is_last)\n    {\n      activation = new SoftMaxLayer();\n    }\n  else\n    {\n      activation = new ReLULayer();\n    }\n\n  new_affine->setNext(activation);\n\n  if( last_layer == NULL )\n    {\n      top_layer = new_affine;\n    }\n  else\n    {\n      last_layer->setNext(new_affine);\n    }\n\n  last_layer = activation;\n}\n\n\nvoid NeuralNetwork::printnet()\n{\n  for(NNLayer *layer = top_layer; layer != NULL; layer = layer->getNext())\n    {\n      layer->printnet();\n    };\n}\n\n\nvoid NeuralNetwork::print_layers()\n{\n  for(NNLayer *layer = top_layer; layer != NULL; layer = layer->getNext())\n    {\n      std::cout << layer << \" --> \";\n    };\n  std::cout << \"NULL\" << std::endl;\n}\n\n\nMatrix<float, Dynamic, Dynamic> NeuralNetwork::forward(Matrix<float, Dynamic, Dynamic> input)\n{\n  output = top_layer->forward(input);\n  return output;\n}\n\nfloat NeuralNetwork::backward(float train_ratio, Matrix<float, Dynamic, Dynamic> m)\n{\n  float ret = ((LastActivation *)last_layer)->loss(m);\n  last_layer->backward(train_ratio, m);\n  return ret;\n}\n\n", "meta": {"hexsha": "76fb533bad4bfa6d6121b1321005543aa777b30a", "size": 1638, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "eigen_test/NeuralNetwork.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/NeuralNetwork.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/NeuralNetwork.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": 18.404494382, "max_line_length": 115, "alphanum_fraction": 0.6391941392, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.6442250996557035, "lm_q1q2_score": 0.558566194336815}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <ayla/geometry/vector.hpp>\n\n#include <glm/gtc/epsilon.hpp>\n\nBOOST_AUTO_TEST_SUITE( ayla )\nBOOST_AUTO_TEST_SUITE( _float )\n\nBOOST_AUTO_TEST_CASE( less_than_zero ) {\n\tconst Float a(0);\n\tBOOST_CHECK(!(a < 0.0f));\n\tBOOST_CHECK(a <= 0.0f);\n}\n\nBOOST_AUTO_TEST_CASE(_isZero) {\n\tconst Float a(0.0f);\n\n\tBOOST_CHECK(isZero(a));\n\n\tBOOST_CHECK(isZero(std::numeric_limits<Float>::epsilon()));\n\tBOOST_CHECK(!isZero(2 * std::numeric_limits<Float>::epsilon()));\n}\n\nBOOST_AUTO_TEST_CASE(_epsilonEqual) {\n\tconst Float epsilon = std::numeric_limits<Float>::epsilon();\n\n\tconst Float a = 1.0f;\n\tconst Float b = a + epsilon;\n\t\n\tBOOST_CHECK(glm::epsilonEqual(a, b, epsilon * 2.0f));\n\tBOOST_CHECK(glm::epsilonNotEqual(a, b, epsilon));\n\n\tconst Float c = b + epsilon;\n\n\tBOOST_CHECK(glm::epsilonNotEqual(a, c, epsilon));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "12357200e8fc6cd8de39fed1df608aebf1ab9f3e", "size": 899, "ext": "cc", "lang": "C++", "max_stars_repo_path": "epoch/ayla/tests/float.cc", "max_stars_repo_name": "oprogramadorreal/vize", "max_stars_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T14:36:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T07:44:54.000Z", "max_issues_repo_path": "epoch/ayla/tests/float.cc", "max_issues_repo_name": "oprogramadorreal/vize", "max_issues_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "epoch/ayla/tests/float.cc", "max_forks_repo_name": "oprogramadorreal/vize", "max_forks_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-04-01T01:22:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T13:06:09.000Z", "avg_line_length": 21.9268292683, "max_line_length": 65, "alphanum_fraction": 0.7274749722, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5585633309550658}}
{"text": "#ifndef ARRAYHELPERS_H\n#define ARRAYHELPERS_H\n\n#include \"random_generator.hpp\"\n#include \"types.hpp\"\n\n#include <Eigen/Core>\n#include <random>\n\nnamespace Optima\n{\n\nclass ArrayHelpers {\n\npublic:\n  static Eigen::ArrayXd randomArray(const size_t dimension) {\n    auto randNum  = []() -> double {\n      return RandomGenerator::uniform<double>();\n    };\n    return Eigen::ArrayXd::NullaryExpr(dimension, 1, randNum);\n  }\n\n  static Eigen::ArrayXd uniformFromBounds(const Bounds &bounds) {\n    const Eigen::ArrayXd &lower = bounds.first;\n    const Eigen::ArrayXd &upper = bounds.second;\n    const Eigen::ArrayXd &range = upper - lower;\n    const size_t dimension = lower.size();\n    return ((randomArray(dimension) + 1) / 2) * range + lower;\n  }\n\n};\n}\n\n#endif // ARRAYHELPERS_H\n", "meta": {"hexsha": "cb288bd3222e618463007189ec6c22b6a5e8578a", "size": 769, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/array_helpers.hpp", "max_stars_repo_name": "samueljackson92/metaopt", "max_stars_repo_head_hexsha": "8d030476a20b8a2661f44f3b2355880689874b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/array_helpers.hpp", "max_issues_repo_name": "samueljackson92/metaopt", "max_issues_repo_head_hexsha": "8d030476a20b8a2661f44f3b2355880689874b96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-04-30T08:27:07.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T08:36:20.000Z", "max_forks_repo_path": "src/array_helpers.hpp", "max_forks_repo_name": "samueljackson92/metaopt", "max_forks_repo_head_hexsha": "8d030476a20b8a2661f44f3b2355880689874b96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9714285714, "max_line_length": 65, "alphanum_fraction": 0.6905071521, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.558563326270652}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013-2014 Mageswaran.D <mageswaran1989@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#include <iostream>\n#include <string>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <boost/compute/system.hpp>\n#include <boost/compute/interop/opencv/core.hpp>\n#include <boost/compute/interop/opencv/highgui.hpp>\n#include <boost/compute/utility/source.hpp>\n\n#include <boost/program_options.hpp>\n\nnamespace compute = boost::compute;\nnamespace po = boost::program_options;\n\n// Create convolution program\nconst char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE (\n    __kernel void convolution(__read_only  image2d_t  sourceImage,\n                              __write_only image2d_t  outputImage,\n                              __constant float* filter,\n                              int filterWidth)\n    {\n        const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE |\n                                  CLK_ADDRESS_CLAMP_TO_EDGE   |\n                                  CLK_FILTER_NEAREST;\n\n        // Store each work-item\u2019s unique row and column\n        int x   = get_global_id(0);\n        int y   = get_global_id(1);\n\n        // Half the width of the filter is needed for indexing\n        // memory later\n        int halfWidth = (int)(filterWidth/2);\n\n        // All accesses to images return data as four-element vector\n        // (i.e., float4).\n        float4 sum = {0.0f, 0.0f, 0.0f, 0.0f};\n\n        // Iterator for the filter\n        int filterIdx = 0;\n\n        // Each work-item iterates around its local area based on the\n        // size of the filter\n        int2 coords;  // Coordinates for accessing the image\n\n        // Iterate the filter rows\n        for(int i = -halfWidth; i <= halfWidth; i++)\n        {\n            coords.y = y + i;\n\n            // Iterate over the filter columns\n            for(int j = -halfWidth; j <= halfWidth; j++)\n            {\n                coords.x = x + j;\n\n                float4 pixel;\n\n                // Read a pixel from the image.\n                // Work on a channel\n                pixel = read_imagef(sourceImage, sampler, coords);\n                sum.x += pixel.x * filter[filterIdx++];\n                //sum.y += pixel.y * filter[filterIdx++];\n                //sum.z += pixel.z * filter[filterIdx++];\n            }\n        }\n\n         barrier(CLK_GLOBAL_MEM_FENCE);\n        // Copy the data to the output image if the\n        // work-item is in bounds\n        if(y < get_image_height(sourceImage) &&\n                x < get_image_width(sourceImage))\n        {\n            coords.x = x;\n            coords.y = y;\n\n            //Same channel is copied in all three channels\n            //write_imagef(outputImage, coords,\n                        // (float4)(sum.x,sum.x,sum.x,1.0f));\n\n            write_imagef(outputImage, coords, sum);\n        }\n    }\n);\n\n// This example shows how to read two images or use camera\n// with OpenCV, transfer the frames to the GPU,\n// and apply a convolution written in OpenCL\nint main(int argc, char *argv[])\n{\n    ///////////////////////////////////////////////////////////////////////////\n\n    // setup the command line arguments\n    po::options_description desc;\n    desc.add_options()\n            (\"help\",  \"show available options\")\n            (\"camera\", po::value<int>()->default_value(-1),\n                                 \"if not default camera, specify a camera id\")\n            (\"image\", po::value<std::string>(), \"path to image file\");\n\n    // Parse the command lines\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    //check the command line arguments\n    if(vm.count(\"help\"))\n    {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n\n    //OpenCV variables\n    cv::Mat cv_mat;\n    cv::VideoCapture cap; //OpenCV camera handle.\n\n    //Filter Variables\n    float filter[9] =  {\n                -1.0,      0.0,      1.0,\n                -2.0,      0.0,      2.0,\n                -1.0,      0.0,      1.0,\n                };\n\n    // The convolution filter is 3x3\n    int filterWidth = 3;\n\n    //OpenCL variables\n    // Get default device and setup context\n    compute::device gpu = compute::system::default_device();\n    compute::context context(gpu);\n    compute::command_queue queue(context, gpu);\n    compute::buffer dev_filter(context, sizeof(filter),\n                               compute::memory_object::read_only |\n                               compute::memory_object::copy_host_ptr,\n                               filter);\n\n    compute::program filter_program =\n            compute::program::create_with_source(source, context);\n\n    try\n    {\n        filter_program.build();\n    }\n    catch(compute::opencl_error e)\n    {\n        std::cout<<\"Build Error: \"<<std::endl\n                 <<filter_program.build_log();\n\treturn -1;\n    }\n\n    // create fliter kernel and set arguments\n    compute::kernel filter_kernel(filter_program, \"convolution\");\n\n    ///////////////////////////////////////////////////////////////////////////\n\n    //check for image paths\n    if(vm.count(\"image\"))\n    {\n        // Read image with OpenCV\n        cv_mat = cv::imread(vm[\"image\"].as<std::string>(),\n                                       CV_LOAD_IMAGE_COLOR);\n        if(!cv_mat.data){\n            std::cerr << \"Failed to load image\" << std::endl;\n            return -1;\n        }\n    }\n    else //by default use camera\n    {\n        //open camera\n        cap.open(vm[\"camera\"].as<int>());\n        // read first frame\n        cap >> cv_mat;\n        if(!cv_mat.data){\n            std::cerr << \"failed to capture frame\" << std::endl;\n            return -1;\n        }\n    }\n\n    // Convert image to BGRA (OpenCL requires 16-byte aligned data)\n    cv::cvtColor(cv_mat, cv_mat, CV_BGR2BGRA);\n\n    // Transfer image/frame data to gpu\n    compute::image2d dev_input_image =\n            compute::opencv_create_image2d_with_mat(\n                cv_mat, compute::image2d::read_write, queue\n                );\n\n    // Create output image\n    // Be sure what will be your ouput image/frame size\n    compute::image2d dev_output_image(\n                context,\n                dev_input_image.width(),\n                dev_input_image.height(),\n                dev_input_image.format(),\n                compute::image2d::write_only\n                );\n\n    filter_kernel.set_arg(0, dev_input_image);\n    filter_kernel.set_arg(1, dev_output_image);\n    filter_kernel.set_arg(2, dev_filter);\n    filter_kernel.set_arg(3, filterWidth);\n\n    // run flip kernel\n    size_t origin[2] = { 0, 0 };\n    size_t region[2] = { dev_input_image.width(),\n                         dev_input_image.height() };\n\n    ///////////////////////////////////////////////////////////////////////////\n\n    queue.enqueue_nd_range_kernel(filter_kernel, 2, origin, region, 0);\n\n    //check for image paths\n    if(vm.count(\"image\"))\n    {\n        // show host image\n        cv::imshow(\"Original Image\", cv_mat);\n\n        // show gpu image\n        compute::opencv_imshow(\"Convoluted Image\", dev_output_image, queue);\n\n        // wait and return\n        cv::waitKey(0);\n    }\n    else\n    {\n        char key = '\\0';\n        while(key != 27) //check for escape key\n        {\n            cap >> cv_mat;\n\n            // Convert image to BGRA (OpenCL requires 16-byte aligned data)\n            cv::cvtColor(cv_mat, cv_mat, CV_BGR2BGRA);\n\n            // Update the device image memory with current frame data\n            compute::opencv_copy_mat_to_image(cv_mat,\n                                              dev_input_image,queue);\n\n            // Run the kernel on the device\n            queue.enqueue_nd_range_kernel(filter_kernel, 2, origin, region, 0);\n\n            // Show host image\n            cv::imshow(\"Camera Frame\", cv_mat);\n\n            // Show GPU image\n            compute::opencv_imshow(\"Convoluted Frame\", dev_output_image, queue);\n\n            // wait\n            key = cv::waitKey(10);\n        }\n    }\n    return 0;\n}\n", "meta": {"hexsha": "4446dc9af947d054482bcacdd424257854d5d92a", "size": 8450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/opencv_convolution.cpp", "max_stars_repo_name": "roshanr95/compute", "max_stars_repo_head_hexsha": "377e509acd16af466cdb133d70e2dcd525ec1a87", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/opencv_convolution.cpp", "max_issues_repo_name": "roshanr95/compute", "max_issues_repo_head_hexsha": "377e509acd16af466cdb133d70e2dcd525ec1a87", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/opencv_convolution.cpp", "max_forks_repo_name": "roshanr95/compute", "max_forks_repo_head_hexsha": "377e509acd16af466cdb133d70e2dcd525ec1a87", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-09T15:56:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-09T15:56:37.000Z", "avg_line_length": 31.7669172932, "max_line_length": 80, "alphanum_fraction": 0.5272189349, "num_tokens": 1853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.558563326270652}}
{"text": "/**\n * @file discontinuousgalerkin1d.cc\n * @brief NPDE homework \"DiscontinuousGalerkin1D\" code\n * @author Oliver Rietmann\n * @date 22.05.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"discontinuousgalerkin1d.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\nnamespace DiscontinuousGalerkin1D {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::SparseMatrix<double> compBmat(int Ml, int Mr, double h) {\n  const int N = 2 * (Ml + Mr + 1);\n  Eigen::SparseMatrix<double> A(N, N);\n  //====================\n  // Your code goes here\n  //====================\n  return A;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\ndouble Feo(double v, double w) {\n  double result;\n  //====================\n  // Your code goes here\n  //====================\n  return result;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nSolution solveTrafficFlow() {\n  int Ml = 40;\n  int Mr = 40;\n  int N_half = Mr + Ml + 1;\n  int N = 2 * N_half;\n\n  double h = 0.05;\n  double tau = h / 3;\n  double T = 1.0;\n  unsigned int m = (unsigned int)(T / tau);\n\n\n  //====================\n  // Your code goes here\n  // Fill the following vectors\n  Eigen::VectorXd x;\n  Eigen::VectorXd u;\n  //====================\n\n  return Solution(std::move(x), std::move(u));\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace DiscontinuousGalerkin1D\n", "meta": {"hexsha": "037c07e44203cdbd6d0d023253983c3ba6ba2c14", "size": 1291, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/DiscontinuousGalerkin1D/templates/discontinuousgalerkin1d.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/DiscontinuousGalerkin1D/templates/discontinuousgalerkin1d.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/DiscontinuousGalerkin1D/templates/discontinuousgalerkin1d.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 20.8225806452, "max_line_length": 64, "alphanum_fraction": 0.5941130906, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.558563321586238}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <boost/scope_exit.hpp>\n#include <boost/program_options.hpp>\n\n#include <amgcl/backend/builtin.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/mpi/util.hpp>\n#include <amgcl/mpi/distributed_matrix.hpp>\n#include <amgcl/profiler.hpp>\n\n#include \"domain_partition.hpp\"\n\nnamespace amgcl {\n    profiler<> prof;\n}\n\nstruct renumbering {\n    const domain_partition<3> &part;\n    const std::vector<ptrdiff_t> &dom;\n\n    renumbering(\n            const domain_partition<3> &p,\n            const std::vector<ptrdiff_t> &d\n            ) : part(p), dom(d)\n    {}\n\n    ptrdiff_t operator()(ptrdiff_t i, ptrdiff_t j, ptrdiff_t k) const {\n        boost::array<ptrdiff_t, 3> p = {{i, j, k}};\n        std::pair<int,ptrdiff_t> v = part.index(p);\n        return dom[v.first] + v.second;\n    }\n};\n\nint main(int argc, char *argv[]) {\n    MPI_Init(&argc, &argv);\n    BOOST_SCOPE_EXIT(void) {\n        MPI_Finalize();\n    } BOOST_SCOPE_EXIT_END\n\n    amgcl::mpi::communicator world(MPI_COMM_WORLD);\n\n    if (world.rank == 0)\n        std::cout << \"World size: \" << world.size << std::endl;\n\n    // Read configuration from command line\n    ptrdiff_t n = 128;\n\n    namespace po = boost::program_options;\n    po::options_description desc(\"Options\");\n\n    desc.add_options()\n        (\"help,h\", \"show help\")\n        (\n         \"size,n\",\n         po::value<ptrdiff_t>(&n)->default_value(n),\n         \"domain size\"\n        )\n        ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    boost::array<ptrdiff_t, 3> lo = { {0,   0,   0  } };\n    boost::array<ptrdiff_t, 3> hi = { {n-1, n-1, n-1} };\n\n    using amgcl::prof;\n\n    prof.tic(\"partition\");\n    domain_partition<3> part(lo, hi, world.size);\n    ptrdiff_t chunk = part.size( world.rank );\n\n    std::vector<ptrdiff_t> domain = world.exclusive_sum(chunk);\n\n    lo = part.domain(world.rank).min_corner();\n    hi = part.domain(world.rank).max_corner();\n\n    renumbering renum(part, domain);\n    prof.toc(\"partition\");\n\n    prof.tic(\"assemble\");\n    std::vector<ptrdiff_t> ptr;\n    std::vector<ptrdiff_t> col;\n    std::vector<double>    val;\n    std::vector<double>    rhs;\n\n    ptr.reserve(chunk + 1);\n    col.reserve(chunk * 7);\n    val.reserve(chunk * 7);\n\n    ptr.push_back(0);\n\n    const double h2i  = (n - 1) * (n - 1);\n\n    for(ptrdiff_t k = lo[2]; k <= hi[2]; ++k) {\n        for(ptrdiff_t j = lo[1]; j <= hi[1]; ++j) {\n            for(ptrdiff_t i = lo[0]; i <= hi[0]; ++i) {\n                if (k > 0)  {\n                    col.push_back(renum(i,j,k-1));\n                    val.push_back(-h2i);\n                }\n\n                if (j > 0)  {\n                    col.push_back(renum(i,j-1,k));\n                    val.push_back(-h2i);\n                }\n\n                if (i > 0) {\n                    col.push_back(renum(i-1,j,k));\n                    val.push_back(-h2i);\n                }\n\n                col.push_back(renum(i,j,k));\n                val.push_back(6 * h2i);\n\n                if (i + 1 < n) {\n                    col.push_back(renum(i+1,j,k));\n                    val.push_back(-h2i);\n                }\n\n                if (j + 1 < n) {\n                    col.push_back(renum(i,j+1,k));\n                    val.push_back(-h2i);\n                }\n\n                if (k + 1 < n) {\n                    col.push_back(renum(i,j,k+1));\n                    val.push_back(-h2i);\n                }\n\n                ptr.push_back( col.size() );\n            }\n        }\n    }\n    prof.toc(\"assemble\");\n\n    typedef amgcl::backend::builtin<double>         Backend;\n    typedef amgcl::mpi::distributed_matrix<Backend> Matrix;\n\n    prof.tic(\"create distributed version\");\n    Matrix A(world, std::tie(chunk, ptr, col, val), chunk);\n    prof.toc(\"create distributed version\");\n\n    prof.tic(\"distributed product\");\n    auto B = amgcl::mpi::product(A, A);\n    prof.toc(\"distributed product\");\n\n    if (world.rank == 0) {\n        if (world.size == 1) {\n            typedef amgcl::backend::crs<double> matrix;\n            matrix A(std::tie(chunk, ptr, col, val));\n            prof.tic(\"openmp product\");\n            auto B = amgcl::backend::product(A, A);\n            prof.toc(\"openmp product\");\n        }\n\n        std::cout << prof << std::endl;\n    }\n}\n", "meta": {"hexsha": "986e4c09bd01d5868aa260535b7035cf7a5b8dbb", "size": 4397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/spmm_scaling.cpp", "max_stars_repo_name": "tenglongcong/amgcl", "max_stars_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 504.0, "max_stars_repo_stars_event_min_datetime": "2015-03-11T13:50:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:08:55.000Z", "max_issues_repo_path": "examples/mpi/spmm_scaling.cpp", "max_issues_repo_name": "tenglongcong/amgcl", "max_issues_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 209.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T19:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:44:12.000Z", "max_forks_repo_path": "examples/mpi/spmm_scaling.cpp", "max_forks_repo_name": "tenglongcong/amgcl", "max_forks_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92.0, "max_forks_repo_forks_event_min_datetime": "2015-01-04T06:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T09:49:12.000Z", "avg_line_length": 26.3293413174, "max_line_length": 71, "alphanum_fraction": 0.5169433705, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.558563316901824}}
{"text": "/*\n This program is free software; you can redistribute it and/or modify it under\n the terms of the European Union Public Licence - EUPL v.1.1 as published by\n the European Commission.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE. See the European Union Public Licence - EUPL v.1.1\n for more details.\n\n You should have received a copy of the European Union Public Licence - EUPL v.1.1\n along with this program.\n\n Further information about the European Union Public Licence - EUPL v.1.1 can\n also be found on the world wide web at http://ec.europa.eu/idabc/eupl\n\n*/\n\n/*\n ------ Copyright (C) 2011 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\n*/\n/*\n------------------ Author: Guillermo Ortega  ----------------------------------------\n July 2011\n\n */\n\n#include \"serviceAngleUnit.h\"\n\n#include <Eigen/Core>\n\nusing namespace Eigen;\n\n#include \"QDebug\"\n\nDialogServiceAngleUnitFrame::DialogServiceAngleUnitFrame( QWidget * parent, Qt::WindowFlags f) : QFrame(parent,f)\n{\n\tsetupUi(this);\n    angleUnitWidget = DialogServiceAngleUnitFrame::comboBoxAngleUnitsChoice;\n    myPastUnits = 0;\n    comboBoxAngleUnitsChoice->setCurrentIndex(myPastUnits);\n}\n\nDialogServiceAngleUnitFrame::~DialogServiceAngleUnitFrame()\n{\n}\n\n\n// Index meaning is as follows:\n// index = 0  is Degree\n// index = 1  is radians\n\n// Matrix coefficients as follows\n// Deg->Deg  Rad->Deg\n// Deg->Rad  Rad->Rad\n\nstatic double angleConversionMatrixCoeffs[4] =\n{1.0,            57.295779513,\n 0.0174532925,   1.0};\n\nstatic const Matrix<double, 2, 2> angleConversionMatrix(angleConversionMatrixCoeffs);\n\n\ndouble DialogServiceAngleUnitFrame::convertAngle(int fromAngleUnit, int toAngleUnit, double distance)\n{\n    //qDebug() << distanceConversionMatrix(0,0) << distanceConversionMatrix(0,1)<< distanceConversionMatrix(0,2) << distanceConversionMatrix(0,3) << distanceConversionMatrix(0,4) << endl;\n    double finalAngle = distance * angleConversionMatrix(fromAngleUnit, toAngleUnit);\n    //qDebug() << fromAngleUnit << toAngleUnit << distanceConversionMatrix(fromAngleUnit, toAngleUnit) << distance << \"--->\" << finalAngle << endl;\n    return finalAngle;\n}\n\n\n//// Sets the input distance, the output distance and the current index inside the method\nvoid DialogServiceAngleUnitFrame::setInputAngle(double niceInputAngle)\n{\n    myPastAngle = niceInputAngle;\n}\n\n\n\n// Index meaning is as follows:\n// index = 0  is Kilometers\n// index = 1  is meters\n// index = 2  is centi-meters\n// index = 3  is mili-meters\n// index = 4 is Astronomical Units\nvoid DialogServiceAngleUnitFrame::on_comboBoxAngleUnitsChoice_currentIndexChanged(int myIndex)\n{\n    //qDebug() << myPastUnits << \"==>\" << myFutureUnits << \"||||\" << myPastAngle << \"--->\" << myFutureAngle << endl;\n    myFutureUnits = myIndex;\n    myFutureAngle = convertAngle(myPastUnits, myFutureUnits, myPastAngle);\n    myPastAngle = myFutureAngle;\n    myPastUnits = myFutureUnits;\n    myRealAngleForXMLSchema = convertAngle (myPastUnits, 0, myFutureAngle);\n}\n\n", "meta": {"hexsha": "1165c6840c575f9906c1ad9e286755176509734a", "size": 3111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Services/serviceAngleUnit.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Services/serviceAngleUnit.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Services/serviceAngleUnit.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.0721649485, "max_line_length": 187, "alphanum_fraction": 0.7264545162, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.558563316901824}}
{"text": "#define BOOST_TEST_MODULE MyDLLTest\n#include <iostream>\n#include <boost/test/included/unit_test.hpp> //single-header\n#include \"MathLibrary.h\" // project being tested\n\nBOOST_AUTO_TEST_CASE(my_boost_test)\n{\n    // Initialize a Fibonacci relation sequence.\n    fibonacci_init(1, 1);\n    // Write out the sequence values until overflow.\n    do {\n        std::cout << fibonacci_index() << \": \"\n            << fibonacci_current() << std::endl;\n    } while (fibonacci_next());\n    // Report count of values written before overflow.\n    std::cout << fibonacci_index() + 1 <<\n        \" Fibonacci sequence values fit in an \" <<\n        \"unsigned 64-bit integer.\" << std::endl;\n    BOOST_CHECK(92 == fibonacci_index());\n}", "meta": {"hexsha": "01d5e27706fc6d4d261c40a704eb8ac765d4ee7e", "size": 710, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DLLExample/MathClient/MathLibraryUnitTest/MathLibraryUnitTest.cpp", "max_stars_repo_name": "zhenxuanjameszhang/LibraryTestCoverageExample", "max_stars_repo_head_hexsha": "8a81a652b2e07977d676459d13690a34f6867cea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DLLExample/MathClient/MathLibraryUnitTest/MathLibraryUnitTest.cpp", "max_issues_repo_name": "zhenxuanjameszhang/LibraryTestCoverageExample", "max_issues_repo_head_hexsha": "8a81a652b2e07977d676459d13690a34f6867cea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DLLExample/MathClient/MathLibraryUnitTest/MathLibraryUnitTest.cpp", "max_forks_repo_name": "zhenxuanjameszhang/LibraryTestCoverageExample", "max_forks_repo_head_hexsha": "8a81a652b2e07977d676459d13690a34f6867cea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5, "max_line_length": 60, "alphanum_fraction": 0.661971831, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5584133447231948}}
{"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    //   \u2022 Imposed a distance_ limit.\n    //   \u2022 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// Created by lirundong on 2019-04-28.\n//\n\n#ifndef POISSON_EDITING_INCLUDE_COMMON_HPP_\n#define POISSON_EDITING_INCLUDE_COMMON_HPP_\n\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <map>\n#include <unordered_map>\n#include <cstdint>\n#include <cmath>\n\n#include <opencv2/opencv.hpp>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <Eigen/SparseCholesky>\n#include <Eigen/PardisoSupport>\n\n#define WITHIN(i, N) (0 <= (i) && (i) < (N))\n#define CLAMP(x, lb, ub) (max((lb), min((x), (ub))))\n#define TO_PIXEL(x) (static_cast<uint8_t>(CLAMP(x, 0., 255.)))\n\n#ifdef EIGEN_USE_MKL_ALL\n  #define EIGEN_SP_SOLVER Eigen::PardisoLDLT\n#else\n  #define EIGEN_SP_SOLVER Eigen::SimplicialLDLT\n#endif\n\n#define EIGEN_CHECK(exp, solver) do { \\\n  exp; \\\n  auto solver_info = solver.info(); \\\n  if (solver_info != Eigen::Success) { \\\n    auto err_info = EIGEN_COMPUTATION_ERROR.find(solver_info); \\\n    std::cerr << \"`\" #exp \"` failed,\" << std::endl \\\n              << err_info->second << std::endl; \\\n    exit(-1); \\\n  } \\\n} while(0)\n\nnamespace poisson {\n\nusing std::max;\nusing std::min;\nusing std::vector;\n\nusing cv::Mat;\nusing cv::Size;\nusing cv::Rect;\nusing cv::Vec3b;\nusing cv::Vec3i;\nusing cv::Vec3d;\nusing cv::Point2i;\nusing cv::resize;\nusing Eigen::VectorXd;\n\nusing triplet = Eigen::Triplet<double>;\nusing triplets = std::vector<triplet>;\nusing spMat = Eigen::SparseMatrix<double>;\nusing vecMap = Eigen::Map<Eigen::VectorXd>;\n\nstatic const std::unordered_map<Eigen::ComputationInfo, std::string>\n    EIGEN_COMPUTATION_ERROR {\n    {Eigen::NumericalIssue, \"The provided data did not satisfy the \"\n                            \"prerequisites\"},\n    {Eigen::NoConvergence,  \"Iterative procedure did not converge\"},\n    {Eigen::InvalidInput,   \"The inputs are invalid, or the algorithm has been \"\n                            \"improperly called\"},\n};\n\nstatic const double EPS = 1e-6;\n\ntemplate<typename T>\ninline uint8_t real_to_pixel(const T value) {\n  CV_Assert(0.0 <= value && value <= 1.0);\n  return TO_PIXEL(value * 255.);\n}\n\ntemplate<typename PointT>\ninline decltype(auto) l2_dist(PointT &&p1, PointT &&p2) {\n  auto diff = p2 - p1;\n  return diff.x * diff.x + diff.y * diff.y;\n}\n\ntemplate<typename PointT>\ninline PointT find_nearest(const PointT &p, const vector<PointT> &border) {\n  return std::min_element(border.cbegin(), border.cend(),\n                          [&](PointT &&p1, PointT &&p2) -> bool {\n                            return l2_dist(p1, p) < l2_dist(p2, p);\n                          });\n}\n\ninline std::tuple<int, int> idx2yx(const int idx, const int W) {\n  const int x = idx % W, y = idx / W;\n  return {y, x};\n}\n\ninline int xy2idx(const int x, const int y, const int W) {\n  return y * W + x;\n}\n\ninline int yx2idx(const int y, const int x, const int W) {\n  return y * W + x;\n}\n\ninline Vec3d operator/(const Vec3d &lhs, const Vec3d &rhs) {\n  return {lhs[0] / rhs[0], lhs[1] / rhs[1], lhs[2] / rhs[2]};\n}\n\nMat fill_nearest(const Mat &img, const Mat &trimap, const int trimap_fore);\n\n}\n\n#endif //POISSON_EDITING_INCLUDE_COMMON_HPP_\n", "meta": {"hexsha": "c14ec30ee144edc9ab66accc351240d1d46f0bd7", "size": 3074, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common.hpp", "max_stars_repo_name": "lirundong/Poisson-Editing", "max_stars_repo_head_hexsha": "c50f6f656e4f68c7a903ef792c3901f19a33ff9e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-06T13:00:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T09:30:10.000Z", "max_issues_repo_path": "include/common.hpp", "max_issues_repo_name": "CrazyRundong/Poisson-Editing", "max_issues_repo_head_hexsha": "c50f6f656e4f68c7a903ef792c3901f19a33ff9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-20T03:32:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T03:32:17.000Z", "max_forks_repo_path": "include/common.hpp", "max_forks_repo_name": "lirundong/Poisson-Editing", "max_forks_repo_head_hexsha": "c50f6f656e4f68c7a903ef792c3901f19a33ff9e", "max_forks_repo_licenses": ["Apache-2.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.0508474576, "max_line_length": 80, "alphanum_fraction": 0.6545217957, "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5584133382257834}}
{"text": "/**\n * \\file dh_key.cpp\n * \\author Julien Kauffmann <julien.kauffmann@freelan.org>\n * \\brief A DH key sample file.\n */\n\n#include <cryptoplus/cryptoplus.hpp>\n#include <cryptoplus/buffer.hpp>\n#include <cryptoplus/pkey/dh_key.hpp>\n#include <cryptoplus/hash/message_digest_context.hpp>\n#include <cryptoplus/error/error_strings.hpp>\n\n#include <boost/shared_ptr.hpp>\n\n#include <iostream>\n#include <string>\n#include <cstdio>\n\n#ifdef MSV\n#include <openssl/applink.c>\n#endif\n\nusing cryptoplus::buffer;\n\nnamespace\n{\n\tint pem_passphrase_callback(char* buf, int buf_len, int rwflag, void*)\n\t{\n\t\tstd::cout << \"Passphrase (max: \" << buf_len << \" characters): \" << std::flush;\n\t\tstd::string passphrase;\n\t\tstd::getline(std::cin, passphrase);\n\n\t\tif (passphrase.empty())\n\t\t{\n\t\t\tstd::cerr << \"Passphrase cannot be empty.\" << std::endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (passphrase.size() > static_cast<size_t>(buf_len))\n\t\t{\n\t\t\tstd::cerr << \"Passphrase cannot exceed \" << buf_len << \" characters.\" << std::endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (rwflag != 0)\n\t\t{\n\t\t\tstd::cout << \"Confirm: \" << std::flush;\n\t\t\tstd::string passphrase_confirmation;\n\t\t\tstd::getline(std::cin, passphrase_confirmation);\n\n\t\t\tif (passphrase_confirmation != passphrase)\n\t\t\t{\n\t\t\t\tstd::cerr << \"The two passphrases do not match !\" << std::endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\n\t\tstd::copy(passphrase.begin(), passphrase.end(), buf);\n\t\treturn passphrase.size();\n\t}\n}\n\nint main()\n{\n\tcryptoplus::crypto_initializer crypto_initializer;\n\tcryptoplus::algorithms_initializer algorithms_initializer;\n\tcryptoplus::error::error_strings_initializer error_strings_initializer;\n\n\tstd::cout << \"DH sample\" << std::endl;\n\tstd::cout << \"=========\" << std::endl;\n\tstd::cout << std::endl;\n\n\tconst int bits = 1024;\n\tconst int generator = 2;\n\n\tstd::cout << \"Using DH keys of \" << bits << \" bits.\" << std::endl;\n\n\tconst std::string parameters_filename = \"parameters.pem\";\n\n\tboost::shared_ptr<FILE> parameters_file(fopen(parameters_filename.c_str(), \"w\"), fclose);\n\n\tif (!parameters_file)\n\t{\n\t\tstd::cerr << \"Unable to open \\\"\" << parameters_filename << \"\\\" for writing.\" << std::endl;\n\n\t\treturn EXIT_FAILURE;\n\t}\n\n\ttry\n\t{\n\t\tstd::cout << \"Generating DH parameters. This can take some time...\" << std::endl;\n\n\t\tcryptoplus::pkey::dh_key dh_key = cryptoplus::pkey::dh_key::generate_parameters(bits, generator);\n\n\t\tint codes = 0;\n\n\t\tdh_key.check(codes);\n\n\t\tif (codes != 0)\n\t\t{\n\t\t\tstd::cerr << \"Generation failed.\" << std::endl;\n\n\t\t\tif (codes & DH_CHECK_P_NOT_SAFE_PRIME)\n\t\t\t{\n\t\t\t\tstd::cerr << \"p is not a safe prime.\" << std::endl;\n\t\t\t}\n\t\t\tif (codes & DH_NOT_SUITABLE_GENERATOR)\n\t\t\t{\n\t\t\t\tstd::cerr << \"g is not a suitable generator.\" << std::endl;\n\t\t\t}\n\n\t\t\tif (codes & DH_UNABLE_TO_CHECK_GENERATOR)\n\t\t\t{\n\t\t\t\tstd::cerr << \"g is not a correct generator. Must be either 2 or 5.\" << std::endl;\n\t\t\t}\n\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\n\t\tdh_key.write_parameters(parameters_file.get());\n\n\t\tstd::cout << \"DH parameters written succesfully to \\\"\" << parameters_filename << \"\\\".\" << std::endl;\n\t\tstd::cout << \"Done.\" << std::endl;\n\n\t\tstd::cout << \"Generating DH key...\" << std::endl;\n\n\t\tdh_key.generate_key();\n\n\t\tstd::cout << \"Done.\" << std::endl;\n\n\t\tparameters_file.reset(fopen(parameters_filename.c_str(), \"r\"), fclose);\n\n\t\tif (!parameters_file)\n\t\t{\n\t\t\tstd::cerr << \"Unable to open \\\"\" << parameters_filename << \"\\\" for reading.\" << std::endl;\n\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\n\t\tstd::cout << \"Trying to read back the DH parameters from \\\"\" << parameters_filename << \"\\\"...\" << std::endl;\n\n\t\tcryptoplus::pkey::dh_key dh_key2 = cryptoplus::pkey::dh_key::from_parameters(parameters_file.get(), pem_passphrase_callback);\n\n\t\tstd::cout << \"Done.\" << std::endl;\n\n\t\tstd::cout << \"Generating DH key...\" << std::endl;\n\n\t\tdh_key2.generate_key();\n\n\t\tstd::cout << \"Done.\" << std::endl;\n\n\t\tstd::cout << \"Public key A: \" << dh_key.public_key().to_dec() << std::endl;\n\t\tstd::cout << \"Public key B: \" << dh_key2.public_key().to_dec() << std::endl;\n\n\t\tstd::cout << \"Computing key A...\" << std::endl;\n\n\t\tbuffer key_a = dh_key.compute_key(dh_key2.public_key());\n\t\t\n\t\tstd::cout << \"Done.\" << std::endl;\n\n\t\tstd::cout << \"Computing key B...\" << std::endl;\n\n\t\tbuffer key_b = dh_key2.compute_key(dh_key.public_key());\n\t\t\n\t\tstd::cout << \"Done.\" << std::endl;\n\n\t\tstd::cout << \"Comparing key A and key B: \" << ((key_a == key_b) ? \"IDENTICAL\" : \"DIFFERENT\") << std::endl;\n\t}\n\tcatch (std::exception& ex)\n\t{\n\t\tstd::cerr << \"Exception: \" << ex.what() << std::endl;\n\n\t\treturn EXIT_FAILURE;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "f00ce667baa21747c5fdc3cbcda5e2d0d7f6f8f5", "size": 4466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "blades/freelan/samples/cryptoplus/dh_key/dh_key.cpp", "max_stars_repo_name": "krattai/AEBL", "max_stars_repo_head_hexsha": "a7b12c97479e1236d5370166b15ca9f29d7d4265", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T03:43:54.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-17T08:09:04.000Z", "max_issues_repo_path": "blades/freelan/samples/cryptoplus/dh_key/dh_key.cpp", "max_issues_repo_name": "krattai/AEBL", "max_issues_repo_head_hexsha": "a7b12c97479e1236d5370166b15ca9f29d7d4265", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T21:06:22.000Z", "max_issues_repo_issues_event_max_datetime": "2015-12-07T20:45:44.000Z", "max_forks_repo_path": "blades/freelan/samples/cryptoplus/dh_key/dh_key.cpp", "max_forks_repo_name": "krattai/AEBL", "max_forks_repo_head_hexsha": "a7b12c97479e1236d5370166b15ca9f29d7d4265", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T03:43:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-06T11:02:08.000Z", "avg_line_length": 25.0898876404, "max_line_length": 127, "alphanum_fraction": 0.6433049709, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5584133328866707}}
{"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": "#ifdef STAND_ALONE\n#   define BOOST_TEST_MODULE RayTracerChallengeTests\n#endif\n\n#include <boost/test/unit_test.hpp>\n#include <shared/Point.h>\n#include <iostream>\n#include <cmath>\n#include <shared/Projectile.h>\n#include <shared/Environment.h>\n#include <shared/World.h>\n#include \"../src/shared/Tuple.h\"\n#include \"shared/Vector.h\"\n#include \"shared/Color.h\"\n\n\nBOOST_AUTO_TEST_SUITE(tuple_suite)\n\n    BOOST_AUTO_TEST_CASE(point_test) {\n        auto a = Tuple(4.3, -4.2, 3.1, 1.0);\n\n        BOOST_CHECK_EQUAL(a.x, 4.3);\n        BOOST_CHECK_EQUAL(a.y, -4.2);\n        BOOST_CHECK_EQUAL(a.z, 3.1);\n        BOOST_CHECK_EQUAL(a.w, 1.0);\n        BOOST_CHECK_EQUAL(a.type, a.POINT);\n        BOOST_CHECK_EQUAL(a.type, !a.VECTOR);\n    }\n\n    BOOST_AUTO_TEST_CASE(vector_test) {\n        auto a = Tuple(4.3, -4.2, 3.1, 0);\n\n        BOOST_CHECK_EQUAL(a.x, 4.3);\n        BOOST_CHECK_EQUAL(a.y, -4.2);\n        BOOST_CHECK_EQUAL(a.z, 3.1);\n        BOOST_CHECK_EQUAL(a.w, 0.0);\n        BOOST_CHECK_EQUAL(a.type, !a.POINT);\n        BOOST_CHECK_EQUAL(a.type, a.VECTOR);\n    }\n\n    BOOST_AUTO_TEST_CASE(point_create_tuple_0_test) {\n        auto a = Tuple(4, -3, 3, 0);\n        auto b = Point(4, -3, 3);\n\n        BOOST_TEST(a.equals(b));\n    }\n\n    BOOST_AUTO_TEST_CASE(vector_create_tuple_1_test) {\n        auto a = Tuple(4, -3, 3, 1);\n        auto b = Vector(4, -3, 3);\n\n        BOOST_TEST(a.equals(b));\n    }\n\n    BOOST_AUTO_TEST_CASE(tuple_addition_test) {\n        auto a1 = Tuple(3, -2, 5, 1);\n        auto b1 = Tuple(-2, 3, 1, 0);\n        auto c = a1.add(b1);\n\n        BOOST_TEST(a1.add(b1).equals(Tuple(1, 1, 6, 1)));\n    }\n\n    BOOST_AUTO_TEST_CASE(point_subtraction_test) {\n        auto p1 = Point(3, 2, 1);\n        auto p2 = Point(5, 6, 7);\n        auto c = p1.subtract(p2);\n\n        BOOST_TEST(p1.subtract(p2).equals(Point(-2, -4, -6)));\n    }\n\n    BOOST_AUTO_TEST_CASE(vector_point_subtraction_test) {\n        auto p1 = Point(3, 2, 1);\n        auto p2 = Vector(5, 6, 7);\n        auto c = p1.subtract(p2);\n\n        BOOST_TEST(p1.subtract(p2).equals(Point(-2, -4, -6)));\n    }\n\n    BOOST_AUTO_TEST_CASE(vector_vector_subtraction_test) {\n        auto p1 = Vector(3, 2, 1);\n        auto p2 = Vector(5, 6, 7);\n        auto c = p1.subtract(p2);\n//        std::cout << c->x << std::endl;\n//        std::cout << c->y << std::endl;\n//        std::cout << c->z << std::endl;\n\n        BOOST_TEST(p1.subtract(p2).equals(Vector(-2, -4, -6)));\n    }\n\n    BOOST_AUTO_TEST_CASE(tuple_negation_test) {\n        auto a = Tuple(1, -2, 3, -4);\n\n        BOOST_TEST(a.negate().equals(Tuple(-1, 2, -3, 4)));\n    }\n\n    BOOST_AUTO_TEST_CASE(multiplying_tuple_by_scalar_test) {\n        auto a = Tuple(1, -2, 3, -4);\n        auto b = a.multiply(3.5);\n\n        BOOST_TEST(b.equals(Tuple(3.5, -7, 10.5, -14)));\n    }\n\n    BOOST_AUTO_TEST_CASE(multiplying_tuple_by_fraction_test) {\n        auto a = Tuple(1, -2, 3, -4);\n        auto b = a.multiply(0.5);\n\n        BOOST_TEST(b.equals(Tuple(0.5, -1, 1.5, -2)));\n    }\n\n    BOOST_AUTO_TEST_CASE(divide_a_tuple_by_a_scaler_test) {\n        auto a = Tuple(1, -2, 3, -4);\n        auto b = a.divide(2);\n\n        BOOST_TEST(b.equals(Tuple(0.5, -1, 1.5, -2)));\n    }\n\n    BOOST_AUTO_TEST_CASE(computing_the_magnitude_of_vector_1_0_0_test) {\n        auto a = Vector(1, 0, 0);\n\n\n        BOOST_CHECK_EQUAL(a.magnitude(), 1);\n    }\n\n    BOOST_AUTO_TEST_CASE(computing_the_magnitude_of_vector_m1_m20_m3_test) {\n        auto a = Vector(-1, -2, -3);\n\n\n        BOOST_CHECK_EQUAL(a.magnitude(), sqrt(14));\n    }\n\n    BOOST_AUTO_TEST_CASE(normalizing_vector_4_0_0_test) {\n        auto a = Vector(4, 0, 0);\n\n        BOOST_TEST(a.normalize().equals(Vector(1, 0, 0)));\n    }\n\n    BOOST_AUTO_TEST_CASE(dot_product_of_two_tuples_test) {\n        auto a = Vector(1, 2, 3);\n        auto b = Vector(2, 3, 4);\n\n\n        BOOST_CHECK_EQUAL(a.dot(b), 20);\n    }\n\n    BOOST_AUTO_TEST_CASE(cross_product_of_two_tuples_test) {\n        auto a = Vector(1, 2, 3);\n        auto b = Vector(2, 3, 4);\n\n\n        BOOST_TEST(a.cross(b).equals(Vector(-1, 2, -1)));\n    }\n\n    BOOST_AUTO_TEST_CASE(projectile_test) {\n        auto projectile = Projectile(Point(0, 1, 0), Vector(1, 1, 0).normalize());\n        auto e = Environment(Vector(0, -0.1, 0), Vector(0, -0.01, 0));\n        auto w = World();\n//        std::cout << \"x \" << projectile.position.x << \" y  \" << projectile.position.y << \" z \" << projectile.position.z << std::endl;\n        int i=0;\n        while(projectile.position.y>0 && i++<200){\n//            std::cout <<\"i \" << i <<\"x \" << projectile.position.x << \" y  \" << projectile.position.y << \" z \" << projectile.position.z << std::endl;\n            projectile=w.tick(e, projectile);\n        }\n\n\n       BOOST_TEST(projectile.position.y<=0);\n    }\n\n    BOOST_AUTO_TEST_CASE(colors_are_tuples_test) {\n        auto a = Color(-0.5, 0.4, 1.7);\n\n\n        BOOST_CHECK_EQUAL(a.red(), -0.5);\n        BOOST_CHECK_EQUAL(a.green(), 0.4);\n        BOOST_CHECK_EQUAL(a.blue(), 1.7);\n    }\n\n    BOOST_AUTO_TEST_CASE(adding_colors_test) {\n        auto a = Color(0.9, 0.6, 0.75);\n        auto b = Color(0.7, 0.1, 0.25);\n\n        auto c=a+b;\n\n        BOOST_TEST(c.equals(Color(1.6,0.7,1.0)));\n    }\n\n    BOOST_AUTO_TEST_CASE(subtract_colors_test) {\n        auto a = Color(0.9, 0.6, 0.75);\n        auto b = Color(0.7, 0.1, 0.25);\n\n        auto c=a-b;\n\n        BOOST_TEST(c.equals(Color(0.2,0.5,0.5)));\n    }\n\n    BOOST_AUTO_TEST_CASE(multiply_color_by_scalar_test) {\n        auto a = Color(0.2, 0.3, 0.4);\n\n        auto c=a*2;\n\n        BOOST_TEST(c.equals(Color(0.4,0.6,0.8)));\n    }\n\n    BOOST_AUTO_TEST_CASE(multiply_colors_test) {\n        auto a = Color(1,0.2,0.4);\n        auto b = Color(0.9,1,0.1);\n\n        auto c=a*b;\n\n        BOOST_TEST(c.equals(Color(0.9,0.2,0.04)));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "8a130a06ae43afa92e0baf4a9c8c36184fa712d2", "size": 5764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_tuple.cpp", "max_stars_repo_name": "RainerBlessing/TheRayTracerChallenge-C-", "max_stars_repo_head_hexsha": "22c990201507f46d5bb1604bc1f6ee88e59cef95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_tuple.cpp", "max_issues_repo_name": "RainerBlessing/TheRayTracerChallenge-C-", "max_issues_repo_head_hexsha": "22c990201507f46d5bb1604bc1f6ee88e59cef95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_tuple.cpp", "max_forks_repo_name": "RainerBlessing/TheRayTracerChallenge-C-", "max_forks_repo_head_hexsha": "22c990201507f46d5bb1604bc1f6ee88e59cef95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1886792453, "max_line_length": 150, "alphanum_fraction": 0.573907009, "num_tokens": 1823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.5584084963967109}}
{"text": "// test_poisson.cpp\n\n// Copyright Paul A. Bristow 2007.\n// Copyright John Maddock 2006.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Basic sanity test for Poisson Cumulative Distribution Function.\n\n#define BOOST_MATH_DISCRETE_QUANTILE_POLICY real\n\n#if !defined(TEST_FLOAT) && !defined(TEST_DOUBLE) && !defined(TEST_LDOUBLE) && !defined(TEST_REAL_CONCEPT)\n#  define TEST_FLOAT\n#  define TEST_DOUBLE\n#  define TEST_LDOUBLE\n#  define TEST_REAL_CONCEPT\n#endif\n\n#ifdef _MSC_VER\n#  pragma warning(disable: 4127) // conditional expression is constant.\n#endif\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp> // Boost.Test\n#include <boost/test/floating_point_comparison.hpp>\n\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\n#include <boost/math/distributions/poisson.hpp>\n    using boost::math::poisson_distribution;\n#include <boost/math/tools/test.hpp> // for real_concept\n\n#include <boost/math/special_functions/gamma.hpp> // for (incomplete) gamma.\n//   using boost::math::qamma_Q;\n#include \"table_type.hpp\"\n#include \"test_out_of_range.hpp\"\n\n#include <iostream>\n   using std::cout;\n   using std::endl;\n   using std::setprecision;\n   using std::showpoint;\n   using std::ios;\n#include <limits>\n  using std::numeric_limits;\n\ntemplate <class RealType> // Any floating-point type RealType.\nvoid test_spots(RealType)\n{\n  // Basic sanity checks, tolerance is about numeric_limits<RealType>::digits10 decimal places,\n   // guaranteed for type RealType, eg 6 for float, 15 for double,\n   // expressed as a percentage (so -2) for BOOST_CHECK_CLOSE,\n\n   int decdigits = numeric_limits<RealType>::digits10;\n  // May eb >15 for 80 and 128-bit FP typtes.\n  if (decdigits <= 0)\n  { // decdigits is not defined, for example real concept,\n    // so assume precision of most test data is double (for example, MathCAD).\n     decdigits = numeric_limits<double>::digits10; // == 15 for 64-bit\n  }\n  if (decdigits > 15 ) // numeric_limits<double>::digits10)\n  { // 15 is the accuracy of the MathCAD test data.\n    decdigits = 15; // numeric_limits<double>::digits10;\n  }\n\n   decdigits -= 1; // Perhaps allow some decimal digit(s) margin of numerical error.\n   RealType tolerance = static_cast<RealType>(std::pow(10., static_cast<double>(2-decdigits))); // 1e-6 (-2 so as %)\n   tolerance *= 2; // Allow some bit(s) small margin (2 means + or - 1 bit) of numerical error.\n   // Typically 2e-13% = 2e-15 as fraction for double.\n\n   // Sources of spot test values:\n\n  // Many be some combinations for which the result is 'exact',\n  // or at least is good to 40 decimal digits.\n   // 40 decimal digits includes 128-bit significand User Defined Floating-Point types,\n   \n   // Best source of accurate values is:\n   // Mathworld online calculator (40 decimal digits precision, suitable for up to 128-bit significands)\n   // http://functions.wolfram.com/webMathematica/FunctionEvaluation.jsp?name=GammaRegularized\n   // GammaRegularized is same as gamma incomplete, gamma or gamma_q(a, x) or Q(a, z).\n\n  // http://documents.wolfram.com/calculationcenter/v2/Functions/ListsMatrices/Statistics/PoissonDistribution.html\n\n  // MathCAD defines ppois(k, lambda== mean) as k integer, k >=0.\n  // ppois(0, 5) =  6.73794699908547e-3\n  // ppois(1, 5) = 0.040427681994513;\n  // ppois(10, 10) = 5.830397501929850E-001\n  // ppois(10, 1) = 9.999999899522340E-001\n  // ppois(5,5) = 0.615960654833065\n\n  // qpois returns inverse Poission distribution, that is the smallest (floor) k so that ppois(k, lambda) >= p\n  // p is real number, real mean lambda > 0\n  // k is approximately the integer for which probability(X <= k) = p\n  // when random variable X has the Poisson distribution with parameters lambda.\n  // Uses discrete bisection.\n  // qpois(6.73794699908547e-3, 5) = 1\n  // qpois(0.040427681994513, 5) = \n\n  // Test Poisson with spot values from MathCAD 'known good'.\n\n  using boost::math::poisson_distribution;\n  using  ::boost::math::poisson;\n  using  ::boost::math::cdf;\n  using  ::boost::math::pdf;\n\n   // Check that bad arguments throw.\n   BOOST_CHECK_THROW(\n   cdf(poisson_distribution<RealType>(static_cast<RealType>(0)), // mean zero is bad.\n      static_cast<RealType>(0)),  // even for a good k.\n      std::domain_error); // Expected error to be thrown.\n\n    BOOST_CHECK_THROW(\n   cdf(poisson_distribution<RealType>(static_cast<RealType>(-1)), // mean negative is bad.\n      static_cast<RealType>(0)),\n      std::domain_error);\n\n   BOOST_CHECK_THROW(\n   cdf(poisson_distribution<RealType>(static_cast<RealType>(1)), // mean unit OK,\n      static_cast<RealType>(-1)),  // but negative events is bad.\n      std::domain_error);\n\n  BOOST_CHECK_THROW(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(0)), // mean zero is bad.\n      static_cast<RealType>(99999)),  // for any k events. \n      std::domain_error);\n  \n  BOOST_CHECK_THROW(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(0)), // mean zero is bad.\n      static_cast<RealType>(99999)),  // for any k events. \n      std::domain_error);\n\n  BOOST_CHECK_THROW(\n     quantile(poisson_distribution<RealType>(static_cast<RealType>(0)), // mean zero.\n      static_cast<RealType>(0.5)),  // probability OK. \n      std::domain_error);\n\n  BOOST_CHECK_THROW(\n     quantile(poisson_distribution<RealType>(static_cast<RealType>(-1)), \n      static_cast<RealType>(-1)),  // bad probability. \n      std::domain_error);\n\n  BOOST_CHECK_THROW(\n     quantile(poisson_distribution<RealType>(static_cast<RealType>(1)), \n      static_cast<RealType>(-1)),  // bad probability. \n      std::domain_error);\n\n  // Check some test values.\n\n  BOOST_CHECK_CLOSE( // mode\n     mode(poisson_distribution<RealType>(static_cast<RealType>(4))), // mode = mean = 4.\n      static_cast<RealType>(4), // mode.\n         tolerance);\n\n  //BOOST_CHECK_CLOSE( // mode\n  //   median(poisson_distribution<RealType>(static_cast<RealType>(4))), // mode = mean = 4.\n  //    static_cast<RealType>(4), // mode.\n      //   tolerance);\n  poisson_distribution<RealType> dist4(static_cast<RealType>(40));\n\n  BOOST_CHECK_CLOSE( // median\n     median(dist4), // mode = mean = 4. median = 40.328333333333333 \n      quantile(dist4, static_cast<RealType>(0.5)), // 39.332839138842637\n         tolerance);\n\n  // PDF\n  BOOST_CHECK_CLOSE(\n     pdf(poisson_distribution<RealType>(static_cast<RealType>(4)), // mean 4.\n      static_cast<RealType>(0)),   \n      static_cast<RealType>(1.831563888873410E-002), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     pdf(poisson_distribution<RealType>(static_cast<RealType>(4)), // mean 4.\n      static_cast<RealType>(2)),   \n      static_cast<RealType>(1.465251111098740E-001), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     pdf(poisson_distribution<RealType>(static_cast<RealType>(20)), // mean big.\n      static_cast<RealType>(1)),   //  k small\n      static_cast<RealType>(4.122307244877130E-008), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     pdf(poisson_distribution<RealType>(static_cast<RealType>(4)), // mean 4.\n      static_cast<RealType>(20)),   //  K>> mean \n      static_cast<RealType>(8.277463646553730E-009), // probability.\n         tolerance);\n  \n  // CDF\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(1)), // mean unity.\n      static_cast<RealType>(0)),  // zero k events. \n      static_cast<RealType>(3.678794411714420E-1), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(1)), // mean unity.\n      static_cast<RealType>(1)),  // one k event. \n      static_cast<RealType>(7.357588823428830E-1), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(1)), // mean unity.\n      static_cast<RealType>(2)),  // two k events. \n      static_cast<RealType>(9.196986029286060E-1), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(1)), // mean unity.\n      static_cast<RealType>(10)),  // two k events. \n      static_cast<RealType>(9.999999899522340E-1), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(1)), // mean unity.\n      static_cast<RealType>(15)),  // two k events. \n      static_cast<RealType>(9.999999999999810E-1), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(1)), // mean unity.\n      static_cast<RealType>(16)),  // two k events. \n      static_cast<RealType>(9.999999999999990E-1), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(1)), // mean unity.\n      static_cast<RealType>(17)),  // two k events. \n      static_cast<RealType>(1.), // probability unity for double.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(1)), // mean unity.\n      static_cast<RealType>(33)),  // k events at limit for float unchecked_factorial table. \n      static_cast<RealType>(1.), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(100)), // mean 100.\n      static_cast<RealType>(33)),  // k events at limit for float unchecked_factorial table. \n      static_cast<RealType>(6.328271240363390E-15), // probability is tiny.\n         tolerance * static_cast<RealType>(2e11)); // 6.3495253382825722e-015 MathCAD\n      // Note that there two tiny probability are much more different.\n\n   BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(100)), // mean 100.\n      static_cast<RealType>(34)),  // k events at limit for float unchecked_factorial table. \n      static_cast<RealType>(1.898481372109020E-14), // probability is tiny.\n         tolerance*static_cast<RealType>(2e11)); //         1.8984813721090199e-014 MathCAD\n\n\n BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(33)), // mean = k\n      static_cast<RealType>(33)),  // k events above limit for float unchecked_factorial table. \n      static_cast<RealType>(5.461191812386560E-1), // probability.\n         tolerance);\n\n BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(33)), // mean = k-1\n      static_cast<RealType>(34)),  // k events above limit for float unchecked_factorial table. \n      static_cast<RealType>(6.133535681502950E-1), // probability.\n         tolerance);\n\n BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(1)), // mean unity.\n      static_cast<RealType>(34)),  // k events above limit for float unchecked_factorial table. \n      static_cast<RealType>(1.), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(5.)), // mean\n      static_cast<RealType>(5)),  // k events. \n      static_cast<RealType>(0.615960654833065), // probability.\n         tolerance);\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(5.)), // mean\n      static_cast<RealType>(1)),  // k events. \n      static_cast<RealType>(0.040427681994512805), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(5.)), // mean\n      static_cast<RealType>(0)),  // k events (uses special case formula, not gamma). \n      static_cast<RealType>(0.006737946999085467), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(1.)), // mean\n      static_cast<RealType>(0)),  // k events (uses special case formula, not gamma). \n      static_cast<RealType>(0.36787944117144233), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(10.)), // mean\n      static_cast<RealType>(10)),  // k events. \n      static_cast<RealType>(0.5830397501929856), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(4.)), // mean\n      static_cast<RealType>(5)),  // k events. \n      static_cast<RealType>(0.785130387030406), // probability.\n         tolerance);\n\n  // complement CDF\n  BOOST_CHECK_CLOSE( // Complement CDF\n     cdf(complement(poisson_distribution<RealType>(static_cast<RealType>(4.)), // mean\n      static_cast<RealType>(5))),  // k events. \n      static_cast<RealType>(1 - 0.785130387030406), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE( // Complement CDF\n     cdf(complement(poisson_distribution<RealType>(static_cast<RealType>(4.)), // mean\n      static_cast<RealType>(0))),  // Zero k events (uses special case formula, not gamma).\n      static_cast<RealType>(0.98168436111126578), // probability.\n         tolerance);\n  BOOST_CHECK_CLOSE( // Complement CDF\n     cdf(complement(poisson_distribution<RealType>(static_cast<RealType>(1.)), // mean\n      static_cast<RealType>(0))),  // Zero k events (uses special case formula, not gamma).\n      static_cast<RealType>(0.63212055882855767), // probability.\n         tolerance);\n\n  // Example where k is bigger than max_factorial (>34 for float)\n  // (therefore using log gamma so perhaps less accurate).\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(40.)), // mean\n      static_cast<RealType>(40)),  // k events. \n      static_cast<RealType>(0.5419181783625430), // probability.\n         tolerance);\n\n   // Quantile & complement.\n  BOOST_CHECK_CLOSE(\n    boost::math::quantile(\n         poisson_distribution<RealType>(5),  // mean.\n         static_cast<RealType>(0.615960654833065)),  //  probability.\n         static_cast<RealType>(5.), // Expect k = 5\n         tolerance/5); // \n\n  // EQUAL is too optimistic - fails [5.0000000000000124 != 5]\n  // BOOST_CHECK_EQUAL(boost::math::quantile( // \n  //       poisson_distribution<RealType>(5.),  // mean.\n  //       static_cast<RealType>(0.615960654833065)),  //  probability.\n  //       static_cast<RealType>(5.)); // Expect k = 5 events.\n \n  BOOST_CHECK_CLOSE(boost::math::quantile(\n         poisson_distribution<RealType>(4),  // mean.\n         static_cast<RealType>(0.785130387030406)),  //  probability.\n         static_cast<RealType>(5.), // Expect k = 5 events.\n         tolerance/5); \n\n  // Check on quantile of other examples of inverse of cdf.\n  BOOST_CHECK_CLOSE( \n     cdf(poisson_distribution<RealType>(static_cast<RealType>(10.)), // mean\n      static_cast<RealType>(10)),  // k events. \n      static_cast<RealType>(0.5830397501929856), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(boost::math::quantile( // inverse of cdf above.\n         poisson_distribution<RealType>(10.),  // mean.\n         static_cast<RealType>(0.5830397501929856)),  //  probability.\n         static_cast<RealType>(10.), // Expect k = 10 events.\n         tolerance/5); \n\n\n  BOOST_CHECK_CLOSE(\n     cdf(poisson_distribution<RealType>(static_cast<RealType>(4.)), // mean\n      static_cast<RealType>(5)),  // k events. \n      static_cast<RealType>(0.785130387030406), // probability.\n         tolerance);\n\n  BOOST_CHECK_CLOSE(boost::math::quantile( // inverse of cdf above.\n         poisson_distribution<RealType>(4.),  // mean.\n         static_cast<RealType>(0.785130387030406)),  //  probability.\n         static_cast<RealType>(5.), // Expect k = 10 events.\n         tolerance/5); \n\n\n\n  //BOOST_CHECK_CLOSE(boost::math::quantile(\n  //       poisson_distribution<RealType>(5),  // mean.\n  //       static_cast<RealType>(0.785130387030406)),  //  probability.\n  //        // 6.1882832344329559 result but MathCAD givest smallest integer ppois(k, mean) >= prob\n  //       static_cast<RealType>(6.), // Expect k = 6 events. \n  //       tolerance/5); \n\n  //BOOST_CHECK_CLOSE(boost::math::quantile(\n  //       poisson_distribution<RealType>(5),  // mean.\n  //       static_cast<RealType>(0.77)),  //  probability.\n  //        // 6.1882832344329559 result but MathCAD givest smallest integer ppois(k, mean) >= prob\n  //       static_cast<RealType>(7.), // Expect k = 6 events. \n  //       tolerance/5); \n\n  //BOOST_CHECK_CLOSE(boost::math::quantile(\n  //       poisson_distribution<RealType>(5),  // mean.\n  //       static_cast<RealType>(0.75)),  //  probability.\n  //        // 6.1882832344329559 result but MathCAD givest smallest integer ppois(k, mean) >= prob\n  //       static_cast<RealType>(6.), // Expect k = 6 events. \n  //       tolerance/5); \n\n  BOOST_CHECK_CLOSE(\n    boost::math::quantile(\n         complement(\n           poisson_distribution<RealType>(4),\n           static_cast<RealType>(1 - 0.785130387030406))),  // complement.\n           static_cast<RealType>(5), // Expect k = 5 events.\n         tolerance/5);\n\n  BOOST_CHECK_EQUAL(boost::math::quantile( // Check case when probability < cdf(0) (== pdf(0))\n         poisson_distribution<RealType>(1),  // mean is small, so cdf and pdf(0) are about 0.35.\n         static_cast<RealType>(0.0001)),  //  probability < cdf(0).\n         static_cast<RealType>(0)); // Expect k = 0 events exactly.\n          \n  BOOST_CHECK_EQUAL(\n    boost::math::quantile(\n         complement(\n           poisson_distribution<RealType>(1),\n           static_cast<RealType>(0.9999))),  // complement, so 1-probability < cdf(0)\n           static_cast<RealType>(0)); // Expect k = 0 events exactly.\n\n  //\n  // Test quantile policies against test data:\n  //\n#define T RealType\n#include \"poisson_quantile.ipp\"\n\n  for(unsigned i = 0; i < poisson_quantile_data.size(); ++i)\n  {\n     using namespace boost::math::policies;\n     typedef policy<discrete_quantile<real> > P1;\n     typedef policy<discrete_quantile<integer_round_down> > P2;\n     typedef policy<discrete_quantile<integer_round_up> > P3;\n     typedef policy<discrete_quantile<integer_round_outwards> > P4;\n     typedef policy<discrete_quantile<integer_round_inwards> > P5;\n     typedef policy<discrete_quantile<integer_round_nearest> > P6;\n     RealType tol = boost::math::tools::epsilon<RealType>() * 20;\n     if(!boost::is_floating_point<RealType>::value)\n        tol *= 7;\n     //\n     // Check full real value first:\n     //\n     poisson_distribution<RealType, P1> p1(poisson_quantile_data[i][0]);\n     RealType x = quantile(p1, poisson_quantile_data[i][1]);\n     BOOST_CHECK_CLOSE_FRACTION(x, poisson_quantile_data[i][2], tol);\n     x = quantile(complement(p1, poisson_quantile_data[i][1]));\n     BOOST_CHECK_CLOSE_FRACTION(x, poisson_quantile_data[i][3], tol * 3);\n     //\n     // Now with round down to integer:\n     //\n     poisson_distribution<RealType, P2> p2(poisson_quantile_data[i][0]);\n     x = quantile(p2, poisson_quantile_data[i][1]);\n     BOOST_CHECK_EQUAL(x, floor(poisson_quantile_data[i][2]));\n     x = quantile(complement(p2, poisson_quantile_data[i][1]));\n     BOOST_CHECK_EQUAL(x, floor(poisson_quantile_data[i][3]));\n     //\n     // Now with round up to integer:\n     //\n     poisson_distribution<RealType, P3> p3(poisson_quantile_data[i][0]);\n     x = quantile(p3, poisson_quantile_data[i][1]);\n     BOOST_CHECK_EQUAL(x, ceil(poisson_quantile_data[i][2]));\n     x = quantile(complement(p3, poisson_quantile_data[i][1]));\n     BOOST_CHECK_EQUAL(x, ceil(poisson_quantile_data[i][3]));\n     //\n     // Now with round to integer \"outside\":\n     //\n     poisson_distribution<RealType, P4> p4(poisson_quantile_data[i][0]);\n     x = quantile(p4, poisson_quantile_data[i][1]);\n     BOOST_CHECK_EQUAL(x, poisson_quantile_data[i][1] < 0.5f ? floor(poisson_quantile_data[i][2]) : ceil(poisson_quantile_data[i][2]));\n     x = quantile(complement(p4, poisson_quantile_data[i][1]));\n     BOOST_CHECK_EQUAL(x, poisson_quantile_data[i][1] < 0.5f ? ceil(poisson_quantile_data[i][3]) : floor(poisson_quantile_data[i][3]));\n     //\n     // Now with round to integer \"inside\":\n     //\n     poisson_distribution<RealType, P5> p5(poisson_quantile_data[i][0]);\n     x = quantile(p5, poisson_quantile_data[i][1]);\n     BOOST_CHECK_EQUAL(x, poisson_quantile_data[i][1] < 0.5f ? ceil(poisson_quantile_data[i][2]) : floor(poisson_quantile_data[i][2]));\n     x = quantile(complement(p5, poisson_quantile_data[i][1]));\n     BOOST_CHECK_EQUAL(x, poisson_quantile_data[i][1] < 0.5f ? floor(poisson_quantile_data[i][3]) : ceil(poisson_quantile_data[i][3]));\n     //\n     // Now with round to nearest integer:\n     //\n     poisson_distribution<RealType, P6> p6(poisson_quantile_data[i][0]);\n     x = quantile(p6, poisson_quantile_data[i][1]);\n     BOOST_CHECK_EQUAL(x, floor(poisson_quantile_data[i][2] + 0.5f));\n     x = quantile(complement(p6, poisson_quantile_data[i][1]));\n     BOOST_CHECK_EQUAL(x, floor(poisson_quantile_data[i][3] + 0.5f));\n  }\n   check_out_of_range<poisson_distribution<RealType> >(1);\n} // template <class RealType>void test_spots(RealType)\n\n//\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n  // Check that can construct normal distribution using the two convenience methods:\n  using namespace boost::math;\n  poisson myp1(2); // Using typedef\n   poisson_distribution<> myp2(2); // Using default RealType double.\n\n   // Basic sanity-check spot values.\n\n  // Some plain double examples & tests:\n  cout.precision(17); // double max_digits10\n  cout.setf(ios::showpoint);\n  \n  poisson mypoisson(4.); // // mean = 4, default FP type is double.\n  cout << \"mean(mypoisson, 4.) == \" << mean(mypoisson) << endl;\n  cout << \"mean(mypoisson, 0.) == \" << mean(mypoisson) << endl;\n  cout << \"cdf(mypoisson, 2.) == \" << cdf(mypoisson, 2.) << endl;\n  cout << \"pdf(mypoisson, 2.) == \" << pdf(mypoisson, 2.) << endl;\n  \n  // poisson mydudpoisson(0.);\n  // throws (if BOOST_MATH_DOMAIN_ERROR_POLICY == throw_on_error).\n\n \n  BOOST_CHECK_THROW(poisson mydudpoisson(-1), std::domain_error);// Mean must be > 0.\n  BOOST_CHECK_THROW(poisson mydudpoisson(-1), std::logic_error);// Mean must be > 0.\n  // Passes the check because logic_error is a parent????\n  // BOOST_CHECK_THROW(poisson mydudpoisson(-1), std::overflow_error); // fails the check\n  // because overflow_error is unrelated - except from std::exception\n  BOOST_CHECK_THROW(cdf(mypoisson, -1), std::domain_error); // k must be >= 0\n\n  BOOST_CHECK_EQUAL(mean(mypoisson), 4.);\n  BOOST_CHECK_CLOSE(\n  pdf(mypoisson, 2.),  // k events = 2. \n    1.465251111098740E-001, // probability.\n      5e-13);\n\n  BOOST_CHECK_CLOSE(\n  cdf(mypoisson, 2.),  // k events = 2. \n    0.238103305553545, // probability.\n      5e-13);\n\n\n#if 0\n  // Compare cdf from finite sum of pdf and gamma_q.\n  using boost::math::cdf;\n  using boost::math::pdf;\n\n  double mean = 4.;\n  cout.precision(17); // double max_digits10\n  cout.setf(ios::showpoint);\n  cout << showpoint << endl;  // Ensure trailing zeros are shown.\n  // This also helps show the expected precision max_digits10\n  //cout.unsetf(ios::showpoint); // No trailing zeros are shown.\n\n  cout << \"k          pdf                     sum                  cdf                   diff\" << endl;\n  double sum = 0.;\n  for (int i = 0; i <= 50; i++)\n  {\n   cout << i << ' ' ;\n   double p =  pdf(poisson_distribution<double>(mean), static_cast<double>(i));\n   sum += p;\n\n   cout << p << ' ' << sum << ' ' \n   << cdf(poisson_distribution<double>(mean), static_cast<double>(i)) << ' ';\n     {\n       cout << boost::math::gamma_q<double>(i+1, mean); // cdf\n       double diff = boost::math::gamma_q<double>(i+1, mean) - sum; // cdf -sum\n       cout << setprecision (2) << ' ' << diff; // 0 0 to 4, 1 eps 5 to 9, 10 to 20 2 eps, 21 upwards 3 eps\n      \n     }\n    BOOST_CHECK_CLOSE(\n    cdf(mypoisson, static_cast<double>(i)),\n      sum, // of pdfs.\n      4e-14); // Fails at 2e-14\n   // This call puts the precision etc back to default 6 !!!\n   cout << setprecision(17) << showpoint;\n\n\n     cout << endl;\n  }\n\n   cout << cdf(poisson_distribution<double>(5), static_cast<double>(0)) << ' ' << endl; // 0.006737946999085467\n   cout << cdf(poisson_distribution<double>(5), static_cast<double>(1)) << ' ' << endl; // 0.040427681994512805\n   cout << cdf(poisson_distribution<double>(2), static_cast<double>(3)) << ' ' << endl; // 0.85712346049854715 \n\n   { // Compare approximate formula in Wikipedia with quantile(half)\n     for (int i = 1; i < 100; i++)\n     {\n       poisson_distribution<double> distn(static_cast<double>(i));\n       cout << i << ' ' << median(distn) << ' ' << quantile(distn, 0.5) << ' ' \n         << median(distn) - quantile(distn, 0.5) << endl; // formula appears to be out-by-one??\n     }  // so quantile(half) used via derived accressors.\n   }\n#endif\n\n   // (Parameter value, arbitrarily zero, only communicates the floating-point type).\n#ifdef TEST_POISSON\n  test_spots(0.0F); // Test float.\n#endif\n#ifdef TEST_DOUBLE\n  test_spots(0.0); // Test double.\n#endif\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n  if (numeric_limits<long double>::digits10 > numeric_limits<double>::digits10)\n  { // long double is better than double (so not MSVC where they are same).\n#ifdef TEST_LDOUBLE\n     test_spots(0.0L); // Test long double.\n#endif\n  }\n\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\n#ifdef TEST_REAL_CONCEPT\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\n#endif\n#endif\n#endif\n   \n} // BOOST_AUTO_TEST_CASE( test_main )\n\n/*\n\nOutput:\n\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\test_poisson.exe\"\nRunning 1 test case...\nmean(mypoisson, 4.) == 4.0000000000000000\nmean(mypoisson, 0.) == 4.0000000000000000\ncdf(mypoisson, 2.) == 0.23810330555354431\npdf(mypoisson, 2.) == 0.14652511110987343\n*** No errors detected\n\n*/\n", "meta": {"hexsha": "74133f233eaa552768bb0cc1bb70a1eb50e4c752", "size": 25659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_poisson.cpp", "max_stars_repo_name": "smart-make/boost", "max_stars_repo_head_hexsha": "46509a094f8a844eefd5bb8a0030b739a04d79e1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:55:56.000Z", "max_issues_repo_path": "libs/math/test/test_poisson.cpp", "max_issues_repo_name": "smart-make/boost", "max_issues_repo_head_hexsha": "46509a094f8a844eefd5bb8a0030b739a04d79e1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/test/test_poisson.cpp", "max_forks_repo_name": "smart-make/boost", "max_forks_repo_head_hexsha": "46509a094f8a844eefd5bb8a0030b739a04d79e1", "max_forks_repo_licenses": ["BSL-1.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.9234449761, "max_line_length": 135, "alphanum_fraction": 0.6725125687, "num_tokens": 7123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.5584084884302697}}
{"text": "#include <Eigen/Sparse>\n#include <vector>\n#include <cmath>\n#include <iostream>\n#include \"day05.hpp\"\n\n\ntypedef Eigen::SparseMatrix<int> SpMat;\n\nvoid add_line_to_grid(std::vector<int> &data_row, SpMat &grid, bool diagonal=true) {\n    int i, j, start, end;\n\n    int step_horiz = data_row[2] - data_row[0];\n    int step_verti = data_row[3] - data_row[1];\n    int sign_horiz = sign(step_horiz);\n    int sign_verti = sign(step_verti);\n\n    if ((!diagonal) && !((step_horiz == 0) || (step_verti == 0)))\n        return;\n\n    if (((step_horiz != 0) && (step_verti != 0)) &&\n            (std::abs(step_horiz) != std::abs(step_verti))) {\n        std::cout << \"Horiz step: \" << step_horiz;\n        std::cout << \"  Vertical step: \" << step_verti << std::endl;\n        throw std::runtime_error(\"APW: Your assumption isn't right!\");\n    }\n\n    int step = std::max(std::abs(step_horiz), std::abs(step_verti));\n    for (int k=0; k < (step+1); k++) {\n        i = sign_horiz * k * (step_horiz != 0) + data_row[0];\n        j = sign_verti * k * (step_verti != 0) + data_row[1];\n        grid.coeffRef(i, j) += 1;\n    }\n\n}\n\nint main(int argc, char** argv) {\n    std::cout << \"---------------- Day 05 ----------------\" << std::endl;\n\n    if (argc != 2)\n        throw std::runtime_error(\n            \"Invalid number of command-line arguments: Pass only the path to the data file\");\n\n    std::string datafile_path(argv[1]);\n    auto data = parse_file(datafile_path);\n\n    int grid_size = max(data) + 1;\n    // print_vector2d<int>(data);\n    std::cout << \"grid size: \" << grid_size << std::endl;\n\n    int num_2s;\n    SpMat grid_part1(grid_size, grid_size);\n    SpMat grid_part2(grid_size, grid_size);\n\n    // Part 1\n    for (auto row : data)\n        add_line_to_grid(row, grid_part1, false);\n\n    // std::cout << grid_part1 << std::endl;\n\n    num_2s = 0;\n    for (int i=0; i < grid_size; i++)\n        for (int j=0; j < grid_size; j++)\n            num_2s += (grid_part1.coeff(i, j) >= 2);\n    std::cout << \"Part 1 answer: \" << num_2s << std::endl;\n\n    std::cout << \"--------\" << std::endl;\n\n    // Part 2\n    for (auto row : data)\n        add_line_to_grid(row, grid_part2, true);\n\n    // std::cout << grid_part2 << std::endl;\n\n    num_2s = 0;\n    for (int i=0; i < grid_size; i++)\n        for (int j=0; j < grid_size; j++)\n            num_2s += (grid_part2.coeff(i, j) >= 2);\n    std::cout << \"Part 2 answer: \" << num_2s << std::endl;\n\n}\n", "meta": {"hexsha": "6f41a30386deb9ab899e4b8717d472b264b9ff6c", "size": 2411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "day05/day05.cpp", "max_stars_repo_name": "adrn/advent-of-code", "max_stars_repo_head_hexsha": "d36c274b5e8ed872ea302113bf8f772b666fb694", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-01T17:42:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T02:26:26.000Z", "max_issues_repo_path": "day05/day05.cpp", "max_issues_repo_name": "adrn/advent-of-code", "max_issues_repo_head_hexsha": "d36c274b5e8ed872ea302113bf8f772b666fb694", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day05/day05.cpp", "max_forks_repo_name": "adrn/advent-of-code", "max_forks_repo_head_hexsha": "d36c274b5e8ed872ea302113bf8f772b666fb694", "max_forks_repo_licenses": ["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.4024390244, "max_line_length": 93, "alphanum_fraction": 0.5578598092, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.5584084884302697}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n\n#include <Utils/Math/BSplines/BSpline.h>\n#include <Utils/Math/BSplines/Splitter.h>\n#include <gmock/gmock.h>\n#include <Eigen/Core>\n\nusing namespace testing;\nnamespace Scine {\nnamespace Utils {\nusing namespace BSplines;\nnamespace Tests {\n\nclass ABSplineSplitterTest : public Test {\n public:\n  unsigned p;\n  BSpline bs, bsLeft, bsRight;\n  Splitter bsSplitter;\n\n  void SetUp() override {\n  }\n};\n\nTEST_F(ABSplineSplitterTest, DisconnectednessDegree3) {\n  unsigned p = 3;\n  Eigen::MatrixXd controlPoints(5, 1);\n  controlPoints << 1, 2, 3, 4, 5;\n\n  Eigen::MatrixXd knotVector(9, 1);\n  knotVector << 0, 0, 0, 0, 0.5, 1, 1, 1, 1;\n\n  BSpline bs = BSpline(knotVector, controlPoints, p);\n\n  double uSplit = 0.5;\n  auto splitResult = bsSplitter.split(uSplit, bs, {false, false});\n\n  bsLeft = splitResult.first;\n  bsRight = splitResult.second;\n\n  Eigen::VectorXd knotVectorLeft = bsLeft.getKnotVector();\n  Eigen::MatrixXd controlPointsLeft = bsLeft.getControlPointMatrix();\n\n  Eigen::VectorXd knotVectorRight = bsRight.getKnotVector();\n  Eigen::MatrixXd controlPointsRight = bsRight.getControlPointMatrix();\n\n  Eigen::VectorXd refKnotVectorLeft;\n  refKnotVectorLeft.resize(8);\n  refKnotVectorLeft << 0, 0, 0, 0, 0.5, 0.5, 0.5, 0.5;\n  ASSERT_TRUE(knotVectorLeft.isApprox(refKnotVectorLeft));\n\n  Eigen::VectorXd refControlPointsLeft;\n  refControlPointsLeft.resize(4);\n  refControlPointsLeft << 1, 2, 2.5, 3;\n  ASSERT_TRUE(controlPointsLeft.isApprox(refControlPointsLeft));\n\n  Eigen::VectorXd refKnotVectorRight;\n  refKnotVectorRight.resize(8);\n  refKnotVectorRight << 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1;\n  ASSERT_TRUE(knotVectorRight.isApprox(refKnotVectorRight));\n\n  Eigen::VectorXd refControlPointsRight;\n  refControlPointsRight.resize(4);\n  refControlPointsRight << 3, 3.5, 4, 5;\n  ASSERT_TRUE(controlPointsRight.isApprox(refControlPointsRight));\n}\n\nTEST_F(ABSplineSplitterTest, Multiplicity0Degree3) {\n  unsigned p = 3;\n  Eigen::MatrixXd controlPoints(5, 1);\n  controlPoints << 1, 2, 3, 4, 5;\n\n  Eigen::MatrixXd knotVector(9, 1);\n  knotVector << 0, 0, 0, 0, 0.5, 1, 1, 1, 1;\n\n  BSpline bs = BSpline(knotVector, controlPoints, p);\n\n  double uSplit = 0.75;\n  auto splitResult = bsSplitter.split(uSplit, bs, {false, false});\n\n  bsLeft = splitResult.first;\n  bsRight = splitResult.second;\n\n  Eigen::VectorXd knotVectorLeft = bsLeft.getKnotVector();\n  Eigen::MatrixXd controlPointsLeft = bsLeft.getControlPointMatrix();\n\n  Eigen::VectorXd knotVectorRight = bsRight.getKnotVector();\n  Eigen::MatrixXd controlPointsRight = bsRight.getControlPointMatrix();\n\n  Eigen::VectorXd refKnotVectorLeft;\n  refKnotVectorLeft.resize(9);\n  refKnotVectorLeft << 0, 0, 0, 0, 0.5, 0.75, 0.75, 0.75, 0.75;\n  ASSERT_TRUE(knotVectorLeft.isApprox(refKnotVectorLeft));\n\n  Eigen::VectorXd refControlPointsLeft;\n  refControlPointsLeft.resize(5);\n  refControlPointsLeft << 1, 2, 2.75, 3.5, 3.8125;\n  ASSERT_TRUE(controlPointsLeft.isApprox(refControlPointsLeft));\n\n  Eigen::VectorXd refKnotVectorRight;\n  refKnotVectorRight.resize(8);\n  refKnotVectorRight << 0.75, 0.75, 0.75, 0.75, 1, 1, 1, 1;\n  ASSERT_TRUE(knotVectorRight.isApprox(refKnotVectorRight));\n\n  Eigen::VectorXd refControlPointsRight;\n  refControlPointsRight.resize(4);\n  refControlPointsRight << 3.8125, 4.125, 4.5, 5;\n  ASSERT_TRUE(controlPointsRight.isApprox(refControlPointsRight));\n}\n\nTEST_F(ABSplineSplitterTest, DisconnectednessDegree1) {\n  unsigned p = 1;\n  Eigen::MatrixXd controlPoints(5, 1);\n  controlPoints << 1, 2, 3, 4, 5;\n\n  Eigen::MatrixXd knotVector(7, 1);\n  knotVector << 0, 0, 0.25, 0.5, 0.75, 1, 1;\n\n  BSpline bs = BSpline(knotVector, controlPoints, p);\n\n  double uSplit = 0.5;\n  auto splitResult = bsSplitter.split(uSplit, bs, {false, false});\n\n  bsLeft = splitResult.first;\n  bsRight = splitResult.second;\n\n  Eigen::VectorXd knotVectorLeft = bsLeft.getKnotVector();\n  Eigen::MatrixXd controlPointsLeft = bsLeft.getControlPointMatrix();\n\n  Eigen::VectorXd knotVectorRight = bsRight.getKnotVector();\n  Eigen::MatrixXd controlPointsRight = bsRight.getControlPointMatrix();\n\n  Eigen::VectorXd refKnotVectorLeft;\n  refKnotVectorLeft.resize(5);\n  refKnotVectorLeft << 0, 0, 0.25, 0.5, 0.5;\n  ASSERT_TRUE(knotVectorLeft.isApprox(refKnotVectorLeft));\n\n  Eigen::VectorXd refControlPointsLeft;\n  refControlPointsLeft.resize(3);\n  refControlPointsLeft << 1, 2, 3;\n  ASSERT_TRUE(controlPointsLeft.isApprox(refControlPointsLeft));\n\n  Eigen::VectorXd refKnotVectorRight;\n  refKnotVectorRight.resize(5);\n  refKnotVectorRight << 0.5, 0.5, 0.75, 1, 1;\n  ASSERT_TRUE(knotVectorRight.isApprox(refKnotVectorRight));\n\n  Eigen::VectorXd refControlPointsRight;\n  refControlPointsRight.resize(3);\n  refControlPointsRight << 3, 4, 5;\n  ASSERT_TRUE(controlPointsRight.isApprox(refControlPointsRight));\n}\n\n} // namespace Tests\n} // namespace Utils\n} // namespace Scine", "meta": {"hexsha": "f79c5b93b21feecb2e0661708ff404575a4bfe4c", "size": 4995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Tests/Math/BSplines/BSplineSplitterTest.cpp", "max_stars_repo_name": "qcscine/utilities", "max_stars_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Tests/Math/BSplines/BSplineSplitterTest.cpp", "max_issues_repo_name": "qcscine/utilities", "max_issues_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-19T14:34:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:07:18.000Z", "max_forks_repo_path": "src/Utils/Tests/Math/BSplines/BSplineSplitterTest.cpp", "max_forks_repo_name": "qcscine/utilities", "max_forks_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T16:44:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T20:48:19.000Z", "avg_line_length": 31.21875, "max_line_length": 85, "alphanum_fraction": 0.7375375375, "num_tokens": 1563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619632, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.55831682277103}}
{"text": "#include <iostream>\n#include <pcl/io/pcd_io.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/search/kdtree.h>\n#include <pcl/search/impl/kdtree.hpp>\n\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <geometry_msgs/Vector3.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Eigen>\n#include <math.h>\n#include <random>\n\nusing namespace std;\nusing namespace Eigen;\n\nros::Publisher _all_map_pub;\n\nint _obs_num, _cir_num;\ndouble _x_size, _y_size, _z_size, _init_x, _init_y, _resolution, _sense_rate;\ndouble _x_l, _x_h, _y_l, _y_h, _w_l, _w_h, _h_l, _h_h, _w_c_l, _w_c_h;\n\nbool _has_map  = false;\n\nsensor_msgs::PointCloud2 globalMap_pcd;\npcl::PointCloud<pcl::PointXYZ> cloudMap;\n\npcl::search::KdTree<pcl::PointXYZ> kdtreeMap;\nvector<int>     pointIdxSearch;\nvector<float>   pointSquaredDistance;      \n\nvoid RandomMapGenerate()\n{  \n   random_device rd;\n   default_random_engine eng(rd());\n   \n   uniform_real_distribution<double> rand_x = uniform_real_distribution<double>(_x_l, _x_h );\n   uniform_real_distribution<double> rand_y = uniform_real_distribution<double>(_y_l, _y_h );\n   uniform_real_distribution<double> rand_w = uniform_real_distribution<double>(_w_l, _w_h);\n   uniform_real_distribution<double> rand_h = uniform_real_distribution<double>(_h_l, _h_h);\n\n   uniform_real_distribution<double> rand_x_circle = uniform_real_distribution<double>(_x_l + 1.0, _x_h - 1.0);\n   uniform_real_distribution<double> rand_y_circle = uniform_real_distribution<double>(_y_l + 1.0, _y_h - 1.0);\n   uniform_real_distribution<double> rand_r_circle = uniform_real_distribution<double>(_w_c_l    , _w_c_h    );\n\n   uniform_real_distribution<double> rand_roll      = uniform_real_distribution<double>(- M_PI,     + M_PI);\n   uniform_real_distribution<double> rand_pitch     = uniform_real_distribution<double>(+ M_PI/4.0, + M_PI/2.0);\n   uniform_real_distribution<double> rand_yaw       = uniform_real_distribution<double>(+ M_PI/4.0, + M_PI/2.0);\n   uniform_real_distribution<double> rand_ellipse_c = uniform_real_distribution<double>(0.5, 2.0);\n   uniform_real_distribution<double> rand_num       = uniform_real_distribution<double>(0.0, 1.0);\n\n   pcl::PointXYZ pt_random;\n\n   // firstly, we put some circles\n   for(int i = 0; i < _cir_num; i ++)\n   {\n      double x0, y0, z0, R;\n      std::vector<Vector3d> circle_set;\n\n      x0   = rand_x_circle(eng);\n      y0   = rand_y_circle(eng);\n      z0   = rand_h(eng) / 2.0;  \n      R    = rand_r_circle(eng);\n\n      if(sqrt( pow(x0-_init_x, 2) + pow(y0-_init_y, 2) ) < 2.0 ) \n         continue;\n\n      double a, b;\n      a = rand_ellipse_c(eng);\n      b = rand_ellipse_c(eng);\n\n      double x, y, z;\n      Vector3d pt3, pt3_rot;\n      for(double theta = -M_PI; theta < M_PI; theta += 0.025)\n      {  \n         x = a * cos(theta) * R;\n         y = b * sin(theta) * R;\n         z = 0;\n         pt3 << x, y, z;\n         circle_set.push_back(pt3);\n      }\n      // Define a random 3d rotation matrix\n      Matrix3d Rot;\n      double roll,  pitch, yaw;\n      double alpha, beta,  gama;\n      roll  = rand_roll(eng); // alpha\n      pitch = rand_pitch(eng); // beta\n      yaw   = rand_yaw(eng); // gama\n\n      alpha = roll;\n      beta  = pitch;\n      gama  = yaw;\n\n      double p = rand_num(eng);\n      if(p < 0.5)\n      {\n         beta = M_PI / 2.0;\n         gama = M_PI / 2.0;\n      }\n\n      Rot << cos(alpha) * cos(gama)  - cos(beta) * sin(alpha) * sin(gama), - cos(beta) * cos(gama) * sin(alpha) - cos(alpha) * sin(gama),   sin(alpha) * sin(beta),\n             cos(gama)  * sin(alpha) + cos(alpha) * cos(beta) * sin(gama),   cos(alpha) * cos(beta) * cos(gama) - sin(alpha) * sin(gama), - cos(alpha) * sin(beta),        \n             sin(beta)  * sin(gama),                                         cos(gama) * sin(beta),                                         cos(beta);\n\n      for(auto pt: circle_set)\n      {\n         pt3_rot = Rot * pt;\n         pt_random.x = pt3_rot(0) + x0 + 0.001;\n         pt_random.y = pt3_rot(1) + y0 + 0.001;\n         pt_random.z = pt3_rot(2) + z0 + 0.001;\n\n         if(pt_random.z >= 0.0)\n            cloudMap.points.push_back( pt_random );\n      }\n   }\n\n   bool is_kdtree_empty = false;\n   if(cloudMap.points.size() > 0)\n      kdtreeMap.setInputCloud( cloudMap.makeShared() ); \n   else\n      is_kdtree_empty = true;\n\n   // then, we put some pilar\n   for(int i = 0; i < _obs_num; i ++)\n   {\n      double x, y, w, h; \n      x    = rand_x(eng);\n      y    = rand_y(eng);\n      w    = rand_w(eng);\n\n      //if(sqrt( pow(x - _init_x, 2) + pow(y - _init_y, 2) ) < 2.0 ) \n      if(sqrt( pow(x - _init_x, 2) + pow(y - _init_y, 2) ) < 0.8 ) \n         continue;\n      \n      pcl::PointXYZ searchPoint(x, y, (_h_l + _h_h)/2.0);\n      pointIdxSearch.clear();\n      pointSquaredDistance.clear();\n      \n      if(is_kdtree_empty == false)\n      {\n         if ( kdtreeMap.nearestKSearch (searchPoint, 1, pointIdxSearch, pointSquaredDistance) > 0 )\n         {\n            if(sqrt(pointSquaredDistance[0]) < 1.0 )\n               continue;\n         }\n      }\n\n      x = floor(x/_resolution) * _resolution + _resolution / 2.0;\n      y = floor(y/_resolution) * _resolution + _resolution / 2.0;\n\n      int widNum = ceil(w/_resolution);\n      for(int r = -widNum/2.0; r < widNum/2.0; r ++ )\n      {\n         for(int s = -widNum/2.0; s < widNum/2.0; s ++ )\n         {\n            h    = rand_h(eng);  \n            int heiNum = 2.0 * ceil(h/_resolution);\n            for(int t = 0; t < heiNum; t ++ ){\n               pt_random.x = x + (r+0.0) * _resolution + 0.001;\n               pt_random.y = y + (s+0.0) * _resolution + 0.001;\n               pt_random.z =     (t+0.0) * _resolution * 0.5 + 0.001;\n               cloudMap.points.push_back( pt_random );\n            }\n         }\n      }\n   }\n\n   cloudMap.width = cloudMap.points.size();\n   cloudMap.height = 1;\n   cloudMap.is_dense = true;\n\n   _has_map = true;\n   \n   pcl::toROSMsg(cloudMap, globalMap_pcd);\n   globalMap_pcd.header.frame_id = \"world\";\n}\n\nvoid pubSensedPoints()\n{     \n   if( !_has_map ) return;\n\n   _all_map_pub.publish(globalMap_pcd);\n}\n\nint main (int argc, char** argv) \n{        \n   ros::init (argc, argv, \"random_complex_scene\");\n   ros::NodeHandle n( \"~\" );\n\n   _all_map_pub   = n.advertise<sensor_msgs::PointCloud2>(\"global_map\", 1);                      \n\n   n.param(\"init_state_x\", _init_x,       0.0);\n   n.param(\"init_state_y\", _init_y,       0.0);\n\n   n.param(\"map/x_size\",  _x_size, 50.0);\n   n.param(\"map/y_size\",  _y_size, 50.0);\n   n.param(\"map/z_size\",  _z_size, 5.0 );\n\n   n.param(\"map/obs_num\",    _obs_num,  30);\n   n.param(\"map/circle_num\", _cir_num,  30);\n   n.param(\"map/resolution\", _resolution, 0.2);\n\n   n.param(\"ObstacleShape/lower_rad\", _w_l,   0.3);\n   n.param(\"ObstacleShape/upper_rad\", _w_h,   0.8);\n   n.param(\"ObstacleShape/lower_hei\", _h_l,   3.0);\n   n.param(\"ObstacleShape/upper_hei\", _h_h,   7.0);\n\n   n.param(\"CircleShape/lower_circle_rad\", _w_c_l, 0.3);\n   n.param(\"CircleShape/upper_circle_rad\", _w_c_h, 0.8);\n\n   n.param(\"sensing/rate\", _sense_rate, 1.0);\n\n   _x_l = - _x_size / 2.0;\n   _x_h = + _x_size / 2.0;\n\n   _y_l = - _y_size / 2.0;\n   _y_h = + _y_size / 2.0;\n\n   RandomMapGenerate();\n   ros::Rate loop_rate(_sense_rate);\n   while (ros::ok())\n   {\n      pubSensedPoints();\n      ros::spinOnce();\n      loop_rate.sleep();\n   }\n}", "meta": {"hexsha": "7b51e8d7298449295bcfd06e9daa0c8f41558c95", "size": 7463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hw_2/ros_code/catkin_ws_ch2/src/grid_path_searcher/src/random_complex_generator.cpp", "max_stars_repo_name": "zhuoqun-chen/shenlan_motion_planning", "max_stars_repo_head_hexsha": "04b4e9130345ead167f7e9d63c7c6f696e73bdc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 119.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:54:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:03:50.000Z", "max_issues_repo_path": "chap4/chap_sub/Q2/grid_path_searcher/src/random_complex_generator.cpp", "max_issues_repo_name": "arnoldcheng1/Motion-Planning-Course", "max_issues_repo_head_hexsha": "f8c0d551beb8d25a169f3b998a0d7d0d4a720f2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-02T08:28:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-02T08:28:49.000Z", "max_forks_repo_path": "chap4/chap_sub/Q2/grid_path_searcher/src/random_complex_generator.cpp", "max_forks_repo_name": "arnoldcheng1/Motion-Planning-Course", "max_forks_repo_head_hexsha": "f8c0d551beb8d25a169f3b998a0d7d0d4a720f2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2019-10-22T12:08:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:39:27.000Z", "avg_line_length": 32.0300429185, "max_line_length": 171, "alphanum_fraction": 0.5970789227, "num_tokens": 2321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5583168132765552}}
{"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": "//  (C) Copyright Jeremy Murphy 2015.\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/config.hpp>\r\n#define BOOST_TEST_MAIN\r\n#include <boost/array.hpp>\r\n#include <boost/math/tools/polynomial.hpp>\r\n#include <boost/math/common_factor_rt.hpp>\r\n#include <boost/mpl/list.hpp>\r\n#include <boost/mpl/joint_view.hpp>\r\n#include <boost/test/test_case_template.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <boost/multiprecision/cpp_bin_float.hpp>\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\n#include <utility>\r\n\r\nusing namespace boost::math::tools;\r\nusing namespace std;\r\n\r\ntemplate <typename T>\r\nstruct answer\r\n{\r\n    answer(std::pair< polynomial<T>, polynomial<T> > const &x) :\r\n    quotient(x.first), remainder(x.second) {}\r\n    \r\n    polynomial<T> quotient;\r\n    polynomial<T> remainder;\r\n};\r\n\r\nboost::array<double, 4> const d3a = {{10, -6, -4, 3}};\r\nboost::array<double, 4> const d3b = {{-7, 5, 6, 1}};\r\nboost::array<double, 4> const d3c = {{10.0/3.0, -2.0, -4.0/3.0, 1.0}};\r\nboost::array<double, 2> const d1a = {{-2, 1}};\r\nboost::array<double, 3> const d2a = {{-2, 2, 3}};\r\nboost::array<double, 3> const d2b = {{-7, 5, 6}};\r\nboost::array<double, 3> const d2c = {{31, -21, -22}};\r\nboost::array<double, 1> const d0a = {{6}};\r\nboost::array<double, 2> const d0a1 = {{0, 6}};\r\nboost::array<double, 6> const d0a5 = {{0, 0, 0, 0, 0, 6}};\r\nboost::array<double, 1> const d0b = {{3}};\r\n\r\nboost::array<int, 9> const d8 = {{-5, 2, 8, -3, -3, 0, 1, 0, 1}};\r\nboost::array<int, 9> const d8b = {{0, 2, 8, -3, -3, 0, 1, 0, 1}};\r\nboost::array<int, 7> const d6 = {{21, -9, -4, 0, 5, 0, 3}};\r\nboost::array<int, 3> const d2 = {{-6, 0, 9}};\r\nboost::array<int, 6> const d5 = {{-9, 0, 3, 0, -15}};\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_construction )\r\n{\r\n    polynomial<double> const a(d3a.begin(), d3a.end());\r\n    polynomial<double> const b(d3a.begin(), 3);\r\n    BOOST_CHECK_EQUAL(a, b);\r\n}\r\n\r\n\r\n#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST) && !BOOST_WORKAROUND(BOOST_GCC_VERSION, < 40500)\r\nBOOST_AUTO_TEST_CASE( test_initializer_list_construction )\r\n{\r\n    polynomial<double> a(begin(d3a), end(d3a));\r\n    polynomial<double> b = {10, -6, -4, 3};\r\n    polynomial<double> c{{10, -6, -4, 3}};\r\n    polynomial<double> d{{10, -6, -4, 3, 0, 0}};\r\n    BOOST_CHECK_EQUAL(a, b);\r\n    BOOST_CHECK_EQUAL(b, c);\r\n    BOOST_CHECK_EQUAL(d.degree(), 3u);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_initializer_list_assignment )\r\n{\r\n    polynomial<double> a(begin(d3a), end(d3a));\r\n    polynomial<double> b;\r\n    b = {10, -6, -4, 3, 0, 0};\r\n    BOOST_CHECK_EQUAL(b.degree(), 3u);\r\n    BOOST_CHECK_EQUAL(a, b);\r\n}\r\n#endif\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_degree )\r\n{\r\n    polynomial<double> const zero;\r\n    polynomial<double> const a(d3a.begin(), d3a.end());\r\n    BOOST_CHECK_THROW(zero.degree(), std::logic_error);\r\n    BOOST_CHECK_EQUAL(a.degree(), 3u);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_division_over_field )\r\n{\r\n    polynomial<double> const a(d3a.begin(), d3a.end());\r\n    polynomial<double> const b(d1a.begin(), d1a.end());\r\n    polynomial<double> const q(d2a.begin(), d2a.end());\r\n    polynomial<double> const r(d0a.begin(), d0a.end());\r\n    polynomial<double> const c(d3b.begin(), d3b.end());\r\n    polynomial<double> const d(d2b.begin(), d2b.end());\r\n    polynomial<double> const e(d2c.begin(), d2c.end());\r\n    polynomial<double> const f(d0b.begin(), d0b.end());\r\n    polynomial<double> const g(d3c.begin(), d3c.end());\r\n    polynomial<double> const zero;\r\n    polynomial<double> const one(1.0);\r\n\r\n    answer<double> result = quotient_remainder(a, b);\r\n    BOOST_CHECK_EQUAL(result.quotient, q);\r\n    BOOST_CHECK_EQUAL(result.remainder, r);\r\n    BOOST_CHECK_EQUAL(a, q * b + r); // Sanity check.\r\n    \r\n    result = quotient_remainder(a, c);\r\n    BOOST_CHECK_EQUAL(result.quotient, f);\r\n    BOOST_CHECK_EQUAL(result.remainder, e);\r\n    BOOST_CHECK_EQUAL(a, f * c + e); // Sanity check.\r\n    \r\n    result = quotient_remainder(a, f);\r\n    BOOST_CHECK_EQUAL(result.quotient, g);\r\n    BOOST_CHECK_EQUAL(result.remainder, zero);\r\n    BOOST_CHECK_EQUAL(a, g * f + zero); // Sanity check.\r\n    // Check that division by a regular number gives the same result.\r\n    BOOST_CHECK_EQUAL(a / 3.0, g);\r\n    BOOST_CHECK_EQUAL(a % 3.0, zero);\r\n\r\n    // Sanity checks.\r\n    BOOST_CHECK_EQUAL(a / a, one);\r\n    BOOST_CHECK_EQUAL(a % a, zero);\r\n    // BOOST_CHECK_EQUAL(zero / zero, zero); // TODO\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_division_over_ufd )\r\n{\r\n    polynomial<int> const zero;\r\n    polynomial<int> const one(1);\r\n    polynomial<int> const aa(d8.begin(), d8.end());\r\n    polynomial<int> const bb(d6.begin(), d6.end());\r\n    polynomial<int> const q(d2.begin(), d2.end());\r\n    polynomial<int> const r(d5.begin(), d5.end());\r\n    \r\n    answer<int> result = quotient_remainder(aa, bb);\r\n    BOOST_CHECK_EQUAL(result.quotient, q);\r\n    BOOST_CHECK_EQUAL(result.remainder, r);\r\n\r\n    // Sanity checks.\r\n    BOOST_CHECK_EQUAL(aa / aa, one);\r\n    BOOST_CHECK_EQUAL(aa % aa, zero);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_gcd )\r\n{\r\n    /* NOTE: Euclidean gcd is not yet customized to return THE greatest \r\n     * common polynomial divisor. If d is THE greatest common divisior of u and\r\n     * v, then gcd(u, v) will return d or -d according to the algorithm.\r\n     * By convention, it should return d, as for example Maxima and Wolfram \r\n     * Alpha do.\r\n     * This test is an example of the fact that it returns -d.\r\n     */\r\n    boost::array<double, 9> const d8 = {{105, 278, -88, -56, 16}};\r\n    boost::array<double, 7> const d6 = {{70, 232, -44, -64, 16}};\r\n    boost::array<double, 7> const d2 = {{-35, 24, -4}};\r\n    polynomial<double> const u(d8.begin(), d8.end());\r\n    polynomial<double> const v(d6.begin(), d6.end());\r\n    polynomial<double> const w(d2.begin(), d2.end());\r\n    polynomial<double> const d = boost::math::gcd(u, v);\r\n    BOOST_CHECK_EQUAL(w, d);\r\n}\r\n\r\n// Sanity checks to make sure I didn't break it.\r\ntypedef boost::mpl::list<int, long\r\n#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1500)\r\n   , boost::multiprecision::cpp_int\r\n#endif\r\n> integral_test_types;\r\ntypedef boost::mpl::list<double\r\n#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1500)\r\n   , boost::multiprecision::cpp_rational, boost::multiprecision::cpp_bin_float_single, boost::multiprecision::cpp_dec_float_50\r\n#endif\r\n> non_integral_test_types;\r\ntypedef boost::mpl::joint_view<integral_test_types, non_integral_test_types> all_test_types;\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_addition, T, all_test_types )\r\n{\r\n    polynomial<T> const a(d3a.begin(), d3a.end());\r\n    polynomial<T> const b(d1a.begin(), d1a.end());\r\n    polynomial<T> const zero;\r\n    \r\n    polynomial<T> result = a + b; // different degree\r\n    boost::array<T, 4> tmp = {{8, -5, -4, 3}};\r\n    polynomial<T> expected(tmp.begin(), tmp.end());\r\n    BOOST_CHECK_EQUAL(result, expected);\r\n    BOOST_CHECK_EQUAL(a + zero, a);\r\n    BOOST_CHECK_EQUAL(a + b, b + a);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_subtraction, T, all_test_types )\r\n{\r\n    polynomial<T> const a(d3a.begin(), d3a.end());\r\n    polynomial<T> const zero;\r\n\r\n    BOOST_CHECK_EQUAL(a - T(0), a);\r\n    BOOST_CHECK_EQUAL(T(0) - a, -a);\r\n    BOOST_CHECK_EQUAL(a - zero, a);\r\n    BOOST_CHECK_EQUAL(zero - a, -a);\r\n    BOOST_CHECK_EQUAL(a - a, zero);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_multiplication, T, all_test_types )\r\n{\r\n    polynomial<T> const a(d3a.begin(), d3a.end());\r\n    polynomial<T> const b(d1a.begin(), d1a.end());\r\n    polynomial<T> const zero;\r\n    boost::array<T, 7> const d3a_sq = {{100, -120, -44, 108, -20, -24, 9}};\r\n    polynomial<T> const a_sq(d3a_sq.begin(), d3a_sq.end());\r\n    \r\n    BOOST_CHECK_EQUAL(a * T(0), zero);\r\n    BOOST_CHECK_EQUAL(a * zero, zero);\r\n    BOOST_CHECK_EQUAL(zero * T(0), zero);\r\n    BOOST_CHECK_EQUAL(zero * zero, zero);\r\n    BOOST_CHECK_EQUAL(a * b, b * a);\r\n    polynomial<T> aa(a);\r\n    aa *= aa;\r\n    BOOST_CHECK_EQUAL(aa, a_sq);\r\n    BOOST_CHECK_EQUAL(aa, a * a);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_arithmetic_relations, T, all_test_types )\r\n{\r\n    polynomial<T> const a(d8b.begin(), d8b.end());\r\n    polynomial<T> const b(d1a.begin(), d1a.end());\r\n\r\n    BOOST_CHECK_EQUAL(a * T(2), a + a);\r\n    BOOST_CHECK_EQUAL(a - b, -b + a);\r\n    BOOST_CHECK_EQUAL(a, (a * a) / a);\r\n    BOOST_CHECK_EQUAL(a, (a / a) * a);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_non_integral_arithmetic_relations, T, non_integral_test_types )\r\n{\r\n    polynomial<T> const a(d8b.begin(), d8b.end());\r\n    polynomial<T> const b(d1a.begin(), d1a.end());\r\n    \r\n    BOOST_CHECK_EQUAL(a * T(0.5), a / T(2));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_self_multiply_assign, T, all_test_types )\r\n{\r\n    polynomial<T> a(d3a.begin(), d3a.end());\r\n    polynomial<T> const b(a);\r\n    boost::array<double, 7> const d3a_sq = {{100, -120, -44, 108, -20, -24, 9}};\r\n    polynomial<T> const asq(d3a_sq.begin(), d3a_sq.end());\r\n\r\n    a *= a;\r\n\r\n    BOOST_CHECK_EQUAL(a, b*b);\r\n    BOOST_CHECK_EQUAL(a, asq);\r\n\r\n    a *= a;\r\n\r\n    BOOST_CHECK_EQUAL(a, b*b*b*b);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_right_shift, T, all_test_types )\r\n{\r\n    polynomial<T> a(d8b.begin(), d8b.end());\r\n    polynomial<T> const aa(a);\r\n    polynomial<T> const b(d8b.begin() + 1, d8b.end());\r\n    polynomial<T> const c(d8b.begin() + 5, d8b.end());\r\n    a >>= 0u;\r\n    BOOST_CHECK_EQUAL(a, aa);\r\n    a >>= 1u;\r\n    BOOST_CHECK_EQUAL(a, b);\r\n    a = a >> 4u;\r\n    BOOST_CHECK_EQUAL(a, c);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_left_shift, T, all_test_types )\r\n{\r\n    polynomial<T> a(d0a.begin(), d0a.end());\r\n    polynomial<T> const aa(a);\r\n    polynomial<T> const b(d0a1.begin(), d0a1.end());\r\n    polynomial<T> const c(d0a5.begin(), d0a5.end());\r\n    a <<= 0u;\r\n    BOOST_CHECK_EQUAL(a, aa);    \r\n    a <<= 1u;\r\n    BOOST_CHECK_EQUAL(a, b);\r\n    a = a << 4u;\r\n    BOOST_CHECK_EQUAL(a, c);\r\n    polynomial<T> zero;\r\n    // Multiplying zero by x should still be zero.\r\n    zero <<= 1u;\r\n    BOOST_CHECK_EQUAL(zero, zero_element(multiplies< polynomial<T> >()));\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_odd_even, T, all_test_types)\r\n{\r\n    polynomial<T> const zero;\r\n    BOOST_CHECK_EQUAL(odd(zero), false);\r\n    BOOST_CHECK_EQUAL(even(zero), true);\r\n    polynomial<T> const a(d0a.begin(), d0a.end());\r\n    BOOST_CHECK_EQUAL(odd(a), true);\r\n    BOOST_CHECK_EQUAL(even(a), false);\r\n    polynomial<T> const b(d0a1.begin(), d0a1.end());\r\n    BOOST_CHECK_EQUAL(odd(b), false);\r\n    BOOST_CHECK_EQUAL(even(b), true);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_pow, T, all_test_types )\r\n{\r\n    polynomial<T> a(d3a.begin(), d3a.end());\r\n    polynomial<T> const one(T(1));\r\n    boost::array<double, 7> const d3a_sqr = {{100, -120, -44, 108, -20, -24, 9}};\r\n    boost::array<double, 10> const d3a_cub =\r\n        {{1000, -1800, -120, 2124, -1032, -684, 638, -18, -108, 27}};\r\n    polynomial<T> const asqr(d3a_sqr.begin(), d3a_sqr.end());\r\n    polynomial<T> const acub(d3a_cub.begin(), d3a_cub.end());\r\n\r\n    BOOST_CHECK_EQUAL(pow(a, 0), one);\r\n    BOOST_CHECK_EQUAL(pow(a, 1), a);\r\n    BOOST_CHECK_EQUAL(pow(a, 2), asqr);\r\n    BOOST_CHECK_EQUAL(pow(a, 3), acub);\r\n    BOOST_CHECK_EQUAL(pow(a, 4), pow(asqr, 2));\r\n    BOOST_CHECK_EQUAL(pow(a, 5), asqr * acub);\r\n    BOOST_CHECK_EQUAL(pow(a, 6), pow(acub, 2));\r\n    BOOST_CHECK_EQUAL(pow(a, 7), acub * acub * a);\r\n\r\n    BOOST_CHECK_THROW(pow(a, -1), std::domain_error);\r\n    BOOST_CHECK_EQUAL(pow(one, 137), one);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_bool, T, all_test_types)\r\n{\r\n    polynomial<T> const zero;\r\n    polynomial<T> const a(d0a.begin(), d0a.end());\r\n    BOOST_CHECK_EQUAL(bool(zero), false);\r\n    BOOST_CHECK_EQUAL(bool(a), true);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_set_zero, T, all_test_types)\r\n{\r\n    polynomial<T> const zero;\r\n    polynomial<T> a(d0a.begin(), d0a.end());\r\n    a.set_zero();\r\n    BOOST_CHECK_EQUAL(a, zero);\r\n    a.set_zero(); // Ensure that setting zero to zero is a no-op.\r\n    BOOST_CHECK_EQUAL(a, zero);\r\n}\r\n", "meta": {"hexsha": "16e994ae6c680330b72072bcc2932480ba1bf8c0", "size": 12059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_polynomial.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/math/test/test_polynomial.cpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/math/test/test_polynomial.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": 34.1614730878, "max_line_length": 127, "alphanum_fraction": 0.6369516544, "num_tokens": 3572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5581513505174606}}
{"text": "#include \"visualization/constant-velocity-smoother.h\"\n\n#include <chrono>\n\n#include <Eigen/Dense>\n#include <glog/logging.h>\n#include <maplab-common/conversions.h>\n\nDEFINE_double(\n    pose_smoother_cutoff_frequency, 40,\n    \"Cutoff frequency for the \"\n    \"velocity smoothing [Hz].\");\n\nnamespace visualization {\nConstantVelocitySmoother::ConstantVelocitySmoother()\n    : ConstantVelocitySmoother(FLAGS_pose_smoother_cutoff_frequency) {}\n\nConstantVelocitySmoother::ConstantVelocitySmoother(double cutoff_frequency)\n    : cutoff_frequency_(cutoff_frequency),\n      is_initialized_(false),\n      n_samples_(0),\n      filtered_position_(Eigen::Vector3d::Constant(0.0)),\n      filtered_velocity_(Eigen::Vector3d::Constant(0.0)),\n      last_sample_(Eigen::Vector3d::Constant(0.0)) {\n  CHECK_GT(cutoff_frequency_, 0.0);\n  time_constant_ = 1. / (2. * M_PI * cutoff_frequency_);\n}\nvoid ConstantVelocitySmoother::addSample(const Eigen::Vector3d& sample) {\n  if (!is_initialized_) {\n    filtered_position_ = sample;\n    last_sample_ = sample;\n    is_initialized_ = true;\n    last_time_ = steady_clock::now();\n    ++n_samples_;\n    return;\n  }\n\n  using std::chrono::duration_cast;\n  steady_clock::time_point current = steady_clock::now();\n  double delta_t_seconds =\n      kMilliSecondsToSeconds *\n      duration_cast<std::chrono::milliseconds>(current - last_time_).count();\n  last_time_ = current;\n\n  if (delta_t_seconds == 0.0) {\n    return;\n  }\n\n  Eigen::Vector3d current_velocity = (sample - last_sample_) / delta_t_seconds;\n\n  double alpha = delta_t_seconds / (time_constant_ + delta_t_seconds);\n  filtered_velocity_ =\n      alpha * current_velocity + (1. - alpha) * filtered_velocity_;\n\n  Eigen::Vector3d predicted_position =\n      filtered_position_ + filtered_velocity_ * delta_t_seconds;\n  filtered_position_ = alpha * sample + (1. - alpha) * predicted_position;\n\n  ++n_samples_;\n  last_sample_ = sample;\n}\n\nconst Eigen::Vector3d& ConstantVelocitySmoother::getCurrentPosition() const {\n  return filtered_position_;\n}\n}  // namespace visualization\n", "meta": {"hexsha": "92c1aa19e1b6f83b4efe48678b82bbef4f2856b6", "size": 2042, "ext": "cc", "lang": "C++", "max_stars_repo_path": "visualization/src/constant-velocity-smoother.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": "visualization/src/constant-velocity-smoother.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": "visualization/src/constant-velocity-smoother.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": 30.4776119403, "max_line_length": 79, "alphanum_fraction": 0.7350636631, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5581513505174606}}
{"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 <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <iostream>\n#include <memory>\n\n#include \"incidencematrices.h\"\n\nint main() {\n  // Step 0: Create demo mesh\n  std::cout << \"Creating demo mesh from exercise sheet.. \";\n  std::shared_ptr<lf::mesh::Mesh> demoMesh =\n      IncidenceMatrices::createDemoMesh();\n  std::cout << \"Done!\\n\\n\";\n\n  // Step 1: Compute and print matrix G\n  std::cout << \"Computing matrix G.. \";\n  Eigen::SparseMatrix<int> G =\n      IncidenceMatrices::computeEdgeVertexIncidenceMatrix(*demoMesh);\n  std::cout << \"Done!\\n\";\n  std::cout << \"G = \\n\" << Eigen::MatrixXi(G) << \"\\n\\n\";\n\n  // Step 2: Compute and print matrix D\n  std::cout << \"Computing matrix D.. \";\n  Eigen::SparseMatrix<int> D =\n      IncidenceMatrices::computeCellEdgeIncidenceMatrix(*demoMesh);\n  std::cout << \"Done!\\n\";\n  std::cout << \"D = \\n\" << Eigen::MatrixXi(D) << \"\\n\\n\";\n\n  // Step 3: Test co-chain complex property (D*G = 0?)\n  std::cout << \"D*G = 0? \"\n            << (IncidenceMatrices::testZeroIncidenceMatrixProduct(*demoMesh)\n                    ? \"Yes!\"\n                    : \"No!\")\n            << \"\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "7b221792a99c64d433d165fe822f870009cb9c1f", "size": 1148, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/IncidenceMatrices/templates/incidencematrices_main.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/IncidenceMatrices/templates/incidencematrices_main.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/IncidenceMatrices/templates/incidencematrices_main.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 29.4358974359, "max_line_length": 76, "alphanum_fraction": 0.6010452962, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5581356331650746}}
{"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": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include <Eigen/Core>\n#include \"../util/AlgorithmUtils.hpp\"\n\n// In scalers, the range cannot be too small otherwise it gets unmanageable as denominator\n// To sanitize, we set an arbitrary threshold of 10*epsilon and replace by 1 if smaller\n// This is in line with scikit learn behaviour (https://github.com/scikit-learn/scikit-learn/blob/16625450b58f555dc3955d223f0c3b64a5686984/sklearn/preprocessing/_data.py#L88-L118)\n\nvoid handleZerosInScale(Eigen::ArrayXd& rangeArray)\n{\n  rangeArray = (rangeArray < 10 * fluid::algorithm::epsilon).select(1,rangeArray);\n}\n\nvoid handleZerosInScale(double& range)\n{\n  range = (range < (10 * fluid::algorithm::epsilon)) ? 1 : range;\n}\n", "meta": {"hexsha": "80c3d0725a2abe3f054344a36894dff568a174b9", "size": 1093, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/ScalerUtils.hpp", "max_stars_repo_name": "jamesb93/flucoma-core", "max_stars_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/algorithms/util/ScalerUtils.hpp", "max_issues_repo_name": "jamesb93/flucoma-core", "max_issues_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/algorithms/util/ScalerUtils.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": 37.6896551724, "max_line_length": 179, "alphanum_fraction": 0.7767612077, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.558054874722875}}
{"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": "#include <iostream>\n#include <boost/algorithm/clamp.hpp>\n#include <boost/algorithm/minmax.hpp>\n\n#include <ros/ros.h>\n#include <eigen_conversions/eigen_msg.h>\n#include <eigen3/Eigen/Dense>\n#include <control_velpid/pid_controller.h>\n\nvoid setup_livel_pid(double p_gain, double i_gain, double d_gain, double i_max, double i_min)\n{\n\t// PID values\n\tp_gain_ = p_gain;\n\ti_gain_ = i_gain;\n\td_gain_ = d_gain;\n\n\t// Min/max bounds for the integral windup\n\ti_min_ = i_min;\n\ti_max_ = i_max;\n\t\n\t//ROS_INFO(\"PID: %f, %f, %f\", p_gain_, i_gain_, d_gain_);\n}\n\ndouble computeCommand_x(double error, ros::Duration dt)\n{\n\tif (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error))\n\t\treturn 0.0;\n\t\n\tdouble error_dot = d_error_x;\n\n\t// Calculate the derivative error\n\tif (dt.toSec() > 0.0)\n\t{\n\t\tif (valid_p_error_last_x) {\n\t\t\terror_dot = (error - p_error_last_x) / dt.toSec();\n\t    }\n\t    p_error_last_x = error;\n\t    valid_p_error_last_x = true;\n\t}\n\treturn computeCommandX(error, error_dot, dt);\n}\n\ndouble computeCommandX(double error, double error_dot, ros::Duration dt)\n{\n\tdouble p_term, d_term, i_term;\n\tp_error_x = error; // this is error = target - state\n\td_error_x = error_dot;\n\n\tif (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot))\n\t\treturn 0.0;\n\n\t// Calculate proportional contribution to command\n\tp_term = p_gain_ * p_error_x;\n\n\t// Calculate the integral of the position error\n\ti_error_x += dt.toSec() * p_error_x;\n\t\n\tif(i_gain_!=0)\n\t{\n\t\t// Prevent i_error_ from climbing higher than permitted by i_max_/i_min_\n\t\tboost::tuple<double, double> bounds = boost::minmax<double>(i_min_ / i_gain_, i_max_ / i_gain_);\n\t\ti_error_x = boost::algorithm::clamp(i_error_x, bounds.get<0>(), bounds.get<1>());\n\t}\n\t\n\t// Calculate integral contribution to command\n\ti_term = i_gain_ * i_error_x;\n\t\n\t// Limit i_term so that the limit is meaningful in the output\n\ti_term = boost::algorithm::clamp(i_term, i_min_, i_max_);\n\t\n\t// Calculate derivative contribution to command\n\td_term = d_gain_ * d_error_x;\n\t\n\t// Compute the command\n\tcmd_x = p_term + i_term + d_term;\n\t\n\treturn cmd_x;\n}\n\n\ndouble computeCommand_y(double error, ros::Duration dt)\n{\n\tif (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error))\n\t\treturn 0.0;\n\t\n\tdouble error_dot = d_error_y;\n\n\t// Calculate the derivative error\n\tif (dt.toSec() > 0.0)\n\t{\n\t\tif (valid_p_error_last_y) {\n\t\t\terror_dot = (error - p_error_last_y) / dt.toSec();\n\t    }\n\t    p_error_last_y = error;\n\t    valid_p_error_last_y = true;\n\t}\n\treturn computeCommandY(error, error_dot, dt);\n}\n\ndouble computeCommandY(double error, double error_dot, ros::Duration dt)\n{\n\tdouble p_term, d_term, i_term;\n\tp_error_y = error; // this is error = target - state\n\td_error_y = error_dot;\n\n\tif (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot))\n\t\treturn 0.0;\n\n\t// Calculate proportional contribution to command\n\tp_term = p_gain_ * p_error_y;\n\n\t// Calculate the integral of the position error\n\ti_error_y += dt.toSec() * p_error_y;\n\t\n\tif(i_gain_!=0)\n\t{\n\t\t// Prevent i_error_ from climbing higher than permitted by i_max_/i_min_\n\t\tboost::tuple<double, double> bounds = boost::minmax<double>(i_min_ / i_gain_, i_max_ / i_gain_);\n\t\ti_error_y = boost::algorithm::clamp(i_error_y, bounds.get<0>(), bounds.get<1>());\n\t}\n\t\n\t// Calculate integral contribution to command\n\ti_term = i_gain_ * i_error_y;\n\t\n\t// Limit i_term so that the limit is meaningful in the output\n\ti_term = boost::algorithm::clamp(i_term, i_min_, i_max_);\n\t\n\t// Calculate derivative contribution to command\n\td_term = d_gain_ * d_error_y;\n\t\n\t// Compute the command\n\tcmd_y = p_term + i_term + d_term;\n\t\n\treturn cmd_y;\n}\n\n\ndouble computeCommand_z(double error, ros::Duration dt)\n{\n\tif (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error))\n\t\treturn 0.0;\n\t\n\tdouble error_dot = d_error_z;\n\n\t// Calculate the derivative error\n\tif (dt.toSec() > 0.0)\n\t{\n\t\tif (valid_p_error_last_z) {\n\t\t\terror_dot = (error - p_error_last_z) / dt.toSec();\n\t    }\n\t    p_error_last_z = error;\n\t    valid_p_error_last_z = true;\n\t}\n\treturn computeCommandZ(error, error_dot, dt);\n}\n\ndouble computeCommandZ(double error, double error_dot, ros::Duration dt)\n{\n\tdouble p_term, d_term, i_term;\n\tp_error_z = error; // this is error = target - state\n\td_error_z = error_dot;\n\n\tif (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot))\n\t\treturn 0.0;\n\n\t// Calculate proportional contribution to command\n\tp_term = p_gain_ * p_error_z;\n\n\t// Calculate the integral of the position error\n\ti_error_z += dt.toSec() * p_error_z;\n\t\n\tif(i_gain_!=0)\n\t{\n\t\t// Prevent i_error_ from climbing higher than permitted by i_max_/i_min_\n\t\tboost::tuple<double, double> bounds = boost::minmax<double>(i_min_ / i_gain_, i_max_ / i_gain_);\n\t\ti_error_z = boost::algorithm::clamp(i_error_z, bounds.get<0>(), bounds.get<1>());\n\t}\n\t\n\t// Calculate integral contribution to command\n\ti_term = i_gain_ * i_error_z;\n\t\n\t// Limit i_term so that the limit is meaningful in the output\n\ti_term = boost::algorithm::clamp(i_term, i_min_, i_max_);\n\t\n\t// Calculate derivative contribution to command\n\td_term = d_gain_ * d_error_z;\n\t\n\t// Compute the command\n\tcmd_z = p_term + i_term + d_term;\n\t\n\treturn cmd_z;\n}\n\n// Function to bound the values of \"v\" between +/- \"b\"\nfloat bound(float v, float b){\n    if(v < -b)\n        return -b;\n    if(v > b)\n        return b;\n    return v;\n}\n\nEigen::Vector3d compute_linvel_effort(Eigen::Vector3d goal, Eigen::Vector3d current, ros::Time last_time){\n\tdouble lin_vel_x = computeCommand_x(goal.x() - current.x(), ros::Time::now() - last_time);\n\tdouble lin_vel_y = computeCommand_y(goal.y() - current.y(), ros::Time::now() - last_time);\n\tdouble lin_vel_z = computeCommand_z(goal.z() - current.z(), ros::Time::now() - last_time);\n\n\tlin_vel_x = bound(lin_vel_x, MAX_vel);\n\tlin_vel_y = bound(lin_vel_y, MAX_vel);\n\tlin_vel_z = bound(lin_vel_z, MAX_vel);\n\n\treturn Eigen::Vector3d(lin_vel_x, lin_vel_y, lin_vel_z);\n}\n\n/*\nEigen::Vector3d compute_linvel_effort(geometry_msgs::PoseStamped goal, geometry_msgs::PoseStamped current, ros::Time last_time){\n\tEigen::Vector3d _goal, _current;\n\ttf::pointMsgToEigen(goal.pose.position, _goal);\n\ttf::pointMsgToEigen(current.pose.position, _current);\n\n\tdouble lin_vel_x = computeCommand_x(_goal(0) - _current(0), ros::Time::now() - last_time);\n\tdouble lin_vel_y = computeCommand_y(_goal(1) - _current(1), ros::Time::now() - last_time);\n\tdouble lin_vel_z = computeCommand_z(_goal(2) - _current(2), ros::Time::now() - last_time);\n\n\tlin_vel_x = bound(lin_vel_x, MAX_vel);\n\tlin_vel_y = bound(lin_vel_y, MAX_vel);\n\tlin_vel_z = bound(lin_vel_z, MAX_vel);\n\n\treturn Eigen::Vector3d(lin_vel_x, lin_vel_y, lin_vel_z);\n}\n*/\n", "meta": {"hexsha": "8622717c1745536bb502a00e25b28142363477a7", "size": 6781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "control_velpid/src/lib/pid_controller.cpp", "max_stars_repo_name": "Dieptranivsr/DroneIVSR", "max_stars_repo_head_hexsha": "5b348465443524878418a6b1f89cf6dba3804c0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "control_velpid/src/lib/pid_controller.cpp", "max_issues_repo_name": "Dieptranivsr/DroneIVSR", "max_issues_repo_head_hexsha": "5b348465443524878418a6b1f89cf6dba3804c0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-04-24T09:36:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-24T09:38:46.000Z", "max_forks_repo_path": "control_velpid/src/lib/pid_controller.cpp", "max_forks_repo_name": "Dieptranivsr/DroneIVSR", "max_forks_repo_head_hexsha": "5b348465443524878418a6b1f89cf6dba3804c0f", "max_forks_repo_licenses": ["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.2284482759, "max_line_length": 128, "alphanum_fraction": 0.702698717, "num_tokens": 1970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936435, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5580548739341376}}
{"text": "#define BOOST_TEST_MODULE Gpufit\n\n#include \"Gpufit/gpufit.h\"\n\n#include <boost/test/included/unit_test.hpp>\n\n#include <array>\n\ntemplate<std::size_t SIZE>\nvoid generate_gauss_2d(std::array< float , SIZE>& values)\n{\n    int const size_x = int(std::sqrt(SIZE));\n    int const size_y = size_x;\n\n    float const a = 4.f;\n    float const x0 = (float(size_x) - 1.f) / 2.f;\n    float const y0 = (float(size_y) - 1.f) / 2.f;\n    float const s = 0.5f;\n    float const b = 1.f;\n\n    for (int point_index_y = 0; point_index_y < size_y; point_index_y++)\n    {\n        for (int point_index_x = 0; point_index_x < size_x; point_index_x++)\n        {\n            int const point_index = point_index_y * size_x + point_index_x;\n            float const argx = ((point_index_x - x0)*(point_index_x - x0)) / (2.f * s * s);\n            float const argy = ((point_index_y - y0)*(point_index_y - y0)) / (2.f * s * s);\n            float const ex = exp(-argx) * exp(-argy);\n            values[point_index] = a * ex + b;\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE( Gauss_Fit_2D )\n{\n    std::size_t const n_fits{ 1 } ;\n    std::size_t const n_points{ 25 } ;\n    std::array< float, n_points > data{};\n    generate_gauss_2d(data);\n    std::array< float, n_points > weights{};\n    std::fill(weights.begin(), weights.end(), 1.f);\n    std::array< float, 5 > initial_parameters{ { 2.f, 1.8f, 2.2f, 0.4f, 0.f } };\n    float tolerance{ 0.001f };\n    int max_n_iterations{ 10 };\n    std::array< int, 5 > parameters_to_fit{ { 1, 1, 1, 1, 1 } };\n    std::array< float, 5 > output_parameters;\n    int output_states;\n    float output_chi_square;\n    int output_n_iterations;\n\n    int const status\n            = gpufit\n            (\n                n_fits,\n                n_points,\n                data.data(),\n                0,\n                GAUSS_2D,\n                initial_parameters.data(),\n                tolerance,\n                max_n_iterations,\n                parameters_to_fit.data(),\n                LSE,\n                0,\n                0,\n                output_parameters.data(),\n                &output_states,\n                &output_chi_square,\n                &output_n_iterations\n            ) ;\n\n    BOOST_CHECK( status == 0 ) ;\n\n    int const status_with_weights\n            = gpufit\n            (\n                n_fits,\n                n_points,\n                data.data(),\n                weights.data(),\n                GAUSS_2D,\n                initial_parameters.data(),\n                tolerance,\n                max_n_iterations,\n                parameters_to_fit.data(),\n                LSE,\n                0,\n                0,\n                output_parameters.data(),\n                &output_states,\n                &output_chi_square,\n                &output_n_iterations\n            ) ;\n\n    BOOST_CHECK( status_with_weights == 0 ) ;\n}\n", "meta": {"hexsha": "02229335a9b48014bb7edc98c5d93c14c2425d3c", "size": 2837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gpufit/tests/Gauss_Fit_2D.cpp", "max_stars_repo_name": "yongdengzhang/Gpufit", "max_stars_repo_head_hexsha": "6e719585badff1c40488a1439fa04da1792e41b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Gpufit/tests/Gauss_Fit_2D.cpp", "max_issues_repo_name": "yongdengzhang/Gpufit", "max_issues_repo_head_hexsha": "6e719585badff1c40488a1439fa04da1792e41b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gpufit/tests/Gauss_Fit_2D.cpp", "max_forks_repo_name": "yongdengzhang/Gpufit", "max_forks_repo_head_hexsha": "6e719585badff1c40488a1439fa04da1792e41b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-18T15:13:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-18T15:13:27.000Z", "avg_line_length": 29.2474226804, "max_line_length": 91, "alphanum_fraction": 0.5125132182, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5580548702323904}}
{"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": "#include <boost/test/unit_test.hpp>\n\n#include \"Werk/Math/WeightedSummaryStatistics.hpp\"\n\nBOOST_AUTO_TEST_SUITE(WeightedSummaryStatisticsTest)\n\nBOOST_AUTO_TEST_CASE(TestEmpty)\n{\n\tWerk::WeightedSummaryStatistics s;\n\tBOOST_REQUIRE_EQUAL(s.count(), 0);\n\tBOOST_REQUIRE_EQUAL(s.weightSum(), 0.0);\n\tBOOST_REQUIRE_EQUAL(s.sum(), 0.0);\n}\n\nBOOST_AUTO_TEST_CASE(TestBasicUnweighted)\n{\n\tWerk::WeightedSummaryStatistics s;\n\ts.sample(5.0, 1.0);\n\ts.sample(1.0, 1.0);\n\n\tBOOST_REQUIRE_EQUAL(s.count(), 2);\n\tBOOST_REQUIRE_EQUAL(s.weightSum(), 2.0);\n\tBOOST_REQUIRE_EQUAL(s.sum(), 6.0);\n\tBOOST_REQUIRE_EQUAL(s.average(), 3.0);\n\tBOOST_REQUIRE_EQUAL(s.variance(), 4.0);\n\tBOOST_REQUIRE_EQUAL(s.stddev(), 2.0);\n\n\ts.reset();\n\tBOOST_REQUIRE_EQUAL(s.count(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(TestBasicEqualWeights)\n{\n\tWerk::WeightedSummaryStatistics s;\n\ts.sample(5.0, 2.0);\n\ts.sample(1.0, 2.0);\n\n\tBOOST_REQUIRE_EQUAL(s.count(), 2);\n\tBOOST_REQUIRE_EQUAL(s.weightSum(), 4.0);\n\tBOOST_REQUIRE_EQUAL(s.sum(), 12.0);\n\tBOOST_REQUIRE_EQUAL(s.average(), 3.0);\n\tBOOST_REQUIRE_EQUAL(s.variance(), 4.0);\n\tBOOST_REQUIRE_EQUAL(s.stddev(), 2.0);\n}\n\nBOOST_AUTO_TEST_CASE(TestBasicUnequalWeights)\n{\n\tWerk::WeightedSummaryStatistics s;\n\ts.sample(5.0, 1.0);\n\ts.sample(1.0, 3.0);\n\n\tBOOST_REQUIRE_EQUAL(s.count(), 2);\n\tBOOST_REQUIRE_EQUAL(s.weightSum(), 4.0);\n\tBOOST_REQUIRE_EQUAL(s.sum(), 8.0);\n\tBOOST_REQUIRE_EQUAL(s.average(), 2.0);\n\tBOOST_REQUIRE_EQUAL(s.variance(), 3.0);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "0e5ba63593d08cf0d9b5eefd482f4333bd122c46", "size": 1454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/WerkTest/Math/WeightedSummaryStatistics.cpp", "max_stars_repo_name": "mish24/werk", "max_stars_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/WerkTest/Math/WeightedSummaryStatistics.cpp", "max_issues_repo_name": "mish24/werk", "max_issues_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/WerkTest/Math/WeightedSummaryStatistics.cpp", "max_forks_repo_name": "mish24/werk", "max_forks_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_forks_repo_licenses": ["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.6440677966, "max_line_length": 52, "alphanum_fraction": 0.7414030261, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5580548512397777}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n/// \\file\n/// Defines helper functions for converting between `DataVector`s and boost\n/// quaternions.\n\n#pragma once\n\n#include <boost/math/quaternion.hpp>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\n/// Convert a `boost::math::quaternion` to a `DataVector`\nDataVector quaternion_to_datavector(\n    const boost::math::quaternion<double>& input) noexcept {\n  return DataVector{input.R_component_1(), input.R_component_2(),\n                    input.R_component_3(), input.R_component_4()};\n}\n\n/// \\brief Convert a `DataVector` to a `boost::math::quaternion`\n///\n/// \\details To convert to a quaternion, a `DataVector` must have either 3 or 4\n/// components. If it has 3 components, the quaternion will be constructed with\n/// 0 scalar part while the vector part is the `DataVector`. If the `DataVector`\n/// has 4 components, the quaternion is just the `DataVector` itself.\nboost::math::quaternion<double> datavector_to_quaternion(\n    const DataVector& input) noexcept {\n  ASSERT(input.size() == 3 or input.size() == 4,\n         \"To form a quaternion, a DataVector can either have 3 or 4 components \"\n         \"only. This DataVector has \"\n             << input.size() << \" components.\");\n  if (input.size() == 3) {\n    return boost::math::quaternion<double>(0.0, input[0], input[1], input[2]);\n  } else {\n    return boost::math::quaternion<double>(input[0], input[1], input[2],\n                                           input[3]);\n  }\n}\n/// Normalize a `boost::math::quaternion`\ntemplate <typename T>\nvoid normalize_quaternion(\n    const gsl::not_null<boost::math::quaternion<T>*> input) noexcept {\n  *input /= abs(*input);\n}\n", "meta": {"hexsha": "67f007dbc842b591314f3dd18e8bb66bf89f848e", "size": 1770, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Domain/FunctionsOfTime/QuaternionHelpers.hpp", "max_stars_repo_name": "noora-gn/spectre", "max_stars_repo_head_hexsha": "fd28ecaa6d16a5accebeb8fae733acefffe27682", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-01T06:07:16.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-01T06:07:16.000Z", "max_issues_repo_path": "src/Domain/FunctionsOfTime/QuaternionHelpers.hpp", "max_issues_repo_name": "noora-gn/spectre", "max_issues_repo_head_hexsha": "fd28ecaa6d16a5accebeb8fae733acefffe27682", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-06-04T20:26:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-27T14:54:55.000Z", "max_forks_repo_path": "src/Domain/FunctionsOfTime/QuaternionHelpers.hpp", "max_forks_repo_name": "prayush/spectre", "max_forks_repo_head_hexsha": "50b70c189a0f213f851caabedc91571c77ddeb2a", "max_forks_repo_licenses": ["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.875, "max_line_length": 80, "alphanum_fraction": 0.6757062147, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5580256300648946}}
{"text": "/*\n * Copyright (C) 2014-2015 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*/\n#include <cmath>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n#include \"gazebo/math/SignalStatsPrivate.hh\"\n#include \"gazebo/math/SignalStats.hh\"\n\nusing namespace gazebo;\nusing namespace math;\n\n//////////////////////////////////////////////////\nSignalStatistic::SignalStatistic()\n  : dataPtr(new SignalStatisticPrivate)\n{\n  this->dataPtr->data = 0.0;\n  this->dataPtr->count = 0;\n}\n\n//////////////////////////////////////////////////\nSignalStatistic::~SignalStatistic()\n{\n  delete this->dataPtr;\n  this->dataPtr = 0;\n}\n\n//////////////////////////////////////////////////\nsize_t SignalStatistic::Count() const\n{\n  return this->dataPtr->count;\n}\n\n//////////////////////////////////////////////////\nvoid SignalStatistic::Reset()\n{\n  this->dataPtr->data = 0;\n  this->dataPtr->count = 0;\n}\n\n//////////////////////////////////////////////////\ndouble SignalMean::Value() const\n{\n  if (this->dataPtr->count == 0)\n  {\n    return 0;\n  }\n  return this->dataPtr->data / this->dataPtr->count;\n}\n\n//////////////////////////////////////////////////\nstd::string SignalMean::ShortName() const\n{\n  return \"mean\";\n}\n\n//////////////////////////////////////////////////\nvoid SignalMean::InsertData(const double _data)\n{\n  this->dataPtr->data += _data;\n  this->dataPtr->count++;\n}\n\n//////////////////////////////////////////////////\ndouble SignalRootMeanSquare::Value() const\n{\n  if (this->dataPtr->count == 0)\n  {\n    return 0;\n  }\n  return sqrt(this->dataPtr->data / this->dataPtr->count);\n}\n\n//////////////////////////////////////////////////\nstd::string SignalRootMeanSquare::ShortName() const\n{\n  return \"rms\";\n}\n\n//////////////////////////////////////////////////\nvoid SignalRootMeanSquare::InsertData(const double _data)\n{\n  this->dataPtr->data += _data * _data;\n  this->dataPtr->count++;\n}\n\n//////////////////////////////////////////////////\ndouble SignalMaxAbsoluteValue::Value() const\n{\n  return this->dataPtr->data;\n}\n\n//////////////////////////////////////////////////\nstd::string SignalMaxAbsoluteValue::ShortName() const\n{\n  return \"maxAbs\";\n}\n\n//////////////////////////////////////////////////\nvoid SignalMaxAbsoluteValue::InsertData(const double _data)\n{\n  double absData = std::abs(_data);\n  if (absData > this->dataPtr->data)\n  {\n    this->dataPtr->data = absData;\n  }\n  this->dataPtr->count++;\n}\n\n//////////////////////////////////////////////////\nSignalStats::SignalStats()\n  : dataPtr(new SignalStatsPrivate)\n{\n}\n\n//////////////////////////////////////////////////\nSignalStats::~SignalStats()\n{\n}\n\n//////////////////////////////////////////////////\nsize_t SignalStats::Count() const\n{\n  if (this->dataPtr->stats.empty())\n    return 0;\n\n  return this->dataPtr->stats.front()->Count();\n}\n\n//////////////////////////////////////////////////\nstd::map<std::string, double> SignalStats::Map() const\n{\n  std::map<std::string, double> map;\n  for (auto const &statistic : this->dataPtr->stats)\n  {\n    map[statistic->ShortName()] = statistic->Value();\n  }\n  return map;\n}\n\n//////////////////////////////////////////////////\nvoid SignalStats::InsertData(const double _data)\n{\n  for (auto &statistic : this->dataPtr->stats)\n  {\n    statistic->InsertData(_data);\n  }\n}\n\n//////////////////////////////////////////////////\nbool SignalStats::InsertStatistic(const std::string &_name)\n{\n  // Check if the statistic is already inserted\n  {\n    std::map<std::string, double> map = this->Map();\n    if (map.find(_name) != map.end())\n    {\n      std::cerr << \"Unable to InsertStatistic [\"\n                << _name\n                << \"] since it has already been inserted.\"\n                << std::endl;\n      return false;\n    }\n  }\n\n  SignalStatisticPtr stat;\n  if (_name == \"maxAbs\")\n  {\n    stat.reset(new SignalMaxAbsoluteValue());\n    this->dataPtr->stats.push_back(stat);\n  }\n  else if (_name == \"mean\")\n  {\n    stat.reset(new SignalMean());\n    this->dataPtr->stats.push_back(stat);\n  }\n  else if (_name == \"rms\")\n  {\n    stat.reset(new SignalRootMeanSquare());\n    this->dataPtr->stats.push_back(stat);\n  }\n  else\n  {\n    // Unrecognized name string\n    std::cerr << \"Unable to InsertStatistic [\"\n              << _name\n              << \"] since it is an unrecognized name.\"\n              << std::endl;\n    return false;\n  }\n  return true;\n}\n\n//////////////////////////////////////////////////\nbool SignalStats::InsertStatistics(const std::string &_names)\n{\n  if (_names.empty())\n  {\n    std::cerr << \"Unable to InsertStatistics \"\n              << \"since no names were supplied.\"\n              << std::endl;\n    return false;\n  }\n\n  bool result = true;\n  std::vector<std::string> names;\n  boost::split(names, _names, boost::is_any_of(\",\"));\n  for (auto &statistic : names)\n  {\n    result = result && this->InsertStatistic(statistic);\n  }\n  return result;\n}\n\n//////////////////////////////////////////////////\nvoid SignalStats::Reset()\n{\n  for (auto &statistic : this->dataPtr->stats)\n  {\n    statistic->Reset();\n  }\n}\n\n", "meta": {"hexsha": "113a93f60e073684ce8c2c58b6b9b1d599011e2c", "size": 5544, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gazebo/math/SignalStats.cc", "max_stars_repo_name": "harderthan/gazebo", "max_stars_repo_head_hexsha": "f00a0e4239ddb08b299dc21ab1ef106ecedb0fac", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-04-06T16:17:36.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-06T16:17:36.000Z", "max_issues_repo_path": "gazebo/math/SignalStats.cc", "max_issues_repo_name": "harderthan/gazebo", "max_issues_repo_head_hexsha": "f00a0e4239ddb08b299dc21ab1ef106ecedb0fac", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gazebo/math/SignalStats.cc", "max_forks_repo_name": "harderthan/gazebo", "max_forks_repo_head_hexsha": "f00a0e4239ddb08b299dc21ab1ef106ecedb0fac", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3924050633, "max_line_length": 75, "alphanum_fraction": 0.5268759019, "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146849, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5580146835178804}}
{"text": "\n// Author(s) : Camille Wormser, Pierre Alliez\n// Example of an AABB tree used with a simple list of\n// triangles (a triangle soup) stored into an array of points.\n\n#include <iostream>\n#include <vector>\n#include <boost/iterator/iterator_adaptor.hpp>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/AABB_tree.h>\n#include <CGAL/AABB_traits.h>\n\n\n\ntypedef CGAL::Simple_cartesian<double> K;\n\n\n// My own point type\nstruct My_point {\n    double x;\n    double y;\n    double z;\n\n    My_point (double _x, double _y, double _z) : x(_x), y(_y), z(_z) {}\n};\n\n// The triangles are stored in a flat vector of points (a triangle soup):\n// three consecutive points represent a triangle\ntypedef std::vector<My_point>::const_iterator Point_iterator;\n\n// defines the iterator over triangles needed by the tree:\nclass Triangle_iterator\n    : public boost::iterator_adaptor<\n    Triangle_iterator               // Derived\n    , Point_iterator                  // Base\n    , boost::use_default              // Value\n    , boost::forward_traversal_tag    // CategoryOrTraversal\n    >\n{\npublic:\n    Triangle_iterator()\n        : Triangle_iterator::iterator_adaptor_() {}\n\n    explicit Triangle_iterator(Point_iterator p)\n        : Triangle_iterator::iterator_adaptor_(p) {}\n\nprivate:\n    friend class boost::iterator_core_access;\n    void increment() { this->base_reference() += 3; }\n};\n\n\n// The following primitive provides the conversion facilities between\n// my own triangle and point types and the CGAL ones\nstruct My_triangle_primitive {\npublic:\n    typedef Triangle_iterator Id;\n\n    // the CGAL types returned\n    typedef K::Point_3    Point;\n    typedef K::Triangle_3 Datum;\nprivate:\n    Id m_it; // this is what the AABB tree will store internally\n\npublic:\n    My_triangle_primitive() {} // default constructor needed\n\n    // the following constructor is the one that receives the iterators from the\n    // iterator range given as input to the AABB_tree\n    My_triangle_primitive(Triangle_iterator a)\n        : m_it(a) {}\n\n    Id id() const { return m_it; }\n\n    // on the fly conversion from the internal data\n    // to the CGAL types\n    Datum datum() const\n    {\n        Point_iterator p_it = m_it.base();\n        Point p(p_it->x, p_it->y, p_it->z);\n        ++p_it;\n        Point q(p_it->x, p_it->y, p_it->z);\n        ++p_it;\n        Point r(p_it->x, p_it->y, p_it->z);\n\n        return Datum(p, q, r); // assembles a triangle from three points\n    }\n\n    // returns one point which must be on the primitive\n    Point reference_point() const\n    {\n        return Point(m_it->x, m_it->y, m_it->z);\n    }\n};\n\n// types\ntypedef CGAL::AABB_traits<K, My_triangle_primitive> My_AABB_traits;\ntypedef CGAL::AABB_tree<My_AABB_traits> Tree;\n\nint main()\n{\n    // generates triangle soup\n    My_point a(1.0, 0.0, 0.0);\n    My_point b(0.0, 1.0, 0.0);\n    My_point c(0.0, 0.0, 1.0);\n    My_point d(0.0, 0.0, 0.0);\n\n    std::vector<My_point> triangles;\n    triangles.push_back(a); triangles.push_back(b); triangles.push_back(c);\n    triangles.push_back(a); triangles.push_back(b); triangles.push_back(d);\n    triangles.push_back(a); triangles.push_back(d); triangles.push_back(c);\n\n    // constructs AABB tree\n    Tree tree(Triangle_iterator(triangles.begin()),\n        Triangle_iterator(triangles.end()));\n\n    // counts #intersections\n    K::Ray_3 ray_query(K::Point_3(1.0, 0.0, 0.0), K::Point_3(0.0, 1.0, 0.0));\n    std::cout << tree.number_of_intersected_primitives(ray_query)\n        << \" intersections(s) with ray query\" << std::endl;\n\n    // computes closest point\n    K::Point_3 point_query(2.0, 2.0, 2.0);\n    K::Point_3 closest_point = tree.closest_point(point_query);\n\n    std::cerr << \"closest point is: \" << closest_point << std::endl;\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "0fe8ffb713adaf64ecdf08dffa62dda10ec4b8bb", "size": 3749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AABB_tree/examples/AABB_tree/AABB_custom_triangle_soup_example.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "AABB_tree/examples/AABB_tree/AABB_custom_triangle_soup_example.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "AABB_tree/examples/AABB_tree/AABB_custom_triangle_soup_example.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 28.8384615385, "max_line_length": 80, "alphanum_fraction": 0.6673779675, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5580146821645601}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <mimkl/kernels.hpp>\n#include <mimkl/linear_algebra.hpp>\n#include <stdexcept>\n\nint main(int argc, char **argv)\n{\n    try\n    {\n        int size = 3;\n        Eigen::SparseMatrix<double> L(size, size);\n        Eigen::SparseMatrix<double> L_reference(size, size);\n\n        // L\n        mimkl::linear_algebra::fill_sparse_diagonal(L, 1.0);\n        // L_reference\n        for (int i = 0; i < size; i++)\n        {\n            L_reference.insert(i, i) = 1.;\n        }\n\n        assert((L - L_reference).norm() == 0.0);\n\n        return EXIT_SUCCESS;\n    }\n    catch (const std::exception &e)\n    {\n        std::cerr << e.what();\n        return EXIT_FAILURE;\n    }\n}\n", "meta": {"hexsha": "c17777a5871ad74e4c68d4da85f088864499d2ec", "size": 732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/sparse_diagonal/main.cpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "test/sparse_diagonal/main.cpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "test/sparse_diagonal/main.cpp", "max_forks_repo_name": "vishalbelsare/mimkl", "max_forks_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:40:27.000Z", "avg_line_length": 21.5294117647, "max_line_length": 60, "alphanum_fraction": 0.556010929, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.5580146705884299}}
{"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": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/functional/fix.hpp>\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/functional/always.hpp>\n#include <boost/hana/integral_constant.hpp>\nusing namespace boost::hana;\n\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto fact = fix(\n    [](auto fact, auto n) {\n        return eval_if(equal(n, ullong<0>),\n            always(ullong<1>),\n            [=](auto _) { return mult(n, fact(_(pred)(n))); }\n        );\n    }\n);\n\nconstexpr unsigned long long reference(unsigned long long n)\n{ return n == 0 ? 1 : n * reference(n - 1); }\n\ntemplate <int n>\nconstexpr void test() {\n    BOOST_HANA_CONSTANT_CHECK(equal(fact(ullong<n>), ullong<reference(n)>));\n    test<n - 1>();\n}\n\ntemplate <> constexpr void test<-1>() { }\n\nint main() {\n    test<15>();\n}\n", "meta": {"hexsha": "2ee674a25f00e5f1a82ce0e94ea8e3530b530984", "size": 955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/functional/fix.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/functional/fix.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/functional/fix.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4871794872, "max_line_length": 78, "alphanum_fraction": 0.6586387435, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5579444608943552}}
{"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": "//####### Test module for Breit-Wheeler tables #################################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"phys/breit_wheeler/tables\"\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#include <picsar_qed/physics/breit_wheeler/breit_wheeler_engine_tables.hpp>\n\n#include <vector>\n#include <algorithm>\n#include <array>\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 5.0e-5;\nconst double double_small = 1e-30;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-3;\nconst float float_small = 1e-20;\n\n\nusing namespace picsar::multi_physics::phys::breit_wheeler;\n\n//Templated tolerance\ntemplate <typename T>\nT constexpr tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\ntemplate <typename T>\nT constexpr small()\n{\n    if(std::is_same<T,float>::value)\n        return float_small;\n    else\n        return double_small;\n}\n\n// ------------- Helper functions --------------\n\nconst double chi_min = 0.01;\nconst double chi_max = 1000;\nconst int how_many = 256;\nconst int how_many_frac = 256;\n\ntemplate <typename RealType, typename VectorType>\nauto get_fake_dndt_table()\n{\n    const auto params =\n        dndt_lookup_table_params<RealType>{\n            static_cast<RealType>(chi_min),\n            static_cast<RealType>(chi_max), how_many};\n\n    return dndt_lookup_table<RealType, VectorType>{params};\n}\n\ntemplate <typename RealType, typename VectorType>\nauto get_fake_pair_table()\n{\n    const auto params =\n        pair_prod_lookup_table_params<RealType>{\n            static_cast<RealType>(chi_min),\n            static_cast<RealType>(chi_max),\n            how_many, how_many_frac};\n\n    return pair_prod_lookup_table<RealType, VectorType>{params};\n}\n\n\n// ------------- Tests --------------\n\n// ***Test Breit Wheeler dndt table\n\ntemplate <typename RealType, typename VectorType>\nvoid check_dndt_table()\n{\n    auto table = get_fake_dndt_table<RealType, VectorType>();\n    BOOST_CHECK_EQUAL(table.is_init(),false);\n\n    VectorType coords = table.get_all_coordinates();\n\n    BOOST_CHECK_EQUAL(coords.size(),how_many);\n\n    const RealType log_chi_min = log(chi_min);\n    const RealType log_chi_max = log(chi_max);\n\n     for (int i = 0 ; i < static_cast<int>(coords.size()); ++i){\n         auto res = coords[i];\n         auto expected = static_cast<RealType>(\n             exp(log_chi_min + i*(log_chi_max-log_chi_min)/(how_many-1)));\n         BOOST_CHECK_SMALL((res-expected)/expected, tolerance<RealType>());\n     }\n\n    auto vals = VectorType{coords};\n\n    const RealType alpha = 3.0;\n\n    std::transform(coords.begin(), coords.end(), vals.begin(),\n        [=](RealType x){return alpha*x;});\n\n    bool result = table.set_all_vals(vals);\n    BOOST_CHECK_EQUAL(result,true);\n    BOOST_CHECK_EQUAL(table.is_init(),true);\n\n    auto table_2 = get_fake_dndt_table<RealType, VectorType>();\n    BOOST_CHECK_EQUAL(table_2 == table, false);\n    BOOST_CHECK_EQUAL(table == table, true);\n    BOOST_CHECK_EQUAL(table_2 == table_2, true);\n\n    const RealType xo0 = chi_min*0.1;\n    const RealType xo1 = chi_max*10;\n    const RealType x0 = chi_min;\n    const RealType x1 = (chi_max+chi_min)*0.5642 + chi_min;\n    const RealType x2 = chi_max;\n\n    const RealType ye_app_o0 = dndt_approx_left<RealType>(xo0);\n    const RealType ye_app_o1 = dndt_approx_right<RealType>(xo1);\n    const RealType ye0 = alpha*x0;\n    const RealType ye1 = alpha*x1;\n    const RealType ye2 = alpha*x2;\n\n    const auto xxs = std::array<RealType, 5>\n        {xo0, x0, x1, x2, xo1};\n\n    const auto exp_app = std::array<RealType, 5>\n        {ye_app_o0, ye0, ye1, ye2, ye_app_o1};\n\n    const auto is_out = std::array<bool, 5>\n        {true, false, false, false, true};\n\n    for(int i = 0 ; i < static_cast<int>(xxs.size()) ; ++i){\n        const RealType res = table.interp(xxs[i]);\n        bool flag_out = false;\n        const RealType res2 = table.interp(xxs[i], &flag_out);\n        BOOST_CHECK_EQUAL(flag_out, is_out[i]);\n        BOOST_CHECK_EQUAL(res, res2);\n\n        const RealType expect = exp_app[i];\n\n        if(i != 0)\n            BOOST_CHECK_SMALL((res-expect)/expect, tolerance<RealType>());\n        else\n            BOOST_CHECK_SMALL((res-expect), tolerance<RealType>());\n    }\n\n    const auto table_view = table.get_view();\n\n    for(int i = 0 ; i < static_cast<int>(xxs.size()) ; ++i){\n        BOOST_CHECK_EQUAL(table_view.interp(xxs[i]), table.interp(xxs[i]));\n    }\n}\n\nBOOST_AUTO_TEST_CASE( picsar_breit_wheeler_dndt_table)\n{\n    check_dndt_table<double, std::vector<double>>();\n    check_dndt_table<float, std::vector<float>>();\n}\n\n// *******************************\n\n// ***Test Breit Wheeler dndt table out range approximation\n\ntemplate <typename RealType>\nvoid check_dndt_table_out_approx()\n{\n    const auto left_chi = std::array<RealType,4>{0.01,0.05,0.1,0.2};\n    const auto left_sol = std::array<RealType,4>{\n        2.9069621438923337e-117,\n        1.2969667695320204e-24,\n        4.944416339700773e-13,\n        3.0528686912504136e-07};\n\n    for(int i = 0; i < 4; i++){\n        const auto left_res = dndt_approx_left(left_chi[i]);\n        if(left_sol[i] < small<RealType>()){\n            BOOST_CHECK_SMALL(\n                left_res,small<RealType>());\n        }\n        else{\n            BOOST_CHECK_SMALL(\n                (left_res - left_sol[i])/left_sol[i],tolerance<RealType>());\n        }\n    }\n\n}\n\nBOOST_AUTO_TEST_CASE( picsar_breit_wheeler_dndt_table_out_approx)\n{\n    check_dndt_table_out_approx<double>();\n    check_dndt_table_out_approx<float>();\n}\n\n// *******************************\n\n// ***Test Breit Wheeler dndt table serialization\n\ntemplate <typename RealType, typename VectorType>\nvoid check_dndt_table_serialization()\n{\n    const auto params =\n        dndt_lookup_table_params<RealType>{\n            static_cast<RealType>(0.1),static_cast<RealType>(10.0),6};\n\n    auto table = dndt_lookup_table<\n        RealType, VectorType>{params, {1.,2.,3.,4.,5.,6.}};\n\n    auto raw_data = table.serialize();\n    auto new_table = dndt_lookup_table<\n        RealType, VectorType>{raw_data};\n\n    BOOST_CHECK_EQUAL(new_table.is_init(), true);\n    BOOST_CHECK_EQUAL(new_table == table, true);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_breit_wheeler_dndt_table_serialization)\n{\n    check_dndt_table_serialization<double, std::vector<double>>();\n    check_dndt_table_serialization<float, std::vector<float>>();\n}\n\n// *******************************\n\n// ***Test Breit Wheeler pair production table\n\ntemplate <typename RealType, typename VectorType>\nvoid check_pair_production_table()\n{\n    auto table = get_fake_pair_table<RealType, VectorType>();\n    BOOST_CHECK_EQUAL(table.is_init(),false);\n\n    auto coords = table.get_all_coordinates();\n\n    BOOST_CHECK_EQUAL(coords.size(),how_many*how_many_frac);\n\n    const RealType log_chi_min = log(chi_min);\n    const RealType log_chi_max = log(chi_max);\n\n     for (int i = 0 ; i < how_many*how_many_frac; ++i){\n         auto res_1 = coords[i][0];\n         auto res_2 = coords[i][1];\n         const auto ii = i/how_many_frac;\n         const auto jj = i%how_many_frac;\n         auto expected_1 = static_cast<RealType>(\n             exp(log_chi_min +ii*(log_chi_max-log_chi_min)/(how_many-1)));\n        auto expected_2 = expected_1*static_cast<RealType>(\n             0.0 +jj*0.5/(how_many_frac-1));\n\n         BOOST_CHECK_SMALL((res_1-expected_1)/expected_1, tolerance<RealType>());\n         if(expected_2 != static_cast<RealType>(0.0))\n            BOOST_CHECK_SMALL((res_2-expected_2)/expected_2, tolerance<RealType>());\n        else\n            BOOST_CHECK_SMALL((res_2-expected_2), tolerance<RealType>());\n     }\n\n    auto vals = VectorType(coords.size());\n\n    auto functor = [=](std::array<RealType,2> x){\n        return static_cast<RealType>(0.5*pow(2*(x[1]/x[0]), 8.0 + log(x[0])));};\n\n    auto inverse_functor = [=](std::array<RealType,2> x){\n            return static_cast<RealType>(0.5*pow(2*x[1], 1.0/(8.0 + log(x[0]))));};\n\n    std::transform(coords.begin(), coords.end(), vals.begin(),functor);\n\n    bool result = table.set_all_vals(vals);\n    BOOST_CHECK_EQUAL(result,true);\n    BOOST_CHECK_EQUAL(table.is_init(),true);\n\n\n    auto table_2 = get_fake_pair_table<RealType, VectorType>();\n    BOOST_CHECK_EQUAL(table_2 == table, false);\n    BOOST_CHECK_EQUAL(table == table, true);\n    BOOST_CHECK_EQUAL(table_2 == table_2, true);\n\n    const RealType xo0 = chi_min*0.1;\n    const RealType xo1 = chi_max*10;\n    const RealType x0 = chi_min;\n    const RealType x1 = (chi_max+chi_min)*0.5642 + chi_min;\n    const RealType x2 = chi_max;\n\n    const auto xxs = std::array<RealType, 5>\n        {xo0, x0, x1, x2, xo1};\n\n    const auto rrs = std::array<RealType, 11>\n            {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.99};\n\n    const auto is_out = std::array<bool, 5>\n            {true, false, false, false, true};\n\n    for (int i = 0; i < static_cast<int>(xxs.size()); ++i){\n        const auto xx = xxs[i];\n        for (const auto rr : rrs){\n            auto res = table.interp(xx, rr);\n            bool flag_out = false;\n            const RealType res2 = table.interp(xx, rr, &flag_out);\n            BOOST_CHECK_EQUAL(flag_out, is_out[i]);\n            BOOST_CHECK_EQUAL(res, res2);\n\n            auto rxx = xx;\n            if(rxx < chi_min) rxx = chi_min;\n            if(rxx > chi_max) rxx = chi_max;\n            auto eff_rr = (rr > 0.5)?(static_cast<RealType>(1.0) - rr):rr;\n            auto expected = inverse_functor(std::array<RealType,2>{rxx, eff_rr})*xx;\n            if(rr >= 0.5) expected = xx - expected;\n\n            if(expected != static_cast<RealType>(0.0))\n                BOOST_CHECK_SMALL((res-expected)/expected, tolerance<RealType>());\n            else\n                BOOST_CHECK_SMALL(res, small<RealType>());\n\n        }\n    }\n    const auto table_view = table.get_view();\n\n    const auto ff = std::array<double,4>{0.0, 0.1, 0.5, 0.99};\n\n    for(int i = 0 ; i < static_cast<int>(xxs.size()) ; ++i){\n        for (auto f : ff)\n            BOOST_CHECK_EQUAL(table_view.interp(xxs[i],f ), table.interp(xxs[i], f));\n    }\n}\n\nBOOST_AUTO_TEST_CASE( picsar_breit_wheeler_pair_production_table)\n{\n    check_pair_production_table<double, std::vector<double>>();\n    check_pair_production_table<float, std::vector<float>>();\n    check_pair_production_table<double, std::vector<double>>();\n    check_pair_production_table<float, std::vector<float>>();\n}\n\n// *******************************\n\n// ***Test Breit Wheeler pair production table serialization\n\ntemplate <typename RealType, typename VectorType>\nvoid check_pair_production_table_serialization()\n{\n    const auto params =\n        pair_prod_lookup_table_params<RealType>{\n            static_cast<RealType>(0.1),static_cast<RealType>(10.0),\n            3, 3};\n\n    auto table = pair_prod_lookup_table<\n        RealType, VectorType>{params, {1.,2.,3.,4.,5.,6.,7.,8.,9.}};\n\n    auto raw_data = table.serialize();\n    auto new_table =\n        pair_prod_lookup_table<RealType, VectorType>{raw_data};\n\n    BOOST_CHECK_EQUAL(new_table.is_init(), true);\n    BOOST_CHECK_EQUAL(new_table == table, true);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_breit_wheeler_pair_production_table_serialization)\n{\n    check_pair_production_table_serialization<double, std::vector<double>>();\n    check_pair_production_table_serialization<float, std::vector<float>>();\n}\n\n// *******************************\n", "meta": {"hexsha": "3aa43d6cc389c1656c30e7ae446aa1811595a702", "size": 11525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multi_physics/QED/QED_tests/test_picsar_breit_wheeler_tables.cpp", "max_stars_repo_name": "ax3l/picsar", "max_stars_repo_head_hexsha": "7ce1b321d9e047a238e56ee95507d36520a95b5b", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T17:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T17:20:30.000Z", "max_issues_repo_path": "multi_physics/QED/QED_tests/test_picsar_breit_wheeler_tables.cpp", "max_issues_repo_name": "ax3l/picsar", "max_issues_repo_head_hexsha": "7ce1b321d9e047a238e56ee95507d36520a95b5b", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-11-03T10:55:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T17:00:36.000Z", "max_forks_repo_path": "multi_physics/QED/QED_tests/test_picsar_breit_wheeler_tables.cpp", "max_forks_repo_name": "ax3l/picsar", "max_forks_repo_head_hexsha": "7ce1b321d9e047a238e56ee95507d36520a95b5b", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-06-23T13:54:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T21:51:38.000Z", "avg_line_length": 31.3179347826, "max_line_length": 85, "alphanum_fraction": 0.6452928416, "num_tokens": 3025, "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": "//  Copyright John Maddock 2007.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include \"required_defines.hpp\"\n\n#include \"performance_measure.hpp\"\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/array.hpp>\n\n#define T double\n#include \"../test/test_gamma_data.ipp\"\n\ntemplate <std::size_t N>\ndouble gamma_evaluate2(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::tgamma(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(gamma_test, \"gamma\")\n{\n   double result = gamma_evaluate2(factorials);\n   result += gamma_evaluate2(near_1);\n   result += gamma_evaluate2(near_2);\n   result += gamma_evaluate2(near_0);\n   result += gamma_evaluate2(near_m10);\n   result += gamma_evaluate2(near_m55);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(factorials) \n      + sizeof(near_1) \n      + sizeof(near_2)\n      + sizeof(near_0)\n      + sizeof(near_m10)\n      + sizeof(near_m55)) / sizeof(factorials[0]));\n}\n\ntemplate <std::size_t N>\ndouble lgamma_evaluate2(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::lgamma(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(lgamma_test, \"lgamma\")\n{\n   double result = lgamma_evaluate2(factorials);\n   result += lgamma_evaluate2(near_1);\n   result += lgamma_evaluate2(near_2);\n   result += lgamma_evaluate2(near_0);\n   result += lgamma_evaluate2(near_m10);\n   result += lgamma_evaluate2(near_m55);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(factorials) \n      + sizeof(near_1) \n      + sizeof(near_2)\n      + sizeof(near_0)\n      + sizeof(near_m10)\n      + sizeof(near_m55)) / sizeof(factorials[0]));\n}\n\ntemplate <std::size_t N>\ndouble tgamma1pm1_evaluate2(const boost::array<boost::array<T, 2>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += boost::math::tgamma1pm1(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(gamma1pm1_test, \"tgamma1pm1\")\n{\n   double result = tgamma1pm1_evaluate2(gammap1m1_data);\n\n   consume_result(result);\n   set_call_count(\n      sizeof(gammap1m1_data) / sizeof(gammap1m1_data[0]));\n}\n\n#ifdef TEST_CEPHES\n\nextern \"C\" {\n\ndouble gamma(double);\ndouble lgam(double);\n\n}\n\ntemplate <std::size_t N>\ndouble gamma_evaluate_cephes(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += gamma(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(gamma_test, \"gamma-cephes\")\n{\n   double result = gamma_evaluate_cephes(factorials);\n   result += gamma_evaluate_cephes(near_1);\n   result += gamma_evaluate_cephes(near_2);\n   result += gamma_evaluate_cephes(near_0);\n   result += gamma_evaluate_cephes(near_m10);\n   result += gamma_evaluate_cephes(near_m55);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(factorials) \n      + sizeof(near_1) \n      + sizeof(near_2)\n      + sizeof(near_0)\n      + sizeof(near_m10)\n      + sizeof(near_m55)) / sizeof(factorials[0]));\n}\n\ntemplate <std::size_t N>\ndouble lgamma_evaluate_cephes(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += lgam(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(lgamma_test, \"lgamma-cephes\")\n{\n   double result = lgamma_evaluate_cephes(factorials);\n   result += lgamma_evaluate_cephes(near_1);\n   result += lgamma_evaluate_cephes(near_2);\n   result += lgamma_evaluate_cephes(near_0);\n   result += lgamma_evaluate_cephes(near_m10);\n   result += lgamma_evaluate_cephes(near_m55);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(factorials) \n      + sizeof(near_1) \n      + sizeof(near_2)\n      + sizeof(near_0)\n      + sizeof(near_m10)\n      + sizeof(near_m55)) / sizeof(factorials[0]));\n}\n\n#endif\n\n#ifdef TEST_GSL\n\n#include <gsl/gsl_sf_gamma.h>\n\ntemplate <std::size_t N>\ndouble gamma_evaluate_gsl(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += gsl_sf_gamma(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(gamma_test, \"gamma-gsl\")\n{\n   double result = gamma_evaluate_gsl(factorials);\n   result += gamma_evaluate_gsl(near_1);\n   result += gamma_evaluate_gsl(near_2);\n   result += gamma_evaluate_gsl(near_0);\n   result += gamma_evaluate_gsl(near_m10);\n   result += gamma_evaluate_gsl(near_m55);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(factorials) \n      + sizeof(near_1) \n      + sizeof(near_2)\n      + sizeof(near_0)\n      + sizeof(near_m10)\n      + sizeof(near_m55)) / sizeof(factorials[0]));\n}\n\ntemplate <std::size_t N>\ndouble lgamma_evaluate_gsl(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n      result += gsl_sf_lngamma(data[i][0]);\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(lgamma_test, \"lgamma-gsl\")\n{\n   double result = lgamma_evaluate_gsl(factorials);\n   result += lgamma_evaluate_gsl(near_1);\n   result += lgamma_evaluate_gsl(near_2);\n   result += lgamma_evaluate_gsl(near_0);\n   result += lgamma_evaluate_gsl(near_m10);\n   result += lgamma_evaluate_gsl(near_m55);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(factorials) \n      + sizeof(near_1) \n      + sizeof(near_2)\n      + sizeof(near_0)\n      + sizeof(near_m10)\n      + sizeof(near_m55)) / sizeof(factorials[0]));\n}\n\n#endif\n\n#ifdef TEST_DCDFLIB\n#include <dcdflib.h>\n\ntemplate <std::size_t N>\ndouble gamma_evaluate2_dcd(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n   {\n      double x = data[i][0];\n      result += gamma_x(&x);\n   }\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(gamma_test_dcd, \"gamma-dcd\")\n{\n   double result = gamma_evaluate2_dcd(factorials);\n   result += gamma_evaluate2_dcd(near_1);\n   result += gamma_evaluate2_dcd(near_2);\n   result += gamma_evaluate2_dcd(near_0);\n   result += gamma_evaluate2_dcd(near_m10);\n   result += gamma_evaluate2_dcd(near_m55);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(factorials) \n      + sizeof(near_1) \n      + sizeof(near_2)\n      + sizeof(near_0)\n      + sizeof(near_m10)\n      + sizeof(near_m55)) / sizeof(factorials[0]));\n}\n\ntemplate <std::size_t N>\ndouble lgamma_evaluate2_dcd(const boost::array<boost::array<T, 3>, N>& data)\n{\n   double result = 0;\n   for(unsigned i = 0; i < N; ++i)\n   {\n      double x = data[i][0];\n      result += gamma_log(&x);\n   }\n   return result;\n}\n\nBOOST_MATH_PERFORMANCE_TEST(lgamma_test_dcd, \"lgamma-dcd\")\n{\n   double result = lgamma_evaluate2_dcd(factorials);\n   result += lgamma_evaluate2_dcd(near_1);\n   result += lgamma_evaluate2_dcd(near_2);\n   result += lgamma_evaluate2_dcd(near_0);\n   result += lgamma_evaluate2_dcd(near_m10);\n   result += lgamma_evaluate2_dcd(near_m55);\n\n   consume_result(result);\n   set_call_count(\n      (sizeof(factorials) \n      + sizeof(near_1) \n      + sizeof(near_2)\n      + sizeof(near_0)\n      + sizeof(near_m10)\n      + sizeof(near_m55)) / sizeof(factorials[0]));\n}\n\n#endif\n", "meta": {"hexsha": "ee596b61dd99f04d1f7d261e5879811640b9bcab", "size": 7283, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/performance/test_gamma.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/math/performance/test_gamma.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "boost/libs/math/performance/test_gamma.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": 25.5543859649, "max_line_length": 78, "alphanum_fraction": 0.6749965673, "num_tokens": 2201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5579394059550377}}
{"text": "/*\n\nMIT License\n\nCopyright (c) 2020, R. Gregor Wei\u00df, 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": "#include \"utils.hpp\"\n\n#include \"edlib/Basis/Basis1DZ2.hpp\"\n#include \"edlib/Basis/ToOriginalBasis.hpp\"\n#include \"edlib/Hamiltonians/TIXXZ.hpp\"\n#include \"edlib/Op/NodeMV.hpp\"\n\n#include \"edlib/EDP/ConstructSparseMat.hpp\"\n#include \"edlib/EDP/LocalHamiltonian.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Sparse>\n\n#include <unsupported/Eigen/KroneckerProduct>\n\n#include <Spectra/MatOp/SparseSymMatProd.h>\n#include <Spectra/SymEigsSolver.h>\n\n#include <catch2/catch.hpp>\n\n#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <random>\n\nusing namespace edlib;\n\ntemplate<typename T>\nEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>\ntwoQubitOp(uint32_t N, uint32_t pos1, uint32_t pos2, // NOLINT\n           const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v1,\n           const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v2)\n{\n    using namespace Eigen;\n    // const uint32_t dim = (1U << N);\n\n    assert(pos1 < pos2);\n\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> res(1, 1);\n    res(0, 0) = 1.0;\n\n    for(uint32_t i = 0; i < pos1; i++)\n    {\n        res = Eigen::kroneckerProduct(MatrixXd::Identity(2, 2), res).eval();\n    }\n    res = Eigen::kroneckerProduct(v1, res).eval();\n    for(uint32_t i = pos1 + 1; i < pos2; i++)\n    {\n        res = Eigen::kroneckerProduct(MatrixXd::Identity(2, 2), res).eval();\n    }\n    res = Eigen::kroneckerProduct(v2, res).eval();\n    for(uint32_t i = pos2 + 1; i < N; i++)\n    {\n        res = Eigen::kroneckerProduct(MatrixXd::Identity(2, 2), res).eval();\n    }\n    return res;\n}\n\ntemplate<typename T>\nEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>\nsingleQubitOp(int N, int pos, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v) // NOLINT\n{\n    using namespace Eigen;\n    // const uint32_t dim = (1u << N);\n\n    using MatrixT = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n    MatrixT res(1, 1);\n    res(0, 0) = 1.0;\n\n    for(int i = 0; i < pos; i++)\n    {\n        res = Eigen::kroneckerProduct(MatrixT::Identity(2, 2), res).eval();\n    }\n\n    res = Eigen::kroneckerProduct(v, res).eval();\n    for(int i = pos + 1; i < N; i++)\n    {\n        res = Eigen::kroneckerProduct(MatrixT::Identity(2, 2), res).eval();\n    }\n    return res;\n}\n\ntemplate<uint32_t N> class CompareXXZ\n{\nprivate:\n    double delta_;\n    Basis1DZ2<uint32_t> basis_;\n\n    Eigen::MatrixXd hamFull_;\n    double gsEnergy_;\n    Eigen::VectorXd gsVec_;\n\npublic:\n    constexpr static int k = (N / 2) * ((N / 2) % 2);\n    constexpr static int parity = 1 - 2 * static_cast<int>((N / 2) % 2);\n\n    explicit CompareXXZ(double delta) : delta_{delta}, basis_{N, k, parity, true}\n    {\n        using namespace Eigen;\n        static_assert(N % 2 == 0, \"N must be even\");\n\n        edp::LocalHamiltonian<double> lh(N, 2);\n        for(uint32_t i = 0; i < N; i++)\n        {\n            lh.addTwoSiteTerm({i, (i + 1) % N}, getSXXYY() + delta_ * getSZZ());\n        }\n        hamFull_ = MatrixXd(edp::constructSparseMat<double>(1U << N, lh));\n        SelfAdjointEigenSolver<MatrixXd> es;\n        es.compute(hamFull_);\n\n        gsEnergy_ = es.eigenvalues()[0];\n        gsVec_ = es.eigenvectors().col(0);\n    }\n\n    void Test()\n    {\n        using namespace Eigen;\n        using Spectra::CompInfo;\n        using Spectra::SortRule;\n        constexpr size_t max_iter = 1000;\n        constexpr double tol = 1e-10;\n\n        TIXXZ<uint32_t> ham(basis_, 1.0, delta_);\n        const int dim = basis_.getDim();\n\n        NodeMV mv(dim, 0, dim, ham);\n\n        Spectra::SymEigsSolver<NodeMV> eigs(mv, 2, 6);\n        eigs.init();\n        eigs.compute(SortRule::SmallestAlge, max_iter, tol, SortRule::SmallestAlge);\n        if(eigs.info() != CompInfo::Successful)\n        {\n            REQUIRE(false);\n        }\n        const double gsEnergy1 = eigs.eigenvalues()[0];\n\n        REQUIRE(gsEnergy_ == Approx(gsEnergy1).margin(1e-4));\n\n        const VectorXd subspaceGs = eigs.eigenvectors().col(0);\n        const VectorXd gsVec1 = [&]() -> VectorXd {\n            auto v = toOriginalVectorLM(basis_, subspaceGs.data());\n            return Map<VectorXd>(v.data(), 1U << N);\n        }();\n\n        const double gsEnergy2\n            = double(gsVec1.transpose() * hamFull_ * gsVec1) / double(gsVec1.transpose() * gsVec1);\n\n        REQUIRE(gsEnergy1 == Approx(gsEnergy2).margin(1e-6));\n        REQUIRE(std::abs(gsVec_.transpose() * gsVec1) == Approx(1.0).margin(1e-6));\n    }\n};\n\nTEST_CASE(\"Compare GS of XXZ using LocalHamiltonian and TIBasis\", \"[XXZGS]\")\n{\n    SECTION(\"TIBasis Z2 XXZ N=8\")\n    {\n        CompareXXZ<8> test(1.0);\n        test.Test();\n    }\n    SECTION(\"TIBasis Z2 XXZ N=10\")\n    {\n        CompareXXZ<10> test(1.0);\n        test.Test();\n    }\n    SECTION(\"TIBasis Z2 XXZ N=12\")\n    {\n        CompareXXZ<12> test(1.0);\n        test.Test();\n    }\n}\n", "meta": {"hexsha": "f948e2befd8447b49f78bb856a537935b8df8a51", "size": 4791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_xxz_gs.cpp", "max_stars_repo_name": "cecri/ExactDiagonalization", "max_stars_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_xxz_gs.cpp", "max_issues_repo_name": "cecri/ExactDiagonalization", "max_issues_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_xxz_gs.cpp", "max_forks_repo_name": "cecri/ExactDiagonalization", "max_forks_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8546511628, "max_line_length": 99, "alphanum_fraction": 0.6015445627, "num_tokens": 1457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.557939394478293}}
{"text": "#include \"MexPackUnpack.h\"\n#include \"mex.h\"\n#include <Eigen>\n\nusing namespace MexPackUnpackTypes;\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n\n  //argument 1 : real double precision scalar\n  //argument 2 : Single precision complex scalar\n  //argument 3 : Double precision complex matrix represented as pair of real matrices corresponding to real/imaginary component \n  //argument 4 : Double precision complex matrix represented as a pair of pointers, number of rows, and number of columns\n  //This will only work with Octave or matlab before 2017b (or newer MATLABs compiled without the -R2018a flag)\n  //Note: on MATLAB 2018b an newer (with the -R2018a compilation flag) you would replace\n  //CDSP with CDIP and EDCSM with EDCIM\n  MexUnpacker<double, std::complex<float>, EDCSM,  CDSP> my_unpack(nrhs, prhs);\n\n  \n  try {\n\n    auto [a, b, c, d] = my_unpack.unpackMex();\n    auto [cr, ci] = c; //cr and ci and Eigen::Map<MatrixXd> corresponding to real and imaginary parts of matrix\n    auto [d_p, d_M, d_N] = d; //dp is std::pair<double*,double*> (pointers to real and imginary part), d_M is number of rows, d_N is number of columns\n\n    Eigen::MatrixXcd c_comp(cr.rows(), cr.cols());\n    c_comp.real() = cr;\n    c_comp.imag() = ci;\n    c_comp *= a;\n    b*=a;\n    MexPacker<std::complex<double>, int, Eigen::MatrixXcd, CDSP> my_pack(nlhs, plhs);\n    my_pack.PackMex(b, 2, c_comp, d);\n\n  } catch (std::string s) {\n    mexPrintf(s.data());\n  }\n\n}\n", "meta": {"hexsha": "3930bdb6783f82b52e198b680787f58c49d7c7ae", "size": 1482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example_2.cpp", "max_stars_repo_name": "kantorset/MexPackUnpack", "max_stars_repo_head_hexsha": "18eb8a62b3a12f3faf3271590478165c997e1843", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/example_2.cpp", "max_issues_repo_name": "kantorset/MexPackUnpack", "max_issues_repo_head_hexsha": "18eb8a62b3a12f3faf3271590478165c997e1843", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example_2.cpp", "max_forks_repo_name": "kantorset/MexPackUnpack", "max_forks_repo_head_hexsha": "18eb8a62b3a12f3faf3271590478165c997e1843", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0, "max_line_length": 150, "alphanum_fraction": 0.6970310391, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.557939394478293}}
{"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": "#ifndef FX_DECON_M_HPP\n#define FX_DECON_M_HPP\n\n#include <armadillo>\n#include \"mconvert.h\"\n#include <cmath>\nusing namespace arma ;\n\nmat fx_decon(mat DATA, double dt, int lf, double mu, double flow, int fhigh) ;\nvoid ar_modeling(cx_vec x, int lf, double mu, cx_vec& yf, cx_vec& yb) ;\n\nmat fx_decon(mat DATA, double dt, int lf, double mu, double flow, int fhigh)\n{\n  cx_mat DATA_FX, DATA_FX_b, DATA_FX_f ;\n  cx_vec aux_in, aux_out_b, aux_out_f ;\n  int ihigh, ilow, k, nf, nt, ntraces ;\n  mat DATA_b, DATA_f ;\n  nt = DATA.n_rows;\n  ntraces = DATA.n_cols;\n  \n  nf = pow(2, m2cpp::nextpow2(nt)) ;\n  DATA_FX_f = arma::zeros<cx_mat>(nf, ntraces) ;\n  DATA_FX_b = arma::zeros<cx_mat>(nf, ntraces) ;\n  ilow = std::floor(flow*dt*nf)+1 ;\n  if (ilow<1)\n  {\n    ilow = 1 ;\n  }\n  ihigh = std::floor(fhigh*dt*nf)+1 ;\n  if (ihigh>std::floor(nf/2.0)+1)\n  {\n    ihigh = std::floor(nf/2.0)+1 ;\n  }\n  DATA_FX = m2cpp::fft<mat>(DATA, nf, 1) ;\n  for (k=ilow; k<=ihigh; k++)\n  {\n    aux_in = arma::trans(DATA_FX.row(k-1)) ;\n    ar_modeling(aux_in, lf, mu, aux_out_f, aux_out_b) ;\n    DATA_FX_f.row(k-1) = arma::trans(aux_out_f) ;\n    DATA_FX_b.row(k-1) = arma::trans(aux_out_b) ;\n  }\n  for (k=nf/2.0+2; k<=nf; k++)\n  {\n    DATA_FX_f.row(k-1) = arma::conj(DATA_FX_f.row(nf-k+1)) ;\n    DATA_FX_b.row(k-1) = arma::conj(DATA_FX_b.row(nf-k+1)) ;\n  }\n  DATA_f = arma::real(m2cpp::ifft<cx_mat>(DATA_FX_f, 1)) ;\n  DATA_f = DATA_f.rows(arma::span(0, nt-1)) ;\n  DATA_b = arma::real(m2cpp::ifft<cx_mat>(DATA_FX_b, 1)) ;\n  DATA_b = DATA_b.rows(arma::span(0, nt-1)) ;\n  DATA_f = (DATA_f+DATA_b) ;\n  DATA_f.cols(arma::span(lf, ntraces-lf-1)) = DATA_f.cols(arma::span(lf, ntraces-lf-1))/2.0 ;\n  return DATA_f ;\n}\n\nvoid ar_modeling(cx_vec x, int lf, double mu, cx_vec& yf, cx_vec& yb)\n{\n  cx_double beta ;\n  cx_mat B, M, temp ;\n  cx_vec C, R, ab, af, y ;\n  uword nx ;\n  nx = m2cpp::length(x) ;\n  y = x(arma::span(0, nx-lf-1)) ;\n  C = x(arma::span(1, nx-lf)) ;\n  R = x(arma::span(nx-lf, nx-1)) ;\n  M = m2cpp::hankel(C, R) ;\n  B = arma::trans(M)*M ;\n  beta = B(0, 0)*(cx_double) mu/100.0 ;\n  ab = arma::solve((B+beta*arma::eye<cx_mat>(lf, lf)), arma::trans(M), solve_opts::fast)*y ;\n  temp = M*ab ;\n  temp = arma::join_cols(temp, arma::zeros<cx_mat>(lf, 1)) ;\n  yb = temp ;\n  y = x(arma::span(lf, nx-1)) ;\n  C = x(arma::span(lf-1, nx-2)) ;\n  R = arma::flipud(x(arma::span(0, lf-1))) ;\n  M = toeplitz(C, R) ;\n  B = arma::trans(M)*M ;\n  beta = B(0, 0)*(cx_double) mu/100.0 ;\n  af = arma::solve((B+beta*arma::eye<cx_mat>(lf, lf)), arma::trans(M), solve_opts::fast)*y ;\n  temp = M*af ;\n  temp = arma::join_cols(arma::zeros<cx_mat>(lf, 1), temp) ;\n  yf = temp ;\n  return ;\n}\n#endif\n", "meta": {"hexsha": "01263d70030a116c3b970fcd7136657ea333ef46", "size": 2634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/data/fx_decon.cpp", "max_stars_repo_name": "neilferg/matlab2cpp", "max_stars_repo_head_hexsha": "aa26671fc73dad297c977511053b076e05bdd2df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/data/fx_decon.cpp", "max_issues_repo_name": "neilferg/matlab2cpp", "max_issues_repo_head_hexsha": "aa26671fc73dad297c977511053b076e05bdd2df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/data/fx_decon.cpp", "max_forks_repo_name": "neilferg/matlab2cpp", "max_forks_repo_head_hexsha": "aa26671fc73dad297c977511053b076e05bdd2df", "max_forks_repo_licenses": ["BSD-3-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.6279069767, "max_line_length": 93, "alphanum_fraction": 0.6070615034, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5579059136712404}}
{"text": "#include <iostream>\n#include <flower/net.h>\n#include <flower/layer/tanh.h>\n#include <flower/layer/sigmoid.h>\n#include <flower/layer/relu.h>\n#include <flower/layer/elu.h>\n#include <flower/layer/fully_connected.h>\n#include <flower/layer/dropout.h>\n#include <flower/gradient_descent.h>\n#include <flower/optimizer/momentum.h>\n#include <Eigen/CXX11/Tensor>\n\nusing namespace std;\n\nint main()\n{\n    flower::Net net = flower::Net();\n\n    net.add(flower::FullyConnected(3, 3));\n    net.add(flower::Elu());\n    net.add(flower::FullyConnected(3, 3));\n    net.add(flower::Relu());\n    net.add(flower::FullyConnected(3, 3));\n    net.add(flower::Sigmoid());\n\n    flower::GradientDescent trainer(&net, flower::Momentum());\n\n    Eigen::Tensor<double, 2> t_data(2, 3);\n    t_data.setValues({{0.05, 0.1, -0.5}, {0.1, -0.3, 0.4}});\n\n    Eigen::Tensor<double, 2> t_target(2, 3);\n    t_target.setValues({{0.01, 0.99, 1.0}, {0.9, 0.3, 0.2}});\n\n    std::cout << \"\\n\";\n\n    for (int i = 0; i < 50; ++i)\n    {\n        std::cout << \"epoch : \"\n                  << i\n                  << \" error: \"\n                  << trainer.feed(t_data, t_target)\n                  << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "3a9537d0a344666b1f458ded3789c2ba3e27c585", "size": 1179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Fs02/Flower", "max_stars_repo_head_hexsha": "b2a91c78fc6a72766abcf1cac620e22233899d99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-12-02T14:33:16.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-02T14:33:16.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "Fs02/Flower", "max_issues_repo_head_hexsha": "b2a91c78fc6a72766abcf1cac620e22233899d99", "max_issues_repo_licenses": ["MIT"], "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": "Fs02/Flower", "max_forks_repo_head_hexsha": "b2a91c78fc6a72766abcf1cac620e22233899d99", "max_forks_repo_licenses": ["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.085106383, "max_line_length": 62, "alphanum_fraction": 0.5801526718, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.6334102567576902, "lm_q1q2_score": 0.5579059072773419}}
{"text": "#pragma once\n\n#include <complex>\n#include <functional>\n#include <Eigen/Dense>\n#include <iostream>\n#include <memory>\n#include <set>\n#include <vector>\n\nnamespace prediction\n{\nenum State {X, Y, YAW, VX, STATES};\nenum Obs {X_OBS, Y_OBS, YAW_OBS, VX_OBS, OBSS};\nenum IMU {VX_IN, YAWRATE_IN, INPUTS};\n\nclass EKF {\n public:\n  EKF();\n  void initializeKF();\n  void initializeSim();\n  void estimate();\n  void motionUpdate(const double& dt, //current_time,\n                 Eigen::Vector4d& x, const Eigen::Vector2d& cont);\n  void predictionUpdate(const double& time, Eigen::Vector2d u);\n  void observationUpdate(Eigen::Vector4d z, Eigen::Matrix4d R);\n  Eigen::Vector4d getObservation();\n  Eigen::Vector4d getImu();\n\n  // simulation methods\n  void simulate(const double& time, const double& dt);\n\n\n private:\n  /*  Kalman Filter parameters */\n  // ground true states [x y yaw v]\n  Eigen::Vector4d xTruth{0, 0, 0, 0};\n\n  // estimated states by KF\n  Eigen::Vector4d xEst{xTruth};\n\n  // covariance matrix for process noise of KF\n  Eigen::Matrix<double, 4, 4> Q;\n\n  // intial covariance of estimation of KF\n  Eigen::Matrix<double, 4, 4> Pest;\n\n  // cov matrix for observation noise of KF\n  //Eigen::Vector4d vR{2.25, 2.25, 0.0027, 0.0025};\n  //Eigen::Matrix<double, 4, 4> R = vR.array().matrix().asDiagonal();\n\n\n\n  Eigen::Vector2d u;\n\n};\n\n}  // namespace EKF\n", "meta": {"hexsha": "7f3ec792d13daecf1c349bafd55f8eb46a8877a0", "size": 1343, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ekf.hpp", "max_stars_repo_name": "nobunoby/EKF", "max_stars_repo_head_hexsha": "610ac2ca1958173c771e1150992cea1e5d5d9da4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ekf.hpp", "max_issues_repo_name": "nobunoby/EKF", "max_issues_repo_head_hexsha": "610ac2ca1958173c771e1150992cea1e5d5d9da4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ekf.hpp", "max_forks_repo_name": "nobunoby/EKF", "max_forks_repo_head_hexsha": "610ac2ca1958173c771e1150992cea1e5d5d9da4", "max_forks_repo_licenses": ["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.7627118644, "max_line_length": 69, "alphanum_fraction": 0.6775874907, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5579059054446934}}
{"text": "// Copyright (c) 2018-2021 FRC Team 3512. All Rights Reserved.\n\n#pragma once\n\n#include <Eigen/Core>\n#include <frc/controller/LinearQuadraticRegulator.h>\n#include <frc/estimator/KalmanFilter.h>\n#include <frc/logging/CSVLogFile.h>\n#include <frc/system/LinearSystem.h>\n#include <frc/system/LinearSystemLoop.h>\n#include <frc/system/plant/DCMotor.h>\n#include <frc/system/plant/LinearSystemId.h>\n#include <frc/trajectory/TrapezoidProfile.h>\n#include <units/angle.h>\n#include <units/angular_velocity.h>\n\n#include \"Constants.hpp\"\n\nnamespace frc3512 {\n\nclass FourBarLiftController {\npublic:\n    // State tolerances in radians and radians/sec respectively.\n    static constexpr double kAngleTolerance = 0.05;\n    static constexpr double kAngularVelocityTolerance = 2.0;\n\n    FourBarLiftController();\n\n    FourBarLiftController(const FourBarLiftController&) = delete;\n    FourBarLiftController& operator=(const FourBarLiftController&) = delete;\n\n    /**\n     * Enables the control loop.\n     */\n    void Enable();\n\n    /**\n     * Disables the control loop.\n     */\n    void Disable();\n\n    /**\n     * Sets the end goal of the controller profile.\n     *\n     * @param goal Position in meters to set the goal to.\n     */\n    void SetGoal(double goal);\n\n    /**\n     * Sets the references.\n     *\n     * @param angle  Angle of the carriage in radians.\n     * @param angularVelocity  Angular velocity of the carriage in radians per\n     *                         second.\n     */\n    void SetReferences(units::radian_t angle,\n                       units::radians_per_second_t angularVelocity);\n\n    /**\n     * Returns whether or not position and velocity are tracking the profile.\n     */\n    bool AtReferences() const;\n\n    /**\n     * Returns whether or not the goal has been reached.\n     */\n    bool AtGoal() const;\n\n    /**\n     * Sets the current encoder measurement.\n     *\n     * @param measuredAngle Angle of the carriage in radians.\n     */\n    void SetMeasuredAngle(double measuredAngle);\n\n    /**\n     * Returns the control loop calculated voltage.\n     */\n    double ControllerVoltage() const;\n\n    /**\n     * Informs the controller if to use the climbing feedforward.\n     *\n     * @param climbing Whether or not to use the climbing feedforward.\n     */\n    void SetClimbing(bool climbing);\n\n    /**\n     * Returns the estimated angle.\n     */\n    double EstimatedAngle() const;\n\n    /**\n     * Returns the estimated angular velocity.\n     */\n    double EstimatedAngularVelocity() const;\n\n    /**\n     * Returns the error between the angle reference and the angle\n     * estimate.\n     */\n    double AngleError() const;\n\n    /**\n     * Returns the error between the angular velocity reference and the angular\n     * velocity estimate.\n     */\n    double AngularVelocityError() const;\n\n    /**\n     * Returns the current angle reference.\n     */\n    double AngleReference();\n\n    /**\n     * Returns the current angular velocity reference.\n     */\n    double AngularVelocityReference();\n\n    /**\n     * Executes the control loop for a cycle.\n     */\n    void Update();\n\n    /**\n     * Resets any internal state.\n     */\n    void Reset();\n\nprivate:\n    // The current sensor measurement.\n    Eigen::Matrix<double, 1, 1> m_y;\n    frc::TrapezoidProfile<units::radians>::State m_goal;\n\n    frc::TrapezoidProfile<units::radians>::Constraints constraints{\n        Constants::FourBarLift::kMaxV, Constants::FourBarLift::kMaxA};\n    frc::TrapezoidProfile<units::radians> m_angleProfile{constraints,\n                                                         {0_rad, 0_rad_per_s}};\n\n    frc::TrapezoidProfile<units::radians>::State m_profiledReference;\n\n    frc::LinearSystem<2, 1, 1> m_plant = [=] {\n        constexpr auto motor = frc::DCMotor::NEO();\n\n        // Arm moment of inertia\n        constexpr auto J = 0.6975_kg_sq_m;\n\n        // Gear ratio\n        constexpr double G = 302.22;\n\n        return frc::LinearSystemId::SingleJointedArmSystem(motor, J, G);\n    }();\n    frc::LinearQuadraticRegulator<2, 1> m_controller{\n        m_plant, {0.01245, 0.109726}, {9.0}, Constants::kDt};\n    frc::KalmanFilter<2, 1, 1> m_observer{\n        m_plant, {0.21745, 0.28726}, {0.01}, Constants::kDt};\n    frc::LinearSystemLoop<2, 1, 1> m_loop{m_plant, m_controller, m_observer,\n                                          12_V, Constants::kDt};\n\n    bool m_atReferences = false;\n    bool m_isEnabled = false;\n    bool m_climbing = false;\n\n    frc::CSVLogFile elevatorLogger{\"FourBarLift\",    \"EstPos (rad)\",\n                                   \"RefPos (rad)\",   \"Voltage (V)\",\n                                   \"EstVel (rad/s)\", \"RefVel (rad/s)\"};\n};\n\n}  // namespace frc3512\n", "meta": {"hexsha": "add33a857482e08c093d0c3f5c77334e2477eddf", "size": 4652, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/main/include/controllers/FourBarLiftController.hpp", "max_stars_repo_name": "frc3512/Robot-2019", "max_stars_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-05T01:06:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T15:18:49.000Z", "max_issues_repo_path": "src/main/include/controllers/FourBarLiftController.hpp", "max_issues_repo_name": "frc3512/Robot-2019", "max_issues_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main/include/controllers/FourBarLiftController.hpp", "max_forks_repo_name": "frc3512/Robot-2019", "max_forks_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T16:21:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-14T16:21:42.000Z", "avg_line_length": 27.3647058824, "max_line_length": 79, "alphanum_fraction": 0.625322442, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5579032830850762}}
{"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\u2013Tung\u2013Striebel 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": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n    This is an example illustrating the use of the support vector machine\n    utilities from the dlib C++ Library.  In particular, we show how to use the\n    C parametrization of the SVM in this example.\n\n    This example creates a simple set of data to train on and then shows\n    you how to use the cross validation and svm training functions\n    to find a good decision function that can classify examples in our\n    data set.\n\n\n    The data used in this example will be 2 dimensional data and will\n    come from a distribution where points with a distance less than 10\n    from the origin are labeled +1 and all other points are labeled\n    as -1.\n        \n*/\n\n\n#include <iostream>\n#include <dlib/svm.h>\n\nusing namespace std;\nusing namespace dlib;\n\n\n\n\n#if defined(BUILD_MONOLITHIC)\n#define main(cnt, arr)      dlib_svm_c_ex_main(cnt, arr)\n#endif\n\nint main(int argc, const char** argv)\n{\n    // The svm functions use column vectors to contain a lot of the data on\n    // which they operate. So the first thing we do here is declare a convenient\n    // typedef.  \n\n    // This typedef declares a matrix with 2 rows and 1 column.  It will be the\n    // object that contains each of our 2 dimensional samples.   (Note that if\n    // you wanted more than 2 features in this vector you can simply change the\n    // 2 to something else.  Or if you don't know how many features you want\n    // until runtime then you can put a 0 here and use the matrix.set_size()\n    // member function)\n    typedef matrix<double, 2, 1> sample_type;\n\n    // This is a typedef for the type of kernel we are going to use in this\n    // example.  In this case I have selected the radial basis kernel that can\n    // operate on our 2D sample_type objects.  You can use your own custom\n    // kernels with these tools as well, see custom_trainer_ex.cpp for an\n    // example.\n    typedef radial_basis_kernel<sample_type> kernel_type;\n\n\n    // Now we make objects to contain our samples and their respective labels.\n    std::vector<sample_type> samples;\n    std::vector<double> labels;\n\n    // Now let's put some data into our samples and labels objects.  We do this\n    // by looping over a bunch of points and labeling them according to their\n    // distance from the origin.\n    for (int r = -20; r <= 20; ++r)\n    {\n        for (int c = -20; c <= 20; ++c)\n        {\n            sample_type samp;\n            samp(0) = r;\n            samp(1) = c;\n            samples.push_back(samp);\n\n            // if this point is less than 10 from the origin\n            if (sqrt((double)r*r + c*c) <= 10)\n                labels.push_back(+1);\n            else\n                labels.push_back(-1);\n\n        }\n    }\n\n\n    // Here we normalize all the samples by subtracting their mean and dividing\n    // by their standard deviation.  This is generally a good idea since it\n    // often heads off numerical stability problems and also prevents one large\n    // feature from smothering others.  Doing this doesn't matter much in this\n    // example so I'm just doing this here so you can see an easy way to\n    // accomplish it.  \n    vector_normalizer<sample_type> normalizer;\n    // Let the normalizer learn the mean and standard deviation of the samples.\n    normalizer.train(samples);\n    // now normalize each sample\n    for (unsigned long i = 0; i < samples.size(); ++i)\n        samples[i] = normalizer(samples[i]); \n\n\n    // Now that we have some data we want to train on it.  However, there are\n    // two parameters to the training.  These are the C and gamma parameters.\n    // Our choice for these parameters will influence how good the resulting\n    // decision function is.  To test how good a particular choice of these\n    // parameters are we can use the cross_validate_trainer() function to perform\n    // n-fold cross validation on our training data.  However, there is a\n    // problem with the way we have sampled our distribution above.  The problem\n    // is that there is a definite ordering to the samples.  That is, the first\n    // half of the samples look like they are from a different distribution than\n    // the second half.  This would screw up the cross validation process but we\n    // can fix it by randomizing the order of the samples with the following\n    // function call.\n    randomize_samples(samples, labels);\n\n\n    // here we make an instance of the svm_c_trainer object that uses our kernel\n    // type.\n    svm_c_trainer<kernel_type> trainer;\n\n    // Now we loop over some different C and gamma values to see how good they\n    // are.  Note that this is a very simple way to try out a few possible\n    // parameter choices.  You should look at the model_selection_ex.cpp program\n    // for examples of more sophisticated strategies for determining good\n    // parameter choices.\n    cout << \"doing cross validation\" << endl;\n    for (double gamma = 0.00001; gamma <= 1; gamma *= 5)\n    {\n        for (double C = 1; C < 100000; C *= 5)\n        {\n            // tell the trainer the parameters we want to use\n            trainer.set_kernel(kernel_type(gamma));\n            trainer.set_c(C);\n\n            cout << \"gamma: \" << gamma << \"    C: \" << C;\n            // Print out the cross validation accuracy for 3-fold cross validation using\n            // the current gamma and C.  cross_validate_trainer() returns a row vector.\n            // The first element of the vector is the fraction of +1 training examples\n            // correctly classified and the second number is the fraction of -1 training\n            // examples correctly classified.\n            cout << \"     cross validation accuracy: \" \n                 << cross_validate_trainer(trainer, samples, labels, 3);\n        }\n    }\n\n\n    // From looking at the output of the above loop it turns out that good\n    // values for C and gamma for this problem are 5 and 0.15625 respectively.\n    // So that is what we will use.\n\n    // Now we train on the full set of data and obtain the resulting decision\n    // function.  The decision function will return values >= 0 for samples it\n    // predicts are in the +1 class and numbers < 0 for samples it predicts to\n    // be in the -1 class.\n    trainer.set_kernel(kernel_type(0.15625));\n    trainer.set_c(5);\n    typedef decision_function<kernel_type> dec_funct_type;\n    typedef normalized_function<dec_funct_type> funct_type;\n\n    // Here we are making an instance of the normalized_function object.  This\n    // object provides a convenient way to store the vector normalization\n    // information along with the decision function we are going to learn.  \n    funct_type learned_function;\n    learned_function.normalizer = normalizer;  // save normalization information\n    learned_function.function = trainer.train(samples, labels); // perform the actual SVM training and save the results\n\n    // print out the number of support vectors in the resulting decision function\n    cout << \"\\nnumber of support vectors in our learned_function is \" \n         << learned_function.function.basis_vectors.size() << endl;\n\n    // Now let's try this decision_function on some samples we haven't seen before.\n    sample_type sample;\n\n    sample(0) = 3.123;\n    sample(1) = 2;\n    cout << \"This is a +1 class example, the classifier output is \" << learned_function(sample) << endl;\n\n    sample(0) = 3.123;\n    sample(1) = 9.3545;\n    cout << \"This is a +1 class example, the classifier output is \" << learned_function(sample) << endl;\n\n    sample(0) = 13.123;\n    sample(1) = 9.3545;\n    cout << \"This is a -1 class example, the classifier output is \" << learned_function(sample) << endl;\n\n    sample(0) = 13.123;\n    sample(1) = 0;\n    cout << \"This is a -1 class example, the classifier output is \" << learned_function(sample) << endl;\n\n\n    // We can also train a decision function that reports a well conditioned\n    // probability instead of just a number > 0 for the +1 class and < 0 for the\n    // -1 class.  An example of doing that follows:\n    typedef probabilistic_decision_function<kernel_type> probabilistic_funct_type;  \n    typedef normalized_function<probabilistic_funct_type> pfunct_type;\n\n    pfunct_type learned_pfunct; \n    learned_pfunct.normalizer = normalizer;\n    learned_pfunct.function = train_probabilistic_decision_function(trainer, samples, labels, 3);\n    // Now we have a function that returns the probability that a given sample is of the +1 class.  \n\n    // print out the number of support vectors in the resulting decision function.  \n    // (it should be the same as in the one above)\n    cout << \"\\nnumber of support vectors in our learned_pfunct is \" \n         << learned_pfunct.function.decision_funct.basis_vectors.size() << endl;\n\n    sample(0) = 3.123;\n    sample(1) = 2;\n    cout << \"This +1 class example should have high probability.  Its probability is: \" \n         << learned_pfunct(sample) << endl;\n\n    sample(0) = 3.123;\n    sample(1) = 9.3545;\n    cout << \"This +1 class example should have high probability.  Its probability is: \" \n         << learned_pfunct(sample) << endl;\n\n    sample(0) = 13.123;\n    sample(1) = 9.3545;\n    cout << \"This -1 class example should have low probability.  Its probability is: \" \n         << learned_pfunct(sample) << endl;\n\n    sample(0) = 13.123;\n    sample(1) = 0;\n    cout << \"This -1 class example should have low probability.  Its probability is: \" \n         << learned_pfunct(sample) << endl;\n\n\n\n    // Another thing that is worth knowing is that just about everything in dlib\n    // is serializable.  So for example, you can save the learned_pfunct object\n    // to disk and recall it later like so:\n    serialize(\"saved_function.dat\") << learned_pfunct;\n\n    // Now let's open that file back up and load the function object it contains.\n    deserialize(\"saved_function.dat\") >> learned_pfunct;\n\n    // Note that there is also an example program that comes with dlib called\n    // the file_to_code_ex.cpp example.  It is a simple program that takes a\n    // file and outputs a piece of C++ code that is able to fully reproduce the\n    // file's contents in the form of a std::string object.  So you can use that\n    // along with the std::istringstream to save learned decision functions\n    // inside your actual C++ code files if you want.  \n\n\n\n\n    // Lastly, note that the decision functions we trained above involved well\n    // over 200 basis vectors.  Support vector machines in general tend to find\n    // decision functions that involve a lot of basis vectors.  This is\n    // significant because the more basis vectors in a decision function, the\n    // longer it takes to classify new examples.  So dlib provides the ability\n    // to find an approximation to the normal output of a trainer using fewer\n    // basis vectors.  \n\n    // Here we determine the cross validation accuracy when we approximate the\n    // output using only 10 basis vectors.  To do this we use the reduced2()\n    // function.  It takes a trainer object and the number of basis vectors to\n    // use and returns a new trainer object that applies the necessary post\n    // processing during the creation of decision function objects.\n    cout << \"\\ncross validation accuracy with only 10 support vectors: \" \n         << cross_validate_trainer(reduced2(trainer,10), samples, labels, 3);\n\n    // Let's print out the original cross validation score too for comparison.\n    cout << \"cross validation accuracy with all the original support vectors: \" \n         << cross_validate_trainer(trainer, samples, labels, 3);\n\n    // When you run this program you should see that, for this problem, you can\n    // reduce the number of basis vectors down to 10 without hurting the cross\n    // validation accuracy. \n\n\n    // To get the reduced decision function out we would just do this:\n    learned_function.function = reduced2(trainer,10).train(samples, labels);\n    // And similarly for the probabilistic_decision_function: \n    learned_pfunct.function = train_probabilistic_decision_function(reduced2(trainer,10), samples, labels, 3);\n}\n\n", "meta": {"hexsha": "a0ffb0085be8599222a366fd139e2e10c719e85d", "size": 12105, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/svm_c_ex.cpp", "max_stars_repo_name": "GerHobbelt/dlib", "max_stars_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/svm_c_ex.cpp", "max_issues_repo_name": "GerHobbelt/dlib", "max_issues_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/svm_c_ex.cpp", "max_forks_repo_name": "GerHobbelt/dlib", "max_forks_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3406593407, "max_line_length": 119, "alphanum_fraction": 0.6858323007, "num_tokens": 2865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.5578429756348668}}
{"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 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_histogram_operators\n\n#include <boost/histogram.hpp>\n#include <cassert>\n#include <vector>\n\nint main() {\n  using namespace boost::histogram;\n\n  // make two histograms\n  auto h1 = make_histogram(axis::regular<>(2, -1.0, 1.0));\n  auto h2 = make_histogram(axis::regular<>(2, -1.0, 1.0));\n\n  h1(-0.5); // counts are: 1 0\n  h2(0.5);  // counts are: 0 1\n\n  // add them\n  auto h3 = h1;\n  h3 += h2; // counts are: 1 1\n\n  // adding multiple histograms at once is likely to be optimized by the compiler so that\n  // superfluous temporaries avoided, but no guarantees are given; use this equivalent\n  // code when you want to make sure: h4 = h1; h4 += h2; h4 += h3;\n  auto h4 = h1 + h2 + h3; // counts are: 2 2\n\n  assert(h4.at(0) == 2 && h4.at(1) == 2);\n\n  // multiply by number; h4 *= 2 is not allowed, because the result of a multiplication is\n  // not a histogram anymore, it has the type boost::histogram::grid<...>)\n  auto g4 = h4 * 2; // counts are: 4 4\n\n  // divide by number; g4 /= 4 also works\n  auto g5 = g4 / 4; // counts are: 1 1\n\n  assert(g5.at(0) == 1 && g5.at(1) == 1);\n  assert(g4 != g5 && g4 == 4 * g5);\n\n  // note the special effect of multiplication on weight_storage\n  auto h = make_histogram_with(weight_storage(), axis::regular<>(2, -1.0, 1.0));\n  h(-0.5);\n\n  // counts are: 1 0\n  assert(h.at(0).value() == 1 && h.at(1).value() == 0);\n\n  auto h_sum = h + h;\n  auto g_mul = 2 * h;\n\n  // values are the same as expected...\n  assert(h_sum.at(0).value() == g_mul.at(0).value());\n  // ... but variances differ\n  assert(h_sum.at(0).variance() == 2 && g_mul.at(0).variance() == 4);\n\n  // equality operator checks variances, so histograms are not equal\n  assert(h_sum != g_mul);\n}\n\n//]\n", "meta": {"hexsha": "dc62a8b167e7b2b99c73e2a059f4aa491f2a2fb0", "size": 1895, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/histogram/examples/guide_histogram_operators.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/histogram/examples/guide_histogram_operators.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/histogram/examples/guide_histogram_operators.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": 29.609375, "max_line_length": 90, "alphanum_fraction": 0.6300791557, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.5578429600933792}}
{"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": "#pragma once\n#include <cstdint>\n#include <cassert>\n#include <algorithm>\n#include <map>\n#include <boost/dynamic_bitset.hpp>\n\n#include \"../Basis/AbstractBasis1D.hpp\"\n\ntemplate<typename UINT>\nclass TIXXZ\n{\nprivate:\n\tconst edlib::AbstractBasis1D<UINT>& basis_;\n\tdouble J_;\n\tdouble delta_;\n\npublic:\n\tTIXXZ(const edlib::AbstractBasis1D<UINT>& basis, double J, double delta)\n\t\t: basis_(basis), J_(J), delta_(delta)\n\t{\n\t\t\n\t}\n\n\tstd::map<int, double> getCol(UINT n) const\n\t{\n\t\tunsigned int N = basis_.getN();\n\n\t\tUINT a = basis_.getNthRep(n);\n\t\tconst boost::dynamic_bitset<> bs(N, a);\n\n\t\tstd::map<int, double> m;\n\t\tfor(unsigned int i = 0; i < N; i++)\n\t\t{\n\t\t\t//Next-nearest\n\t\t\t{\n\t\t\t\tunsigned int j = (i+1)%N;\n\t\t\t\tint sgn = (1-2*bs[i])*(1-2*bs[j]);\n\n\t\t\t\tm[n] += J_*delta_*sgn;\n\t\t\t\t\n\t\t\t\tUINT s = a;\n\t\t\t\ts ^= basis_.mask({i,j});\n\n\t\t\t\tint bidx;\n\t\t\t\tdouble coeff;\n\n\t\t\t\tstd::tie(bidx, coeff) = basis_.hamiltonianCoeff(s, n);\n\t\t\t\t\n\t\t\t\tif(bidx >= 0)\n\t\t\t\t{\n\t\t\t\t\tm[bidx] += J_*(1.0-sgn)*coeff;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn m;\n\t}\n};\n", "meta": {"hexsha": "d54472291b789832a5139fcc6786832ab57feece", "size": 1005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/edlib/Hamiltonians/TIXXZ.hpp", "max_stars_repo_name": "chaeyeunpark/ExactDiagonalization", "max_stars_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T08:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:47:05.000Z", "max_issues_repo_path": "include/edlib/Hamiltonians/TIXXZ.hpp", "max_issues_repo_name": "chaeyeunpark/ExactDiagonalization", "max_issues_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T19:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T19:02:14.000Z", "max_forks_repo_path": "include/edlib/Hamiltonians/TIXXZ.hpp", "max_forks_repo_name": "chaeyeunpark/ExactDiagonalization", "max_forks_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-22T18:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T18:59:11.000Z", "avg_line_length": 17.0338983051, "max_line_length": 73, "alphanum_fraction": 0.5990049751, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597268408361, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5577358133214961}}
{"text": "//\n// Copyright (c) 2020 INRIA\n//\n\n#include \"pinocchio/multibody/liegroup/liegroup.hpp\"\n#include \"pinocchio/multibody/liegroup/liegroup-collection.hpp\"\n#include \"pinocchio/multibody/liegroup/liegroup-generic.hpp\"\n#include \"pinocchio/multibody/liegroup/cartesian-product-variant.hpp\"\n#include \"pinocchio/multibody/liegroup/cartesian-product.hpp\"\n\n#include \"pinocchio/multibody/joint/joint-generic.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing namespace pinocchio;\n\nnamespace pinocchio {\ntemplate<typename Derived>\nstd::ostream& operator<< (std::ostream& os, const LieGroupBase<Derived>& lg)\n{\n  return os << lg.name();\n}\ntemplate<typename LieGroupCollection>\nstd::ostream& operator<< (std::ostream& os, const LieGroupGenericTpl<LieGroupCollection>& lg)\n{\n  return os << lg.name();\n}\n} // namespace pinocchio\n\n\ntemplate<typename Scalar, int Options, template<typename S, int O> class LieGroupCollectionTpl>\nstruct TestCartesianProduct\n{\n  \n  typedef LieGroupCollectionTpl<Scalar,Options> LieGroupCollection;\n  \n  typedef LieGroupGenericTpl<LieGroupCollection> LieGroupGeneric;\n  typedef typename LieGroupGeneric::ConfigVector_t ConfigVector_t;\n  typedef typename LieGroupGeneric::TangentVector_t TangentVector_t;\n  \n  typedef CartesianProductOperationVariantTpl<Scalar, Options, LieGroupCollectionTpl > CartesianProduct;\n  \n  template<typename Derived>\n  void operator() (const LieGroupBase<Derived> & lg) const\n  {\n    LieGroupGenericTpl<LieGroupCollection> lg_generic(lg.derived());\n    CartesianProduct cp(lg_generic);\n    test(lg,cp);\n    \n    CartesianProduct cp2;\n    cp2.append(lg);\n    BOOST_CHECK(cp == cp2);\n  }\n  \n  template<typename LieGroup>\n  static void test(const LieGroupBase<LieGroup> & lg,\n                   const CartesianProduct & cp)\n  {\n    BOOST_CHECK(lg.nq() == cp.nq());\n    BOOST_CHECK(lg.nv() == cp.nv());\n    \n    std::cout << \"name: \" << cp.name() << std::endl;\n    \n    BOOST_CHECK(lg.neutral() == cp.neutral());\n\n    typedef typename LieGroup::ConfigVector_t ConfigVector;\n    typedef typename LieGroup::TangentVector_t TangentVector;\n    typedef typename LieGroup::JacobianMatrix_t JacobianMatrix;\n\n    ConfigVector q0 = lg.random();\n    ConfigVector q1 = lg.random();\n    TangentVector v = TangentVector_t::Random(lg.nv());\n    ConfigVector qout_ref(lg.nq()), qout(lg.nq());\n    lg.integrate(q0, v, qout_ref);\n    cp.integrate(q0, v, qout);\n    \n    BOOST_CHECK(qout.isApprox(qout_ref));\n    \n    TangentVector v_diff_ref(lg.nv()), v_diff(lg.nv());\n    lg.difference(q0,q1,v_diff_ref);\n    cp.difference(q0,q1,v_diff);\n    \n    BOOST_CHECK(v_diff_ref.isApprox(v_diff));\n    BOOST_CHECK_EQUAL(lg.squaredDistance(q0, q1), cp.squaredDistance(q0, q1));\n    BOOST_CHECK_EQUAL(lg.distance(q0, q1), cp.distance(q0, q1));\n    \n    JacobianMatrix\n    J_ref(JacobianMatrix::Zero(lg.nv(),lg.nv())),\n    J(JacobianMatrix::Zero(lg.nv(),lg.nv()));\n    \n    lg.dDifference(q0, q1, J_ref, ARG0);\n    cp.dDifference(q0, q1, J, ARG0);\n    \n    BOOST_CHECK(J.isApprox(J_ref));\n    \n    lg.dDifference(q0, q1, J_ref, ARG1);\n    cp.dDifference(q0, q1, J, ARG1);\n    \n    BOOST_CHECK(J.isApprox(J_ref));\n    \n    lg.dIntegrate(q0, v, J_ref, ARG0);\n    cp.dIntegrate(q0, v, J, ARG0);\n    \n    BOOST_CHECK(J.isApprox(J_ref));\n    \n    lg.dIntegrate(q0, v, J_ref, ARG1);\n    cp.dIntegrate(q0, v, J, ARG1);\n    \n    BOOST_CHECK(J.isApprox(J_ref));\n    \n    BOOST_CHECK(cp.isSameConfiguration(q0,q0));\n    ConfigVector q_rand;\n    cp.random(q_rand);\n    ConfigVector q_rand_copy = q_rand;\n    \n    lg.normalize(q_rand_copy);\n    cp.normalize(q_rand);\n    BOOST_CHECK(q_rand.isApprox(q_rand_copy));\n    \n    const ConfigVector lb(-ConfigVector::Ones(lg.nq()));\n    const ConfigVector ub( ConfigVector::Ones(lg.nq()));\n    \n    cp.randomConfiguration(lb, ub, q_rand);\n  }\n};\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_cartesian_product_with_liegroup_variant)\n{\n  boost::mpl::for_each<LieGroupCollectionDefault::LieGroupVariant::types>(TestCartesianProduct<double,0,LieGroupCollectionDefaultTpl>());\n}\n\nBOOST_AUTO_TEST_CASE(test_cartesian_product_vs_cartesian_product_variant)\n{\n  typedef SpecialEuclideanOperationTpl<3,double,0> SE3;\n  typedef VectorSpaceOperationTpl<3,double,0> Rn;\n  \n  typedef CartesianProductOperation<SE3, Rn> CPRef;\n  typedef CartesianProductOperationVariantTpl<double, 0, LieGroupCollectionDefaultTpl > CP;\n  \n  SE3 lg1; Rn lg2;\n  typedef LieGroupGenericTpl<CP::LieGroupCollection> LieGroupGeneric;\n  LieGroupGeneric lg1_variant(lg1);\n  LieGroupGeneric lg2_variant(lg2);\n  \n  CP cartesian_product(lg1_variant,lg2_variant);\n  CP cartesian_product2(lg1_variant); cartesian_product2.append(lg2_variant);\n  std::cout << \"cartesian_product: \" << cartesian_product << std::endl;\n  \n  BOOST_CHECK(cartesian_product == cartesian_product2);\n  CPRef cartesian_product_ref;\n  \n  TestCartesianProduct<double,0,LieGroupCollectionDefaultTpl>::test(cartesian_product_ref,\n                                                                    cartesian_product);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "30b53bdea76f88518860287b69c41a9a9438aff6", "size": 5107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/cartesian-product-liegroups.cpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 716.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T16:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:26:58.000Z", "max_issues_repo_path": "unittest/cartesian-product-liegroups.cpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1130.0, "max_issues_repo_issues_event_min_datetime": "2015-02-21T17:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:06:22.000Z", "max_forks_repo_path": "unittest/cartesian-product-liegroups.cpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 31.7204968944, "max_line_length": 137, "alphanum_fraction": 0.7188173096, "num_tokens": 1355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5574834160918248}}
{"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": "//cl /EHsc /I D:\\Project\\boost_1_53_0\\boost_1_53_0\\ transform_iterator.cpp\n#include <iostream>\n#include <functional>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/permutation_iterator.hpp>\n#include <boost/functional.hpp>\n\ntemplate< typename T >\nstruct square\n{\n    T operator() (const T& x)  const { return x * x; }\n    typedef T result_type;\n};\n\n\n\nint main()\n{\n\n\tint x[] = { 1, 2, 3, 4, 5, 6, 7, 8 };\n\tint y[] = { 1, 2, 3, 4, 5, 6, 7, 8 };\n\tconst int N = sizeof(x)/sizeof(int);\n\n\ttypedef square <int>  Function;\n\n    //Example 1///////////////////////////////\n\ttypedef boost::counting_iterator<int>                       count_iterator;\n\ttypedef boost::transform_iterator<Function, count_iterator> square_transform_count_iterator;\n\tcount_iterator count_i_begin(0), count_i_end(N);\n\tsquare_transform_count_iterator square_transform_begin(count_i_begin, Function());\n\tsquare_transform_count_iterator square_transform_end  (count_i_end,   Function());\n\n\tstd::cout << \"\\n\\nSquaring with counting iterator:\" << std::endl;\n\twhile (square_transform_begin != square_transform_end)\n\t  std::cout << *square_transform_begin++ << \" \";\n\tstd::cout << std::endl;\n\n\t//Example 2///////////////////////////////\n\ttypedef boost::transform_iterator<Function, int *> square_transform_raw_iterator;\n\t{\n\t\tsquare_transform_raw_iterator square_raw_begin(x, Function());\n\t\tsquare_transform_raw_iterator square_raw_end(x+N, Function());\n\t\tstd::cout << \"\\n\\nSquaring with raw input buffer:\" << std::endl;\n\t\twhile (square_raw_begin != square_raw_end)\n\t\t  std::cout << *square_raw_begin++ << \" \" ;\n\t\tstd::cout << std::endl;\n\n\t\tstd::cout << \"Checking whether input buffer is modified.\\n Input Buffer x is:\" << std::endl;\n\t\tfor(int index=0; index<N; index++)\n\t\t  std::cout << x[index] << \" \" ;\n\t\tstd::cout << std::endl;\n\t}\n\n\t//Example 3///////////////////////////////\n\ttypedef boost::transform_iterator<Function, square_transform_raw_iterator> square_transform_transform_iterator;\n\t{\n\t\tsquare_transform_raw_iterator square_raw_begin(x, Function());\n\t\tsquare_transform_raw_iterator square_raw_end(x+N, Function());\n\t\tsquare_transform_transform_iterator square_transform_begin(square_raw_begin, Function());\n\t\tsquare_transform_transform_iterator square_transform_end  (square_raw_end,   Function());\n\n\t\tstd::cout << \"\\nExample 3\\nSquare and Square of the raw input buffer:\" << std::endl;\n\t\twhile (square_transform_begin != square_transform_end)\n\t\t  std::cout << *square_transform_begin++ << \" \" ;\n\t\tstd::cout << std::endl;\n\n\t\tstd::cout << \"Checking whether input buffer is modified.\\n Input Buffer x is:\" << std::endl;\n\t\tfor(int index=0; index<N; index++)\n\t\t  std::cout << x[index] << \" \" ;\n\t\tstd::cout << std::endl;\n\t}\n\n\ttypedef boost::permutation_iterator<square_transform_raw_iterator, count_iterator> permutation_iterator;\n\t//Example 4///////////////////////////////\n    {\n\t\tsquare_transform_raw_iterator square_raw_begin(x, Function());\n\t\tsquare_transform_raw_iterator square_raw_end(x+N, Function());\n\n\t\tpermutation_iterator perm_begin(square_raw_begin, count_i_begin);\n\t\tpermutation_iterator perm_end  (square_raw_end, count_i_end);\n\n\t\tstd::cout << \"\\nUsing Permutation Iterator with transform and counting Iterator:\" << std::endl;\n\t\twhile (perm_begin != perm_end)\n\t\t  std::cout << *perm_begin++ << \" \";\n\t\tstd::cout << std::endl;\n\t}\n\n    //Example 5///////////////////////////////\n    {\n\t\ttypedef boost::permutation_iterator<int *, count_iterator> permute_iterator;\n\t\tpermute_iterator perm_begin(x, count_i_begin);\n\t\tpermute_iterator perm_end  (x+N, count_i_end);\n        //First modify\n\t\t*perm_begin = 10;\n\n\t\tstd::cout << \"\\nUsing Permutation Iterator with Simple buffer:\" << std::endl;\n\t\twhile (perm_begin != perm_end)\n\t\t  std::cout << *perm_begin++ << \" \";\n\t\tstd::cout << std::endl;\n\t}\n\n    //Example 5///////////////////////////////\n    {\n\t\ttypedef boost::permutation_iterator<int *, count_iterator> permute_iterator;\n\t\ttypedef boost::transform_iterator<Function, permute_iterator> permute_transform_iterator;\n\t\tpermute_iterator perm_begin(x, count_i_begin);\n\t\tpermute_iterator perm_end  (x+N, count_i_end);\n\n\t\tpermute_transform_iterator perm_transform_begin(perm_begin, Function());\n\t\tpermute_transform_iterator perm_transform_end  (perm_end, Function());\n\t\t//First modify\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "c04bc5ab9b735d61df476ece259b8d8d0ea26797", "size": 4344, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost iterator/transform_iterator.cpp", "max_stars_repo_name": "ravibanger/github-work", "max_stars_repo_head_hexsha": "cfbbf2cd1f6d09d55c940e49b2be03eb58bc7c03", "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": "boost iterator/transform_iterator.cpp", "max_issues_repo_name": "ravibanger/github-work", "max_issues_repo_head_hexsha": "cfbbf2cd1f6d09d55c940e49b2be03eb58bc7c03", "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": "boost iterator/transform_iterator.cpp", "max_forks_repo_name": "ravibanger/github-work", "max_forks_repo_head_hexsha": "cfbbf2cd1f6d09d55c940e49b2be03eb58bc7c03", "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": 37.1282051282, "max_line_length": 112, "alphanum_fraction": 0.6919889503, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5574834084186845}}
{"text": "// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n/*\n   confidence_interval_test.cc\n   Copyright (c) 2010 mldb.ai inc.  All rights reserved.\n*/\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n#include \"mldb/utils/confidence_intervals.h\"\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n\n\nusing namespace std;\nusing namespace MLDB;\n\n\nBOOST_AUTO_TEST_CASE( conf_intervals )\n{\n    ConfidenceIntervals ci(0.5);\n    vector<double> sample = {1.0,1.0,2.0,3.0,3.0};\n    BOOST_CHECK_GE(2, ci.bootstrapMeanLowerBound(sample, 10000, 4));\n    BOOST_CHECK_LE(2, ci.bootstrapMeanUpperBound(sample, 10000, 4));\n    auto b = ci.bootstrapMeanTwoSidedBound(sample, 10000, 4);\n    BOOST_CHECK_GE(2, b.first);\n    BOOST_CHECK_LE(2, b.second);\n}\n\nBOOST_AUTO_TEST_CASE( conf_intervals_wilson )\n{\n    // from boost doc:\n    // In order to obtain a two sided bound on the success fraction, you call both find_lower_bound_on_p and find_upper_bound_on_p each with the same arguments. If the desired risk level that the true success fraction lies outside the bounds is \u03b1, then you pass \u03b1/2 to these functions. So for example a two sided 95% confidence interval would be obtained by passing \u03b1 = 0.025 to each of the functions. \n    float confidence = 0.8;\n    float alpha = (1 - confidence) / 2;\n\n    // comparing against http://epitools.ausvet.com.au/content.php?page=CIProportion&SampleSize=200&Positive=35&Conf=0.8&Digits=3\n    // and https://gist.github.com/paulgb/6627336\n\n    cout << \"Wilson\" << endl;\n    ConfidenceIntervals cI(alpha, \"wilson\");\n    BOOST_CHECK_CLOSE( cI.binomialLowerBound(200, 35), 0.1432, 0.1);\n    BOOST_CHECK_CLOSE( cI.binomialUpperBound(200, 35), 0.212, 0.1);\n\n    cout << \"CP\" << endl;\n    ConfidenceIntervals cI2(alpha, \"clopper_pearson\");\n    BOOST_CHECK_CLOSE( cI2.binomialLowerBound(200, 35), 0.14065, 0.1);\n    BOOST_CHECK_CLOSE( cI2.binomialUpperBound(200, 35), 0.2144, 0.1);\n}\n\n", "meta": {"hexsha": "fb1645c24165205a2c68012b9b9e7507739a9fcb", "size": 1930, "ext": "cc", "lang": "C++", "max_stars_repo_path": "testing/MLDB-1092_confidence_intervals_test.cc", "max_stars_repo_name": "kstepanmpmg/mldb", "max_stars_repo_head_hexsha": "f78791cd34d01796705c0f173a14359ec1b2e021", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 665.0, "max_stars_repo_stars_event_min_datetime": "2015-12-09T17:00:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:46:46.000Z", "max_issues_repo_path": "testing/MLDB-1092_confidence_intervals_test.cc", "max_issues_repo_name": "tomzhang/mldb", "max_issues_repo_head_hexsha": "a09cf2d9ca454d1966b9e49ae69f2fe6bf571494", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 797.0, "max_issues_repo_issues_event_min_datetime": "2015-12-09T19:48:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T02:19:47.000Z", "max_forks_repo_path": "testing/MLDB-1092_confidence_intervals_test.cc", "max_forks_repo_name": "matebestek/mldb", "max_forks_repo_head_hexsha": "f78791cd34d01796705c0f173a14359ec1b2e021", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 103.0, "max_forks_repo_forks_event_min_datetime": "2015-12-25T04:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T02:55:22.000Z", "avg_line_length": 37.8431372549, "max_line_length": 402, "alphanum_fraction": 0.7274611399, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.5574834038475966}}
{"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": "#include <geometry.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n\n#include <vector>\n\ntypedef tiny::MathTypes<float> MT;\ntypedef MT::vector3_type       V;\ntypedef MT::quaternion_type    Q;\ntypedef MT::real_type          T;\n\nclass ContactInfo\n{\npublic:\n\n  V m_point;\n  V m_normal;\n  T m_distance;\n\n};\n\n\nclass MyCallback\n  : public geometry::ContactsCallback<V>\n{\npublic:\n\n  std::vector<ContactInfo> m_contacts;\n\npublic:\n\n  void operator()(\n                  V const & point\n                  , V const & normal\n                  , typename V::real_type const & distance\n                  )\n  {\n    ContactInfo info;\n\n    info.m_point = point;\n    info.m_normal = normal;\n    info.m_distance = distance;\n\n    m_contacts.push_back(info);\n  }\n\n};\n\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(contacts_obb_sphere_test)\n{\n  // Touching rigth side\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    V const centerB = V::make(2.0, 0.0, 0.0);\n    T const radiusB = 1.0;\n\n    geometry::OBB<MT>   const obb    = geometry::make_obb<MT>(centerA, qA, half_extA);\n    geometry::Sphere<V> const sphere = geometry::make_sphere(centerB, radiusB);\n\n    MyCallback callback;\n\n    geometry::contacts_obb_sphere(obb, sphere, 0.0, callback, false);\n\n    BOOST_CHECK(callback.m_contacts.size() == 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[0], 1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[0], 1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, 0.0, 0.01);\n\n  }\n  // Separating rigth side\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    V const centerB = V::make(2.1, 0.0, 0.0);\n    T const radiusB = 1.0;\n\n    geometry::OBB<MT>   const obb    = geometry::make_obb<MT>(centerA, qA, half_extA);\n    geometry::Sphere<V> const sphere = geometry::make_sphere(centerB, radiusB);\n\n    MyCallback callback;\n\n    geometry::contacts_obb_sphere(obb, sphere, 0.0, callback, false);\n\n    BOOST_CHECK(callback.m_contacts.size() == 0u);\n  }\n  // Penetration rigth side\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    V const centerB = V::make(1.5, 0.0, 0.0);\n    T const radiusB = 1.0;\n\n    geometry::OBB<MT>   const obb    = geometry::make_obb<MT>(centerA, qA, half_extA);\n    geometry::Sphere<V> const sphere = geometry::make_sphere(centerB, radiusB);\n\n    MyCallback callback;\n\n    geometry::contacts_obb_sphere(obb, sphere, 0.0, callback, false);\n\n    BOOST_CHECK(callback.m_contacts.size() == 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[0], 1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[0], 1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.5, 0.01);\n    \n  }\n  // Penetration rigth side flipped-case\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    V const centerB = V::make(1.5, 0.0, 0.0);\n    T const radiusB = 1.0;\n\n    geometry::OBB<MT>   const obb    = geometry::make_obb<MT>(centerA, qA, half_extA);\n    geometry::Sphere<V> const sphere = geometry::make_sphere(centerB, radiusB);\n\n    MyCallback callback;\n\n    geometry::contacts_obb_sphere(obb, sphere, 0.0, callback, true);\n\n    BOOST_CHECK(callback.m_contacts.size() == 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[0], 1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[0],-1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.5, 0.01);\n    \n  }\n\n  // Touching left side\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    V const centerB = V::make(-2.0, 0.0, 0.0);\n    T const radiusB = 1.0;\n\n    geometry::OBB<MT>   const obb    = geometry::make_obb<MT>(centerA, qA, half_extA);\n    geometry::Sphere<V> const sphere = geometry::make_sphere(centerB, radiusB);\n\n    MyCallback callback;\n\n    geometry::contacts_obb_sphere(obb, sphere, 0.0, callback, false);\n\n    BOOST_CHECK(callback.m_contacts.size() == 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[0],-1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[0],-1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, 0.0, 0.01);\n\n  }\n  // Separating left side\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    V const centerB = V::make(-2.1, 0.0, 0.0);\n    T const radiusB = 1.0;\n\n    geometry::OBB<MT>   const obb    = geometry::make_obb<MT>(centerA, qA, half_extA);\n    geometry::Sphere<V> const sphere = geometry::make_sphere(centerB, radiusB);\n\n    MyCallback callback;\n\n    geometry::contacts_obb_sphere(obb, sphere, 0.0, callback, false);\n\n    BOOST_CHECK(callback.m_contacts.size() == 0u);\n  }\n  // Penetration left side\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    V const centerB = V::make(-1.5, 0.0, 0.0);\n    T const radiusB = 1.0;\n\n    geometry::OBB<MT>   const obb    = geometry::make_obb<MT>(centerA, qA, half_extA);\n    geometry::Sphere<V> const sphere = geometry::make_sphere(centerB, radiusB);\n\n    MyCallback callback;\n\n    geometry::contacts_obb_sphere(obb, sphere, 0.0, callback, false);\n\n    BOOST_CHECK(callback.m_contacts.size() == 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[0], -1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[0], -1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.5, 0.01);\n\n  }\n  // Penetration left side flipped-case\n  {\n    V const centerA   = V::make(0.0, 0.0, 0.0);\n    V const half_extA = V::make(1.0, 1.0, 1.0);\n    Q const qA        = Q::identity();\n\n    V const centerB = V::make(-1.5, 0.0, 0.0);\n    T const radiusB = 1.0;\n\n    geometry::OBB<MT>   const obb    = geometry::make_obb<MT>(centerA, qA, half_extA);\n    geometry::Sphere<V> const sphere = geometry::make_sphere(centerB, radiusB);\n\n    MyCallback callback;\n\n    geometry::contacts_obb_sphere(obb, sphere, 0.0, callback, true);\n\n    BOOST_CHECK(callback.m_contacts.size() == 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[0], -1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point[2], 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[0], 1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[1], 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal[2], 0.0, 0.01);\n    \n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.5, 0.01);\n    \n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "f9a2833bea198298411beeea5d372598ba1f01f3", "size": 8515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_obb_sphere/geometry_contacts_obb_sphere.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_obb_sphere/geometry_contacts_obb_sphere.cpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_obb_sphere/geometry_contacts_obb_sphere.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": 30.8514492754, "max_line_length": 86, "alphanum_fraction": 0.6529653553, "num_tokens": 2862, "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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n#include <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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// Written by Cornelius Steinhardt\n\n#include <cmath>\n#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": "/*\n * Copyright (c) 2018, Sunanda Bose (Neel Basu) (neel.basu.z@gmail.com) \n * All rights reserved. \n * \n * Redistribution and use in source and binary forms, with or without \n * modification, are permitted provided that the following conditions 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 \n *    notice, this list of conditions and the following disclaimer in the \n *    documentation and/or other materials provided with the distribution. \n * \n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 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 THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY \n * DIRECT, 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) 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 SUCH \n * DAMAGE. \n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"mathematica++ Unit Test (Module::Integer)\"\n#include <boost/test/unit_test.hpp>\n#include <string>\n#include <cmath>\n#include <complex>\n#include <map>\n#include <vector>\n#include <iostream>\n#include <boost/format.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_io.hpp>\n#include <boost/tuple/tuple_comparison.hpp>\n#include \"boost/tuple/tuple.hpp\"\n#include \"mathematica++/connector.h\"\n#include \"mathematica++/m.h\"\n#include \"mathematica++/io.h\"\n#include \"mathematica++/declares.h\"\n#include \"mathematica++/operators.h\"\n#include \"mathematica++/rules.h\"\n\nusing namespace mathematica;\n\nMATHEMATICA_DECLARE(Table)\nMATHEMATICA_DECLARE(Det)\nMATHEMATICA_DECLARE(Dot)\nMATHEMATICA_DECLARE(Mod)\n\nBOOST_AUTO_TEST_SUITE(integer)\n\nBOOST_AUTO_TEST_CASE(integer_size){\n    connector shell;\n    BOOST_CHECK(shell.connected());\n    {\n        value result;\n        shell << Power(2, 68);\n        shell >> result;\n        \n        std::string res_str = *result;\n        res_str.erase(0, 1);\n        \n        // std::cout << *result << \" \" << res_str << std::endl;\n        \n        BOOST_CHECK(res_str == \"295147905179352825856\");\n    }\n    {\n        value res_intermediate;\n        value res_final;\n        \n        shell << List(Power(2, 61), Power(2, 62), Power(2, 63), Power(2, 64), Power(2, 65));\n        shell >> res_intermediate;\n        shell << Total(res_intermediate);\n        shell >> res_final;\n        \n        std::string res_nstr = *res_final;\n        res_nstr.erase(0, 1);\n        \n        // std::cout << res_intermediate << std::endl;\n        // std::cout << res_final << std::endl;\n        \n        BOOST_CHECK(res_nstr == \"71481133285624512512\");        \n    }\n    {\n        mathematica::symbol i(\"i\");\n        mathematica::symbol j(\"j\");\n        \n        value res_mata;\n        value res_matb;\n        value res_matc;\n        value res_det;\n\n        shell << Table(Mod(i+j, 2), List(i, 1, 2), List(j, 1, 2));\n        shell >> res_mata;\n        shell << Table(Mod(i+j, 3), List(i, 1, 2), List(j, 1, 2));\n        shell >> res_matb;\n        shell << Dot(res_mata, res_matb);\n        shell >> res_matc;\n        shell << Det(res_matc);\n        shell >> res_det;\n        \n        BOOST_CHECK(*res_det == -2);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "5d64ddaa3fe84a5bdc3add24f3a4b70293c15afd", "size": 3721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/integer.cpp", "max_stars_repo_name": "DominikLindorfer/mathematicapp", "max_stars_repo_head_hexsha": "ce9de342501d803ccd115533d19c7e3ace51e475", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-10-04T16:27:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T22:28:51.000Z", "max_issues_repo_path": "tests/integer.cpp", "max_issues_repo_name": "DominikLindorfer/mathematicapp", "max_issues_repo_head_hexsha": "ce9de342501d803ccd115533d19c7e3ace51e475", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/integer.cpp", "max_forks_repo_name": "DominikLindorfer/mathematicapp", "max_forks_repo_head_hexsha": "ce9de342501d803ccd115533d19c7e3ace51e475", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-22T03:33:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-17T07:10:21.000Z", "avg_line_length": 32.9292035398, "max_line_length": 92, "alphanum_fraction": 0.65546896, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5574373973451866}}
{"text": "#include \"../metropolis_hastings.hpp\"\n#include \"../utils.hpp\"\n#include \"gtest/gtest.h\"\n\n#include <boost/log/trivial.hpp>\n#include <boost/math/distributions/beta.hpp>\n#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <string>\n\nnamespace FilterModel {\nTEST(sample, wtv) {\n    boost::math::beta_distribution<double> dist(2, 2);\n    std::default_random_engine generator;\n    generator.seed(std::chrono::system_clock::now().time_since_epoch().count());\n\n    std::vector<double> values;\n\n    double x = MetropolisHastingsSampler::sample<double, std::default_random_engine>(\n        100000,\n        [dist](double x) {\n            double p = pdf(dist, x);\n            double log_p = std::log(p);\n            return log_p;\n        },\n        [](std::default_random_engine gen) {\n            std::uniform_real_distribution<double> uniform(0, 1);\n            double x = uniform(gen);\n            return x;\n        },\n        [](double center, std::default_random_engine gen) {\n            std::normal_distribution<double> conditional(center, 0.25);\n            double x = sample_probability(conditional, gen);\n            return x;\n        },\n        generator, &values);\n\n    std::string out_path =\n        \"/home/skinnersboxy/perkins-input-filter/MulticlassFilterModel/output/values.csv\";\n    std::ofstream output_file(out_path);\n\n    if (output_file.is_open()) {\n        output_file << vector_to_string(values);\n        output_file.close();\n    } else {\n        BOOST_LOG_TRIVIAL(fatal) << \"File \" << out_path << \" cannot be written to.\";\n        assert(false);\n    }\n}\n\n}  // namespace FilterModel", "meta": {"hexsha": "b9db39aebcbde5872211a3f8e7b2b31742ce5e09", "size": 1624, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/tests/metropolis_hastings_tests.cpp", "max_stars_repo_name": "skinnersBoxy/input-filter", "max_stars_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/tests/metropolis_hastings_tests.cpp", "max_issues_repo_name": "skinnersBoxy/input-filter", "max_issues_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/tests/metropolis_hastings_tests.cpp", "max_forks_repo_name": "skinnersBoxy/input-filter", "max_forks_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.641509434, "max_line_length": 90, "alphanum_fraction": 0.6262315271, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5574347522440504}}
{"text": "#include \"../src/params.h\"\n#include \"../src/sigmaplus_prover.h\"\n#include \"../src/sigmaplus_verifier.h\"\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\n\n\nBOOST_AUTO_TEST_SUITE(sigma_protocol_tests)\n\nBOOST_AUTO_TEST_CASE(one_out_of_n)\n{\n    auto params = sigma::Params::get_default();\n    int N = 16384;\n    int n = params->get_n();\n    int m = params->get_m();\n    int index = 102;\n\n    secp_primitives::GroupElement g;\n    g.randomize();\n    std::vector<secp_primitives::GroupElement> h_gens;\n    h_gens.resize(n * m);\n    for(int i = 0; i < n * m; ++i ){\n        h_gens[i].randomize();\n    }\n    secp_primitives::Scalar r;\n    r.randomize();\n    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);\n\n    std::vector<secp_primitives::GroupElement> commits;\n    for(int i = 0; i < N; ++i){\n        if(i == index){\n            secp_primitives::GroupElement c;\n            secp_primitives::Scalar zero(unsigned(0));\n            c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, zero, h_gens[0], r);\n            commits.push_back(c);\n\n        }\n        else{\n            commits.push_back(secp_primitives::GroupElement());\n            commits[i].randomize();\n        }\n    }\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n,m);\n\n    prover.proof(commits, index, r, true, proof);\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n\n    BOOST_CHECK(verifier.verify(commits, proof, true));\n}\n\nBOOST_AUTO_TEST_CASE(one_out_of_n_one)\n{\n    auto params = sigma::Params::get_default();\n    int N = 16384;\n    int n = params->get_n();\n    int m = params->get_m();\n    int index = 1023;\n\n    secp_primitives::GroupElement g;\n    g.randomize();\n    std::vector<secp_primitives::GroupElement> h_gens;\n    h_gens.resize(n * m);\n    for(int i = 0; i < n * m; ++i ){\n        h_gens[i].randomize();\n    }\n    secp_primitives::Scalar r;\n    r.randomize();\n    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);\n\n    std::vector<secp_primitives::GroupElement> commits;\n    for(int i = 0; i < N; ++i){\n        if(i == index){\n            secp_primitives::GroupElement c;\n            secp_primitives::Scalar one(unsigned(1));\n            c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, one, h_gens[0], r);\n            commits.push_back(c);\n\n        }\n        else{\n            commits.push_back(secp_primitives::GroupElement());\n            commits[i].randomize();\n        }\n    }\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n,m);\n\n    prover.proof(commits, index, r, true, proof, unsigned(1));\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n\n    BOOST_CHECK(verifier.verify(commits, proof, true, unsigned(1)));\n}\n\nBOOST_AUTO_TEST_CASE(one_out_of_n_padding)\n{\n    auto params = sigma::Params::get_default();\n    int N = 10000;\n    int n = params->get_n();\n    int m = params->get_m();\n    int index = 9999;\n\n    secp_primitives::GroupElement g;\n    g.randomize();\n    std::vector<secp_primitives::GroupElement> h_gens;\n    h_gens.resize(n * m);\n    for(int i = 0; i < n * m; ++i ){\n        h_gens[i].randomize();\n    }\n    secp_primitives::Scalar r;\n    r.randomize();\n    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);\n\n    std::vector<secp_primitives::GroupElement> commits;\n    for(int i = 0; i < N; ++i){\n        if(i == index){\n            secp_primitives::GroupElement c;\n            secp_primitives::Scalar zero(unsigned(0));\n            c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, zero, h_gens[0], r);\n            commits.push_back(c);\n\n        }\n        else{\n            commits.push_back(secp_primitives::GroupElement());\n            commits[i].randomize();\n        }\n    }\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n, m);\n\n    prover.proof(commits, index, r, true, proof);\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n\n    BOOST_CHECK(verifier.verify(commits, proof, true));\n\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proofNew(n, m);\n    prover.proof(commits, 11111, r, true, proofNew);\n    BOOST_CHECK(verifier.verify(commits, proofNew, true));\n}\n\nBOOST_AUTO_TEST_CASE(prove_and_verify_in_different_set)\n{\n    auto params = sigma::Params::get_default();\n    int N = 16384;\n    int n = params->get_n();\n    int m = params->get_m();\n    int index = 0;\n\n    secp_primitives::GroupElement g;\n    g.randomize();\n    std::vector<secp_primitives::GroupElement> h_gens;\n    h_gens.resize(n * m);\n    for(int i = 0; i < n * m; ++i ){\n        h_gens[i].randomize();\n    }\n    secp_primitives::Scalar r;\n    r.randomize();\n    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);\n\n    std::vector<secp_primitives::GroupElement> commits;\n    for(int i = 0; i < N; ++i){\n        if(i == index){\n            secp_primitives::GroupElement c;\n            secp_primitives::Scalar zero(unsigned(0));\n            c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, zero, h_gens[0], r);\n            commits.push_back(c);\n\n        }\n        else{\n            commits.push_back(secp_primitives::GroupElement());\n            commits[i].randomize();\n        }\n    }\n\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n,m);\n\n    prover.proof(commits, index, r, true, proof);\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n\n    // Add more commit\n    secp_primitives::GroupElement c;\n    secp_primitives::Scalar zero(unsigned(0));\n    c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, zero, h_gens[0], r);\n    commits.push_back(c);\n\n    BOOST_CHECK(!verifier.verify(commits, proof, true));\n}\n\nBOOST_AUTO_TEST_CASE(prove_coin_out_of_index)\n{\n    auto params = sigma::Params::get_default();\n    int N = 16384;\n    int n = params->get_n();\n    int m = params->get_m();\n\n    secp_primitives::GroupElement g;\n    g.randomize();\n    std::vector<secp_primitives::GroupElement> h_gens;\n    h_gens.resize(n * m);\n    for(int i = 0; i < n * m; ++i ){\n        h_gens[i].randomize();\n    }\n    secp_primitives::Scalar r;\n    r.randomize();\n    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);\n\n    std::vector<secp_primitives::GroupElement> commits;\n    for(int i = 0; i < N; ++i){\n        commits.push_back(secp_primitives::GroupElement());\n        commits[i].randomize();\n    }\n\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n,m);\n\n    prover.proof(commits, commits.size(), r, true, proof);\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n    BOOST_CHECK(!verifier.verify(commits,proof, true));\n}\n\nBOOST_AUTO_TEST_CASE(prove_coin_not_in_set)\n{\n    auto params = sigma::Params::get_default();\n    int N = 16384;\n    int n = params->get_n();\n    int m = params->get_m();\n    int index = 0;\n    secp_primitives::GroupElement g;\n    g.randomize();\n    std::vector<secp_primitives::GroupElement> h_gens;\n    h_gens.resize(n * m);\n    for(int i = 0; i < n * m; ++i ){\n        h_gens[i].randomize();\n    }\n    secp_primitives::Scalar r;\n    r.randomize();\n    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);\n\n    std::vector<secp_primitives::GroupElement> commits;\n    for(int i = 0; i < N; ++i){\n        commits.push_back(secp_primitives::GroupElement());\n        commits[i].randomize();\n    }\n\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n,m);\n\n    prover.proof(commits, index, r, true, proof);\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n    BOOST_CHECK(!verifier.verify(commits,proof, true));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "25d61c3b907e85fa91d31164e0b0791014a1e04c", "size": 8427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/protocol_tests.cpp", "max_stars_repo_name": "3for/libsigma", "max_stars_repo_head_hexsha": "791f2a596eb445e2d269ca3609c4b32a646fc45f", "max_stars_repo_licenses": ["MIT"], "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/protocol_tests.cpp", "max_issues_repo_name": "3for/libsigma", "max_issues_repo_head_hexsha": "791f2a596eb445e2d269ca3609c4b32a646fc45f", "max_issues_repo_licenses": ["MIT"], "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/protocol_tests.cpp", "max_forks_repo_name": "3for/libsigma", "max_forks_repo_head_hexsha": "791f2a596eb445e2d269ca3609c4b32a646fc45f", "max_forks_repo_licenses": ["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.7898832685, "max_line_length": 125, "alphanum_fraction": 0.6559867094, "num_tokens": 2390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.5574347496779586}}
{"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// \u30db\u30e9\u30a4\u30be\u30f3\u9577\u3055\nint T = 5;\n// \u5468\u671f\ndouble DT = 0.1;// [s]\nconst double HZ = 10;\n// \u76ee\u6a19\u901f\u5ea6\ndouble VREF = 0.5;// [m/s]\n// \u6700\u5927\u89d2\u901f\u5ea6\ndouble MAX_ANGULAR_VELOCITY = 1.0;// [rad/s]\n// \u30db\u30a4\u30fc\u30eb\u89d2\u52a0\u901f\u5ea6\ndouble MAX_WHEEL_ANGULAR_ACCELERATION = 60;// [rad/s^2]\n// \u30db\u30a4\u30fc\u30eb\u89d2\u901f\u5ea6\ndouble MAX_WHEEL_ANGULAR_VELOCITY = 30;// [rad/s]\n// \u30db\u30a4\u30fc\u30eb\u534a\u5f84\ndouble WHEEL_RADIUS = 0.1;// [m]\n// \u30c8\u30ec\u30c3\u30c9\ndouble TREAD = 0.4;// [m]\n// \u30db\u30a4\u30fc\u30eb\u30d9\u30fc\u30b9\ndouble WHEEL_BASE = 0.4;// [m]\n// \u30b0\u30ea\u30c3\u30c9\u30de\u30c3\u30d7\u5206\u89e3\u80fd\ndouble RESOLUTION = 0.1;// [m]\n// \u30ed\u30dc\u30c3\u30c8\u306e\u8db3\u307e\u308f\u308a\u534a\u5f84\ndouble ROBOT_RADIUS;\n// \u8db3\u56de\u308a\u914d\u7f6e\ndouble ROBOT_THETA;\n// \u30b9\u30c6\u30a2\u89d2\u5ea6\u5236\u9650\ndouble MAX_STEERING_ANGLE = M_PI * 2. / 3.;// [rad]\n// \u6700\u9ad8\u901f\u5ea6\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// \u6700\u9069\u5316\u5931\u6557\u6642\u306f\u6700\u5f8c\u306e\u6210\u529f\u30c7\u30fc\u30bf\u3092\u4f7f\u3046\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    // \u9069\u5f53\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  // \u7b49\u5f0f\u5236\u7d04\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\u306e\u8a2d\u5b9a\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    // \u4f55\u6545\u304b0\u3060\u3068\u3046\u307e\u304f\u884c\u304b\u306a\u3044\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    //\u4e88\u6e2c\u8ecc\u9053\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    // \u3044\u3044\u306e\u304b\u4e0d\u660e\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      //\u4e88\u6e2c\u8ecc\u9053\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\u3068\u306e\u8ddd\u96e2\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    // \u5411\u304d\n    fg[0] += 10 * CppAD::pow(vars[yaw_start + i] - ref_yaw[i], 2);\n    // \u901f\u5ea6\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    // \u89d2\u52a0\u901f\u5ea6\n    fg[0] += 1 * CppAD::pow(vars[omega_start + i] - vars[omega_start + i + 1], 2);\n    // \u89d2\u901f\u5ea6\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  //\u521d\u671f\u72b6\u614b\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    //\u5165\u529b\u30db\u30e9\u30a4\u30be\u30f3\u306ft+1\u3092\u8003\u616e\u3057\u306a\u3044\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    //\u5236\u7d04\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\u8868\u793a\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\u8868\u793a\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": "#ifndef STAN_MATH_PRIM_SCAL_FUN_ERF_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_ERF_HPP\n\n#include <stan/math/prim/scal/fun/boost_policy.hpp>\n#include <stan/math/prim/scal/fun/is_nan.hpp>\n#include <boost/math/special_functions/erf.hpp>\n#include <limits>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Return the error function of the specified value.\n     *\n     * \\f[\n     * \\mbox{erf}(x) = \\frac{2}{\\sqrt{\\pi}} \\int_0^x e^{-t^2} dt\n     * \\f]\n     *\n     * @param[in] x Argument.\n     * @return Error function of the argument.\n     */\n    inline double erf(double x) {\n      if (is_nan(x))\n        return std::numeric_limits<double>::quiet_NaN();\n      return boost::math::erf(x, boost_policy_t());\n    }\n\n    /**\n     * Return the error function of the specified argument.  This\n     * version is required to disambiguate <code>erf(int)</code>.\n     *\n     * @param[in] x Argument.\n     * @return Error function of the argument.\n     */\n    inline double erf(int x) {\n      return erf(static_cast<double>(x));\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "7a64b975a891a5fb977400b0988d0a544e5e793a", "size": 1030, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/fun/erf.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/erf.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/erf.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.5238095238, "max_line_length": 65, "alphanum_fraction": 0.6242718447, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5573943833608829}}
{"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": "#include \"system/CameraModel.h\"\n#include \"system/DsoSystem.h\"\n#include \"util/geometry.h\"\n#include \"util/types.h\"\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n#include <tuple>\n\nusing namespace fishdso;\n\nTEST(GeometryTest, IntersectOnSphereTest) {\n  std::vector<std::tuple<double, Vec3, Vec3>> tests{\n      {M_PI_2, Vec3(0, 0, 1), Vec3(1, 0, -1).normalized()},\n      {M_PI_2, Vec3(1, 0, -1).normalized(), Vec3(0, 0, 1)},\n      {M_PI_2, Vec3(1, 1, 0).normalized(), Vec3(1, -1, 0).normalized()},\n      {M_PI_2, Vec3(1, 0, 1).normalized(), Vec3(-1, -1, -1).normalized()},\n      {M_PI / 3, Vec3(0, 1, 0), Vec3(0, 0, 1)}};\n\n  std::vector<std::pair<Vec3, Vec3>> answers{\n      {Vec3(0, 0, 1), Vec3(1, 0, 0)},\n      {Vec3(1, 0, 0), Vec3(0, 0, 1)},\n      {Vec3(1, 1, 0).normalized(), Vec3(1, -1, 0).normalized()},\n      {Vec3(1, 0, 1).normalized(), Vec3(0, -1, 0)},\n      {Vec3(0, std::sqrt(3) / 2, 0.5), Vec3(0, 0, 1)}};\n\n  std::vector<std::tuple<double, Vec3, Vec3>> testsFalse{\n      {M_PI_2, Vec3(0, 0, -1), Vec3(-1, 0, -1).normalized()},\n      {M_PI_2, Vec3(-1, 0, -1).normalized(), Vec3(0, -1, -1).normalized()},\n      {M_PI * 0.75, Vec3(-1, 0, -100).normalized(),\n       Vec3(0, -1, -100).normalized()}};\n\n  const double eps = 1e-9;\n  for (int i = 0; i < tests.size(); ++i) {\n    ASSERT_TRUE(intersectOnSphere(std::get<0>(tests[i]), std::get<1>(tests[i]),\n                                  std::get<2>(tests[i])))\n        << \"test #\" << i << \" failed: returned false\" << std::endl;\n    double err =\n        std::sqrt((std::get<1>(tests[i]) - answers[i].first).squaredNorm() +\n                  (std::get<2>(tests[i]) - answers[i].second).squaredNorm());\n    ASSERT_LT(err, eps) << \"test #\" << i << \" failed: error = \" << err\n                        << std::endl;\n  }\n\n  for (int i = 0; i < testsFalse.size(); ++i)\n    ASSERT_FALSE(intersectOnSphere(std::get<0>(testsFalse[i]),\n                                   std::get<1>(testsFalse[i]),\n                                   std::get<2>(testsFalse[i])))\n        << \"false-test #\" << i << \" failed: returned true\" << std::endl;\n}\n\nTEST(GeometryTest, TriangulateTest) {\n  const int testCount = 1000;\n  const double border = 1e2;\n  const double eps = 1e-8;\n\n  std::mt19937 mt;\n  std::uniform_real_distribution<double> coord(-border, border);\n  for (int it = 0; it < testCount; ++it) {\n    Vec3 a(coord(mt), coord(mt), coord(mt));\n    Vec3 b(coord(mt), coord(mt), coord(mt));\n    Vec3 c(coord(mt), coord(mt), coord(mt));\n    SO3 rot = SO3::sampleUniform(mt);\n\n    double depth1 = (c - a).norm();\n    double depth2 = (c - b).norm();\n\n    Vec3 t = -(rot * (b - a));\n    SE3 aToB(rot, t);\n\n    Vec3 cDirInACoord = (c - a).normalized();\n    Vec3 cDirInBCoord = (aToB * (c - a)).normalized();\n\n    Vec2 result = triangulate(aToB, cDirInACoord, cDirInBCoord);\n    Vec2 expected(depth1, depth2);\n    double err = (result - expected).norm();\n    ASSERT_LT(err, eps) << \"test failed:\\n\"\n                        << \"a = \" << a.transpose() << \"\\n\"\n                        << \"b = \" << b.transpose() << \"\\n\"\n                        << \"c = \" << c.transpose() << \"\\n\"\n                        << \"rot = \"\n                        << rot.unit_quaternion().coeffs().transpose() << \"\\n\"\n                        << \"err = \" << err << \"\\n\"\n                        << \"expected = \" << expected.transpose() << \"\\n\"\n                        << \"result   = \" << result.transpose() << std::endl;\n  }\n}\n\nTEST(GeometryTest, IsSameSideTest) {\n  StdVector<std::array<Vec2, 4>> testsTrue{\n      {Vec2(0, 0), Vec2(1, 0), Vec2(1, 1), Vec2(0, 1)},\n      {Vec2(0, 0), Vec2(1, 1), Vec2(2, 2), Vec2(0, 1)},\n      {Vec2(0, 0), Vec2(1, 1), Vec2(2, 2), Vec2(0, -1)},\n      {Vec2(1, 1), Vec2(2, 1), Vec2(2, 1), Vec2(3, 1)}};\n  StdVector<std::array<Vec2, 4>> testsFalse{\n      {Vec2(0, 0), Vec2(1, 0), Vec2(1, 1), Vec2(1, -1)},\n      {Vec2(1, 1), Vec2(1, -1), Vec2(-1, -1), Vec2(2, 2)},\n      {Vec2(0, 0), Vec2(1, 0), Vec2(1e6, 1), Vec2(1e8, -1)},\n      {Vec2(-1, -2), Vec2(0, 2), Vec2(-1, -1), Vec2(0, 0)}};\n\n  for (int i = 0; i < testsTrue.size(); ++i)\n    ASSERT_TRUE(isSameSide(testsTrue[i][0], testsTrue[i][1], testsTrue[i][2],\n                           testsTrue[i][3]))\n        << \"test #\" << i << \" failed: returned false\" << std::endl;\n  for (int i = 0; i < testsFalse.size(); ++i)\n    ASSERT_FALSE(isSameSide(testsFalse[i][0], testsFalse[i][1],\n                            testsFalse[i][2], testsFalse[i][3]))\n        << \"test #\" << i << \" failed: returned true\" << std::endl;\n}\n\nTEST(GeometryTest, InInsideTriangleTest) {\n  StdVector<std::array<Vec2, 4>> testsTrue{\n      {Vec2(0, 0), Vec2(3, 0), Vec2(0, 3), Vec2(1, 1)},\n      {Vec2(0, 0), Vec2(1e4, 1), Vec2(2, 2), Vec2(1e4 - 1, 1)},\n      {Vec2(0, 0), Vec2(2, 1), Vec2(0, 2), Vec2(0, 1)},\n      {Vec2(0, 0), Vec2(2, 0), Vec2(2, 2), Vec2(2, 2)},\n      {Vec2(0, 0), Vec2(1, 0), Vec2(2, 0), Vec2(1, 1)},\n  };\n  StdVector<std::array<Vec2, 4>> testsFalse{\n      {Vec2(0, 0), Vec2(1, 0), Vec2(0, 1), Vec2(2, 0)},\n      {Vec2(-1, -1), Vec2(0, 2), Vec2(2, 0), Vec2(-1, 1)},\n      {Vec2(0, 0), Vec2(1e5, 1), Vec2(0, 1), Vec2(1, 0)}};\n\n  for (int i = 0; i < testsTrue.size(); ++i)\n    ASSERT_TRUE(isInsideTriangle(testsTrue[i][0], testsTrue[i][1],\n                                 testsTrue[i][2], testsTrue[i][3]))\n        << \"test #\" << i << \" failed: returned false\" << std::endl;\n  for (int i = 0; i < testsFalse.size(); ++i)\n    ASSERT_FALSE(isInsideTriangle(testsFalse[i][0], testsFalse[i][1],\n                                  testsFalse[i][2], testsFalse[i][3]))\n        << \"test #\" << i << \" failed: returned true\" << std::endl;\n}\n\nTEST(GeometryTest, IsABCDConvexTest) {\n  StdVector<std::array<Vec2, 4>> testsTrue{\n      {Vec2(0, 0), Vec2(1, 0), Vec2(1, 1), Vec2(0, 1)},\n      {Vec2(-3, 0), Vec2(-2, 2), Vec2(3, 0), Vec2(2, -2)},\n      {Vec2(0, 0), Vec2(0, 1), Vec2(0, 2), Vec2(1, 1)},\n      {Vec2(-1e5, -1), Vec2(0, 0), Vec2(1e4, 1), Vec2(0, 1)}};\n  StdVector<std::array<Vec2, 4>> testsFalse{\n      {Vec2(0, 0), Vec2(1, 1), Vec2(2, 0), Vec2(1, 3)},\n      {Vec2(-1e4, -1), Vec2(0, 0), Vec2(1e5, 1), Vec2(0, 1)},\n      {Vec2(0, 0), Vec2(1, 1), Vec2(1, 0), Vec2(0, 1)}};\n\n  for (int i = 0; i < testsTrue.size(); ++i)\n    ASSERT_TRUE(isABCDConvex(testsTrue[i][0], testsTrue[i][1], testsTrue[i][2],\n                             testsTrue[i][3]))\n        << \"test #\" << i << \" failed: returned false\" << std::endl;\n  for (int i = 0; i < testsFalse.size(); ++i)\n    ASSERT_FALSE(isABCDConvex(testsFalse[i][0], testsFalse[i][1],\n                              testsFalse[i][2], testsFalse[i][3]))\n        << \"test #\" << i << \" failed: returned true\" << std::endl;\n}\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "cf21e2d271dabc4df55c74853bfd5d97180c5969", "size": 6730, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_geometry.cpp", "max_stars_repo_name": "MikhailTerekhov/mdso", "max_stars_repo_head_hexsha": "e032083bc6da6548718a5d222ec4016189ec2dc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-09-11T11:27:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T02:12:07.000Z", "max_issues_repo_path": "test/test_geometry.cpp", "max_issues_repo_name": "MikhailTerekhov/mdso", "max_issues_repo_head_hexsha": "e032083bc6da6548718a5d222ec4016189ec2dc8", "max_issues_repo_licenses": ["MIT"], "max_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_geometry.cpp", "max_forks_repo_name": "MikhailTerekhov/mdso", "max_forks_repo_head_hexsha": "e032083bc6da6548718a5d222ec4016189ec2dc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-11T19:52:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-11T19:52:59.000Z", "avg_line_length": 42.5949367089, "max_line_length": 79, "alphanum_fraction": 0.5072808321, "num_tokens": 2525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514084, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5573943805550686}}
{"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": "#include <boost/simd/memory/is_power_of_2.hpp>\n#include <boost/assert.hpp>\n\nint main()\n{\n  BOOST_ASSERT(  boost::simd::is_power_of_2(   2 ) );\n  BOOST_ASSERT(  boost::simd::is_power_of_2(  16 ) );\n  BOOST_ASSERT( !boost::simd::is_power_of_2(   0 ) );\n  BOOST_ASSERT( !boost::simd::is_power_of_2(1337 ) );\n}\n", "meta": {"hexsha": "dd182d06c47fdd1b193374dd2f663a267e24cd9b", "size": 307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/examples/memory/is_power_of_2.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/sdk/examples/memory/is_power_of_2.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/sdk/examples/memory/is_power_of_2.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 27.9090909091, "max_line_length": 53, "alphanum_fraction": 0.6840390879, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5573611843290691}}
{"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": "#include \"benchmark/benchmark.h\"\n#include <Eigen/Dense>\n\nvoid BM_DGEMM(benchmark::State& state) {\n  // First resume to ensure the timer is running.  Without this benchmark\n  // gives garbage results.\n  // You do not need to do this with the opensource version of benchmark.\n  state.ResumeTiming();\n  state.PauseTiming();\n  const int size = state.range(0);\n  Eigen::MatrixXd a = Eigen::MatrixXd::Random(size, size);\n  Eigen::MatrixXd b = Eigen::MatrixXd::Random(size, size);\n  Eigen::MatrixXd c = Eigen::MatrixXd::Random(size, size);\n  state.ResumeTiming();\n  for (auto _ : state) {\n    a.noalias() += b * c;\n  }\n}\n\nBENCHMARK(BM_DGEMM)\n    ->Arg(3)\n    ->Arg(4)\n    ->Arg(5)\n    ->Arg(6)\n    ->Arg(7)\n    ->Arg(8)\n    ->Arg(9)\n    ->Arg(10)\n    ->Arg(15)\n    ->Arg(16)\n    ->Arg(20)\n    ->Arg(24)\n    ->Arg(28)\n    ->Arg(31)\n    ->Arg(32)\n    ->Arg(40)\n    ->Arg(63)\n    ->Arg(64)\n    ->Arg(80)\n    ->Arg(100)\n    ->Arg(128)\n    ->Arg(150)\n    ->Arg(200)\n    ->Arg(256)\n    ->Arg(300)\n    ->Arg(400)\n    ->Arg(500)\n    ->Arg(600);\n// any larger and it OOMs\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "ab5526abd747bb088b405a1256d9d915bd8a9b1e", "size": 1075, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gemm_benchmark_test.cc", "max_stars_repo_name": "ngzhian/simd-benchmarks", "max_stars_repo_head_hexsha": "20b13950ee9ec2eb237b174b74c41ec0369c41bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-14T07:34:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T13:48:41.000Z", "max_issues_repo_path": "gemm_benchmark_test.cc", "max_issues_repo_name": "ngzhian/simd-benchmarks", "max_issues_repo_head_hexsha": "20b13950ee9ec2eb237b174b74c41ec0369c41bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-08-20T16:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-10T02:49:53.000Z", "max_forks_repo_path": "gemm_benchmark_test.cc", "max_forks_repo_name": "ngzhian/simd-benchmarks", "max_forks_repo_head_hexsha": "20b13950ee9ec2eb237b174b74c41ec0369c41bb", "max_forks_repo_licenses": ["BSD-3-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.6730769231, "max_line_length": 73, "alphanum_fraction": 0.5711627907, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5573611733768403}}
{"text": "#include <stan/math/fwd/mat.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <limits>\n\nusing stan::math::fvar;\n\nTEST(AgradFwdMatrixSquaredDistance, vector_fd_vector_fd) {\n  stan::math::vector_fd v1, v2;\n\n  v1.resize(3);\n  v2.resize(3);\n  v1 << 1, 3, -5;\n  v2 << 4, -2, -1;\n  v1(0).d_ = 1.0;\n  v1(1).d_ = 2.0;\n  v1(2).d_ = 3.0;\n  v2(0).d_ = 4.0;\n  v2(1).d_ = 5.0;\n  v2(2).d_ = 6.0;\n\n  stan::math::fvar<double> a = stan::math::squared_distance(v1, v2);\n\n  EXPECT_FLOAT_EQ(50, a.val_);\n  EXPECT_FLOAT_EQ(12, a.d_);\n\n  v1.resize(0);\n  v2.resize(0);\n  EXPECT_FLOAT_EQ(0, stan::math::squared_distance(v1, v2).val_);\n\n  v1.resize(1);\n  v2.resize(2);\n  v1 << 1;\n  v2 << 2, 3;\n  EXPECT_THROW(stan::math::squared_distance(v1, v2), std::invalid_argument);\n}\n\nTEST(AgradFwdMatrixSquaredDistance, rowvector_fd_vector_fd) {\n  stan::math::row_vector_fd rv;\n  stan::math::vector_fd v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n\n  stan::math::fvar<double> a = stan::math::squared_distance(rv, v);\n\n  EXPECT_FLOAT_EQ(50, a.val_);\n  EXPECT_FLOAT_EQ(12, a.d_);\n\n  rv.resize(0);\n  v.resize(0);\n  EXPECT_FLOAT_EQ(0, stan::math::squared_distance(rv, v).val_);\n\n  rv.resize(1);\n  v.resize(2);\n  rv << 1;\n  v << 2, 3;\n  EXPECT_THROW(stan::math::squared_distance(rv, v), std::invalid_argument);\n}\n\nTEST(AgradFwdMatrixSquaredDistance, vector_fd_rowvector_fd) {\n  stan::math::row_vector_fd rv;\n  stan::math::vector_fd v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n\n  stan::math::fvar<double> a = stan::math::squared_distance(v, rv);\n\n  EXPECT_FLOAT_EQ(50, a.val_);\n  EXPECT_FLOAT_EQ(12, a.d_);\n\n  v.resize(0);\n  rv.resize(0);\n  EXPECT_FLOAT_EQ(0, stan::math::squared_distance(v, rv).val_);\n\n  v.resize(1);\n  rv.resize(2);\n  v << 1;\n  rv << 2, 3;\n  EXPECT_THROW(stan::math::squared_distance(v, rv), std::invalid_argument);\n}\n\nTEST(AgradFwdMatrixSquaredDistance, special_values_fd) {\n  stan::math::vector_fd v1, v2;\n  v1.resize(1);\n  v2.resize(1);\n\n  v1 << 0;\n  v2 << std::numeric_limits<double>::quiet_NaN();\n  EXPECT_TRUE(boost::math::isnan(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(boost::math::isnan(stan::math::squared_distance(v2, v1)));\n\n  v1 << 0;\n  v2 << std::numeric_limits<double>::infinity();\n  EXPECT_TRUE(boost::math::isinf(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(boost::math::isinf(stan::math::squared_distance(v2, v1)));\n\n  v1 << std::numeric_limits<double>::infinity();\n  v2 << std::numeric_limits<double>::infinity();\n  EXPECT_TRUE(boost::math::isnan(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(boost::math::isnan(stan::math::squared_distance(v2, v1)));\n\n  v1 << -std::numeric_limits<double>::infinity();\n  v2 << std::numeric_limits<double>::infinity();\n  EXPECT_TRUE(boost::math::isinf(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(boost::math::isinf(stan::math::squared_distance(v2, v1)));\n}\n\nTEST(AgradFwdMatrixSquaredDistance, vector_ffd_vector_ffd) {\n  stan::math::vector_ffd v1, v2;\n\n  v1.resize(3);\n  v2.resize(3);\n  v1 << 1, 3, -5;\n  v2 << 4, -2, -1;\n  v1(0).d_ = 1.0;\n  v1(1).d_ = 2.0;\n  v1(2).d_ = 3.0;\n  v2(0).d_ = 4.0;\n  v2(1).d_ = 5.0;\n  v2(2).d_ = 6.0;\n\n  stan::math::fvar<fvar<double> > a = stan::math::squared_distance(v1, v2);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_);\n  EXPECT_FLOAT_EQ(12, a.d_.val_);\n\n  v1.resize(0);\n  v2.resize(0);\n  EXPECT_FLOAT_EQ(0, stan::math::squared_distance(v1, v2).val_.val_);\n\n  v1.resize(1);\n  v2.resize(2);\n  v1 << 1;\n  v2 << 2, 3;\n  EXPECT_THROW(stan::math::squared_distance(v1, v2), std::invalid_argument);\n}\n\nTEST(AgradFwdMatrixSquaredDistance, rowvector_ffd_vector_ffd) {\n  stan::math::row_vector_ffd rv;\n  stan::math::vector_ffd v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n\n  stan::math::fvar<fvar<double> > a = stan::math::squared_distance(rv, v);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_);\n  EXPECT_FLOAT_EQ(12, a.d_.val_);\n\n  rv.resize(0);\n  v.resize(0);\n  EXPECT_FLOAT_EQ(0, stan::math::squared_distance(rv, v).val_.val_);\n\n  rv.resize(1);\n  v.resize(2);\n  rv << 1;\n  v << 2, 3;\n  EXPECT_THROW(stan::math::squared_distance(rv, v), std::invalid_argument);\n}\n\nTEST(AgradFwdMatrixSquaredDistance, vector_ffd_rowvector_ffd) {\n  stan::math::row_vector_ffd rv;\n  stan::math::vector_ffd v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n\n  stan::math::fvar<fvar<double> > a = stan::math::squared_distance(v, rv);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_);\n  EXPECT_FLOAT_EQ(12, a.d_.val_);\n\n  v.resize(0);\n  rv.resize(0);\n  EXPECT_FLOAT_EQ(0, stan::math::squared_distance(v, rv).val_.val_);\n\n  v.resize(1);\n  rv.resize(2);\n  v << 1;\n  rv << 2, 3;\n  EXPECT_THROW(stan::math::squared_distance(v, rv), std::invalid_argument);\n}\n\nTEST(AgradFwdMatrixSquaredDistance, special_values_ffd) {\n  stan::math::vector_ffd v1, v2;\n  v1.resize(1);\n  v2.resize(1);\n\n  v1 << 0;\n  v2 << std::numeric_limits<double>::quiet_NaN();\n  EXPECT_TRUE(boost::math::isnan(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(boost::math::isnan(stan::math::squared_distance(v2, v1)));\n\n  v1 << 0;\n  v2 << std::numeric_limits<double>::infinity();\n  EXPECT_TRUE(boost::math::isinf(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(boost::math::isinf(stan::math::squared_distance(v2, v1)));\n\n  v1 << std::numeric_limits<double>::infinity();\n  v2 << std::numeric_limits<double>::infinity();\n  EXPECT_TRUE(boost::math::isnan(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(boost::math::isnan(stan::math::squared_distance(v2, v1)));\n\n  v1 << -std::numeric_limits<double>::infinity();\n  v2 << std::numeric_limits<double>::infinity();\n  EXPECT_TRUE(boost::math::isinf(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(boost::math::isinf(stan::math::squared_distance(v2, v1)));\n}\n", "meta": {"hexsha": "d45cb60763b737f620c5d47b23b8ab66e3839091", "size": 6187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/fwd/mat/fun/squared_distance_test.cpp", "max_stars_repo_name": "sakrejda/math", "max_stars_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/math/fwd/mat/fun/squared_distance_test.cpp", "max_issues_repo_name": "sakrejda/math", "max_issues_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/fwd/mat/fun/squared_distance_test.cpp", "max_forks_repo_name": "sakrejda/math", "max_forks_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4609053498, "max_line_length": 76, "alphanum_fraction": 0.6392435752, "num_tokens": 2357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5573218488793427}}
{"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": "#ifndef _ISAC_\n#define _ISAC_\n\n#include <iostream>\n#include <vector> \n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nclass iSAC{\n    public:\n    iSAC(int x_dim, int u_dim);\n\n    void Initialize(MatrixXd w1,MatrixXd w2,MatrixXd w3);\n    void set_u_limit(double max[], double min[]);\n    \n    void Optimize(double t, VectorXd x, VectorXd x_ref);\n    VectorXd Control(double t);\n\n    VectorXd (*state_eq)(double t, VectorXd x, VectorXd u); //f\n    MatrixXd (*control_func)(double t, VectorXd x); //h\n    MatrixXd (*dstate_eq)(double t, VectorXd x, VectorXd u); //df\n\n    VectorXd get_u_A(void);\n    double get_tau_A(void);\n    double get_duration(void);\n\n    private:\n    int x_dimention;\n    int u_dimention;\n\n    /*parameter*/\n    const double T_S = 0.02; //sampling parameter\n    const int T_HOR = 100; //time horizon\n    const double INF = 100000000.0;\n    const double EPS = 1.0e-3;\n\n    double inc_cost(double t, VectorXd x, VectorXd x_ref);//incremental cost\n    VectorXd dinc_cost(double t, VectorXd x, VectorXd x_ref);//differential incremental cost\n    double end_cost(double t, VectorXd x, VectorXd x_ref); //end cost\n    VectorXd dend_cost(double t, VectorXd x, VectorXd x_ref);//differential end cost\n\n    double calc_J(double t, VectorXd x, VectorXd u, VectorXd x_ref);\n    double calc_J_controlled(double t, MatrixXd x, MatrixXd u, VectorXd x_ref);\n\n    VectorXd u_def(double t);\n    \n    /*iSAC parameter*/\n    MatrixXd u_nom = VectorXd::Zero(2);//nominal control (often u_nom = 0)\n    MatrixXd Q = MatrixXd::Identity(4,4);\n    MatrixXd P = MatrixXd::Identity(4,4);\n    MatrixXd R = MatrixXd::Identity(2,2);\n    double alpha_d = -5;\n    double default_duration = T_S/100;\n\n    /*limit*/\n    double* u_max;\n    double* u_min;\n\n    /*variable*/\n    VectorXd u_A;\n    double tau_A;\n    double duration;\n\n    std::vector<VectorXd> u_s;\n    std::vector<double> tau_s;\n    std::vector<double> duration_s;\n};\n\n#endif //_iSAC_", "meta": {"hexsha": "839b65342c7e830f7f181cc44f258efe27d11b22", "size": 1932, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/isac.hpp", "max_stars_repo_name": "Taiki-Ishigaki/iSAC", "max_stars_repo_head_hexsha": "db66badf4713693d8fc0f88c28d12b8e006ced9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/isac.hpp", "max_issues_repo_name": "Taiki-Ishigaki/iSAC", "max_issues_repo_head_hexsha": "db66badf4713693d8fc0f88c28d12b8e006ced9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/isac.hpp", "max_forks_repo_name": "Taiki-Ishigaki/iSAC", "max_forks_repo_head_hexsha": "db66badf4713693d8fc0f88c28d12b8e006ced9c", "max_forks_repo_licenses": ["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.6, "max_line_length": 92, "alphanum_fraction": 0.6749482402, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938799869521, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5573218372743148}}
{"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 * Copyright Nick Thompson, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <vector>\n#include <array>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/interpolators/quintic_hermite.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/circular_buffer.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\n\nusing boost::math::interpolators::quintic_hermite;\nusing boost::math::interpolators::cardinal_quintic_hermite;\nusing boost::math::interpolators::cardinal_quintic_hermite_aos;\n\ntemplate<typename Real>\nvoid test_constant()\n{\n    std::vector<Real> x{0,1,2,3, 9, 22, 81};\n    std::vector<Real> y(x.size());\n    std::vector<Real> dydx(x.size(), 0);\n    std::vector<Real> d2ydx2(x.size(), 0);\n    for (auto & t : y)\n    {\n        t = 7;\n    }\n\n    auto qh = quintic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2));\n    for (Real t = 0; t <= 81; t += 0.25)\n    {\n        CHECK_ULP_CLOSE(Real(7), qh(t), 24);\n        CHECK_ULP_CLOSE(Real(0), qh.prime(t), 24);\n        CHECK_ULP_CLOSE(Real(0), qh.double_prime(t), 24);\n    }\n}\n\n\ntemplate<typename Real>\nvoid test_linear()\n{\n    std::vector<Real> x{0,1,2,3, 4,5,6,7,8,9};\n    std::vector<Real> y = x;\n    std::vector<Real> dydx(x.size(), 1);\n    std::vector<Real> d2ydx2(x.size(), 0);\n\n    auto qh = quintic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2));\n\n    for (Real t = 0; t <= 9; t += 0.25)\n    {\n        CHECK_ULP_CLOSE(Real(t), qh(t), 2);\n        CHECK_ULP_CLOSE(Real(1), qh.prime(t), 2);\n        CHECK_ULP_CLOSE(Real(0), qh.double_prime(t), 2);\n    }\n\n    boost::random::mt19937 rng;\n    boost::random::uniform_real_distribution<Real> dis(0.5,1);\n    x.resize(512);\n    x[0] = dis(rng);\n    Real xmin = x[0];\n    for (size_t i = 1; i < x.size(); ++i)\n    {\n        x[i] = x[i-1] + dis(rng);\n    }\n    Real xmax = x.back();\n\n    y = x;\n    dydx.resize(x.size(), 1);\n    d2ydx2.resize(x.size(), 0);\n\n    qh = quintic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2));\n\n    for (Real t = xmin; t <= xmax; t += 0.125)\n    {\n        CHECK_ULP_CLOSE(t, qh(t), 2);\n        CHECK_ULP_CLOSE(Real(1), qh.prime(t), 100);\n        CHECK_MOLLIFIED_CLOSE(Real(0), qh.double_prime(t), 200*std::numeric_limits<Real>::epsilon());\n    }\n}\n\ntemplate<typename Real>\nvoid test_quadratic()\n{\n\n    std::vector<Real> x{0,1,2,3, 4,5,6,7,8,9};\n    std::vector<Real> y(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = x[i]*x[i]/2;\n    }\n\n    std::vector<Real> dydx(x.size());\n    for (size_t i = 0; i < y.size(); ++i) {\n        dydx[i] = x[i];\n    }\n\n    std::vector<Real> d2ydx2(x.size(), 1);\n\n    auto qh = quintic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2));\n\n    for (Real t = 0; t <= 9; t += 0.0078125)\n    {\n        CHECK_ULP_CLOSE(Real(t*t)/2, qh(t), 2);\n        CHECK_ULP_CLOSE(t, qh.prime(t), 12);\n        CHECK_ULP_CLOSE(Real(1), qh.double_prime(t), 32);\n    }\n\n    boost::random::mt19937 rng;\n    boost::random::uniform_real_distribution<Real> dis(0.5,1);\n    x.resize(8);\n    x[0] = dis(rng);\n    Real xmin = x[0];\n    for (size_t i = 1; i < x.size(); ++i)\n    {\n        x[i] = x[i-1] + dis(rng);\n    }\n    Real xmax = x.back();\n\n    y.resize(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = x[i]*x[i]/2;\n    }\n\n    dydx.resize(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        dydx[i] = x[i];\n    }\n\n    d2ydx2.resize(x.size(), 1);\n\n    qh = quintic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2));\n\n    for (Real t = xmin; t <= xmax; t += 0.125)\n    {\n        CHECK_ULP_CLOSE(Real(t*t)/2, qh(t), 4);\n        CHECK_ULP_CLOSE(t, qh.prime(t), 53);\n        CHECK_ULP_CLOSE(Real(1), qh.double_prime(t), 700);\n    }\n}\n\ntemplate<typename Real>\nvoid test_cubic()\n{\n\n    std::vector<Real> x{0,1,2,3, 4,5,6,7,8,9};\n    std::vector<Real> y(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = x[i]*x[i]*x[i];\n    }\n\n    std::vector<Real> dydx(x.size());\n    for (size_t i = 0; i < y.size(); ++i) {\n        dydx[i] = 3*x[i]*x[i];\n    }\n\n    std::vector<Real> d2ydx2(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        d2ydx2[i] = 6*x[i];\n    }\n\n    auto qh = quintic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2));\n\n    for (Real t = 0; t <= 9; t += 0.0078125)\n    {\n        CHECK_ULP_CLOSE(t*t*t, qh(t), 10);\n        CHECK_ULP_CLOSE(3*t*t, qh.prime(t), 15);\n        CHECK_ULP_CLOSE(6*t, qh.double_prime(t), 20);\n    }\n}\n\ntemplate<typename Real>\nvoid test_quartic()\n{\n\n    std::vector<Real> x{0,1,2,3, 4,5,6,7,8,9, 10, 11};\n    std::vector<Real> y(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = x[i]*x[i]*x[i]*x[i];\n    }\n\n    std::vector<Real> dydx(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        dydx[i] = 4*x[i]*x[i]*x[i];\n    }\n\n    std::vector<Real> d2ydx2(x.size());\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        d2ydx2[i] = 12*x[i]*x[i];\n    }\n\n    auto qh = quintic_hermite(std::move(x), std::move(y), std::move(dydx), std::move(d2ydx2));\n\n    for (Real t = 1; t <= 11; t += 0.0078125)\n    {\n        CHECK_ULP_CLOSE(t*t*t*t, qh(t), 100);\n        CHECK_ULP_CLOSE(4*t*t*t, qh.prime(t), 100);\n        CHECK_ULP_CLOSE(12*t*t, qh.double_prime(t), 100);\n    }\n}\n\n\ntemplate<typename Real>\nvoid test_interpolation_condition()\n{\n    for (size_t n = 4; n < 50; ++n) {\n        std::vector<Real> x(n);\n        std::vector<Real> y(n);\n        std::vector<Real> dydx(n);\n        std::vector<Real> d2ydx2(n);\n        boost::random::mt19937 rd; \n        boost::random::uniform_real_distribution<Real> dis(0,1);\n        Real x0 = dis(rd);\n        x[0] = x0;\n        y[0] = dis(rd);\n        for (size_t i = 1; i < n; ++i) {\n            x[i] = x[i-1] + dis(rd);\n            y[i] = dis(rd);\n            dydx[i] = dis(rd);\n            d2ydx2[i] = dis(rd);\n        }\n\n        auto x_copy = x;\n        auto y_copy = y;\n        auto dydx_copy = dydx;\n        auto d2ydx2_copy = d2ydx2;\n        auto s = quintic_hermite(std::move(x_copy), std::move(y_copy), std::move(dydx_copy), std::move(d2ydx2_copy));\n        //std::cout << \"s = \" << s << \"\\n\";\n        for (size_t i = 0; i < x.size(); ++i) {\n            CHECK_ULP_CLOSE(y[i], s(x[i]), 2);\n            CHECK_ULP_CLOSE(dydx[i], s.prime(x[i]), 2);\n            CHECK_ULP_CLOSE(d2ydx2[i], s.double_prime(x[i]), 2);\n        }\n    }\n}\n\ntemplate<typename Real>\nvoid test_cardinal_constant()\n{\n\n    std::vector<Real> y(25);\n    std::vector<Real> dydx(y.size(), 0);\n    std::vector<Real> d2ydx2(y.size(), 0);\n    for (auto & t : y) {\n        t = 7;\n    }\n    Real x0 = 4;\n    Real dx = Real(1)/Real(8);\n\n    auto qh = cardinal_quintic_hermite(std::move(y), std::move(dydx), std::move(d2ydx2), x0, dx);\n\n    for (Real t = x0; t <= x0 + 24*dx; t += 0.25)\n    {\n        CHECK_ULP_CLOSE(Real(7), qh(t), 24);\n        CHECK_ULP_CLOSE(Real(0), qh.prime(t), 24);\n        CHECK_ULP_CLOSE(Real(0), qh.double_prime(t), 24);\n    }\n\n    std::vector<std::array<Real, 3>> data(25);\n    for (size_t i = 0; i < data.size(); ++i)\n    {\n        data[i][0] = 7;\n        data[i][1] = 0;\n        data[i][2] = 0;\n    }\n\n    auto qh_aos = cardinal_quintic_hermite_aos(std::move(data), x0, dx);\n    for (Real t = x0; t <= x0 + 24*dx; t += 0.25)\n    {\n        CHECK_ULP_CLOSE(Real(7), qh_aos(t), 24);\n        CHECK_ULP_CLOSE(Real(0), qh_aos.prime(t), 24);\n        CHECK_ULP_CLOSE(Real(0), qh_aos.double_prime(t), 24);\n    }\n\n    // Now check the boundaries:\n    auto [tlo, thi] = qh.domain();\n    int samples = 5000;\n    int i = 0;\n    while (i++ < samples)\n    {\n        CHECK_ULP_CLOSE(Real(7), qh(tlo), 2);\n        CHECK_ULP_CLOSE(Real(7), qh(thi), 2);\n        CHECK_ULP_CLOSE(Real(7), qh_aos(tlo), 2);\n        CHECK_ULP_CLOSE(Real(7), qh_aos(thi), 2);\n        CHECK_ULP_CLOSE(Real(0), qh.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(0), qh.prime(thi), 2);\n        CHECK_ULP_CLOSE(Real(0), qh_aos.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(0), qh_aos.prime(thi), 2);\n\n        tlo = boost::math::nextafter(tlo, std::numeric_limits<Real>::max());\n        thi = boost::math::nextafter(thi, std::numeric_limits<Real>::lowest());\n    }\n}\n\n\ntemplate<typename Real>\nvoid test_cardinal_linear()\n{\n    std::vector<Real> y{0,1,2,3,4,5,6,7,8,9};\n    Real x0 = 0;\n    Real dx = 1;\n    std::vector<Real> dydx(y.size(), 1);\n    std::vector<Real> d2ydx2(y.size(), 0);\n\n    auto qh = cardinal_quintic_hermite(std::move(y), std::move(dydx), std::move(d2ydx2), x0, dx);\n\n    for (Real t = 0; t <= 9; t += 0.25) {\n        CHECK_ULP_CLOSE(Real(t), qh(t), 2);\n        CHECK_ULP_CLOSE(Real(1), qh.prime(t), 2);\n        CHECK_ULP_CLOSE(Real(0), qh.double_prime(t), 2);\n    }\n\n    std::vector<std::array<Real, 3>> data(10);\n    for (size_t i = 0; i < data.size(); ++i) {\n        data[i][0] = i;\n        data[i][1] = 1;\n        data[i][2] = 0;\n    }\n\n    auto qh_aos = cardinal_quintic_hermite_aos(std::move(data), x0, dx);\n\n    for (Real t = 0; t <= 9; t += 0.25) {\n        CHECK_ULP_CLOSE(Real(t), qh_aos(t), 2);\n        CHECK_ULP_CLOSE(Real(1), qh_aos.prime(t), 2);\n        CHECK_ULP_CLOSE(Real(0), qh_aos.double_prime(t), 2);\n    }\n\n    // Now check the boundaries:\n    auto [tlo, thi] = qh.domain();\n    int samples = 5000;\n    int i = 0;\n    while (i++ < samples)\n    {\n        CHECK_ULP_CLOSE(Real(tlo), qh(tlo), 2);\n        CHECK_ULP_CLOSE(Real(thi), qh(thi), 2);\n        CHECK_ULP_CLOSE(Real(tlo), qh_aos(tlo), 2);\n        CHECK_ULP_CLOSE(Real(thi), qh_aos(thi), 2);\n        CHECK_ULP_CLOSE(Real(1), qh.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(1), qh.prime(thi), 128);\n        CHECK_ULP_CLOSE(Real(1), qh_aos.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(1), qh_aos.prime(thi), 128);\n\n        tlo = boost::math::nextafter(tlo, std::numeric_limits<Real>::max());\n        thi = boost::math::nextafter(thi, std::numeric_limits<Real>::lowest());\n    }\n}\n\ntemplate<typename Real>\nvoid test_cardinal_quadratic()\n{\n    Real x0 = 0;\n    Real dx = 1;\n    std::vector<Real> y(10);\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = i*i/Real(2);\n    }\n\n    std::vector<Real> dydx(y.size());\n    for (size_t i = 0; i < y.size(); ++i) {\n        dydx[i] = i;\n    }\n\n    std::vector<Real> d2ydx2(y.size(), 1);\n\n    auto qh = cardinal_quintic_hermite(std::move(y), std::move(dydx), std::move(d2ydx2), x0, dx);\n\n    for (Real t = 0; t <= 9; t += 0.0078125) {\n        Real computed = qh(t);\n        CHECK_ULP_CLOSE(Real(t*t)/2, computed, 2);\n        CHECK_ULP_CLOSE(t, qh.prime(t), 15);\n        CHECK_ULP_CLOSE(Real(1), qh.double_prime(t), 32);\n    }\n\n    std::vector<std::array<Real, 3>> data(10);\n    for (size_t i = 0; i < data.size(); ++i) {\n        data[i][0] = i*i/Real(2);\n        data[i][1] = i;\n        data[i][2] = 1;\n    }\n    auto qh_aos = cardinal_quintic_hermite_aos(std::move(data), x0, dx);\n\n    for (Real t = 0; t <= 9; t += 0.0078125)\n    {\n        Real computed = qh_aos(t);\n        CHECK_ULP_CLOSE(Real(t*t)/2, computed, 2);\n        CHECK_ULP_CLOSE(t, qh_aos.prime(t), 12);\n        CHECK_ULP_CLOSE(Real(1), qh_aos.double_prime(t), 64);\n    }\n\n        // Now check the boundaries:\n    auto [tlo, thi] = qh.domain();\n    int samples = 5000;\n    int i = 0;\n    while (i++ < samples)\n    {\n        CHECK_ULP_CLOSE(tlo*tlo/2, qh(tlo), 16);\n        CHECK_ULP_CLOSE(thi*thi/2, qh(thi), 16);\n        CHECK_ULP_CLOSE(tlo*tlo/2, qh_aos(tlo), 16);\n        CHECK_ULP_CLOSE(thi*thi/2, qh_aos(thi), 16);\n        CHECK_ULP_CLOSE(tlo, qh.prime(tlo), 16);\n        CHECK_ULP_CLOSE(thi, qh.prime(thi), 64);\n        CHECK_ULP_CLOSE(tlo, qh_aos.prime(tlo), 16);\n        CHECK_ULP_CLOSE(thi, qh_aos.prime(thi), 64);\n\n        tlo = boost::math::nextafter(tlo, std::numeric_limits<Real>::max());\n        thi = boost::math::nextafter(thi, std::numeric_limits<Real>::lowest());\n    }\n}\n\ntemplate<typename Real>\nvoid test_cardinal_cubic()\n{\n    Real x0 = 0;\n    Real dx = 1;\n    std::vector<Real> y(10);\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = i*i*i;\n    }\n\n    std::vector<Real> dydx(y.size());\n    for (size_t i = 0; i < y.size(); ++i) {\n        dydx[i] = 3*i*i;\n    }\n\n    std::vector<Real> d2ydx2(y.size());\n    for (size_t i = 0; i < y.size(); ++i) {\n        d2ydx2[i] = 6*i;\n    }\n\n    auto qh = cardinal_quintic_hermite(std::move(y), std::move(dydx), std::move(d2ydx2), x0, dx);\n\n    for (Real t = 0; t <= 9; t += 0.0078125)\n    {\n        Real computed = qh(t);\n        CHECK_ULP_CLOSE(t*t*t, computed, 10);\n        CHECK_ULP_CLOSE(3*t*t, qh.prime(t), 15);\n        CHECK_ULP_CLOSE(6*t, qh.double_prime(t), 39);\n    }\n\n    std::vector<std::array<Real, 3>> data(10);\n    for (size_t i = 0; i < data.size(); ++i) {\n        data[i][0] = i*i*i;\n        data[i][1] = 3*i*i;\n        data[i][2] = 6*i;\n    }\n\n    auto qh_aos = cardinal_quintic_hermite_aos(std::move(data), x0, dx);\n    for (Real t = 0; t <= 9; t += 0.0078125)\n    {\n        Real computed = qh_aos(t);\n        CHECK_ULP_CLOSE(t*t*t, computed, 10);\n        CHECK_ULP_CLOSE(3*t*t, qh_aos.prime(t), 15);\n        CHECK_ULP_CLOSE(6*t, qh_aos.double_prime(t), 30);\n    }\n}\n\ntemplate<typename Real>\nvoid test_cardinal_quartic()\n{\n    Real x0 = 0;\n    Real dx = 1;\n    std::vector<Real> y(7);\n    for (size_t i = 0; i < y.size(); ++i)\n    {\n        y[i] = i*i*i*i;\n    }\n\n    std::vector<Real> dydx(y.size());\n    for (size_t i = 0; i < y.size(); ++i) {\n        dydx[i] = 4*i*i*i;\n    }\n\n    std::vector<Real> d2ydx2(y.size());\n    for (size_t i = 0; i < y.size(); ++i) {\n        d2ydx2[i] = 12*i*i;\n    }\n\n    auto qh = cardinal_quintic_hermite(std::move(y), std::move(dydx), std::move(d2ydx2), x0, dx);\n\n    for (Real t = 0; t <= 6; t += 0.0078125)\n    {\n        CHECK_ULP_CLOSE(Real(t*t*t*t), qh(t), 250);\n        CHECK_ULP_CLOSE(4*t*t*t, qh.prime(t), 250);\n        CHECK_ULP_CLOSE(12*t*t, qh.double_prime(t), 250);\n    }\n\n    std::vector<std::array<Real, 3>> data(7);\n    for (size_t i = 0; i < data.size(); ++i) {\n        data[i][0] = i*i*i*i;\n        data[i][1] = 4*i*i*i;\n        data[i][2] = 12*i*i;\n    }\n\n    auto qh_aos = cardinal_quintic_hermite_aos(std::move(data), x0, dx);\n    for (Real t = 0; t <= 6; t += 0.0078125)\n    {\n        Real computed = qh_aos(t);\n        CHECK_ULP_CLOSE(t*t*t*t, computed, 10);\n        CHECK_ULP_CLOSE(4*t*t*t, qh_aos.prime(t), 64);\n        CHECK_ULP_CLOSE(12*t*t, qh_aos.double_prime(t), 128);\n    }\n}\n\n\nint main()\n{\n    test_constant<float>();\n    test_linear<float>();\n    test_quadratic<float>();\n    test_cubic<float>();\n    test_quartic<float>();\n    test_interpolation_condition<float>();\n\n    test_cardinal_constant<float>();\n    test_cardinal_linear<float>();\n    test_cardinal_quadratic<float>();\n    test_cardinal_cubic<float>();\n    test_cardinal_quartic<float>();\n\n    test_constant<double>();\n    test_linear<double>();\n    test_quadratic<double>();\n    test_cubic<double>();\n    test_quartic<double>();\n    test_interpolation_condition<double>();\n\n    test_cardinal_constant<double>();\n    test_cardinal_linear<double>();\n    test_cardinal_quadratic<double>();\n    test_cardinal_cubic<double>();\n    test_cardinal_quartic<double>();\n\n    test_constant<long double>();\n    test_linear<long double>();\n    test_quadratic<long double>();\n    test_cubic<long double>();\n    test_quartic<long double>();\n    test_interpolation_condition<long double>();\n\n    test_cardinal_constant<long double>();\n    test_cardinal_linear<long double>();\n    test_cardinal_quadratic<long double>();\n    test_cardinal_cubic<long double>();\n    test_cardinal_quartic<long double>();\n\n#ifdef BOOST_HAS_FLOAT128\n    test_constant<float128>();\n    //test_linear<float128>();\n    test_quadratic<float128>();\n    test_cubic<float128>();\n    test_quartic<float128>();\n    test_interpolation_condition<float128>();\n    test_cardinal_constant<float128>();\n    test_cardinal_linear<float128>();\n    test_cardinal_quadratic<float128>();\n    test_cardinal_cubic<float128>();\n    test_cardinal_quartic<float128>();\n#endif\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "05299bae3526671e74c3205cf23bbf812e2519e1", "size": 16365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/quintic_hermite_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:52:18.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/test/quintic_hermite_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/test/quintic_hermite_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 28.1669535284, "max_line_length": 117, "alphanum_fraction": 0.5599755576, "num_tokens": 5641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5573218318319132}}
{"text": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/integer_list.hpp>\n#include <boost/hana/integral.hpp>\nusing namespace boost::hana;\nusing namespace literals;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTEXPR_LAMBDA auto numbers = integer_list<int, 5, -1, 0, -7, -2, 0, -5, 4>;\n    BOOST_HANA_CONSTEXPR_LAMBDA auto negatives = integer_list<int, -1, -7, -2, -5>;\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto keep_negatives = [](auto n, auto acc) {\n        return if_(n < 0_c, cons(n, acc), acc);\n    };\n\n    BOOST_HANA_CONSTANT_ASSERT(\n        foldr(numbers, integer_list<int>, keep_negatives) == negatives\n    );\n    //! [main]\n}\n", "meta": {"hexsha": "5519ceb890a023e5e058d4ccd41250513d3f9d3c", "size": 856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/integer_list/foldable/foldr.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/integer_list/foldable/foldr.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/integer_list/foldable/foldr.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5172413793, "max_line_length": 93, "alphanum_fraction": 0.6939252336, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5572482696956911}}
{"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\n * @brief NPDE homework ProjectionOntoGradients code\n * @author ?, Philippe Peter\n * @date December 2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"../projectionontogradients.h\"\n\n#include <gtest/gtest.h>\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/fe/fe.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <memory>\n\nnamespace ProjectionOntoGradients::test {\n\nTEST(ProjectionOntoGradients, ElementMatrixProvider) {\n  // Building triangular test mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n\n  // implemented element matrix provider\n  ElementMatrixProvider my_elem_mat_provider{};\n\n  // For comparison\n  lf::uscalfe::LinearFELaplaceElementMatrix lfe_elem_mat_provider{};\n\n  // loop over cells and compute element matrices\n  for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n    Eigen::Matrix3d my_mat{my_elem_mat_provider.Eval(*cell)};\n    lf::uscalfe::LinearFELaplaceElementMatrix::ElemMat lfe_mat{\n        lfe_elem_mat_provider.Eval(*cell)};\n\n    // compare element matrices:\n    EXPECT_NEAR((lfe_mat.block<3, 3>(0, 0) - my_mat).norm(), 0.0, 1E-3);\n  }\n}\n\nTEST(ProjectionOntoGradients, GradProjRhsProvider_1) {\n  // Building triangular test mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n\n  // initialize functions f and v for which the linear form is evaluated\n  auto f = [](Eigen::Vector2d x) { return Eigen::Vector2d(1.0, 2.0); };\n  auto v = [](Eigen::Vector2d x) { return 2 * x(0) + x(1); };\n  auto v_mf = lf::mesh::utils::MeshFunctionGlobal(v);\n\n  // set up finite elements\n  std::shared_ptr<const lf::uscalfe::UniformScalarFESpace<double>> fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  // construct element vector provider\n  GradProjRhsProvider my_vec_provider(f);\n\n  // assemble vector\n  Eigen::VectorXd phi(fe_space->LocGlobMap().NumDofs());\n  phi.setZero();\n  lf::assemble::AssembleVectorLocally(0, fe_space->LocGlobMap(),\n                                      my_vec_provider, phi);\n\n  // project v onto the fe space\n  auto v_vec = lf::fe::NodalProjection<double>(*fe_space, v_mf);\n\n  // evaluate linear form on projected function:\n  auto product = (v_vec.transpose() * phi).eval();\n  EXPECT_NEAR(product(0, 0), 36, 1E-5);\n}\n\nTEST(ProjectionOntoGradients, GradProjRhsProvider_2) {\n  // Building triangular test mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n\n  // initialize functions f and v for which the linear form is evaluated\n  auto f = [](Eigen::Vector2d x) { return Eigen::Vector2d(x(1), x(0)); };\n  auto v = [](Eigen::Vector2d x) { return 2 * x(0) + x(1); };\n  auto v_mf = lf::mesh::utils::MeshFunctionGlobal(v);\n\n  // set up finite elements\n  std::shared_ptr<const lf::uscalfe::UniformScalarFESpace<double>> fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  // construct element vector provider\n  GradProjRhsProvider my_vec_provider(f);\n\n  // assemble vector\n  Eigen::VectorXd phi(fe_space->LocGlobMap().NumDofs());\n  phi.setZero();\n  lf::assemble::AssembleVectorLocally(0, fe_space->LocGlobMap(),\n                                      my_vec_provider, phi);\n\n  // project v onto the fe space\n  auto v_vec = lf::fe::NodalProjection<double>(*fe_space, v_mf);\n\n  // evaluate linear form on projected function:\n  auto product = (v_vec.transpose() * phi).eval();\n  EXPECT_NEAR(product(0, 0), 40.5, 1E-5);\n}\n\n/* SAM_LISTING_BEGIN_1 */\nTEST(ProjectionOntoGradients, div_free_test) {\n  // Building test mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n  // Divergence-free vector field\n  const auto f = [](Eigen::Vector2d x) { return Eigen::Vector2d(-x(1), x(0)); };\n\n  // DofHandler for the p.w. linear Lagrangian finite element\n  lf::assemble::UniformFEDofHandler dofh(mesh_p,\n                                         {{lf::base::RefEl::kPoint(), 1},\n                                          {lf::base::RefEl::kSegment(), 0},\n                                          {lf::base::RefEl::kTria(), 0}});\n  // Compute solution\n  const Eigen::VectorXd sol_vec =\n      ProjectionOntoGradients::projectOntoGradients(dofh, f);\n\n  // As stated in the exercise, we would expect the solution to be zero.\n  // Hence we check every entry if its (numerically) zero.\n  // The GoogleTest framework provides a function we may use:\n  /*   EXPECT_NEAR(value 1, value 2, max. difference) */\n  const double eps = 1e-15;\n  for (std::size_t i = 0; i < sol_vec.size(); ++i) {\n    EXPECT_NEAR(sol_vec[i], 0.0, eps);\n    // Try testing for equality, you'll see it will fail miserably!\n    /* EXPECT_EQ(sol_vec[i], 0.0); */\n  }\n}\n/* SAM_LISTING_END_1 */\n\nTEST(ProjectionOntoGradients, exact_sol_test) {\n  // I. Construct the test mesh\n  // mesh builder in a world of dimension 2\n  lf::mesh::utils::TPTriagMeshBuilder my_builder(\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2));\n\n  // define the test mesh\n  my_builder.setBottomLeftCorner(Eigen::Vector2d{0, 0})\n      .setTopRightCorner(Eigen::Vector2d{1, 1})\n      .setNumXCells(10)\n      .setNumYCells(10);\n\n  auto mesh_p = my_builder.Build();\n\n  // II. Construct a linear finite element space on the test mesh\n  lf::uscalfe::FeSpaceLagrangeO1<double> fe_space(mesh_p);\n\n  // III. Define a function which computes the index of the triangle in which\n  // the coorindates of a given point are\n  const auto triangleIndex = [](Eigen::Vector2d x) {\n    if (x(0) >= 0.0 && x(0) <= 0.5 && x(1) >= 0.0 && x(1) <= 0.5) {\n      if (x(0) < x(1))\n        return 0;\n      else\n        return 1;\n    } else if (x(0) >= 0.0 && x(0) <= 0.5 && x(1) >= 0.5 && x(1) <= 1.0) {\n      if (x(0) + 0.5 < x(1))\n        return 2;\n      else\n        return 3;\n    } else if (x(0) >= 0.5 && x(0) <= 1.0 && x(1) >= 0.0 && x(1) <= 0.5) {\n      if (x(0) < 0.5 + x(1))\n        return 4;\n      else\n        return 5;\n    } else if (x(0) >= 0.5 && x(0) <= 1.0 && x(1) >= 0.5 && x(1) <= 1.0) {\n      if (x(0) < x(1))\n        return 6;\n      else\n        return 7;\n    } else {\n      LF_ASSERT_MSG(false, \"Coordinates outside of unit square\");\n    }\n  };\n\n  // IV. Define the function f\n  const auto f = [&triangleIndex](Eigen::Vector2d x) {\n    int triang_idx = triangleIndex(x);\n    // return the function value according to the definition in the\n    // exercise\n    switch (triang_idx) {\n      case 0:\n        return Eigen::Vector2d(2, 0);\n      case 1:\n        return Eigen::Vector2d(0, 2);\n      case 3:\n        return Eigen::Vector2d(2, -2);\n      case 4:\n        return Eigen::Vector2d(-2, 2);\n      case 6:\n        return Eigen::Vector2d(0, -2);\n      case 7:\n        return Eigen::Vector2d(-2, 0);\n      default:\n        return Eigen::Vector2d(0, 0);\n    }\n  };\n\n  // V. Define the tent function associated with the central node\n  const auto tentFunction = [&triangleIndex](Eigen::Vector2d x) {\n    int triang_idx = triangleIndex(x);\n    // Observe that the restriction of the tent function on\n    // any adjecant triangle is by definition a linear function a*x + b*y + c.\n    // The gradients of these linear functions are given in the exercise\n    // so we can read of the values of a and b. We then compute the\n    // value of c to ensure that the linear function evaluates to\n    // one at the central node.\n    switch (triang_idx) {\n      case 0:\n        return 2.0 * x(0);\n      case 1:\n        return 2.0 * x(1);\n      case 3:\n        return 2.0 * x(0) - 2.0 * x(1) + 1.0;\n      case 4:\n        return -2.0 * x(0) + 2.0 * x(1) + 1.0;\n      case 6:\n        return -2.0 * x(1) + 2.0;\n      case 7:\n        return -2.0 * x(0) + 2.0;\n      default:\n        return 0.0;\n    }\n  };\n\n  // VI.Determine the coefficient vector of the tent function in\n  // the FE space (perform a Nodal projection)\n  // The Function lf::fe::NodalProjection requires a mesh function as its\n  // second argument, so we first construct a meshFunction object which\n  // describes the tent function.\n  auto tentFunction_mf = lf::mesh::utils::MeshFunctionGlobal(tentFunction);\n  auto ref_vec = lf::fe::NodalProjection<double>(fe_space, tentFunction_mf);\n\n  // VII. Test your implementation\n  const Eigen::VectorXd sol_vec =\n      projectOntoGradients(fe_space.LocGlobMap(), f);\n  EXPECT_NEAR((sol_vec - ref_vec).norm(), 0.0, 1e-12);\n}\n\n}  // namespace ProjectionOntoGradients::test\n", "meta": {"hexsha": "057c80aff0cd689fd2e58b6b00662c020be25b76", "size": 8443, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ProjectionOntoGradients/mastersolution/test/projectionontogradients_test.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ProjectionOntoGradients/mastersolution/test/projectionontogradients_test.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ProjectionOntoGradients/mastersolution/test/projectionontogradients_test.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 34.4612244898, "max_line_length": 80, "alphanum_fraction": 0.6388724387, "num_tokens": 2564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5572482580264495}}
{"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 CombinedImuFactorsExample\n * @brief Test example for using GTSAM ImuCombinedFactor\n * navigation code.\n * @author Varun Agrawal\n */\n\n/**\n * Example of use of the CombinedImuFactor in\n * conjunction with GPS\n *  - we read IMU and GPS data from a CSV file, with the following format:\n *  A row starting with \"i\" is the first initial position formatted with\n *  N, E, D, qx, qY, qZ, qW, velN, velE, velD\n *  A row starting with \"0\" is an imu measurement\n *  (body frame - Forward, Right, Down)\n *  linAccX, linAccY, linAccZ, angVelX, angVelY, angVelX\n *  A row starting with \"1\" is a gps correction formatted with\n *  N, E, D, qX, qY, qZ, qW\n * Note that for GPS correction, we're only using the position not the\n * rotation. The rotation is provided in the file for ground truth comparison.\n *\n *  See usage: ./CombinedImuFactorsExample --help\n */\n\n#include <boost/program_options.hpp>\n\n// GTSAM related includes.\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/navigation/CombinedImuFactor.h>\n#include <gtsam/navigation/GPSFactor.h>\n#include <gtsam/navigation/ImuFactor.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/slam/dataset.h>\n\n#include <cstring>\n#include <fstream>\n#include <iostream>\n\nusing namespace gtsam;\nusing namespace std;\n\nusing symbol_shorthand::B;  // Bias  (ax,ay,az,gx,gy,gz)\nusing symbol_shorthand::V;  // Vel   (xdot,ydot,zdot)\nusing symbol_shorthand::X;  // Pose3 (x,y,z,r,p,y)\n\nnamespace po = boost::program_options;\n\npo::variables_map parseOptions(int argc, char* argv[]) {\n  po::options_description desc;\n  desc.add_options()(\"help,h\", \"produce help message\")(\n      \"data_csv_path\", po::value<string>()->default_value(\"imuAndGPSdata.csv\"),\n      \"path to the CSV file with the IMU data\")(\n      \"output_filename\",\n      po::value<string>()->default_value(\"imuFactorExampleResults.csv\"),\n      \"path to the result file to use\")(\"use_isam\", po::bool_switch(),\n                                        \"use ISAM as the optimizer\");\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n\n  if (vm.count(\"help\")) {\n    cout << desc << \"\\n\";\n    exit(1);\n  }\n\n  return vm;\n}\n\nVector10 readInitialState(ifstream& file) {\n  string value;\n  // Format is (N,E,D,qX,qY,qZ,qW,velN,velE,velD)\n  Vector10 initial_state;\n  getline(file, value, ',');  // i\n  for (int i = 0; i < 9; i++) {\n    getline(file, value, ',');\n    initial_state(i) = stof(value.c_str());\n  }\n  getline(file, value, '\\n');\n  initial_state(9) = stof(value.c_str());\n\n  return initial_state;\n}\n\nboost::shared_ptr<PreintegratedCombinedMeasurements::Params> imuParams() {\n  // We use the sensor specs to build the noise model for the IMU factor.\n  double accel_noise_sigma = 0.0003924;\n  double gyro_noise_sigma = 0.000205689024915;\n  double accel_bias_rw_sigma = 0.004905;\n  double gyro_bias_rw_sigma = 0.000001454441043;\n  Matrix33 measured_acc_cov = I_3x3 * pow(accel_noise_sigma, 2);\n  Matrix33 measured_omega_cov = I_3x3 * pow(gyro_noise_sigma, 2);\n  Matrix33 integration_error_cov =\n      I_3x3 * 1e-8;  // error committed in integrating position from velocities\n  Matrix33 bias_acc_cov = I_3x3 * pow(accel_bias_rw_sigma, 2);\n  Matrix33 bias_omega_cov = I_3x3 * pow(gyro_bias_rw_sigma, 2);\n  Matrix66 bias_acc_omega_int =\n      I_6x6 * 1e-5;  // error in the bias used for preintegration\n\n  auto p = PreintegratedCombinedMeasurements::Params::MakeSharedD(0.0);\n  // PreintegrationBase params:\n  p->accelerometerCovariance =\n      measured_acc_cov;  // acc white noise in continuous\n  p->integrationCovariance =\n      integration_error_cov;  // integration uncertainty continuous\n  // should be using 2nd order integration\n  // PreintegratedRotation params:\n  p->gyroscopeCovariance =\n      measured_omega_cov;  // gyro white noise in continuous\n  // PreintegrationCombinedMeasurements params:\n  p->biasAccCovariance = bias_acc_cov;      // acc bias in continuous\n  p->biasOmegaCovariance = bias_omega_cov;  // gyro bias in continuous\n  p->biasAccOmegaInt = bias_acc_omega_int;\n\n  return p;\n}\n\nint main(int argc, char* argv[]) {\n  string data_filename, output_filename;\n  po::variables_map var_map = parseOptions(argc, argv);\n\n  data_filename = findExampleDataFile(var_map[\"data_csv_path\"].as<string>());\n  output_filename = var_map[\"output_filename\"].as<string>();\n\n  // Set up output file for plotting errors\n  FILE* fp_out = fopen(output_filename.c_str(), \"w+\");\n  fprintf(fp_out,\n          \"#time(s),x(m),y(m),z(m),qx,qy,qz,qw,gt_x(m),gt_y(m),gt_z(m),gt_qx,\"\n          \"gt_qy,gt_qz,gt_qw\\n\");\n\n  // Begin parsing the CSV file.  Input the first line for initialization.\n  // From there, we'll iterate through the file and we'll preintegrate the IMU\n  // or add in the GPS given the input.\n  ifstream file(data_filename.c_str());\n\n  Vector10 initial_state = readInitialState(file);\n  cout << \"initial state:\\n\" << initial_state.transpose() << \"\\n\\n\";\n\n  // Assemble initial quaternion through GTSAM constructor\n  // ::Quaternion(w,x,y,z);\n  Rot3 prior_rotation = Rot3::Quaternion(initial_state(6), initial_state(3),\n                                         initial_state(4), initial_state(5));\n  Point3 prior_point(initial_state.head<3>());\n  Pose3 prior_pose(prior_rotation, prior_point);\n  Vector3 prior_velocity(initial_state.tail<3>());\n\n  imuBias::ConstantBias prior_imu_bias;  // assume zero initial bias\n\n  int index = 0;\n\n  Values initial_values;\n\n  // insert pose at initialization\n  initial_values.insert(X(index), prior_pose);\n  initial_values.insert(V(index), prior_velocity);\n  initial_values.insert(B(index), prior_imu_bias);\n\n  // Assemble prior noise model and add it the graph.`\n  auto pose_noise_model = noiseModel::Diagonal::Sigmas(\n      (Vector(6) << 0.01, 0.01, 0.01, 0.5, 0.5, 0.5)\n          .finished());  // rad,rad,rad,m, m, m\n  auto velocity_noise_model = noiseModel::Isotropic::Sigma(3, 0.1);  // m/s\n  auto bias_noise_model = noiseModel::Isotropic::Sigma(6, 1e-3);\n\n  // Add all prior factors (pose, velocity, bias) to the graph.\n  NonlinearFactorGraph graph;\n  graph.addPrior<Pose3>(X(index), prior_pose, pose_noise_model);\n  graph.addPrior<Vector3>(V(index), prior_velocity, velocity_noise_model);\n  graph.addPrior<imuBias::ConstantBias>(B(index), prior_imu_bias,\n                                        bias_noise_model);\n\n  auto p = imuParams();\n\n  std::shared_ptr<PreintegrationType> preintegrated =\n      std::make_shared<PreintegratedCombinedMeasurements>(p, prior_imu_bias);\n\n  assert(preintegrated);\n\n  // Store previous state for imu integration and latest predicted outcome.\n  NavState prev_state(prior_pose, prior_velocity);\n  NavState prop_state = prev_state;\n  imuBias::ConstantBias prev_bias = prior_imu_bias;\n\n  // Keep track of total error over the entire run as simple performance metric.\n  double current_position_error = 0.0, current_orientation_error = 0.0;\n\n  double output_time = 0.0;\n  double dt = 0.005;  // The real system has noise, but here, results are nearly\n                      // exactly the same, so keeping this for simplicity.\n\n  // All priors have been set up, now iterate through the data file.\n  while (file.good()) {\n    // Parse out first value\n    string value;\n    getline(file, value, ',');\n    int type = stoi(value.c_str());\n\n    if (type == 0) {  // IMU measurement\n      Vector6 imu;\n      for (int i = 0; i < 5; ++i) {\n        getline(file, value, ',');\n        imu(i) = stof(value.c_str());\n      }\n      getline(file, value, '\\n');\n      imu(5) = stof(value.c_str());\n\n      // Adding the IMU preintegration.\n      preintegrated->integrateMeasurement(imu.head<3>(), imu.tail<3>(), dt);\n\n    } else if (type == 1) {  // GPS measurement\n      Vector7 gps;\n      for (int i = 0; i < 6; ++i) {\n        getline(file, value, ',');\n        gps(i) = stof(value.c_str());\n      }\n      getline(file, value, '\\n');\n      gps(6) = stof(value.c_str());\n\n      index++;\n\n      // Adding IMU factor and GPS factor and optimizing.\n      auto preint_imu_combined =\n          dynamic_cast<const PreintegratedCombinedMeasurements&>(\n              *preintegrated);\n      CombinedImuFactor imu_factor(X(index - 1), V(index - 1), X(index),\n                                   V(index), B(index - 1), B(index),\n                                   preint_imu_combined);\n      graph.add(imu_factor);\n\n      auto correction_noise = noiseModel::Isotropic::Sigma(3, 1.0);\n      GPSFactor gps_factor(X(index),\n                           Point3(gps(0),   // N,\n                                  gps(1),   // E,\n                                  gps(2)),  // D,\n                           correction_noise);\n      graph.add(gps_factor);\n\n      // Now optimize and compare results.\n      prop_state = preintegrated->predict(prev_state, prev_bias);\n      initial_values.insert(X(index), prop_state.pose());\n      initial_values.insert(V(index), prop_state.v());\n      initial_values.insert(B(index), prev_bias);\n\n      LevenbergMarquardtParams params;\n      params.setVerbosityLM(\"SUMMARY\");\n      LevenbergMarquardtOptimizer optimizer(graph, initial_values, params);\n      Values result = optimizer.optimize();\n\n      // Overwrite the beginning of the preintegration for the next step.\n      prev_state =\n          NavState(result.at<Pose3>(X(index)), result.at<Vector3>(V(index)));\n      prev_bias = result.at<imuBias::ConstantBias>(B(index));\n\n      // Reset the preintegration object.\n      preintegrated->resetIntegrationAndSetBias(prev_bias);\n\n      // Print out the position and orientation error for comparison.\n      Vector3 result_position = prev_state.pose().translation();\n      Vector3 position_error = result_position - gps.head<3>();\n      current_position_error = position_error.norm();\n\n      Quaternion result_quat = prev_state.pose().rotation().toQuaternion();\n      Quaternion gps_quat(gps(6), gps(3), gps(4), gps(5));\n      Quaternion quat_error = result_quat * gps_quat.inverse();\n      quat_error.normalize();\n      Vector3 euler_angle_error(quat_error.x() * 2, quat_error.y() * 2,\n                                quat_error.z() * 2);\n      current_orientation_error = euler_angle_error.norm();\n\n      // display statistics\n      cout << \"Position error:\" << current_position_error << \"\\t \"\n           << \"Angular error:\" << current_orientation_error << \"\\n\"\n           << endl;\n\n      fprintf(fp_out, \"%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f\\n\",\n              output_time, result_position(0), result_position(1),\n              result_position(2), result_quat.x(), result_quat.y(),\n              result_quat.z(), result_quat.w(), gps(0), gps(1), gps(2),\n              gps_quat.x(), gps_quat.y(), gps_quat.z(), gps_quat.w());\n\n      output_time += 1.0;\n\n    } else {\n      cerr << \"ERROR parsing file\\n\";\n      return 1;\n    }\n  }\n  fclose(fp_out);\n  cout << \"Complete, results written to \" << output_filename << \"\\n\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "9211a4d5f0fbe5b9a915fb1fc9e9bfe7ddcc258e", "size": 11355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/CombinedImuFactorsExample.cpp", "max_stars_repo_name": "h-rover/gtsam", "max_stars_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "examples/CombinedImuFactorsExample.cpp", "max_issues_repo_name": "h-rover/gtsam", "max_issues_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "examples/CombinedImuFactorsExample.cpp", "max_forks_repo_name": "h-rover/gtsam", "max_forks_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 37.2295081967, "max_line_length": 80, "alphanum_fraction": 0.65222369, "num_tokens": 2967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5572482479278316}}
{"text": "#include <stan/math/mix/mat.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <vector>\n#include <limits>\n\nusing stan::math::fvar;\nusing stan::math::var;\n\nTEST(AgradMixMatrixSquaredDistance, vector_fv_vector_fv1) {\n  stan::math::vector_fv v1, v2;\n\n  v1.resize(3);\n  v2.resize(3);\n  v1 << 1, 3, -5;\n  v2 << 4, -2, -1;\n  v1(0).d_ = 1.0;\n  v1(1).d_ = 2.0;\n  v1(2).d_ = 3.0;\n  v2(0).d_ = 4.0;\n  v2(1).d_ = 5.0;\n  v2(2).d_ = 6.0;\n\n  stan::math::fvar<var> a = stan::math::squared_distance(v1, v2);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(v1(0).val_);\n  vars.push_back(v1(1).val_);\n  vars.push_back(v1(2).val_);\n  vars.push_back(v2(0).val_);\n  vars.push_back(v2(1).val_);\n  vars.push_back(v2(2).val_);\n\n  a.val_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(10, grads[1]);\n  EXPECT_FLOAT_EQ(-8, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(-10, grads[4]);\n  EXPECT_FLOAT_EQ(8, grads[5]);\n\n  v1.resize(0);\n  v2.resize(0);\n  EXPECT_FLOAT_EQ(0, stan::math::squared_distance(v1, v2).val_.val());\n\n  v1.resize(1);\n  v2.resize(2);\n  v1 << 1;\n  v2 << 2, 3;\n  EXPECT_THROW(stan::math::squared_distance(v1, v2), std::invalid_argument);\n}\n\nTEST(AgradMixMatrixSquaredDistance, vector_fv_vector_fv2) {\n  stan::math::vector_fv v1, v2;\n\n  v1.resize(3);\n  v2.resize(3);\n  v1 << 1, 3, -5;\n  v2 << 4, -2, -1;\n  v1(0).d_ = 1.0;\n  v1(1).d_ = 2.0;\n  v1(2).d_ = 3.0;\n  v2(0).d_ = 4.0;\n  v2(1).d_ = 5.0;\n  v2(2).d_ = 6.0;\n\n  stan::math::fvar<var> a = stan::math::squared_distance(v1, v2);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(v1(0).val_);\n  vars.push_back(v1(1).val_);\n  vars.push_back(v1(2).val_);\n  vars.push_back(v2(0).val_);\n  vars.push_back(v2(1).val_);\n  vars.push_back(v2(2).val_);\n\n  a.d_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(-6, grads[1]);\n  EXPECT_FLOAT_EQ(-6, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(6, grads[4]);\n  EXPECT_FLOAT_EQ(6, grads[5]);\n}\n\nTEST(AgradMixMatrixSquaredDistance, rowvector_fv_vector_fv1) {\n  stan::math::row_vector_fv rv;\n  stan::math::vector_fv v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n\n  stan::math::fvar<var> a = stan::math::squared_distance(rv, v);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(rv(0).val_);\n  vars.push_back(rv(1).val_);\n  vars.push_back(rv(2).val_);\n  vars.push_back(v(0).val_);\n  vars.push_back(v(1).val_);\n  vars.push_back(v(2).val_);\n\n  a.val_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(10, grads[1]);\n  EXPECT_FLOAT_EQ(-8, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(-10, grads[4]);\n  EXPECT_FLOAT_EQ(8, grads[5]);\n\n  rv.resize(0);\n  v.resize(0);\n  EXPECT_FLOAT_EQ(0, stan::math::squared_distance(rv, v).val_.val());\n\n  rv.resize(1);\n  v.resize(2);\n  rv << 1;\n  v << 2, 3;\n  EXPECT_THROW(stan::math::squared_distance(rv, v), std::invalid_argument);\n}\n\nTEST(AgradMixMatrixSquaredDistance, rowvector_fv_vector_fv2) {\n  stan::math::row_vector_fv rv;\n  stan::math::vector_fv v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n\n  stan::math::fvar<var> a = stan::math::squared_distance(rv, v);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(rv(0).val_);\n  vars.push_back(rv(1).val_);\n  vars.push_back(rv(2).val_);\n  vars.push_back(v(0).val_);\n  vars.push_back(v(1).val_);\n  vars.push_back(v(2).val_);\n\n  a.d_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(-6, grads[1]);\n  EXPECT_FLOAT_EQ(-6, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(6, grads[4]);\n  EXPECT_FLOAT_EQ(6, grads[5]);\n}\n\nTEST(AgradMixMatrixSquaredDistance, vector_fv_rowvector_fv1) {\n  stan::math::row_vector_fv rv;\n  stan::math::vector_fv v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n\n  stan::math::fvar<var> a = stan::math::squared_distance(v, rv);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(rv(0).val_);\n  vars.push_back(rv(1).val_);\n  vars.push_back(rv(2).val_);\n  vars.push_back(v(0).val_);\n  vars.push_back(v(1).val_);\n  vars.push_back(v(2).val_);\n\n  a.val_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(10, grads[1]);\n  EXPECT_FLOAT_EQ(-8, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(-10, grads[4]);\n  EXPECT_FLOAT_EQ(8, grads[5]);\n\n  v.resize(0);\n  rv.resize(0);\n  EXPECT_FLOAT_EQ(0, stan::math::squared_distance(v, rv).val_.val());\n\n  v.resize(1);\n  rv.resize(2);\n  v << 1;\n  rv << 2, 3;\n  EXPECT_THROW(stan::math::squared_distance(v, rv), std::invalid_argument);\n}\n\nTEST(AgradMixMatrixSquaredDistance, vector_fv_rowvector_fv2) {\n  stan::math::row_vector_fv rv;\n  stan::math::vector_fv v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n\n  stan::math::fvar<var> a = stan::math::squared_distance(v, rv);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(rv(0).val_);\n  vars.push_back(rv(1).val_);\n  vars.push_back(rv(2).val_);\n  vars.push_back(v(0).val_);\n  vars.push_back(v(1).val_);\n  vars.push_back(v(2).val_);\n\n  a.d_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(-6, grads[1]);\n  EXPECT_FLOAT_EQ(-6, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(6, grads[4]);\n  EXPECT_FLOAT_EQ(6, grads[5]);\n}\nTEST(AgradMixMatrixSquaredDistance, special_values_fv) {\n  stan::math::vector_fv v1, v2;\n  v1.resize(1);\n  v2.resize(1);\n\n  v1 << 0;\n  v2 << std::numeric_limits<double>::quiet_NaN();\n  EXPECT_TRUE(stan::math::is_nan(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(stan::math::is_nan(stan::math::squared_distance(v2, v1)));\n\n  v1 << 0;\n  v2 << std::numeric_limits<double>::infinity();\n  EXPECT_TRUE(stan::math::is_inf(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(stan::math::is_inf(stan::math::squared_distance(v2, v1)));\n\n  v1 << std::numeric_limits<double>::infinity();\n  v2 << std::numeric_limits<double>::infinity();\n  EXPECT_TRUE(stan::math::is_nan(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(stan::math::is_nan(stan::math::squared_distance(v2, v1)));\n\n  v1 << -std::numeric_limits<double>::infinity();\n  v2 << std::numeric_limits<double>::infinity();\n  EXPECT_TRUE(stan::math::is_inf(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(stan::math::is_inf(stan::math::squared_distance(v2, v1)));\n}\n\nTEST(AgradMixMatrixSquaredDistance, vector_fv_vector_ffv1) {\n  stan::math::vector_ffv v1, v2;\n\n  v1.resize(3);\n  v2.resize(3);\n  v1 << 1, 3, -5;\n  v2 << 4, -2, -1;\n  v1(0).d_ = 1.0;\n  v1(1).d_ = 2.0;\n  v1(2).d_ = 3.0;\n  v2(0).d_ = 4.0;\n  v2(1).d_ = 5.0;\n  v2(2).d_ = 6.0;\n\n  stan::math::fvar<fvar<var> > a = stan::math::squared_distance(v1, v2);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(v1(0).val_.val_);\n  vars.push_back(v1(1).val_.val_);\n  vars.push_back(v1(2).val_.val_);\n  vars.push_back(v2(0).val_.val_);\n  vars.push_back(v2(1).val_.val_);\n  vars.push_back(v2(2).val_.val_);\n\n  a.val_.val_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(10, grads[1]);\n  EXPECT_FLOAT_EQ(-8, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(-10, grads[4]);\n  EXPECT_FLOAT_EQ(8, grads[5]);\n\n  v1.resize(0);\n  v2.resize(0);\n  EXPECT_FLOAT_EQ(0, stan::math::squared_distance(v1, v2).val_.val_.val());\n\n  v1.resize(1);\n  v2.resize(2);\n  v1 << 1;\n  v2 << 2, 3;\n  EXPECT_THROW(stan::math::squared_distance(v1, v2), std::invalid_argument);\n}\n\nTEST(AgradMixMatrixSquaredDistance, vector_fv_vector_ffv2) {\n  stan::math::vector_ffv v1, v2;\n\n  v1.resize(3);\n  v2.resize(3);\n  v1 << 1, 3, -5;\n  v2 << 4, -2, -1;\n  v1(0).d_ = 1.0;\n  v1(1).d_ = 2.0;\n  v1(2).d_ = 3.0;\n  v2(0).d_ = 4.0;\n  v2(1).d_ = 5.0;\n  v2(2).d_ = 6.0;\n  v1(0).val_.d_ = 1.0;\n  v1(1).val_.d_ = 2.0;\n  v1(2).val_.d_ = 3.0;\n  v2(0).val_.d_ = 4.0;\n  v2(1).val_.d_ = 5.0;\n  v2(2).val_.d_ = 6.0;\n\n  stan::math::fvar<fvar<var> > a = stan::math::squared_distance(v1, v2);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(v1(0).val_.val_);\n  vars.push_back(v1(1).val_.val_);\n  vars.push_back(v1(2).val_.val_);\n  vars.push_back(v2(0).val_.val_);\n  vars.push_back(v2(1).val_.val_);\n  vars.push_back(v2(2).val_.val_);\n\n  a.val_.d_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(-6, grads[1]);\n  EXPECT_FLOAT_EQ(-6, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(6, grads[4]);\n  EXPECT_FLOAT_EQ(6, grads[5]);\n}\n\nTEST(AgradMixMatrixSquaredDistance, vector_fv_vector_ffv3) {\n  stan::math::vector_ffv v1, v2;\n\n  v1.resize(3);\n  v2.resize(3);\n  v1 << 1, 3, -5;\n  v2 << 4, -2, -1;\n  v1(0).d_ = 1.0;\n  v1(1).d_ = 2.0;\n  v1(2).d_ = 3.0;\n  v2(0).d_ = 4.0;\n  v2(1).d_ = 5.0;\n  v2(2).d_ = 6.0;\n  v1(0).val_.d_ = 1.0;\n  v1(1).val_.d_ = 2.0;\n  v1(2).val_.d_ = 3.0;\n  v2(0).val_.d_ = 4.0;\n  v2(1).val_.d_ = 5.0;\n  v2(2).val_.d_ = 6.0;\n\n  stan::math::fvar<fvar<var> > a = stan::math::squared_distance(v1, v2);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(v1(0).val_.val_);\n  vars.push_back(v1(1).val_.val_);\n  vars.push_back(v1(2).val_.val_);\n  vars.push_back(v2(0).val_.val_);\n  vars.push_back(v2(1).val_.val_);\n  vars.push_back(v2(2).val_.val_);\n\n  a.d_.val_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(-6, grads[1]);\n  EXPECT_FLOAT_EQ(-6, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(6, grads[4]);\n  EXPECT_FLOAT_EQ(6, grads[5]);\n}\n\nTEST(AgradMixMatrixSquaredDistance, vector_fv_vector_ffv4) {\n  stan::math::vector_ffv v1, v2;\n\n  v1.resize(3);\n  v2.resize(3);\n  v1 << 1, 3, -5;\n  v2 << 4, -2, -1;\n  v1(0).d_ = 1.0;\n  v1(1).d_ = 2.0;\n  v1(2).d_ = 3.0;\n  v2(0).d_ = 4.0;\n  v2(1).d_ = 5.0;\n  v2(2).d_ = 6.0;\n  v1(0).val_.d_ = 1.0;\n  v1(1).val_.d_ = 2.0;\n  v1(2).val_.d_ = 3.0;\n  v2(0).val_.d_ = 4.0;\n  v2(1).val_.d_ = 5.0;\n  v2(2).val_.d_ = 6.0;\n\n  stan::math::fvar<fvar<var> > a = stan::math::squared_distance(v1, v2);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(v1(0).val_.val_);\n  vars.push_back(v1(1).val_.val_);\n  vars.push_back(v1(2).val_.val_);\n  vars.push_back(v2(0).val_.val_);\n  vars.push_back(v2(1).val_.val_);\n  vars.push_back(v2(2).val_.val_);\n\n  a.d_.d_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(0, grads[0]);\n  EXPECT_FLOAT_EQ(-0, grads[1]);\n  EXPECT_FLOAT_EQ(0, grads[2]);\n  EXPECT_FLOAT_EQ(-0, grads[3]);\n  EXPECT_FLOAT_EQ(0, grads[4]);\n  EXPECT_FLOAT_EQ(-0, grads[5]);\n}\n\nTEST(AgradMixMatrixSquaredDistance, rowvector_fv_vector_ffv1) {\n  stan::math::row_vector_ffv rv;\n  stan::math::vector_ffv v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n\n  stan::math::fvar<fvar<var> > a = stan::math::squared_distance(rv, v);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(rv(0).val_.val_);\n  vars.push_back(rv(1).val_.val_);\n  vars.push_back(rv(2).val_.val_);\n  vars.push_back(v(0).val_.val_);\n  vars.push_back(v(1).val_.val_);\n  vars.push_back(v(2).val_.val_);\n\n  a.val_.val_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(10, grads[1]);\n  EXPECT_FLOAT_EQ(-8, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(-10, grads[4]);\n  EXPECT_FLOAT_EQ(8, grads[5]);\n\n  rv.resize(0);\n  v.resize(0);\n  EXPECT_FLOAT_EQ(0, stan::math::squared_distance(rv, v).val_.val_.val());\n\n  rv.resize(1);\n  v.resize(2);\n  rv << 1;\n  v << 2, 3;\n  EXPECT_THROW(stan::math::squared_distance(rv, v), std::invalid_argument);\n}\n\nTEST(AgradMixMatrixSquaredDistance, rowvector_fv_vector_ffv2) {\n  stan::math::row_vector_ffv rv;\n  stan::math::vector_ffv v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n  rv(0).val_.d_ = 1.0;\n  rv(1).val_.d_ = 2.0;\n  rv(2).val_.d_ = 3.0;\n  v(0).val_.d_ = 4.0;\n  v(1).val_.d_ = 5.0;\n  v(2).val_.d_ = 6.0;\n\n  stan::math::fvar<fvar<var> > a = stan::math::squared_distance(rv, v);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(rv(0).val_.val_);\n  vars.push_back(rv(1).val_.val_);\n  vars.push_back(rv(2).val_.val_);\n  vars.push_back(v(0).val_.val_);\n  vars.push_back(v(1).val_.val_);\n  vars.push_back(v(2).val_.val_);\n\n  a.val_.d_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(-6, grads[1]);\n  EXPECT_FLOAT_EQ(-6, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(6, grads[4]);\n  EXPECT_FLOAT_EQ(6, grads[5]);\n}\nTEST(AgradMixMatrixSquaredDistance, rowvector_fv_vector_ffv3) {\n  stan::math::row_vector_ffv rv;\n  stan::math::vector_ffv v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n  rv(0).val_.d_ = 1.0;\n  rv(1).val_.d_ = 2.0;\n  rv(2).val_.d_ = 3.0;\n  v(0).val_.d_ = 4.0;\n  v(1).val_.d_ = 5.0;\n  v(2).val_.d_ = 6.0;\n\n  stan::math::fvar<fvar<var> > a = stan::math::squared_distance(rv, v);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(rv(0).val_.val_);\n  vars.push_back(rv(1).val_.val_);\n  vars.push_back(rv(2).val_.val_);\n  vars.push_back(v(0).val_.val_);\n  vars.push_back(v(1).val_.val_);\n  vars.push_back(v(2).val_.val_);\n\n  a.d_.val_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(-6, grads[1]);\n  EXPECT_FLOAT_EQ(-6, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(6, grads[4]);\n  EXPECT_FLOAT_EQ(6, grads[5]);\n}\nTEST(AgradMixMatrixSquaredDistance, rowvector_fv_vector_ffv4) {\n  stan::math::row_vector_ffv rv;\n  stan::math::vector_ffv v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n  rv(0).val_.d_ = 1.0;\n  rv(1).val_.d_ = 2.0;\n  rv(2).val_.d_ = 3.0;\n  v(0).val_.d_ = 4.0;\n  v(1).val_.d_ = 5.0;\n  v(2).val_.d_ = 6.0;\n\n  stan::math::fvar<fvar<var> > a = stan::math::squared_distance(rv, v);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(rv(0).val_.val_);\n  vars.push_back(rv(1).val_.val_);\n  vars.push_back(rv(2).val_.val_);\n  vars.push_back(v(0).val_.val_);\n  vars.push_back(v(1).val_.val_);\n  vars.push_back(v(2).val_.val_);\n\n  a.d_.d_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(0, grads[0]);\n  EXPECT_FLOAT_EQ(-0, grads[1]);\n  EXPECT_FLOAT_EQ(0, grads[2]);\n  EXPECT_FLOAT_EQ(-0, grads[3]);\n  EXPECT_FLOAT_EQ(0, grads[4]);\n  EXPECT_FLOAT_EQ(-0, grads[5]);\n}\n\nTEST(AgradMixMatrixSquaredDistance, vector_fv_rowvector_ffv1) {\n  stan::math::row_vector_ffv rv;\n  stan::math::vector_ffv v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n\n  stan::math::fvar<fvar<var> > a = stan::math::squared_distance(v, rv);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(rv(0).val_.val_);\n  vars.push_back(rv(1).val_.val_);\n  vars.push_back(rv(2).val_.val_);\n  vars.push_back(v(0).val_.val_);\n  vars.push_back(v(1).val_.val_);\n  vars.push_back(v(2).val_.val_);\n\n  a.val_.val_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(10, grads[1]);\n  EXPECT_FLOAT_EQ(-8, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(-10, grads[4]);\n  EXPECT_FLOAT_EQ(8, grads[5]);\n\n  v.resize(0);\n  rv.resize(0);\n  EXPECT_FLOAT_EQ(0, stan::math::squared_distance(v, rv).val_.val_.val());\n\n  v.resize(1);\n  rv.resize(2);\n  v << 1;\n  rv << 2, 3;\n  EXPECT_THROW(stan::math::squared_distance(v, rv), std::invalid_argument);\n}\n\nTEST(AgradMixMatrixSquaredDistance, vector_fv_rowvector_ffv2) {\n  stan::math::row_vector_ffv rv;\n  stan::math::vector_ffv v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n  rv(0).val_.d_ = 1.0;\n  rv(1).val_.d_ = 2.0;\n  rv(2).val_.d_ = 3.0;\n  v(0).val_.d_ = 4.0;\n  v(1).val_.d_ = 5.0;\n  v(2).val_.d_ = 6.0;\n\n  stan::math::fvar<fvar<var> > a = stan::math::squared_distance(v, rv);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(rv(0).val_.val_);\n  vars.push_back(rv(1).val_.val_);\n  vars.push_back(rv(2).val_.val_);\n  vars.push_back(v(0).val_.val_);\n  vars.push_back(v(1).val_.val_);\n  vars.push_back(v(2).val_.val_);\n\n  a.d_.val_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(-6, grads[1]);\n  EXPECT_FLOAT_EQ(-6, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(6, grads[4]);\n  EXPECT_FLOAT_EQ(6, grads[5]);\n}\nTEST(AgradMixMatrixSquaredDistance, vector_fv_rowvector_ffv3) {\n  stan::math::row_vector_ffv rv;\n  stan::math::vector_ffv v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n  rv(0).val_.d_ = 1.0;\n  rv(1).val_.d_ = 2.0;\n  rv(2).val_.d_ = 3.0;\n  v(0).val_.d_ = 4.0;\n  v(1).val_.d_ = 5.0;\n  v(2).val_.d_ = 6.0;\n\n  stan::math::fvar<fvar<var> > a = stan::math::squared_distance(v, rv);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(rv(0).val_.val_);\n  vars.push_back(rv(1).val_.val_);\n  vars.push_back(rv(2).val_.val_);\n  vars.push_back(v(0).val_.val_);\n  vars.push_back(v(1).val_.val_);\n  vars.push_back(v(2).val_.val_);\n\n  a.val_.d_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(-6, grads[0]);\n  EXPECT_FLOAT_EQ(-6, grads[1]);\n  EXPECT_FLOAT_EQ(-6, grads[2]);\n  EXPECT_FLOAT_EQ(6, grads[3]);\n  EXPECT_FLOAT_EQ(6, grads[4]);\n  EXPECT_FLOAT_EQ(6, grads[5]);\n}\nTEST(AgradMixMatrixSquaredDistance, vector_fv_rowvector_ffv4) {\n  stan::math::row_vector_ffv rv;\n  stan::math::vector_ffv v;\n\n  rv.resize(3);\n  v.resize(3);\n  rv << 1, 3, -5;\n  v << 4, -2, -1;\n  rv(0).d_ = 1.0;\n  rv(1).d_ = 2.0;\n  rv(2).d_ = 3.0;\n  v(0).d_ = 4.0;\n  v(1).d_ = 5.0;\n  v(2).d_ = 6.0;\n  rv(0).val_.d_ = 1.0;\n  rv(1).val_.d_ = 2.0;\n  rv(2).val_.d_ = 3.0;\n  v(0).val_.d_ = 4.0;\n  v(1).val_.d_ = 5.0;\n  v(2).val_.d_ = 6.0;\n\n  stan::math::fvar<fvar<var> > a = stan::math::squared_distance(v, rv);\n\n  EXPECT_FLOAT_EQ(50, a.val_.val_.val());\n  EXPECT_FLOAT_EQ(12, a.d_.val_.val());\n\n  std::vector<double> grads;\n  std::vector<var> vars;\n  vars.push_back(rv(0).val_.val_);\n  vars.push_back(rv(1).val_.val_);\n  vars.push_back(rv(2).val_.val_);\n  vars.push_back(v(0).val_.val_);\n  vars.push_back(v(1).val_.val_);\n  vars.push_back(v(2).val_.val_);\n\n  a.d_.d_.grad(vars, grads);\n  EXPECT_FLOAT_EQ(0, grads[0]);\n  EXPECT_FLOAT_EQ(-0, grads[1]);\n  EXPECT_FLOAT_EQ(0, grads[2]);\n  EXPECT_FLOAT_EQ(-0, grads[3]);\n  EXPECT_FLOAT_EQ(0, grads[4]);\n  EXPECT_FLOAT_EQ(-0, grads[5]);\n}\nTEST(AgradMixMatrixSquaredDistance, special_values_ffv) {\n  stan::math::vector_ffv v1, v2;\n  v1.resize(1);\n  v2.resize(1);\n\n  v1 << 0;\n  v2 << std::numeric_limits<double>::quiet_NaN();\n  EXPECT_TRUE(stan::math::is_nan(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(stan::math::is_nan(stan::math::squared_distance(v2, v1)));\n\n  v1 << 0;\n  v2 << std::numeric_limits<double>::infinity();\n  EXPECT_TRUE(stan::math::is_inf(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(stan::math::is_inf(stan::math::squared_distance(v2, v1)));\n\n  v1 << std::numeric_limits<double>::infinity();\n  v2 << std::numeric_limits<double>::infinity();\n  EXPECT_TRUE(stan::math::is_nan(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(stan::math::is_nan(stan::math::squared_distance(v2, v1)));\n\n  v1 << -std::numeric_limits<double>::infinity();\n  v2 << std::numeric_limits<double>::infinity();\n  EXPECT_TRUE(stan::math::is_inf(stan::math::squared_distance(v1, v2)));\n  EXPECT_TRUE(stan::math::is_inf(stan::math::squared_distance(v2, v1)));\n}\n", "meta": {"hexsha": "7302322b318bb3e5585f057bdc013afa5dae207d", "size": 21492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/mix/mat/fun/squared_distance_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/mix/mat/fun/squared_distance_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/mix/mat/fun/squared_distance_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3742621015, "max_line_length": 76, "alphanum_fraction": 0.6276288852, "num_tokens": 8704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.557223669514265}}
{"text": "\n#include \"remainder.hpp\"\n#include \"ast.hpp\"\n#include \"parsers.hpp\"\n#include \"types.hpp\"\n#include \"utility/itoa.hpp\"\n#include <boost/variant.hpp>\n#include <cmath>\n#include <stdexcept>\n#include <algorithm>\nnamespace HT\n{\n    void remainder(PASTNode astnode, ParsersHelper& ph)\n    {\n        auto myParserHelper(ph);\n        if (astnode->ch.size()!=3)\n          throw std::runtime_error(\"Remainder should have exact 2 parameters\");\n        auto & thirdCh = *astnode->ch.rbegin();\n        auto & secondCh = *(++astnode->ch.begin());\n        ph.parse(secondCh);\n        ph.parse(thirdCh);\n        if (secondCh->token.tokenType!=Complex || !boost::get<ComplexType>(secondCh->token.info).isInt())\n          throw std::runtime_error(\"The arguments of Remainder should be integer\");\n        \n        if (thirdCh->token.tokenType!=Complex || !boost::get<ComplexType>(thirdCh->token.info).isInt())\n          throw std::runtime_error(\"The arguments of Remainder should be integer\");\n\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        auto cast =boost::get<ComplexType>(secondCh->token.info);\n\n        if (cast.toInt().isZero()) astnode->token.info = ComplexType(0);\n        else\n        {\n            astnode->token.info = ComplexType(cast.toInt()  \\\n                        % \n                        boost::get<ComplexType>(thirdCh->token.info).toInt()) ;\n            if (!cast.exact() || !boost::get<ComplexType>(thirdCh->token.info).exact())\n              astnode->token.info = boost::get<ComplexType>(astnode->token.info).toinexact();\n\n            astnode->token.info = ComplexType( boost::get<ComplexType>(astnode->token.info).toInt().setSign(\n                            boost::get<ComplexType>(secondCh->token.info).toInt().getSign()));\n\n        }\n        astnode->remove();\n    }\n}\n\n\n", "meta": {"hexsha": "94e4a682a248cae1ccd2bb986ab17dff267df6d2", "size": 1816, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "funs/remainder.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/remainder.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/remainder.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.32, "max_line_length": 108, "alphanum_fraction": 0.6046255507, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5571807762769204}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation, \n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file    testGaussianISAM.cpp\n * @brief   Unit tests for GaussianISAM\n * @author  Michael Kaess\n */\n\n#include <tests/smallExample.h>\n#include <gtsam/nonlinear/Ordering.h>\n#include <gtsam/nonlinear/Symbol.h>\n#include <gtsam/linear/GaussianBayesNet.h>\n#include <gtsam/linear/GaussianISAM.h>\n#include <gtsam/linear/GaussianSequentialSolver.h>\n#include <gtsam/linear/GaussianMultifrontalSolver.h>\n#include <gtsam/inference/ISAM.h>\n#include <gtsam/geometry/Rot2.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/foreach.hpp>\n#include <boost/assign/std/list.hpp> // for operator +=\nusing namespace boost::assign;\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace example;\n\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\n/* ************************************************************************* */\n// Some numbers that should be consistent among all smoother tests\n\nstatic double sigmax1 = 0.786153, sigmax2 = 1.0/1.47292, sigmax3 = 0.671512, sigmax4 =\n\t\t0.669534 /*, sigmax5 = sigmax3, sigmax6 = sigmax2*/, sigmax7 = sigmax1;\n\nstatic const double tol = 1e-4;\n\n/* ************************************************************************* */\nTEST( ISAM, iSAM_smoother )\n{\n  Ordering ordering;\n  for (int t = 1; t <= 7; t++) ordering += X(t);\n\n  // Create smoother with 7 nodes\n\tGaussianFactorGraph smoother = createSmoother(7, ordering).first;\n\n\t// run iSAM for every factor\n\tGaussianISAM actual;\n\tBOOST_FOREACH(boost::shared_ptr<GaussianFactor> factor, smoother) {\n\t\tGaussianFactorGraph factorGraph;\n\t\tfactorGraph.push_back(factor);\n\t\tactual.update(factorGraph);\n\t}\n\n\tBayesTree<GaussianConditional>::shared_ptr bayesTree = GaussianMultifrontalSolver(smoother).eliminate();\n\t// Create expected Bayes Tree by solving smoother with \"natural\" ordering\n\tGaussianISAM expected(*bayesTree);\n\n\t// Check whether BayesTree is correct\n\tEXPECT(assert_equal(expected, actual));\n\n\t// obtain solution\n\tVectorValues e(VectorValues::Zero(7,2)); // expected solution\n\tVectorValues optimized = optimize(actual); // actual solution\n\tEXPECT(assert_equal(e, optimized));\n}\n\n/* ************************************************************************* *\n Bayes tree for smoother with \"natural\" ordering:\nC1 x6 x7\nC2   x5 : x6\nC3     x4 : x5\nC4       x3 : x4\nC5         x2 : x3\nC6           x1 : x2\n**************************************************************************** */\nTEST_UNSAFE( BayesTree, linear_smoother_shortcuts )\n{\n\t// Create smoother with 7 nodes\n  Ordering ordering;\n\tGaussianFactorGraph smoother;\n\tboost::tie(smoother, ordering) = createSmoother(7);\n\n\tBayesTree<GaussianConditional> bayesTree = *GaussianMultifrontalSolver(smoother).eliminate();\n\n\t// Create the Bayes tree\n\tGaussianISAM isamTree(bayesTree);\n\tLONGS_EQUAL(6,isamTree.size());\n\n\t// Check the conditional P(Root|Root)\n\tGaussianBayesNet empty;\n\tGaussianISAM::sharedClique R = isamTree.root();\n\tGaussianBayesNet actual1 = GaussianISAM::shortcut(R,R);\n\tEXPECT(assert_equal(empty,actual1,tol));\n\n\t// Check the conditional P(C2|Root)\n\tGaussianISAM::sharedClique C2 = isamTree[ordering[X(5)]];\n\tGaussianBayesNet actual2 = GaussianISAM::shortcut(C2,R);\n\tEXPECT(assert_equal(empty,actual2,tol));\n\n\t// Check the conditional P(C3|Root)\n\tdouble sigma3 = 0.61808;\n\tMatrix A56 = Matrix_(2,2,-0.382022,0.,0.,-0.382022);\n\tGaussianBayesNet expected3;\n\tpush_front(expected3,ordering[X(5)], zero(2), eye(2)/sigma3, ordering[X(6)], A56/sigma3, ones(2));\n\tGaussianISAM::sharedClique C3 = isamTree[ordering[X(4)]];\n\tGaussianBayesNet actual3 = GaussianISAM::shortcut(C3,R);\n\tEXPECT(assert_equal(expected3,actual3,tol));\n\n\t// Check the conditional P(C4|Root)\n\tdouble sigma4 = 0.661968;\n\tMatrix A46 = Matrix_(2,2,-0.146067,0.,0.,-0.146067);\n\tGaussianBayesNet expected4;\n\tpush_front(expected4, ordering[X(4)], zero(2), eye(2)/sigma4, ordering[X(6)], A46/sigma4, ones(2));\n\tGaussianISAM::sharedClique C4 = isamTree[ordering[X(3)]];\n\tGaussianBayesNet actual4 = GaussianISAM::shortcut(C4,R);\n\tEXPECT(assert_equal(expected4,actual4,tol));\n}\n\n/* ************************************************************************* *\n Bayes tree for smoother with \"nested dissection\" ordering:\n\n\t Node[x1] P(x1 | x2)\n\t Node[x3] P(x3 | x2 x4)\n\t Node[x5] P(x5 | x4 x6)\n\t Node[x7] P(x7 | x6)\n\t Node[x2] P(x2 | x4)\n\t Node[x6] P(x6 | x4)\n\t Node[x4] P(x4)\n\n becomes\n\n\t C1\t\t x5 x6 x4\n\t C2\t\t  x3 x2 : x4\n\t C3\t\t    x1 : x2\n\t C4\t\t  x7 : x6\n\n************************************************************************* */\nTEST_UNSAFE( BayesTree, balanced_smoother_marginals )\n{\n  // Create smoother with 7 nodes\n  Ordering ordering;\n  ordering += X(1),X(3),X(5),X(7),X(2),X(6),X(4);\n  GaussianFactorGraph smoother = createSmoother(7, ordering).first;\n\n  // Create the Bayes tree\n  BayesTree<GaussianConditional> chordalBayesNet = *GaussianMultifrontalSolver(smoother).eliminate();\n\n\tVectorValues expectedSolution(VectorValues::Zero(7,2));\n\tVectorValues actualSolution = optimize(chordalBayesNet);\n\tEXPECT(assert_equal(expectedSolution,actualSolution,tol));\n\n\t// Create the Bayes tree\n\tGaussianISAM bayesTree(chordalBayesNet);\n\tLONGS_EQUAL(4,bayesTree.size());\n\n\tdouble tol=1e-5;\n\n\t// Check marginal on x1\n\tGaussianBayesNet expected1 = simpleGaussian(ordering[X(1)], zero(2), sigmax1);\n\tGaussianBayesNet actual1 = *bayesTree.marginalBayesNet(ordering[X(1)]);\n\tMatrix expectedCovarianceX1 = eye(2,2) * (sigmax1 * sigmax1);\n\tMatrix actualCovarianceX1;\n\tactualCovarianceX1 = bayesTree.marginalCovariance(ordering[X(1)]);\n\tEXPECT(assert_equal(expectedCovarianceX1, actualCovarianceX1, tol));\n\tEXPECT(assert_equal(expected1,actual1,tol));\n\n\t// Check marginal on x2\n\tdouble sigx2 = 0.68712938; // FIXME: this should be corrected analytically\n\tGaussianBayesNet expected2 = simpleGaussian(ordering[X(2)], zero(2), sigx2);\n\tGaussianBayesNet actual2 = *bayesTree.marginalBayesNet(ordering[X(2)]);\n\tMatrix expectedCovarianceX2 = eye(2,2) * (sigx2 * sigx2);\n\tMatrix actualCovarianceX2;\n\tactualCovarianceX2 = bayesTree.marginalCovariance(ordering[X(2)]);\n\tEXPECT(assert_equal(expectedCovarianceX2, actualCovarianceX2, tol));\n\tEXPECT(assert_equal(expected2,actual2,tol));\n\n\t// Check marginal on x3\n\tGaussianBayesNet expected3 = simpleGaussian(ordering[X(3)], zero(2), sigmax3);\n\tGaussianBayesNet actual3 = *bayesTree.marginalBayesNet(ordering[X(3)]);\n\tMatrix expectedCovarianceX3 = eye(2,2) * (sigmax3 * sigmax3);\n\tMatrix actualCovarianceX3;\n\tactualCovarianceX3 = bayesTree.marginalCovariance(ordering[X(3)]);\n\tEXPECT(assert_equal(expectedCovarianceX3, actualCovarianceX3, tol));\n\tEXPECT(assert_equal(expected3,actual3,tol));\n\n\t// Check marginal on x4\n\tGaussianBayesNet expected4 = simpleGaussian(ordering[X(4)], zero(2), sigmax4);\n\tGaussianBayesNet actual4 = *bayesTree.marginalBayesNet(ordering[X(4)]);\n\tMatrix expectedCovarianceX4 = eye(2,2) * (sigmax4 * sigmax4);\n\tMatrix actualCovarianceX4;\n\tactualCovarianceX4 = bayesTree.marginalCovariance(ordering[X(4)]);\n\tEXPECT(assert_equal(expectedCovarianceX4, actualCovarianceX4, tol));\n\tEXPECT(assert_equal(expected4,actual4,tol));\n\n\t// Check marginal on x7 (should be equal to x1)\n\tGaussianBayesNet expected7 = simpleGaussian(ordering[X(7)], zero(2), sigmax7);\n\tGaussianBayesNet actual7 = *bayesTree.marginalBayesNet(ordering[X(7)]);\n\tMatrix expectedCovarianceX7 = eye(2,2) * (sigmax7 * sigmax7);\n\tMatrix actualCovarianceX7;\n\tactualCovarianceX7 = bayesTree.marginalCovariance(ordering[X(7)]);\n\tEXPECT(assert_equal(expectedCovarianceX7, actualCovarianceX7, tol));\n\tEXPECT(assert_equal(expected7,actual7,tol));\n}\n\n/* ************************************************************************* */\nTEST_UNSAFE( BayesTree, balanced_smoother_shortcuts )\n{\n\t// Create smoother with 7 nodes\n  Ordering ordering;\n  ordering += X(1),X(3),X(5),X(7),X(2),X(6),X(4);\n\tGaussianFactorGraph smoother = createSmoother(7, ordering).first;\n\n\t// Create the Bayes tree\n\tBayesTree<GaussianConditional> bayesTree = *GaussianMultifrontalSolver(smoother).eliminate();\n\tGaussianISAM isamTree(bayesTree);\n\n\t// Check the conditional P(Root|Root)\n\tGaussianBayesNet empty;\n\tGaussianISAM::sharedClique R = isamTree.root();\n\tGaussianBayesNet actual1 = GaussianISAM::shortcut(R,R);\n\tEXPECT(assert_equal(empty,actual1,tol));\n\n\t// Check the conditional P(C2|Root)\n\tGaussianISAM::sharedClique C2 = isamTree[ordering[X(3)]];\n\tGaussianBayesNet actual2 = GaussianISAM::shortcut(C2,R);\n\tEXPECT(assert_equal(empty,actual2,tol));\n\n\t// Check the conditional P(C3|Root), which should be equal to P(x2|x4)\n\t/** TODO: Note for multifrontal conditional:\n\t * p_x2_x4 is now an element conditional of the multifrontal conditional bayesTree[ordering[X(2)]]->conditional()\n\t * We don't know yet how to take it out.\n\t */\n//\tGaussianConditional::shared_ptr p_x2_x4 = bayesTree[ordering[X(2)]]->conditional();\n//\tp_x2_x4->print(\"Conditional p_x2_x4: \");\n//\tGaussianBayesNet expected3(p_x2_x4);\n//\tGaussianISAM::sharedClique C3 = isamTree[ordering[X(1)]];\n//\tGaussianBayesNet actual3 = GaussianISAM::shortcut(C3,R);\n//\tEXPECT(assert_equal(expected3,actual3,tol));\n}\n\n///* ************************************************************************* */\n//TEST( BayesTree, balanced_smoother_clique_marginals )\n//{\n//  // Create smoother with 7 nodes\n//  Ordering ordering;\n//  ordering += X(1),X(3),X(5),X(7),X(2),X(6),X(4);\n//  GaussianFactorGraph smoother = createSmoother(7, ordering).first;\n//\n//  // Create the Bayes tree\n//  GaussianBayesNet chordalBayesNet = *GaussianSequentialSolver(smoother).eliminate();\n//  GaussianISAM bayesTree(chordalBayesNet);\n//\n//\t// Check the clique marginal P(C3)\n//\tdouble sigmax2_alt = 1/1.45533; // THIS NEEDS TO BE CHECKED!\n//\tGaussianBayesNet expected = simpleGaussian(ordering[X(2)],zero(2),sigmax2_alt);\n//\tpush_front(expected,ordering[X(1)], zero(2), eye(2)*sqrt(2), ordering[X(2)], -eye(2)*sqrt(2)/2, ones(2));\n//\tGaussianISAM::sharedClique R = bayesTree.root(), C3 = bayesTree[ordering[X(1)]];\n//\tGaussianFactorGraph marginal = C3->marginal(R);\n//\tGaussianVariableIndex varIndex(marginal);\n//\tPermutation toFront(Permutation::PullToFront(C3->keys(), varIndex.size()));\n//\tPermutation toFrontInverse(*toFront.inverse());\n//\tvarIndex.permute(toFront);\n//\tBOOST_FOREACH(const GaussianFactor::shared_ptr& factor, marginal) {\n//\t  factor->permuteWithInverse(toFrontInverse); }\n//\tGaussianBayesNet actual = *inference::EliminateUntil(marginal, C3->keys().size(), varIndex);\n//\tactual.permuteWithInverse(toFront);\n//\tEXPECT(assert_equal(expected,actual,tol));\n//}\n\n/* ************************************************************************* */\nTEST_UNSAFE( BayesTree, balanced_smoother_joint )\n{\n\t// Create smoother with 7 nodes\n\tOrdering ordering;\n\tordering += X(1),X(3),X(5),X(7),X(2),X(6),X(4);\n\tGaussianFactorGraph smoother = createSmoother(7, ordering).first;\n\n\t// Create the Bayes tree, expected to look like:\n\t//\t x5 x6 x4\n\t//\t   x3 x2 : x4\n\t//\t     x1 : x2\n\t//\t   x7 : x6\n\tBayesTree<GaussianConditional> chordalBayesNet = *GaussianMultifrontalSolver(smoother).eliminate();\n\tGaussianISAM bayesTree(chordalBayesNet);\n\n\t// Conditional density elements reused by both tests\n\tconst Vector sigma = ones(2);\n\tconst Matrix I = eye(2), A = -0.00429185*I;\n\n\t// Check the joint density P(x1,x7) factored as P(x1|x7)P(x7)\n\tGaussianBayesNet expected1;\n\t// Why does the sign get flipped on the prior?\n\tGaussianConditional::shared_ptr\n\t\tparent1(new GaussianConditional(ordering[X(7)], zero(2), -1*I/sigmax7, ones(2)));\n\texpected1.push_front(parent1);\n\tpush_front(expected1,ordering[X(1)], zero(2), I/sigmax7, ordering[X(7)], A/sigmax7, sigma);\n\tGaussianBayesNet actual1 = *bayesTree.jointBayesNet(ordering[X(1)],ordering[X(7)]);\n\tEXPECT(assert_equal(expected1,actual1,tol));\n\n//\t// Check the joint density P(x7,x1) factored as P(x7|x1)P(x1)\n//\tGaussianBayesNet expected2;\n//\tGaussianConditional::shared_ptr\n//\t\t\tparent2(new GaussianConditional(ordering[X(1)], zero(2), -1*I/sigmax1, ones(2)));\n//\t\texpected2.push_front(parent2);\n//\tpush_front(expected2,ordering[X(7)], zero(2), I/sigmax1, ordering[X(1)], A/sigmax1, sigma);\n//\tGaussianBayesNet actual2 = *bayesTree.jointBayesNet(ordering[X(7)],ordering[X(1)]);\n//\tEXPECT(assert_equal(expected2,actual2,tol));\n\n\t// Check the joint density P(x1,x4), i.e. with a root variable\n\tGaussianBayesNet expected3;\n\tGaussianConditional::shared_ptr\n\t\t\tparent3(new GaussianConditional(ordering[X(4)], zero(2), I/sigmax4, ones(2)));\n\t\texpected3.push_front(parent3);\n\tdouble sig14 = 0.784465;\n\tMatrix A14 = -0.0769231*I;\n\tpush_front(expected3,ordering[X(1)], zero(2), I/sig14, ordering[X(4)], A14/sig14, sigma);\n\tGaussianBayesNet actual3 = *bayesTree.jointBayesNet(ordering[X(1)],ordering[X(4)]);\n\tEXPECT(assert_equal(expected3,actual3,tol));\n\n//\t// Check the joint density P(x4,x1), i.e. with a root variable, factored the other way\n//\tGaussianBayesNet expected4;\n//\tGaussianConditional::shared_ptr\n//\t\t\tparent4(new GaussianConditional(ordering[X(1)], zero(2), -1.0*I/sigmax1, ones(2)));\n//\t\texpected4.push_front(parent4);\n//\tdouble sig41 = 0.668096;\n//\tMatrix A41 = -0.055794*I;\n//\tpush_front(expected4,ordering[X(4)], zero(2), I/sig41, ordering[X(1)], A41/sig41, sigma);\n//\tGaussianBayesNet actual4 = *bayesTree.jointBayesNet(ordering[X(4)],ordering[X(1)]);\n//\tEXPECT(assert_equal(expected4,actual4,tol));\n}\n\n/* ************************************************************************* */\nTEST_UNSAFE(BayesTree, simpleMarginal)\n{\n  GaussianFactorGraph gfg;\n\n  Matrix A12 = Rot2::fromDegrees(45.0).matrix();\n\n  gfg.add(0, eye(2), zero(2), noiseModel::Isotropic::Sigma(2, 1.0));\n  gfg.add(0, -eye(2), 1, eye(2), ones(2), noiseModel::Isotropic::Sigma(2, 1.0));\n  gfg.add(1, -eye(2), 2, A12, ones(2), noiseModel::Isotropic::Sigma(2, 1.0));\n\n  Matrix expected(GaussianSequentialSolver(gfg).marginalCovariance(2));\n  Matrix actual(GaussianMultifrontalSolver(gfg).marginalCovariance(2));\n\n  EXPECT(assert_equal(expected, actual));\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "74417b57af1bd471f22a3dc686d1763255756792", "size": 14427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testGaussianISAM.cpp", "max_stars_repo_name": "sdmiller/gtsam_pcl", "max_stars_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T07:02:44.000Z", "max_issues_repo_path": "tests/testGaussianISAM.cpp", "max_issues_repo_name": "sdmiller/gtsam_pcl", "max_issues_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/testGaussianISAM.cpp", "max_forks_repo_name": "sdmiller/gtsam_pcl", "max_forks_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T12:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:02:48.000Z", "avg_line_length": 39.6346153846, "max_line_length": 114, "alphanum_fraction": 0.6818465377, "num_tokens": 4199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5571807724139289}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <stdexcept>\n#include <cmath>\n\nTEST(MathFunctions, expm1) {\n  using stan::math::expm1;\n  using std::exp;\n  EXPECT_FLOAT_EQ(exp(-14.2) - 1, expm1(-14.2));\n  EXPECT_FLOAT_EQ(exp(0) - 1, expm1(0));\n  EXPECT_FLOAT_EQ(exp(172.987) - 1, expm1(172.987));\n  EXPECT_FLOAT_EQ(-1, expm1(-std::numeric_limits<double>::infinity()));\n}\n\nTEST(MathFunctions, expm1_inf_return) {\n  EXPECT_EQ(std::numeric_limits<double>::infinity(),\n            stan::math::expm1(std::numeric_limits<double>::infinity()));\n}\n\nTEST(MathFunctions, expm1_nan) {\n  using stan::math::expm1;\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::expm1(std::numeric_limits<double>::quiet_NaN()));\n}\n", "meta": {"hexsha": "c1bbcadc7165dec61bfe99fd645e9d15e00bf089", "size": 815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/expm1_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/prim/scal/fun/expm1_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/prim/scal/fun/expm1_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1851851852, "max_line_length": 76, "alphanum_fraction": 0.6920245399, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5571807713373484}}
{"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": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/test/included/test_exec_monitor.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/tools/stats.hpp>\n#include <boost/math/tools/test.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/array.hpp>\n#include \"functor.hpp\"\n\n#include \"test_gamma_hooks.hpp\"\n#include \"handle_test_result.hpp\"\n\n//\n// DESCRIPTION:\n// ~~~~~~~~~~~~\n//\n// This file tests the functions tgamma and lgamma, and the \n// function tgamma1pm1.  There are two sets of tests, spot\n// tests which compare our results with selected values computed\n// using the online special function calculator at \n// functions.wolfram.com, while the bulk of the accuracy tests\n// use values generated with NTL::RR at 1000-bit precision\n// and our generic versions of these functions.\n//\n// Note that when this file is first run on a new platform many of\n// these tests will fail: the default accuracy is 1 epsilon which\n// is too tight for most platforms.  In this situation you will \n// need to cast a human eye over the error rates reported and make\n// a judgement as to whether they are acceptable.  Either way please\n// report the results to the Boost mailing list.  Acceptable rates of\n// error are marked up below as a series of regular expressions that\n// identify the compiler/stdlib/platform/data-type/test-data/test-function\n// along with the maximum expected peek and RMS mean errors for that\n// test.\n//\n\nvoid expected_results()\n{\n   //\n   // Define the max and mean errors expected for\n   // various compilers and platforms.\n   //\n   const char* largest_type;\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())\n   {\n      largest_type = \"(long\\\\s+)?double\";\n   }\n   else\n   {\n      largest_type = \"long double\";\n   }\n#else\n   largest_type = \"(long\\\\s+)?double\";\n#endif\n   //\n   // G++ on Darwin: results are just slightly worse than we might hope for\n   // but still pretty good:\n   //\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"Mac OS\",                      // platform\n      largest_type,                  // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::tgamma\", 100, 15); // test function\n\n   //\n   // G++ on Linux, result vary a bit by processor type,\n   // on Itanium results are *much* better than listed here,\n   // but x86 appears to have much less accurate std::pow\n   // that throws off the results:\n   //\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"linux\",                       // platform\n      largest_type,                  // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::tgamma\", 400, 200); // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"linux\",                          // platform\n      largest_type,                  // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::lgamma\", 30, 10);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"linux\",                       // platform\n      largest_type,                  // test type(s)\n      \"near (1|2|-10)\",              // test data group\n      \"boost::math::tgamma\", 10, 5);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"linux\",                       // platform\n      largest_type,                  // test type(s)\n      \"near (1|2|-10)\",              // test data group\n      \"boost::math::lgamma\", 50, 50);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"linux\",                       // platform\n      largest_type,                  // test type(s)\n      \"tgamma1pm1.*\",                // test data group\n      \"boost::math::tgamma1pm1\", 50, 15);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"linux\",                       // platform\n      \"real_concept\",                // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::tgamma\", 220, 70);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"linux\",                       // platform\n      \"real_concept\",                // test type(s)\n      \"near (0|-55)\",                // test data group\n      \"boost::math::(t|l)gamma\", 130, 80);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"linux\",                       // platform\n      \"real_concept\",                // test type(s)\n      \"tgamma1pm1.*\",                // test data group\n      \"boost::math::tgamma1pm1\", 40, 10);  // test function\n   //\n   // HP-UX results:\n   //\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"HP-UX\",                          // platform\n      largest_type,                  // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::tgamma\", 5, 4);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"HP-UX\",                       // platform\n      largest_type,                  // test type(s)\n      \"near (0|-55)\",                // test data group\n      \"boost::math::tgamma\", 10, 5);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"HP-UX\",                       // platform\n      largest_type,                  // test type(s)\n      \"near (1|2|-10)\",              // test data group\n      \"boost::math::lgamma\", 250, 200);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"HP-UX\",                          // platform\n      \"real_concept\",                // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::lgamma\", 50, 20);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"HP-UX\",                          // platform\n      \"real_concept\",                // test type(s)\n      \"tgamma1pm1.*\",                // test data group\n      \"boost::math::tgamma1pm1\", 200, 80);  // test function\n   //\n   // Tru64:\n   //\n   add_expected_result(\n      \".*Tru64.*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"real_concept\",                // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::lgamma\", 50, 20);  // test function\n   //\n   // Sun OS:\n   //\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"Sun.*\",                       // platform\n      largest_type,                  // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::tgamma\", 300, 50); // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \"Sun.*\",                       // platform\n      \"real_concept\",                // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::tgamma\", 300, 50); // test function\n\n   //\n   // Catch all cases come last:\n   //\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      largest_type,                  // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::tgamma\", 4, 1);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      largest_type,                  // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::lgamma\", 9, 1);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      largest_type,                  // test type(s)\n      \"near (0|-55)\",                // test data group\n      \"boost::math::(t|l)gamma\", 200, 100);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      largest_type,                  // test type(s)\n      \"near (1|2|-10)\",              // test data group\n      \"boost::math::tgamma\", 10, 5);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      largest_type,                  // test type(s)\n      \"near (1|2|-10)\",              // test data group\n      \"boost::math::lgamma\", 14, 7);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      largest_type,                  // test type(s)\n      \"tgamma1pm1.*\",                // test data group\n      \"boost::math::tgamma1pm1\", 30, 9);  // test function\n\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"real_concept\",                // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::tgamma\", 70, 25);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"real_concept\",                // test type(s)\n      \"factorials\",                  // test data group\n      \"boost::math::lgamma\", 40, 4);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"real_concept\",                // test type(s)\n      \"near.*\",                      // test data group\n      \"boost::math::tgamma\", 80, 60);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"real_concept\",                // test type(s)\n      \"near.*\",                      // test data group\n      \"boost::math::lgamma\", 10000000, 10000000);  // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"real_concept\",                // test type(s)\n      \"tgamma1pm1.*\",                // test data group\n      \"boost::math::tgamma1pm1\", 20, 5);  // test function\n\n   //\n   // Finish off by printing out the compiler/stdlib/platform names,\n   // we do this to make it easier to mark up expected error rates.\n   //\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \" \n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\n}\n\ntemplate <class T>\nvoid do_test_gamma(const T& data, const char* type_name, const char* test_name)\n{\n   typedef typename T::value_type row_type;\n   typedef typename row_type::value_type value_type;\n\n   typedef value_type (*pg)(value_type);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::tgamma<value_type>;\n#else\n   pg funcp = boost::math::tgamma;\n#endif\n\n   boost::math::tools::test_result<value_type> result;\n\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n\n   //\n   // test tgamma against data:\n   //\n   result = boost::math::tools::test(\n      data,\n      bind_func(funcp, 0),\n      extract_result(1));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::tgamma\", test_name);\n#ifdef TEST_OTHER\n   if(::boost::is_floating_point<value_type>::value){\n      funcp = other::tgamma;\n      result = boost::math::tools::test(\n         data,\n         bind_func(funcp, 0),\n         extract_result(1));\n      print_test_result(result, data[result.worst()], result.worst(), type_name, \"other::tgamma\");\n   }\n#endif\n   //\n   // test lgamma against data:\n   //\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   funcp = boost::math::lgamma<value_type>;\n#else\n   funcp = boost::math::lgamma;\n#endif\n   result = boost::math::tools::test(\n      data,\n      bind_func(funcp, 0),\n      extract_result(2));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::lgamma\", test_name);\n#ifdef TEST_OTHER\n   if(::boost::is_floating_point<value_type>::value){\n      funcp = other::lgamma;\n      result = boost::math::tools::test(\n         data,\n         bind_func(funcp, 0),\n         extract_result(2));\n      print_test_result(result, data[result.worst()], result.worst(), type_name, \"other::lgamma\");\n   }\n#endif\n\n   std::cout << std::endl;\n}\n\ntemplate <class T>\nvoid do_test_gammap1m1(const T& data, const char* type_name, const char* test_name)\n{\n   typedef typename T::value_type row_type;\n   typedef typename row_type::value_type value_type;\n\n   typedef value_type (*pg)(value_type);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::tgamma1pm1<value_type>;\n#else\n   pg funcp = boost::math::tgamma1pm1;\n#endif\n\n   boost::math::tools::test_result<value_type> result;\n\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n\n   //\n   // test tgamma1pm1 against data:\n   //\n   result = boost::math::tools::test(\n      data,\n      bind_func(funcp, 0),\n      extract_result(1));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::tgamma1pm1\", test_name);\n   std::cout << std::endl;\n}\n\ntemplate <class T>\nvoid test_gamma(T, const char* name)\n{\n   //\n   // The actual test data is rather verbose, so it's in a separate file\n   //\n   // The contents are as follows, each row of data contains\n   // three items, input value, gamma and lgamma:\n   //\n   // gamma and lgamma at integer and half integer values:\n   // boost::array<boost::array<T, 3>, N> factorials;\n   //\n   // gamma and lgamma for z near 0:\n   // boost::array<boost::array<T, 3>, N> near_0;\n   //\n   // gamma and lgamma for z near 1:\n   // boost::array<boost::array<T, 3>, N> near_1;\n   //\n   // gamma and lgamma for z near 2:\n   // boost::array<boost::array<T, 3>, N> near_2;\n   //\n   // gamma and lgamma for z near -10:\n   // boost::array<boost::array<T, 3>, N> near_m10;\n   //\n   // gamma and lgamma for z near -55:\n   // boost::array<boost::array<T, 3>, N> near_m55;\n   //\n   // The last two cases are chosen more or less at random,\n   // except that one is even and the other odd, and both are\n   // at negative poles.  The data near zero also tests near\n   // a pole, the data near 1 and 2 are to probe lgamma as\n   // the result -> 0.\n   //\n#  include \"test_gamma_data.ipp\"\n\n   do_test_gamma(factorials, name, \"factorials\");\n   do_test_gamma(near_0, name, \"near 0\");\n   do_test_gamma(near_1, name, \"near 1\");\n   do_test_gamma(near_2, name, \"near 2\");\n   do_test_gamma(near_m10, name, \"near -10\");\n   do_test_gamma(near_m55, name, \"near -55\");\n\n   //\n   // And now tgamma1pm1 which computes gamma(1+dz)-1:\n   //\n   do_test_gammap1m1(gammap1m1_data, name, \"tgamma1pm1(dz)\");\n}\n\ntemplate <class T>\nvoid test_spots(T)\n{\n   //\n   // basic sanity checks, tolerance is 50 epsilon expressed as a percentage:\n   //\n   T tolerance = boost::math::tools::epsilon<T>() * 5000;\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(3.5)), static_cast<T>(3.3233509704478425511840640312646472177454052302295L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(0.125)), static_cast<T>(7.5339415987976119046992298412151336246104195881491L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(-0.125)), static_cast<T>(-8.7172188593831756100190140408231437691829605421405L), tolerance);\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(-3.125)), static_cast<T>(1.1668538708507675587790157356605097019141636072094L), tolerance);\n   // Lower tolerance on this one, is only really needed on Linux x86 systems, result is mostly down to std lib accuracy:\n   BOOST_CHECK_CLOSE(::boost::math::tgamma(static_cast<T>(-53249.0/1024)), static_cast<T>(-1.2646559519067605488251406578743995122462767733517e-65L), tolerance * 3);\n\n   int sign = 1;\n   BOOST_CHECK_CLOSE(::boost::math::lgamma(static_cast<T>(3.5), &sign), static_cast<T>(1.2009736023470742248160218814507129957702389154682L), tolerance);\n   BOOST_CHECK(sign == 1);\n   BOOST_CHECK_CLOSE(::boost::math::lgamma(static_cast<T>(0.125), &sign), static_cast<T>(2.0194183575537963453202905211670995899482809521344L), tolerance);\n   BOOST_CHECK(sign == 1);\n   BOOST_CHECK_CLOSE(::boost::math::lgamma(static_cast<T>(-0.125), &sign), static_cast<T>(2.1653002489051702517540619481440174064962195287626L), tolerance);\n   BOOST_CHECK(sign == -1);\n   BOOST_CHECK_CLOSE(::boost::math::lgamma(static_cast<T>(-3.125), &sign), static_cast<T>(0.1543111276840418242676072830970532952413339012367L), tolerance);\n   BOOST_CHECK(sign == 1);\n   BOOST_CHECK_CLOSE(::boost::math::lgamma(static_cast<T>(-53249.0/1024), &sign), static_cast<T>(-149.43323093420259741100038126078721302600128285894L), tolerance);\n   BOOST_CHECK(sign == -1);\n}\n\nint test_main(int, char* [])\n{\n   expected_results();\n   BOOST_MATH_CONTROL_FP;\n\n#ifndef BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS\n   test_spots(0.0F);\n#endif\n   test_spots(0.0);\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_spots(0.0L);\n   test_spots(boost::math::concepts::real_concept(0.1));\n#endif\n\n#ifndef BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS\n   test_gamma(0.1F, \"float\");\n#endif\n   test_gamma(0.1, \"double\");\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_gamma(0.1L, \"long double\");\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n   test_gamma(boost::math::concepts::real_concept(0.1), \"real_concept\");\n#endif\n#endif\n#else\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\n      \"either because the long double overloads of the usual math functions are \"\n      \"not available at all, or because they are too inaccurate for these tests \"\n      \"to pass.</note>\" << std::cout;\n#endif\n   return 0;\n}\n\n\n\n", "meta": {"hexsha": "f5801084d6e7a811eb64904de603779e8c3cd10e", "size": 19985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_gamma.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/math/test/test_gamma.cpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/test/test_gamma.cpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1305220884, "max_line_length": 165, "alphanum_fraction": 0.5295971979, "num_tokens": 5011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.5571807629622427}}
{"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": "#include <string>\n#include <stdexcept>\n\n#include <iostream>\n\n#include <armadillo>\n\n#include \"Conv2D/Mesh.hpp\"\n#include \"Conv2D/EulerDefaultBase.hpp\"\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        throw std::runtime_error(\"No choice of input mesh given\");\n    }\n\n    int choice = std::atoi(argv[1]);\n\n    if (choice < 0 || choice > 4)\n    {\n        throw std::runtime_error(\"Invalid choice of input mesh\");\n    }\n\n    const std::string choiceString = std::to_string(choice);\n\n    const std::string meshFile     = \"bump\" + choiceString + \".gri\";\n    const std::string residualFile = \"FirstOrderPreserveResidual\" + choiceString + \".dat\";\n\n    Mesh mesh;\n    mesh.readFromFile(meshFile);\n    mesh.computeMatrices();\n\n    EulerDefaultBase problem;\n    problem.setMesh(mesh);\n    problem.setGasConstant(1.0);\n    problem.setSpecificHeatRatio(1.4);\n    problem.setFreeFlowMachNumber(0.5);\n    problem.setFreeFlowStaticPressure(1.0);\n    problem.setCFLNumber(0.5);\n\n    problem.setInitialState();\n\n    const arma::uword numIter = 1000;\n    problem.runFirstOrderSolver(numIter, residualFile);\n\n    return 0;\n}\n", "meta": {"hexsha": "b834a574c3cd43f09bf2dfc8a9fd5b541092f5c8", "size": 1122, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/FirstOrderPreserve.cpp", "max_stars_repo_name": "saibalde/Aerosp623Project2", "max_stars_repo_head_hexsha": "cfa1c725f370404b2a2cee463d51826b9592d066", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/FirstOrderPreserve.cpp", "max_issues_repo_name": "saibalde/Aerosp623Project2", "max_issues_repo_head_hexsha": "cfa1c725f370404b2a2cee463d51826b9592d066", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/FirstOrderPreserve.cpp", "max_forks_repo_name": "saibalde/Aerosp623Project2", "max_forks_repo_head_hexsha": "cfa1c725f370404b2a2cee463d51826b9592d066", "max_forks_repo_licenses": ["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.8979591837, "max_line_length": 90, "alphanum_fraction": 0.6666666667, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5571421842875912}}
{"text": "#include <cmath>\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include <isce3/antenna/EdgeMethodCostFunc.h>\n#include <isce3/core/Poly1d.h>\n#include <isce3/math/polyfunc.h>\n\nusing namespace isce3::antenna;\n\n// a helper function to evaluate a Poly1d object over Eigen array of inputs\nEigen::ArrayXd polyvals(const isce3::core::Poly1d& pf, Eigen::ArrayXd x)\n{\n    Eigen::Map<const Eigen::ArrayXd> pf_coef_map(\n            pf.coeffs.data(), pf.coeffs.size());\n    return isce3::math::polyval(pf_coef_map, x, pf.mean, pf.norm);\n}\n\nstruct EdgeMethodCostFuncTest : public ::testing::Test {\n\n    void SetUp() override\n    {\n        // form gain and look angle of reference antenna pattern\n        // perform polyfiting to build Poly1d object version of reference\n        // antenna pattern\n        Eigen::Map<const Eigen::ArrayXd> lka_deg_map(\n                lka_deg.data(), lka_deg.size());\n        Eigen::Map<const Eigen::ArrayXd> gain_map(gain.data(), gain.size());\n        pf_ref = isce3::math::polyfitObj(lka_deg_map * d2r, gain_map, 6, false);\n\n        // uniformly-spaced look angles around rising edge used for both antenna\n        // and echo objects\n        Eigen::ArrayXd lka_edge_rad;\n        lka_edge_rad = Eigen::ArrayXd::LinSpaced(\n                num_lka_edge, d2r * min_lka_edge_deg, d2r * max_lka_edge_deg);\n\n        // form ANT 3rd-order poly object with roll offset applied to edge look\n        // angles\n        pf_ant_vec.reserve(roll_ofs_ant_mdeg.size());\n        for (const auto& roll : roll_ofs_ant_mdeg) {\n            // add roll offset (perturbed)\n            auto lka_ant_rad = lka_edge_rad + roll * md2r;\n            // add a gain offset\n            Eigen::ArrayXd gain_ant = polyvals(pf_ref, lka_ant_rad) + gain_ofs;\n            pf_ant_vec.push_back(\n                    isce3::math::polyfitObj(lka_edge_rad, gain_ant, 3, false));\n        }\n\n        // form echo 3rd-order poly object with roll offset applied to edge look\n        // angles\n        auto gain_echo = polyvals(pf_ref, lka_edge_rad);\n        pf_echo = isce3::math::polyfitObj(lka_edge_rad, gain_echo, 3, false);\n\n        // here we use constant but non-normalized weights (order 0)\n        pf_wgt = isce3::core::Poly1d(0, 0.0, 1.0);\n        pf_wgt.coeffs = std::vector<double> {10};\n    }\n    // List of methods\n    void validate_estimation(const std::tuple<double, double, bool, int>& est,\n            double roll_true_mdeg, const std::string& err_msg = {})\n    {\n        auto [roll_est, f_val, flag, n_iter] = est;\n        // Absolute error (residual after compensating for estimated offset) in\n        // (mdeg)\n        auto abs_err = std::abs(roll_est * r2md + roll_true_mdeg);\n        // check individual values\n        std::string err_msg1 {\"@ true roll offset \" +\n                              std::to_string(roll_true_mdeg) + \" (mdeg) \" +\n                              err_msg};\n        EXPECT_LE(n_iter, max_iter)\n                << \"Exceed max number of iteration \" + err_msg1;\n        EXPECT_TRUE(flag) << \"Wrong convergence flag \" + err_msg1;\n        EXPECT_NEAR(abs_err, 0.0, max_abs_err_mdeg)\n                << \"Too large residual roll offset \" + err_msg1;\n        EXPECT_NEAR(f_val, 0.0, abs_tol)\n                << \"Wrong cost function value \" + err_msg1;\n    }\n\n    // List of public members\n\n    // conversion from (deg/mdeg) to (rad) and vice versa\n    const double d2r {M_PI / 180.};\n    const double md2r {d2r * 1e-3};\n    const double r2md {1.0 / md2r};\n\n    // max absolute pointing error (mdeg) of the estimation over wide range of\n    // Roll angle offset. This is used to evaluate the residual error after\n    // compensating for estimated offset. e.g. within [-200, +200] (mdeg, mdeg)\n    // used here, it is set to around 1% margin of total 400 mdeg. This is way\n    // finer than the requirement (>=15 mdeg)!\n    const double max_abs_err_mdeg {5.0};\n\n    // Absolute function value tolerance in root of cost function used in\n    // \"RollAngleOffsetFromEdge\"\n    const double abs_tol {1e-4};\n    // Max expected interation of cost function used in\n    // \"RollAngleOffsetFromEdge\"\n    const int max_iter {20};\n\n    // look angle (off-nadir angle) inputs\n    const double min_lka_edge_deg {32.8};\n    const double max_lka_edge_deg {34.0};\n    const double prec_lka_edge_deg {1e-3};\n    const int num_lka_edge {\n            static_cast<int>(std::round((max_lka_edge_deg - min_lka_edge_deg) /\n                                        prec_lka_edge_deg) +\n                             1)};\n\n    // gain offset in (dB) between relative EL power patterns extracted from\n    // antenna and echo. the roll offset estimation is insensitive to this gain\n    // offset!\n    const double gain_ofs {0.5};\n\n    // desired roll angle offset in (mdeg) , ground truth values used for\n    // validation. These value are also used to perturb EL power pattern from\n    // antenna given the cost function tries to find a roll offset to be added\n    // to antenna EL to align its power pattern with that of echo data. Thus,\n    // the sign of estimated roll offset will be the opposite of these angles\n    // with some tiny deviation due to poly fitting.\n    std::vector<double> roll_ofs_ant_mdeg {-198.0, -42.5, 0.0, 67.0, 157.3};\n\n    // Build a 6-order polyminals of a relative antenna gain from gain (dB)\n    // versus look angles (rad) to be used as a reference for building both\n    // antenna and echo data\n    // These points are extracted from a realistic EL power pattern of ALOS1\n    // beam #7.\n    std::vector<double> gain {\n            -2.2, -1.2, -0.55, -0.2, 0.0, -0.2, -0.5, -1.0, -2.0};\n    std::vector<double> lka_deg {\n            32.0, 32.5, 33.0, 33.5, 34.1, 34.5, 35., 35.5, 36.};\n    isce3::core::Poly1d pf_ref;\n\n    // a vector of 3rd-order polyfit objects for Antenna , one per each roll\n    // angle offset (perturbed)\n    std::vector<isce3::core::Poly1d> pf_ant_vec;\n\n    // 3rd-order polyfit object for Echo common for all offset (unperturbed)\n    isce3::core::Poly1d pf_echo;\n\n    // Polyfit version of weights used in weighting cost function over look\n    // angles (optional)\n    isce3::core::Poly1d pf_wgt;\n};\n\nTEST_F(EdgeMethodCostFuncTest, RollAngleOffsetFromEdge_LookAngNearFar)\n{\n    // loop over roll offset (and antenna polyfit objects)\n    for (std::size_t idx = 0; idx < roll_ofs_ant_mdeg.size(); ++idx) {\n        // estimate roll offset w/o weighting\n        auto est_tuple = rollAngleOffsetFromEdge(pf_echo, pf_ant_vec[idx],\n                min_lka_edge_deg * d2r, max_lka_edge_deg * d2r,\n                prec_lka_edge_deg * d2r);\n        // validate results w/o weighting\n        validate_estimation(est_tuple, roll_ofs_ant_mdeg[idx],\n                std::string(\"w/o weighting!\"));\n\n        // estimate roll offset w/ weighting\n        auto est_wgt_tuple = rollAngleOffsetFromEdge(pf_echo, pf_ant_vec[idx],\n                min_lka_edge_deg * d2r, max_lka_edge_deg * d2r,\n                prec_lka_edge_deg * d2r, pf_wgt);\n        // validate results w/ weighting\n        validate_estimation(est_wgt_tuple, roll_ofs_ant_mdeg[idx],\n                std::string(\"w/ weighting!\"));\n    }\n}\n\nTEST_F(EdgeMethodCostFuncTest, RollAngleOffsetFromEdge_LookAngLinspace)\n{\n    // form isce3 Linspace object for uniformly sampled look angles within [min\n    // ,max]\n    auto lka_lsp = isce3::core::Linspace<double>::from_interval(\n            min_lka_edge_deg * d2r, max_lka_edge_deg * d2r, num_lka_edge);\n    // loop over roll offset (and antenna polyfit objects)\n    for (std::size_t idx = 0; idx < roll_ofs_ant_mdeg.size(); ++idx) {\n        // estimate roll offset w/o weighting\n        auto est_tuple =\n                rollAngleOffsetFromEdge(pf_echo, pf_ant_vec[idx], lka_lsp);\n        // validate results\n        validate_estimation(est_tuple, roll_ofs_ant_mdeg[idx],\n                std::string(\"w/o weighting!\"));\n\n        // estimate roll offset w/ weighting\n        auto est_wgt_tuple = rollAngleOffsetFromEdge(\n                pf_echo, pf_ant_vec[idx], lka_lsp, pf_wgt);\n        // validate results w/ weighting\n        validate_estimation(est_wgt_tuple, roll_ofs_ant_mdeg[idx],\n                std::string(\"w/ weighting!\"));\n    }\n}\n\nint main(int argc, char** argv)\n{\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "692bec211d90a3b15cb01eb95eb28166bddb85b6", "size": 8319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cxx/isce3/antenna/edge_method_cost_func.cpp", "max_stars_repo_name": "isce3-testing/isce3-circleci-poc", "max_stars_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/cxx/isce3/antenna/edge_method_cost_func.cpp", "max_issues_repo_name": "isce3-testing/isce3-circleci-poc", "max_issues_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T00:00:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T00:00:31.000Z", "max_forks_repo_path": "tests/cxx/isce3/antenna/edge_method_cost_func.cpp", "max_forks_repo_name": "isce3-testing/isce3-circleci-poc", "max_forks_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T21:10:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T21:10:11.000Z", "avg_line_length": 41.8040201005, "max_line_length": 80, "alphanum_fraction": 0.6402211804, "num_tokens": 2245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5571421842875912}}
{"text": "#include <Eigen/Eigen>\n#include <algorithm>\n#include <chrono>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <string>\n#include <unordered_set>\n#include <vector>\n\n#include <pcl/console/parse.h>\n#include <pcl/filters/frustum_culling.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/surface/convex_hull.h>\n#include <pcl/visualization/pcl_visualizer.h>\n\n#include \"Cube.h\"\n#include \"Drawer.h\"\n#include \"Frustum.h\"\n\nvoid cubes() {\n    auto start = std::chrono::high_resolution_clock::now();\n    Drawer<pcl::PointXYZRGB>::init();\n    auto draw = Drawer<pcl::PointXYZRGB>::get();\n\n    Eigen::Matrix4f pose1;\n    pose1 << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;\n    std::shared_ptr<Cube> c1(new Cube(1, pose1, 10, 10, 10));\n\n    Eigen::Matrix4f pose2;\n    pose2 << 0.7071068, 0, 0.7071068, 1, 0, 1, 0, 1, -0.7071068, 0, 0.7071068,\n        2, 0, 0, 0, 1;\n    std::shared_ptr<Cube> c2(new Cube(2, pose2, 15, 5, 10));\n\n    draw->polyhedron(c1->id, c1->mPose.block(0, 3, 3, 1), c1->getFacets());\n    draw->polyhedron(c2->id, c2->mPose.block(0, 3, 3, 1), c2->getFacets());\n\n    std::vector<Eigen::Vector3f> inter;\n    std::vector<Eigen::Vector3f> culledInter;\n    c2->clipConvexPolyhedron(c1, inter);\n\n    std::cout << \"Number of intersection points: \" << inter.size() << \"\\n\";\n\n    // for (auto &p : inter) {\n    //     bool duplicated = false;\n    //     for (auto &c : culledInter) {\n    //         if (p == c) {\n    //             duplicated = true;\n    //             break;\n    //         }\n    //     }\n    //     if (!duplicated) culledInter.push_back(p);\n    // }\n    // std::cout << \"Number of intersection points: \" << culledInter.size()\n    //           << \"\\n\";\n\n    std::string v = \"Intersection_point_\";\n    int i = 0;\n    for (auto point : inter) {\n        std::cout << \" Point \" << i << \" : \" << point(0) << \" \" << point(1)\n                  << \" \" << point(2) << std::endl;\n        draw->point(point, v + std::to_string(i));\n        i++;\n    }\n\n    std::cout << \"Convex hull has \" << c1->computeVolumeFromPoints(inter)\n              << \" m\u00b3 \\n\";\n    std::cout << \"Volume of frustum: \" << c1->getVolume() << \" m\u00b3 \\n\";\n    std::cout << \"% of volume intersected \"\n              << 100 * (c1->computeVolumeFromPoints(inter) / c1->getVolume())\n              << \"  \\n\";\n    \n    std::cout << \"Volume of frustum: \" << c1->computeVolumeFromPoints(c1->getVertices()) << \" m\u00b3 \\n\";\n        std::cout << \"% of volume intersected \"\n              << 100 * (c1->computeVolumeFromPoints(inter) / c1->computeVolumeFromPoints(c1->getVertices()))\n              << \"  \\n\";\n    \n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<float, std::milli> duration = (end - start);\n    std::cout << \"Time elapsed: \" << duration.count() / 1000 << std::endl;\n\n    // std::cout << \"Clipping ended \\n\";\n    bool run = true;\n    while (run) {\n        draw->spinOnce();\n    }\n    std::cout << \"Closing \\n\";\n}\n\nvoid frustum()\n{\n    Drawer<pcl::PointXYZRGB>::init();\n    auto draw = Drawer<pcl::PointXYZRGB>::get();\n\n    Eigen::Matrix4f pose1;\n    pose1 << 1, 0, 0, 0,\n        0, 1, 0, 0,\n        0, 0, 1, 0,\n        0, 0, 0, 1;\n    std::shared_ptr<Frustum> f1(new Frustum(1, pose1, 45, 45, 1, 5));\n\n    Eigen::Matrix4f pose2;\n    pose2 << 1, 0, 0, 1,\n        0, 0.5, 0, 1,\n        0, 0, 1, 2,\n        0, 0, 0, 1;\n    std::shared_ptr<Frustum> f2(new Frustum(2, pose2, 45, 45, 1, 5));\n\n    draw->polyhedron(f1->id, f1->mPosition, f1->getFacets());\n    draw->polyhedron(f2->id, f2->mPosition, f2->getFacets());\n\n    std::vector<Eigen::Vector3f> inter;\n    f1->clipConvexPolyhedron(f2, inter);\n    std::cout << \"Number of intersection points: \" << inter.size() << \"\\n\";\n\n    std::string v = \"Intersection_point_\";\n    int i = 0;\n    for (auto point : inter)\n    {\n        draw->point(point, v + std::to_string(i));\n        i++;\n    }\n\n    std::cout << \"Convex hull has \" << f1->computeVolumeFromPoints(inter) <<\n    \" m\u00b3 \\n\"; std::cout << \"Volume of frustum: \" << f1->getVolume() << \" m\u00b3\\n\"; \n    std::cout << \"% of volume intersected \" <<\n    100*(f1->computeVolumeFromPoints(inter)/f1->getVolume()) << \"  \\n\";\n\n    std::cout << \"Clipping ended \\n\";\n    bool end = true;\n    while (end)\n    {\n        draw->spinOnce();\n    }\n    std::cout << \"Closing \\n\";\n}\n\nint main(int argc, char const *argv[])\n{\n    // frustum();\n    cubes();\n    return 0;\n}\n", "meta": {"hexsha": "aa140a72b4f26db58063acd09815c3d5c92bf760", "size": 4437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Ric92/frustum_clipping", "max_stars_repo_head_hexsha": "e8a90270bda37023ab41bbf3cadaa2dab954d625", "max_stars_repo_licenses": ["MIT"], "max_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": "Ric92/frustum_clipping", "max_issues_repo_head_hexsha": "e8a90270bda37023ab41bbf3cadaa2dab954d625", "max_issues_repo_licenses": ["MIT"], "max_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": "Ric92/frustum_clipping", "max_forks_repo_head_hexsha": "e8a90270bda37023ab41bbf3cadaa2dab954d625", "max_forks_repo_licenses": ["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.1836734694, "max_line_length": 108, "alphanum_fraction": 0.5483434753, "num_tokens": 1485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5571421789039441}}
{"text": "/*******************************************************************************\n *         Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II\n *         Copyright 2009 & onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n *\n *          Distributed under the Boost Software License, Version 1.0.\n *                 See accompanying file LICENSE.txt or copy at\n *                     http://www.boost.org/LICENSE_1_0.txt\n ******************************************************************************/\n#define NT2_UNIT_MODULE \"nt2::meta::arithmetic\"\n\n#include <boost/tr1/functional.hpp>\n#include <nt2/sdk/config/types.hpp>\n#include <nt2/sdk/meta/arithmetic.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/basic.hpp>\n\n////////////////////////////////////////////////////////////////////////////////\n// Test any with 1 types\n////////////////////////////////////////////////////////////////////////////////\nNT2_TEST_CASE( unary_arithmetic )\n{\n  using nt2::meta::arithmetic;\n  using std::tr1::result_of;\n  using boost::is_same;\n\n  NT2_TEST( (is_same<double, result_of<arithmetic(double)>::type >::value ) );\n  NT2_TEST( (is_same<float, result_of<arithmetic(float )>::type >::value ) );\n  NT2_TEST( (is_same<nt2::uint64_t, result_of<arithmetic(nt2::uint64_t )>::type >::value ) );\n  NT2_TEST( (is_same<nt2::uint32_t, result_of<arithmetic(nt2::uint32_t )>::type >::value ) );\n  NT2_TEST( (is_same<nt2::int32_t, result_of<arithmetic(nt2::uint16_t )>::type >::value ) );\n  NT2_TEST( (is_same<nt2::int32_t, result_of<arithmetic(nt2::uint8_t )>::type >::value ) );\n  NT2_TEST( (is_same<nt2::int64_t, result_of<arithmetic(nt2::int64_t )>::type >::value ) );\n  NT2_TEST( (is_same<nt2::int32_t, result_of<arithmetic(nt2::int32_t )>::type >::value ) );\n  NT2_TEST( (is_same<nt2::int32_t, result_of<arithmetic(nt2::int16_t )>::type >::value ) );\n  NT2_TEST( (is_same<nt2::int32_t, result_of<arithmetic(nt2::int8_t )>::type >::value ) );\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Test any with 2 types\n////////////////////////////////////////////////////////////////////////////////\nNT2_TEST_CASE( binary_arithmetic )\n{\n  using nt2::meta::arithmetic;\n  using std::tr1::result_of;\n  using boost::is_same;\n\n  NT2_TEST( (is_same<double, result_of<arithmetic(double,double)>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(double,float )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(double,nt2::uint64_t )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(double,nt2::uint32_t )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(double,nt2::uint16_t )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(double,nt2::uint8_t )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(double,nt2::int64_t )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(double,nt2::int32_t )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(double,nt2::int16_t )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(double,nt2::int8_t )>::type >::value ) );\n\n  NT2_TEST( (is_same<double, result_of<arithmetic(float,double)>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(float,float )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(float,nt2::uint64_t )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(float,nt2::uint32_t )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(float,nt2::uint16_t )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(float,nt2::uint8_t )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(float,nt2::int64_t )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(float,nt2::int32_t )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(float,nt2::int16_t )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(float,nt2::int8_t )>::type >::value ) );\n\n  NT2_TEST( (is_same<double, result_of<arithmetic(double,double)>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(float,double )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(nt2::uint64_t,double )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(nt2::uint32_t,double )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(nt2::uint16_t,double )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(nt2::uint8_t ,double )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(nt2::int64_t ,double )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(nt2::int32_t ,double )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(nt2::int16_t ,double )>::type >::value ) );\n  NT2_TEST( (is_same<double, result_of<arithmetic(nt2::int8_t  ,double )>::type >::value ) );\n\n  NT2_TEST( (is_same<double, result_of<arithmetic(double,float)>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(float ,float)>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(nt2::uint64_t,float )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(nt2::uint32_t,float )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(nt2::uint16_t,float )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(nt2::uint8_t ,float )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(nt2::int64_t ,float )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(nt2::int32_t ,float )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(nt2::int16_t ,float )>::type >::value ) );\n  NT2_TEST( (is_same<float , result_of<arithmetic(nt2::int8_t  ,float )>::type >::value ) );\n}\n", "meta": {"hexsha": "d93de0f7879f3519f676aa9d164539b813616dbc", "size": 5971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/sdk/unit/meta/m_arithmetic.cpp", "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/sdk/unit/meta/m_arithmetic.cpp", "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/sdk/unit/meta/m_arithmetic.cpp", "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": 64.902173913, "max_line_length": 93, "alphanum_fraction": 0.6337296935, "num_tokens": 1726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5570728055099637}}
{"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": "/*! \\file demo_1d_axis_scaling.cpp\n\n  \\brief Demonstration of 1D plot with axis scaling.\n  \\details See auto_1d_containers.cpp for an example axis_scaling with multiple data series.\n\n  \\author Paul A Bristow\n\n  \\date 2009\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A Bristow 2008\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_1d_axis_scaling_1\n\n/*`This example shows the use of functions scale_axis to find suitable axis limits.\nNormally one would use autoscaling, but there are conceivable circumstances when\none would want to check on the scale_axis algorithm's choice of axis,\nand perhaps intervene in the process.\n\nFirst some includes to use Boost.Plot\n(and some others only needed for this example).\n*/\n\n#include <boost/svg_plot/svg_1d_plot.hpp>\n  using namespace boost::svg;\n  using boost::svg::svg_1d_plot;\n\n#include <boost/svg_plot/show_1d_settings.hpp>\n// Only needed for showing which settings in use.\n// void boost::svg::show_1d_plot_settings(svg_1d_plot&);\n // (Also provides operator<< for std::pair).\n\n#include <boost/algorithm/minmax.hpp>\n using boost::minmax;\n#include <boost/algorithm/minmax_element.hpp>\n using boost::minmax_element;\n\n#include <iostream> // for debugging.\n  using std::cout;\n  using std::endl;\n  using std::boolalpha;\n\n#include <limits>\n  using std::numeric_limits;\n\n#include <vector>\n  using std::vector;\n#include <set>\n  using std::multiset;\n\n#include <utility>\n  using std::pair;\n\n#include <boost/svg_plot/detail/auto_axes.hpp>\n  using boost::svg::show; // A single STL container.\n  using boost::svg::show_all; // Multiple STL containers.\n  // using boost::svg::range; // Find min and max of a STL container.\n  using boost::svg::range_all;// Find min and max of multipler STL containers.\n//] [/demo_1d_axis_scaling_1]\n\nvoid scale_axis(double min_value, double max_value, // Input range\n               double* axis_min_value,  double* axis_max_value, double* axis_tick_increment, int* major_ticks, // All 4 updated.\n               bool origin, // If true, ensures that zero is a tick value.\n               double tight, // Allows user to avoid a small fraction over a tick using another tick.\n               int min_ticks, // Minimum number of ticks.\n               int steps); // Round up and down to 2, 4, 6, 8, 10, or 5, 10 or 2, 5, 10 systems.\n\ndouble tol100eps = 1000 * numeric_limits<double>::epsilon(); // suitable tight value.\n\nint main()\n{\n  using namespace boost::svg;\n  try\n  {\n//[demo_1d_axis_scaling_2\n  /*`This example uses a few types of containers to demonstrate axis_scaling.\n  axis_scaling must inspect the container in order to find axis ranges that will be suitable.\n  First we create a container and fill with some fictional data.\n  */\n  vector<double> my_data;\n  // Initialize my_data with some entirely fictional data.\n  my_data.push_back(0.2);\n  my_data.push_back(1.1); // [1]\n  my_data.push_back(4.2); // [2]\n  my_data.push_back(3.3); // [3]\n  my_data.push_back(5.4); // [4]\n  my_data.push_back(6.5); // [5]\n  show(my_data); // Show entire container contents,\n  // 6 values in container: 0.2 1.1 4.2 3.3 5.4 6.5\n//] [/demo_1d_axis_scaling_2]\n\n//[demo_1d_axis_scaling_3\n  multiset<double> my_set;\n  // Initialize my_set with some entirely fictional data.\n  my_set.insert(1.2);\n  my_set.insert(2.3);\n  my_set.insert(3.4);\n  my_set.insert(4.5);\n  my_set.insert(5.6);\n  my_set.insert(6.7);\n  my_set.insert(7.8);\n  my_set.insert(8.9);\n  // Show the set.\n  multiset<double>::const_iterator si;\n  show(my_set); // for two different types of container.\n  // 8 values in container: 1.2 2.3 3.4 4.5 5.6 6.7 7.8 8.9\n/*` Show can also display just a part of the container contents.\n*/\n  // show(&my_data[0], &my_data[my_data.size()]); // pointers - wrong! > all data ;-)\n  show(&my_data[0], &my_data[my_data.size()-1]); // pointers, all data.\n  show(&my_data[1], &my_data[5]); // pointers, part data.\n  show(my_data.begin(), my_data.end()); // iterators.\n  show(++(my_data.begin()), --(my_data.end())); // Just the 4 middle values.\n\n  vector<double>::const_iterator idb = my_data.begin();\n  vector<double>::const_iterator ide = my_data.end();\n  show(idb, ide); // All\n  ++idb; // Move to 2nd value.\n  --ide; // move back from last value.\n  show(idb, ide); // Just the 4 middle values.\n//] [/demo_1d_axis_scaling_3]\n\n//[demo_1d_axis_scaling_4\n\n  /*`Is is possible to find the minimum and maximum values in a container using the STL functions min & max\n  or more conveniently and efficiently with boost::minmax_element:\n  */\n\n  typedef vector<double>::const_iterator vector_iterator;\n  pair<vector_iterator, vector_iterator> result = boost::minmax_element(my_data.begin(), my_data.end());\n  cout << \"The smallest element is \" << *(result.first) << endl; // 0.2\n  cout << \"The largest element is  \" << *(result.second) << endl; // 6.5\n\n  // axis_scaling using two double min and max values.\n  double min_value = *(my_data.begin());\n  double max_value = *(--my_data.end());\n  cout << \"axis_scaling 1 min \" << min_value << \", max = \" << max_value << endl;\n\n/*` and to apply these values to the axis_scaling algorithm using by plot to choose the axes limits and ticks.\n*/\n  double axis_min_value; // Values to be updated by function `scale_axis`.\n  double axis_max_value;\n  double axis_tick_increment;\n  int axis_ticks;\n  \n  scale_axis(min_value, max_value,\n    &axis_min_value, &axis_max_value, &axis_tick_increment, &axis_ticks,\n    false, tol100eps, 6); // Display range.\n  cout << \"Axis_scaled 2 min \" << axis_min_value << \", max = \" << axis_max_value << \", increment \" << axis_tick_increment << endl;\n/*`It is also possible to use this with containers that use iterators and whose contents are ordered in ascending value,\naxis_scaling using first and last in container, for example, set, map, multimap, or a sorted vector or array.\nA number of variations are shown below, mainly by way of testing.\n*/\n  scale_axis(*my_data.begin(),*(--my_data.end()),\n    &axis_min_value, &axis_max_value, &axis_tick_increment, &axis_ticks,\n    false, tol100eps, 6); // Display range.\n  cout << \"Axis_scaled 3 min \" << axis_min_value << \", max = \" << axis_max_value << \", increment \" << axis_tick_increment << endl;\n\n  // axis_scaling using two begin & end iterators into STL container,\n  // scale_axis does finding min and max.\n  scale_axis(my_data.begin(), my_data.end(), // Input range\n    &axis_min_value, &axis_max_value, &axis_tick_increment, &axis_ticks, // to update.\n    true, // check for non-finite\n    3., // autoscale_plusminus = 3 sd\n    false, // Do not include origin\n    tol100eps, // tight\n    6, // steps at default.\n    0); // Display range.\n  cout << \"Axis_scaled 4 min \" << axis_min_value << \", max = \" << axis_max_value << \", increment \" << axis_tick_increment << endl;\n\n  // axis_scaling using two iterators @c begin() & @c end() into an STL container,\n  // scale_axis does finding min and max.\n  scale_axis(my_data[1], my_data[4], // Only middle part of the container used, ignoring 1st and last values.\n    &axis_min_value, &axis_max_value, &axis_tick_increment, &axis_ticks,\n    true, tol100eps, 6); // Display range.\n  cout << \"Axis_scaled 5 min \" << axis_min_value << \", max = \" << axis_max_value << \", increment \" << axis_tick_increment << endl;\n\n  // axis_scaling using whole STL container,\n  // scale_axis does finding min and max.\n  scale_axis(my_data, &axis_min_value, &axis_max_value, &axis_tick_increment, &axis_ticks,\n    true, 3., false, tol100eps, 6); // Display range.\n  cout << \"Axis_scaled 6 min \" << axis_min_value << \", max = \" << axis_max_value << \", increment \" << axis_tick_increment << endl;\n\n  svg_1d_plot my_1d_plot; // Construct a plot with all the default constructor values.\n\n  // One could intercept and change any values calculated by scale_axis here?\n  // Set the plot to use range and interval from the scale_axis values.\n\n  /*`The axis range thus computed can be inserted directly into the plot using the `range` and `x_major_interval` functions.\n  */\n\n  my_1d_plot.x_range(axis_min_value, axis_max_value)\n    .x_major_interval(axis_tick_increment);\n\n  //my_1d_plot.x_autoscale(false);  // Ensure autoscale values are *not* recalculated for the plot.\n  //] [/demo_1d_axis_scaling_4]\n\n  //[demo_1d_axis_scaling_5\n\n  // Set some axis_scaling parameters:\n  my_1d_plot.x_with_zero(false);\n  my_1d_plot.x_min_ticks(10);\n  my_1d_plot.x_steps(0);\n  my_1d_plot.x_tight(0.001);\n\n  // Show the flags just set.\n  cout << (my_1d_plot.x_with_zero() ? \"x_with_zero, \" : \"not x_with_zero, \")\n    << my_1d_plot.x_min_ticks() << \" x_min_ticks, \"\n    << my_1d_plot.x_steps() << \" x_steps, \"\n    << my_1d_plot.x_tight() << \" tightness.\" << endl;\n\n  my_1d_plot.x_autoscale(my_data);  // Use all my_data to autoscale.\n  cout << \"Axis_scaled \" // Show the results of autoscale:\n    \"min \" << my_1d_plot.x_auto_min_value()\n    << \", max \"<< my_1d_plot.x_auto_max_value()\n    << \", interval \" << my_1d_plot.x_auto_tick_interval() << endl; // Autoscaled min 0, max 6.5, interval 0.5\n\n  my_1d_plot.x_autoscale(my_data.begin(), my_data.end());  // Use all my_data to autoscale.\n\n  cout << \"Axis_scaled \" // Show the results of autoscale:\n    \"min \" << my_1d_plot.x_auto_min_value()\n    << \", max \"<< my_1d_plot.x_auto_max_value()\n    << \", interval \" << my_1d_plot.x_auto_tick_interval() << endl; // Autoscaled min 0, max 6.5, interval 0.5\n\n  my_1d_plot.x_autoscale(my_data[1], my_data[4]);  // Use only part of my_data to autoscale.\n\n  cout << \"Axis_scaled \" // Show the results of autoscale:\n    \"min \" << my_1d_plot.x_auto_min_value()\n    << \", max \"<< my_1d_plot.x_auto_max_value()\n    << \", interval \" << my_1d_plot.x_auto_tick_interval() << endl; // Autoscaled min 1, max 5.5, interval 0.5\n\n  my_1d_plot.x_autoscale(true);  // Ensure autoscale values are used for the plot.\n\n  my_1d_plot.plot(my_data, \"Auto 1D\"); // Add the one data series.\n  cout << \"Axis_scaled \" // Show the results of autoscale:\n    \" min \" << my_1d_plot.x_auto_min_value()\n    << \", max \"<< my_1d_plot.x_auto_max_value()\n    << \", interval \" << my_1d_plot.x_auto_tick_interval() << endl; // Autoscaled min 1, max 5.5, interval 0.5\n\n  my_1d_plot.plot(my_set.begin(), my_set.end(), \"Auto 1D\"); // Add another data series from my_set.\n  my_1d_plot.plot(my_set, \"Auto 1D\"); // Add another whole data series from my_set.\n  my_1d_plot.plot(&my_data[1], &my_data[4], \"Auto 1D\"); // Add part (1,2 3 but *not* 4) of the one data series.\n  //my_1d_plot.plot(&my_set[1], &my_set[4], \"Auto 1D\"); // operator[] is not defined for set container!\n\n  my_1d_plot.write(\"demo_1d_axis_scaling.svg\"); // Write the plot to file.\n\n  using boost::svg::detail::operator<<; // Needed for output a pair.\n  cout << \"x_range() \" << my_1d_plot.x_range() << endl; // x_range() 1, 5.5\n\n  //show_1d_plot_settings(my_1d_plot); // For *all* settings.\n//] [/demo_1d_axis_scaling_5]\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n  \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n/*\n//[demo_1d_axis_scaling_output\n\nAutorun \"j:\\Cpp\\SVG\\Debug\\demo_1d_axis_scaling.exe\"\n6 values in container: 0.2 1.1 4.2 3.3 5.4 6.5\n8 values in container: 1.2 2.3 3.4 4.5 5.6 6.7 7.8 8.9\n0.2 1.1 4.2 3.3 5.4 : 5 values used.\n1.1 4.2 3.3 5.4 : 4 values used.\n0.2 1.1 4.2 3.3 5.4 6.5 : 6 values used.\n1.1 4.2 3.3 5.4 : 4 values used.\n0.2 1.1 4.2 3.3 5.4 6.5 : 6 values used.\n1.1 4.2 3.3 5.4 : 4 values used.\nThe smallest element is 0.2\nThe largest element is  6.5\naxis_scaling 1 min 0.2, max = 6.5\nAxis_scaled 2 min 0, max = 7, increment 1\nAxis_scaled 3 min 0, max = 7, increment 1\nAxis_scaled 4 min 0, max = 7, increment 1\nAxis_scaled 5 min 0, max = 6, increment 1\nAxis_scaled 6 min 0, max = 7, increment 1\nnot x_with_zero, 10 x_min_ticks, 0 x_steps, 0.001 tightness.\nAxis_scaled min 0, max 6.5, interval 0.5\nAxis_scaled min 0, max 6.5, interval 0.5\nAxis_scaled min 1, max 5.5, interval 0.5\nAxis_scaled  min 1, max 5.5, interval 0.5\nx_range() 1, 5.5\n\n//] [/demo_1d_axis_scaling_output]\n\n*/\n\n", "meta": {"hexsha": "0d0c3dc88c32ea16f6bbe8ad5be55e585545874c", "size": 12451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_1d_axis_scaling.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_1d_axis_scaling.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_1d_axis_scaling.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": 40.9572368421, "max_line_length": 130, "alphanum_fraction": 0.6940004819, "num_tokens": 3726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.557005280950216}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Surface_mesh.h>\n\n#include <CGAL/Polygon_mesh_processing/triangulate_hole.h>\n#include <CGAL/Polygon_mesh_processing/border.h>\n#include <CGAL/Polygon_mesh_processing/IO/polygon_mesh_io.h>\n\n#include <boost/lexical_cast.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <set>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::Point_3                                     Point;\ntypedef CGAL::Surface_mesh<Point>                           Mesh;\n\ntypedef boost::graph_traits<Mesh>::vertex_descriptor        vertex_descriptor;\ntypedef boost::graph_traits<Mesh>::halfedge_descriptor      halfedge_descriptor;\ntypedef boost::graph_traits<Mesh>::face_descriptor          face_descriptor;\n\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\nbool is_small_hole(halfedge_descriptor h, Mesh & mesh,\n                   double max_hole_diam, int max_num_hole_edges)\n{\n  int num_hole_edges = 0;\n  CGAL::Bbox_3 hole_bbox;\n  for (halfedge_descriptor hc : CGAL::halfedges_around_face(h, mesh))\n  {\n    const Point& p = mesh.point(target(hc, mesh));\n\n    hole_bbox += p.bbox();\n    ++num_hole_edges;\n\n    // Exit early, to avoid unnecessary traversal of large holes\n    if (num_hole_edges > max_num_hole_edges) return false;\n    if (hole_bbox.xmax() - hole_bbox.xmin() > max_hole_diam) return false;\n    if (hole_bbox.ymax() - hole_bbox.ymin() > max_hole_diam) return false;\n    if (hole_bbox.zmax() - hole_bbox.zmin() > max_hole_diam) return false;\n  }\n\n  return true;\n}\n\n// Incrementally fill the holes that are no larger than given diameter\n// and with no more than a given number of edges (if specified).\n\nint main(int argc, char* argv[])\n{\n  const char* filename = (argc > 1) ? argv[1] : \"data/mech-holes-shark.off\";\n\n  Mesh mesh;\n  if(!PMP::read_polygon_mesh(filename, mesh))\n  {\n    std::cerr << \"Invalid input.\" << std::endl;\n    return 1;\n  }\n\n  // Both of these must be positive in order to be considered\n  double max_hole_diam   = (argc > 2) ? boost::lexical_cast<double>(argv[2]): -1.0;\n  int max_num_hole_edges = (argc > 3) ? boost::lexical_cast<int>(argv[3]) : -1;\n\n  unsigned int nb_holes = 0;\n  std::vector<halfedge_descriptor> border_cycles;\n\n  // collect one halfedge per boundary cycle\n  PMP::extract_boundary_cycles(mesh, std::back_inserter(border_cycles));\n\n  for(halfedge_descriptor h : border_cycles)\n  {\n    if(max_hole_diam > 0 && max_num_hole_edges > 0 &&\n       !is_small_hole(h, mesh, max_hole_diam, max_num_hole_edges))\n      continue;\n\n    std::vector<face_descriptor>  patch_facets;\n    std::vector<vertex_descriptor> patch_vertices;\n    bool success = std::get<0>(PMP::triangulate_refine_and_fair_hole(mesh,\n                                                                     h,\n                                                                     std::back_inserter(patch_facets),\n                                                                     std::back_inserter(patch_vertices)));\n\n    std::cout << \"* Number of facets in constructed patch: \" << patch_facets.size() << std::endl;\n    std::cout << \"  Number of vertices in constructed patch: \" << patch_vertices.size() << std::endl;\n    std::cout << \"  Is fairing successful: \" << success << std::endl;\n    ++nb_holes;\n  }\n\n  std::cout << std::endl;\n  std::cout << nb_holes << \" holes have been filled\" << std::endl;\n\n  CGAL::write_polygon_mesh(\"filled_SM.off\", mesh, CGAL::parameters::stream_precision(17));\n  std::cout << \"Mesh written to: filled_SM.off\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "40689ff20545cd9958dc74ceca91407dbb14d24f", "size": 3587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Polygon_mesh_processing/examples/Polygon_mesh_processing/hole_filling_example_SM.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": "Polygon_mesh_processing/examples/Polygon_mesh_processing/hole_filling_example_SM.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": "Polygon_mesh_processing/examples/Polygon_mesh_processing/hole_filling_example_SM.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": 36.6020408163, "max_line_length": 106, "alphanum_fraction": 0.6593253415, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5570052805718145}}
{"text": "#include <cstdlib>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <Eigen/Core>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/ublas/matrix_expression.hpp>\n#include <boost/numeric/bindings/eigen/vector.hpp>\n#include <boost/numeric/bindings/eigen/matrix.hpp>\n#include <boost/numeric/bindings/blas/level1.hpp>\n#include \"random.hpp\"\n#include \"print.hpp\"\n\nnamespace ublas=boost::numeric::ublas;\nnamespace blas=boost::numeric::bindings::blas;\n\n\nint main(int argc, char *argv[]) {\n  {\n    typedef ublas::vector<double> vector;\n    typedef ublas::matrix<double> matrix;\n    typedef vector::size_type size_type;\n    rand_normal<double>::reset();\n    size_type n=8;\n    vector v1(n);\n    for (size_type i=0; i<n; ++i)\n      v1(i)=rand_normal<double>::get();\n    vector v2(n);\n    blas::copy(v1, v2);\n    matrix M(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i) \n     \tM(i, j)=0;\n    ublas::matrix_column<matrix> mc(M, 2);\n    ublas::matrix_row<matrix> mr(M, 3);\n    blas::copy(v1, mc);\n    blas::copy(v1, mr);\n    std::cout << \"v1 : \" << print_vec(v1) << '\\n'\n\t      << \"v2 : \" << print_vec(v2) << '\\n'\n\t      << \"M :\\n\" \n\t      << print_mat(M) << '\\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    vector v1(n);\n    for (size_type i=0; i<n; ++i)\n      v1(i)=rand_normal<double>::get();\n    vector v2(n);\n    blas::copy(v1, v2);\n    matrix M(n, n);\n    for (size_type j=0; j<n; ++j)\n      for (size_type i=0; i<n; ++i) \n     \tM(i, j)=0;\n    auto mc=M.col(2);\n    auto mr=M.row(3);\n    blas::copy(v1, mc);\n    blas::copy(v1, mr);\n    std::cout << \"v1 : \" << print_vec(v1) << '\\n'\n\t      << \"v2 : \" << print_vec(v2) << '\\n'\n\t      << \"M :\\n\" \n\t      << print_mat(M) << '\\n';\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "e506c4777557c1b54fb6092286c24cfaa9fc95f8", "size": 2180, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/copy.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/copy.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/copy.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.2777777778, "max_line_length": 73, "alphanum_fraction": 0.6110091743, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.557005276628917}}
{"text": "#include <algorithm>\n#include <array>\n#include <bitset>\n#include <charconv>\n#include <iostream>\n#include <numeric>\n#include <queue>\n#include <string_view>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include <boost/range/irange.hpp>\n\n#include \"input.hpp\"\n\nusing uintmax = std::uintmax_t;\n\nusing Location = std::string_view;\nusing LocationID = uintmax;\nusing Distance = uintmax;\n\nstruct ParseStats {\n  uintmax num_locations;\n  uintmax num_entries;\n};\n\nconstexpr auto space = ' ';\nconstexpr auto newline = '\\n';\n\n// compile-time parsing of string_view\nconstexpr auto parse_stats(std::string_view input) {\n  auto stats = ParseStats{};\n  auto& num_locations = stats.num_locations;\n  auto& num_entries = stats.num_entries;\n\n  const auto starts_with = [&input] (auto substring) {\n    return input.substr(0, substring.size()) == substring;\n  };\n\n  const auto end = input.find_first_of(space) + 1;\n  const auto first_place = input.substr(0, end);\n\n  while(starts_with(first_place)) {\n    ++num_locations;\n    input.remove_prefix(input.find_first_of(newline) + 1);\n    ++num_entries;\n  }\n\n  for(const auto c : input) {\n    num_entries += (c == newline);\n  }\n\n  return stats;\n}\n\nconstexpr auto PARSE_STATS = parse_stats(puzzle_input);\nconstexpr auto NUM_ENTRIES = (PARSE_STATS.num_entries + 1);\nconstexpr auto NUM_LOCATIONS = (PARSE_STATS.num_locations + 1);\n\nusing Visits = std::bitset<NUM_LOCATIONS>;\n\n/*\n * Diagonal matrix\n *\n * (1,0)\n * (2,0), (2,1)\n * (3,0), (3,1), (3,2)\n */\nstruct AdjacencyMatrix {\n\n  uintmax num_locations = NUM_LOCATIONS;\n  std::array<Distance, NUM_ENTRIES> matrix;\n\n//  std::vector<Distance> matrix;\n//  AdjacencyMatrix() {\n//    matrix.reserve(NUM_ENTRIES);\n//  }\n\n  auto lookup(LocationID x, LocationID y) const {\n    const auto triangle = [] (auto n) {\n        return (n * (n - 1)) / 2;\n    };\n    const auto [min, max] = std::minmax(x, y);\n    return matrix[triangle(max) + min];\n  }\n};\n\nconstexpr auto split_input(std::string_view input) {\n\n  auto lines = std::array<std::string_view, NUM_ENTRIES>{};\n\n  for(auto& line : lines) {\n    const auto pos = input.find(newline);\n    line = input.substr(0, pos);\n    input.remove_prefix(pos + 1);\n  }\n\n  return lines;\n}\n\nconstexpr auto to_int(std::string_view input) {\n  uintmax result = 0;\n  for(auto c : input) {\n    result *= 10;\n    result += c - '0';\n  }\n  return result;\n\n}\n\ntemplate<typename Iterator>\nconstexpr void reverse(Iterator first, Iterator last) {\n  while ((first != last) && (first != --last)) {\n    std::iter_swap(first++, last);\n  }\n}\n\nconstexpr auto parse_input(std::string_view input) {\n\n  auto paths = AdjacencyMatrix{};\n\n  auto& matrix = paths.matrix;\n\n  auto i = 0;\n  for(auto line : split_input(input)) {\n    const auto last_token = line.find_last_of(space) + 1;\n    const auto distance = to_int(line.substr(last_token));\n    matrix[i++] = distance;\n  }\n\n  /*\n   * The matrix looks like this (conceptually):\n   *\n   * (1,0)\n   * (2,0), (2,1)\n   * (3,0), (3,1), (3,2)\n   *\n   * But the actual ordering is:\n   *\n   * (1,0), (2,0), (2,1), (3,0), (3,1), (3,2)\n   *\n   * However, in the input the distances are grouped by point of origin,\n   * and the next group has alway one entry less to avoid the duplicate\n   * entry from the previous group (remember: A->B is equal to B->A)\n   *\n   * We end up with an ordering that would translate to:\n   *\n   * (3,2) (3,1) (3,0)\n   * (2,1) (2,0)\n   * (1,0)\n   *\n   * which won't work for an adjacency matrix. So we reverse the array\n   * instead.\n   */\n  reverse(matrix.begin(), matrix.end());\n\n  return paths;\n}\n\nstruct State {\n  uintmax first, last;\n  Visits visits;\n  Distance distance;\n\n  /*\n   * Always make sure the locations (first and last) are sorted by id so we can\n   * avoid creating equivalent states, thus reducing the search space in half.\n   *\n   * E.g. A->B->C is equivalent to C->B->A.\n   */\n  State(uintmax f, uintmax l, Visits v, Distance d = {}):\n    first(std::min(f, l)),\n    last(std::max(f, l)),\n    visits(v),\n    distance(d) {};\n\n  // this will be called by the comparator of the priority queue in the A* search algorithm\n  auto operator<(const State& other) const {\n    const auto lhs = visits.to_ulong();\n    const auto rhs = other.visits.to_ulong();\n    return std::tie(first, last, lhs) < std::tie(other.first, other.last, rhs);\n  }\n\n  // this is required so we can use State as a key in an unordered map\n  auto operator==(const State& other) const {\n    return first == other.first\n           and last == other.last\n           and visits == other.visits;\n  }\n};\n\nnamespace std {\n  template<>\n  struct hash<State> {\n    auto operator()(const State& state) const {\n      return state.first\n             + (state.last << 8)\n             + (state.visits.to_ulong() << 16);\n    }\n  };\n}\n\n/*\n * An implementation of the A* search algorithm\n *\n * Score represents the total distance between the end points of any path.\n */\ntemplate<typename Score, typename Heuristic, typename Goal, typename Next>\nauto a_star(const State& start, Heuristic&& heuristic, Goal&& is_goal, Next&& for_each_neighbor) {\n\n  auto result = std::pair{start, Score{}};\n\n  // We need reverse ordering, so the smallest elements can be accessed first\n  const auto cmp = [](auto lhs, auto rhs) {\n    return lhs.first > rhs.first;\n  };\n\n  using T = std::pair<Score, State>;\n  using Container = std::vector<T>;\n  using Comparator = decltype(cmp);\n\n  auto queue = std::priority_queue<T, Container, Comparator>{cmp};\n\n  queue.emplace(heuristic(start), start);\n\n  auto scores = std::unordered_map<State, Score>{\n    {start, 0}\n  };\n\n  while(not queue.empty()) {\n\n    const auto [f_score, state] = queue.top();\n\n    queue.pop();\n\n    // A* uses the notation f = g + h, where f is a function of the sum of g and h\n    const auto g_score = scores[state];\n\n    if(f_score - heuristic(state) <= g_score) {\n\n      if(not is_goal(state)) {\n\n        const auto add_next = [&] (State next, Score distance) {\n\n          const auto new_score = (g_score + distance);\n\n          const auto next_not_found = [&scores, next] {\n              return (scores.find(next) == scores.end());\n          };\n\n          const auto new_score_is_better = [&scores, next, new_score] {\n            return new_score < scores[next];\n          };\n\n          if(next_not_found() or new_score_is_better()) {\n            scores[next] = new_score;\n            queue.emplace((new_score + heuristic(next)), next);\n          }\n        };\n\n        // We advance to a next state by adding a new place to either end of the current state\n        for_each_neighbor(state, add_next);\n\n      } else {\n        result = {state, g_score};\n        break;\n      }\n    }\n  }\n\n  return result;\n}\n\n/*\n * Adapted from https://stackoverflow.com/a/33181173\n *\n * Heap tracks the minimum k values.\n *\n * If the internal storage space is full, it will do a heap\n * sort which puts the maximum element in the heap at the top.\n *\n * A new value will only be inserted if it's smaller than the\n * top element. On insertion, the top element will be popped\n * off the heap, the new element inserted, and the next max\n * element put at the top.\n *\n */\ntemplate<typename T = double, typename U = uintmax>\nclass Heap {\n  private:\n    U k;\n  public:\n    std::vector<T> container;\n\n    Heap(U n) : k(n) {\n        container.reserve(k);\n    }\n\n    void insert(T value) {\n      const auto begin = container.begin();\n      const auto end   = container.end();\n\n      if(container.size() < k) {\n\n        container.push_back(value);\n\n        if (container.size() == k) {\n          std::make_heap(begin, end);\n        }\n\n      } else if(value < container.front()) {\n        // this is the equivalent of a heap_swift_down\n        std::pop_heap(begin, end);\n        container.back() = value;\n        std::push_heap(begin, end);\n      }\n    }\n};\n\nauto solution(std::string_view input) {\n\n  const auto paths = parse_input(input);\n\n  const auto lookup = [&paths] (auto x, auto y) {\n    return paths.lookup(x, y);\n  };\n\n  const auto inverse = [] (auto x) {\n    return (1.0 / x);\n  };\n\n  /*\n   * Estimates the lowest cost from the current location (State::first) to the goal.\n   *\n   * Note: A* with a heuristic of zero is equivalent to Dijkstra's search.\n   */\n  const auto heuristic = [&] (const auto& state) {\n\n    auto result = Distance{};\n\n    const auto visits = state.visits;\n    const auto num_visits  = visits.count();\n    const auto num_locations = paths.num_locations;\n\n    if(num_visits < num_locations) {\n      auto mins = Heap{num_locations - num_visits - 1};\n\n      // every state has visited the 0th location, because they have to start somewhere\n      // i represents the first endpoint of a path\n      for(const auto first : boost::irange({1}, num_locations)) {\n\n        if(not visits.test(first)) {\n\n          // j represents the other endpoint of a path\n          for(const auto last : boost::irange(first)) {\n\n            if(not visits.test(last)) {\n              mins.insert(inverse(lookup(first, last)));\n            }\n          }\n        }\n      }\n      const auto& heap = mins.container;\n      result = std::accumulate(heap.begin(), heap.end(), Distance{});\n    }\n    return result;\n  };\n\n  const auto is_goal = [&paths] (const auto& state) {\n    return (state.visits.count() == paths.num_locations);\n  };\n\n  /*\n   * Each state has a point of origin (first) and a destination (last). Both locations have\n   * a \"chain\" of sub-paths where they act as the point of origin, and the sub-paths show\n   * the distances to other destinations. A neighbor of a state is another state, and its\n   * locations (first and last) are the destinations from the aforementioned sub-paths that\n   * have not been visited yet.\n   *\n   * Every time for_each_neighbor is called, we check which of the sub-paths for which the\n   * locations of the passed state act as the point of origin have not been traveled yet. The\n   * destinations of those sub-paths will be part of the new state we construct (the neighbor),\n   * which will be used to repeat the process, but with different locations, until no subpaths\n   * remain.\n   */\n  const auto for_each_neighbor = [&] (const auto& state, auto&& callback) {\n\n    for(const auto id : boost::irange(paths.num_locations)) {\n\n      auto visits = state.visits;\n\n      const auto target_not_visited = (not visits.test(id));\n\n      if(target_not_visited) {\n\n        visits.set(id);\n\n        const auto first = state.first;\n        const auto last  = state.last;\n\n        const auto distance = state.distance;\n\n        const auto new_distance = [&] (auto location) {\n          return (lookup(location, id) + distance);\n        };\n\n        const auto last_distance  = new_distance(last);\n        const auto first_distance = new_distance(first);\n\n        /*\n         * A* will supply the callback function that will\n         * add the next possible state (neighbor) to explore\n         * to the queue\n         */\n        callback({first, id, visits, last_distance}, inverse(lookup(last, id)));\n        callback({id, last, visits, first_distance}, inverse(lookup(first, id)));\n      }\n    }\n  };\n\n  const auto begin_state = State{0, 0, 1};\n\n  return a_star<double>(begin_state, heuristic, is_goal, for_each_neighbor).first.distance;\n}\n\nint main() {\n\n  std::cout << solution(puzzle_input) << std::endl;\n\n}\n", "meta": {"hexsha": "79d6f76d482a62281dcbb5c3eef600a82c8fa493", "size": 11292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 09 Part 2/main_v4.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 09 Part 2/main_v4.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 09 Part 2/main_v4.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1388888889, "max_line_length": 98, "alphanum_fraction": 0.6315090329, "num_tokens": 2845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5570052702567294}}
{"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 (\u00eatre certain de l'ordre en temps et en espace)\n* chercher une autre source de bug qu'une erreur d'impl\u00e9mentation des sch\u00e9mas...\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": "//\n// Copyright (c) 2017 CNRS\n//\n// This file is part of tsid\n// tsid is free software: you can redistribute it\n// and/or modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation, either version\n// 3 of the License, or (at your option) any later version.\n// tsid is distributed in the hope that it will be\n// useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// General Lesser Public License for more details. You should have\n// received a copy of the GNU Lesser General Public License along with\n// tsid If not, see\n// <http://www.gnu.org/licenses/>.\n//\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\n#include <tsid/math/utils.hpp>\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE ( test_pseudoinverse)\n{\n  std::cout << \"test_pseudoinverse\\n\";\n  using namespace tsid::math;\n  const unsigned int m = 3;\n  const unsigned int n = 5;\n\n  Matrix A = Matrix::Random(m,n);\n  Matrix Apinv = Matrix::Zero(n,m);\n  pseudoInverse(A, Apinv, 1e-5);\n\n  BOOST_CHECK(Matrix::Identity(m,m).isApprox(A*Apinv));\n}\n\n\nBOOST_AUTO_TEST_SUITE_END ()\n", "meta": {"hexsha": "082b9d8efa145330919a72de06a1cd99ae212d8e", "size": 1238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_utils.cpp", "max_stars_repo_name": "hucebot/tsid", "max_stars_repo_head_hexsha": "b0d6bff80292fb3451ca7ca438a4ab84b5b8c022", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 74.0, "max_stars_repo_stars_event_min_datetime": "2017-10-19T08:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T16:31:17.000Z", "max_issues_repo_path": "tests/math_utils.cpp", "max_issues_repo_name": "hucebot/tsid", "max_issues_repo_head_hexsha": "b0d6bff80292fb3451ca7ca438a4ab84b5b8c022", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 123.0, "max_issues_repo_issues_event_min_datetime": "2017-06-16T14:10:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:04:32.000Z", "max_forks_repo_path": "tests/math_utils.cpp", "max_forks_repo_name": "hucebot/tsid", "max_forks_repo_head_hexsha": "b0d6bff80292fb3451ca7ca438a4ab84b5b8c022", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2017-11-24T15:11:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T11:10:34.000Z", "avg_line_length": 28.7906976744, "max_line_length": 71, "alphanum_fraction": 0.7326332795, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5569833159763184}}
{"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": "\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n#include <iostream>\n\n#include <bot_core/trans.h>\n\n\nstd::string print_Isometry3d(Eigen::Isometry3d pose){\n  Eigen::Vector3d t(pose.translation());\n  Eigen::Quaterniond r(pose.rotation());\n  \n  std::stringstream ss;\n  ss <<t[0]<<\", \"<<t[1]<<\", \"<<t[2]<<\", \" \n       <<r.w()<<\", \"<<r.x()<<\", \"<<r.y()<<\", \"<<r.z() ;\n  return ss.str();\n}\n\nstd::string print_BotTrans(BotTrans *bt){\n  std::stringstream ss;\n  ss << bt->trans_vec[0] <<\", \"<<bt->trans_vec[1]<<\", \"<<bt->trans_vec[2]<<\", \" \n       <<bt->rot_quat[0]<<\", \"<<bt->rot_quat[1]<<\", \"<<bt->rot_quat[2]<<\", \"<<bt->rot_quat[3] ;\n  return ss.str();\n}\n\nvoid setBotTrans(BotTrans *bt, double x, double y, double z, double qw, double qx, double qy, double qz){\n  bt->trans_vec[0] = x;  bt->trans_vec[1] = y;  bt->trans_vec[2] = z;\n  bt->rot_quat[0] = qw;  bt->rot_quat[1] = qx;\n  bt->rot_quat[2] = qy;  bt->rot_quat[3] = qz;  \n}\n\n\nEigen::Isometry3d setIsometry3dFromBotTrans(BotTrans *bt){\n  Eigen::Isometry3d tf;\n  tf.setIdentity();\n  tf.translation()  << bt->trans_vec[0], bt->trans_vec[1],bt->trans_vec[2];\n  Eigen::Quaterniond q = Eigen::Quaterniond(bt->rot_quat[0], bt->rot_quat[1], bt->rot_quat[2], bt->rot_quat[3]);  \n  tf.rotate(q); \n\n  return tf;\n}\n\nint \nmain(int argc, char ** argv){\n  \n   double trans_vec[] = {-2.7363, 0.5958, -1.1588};\n   double rot_quat[] = {0.8977, 0.0011, -9.0933e-04, -0.4407};\n  \n  BotTrans init_vicon, init_est, current_est;\n  setBotTrans(&init_vicon, 1.4696,  0.5235, 0.8753, 0.9749, -0.0108, 0.0076, 0.2221);\n  setBotTrans(&init_est, 2.1455, 1.8038, 1.1523, 0.8977, -0.0011, 9.0933e-04, 0.4407);\n  setBotTrans(&current_est, 2.1456, 1.8038, 1.1523, 0.8976, -0.0011, 9.2603e-04, 0.4407);\n  \n  Eigen::Isometry3d init_vicon_e = setIsometry3dFromBotTrans(&init_vicon);\n  Eigen::Isometry3d init_est_e = setIsometry3dFromBotTrans(&init_est);\n  Eigen::Isometry3d current_est_e = setIsometry3dFromBotTrans(&current_est);\n  \n  std::cout << print_Isometry3d(current_est_e) << \" current_est_e\\n\";  \n  std::cout << print_Isometry3d(init_est_e) << \" init_est_e\\n\";  \n  Eigen::Isometry3d init_est_e_inv = init_est_e.inverse();\n  std::cout << print_Isometry3d(init_est_e_inv) << \" init_est_e.inverse\\n\";    \n  \n  Eigen::Isometry3d delta_e =  init_est_e_inv * current_est_e;\n  std::cout << print_Isometry3d(delta_e) << \" delta_e\\n\";    \n  \n  \n  \n  BotTrans init_est_inv;\n  BotTrans* init_est_ptr = &init_est;\n  bot_trans_copy(&init_est_inv, init_est_ptr);\n  \n  \n  bot_trans_invert ( &init_est_inv );\n  \n  std::cout << print_BotTrans(&current_est) << \" current_est\\n\";    \n\n  \n  std::cout << print_BotTrans(&init_est_inv) << \" init_est_inv\\n\";    \n  \n  BotTrans delta;\n  BotTrans* delta_ptr = &current_est;\n  bot_trans_apply_trans( delta_ptr  ,  &init_est_inv );\n  std::cout << print_BotTrans(&current_est) << \" delta\\n\";    \n  \n  \n  return 0;\n}", "meta": {"hexsha": "62cb804f7e9ec30af56b9956e3017642185265be", "size": 2861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/perception/mfallon_sandbox/src/libbot_eigen_comparison/main.cpp", "max_stars_repo_name": "liangfok/oh-distro", "max_stars_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T21:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T17:57:46.000Z", "max_issues_repo_path": "software/perception/mfallon_sandbox/src/libbot_eigen_comparison/main.cpp", "max_issues_repo_name": "liangfok/oh-distro", "max_issues_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2016-01-16T18:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-24T15:16:28.000Z", "max_forks_repo_path": "software/perception/mfallon_sandbox/src/libbot_eigen_comparison/main.cpp", "max_forks_repo_name": "liangfok/oh-distro", "max_forks_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2016-01-14T21:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:10:39.000Z", "avg_line_length": 32.8850574713, "max_line_length": 114, "alphanum_fraction": 0.6473261098, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5569832836225537}}
{"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": "#define CATCH_CONFIG_MAIN\n\n#include \"CALPHADFreeEnergyFunctionsTernary.h\"\n#include \"InterpolationType.h\"\n\n#include \"catch.hpp\"\n\n#include <boost/optional/optional.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n\n#include <string>\n\n#include <omp.h>\n\nnamespace pt = boost::property_tree;\n\nTEST_CASE(\"CALPHAD ternary kks in a loop\", \"[ternary kks loop]\")\n{\n#ifdef _OPENMP\n    std::cout << \"Run test with \" << omp_get_max_threads() << \" threads\"\n              << std::endl;\n#endif\n\n    Thermo4PFM::EnergyInterpolationType energy_interp_func_type\n        = Thermo4PFM::EnergyInterpolationType::PBG;\n    Thermo4PFM::ConcInterpolationType conc_interp_func_type\n        = Thermo4PFM::ConcInterpolationType::PBG;\n\n    const double Tmin     = 2990;\n    const double Tmax     = 3020.;\n    const int nTintervals = 10;\n    const double deltaT   = (Tmax - Tmin) / (double)nTintervals;\n\n    std::cout << \"Read CALPHAD database...\" << std::endl;\n    pt::ptree calphad_db;\n    try\n    {\n        pt::read_json(\"../thermodynamic_data/calphadMoNbTa.json\", calphad_db);\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"exception caught: \" << e.what() << std::endl;\n    }\n\n    boost::optional<pt::ptree&> newton_db;\n\n    // initial guesses\n    const double init_guess[4] = { 0.33, 0.38, 0.32, 0.33 };\n    double nominalc[2]         = { 0.33, 0.33 };\n\n    std::vector<double> cl(2 * (nTintervals + 1));\n    std::vector<double> cs(2 * (nTintervals + 1));\n\n    Thermo4PFM::CALPHADFreeEnergyFunctionsTernary* cafe\n        = new Thermo4PFM::CALPHADFreeEnergyFunctionsTernary(calphad_db,\n            newton_db, energy_interp_func_type, conc_interp_func_type);\n\n    {\n        // serial loop\n        for (int i = 0; i < nTintervals + 1; i++)\n        {\n            const double temperature = Tmin + i * deltaT;\n\n            double phi = 0.5;\n\n            double conc[4] = { init_guess[0], init_guess[1], // liquid\n                init_guess[2], init_guess[3] }; // solid\n\n            // compute equilibrium concentrations in each phase\n            cafe->computePhaseConcentrations(temperature, nominalc, &phi, conc);\n\n            std::cout << \"Temperature = \" << temperature << std::endl;\n            std::cout << \"Concentrations: cl = (\" << conc[0] << \".\" << conc[1]\n                      << \")\"\n                      << \" and cs = (\" << conc[2] << \",\" << conc[3] << \")\"\n                      << std::endl;\n\n            cl[2 * i]     = conc[0];\n            cl[2 * i + 1] = conc[1];\n            cs[2 * i]     = conc[2];\n            cs[2 * i + 1] = conc[3];\n        }\n    }\n\n// parallel loop\n#pragma omp parallel for\n    for (int i = 0; i < nTintervals + 1; i++)\n    {\n        const double temperature = Tmin + i * deltaT;\n        double phi               = 0.5;\n\n        double conc[4] = { init_guess[0], init_guess[1], // liquid\n            init_guess[2], init_guess[3] }; // solid\n\n        // compute equilibrium concentrations in each phase\n        cafe->computePhaseConcentrations(temperature, nominalc, &phi, &conc[0]);\n\n        CHECK(conc[0] == Approx(cl[2 * i]).margin(1.e-6));\n        CHECK(conc[1] == Approx(cl[2 * i + 1]).margin(1.e-6));\n        CHECK(conc[2] == Approx(cs[2 * i]).margin(1.e-6));\n        CHECK(conc[3] == Approx(cs[2 * i + 1]).margin(1.e-6));\n    }\n\n#ifdef HAVE_OPENMP_OFFLOAD\n    double* xdev = new double[4 * (nTintervals + 1)];\n// clang-format off\n#pragma omp target map(to : cafe [0:1],     \\\n                            init_guess[:4]) \\\n                   map(from : xdev[:4 * (nTintervals + 1)])\n// clang-format on\n#pragma omp parallel for\n    for (int i = 0; i < nTintervals + 1; i++)\n    {\n        const double temperature = Tmin + i * deltaT;\n\n        double phi = 0.5;\n\n        xdev[4 * i + 0] = init_guess[0];\n        xdev[4 * i + 1] = init_guess[1]; // liquid\n        xdev[4 * i + 2] = init_guess[2];\n        xdev[4 * i + 3] = init_guess[3]; // solid\n        // compute equilibrium concentrations in each phase\n        cafe->computePhaseConcentrations(\n            temperature, nominalc, &phi, &xdev[4 * i]);\n    }\n\n    for (int i = 0; i < nTintervals + 1; i++)\n    {\n        std::cout << \"Device: x=\" << xdev[4 * i] << \",\" << xdev[4 * i + 1]\n                  << \",\" << xdev[4 * i + 2] << \",\" << xdev[4 * i + 3]\n                  << std::endl;\n        CHECK(xdev[4 * i + 0] == Approx(cl[2 * i]).margin(1.e-6));\n        CHECK(xdev[4 * i + 1] == Approx(cl[2 * i + 1]).margin(1.e-6));\n        CHECK(xdev[4 * i + 2] == Approx(cs[2 * i]).margin(1.e-6));\n        CHECK(xdev[4 * i + 3] == Approx(cs[2 * i + 1]).margin(1.e-6));\n    }\n\n    delete[] xdev;\n#endif\n\n    delete cafe;\n}\n", "meta": {"hexsha": "73c2332b3208c6187310d471d770482ce3e83cd5", "size": 4642, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/testLoopCALPHADternaryKKS.cc", "max_stars_repo_name": "TApplencourt/Thermo4PFM", "max_stars_repo_head_hexsha": "6e98249d1b871e017c4a15052aed9d00ec2d6d96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2022-01-21T17:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T21:00:24.000Z", "max_issues_repo_path": "tests/testLoopCALPHADternaryKKS.cc", "max_issues_repo_name": "TApplencourt/Thermo4PFM", "max_issues_repo_head_hexsha": "6e98249d1b871e017c4a15052aed9d00ec2d6d96", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-21T16:51:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T16:51:52.000Z", "max_forks_repo_path": "tests/testLoopCALPHADternaryKKS.cc", "max_forks_repo_name": "TApplencourt/Thermo4PFM", "max_forks_repo_head_hexsha": "6e98249d1b871e017c4a15052aed9d00ec2d6d96", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-13T14:29:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T18:12:51.000Z", "avg_line_length": 32.2361111111, "max_line_length": 80, "alphanum_fraction": 0.5420077553, "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5568886526508358}}
{"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": "/*!@file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Molassembler/Temple/Optimization/NelderMead.h\"\n\nusing namespace Scine::Molassembler;\n\nstruct NelderMeadHimmelblau {\n  double operator() (const Eigen::VectorXd& parameters) {\n    assert(parameters.size() == 2);\n\n    const double x = parameters(0);\n    const double y = parameters(1);\n\n    const double firstBracket = (x * x + y - 11);\n    const double secondBracket = (x + y * y - 7);\n\n    return firstBracket * firstBracket + secondBracket * secondBracket;\n  }\n};\n\nBOOST_AUTO_TEST_CASE(NelderMead, *boost::unit_test::label(\"Temple\")) {\n  Eigen::Matrix<double, 2, 3> simplexVertices;\n  simplexVertices << -3.0,  0.0,  0.0,\n                     -1.5,  0.0, -3.0;\n\n  struct NelderMeadChecker {\n    bool shouldContinue(unsigned iteration, double /* lowestValue */, double stddev) {\n      return iteration < 1000 && stddev > 0.01;\n    }\n  };\n\n  auto optimizationResult = Temple::NelderMead<>::minimize(\n    simplexVertices,\n    NelderMeadHimmelblau {},\n    NelderMeadChecker {}\n  );\n\n  BOOST_CHECK_MESSAGE(\n    std::fabs(optimizationResult.value) <= 0.1,\n    \"Nelder-Mead does not find minimization of Himmelblau function, value is \"\n    << optimizationResult.value << \" after \" << optimizationResult.iterations\n    << \" iterations. Simplex vertices are: \" << simplexVertices\n  );\n}\n", "meta": {"hexsha": "8a5072e9b6f7bb91710dc146b2f2e618d76e63c4", "size": 1516, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Temple/Optimization/NelderMead.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "test/Temple/Optimization/NelderMead.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Temple/Optimization/NelderMead.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 29.7254901961, "max_line_length": 86, "alphanum_fraction": 0.6794195251, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5568886456183517}}
{"text": "#ifndef __INS_HH__\n#define __INS_HH__\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (Describe the INS Module On Board, Error equations based on Zipfel,\nFigure 10.27, space stabilized INS with GPS updates) LIBRARY DEPENDENCY:\n      ((../src/Ins.cpp))\n*******************************************************************************/\n#include <armadillo>\n#include <cassert>\n#include <fstream>\n#include <functional>\n#include <tuple>\n#include \"Time_management.hh\"\n#include \"aux.hh\"\n#include \"cad_utility.hh\"\n#include \"dm_delta_ut.hh\"\n#include \"integrate.hh\"\n#include \"math_utility.hh\"\n#include \"matrix/utility.hh\"\n\nclass time_management;\n\nclass INS {\n  TRICK_INTERFACE(INS);\n\n public:\n  INS();\n\n  INS(const INS& other);\n\n  INS& operator=(const INS& other);\n\n  void initialize();\n\n  /* Internal Getter */\n  arma::mat build_WEII();\n\n  void load_location(double lonx, double latx, double alt);\n  void load_angle(double yaw, double roll, double pitch);\n  void load_geodetic_velocity(double alpha0x, double beta0x, double dvbe);\n  void calculate_INS_derived_TEI();\n\n  void update(double int_step);\n\n  void set_ideal();\n  void set_non_ideal();\n  void set_gps_correction(unsigned int index);\n  void set_liftoff(unsigned int index);\n\n  /* Input File */\n\n  std::function<arma::vec3()> grab_computed_WBIB;\n  std::function<arma::vec3()> grab_error_of_computed_WBIB;\n\n  std::function<arma::vec3()> grab_computed_FSPB;\n  std::function<arma::vec3()> grab_error_of_computed_FSPB;\n\n  // std::function<arma::vec3()>   grab_SBII;\n  // std::function<arma::vec3()>   grab_VBII;\n  // std::function<double()>       grab_dbi;\n  // std::function<arma::mat33()>  grab_TBI;\n  std::function<int()> grab_gps_update;\n  std::function<arma::vec3()> grab_SXH;\n  std::function<arma::vec3()> grab_VXH;\n  std::function<void()> clear_gps_flag;\n  // std::function<arma::mat33()>  grab_TEI;  // Only for testing\n  // std::function<arma::vec3()>   grab_SBEE;\n  // std::function<arma::vec3()>   grab_VBEE;\n  // std::function<double()>   grab_phibdx;\n  // std::function<double()>   grab_thtbdx;\n  // std::function<double()>   grab_psibdx;\n  std::function<arma::vec3()> grab_PHI;\n  std::function<arma::vec3()> grab_DELTA_VEL;\n  std::function<arma::vec3()> grab_PHI_HIGH;\n  std::function<arma::vec3()> grab_PHI_LOW;\n\n  double get_loncx();\n  double get_latcx();\n  double get_altc();\n  double get_dvbec();\n  double get_alphacx();\n  double get_betacx();\n  double get_phibdcx();\n  double get_thtbdcx();\n  double get_psibdcx();\n  double get_thtvdcx();\n  double get_phipcx();\n  double get_alppcx();\n\n  arma::vec3 get_SBIIC();\n  arma::vec3 get_VBIIC();\n  arma::vec3 get_WBICI();\n  arma::vec3 get_EGRAVI();\n  arma::mat33 get_TBIC();\n  arma::vec3 get_SBEEC();\n  arma::vec3 get_VBEEC();\n  arma::mat33 get_TEIC();\n  arma::vec4 get_TBDQ();\n  arma::mat33 get_TBD();\n  arma::mat33 get_TBICI();\n  arma::mat33 get_TDCI();\n  arma::vec3 get_WBECB();\n  arma::vec3 get_ABICB();\n\n  /* Internal Initializers */\n  void default_data();\n\n private:\n  arma::vec build_VBEB(double _alpha0x, double _beta0x, double _dvbe);\n\n  time_management* time;\n\n  /* Internal Propagator / Calculators */\n  bool GPS_update();\n\n  arma::vec3 calculate_INS_derived_postion(arma::vec3 SBII);\n  arma::vec3 calculate_INS_derived_velocity(arma::vec3 VBII);\n  arma::vec3 calculate_INS_derived_bodyrate(arma::mat33 TBIC, arma::vec3 WBICB);\n\n  arma::mat33 calculate_INS_derived_TBI(arma::mat33 TBI);\n\n  arma::vec3 calculate_gravity_error(double dbi);\n  double calculate_INS_derived_dvbe();\n\n  double calculate_INS_derived_alpha(arma::vec3 VBECB);\n  double calculate_INS_derived_beta(arma::vec3 VBECB);\n\n  double calculate_INS_derived_alpp(arma::vec3 VBECB);\n  double calculate_INS_derived_phip(arma::vec3 VBECB);\n\n  double calculate_INS_derived_psivd(arma::vec3 VBECD);\n  double calculate_INS_derived_thtvd(arma::vec3 VBECD);\n\n  void calculate_INS_derived_euler_angles(arma::mat33 TBD);\n\n  void load_angle();\n  void propagate_TBI_Q(double int_step, arma::vec3 WBICB);\n\n  // void error_diagnostics();\n  // For test\n  arma::vec3 euler_angle(arma::mat33 TBD);\n  arma::mat33 build_321_rotation_matrix(arma::vec3 angle);\n\n  arma::vec AccelHarmonic(arma::vec3 SBII, double CS[21][21], int n_max,\n                          int m_max, arma::mat33 TEIC);\n\n  /* Internal Calculators */\n\n  /* Sensors */\n\n  /* Constants */\n  arma::mat WEII;     /* *o  (r/s)    Earth's angular velocity (skew-sym) */\n  double _WEII[3][3]; /* *o  (r/s)    Earth's angular velocity (skew-sym) */\n\n  /* Propagative Stats */\n  arma::vec EVBI;  /* *o  (m/s)   INS vel error */\n  double _EVBI[3]; /* *o  (m/s)   INS vel error */\n\n  arma::vec EVBID;  /* *o  (m/s)   INS vel error derivative */\n  double _EVBID[3]; /* *o  (m/s)   INS vel error derivative */\n\n  arma::vec ESBI;  /* *o  (m)     INS pos error */\n  double _ESBI[3]; /* *o  (m)     INS pos error */\n\n  arma::vec ESBID;  /* *o  (m)     INS pos error derivative */\n  double _ESBID[3]; /* *o  (m)     INS pos error derivative */\n\n  arma::vec RICI;  /* *o  (r)     INS tilt error derivative */\n  double _RICI[3]; /* *o  (r)     INS tilt error */\n\n  arma::vec RICID;  /* *o  (r)     INS tilt error derivative */\n  double _RICID[3]; /* *o  (r)     INS tilt error derivative */\n\n  /* Generating Outputs */\n  arma::mat TBIC; /* *o  (--)    Computed T.M. of body wrt inertia coordinate */\n  double _TBIC[3][3]; /* *o  (--)    Computed T.M. of body wrt inertia\n                         coordinate */\n\n  arma::vec TBIC_Q;  /* *o  (--)    Computed T.M of body wrt inertia coordinate\n                        quaterion */\n  double _TBIC_Q[4]; /* *o  (--)    Computed T.M of body wrt inertia coordinate\n                        quaterion */\n\n  arma::vec TBIDC_Q;  /* *io (--)    Transformation Matrix of body coord wrt\n                         inertia coord derivative (Quaternion) */\n  double _TBIDC_Q[4]; /* *io (--)    Transformation Matrix of body coord wrt\n                         inertia coord derivative (Quaternion) */\n\n  arma::vec\n      SBIIC; /* *o  (m)     Computed pos of body wrt inertia reference point*/\n  double _SBIIC[3]; /* *o  (m)     Computed pos of body wrt inertia reference\n                       point*/\n\n  arma::vec VBIIC;  /* *o  (m/s)   Computed body vel in inertia coor */\n  double _VBIIC[3]; /* *o  (m/s)   Computed body vel in inertia coor */\n\n  arma::vec SBEEC;  /* *o   (m)    Computed body position in ECEF */\n  double _SBEEC[3]; /* *o   (m)    Computed body position in ECEF */\n\n  arma::vec VBEEC;  /* *o   (m)    Computed body velocity in ECEF */\n  double _VBEEC[3]; /* *o   (m)    Computed body velocity in ECEF */\n\n  arma::vec\n      WBICI; /* *o  (r/s)   Computed inertial body rate in inert coordinate */\n  double _WBICI[3]; /* *o  (r/s)   Computed inertial body rate in inert\n                       coordinate */\n\n  arma::vec EGRAVI;  /* *o  (--)    error by gravity */\n  double _EGRAVI[3]; /* *o  (--)    error by gravity */\n\n  arma::vec VBECD;  /* *o  (m/s)   Geodetic velocity */\n  double _VBECD[3]; /* *o  (m/s)   Geodetic velocity */\n\n  arma::mat TDCI;     /* *o  (--)    Comp T.M. of geodetic wrt inertial */\n  double _TDCI[3][3]; /* *o  (--)    Comp T.M. of geodetic wrt inertial */\n\n  arma::mat TEIC;     /* *o  (--)   T.M. of inertia to ECEF */\n  double _TEIC[3][3]; /* *o  (--)   T.M. of inertia to ECEF */\n\n  arma::vec INS_I_ATT_ERR;\n  double _INS_I_ATT_ERR[3];\n\n  arma::vec TESTV;\n  double _TESTV[3];\n\n  arma::vec TMP_old;\n  double _TMP_old[3];\n\n  arma::vec VBIIC_old;\n  double _VBIIC_old[3];\n\n  arma::vec POS_ERR;\n  double _POS_ERR[3];\n\n  arma::vec GRAVGI;  /* *o (m/s2)  Gravity acceleration wrt inertial frame */\n  double _GRAVGI[3]; /* *o (m/s2)  Gravity acceleration wrt inertial frame */\n\n  arma::vec TBDQ;\n  double _TBDQ[4];\n\n  arma::mat TBD;\n  double _TBD[3][3];\n\n  arma::mat TBICI;\n  double _TBICI[3][3];\n\n  arma::mat TLI;\n  double _TLI[3][3];\n\n  arma::vec VBIIC_old_old;\n  double _VBIIC_old_old[3];\n\n  VECTOR(WBECB, 3); /* ** (r/s)  Body angular rate in ECEF */\n\n  VECTOR(ABICB, 3); /* **  (m/s2) Computed body net acceleration */\n\n  double\n      dbic; /* *io  (m)     INS computed vehicle distance from Earth center */\n  double dvbec; /* *io  (m/s)   Computed body speed wrt earth */\n\n  double alphacx; /* *io  (d)     INS computed angle of attack */\n  double betacx;  /* *io  (d)     INS computed sideslip angle */\n\n  double thtvdcx; /* *io  (d)     INS computed vertical flight path angle */\n  double psivdcx; /* *io  (d)     INS computed heading angle */\n\n  double alppcx; /* *io  (d)     INS computed total angle of attack */\n  double phipcx; /* *io  (d)     INS computed aero roll angle */\n\n  double loncx; /* *io  (d)     INS derived longitude */\n  double latcx; /* *io  (d)     INS derived latitude */\n  double altc;  /* *io  (m)     INS derived altitude */\n\n  double phibdcx; /* *io  (d)     INS computed geodetic Euler roll angle */\n  double thtbdcx; /* *io  (d)     INS computed geodetic Euler pitch angle */\n  double psibdcx; /* *io  (d)     INS computed geodetic Euler yaw angle */\n\n  /* Non-propagating Diagnostic Variables */\n  /* These can be deleted, but keep to remain trackable in trick simulator */\n\n  double ins_pos_err;     /* *io  (m)     INS absolute postion error */\n  double ins_vel_err;     /* *io  (m/s)   INS absolute velocity error */\n  double ins_tilt_err;    /* *o  (r)     INS absolute tilt error */\n  double ins_pose_err;    /* *io  (m)     INS absolute postion error */\n  double ins_vele_err;    /* *io  (m/s)   INS absolute velocity error */\n  double ins_phi_err;     /* *o (d)      INS absolute phi angle error */\n  double ins_tht_err;     /* *o (d)     INS absolute tht angle error */\n  double ins_psi_err;     /* *o  (d)     INS absolute psi angle error */\n  unsigned int gpsupdate; /* *o (--)   Set wether use gps correction or not */\n  unsigned int liftoff;   /* *o (--)  set LV liftoff */\n  unsigned int ideal; /* *o (--)  choose which extropolate algorithm to use */\n\n  unsigned int testindex;\n};\n\n#endif  // __INS_HH__\n", "meta": {"hexsha": "16e99bef860e8ea90955188ad9844d67dd8958b1", "size": 9984, "ext": "hh", "lang": "C++", "max_stars_repo_path": "models/gnc/include/Ins.hh", "max_stars_repo_name": "cihuang123/Next-simulation", "max_stars_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/gnc/include/Ins.hh", "max_issues_repo_name": "cihuang123/Next-simulation", "max_issues_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/gnc/include/Ins.hh", "max_forks_repo_name": "cihuang123/Next-simulation", "max_forks_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_forks_repo_licenses": ["BSD-3-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.5033557047, "max_line_length": 80, "alphanum_fraction": 0.6284054487, "num_tokens": 3064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5568886409149679}}
{"text": "#include <cmath>\n#include <exception>\n#include <iostream>\n#include <string>\n#include <boost/algorithm/string.hpp>\n\nclass NucPepXform\n{\n    std::string baseDNA = \"ACGT\";\n    std::string baseRNA = \"ACGU\";\n    std::string basePEP = \"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV.Y.YSSSS.CWCLFLF\";\n\n\n    int strToInt(std::string inStr, std::string inBase)\n    {\n        int retNum = 0;\n        for (auto i: inStr)\n        {\n            retNum += pow(inBase.length(), inStr.length()-i-1) * (inBase.at(inStr.at(i)));\n        }\n\n        return retNum;\n     };\n\n\n    std::string intToStr(int inInt, std::string outBase, int maxDigits)\n    {\n        int remainder = inInt;\n        std::string retStr = \"\";\n\n        for (int i = maxDigits; i >= 0; --i)\n        {\n            retStr += outBase.at(trunc(remainder / (int)pow(outBase.length(), i)));\n            remainder = trunc(remainder % (int)pow(outBase.length(), i));\n        }\n\n        return retStr;\n    };\n\n\n    std::string verify(std::string inStr, std::string strBase)\n    {\n        boost::to_upper(inStr);\n        std::string outStr = \"\";\n\n        for (auto i: inStr)\n        {\n            if (strBase.find(inStr.at(i)) >=0)\n            { \n                outStr += inStr.at(i);\n            } else {\n                std::cout << inStr.at(i) << \": invalid character, removing from value.\" << std::endl;\n            };\n        };\n\n        return outStr;\n    };\n\n\n    std::string transcribe(std::string DNAseq)\n    {\n        std::string DNAstr = verify(DNAseq, baseDNA);\n        std::string RNAstr = \"\";\n\n        for (auto i: DNAstr)\n        {\n            RNAstr += intToStr(strToInt(&DNAstr.at(i), baseDNA), baseRNA, 0);\n        };\n\n        return RNAstr;\n    };\n\n\n    std::string revTranscribe(std::string RNAseq)\n    {\n        std::string RNAstr = verify(RNAseq, baseRNA);\n        std::string DNAstr = \"\";\n\n        for (auto i: RNAstr)\n        {\n            DNAstr += intToStr(strToInt(&RNAstr.at(i), baseRNA), baseDNA, 0);\n        };\n\n        return DNAstr;\n    };\n\n\n    std::string translate(std::string RNAseq)\n    {\n        std::string RNAstr = verify(RNAseq, baseRNA);\n        std::string peptide = \"\";\n        std::string codon = \"123\";\n\n        for (int i=0; i<(int)RNAseq.length(); ++i)\n        {\n            codon = RNAstr.substr(i, i+codon.length());\n            peptide += intToStr(strToInt(codon, baseRNA), basePEP, 0);\n\n        };\n\n        return peptide;\n    };\n};\n\n", "meta": {"hexsha": "6928d1f4aa48e929838955de06892cca15ed7460", "size": 2432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "parser/nucPepXform.cpp", "max_stars_repo_name": "BMJHayward/navtome", "max_stars_repo_head_hexsha": "6d2ed87bf551f00520600c9f6f742b9eef9abe05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "parser/nucPepXform.cpp", "max_issues_repo_name": "BMJHayward/navtome", "max_issues_repo_head_hexsha": "6d2ed87bf551f00520600c9f6f742b9eef9abe05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-19T09:55:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-19T09:55:53.000Z", "max_forks_repo_path": "parser/nucPepXform.cpp", "max_forks_repo_name": "BMJHayward/navtome", "max_forks_repo_head_hexsha": "6d2ed87bf551f00520600c9f6f742b9eef9abe05", "max_forks_repo_licenses": ["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.1619047619, "max_line_length": 101, "alphanum_fraction": 0.5238486842, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.63341024983754, "lm_q1q2_score": 0.5568605656294818}}
{"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 \"CalibrationTool.h\"\n\n#include <Eigen/Dense>\n#include <fstream>\n#include <iostream>\n\nnamespace echobot {\n\n\nvoid CalibrationTool::calibrate() {\n\n}\n\nEigen::Affine3d CalibrationTool::loadCalFile(std::string path) {\n    auto calMat = Eigen::Affine3d::Identity();\n    std::ifstream inFile;\n    inFile.open(path);\n\n    if(inFile.is_open())\n    {\n        for(int row = 0; row < calMat.rows(); row++){\n            for(int col = 0; col < calMat.cols(); col++)\n            {\n                double item = 0;\n                inFile >> item;\n                calMat(row, col) = item;\n            }\n        }\n        inFile.close();\n    }\n    return calMat;\n}\n\nvoid CalibrationTool::saveCalFile(std::string path, Eigen::Affine3d calMat) {\n    std::ofstream outFile;\n    outFile.open(path);\n\n    if(outFile.is_open()){\n        outFile << calMat.matrix();\n        outFile.close();\n    }\n}\n\nCalibrationTool::CalibrationTool() {\n    mCalibrationFilePath = Config::getConfigPath() + \"calibration/\";\n    m_rMb = loadCalFile(mCalibrationFilePath + \"camMbase.cal\");\n    m_eeMt = loadCalFile(mCalibrationFilePath + \"eeMtool.cal\");\n    m_tMus = loadCalFile(mCalibrationFilePath + \"toolMus.cal\");\n    m_registration_pcMdata = loadCalFile(mCalibrationFilePath + \"registration_pcMdata.cal\");\n    m_registration_pcMt = loadCalFile(mCalibrationFilePath + \"registration_pcMt.cal\");\n    std::cout << m_registration_pcMdata.matrix() << std::endl;\n}\n\nvoid CalibrationTool::set_rMb(Eigen::Affine3d mat) {\n    m_rMb = mat;\n}\n\nvoid CalibrationTool::set_eeMt(Eigen::Affine3d mat) {\n    m_eeMt = mat;\n}\n\nvoid CalibrationTool::set_tMus(Eigen::Affine3d mat) {\n    m_tMus = mat;\n}\n\nvoid CalibrationTool::set_registration_pcMdata(Eigen::Affine3d mat) {\n    m_registration_pcMdata = mat;\n}\n\nvoid CalibrationTool::set_registration_pcMt(Eigen::Affine3d mat) {\n    m_registration_pcMt = mat;\n}\n\nEigen::Affine3d CalibrationTool::get_registration_pcMdata(){\n    std::cout << m_registration_pcMdata.matrix() << std::endl;\n    return m_registration_pcMdata;\n}\n\n}\n\n", "meta": {"hexsha": "fc48a85bf6fab78b51820f6ea11dc81e7eb86e94", "size": 2022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/EchoBot/Utilities/CalibrationTool.cpp", "max_stars_repo_name": "SINTEFMedtek/EchoBot", "max_stars_repo_head_hexsha": "ce08f2d81cb7a2b4236068bff6eab6de56731632", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-06-21T10:23:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T09:36:02.000Z", "max_issues_repo_path": "source/EchoBot/Utilities/CalibrationTool.cpp", "max_issues_repo_name": "SINTEFMedtek/EchoBot", "max_issues_repo_head_hexsha": "ce08f2d81cb7a2b4236068bff6eab6de56731632", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-05T09:48:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-05T09:48:15.000Z", "max_forks_repo_path": "source/EchoBot/Utilities/CalibrationTool.cpp", "max_forks_repo_name": "SINTEFMedtek/EchoBot", "max_forks_repo_head_hexsha": "ce08f2d81cb7a2b4236068bff6eab6de56731632", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-25T23:48:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-25T23:48:21.000Z", "avg_line_length": 24.962962963, "max_line_length": 92, "alphanum_fraction": 0.6641938675, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5568540886945965}}
{"text": "#define BOOST_TEST_MODULE TS test\n#include <boost/test/unit_test.hpp>\n#include \"Sum.h\"\n#include \"Variable.h\"\n#include \"System.h\"\n\n\nusing namespace omnn::math;\nusing namespace boost::unit_test;\n\ntemplate<typename T>\nT bits(T v){\n    T bits = 0;\n    while (v) {\n        ++bits;\n        v = v >> 1;\n    }\n    return bits;\n}\n\nBOOST_AUTO_TEST_CASE(TS_1d)\n{\n//    System s;\n//    s.MakeTotalEqu(true);\n    // y=f(x), where x is code of sequence\n    Variable time, price;\n    int points[] = {\n        10,1,30,5\n    };\n    int sz = std::size(points);\n    int encodeBits = bits(sz);\n    int mask = (1 << encodeBits) - 1;\n\n    auto sys = 0_v;\n\n    // points math data\n    Variable x;\n    auto ExtractMove = [&](int i){\n        auto targetId = x.And((i+1)*encodeBits,mask<<(i*encodeBits)).shr(i*encodeBits);\n        return targetId;\n    };\n    // last move back to start\n    auto statement = ExtractMove(sz-1).Equals(0);\n//    s << statement;\n    sys.logic_and(statement);\n    // moves uniqueness\n    for (int i=1; i<sz; ++i) {\n        statement = ExtractMove(i).NotEquals(ExtractMove(i-1));\n//        s << statement;\n        sys.logic_and(statement);\n    }\n    // generate function of getting point value by its index\n    auto ValueByIdx=[&](Valuable i){\n        Variable id;\n        static auto MathDataForm = [&](){\n            auto data = 1_v;\n            Variable val;\n            for (int i=0; i<sz; ++i) {\n                data.logic_or(id.Equals(i).LogicAnd(val.Equals(points[i])));\n            }\n            return data(val);\n        };\n        \n        static auto data = MathDataForm();\n        \n        auto localData = data;\n        localData.Eval(id, i);\n        return localData;\n    };\n    // move len square\n    auto MoveLenSq=[&](int i)\n    {\n        assert(i);\n        auto prev = ExtractMove(i-1);\n        auto target = ExtractMove(i);\n        auto diff = ValueByIdx(prev)-ValueByIdx(target);\n        return diff ^ 2;\n    };\n    auto SumSqLens = [&](){\n        auto sum = 0_v;\n        for (int i=1; i<sz; ++i)\n            sum+=MoveLenSq(i);\n        return sum;\n    };\n    auto sumSqLens=SumSqLens();\n}\n\n\nBOOST_AUTO_TEST_CASE(TS_2d\n                     ,*disabled()\n                     )\n{\n\tVariable time, price;\n    std::pair<Valuable,Valuable> points[] = {\n\t\t{0,0},\n\t\t{1,5},\n\t\t{3,8},\n\t};\n\tauto bits = 2;\n\n\tVariable xpath, ypath;\n    Variable xmove[std::size(points)], ymove[std::size(points)];\n//\n//    auto unix = xpath.equals((xmove[0] << (2 * 2)) + (xmove[1] << 2) + xmove[2]);\n//    auto uniy = ypath.equals((xmove[0] << (2 * 2)) + (xmove[1] << 2) + xmove[2]);\n\n//    auto xext = unix(\n    \nIMPLEMENT\n}\n", "meta": {"hexsha": "f11210de4fc7eac9b6593dfec1fdd12f3cab604a", "size": 2617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/test/ts.cpp", "max_stars_repo_name": "ApusDT/openmind", "max_stars_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-08-13T18:46:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T14:18:10.000Z", "max_issues_repo_path": "omnn/math/test/ts.cpp", "max_issues_repo_name": "SergMariaDB/openmind", "max_issues_repo_head_hexsha": "98ad7f1c2c5c02d41418c7f9af25876342270d25", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2017-11-26T12:42:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T09:38:33.000Z", "max_forks_repo_path": "omnn/math/test/ts.cpp", "max_forks_repo_name": "SergMariaDB/openmind", "max_forks_repo_head_hexsha": "98ad7f1c2c5c02d41418c7f9af25876342270d25", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-08-28T07:00:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T19:59:55.000Z", "avg_line_length": 23.5765765766, "max_line_length": 87, "alphanum_fraction": 0.5357279327, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857831, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5568141359591985}}
{"text": "#include <iostream>\n#include <stdio.h>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <Eigen/Core>\n\n/*\n * A benchmark to test performance of calculating determinants of \n * 6x6 matrices with the Eigen linear algebra package.\n */\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char * argv[])\n{\n  if (argc != 3 || strcmp(argv[1], \"-h\") == 0)\n  {\n    cout << \"Usage: ./eigDeterm N_MATRIX(<=1000) ITERATIONS(~1000)\"\n      << endl;\n    return 1;\n  }\n\n  srand(time(NULL));\n  int MAT_DIM = 6;\n  int N_MATRIX = atoi(argv[1]);\n  int ITERATIONS = atoi(argv[2]);\n  int i, j, k, count;\n  double start, end, t_time = 0.0;\n\n  printf(\"N_MATRIX: %d, ITERATIONS: %d\\n\", N_MATRIX, ITERATIONS);\n\n  //Setting up array of matrices\n  MatrixXd *m_list = new MatrixXd[N_MATRIX];\n\n  //Initialise each matrix in m_list as random 6x6 matrices\n  for (i=0; i<N_MATRIX; i++)\n  {\n    m_list[i] = MatrixXd::Random(MAT_DIM, MAT_DIM);\n  }\n\n  start = (double)clock() / (double) CLOCKS_PER_SEC;\n  \n  //Calculating determinants of matrices\n  for(i=0; i<ITERATIONS; i++)\n  {\n    for(j=0; j<N_MATRIX; j++)\n    {\n    volatile double determinant;\n    determinant = m_list[j].determinant();\n    }\n  }\n  end = (double)clock() / (double) CLOCKS_PER_SEC;\n\n  cout << \"Total CPU time: \" << end - start << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "ff5e4726d6c26116f851d575a2884b69a4e7de62", "size": 1302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/matrix_library_tests/eigDetermBeta.cpp", "max_stars_repo_name": "tcrundall/chronostar", "max_stars_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-28T11:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T01:13:11.000Z", "max_issues_repo_path": "benchmarks/matrix_library_tests/eigDetermBeta.cpp", "max_issues_repo_name": "tcrundall/chronostar", "max_issues_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2019-08-14T07:30:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T23:44:29.000Z", "max_forks_repo_path": "benchmarks/matrix_library_tests/eigDetermBeta.cpp", "max_forks_repo_name": "tcrundall/chronostar", "max_forks_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-21T08:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T06:53:52.000Z", "avg_line_length": 22.0677966102, "max_line_length": 67, "alphanum_fraction": 0.6351766513, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.556814119733506}}
{"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_ASECD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ASECD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the inverse secant\n    in degree: \\f$(180/\\pi) \\arccos(1/x)\\f$.\n\n    @par Header <boost/simd/function/asecd.hpp>\n\n    @see asec,  asecpi\n\n    @par Example:\n\n      @snippet asecd.cpp asecd\n\n    @par Possible output:\n\n      @snippet asecd.txt asecd\n\n  **/\n  IEEEValue asecd(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/asecd.hpp>\n#include <boost/simd/function/simd/asecd.hpp>\n\n#endif\n", "meta": {"hexsha": "24067673e03a43478d75aa97b269c9fa36070ae9", "size": 1031, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/asecd.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/asecd.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/asecd.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.4318181818, "max_line_length": 100, "alphanum_fraction": 0.5722599418, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5568141194879248}}
{"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": "#pragma once\n\n/* Type lattice */\n\n#include <crab/domains/lattice_domain.hpp>\n#include <crab/support/os.hpp>\n#include <crab/types/variable.hpp>\n\n#include <boost/optional.hpp>\n#include <string>\n\nnamespace crab {\nnamespace domains {\n/**\n *  Lattice for variable types which is almost flat except regions\n *  that can be unknown. An unknown region unifies with any other\n *  region.\n *\n *  Num    = bool | int | real\n *  Scalar = Num | reference\n * \n *                 -------- top\n *                /         /   \\\n *               /         /    region(unknown)-------- \n *              /         /           |                |\n *            Scalar array(Num)    region(Scalar) region(array(Num))\n *               |          \\      /                   |\n *               ---------- bottom----------------------\n *\n **/\nclass type_value: public lattice_domain_api<type_value> {\n  \n  boost::optional<variable_type> m_type;\n  bool m_is_bottom;\n  \n  type_value(bool is_bottom);\n  \npublic:\n\n  type_value();\n  \n  type_value(variable_type ty);\n\n  static type_value bottom();\n\n  static type_value top();\n\n  type_value make_top() const override;\n\n  type_value make_bottom() const override;\n\n  void set_to_top() override;\n\n  void set_to_bottom() override;\n  \n  bool is_bottom() const override;\n\n  bool is_top() const override;\n\n  bool operator<=(const type_value &o) const override;\n\n  bool operator==(const type_value &o) const;\n\n  void operator|=(const type_value &o) override;\n  \n  type_value operator|(const type_value &o) const override;\n\n  type_value operator||(const type_value &o) const override;\n\n  template <typename Thresholds>\n  type_value widening_thresholds(const type_value &o,\n\t\t\t\t const Thresholds &ts /*unused*/) const;\n\n  type_value operator&(const type_value &o) const override;\n\n  type_value operator&&(const type_value &o) const override;\n\n  variable_type get() const;\n\n  void set(variable_type ty);\n    \n  void write(crab::crab_os &o) const override;\n\n  friend inline crab_os &operator<<(crab_os &o, const type_value &c) {\n    c.write(o);\n    return o;\n  }\n\n  std::string domain_name() const override;\n  \n};\n} // namespace domains\n} // namespace crab\n", "meta": {"hexsha": "1202cf4a860772235d8d274bfc7d8107821ba533", "size": 2162, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/types.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/types.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/types.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": 23.0, "max_line_length": 70, "alphanum_fraction": 0.6184088807, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5567988120716669}}
{"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": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_histogram_projection\n\n#include <boost/histogram.hpp>\n#include <cassert>\n#include <iostream>\n#include <sstream>\n\nint main() {\n  using namespace boost::histogram;\n  using namespace literals; // enables _c suffix\n\n  // make a 2d histogram\n  auto h = make_histogram(axis::regular<>(3, -1.0, 1.0), axis::integer<>(0, 2));\n\n  h(-0.9, 0);\n  h(0.9, 1);\n  h(0.1, 0);\n\n  auto hr0 = algorithm::project(h, 0_c); // keep only first axis\n  auto hr1 = algorithm::project(h, 1_c); // keep only second axis\n\n  // reduce does not remove counts; returned histograms are summed over\n  // the removed axes, so h, hr0, and hr1 have same number of total counts;\n  // we compute the sum of counts with the sum algorithm\n  assert(algorithm::sum(h) == 3 && algorithm::sum(hr0) == 3 && algorithm::sum(hr1) == 3);\n\n  std::ostringstream os1;\n  for (auto x : indexed(h))\n    os1 << \"(\" << x.index(0) << \", \" << x.index(1) << \"): \" << *x << \"\\n\";\n  std::cout << os1.str() << std::flush;\n  assert(os1.str() == \"(0, 0): 1\\n\"\n                      \"(1, 0): 1\\n\"\n                      \"(2, 0): 0\\n\"\n                      \"(0, 1): 0\\n\"\n                      \"(1, 1): 0\\n\"\n                      \"(2, 1): 1\\n\");\n\n  std::ostringstream os2;\n  for (auto x : indexed(hr0)) os2 << \"(\" << x.index(0) << \", -): \" << *x << \"\\n\";\n  std::cout << os2.str() << std::flush;\n  assert(os2.str() == \"(0, -): 1\\n\"\n                      \"(1, -): 1\\n\"\n                      \"(2, -): 1\\n\");\n\n  std::ostringstream os3;\n  for (auto x : indexed(hr1)) os3 << \"(- ,\" << x.index(0) << \"): \" << *x << \"\\n\";\n  std::cout << os3.str() << std::flush;\n  assert(os3.str() == \"(- ,0): 2\\n\"\n                      \"(- ,1): 1\\n\");\n}\n\n//]\n", "meta": {"hexsha": "4f5985831cec45de2521a9385dd47b9448eba2e8", "size": 1871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/guide_histogram_projection.cpp", "max_stars_repo_name": "henryiii/histogram", "max_stars_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2020-12-21T05:14:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T11:27:32.000Z", "max_issues_repo_path": "examples/guide_histogram_projection.cpp", "max_issues_repo_name": "henryiii/histogram", "max_issues_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T11:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T13:40:06.000Z", "max_forks_repo_path": "examples/guide_histogram_projection.cpp", "max_forks_repo_name": "henryiii/histogram", "max_forks_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2020-12-22T09:40:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T18:16:00.000Z", "avg_line_length": 31.7118644068, "max_line_length": 89, "alphanum_fraction": 0.5189738108, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.556798809775039}}
{"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": "#ifndef JOINT_HPP\n#define JOINT_HPP\n#include <armadillo>\n#include \"Math.hpp\"\n#include \"Body.hpp\"\n#include <boost/shared_ptr.hpp>\n#include <boost/enable_shared_from_this.hpp>\n\n\nclass Joint : public boost::enable_shared_from_this<Joint>\n{\npublic:\n    Joint(unsigned int TypeIn, arma::vec piIn, arma::vec pjIn, arma::vec qiIn,\n            arma::vec qjIn, BodyPtr i_In, BodyPtr j_In);\n    ~Joint() {};\n    void Build_C();\n    void Build_Cq();\n    void Build_GAMMA();\n    void update();\n\n    arma::mat get_Cqi();\n    arma::mat get_Cqj();\n    arma::vec get_GAMMA();\n    arma::vec get_Pi();\n    arma::vec get_Pj();\n    arma::vec get_pi();\n    arma::vec get_pj();\n    arma::vec get_CONSTRAINT();\n    BodyPtr get_body_i_ptr();\n    BodyPtr get_body_j_ptr();\n\nprivate:\n    unsigned int Type;  \n    arma::vec pi;\n    arma::vec pj;\n    arma::vec qi;\n    arma::vec qj;\n    arma::mat Cqi;\n    arma::mat Cqj;\n    arma::vec GAMMA;\n    arma::vec CONSTRAINT;\n    arma::mat TBI_i;\n    arma::mat TBI_j;\n    arma::vec Pi;\n    arma::vec Pj;\n    arma::vec Qi;\n    arma::vec Qj;\n    arma::vec wi;\n    arma::vec wj;\n    arma::vec Si;\n    arma::vec Sj;\n    BodyPtr body_i_ptr;\n    BodyPtr body_j_ptr;\n};\n\ntypedef boost::shared_ptr<Joint> JointPtr;\n#endif  //JOINT_HPP", "meta": {"hexsha": "01b5d7827d7e1f36f5a81011628930c2ad0a18a7", "size": 1240, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Joint.hpp", "max_stars_repo_name": "octoberskyTW/Multibody-Dynamics-Solver", "max_stars_repo_head_hexsha": "67b0ea9f6cfbed9e9cf8f048b7e35b620b9aeb4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-17T03:06:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T03:06:47.000Z", "max_issues_repo_path": "include/Joint.hpp", "max_issues_repo_name": "octoberskyTW/Multibody-Dynamics-Solver", "max_issues_repo_head_hexsha": "67b0ea9f6cfbed9e9cf8f048b7e35b620b9aeb4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Joint.hpp", "max_forks_repo_name": "octoberskyTW/Multibody-Dynamics-Solver", "max_forks_repo_head_hexsha": "67b0ea9f6cfbed9e9cf8f048b7e35b620b9aeb4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-31T13:05:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T13:05:36.000Z", "avg_line_length": 21.7543859649, "max_line_length": 78, "alphanum_fraction": 0.6274193548, "num_tokens": 371, "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": "#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n#include \"ceinms2/Types.h\"\n#include \"ceinms2/NMSmodel.h\"\n#include \"ceinms2/ElectromechanicalDelay.h\"\n#include \"ceinms2/ExponentialActivation.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace ceinms;\n\nint testMatrix() {\n    MatrixXd m(2, 2);\n    m(0, 0) = 3;\n    m(1, 0) = 2.5;\n    m(0, 1) = -1;\n    m(1, 1) = m(1, 0) + m(0, 1);\n    std::cout << \"Here is the matrix m:\\n\" << m << std::endl;\n    VectorXd v(2);\n    v(0) = 4;\n    v(1) = v(0) - 1;\n    std::cout << \"Here is the vector v:\\n\" << v << std::endl;\n    return 0;\n}\n\n\nint main() {\n    size_t N = 10, M = 10;\n    using EMGMapping =  ceinms::MultiInputMultiOutput<Excitation, Excitation>;\n    EMGMapping emgGenerator(N, M); \n    \n    auto f{ [N,M](const vector<Excitation> &in) {\n        MatrixXd m{ MatrixXd::Random(M, N) };\n        VectorXd v(N);\n        for (int i(0); i < N; ++i) {\n            v[i] = in[i];\n        }\n        MatrixXd x = m * v;\n        std::vector<Excitation> out(x.data(), x.data() + x.size());\n        return out;\n    }};\n    emgGenerator.setName(\"emgGenerator\");\n    emgGenerator.setFunction(f);\n    emgGenerator.setInput(vector<Excitation>(N, 1.));\n    emgGenerator.evaluate(0.01);\n    for (auto &e : emgGenerator.getOutput())\n        cout << e << endl;\n\n    ElectromechanicalDelay delay({ 0.05 });\n    delay.setName(\"mtu1\");\n    ExponentialActivation act;\n    act.setName(\"mtu1\");\n    NMSmodel<EMGMapping, ElectromechanicalDelay, ExponentialActivation> model;\n    model.addComponent(emgGenerator);\n    model.addComponent(delay);\n    model.addComponent(act);\n    model.connect<EMGMapping, ElectromechanicalDelay>({ \"emgGenerator\", 0 }, \"mtu1\");\n    model.connect<ElectromechanicalDelay, ExponentialActivation>();\n\n\n\n    return 0;\n\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "fbef18f61fb8eced481c5d3b4d55ecb2b4d8927e", "size": 1795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mainSandboxMuscleMapping.cpp", "max_stars_repo_name": "RealTimeBiomechanics/ceinms2", "max_stars_repo_head_hexsha": "1074afabc40249d374778f320e43ee4bc4e77f0b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T07:12:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T10:25:03.000Z", "max_issues_repo_path": "src/mainSandboxMuscleMapping.cpp", "max_issues_repo_name": "RealTimeBiomechanics/ceinms2", "max_issues_repo_head_hexsha": "1074afabc40249d374778f320e43ee4bc4e77f0b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mainSandboxMuscleMapping.cpp", "max_forks_repo_name": "RealTimeBiomechanics/ceinms2", "max_forks_repo_head_hexsha": "1074afabc40249d374778f320e43ee4bc4e77f0b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-05-15T00:48:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-01T05:00:13.000Z", "avg_line_length": 24.5890410959, "max_line_length": 85, "alphanum_fraction": 0.608913649, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5567779442760099}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/ml/glm/logistic_regression_with_sgd.hpp>\n#include <frovedis/ml/glm/svm_with_sgd.hpp>\n#include <boost/lexical_cast.hpp>\n\nint main(int argc, char* argv[]){\n  frovedis::use_frovedis use(argc, argv);\n\n  auto samples = frovedis::make_crs_matrix_load<double>(\"./train.mat\");\n  auto label = frovedis::make_dvector_loadline(\"./train.label\").\n    map(+[](const std::string& s){return boost::lexical_cast<double>(s);});\n  \n  int num_iteration = 100;\n  double alpha = 1.0;\n  double minibatch_fraction = 1.0;\n  frovedis::RegType rt = frovedis::ZERO;\n  double regParam = 0.01;\n  bool intercept = false;\n  auto model = frovedis::logistic_regression_with_sgd::\n    train(samples, label, num_iteration, alpha, minibatch_fraction, regParam,\n          rt, intercept);\n\n  /*\n  double convTol = 0.001;\n  frovedis::MatType mType = frovedis::CRS;\n  auto model = frovedis::svm_with_sgd::\n  train(samples, label, num_iteration, alpha, minibatch_fraction, regParam,\n        rt, intercept, convTol, mType);\n  */\n\n  model.save(\"./model\");\n\n  frovedis::logistic_regression_model<double> lm;\n  //frovedis::svm_model<double> lm;\n  lm.load(\"./model\");\n  auto test = frovedis::make_crs_matrix_local_load<double>(\"./test.mat\");\n  auto result = lm.predict(test);\n  for(auto i: result) std::cout << i << std::endl;\n}\n", "meta": {"hexsha": "c62c44ddfbf008b642d358e32f85868c24041c08", "size": 1325, "ext": "cc", "lang": "C++", "max_stars_repo_path": "doc/tutorial/src/tut4.1-1/tut.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "doc/tutorial/src/tut4.1-1/tut.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "doc/tutorial/src/tut4.1-1/tut.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 33.125, "max_line_length": 77, "alphanum_fraction": 0.7026415094, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5567454735337315}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathMatrixPrimMat, chol2inv_exception) {\n  using stan::math::chol2inv;\n\n  stan::math::matrix_d m1(2, 3);\n\n  // non-square\n  m1 << 1, 2, 3, 4, 5, 6;\n  EXPECT_THROW(chol2inv(m1), std::invalid_argument);\n\n  stan::math::matrix_d m2(3, 3);\n\n  // non-lower-triangular\n  m2 << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n  EXPECT_THROW(chol2inv(m2), std::domain_error);\n}\n\nTEST(MathMatrixPrimMat, chol2inv) {\n  using stan::math::chol2inv;\n  using stan::math::cholesky_decompose;\n  using stan::math::inverse_spd;\n  using stan::math::matrix_d;\n  using stan::math::wishart_rng;\n\n  boost::random::mt19937 rng;\n  matrix_d I(3, 3);\n  I.setZero();\n  I.diagonal().setOnes();\n  matrix_d Y = wishart_rng(4.0, I, rng);\n  matrix_d L = cholesky_decompose(Y);\n  matrix_d Y_inv = inverse_spd(Y);\n  matrix_d Y_inv2 = chol2inv(L);\n  for (int j = 0; j < Y.cols(); j++)\n    for (int i = 0; i < Y.rows(); i++)\n      EXPECT_FLOAT_EQ(Y_inv(i, j), Y_inv2(i, j));\n}\n\nTEST(MathMatrixPrimMat, chol2inv01) {\n  using stan::math::chol2inv;\n  using stan::math::matrix_d;\n\n  matrix_d Y(0, 0);\n  matrix_d Y_inv2 = chol2inv(Y);\n  EXPECT_EQ(0, Y_inv2.rows());\n  EXPECT_EQ(0, Y_inv2.cols());\n\n  matrix_d L(1, 1);\n  L(0, 0) = 3.0;\n  matrix_d inv2 = chol2inv(L);\n  EXPECT_FLOAT_EQ(1 / 9.0, inv2(0, 0));\n}\n", "meta": {"hexsha": "05c8d5734439cb52222975856ef432c1119f1745", "size": 1354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/mat/fun/chol2inv_test.cpp", "max_stars_repo_name": "peterwicksstringfield/math", "max_stars_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/math/prim/mat/fun/chol2inv_test.cpp", "max_issues_repo_name": "peterwicksstringfield/math", "max_issues_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/prim/mat/fun/chol2inv_test.cpp", "max_forks_repo_name": "peterwicksstringfield/math", "max_forks_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "max_forks_repo_licenses": ["BSD-3-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.6181818182, "max_line_length": 52, "alphanum_fraction": 0.6499261448, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.5566976524475452}}
{"text": "/**\n * Copyright (C) Omar Thor <omarthoro@gmail.com> - All Rights Reserved\n * Unauthorized copying of this file, via any medium is strictly prohibited\n * Proprietary and confidential\n *\n * Written by Omar Thor <omarthoro@gmail.com>, 2017\n */\n\n#ifndef SP_UTIL_RAND_HPP\n#define\tSP_UTIL_RAND_HPP\n\n#include <random>\n#include <memory>\n#include <limits>\n#include <set>\n#include <boost/random.hpp>\n\n#include \"sp/config.hpp\"\n#include \"hints.hpp\"\n\nSP_UTIL_NAMESPACE_BEGIN\n\n/**\n * \\brief Random utility\n *\n * Encapsulates common usage cases for uniform real distributions of float, double type,\n * and any integral type.\n */\ntemplate<typename Random_engine_type = boost::random::mt19937_64> //mt19937, consider default_random_engine\nstruct rand_util {\n\n    using random_engine_type = Random_engine_type;\n    using result_type = typename random_engine_type::result_type;\n\npublic:\n\n    rand_util(uint seed = 0) : rng(), distFl(0, 1), distDl(0,1) {\n        if (seed > 0) {\n            rng.seed(seed);\n        } else {\n            rng.seed(std::random_device{}());\n        }\n    }\n\n    sp_hot float rand_float() {\n        return distFl(rng);\n    }\n\n    sp_hot double rand_double() {\n        return distDl(rng);\n    }\n\n    /**\n     * Generate a random integral in the range of [from, to)\n     * \\param from\n     * \\param to\n     * \\return\n     */\n    template<typename T>\n    sp_hot T rand_integral(T from, T to) {\n        if(std::numeric_limits<T>::digits10 > std::numeric_limits<float>::digits10) {\n            return (to - from) * distDl(rng) + from;\n        } else {\n            return (to - from) * distFl(rng) + from;\n        }\n    }\n        /**\n     * Creates a completely randomized integer from\n     * \\return\n     */\n    sp_hot typename random_engine_type::result_type rand_integral() {\n        return this->rng();\n    }\n\n    /**\n     * Return the random engine being used\n     */\n    sp_hot random_engine_type& eng() {\n        return this->rng;\n    }\n\nprivate:\n    random_engine_type rng;\n    boost::random::uniform_real_distribution<float> distFl;\n    boost::random::uniform_real_distribution<double> distDl;\n};\n\ntypedef std::shared_ptr<rand_util<>> rand_util_ptr;\n\ninline rand_util_ptr new_rand() {\n    return std::make_shared<rand_util<>>();\n}\n\n\n/**\n * Generated N unique numbers in the range [from, to)\n *\n * \\param n\n * \\param from\n * \\param to\n * \\return set of n unique numbers\n */\ntemplate<size_t N, typename result_type, typename Rand_util_type>\nsp_hot std::array<result_type, N> n_unique(Rand_util_type& util, result_type from, result_type to) {\n    std::set<result_type> s;\n    //select n points\n    for(result_type i = 0; i < N; ++i) {\n        result_type rand_idx;\n        do {\n            rand_idx = util.rand_integral(from, to);\n        } while(s.find(rand_idx) != s.end());\n        s.insert(rand_idx);\n    }\n    std::array<result_type, N> arr;\n    std::copy(s.begin(), s.end(), arr.begin());\n    return arr;\n}\n\nSP_UTIL_NAMESPACE_END\n\n\n#endif /* SP_UTIL_RAND_HPP */\n\n", "meta": {"hexsha": "28600d8a0019a8cf7b8e32ac52176c0f44638be3", "size": 2978, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sp/util/rand.hpp", "max_stars_repo_name": "thorigin/sp", "max_stars_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sp/util/rand.hpp", "max_issues_repo_name": "thorigin/sp", "max_issues_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "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": "include/sp/util/rand.hpp", "max_forks_repo_name": "thorigin/sp", "max_forks_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "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.0161290323, "max_line_length": 107, "alphanum_fraction": 0.6386836803, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5566976480882708}}
{"text": "#include <boost/math/special_functions/binomial.hpp>\n\n#include <iostream>\n#include <ctime>\n#include <cassert>\n#include <vector>\n#include <algorithm>\n#include <math.h> \n\ndouble condRankP(unsigned int r, unsigned int c, double p, unsigned int q);\ndouble nCkF(unsigned int n, unsigned int k);\n", "meta": {"hexsha": "ed70dabb9da076481f7126d23d962857d2fd1e31", "size": 290, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trunk/+simLib/src/C-mexed/rankProb.hpp", "max_stars_repo_name": "andreatassi/SparseRLNC", "max_stars_repo_head_hexsha": "7b98409409762e381c2da4633e0fb584909393e6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trunk/+simLib/src/C-mexed/rankProb.hpp", "max_issues_repo_name": "andreatassi/SparseRLNC", "max_issues_repo_head_hexsha": "7b98409409762e381c2da4633e0fb584909393e6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trunk/+simLib/src/C-mexed/rankProb.hpp", "max_forks_repo_name": "andreatassi/SparseRLNC", "max_forks_repo_head_hexsha": "7b98409409762e381c2da4633e0fb584909393e6", "max_forks_repo_licenses": ["Apache-2.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.1666666667, "max_line_length": 75, "alphanum_fraction": 0.7517241379, "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5566416584563517}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EVecPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <smooth/so3.hpp>\n\n// #include \"smooth/compat/autodiff.hpp\"\n#include \"smooth/feedback/ocp.hpp\"\n\ntemplate<typename T>\nusing Vec = Eigen::VectorX<T>;\n\nTEST(Ocp, Jacobians)\n{\n  // objective\n  auto theta = []<typename T>(T tf, Vec<T> x0, Vec<T> xf, Vec<T> q) -> T {\n    return (tf - 2) * (tf - 2) + x0.squaredNorm() + xf.squaredNorm() + q.sum();\n  };\n\n  // dynamics\n  auto f = []<typename T>(T t, Vec<T> x, Vec<T> u) -> Vec<T> { return Vec<T>{{x.y() + t, u.x()}}; };\n\n  // integrals\n  auto g = []<typename T>(T t, Vec<T> x, Vec<T> u) -> Vec<T> {\n    return Vec<T>{{t + x.squaredNorm() + u.squaredNorm()}};\n  };\n\n  // running constraint\n  auto cr = []<typename T>(T t, Vec<T> x, Vec<T> u) -> Vec<T> {\n    Vec<T> ret(4);\n    ret << t, x, u;\n    return ret;\n  };\n\n  // end constraint\n  auto ce = []<typename T>(T tf, Vec<T> x0, Vec<T> xf, Vec<T> q) -> Vec<T> {\n    Vec<T> ret(6);\n    ret << tf, x0, xf, q;\n    return ret;\n  };\n\n  const smooth::feedback::\n    FlatOCP<decltype(theta), decltype(f), decltype(g), decltype(cr), decltype(ce)>\n      ocp{\n        .nx    = 2,\n        .nu    = 1,\n        .nq    = 1,\n        .ncr   = 4,\n        .nce   = 6,\n        .theta = theta,\n        .f     = f,\n        .g     = g,\n        .cr    = cr,\n        .crl   = Vec<double>::Constant(4, -1),\n        .cru   = Vec<double>::Constant(4, 1),\n        .ce    = ce,\n        .cel   = Vec<double>::Constant(6, -1),\n        .ceu   = Vec<double>::Constant(6, 1),\n      };\n\n  ASSERT_TRUE(smooth::feedback::check_ocp(ocp));\n\n  smooth::feedback::Mesh<5, 5> mesh;\n  mesh.refine_ph(0, 8 * 5);\n\n  auto nlp = smooth::feedback::ocp_to_nlp(ocp, mesh);\n\n  Eigen::VectorXd x = Eigen::VectorXd::Constant(nlp.n, 1);\n\n  const auto df_dx = nlp.df_dx(x);\n  const auto dg_dx = nlp.dg_dx(x);\n\n  const auto [fval, df_dx_num] =\n    smooth::diff::dr<1, smooth::diff::Type::Numerical>(nlp.f, smooth::wrt(x));\n  const auto [gval, dg_dx_num] =\n    smooth::diff::dr<1, smooth::diff::Type::Numerical>(nlp.g, smooth::wrt(x));\n\n  ASSERT_TRUE(Eigen::MatrixXd(df_dx).isApprox(df_dx_num, 1e-8));\n  ASSERT_TRUE(Eigen::MatrixXd(dg_dx).isApprox(dg_dx_num, 1e-8));\n}\n\nTEST(OCP, Flatten)\n{\n  // objective\n  auto theta = []<typename T>(T tf, smooth::SO3<T>, smooth::SO3<T>, Vec<T> q) -> T {\n    return (tf - 2) * (tf - 2) + q.sum();\n  };\n\n  // dynamics\n  auto f = []<typename T>(T, smooth::SO3<T> x, Eigen::Vector2<T> u) -> Vec<T> {\n    return Vec<T>{{u.x(), -u.y(), 0.01 * x.log().x()}};\n  };\n\n  // integrals\n  auto g = []<typename T>(T t, smooth::SO3<T> x, Eigen::Vector2<T> u) -> Vec<T> {\n    return Vec<T>{{t + x.log().squaredNorm() + u.squaredNorm()}};\n  };\n\n  // running constraint\n  auto cr = []<typename T>(T t, smooth::SO3<T>, Eigen::Vector2<T> u) -> Vec<T> {\n    Vec<T> ret(3);\n    ret << t, u;\n    return ret;\n  };\n\n  // end constraint\n  auto ce = []<typename T>(T tf, smooth::SO3<T> x0, smooth::SO3<T> xf, Vec<T>) -> Vec<T> {\n    Vec<T> ret(7);\n    ret << tf, x0.log(), xf.log();\n    return ret;\n  };\n\n  const smooth::feedback::OCP<\n    smooth::SO3d,\n    Eigen::Vector2d,\n    decltype(theta),\n    decltype(f),\n    decltype(g),\n    decltype(cr),\n    decltype(ce)>\n    ocp{\n      .nx    = 3,\n      .nu    = 2,\n      .nq    = 1,\n      .ncr   = 3,\n      .nce   = 7,\n      .theta = theta,\n      .f     = f,\n      .g     = g,\n      .cr    = cr,\n      .crl   = Vec<double>::Constant(3, -1),\n      .cru   = Vec<double>::Constant(3, 1),\n      .ce    = ce,\n      .cel   = Vec<double>::Constant(7, -1),\n      .ceu   = Vec<double>::Constant(7, 1),\n    };\n\n  const auto xl_fun = []<typename T>(T) -> smooth::SO3<T> { return smooth::SO3<T>::Identity(); };\n\n  const auto ul_fun = []<typename T>(T) -> Eigen::Vector2<T> { return Eigen::Vector2<T>::Zero(); };\n\n  ASSERT_TRUE(smooth::feedback::check_ocp(ocp));\n\n  const auto flat_ocp = smooth::feedback::flatten_ocp(ocp, xl_fun, ul_fun);\n\n  ASSERT_TRUE(smooth::feedback::check_ocp(flat_ocp));\n}\n", "meta": {"hexsha": "70c143c01e820f94ead58a793ddd6060a946c2f5", "size": 5216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_ocp.cpp", "max_stars_repo_name": "pettni/smooth_feedback", "max_stars_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "tests/test_ocp.cpp", "max_issues_repo_name": "pettni/smooth_feedback", "max_issues_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "tests/test_ocp.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": 30.3255813953, "max_line_length": 100, "alphanum_fraction": 0.5899156442, "num_tokens": 1645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5566416542259361}}
{"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": "//\n// Created by yu on 13.05.20.\n//\n\n#ifndef HW4_FASTEIGEN_HPP\n#define HW4_FASTEIGEN_HPP\n#include <Eigen/Eigenvalues>\nEigen::Vector3d ComputeEigenvector0(const Eigen::Matrix3d &A, double eval0);\nEigen::Vector3d ComputeEigenvector1(const Eigen::Matrix3d &A,\n                                    const Eigen::Vector3d &evec0,\n                                    double eval1);\nEigen::Vector3d FastEigen3x3(Eigen::Matrix3d &A);\n#endif //HW4_FASTEIGEN_HPP\n", "meta": {"hexsha": "18cb39ad6d5efeb8193e70232969e703f1e3252e", "size": 451, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fastEigen.hpp", "max_stars_repo_name": "eglrp/PointCloudClustering", "max_stars_repo_head_hexsha": "4e18997859b402ac5c4478c273cccc1ed0d75a1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-05-25T15:17:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T10:16:01.000Z", "max_issues_repo_path": "include/fastEigen.hpp", "max_issues_repo_name": "yf26/PointCloudClustering", "max_issues_repo_head_hexsha": "4e18997859b402ac5c4478c273cccc1ed0d75a1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/fastEigen.hpp", "max_forks_repo_name": "yf26/PointCloudClustering", "max_forks_repo_head_hexsha": "4e18997859b402ac5c4478c273cccc1ed0d75a1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-11-25T05:16:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T02:21:37.000Z", "avg_line_length": 32.2142857143, "max_line_length": 76, "alphanum_fraction": 0.6563192905, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5566416377981654}}
{"text": "#include <geometry.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n\n#include <vector>\n\ntypedef tiny::MathTypes<float> MT;\ntypedef MT::vector3_type       V;\ntypedef MT::quaternion_type    Q;\ntypedef MT::real_type          T;\n\nclass ContactInfo\n{\npublic:\n\n  V m_point;\n  V m_normal;\n  T m_distance;\n\n};\n\n\nclass MyCallback\n  : public geometry::ContactsCallback<V>\n{\npublic:\n\n  std::vector<ContactInfo> m_contacts;\n\npublic:\n\n  void operator()(\n                  V const & point\n                  , V const & normal\n                  , typename V::real_type const & distance\n                  )\n  {\n    ContactInfo info;\n\n    info.m_point = point;\n    info.m_normal = normal;\n    info.m_distance = distance;\n\n    m_contacts.push_back(info);\n  }\n\n};\n\n\n\nBOOST_AUTO_TEST_SUITE(geometry);\n\nBOOST_AUTO_TEST_CASE(contacts_sphere_tetrahedron_test)\n{\n  // Separation in vertex regions\n  {\n    V const center = V::make(2.1, 0.0, 0.0);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  {\n    V const center = V::make(0.0, 2.1, 0.0);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  {\n    V const center = V::make(0.0, 0.0, 2.1);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  {\n    V const center = V::make(-1.0, -1.0, -1.0);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  // Separation in edge regions\n  {\n    V const center = V::make(0.5, -1.0, -0.5);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  {\n    V const center = V::make(-1.0, 0.5, -0.5);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  {\n    V const center = V::make(-1.0, -1.0, 0.5);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  {\n    V const center = V::make( 1.0, 1.0, -1.0);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  {\n    V const center = V::make( 1.0, -1.0, 1.0);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  {\n    V const center = V::make(-1.0, 1.0, 1.0);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  // Separation in face regions\n  {\n    V const center = V::make( 0.2, 0.2, -2.1);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  {\n    V const center = V::make( 0.2, -2.1,  0.2);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  {\n    V const center = V::make( -2.1, 0.2,  0.2);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  {\n    V const center = V::make( 2.0, 2.0, 2.0);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(!test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);\n  }\n  // Contacts in vertex regions\n  {\n    V const center = V::make(1.9, 0.0, 0.0);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(0), 1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(1), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(2), 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(0),-1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(1), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(2), 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.1, 0.01);\n  }\n  {\n    V const center = V::make(1.9, 0.0, 0.0);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, true);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(0), 1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(1), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(2), 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(0), 1.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(1), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(2), 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.1, 0.01);\n  }\n\n  {\n    V const center = V::make(0.0, 1.9, 0.0);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n  }\n  {\n    V const center = V::make(0.0, 0.0, 1.9);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n  }\n  {\n    V const center = V::make(-0.5, -0.5, -0.5);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n  }\n  // Contact in edge regions\n  {\n    V const center = V::make(0.5, -0.5, -0.5);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(0), 0.5, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(1), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(2), 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(0), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(1), 0.707106769, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(2), 0.707106769, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.292893231, 0.01);\n\n  }\n  {\n    V const center = V::make(0.5, -0.5, -0.5);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, true);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(0), 0.5, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(1), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(2), 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(0), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(1), -0.707106769, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(2), -0.707106769, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.292893231, 0.01);\n    \n  }\n  {\n    V const center = V::make(-0.5, 0.5, -0.5);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n  }\n  {\n    V const center = V::make(-0.5, -0.5, 0.5);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron,  callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n  }\n  {\n    V const center = V::make( 0.5, 0.5, -0.5);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n  }\n  {\n    V const center = V::make( 0.5, -0.5, 0.5);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n  }\n  {\n    V const center = V::make(-0.5, 0.5, 0.5);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n  }\n  // Contact in face regions\n  {\n    V const center = V::make( 0.2, 0.2, -0.9);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(0), 0.2, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(1), 0.2, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(2), 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(0), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(1), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(2), 1.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.1, 0.01);\n  }\n  {\n    V const center = V::make( 0.2, 0.2, -0.9);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, true);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(0), 0.2, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(1), 0.2, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(2), 0.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(0), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(1), 0.0, 0.01);\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(2),-1.0, 0.01);\n\n    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.1, 0.01);\n  }\n  {\n    V const center = V::make( 0.2, -0.9,  0.2);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n  }\n  {\n    V const center = V::make( -0.9, 0.2,  0.2);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n  }\n  {\n    V const center = V::make( 0.7, 0.7, 0.7);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n    \n    MyCallback callback;\n    \n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n    \n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n  }\n\n  // sphere inside\n  {\n    V const center = V::make( 0.3, 0.2, 0.1);\n    T const radius = 1.0;\n\n    V const p0 = V::make(0.0, 0.0, 0.0);\n    V const p1 = V::make(1.0, 0.0, 0.0);\n    V const p2 = V::make(0.0, 1.0, 0.0);\n    V const p3 = V::make(0.0, 0.0, 1.0);\n\n    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);\n    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);\n\n    MyCallback callback;\n\n    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);\n\n    BOOST_CHECK(test);\n\n    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "62802234b71338f3cbbea9a8304d704c58287ee2", "size": 24551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_sphere_tetrahedron/geometry_contacts_sphere_tetrahedron.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_sphere_tetrahedron/geometry_contacts_sphere_tetrahedron.cpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/GEOMETRY/unit_tests/geometry_contacts_sphere_tetrahedron/geometry_contacts_sphere_tetrahedron.cpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6378865979, "max_line_length": 99, "alphanum_fraction": 0.6298317787, "num_tokens": 8960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5566416328204448}}
{"text": "/*\n * This file is part of the Interpolated Polyline (https://github.com/fzi-forschungszentrum-informatik/P3IV),\n * copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory)\n */\n\n#include <glog/logging.h>\n#include <boost/math/distributions/lognormal.hpp>\n#include <boost/math/special_functions/erf.hpp> // for erf/erfc.\n#include \"gtest/gtest.h\"\n#include \"internal/approximations.hpp\"\n\nusing namespace util_probability;\n\n\nTEST(UtilNumeric, CDF) {\n\n    double stddev = 1.0;\n    double mean = 0.0;\n    double sigma = 1.0;\n\n    boost::math::normal norm(mean, stddev);\n\n    double sigma_1_region = boost::math::cdf(norm, sigma) - boost::math::cdf(norm, -sigma);\n    LOG_ASSERT(std::abs(sigma_1_region - 0.68) < 0.01);\n    LOG_ASSERT(0.5 * boost::math::erfc(-sigma * M_SQRT1_2) == boost::math::cdf(norm, 1.0));\n\n    double val = 0.5;\n    auto boost_cdf = boost::math::cdf(norm, val);\n    auto numeric_cdf = util_probability::norm_cdf(val, mean, sigma);\n    LOG_ASSERT(std::abs(boost_cdf - numeric_cdf) < 1e-5);\n}\n\n\nint main(int argc, char** argv) {\n    ::google::InitGoogleLogging(argv[0]);\n    ::google::InstallFailureSignalHandler();\n    ::testing::InitGoogleTest(&argc, argv);\n\n    FLAGS_colorlogtostderr = true;\n    FLAGS_logtostderr = true;\n\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "897cb9eb2f8b3b0e3540b629e84d01cb702f2455", "size": 1330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "p3iv_utils_probability/test/test_approximations.cpp", "max_stars_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_stars_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T06:56:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:21:30.000Z", "max_issues_repo_path": "p3iv_utils_probability/test/test_approximations.cpp", "max_issues_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_issues_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p3iv_utils_probability/test/test_approximations.cpp", "max_forks_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_forks_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-10T01:56:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T01:56:44.000Z", "avg_line_length": 30.2272727273, "max_line_length": 119, "alphanum_fraction": 0.6954887218, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5566416270954198}}
{"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 \u00a9 2017\u5e74 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 * adjointness.cpp\n *\n *  Created on: 22.07.2017\n *      Author: thies\n */\n\n#include <base/ConstantMesh.h>\n#include <base/DiscretizedFunction.h>\n#include <base/SpaceTimeMesh.h>\n#include <base/Util.h>\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/numbers.h>\n#include <deal.II/base/point.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria.h>\n#include <forward/DivRightHandSide.h>\n#include <forward/DivRightHandSideAdjoint.h>\n#include <gtest/gtest.h>\n#include <norms/H1L2.h>\n#include <norms/L2Coefficients.h>\n#include <stddef.h>\n#include <iostream>\n#include <memory>\n#include <vector>\n\nnamespace {\n\nusing namespace dealii;\nusing namespace wavepi::forward;\nusing namespace wavepi::base;\nusing namespace wavepi;\n\ntemplate<int dim>\nclass TestF: public Function<dim> {\npublic:\n   double value(const Point<dim> &p, const unsigned int component = 0) const {\n      Assert(component == 0, ExcIndexRange(component, 0, 1));\n\n      Point<dim> pc = Point<dim>::unit_vector(0);\n      pc *= 0.2;\n\n      return this->get_time() * std::sin(p.distance(pc) * 2 * numbers::PI);\n   }\n};\n\ntemplate<int dim>\nclass TestG: public Function<dim> {\npublic:\n   double value(const Point<dim> &p, const unsigned int component = 0) const {\n      Assert(component == 0, ExcIndexRange(component, 0, 1));\n\n      Point<dim> pc = Point<dim>::unit_vector(0);\n      pc *= 0.5;\n\n      return this->get_time() * std::sin(p.distance(pc) * 2 * numbers::PI);\n   }\n};\n\ntemplate<int dim>\nvoid run_div_rhs_adjoint_test(int fe_order, int quad_order, int refines, int n_steps, double tol) {\n   auto triangulation = std::make_shared<Triangulation<dim>>();\n   GridGenerator::hyper_cube(*triangulation, -1, 1);\n   Util::set_all_boundary_ids(*triangulation, 0);\n   triangulation->refine_global(refines);\n\n   double t_start = 0.0, t_end = 2.0, dt = t_end / n_steps;\n   std::vector<double> times;\n\n   for (size_t i = 0; t_start + i * dt <= t_end; i++)\n      times.push_back(t_start + i * dt);\n\n   std::shared_ptr<SpaceTimeMesh<dim>> mesh = std::make_shared<ConstantMesh<dim>>(times, FE_Q<dim>(fe_order),\n         QGauss<dim>(quad_order), triangulation);\n\n   deallog << std::endl << \"----------  n_dofs / timestep: \" << mesh->get_dof_handler(0)->n_dofs();\n   deallog << \", n_steps: \" << times.size() << \"  ----------\" << std::endl;\n   double err_avg = 0.0;\n   double err_simple;\n\n   for (size_t i = 0; i < 11; i++) {\n      std::shared_ptr<DiscretizedFunction<dim>> f, g;\n\n      if (i == 0) {\n         // it is kind of important for this test that f and g are space dependent\n         // (otherwise quantities will be very very small)\n         TestF<dim> f_cont;\n         f = std::make_shared<DiscretizedFunction<dim>>(mesh, f_cont);\n\n         TestG<dim> g_cont;\n         g = std::make_shared<DiscretizedFunction<dim>>(mesh, g_cont);\n      } else {\n         f = std::make_shared<DiscretizedFunction<dim>>(DiscretizedFunction<dim>::noise(mesh));\n\n         // make it a bit smoother, random noise might be a bit too harsh\n         f->set_norm(std::make_shared<norms::H1L2<dim>>(0.5));\n         f->dot_transform_inverse();\n\n         g = std::make_shared<DiscretizedFunction<dim>>(DiscretizedFunction<dim>::noise(mesh));\n\n         // make it a bit smoother, random noise might be a bit too harsh\n         g->set_norm(std::make_shared<norms::H1L2<dim>>(0.5));\n         g->dot_transform_inverse();\n      }\n\n      f->set_norm(std::make_shared<norms::L2Coefficients<dim>>());\n      *f *= 1.0 / f->norm();\n\n      g->set_norm(std::make_shared<norms::L2Coefficients<dim>>());\n      *g *= 1.0 / g->norm();\n\n      auto zero = std::make_shared<DiscretizedFunction<dim>>(f->get_mesh());\n\n      DivRightHandSide<dim> divrhs(f, zero, f);\n      DivRightHandSideAdjoint<dim> divrhs_adj(f, g);\n\n      DiscretizedFunction<dim> sol_f(mesh, std::make_shared<norms::L2Coefficients<dim>>());\n\n      for (size_t i = 0; i < mesh->length(); i++) {\n         divrhs.set_time(mesh->get_times()[i]);\n         divrhs.create_right_hand_side(*mesh->get_dof_handler(i), mesh->get_quadrature(), sol_f[i]);\n      }\n\n      EXPECT_GT(sol_f.norm(), 0.0);\n\n      auto adj_g = divrhs_adj.run_adjoint(mesh);\n      adj_g.set_norm(std::make_shared<norms::L2Coefficients<dim>>());\n      EXPECT_GT(adj_g.norm(), 0.0);\n\n      double dot_solf_g = sol_f * (*g);\n      double dot_f_adjg = (*f) * adj_g;\n      double fg_err = std::abs(dot_solf_g - dot_f_adjg) / (std::abs(dot_solf_g) + 1e-300);\n\n      if (i == 0) {\n         // deallog << \"simple f,g: \" << std::scientific << \"(Lf, g) = \" << dot_solf_g << \", (f, L*g) = \" << dot_f_adjg\n         //         << std::endl;\n         err_simple = fg_err;\n         deallog << std::scientific << \"        relative error for simple f,g = \" << fg_err << std::endl;\n      } else\n         err_avg = ((i - 1) * err_avg + fg_err) / i;\n\n      deallog << std::scientific << \"(Lf, g) = \" << dot_solf_g << \", (f, L*g) = \" << dot_f_adjg << \", rel. error = \"\n            << fg_err << std::endl;\n\n      // EXPECT_LT(zz_err, tol);\n   }\n\n   deallog << std::scientific << \"average relative error for random f,g = \" << err_avg << std::endl;\n   EXPECT_LT(err_simple, tol);\n   EXPECT_LT(err_avg, tol);\n}\n}  // namespace\n\nTEST(DivRightHandSide, Adjoint1DFE1) {\n   for (int i = 6; i < 7; i++)\n      run_div_rhs_adjoint_test<1>(1, 3, 6, 1 << i, 1e-1);\n}\n\nTEST(DivRightHandSide, Adjoint1DFE2) {\n   for (int i = 6; i < 7; i++)\n      run_div_rhs_adjoint_test<1>(2, 6, 4, 1 << i, 1e-1);\n}\nTEST(DivRightHandSide, Adjoint2DFE1) {\n   for (int i = 6; i < 7; i++)\n      run_div_rhs_adjoint_test<2>(1, 3, 5, 1 << i, 1e-1);\n}\n\nTEST(DivRightHandSide, Adjoint3DFE1) {\n   for (int i = 6; i < 7; i++)\n      run_div_rhs_adjoint_test<3>(1, 3, 2, 1 << i, 1e-1);\n}\n", "meta": {"hexsha": "bc4eec5db08f6c4bcb49133bc856f8e1fe0e7dec", "size": 5834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/div_right_hand_side.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/div_right_hand_side.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/div_right_hand_side.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1477272727, "max_line_length": 119, "alphanum_fraction": 0.6220431951, "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.55660158885495}}
{"text": "#pragma once\n\n#define EIGEN_HAS_CXX11_MATH 0\n#include <Eigen/Dense>\n#include <array>\n#include \"Geometry2d/Util.hpp\"\n#include \"const-math.hpp\"\n\n/// Model parameters for a robot.  Used by the controls system.\nclass RobotModel {\npublic:\n    /// Radius of omni-wheel (in meters)\n    float WheelRadius;\n\n    /// Distance from center of robot to center of wheel\n    float WheelDist;\n\n    /// Wheel angles (in radians) measured between +x axis and wheel axle\n    std::array<float, 4> WheelAngles;\n\n    /// wheelSpeeds = BotToWheel * V_bot\n    Eigen::Matrix<float, 4, 3> BotToWheel;\n\n    /// This should be called when any of the other parameters are changed\n    void recalculateBotToWheel() {\n        // See this paper for more info on how this matrix is derived:\n        // http://people.idsia.ch/~foerster/2006/1/omnidrive_kiart_preprint.pdf\n\n        // clang-format off\n        BotToWheel <<\n            sinf(WheelAngles[0]), cosf(WheelAngles[0]), -WheelDist,\n            sinf(WheelAngles[1]), cosf(WheelAngles[1]), -WheelDist,\n            sinf(WheelAngles[2]), cosf(WheelAngles[2]), -WheelDist,\n            sinf(WheelAngles[3]), cosf(WheelAngles[3]), -WheelDist;\n        BotToWheel /= WheelRadius;\n        // clang-format on\n    }\n\n    /// (wheel rad/s desired) * DutyCycleMultiplier = duty cycle\n    /// Note that this is an approximation, as the relationship isn't exactly\n    /// linear\n    float DutyCycleMultiplier;\n};\n\n/// Model parameters for 2015 robot.  See RobotModel.cpp for values.\nextern const RobotModel RobotModel2015;\n", "meta": {"hexsha": "67ba317e96a7b91b3983cb84603b65a5f248a66c", "size": 1531, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "firmware/robot2015/src-ctrl/modules/control/RobotModel.hpp", "max_stars_repo_name": "JNeiger/robocup-firmware", "max_stars_repo_head_hexsha": "c1bfd4ba24070eaa4e012fdc88aa468aafcc2e4e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-25T20:28:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-25T20:28:58.000Z", "max_issues_repo_path": "firmware/robot2015/src-ctrl/modules/control/RobotModel.hpp", "max_issues_repo_name": "JNeiger/robocup-firmware", "max_issues_repo_head_hexsha": "c1bfd4ba24070eaa4e012fdc88aa468aafcc2e4e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "firmware/robot2015/src-ctrl/modules/control/RobotModel.hpp", "max_forks_repo_name": "JNeiger/robocup-firmware", "max_forks_repo_head_hexsha": "c1bfd4ba24070eaa4e012fdc88aa468aafcc2e4e", "max_forks_repo_licenses": ["Apache-2.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.5744680851, "max_line_length": 79, "alphanum_fraction": 0.6708033965, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417088, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.5566015882883777}}
{"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// \tCopyright (c) 2021 Cem Bassoy, cem.bassoy@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include <boost/test/unit_test.hpp>\n#include <boost/numeric/ublas/tensor/extents.hpp>\n\nBOOST_AUTO_TEST_SUITE ( test_shape_dynamic_static_rank )\n\n\nstruct fixture\n{\n  template<std::size_t N>\n  using shape_t = boost::numeric::ublas::extents<N>;\n\n//  static inline auto n     = shape_t<0>{};\n  static inline auto n1    = shape_t<1>{1};\n  static inline auto n2    = shape_t<1>{2};\n  static inline auto n11   = shape_t<2>{1,1};\n  static inline auto n12   = shape_t<2>{1,2};\n  static inline auto n21   = shape_t<2>{2,1};\n  static inline auto n22   = shape_t<2>{2,2};\n  static inline auto n32   = shape_t<2>{3,2};\n  static inline auto n111  = shape_t<3>{1,1,1};\n  static inline auto n211  = shape_t<3>{2,1,1};\n  static inline auto n121  = shape_t<3>{1,2,1};\n  static inline auto n112  = shape_t<3>{1,1,2};\n  static inline auto n123  = shape_t<3>{1,2,3};\n  static inline auto n321  = shape_t<3>{3,2,1};\n  static inline auto n213  = shape_t<3>{2,1,3};\n  static inline auto n432  = shape_t<3>{4,3,2};\n};\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_rank_static_empty,\n                        fixture,\n                        *boost::unit_test::label(\"dynamic_extents_rank_static\") *boost::unit_test::label(\"empty\"))\n{\n  namespace ublas = boost::numeric::ublas;\n//  BOOST_CHECK( ublas::empty(n   ));\n  BOOST_CHECK(!ublas::empty(n1  ));\n  BOOST_CHECK(!ublas::empty(n2  ));\n  BOOST_CHECK(!ublas::empty(n11 ));\n  BOOST_CHECK(!ublas::empty(n12 ));\n  BOOST_CHECK(!ublas::empty(n21 ));\n  BOOST_CHECK(!ublas::empty(n22 ));\n  BOOST_CHECK(!ublas::empty(n32 ));\n  BOOST_CHECK(!ublas::empty(n111));\n  BOOST_CHECK(!ublas::empty(n211));\n  BOOST_CHECK(!ublas::empty(n121));\n  BOOST_CHECK(!ublas::empty(n112));\n  BOOST_CHECK(!ublas::empty(n123));\n  BOOST_CHECK(!ublas::empty(n321));\n  BOOST_CHECK(!ublas::empty(n213));\n  BOOST_CHECK(!ublas::empty(n432));\n\n  BOOST_CHECK_THROW( shape_t<3>({1,1,0}), std::invalid_argument);\n  BOOST_CHECK_THROW( shape_t<2>({1,0}), std::invalid_argument);\n  BOOST_CHECK_THROW( shape_t<1>({0}  ), std::invalid_argument);\n  BOOST_CHECK_THROW( shape_t<2>({0,1}), std::invalid_argument);\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_rank_static_size,\n                        fixture,\n                        *boost::unit_test::label(\"dynamic_extents_rank_static\") *boost::unit_test::label(\"size\"))\n{\n  namespace ublas = boost::numeric::ublas;\n\n//  BOOST_CHECK_EQUAL(ublas::size(n   ),0);\n  BOOST_CHECK_EQUAL(ublas::size(n1  ),1);\n  BOOST_CHECK_EQUAL(ublas::size(n2  ),1);\n  BOOST_CHECK_EQUAL(ublas::size(n11 ),2);\n  BOOST_CHECK_EQUAL(ublas::size(n12 ),2);\n  BOOST_CHECK_EQUAL(ublas::size(n21 ),2);\n  BOOST_CHECK_EQUAL(ublas::size(n22 ),2);\n  BOOST_CHECK_EQUAL(ublas::size(n32 ),2);\n  BOOST_CHECK_EQUAL(ublas::size(n111),3);\n  BOOST_CHECK_EQUAL(ublas::size(n211),3);\n  BOOST_CHECK_EQUAL(ublas::size(n121),3);\n  BOOST_CHECK_EQUAL(ublas::size(n112),3);\n  BOOST_CHECK_EQUAL(ublas::size(n123),3);\n  BOOST_CHECK_EQUAL(ublas::size(n321),3);\n  BOOST_CHECK_EQUAL(ublas::size(n213),3);\n  BOOST_CHECK_EQUAL(ublas::size(n432),3);\n}\n\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_rank_static_at_read,\n                        fixture,\n                        *boost::unit_test::label(\"dynamic_extents_rank_static\") *boost::unit_test::label(\"at_read\"))\n{\n  BOOST_CHECK_EQUAL(n1  .at(0),1);\n  BOOST_CHECK_EQUAL(n2  .at(0),2);\n\n  BOOST_CHECK_EQUAL(n11 .at(0),1);\n  BOOST_CHECK_EQUAL(n11 .at(1),1);\n\n  BOOST_CHECK_EQUAL(n12 .at(0),1);\n  BOOST_CHECK_EQUAL(n12 .at(1),2);\n\n  BOOST_CHECK_EQUAL(n21 .at(0),2);\n  BOOST_CHECK_EQUAL(n21 .at(1),1);\n\n  BOOST_CHECK_EQUAL(n22 .at(0),2);\n  BOOST_CHECK_EQUAL(n22 .at(1),2);\n\n  BOOST_CHECK_EQUAL(n32 .at(0),3);\n  BOOST_CHECK_EQUAL(n32 .at(1),2);\n\n  BOOST_CHECK_EQUAL(n432.at(0),4);\n  BOOST_CHECK_EQUAL(n432.at(1),3);\n  BOOST_CHECK_EQUAL(n432.at(2),2);\n\n\n//  BOOST_CHECK_THROW( (void)n  .at(0), std::out_of_range);\n  BOOST_CHECK_THROW( (void)n32.at(2), std::out_of_range);\n  BOOST_CHECK_THROW( (void)n32.at(5), std::out_of_range);\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_extents_dynamic_rank_static_operator_access_read,\n                        fixture,\n                        *boost::unit_test::label(\"dynamic_extents_rank_static\") *boost::unit_test::label(\"operator_access_read\"))\n{\n  BOOST_CHECK_EQUAL(n1  [0],1);\n  BOOST_CHECK_EQUAL(n2  [0],2);\n\n  BOOST_CHECK_EQUAL(n11 [0],1);\n  BOOST_CHECK_EQUAL(n11 [1],1);\n\n  BOOST_CHECK_EQUAL(n12 [0],1);\n  BOOST_CHECK_EQUAL(n12 [1],2);\n\n  BOOST_CHECK_EQUAL(n21 [0],2);\n  BOOST_CHECK_EQUAL(n21 [1],1);\n\n  BOOST_CHECK_EQUAL(n22 [0],2);\n  BOOST_CHECK_EQUAL(n22 [1],2);\n\n  BOOST_CHECK_EQUAL(n32 [0],3);\n  BOOST_CHECK_EQUAL(n32 [1],2);\n\n  BOOST_CHECK_EQUAL(n432[0],4);\n  BOOST_CHECK_EQUAL(n432[1],3);\n  BOOST_CHECK_EQUAL(n432[2],2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c7d4a6a9de5e2cf9bf360a80656b8e30faf536dc", "size": 4946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/test_extents_dynamic_rank_static.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "test/tensor/test_extents_dynamic_rank_static.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "test/tensor/test_extents_dynamic_rank_static.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": 31.7051282051, "max_line_length": 129, "alphanum_fraction": 0.6793368378, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.5564917278125213}}
{"text": "#include \"Include\\NeuralNetwork.h\"\n#include <iostream>\n#include <assert.h>\n#include <armadillo_bits/constants_old.hpp>\n\n\n#include \"../math.h\"\n#include \"../Drawing.h\"\n#include \"../GenericAlgorithm/Include/GenericAlgorithm.h\"\n\n\nnamespace nn\n{\n\tNeuralNetwork::NeuralNetwork(uint16_t inputLayer, uint16_t hiddenLayer, uint16_t outputLayer, float learnRate)\n\t\t: learnRate_(learnRate)\n\t\t, layersCount_(3)\n\t{\n\t\tlayers_\t\t= { inputLayer, hiddenLayer, outputLayer };\n\t\tneurons_\t= new arma::mat[3];\n\t\tbias_\t\t= new arma::mat[3];\n\t\tweights_\t= new arma::mat[2];\n\n\t\tweights_[0] = (arma::randu(hiddenLayer, inputLayer) * 2.0f - 1.0f);\t// input - hidden\n\t\tweights_[1] = (arma::randu(outputLayer, hiddenLayer) * 2.0f - 1.0f); // hidden - output\n\n\t\tbias_[0] = (arma::randu(inputLayer,\t1) * 2.0f - 1.0f);\n\t\tbias_[1] = (arma::randu(hiddenLayer, 1) * 2.0f - 1.0f);\n\t\tbias_[2] = (arma::randu(outputLayer, 1) * 2.0f - 1.0f);\n\t}\n\n\tNeuralNetwork::NeuralNetwork(const std::vector<uint16_t>& layers, float learnRate)\n\t\t: learnRate_(learnRate)\n\t\t, layersCount_(layers.size())\n\t{\n\t\tassert(layers.size() > 2);\n\n\t\tlayers_\t\t= layers;\n\t\tneurons_\t= new arma::mat[layersCount_];\n\t\tbias_\t\t= new arma::mat[layersCount_];\n\t\tweights_\t= new arma::mat[layersCount_ - 1];\n\n\t\t// filling random weights\n\t\tfor (size_t i = 1; i < layersCount_; i++)\n\t\t\tweights_[i - 1] = (arma::randu(layers[i], layers[i - 1]) * 2.0f - 1.0f);\n\n\t\t// filling random biases\n\t\tfor (size_t i = 0; i < layersCount_; i++)\n\t\t\tbias_[i] = (arma::randu(layers[i], 1) * 2.0f - 1.0f);\n\t}\n\n\tNeuralNetwork::NeuralNetwork(NeuralNetwork* neural_network)\n\t\t: learnRate_(neural_network->learnRate_)\n\t\t, layersCount_(neural_network->layersCount_)\n\t{\n\t\tlayers_.assign(neural_network->layers_.begin(), neural_network->layers_.end());\n\t\tneurons_\t= new arma::mat[layersCount_];\n\t\tbias_\t\t= new arma::mat[layersCount_];\n\t\tweights_\t= new arma::mat[layersCount_ - 1];\n\n\t\t// filling random weights\n\t\tfor (size_t i = 1; i < layersCount_; i++)\n\t\t\tweights_[i - 1] = arma::zeros(layers_[i], layers_[i - 1]);\n\n\t\t// filling random biases\n\t\tfor (size_t i = 0; i < layersCount_; i++)\n\t\t\tbias_[i] = arma::zeros(layers_[i]);\n\t}\n\n\tNeuralNetwork::~NeuralNetwork()\n\t{ \n\t\tlayers_.clear();\n\t\tdelete[] bias_;\n\t\tdelete[] neurons_;\n\t\tdelete[] weights_;\n\t}\n\n\tvoid NeuralNetwork::activationFunction(double& x)\n\t{\n\t\tx = atan(x);\n\t}\n\n\tvoid NeuralNetwork::train(const arma::mat& inputs, const arma::mat& targets)\n\t{\n\t\tassert(inputs.n_rows == layers_[0] || targets.n_rows == layers_[layersCount_ - 1]);\n\n\t\tquery(inputs);\n\n\t\t// error for output layer\n\t\tarma::mat error = targets - neurons_[layersCount_ - 1];\n\t\terror_coef = abs(arma::accu(error));\n\n\t\tfor (size_t i = layersCount_ - 1; i > 0; i--)\n\t\t{\n\t\t\t// error for each layer\n\t\t\tif (i != layersCount_ - 1)\n\t\t\t\terror = weights_[i].t() * error;\n\n\t\t\t// (error % neurons_[i] % (1 - neurons_[i])) - delta\n\t\t\tweights_[i - 1] += learnRate_ * (error % neurons_[i] % (1 - neurons_[i])) * neurons_[i - 1].t();\n\t\t\tbias_[i] += learnRate_ * (error % neurons_[i] % (1 - neurons_[i]));\n\t\t}\n\t}\n\n\tvoid NeuralNetwork::query(const arma::mat& inputs)\n\t{\n\t\tassert(inputs.n_rows == layers_[0]);\n\n\t\tneurons_[0] = inputs;\n\t\tfor (size_t i = 1; i < layersCount_; i++)\n\t\t{\n\t\t\tneurons_[i] = weights_[i - 1] * neurons_[i - 1] + bias_[i];\n\t\t\tneurons_[i].for_each([](arma::mat::elem_type& val) { activationFunction(val); });\n\t\t}\n\t}\n\n\tvoid NeuralNetwork::backQuery(const arma::mat& inputs)\n\t{\n\t\tassert(inputs.n_rows == layers_[layersCount_ - 1]);\n\n\t\tneurons_[layersCount_ - 1] = inputs;\n\n\t\tfor (int32_t i = layersCount_ - 1; i > 0; i--)\n\t\t{\n\t\t\tneurons_[i - 1] = weights_[i - 1].t() * neurons_[i];\n\t\t\tneurons_[i - 1].for_each([](arma::mat::elem_type& val) { activationFunction(val); });\n\t\t}\n\t}\n\n\tconst arma::mat& NeuralNetwork::result()\n\t{\n\t\treturn neurons_[layersCount_ - 1];\n\t}\n\n\tconst arma::Mat<double>& nn::NeuralNetwork::input()\n\t{\n\t\treturn neurons_[0];\n\t}\n\n\tconst arma::Mat<double>& nn::NeuralNetwork::getLayer(uint16_t inx)\n\t{\n\t\treturn neurons_[inx];\n\t}\n\n\tuint16_t NeuralNetwork::getGeneration()\n\t{\n\t\treturn generation_;\n\t}\n\n\tvoid NeuralNetwork::setGeneration(uint16_t generation)\n\t{\n\t\tgeneration_ = generation;\n\t}\n\n\tdouble NeuralNetwork::getFitness()\n\t{\n\t\treturn fitness_;\n\t}\n\n\tvoid NeuralNetwork::setFitness(double fitness)\n\t{\n\t\tfitness_ = fitness;\n\t}\n\n\tvoid NeuralNetwork::addFitness(double value)\n\t{\n\t\tfitness_ += value;\n\t}\n\n\tvoid NeuralNetwork::save(const std::string& fileName)\n\t{\n\n\t}\n\n\tvoid NeuralNetwork::load(const std::string& fileName)\n\t{\n\n\t}\n\t\n\tvoid NeuralNetwork::reproduce(const NeuralNetwork* brain1, const NeuralNetwork* brain2)\n\t{\n\t\tassert(brain1->layersCount_ == brain2->layersCount_);\n\t\tassert(layersCount_ == brain1->layersCount_);\n\n\t\tfor (int i = 0; i < layersCount_ - 1; ++i)\n\t\t{\n\t\t\tga::GenericAlgorithm::selection(brain1->weights_[i], brain2->weights_[i], weights_[i], true);\n\t\t}\n\n\t\tfor (int i = 0; i < layersCount_; ++i)\n\t\t{\n\t\t\tga::GenericAlgorithm::selection(brain1->bias_[i], brain2->bias_[i], bias_[i], true);\n\t\t}\n\t}\n\n\tvoid NeuralNetwork::draw(int x, int y, float neuronScale, float spacingX, float spacingY)\n\t{\n\t\tfloat multX = (neuronScale * 2 + spacingX);\n\t\tfloat multY = (neuronScale * 2 + spacingY);\n\t\t//DrawFilledRect(x - m_Layers.size() * multX / 2, y - 250, m_Layers.size() * multX, 500, RGBColor(0.3f * 255, 0.4f * 255, 0.6f * 255));\n\t\t//DrawTextQL(\"Generation: \" + std::to_string(m_Generation), 0, 20, 0, RGBColor{ 255, 255, 255 });\n\n\t\t// Draw Dendrites\n\t\tfor (int i = 1; i < layersCount_; i++)\n\t\t{\n\t\t\tint prevLayerNeurCount = i > 0 ? layers_[i - 1] : 0;\n\t\t\n\t\t\tfor (int j = 0; j < layers_[i]; j++)\n\t\t\t{\n\t\t\t\tint x1 = x + (i - layersCount_ / 2.0f + 0.5) * multX;\n\t\t\t\tint y1 = y + (j - neurons_[i].n_rows / 2.0f + 0.5) * multY;\n\t\t\n\t\t\t\tfloat value = neurons_[i][j];\n\t\t\t\t\n\t\t\t\t// Draw Dendrites\n\t\t\t\tfor (int k = 0; k < layers_[i - 1]; k++)\n\t\t\t\t{\n\t\t\t\t\tfloat weight = weights_[i - 1].at(j, k);\n\t\t\t\t\t\n\t\t\t\t\t int x2 = x + ((i - 1) - layersCount_ / 2.0f + 0.5) * multX;\n\t\t\t\t\t int y2 = y + (k - prevLayerNeurCount / 2.0f + 0.5) * multY;\n\t\t\t\t\t\n\t\t\t\t\t int cX = (x1 + x2) / 2;\n\t\t\t\t\t int cY = (y1 + y2) / 2;\n\t\t\t\t\t float dirX = (x2 - (x1));\n\t\t\t\t\t float dirY = (y2 - (y1));\n\t\t\t\t\t float angle = std::atan2(dirY, dirX);\n\t\t\t\t\t //float angle = atan2(vector2.y, vector2.x) - atan2(vector1.y, vector1.x);;\n\t\t\t\t\t if (angle < 0) angle += 2 * M_PI;\n\t\t\t\t\t angle = angle * 180 / M_PI + 180;\n\t\t\t\t\t\n\t\t\t\t\t DrawLineThinkT(\n\t\t\t\t\t \tx1, y1,\n\t\t\t\t\t \tx2, y2,\n\t\t\t\t\t \tfabs(weight) * 2.0f,\n\t\t\t\t\t \tRGBColor(255 * std::fmax(0, -weight), 0, 255 * fmax(0, weight), 0)\n\t\t\t\t\t );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Draw Neurons\n\t\tfor (int i = 0; i < layersCount_; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < neurons_[i].n_rows; j++)\n\t\t\t{\n\t\t\t\tint x1 = x + (i - layersCount_ / 2.0f + 0.5) * multX;\n\t\t\t\tint y1 = y + (j - neurons_[i].n_rows / 2.0f + 0.5) * multY;\n\t\t\t\tfloat value = neurons_[i][j];\n\n\t\t\t\t// Draw Neurons\n\t\t\t\tDrawFilledCircle(x1, y1, neuronScale, RGBColor(0, 0, 0));\n\t\t\t\tDrawFilledCircle(x1, y1, neuronScale - 2, RGBColor(255 * std::abs(value), 255 * value, 255 * value));\n\t\t\t}\n\n\t\t}\n\t}\n} // namespace nn", "meta": {"hexsha": "9739a99bca4f921bd57d7204cb9b398f440aec2a", "size": 6979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NeuralBots/NeuralNetwork/NeuralNetwork.cpp", "max_stars_repo_name": "CrishNate/NeuralBots", "max_stars_repo_head_hexsha": "fcf119b9cee2a2c9e3e19644d88c02bd68fc4af0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NeuralBots/NeuralNetwork/NeuralNetwork.cpp", "max_issues_repo_name": "CrishNate/NeuralBots", "max_issues_repo_head_hexsha": "fcf119b9cee2a2c9e3e19644d88c02bd68fc4af0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NeuralBots/NeuralNetwork/NeuralNetwork.cpp", "max_forks_repo_name": "CrishNate/NeuralBots", "max_forks_repo_head_hexsha": "fcf119b9cee2a2c9e3e19644d88c02bd68fc4af0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-05T22:30:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-05T22:30:48.000Z", "avg_line_length": 27.1556420233, "max_line_length": 137, "alphanum_fraction": 0.6200028657, "num_tokens": 2480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5564733683298843}}
{"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": "//=====================================================\n// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>\n//=====================================================\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 2\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n// You should have received a copy of the GNU General Public License\n// along with this program; if not, write to the Free Software\n// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n//\n#ifndef EIGEN2_INTERFACE_HH\n#define EIGEN2_INTERFACE_HH\n// #include <cblas.h>\n\n#include <Eigen/Cholesky>\n#include <Eigen/LU>\n#include <Eigen/QR>\n\n#include \"btl.hh\"\n\nusing namespace Eigen;\n\ntemplate<class real, int SIZE=Dynamic>\nclass eigen2_interface\n{\n\npublic :\n\n  enum {IsFixedSize = (SIZE!=Dynamic)};\n\n  typedef real real_type;\n\n  typedef std::vector<real> stl_vector;\n  typedef std::vector<stl_vector> stl_matrix;\n\n  typedef Eigen::Matrix<real,SIZE,SIZE> gene_matrix;\n  typedef Eigen::Matrix<real,SIZE,1> gene_vector;\n\n  static inline std::string name( void )\n  {\n    #if defined(EIGEN_VECTORIZE_SSE)\n    if (SIZE==Dynamic) return \"eigen2\"; else return \"tiny_eigen2\";\n    #elif defined(EIGEN_VECTORIZE_ALTIVEC) || defined(EIGEN_VECTORIZE_VSX)\n    if (SIZE==Dynamic) return \"eigen2\"; else return \"tiny_eigen2\";\n    #else\n    if (SIZE==Dynamic) return \"eigen2_novec\"; else return \"tiny_eigen2_novec\";\n    #endif\n  }\n\n  static void free_matrix(gene_matrix & A, int N) {}\n\n  static void free_vector(gene_vector & B) {}\n\n  static BTL_DONT_INLINE void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){\n    A.resize(A_stl[0].size(), A_stl.size());\n\n    for (int j=0; j<A_stl.size() ; j++){\n      for (int i=0; i<A_stl[j].size() ; i++){\n        A.coeffRef(i,j) = A_stl[j][i];\n      }\n    }\n  }\n\n  static BTL_DONT_INLINE  void vector_from_stl(gene_vector & B, stl_vector & B_stl){\n    B.resize(B_stl.size(),1);\n\n    for (int i=0; i<B_stl.size() ; i++){\n      B.coeffRef(i) = B_stl[i];\n    }\n  }\n\n  static BTL_DONT_INLINE  void vector_to_stl(gene_vector & B, stl_vector & B_stl){\n    for (int i=0; i<B_stl.size() ; i++){\n      B_stl[i] = B.coeff(i);\n    }\n  }\n\n  static BTL_DONT_INLINE  void matrix_to_stl(gene_matrix & A, stl_matrix & A_stl){\n    int N=A_stl.size();\n\n    for (int j=0;j<N;j++){\n      A_stl[j].resize(N);\n      for (int i=0;i<N;i++){\n        A_stl[j][i] = A.coeff(i,j);\n      }\n    }\n  }\n\n  static inline void matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){\n    X = (A*B).lazy();\n  }\n\n  static inline void transposed_matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){\n    X = (A.transpose()*B.transpose()).lazy();\n  }\n\n  static inline void ata_product(const gene_matrix & A, gene_matrix & X, int N){\n    X = (A.transpose()*A).lazy();\n  }\n\n  static inline void aat_product(const gene_matrix & A, gene_matrix & X, int N){\n    X = (A*A.transpose()).lazy();\n  }\n\n  static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N){\n    X = (A*B)/*.lazy()*/;\n  }\n\n  static inline void atv_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){\n    X = (A.transpose()*B)/*.lazy()*/;\n  }\n\n  static inline void axpy(real coef, const gene_vector & X, gene_vector & Y, int N){\n    Y += coef * X;\n  }\n\n  static inline void axpby(real a, const gene_vector & X, real b, gene_vector & Y, int N){\n    Y = a*X + b*Y;\n  }\n\n  static inline void copy_matrix(const gene_matrix & source, gene_matrix & cible, int N){\n    cible = source;\n  }\n\n  static inline void copy_vector(const gene_vector & source, gene_vector & cible, int N){\n    cible = source;\n  }\n\n  static inline void trisolve_lower(const gene_matrix & L, const gene_vector& B, gene_vector& X, int N){\n    X = L.template marked<LowerTriangular>().solveTriangular(B);\n  }\n\n  static inline void trisolve_lower_matrix(const gene_matrix & L, const gene_matrix& B, gene_matrix& X, int N){\n    X = L.template marked<LowerTriangular>().solveTriangular(B);\n  }\n\n  static inline void cholesky(const gene_matrix & X, gene_matrix & C, int N){\n    C = X.llt().matrixL();\n//     C = X;\n//     Cholesky<gene_matrix>::computeInPlace(C);\n//     Cholesky<gene_matrix>::computeInPlaceBlock(C);\n  }\n\n  static inline void lu_decomp(const gene_matrix & X, gene_matrix & C, int N){\n    C = X.lu().matrixLU();\n//     C = X.inverse();\n  }\n\n  static inline void tridiagonalization(const gene_matrix & X, gene_matrix & C, int N){\n    C = Tridiagonalization<gene_matrix>(X).packedMatrix();\n  }\n\n  static inline void hessenberg(const gene_matrix & X, gene_matrix & C, int N){\n    C = HessenbergDecomposition<gene_matrix>(X).packedMatrix();\n  }\n\n\n\n};\n\n#endif\n", "meta": {"hexsha": "b98857c37a5e6097675e77376deb0c07c3d99c8e", "size": 5113, "ext": "hh", "lang": "C++", "max_stars_repo_path": "External/eigen-3.3.7/bench/btl/libs/eigen2/eigen2_interface.hh", "max_stars_repo_name": "RokKos/eol-cloth", "max_stars_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "External/eigen-3.3.7/bench/btl/libs/eigen2/eigen2_interface.hh", "max_issues_repo_name": "RokKos/eol-cloth", "max_issues_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "External/eigen-3.3.7/bench/btl/libs/eigen2/eigen2_interface.hh", "max_forks_repo_name": "RokKos/eol-cloth", "max_forks_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2544378698, "max_line_length": 124, "alphanum_fraction": 0.6563661256, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5564562724147413}}
{"text": "#ifndef INCLUDE_SWIFT_VIO_TWO_VIEW_GEOMETRY_HPP_\n#define INCLUDE_SWIFT_VIO_TWO_VIEW_GEOMETRY_HPP_\n#include <okvis/kinematics/Transformation.hpp>\n#include <Eigen/Core>\n\nnamespace okvis {\nclass TwoViewGeometry {\n public:\n  static float computeErrorEssentialMat(okvis::kinematics::Transformation T_ji,\n                                        Eigen::Vector3d bearing_i,\n                                        Eigen::Vector3d bearing_j, double fi,\n                                        double fj, double sigmai = 1.0,\n                                        double sigmaj = 1.0);\n\n  /**\n   * @brief deviationFromEpipolarLine compute deviation in pixels from the\n   * epipolar line. see\n   * https://github.com/opencv/opencv/blob/master/modules/calib3d/src/fundam.cpp\n   * @param E_ji t_ji X R_ji. Epipolar constraint is p_j' * t_ji X R_ji * p_i = 0.\n   * @param bearing_i [x, y, 1] undistorted image coordinate at z=1 for point in\n   * image i\n   * @param bearing_j [x, y, 1] undistorted image coordinate at z=1 for point in\n   * image j\n   * @param focal_length nominal focal length to convert the epipolar line error\n   * into error of pixel unit.\n   * @return squared distance to epipolar line. Distance has a unit of pixels.\n   */\n  static float computeErrorEssentialMat(Eigen::Matrix3d E_ji,\n                                        Eigen::Vector3d bearing_i,\n                                        Eigen::Vector3d bearing_j, double fi,\n                                        double fj, double sigmai = 1.0,\n                                        double sigmaj = 1.0);\n};\n}  // namespace okvis\n\n#endif  // INCLUDE_SWIFT_VIO_TWO_VIEW_GEOMETRY_HPP_\n", "meta": {"hexsha": "9f5662d5191891ed16c6aedc6ce42de7b24bd87b", "size": 1652, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "okvis_frontend/include/swift_vio/TwoViewGeometry.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_frontend/include/swift_vio/TwoViewGeometry.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_frontend/include/swift_vio/TwoViewGeometry.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": 44.6486486486, "max_line_length": 82, "alphanum_fraction": 0.6071428571, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5563674491070476}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Unit tests for the transformation of points (with and without\n/// covariance)\n///\n/// \\author Kirk MacTavish\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <gtest/gtest.h>\n\n#include <math.h>\n#include <iomanip>\n#include <ios>\n#include <iostream>\n#include <typeinfo>\n\n#include <Eigen/Dense>\n#include <lgmath.hpp>\n#include <lgmath/CommonMath.hpp>\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n///\n/// UNIT TESTS OF POINTS WITH AND WITHOUT COVARIANCE\n///\n/////////////////////////////////////////////////////////////////////////////////////////////\n\nusing namespace lgmath;\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n// HELPER CONSTANTS\n/////////////////////////////////////////////////////////////////////////////////////////////\n\nstatic const so3::RotationMatrix C_z180 =\n    so3::Rotation(so3::AxisAngle(0., 0., constants::PI)).matrix();\nstatic const so3::RotationMatrix C_z90 =\n    so3::Rotation(so3::AxisAngle(0., 0., constants::PI_DIV_TWO)).matrix();\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n// MAIN TESTS\n/////////////////////////////////////////////////////////////////////////////////////////////\n\nTEST(Points, PointCovarianceTransform) {\n  r3::CovarianceMatrix cov_a;\n  cov_a.setZero();\n  cov_a.diagonal() << 1., 2., 3.;\n  r3::HPoint p_a = (r3::Point() << 2., 3., 4.).finished().homogeneous();\n\n  {\n    std::cout << \"Given a 180 degree transform, \"\n              << \"when we transform the covariance, \"\n              << \"then the covariance should be unchanged.\" << std::endl;\n    se3::Transformation T_ba(C_z180, se3::TranslationVector::Zero());\n    auto cov_b =\n        r3::transformCovariance<r3::COVARIANCE_NOT_REQUIRED>(T_ba, cov_a);\n    std::cout << cov_a << \"\\n==\\n\" << cov_b << std::endl;\n    EXPECT_TRUE(cov_a.isApprox(cov_b));\n  }\n  {\n    std::cout << \"Given a 90 degree transform, \"\n              << \"when we transform the covariance, \"\n              << \"then the covariance should should have x and y swapped.\"\n              << std::endl;\n    se3::Transformation T_ba(C_z90, se3::TranslationVector::Zero());\n    auto cov_b =\n        r3::transformCovariance<r3::COVARIANCE_NOT_REQUIRED>(T_ba, cov_a);\n    cov_a.row(0).swap(cov_a.row(1));\n    cov_a.col(0).swap(cov_a.col(1));\n    std::cout << cov_a << \"\\n==\\n\" << cov_b << std::endl;\n    EXPECT_TRUE(cov_a.isApprox(cov_b));\n  }\n  {\n    std::cout << \"Given uncertain translation, \"\n              << \"when we translate the point and covariance, \"\n              << \"then the covariance should be additive.\" << std::endl;\n    se3::LieAlgebraCovariance S_ba = se3::LieAlgebraCovariance::Zero();\n    S_ba.topLeftCorner<3, 3>() = cov_a;\n    se3::TransformationWithCovariance T_ba(\n        so3::RotationMatrix::Identity(), se3::TranslationVector::Zero(), S_ba);\n    auto p_b = T_ba * p_a;\n    r3::CovarianceMatrix cov_b;\n    EXPECT_NO_THROW(cov_b = r3::transformCovariance(T_ba, cov_a, p_b));\n    r3::CovarianceMatrix cov_b_expect = cov_a * 2.;\n    std::cout << cov_b << \"\\n==\\n\" << cov_b_expect << std::endl;\n    EXPECT_TRUE(cov_b.isApprox(cov_b_expect));\n  }\n  {\n    std::cout << \"Given uninitialized uncertain transform, \"\n              << \"when we transform the point without ignoring the 'covariance \"\n                 \"set' flag, \"\n              << \"then it should throw.\" << std::endl;\n    se3::TransformationWithCovariance T_ba;\n    r3::CovarianceMatrix cov_b;\n    auto p_b = T_ba * p_a;\n    EXPECT_THROW(cov_b = r3::transformCovariance(T_ba, cov_a, p_b),\n                 std::runtime_error);\n\n    std::cout\n        << \"when we transform the point but ignore the 'covariance set' flag, \"\n        << \"then it shouldn't throw, and the covariance should be unchanged, \"\n        << std::endl;\n    EXPECT_NO_THROW(cov_b =\n                        r3::transformCovariance<r3::COVARIANCE_NOT_REQUIRED>(\n                            T_ba, cov_a, p_b));\n    std::cout << cov_a << \"\\n==\\n\" << cov_b << std::endl;\n    EXPECT_TRUE(cov_a.isApprox(cov_b));\n  }\n  {\n    std::cout\n        << \"Given uncertain rotation, \"\n        << \"when we transform the point and covariance, \"\n        << \"then the covariance should be unchanged in Z, and larger in X and Y\"\n        << std::endl;\n    se3::LieAlgebraCovariance S_ba;\n    S_ba.setZero();\n    S_ba(5, 5) = 1;\n    se3::TransformationWithCovariance T_ba(\n        se3::TransformationMatrix(se3::TransformationMatrix::Identity()), S_ba);\n    auto p_b = T_ba * p_a;\n    auto cov_b = r3::transformCovariance(T_ba, cov_a, p_b);\n    EXPECT_TRUE(cov_b(0, 0) > cov_a(0, 0) + 1e-3);\n    EXPECT_TRUE(cov_b(1, 1) > cov_a(1, 1) + 1e-3);\n    EXPECT_TRUE(cov_b(2, 2) == cov_a(2, 2));  // Approximately\n  }\n}\n\nTEST(Points, PointTransform) {\n  std::cout << \"Given a point, \"\n            << \"when we transform it, \"\n            << \"then it should be in the right spot.\" << std::endl;\n\n  r3::HPoint x;\n  x << 1., 2., 3., 1.;\n  se3::Transformation T(\n      (se3::LieAlgebra() << 1., 0, 0, constants::PI, 0, 0).finished());\n  r3::HPoint x_tf;\n  x_tf << 2., -2., -3., 1.;\n  std::cout << T * x << \"\\n==\\n\" << x_tf << std::endl;\n  EXPECT_TRUE((T * x).isApprox(x_tf));\n}\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "f2eb29f5320124a981830bdd93c2891f456d2dd0", "size": 5465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/CovarianceTests.cpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "tests/CovarianceTests.cpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "tests/CovarianceTests.cpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 37.9513888889, "max_line_length": 94, "alphanum_fraction": 0.5280878317, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5563674491070476}}
{"text": "//  (C) Copyright Matt Borland 2022.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <cmath>\n#include <cfloat>\n#include <cstdint>\n#include <limits>\n#include <type_traits>\n#include <boost/math/ccmath/fdim.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\ntemplate <typename T>\nconstexpr void test()\n{\n    static_assert(boost::math::ccmath::isnan(boost::math::ccmath::fdim(std::numeric_limits<T>::quiet_NaN(), T(1))), \"If x is NaN, NaN is returned\");\n    static_assert(boost::math::ccmath::isnan(boost::math::ccmath::fdim(T(1), std::numeric_limits<T>::quiet_NaN())), \"If y is NaN, NaN is returned\");\n\n    static_assert(boost::math::ccmath::fdim(T(4), T(1)) == T(3));\n    static_assert(boost::math::ccmath::fdim(T(1), T(4)) == T(0));\n    static_assert(boost::math::ccmath::fdim(T(4), T(-1)) == T(5));\n    static_assert(boost::math::ccmath::fdim(T(1), T(-4)) == T(5));\n\n    static_assert(boost::math::ccmath::isinf(boost::math::ccmath::fdim(std::numeric_limits<T>::infinity(), T(-1))));\n}\n\n#if !defined(BOOST_MATH_NO_CONSTEXPR_DETECTION) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\nint main()\n{\n    test<float>();\n    test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test<long double>();\n    #endif\n    \n    #ifdef BOOST_HAS_FLOAT128\n    test<boost::multiprecision::float128>();\n    #endif\n\n    return 0;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "f5f688d534785a8293b4f4c68f77ad733cfd7637", "size": 1641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_fdim_test.cpp", "max_stars_repo_name": "jamesfolberth/math", "max_stars_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/ccmath_fdim_test.cpp", "max_issues_repo_name": "jamesfolberth/math", "max_issues_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/ccmath_fdim_test.cpp", "max_forks_repo_name": "jamesfolberth/math", "max_forks_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8363636364, "max_line_length": 148, "alphanum_fraction": 0.6867763559, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5563674459101006}}
{"text": "#pragma once\r\n\r\n#include \"RelaxedUT.h\"\r\n#include <Eigen/QR>\n\nusing namespace RelaxedUnscentedTransformation;\n\nvoid RelaxedUnscentedTransformation::genQ(int n, const Eigen::VectorXi& inl, const MixedNonlinearityList& mix,\n\tEigen::SparseMatrix<double>& Q,\n\tEigen::SparseMatrix<double>& Q1) {\n\t// Construct M matrix from the weights keeping it orthogonal to inl\r\n\ttypedef Eigen::MatrixXd Matrix;\r\n\tMatrix M = Matrix::Zero(mix.size() + inl.size(), n);\r\n\tfor (int n = 0; n < inl.size(); n++)\r\n\t\tM(n, inl(n)) = 1;\r\n\tfor (int n = 0; n < mix.size(); n++)\r\n\t\tfor (int i0 = 0; i0 < mix[n].i.size(); i0++) {\r\n\t\t\tbool flag = false;\r\n\t\t\tfor (int i = 0; i < inl.size(); i++)\r\n\t\t\t\tif (mix[n].i[i0] == inl(i))\r\n\t\t\t\t\tflag = true;\r\n\t\t\tif (!flag)\r\n\t\t\t\tM(n + inl.size(), mix[n].i[i0]) = mix[n].M(i0);\r\n\t\t}\r\n\t// RQ factorization\r\n\tEigen::HouseholderQR<Matrix> solver(M.transpose());\r\n\tEigen::MatrixXd Qdense = solver.householderQ().transpose();\r\n\tdouble rel_treshold = 1e-6;\r\n\t// Compute rank\r\n\tint rank = n;\r\n\t{\r\n\t\tEigen::MatrixXd to_compute_rank = (M * Qdense.transpose()).cwiseAbs();\r\n\t\tdouble treshold = to_compute_rank.maxCoeff() * rel_treshold;\r\n\t\tfor (int i = 0; i < to_compute_rank.cols(); i++)\r\n\t\t\tif (to_compute_rank.col(i).maxCoeff() < treshold) {\r\n\t\t\t\trank = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t}\r\n\t// make it sparse\r\n\tfor (int i = 0; i < Qdense.rows(); i++)\r\n\t\tfor (int j = 0; j < Qdense.cols(); j++)\r\n\t\t\tif (abs(Qdense(i, j)) < 1e-8)\r\n\t\t\t\tQdense(i, j) = 0;\r\n\t// save it sparse\r\n\tQ = Qdense.sparseView();\r\n\tQ1 = Q.block(0, 0, rank, n);\n}\n", "meta": {"hexsha": "33f9cc089f1229d4a6b87bc83ae210d96a80e4b6", "size": 1517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppsource/RelaxedUT.cpp", "max_stars_repo_name": "ABC-iRobotics/RelaxedUnscentedTransformation", "max_stars_repo_head_hexsha": "b0e2dc4d484f998fad84796d639af68b5ebdfbbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cppsource/RelaxedUT.cpp", "max_issues_repo_name": "ABC-iRobotics/RelaxedUnscentedTransformation", "max_issues_repo_head_hexsha": "b0e2dc4d484f998fad84796d639af68b5ebdfbbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppsource/RelaxedUT.cpp", "max_forks_repo_name": "ABC-iRobotics/RelaxedUnscentedTransformation", "max_forks_repo_head_hexsha": "b0e2dc4d484f998fad84796d639af68b5ebdfbbc", "max_forks_repo_licenses": ["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.9591836735, "max_line_length": 110, "alphanum_fraction": 0.6064601187, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5563674441203725}}
{"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": "/*\n   bernmm-test.cpp:  test module\n\n   Copyright (C) 2008, 2009, David Harvey\n\n   This file is part of the bernmm package (version 1.1).\n\n   bernmm is released under a BSD-style license. See the README file in\n   the source distribution for details.\n*/\n\n#include <iostream>\n#include <NTL/ZZ.h>\n#include <gmp.h>\n#include \"bern_modp_util.h\"\n#include \"bern_modp.h\"\n#include \"bern_rat.h\"\n\n\nNTL_CLIENT;\n\n\nusing namespace bernmm;\nusing namespace std;\n\n\n/*\n   Computes B_0, B_1, ..., B_{n-1} using naive algorithm, writes them to res.\n*/\nvoid bern_naive(mpq_t* res, long n)\n{\n   mpq_t t, u;\n   mpq_init(t);\n   mpq_init(u);\n\n   // compute res[j] = B_j / j! for 0 <= j < n\n   if (n > 0)\n      mpq_set_si(res[0], 1, 1);\n\n   for (long j = 1; j < n; j++)\n   {\n      mpq_set_si(res[j], 0, 1);\n      mpq_set_ui(t, 1, 1);\n      for (long k = 0; k < j; k++)\n      {\n         mpz_mul_ui(mpq_denref(t), mpq_denref(t), k + 2);\n         mpq_mul(u, res[j - 1 - k], t);\n         mpq_sub(res[j], res[j], u);\n      }\n   }\n\n   // multiply through by j! for 0 <= j < n\n   mpq_set_ui(t, 1, 1);\n   for (long j = 2; j < n; j++)\n   {\n      mpz_mul_ui(mpq_numref(t), mpq_numref(t), j);\n      mpq_mul(res[j], res[j], t);\n   }\n\n   mpq_clear(u);\n   mpq_clear(t);\n}\n\n\n/*\n   Tests _bern_modp_powg() for a given p and k by comparing against the\n   rational number B_k (must be supplied in b).\n\n   Returns 1 on success.\n*/\nint testcase__bern_modp_powg(long p, long k, mpq_t b)\n{\n   mulmod_t pinv = PrepMulMod(p);\n\n   // compute B_k mod p using _bern_modp_powg()\n   long x = _bern_modp_powg(p, pinv, k);\n   x = MulMod(x, k, p, pinv);\n\n   // compute B_k mod p from rational B_k\n   long y = mpz_fdiv_ui(mpq_numref(b), p);\n   long z = mpz_fdiv_ui(mpq_denref(b), p);\n   return y == MulMod(z, x, p, pinv);\n}\n\n\n\n/*\n   Tests _bern_modp_powg() by comparing against naive computation of B_k\n   (as a rational) for a range of small p and k.\n\n   Returns 1 on success.\n*/\nint test__bern_modp_powg()\n{\n   int success = 1;\n\n   const long MAX = 300;\n   mpq_t bern[MAX];\n\n   // compute B_k's as rational numbers using naive algorithm\n   for (long i = 0; i < MAX; i++)\n      mpq_init(bern[i]);\n   bern_naive(bern, MAX);\n\n   // try a range of k's\n   for (long k = 2; k < MAX && success; k += 2)\n   {\n      // try a range of small p's\n      for (long p = k + 3; p < 2*MAX && success; p += 2)\n      {\n         if (!ProbPrime(p))\n            continue;\n         success = success && testcase__bern_modp_powg(p, k, bern[k]);\n      }\n\n      // try a single larger p\n      success = success && testcase__bern_modp_powg(1000003, k, bern[k]);\n   }\n\n   // if we're on a 32-bit machine, try a single example with p right near\n   // NTL's boundary (this is infeasible on a 64-bit machine)\n   if (NTL_SP_NBITS <= 32)\n   {\n      long p = NTL_SP_BOUND - 1;\n      while (!ProbPrime(p))\n         p--;\n\n      long k = (MAX/2)*2 - 2;\n      success = success && testcase__bern_modp_powg(p, k, bern[k]);\n   }\n\n   for (long i = 0; i < MAX; i++)\n      mpq_clear(bern[i]);\n\n   return success;\n}\n\n\n\n/*\n   Tests _bern_modp_pow2() for a given p and k by comparing against result\n   from _bern_modp_powg().\n\n   Returns 1 on success.\n\n   If 2^k = 1 mod p, then _bern_modp_pow2() won't work, so it just returns 1.\n*/\nint testcase__bern_modp_pow2(long p, long k)\n{\n   mulmod_t pinv = PrepMulMod(p);\n\n   if (PowerMod(2, k, p, pinv) == 1)\n      return 1;\n\n   long x = _bern_modp_powg(p, pinv, k);\n   long y = _bern_modp_pow2(p, pinv, k);\n\n   return x == y;\n}\n\n\n\n/*\n   Tests _bern_modp_pow2() by comparing against _bern_modp_powg() for\n   a range of p and k.\n\n   Returns 1 on success.\n*/\nint test__bern_modp_pow2()\n{\n   int success = 1;\n\n   // exhaustive comparison over some small p and k\n   for (long p = 5; p < 2000 && success; p += 2)\n   {\n      if (!ProbPrime(p))\n         continue;\n\n      for (long k = 2; k <= p - 3 && success; k += 2)\n         success = success && testcase__bern_modp_pow2(p, k);\n   }\n\n   // a few larger values of p\n   for (long p = 1000000; p < 1030000; p++)\n   {\n      if (!ProbPrime(p))\n         continue;\n\n      long k = 2 * (rand() % ((p-3)/2)) + 2;\n      success = success && testcase__bern_modp_pow2(p, k);\n   }\n\n   // if we're on a 32-bit machine, try a single example with p right near\n   // NTL's boundary (this is infeasible on a 64-bit machine)\n   if (NTL_SP_NBITS <= 32)\n   {\n      long p = NTL_SP_BOUND - 1;\n      while (!ProbPrime(p))\n         p--;\n      success = success & testcase__bern_modp_pow2(p, 10);\n   }\n\n   // try a few just below the REDC barrier\n   if (ULONG_BITS == 32)\n   {\n      long boundary = 1L << (ULONG_BITS/2 - 1);\n      for (long p = boundary - 1000; p < boundary && success; p++)\n      {\n         if (ProbPrime(p))\n         {\n            for (long trial = 0; trial < 1000 && success; trial++)\n            {\n               long k = 2 * (rand() % ((p-3)/2)) + 2;\n               success = success && testcase__bern_modp_pow2(p, k);\n            }\n         }\n      }\n   }\n   else\n   {\n      // on a 64-bit machine, only try one, since these are huge!\n      long p = 1L << (ULONG_BITS/2 - 1);\n      while (!ProbPrime(p))\n         p--;\n      success = success && testcase__bern_modp_pow2(p, 10);\n   }\n\n   return success;\n}\n\n\n/*\n   Tests bern_rat() by comparing against the naive algorithm for several small\n   k, and testing against bern_modp() for a couple of larger k.\n\n   Returns 1 on success.\n*/\nint test_bern_rat()\n{\n   int success = 1;\n\n   const long MAX = 300;\n   mpq_t bern[MAX];\n\n   // compute B_k's as rational numbers using naive algorithm\n   for (long i = 0; i < MAX; i++)\n      mpq_init(bern[i]);\n   bern_naive(bern, MAX);\n\n   mpq_t x;\n   mpq_init(x);\n\n   // exhaustive test for small k\n   for (long k = 0; k < MAX && success; k++)\n   {\n      bern_rat(x, k, 4);    // try with 4 threads just for fun\n      success = success && mpq_equal(x, bern[k]);\n   }\n\n   // try a few larger k\n   for (long i = 0; i < 50 && success; i++)\n   {\n      long k = ((random() % 20000) / 2) * 2;\n      bern_rat(x, k, 4);\n\n      // compare with modular information\n      long p = 1000003;\n      long num = mpz_fdiv_ui(mpq_numref(x), p);\n      long den = mpz_fdiv_ui(mpq_denref(x), p);\n      success = success && (MulMod(bern_modp(p, k), den, p) == num);\n   }\n\n   mpq_clear(x);\n   for (long i = 0; i < MAX; i++)\n      mpq_clear(bern[i]);\n\n   return success;\n}\n\n\nvoid report(int success)\n{\n   if (success)\n      cout << \"ok\" << endl;\n   else\n   {\n      cout << \"failed!\" << endl;\n      abort();\n   }\n}\n\n\nint main(int argc, char* argv[])\n{\n   if (argc == 1)\n   {\n      cout << \"bernmm test module\" << endl;\n      cout << endl;\n      cout << \"   bernmm-test --test\" << endl;\n      cout << \"        runs test suite\" << endl;\n      cout << \"   bernmm-test --rational <k> <threads>\" << endl;\n      cout << \"        computes B_k with <threads> threads\" << endl;\n      cout << \"   bernmm-test --modular <p> <k>\" << endl;\n      cout << \"        computes B_k mod p\" << endl;\n      return 0;\n   }\n\n   if (!strcmp(argv[1], \"--test\"))\n   {\n      cout << \"testing _bern_modp_powg()... \" << flush;\n      report(test__bern_modp_powg());\n\n      cout << \"testing _bern_modp_pow2()... \" << flush;\n      report(test__bern_modp_pow2());\n\n      cout << \"testing bern_rat()... \" << flush;\n      report(test_bern_rat());\n   }\n   else if (!strcmp(argv[1], \"--rational\"))\n   {\n      if (argc <= 3)\n      {\n         cout << \"not enough arguments\" << endl;\n         return 0;\n      }\n      long k = atol(argv[2]);\n      long threads = atol(argv[3]);\n      mpq_t r;\n      mpq_init(r);\n      bern_rat(r, k, threads);\n      gmp_printf(\"%Zd/%Zd\\n\", mpq_numref(r), mpq_denref(r));\n      mpq_clear(r);\n   }\n   else if (!strcmp(argv[1], \"--modular\"))\n   {\n      if (argc <= 3)\n      {\n         cout << \"not enough arguments\" << endl;\n         return 0;\n      }\n      long p = atol(argv[2]);\n      long k = atol(argv[3]);\n      cout << bern_modp(p, k) << endl;\n   }\n   else\n   {\n      cout << \"unknown command\" << endl;\n   }\n\n   return 0;\n}\n\n\n// end of file ================================================================\n", "meta": {"hexsha": "06f381500de8dda717f12b2b6f29b66b10880a41", "size": 8044, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sage/rings/bernmm/bernmm-test.cpp", "max_stars_repo_name": "bopopescu/sage", "max_stars_repo_head_hexsha": "2d495be78e0bdc7a0a635454290b27bb4f5f70f0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1742.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:32:52.000Z", "max_issues_repo_path": "src/sage/rings/bernmm/bernmm-test.cpp", "max_issues_repo_name": "Ivo-Maffei/sage", "max_issues_repo_head_hexsha": "467fbc70a08b552b3de33d9065204ee9cbfb02c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T19:17:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:59:30.000Z", "max_forks_repo_path": "src/sage/rings/bernmm/bernmm-test.cpp", "max_forks_repo_name": "dimpase/sage", "max_forks_repo_head_hexsha": "468f23815ade42a2192b0a9cd378de8fdc594dcd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 495.0, "max_forks_repo_forks_event_min_datetime": "2015-01-10T10:23:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:06:11.000Z", "avg_line_length": 22.6591549296, "max_line_length": 79, "alphanum_fraction": 0.5481103928, "num_tokens": 2533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.5563118925412069}}
{"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 * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearloadvector.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <functional>\n\nnamespace ElementMatrixComputation {\n\nnamespace {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector4d computeLoadVector(\n    const Eigen::MatrixXd &vertices,\n    std::function<double(const Eigen::Vector2d &)> f) {\n  // Number of nodes of the element: triangles = 3, rectangles = 4\n  const int num_nodes = vertices.cols();\n  // Vector for returning element vector\n  Eigen::Vector4d elem_vec = Eigen::Vector4d::Zero();\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return elem_vec;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace\n\nEigen::Vector4d MyLinearLoadVector::Eval(const lf::mesh::Entity &cell) {\n  // Topological type of the cell\n  const lf::base::RefEl ref_el{cell.RefEl()};\n  const lf::base::size_type num_nodes{ref_el.NumNodes()};\n\n  // Obtain the vertex coordinates of the cell, which completely\n  // describe its shape.\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n\n  // Matrix storing corner coordinates in its columns\n  auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n\n  return computeLoadVector(vertices, f_);\n}\n\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "8dedf844cb176b6004777d6919d4309e405bdfe2", "size": 1456, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/templates/mylinearloadvector.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/ElementMatrixComputation/templates/mylinearloadvector.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/ElementMatrixComputation/templates/mylinearloadvector.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 25.5438596491, "max_line_length": 72, "alphanum_fraction": 0.698489011, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.5563116577671317}}
{"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": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <iostream>\n#include <random>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n#include <Eigen/LU>\n\n#include <gtest/gtest.h>\n#include \"calibration/Calibration.h\"\n\nint main(int argc, char **argv) \n{\n\tstd::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<> dis(-1, 1);\n\n\t// AX = ZB\n\tEigen::Matrix4f Z = Eigen::Matrix4f::Identity();\n\tEigen::Vector4f qz_use = Eigen::Vector4f(dis(gen), dis(gen), dis(gen), dis(gen) );\n\tEigen::Quaternionf qz( qz_use[0], qz_use[1], qz_use[2], qz_use[3] );\n\tqz.normalize();\n\tEigen::Vector3f tz = Eigen::Vector3f( dis(gen), dis(gen), dis(gen) );\n\tZ.block<3,3>(0,0) = qz.toRotationMatrix();\n\tZ.block<3,1>(0,3) = tz;\n\t//std::cout << \"Z: \" << std::endl << Z << std::endl;\n\n \tEigen::Matrix4f X = Eigen::Matrix4f::Identity();\n\tEigen::Vector4f qx_use = Eigen::Vector4f(dis(gen), dis(gen), dis(gen), dis(gen) );\n\tEigen::Quaternionf qx( qx_use[0], qx_use[1], qx_use[2], qx_use[3] );\n\tqx.normalize();\n\tEigen::Vector3f tx = Eigen::Vector3f(dis(gen),dis(gen), dis(gen));\n\tX.block<3,3>(0,0) = qx.toRotationMatrix();\n\tX.block<3,1>(0,3) = tx;\n\t//std::cout << \"X: \" << std::endl << X << std::endl;\n\n \tint NPoses = 6;\n\n\n\tstd::vector<Matrix4f> A, B;\n\n\tEigen::Matrix4f a = Eigen::Matrix4f::Identity();\n\n\n\tEigen::Vector4f q_use = Eigen::Vector4f::Random();\n\tEigen::Quaternionf q( q_use[0], q_use[1], q_use[2], q_use[3]);\n\tq.normalize();\n\n\tEigen::Vector3f t = Eigen::Vector3f( dis(gen), dis(gen), dis(gen) );\n\n\ta.block<3,3>(0,0) = q.toRotationMatrix();\n\ta.block<3,1>(0,3) = t;\n\n\tfor (int i = 0; i < NPoses; i++)\n\t\n\t{\n\n\t\t// test data\n\t\tEigen::Matrix4f b = Eigen::Matrix4f::Identity();\n\t\tb = Z.inverse()*a*X;\n\n\t\tEigen::Matrix4f d = Eigen::Matrix4f::Identity();\n        \n\t\tEigen::Vector3f t = 0.001*Eigen::Vector3f( dis(gen),dis(gen), dis(gen) );\n\n\t\tfloat roll = dis(gen)*M_PI/512;\n\t\tfloat pitch = dis(gen)*M_PI/512;\n\t\tfloat yaw = dis(gen)*M_PI/512;\n\t\tEigen::Matrix3f R;\n\t\tR = AngleAxisf(roll, Vector3f::UnitX())\n\t\t\t*AngleAxisf(pitch, Vector3f::UnitY())\n  \t\t\t*AngleAxisf(yaw, Vector3f::UnitZ());\n\t\td.block<3,3>(0,0) = R;\n\t\td.block<3,1>(0,3) = t;\n\n\t\ta = d*a;\n\n\t\tA.push_back(a);\n\t\tB.push_back(b);\n\n\t}\n\n\t// first, create an object of your class \n\tcalibration::Calibration mycalib;\n\n\tmycalib.setInput(A, B);\n\n\tmycalib.computeNonLinOpt();\n\n\tEigen::Matrix4f Tx, Tz;\n\tTx = Eigen::Matrix4f::Identity();\n\tTz = Eigen::Matrix4f::Identity();\n\tmycalib.getOutput(Tz, Tx);\n\n\t// print out the result\n\n\n\tstd::cout << \"Input Z: \" << std::endl << Z << std::endl;\n\tstd::cout << \"Estimated Z:\" << std::endl << Tz << std::endl;\n\tstd::cout << \"Error over Z estimation: \" << std::endl << Z-Tz << std::endl << std::endl;\n\n\t\n\tstd::cout << \"Input X: \" << std::endl << X << std::endl;\n\tstd::cout << \"Estimated X:\" << std::endl << Tx << std::endl;\n\tstd::cout << \"Error over X estimation: \" << std::endl << X-Tx << std::endl;\n\n\treturn 0;\n}", "meta": {"hexsha": "8875d2814c59375168347bdb552335edcc9523e0", "size": 2956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/calibration_test.cpp", "max_stars_repo_name": "gialen/calibration", "max_stars_repo_head_hexsha": "e9247df76d36ddc5f7bf928aa2433214032449c7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-14T22:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-14T22:44:21.000Z", "max_issues_repo_path": "test/calibration_test.cpp", "max_issues_repo_name": "gialen/calibration", "max_issues_repo_head_hexsha": "e9247df76d36ddc5f7bf928aa2433214032449c7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/calibration_test.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": 26.6306306306, "max_line_length": 89, "alphanum_fraction": 0.6187415426, "num_tokens": 1028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5562185446087238}}
{"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": "#include <boost/ut.hpp>\n#include <units/isq/si/international/length.h>\n#include <units/isq/si/international/speed.h>  // IWYU pragma: keep\n#include <units/isq/si/length.h>\n#include <units/isq/si/speed.h>  // IWYU pragma: keep\n#include <units/isq/si/time.h>\n\nnamespace embed {\nusing namespace units::isq;\nnamespace units_testing {\nSpeed auto avg_speed(Length auto d, Time auto t)\n{\n  return d / t;\n}\n}  // namespace units_testing\n\n// This test is here purely to ensure that units compile and work in\n// libembeddedhal\nboost::ut::suite units_test = []() {\n  using namespace boost::ut;\n\n  using namespace units::isq;\n  using namespace units::aliases::isq::si::speed;\n  using namespace units::aliases::isq::si::length;\n  using namespace units::aliases::isq::si::time;\n  using units::aliases::isq::si::international::speed::mi_per_h;\n\n  Speed auto v1 =\n    units_testing::avg_speed(km<std::int64_t>(1000), h<std::int64_t>(3));\n  Speed auto v2 = units_testing::avg_speed(\n    si::length<si::international::mile>(140), si::time<si::hour>(2));\n\n  expect(v1 == km_per_h<std::int64_t>(333));\n  expect(v2 == mi_per_h(70));\n};\n}  // namespace embed\n", "meta": {"hexsha": "1bbae47e625f5b716aa9139fec72d6e6c7c66aba", "size": 1137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/units.test.cpp", "max_stars_repo_name": "MaliaLabor/libembeddedhal", "max_stars_repo_head_hexsha": "9f40affd438602df7ad818a1573c51347fd753bd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-10T20:25:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T20:25:00.000Z", "max_issues_repo_path": "tests/units.test.cpp", "max_issues_repo_name": "MaliaLabor/libembeddedhal", "max_issues_repo_head_hexsha": "9f40affd438602df7ad818a1573c51347fd753bd", "max_issues_repo_licenses": ["Apache-2.0"], "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/units.test.cpp", "max_forks_repo_name": "MaliaLabor/libembeddedhal", "max_forks_repo_head_hexsha": "9f40affd438602df7ad818a1573c51347fd753bd", "max_forks_repo_licenses": ["Apache-2.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.7297297297, "max_line_length": 73, "alphanum_fraction": 0.7027264732, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5562185310217042}}
{"text": "/* Copyright (c) 2017, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n// g++ -Wall -std=c++1z -I /usr/include/eigen3/ main.cpp -o test \n#include <random>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include \"vmf.hpp\"\n\nint main() {\n\n  std::mt19937 rnd(1);\n  vMF<float,3> vmf(Eigen::Vector3f(0,0,1), 100);\n\n  std::ofstream out(\"vmfSamples_tau100.csv\");\n  for (size_t i=0; i<10000; ++i) {\n    Eigen::Vector3f x = vmf.sample(rnd);\n    out << x(0) << \" \" << x(1) << \" \" << x(2) << std::endl;\n  }\n  out.close();\n\n  return 0;\n}\n", "meta": {"hexsha": "9a610f29f5c63d2ba9d1636b3f3ed3a5ef1ad834", "size": 616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/dpvmf/outputvMFsamples.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": "experiments/dpvmf/outputvMFsamples.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": "experiments/dpvmf/outputvMFsamples.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": 23.6923076923, "max_line_length": 65, "alphanum_fraction": 0.6152597403, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5562002295425155}}
{"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      // \u753b\u6bcf\u4e2a\u4f4d\u59ff\u7684\u4e09\u4e2a\u5750\u6807\u8f74\n      Vector3d Ow = poses[i].translation();\n      Vector3d Xw = poses[i] * (0.1 * Vector3d(1, 0, 0));\n      Vector3d Yw = poses[i] * (0.1 * Vector3d(0, 1, 0));\n      Vector3d Zw = poses[i] * (0.1 * Vector3d(0, 0, 1));\n      glBegin(GL_LINES);\n      glColor3f(1.0, 0.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Xw[0], Xw[1], Xw[2]);\n      glColor3f(0.0, 1.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Yw[0], Yw[1], Yw[2]);\n      glColor3f(0.0, 0.0, 1.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Zw[0], Zw[1], Zw[2]);\n      glEnd();\n    }\n    // \u753b\u51fa\u8fde\u7ebf\n    for (size_t i = 0; i < poses.size(); i++) {\n      glColor3f(1.0, 0.0, 0.0);\n      glBegin(GL_LINES);\n      auto p1 = poses[i], p2 = poses[i + 1];\n      glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n      glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n      glEnd();\n    }\n\n    for (size_t i = 0; i < gt_poses.size(); i++) {\n      // \u753b\u6bcf\u4e2a\u4f4d\u59ff\u7684\u4e09\u4e2a\u5750\u6807\u8f74\n      Vector3d Ow = gt_poses[i].translation();\n      Vector3d Xw = gt_poses[i] * (0.1 * Vector3d(1, 0, 0));\n      Vector3d Yw = gt_poses[i] * (0.1 * Vector3d(0, 1, 0));\n      Vector3d Zw = gt_poses[i] * (0.1 * Vector3d(0, 0, 1));\n      glBegin(GL_LINES);\n      glColor3f(1.0, 0.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Xw[0], Xw[1], Xw[2]);\n      glColor3f(0.0, 1.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Yw[0], Yw[1], Yw[2]);\n      glColor3f(0.0, 0.0, 1.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Zw[0], Zw[1], Zw[2]);\n      glEnd();\n    }\n    // \u753b\u51fa\u8fde\u7ebf\n    for (size_t i = 0; i < gt_poses.size(); i++) {\n      glColor3f(0.0, 1.0, 0.0);\n      glBegin(GL_LINES);\n      auto p1 = gt_poses[i], p2 = gt_poses[i + 1];\n      glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n      glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n      glEnd();\n    }\n    pangolin::FinishFrame();\n    usleep(5000);   // sleep 5 ms\n  }\n}\n\n/*******************************************************************************************/\nvoid DrawTrajectory(vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> poses) {\n  // create pangolin window and plot the trajectory\n  pangolin::CreateWindowAndBind(\"Trajectory Viewer\", 1024, 768);\n  glEnable(GL_DEPTH_TEST);\n  glEnable(GL_BLEND);\n  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n  pangolin::OpenGlRenderState s_cam(\n    pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n    pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n  );\n\n  pangolin::View &d_cam = pangolin::CreateDisplay()\n    .SetBounds(0.0, 1.0, 0.0, 1.0, -1024.0f / 768.0f)\n    .SetHandler(new pangolin::Handler3D(s_cam));\n\n  while (pangolin::ShouldQuit() == false) {\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n    d_cam.Activate(s_cam);\n    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n    glLineWidth(2);\n    for (size_t i = 0; i < poses.size(); i++) {\n      // \u753b\u6bcf\u4e2a\u4f4d\u59ff\u7684\u4e09\u4e2a\u5750\u6807\u8f74\n      Vector3d Ow = poses[i].translation();\n      Vector3d Xw = poses[i] * (0.1 * Vector3d(1, 0, 0));\n      Vector3d Yw = poses[i] * (0.1 * Vector3d(0, 1, 0));\n      Vector3d Zw = poses[i] * (0.1 * Vector3d(0, 0, 1));\n      glBegin(GL_LINES);\n      glColor3f(1.0, 0.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Xw[0], Xw[1], Xw[2]);\n      glColor3f(0.0, 1.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Yw[0], Yw[1], Yw[2]);\n      glColor3f(0.0, 0.0, 1.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Zw[0], Zw[1], Zw[2]);\n      glEnd();\n    }\n    // \u753b\u51fa\u8fde\u7ebf\n    for (size_t i = 0; i < poses.size(); i++) {\n      glColor3f(0.0, 0.0, 0.0);\n      glBegin(GL_LINES);\n      auto p1 = poses[i], p2 = poses[i + 1];\n      glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n      glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n      glEnd();\n    }\n    pangolin::FinishFrame();\n    usleep(5000);   // sleep 5 ms\n  }\n}\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": "#pragma once\n#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid split(const string& s, char c, vector<string>& v) {\n    string::size_type i = 0;\n    string::size_type j = s.find(c);\n\n    while (j != string::npos) {\n        v.push_back(s.substr(i, j-i));\n        i = ++j;\n        j = s.find(c, j);\n    }\n    if (j == string::npos) v.push_back(s.substr(i, s.length( )));\n}\n\ninline double string2double(const std::string& s){ std::istringstream i(s); double x = 0; i >> x; return x; }\n\nMatrixXd read_matrix_file(string filename, char sep) {\n    cerr << \"Loading \" << filename << endl;\n    ifstream myfile(filename.c_str());\n    stringstream ss;\n\n    vector<vector<double> > M;\n    if (myfile.is_open()) {\n        string line;\n\n        while ( getline(myfile,line) ) {\n            //split string based on \",\" and store results into vector\n            vector<string> fields;\n            split(line, sep, fields);\n\n            vector<double>row(fields.size());\n            for( int i=0; i < fields.size(); i++ ) {\n                row[i] = string2double(fields[i]);\n            }\n            M.push_back(row);\n        }\n    }\n\n    MatrixXd X( (int) M.size(), (int) M[0].size() );\n    for(int i=0; i < M.size(); i++ ) {\n        for(int j=0; j < M[i].size(); j++ ) {  \n            X(i,j)=M[i][j]; \n        }\n    }\n    return X;\n}\n", "meta": {"hexsha": "cf7ff5a522e58ed3133892672fdaa789aff16584", "size": 1401, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/csv-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": "test/csv-eigen.hpp", "max_issues_repo_name": "vitorpavinato/abcranger", "max_issues_repo_head_hexsha": "71f950817bedeebed12d13610d8747c6dcc75a72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2019-06-20T11:39:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T04:13:46.000Z", "max_forks_repo_path": "test/csv-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": 25.9444444444, "max_line_length": 109, "alphanum_fraction": 0.533904354, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5561100478798597}}
{"text": "#include \"TestFunctions.h\"\n\n#include \"stdafx.h\"\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include \"cc_GraphicsFunctions.h\"\n#include \"cc_Nastran.h\"\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\n\n/////////////////////////////////////////////////////////////////////////////////\nvoid Tests::DotProduct_2D_test()\n{\n\n\t// Dot Product  2D\n\tstd::vector<double>  vector_1(2);\n\tstd::vector<double>  vector_2(2);\n\n\tvector_1[0] =\t2.0; \n\tvector_1[1] =\t-3.0;\n\tvector_2[0] =\t-.5;\n\tvector_2[1] =\t 4.0;\n\n\tdouble dp = DotProduct_2D(vector_1, vector_2);\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(-13, dp, 0.0001);\n\n}\n/////////////////////////////////////////////////////////////////////////////////\nvoid Tests::DotProduct_3D_test()\n{\n\t/// Dot Product  3D\n\tstd::vector<double>  vector_1(3);\n\tstd::vector<double>  vector_2(3);\n\n\tvector_1[0] =\t 4.0; \n\tvector_1[1] =\t 2.0;\n\tvector_1[2] =\t-6.0;\n\tvector_2[0] =\t-5.0;\n\tvector_2[1] =\t 3.0;\n\tvector_2[2] =\t-2.0;\n\n\tdouble dp = DotProduct_3D(vector_1, vector_2);\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(-2, dp, 0.0001);\n\n}\n/////////////////////////////////////////////////////////////////////////////////\nvoid Tests::CrossProduct_3D_test()\n{\n\n\tstd::vector<double>  vector_1(3);\n\tstd::vector<double>  vector_2(3);\n\n\tvector_1[0] =\t 2.0; \n\tvector_1[1] =\t 1.0;\n\tvector_1[2] =\t-3.0;\n\tvector_2[0] =\t 3.0;\n\tvector_2[1] =\t-1.0;\n\tvector_2[2] =\t 4.0;\n\n\tstd::vector<double>  vector_out = CrossProduct_3D(vector_1, vector_2);\n\n\t//std::cout << std::endl << \"Cross Product: \" <<  vector_out[0] << \"  \" <<  vector_out[1] << \"  \" <<  vector_out[2];\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(1, vector_out[0], 0.0001);\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(-17, vector_out[1], 0.0001);\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(-5, vector_out[2], 0.0001);\n}\n\nvoid Tests::Magnitude_3D_test()\n{\n\tstd::vector<double>  vector_1(3);\n\n\tvector_1[0] =\t 3.0; \n\tvector_1[1] =\t 2.0;\n\tvector_1[2] =\t-6.0;\n\n\t// Answer should be 7.0\n\tdouble m = Magnitude_3D(vector_1);\n\t//std::cout << std::endl << \"Magnitude 3D: \" <<   m;\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(7, m, 0.0001);\n}\n\n/////////////////////////////////////////////////////////////////////////////////\nvoid Tests::UnitVector_3D_test()\n{\n\n\t///** Magnitude 3D\n\tstd::vector<double>  vector_1(3);\n\n\tvector_1[0] =\t 1.0; \n\tvector_1[1] =\t 5.0;\n\tvector_1[2] =\t 3.0;\n\n\tstd::vector<double>  vector_out = UnitVector_3D(vector_1);\n\n\t// Answer should be 0.169030851\t0.845154255\t0.507092553\n\t//std::cout << std::endl << \"Unit Vector: \" <<  vector_out[0] << \"  \" <<  vector_out[1] << \"  \" <<  vector_out[2];\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(0.16903, vector_out[0], 0.0001);\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(0.84515, vector_out[1], 0.0001);\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(0.50709, vector_out[2], 0.0001);\n\n}\n/////////////////////////////////////////////////////////////////////////////////\n\nvoid Tests::PointOnLine_2D_test()\n{\n\n\tbool b = PointOnLine_2D( Point_2D(-.0001, 10),Line_2D( Point_2D(0,10),   Point_2D(10,10)), .001 );\n\n\tCPPUNIT_ASSERT(b);\n\n}\n/////////////////////////////////////////////////////////////////////////////////\n#if 0\n\t////////////////////////////////\n\t//\tstruct BoostPolygon_struct\n\t///////////////////////////////\n\tstruct BoostPolygon_struct\n\t{\n\t\ttypedef boost::geometry::model::d2::point_xy<double> boostpoint_type;\n\t\ttypedef boost::geometry::model::polygon<boostpoint_type> boostpolygon_type;\n\t\t\t\n\t\tboostpolygon_type boostPolygon;\n\n\t};\nstatic void Point2D_Within_Polygon_2D_test(bool in_IncludePointsOnBoundary)\n{\n\t// WARNING - Before running this function, make sure that BoostPolygon_struct has not changed\n\t// the above version should agree verbatim with the GraphicsFunctions.cpp version\n\n\tstd::vector<Point_3D> points;\n\tpoints.push_back( Point_3D(0,0,0) );\n\tpoints.push_back( Point_3D(10,0,0) );\n\tpoints.push_back( Point_3D(10,10,0) );\n\tpoints.push_back( Point_3D(0,10,0) );\n\t\n\tstd::vector<Line_2D> PolygonLines;\n\tfor ( std::vector<Point_3D>::const_iterator i(points.begin()); i != points.end(); ++i )\n\t{\n\t\tstd::vector<Point_3D>::const_iterator  j = i;\n\t\t++j;\n\t\tif ( j != points.end() )\n\t\t\tPolygonLines.push_back( Line_2D( Point_2D(i->x,i->y),   Point_2D(j->x,j->y) ));\n\t\telse\n\t\t\tPolygonLines.push_back( Line_2D( Point_2D(i->x,i->y), Point_2D( points.begin()->x,points.begin()->y)) );\n\t}\n\n\t::BoostPolygon_struct   boostPolygon_struct;\n\t// Populate boost polygon\n\tfor ( std::vector<Point_3D>::const_iterator i(points.begin()); i != points.end(); ++i )\n\t{\n\t\tboost::geometry::exterior_ring(boostPolygon_struct.boostPolygon).push_back(boost::geometry::model::d2::point_xy<double>(i->x,i->y));\n\t} \n\t// Correct the plolygon - clockwise orientiatin, closed loop (i.e. last point repeated to close the loop\n\tboost::geometry::correct(boostPolygon_struct.boostPolygon);\n\n\tif (   boost::geometry::intersects(boostPolygon_struct.boostPolygon) )\n\t\tstd::cout << std::endl << \"ERROR -->Intersects\";\n\telse\n\t\tstd::cout << std::endl << \"Does Not Intersect\";\n\n\n\tstd::vector<Line_2D> PolygonLinesSorted = SortPolygonLines (PolygonLines, .001 );\n\n\tif ( Point2D_Within_Polygon_2D( Point_2D(-.001, 10.001), PolygonLinesSorted, &boostPolygon_struct, true, .001) )\n\t\tstd::cout << std::endl << \"Inside/On Polygon = TRUE\";\n\telse\n\t\tstd::cout << std::endl << \"Inside/On Polygon = FALSE\";\n\n\tif ( Point2D_Within_Polygon_2D( Point_2D(-.001, 10.001), PolygonLinesSorted,&boostPolygon_struct, false , .001) )\n\t\tstd::cout << std::endl << \"Inside (but not on) Polygon = TRUE\";\n\telse\n\t\tstd::cout << std::endl << \"Inside (but not on) = FALSE\";\n\n\tif ( Point2D_Within_Polygon_2D( Point_2D(1.0, 6), PolygonLinesSorted, &boostPolygon_struct,true, .001) )\n\t\tstd::cout << std::endl << \"Inside/On Polygon = TRUE\";\n\telse\n\t\tstd::cout << std::endl << \"Inside/On Polygon = FALSE\";\n\n\tif ( Point2D_Within_Polygon_2D( Point_2D(1.0, 6), PolygonLinesSorted, &boostPolygon_struct,false, .001) )\n\t\tstd::cout << std::endl << \"Inside (but not on) = TRUE\";\n\telse\n\t\tstd::cout << std::endl << \"Inside (but not on) = FALSE\";\n\n\tstd::vector<double> vector_x_axis;\n\tstd::vector<double> vector_y_axis;\n\n\tVectorsFormingIntersection_of_FirstAndLastLine_2D(PolygonLinesSorted, vector_x_axis, vector_y_axis);\n\n\tstd::cout << std::endl << \"vector_x_axis: \" <<  std::setw(10) <<  vector_x_axis[0] << \n\t\t\t\t\t\t\t\t\t\t\t\t\tstd::setw(10) <<  vector_x_axis[1];\n\n\tstd::cout << std::endl << \"vector_y_axis: \" <<  std::setw(10) <<  vector_y_axis[0] << \n\t\t\t\t\t\t\t\t\t\t\t\t\tstd::setw(10) <<  vector_y_axis[1]; \n}\n\nvoid Test::Point2D_Within_Polygon_2D_test()\n{\n\tPoint2D_Within_Polygon_2D_test(true);\n}\n#endif\n/////////////////////////////////////////////////////////////////////////////////\nvoid Tests::AngleBetweenVectors_test()\n{\n\t\n\tstd::vector<double>  vector_1(3);\n\tvector_1[0] =\t 0.0; \n\tvector_1[1] =\t 1.0;\n\tvector_1[2] =\t 0.0;\n\n\tstd::vector<double>  vector_2(3);\n\tvector_2[0] =\t 0; \n\tvector_2[1] =\t -5.0;    //-1.41421;\n\tvector_2[2] =\t 5.0;    //1.41421;\n\n\n\t/* \n\tstd::vector<double>  vector_1(3);\n\tvector_1[0] =\t 2.0; \n\tvector_1[1] =\t 2.0;\n\tvector_1[2] =\t 12.0;\n\n\tstd::vector<double>  vector_2(3);\n\tvector_2[0] =\t 1.0; \n\tvector_2[1] =\t 1.0;\n\tvector_2[2] =\t 6.0;\n\t*/\n\n\tdouble a = AngleBetweenVectors_3D(vector_1, vector_2);\n\t//std::cout << std::endl << \"AngleBetweenVectors: \" << a;\n\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(2.35619, a, 0.0001);\n\t\n\n}\n/////////////////////////////////////////////////////////////////////////////////\nvoid Tests::TransformationMatrix_test()\n{\n\tstd::vector<double>  vector_1(3);\n\t// xy plane\n\t//vector_1[0] =\t 1.0; \n\t//vector_1[1] =\t 1.0;\n\t//vector_1[2] =\t 0.0;\n\t// yz plane\n\t//vector_1[0] =\t 0.0; \n\t//vector_1[1] =\t 1.0;\n\t//vector_1[2] =\t 1.0;\n\t// xz plane\n\tvector_1[0] =\t 1.0; \n\tvector_1[1] =\t 0.0;\n\tvector_1[2] =\t 1.0;\n\n\n\tstd::vector<double>  vector_2(3);\n\t// xy plane\n\t//vector_2[0] =\t -1; \n\t//vector_2[1] =\t 1;\n\t//vector_2[2] =\t 0;\n\t// yz plane\n\t//vector_2[0] =\t 0.0; \n\t//vector_2[1] =\t -1.0;\n\t//vector_2[2] =\t 1.0;\n\t// xz plane\n\tvector_2[0] =\t -1.0; \n\tvector_2[1] =\t 0.0;\n\tvector_2[2] =\t 1.0;\n\n\tstd::vector<double>  offset(3);\n\toffset[0] =\t 0; \n\toffset[1] =\t 0;\n\toffset[2] =\t 0;\n\n\t//std::cout << std::endl << \"Vector 1: \" <<  std::setw(10) << vector_1[0] <<  std::setw(10) << vector_1[1] << std::setw(10) << vector_1[2];\n\t//std::cout << std::endl << \"Vector 2: \" <<  std::setw(10) << vector_2[0] << std::setw(10)  << vector_2[1] << std::setw(10) << vector_2[2];\n\t//std::cout << std::endl << \"offset  : \" <<  std::setw(10) << offset[0]   << std::setw(10)  << offset[1]   << std::setw(10) << offset[2];\n\t\n\tTransformationMatrix  transformationMatrix_1;\n\n\ttransformationMatrix_1.setTransformationMatrix( vector_1, vector_2, offset );\n\n\t//std::cout << std::endl << transformationMatrix_1;\n\t//std::cout << std::endl;\n\n\tPoint_3D  TestCoords;\n\t// xy plane\n\t//TestCoords.x = 03;\n\t//TestCoords.y = 3;\n\t//TestCoords.z = 0;\n\t// yz plane\n\t//TestCoords.x = 0;\n\t//TestCoords.y = 3;\n\t//TestCoords.z = 3;\n\t// xz plane\n\tTestCoords.x = 0;\n\tTestCoords.y = 0;\n\tTestCoords.z = 4;\n\n\tPoint_3D  TransformedCoords;\n\n\tTransformedCoords = transformationMatrix_1.getTransformedCoordinates(  TestCoords  );\n\n\t//std::cout << std::endl << \"TestCoords x, y, z: \" <<  TestCoords ;\n\t//std::cout << std::endl << \"Transposed x, y, z: \" <<  TransformedCoords;\n\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(2.82843, TransformedCoords.x, 0.0001);\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(2.82843, TransformedCoords.y, 0.0001);\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(0, TransformedCoords.z, 0.0001);\n}\n/////////////////////////////////////////////////////////////////////////////////\nvoid Tests::ComputeRotationAngles_test()\n{\n\tstd::vector<double>  vector_1(3);\n\tstd::vector<double>  vector_2(3);\n\n\t//////////////////\n\t// No Rotation\n\t///////////////////\n\t/*\n\t// r[2,0] = 0   correct\n\tvector_1[0] =\t 1.0; \n\tvector_1[1] =\t 0.0;\n\tvector_1[2] =\t 0.0;\n\n\tvector_2[0] =\t 0.0; \n\tvector_2[1] =\t 1.0;\n\tvector_2[2] =\t 0.0;\n\t*/\n\n\t//////////////////////////////////////////////////\n\t// Rotation  45 degrees counter clockwise about z\n\t/////////////////////////////////////////////////\n\t// r[2,0] = 0      correct\n\t/*\n\tvector_1[0] =\t 1.0; \n\tvector_1[1] =\t 1.0;\n\tvector_1[2] =\t 0.0;\n\n\tvector_2[0] =\t -1.0; \n\tvector_2[1] =\t 1.0;\n\tvector_2[2] =\t 0.0;\n\t*/\n\t//////////////////////////////////////////////////\n\t// Rotation  45 degrees clockwise about z\n\t/////////////////////////////////////////////////\n\t/*\n\t// r[2,0] = 0      correct\n\tvector_1[0] =\t 1.0; \n\tvector_1[1] =\t -1.0;\n\tvector_1[2] =\t 0.0;\n\n\tvector_2[0] =\t 1.0; \n\tvector_2[1] =\t 1.0;\n\tvector_2[2] =\t 0.0;\n\t*/\n\n\t//////////////////////////////////////////////////\n\t// Rotation  45 about Y\n\t/////////////////////////////////////////////////\n\t/*\n\t// r[2,0] = 0     correct\n\tvector_1[0] =\t 1.0; \n\tvector_1[1] =\t 0.0;\n\tvector_1[2] =\t 1.0;\n\n\tvector_2[0] =\t -1.0; \n\tvector_2[1] =\t 0.0;\n\tvector_2[2] =\t 1.0;\n\t*/\n\n\t//////////////////////////////////////////////////\n\t// Rotation  -45 about Y\n\t/////////////////////////////////////////////////\n\t/*\n\t// r[2,0] = 0     correct\n\tvector_1[0] =\t 1.0; \n\tvector_1[1] =\t 0.0;\n\tvector_1[2] =\t -1.0;\n\n\tvector_2[0] =\t 1.0; \n\tvector_2[1] =\t 0.0;\n\tvector_2[2] =\t 1.0;\n\t*/\n\n\t//////////////////////////////////////////////////\n\t// Rotation  ??\n\t/////////////////////////////////////////////////\n\t// r[2,0] = 1   Correct\n\t/*\n\tvector_1[0] =\t 0.0; \n\tvector_1[1] =\t 1.0;\n\tvector_1[2] =\t 1.0;\n\n\tvector_2[0] =\t 0.0; \n\tvector_2[1] =\t -1.0;\n\tvector_2[2] =\t 1.0;\t\n\t*/\n\t//////////////////////////////////////////////////\n\t// Rotation  -????\n\t/////////////////////////////////////////////////\n\t// r[2,0] = 1   correct\n\t/*\n\tvector_1[0] =\t 0.0; \n\tvector_1[1] =\t -1.0;\n\tvector_1[2] =\t -1.0;\n\n\tvector_2[0] =\t 0.0; \n\tvector_2[1] =\t 1.0;\n\tvector_2[2] =\t -1.0;\n\t*/\n\n\t//////////////////////////////////////////////////\n\t// Rotation  -????\n\t/////////////////////////////////////////////////\n\t// r[2,0] = -1   correct\n\t/*\n\tvector_1[0] =\t 0.0; \n\tvector_1[1] =\t -1.0;\n\tvector_1[2] =\t 1.0;\n\n\tvector_2[0] =\t 0.0; \n\tvector_2[1] =\t 1.0;\n\tvector_2[2] =\t 1.0;\n\t*/\n\n\t//////////////////////////////////////////////////\n\t// Rotation  small angle counter clockwise about z\n\t/////////////////////////////////////////////////\n\t// r[2,0] = 0  correct\n\t/*\n\tvector_1[0] =\t 1.0; \n\tvector_1[1] =\t .00001;\n\tvector_1[2] =\t 0;\n\n\tvector_2[0] =\t -.00001;; \n\tvector_2[1] =\t 1.0;\n\tvector_2[2] =\t 0.0;\n\t*/\n\n\t//////////////////////////////////////////////////\n\t// Rotation  small angle counter clockwise about z\n\t/////////////////////////////////////////////////\n\t// r[2,0] = 0\n\t/*\n\tdouble  value_1 = .00000001;\n\tdouble  value_2 = .99999999;\n\n\tvector_1[0] =\t value_1;\n\tvector_1[1] =\t value_2; \n\tvector_1[2] =\t 0;\n\n\tvector_2[0] =\t -value_2; \n\tvector_2[1] =\t value_1;\n\tvector_2[2] =\t 0.0;\n\t*/\n\n\t//////////////////////////////////////////////////\n\t// Rotation  small angle counter clockwise about x\n\t/////////////////////////////////////////////////\n\t// r[2,0] = 0\n\t///*\n\tdouble  value_1 = .00000001;\n\tdouble  value_2 = .99999999;\n\n\tvector_1[0] =\t value_1;\n\tvector_1[1] =\t value_2; \n\tvector_1[2] =\t value_1;\n\n\tvector_2[0] =\t value_1; \n\tvector_2[1] =\t -value_1;\n\tvector_2[2] =\t value_2;\n\t//*/\n\n\n\tstd::vector<double>  offset(3);\n\toffset[0] =\t 0; \n\toffset[1] =\t 0;\n\toffset[2] =\t 0;\n\n\t//std::cout << std::endl << \"Vector 1: \" <<  std::setw(10) << vector_1[0] <<  std::setw(10) << vector_1[1] << std::setw(10) << vector_1[2];\n\t//std::cout << std::endl << \"Vector 2: \" <<  std::setw(10) << vector_2[0] << std::setw(10)  << vector_2[1] << std::setw(10) << vector_2[2];\n\t//std::cout << std::endl << \"offset  : \" <<  std::setw(10) << offset[0]   << std::setw(10)  << offset[1]   << std::setw(10) << offset[2];\n\t\n\tTransformationMatrix  transformationMatrix_1;\n\n\ttransformationMatrix_1.setTransformationMatrix( vector_1, vector_2, offset );\n\n\t//std::cout << std::endl << transformationMatrix_1;\n\t//std::cout << std::endl;\n\n\tdouble rot_x, rot_y, rot_z;\n\n\ttransformationMatrix_1.getRotationAngles( rot_x, rot_y, rot_z );\n\n\t//std::cout << std::endl << \"Rotation Angles x, y. z: \" <<  rot_x << \"  \" << rot_y << \"  \" << rot_z;\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(-1.5708, rot_x, 0.0001);\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(-1.5708, rot_y, 0.0001);\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(0, rot_z, 0.0001);\n}\n\n\n/////////////////////////////////////////////////////////////////////////////////\nvoid Tests::DuplicatePointInList_test()\n{\n\t////////////////////////////////\n\t// DuplicatePointInList\n\t////////////////////////////////\n\tdouble precision = .001;\n\tstd::list< Point_3D> Points_set;\n\tPoints_set.push_back(Point_3D(0, 0, 0));\n\tPoints_set.push_back(Point_3D(-5, 1, 4));\n\tPoints_set.push_back(Point_3D(.01, 0, 0));\n\tPoints_set.push_back(Point_3D(6, 7, 1));\n\n\tCPPUNIT_ASSERT(!DuplicatePointInList( Points_set, precision ));\n}\n/////////////////////////////////////////////////////////////////////////////////\nvoid Tests::PointsWithinPolygon_test()\n{\n\n\t////////////////////////////////\n\t// Points Within Polygon\n\t////////////////////////////////\n\n\t\t\n\tstd::map<int,GridPoint> gridPoints_map;\n\tstd::vector<Point_3D>   polygon;\n\tdouble precision = .0001;\n\tstd::vector<int>       gridPointIds_WithinPolygon;\n\t\t\n\t/*\n\tgridPoints_map[1] = GridPoint(1, 2, Point_3D(0, 0, 0), 2); \n\tgridPoints_map[2] = GridPoint(2, 2, Point_3D(5, 0, 0), 2); \n\tgridPoints_map[3] = GridPoint(3, 2, Point_3D(5, 5, 0), 2);\n\tgridPoints_map[4] = GridPoint(4, 2, Point_3D(0, 5, 0), 2);\t\n\n\tpolygon.push_back( Point_3D( -1,-1, 0));   // should yield 1 2 3 4\n\tpolygon.push_back( Point_3D( 6,-1, 0));\n\tpolygon.push_back( Point_3D( 6, 6, 0));\n\tpolygon.push_back( Point_3D(-1, 6, 0));\n\t*/\n\n\t/*\n\tgridPoints_map[1] = GridPoint(1, 2, Point_3D(2.1, 3.5, 0), 2); // should yield 1\n\tgridPoints_map[2] = GridPoint(2, 2, Point_3D(0, 6, 0), 2); \n\t//gridPoints_map[3] = GridPoint(3, 2, Point_3D(5, 5, 0), 2);\n\t//gridPoints_map[4] = GridPoint(4, 2, Point_3D(0, 5, 0), 2);\t\t\n\n\tpolygon.push_back( Point_3D( 0, 5, 0));\n\tpolygon.push_back( Point_3D( 0, 0, 0));\n\tpolygon.push_back( Point_3D( 5, 0, 0));\n\tpolygon.push_back( Point_3D( 5, 5, 0));\n\t*/\n\n\t/*\n\tpolygon.push_back( Point_3D( 1, 0, 0));\n\tpolygon.push_back( Point_3D( 5, 0, 0));\n\tpolygon.push_back( Point_3D( 5, 5, 0));\n\tpolygon.push_back( Point_3D( 1, 5, 0));\n\t*/\n\t\t\n\t/*\n\tgridPoints_map[1] = GridPoint(1, 2, Point_3D(6, 5, 1), 2); \n\tgridPoints_map[2] = GridPoint(2, 2, Point_3D(6, 5.5, 8), 2); \n\tgridPoints_map[3] = GridPoint(3, 2, Point_3D(10, 5, 20), 2);\n\tgridPoints_map[4] = GridPoint(4, 2, Point_3D(5, 5, 20), 2);\t\n\n\t\t\n\tpolygon.push_back( Point_3D( 6, 5, 0));  // should be 1 3 4\n\tpolygon.push_back( Point_3D( 10, 5, 0));\n\tpolygon.push_back( Point_3D( 10, 5, 20));\n\tpolygon.push_back( Point_3D( 5, 5, 20));\n\t*/\n\t\n\t\t\n\t// Slanted Plane\n\t\t\n\tgridPoints_map[1] = GridPoint(1, 2, Point_3D(3, 3, 18), 2); \n\tgridPoints_map[2] = GridPoint(2, 2, Point_3D(6, 5.1, 8), 2); \n\tgridPoints_map[3] = GridPoint(3, 2, Point_3D(10, 5, 20), 2);\n\tgridPoints_map[4] = GridPoint(4, 2, Point_3D(5, 5, 20), 2);\t\n\n\n\tpolygon.push_back( Point_3D( 1, 1, 0));  // should be 1 4\n\tpolygon.push_back( Point_3D( 6, 6, 0));\n\tpolygon.push_back( Point_3D( 6, 6, 20));\n\tpolygon.push_back( Point_3D( 1, 1, 20));\t\n\t\t\n\t\t\n\t// Slanted negative Plane\n\n/*\n\tgridPoints_map[1] = GridPoint(1, 2, Point_3D(-3, 3, 18), 2); \n\tgridPoints_map[2] = GridPoint(2, 2, Point_3D(6, 5.1, 8), 2); \n\tgridPoints_map[3] = GridPoint(3, 2, Point_3D(10, 5, 20), 2);\n\tgridPoints_map[4] = GridPoint(4, 2, Point_3D(5, 5, 20), 2);\t\n\n\tpolygon.push_back( Point_3D( -1, 1, 0));  // should be 1\n\tpolygon.push_back( Point_3D( -6, 6, 0));\n\tpolygon.push_back( Point_3D( -6, 6, 20));\n\tpolygon.push_back( Point_3D( -1, 1, 20));\n\t\t\n\t//GetGridPointsWithinPolygon( gridPoints_map,polygon, precision, gridPointIds_WithinPolygon);\n\n*/\n\n\tPolygon_3D polygon_obj(polygon, precision ); \n\n\t//polygon_obj.pointWithinGeometry( gridPoints_map[2].point, true, precision ); \n\n\t\t\n\tGetGridPointsWithinGeometry (\tgridPoints_map, \n\t\t\t\t\t\t\t\t\t\tpolygon_obj,\n\t\t\t\t\t\t\t\t\t\tGEOMETRY_INTERIOR_AND_BOUNDARY,\n\t\t\t\t\t\t\t\t\t\tprecision,\n\t\t\t\t\t\t\t\t\t\tgridPointIds_WithinPolygon );\n\n\tCPPUNIT_ASSERT_EQUAL(2, (int)gridPointIds_WithinPolygon.size());\n\tCPPUNIT_ASSERT_EQUAL(1, gridPointIds_WithinPolygon[0]);\n\tCPPUNIT_ASSERT_EQUAL(4, gridPointIds_WithinPolygon[1]);\n\n\t/*std::cout << std::endl << \"IDs Within Polygon\";\n\tfor ( std::vector<int>::const_iterator i( gridPointIds_WithinPolygon.begin()); i != gridPointIds_WithinPolygon.end(); ++i)\n\t{\n\t\tstd::cout << std::endl << *i;\n\t}*/\n\n}\n\n/////////////////////////////////////////////////////////////////////////////////\nstatic void GetGridPointsWithinCircle_test(bool in_IncludePointsOnBoundary)\n{\n\n\t/////////////////////////////\n\t// GetGridPointsWithinCircle\n\t/////////////////////////////\t\n\n\tstd::map<int,GridPoint> gridPoints_map;\n\tdouble precision = .0001;\n\tstd::vector<int>       gridPointIds_WithinCircle;\n\n\tgridPoints_map[1] = GridPoint(1, 2, Point_3D(0, 0, 10), 2); \n\tgridPoints_map[2] = GridPoint(2, 2, Point_3D(25, 21 - .0001, 10), 2); \n\tgridPoints_map[3] = GridPoint(3, 2, Point_3D(25.5, 20.5, 10.0001), 2);\n\tgridPoints_map[4] = GridPoint(4, 2, Point_3D(25.5, 20, 10), 2);\t\n\tgridPoints_map[5] = GridPoint(5, 2, Point_3D(25.00, 19, 10), 2);\t\n\n\tCircle_3D   circle(  Point_3D( 25,20, 10),    // should get back 2 3 4 5\n\t\t\t\t\t\t\tPoint_3D( 26,20, 10),\n\t\t\t\t\t\t\tPoint_3D( 25,22, 10));\n\n\t//Circle_3D   circle(  Point_3D( 25,20, 10),  // second point identical to first, should throw exception\n\t//\t\t\t\t\t Point_3D( 25,20, 10),\n\t//\t\t\t\t\t Point_3D( 25,22, 10));\n\n\t//Circle_3D   circle(  Point_3D( 25,20, 10),  // third point identical to first, should throw exception\n\t//\t\t\t\t\t Point_3D( 26,20, 10),\n\t//\t\t\t\t\t Point_3D( 25,20, 10));\n\n\t//Circle_3D   circle(  Point_3D( 25,20, 10),  // 3rd point colinear with line from 1st and 2nd points, should throw exception\n\t//\t\t\t\t\t Point_3D( 26,20, 10),\n\t//\t\t\t\t\t Point_3D( 27,20, 10));\n\t\n\t\t\n\tGetGridPointsWithinGeometry (\tgridPoints_map, \n\t\t\t\t\t\t\t\t\t\tcircle,\n\t\t\t\t\t\t\t\t\t \tGEOMETRY_INTERIOR_AND_BOUNDARY,\t\n\t\t\t\t\t\t\t\t\t\tprecision,\n\t\t\t\t\t\t\t\t\t\tgridPointIds_WithinCircle );\n\n\tCPPUNIT_ASSERT_EQUAL(4, (int)gridPointIds_WithinCircle.size());\n\tCPPUNIT_ASSERT_EQUAL(2, gridPointIds_WithinCircle[0]);\n\tCPPUNIT_ASSERT_EQUAL(3, gridPointIds_WithinCircle[1]);\n\tCPPUNIT_ASSERT_EQUAL(4, gridPointIds_WithinCircle[2]);\n\tCPPUNIT_ASSERT_EQUAL(5, gridPointIds_WithinCircle[3]);\n\t/*std::cout << std::endl << \"IDs Within Circle\";\n\tfor ( std::vector<int>::const_iterator i( gridPointIds_WithinCircle.begin()); i != gridPointIds_WithinCircle.end(); ++i)\n\t{\n\t\tstd::cout << std::endl << *i;\n\t}*/\n\t\t\n\n}\n\nvoid Tests::GetGridPointsWithinCircle_test()\n{\n\t::GetGridPointsWithinCircle_test(true);\n}\n/////////////////////////////////////////////////////////////////////////////////\nstatic void GetGridPointsBetweenOrOnConcentricCircles_test(bool in_IncludePointsOnBoundary)\n{\n\n\t////////////////////////////////////////////\n\t// GetGridPointsBetweenOrOnConcentricCircles\n\t////////////////////////////////////////////\t\n\n\tstd::map<int,GridPoint> gridPoints_map;\n\tdouble precision = .0001;\n\tstd::vector<int>       gridPointIds_BetweenOrOnConcentricCircles;\n\n\tgridPoints_map[1] = GridPoint(1, 2, Point_3D(0, 0, 10), 2); \n\tgridPoints_map[2] = GridPoint(2, 2, Point_3D(25, 21 - .0001, 10), 2); \n\tgridPoints_map[3] = GridPoint(3, 2, Point_3D(25.5, 20.5, 10.0001), 2);\n\tgridPoints_map[4] = GridPoint(4, 2, Point_3D(25.5, 20, 10), 2);\t\n\tgridPoints_map[5] = GridPoint(5, 2, Point_3D(25.00, 19, 10), 2);\t\n\n\tConcentricCircles_3D concentricCircles(\n\t\t\t\t\t\t\tPoint_3D( 25,20, 10),    // should get back 2 3 4 5\n\t\t\t\t\t\t\tPoint_3D( 26,20, 10),\n\t\t\t\t\t\t\tPoint_3D( 25,20.5, 10));\n\t\n\t\t\n\tGetGridPointsWithinGeometry (\tgridPoints_map, \n\t\t\t\t\t\t\t\t\t\tconcentricCircles,\n\t\t\t\t\t\t\t\t\t\tGEOMETRY_INTERIOR_AND_BOUNDARY,\n\t\t\t\t\t\t\t\t\t\tprecision,\n\t\t\t\t\t\t\t\t\t\tgridPointIds_BetweenOrOnConcentricCircles );\n\n\tCPPUNIT_ASSERT_EQUAL(4, (int)gridPointIds_BetweenOrOnConcentricCircles.size());\n\tCPPUNIT_ASSERT_EQUAL(2, gridPointIds_BetweenOrOnConcentricCircles[0]);\n\tCPPUNIT_ASSERT_EQUAL(3, gridPointIds_BetweenOrOnConcentricCircles[1]);\n\tCPPUNIT_ASSERT_EQUAL(4, gridPointIds_BetweenOrOnConcentricCircles[2]);\n\tCPPUNIT_ASSERT_EQUAL(5, gridPointIds_BetweenOrOnConcentricCircles[3]);\n/*\tstd::cout << std::endl << \"IDs Between/Within Circle\";\n\tfor ( std::vector<int>::const_iterator i( gridPointIds_BetweenOrOnConcentricCircles.begin()); i != gridPointIds_BetweenOrOnConcentricCircles.end(); ++i)\n\t{\n\t\tstd::cout << std::endl << *i;\n\t}*/\n\n}\n\nvoid Tests::GetGridPointsBetweenOrOnConcentricCircles_test()\n{\n\t::GetGridPointsBetweenOrOnConcentricCircles_test(true);\n}\n/////////////////////////////////////////////////////////////////////////////////\nvoid Tests::ShortestDistanceBetweenPointAndLine_test()\n{\n\n\t////////////////////////////////////////////\n\t// ShortestDistanceBetweenPointAndLine\n\t////////////////////////////////////////////\t\n\n\tstd::vector<Point_3D> line;\n\tdouble precision = .001;\n\t\n\tline.push_back( Point_3D(-5,5,0));\n\tline.push_back( Point_3D(-10,10,0));\n\n\tPoint_3D  point(-10.001,10,0);  // on second point\n\t//Point_3D  point(-10,5,0);\n\t//Point_3D  point(-6,6,0);  // on the line\n\n\tdouble distance = ShortestDistanceBetweenPointAndLine(line, point, precision );\n\t/*std::cout << std::endl << \"Line, start point, end point: \" << line[0] << \"  \" << line[1];\n\tstd::cout << std::endl << \"Point: \" << point;\n\tstd::cout << std::endl << \"Distance: \" << distance;*/\n\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(0, distance, 0.001);\n\t\t\n\n}\n/////////////////////////////////////////////////////////////////////////////////\nstatic void OnOrWithinCylinder_test(e_GeneralGeometryInclusionSpecifier\tin_GeneralGeometryInclusionSpecifier)\n{\n\n\t////////////////////////////////////////////\n\t// On or Within Cylinder\n\t////////////////////////////////////////////\t\t\n\n\tstd::map<int,GridPoint> gridPoints_map;\n\n\tdouble precision = .001;\n\tstd::vector<int>       gridPointIds_OnCylinderSurface;\n\n\tgridPoints_map[1] = GridPoint(1, 2, Point_3D(0, 0, 10), 2); \n\tgridPoints_map[2] = GridPoint(2, 2, Point_3D(358.9941, 104.2714, 165.0611),  2); \n\tgridPoints_map[3] = GridPoint(3, 2, Point_3D(307.16, 75 + 30, 267.98), 2);\n\tgridPoints_map[4] = GridPoint(4, 2, Point_3D(338.0405, 95.0519, 169.8683), 2);\t\n\tgridPoints_map[5] = GridPoint(5, 2, Point_3D(350, 80, 170), 2);\t// interior of cylinder\n\n\tCylinder_3D  cyclinder(\n\t\t\t\t\t\t\tPoint_3D( 307.16, 75, 267.98),    // should get back 2 3 4 5\n\t\t\t\t\t\t\tPoint_3D( 385.66, 75, 132.02),\n\t\t\t\t\t\t\tPoint_3D( 358.9941, 104.2714, 165.0611),\n\t\t\t\t\t\t\tGEOMETRY_INCLUDE_END_CAP);\n\n\t//cylinder.push_back( Point_3D( 307.16, 75, 267.98));  // 1st point, first point at center of cylinder\n\t//cylinder.push_back( Point_3D( 385.66, 75, 132.02));\t// 2nd point, second point at center of cylinder\n\t////cylinder.push_back( Point_3D( 25,20, 10));  // 2nd pointCheck identical points\n\t//cylinder.push_back( Point_3D( 358.9941, 104.2714, 165.0611));  // 3rd point, on cylinder surface\n \t////cylinder.push_back( Point_3D( 25,20, 10));  // 3rd Check identical points\n\t////cylinder.push_back( Point_3D( 27,20, 10));   // 3rd Check colinear with line from 1st and 2nd points\n\t\t\n\tGetGridPointsWithinGeometry (\tgridPoints_map, \n\t\t\t\t\t\t\t\t\tcyclinder,\n\t\t\t\t\t\t\t\t\tin_GeneralGeometryInclusionSpecifier,\n\t\t\t\t\t\t\t\t\tprecision,\n\t\t\t\t\t\t\t\t\tgridPointIds_OnCylinderSurface );\n\n\tCPPUNIT_ASSERT_EQUAL(3, (int)gridPointIds_OnCylinderSurface.size());\n\tCPPUNIT_ASSERT_EQUAL(2, gridPointIds_OnCylinderSurface[0]);\n\tCPPUNIT_ASSERT_EQUAL(3, gridPointIds_OnCylinderSurface[1]);\n\tCPPUNIT_ASSERT_EQUAL(4, gridPointIds_OnCylinderSurface[2]);\n\t/*std::cout << std::endl << \"IDs on/within cylinder\";\n\tfor ( std::vector<int>::const_iterator i( gridPointIds_OnCylinderSurface.begin()); i != gridPointIds_OnCylinderSurface.end(); ++i)\n\t{\n\t\tstd::cout << std::endl << *i;\n\t}*/\t\t\t\n}\n\nvoid Tests::OnOrWithinCylinder_test()\n{\n\t::OnOrWithinCylinder_test(isis_CADCommon::GEOMETRY_BOUNDARY_ONLY);\n}\n/////////////////////////////////////////////////////////////////////////////////\nstatic void OnCylinderSurface_test(e_GeneralGeometryInclusionSpecifier\tin_GeneralGeometryInclusionSpecifier)\n{\n\n\t////////////////////////////////////////////\n\t// On Cylinder Surface\n\t////////////////////////////////////////////\t\n\n\tstd::map<int,GridPoint> gridPoints_map;\n\n\tdouble precision = .001;\n\tstd::vector<int>       gridPointIds_OnCylinderSurface;\n\n\tgridPoints_map[1] = GridPoint(1, 2, Point_3D(0, 0, 10), 2); \n\tgridPoints_map[2] = GridPoint(2, 2, Point_3D(358.9941, 104.2714, 165.0611),  2); \n\tgridPoints_map[3] = GridPoint(3, 2, Point_3D(307.16, 75 + 30, 267.98), 2);\n\tgridPoints_map[4] = GridPoint(4, 2, Point_3D(338.0405, 95.0519, 169.8683), 2);\t\n\n\tCylinder_3D  cyclinderSurface(\n\t\t\t\t\t\t\tPoint_3D( 307.16, 75, 267.98),\t\t// should get back 2 3 4 for GEOMETRY_INCLUDE_END_CAP\n\t\t\t\t\t\t\tPoint_3D( 385.66, 75, 132.02),\t\t// should get back 2 4 for GEOMETRY_EXCLUDE_END_CAP\n\t\t\t\t\t\t\tPoint_3D( 358.9941, 104.2714, 165.0611),\n\t\t\t\t\t\t\tGEOMETRY_INCLUDE_END_CAP);\n\n\t//cylinder.push_back( Point_3D( 307.16, 75, 267.98));  // 1st point, first point at center of cylinder\n\t//cylinder.push_back( Point_3D( 385.66, 75, 132.02));\t// 2nd point, second point at center of cylinder\n\t////cylinder.push_back( Point_3D( 25,20, 10));  // 2nd pointCheck identical points\n\t//cylinder.push_back( Point_3D( 358.9941, 104.2714, 165.0611));  // 3rd point, on cylinder surface\n \t////cylinder.push_back( Point_3D( 25,20, 10));  // 3rd Check identical points\n\t////cylinder.push_back( Point_3D( 27,20, 10));   // 3rd Check colinear with line from 1st and 2nd points\n\t\t\n\tGetGridPointsWithinGeometry (\tgridPoints_map, \n\t\t\t\t\t\t\t\t\t\tcyclinderSurface,\n\t\t\t\t\t\t\t\t\t\tGEOMETRY_BOUNDARY_ONLY,\n\t\t\t\t\t\t\t\t\t\tprecision,\n\t\t\t\t\t\t\t\t\t\tgridPointIds_OnCylinderSurface );\n\n\tCPPUNIT_ASSERT_EQUAL(3, (int)gridPointIds_OnCylinderSurface.size());\n\tCPPUNIT_ASSERT_EQUAL(2, gridPointIds_OnCylinderSurface[0]);\n\tCPPUNIT_ASSERT_EQUAL(3, gridPointIds_OnCylinderSurface[1]);\n\tCPPUNIT_ASSERT_EQUAL(4, gridPointIds_OnCylinderSurface[2]);\n/*\tstd::cout << std::endl << \"IDs On cylinder\";\n\tfor ( std::vector<int>::const_iterator i( gridPointIds_OnCylinderSurface.begin()); i != gridPointIds_OnCylinderSurface.end(); ++i)\n\t{\n\t\tstd::cout << std::endl << *i;\n\t}\t*/\n}\n\nvoid Tests::OnCylinderSurface_test()\n{\n\t::OnCylinderSurface_test(GEOMETRY_BOUNDARY_ONLY);\n}\n/////////////////////////////////////////////////////////////////////////////////\nstatic void WithinSphere_test(bool in_IncludePointsOnBoundary)\n{\n\n\t////////////////////////////////////////////\n\t// Within Sphere \n\t////////////////////////////////////////////\t\n\n\tstd::map<int,GridPoint> gridPoints_map;\n\n\tdouble precision = .001;\n\tstd::vector<int>       gridPointIds_WithinSphere;\n\n\tgridPoints_map[1] = GridPoint(1, 2, Point_3D(5, 6, 1), 2); \n\tgridPoints_map[2] = GridPoint(2, 2, Point_3D(5.1, 6.1, .1 ),  2); \n\tgridPoints_map[3] = GridPoint(3, 2, Point_3D(6, 6, 0 ), 2);\n\tgridPoints_map[4] = GridPoint(4, 2, Point_3D(5, 7.00099999, 0), 2);\t\n\n\tSphere_3D  sphere(\n\t\t\t\t\t\t\tPoint_3D(  5, 6, 0 ),    // should get back ???\n\t\t\t\t\t\t\tPoint_3D(  5, 7, 0 ));\n\t\n\t//sphere.pointWithinGeometry( Point_3D(5, 7.001, 0),true, precision );\n\t\t\n\tGetGridPointsWithinGeometry (\tgridPoints_map, \n\t\t\t\t\t\t\t\t\t\tsphere,\n\t\t\t\t\t\t\t\t\t\tGEOMETRY_INTERIOR_AND_BOUNDARY,\n\t\t\t\t\t\t\t\t\t\tprecision,\n\t\t\t\t\t\t\t\t\t\tgridPointIds_WithinSphere );\n\n\tCPPUNIT_ASSERT_EQUAL(4, (int)gridPointIds_WithinSphere.size());\n\tCPPUNIT_ASSERT_EQUAL(1, gridPointIds_WithinSphere[0]);\n\tCPPUNIT_ASSERT_EQUAL(2, gridPointIds_WithinSphere[1]);\n\tCPPUNIT_ASSERT_EQUAL(3, gridPointIds_WithinSphere[2]);\n\tCPPUNIT_ASSERT_EQUAL(4, gridPointIds_WithinSphere[3]);\n/*\tstd::cout << std::endl << \"IDs within Sphere\";\n\tfor ( std::vector<int>::const_iterator i( gridPointIds_WithinSphere.begin()); i != gridPointIds_WithinSphere.end(); ++i)\n\t{\n\t\tstd::cout << std::endl << *i;\n\t}\t*/\n\n\n}\n\nvoid Tests::WithinSphere_test()\n{\n\t::WithinSphere_test(isis_CADCommon::GEOMETRY_BOUNDARY_ONLY);\n}\n/////////////////////////////////////////////////////////////////////////////////\n\nvoid Tests::OnSphereSurface_test()\n{\n\n\t////////////////////////////////////////////\n\t// On Sphere Surface \n\t////////////////////////////////////////////\t\n\n\tstd::map<int,GridPoint> gridPoints_map;\n\n\tdouble precision = .001;\n\tstd::vector<int>       gridPointIds_WithinsphereSurface;\n\n\tgridPoints_map[1] = GridPoint(1, 2, Point_3D(5, 6.001, 1.00), 2); \n\tgridPoints_map[2] = GridPoint(2, 2, Point_3D(5.1, 6.1, .1 ),  2); \n\tgridPoints_map[3] = GridPoint(3, 2, Point_3D(6, 6, 0 ), 2);\n\tgridPoints_map[4] = GridPoint(4, 2, Point_3D(338.0405, 95.0519, 169.8683), 2);\t\n\n\tSphereSurface_3D  sphereSurface(\n\t\t\t\t\t\t\tPoint_3D( 5, 6, 0 ),    // should get back ???\n\t\t\t\t\t\t\tPoint_3D(  5, 7, 0 ));\n\t\n\tsphereSurface.pointWithinGeometry(Point_3D(5, 6.01, 1.00), true, precision);\n\n\t\t\n\tGetGridPointsWithinGeometry (\tgridPoints_map, \n\t\t\t\t\t\t\t\t\t\tsphereSurface,\n\t\t\t\t\t\t\t\t\t\tGEOMETRY_INTERIOR_AND_BOUNDARY,\n\t\t\t\t\t\t\t\t\t\tprecision,\n\t\t\t\t\t\t\t\t\t\tgridPointIds_WithinsphereSurface );\n\n\tCPPUNIT_ASSERT_EQUAL(2, (int)gridPointIds_WithinsphereSurface.size());\n\tCPPUNIT_ASSERT_EQUAL(1, gridPointIds_WithinsphereSurface[0]);\n\tCPPUNIT_ASSERT_EQUAL(3, gridPointIds_WithinsphereSurface[1]);\n\t/*std::cout << std::endl << \"IDs within sphereSurface\";\n\tfor ( std::vector<int>::const_iterator i( gridPointIds_WithinsphereSurface.begin()); i != gridPointIds_WithinsphereSurface.end(); ++i)\n\t{\n\t\tstd::cout << std::endl << *i;\n\t}*/\t\n\t\n\n}\n/////////////////////////////////////////////////////////////////////////////////\n\nstatic void WithinExtrusion_test(bool in_IncludePointsOnBoundary)\n{\n\t////////////////////////////////////////////\n\t// Within Extrusion  \n\t////////////////////////////////////////////\t\n\n\tstd::map<int,GridPoint> gridPoints_map;\n\n\tdouble precision = .001;\n\tstd::vector<int>       gridPointIds_WithinExtrusion;\n\n\tgridPoints_map[1] = GridPoint(1, 2, Point_3D(5, 0, 0 ), 2); \n\tgridPoints_map[2] = GridPoint(2, 2, Point_3D(1, -1, 1), 2); \n\tgridPoints_map[3] = GridPoint(3, 2, Point_3D(3, 3, 4.99), 2);\n\tgridPoints_map[4] = GridPoint(4, 2, Point_3D(5, 5, 20), 2);\t\n\n\tstd::vector<Point_3D>   polygon;\n\n\tpolygon.push_back( Point_3D( 5, 0, 0));  \n\tpolygon.push_back( Point_3D( 5, 5, 0));\n\tpolygon.push_back( Point_3D( 0, 5, 0));\n\tpolygon.push_back( Point_3D( 0, 0, 0));\n\n\tPoint_3D  offsetPoint (0, 0, 5 );\n\n\tExtrusion_3D  extrusion( polygon,     // should get back ???\n\t\t\t\t\t\t\t\toffsetPoint,    \n\t\t\t\t\t\t\t\tprecision);\n\t\n\t//extrusion.pointWithinGeometry(Point_3D(4, 3, 1.00), true, precision);\n\n\t\t\n\tGetGridPointsWithinGeometry (\tgridPoints_map, \n\t\t\t\t\t\t\t\t\t\textrusion,\n\t\t\t\t\t\t\t\t\t\tGEOMETRY_INTERIOR_AND_BOUNDARY,\n\t\t\t\t\t\t\t\t\t\tprecision,\n\t\t\t\t\t\t\t\t\t\tgridPointIds_WithinExtrusion );\n\n\tCPPUNIT_ASSERT_EQUAL(2, (int)gridPointIds_WithinExtrusion.size());\n\tCPPUNIT_ASSERT_EQUAL(1, gridPointIds_WithinExtrusion[0]);\n\tCPPUNIT_ASSERT_EQUAL(3, gridPointIds_WithinExtrusion[1]);\n\n\t/*std::cout << std::endl << \"IDs within extrusionSurface\";\n\tfor ( std::vector<int>::const_iterator i( gridPointIds_WithinExtrusion.begin()); i != gridPointIds_WithinExtrusion.end(); ++i)\n\t{\n\t\tstd::cout << std::endl << *i;\n\t}*/\t\n}\n\nvoid Tests::WithinExtrusion_test()\n{\n\t::WithinExtrusion_test(true);\n}\n#if 0\n/////////////////////////////////////////////////////////////////////////////////\n//\tvoid ComputeStressValues( double  in_StressTensor[3][3], \n//\t\t\t\t\t\t\t  double &out_VonMises,\t\t// always postive\n//\t\t\t\t\t\t\t  double &out_MaxShear,\t\t// either 0 ( no shear stress ) or positive \n//\t\t\t\t\t\t\t  double &out_MaxBearing\t// either 0 ( no bearing stress ) or positive\n//\t\t\t\t\t\t\t ) throw (isis::application_exception);\nvoid ComputeStressValues_test()\n{\n\t//\t\tS00\tS01\tS02\n\t//\t\tS10\tS11\tS12\n\t//\t\tS20\tS21\tS22\n\n\tdouble stressTensor[3][3];\n\n\t// From Abaqus\n\tstressTensor[0][0] = -0.2267;\n\tstressTensor[1][1] = .0133441;\n\tstressTensor[2][2] = .0311546;\n\n\tstressTensor[0][1] = -.0137862;\n\tstressTensor[0][2] = -.107133;\n\tstressTensor[1][2] = -.0170857;\n\t\n\t// Result From Abaqus\n\t// Principal  .0721027   .0123583  -.266663\n\t// Von Mises  .313196\n\t// Tresca = .338765\n\t// Pressure = .0607339\n\n\t// From Abaqus\n\tstressTensor[0][0] = 100;\n\tstressTensor[1][1] = 100;\n\tstressTensor[2][2] = 100;\n\n\tstressTensor[0][1] = 0;\n\tstressTensor[0][2] = 0;\n\tstressTensor[1][2] = 0;\n\n\t//stressTensor[0][0] = 100;\n\t//stressTensor[1][1] = 200;\n\t//stressTensor[2][2] = 0;\n\n\t//stressTensor[0][1] = 88;\n\t//stressTensor[0][2] = 0;\n\t//stressTensor[1][2] = 0;\n\n\n\tdouble VonMises;\n\tdouble MaxShear;\n\tdouble MaxBearing;\n\n\tisis_CADCommon::ComputeStressValues( stressTensor, VonMises, MaxShear, MaxBearing );\n\n\n\tstd::cout << std::endl << \"Stress Tensor\";\n\tstd::cout << std::endl << stressTensor[0][0] << \"  \" << stressTensor[0][1] << \"  \" << stressTensor[0][2];\n\tstd::cout << std::endl << stressTensor[1][0] << \"  \" << stressTensor[1][1] << \"  \" << stressTensor[1][2];\n\tstd::cout << std::endl << stressTensor[2][0] << \"  \" << stressTensor[2][1] << \"  \" << stressTensor[2][2];\n\tstd::cout << std::endl;\n\tstd::cout << std::endl << \"VonMises:   \" << VonMises;\n\tstd::cout << std::endl << \"MaxShear:   \" << MaxShear;\n\tstd::cout << std::endl << \"MaxBearing: \" << MaxBearing;\n\n\tstd::cout << std::endl << \"******************************************\";\n\tstd::cout << std::endl << \"************** CalculiX ******************\";\n\tstd::cout << std::endl << \"******************************************\";\n\n\n\tdouble stressTensor_CalculiX[6];\n\tstressTensor_CalculiX[0] = stressTensor[0][0];\n\tstressTensor_CalculiX[1] = stressTensor[1][1];\n\tstressTensor_CalculiX[2] = stressTensor[2][2];\n\tstressTensor_CalculiX[3] = stressTensor[0][1];\n\tstressTensor_CalculiX[5] = stressTensor[0][2];\n\tstressTensor_CalculiX[4] = stressTensor[1][2];\n\n\tdouble stressPrincipal_CalculiX[12];\n\tdouble alpha_0[3];\n\tdouble alpha_1[3];\n\tdouble alpha_2[3];\n#define  TEST1\n\t//calcPrinc( double *s, double *p, double *a0, double *a1, double *a2, int flag )\n\tisis_CADCommon::calcPrinc(  stressTensor_CalculiX,  stressPrincipal_CalculiX, alpha_0, alpha_1, alpha_2, 0 );\n\tstd::cout << std::endl << \"CalculiX Principal 0: \" << stressPrincipal_CalculiX[0];\n\tstd::cout << std::endl << \"CalculiX Principal 1: \" << stressPrincipal_CalculiX[1];\n\tstd::cout << std::endl << \"CalculiX Principal 2: \" << stressPrincipal_CalculiX[2];\n/*\n\tdouble stressTensor[3][3];\n\n\tstressTensor[0][0] = -2;\n\tstressTensor[1][1] = 10;\n\tstressTensor[2][2] = -5;\n\n\tstressTensor[0][1] = 7;\n\tstressTensor[0][2] = -3;\n\tstressTensor[1][2] = 5;\n\n\tdouble VonMises;\n\tdouble MaxShear;\n\tdouble MaxBearing;\n\n\tisis_CADCommon::ComputeStressValues( stressTensor, VonMises, MaxShear, MaxBearing );\n\n\n\tstd::cout << std::endl << \"Stress Tensor\";\n\tstd::cout << std::endl << stressTensor[0][0] << \"  \" << stressTensor[0][1] << \"  \" << stressTensor[0][2];\n\tstd::cout << std::endl << stressTensor[1][0] << \"  \" << stressTensor[1][1] << \"  \" << stressTensor[1][2];\n\tstd::cout << std::endl << stressTensor[2][0] << \"  \" << stressTensor[2][1] << \"  \" << stressTensor[2][2];\n\tstd::cout << std::endl;\n\tstd::cout << std::endl << \"VonMises:   \" << VonMises;\n\tstd::cout << std::endl << \"MaxShear:   \" << MaxShear;\n\tstd::cout << std::endl << \"MaxBearing: \" << MaxBearing;\n*/\n}\n#endif\n\ntemplate<typename T> std::vector<T> make_vec(T *values, int N) {\n    std::vector<T> v;\n\tfor (int i = 0; i < N; i++)\n\t\tv.push_back(values[i]);\n\treturn v;\n}\n\nvoid Tests::NastranDeck_test()\n{\n\ttry\n\t\t{\n\t\t\tNastranDeck deck;\n\t\t\tstd::cout << std::endl << \"Reading Deck: \" << \"..\\\\..\\\\Edited_Thermal_Mesh.nas\";\n\t\t\tdeck.ReadNastranDeck(\"src\\\\CADAssembler\\\\CADCommonTest\\\\Edited_Thermal_Mesh.nas\");\n\t\t\t//deck.ReadNastranDeck(\"..\\\\Edited_Thermal_Mesh.nas\");\n\n\n\t\t\t//std::cout << std::endl << \"Display Deck: \";\n\t\t\t//std::cout << deck;\n\n\n\t\t\tNastranDeckHelper nastranDeckHelper(deck);\n\n\t\t\tbool\tDefaultGridPointTemperature_set;\n\t\t\tdouble  DefaultGridPointTemperature;\n\n\t\t\t//std::cout << std::endl;\n\t\t\t//std::cout << std::endl << \"*****************  nastranDeckHelper ***********************\";\n\n\t\t\t///////////////////////////////\n\t\t\t// DefaultGridPointTemperature\n\t\t\t///////////////////////////////\n\t\t\tnastranDeckHelper.getDefaultGridPointTemperature( DefaultGridPointTemperature_set, DefaultGridPointTemperature );\n\n\t\t\t//std::cout << std::endl;\n\t\t\t//std::cout << std::endl << \"*****************  DefaultGridPointTemperature ***********************\";\n\n\t\t\tCPPUNIT_ASSERT(DefaultGridPointTemperature_set);\n\t\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(293, DefaultGridPointTemperature, 0.0001);\n\n\t\t\t///////////////////////////////\n\t\t\t// GridPointTemperatures\n\t\t\t///////////////////////////////\n\t\t\t std::map<int,double> gridPointToTemperature_map;\n\n\t\t\t//std::cout << std::endl;\n\t\t\t//std::cout << std::endl << \"*****************  GridPointTemperatures ***********************\";\n\n\t\t\tnastranDeckHelper.getSpecifiedGridPointTemperatures( gridPointToTemperature_map );\n\n\n\t\t\tCPPUNIT_ASSERT_EQUAL(9, (int)gridPointToTemperature_map.size());\n\t\t\tfor each ( const std::pair<int,double> &i in gridPointToTemperature_map)\n\t\t\t{\n\t\t\t\t//std::cout << std::endl << \"Grid Point: \" << i.first << \"  Temperature: \" << i.second;\n\t\t\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(401.123, i.second, 0.0001);\n\t\t\t}\n\n\t\t\t//std::cout << std::endl;\n\t\t\t//std::cout << std::endl << \"*****************  findElementsContainingSurface ***********************\";\n\n\t\t\tstd::vector<int> surfaceCornerGridIDs;\n\n\t\t\tsurfaceCornerGridIDs.push_back(20);\n\t\t\tsurfaceCornerGridIDs.push_back(14);\n\t\t\tsurfaceCornerGridIDs.push_back(32);\n\n\t\t\tbool elementFound;\n\t\t\tstd::set<int> elementIDs;\n\n\t\t\tnastranDeckHelper.findElementsContainingSurface( surfaceCornerGridIDs,elementFound, elementIDs );\n\n\t\t\t//std::cout <<std::endl << \"Element Key: \"; \n\t\t\t//for each ( const int &j in surfaceCornerGridIDs) std::cout << \" \" << j;\n\n\n\n\t\t\tCPPUNIT_ASSERT(elementFound);\n\n\t\t\t// In the deck Edited_Thermal_Mesh.nas, there are two tetra with the element combination\n\t\t\t// CTETRA,20,1,20,14,32,13,93,94,\n\t\t\t//\t,117,87,84,92\n\t\t\t// CTETRA,10,1,14,20,32,5,93,117,       // We want this one\n\t\t\t//\t,94,50,51,52\n\n\t\t\tint elementID = 0;\n\t\t\tfor each ( const int &i_target in elementIDs )\n\t\t\t{\n\t\t\t\tif ( i_target == 10 ) elementID = 10;\n\t\t\t}\n\t\n\t\t\tCPPUNIT_ASSERT_EQUAL(10, elementID);\n\t\t\tCPPUNIT_ASSERT_EQUAL(10, deck.getElementData().find(elementID)->second.EID);\n\t\t\tCPPUNIT_ASSERT_EQUAL(CTETRA, deck.getElementData().find(elementID)->second.Type);\n\n\t\t\t//std::cout << std::endl;\n\t\t\t//std::cout << std::endl << \"*****************  getHeatFluxLoadsForBoundarySurfaces ***********************\";\n\n\t\t\tstd::vector<HeatFluxLoad> heatFluxLoads;\n\t\t\tnastranDeckHelper.getHeatFluxLoadsForBoundarySurfaces( heatFluxLoads ) ;\n\t\t\tCPPUNIT_ASSERT_EQUAL(2, (int)heatFluxLoads.size());\n\t\t\t//const std::map<int, FEAElement> &elementData_map = deck.getElementData();\n\n\t\t\tCPPUNIT_ASSERT_EQUAL(std::string(\"QBDY3\"), heatFluxLoads[0].name);\n\t\t\tCPPUNIT_ASSERT_EQUAL(39, heatFluxLoads[0].elementIDThatContainsSurface);\n\t\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(310, heatFluxLoads[0].Q0, 0.0001);\n\t\t\tCPPUNIT_ASSERT_EQUAL(59, heatFluxLoads[0].SID);\n\t\t\tint vals[] = {12,30,29,83,141,82};\n\t\t\tCPPUNIT_ASSERT_EQUAL(make_vec<int>(vals, 6), heatFluxLoads[0].surfaceGridPointIDs);\n\n\t\t\tCPPUNIT_ASSERT_EQUAL(std::string(\"QBDY3\"), heatFluxLoads[1].name);\n\t\t\tCPPUNIT_ASSERT_EQUAL(49, heatFluxLoads[1].elementIDThatContainsSurface);\n\t\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(310, heatFluxLoads[1].Q0, 0.0001);\n\t\t\tCPPUNIT_ASSERT_EQUAL(59, heatFluxLoads[1].SID);\n\t\t\tint vals2[] = {29,12,11,82,73,77};\n\t\t\tCPPUNIT_ASSERT_EQUAL(make_vec<int>(vals2, 6), heatFluxLoads[1].surfaceGridPointIDs);\n\n\t\t\t//std::cout << std::endl;\n\t\t\t//std::cout << std::endl << \"*****************  getSurfaceConvectionConstraints ***********************\";\n\t\t\t\n\t\t\tstd::vector<SurfaceConvection> surfaceConvections;\n\t\t\tnastranDeckHelper.getSurfaceConvectionConstraints ( surfaceConvections);\n\t\t\tCPPUNIT_ASSERT_EQUAL(2, (int)surfaceConvections.size());\n\t\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(222.34, surfaceConvections[0].convectionCoefficient, 0.01);\n\t\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(243.99, surfaceConvections[0].ambientTemperature, 0.01);\n\t\t\tCPPUNIT_ASSERT_EQUAL(24, surfaceConvections[0].elementIDThatContainsSurface);\n\t\t\tCPPUNIT_ASSERT_EQUAL(100005, surfaceConvections[0].convID);\n\t\t\tCPPUNIT_ASSERT_EQUAL(100004, surfaceConvections[0].pconvID);\n\t\t\tCPPUNIT_ASSERT_EQUAL(100003, surfaceConvections[0].mat4ID);\n\t\t\tCPPUNIT_ASSERT_EQUAL(145, surfaceConvections[0].spointID);\n\t\t\tint vals3[] = {3,1,4,35,36,44};\n\t\t\tCPPUNIT_ASSERT_EQUAL(make_vec<int>(vals3, 6), surfaceConvections[0].surfaceGridPointIDs);\n\n\t\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(222.34, surfaceConvections[1].convectionCoefficient, 0.01);\n\t\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(243.99, surfaceConvections[1].ambientTemperature, 0.01);\n\t\t\tCPPUNIT_ASSERT_EQUAL(43, surfaceConvections[1].elementIDThatContainsSurface);\n\t\t\tCPPUNIT_ASSERT_EQUAL(100006, surfaceConvections[1].convID);\n\t\t\tCPPUNIT_ASSERT_EQUAL(100004, surfaceConvections[1].pconvID);\n\t\t\tCPPUNIT_ASSERT_EQUAL(100003, surfaceConvections[1].mat4ID);\n\t\t\tCPPUNIT_ASSERT_EQUAL(145, surfaceConvections[1].spointID);\n\t\t\tint vals4[] = {2,1,3,34,35,41};\n\t\t\tCPPUNIT_ASSERT_EQUAL(make_vec<int>(vals4, 6), surfaceConvections[1].surfaceGridPointIDs);\n\n\t\t\t//std::cout << std::endl;\n\t\t\t//std::cout << std::endl << \"*****************  getSurfaceElementsContainingGridPoints ***********************\";\n\n\t\t\tstd::set<int>  targetGridPoints;\n\t\t\t// Element 1\n\t\t\t// CTETRA,1,1,17,22,33,23,102,124,\n\t\t\t// ,105,103,121,128\n\t\t\ttargetGridPoints.insert(17);\n\t\t\ttargetGridPoints.insert(22);\n\t\t\ttargetGridPoints.insert(33);\n\t\t\t//targetGridPoints.insert(23);\n\n\t\t\t// Element 9 \n\t\t\t// CTETRA,9,1,9,15,21,10,63,96,\n\t\t\t// ,64,62,67,69\n\n\t\t\ttargetGridPoints.insert(9);\n\t\t\ttargetGridPoints.insert(15);\n\t\t\ttargetGridPoints.insert(21);\n\n\t\t\tstd::multimap< int, std::vector<int>> foundElements_map;\n\n\t\t\tnastranDeckHelper.getSurfaceElementsContainingGridPoints (\ttargetGridPoints, foundElements_map);\n\t\t\n\t\t\tCPPUNIT_ASSERT_EQUAL(3, (int)foundElements_map.size());\n\t\t\n\t\t\tfor each ( const std::pair< int, std::vector<int>> &i in foundElements_map )\n\t\t\t{\n\t\t\t\t//std::cout << std::endl <<  \"Element ID: \" << i.first  << \" Grid Points:\" ;\n\t\t\t\t//for each ( const int &j in i.second ) std::cout << \" \" << j;\n\t\t\t\tif (i.first == 1)\n\t\t\t\t{\n\t\t\t\t\tint vals4[] = {17, 22, 33, 102, 124, 105};\n\t\t\t\t\tCPPUNIT_ASSERT_EQUAL(make_vec<int>(vals4, 6), i.second);\n\t\t\t\t} else if (i.first == 7)\n\t\t\t\t{\n\t\t\t\t\tint vals4[] = {21, 22, 33, 118, 124, 120};\n\t\t\t\t\tCPPUNIT_ASSERT_EQUAL(make_vec<int>(vals4, 6), i.second);\n\t\t\t\t} else if (i.first == 9)\n\t\t\t\t{\n\t\t\t\t\tint vals4[] = {9, 15, 21, 63, 96, 64};\n\t\t\t\t\tCPPUNIT_ASSERT_EQUAL(make_vec<int>(vals4, 6), i.second);\n\t\t\t\t} else {\n\t\t\t\t\tCPPUNIT_ASSERT(false);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t//std::cout << std::endl;\n\t\t\t//std::cout << std::endl << \"*****************  getVolumetricHeatGenerations ***********************\";\n\n\t\t\tstd::vector<VolumetricHeatGeneration> volumetricHeatGenerations;\n\n\t\t\tnastranDeckHelper.getVolumetricHeatGenerations( volumetricHeatGenerations );\n\n\t\t\tCPPUNIT_ASSERT_EQUAL(1, (int)volumetricHeatGenerations.size());\n\t\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(.003114, volumetricHeatGenerations[0].powerInputPerVolume, 0.0001);\n\t\t\tint i=1;\n\t\t\tfor each ( const int j in volumetricHeatGenerations[0].elementIDs )\n\t\t\t{\n\t\t\t\tCPPUNIT_ASSERT_EQUAL(j, i);\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t}\n\n\t\t//catch ( isis::application_exception &ex )\n\t\tcatch ( isis::application_exception &)\n\t\t{\n\t\t\tCPPUNIT_ASSERT(false);\n\n\t\t}\n\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n\nvoid Tests::ComputeTransformationToAlignVectors_test()\n{\n\t// Warning, This function needs work\n\t// See GraphicsFunctions ComputeRotationMatrixToAlignVectorsy.cpp\n\n\tstd::vector<double>\tin_Vector_1;\n\tstd::vector<double>\tin_Vector_2;\n\n\tin_Vector_1.push_back(1);\n\tin_Vector_1.push_back(1);\n\tin_Vector_1.push_back(3);\n\n\tin_Vector_2.push_back(-1);\n\tin_Vector_2.push_back(10);\n\tin_Vector_2.push_back(5);\n\n\tdouble\trotationMatrix[3][3] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};\n\n\t//isis_CADCommon::ComputeRotationMatrixToAlignVectors( in_Vector_1, in_Vector_2,rotationMatrix);\n\n\tTransformationMatrix transformationMatrix;\n\n\tstd::vector<double>\toffset(3, 0.0);\n\n\ttransformationMatrix.setTransformationMatrix(rotationMatrix, offset);\n\n\tisis_CADCommon::Point_3D  point_start(1,1,3);\n\t\n\tisis_CADCommon::Point_3D  point_transformed = transformationMatrix.getTransformedCoordinates( point_start);\n\n\t/*std::cout << std::endl << \"Vector 1\";\n\tfor each ( double i in in_Vector_1 ) std::cout << std::endl << i;\n\n\tstd::cout << std::endl << \"Vector 2\";\n\tfor each ( double i in in_Vector_2 ) std::cout << std::endl << i;\n\n\tstd::cout << std::endl;\n\tstd::cout << std::endl << \"Point Start:       \" << point_start;\n\tstd::cout << std::endl << \"Point Transformed: \" << point_transformed;*/\n\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(0, point_transformed.x, 0.0001);\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(0, point_transformed.y, 0.0001);\n\tCPPUNIT_ASSERT_DOUBLES_EQUAL(0, point_transformed.z, 0.0001);\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n\tvoid Tests::Determinant_4_x_4_test ( )\n\t{\n\t\t// Example from http://nebula.deanza.edu/~bloom/math43/Determinant4x4Matrix.pdf\n\t\tdouble matrix[4][4];\n\n\t\tmatrix[0][0] = 3.0;\n\t\tmatrix[0][1] = 0.0;\n\t\tmatrix[0][2] = 2.0;\n\t\tmatrix[0][3] = -1.0;\n\n\t\tmatrix[1][0] = 1.0;\n\t\tmatrix[1][1] = 2.0;\n\t\tmatrix[1][2] = 0.0;\n\t\tmatrix[1][3] = -2.0;\n\n\t\tmatrix[2][0] = 4.0;\n\t\tmatrix[2][1] = 0.0;\n\t\tmatrix[2][2] = 6.0;\n\t\tmatrix[2][3] = -3.0;\n\n\t\tmatrix[3][0] = 5.0;\n\t\tmatrix[3][1] = 0.0;\n\t\tmatrix[3][2] = 2.0;\n\t\tmatrix[3][3] = 0.0;\n\n\t\tdouble determinant = Determinant_4_x_4(matrix);\n\n\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(20, determinant, 0.001);\n\t\t//std::cout << std::endl << \"Determinant, Answer should be 20.\";\n\t\t//std::cout << std::endl << \"Determinant Answer: \" << determinant;\n\n\t\tmatrix[0][0] = 1.0;\n\t\tmatrix[0][1] = 2.0;\n\t\tmatrix[0][2] = 3.0;\n\t\tmatrix[0][3] = 4.0;\n\n\t\tmatrix[1][0] = -1.0;\n\t\tmatrix[1][1] = -2.0;\n\t\tmatrix[1][2] = -3.0;\n\t\tmatrix[1][3] = -4.0;\n\n\t\tmatrix[2][0] = 5.0;\n\t\tmatrix[2][1] = 6.0;\n\t\tmatrix[2][2] = 7.0;\n\t\tmatrix[2][3] = 8.0;\n\n\t\tmatrix[3][0] = -8.0;\n\t\tmatrix[3][1] = -7.0;\n\t\tmatrix[3][2] = -6.0;\n\t\tmatrix[3][3] = -5.0;\n\n\t\tdeterminant = Determinant_4_x_4(matrix);\n\n\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(0, determinant, 0.001);\n\t\t//std::cout << std::endl << \"Determinant, Answer should be 0.\";\n\t\t//std::cout << std::endl << \"Determinant Answer: \" << determinant;\n\n\t\tmatrix[0][0] = 5.0;\n\t\tmatrix[0][1] = 23.0;\n\t\tmatrix[0][2] = 14.0;\n\t\tmatrix[0][3] = 17.0;\n\n\t\tmatrix[1][0] = 4.0;\n\t\tmatrix[1][1] = 5.0;\n\t\tmatrix[1][2] = 6.0;\n\t\tmatrix[1][3] = 7.0;\n\n\t\tmatrix[2][0] = 8.0;\n\t\tmatrix[2][1] = 9.0;\n\t\tmatrix[2][2] = 10.0;\n\t\tmatrix[2][3] = 11.0;\n\n\t\tmatrix[3][0] = 24.0;\n\t\tmatrix[3][1] = 18.0;\n\t\tmatrix[3][2] = -2.0;\n\t\tmatrix[3][3] = 4.0;\n\n\t\tdeterminant = Determinant_4_x_4(matrix);\n\n\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(2136, determinant, 0.001);\n\t\t//std::cout << std::endl << \"Determinant, Answer should be 2136.\";\n\t\t//std::cout << std::endl << \"Determinant Answer: \" << determinant;\n\n\n\t}\n#if 0\n\tvoid PointWithinOrOnTetrahedron_test()\n\t{\n\n\t\t/* All positive coordinates\n\t\tisis_CADCommon::Point_3D  point_1(  0,  0, 0 );\n\t\tisis_CADCommon::Point_3D  point_2(  0,  1, 0 );\n\t\tisis_CADCommon::Point_3D  point_3(  1,  1, 0 );\n\t\tisis_CADCommon::Point_3D  point_4( .5, .5, 1.0 );\n\n\t\tstd::vector<isis_CADCommon::Point_3D> Tetrahedron_points;\n\n\t\tTetrahedron_points.push_back(point_1);\n\t\tTetrahedron_points.push_back(point_2);\n\t\tTetrahedron_points.push_back(point_3);\n\t\tTetrahedron_points.push_back(point_4);\n\n\t\t//Point_3D point(.5,.5, 1.0005);  // Not Within/On\n\t\t//Point_3D point(.5,.5, 1.000);  // Within/On \n\n\t\t//Point_3D point(.25,.25, .500001);  // Not Within/On \n\t\t//Point_3D point(.25,.25, .5);  // Within/On \n\n\t\t//Point_3D point(.75,.75, .500001);  // Not Within/On \n\t\t//Point_3D point(.75,.75, .5);  // Within/On \n\n\t\t//Point_3D point(0.0, 1.0, 0);  // Within/On \n\t\t//Point_3D point(0.0, 1.000006, 0);  // Not Within/On \n\n\t\t//Point_3D point(1.0, 1.0, 0);  // Within/On \n\t\t//Point_3D point(1.0, 1.000006, 0);  // Not Within/On \n\n\t\tPoint_3D point(.2, .2, .2);  //  Within/On \n\t\tbool pointWithin/On =  PointWithin/OnTetrahedron ( Tetrahedron_points, point );\n\n\t\t*/\n\n\t\t/* All negative coordinates\n\t\tisis_CADCommon::Point_3D  point_1(  0,  0, 0 );\n\t\tisis_CADCommon::Point_3D  point_2(  0,  -1, 0 );\n\t\tisis_CADCommon::Point_3D  point_3(  -1,  -1, 0 );\n\t\tisis_CADCommon::Point_3D  point_4( -.5, -.5, -1.0 );\n\n\t\tstd::vector<isis_CADCommon::Point_3D> Tetrahedron_points;\n\n\t\tTetrahedron_points.push_back(point_1);\n\t\tTetrahedron_points.push_back(point_2);\n\t\tTetrahedron_points.push_back(point_3);\n\t\tTetrahedron_points.push_back(point_4);\n\n\t\t//Point_3D point(-.5,-.5, -1.0005);  // Not Within/On\n\t\t//Point_3D point(-.5,-.5, -1.000);  // Within/On \n\n\t\t//Point_3D point(-.25,-.25, -.500001);  // Not Within/On \n\t\t//Point_3D point(-.25,-.25, -.5);  // Within/On \n\n\t\t//Point_3D point(-.75,-.75, -.500001);  // Not Within/On \n\t\t//Point_3D point(-.75,-.75, -.5);  // Within/On \n\n\t\t//Point_3D point(0.0, -1.0, 0);  // Within/On \n\t\t//Point_3D point(0.0, -1.000006, 0);  // Not Within/On \n\n\t\t//Point_3D point(-1.0, -1.0, 0);  // Within/On \n\t\t//Point_3D point(-1.0, -1.000006, 0);  // Not Within/On \n\n\t\tPoint_3D point(-.2, -.2, -.2);  //  Within/On \n\n\t\tbool pointWithin/On =  PointWithin/OnTetrahedron ( Tetrahedron_points, point );\n\t\t*/\n\n\n\t\t//* Mix negative and positive\n\t\tisis_CADCommon::Point_3D  point_1( -.5,   0, 0 );\n\t\tisis_CADCommon::Point_3D  point_2(   .5,  .5, 0 );\n\t\tisis_CADCommon::Point_3D  point_3(  .5,  0, 0 );\n\n\t\tisis_CADCommon::Point_3D  point_4(   0,   .5, 1.0 );\n\n\t\tstd::vector<isis_CADCommon::Point_3D> Tetrahedron_points;\n\n\t\tTetrahedron_points.push_back(point_1);\n\t\tTetrahedron_points.push_back(point_2);\n\t\tTetrahedron_points.push_back(point_3);\n\t\tTetrahedron_points.push_back(point_4);\n\n\t\t//Point_3D point( 0, 0.5, -1.0005);  // Not Within/On\n\t\t//Point_3D point( 0, 0.5, 1.000);  // Within/On \n\n\t\t//Point_3D point(.25, .25, .500001);  // Not Within/On \n\t\t//Point_3D point(.25, .25, .5);  // Within/On \n\n\t\t//Point_3D point( .25, .25, .500001);  // Not Within/On \n\t\t//Point_3D point( -.25, .25, .5);  // Within/On \n\n\t\t//Point_3D point( .5, .5, 0);  // Within/On \n\t\t//Point_3D point(.5, .5000001, 0);  // Not Within/On \n\n\t\t//Point_3D point(-.5, 0 , 0);  // Within/On \n\t\t//Point_3D point( -.50000001, 0 , 0);  // Not Within/On \n\n\t\tPoint_3D point(.2, .2, .2);  //  Within/On \n\n\t\tbool pointWithin =  PointWithinOrOnTetrahedron ( Tetrahedron_points, point );\n\t\t//*/\n\n\t\tstd::cout << std::endl << \"pointWithin: \" << pointWithin;\n\t}\n\n\tvoid CentroidOfTetrahedron_test()\n\t{\n\t\t//isis_CADCommon::Point_3D  point_1(  0,  0, 0 );\n\t\t//isis_CADCommon::Point_3D  point_2(  1,  0, 0 );\n\t\t//isis_CADCommon::Point_3D  point_3(  0,  1, 0 );\n\t\t//isis_CADCommon::Point_3D  point_4( .5, .5, 1.0 );\n\n\t\tisis_CADCommon::Point_3D  point_1(  1,  0, 0 );\n\t\tisis_CADCommon::Point_3D  point_2(  0,  2, 0 );\n\t\tisis_CADCommon::Point_3D  point_3(  0,  4, 1 );\n\t\tisis_CADCommon::Point_3D  point_4( 0, 0, 3.0 );\n\t\t// Answer Centroid: 0.25  1.5  1\n\n\n\t\tstd::vector<isis_CADCommon::Point_3D> Tetrahedron_points;\n\n\t\tTetrahedron_points.push_back(point_1);\n\t\tTetrahedron_points.push_back(point_2);\n\t\tTetrahedron_points.push_back(point_3);\n\t\tTetrahedron_points.push_back(point_4);\t\t\n\n\t\tPoint_3D centroid;\n\n\t\tCentroidOfTetrahedron( Tetrahedron_points, centroid);\n\n\t\tstd::cout << std::endl << \"Centroid: \" << centroid.x << \"  \" << centroid.y << \"  \" << centroid.z; \n\t}\n#endif\n\n\tvoid Tests::VolumeOfTetrahedron_test()\n\t{\n\t\t// https://www.easycalculation.com/analytical/parellelepiped-tetrahedron-volume.php\n\n\t\tstd::vector<isis_CADCommon::Point_3D> Tetrahedron_points;\n\n\t\tisis_CADCommon::Point_3D  point_1(  0,  0, 0 );\n\t\tisis_CADCommon::Point_3D  point_2(  2,  0, 0 );\n\t\tisis_CADCommon::Point_3D  point_3(  1,  2, 0 );\n\t\tisis_CADCommon::Point_3D  point_4( 1,  1.0, 2.0 );\n\n\n\t\tTetrahedron_points.clear();\n\t\tTetrahedron_points.push_back(point_1);\n\t\tTetrahedron_points.push_back(point_2);\n\t\tTetrahedron_points.push_back(point_3);\n\t\tTetrahedron_points.push_back(point_4);\t\n\n\t\tdouble volume =  VolumeOfTetrahedron( Tetrahedron_points);\n\t\t//std::cout << std::endl << \"Answer should be: 1.33\"; \n\t\t//std::cout << std::endl << \"Volume: \" << volume; \n\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(1.33333, volume, 0.001);\n\n\t\tisis_CADCommon::Point_3D  point_1_2(  0,  0, 0 );\n\t\tisis_CADCommon::Point_3D  point_2_2(  1,  0, 0 );\n\t\tisis_CADCommon::Point_3D  point_3_2(  0,  1, 0 );\n\t\tisis_CADCommon::Point_3D  point_4_2( .5, .5, 1.0 );\n\n\t\tTetrahedron_points.clear();\n\t\tTetrahedron_points.push_back(point_1_2);\n\t\tTetrahedron_points.push_back(point_2_2);\n\t\tTetrahedron_points.push_back(point_3_2);\n\t\tTetrahedron_points.push_back(point_4_2);\t\n\n\t\tvolume =  VolumeOfTetrahedron( Tetrahedron_points);\n\t\t//std::cout << std::endl << \"Answer should be: 1.1666\"; \n\t\t//std::cout << std::endl << \"Volume: \" << volume;\n\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(0.16666666, volume, 0.001);\n\n\n\t\tisis_CADCommon::Point_3D  point_1_3(  -5,  0, 0 );\n\t\tisis_CADCommon::Point_3D  point_2_3(  1,  0, 0 );\n\t\tisis_CADCommon::Point_3D  point_3_3(  2,  -1, 0 );\n\t\tisis_CADCommon::Point_3D  point_4_3( .5, .5, 3.0 );\n\n\t\tTetrahedron_points.clear();\n\t\tTetrahedron_points.push_back(point_1_3);\n\t\tTetrahedron_points.push_back(point_2_3);\n\t\tTetrahedron_points.push_back(point_3_3);\n\t\tTetrahedron_points.push_back(point_4_3);\t\n\n\t\tvolume =  VolumeOfTetrahedron( Tetrahedron_points);\n\t\t//std::cout << std::endl << \"Answer should be: 3.0\"; \n\t\t//std::cout << std::endl << \"Volume: \" << volume; \n\t\tCPPUNIT_ASSERT_DOUBLES_EQUAL(3.0, volume, 0.001);\n\t}\n\n", "meta": {"hexsha": "46c0288e15a109a900e6f3e412ce8fc984b53f89", "size": 54862, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CADAssembler/CADCommonTest/TestFunctions.cpp", "max_stars_repo_name": "lefevre-fraser/openmeta-mms", "max_stars_repo_head_hexsha": "08f3115e76498df1f8d70641d71f5c52cab4ce5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CADAssembler/CADCommonTest/TestFunctions.cpp", "max_issues_repo_name": "lefevre-fraser/openmeta-mms", "max_issues_repo_head_hexsha": "08f3115e76498df1f8d70641d71f5c52cab4ce5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CADAssembler/CADCommonTest/TestFunctions.cpp", "max_forks_repo_name": "lefevre-fraser/openmeta-mms", "max_forks_repo_head_hexsha": "08f3115e76498df1f8d70641d71f5c52cab4ce5f", "max_forks_repo_licenses": ["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.694874851, "max_line_length": 153, "alphanum_fraction": 0.6141956181, "num_tokens": 19140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5561100430037258}}
{"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": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <functional>\n#include <stack>\n#include <utility>\n\n#include <tr1/array>\n\n#include <boost/lambda/lambda.hpp>\n\n#include <cassert>\n#include <cstdlib>\n#include <sys/time.h>\n#include <ctime>\n\n////////////////////////////////////////////////////////////////////////////////////\nstd::string tab(int);\n\nstd::string\ntab(int size)\n{\n  std::string res;\n  for( std::size_t i = 0; i < size; ++i)\n  {\n    res += \" \";\n  }\n  return res;\n}\n\n////////////////////////////////////////////////////////////////////////////////////\ntypedef std::vector<unsigned int> vec_type;\n\nstd::ostream& operator<<(std::ostream&, const std::vector<unsigned int>&);\n\nstd::ostream&\noperator<<(std::ostream& os, const std::vector<unsigned int>& c)\n{\n  std::cout << \"{\";\n  std::vector<unsigned int>::const_iterator cit = c.begin();\n  if (cit != c.end())\n  {\n    os << *cit;\n    for( ++cit; cit != c.end(); ++cit)\n    {\n      os << \",\" << *cit;\n    }\n  }\n  return os << \"}\";\n}\n\n////////////////////////////////////////////////////////////////////////////////////\ntemplate<typename Iterator>\nvoid\nquicksort(const Iterator first, const Iterator last)\n{\n  const std::size_t distance = std::distance(first, last);\n  if (distance > 1)\n  {\n    Iterator pivot = first + distance/2;\n    std::swap(*pivot, *(last - 1)); // backup pivot in last position\n    pivot = last - 1;\n    const Iterator middle = std::partition(first, pivot, boost::lambda::_1 < *pivot); // partition of [first,pivot)\n    std::swap(*middle, *pivot);\n    quicksort(first, middle);\n    quicksort(middle + 1, last);\n  }\n}\n\n////////////////////////////////////////////////////////////////////////////////////\ntemplate<typename Iterator>\nvoid\nquicksort_stack(const Iterator first, const Iterator last)\n{\n  typedef typename Iterator::value_type value_type;\n  typedef std::pair<Iterator, Iterator> work_type;\n  typedef std::stack< work_type > stack_type;\n  stack_type stack;\n  \n  stack.push(make_pair(first, last));\n  \n  while (not stack.empty())\n  {\n    const work_type w = stack.top();\n    stack.pop();\n\n    const std::size_t distance = std::distance(w.first, w.second);\n    if (distance > 1)\n    {\n      Iterator pivot = w.first + distance/2;\n      std::swap(*pivot, *(w.second - 1)); // backup pivot in last position\n      pivot = w.second - 1;\n      const Iterator middle = std::partition(w.first, pivot, boost::lambda::_1 < *pivot); // partition of [first,pivot)\n      std::swap(*middle, *pivot);\n      stack.push(make_pair(w.first, middle));\n      stack.push(make_pair(middle + 1, w.second));\n    }\n  }\n}\n\n////////////////////////////////////////////////////////////////////////////////////\ntemplate<typename Iterator>\nvoid\nquicksort2(Iterator first, Iterator last, int depth = 0)\n{\n  while (last - first > 1)\n  {\n    const std::size_t distance = std::distance(first, last);\n    Iterator pivot = first + distance/2;\n    std::swap(*pivot, *(last - 1)); // backup pivot in last position\n    pivot = last - 1;\n    const Iterator middle = std::partition(first, pivot, boost::lambda::_1 < *pivot); // partition of [first,pivot)\n    std::swap(*middle, *pivot);\n    if (middle - first < last - middle-1)\n    {\n      quicksort2(first, middle, depth + 4);\n      first = middle + 1;\n    }\n    else\n    {\n      quicksort2(middle + 1, last, depth + 4);\n      last = middle;\n    }\n  }\n}\n\n////////////////////////////////////////////////////////////////////////////////////\nint\nmain ()\n{\n  std::tr1::array<unsigned int, 4> a = {19,16,1,13};\n  std::vector<unsigned int> d(a.begin(), a.end());\n  quicksort(d.begin(), d.end());\n  \n  std::cout << std::endl << d << std::endl;\n  \n  srandom(static_cast<int>(time(NULL)));\n  struct timeval begin;\n  struct timeval end;\n  ::gettimeofday(&begin, NULL);\n  for(std::size_t i = 0; i < 10; ++i)\n  {\n    std::vector<unsigned int> data;\n    for( unsigned int i = 0; i < 10000; ++i)\n    {\n      data.push_back(static_cast<unsigned int>(random() % 20));\n    }\n//    std::cout << std::endl << data << std::endl;\n    std::vector<unsigned int> oracle(data.begin(), data.end());\n    quicksort(data.begin(), data.end());\n    std::sort(oracle.begin(), oracle.end());\n//    std::cout << data << std::endl;\n    assert(data == oracle);\n  }  \n  ::gettimeofday(&end, NULL);  \n  std::cout << (end.tv_sec - begin.tv_sec)*1000 + (end.tv_usec - begin.tv_usec)/1000 << \"ms \" << std::endl;\n\n  return 0;\n}", "meta": {"hexsha": "3884fe6ced9e285b98b3211b4d5b185f995aa18b", "size": 4396, "ext": "cc", "lang": "C++", "max_stars_repo_path": "c++/algorithms/quicksort.cc", "max_stars_repo_name": "ahamez/snippets", "max_stars_repo_head_hexsha": "28f773c7488efcf474f83114747dd377e128e30d", "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++/algorithms/quicksort.cc", "max_issues_repo_name": "ahamez/snippets", "max_issues_repo_head_hexsha": "28f773c7488efcf474f83114747dd377e128e30d", "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++/algorithms/quicksort.cc", "max_forks_repo_name": "ahamez/snippets", "max_forks_repo_head_hexsha": "28f773c7488efcf474f83114747dd377e128e30d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6477987421, "max_line_length": 119, "alphanum_fraction": 0.5429936306, "num_tokens": 1102, "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/*!\n  @file\n\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/log10.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/meta/cardinal_of.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/ten.hpp>\n#include <boost/simd/constant/three.hpp>\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& runtime)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], b[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : bs::rec(T(i));\n    b[i] = bs::plain_(bs::log10)(a1[i]) ;\n  }\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n\n  STF_ULP_EQUAL(/*bs::plain_*/(bs::log10)(aa1), bb, 0.5);\n}\n\nSTF_CASE_TPL(\"Check log10 on pack\", STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  using p_t = bs::pack<T>;\n  static const std::size_t N = bs::cardinal_of<p_t>::value;\n  test<T, N>(runtime);\n  test<T, N/2>(runtime);\n  test<T, N*2>(runtime);\n}\n\n\n\nSTF_CASE_TPL (\" log10\", STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::log10;\n  using p_t = bs::pack<T>;\n\n  using r_t = decltype(bs::plain_(log10)(p_t()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, p_t);\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(bs::plain_(log10)(bs::Inf<p_t>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(bs::plain_(log10)(bs::Minf<p_t>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(bs::plain_(log10)(bs::Nan<p_t>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(bs::plain_(log10)(bs::Mone<p_t>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(bs::plain_(log10)(bs::Zero<p_t>()), bs::Minf<r_t>(), 0);\n  STF_ULP_EQUAL(bs::plain_(log10)(bs::Mzero<p_t>()), bs::Minf<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(bs::plain_(log10)(bs::One<p_t>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(bs::plain_(log10)(bs::Two<p_t>()), p_t(0.301029995663981195213738894724), 0);\n  STF_ULP_EQUAL(bs::plain_(log10)(bs::Three<p_t>()),p_t(0.477121254719662437295027903255), 0.5);\n}\n\n", "meta": {"hexsha": "3e42929682c4ed65d29dbfb3656a24ffe0026bd4", "size": 2645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/log10.plain.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "test/function/simd/log10.plain.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/simd/log10.plain.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": 32.256097561, "max_line_length": 100, "alphanum_fraction": 0.6151228733, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5560989678872469}}
{"text": "#include <iostream>\n#include <typeinfo>\r\n#define BOOST_TEST_MODULE SparseMIAAddSubtractTests\n\r\n\n\n#include \"MIAConfig.h\"\n\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#endif\r\n\r\n\r\n\n#include \"DenseMIA.h\"\r\n#include \"SparseMIA.h\"\n#include \"Index.h\"\n#include \"LibMIAUtil.h\"\r\ntemplate<class _data_type>\r\nvoid do_work(size_t dim1,size_t dim2){\r\n\r\n    LibMIA::MIAINDEX i;\n    LibMIA::MIAINDEX j;\n    LibMIA::MIAINDEX k;\r\n    LibMIA::MIAINDEX l;\n\r\n\r\n    LibMIA::DenseMIA<_data_type,4> dense_a(dim1,dim1,dim2,dim2);\r\n    LibMIA::DenseMIA<_data_type,4> dense_b(dim2,dim1,dim2,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> dense_c(dim2,dim1,dim2,dim1);\r\n\r\n    dense_a.ones();\r\n    dense_b.ones();\r\n\r\n    LibMIA::SparseMIA<_data_type,4> a(dense_a);\r\n    LibMIA::SparseMIA<_data_type,4> b(dense_b);\r\n    LibMIA::SparseMIA<_data_type,4> c(dim2,dim1,dim2,dim1);\r\n    //a.print();\r\n    //b.print();\r\n    //boost::timer::cpu_timer scan_t,total_t;\r\n\r\n    std::array<size_t,4> new_linIdxSequence{{2,0,3,1}};\r\n    std::array<size_t,4> new_linIdxSequence2{{1,3,0,2}};\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n\r\n    //scan_t.stop();\r\n    //c.print();\r\n    //std::cout << \"Scan add \" << boost::timer::format(scan_t.elapsed()) << std::endl;\r\n    //boost::timer::cpu_timer dense_t;\r\n    dense_c(i,j,k,l)=dense_b(i,j,k,l)+dense_a(j,l,i,k);\r\n    //std::cout << \"Dense Scan add \" << boost::timer::format(dense_t.elapsed()) << std::endl;\r\n\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Add (Scan) 1a for \")+typeid(_data_type).name());\r\n\r\n    //now check when b is not sorted\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Add (Scan) 1b for \")+typeid(_data_type).name());\r\n\r\n    //now check when a and b have non default sort orders\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Add (Scan) 1c for \")+typeid(_data_type).name());\r\n\r\n\r\n    c(i,j,k,l)=b(i,j,k,l)+b(k,l,i,j);\r\n    dense_c(i,j,k,l)=dense_b(i,j,k,l)+dense_b(k,l,i,j);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Self addition check 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n    //test when a is not sorted (uses a different merge algorithm)\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    //boost::timer::cpu_timer sort_t;\r\n    c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n\r\n    //sort_t.stop();\r\n    //std::cout << \"Sort add \" << boost::timer::format(sort_t.elapsed()) << std::endl;\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Add (Sort) 1a for \")+typeid(_data_type).name());\r\n\r\n    //test when a is not sorted (uses a different merge algorithm) and both have different sort orders\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    //boost::timer::cpu_timer sort_t;\r\n    c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n\r\n    //sort_t.stop();\r\n    //std::cout << \"Sort add \" << boost::timer::format(sort_t.elapsed()) << std::endl;\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Add (Sort) 1b for \")+typeid(_data_type).name());\r\n\r\n\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)+=a(j,l,i,k);\r\n    dense_b(i,j,k,l)+=dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Add (Scan) 1a for \")+typeid(_data_type).name());\r\n\r\n    dense_b.ones();\r\n    b=dense_b;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)+=a(j,l,i,k);\r\n    dense_b(i,j,k,l)+=dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Add (Scan) 1b for \")+typeid(_data_type).name());\r\n\r\n    dense_b.ones();\r\n    b=dense_b;\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    b(i,j,k,l)+=a(j,l,i,k);\r\n    dense_b(i,j,k,l)+=dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Add (Scan) 1c for \")+typeid(_data_type).name());\r\n\r\n\r\n    dense_b.ones();\r\n    b=dense_b;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)+=a(j,l,i,k);\r\n    dense_b(i,j,k,l)+=dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Add (Sort) 1a for \")+typeid(_data_type).name());\r\n\r\n    dense_b.ones();\r\n    b=dense_b;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    b(i,j,k,l)+=a(j,l,i,k);\r\n    dense_b(i,j,k,l)+=dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Add (Sort) 1b for \")+typeid(_data_type).name());\r\n\r\n    dense_b.fill(3);\r\n    b=dense_b;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n    dense_c(i,j,k,l)=dense_b(i,j,k,l)-dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Subtract (Scan) 1a for \")+typeid(_data_type).name());\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Subtract (Scan) 1b for \")+typeid(_data_type).name());\r\n\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Subtract (Scan) 1c for \")+typeid(_data_type).name());\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Subtract (Sort) 1a for \")+typeid(_data_type).name());\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    a.change_linIdx_sequence(new_linIdxSequence2);\r\n    c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Subtract (Sort) 1b for \")+typeid(_data_type).name());\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)-=a(j,l,i,k);\r\n    dense_b(i,j,k,l)-=dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Subtract (Scan) 1a for \")+typeid(_data_type).name());\r\n\r\n    dense_b.fill(3);\r\n    b=dense_b;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)-=a(j,l,i,k);\r\n    dense_b(i,j,k,l)-=dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Subtract (Scan) 1b for \")+typeid(_data_type).name());\r\n\r\n    dense_b.fill(3);\r\n    b=dense_b;\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    b(i,j,k,l)-=a(j,l,i,k);\r\n    dense_b(i,j,k,l)-=dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Subtract (Scan) 1c for \")+typeid(_data_type).name());\r\n\r\n    dense_b.fill(3);\r\n    b=dense_b;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)-=a(j,l,i,k);\r\n    dense_b(i,j,k,l)-=dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Subtract (Sort) 1a for \")+typeid(_data_type).name());\r\n\r\n    dense_b.fill(3);\r\n    b=dense_b;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence2);\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)-=a(j,l,i,k);\r\n    dense_b(i,j,k,l)-=dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Subtract (Sort) 1b for \")+typeid(_data_type).name());\r\n\r\n    //****Now try with lots of zeros in our MIAs\r\n    LibMIA::DenseMIA<_data_type,4> dense_a_orig(dim1,dim1,dim2,dim2);\r\n    LibMIA::DenseMIA<_data_type,4> dense_b_orig(dim2,dim1,dim2,dim1);\r\n    dense_a_orig.randu(0,20);\r\n    dense_b_orig.randu(0,20);\r\n    for(auto it=dense_a_orig.data_begin();it<dense_a_orig.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n    for(auto it=dense_b_orig.data_begin();it<dense_b_orig.data_end();++it)\r\n        if(*it<15)\r\n            *it=0;\r\n    a=dense_a_orig;\r\n    b=dense_b_orig;\r\n    dense_a=dense_a_orig;\r\n    dense_b=dense_b_orig;\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n    dense_c(i,j,k,l)=dense_b(i,j,k,l)+dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Add (Scan) 2a for \")+typeid(_data_type).name());\r\n\r\n\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Add (Scan) 2b for \")+typeid(_data_type).name());\r\n\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Add (Scan) 2c for \")+typeid(_data_type).name());\r\n\r\n    //test when a is not sorted (uses a different merge algorithm)\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Add (Sort) 2a for \")+typeid(_data_type).name());\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Add (Sort) 2b for \")+typeid(_data_type).name());\r\n\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k)+b(k,l,i,j)+a(l,j,i,k);\r\n    dense_c(i,j,k,l)=dense_b(i,j,k,l)+dense_a(j,l,i,k)+dense_b(k,l,i,j)+dense_a(l,j,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Chained Non-destructive Add (Sort) 2a for \")+typeid(_data_type).name());\r\n\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)+=a(j,l,i,k);\r\n    dense_b(i,j,k,l)+=dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Add (Scan) 2a for \")+typeid(_data_type).name());\r\n\r\n    b=dense_b_orig;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)+=a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Add (Scan) 2b for \")+typeid(_data_type).name());\r\n\r\n    b=dense_b_orig;\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    b(i,j,k,l)+=a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Add (Scan) 2c for \")+typeid(_data_type).name());\r\n\r\n\r\n    b=dense_b_orig;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)+=a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Add (Sort) 2a for \")+typeid(_data_type).name());\r\n\r\n    b=dense_b_orig;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)+=a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Add (Sort) 2b for \")+typeid(_data_type).name());\r\n\r\n    dense_b=dense_b_orig;\r\n    b=dense_b;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n    dense_c(i,j,k,l)=dense_b(i,j,k,l)-dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Subtract (Scan) 2a for \")+typeid(_data_type).name());\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Subtract (Scan) 2b for \")+typeid(_data_type).name());\r\n\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Subtract (Scan) 2c for \")+typeid(_data_type).name());\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Subtract (Sort) 2a for \")+typeid(_data_type).name());\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(c==dense_c,std::string(\"Non-destructive Subtract (Sort) 2b for \")+typeid(_data_type).name());\r\n\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)-=a(j,l,i,k);\r\n    dense_b(i,j,k,l)-=dense_a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Subtract (Scan) 2a for \")+typeid(_data_type).name());\r\n\r\n\r\n\r\n    b=dense_b_orig;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)-=a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Subtract (Scan) 2b for \")+typeid(_data_type).name());\r\n\r\n    b=dense_b_orig;\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    b(i,j,k,l)-=a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Subtract (Scan) 2c for \")+typeid(_data_type).name());\r\n\r\n\r\n    b=dense_b_orig;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence);\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)-=a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Subtract (Sort) 2a for \")+typeid(_data_type).name());\r\n\r\n    b=dense_b_orig;\r\n    a.reset_linIdx_sequence();\r\n    a.sort();\r\n    b.reset_linIdx_sequence();\r\n    b.sort();\r\n    b.change_linIdx_sequence(new_linIdxSequence2);\r\n    a.change_linIdx_sequence(new_linIdxSequence);\r\n    b(i,j,k,l)-=a(j,l,i,k);\r\n    BOOST_CHECK_MESSAGE(b==dense_b,std::string(\"Destructive Subtract (Sort) 2b for \")+typeid(_data_type).name());\r\n\r\n\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( SparseMIAAddSubtractTests )\n{\n\r\n\n\r\n    //do_work<double>(2,3);\r\n    do_work<double>(5,8);\n    do_work<float>(5,8);\r\n    do_work<int>(5,8);\n    do_work<long long int>(5,8);\r\n\r\n//    do_work<double>(10,8);\n//    do_work<float>(10,8);\r\n//    do_work<int>(10,8);\n//    do_work<long long int>(10,8);\r\n\r\n\r\n\n\n}\r\n", "meta": {"hexsha": "fb75c0727c59348dee6751350249a5bddfd9e6c6", "size": 17582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/SparseMIA/sparse_mia_add_sub_tests.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/SparseMIA/sparse_mia_add_sub_tests.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/SparseMIA/sparse_mia_add_sub_tests.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 34.4745098039, "max_line_length": 121, "alphanum_fraction": 0.646399727, "num_tokens": 5035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5560989678872469}}
{"text": "/*\n *  random.cpp\n *\n *  Created by Ania M. Kedzierska on 11/11/11.\n *  Copyright 2011 Politecnic University of Catalonia, Center for Genomic Regulation.  This is program can be redistributed, modified or else as given by the terms of the GNU General Public License.\n *\n */\n\n#include <ctime>\n\n#include \"random.h\"\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/discrete_distribution.hpp>\n\n\nboost::random::mt19937 random_gen((unsigned int) std::time(NULL)+getpid());  // Random number generator\n\nboost::random::uniform_real_distribution<double> uni_real_dist;  // Uniform distribution\nboost::random::uniform_int_distribution<long> uni_int_dist;      // Uniform distribution\nboost::random::discrete_distribution<long, double> disc_dist;    // Discrete distribution\n\n\n// Initialize the seed of the random number generator\nvoid random_initialize(unsigned int seed) {\n  random_gen.seed(seed);\n}\n\n// Initialize with a time derived seed\nvoid random_initialize() {\n  random_initialize((unsigned int) std::time(NULL)+getpid());\n}\n\n\n// uniformly random real in [a,b)\ndouble uniform_real(double a, double b) {\n  boost::random::uniform_real_distribution<double>::param_type param(a, b);\n  uni_real_dist.param(param);\n  return uni_real_dist(random_gen);\n}\n\n// random integer in[a,b]\n  long uniform_int(long a, long b) {\n  boost::random::uniform_int_distribution<long>::param_type param(a, b);\n  uni_int_dist.param(param);\n  return uni_int_dist(random_gen);\n}\n\n// random integer between 0 and p.size()-1 according to the probabilities in p.\nlong discrete(std::vector<double> &p) {\n  boost::random::discrete_distribution<long, double>::param_type param(p);\n  disc_dist.param(param);\n  return disc_dist(random_gen);\n}\n", "meta": {"hexsha": "20781bdde4936cd83a0f3f50188b7cb1465acefa", "size": 1830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/random.cpp", "max_stars_repo_name": "Algebraicphylogenetics/GenNon-H", "max_stars_repo_head_hexsha": "c60b4ebeefbe154c2c9f13f76f78591c36786a36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-07-18T21:09:19.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-18T21:09:19.000Z", "max_issues_repo_path": "src/random.cpp", "max_issues_repo_name": "Algebraicphylogenetics/GenNon-H", "max_issues_repo_head_hexsha": "c60b4ebeefbe154c2c9f13f76f78591c36786a36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/random.cpp", "max_forks_repo_name": "Algebraicphylogenetics/GenNon-H", "max_forks_repo_head_hexsha": "c60b4ebeefbe154c2c9f13f76f78591c36786a36", "max_forks_repo_licenses": ["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.1052631579, "max_line_length": 198, "alphanum_fraction": 0.7573770492, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5560989605056098}}
{"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": "//=======================================================================\n// Copyright (c) 2005 Aaron Windsor\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 <string>\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <cassert>\n\n#include <boost/graph/max_cardinality_matching.hpp>\n\nusing namespace boost;\n\ntypedef adjacency_list< vecS, vecS, undirectedS > my_graph;\n\nint main()\n{\n\n    // Create the following graph: (it'll look better when output\n    // to the terminal in a fixed width font...)\n\n    const int n_vertices = 18;\n\n    std::vector< std::string > ascii_graph;\n\n    ascii_graph.push_back(\"           0       1---2       3       \");\n    ascii_graph.push_back(\"            \\\\     /     \\\\     /        \");\n    ascii_graph.push_back(\"             4---5       6---7         \");\n    ascii_graph.push_back(\"             |   |       |   |         \");\n    ascii_graph.push_back(\"             8---9      10---11        \");\n    ascii_graph.push_back(\"            /     \\\\     /     \\\\        \");\n    ascii_graph.push_back(\"     12   13      14---15      16   17 \");\n\n    // It has a perfect matching of size 8. There are two isolated\n    // vertices that we'll use later...\n\n    my_graph g(n_vertices);\n\n    // our vertices are stored in a vector, so we can refer to vertices\n    // by integers in the range 0..15\n\n    add_edge(1, 2, g);\n    add_edge(0, 4, g);\n    add_edge(1, 5, g);\n    add_edge(2, 6, g);\n    add_edge(3, 7, g);\n    add_edge(4, 5, g);\n    add_edge(6, 7, g);\n    add_edge(4, 8, g);\n    add_edge(5, 9, g);\n    add_edge(6, 10, g);\n    add_edge(7, 11, g);\n    add_edge(8, 9, g);\n    add_edge(10, 11, g);\n    add_edge(8, 13, g);\n    add_edge(9, 14, g);\n    add_edge(10, 15, g);\n    add_edge(11, 16, g);\n    add_edge(14, 15, g);\n\n    std::vector< graph_traits< my_graph >::vertex_descriptor > mate(n_vertices);\n\n    // find the maximum cardinality matching. we'll use a checked version\n    // of the algorithm, which takes a little longer than the unchecked\n    // version, but has the advantage that it will return \"false\" if the\n    // matching returned is not actually a maximum cardinality matching\n    // in the graph.\n\n    bool success = checked_edmonds_maximum_cardinality_matching(g, &mate[0]);\n    assert(success);\n\n    std::cout << \"In the following graph:\" << std::endl << std::endl;\n\n    for (std::vector< std::string >::iterator itr = ascii_graph.begin();\n         itr != ascii_graph.end(); ++itr)\n        std::cout << *itr << std::endl;\n\n    std::cout << std::endl\n              << \"Found a matching of size \" << matching_size(g, &mate[0])\n              << std::endl;\n\n    std::cout << \"The matching is:\" << std::endl;\n\n    graph_traits< my_graph >::vertex_iterator vi, vi_end;\n    for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n        if (mate[*vi] != graph_traits< my_graph >::null_vertex()\n            && *vi < mate[*vi])\n            std::cout << \"{\" << *vi << \", \" << mate[*vi] << \"}\" << std::endl;\n\n    std::cout << std::endl;\n\n    // now we'll add two edges, and the perfect matching has size 9\n\n    ascii_graph.pop_back();\n    ascii_graph.push_back(\"     12---13      14---15      16---17 \");\n\n    add_edge(12, 13, g);\n    add_edge(16, 17, g);\n\n    success = checked_edmonds_maximum_cardinality_matching(g, &mate[0]);\n    assert(success);\n\n    std::cout << \"In the following graph:\" << std::endl << std::endl;\n\n    for (std::vector< std::string >::iterator itr = ascii_graph.begin();\n         itr != ascii_graph.end(); ++itr)\n        std::cout << *itr << std::endl;\n\n    std::cout << std::endl\n              << \"Found a matching of size \" << matching_size(g, &mate[0])\n              << std::endl;\n\n    std::cout << \"The matching is:\" << std::endl;\n\n    for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n        if (mate[*vi] != graph_traits< my_graph >::null_vertex()\n            && *vi < mate[*vi])\n            std::cout << \"{\" << *vi << \", \" << mate[*vi] << \"}\" << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "3c8a4fbb9d61d844b1431c9c1dbe86a3759bedb8", "size": 4177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/matching_example.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/matching_example.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/matching_example.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.1507936508, "max_line_length": 80, "alphanum_fraction": 0.5408187695, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.5560801760661908}}
{"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": "//==================================================================================================\n/*!\n\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#include <boost/simd/function/scalar/expocvt.hpp>\n#include <scalar_test.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/detail/constant/maxexponent.hpp>\n\nSTF_CASE_TPL (\" expocvt real\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using uiT = bd::as_integer_t<T, unsigned>;\n  using iT = bd::as_integer_t<T>;\n  using bs::expocvt;\n  using r_t = decltype(expocvt(T()));\n\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T); //(bd::as_integer_t<T, signed>));\n\n  // specific values tests\n\n  for( iT i=-bs::Maxexponent<T>(); i < bs::Maxexponent<T>(); ++i)\n  {\n    std::cout << i << std::endl;\n    STF_EQUAL(expocvt(T(i)),std::ldexp(T(1), i));\n  }\n} // end of test for floating_\n\n", "meta": {"hexsha": "fb5a2f1177f8107a073b533c39054ed83b011ace", "size": 1372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/expocvt.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "test/function/scalar/expocvt.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/scalar/expocvt.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 31.9069767442, "max_line_length": 100, "alphanum_fraction": 0.5983965015, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5559475834617398}}
{"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(\"\u2192 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(\" \u2192 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(\" \u2192 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(\" \u2192 \u2192 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(\" \u2192 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(\" \u2192 \u2192 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#include <Eigen/Dense>\n#include <memory>\n\ntypedef std::pair<Eigen::Vector3d, double> PlaneParam; //normal, offset\ntypedef std::pair<std::pair<Eigen::Vector3d, Eigen::Vector3d>, double> CylinderParam; //(point, direction), radius\ntypedef std::pair<Eigen::Vector3d, Eigen::Vector3d> Edge3d;\ntypedef std::pair<Eigen::Vector2d, Eigen::Vector2d> Edge2d;\n\nstruct PointCloud3 {\n    Eigen::MatrixX3d P;\n    Eigen::MatrixX3d N;\n    typedef std::shared_ptr<PointCloud3> Handle;\n};\n\nstruct PointCloud2 {\n    Eigen::MatrixX2d P;\n    typedef std::shared_ptr<PointCloud2> Handle;\n};\n", "meta": {"hexsha": "e8caf901311941eabe06993d731c01718709b4ca", "size": 582, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/typedefs.hpp", "max_stars_repo_name": "ShnitzelKiller/Reverse-Engineering-Carpentry", "max_stars_repo_head_hexsha": "585b5ff053c7e3bf286b663a584bc83687691bd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T07:28:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T21:12:40.000Z", "max_issues_repo_path": "src/utils/typedefs.hpp", "max_issues_repo_name": "ShnitzelKiller/Reverse-Engineering-Carpentry", "max_issues_repo_head_hexsha": "585b5ff053c7e3bf286b663a584bc83687691bd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-21T14:40:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-26T01:19:38.000Z", "max_forks_repo_path": "src/utils/typedefs.hpp", "max_forks_repo_name": "ShnitzelKiller/Reverse-Engineering-Carpentry", "max_forks_repo_head_hexsha": "585b5ff053c7e3bf286b663a584bc83687691bd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1, "max_line_length": 114, "alphanum_fraction": 0.7319587629, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.555939583694363}}
{"text": "#include <ros/ros.h>\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/QR>\n#include <sophus/se3.hpp>\n#include <math.h>\n#include <mutex>\n#include <atomic>\n\n// MoveIt!\n#include <moveit/robot_model_loader/robot_model_loader.h>\n#include <moveit/robot_model/robot_model.h>\n#include <moveit/robot_state/robot_state.h>\n#include <moveit/move_group_interface/move_group_interface.h>\n#include <moveit/planning_scene_interface/planning_scene_interface.h>\n\n// visp\n#include <visp3/visual_features/vpFeatureBuilder.h>\n#include <visp3/vs/vpServo.h>\n#include <visp3/visual_features/vpFeatureThetaU.h>\n#include <visp3/visual_features/vpFeatureTranslation.h>\n#include <visp3/core/vpHomogeneousMatrix.h>\n\nclass PBVS {\npublic:\n    PBVS():s_t_(vpFeatureTranslation::cMo), s_tu_(vpFeatureThetaU::cdRc),\n                              s_star_t_(vpFeatureTranslation::cMo), s_star_tu_(vpFeatureThetaU::cdRc),\n                              v_c_(6) {}\n    ~PBVS() {task_.kill();}\n    void Init() {\n        cdMo_[0][0] = -1; cdMo_[0][1] = 0; cdMo_[0][2] =  0; cdMo_[0][3] = 0.1112315;\n        cdMo_[1][0] = 0; cdMo_[1][1] = -1; cdMo_[1][2] =  0; cdMo_[1][3] = 0.21367;\n        cdMo_[2][0] = 0; cdMo_[2][1] =  0; cdMo_[2][2] = 1; cdMo_[2][3] = 0.6;\n        s_star_t_.buildFrom(cdMo_);\n        task_.setServo(vpServo::EYEINHAND_CAMERA);    // Camera is monted on the robot end-effector and velocities are computed in the camera frame\n        task_.setInteractionMatrixType(vpServo::CURRENT);    // Interaction matrix is computed with the current visual features s\n        task_.setLambda(0.1);         // Set the contant 0.5\n        task_.addFeature(s_t_, s_star_t_);          // Add current and desired translation feature\n        task_.addFeature(s_tu_, s_star_tu_);           // Add current and desired ThetaU feature for the rotation\n    }\n    bool Calc(const Eigen::Transform<double, 3, Eigen::Isometry>& cMo, Eigen::Matrix<double, 6, 1>& cart_v) {\n        cMo_[0][0] = cMo(0, 0); cMo_[0][1] = cMo(0, 1); cMo_[0][2] = cMo(0, 2); cMo_[0][3] = cMo(0, 3);\n        cMo_[1][0] = cMo(1, 0); cMo_[1][1] = cMo(1, 1); cMo_[1][2] = cMo(1, 2); cMo_[1][3] = cMo(1, 3);\n        cMo_[2][0] = cMo(2, 0); cMo_[2][1] = cMo(2, 1); cMo_[2][2] = cMo(2, 2); cMo_[2][3] = cMo(2, 3);\n        cMo_[3][0] = cMo(3, 0); cMo_[3][1] = cMo(3, 1); cMo_[3][2] = cMo(3, 2); cMo_[3][3] = cMo(3, 3);\n        cdMc_ = cdMo_ * cMo_.inverse();\n        s_t_.buildFrom(cMo_);\n        s_tu_.buildFrom(cdMc_);\n        v_c_ = task_.computeControlLaw(); // Compute camera velocity skew\n        cart_v << v_c_[0], v_c_[1], v_c_[2], v_c_[3], v_c_[4], v_c_[5];\n        error_ = (task_.getError()).sumSquare(); // error = s^2 - s_star^2\n        // ROS_INFO_STREAM(\"error_: \" << error_);\n        if(error_ < 0.00001) {\n            return true;\n        }\n        return false;\n        // ROS_INFO_STREAM(\"error_: \" << error_);\n    }\nprivate:\n    vpHomogeneousMatrix cdMc_;      //the displacement the camera has to achieve to move from the desired camera frame and the current one\n    vpHomogeneousMatrix cMo_;\n    vpHomogeneousMatrix oMo_;\n    vpHomogeneousMatrix cdMo_;\n    vpFeatureTranslation s_t_;     //the current visual feature s\n    vpFeatureThetaU s_tu_;\n    vpFeatureTranslation s_star_t_;      //the desired visual feature s*\n    vpFeatureThetaU s_star_tu_;\n    vpServo task_;         // the visual servo task\n    vpColVector v_c_;      // Camera velocity\n    double error_;         // Task error\n};\n\nclass SE3Pid {\npublic:\n    SE3Pid():kp_(0.01), ki_(0.0), kd_(0.0), dt_(1), max_(0.1), integral_(Eigen::Matrix<double, 6, 1>::Zero()), pre_error_(Eigen::Matrix<double, 6, 1>::Zero()) {}\n    ~SE3Pid() {}\n    bool Init() {\n        cdMo_ = Eigen::Transform<double, 3, Eigen::Isometry>::Identity();\n        Eigen::Matrix<double, 3, 3> rot;\n        rot << -1.0, 0.0, 0.0,\n                0.0, -1.0, 0.0,\n                0.0, 0.0, 1.0;\n        cdMo_.rotate(Eigen::Quaterniond(rot));\n        cdMo_.pretranslate(Eigen::Vector3d(0.1112315, 0.21367, 0.6));\n        cdMo_se3_ = Sophus::SE3d(Eigen::Quaterniond(cdMo_.matrix().block<3, 3>(0, 0)), Eigen::Vector3d(cdMo_.matrix().block<3, 1>(0, 3)));\n        oMcd_se3_ = Sophus::SE3d(Eigen::Quaterniond(cdMo_.inverse().matrix().block<3, 3>(0, 0)), Eigen::Vector3d(cdMo_.inverse().matrix().block<3, 1>(0, 3)));\n    }\n    bool Calc(const Eigen::Transform<double, 3, Eigen::Isometry>& cMo, Eigen::Transform<double, 3, Eigen::Isometry>& pose)  {\n        Sophus::SE3d cMo_se3(Eigen::Quaterniond(cMo.matrix().block<3, 3>(0, 0)), Eigen::Vector3d(cMo.matrix().block<3, 1>(0, 3)));\n        Eigen::Matrix<double, 6, 1> error = (cMo_se3.inverse() * cdMo_se3_).log();\n        Eigen::Matrix<double, 6, 1> diff = 0.1*error;\n        Sophus::SE3d se_i = cMo_se3 * Sophus::SE3d::exp(diff);\n        pose = se_i.matrix();\n        return false;\n    }\n    bool Calc(const Eigen::Transform<double, 3, Eigen::Isometry>& cMo, Eigen::Matrix<double, 6, 1>& cart_v)  {\n        Sophus::SE3d cMo_se3(Eigen::Quaterniond(cMo.matrix().block<3, 3>(0, 0)), Eigen::Vector3d(cMo.matrix().block<3, 1>(0, 3)));\n        Eigen::Matrix<double, 6, 1> error = (cMo_se3.inverse() * cdMo_se3_).log();\n        Eigen::Matrix<double, 6, 1> delta = 0.1*error;\n        // ROS_INFO_STREAM(\"delta: \" << delta);\n        cart_v = delta;\n        // if (error.norm() < 1e-6) {\n        //     return true;\n        // }\n        // // Proportional term\n        // Eigen::Matrix<double, 6, 1> p_out = kp_ * error;\n        // // Integral term\n        // integral_ += error * dt_;\n        // Eigen::Matrix<double, 6, 1> i_out = ki_ * integral_;\n        // // Derivative term\n        // Eigen::Matrix<double, 6, 1> derivative = (error - pre_error_) / dt_;\n        // Eigen::Matrix<double, 6, 1> d_out = kd_ * derivative;\n        // // Calculate total output\n        // Eigen::Matrix<double, 6, 1> diff = p_out + i_out + d_out;\n        // if (diff.norm() > max_) {\n        //     ROS_INFO_STREAM(\"pid is too large: \" << diff);\n        //     diff = diff * max_/diff.norm();\n        // }\n        // cart_v = diff;\n        // pre_error_ = error;\n        // return false;\n    }\n    bool Calc2o(const Eigen::Transform<double, 3, Eigen::Isometry>& cMo, Eigen::Matrix<double, 6, 1>& cart_v)  {\n        Sophus::SE3d oMc_se3(Eigen::Quaterniond(cMo.inverse().matrix().block<3, 3>(0, 0)), Eigen::Vector3d(cMo.inverse().matrix().block<3, 1>(0, 3)));\n        Eigen::Matrix<double, 6, 1> error = (oMc_se3.inverse() * oMcd_se3_).log();\n        Eigen::Matrix<double, 6, 1> delta = 0.1*error;\n        // ROS_INFO_STREAM(\"delta: \" << delta);\n        cart_v = delta;\n    }\nprivate:\n    float kp_;\n    float ki_;\n    float kd_;\n    float dt_;\n    float max_;\n    Eigen::Matrix<double, 6, 1> pre_error_;\n    Eigen::Matrix<double, 6, 1> integral_;\n    Eigen::Transform<double, 3, Eigen::Isometry> cdMo_;\n    Sophus::SE3d cdMo_se3_;\n    Sophus::SE3d oMcd_se3_;\n};\n\nclass Robot {\npublic:\n    // Robot(ros::NodeHandle& nh):nh_(nh), planning_group_(\"panda_arm\"), move_group_(\"panda_arm\"), robot_model_loader_(\"robot_description\") {\n    Robot(ros::NodeHandle& nh):nh_(nh), planning_group_(\"panda_arm\"), move_group_(\"panda_arm\"), reference_point_position_(0.0, 0.0, 0.0) {\n        // std::vector<double> joints = move_group_.getCurrentJointValues();\n        std::vector<double> joints = {0, 0, 0, -M_PI/2, 0, M_PI/2, 0};\n        move_group_.setStartStateToCurrentState();\n        move_group_.setJointValueTarget(joints);\n        move_group_.move();\n    }\n    ~Robot() {}\n    Eigen::Transform<double, 3, Eigen::Isometry> bMe() {\n        geometry_msgs::PoseStamped pose_msg = move_group_.getCurrentPose(\"panda_link8\");\n        Eigen::Transform<double, 3, Eigen::Isometry> pose = Eigen::Transform<double, 3, Eigen::Isometry>::Identity();\n        pose.rotate(Eigen::Quaterniond(pose_msg.pose.orientation.w, pose_msg.pose.orientation.x, pose_msg.pose.orientation.y, pose_msg.pose.orientation.z));\n        pose.pretranslate(Eigen::Vector3d(pose_msg.pose.position.x, pose_msg.pose.position.y, pose_msg.pose.position.z));\n        return pose;\n    }\n    // Eigen::MatrixXd jacobian() {\n    //     kinematic_state_ = move_group_.getCurrentState();\n    //     kinematic_state_->getJacobian(kinematic_state_->getJointModelGroup(\"panda_arm\"),\n    //                            kinematic_state_->getLinkModel(kinematic_state_->getJointModelGroup(\"panda_arm\")->getLinkModelNames().back()),\n    //                            reference_point_position_, jacobian_);\n    //     return jacobian_;\n    // }\n    Eigen::MatrixXd jacobian() {\n        kinematic_state_ = move_group_.getCurrentState();\n        // ROS_INFO_STREAM(kinematic_state_->getJointModelGroup(\"panda_arm\")->getLinkModelNames().back());\n        return kinematic_state_->getJacobian(kinematic_state_->getJointModelGroup(\"panda_arm\"));\n    }\n    bool Move(const Eigen::Matrix<double, 7, 1>& joint_v) {\n        joint_position_ = move_group_.getCurrentJointValues();\n        for (int i=0; i<7; i++) {\n            joint_position_.at(i) += joint_v(i, 0);\n        }\n        move_group_.setStartStateToCurrentState();\n        move_group_.setJointValueTarget(joint_position_);\n        move_group_.move();\n    }\n    bool Move(const Eigen::Transform<double, 3, Eigen::Isometry>& pose) {\n        move_group_.setStartStateToCurrentState();\n        move_group_.setPoseTarget(pose);\n        move_group_.move();\n    }\nprivate:\n    ros::NodeHandle nh_;\n    std::string planning_group_;\n    moveit::planning_interface::MoveGroupInterface move_group_;\n    robot_state::RobotStatePtr kinematic_state_;\n    Eigen::Vector3d reference_point_position_;\n    Eigen::MatrixXd jacobian_;\n    std::vector<double> joint_position_;\n\n    geometry_msgs::PoseStamped pose_msg_;\n    Eigen::Transform<double, 3, Eigen::Isometry> pose_eg_;\n};\n\nclass VisualServoing {\npublic:\n    VisualServoing(ros::NodeHandle& nh):nh_(nh), robot_(nh) {\n        eMc_ = Eigen::Transform<double, 3, Eigen::Isometry>::Identity();\n        Eigen::Matrix<double, 3, 3> rot;\n        rot << 0.0, 1.0, 0.0,\n                -1.0, 0.0, 0.0,\n                0.0, 0.0, 1.0;\n        eMc_.rotate(Eigen::Quaterniond(rot));\n        eMc_.pretranslate(Eigen::Vector3d(0.0, 0.0, 0.02));\n\n        cdMo_ = Eigen::Transform<double, 3, Eigen::Isometry>::Identity();\n        rot << -1.0, 0.0, 0.0,\n                0.0, -1.0, 0.0,\n                0.0, 0.0, 1.0;\n        cdMo_.rotate(Eigen::Quaterniond(rot));\n        cdMo_.pretranslate(Eigen::Vector3d(0.1112315, 0.21367, 0.7107));\n\n        cVe_ = Eigen::Matrix<double, 6, 6>::Zero();\n        Eigen::Transform<double, 3, Eigen::Isometry> cMe = eMc_.inverse();\n        Eigen::Matrix<double, 3, 3> t_skew;\n        t_skew << 0, -cMe.matrix()(2, 3), cMe.matrix()(1, 3),\n              cMe.matrix()(2, 3), 0, -cMe.matrix()(0, 3),\n              -cMe.matrix()(1, 3), cMe.matrix()(0, 3), 0;\n        Eigen::Matrix<double, 3, 3> r(cMe.matrix().block<3, 3>(0, 0));\n        Eigen::Matrix<double, 3, 3> t_r = t_skew * r;\n        for (unsigned int i = 0; i < 3; i++) {\n            for (unsigned int j = 0; j < 3; j++) {\n                cVe_(i, j) = r(i, j);\n                cVe_(i+3, j+3) = r(i, j);\n                cVe_(i, j+3) = t_r(i, j);\n            }\n        }\n\n        pbvs_.Init();\n        pid_.Init();\n        cMo_sub_ = nh_.subscribe(\"board/pose\", 1, &VisualServoing::CalibPoseCallback, this);\n    }\n    ~VisualServoing() {}\n    void CalibPoseCallback(const geometry_msgs::PoseStamped& cMo_msg) {\n        // std::unique_lock<std::mutex> locker(mutex_);\n        Eigen::Transform<double, 3, Eigen::Isometry> cMo = Eigen::Transform<double, 3, Eigen::Isometry>::Identity();\n        cMo.rotate(Eigen::Quaterniond(cMo_msg.pose.orientation.w, cMo_msg.pose.orientation.x, cMo_msg.pose.orientation.y, cMo_msg.pose.orientation.z));\n        cMo.pretranslate(Eigen::Vector3d(cMo_msg.pose.position.x, cMo_msg.pose.position.y, cMo_msg.pose.position.z));\n        // ROS_INFO_STREAM(\"cMo: \" << cMo.matrix());\n        // locker.unlock();\n        mutex_.lock();\n        cMo_ = cMo;\n        mutex_.unlock();\n    }\n    void RunVisp() {\n        Eigen::Transform<double, 3, Eigen::Isometry> cMo;\n        mutex_.lock();\n        cMo = cMo_;\n        mutex_.unlock();\n        if (pbvs_.Calc(cMo, cart_v_)) {\n            ROS_INFO_STREAM(\"motion_finished\");\n            return;\n        }\n        ROS_INFO_STREAM(\"pbvs_ cart_v_:\" << cart_v_*10);\n        jacobian_ = robot_.jacobian();\n        Eigen::Matrix<double, 6, 1> cart_v;\n        // cart_v << cart_v_(1, 0), cart_v_(0, 0), -cart_v_(2, 0), cart_v_(4, 0), cart_v_(3, 0), -cart_v_(5, 0);\n        cart_v << cart_v_(1, 0), cart_v_(0, 0), -cart_v_(2, 0), cart_v_(4, 0), cart_v_(3, 0), -cart_v_(5, 0);\n        Eigen::Matrix<double, 7, 1> q_dot = jacobian_.transpose() * (jacobian_ * jacobian_.transpose()).inverse() * cart_v;\n        // robot_.Move(q_dot);\n    }\n    void RunPid() {\n        Eigen::Transform<double, 3, Eigen::Isometry> cMo;\n        mutex_.lock();\n        cMo = cMo_;\n        mutex_.unlock();\n        pid_.Calc(cMo, cart_v_);\n        ROS_INFO_STREAM(\"pid_ cart_v_:\" << cart_v_*10);\n        jacobian_ = robot_.jacobian();\n        Eigen::Matrix<double, 6, 1> cart_v;\n        cart_v << cart_v_(1, 0), cart_v_(0, 0), cart_v_(2, 0), cart_v_(4, 0), cart_v_(3, 0), cart_v_(5, 0);\n        sleep(1);\n        Eigen::Matrix<double, 7, 1> q_dot = jacobian_.transpose() * (jacobian_ * jacobian_.transpose()).inverse() * cart_v;\n        // robot_.Move(q_dot);\n    }\n    void RunPid2o() {\n        jacobian_ = robot_.jacobian();\n        Eigen::Matrix<double, 3, 3> eRb = robot_.bMe().inverse().matrix().block<3, 3>(0, 0);\n        Eigen::Matrix<double, 6, 6> eVb = Eigen::Matrix<double, 6, 6>::Zero();\n        for(int i=0; i<3; i++) {\n            for (int j = 0; j < 3; j++) {\n                eVb(i, j) = eRb(i, j);\n                eVb(i+3, j+3) = eRb(i, j);\n            }\n        }\n        Eigen::MatrixXd eJe = eVb * jacobian_;\n        Eigen::Transform<double, 3, Eigen::Isometry> cMo;\n        mutex_.lock();\n        cMo = cMo_;\n        mutex_.unlock();\n        pid_.Calc2o(cMo, cart_v_);\n        ROS_INFO_STREAM(\"pid_ Calc2o cart_v_:\" << cart_v_*10);\n        // pid_.Calc(cMo, cart_v_);\n        // ROS_INFO_STREAM(\"pid_ Calc cart_v_:\" << cart_v_*10);\n        // pbvs_.Calc(cMo, cart_v_);\n        // ROS_INFO_STREAM(\"pbvs_ Calc cart_v_:\" << cart_v_*10);\n        Eigen::Matrix<double, 6, 1> cart_v;\n        cart_v << cart_v_(1, 0), -cart_v_(0, 0), cart_v_(2, 0), cart_v_(4, 0), -cart_v_(3, 0), cart_v_(5, 0);\n        // sleep(1);\n        Eigen::Matrix<double, 7, 1> q_dot = eJe.transpose() * (eJe * eJe.transpose()).inverse() * cVe_.inverse() * cart_v_;\n        robot_.Move(q_dot);\n    }\n    void RunPidPose() {\n        Eigen::Transform<double, 3, Eigen::Isometry> cMo;\n        mutex_.lock();\n        cMo = cMo_;\n        mutex_.unlock();\n        Eigen::Transform<double, 3, Eigen::Isometry> cMo_next;\n        pid_.Calc(cMo, cMo_next);\n        Eigen::Transform<double, 3, Eigen::Isometry> bMo = robot_.bMe() * eMc_ * cMo;\n        Eigen::Transform<double, 3, Eigen::Isometry> bMe_next = bMo * cMo_next.inverse()*eMc_.inverse();\n        robot_.Move(bMe_next);\n    }\n    void Run() {\n        jacobian_ = robot_.jacobian();\n        Eigen::Matrix<double, 3, 3> eRb = robot_.bMe().inverse().matrix().block<3, 3>(0, 0);\n        Eigen::Matrix<double, 6, 6> eVb = Eigen::Matrix<double, 6, 6>::Zero();\n        for(int i=0; i<3; i++) {\n            for (int j = 0; j < 3; j++) {\n                eVb(i, j) = eRb(i, j);\n                eVb(i+3, j+3) = eRb(i, j);\n            }\n        }\n        Eigen::MatrixXd eJe = eVb * jacobian_;\n        Eigen::Matrix<double, 6, 1> cart_v;\n        cart_v << 0, 0, 0, 0.01, 0.01, 0;\n        sleep(1);\n        Eigen::Matrix<double, 7, 1> q_dot = eJe.transpose() * (eJe * eJe.transpose()).inverse() * cVe_.inverse() * cart_v;\n        robot_.Move(q_dot);\n    }\nprivate:\n    ros::NodeHandle nh_;\n    ros::Subscriber cMo_sub_;\n    Robot robot_;\n    SE3Pid pid_;\n    PBVS pbvs_;\n    Eigen::Transform<double, 3, Eigen::Isometry> bMe_;\n    Eigen::Transform<double, 3, Eigen::Isometry> bMc_;\n    Eigen::Transform<double, 3, Eigen::Isometry> eMc_;\n    Eigen::Transform<double, 3, Eigen::Isometry> bMcd_;\n    Eigen::Transform<double, 3, Eigen::Isometry> cdMo_;\n    // std::atomic<Eigen::Transform<double, 3, Eigen::Isometry>> cMo_;\n    Eigen::Transform<double, 3, Eigen::Isometry> cMo_;\n    Eigen::Matrix<double, 6, 1> cart_v_;\n    Eigen::MatrixXd jacobian_;\n    Eigen::Matrix<double, 6, 6> cVe_;\n    std::mutex mutex_;\n};\n\nint main(int argc, char** argv) {\n    ros::init(argc, argv, \"panda_visual_servoing\");\n    ros::NodeHandle nh;\n    ros::AsyncSpinner spinner(4);\n    spinner.start();\n    ROS_INFO(\"hello panda_visual_servoing\");\n\n    VisualServoing vs(nh);\n    while(1) {\n        // vs.RunVisp();\n        // vs.RunPid();\n        vs.RunPid2o();\n        // vs.RunPidPose();\n        // vs.Run();\n    }\n\n    // ros::waitForShutdown();\n    return 0;\n}", "meta": {"hexsha": "7207e5b444907e7ecc1ebe7d9717af84654c70a2", "size": 16906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/panda_visual_servoing.cpp", "max_stars_repo_name": "NodYoung/panda_simulation", "max_stars_repo_head_hexsha": "b09bb7f52621f9648740f1c95f0ceb3b83c30725", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/panda_visual_servoing.cpp", "max_issues_repo_name": "NodYoung/panda_simulation", "max_issues_repo_head_hexsha": "b09bb7f52621f9648740f1c95f0ceb3b83c30725", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/panda_visual_servoing.cpp", "max_forks_repo_name": "NodYoung/panda_simulation", "max_forks_repo_head_hexsha": "b09bb7f52621f9648740f1c95f0ceb3b83c30725", "max_forks_repo_licenses": ["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.2032085561, "max_line_length": 161, "alphanum_fraction": 0.5914468236, "num_tokens": 5404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5559395755170938}}
{"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": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <cmath>\n#include <cfloat>\n#include <cstdint>\n#include <limits>\n#include <type_traits>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n#include <boost/math/ccmath/fmod.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\n#if !defined(BOOST_MATH_NO_CONSTEXPR_DETECTION) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\ntemplate <typename T>\nconstexpr void test()\n{\n    // Error Handling\n    if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    {\n        static_assert(boost::math::ccmath::isnan(boost::math::ccmath::fmod(std::numeric_limits<T>::quiet_NaN(), T(1))), \"If x is NaN, NaN is returned\");\n        static_assert(boost::math::ccmath::isnan(boost::math::ccmath::fmod(T(1), std::numeric_limits<T>::quiet_NaN())), \"If y is NaN, NaN is returned\");\n    }\n\n    static_assert(boost::math::ccmath::fmod(T(0), T(1.0)) == 0);\n    static_assert(boost::math::ccmath::fmod(T(-0), T(1.0)) == -0);\n    static_assert(boost::math::ccmath::isnan(boost::math::ccmath::fmod(std::numeric_limits<T>::infinity(), T(1.0))));\n    static_assert(boost::math::ccmath::isnan(boost::math::ccmath::fmod(-std::numeric_limits<T>::infinity(), T(1.0))));\n\n    static_assert(boost::math::ccmath::isnan(boost::math::ccmath::fmod(T(1), T(0))));\n    static_assert(boost::math::ccmath::isnan(boost::math::ccmath::fmod(T(1), T(-0))));\n    static_assert(boost::math::ccmath::fmod(T(1), std::numeric_limits<T>::infinity()) == T(1));\n    static_assert(boost::math::ccmath::fmod(T(1), -std::numeric_limits<T>::infinity()) == T(1));\n\n    // Functionality\n    static_assert(boost::math::ccmath::fmod(T(3.0/2), T(1.0) == T(3.0/2)));\n    static_assert(boost::math::ccmath::fmod(T(7.0/3), T(2.0) == T(1.0/3)));\n    static_assert(boost::math::ccmath::fmod(T(-8.0/3), T(2.0) == T(-2.0/3)));\n\n    // Correct promoted types\n    if constexpr (!std::is_same_v<T, float>)\n    {\n        constexpr auto test_type = boost::math::ccmath::fmod(T(1), 1.0f);\n        static_assert(std::is_same_v<T, std::remove_cv_t<decltype(test_type)>>);\n    }\n    else\n    {\n        constexpr auto test_type = boost::math::ccmath::fmod(1.0f, 1);\n        static_assert(std::is_same_v<double, std::remove_cv_t<decltype(test_type)>>);\n    }\n}\n\nint main()\n{\n    test<float>();\n    test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test<long double>();\n    #endif\n    \n    #ifdef BOOST_HAS_FLOAT128\n    test<boost::multiprecision::float128>();\n    #endif\n\n    return 0;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "83f9e505326de2f2e0cfabaf8cdb93cdaed908d5", "size": 2819, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/math/test/ccmath_fmod_test.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/math/test/ccmath_fmod_test.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "console/src/boost_1_78_0/libs/math/test/ccmath_fmod_test.cpp", "max_forks_repo_name": "vany152/FilesHash", "max_forks_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 35.2375, "max_line_length": 152, "alphanum_fraction": 0.6647747428, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5559395673398241}}
{"text": "/**\n*\n* @file\n*\n* @brief  Mixer test\n*\n* @author vitamin.caig@gmail.com\n*\n**/\n\n#include <error_tools.h>\n#include <math/numeric.h>\n#include <sound/matrix_mixer.h>\n#include <sound/mixer_parameters.h>\n\n#include <iostream>\n#include <iomanip>\n\n#include <boost/range/size.hpp>\n\n#define FILE_TAG 25E829A2\n\nnamespace Sound\n{\n  //BOOST_STATIC_ASSERT(SAMPLE_MIN == 0 && SAMPLE_MID == 32768 && SAMPLE_MAX == 65535);\n\n  const int_t THRESHOLD = 5 * (Sample::MAX - Sample::MIN) / 1000;//0.5%\n\n  Gain CreateGain(double l, double r)\n  {\n    return Gain(Gain::Type(l), Gain::Type(r));\n  }\n  \n  const Gain GAINS[] = {\n    CreateGain(0.0, 0.0),\n    CreateGain(1.0, 1.0),\n    CreateGain(1.0, 0.0),\n    CreateGain(0.0, 1.0),\n    CreateGain(0.5, 0.5),\n    CreateGain(0.1, 0.9)\n  };\n  \n  const String GAIN_NAMES[] = {\n    \"empty\", \"full\", \"left\", \"right\", \"middle\", \"-10dB,-0.45dB\"\n  };\n  \n  const Gain INVALID_GAIN = CreateGain(2.0, 3.0);\n\n  const Sample::Type INPUTS[] = {\n    Sample::MIN,\n    Sample::MID,\n    Sample::MAX\n  };\n  \n  const String INPUT_NAMES[] = {\n    \"min\", \"mid\", \"max\"\n  };\n\n  \n  const Sample OUTS[] = {\n  //zero matrix\n     Sample(Sample::MID, Sample::MID),\n     Sample(Sample::MID, Sample::MID),\n     Sample(Sample::MID, Sample::MID),\n  //full matrix\n     Sample(Sample::MIN, Sample::MIN),\n     Sample(Sample::MID, Sample::MID),\n     Sample(Sample::MAX, Sample::MAX),\n  //left matrix\n     Sample(Sample::MIN, Sample::MID),\n     Sample(Sample::MID, Sample::MID),\n     Sample(Sample::MAX, Sample::MID),\n  //right matrix\n     Sample(Sample::MID, Sample::MIN),\n     Sample(Sample::MID, Sample::MID),\n     Sample(Sample::MID, Sample::MAX),\n  //mid matrix\n     Sample((Sample::MID+Sample::MIN)/2, (Sample::MID+Sample::MIN)/2),\n     Sample(Sample::MID, Sample::MID),\n     Sample((Sample::MID+Sample::MAX)/2, (Sample::MID+Sample::MAX)/2),\n  //balanced\n     //left=25 right=230\n     //(25*32768)/256, (230*32768)/256\n     //(25*65535)/256, (230*65535)/256\n     Sample(Sample::MID+(int_t(Sample::MIN)-Sample::MID)/10, Sample::MID+9*(int_t(Sample::MIN)-Sample::MID)/10),\n     Sample(Sample::MID, Sample::MID),\n     Sample(Sample::MID+(int_t(Sample::MAX)-Sample::MID)/10, Sample::MID+9*(int_t(Sample::MAX)-Sample::MID)/10),\n  };\n\n  template<class Res>\n  typename Res::Type MakeSample(Sample::Type in)\n  {\n    typename Res::Type res;\n    res.assign(in);\n    return res;\n  }\n\n  template<unsigned Channels>\n  typename FixedChannelsMatrixMixer<Channels>::Matrix MakeMatrix(const Gain& mg)\n  {\n    typename FixedChannelsMatrixMixer<Channels>::Matrix res;\n    res.assign(mg);\n    return res;\n  }\n\n  bool ShowIfError(const Error& e)\n  {\n    if (e)\n    {\n      std::cerr << e.ToString();\n    }\n    return e;\n  }\n\n  bool Check(Sample::Type data, Sample::Type ref)\n  {\n    return Math::Absolute(int_t(data) - ref) <= THRESHOLD;\n  }\n\n  void Check(const Sample& data, const Sample& ref)\n  {\n    if (Check(data.Left(), ref.Left()) && Check(data.Right(), ref.Right()))\n    {\n      std::cout << \" passed\\n\";\n    }\n    else\n    {\n      std::cout << \" failed\\n\";\n      throw MakeFormattedError(THIS_LINE, \"Value=<%1%,%2%> while expected=<%3%,%4%>\",\n        data.Left(), data.Right(), ref.Left(), ref.Right());\n    }\n  }\n\n  template<unsigned Channels>\n  void TestMixer()\n  {\n    std::cout << \"**** Testing for \" << Channels << \" channels ****\\n\";\n \n    const typename FixedChannelsMatrixMixer<Channels>::Ptr mixer = FixedChannelsMatrixMixer<Channels>::Create();\n    \n    std::cout << \"--- Test for invalid matrix---\\n\";\n    try\n    {\n      mixer->SetMatrix(MakeMatrix<Channels>(INVALID_GAIN));\n      throw \"Failed\";\n    }\n    catch (const Error& e)\n    {\n      std::cout << \" Passed\\n\";\n      std::cerr << e.ToString();\n    }\n    catch (const std::string& str)\n    {\n      throw Error(THIS_LINE, str);\n    }\n    \n    assert(boost::size(OUTS) == boost::size(GAINS) * boost::size(INPUTS));\n    assert(boost::size(GAINS) == boost::size(GAIN_NAMES));\n    assert(boost::size(INPUTS) == boost::size(INPUT_NAMES));\n    \n    const Sample* result(OUTS);\n    for (unsigned matrix = 0; matrix != boost::size(GAINS); ++matrix)\n    {\n      std::cout << \"--- Test for \" << GAIN_NAMES[matrix] << \" matrix ---\\n\";\n      mixer->SetMatrix(MakeMatrix<Channels>(GAINS[matrix]));\n      for (unsigned input = 0; input != boost::size(INPUTS); ++input, ++result)\n      {\n        std::cout << \"Checking for \" << INPUT_NAMES[input] << \" input: \";\n        Check(mixer->ApplyData(MakeSample<MultichannelSample<Channels> >(INPUTS[input])), *result);\n      }\n    }\n    std::cout << \"Parameters:\" << std::endl;\n    for (uint_t inChan = 0; inChan != Channels; ++inChan)\n    {\n      for (uint_t outChan = 0; outChan != Sample::CHANNELS; ++outChan)\n      {\n        const Parameters::NameType name = Parameters::ZXTune::Sound::Mixer::LEVEL(Channels, inChan, outChan);\n        const Parameters::IntType val = Parameters::ZXTune::Sound::Mixer::LEVEL_DEFAULT(Channels, inChan, outChan);\n        std::cout << name.FullPath() << \": \" << val << std::endl;\n      }\n    }\n  }\n}\n\nint main()\n{\n  using namespace Sound;\n  try\n  {\n    TestMixer<1>();\n    TestMixer<2>();\n    TestMixer<3>();\n    TestMixer<4>();\n    std::cout << \" Succeed!\" << std::endl;\n  }\n  catch (const Error& e)\n  {\n    std::cerr << e.ToString();\n    return 1;\n  }\n}\n", "meta": {"hexsha": "1091930b0f651455dd4b2769d2c20fc6c17f3bfd", "size": 5261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/train/cpp/1091930b0f651455dd4b2769d2c20fc6c17f3bfdtest.cpp", "max_stars_repo_name": "harshp8l/deep-learning-lang-detection", "max_stars_repo_head_hexsha": "2a54293181c1c2b1a2b840ddee4d4d80177efb33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 84.0, "max_stars_repo_stars_event_min_datetime": "2017-10-25T15:49:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T21:25:54.000Z", "max_issues_repo_path": "data/train/cpp/1091930b0f651455dd4b2769d2c20fc6c17f3bfdtest.cpp", "max_issues_repo_name": "vassalos/deep-learning-lang-detection", "max_issues_repo_head_hexsha": "cbb00b3e81bed3a64553f9c6aa6138b2511e544e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-03-29T11:50:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T13:33:18.000Z", "max_forks_repo_path": "data/train/cpp/1091930b0f651455dd4b2769d2c20fc6c17f3bfdtest.cpp", "max_forks_repo_name": "vassalos/deep-learning-lang-detection", "max_forks_repo_head_hexsha": "cbb00b3e81bed3a64553f9c6aa6138b2511e544e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2017-11-22T08:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T01:22:31.000Z", "avg_line_length": 26.0445544554, "max_line_length": 115, "alphanum_fraction": 0.5945637711, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5559395617962493}}
{"text": "/** @file\n *\n *  Definition of the LikelihoodField class.\n */\n\n#include \"grid_map_lf/LikelihoodField.h\"\n\n#include <grid_map_core/GridMapMath.hpp>\n\n#include <boost/math/distributions/normal.hpp>\n#include <cmath>\n\nnamespace grid_map {\n\nvoid LikelihoodField::setData(const grid_map::GridMap& grid_map, const std::string layer)\n{\n  data_ = grid_map[layer];\n  size_ = grid_map.getSize();\n  length_ = grid_map.getLength();\n  position_ = grid_map.getPosition();\n  resolution_ = grid_map.getResolution();\n}\n\nconst Matrix& LikelihoodField::getData() const\n{\n  return data_;\n}\n\nvoid LikelihoodField::calculateLikelihoodField(const GridMap& gridMap,\n                                               const std::string layer,\n                                               const double sigma)\n{\n  if(sigma == 0)\n  {\n    throw std::domain_error(\"Standard deviation of 0 is not allowed\");\n  }\n\n  boost::math::normal_distribution<double> normalDistribution(0, sigma);\n  double normalization = pdf(normalDistribution, 0);\n\n  // set properties\n  resolution_ = gridMap.getResolution();\n  size_ = gridMap.getSize();\n  length_ = gridMap.getLength();\n  position_ = gridMap.getPosition();\n\n  // Size the Matrix and set to zero\n  data_.resize(size_(0), size_(1));\n  data_.setZero();\n\n  const auto& data = gridMap[layer];\n\n  for (std::size_t i = 0; i < size_(0); ++i)\n  {\n    for (std::size_t j = 0; j < size_(1); ++j)\n    {\n      // if unknown, set likelihood to 0.5\n      if(std::isnan(data(i, j)))\n      {\n        data_(i, j) = 0.5;\n      }\n      else\n      {\n        data_(i, j) = pdf(normalDistribution, data(i, j))/normalization;\n      }\n    }\n  }\n}\n\ndouble LikelihoodField::getLikelihoodAt(const Vector& position) const\n{\n  double xCenter = size_.x() / 2.0;\n  double yCenter = size_.y() / 2.0;\n  int i = std::round(xCenter - (position.x() - position_.x()) / resolution_);\n  int j = std::round(yCenter - (position.y() - position_.y()) / resolution_);\n  i = std::max(i, 0);\n  i = std::min(i, size_.x() - 1);\n  j = std::max(j, 0);\n  j = std::min(j, size_.y() - 1);\n\n  return data_(i, j);\n}\n\nstd::ostream& operator<< (std::ostream& out, const LikelihoodField& in)\n{\n  out << in.data_ << std::endl;\n  return out;\n}\n\n} // namespace grid_map\n\n", "meta": {"hexsha": "328bf00ae7a42c172f6aea5933da5415b4280e3c", "size": 2216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grid_map_lf/src/LikelihoodField.cpp", "max_stars_repo_name": "BeatScherrer/grid_map", "max_stars_repo_head_hexsha": "9a6ba1ef494cd3c5bbd9c0f050653bc50f758ecf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grid_map_lf/src/LikelihoodField.cpp", "max_issues_repo_name": "BeatScherrer/grid_map", "max_issues_repo_head_hexsha": "9a6ba1ef494cd3c5bbd9c0f050653bc50f758ecf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_lf/src/LikelihoodField.cpp", "max_forks_repo_name": "BeatScherrer/grid_map", "max_forks_repo_head_hexsha": "9a6ba1ef494cd3c5bbd9c0f050653bc50f758ecf", "max_forks_repo_licenses": ["BSD-3-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.0869565217, "max_line_length": 89, "alphanum_fraction": 0.6204873646, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5559395617041873}}
{"text": "#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/quote.hpp>\n#include <boost/mpl/protect.hpp>\n#include <boost/mpl/bind.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <limits>\n\n\n#include <cmath>\n#include <boost/safe_float.hpp>\n#include <boost/safe_float/convenience.hpp>\n#include <boost/safe_float/policy/check_addition_overflow.hpp>\n#include <boost/safe_float/policy/check_addition_underflow.hpp>\n#include <boost/safe_float/policy/check_addition_inexact.hpp>\n#include <boost/safe_float/policy/check_addition_invalid_result.hpp>\n\n//types to be tested\nusing test_types=boost::mpl::list<\n    float, double, long double\n>;\n\nusing namespace boost::safe_float;\n\n/**\n  This test suite checks different policies on addition operations using default parameters for the other policies.\n  */\nBOOST_AUTO_TEST_SUITE( safe_float_addition_test_suite )\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_addition_throws_on_overflow, FPT, test_types){\n    // define two FPT numbers suppose to positive overflow\n    FPT a = std::numeric_limits<FPT>::max();\n    FPT b = std::numeric_limits<FPT>::max();\n    // check FPT overflows to inf after add\n    BOOST_CHECK(std::isinf(a+b));\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_addition_overflow> c(std::numeric_limits<FPT>::max());\n    safe_float<FPT, policy::check_addition_overflow> d(std::numeric_limits<FPT>::max());\n\n    // check the addition throws\n    BOOST_CHECK_THROW(c+d, std::exception);\n\n    // define two FPT numbers suppose to negative overflow\n    FPT e = std::numeric_limits<FPT>::lowest();\n    FPT f = std::numeric_limits<FPT>::lowest();\n    // check FPT overflows to inf after add\n    BOOST_CHECK(std::isinf(e+f));\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_addition_overflow> g(std::numeric_limits<FPT>::lowest());\n    safe_float<FPT, policy::check_addition_overflow> h(std::numeric_limits<FPT>::lowest());\n\n    // check the addition throws\n    BOOST_CHECK_THROW(g+h, std::exception);\n\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_addition_inexact_rounding, FPT, test_types){\n    // define two FPT numbers suppose to produce an inexact rounded result\n    FPT a = 1;\n    FPT b = pow(2, std::numeric_limits<FPT>::digits);\n\n    // check adding and substracting b does not obtain a again.\n    BOOST_CHECK(a+b-b != a);\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_addition_inexact> c(FPT(1));\n    safe_float<FPT, policy::check_addition_inexact> d((FPT)pow(2, std::numeric_limits<FPT>::digits));\n\n    // check the addition throws\n    BOOST_CHECK_THROW(c+d, std::exception);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_addition_underflow, FPT, test_types){\n    // define two FPT numbers suppose to underflow\n    FPT a, b, c;\n    if(std::is_same<FPT, float>()) {\n        a =  4.01254977e-38f;\n        b = -4.01254949e-38f;\n\n        BOOST_CHECK(std::isnormal(a));\n        BOOST_CHECK(std::isnormal(b));\n\n        //check the addition produces an denormal result (considered underflow)\n        c = a + b;\n        BOOST_CHECK( std::fpclassify( c ) == FP_SUBNORMAL ) ;\n\n        // construct safe_float version of the same two numbers\n        safe_float<FPT, policy::check_addition_underflow> d(a);\n        safe_float<FPT, policy::check_addition_underflow> e(b);\n\n        // check the addition throws\n        BOOST_CHECK_THROW(d+e, std::exception);\n    } else if (std::is_same<FPT, double>()) {\n        a =  2.2250738585072019e-308;\n        b = -2.2250738585072014e-308;\n        \n        BOOST_CHECK(std::isnormal(a));\n        BOOST_CHECK(std::isnormal(b));\n        \n        //check the addition produces an denormal result (considered underflow)\n        c = a + b;\n        BOOST_CHECK( std::fpclassify( c ) == FP_SUBNORMAL ) ;\n\n        // construct safe_float version of the same two numbers\n        safe_float<FPT, policy::check_addition_underflow> d(a);\n        safe_float<FPT, policy::check_addition_underflow> e(b);\n\n        // check the addition throws\n        BOOST_CHECK_THROW(d+e, std::exception);\n    } else if(std::is_same<FPT, long double>()) {\n        a =  3.40132972460942461217e-4932l;\n        b = -3.40132972460942461181e-4932l;\n\n        BOOST_CHECK(std::isnormal(a));\n        BOOST_CHECK(std::isnormal(b));\n\n        //check the addition produces an denormal result (considered underflow)\n        c = a + b;\n        BOOST_CHECK( std::fpclassify( c ) == FP_SUBNORMAL ) ;\n\n        // construct safe_float version of the same two numbers\n        safe_float<FPT, policy::check_addition_underflow> d(a);\n        safe_float<FPT, policy::check_addition_underflow> e(b);\n\n        // check the addition throws\n        BOOST_CHECK_THROW(d+e, std::exception);\n    } else {\n        BOOST_ERROR(\"underflow test only implemented for, float, double and long double\");\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_addition_invalid_result, FPT, test_types){\n    // define two FPT numbers suppose to produce a NAN\n    FPT a = std::numeric_limits<FPT>::infinity();\n    FPT b = -(std::numeric_limits<FPT>::infinity());\n\n    // check adding produced NaN\n    BOOST_CHECK(std::isnan(a+b));\n\n    // construct safe_float version of the same two numbers\n    safe_float<FPT, policy::check_addition_invalid_result> c(std::numeric_limits<FPT>::infinity());\n    safe_float<FPT, policy::check_addition_invalid_result> d(-(std::numeric_limits<FPT>::infinity()));\n\n    // check the addition throws\n    BOOST_CHECK_THROW(c+d, std::exception);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n", "meta": {"hexsha": "5003c8b76f6d6bb2cdbe7be6227403370be9bfd7", "size": 5638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/safe_float_addition_test.cpp", "max_stars_repo_name": "aTom3333/safefloat", "max_stars_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-08T01:24:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-08T01:24:16.000Z", "max_issues_repo_path": "test/safe_float_addition_test.cpp", "max_issues_repo_name": "aTom3333/safefloat", "max_issues_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/safe_float_addition_test.cpp", "max_forks_repo_name": "aTom3333/safefloat", "max_forks_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T11:31:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-12T21:55:25.000Z", "avg_line_length": 35.6835443038, "max_line_length": 115, "alphanum_fraction": 0.6961688542, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5559395562526743}}
{"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": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm accumulator mean\n#include <boost/test/unit_test.hpp>\n#include \"fern/algorithm/accumulator/mean.h\"\n\n\nnamespace faa = fern::algorithm::accumulator;\n\nBOOST_AUTO_TEST_CASE(default_construct)\n{\n    faa::Mean<int> mean;\n    // Don't calculate the mean. Division by zero.\n}\n\n\nBOOST_AUTO_TEST_CASE(accumulate)\n{\n    {\n        faa::Mean<int> mean(5);\n        BOOST_CHECK_EQUAL(mean(), 5);\n\n        mean(2);\n        BOOST_CHECK_EQUAL(mean(), 7 / 2u);\n\n        mean = 3;\n        BOOST_CHECK_EQUAL(mean(), 3);\n    }\n\n    {\n        faa::Mean<int, double> mean(5);\n        BOOST_CHECK_EQUAL(mean(), 5.0);\n\n        mean(2);\n        BOOST_CHECK_EQUAL(mean(), 3.5);\n\n        mean = 3;\n        BOOST_CHECK_EQUAL(mean(), 3.0);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(merge)\n{\n    {\n        auto mean(faa::Mean<int>(5) | faa::Mean<int>(15));\n        BOOST_CHECK_EQUAL(mean(), 10);\n    }\n\n    {\n        auto mean(faa::Mean<int, double>(5) | faa::Mean<int, double>(20));\n        BOOST_CHECK_EQUAL(mean(), 12.5);\n    }\n}\n", "meta": {"hexsha": "cefed0667ce139e8c59e9b8929ac7cf2a5646e97", "size": 1491, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/accumulator/test/mean_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/accumulator/test/mean_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/accumulator/test/mean_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4426229508, "max_line_length": 80, "alphanum_fraction": 0.5519785379, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5559351838523223}}
{"text": "/**\n * Copyright 2020, Massachusetts Institute of Technology,\n * Cambridge, MA 02139\n * All Rights Reserved\n * Authors: Jingnan Shi, et al. (see THANKS for the full author list)\n * See LICENSE for the license information\n */\n\n#include \"gtest/gtest.h\"\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <chrono>\n\n#include <Eigen/Eigenvalues>\n\n#include \"teaser/registration.h\"\n#include \"test_utils.h\"\n\nTEST(TranslationTest, TLSTranslation) {\n  // Problem 1: Zero translation\n  {\n    std::ifstream objectFile(\"./data/registration_test/translation_test_v1_inliers.csv\");\n    auto object_points = teaser::test::readFileToEigenMatrix<float, 3, Eigen::Dynamic>(objectFile);\n\n    // Parameters for estimating translation\n    float noise_bound = 0.025; // arbitrary\n    float cbar2 = 1;\n\n    // Estimating translation\n    Eigen::Vector3f actual_t;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> actual_inliers;\n    actual_inliers.resize(1, object_points.cols());\n    teaser::TLSTranslationSolver translationSolver(noise_bound, cbar2);\n    // Pass the same vector of points b/c we are testing for zero translation\n    translationSolver.solveForTranslation(object_points, object_points, &actual_t, &actual_inliers);\n\n    // Expected\n    Eigen::Vector3f expected_t = Eigen::Vector3f::Zero();\n    EXPECT_TRUE((actual_t - expected_t).norm() < 1e-5);\n  }\n  // Problem 2: Translation in x / y / z only\n  {\n    std::ifstream objectFile(\"./data/registration_test/translation_test_v1_inliers.csv\");\n    auto object_points = teaser::test::readFileToEigenMatrix<float, 3, Eigen::Dynamic>(objectFile);\n\n    // Parameters for estimating translation\n    float noise_bound = 0.025; // arbitrary\n    float cbar2 = 1;\n\n    // Estimating translation\n    // 1. in x only\n    Eigen::Matrix<float, 3, Eigen::Dynamic> translated_points = object_points;\n    translated_points.row(0).array() += 1;\n    Eigen::Vector3f actual_t;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> actual_inliers;\n    actual_inliers.resize(1, object_points.cols());\n    teaser::TLSTranslationSolver translationSolver(noise_bound, cbar2);\n    translationSolver.solveForTranslation(object_points, translated_points, &actual_t,\n                                          &actual_inliers);\n\n    // Expected\n    Eigen::Vector3f expected_t;\n    expected_t << 1, 0, 0;\n    EXPECT_TRUE((actual_t - expected_t).norm() < 1e-5);\n\n    // 2. in y only\n    translated_points = object_points;\n    translated_points.row(1).array() += 1;\n    translationSolver.solveForTranslation(object_points, translated_points, &actual_t,\n                                          &actual_inliers);\n\n    // Expected\n    expected_t << 0, 1, 0;\n    EXPECT_TRUE((actual_t - expected_t).norm() < 1e-5);\n\n    // 3. in z only\n    translated_points = object_points;\n    translated_points.row(2).array() += 1;\n    translationSolver.solveForTranslation(object_points, translated_points, &actual_t,\n                                          &actual_inliers);\n\n    // Expected\n    expected_t << 0, 0, 1;\n    EXPECT_TRUE((actual_t - expected_t).norm() < 1e-5);\n  }\n  // Problem 3: An arbitrary translation\n  {\n    // Prepare input data\n    std::ifstream objectFile(\"./data/registration_test/translation_test_v1_inliers.csv\");\n    std::ifstream sceneFile(\"./data/registration_test/translation_test_v2_inliers.csv\");\n    auto object_points = teaser::test::readFileToEigenMatrix<float, 3, Eigen::Dynamic>(objectFile);\n    auto scene_points = teaser::test::readFileToEigenMatrix<float, 3, Eigen::Dynamic>(sceneFile);\n    EXPECT_EQ(object_points.cols(), scene_points.cols());\n\n    // Parameters for estimating translation\n    float noise_bound = 0.00673642835;\n    float cbar2 = 1;\n\n    // Estimating translation\n    Eigen::Vector3f actual_t;\n    Eigen::Matrix<bool, 1, Eigen::Dynamic> actual_inliers;\n    actual_inliers.resize(1, object_points.cols());\n    teaser::TLSTranslationSolver translationSolver(noise_bound, cbar2);\n    translationSolver.solveForTranslation(object_points, scene_points, &actual_t, &actual_inliers);\n\n    // Expected\n    Eigen::Vector3f expected_t;\n    expected_t << -0.098430131086161, 0.008679113091532, 0.197317864174211;\n    EXPECT_TRUE((actual_t - expected_t).norm() < 1e-5);\n  }\n}\n", "meta": {"hexsha": "bbaa1901b19dd8a246939222e6ad28cd96e5a88c", "size": 4216, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/teaser/translation-solver-test.cc", "max_stars_repo_name": "BEAMRobotics/TEASER-plusplus", "max_stars_repo_head_hexsha": "6367df1c06760472cefd80e666c67b8a4600fac6", "max_stars_repo_licenses": ["MIT"], "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/teaser/translation-solver-test.cc", "max_issues_repo_name": "BEAMRobotics/TEASER-plusplus", "max_issues_repo_head_hexsha": "6367df1c06760472cefd80e666c67b8a4600fac6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/teaser/translation-solver-test.cc", "max_forks_repo_name": "BEAMRobotics/TEASER-plusplus", "max_forks_repo_head_hexsha": "6367df1c06760472cefd80e666c67b8a4600fac6", "max_forks_repo_licenses": ["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.9824561404, "max_line_length": 100, "alphanum_fraction": 0.6985294118, "num_tokens": 1073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757313, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5559351809454203}}
{"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": "#include <vector>\n#include <Eigen/Dense>\n#include <algorithm>\n\n# pragma once\n\nusing std::vector; using std::string;\n\ntypedef Eigen::MatrixXd matrix;\n\nint atom(int ao_index, int orbitals_per_atom);\n\nint orb_index(int ao_index, int orbitals_per_atom);\n\nmatrix calculate_fock_matrix(matrix hamiltonian_matrix, matrix interaction_matrix, matrix density_matrix, vector<string> orbitals, int orbitals_per_atom, double dipole);\n", "meta": {"hexsha": "a81bf8c4e69c55c6f2bac7ff5887085b87538566", "size": 421, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/fock_matrix.hpp", "max_stars_repo_name": "Abdul-Zamani/qm_2019_sss_1", "max_stars_repo_head_hexsha": "fd665cccd90d8cf68cb97c8738cd32fb7981fe54", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/fock_matrix.hpp", "max_issues_repo_name": "Abdul-Zamani/qm_2019_sss_1", "max_issues_repo_head_hexsha": "fd665cccd90d8cf68cb97c8738cd32fb7981fe54", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-24T01:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-24T01:45:23.000Z", "max_forks_repo_path": "test/fock_matrix.hpp", "max_forks_repo_name": "MolSSI-Education/qm_2019_sss_1", "max_forks_repo_head_hexsha": "c1b3c1d66dd32e47edc5214bc32c5e996a03db26", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-07-23T20:16:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-31T17:47:46.000Z", "avg_line_length": 26.3125, "max_line_length": 169, "alphanum_fraction": 0.8028503563, "num_tokens": 94, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5559351672849353}}
{"text": "#define BOOST_TEST_MODULE \"test_potential_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <test/util/check_potential.hpp>\n#include <mjolnir/forcefield/local/CosinePotential.hpp>\n#include <mjolnir/math/constants.hpp>\n\nBOOST_AUTO_TEST_CASE(CosinePotential_double)\n{\n    using real_type = double;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-6;\n    constexpr real_type tol = 1e-6;\n    constexpr real_type   pi = mjolnir::math::constants<real_type>::pi();\n    const real_type    k = 2.0;\n    const std::int32_t n = 2;\n    const real_type   v0 = 3.0;\n\n    mjolnir::CosinePotential<real_type> potential(k, n, v0);\n\n    const real_type x_min = -pi;\n    const real_type x_max =  pi;\n\n    mjolnir::test::check_potential(potential, x_min, x_max, tol, h, N);\n}\n\nBOOST_AUTO_TEST_CASE(CosinePotential_float)\n{\n    using real_type = float;\n    constexpr std::size_t N = 100;\n    constexpr real_type   h = 1e-3;\n    constexpr real_type tol = 1e-3;\n    constexpr real_type   pi = mjolnir::math::constants<real_type>::pi();\n    const real_type    k = 2.0;\n    const std::int32_t n = 2;\n    const real_type   v0 = 3.0;\n\n    mjolnir::CosinePotential<real_type> potential(k, n, v0);\n\n    const real_type x_min = -2 * pi;\n    const real_type x_max =  2 * pi;\n\n    mjolnir::test::check_potential(potential, x_min, x_max, tol, h, N);\n}\n", "meta": {"hexsha": "a5e2b91dbf21e1e260a9768150063768dffe1c9b", "size": 1432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_cosine_potential.cpp", "max_stars_repo_name": "ToruNiina/Mjolnir", "max_stars_repo_head_hexsha": "44435dd3afc12f5c8ea27a66d7ab282df3e588ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-01T08:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-25T15:47:51.000Z", "max_issues_repo_path": "test/core/test_cosine_potential.cpp", "max_issues_repo_name": "Mjolnir-MD/Mjolnir", "max_issues_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T08:11:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T08:26:36.000Z", "max_forks_repo_path": "test/core/test_cosine_potential.cpp", "max_forks_repo_name": "Mjolnir-MD/Mjolnir", "max_forks_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-01-13T11:03:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T11:38:00.000Z", "avg_line_length": 28.64, "max_line_length": 73, "alphanum_fraction": 0.6934357542, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733979704703, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5558391363954456}}
{"text": "#include <string>\n#include <sstream>\n#include <iostream>\n#include <map>\n#include <regex>\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\n#include \"../common.hpp\"\n\nusing namespace std;\n\nvoid run(vector<int> & memory) {\n    int pc = 0;\n\n    while (pc < memory.size()) {\n        switch (memory[pc]) {\n            case 1: { // add\n                int src1 = memory[pc + 1];\n                int src2 = memory[pc + 2];\n                int dest = memory[pc + 3];\n                memory[dest] = memory[src1] + memory[src2];\n                pc += 4;\n                break;\n            }\n            case 2: {// mul\n                int src1 = memory[pc + 1];\n                int src2 = memory[pc + 2];\n                int dest = memory[pc + 3];\n                memory[dest] = memory[src1] * memory[src2];\n                pc += 4;\n                break;\n            }\n            case 99: // pass though\n                pc++;\n                return;\n            default:\n                cout << \"Unhandled op code: \" << memory[pc] << endl;\n                return;\n        };\n    }\n\n    cout << \"No more instructions\" << memory[pc] << endl;\n}\n\nint main() {\n    ifstream file (\"2019/2.txt\");\n    if (!file.is_open()) {\n        cout << \"Failed to open file: \" << strerror(errno) << endl;\n        return -1;\n    }\n\n    // Read the program\n    vector<int> memory;\n    string line; \n    while (getline(file, line, ',')) {\n        boost::trim(line);\n\n        if (line == \"\") {\n            continue;\n        }\n\n        memory.push_back(stoi(line));\n    }\n\n    const vector<int> backup_memory(memory); // make a backup\n\n    memory[1] = 12;\n    memory[2] = 2; \n\n    //cout << memory << endl;\n    run(memory);\n    //cout << memory << endl;\n\n    cout << \"Answer 2.1: \" << memory[0] << endl;\n\n    // Bruteforce lazy!\n    for (int noun = 0; noun < 99; noun++) {\n        for (int verb = 0; verb < 99; verb++) {\n            memory = backup_memory; // reset\n            memory[1] = noun;\n            memory[2] = verb;\n            run(memory);\n\n            if (memory[0] == 19690720) {\n                cout << \"Answer 2.2: \" << (100 * noun + verb) << endl;\n                return 0;\n            }\n        }\n    }\n\n    cout << \"Answer 2.2: Not found\" << endl;\n\n    file.close();\n}", "meta": {"hexsha": "357307ec8a000a27753cba5e70d7b8a3e00c27be", "size": 2260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/2.cpp", "max_stars_repo_name": "bramp/aoc", "max_stars_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2019/2.cpp", "max_issues_repo_name": "bramp/aoc", "max_issues_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2019/2.cpp", "max_forks_repo_name": "bramp/aoc", "max_forks_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7894736842, "max_line_length": 70, "alphanum_fraction": 0.4420353982, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5558391145753324}}
{"text": "#include \"../write_code_segment.hpp\"\n\n#include \"vm/processor.hpp\"\n#include \"vm/stack.hpp\"\n#include \"vm/exceptions.hpp\"\n\n#include <utility>\n#include <cstdint>\n#include <array>\n\n#include <boost/test/unit_test.hpp>\n\nusing perseus::detail::processor;\nusing perseus::detail::opcode;\n\nBOOST_AUTO_TEST_SUITE( vm )\n\nBOOST_AUTO_TEST_SUITE( execution )\n\nBOOST_AUTO_TEST_SUITE( boolean_arithmetic )\n\nBOOST_AUTO_TEST_CASE( boolean_and )\n{\n  for( std::uint8_t a = 0; a < 2; ++a )\n  {\n    for( std::uint8_t b = 0; b < 2; ++b )\n    {\n      auto code = create_code_segment( opcode::and_b, opcode::exit );\n      perseus::stack stack;\n      stack.push< std::uint8_t >( a );\n      stack.push< std::uint8_t >( b );\n      perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n      BOOST_CHECK_EQUAL( static_cast< bool >( result.pop< std::uint8_t >() ), a && b );\n      BOOST_CHECK_EQUAL( result.size(), 0 );\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE( boolean_or )\n{\n  for( std::uint8_t a = 0; a < 2; ++a )\n  {\n    for( std::uint8_t b = 0; b < 2; ++b )\n    {\n      auto code = create_code_segment( opcode::or_b, opcode::exit );\n      perseus::stack stack;\n      stack.push< std::uint8_t >( a );\n      stack.push< std::uint8_t >( b );\n      perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n      BOOST_CHECK_EQUAL( static_cast< bool >( result.pop< std::uint8_t >() ), a || b );\n      BOOST_CHECK_EQUAL( result.size(), 0 );\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE( boolean_equals )\n{\n  for( std::uint8_t a = 0; a < 2; ++a )\n  {\n    for( std::uint8_t b = 0; b < 2; ++b )\n    {\n      auto code = create_code_segment( opcode::equals_b, opcode::exit );\n      perseus::stack stack;\n      stack.push< std::uint8_t >( a );\n      stack.push< std::uint8_t >( b );\n      perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n      BOOST_CHECK_EQUAL( static_cast< bool >( result.pop< std::uint8_t >() ), a == b );\n      BOOST_CHECK_EQUAL( result.size(), 0 );\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE( boolean_not_equals )\n{\n  for( std::uint8_t a = 0; a < 2; ++a )\n  {\n    for( std::uint8_t b = 0; b < 2; ++b )\n    {\n      auto code = create_code_segment( opcode::not_equals_b, opcode::exit );\n      perseus::stack stack;\n      stack.push< std::uint8_t >( a );\n      stack.push< std::uint8_t >( b );\n      perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n      BOOST_CHECK_EQUAL( static_cast< bool >( result.pop< std::uint8_t >() ), a != b );\n      BOOST_CHECK_EQUAL( result.size(), 0 );\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE( boolean_negate )\n{\n  for( std::uint8_t a = 0; a < 2; ++a )\n  {\n    auto code = create_code_segment( opcode::negate_b, opcode::exit );\n    perseus::stack stack;\n    stack.push< std::uint8_t >( a );\n    perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n    BOOST_CHECK_EQUAL( static_cast< bool >( result.pop< std::uint8_t >() ), !a );\n    BOOST_CHECK_EQUAL( result.size(), 0 );\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE( int32_arithmetic )\n\nBOOST_AUTO_TEST_CASE( int32_add )\n{\n  auto code = create_code_segment( opcode::add_i32, opcode::exit );\n  perseus::stack stack;\n  stack.push< std::int32_t >( 4250 );\n  stack.push< std::int32_t >( -8 );\n  perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n  BOOST_CHECK_EQUAL( result.pop< std::int32_t >(), 4242 );\n  BOOST_CHECK_EQUAL( result.size(), 0 );\n}\n\nBOOST_AUTO_TEST_CASE( int32_subtract )\n{\n  auto code = create_code_segment( opcode::subtract_i32, opcode::exit );\n  perseus::stack stack;\n  stack.push< std::int32_t >( 1008 );\n  stack.push< std::int32_t >( 1050 );\n  perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n  BOOST_CHECK_EQUAL( result.pop< std::int32_t >(), -42 );\n  BOOST_CHECK_EQUAL( result.size(), 0 );\n}\n\nBOOST_AUTO_TEST_CASE( int32_multiply )\n{\n  auto code = create_code_segment( opcode::multiply_i32, opcode::exit );\n  perseus::stack stack;\n  stack.push< std::int32_t >( 6 );\n  stack.push< std::int32_t >( 7 );\n  perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n  BOOST_CHECK_EQUAL( result.pop< std::int32_t >(), 42 );\n  BOOST_CHECK_EQUAL( result.size(), 0 );\n}\n\nBOOST_AUTO_TEST_CASE( int32_divide_no_remainder )\n{\n  auto code = create_code_segment( opcode::divide_i32, opcode::exit );\n  perseus::stack stack;\n  stack.push< std::int32_t >( 42 );\n  stack.push< std::int32_t >( 7 );\n  perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n  BOOST_CHECK_EQUAL( result.pop< std::int32_t >(), 6 );\n  BOOST_CHECK_EQUAL( result.size(), 0 );\n}\n\nBOOST_AUTO_TEST_CASE( int32_divide_round_down )\n{\n  BOOST_TEST_MESSAGE( \"48/7 is closer to 7 than 6, but integer division is supposed to round down.\" );\n  auto code = create_code_segment( opcode::divide_i32, opcode::exit );\n  perseus::stack stack;\n  stack.push< std::int32_t >( 48 );\n  stack.push< std::int32_t >( 7 );\n  perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n  BOOST_CHECK_EQUAL( result.pop< std::int32_t >(), 6 );\n  BOOST_CHECK_EQUAL( result.size(), 0 );\n}\n\nBOOST_AUTO_TEST_CASE( int32_modulo )\n{\n  auto code = create_code_segment( opcode::modulo_i32, opcode::exit );\n  perseus::stack stack;\n  stack.push< std::int32_t >( 47 );\n  stack.push< std::int32_t >( 7 );\n  perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n  BOOST_CHECK_EQUAL( result.pop< std::int32_t >(), 5 );\n  BOOST_CHECK_EQUAL( result.size(), 0 );\n}\n\nBOOST_AUTO_TEST_CASE( int32_less_than_true )\n{\n  auto code = create_code_segment( opcode::less_than_i32, opcode::exit );\n  perseus::stack stack;\n  stack.push< std::int32_t >( 1 );\n  stack.push< std::int32_t >( 2 );\n  perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n  BOOST_CHECK_EQUAL( static_cast< bool >( result.pop< std::uint8_t >() ), true );\n  BOOST_CHECK_EQUAL( result.size(), 0 );\n}\n\nBOOST_AUTO_TEST_CASE( int32_less_than_false )\n{\n  auto code = create_code_segment( opcode::less_than_i32, opcode::exit );\n  perseus::stack stack;\n  stack.push< std::int32_t >( 2 );\n  stack.push< std::int32_t >( 2 );\n  perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n  BOOST_CHECK_EQUAL( static_cast< bool >( result.pop< std::uint8_t >() ), false );\n  BOOST_CHECK_EQUAL( result.size(), 0 );\n}\n\nBOOST_AUTO_TEST_CASE( int32_less_than_or_equals_true )\n{\n  auto code = create_code_segment( opcode::less_than_or_equals_i32, opcode::exit );\n  perseus::stack stack;\n  stack.push< std::int32_t >( 2 );\n  stack.push< std::int32_t >( 2 );\n  perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n  BOOST_CHECK_EQUAL( static_cast< bool >( result.pop< std::uint8_t >() ), true );\n  BOOST_CHECK_EQUAL( result.size(), 0 );\n}\n\nBOOST_AUTO_TEST_CASE( int32_less_than_or_equals_false )\n{\n  auto code = create_code_segment( opcode::less_than_or_equals_i32, opcode::exit );\n  perseus::stack stack;\n  stack.push< std::int32_t >( 3 );\n  stack.push< std::int32_t >( 2 );\n  perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n  BOOST_CHECK_EQUAL( static_cast< bool >( result.pop< std::uint8_t >() ), false );\n  BOOST_CHECK_EQUAL( result.size(), 0 );\n}\n\nBOOST_AUTO_TEST_CASE( int32_negate )\n{\n  auto code = create_code_segment( opcode::negate_i32, opcode::exit );\n  perseus::stack stack;\n  stack.push< std::int32_t >( -42 );\n  perseus::stack result = processor( std::move( code ) ).execute( 0, std::move( stack ) );\n  BOOST_CHECK_EQUAL( result.pop< std::int32_t >(), 42 );\n  BOOST_CHECK_EQUAL( result.size(), 0 );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ef029618faef97a1f59bc0f10d8f675396f0a7e4", "size": 7850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/test/execution/arithmetic.cpp", "max_stars_repo_name": "mrwonko/perseus", "max_stars_repo_head_hexsha": "45fcef10c5df7aeae469bf22b9be80e20f79cb21", "max_stars_repo_licenses": ["MIT"], "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/test/execution/arithmetic.cpp", "max_issues_repo_name": "mrwonko/perseus", "max_issues_repo_head_hexsha": "45fcef10c5df7aeae469bf22b9be80e20f79cb21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-04-07T23:16:02.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-17T08:14:15.000Z", "max_forks_repo_path": "code/test/execution/arithmetic.cpp", "max_forks_repo_name": "mrwonko/perseus", "max_forks_repo_head_hexsha": "45fcef10c5df7aeae469bf22b9be80e20f79cb21", "max_forks_repo_licenses": ["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.6909871245, "max_line_length": 102, "alphanum_fraction": 0.6563057325, "num_tokens": 2326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5558391116298389}}
{"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\u00e9lie 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\u00b2([0,T], L\u00b2(\u03a9))\";\n}\n\ntemplate <int dim>\nstd::string H2L2<dim>::unique_id() const {\n  return \"H\u00b2([0,T], L\u00b2(\u03a9)) with \u03b1=\" + std::to_string(alpha_) + \", \u03b2=\" + 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\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// Written by Cornelius Steinhardt\n\n\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//\u56fa\u5b9a\u7f51\u683cx\u5750\u6807\u6700\u5c0f\u70b9\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": "#include <iostream>\n#include <string>\n#include <memory>\n#include <vector>\n#include <random>\n#include <cmath>\n#include <unordered_map>\n#include <Eigen/Dense>\n#include <matplotlibcpp.h>\n#include \"../include/model.h\"\n#include \"../datasets/include/mnist.h\"\n#include \"../include/trainer.h\"\n\nusing std::vector;\nnamespace plt = matplotlibcpp;\n\nvoid search_train(double, double, int, vector<double> &, vector<double> &);\nvoid print_vector(vector<double> &);\n\n\nint main()\n{\n    using namespace Eigen;\n    using namespace MyDL;\n    using std::cout;\n    using std::endl;\n    using std::string;\n    using std::vector;\n    using std::shared_ptr;\n    using std::make_shared;\n    using std::unordered_map;\n\n    int optimization_trial = 2; //\u63a2\u7d22\u56de\u6570(\u30c6\u30b9\u30c8\u7528\u306e\u6570\u5024\u3002\u3057\u3063\u304b\u308a\u78ba\u8a8d\u3059\u308b\u306a\u3089100\u56de\u7a0b\u5ea6\u3084\u308b\u5fc5\u8981\u3042\u308a)\n    // int optimization_trial = 100;\n    int trial = 1;\n\n    // \u4e71\u6570\u767a\u751f\u306e\u305f\u3081\u306e\u8a2d\u5b9a\n    std::random_device seed_gen;\n    std::default_random_engine engine(seed_gen());\n    std::uniform_real_distribution<> lr_dist(-8, -4);\n    std::uniform_real_distribution<> lambda_dist(-6, -2);\n\n    // \u52d5\u4f5c\u30c6\u30b9\u30c8\u3002\u672c\u6765\u306f\u3053\u308c\u3089\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u30e9\u30f3\u30c0\u30e0\u5316\u3057\u3066seach_train\u306b\u7a81\u3063\u8fbc\u3080\n    // \u7a81\u3063\u8fbc\u3080\u5185\u5bb9\u306f\u300110^(-8) ~ 10^(-4)\n    // 10^(-6) ~ 10^(-2)\n\n    unordered_map<string, vector<double>> train_acc_history_dictionary, test_acc_history_dictionary;\n    unordered_map<string, double> learning_rate_dictionary, weight_decay_lambda_dictionary;\n\n    while (trial <= optimization_trial )\n    {\n        vector<double> train_acc_history, test_acc_history;\n\n        double learning_rate = std::pow(10, lr_dist(engine));           // -8 ~ -4\n        double weight_decay_lambda = std::pow(10, lambda_dist(engine)); // -6, -2\n        int epochs = 5;\n        // int epochs = 50;\n\n        cout << \"Learning Rate: \" << learning_rate << endl;\n        cout << \"Weight Decay Lambda: \" << weight_decay_lambda << endl;\n\n        search_train(learning_rate, weight_decay_lambda, epochs, train_acc_history, test_acc_history);\n\n        cout << \"===== Train accuracy =====\" << endl;\n        print_vector(train_acc_history);\n        cout << \"===== Test accuracy =====\" << endl;\n        print_vector(test_acc_history);\n\n        train_acc_history_dictionary[\"trial\" + std::to_string(trial)] = train_acc_history;\n        test_acc_history_dictionary[\"trial\" + std::to_string(trial)] = test_acc_history;\n        learning_rate_dictionary[\"trial\" + std::to_string(trial)] = learning_rate;\n        weight_decay_lambda_dictionary[\"trial\" + std::to_string(trial)] = weight_decay_lambda;\n\n        // train_acc_history, test_acc_history\u306e\u4e2d\u8eab\u3092\u6d88\u53bb\u3059\u308b\u30b3\u30fc\u30c9\u3092\u4f5c\u6210\u3059\u308b\n        train_acc_history.clear();\n        train_acc_history.shrink_to_fit();\n        test_acc_history.clear();\n        test_acc_history.shrink_to_fit();\n\n        trial++;\n    }\n\n    // \u5b66\u7fd2\u7d50\u679c\u3092\u63cf\u753b\n\n    for (auto item : train_acc_history_dictionary)\n    {\n        string trial_num = item.first;\n        string lr_str = std::to_string(learning_rate_dictionary[trial_num]);\n        string lambda_str = std::to_string(weight_decay_lambda_dictionary[trial_num]);\n        vector<int> x_axis(item.second.size());\n        std::iota(x_axis.begin(), x_axis.end(), 1);\n        \n        plt::title(\"accuracy history of \" + trial_num);\n        plt::plot(x_axis, train_acc_history_dictionary[trial_num], \"b\");\n        plt::plot(x_axis, test_acc_history_dictionary[trial_num], \"r\");\n        plt::grid(true);\n\n        plt::save(\"Hyperparameter Tuning \" + trial_num);\n        plt::cla();\n\n        cout << \"=== \" << trial_num << \"===\" << endl;\n        cout << \"Learning Rate: \" << lr_str << endl;\n        cout << \"Weight Decay Lambda: \" << lambda_str << endl;\n        cout << endl;\n    }\n\n    return 0;\n}\n\n\nvoid search_train(double learning_rate,\n                  double weight_decay_lambda,\n                  int epochs,\n                  vector<double> & train_acc_history,\n                  vector<double> & test_acc_history)\n{\n    using namespace Eigen;\n    using namespace MyDL;\n    using std::vector;\n    using std::string;\n    using std::shared_ptr;\n    using std::make_shared;\n\n    int input_size = 28 * 28;\n    vector<int> hidden_list = {50};\n    int output_size = 10;\n    int batch_size = 100;\n    string activation = \"relu\";\n    string weight_initializer = \"he\";\n    bool use_dropout = false;\n    double dropout_ratio = 0.5;\n    bool use_batchnorm = false;\n\n    auto model = make_shared<MultiLayerModel>(input_size,\n                                              hidden_list, \n                                              output_size, \n                                              weight_decay_lambda,\n                                              activation,\n                                              weight_initializer,\n                                              use_dropout,\n                                              dropout_ratio,\n                                              use_batchnorm);\n    auto dataset = make_shared<MnistEigenDataset>(batch_size);\n    auto optimizer = make_shared<SGD>(learning_rate);\n    // Trainer trainer(model, optimizer, dataset, epochs=epochs, false);\n    Trainer trainer(model, optimizer, dataset, epochs=epochs, true);\n\n    trainer.train();\n\n    train_acc_history = trainer.train_acc_history;\n    test_acc_history  = trainer.test_acc_history;\n}\n\n\nvoid print_vector(vector<double> & vec)\n{\n    for (const auto &item : vec)\n    {\n        std::cout << item << \" \";\n    }\n    std::cout << std::endl;\n}", "meta": {"hexsha": "2f47982faa2422385ff5abb24251129ff51e90d5", "size": 5349, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/hyperparameter_optimization.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch6/hyperparameter_optimization.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch6/hyperparameter_optimization.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": 33.0185185185, "max_line_length": 102, "alphanum_fraction": 0.6094597121, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5556606498287479}}
{"text": "/**\n * @file rbm_network_test.cpp\n * @author Kris Singh\n * @author Shikhar Jaiswal\n *\n * Tests the RBM Network\n *\n * digits dataset source:\n * @misc{Lichman:2013 ,\n * author = \"M. Lichman\",\n * year = \"2013\",\n * title = \"{UCI} Machine Learning Repository\",\n * url = \"http://archive.ics.uci.edu/ml\",\n * institution = \"University of California,\n * Irvine, School of Information and Computer Sciences\" }\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license. You should have received a copy of the\n * 3-clause BSD license along with mlpack. If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/init_rules/gaussian_init.hpp>\n#include <mlpack/methods/ann/rbm/rbm.hpp>\n#include <mlpack/methods/softmax_regression/softmax_regression.hpp>\n#include <ensmallen.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\nusing namespace ens;\nusing namespace mlpack::regression;\n\nBOOST_AUTO_TEST_SUITE(RBMNetworkTest);\n\n/*\n * Tests the BinaryRBM implementation on the Digits dataset.\n */\nBOOST_AUTO_TEST_CASE(BinaryRBMClassificationTest)\n{\n  // Normalised dataset.\n  int hiddenLayerSize = 100;\n  size_t batchSize = 10;\n  size_t numEpoches = 30;\n  arma::mat trainData, testData, dataset;\n  arma::mat trainLabelsTemp, testLabelsTemp;\n  trainData.load(\"digits_train.arm\");\n  testData.load(\"digits_test.arm\");\n  trainLabelsTemp.load(\"digits_train_label.arm\");\n  testLabelsTemp.load(\"digits_test_label.arm\");\n\n  arma::Row<size_t> trainLabels = arma::zeros<arma::Row<size_t>>(1,\n      trainLabelsTemp.n_cols);\n  arma::Row<size_t> testLabels = arma::zeros<arma::Row<size_t>>(1,\n      testLabelsTemp.n_cols);\n\n  for (size_t i = 0; i < trainLabelsTemp.n_cols; ++i)\n    trainLabels(i) = arma::as_scalar(trainLabelsTemp.col(i));\n\n  for (size_t i = 0; i < testLabelsTemp.n_cols; ++i)\n    testLabels(i) = arma::as_scalar(testLabelsTemp.col(i));\n\n  arma::mat output, XRbm(hiddenLayerSize, trainData.n_cols),\n      YRbm(hiddenLayerSize, testLabels.n_cols);\n\n  XRbm.zeros();\n  YRbm.zeros();\n\n  GaussianInitialization gaussian(0, 0.1);\n  RBM<GaussianInitialization> model(trainData,\n      gaussian, trainData.n_rows, hiddenLayerSize, batchSize);\n\n  size_t numRBMIterations = trainData.n_cols * numEpoches;\n  numRBMIterations /= batchSize;\n  ens::StandardSGD msgd(0.03, batchSize, numRBMIterations, 0, true);\n  model.Reset();\n  model.VisibleBias().ones();\n  model.HiddenBias().ones();\n\n  // Test the reset function.\n  model.Train(msgd);\n\n  for (size_t i = 0; i < trainData.n_cols; i++)\n  {\n    model.HiddenMean(std::move(trainData.col(i)), std::move(output));\n    XRbm.col(i) = output;\n  }\n\n  for (size_t i = 0; i < testData.n_cols; i++)\n  {\n    model.HiddenMean(std::move(testData.col(i)),\n      std::move(output));\n    YRbm.col(i) = output;\n  }\n  const size_t numClasses = 10; // Number of classes.\n  const size_t numBasis = 5; // Parameter required for L-BFGS algorithm.\n  const size_t numIterations = 100; // Maximum number of iterations.\n\n  // Use an instantiated optimizer for the training.\n  L_BFGS optimizer(numBasis, numIterations);\n  SoftmaxRegression regressor(trainData, trainLabels,\n      numClasses, 0.001, false, optimizer);\n\n  double classificationAccuracy = regressor.ComputeAccuracy(testData,\n    testLabels);\n\n  L_BFGS rbmOptimizer(numBasis, numIterations);\n  SoftmaxRegression rbmRegressor(XRbm, trainLabels, numClasses,\n        0.001, false, rbmOptimizer);\n  double rbmClassificationAccuracy = rbmRegressor.ComputeAccuracy(YRbm,\n      testLabels);\n\n  // We allow a 6% tolerance because the RBM may not reconstruct samples as\n  // well.  (Typically it does, but we have no guarantee.)\n  BOOST_REQUIRE_GE(rbmClassificationAccuracy, classificationAccuracy - 6.0);\n}\n\n/*\n * Tests the SpikeSlabRBM implementation on the Digits dataset.\n */\nBOOST_AUTO_TEST_CASE(ssRBMClassificationTest)\n{\n  size_t batchSize = 10;\n  size_t numEpoches = 3;\n  int hiddenLayerSize = 80;\n  double radius = 0;\n  double tempRadius = 0;\n  arma::mat trainData, testData, dataset;\n  arma::mat trainLabelsTemp, testLabelsTemp;\n  trainData.load(\"digits_train.arm\");\n  testData.load(\"digits_test.arm\");\n  trainLabelsTemp.load(\"digits_train_label.arm\");\n  testLabelsTemp.load(\"digits_test_label.arm\");\n  GaussianInitialization gaussian(0, 1);\n\n  arma::Row<size_t> trainLabels = arma::zeros<arma::Row<size_t>>(1,\n      trainLabelsTemp.n_cols);\n  arma::Row<size_t> testLabels = arma::zeros<arma::Row<size_t>>(1,\n      testLabelsTemp.n_cols);\n\n  for (size_t i = 0; i < trainLabelsTemp.n_cols; ++i)\n    trainLabels(i) = arma::as_scalar(trainLabelsTemp.col(i));\n\n  for (size_t i = 0; i < testLabelsTemp.n_cols; ++i)\n    testLabels(i) = arma::as_scalar(testLabelsTemp.col(i));\n\n  for (size_t i = 0; i < trainData.n_cols; i++)\n  {\n    tempRadius = arma::norm(trainData.col(i));\n    if (radius < tempRadius)\n      radius = tempRadius;\n  }\n\n  size_t poolSize = 2;\n  radius *= 1.3;\n\n  arma::mat output;\n  arma::mat XRbm(hiddenLayerSize + poolSize * hiddenLayerSize,\n      trainData.n_cols);\n  arma::mat YRbm(hiddenLayerSize + poolSize * hiddenLayerSize,\n      testLabels.n_cols);\n\n  XRbm.zeros();\n  YRbm.zeros();\n  double slabPenalty = 8;\n\n  RBM<GaussianInitialization, arma::mat, SpikeSlabRBM> modelssRBM(trainData,\n      gaussian, trainData.n_rows, hiddenLayerSize, batchSize, 1, 1, poolSize,\n      slabPenalty, radius);\n\n  size_t numRBMIterations = trainData.n_cols * numEpoches;\n  numRBMIterations /= batchSize;\n\n  ens::StandardSGD msgd(0.02, batchSize, numRBMIterations, 0, true);\n  modelssRBM.Reset();\n  modelssRBM.VisiblePenalty().fill(5);\n  modelssRBM.SpikeBias().fill(1);\n\n  modelssRBM.Train(msgd);\n  for (size_t i = 0; i < trainData.n_cols; i++)\n  {\n    modelssRBM.HiddenMean(std::move(trainData.col(i)),\n        std::move(output));\n    XRbm.col(i) = output;\n  }\n\n  for (size_t i = 0; i < testData.n_cols; i++)\n  {\n    modelssRBM.HiddenMean(std::move(testData.col(i)),\n      std::move(output));\n    YRbm.col(i) = output;\n  }\n  const size_t numClasses = 10; // Number of classes.\n  const size_t numBasis = 5; // Parameter required for L-BFGS algorithm.\n  const size_t numIterations = 100; // Maximum number of iterations.\n\n  L_BFGS ssRbmOptimizer(numBasis, numIterations);\n  SoftmaxRegression ssRbmRegressor(XRbm, trainLabels, numClasses,\n        0.001, false, ssRbmOptimizer);\n  double ssRbmClassificationAccuracy = ssRbmRegressor.ComputeAccuracy(\n      YRbm, testLabels);\n\n  // 76.18 is the standard accuracy of the Softmax regression classifier,\n  // omitted here for speed.  We add a margin of 2% since ssRBM isn't guaranteed\n  // to give us better results (we just generally expect it to be about as good\n  // or better).\n  BOOST_REQUIRE_GE(ssRbmClassificationAccuracy, 76.18 - 2.0);\n}\n\ntemplate<typename MatType = arma::mat>\nvoid BuildVanillaNetwork(MatType& trainData,\n                         const size_t hiddenLayerSize)\n{\n  MatType output;\n  GaussianInitialization gaussian(0, 0.1);\n  RBM<GaussianInitialization, MatType, BinaryRBM> model(trainData, gaussian,\n      trainData.n_rows, hiddenLayerSize, 1, 1, 1, 2, 8, 1, true);\n\n  model.Reset();\n  // Set the parameters from a learned RBM Sklearn random state 23.\n  model.Parameters() = MatType(\n      \"-0.23224054, -0.23000632, -0.25701271, -0.25122418, -0.20716651,\"\n      \"-0.20962217, -0.59922456, -0.60003836, -0.6, -0.625, -0.475;\");\n\n  // Check free energy.\n  arma::Mat<float> freeEnergy = MatType(\n      \"-0.87523715, 0.50615066, 0.46923476, 1.21509084;\");\n  arma::vec calculatedFreeEnergy(4, arma::fill::zeros);\n  for (size_t i = 0; i < trainData.n_cols; i++)\n  {\n    calculatedFreeEnergy(i) = model.FreeEnergy(std::move(trainData.col(i)));\n  }\n\n  for (size_t i = 0; i < freeEnergy.n_elem; i++)\n    BOOST_REQUIRE_CLOSE(calculatedFreeEnergy(i), freeEnergy(i), 1e-3);\n}\n\n/*\n * Train and evaluate a Vanilla network with the specified structure.\n */\nBOOST_AUTO_TEST_CASE(MiscTest)\n{\n  arma::Mat<float> X = arma::Mat<float>(\"0.0, 0.0, 0.0;\"\n                          \"0.0, 1.0, 1.0;\"\n                          \"1.0, 0.0, 1.0;\"\n                          \"1.0, 1.0, 1.0;\");\n  X = X.t();\n  BuildVanillaNetwork<arma::Mat<float>>(X, 2);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "f6946b27bccb8cc62f9bc2070046d9b72a478c7b", "size": 8301, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/rbm_network_test.cpp", "max_stars_repo_name": "RMaron/mlpack", "max_stars_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-21T23:30:34.000Z", "max_issues_repo_path": "src/mlpack/tests/rbm_network_test.cpp", "max_issues_repo_name": "RMaron/mlpack", "max_issues_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-01-23T18:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T13:58:34.000Z", "max_forks_repo_path": "src/mlpack/tests/rbm_network_test.cpp", "max_forks_repo_name": "RMaron/mlpack", "max_forks_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-20T00:54:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-16T05:34:32.000Z", "avg_line_length": 32.5529411765, "max_line_length": 80, "alphanum_fraction": 0.697626792, "num_tokens": 2379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5556606475852678}}
{"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": "#include <Eigen/Core>\n#include <Eigen/StdVector>\n#include <boost/make_unique.hpp>\n#include <boost/optional/optional_io.hpp>\n#include <catch2/catch.hpp>\n#include <random>\n#include <string>\n#include \"common/convex_hull.hpp\"\n#include \"common/facets.hpp\"\n#include \"common/geom.hpp\"\n#include \"common/point_source_panner.hpp\"\n#include \"ear/bs2051.hpp\"\n#include \"ear/exceptions.hpp\"\n#include \"helper/compare.hpp\"\n\nusing namespace ear;\n\nTEST_CASE(\"test_virtual_ngon\") {\n  Eigen::MatrixXd spkPositions(4, 3);\n  spkPositions << cartT(30.0, 0.0, 1.0), cartT(-30.0, 0.0, 1.0),\n      cartT(30.0, 30.0, 1.0), cartT(-30.0, 30.0, 1.0);\n  Eigen::Vector4d virtualDownmix(0.2, 0.2, 0.3, 0.3);\n  Eigen::Vector3d virtualPos = virtualDownmix.transpose() * spkPositions;\n  auto ng =\n      std::make_shared<VirtualNgon>(Eigen::Vector4i::LinSpaced(4, 0, 4),\n                                    spkPositions, virtualPos, virtualDownmix);\n  // panning to the virtual speaker, the output should be the normalised downmix\n  boost::optional<Eigen::VectorXd> pv = ng->handle(virtualPos);\n  REQUIRE(pv != boost::none);\n  REQUIRE(pv.get().size() == 4);\n  REQUIRE(pv->isApprox(virtualDownmix / virtualDownmix.norm()));\n\n  std::default_random_engine generator;\n  std::uniform_real_distribution<double> distribution(0.0, 1.0);\n  auto random = [&](double) { return distribution(generator); };\n  for (int i = 0; i < 100; ++i) {\n    Eigen::Vector4d proportion = Eigen::Vector4d::NullaryExpr(4, random);\n    // we can calculate a position within the ngon\n    Eigen::Vector3d pos = spkPositions.transpose() * proportion;\n    pos /= pos.norm();\n    // which when rendered\n    boost::optional<Eigen::VectorXd> pv = ng->handle(pos);\n    REQUIRE(pv != boost::none);\n    // can be multiplied by the speaker positions to produce another position\n    Eigen::Vector3d posCalc = pv->transpose() * spkPositions;\n    posCalc /= posCalc.norm();\n    // that should be the same as the one we started with\n    REQUIRE(pos.isApprox(posCalc));\n  }\n}\n\nTEST_CASE(\"test_quad\") {\n  Eigen::MatrixXd spkPositions(4, 3);\n  spkPositions << cartT(30.0, -15.0, 1.0), cartT(-30.0, -15.0, 1.0),\n      cartT(30.0, 15.0, 1.0), cartT(-30.0, 15.0, 1.0);\n  auto quad = std::make_shared<QuadRegion>(Eigen::Vector4i::LinSpaced(4, 0, 4),\n                                           spkPositions);\n\n  using PosGainsT = std::pair<Eigen::Vector3d, Eigen::Vector4d>;\n  std::vector<PosGainsT, Eigen::aligned_allocator<PosGainsT>> posGains;\n  posGains.push_back(\n      std::make_pair(spkPositions.row(0), Eigen::Vector4d(1.0, 0.0, 0.0, 0.0)));\n  posGains.push_back(\n      std::make_pair(spkPositions.row(1), Eigen::Vector4d(0.0, 1.0, 0.0, 0.0)));\n  posGains.push_back(\n      std::make_pair(spkPositions.row(2), Eigen::Vector4d(0.0, 0.0, 1.0, 0.0)));\n  posGains.push_back(\n      std::make_pair(spkPositions.row(3), Eigen::Vector4d(0.0, 0.0, 0.0, 1.0)));\n  posGains.push_back(\n      std::make_pair(cart(0.0, 0.0, 1.0), Eigen::Vector4d(0.5, 0.5, 0.5, 0.5)));\n  for (const auto& pair : posGains) {\n    auto pv = quad->handle(pair.first);\n    REQUIRE(pv != boost::none);\n    REQUIRE(pv->isApprox(pair.second));\n  }\n};\n\nTEST_CASE(\"test_stereo_downmix\") {\n  Eigen::MatrixXd spkPositions(2, 3);\n  spkPositions << cartT(30.0, 0.0, 1.0), cartT(-30.0, 0.0, 1.0);\n\n  auto p = std::make_shared<StereoPannerDownmix>(\n      Eigen::Vector2i::LinSpaced(2, 0, 1), spkPositions);\n\n  std::vector<std::pair<Eigen::Vector3d, Eigen::Vector2d>> posGains;\n  posGains.push_back(std::make_pair(cart(0.0, 0.0, 1.0),\n                                    Eigen::Vector2d(sqrt(0.5), sqrt(0.5))));\n  posGains.push_back(\n      std::make_pair(cart(-30.0, 0.0, 1.0), Eigen::Vector2d(0.0, 1.0)));\n  posGains.push_back(\n      std::make_pair(cart(-110.0, 0.0, 1.0), Eigen::Vector2d(0.0, sqrt(0.5))));\n  posGains.push_back(std::make_pair(cart(-180.0, 0.0, 1.0),\n                                    Eigen::Vector2d(sqrt(0.25), sqrt(0.25))));\n\n  for (auto pair : posGains) {\n    auto pv = p->handle(pair.first);\n    REQUIRE(pv->isApprox(pair.second));\n  }\n}\n\nEigen::MatrixXd createDownmixMatrixFromIndices(std::vector<int> indices,\n                                               size_t size) {\n  Eigen::MatrixXd downmix = Eigen::MatrixXd::Identity(size, size);\n  for (int index : indices) {\n    Eigen::VectorXd downmixRow = Eigen::VectorXd::Zero(size);\n    downmixRow(index) = 1.0;\n    downmix.conservativeResize(downmix.rows() + 1, Eigen::NoChange);\n    downmix.row(downmix.rows() - 1) = downmixRow;\n  }\n  return downmix;\n}\n\nTEST_CASE(\"extra_pos_vertical_nominal\") {\n  std::vector<Channel> extraChannels;\n  Eigen::MatrixXd downmix;\n  std::vector<PolarPosition> expectedPositions;\n\n  SECTION(\"0+5+0\") {\n    Layout layout = getLayout(\"0+5+0\").withoutLfe();\n    std::tie(extraChannels, downmix) = extraPosVerticalNominal(layout);\n    std::vector<PolarPosition> expectedPositions = {\n        PolarPosition(30.0, -30.0, 1.0),   PolarPosition(-30.0, -30.0, 1.0),\n        PolarPosition(0.0, -30.0, 1.0),    PolarPosition(110.0, -30.0, 1.0),\n        PolarPosition(-110.0, -30.0, 1.0), PolarPosition(30.0, 30.0, 1.0),\n        PolarPosition(-30.0, 30.0, 1.0),   PolarPosition(0.0, 30.0, 1.0),\n        PolarPosition(110.0, 30.0, 1.0),   PolarPosition(-110.0, 30.0, 1.0)};\n    REQUIRE(extraChannels.size() == expectedPositions.size());\n    for (size_t i = 0; i < extraChannels.size(); ++i) {\n      REQUIRE(extraChannels[i].polarPosition() == expectedPositions[i]);\n    }\n    Eigen::MatrixXd expectedDownmix = createDownmixMatrixFromIndices(\n        std::vector<int>{0, 1, 2, 3, 4, 0, 1, 2, 3, 4},\n        layout.channels().size());\n    REQUIRE(downmix == expectedDownmix);\n  };\n\n  SECTION(\"2+5+0\") {\n    Layout layout = getLayout(\"2+5+0\").withoutLfe();\n    std::tie(extraChannels, downmix) = extraPosVerticalNominal(layout);\n    std::vector<PolarPosition> expectedPositions = {\n        PolarPosition(30.0, -30.0, 1.0),   PolarPosition(-30.0, -30.0, 1.0),\n        PolarPosition(0.0, -30.0, 1.0),    PolarPosition(110.0, -30.0, 1.0),\n        PolarPosition(-110.0, -30.0, 1.0), PolarPosition(110.0, 30.0, 1.0),\n        PolarPosition(-110.0, 30.0, 1.0)};\n    REQUIRE(extraChannels.size() == expectedPositions.size());\n    for (size_t i = 0; i < extraChannels.size(); ++i) {\n      REQUIRE(extraChannels[i].polarPosition() == expectedPositions[i]);\n    }\n    Eigen::MatrixXd expectedDownmix = createDownmixMatrixFromIndices(\n        std::vector<int>{0, 1, 2, 3, 4, 3, 4}, layout.channels().size());\n    REQUIRE(downmix == expectedDownmix);\n  };\n\n  SECTION(\"4+5+0/4+5+1\") {\n    for (const std::string& layoutName : {\"4+5+0\", \"4+5+1\"}) {\n      Layout layout = getLayout(\"4+5+0\").withoutLfe();\n      std::tie(extraChannels, downmix) = extraPosVerticalNominal(layout);\n      std::vector<PolarPosition> expectedPositions = {\n          PolarPosition(30.0, -30.0, 1.0), PolarPosition(-30.0, -30.0, 1.0),\n          PolarPosition(0.0, -30.0, 1.0), PolarPosition(110.0, -30.0, 1.0),\n          PolarPosition(-110.0, -30.0, 1.0)};\n      REQUIRE(extraChannels.size() == expectedPositions.size());\n      for (size_t i = 0; i < extraChannels.size(); ++i) {\n        REQUIRE(extraChannels[i].polarPosition() == expectedPositions[i]);\n      }\n      Eigen::MatrixXd expectedDownmix = createDownmixMatrixFromIndices(\n          std::vector<int>{0, 1, 2, 3, 4}, layout.channels().size());\n      REQUIRE(downmix == expectedDownmix);\n    }\n  };\n\n  SECTION(\"3+7+0\") {\n    Layout layout = getLayout(\"3+7+0\").withoutLfe();\n    std::tie(extraChannels, downmix) = extraPosVerticalNominal(layout);\n    std::vector<PolarPosition> expectedPositions = {\n        PolarPosition(0.0, -30.0, 1.0),   PolarPosition(30.0, -30.0, 1.0),\n        PolarPosition(-30.0, -30.0, 1.0), PolarPosition(90.0, -30.0, 1.0),\n        PolarPosition(-90.0, -30.0, 1.0), PolarPosition(135.0, -30.0, 1.0),\n        PolarPosition(-135.0, -30.0, 1.0)};\n    REQUIRE(extraChannels.size() == expectedPositions.size());\n    for (size_t i = 0; i < extraChannels.size(); ++i) {\n      REQUIRE(extraChannels[i].polarPosition() == expectedPositions[i]);\n    }\n    Eigen::MatrixXd expectedDownmix = createDownmixMatrixFromIndices(\n        std::vector<int>{0, 1, 2, 5, 6, 7, 8}, layout.channels().size());\n    REQUIRE(downmix == expectedDownmix);\n  };\n\n  SECTION(\"4+9+0\") {\n    Layout layout = getLayout(\"4+9+0\").withoutLfe();\n    std::tie(extraChannels, downmix) = extraPosVerticalNominal(layout);\n    std::vector<PolarPosition> expectedPositions = {\n        PolarPosition(30.0, -30.0, 1.0),   PolarPosition(-30.0, -30.0, 1.0),\n        PolarPosition(0.0, -30.0, 1.0),    PolarPosition(90.0, -30.0, 1.0),\n        PolarPosition(-90.0, -30.0, 1.0),  PolarPosition(135.0, -30.0, 1.0),\n        PolarPosition(-135.0, -30.0, 1.0), PolarPosition(15.0, -30.0, 1.0),\n        PolarPosition(-15.0, -30.0, 1.0)};\n    REQUIRE(extraChannels.size() == expectedPositions.size());\n    for (size_t i = 0; i < extraChannels.size(); ++i) {\n      REQUIRE(extraChannels[i].polarPosition() == expectedPositions[i]);\n    }\n    Eigen::MatrixXd expectedDownmix = createDownmixMatrixFromIndices(\n        std::vector<int>{0, 1, 2, 3, 4, 5, 6, 11, 12},\n        layout.channels().size());\n    REQUIRE(downmix == expectedDownmix);\n  };\n\n  SECTION(\"9+10+3\") {\n    Layout layout = getLayout(\"9+10+3\").withoutLfe();\n    std::tie(extraChannels, downmix) = extraPosVerticalNominal(layout);\n    std::vector<PolarPosition> expectedPositions = {\n        PolarPosition(135.0, -30.0, 1.0), PolarPosition(-135.0, -30.0, 1.0),\n        PolarPosition(180.0, -30.0, 1.0), PolarPosition(90.0, -30.0, 1.0),\n        PolarPosition(-90.0, -30.0, 1.0)};\n    REQUIRE(extraChannels.size() == expectedPositions.size());\n    for (size_t i = 0; i < extraChannels.size(); ++i) {\n      REQUIRE(extraChannels[i].polarPosition() == expectedPositions[i]);\n    }\n    Eigen::MatrixXd expectedDownmix = createDownmixMatrixFromIndices(\n        std::vector<int>{3, 4, 7, 8, 9}, layout.channels().size());\n    REQUIRE(downmix == expectedDownmix);\n  };\n\n  SECTION(\"0+7+0\") {\n    Layout layout = getLayout(\"0+7+0\").withoutLfe();\n    std::tie(extraChannels, downmix) = extraPosVerticalNominal(layout);\n    std::vector<PolarPosition> expectedPositions = {\n        PolarPosition(30.0, -30.0, 1.0),   PolarPosition(-30.0, -30.0, 1.0),\n        PolarPosition(0.0, -30.0, 1.0),    PolarPosition(90.0, -30.0, 1.0),\n        PolarPosition(-90.0, -30.0, 1.0),  PolarPosition(135.0, -30.0, 1.0),\n        PolarPosition(-135.0, -30.0, 1.0), PolarPosition(30.0, 30.0, 1.0),\n        PolarPosition(-30.0, 30.0, 1.0),   PolarPosition(0.0, 30.0, 1.0),\n        PolarPosition(90.0, 30.0, 1.0),    PolarPosition(-90.0, 30.0, 1.0),\n        PolarPosition(135.0, 30.0, 1.0),   PolarPosition(-135.0, 30.0, 1.0)};\n    REQUIRE(extraChannels.size() == expectedPositions.size());\n    for (size_t i = 0; i < extraChannels.size(); ++i) {\n      REQUIRE(extraChannels[i].polarPosition() == expectedPositions[i]);\n    }\n    Eigen::MatrixXd expectedDownmix = createDownmixMatrixFromIndices(\n        std::vector<int>{0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6},\n        layout.channels().size());\n    REQUIRE(downmix == expectedDownmix);\n  };\n\n  SECTION(\"4+7+0\") {\n    Layout layout = getLayout(\"4+7+0\").withoutLfe();\n    std::tie(extraChannels, downmix) = extraPosVerticalNominal(layout);\n    std::vector<PolarPosition> expectedPositions = {\n        PolarPosition(30.0, -30.0, 1.0),  PolarPosition(-30.0, -30.0, 1.0),\n        PolarPosition(0.0, -30.0, 1.0),   PolarPosition(90.0, -30.0, 1.0),\n        PolarPosition(-90.0, -30.0, 1.0), PolarPosition(135.0, -30.0, 1.0),\n        PolarPosition(-135.0, -30.0, 1.0)};\n    REQUIRE(extraChannels.size() == expectedPositions.size());\n    for (size_t i = 0; i < extraChannels.size(); ++i) {\n      REQUIRE(extraChannels[i].polarPosition() == expectedPositions[i]);\n    }\n    Eigen::MatrixXd expectedDownmix = createDownmixMatrixFromIndices(\n        std::vector<int>{0, 1, 2, 3, 4, 5, 6}, layout.channels().size());\n    REQUIRE(downmix == expectedDownmix);\n  };\n};\n\nstd::vector<std::pair<Eigen::Vector3d, Eigen::VectorXd>> generatePositionGains(\n    const Layout& layout) {\n  std::vector<std::pair<Eigen::Vector3d, Eigen::VectorXd>> ret;\n  auto positions = layout.positions();\n  for (size_t i = 0; i < positions.size(); ++i) {\n    Eigen::VectorXd expectedGain =\n        Eigen::VectorXd::Zero(layout.channels().size());\n    expectedGain(i) = 1.0;\n    ret.push_back(\n        std::make_pair(toCartesianVector3d(positions[i]), expectedGain));\n  }\n  return ret;\n}\n\nTEST_CASE(\"test_polar_point_source_panner\") {\n  Eigen::MatrixXd positions(4, 3);\n  positions << cartT(30.0, 0.0, 1.0),  //\n      cartT(0.0, 0.0, 1.0),  //\n      cartT(-30.0, 0.0, 1.0),  //\n      cartT(0.0, 30.0, 1.0);\n  std::vector<Eigen::Vector3i> outputChannelsVec = {{0, 1, 3}, {2, 1, 3}};\n  std::vector<std::unique_ptr<RegionHandler>> regions_1;\n  for (const auto& outputChannels : outputChannelsVec) {\n    regions_1.push_back(boost::make_unique<Triplet>(\n        outputChannels, positions(outputChannels, {0, 1, 2})));\n  }\n\n  // should fail if not given enough channels\n  REQUIRE_THROWS(PolarPointSourcePanner(\n      std::move(regions_1), static_cast<int>(positions.rows() - 1)));\n\n  std::vector<std::unique_ptr<RegionHandler>> regions_2;\n  for (const auto& outputChannels : outputChannelsVec) {\n    regions_2.push_back(boost::make_unique<Triplet>(\n        outputChannels, positions(outputChannels, {0, 1, 2})));\n  }\n  PolarPointSourcePanner psp(std::move(regions_2));\n  REQUIRE(psp.numberOfOutputChannels() == positions.rows());\n  for (int i = 0; i < psp.numberOfOutputChannels(); ++i) {\n    Eigen::VectorXd pv_req =\n        Eigen::VectorXd::Zero(psp.numberOfOutputChannels());\n    pv_req(i) = 1.0;\n    auto pv = psp.handle(positions(i, {0, 1, 2}));\n    REQUIRE(pv != boost::none);\n    REQUIRE(pv->isApprox(pv_req));\n  }\n  REQUIRE(psp.handle(Eigen::Vector3d{0.0, -1.0, 0.0}) == boost::none);\n}\n\nEigen::VectorXi getChannelFlipVector(const Eigen::MatrixXd& spkPositions) {\n  Eigen::VectorXi channelFlipX = Eigen::VectorXi::Zero(spkPositions.rows());\n  Eigen::VectorXd spkNorm(spkPositions.rows());\n  Eigen::RowVector3d spkPositionFlipX;\n  Eigen::VectorXd::Index minIndex;\n  for (int i = 0; i < spkPositions.rows(); ++i) {\n    spkPositionFlipX << -spkPositions(i, 0), spkPositions(i, 1),\n        spkPositions(i, 2);\n    spkNorm = (spkPositions.rowwise() - spkPositionFlipX).rowwise().norm();\n    spkNorm.minCoeff(&minIndex);\n    channelFlipX(i) = static_cast<int>(minIndex);\n  }\n  return channelFlipX;\n}\n\nTEST_CASE(\"test_all_layouts\") {\n  for (const auto& l : loadLayouts()) {\n    Layout layout = l.withoutLfe();\n    Eigen::MatrixXd spkPositions(layout.positions().size(), 3);\n    for (int i = 0; i < spkPositions.rows(); ++i) {\n      spkPositions.row(i) = toCartesianVector3d(layout.positions().at(i));\n    }\n\n    SECTION(layout.name()) {\n      std::shared_ptr<PointSourcePanner> psp = configurePolarPanner(layout);\n      Eigen::VectorXi channelFlipX = getChannelFlipVector(spkPositions);\n\n      // calculate gains for every position on a grid\n      Eigen::VectorXd azimuths = Eigen::VectorXd::LinSpaced(21, -180.0, 180.0);\n      Eigen::VectorXd elevations = Eigen::VectorXd::LinSpaced(11, -90.0, 90.0);\n\n      std::vector<std::vector<Eigen::VectorXd>> pvs(61);\n      for (int a = 0; a < azimuths.size(); ++a) {\n        for (int e = 0; e < elevations.size(); ++e) {\n          double az = azimuths(a);\n          double el = elevations(e);\n          Eigen::VectorXd position = cartT(az, el, 1.0);\n          auto pv = psp->handle(position);\n          REQUIRE(pv != boost::none);\n          REQUIRE((pv->array() >= 0.0).any());\n\n          // check that the gains are normalised\n\n          // stereo is normalised only at the front, and at the back at -3dB\n          if (layout.name() == std::string(\"0+2+0\")) {\n            if (abs(az) <= 30.0 && el == 0.0) {\n              REQUIRE(pv->norm() == Approx(1.0));\n            } else if (abs(az) >= 110.0 && el == 0.0) {\n              REQUIRE(pv->norm() == Approx(sqrt(0.5)));\n            }\n          } else {\n            REQUIRE(pv->norm() == Approx(1.0));\n          }\n\n          // check that the velocity vector matches the source position\n          bool doPositionCheck = true;\n          if (layout.name() == std::string(\"0+2+0\")) {\n            if (abs(az) >= 30.0 || el != 0.0) {\n              doPositionCheck = false;\n            }\n          } else if (layout.name() == std::string(\"0+5+0\") ||\n                     layout.name() == std::string(\"2+5+0\") ||\n                     layout.name() == std::string(\"0+7+0\")) {\n            if (el != 0.0) {\n              doPositionCheck = false;\n            }\n          }\n          // only 9+10+3 has no remapping above the horizontal plane\n          // all layouts have remapping below the horizontal plane\n          if (layout.name() == std::string(\"9+10+3\")) {\n            if (el < 0.0) {\n              doPositionCheck = false;\n            }\n          } else if (el != 0.0) {\n            doPositionCheck = false;\n          }\n\n          if (doPositionCheck) {\n            Eigen::VectorXd vv = pv.get().transpose() * spkPositions;\n            vv /= vv.norm();\n            INFO(\"az: \" << az << \" != \" << azimuth(vv));\n            INFO(\"el: \" << el << \" != \" << elevation(vv));\n            REQUIRE(vv.isApprox(cart(az, el, 1.0)));\n          }\n\n          Eigen::Vector3d positionFlipX{-position(0), position(1), position(2)};\n          auto pvFlipX = psp->handle(positionFlipX);\n\n          REQUIRE(pv.get().isApprox(pvFlipX.get()(channelFlipX)));\n        }\n      }\n    }\n  }\n}\n\nTEST_CASE(\"configure_full_polar_panner\") {\n  SECTION(\"0+5+0\") {\n    auto layout = getLayout(\"0+5+0\").withoutLfe();\n    auto psp = configurePolarPanner(layout);\n    for (const auto& pair : generatePositionGains(layout)) {\n      auto pv = psp->handle(pair.first);\n      REQUIRE(pv != boost::none);\n      REQUIRE(pv.get().isApprox(pair.second));\n    }\n    SECTION(\"azimuth=15.0\") {\n      Eigen::VectorXd expectedGain =\n          Eigen::VectorXd::Zero(layout.channels().size());\n      expectedGain({0, 2}) << 1.0 / std::sqrt(2.0), 1.0 / std::sqrt(2.0);\n      auto pv = psp->handle(cart(15.0, 0.0, 1.0));\n      REQUIRE(pv != boost::none);\n      REQUIRE(pv.get().isApprox(expectedGain));\n    };\n    SECTION(\"azimuth=-15.0\") {\n      Eigen::VectorXd expectedGain =\n          Eigen::VectorXd::Zero(layout.channels().size());\n      expectedGain({1, 2}) << 1.0 / std::sqrt(2.0), 1.0 / std::sqrt(2.0);\n      auto pv = psp->handle(cart(-15.0, 0.0, 1.0));\n      REQUIRE(pv != boost::none);\n      REQUIRE(pv.get().isApprox(expectedGain));\n    };\n  };\n  SECTION(\"2+5+0\") {\n    auto layout = getLayout(\"2+5+0\").withoutLfe();\n    auto psp = configurePolarPanner(layout);\n    for (const auto& pair : generatePositionGains(layout)) {\n      auto pv = psp->handle(pair.first);\n      REQUIRE(pv != boost::none);\n      REQUIRE(pv.get().isApprox(pair.second));\n    }\n  };\n  SECTION(\"4+5+0\") {\n    auto layout = getLayout(\"4+5+0\").withoutLfe();\n    auto psp = configurePolarPanner(layout);\n    for (const auto& pair : generatePositionGains(layout)) {\n      auto pv = psp->handle(pair.first);\n      REQUIRE(pv != boost::none);\n      REQUIRE(pv.get().isApprox(pair.second));\n    }\n  };\n  SECTION(\"4+5+1\") {\n    auto layout = getLayout(\"4+5+1\").withoutLfe();\n    auto psp = configurePolarPanner(layout);\n    for (const auto& pair : generatePositionGains(layout)) {\n      auto pv = psp->handle(pair.first);\n      REQUIRE(pv != boost::none);\n      REQUIRE(pv.get().isApprox(pair.second));\n    }\n  };\n  SECTION(\"3+7+0\") {\n    auto layout = getLayout(\"3+7+0\").withoutLfe();\n    auto psp = configurePolarPanner(layout);\n    for (const auto& pair : generatePositionGains(layout)) {\n      auto pv = psp->handle(pair.first);\n      REQUIRE(pv != boost::none);\n      REQUIRE(pv.get().isApprox(pair.second));\n    }\n  };\n  SECTION(\"4+9+0\") {\n    auto layout = getLayout(\"4+9+0\").withoutLfe();\n    auto psp = configurePolarPanner(layout);\n    for (const auto& pair : generatePositionGains(layout)) {\n      auto pv = psp->handle(pair.first);\n      REQUIRE(pv != boost::none);\n      REQUIRE(pv.get().isApprox(pair.second));\n    }\n  };\n  SECTION(\"9+10+3\") {\n    auto layout = getLayout(\"9+10+3\").withoutLfe();\n    auto psp = configurePolarPanner(layout);\n    for (const auto& pair : generatePositionGains(layout)) {\n      auto pv = psp->handle(pair.first);\n      REQUIRE(pv != boost::none);\n      REQUIRE(pv.get().isApprox(pair.second));\n    }\n  };\n  SECTION(\"0+7+0\") {\n    auto layout = getLayout(\"0+7+0\").withoutLfe();\n    auto psp = configurePolarPanner(layout);\n    for (const auto& pair : generatePositionGains(layout)) {\n      auto pv = psp->handle(pair.first);\n      REQUIRE(pv != boost::none);\n      REQUIRE(pv.get().isApprox(pair.second));\n    }\n  };\n  SECTION(\"4+7+0\") {\n    auto layout = getLayout(\"4+7+0\").withoutLfe();\n    auto psp = configurePolarPanner(layout);\n    for (const auto& pair : generatePositionGains(layout)) {\n      auto pv = psp->handle(pair.first);\n      REQUIRE(pv != boost::none);\n      REQUIRE(pv.get().isApprox(pair.second));\n    }\n  };\n};\n\nTEST_CASE(\"screen_loudspeaker_positions\") {\n  auto layout = getLayout(\"4+9+0\").withoutLfe();\n\n  SECTION(\"too wide\") {\n    SECTION(\"+\") {\n      for (auto& channel : layout.channels())\n        if (channel.name() == \"M+SC\") channel.polarPosition({40.0, 0.0, 1.0});\n      REQUIRE_THROWS_AS(configurePolarPanner(layout), not_implemented);\n    }\n    SECTION(\"-\") {\n      for (auto& channel : layout.channels())\n        if (channel.name() == \"M-SC\") channel.polarPosition({-40.0, 0.0, 1.0});\n      REQUIRE_THROWS_AS(configurePolarPanner(layout), not_implemented);\n    }\n  }\n\n  SECTION(\"not in range\") {\n    SECTION(\"+\") {\n      for (auto& channel : layout.channels())\n        if (channel.name() == \"M+SC\") channel.polarPosition({30.0, 0.0, 1.0});\n      REQUIRE_THROWS_AS(configurePolarPanner(layout), invalid_argument);\n    }\n\n    SECTION(\"-\") {\n      for (auto& channel : layout.channels())\n        if (channel.name() == \"M-SC\") channel.polarPosition({-30.0, 0.0, 1.0});\n      REQUIRE_THROWS_AS(configurePolarPanner(layout), invalid_argument);\n    }\n  }\n}\n\nTEST_CASE(\"hull\") {\n  for (auto& layoutFull : loadLayouts()) {\n    if (layoutFull.name() == \"0+2+0\") continue;\n    auto layout = layoutFull.withoutLfe();\n\n    SECTION(layout.name()) {\n      std::vector<Eigen::Vector3d> positionsReal;\n      std::vector<Eigen::Vector3d> positionsNominal;\n      std::set<int> virtualVerts;\n      Eigen::MatrixXd downmix;\n      std::tie(positionsReal, positionsNominal, virtualVerts, downmix) =\n          getAugmentedLayout(layout);\n\n      std::vector<Facet> facets_precomputed = FACETS.at(layout.name());\n\n      // check that we're not close to a tolerance that is too big or small\n      for (double tolerance : {1e-6, 1e-5, 1e-4}) {\n        SECTION(\"tol = \" + std::to_string(tolerance)) {\n          std::vector<Facet> facets_calculated =\n              convex_hull(positionsNominal, tolerance);\n\n          std::sort(facets_precomputed.begin(), facets_precomputed.end());\n          std::sort(facets_calculated.begin(), facets_calculated.end());\n\n          REQUIRE(facets_precomputed == facets_calculated);\n        }\n      }\n    }\n  }\n}\n\n#ifdef CATCH_CONFIG_ENABLE_BENCHMARKING\nTEST_CASE(\"hull_benchmark\", \"[.benchmark]\") {\n  auto layout = getLayout(\"9+10+3\").withoutLfe();\n\n  std::vector<Eigen::Vector3d> positionsReal, positionsNominal;\n  std::set<int> virtualVerts;\n  Eigen::MatrixXd downmix;\n  std::tie(positionsReal, positionsNominal, virtualVerts, downmix) =\n      getAugmentedLayout(layout);\n\n  BENCHMARK(\"hull 9+10+3\") { return convex_hull(positionsNominal); };\n}\n#endif\n", "meta": {"hexsha": "c18f3cd91246d961d2f45f9daeb8dea60cf81bb4", "size": 23628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/point_source_panner_tests.cpp", "max_stars_repo_name": "benjamin-weiss/libear", "max_stars_repo_head_hexsha": "dd62812f7cc0889d5b023eae3db82ede087d923c", "max_stars_repo_licenses": ["Apache-2.0"], "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/point_source_panner_tests.cpp", "max_issues_repo_name": "benjamin-weiss/libear", "max_issues_repo_head_hexsha": "dd62812f7cc0889d5b023eae3db82ede087d923c", "max_issues_repo_licenses": ["Apache-2.0"], "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/point_source_panner_tests.cpp", "max_forks_repo_name": "benjamin-weiss/libear", "max_forks_repo_head_hexsha": "dd62812f7cc0889d5b023eae3db82ede087d923c", "max_forks_repo_licenses": ["Apache-2.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.5979381443, "max_line_length": 80, "alphanum_fraction": 0.6152023024, "num_tokens": 7382, "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": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"EntropyRegularizedEisner\"\n\n#include <boost/test/unit_test.hpp>\nnamespace utf = boost::unit_test;\n\n#include <vector>\n\n#include \"diffdp/algorithm/eisner.h\"\n#include \"diffdp/math.h\"\n#include \"dynet/expr.h\"\n\n// using boost test with intolerance fails (too precise),\n// so let's just use the same test as in Dynet.\nbool check_grad(float g, float g_act)\n{\n    float f = std::fabs(g - g_act);\n    float m = std::max(std::fabs(g), std::fabs(g_act));\n    if (f > 0.01 && m > 0.f)\n        f /= m;\n\n    if (f > 0.01 || std::isnan(f))\n        return false;\n    else\n        return true;\n}\n\nBOOST_AUTO_TEST_CASE(test_softmax)\n{\n    int argc = 1;\n    char **argv;\n    dynet::initialize(argc, argv);\n\n    std::vector<float> input(10);\n    std::vector<float> output(10);\n    std::vector<float> input_grad(10);\n    std::vector<float> output_grad(10);\n    for (unsigned i = 0 ; i < input.size() ; ++i)\n    input.at(i) = i;\n\n    {\n        diffdp::softmax(output.begin(), input.begin(), input.size());\n\n        dynet::ComputationGraph cg;\n        auto e_output = dynet::softmax(dynet::input(cg, {10}, input));\n        auto dynet_output = as_vector(cg.forward(e_output));\n\n        for (unsigned i = 0 ; i < 10 ; ++i)\n            BOOST_CHECK(check_grad(output.at(i), dynet_output.at(i)));\n    }\n\n    for (unsigned input_id = 0 ; input_id < input.size() ; ++input_id)\n    {\n        for (unsigned output_id = 0 ; output_id < input.size() ; ++output_id)\n        {\n\n            // compute gradient\n\n            std::fill(input_grad.begin(), input_grad.end(), 0.f);\n            std::fill(output_grad.begin(), output_grad.end(), 0.f);\n            //std::fill(output.begin(), output.end(), 0.f);\n\n            diffdp::softmax(output.begin(), input.begin(), input.size());\n            output_grad.at(output_id) = 1.f;\n            diffdp::backprop_softmax(\n                    input_grad.begin(), output_grad.begin(),\n                    input.begin(), output.begin(),\n                    input.size()\n            );\n            const float computed_gradient = input_grad.at(input_id);\n\n            // dynet gradient\n            dynet::ComputationGraph cg;\n\n            auto e_input = dynet::input(cg, {10}, input);\n            auto e_softmax = dynet::softmax(e_input);\n            auto e_output = dynet::pick(e_softmax, output_id);\n            cg.forward(e_output);\n            cg.backward(e_output, true);\n\n            auto dynet_gradient_all = as_vector(e_input.gradient());\n            float dynet_gradient = dynet_gradient_all.at(input_id);\n\n            BOOST_CHECK(check_grad(computed_gradient, dynet_gradient));\n        }\n\n    }\n}", "meta": {"hexsha": "24e070b6c3eb7d78f1d415d937b064d1c4aa7f47", "size": 2660, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test-math.cpp", "max_stars_repo_name": "FilippoC/diffdp", "max_stars_repo_head_hexsha": "58ae35b171ddd54b778790bc64838890c0f8956f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2019-03-18T21:17:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:06:30.000Z", "max_issues_repo_path": "test/test-math.cpp", "max_issues_repo_name": "FilippoC/diffdp", "max_issues_repo_head_hexsha": "58ae35b171ddd54b778790bc64838890c0f8956f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test-math.cpp", "max_forks_repo_name": "FilippoC/diffdp", "max_forks_repo_head_hexsha": "58ae35b171ddd54b778790bc64838890c0f8956f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-12-10T15:04:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T17:41:57.000Z", "avg_line_length": 30.2272727273, "max_line_length": 77, "alphanum_fraction": 0.584962406, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.555635304646596}}
{"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": "#include <rviz_helper/kr_marker.hpp>\n#include <Eigen/Geometry>\n\nnamespace kr {\nnamespace viz {\nMarker &Marker::covariance(const geometry_msgs::PoseWithCovariance &pose_cov) {\n  Eigen::Matrix<double, 6, 6> cov;\n  for (int i = 0; i < 6; i++) {\n    for (int j = 0; j < 6; j++) {\n      cov(i, j) = pose_cov.covariance[(i * 6) + j];\n    }\n  }\n  covariance(cov.block<3,3>(0,0));\n  position(pose_cov.pose.position);\n  return *this;\n}\n\nMarker &Marker::covariance(const Eigen::Matrix3d &cov) {\n  //  we assume here that covariance is symmetric positive definite\n  Eigen::JacobiSVD<Eigen::Matrix3d> SVD = cov.jacobiSvd(Eigen::ComputeFullU);\n\n  Eigen::Matrix3d U = SVD.matrixU();  //  U == V in this case\n  Eigen::Vector3d S = SVD.singularValues();\n\n  //  U is a rotation matrix of the ellipse, convert to quaternion\n  Eigen::Quaterniond quat(U*U.determinant());\n  quat.normalize();\n\n  mark_.pose.orientation.w = quat.w();\n  mark_.pose.orientation.x = quat.x();\n  mark_.pose.orientation.y = quat.y();\n  mark_.pose.orientation.z = quat.z();\n\n  //  set scale\n  for (int i = 0; i < 3; i++) {\n    S[i] = std::sqrt(S[i]);\n  }\n  scale(S[0], S[1], S[2]);\n\n  return *this;\n}\n\n}  // namespace viz\n}  // namespace kr\n", "meta": {"hexsha": "2e2c689563230957efc7dcb391dfe3779d63f0bb", "size": 1196, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kr_viz/rviz_helper/src/marker_covariance.cpp", "max_stars_repo_name": "KumarRobotics/kr_utils", "max_stars_repo_head_hexsha": "049685a8fd9bb8a37490cafeda94b4ab652c829e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-10-12T01:59:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-19T05:03:26.000Z", "max_issues_repo_path": "kr_viz/rviz_helper/src/marker_covariance.cpp", "max_issues_repo_name": "KumarRobotics/kr_utils", "max_issues_repo_head_hexsha": "049685a8fd9bb8a37490cafeda94b4ab652c829e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-02-25T08:58:26.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-29T07:25:38.000Z", "max_forks_repo_path": "kr_viz/rviz_helper/src/marker_covariance.cpp", "max_forks_repo_name": "KumarRobotics/kr_utils", "max_forks_repo_head_hexsha": "049685a8fd9bb8a37490cafeda94b4ab652c829e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:39:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T05:03:30.000Z", "avg_line_length": 26.5777777778, "max_line_length": 79, "alphanum_fraction": 0.6387959866, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5556352985038665}}
{"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": "#include \"dense_solver.hpp\"\n#include <Eigen/Dense>\n#include <iostream>\n#include <stdexcept>\n\nstd::unique_ptr<dense_solver_interface> make_dense_solver(\n    const std::string& type) {\n  using std::make_unique;\n  using namespace Eigen;\n\n  if (type == \"PartialPivLU\")\n    return make_unique<dense_solver<PartialPivLU<MatrixXd>>>();\n  else if (type == \"FullPivLU\")\n    return make_unique<dense_solver<FullPivLU<MatrixXd>>>();\n  else if (type == \"HouseholderQR\")\n    return make_unique<dense_solver<HouseholderQR<MatrixXd>>>();\n  else if (type == \"ColPivHouseholderQR\")\n    return make_unique<dense_solver<ColPivHouseholderQR<MatrixXd>>>();\n  else if (type == \"FullPivHouseholderQR\")\n    return make_unique<dense_solver<FullPivHouseholderQR<MatrixXd>>>();\n  else if (type == \"CompleteOrthogonalDecomposition\")\n    return make_unique<\n        dense_solver<CompleteOrthogonalDecomposition<MatrixXd>>>();\n  else if (type == \"BDCSVD\")\n    return make_unique<dense_solver<BDCSVD<MatrixXd>>>();\n  else if (type == \"JacobiSVD\")\n    return make_unique<dense_solver<JacobiSVD<MatrixXd>>>();\n  else if (type == \"LLT\")\n    return make_unique<dense_solver<LLT<MatrixXd>>>();\n  else if (type == \"LDLT\")\n    return make_unique<dense_solver<LDLT<MatrixXd>>>();\n  else {\n    std::stringstream ss;\n    ss << \"Error: \" << __FILE__ << \": \" << __LINE__\n       << \"\\n  Invalid dense solver type found: \" << type\n       << \"\\n  Available types are:\\n\"\n       << \"    PartialPivLU,\\n\"\n       << \"    FullPivLU,\\n\"\n       << \"    HouseholderQR,\\n\"\n       << \"    ColPivHouseholderQR,\\n\"\n       << \"    FullPivHouseholderQR,\\n\"\n       << \"    CompleteOrthogonalDecomposition,\\n\"\n       << \"    BDCSVD,\\n\"\n       << \"    JacobiSVD,\\n\"\n       << \"    LLT,\\n\"\n       << \"    LDLT\" << std::endl;\n    throw std::invalid_argument(ss.str());\n  }\n}\n", "meta": {"hexsha": "df8a040fe3ec0f3c8a982c834fc83639e46422d9", "size": 1811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shohirose/eigen_solvers/dense_solver.cpp", "max_stars_repo_name": "shohirose/qiita", "max_stars_repo_head_hexsha": "ff8548762e1587b17eee32d3733283b8b1cc937b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shohirose/eigen_solvers/dense_solver.cpp", "max_issues_repo_name": "shohirose/qiita", "max_issues_repo_head_hexsha": "ff8548762e1587b17eee32d3733283b8b1cc937b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shohirose/eigen_solvers/dense_solver.cpp", "max_forks_repo_name": "shohirose/qiita", "max_forks_repo_head_hexsha": "ff8548762e1587b17eee32d3733283b8b1cc937b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-15T08:47:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:47:39.000Z", "avg_line_length": 36.22, "max_line_length": 71, "alphanum_fraction": 0.6416344561, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5556063102690696}}
{"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_EXPONENTIAL_HPP_INCLUDED\n#define BOOST_SIMD_EXPONENTIAL_HPP_INCLUDED\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-functions\n    @defgroup group-exponential Exponential functions\n\n    Those functions provide algorithms for computing exponentials\n    and logarithms.\n\n      <center>\n        |                      |                  |                  |                 |\n        |:--------------------:|:----------------:|:----------------:|:---------------:|\n        | @ref cbrt            | @ref exp10       | @ref exp2        | @ref exp        |\n        | @ref expm1           | @ref exprecneg   | @ref exprecnegc  | @ref expx2      |\n        | @ref log10           | @ref log2        | @ref log         | @ref log1p      |\n        | @ref nthroot         | @ref pow2        | @ref pow_abs     | @ref pow        |\n        | @ref significants    |                  |                  |                 |\n       </center>\n  **/\n\n} }\n\n#include <boost/simd/function/cbrt.hpp>\n#include <boost/simd/function/exp10.hpp>\n#include <boost/simd/function/exp2.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/expm1.hpp>\n#include <boost/simd/function/exprecnegc.hpp>\n#include <boost/simd/function/exprecneg.hpp>\n#include <boost/simd/function/expx2.hpp>\n#include <boost/simd/function/log10.hpp>\n#include <boost/simd/function/log2.hpp>\n#include <boost/simd/function/log.hpp>\n#include <boost/simd/function/log1p.hpp>\n#include <boost/simd/function/nthroot.hpp>\n#include <boost/simd/function/pow2.hpp>\n#include <boost/simd/function/pow_abs.hpp>\n#include <boost/simd/function/pow.hpp>\n#include <boost/simd/function/significants.hpp>\n\n#endif\n", "meta": {"hexsha": "277a86fddb2a5a392220f9b6e6492bb423428dfb", "size": 2077, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/exponential.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/exponential.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/exponential.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 37.0892857143, "max_line_length": 100, "alphanum_fraction": 0.5281656235, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5556063097493634}}
{"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_CARTESIAN_UNIFORM_POINT_DISTRIBUTION_TRIANGLE_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_RANDOM_STRATEGIES_CARTESIAN_UNIFORM_POINT_DISTRIBUTION_TRIANGLE_HPP\n\n#include <random>\n#include <cmath>\n\n#include <boost/geometry/arithmetic/arithmetic.hpp>\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/point_type.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace uniform_point_distribution {\n\n//The following strategy is suitable for rings or polygons of three points.\ntemplate\n<\n    typename Point,\n    typename DomainGeometry\n>\nstruct uniform_2d_cartesian_triangle\n{\nprivate:\n    typedef typename point_type<DomainGeometry>::type domain_point_type;\npublic:\n    uniform_2d_cartesian_triangle(DomainGeometry const& g) {}\n    bool equals(DomainGeometry const& l_domain,\n                DomainGeometry const& r_domain,\n                uniform_2d_cartesian_triangle const& r_strategy) const\n    {\n        return boost::geometry::equals(l_domain.domain(), r_domain.domain());\n    }\n\n    template<typename sample_type>\n    static Point map(domain_point_type const& p1,\n                     domain_point_type const& p2,\n                     domain_point_type const& p3,\n                     sample_type const& s1,\n                     sample_type const& s2)\n    {\n        Point out;\n        sample_type r1 = std::sqrt(s1);\n        set<0>(out, (1 - r1) * get<0>(p1)\n                  + ( r1 * (1 - s2) ) * get<0>(p2)\n                  + ( s2 * r1 * get<0>(p3)));\n        set<1>(out, (1 - r1) * get<1>(p1)\n                  + ( r1 * (1 - s2) ) * get<1>(p2)\n                  + ( s2 * r1 * get<1>(p3)));\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        sample_type s1 = real_dist(g),\n                    s2 = real_dist(g);\n        return map(*d.begin(), *(d.begin() + 1), *(d.begin() + 2), s1, s2);\n    }\n    void reset(DomainGeometry const&) {};\n};\n\n}} // namespace strategy::uniform_point_distribution\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_RANDOM_STRATEGIES_CARTESIAN_UNIFORM_POINT_DISTRIBUTION_TRIANGLE_HPP\n", "meta": {"hexsha": "4daf0114ac2ad584ca1d20336553c2c141e898e0", "size": 2785, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/random/strategies/cartesian/uniform_point_distribution_triangle.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/cartesian/uniform_point_distribution_triangle.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/cartesian/uniform_point_distribution_triangle.hpp", "max_forks_repo_name": "BoostGSoC19/geometry", "max_forks_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T04:54:35.000Z", "avg_line_length": 33.5542168675, "max_line_length": 103, "alphanum_fraction": 0.6563734291, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5556063033411444}}
{"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": "#include <burst/integer/intpow.hpp>\n#include <burst/iterator/subsequence_iterator.hpp>\n#include <utility/io/vector.hpp>\n\n#include <doctest/doctest.h>\n\n#include <boost/range/iterator_range.hpp>\n\n#include <iterator>\n#include <list>\n#include <vector>\n\nTEST_SUITE(\"subsequence_iterator\")\n{\n    TEST_CASE(\"\u041a\u043e\u043d\u0435\u0446 \u0438\u0442\u0435\u0440\u0430\u0442\u043e\u0440\u0430 \u043f\u043e\u0434\u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u0435\u0439 \u0441\u043e\u0437\u0434\u0430\u0451\u0442\u0441\u044f \u0438\u0437 \u0435\u0433\u043e \u043d\u0430\u0447\u0430\u043b\u0430 \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \"\n        \"\u0441\u043f\u0435\u0446\u0438\u0430\u043b\u044c\u043d\u043e\u0439 \u043c\u0435\u0442\u043a\u0438-\u0438\u043d\u0434\u0438\u043a\u0430\u0442\u043e\u0440\u0430\")\n    {\n        const auto sequence = {'a', 'b', 'c'};\n\n        const auto subsequences_begin = burst::make_subsequence_iterator(sequence);\n        const auto subsequences_end =\n            burst::make_subsequence_iterator(burst::iterator::end_tag, subsequences_begin);\n\n        const auto expected_subsequences =\n            std::vector<std::vector<char>>\n            {\n                {'a'}, {'b'}, {'c'},\n                {'a', 'b'}, {'a', 'c'}, {'b', 'c'},\n                {'a', 'b', 'c'}\n            };\n        const auto subsequences = boost::make_iterator_range(subsequences_begin, subsequences_end);\n        CHECK(subsequences == expected_subsequences);\n    }\n\n    TEST_CASE(\"\u041f\u0443\u0441\u0442\u0430\u044f \u043f\u043e\u0434\u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u043d\u0435 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u043f\u043e\u0434\u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u0435\u0439\")\n    {\n        const auto sequence = std::vector<int>{};\n\n        const auto subsequences_begin = burst::make_subsequence_iterator(sequence);\n        const auto subsequences_end =\n            burst::make_subsequence_iterator(burst::iterator::end_tag, subsequences_begin);\n\n        CHECK(subsequences_begin == subsequences_end);\n    }\n\n    TEST_CASE(\"\u041e\u0434\u043d\u043e\u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043d\u0430\u044f \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u0440\u043e\u0432\u043d\u043e \u043e\u0434\u043d\u0443 \u043f\u043e\u0434\u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c, \u0440\u0430\u0432\u043d\u0443\u044e \"\n        \"\u0432\u0441\u0435\u0439 \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u0438\")\n    {\n        const auto sequence = std::list<int>{3};\n\n        const auto subsequence = burst::make_subsequence_iterator(sequence);\n        const auto subsequences_end =\n            burst::make_subsequence_iterator(burst::iterator::end_tag, subsequence);\n\n        const auto expected_subsequence = std::vector<int>{3};\n        CHECK(*subsequence == expected_subsequence);\n        CHECK(std::distance(subsequence, subsequences_end) == 1);\n    }\n\n    TEST_CASE(\"\u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u043e\u0434\u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u0435\u0439 \u0440\u0430\u0432\u043d\u043e 2 ^ N - 1, \u0433\u0434\u0435 N \u2014 \u0434\u043b\u0438\u043d\u0430 \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u0438\")\n    // \u041f\u0443\u0441\u0442\u0430\u044f \u043f\u043e\u0434\u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u0441\u0447\u0438\u0442\u0430\u0435\u0442\u0441\u044f \u043a\u043e\u043d\u0446\u043e\u043c, \u0430 \u043f\u043e\u0442\u043e\u043c\u0443 \u043d\u0435 \u0432\u0445\u043e\u0434\u0438\u0442 \u0432 \u0447\u0438\u0441\u043b\u043e \"\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0445\"\n    // \u043f\u043e\u0434\u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u0435\u0439.\n    {\n        const auto sequence = {1, 1, 1, 1, 1, 1};\n\n        const auto subsequences_begin = burst::make_subsequence_iterator(sequence);\n        const auto subsequences_end =\n            burst::make_subsequence_iterator(burst::iterator::end_tag, subsequences_begin);\n\n        const auto expected_subsequence_count = burst::intpow(2, sequence.size()) - 1;\n        CHECK(std::distance(subsequences_begin, subsequences_end) == expected_subsequence_count);\n    }\n}\n", "meta": {"hexsha": "9c2db6912e2715669ac24cdba5c4bf8f5836e045", "size": 2774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/burst/iterator/subsequence_iterator.cpp", "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": "test/burst/iterator/subsequence_iterator.cpp", "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": "test/burst/iterator/subsequence_iterator.cpp", "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": 37.4864864865, "max_line_length": 100, "alphanum_fraction": 0.6726748378, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5555360470388535}}
{"text": "// unit test file sinhc.hpp for the special functions test suite\r\n\r\n//  (C) Copyright Hubert Holin 2003. Permission to copy, use, modify, sell and\r\n//  distribute this software is granted provided this copyright notice appears\r\n//  in all copies. This software is provided \"as is\" without express or implied\r\n//  warranty, and with no claim as to its suitability for any purpose.\r\n\r\n\r\n#include <functional>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <complex>\r\n\r\n\r\n#include <boost/math/special_functions/sinhc.hpp>\r\n\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n\r\ntemplate<typename T>\r\nvoid    sinhc_pi_test(const char * more_blurb)\r\n{\r\n    using    ::std::abs;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    using    ::boost::math::sinhc_pi;\r\n    \r\n    \r\n    BOOST_MESSAGE(\"Testing sinhc_pi in the real domain for \"\r\n        << more_blurb << \".\");\r\n    \r\n    BOOST_CHECK_PREDICATE(::std::less_equal<T>(), 2,\r\n        (\r\n            abs(sinhc_pi<T>(static_cast<T>(0))-static_cast<T>(1)),\r\n            numeric_limits<T>::epsilon()\r\n        ));\r\n}\r\n\r\n\r\ntemplate<typename T>\r\nvoid    sinhc_pi_complex_test(const char * more_blurb)\r\n{\r\n    using    ::std::abs;\r\n    using    ::std::sin;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    using    ::boost::math::sinhc_pi;\r\n    \r\n    \r\n    BOOST_MESSAGE(\"Testing sinhc_pi in the complex domain for \"\r\n        << more_blurb << \".\");\r\n    \r\n    BOOST_CHECK_PREDICATE(::std::less_equal<T>(), 2,\r\n        (\r\n            abs(sinhc_pi<T>(::std::complex<T>(0, 1))-\r\n                ::std::complex<T>(sin(static_cast<T>(1)))),\r\n            numeric_limits<T>::epsilon()\r\n        ));\r\n}\r\n\r\n\r\nvoid    sinhc_pi_manual_check()\r\n{\r\n    using    ::boost::math::sinhc_pi;\r\n    \r\n    \r\n    BOOST_MESSAGE(\"sinc_pi\");\r\n    \r\n    for    (int i = 0; i <= 100; i++)\r\n    {\r\n        BOOST_MESSAGE( ::std::setw(15)\r\n                    << sinhc_pi<float>(static_cast<float>(i-50)/\r\n                                                static_cast<float>(50))\r\n                    << ::std::setw(15)\r\n                    << sinhc_pi<double>(static_cast<double>(i-50)/\r\n                                                static_cast<double>(50))\r\n                    << ::std::setw(15)\r\n                    << sinhc_pi<long double>(static_cast<long double>(i-50)/\r\n                                                static_cast<long double>(50)));\r\n    }\r\n    \r\n    BOOST_MESSAGE(\" \");\r\n}\r\n    \r\n\r\n", "meta": {"hexsha": "22c90a9db7e67e967b3260a7ae586ec6ddf58252", "size": 2429, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/sinhc_test.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/sinhc_test.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/math/special_functions/sinhc_test.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2921348315, "max_line_length": 80, "alphanum_fraction": 0.5236722931, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5555360445182219}}
{"text": "#include <iostream>\n#include <fstream>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include \"headers/util.h\"\n#include \"headers/rmat.h\"\n#include \"headers/matutil.h\"\n#include \"headers/matrix_wrapper.h\"\n#include \"headers/timer.h\"\n\nusing namespace std;\nusing namespace boost::numeric::ublas;\n\n// constexpr size_t N = 20000;\n// constexpr size_t N_EDGES = 4000000;\nconstexpr size_t N = 1000;\nconstexpr size_t N_EDGES = 25500;\n\ntemplate <class T>\ninline void saveToFile(const string &name, T *mat, timer *t) {\n  string fileName = \"data/benchmark/\" + name + \".csv\";\n  ofstream ofs;\n  ofs.open(fileName, ios::trunc);\n  t->start();\n  will::matutil::writeAdjMatrix(*mat, ofs);\n  t->stop();\n}\n\ntemplate <class T>\ninline void runWrappedBenchmark(const RmatConfig &cfg, const string &shortname,\n                                bool parallel = false, bool useMutex = false) {\n  string name = (parallel ? \"par_\" : \"seq_\") + shortname;\n  cout << \"Running \" << name << \" benchmark\" << endl;\n  timer t1, t2, t3;\n  t1.start();\n  T *w = new T(N, N, 0, useMutex);\n  t1.stop();\n  t2.start();\n  if (parallel) rmat<T>(w, N_EDGES, cfg);\n  else\n    rmatSeq<T>(w, N_EDGES, cfg);\n  t2.stop();\n  saveToFile<T>(name, w, &t3);\n  cout << \"Took \" << t1.get_total() << \" to allocate\" << endl;\n  cout << \"Took \" << t2.get_total() << \" to run RMAT\" << endl;\n  cout << \"Took \" << t3.get_total() << \" to save to file\" << endl;\n}\n\ninline void runListRmat(const RmatConfig &cfg, const string &shortname,\n                                bool parallel = true) {\n  if (parallel != true)\n    cout << \"WARNING: no sequential implementation yet\" << endl;\n  string name = (parallel ? \"par_\" : \"seq_\") + shortname;\n  cout << \"Running \" << name << \" benchmark\" << endl;\n  timer t1, t2, t3;\n  t1.start();\n  std::list<Edge> l;\n  t1.stop();\n  t2.start();\n  l = listRmat(N, N_EDGES, cfg);\n  t2.stop();\n  EdgeList el(&l, N);\n  saveToFile<EdgeList>(name, &el, &t3);\n  cout << \"Took \" << t1.get_total() << \" to allocate\" << endl;\n  cout << \"Took \" << t2.get_total() << \" to run RMAT\" << endl;\n  cout << \"Took \" << t3.get_total() << \" to save to file\" << endl;\n}\n\nint main() {\n  const RmatConfig cfg(0.57, 0.19, 0.19);\n\n  cout << \"===== Running sequential benchmarks =====\" << endl;\n  runWrappedBenchmark<MatrixWrapper<AdjMatrix>>(cfg, \"boost-mat\", false);\n  // runWrappedBenchmark<MatrixWrapper<CompAdjMat>>(cfg, \"compressed-mat\", false);\n  runWrappedBenchmark<MatrixWrapper<SparseAdjMat>>(cfg, \"sparse-mat\", false);\n  runWrappedBenchmark<CustomMatrix>(cfg, \"custom-mat\", false);\n\n  cout << \"===== Running parallel benchmarks =====\" << endl;\n  runWrappedBenchmark<MatrixWrapper<AdjMatrix>>(cfg, \"boost-mat\", true);\n  // runWrappedBenchmark<MatrixWrapper<CompAdjMat>>(cfg, \"compressed-mat-mut\",\n                                                //  true, true);\n  runWrappedBenchmark<MatrixWrapper<SparseAdjMat>>(cfg, \"sparse-mat-mut\",\n                                                 true, true);\n  runWrappedBenchmark<CustomMatrix>(cfg, \"custom-mat\", true);\n  runListRmat(cfg, \"custom-list\");\n\n  cout << \"Done!\" << endl;\n  // {\n  //   timer t;\n  //   MatrixWrapper<AdjMatrix> *w = new MatrixWrapper<AdjMatrix>(50000, 50000);\n  //   RmatConfig cfg(0.57, 0.19, 0.19);\n  //   t.start();\n  //   rmatSeq<AdjMatrix>(w, 505571000, cfg);\n  //   t.stop();\n  //   cout << w->getMat() << endl;\n  //   cout << \"Took: \" << t.get_total() << endl;\n  // }\n\n  // {\n  //   timer t;\n  //   RmatConfig cfg(0.57, 0.19, 0.19);\n  //   t.start();\n  //   std::list<Edge> res = listRmat(30000, 50557100, cfg);\n  //   t.stop();\n  //   cout << res.size() << endl;\n  //   cout << \"Took: \" << t.get_total() << endl;\n  // }\n\n\n  // will::matutil::writeAdjMatrix(*w, std::cout);\n  // std::cout << m << std::endl;\n  // MatrixWrapper<CompAdjMat> w(10, 10);\n  // w.insert(3, 3, 9);\n  // w.set(1, 1, 9);\n  // cout << static_cast<int>(w.get(3, 3)) << endl;\n  // m = w.getMat();\n  // will::matutil::writeAdjMatrix(*m, std::cout);\n}\n", "meta": {"hexsha": "a7d1e0f2b5f29c704508f4b0c8ab6b64241dbbf8", "size": 3972, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/benchmark.cpp", "max_stars_repo_name": "willshiao/cs260-rmat", "max_stars_repo_head_hexsha": "d7103e0a643976ce1553b9e674468c1d40fbaf72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-16T21:08:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-16T21:11:04.000Z", "max_issues_repo_path": "src/benchmark.cpp", "max_issues_repo_name": "willshiao/cs260-rmat", "max_issues_repo_head_hexsha": "d7103e0a643976ce1553b9e674468c1d40fbaf72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/benchmark.cpp", "max_forks_repo_name": "willshiao/cs260-rmat", "max_forks_repo_head_hexsha": "d7103e0a643976ce1553b9e674468c1d40fbaf72", "max_forks_repo_licenses": ["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.1, "max_line_length": 82, "alphanum_fraction": 0.5944108761, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5555360445182219}}
{"text": "// -----------------------------------------------------------------------\r\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\r\n//\r\n// Copyright (c) German Cancer Research Center (DKFZ),\r\n// Software development for Integrated Diagnostics and Therapy (SIDT).\r\n// ALL RIGHTS RESERVED.\r\n// See rttbCopyright.txt or\r\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html\r\n//\r\n// This software is distributed WITHOUT ANY WARRANTY; without even\r\n// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\r\n// PURPOSE.  See the above copyright notices for more information.\r\n//\r\n//------------------------------------------------------------------------\r\n\r\n#include <boost/make_shared.hpp>\r\n#include <boost/shared_ptr.hpp>\r\n\r\n#include \"litCheckMacros.h\"\r\n\r\n#include \"rttbBaseType.h\"\r\n#include \"rttbBaseTypeModels.h\"\r\n#include \"rttbBioModel.h\"\r\n#include \"rttbDVH.h\"\r\n#include \"rttbTCPLQModel.h\"\r\n#include \"rttbNTCPLKBModel.h\"\r\n#include \"rttbNTCPRSModel.h\"\r\n#include \"rttbBaseTypeModels.h\"\r\n#include \"rttbBioModelCurve.h\"\r\n#include \"rttbInvalidParameterException.h\"\r\n#include \"rttbBioModelScatterPlots.h\"\r\n\r\nnamespace rttb\r\n{\r\n\tnamespace testing\r\n\t{\r\n\r\n\t\ttypedef core::DVH::DataDifferentialType DataDifferentialType;\r\n\r\n\t\t/*! @brief RTBioModelTest. TCP calculated using a DVH PTV and LQ Model. NTCP tested using 3 Normal Tissue DVHs and LKB/RS Model.\r\n\t\tTCPLQ:\r\n\t\t1) test constructors (values as expected?)\r\n\t\t2) test init (calcTCPxxx)\r\n\t\t3) test set/get<Values>\r\n\r\n\t\tNTCP (LKB):\r\n\t\t1) test constructors (values as expected?)\r\n\t\t2) test init (calcxxx)\r\n\t\t3) test set/get<Values>\r\n\r\n\t\tNTCP (RS):\r\n\t\t1) test constructors (values as expected?)\r\n\t\t2) test init (calcxxx)\r\n\t\t3) test set/get<Values>\r\n\t\t*/\r\n\t\tint BioModelTest(int argc, char* argv[])\r\n\t\t{\r\n\t\t\tPREPARE_DEFAULT_TEST_REPORTING;\r\n\r\n\t\t\t//generate artificial DVH and corresponding statistical values\r\n\t\t\tDoseTypeGy binSize = DoseTypeGy(0.1);\r\n\t\t\tDoseVoxelVolumeType voxelVolume = 8;\r\n\r\n\t\t\tDataDifferentialType aDataDifferential;\r\n\r\n\t\t\tDoseCalcType value = 0;\r\n\t\t\tDVHVoxelNumber numberOfVoxels = 0;\r\n\r\n\t\t\t// creat default values\r\n\t\t\tfor (int i = 0; i < 98; i++)\r\n\t\t\t{\r\n\t\t\t\tvalue = 0;\r\n\t\t\t\tnumberOfVoxels += value;\r\n\t\t\t\taDataDifferential.push_back(value);\r\n\t\t\t}\r\n\r\n\t\t\taDataDifferential.push_back(10);\r\n\t\t\taDataDifferential.push_back(20);\r\n\r\n\t\t\tconst IDType structureID = \"myStructure\";\r\n\t\t\tconst IDType doseID = \"myDose\";\r\n\t\t\tconst IDType voxelizationID = \"myVoxelization\";\r\n\r\n\t\t\tcore::DVH::Pointer dvhPtr = boost::make_shared<core::DVH>(aDataDifferential, binSize,\r\n\t\t\t                               voxelVolume, structureID,\r\n\t\t\t                               doseID, voxelizationID);\r\n\r\n\t\t\t//test TCP LQ Model\r\n\t\t\tmodels::BioModelParamType alpha = 0.35;\r\n\t\t\tmodels::BioModelParamType beta = 0.023333333333333;\r\n\t\t\tmodels::BioModelParamType roh = 10000000;\r\n\t\t\tint numFractions = 8;\r\n\r\n\t\t\tDoseTypeGy normalizationDose = 50;\r\n\r\n\t\t\t//1) test constructors (values as expected?)\r\n\t\t\trttb::models::TCPLQModel tcplq = rttb::models::TCPLQModel();\r\n\t\t\tCHECK_EQUAL(0, tcplq.getAlphaMean());\r\n\t\t\tCHECK_EQUAL(0, tcplq.getAlphaBeta());\r\n\t\t\tCHECK_EQUAL(0, tcplq.getRho());\r\n\t\t\tCHECK_EQUAL(0, tcplq.getValue());\r\n\r\n\r\n\t\t\ttcplq = rttb::models::TCPLQModel(dvhPtr, roh, numFractions, alpha / beta, alpha, 0.08);\r\n\t\t\tCHECK_EQUAL(alpha, tcplq.getAlphaMean());\r\n\t\t\tCHECK_EQUAL(alpha / beta, tcplq.getAlphaBeta());\r\n\t\t\tCHECK_EQUAL(roh, tcplq.getRho());\r\n\t\t\tCHECK_EQUAL(0, tcplq.getValue());\r\n\r\n\r\n\t\t\ttcplq = rttb::models::TCPLQModel();\r\n\t\t\tCHECK_EQUAL(0, tcplq.getAlphaMean());\r\n\t\t\tCHECK_EQUAL(0, tcplq.getAlphaBeta());\r\n\t\t\tCHECK_EQUAL(0, tcplq.getRho());\r\n\t\t\tCHECK_EQUAL(0, tcplq.getValue());\r\n\r\n\t\t\ttcplq = rttb::models::TCPLQModel(dvhPtr, alpha, beta, roh, numFractions);\r\n\t\t\tCHECK_EQUAL(alpha, tcplq.getAlphaMean());\r\n\t\t\tCHECK_EQUAL(alpha / beta, tcplq.getAlphaBeta());\r\n\t\t\tCHECK_EQUAL(roh, tcplq.getRho());\r\n\t\t\tCHECK_EQUAL(0, tcplq.getValue());\r\n\r\n\t\t\t//2) test init (calcTCPxxx)\r\n\t\t\tCHECK_NO_THROW(tcplq.init(1));\r\n\r\n\t\t\t//3) test set/get<Values>\r\n\t\t\tCHECK_EQUAL(0, tcplq.getValue());\r\n\t\t\tCHECK_NO_THROW(tcplq.setParameters(alpha, 10, roh, 0.08));\r\n\t\t\tCHECK_EQUAL(10, tcplq.getAlphaBeta());\r\n\t\t\tCHECK_EQUAL(0.08, tcplq.getAlphaVariance());\r\n\t\t\tCHECK_EQUAL(alpha, tcplq.getAlphaMean());\r\n\t\t\tCHECK_EQUAL(roh, tcplq.getRho());\r\n\r\n\t\t\tCHECK_NO_THROW(models::getCurveDoseVSBioModel(tcplq, normalizationDose));\r\n\r\n\t\t\tstd::vector<models::BioModelParamType> aParameterVector;\r\n\t\t\taParameterVector.push_back(alpha + 0.02);\r\n\t\t\tCHECK_THROW_EXPLICIT(tcplq.setParameterVector(aParameterVector), core::InvalidParameterException);\r\n\t\t\taParameterVector.push_back(0.06);\r\n\t\t\taParameterVector.push_back(8);\r\n\t\t\taParameterVector.push_back(roh / 10);\r\n\t\t\tCHECK_NO_THROW(tcplq.setParameterVector(aParameterVector));\r\n\t\t\tCHECK_EQUAL(8, tcplq.getAlphaBeta());\r\n\t\t\tCHECK_EQUAL(0.06, tcplq.getAlphaVariance());\r\n\t\t\tCHECK_EQUAL(alpha + 0.02, tcplq.getAlphaMean());\r\n\t\t\tCHECK_EQUAL(roh / 10, tcplq.getRho());\r\n\r\n\t\t\tfor (int i = 0; i < 4; i++)\r\n\t\t\t{\r\n\t\t\t\tCHECK_NO_THROW(tcplq.setParameterByID(i, models::BioModelParamType(i)));\r\n\t\t\t}\r\n\r\n\t\t\tCHECK_THROW_EXPLICIT(tcplq.setParameterByID(4, 4.0), core::InvalidParameterException);\r\n\r\n\t\t\tCHECK_EQUAL(0, tcplq.getParameterID(\"alphaMean\"));\r\n\t\t\tCHECK_EQUAL(0, tcplq.getAlphaMean());\r\n\t\t\tCHECK_EQUAL(1, tcplq.getParameterID(\"alphaVariance\"));\r\n\t\t\tCHECK_EQUAL(1, tcplq.getAlphaVariance());\r\n\t\t\tCHECK_EQUAL(2, tcplq.getParameterID(\"alpha_beta\"));\r\n\t\t\tCHECK_EQUAL(2, tcplq.getAlphaBeta());\r\n\t\t\tCHECK_EQUAL(3, tcplq.getParameterID(\"rho\"));\r\n\t\t\tCHECK_EQUAL(3, tcplq.getRho());\r\n\r\n\r\n\t\t\t//test NTCPLKBModel\r\n\t\t\t//1) test constructors (values as expected?)\r\n\t\t\tmodels::BioModelParamType aVal = 10;\r\n\t\t\tmodels::BioModelParamType mVal = 0.16;\r\n\t\t\tmodels::BioModelParamType d50Val = 35;\r\n\t\t\tCHECK_NO_THROW(rttb::models::NTCPLKBModel());\r\n\t\t\trttb::models::NTCPLKBModel lkb = rttb::models::NTCPLKBModel();\r\n\t\t\tCHECK_EQUAL(0, lkb.getA());\r\n\t\t\tCHECK_EQUAL(0, lkb.getM());\r\n\t\t\tCHECK_EQUAL(0, lkb.getD50());\r\n\t\t\tCHECK_EQUAL(0, lkb.getValue());\r\n\t\t\tCHECK_NO_THROW(rttb::models::NTCPLKBModel(dvhPtr, d50Val, mVal, aVal));\r\n\t\t\tlkb = rttb::models::NTCPLKBModel(dvhPtr, d50Val, mVal, aVal);\r\n\t\t\tCHECK_EQUAL(0, lkb.getValue());\r\n\t\t\tCHECK_EQUAL(dvhPtr, lkb.getDVH());\r\n\t\t\tCHECK_EQUAL(aVal, lkb.getA());\r\n\t\t\tCHECK_EQUAL(mVal, lkb.getM());\r\n\t\t\tCHECK_EQUAL(d50Val, lkb.getD50());\r\n\r\n\t\t\t//2) test init (calcxxx)\r\n\t\t\tCHECK_NO_THROW(lkb.init(1));\r\n\t\t\tlkb.getValue();\r\n\r\n\t\t\t//3) test set/get<Values>\r\n\t\t\tlkb = rttb::models::NTCPLKBModel();\r\n\t\t\tCHECK_EQUAL(0, lkb.getA());\r\n\t\t\tCHECK_EQUAL(0, lkb.getM());\r\n\t\t\tCHECK_EQUAL(0, lkb.getD50());\r\n\t\t\tlkb.setDVH(dvhPtr);\r\n\t\t\tCHECK_EQUAL(dvhPtr, lkb.getDVH());\r\n\t\t\tlkb.setA(aVal);\r\n\t\t\tCHECK_EQUAL(aVal, lkb.getA());\r\n\t\t\tlkb.setM(mVal);\r\n\t\t\tCHECK_EQUAL(mVal, lkb.getM());\r\n\t\t\tlkb.setD50(d50Val);\r\n\t\t\tCHECK_EQUAL(d50Val, lkb.getD50());\r\n\r\n\t\t\tCHECK_NO_THROW(models::getCurveEUDVSBioModel(lkb));\r\n\r\n\t\t\taParameterVector.clear();\r\n\t\t\taParameterVector.push_back(d50Val + 5);\r\n\t\t\tCHECK_THROW_EXPLICIT(lkb.setParameterVector(aParameterVector), core::InvalidParameterException);\r\n\t\t\taParameterVector.push_back(mVal + 0.2);\r\n\t\t\taParameterVector.push_back(aVal + 0.5);\r\n\t\t\tCHECK_NO_THROW(lkb.setParameterVector(aParameterVector));\r\n\t\t\tCHECK_EQUAL(aVal + 0.5, lkb.getA());\r\n\t\t\tCHECK_EQUAL(mVal + 0.2, lkb.getM());\r\n\t\t\tCHECK_EQUAL(d50Val + 5, lkb.getD50());\r\n\r\n\t\t\tfor (int i = 0; i < 3; i++)\r\n\t\t\t{\r\n\t\t\t\tCHECK_NO_THROW(lkb.setParameterByID(i, models::BioModelParamType(i)));\r\n\t\t\t}\r\n\r\n\t\t\tCHECK_THROW_EXPLICIT(lkb.setParameterByID(3, 4.0), core::InvalidParameterException);\r\n\r\n\t\t\tCHECK_EQUAL(0, lkb.getParameterID(\"d50\"));\r\n\t\t\tCHECK_EQUAL(0, lkb.getD50());\r\n\t\t\tCHECK_EQUAL(1, lkb.getParameterID(\"m\"));\r\n\t\t\tCHECK_EQUAL(1, lkb.getM());\r\n\t\t\tCHECK_EQUAL(2, lkb.getParameterID(\"a\"));\r\n\t\t\tCHECK_EQUAL(2, lkb.getA());\r\n\r\n\t\t\t//test NTCPRSModel\r\n\t\t\t//1) test constructors (values as expected?)\r\n\t\t\tCHECK_NO_THROW(rttb::models::NTCPRSModel());\r\n\t\t\tmodels::BioModelParamType gammaVal = 1.7;\r\n\t\t\tmodels::BioModelParamType sVal = 1;\r\n\t\t\tCHECK_NO_THROW(rttb::models::NTCPRSModel(dvhPtr, d50Val, gammaVal, sVal));\r\n\t\t\trttb::models::NTCPRSModel rs = rttb::models::NTCPRSModel(dvhPtr, d50Val, gammaVal, sVal);\r\n\t\t\tCHECK_EQUAL(dvhPtr, rs.getDVH());\r\n\t\t\tCHECK_EQUAL(d50Val, rs.getD50());\r\n\t\t\tCHECK_EQUAL(gammaVal, rs.getGamma());\r\n\t\t\tCHECK_EQUAL(sVal, rs.getS());\r\n\r\n\t\t\trs = rttb::models::NTCPRSModel();\r\n\t\t\tCHECK_EQUAL(0, rs.getGamma());\r\n\t\t\tCHECK_EQUAL(0, rs.getS());\r\n\t\t\tCHECK_EQUAL(0, rs.getD50());\r\n\r\n\t\t\t//3) test set/get<Values>\r\n\t\t\trs.setDVH(dvhPtr);\r\n\t\t\tCHECK_EQUAL(dvhPtr, rs.getDVH());\r\n\t\t\trs.setD50(d50Val);\r\n\t\t\tCHECK_EQUAL(d50Val, rs.getD50());\r\n\t\t\trs.setGamma(gammaVal);\r\n\t\t\tCHECK_EQUAL(gammaVal, rs.getGamma());\r\n\t\t\trs.setS(sVal);\r\n\t\t\tCHECK_EQUAL(sVal, rs.getS());\r\n\r\n\t\t\t//2) test init (calcxxx)\r\n\t\t\tCHECK_NO_THROW(rs.init(1));\r\n\r\n\t\t\t//3) test set/get<Values> continued\r\n\t\t\taParameterVector.clear();\r\n\t\t\taParameterVector.push_back(d50Val + 5);\r\n\t\t\tCHECK_THROW_EXPLICIT(rs.setParameterVector(aParameterVector), core::InvalidParameterException);\r\n\t\t\taParameterVector.push_back(gammaVal + 0.2);\r\n\t\t\taParameterVector.push_back(sVal + 0.5);\r\n\t\t\tCHECK_NO_THROW(rs.setParameterVector(aParameterVector));\r\n\t\t\tCHECK_EQUAL(gammaVal + 0.2, rs.getGamma());\r\n\t\t\tCHECK_EQUAL(sVal + 0.5, rs.getS());\r\n\t\t\tCHECK_EQUAL(d50Val + 5, rs.getD50());\r\n\r\n\t\t\tfor (int i = 0; i < 3; i++)\r\n\t\t\t{\r\n\t\t\t\tCHECK_NO_THROW(rs.setParameterByID(i, models::BioModelParamType(i)));\r\n\t\t\t}\r\n\r\n\t\t\tCHECK_THROW_EXPLICIT(rs.setParameterByID(3, 4.0), core::InvalidParameterException);\r\n\r\n\t\t\tCHECK_EQUAL(0, rs.getParameterID(\"d50\"));\r\n\t\t\tCHECK_EQUAL(0, rs.getD50());\r\n\t\t\tCHECK_EQUAL(1, rs.getParameterID(\"gamma\"));\r\n\t\t\tCHECK_EQUAL(1, rs.getGamma());\r\n\t\t\tCHECK_EQUAL(2, rs.getParameterID(\"s\"));\r\n\t\t\tCHECK_EQUAL(2, rs.getS());\r\n\r\n\t\t\t//Scatter plot tests\r\n\t\t\tCHECK_NO_THROW(models::getScatterPlotVary1Parameter(tcplq, 0, alpha, 0,\r\n\t\t\t               normalizationDose)); //variance=0, will be set to 1e-30\r\n\t\t\tCHECK_THROW_EXPLICIT(models::getScatterPlotVary1Parameter(tcplq, 0, alpha, alpha * 0.1, 0),\r\n\t\t\t                     core::InvalidParameterException);//normalisationdose=0\r\n\t\t\tCHECK_THROW_EXPLICIT(models::getScatterPlotVary1Parameter(tcplq, 0, alpha, alpha * 0.1,\r\n\t\t\t                     normalizationDose, 10000, 0, 0),\r\n\t\t\t                     core::InvalidParameterException);//maxDose-minDose=0\r\n\r\n\t\t\tRETURN_AND_REPORT_TEST_SUCCESS;\r\n\r\n\t\t}\r\n\r\n\t}//testing\r\n}//rttb", "meta": {"hexsha": "6f4e9be6b28c212f22de3ede40bacbb1fa83d1d2", "size": 10385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/models/BioModelTest.cpp", "max_stars_repo_name": "MIC-DKFZ/RTTB", "max_stars_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T12:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:43:02.000Z", "max_issues_repo_path": "testing/models/BioModelTest.cpp", "max_issues_repo_name": "MIC-DKFZ/RTTB", "max_issues_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/models/BioModelTest.cpp", "max_forks_repo_name": "MIC-DKFZ/RTTB", "max_forks_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T21:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T09:30:49.000Z", "avg_line_length": 34.9663299663, "max_line_length": 131, "alphanum_fraction": 0.6710640347, "num_tokens": 3057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5555047278660048}}
{"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": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"common/pixel_benchmark.h\"\n#include \"common/pixel_fast_rng.h\"\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/simd_intrinsics.hpp>\n\n//#define USE_MIPP\n#ifdef USE_MIPP\n#include \"mipp.h\"\n#endif\n\n#include <Eigen/Dense>\n#include \"xsimd/xsimd.hpp\"\n\n#ifdef _MSC_VER\n#define USE_SSE 1\n#endif\n\n#ifdef USE_SSE\n#include <xmmintrin.h> // SSE\n#endif\n\n#include \"pixel_simd.h\"\n\nfloat dotproduct1(size_t len, float* va, float* vb)\n{\n    float sum = 0;\n    for (size_t i=0; i<len; i++) {\n        sum += va[i] * vb[i];\n    }\n    return sum;\n}\n\n// OpenCV universal intrinsics based implementation\nfloat dotproduct2(size_t len, float* va, float* vb)\n{\n    size_t step = sizeof(cv::v_float32)/sizeof(float);\n    cv::v_float32 v_sum = cv::vx_setzero_f32();\n    size_t vec_size = len - len % step;\n    for (size_t i=0; i< vec_size; i+=step)\n    {\n        cv::v_float32 v1 = cv::vx_load(va+i);\n        cv::v_float32 v2 = cv::vx_load(vb+i);\n        v_sum += v1 * v2;\n    }\n\n    float sum = cv::v_reduce_sum(v_sum);\n\n    for (size_t i= vec_size; i<len; i++) {\n        sum += va[i] * vb[i];\n    }\n\n    return sum;\n}\n\n#ifdef __ARM_NEON\nfloat dotproduct3(size_t len, float* va, float* vb)\n{\n    const size_t step = 4; // 128 / sizeof(float)\n    size_t vec_size = len - len % step;\n    float32x4_t vres = vdupq_n_f32(0);\n    float32x4_t v1;\n    float32x4_t v2;\n    float32x4_t vtmp;\n    for (size_t i = 0; i < vec_size; i+=step) {\n        v1 = vld1q_f32(va + i);\n        v2 = vld1q_f32(vb + i);\n        vtmp = vmulq_f32(v1, v2);\n        vres = vaddq_f32(vtmp, vres);\n    }\n\n    float sum_lst[4];\n    vst1q_f32(sum_lst, vres);\n\n    float sum = 0;\n    for (size_t i = 0; i < step; i++) {\n        sum += sum_lst[i];\n    }\n    for (size_t i = vec_size; i < len; i++) {\n        sum += va[i] * vb[i];\n    }\n    return sum;\n}\n\nfloat dotproduct3_cache(size_t len, float* va, float* vb)\n{\n    int segments = len / 4;\n    int remain = len - (segments/4*4)*4;\n\n    float32x4_t partSum = vdupq_n_f32(0);\n    float32x4_t sum1 = vdupq_n_f32(0);\n    float32x4_t sum2 = vdupq_n_f32(0);\n    float32x4_t sum3 = vdupq_n_f32(0);\n    float32x4_t sum4 = vdupq_n_f32(0);\n    for (int i=0; i+3<segments; i+=4)\n    {\n        float32x4_t v11 = vld1q_f32(va);\n        float32x4_t v12 = vld1q_f32(vb);\n\n        float32x4_t v21 = vld1q_f32(va+4);\n        float32x4_t v22 = vld1q_f32(vb+4);\n\n        float32x4_t v31 = vld1q_f32(va+8);\n        float32x4_t v32 = vld1q_f32(vb+8);\n\n        float32x4_t v41 = vld1q_f32(va+12);\n        float32x4_t v42 = vld1q_f32(vb+12);\n\n        sum1 = vmlaq_f32(sum1, v11, v12);\n        sum2 = vmlaq_f32(sum2, v21, v22);\n        sum3 = vmlaq_f32(sum3, v31, v32);\n        sum4 = vmlaq_f32(sum4, v41, v42);\n\n        va += 16;\n        vb += 16;\n    }\n    partSum = sum1 + sum2 + sum3 + sum4;\n\n    for (int i=0; i<remain; i++) {\n        float32x4_t vector1Neon = vld1q_f32(va);\n        float32x4_t vector2Neon = vld1q_f32(vb);\n        partSum = vmlaq_f32(partSum, vector1Neon, vector2Neon);\n\n        va += 4;\n        vb += 4;\n    }\n\n    float sum = partSum[0] + partSum[1] + partSum[2] + partSum[3];\n\n    return sum;\n}\n#endif\n\n#ifdef USE_MIPP\n// MIPP based implementation\nfloat dotproduct4(size_t len, float* va, float* vb)\n{\n    constexpr int step = mipp::N<float>();\n    //printf(\"--- mipp::N<float>() is %d\\n\", mipp::N<float>());\n    size_t vec_size = len - len % step;\n    mipp::Reg<float> rc;\n    mipp::Reg<float> ra, rb;\n    rc.set0();\n    for (size_t i=0; i< vec_size; i+=step) {\n        ra.load(va + i);\n        rb.load(vb + i);\n        rc += ra * rb;\n    }\n\n    float sum = rc.sum();\n\n    for (size_t i= vec_size; i<len; i++) {\n        sum += va[i] * vb[i];\n    }\n\n    return sum;\n}\n#endif\n\n// Eigen based implementation\nfloat dotproduct5(size_t len, float* va, float* vb)\n{\n    Eigen::Map<Eigen::Matrix<float, 1, Eigen::Dynamic, Eigen::RowMajor>> vva(va, len);\n    Eigen::Map<Eigen::Matrix<float, 1, Eigen::Dynamic, Eigen::RowMajor>> vvb(vb, len);\n    float res = vva.dot(vvb);\n    return res;\n}\n\n// xsimd based implementation\nfloat dotproduct6(size_t len, float* va, float* vb)\n{\n    constexpr size_t simd_size = xsimd::simd_type<float>::size;\n    size_t vec_size = len - len % simd_size;\n\n    //xsimd::batch<float, simd_size> vres;\n    //for (size_t i = 0; i < simd_size; i++) {\n    //    vres[i] = 0;\n    //}\n    xsimd::batch<float, simd_size> vres(0.f);\n    for (size_t i=0; i<vec_size; i+=simd_size)\n    {\n        auto vva = xsimd::load_unaligned(va + i);\n        auto vvb = xsimd::load_unaligned(vb + i);\n        vres += vva * vvb;\n    }\n    float sum = 0;\n    for (size_t i = 0; i < simd_size; i++) {\n        sum += vres[i];\n    }\n    for (size_t i = vec_size; i < len; i++) {\n        sum += va[i] * vb[i];\n    }\n    return sum;\n}\n\n#ifdef USE_SSE\n// SSE based implementation\nfloat dotproduct7(size_t len, float* va, float* vb)\n{\n    const size_t step = 4; // 128 / sizeof(float)\n    size_t vec_size = len - len % step;\n    __m128 vacc = _mm_setzero_ps();\n    __m128 v1;\n    __m128 v2;\n    for (size_t i=0; i<vec_size; i+=step) {\n        v1 = _mm_loadu_ps(va + i);\n        v2 = _mm_loadu_ps(vb + i);\n        vacc = _mm_add_ps(_mm_mul_ps(v1, v2), vacc);\n    }\n\n    float sum_lst[step];\n    _mm_store_ps(sum_lst, vacc);\n\n    float sum = 0;\n    for (size_t i = 0; i < step; i++) {\n        sum += sum_lst[i];\n    }\n\n    for (size_t i = vec_size; i < len; i++) {\n        sum += va[i] * vb[i];\n    }\n    return sum;\n}\n#endif\n\n// pixel_simd based impl, for NEON/SSE/NONE-SIMD\nfloat dotproduct8(size_t len, float* va, float* vb)\n{\n    const size_t step = 4; // 128 / sizeof(float)\n    size_t vec_size = len - len % step;\n    v_float32x4 v1, v2;\n    v_float32x4 vres = vq_setzero_f32();\n    for (size_t i = 0; i < vec_size; i += step) {\n        v1 = vq_load_f32(va + i);\n        v2 = vq_load_f32(vb + i);\n        //vres = vq_add_f32(v_mul_f32(v1, v2), vres);\n        vres = vq_fmadd_f32(v1, v2, vres);\n    }\n    float sum_lst[step];\n    vq_store_f32(sum_lst, vres);\n    float sum = 0;\n    for (size_t i = 0; i < step; i++) {\n        sum += sum_lst[i];\n    }\n\n    for (size_t i = vec_size; i < len; i++) {\n        sum += va[i] * vb[i];\n    }\n    return sum;\n}\n\nstatic void opencv_simd_test()\n{\n    using namespace cv;\n#ifdef CV_SIMD\n    printf(\"CV_SIMD is : \" CVAUX_STR(CV_SIMD) \"\\n\");\n    printf(\"CV_SIMD_WIDTH is : \" CVAUX_STR(CV_SIMD_WIDTH) \"\\n\");\n    printf(\"CV_SIMD128 is : \" CVAUX_STR(CV_SIMD128) \"\\n\");\n    printf(\"CV_SIMD256 is : \" CVAUX_STR(CV_SIMD256) \"\\n\");\n    printf(\"CV_SIMD512 is : \" CVAUX_STR(CV_SIMD512) \"\\n\");\n#else\n    printf(\"CV_SIMD is NOT defined\\n\");\n#endif\n\n#ifdef CV_SIMD\n    printf(\"sizeof(v_uint8) = %d\\n\", (int)sizeof(v_uint8));\n    printf(\"sizeof(v_int32) = %d\\n\", (int)sizeof(v_int32));\n    printf(\"sizeof(v_float32) = %d\\n\", (int)sizeof(v_float32));\n#endif\n}\n\nint main2() {\n\n    float c1[4] = {12.0f,12.0f,12.0f,12.0f};\n    float c2[4] = {13.0f,12.0f,9.0f,12.0f};\n    float32x4_t t1,t2;\n    uint32x4_t rq;\n    t1 = vld1q_f32(c1);\n    t2 = vld1q_f32(c2);\n    rq = vceqq_f32(t1,t2);\n    printf(\"start\\n\");\n    for( int i = 0;i < 4; i++){\n        printf(\"%u\\n\",rq[i]);\n    }\n    printf(\"end\\n\");\n\n    return 0;\n}\n\nint main() {\n    //opencv_simd_test();\n\n    size_t len = 200000000; //200M\n    //size_t len = 9;\n    float* va = (float*)malloc(sizeof(float)*len);\n    float* vb = (float*)malloc(sizeof(float)*len);\n\n    g_state.a = 7767517;\n    double r_start = pixel_get_current_time();\n    for (size_t i=0; i<len; i++) {\n        va[i] = pixel_fast_random_float(-1.2, 1.2);\n        vb[i] = pixel_fast_random_float(-1.2, 1.2);\n    }\n    double r_cost = pixel_get_current_time() - r_start;\n    printf(\"time cost for random assign is %.6lf ms\\n\", r_cost);\n\n    double t_start, t_cost;\n    float res;\n\n    t_start = pixel_get_current_time();\n    res = dotproduct1(len, va, vb);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"impl1(Naive),\\tresult is %.6f, time cost is %.6lf ms\\n\", res, t_cost);\n\n    t_start = pixel_get_current_time();\n    res = dotproduct2(len, va, vb);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"impl2(OpenCV),\\tresult is %.6f, time cost is %.6lf ms\\n\", res, t_cost);\n\n#ifdef __ARM_NEON\n    t_start = pixel_get_current_time();\n    res = dotproduct3(len, va, vb);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"impl3(neon),\\tresult is %.6f, time cost is %.6lf ms\\n\", res, t_cost);\n#endif\n\n#ifdef USE_MIPP\n    t_start = pixel_get_current_time();\n    res = dotproduct4(len, va, vb);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"impl4(MIPP),\\tresult is %.6f, time cost is %.6lf ms\\n\", res, t_cost);\n#endif\n\n    t_start = pixel_get_current_time();\n    res = dotproduct5(len, va, vb);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"impl5(Eigen),\\tresult is %.6f, time cost is %.6lf ms\\n\", res, t_cost);\n\n    //t_start = pixel_get_current_time();\n    //res = dotproduct6(len, va, vb);\n    //t_cost = pixel_get_current_time() - t_start;\n    //printf(\"impl6(xsimd),\\tresult is %.6f, time cost is %.6lf ms\\n\", res, t_cost);\n\n#ifdef USE_SSE\n    t_start = pixel_get_current_time();\n    res = dotproduct7(len, va, vb);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"impl7(sse),\\tresult is %.6f, time cost is %.6lf ms\\n\", res, t_cost);\n#endif\n\n    t_start = pixel_get_current_time();\n    res = dotproduct8(len, va, vb);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"impl8(pixel),\\tresult is %.6f, time cost is %.6lf ms\\n\", res, t_cost);\n\n#if defined(PIXEL_NEON)\n    printf(\"defined PIXEL_NEON\\n\");\n#else\n    printf(\"not defined PIXEL_NEON\\n\");\n#endif\n\n    free(va);\n    free(vb);\n\n    return 0;\n}\n", "meta": {"hexsha": "f8346495dea8d9277a1202cb642199918b532605", "size": 9680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contrib/simd/main.cpp", "max_stars_repo_name": "zchrissirhcz/pixel", "max_stars_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T16:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:46:04.000Z", "max_issues_repo_path": "contrib/simd/main.cpp", "max_issues_repo_name": "zchrissirhcz/pixel", "max_issues_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-01-31T16:04:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T13:58:11.000Z", "max_forks_repo_path": "contrib/simd/main.cpp", "max_forks_repo_name": "zchrissirhcz/pixel", "max_forks_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:33:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T08:13:56.000Z", "avg_line_length": 26.0916442049, "max_line_length": 86, "alphanum_fraction": 0.5940082645, "num_tokens": 3327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.5554634846962648}}
{"text": "#include <cassert>\n#include <boost/contract.hpp>\n\nint\nfactorial (int n)\n{\n  int result;\n\n  boost::contract::check c (\n      boost::contract::function ()\n          .precondition (\n              [&]\n              {\n                BOOST_CONTRACT_ASSERT (n >= 0);  // Non-negative natural number.\n                BOOST_CONTRACT_ASSERT (n <= 12); // Max function input.\n              })\n          .postcondition (\n              [&]\n              {\n                BOOST_CONTRACT_ASSERT (result >= 1);\n                if (n < 2)\n                { // Select assertion.\n                  BOOST_CONTRACT_ASSERT (result == 1);\n                }\n                else\n                {\n                  // Assertions automatically disabled in other assertions.\n                  // Therefore, this postcondition can recursively call the\n                  // function without causing infinite recursion.\n                  BOOST_CONTRACT_ASSERT_AUDIT (n * factorial (n - 1) != 0);\n                }\n              }));\n\n  return n < 2 ? (result = 1) : (result = n * factorial (n - 1));\n}\n\nint\nmain ()\n{\n  return factorial (4) == 24 ? 0 : 1;\n}\n", "meta": {"hexsha": "e19ba5fa278daa058abd478fb2927c6a53cc29e9", "size": 1130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libboost-contract/tests/basics/driver.cpp", "max_stars_repo_name": "build2-packaging/boost", "max_stars_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-23T11:24:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T20:10:46.000Z", "max_issues_repo_path": "libboost-contract/tests/basics/driver.cpp", "max_issues_repo_name": "build2-packaging/boost", "max_issues_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libboost-contract/tests/basics/driver.cpp", "max_forks_repo_name": "build2-packaging/boost", "max_forks_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_forks_repo_licenses": ["BSL-1.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.9047619048, "max_line_length": 80, "alphanum_fraction": 0.4663716814, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.5554634755872138}}
{"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": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n\n//typedef boost::multiprecision::cpp_dec_float_50 rub_float;\ntypedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<64> > rub_float;\ntypedef boost::multiprecision::cpp_int rub_int;\ntypedef boost::multiprecision::uint128_t rub_uint_128;\n\nconst rub_float RUB_UINT = rub_float(1000000000000.0);\nconst rub_uint_128 RUB_INT_MAX = rub_uint_128((uint64_t)10000000000000000000ull);\n\ninline double rub_int_to_double(rub_int amount) {\n        rub_uint_128 amount_128 = amount.convert_to<rub_uint_128>();\n        //std::cout<<\"uint128_t amount:\" << amount_128 << std::endl;\n\n\tif(amount_128 < RUB_INT_MAX)\n\t{\n\t\tuint64_t int_amount = amount_128.convert_to<uint64_t>();\n\t\t//std::cout<< \"amount < RUB_DEFAULT_DECIMAL :\" << int_amount << std::endl;\n\t\tdouble ret = int_amount / 1000000000000.0;\n\t\t//std::cout<< \"****** return value:\" << ret << std::endl;\n\t\treturn ret;\n\t}\n\t//std::setprecision(std::numeric_limits<rub_float>::max_digits10);\n\t//std::cout<<\"# RUB int to double ==> rub_int:\" << amount << std::endl;\n\t//rub_float amount_float = amount_128.convert_to<rub_float>();\n\trub_float amount_float = rub_float(amount_128);\n\t//std::cout<<\"# RUB int to double ==> rub_float:\" << amount_float << std::endl;\n\trub_float amount_rub = amount_float / RUB_UINT;\n\t//std::cout<<\"#RUB int to double ==> amount_rub:\" << amount_rub << std::endl;\n\tdouble ret = amount_rub.convert_to<double>();\n\t//std::cout<<\"#RUB int to double ==> result:\" << ret << std::endl;\n\treturn ret;\n}\n", "meta": {"hexsha": "c985c6e3f509bbf2b9f11c14d590d6a77274180a", "size": 1608, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libwalletqt/rub_int_to_double.hpp", "max_stars_repo_name": "monero-rub/monero-gui", "max_stars_repo_head_hexsha": "ca2abbb1394b11f2dec9ecd197514f83f5bcaf81", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libwalletqt/rub_int_to_double.hpp", "max_issues_repo_name": "monero-rub/monero-gui", "max_issues_repo_head_hexsha": "ca2abbb1394b11f2dec9ecd197514f83f5bcaf81", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libwalletqt/rub_int_to_double.hpp", "max_forks_repo_name": "monero-rub/monero-gui", "max_forks_repo_head_hexsha": "ca2abbb1394b11f2dec9ecd197514f83f5bcaf81", "max_forks_repo_licenses": ["BSD-3-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.6666666667, "max_line_length": 91, "alphanum_fraction": 0.7232587065, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.555454187662055}}
{"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 <fstream>\n#include <iostream>\n#include <vector>\n\n#include <boost/timer.hpp>\n#include <opencv2/opencv.hpp>\n\n#include \"include/depth_predictor.h\"\n#include \"include/util/image_processor.h\"\n#include \"include/util/plotter.h\"\n#include \"include/util/reader.h\"\n\nusing namespace util;\nusing namespace dense_mapper;\n\n/**********************************************\n* \u672c\u7a0b\u5e8f\u6f14\u793a\u4e86\u5355\u76ee\u76f8\u673a\u5728\u5df2\u77e5\u8f68\u8ff9\u4e0b\u7684\u7a20\u5bc6\u6df1\u5ea6\u4f30\u8ba1\n* \u4f7f\u7528\u6781\u7ebf\u641c\u7d22 + NCC \u5339\u914d\u7684\u65b9\u5f0f\uff0c\u4e0e\u4e66\u672c\u7684 12.2 \u8282\u5bf9\u5e94\n* \u8bf7\u6ce8\u610f\u672c\u7a0b\u5e8f\u5e76\u4e0d\u5b8c\u7f8e\uff0c\u4f60\u5b8c\u5168\u53ef\u4ee5\u6539\u8fdb\u5b83\u2014\u2014\u6211\u5176\u5b9e\u5728\u6545\u610f\u66b4\u9732\u4e00\u4e9b\u95ee\u9898(\u8fd9\u662f\u501f\u53e3)\u3002\n***********************************************/\n\n// ------------------------------------------------------------------\n// parameters\nconst int border = 20;     // \u8fb9\u7f18\u5bbd\u5ea6\nconst int width = 640;     // \u56fe\u50cf\u5bbd\u5ea6\nconst int height = 480;    // \u56fe\u50cf\u9ad8\u5ea6\nconst double fx = 481.2;   // \u76f8\u673a\u5185\u53c2\nconst double fy = -480.0;  // WHY NEGATIVE?\nconst double cx = 319.5;\nconst double cy = 239.5;\nconst int ncc_window_size = 3;  // NCC \u53d6\u7684\u7a97\u53e3\u534a\u5bbd\u5ea6\nconst double min_cov = 0.1;     // \u6536\u655b\u5224\u5b9a\uff1a\u6700\u5c0f\u65b9\u5dee\nconst double max_cov = 10.;     // \u53d1\u6563\u5224\u5b9a\uff1a\u6700\u5927\u65b9\u5dee\n\nint main(int argc, char **argv) {\n  if (argc != 2) {\n    std::cout << \"Usage: dense_mapping path_to_test_dataset\" << std::endl;\n    return -1;\n  }\n\n  // \u4ece\u6570\u636e\u96c6\u8bfb\u53d6\u6570\u636e\n  std::vector<std::string> color_image_files;\n  std::vector<Sophus::SE3d> poses_Twc;\n  cv::Mat ref_depth;\n  Reader::ReadRemode(width, height, argv[1], &color_image_files, &poses_Twc,\n                     &ref_depth);\n  std::cout << \"read total \" << color_image_files.size() << \" files.\"\n            << std::endl;\n\n  DepthPredictor predictor(border, width, height, fx, fy, cx, cy,\n                           ncc_window_size, min_cov, max_cov);\n\n  // \u7b2c\u4e00\u5f20\u56fe\n  const cv::Mat ref = cv::imread(color_image_files[0], 0);  // gray-scale image\n  const Sophus::SE3d pose_ref_Twc = poses_Twc[0];           // reference pose\n  const double init_depth = 3.0;                            // \u6df1\u5ea6\u521d\u59cb\u503c\n  const double init_cov2 = 3.0;                             // \u65b9\u5dee\u521d\u59cb\u503c\n  cv::Mat depth(height, width, CV_64F, init_depth);         // \u6df1\u5ea6\u56fe\n  cv::Mat depth_cov2(height, width, CV_64F, init_cov2);     // \u6df1\u5ea6\u56fe\u65b9\u5dee\n\n  for (size_t index = 1; index < color_image_files.size(); ++index) {\n    std::cout << \"*** loop \" << index << \" ***\" << std::endl;\n    cv::Mat curr = cv::imread(color_image_files[index], 0);\n    if (curr.data == nullptr) {\n      continue;\n    }\n    Sophus::SE3d pose_curr_Twc = poses_Twc[index];\n\n    // \u5750\u6807\u8f6c\u6362\u5173\u7cfb\uff1a T_cw * T_wr = T_cr\n    Sophus::SE3d pose_T_cr = pose_curr_Twc.inverse() * pose_ref_Twc;\n    predictor.Update(ref, curr, pose_T_cr, &depth, &depth_cov2);\n    predictor.EvaludateDepth(ref_depth, depth);\n    Plotter::PlotDepth(ref_depth, depth);\n    cv::imshow(\"image\", curr);\n    cv::waitKey(1);\n  }\n\n  std::cout << \"estimation returns, saving depth map ...\" << std::endl;\n  cv::imwrite(\"depth.png\", depth);\n  std::cout << \"done.\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "91a75aaf85d0c5aa229818bd599147b40b26a8d8", "size": 2794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch12/dense_mono/app/dense_mapping.cpp", "max_stars_repo_name": "TongLing916/slambook2", "max_stars_repo_head_hexsha": "73adc5a0228d449d6eaa9e7de162a684e174d17e", "max_stars_repo_licenses": ["MIT"], "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/app/dense_mapping.cpp", "max_issues_repo_name": "TongLing916/slambook2", "max_issues_repo_head_hexsha": "73adc5a0228d449d6eaa9e7de162a684e174d17e", "max_issues_repo_licenses": ["MIT"], "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/app/dense_mapping.cpp", "max_forks_repo_name": "TongLing916/slambook2", "max_forks_repo_head_hexsha": "73adc5a0228d449d6eaa9e7de162a684e174d17e", "max_forks_repo_licenses": ["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.2619047619, "max_line_length": 79, "alphanum_fraction": 0.5926986399, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5553713032136424}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nnamespace FieldMath::detail \n{\n    // Scalar typedef\n    typedef double scalar;\n\n    // Dynamic Eigen typedefs\n    typedef Eigen::Matrix<scalar, -1,  1> VectorX;\n    typedef Eigen::Matrix<scalar,  1, -1> RowVectorX;\n    typedef Eigen::Matrix<scalar, -1, -1> MatrixX;\n\n    // 3D Eigen typedefs\n    typedef Eigen::Matrix<scalar, 3, 1> Vector3;\n    typedef Eigen::Matrix<scalar, 1, 3> RowVector3;\n    typedef Eigen::Matrix<scalar, 3, 3> Matrix3;\n}", "meta": {"hexsha": "8a75bc02092f99fcc328af319a81658c07353528", "size": 504, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/detail/Typedefs.hpp", "max_stars_repo_name": "GPMueller/mwe-expression-template", "max_stars_repo_head_hexsha": "05c6edec252c7aca29707321f96ecc0a57100275", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-12-24T13:36:23.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-24T13:36:23.000Z", "max_issues_repo_path": "include/detail/Typedefs.hpp", "max_issues_repo_name": "GPMueller/mwe-expression-template", "max_issues_repo_head_hexsha": "05c6edec252c7aca29707321f96ecc0a57100275", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/detail/Typedefs.hpp", "max_forks_repo_name": "GPMueller/mwe-expression-template", "max_forks_repo_head_hexsha": "05c6edec252c7aca29707321f96ecc0a57100275", "max_forks_repo_licenses": ["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.2, "max_line_length": 53, "alphanum_fraction": 0.6706349206, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5553713003005952}}
{"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 <iostream>\n#include <sstream>\n#include <time.h>\n#include <stdio.h>\n\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n#include <iostream>\n#include <thread>\n#include <unistd.h>\n#include <string.h>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/regex.hpp>\n\n#include <Eigen/Eigen>\n#include <AlignTrajectory.h>\n#include <Viewer.h>\n#include <pangolin/pangolin.h>\n\n\nusing namespace cv;\nusing namespace std;\n\nenum GTformat  { TUM, VISIM, ICLNUIM };\n\nbool readFiles(const std::string& strGroundTruth,\n               const std::string& strEstimate,\n               std::vector<std::pair<double, Eigen::Matrix4d>>& vGroundTruthTimed,\n               std::vector<std::pair<double, Eigen::Matrix4d>>& vEstimateTimed,\n               const std::string& strGTformat);\n\nEigen::Matrix3d quat2mat(float qx, float qy, float qz, float qw);\n\nint main(int argc, char* argv[])\n{\n    for(int i = 0; i < argc; ++i)\n        printf(\"Argument %d : %s\\n\", i, argv[i]);\n\n    if(argc < 4)\n    {\n        std::cout << \"USAGE: ./align [ground_truth_trajectory] [estime_trajectory] [dataset format: TUM, VISIM, ICLNUIM]\" << std::endl;\n        return 1;\n    }\n\n    std::string strGroundTruth = std::string(argv[1]);\n    std::string strEstimate    = std::string(argv[2]);\n    std::string strGTformat    = std::string(argv[3]);\n \n    int iDriftRange  = 1;   //for RPE evaluation, number of frames to evaluate the drift over\n\n    std::vector<std::pair<double, Eigen::Matrix4d>> vGroundTruthTimed;\n    std::vector<std::pair<double, Eigen::Matrix4d>> vEstimateTimed;\n    std::vector<std::pair<double, Eigen::Matrix4d>> vTransformedTimed;\n\n\n    \n    std::vector<Eigen::Matrix4d> vGroundTruth;\n    std::vector<Eigen::Matrix4d> vEstimate;\n    std::vector<Eigen::Matrix4d> vTransformed;\n\n    readFiles(strGroundTruth, strEstimate, vGroundTruthTimed, vEstimateTimed, strGTformat);\n\n    // calculte ATE \n    float ate=0;\n    AlignTrajectory align;\n     \n    bool bDoAssociation;\n    if(vGroundTruthTimed.size() == vEstimateTimed.size())\n        bDoAssociation = false;\n    else\n        bDoAssociation = true;\n\n\n    Eigen::Matrix4d Mat = align.calculateATE(vGroundTruthTimed, vEstimateTimed, ate, bDoAssociation);\n\n    std::cout << \"M is : \" << std::endl << Mat << std::endl;\n    std::cout << \"ATE is: \" << std::endl << ate << std::endl;\n\n    // generate the aligned trajectory\n    Eigen::Matrix3d scaledRotation = Mat.block<3,3>(0,0);\n    Eigen::Vector3d translation    = Mat.block<3,1>(0,3);\n    vTransformedTimed.clear();\n\n    for(int i = 0 ; i < vEstimateTimed.size(); i++)\n    {\n        std::pair<double, Eigen::Matrix4d> poseTimed;\n        poseTimed = std::make_pair(vEstimateTimed[i].first, (Mat.inverse())*vEstimateTimed[i].second);\n        vTransformedTimed.push_back(poseTimed);\n    }\n\n    // calculate RPE\n    int iDeltaFrames;\n    double  rpe_rmse;\n \n    std::vector<std::pair<double, Eigen::Matrix4d>>  rpe = align.calculateRPE(vGroundTruthTimed, vEstimateTimed, iDriftRange, rpe_rmse, bDoAssociation);\n    \n    if(!(rpe.size() == 0))\n    {\n        std::cout << \"RPE is: \" << std::endl << rpe_rmse << std::endl;\n\t\n\tofstream f;\n\tstring filename;;\n\tfilename = \"RGBDRPE.txt\";\n\tf.open(filename.c_str());\n\tf << fixed;\n\n\tfor (int i = 0; i < rpe.size(); i++)\n\t{\n\t\tEigen::Matrix4d poseEr = rpe[i].second;\n\t\tf << setprecision(6) <<  rpe[i].first\n\t           << setprecision(7) \n        \t   << \" \"\n        \t   << poseEr(0,3) << \" \"\n        \t   << poseEr(1,3) << \" \"\n        \t   << poseEr(2,3) << \" \"\n        \t   //<< q.x() << \" \" << q.y() << \" \" << q.z() << \" \" << q.w() \n\t\t   << endl;\n\t}\n\tf.close();\n    }\n    else\n        std::cout << \"RPE is: \" << std::endl << \"N.A.\" << std::endl;\n\n    // plot results\n    Viewer* mpViewer;\n    std::thread* mptViewer;\n\n    mpViewer = new Viewer(&vGroundTruthTimed, &vEstimateTimed, &vTransformedTimed);\n    mptViewer = new thread(&Viewer::Run, mpViewer);\n\n    getchar();\n    cout << \"Done!\" << endl;\n\n    if(mpViewer)\n    {\n        mpViewer->RequestStop();\n        while(!mpViewer->isStopped())\n            sleep(1);\n    }\n\n\n/*    if(mpViewer)\n        pangolin::BindToContext(\"Trajectory\");*/\n\n    return 0;\n}\n\nEigen::Matrix3d quat2mat(float qx, float qy, float qz, float qw)\n{\n    Eigen::Matrix3d rot;\n    \n    rot(0,0) = 1.0;\n    rot(0,1) = 0.0;\n    rot(0,2) = 0.0;\n\n    rot(1,0) = 0.0;\n    rot(1,1) = 1.0;\n    rot(1,2) = 0.0;\n\n    rot(2,0) = 0.0;\n    rot(2,1) = 0.0;\n    rot(2,2) = 1.0;\n\n    return rot;\n}\n\nbool readFiles(const std::string& strGroundTruth,\n               const std::string& strEstimate,\n               std::vector<std::pair<double, Eigen::Matrix4d>>& vGroundTruthTimed,\n               std::vector<std::pair<double, Eigen::Matrix4d>>& vEstimateTimed,\n               const std::string& strGTformat)\n{\n    std::ifstream gtFile(strGroundTruth);\n    std::ifstream estimateFile(strEstimate);\n\n    std::string line;\n    boost::smatch match;\n\n    if(strGTformat.compare(\"VISIM\") == 0)\n    {\n\t    while (std::getline(gtFile, line))\n\t    {\n\t\tif (line.size() == 0) {\n\t\tcontinue;\n\t\t}\n\t\telse if(boost::regex_match(line,match,boost::regex(\"^\\\\s*#.*$\")))\n\t\t{\n\t\tcontinue;\n\t\t}\n\t\telse if (boost::regex_match(line,match,boost::regex(\"^([0-9]+),+([-0-9.e]+),+([-0-9.e]+),+([-0-9.e]+),+([-0-9.e]+),+([-0-9.e]+),+([-0-9.e]+),+([-0-9.e]+).*\")))\n\t\t{\n                    double time =  std::stod(match[1]); \n\t\t    \n                    float tx =  std::stof(match[2]);\n\t\t    float ty =  std::stof(match[4]);\n\t\t    float tz =  std::stof(match[3]);\n\n\t\t    float qx =  std::stof(match[6]);\n\t\t    float qy =  std::stof(match[7]);\n\t\t    float qz =  std::stof(match[8]);\n\t\t    float qw =  std::stof(match[5]);\n\n\t\t    Eigen::Matrix3d rot = quat2mat(qx, qy, qz, qw);\n\n\t\t    Eigen::Matrix4d pose6d;\n\t\t    pose6d.block<3,3>(0,0) = rot;\n\t\t    pose6d.block<3,1>(0,3) << tx, ty, tz;\n\t\t    pose6d.block<1,4>(3,0) << 0.0, 0.0, 0.0, 1.0;\n\n                    std::pair<double, Eigen::Matrix4d> pose6dTimed (time, pose6d);\n\n\t\t    vGroundTruthTimed.push_back(pose6dTimed);\n\t\t }\n\t\t else\n\t\t {\n\t\t     std::cerr << \"Unknown line:\" << line << std::endl;\n\t\t     return false;\n\t\t }\n\t    }\n\t    std::cout << \"Number of ground truth poses: \" << vGroundTruthTimed.size() << std::endl;\n    }\n\n\n\n    if(strGTformat.compare(\"TUM\") == 0)\n    {\n\t    while (std::getline(gtFile, line))\n\t    {\n\t\tif (line.size() == 0) {\n\t\tcontinue;\n\t\t}\n\t\telse if(boost::regex_match(line,match,boost::regex(\"^\\\\s*#.*$\")))\n\t\t{\n\t\tcontinue;\n\t\t}\n                else if (boost::regex_match(line,match,boost::regex(\"^([0-9.e]+)\\\\s+([-0-9.e]+)\\\\s+([-0-9.e]+)\\\\s+([-0-9.e]+)\\\\s+([-0-9.e]+)\\\\s+([-0-9.e]+)\\\\s+([-0-9.e]+)\\\\s+([-0-9.e]+).*\")))\n\t\t{\n\n                    double time =  std::stod(match[1]); \n\n\t\t    float tx =  std::stof(match[2]);\n\t\t    float ty =  std::stof(match[3]);\n\t\t    float tz =  std::stof(match[4]);\n\n\t\t    float qx =  std::stof(match[5]);\n\t\t    float qy =  std::stof(match[6]);\n\t\t    float qz =  std::stof(match[7]);\n\t\t    float qw =  std::stof(match[8]);\n\n\t\t    Eigen::Matrix3d rot = quat2mat(qx, qy, qz, qw);\n\n\t\t    Eigen::Matrix4d pose6d;\n\t\t    pose6d.block<3,3>(0,0) = rot;\n\t\t    pose6d.block<3,1>(0,3) << tx, ty, tz;\n\t\t    pose6d.block<1,4>(3,0) << 0.0, 0.0, 0.0, 1.0;\n\n\t\t    //vGroundTruth.push_back(pose6d);\n\n                    std::pair<double, Eigen::Matrix4d> pose6dTimed (time, pose6d);\n\n\t\t    vGroundTruthTimed.push_back(pose6dTimed);\n\n\t\t }\n\t\t else\n\t\t {\n\t\t     std::cerr << \"Unknown line in reading groundtruth poses: \" << line << std::endl;\n\t\t     return false;\n\t\t }\n\t    }\n\t    std::cout << \"Number of ground truth poses: \" << vGroundTruthTimed.size() << std::endl;\n    }\n\n    while (std::getline(estimateFile, line))\n    {\n        if (line.size() == 0) {\n        continue;\n        }\n        else if(boost::regex_match(line,match,boost::regex(\"^\\\\s*#.*$\")))\n        {\n        continue;\n        }\n        else if (boost::regex_match(line,match,boost::regex(\"^([0-9.e]+)\\\\s+([-0-9.e]+)\\\\s+([-0-9.e]+)\\\\s+([-0-9.e]+)\\\\s+([-0-9.e]+)\\\\s+([-0-9.e]+)\\\\s+([-0-9.e]+)\\\\s+([-0-9.e]+).*\")))\n        {\n\n            double time =  std::stod(match[1]); \n\n            float tx =  std::stof(match[2]);\n            float ty =  std::stof(match[4]);\n            float tz =  std::stof(match[3]);\n\n            float qx =  std::stof(match[5]);\n            float qy =  std::stof(match[6]);\n            float qz =  std::stof(match[7]);\n            float qw =  std::stof(match[8]);\n\n            Eigen::Matrix3d rot = quat2mat(qx, qy, qz, qw);\n\n            Eigen::Matrix4d pose6d;\n            pose6d.block<3,3>(0,0) = rot;\n            pose6d.block<3,1>(0,3) << tx, ty, tz;\n            pose6d.block<1,4>(3,0) << 0.0, 0.0, 0.0, 1.0;\n\n//            vEstimate.push_back(pose6d);\n\n                    std::pair<double, Eigen::Matrix4d> pose6dTimed (time, pose6d);\n\n\t\t    vEstimateTimed.push_back(pose6dTimed);\n         }\n         else\n         {\n             std::cerr << \"Unknown line in reading estimated poses: \" << line << std::endl;\n             return false;\n         }\n    }\n\n\n    std::cout << \"Number of estimate poses: \" << vEstimateTimed.size() << std::endl;\n\n    return true;\n}\n", "meta": {"hexsha": "679a60b7cd4f8a3a86d729a7495e42f6baa5f663", "size": 9212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "SajadSaeediG/AlignTrajectory", "max_stars_repo_head_hexsha": "004fc0eaaf2806e9ee94bad94eb018501b048ff8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-08T07:47:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T07:47:09.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "SajadSaeediG/AlignTrajectory", "max_issues_repo_head_hexsha": "004fc0eaaf2806e9ee94bad94eb018501b048ff8", "max_issues_repo_licenses": ["MIT"], "max_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": "SajadSaeediG/AlignTrajectory", "max_forks_repo_head_hexsha": "004fc0eaaf2806e9ee94bad94eb018501b048ff8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-12-27T03:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T01:07:27.000Z", "avg_line_length": 28.0, "max_line_length": 191, "alphanum_fraction": 0.5535171515, "num_tokens": 2987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5553295989039431}}
{"text": "// Copyright (c) 2017 Franka Emika GmbH\n// Use of this source code is governed by the Apache-2.0 license, see LICENSE\n#include <franka/rate_limiting.h>\n\n#include <Eigen/Dense>\n\n#include <franka/control_tools.h>\n\nnamespace franka {\n\nnamespace {\n\nEigen::Vector3d limitRate(double max_velocity,\n                          double max_acceleration,\n                          double max_jerk,\n                          const Eigen::Vector3d& commanded_velocity,\n                          const Eigen::Vector3d& last_commanded_velocity,\n                          const Eigen::Vector3d& last_commanded_acceleration) {\n  // Differentiate to get jerk\n  Eigen::Vector3d commanded_jerk =\n      (((commanded_velocity - last_commanded_velocity) / kDeltaT) - last_commanded_acceleration) /\n      kDeltaT;\n\n  // Limit jerk and integrate to get desired acceleration\n  Eigen::Vector3d commanded_acceleration = last_commanded_acceleration;\n  if (commanded_jerk.norm() > kNormEps) {\n    commanded_acceleration += (commanded_jerk / commanded_jerk.norm()) *\n                              std::max(std::min(commanded_jerk.norm(), max_jerk), -max_jerk) *\n                              kDeltaT;\n  }\n\n  // Compute Euclidean distance to the max velocity vector that would be reached starting from\n  // last_commanded_velocity with the direction of the desired acceleration\n  Eigen::Vector3d unit_commanded_acceleration =\n      commanded_acceleration / commanded_acceleration.norm();\n  double dot_product = unit_commanded_acceleration.transpose() * last_commanded_velocity;\n  double distance_to_max_velocity =\n      -dot_product + std::sqrt(pow(dot_product, 2.0) - last_commanded_velocity.squaredNorm() +\n                               pow(max_velocity, 2.0));\n\n  // Compute safe acceleration limits\n  double safe_max_acceleration =\n      std::min((max_jerk / max_acceleration) * distance_to_max_velocity, max_acceleration);\n\n  // Limit acceleration and integrate to get desired velocities\n  Eigen::Vector3d limited_commanded_velocity = last_commanded_velocity;\n\n  if (commanded_acceleration.norm() > kNormEps) {\n    limited_commanded_velocity += unit_commanded_acceleration *\n                                  std::min(commanded_acceleration.norm(), safe_max_acceleration) *\n                                  kDeltaT;\n  }\n\n  return limited_commanded_velocity;\n}\n\n}  // anonymous namespace\n\nstd::array<double, 7> limitRate(const std::array<double, 7>& max_derivatives,\n                                const std::array<double, 7>& commanded_values,\n                                const std::array<double, 7>& last_commanded_values) {\n  if (!std::all_of(commanded_values.begin(), commanded_values.end(),\n                   [](double d) { return std::isfinite(d); })) {\n    throw std::invalid_argument(\"Commanding value is infinite or NaN.\");\n  }\n  std::array<double, 7> limited_values{};\n  for (size_t i = 0; i < 7; i++) {\n    double commanded_derivative = (commanded_values[i] - last_commanded_values[i]) / kDeltaT;\n    limited_values[i] =\n        last_commanded_values[i] +\n        std::max(std::min(commanded_derivative, max_derivatives[i]), -max_derivatives[i]) * kDeltaT;\n  }\n  return limited_values;\n}\n\ndouble limitRate(double max_velocity,\n                 double max_acceleration,\n                 double max_jerk,\n                 double commanded_velocity,\n                 double last_commanded_velocity,\n                 double last_commanded_acceleration) {\n  if (!std::isfinite(commanded_velocity)) {\n    throw std::invalid_argument(\"commanded_velocity is infinite or NaN.\");\n  }\n  // Differentiate to get jerk\n  double commanded_jerk =\n      (((commanded_velocity - last_commanded_velocity) / kDeltaT) - last_commanded_acceleration) /\n      kDeltaT;\n\n  // Limit jerk and integrate to get acceleration\n  double commanded_acceleration = last_commanded_acceleration +\n                                  std::max(std::min(commanded_jerk, max_jerk), -max_jerk) * kDeltaT;\n\n  // Compute acceleration limits\n  double safe_max_acceleration = std::min(\n      (max_jerk / max_acceleration) * (max_velocity - last_commanded_velocity), max_acceleration);\n  double safe_min_acceleration = std::max(\n      (max_jerk / max_acceleration) * (-max_velocity - last_commanded_velocity), -max_acceleration);\n\n  // Limit acceleration and integrate to get desired velocities\n  return last_commanded_velocity +\n         std::max(std::min(commanded_acceleration, safe_max_acceleration), safe_min_acceleration) *\n             kDeltaT;\n}\n\ndouble limitRate(double max_velocity,\n                 double max_acceleration,\n                 double max_jerk,\n                 double commanded_position,\n                 double last_commanded_position,\n                 double last_commanded_velocity,\n                 double last_commanded_acceleration) {\n  if (!std::isfinite(commanded_position)) {\n    throw std::invalid_argument(\"commanded_position is infinite or NaN.\");\n  }\n  return last_commanded_position +\n         limitRate(max_velocity, max_acceleration, max_jerk,\n                   (commanded_position - last_commanded_position) / kDeltaT,\n                   last_commanded_velocity, last_commanded_acceleration) *\n             kDeltaT;\n}\n\nstd::array<double, 7> limitRate(const std::array<double, 7>& max_velocity,\n                                const std::array<double, 7>& max_acceleration,\n                                const std::array<double, 7>& max_jerk,\n                                const std::array<double, 7>& commanded_velocities,\n                                const std::array<double, 7>& last_commanded_velocities,\n                                const std::array<double, 7>& last_commanded_accelerations) {\n  if (!std::all_of(commanded_velocities.begin(), commanded_velocities.end(),\n                   [](double d) { return std::isfinite(d); })) {\n    throw std::invalid_argument(\"commanded_velocities is infinite or NaN.\");\n  }\n  std::array<double, 7> limited_commanded_velocities{};\n\n  for (size_t i = 0; i < 7; i++) {\n    limited_commanded_velocities[i] =\n        limitRate(max_velocity[i], max_acceleration[i], max_jerk[i], commanded_velocities[i],\n                  last_commanded_velocities[i], last_commanded_accelerations[i]);\n  }\n  return limited_commanded_velocities;\n}\n\nstd::array<double, 7> limitRate(const std::array<double, 7>& max_velocity,\n                                const std::array<double, 7>& max_acceleration,\n                                const std::array<double, 7>& max_jerk,\n                                const std::array<double, 7>& commanded_positions,\n                                const std::array<double, 7>& last_commanded_positions,\n                                const std::array<double, 7>& last_commanded_velocities,\n                                const std::array<double, 7>& last_commanded_accelerations) {\n  if (!std::all_of(commanded_positions.begin(), commanded_positions.end(),\n                   [](double d) { return std::isfinite(d); })) {\n    throw std::invalid_argument(\"commanded_positions is infinite or NaN.\");\n  }\n  std::array<double, 7> limited_commanded_positions{};\n  for (size_t i = 0; i < 7; i++) {\n    limited_commanded_positions[i] = limitRate(\n        max_velocity[i], max_acceleration[i], max_jerk[i], commanded_positions[i],\n        last_commanded_positions[i], last_commanded_velocities[i], last_commanded_accelerations[i]);\n  }\n  return limited_commanded_positions;\n}\n\nstd::array<double, 6> limitRate(\n    double max_translational_velocity,\n    double max_translational_acceleration,\n    double max_translational_jerk,\n    double max_rotational_velocity,\n    double max_rotational_acceleration,\n    double max_rotational_jerk,\n    const std::array<double, 6>& O_dP_EE_c,          // NOLINT(readability-identifier-naming)\n    const std::array<double, 6>& last_O_dP_EE_c,     // NOLINT(readability-identifier-naming)\n    const std::array<double, 6>& last_O_ddP_EE_c) {  // NOLINT(readability-identifier-naming)\n  if (!std::all_of(O_dP_EE_c.begin(), O_dP_EE_c.end(), [](double d) { return std::isfinite(d); })) {\n    throw std::invalid_argument(\"O_dP_EE_c is infinite or NaN.\");\n  }\n  Eigen::Matrix<double, 6, 1> dx(O_dP_EE_c.data());\n  Eigen::Matrix<double, 6, 1> last_dx(last_O_dP_EE_c.data());\n  Eigen::Matrix<double, 6, 1> last_ddx(last_O_ddP_EE_c.data());\n\n  dx.head(3) << limitRate(max_translational_velocity, max_translational_acceleration,\n                          max_translational_jerk, dx.head(3), last_dx.head(3), last_ddx.head(3));\n  dx.tail(3) << limitRate(max_rotational_velocity, max_rotational_acceleration, max_rotational_jerk,\n                          dx.tail(3), last_dx.tail(3), last_ddx.tail(3));\n\n  std::array<double, 6> limited_values{};\n  Eigen::Map<Eigen::Matrix<double, 6, 1>>(&limited_values[0], 6, 1) = dx;\n  return limited_values;\n}\n\nstd::array<double, 16> limitRate(\n    double max_translational_velocity,\n    double max_translational_acceleration,\n    double max_translational_jerk,\n    double max_rotational_velocity,\n    double max_rotational_acceleration,\n    double max_rotational_jerk,\n    const std::array<double, 16>& O_T_EE_c,          // NOLINT(readability-identifier-naming)\n    const std::array<double, 16>& last_O_T_EE_c,     // NOLINT(readability-identifier-naming)\n    const std::array<double, 6>& last_O_dP_EE_c,     // NOLINT(readability-identifier-naming)\n    const std::array<double, 6>& last_O_ddP_EE_c) {  // NOLINT(readability-identifier-naming)\n  if (!std::all_of(O_T_EE_c.begin(), O_T_EE_c.end(), [](double d) { return std::isfinite(d); })) {\n    throw std::invalid_argument(\"O_T_EE_c is infinite or NaN.\");\n  }\n  if (!isHomogeneousTransformation(O_T_EE_c)) {\n    throw std::invalid_argument(\n        \"O_T_EE_c is invalid transformation matrix. Has to be column major!\");\n  }\n  Eigen::Matrix<double, 6, 1> dx;\n  Eigen::Affine3d commanded_pose(Eigen::Matrix4d::Map(O_T_EE_c.data()));\n  Eigen::Affine3d limited_commanded_pose = Eigen::Affine3d::Identity();\n  Eigen::Affine3d last_commanded_pose(Eigen::Matrix4d::Map(last_O_T_EE_c.data()));\n\n  // Compute translational velocity\n  dx.head(3) << (commanded_pose.translation() - last_commanded_pose.translation()) / kDeltaT;\n\n  // Compute rotational velocity\n  Eigen::AngleAxisd rot_difference(commanded_pose.linear() *\n                                   last_commanded_pose.linear().transpose());\n  dx.tail(3) << rot_difference.axis() * rot_difference.angle() / kDeltaT;\n\n  // Limit the rate of the twist\n  std::array<double, 6> commanded_O_dP_EE_c{};  // NOLINT(readability-identifier-naming)\n  Eigen::Map<Eigen::Matrix<double, 6, 1>>(&commanded_O_dP_EE_c[0], 6, 1) = dx;\n  commanded_O_dP_EE_c =\n      limitRate(max_translational_velocity, max_translational_acceleration, max_translational_jerk,\n                kFactorCartesianRotationPoseInterface * max_rotational_velocity,\n                kFactorCartesianRotationPoseInterface * max_rotational_acceleration,\n                kFactorCartesianRotationPoseInterface * max_rotational_jerk, commanded_O_dP_EE_c,\n                last_O_dP_EE_c, last_O_ddP_EE_c);\n  dx = Eigen::Matrix<double, 6, 1>(commanded_O_dP_EE_c.data());\n\n  // Integrate limited twist\n  limited_commanded_pose.translation() << last_commanded_pose.translation() + dx.head(3) * kDeltaT;\n  limited_commanded_pose.linear() << last_commanded_pose.linear();\n  if (dx.tail(3).norm() > kNormEps) {\n    Eigen::Matrix3d omega_skew;\n    Eigen::Vector3d w_norm(dx.tail(3) / dx.tail(3).norm());\n    double theta = kDeltaT * dx.tail(3).norm();\n    omega_skew << 0, -w_norm(2), w_norm(1), w_norm(2), 0, -w_norm(0), -w_norm(1), w_norm(0), 0;\n    // NOLINTNEXTLINE(readability-identifier-naming)\n    Eigen::Matrix3d R = Eigen::Matrix3d::Identity() + sin(theta) * omega_skew +\n                        (1.0 - cos(theta)) * (omega_skew * omega_skew);\n    limited_commanded_pose.linear() << R * last_commanded_pose.linear();\n  }\n\n  std::array<double, 16> limited_values{};\n  Eigen::Map<Eigen::Matrix4d>(&limited_values[0], 4, 4) = limited_commanded_pose.matrix();\n  return limited_values;\n}\n\n}  // namespace franka\n", "meta": {"hexsha": "4c78642d1477d21f87b1dae31416ee44af8602a5", "size": 12073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rate_limiting.cpp", "max_stars_repo_name": "archie1983/libfranka", "max_stars_repo_head_hexsha": "f1f46fb008a37eb0d1dba00c971ff7e5a7bfbfd3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 133.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T22:58:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T12:25:47.000Z", "max_issues_repo_path": "src/rate_limiting.cpp", "max_issues_repo_name": "archie1983/libfranka", "max_issues_repo_head_hexsha": "f1f46fb008a37eb0d1dba00c971ff7e5a7bfbfd3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2017-09-18T14:40:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T05:44:12.000Z", "max_forks_repo_path": "src/rate_limiting.cpp", "max_forks_repo_name": "archie1983/libfranka", "max_forks_repo_head_hexsha": "f1f46fb008a37eb0d1dba00c971ff7e5a7bfbfd3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 98.0, "max_forks_repo_forks_event_min_datetime": "2017-09-15T21:30:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:51:41.000Z", "avg_line_length": 47.9087301587, "max_line_length": 100, "alphanum_fraction": 0.6701731136, "num_tokens": 2966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5553295963877924}}
{"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  // \u5165\u6b21\u6570\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  // \u5165\u6b21\u6570\u304c\u30bc\u30ed\u306e\u3084\u3064\u3092\u96c6\u3081\u308b\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  // \u30bc\u30ed\u306e\u3084\u3064\u304b\u3089\u8ffd\u52a0\u3057\u3066\u304f\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  // \u9589\u8def\u304c\u3042\u308b\u3068\u5165\u6b21\u6570\u304c\u7d76\u5bfe\u30bc\u30ed\u306b\u306a\u3089\u306a\u3044\n  if (ret.size() != size) {\n    throw invalid_argument(\"\u9589\u8def\u304c\u3042\u308a\u307e\u3059\");\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": "/*\n@copyright Louis Dionne 2014\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/detail/assert.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/integer_list.hpp>\n#include <boost/hana/integral.hpp>\nusing namespace boost::hana;\nusing namespace literals;\n\n\nint main() {\n    //! [main]\n    BOOST_HANA_CONSTANT_ASSERT(\n        take_while(_ < 2_c, integer_list<int, 0, 1, 2, 3>) == integer_list<int, 0, 1>\n    );\n    //! [main]\n}\n", "meta": {"hexsha": "50db5d672ebe25ada4e9b391b7272513039a7def", "size": 553, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/list/take_while.cpp", "max_stars_repo_name": "rbock/hana", "max_stars_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T14:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-04T10:59:46.000Z", "max_issues_repo_path": "example/list/take_while.cpp", "max_issues_repo_name": "rbock/hana", "max_issues_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/list/take_while.cpp", "max_forks_repo_name": "rbock/hana", "max_forks_repo_head_hexsha": "2b76377f91a5ebe037dea444e4eaabba6498d3a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1363636364, "max_line_length": 85, "alphanum_fraction": 0.7016274864, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5552791745293483}}
{"text": "/*\n \n [begin_description]\n Test case for issue 189: \n Controlled Rosenbrock stepper fails to increase step size\n [end_description]\n\n Copyright 2016 Karsten Ahnert\n Copyright 2016 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#define BOOST_TEST_MODULE odeint_regression_189\n\n#include <boost/numeric/odeint.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/phoenix/core.hpp>\n#include <boost/phoenix/operator.hpp>\n\nusing namespace boost::numeric::odeint;\nnamespace phoenix = boost::phoenix;\n\ntypedef boost::numeric::ublas::vector< double > vector_type;\ntypedef boost::numeric::ublas::matrix< double > matrix_type;\n\nstruct stiff_system\n{\n    void operator()( const vector_type &x , vector_type &dxdt , double /* t */ )\n    {\n        dxdt[ 0 ] = -101.0 * x[ 0 ] - 100.0 * x[ 1 ];\n        dxdt[ 1 ] = x[ 0 ];\n    }\n};\n\nstruct stiff_system_jacobi\n{\n    void operator()( const vector_type & /* x */ , matrix_type &J , const double & /* t */ , vector_type &dfdt )\n    {\n        J( 0 , 0 ) = -101.0;\n        J( 0 , 1 ) = -100.0;\n        J( 1 , 0 ) = 1.0;\n        J( 1 , 1 ) = 0.0;\n        dfdt[0] = 0.0;\n        dfdt[1] = 0.0;\n    }\n};\n\n\nBOOST_AUTO_TEST_CASE( regression_189 )\n{\n    vector_type x( 2 , 1.0 );\n\n    size_t num_of_steps = integrate_const( make_dense_output< rosenbrock4< double > >( 1.0e-6 , 1.0e-6 ) ,\n            std::make_pair( stiff_system() , stiff_system_jacobi() ) ,\n            x , 0.0 , 50.0 , 0.01 ,\n            std::cout << phoenix::arg_names::arg2 << \" \" << phoenix::arg_names::arg1[0] << \"\\n\" );\n    // regression: number of steps should be 74\n    BOOST_CHECK_EQUAL( num_of_steps , 74 );\n    \n    vector_type x2( 2 , 1.0 );\n\n    size_t num_of_steps2 = integrate_const( make_dense_output< runge_kutta_dopri5< vector_type > >( 1.0e-6 , 1.0e-6 ) ,\n            stiff_system() , x2 , 0.0 , 50.0 , 0.01 ,\n            std::cout << phoenix::arg_names::arg2 << \" \" << phoenix::arg_names::arg1[0] << \"\\n\" );\n    \n    BOOST_CHECK_EQUAL( num_of_steps2 , 1531 );\n}\n", "meta": {"hexsha": "dbd88ac8078b3f62e8bcf5bc764e6c5bd6554c9a", "size": 2103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/odeint-v2/test/regression/regression_189.cpp", "max_stars_repo_name": "robertodr/odeint-autodiff", "max_stars_repo_head_hexsha": "a6bf8b07aa6b838c26b7b6a1336f7bf9026a449b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-21T10:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-21T10:05:51.000Z", "max_issues_repo_path": "external/odeint-v2/test/regression/regression_189.cpp", "max_issues_repo_name": "robertodr/odeint-autodiff", "max_issues_repo_head_hexsha": "a6bf8b07aa6b838c26b7b6a1336f7bf9026a449b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/odeint-v2/test/regression/regression_189.cpp", "max_forks_repo_name": "robertodr/odeint-autodiff", "max_forks_repo_head_hexsha": "a6bf8b07aa6b838c26b7b6a1336f7bf9026a449b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2083333333, "max_line_length": 119, "alphanum_fraction": 0.6195910604, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.5552791706774634}}
{"text": "#include \"CppUnitTest.h\"\n#include \"UnitTestAux.h\"\n#include \"../BVP/Utils/AuxUtils.h\"\n#include \"..\\BVP\\Problems\\TroeschProblem.h\"\n#include \"..\\BVP\\FunctionApproximation\\PointSimple.h\"\n#include \"..\\BVP\\MultipleShooting\\HybridMultipleShootingComponent.h\"\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"../BVP/Utils/AuxUtils.h\"\n#include \"../BVP/FunctionApproximation/InitialCondition.h\"\n\nusing namespace auxutils;\n\nusing namespace UnitTestAux;\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\ntypedef float_50_noet numTypeMp;\ntypedef double numType;\n\nnamespace GeneralTest\n{\n\tTEST_CLASS(MultipleShootingHybridTestUnit)\n\t{\n\tpublic:\n\t\t\n\t\tTEST_METHOD(MultipleShootingHybridTest)\n\t\t{\n\t\t\tTroeschProblem<numType> tp(20);\n\t\t\ttry\n\t\t\t{\n\t\t\t\tPointSimple<numType> ptLeft;\n\t\t\t\tptLeft.Argument  = 0;\n\t\t\t\tptLeft.Value  = 0;\n\n\t\t\t\tPointSimple<numType> ptRight;\n\t\t\t\tptRight.Argument  = 1;\n\t\t\t\tptRight.Value  = 1;\n\n\t\t\t\tHybridMultipleShootingComponent<numType> HMSComp(tp);\n\n\t\t\t\tbool succeeded;\n\t\t\t\tstd::vector<InitCondition<numType>> solution = HMSComp.Run(ptLeft, ptRight, 0.0001, succeeded);\n\n\t\t\t    Assert::IsTrue(succeeded, Message(\"Algorithm has not succeeded\"));\n\t\t\t\tauto startDerivativeDiff = abs(solution[0].Derivative - 1.64877350732915e-008); \n\t\t\t\tAssert::IsTrue(startDerivativeDiff <= 5e-20, Message(\"du(0) is different\" + auxutils::ToString(startDerivativeDiff)));\n\t\t\t\tauto finalDerivativeDiff = abs(solution[solution.size() - 1].Derivative - 22026.4657494062);\n\t\t\t\tAssert::IsTrue(finalDerivativeDiff <= 1e-10, Message(\"du(1) is different\" + auxutils::ToString(finalDerivativeDiff)));\n\t\t\t}\n\t\t\tcatch (exception e)\n\t\t\t{\n\t\t\t\tAssert::IsTrue(false, Message(e.what()));\n\n\t\t\t}\n\t\t\t// TODO: Your test code here\n\t\t}\n\n\t\tTEST_METHOD(MultipleShootingHybridTestMultiPrec)\n\t\t{\n\t\t\tTroeschProblem<numTypeMp> tp(20);\n\t\t\ttry\n\t\t\t{\n\t\t\t\tPointSimple<numTypeMp> ptLeft;\n\t\t\t\tptLeft.Argument  = 0;\n\t\t\t\tptLeft.Value  = 0;\n\n\t\t\t\tPointSimple<numTypeMp> ptRight;\n\t\t\t\tptRight.Argument  = 1;\n\t\t\t\tptRight.Value  = 1;\n\n\t\t\t\tHybridMultipleShootingComponent<numTypeMp> HMSComp(tp);\n\n\t\t\t\tbool succeeded;\n\t\t\t\tstd::vector<InitCondition<numTypeMp>> solution = HMSComp.Run(ptLeft, ptRight, (numTypeMp)1/50, succeeded);\n\n\t\t\t    Assert::IsTrue(succeeded, Message(\"Algorithm has not succeeded\"));\n\n\t\t\t\tauto startDerivativeDiff = abs(solution[0].Derivative - (numTypeMp)\"1.65428160979175801124447457829e-08\");\n\t\t\t\tAssert::IsTrue(startDerivativeDiff <= std::numeric_limits<numTypeMp>::epsilon(), \n\t\t\t\t\tMessage(\"du(0) is different \" + auxutils::ToString(solution[0].Derivative)+ \" \" + auxutils::ToString(startDerivativeDiff)));\n\n\t\t\t\tauto finalDerivativeDiff = abs(solution[solution.size() - 1].Derivative - (numTypeMp)\"22026.4657402382174165421786901\");\n\t\t\t\tAssert::IsTrue( finalDerivativeDiff <= 1e-24, \n\t\t\t\t\tMessage(\"du(1) is different \" + auxutils::ToString(solution[solution.size() - 1].Derivative) + \" \" + auxutils::ToString(finalDerivativeDiff)));\n\t\t\t}\n\t\t\tcatch (exception e)\n\t\t\t{\n\t\t\t\tAssert::IsTrue(false, Message(e.what()));\n\n\t\t\t}\n\t\t\t// TODO: Your test code here\n\t\t}\n\n\t};\n}", "meta": {"hexsha": "0d2b7df7436090f6393823ad997a4a38cd417843", "size": 3049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Software/GeneralTest/MultipleShootingHybridTestUnit.cpp", "max_stars_repo_name": "imathsoft/MathSoftDevelopment", "max_stars_repo_head_hexsha": "4c449f6e378a942cfc39081739ba4c0aa2dce4de", "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": "Software/GeneralTest/MultipleShootingHybridTestUnit.cpp", "max_issues_repo_name": "imathsoft/MathSoftDevelopment", "max_issues_repo_head_hexsha": "4c449f6e378a942cfc39081739ba4c0aa2dce4de", "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": "Software/GeneralTest/MultipleShootingHybridTestUnit.cpp", "max_forks_repo_name": "imathsoft/MathSoftDevelopment", "max_forks_repo_head_hexsha": "4c449f6e378a942cfc39081739ba4c0aa2dce4de", "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": 32.4361702128, "max_line_length": 148, "alphanum_fraction": 0.7172843555, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5552791692202022}}
{"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 <bits/stdc++.h>\n//#include <boost/multiprecision/cpp_int.hpp>\n//using namespace boost::multiprecision;\nusing namespace std;\ntypedef long long ll;\ntypedef vector <int> vi;\n\nint n, a[10010];\nint b[10010];\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    while(cin >> n, n){\n        ll cnt = 0;\n        a[0] = INT_MAX;\n        for(int i=1; i<=n; i++){\n            cin >> a[i], cnt += a[i];\n        }\n        sort(a+1, a+n+1, greater<int> ());\n        b[n] = a[n];\n        for(int i=n-1; i>=1; i--){\n            b[i] = b[i+1] + a[i];\n        }\n        b[n+1] = 0;\n        //for(int i=1; i<=n; i++) cout << a[i] << \" \"; cout << endl;\n        //for(int i=1; i<=n; i++) cout << b[i] << \" \"; cout << endl;\n        bool flag = true;\n        if(a[n] < 0 || cnt % 2)\n            flag = false;\n        int last = 0, sum;\n        for(int i=1; i<=n && flag; i++){\n            last += a[i];\n            int index = lower_bound(a+i+1, a+n+1, i, greater<int> ()) - a;\n            sum = b[index] + (index - i - 1) * (i);\n            if(last > (i)*(i-1) + sum)\n                flag = false;\n        }\n        if(flag)\n            cout << \"Possible\\n\";\n        else cout << \"Not possible\\n\";\n\n    }\n    return 0;\n}", "meta": {"hexsha": "f46c75b13404e663b6854a77ce3a04fa183cdcef", "size": 1303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/Graph Construction.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/Graph Construction.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/Graph Construction.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": 27.7234042553, "max_line_length": 74, "alphanum_fraction": 0.4351496546, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5552791578732786}}
{"text": "/*  _______________________________________________________________________\n\n    PECOS: Parallel Environment for Creation Of Stochastics\n    Copyright (c) 2011, Sandia National Laboratories.\n    This software is distributed under the GNU Lesser General Public License.\n    For more information, see the README file in the top Pecos directory.\n    _______________________________________________________________________ */\n\n#ifndef PECOS_GLOBAL_DEFS_H\n#define PECOS_GLOBAL_DEFS_H\n\n#include <iostream>\n#include <cfloat>  // for DBL_MIN, DBL_MAX\n#include <cmath>\n#include <cstdlib>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace Pecos {\n\n// --------------\n// Special values\n// --------------\n/// the value for PI used in various numerical routines\nconst double PI = boost::math::constants::pi<double>();\n\n/// special value returned by index() when entry not found\nconst size_t _NPOS = ~(size_t)0; // one's complement\n\n/// used in ostream data output functions\nconst int WRITE_PRECISION = 10;\n\n/// small value used for protecting division by zero, etc.; an alternative\n/// to DBL_MIN that is less likely to cause underflow/overflow when numbers\n/// larger than it are used in calculations\nconst double SMALL_NUMBER = 1.e-25;\n/// large value used as a surrogate for infinity in error traps; an alternative\n/// to DBL_MAX or inf that is less likely to cause underflow/overflow when used\n/// in subsequent calculations\nconst double LARGE_NUMBER = 1.e+50;\n\n// define special values for vector/matrix data copying modes\nenum { DEFAULT_COPY=0, SHALLOW_COPY, DEEP_COPY };\n\n// define special values for ExpansionConfigOptions::outputLevel\nenum { SILENT_OUTPUT, QUIET_OUTPUT, NORMAL_OUTPUT, VERBOSE_OUTPUT,\n       DEBUG_OUTPUT };\n\n// define special values for ranVarTypesX/U\nenum { NO_TYPE=0,\n       // continuous random variable types:\n       CONTINUOUS_DESIGN, STD_NORMAL, NORMAL, BOUNDED_NORMAL,\n       LOGNORMAL, BOUNDED_LOGNORMAL, STD_UNIFORM, UNIFORM, LOGUNIFORM,\n       TRIANGULAR, STD_EXPONENTIAL, EXPONENTIAL, STD_BETA, BETA, STD_GAMMA,\n       GAMMA, GUMBEL, FRECHET, WEIBULL, HISTOGRAM_BIN, INV_GAMMA,\n       CONTINUOUS_INTERVAL, CONTINUOUS_STATE, STOCHASTIC_EXPANSION,\n       // discrete random variable types:\n       POISSON, BINOMIAL, NEGATIVE_BINOMIAL, GEOMETRIC, HYPERGEOMETRIC,\n       HISTOGRAM_PT_INT, HISTOGRAM_PT_STRING, HISTOGRAM_PT_REAL };\n\n// define special values for secondaryACVarMapTargets/secondaryADVarMapTargets\nenum { NO_TARGET=0, CDV_LWR_BND, CDV_UPR_BND, DDRIV_LWR_BND, DDRIV_UPR_BND,\n       N_MEAN, N_STD_DEV, N_LWR_BND, N_UPR_BND, N_LOCATION, N_SCALE, LN_MEAN,\n       LN_STD_DEV, LN_LAMBDA, LN_ZETA, LN_ERR_FACT, LN_LWR_BND, LN_UPR_BND,\n       U_LWR_BND, U_UPR_BND, U_LOCATION, U_SCALE, LU_LWR_BND, LU_UPR_BND,\n       T_MODE, T_LWR_BND, T_UPR_BND, T_LOCATION, T_SCALE, E_BETA,\n       BE_ALPHA, BE_BETA, BE_LWR_BND, BE_UPR_BND, GA_ALPHA, GA_BETA,\n       GU_ALPHA, GU_BETA, F_ALPHA, F_BETA, W_ALPHA, W_BETA, IGA_ALPHA, IGA_BETA,\n       P_LAMBDA, BI_P_PER_TRIAL, BI_TRIALS, NBI_P_PER_TRIAL, NBI_TRIALS,\n       GE_P_PER_TRIAL, HGE_TOT_POP, HGE_SEL_POP, HGE_FAILED,\n       CSV_LWR_BND, CSV_UPR_BND, DSRIV_LWR_BND, DSRIV_UPR_BND };\n\n/// derived basis approximation types\nenum { NO_BASIS=0, //FOURIER_BASIS, EIGEN_BASIS,\n       GLOBAL_NODAL_INTERPOLATION_POLYNOMIAL,\n       PIECEWISE_NODAL_INTERPOLATION_POLYNOMIAL,\n       GLOBAL_HIERARCHICAL_INTERPOLATION_POLYNOMIAL,\n       PIECEWISE_HIERARCHICAL_INTERPOLATION_POLYNOMIAL,\n       GLOBAL_REGRESSION_ORTHOGONAL_POLYNOMIAL,\n       GLOBAL_PROJECTION_ORTHOGONAL_POLYNOMIAL,\n       GLOBAL_ORTHOGONAL_POLYNOMIAL };\n       //PIECEWISE_REGRESSION_ORTHOGONAL_POLYNOMIAL,\n       //PIECEWISE_PROJECTION_ORTHOGONAL_POLYNOMIAL,\n       //PIECEWISE_ORTHOGONAL_POLYNOMIAL };\n\n/// derived basis polynomial types (orthogonal polynomial order follows\n/// uncertain variable spec order of normal, uniform, exponential, beta, gamma)\nenum { NO_POLY=0, HERMITE_ORTHOG, LEGENDRE_ORTHOG, LAGUERRE_ORTHOG,\n       JACOBI_ORTHOG, GEN_LAGUERRE_ORTHOG, CHEBYSHEV_ORTHOG, NUM_GEN_ORTHOG,\n       LAGRANGE_INTERP, HERMITE_INTERP, PIECEWISE_LINEAR_INTERP,\n       PIECEWISE_QUADRATIC_INTERP, PIECEWISE_CUBIC_INTERP };\n\n/// integration rules within VPISparseGrid (1-12: CC through User-closed)\n/// and beyond (GOLUB_WELSCH, NEWTON_COTES)\nenum { NO_RULE=0, CLENSHAW_CURTIS, FEJER2, GAUSS_PATTERSON, GAUSS_LEGENDRE,\n       GAUSS_HERMITE, GEN_GAUSS_HERMITE, GAUSS_LAGUERRE, GEN_GAUSS_LAGUERRE,\n       GAUSS_JACOBI, GENZ_KEISTER, /*USER_OPEN, USER_CLOSED,*/ GOLUB_WELSCH,\n       NEWTON_COTES };\n\n// growth rules within VPISparseGrid\n//enum { DEFAULT_GROWTH=0, SLOW_LINEAR, SLOW_LINEAR_ODD, MODERATE_LINEAR,\n//       SLOW_EXPONENTIAL, MODERATE_EXPONENTIAL, FULL_EXPONENTIAL };\n\n/// options for synchronizing linear and exponential growth rule settings\n/// (consistent with slow/moderate/full growth for new level_to_growth_*\n/// functions in sandia_rules.cpp)\nenum { SLOW_RESTRICTED_GROWTH, MODERATE_RESTRICTED_GROWTH,\n       UNRESTRICTED_GROWTH };\n\n/// solution approaches for calculating the polynomial basis coefficients\n/// (options for ExpansionConfigOptions::expCoeffsSolnApproach)\nenum { QUADRATURE, CUBATURE, LIGHTWEIGHT_SPARSE_GRID, COMBINED_SPARSE_GRID,\n       HIERARCHICAL_SPARSE_GRID, SAMPLING, DEFAULT_REGRESSION,\n       DEFAULT_LEAST_SQ_REGRESSION, SVD_LEAST_SQ_REGRESSION,\n       EQ_CON_LEAST_SQ_REGRESSION, BASIS_PURSUIT, BASIS_PURSUIT_DENOISING,\n       ORTHOG_MATCH_PURSUIT, LASSO_REGRESSION, LEAST_ANGLE_REGRESSION,\n       ORTHOG_LEAST_INTERPOLATION };\n/// options for BasisConfigOptions::nestingOverride (inactive)\nenum { NO_NESTING_OVERRIDE=0, NESTED, NON_NESTED };\n/// options for overriding the default growth restriction policy\nenum { NO_GROWTH_OVERRIDE=0, RESTRICTED, UNRESTRICTED };\n/// options for ExpansionConfigOptions::refinementType (inactive)\nenum { NO_REFINEMENT=0, P_REFINEMENT, H_REFINEMENT };\n/// options for ExpansionConfigOptions::refinementControl\nenum { NO_CONTROL=0, UNIFORM_CONTROL, LOCAL_ADAPTIVE_CONTROL,\n       DIMENSION_ADAPTIVE_CONTROL_SOBOL, DIMENSION_ADAPTIVE_CONTROL_DECAY,\n       DIMENSION_ADAPTIVE_CONTROL_GENERALIZED };\n\n/// options for expansion basis type\nenum { DEFAULT_BASIS=0, TENSOR_PRODUCT_BASIS, TOTAL_ORDER_BASIS,\n       ADAPTED_BASIS_GENERALIZED, ADAPTED_BASIS_EXPANDING_FRONT,\n       NODAL_INTERPOLANT, HIERARCHICAL_INTERPOLANT };\n\n/// mode of integration driver: integration versus interpolation\nenum { DEFAULT_MODE=0, INTEGRATION_MODE, INTERPOLATION_MODE };\n\n/// options for local basis functions within PiecewiseInterpPolynomial\nenum { LINEAR_EQUIDISTANT, LINEAR, QUADRATIC_EQUIDISTANT, QUADRATIC,\n       CUBIC_EQUIDISTANT, CUBIC };\n\n/// special values for nodal interpolation of variance and variance gradient\nenum { INTERPOLATION_OF_PRODUCTS, REINTERPOLATION_OF_PRODUCTS,\n       PRODUCT_OF_INTERPOLANTS_FAST, PRODUCT_OF_INTERPOLANTS_FULL };\n\n/// special values for polynomial expansion combination\nenum { NO_COMBINE=0,  ADD_COMBINE, MULT_COMBINE, ADD_MULT_COMBINE };\n\n\n// ----------------\n// Standard streams\n// ----------------\n#define PCout std::cout\n#define PCerr std::cerr\n\n\n// --------------\n// Global objects\n// --------------\n/// Dummy struct for overloading letter-envelope constructors.\n/** BaseConstructor is used to overload the constructor for the base class\n    portion of letter objects.  It avoids infinite recursion (Coplien p.139)\n    in the letter-envelope idiom by preventing the letter from instantiating\n    another envelope.  Putting this struct here avoids circular dependencies. */\nstruct BaseConstructor {\n  BaseConstructor(int = 0) {} ///< C++ structs can have constructors\n};\n\n\n// ----------------\n// Global functions\n// ----------------\n\n/// global function which handles serial or parallel aborts\nvoid abort_handler(int code);\n\n\ninline void abort_handler(int code)\n{ std::exit(code); } // for now, prior to use of MPI\n\n\n/** Templatized abort_handler_t method that allows for convenient return from \n    methods that otherwise have no sensible return from error clauses.  Usage:\n    MyType& method() { return abort_handler<MyType&>(-1); } */\ntemplate <typename T>\nT abort_handler_t(int code)\n{\n  abort_handler(code);\n  throw code;\n}\n\n} // namespace Pecos\n\n#endif // PECOS_GLOBAL_DEFS_H\n", "meta": {"hexsha": "fcf7fc305924963cc7a36c539da15bb79bba21b0", "size": 8217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dakota-6.3.0.Windows.x86/include/pecos_global_defs.hpp", "max_stars_repo_name": "seakers/ExtUtils", "max_stars_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dakota-6.3.0.Windows.x86/include/pecos_global_defs.hpp", "max_issues_repo_name": "seakers/ExtUtils", "max_issues_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dakota-6.3.0.Windows.x86/include/pecos_global_defs.hpp", "max_forks_repo_name": "seakers/ExtUtils", "max_forks_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-18T14:13:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T14:13:14.000Z", "avg_line_length": 42.3556701031, "max_line_length": 80, "alphanum_fraction": 0.7640258002, "num_tokens": 2223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.5552791525641323}}
{"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": "/*    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 *        Wakker, K.F., \"Astrodynamics I, AE4-874\", Delft University of Technology, 2007.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Astrodynamics/Gravitation/jacobiEnergy.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace gravitation;\nusing namespace orbital_element_conversions;\n\n//! Test if Jacobi energy is computed correctly.\nBOOST_AUTO_TEST_CASE( testJacobiEnergy )\n{\n    // Test 1: test Jacobi energy at L1.\n    {\n\n        // Set mass parameter for Earth-moon system. Value from Table 3.1 (Wakker, 2007).\n        double massParameter = 0.01215;\n\n        // Initialize position L1, from Table 3.4 (Wakker, 2007).\n        Eigen::VectorXd stateAtL1 = Eigen::VectorXd::Zero( 6 );\n        stateAtL1( xCartesianPositionIndex ) = 0.836914;\n\n        // Set expected value of Jacobi energy at L1.\n        double expectedJacobiEnergy = 3.1883;\n\n        // Compute Jacobi energy.\n        double computedJacobiEnergy = computeJacobiEnergy( massParameter, stateAtL1 );\n\n        // Check if expected Jacobi energy matches computed.\n        BOOST_CHECK_CLOSE_FRACTION( expectedJacobiEnergy,  computedJacobiEnergy, 1.0e-4 );\n    }\n\n    // Test 2: test Jacobi energy at L4.\n    {\n\n        // Set mass parameter for Earth-moon system. Value from Table 3.1 (Wakker, 2007).\n        double massParameter = 0.01215;\n\n        // Initialize position L4, from Table 3.4 (Wakker, 2007).\n        Eigen::VectorXd stateAtL4 = Eigen::VectorXd::Zero( 6 );\n        stateAtL4( xCartesianPositionIndex ) = 0.487849;\n        stateAtL4( yCartesianPositionIndex ) = 0.866025;\n\n        // Set expected value of Jacobi energy at L4.\n        double expectedJacobiEnergy = 2.9880;\n\n        // Compute Jacobi energy.\n        double computedJacobiEnergy = computeJacobiEnergy( massParameter, stateAtL4 );\n\n        // Check if expected Jacobi energy matches computed.\n        BOOST_CHECK_CLOSE_FRACTION( expectedJacobiEnergy,  computedJacobiEnergy, 1.0e-6 );\n    }\n}\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "130175f21df29f9e8252e1f3f7eeb17335fecd5b", "size": 2623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Gravitation/UnitTests/unitTestJacobiEnergy.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Gravitation/UnitTests/unitTestJacobiEnergy.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Gravitation/UnitTests/unitTestJacobiEnergy.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2025316456, "max_line_length": 90, "alphanum_fraction": 0.6953869615, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5550245479891022}}
{"text": "/** @file */\n\n#include <boost/program_options.hpp>\n#include <boost/test/unit_test.hpp>\n#include <sstream>\n\n#include <YukariMaths/Transform.h>\n#include <YukariMaths/Units.h>\n\nnamespace po = boost::program_options;\n\nnamespace Yukari\n{\nnamespace Maths\n{\n  namespace Test\n  {\n    BOOST_AUTO_TEST_SUITE(TransformTest)\n\n    BOOST_AUTO_TEST_CASE(Transform_FromMatrix)\n    {\n      Eigen::Matrix4f mat;\n      // clang-format off\n      mat << 0.75f       , -0.216506362f, 0.62499994f  , 5.5f,\n             0.433012664f, 0.875f       , -0.216506317f, 7.8f,\n             -0.5f       , 0.433012664f , 0.75f        , 2.1f,\n             0.0f        , 0.0f         , 0.0f         , 1.0f;\n      // clang-format on\n\n      Transform t(mat);\n\n      Eigen::Quaternionf expected;\n      expected = Eigen::AngleAxisf(30.0f * DEG_TO_RAD, Eigen::Vector3f::UnitZ()) *\n                 Eigen::AngleAxisf(30.0f * DEG_TO_RAD, Eigen::Vector3f::UnitY()) *\n                 Eigen::AngleAxisf(30.0f * DEG_TO_RAD, Eigen::Vector3f::UnitX());\n\n      BOOST_CHECK_CLOSE(t.orientation().w(), expected.w(), 0.1f);\n      BOOST_CHECK_CLOSE(t.orientation().x(), expected.x(), 0.1f);\n      BOOST_CHECK_CLOSE(t.orientation().y(), expected.y(), 0.1f);\n      BOOST_CHECK_CLOSE(t.orientation().z(), expected.z(), 0.1f);\n\n      BOOST_CHECK_CLOSE(t.position().x(), 5.5f, 0.1f);\n      BOOST_CHECK_CLOSE(t.position().y(), 7.8f, 0.1f);\n      BOOST_CHECK_CLOSE(t.position().z(), 2.1f, 0.1f);\n    }\n\n    BOOST_AUTO_TEST_CASE(Transform_ToMatrix)\n    {\n      Transform t;\n      t.orientation() = Eigen::AngleAxisf(30.0f * DEG_TO_RAD, Eigen::Vector3f::UnitZ()) *\n                        Eigen::AngleAxisf(30.0f * DEG_TO_RAD, Eigen::Vector3f::UnitY()) *\n                        Eigen::AngleAxisf(30.0f * DEG_TO_RAD, Eigen::Vector3f::UnitX());\n      t.position() = Eigen::Vector3f(5.5f, 7.8f, 2.1f);\n\n      Eigen::Matrix4f mat = t.toEigen();\n\n      BOOST_CHECK_CLOSE(mat(0, 0), 0.75f, 0.1f);\n      BOOST_CHECK_CLOSE(mat(0, 1), -0.216506362f, 0.1f);\n      BOOST_CHECK_CLOSE(mat(0, 2), 0.62499994f, 0.1f);\n      BOOST_CHECK_CLOSE(mat(0, 3), 5.5f, 0.1f);\n\n      BOOST_CHECK_CLOSE(mat(1, 0), 0.433012664f, 0.1f);\n      BOOST_CHECK_CLOSE(mat(1, 1), 0.875f, 0.1f);\n      BOOST_CHECK_CLOSE(mat(1, 2), -0.216506317f, 0.1f);\n      BOOST_CHECK_CLOSE(mat(1, 3), 7.8f, 0.1f);\n\n      BOOST_CHECK_CLOSE(mat(2, 0), -0.5f, 0.1f);\n      BOOST_CHECK_CLOSE(mat(2, 1), 0.433012664f, 0.1f);\n      BOOST_CHECK_CLOSE(mat(2, 2), 0.75f, 0.1f);\n      BOOST_CHECK_CLOSE(mat(2, 3), 2.1f, 0.1f);\n\n      BOOST_CHECK_CLOSE(mat(3, 0), 0.0f, 0.1f);\n      BOOST_CHECK_CLOSE(mat(3, 1), 0.0f, 0.1f);\n      BOOST_CHECK_CLOSE(mat(3, 2), 0.0f, 0.1f);\n      BOOST_CHECK_CLOSE(mat(3, 3), 1.0f, 0.1f);\n    }\n\n    BOOST_AUTO_TEST_CASE(Transform_Stream_Out_Empty)\n    {\n      Transform t;\n\n      std::stringstream str;\n      str << t;\n\n      BOOST_CHECK_EQUAL(str.str(), \"(o=[0, 0, 0, 1], p=[0, 0, 0])\");\n    }\n\n    BOOST_AUTO_TEST_CASE(Transform_Stream_Out)\n    {\n      Transform t;\n      t.orientation() = Eigen::AngleAxisf(30.0f * DEG_TO_RAD, Eigen::Vector3f::UnitZ()) *\n                        Eigen::AngleAxisf(30.0f * DEG_TO_RAD, Eigen::Vector3f::UnitY()) *\n                        Eigen::AngleAxisf(30.0f * DEG_TO_RAD, Eigen::Vector3f::UnitX());\n      t.position() = Eigen::Vector3f(5.5f, 7.8f, 2.1f);\n\n      std::stringstream str;\n      str << t;\n\n      BOOST_CHECK_EQUAL(str.str(),\n                        \"(o=[0.176777, 0.306186, 0.176777, 0.918559], p=[5.5, 7.8, 2.1])\");\n    }\n\n    BOOST_AUTO_TEST_CASE(Transform_Stream_In)\n    {\n      Transform t;\n\n      std::stringstream in(\"(o=[0.176777, 0.306186, 0.176777, 0.918559], p=[5.5, 7.8, 2.1])\");\n      in >> t;\n\n      std::stringstream out;\n      out << t;\n\n      BOOST_CHECK_EQUAL(out.str(),\n                        \"(o=[0.176777, 0.306186, 0.176777, 0.918559], p=[5.5, 7.8, 2.1])\");\n    }\n\n    BOOST_AUTO_TEST_CASE(Transform_From_String)\n    {\n      Transform t(\"(o=[0.176777, 0.306186, 0.176777, 0.918559], p=[5.5, 7.8, 2.1])\");\n\n      std::stringstream out;\n      out << t;\n\n      BOOST_CHECK_EQUAL(out.str(),\n                        \"(o=[0.176777, 0.306186, 0.176777, 0.918559], p=[5.5, 7.8, 2.1])\");\n    }\n\n    BOOST_AUTO_TEST_CASE(Transform_From_Boost_Args_Orientation_Only)\n    {\n      po::variables_map args;\n      args.insert(std::make_pair(\n          \"orientation\", po::variable_value(boost::any(std::string(\"[0, 0, 1] -90.5\")), false)));\n\n      Transform t(args);\n\n      Eigen::Quaternionf expectedQuat;\n      expectedQuat = Eigen::AngleAxisf(-90.5f * DEG_TO_RAD, Eigen::Vector3f::UnitZ());\n      BOOST_CHECK_EQUAL(expectedQuat.w(), t.orientation().w());\n      BOOST_CHECK_EQUAL(expectedQuat.x(), t.orientation().x());\n      BOOST_CHECK_EQUAL(expectedQuat.y(), t.orientation().y());\n      BOOST_CHECK_EQUAL(expectedQuat.z(), t.orientation().z());\n\n      BOOST_CHECK_EQUAL(t.position().x(), 0.0f);\n      BOOST_CHECK_EQUAL(t.position().y(), 0.0f);\n      BOOST_CHECK_EQUAL(t.position().z(), 0.0f);\n    }\n\n    BOOST_AUTO_TEST_CASE(Transform_From_Boost_Args_Position_Only)\n    {\n      po::variables_map args;\n      args.insert(std::make_pair(\n          \"position\", po::variable_value(boost::any(std::string(\"[1, 4.5, 7.1]\")), false)));\n\n      Transform t(args);\n\n      Eigen::Quaternionf expectedQuat = Eigen::Quaternionf::Identity();\n      BOOST_CHECK_EQUAL(expectedQuat.w(), t.orientation().w());\n      BOOST_CHECK_EQUAL(expectedQuat.x(), t.orientation().x());\n      BOOST_CHECK_EQUAL(expectedQuat.y(), t.orientation().y());\n      BOOST_CHECK_EQUAL(expectedQuat.z(), t.orientation().z());\n\n      BOOST_CHECK_EQUAL(t.position().x(), 1.0f);\n      BOOST_CHECK_EQUAL(t.position().y(), 4.5f);\n      BOOST_CHECK_EQUAL(t.position().z(), 7.1f);\n    }\n\n    BOOST_AUTO_TEST_CASE(Transform_From_Boost_Args_Both)\n    {\n      po::variables_map args;\n      args.insert(std::make_pair(\n          \"orientation\", po::variable_value(boost::any(std::string(\"[0, 0, 1] 90.0\")), false)));\n      args.insert(std::make_pair(\n          \"position\", po::variable_value(boost::any(std::string(\"[1, 4.5, 7.1]\")), false)));\n\n      Transform t(args);\n\n      Eigen::Quaternionf expectedQuat;\n      expectedQuat = Eigen::AngleAxisf(90.0f * DEG_TO_RAD, Eigen::Vector3f::UnitZ());\n      BOOST_CHECK_EQUAL(expectedQuat.w(), t.orientation().w());\n      BOOST_CHECK_EQUAL(expectedQuat.x(), t.orientation().x());\n      BOOST_CHECK_EQUAL(expectedQuat.y(), t.orientation().y());\n      BOOST_CHECK_EQUAL(expectedQuat.z(), t.orientation().z());\n\n      BOOST_CHECK_EQUAL(t.position().x(), 1.0f);\n      BOOST_CHECK_EQUAL(t.position().y(), 4.5f);\n      BOOST_CHECK_EQUAL(t.position().z(), 7.1f);\n    }\n\n    BOOST_AUTO_TEST_CASE(Transform_From_Boost_Args_Both_Empty)\n    {\n      po::variables_map args;\n      args.insert(\n          std::make_pair(\"orientation\", po::variable_value(boost::any(std::string(\"\")), false)));\n      args.insert(\n          std::make_pair(\"position\", po::variable_value(boost::any(std::string(\"\")), false)));\n\n      Transform t(args);\n\n      Eigen::Quaternionf expectedQuat = Eigen::Quaternionf::Identity();\n      BOOST_CHECK_EQUAL(expectedQuat.w(), t.orientation().w());\n      BOOST_CHECK_EQUAL(expectedQuat.x(), t.orientation().x());\n      BOOST_CHECK_EQUAL(expectedQuat.y(), t.orientation().y());\n      BOOST_CHECK_EQUAL(expectedQuat.z(), t.orientation().z());\n\n      BOOST_CHECK_EQUAL(t.position().x(), 0.0f);\n      BOOST_CHECK_EQUAL(t.position().y(), 0.0f);\n      BOOST_CHECK_EQUAL(t.position().z(), 0.0f);\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n  }\n}\n}\n", "meta": {"hexsha": "8526ad345a44fce258678b54ccbc5a1b469be7c6", "size": 7503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Libraries/YukariMaths/test/TransformTest.cpp", "max_stars_repo_name": "DanNixon/Yukari", "max_stars_repo_head_hexsha": "da3e599477302c241b438ca44d6711fdd68b6ef8", "max_stars_repo_licenses": ["MIT"], "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/YukariMaths/test/TransformTest.cpp", "max_issues_repo_name": "DanNixon/Yukari", "max_issues_repo_head_hexsha": "da3e599477302c241b438ca44d6711fdd68b6ef8", "max_issues_repo_licenses": ["MIT"], "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/YukariMaths/test/TransformTest.cpp", "max_forks_repo_name": "DanNixon/Yukari", "max_forks_repo_head_hexsha": "da3e599477302c241b438ca44d6711fdd68b6ef8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-04-04T12:58:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-01T21:47:22.000Z", "avg_line_length": 35.0607476636, "max_line_length": 97, "alphanum_fraction": 0.6050912968, "num_tokens": 2338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5550245447127852}}
{"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_ACOSH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACOSH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-hyperbolic\n    This function object returns the hyperbolic cosine argument: \\f$\\log(x+\\sqrt{x^2-1})\\f$.\n\n    @see cosh, sinh,  acsch, asinh, atanh, asech, acoth, acsch\n\n\n    @par Header <boost/simd/function/acosh.hpp>\n\n    @par Example:\n\n      @snippet acosh.cpp acosh\n\n    @par Possible output:\n\n      @snippet acosh.txt acosh\n\n  **/\n  IEEEValue acosh(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acosh.hpp>\n#include <boost/simd/function/simd/acosh.hpp>\n\n#endif\n", "meta": {"hexsha": "6ca41ab73fd33dc0f9ecf3b375fe8f24d4007dc1", "size": 1065, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acosh.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/acosh.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/acosh.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.2045454545, "max_line_length": 100, "alphanum_fraction": 0.5784037559, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5550245329430255}}
{"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": "/**\n * \\file\n *\n * \\copyright\n * Copyright (c) 2012-2022, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n */\n\n#include <gtest/gtest.h>\n\n#include <boost/math/constants/constants.hpp>\n#include <random>\n\n#include \"GeoLib/Utils.h\"\n\nstruct GeoLibGenerateEquidistantPoints : public testing::Test\n{\n    GeoLibGenerateEquidistantPoints()\n    {\n        // enable random engine\n        std::random_device rd;\n        std::mt19937 random_engine_mt19937(rd());\n        constexpr auto pi = boost::math::double_constants::pi;\n        std::normal_distribution<> normal_dist_phi(-pi, pi);  // azimuthal angle\n        std::normal_distribution<> normal_dist_theta(0, pi);  // polar angle\n        // generate point on unit sphere\n        double const phi = normal_dist_phi(random_engine_mt19937);\n        double const theta = normal_dist_theta(random_engine_mt19937);\n\n        start = MathLib::Point3d{{std::cos(phi) * std::sin(theta),\n                                  std::sin(phi) * std::sin(theta),\n                                  std::cos(theta)}};\n        // mirror of start point at origin\n        end = MathLib::Point3d{{-start[0], -start[1], -start[2]}};\n    }\n\n    ~GeoLibGenerateEquidistantPoints()\n    {\n        for (auto* p : equidistant_points)\n        {\n            delete p;\n        }\n    }\n\n    void checkLength() const\n    {\n        constexpr double eps = 4 * std::numeric_limits<double>::epsilon();\n        double sum = 0.0;\n        for (std::size_t i = 0; i < equidistant_points.size() - 1; ++i)\n        {\n            sum += std::sqrt(MathLib::sqrDist(*(equidistant_points[i]),\n                                              *(equidistant_points[i + 1])));\n        }\n        auto const sum_start_end = std::sqrt(MathLib::sqrDist(start, end));\n        EXPECT_NEAR(sum_start_end, sum, eps)\n            << start[0] << \" \" << start[1] << \" \" << start[2] << \" -- \"\n            << end[0] << \" \" << end[1] << \" \" << end[2];\n    }\n\n    MathLib::Point3d start;\n    MathLib::Point3d end;\n    std::vector<GeoLib::Point*> equidistant_points;\n};\n\nTEST_F(GeoLibGenerateEquidistantPoints, IdenticalStartEndPoints)\n{\n    equidistant_points = GeoLib::generateEquidistantPoints(start, start, 2);\n    ASSERT_EQ(4, equidistant_points.size());\n    EXPECT_DOUBLE_EQ(start[0], (*equidistant_points[0])[0]);\n    EXPECT_DOUBLE_EQ(start[1], (*equidistant_points[0])[1]);\n    EXPECT_DOUBLE_EQ(start[2], (*equidistant_points[0])[2]);\n    EXPECT_DOUBLE_EQ(start[0], (*equidistant_points[1])[0]);\n    EXPECT_DOUBLE_EQ(start[1], (*equidistant_points[1])[1]);\n    EXPECT_DOUBLE_EQ(start[2], (*equidistant_points[1])[2]);\n}\n\nTEST_F(GeoLibGenerateEquidistantPoints, ZeroSubdivisions)\n{\n    equidistant_points = GeoLib::generateEquidistantPoints(start, end, 0);\n    ASSERT_EQ(2, equidistant_points.size());\n    checkLength();\n}\n\nTEST_F(GeoLibGenerateEquidistantPoints, OneSubdivision)\n{\n    equidistant_points = GeoLib::generateEquidistantPoints(start, end, 1);\n    ASSERT_EQ(3, equidistant_points.size());\n    EXPECT_DOUBLE_EQ(0.0, (*equidistant_points[1])[0]);\n    EXPECT_DOUBLE_EQ(0.0, (*equidistant_points[1])[1]);\n    EXPECT_DOUBLE_EQ(0.0, (*equidistant_points[1])[2]);\n    checkLength();\n}\n\nTEST_F(GeoLibGenerateEquidistantPoints, ThreeSubdivisions)\n{\n    equidistant_points = GeoLib::generateEquidistantPoints(start, end, 3);\n    ASSERT_EQ(5, equidistant_points.size());\n    EXPECT_DOUBLE_EQ(0.0, (*equidistant_points[2])[0]);\n    EXPECT_DOUBLE_EQ(0.0, (*equidistant_points[2])[1]);\n    EXPECT_DOUBLE_EQ(0.0, (*equidistant_points[2])[2]);\n    checkLength();\n}\n\nTEST_F(GeoLibGenerateEquidistantPoints, FiveSubdivisions)\n{\n    constexpr double eps = std::numeric_limits<double>::epsilon();\n    equidistant_points = GeoLib::generateEquidistantPoints(start, end, 5);\n    ASSERT_EQ(7, equidistant_points.size());\n    EXPECT_NEAR(0.0, (*equidistant_points[3])[0], eps);\n    EXPECT_NEAR(0.0, (*equidistant_points[3])[1], eps);\n    EXPECT_NEAR(0.0, (*equidistant_points[3])[2], eps);\n    EXPECT_NEAR(\n        MathLib::sqrDist(start, *(equidistant_points[1])),\n        MathLib::sqrDist(*(equidistant_points[1]), *(equidistant_points[2])),\n        eps);\n    EXPECT_NEAR(MathLib::sqrDist(start, *(equidistant_points[1])),\n                MathLib::sqrDist(*(equidistant_points[5]), end),\n                eps);\n    checkLength();\n}\n", "meta": {"hexsha": "976214489ee912981d44a6e964f0e743ef4c5f0b", "size": 4462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/GeoLib/TestEquidistantPointGeneration.cpp", "max_stars_repo_name": "garibay-j/ogs", "max_stars_repo_head_hexsha": "33340f22e9dbe0b7ccc60f0c828c2a528737c81e", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/GeoLib/TestEquidistantPointGeneration.cpp", "max_issues_repo_name": "garibay-j/ogs", "max_issues_repo_head_hexsha": "33340f22e9dbe0b7ccc60f0c828c2a528737c81e", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/GeoLib/TestEquidistantPointGeneration.cpp", "max_forks_repo_name": "garibay-j/ogs", "max_forks_repo_head_hexsha": "33340f22e9dbe0b7ccc60f0c828c2a528737c81e", "max_forks_repo_licenses": ["BSD-3-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.2764227642, "max_line_length": 80, "alphanum_fraction": 0.6378305693, "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5549236184565421}}
{"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": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nMatrix3i m = Matrix3i::Random();\ncout << \"Here is the initial matrix m:\" << endl << m << endl;\nint i = -1;\nfor(auto c: m.colwise()) {\n  c *= i;\n  ++i;\n}\ncout << \"Here is the matrix m after the for-range-loop:\" << endl << m << endl;\nauto cols = m.colwise();\nauto it = std::find_if(cols.cbegin(), cols.cend(),\n                       [](Matrix3i::ConstColXpr x) { return x.squaredNorm() == 0; });\ncout << \"The first empty column is: \" << distance(cols.cbegin(),it) << endl;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "ad48a42fe57e6cae6beff7f81eb034a4cfb147ea", "size": 1004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_MatrixBase_colwise_iterator_cxx11.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_MatrixBase_colwise_iterator_cxx11.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_MatrixBase_colwise_iterator_cxx11.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8888888889, "max_line_length": 224, "alphanum_fraction": 0.6394422311, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.5549226656846563}}
{"text": "#include \"crit_dijkstra.hpp\"\n#include \"dijkstra.hpp\"\n#include \"graph.hpp\"\n#include <boost/test/unit_test.hpp>\n#include <cfloat>\n\nusing namespace sssp;\nnamespace tt = boost::test_tools;\n\nBOOST_AUTO_TEST_CASE(dijkstra_basic_test_1) {\n    graph g;\n    for (size_t i = 0; i < 4; ++i) {\n        g.add_node();\n    }\n    g.add_edge(0, 1, 1.0);\n    g.add_edge(0, 2, 0.3);\n    g.add_edge(2, 3, 0.3);\n    g.add_edge(3, 1, 0.3);\n\n    boost::base_collection<criteria> criteria;\n    criteria.insert(smallest_tentative_distance(&g, 0));\n    node_map<dijkstra_result> result = dijkstra(g, 0, criteria);\n\n    BOOST_TEST_REQUIRE(result.size() == 4);\n    BOOST_TEST(result[0].predecessor == -1);\n    BOOST_TEST(result[1].predecessor == 3);\n    BOOST_TEST(result[2].predecessor == 0);\n    BOOST_TEST(result[3].predecessor == 2);\n    BOOST_TEST(result[0].distance == 0.0, tt::tolerance(DBL_EPSILON));\n    BOOST_TEST(result[1].distance == 0.9, tt::tolerance(DBL_EPSILON));\n    BOOST_TEST(result[2].distance == 0.3, tt::tolerance(DBL_EPSILON));\n    BOOST_TEST(result[3].distance == 0.6, tt::tolerance(DBL_EPSILON));\n}\n\nBOOST_AUTO_TEST_CASE(dijkstra_basic_test_2) {\n    graph g;\n    for (size_t i = 0; i < 10; ++i) {\n        g.add_node();\n    }\n    for (size_t i = 0; i < 10; ++i) {\n        for (size_t j = 0; j < 10; ++j) {\n            if (i != j) {\n                g.add_edge(i, j, 1.0);\n            }\n        }\n    }\n\n    boost::base_collection<criteria> criteria;\n    criteria.insert(smallest_tentative_distance(&g, 0));\n    node_map<dijkstra_result> result = dijkstra(g, 0, criteria);\n\n    BOOST_TEST_REQUIRE(result.size() == 10);\n    BOOST_TEST(result[0].predecessor == -1);\n    BOOST_TEST(result[0].distance == 0.0, tt::tolerance(DBL_EPSILON));\n    for (size_t i = 1; i < 10; ++i) {\n        BOOST_TEST(result[i].predecessor == 0);\n        BOOST_TEST(result[i].distance == 1.0, tt::tolerance(DBL_EPSILON));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(dijkstra_basic_test_3) {\n    graph g;\n    g.add_node();\n    g.add_node();\n    g.add_node();\n    g.add_edge(0, 1, 1.0);\n    g.add_edge(1, 0, 1.0);\n    g.add_edge(2, 1, 1.0);\n    g.add_edge(2, 0, 1.0);\n\n    boost::base_collection<criteria> criteria;\n    criteria.insert(smallest_tentative_distance(&g, 0));\n    node_map<dijkstra_result> result = dijkstra(g, 0, criteria);\n\n    BOOST_TEST_REQUIRE(result.size() == 3);\n    BOOST_TEST(result[0].predecessor == -1);\n    BOOST_TEST(result[1].predecessor == 0);\n    BOOST_TEST(result[2].predecessor == -1);\n    BOOST_TEST(result[0].distance == 0.0, tt::tolerance(DBL_EPSILON));\n    BOOST_TEST(result[1].distance == 1.0, tt::tolerance(DBL_EPSILON));\n    BOOST_TEST(result[2].distance == INFINITY);\n}\n", "meta": {"hexsha": "8f6779534aeb11696cd7940f996ca1dac3beaf57", "size": 2661, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/dijkstra_basic_test.cpp", "max_stars_repo_name": "kaini/sssp-simulation", "max_stars_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_stars_repo_licenses": ["MIT"], "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/dijkstra_basic_test.cpp", "max_issues_repo_name": "kaini/sssp-simulation", "max_issues_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_issues_repo_licenses": ["MIT"], "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/dijkstra_basic_test.cpp", "max_forks_repo_name": "kaini/sssp-simulation", "max_forks_repo_head_hexsha": "0ee9cefb9b5d3a79c59eedd44092cd0401e99581", "max_forks_repo_licenses": ["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.0602409639, "max_line_length": 74, "alphanum_fraction": 0.6290868095, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5549226632488313}}
{"text": "// Copyright (C) 2017 Minhyuk Sung <mhsung@cs.stanford.edu>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n//\n\n#include \"LibiglMesh.h\"\n\n#include <Eigen/Geometry>\n#include <igl/doublearea.h>\n#include <igl/per_face_normals.h>\n#include <igl/random_points_on_mesh.h>\n#include <modules/PCA.h>\n#include <modules/remove_duplicates_custom.h>\n#include <utils/utils.h>\n\n\nvoid LibiglMesh::sample_points_on_mesh(\n    const int _num_points, const bool _with_normals) {\n  // NOTE: 03-24-2017\n  // Remove duplicated faces in mesh before sampling points.\n  MatrixXi newF;\n  igl::remove_duplicate_faces_custom(F_, newF);\n\n  SparseMatrix<double> B;\n  // NOTE: 02-25-2018\n  // Assign face indices to points labels.\n  igl::random_points_on_mesh(_num_points, V_, newF, B, PL_);\n  const VectorXi& FI = PL_;\n  P_ = B * V_;\n\n  if (_with_normals) {\n    igl::per_face_normals(V_, F_, FN_);\n    PN_ = Utils::slice_rows(FN_, FI);\n  }\n}\n\nvoid LibiglMesh::normalize_points() {\n  const int num_samples = P_.rows();\n  CHECK_GT(num_samples, 0);\n\n  // Compute center and bounding box diagonal.\n  const auto bb_min = P_.colwise().minCoeff();\n  const auto bb_max = P_.colwise().maxCoeff();\n\n  const RowVector3d bb_center = 0.5 * (bb_min + bb_max);\n  P_ = P_.rowwise() - bb_center;\n\n  const auto radius = P_.rowwise().norm().maxCoeff();\n  P_ = P_ / radius;\n}\n\nvoid LibiglMesh::compute_point_set_center_and_area(\n    const std::string& _out_file, bool _centerize) {\n  const int num_samples = P_.rows();\n  CHECK_GT(num_samples, 0);\n\n  // Compute center and bounding box diagonal.\n  const auto bb_min = P_.colwise().minCoeff();\n  const auto bb_max = P_.colwise().maxCoeff();\n\n  // NOTE: 03-24-2017\n  // Use bounding box center as center instead of mean of point positions.\n  //const RowVector3d center = P_.colwise().mean();\n  const RowVector3d bb_center = 0.5 * (bb_min + bb_max);\n\n\n  // NOTE: 03-24-2017\n  // Use sum of face areas as size instead of bounding box diagonal.\n  //const double bbox_diagonal = (bb_max - bb_min).norm();\n  MatrixXi newF;\n  igl::remove_duplicate_faces_custom(F_, newF);\n  VectorXd FA;\n  igl::doublearea(V_, newF, FA);\n  const double sum_face_areas = 0.5 * FA.sum();\n\n  if (_centerize) {\n    // Centerize point set.\n    P_ = P_.rowwise() - bb_center;\n  }\n\n  if (_out_file != \"\") {\n    RowVector4d center_and_area;\n    //center_and_area << center, bbox_diagonal;\n    center_and_area << bb_center, sum_face_areas;\n    Utils::write_eigen_matrix_to_file(_out_file, center_and_area);\n  }\n}\n\nvoid LibiglMesh::pca_align_points(const std::string& _out_file) {\n  const int num_samples = P_.rows();\n  CHECK_GT(num_samples, 0);\n\n  // Compute PCA transformation matrix.\n  Affine3d T = Affine3d::Identity();\n  igl::PCA(P_, T);\n\n  // PCA-align point set.\n  const Eigen::Matrix<double, Dynamic, 3>& P_temp = P_;\n  P_ = (T * P_temp.transpose()).transpose();\n\n  // NOTE:\n  // P.transpose == R * P_aligned.transpose() + t\n  Affine3d T_inv = T.inverse();\n  const Matrix3d R = T_inv.rotation();\n  const Vector3d t = T_inv.translation();\n\n  const AngleAxisd rotation(R);\n  double angle = rotation.angle();\n  // Make angle to be in [-pi, +pi) range.\n  while (angle < -M_PI) angle += (2.0 * M_PI);\n  while (angle >= M_PI) angle -= (2.0 * M_PI);\n  Vector3d axis = rotation.axis().normalized();\n\n  const Vector3d r = angle * axis;\n\n  // NOTE: 03-24-2017\n  // Add sum of face areas.\n  MatrixXi newF;\n  igl::remove_duplicate_faces_custom(F_, newF);\n  VectorXd FA;\n  igl::doublearea(V_, newF, FA);\n  const double a = 0.5 * FA.sum();\n\n  // Scale along the first PCA axis.\n  const double s = P_.col(0).maxCoeff() - P_.col(0).minCoeff();\n\n  VectorXd transformation(8);\n  transformation << r, t, a, s;\n  if (_out_file != \"\") {\n    Utils::write_eigen_matrix_to_file(_out_file, transformation.transpose());\n  }\n}\n", "meta": {"hexsha": "699b02489237affb88064fcbd343c07faed4e131", "size": 3924, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/point_set_processing.cc", "max_stars_repo_name": "mhsung/libigl-renderer", "max_stars_repo_head_hexsha": "b119f66946b43d989da31ccbf6929aaa7ec4e9aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-05-13T16:45:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:46:00.000Z", "max_issues_repo_path": "src/point_set_processing.cc", "max_issues_repo_name": "mhsung/libigl-renderer", "max_issues_repo_head_hexsha": "b119f66946b43d989da31ccbf6929aaa7ec4e9aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-20T09:04:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T09:11:58.000Z", "max_forks_repo_path": "src/point_set_processing.cc", "max_forks_repo_name": "mhsung/libigl-renderer", "max_forks_repo_head_hexsha": "b119f66946b43d989da31ccbf6929aaa7ec4e9aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-18T08:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T08:31:00.000Z", "avg_line_length": 29.0666666667, "max_line_length": 78, "alphanum_fraction": 0.6837410805, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5548418921556421}}
{"text": "#include \"SimpleHydraulicLib/ConvEigen.h\"\n\n#include <Eigen/QR>\n\n#include <fstream>\n#include <iostream>\n#include <sstream>  // std::stringstream\n#include <stdexcept>// std::runtime_error\n#include <string>\n#include <utility>// std::pair\n#include <vector>\n\nusing Eigen::VectorXd;\nusing std::cerr;\nusing std::cout;\n\nvoid process() {\n    //    // Read three_cols.csv and ones.csv\n    //    std::vector<std::pair<std::string, std::vector<double>>> mul_cols = read_csv(\"Heating_Cooling_data.csv\");\n    //\n    //    // Write to another file to check that this was successful\n    //    write_csv(\"Heating_Cooling_data_copy.csv\", mul_cols);\n    // matrix to be loaded from a file\n    MatrixXd data;\n\n    // load the matrix from the file\n    data = openData(\"inputs/matrix.csv\");\n    VectorXd Demand_A = data.col(0);\n    VectorXd Demand_B = data.col(1);\n    VectorXd Demand_C = data.col(2);\n    VectorXd Demand_D = data.col(3);\n    VectorXd Demand_E = data.col(4);\n    VectorXd Demand_F = data.col(5);\n    VectorXd Demand_z0(8760);\n    Demand_z0.setZero();\n    VectorXd Demand_z4(8760);\n    Demand_z4.setZero();\n\n    Demand_A = Demand_A / 4.2 / 15;\n    Demand_B = Demand_B / 4.2 / 15;\n    Demand_C = Demand_C / 4.2 / 15;\n    Demand_D = Demand_D / 4.2 / 15;\n    Demand_E = Demand_E / 4.2 / 15;\n    Demand_F = Demand_F / 4.2 / 15;\n\n    //   cerr << Demand_C.size() << \"\\n\";\n    MatrixXd B(8760, 8);\n    B << Demand_z0, Demand_C, Demand_B, Demand_D, Demand_z4, Demand_A, Demand_E, Demand_F;\n    //   cerr << B << \"\\n\";\n\n    MatrixXd Q = MatrixXd::Zero(8760, 8);\n    Q.col(1) = Demand_C;\n    Q.col(2) = Demand_B;\n    Q.col(3) = Demand_D;\n    Q.col(4) = Demand_A + Demand_E + Demand_F;\n    Q.col(5) = Demand_A;\n    Q.col(6) = Demand_E;\n    Q.col(7) = Demand_F;\n    Q.col(0) = Demand_C + Demand_B + Demand_D + Demand_A + Demand_E + Demand_F;\n    cerr << \"The first set of solutions is \\n\"\n         << Q.row(0) << \"\\n\";\n    saveData(\"outputs/flowQ.csv\", Q);\n    cerr << Q.rows() << \" rows and \" << Q.cols() << \" columns.\";\n    //    MatrixXd A(8, 8);\n    //    A << 1, -1, -1, -1, -1, 0, 0, 0,\n    //            0, 1, 0, 0, 0, 0, 0, 0,\n    //            0, 0, 1, 0, 0, 0, 0, 0,\n    //            0, 0, 0, 1, 0, 0, 0, 0,\n    //            0, 0, 0, 0, 1, -1, -1, 1,\n    //            0, 0, 0, 0, 0, 1, 0, 0,\n    //            0, 0, 0, 0, 0, 0, 1, 0,\n    //            0, 0, 0, 0, 0, 0, 0, 1;\n\n    //MatrixXd X = A.colPivHouseholderQr().solve(B.transpose());\n    //    MatrixXd X = A.lu().solve(B.transpose());\n    //    cerr << \"The condition number is \" << A.lu().rcond() << \"\\n\";\n    //    cerr << \"The first set of solutions is \\n\" << X.col(0) << \"\\n\";\n    //    double relative_err = (A*X - B.transpose()).norm()/B.transpose().norm();\n    //    cerr << \"The relative error is:\\n\" << relative_err << \"\\n\";\n    //    saveData(\"outputs/flow.csv\", X.transpose());\n    ////    Eigen::IOFormat csv(-1, 0, \", \", \"\\n\");\n    ////    std::cout << X.format(csv) << std::endl;\n    //    cerr << X.rows() << \" rows and \" << X.cols() << \" columns.\";\n\n    //    for (int i = 0; i < data.rows(); ++i){\n    //        Demand_A(i) = Demand_A(i)/4.2/15;\n    //        Demand_B(i) = Demand_B(i)/4.2/15;\n    //        Demand_C(i) = Demand_C(i)/4.2/15;\n    //        Demand_D(i) = Demand_D(i)/4.2/15;\n    //        Demand_E(i) = Demand_E(i)/4.2/15;\n    //        Demand_F(i) = Demand_F(i)/4.2/15;\n    //;    }\n    // MatrixXd Q = MatrixXd::Zero(8760, 8);\n\n    //    for (int i = 0; i < data.rows(); ++i){\n    //        b << 0.0, Demand_C(i), Demand_B(i), Demand_D(i), 0.0, Demand_A(i), Demand_E(i), Demand_F(i);\n    //        VectorXd x = A.colPivHouseholderQr().solve(b);\n    //        cout << \"The solution is:\\n\" << x << \"\\n\";\n    //    }\n}\n\n/*\n * Our accuracy are good but we are getting some systematic error as the solutions from Matlab and C++ deviate.\n * This might due to the non-empty nullspace. If our matrix is rank deficient the solution may have an arbitrary large component added in the null space.\n * In other words if Ax = b then the computed solution might be x' = x* + x0, where A*x0 = 0, so r = A*x'-b = 0.\n * So, we could have perfect accuracy but still produce different solutions due to the non-empty nullspace.\n * If my system is well-conditioned, I will not need to worry about that.  If it isn't, it might help explain the systematic error I'm getting.\n *\n */\n\n/*\n * Precision could be lost when reading/writing CSV file\n * Residual error (or existence of solutions)\n * Rank deficiency\n * Well conditionness\n */\n", "meta": {"hexsha": "81ca16ac050f85c095b8ff99574db3e5be1c7e2a", "size": 4499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SimpleHydraulicLib/src/process.cpp", "max_stars_repo_name": "janwilmans/SimpleHydraulicNetwork", "max_stars_repo_head_hexsha": "a64703e6f8f7823546114c0e8761469bed0deb5c", "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": "SimpleHydraulicLib/src/process.cpp", "max_issues_repo_name": "janwilmans/SimpleHydraulicNetwork", "max_issues_repo_head_hexsha": "a64703e6f8f7823546114c0e8761469bed0deb5c", "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": "SimpleHydraulicLib/src/process.cpp", "max_forks_repo_name": "janwilmans/SimpleHydraulicNetwork", "max_forks_repo_head_hexsha": "a64703e6f8f7823546114c0e8761469bed0deb5c", "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.452991453, "max_line_length": 153, "alphanum_fraction": 0.5623471883, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.554841892155642}}
{"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": "//\n// Add --log_level=message to see the messages!\n//\n#include <boost/test/unit_test.hpp>\n\n#include <sstream>\n\n#include \"core/functions.h\"\n#include \"core/utils.h\"\n#include \"core/random.h\"\n#include \"core/training.h\"\n#include \"layers/convlayer.h\"\n\n#include \"test_utils.h\"\n#include \"timer.h\"\n#include \"test_layers.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::unit_test;\nusing namespace yann;\nusing namespace yann::test;\n\n\nstruct ConvolutionalLayerTestFixture\n{\n  ConvolutionalLayerTestFixture()\n  {\n\n  }\n  ~ConvolutionalLayerTestFixture()\n  {\n\n  }\n\n  inline MatrixSize find_max_pos(const RefConstVector & vv)\n  {\n    MatrixSize pos = 0;\n    vv.maxCoeff(&pos);\n    return pos;\n  }\n\n\n  void conv_perf_test(const MatrixSize & size, const MatrixSize & filter_size, const size_t & epochs)\n  {\n      BOOST_TEST_MESSAGE(\"*** ConvOp Performance test with\"\n          << \" size=\" << size\n          << \", filter_size=\" << filter_size\n          << \", epochs=\" << epochs\n      );\n\n      Matrix input(size, size);\n      Matrix filter(filter_size, filter_size);\n      Matrix output(size + filter_size, size + filter_size);\n      {\n        Timer timer(\"Random generation\");\n        unique_ptr<RandomGenerator> gen = RandomGenerator::normal_distribution(0, 1);\n        gen->generate(input);\n        gen->generate(filter);\n      }\n      output.resize(ConvolutionalLayer::get_conv_output_rows(size, filter_size),\n                    ConvolutionalLayer::get_conv_output_cols(size, filter_size));\n      {\n        Timer timer(\"Test plus_conv\");\n        for(auto ii = epochs; ii > 0; --ii) {\n          ConvolutionalLayer::plus_conv(input, filter, output);\n        }\n      }\n      output.resize(ConvolutionalLayer::get_full_conv_output_rows(size, filter_size),\n                    ConvolutionalLayer::get_full_conv_output_cols(size, filter_size));\n      {\n        Timer timer(\"Test full_conv\");\n        for(auto ii = epochs; ii > 0; --ii) {\n          ConvolutionalLayer::full_conv(input, filter, output);\n        }\n      }\n  }\n\n  void conv_perf_batch_test(const MatrixSize & batch_size, const MatrixSize & size, const MatrixSize & filter_size, const size_t & epochs)\n  {\n      BOOST_TEST_MESSAGE(\"*** ConvOp Performance batch test with\"\n          << \" batch_size=\" << batch_size\n          << \", size=\" << size\n          << \", filter_size=\" << filter_size\n          << \", epochs=\" << epochs\n      );\n      VectorBatch input, output;\n      Matrix filter(filter_size, filter_size);\n\n      resize_batch(input, batch_size, size * size);\n      {\n        Timer timer(\"Random generation\");\n        unique_ptr<RandomGenerator> gen = RandomGenerator::normal_distribution(0, 1);\n        gen->generate(input);\n        gen->generate(filter);\n      }\n      resize_batch(output, batch_size, ConvolutionalLayer::get_conv_output_size(size, size, filter_size));\n      {\n        Timer timer(\"Test plus_conv\");\n        for(auto ii = epochs; ii > 0; --ii) {\n          ConvolutionalLayer::plus_conv(input, size, size, filter, output);\n        }\n      }\n      resize_batch(output, batch_size, ConvolutionalLayer::get_full_conv_output_size(size, size, filter_size));\n      {\n        Timer timer(\"Test full_conv\");\n        for(auto ii = epochs; ii > 0; --ii) {\n          ConvolutionalLayer::full_conv(input, size, size, filter, output);\n        }\n      }\n  }\n}; // struct ConvolutionalLayerTestFixture\n\nBOOST_FIXTURE_TEST_SUITE(ConvolutionalLayerTest, ConvolutionalLayerTestFixture);\n\nBOOST_AUTO_TEST_CASE(IO_Test)\n{\n  BOOST_TEST_MESSAGE(\"*** ConvolutionalLayer IO test ...\");\n\n  const MatrixSize input_cols = 5;\n  const MatrixSize input_rows = 3;\n  const MatrixSize filter_size = 2;\n  auto one = make_unique<ConvolutionalLayer>(input_cols, input_rows, filter_size);\n  one->init(Layer::InitMode_Random, boost::none);\n\n  BOOST_TEST_MESSAGE(\"ConvolutionalLayer before writing to file: \" << \"\\n\" << *one);\n  ostringstream oss;\n  oss << *one;\n  BOOST_CHECK(!oss.fail());\n\n  auto two = make_unique<ConvolutionalLayer>(input_cols, input_rows, filter_size);\n  std::istringstream iss(oss.str());\n  iss >> *two;\n  BOOST_CHECK(!iss.fail());\n  BOOST_TEST_MESSAGE(\"ConvolutionalLayer after loading from file: \" << \"\\n\" << *two);\n\n  BOOST_CHECK(one->is_equal(*two, TEST_TOLERANCE));\n}\n\nBOOST_AUTO_TEST_CASE(ConvOp_Test)\n{\n  BOOST_TEST_MESSAGE(\"*** Convolutional operation test ...\");\n\n  const size_t image_size = 4;\n  const size_t max_filter_size = 4;\n  Matrix filter(max_filter_size, max_filter_size);\n  Matrix input(image_size, image_size);\n  Matrix expected(image_size, image_size);\n  Matrix output(image_size, image_size);\n\n  //////////////////////////////////////////////////////////////////////\n  //\n  // Test different filter sizes\n  //\n  input <<\n      1,  2,  3,  4,\n      5,  6,  7,  8,\n      9, 10, 11, 12,\n     13, 14, 15, 16;\n\n  // 1x1\n  filter.resize(1, 1);\n  filter <<\n      3;\n  expected.resize(4, 4);\n  expected <<\n      3,  6,  9, 12,\n     15, 18, 21, 24,\n     27, 30, 33, 36,\n     39, 42, 45, 48;\n  output.resizeLike(expected);\n  {\n      // ensure we don't do allocations in eigen\n      BlockAllocations block;\n      ConvolutionalLayer::plus_conv(input, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 2x1\n  filter.resize(2, 1);\n  filter <<\n      2,\n      3;\n  expected.resize(3, 4);\n  expected <<\n      17, 22, 27, 32,\n      37, 42, 47, 52,\n      57, 62, 67, 72;\n  output.resizeLike(expected);\n  {\n    // ensure we don't do allocations in eigen\n    BlockAllocations block;\n    ConvolutionalLayer::plus_conv(input, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 2x2\n  filter.resize(2, 2);\n  filter <<\n      1, 2,\n      3, 4;\n  expected.resize(3, 3);\n  expected <<\n      44,  54,  64,\n      84,  94, 104,\n     124, 134, 144;\n  output.resizeLike(expected);\n  {\n    // ensure we don't do allocations in eigen\n    BlockAllocations block;\n    ConvolutionalLayer::plus_conv(input, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 2x3\n  filter.resize(2, 3);\n  filter <<\n      1, 2, 3,\n      4, 5, 6;\n  expected.resize(3, 2);\n  expected <<\n      106, 127,\n      190, 211,\n      274, 295;\n  output.resizeLike(expected);\n  {\n    // ensure we don't do allocations in eigen\n    BlockAllocations block;\n    ConvolutionalLayer::plus_conv(input, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 3x3\n  filter.resize(3, 3);\n  filter <<\n      1, 2, 3,\n      4, 5, 6,\n      7, 8, 9;\n  expected.resize(2, 2);\n  expected <<\n      348, 393,\n      528, 573;\n  output.resizeLike(expected);\n  {\n    // ensure we don't do allocations in eigen\n    BlockAllocations block;\n    ConvolutionalLayer::plus_conv(input, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 4x4\n  filter.resize(4, 4);\n  filter <<\n      1,  2,  3,  4,\n      5,  6,  7,  8,\n      9, 10, 11, 12,\n     13, 14, 15, 16;\n  expected.resize(1, 1);\n  expected <<\n      1496;\n  output.resizeLike(expected);\n  {\n    // ensure we don't do allocations in eigen\n    BlockAllocations block;\n    ConvolutionalLayer::plus_conv(input, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n}\n\nBOOST_AUTO_TEST_CASE(ConvOp_Batch_Test)\n{\n  BOOST_TEST_MESSAGE(\"*** Convolutional operation batch test ...\");\n\n  const size_t max_filter_size = 4;\n  const MatrixSize image_size = 4;\n  const MatrixSize input_size = image_size * image_size;\n  const MatrixSize batch_size = 2;\n  Matrix filter(max_filter_size, max_filter_size);\n  VectorBatch input, output, expected;\n\n  //////////////////////////////////////////////////////////////////////\n  //\n  // Test different filter sizes\n  //\n  resize_batch(input, batch_size, input_size);\n  input << 1, 0, 1, 0,\n           0, 1, 0, 0,\n           1, 0, 1, 0,\n           0, 0, 0, 0,\n           ///////////\n           0, 0, 0, 0,\n           0, 1, 0, 0,\n           0, 0, 1, 0,\n           0, 0, 0, 0;\n\n  // 1x1\n  filter.resize(1, 1);\n  filter << 1;\n  resize_batch(expected, batch_size, 4 * 4);\n  expected << 1, 0, 1, 0,\n              0, 1, 0, 0,\n              1, 0, 1, 0,\n              0, 0, 0, 0,\n              ///////////\n              0, 0, 0, 0,\n              0, 1, 0, 0,\n              0, 0, 1, 0,\n              0, 0, 0, 0;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 2x1\n  filter.resize(2, 1);\n  filter << 1,\n            1;\n  resize_batch(expected, batch_size, 3 * 4);\n  expected << 1, 1, 1, 0,\n              1, 1, 1, 0,\n              1, 0, 1, 0,\n              ///////////\n              0, 1, 0, 0,\n              0, 1, 1, 0,\n              0, 0, 1, 0;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 2x2\n  filter.resize(2, 2);\n  filter << 1, 1,\n            1, 0;\n  resize_batch(expected, batch_size, 3 * 3);\n  expected << 1, 2, 1,\n              2, 1, 1,\n              1, 1, 1,\n              ////////\n              0, 1, 0,\n              1, 1, 1,\n              0, 1, 1;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 3x2\n  filter.resize(3, 2);\n  filter << 1, 1,\n            1, 0,\n            1, 0;\n  resize_batch(expected, batch_size, 2 * 3);\n  expected << 2, 2, 2,\n              2, 1, 1,\n              ////////\n              0, 1, 1,\n              1, 1, 1;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 3x3\n  filter.resize(3, 3);\n  filter << 1, 1, 1,\n            1, 0, 0,\n            1, 0, 1;\n  resize_batch(expected, batch_size, 2 * 2);\n  expected << 4, 2,\n              2, 1,\n              /////\n              1, 1,\n              1, 1;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 4x4\n  filter.resize(4, 4);\n  filter << 1, 1, 1, 1,\n            1, 1, 0, 0,\n            1, 0, 1, 0,\n            1, 0, 0, 1;\n  resize_batch(expected, batch_size, 1 * 1);\n  expected << 5,\n              //\n              2;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n}\n\nBOOST_AUTO_TEST_CASE(FullConvOp_Test)\n{\n  BOOST_TEST_MESSAGE(\"*** Full convolutional operation test ...\");\n\n  const size_t image_size = 3;\n  const size_t max_filter_size = 2;\n  Matrix filter(max_filter_size, max_filter_size);\n  Matrix input(image_size, image_size);\n  Matrix expected(image_size + max_filter_size, image_size + max_filter_size);\n  Matrix output(image_size + max_filter_size, image_size + max_filter_size);\n\n  //////////////////////////////////////////////////////////////////////\n  //\n  // Test different filter sizes\n  //\n  input.resize(image_size, image_size);\n  input <<\n      1, 2, 3,\n      4, 5, 6,\n      7, 8, 9;\n\n  // 1x1\n  filter.resize(1, 1);\n  filter <<\n      3;\n  expected.resize(3, 3);\n  expected <<\n      3,  6,  9,\n     12, 15, 18,\n     21, 24, 27;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::full_conv(input, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 2x2\n  filter.resize(2, 2);\n  filter <<\n      1, 2,\n      3, 4;\n  expected.resize(4, 4);\n  expected <<\n      4, 11, 18, 9,\n     18, 37, 47, 21,\n     36, 67, 77, 33,\n     14, 23, 26, 9;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::full_conv(input, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 2x3\n  filter.resize(2, 3);\n  filter <<\n      1, 2, 3,\n      4, 5, 6;\n  expected.resize(4, 5);\n  expected <<\n      6,  17,  32, 23, 12,\n     27,  58,  91, 58, 27,\n     54, 106, 154, 94, 42,\n     21,  38,  50, 26, 9;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::full_conv(input, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 3x3\n  filter.resize(3, 3);\n  filter <<\n      1, 2, 3,\n      4, 5, 6,\n      7, 8, 9;\n  expected.resize(5, 5);\n  expected <<\n      9,  26,  50,  38,  21,\n     42,  94, 154, 106,  54,\n     90, 186, 285, 186,  90,\n     54, 106, 154,  94,  42,\n     21,  38,  50,  26,   9;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::full_conv(input, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n}\n\nBOOST_AUTO_TEST_CASE(FullConvOp_Batch_Test)\n{\n  BOOST_TEST_MESSAGE(\"*** Full convolutional operation batch test ...\");\n\n  const size_t max_filter_size = 4;\n  const MatrixSize image_size = 3;\n  const MatrixSize input_size = image_size * image_size;\n  const MatrixSize batch_size = 3;\n  Matrix filter(max_filter_size, max_filter_size);\n  VectorBatch input, output, expected;\n\n  //////////////////////////////////////////////////////////////////////\n  //\n  // Test different filter sizes\n  //\n  resize_batch(input, batch_size, input_size);\n  input << 1, 0, 1,\n           0, 1, 0,\n           1, 0, 0,\n           ///////\n           0, 0, 0,\n           0, 0, 0,\n           0, 0, 0,\n           ///////\n           1, 1, 1,\n           1, 1, 1,\n           1, 1, 1;\n\n  // 1x1\n  filter.resize(1, 1);\n  filter << 1;\n  resize_batch(expected, batch_size, 3 * 3);\n  expected << 1, 0, 1,\n              0, 1, 0,\n              1, 0, 0,\n              ///////\n              0, 0, 0,\n              0, 0, 0,\n              0, 0, 0,\n              ///////\n              1, 1, 1,\n              1, 1, 1,\n              1, 1, 1;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::full_conv(input, image_size, image_size, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 2x2\n  filter.resize(2, 2);\n  filter << 1, 1,\n            1, 0;\n  resize_batch(expected, batch_size, 4 * 4);\n  expected << 0, 1, 0, 1,\n              1, 1, 2, 1,\n              0, 2, 1, 0,\n              1, 1, 0, 0,\n              //////////\n              0, 0, 0, 0,\n              0, 0, 0, 0,\n              0, 0, 0, 0,\n              0, 0, 0, 0,\n              //////////\n              0, 1, 1, 1,\n              1, 3, 3, 2,\n              1, 3, 3, 2,\n              1, 2, 2, 1;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::full_conv(input, image_size, image_size, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 2x3\n  filter.resize(2, 3);\n  filter << 1, 1, 1,\n            1, 0, 0;\n  resize_batch(expected, batch_size, 4 * 5);\n  expected << 0, 0, 1, 0, 1,\n              1, 1, 2, 2, 1,\n              0, 1, 2, 1, 0,\n              1, 1, 1, 0, 0,\n              /////////////\n              0, 0, 0, 0, 0,\n              0, 0, 0, 0, 0,\n              0, 0, 0, 0, 0,\n              0, 0, 0, 0, 0,\n              /////////////\n              0, 0, 1, 1, 1,\n              1, 2, 4, 3, 2,\n              1, 2, 4, 3, 2,\n              1, 2, 3, 2, 1;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::full_conv(input, image_size, image_size, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n  // 3x3\n  filter.resize(3, 3);\n  filter << 1, 1, 1,\n            1, 0, 0,\n            1, 0, 1;\n  resize_batch(expected, batch_size, 5 * 5);\n  expected << 1, 0, 2, 0, 1,\n              0, 1, 1, 1, 1,\n              2, 1, 3, 2, 1,\n              0, 1, 2, 1, 0,\n              1, 1, 1, 0, 0,\n              /////////////\n              0, 0, 0, 0, 0,\n              0, 0, 0, 0, 0,\n              0, 0, 0, 0, 0,\n              0, 0, 0, 0, 0,\n              0, 0, 0, 0, 0,\n              /////////////\n              1, 1, 2, 1, 1,\n              1, 1, 3, 2, 2,\n              2, 3, 6, 4, 3,\n              1, 2, 4, 3, 2,\n              1, 2, 3, 2, 1;\n  output.resizeLike(expected);\n  {\n     // ensure we don't do allocations in eigen\n     BlockAllocations block;\n     ConvolutionalLayer::full_conv(input, image_size, image_size, filter, output);\n  }\n  BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));\n\n}\n\nBOOST_AUTO_TEST_CASE(Rotate180_Test)\n{\n  BOOST_TEST_MESSAGE(\"*** Rotate180 test ...\");\n\n  const MatrixSize input0_size = 2;\n  Matrix input0(input0_size, input0_size);\n  input0 << 1, 2,\n            3, 4;\n  Matrix expected0(input0_size, input0_size);\n  expected0 << 4, 3,\n               2, 1;\n  Matrix output0(input0_size, input0_size);\n  {\n       // ensure we don't do allocations in eigen\n       BlockAllocations block;\n       ConvolutionalLayer::rotate180(input0, output0);\n  }\n  BOOST_CHECK(expected0.isApprox(output0, TEST_TOLERANCE));\n\n  const MatrixSize input1_size = 3;\n  Matrix input1(input1_size, input1_size);\n  input1 << 1, 2, 3,\n            4, 5, 6,\n            7, 8, 9;\n  Matrix expected1(input1_size, input1_size);\n  expected1 << 9, 8, 7,\n               6, 5, 4,\n               3, 2, 1;\n  Matrix output1(input1_size, input1_size);\n  {\n       // ensure we don't do allocations in eigen\n       BlockAllocations block;\n       ConvolutionalLayer::rotate180(input1, output1);\n  }\n  BOOST_CHECK(expected1.isApprox(output1, TEST_TOLERANCE));\n}\n\nBOOST_AUTO_TEST_CASE(FeedForward_Test)\n{\n  BOOST_TEST_MESSAGE(\"*** ConvolutionalLayer FeedForward test ...\");\n\n  const MatrixSize image_size = 5;\n  const MatrixSize input_size = image_size * image_size;\n  const MatrixSize filter_size = 3;\n  const MatrixSize batch_size = 2;\n  const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size(\n      image_size, image_size, filter_size);\n\n  Matrix ww(filter_size, filter_size);\n  VectorBatch input, expected_output;\n  resize_batch(input, batch_size, input_size);\n  resize_batch(expected_output, batch_size, output_size);\n\n  ww <<\n      1, 0, 1,\n      0, 1, 0,\n      1, 0, 1;\n\n  input <<\n      1, 0, 1, 0, 0,\n      0, 1, 0, 0, 0,\n      1, 0, 1, 0, 0,\n      0, 0, 0, 0, 0,\n      0, 0, 0, 0, 1,\n      /////////////\n      0, 0, 1, 0, 1,\n      0, 1, 0, 1, 0,\n      1, 0, 1, 0, 1,\n      0, 1, 0, 1, 0,\n      1, 0, 1, 0, 0;\n\n  expected_output <<\n      5.5, 0.5, 2.5,\n      0.5, 2.5, 0.5,\n      2.5, 0.5, 2.5,\n      /////////////\n      4.5, 0.5, 5.5,\n      0.5, 5.5, 0.5,\n      5.5, 0.5, 4.5;\n\n  auto layer = make_unique<ConvolutionalLayer>(image_size, image_size, filter_size);\n  BOOST_CHECK(layer);\n  layer->set_activation_function(make_unique<IdentityFunction>());\n  layer->set_values(ww, 0.5);\n\n  test_layer_feedforward(*layer, input, expected_output);\n}\n\nBOOST_AUTO_TEST_CASE(Backprop_Test)\n{\n  BOOST_TEST_MESSAGE(\"*** ConvolutionalLayer backprop test ...\");\n\n  const MatrixSize image_size = 3;\n  const MatrixSize input_size = image_size * image_size;\n  const MatrixSize filter_size = 2;\n  const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size(\n      image_size, image_size, filter_size);\n  const double learning_rate = 0.1;\n  const size_t epochs = 100;\n  const MatrixSize batch_size = 2;\n\n  Matrix ww(filter_size, filter_size);\n  VectorBatch input, expected_output;\n  resize_batch(input, batch_size, input_size);\n  resize_batch(expected_output, batch_size, output_size);\n\n  ww <<\n      0, 0,\n      0, 1;\n\n  input <<\n      0, 0, 0,\n      0, 1, 1,\n      0, 1, 0,\n      ////////\n      0, 0, 0,\n      1, 1, 0,\n      1, 0, 0;\n\n  expected_output <<\n      1, 0,\n      0, 0,\n      ////\n      0, 0,\n      1, 0;\n\n  auto layer = make_unique<ConvolutionalLayer>(image_size, image_size, filter_size);\n  BOOST_CHECK(layer);\n  layer->set_activation_function(make_unique<IdentityFunction>());\n  layer->set_values(ww, 0.0);\n\n  test_layer_backprop(\n      *layer,\n      input,\n      boost::none,\n      expected_output,\n      make_unique<QuadraticCost>(),\n      learning_rate,\n      epochs\n  );\n}\n\nBOOST_AUTO_TEST_CASE(Backprop_OnVector_Test)\n{\n  BOOST_TEST_MESSAGE(\"*** ConvolutionalLayer backprop on vector test ...\");\n\n  const MatrixSize shift = 4;\n  const MatrixSize image_size = 3;\n  const MatrixSize input_size = image_size * image_size;\n  const MatrixSize filter_size = 2;\n  const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size(\n      image_size, image_size, filter_size);\n  const double learning_rate = 0.1;\n  const size_t epochs = 100;\n  const MatrixSize batch_size = 2;\n\n  Matrix ww(filter_size, filter_size);\n  Vector input_buffer(shift + batch_size * input_size);\n  MapMatrix input(input_buffer.data() + shift, batch_size, input_size); // this assumes RowMajor layout\n  VectorBatch expected_output;\n  resize_batch(expected_output, batch_size, output_size);\n\n  ww <<\n      0, 0,\n      0, 1;\n\n  input_buffer <<\n      1, 2, 3, 4, // shift\n      0, 0, 0,\n      0, 1, 1,\n      0, 1, 0,\n      ////////\n      0, 0, 0,\n      1, 1, 0,\n      1, 0, 0;\n\n  expected_output <<\n      1, 0,\n      0, 0,\n      ////\n      0, 0,\n      1, 0;\n\n  auto layer = make_unique<ConvolutionalLayer>(image_size, image_size, filter_size);\n  BOOST_CHECK(layer);\n  layer->set_activation_function(make_unique<IdentityFunction>());\n  layer->set_values(ww, 0.0);\n\n  test_layer_backprop(\n      *layer,\n      input,\n      boost::none,\n      expected_output,\n      make_unique<QuadraticCost>(),\n      learning_rate,\n      epochs\n  );\n}\n\nBOOST_AUTO_TEST_CASE(Training_WithIdentity_Test)\n{\n  BOOST_TEST_MESSAGE(\"*** ConvolutionalLayer with Identity activation training test ...\");\n\n  const MatrixSize image_rows  = 6;\n  const MatrixSize image_cols  = 3;\n  const MatrixSize input_size  = image_rows * image_cols;\n  const MatrixSize filter_size = 2;\n  const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size(image_rows, image_cols, filter_size);\n  const MatrixSize batch_size  = 2;\n\n\n  VectorBatch input, expected;\n  resize_batch(input, batch_size, input_size);\n  resize_batch(expected, batch_size, output_size);\n\n  input <<\n      0.01, 0.02, 0.11, 0.10, 0.13, 0.18,\n      0.03, 0.04, 0.12, 0.09, 0.14, 0.17,\n      0.05, 0.06, 0.07, 0.08, 0.15, 0.16,\n      ///////////////////////////////////\n      0.02, 0.06, 0.08, 0.10, 0.13, 0.14,\n      0.03, 0.02, 0.07, 0.09, 0.16, 0.15,\n      0.04, 0.05, 0.13, 0.11, 0.16, 0.18;\n\n  expected <<\n      0.347, 0.478, 0.308, 0.462, 0.378,\n      0.492, 0.343, 0.415, 0.409, 0.480,\n      //////////////////////////////////\n      0.373, 0.446, 0.282, 0.368, 0.395,\n      0.442, 0.332, 0.492, 0.429, 0.530;\n\n  // create layer\n  auto layer = make_unique<ConvolutionalLayer>(image_rows, image_cols, filter_size);\n  BOOST_CHECK(layer);\n  layer->set_activation_function(make_unique<IdentityFunction>());\n  layer->init(Layer::InitMode_Zeros, boost::none);\n\n  // test\n  test_layer_training(\n      *layer,\n      input,\n      expected,\n      batch_size, // tests num\n      make_unique<QuadraticCost>(),\n      0.09, // learning rate\n      8000  // epochs\n  );\n}\n\n\nBOOST_AUTO_TEST_CASE(Training_WithSigmoid_Test)\n{\n  BOOST_TEST_MESSAGE(\"*** ConvolutionalLayer with Sigmoid activation training test ...\");\n\n  const MatrixSize image_rows  = 6;\n  const MatrixSize image_cols  = 3;\n  const MatrixSize input_size  = image_rows * image_cols;\n  const MatrixSize filter_size = 2;\n  const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size(image_rows, image_cols, filter_size);\n  const MatrixSize batch_size  = 2;\n\n\n  VectorBatch input, expected;\n  resize_batch(input, batch_size, input_size);\n  resize_batch(expected, batch_size, output_size);\n\n  input <<\n      0.01, 0.02, 0.11, 0.10, 0.13, 0.18,\n      0.03, 0.04, 0.12, 0.09, 0.14, 0.17,\n      0.05, 0.06, 0.07, 0.08, 0.15, 0.16,\n      ///////////////////////////////////\n      0.02, 0.06, 0.08, 0.10, 0.13, 0.14,\n      0.03, 0.02, 0.07, 0.09, 0.16, 0.15,\n      0.04, 0.05, 0.13, 0.11, 0.16, 0.18;\n\n  expected <<\n      0.348, 0.478, 0.309, 0.462, 0.378,\n      0.492, 0.341, 0.412, 0.409, 0.480,\n      //////////////////////////////////\n      0.372, 0.445, 0.287, 0.366, 0.395,\n      0.440, 0.331, 0.494, 0.429, 0.532;\n\n  // create layer\n  auto layer = make_unique<ConvolutionalLayer>(image_rows, image_cols, filter_size);\n  BOOST_CHECK(layer);\n  layer->set_activation_function(make_unique<SigmoidFunction>());\n  layer->init(Layer::InitMode_Zeros, boost::none);\n\n  // test\n  test_layer_training(\n      *layer,\n      input,\n      expected,\n      batch_size, // tests num\n      make_unique<CrossEntropyCost>(),\n      0.75,  // learning rate\n      8000  // epochs\n  );\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// perf conv tests\n//\nBOOST_AUTO_TEST_CASE(PerfConvTest, * disabled())\n{\n  conv_perf_test(\n      1000, // size\n      10,   // filter\n      100   // epochs\n  );\n}\n\nBOOST_AUTO_TEST_CASE(PerfBatchConvTest, * disabled())\n{\n  conv_perf_batch_test(\n      10,   // batch\n      1000, // size\n      10,   // filter\n      10    // epochs\n   );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d39753420daa127b7f465efa38881a75a004d213", "size": 25873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_convlayer.cpp", "max_stars_repo_name": "lsh123/yann", "max_stars_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:14:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T10:25:07.000Z", "max_issues_repo_path": "src/test/test_convlayer.cpp", "max_issues_repo_name": "lsh123/yann", "max_issues_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/test_convlayer.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": 26.5364102564, "max_line_length": 138, "alphanum_fraction": 0.5763923782, "num_tokens": 8214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5548418816579892}}
{"text": "#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <random>\n#include <Eigen/Cholesky>\n#include <fstream>\n#include <iomanip>\n#include <srrg_system_utils/parse_command_line.h>\n\n#include \"srrg_solver/solver_core/instances.h\"\n#include \"srrg_solver/solver_core/factor_graph.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/variable_se3_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/variable_point3_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/se3_pose_pose_geodesic_error_factor.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/se3_pose_point_offset_error_factor.h\"\n#include \"srrg_solver/variables_and_factors/types_projective/se3_pose_point_omni_ba_error_factor.h\"\n\n#include \"srrg_solver/variables_and_factors/types_2d/variable_se2_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/variable_point2_ad.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/se2_pose_pose_geodesic_error_factor.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/se2_pose_point_error_factor.h\"\n\n#include \"factor_noise_adder.h\"\n\nusing namespace srrg2_core;\nusing namespace srrg2_solver;\nusing namespace std;\n\n\nconst std::string exe_name = \"solver_app_noise_adder\";\n#define LOG std::cerr << exe_name << \"|\"\n\nusing StringNoiseAdderMap=std::map<std::string, FactorNoiseAdderPtr >;\n\ndefault_random_engine rnd_gen;\nstd::normal_distribution<float> norm_gen;\n\nStringNoiseAdderMap noise_adders;\nvoid initNoiseAdders() {\n  noise_adders.insert(std::make_pair(\"SE3PosePointOffsetErrorFactor\", FactorNoiseAdderPtr(new FactorNoiseAdderEuclidean_<SE3PosePointOffsetErrorFactor>(rnd_gen, norm_gen))));\n  \n  noise_adders.insert(std::make_pair(\"SE3PosePoseGeodesicErrorFactor\", FactorNoiseAdderPtr(new FactorNoiseAdderSE3Quat_<SE3PosePoseGeodesicErrorFactor>(rnd_gen, norm_gen))));\n\n  noise_adders.insert(std::make_pair(\"SE2PosePointErrorFactor\", FactorNoiseAdderPtr(new FactorNoiseAdderEuclidean_<SE2PosePointErrorFactor>(rnd_gen, norm_gen))));\n  \n  noise_adders.insert(std::make_pair(\"SE2PosePoseGeodesicErrorFactor\", FactorNoiseAdderPtr(new FactorNoiseAdderSE2_<SE2PosePoseGeodesicErrorFactor>(rnd_gen, norm_gen))));\n\n  noise_adders.insert(std::make_pair(\"Sim3PosePoseErrorFactorAD\", FactorNoiseAdderPtr(new FactorNoiseAdderSim3_<Sim3PosePoseErrorFactorAD>(rnd_gen, norm_gen))));\n\n  noise_adders.insert(std::make_pair(\"SE3PosePointOmniBAErrorFactor\", FactorNoiseAdderPtr(new FactorNoiseAdderNormalize_<SE3PosePointOmniBAErrorFactor>(rnd_gen, norm_gen))));\n\n}\n\nstd::string listNoiseAdders() {\n  ostringstream os;\n  for (const auto& it: noise_adders) {\n    os << it.first << endl;\n  }\n  return os.str();\n}\n\nstatic const char* banner[] = {\n  \"adds noise to an (ideal) graph, based on the value of the information matrices\",\n  \"usage: solver_app_noise_adder -i <input> -o <output>\",\n  0\n};\n\n// ia THE PROGRAM\nint main(int argc, char** argv) {\n  initNoiseAdders();\n  ParseCommandLine cmd_line(argv, banner);\n  ArgumentInt seed                    (&cmd_line, \"s\",    \"seed\",           \"starting_seed\", 0);\n  ArgumentString output_file          (&cmd_line, \"o\",    \"output-file\",           \"file where to save the output\", \"\");\n  ArgumentString input_file          (&cmd_line, \"i\",    \"input-file\",             \"file where to read the input \", \"\");\n  ArgumentFlag list_adders          (&cmd_line, \"l\",    \"list-adders\",             \" prints a list of noise adders registered\");\n  cmd_line.parse();\n\n  if (seed.isSet()){\n    rnd_gen.seed(seed.value());\n  }\n  if (list_adders.isSet()) {\n    cerr << \"Adders: \" << endl;\n    cerr << listNoiseAdders() << endl;\n    return 0;\n  }\n  if (! input_file.isSet()) {\n    cerr << \"no input file provided, aborting\" << endl;\n    return 0;\n  }\n  std::cerr << \"loding file: [\" << input_file.value() << \"]... \";\n  FactorGraphPtr graph = FactorGraph::read(input_file.value());\n  std::cerr << \"done, factors:\" << graph->factors().size() << \" vars: \" << graph->variables().size() << std::endl;\n\n  std::cerr << \"adding noise...\";\n  for (auto it = graph->factors().begin();\n       it != graph->factors().end(); ++it) {\n    FactorBase* factor=it.value();\n\n    auto adder_it=noise_adders.find(factor->className());\n    if (adder_it==noise_adders.end()) {\n      cerr << \"unknown adder [\" << factor->className() << \"] skupping\" << endl;\n      continue;\n    }\n    FactorNoiseAdderPtr adder=adder_it->second;\n\n    adder->addNoise(factor);\n  }\n  \n  std::cerr << \"done\" << std::endl;\n\n  if (! output_file.isSet()) {\n    cerr << \"no output file provided, skipping output\" << endl;\n    return 0;\n  }\n\n  std::cerr << \"writing output to file [ \" << output_file.value() << \"]... \";\n  graph->write(output_file.value());\n  cerr << \" done\" << endl;\n  return 0;\n}\n", "meta": {"hexsha": "6438ea7818b698462249e1d52b26515d77263e2f", "size": 4707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/app/graph_manipulators/solver_app_noise_adder.cpp", "max_stars_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_stars_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/app/graph_manipulators/solver_app_noise_adder.cpp", "max_issues_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_issues_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/app/graph_manipulators/solver_app_noise_adder.cpp", "max_forks_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_forks_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9008264463, "max_line_length": 174, "alphanum_fraction": 0.7225408965, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5548418807181221}}
{"text": "#include <Eigen/Core>\n#include <igl/writeOBJ.h>\n#include \"platonic_solid.h\"\n\nint main(int argc, char **argv) { \n    Eigen::MatrixXd TV, OV, CV, IV, DV;\n    Eigen::MatrixXi TF, OF, CF, IF, DF;\n\n    platonic_solid::tetrahedron(TV, TF);\n    igl::writeOBJ(\"tetrahedron.obj\", TV, TF);\n\n    platonic_solid::octahedron(OV, OF);\n    igl::writeOBJ(\"octahedron.obj\", OV, OF);\n\n    platonic_solid::cube(CV, CF);\n    igl::writeOBJ(\"cube.obj\", CV, CF);\n\n    platonic_solid::icosahedron(IV, IF);\n    igl::writeOBJ(\"icosahedron.obj\", IV, IF);\n\n    platonic_solid::dodecahedron(DV, DF);\n    igl::writeOBJ(\"dodecahedron.obj\", DV, DF);\n}", "meta": {"hexsha": "67c6c783f57cee3df7c3bf9d2e0337c6a0fb8581", "size": 619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main.cpp", "max_stars_repo_name": "jmanek/platonic_solid", "max_stars_repo_head_hexsha": "6de033e9dd088c1fe641d5e29c3842d9c5bda08e", "max_stars_repo_licenses": ["MIT"], "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/main.cpp", "max_issues_repo_name": "jmanek/platonic_solid", "max_issues_repo_head_hexsha": "6de033e9dd088c1fe641d5e29c3842d9c5bda08e", "max_issues_repo_licenses": ["MIT"], "max_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.cpp", "max_forks_repo_name": "jmanek/platonic_solid", "max_forks_repo_head_hexsha": "6de033e9dd088c1fe641d5e29c3842d9c5bda08e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9130434783, "max_line_length": 46, "alphanum_fraction": 0.647819063, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5548418807181221}}
{"text": "#include <stan/math/rev/arr.hpp>\n#include <gtest/gtest.h>\n#include <boost/numeric/odeint.hpp>\n#include <test/unit/math/rev/arr/functor/util.hpp>\n#include <test/unit/math/prim/arr/functor/harmonic_oscillator.hpp>\n#include <test/unit/math/prim/arr/functor/lorenz.hpp>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\ntemplate <typename F, typename T_y0, typename T_theta>\nvoid sho_value_test(F harm_osc, std::vector<double>& y0, double t0,\n                    std::vector<double>& ts, std::vector<double>& theta,\n                    std::vector<double>& x, std::vector<int>& x_int) {\n  using stan::math::promote_scalar;\n  using stan::math::var;\n\n  std::vector<std::vector<var> > ode_res_vd = stan::math::integrate_ode_rk45(\n      harm_osc, promote_scalar<T_y0>(y0), t0, ts,\n      promote_scalar<T_theta>(theta), x, x_int, 0);\n  EXPECT_NEAR(0.995029, ode_res_vd[0][0].val(), 1e-5);\n  EXPECT_NEAR(-0.0990884, ode_res_vd[0][1].val(), 1e-5);\n\n  EXPECT_NEAR(-0.421907, ode_res_vd[99][0].val(), 1e-5);\n  EXPECT_NEAR(0.246407, ode_res_vd[99][1].val(), 1e-5);\n}\n\nvoid sho_finite_diff_test(double t0) {\n  using stan::math::var;\n  harm_osc_ode_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n\n  test_ode(harm_osc, t0, ts, y0, theta, x, x_int, 1e-8, 1e-4);\n\n  sho_value_test<harm_osc_ode_fun, double, var>(harm_osc, y0, t0, ts, theta, x,\n                                                x_int);\n  sho_value_test<harm_osc_ode_fun, var, double>(harm_osc, y0, t0, ts, theta, x,\n                                                x_int);\n  sho_value_test<harm_osc_ode_fun, var, var>(harm_osc, y0, t0, ts, theta, x,\n                                             x_int);\n}\n\nvoid sho_data_finite_diff_test(double t0) {\n  using stan::math::var;\n  harm_osc_ode_data_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x(3, 1);\n  std::vector<int> x_int(2, 0);\n\n  test_ode(harm_osc, t0, ts, y0, theta, x, x_int, 1e-8, 1e-4);\n\n  sho_value_test<harm_osc_ode_data_fun, double, var>(harm_osc, y0, t0, ts,\n                                                     theta, x, x_int);\n  sho_value_test<harm_osc_ode_data_fun, var, double>(harm_osc, y0, t0, ts,\n                                                     theta, x, x_int);\n  sho_value_test<harm_osc_ode_data_fun, var, var>(harm_osc, y0, t0, ts, theta,\n                                                  x, x_int);\n}\n\nTEST(StanAgradRevOde_integrate_ode_rk45, harmonic_oscillator_finite_diff) {\n  sho_finite_diff_test(0);\n  sho_finite_diff_test(1.0);\n  sho_finite_diff_test(-1.0);\n\n  sho_data_finite_diff_test(0);\n  sho_data_finite_diff_test(1.0);\n  sho_data_finite_diff_test(-1.0);\n}\n\nTEST(StanAgradRevOde_integrate_ode_rk45, lorenz_finite_diff) {\n  lorenz_ode_fun lorenz;\n\n  std::vector<double> y0;\n  std::vector<double> theta;\n  double t0;\n  std::vector<double> ts;\n\n  t0 = 0;\n\n  theta.push_back(10.0);\n  theta.push_back(28.0);\n  theta.push_back(8.0 / 3.0);\n  y0.push_back(10.0);\n  y0.push_back(1.0);\n  y0.push_back(1.0);\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n\n  for (int i = 0; i < 100; i++)\n    ts.push_back(0.1 * (i + 1));\n\n  test_ode(lorenz, t0, ts, y0, theta, x, x_int, 1e-8, 1e-1);\n}\n", "meta": {"hexsha": "bf697af288523c6ddc4179b36226ef84ea833ac2", "size": 3574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/arr/functor/integrate_ode_rk45_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/math/rev/arr/functor/integrate_ode_rk45_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/rev/arr/functor/integrate_ode_rk45_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0336134454, "max_line_length": 79, "alphanum_fraction": 0.62115277, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5548418702204694}}
{"text": "#include \"signing.h\"\n#include <NTL/ZZ.h>\n#include \"generalhelpers.h\"\n\nnamespace CryptoHelpers\n{\n    void ModifyHashToLong(const long long& hash, NTL::ZZ& longModifiedHash)\n    {\n        longModifiedHash = 0;\n        auto rhash = hash;\n        ReverseBytes(8, rhash);\n        ConvertHexStringToLong(\"00FFFFFFFFFFFF00\", longModifiedHash); \n\n#pragma region dirtyhackforntl\n        longModifiedHash *= NTL::power2_ZZ(16);\n        longModifiedHash += ((rhash >> 48) & 0xFFFF);\n        longModifiedHash *= NTL::power2_ZZ(16);\n        longModifiedHash += ((rhash >> 32) & 0xFFFF);\n        longModifiedHash *= NTL::power2_ZZ(16);\n        longModifiedHash += ((rhash >> 16) & 0xFFFF);\n        longModifiedHash *= NTL::power2_ZZ(16);\n        longModifiedHash += ((rhash) & 0xFFFF);\n\n#pragma endregion\n    }\n\n    bool CheckSignature(const long long& hash,const NTL::ZZ& signature,const NTL::ZZ& y,const NTL::ZZ& k)\n    {\n        NTL::ZZ a(0);\n        NTL::ZZ p(0);\n        ConvertHexStringToLong(\"9E93A4096E5416CED0242228014B67B5\", a);\n        ConvertHexStringToLong(\"AF5228967057FE1CB84B92511BE89A47\", p);\n        \n        NTL::ZZ longModifiedHash;\n        ModifyHashToLong(hash, longModifiedHash);\n        NTL::ZZ tmp1(0);\n        NTL::PowerMod(tmp1,signature, longModifiedHash, p);\n        NTL::ZZ tmp2(0);\n        NTL::ZZ tmp3(0);\n        NTL::ZZ tmp4(0);    \n        NTL::PowerMod(tmp3,a, k, p);\n        NTL::MulMod(tmp4, signature, tmp3, p);\n        NTL::PowerMod(tmp2,y, (tmp4), p);\n\n        if (tmp2 == tmp1)\n        {\n            return true;\n        }\n        return false;\n    }\n\n    bool Sign(const long long& hash, NTL::ZZ& signature, NTL::ZZ& y, NTL::ZZ& k, NTL::ZZ& g, NTL::ZZ& rnd, NTL::ZZ& z, NTL::ZZ& x)\n    {\n        NTL::ZZ longModifiedHash;\n        ModifyHashToLong(hash, longModifiedHash);\n\n        GetRandom(rnd);\n\n        NTL::ZZ a(0);\n        NTL::ZZ p(0);\n        NTL::ZZ q(0);\n        ConvertHexStringToLong(\"9E93A4096E5416CED0242228014B67B5\", a);\n        ConvertHexStringToLong(\"AF5228967057FE1CB84B92511BE89A47\", p);\n        ConvertHexStringToLong(\"57A9144B382BFF0E5C25C9288DF44D23\", q);\n        NTL::PowerMod(z,\n            a, rnd, p\n        );\n        x = NTL::RandomBits_ZZ(127);\n        y = NTL::PowerMod(a, x, p);\n        k = ((rnd*longModifiedHash - x*z) * NTL::InvMod(longModifiedHash, q)) % q;\n        g = (x*z * NTL::InvMod(longModifiedHash,q)) % q;\n        NTL::PowerMod(signature,a, g, p);\n        return true;\n    }\n}\n", "meta": {"hexsha": "2cc1ef30f9bcad49dad5b47c10c2b082b8b970ce", "size": 2448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lab2/signing.cpp", "max_stars_repo_name": "mikhaelmurmur/SimpleHash", "max_stars_repo_head_hexsha": "effb2a4da93ce7c59eb36c5057ea868ba02042ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab2/signing.cpp", "max_issues_repo_name": "mikhaelmurmur/SimpleHash", "max_issues_repo_head_hexsha": "effb2a4da93ce7c59eb36c5057ea868ba02042ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab2/signing.cpp", "max_forks_repo_name": "mikhaelmurmur/SimpleHash", "max_forks_repo_head_hexsha": "effb2a4da93ce7c59eb36c5057ea868ba02042ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2105263158, "max_line_length": 130, "alphanum_fraction": 0.5878267974, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5547324855335601}}
{"text": "// TRENTO: Reduced Thickness Event-by-event Nuclear Topology\n// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland\n// MIT License\n\n#include \"../src/nucleon.h\"\n\n#include <cmath>\n\n#include \"catch.hpp\"\n#include \"util.h\"\n\n#include \"../src/eventqty.h\"\n#include \"../src/nucleus.h\"\n#include \"../src/random.h\"\n#include <boost/math/constants/constants.hpp>\n#include <boost/multi_array.hpp>\n\n#include <iostream>\n\nusing namespace trento;\n\nTEST_CASE( \"nucleon\" ) {\n  auto fluct = 1. + .5*random::canonical<>();\n  auto xsec = 4. + 3.*random::canonical<>();\n  auto width = .5 + .2*random::canonical<>();\n  auto wsq = width*width;\n\n  auto var_map = make_var_map({\n      {\"ncoll\", false},\n      {\"fluctuation\",   fluct},\n      {\"cross-section\", xsec},\n      {\"nucleon-width\", width},\n      {\"constit-width\", width},\n      {\"constit-number\", 1},\n      {\"columns\", DefaultEventQuantityList},\n  });\n\n  NucleonCommon nc{var_map};\n\n  Proton proton{};\n  proton.sample_nucleons(0.);\n  auto& nucleon = *proton.begin();\n  while (!nc.participate(nucleon, nucleon)) {}\n\n  // truncation radius\n  auto R = 5*width;\n\n  // random angle\n  auto phi = math::double_constants::two_pi * random::canonical<>();\n  auto cs = std::cos(phi);\n  auto sn = std::sin(phi);\n\n  // thickness function\n  // check relative to zero\n  auto tzero = nc.thickness(nucleon, 0., 0.);\n  CHECK( nc.thickness(nucleon, width*cs, width*sn) == Approx(tzero*std::exp(-.5)) );\n\n  // random point inside radius\n  auto x = R * random::canonical<>();\n  auto y = R * random::canonical<>();\n  auto dsq = x*x + y*y;\n  CHECK( nc.thickness(nucleon, x, y) == Approx(tzero*std::exp(-.5*dsq/wsq)).epsilon(1e-5).margin(1e-5) );\n\n  // random point outside radius\n  auto d = R * (1 + random::canonical<>());\n  CHECK( nc.thickness(nucleon, d*cs, d*sn) == 0. );\n\n  // fluctuations\n  // just check they have unit mean -- the rest is handled by the C++ impl.\n  auto total = 0.;\n  auto n = 1e6;\n  for (auto i = 0; i < static_cast<int>(n); ++i) {\n    proton.sample_nucleons(0.);\n    nucleon = *proton.begin();\n    while (!nc.participate(nucleon, nucleon)) {}\n    total += nc.thickness(nucleon, 0., 0.) * (2*M_PI*wsq);\n  }\n\n  auto mean = total/n;\n  CHECK( mean == Approx(1.).epsilon(.003) );\n\n  // must use a Nucleus to set Nucleon position\n  // Proton conveniently sets a deterministic position\n  // a mock class would be better but this works fine\n  Proton A{}, B{};\n  A.sample_nucleons(0.);\n  B.sample_nucleons(0.);\n  auto& nA = *A.begin();\n  auto& nB = *B.begin();\n  CHECK( nA.x() == 0. );\n  CHECK( nA.y() == 0. );\n  CHECK( nA.z() == 0. );\n  CHECK( !nA.is_participant() );\n\n  // wait until the nucleons participate\n  while (!nc.participate(nA, nB)) {}\n  CHECK( nA.is_participant() );\n  CHECK( nB.is_participant() );\n\n  // resampling nucleons resets participant state\n  A.sample_nucleons(0.);\n  CHECK( !nA.is_participant() );\n\n  // test cross section\n  // min-bias impact params\n  auto bmax = nc.max_impact();\n  CHECK( bmax == Approx(6*width) );\n\n  auto nev = 1e6;\n  auto count = 0;\n  for (auto i = 0; i < static_cast<int>(nev); ++i) {\n    auto b = bmax * std::sqrt(random::canonical<>());\n    A.sample_nucleons(.5*b);\n    B.sample_nucleons(-.5*b);\n    if (nc.participate(nA, nB))\n      ++count;\n  }\n\n  auto xsec_mc = M_PI*bmax*bmax * static_cast<double>(count)/nev;\n\n  // precision is better than this, but let's be conservative\n  CHECK( xsec_mc == Approx(xsec).epsilon(.02) );\n\n  // impact larger than max should never participate\n  auto b = bmax + random::canonical<>();\n  A.sample_nucleons(.5*b);\n  B.sample_nucleons(-.5*b);\n  CHECK( !nc.participate(nA, nB) );\n\n  // very large fluctuation parameters mean no fluctuations\n  auto no_fluct_var_map = make_var_map({\n      {\"ncoll\", false},\n      {\"fluctuation\",   1e12},\n      {\"cross-section\", xsec},\n      {\"nucleon-width\", width},\n      {\"constit-width\", width},\n      {\"constit-number\", 1},\n  });\n\n  NucleonCommon no_fluct_nc{no_fluct_var_map};\n\n  proton.sample_nucleons(0.);\n  nucleon = *proton.begin();\n  while (!no_fluct_nc.participate(nucleon, nucleon)) {}\n  CHECK( no_fluct_nc.thickness(nucleon, 0, 0) == Approx(1/(2*M_PI*wsq)) );\n\n  CHECK_THROWS_AS([]() {\n    // nucleon width too small\n    auto bad_var_map = make_var_map({\n        {\"ncoll\", false},\n        {\"fluctuation\",   1.},\n        {\"cross-section\", 5.},\n        {\"nucleon-width\", .1},\n        {\"constit-width\", .1},\n        {\"constit-number\", 1},\n    });\n    NucleonCommon bad_profile{bad_var_map};\n  }(),\n  std::domain_error);\n\n  // test nucleon-nucleon cross section with random constituent substructure\n  auto nucleon_width = 0.5;\n  auto constituent_number = std::uniform_int_distribution<>{2, 6}(random::engine);\n  auto constituent_width = .3 + .2*random::canonical<>();\n\n  // Coarse-ish p+p grid.\n  auto grid_max = 3.;\n  auto grid_step = 0.1;\n  auto grid_nsteps = 60;\n\n  // constituent var map\n  var_map = make_var_map({\n      {\"ncoll\", false},\n      {\"grid-max\", grid_max},\n      {\"grid-step\", grid_step},\n      {\"fluctuation\",   1e12},\n      {\"cross-section\", xsec},\n      {\"nucleon-width\", nucleon_width},\n      {\"constit-width\", constituent_width},\n      {\"constit-number\", constituent_number},\n  });\n\n  NucleonCommon nc_constituent{var_map};\n  bmax = nc_constituent.max_impact();\n\n  // inelastic collision counter\n  count = 0;\n\n  // measure the cross section with min bias p+p collisions\n  for (auto i = 0; i < static_cast<int>(nev); ++i) {\n    b = bmax * std::sqrt(random::canonical<>());\n    A.sample_nucleons(.5*b);\n    B.sample_nucleons(-.5*b);\n    if (nc_constituent.participate(*A.begin(), *B.begin()))\n      ++count;\n  }\n\n  // calculate Monte Carlo cross section\n  xsec_mc = M_PI*bmax*bmax * static_cast<double>(count)/nev;\n\n  // assert a rather loose tolerance for the numerical cross section finder\n  CHECK( xsec_mc/xsec == Approx(1).epsilon(.02) );\n\n  // verify root-mean-square nucleon width for nucleons with substructure\n  double mean_square_width_num = 0.0;\n  double mean_square_width_denom = 0.0;\n\n  for (auto i = 0; i < 1000; ++i) {\n    A.sample_nucleons(0.);\n    auto nucleon = *A.begin();\n\n    while (!nc_constituent.participate(nucleon, nucleon)) {}\n\n    for (auto iy = 0; iy < grid_nsteps; ++iy) {\n      for (auto ix = 0; ix < grid_nsteps; ++ix) {\n        auto x = (ix + .5) * 2 * grid_max/grid_nsteps - grid_max;\n        auto y = (iy + .5) * 2 * grid_max/grid_nsteps - grid_max;\n        auto thick = nc_constituent.thickness(nucleon, x, y);\n        mean_square_width_num += (x*x + y*y)*thick;\n        mean_square_width_denom += 2*thick;\n      }\n    }\n  }\n\n  auto rms_width = std::sqrt(mean_square_width_num / mean_square_width_denom);\n\n  CHECK( rms_width == Approx(nucleon_width).epsilon(.01).margin(.01) );\n\n}\n", "meta": {"hexsha": "13c2b13566c7b8c401c93651be832e1645b68d19", "size": 6680, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/test_nucleon.cxx", "max_stars_repo_name": "dereksoeder/trento", "max_stars_repo_head_hexsha": "4645d2cd5ee68c0e7c103e43f148bd0053622839", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_nucleon.cxx", "max_issues_repo_name": "dereksoeder/trento", "max_issues_repo_head_hexsha": "4645d2cd5ee68c0e7c103e43f148bd0053622839", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_nucleon.cxx", "max_forks_repo_name": "dereksoeder/trento", "max_forks_repo_head_hexsha": "4645d2cd5ee68c0e7c103e43f148bd0053622839", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0434782609, "max_line_length": 105, "alphanum_fraction": 0.628742515, "num_tokens": 2028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.554732479372974}}
{"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": "//\n// Timing Pinocchio\n//\n// Based on timings.cpp from Pinocchio\n//\n\n#include \"pinocchio/spatial/fwd.hpp\"\n#include \"pinocchio/spatial/se3.hpp\"\n#include \"pinocchio/multibody/visitor.hpp\"\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/centroidal.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/cholesky.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/center-of-mass.hpp\"\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/parsers/urdf.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <stdlib.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include \"csv_reader.h\"\n#include \"tictoc_timer.h\"\n\n#include <Eigen/StdVector>\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::VectorXd)\n\nint main(int argc, const char ** argv)\n{\n   using namespace Eigen;\n   using namespace pinocchio;\n\n   // Check arguments\n   if (argc != 2)\n   {\n      std::cerr << \"You have to specify a robot model. Choices are: iiwa, hyq, atlas\" << std::endl;\n      return 1;\n   }\n\n   // Set robot model\n   bool floating_base;\n   std::string robot_model(argv[1]);\n   if (robot_model == \"iiwa\")\n   {\n      std::cout << \"Robot Model = \" << robot_model << std::endl;\n      floating_base = false;\n   }\n   else if ((robot_model == \"hyq\")|(robot_model == \"atlas\"))\n   {\n      std::cout << \"Robot Model = \" << robot_model << std::endl;\n      floating_base = true;\n   }\n   else\n   {\n      std::cerr << \"Invalid robot model: \" << robot_model << \"\\nChoices are: iiwa, hyq, atlas\" << std::endl;\n      return 2;\n   }\n\n   // Setup timer\n   TicToc timer(TicToc::NS);\n   const int NBT = 1000*100;\n\n   // Import URDF model\n   Model model;\n   std::string urdf_filename;\n   urdf_filename = RBD_BENCHMARKS_DIR\"/description/urdf/\"+robot_model+\".urdf\";\n   if (floating_base)\n      pinocchio::urdf::buildModel(urdf_filename,JointModelFreeFlyer(),model);\n   else\n      pinocchio::urdf::buildModel(urdf_filename,model);\n   model.gravity = Eigen::Vector3d(0,0,0);\n   Data data(model);\n   int dof = model.nv;\n   std::cout << \"dof = \" << dof << std::endl;\n\n   // Import CSV inputs\n   std::string input_filename;\n   input_filename = RBD_BENCHMARKS_DIR\"/csv/pinocchio/\"+robot_model+\"_inputs.csv\";\n   std::ifstream input_csv(input_filename.c_str());\n   CSVRow row;\n   std::vector<VectorXd> qs     (NBT, VectorXd::Zero(model.nq));\n   std::vector<VectorXd> qdots  (NBT, VectorXd::Zero(model.nv));\n   std::vector<VectorXd> qddots (NBT, VectorXd::Zero(model.nv));\n   std::vector<VectorXd> taus   (NBT, VectorXd::Zero(model.nv));\n   input_csv >> row;\n   int tot_q, tot_qdot;\n   tot_q    = model.nq;\n   tot_qdot = model.nv;\n   std::cout << \"qs, qdots = \" << tot_q << \", \" << tot_qdot << std::endl;\n   int col, start_col;\n   for(int i=0;i<NBT;++i)\n   {\n      input_csv >> row;\n      start_col = 0;                 // 0\n      for(int j=0;j<tot_q;++j)\n      {\n            col = start_col+j;\n            qs[i][j] = atof(row[col].c_str());\n      }\n      start_col = tot_q;               // 1xQ\n      for(int j=0;j<tot_qdot;++j)\n      {\n            col = start_col+j;\n            qdots[i][j] = atof(row[col].c_str());\n      }\n      start_col = tot_q+tot_qdot;      // 1xQ+1xQd\n      for(int j=0;j<tot_qdot;++j)\n      {\n            col = start_col+j;\n            qddots[i][j] = atof(row[col].c_str());\n      }\n      start_col = tot_q+2*tot_qdot;  // 1xQ+2xQd\n      for(int j=0;j<tot_qdot;++j)\n      {\n            col = start_col+j;\n            taus[i][j] = atof(row[col].c_str());\n      }\n   }\n\n   // Initialize some output variables\n   double time_data;\n\n   std::cout << \"--\" << std::endl;\n\n   // Dynamics Algorithms\n   std::string algorithm_name;\n   #ifdef RNEA_ALG\n   algorithm_name = \"rnea\";\n   std::cout << \"RNEA\" << std::endl;\n   #elif  CRBA_ALG\n   algorithm_name = \"crba\";\n   std::cout << \"CRBA\" << std::endl;\n   #elif  ABA_ALG\n   algorithm_name = \"aba\";\n   std::cout << \"ABA\" << std::endl;\n   #else\n   algorithm_name = \"rnea\";\n   std::cout << \"RNEA\" << std::endl;\n   #endif /* Dynamics Algorithms */\n\n   // Write CSV outputs\n   std::ofstream output_csv;\n   std::string output_filename;\n   std::stringstream num_inputs;\n   num_inputs << NBT;\n   output_filename = RESULTS_DIR\"/terr_\"+robot_model+\"_\"+num_inputs.str()+\"_pinocchio_\"+algorithm_name+\".csv\";\n   output_csv.open (output_filename.c_str());\n\n   SMOOTH(NBT)\n   {\n      if (_smooth != 0) output_csv << \"\\n\";\n\n      timer.tic();\n      // Dynamics Algorithms\n      #ifdef RNEA_ALG\n      rnea(model,data,qs[_smooth],qdots[_smooth],qddots[_smooth]);\n      #elif  CRBA_ALG\n      crba(model,data,qs[_smooth]);\n      #elif  ABA_ALG\n      aba(model,data,qs[_smooth],qdots[_smooth],taus[_smooth]);\n      #else\n      rnea(model,data,qs[_smooth],qdots[_smooth],qddots[_smooth]);\n      #endif /* Dynamics Algorithms */\n      time_data = timer.toc(TicToc::NS);\n\n      output_csv << time_data;\n   }\n\n   output_csv.close();\n\n   std::cout << \"--\" << std::endl;\n\n   return 0;\n}\n", "meta": {"hexsha": "e730a7cca357318bdfd7a2ed53fb12b570cdf367", "size": 5133, "ext": "cc", "lang": "C++", "max_stars_repo_path": "testbenches/pinocchio/terr_pinocchio/terr_pinocchio.cc", "max_stars_repo_name": "CobbledSteel/rbd-benchmarks-riscv", "max_stars_repo_head_hexsha": "7bbc80252901cc2ac7845945db19b77c38d6a6f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-10-15T09:56:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T12:24:30.000Z", "max_issues_repo_path": "testbenches/pinocchio/terr_pinocchio/terr_pinocchio.cc", "max_issues_repo_name": "CobbledSteel/rbd-benchmarks-riscv", "max_issues_repo_head_hexsha": "7bbc80252901cc2ac7845945db19b77c38d6a6f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-02-01T19:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-01T19:15:16.000Z", "max_forks_repo_path": "testbenches/pinocchio/terr_pinocchio/terr_pinocchio.cc", "max_forks_repo_name": "CobbledSteel/rbd-benchmarks-riscv", "max_forks_repo_head_hexsha": "7bbc80252901cc2ac7845945db19b77c38d6a6f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-02T11:21:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T03:15:20.000Z", "avg_line_length": 28.2032967033, "max_line_length": 110, "alphanum_fraction": 0.620884473, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5547324671518102}}
{"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": "#include <Eigen/Cholesky>\n#include <Eigen/Dense>\n#include \"Object.hpp\"\n\nconst double PI = 3.141592653589793238;\n \nvoid Object::internalProjection(const Eigen::Vector2d& obs) {\n    HeapType heap(edges);\n    for (size_t i = 0; i < edges.size(); i++) {\n        if (edges[i].valid)\n            heap.emplace(i);\n    }\n    while (heap.empty() == false) {\n        size_t top = heap.top();\n        heap.pop();\n        for (size_t i = 0; i < edges.size(); i++) {\n            Edge& this_edge = edges[top];\n            Edge& eg = edges[i];\n            if (eg.valid == false || &eg == &this_edge)\n                continue;\n            printf(\"Source : %lu, dst: %lu\\n\", top, i);\n            projectEdge2Edge(this_edge, obs, eg, heap);\n            printf(\"After Source : %lu, dst: %lu\\n\", top, i);\n        }\n    }\n}\n\nvoid Object::externalOcclusion(Object& obj, Eigen::Vector2d obs) {\n    HeapType heap(edges);\n    for (size_t i = 0; i < edges.size(); i++) {\n        if (edges[i].valid)\n            heap.emplace(i);\n    }\n    while (heap.empty() == false) {\n        size_t top = heap.top();\n        Edge& this_edge = edges[top];\n        heap.pop();\n        obj.externalProjector(this_edge, obs);\n    }\n}\n\nvoid Object::externalProjector(Edge& src, const Eigen::Vector2d& obs) {\n    HeapType heap(edges);\n    for (size_t i = 0; i < edges.size(); i++)\n        heap.emplace(i);\n    while (heap.empty() == false) {\n        size_t top = heap.top();\n        Edge& this_edge = edges[top];\n        heap.pop();\n        if (this_edge.valid == false) continue;\n        projectEdge2Edge(src, obs, this_edge, heap);\n    }\n    bool valid_flag = false;\n    for (size_t i = 0; i < edges.size(); i++) {\n        if (edges[i].valid == true) {\n            valid_flag = true;\n            break;\n        }\n    }\n    if (valid_flag == false)                    // \u5047\u5982\u5168\u90e8\u88ab\u906e\u6321\uff0c\u90a3\u4e48\u8fd9\u4e2aobject\u5c31\u6ca1\u6709\u6295\u5f71\u7684\u5fc5\u8981\u4e86\n        valid = false;\n}\n\nvoid Object::intialize(const std::vector<Eigen::Vector2d>& pts, const Eigen::Vector2d& obs) {\n    edges.clear();\n    Edge to_add;\n    bool zero_pushed = false;\n    for (size_t i = 1; i < pts.size(); i++) {\n        Eigen::Vector2d vec = pts[i] - pts[i - 1];\n        Eigen::Vector2d ctr_vec = (pts[i] + pts[i - 1]) / 2.0 - obs;\n        Eigen::Vector2d norm = Eigen::Vector2d(-vec(1), vec(0));\n        if (ctr_vec.dot(norm) < 0.0) {\n            if (i == 1)\n                zero_pushed = true;\n            Eigen::Vector2d o2p = pts[i - 1] - obs;\n            to_add.emplace_back();\n            to_add.back() << pts[i - 1], atan2(o2p(1), o2p(0));\n        } else {\n            if (to_add.empty() == false) {\n                Eigen::Vector2d o2p = pts[i - 1] - obs;\n                to_add.emplace_back();\n                to_add.back() << pts[i - 1], atan2(o2p(1), o2p(0));\n                edges.push_back(to_add);\n                to_add.reset();\n            }\n        }\n    }\n    Eigen::Vector2d vec = pts.front() - pts.back();\n    Eigen::Vector2d ctr_vec = (pts.back() + pts.front()) / 2.0 - obs;\n    Eigen::Vector2d norm = Eigen::Vector2d(-vec(1), vec(0));\n    if (to_add.empty() == false) {\n        Eigen::Vector2d o2p = pts.back() - obs;\n        to_add.emplace_back();\n        to_add.back() << pts.back(), atan2(o2p(1), o2p(0));\n    }\n    if (ctr_vec.dot(norm) < 0.0) {\n        if (zero_pushed == true) {\n            Edge& front = edges.front();\n            if (to_add.empty() == true) {\n                front.emplace_front();\n                Eigen::Vector2d o2p = pts.back() - obs;\n                front.front() << pts.back(), atan2(o2p(1), o2p(0));\n            } else {\n                for (Edge::const_reverse_iterator rit = to_add.crbegin(); rit != to_add.crend(); rit++)\n                    front.push_front(*rit);\n            }\n        } else {\n            if (to_add.size() == 0) {\n                Eigen::Vector2d o2p = pts.back() - obs;\n                to_add.emplace_back();\n                to_add.back() << pts.back(), atan2(o2p(1), o2p(0));  \n            }\n            Eigen::Vector2d o2p = pts.front() - obs;\n            to_add.emplace_back();\n            to_add.back() << pts.front(), atan2(o2p(1), o2p(0));\n            edges.push_back(to_add);\n        }\n    } else if (to_add.empty() == false) {\n        edges.push_back(to_add);\n    }\n    for (Edge& eg: edges) {\n        for (const Eigen::Vector3d& pt: eg) {\n            double dist = (pt.block<2, 1>(0, 0) - obs).norm();\n            if (dist < eg.min_dist) eg.min_dist = dist;\n        }\n    }\n    for (size_t i = 0; i < edges.size(); i++) {\n        Edge& eg = edges[i];\n        eg.valid = true;\n        if (eg.min_dist < min_dist)\n            min_dist = eg.min_dist;\n    }\n    valid = true;\n}\n\nvoid Object::makePolygons4Render(Eigen::Vector2d obs, std::vector<std::vector<cv::Point>>& polygons) const{\n    for (const Edge& eg: edges) {\n        if (eg.valid == false) continue;\n        polygons.emplace_back();\n        std::vector<cv::Point>& back = polygons.back();\n        back.emplace_back(obs.x(), obs.y());\n        for (const Eigen::Vector3d& p: eg) {\n            back.emplace_back(p.x(), p.y());\n        }\n    }\n}\n\nvoid Object::projectEdge2Edge(const Edge& src, const Eigen::Vector2d& obs, Edge& dst, HeapType& heap) {\n    bool pop_back_flag = true;\n    Eigen::Vector2d fpt = src.front().block<2, 1>(0, 0) - obs, ept = src.back().block<2, 1>(0, 0) - obs;\n    double f_ang = src.front().z(), e_ang = src.back().z();\n    bool head_in_range = dst.angleInRange(f_ang), end_in_range = dst.angleInRange(e_ang), mid_in_range = true;\n    if (src.size() > 2) {\n        size_t mid_id = src.size() / 2;\n        mid_in_range = dst.angleInRange(src[mid_id].z());\n    }\n    std::vector<Eigen::Vector3d> tasks;\n    if (head_in_range && end_in_range) {        \n        if (mid_in_range) {                     // \u52a0edge \u6253\u65ad\n            LOG_ERROR_STREAM(\"Breaking edge!\");\n            if (breakEdge(fpt, ept, obs, dst, heap) == true)\n                return;\n        }                          // \u7279\u6b8a\u60c5\u51b5\n        tasks.emplace_back(fpt.x(), fpt.y(), f_ang);\n        tasks.emplace_back(ept.x(), ept.y(), e_ang);\n    } else if (head_in_range) {\n        tasks.emplace_back(fpt.x(), fpt.y(), f_ang);\n    } else if (end_in_range) {\n        tasks.emplace_back(ept.x(), ept.y(), e_ang);\n        pop_back_flag = false;          // pop_front\n    } else {                            // SRC\u7684\u4e24\u4e2a\u7aef\u70b9\u4e0d\u5728DST\u8303\u56f4\u5185\uff08\u6709\u53ef\u80fd\u5b8c\u5168\u906e\u6321\u7684\uff09\n        const Eigen::Vector2d dst_f = dst.front().block<2, 1>(0, 0) - obs, dst_b = dst.back().block<2, 1>(0, 0) - obs;\n        int f_id = src.rotatedBinarySearch(dst.front().z());\n        if (f_id > 0) {\n            Eigen::Vector3d tmp;\n            bool dst_closer = rangeSuitable(src[f_id - 1], src[f_id], dst_f, obs, tmp);\n            if (dst_closer == true) return;\n        }\n        int e_id = src.rotatedBinarySearch(dst.back().z());\n        if (e_id > 0) {\n            Eigen::Vector3d tmp;\n            bool dst_closer = rangeSuitable(src[e_id - 1], src[e_id], dst_b, obs, tmp);\n            if (dst_closer == true) return;        // \u6295\u5f71\u8fb9\u7684range\u66f4\u5927\n        }\n        if (f_id <= 0 && e_id <= 0) return;          // \u53cd\u5411\u5149\u7ebf\n        if (f_id > 0 && e_id > 0) {\n            dst.valid = false;\n            return;\n        }\n        if (f_id > 0) {\n            tasks.emplace_back(ept.x(), ept.y(), e_ang);\n            pop_back_flag = false;          // pop_front\n        } else {\n            tasks.emplace_back(fpt.x(), fpt.y(), f_ang);\n        }\n    }\n    int task_id = 0;\n    for (const Eigen::Vector3d& task: tasks) {\n        if (task_id > 0) pop_back_flag = false;\n        double angle = task.z();\n        Eigen::Vector2d beam = task.block<2, 1>(0, 0);\n        int id = dst.rotatedBinarySearch(angle);\n        if (task_id == 0 && id <= 0) {\n            LOG_ERROR_STREAM(\"Task is 0 and id <= 0\");\n            throw 0;\n        } else if (task_id > 0 && id <= 0) break;\n        Eigen::Vector3d intersect = Eigen::Vector3d::Zero();\n        if (rangeSuitable(dst[id - 1], dst[id], beam, obs, intersect) == false) {\n            return;\n        }\n        if (pop_back_flag == true) {            // \u5220\u9664\u5927\u89d2\u5ea6\n            int delete_cnt = static_cast<int>(dst.size()) - id;\n            for (int i = 0; i < delete_cnt; i++)\n                dst.pop_back();\n            dst.emplace_back(intersect);\n        } else {\n            for (int i = 0; i < id; i++) {\n                dst.pop_front();\n            }\n            dst.emplace_front(intersect);\n        }\n        for (const Eigen::Vector3d& pt: dst) {\n            double dist = (pt.block<2, 1>(0, 0) - obs).norm();\n            if (dist < dst.min_dist) dst.min_dist = dist;\n        }\n        task_id ++;\n    }\n}\n\nbool Object::breakEdge(Eigen::Vector2d b1, Eigen::Vector2d b2, Eigen::Vector2d obs, Edge& dst, HeapType& heap) {\n    std::array<Eigen::Vector2d, 2> task = {b1, b2};\n    std::vector<Eigen::Vector3d> crs;\n    std::array<size_t, 2> ids = {0, 0};\n    for (size_t i = 0; i < 2; i++) {\n        const Eigen::Vector2d& beam = task[i];\n        double this_angle = atan2(beam(1), beam(0));\n        int id = dst.rotatedBinarySearch(this_angle);\n        Eigen::Vector3d intersect = Eigen::Vector3d::Zero();\n        if (rangeSuitable(dst[id - 1], dst[id], beam, obs, intersect) == false) return true;\n        crs.emplace_back(intersect);\n        ids[i] = dst.size() - static_cast<size_t>(id);\n    }\n    if (ids[0] < ids[1]) return false;\n    Edge new_edge;\n    size_t add_cnt = 0;\n    for (Edge::const_reverse_iterator rit = dst.crbegin(); rit != dst.crend() && add_cnt < ids[1]; rit++, add_cnt++)\n        new_edge.push_front(*rit);\n    new_edge.push_front(crs[1]);\n    new_edge.initWithObs(obs);\n    for (size_t i = 0; i < ids[0]; i++)\n        dst.pop_back();\n    dst.push_back(crs[0]);\n    for (const Eigen::Vector3d& pt: dst) {\n        double dist = (pt.block<2, 1>(0, 0) - obs).norm();\n        if (dist < dst.min_dist) dst.min_dist = dist;\n    }\n    edges.push_back(new_edge);\n    heap.emplace(edges.size() - 1);              // \u53ef\u80fd\u4e0d\u592a\u5b89\u5168\n    return true;\n}\n\nvoid Object::visualizeEdges(cv::Mat& src, cv::Point obs) const{\n    if (valid == false)\n        return;\n    int cnt = -1;\n    for (const Edge& eg: edges) {\n        cnt++;\n        if (eg.valid == false) continue;\n        for (size_t i = 1; i < eg.size(); i++) {\n            cv::line(src, cv::Point(eg[i - 1].x(), eg[i - 1].y()), cv::Point(eg[i].x(), eg[i].y()), cv::Scalar(0, 255, 255), 3);\n        }\n        char str[8];\n        snprintf(str, 8, \"%d:%lu\", cnt, eg.size());\n\t\tcv::putText(src, str, cv::Point(eg.front().x(), eg.front().y()) + cv::Point(10, 10),\n\t\t\t\t\tcv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(0, 255, 0));\n        cv::circle(src, cv::Point(eg.front().x(), eg.front().y()), 3, cv::Scalar(255, 255, 0), -1);\n        cv::circle(src, cv::Point(eg.back().x(), eg.back().y()), 3, cv::Scalar(255, 0, 255), -1);\n    }\n    cv::circle(src, obs, 4, cv::Scalar(0, 255, 0), -1);\n}\n\nEigen::Vector3d Object::getIntersection(\n    const Eigen::Vector2d& vec,\n    const Eigen::Vector3d& _p1,\n    const Eigen::Vector3d& _p2, \n    const Eigen::Vector2d& obs\n) {\n    const Eigen::Vector2d p1 = _p1.block<2, 1>(0, 0), p2 = _p2.block<2, 1>(0, 0);\n    const Eigen::Vector2d vec_line = p2 - p1;\n    Eigen::Matrix2d A = Eigen::Matrix2d::Zero();\n    A << -vec(1), vec(0), -vec_line(1), vec_line(0);\n    double b1 = Eigen::RowVector2d(-vec(1), vec(0)) * obs;\n    double b2 = Eigen::RowVector2d(-vec_line(1), vec_line(0)) * p1;\n    const Eigen::Vector2d b(b1, b2);\n    double det = A(0, 0) * A(1, 1) - A(0, 1) * A(1, 0);\n    if (std::abs(det) < 1e-5)\n        return _p1;\n    const Eigen::Vector2d pt = A.inverse() * b, new_vec = pt - obs;\n    double angle = atan2(new_vec(1), new_vec(0));\n    Eigen::Vector3d result;\n    result << pt, angle;\n    return result;                   // \u89e3\u4ea4\u70b9\n}\n\nbool Object::rangeSuitable(\n    const Eigen::Vector3d& p1, \n    const Eigen::Vector3d& p2, \n    const Eigen::Vector2d& beam, \n    const Eigen::Vector2d& obs,\n    Eigen::Vector3d& intersect\n) const {\n    intersect = getIntersection(beam, p1, p2, obs);\n    double range = (intersect.block<2, 1>(0, 0) - obs).norm();\n    return beam.norm() < range;\n}\n\nvoid Object::anglePostCheck(const Eigen::Vector2d& obs) {\n    size_t max_size = edges.size();\n    for (size_t j = 0; j < max_size; j++) {\n        Edge& eg = edges[j];\n        if (eg.size() < 4) continue;\n        double front_angle = eg.front().z();\n        int size_1 = static_cast<int>(eg.size()) - 1, id = 2;\n        bool break_judge = false;\n        for (; id < size_1; id++) {\n            if (eg.angleInRange(front_angle, id, id + 1) == false) continue;\n            break_judge = true;\n            break;\n        }\n        if (break_judge == false) continue;\n        int pop_cnt = size_1 - id;\n        Edge new_edge;\n        for (int i = 0; i < pop_cnt; i++) {\n            Eigen::Vector3d pt = eg.back();\n            eg.pop_back();\n            new_edge.emplace_front(pt);\n        }\n        new_edge.emplace_front(eg.back());\n        new_edge.initWithObs(obs);\n        edges.push_back(new_edge);\n    }\n}\n", "meta": {"hexsha": "ee6aa04a528d7cbf89f06cf3d39f1d33e4aa0b17", "size": 12943, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Object.cc", "max_stars_repo_name": "Enigmatisms/Volume", "max_stars_repo_head_hexsha": "4bdb34d715dd46bf6c19399c30daf74fe82566e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-02T08:52:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T02:01:21.000Z", "max_issues_repo_path": "src/Object.cc", "max_issues_repo_name": "Enigmatisms/Volume", "max_issues_repo_head_hexsha": "4bdb34d715dd46bf6c19399c30daf74fe82566e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Object.cc", "max_forks_repo_name": "Enigmatisms/Volume", "max_forks_repo_head_hexsha": "4bdb34d715dd46bf6c19399c30daf74fe82566e1", "max_forks_repo_licenses": ["Apache-2.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.7346938776, "max_line_length": 128, "alphanum_fraction": 0.5213628989, "num_tokens": 3914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5547036239249146}}
{"text": "#pragma once\n#include <vector>\n#include <memory>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include \"MACGrid.hpp\"\n\ntypedef Eigen::Triplet<double> T;\n\nclass Simulator\n{\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  Simulator(std::shared_ptr<MACGrid> grids, double &time);\n  ~Simulator();\n\n  void update();\n\nprivate:\n  void setEmitterVelocity();\n  void addSource();\n\n  void resetForce();\n  void calVorticity();\n  void addForce();\n  void calPressure();\n  void applyPressureTerm();\n  void advectVelocity();\n  void advectScalar();\n\n  std::shared_ptr<MACGrid> m_grids;\n  double &m_time;\n\n  // solver\n  std::vector<T> tripletList;\n  Eigen::ConjugateGradient<Eigen::SparseMatrix<double>, Eigen::Lower | Eigen::Upper> ICCG;\n\n  Eigen::SparseMatrix<double, Eigen::RowMajor> A;\n  Eigen::VectorXd b;\n  Eigen::VectorXd x;\n};", "meta": {"hexsha": "3e331b3c639146bdaf9c2428d79f862b82b9db3c", "size": 813, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Simulator.hpp", "max_stars_repo_name": "daichi-ishida/Visual-Simulation-of-Smoke", "max_stars_repo_head_hexsha": "b925d0cfc86f642ab4ee9470e67360b2ab5adcb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-06-12T11:42:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T00:57:46.000Z", "max_issues_repo_path": "include/Simulator.hpp", "max_issues_repo_name": "daichi-ishida/Visual-Simulation-of-Smoke", "max_issues_repo_head_hexsha": "b925d0cfc86f642ab4ee9470e67360b2ab5adcb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-05-10T13:32:02.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-12T18:32:53.000Z", "max_forks_repo_path": "include/Simulator.hpp", "max_forks_repo_name": "daichi-ishida/Visual-Simulation-of-Smoke", "max_forks_repo_head_hexsha": "b925d0cfc86f642ab4ee9470e67360b2ab5adcb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-01-06T07:07:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T15:43:00.000Z", "avg_line_length": 19.3571428571, "max_line_length": 90, "alphanum_fraction": 0.7146371464, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.554699463405774}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"STFT.hpp\"\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/Munkres.hpp\"\n#include \"../util/OptimalTransport.hpp\"\n#include \"../util/RTPGHI.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass NMFMorph\n{\n\npublic:\n  using MatrixXd = Eigen::MatrixXd;\n\n  void init(RealMatrixView W1, RealMatrixView W2, RealMatrixView H,\n            index winSize, index fftSize, index hopSize, bool assign)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    using namespace std;\n    mInitialized = false;\n    mW1 = asEigen<Matrix>(W1).transpose();\n    mH = asEigen<Matrix>(H);\n    MatrixXd tmpW2 = asEigen<Matrix>(W2).transpose();\n    ArrayXXd cost = ArrayXXd::Zero(mW1.cols(), tmpW2.cols());\n    if (assign)\n    {\n      for (index i = 0; i < mW1.cols(); i++)\n      {\n        for (index j = 0; j < tmpW2.cols(); j++)\n        {\n          OptimalTransport tmpOT;\n          tmpOT.init(mW1.col(i), tmpW2.col(j));\n          if(!tmpOT.initialized()) return;\n          cost(i, j) = tmpOT.mDistance;\n        }\n      }\n      Munkres munk;\n      munk.init(mW1.cols(), tmpW2.cols());\n      ArrayXi result = ArrayXi::Zero(mW1.cols());\n      munk.process(cost, result);\n      mW2 = MatrixXd::Zero(tmpW2.rows(), tmpW2.cols());\n      for (index i = 0; i < result.size(); i++)\n      { mW2.col(i) = tmpW2.col(result(i)); }\n    }\n    else\n    {\n      mW2 = asEigen<Matrix>(W2).transpose();\n    }\n    mWindowSize = winSize;\n    mFFTSize = fftSize;\n    mHopSize = hopSize;\n    mRTPGHI.init(fftSize);\n\n    index rank = mW1.cols();\n    mOT = std::vector<OptimalTransport>(asUnsigned(rank));\n    for (index i = 0; i < rank; i++) { mOT[asUnsigned(i)].init(mW1.col(i), mW2.col(i)); }\n    mPos = 0;\n    mInitialized = true;\n  }\n  \n  bool initialized() { return mInitialized; }\n\n  void processFrame(ComplexVectorView v, double interpolation)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    MatrixXd W = MatrixXd::Zero(mW1.rows(), mW1.cols());\n    for (int i = 0; i < W.cols(); i++)\n    {\n      ArrayXd out = ArrayXd::Zero(mW2.rows());\n      mOT[asUnsigned(i)].interpolate(interpolation, out);\n      W.col(i) = out;\n    }\n\n    VectorXd       hFrame = mH.col(mPos);\n    VectorXd       frame = W * hFrame;\n    RealVectorView mag1 = asFluid(frame);\n    mRTPGHI.processFrame(mag1, v, mWindowSize, mFFTSize, mHopSize, 1e-6);\n    mPos = (mPos + 1) % mH.cols();\n  }\n\nprivate:\n  MatrixXd                      mW1;\n  MatrixXd                      mW2;\n  MatrixXd                      mH;\n  index                         mWindowSize;\n  index                         mHopSize;\n  index                         mFFTSize;\n  RTPGHI                        mRTPGHI;\n  std::vector<OptimalTransport> mOT;\n  int                           mPos{0};\n  bool                          mInitialized;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "59309436c288459dc7d6bbe8d3a2b48c55b6a90b", "size": 3380, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/NMFMorph.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/NMFMorph.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/NMFMorph.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3913043478, "max_line_length": 89, "alphanum_fraction": 0.5979289941, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5546994553199932}}
{"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 <fstream>\n#include <boost/config.hpp>\n#include <boost/version.hpp>\n\n// CGAL headers\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n\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 \"TriangulationCircumcircle.h\"\n#include \"TriangulationMovingPoint.h\"\n#include \"TriangulationConflictZone.h\"\n#include \"TriangulationRemoveVertex.h\"\n#include \"TriangulationPointInputAndConflictZone.h\"\n#include <CGAL/Qt/TriangulationGraphicsItem.h>\n#include <CGAL/Qt/VoronoiGraphicsItem.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_Delaunay_triangulation_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::Delaunay_triangulation_2<K> Delaunay;\n\nclass MainWindow :\n  public CGAL::Qt::DemosMainWindow,\n  public Ui::Delaunay_triangulation_2\n{\n  Q_OBJECT\n\nprivate:\n  Delaunay dt;\n  QGraphicsScene scene;\n\n  CGAL::Qt::TriangulationGraphicsItem<Delaunay> * dgi;\n  CGAL::Qt::VoronoiGraphicsItem<Delaunay> * vgi;\n\n  CGAL::Qt::TriangulationMovingPoint<Delaunay> * mp;\n  CGAL::Qt::TriangulationConflictZone<Delaunay> * cz;\n  CGAL::Qt::TriangulationRemoveVertex<Delaunay> * trv;\n  CGAL::Qt::TriangulationPointInputAndConflictZone<Delaunay> * pi;\n  CGAL::Qt::TriangulationCircumcircle<Delaunay> *tcc;\npublic:\n  MainWindow();\n\npublic Q_SLOTS:\n\n  void processInput(CGAL::Object o);\n\n  void on_actionMovingPoint_toggled(bool checked);\n\n  void on_actionShowConflictZone_toggled(bool checked);\n\n  void on_actionCircumcenter_toggled(bool checked);\n\n  void on_actionShowDelaunay_toggled(bool checked);\n\n  void on_actionShowVoronoi_toggled(bool checked);\n\n  void on_actionInsertPoint_toggled(bool checked);\n\n  void on_actionInsertRandomPoints_triggered();\n\n  void on_actionLoadPoints_triggered();\n\n  void on_actionSavePoints_triggered();\n\n  void on_actionClear_triggered();\n\n  void on_actionRecenter_triggered();\n\n  virtual void open(QString fileName);\n\nQ_SIGNALS:\n  void changed();\n};\n\n\nMainWindow::MainWindow()\n  : DemosMainWindow()\n{\n  setupUi(this);\n\n  this->graphicsView->setAcceptDrops(false);\n\n  // Add a GraphicItem for the Delaunay triangulation\n  dgi = new CGAL::Qt::TriangulationGraphicsItem<Delaunay>(&dt);\n\n  QObject::connect(this, SIGNAL(changed()),\n                   dgi, SLOT(modelChanged()));\n\n  dgi->setVerticesPen(QPen(Qt::red, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(dgi);\n\n  // Add a GraphicItem for the Voronoi diagram\n  vgi = new CGAL::Qt::VoronoiGraphicsItem<Delaunay>(&dt);\n\n  QObject::connect(this, SIGNAL(changed()),\n                   vgi, SLOT(modelChanged()));\n\n  vgi->setEdgesPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(vgi);\n  vgi->hide();\n\n  // Setup input handlers. They get events before the scene gets them\n  // and the input they generate is passed to the triangulation with\n  // the signal/slot mechanism\n  pi = new CGAL::Qt::TriangulationPointInputAndConflictZone<Delaunay>(&scene, &dt, this );\n\n  QObject::connect(pi, SIGNAL(generate(CGAL::Object)),\n                   this, SLOT(processInput(CGAL::Object)));\n\n  mp = new CGAL::Qt::TriangulationMovingPoint<Delaunay>(&dt, this);\n  // TriangulationMovingPoint<Delaunay> emits a modelChanged() signal each\n  // time the moving point moves.\n  // The following connection is for the purpose of emitting changed().\n  QObject::connect(mp, SIGNAL(modelChanged()),\n                   this, SIGNAL(changed()));\n\n  trv = new CGAL::Qt::TriangulationRemoveVertex<Delaunay>(&dt, this);\n  QObject::connect(trv, SIGNAL(modelChanged()),\n                   this, SIGNAL(changed()));\n\n  tcc = new CGAL::Qt::TriangulationCircumcircle<Delaunay>(&scene, &dt, this);\n  tcc->setPen(QPen(Qt::red, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n\n  cz = new CGAL::Qt::TriangulationConflictZone<Delaunay>(&scene, &dt, this);\n\n  //\n  // Manual handling of actions\n  //\n\n  QObject::connect(this->actionQuit, SIGNAL(triggered()),\n                   this, SLOT(close()));\n\n  // We put mutually exclusive actions in an QActionGroup\n  QActionGroup* ag = new QActionGroup(this);\n  ag->addAction(this->actionInsertPoint);\n  ag->addAction(this->actionMovingPoint);\n  ag->addAction(this->actionCircumcenter);\n  ag->addAction(this->actionShowConflictZone);\n\n  // Check two actions\n  this->actionInsertPoint->setChecked(true);\n  this->actionShowDelaunay->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_Delaunay_triangulation_2.html\");\n  this->addAboutCGAL();\n  this->setupExportSVG(actionExport_SVG, graphicsView);\n\n  this->addRecentFiles(this->menuFile, this->actionQuit);\n  connect(this, SIGNAL(openRecentFile(QString)),\n          this, SLOT(open(QString)));\n}\n\n\nvoid\nMainWindow::processInput(CGAL::Object o)\n{\n  Point_2 p;\n  if(CGAL::assign(p, o)){\n    dt.insert(p);\n  }\n  Q_EMIT( changed());\n}\n\n\n/*\n *  Qt Automatic Connections\n *  https://doc.qt.io/qt-5/designer-using-a-ui-file.html#automatic-connections\n *\n *  setupUi(this) generates connections to the slots named\n *  \"on_<action_name>_<signal_name>\"\n */\nvoid\nMainWindow::on_actionInsertPoint_toggled(bool checked)\n{\n  if(checked){\n    scene.installEventFilter(pi);\n    scene.installEventFilter(trv);\n  } else {\n    scene.removeEventFilter(pi);\n    scene.removeEventFilter(trv);\n  }\n}\n\n\nvoid\nMainWindow::on_actionMovingPoint_toggled(bool checked)\n{\n\n  if(checked){\n    scene.installEventFilter(mp);\n  } else {\n    scene.removeEventFilter(mp);\n  }\n}\n\n\nvoid\nMainWindow::on_actionShowConflictZone_toggled(bool checked)\n{\n\n  if(checked){\n    scene.installEventFilter(cz);\n  } else {\n    scene.removeEventFilter(cz);\n  }\n}\n\nvoid\nMainWindow::on_actionCircumcenter_toggled(bool checked)\n{\n  if(checked){\n    scene.installEventFilter(tcc);\n    tcc->show();\n  } else {\n    scene.removeEventFilter(tcc);\n    tcc->hide();\n  }\n}\n\n\nvoid\nMainWindow::on_actionShowDelaunay_toggled(bool checked)\n{\n  dgi->setVisibleEdges(checked);\n}\n\n\nvoid\nMainWindow::on_actionShowVoronoi_toggled(bool checked)\n{\n  vgi->setVisible(checked);\n}\n\n\nvoid\nMainWindow::on_actionClear_triggered()\n{\n  dt.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  std::vector<Point_2> points;\n  points.reserve(number_of_points);\n  for(int i = 0; i < number_of_points; ++i){\n    points.push_back(*pg++);\n  }\n  dt.insert(points.begin(), points.end());\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionLoadPoints_triggered()\n{\n  QString fileName = QFileDialog::getOpenFileName(this,\n                                                  tr(\"Open Points file\"),\n                                                  \".\",\n                                                  tr(\"CGAL files (*.pts.cgal);;\"\n                                                   #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                                                     \"WKT files (*.WKT *.wkt);;\"\n                                                   #endif\n                                                     \"All files (*)\"));\n  if(! fileName.isEmpty()){\n    open(fileName);\n  }\n}\n\n\nvoid\nMainWindow::open(QString fileName)\n{\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::ifstream ifs(qPrintable(fileName));\n\n  K::Point_2 p;\n  std::vector<K::Point_2> points;\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    while(ifs >> p) {\n      // ignore whatever comes after x and y\n      ifs.ignore((std::numeric_limits<std::streamsize>::max)(), '\\n');\n      points.push_back(p);\n    }\n  dt.insert(points.begin(), points.end());\n\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  this->addToRecentFiles(fileName);\n  actionRecenter->trigger();\n  Q_EMIT( changed());\n\n}\n\nvoid\nMainWindow::on_actionSavePoints_triggered()\n{\n  QString fileName = QFileDialog::getSaveFileName(this,\n                                                  tr(\"Save points\"),\n                                                  \".\",\n                                                  tr(\"CGAL files (*.pts.cgal);;\"\n                                                   #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                                                     \"WKT files (*.WKT *.wkt);;\"\n                                                   #endif\n                                                     \"All files (*)\"));\n  if(! fileName.isEmpty()){\n    std::ofstream ofs(qPrintable(fileName));\n    if(fileName.endsWith(\".wkt\", Qt::CaseInsensitive))\n    {\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n      std::vector<K::Point_2> points;\n      points.reserve(dt.number_of_vertices());\n      for(Delaunay::Finite_vertices_iterator\n          vit = dt.finite_vertices_begin(),\n          end = dt.finite_vertices_end();\n          vit!= end; ++vit)\n      {\n        points.push_back(vit->point());\n      }\n      CGAL::IO::write_multi_point_WKT(ofs, points);\n#endif\n    }\n    else\n      for(Delaunay::Finite_vertices_iterator\n          vit = dt.finite_vertices_begin(),\n          end = dt.finite_vertices_end();\n          vit!= end; ++vit)\n      {\n        ofs << vit->point() << std::endl;\n      }\n  }\n}\n\n\nvoid\nMainWindow::on_actionRecenter_triggered()\n{\n  this->graphicsView->setSceneRect(dgi->boundingRect());\n  this->graphicsView->fitInView(dgi->boundingRect(), Qt::KeepAspectRatio);\n}\n\n\n#include \"Delaunay_triangulation_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(\"Delaunay_triangulation_2 demo\");\n\n  // Import resources from libCGAL (QT5).\n  CGAL_QT_INIT_RESOURCES;\n\n  MainWindow mainWindow;\n  mainWindow.show();\n\n  QStringList args = app.arguments();\n  args.removeAt(0);\n  Q_FOREACH(QString filename, args) {\n    mainWindow.open(filename);\n  }\n\n  return app.exec();\n}\n", "meta": {"hexsha": "1bed7aeef2cb5f46938bd0115557a2324a796c5e", "size": 11728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphicsView/demo/Triangulation_2/Delaunay_triangulation_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/Triangulation_2/Delaunay_triangulation_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/Triangulation_2/Delaunay_triangulation_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.715261959, "max_line_length": 126, "alphanum_fraction": 0.6500682128, "num_tokens": 2905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5546424065982797}}
{"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": "// Author(s): Wieger Wesselink\n// Copyright: see the accompanying file COPYING or copy at\n// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file monotonicity_test.cpp\n/// \\brief Tests for the is_monotonous function for pbes expressions.\n\n#include <iostream>\n#include <string>\n\n#include <boost/test/included/unit_test_framework.hpp>\n\n#include \"mcrl2/pbes/is_monotonous.h\"\n#include \"mcrl2/pbes/parse.h\"\n#include \"mcrl2/pbes/txt2pbes.h\"\n\nusing namespace mcrl2;\nusing namespace mcrl2::pbes_system;\n\nvoid run_monotonicity_test_case(const pbes_expression& x, bool expected_result)\n{\n  bool result = is_monotonous(x);\n  if (result != expected_result)\n  {\n    std::cerr << \"--- Failing monotonicity test case ---\\n\";\n    std::cerr << \" x = \" << pbes_system::pp(x) << std::endl;\n    std::cerr << \" expected_result = \" << std::boolalpha << expected_result << std::endl;\n  }\n  BOOST_CHECK(result == expected_result);\n}\n\nBOOST_AUTO_TEST_CASE(test_monotonicity)\n{\n  std::string text =\n    \"pbes                                                 \\n\"\n    \" nu X0(m, n: Nat) = val(n == m) && X0(m + 1, n + 1); \\n\"\n    \" nu X1            = !X1;                             \\n\"\n    \" nu X2            = !!X2;                            \\n\"\n    \" nu X3            = !X2 => X1;                       \\n\"\n    \" nu X4            = !(forall n:Nat . (X2 => !X1));   \\n\"\n    \" nu X5            = !(forall n:Nat . (X2 || !X1));   \\n\"\n    \"                                                     \\n\"\n    \" init X0(0, 0);                                      \\n\"\n    ;\n  bool normalize = false;\n  pbes p = txt2pbes(text, normalize);\n  std::vector<pbes_equation> eqn = p.equations();\n\n  std::vector<bool> expected_results(eqn.size(), true);\n  expected_results[0] = true;\n  expected_results[1] = false;\n  expected_results[2] = true;\n  expected_results[3] = true;\n  expected_results[4] = true;\n  expected_results[5] = false;\n\n  for (std::size_t i = 0; i < eqn.size(); ++i)\n  {\n    run_monotonicity_test_case(eqn[i].formula(), expected_results[i]);\n  }\n}\n\nboost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[])\n{\n  return nullptr;\n}\n", "meta": {"hexsha": "e157e5c94810028df415b85a4b851686fbcdfff8", "size": 2292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/pbes/test/monotonicity_test.cpp", "max_stars_repo_name": "gijskant/mcrl2-pmc", "max_stars_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/pbes/test/monotonicity_test.cpp", "max_issues_repo_name": "gijskant/mcrl2-pmc", "max_issues_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/pbes/test/monotonicity_test.cpp", "max_forks_repo_name": "gijskant/mcrl2-pmc", "max_forks_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2816901408, "max_line_length": 89, "alphanum_fraction": 0.5763525305, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5545929129603742}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/illcond.hpp\n *\n * \\brief Check if a matrix is ill-conditioned.\n *\n * Copyright (c) 2012, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_ILLCOND_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_ILLCOND_HPP\n\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublasx/operation/rcond.hpp>\n#include <cmath>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\nbool illcond(matrix_expression<MatrixExprT> const& A)\n{\n\tdouble r = rcond(A);\n\tvolatile double rp1 = r + 1.0;\n\n\treturn (rp1 == 1.0) || ::std::isnan(r);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_ILLCOND_HPP\n", "meta": {"hexsha": "c456066c490b6e0e512f77adb65403a823ef4ec1", "size": 987, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/illcond.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/illcond.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/illcond.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": 23.5, "max_line_length": 66, "alphanum_fraction": 0.7467071935, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5545928997835989}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nnamespace la3dm {\n  class FeatureArray {\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    \n    FeatureArray(int num_channel, bool need_normalizing=false):\n      dimension (num_channel),\n      need_normalizing(need_normalizing){\n      \n      feature.resize(num_channel);\n      feature.setZero();\n      for (int i = 0; i < num_channel; i++)\n        feature(i) = 1.0 / num_channel;\n      if (need_normalizing == false)\n        feature = (feature * 255.0).eval();\n      //feature.colwise() += 1.0 / num_channel ;\n      counter = 1;\n\n    };\n\n    FeatureArray(const FeatureArray & other):\n      dimension(other.dimension),\n      counter(other.counter),\n      need_normalizing(other.need_normalizing)\n    {\n      feature  = other.feature;\n      \n    }\n\n    FeatureArray &operator=(const FeatureArray &other) {\n      dimension = other.dimension;\n      counter = other.counter;\n      need_normalizing = other.need_normalizing;\n      feature = other.feature;\n      return *this;\n    }\n\n    \n    int add_observation_by_averaging(const Eigen::VectorXf & f) {\n      if (f.size() == feature.size()){\n        Eigen::VectorXf to_add = f;\n        if (need_normalizing && f.sum() != 0)\n          to_add = (to_add / f.sum()).eval();\n        feature = ((feature * counter + f)/(counter+1)).eval();\n        counter++;\n        if (need_normalizing && feature.sum() != 0)\n          feature = (feature / feature.sum()).eval();\n        return 0;\n      } else {\n        return -1;\n      }\n      \n    }\n\n    int get_counter() const {return counter;}\n\n    int overwrite_feature(const Eigen::VectorXf & f) {\n      if (f.size() != feature.size())\n        return -1;\n\n      feature = f;\n      if (need_normalizing && feature.sum()!= 0 )\n        feature = (feature / feature.sum()) .eval();\n      return 0;\n    }\n\n    int dimension;\n    Eigen::VectorXf get_feature()  const {return feature;}\n    \n  private:\n    Eigen::VectorXf feature;\n    int counter;\n    bool need_normalizing;\n  };\n  \n}\n", "meta": {"hexsha": "5740bae4176556f914c672b2792d91bfbc40fd7b", "size": 2005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bgkoctomap/FeatureArray.hpp", "max_stars_repo_name": "zeroAska/BGKOctoMap-CRF", "max_stars_repo_head_hexsha": "b093b667eadc6c941e5576c714ed91d14ce52a56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-08T10:37:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T10:37:48.000Z", "max_issues_repo_path": "include/bgkoctomap/FeatureArray.hpp", "max_issues_repo_name": "zeroAska/BGKOctoMap-CRF", "max_issues_repo_head_hexsha": "b093b667eadc6c941e5576c714ed91d14ce52a56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/bgkoctomap/FeatureArray.hpp", "max_forks_repo_name": "zeroAska/BGKOctoMap-CRF", "max_forks_repo_head_hexsha": "b093b667eadc6c941e5576c714ed91d14ce52a56", "max_forks_repo_licenses": ["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.0625, "max_line_length": 65, "alphanum_fraction": 0.5840399002, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5545928962118641}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#include <boost/simd/constant/ratio.hpp>\n#include <scalar_test.hpp>\n\nSTF_CASE_TPL( \"Check constant behavior for ratio\", STF_NUMERIC_TYPES)\n{\n  using boost::simd::Ratio;\n\n  STF_EXPR_IS   ( (Ratio<T,7,21>()  ) , T         );\n  STF_IEEE_EQUAL( (Ratio<T,7,21>()  ) , T(7./21.) );\n\n  STF_EXPR_IS   ( (Ratio<T,7>()  ) , T    );\n  STF_IEEE_EQUAL( (Ratio<T,7>()  ) , T(7) );\n}\n", "meta": {"hexsha": "73e14d56b24a9e2e88aca4b531a19197d6aa5a9b", "size": 752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/constant/scalar/ratio.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/constant/scalar/ratio.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/constant/scalar/ratio.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": 32.6956521739, "max_line_length": 100, "alphanum_fraction": 0.4707446809, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5545928896234765}}
{"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#include <numeric>\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 <mpi2/mpi2.h>\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 = 5000000;\n\tmf_size_type rank = 10;\n\n\t// parameters for distribution\n\tint tasksPerRank = 2;\n\tmf_size_type blocks = world.size() * tasksPerRank;\n\n\t// parameters for Lee01\n\tunsigned epochs = 20;\n\n\t// initialize mf library and mpi2\n\tmfStart();\n\n\tif (world.rank() == 0) {\n#ifndef NDEBUG\n\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n#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, rank);\n\t\tDenseMatrixCM hIn(rank, size2);\n\t\tgenerateRandom(wIn, random,  boost::uniform_real<>(0, 1));\n\t\tgenerateRandom(hIn, random, boost::uniform_real<>(0, 1));\n\t\t// div2(wIn, sums2(wIn));\n\t\t// div1(hIn, sums1(hIn));\n\n\t\t// generate a sparse matrix by selecting random entries from the generated factors\n\t\t// and sample from a Poisson with mean equal to the entry\n\t\t// TODO: this generation process does not match the factorization model since we sample\n\t\t//       from the Poisson only at some entries of wh\n\t\tSparseMatrix v;\n\t\tgenerateRandom(v, nnz, wIn, hIn, random);\n\t\tapplyPoisson(v, random);\n\t\tSparseMatrixCM vc;\n\t\tcopyCm(v, vc);\n\t\tLOG4CXX_INFO(logger, \"Data matrix: \"\n\t\t\t<< v.size1() << \" x \" << v.size2() << \", \" << v.nnz() << \" nonzeros\");\n\t\tLOG4CXX_INFO(logger, \"Loss with original factors: \" << gkl(v, wIn, hIn));\n\n\t\t// generate initial factors by sampling from a uniform[0,1] distribution\n\t\tDenseMatrix w(size1, rank);\n\t\tDenseMatrixCM h(rank, size2);\n\t\tgenerateRandom(w, random, boost::uniform_real<>(0, 1));\n\t\tgenerateRandom(h, random, boost::uniform_real<>(0, 1));\n\t\tdiv2(w, sums2(w));\n\t\tdiv1(h, sums1(h));\n\t\tdouble scaleFactor = sqrt(sum(v));\n\t\tmult(w, scaleFactor);\n\t\tmult(h, scaleFactor);\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\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// perform the factorization\n\t\tDapFactorizationData<> data(dv, dw, dh, tasksPerRank, &dvc);\n\t\tTrace trace;\n\t\tdlee01Gkl(data, epochs, trace);\n\n\t\t// write the trace\n\t\tLOG4CXX_INFO(logger, \"Writing trace to \" << \"/tmp/dlee01-gkl-trace.R\");\n\t\ttrace.toRfile(\"/tmp/dlee01-gkl-trace.R\", \"dlee01.gkl\");\n\t}\n\n\tmfStop();\n\tmfFinalize();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "bc5294e44ca164e9566bc41a906778b08a70a4f1", "size": 4207, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/mf/dlee01-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/dlee01-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/dlee01-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": 34.7685950413, "max_line_length": 106, "alphanum_fraction": 0.7004991681, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.554582847704182}}
{"text": "\n/** \\file oatest.cpp\n\nC++ program: oatest\n\noatest: tool for testing new algorithms\n\nAuthor: Pieter Eendebak <pieter.eendebak@gmail.com>, (C) 2014\n\nCopyright: See LICENSE.txt file that comes with this distribution\n*/\n\n#include <algorithm>\n#include <iostream>\n#include <map>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"anyoption.h\"\n#include \"arrayproperties.h\"\n#include \"arraytools.h\"\n#include \"extend.h\"\n#include \"graphtools.h\"\n#include \"unittests.h\"\n#include \"tools.h\"\n\n#include \"evenodd.h\"\n#include \"lmc.h\"\n\n#include \"conference.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\n#include \"Deff.h\"\n#include \"arraytools.h\"\n#include \"strength.h\"\n\n#ifdef HAVE_BOOST\n#include <boost/filesystem.hpp>\n#include <string>\n#endif\n\nusing namespace Eigen;\n\n\n#include \"graphtools.h\"\n\n\n/// show information about Pareto criteria for conference matrix\nvoid paretoInfo (const array_link &alx) {\n        std::vector< int > j5 = alx.Jcharacteristics (5);\n        int j5max = vectormax (j5, 0);\n\n        int v1 = (j5max == alx.n_rows);\n        int v2 = 1 - v1;\n\n        int N = alx.n_rows;\n        int rank = array2xf (alx).rank ();\n        std::vector< int > F4 = alx.Fvalues (4);\n        std::vector< double > gwlp = alx.GWLP ();\n        printf (\"pareto data: %d ; \", rank);\n        printf (\" %d \", (int)(N * N * gwlp[4]));\n        printf (\" ; \");\n        display_vector (F4);\n        printf (\" ; \");\n        printf (\" %d ; %d\", v1, v2);\n        printf (\"\\n\");\n}\n\n/// check whether an array is contained in a Pareto set\nint arrayInPareto (const Pareto< mvalue_t< long >, array_link > &pset, const array_link &al, int verbose = 1) {\n\n        std::vector< array_link > llx = pset.allindices ();\n        arraylist_t ll (llx.begin (), llx.end ());\n        int jx = arrayInList (al, ll, 0);\n        if (verbose)\n                myprintf (\"arrayInPareto: index in pareto list %d\\n\", jx);\n        return jx;\n}\n\n\nint main(int argc, char* argv[]) {\n    AnyOption opt;\n    /* parse command line options */\n    opt.setFlag(\"help\", 'h'); /* a flag (takes no argument), supporting long and short form */\n    opt.setOption(\"output\", 'o');\n    opt.setOption(\"input\", 'I');\n    opt.setOption(\"rand\", 'r');\n    opt.setOption(\"verbose\", 'v');\n    opt.setOption(\"ii\", 'i');\n    opt.setOption(\"jj\");\n    opt.setOption(\"xx\", 'x');\n    opt.setOption(\"dverbose\", 'd');\n    opt.setOption(\"rows\");\n    opt.setOption(\"cols\");\n    opt.setOption(\"nrestarts\");\n    opt.setOption(\"niter\");\n    opt.setOption(\"mdebug\", 'm');\n    opt.setOption(\"oaconfig\", 'c'); /* file that specifies the design */\n\n    opt.addUsage(\"Orthonal Array: oatest: testing platform\");\n    opt.addUsage(\"Usage: oatest [OPTIONS] [FILE]\");\n    opt.addUsage(\"\");\n    opt.addUsage(\" -h --help  \t\t\tPrints this help \");\n    opt.processCommandArgs(argc, argv);\n\n    double t0 = get_time_ms(), dt = 0;\n    int randvalseed = opt.getIntValue('r', 1);\n    int ix = opt.getIntValue('i', 1);\n    int r = opt.getIntValue('r', 1);\n    int jj = opt.getIntValue(\"jj\", 5);\n\n    int xx = opt.getIntValue('x', 0);\n    int niter = opt.getIntValue(\"niter\", 10);\n    int verbose = opt.getIntValue(\"verbose\", 1);\n\n    const char* input = opt.getValue('I');\n    if (input == 0)\n        input = \"test.oa\";\n\n    array_link G(4, 4, 0);\n    G.at(0, 0) = 1;\n    G.at(1, 0) = 1;\n    G.at(1, 2) = 1;\n    G.at(1, 3) = 1;\n    G.at(2, 2) = 1;\n    G.at(3, 1) = 1;\n\n    if (xx) {\n    G.at(0, 1) = 1; G.at(2, 1) = G.at(3, 1) = G.at(1, 3) = 1; // symmetric\n}\n        G.showarraycompact();\n\n        std::vector<int> colors(4);\n\n        std::vector<int> perm = nauty::reduceNauty(G, colors, 4);\n        myprintf(\"perm: \");  print_perm(perm);\n        return 0;\n\n        printf(\"test! %ld\\n\", choose(6,4));\n        for (int i = 4; i < 12; i++)\n            printf(\"choose(%d, %d): %ld\\n\", i, i-2, choose(i, i - 2) - ncombs(i, i - 2));\n        fflush(0);\n\n        array_link A = exampleArray(56, 1);\n        ndarray<double> D = distance_distribution_mixed(A, 2);\n        D.show();\n\n        t0 = get_time_ms();\n        for(int x=0; x<100000; x++)\n            choose(15, 11);\n        dt = get_time_ms() - t0;\n        printf(\"dt: %f\\n\", dt);\n\n        t0 = get_time_ms();\n        for (int x = 0; x < 100000; x++)\n            ncombs(15, 11);\n        dt = get_time_ms() - t0;\n        printf(\"dt: %f\\n\", dt);\n        return 0;\n\n        srand (randvalseed);\n        if (randvalseed == -1) {\n                randvalseed = time (NULL);\n                printf (\"random seed %d\\n\", randvalseed);\n                srand (randvalseed);\n        }\n\n\n\n\t\tarray_link array = exampleArray(0);\n\t\tlmc_t lmc_type = LMCcheck(array);\n\n\n\t\tarray = array.randomperm();\n\t\tarray.showarray();\n\t\tarray_link reduced_array = reduceLMCform(array);\n\t\treduced_array.showarray();\n\t\texit(0);\n\n\t\ttry {\n\t\t\tarray_link al = exampleArray(r);\n\t\t\tal.show();\n\t\t\tal.showarray();\n\n\t\t\tstd::vector<int> sizes = array2modelmatrix_sizes(al);\n\t\t\tdisplay_vector(sizes); myprintf(\"\\n\");\n\t\t\tMatrixFloat modelmatrix = array2modelmatrix(al, \"i\", 1);\n\t\t\tarray_link modelmatrixx = modelmatrix;\n\t\t\tmodelmatrixx.show();\n\t\t\tmodelmatrixx.showarray();\n\n\t\t\tmodelmatrix = array2modelmatrix(al, \"main\", 1);\n\t\t\tmodelmatrixx = modelmatrix;\n\t\t\tmodelmatrixx.show();\n\t\t\tmodelmatrixx.showarray();\n\n\t\t\texit(0);\n\n\t\t}\n\t\tcatch (const std::exception &e) {\n\t\t\tstd::cerr << e.what() << std::endl;\n\t\t\tthrow;\n\t\t}\n\n        {\n                array_link al = exampleArray (r);\n\n                array_transformation_t tt = reduceOAnauty (al);\n                array_link alx = tt.apply (al);\n                exit (0);\n        }\n\n\n\n        return 0;\n}\n\n// kate: indent-mode cstyle; indent-width 5; replace-tabs on;\n", "meta": {"hexsha": "619e5b3976107168e7cafecf3919688ca5d6c797", "size": 5654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/oatest.cpp", "max_stars_repo_name": "ABohynDOE/oapackage", "max_stars_repo_head_hexsha": "d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2015-11-06T07:24:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:02:19.000Z", "max_issues_repo_path": "utils/oatest.cpp", "max_issues_repo_name": "ABohynDOE/oapackage", "max_issues_repo_head_hexsha": "d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2015-11-06T07:25:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T01:33:47.000Z", "max_forks_repo_path": "utils/oatest.cpp", "max_forks_repo_name": "ABohynDOE/oapackage", "max_forks_repo_head_hexsha": "d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-08-16T15:09:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T11:48:55.000Z", "avg_line_length": 25.3542600897, "max_line_length": 111, "alphanum_fraction": 0.5723381677, "num_tokens": 1694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059462938815, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5545828442846666}}
{"text": "/*\n *  (C) Copyright Nick Thompson 2018.\n *  Use, modification and distribution are subject to the\n *  Boost Software License, Version 1.0. (See accompanying file\n *  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n#include <cmath>\n#include <vector>\n#include <array>\n#include <forward_list>\n#include <algorithm>\n#include <random>\n#include <limits>\n#include <boost/core/lightweight_test.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/norms.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_complex.hpp>\n\nusing std::abs;\nusing std::pow;\nusing std::sqrt;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::multiprecision::cpp_complex_50;\nusing boost::math::tools::lp_norm;\nusing boost::math::tools::l1_norm;\nusing boost::math::tools::l2_norm;\nusing boost::math::tools::sup_norm;\nusing boost::math::tools::lp_distance;\nusing boost::math::tools::l1_distance;\nusing boost::math::tools::l2_distance;\nusing boost::math::tools::sup_distance;\nusing boost::math::tools::total_variation;\n\n/*\n * Test checklist:\n * 1) Does it work with multiprecision?\n * 2) Does it work with .cbegin()/.cend() if the data is not altered?\n * 3) Does it work with ublas and std::array? (Checking Eigen and Armadillo will make the CI system really unhappy.)\n * 4) Does it work with std::forward_list if a forward iterator is all that is required?\n * 5) Does it work with complex data if complex data is sensible?\n */\n\n// To stress test, set global_seed = 0, global_size = huge.\nstatic const constexpr size_t global_seed = 834;\nstatic const constexpr size_t global_size = 64;\n\ntemplate<class T>\nstd::vector<T> generate_random_vector(size_t size, size_t seed)\n{\n    if (seed == 0)\n    {\n        std::random_device rd;\n        seed = rd();\n    }\n    std::vector<T> v(size);\n\n    std::mt19937 gen(seed);\n\n    if constexpr (std::is_floating_point<T>::value)\n    {\n        std::normal_distribution<T> dis(0, 1);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = dis(gen);\n        }\n        return v;\n    }\n    else if constexpr (std::is_integral<T>::value)\n    {\n        // Rescaling by larger than 2 is UB!\n        std::uniform_int_distribution<T> dis(std::numeric_limits<T>::lowest()/2, std::numeric_limits<T>::max()/2);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = dis(gen);\n        }\n        return v;\n    }\n    else if constexpr (boost::is_complex<T>::value)\n    {\n        std::normal_distribution<typename T::value_type> dis(0, 1);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = {dis(gen), dis(gen)};\n        }\n        return v;\n    }\n    else if constexpr (boost::multiprecision::number_category<T>::value == boost::multiprecision::number_kind_complex)\n    {\n        std::normal_distribution<long double> dis(0, 1);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = {dis(gen), dis(gen)};\n        }\n        return v;\n    }\n    else if constexpr (boost::multiprecision::number_category<T>::value == boost::multiprecision::number_kind_floating_point)\n    {\n        std::normal_distribution<long double> dis(0, 1);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = dis(gen);\n        }\n        return v;\n    }\n    else\n    {\n        BOOST_ASSERT_MSG(false, \"Could not identify type for random vector generation.\");\n        return v;\n    }\n}\n\n\ntemplate<class Real>\nvoid test_lp()\n{\n    Real tol = 50*std::numeric_limits<Real>::epsilon();\n\n    std::array<Real, 3> u{1,0,0};\n    Real l3 = lp_norm(u.begin(), u.end(), 3);\n    BOOST_TEST(abs(l3 - 1) < tol);\n\n    u[0] = -8;\n    l3 = lp_norm(u.cbegin(), u.cend(), 3);\n    BOOST_TEST(abs(l3 - 8) < tol);\n\n    std::vector<Real> v(500);\n    for (size_t i = 0; i < v.size(); ++i) {\n        v[i] = 7;\n    }\n    Real l8 = lp_norm(v, 8);\n    Real expected = 7*pow(v.size(), static_cast<Real>(1)/static_cast<Real>(8));\n    BOOST_TEST(abs(l8 - expected) < tol*abs(expected));\n\n    // Does it work with ublas vectors?\n    // Does it handle the overflow of intermediates?\n    boost::numeric::ublas::vector<Real> w(4);\n    Real bignum = sqrt(std::numeric_limits<Real>::max())/256;\n    for (size_t i = 0; i < w.size(); ++i)\n    {\n        w[i] = bignum;\n    }\n    Real l20 = lp_norm(w.cbegin(), w.cend(), 4);\n    expected = bignum*pow(w.size(), static_cast<Real>(1)/static_cast<Real>(4));\n    BOOST_TEST(abs(l20 - expected) < tol*expected);\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    Real scale = 8;\n    Real l7 = scale*lp_norm(v, 7);\n    for (auto & x : v)\n    {\n        x *= -scale;\n    }\n    Real l7_ = lp_norm(v, 7);\n    BOOST_TEST(abs(l7_ - l7) < tol*l7);\n}\n\n\ntemplate<class Complex>\nvoid test_complex_lp()\n{\n    typedef typename Complex::value_type Real;\n    Real tol = 50*std::numeric_limits<Real>::epsilon();\n    std::vector<Complex> v{{1,0}, {0,0}, {0,0}};\n    Real l3 = lp_norm(v.cbegin(), v.cend(), 3);\n    BOOST_TEST(abs(l3 - 1) < tol);\n\n    l3 = lp_norm(v, 3);\n    BOOST_TEST(abs(l3 - 1) < tol);\n\n    v = generate_random_vector<Complex>(global_size, global_seed);\n    Real scale = 8;\n    Real l7 = scale*lp_norm(v, 7);\n    for (auto & x : v)\n    {\n        x *= -scale;\n    }\n    Real l7_ = lp_norm(v, 7);\n    BOOST_TEST(abs(l7_ - l7) < tol*l7);\n}\n\ntemplate<class Z>\nvoid test_integer_lp()\n{\n    double tol = 100*std::numeric_limits<double>::epsilon();\n\n    std::array<Z, 3> u{1,0,0};\n    double l3 = lp_norm(u.begin(), u.end(), 3);\n    BOOST_TEST(abs(l3 - 1) < tol);\n\n    auto v = generate_random_vector<Z>(global_size, global_seed);\n    Z scale = 2;\n    double l7 = scale*lp_norm(v, 7);\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    double l7_ = lp_norm(v, 7);\n    BOOST_TEST(abs(l7_ - l7) < tol*l7);\n}\n\ntemplate<class Real>\nvoid test_lp_distance()\n{\n    Real tol = 100*std::numeric_limits<Real>::epsilon();\n\n    std::vector<Real> u{1,0,0};\n    std::vector<Real> v{0,0,0};\n\n    Real dist = lp_distance(u,u, 3);\n    BOOST_TEST(abs(dist) < tol);\n\n    dist = lp_distance(u,v, 3);\n    BOOST_TEST(abs(dist - 1) < tol);\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    u = generate_random_vector<Real>(global_size, global_seed+1);\n    Real dist1 = lp_distance(u, v, 7);\n    Real dist2 = lp_distance(v, u, 7);\n\n    BOOST_TEST(abs(dist1 - dist2) < tol*dist1);\n}\n\ntemplate<class Complex>\nvoid test_complex_lp_distance()\n{\n    using Real = typename Complex::value_type;\n    Real tol = 100*std::numeric_limits<Real>::epsilon();\n\n    std::vector<Complex> u{{1,0},{0,0},{0,0}};\n    std::vector<Complex> v{{0,0},{0,0},{0,0}};\n\n    Real dist = boost::math::tools::lp_distance(u,u, 3);\n    BOOST_TEST(abs(dist) < tol);\n\n    dist = boost::math::tools::lp_distance(u,v, 3);\n    BOOST_TEST(abs(dist - 1) < tol);\n\n    v = generate_random_vector<Complex>(global_size, global_seed);\n    u = generate_random_vector<Complex>(global_size, global_seed + 1);\n    Real dist1 = lp_distance(u, v, 7);\n    Real dist2 = lp_distance(v, u, 7);\n\n    BOOST_TEST(abs(dist1 - dist2) < tol*dist1);\n}\n\ntemplate<class Z>\nvoid test_integer_lp_distance()\n{\n    double tol = 100*std::numeric_limits<double>::epsilon();\n\n    std::array<Z, 3> u{1,0,0};\n    std::array<Z, 3> w{0,0,0};\n    double l3 = lp_distance(u, w, 3);\n    BOOST_TEST(abs(l3 - 1) < tol);\n\n    auto v = generate_random_vector<Z>(global_size, global_seed);\n    Z scale = 2;\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    auto s = generate_random_vector<Z>(global_size, global_seed + 1);\n    double dist1 = lp_distance(v, s, 7);\n    double dist2 = lp_distance(s, v, 7);\n    BOOST_TEST(abs(dist1 - dist2) < tol*dist2);\n}\n\n\ntemplate<class Z>\nvoid test_integer_total_variation()\n{\n    double eps = std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{1,1};\n    double tv = boost::math::tools::total_variation(v);\n    BOOST_TEST_EQ(tv, 0);\n\n    v[1] = 2;\n    tv = boost::math::tools::total_variation(v.begin(), v.end());\n    BOOST_TEST_EQ(tv, 1);\n\n    v.resize(16);\n    for (size_t i = 0; i < v.size(); ++i) {\n        v[i] = i;\n    }\n\n    tv = boost::math::tools::total_variation(v);\n    BOOST_TEST_EQ(tv, v.size() -1);\n\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = i*i;\n    }\n\n    tv = boost::math::tools::total_variation(v);\n    BOOST_TEST_EQ(tv, (v.size() - 1)*(v.size() - 1));\n\n    // Work with std::array?\n    std::array<Z, 2> w{1,1};\n    tv = boost::math::tools::total_variation(w);\n    BOOST_TEST_EQ(tv,0);\n\n    std::array<Z, 4> u{1, 2, 1, 2};\n    tv = boost::math::tools::total_variation(u);\n    BOOST_TEST_EQ(tv, 3);\n\n    v = generate_random_vector<Z>(global_size, global_seed);\n    double tv1 = 2*total_variation(v);\n    Z scale = 2;\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    double tv2 = total_variation(v);\n    BOOST_TEST(abs(tv1 - tv2) < tv1*eps);\n}\n\ntemplate<class Real>\nvoid test_total_variation()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,1};\n    Real tv = total_variation(v.begin(), v.end());\n    BOOST_TEST(tv >= 0 && abs(tv) < tol);\n\n    tv = total_variation(v);\n    BOOST_TEST(tv >= 0 && abs(tv) < tol);\n\n    v[1] = 2;\n    tv = total_variation(v.begin(), v.end());\n    BOOST_TEST(abs(tv - 1) < tol);\n\n    v.resize(50);\n    for (size_t i = 0; i < v.size(); ++i) {\n        v[i] = i;\n    }\n\n    tv = total_variation(v.begin(), v.end());\n    BOOST_TEST(abs(tv - (v.size() -1)) < tol);\n\n    for (size_t i = 0; i < v.size(); ++i) {\n        v[i] = i*i;\n    }\n\n    tv = total_variation(v.begin(), v.end());\n    BOOST_TEST(abs(tv - (v.size() - 1)*(v.size() - 1)) < tol);\n\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    Real scale = 8;\n    Real tv1 = scale*total_variation(v);\n    for (auto & x : v)\n    {\n        x *= -scale;\n    }\n    Real tv2 = total_variation(v);\n    BOOST_TEST(abs(tv1 - tv2) < tol*tv1);\n}\n\ntemplate<class Real>\nvoid test_sup_norm()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{-2,1,0};\n    Real s = boost::math::tools::sup_norm(v.begin(), v.end());\n    BOOST_TEST(abs(s - 2) < tol);\n\n    s = boost::math::tools::sup_norm(v);\n    BOOST_TEST(abs(s - 2) < tol);\n\n    // Work with std::array?\n    std::array<Real, 3> w{-2,1,0};\n    s = boost::math::tools::sup_norm(w);\n    BOOST_TEST(abs(s - 2) < tol);\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    Real scale = 8;\n    Real sup1 = scale*sup_norm(v);\n    for (auto & x : v)\n    {\n        x *= -scale;\n    }\n    Real sup2 = sup_norm(v);\n    BOOST_TEST(abs(sup1 - sup2) < tol*sup1);\n}\n\ntemplate<class Z>\nvoid test_integer_sup_norm()\n{\n    double eps = std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{2,1,0};\n    Z s = sup_norm(v.begin(), v.end());\n    BOOST_TEST_EQ(s, 2);\n\n    s = sup_norm(v);\n    BOOST_TEST_EQ(s,2);\n\n    v = generate_random_vector<Z>(global_size, global_seed);\n    double sup1 = 2*sup_norm(v);\n    Z scale = 2;\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    double sup2 = sup_norm(v);\n    BOOST_TEST(abs(sup1 - sup2) < sup1*eps);\n}\n\ntemplate<class Complex>\nvoid test_complex_sup_norm()\n{\n    typedef typename Complex::value_type Real;\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Complex> w{{0,-8}, {1,1}, {3,2}};\n    Real s = sup_norm(w.cbegin(), w.cend());\n    BOOST_TEST(abs(s-8) < tol);\n\n    s = sup_norm(w);\n    BOOST_TEST(abs(s-8) < tol);\n\n    auto v = generate_random_vector<Complex>(global_size, global_seed);\n    Real scale = 8;\n    Real sup1 = scale*sup_norm(v);\n    for (auto & x : v)\n    {\n        x *= -scale;\n    }\n    Real sup2 = sup_norm(v);\n    BOOST_TEST(abs(sup1 - sup2) < tol*sup1);\n}\n\ntemplate<class Real>\nvoid test_l0_pseudo_norm()\n{\n    std::vector<Real> v{0,0,1};\n    size_t count = boost::math::tools::l0_pseudo_norm(v.begin(), v.end());\n    BOOST_TEST_EQ(count, 1);\n\n    // Compiles with cbegin()/cend()?\n    count = boost::math::tools::l0_pseudo_norm(v.cbegin(), v.cend());\n    BOOST_TEST_EQ(count, 1);\n\n    count = boost::math::tools::l0_pseudo_norm(v);\n    BOOST_TEST_EQ(count, 1);\n\n    std::array<Real, 3> w{0,0,1};\n    count = boost::math::tools::l0_pseudo_norm(w);\n    BOOST_TEST_EQ(count, 1);\n}\n\ntemplate<class Complex>\nvoid test_complex_l0_pseudo_norm()\n{\n    std::vector<Complex> v{{0,0}, {0,0}, {1,0}};\n    size_t count = boost::math::tools::l0_pseudo_norm(v.begin(), v.end());\n    BOOST_TEST_EQ(count, 1);\n\n    count = boost::math::tools::l0_pseudo_norm(v);\n    BOOST_TEST_EQ(count, 1);\n}\n\ntemplate<class Z>\nvoid test_hamming_distance()\n{\n    std::vector<Z> v{1,2,3};\n    std::vector<Z> w{1,2,4};\n    size_t count = boost::math::tools::hamming_distance(v, w);\n    BOOST_TEST_EQ(count, 1);\n\n    count = boost::math::tools::hamming_distance(v, v);\n    BOOST_TEST_EQ(count, 0);\n}\n\ntemplate<class Real>\nvoid test_l1_norm()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,1,1};\n    Real l1 = l1_norm(v.begin(), v.end());\n    BOOST_TEST(abs(l1 - 3) < tol);\n\n    l1 = l1_norm(v);\n    BOOST_TEST(abs(l1 - 3) < tol);\n\n    std::array<Real, 3> w{1,1,1};\n    l1 = l1_norm(w);\n    BOOST_TEST(abs(l1 - 3) < tol);\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    Real scale = 8;\n    Real l1_1 = scale*l1_norm(v);\n    for (auto & x : v)\n    {\n        x *= -scale;\n    }\n    Real l1_2 = l1_norm(v);\n    BOOST_TEST(abs(l1_1 - l1_2) < tol*l1_1);\n}\n\ntemplate<class Z>\nvoid test_integer_l1_norm()\n{\n    double eps = std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{1,1,1};\n    Z l1 = boost::math::tools::l1_norm(v.begin(), v.end());\n    BOOST_TEST_EQ(l1, 3);\n\n    v = generate_random_vector<Z>(global_size, global_seed);\n    double l1_1 = 2*l1_norm(v);\n    Z scale = 2;\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    double l1_2 = l1_norm(v);\n    BOOST_TEST(l1_1 > 0);\n    BOOST_TEST(l1_2 > 0);\n    if (abs(l1_1 - l1_2) > 2*l1_1*eps)\n    {\n        std::cout << std::setprecision(std::numeric_limits<double>::digits10);\n        std::cout << \"L1_1 = \" << l1_1 << \"\\n\";\n        std::cout << \"L1_2 = \" << l1_2 << \"\\n\";\n        BOOST_TEST(abs(l1_1 - l1_2) < 2*l1_1*eps);\n    }\n}\n\ntemplate<class Complex>\nvoid test_complex_l1_norm()\n{\n    typedef typename Complex::value_type Real;\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Complex> v{{1,0}, {0,1},{0,-1}};\n    Real l1 = l1_norm(v.begin(), v.end());\n    BOOST_TEST(abs(l1 - 3) < tol);\n\n    l1 = l1_norm(v);\n    BOOST_TEST(abs(l1 - 3) < tol);\n\n    v = generate_random_vector<Complex>(global_size, global_seed);\n    Real scale = 8;\n    Real l1_1 = scale*l1_norm(v);\n    for (auto & x : v)\n    {\n        x *= -scale;\n    }\n    Real l1_2 = l1_norm(v);\n    BOOST_TEST(abs(l1_1 - l1_2) < tol*l1_1);\n}\n\ntemplate<class Real>\nvoid test_l1_distance()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,2,3};\n    std::vector<Real> w{1,1,1};\n    Real l1 = boost::math::tools::l1_distance(v, v);\n    BOOST_TEST(abs(l1) < tol);\n\n    l1 = boost::math::tools::l1_distance(w, v);\n    BOOST_TEST(abs(l1 - 3) < tol);\n\n    l1 = boost::math::tools::l1_distance(v, w);\n    BOOST_TEST(abs(l1 - 3) < tol);\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    w = generate_random_vector<Real>(global_size, global_seed+1);\n    Real dist1 = l1_distance(v, w);\n    Real dist2 = l1_distance(w, v);\n    BOOST_TEST(abs(dist1 - dist2) < tol*dist1);\n}\n\ntemplate<class Z>\nvoid test_integer_l1_distance()\n{\n    double tol = std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{1,2,3};\n    std::vector<Z> w{1,1,1};\n    double l1 = boost::math::tools::l1_distance(v, v);\n    BOOST_TEST(abs(l1) < tol);\n\n    l1 = boost::math::tools::l1_distance(w, v);\n    BOOST_TEST(abs(l1 - 3) < tol);\n\n    l1 = boost::math::tools::l1_distance(v, w);\n    BOOST_TEST(abs(l1 - 3) < tol);\n\n    v = generate_random_vector<Z>(global_size, global_seed);\n    w = generate_random_vector<Z>(global_size, global_seed + 1);\n    double dist1 = l1_distance(v, w);\n    double dist2 = l1_distance(w, v);\n    BOOST_TEST(abs(dist1 - dist2) < tol*dist1);\n}\n\ntemplate<class Complex>\nvoid test_complex_l1_distance()\n{\n    typedef typename Complex::value_type Real;\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Complex> v{{1,0}, {0,1},{0,-1}};\n    Real l1 = boost::math::tools::l1_distance(v, v);\n    BOOST_TEST(abs(l1) < tol);\n\n    std::vector<Complex> w{{2,0}, {0,1},{0,-1}};\n    l1 = boost::math::tools::l1_distance(v.cbegin(), v.cend(), w.cbegin());\n    BOOST_TEST(abs(l1 - 1) < tol);\n\n    v = generate_random_vector<Complex>(global_size, global_seed);\n    w = generate_random_vector<Complex>(global_size, global_seed + 1);\n    Real dist1 = l1_distance(v, w);\n    Real dist2 = l1_distance(w, v);\n    BOOST_TEST(abs(dist1 - dist2) < tol*dist1);\n}\n\n\ntemplate<class Real>\nvoid test_l2_norm()\n{\n    using std::sqrt;\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,1,1,1};\n    Real l2 = boost::math::tools::l2_norm(v.begin(), v.end());\n    BOOST_TEST(abs(l2 - 2) < tol);\n\n    l2 = boost::math::tools::l2_norm(v);\n    BOOST_TEST(abs(l2 - 2) < tol);\n\n    std::array<Real, 4> w{1,1,1,1};\n    l2 = boost::math::tools::l2_norm(w);\n    BOOST_TEST(abs(l2 - 2) < tol);\n\n    Real bignum = 4*sqrt(std::numeric_limits<Real>::max());\n    v[0] = bignum;\n    v[1] = 0;\n    v[2] = 0;\n    v[3] = 0;\n    l2 = boost::math::tools::l2_norm(v.begin(), v.end());\n    BOOST_TEST(abs(l2 - bignum) < tol*l2);\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    Real scale = 8;\n    Real l2_1 = scale*l2_norm(v);\n    for (auto & x : v)\n    {\n        x *= -scale;\n    }\n    Real l2_2 = l2_norm(v);\n    BOOST_TEST(l2_1 > 0);\n    BOOST_TEST(l2_2 > 0);\n    BOOST_TEST(abs(l2_1 - l2_2) < tol*l2_1);\n}\n\ntemplate<class Z>\nvoid test_integer_l2_norm()\n{\n    double tol = 100*std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{1,1,1,1};\n    double l2 = boost::math::tools::l2_norm(v.begin(), v.end());\n    BOOST_TEST(abs(l2 - 2) < tol);\n\n    v = generate_random_vector<Z>(global_size, global_seed);\n    Z scale = 2;\n    double l2_1 = scale*l2_norm(v);\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    double l2_2 = l2_norm(v);\n    BOOST_TEST(l2_1 > 0);\n    BOOST_TEST(l2_2 > 0);\n    BOOST_TEST(abs(l2_1 - l2_2) < tol*l2_1);\n}\n\ntemplate<class Complex>\nvoid test_complex_l2_norm()\n{\n    typedef typename Complex::value_type Real;\n    Real tol = 100*std::numeric_limits<Real>::epsilon();\n    std::vector<Complex> v{{1,0}, {0,1},{0,-1}, {1,0}};\n    Real l2 = boost::math::tools::l2_norm(v.begin(), v.end());\n    BOOST_TEST(abs(l2 - 2) < tol);\n\n    l2 = boost::math::tools::l2_norm(v);\n    BOOST_TEST(abs(l2 - 2) < tol);\n\n    v = generate_random_vector<Complex>(global_size, global_seed);\n    Real scale = 8;\n    Real l2_1 = scale*l2_norm(v);\n    for (auto & x : v)\n    {\n        x *= -scale;\n    }\n    Real l2_2 = l2_norm(v);\n    BOOST_TEST(abs(l2_1 - l2_2) < tol*l2_1);\n}\n\ntemplate<class Real>\nvoid test_l2_distance()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,1,1,1};\n    Real l2 = boost::math::tools::l2_distance(v, v);\n    BOOST_TEST(abs(l2) < tol);\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    auto w = generate_random_vector<Real>(global_size, global_seed + 1);\n    Real dist1 = l2_distance(v, w);\n    Real dist2 = l2_distance(w, v);\n    BOOST_TEST(abs(dist1 - dist2) < tol*dist1);\n}\n\n\ntemplate<class Z>\nvoid test_integer_l2_distance()\n{\n    double tol = std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{1,1,1,1};\n    double l2 = boost::math::tools::l2_distance(v, v);\n    BOOST_TEST(abs(l2) < tol);\n\n    v = generate_random_vector<Z>(global_size, global_seed);\n    auto w = generate_random_vector<Z>(global_size, global_seed + 1);\n    double dist1 = l2_distance(v, w);\n    double dist2 = l2_distance(w, v);\n    BOOST_TEST(abs(dist1 - dist2) < tol*dist1);\n}\n\ntemplate<class Complex>\nvoid test_complex_l2_distance()\n{\n    typedef typename Complex::value_type Real;\n    Real tol = 100*std::numeric_limits<Real>::epsilon();\n    std::vector<Complex> v{{1,0}, {0,1},{0,-1}, {1,0}};\n    Real l2 = boost::math::tools::l2_distance(v, v);\n    BOOST_TEST(abs(l2) < tol);\n\n    v = generate_random_vector<Complex>(global_size, global_seed);\n    auto w = generate_random_vector<Complex>(global_size, global_seed + 1);\n    Real dist1 = l2_distance(v, w);\n    Real dist2 = l2_distance(w, v);\n    BOOST_TEST(abs(dist1 - dist2) < tol*dist1);\n}\n\ntemplate<class Real>\nvoid test_sup_distance()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,1,1,1};\n    std::vector<Real> w{0,0,0,0};\n    Real sup = boost::math::tools::sup_distance(v, v);\n    BOOST_TEST(abs(sup) < tol);\n    sup = boost::math::tools::sup_distance(v, w);\n    BOOST_TEST(abs(sup -1) < tol);\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    w = generate_random_vector<Real>(global_size, global_seed + 1);\n    Real dist1 = sup_distance(v, w);\n    Real dist2 = sup_distance(w, v);\n    BOOST_TEST(abs(dist1 - dist2) < tol*dist1);\n}\n\n\ntemplate<class Z>\nvoid test_integer_sup_distance()\n{\n    double tol = std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{1,1,1,1};\n    std::vector<Z> w{0,0,0,0};\n    double sup = boost::math::tools::sup_distance(v, v);\n    BOOST_TEST(abs(sup) < tol);\n\n    sup = boost::math::tools::sup_distance(v, w);\n    BOOST_TEST(abs(sup -1) < tol);\n\n    v = generate_random_vector<Z>(global_size, global_seed);\n    w = generate_random_vector<Z>(global_size, global_seed + 1);\n    double dist1 = sup_distance(v, w);\n    double dist2 = sup_distance(w, v);\n    BOOST_TEST(abs(dist1 - dist2) < tol*dist1);\n}\n\ntemplate<class Complex>\nvoid test_complex_sup_distance()\n{\n    typedef typename Complex::value_type Real;\n    Real tol = 100*std::numeric_limits<Real>::epsilon();\n    std::vector<Complex> v{{1,0}, {0,1},{0,-1}, {1,0}};\n    Real sup = boost::math::tools::sup_distance(v, v);\n    BOOST_TEST(abs(sup) < tol);\n\n    v = generate_random_vector<Complex>(global_size, global_seed);\n    auto w = generate_random_vector<Complex>(global_size, global_seed + 1);\n    Real dist1 = sup_distance(v, w);\n    Real dist2 = sup_distance(w, v);\n    BOOST_TEST(abs(dist1 - dist2) < tol*dist1);\n}\n\nint main()\n{\n    test_l0_pseudo_norm<unsigned>();\n    test_l0_pseudo_norm<int>();\n    test_l0_pseudo_norm<float>();\n    test_l0_pseudo_norm<double>();\n    test_l0_pseudo_norm<long double>();\n    test_l0_pseudo_norm<cpp_bin_float_50>();\n\n    test_complex_l0_pseudo_norm<std::complex<float>>();\n    test_complex_l0_pseudo_norm<std::complex<double>>();\n    test_complex_l0_pseudo_norm<std::complex<long double>>();\n    test_complex_l0_pseudo_norm<cpp_complex_50>();\n\n    test_hamming_distance<int>();\n    test_hamming_distance<unsigned>();\n\n    test_l1_norm<float>();\n    test_l1_norm<double>();\n    test_l1_norm<long double>();\n    test_l1_norm<cpp_bin_float_50>();\n\n    test_integer_l1_norm<int>();\n    test_integer_l1_norm<unsigned>();\n\n    test_complex_l1_norm<std::complex<float>>();\n    test_complex_l1_norm<std::complex<double>>();\n    test_complex_l1_norm<std::complex<long double>>();\n    test_complex_l1_norm<cpp_complex_50>();\n\n    test_l1_distance<float>();\n    test_l1_distance<cpp_bin_float_50>();\n\n    test_integer_l1_distance<int>();\n    test_integer_l1_distance<unsigned>();\n\n    test_complex_l1_distance<std::complex<float>>();\n    test_complex_l1_distance<cpp_complex_50>();\n\n    test_complex_l2_norm<std::complex<float>>();\n    test_complex_l2_norm<std::complex<double>>();\n    test_complex_l2_norm<std::complex<long double>>();\n    test_complex_l2_norm<cpp_complex_50>();\n\n    test_l2_norm<float>();\n    test_l2_norm<double>();\n    test_l2_norm<long double>();\n    test_l2_norm<cpp_bin_float_50>();\n\n    test_integer_l2_norm<int>();\n    test_integer_l2_norm<unsigned>();\n\n    test_l2_distance<double>();\n    test_l2_distance<cpp_bin_float_50>();\n\n    test_integer_l2_distance<int>();\n    test_integer_l2_distance<unsigned>();\n\n    test_complex_l2_distance<std::complex<double>>();\n    test_complex_l2_distance<cpp_complex_50>();\n\n    test_lp<float>();\n    test_lp<double>();\n    test_lp<long double>();\n    test_lp<cpp_bin_float_50>();\n\n    test_complex_lp<std::complex<float>>();\n    test_complex_lp<std::complex<double>>();\n    test_complex_lp<std::complex<long double>>();\n    test_complex_lp<cpp_complex_50>();\n\n    test_integer_lp<int>();\n    test_integer_lp<unsigned>();\n\n    test_lp_distance<double>();\n    test_lp_distance<cpp_bin_float_50>();\n\n    test_complex_lp_distance<std::complex<double>>();\n    test_complex_lp_distance<cpp_complex_50>();\n\n    test_integer_lp_distance<int>();\n    test_integer_lp_distance<unsigned>();\n\n    test_sup_norm<float>();\n    test_sup_norm<double>();\n    test_sup_norm<long double>();\n    test_sup_norm<cpp_bin_float_50>();\n\n    test_integer_sup_norm<int>();\n    test_integer_sup_norm<unsigned>();\n\n    test_complex_sup_norm<std::complex<float>>();\n    test_complex_sup_norm<std::complex<double>>();\n    test_complex_sup_norm<std::complex<long double>>();\n    test_complex_sup_norm<cpp_complex_50>();\n\n    test_sup_distance<double>();\n    test_sup_distance<cpp_bin_float_50>();\n\n    test_integer_sup_distance<int>();\n    test_integer_sup_distance<unsigned>();\n\n    test_complex_sup_distance<std::complex<double>>();\n    test_complex_sup_distance<cpp_complex_50>();\n\n    test_total_variation<float>();\n    test_total_variation<double>();\n    test_total_variation<long double>();\n    test_total_variation<cpp_bin_float_50>();\n\n    test_integer_total_variation<uint32_t>();\n    test_integer_total_variation<int>();\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "b176fa6c7c4898ab7b856ebb0cd986694c6911b6", "size": 25667, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/test/norms_test.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/math/test/norms_test.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/math/test/norms_test.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 28.1128148959, "max_line_length": 125, "alphanum_fraction": 0.6233685277, "num_tokens": 7670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.5545828362116575}}
{"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 * ModelPropertyTest.cpp\n *\n *  Created on: 14-05-2009\n *      Author: jimali\n */\n\n#include <rw/core/Log.hpp>\n#include <rw/graspplanning/GraspTable.hpp>\n#include <rw/math/MetricUtil.hpp>\n#include <rw/math/Random.hpp>\n#include <rw/math/Vector3D.hpp>\n\n#include <boost/numeric/conversion/cast.hpp>\n\nusing namespace rw::core;\nusing namespace rw::graspplanning;\nusing namespace rw::math;\n\nint main(int argc, char** argv)\n{\n\tconst double EPSILON = 0.000001;\n\tfor(int i=0;i<1000000;i++){\n\t\t//generate random vector\n\t\tVector3D<> v(Random::ran(0,1),Random::ran(0,1),Random::ran(0,1));\n\t\tif(MetricUtil::norm2(v)<0.001)\n\t\t\tcontinue;\n\n\t\tVector3D<> normal = normalize(v);\n\t\t// create perpendicular vector\n        Vector3D<> tdir;\n        if( fabs(normal(0))<EPSILON && fabs(normal(1))<EPSILON ){\n            tdir = normalize(  Vector3D<>(0,-normal(2),normal(1)) );\n        } else {\n            tdir = normalize(  Vector3D<>(-normal(1),normal(0),0) );\n        }\n        //std::cout << \"Angle: \" << (angle(tdir,normal)*Rad2Deg) << std::endl;\n        double ang = 90-angle(tdir,normal)*Rad2Deg;\n        if(fabs(ang)>2)\n        \tstd::cout << \"Angle: \" << (angle(tdir,normal)*Rad2Deg) << std::endl;\n\t}\n\texit(0);\n\n\n\n\n\n\n\tif( argc < 3 ){\n\t\tstd::cout << \"------ Usage: \" << std::endl;\n\t    std::cout << \"- Arg 1 name of grasp table\" << std::endl;\n\t    std::cout << \"- Arg 2 size of group\\n\" << std::endl;\n\t    return 0;\n\t}\n\tstd::string filename(argv[1]);\n\tint groupSize = 1;\n\tif(argc>2)\n\t    groupSize = std::atoi(argv[2]);\n\n\tPtr<GraspTable> gtable = GraspTable::load(filename);\n\tRW_ASSERT(gtable!=NULL);\n\tLog::infoLog() << \"Table size: \" << gtable->size() << std::endl;\n\tint nrOfGroups = boost::numeric_cast<int>(gtable->size())/groupSize;\n\tint globalStat = 0;\n\tfor(int i=0;i<nrOfGroups; i++){\n\t\tGraspTable::GraspData &ngrasp = gtable->getData()[i*groupSize];\n\t\tint localStat = 0;\n\t\tfor(int j=0;j<groupSize-1;j++){\n\t\t\tGraspTable::GraspData &grasp = gtable->getData()[i*groupSize+1+j];\n\t\t\t// test if any of the angles are too far away\n\t\t\tEAA<> eaa1 = grasp.hp.getEAA();\n\t\t\tEAA<> eaa2 = ngrasp.hp.getEAA();\n\t\t\tVector3D<> v1(eaa1(0),eaa1(1),eaa1(2));\n\t\t\tVector3D<> v2(eaa2(0),eaa2(1),eaa2(2));\n\t\t\tif( MetricUtil::dist2(v1,v2)>0.5 ){\n\t\t\t\tgrasp = ngrasp;\n\t\t\t\tlocalStat++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tglobalStat += localStat;\n\t\tstd::cout << \"Stat: \" << localStat << \"/\" << groupSize << std::endl;\n\t}\n\tstd::cout << \"Stat: \" << globalStat << \"/\" << groupSize*nrOfGroups << std::endl;\n\tgtable->save(\"grasptable_out.txt\");\n\treturn 0;\n}\n", "meta": {"hexsha": "8fc7a4a299714f040032c5c207d5dc2949a35ab9", "size": 2505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RobWorkSim/example/tools/src/GraspTableConvert.cpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWorkSim/example/tools/src/GraspTableConvert.cpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWorkSim/example/tools/src/GraspTableConvert.cpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4659090909, "max_line_length": 81, "alphanum_fraction": 0.6083832335, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.5545152679132166}}
{"text": "/*\n * utilities_trapz_test.cpp Test fixtures for the trapz function\n *\n * Author:                   Tom Clark (thclark @ github)\n *\n * Copyright (c) 2016-9 Octue Ltd. All Rights Reserved.\n *\n */\n\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\n#include \"utilities/cumsum.h\"\n\n\nusing namespace utilities;\n\n\nclass CumsumTest : public ::testing::Test {};\n\n\nTEST_F(CumsumTest, test_cumsum) {\n\n    // Test that zeros are returned when trying to colwise integrate an array with 1 row\n    Eigen::VectorXd in(4);\n    in << 1, 2, 6, 9;\n    Eigen::VectorXd out_correct(4);\n    out_correct << 1, 3, 9, 18;\n\n    Eigen::VectorXd out;\n    cumsum(out, in);\n    EXPECT_EQ(out.matrix(), out_correct.matrix());\n\n}\n", "meta": {"hexsha": "ae11d6a9b1bd1c0559ed1cabbfcab37a8b7589ec", "size": 696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/utilities_cumsum_test.cpp", "max_stars_repo_name": "octue/es-flow", "max_stars_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_stars_repo_licenses": ["Intel", "MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-01-07T13:55:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T16:30:03.000Z", "max_issues_repo_path": "test/unit/utilities_cumsum_test.cpp", "max_issues_repo_name": "octue/es-flow", "max_issues_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_issues_repo_licenses": ["Intel", "MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-09-04T10:40:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-02T10:13:25.000Z", "max_forks_repo_path": "test/unit/utilities_cumsum_test.cpp", "max_forks_repo_name": "octue/es-flow", "max_forks_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_forks_repo_licenses": ["Intel", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8857142857, "max_line_length": 88, "alphanum_fraction": 0.650862069, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5545066338430843}}
{"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 <gtest/gtest.h>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <stdexcept>\n#include <Eigen/Dense>\n\n// testing following API\n#include \"estimation/IEstimator.h\"\n#include \"estimation/ExtendedKalmanFilter.h\"\n#include \"estimation/Input.h\"\n#include \"estimation/InputValue.h\"\n#include \"estimation/Output.h\"\n#include \"estimation/OutputValue.h\"\n\nusing namespace std;\nusing namespace estimation;\n\nnamespace ExtendedKalmanFilterTest \n{\n  void f(VectorXd& x, const VectorXd& u)\n  {\n    x[0] = x[0] + u[0];\n  }\n  void df(MatrixXd& A, const VectorXd& x, const VectorXd& u)\n  {\n    A(0,0) = 1;\n  }\n  void h(VectorXd& z, const VectorXd& x)\n  {\n    z[0] = x[0];\n  }\n  void dh(MatrixXd& H, const VectorXd& x)\n  {\n    H(0,0) = 1;\n  }\n\n  void f2(VectorXd& x, const VectorXd& u)\n  {\n    VectorXd x_apriori(x.size());\n\n    x_apriori[0] = x[0] + 0.1*x[1];\n    x_apriori[1] = x[1];\n    \n    x = x_apriori;\n  }\n  void df2(MatrixXd& A, const VectorXd& x, const VectorXd& u)\n  {\n    A(0,0) = 1;\n    A(0,1) = 0.1;\n    A(1,0) = 0;\n    A(1,1) = 1;\n  }\n  void h2(VectorXd& z, const VectorXd& x)\n  {\n    z[0] = x[1];\n  }\n  void dh2(MatrixXd& H, const VectorXd& x)\n  {\n    H(0,0) = 0;\n    H(0,1) = 1;\n  }\n\n  // -----------------------------------------\n  // tests\n  // -----------------------------------------\n  TEST(ExtendedKalmanFilterTest, initialization)\n  {\n    ExtendedKalmanFilter ekf;\n\n    // check setting required params\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"STM missing\"\n    ekf.setStateTransitionModel(f);\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"Jacobian of STM missing\"\n    ekf.setJacobianOfStateTransitionModel(df);\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"OM missing\"\n    ekf.setObservationModel(h);\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"Jacobian of OM missing\"\n    ekf.setJacobianOfObservationModel(dh);\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"PNC missing\"\n    MatrixXd Q(1,1); Q << 0.1;\n    ekf.setProcessNoiseCovariance(Q);\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"MNC missing\"\n    MatrixXd R(1,1); R << 10;\n    ekf.setMeasurementNoiseCovariance(R);\n    EXPECT_NO_THROW(ekf.validate());\t\t\t// all required params given\n\n    // check setting optional params  \n    // optional params doesn't set new sizes\n    MatrixXd P0_f(2,2); P0_f << 1, 0, 0, 1;\n    ekf.setInitialErrorCovariance(P0_f);\n    EXPECT_NO_THROW(ekf.validate());\n    EXPECT_EQ(ekf.getState().size(), 1);\n\n    VectorXd x_f(2); x_f << 0,1;\n    ekf.setInitialState(x_f);\n    EXPECT_NO_THROW(ekf.validate());\n    EXPECT_NE(ekf.getState().size(), 2);\n\n    // required param Q sets new size of x and out\n    MatrixXd Q2(2,2); Q2 << 0.1, 0, 0, 0.1;\n    ekf.setProcessNoiseCovariance(Q2);   \n    EXPECT_NO_THROW(ekf.validate());\n    EXPECT_EQ(ekf.getState().size(), 2);\n    EXPECT_EQ(ekf.getLastEstimate().size(), 2);\n\n    // check initialization of output\n    Output out = ekf.getLastEstimate();\n    OutputValue defaultOutVal;\n    EXPECT_GT(out.size(), 0);\n    EXPECT_DOUBLE_EQ(out.getValue(), defaultOutVal.getValue());\n\n    // check setting the control input\n    InputValue ctrl(0);\n    Input in_ctrl(ctrl);\n    EXPECT_THROW(ekf.setControlInput(in_ctrl), length_error);\n    ekf.setControlInputSize(1);\n    EXPECT_NO_THROW(ekf.setControlInput(in_ctrl));\n  }\n\n  TEST(ExtendedKalmanFilterTest, validation)\n  {\n    ExtendedKalmanFilter ekf;\n\n    // check validation itself (e.g. invalid sizes of vectors/matrices,\n    // empty callbacks, etc.)\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"STM missing\"\n    ekf.setStateTransitionModel(0);\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"STM missing\"\n    ekf.setStateTransitionModel(f);\n    ekf.setJacobianOfStateTransitionModel(0);\t\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"STMJ missing\"\n    ekf.setJacobianOfStateTransitionModel(df);\n    ekf.setObservationModel(0);\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"OM missing\"\n    ekf.setObservationModel(h);\n    ekf.setJacobianOfObservationModel(0);\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"OMJ missing\"\n    ekf.setJacobianOfObservationModel(dh);\n\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"PNC missing\"\n    MatrixXd Q_f(2,1); Q_f << 0.1, 1;\n    ekf.setProcessNoiseCovariance(Q_f);\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"Q not square\"\n    MatrixXd Q1(1,1); Q1 << 0.1;\n    ekf.setProcessNoiseCovariance(Q1);\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"MNC missing\"\n    MatrixXd R_f(2,1); R_f << 10, 1;\n    ekf.setMeasurementNoiseCovariance(R_f);\n    EXPECT_THROW(ekf.validate(), IEstimator::estimator_error);\t// \"R not square\"\n    MatrixXd R(1,1); R << 10;\n    ekf.setMeasurementNoiseCovariance(R);\n\n    EXPECT_NO_THROW(ekf.validate());\t\t\t\t// all required params given\n\n    // optional params\n    VectorXd x(2); x << 0, 1;\n    ekf.setInitialState(x);\n    EXPECT_NO_THROW(ekf.validate());\n    EXPECT_NE(ekf.getState().size(), 2);\n\n    MatrixXd Q(2,2); Q << 0.1, 0, 0, 0.1;\n    ekf.setProcessNoiseCovariance(Q);\n    EXPECT_NO_THROW(ekf.validate());\n    ekf.setInitialState(x);\n    EXPECT_NO_THROW(ekf.validate());\n    EXPECT_EQ(ekf.getState().size(), 2);\t\t\t// sizes now ok\n\n    // size of R cannot be checked, must match number of formulas in h\n    // -> check during compile time\n  }\n\n  TEST(ExtendedKalmanFilterTest, validationEffect)\n  {  \n    ExtendedKalmanFilter ekf;\n\n    ekf.setStateTransitionModel(f);\n    ekf.setJacobianOfStateTransitionModel(df);\n    ekf.setObservationModel(h);\n    ekf.setJacobianOfObservationModel(dh);\n    MatrixXd Q(1,1); Q << 0.1;\n    ekf.setProcessNoiseCovariance(Q);\n    MatrixXd R(1,1); R << 10;\n    ekf.setMeasurementNoiseCovariance(R);\n    ekf.setControlInputSize(1);\t\t// initializes u, so it can be used in f\n\n    // validate has an effect?\n    InputValue measurement(1);\n    Input in(measurement);\n    Output out;\n  \n    EXPECT_THROW(out = ekf.estimate(in), IEstimator::estimator_error);\t// \"not yet validated\"\n  \n    EXPECT_NO_THROW(ekf.validate());\n    EXPECT_NO_THROW(out = ekf.estimate(in));\n\n    // changing a parameter -> EKF must be re-validated\n    ekf.setProcessNoiseCovariance(Q);\n    EXPECT_THROW(out = ekf.estimate(in), IEstimator::estimator_error);\t// \"not yet validated\"\n    EXPECT_NO_THROW(ekf.validate());\n  \n    // EKF should now be released and return an estimate (should not be\n    // the default)\n    EXPECT_NO_THROW(out = ekf.estimate(in));\n    EXPECT_GT(out.size(), 0);\n    OutputValue defaultOutVal;\n    EXPECT_NE(out.getValue(), defaultOutVal.getValue());\n  }\n\n  TEST(ExtendedKalmanFilterTest, functionality)\n  {\n    ExtendedKalmanFilter ekf;\n\n    ekf.setStateTransitionModel(f);\n    ekf.setJacobianOfStateTransitionModel(df);\n    ekf.setObservationModel(h);\n    ekf.setJacobianOfObservationModel(dh);\n    MatrixXd Q(1,1); Q << 0.1;\n    ekf.setProcessNoiseCovariance(Q);\n    MatrixXd R(1,1); R << 10;\n    ekf.setMeasurementNoiseCovariance(R);\n\n    ekf.validate();\n\n    // check if the calculation of an estimate is correct\n    // first measurement z1:\n    InputValue measurement(1);\n    Input in(measurement);\n    Output out;\n\n    // u contained in a state transition formula, so an error will be\n    // thrown when u is not initialized with the correct size\n    //out = ekf.estimate(in);\t\t// fail assertion produced by Eigen (out-of-range error)\n    ekf.setControlInputSize(1);\n    ekf.validate();\n    EXPECT_NO_THROW(out = ekf.estimate(in));\n\n    EXPECT_EQ(out.size(), 1);\n    EXPECT_NEAR(out[0].getValue(), 0.0099, 0.0001);\n    EXPECT_NEAR(out[0].getVariance(), 0.0990, 0.0001);\n\n    // next measurement z2:\n    in[0].setValue(5);\n\n    // setting a control input = 0 does not change the result, it can\n    // be calculated as if there is no control input\n    InputValue ctrl(0);\n    Input in_ctrl(ctrl);\n    ekf.setControlInput(in_ctrl);\t// (no validation needed, cannot be validated)\n\n    EXPECT_NO_THROW(out = ekf.estimate(in));\n  \n    EXPECT_NEAR(out[0].getValue(), 0.1073, 0.0001);\n    EXPECT_NEAR(out[0].getVariance(), 0.1951, 0.0001);\n\n    // missing measurement\n    InputValue missingValue;\n    Input inMissing(missingValue);\n    EXPECT_NO_THROW(out = ekf.estimate(inMissing));\n  \n    EXPECT_NEAR(out[0].getValue(), 0.1073, 0.0001);\n    EXPECT_NEAR(out[0].getVariance(), 0.2866, 0.0001);\n\n    // another example -----------------------------------\n    ExtendedKalmanFilter ekf2;\n    ekf2.setStateTransitionModel(f2);\n    ekf2.setJacobianOfStateTransitionModel(df2);\n    ekf2.setObservationModel(h2);\n    ekf2.setJacobianOfObservationModel(dh2);\n    MatrixXd Q2(2,2); Q2 << 0.1, 0, 0, 0.1;\n    ekf2.setProcessNoiseCovariance(Q2);\n    MatrixXd R2(1,1); R2 << 10;\n    ekf2.setMeasurementNoiseCovariance(R2);\n\n    ekf2.validate();\n\n    in[0].setValue(1);\n    EXPECT_NO_THROW(out = ekf2.estimate(in));\n    EXPECT_EQ(out.size(), 2);\n    \n    EXPECT_NEAR(out[0].getValue(), 0.0, 0.0001);\n    EXPECT_NEAR(out[0].getVariance(), 0.1, 0.0001);\n    EXPECT_NEAR(out[1].getValue(), 0.0099, 0.0001);\n    EXPECT_NEAR(out[1].getVariance(), 0.0990, 0.0001);\n\n    // missing measurement\n    EXPECT_NO_THROW(out = ekf2.estimate(inMissing));\n    \n    EXPECT_NEAR(out[0].getValue(), 0.00099, 0.0001);\n    EXPECT_NEAR(out[1].getValue(), 0.0099, 0.0001);\n  }\n\n}\n", "meta": {"hexsha": "63f8a668a76e214e41347009eff00388fc16b225", "size": 9426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sf_estimation/tests/utest_ExtendedKalmanFilter.cpp", "max_stars_repo_name": "tuw-cpsg/sf-pkg", "max_stars_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T09:47:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T16:01:11.000Z", "max_issues_repo_path": "sf_estimation/tests/utest_ExtendedKalmanFilter.cpp", "max_issues_repo_name": "ros-agriculture/sf-pkg", "max_issues_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T04:59:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-13T14:39:24.000Z", "max_forks_repo_path": "sf_estimation/tests/utest_ExtendedKalmanFilter.cpp", "max_forks_repo_name": "tuw-cpsg/sf-pkg", "max_forks_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-17T21:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T17:00:28.000Z", "avg_line_length": 32.0612244898, "max_line_length": 93, "alphanum_fraction": 0.6656057713, "num_tokens": 2851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5545029900723476}}
{"text": "#pragma once\n\n#include <ctime>\n#include <cstdlib>\n\n#include <vpp/vpp.hh>\n#include \"vpp/algorithms/line_tracker_4_sfm/miscellanous/operations.hh\"\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <unsupported/Eigen/Polynomials>\n\n\nusing namespace vpp;\nusing namespace std;\nusing namespace Eigen;\nusing namespace iod;\nusing namespace cv;\n\nnamespace vpp\n{\n\n//from http://www.mip.informatik.uni-kiel.de/tiki-index.php?page=Lilian+Zhang\n\nstruct structure_from_motion_ctx {\n    structure_from_motion_ctx(box2d domain) : keypoints(domain) {}\n\n    // Keypoint container.\n    // ctx.keypoint[i] to access the ith keypoint.\n    keypoint_container<keypoint<int>, int> keypoints;\n\n    std::vector<vfloat3> start_points;\n    std::vector<vfloat3> end_points;\n    std::vector<vfloat3> directions;\n};\n\nstructure_from_motion_ctx structure_from_motion_init(box2d domain);\n\nvoid initialize_rotation_matrix();\nvoid initialize_translation_matrix();\nvoid pose_estimation_from_line_correspondence(MatrixXf start_points, MatrixXf end_points,\n                                              MatrixXf directions, MatrixXf points,\n                                              MatrixXf &rot_cw, VectorXf &pos_cw);\ninline\nvoid cal_campose(MatrixXf XXc, MatrixXf XXw, int n, MatrixXf &R2, VectorXf &t2);\ninline\nvoid r_and_t(MatrixXf &rot_cw, VectorXf &pos_cw,MatrixXf start_points, MatrixXf end_points,\n             MatrixXf P1w,MatrixXf P2w,MatrixXf initRot_cw,VectorXf initPos_cw,\n             int maxIterNum,float TerminateTh,int nargin);\n\ninline\nvfloat3 x_cross(vfloat3 a,vfloat3 b);\n\n\nvoid triangulation();\nvoid bundle_adjustement();\n\n\n}\n\n#include \"structure_from_motion.hpp\"\n\n", "meta": {"hexsha": "322126e495db99cc4b029f7044ba5a43bb6fc230", "size": 1653, "ext": "hh", "lang": "C++", "max_stars_repo_path": "vpp/algorithms/line_tracker_4_sfm/sfm/structure_from_motion.hh", "max_stars_repo_name": "WLChopSticks/vpp", "max_stars_repo_head_hexsha": "2e17b21c56680bcfa94292ef5117f73572bf277d", "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/line_tracker_4_sfm/sfm/structure_from_motion.hh", "max_issues_repo_name": "WLChopSticks/vpp", "max_issues_repo_head_hexsha": "2e17b21c56680bcfa94292ef5117f73572bf277d", "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/line_tracker_4_sfm/sfm/structure_from_motion.hh", "max_forks_repo_name": "WLChopSticks/vpp", "max_forks_repo_head_hexsha": "2e17b21c56680bcfa94292ef5117f73572bf277d", "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": 26.2380952381, "max_line_length": 91, "alphanum_fraction": 0.7313974592, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.554502984604505}}
{"text": "/*!\n * \\file QBezierLine3D.hpp\n * \\author Jun Yoshida\n * \\copyright (c) 2019 Jun Yoshida.\n * The project is released under the MIT License.\n * \\date Descember 6, 2019: created\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include \"../math/Bezier.hpp\"\n#include \"../PathScheme.hpp\"\n#include \"PathFigure3D.hpp\"\n\nclass QBezierLine3D : public PathFigure3D, public Bezier<Eigen::Vector3d,2>\n{\npublic:\n    using BezierT = Bezier<Eigen::Vector3d,2>;\n\nprivate:\n    //! Three control points\n    Eigen::Vector3d m_init, m_ctrl, m_term;\n\npublic:\n    QBezierLine3D(std::array<double,3> const &init, std::array<double,3> const &ctrl, std::array<double,3> const &term)\n        : BezierT(\n            Eigen::Vector3d(init[0], init[1], init[2]),\n            Eigen::Vector3d(ctrl[0], ctrl[1], ctrl[2]),\n            Eigen::Vector3d(term[0], term[1], term[2])\n            )\n    {}\n\n    virtual ~QBezierLine3D() = default;\n\n    //! Methods inherited from PathFigure\n    void draw(SchemeType &scheme) const override {\n        scheme.moveTo(BezierT::get<0>());\n        scheme.qbezierTo(BezierT::get<1>(), BezierT::get<2>());\n        scheme.stroke();\n    }\n};\n", "meta": {"hexsha": "11992fb6850cc0857041f5979137f978b1308df6", "size": 1134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/figures/QBezierLine3D.hpp", "max_stars_repo_name": "Junology/bord2", "max_stars_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/figures/QBezierLine3D.hpp", "max_issues_repo_name": "Junology/bord2", "max_issues_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/figures/QBezierLine3D.hpp", "max_forks_repo_name": "Junology/bord2", "max_forks_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7727272727, "max_line_length": 119, "alphanum_fraction": 0.6313932981, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.554502984584036}}
{"text": "#include \"precompiled.h\"\r\n\r\n#include \"NetworkSenderApp.h\"\r\n\r\n#define WIN32_LEAN_AND_MEAN\r\n#include <windows.h>\r\n\r\n\r\n#include <boost/format.hpp>\r\n\r\n\r\nVector3 getDerive(const Vector3 &_p, const Vector3 &_q, const Real &_dt, const Real &_T)\r\n{\r\n    return (_p - _q) * (_T/(3*_dt));\r\n\r\n    \r\n    \r\n}\r\n\r\n\r\nNetworkSenderApp::NetworkSenderApp()\r\n\t:mAnimState(NULL)\r\n\t,mAnimState2(NULL)\r\n\t,mUdpSocket(0)\r\n\t,mIpAddress(\"\")\r\n\t,mConnected(1)\r\n    ,mTimeSinceLastUpdate(0)\r\n\t,mCurrentSpeed(Vector3::ZERO)\r\n\t,mIsMoving(false)\r\n    ,mHasMoved(false)\r\n    ,mSamplingInterval(1.0)\r\n    ,mTimeSinceLastSpeedSample(0.0)\r\n    ,mLastTimeDelta(0.0)\r\n{\r\n    mTitle = \"Sender\";\r\n}\r\n//------------------------------------------------------------------------------\r\nNetworkSenderApp::~NetworkSenderApp(void)\r\n{\r\n}\r\n//------------------------------------------------------------------------------\r\nbool NetworkSenderApp::frameStarted(const FrameEvent& evt)\r\n{\r\n\tif (mAnimState)\r\n\t\tmAnimState->addTime(evt.timeSinceLastFrame);\r\n\r\n\tif (mAnimState2)\r\n\t\tmAnimState2->addTime(evt.timeSinceLastFrame);\r\n\r\n\r\n    mTimeSinceLastUpdate += evt.timeSinceLastFrame;\r\n    mTimeSinceLastSpeedSample += evt.timeSinceLastFrame;\r\n    \r\n\r\n    Vector3 currentPos = mBallNode->getPosition();\r\n\r\n    if (! mIsMoving)\r\n    {\r\n        if(currentPos != mLastBallPosition)\r\n        {\r\n            mHasMoved = true;\r\n            mIsMoving = true;\r\n            //mCurrentSpeed = getDerive(currentPos, mLastBallPosition, evt.timeSinceLastFrame);\r\n            mCurrentSpeed =  0.33 * (currentPos - mLastBallPosition);\r\n            mLastTimeDelta = evt.timeSinceLastFrame;\r\n            mLastBallPosition = currentPos;\r\n        }\r\n    }\r\n    else\r\n    {\r\n        if(mTimeSinceLastUpdate > mSamplingInterval)\r\n        {\r\n             mCurrentSpeed = getDerive(currentPos, mLastBallPosition\r\n                                      ,evt.timeSinceLastFrame\r\n                                      ,mSamplingInterval);\r\n            mLastBallPosition = currentPos;\r\n            _sendPosition();\r\n            mTimeSinceLastUpdate = 0;\r\n        }\r\n        //else if (mTimeSinceLastSpeedSample > mSamplingInterval/10)\r\n        //{\r\n        //    mCurrentSpeed = getDerive(currentPos, mLastBallPosition, mSamplingInterval/10);\r\n        //    mCurrentSpeed *= (mSamplingInterval) / 3;\r\n        //    mLastTimeDelta = evt.timeSinceLastFrame;\r\n        //    mLastBallPosition = currentPos;\r\n        //    mTimeSinceLastSpeedSample = 0.0;\r\n        //    \r\n        //}\r\n    }\r\n\r\n    mLastBallPosition = currentPos;\r\n\r\n   \treturn true;\r\n}\r\n//------------------------------------------------------------------------------\r\nbool NetworkSenderApp::frameEnded_(const FrameEvent& evt)\r\n{\r\n    //if(mLastBallPosition == mBallNode->getPosition())\r\n    //{\r\n    //    if(mIsMoving)\r\n    //    {\r\n    //        mIsMoving = false;\r\n    //        mCurrentSpeed = Vector3::ZERO;\r\n    //    }\r\n    //}\r\n    //else\r\n    //{\r\n    //    if(!mIsMoving)\r\n    //    {\r\n    //        \r\n    //    }\r\n    //}\r\n\r\n\t//mTimeSinceLastUpdate += evt.timeSinceLastFrame;\r\n\t//_sendPosition();\r\n\r\n\treturn true;\r\n}\r\n//------------------------------------------------------------------------------\r\nvoid NetworkSenderApp::createScene()\r\n{\r\n\r\n\r\n\tconst RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities();\r\n\tif (!caps->hasCapability(RSC_VERTEX_PROGRAM) || !(caps->hasCapability(RSC_FRAGMENT_PROGRAM)))\r\n\t{\r\n\t\tOGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, \"Your card does not support vertex and fragment programs, so cannot \"\r\n\t\t\t\"run this demo. Sorry!\", \r\n\t\t\t\"createScene\");\r\n\t}\r\n\r\n\tViewport *vp = mWindow->getViewport(0);\r\n\tvp->setBackgroundColour(ColourValue(0.7, 0.7, 0.7));\r\n\r\n\tmRoot->addFrameListener(this); \r\n\r\n\tmSceneMgr->setNormaliseNormalsOnScale(true);\r\n\r\n\t_createAxes(5);\r\n\t_createGrid(5);\r\n\r\n\t\tmCamera->setPosition(Vector3(100, 100, 100));\r\n\tmCamera->lookAt(Vector3::ZERO);\r\n\r\n\t_createLight();\r\n\r\n\r\n\tmBallNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(\"Ball Node\");\r\n\tEntity *ent = mSceneMgr->createEntity(\"my ball\", \"sphere.mesh\");\r\n\t//ent->setMaterialName(\"Objects/Ball\");\r\n\r\n\r\n\tent->getSubEntity(0)->setMaterialName(\"Examples/CelShading\");\r\n\r\n\tent->getSubEntity(0)->setCustomParameter(0, Vector4(10.0f, 0.0f, 0.0f, 0.0f));\r\n\tent->getSubEntity(0)->setCustomParameter(1, Vector4(0.0f, 0.5f, 0.0f, 1.0f));\r\n\tent->getSubEntity(0)->setCustomParameter(2, Vector4(0.3f, 0.5f, 0.3f, 1.0f));\r\n\r\n\r\n\r\n\tfloat w = ent->getBoundingBox().getSize().x;\r\n\tfloat ws = 10.0 / w;\r\n\t\r\n\tmBallNode->attachObject(ent);\r\n\tmBallNode->setScale(ws, ws, ws);\r\n\r\n\tfloat totalTime = 8;\r\n\tfloat halfTime  = totalTime/2;\r\n\r\n\tAnimation *anim = mSceneMgr->createAnimation(\"bouncing ball\", totalTime);\r\n\tanim->setDefaultInterpolationMode(Animation::IM_SPLINE);\r\n\tNodeAnimationTrack *track = anim->createNodeTrack(0, mBallNode);\r\n\tTransformKeyFrame *key = track->createNodeKeyFrame(0);\r\n\t\r\n\t// start\r\n\tkey->setScale(Vector3(ws, ws, ws));\r\n\tkey->setTranslate(Vector3(0, 0, 0));    \r\n\r\n\r\n\t// first half\r\n\tkey = track->createNodeKeyFrame(halfTime * 1./4);\r\n\tkey->setScale(Vector3(ws, ws, ws));\r\n\tkey->setTranslate(Vector3(50, 0, -25));\r\n\r\n\tkey = track->createNodeKeyFrame(halfTime * 2./4);\r\n\tkey->setScale(Vector3(ws, ws, ws));\r\n\tkey->setTranslate(Vector3(100, 0, 0));\r\n\r\n\tkey = track->createNodeKeyFrame(halfTime * 3./4);\r\n\tkey->setScale(Vector3(ws, ws, ws));\r\n\tkey->setTranslate(Vector3(50, 0, 25));\r\n\r\n\tkey = track->createNodeKeyFrame(halfTime);\r\n\tkey->setScale(Vector3(ws, ws, ws));\r\n\tkey->setTranslate(Vector3(0, 0, 0));\r\n\r\n\t// second half\r\n\tkey = track->createNodeKeyFrame(halfTime + halfTime * 1./4);\r\n\tkey->setScale(Vector3(ws, ws, ws));\r\n\tkey->setTranslate(Vector3(-50, 0, -25));\r\n\r\n\tkey = track->createNodeKeyFrame(halfTime + halfTime * 2./4);\r\n\tkey->setScale(Vector3(ws, ws, ws));\r\n\tkey->setTranslate(Vector3(-100, 0, 0));\r\n\r\n\tkey = track->createNodeKeyFrame(halfTime + halfTime * 3./4);\r\n\tkey->setScale(Vector3(ws, ws, ws));\r\n\tkey->setTranslate(Vector3(-50, 0, 25));\r\n\r\n\t\r\n\tkey = track->createNodeKeyFrame(totalTime);\r\n\tkey->setScale(Vector3(ws, ws, ws));\r\n\tkey->setTranslate(Vector3(0, 0, 0));\r\n\r\n\tmAnimState = mSceneMgr->createAnimationState(\"bouncing ball\");\r\n\tmAnimState->setEnabled(1);\r\n\r\n    _readConfigurationFromFile();\r\n\t_initNetwork();\r\n\r\n\t// start of track\r\n\tmLastBallPosition = Vector3(0, 0, 0);\r\n}\r\n//------------------------------------------------------------------------------\r\nvoid NetworkSenderApp::_createAxes(int _nUnits)\r\n{\r\n\tmGridNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(\"WorldGrid Node\");\r\n\tManualObject *line = mSceneMgr->createManualObject(\"X Axis\");\r\n\tint scale = 100;\r\n\r\n\tline->begin(\"WorldGrid/XAxis\", RenderOperation::OT_LINE_LIST);\r\n\tline->position(-_nUnits, 0.0, 0.0);     line->normal(Vector3::UNIT_Y);      line->colour(0.1, 0.0, 0.0);\r\n\tline->position( _nUnits, 0.0, 0.0);     line->normal(Vector3::UNIT_Y);      line->colour(1.0, 0.0, 0.0);\r\n\tline->end();\r\n\tmGridNode->attachObject(line);\r\n\r\n\tline = mSceneMgr->createManualObject(\"Y Axis\");\r\n\tline->begin(\"WorldGrid/YAxis\", RenderOperation::OT_LINE_LIST);\r\n\tline->position(0.0, -_nUnits, 0.0);     line->normal(Vector3::UNIT_Y);      line->colour(0.0, 0.1, 0.0);\r\n\tline->position(0.0,  _nUnits, 0.0);     line->normal(Vector3::UNIT_Y);      line->colour(0.0, 1.0, 0.0);\r\n\tline->end();\r\n\tmGridNode->attachObject(line);\r\n\r\n\tline = mSceneMgr->createManualObject(\"Z Axis\");\r\n\tline->begin(\"WorldGrid/ZAxis\", RenderOperation::OT_LINE_LIST);\r\n\tline->position( 0.0, 0.0, -_nUnits);     line->normal(Vector3::UNIT_Y);      line->colour(0.0, 0.0, 0.1);\r\n\tline->position( 0.0, 0.0,  _nUnits);     line->normal(Vector3::UNIT_Y);      line->colour(0.0, 0.0, 1.0);\r\n\tline->end();\r\n\tmGridNode->attachObject(line);\r\n\r\n\r\n\r\n\tmGridNode->scale(scale, scale, scale);\r\n\r\n}\r\n//------------------------------------------------------------------------------\r\nvoid NetworkSenderApp::_createGrid(int _nUnits)\r\n{\r\n\tfloat step = 0.1;\r\n\tint nUnits = _nUnits;\r\n\r\n\tManualObject *grid = mSceneMgr->createManualObject(\"Grid Lines\");\r\n\tgrid->begin(\"WorldGrid/Lines\", RenderOperation::OT_LINE_LIST);\r\n\r\n\tgrid->colour(0.5, 0.5, 0.5);\r\n\r\n\tfor(int i=1 ; i <= int(nUnits * (1.0/step)) ; i++)\r\n\t{\r\n\t\tfloat offset=i*step;\r\n\r\n\t\t// horizontal (parallel to X axis)\r\n\r\n\r\n\t\tgrid->position( -nUnits, 0.0, offset);   grid->normal(Vector3::UNIT_Y); \r\n\t\tgrid->position(  nUnits, 0.0, offset);   grid->normal(Vector3::UNIT_Y); \r\n\r\n\t\tgrid->position( -nUnits, 0.0, -offset);   grid->normal(Vector3::UNIT_Y);\r\n\t\tgrid->position(  nUnits, 0.0, -offset);   grid->normal(Vector3::UNIT_Y);\r\n\r\n\r\n\t\t// vertical (parallel to Z axis)\r\n\t\tgrid->position( offset, 0.0, -nUnits);   grid->normal(Vector3::UNIT_Y);\r\n\t\tgrid->position( offset, 0.0,  nUnits);   grid->normal(Vector3::UNIT_Y);\r\n\r\n\t\tgrid->position( -offset, 0.0, -nUnits);   grid->normal(Vector3::UNIT_Y);\r\n\t\tgrid->position( -offset, 0.0,  nUnits);   grid->normal(Vector3::UNIT_Y);\r\n\r\n\t}\r\n\r\n\r\n\tgrid->end();\r\n\r\n\tmGridNode->attachObject(grid);\r\n\r\n\r\n}\r\n//------------------------------------------------------------------------------\r\nvoid NetworkSenderApp::_createLight()\r\n{\r\n\tLight *light = mSceneMgr->createLight(\"Main Light\");\r\n\tlight->setType(Light::LT_POINT);\r\n\tlight->setPosition(Vector3(0, 100, 0));\r\n\tlight->setSpecularColour(ColourValue::White);\r\n\tlight->setDiffuseColour(ColourValue::White);\r\n\r\n\tmLightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(\"light node\");\r\n\tmLightNode->attachObject(light);\r\n\r\n\tAnimation *anim = mSceneMgr->createAnimation(\"light track\", 4);\r\n\tanim->setDefaultInterpolationMode(Animation::IM_SPLINE);\r\n\r\n\tNodeAnimationTrack *track = anim->createNodeTrack(0, mLightNode);\r\n\tTransformKeyFrame *key = track->createNodeKeyFrame(0);\r\n\tkey->setTranslate(Vector3(100, 100, 0));\r\n\tkey = track->createNodeKeyFrame(1);\r\n\tkey->setTranslate(Vector3(100, 100, 100));\r\n\tkey = track->createNodeKeyFrame(2);\r\n\tkey->setTranslate(Vector3(-100, 100, 0));\r\n\tkey = track->createNodeKeyFrame(3);\r\n\tkey->setTranslate(Vector3(-100, 100, -100));\r\n\tkey = track->createNodeKeyFrame(4);\r\n\tkey->setTranslate(Vector3(100, 100, 0));\r\n\r\n\tmAnimState2 = mSceneMgr->createAnimationState(\"light track\");\r\n\tmAnimState2->setEnabled(1);\r\n\r\n\r\n}\r\n//------------------------------------------------------------------------------\r\nvoid NetworkSenderApp::_readConfigurationFromFile()\r\n{\r\n    ConfigFile cf;\r\n    cf.load(\"sender.cfg\");\r\n\r\n    mIpAddress = cf.getSetting(\"Peer Address\", \"Network\");\r\n    mUdpPort   =  cf.getSetting(\"UDP Port\", \"Network\");\r\n\r\n    mSamplingInterval = StringConverter::parseReal(cf.getSetting(\"Sampling Interval\", \"Network\"));\r\n\r\n}\r\n//------------------------------------------------------------------------------\r\nvoid NetworkSenderApp::_initNetwork()\r\n{\r\n\tmNetworkLog = LogManager::getSingleton().createLog(\"network.log\");\r\n\r\n\r\n\tmUdpResolver = new udp::resolver(mIOService);\r\n\tmUdpQuery = new udp::resolver::query(udp::v4(), mIpAddress, mUdpPort);\r\n\t\r\n    mUdpReceiverEndpoint = *(mUdpResolver->resolve(*mUdpQuery));\r\n\r\n\tmUdpSocket = new udp::socket(mIOService);\r\n\tmUdpSocket->open(udp::v4());\r\n\r\n    mConnected = true;\r\n\r\n}\r\n//------------------------------------------------------------------------------\r\nvoid NetworkSenderApp::_sendPosition()\r\n{\r\n\tif(mConnected)\r\n\t{\t\t\r\n        Vector3 pos = mBallNode->getPosition();\r\n        Vector3 speed = mCurrentSpeed;\r\n\r\n\t\tboost::format fmt(\"[new pdu] position (%.2f  %.2f  %.2f) speed (%.3f  %.3f  %.3f) dt %.6f\");\r\n\t\tfmt % pos.x % pos.y % pos.z % speed.x % speed.y % speed.z % mLastTimeDelta;\r\n\t\tmNetworkLog->logMessage(fmt.str());\r\n\r\n        _sendPdu(pos, speed);\r\n\t}\r\n}\r\n//------------------------------------------------------------------------------\r\nvoid NetworkSenderApp::_sendPdu(const Vector3 &_pos, const Vector3 &_speed)\r\n{\r\n    char arr[6*sizeof(Real)];\r\n    \r\n    memcpy(arr,                 _pos.ptr(),   3*sizeof(Real));\r\n    memcpy(arr+3*sizeof(Real),  _speed.ptr(), 3*sizeof(Real));\r\n    \r\n    mUdpSocket->send_to(boost::asio::buffer(arr, 6*sizeof(Real))\r\n                        ,mUdpReceiverEndpoint\r\n                        ,0\r\n                        ,mSocketError);\r\n\r\n    if (mSocketError)\r\n    {\r\n        boost::format fmt(\"socket error : %d\");\r\n        fmt % mSocketError;\r\n        mNetworkLog->logMessage(fmt.str());\r\n    }\r\n}\r\n//------------------------------------------------------------------------------\r\nvoid NetworkSenderApp::_sendFloat(float _val)\r\n{\r\n\tchar arr[4];\r\n\tmemcpy(arr, &_val, sizeof(_val));\r\n\r\n\t//int n = boost::asio::write(*mSocket\r\n\t//\t\t\t\t\t\t  ,boost::asio::buffer(arr, sizeof(_val))\r\n\t//\t\t\t\t\t\t  ,boost::asio::transfer_all()\r\n\t//\t\t\t\t\t\t  ,mSocketError);\r\n\r\n\r\n\tmUdpSocket->send_to(boost::asio::buffer(arr, sizeof(_val))\r\n\t\t\t\t\t   ,mUdpReceiverEndpoint\r\n\t\t\t\t\t   ,0\r\n\t\t\t\t\t   ,mSocketError);\r\n\r\n\r\n\tif (mSocketError)\r\n\t{\r\n\t\tboost::format fmt(\"socket error : %d\");\r\n\t\tfmt % mSocketError;\r\n\t\tmNetworkLog->logMessage(fmt.str());\r\n\t}\r\n}\r\n//------------------------------------------------------------------------------\r\nvoid NetworkSenderApp::_sleep(int _ms)\r\n{\r\n\t// sleep 20ms\r\n\tboost::xtime sleeptime;\r\n\tboost::xtime_get(&sleeptime, boost::TIME_UTC);\r\n\tsleeptime.nsec += 1000000 * _ms;\r\n\tboost::thread::sleep(sleeptime);\r\n}\r\n//------------------------------------------------------------------------------\r\n", "meta": {"hexsha": "a6eaaf3a4f39a44ad254f9c63a1e19501883b775", "size": 13239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ogre-network-sender/NetworkSenderApp.cpp", "max_stars_repo_name": "sevas/ogre-path-interpolation", "max_stars_repo_head_hexsha": "828efa8c0e4878ab1ed9b6c410c14b1e337c6cef", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-07T03:48:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-03T06:59:10.000Z", "max_issues_repo_path": "ogre-network-sender/NetworkSenderApp.cpp", "max_issues_repo_name": "sevas/ogre-path-interpolation", "max_issues_repo_head_hexsha": "828efa8c0e4878ab1ed9b6c410c14b1e337c6cef", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ogre-network-sender/NetworkSenderApp.cpp", "max_forks_repo_name": "sevas/ogre-path-interpolation", "max_forks_repo_head_hexsha": "828efa8c0e4878ab1ed9b6c410c14b1e337c6cef", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9322429907, "max_line_length": 116, "alphanum_fraction": 0.5829745449, "num_tokens": 3512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.554502984584036}}
{"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": "// Copyright Louis Dionne 2013-2017\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n\n#include <boost/hana/all_of.hpp>\n#include <boost/hana/assert.hpp>\n#include <boost/hana/cartesian_product.hpp>\n#include <boost/hana/contains.hpp>\n#include <boost/hana/core/to.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/functional/demux.hpp>\n#include <boost/hana/fuse.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/minus.hpp>\n#include <boost/hana/mod.hpp>\n#include <boost/hana/not.hpp>\n#include <boost/hana/not_equal.hpp>\n#include <boost/hana/or.hpp>\n#include <boost/hana/plus.hpp>\n#include <boost/hana/set.hpp>\n#include <boost/hana/transform.hpp>\n#include <boost/hana/tuple.hpp>\nnamespace hana = boost::hana;\nusing namespace hana::literals;\n\n\n// A function that can have an arbitrary compile-time set of values as a domain\n// and co-domain. This is most likely purely of theoretical interest, but it\n// allows creating functions with very complex domains and co-domains that are\n// computed at compile-time.\n\nstruct Function { };\n\ntemplate <typename Domain, typename Codomain, typename F>\nstruct function_type {\n    using hana_tag = Function;\n\n    Domain domain_;\n    Codomain codomain_;\n    F f_;\n\n    template <typename X>\n    constexpr auto operator()(X x) const {\n        BOOST_HANA_CONSTANT_ASSERT(boost::hana::contains(domain_, x));\n        return f_(x);\n    }\n};\n\ntemplate <typename ...F, typename ...G>\nconstexpr auto operator==(function_type<F...> f, function_type<G...> g)\n{ return hana::equal(f, g); }\n\ntemplate <typename ...F, typename ...G>\nconstexpr auto operator!=(function_type<F...> f, function_type<G...> g)\n{ return hana::not_equal(f, g); }\n\n\nauto function = [](auto domain, auto codomain) {\n    return [=](auto definition) {\n        return function_type<decltype(domain), decltype(codomain), decltype(definition)>{\n            domain, codomain, definition\n        };\n    };\n};\n\ntemplate <typename Function>\nconstexpr auto domain(Function f)\n{ return f.domain_; }\n\ntemplate <typename Function>\nconstexpr auto codomain(Function f)\n{ return f.codomain_; }\n\ntemplate <typename Function>\nconstexpr auto range(Function f) {\n    // We must convert to hana::tuple first because hana::set is not a Functor\n    return hana::to_set(hana::transform(hana::to_tuple(domain(f)), f));\n}\n\ntemplate <typename P, typename Q>\nconstexpr auto implies(P p, Q q) {\n    return hana::or_(hana::not_(p), q);\n}\n\ntemplate <typename F>\nconstexpr auto is_injective(F f) {\n    auto dom = hana::to_tuple(domain(f));\n    auto pairs = hana::cartesian_product(hana::make_tuple(dom, dom));\n    return hana::all_of(pairs, hana::fuse([&](auto x, auto y) {\n        return implies(hana::not_equal(x, y), hana::not_equal(f(x), f(y)));\n    }));\n}\n\ntemplate <typename F>\nconstexpr auto is_onto(F f) {\n    return codomain(f) == range(f);\n}\n\nnamespace boost { namespace hana {\n    template <>\n    struct equal_impl<Function, Function> {\n        template <typename F, typename G>\n        static constexpr auto apply(F f, G g) {\n            return domain(f) == domain(g) &&\n                   hana::all_of(domain(f), hana::demux(hana::equal)(f, g));\n        }\n    };\n}} // end namespace boost::hana\n\nint main() {\n    auto f = function(hana::make_set(1_c, 2_c, 3_c), hana::make_set(1_c, 2_c, 3_c, 4_c, 5_c, 6_c))(\n        [](auto x) { return x + 1_c; }\n    );\n\n    auto g = function(hana::make_set(1_c, 2_c, 3_c), hana::make_set(2_c, 3_c, 4_c))(\n        [](auto x) { return x + 1_c; }\n    );\n\n    auto h = function(hana::make_set(1_c, 2_c, 3_c), hana::make_set(0_c, 1_c, 2_c))(\n        [](auto x) { return x - 1_c; }\n    );\n\n    BOOST_HANA_CONSTANT_CHECK(f == g);\n    BOOST_HANA_CONSTANT_CHECK(f != h);\n    BOOST_HANA_CONSTANT_CHECK(f(1_c) == 2_c);\n\n    BOOST_HANA_CONSTANT_CHECK(range(f) == hana::make_set(4_c, 3_c, 2_c));\n    BOOST_HANA_CONSTANT_CHECK(range(g) == hana::make_set(2_c, 3_c, 4_c));\n    BOOST_HANA_CONSTANT_CHECK(range(h) == hana::make_set(0_c, 1_c, 2_c));\n\n    BOOST_HANA_CONSTANT_CHECK(hana::not_(is_onto(f)));\n    BOOST_HANA_CONSTANT_CHECK(is_onto(g));\n    BOOST_HANA_CONSTANT_CHECK(is_onto(h));\n\n    auto even = function(hana::make_set(1_c, 2_c, 3_c), hana::make_set(hana::true_c, hana::false_c))(\n        [](auto x) { return x % 2_c == 0_c; }\n    );\n\n    BOOST_HANA_CONSTANT_CHECK(is_injective(f));\n    BOOST_HANA_CONSTANT_CHECK(is_injective(g));\n    BOOST_HANA_CONSTANT_CHECK(is_injective(h));\n    BOOST_HANA_CONSTANT_CHECK(hana::not_(is_injective(even)));\n}\n", "meta": {"hexsha": "6a290489b33a5ab46d66cfa3f5b0fa4a44be7139", "size": 4568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/hana/example/misc/restricted_function.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/hana/example/misc/restricted_function.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/hana/example/misc/restricted_function.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 31.7222222222, "max_line_length": 101, "alphanum_fraction": 0.6766637478, "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388209992571, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.55446081442162}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/vector/object.hpp>\n#include <fcppt/math/vector/static.hpp>\n#include <fcppt/math/vector/unit.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_vector_unit\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef fcppt::math::vector::static_<\n\t\tint,\n\t\t3\n\t> int3_vector;\n\n\tint3_vector const vec(\n\t\tfcppt::math::vector::unit<\n\t\t\tint3_vector\n\t\t>(\n\t\t\t2\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tvec[0],\n\t\t0\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tvec[1],\n\t\t0\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tvec[2],\n\t\t1\n\t);\n}\n", "meta": {"hexsha": "5a198e7f896e669815b167702510356eefa61b76", "size": 1009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/vector/unit.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/vector/unit.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/vector/unit.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3454545455, "max_line_length": 61, "alphanum_fraction": 0.7224975223, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5544608114131574}}
{"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 \"pypearray.h\"\n\n#include <Eigen/Geometry>\n#include <pybind11/operators.h>\n\nusing namespace PR;\nnamespace PRPY {\n\nPR_NO_SANITIZE_ADDRESS\nvoid setup_math(py::module& m)\n{\n\ttypedef Eigen::Quaternion<float, 0> Quat;\n\n\tpy::class_<Quat>(m, \"Quaternionf\")\n\t\t.def_static(\"Identity\", &Quat::Identity)\n\n\t\t.def(py::init<>())\n\t\t.def(py::init<float, float, float, float>())\n\t\t.def_static(\"UnitRandom\", &Quat::UnitRandom)\n\n\t\t.def(py::self * py::self)\n\t\t.def(py::self *= py::self)\n\n\t\t.def(\"angularDistance\", &Quat::angularDistance<Quat>)\n\t\t.def(\"conjugate\", &Quat::conjugate)\n\t\t.def(\"dot\", &Quat::dot<Quat>)\n\t\t.def(\"inverse\", &Quat::inverse)\n\t\t.def(\"norm\", &Quat::norm)\n\t\t.def(\"squaredNorm\", &Quat::squaredNorm)\n\t\t.def(\"normalize\", &Quat::normalize)\n\t\t.def(\"normalized\", &Quat::normalized)\n\t\t.def(\"toRotationMatrix\", &Quat::toRotationMatrix)\n\t\t.def(\"slerp\", &Quat::slerp<Quat>)\n\n\t\t.def_property(\"w\", [](const Quat& o) { return o.w(); }, [](Quat& o, float v) { o.w() = v; })\n\t\t.def_property(\"x\", [](const Quat& o) { return o.x(); }, [](Quat& o, float v) { o.x() = v; })\n\t\t.def_property(\"y\", [](const Quat& o) { return o.y(); }, [](Quat& o, float v) { o.y() = v; })\n\t\t.def_property(\"z\", [](const Quat& o) { return o.z(); }, [](Quat& o, float v) { o.z() = v; })\n\n\t\t.def(\"__getitem__\", [](const Quat& o, size_t i) {\n\t\t\tswitch (i) {\n\t\t\tcase 0:\n\t\t\t\treturn o.w();\n\t\t\tcase 1:\n\t\t\t\treturn o.x();\n\t\t\tcase 2:\n\t\t\t\treturn o.y();\n\t\t\tcase 3:\n\t\t\t\treturn o.z();\n\t\t\tdefault:\n\t\t\t\tthrow std::runtime_error(\"Quaternion access out of bound!\");\n\t\t\t\treturn 0.0f;\n\t\t\t}\n\t\t})\n\t\t.def(\"__setitem__\", [](Quat& o, size_t i, float v) {\n\t\t\tswitch (i) {\n\t\t\tcase 0:\n\t\t\t\to.w() = v;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\to.x() = v;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\to.y() = v;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\to.z() = v;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow std::runtime_error(\"Quaternion access out of bound!\");\n\t\t\t}\n\t\t});\n\t//.def_static(\"FromTwoVectors\", &Eigen::Quaternionf::FromTwoVectors<Eigen::Matrix<float,3,1>, Eigen::Matrix<float,3,1>>)\n}\n}", "meta": {"hexsha": "2229f5b47e416c801761303f8bbc8b4b3fdbfce2", "size": 1973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python/math.cpp", "max_stars_repo_name": "PearCoding/PearRay", "max_stars_repo_head_hexsha": "8654a7dcd55cc67859c7c057c7af64901bf97c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2016-11-07T00:01:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T05:35:14.000Z", "max_issues_repo_path": "src/python/math.cpp", "max_issues_repo_name": "PearCoding/PearRay", "max_issues_repo_head_hexsha": "8654a7dcd55cc67859c7c057c7af64901bf97c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2016-07-06T21:58:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-01T18:18:24.000Z", "max_forks_repo_path": "src/python/math.cpp", "max_forks_repo_name": "PearCoding/PearRay", "max_forks_repo_head_hexsha": "8654a7dcd55cc67859c7c057c7af64901bf97c35", "max_forks_repo_licenses": ["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.3066666667, "max_line_length": 121, "alphanum_fraction": 0.5838824126, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5544608057598518}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[register_multi_linestring\r\n//` Show the use of the macro BOOST_GEOMETRY_REGISTER_MULTI_LINESTRING\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/linestring.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\r\n#include <boost/geometry/multi/geometries/register/multi_linestring.hpp>\r\n\r\ntypedef boost::geometry::model::linestring\r\n    <\r\n        boost::tuple<float, float> \r\n    > linestring_type;\r\n\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\r\nBOOST_GEOMETRY_REGISTER_MULTI_LINESTRING(std::deque<linestring_type>)\r\n\r\nint main()\r\n{\r\n    // Normal usage of std::\r\n    std::deque<linestring_type> lines(2);\r\n    boost::geometry::read_wkt(\"LINESTRING(0 0,1 1)\", lines[0]);\r\n    boost::geometry::read_wkt(\"LINESTRING(2 2,3 3)\", lines[1]);\r\n    \r\n    // Usage of Boost.Geometry\r\n    std::cout << \"LENGTH: \"  << boost::geometry::length(lines) << std::endl;\r\n    \r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[register_multi_linestring_output\r\n/*`\r\nOutput:\r\n[pre\r\nLENGTH: 2.82843\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "4f3a331fff8f8a82e27a81b643503f504268a854", "size": 1391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/geometries/register/multi_linestring.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/geometries/register/multi_linestring.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/geometries/register/multi_linestring.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 26.75, "max_line_length": 80, "alphanum_fraction": 0.6994967649, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.554455137345938}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_BERNOULLI_LOGIT_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_BERNOULLI_LOGIT_RNG_HPP\n\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_bounded.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/fun/inv_logit.hpp>\n#include <stan/math/prim/scal/fun/log1m.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * A Bernoulli random number generator which takes as its argument the\n     * often more convenient logit-parametrization.\n     * \n     * @tparam RNG Random number generator type.\n     * @param t logit-transformed probability parameter.\n     * @param rng pseudorandom number generator.\n     * @return Bernoulli(logit^{-1}(t)) generated random number, either 0 or 1.\n     */\n    template <class RNG>\n    inline int\n    bernoulli_logit_rng(double t, RNG& rng) {\n      using boost::variate_generator;\n      using boost::bernoulli_distribution;\n      using stan::math::inv_logit;\n\n      check_finite(\"bernoulli_logit_rng\",\n                   \"Logit transformed probability parameter\", t);\n\n      variate_generator<RNG&, bernoulli_distribution<> >\n        bernoulli_rng(rng, bernoulli_distribution<>(inv_logit(t)));\n      return bernoulli_rng();\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "3ef205cbe878ad5d03aa2d17cca60f4afce00a82", "size": 1590, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/bernoulli_logit_rng.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/bernoulli_logit_rng.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/prob/bernoulli_logit_rng.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5652173913, "max_line_length": 79, "alphanum_fraction": 0.7314465409, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5544398149989375}}
{"text": "#pragma once\n#include <Eigen/Eigen>\n\nclass XXZ\n{\nprivate:\n    uint32_t n_;\n    double J_;\n    double Delta_;\n\npublic:\n    XXZ(uint32_t n, double J, double Delta) : n_(n), J_(J), Delta_(Delta) { }\n\n    template<class State> typename State::T operator()(const State& smp) const\n    {\n        typename State::T s = 0.0;\n        // Nearest-neighbor\n        for(uint32_t i = 0; i < n_; i++)\n        {\n            int zz = smp.sigmaAt(i) * smp.sigmaAt((i + 1) % n_);\n            s += J_ * Delta_ * zz; // zz\n            s += J_ * (1 - zz) * smp.ratio(i, (i + 1) % n_); // xx+yy\n        }\n        return s;\n    }\n\n    std::map<uint32_t, double> operator()(uint32_t col) const;\n};\n", "meta": {"hexsha": "c0dd512351017cec95a4b82e4e59fb9b5585a2f7", "size": 673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/XXZ.hpp", "max_stars_repo_name": "cecri/ExactDiagonalization", "max_stars_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/XXZ.hpp", "max_issues_repo_name": "cecri/ExactDiagonalization", "max_issues_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/XXZ.hpp", "max_forks_repo_name": "cecri/ExactDiagonalization", "max_forks_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2068965517, "max_line_length": 78, "alphanum_fraction": 0.5185735513, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5544188547129644}}
{"text": "#include <Eigen/Core>\n#include <catch2/catch.hpp>\n\n#include <finitediff.hpp>\n\n#include <barrier/barrier.hpp>\n#include <utils/eigen_ext.hpp>\n\nusing namespace ipc;\nusing namespace ipc::rigid;\n\nTEST_CASE(\"Test barriers and their derivatives\", \"[opt][barrier]\")\n{\n    double s = GENERATE(range(-5, 2));\n    s = pow(10, s);\n\n    BarrierType barrier_type =\n        GENERATE(BarrierType::IPC, BarrierType::POLY_LOG, BarrierType::SPLINE);\n\n    double x = GENERATE_COPY(take(10, random(s / 2, 0.9 * s))); // \u2208 [0, s]\n    Vector1d x_vec;\n    x_vec << x;\n\n    Eigen::VectorXd fgrad(1);\n    fd::finite_gradient(\n        x_vec,\n        [&](const Eigen::VectorXd& x) {\n            return barrier(x[0], s, barrier_type);\n        },\n        fgrad);\n\n    Eigen::VectorXd grad(1);\n    grad << barrier_gradient(x, s, barrier_type);\n\n    CAPTURE(barrier_type, s, x, fgrad(0), grad(0));\n    CHECK(fd::compare_gradient(fgrad, grad));\n\n    fd::finite_gradient(\n        x_vec,\n        [&](const Eigen::VectorXd& x) {\n            return barrier_gradient(x[0], s, barrier_type);\n        },\n        fgrad);\n\n    grad << barrier_hessian(x, s, barrier_type);\n\n    CAPTURE(barrier_type, s, x, fgrad(0), grad(0));\n    CHECK(fd::compare_gradient(fgrad, grad));\n}\n", "meta": {"hexsha": "508a853578163efa46df6d9d0196cbaa1806dc17", "size": 1231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/barrier/test_barriers.cpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "tests/barrier/test_barriers.cpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "tests/barrier/test_barriers.cpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 24.62, "max_line_length": 79, "alphanum_fraction": 0.6100731113, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5544188515453089}}
{"text": "#pragma once\n\n#include <boost/random/random_number_generator.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\nnamespace calotypes\n{\n\t\ntemplate<class Engine>\nvoid FisherYatesShuffle( unsigned int numItems, std::vector<unsigned int>& inds, Engine& engine )\n{\n\tinds.resize( numItems );\n\tfor( unsigned int i = 0; i < numItems; i++ )\n\t{\n\t\tinds[i] = i;\n\t}\n\t\n\tunsigned int temp;\n\tfor( unsigned int i = numItems-1; i > 0; i-- )\n\t{\n\t\tboost::random::uniform_int_distribution<> dist( 0, i ); // i inclusive\n\t\tunsigned int j = (unsigned int) dist( engine );\n\t\ttemp = inds[j];\n\t\tinds[j] = inds[i];\n\t\tinds[i] = temp;\n\t}\n}\n\n} // end namespace calotypes\n", "meta": {"hexsha": "b200c7ec8436321c934bacd197c019bf4fb83d60", "size": 648, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/calotypes/Shufflers.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/Shufflers.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/Shufflers.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": 21.6, "max_line_length": 97, "alphanum_fraction": 0.6759259259, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.5543521946100416}}
{"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\u0142o si\u0119 zinterpretowa\u0107 wpisanych danych jako liczb\u0119!\";\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\u0142\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\u0142o si\u0119 zinterpretowa\u0107 wpisanych danych jako liczb\u0119!\";\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\u0142u musi by\u0107 mniejszy od prawego ko\u0144ca!\";\n        } else if (err == NO_REAL_ROOTS) {\n            throw \"Brak rozwi\u0105za\u0144 rzeczywistych w tym przedziale. Upewnij si\u0119, \u017ce 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\u017cna zbudowa\u0107 takiego przedzia\u0142u!\";\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\u0142u musi by\u0107 mniejszy od prawego ko\u0144ca!\";\n        } else if (err == NO_REAL_ROOTS) {\n            throw \"Mo\u017cliwy brak rozwi\u0105za\u0144 rzeczywistych w tym przedziale. Upewnij si\u0119, \u017ce 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": "\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <csim/init_ops.hpp>\n#include <csim/memory_ops.hpp>\n#include <csim/stat_ops.hpp>\n#include <csim/update_ops.hpp>\n#include <csim/update_ops_cpp.hpp>\n#include <string>\n\n#include \"../util/util.hpp\"\n\nvoid test_double_dense_matrix_gate(\n    std::function<void(UINT, UINT, const CTYPE*, CTYPE*, ITYPE)> func) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    std::vector<UINT> index_list;\n    for (UINT i = 0; i < n; ++i) index_list.push_back(i);\n\n    Eigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U, U2;\n    Eigen::Matrix<std::complex<double>, 4, 4, Eigen::RowMajor> Umerge;\n\n    UINT targets[2];\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n    Eigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        // two qubit dense matrix gate\n        U = get_eigen_matrix_random_single_qubit_unitary();\n        U2 = get_eigen_matrix_random_single_qubit_unitary();\n\n        std::random_shuffle(index_list.begin(), index_list.end());\n\n        targets[0] = index_list[0];\n        targets[1] = index_list[1];\n        Umerge = kronecker_product(U2, U);\n        // the below two lines are equivalent to the above two line\n        // UINT targets_rev[2] = { targets[1], targets[0] };\n        // Umerge = kronecker_product(U, U2);\n        test_state =\n            get_expanded_eigen_matrix_with_identity(targets[1], U2, n) *\n            get_expanded_eigen_matrix_with_identity(targets[0], U, n) *\n            test_state;\n        func(targets[0], targets[1], (CTYPE*)Umerge.data(), state, dim);\n        state_equal(state, test_state, dim, \"two-qubit separable dense gate\");\n    }\n\n    std::vector<std::pair<UINT, UINT>> test_pairs;\n    for (UINT i = 0; i < n; ++i) {\n        for (UINT j = 0; j < n; ++j) {\n            if (i == j) continue;\n            test_pairs.push_back(std::make_pair(i, j));\n        }\n    }\n    for (auto pair : test_pairs) {\n        // two qubit dense matrix gate\n        U = get_eigen_matrix_random_single_qubit_unitary();\n        U2 = get_eigen_matrix_random_single_qubit_unitary();\n\n        std::random_shuffle(index_list.begin(), index_list.end());\n        targets[0] = pair.first;\n        targets[1] = pair.second;\n        Umerge = kronecker_product(U2, U);\n        // the below two lines are equivalent to the above two line\n        // UINT targets_rev[2] = { targets[1], targets[0] };\n        // Umerge = kronecker_product(U, U2);\n        test_state =\n            get_expanded_eigen_matrix_with_identity(targets[1], U2, n) *\n            get_expanded_eigen_matrix_with_identity(targets[0], U, n) *\n            test_state;\n        func(targets[0], targets[1], (CTYPE*)Umerge.data(), state, dim);\n        state_equal(state, test_state, dim, \"two-qubit separable dense gate\");\n    }\n\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, TwoQubitDenseMatrixTest) {\n    test_double_dense_matrix_gate(double_qubit_dense_matrix_gate_c);\n    test_double_dense_matrix_gate(double_qubit_dense_matrix_gate_nosimd);\n#ifdef _USE_SIMD\n    test_double_dense_matrix_gate(double_qubit_dense_matrix_gate_simd);\n#endif\n}\n", "meta": {"hexsha": "6f363f93f35cc06d489c638ed80f4ee25531b2d4", "size": 3383, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/csim/test_update_dense_double.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": "test/csim/test_update_dense_double.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": "test/csim/test_update_dense_double.cpp", "max_forks_repo_name": "kodack64/qulacs-osaka", "max_forks_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-19T11:52:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T04:20:17.000Z", "avg_line_length": 35.9893617021, "max_line_length": 78, "alphanum_fraction": 0.6491279929, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5543118994687893}}
{"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\u6570\u636e\u52a0\u8f7d\u5931\u8d25\uff01\" << 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)); //\u6821\u6b63\u4e3b\u65b9\u5411\u95f4\u5782\u76f4\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 << \"\u7279\u5f81\u503cva(3x1):\\n\" << eigenValuesPCA << std::endl;\n    std::cout << \"\u7279\u5f81\u5411\u91cfve(3x3):\\n\" << eigenVectorsPCA << std::endl;\n    std::cout << \"\u8d28\u5fc3\u70b9(4x1):\\n\" << pcaCentroid << std::endl;\n    /*\n    // \u53e6\u4e00\u79cd\u8ba1\u7b97\u70b9\u4e91\u534f\u65b9\u5dee\u77e9\u9635\u7279\u5f81\u503c\u548c\u7279\u5f81\u5411\u91cf\u7684\u65b9\u5f0f:\u901a\u8fc7pcl\u4e2d\u7684pca\u63a5\u53e3\uff0c\u5982\u4e0b\uff0c\u8fd9\u79cd\u60c5\u51b5\u5f97\u5230\u7684\u7279\u5f81\u5411\u91cf\u76f8\u4f3c\u7279\u5f81\u5411\u91cf\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;//\u8ba1\u7b97\u7279\u5f81\u5411\u91cf\n    std::cerr << std::endl << \"EigenValues: \" << pca.getEigenValues() << std::endl;//\u8ba1\u7b97\u7279\u5f81\u503c\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 << \"\u53d8\u6362\u77e9\u9635tm(4x4):\\n\" << tm << std::endl;\n    std::cout << \"\u9006\u53d8\u77e9\u9635tm'(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 << \"\u578b\u5fc3c1(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;  //\u70b9\u4e91\u5e73\u5747\u5c3a\u5ea6\uff0c\u7528\u4e8e\u8bbe\u7f6e\u4e3b\u65b9\u5411\u7bad\u5934\u5927\u5c0f\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    //\u53d8\u6362\u5230\u539f\u70b9\u7684\u70b9\u4e91\u4e3b\u65b9\u5411\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    //\u521d\u59cb\u70b9\u4e91\u7684\u4e3b\u65b9\u5411\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>);//\u5b58\u653e\u53d8\u6362\u540e\u70b9\u4e91\u5305\u56f4\u76d2\u76846\u4e2a\u9876\u70b9\n\tpcl::PointCloud<PointType>::Ptr VertexCloud(new pcl::PointCloud<PointType>);//\u5b58\u653e\u539f\u6765\u70b9\u4e91\u4e2d\u5305\u56f4\u76d2\u76846\u4e2a\u9876\u70b9\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// \u9006\u53d8\u6362\u56de\u6765\u7684\u89d2\u5ea6\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 << \"\u8fd0\u884c\u65f6\u95f4\" << time.getTime() << \"ms\" << std::endl;\n \n    //visualization\n    pcl::visualization::PCLVisualizer viewer;\n    pcl::visualization::PointCloudColorHandlerCustom<PointType> tc_handler(transformedCloud, 0, 255, 0); //\u8bbe\u7f6e\u70b9\u4e91\u989c\u8272\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//         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_ELLIPTIC_FUNCTIONS_SCALAR_ELLINT_2_HPP_INCLUDED\n#define NT2_TOOLBOX_ELLIPTIC_FUNCTIONS_SCALAR_ELLINT_2_HPP_INCLUDED\n#include <nt2/toolbox/elliptic/functions/ellint_2.hpp>\n#include <nt2/include/constants/digits.hpp>\n#include <nt2/include/constants/real.hpp>\n#include <boost/math/special_functions/ellint_2.hpp>\n#include <nt2/toolbox/polynomials/functions/scalar/impl/horner.hpp>\n#include <nt2/include/functions/scalar/sqrt.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/oneminus.hpp>\n#include <nt2/sdk/error/policies.hpp>\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::ellint_2_, 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::ellint_2(result_type(a0));\n    }\n  };\n} }\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is double\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::ellint_2_, tag::cpu_\n                            , (A0)\n                            , (scalar_< floating_<A0> >)\n                            )\n  {\n\n    typedef typename meta::strip<A0>::type result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      result_type x = nt2::abs(a0);\n      if (x>One<A0>())    return Nan<A0>();\n      if (x == One<A0>()) return x;\n      return boost::math::ellint_2(a0, nt2_policy());\n    }\n  };\n} }\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is float\n/////////////////////////////////////////////////////////////////////////////\n// NT2_REGISTER_DISPATCH(tag::ellint_2_, tag::cpu_,\n//                           (A0),\n//                           (single_<A0>)\n//                          )\n\n// namespace nt2 { namespace ext\n// {\n//   template<class Dummy>\n//   struct call<tag::ellint_2_(tag::float_),\n//               tag::cpu_, Dummy> : callable\n//   {\n//     template<class Sig> struct result;\n//     template<class This,class A0>\n//     struct result<This(A0)> :\n//       meta::result_of<meta::floating(A0)>{};\n\n//     NT2_FUNCTOR_CALL(1)\n//     {\n//       A0 x = nt2::abs(a0);\n//       if (x>One<A0>()) return Nan<A0>();\n//       if (x == One<A0>()) return x;\n//       const A0 a = nt2::sqrt(oneminus(x));\n//       return horner< NT2_HORNER_COEFF_T(A0, 11,\n//                               (0x392102f5,\n//                                0x3b246c1b,\n//                                0x3c0e578f,\n//                                0x3c2fe240,\n//                                0x3bfebca9,\n//                                0x3bf882cf,\n//                                0x3c3d8b3f,\n//                                0x3cb2d89a,\n//                                0x3d68ac90,\n//                                0x3ee2e430,\n//                                0x3f800000) ) > (a)\n//                 -nt2::log(a)*a*horner< NT2_HORNER_COEFF_T(A0, 10,\n//                                     (0x38098de4,\n//                                      0x3a84557e,\n//                                      0x3bd53114,\n//                                      0x3c8a54f6,\n//                                      0x3cd67118,\n//                                      0x3d0925e1,\n//                                      0x3d2ef92b,\n//                                      0x3d6fffe9,\n//                                      0x3dc00000,\n//                                      0x3e800000\n//                                      ) ) > (a);\n//     }\n//   };\n// } }\n\n#endif\n", "meta": {"hexsha": "7b8e122d7fc4b464ea04bfb0fbd8f5c9401c014c", "size": 4491, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/elliptic/include/nt2/toolbox/elliptic/functions/scalar/ellint_2.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/elliptic/include/nt2/toolbox/elliptic/functions/scalar/ellint_2.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/elliptic/include/nt2/toolbox/elliptic/functions/scalar/ellint_2.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.425, "max_line_length": 80, "alphanum_fraction": 0.4126029837, "num_tokens": 1026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5543118874826944}}
{"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": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Tetrahedral_remeshing/Remeshing_triangulation_3.h>\n#include <CGAL/tetrahedral_remeshing.h>\n\n#include <CGAL/property_map.h>\n\n#include <boost/unordered_set.hpp>\n\n#include <iostream>\n#include <utility>\n\n#include \"tetrahedral_remeshing_generate_input.h\"\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n\ntypedef CGAL::Tetrahedral_remeshing::Remeshing_triangulation_3<K> Remeshing_triangulation;\n\ntypedef Remeshing_triangulation::Point         Point;\ntypedef Remeshing_triangulation::Vertex_handle Vertex_handle;\ntypedef Remeshing_triangulation::Cell_handle   Cell_handle;\ntypedef Remeshing_triangulation::Edge          Edge;\n\nclass Constrained_edges_property_map\n{\npublic:\n  typedef bool                               value_type;\n  typedef bool                               reference;\n  typedef std::pair<Vertex_handle, Vertex_handle> key_type;\n  typedef boost::read_write_property_map_tag category;\n\nprivate:\n  boost::unordered_set<key_type>* m_set_ptr;\n\npublic:\n  Constrained_edges_property_map()\n    : m_set_ptr(NULL)\n  {}\n  Constrained_edges_property_map(boost::unordered_set<key_type>* set_)\n    : m_set_ptr(set_)\n  {}\n\npublic:\n  friend void put(Constrained_edges_property_map& map,\n                  const key_type& k,\n                  const bool b)\n  {\n    CGAL_assertion(map.m_set_ptr != NULL);\n    CGAL_assertion(k.first < k.second);\n    if (b)  map.m_set_ptr->insert(k);\n    else    map.m_set_ptr->erase(k);\n  }\n\n  friend value_type get(const Constrained_edges_property_map& map,\n                              const key_type& k)\n  {\n    CGAL_assertion(map.m_set_ptr != NULL);\n    CGAL_assertion(k.first < k.second);\n    return (map.m_set_ptr->count(k) > 0);\n  }\n};\n\nvoid set_subdomain(Remeshing_triangulation& tr, const int index)\n{\n  for (Remeshing_triangulation::Finite_cells_iterator cit = tr.finite_cells_begin();\n       cit != tr.finite_cells_end(); ++cit)\n  {\n    cit->set_subdomain_index(index);\n  }\n}\n\nint main(int argc, char* argv[])\n{\n  const double target_edge_length = (argc > 1) ? atof(argv[1]) : 0.02;\n  const int nb_iter = (argc > 2) ? atoi(argv[2]) : 1;\n  const int nbv = (argc > 3) ? atoi(argv[3]) : 500;\n\n  Remeshing_triangulation t3;\n  boost::unordered_set<std::pair<Vertex_handle, Vertex_handle> > constraints;\n\n  CGAL::Tetrahedral_remeshing::generate_input_cube(nbv, t3, constraints);\n  make_constraints_from_cube_edges(t3, constraints);\n  CGAL_assertion(t3.is_valid());\n\n  CGAL::tetrahedral_isotropic_remeshing(t3, target_edge_length,\n    CGAL::parameters::edge_is_constrained_map(\n      Constrained_edges_property_map(&constraints))\n    .number_of_iterations(nb_iter));\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "9135cf65a15ff42cde54c7d8f896ded84fe2962c", "size": 2723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tetrahedral_remeshing/examples/Tetrahedral_remeshing/tetrahedral_remeshing_with_features.cpp", "max_stars_repo_name": "gaschler/cgal", "max_stars_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T09:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T05:00:23.000Z", "max_issues_repo_path": "Tetrahedral_remeshing/examples/Tetrahedral_remeshing/tetrahedral_remeshing_with_features.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": "Tetrahedral_remeshing/examples/Tetrahedral_remeshing/tetrahedral_remeshing_with_features.cpp", "max_forks_repo_name": "gaschler/cgal", "max_forks_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-05T04:18:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:18:59.000Z", "avg_line_length": 29.2795698925, "max_line_length": 90, "alphanum_fraction": 0.7212633125, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5542935816426525}}
{"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": "#pragma once\n\n#ifdef NOOB_PLATFORM_LINUX\n#undef Success\n#endif\n\n#include <Eigen/Geometry>\n#include \"vec3.hpp\"\n\nnamespace noob\n{\n\ttemplate <typename T>\n\tclass plane\n\t{\n\t\tpublic:\n\t\t\tvoid through(noob::vec3_type<T>& a, const noob::vec3_type<T>& b, const noob::vec3_type<T>& c)\n\t\t\t{\n\t\t\t\tinner = Eigen::Hyperplane<float, 3>::Through(Eigen::Vector3f(b.v[0], b.v[1], b.v[2]), Eigen::Vector3f(c.v[0], c.v[1], c.v[2]));\n\t\t\t}\n\n\t\t\tvoid normalize()\n\t\t\t{\n\t\t\t\tinner.normalize();\n\t\t\t}\n\n\t\t\tfloat signed_distance(const noob::vec3_type<T>& p) const\n\t\t\t{\n\t\t\t\treturn inner.signedDistance(Eigen::Vector3f(p.v[0], p.v[1], p.v[2]));\n\t\t\t}\n\n\t\t\tnoob::vec3_type<T> normal() const\n\t\t\t{\n\t\t\t\treturn vec3_from_eigen_vec3(inner.normal());\n\t\t\t}\n\n\t\t\tfloat offset() const\n\t\t\t{\n\t\t\t\treturn inner.offset();\n\t\t\t}\n\n\t\t\tnoob::vec3_type<T> projection(const noob::vec3_type<T>& p) const\n\t\t\t{\n\t\t\t\treturn vec3_from_eigen_vec3(inner.projection(Eigen::Vector3f(p.v[0], p.v[1], p.v[2])));\n\t\t\t}\n\n\n\t\tprotected:\n\t\t\tEigen::Hyperplane<T, 3> inner;\n\t};\n}\n", "meta": {"hexsha": "bb3ed13ed5317d933f2730a2dc9e4010cb6b20d1", "size": 1000, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "engine/lib/math-funcs/include/noob/math/plane.hpp", "max_stars_repo_name": "ColinGilbert/noobwerkz-engine", "max_stars_repo_head_hexsha": "f5670e98ca0dada8865be9ab82d25d3acf549ebe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-03-02T10:56:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T03:32:49.000Z", "max_issues_repo_path": "engine/lib/math-funcs/include/noob/math/plane.hpp", "max_issues_repo_name": "ColinGilbert/noobwerkz-engine-borked", "max_issues_repo_head_hexsha": "f5670e98ca0dada8865be9ab82d25d3acf549ebe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 73.0, "max_issues_repo_issues_event_min_datetime": "2015-04-14T09:39:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-11T21:49:10.000Z", "max_forks_repo_path": "engine/lib/math-funcs/include/noob/math/plane.hpp", "max_forks_repo_name": "ColinGilbert/noobwerkz-engine-borked", "max_forks_repo_head_hexsha": "f5670e98ca0dada8865be9ab82d25d3acf549ebe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-22T01:29:32.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-02T06:07:12.000Z", "avg_line_length": 19.6078431373, "max_line_length": 131, "alphanum_fraction": 0.631, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782012, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5542935668025485}}
{"text": "\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/multi/geometries/multi_point.hpp>\n\n#include <iostream>\n#include <vector>\n\n#include \"mesh.h\"\n#include \"component.h\"\n#include \"vertex.h\"\n\nvoid Mesh::createHull(int c_num)\n{\n\n\n\tusing boost::geometry::append;\n\tusing boost::geometry::make;\n\tusing boost::geometry::model::d2::point_xy;\n\n\tboost::geometry::model::multi_point<point_xy<dReal> > pointset;\n\n\tfor (int i = 0; i < components.at(c_num)->faces.size(); i++)\n\t{\n\t\tfor (std::vector<int>::iterator vertIter = components.at(c_num)->faces.at(i)->vertices.begin(); vertIter != components.at(c_num)->faces.at(i)->vertices.end(); vertIter++)\n\t\t{\n\t\t\tappend(pointset, make<point_xy<dReal> >(vertexPalette.at(*vertIter)->pos.x, vertexPalette.at(*vertIter)->pos.y));\n\t\t}\n\t}\n\n\tboost::geometry::model::multi_point<point_xy<dReal> > hull;\n\tboost::geometry::convex_hull(pointset, hull);\n\n\tfor (std::vector<point_xy<dReal> >::size_type i = 0; i < hull.size(); i++)\n\t{\n\t\tcomponents.at(c_num)->hull.push_back(std::make_pair(boost::geometry::get<0>(hull[i]), boost::geometry::get<1>(hull[i])));\n\t}\n\n\n}\n", "meta": {"hexsha": "4da00025d02c6016049b4ae806c28fd07ea05119", "size": 1139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mesh.cpp", "max_stars_repo_name": "mfirmin/c5sc", "max_stars_repo_head_hexsha": "66b06061bf0f1a53c435f4109cd7fa636466c353", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T07:49:33.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-05T07:49:33.000Z", "max_issues_repo_path": "src/mesh.cpp", "max_issues_repo_name": "mfirmin/c5sc", "max_issues_repo_head_hexsha": "66b06061bf0f1a53c435f4109cd7fa636466c353", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mesh.cpp", "max_forks_repo_name": "mfirmin/c5sc", "max_forks_repo_head_hexsha": "66b06061bf0f1a53c435f4109cd7fa636466c353", "max_forks_repo_licenses": ["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.7804878049, "max_line_length": 172, "alphanum_fraction": 0.6979806848, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5542935549278087}}
{"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); // \u3053\u3061\u3089\u306f\u66f4\u65b0\u3055\u308c\u308b->grads\u306b\u3088\u308b\u66f4\u65b0\u304c\u304a\u304b\u3057\u3044\uff1f\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); // \u3053\u3061\u3089\u306f\u66f4\u65b0\u3055\u308c\u308b->grads\u306b\u3088\u308b\u66f4\u65b0\u304c\u304a\u304b\u3057\u3044\uff1f\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": "// 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// test_dist_overloads.cpp\r\n\r\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\r\n#include <boost/math/distributions/normal.hpp>\r\n    using boost::math::normal_distribution;\r\n\r\n#include <boost/test/test_exec_monitor.hpp> // Boost.Test\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\n#include <iostream>\r\n   using std::cout;\r\n   using std::endl;\r\n   using std::setprecision;\r\n\r\ntemplate <class RealType>\r\nvoid test_spots(RealType)\r\n{\r\n   // Basic sanity checks,\r\n   // 2 eps as a percentage:\r\n   RealType tolerance = boost::math::tools::epsilon<RealType>() * 2 * 100;\r\n\r\n   cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \" %\" << endl;\r\n\r\n   for(int i = -4; i <= 4; ++i)\r\n   {\r\n      BOOST_CHECK_CLOSE(\r\n         ::boost::math::cdf(normal_distribution<RealType>(), i),\r\n         ::boost::math::cdf(normal_distribution<RealType>(), static_cast<RealType>(i)),\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(\r\n         ::boost::math::pdf(normal_distribution<RealType>(), i),\r\n         ::boost::math::pdf(normal_distribution<RealType>(), static_cast<RealType>(i)),\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(\r\n         ::boost::math::cdf(complement(normal_distribution<RealType>(), i)),\r\n         ::boost::math::cdf(complement(normal_distribution<RealType>(), static_cast<RealType>(i))),\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(\r\n         ::boost::math::hazard(normal_distribution<RealType>(), i),\r\n         ::boost::math::hazard(normal_distribution<RealType>(), static_cast<RealType>(i)),\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(\r\n         ::boost::math::chf(normal_distribution<RealType>(), i),\r\n         ::boost::math::chf(normal_distribution<RealType>(), static_cast<RealType>(i)),\r\n         tolerance);\r\n   }\r\n   for(float f = 0.01f; f < 1; f += 0.01f)\r\n   {\r\n      BOOST_CHECK_CLOSE(\r\n         ::boost::math::quantile(normal_distribution<RealType>(), f),\r\n         ::boost::math::quantile(normal_distribution<RealType>(), static_cast<RealType>(f)),\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(\r\n         ::boost::math::quantile(complement(normal_distribution<RealType>(), f)),\r\n         ::boost::math::quantile(complement(normal_distribution<RealType>(), static_cast<RealType>(f))),\r\n         tolerance);\r\n   }\r\n} // template <class RealType>void test_spots(RealType)\r\n\r\nint test_main(int, char* [])\r\n{\r\n    // Basic sanity-check spot values.\r\n   // (Parameter value, arbitrarily zero, only communicates the floating point type).\r\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %\r\n  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n  test_spots(0.0L); // Test long double.\r\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\r\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\r\n#endif\r\n#else\r\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\r\n      \"either because the long double overloads of the usual math functions are \"\r\n      \"not available at all, or because they are too inaccurate for these tests \"\r\n      \"to pass.</note>\" << std::cout;\r\n#endif\r\n\r\n   return 0;\r\n} // int test_main(int, char* [])\r\n\r\n/*\r\n\r\nOutput:\r\n\r\nRunning 1 test case...\r\nTolerance for type float is 2.38419e-005 %\r\nTolerance for type double is 4.44089e-014 %\r\nTolerance for type long double is 4.44089e-014 %\r\nTolerance for type class boost::math::concepts::real_concept is 4.44089e-014 %\r\n*** No errors detected\r\n\r\n*/\r\n\r\n", "meta": {"hexsha": "2414f3cfff5172484c3b8def1c98488dd51c9bab", "size": 3821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_dist_overloads.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/math/test/test_dist_overloads.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": 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/test/test_dist_overloads.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": 37.4607843137, "max_line_length": 105, "alphanum_fraction": 0.6571578121, "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.5542932798781225}}
{"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": "#ifndef MOCHIMOCHI_ADAGRAD_RDA_HPP_\n#define MOCHIMOCHI_ADAGRAD_RDA_HPP_\n\n#include <Eigen/Dense>\n#include \"../../functions/enumerate.hpp\"\n\nclass ADAGRAD_RDA {\nprivate :\n  const std::size_t kDim;\n  const double kEta;\n  const double kLambda;\n\nprivate :\n  std::size_t _timestep;\n  Eigen::VectorXd _w;\n  Eigen::VectorXd _h;\n  Eigen::VectorXd _g;\n\npublic :\n  ADAGRAD_RDA(const std::size_t dim, const double eta, const double lambda)\n    : kDim(dim),\n      kEta(eta),\n      kLambda(lambda),\n      _timestep(0),\n      _w(Eigen::VectorXd::Zero(kDim)),\n      _h(Eigen::VectorXd::Zero(kDim)),\n      _g(Eigen::VectorXd::Zero(kDim)) {\n    static_assert(std::numeric_limits<decltype(dim)>::max() > 0, \"Dimension Error. (Dimension > 0)\");\n    static_assert(std::numeric_limits<decltype(eta)>::max() > 0, \"Hyper Parameter Error. (eta > 0)\");\n    static_assert(std::numeric_limits<decltype(lambda)>::max() > 0, \"Hyper Parameter Error. (lambda > 0)\");\n    assert(dim > 0);\n    assert(eta > 0);\n    assert(lambda > 0);\n  }\n\n  virtual ~ADAGRAD_RDA() { }\n\nprivate :\n\n  double calculate_margin(const Eigen::VectorXd& x) const {\n    return _w.dot(x);\n  }\n\n  double suffer_loss(const Eigen::VectorXd& x, const int y) const {\n    return std::max(0.0, 1.0 - y * _w.dot(x));\n  }\n\npublic :\n\n  bool update(const Eigen::VectorXd& feature, const int label) {\n    if (suffer_loss(feature, label) <= 0.0) { return false; }\n\n    _timestep++;\n    functions::enumerate(feature.data(), feature.data() + feature.size(), 0,\n                       [&](const int index, const double value) {\n                         const auto gradiant = -label * value;\n                         _g[index] += gradiant;\n                         _h[index] += gradiant * gradiant;\n\n                         const auto sign = _g[index] >= 0 ? 1 : -1;\n                         const auto eta = kEta / std::sqrt(_h[index]);\n                         const auto u = std::abs(_g[index]) / _timestep;\n\n                         _w[index] = (u <= kLambda) ? 0.0 : -sign * eta * _timestep * (u - kLambda);\n                       });\n    return true;\n  }\n\n  int predict(const Eigen::VectorXd& x) const {\n    return calculate_margin(x) > 0.0 ? 1 : -1;\n  }\n\n};\n\n#endif //MOCHIMOCHI_ADAGRAD_RDA_HPP_\n", "meta": {"hexsha": "26079b01752cd0b1e627a0d11c61198d2427e849", "size": 2226, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mochimochi/classifier/binary/adagrad_rda.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/adagrad_rda.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/adagrad_rda.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": 29.2894736842, "max_line_length": 107, "alphanum_fraction": 0.5849056604, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5542932647465068}}
{"text": "#include <iostream>\n#include <stdio.h>\n#include <opencv_workbench/cluster/RTree.h>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n\n#include <boost/geometry/index/rtree.hpp>\n\n// to store queries results\n#include <vector>\n#include <boost/foreach.hpp>\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\n//\n// Test.cpp\n//\n// This is a direct port of the C version of the RTree test program.\n//\n\nusing namespace std;\n\n// From: https://github.com/nushoin/RTree\n\ntypedef int ValueType;\n\nstruct Rect\n{\n     Rect()  {}\n\n     Rect(int a_minX, int a_minY, int a_maxX, int a_maxY)\n          {\n               min[0] = a_minX;\n               min[1] = a_minY;\n\n               max[0] = a_maxX;\n               max[1] = a_maxY;\n          }\n\n\n     int min[2];\n     int max[2];\n};\n\nstruct Rect rects[] =\n{\n     Rect(0, 0, 2, 2), // xmin, ymin, xmax, ymax (for 2 dimensional RTree)\n     Rect(5, 5, 7, 7),\n     Rect(8, 5, 9, 6),\n     Rect(7, 1, 9, 2),\n};\n\nint nrects = sizeof(rects) / sizeof(rects[0]);\n\nRect search_rect(6, 4, 10, 6); // search will find above rects that this one overlaps\n\n\nbool MySearchCallback(ValueType id, void* arg)\n{\n     cout << \"Hit data rect \" << id << \"\\n\";\n     return true; // keep going\n}\n\n\nint main()\n{\n     ////////////////\n     // RTree.h Example\n     ////////////////\n     typedef RTree<ValueType, int, 2, float> MyTree;\n     MyTree tree;\n\n     int i, nhits;\n     cout << \"nrects = \" << nrects << \"\\n\";\n\n     for(i=0; i<nrects; i++) {\n          tree.Insert(rects[i].min, rects[i].max, i); // Note, all values including zero are fine in this version\n     }\n\n     nhits = tree.Search(search_rect.min, search_rect.max, MySearchCallback, NULL);\n\n     cout << \"Search resulted in \" << nhits << \" hits\\n\";\n\n     // Iterator test\n     int itIndex = 0;\n     MyTree::Iterator it;\n     for( tree.GetFirst(it);\n          !tree.IsNull(it);\n          tree.GetNext(it) ) {\n          int value = tree.GetAt(it);\n\n          int boundsMin[2] = {0,0};\n          int boundsMax[2] = {0,0};\n          it.GetBounds(boundsMin, boundsMax);\n          cout << \"it[\" << itIndex++ << \"] \" << value << \" = (\" << boundsMin[0] << \",\" << boundsMin[1] << \",\" << boundsMax[0] << \",\" << boundsMax[1] << \")\\n\";\n     }\n\n     // Iterator test, alternate syntax\n     itIndex = 0;\n     tree.GetFirst(it);\n     while( !it.IsNull() )\n     {\n          int value = *it;\n          ++it;\n          cout << \"it[\" << itIndex++ << \"] \" << value << \"\\n\";\n     }     \n\n     // Output:\n     //\n     // nrects = 4\n     // Hit data rect 1\n     // Hit data rect 2\n     // Search resulted in 2 hits\n     // it[0] 0 = (0,0,2,2)\n     // it[1] 1 = (5,5,7,7)\n     // it[2] 2 = (8,5,9,6)\n     // it[3] 3 = (7,1,9,2)\n     // it[0] 0\n     // it[1] 1\n     // it[2] 2\n     // it[3] 3\n\n     cout << \"===================================\" << endl;\n     \n     ////////////////////\n     // Boost RTree\n     ////////////////////\n     typedef bg::model::point<float, 2, bg::cs::cartesian> point;\n     typedef bg::model::box<point> box;\n     typedef std::pair<box, unsigned> value;\n\n     // create the rtree using default constructor\n     //bgi::rtree< value, bgi::quadratic<16> > rtree; // max elements is 16\n     //bgi::rtree< value, bgi::quadratic<16> > rtree; // max elements is 16\n     // rstar\n     bgi::rtree<value, bgi::dynamic_rstar> rtree(bgi::dynamic_rstar(16));\n     \n     // create some values\n     for ( unsigned i = 0 ; i < 10 ; ++i ) {\n          // create a box\n          box b(point(i + 0.0f, i + 0.0f), point(i + 0.5f, i + 0.5f));\n          // insert new value\n          rtree.insert(std::make_pair(b, i));\n     }\n\n     // find values intersecting some area defined by a box\n     box query_box(point(0, 0), point(5, 5));\n     std::vector<value> result_s;\n     rtree.query(bgi::intersects(query_box), std::back_inserter(result_s));\n\n     // find 5 nearest values to a point\n     std::vector<value> result_n;\n     rtree.query(bgi::nearest(point(0, 0), 5), std::back_inserter(result_n));\n\n     // display results\n     std::cout << \"spatial query box:\" << std::endl;\n     std::cout << bg::wkt<box>(query_box) << std::endl;\n     std::cout << \"spatial query result:\" << std::endl;\n     BOOST_FOREACH(value const& v, result_s)\n          std::cout << bg::wkt<box>(v.first) << \" - \" << v.second << std::endl;\n\n     std::cout << \"knn query point:\" << std::endl;\n     std::cout << bg::wkt<point>(point(0, 0)) << std::endl;\n     std::cout << \"knn query result:\" << std::endl;\n     BOOST_FOREACH(value const& v, result_n)\n          std::cout << bg::wkt<box>(v.first) << \" - \" << v.second << std::endl;\n\n     return 0;\n}\n", "meta": {"hexsha": "c0437ba937d6e70223e7bb01b7ffbd2f808b2a58", "size": 4664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "share/rtree-test/main.cpp", "max_stars_repo_name": "SyllogismRXS/opencv-workbench", "max_stars_repo_head_hexsha": "2fb5b0d67589642d438f21f1cf58aaa761d15757", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-10-05T04:33:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-20T02:47:36.000Z", "max_issues_repo_path": "share/rtree-test/main.cpp", "max_issues_repo_name": "SyllogismRXS/opencv-workbench", "max_issues_repo_head_hexsha": "2fb5b0d67589642d438f21f1cf58aaa761d15757", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "share/rtree-test/main.cpp", "max_forks_repo_name": "SyllogismRXS/opencv-workbench", "max_forks_repo_head_hexsha": "2fb5b0d67589642d438f21f1cf58aaa761d15757", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2015-07-18T16:01:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T11:56:02.000Z", "avg_line_length": 26.9595375723, "max_line_length": 158, "alphanum_fraction": 0.5306603774, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5542932635932162}}
{"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#include <gtest/gtest.h>\n#include \"../util/util.h\"\n#include <Eigen/Core>\n#include <string>\n#include <algorithm>\n\n#ifndef _MSC_VER\nextern \"C\" {\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#include <csim/update_ops.h>\n#include <csim/init_ops.h>\n}\n#else\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#include <csim/update_ops.h>\n#include <csim/init_ops.h>\n#endif\n\nTEST(UpdateTest, MultiQubitDiagonalMatrixTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tstd::vector<UINT> index_list;\n\tfor (UINT i = 0; i < n; ++i) index_list.push_back(i);\n\n\tEigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U1, U2, U3;\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\tfor (UINT gate_size = 1; gate_size <= 1; ++gate_size) {\n\t\tITYPE gate_dim = (1ULL) << gate_size;\n\t\tfor (UINT r = 0; r < max_repeat; ++r) {\n\t\t\tstd::random_shuffle(index_list.begin(), index_list.end());\n\t\t\tauto diag = get_eigen_diagonal_matrix_random_multi_qubit_unitary(gate_size);\n\t\t\tEigen::MatrixXcd matrix = Eigen::MatrixXcd::Zero(dim, dim);\n\t\t\tfor (ITYPE i = 0; i < dim; ++i) {\n\t\t\t\tUINT ti = 0;\n\t\t\t\tfor (int j = 0; j < gate_size; ++j) {\n\t\t\t\t\tUINT gi = index_list[j];\n\t\t\t\t\tti += ((i >> gi) % 2) * (1 << j);\n\t\t\t\t}\n\t\t\t\tmatrix(i, i) = diag[ti];\n\t\t\t}\n\t\t\t//std::cout << test_state << std::endl;\n\t\t\t//std::cout << diag << std::endl;\n\t\t\t//std::cout << matrix << std::endl;\n\t\t\tmulti_qubit_diagonal_matrix_gate(index_list.data(), gate_size, (CTYPE*)diag.data(), state, dim);\n\t\t\ttest_state = matrix * test_state;\n\t\t\tstate_equal(state, test_state, dim, \"diagonal gate\");\n\t\t}\n\t}\n\trelease_quantum_state(state);\n}\n\n\nTEST(UpdateTest, MultiQubitDiagonalMatrixTest2) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tstd::vector<UINT> index_list;\n\tfor (UINT i = 0; i < n; ++i) index_list.push_back(i);\n\n\tEigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U1, U2, U3;\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\tfor (UINT gate_size = 1; gate_size <= 1; ++gate_size) {\n\t\tITYPE gate_dim = (1ULL) << gate_size;\n\t\tfor (UINT r = 0; r < max_repeat; ++r) {\n\t\t\tstd::random_shuffle(index_list.begin(), index_list.end());\n\t\t\tauto diag = get_eigen_diagonal_matrix_random_multi_qubit_unitary(gate_size);\n\t\t\tEigen::MatrixXcd matrix = Eigen::MatrixXcd::Zero(dim, dim);\n\t\t\tfor (ITYPE i = 0; i < dim; ++i) {\n\t\t\t\tUINT ti = 0;\n\t\t\t\tfor (int j = 0; j < gate_size; ++j) {\n\t\t\t\t\tUINT gi = index_list[j];\n\t\t\t\t\tti += ((i >> gi) % 2) * (1 << j);\n\t\t\t\t}\n\t\t\t\tmatrix(i, i) = diag[ti];\n\t\t\t}\n\t\t\t//std::cout << test_state << std::endl;\n\t\t\t//std::cout << diag << std::endl;\n\t\t\t//std::cout << matrix << std::endl;\n\t\t\tmulti_qubit_control_multi_qubit_diagonal_matrix_gate({}, {}, 0, index_list.data(), gate_size, (CTYPE*)diag.data(), state, dim);\n\t\t\ttest_state = matrix * test_state;\n\t\t\tstate_equal(state, test_state, dim, \"diagonal gate\");\n\t\t}\n\t}\n\trelease_quantum_state(state);\n}\n\n\n\n\nTEST(UpdateTest, TwoQubitControlTwoQubitDiagonalMatrixTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tstd::vector<UINT> index_list;\n\tfor (UINT i = 0; i < n; ++i) index_list.push_back(i);\n\n\tEigen::MatrixXcd P0(2, 2), P1(2, 2);\n\tP0 << 1, 0, 0, 0;\n\tP1 << 0, 0, 0, 1;\n\n\tEigen::VectorXcd d, d2;\n\n\tUINT targets[2], controls[2], mvalues[2];\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\tEigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\n\t\t// two qubit control-11 two qubit gate\n\t\td = get_eigen_diagonal_matrix_random_multi_qubit_unitary(1);\n\t\td2 = get_eigen_diagonal_matrix_random_multi_qubit_unitary(1);\n\t\tstd::random_shuffle(index_list.begin(), index_list.end());\n\t\ttargets[0] = index_list[0];\n\t\ttargets[1] = index_list[1];\n\t\tcontrols[0] = index_list[2];\n\t\tcontrols[1] = index_list[3];\n\n\t\tmvalues[0] = 1; mvalues[1] = 1;\n\t\tEigen::Vector4cd dmerge;\n\t\tdmerge(0) = d[0] * d2[0];\n\t\tdmerge(1) = d[1] * d2[0];\n\t\tdmerge(2) = d[0] * d2[1];\n\t\tdmerge(3) = d[1] * d2[1];\n\t\tmulti_qubit_control_multi_qubit_diagonal_matrix_gate(controls, mvalues, 2, targets, 2, (CTYPE*)dmerge.data(), state, dim);\n\n\t\tEigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U, U2;\n\t\tU(0, 0) = d[0]; U(1, 1) = d[1]; U(0, 1) = 0; U(1, 0) = 0;\n\t\tU2(0, 0) = d2[0]; U2(1, 1) = d2[1]; U2(0, 1) = 0; U2(1, 0) = 0;\n\n\t\ttest_state = (\n\t\t\tget_expanded_eigen_matrix_with_identity(controls[0], P0, n)*get_expanded_eigen_matrix_with_identity(controls[1], P0, n) +\n\t\t\tget_expanded_eigen_matrix_with_identity(controls[0], P0, n)*get_expanded_eigen_matrix_with_identity(controls[1], P1, n) +\n\t\t\tget_expanded_eigen_matrix_with_identity(controls[0], P1, n)*get_expanded_eigen_matrix_with_identity(controls[1], P0, n) +\n\t\t\tget_expanded_eigen_matrix_with_identity(controls[0], P1, n)*get_expanded_eigen_matrix_with_identity(controls[1], P1, n)*get_expanded_eigen_matrix_with_identity(targets[0], U, n)*get_expanded_eigen_matrix_with_identity(targets[1], U2, n)\n\t\t\t) * test_state;\n\t\tstate_equal(state, test_state, dim, \"two qubit control two qubit diagonal gate\");\n\t}\n\trelease_quantum_state(state);\n}\n", "meta": {"hexsha": "ab947fec0b3127b920f7ae0ef7cd27d606ff9782", "size": 5527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/csim/test_update_diagonal_multi.cpp", "max_stars_repo_name": "kamakiri01/qulacs", "max_stars_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 260.0, "max_stars_repo_stars_event_min_datetime": "2018-10-13T15:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T11:03:58.000Z", "max_issues_repo_path": "test/csim/test_update_diagonal_multi.cpp", "max_issues_repo_name": "kamakiri01/qulacs", "max_issues_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 182.0, "max_issues_repo_issues_event_min_datetime": "2018-10-14T02:29:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:23:18.000Z", "max_forks_repo_path": "test/csim/test_update_diagonal_multi.cpp", "max_forks_repo_name": "kamakiri01/qulacs", "max_forks_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 88.0, "max_forks_repo_forks_event_min_datetime": "2018-10-10T03:46:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T21:56:05.000Z", "avg_line_length": 34.1172839506, "max_line_length": 239, "alphanum_fraction": 0.6694409264, "num_tokens": 1871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5542727468273896}}
{"text": "/*\n * Copyright 2017 \u00a9 Centre Interdisciplinaire de d\u00e9veloppement en Cartographie des Oc\u00e9ans (CIDCO), Tous droits r\u00e9serv\u00e9s\n */\n\n/* \n * File:   GeoreferencingTest.hpp\n * Author: glm, jordan\n */\n\n#ifndef GEOREFERENCINGTEST_HPP\n#define GEOREFERENCINGTEST_HPP\n\n\n#include \"catch.hpp\"\n#include <Eigen/Dense>\n#include \"../src/Position.hpp\"\n#include \"../src/georeferencing/Georeferencing.hpp\"\n#include \"../src/math/Boresight.hpp\"\n#include \"../src/math/CoordinateTransform.hpp\"\n#include \"../src/utils/Constants.hpp\"\n#include \"../src/svp/SoundVelocityProfileFactory.hpp\"\n#include \"../src/svp/CarisSvpFile.hpp\"\n\n#define POSITION_PRECISION 0.00000001\n\n\n\nTEST_CASE(\"Georeferencing LGF test\") {\n\n    GeoreferencingLGF georef;\n\n    /*Build centroid position*/\n    double latitudeCentroidDegrees = 0.859286627204 * R2D;\n    double longitudeCentroidDegrees = -1.189078930041 * R2D;\n    double ellipsoidalCentroidHeight = -25.711914675768;\n    Position positionCentroid(0, latitudeCentroidDegrees, longitudeCentroidDegrees, ellipsoidalCentroidHeight);\n\n    georef.setCentroid(positionCentroid);\n\n\n    /*Build attitude*/\n    double rollDegrees = 0.0273983876 * R2D; // roll at receive\n    double pitchDegrees = 0.0243184966 * R2D; // pitch at transmit\n    double headingDegrees = 0.1056083942 * R2D; // heading at transmit\n    Attitude attitude(0, rollDegrees, pitchDegrees, headingDegrees);\n\n    /*Build Position*/\n    double latitudeDegrees = 0.859282504615 * R2D;\n    double longitudeDegrees = -1.189079133235 * R2D;\n    double ellipsoidalHeight = -25.753195024025;\n    Position position(0, latitudeDegrees, longitudeDegrees, ellipsoidalHeight);\n\n    /*Build Ping*/\n    uint64_t microEpoch = 0;\n    long id = 0;\n    uint32_t quality = 0;\n    double intensity = 0;\n    double surfaceSoundSpeed = 1446.4250488;\n    double twoWayTravelTime = 0.0091418369 * 2;\n    double alongTrackAngle = 0.0;\n    double acrossTrackAngle = 0.7031931281 * R2D;\n\n    Ping ping(\n            microEpoch,\n            id,\n            quality,\n            intensity,\n            surfaceSoundSpeed,\n            twoWayTravelTime,\n            alongTrackAngle,\n            acrossTrackAngle\n            );\n\n    /*Obtain svp*/\n    std::string svpFilePath = \"test/data/rayTracingTestData/SVP-0.svp\";\n    CarisSvpFile svps;\n    svps.readSvpFile(svpFilePath);\n    SoundVelocityProfile * svp = svps.getSvps()[0];\n\n\n    Eigen::Vector3d leverArm;\n    leverArm << 0.0, 0.0, 0.0;\n\n    /*Build Boresight Matrix*/\n    double rollBoresightDegrees = 0.62;\n    double pitchBoresightDegrees = 0.0;\n    double headingBoresightDegrees = 0.0;\n    Attitude boresightAngles(0, rollBoresightDegrees, pitchBoresightDegrees, headingBoresightDegrees);\n    Eigen::Matrix3d boresightMatrix;\n    Boresight::buildMatrix(boresightMatrix, boresightAngles);\n\n    /*Perform georeferencing in LGF*/\n    Eigen::Vector3d georeferencedPing;\n    georef.georeference(georeferencedPing, attitude, position, ping, *svp, leverArm, boresightMatrix);\n\n    Eigen::Vector3d expectedGeoreferencedPing;\n    expectedGeoreferencedPing << -26.8825997032, 7.3549385469, 10.4758625062;\n\n    double georefTestTreshold = 2e-2; // 2cm\n    REQUIRE(std::abs(expectedGeoreferencedPing(0) - georeferencedPing(0)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeoreferencedPing(1) - georeferencedPing(1)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeoreferencedPing(2) - georeferencedPing(2)) < georefTestTreshold);\n}\n\nTEST_CASE(\"Georeference TRF with position and downward ping only\") {\n    Eigen::Vector3d georefedPing;\n\n    Attitude attitude(0, 0, 0, 0);\n    Position position(0, 48.4525, -68.5232, 15.401);\n    Ping ping(0, 0, 0, 0, 0, 0.01, 0.0, 0.0);\n    SoundVelocityProfile * svp = SoundVelocityProfileFactory::buildFreshWaterModel();\n    ping.setSurfaceSoundSpeed(svp->getSpeeds()(0)); //important now that raytracing uses it\n    Eigen::Vector3d leverArm(0, 0, 0);\n    Eigen::Matrix3d boresight = Eigen::Matrix3d::Identity();\n\n    GeoreferencingTRF geo;\n    geo.georeference(georefedPing, attitude, position, ping, *svp, leverArm, boresight);\n\n    //std::cerr << \"GEOREF TRF: \" << georefedPing << std::endl;\n\n    Position georefPosition(0, 0, 0, 0);\n\n    CoordinateTransform::convertECEFToLongitudeLatitudeElevation(georefedPing, georefPosition);\n\n    //std::cerr << \"Final position: \" << std::endl << georefPosition << std::endl << std::endl;\n\n    REQUIRE(abs(georefPosition.getLongitude() - position.getLongitude()) < POSITION_PRECISION);\n    REQUIRE(abs(georefPosition.getLatitude() - position.getLatitude()) < POSITION_PRECISION);\n    REQUIRE(abs(georefPosition.getEllipsoidalHeight() - (position.getEllipsoidalHeight() - 7.4)) < POSITION_PRECISION);\n    \n    delete svp;\n}\n\nTEST_CASE(\"Georeference LGF with position and downward ping only\") {\n\n    Eigen::Vector3d georefedPing;\n\n    Attitude attitude(0, 0, 0, 0);\n    Position position(0, 48.4525, -68.5232, 15.401);\n    Ping ping(0, 0, 0, 0, 0, 0.01, 0, 0);\n    SoundVelocityProfile * svp = SoundVelocityProfileFactory::buildFreshWaterModel();\n    ping.setSurfaceSoundSpeed(svp->getSpeeds()(0)); //important now that raytracing uses it\n    Eigen::Vector3d leverArm(0, 0, 0);\n    Eigen::Matrix3d boresight = Eigen::Matrix3d::Identity();\n    \n    /*georef LGF*/\n    /*Build Centroid Position*/\n    double centroidLatitude = 48.4525;\n    double centroidLongitude = -68.5232;\n    double centroidEllipsoidHeight = 15.401;\n    Position centroidPosition(0, centroidLatitude, centroidLongitude, centroidEllipsoidHeight);\n    \n    GeoreferencingLGF geo;\n    geo.setCentroid(centroidPosition);\n    \n    geo.georeference(georefedPing, attitude, position, ping, *svp, leverArm, boresight);\n\n    //std::cerr << \"GEOREF LGF: \" << std::endl << georefedPing << std::endl << std::endl;\n\n    Eigen::Vector3d expectedPosition(0, 0, 7.4);\n    REQUIRE(georefedPing.isApprox(expectedPosition, POSITION_PRECISION));\n    \n    delete svp;\n}\n\nTEST_CASE(\"Georeference TRF with position and perpendicular unit vector ping and non-zero attitude\") {\n    \n    /*Build Centroid Position*/\n    double centroidLatitude = 48.4525;\n    double centroidLongitude = -68.5232;\n    double centroidEllipsoidHeight = 15.401;\n    Position centroidPosition(0, centroidLatitude, centroidLongitude, centroidEllipsoidHeight);\n\n    /*Build attitude*/\n    double roll = 1.0;\n    double pitch = 2.0;\n    double heading = 45.0;\n    Attitude attitude(0, roll, pitch, heading);\n\n    /*Build Position*/\n    double latitude = 48.4525;\n    double longitude = -68.5232;\n    double ellipsoidHeight = 15.401;\n    Position position(0, latitude, longitude, ellipsoidHeight);\n\n    /*Build Ping*/\n    uint64_t microEpoch = 0;\n    long id = 0;\n    uint32_t quality = 0;\n    double intensity = 0;\n    double surfaceSoundSpeed = 0;\n    double twoWayTravelTime = 0.01;\n    double alongTrackAngle = 0.0;\n    double acrossTrackAngle = 0.0;\n    \n    Ping ping(\n            microEpoch,\n            id,\n            quality,\n            intensity,\n            surfaceSoundSpeed,\n            twoWayTravelTime,\n            alongTrackAngle,\n            acrossTrackAngle\n            );\n\n    /*Build SVP*/\n    SoundVelocityProfile * svp = SoundVelocityProfileFactory::buildFreshWaterModel();\n    ping.setSurfaceSoundSpeed(svp->getSpeeds()(0)); //important now that raytracing uses it\n\n    /*Build lever arm*/\n    Eigen::Vector3d leverArm(0, 0, 0);\n\n    /*Build boresight matrix*/\n    Eigen::Matrix3d boresight = Eigen::Matrix3d::Identity();\n    \n    /*georef TRF*/\n    GeoreferencingTRF geo;\n    \n    Eigen::Vector3d georefedPingTRF;\n    geo.georeference(georefedPingTRF, attitude, position, ping, *svp, leverArm, boresight);\n    \n    /*georef LGF*/\n    GeoreferencingLGF geoLGF;\n    geoLGF.setCentroid(centroidPosition);\n    \n    Eigen::Vector3d georefedPingLGF;\n    geoLGF.georeference(georefedPingLGF, attitude, position, ping, *svp, leverArm, boresight);\n    \n    /*Test georefTRF*/\n    Eigen::Vector3d centroidTRF;\n    CoordinateTransform::getPositionECEF(centroidTRF, centroidPosition);\n    \n    Eigen::Matrix3d ned2ecef;\n    CoordinateTransform::ned2ecef(ned2ecef,centroidPosition);\n    \n    Eigen::Vector3d expectedGeorefedPingTRF = centroidTRF + ned2ecef*georefedPingLGF;\n    \n    double georefTestTreshold = 1e-5;\n    REQUIRE(std::abs(expectedGeorefedPingTRF(0) - georefedPingTRF(0)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPingTRF(1) - georefedPingTRF(1)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPingTRF(2) - georefedPingTRF(2)) < georefTestTreshold);\n    \n    delete svp;\n}\n\nTEST_CASE(\"Georeference LGF with position and perpendicular unit vector ping and non-zero attitude\"){\n    /*Build Centroid Position*/\n    double centroidLatitude = 48.4525;\n    double centroidLongitude = -68.5232;\n    double centroidEllipsoidHeight = 15.401;\n    Position centroidPosition(0, centroidLatitude, centroidLongitude, centroidEllipsoidHeight);\n    \n    /*Build attitude*/\n    double roll = 1.0; // 0.017453293\n    double pitch = 2.0; // 0.034906585\n    double heading = 45.0; // 0.785398185\n    Attitude attitude(0, roll, pitch, heading);\n\n    /*Build Position*/\n    double latitude = 48.4525;\n    double longitude = -68.5232;\n    double ellipsoidHeight = 15.401;\n    Position position(0, latitude, longitude, ellipsoidHeight);\n\n    /*Build Ping*/\n    uint64_t microEpoch = 0;\n    long id = 0;\n    uint32_t quality = 0;\n    double intensity = 0;\n    double surfaceSoundSpeed = 0;\n    double twoWayTravelTime = 0.01;\n    double alongTrackAngle = 0.0;\n    double acrossTrackAngle = 0.0;\n    \n    Ping ping(\n            microEpoch,\n            id,\n            quality,\n            intensity,\n            surfaceSoundSpeed,\n            twoWayTravelTime,\n            alongTrackAngle,\n            acrossTrackAngle\n            );\n\n    /*Build SVP*/\n    SoundVelocityProfile * svp = SoundVelocityProfileFactory::buildFreshWaterModel();\n    ping.setSurfaceSoundSpeed(svp->getSpeeds()(0)); //important now that raytracing uses it\n\n    /*Build lever arm*/\n    Eigen::Vector3d leverArm(0, 0, 0);\n\n    /*Build boresight matrix*/\n    Eigen::Matrix3d boresight = Eigen::Matrix3d::Identity();\n    \n    /*georef LGF*/\n    GeoreferencingLGF geo;\n    geo.setCentroid(centroidPosition);\n    \n    Eigen::Vector3d georefedPing;\n    geo.georeference(georefedPing, attitude, position, ping, *svp, leverArm, boresight);\n    \n    Eigen::Vector3d expectedGeorefedPing;\n    expectedGeorefedPing << 0.2739082412, 0.0912656601, 7.3943657507;\n    \n    double georefTestTreshold = 1e-5;\n    REQUIRE(std::abs(expectedGeorefedPing(0) - georefedPing(0)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPing(1) - georefedPing(1)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPing(2) - georefedPing(2)) < georefTestTreshold);\n    \n    delete svp;\n}\n\nTEST_CASE(\"Georeference TRF with position and perpendicular unit vector ping and non-zero attitude and non-zero lever-arm\"){\n    \n    /*Build Centroid Position*/\n    double centroidLatitude = 48.4525;\n    double centroidLongitude = -68.5232;\n    double centroidEllipsoidHeight = 15.401;\n    Position centroidPosition(0, centroidLatitude, centroidLongitude, centroidEllipsoidHeight);\n    \n    /*Build attitude*/\n    double roll = 1.0; // 0.017453293\n    double pitch = 2.0; // 0.034906585\n    double heading = 45.0; // 0.785398185\n    Attitude attitude(0, roll, pitch, heading);\n\n    /*Build Position*/\n    double latitude = 48.4525;\n    double longitude = -68.5232;\n    double ellipsoidHeight = 15.401;\n    Position position(0, latitude, longitude, ellipsoidHeight);\n\n    /*Build Ping*/\n    uint64_t microEpoch = 0;\n    long id = 0;\n    uint32_t quality = 0;\n    double intensity = 0;\n    double surfaceSoundSpeed = 0;\n    double twoWayTravelTime = 0.01;\n    double alongTrackAngle = 0.0;\n    double acrossTrackAngle = 0.0;\n    \n    Ping ping(\n            microEpoch,\n            id,\n            quality,\n            intensity,\n            surfaceSoundSpeed,\n            twoWayTravelTime,\n            alongTrackAngle,\n            acrossTrackAngle\n            );\n\n    /*Build SVP*/\n    SoundVelocityProfile * svp = SoundVelocityProfileFactory::buildFreshWaterModel();\n    ping.setSurfaceSoundSpeed(svp->getSpeeds()(0)); //important now that raytracing uses it\n\n    /*Build lever arm*/\n    Eigen::Vector3d leverArm(1, 2, 3);\n\n    /*Build boresight matrix*/\n    Eigen::Matrix3d boresight = Eigen::Matrix3d::Identity();\n    \n    /*georef TRF*/\n    GeoreferencingTRF geo;\n    \n    Eigen::Vector3d georefedPingTRF;\n    geo.georeference(georefedPingTRF, attitude, position, ping, *svp, leverArm, boresight);\n    \n    /*georef LGF*/\n    GeoreferencingLGF geoLGF;\n    geoLGF.setCentroid(centroidPosition);\n    \n    Eigen::Vector3d georefedPingLGF;\n    geoLGF.georeference(georefedPingLGF, attitude, position, ping, *svp, leverArm, boresight);\n    \n    /*Test georefTRF*/\n    Eigen::Vector3d centroidTRF;\n    CoordinateTransform::getPositionECEF(centroidTRF, centroidPosition);\n    \n    Eigen::Matrix3d ned2ecef;\n    CoordinateTransform::ned2ecef(ned2ecef,centroidPosition);\n    \n    Eigen::Vector3d expectedGeorefedPingTRF = centroidTRF + ned2ecef*georefedPingLGF;\n    \n    double georefTestTreshold = 1e-5;\n    REQUIRE(std::abs(expectedGeorefedPingTRF(0) - georefedPingTRF(0)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPingTRF(1) - georefedPingTRF(1)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPingTRF(2) - georefedPingTRF(2)) < georefTestTreshold);\n    \n    delete svp;\n}\n\nTEST_CASE(\"Georeference LGF with position and perpendicular unit vector ping and non-zero attitude and non-zero lever arm\"){\n    \n    /*Build Centroid Position*/\n    double centroidLatitude = 48.4525;\n    double centroidLongitude = -68.5232;\n    double centroidEllipsoidHeight = 15.401;\n    Position centroidPosition(0, centroidLatitude, centroidLongitude, centroidEllipsoidHeight);\n    \n    /*Build attitude*/\n    double roll = 1.0; // 0.017453293\n    double pitch = 2.0; // 0.034906585\n    double heading = 45.0; // 0.785398185\n    Attitude attitude(0, roll, pitch, heading);\n\n    /*Build Position*/\n    double latitude = 48.4525;\n    double longitude = -68.5232;\n    double ellipsoidHeight = 15.401;\n    Position position(0, latitude, longitude, ellipsoidHeight);\n\n    /*Build Ping*/\n    uint64_t microEpoch = 0;\n    long id = 0;\n    uint32_t quality = 0;\n    double intensity = 0;\n    double surfaceSoundSpeed = 0;\n    double twoWayTravelTime = 0.01;\n    double alongTrackAngle = 0.0;\n    double acrossTrackAngle = 0.0;\n    \n    Ping ping(\n            microEpoch,\n            id,\n            quality,\n            intensity,\n            surfaceSoundSpeed,\n            twoWayTravelTime,\n            alongTrackAngle,\n            acrossTrackAngle\n            );\n\n    /*Build SVP*/\n    SoundVelocityProfile * svp = SoundVelocityProfileFactory::buildFreshWaterModel();\n    ping.setSurfaceSoundSpeed(svp->getSpeeds()(0)); //important now that raytracing uses it\n\n    /*Build lever arm*/\n    Eigen::Vector3d leverArm(1, 2, 3);\n\n    /*Build boresight matrix*/\n    Eigen::Matrix3d boresight = Eigen::Matrix3d::Identity();\n    \n    /*georef LGF*/\n    GeoreferencingLGF geo;\n    geo.setCentroid(centroidPosition);\n    \n    Eigen::Vector3d georefedPing;\n    geo.georeference(georefedPing, attitude, position, ping, *svp, leverArm, boresight);\n    \n    Eigen::Vector3d expectedGeorefedPing;\n    expectedGeorefedPing << -0.3215086477, 2.2498008231, 10.3920656486;\n    \n    \n    double georefTestTreshold = 1e-5;\n    REQUIRE(std::abs(expectedGeorefedPing(0) - georefedPing(0)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPing(1) - georefedPing(1)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPing(2) - georefedPing(2)) < georefTestTreshold);\n    \n    delete svp;\n}\n\nTEST_CASE(\"Georeference TRF with position and perpendicular unit vector ping and non-zero attitude and non-zero lever-arm and non-zero boresight\"){\n    /*Build Centroid Position*/\n    double centroidLatitude = 48.4525;\n    double centroidLongitude = -68.5232;\n    double centroidEllipsoidHeight = 15.401;\n    Position centroidPosition(0, centroidLatitude, centroidLongitude, centroidEllipsoidHeight);\n    \n    /*Build attitude*/\n    double roll = 1.0; // 0.017453293\n    double pitch = 2.0; // 0.034906585\n    double heading = 45.0; // 0.785398185\n    Attitude attitude(0, roll, pitch, heading);\n\n    /*Build Position*/\n    double latitude = 48.4525;\n    double longitude = -68.5232;\n    double ellipsoidHeight = 15.401;\n    Position position(0, latitude, longitude, ellipsoidHeight);\n\n    /*Build Ping*/\n    uint64_t microEpoch = 0;\n    long id = 0;\n    uint32_t quality = 0;\n    double intensity = 0;\n    double surfaceSoundSpeed = 0;\n    double twoWayTravelTime = 0.01;\n    double alongTrackAngle = 0.0;\n    double acrossTrackAngle = 0.0;\n    \n    Ping ping(\n            microEpoch,\n            id,\n            quality,\n            intensity,\n            surfaceSoundSpeed,\n            twoWayTravelTime,\n            alongTrackAngle,\n            acrossTrackAngle\n            );\n\n    /*Build SVP*/\n    SoundVelocityProfile * svp = SoundVelocityProfileFactory::buildFreshWaterModel();\n    ping.setSurfaceSoundSpeed(svp->getSpeeds()(0)); //important now that raytracing uses it\n\n    /*Build lever arm*/\n    Eigen::Vector3d leverArm(1, 2, 3);\n\n    /*Build boresight matrix*/\n    double rollBoresightDegrees = 0.4;\n    double pitchBoresightDegrees = 0.5;\n    double headingBoresightDegrees = 0.6;\n    Attitude boresightAngles(0, rollBoresightDegrees, pitchBoresightDegrees, headingBoresightDegrees);\n    Eigen::Matrix3d boresight;\n    Boresight::buildMatrix(boresight, boresightAngles);\n    \n    /*georef TRF*/\n    GeoreferencingTRF geo;\n    \n    Eigen::Vector3d georefedPingTRF;\n    geo.georeference(georefedPingTRF, attitude, position, ping, *svp, leverArm, boresight);\n    \n    /*georef LGF*/\n    GeoreferencingLGF geoLGF;\n    geoLGF.setCentroid(centroidPosition);\n    \n    Eigen::Vector3d georefedPingLGF;\n    geoLGF.georeference(georefedPingLGF, attitude, position, ping, *svp, leverArm, boresight);\n    \n    /*Test georefTRF*/\n    Eigen::Vector3d centroidTRF;\n    CoordinateTransform::getPositionECEF(centroidTRF, centroidPosition);\n    \n    Eigen::Matrix3d ned2ecef;\n    CoordinateTransform::ned2ecef(ned2ecef,centroidPosition);\n    \n    Eigen::Vector3d expectedGeorefedPingTRF = centroidTRF + ned2ecef*georefedPingLGF;\n    \n    double georefTestTreshold = 1e-5;\n    REQUIRE(std::abs(expectedGeorefedPingTRF(0) - georefedPingTRF(0)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPingTRF(1) - georefedPingTRF(1)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPingTRF(2) - georefedPingTRF(2)) < georefTestTreshold);\n    \n    delete svp;\n}\n\nTEST_CASE(\"Georeference LGF with position and perpendicular unit vector ping and non-zero attitude and non-zero lever arm and non-zero boresight\"){\n    \n    /*Build Centroid Position*/\n    double centroidLatitude = 48.4525;\n    double centroidLongitude = -68.5232;\n    double centroidEllipsoidHeight = 15.401;\n    Position centroidPosition(0, centroidLatitude, centroidLongitude, centroidEllipsoidHeight);\n    \n    /*Build attitude*/\n    double roll = 1.0; // 0.017453293\n    double pitch = 2.0; // 0.034906585\n    double heading = 45.0; // 0.785398185\n    Attitude attitude(0, roll, pitch, heading);\n\n    /*Build Position*/\n    double latitude = 48.4525;\n    double longitude = -68.5232;\n    double ellipsoidHeight = 15.401;\n    Position position(0, latitude, longitude, ellipsoidHeight);\n\n    /*Build Ping*/\n    uint64_t microEpoch = 0;\n    long id = 0;\n    uint32_t quality = 0;\n    double intensity = 0;\n    double surfaceSoundSpeed = 0;\n    double twoWayTravelTime = 0.01;\n    double alongTrackAngle = 0.0;\n    double acrossTrackAngle = 0.0;\n    \n    Ping ping(\n            microEpoch,\n            id,\n            quality,\n            intensity,\n            surfaceSoundSpeed,\n            twoWayTravelTime,\n            alongTrackAngle,\n            acrossTrackAngle\n            );\n\n    /*Build SVP*/\n    SoundVelocityProfile * svp = SoundVelocityProfileFactory::buildFreshWaterModel();\n    ping.setSurfaceSoundSpeed(svp->getSpeeds()(0)); //important now that raytracing uses it\n\n    /*Build lever arm*/\n    Eigen::Vector3d leverArm(1, 2, 3);\n\n    /*Build boresight matrix*/\n    double rollBoresightDegrees = 0.4;\n    double pitchBoresightDegrees = 0.5;\n    double headingBoresightDegrees = 0.6;\n    Attitude boresightAngles(0, rollBoresightDegrees, pitchBoresightDegrees, headingBoresightDegrees);\n    Eigen::Matrix3d boresight;\n    Boresight::buildMatrix(boresight, boresightAngles);\n    \n    /*georef LGF*/\n    GeoreferencingLGF geo;\n    geo.setCentroid(centroidPosition);\n    \n    Eigen::Vector3d georefedPing;\n    geo.georeference(georefedPing, attitude, position, ping, *svp, leverArm, boresight);\n    \n    Eigen::Vector3d expectedGeorefedPing;\n    expectedGeorefedPing << -0.2394900282, 2.2597419967, 10.3884422996;\n    \n    \n    double georefTestTreshold = 1e-5;\n    REQUIRE(std::abs(expectedGeorefedPing(0) - georefedPing(0)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPing(1) - georefedPing(1)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPing(2) - georefedPing(2)) < georefTestTreshold);\n    \n    delete svp;\n}\n\nTEST_CASE(\"Georeference TRF with position and perpendicular unit vector ping and non-zero attitude and non-zero lever-arm and non-zero boresight and centroid not colocated with position\"){\n    /*Build Centroid Position*/\n    double centroidLatitude = 48.4525033333222;\n    double centroidLongitude = -68.52320333332072;\n    double centroidEllipsoidHeight = 15.267333333333;\n    Position centroidPosition(0, centroidLatitude, centroidLongitude, centroidEllipsoidHeight);\n    \n    /*Build attitude*/\n    double roll = 1.0; // 0.017453293\n    double pitch = 2.0; // 0.034906585\n    double heading = 45.0; // 0.785398185\n    Attitude attitude(0, roll, pitch, heading);\n\n    /*Build Position*/\n    double latitude = 48.4525;\n    double longitude = -68.5232;\n    double ellipsoidHeight = 15.401;\n    Position position(0, latitude, longitude, ellipsoidHeight);\n\n    /*Build Ping*/\n    uint64_t microEpoch = 0;\n    long id = 0;\n    uint32_t quality = 0;\n    double intensity = 0;\n    double surfaceSoundSpeed = 0;\n    double twoWayTravelTime = 0.01;\n    double alongTrackAngle = 0.0;\n    double acrossTrackAngle = 0.0;\n    \n    Ping ping(\n            microEpoch,\n            id,\n            quality,\n            intensity,\n            surfaceSoundSpeed,\n            twoWayTravelTime,\n            alongTrackAngle,\n            acrossTrackAngle\n            );\n\n    /*Build SVP*/\n    SoundVelocityProfile * svp = SoundVelocityProfileFactory::buildFreshWaterModel();\n    ping.setSurfaceSoundSpeed(svp->getSpeeds()(0)); //important now that raytracing uses it\n\n    /*Build lever arm*/\n    Eigen::Vector3d leverArm(1, 2, 3);\n\n    /*Build boresight matrix*/\n    double rollBoresightDegrees = 0.4;\n    double pitchBoresightDegrees = 0.5;\n    double headingBoresightDegrees = 0.6;\n    Attitude boresightAngles(0, rollBoresightDegrees, pitchBoresightDegrees, headingBoresightDegrees);\n    Eigen::Matrix3d boresight;\n    Boresight::buildMatrix(boresight, boresightAngles);\n    \n    /*georef TRF*/\n    GeoreferencingTRF geo;\n    \n    Eigen::Vector3d georefedPingTRF;\n    geo.georeference(georefedPingTRF, attitude, position, ping, *svp, leverArm, boresight);\n    \n    /*georef LGF*/\n    GeoreferencingLGF geoLGF;\n    geoLGF.setCentroid(centroidPosition);\n    \n    Eigen::Vector3d georefedPingLGF;\n    geoLGF.georeference(georefedPingLGF, attitude, position, ping, *svp, leverArm, boresight);\n    \n    /*Test georefTRF*/\n    Eigen::Vector3d centroidTRF;\n    CoordinateTransform::getPositionECEF(centroidTRF, centroidPosition);\n    \n    Eigen::Matrix3d ned2ecef;\n    CoordinateTransform::ned2ecef(ned2ecef,centroidPosition);\n    \n    Eigen::Vector3d expectedGeorefedPingTRF = centroidTRF + ned2ecef*georefedPingLGF;\n    \n    double georefTestTreshold = 1e-5;\n    REQUIRE(std::abs(expectedGeorefedPingTRF(0) - georefedPingTRF(0)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPingTRF(1) - georefedPingTRF(1)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPingTRF(2) - georefedPingTRF(2)) < georefTestTreshold);\n    \n    delete svp;\n}\n\nTEST_CASE(\"Georeference LGF with position and perpendicular unit vector ping and non-zero attitude and non-zero lever arm and non-zero boresight and centroid not colocated with position\"){\n    \n    /*Build Centroid Position*/\n    double centroidLatitude = 48.4525033333222;\n    double centroidLongitude = -68.52320333332072;\n    double centroidEllipsoidHeight = 15.267333333333;\n    Position centroidPosition(0, centroidLatitude, centroidLongitude, centroidEllipsoidHeight);\n    \n    /*Build attitude*/\n    double roll = 1.0; // 0.017453293\n    double pitch = 2.0; // 0.034906585\n    double heading = 45.0; // 0.785398185\n    Attitude attitude(0, roll, pitch, heading);\n\n    /*Build Position*/\n    double latitude = 48.4525;\n    double longitude = -68.5232;\n    double ellipsoidHeight = 15.401;\n    Position position(0, latitude, longitude, ellipsoidHeight);\n\n    /*Build Ping*/\n    uint64_t microEpoch = 0;\n    long id = 0;\n    uint32_t quality = 0;\n    double intensity = 0;\n    double surfaceSoundSpeed = 0;\n    double twoWayTravelTime = 0.01;\n    double alongTrackAngle = 0.0;\n    double acrossTrackAngle = 0.0;\n    \n    Ping ping(\n            microEpoch,\n            id,\n            quality,\n            intensity,\n            surfaceSoundSpeed,\n            twoWayTravelTime,\n            alongTrackAngle,\n            acrossTrackAngle\n            );\n\n    /*Build SVP*/\n    SoundVelocityProfile * svp = SoundVelocityProfileFactory::buildFreshWaterModel();\n    ping.setSurfaceSoundSpeed(svp->getSpeeds()(0)); //important now that raytracing uses it\n\n    /*Build lever arm*/\n    Eigen::Vector3d leverArm(1, 2, 3);\n\n    /*Build boresight matrix*/\n    double rollBoresightDegrees = 0.4;\n    double pitchBoresightDegrees = 0.5;\n    double headingBoresightDegrees = 0.6;\n    Attitude boresightAngles(0, rollBoresightDegrees, pitchBoresightDegrees, headingBoresightDegrees);\n    Eigen::Matrix3d boresight;\n    Boresight::buildMatrix(boresight, boresightAngles);\n    \n    /*georef LGF*/\n    GeoreferencingLGF geo;\n    geo.setCentroid(centroidPosition);\n    \n    Eigen::Vector3d georefedPing;\n    geo.georeference(georefedPing, attitude, position, ping, *svp, leverArm, boresight);\n    \n    Eigen::Vector3d expectedGeorefedPing;\n    expectedGeorefedPing << -0.6101546444, 2.5063106918, 10.2547756501;\n    \n    double georefTestTreshold = 1e-5;\n    REQUIRE(std::abs(expectedGeorefedPing(0) - georefedPing(0)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPing(1) - georefedPing(1)) < georefTestTreshold);\n    REQUIRE(std::abs(expectedGeorefedPing(2) - georefedPing(2)) < georefTestTreshold);\n    \n    delete svp;\n}\n\n#endif /* GEOREFERENCINGTEST_HPP */\n\n", "meta": {"hexsha": "a3fc6af039c48209a32281651253e59569a8edca", "size": 26988, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/GeoreferencingTest.hpp", "max_stars_repo_name": "Ddoiron-cidco/MBES-lib", "max_stars_repo_head_hexsha": "185d2a284a4089507f589f71716d5ded82154e68", "max_stars_repo_licenses": ["MIT"], "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/GeoreferencingTest.hpp", "max_issues_repo_name": "Ddoiron-cidco/MBES-lib", "max_issues_repo_head_hexsha": "185d2a284a4089507f589f71716d5ded82154e68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/GeoreferencingTest.hpp", "max_forks_repo_name": "Ddoiron-cidco/MBES-lib", "max_forks_repo_head_hexsha": "185d2a284a4089507f589f71716d5ded82154e68", "max_forks_repo_licenses": ["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.292249047, "max_line_length": 188, "alphanum_fraction": 0.6871943086, "num_tokens": 7712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5542727411849199}}
{"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": "\n#include <iostream>\n#include <map>\n#include <vector>\n\n#include <boost/dynamic_bitset.hpp>\n\n#include \"CliqueList.h\"\n\nusing namespace std;\nusing namespace boost;\n\n/** Constructor. Note that this isn't particularly fast (but\n    doesn't have to be). */\nCliqueList::CliqueList(int n, int r, int maxCliqueSize) {\n    n_ = n;\n    r_ = r;\n    max_clique_size_ = maxCliqueSize;\n    // number the (hyper)edges\n    initEdgeNumbering();\n    // initialize the cliques\n    clique_.resize(maxCliqueSize+1);\n    for(int k=r; k<=maxCliqueSize; k++)\n        addCliques(k);\n}\n\n/** Adds counts of which cliques are present in a graph.\n    Should be multithreaded.\n    Possibly not used, as the bookkeeping seems easier if I\n    just track the largest clique. (Clearly, if there's a\n    9-vertex clique, there are many 8-cliques, and even\n    more 7-vertex cliques, etc.) */\nvoid CliqueList::addToCounts(vector<int> count, const bits & g) {\n    // loop through the possible sizes of clique\n    for(int k = 0; k < int(clique_.size()); k++)\n        // loop through the cliques\n        for(int i = 0; i < int(clique_[k].size()); i++)\n            if (clique_[k][i].is_subset_of(g))\n                count[k]++;\n}\n\n/** Gets size of the largest clique in a graph.\n    Should be multithreaded.\n    g: vertices of a hypergraph\n    Returns: number of vertices in the largest clique */\nint CliqueList::getMaxCliqueSize(const bits & g) {\n    // loop through possible clique sizes (starting with largest)\n    for(int k = n_; k >= r_; k--)\n        // loop through the cliques\n        for(int i = 0; i < int(clique_[k].size()); i++) {\n            if (clique_[k][i].is_subset_of(g))\n                return k;\n        }\n    return 0;\n}\n\n/** Gets vertices covered by hypergraphs.\n    g: vertices of a hypergraph\n    k: size of the hyperclique to check for\n    coveredEdges: ref. to bits, which will be set with\n        the edges which are covered\n    Side effects: fills in coveredEdges\n    Returns: number of k-vertex cliques found */\nint CliqueList::getCoveredEdges(const bits & g,\n        int k, bits & coveredEdges) {\n    // set coveredEdges to all 0 (In theory, if we enforced\n    // that callers looked for larger cliques first, we wouldn't\n    // need this. But this seems simpler).\n    coveredEdges.reset();\n    int cliqueCount = 0;\n    // loop through the cliques\n    for(int i = 0; i < int(clique_[k].size()); i++) {\n        if (clique_[k][i].is_subset_of(g)) {\n            // record the edges covered by this clique\n            coveredEdges |= clique_[k][i];\n            ++cliqueCount;\n        }\n    }\n    return cliqueCount;\n}\n\n/** Initialize the edge numbering. */\nvoid CliqueList::initEdgeNumbering() {\n    int e = 0;\n    // this loops through all r-element subsets of n vertices\n    SubsetIterator edge(n_, r_);\n    do {\n        edgeIndex_[ edge.getSet() ] = e;\n        ++e;\n    } while (edge.next());\n}\n\n/** Initialize the cliques with k vertices. */\nvoid CliqueList::addCliques(int k) {\n    // this will contain one bitvector per clique\n    vector<bits> bitvectors;\n    // this loops through the cliques\n    SubsetIterator clique(n_, k);\n    do {\n        // this is the k indices of vertices\n        vector<int> &v = clique.getSet();\n        // this loops through the edges in a clique\n        SubsetIterator edge(k, r_);\n        // this tracks the bits corresponding to those edges\n        bits edgeBits(edgeIndex_.size());\n        do {\n            // this will be the r indices of an edge\n            // in the clique, among all n vertices\n            vector<int> r1;\n            vector<int> &e = edge.getSet();\n            for(int i=0; i<int(e.size()); i++)\n                r1.push_back(v[e[i]]);\n            // add this edge into the clique\n            edgeBits |= getBitmask(r1);\n        } while (edge.next());\n        bitvectors.push_back(edgeBits);\n    } while (clique.next());\n    clique_[k] = bitvectors;                \n}\n\n/** Gets the bitmask corresponding to a particular clique. */\nbits CliqueList::getBitmask(vector<int> & edge) {\n    bits x(edgeIndex_.size());\n    // set bits corresponding to each edge\n    for(int i=0; i<int(edge.size()); i++)\n        x[ edgeIndex_[edge] ] = 1;\n    return x;\n}\n\n\n/** Dumps list of cliques to standard output. */\nvoid CliqueList::printCliques() {\n    cout << \"dumping cliques\" << endl;\n    for(int cliqueSize = n_; cliqueSize >= r_; --cliqueSize) {\n        cout << \"n = \" << cliqueSize << endl;\n        vector<bits> & clique1 = clique_[cliqueSize];\n        // loop through cliques of this size\n        for(int c = 0; c < int(clique1.size()); ++c) {\n            cout << clique1[c] << \" \";\n        }\n        cout << endl;\n    }\n}\n\n/** Prints the edges in one graph. */\nvoid CliqueList::printGraph(bits &e) {\n    // FIXME print the vertices\n    cout << e << \" \";\n}\n\n", "meta": {"hexsha": "337bae3ce9c10cda5efffcc14f49442740a68486", "size": 4793, "ext": "cc", "lang": "C++", "max_stars_repo_path": "countingBound/cliqueCounter/CliqueList.cc", "max_stars_repo_name": "joshtburdick/misc", "max_stars_repo_head_hexsha": "7bb103b4f9d850e3279eb675c6df420aa7b8da22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "countingBound/cliqueCounter/CliqueList.cc", "max_issues_repo_name": "joshtburdick/misc", "max_issues_repo_head_hexsha": "7bb103b4f9d850e3279eb675c6df420aa7b8da22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "countingBound/cliqueCounter/CliqueList.cc", "max_forks_repo_name": "joshtburdick/misc", "max_forks_repo_head_hexsha": "7bb103b4f9d850e3279eb675c6df420aa7b8da22", "max_forks_repo_licenses": ["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.7417218543, "max_line_length": 65, "alphanum_fraction": 0.6025453787, "num_tokens": 1257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5542590457151444}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <dlib/clustering.h>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include \"flat.hpp\"\n\nnamespace otus {\n  class Clusterer {\n  public:\n    class IOError: public std::runtime_error {\n    public:\n      IOError(std::string const & message):\n      std::runtime_error(message) { }\n    };\n\n    Clusterer(\n        std::vector<Flat> const & data,\n        int numberOfClusters,\n        float gamma=0.1,\n        float accuracy=0.01);\n\n    Clusterer(std::string const & filename);\n\n    void save(std::string const & filename);\n\n    std::string operator()(Flat const & flat) const;\n\n  private:\n    using KernelType = dlib::radial_basis_kernel<DataType>;\n    using DataSizeType = decltype(DataType().size());\n    using ClusterNumType = unsigned long int;\n\n    std::string const fileSuffix { \".dat\" };\n    std::vector<DataType> data;\n    std::vector<std::pair<Flat, ClusterNumType>> metaData;\n    dlib::kkmeans<KernelType> kMeans;\n    /// For normalization function y = kx - a.\n    std::vector<float> k, a; // TODO Make serializable functor.\n\n    void normalizeData();\n\n    void normalize(DataType & item) const;\n\n    void train(int numberOfClusters);\n  };\n}\n", "meta": {"hexsha": "6eacfd84f8cba65377644bd747e940ef93f2ea9d", "size": 1236, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/clusterer.hpp", "max_stars_repo_name": "bergentroll/otus-cpp-16", "max_stars_repo_head_hexsha": "987f1351d081bfa38ef88fbe21b87e9be9dc5b5d", "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": "inc/clusterer.hpp", "max_issues_repo_name": "bergentroll/otus-cpp-16", "max_issues_repo_head_hexsha": "987f1351d081bfa38ef88fbe21b87e9be9dc5b5d", "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": "inc/clusterer.hpp", "max_forks_repo_name": "bergentroll/otus-cpp-16", "max_forks_repo_head_hexsha": "987f1351d081bfa38ef88fbe21b87e9be9dc5b5d", "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.320754717, "max_line_length": 63, "alphanum_fraction": 0.6593851133, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7057850340255387, "lm_q1q2_score": 0.5542590363897792}}
{"text": "/**\n * Decode binary space partitioning airline seating assignments\n */\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <sstream>\n\n#include <boost/algorithm/string.hpp>\n\nvoid decode(const std::string &spec, int &row, int &col)\n{\n    if(spec.length() != 10) { return; }\n\n    const std::string rowspec = spec.substr(0, 7);\n    const std::string colspec = spec.substr(7, 3);\n\n    row = 0;\n    for(int i=0; i<7; ++i)\n    {\n        row <<= 1;\n\n        //std::cout << rowspec.at(i) << std::endl;\n        if(rowspec.at(i) == 'F')\n        {\n            row |= 0;\n        }\n        else\n        {\n            row |= 1;\n        }\n    }\n\n    col = 0;\n    for(int i=0; i<3; ++i)\n    {\n        col <<= 1;\n\n        //std::cout << colspec.at(i) << std::endl;\n        if(colspec.at(i) == 'R')\n        {\n            col |= 1;\n        }\n        else\n        {\n            col |= 0;\n        }\n    }\n}\n\nvoid usage()\n{\n    std::cout << \"day5 <input.txt>\" << std::endl;\n}\n\nint main(int argc, char *argv[])\n{\n    if(argc != 2)\n    {\n        usage();\n        return EXIT_FAILURE;\n    }\n\n    int row, col;\n\n    //  test data\n    /*\n    decode(\"FBFBBFFRLR\", row, col);\n    std::cout << \"row: \" << row << std::endl;\n    std::cout << \"col: \" << col << std::endl;\n\n    decode(\"BFFFBBFRRR\", row, col);\n    std::cout << \"row: \" << row << std::endl;\n    std::cout << \"col: \" << col << std::endl;\n\n    decode(\"FFFBBBFRRR\", row, col);\n    std::cout << \"row: \" << row << std::endl;\n    std::cout << \"col: \" << col << std::endl;\n\n    decode(\"BBFFBBFRLL\", row, col);\n    std::cout << \"row: \" << row << std::endl;\n    std::cout << \"col: \" << col << std::endl;\n    */\n\n    int maxSeatId = 0;\n\n    std::ifstream ifs(argv[1], std::ifstream::in);\n    std::string line;\n    while(std::getline(ifs, line))\n    {\n        decode(line, row, col);\n        int seatId = row * 8 + col;\n        if(seatId > maxSeatId)\n        {\n            maxSeatId = seatId;\n        }\n    }\n\n    std::cout << \"max seat id: \" << maxSeatId << std::endl;\n\n    ifs.close();\n}\n", "meta": {"hexsha": "8dfa02a0fc9744ee7684ba08bd113fc1150bc2ba", "size": 2043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "day5/part1.cpp", "max_stars_repo_name": "deltj/advent_of_code_2020", "max_stars_repo_head_hexsha": "52d1eeeff6ba0df6bc49679ae9fc73e04a543ca1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day5/part1.cpp", "max_issues_repo_name": "deltj/advent_of_code_2020", "max_issues_repo_head_hexsha": "52d1eeeff6ba0df6bc49679ae9fc73e04a543ca1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day5/part1.cpp", "max_forks_repo_name": "deltj/advent_of_code_2020", "max_forks_repo_head_hexsha": "52d1eeeff6ba0df6bc49679ae9fc73e04a543ca1", "max_forks_repo_licenses": ["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.6442307692, "max_line_length": 63, "alphanum_fraction": 0.4659813999, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.5542590266699718}}
{"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": "#include <Eigen/Dense>\n#include <iostream>\n\n#include \"y2017/vision/target_finder.h\"\n\n#include \"aos/vision/blob/move_scale.h\"\n#include \"aos/vision/blob/stream_view.h\"\n#include \"aos/vision/blob/transpose.h\"\n#include \"aos/vision/debug/debug_framework.h\"\n#include \"aos/vision/math/vector.h\"\n\nusing aos::vision::ImageRange;\nusing aos::vision::ImageFormat;\nusing aos::vision::RangeImage;\nusing aos::vision::BlobList;\n\nnamespace y2017 {\nnamespace vision {\n\nBlobList RenderTargetListShifted(const std::vector<TargetComponent> &list) {\n  BlobList out;\n  for (const auto &entity : list) {\n    out.emplace_back(entity.RenderShifted());\n  }\n  return out;\n}\n\nRangeImage TargetComponent::RenderShifted() const {\n  std::vector<std::vector<ImageRange>> out_range_list;\n  int y = 0;\n  double max_y = -b / (2 * a);\n  double parab_off = max_y * max_y * a + max_y * b;\n  RangeImage t_img = Transpose(*img);\n  for (const auto &row : t_img) {\n    int off = -(y * y * a + y * b - parab_off);\n    // int off = 0;\n    // fprintf(stderr, \"off: %d %d\\n\", off, y);\n    std::vector<ImageRange> row_out;\n    for (const ImageRange &range : row) {\n      row_out.emplace_back(ImageRange{off + range.st, off + range.ed});\n    }\n    ++y;\n    out_range_list.emplace_back(std::move(row_out));\n  }\n  return RangeImage(t_img.min_y(), std::move(out_range_list));\n}\n\nclass FilterHarnessExample : public aos::vision::FilterHarness {\n public:\n  aos::vision::RangeImage Threshold(aos::vision::ImagePtr image) override {\n    return finder_.Threshold(image);\n  }\n\n  void InstallViewer(aos::vision::BlobStreamViewer *viewer) override {\n    viewer_ = viewer;\n    viewer_->SetScale(0.5);\n    overlays_.push_back(&overlay_);\n    overlays_.push_back(finder_.GetOverlay());\n    viewer_->view()->SetOverlays(&overlays_);\n  }\n\n  bool HandleBlobs(BlobList imgs, ImageFormat /*fmt*/) override {\n    // reset for next drawing cycle\n    for (auto &overlay : overlays_) {\n      overlay->Reset();\n    }\n\n    // Remove bad blobs.\n    finder_.PreFilter(imgs);\n\n    // calculate each component/\n    std::vector<TargetComponent> target_component_list =\n        finder_.FillTargetComponentList(imgs);\n\n    DrawComponents(target_component_list);\n\n    // Put the compenents together into targets and pick the best.\n    Target final_target;\n    bool found_target =\n        finder_.FindTargetFromComponents(target_component_list, &final_target);\n\n    // BlobList newImg = RenderTargetListShifted(target_component_list);\n    if (viewer_) {\n      viewer_->DrawBlobList(imgs, {0, 0, 255});\n    }\n\n    if (found_target) {\n      BlobList list;\n      list.emplace_back(*(final_target.comp1.img));\n      list.emplace_back(*(final_target.comp2.img));\n      viewer_->DrawBlobList(list, {0, 255, 0});\n      overlay_.DrawCross(final_target.screen_coord, 25, {255, 255, 255});\n    }\n\n    // No targets.\n    return found_target;\n  }\n\n  void DrawComponents(const std::vector<TargetComponent> comp) {\n    for (const TargetComponent &t : comp) {\n      aos::vision::ImageBBox bbox;\n      GetBBox(*(t.img), &bbox);\n      overlay_.DrawBBox(bbox, {255, 0, 0});\n\n      overlay_.StartNewProfile();\n      for (int i = 0; i < bbox.maxx - bbox.minx; i += 10) {\n        double y0 = t.a * i * i + t.b * i + t.c_0;\n        double y1 = t.a * i * i + t.b * i + t.c_1;\n        overlay_.AddPoint(aos::vision::Vector<2>(i + t.mini, y0), {255, 0, 0});\n        overlay_.AddPoint(aos::vision::Vector<2>(i + t.mini, y1), {255, 0, 0});\n      }\n    }\n  }\n\n private:\n  // implementation of the filter pipeline.\n  TargetFinder finder_;\n  aos::vision::BlobStreamViewer *viewer_ = nullptr;\n  aos::vision::PixelLinesOverlay overlay_;\n  std::vector<aos::vision::OverlayBase *> overlays_;\n};\n\n}  // namespace vision\n}  // namespace y2017\n\nint main(int argc, char **argv) {\n  y2017::vision::FilterHarnessExample filter_harness;\n  aos::vision::DebugFrameworkMain(argc, argv, &filter_harness,\n                                  aos::vision::CameraParams());\n}\n", "meta": {"hexsha": "10dd57ec3dc5ecfaf76392801ec94316abead838", "size": 3941, "ext": "cc", "lang": "C++", "max_stars_repo_path": "y2017/vision/debug_viewer.cc", "max_stars_repo_name": "Ewpratten/frc_971_mirror", "max_stars_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2021-06-18T03:22:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T15:23:43.000Z", "max_issues_repo_path": "y2017/vision/debug_viewer.cc", "max_issues_repo_name": "Ewpratten/frc_971_mirror", "max_issues_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-06-18T03:22:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T22:14:15.000Z", "max_forks_repo_path": "y2017/vision/debug_viewer.cc", "max_forks_repo_name": "Ewpratten/frc_971_mirror", "max_forks_repo_head_hexsha": "3a8a0c4359f284d29547962c2b4c43d290d8065c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-08-19T19:20:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T07:33:18.000Z", "avg_line_length": 30.0839694656, "max_line_length": 79, "alphanum_fraction": 0.6622684598, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.554171943129217}}
{"text": "//\n// Created by haohanwang on 1/22/16.\n//\n\n#ifndef ALGORITHMS_LASSO_HPP\n#define ALGORITHMS_LASSO_HPP\n\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nclass Lasso {\nprivate:\n    MatrixXf X;\n    MatrixXf beta;\n    VectorXf y;\n    float lambda;\n    float learningRate;\n    float progress;\npublic:\n    void setX(MatrixXf);\n    void setY(VectorXf);\n    void setLambda(float);\n    void setLearningRage(float);\n\n    MatrixXf getX(void);\n    MatrixXf getBeta(void);\n    VectorXf getY(void);\n    float getLambda(void);\n    float getLearningRate(void);\n\n    virtual void assertReadyToRun();\n    void train();\n    void train(MatrixXf, VectorXf, float, float, float);\n\n    VectorXf predict();\n    VectorXf predict(MatrixXf);\n\n    Lasso();\n};\n\n\n#endif //ALGORITHMS_LASSO_HPP\n", "meta": {"hexsha": "86bb7bea2086202db9bdb5b922c6ae4a5cb16c65", "size": 804, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Models/lasso.hpp", "max_stars_repo_name": "blengerich/jenkins_test", "max_stars_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T00:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-06T16:40:52.000Z", "max_issues_repo_path": "src/Models/lasso.hpp", "max_issues_repo_name": "blengerich/jenkins_test", "max_issues_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2016-11-11T22:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-04T21:55:57.000Z", "max_forks_repo_path": "src/Models/lasso.hpp", "max_forks_repo_name": "blengerich/jenkins_test", "max_forks_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-02-01T09:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T14:40:43.000Z", "avg_line_length": 17.4782608696, "max_line_length": 56, "alphanum_fraction": 0.6853233831, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5541555491663693}}
{"text": "// Copyright (c) 2015\n// Author: Chrono Law\n#include <std.hpp>\nusing namespace std;\n\n#include <boost/assign.hpp>\n#include <boost/multi_array.hpp>\nusing namespace boost;\n\n//////////////////////////////////////////\nvoid case1()\n{\n    multi_array<int, 3> ma(extents[2][3][4]);\n\n    auto shape = ma.shape();\n    for (size_t i = 0; i < ma.num_dimensions(); ++i)\n    {\n        cout << shape[i] << \",\";\n    }\n    cout << endl << ma.num_elements() << endl;\n\n    for (int i = 0,  v = 0; i < 2; ++i)\n        for (int j = 0; j < 3;++j)\n            for (int k = 0;k < 4;++k)\n            {\n                ma[i][j][k] = v++;\n            }\n\n    for (int i = 0; i < 2; ++i)\n    {\n        for (int j = 0; j < 3;++j)\n        {\n            for (int k = 0;k < 4;++k)\n            {\n                cout << ma[i][j][k] << \",\";\n            }\n            cout << endl;\n        }\n        cout << endl;\n    }\n\n    //cout << ma[2][3][4];\n\n    std::array<size_t, 3> idx = {0,1,2};\n    ma(idx) = 10;\n    cout << ma(idx) << endl;\n}\n\n//////////////////////////////////////////\nvoid case2()\n{\n    multi_array<int, 3> ma(extents[2][3][4]);\n    assert(ma.shape()[0] == 2);\n\n    std::array<std::size_t, 3> arr = {4,3,2};\n    ma.reshape(arr);\n    assert(ma.shape()[0] == 4);\n\n    ma.resize(extents[2][9][9]);\n    assert(ma.num_elements() == 2*9*9);\n    assert(ma.shape()[1] == 9);\n}\n\n//////////////////////////////////////////\nvoid case3()\n{\n    typedef multi_array<int, 2> ma_type;\n    multi_array<int, 2> ma(extents[3][4]) ;\n\n    typedef ma_type::index_range range;\n    //indices[range(0,2)][range(0,2)];\n\n    auto view = ma[indices[range(0,2)][range(0,2)] ];\n\n    cout << view.num_elements() << endl;\n    for (int i = 0; i < 2; ++i)\n    {\n        for (int j = 0; j < 2;++j)\n        {\n            cout << view[i][j] << \",\";\n        }\n        cout << endl;\n    }\n    cout << *view.shape() << endl;\n\n}\n\n//////////////////////////////////////////\nvoid case4()\n{\n    int arr[12];\n    for (int i = 0;i < 12;++i)\n    {   arr[i] = i; }\n\n    multi_array_ref<int, 2> mar(arr, extents[3][4]);\n\n    for (size_t i = 0; i < 3; ++i)\n    {\n        cout << \"(\";\n        for(size_t j = 0;j < 4;++j)\n        {\n            cout << mar[i][j]++;\n            cout << (j!=3?',':' ');\n        }\n        cout << \")\" << endl;\n    }\n\n    const_multi_array_ref<int, 2> cmar(arr, extents[2][6]);\n\n    for (size_t i = 0; i < 2; ++i)\n    {\n        cout << \"(\";\n        for(size_t j = 0;j < 6;++j)\n        {\n            cout << cmar[i][j];\n            cout << (j!=5?',':' ');\n        }\n        cout << \")\" << endl;\n    }\n\n}\n\n//////////////////////////////////////////\nvoid case5()\n{\n    //multi_array<int, 3> ma(vector<int>(assign::list_of(2)(2)));\n    multi_array<int, 3> ma(vector<int>{2,2,2});\n    auto shape = ma.shape();\n    for (size_t i = 0; i < ma.num_dimensions(); ++i)\n    {\n        cout << shape[i] << \",\";\n    }\n\n}\n\n//////////////////////////////////////////\nvoid case6()\n{\n    typedef multi_array<int, 3> ma_type;\n    typedef ma_type::extent_range range;\n    ma_type ma(extents [range(1,5)][4][range(-2,2)]);\n    ma[1][0][-2] = 10;\n\n    ma.reindex(1);\n    assert(ma[1][1][1] == 10);\n    ma.reindex(std::array<int,3>{1,0,-4});\n    assert(ma[1][0][-4] == 10);\n\n    cout << *ma.index_bases() << endl;\n}\n//////////////////////////////////////////\nvoid case7()\n{\n    using namespace boost::detail::multi_array;\n\n    typedef multi_array<int, 3> ma_type;\n    typedef ma_type::index_range range;\n    ma_type ma(extents[9][8][7]);\n\n    auto view = ma[indices[range()< 3L][2L<=range()<= 5L][range()] ];\n    cout << *view.shape() << endl;\n\n}\n//////////////////////////////////////////\n\nint main()\n{\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n    case7();\n}\n", "meta": {"hexsha": "da798a1b7a85fd735fc4bf5b95370ca5bd908e8d", "size": 3729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "container/multi_array.cpp", "max_stars_repo_name": "xujungp02/boost_guide", "max_stars_repo_head_hexsha": "328516455d334506f824402455a17afc606ca3bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 355.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T12:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T04:15:00.000Z", "max_issues_repo_path": "container/multi_array.cpp", "max_issues_repo_name": "lak123456/boost_guide", "max_issues_repo_head_hexsha": "1886ec8014838717222484f0fe872ecebc324e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-04T18:14:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-09T02:38:12.000Z", "max_forks_repo_path": "container/multi_array.cpp", "max_forks_repo_name": "lak123456/boost_guide", "max_forks_repo_head_hexsha": "1886ec8014838717222484f0fe872ecebc324e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 202.0, "max_forks_repo_forks_event_min_datetime": "2015-03-23T16:16:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:55:48.000Z", "avg_line_length": 21.1875, "max_line_length": 69, "alphanum_fraction": 0.4124430142, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.5541555434895374}}
{"text": "#ifndef BOOST_METAPARSE_GETTING_STARTED_5_HPP\r\n#define BOOST_METAPARSE_GETTING_STARTED_5_HPP\r\n\r\n// Automatically generated header file\r\n\r\n// Definitions before section 4.2\r\n#include \"4_2.hpp\"\r\n\r\n// Definitions of section 4.2\r\n#include <boost/metaparse/transform.hpp>\r\n\r\n#include <boost/mpl/plus.hpp>\r\n\r\n#include <boost/mpl/at.hpp>\r\n\r\ntemplate <class Vector> \r\n struct eval_plus : \r\n   boost::mpl::plus< \r\n     typename boost::mpl::at_c<Vector, 0>::type, \r\n     typename boost::mpl::at_c<Vector, 2>::type \r\n   > {};\r\n\r\n// query:\r\n//   eval_plus< \r\n//     boost::mpl::vector< \r\n//       mpl_::integral_c<int, 11>, \r\n//       mpl_::char_<'+'>, \r\n//       mpl_::integral_c<int, 2> \r\n//     >>::type\r\n\r\n#include <boost/mpl/quote.hpp>\r\n\r\nusing exp_parser6 = \r\n build_parser< \r\n   transform< \r\n     sequence<int_token, plus_token, int_token>, \r\n     boost::mpl::quote1<eval_plus> \r\n   > \r\n >;\r\n\r\n// query:\r\n//    exp_parser6::apply<BOOST_METAPARSE_STRING(\"11 + 2\")>::type\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "3334744644d78cca724f5d1192b6d43ed7d07ebd", "size": 978, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/getting_started/5.hpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/getting_started/5.hpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/getting_started/5.hpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 21.2608695652, "max_line_length": 65, "alphanum_fraction": 0.6278118609, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5540548864798275}}
{"text": "#include \"dbg.hh\"\n#include <cmath>\n#include <Eigen/LU>\n\nnamespace dbg {\n\n#define KT84DBG_CPP_MAKE_EIGEN_MATRIX_FUNC_SUB1(Type, Size)\\\n    Type&                           at  (Eigen::Matrix<Type, Size, Size>& m, int i, int j) { return m(i, j); }\\\n    Eigen::Matrix<Type, Size, 1>    row (Eigen::Matrix<Type, Size, Size>& m, int i, Eigen::Matrix<Type, Size, 1>& dst) { return dst = m.row(i); }\\\n    Eigen::Matrix<Type, Size, 1>    col (Eigen::Matrix<Type, Size, Size>& m, int i, Eigen::Matrix<Type, Size, 1>& dst) { return dst = m.col(i); }\\\n    Type                            det (Eigen::Matrix<Type, Size, Size>& m) { return m.determinant(); }\\\n    Eigen::Matrix<Type, Size, Size> add (Eigen::Matrix<Type, Size, Size>& m1, Eigen::Matrix<Type, Size, Size>& m2, Eigen::Matrix<Type, Size, Size>& dst) { return dst = m1 + m2; }\\\n    Eigen::Matrix<Type, Size, Size> sub (Eigen::Matrix<Type, Size, Size>& m1, Eigen::Matrix<Type, Size, Size>& m2, Eigen::Matrix<Type, Size, Size>& dst) { return dst = m1 - m2; }\\\n    Eigen::Matrix<Type, Size, Size> mul (Eigen::Matrix<Type, Size, Size>& m1, Eigen::Matrix<Type, Size, Size>& m2, Eigen::Matrix<Type, Size, Size>& dst) { return dst = m1 * m2; }\\\n    Eigen::Matrix<Type, Size, Size> mul (Type s, Eigen::Matrix<Type, Size, Size>& m, Eigen::Matrix<Type, Size, Size>& dst) { return dst = s * m; }\\\n    Eigen::Matrix<Type, Size, Size> wsum(Eigen::Matrix<Type, Size, Size>& m1, Eigen::Matrix<Type, Size, Size>& m2, Type w1, Type w2, Eigen::Matrix<Type, Size, Size>& dst) { return dst = w1 * m1 + w2 * m2; }\\\n    Eigen::Matrix<Type, Size, Size> wsum(Eigen::Matrix<Type, Size, Size>& m1, Eigen::Matrix<Type, Size, Size>& m2, Eigen::Matrix<Type, Size, Size>& m3, Type w1, Type w2, Type w3, Eigen::Matrix<Type, Size, Size>& dst) { return dst = w1 * m1 + w2 * m2 + w3 * m3; }\\\n    Eigen::Matrix<Type, Size, Size> rand(Eigen::Matrix<Type, Size, Size>& m, int rows, int cols) { return m = Eigen::Matrix<Type, Size, Size>::Random(rows, cols); }\\\n    Eigen::Matrix<Type, Size, Size> zero(Eigen::Matrix<Type, Size, Size>& m, int rows, int cols) { return m = Eigen::Matrix<Type, Size, Size>::Zero  (rows, cols); }\\\n    Eigen::Matrix<Type, Size, Size> rand(Eigen::Matrix<Type, Size, Size>& m) { return m = Eigen::Matrix<Type, Size, Size>::Random(Size, Size); }\\\n    Eigen::Matrix<Type, Size, Size> zero(Eigen::Matrix<Type, Size, Size>& m) { return m = Eigen::Matrix<Type, Size, Size>::Zero  (Size, Size); }\\\n\n#define KT84DBG_CPP_MAKE_EIGEN_VECTOR_FUNC_SUB1(Type, Rows, Cols)\\\n    Type&                           at   (Eigen::Matrix<Type, Rows, Cols>& v, int i) { return v[i]; }\\\n    Type                            dot  (Eigen::Matrix<Type, Rows, Cols>& v1, Eigen::Matrix<Type, Rows, Cols>& v2) { return v1.dot(v2); }\\\n    double                          norm(Eigen::Matrix<Type, Rows, Cols>& v) { return std::sqrt(v.dot(v)); }\\\n    Eigen::Matrix<Type, Rows, Cols> normalize(Eigen::Matrix<Type, Rows, Cols>& v) { return v = v / norm(v); }\\\n    Eigen::Matrix<Type, Rows, Cols> cross(Eigen::Matrix<Type, Rows, Cols>& v1, Eigen::Matrix<Type, Rows, Cols>& v2, Eigen::Matrix<Type, Rows, Cols>& dst) {\\\n        dst.resize(3);\\\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        return dst;\\\n    }\\\n    Eigen::Matrix<Type, Rows, Cols> add  (Eigen::Matrix<Type, Rows, Cols>& v1, Eigen::Matrix<Type, Rows, Cols>& v2, Eigen::Matrix<Type, Rows, Cols>& dst) { return dst = v1 + v2; }\\\n    Eigen::Matrix<Type, Rows, Cols> sub  (Eigen::Matrix<Type, Rows, Cols>& v1, Eigen::Matrix<Type, Rows, Cols>& v2, Eigen::Matrix<Type, Rows, Cols>& dst) { return dst = v1 - v2; }\\\n    Eigen::Matrix<Type, Rows, Cols> mul  (Type s, Eigen::Matrix<Type, Rows, Cols>& v, Eigen::Matrix<Type, Rows, Cols>& dst) { return dst = s * v; }\\\n    /* TODO: matrix-vector multiplication */\\\n    Eigen::Matrix<Type, Rows, Cols> wsum (Eigen::Matrix<Type, Rows, Cols>& v1, Eigen::Matrix<Type, Rows, Cols>& v2, Type w1, Type w2, Eigen::Matrix<Type, Rows, Cols>& dst) { return dst = w1 * v1 + w2 * v2; }\\\n    Eigen::Matrix<Type, Rows, Cols> wsum (Eigen::Matrix<Type, Rows, Cols>& v1, Eigen::Matrix<Type, Rows, Cols>& v2, Eigen::Matrix<Type, Rows, Cols>& v3, Type w1, Type w2, Type w3, Eigen::Matrix<Type, Rows, Cols>& dst) { return dst = w1 * v1 + w2 * v2 + w3 * v3; }\\\n    Eigen::Matrix<Type, Rows, Cols> rand(Eigen::Matrix<Type, Rows, Cols>& v, int size) { return v = Eigen::Matrix<Type, Rows, Cols>::Random(size); }\\\n    Eigen::Matrix<Type, Rows, Cols> zero(Eigen::Matrix<Type, Rows, Cols>& v, int size) { return v = Eigen::Matrix<Type, Rows, Cols>::Zero  (size); }\\\n    Eigen::Matrix<Type, Rows, Cols> rand(Eigen::Matrix<Type, Rows, Cols>& v) { return v = Eigen::Matrix<Type, Rows, Cols>::Random(Rows * Cols); }\\\n    Eigen::Matrix<Type, Rows, Cols> zero(Eigen::Matrix<Type, Rows, Cols>& v) { return v = Eigen::Matrix<Type, Rows, Cols>::Zero  (Rows * Cols); }\\\n\n#define KT84DBG_CPP_MAKE_EIGEN_VECTOR_FUNC_SUB2(Type, Size)\\\n    KT84DBG_CPP_MAKE_EIGEN_VECTOR_FUNC_SUB1(Type, Size, 1)\\\n    KT84DBG_CPP_MAKE_EIGEN_VECTOR_FUNC_SUB1(Type, 1, Size)\\\n\n#define KT84DBG_CPP_MAKE_EIGEN_FUNC_SUB1(Type, Size)\\\n    KT84DBG_CPP_MAKE_EIGEN_MATRIX_FUNC_SUB1(Type, Size)\\\n    KT84DBG_CPP_MAKE_EIGEN_VECTOR_FUNC_SUB2(Type, Size)\\\n\n#define KT84DBG_CPP_MAKE_EIGEN_FUNC_SUB2(Type)\\\n    KT84DBG_CPP_MAKE_EIGEN_FUNC_SUB1(Type,  2)\\\n    KT84DBG_CPP_MAKE_EIGEN_FUNC_SUB1(Type,  3)\\\n    KT84DBG_CPP_MAKE_EIGEN_FUNC_SUB1(Type,  4)\\\n    KT84DBG_CPP_MAKE_EIGEN_FUNC_SUB1(Type, -1)\\\n\n#define KT84DBG_CPP_MAKE_STL_FUNC_SUB1(Type)\\\n    Type& at(std::vector<Type>& c, int i) { return c[i]; }\\\n\n#define KT84DBG_CPP_MAKE_VARIABLE_SUB1(Type, TypeSuffix, Size, SizeSuffix)\\\n    Eigen::Matrix<Type, Size, Size> mat##SizeSuffix##TypeSuffix [pool_size];\\\n    Eigen::Matrix<Type, Size, 1>    vec##SizeSuffix##TypeSuffix [pool_size];\\\n    Eigen::Matrix<Type, 1, Size>    cvec##SizeSuffix##TypeSuffix[pool_size];\\\n\n#define KT84DBG_CPP_MAKE_VARIABLE_SUB2(Type, TypeSuffix)\\\n    Type x##TypeSuffix[pool_size];\\\n    KT84DBG_CPP_MAKE_VARIABLE_SUB1(Type, TypeSuffix,  2, 2)\\\n    KT84DBG_CPP_MAKE_VARIABLE_SUB1(Type, TypeSuffix,  3, 3)\\\n    KT84DBG_CPP_MAKE_VARIABLE_SUB1(Type, TypeSuffix,  4, 4)\\\n    KT84DBG_CPP_MAKE_VARIABLE_SUB1(Type, TypeSuffix, -1, x)\\\n\n#define KT84DBG_CPP_MAKE_SUB1(Type, TypeSuffix)\\\n    KT84DBG_CPP_MAKE_EIGEN_FUNC_SUB2(Type)\\\n    KT84DBG_CPP_MAKE_STL_FUNC_SUB1(Type)\\\n    KT84DBG_CPP_MAKE_VARIABLE_SUB2(Type, TypeSuffix)\\\n\nKT84DBG_CPP_MAKE_SUB1(int   , i)\nKT84DBG_CPP_MAKE_SUB1(double, d)\nKT84DBG_CPP_MAKE_SUB1(float , f)\n\n#define KT84DBG_CPP_EIGEN_COPY_SUB1(TypeSrc, TypeDst, Size)\\\n    void copy(Eigen::Matrix<TypeSrc, Size, Size>& src, Eigen::Matrix<TypeDst, Size, Size>& dst) { dst = src.cast<TypeDst>(); }\\\n    void copy(Eigen::Matrix<TypeSrc, Size, 1   >& src, Eigen::Matrix<TypeDst, Size, 1   >& dst) { dst = src.cast<TypeDst>(); }\\\n    void copy(Eigen::Matrix<TypeSrc, 1   , Size>& src, Eigen::Matrix<TypeDst, 1   , Size>& dst) { dst = src.cast<TypeDst>(); }\\\n\n#define KT84DBG_CPP_EIGEN_COPY_SUB2(TypeSrc, TypeDst)\\\n    KT84DBG_CPP_EIGEN_COPY_SUB1(TypeSrc, TypeDst,  2)\\\n    KT84DBG_CPP_EIGEN_COPY_SUB1(TypeSrc, TypeDst,  3)\\\n    KT84DBG_CPP_EIGEN_COPY_SUB1(TypeSrc, TypeDst,  4)\\\n    KT84DBG_CPP_EIGEN_COPY_SUB1(TypeSrc, TypeDst, -1)\\\n\nKT84DBG_CPP_EIGEN_COPY_SUB2(int   , int   )\nKT84DBG_CPP_EIGEN_COPY_SUB2(int   , double)\nKT84DBG_CPP_EIGEN_COPY_SUB2(int   , float )\nKT84DBG_CPP_EIGEN_COPY_SUB2(double, int   )\nKT84DBG_CPP_EIGEN_COPY_SUB2(double, double)\nKT84DBG_CPP_EIGEN_COPY_SUB2(double, float )\nKT84DBG_CPP_EIGEN_COPY_SUB2(float , int   )\nKT84DBG_CPP_EIGEN_COPY_SUB2(float , double)\nKT84DBG_CPP_EIGEN_COPY_SUB2(float , float )\n\n}\n", "meta": {"hexsha": "355d0303d33f30023d245861e63ee137b892d779", "size": 7704, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/kt84/dbg.cc", "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/dbg.cc", "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/dbg.cc", "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": 72.679245283, "max_line_length": 264, "alphanum_fraction": 0.6629023884, "num_tokens": 2537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5540548823141572}}
{"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": "#include <chrono>\n#include <pcl/io/ply_io.h>\n#include <Eigen/Dense>\n\n#include \"../Edge_Extraction/Difference_Eigenvalues.h\"\n#include \"../hough3d-code/hough3dlines.h\"\n#include \"../hough3d-code/vector3d.h\"\n#include \"icp.h\"\n#include \"filter.h\"\n#include \"findTransformation.h\"\n#include \"intersection.h\"\n#include \"resultWriter.h\"\n#include \"line_descriptor.h\"\n#include \"boundingBox.h\"\n\n#include <pcl/segmentation/cpc_segmentation.h>\n\n\nusing namespace boost::system;\nnamespace filesys = boost::filesystem;\n\nbool calculateOverlappingRatio = false;\n\nint main(int argc, char *argv[]){\n\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloudA (new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloudB (new pcl::PointCloud<pcl::PointXYZ>);\n   \n    const std::string input_fileA = argv[1];\n    const std::string input_fileB = argv[2];\n    const std::string edges_output_file = argv[3];\n    const std::string lines_output_file = argv[4];\n    const std::string filtered_statistical_output_file = argv[5];\n    const std::string filtered_median_output_file = argv[6];\n    const std::string merged_output_file = argv[7];\n\n    if( pcl::io::loadPLYFile (input_fileA, *cloudA) == -1 ){\n    \n        std::cerr << \"File not found\\n\";\n        return -1;\n    }\n\n    std::cout << input_fileA << \" loaded.\\n\";\n\n    if(  pcl::io::loadPLYFile (input_fileB, *cloudB) == -1 ){\n    \n        std::cerr << \"File not found\\n\";\n        return -1;\n    }\n\n    std::cout << input_fileB << \" loaded.\\n\";\n\n    //copy original PointClouds to a buffer to use them in the final merging step\n    ResultWriter resultWriter(*cloudA, *cloudB);\n\n    std::chrono::steady_clock::time_point begin;\n    std::chrono::steady_clock::time_point end;\n \n    //3D convolve\n    begin = std::chrono::steady_clock::now();\n       applyGaussianKernel(cloudA, filtered_median_output_file, true);    \n       applyGaussianKernel(cloudB, filtered_median_output_file+\"2.ply\", true);  \n    end = std::chrono::steady_clock::now();\n    std::cout << \"3D convolve:  \" << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << \"s\" << std::endl;\n\n    //Extract edges\n    begin = std::chrono::steady_clock::now();\n        pcl::PointCloud<pcl::PointXYZ>::Ptr extractedEdgesA = extract_edges(cloudA, edges_output_file, true);   \n        pcl::PointCloud<pcl::PointXYZ>::Ptr extractedEdgesB = extract_edges(cloudB, edges_output_file+\"2.ply\", true);  \n    end = std::chrono::steady_clock::now();\n    std::cout << \"Edge extraction:  \" << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << \"s\" << std::endl;\n\n    //Filter\n    begin = std::chrono::steady_clock::now();\n        applyStatisticalOutlierFilter(extractedEdgesA, filtered_statistical_output_file, true);    \n        applyStatisticalOutlierFilter(extractedEdgesB, filtered_statistical_output_file+\"2.ply\", true);  \n    end = std::chrono::steady_clock::now();\n    std::cout << \"Filtering:  \" << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << \"s\" << std::endl;   begin = std::chrono::steady_clock::now();\n    \n    //Center pointcloud A on top of XY plane\n    \n        //Calculate bounding box\n        const size_t sizeA =  extractedEdgesA -> points.size();\n\n        BoundingBox bbA, bbB;\n     \n        bbA.setCoefficients(extractedEdgesA);\n\n        const float xShift = (bbA.minX + bbA.maxX) / 2.0;\n        const float yShift = (bbA.minY + bbA.maxY) / 2.0;\n     \n        std::cout << \"Shifting by X: \" << -xShift << \" Y:\" << -yShift << \" Z:\" << -bbA.minZ << std::endl; \n \n        //Center cloud A\n        for(size_t i = 0; i < sizeA; ++i){\n        \n            extractedEdgesA -> points[i].x -= xShift;\n            extractedEdgesA -> points[i].y -= yShift;\n            extractedEdgesA -> points[i].z -= bbA.minZ;\n\n         }\n\n        //Center cloud B\n        for(size_t i = 0; i < extractedEdgesB -> points.size(); ++i){\n    \n            extractedEdgesB -> points[i].x -= xShift;\n            extractedEdgesB -> points[i].y -= yShift;\n            extractedEdgesB -> points[i].z -= bbA.minZ;     \n\n         }\n\n        bbA.minX -= xShift;\n        bbA.maxX -= xShift;\n        bbA.minY -= yShift;\n        bbA.maxY -= yShift;\n        bbA.maxZ -= bbA.minZ;\n        bbA.minZ  = 0;\n\n    end = std::chrono::steady_clock::now();\n    std::cout << \"Centering pointclouds:  \" << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << \"s\" << std::endl; \n\n    //Hough transform\n    begin = std::chrono::steady_clock::now();\n        std::vector<Vector3d> pcA;\n        std::vector<Vector3d> pcB;\n\n        for (size_t i = 0; i < extractedEdgesA -> points.size (); ++i)\n            pcA.push_back(Vector3d(extractedEdgesA->points[i].x, extractedEdgesA->points[i].y, extractedEdgesA->points[i].z));\n\n         for (size_t i = 0; i < extractedEdgesB -> points.size (); ++i)\n            pcB.push_back(Vector3d(extractedEdgesB->points[i].x, extractedEdgesB->points[i].y, extractedEdgesB->points[i].z));       \n\n        Eigen::MatrixXf detected_linesA = hough_transform(pcA, lines_output_file, true);\n        Eigen::MatrixXf detected_linesB = hough_transform(pcB, lines_output_file+\"2.ply\", true);\n\n    end = std::chrono::steady_clock::now();\n    std::cout << \"Hough transform:  \" << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << \"s\" << std::endl;\n\n    //x y score\n    std::tuple<float, float, float> maxTranslation = std::tuple<float, float, float>(0, 0, -1);\n    float maximizingAngle;\n    \n    begin = std::chrono::steady_clock::now();\n    std::vector<float> possibleRotations = findPossibleRotations(detected_linesA, detected_linesB);\n    end = std::chrono::steady_clock::now();\n    std::cout << \"Rotation angle search:  \" << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << \"s\" << std::endl;\n\n    begin = std::chrono::steady_clock::now();\n    for(const auto angle: possibleRotations){\n\n       std::cout << \"Trying angle \" << angle << \"...\" << std::endl;    \n\n        pcl::PointCloud<pcl::PointXYZ>::Ptr tempB(new pcl::PointCloud<pcl::PointXYZ>);\n        pcl::transformPointCloud(*extractedEdgesB, *tempB, calculateTMatrix(angle, 0, 0));        \n        \n        bbB.setCoefficients(tempB);\n   \n        //bbA.print();\n        //bbB.print();\n \n        //USEFUL FOR DEBUGGING\n        //pcl::PLYWriter w;\n        //w.write(\"experimental1.ply\", *extractedEdgesA, true, false);\n        //w.write(\"experimental2.ply\", *tempB, true, false);     \n\n       std::tuple<float, float, float> translation = findTranslation(angle, detected_linesA, detected_linesB, bbA, bbB);//min_y, max_y, min_yB, max_yB ); \n        \n        if(std::get<2>(maxTranslation) < std::get<2>(translation)){\n            maxTranslation = translation;\n            maximizingAngle = angle;\n        }\n \n    }\n    end = std::chrono::steady_clock::now();\n    std::cout << \"Transformation search:  \" << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << \"s\" << std::endl;\n\n    float tX = std::get<0>(maxTranslation);\n    float tY = std::get<1>(maxTranslation);\n \n    std::cout << \"Transformation parameters:    angle: \" << maximizingAngle << \"        X: \" << tX << \"         Y: \" << tY << std::endl; \n    \n    //PerformTransformation based on line matching\n    \n    resultWriter.saveTransformedPointClouds( merged_output_file+\"original_config.ply\" );    \n \n    //BUG: sometimes these 2 lines need to be commented out, sometimes not. We suggest comparing to experimental2.ply to find out whether to comment them out or not.\n    //resultWriter.transformDynamicPointCloud( calculateTMatrix(0, -xShift, -yShift, -bbA.minZ) );\n    resultWriter.transformDynamicPointCloud( calculateTMatrix(maximizingAngle, 0, 0) );\n    //resultWriter.transformDynamicPointCloud( calculateTMatrix(0, xShift, yShift, bbA.minZ) );    \n\n    resultWriter.transformDynamicPointCloud( calculateTMatrix(0, 0, tY) ); \n    resultWriter.saveTransformedPointClouds( merged_output_file+\"rotated_ty.ply\" );   \n\n    resultWriter.transformDynamicPointCloud( calculateTMatrix(0, tX, 0) ); \n    resultWriter.saveTransformedPointClouds( merged_output_file+\"rotated_ty_tx.ply\" ); \n\n    resultWriter.saveTransformedPointClouds( merged_output_file+\"before_icp.ply\" );    \n \n    pcl::transformPointCloud(*extractedEdgesA, *extractedEdgesA, calculateTMatrix(0, xShift, yShift, bbA.minZ) );\n    pcl::transformPointCloud(*extractedEdgesB, *extractedEdgesB, calculateTMatrix(maximizingAngle, tX + xShift, tY + yShift, bbA.minZ) );\n   \n\n    IntersectionInterface ii;\n    ii.setStaticPointCloud(extractedEdgesA);\n    ii.setDynamicPointCloud(extractedEdgesB);\n    pcl::CropHull<pcl::PointXYZ> intersectionFilter = ii.getIntersectionFilter();\n\n    pcl::PointCloud<pcl::PointXYZ>::Ptr iA(new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::PointCloud<pcl::PointXYZ>::Ptr iB(new pcl::PointCloud<pcl::PointXYZ>);\n\n    intersectionFilter.setInputCloud( resultWriter.getStaticPointCloud() );\n    intersectionFilter.filter(*iA);\n\n    intersectionFilter.setInputCloud( resultWriter.getDynamicPointCloud() );\n    intersectionFilter.filter(*iB);\n \n    pcl::PLYWriter w;\n    //USEFUL FOR DEBUGGING\n    //w.write(\"hullA.ply\", *iA, true, false);\n    //w.write(\"hullB.ply\", *iB, true, false);\n    //std::cout << \"hull files written\" << std::endl; \n\n    std::cout << \"Running ICP matching...\" << std::endl;\n    begin = std::chrono::steady_clock::now();\n        Eigen::Matrix4f icpCorrectionTransformation = registerPointClouds(iA, iB);\n    end = std::chrono::steady_clock::now();\n    std::cout << \"ICP matching finished:  \" << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << \"s\" << std::endl;\n    \n    resultWriter.transformDynamicPointCloud( icpCorrectionTransformation );\n    resultWriter.saveTransformedPointClouds( merged_output_file );    \n    std::cout << \"ICP corrected pointcloud written\" << std::endl; \n\n    if(calculateOverlappingRatio){\n\n        std::cout << \"Calculating overlapping ratio...\" << std::endl;\n\n        pcl::PointCloud<pcl::PointXYZ>::Ptr correctedEdgesB(new pcl::PointCloud<pcl::PointXYZ>);\n        pcl::transformPointCloud(*extractedEdgesB, *correctedEdgesB, icpCorrectionTransformation);\n \n        IntersectionInterface iiOverlap;\n        iiOverlap.setStaticPointCloud(extractedEdgesA);\n        iiOverlap.setDynamicPointCloud(correctedEdgesB);\n        double intersectionVolume = iiOverlap.getIntersectionHull().getTotalVolume();\n\n        pcl::ConvexHull<pcl::PointXYZ> hullTotal;\n\n        pcl::PointCloud<pcl::PointXYZ>::Ptr mergedPC(new pcl::PointCloud<pcl::PointXYZ>);\n        pcl::transformPointCloud(*cloudB, *mergedPC, icpCorrectionTransformation * calculateTMatrix(maximizingAngle, tX + xShift, tY + yShift, bbA.minZ));\n       \n        *mergedPC += *cloudA;\n\n        hullTotal.setInputCloud(mergedPC);\n        double totalVolume = hullTotal.getTotalVolume();\n\n        std::cout << \"Intersection volume: \" << intersectionVolume << std::endl;\n        std::cout << \"Total volume: \" << totalVolume << std::endl;\n\n        std::cout << \"Overlapping ratio: \" << intersectionVolume / totalVolume << std::endl;\n\n    }\n\n\n}\n", "meta": {"hexsha": "8722bd912b154fa25382d730a9ccf87c94cd48b9", "size": 11081, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/main.cc", "max_stars_repo_name": "Milos9304/LowOverlapPCRegistration", "max_stars_repo_head_hexsha": "fd9d7d3cb31978b700dc0160bc0fa022f02762f2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-11-01T11:46:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T12:07:47.000Z", "max_issues_repo_path": "src/main.cc", "max_issues_repo_name": "Milos9304/LowOverlapPCRegistration", "max_issues_repo_head_hexsha": "fd9d7d3cb31978b700dc0160bc0fa022f02762f2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cc", "max_forks_repo_name": "Milos9304/LowOverlapPCRegistration", "max_forks_repo_head_hexsha": "fd9d7d3cb31978b700dc0160bc0fa022f02762f2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-04-22T07:19:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T12:43:05.000Z", "avg_line_length": 41.9734848485, "max_line_length": 169, "alphanum_fraction": 0.6533706344, "num_tokens": 2903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5540032330920753}}
{"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\u306e\u6e2c\u5b9a\u5024\u304b\u3089\u91cd\u529b\u306e\u5f71\u97ff\u3092\u53d6\u308a\u9664\u304f\u30d5\u30a3\u30eb\u30bf\n */\nclass GravityFilter {\npublic:\n    /**\n     * @brief \u5185\u90e8\u72b6\u614b\u3092\u30ea\u30bb\u30c3\u30c8\u3059\u308b\n     */\n    void reset(void) {\n        _initialized = false;\n    }\n\n    /**\n     * @brief \u30d5\u30a3\u30eb\u30bf\u306b\u65b0\u305f\u306a\u5165\u529b\u3092\u4e0e\u3048\u3066\u51fa\u529b\u3092\u66f4\u65b0\u3059\u308b\n     * @param accel \u52a0\u901f\u5ea6\u30bb\u30f3\u30b5\u30fc\u306e\u6e2c\u5b9a\u5024\n     * @param gyro \u30b8\u30e3\u30a4\u30ed\u30b9\u30b3\u30fc\u30d7\u306e\u6e2c\u5b9a\u5024\n     */\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            // \u91cd\u529b\u52a0\u901f\u5ea6\u30d9\u30af\u30c8\u30eb\u3092\u521d\u671f\u5316\u3059\u308b\n            _initialized = true;\n            _gravity = accel;\n            _gyro_error_integ = Vector3f::Zero();\n        }\n\n        // \u52a0\u901f\u5ea6\u30d9\u30af\u30c8\u30eb\u3068\u91cd\u529b\u52a0\u901f\u5ea6\u30d9\u30af\u30c8\u30eb\u306e\u6210\u3059\u89d2\u5ea6\u3092\u6c42\u3081\u308b\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            // \u91cd\u529b\u304c\u7570\u69d8\u306b\u5c0f\u3055\u3044\u3068\u304d\u306f\u52a0\u901f\u5ea6\u30bb\u30f3\u30b5\u30fc\u306b\u3088\u308b\u89d2\u901f\u5ea6\u306e\u88dc\u6b63\u3092\u6e1b\u3089\u3059\n            gyro_error = Vector3f::Zero();\n            _gyro_error_integ *= fpu::max(1.0f - 1.0f / IMU_OUTPUT_RATE, 0.0f);\n        }\n\n        // \u89d2\u901f\u5ea6\u3092\u52a0\u901f\u5ea6\u30bb\u30f3\u30b5\u30fc\u304b\u3089\u5f97\u305f\u89d2\u5ea6\u8aa4\u5dee\u3067\u88dc\u6b63\u3059\u308b\n        Vector3f delta_omega = GYRO_GAIN_P * gyro_error + GYRO_GAIN_I * _gyro_error_integ;\n        _compensated_gyro = gyro + delta_omega;\n\n        // \u91cd\u529b\u30d9\u30af\u30c8\u30eb\u3092\u56de\u8ee2\u3059\u308b\n        Matrix3f Rt = rotationMatrixTransposed(_compensated_gyro * (1.0f / IMU_OUTPUT_RATE));\n        _gravity = Rt * _gravity;\n\n        // \u91cd\u529b\u52a0\u901f\u5ea6\u30d9\u30af\u30c8\u30eb\u306e\u5927\u304d\u3055\u3092\u5f90\u3005\u306b\u52a0\u901f\u5ea6\u306e\u5927\u304d\u3055\u306b\u8fd1\u3065\u3051\u308b\n        // \u91cd\u529b\u304c\u5c0f\u3055\u3044\u3068\u304d\u306f\u5927\u304d\u3055\u3067\u306f\u306a\u304f\u30d9\u30af\u30c8\u30eb\u305d\u306e\u3082\u306e\u3092\u4f7f\u3063\u3066\u88dc\u6b63\u3059\u308b\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        // \u52a0\u901f\u5ea6\u30d9\u30af\u30c8\u30eb\u304b\u3089\u91cd\u529b\u306e\u5f71\u97ff\u3092\u9664\u53bb\u3059\u308b\n        _compensated_accel = accel - _gravity;\n    }\n\n    /**\n     * @brief \u91cd\u529b\u52a0\u901f\u5ea6\u30d9\u30af\u30c8\u30eb(\u306e\u53cd\u529b)\u3092\u53d6\u5f97\u3059\u308b\n     * @return \u91cd\u529b\u52a0\u901f\u5ea6\u30d9\u30af\u30c8\u30eb(\u306e\u53cd\u529b) X, Y, Z [m/s^2]\n     */\n    const Eigen::Vector3f& gravity(void) const {\n        return _gravity;\n    }\n\n    /**\n     * @brief \u91cd\u529b\u3092\u9664\u53bb\u6e08\u307f\u306e\u52a0\u901f\u5ea6\u3092\u53d6\u5f97\u3059\u308b\n     * @return \u52a0\u901f\u5ea6 X, Y, Z [m/s^2]\n     */\n    const Eigen::Vector3f& acceleration(void) const {\n        return _compensated_accel;\n    }\n\n    /**\n     * @brief \u91cd\u529b\u3067\u88dc\u6b63\u6e08\u307f\u306e\u89d2\u901f\u5ea6\u3092\u53d6\u5f97\u3059\u308b\n     * @return \u89d2\u901f\u5ea6 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": "/****************************************************************************\n * Copyright (c) 2012-2020 by the DataTransferKit authors                   *\n * All rights reserved.                                                     *\n *                                                                          *\n * This file is part of the DataTransferKit library. DataTransferKit is     *\n * distributed under a BSD 3-clause license. For the licensing terms see    *\n * the LICENSE file in the top-level directory.                             *\n *                                                                          *\n * SPDX-License-Identifier: BSD-3-Clause                                    *\n ****************************************************************************/\n\n#include <Teuchos_UnitTestHarness.hpp>\n\n#include <Kokkos_Core.hpp>\n\n#include <DTK_CompactlySupportedRadialBasisFunctions.hpp>\n\n#include <boost/math/tools/polynomial.hpp>\n#include <boost/math/tools/rational.hpp>\n\ntemplate <typename DeviceType, typename RadialBasisFunction>\nvoid check_polynomial( boost::math::tools::polynomial<double> const &poly,\n                       std::vector<double> const &radii,\n                       RadialBasisFunction const &rbf,\n                       Teuchos::FancyOStream &out, bool &success )\n{\n    using ExecutionSpace = typename DeviceType::execution_space;\n    int const n = radii.size();\n    Kokkos::View<double *, DeviceType> r( \"radii\", n );\n    auto r_host = Kokkos::create_mirror_view( r );\n    for ( int i = 0; i < n; ++i )\n        r_host( i ) = radii[i];\n    Kokkos::deep_copy( r, r_host );\n\n    std::vector<double> p = poly.data();\n    std::vector<double> values;\n    for ( auto const &x : radii )\n        values.push_back(\n            boost::math::tools::evaluate_polynomial( p.data(), x, p.size() ) );\n\n    Kokkos::View<double *, DeviceType> v( \"values\", n );\n    Kokkos::parallel_for( \"evaluate\",\n                          Kokkos::RangePolicy<ExecutionSpace>( 0, n ),\n                          KOKKOS_LAMBDA( int i ) { v( i ) = rbf( r( i ) ); } );\n    Kokkos::fence();\n    auto v_host = Kokkos::create_mirror_view( v );\n    Kokkos::deep_copy( v_host, v );\n    double const relative_tolerance = 1.0e-8;\n    TEST_COMPARE_FLOATING_ARRAYS( v_host, values, relative_tolerance );\n}\n\nTEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( CompactlySupportedRadialBasisFunctions,\n                                   polynomial_rbf, DeviceType )\n{\n    int const n = 10;\n    std::vector<double> r( n );\n    for ( int i = 0; i < n; ++i )\n        r[i] = static_cast<double>( i ) / n;\n\n    check_polynomial<DeviceType>(\n        boost::math::tools::pow(\n            boost::math::tools::polynomial<double>{1.0, -1.0}, 2 ),\n        r, DataTransferKit::Wendland<0>(), out, success );\n\n    check_polynomial<DeviceType>(\n        boost::math::tools::pow(\n            boost::math::tools::polynomial<double>{1.0, -1.0}, 4 ) *\n            boost::math::tools::polynomial<double>{1.0, 4.0},\n        r, DataTransferKit::Wendland<2>(), out, success );\n\n    check_polynomial<DeviceType>(\n        boost::math::tools::pow(\n            boost::math::tools::polynomial<double>{1.0, -1.0}, 6 ) *\n            boost::math::tools::polynomial<double>{3.0, 18.0, 35.0},\n        r, DataTransferKit::Wendland<4>(), out, success );\n\n    check_polynomial<DeviceType>(\n        boost::math::tools::pow(\n            boost::math::tools::polynomial<double>{1.0, -1.0}, 8 ) *\n            boost::math::tools::polynomial<double>{1.0, 8.0, 25.0, 32.0},\n        r, DataTransferKit::Wendland<6>(), out, success );\n\n    check_polynomial<DeviceType>(\n        boost::math::tools::pow(\n            boost::math::tools::polynomial<double>{1.0, -1.0}, 4 ) *\n            boost::math::tools::polynomial<double>{4.0, 16.0, 12.0, 3.0},\n        r, DataTransferKit::Wu<2>(), out, success );\n\n    check_polynomial<DeviceType>(\n        boost::math::tools::pow(\n            boost::math::tools::polynomial<double>{1.0, -1.0}, 6 ) *\n            boost::math::tools::polynomial<double>{6.0, 36.0, 82.0, 72.0, 30.0,\n                                                   5.0},\n        r, DataTransferKit::Wu<4>(), out, success );\n}\n\nTEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( CompactlySupportedRadialBasisFunctions,\n                                   wrap_rbf, DeviceType )\n{\n    struct X\n    {\n        KOKKOS_INLINE_FUNCTION double operator()( double x ) const { return x; }\n    };\n    DataTransferKit::RadialBasisFunction<X> rbf( 2. );\n    TEST_EQUALITY( rbf( 1. ), .5 );\n    TEST_EQUALITY( rbf( 2. ), 1. );\n    TEST_EQUALITY( rbf( 4. ), 2. );\n}\n\n// Include the test macros.\n#include \"DataTransferKit_ETIHelperMacros.h\"\n\n// Create the test group\n#define UNIT_TEST_GROUP( NODE )                                                \\\n    using DeviceType##NODE = typename NODE::device_type;                       \\\n    TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT(                                      \\\n        CompactlySupportedRadialBasisFunctions, polynomial_rbf,                \\\n        DeviceType##NODE )                                                     \\\n    TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT(                                      \\\n        CompactlySupportedRadialBasisFunctions, wrap_rbf, DeviceType##NODE )\n// Demangle the types\nDTK_ETI_MANGLING_TYPEDEFS()\n\n// Instantiate the tests\nDTK_INSTANTIATE_N( UNIT_TEST_GROUP )\n", "meta": {"hexsha": "bd8af8236a439eca36159f6dc957f0a21fc9bcab", "size": 5346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/Meshfree/test/tstCompactlySupportedRadialBasisFunctions.cpp", "max_stars_repo_name": "Rombur/DataTransferKit", "max_stars_repo_head_hexsha": "5c674720d13b89dd5f23f51285f5c613b6298147", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 51.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T15:41:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T12:35:39.000Z", "max_issues_repo_path": "packages/Meshfree/test/tstCompactlySupportedRadialBasisFunctions.cpp", "max_issues_repo_name": "Rombur/DataTransferKit", "max_issues_repo_head_hexsha": "5c674720d13b89dd5f23f51285f5c613b6298147", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 552.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T22:06:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T15:39:40.000Z", "max_forks_repo_path": "packages/Meshfree/test/tstCompactlySupportedRadialBasisFunctions.cpp", "max_forks_repo_name": "Rombur/DataTransferKit", "max_forks_repo_head_hexsha": "5c674720d13b89dd5f23f51285f5c613b6298147", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T04:59:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-27T16:56:55.000Z", "avg_line_length": 42.4285714286, "max_line_length": 80, "alphanum_fraction": 0.5409652076, "num_tokens": 1337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5538169781634856}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <math/prim/mat/prob/vector_rng_test_helper.hpp>\n#include <limits>\n#include <vector>\n\nclass NormalTestRig : public VectorRealRNGTestRig {\n public:\n  /*\n   * The default NormalTestRig constructor initializes the TestRig with\n   * valid and invalid parameters for a random number generator with two\n   * arguments.\n   */\n  NormalTestRig()\n      : VectorRealRNGTestRig(\n            10000,  // Number of samples used for quantiles tests\n            10,     // Length of vectors for vectorization tests\n            {-2.5, -1.7, -0.1, 0.0, 2.0, 5.8},  // Valid values for p1\n            {-3, -2, -1, 0, 2, 6},              // Valid integer values for p1\n            {}, {}, {0.1, 1.0, 2.5, 4.0}, {1, 2, 3, 4}, {-2.7, -1.5, -0.5, 0.0},\n            {-3, -2, -1, 0}) {}\n\n  /*\n   * This function wraps up the random number generator for testing.\n   *\n   * The tested rng can have up to three parameters. Any unused parameters can\n   * be ignored.\n   */\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& mean, const T2& sd, const T3& unused,\n                        T_rng& rng) const {\n    return stan::math::normal_rng(mean, sd, rng);\n  }\n\n  /*\n   * This function builds the quantiles that we will supply to\n   * assert_matches_quantiles to test the normal_rng\n   */\n  std::vector<double> generate_quantiles(double mu, double sigma,\n                                         double unused) const {\n    std::vector<double> quantiles;\n    double K = stan::math::round(2 * std::pow(N_, 0.4));\n    boost::math::normal_distribution<> dist(mu, sigma);\n\n    for (int i = 1; i < K; ++i) {\n      double frac = i / K;\n      quantiles.push_back(quantile(dist, frac));\n    }\n    quantiles.push_back(std::numeric_limits<double>::max());\n\n    return quantiles;\n  }\n};\n\nTEST(ProbDistributionsNormal, errorCheck) {\n  /*\n   * This test verifies that normal_rng throws errors in the right places.\n   *\n   * It does so by calling test_rig::generate_samples for all possible\n   * combinations of calling arguments.\n   */\n  check_dist_throws_all_types(NormalTestRig());\n}\n\nTEST(ProbDistributionsNormal, distributionTest) {\n  /*\n   * This test checks that the normal_rng is actually generating numbers from\n   * the correct distributions. Quantiles are computed from\n   * test_rig::generate_quantiles\n   *\n   * It does so for all possible combinations of calling arguments.\n   */\n  check_quantiles_real_real(NormalTestRig());\n}\n", "meta": {"hexsha": "28de9b988cea4ba1139ed4cbff3b8a16e4cd9a1f", "size": 2553, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/mat/prob/normal_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/prim/mat/prob/normal_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/prim/mat/prob/normal_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5921052632, "max_line_length": 80, "alphanum_fraction": 0.6447316882, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5537448903812773}}
{"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": "/* ----------------------------------------------------------------------------\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    testRegularHessianFactor.cpp\n * @author  Frank Dellaert\n * @date    March 4, 2014\n */\n\n#include <gtsam/linear/RegularHessianFactor.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/VectorValues.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/assign/std/map.hpp>\n#include <boost/assign/list_of.hpp>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace boost::assign;\n\n/* ************************************************************************* */\nTEST(RegularHessianFactor, Constructors)\n{\n  // First construct a regular JacobianFactor\n  // 0.5*|x0 + x1 + x3 - [1;2]|^2 = 0.5*|A*x-b|^2, with A=[I I I]\n  Matrix A1 = I_2x2, A2 = I_2x2, A3 = I_2x2;\n  Vector2 b(1,2);\n  vector<pair<Key, Matrix> > terms;\n  terms += make_pair(0, A1), make_pair(1, A2), make_pair(3, A3);\n  RegularJacobianFactor<2> jf(terms, b);\n\n  // Test conversion from JacobianFactor\n  RegularHessianFactor<2> factor(jf);\n\n  // 0.5*|A*x-b|^2 = 0.5*(Ax-b)'*(Ax-b) = 0.5*x'*A'A*x - x'*A'b + 0.5*b'*b\n  // Compare with comment in HessianFactor: E(x) = 0.5 x^T G x - x^T g + 0.5 f\n  // Hence G = I6, g A'*b = [b;b;b], and f = b'*b = 1+4 = 5\n  Matrix G11 = I_2x2;\n  Matrix G12 = I_2x2;\n  Matrix G13 = I_2x2;\n\n  Matrix G22 = I_2x2;\n  Matrix G23 = I_2x2;\n\n  Matrix G33 = I_2x2;\n\n  Vector2 g1 = b, g2 = b, g3 = b;\n\n  double f = 5;\n\n  // Test ternary constructor\n  RegularHessianFactor<2> factor2(0, 1, 3, G11, G12, G13, g1, G22, G23, g2, G33, g3, f);\n  EXPECT(assert_equal(factor,factor2));\n\n  // Test n-way constructor\n  vector<Key> keys; keys += 0, 1, 3;\n  vector<Matrix> Gs; Gs += G11, G12, G13, G22, G23, G33;\n  vector<Vector> gs; gs += g1, g2, g3;\n  RegularHessianFactor<2> factor3(keys, Gs, gs, f);\n  EXPECT(assert_equal(factor, factor3));\n\n  // Test constructor from Gaussian Factor Graph\n  GaussianFactorGraph gfg;\n  gfg += jf;\n  RegularHessianFactor<2> factor4(gfg);\n  EXPECT(assert_equal(factor, factor4));\n  GaussianFactorGraph gfg2;\n  gfg2 += factor;\n  RegularHessianFactor<2> factor5(gfg);\n  EXPECT(assert_equal(factor, factor5));\n\n  // Test constructor from Information matrix\n  Matrix info = factor.augmentedInformation();\n  vector<size_t> dims; dims += 2, 2, 2;\n  SymmetricBlockMatrix sym(dims, info, true);\n  RegularHessianFactor<2> factor6(keys, sym);\n  EXPECT(assert_equal(factor, factor6));\n\n  // multiplyHessianAdd:\n  {\n  // brute force\n  Matrix AtA = factor.information();\n  HessianFactor::const_iterator i1 = factor.begin();\n  HessianFactor::const_iterator i2 = i1 + 1;\n  Vector X(6); X << 1,2,3,4,5,6;\n  Vector Y(6); Y << 9, 12, 9, 12, 9, 12;\n  EXPECT(assert_equal(Y,AtA*X));\n\n  VectorValues x = map_list_of<Key, Vector>\n    (0, Vector2(1,2))\n    (1, Vector2(3,4))\n    (3, Vector2(5,6));\n\n  VectorValues expected;\n  expected.insert(0, Y.segment<2>(0));\n  expected.insert(1, Y.segment<2>(2));\n  expected.insert(3, Y.segment<2>(4));\n\n  // VectorValues version\n  double alpha = 1.0;\n  VectorValues actualVV;\n  actualVV.insert(0, Vector2::Zero());\n  actualVV.insert(1, Vector2::Zero());\n  actualVV.insert(3, Vector2::Zero());\n  factor.multiplyHessianAdd(alpha, x, actualVV);\n  EXPECT(assert_equal(expected, actualVV));\n\n  // RAW ACCESS\n  Vector expected_y(8); expected_y << 9, 12, 9, 12, 0, 0, 9, 12;\n  Vector fast_y = Vector8::Zero();\n  double xvalues[8] = {1,2,3,4,0,0,5,6};\n  factor.multiplyHessianAdd(alpha, xvalues, fast_y.data());\n  EXPECT(assert_equal(expected_y, fast_y));\n\n  // now, do it with non-zero y\n  factor.multiplyHessianAdd(alpha, xvalues, fast_y.data());\n  EXPECT(assert_equal(2*expected_y, fast_y));\n\n  // check some expressions\n  EXPECT(assert_equal(G12,factor.info().aboveDiagonalBlock(i1 - factor.begin(), i2 - factor.begin())));\n  EXPECT(assert_equal(G22,factor.info().diagonalBlock(i2 - factor.begin())));\n  }\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "1618451f31a490d335a6920d7692989e6f61ef6b", "size": 4432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/tests/testRegularHessianFactor.cpp", "max_stars_repo_name": "alexhagiopol/GTSAM", "max_stars_repo_head_hexsha": "c397fac199d0202c7abb1cd8e6005731658f56e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 105.0, "max_stars_repo_stars_event_min_datetime": "2017-12-02T14:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T18:20:25.000Z", "max_issues_repo_path": "trunk/gtsam/linear/tests/testRegularHessianFactor.cpp", "max_issues_repo_name": "shaolinbit/PPP-BayesTree", "max_issues_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-04T15:15:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-08T08:51:02.000Z", "max_forks_repo_path": "trunk/gtsam/linear/tests/testRegularHessianFactor.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": 31.8848920863, "max_line_length": 103, "alphanum_fraction": 0.6146209386, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.5537350093215924}}
{"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 * @file tests/tree_test.cpp\n *\n * Tests for tree-building methods.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/core/tree/bounds.hpp>\n#include <mlpack/core/tree/binary_space_tree.hpp>\n#include <mlpack/core/metrics/lmetric.hpp>\n#include <mlpack/core/metrics/mahalanobis_distance.hpp>\n#include <mlpack/core/tree/cover_tree/cover_tree.hpp>\n#include <mlpack/core/tree/rectangle_tree.hpp>\n\n#include <queue>\n#include <stack>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::math;\nusing namespace mlpack::tree;\nusing namespace mlpack::metric;\nusing namespace mlpack::bound;\n\nBOOST_AUTO_TEST_SUITE(TreeTest);\n\n/**\n * Ensure that a bound, by default, is empty and has no dimensionality.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundEmptyConstructor)\n{\n  HRectBound<EuclideanDistance> b;\n\n  BOOST_REQUIRE_EQUAL((int) b.Dim(), 0);\n  BOOST_REQUIRE_EQUAL(b.MinWidth(), 0.0);\n}\n\n/**\n * Ensure that when we specify the dimensionality in the constructor, it is\n * correct, and the bounds are all the empty set.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundDimConstructor)\n{\n  HRectBound<EuclideanDistance> b(2); // We'll do this with 2 and 5 dimensions.\n\n  BOOST_REQUIRE_EQUAL(b.Dim(), 2);\n  BOOST_REQUIRE_SMALL(b[0].Width(), 1e-5);\n  BOOST_REQUIRE_SMALL(b[1].Width(), 1e-5);\n\n  b = HRectBound<EuclideanDistance>(5);\n\n  BOOST_REQUIRE_EQUAL(b.Dim(), 5);\n  BOOST_REQUIRE_SMALL(b[0].Width(), 1e-5);\n  BOOST_REQUIRE_SMALL(b[1].Width(), 1e-5);\n  BOOST_REQUIRE_SMALL(b[2].Width(), 1e-5);\n  BOOST_REQUIRE_SMALL(b[3].Width(), 1e-5);\n  BOOST_REQUIRE_SMALL(b[4].Width(), 1e-5);\n\n  BOOST_REQUIRE_EQUAL(b.MinWidth(), 0.0);\n}\n\n/**\n * Test the copy constructor.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundCopyConstructor)\n{\n  HRectBound<EuclideanDistance> b(2);\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(2.0, 3.0);\n  b.MinWidth() = 0.5;\n\n  HRectBound<EuclideanDistance> c(b);\n\n  BOOST_REQUIRE_EQUAL(c.Dim(), 2);\n  BOOST_REQUIRE_SMALL(c[0].Lo(), 1e-5);\n  BOOST_REQUIRE_CLOSE(c[0].Hi(), 2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(c[1].Lo(), 2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(c[1].Hi(), 3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MinWidth(), 0.5, 1e-5);\n}\n\n/**\n * Test the assignment operator.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundAssignmentOperator)\n{\n  HRectBound<EuclideanDistance> b(2);\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(2.0, 3.0);\n  b.MinWidth() = 0.5;\n\n  HRectBound<EuclideanDistance> c(4);\n\n  c = b;\n\n  BOOST_REQUIRE_EQUAL(c.Dim(), 2);\n  BOOST_REQUIRE_SMALL(c[0].Lo(), 1e-5);\n  BOOST_REQUIRE_CLOSE(c[0].Hi(), 2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(c[1].Lo(), 2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(c[1].Hi(), 3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MinWidth(), 0.5, 1e-5);\n}\n\n/**\n * Test that clearing the dimensions resets the bound to empty.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundClear)\n{\n  HRectBound<EuclideanDistance> b(2); // We'll do this with two dimensions only.\n\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(2.0, 4.0);\n  b.MinWidth() = 1.0;\n\n  // Now we just need to make sure that we clear the range.\n  b.Clear();\n\n  BOOST_REQUIRE_SMALL(b[0].Width(), 1e-5);\n  BOOST_REQUIRE_SMALL(b[1].Width(), 1e-5);\n  BOOST_REQUIRE_SMALL(b.MinWidth(), 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(HRectBoundMoveConstructor)\n{\n  HRectBound<EuclideanDistance> b(2);\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(2.0, 4.0);\n  b.MinWidth() = 1.0;\n\n  HRectBound<EuclideanDistance> b2(std::move(b));\n\n  BOOST_REQUIRE_EQUAL(b.Dim(), 0);\n  BOOST_REQUIRE_EQUAL(b2.Dim(), 2);\n\n  BOOST_REQUIRE_EQUAL(b.MinWidth(), 0.0);\n  BOOST_REQUIRE_EQUAL(b2.MinWidth(), 1.0);\n\n  BOOST_REQUIRE_SMALL(b2[0].Lo(), 1e-5);\n  BOOST_REQUIRE_CLOSE(b2[0].Hi(), 2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b2[1].Lo(), 2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b2[1].Hi(), 4.0, 1e-5);\n}\n\n/**\n * Ensure that we get the correct center for our bound.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundCenter)\n{\n  // Create a simple 3-dimensional bound.\n  HRectBound<EuclideanDistance> b(3);\n\n  b[0] = Range(0.0, 5.0);\n  b[1] = Range(-2.0, -1.0);\n  b[2] = Range(-10.0, 50.0);\n\n  arma::vec center;\n\n  b.Center(center);\n\n  BOOST_REQUIRE_EQUAL(center.n_elem, 3);\n  BOOST_REQUIRE_CLOSE(center[0], 2.5, 1e-5);\n  BOOST_REQUIRE_CLOSE(center[1], -1.5, 1e-5);\n  BOOST_REQUIRE_CLOSE(center[2], 20.0, 1e-5);\n}\n\n/**\n * Ensure the volume calculation is correct.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundVolume)\n{\n  // Create a simple 3-dimensional bound.\n  HRectBound<EuclideanDistance> b(3);\n\n  b[0] = Range(0.0, 5.0);\n  b[1] = Range(-2.0, -1.0);\n  b[2] = Range(-10.0, 50.0);\n\n  BOOST_REQUIRE_CLOSE(b.Volume(), 300.0, 1e-5);\n}\n\n/**\n * Ensure that we calculate the correct minimum distance between a point and a\n * bound.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundMinDistancePoint)\n{\n  // We'll do the calculation in five dimensions, and we'll use three cases for\n  // the point: point is outside the bound; point is on the edge of the bound;\n  // point is inside the bound.  In the latter two cases, the distance should be\n  // zero.\n  HRectBound<EuclideanDistance> b(5);\n\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(1.0, 5.0);\n  b[2] = Range(-2.0, 2.0);\n  b[3] = Range(-5.0, -2.0);\n  b[4] = Range(1.0, 2.0);\n\n  arma::vec point = \"-2.0 0.0 10.0 3.0 3.0\";\n\n  // This will be the Euclidean distance.\n  BOOST_REQUIRE_CLOSE(b.MinDistance(point), sqrt(95.0), 1e-5);\n\n  point = \"2.0 5.0 2.0 -5.0 1.0\";\n\n  BOOST_REQUIRE_SMALL(b.MinDistance(point), 1e-5);\n\n  point = \"1.0 2.0 0.0 -2.0 1.5\";\n\n  BOOST_REQUIRE_SMALL(b.MinDistance(point), 1e-5);\n}\n\n/**\n * Ensure that we calculate the correct minimum distance between a bound and\n * another bound.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundMinDistanceBound)\n{\n  // We'll do the calculation in five dimensions, and we can use six cases.\n  // The other bound is completely outside the bound; the other bound is on the\n  // edge of the bound; the other bound partially overlaps the bound; the other\n  // bound fully overlaps the bound; the other bound is entirely inside the\n  // bound; the other bound entirely envelops the bound.\n  HRectBound<EuclideanDistance> b(5);\n\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(1.0, 5.0);\n  b[2] = Range(-2.0, 2.0);\n  b[3] = Range(-5.0, -2.0);\n  b[4] = Range(1.0, 2.0);\n\n  HRectBound<EuclideanDistance> c(5);\n\n  // The other bound is completely outside the bound.\n  c[0] = Range(-5.0, -2.0);\n  c[1] = Range(6.0, 7.0);\n  c[2] = Range(-2.0, 2.0);\n  c[3] = Range(2.0, 5.0);\n  c[4] = Range(3.0, 4.0);\n\n  BOOST_REQUIRE_CLOSE(b.MinDistance(c), sqrt(22.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MinDistance(b), sqrt(22.0), 1e-5);\n\n  // The other bound is on the edge of the bound.\n  c[0] = Range(-2.0, 0.0);\n  c[1] = Range(0.0, 1.0);\n  c[2] = Range(-3.0, -2.0);\n  c[3] = Range(-10.0, -5.0);\n  c[4] = Range(2.0, 3.0);\n\n  BOOST_REQUIRE_SMALL(b.MinDistance(c), 1e-5);\n  BOOST_REQUIRE_SMALL(c.MinDistance(b), 1e-5);\n\n  // The other bound partially overlaps the bound.\n  c[0] = Range(-2.0, 1.0);\n  c[1] = Range(0.0, 2.0);\n  c[2] = Range(-2.0, 2.0);\n  c[3] = Range(-8.0, -4.0);\n  c[4] = Range(0.0, 4.0);\n\n  BOOST_REQUIRE_SMALL(b.MinDistance(c), 1e-5);\n  BOOST_REQUIRE_SMALL(c.MinDistance(b), 1e-5);\n\n  // The other bound fully overlaps the bound.\n  BOOST_REQUIRE_SMALL(b.MinDistance(b), 1e-5);\n  BOOST_REQUIRE_SMALL(c.MinDistance(c), 1e-5);\n\n  // The other bound is entirely inside the bound / the other bound entirely\n  // envelops the bound.\n  c[0] = Range(-1.0, 3.0);\n  c[1] = Range(0.0, 6.0);\n  c[2] = Range(-3.0, 3.0);\n  c[3] = Range(-7.0, 0.0);\n  c[4] = Range(0.0, 5.0);\n\n  BOOST_REQUIRE_SMALL(b.MinDistance(c), 1e-5);\n  BOOST_REQUIRE_SMALL(c.MinDistance(b), 1e-5);\n\n  // Now we must be sure that the minimum distance to itself is 0.\n  BOOST_REQUIRE_SMALL(b.MinDistance(b), 1e-5);\n  BOOST_REQUIRE_SMALL(c.MinDistance(c), 1e-5);\n}\n\n/**\n * Ensure that we calculate the correct maximum distance between a bound and a\n * point.  This uses the same test cases as the MinDistance test.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundMaxDistancePoint)\n{\n  // We'll do the calculation in five dimensions, and we'll use three cases for\n  // the point: point is outside the bound; point is on the edge of the bound;\n  // point is inside the bound.  In the latter two cases, the distance should be\n  // zero.\n  HRectBound<EuclideanDistance> b(5);\n\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(1.0, 5.0);\n  b[2] = Range(-2.0, 2.0);\n  b[3] = Range(-5.0, -2.0);\n  b[4] = Range(1.0, 2.0);\n\n  arma::vec point = \"-2.0 0.0 10.0 3.0 3.0\";\n\n  // This will be the Euclidean distance.\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(point), sqrt(253.0), 1e-5);\n\n  point = \"2.0 5.0 2.0 -5.0 1.0\";\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(point), sqrt(46.0), 1e-5);\n\n  point = \"1.0 2.0 0.0 -2.0 1.5\";\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(point), sqrt(23.25), 1e-5);\n}\n\n/**\n * Ensure that we calculate the correct maximum distance between a bound and\n * another bound.  This uses the same test cases as the MinDistance test.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundMaxDistanceBound)\n{\n  // We'll do the calculation in five dimensions, and we can use six cases.\n  // The other bound is completely outside the bound; the other bound is on the\n  // edge of the bound; the other bound partially overlaps the bound; the other\n  // bound fully overlaps the bound; the other bound is entirely inside the\n  // bound; the other bound entirely envelops the bound.\n  HRectBound<EuclideanDistance> b(5);\n\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(1.0, 5.0);\n  b[2] = Range(-2.0, 2.0);\n  b[3] = Range(-5.0, -2.0);\n  b[4] = Range(1.0, 2.0);\n\n  HRectBound<EuclideanDistance> c(5);\n\n  // The other bound is completely outside the bound.\n  c[0] = Range(-5.0, -2.0);\n  c[1] = Range(6.0, 7.0);\n  c[2] = Range(-2.0, 2.0);\n  c[3] = Range(2.0, 5.0);\n  c[4] = Range(3.0, 4.0);\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(c), sqrt(210.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MaxDistance(b), sqrt(210.0), 1e-5);\n\n  // The other bound is on the edge of the bound.\n  c[0] = Range(-2.0, 0.0);\n  c[1] = Range(0.0, 1.0);\n  c[2] = Range(-3.0, -2.0);\n  c[3] = Range(-10.0, -5.0);\n  c[4] = Range(2.0, 3.0);\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(c), sqrt(134.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MaxDistance(b), sqrt(134.0), 1e-5);\n\n  // The other bound partially overlaps the bound.\n  c[0] = Range(-2.0, 1.0);\n  c[1] = Range(0.0, 2.0);\n  c[2] = Range(-2.0, 2.0);\n  c[3] = Range(-8.0, -4.0);\n  c[4] = Range(0.0, 4.0);\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(c), sqrt(102.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MaxDistance(b), sqrt(102.0), 1e-5);\n\n  // The other bound fully overlaps the bound.\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(b), sqrt(46.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MaxDistance(c), sqrt(61.0), 1e-5);\n\n  // The other bound is entirely inside the bound / the other bound entirely\n  // envelops the bound.\n  c[0] = Range(-1.0, 3.0);\n  c[1] = Range(0.0, 6.0);\n  c[2] = Range(-3.0, 3.0);\n  c[3] = Range(-7.0, 0.0);\n  c[4] = Range(0.0, 5.0);\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(c), sqrt(100.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MaxDistance(b), sqrt(100.0), 1e-5);\n\n  // Identical bounds.  This will be the sum of the squared widths in each\n  // dimension.\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(b), sqrt(46.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MaxDistance(c), sqrt(162.0), 1e-5);\n\n  // One last additional case.  If the bound encloses only one point, the\n  // maximum distance between it and itself is 0.\n  HRectBound<EuclideanDistance> d(2);\n\n  d[0] = Range(2.0, 2.0);\n  d[1] = Range(3.0, 3.0);\n\n  BOOST_REQUIRE_SMALL(d.MaxDistance(d), 1e-5);\n}\n\n/**\n * Ensure that the ranges returned by RangeDistance() are equal to the minimum\n * and maximum distance.  We will perform this test by creating random bounds\n * and comparing the behavior to MinDistance() and MaxDistance() -- so this test\n * is assuming that those passed and operate correctly.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundRangeDistanceBound)\n{\n  for (int i = 0; i < 50; ++i)\n  {\n    size_t dim = math::RandInt(20);\n\n    HRectBound<EuclideanDistance> a(dim);\n    HRectBound<EuclideanDistance> b(dim);\n\n    // We will set the low randomly and the width randomly for each dimension of\n    // each bound.\n    arma::vec loA(dim);\n    arma::vec widthA(dim);\n\n    loA.randu();\n    widthA.randu();\n\n    arma::vec lo_b(dim);\n    arma::vec width_b(dim);\n\n    lo_b.randu();\n    width_b.randu();\n\n    for (size_t j = 0; j < dim; ++j)\n    {\n      a[j] = Range(loA[j], loA[j] + widthA[j]);\n      b[j] = Range(lo_b[j], lo_b[j] + width_b[j]);\n    }\n\n    // Now ensure that MinDistance and MaxDistance report the same.\n    Range r = a.RangeDistance(b);\n    Range s = b.RangeDistance(a);\n\n    BOOST_REQUIRE_CLOSE(r.Lo(), s.Lo(), 1e-5);\n    BOOST_REQUIRE_CLOSE(r.Hi(), s.Hi(), 1e-5);\n\n    BOOST_REQUIRE_CLOSE(r.Lo(), a.MinDistance(b), 1e-5);\n    BOOST_REQUIRE_CLOSE(r.Hi(), a.MaxDistance(b), 1e-5);\n\n    BOOST_REQUIRE_CLOSE(s.Lo(), b.MinDistance(a), 1e-5);\n    BOOST_REQUIRE_CLOSE(s.Hi(), b.MaxDistance(a), 1e-5);\n  }\n}\n\n/**\n * Ensure that the ranges returned by RangeDistance() are equal to the minimum\n * and maximum distance.  We will perform this test by creating random bounds\n * and comparing the bheavior to MinDistance() and MaxDistance() -- so this test\n * is assuming that those passed and operate correctly.  This is for the\n * bound-to-point case.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundRangeDistancePoint)\n{\n  for (int i = 0; i < 20; ++i)\n  {\n    size_t dim = math::RandInt(20);\n\n    HRectBound<EuclideanDistance> a(dim);\n\n    // We will set the low randomly and the width randomly for each dimension of\n    // each bound.\n    arma::vec loA(dim);\n    arma::vec widthA(dim);\n\n    loA.randu();\n    widthA.randu();\n\n    for (size_t j = 0; j < dim; ++j)\n      a[j] = Range(loA[j], loA[j] + widthA[j]);\n\n    // Now run the test on a few points.\n    for (int j = 0; j < 10; ++j)\n    {\n      arma::vec point(dim);\n\n      point.randu();\n\n      Range r = a.RangeDistance(point);\n\n      BOOST_REQUIRE_CLOSE(r.Lo(), a.MinDistance(point), 1e-5);\n      BOOST_REQUIRE_CLOSE(r.Hi(), a.MaxDistance(point), 1e-5);\n    }\n  }\n}\n\n/**\n * Test that we can expand the bound to include a new point.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundOrOperatorPoint)\n{\n  // Because this should be independent in each dimension, we can essentially\n  // run five test cases at once.\n  HRectBound<EuclideanDistance> b(5);\n\n  b[0] = Range(1.0, 3.0);\n  b[1] = Range(2.0, 4.0);\n  b[2] = Range(-2.0, -1.0);\n  b[3] = Range(0.0, 0.0);\n  b[4] = Range(); // Empty range.\n  b.MinWidth() = 0.0;\n\n  arma::vec point = \"2.0 4.0 2.0 -1.0 6.0\";\n\n  b |= point;\n\n  BOOST_REQUIRE_CLOSE(b[0].Lo(), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[0].Hi(), 3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[1].Lo(), 2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[1].Hi(), 4.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[2].Lo(), -2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[2].Hi(), 2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[3].Lo(), -1.0, 1e-5);\n  BOOST_REQUIRE_SMALL(b[3].Hi(), 1e-5);\n  BOOST_REQUIRE_CLOSE(b[4].Lo(), 6.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[4].Hi(), 6.0, 1e-5);\n  BOOST_REQUIRE_SMALL(b.MinWidth(), 1e-5);\n}\n\n/**\n * Test that we can expand the bound to include another bound.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundOrOperatorBound)\n{\n  // Because this should be independent in each dimension, we can run many tests\n  // at once.\n  HRectBound<EuclideanDistance> b(8);\n\n  b[0] = Range(1.0, 3.0);\n  b[1] = Range(2.0, 4.0);\n  b[2] = Range(-2.0, -1.0);\n  b[3] = Range(4.0, 5.0);\n  b[4] = Range(2.0, 4.0);\n  b[5] = Range(0.0, 0.0);\n  b[6] = Range();\n  b[7] = Range(1.0, 3.0);\n\n  HRectBound<EuclideanDistance> c(8);\n\n  c[0] = Range(-3.0, -1.0); // Entirely less than the other bound.\n  c[1] = Range(0.0, 2.0); // Touching edges.\n  c[2] = Range(-3.0, -1.5); // Partially overlapping.\n  c[3] = Range(4.0, 5.0); // Identical.\n  c[4] = Range(1.0, 5.0); // Entirely enclosing.\n  c[5] = Range(2.0, 2.0); // A single point.\n  c[6] = Range(1.0, 3.0);\n  c[7] = Range(); // Empty set.\n\n  HRectBound<EuclideanDistance> d = c;\n\n  b |= c;\n  d |= b;\n\n  BOOST_REQUIRE_CLOSE(b[0].Lo(), -3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[0].Hi(), 3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[0].Lo(), -3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[0].Hi(), 3.0, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(b[1].Lo(), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[1].Hi(), 4.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[1].Lo(), 0.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[1].Hi(), 4.0, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(b[2].Lo(), -3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[2].Hi(), -1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[2].Lo(), -3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[2].Hi(), -1.0, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(b[3].Lo(), 4.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[3].Hi(), 5.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[3].Lo(), 4.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[3].Hi(), 5.0, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(b[4].Lo(), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[4].Hi(), 5.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[4].Lo(), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[4].Hi(), 5.0, 1e-5);\n\n  BOOST_REQUIRE_SMALL(b[5].Lo(), 1e-5);\n  BOOST_REQUIRE_CLOSE(b[5].Hi(), 2.0, 1e-5);\n  BOOST_REQUIRE_SMALL(d[5].Lo(), 1e-5);\n  BOOST_REQUIRE_CLOSE(d[5].Hi(), 2.0, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(b[6].Lo(), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[6].Hi(), 3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[6].Lo(), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[6].Hi(), 3.0, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(b[7].Lo(), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b[7].Hi(), 3.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[7].Lo(), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d[7].Hi(), 3.0, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(b.MinWidth(), 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(d.MinWidth(), 1.0, 1e-5);\n}\n\n/**\n * Test that the Contains() function correctly figures out whether or not a\n * point is in a bound.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundContains)\n{\n  // We can test a couple different points: completely outside the bound,\n  // adjacent in one dimension to the bound, adjacent in all dimensions to the\n  // bound, and inside the bound.\n  HRectBound<EuclideanDistance> b(3);\n\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(0.0, 2.0);\n  b[2] = Range(0.0, 2.0);\n\n  // Completely outside the range.\n  arma::vec point = \"-1.0 4.0 4.0\";\n  BOOST_REQUIRE(!b.Contains(point));\n\n  // Completely outside, but one dimension is in the range.\n  point = \"-1.0 4.0 1.0\";\n  BOOST_REQUIRE(!b.Contains(point));\n\n  // Outside, but one dimension is on the edge.\n  point = \"-1.0 0.0 3.0\";\n  BOOST_REQUIRE(!b.Contains(point));\n\n  // Two dimensions are on the edge, but one is outside.\n  point = \"0.0 0.0 3.0\";\n  BOOST_REQUIRE(!b.Contains(point));\n\n  // Completely on the edge (should be contained).\n  point = \"0.0 0.0 0.0\";\n  BOOST_REQUIRE(b.Contains(point));\n\n  // Inside the range.\n  point = \"0.3 1.0 0.4\";\n  BOOST_REQUIRE(b.Contains(point));\n}\n\nBOOST_AUTO_TEST_CASE(TestBallBound)\n{\n  BallBound<> b1;\n  BallBound<> b2;\n\n  // Create two balls with a center distance of 1 from each other.\n  // Give the first one a radius of 0.3 and the second a radius of 0.4.\n  b1.Center().set_size(3);\n  b1.Center()[0] = 1;\n  b1.Center()[1] = 2;\n  b1.Center()[2] = 3;\n  b1.Radius() = 0.3;\n\n  b2.Center().set_size(3);\n  b2.Center()[0] = 1;\n  b2.Center()[1] = 2;\n  b2.Center()[2] = 4;\n  b2.Radius() = 0.4;\n\n  BOOST_REQUIRE_CLOSE(b1.MinDistance(b2), 1-0.3-0.4, 1e-5);\n  BOOST_REQUIRE_CLOSE(b1.RangeDistance(b2).Hi(), 1+0.3+0.4, 1e-5);\n  BOOST_REQUIRE_CLOSE(b1.RangeDistance(b2).Lo(), 1-0.3-0.4, 1e-5);\n  BOOST_REQUIRE_CLOSE(b1.RangeDistance(b2).Hi(), 1+0.3+0.4, 1e-5);\n  BOOST_REQUIRE_CLOSE(b1.RangeDistance(b2).Lo(), 1-0.3-0.4, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(b2.MinDistance(b1), 1-0.3-0.4, 1e-5);\n  BOOST_REQUIRE_CLOSE(b2.MaxDistance(b1), 1+0.3+0.4, 1e-5);\n  BOOST_REQUIRE_CLOSE(b2.RangeDistance(b1).Hi(), 1+0.3+0.4, 1e-5);\n  BOOST_REQUIRE_CLOSE(b2.RangeDistance(b1).Lo(), 1-0.3-0.4, 1e-5);\n\n  BOOST_REQUIRE(b1.Contains(b1.Center()));\n  BOOST_REQUIRE(!b1.Contains(b2.Center()));\n\n  BOOST_REQUIRE(!b2.Contains(b1.Center()));\n  BOOST_REQUIRE(b2.Contains(b2.Center()));\n  arma::vec b2point(3); // A point that's within the radius but not the center.\n  b2point[0] = 1.1;\n  b2point[1] = 2.1;\n  b2point[2] = 4.1;\n\n  BOOST_REQUIRE(b2.Contains(b2point));\n\n  BOOST_REQUIRE_SMALL(b1.MinDistance(b1.Center()), 1e-5);\n  BOOST_REQUIRE_CLOSE(b1.MinDistance(b2.Center()), 1 - 0.3, 1e-5);\n  BOOST_REQUIRE_CLOSE(b2.MinDistance(b1.Center()), 1 - 0.4, 1e-5);\n  BOOST_REQUIRE_CLOSE(b2.MaxDistance(b1.Center()), 1 + 0.4, 1e-5);\n  BOOST_REQUIRE_CLOSE(b1.MaxDistance(b2.Center()), 1 + 0.3, 1e-5);\n}\n\nBOOST_AUTO_TEST_CASE(BallBoundMoveConstructor)\n{\n  BallBound<> b1(2.0, arma::vec(\"2 1 1\"));\n  BallBound<> b2(std::move(b1));\n\n  BOOST_REQUIRE_EQUAL(b2.Dim(), 3);\n  BOOST_REQUIRE_EQUAL(b1.Dim(), 0);\n\n  BOOST_REQUIRE_CLOSE(b2.Center()[0], 2.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b2.Center()[1], 1.0, 1e-5);\n  BOOST_REQUIRE_CLOSE(b2.Center()[2], 1.0, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(b2.MinWidth(), 4.0, 1e-5);\n  BOOST_REQUIRE_SMALL(b1.MinWidth(), 1e-5);\n}\n\n/**\n * Ensure that we calculate the correct minimum distance between a point and a\n * bound.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundRootMinDistancePoint)\n{\n  // We'll do the calculation in five dimensions, and we'll use three cases for\n  // the point: point is outside the bound; point is on the edge of the bound;\n  // point is inside the bound.  In the latter two cases, the distance should be\n  // zero.\n  HRectBound<EuclideanDistance> b(5);\n\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(1.0, 5.0);\n  b[2] = Range(-2.0, 2.0);\n  b[3] = Range(-5.0, -2.0);\n  b[4] = Range(1.0, 2.0);\n\n  arma::vec point = \"-2.0 0.0 10.0 3.0 3.0\";\n\n  // This will be the Euclidean distance.\n  BOOST_REQUIRE_CLOSE(b.MinDistance(point), sqrt(95.0), 1e-5);\n\n  point = \"2.0 5.0 2.0 -5.0 1.0\";\n\n  BOOST_REQUIRE_SMALL(b.MinDistance(point), 1e-5);\n\n  point = \"1.0 2.0 0.0 -2.0 1.5\";\n\n  BOOST_REQUIRE_SMALL(b.MinDistance(point), 1e-5);\n}\n\n/**\n * Ensure that we calculate the correct minimum distance between a bound and\n * another bound.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundRootMinDistanceBound)\n{\n  // We'll do the calculation in five dimensions, and we can use six cases.\n  // The other bound is completely outside the bound; the other bound is on the\n  // edge of the bound; the other bound partially overlaps the bound; the other\n  // bound fully overlaps the bound; the other bound is entirely inside the\n  // bound; the other bound entirely envelops the bound.\n  HRectBound<EuclideanDistance> b(5);\n\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(1.0, 5.0);\n  b[2] = Range(-2.0, 2.0);\n  b[3] = Range(-5.0, -2.0);\n  b[4] = Range(1.0, 2.0);\n\n  HRectBound<EuclideanDistance> c(5);\n\n  // The other bound is completely outside the bound.\n  c[0] = Range(-5.0, -2.0);\n  c[1] = Range(6.0, 7.0);\n  c[2] = Range(-2.0, 2.0);\n  c[3] = Range(2.0, 5.0);\n  c[4] = Range(3.0, 4.0);\n\n  BOOST_REQUIRE_CLOSE(b.MinDistance(c), sqrt(22.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MinDistance(b), sqrt(22.0), 1e-5);\n\n  // The other bound is on the edge of the bound.\n  c[0] = Range(-2.0, 0.0);\n  c[1] = Range(0.0, 1.0);\n  c[2] = Range(-3.0, -2.0);\n  c[3] = Range(-10.0, -5.0);\n  c[4] = Range(2.0, 3.0);\n\n  BOOST_REQUIRE_SMALL(b.MinDistance(c), 1e-5);\n  BOOST_REQUIRE_SMALL(c.MinDistance(b), 1e-5);\n\n  // The other bound partially overlaps the bound.\n  c[0] = Range(-2.0, 1.0);\n  c[1] = Range(0.0, 2.0);\n  c[2] = Range(-2.0, 2.0);\n  c[3] = Range(-8.0, -4.0);\n  c[4] = Range(0.0, 4.0);\n\n  BOOST_REQUIRE_SMALL(b.MinDistance(c), 1e-5);\n  BOOST_REQUIRE_SMALL(c.MinDistance(b), 1e-5);\n\n  // The other bound fully overlaps the bound.\n  BOOST_REQUIRE_SMALL(b.MinDistance(b), 1e-5);\n  BOOST_REQUIRE_SMALL(c.MinDistance(c), 1e-5);\n\n  // The other bound is entirely inside the bound / the other bound entirely\n  // envelops the bound.\n  c[0] = Range(-1.0, 3.0);\n  c[1] = Range(0.0, 6.0);\n  c[2] = Range(-3.0, 3.0);\n  c[3] = Range(-7.0, 0.0);\n  c[4] = Range(0.0, 5.0);\n\n  BOOST_REQUIRE_SMALL(b.MinDistance(c), 1e-5);\n  BOOST_REQUIRE_SMALL(c.MinDistance(b), 1e-5);\n\n  // Now we must be sure that the minimum distance to itself is 0.\n  BOOST_REQUIRE_SMALL(b.MinDistance(b), 1e-5);\n  BOOST_REQUIRE_SMALL(c.MinDistance(c), 1e-5);\n}\n\n/**\n * Ensure that we calculate the correct maximum distance between a bound and a\n * point.  This uses the same test cases as the MinDistance test.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundRootMaxDistancePoint)\n{\n  // We'll do the calculation in five dimensions, and we'll use three cases for\n  // the point: point is outside the bound; point is on the edge of the bound;\n  // point is inside the bound.  In the latter two cases, the distance should be\n  // zero.\n  HRectBound<EuclideanDistance> b(5);\n\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(1.0, 5.0);\n  b[2] = Range(-2.0, 2.0);\n  b[3] = Range(-5.0, -2.0);\n  b[4] = Range(1.0, 2.0);\n\n  arma::vec point = \"-2.0 0.0 10.0 3.0 3.0\";\n\n  // This will be the Euclidean distance.\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(point), sqrt(253.0), 1e-5);\n\n  point = \"2.0 5.0 2.0 -5.0 1.0\";\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(point), sqrt(46.0), 1e-5);\n\n  point = \"1.0 2.0 0.0 -2.0 1.5\";\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(point), sqrt(23.25), 1e-5);\n}\n\n/**\n * Ensure that we calculate the correct maximum distance between a bound and\n * another bound.  This uses the same test cases as the MinDistance test.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundRootMaxDistanceBound)\n{\n  // We'll do the calculation in five dimensions, and we can use six cases.\n  // The other bound is completely outside the bound; the other bound is on the\n  // edge of the bound; the other bound partially overlaps the bound; the other\n  // bound fully overlaps the bound; the other bound is entirely inside the\n  // bound; the other bound entirely envelops the bound.\n  HRectBound<EuclideanDistance> b(5);\n\n  b[0] = Range(0.0, 2.0);\n  b[1] = Range(1.0, 5.0);\n  b[2] = Range(-2.0, 2.0);\n  b[3] = Range(-5.0, -2.0);\n  b[4] = Range(1.0, 2.0);\n\n  HRectBound<EuclideanDistance> c(5);\n\n  // The other bound is completely outside the bound.\n  c[0] = Range(-5.0, -2.0);\n  c[1] = Range(6.0, 7.0);\n  c[2] = Range(-2.0, 2.0);\n  c[3] = Range(2.0, 5.0);\n  c[4] = Range(3.0, 4.0);\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(c), sqrt(210.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MaxDistance(b), sqrt(210.0), 1e-5);\n\n  // The other bound is on the edge of the bound.\n  c[0] = Range(-2.0, 0.0);\n  c[1] = Range(0.0, 1.0);\n  c[2] = Range(-3.0, -2.0);\n  c[3] = Range(-10.0, -5.0);\n  c[4] = Range(2.0, 3.0);\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(c), sqrt(134.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MaxDistance(b), sqrt(134.0), 1e-5);\n\n  // The other bound partially overlaps the bound.\n  c[0] = Range(-2.0, 1.0);\n  c[1] = Range(0.0, 2.0);\n  c[2] = Range(-2.0, 2.0);\n  c[3] = Range(-8.0, -4.0);\n  c[4] = Range(0.0, 4.0);\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(c), sqrt(102.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MaxDistance(b), sqrt(102.0), 1e-5);\n\n  // The other bound fully overlaps the bound.\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(b), sqrt(46.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MaxDistance(c), sqrt(61.0), 1e-5);\n\n  // The other bound is entirely inside the bound / the other bound entirely\n  // envelops the bound.\n  c[0] = Range(-1.0, 3.0);\n  c[1] = Range(0.0, 6.0);\n  c[2] = Range(-3.0, 3.0);\n  c[3] = Range(-7.0, 0.0);\n  c[4] = Range(0.0, 5.0);\n\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(c), sqrt(100.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MaxDistance(b), sqrt(100.0), 1e-5);\n\n  // Identical bounds.  This will be the sum of the squared widths in each\n  // dimension.\n  BOOST_REQUIRE_CLOSE(b.MaxDistance(b), sqrt(46.0), 1e-5);\n  BOOST_REQUIRE_CLOSE(c.MaxDistance(c), sqrt(162.0), 1e-5);\n\n  // One last additional case.  If the bound encloses only one point, the\n  // maximum distance between it and itself is 0.\n  HRectBound<EuclideanDistance> d(2);\n\n  d[0] = Range(2.0, 2.0);\n  d[1] = Range(3.0, 3.0);\n\n  BOOST_REQUIRE_SMALL(d.MaxDistance(d), 1e-5);\n}\n\n/**\n * Ensure that the ranges returned by RangeDistance() are equal to the minimum\n * and maximum distance.  We will perform this test by creating random bounds\n * and comparing the behavior to MinDistance() and MaxDistance() -- so this test\n * is assuming that those passed and operate correctly.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundRootRangeDistanceBound)\n{\n  for (int i = 0; i < 50; ++i)\n  {\n    size_t dim = math::RandInt(20);\n\n    HRectBound<EuclideanDistance> a(dim);\n    HRectBound<EuclideanDistance> b(dim);\n\n    // We will set the low randomly and the width randomly for each dimension of\n    // each bound.\n    arma::vec loA(dim);\n    arma::vec widthA(dim);\n\n    loA.randu();\n    widthA.randu();\n\n    arma::vec lo_b(dim);\n    arma::vec width_b(dim);\n\n    lo_b.randu();\n    width_b.randu();\n\n    for (size_t j = 0; j < dim; ++j)\n    {\n      a[j] = Range(loA[j], loA[j] + widthA[j]);\n      b[j] = Range(lo_b[j], lo_b[j] + width_b[j]);\n    }\n\n    // Now ensure that MinDistance and MaxDistance report the same.\n    Range r = a.RangeDistance(b);\n    Range s = b.RangeDistance(a);\n\n    BOOST_REQUIRE_CLOSE(r.Lo(), s.Lo(), 1e-5);\n    BOOST_REQUIRE_CLOSE(r.Hi(), s.Hi(), 1e-5);\n\n    BOOST_REQUIRE_CLOSE(r.Lo(), a.MinDistance(b), 1e-5);\n    BOOST_REQUIRE_CLOSE(r.Hi(), a.MaxDistance(b), 1e-5);\n\n    BOOST_REQUIRE_CLOSE(s.Lo(), b.MinDistance(a), 1e-5);\n    BOOST_REQUIRE_CLOSE(s.Hi(), b.MaxDistance(a), 1e-5);\n  }\n}\n\n/**\n * Ensure that the ranges returned by RangeDistance() are equal to the minimum\n * and maximum distance.  We will perform this test by creating random bounds\n * and comparing the bheavior to MinDistance() and MaxDistance() -- so this test\n * is assuming that those passed and operate correctly.  This is for the\n * bound-to-point case.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundRootRangeDistancePoint)\n{\n  for (int i = 0; i < 20; ++i)\n  {\n    size_t dim = math::RandInt(20);\n\n    HRectBound<EuclideanDistance> a(dim);\n\n    // We will set the low randomly and the width randomly for each dimension of\n    // each bound.\n    arma::vec loA(dim);\n    arma::vec widthA(dim);\n\n    loA.randu();\n    widthA.randu();\n\n    for (size_t j = 0; j < dim; ++j)\n      a[j] = Range(loA[j], loA[j] + widthA[j]);\n\n    // Now run the test on a few points.\n    for (int j = 0; j < 10; ++j)\n    {\n      arma::vec point(dim);\n\n      point.randu();\n\n      Range r = a.RangeDistance(point);\n\n      BOOST_REQUIRE_CLOSE(r.Lo(), a.MinDistance(point), 1e-5);\n      BOOST_REQUIRE_CLOSE(r.Hi(), a.MaxDistance(point), 1e-5);\n    }\n  }\n}\n\n/**\n * Ensure that HRectBound::Diameter() works properly.\n */\nBOOST_AUTO_TEST_CASE(HRectBoundDiameter)\n{\n  HRectBound<LMetric<3, true>> b(4);\n  b[0] = math::Range(0.0, 1.0);\n  b[1] = math::Range(-1.0, 0.0);\n  b[2] = math::Range(2.0, 3.0);\n  b[3] = math::Range(7.0, 7.0);\n\n  BOOST_REQUIRE_CLOSE(b.Diameter(), std::pow(3.0, 1.0 / 3.0), 1e-5);\n\n  HRectBound<LMetric<2, false>> c(4);\n  c[0] = math::Range(0.0, 1.0);\n  c[1] = math::Range(-1.0, 0.0);\n  c[2] = math::Range(2.0, 3.0);\n  c[3] = math::Range(0.0, 0.0);\n\n  BOOST_REQUIRE_CLOSE(c.Diameter(), 3.0, 1e-5);\n\n  HRectBound<LMetric<5, true>> d(2);\n  d[0] = math::Range(2.2, 2.2);\n  d[1] = math::Range(1.0, 1.0);\n\n  BOOST_REQUIRE_SMALL(d.Diameter(), 1e-5);\n}\n\n/**\n * It seems as though Bill has stumbled across a bug where\n * BinarySpaceTree<>::count() returns something different than\n * BinarySpaceTree<>::count_.  So, let's build a simple tree and make sure they\n * are the same.\n */\nBOOST_AUTO_TEST_CASE(TreeCountMismatch)\n{\n  arma::mat dataset = \"2.0 5.0 9.0 4.0 8.0 7.0;\"\n                      \"3.0 4.0 6.0 7.0 1.0 2.0 \";\n\n  // Leaf size of 1.\n  KDTree<EuclideanDistance, EmptyStatistic, arma::mat> rootNode(dataset, 1);\n\n  BOOST_REQUIRE(rootNode.Count() == 6);\n  BOOST_REQUIRE(rootNode.Left()->Count() == 3);\n  BOOST_REQUIRE(rootNode.Left()->Left()->Count() == 2);\n  BOOST_REQUIRE(rootNode.Left()->Left()->Left()->Count() == 1);\n  BOOST_REQUIRE(rootNode.Left()->Left()->Right()->Count() == 1);\n  BOOST_REQUIRE(rootNode.Left()->Right()->Count() == 1);\n  BOOST_REQUIRE(rootNode.Right()->Count() == 3);\n  BOOST_REQUIRE(rootNode.Right()->Left()->Count() == 2);\n  BOOST_REQUIRE(rootNode.Right()->Left()->Left()->Count() == 1);\n  BOOST_REQUIRE(rootNode.Right()->Left()->Right()->Count() == 1);\n  BOOST_REQUIRE(rootNode.Right()->Right()->Count() == 1);\n}\n\nBOOST_AUTO_TEST_CASE(CheckParents)\n{\n  arma::mat dataset = \"2.0 5.0 9.0 4.0 8.0 7.0;\"\n                      \"3.0 4.0 6.0 7.0 1.0 2.0 \";\n\n  // Leaf size of 1.\n  KDTree<EuclideanDistance, EmptyStatistic, arma::mat> rootNode(dataset, 1);\n\n  BOOST_REQUIRE_EQUAL(rootNode.Parent(),\n      (KDTree<EuclideanDistance, EmptyStatistic, arma::mat>*) NULL);\n  BOOST_REQUIRE_EQUAL(&rootNode, rootNode.Left()->Parent());\n  BOOST_REQUIRE_EQUAL(&rootNode, rootNode.Right()->Parent());\n  BOOST_REQUIRE_EQUAL(rootNode.Left(), rootNode.Left()->Left()->Parent());\n  BOOST_REQUIRE_EQUAL(rootNode.Left(), rootNode.Left()->Right()->Parent());\n  BOOST_REQUIRE_EQUAL(rootNode.Left()->Left(),\n      rootNode.Left()->Left()->Left()->Parent());\n  BOOST_REQUIRE_EQUAL(rootNode.Left()->Left(),\n      rootNode.Left()->Left()->Right()->Parent());\n  BOOST_REQUIRE_EQUAL(rootNode.Right(), rootNode.Right()->Left()->Parent());\n  BOOST_REQUIRE_EQUAL(rootNode.Right(), rootNode.Right()->Right()->Parent());\n  BOOST_REQUIRE_EQUAL(rootNode.Right()->Left(),\n      rootNode.Right()->Left()->Left()->Parent());\n  BOOST_REQUIRE_EQUAL(rootNode.Right()->Left(),\n      rootNode.Right()->Left()->Right()->Parent());\n}\n\nBOOST_AUTO_TEST_CASE(CheckDataset)\n{\n  arma::mat dataset = \"2.0 5.0 9.0 4.0 8.0 7.0;\"\n                      \"3.0 4.0 6.0 7.0 1.0 2.0 \";\n\n  // Leaf size of 1.\n  KDTree<EuclideanDistance, EmptyStatistic, arma::mat> rootNode(dataset, 1);\n\n  arma::mat* rootDataset = &rootNode.Dataset();\n  BOOST_REQUIRE_EQUAL(&rootNode.Left()->Dataset(), rootDataset);\n  BOOST_REQUIRE_EQUAL(&rootNode.Right()->Dataset(), rootDataset);\n  BOOST_REQUIRE_EQUAL(&rootNode.Left()->Left()->Dataset(), rootDataset);\n  BOOST_REQUIRE_EQUAL(&rootNode.Left()->Right()->Dataset(), rootDataset);\n  BOOST_REQUIRE_EQUAL(&rootNode.Right()->Left()->Dataset(), rootDataset);\n  BOOST_REQUIRE_EQUAL(&rootNode.Right()->Right()->Dataset(), rootDataset);\n  BOOST_REQUIRE_EQUAL(&rootNode.Left()->Left()->Left()->Dataset(),\n      rootDataset);\n  BOOST_REQUIRE_EQUAL(&rootNode.Left()->Left()->Right()->Dataset(),\n      rootDataset);\n  BOOST_REQUIRE_EQUAL(&rootNode.Right()->Left()->Left()->Dataset(),\n      rootDataset);\n  BOOST_REQUIRE_EQUAL(&rootNode.Right()->Left()->Right()->Dataset(),\n      rootDataset);\n}\n\n// Ensure FurthestDescendantDistance() works.\nBOOST_AUTO_TEST_CASE(FurthestDescendantDistanceTest)\n{\n  arma::mat dataset = \"1; 3\"; // One point.\n  KDTree<EuclideanDistance, EmptyStatistic, arma::mat> rootNode(dataset, 1);\n\n  BOOST_REQUIRE_SMALL(rootNode.FurthestDescendantDistance(), 1e-5);\n\n  dataset = \"1 -1; 1 -1\"; // Square of size [2, 2].\n\n  // Both points are contained in the one node.\n  KDTree<EuclideanDistance, EmptyStatistic, arma::mat> twoPoint(dataset);\n  BOOST_REQUIRE_CLOSE(twoPoint.FurthestDescendantDistance(), sqrt(2.0), 1e-5);\n}\n\n// Ensure that FurthestPointDistance() works.\nBOOST_AUTO_TEST_CASE(FurthestPointDistanceTest)\n{\n  arma::mat dataset;\n  dataset.randu(5, 100);\n\n  typedef KDTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  TreeType tree(dataset);\n\n  // Now, check each node.\n  std::queue<TreeType*> nodeQueue;\n  nodeQueue.push(&tree);\n\n  while (!nodeQueue.empty())\n  {\n    TreeType* node = nodeQueue.front();\n    nodeQueue.pop();\n\n    if (node->NumChildren() != 0)\n      BOOST_REQUIRE_EQUAL(node->FurthestPointDistance(), 0.0);\n    else\n    {\n      // Get center.\n      arma::vec center;\n      node->Center(center);\n\n      double maxDist = 0.0;\n      for (size_t i = 0; i < node->NumPoints(); ++i)\n      {\n        const double dist = metric::EuclideanDistance::Evaluate(center,\n            dataset.col(node->Point(i)));\n        if (dist > maxDist)\n          maxDist = dist;\n      }\n\n      // We don't require an exact value because FurthestPointDistance() can\n      // just bound the value instead of returning the exact value.\n      BOOST_REQUIRE_LE(maxDist, node->FurthestPointDistance());\n\n      if (node->Left())\n        nodeQueue.push(node->Left());\n      if (node->Right())\n        nodeQueue.push(node->Right());\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(ParentDistanceTest)\n{\n  arma::mat dataset;\n  dataset.randu(5, 500);\n\n  typedef KDTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  TreeType tree(dataset);\n\n  // The root's parent distance should be 0 (although maybe it doesn't actually\n  // matter; I just want to be sure it's not an uninitialized value, which this\n  // test *sort* of checks).\n  BOOST_REQUIRE_EQUAL(tree.ParentDistance(), 0.0);\n\n  // Do a depth-first traversal and make sure the parent distance is the same as\n  // we calculate.\n  std::stack<TreeType*> nodeStack;\n  nodeStack.push(&tree);\n\n  while (!nodeStack.empty())\n  {\n    TreeType* node = nodeStack.top();\n    nodeStack.pop();\n\n    // If it's a leaf, nothing to check.\n    if (node->NumChildren() == 0)\n      continue;\n\n    arma::vec center, leftCenter, rightCenter;\n    node->Center(center);\n    node->Left()->Center(leftCenter);\n    node->Right()->Center(rightCenter);\n\n    const double leftDistance = LMetric<2>::Evaluate(center, leftCenter);\n    const double rightDistance = LMetric<2>::Evaluate(center, rightCenter);\n\n    BOOST_REQUIRE_CLOSE(leftDistance, node->Left()->ParentDistance(), 1e-5);\n    BOOST_REQUIRE_CLOSE(rightDistance, node->Right()->ParentDistance(), 1e-5);\n\n    nodeStack.push(node->Left());\n    nodeStack.push(node->Right());\n  }\n}\n\nBOOST_AUTO_TEST_CASE(ParentDistanceTestWithMapping)\n{\n  arma::mat dataset;\n  dataset.randu(5, 500);\n  std::vector<size_t> oldFromNew;\n\n  typedef KDTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  TreeType tree(dataset, oldFromNew);\n\n  // The root's parent distance should be 0 (although maybe it doesn't actually\n  // matter; I just want to be sure it's not an uninitialized value, which this\n  // test *sort* of checks).\n  BOOST_REQUIRE_EQUAL(tree.ParentDistance(), 0.0);\n\n  // Do a depth-first traversal and make sure the parent distance is the same as\n  // we calculate.\n  std::stack<TreeType*> nodeStack;\n  nodeStack.push(&tree);\n\n  while (!nodeStack.empty())\n  {\n    TreeType* node = nodeStack.top();\n    nodeStack.pop();\n\n    // If it's a leaf, nothing to check.\n    if (node->NumChildren() == 0)\n      continue;\n\n    arma::vec center, leftCenter, rightCenter;\n    node->Center(center);\n    node->Left()->Center(leftCenter);\n    node->Right()->Center(rightCenter);\n\n    const double leftDistance = LMetric<2>::Evaluate(center, leftCenter);\n    const double rightDistance = LMetric<2>::Evaluate(center, rightCenter);\n\n    BOOST_REQUIRE_CLOSE(leftDistance, node->Left()->ParentDistance(), 1e-5);\n    BOOST_REQUIRE_CLOSE(rightDistance, node->Right()->ParentDistance(), 1e-5);\n\n    nodeStack.push(node->Left());\n    nodeStack.push(node->Right());\n  }\n}\n\n// Forward declaration of methods we need for the next test.\ntemplate<typename TreeType>\nbool CheckPointBounds(TreeType& node);\n\ntemplate<typename TreeType>\nvoid GenerateVectorOfTree(TreeType* node,\n                          size_t depth,\n                          std::vector<TreeType*>& v);\n\n/**\n * Exhaustive kd-tree test based on #125.\n *\n * - Generate a random dataset of a random size.\n * - Build a tree on that dataset.\n * - Ensure all the permutation indices map back to the correct points.\n * - Verify that each point is contained inside all of the bounds of its parent\n *     nodes.\n * - Verify that each bound at a particular level of the tree does not overlap\n *     with any other bounds at that level.\n *\n * Then, we do that whole process a handful of times.\n */\nBOOST_AUTO_TEST_CASE(KdTreeTest)\n{\n  typedef KDTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n\n  size_t maxRuns = 10; // Ten total tests.\n  size_t pointIncrements = 1000; // Range is from 2000 points to 11000.\n\n  // We use the default leaf size of 20.\n  for (size_t run = 0; run < maxRuns; run++)\n  {\n    size_t dimensions = run + 2;\n    size_t maxPoints = (run + 1) * pointIncrements;\n\n    size_t size = maxPoints;\n    arma::mat dataset = arma::mat(dimensions, size);\n\n    // Mappings for post-sort verification of data.\n    std::vector<size_t> newToOld;\n    std::vector<size_t> oldToNew;\n\n    // Generate data.\n    dataset.randu();\n\n    // Build the tree itself.\n    TreeType root(dataset, newToOld, oldToNew);\n    const arma::mat& treeset = root.Dataset();\n\n    // Ensure the size of the tree is correct.\n    BOOST_REQUIRE_EQUAL(root.Count(), size);\n\n    // Check the forward and backward mappings for correctness.\n    for (size_t i = 0; i < size; ++i)\n    {\n      for (size_t j = 0; j < dimensions; ++j)\n      {\n        BOOST_REQUIRE_EQUAL(treeset(j, i), dataset(j, newToOld[i]));\n        BOOST_REQUIRE_EQUAL(treeset(j, oldToNew[i]), dataset(j, i));\n      }\n    }\n\n    // Now check that each point is contained inside of all bounds above it.\n    CheckPointBounds(root);\n\n    // Now check that no peers overlap.\n    std::vector<TreeType*> v;\n    GenerateVectorOfTree(&root, 1, v);\n\n    // Start with the first pair.\n    size_t depth = 2;\n    // Compare each peer against every other peer.\n    while (depth < v.size())\n    {\n      for (size_t i = depth; i < 2 * depth && i < v.size(); ++i)\n        for (size_t j = i + 1; j < 2 * depth && j < v.size(); ++j)\n          if (v[i] != NULL && v[j] != NULL)\n            BOOST_REQUIRE(!v[i]->Bound().Contains(v[j]->Bound()));\n\n      depth *= 2;\n    }\n  }\n\n  arma::mat dataset(25, 1000);\n  for (size_t col = 0; col < dataset.n_cols; ++col)\n    for (size_t row = 0; row < dataset.n_rows; ++row)\n      dataset(row, col) = row + col;\n\n  TreeType root(dataset);\n}\n\nBOOST_AUTO_TEST_CASE(MaxRPTreeTest)\n{\n  typedef MaxRPTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n\n  size_t maxRuns = 10; // Ten total tests.\n  size_t pointIncrements = 1000; // Range is from 2000 points to 11000.\n\n  // We use the default leaf size of 20.\n  for (size_t run = 0; run < maxRuns; run++)\n  {\n    size_t dimensions = run + 2;\n    size_t maxPoints = (run + 1) * pointIncrements;\n\n    size_t size = maxPoints;\n    arma::mat dataset = arma::mat(dimensions, size);\n\n    // Mappings for post-sort verification of data.\n    std::vector<size_t> newToOld;\n    std::vector<size_t> oldToNew;\n\n    // Generate data.\n    dataset.randu();\n\n    // Build the tree itself.\n    TreeType root(dataset, newToOld, oldToNew);\n    const arma::mat& treeset = root.Dataset();\n\n    // Ensure the size of the tree is correct.\n    BOOST_REQUIRE_EQUAL(root.Count(), size);\n\n    // Check the forward and backward mappings for correctness.\n    for (size_t i = 0; i < size; ++i)\n    {\n      for (size_t j = 0; j < dimensions; ++j)\n      {\n        BOOST_REQUIRE_EQUAL(treeset(j, i), dataset(j, newToOld[i]));\n        BOOST_REQUIRE_EQUAL(treeset(j, oldToNew[i]), dataset(j, i));\n      }\n    }\n  }\n}\n\ntemplate<typename TreeType>\nbool CheckHyperplaneSplit(const TreeType& tree)\n{\n  typedef typename TreeType::ElemType ElemType;\n\n  const typename TreeType::Mat& dataset = tree.Dataset();\n  arma::Mat<typename TreeType::ElemType> mat(dataset.n_rows + 1,\n      tree.Left()->NumDescendants() + tree.Right()->NumDescendants());\n\n  // We will try to find a hyperplane that splits the node.\n  // The hyperplane may be represented as\n  // a_1 * x_1 + ... + a_n * x_n + a_{n + 1} = 0.\n  // We have to solve the system of inequalities (mat^t) * x <= 0,\n  // where x[0], ... , x[dataset.n_rows-1] are the components of the normal\n  // to the hyperplane and x[dataset.n_rows] is the position of the hyperplane\n  // i.e. x = (a_1, ... , a_{n + 1}).\n  // Each column of the matrix consists of a point and 1.\n  // In such a way, the inner product of a column and x is equal to the value\n  // of the hyperplane expression.\n  // The hyperplane splits the node if the expression takes on opposite\n  // values on node's children.\n\n  for (size_t i = 0; i < tree.Left()->NumDescendants(); ++i)\n  {\n    for (size_t k = 0; k < dataset.n_rows; ++k)\n      mat(k, i) = - dataset(k, tree.Left()->Descendant(i));\n\n    mat(dataset.n_rows, i) = -1;\n  }\n\n  for (size_t i = 0; i < tree.Right()->NumDescendants(); ++i)\n  {\n    for (size_t k = 0; k < dataset.n_rows; ++k)\n      mat(k, i + tree.Left()->NumDescendants()) =\n          dataset(k, tree.Right()->Descendant(i));\n\n    mat(dataset.n_rows, i + tree.Left()->NumDescendants()) = 1;\n  }\n\n  arma::Col<ElemType> x(dataset.n_rows + 1);\n  x.zeros();\n  // Define an initial value.\n  x[0] = 1.0;\n  x[1] = -arma::mean(\n      dataset.cols(tree.Begin(), tree.Begin() + tree.Count() - 1).row(0));\n\n  const size_t numIters = 1000000;\n  const ElemType delta = 1e-4;\n\n  // We will solve the system using a simple gradient method.\n  bool success = false;\n  for (size_t it = 0; it < numIters; it++)\n  {\n    success = true;\n    for (size_t k = 0; k < tree.Count(); ++k)\n    {\n      ElemType result = arma::dot(mat.col(k), x);\n      if (result > 0)\n      {\n        x -= mat.col(k) * delta;\n        success = false;\n      }\n    }\n\n    // The norm of the direction shouldn't be equal to zero.\n    if (arma::norm(x.rows(0, dataset.n_rows-1)) < 1e-8)\n    {\n      x[math::RandInt(0, dataset.n_rows)] = 1.0;\n      success = false;\n    }\n\n    if (success)\n      break;\n  }\n\n  return success;\n}\n\ntemplate<typename TreeType>\nvoid CheckMaxRPTreeSplit(const TreeType& tree)\n{\n  if (tree.IsLeaf())\n    return;\n\n  BOOST_REQUIRE_EQUAL(CheckHyperplaneSplit(tree), true);\n\n  CheckMaxRPTreeSplit(*tree.Left());\n  CheckMaxRPTreeSplit(*tree.Right());\n}\n\nBOOST_AUTO_TEST_CASE(MaxRPTreeSplitTest)\n{\n  typedef MaxRPTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  arma::mat dataset;\n  dataset.randu(8, 1000);\n  TreeType root(dataset);\n\n  CheckMaxRPTreeSplit(root);\n}\n\nBOOST_AUTO_TEST_CASE(RPTreeTest)\n{\n  typedef RPTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n\n  size_t maxRuns = 10; // Ten total tests.\n  size_t pointIncrements = 1000; // Range is from 2000 points to 11000.\n\n  // We use the default leaf size of 20.\n  for (size_t run = 0; run < maxRuns; run++)\n  {\n    size_t dimensions = run + 2;\n    size_t maxPoints = (run + 1) * pointIncrements;\n\n    size_t size = maxPoints;\n    arma::mat dataset = arma::mat(dimensions, size);\n\n    // Mappings for post-sort verification of data.\n    std::vector<size_t> newToOld;\n    std::vector<size_t> oldToNew;\n\n    // Generate data.\n    dataset.randu();\n\n    // Build the tree itself.\n    TreeType root(dataset, newToOld, oldToNew);\n    const arma::mat& treeset = root.Dataset();\n\n    // Ensure the size of the tree is correct.\n    BOOST_REQUIRE_EQUAL(root.Count(), size);\n\n    // Check the forward and backward mappings for correctness.\n    for (size_t i = 0; i < size; ++i)\n    {\n      for (size_t j = 0; j < dimensions; ++j)\n      {\n        BOOST_REQUIRE_EQUAL(treeset(j, i), dataset(j, newToOld[i]));\n        BOOST_REQUIRE_EQUAL(treeset(j, oldToNew[i]), dataset(j, i));\n      }\n    }\n  }\n}\n\ntemplate<typename TreeType, typename MetricType>\nvoid CheckRPTreeSplit(const TreeType& tree)\n{\n  typedef typename TreeType::ElemType ElemType;\n  if (tree.IsLeaf())\n    return;\n\n  if (!CheckHyperplaneSplit(tree))\n  {\n    // Check if that was mean split.\n    arma::Col<ElemType> center;\n    tree.Left()->Bound().Center(center);\n    ElemType maxDist = 0;\n    for (size_t k =0; k < tree.Left()->NumDescendants(); ++k)\n    {\n      ElemType dist = MetricType::Evaluate(center,\n          tree.Dataset().col(tree.Left()->Descendant(k)));\n\n      if (dist > maxDist)\n        maxDist = dist;\n    }\n\n    for (size_t k =0; k < tree.Right()->NumDescendants(); ++k)\n    {\n      ElemType dist = MetricType::Evaluate(center,\n          tree.Dataset().col(tree.Right()->Descendant(k)));\n\n      BOOST_REQUIRE_LE(maxDist, dist *\n          (1.0 + 10.0 * std::numeric_limits<ElemType>::epsilon()));\n    }\n  }\n\n  CheckRPTreeSplit<TreeType, MetricType>(*tree.Left());\n  CheckRPTreeSplit<TreeType, MetricType>(*tree.Right());\n}\n\nBOOST_AUTO_TEST_CASE(RPTreeSplitTest)\n{\n  typedef RPTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  arma::mat dataset;\n  dataset.randu(8, 1000);\n  TreeType root(dataset);\n\n  CheckRPTreeSplit<TreeType, EuclideanDistance>(root);\n}\n\n// Recursively checks that each node contains all points that it claims to have.\ntemplate<typename TreeType>\nbool CheckPointBounds(TreeType& node)\n{\n  // Check that each point which this tree claims is actually inside the tree.\n  for (size_t index = 0; index < node.NumDescendants(); index++)\n    if (!node.Bound().Contains(node.Dataset().col(node.Descendant(index))))\n      return false;\n\n  bool result = true;\n  for (size_t child = 0; child < node.NumChildren(); ++child)\n    result &= CheckPointBounds(node.Child(child));\n  return result;\n}\n\n/**\n * Exhaustive ball tree test based on #125.\n *\n * - Generate a random dataset of a random size.\n * - Build a tree on that dataset.\n * - Ensure all the permutation indices map back to the correct points.\n * - Verify that each point is contained inside all of the bounds of its parent\n *     nodes.\n *\n * Then, we do that whole process a handful of times.\n */\nBOOST_AUTO_TEST_CASE(BallTreeTest)\n{\n  typedef BallTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n\n  size_t maxRuns = 10; // Ten total tests.\n  size_t pointIncrements = 1000; // Range is from 2000 points to 11000.\n\n  // We use the default leaf size of 20.\n  for (size_t run = 0; run < maxRuns; run++)\n  {\n    size_t dimensions = run + 2;\n    size_t maxPoints = (run + 1) * pointIncrements;\n\n    size_t size = maxPoints;\n    arma::mat dataset = arma::mat(dimensions, size);\n    arma::mat datacopy; // Used to test mappings.\n\n    // Mappings for post-sort verification of data.\n    std::vector<size_t> newToOld;\n    std::vector<size_t> oldToNew;\n\n    // Generate data.\n    dataset.randu();\n\n    // Build the tree itself.\n    TreeType root(dataset, newToOld, oldToNew);\n    const arma::mat& treeset = root.Dataset();\n\n    // Ensure the size of the tree is correct.\n    BOOST_REQUIRE_EQUAL(root.NumDescendants(), size);\n\n    // Check the forward and backward mappings for correctness.\n    for (size_t i = 0; i < size; ++i)\n    {\n      for (size_t j = 0; j < dimensions; ++j)\n      {\n        BOOST_REQUIRE_EQUAL(treeset(j, i), dataset(j, newToOld[i]));\n        BOOST_REQUIRE_EQUAL(treeset(j, oldToNew[i]), dataset(j, i));\n      }\n    }\n\n    // Now check that each point is contained inside of all bounds above it.\n    CheckPointBounds(root);\n  }\n}\n\n/**\n * Ensure that we can build a ball tree with a custom instantiated metric type.\n */\nBOOST_AUTO_TEST_CASE(MahalanobisBallTreeTest)\n{\n  arma::mat dataset(10, 1000, arma::fill::randu);\n  arma::mat cov = arma::eye<arma::mat>(10, 10);\n  cov(2, 2) = 2.0; // Just so it's not completely the identity matrix.\n  MahalanobisDistance<> m(std::move(cov));\n\n  typedef BallTree<MahalanobisDistance<>, EmptyStatistic, arma::mat> TreeType;\n\n  TreeType tree(dataset);\n\n  // As long as it built successfully, I am okay with that.\n  BOOST_REQUIRE_EQUAL(tree.NumDescendants(), 1000);\n\n  // Also test when we give oldFromNew, since this uses a different code path.\n  std::vector<size_t> oldFromNew;\n  TreeType tree2(std::move(dataset), oldFromNew);\n\n  BOOST_REQUIRE_EQUAL(tree.NumDescendants(), 1000);\n}\n\ntemplate<typename TreeType>\nvoid GenerateVectorOfTree(TreeType* node,\n                          size_t depth,\n                          std::vector<TreeType*>& v)\n{\n  if (node == NULL)\n    return;\n\n  if (depth >= v.size())\n    v.resize(2 * depth + 1, NULL); // Resize to right size; fill with NULL.\n\n  v[depth] = node;\n\n  // Recurse to the left and right children.\n  GenerateVectorOfTree(node->Left(), depth * 2, v);\n  GenerateVectorOfTree(node->Right(), depth * 2 + 1, v);\n\n  return;\n}\n\n/**\n * Exhaustive sparse kd-tree test based on #125.\n *\n * - Generate a random dataset of a random size.\n * - Build a tree on that dataset.\n * - Ensure all the permutation indices map back to the correct points.\n * - Verify that each point is contained inside all of the bounds of its parent\n *     nodes.\n * - Verify that each bound at a particular level of the tree does not overlap\n *     with any other bounds at that level.\n *\n * Then, we do that whole process a handful of times.\n */\nBOOST_AUTO_TEST_CASE(ExhaustiveSparseKDTreeTest)\n{\n  typedef KDTree<EuclideanDistance, EmptyStatistic, arma::SpMat<double>>\n      TreeType;\n\n  size_t maxRuns = 2; // Two total tests.\n  size_t pointIncrements = 200; // Range is from 200 points to 400.\n\n  // We use the default leaf size of 20.\n  for (size_t run = 0; run < maxRuns; run++)\n  {\n    size_t dimensions = run + 2;\n    size_t maxPoints = (run + 1) * pointIncrements;\n\n    size_t size = maxPoints;\n    arma::SpMat<double> dataset = arma::SpMat<double>(dimensions, size);\n    arma::SpMat<double> datacopy; // Used to test mappings.\n\n    // Mappings for post-sort verification of data.\n    std::vector<size_t> newToOld;\n    std::vector<size_t> oldToNew;\n\n    // Generate data.\n    dataset.sprandu(dimensions, size, 0.1);\n    datacopy = dataset; // Save a copy.\n\n    // Build the tree itself.\n    TreeType root(dataset, newToOld, oldToNew);\n    const arma::sp_mat& treeset = root.Dataset();\n\n    // Ensure the size of the tree is correct.\n    BOOST_REQUIRE_EQUAL(root.Count(), size);\n\n    // Check the forward and backward mappings for correctness.\n    for (size_t i = 0; i < size; ++i)\n    {\n      for (size_t j = 0; j < dimensions; ++j)\n      {\n        BOOST_REQUIRE_EQUAL(treeset(j, i), dataset(j, newToOld[i]));\n        BOOST_REQUIRE_EQUAL(treeset(j, oldToNew[i]), dataset(j, i));\n      }\n    }\n\n    // Now check that each point is contained inside of all bounds above it.\n    CheckPointBounds(root);\n\n    // Now check that no peers overlap.\n    std::vector<TreeType*> v;\n    GenerateVectorOfTree(&root, 1, v);\n\n    // Start with the first pair.\n    size_t depth = 2;\n    // Compare each peer against every other peer.\n    while (depth < v.size())\n    {\n      for (size_t i = depth; i < 2 * depth && i < v.size(); ++i)\n        for (size_t j = i + 1; j < 2 * depth && j < v.size(); ++j)\n          if (v[i] != NULL && v[j] != NULL)\n            BOOST_REQUIRE(!v[i]->Bound().Contains(v[j]->Bound()));\n\n      depth *= 2;\n    }\n  }\n\n  arma::SpMat<double> dataset(25, 1000);\n  for (size_t col = 0; col < dataset.n_cols; ++col)\n    for (size_t row = 0; row < dataset.n_rows; ++row)\n      dataset(row, col) = row + col;\n\n  TreeType root(dataset);\n}\n\nBOOST_AUTO_TEST_CASE(BinarySpaceTreeMoveConstructorTest)\n{\n  arma::mat dataset(5, 1000);\n  dataset.randu();\n\n  BinarySpaceTree<EuclideanDistance> tree(dataset);\n  BinarySpaceTree<EuclideanDistance> tree2(std::move(tree));\n\n  BOOST_REQUIRE_EQUAL(tree.NumChildren(), 0);\n  BOOST_REQUIRE_EQUAL(tree2.NumChildren(), 2);\n}\n\ntemplate<typename TreeType>\nvoid RecurseTreeCountLeaves(const TreeType& node, arma::vec& counts)\n{\n  for (size_t i = 0; i < node.NumChildren(); ++i)\n  {\n    if (node.Child(i).NumChildren() == 0)\n      counts[node.Child(i).Point()]++;\n    else\n      RecurseTreeCountLeaves<TreeType>(node.Child(i), counts);\n  }\n}\n\ntemplate<typename TreeType>\nvoid CheckSelfChild(const TreeType& node)\n{\n  if (node.NumChildren() == 0)\n    return; // No self-child applicable here.\n\n  bool found = false;\n  for (size_t i = 0; i < node.NumChildren(); ++i)\n  {\n    if (node.Child(i).Point() == node.Point())\n      found = true;\n\n    // Recursively check the children.\n    CheckSelfChild(node.Child(i));\n  }\n\n  // Ensure this has its own self-child.\n  BOOST_REQUIRE_EQUAL(found, true);\n}\n\ntemplate<typename TreeType, typename MetricType>\nvoid CheckCovering(const TreeType& node)\n{\n  // Return if a leaf.  No checking necessary.\n  if (node.NumChildren() == 0)\n    return;\n\n  const typename TreeType::Mat& dataset = node.Dataset();\n  const size_t nodePoint = node.Point();\n\n  // To ensure that this node satisfies the covering principle, we must ensure\n  // that the distance to each child is less than pow(base, scale).\n  double maxDistance = pow(node.Base(), node.Scale());\n  for (size_t i = 0; i < node.NumChildren(); ++i)\n  {\n    const size_t childPoint = node.Child(i).Point();\n\n    double distance = MetricType::Evaluate(dataset.col(nodePoint),\n        dataset.col(childPoint));\n\n    BOOST_REQUIRE_LE(distance, maxDistance);\n\n    // Check the child.\n    CheckCovering<TreeType, MetricType>(node.Child(i));\n  }\n}\n\n/**\n * Create a simple cover tree and then make sure it is valid.\n */\nBOOST_AUTO_TEST_CASE(SimpleCoverTreeConstructionTest)\n{\n  // 20-point dataset.\n  arma::mat data = arma::trans(arma::mat(\"0.0 0.0;\"\n                                         \"1.0 0.0;\"\n                                         \"0.5 0.5;\"\n                                         \"2.0 2.0;\"\n                                         \"-1.0 2.0;\"\n                                         \"3.0 0.0;\"\n                                         \"1.5 5.5;\"\n                                         \"-2.0 -2.0;\"\n                                         \"-1.5 1.5;\"\n                                         \"0.0 4.0;\"\n                                         \"2.0 1.0;\"\n                                         \"2.0 1.2;\"\n                                         \"-3.0 -2.5;\"\n                                         \"-5.0 -5.0;\"\n                                         \"3.5 1.5;\"\n                                         \"2.0 2.5;\"\n                                         \"-1.0 -1.0;\"\n                                         \"-3.5 1.5;\"\n                                         \"3.5 -1.5;\"\n                                         \"2.0 1.0;\"));\n\n  // The root point will be the first point, (0, 0).\n  typedef StandardCoverTree<EuclideanDistance, EmptyStatistic, arma::mat>\n      TreeType;\n  TreeType tree(data); // Expansion constant of 2.0.\n\n  // The furthest point from the root will be (-5, -5), with a distance of\n  // of sqrt(50).  This means the scale of the root node should be 3 (because\n  // 2^3 = 8).\n  BOOST_REQUIRE_EQUAL(tree.Scale(), 3);\n\n  // Now loop through the tree and ensure that each leaf is only created once.\n  arma::vec counts;\n  counts.zeros(20);\n  RecurseTreeCountLeaves(tree, counts);\n\n  // Each point should only have one leaf node representing it.\n  for (size_t i = 0; i < 20; ++i)\n    BOOST_REQUIRE_EQUAL(counts[i], 1);\n\n  // Each non-leaf should have a self-child.\n  CheckSelfChild<TreeType>(tree);\n\n  // Each node must satisfy the covering principle (its children must be less\n  // than or equal to a certain distance apart).\n  CheckCovering<TreeType, LMetric<2, true>>(tree);\n\n  // There's no need to check the separation invariant because that is relaxed\n  // in our implementation.\n}\n\n/**\n * Create a large cover tree and make sure it's accurate.\n */\nBOOST_AUTO_TEST_CASE(CoverTreeConstructionTest)\n{\n  arma::mat dataset;\n  // 50-dimensional, 1000 point.\n  dataset.randu(50, 1000);\n\n  typedef StandardCoverTree<EuclideanDistance, EmptyStatistic, arma::mat>\n      TreeType;\n  TreeType tree(dataset);\n\n  // Ensure each leaf is only created once.\n  arma::vec counts;\n  counts.zeros(1000);\n  RecurseTreeCountLeaves(tree, counts);\n\n  for (size_t i = 0; i < 1000; ++i)\n    BOOST_REQUIRE_EQUAL(counts[i], 1);\n\n  // Each non-leaf should have a self-child.\n  CheckSelfChild<TreeType>(tree);\n\n  // Each node must satisfy the covering principle (its children must be less\n  // than or equal to a certain distance apart).\n  CheckCovering<TreeType, LMetric<2, true> >(tree);\n\n  // There's no need to check the separation because that is relaxed in our\n  // implementation.\n}\n\n/**\n * Create a cover tree on sparse data and make sure it's accurate.\n */\nBOOST_AUTO_TEST_CASE(SparseCoverTreeConstructionTest)\n{\n  arma::sp_mat dataset;\n  // 50-dimensional, 1000 point.\n  dataset.sprandu(50, 1000, 0.3);\n\n  typedef StandardCoverTree<EuclideanDistance, EmptyStatistic, arma::sp_mat>\n      TreeType;\n  TreeType tree(dataset);\n\n  // Ensure each leaf is only created once.\n  arma::vec counts;\n  counts.zeros(1000);\n  RecurseTreeCountLeaves(tree, counts);\n\n  for (size_t i = 0; i < 1000; ++i)\n    BOOST_REQUIRE_EQUAL(counts[i], 1);\n\n  // Each non-leaf should have a self-child.\n  CheckSelfChild<TreeType>(tree);\n\n  // Each node must satisfy the covering principle (its children must be less\n  // than or equal to a certain distance apart).\n  CheckCovering<TreeType, LMetric<2, true> >(tree);\n\n  // There's no need to check the separation invariant because that is relaxed\n  // in our implementation.\n}\n\n/**\n * Test the manual constructor.\n */\nBOOST_AUTO_TEST_CASE(CoverTreeManualConstructorTest)\n{\n  arma::mat dataset;\n  dataset.zeros(10, 10);\n\n  typedef StandardCoverTree<EuclideanDistance, EmptyStatistic, arma::mat>\n      TreeType;\n  TreeType node(dataset, 1.3, 3, 2, NULL, 1.5, 2.75);\n\n  BOOST_REQUIRE_EQUAL(&node.Dataset(), &dataset);\n  BOOST_REQUIRE_EQUAL(node.Base(), 1.3);\n  BOOST_REQUIRE_EQUAL(node.Point(), 3);\n  BOOST_REQUIRE_EQUAL(node.Scale(), 2);\n  BOOST_REQUIRE_EQUAL(node.Parent(), (CoverTree<>*) NULL);\n  BOOST_REQUIRE_EQUAL(node.ParentDistance(), 1.5);\n  BOOST_REQUIRE_EQUAL(node.FurthestDescendantDistance(), 2.75);\n}\n\n/**\n * Make sure cover trees work in different metric spaces.\n */\nBOOST_AUTO_TEST_CASE(CoverTreeAlternateMetricTest)\n{\n  arma::mat dataset;\n  // 5-dimensional, 300-point dataset.\n  dataset.randu(5, 300);\n\n  typedef StandardCoverTree<ManhattanDistance, EmptyStatistic, arma::mat>\n      TreeType;\n  TreeType tree(dataset);\n\n  // Ensure each leaf is only created once.\n  arma::vec counts;\n  counts.zeros(300);\n  RecurseTreeCountLeaves<TreeType>(tree, counts);\n\n  for (size_t i = 0; i < 300; ++i)\n    BOOST_REQUIRE_EQUAL(counts[i], 1);\n\n  // Each non-leaf should have a self-child.\n  CheckSelfChild<TreeType>(tree);\n\n  // Each node must satisfy the covering principle (its children must be less\n  // than or equal to a certain distance apart).\n  CheckCovering<TreeType, ManhattanDistance>(tree);\n\n  // There's no need to check the separation invariant because that is relaxed\n  // in our implementation.\n}\n\n/**\n * Make sure copy constructor works for the cover tree.\n */\nBOOST_AUTO_TEST_CASE(CoverTreeCopyConstructor)\n{\n  arma::mat dataset;\n  dataset.randu(10, 10); // dataset is irrelevant.\n  typedef StandardCoverTree<EuclideanDistance, EmptyStatistic, arma::mat>\n      TreeType;\n  TreeType c(dataset, 1.3, 0, 5, NULL, 1.45, 5.2); // Random parameters.\n  c.Children().push_back(new TreeType(dataset, 1.3, 1, 4, &c, 1.3, 2.45));\n  c.Children().push_back(new TreeType(dataset, 1.5, 2, 3, &c, 1.2, 5.67));\n\n  TreeType d = c;\n\n  // Check that everything is the same.\n  // As the tree being copied doesn't own the dataset, they must share the same\n  // pointer.\n  BOOST_REQUIRE_EQUAL(c.Dataset().memptr(), d.Dataset().memptr());\n  BOOST_REQUIRE_CLOSE(c.Base(), d.Base(), 1e-50);\n  BOOST_REQUIRE_EQUAL(c.Point(), d.Point());\n  BOOST_REQUIRE_EQUAL(c.Scale(), d.Scale());\n  BOOST_REQUIRE_EQUAL(c.Parent(), d.Parent());\n  BOOST_REQUIRE_EQUAL(c.ParentDistance(), d.ParentDistance());\n  BOOST_REQUIRE_EQUAL(c.FurthestDescendantDistance(),\n                      d.FurthestDescendantDistance());\n  BOOST_REQUIRE_EQUAL(c.NumChildren(), d.NumChildren());\n  BOOST_REQUIRE_NE(&c.Child(0), &d.Child(0));\n  BOOST_REQUIRE_NE(&c.Child(1), &d.Child(1));\n\n  BOOST_REQUIRE_EQUAL(c.Child(0).Parent(), &c);\n  BOOST_REQUIRE_EQUAL(c.Child(1).Parent(), &c);\n  BOOST_REQUIRE_EQUAL(d.Child(0).Parent(), &d);\n  BOOST_REQUIRE_EQUAL(d.Child(1).Parent(), &d);\n\n  // Check that the children are okay.\n  BOOST_REQUIRE_EQUAL(c.Child(0).Dataset().memptr(), c.Dataset().memptr());\n  BOOST_REQUIRE_CLOSE(c.Child(0).Base(), d.Child(0).Base(), 1e-50);\n  BOOST_REQUIRE_EQUAL(c.Child(0).Point(), d.Child(0).Point());\n  BOOST_REQUIRE_EQUAL(c.Child(0).Scale(), d.Child(0).Scale());\n  BOOST_REQUIRE_EQUAL(c.Child(0).ParentDistance(), d.Child(0).ParentDistance());\n  BOOST_REQUIRE_EQUAL(c.Child(0).FurthestDescendantDistance(),\n                      d.Child(0).FurthestDescendantDistance());\n  BOOST_REQUIRE_EQUAL(c.Child(0).NumChildren(), d.Child(0).NumChildren());\n\n  BOOST_REQUIRE_EQUAL(c.Child(1).Dataset().memptr(), c.Dataset().memptr());\n  BOOST_REQUIRE_CLOSE(c.Child(1).Base(), d.Child(1).Base(), 1e-50);\n  BOOST_REQUIRE_EQUAL(c.Child(1).Point(), d.Child(1).Point());\n  BOOST_REQUIRE_EQUAL(c.Child(1).Scale(), d.Child(1).Scale());\n  BOOST_REQUIRE_EQUAL(c.Child(1).ParentDistance(), d.Child(1).ParentDistance());\n  BOOST_REQUIRE_EQUAL(c.Child(1).FurthestDescendantDistance(),\n                      d.Child(1).FurthestDescendantDistance());\n  BOOST_REQUIRE_EQUAL(c.Child(1).NumChildren(), d.Child(1).NumChildren());\n\n  // Check copy constructor when the tree being copied owns the dataset.\n  TreeType e(std::move(dataset), 1.3);\n  TreeType f = e;\n  // As the tree being copied owns the dataset, they must have different\n  // instances.\n  BOOST_REQUIRE_NE(e.Dataset().memptr(), f.Dataset().memptr());\n}\n\nBOOST_AUTO_TEST_CASE(CoverTreeMoveDatasetTest)\n{\n  arma::mat dataset = arma::randu<arma::mat>(3, 1000);\n  typedef StandardCoverTree<EuclideanDistance, EmptyStatistic, arma::mat>\n      TreeType;\n\n  TreeType t(std::move(dataset));\n\n  BOOST_REQUIRE_EQUAL(dataset.n_elem, 0);\n  BOOST_REQUIRE_EQUAL(t.Dataset().n_rows, 3);\n  BOOST_REQUIRE_EQUAL(t.Dataset().n_cols, 1000);\n\n  EuclideanDistance ed; // Test the other constructor.\n  dataset = arma::randu<arma::mat>(3, 1000);\n  TreeType t2(std::move(dataset), ed);\n\n  BOOST_REQUIRE_EQUAL(dataset.n_elem, 0);\n  BOOST_REQUIRE_EQUAL(t2.Dataset().n_rows, 3);\n  BOOST_REQUIRE_EQUAL(t2.Dataset().n_cols, 1000);\n}\n\n/**\n * Make sure copy constructor works right for the binary space tree.\n */\nBOOST_AUTO_TEST_CASE(BinarySpaceTreeCopyConstructor)\n{\n  arma::mat data(\"1\");\n  typedef KDTree<EuclideanDistance, EmptyStatistic, arma::mat> TreeType;\n  TreeType b(data);\n  b.Begin() = 10;\n  b.Count() = 50;\n\n  b.Left() = new TreeType(data);\n  b.Left()->Begin() = 10;\n  b.Left()->Count() = 30;\n  b.Left()->Parent() = &b;\n  b.Right() = new TreeType(data);\n  b.Right()->Begin() = 40;\n  b.Right()->Count() = 20;\n  b.Right()->Parent() = &b;\n\n  // Copy the tree.\n  TreeType c(b);\n\n  // Ensure everything copied correctly.\n  BOOST_REQUIRE_EQUAL(b.Begin(), c.Begin());\n  BOOST_REQUIRE_EQUAL(b.Count(), c.Count());\n  BOOST_REQUIRE_NE(b.Left(), c.Left());\n  BOOST_REQUIRE_NE(b.Right(), c.Right());\n\n  // Check the children.\n  BOOST_REQUIRE_EQUAL(b.Left()->Begin(), c.Left()->Begin());\n  BOOST_REQUIRE_EQUAL(b.Left()->Count(), c.Left()->Count());\n  BOOST_REQUIRE_EQUAL(b.Left()->Left(), (TreeType*) NULL);\n  BOOST_REQUIRE_EQUAL(b.Left()->Left(), c.Left()->Left());\n  BOOST_REQUIRE_EQUAL(b.Left()->Right(), (TreeType*) NULL);\n  BOOST_REQUIRE_EQUAL(b.Left()->Right(), c.Left()->Right());\n\n  BOOST_REQUIRE_EQUAL(b.Right()->Begin(), c.Right()->Begin());\n  BOOST_REQUIRE_EQUAL(b.Right()->Count(), c.Right()->Count());\n  BOOST_REQUIRE_EQUAL(b.Right()->Left(), (TreeType*) NULL);\n  BOOST_REQUIRE_EQUAL(b.Right()->Left(), c.Right()->Left());\n  BOOST_REQUIRE_EQUAL(b.Right()->Right(), (TreeType*) NULL);\n  BOOST_REQUIRE_EQUAL(b.Right()->Right(), c.Right()->Right());\n\n  // Clean memory (we built the tree by hand, so this is what we have to do\n  // since the destructor won't free the children's datasets).\n  delete &b.Left()->Dataset();\n  delete &b.Right()->Dataset();\n}\n\n//! Count the number of leaves under this node.\ntemplate<typename TreeType>\nsize_t NumLeaves(TreeType* node)\n{\n  if (node->NumChildren() == 0)\n    return 1;\n\n  size_t count = 0;\n  for (size_t i = 0; i < node->NumChildren(); ++i)\n    count += NumLeaves(&node->Child(i));\n\n  return count;\n}\n\n//! Returns true if the index is contained somewhere under this node.\ntemplate<typename TreeType>\nbool FindIndex(TreeType* node, const size_t index)\n{\n  for (size_t i = 0; i < node->NumPoints(); ++i)\n    if (node->Point(i) == index)\n      return true;\n\n  for (size_t i = 0; i < node->NumChildren(); ++i)\n    if (FindIndex(&node->Child(i), index))\n      return true;\n\n  return false;\n}\n\n//! Check that the points in the given node are accessible through the\n//! Descendant() function of the root node.\ntemplate<typename TreeType>\nbool CheckAccessibility(TreeType* childNode, TreeType* rootNode)\n{\n  for (size_t i = 0; i < childNode->NumPoints(); ++i)\n  {\n    bool found = false;\n    for (size_t j = 0; j < rootNode->NumDescendants(); ++j)\n    {\n      if (childNode->Point(i) == rootNode->Descendant(j))\n      {\n        found = true;\n        break;\n      }\n    }\n\n    if (!found)\n    {\n      Log::Debug << \"Did not find descendant \" << childNode->Point(i) << \".\\n\";\n      return false;\n    }\n  }\n\n  // Now check the children.\n  for (size_t i = 0; i < childNode->NumChildren(); ++i)\n    if (!CheckAccessibility(&childNode->Child(i), rootNode))\n      return false;\n\n  return true;\n}\n\n//! Check that Descendant() and NumDescendants() is right for this node.\ntemplate<typename TreeType>\nvoid CheckDescendants(TreeType* node)\n{\n  // In a cover tree, the number of leaves should be the number of descendant\n  // points.\n  const size_t numLeaves = NumLeaves(node);\n  BOOST_REQUIRE_EQUAL(numLeaves, node->NumDescendants());\n\n  // Now check that each descendant is somewhere in the tree.\n  for (size_t i = 0; i < node->NumDescendants(); ++i)\n  {\n    Log::Debug << \"Check for descendant \" << node->Descendant(i) << \" (i \" <<\n        i << \").\\n\";\n    BOOST_REQUIRE_EQUAL(FindIndex(node, node->Descendant(i)), true);\n  }\n\n  // Now check that every actual descendant is accessible through the\n  // Descendant() function.\n  BOOST_REQUIRE_EQUAL(CheckAccessibility(node, node), true);\n\n  // Now check that there are no duplicates in the list of descendants.\n  std::vector<size_t> descendants;\n  descendants.resize(node->NumDescendants());\n  for (size_t i = 0; i < node->NumDescendants(); ++i)\n    descendants[i] = node->Descendant(i);\n\n  // Sort the list.\n  std::sort(descendants.begin(), descendants.end());\n\n  // Check that there are no duplicates (this is easy because it's sorted).\n  for (size_t i = 1; i < descendants.size(); ++i)\n    BOOST_REQUIRE_NE(descendants[i], descendants[i - 1]);\n\n  // Now perform these same checks for the children.\n  for (size_t i = 0; i < node->NumChildren(); ++i)\n    CheckDescendants(&node->Child(i));\n}\n\n/**\n * Make sure Descendant() and NumDescendants() works properly for the cover\n * tree.\n */\nBOOST_AUTO_TEST_CASE(CoverTreeDescendantTest)\n{\n  arma::mat dataset;\n  dataset.randu(3, 100);\n\n  StandardCoverTree<EuclideanDistance, EmptyStatistic, arma::mat> tree(dataset);\n\n  // Now check that the NumDescendants() count and each Descendant() is right\n  // using the recursive function above.\n  CheckDescendants(&tree);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "9efb8c8769b5a12b635b0a9d469239b5718ff37f", "size": 70377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/tree_test.cpp", "max_stars_repo_name": "gaurav-singh1998/mlpack", "max_stars_repo_head_hexsha": "c104a2dcf0b51a98d9d6fcfc01d4e7047cc83872", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-29T17:39:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-16T23:36:01.000Z", "max_issues_repo_path": "src/mlpack/tests/tree_test.cpp", "max_issues_repo_name": "R-Aravind/mlpack", "max_issues_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/tree_test.cpp", "max_forks_repo_name": "R-Aravind/mlpack", "max_forks_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-17T21:33:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-17T21:33:59.000Z", "avg_line_length": 30.745740498, "max_line_length": 80, "alphanum_fraction": 0.6491893658, "num_tokens": 21718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5537349924436058}}
{"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": "#define BOOST_TEST_MODULE Gpufit\n\n#include \"Gpufit/gpufit.h\"\n\n#include <boost/test/included/unit_test.hpp>\n\n#include <array>\n#include <cmath>\n\ntemplate<std::size_t SIZE>\nvoid generate_gauss_2d_elliptic(std::array< REAL, SIZE>& values, std::array< REAL, 6 > const & parameters)\n{\n    int const size_x = int(std::sqrt(SIZE));\n    int const size_y = size_x;\n\n    REAL const a = parameters[0];\n    REAL const x0 = parameters[1];\n    REAL const y0 = parameters[2];\n    REAL const sx = parameters[3];\n    REAL const sy = parameters[4];\n    REAL const b = parameters[5];\n\n    for (int point_index_y = 0; point_index_y < size_y; point_index_y++)\n    {\n        for (int point_index_x = 0; point_index_x < size_x; point_index_x++)\n        {\n            int const point_index = point_index_y * size_x + point_index_x;\n            REAL const argx = ((point_index_x - x0)*(point_index_x - x0)) / (2 * sx * sx);\n            REAL const argy = ((point_index_y - y0)*(point_index_y - y0)) / (2* sy * sy);\n            REAL const ex = exp(-argx) * exp(-argy);\n            values[point_index] = a * ex + b;\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE( Gauss_Fit_2D_Elliptic )\n{\n    std::size_t const n_fits{ 1 } ;\n    std::size_t const n_points{ 25 } ;\n\n    std::array< REAL, 6 > const true_parameters{ { 4, 2, 2, .4f, .6f, 1 } };\n\n    std::array< REAL, n_points > data{};\n    generate_gauss_2d_elliptic(data, true_parameters);\n\n    std::array< REAL, n_points > weights{};\n    std::fill(weights.begin(), weights.end(), 1.f);\n    std::array< REAL, 6 > initial_parameters{ { 2, 1.8f, 2.2f, .5f, .5f, 0 } };\n    REAL tolerance{ .001f };\n    int max_n_iterations{ 10 };\n    std::array< int, 6 > parameters_to_fit{ { 1, 1, 1, 1, 1, 1 } };\n    std::array< REAL, 6 > output_parameters;\n    int output_state;\n    REAL output_chi_square;\n    int output_n_iterations;\n\n    int const status\n            = gpufit\n            (\n                n_fits,\n                n_points,\n                data.data(),\n                weights.data(),\n                GAUSS_2D_ELLIPTIC,\n                initial_parameters.data(),\n                tolerance,\n                max_n_iterations,\n                parameters_to_fit.data(),\n                LSE,\n                0,\n                0,\n                output_parameters.data(),\n                &output_state,\n                &output_chi_square,\n                &output_n_iterations\n            ) ;\n\n    BOOST_CHECK(status == 0);\n    BOOST_CHECK(output_state == 0);\n    BOOST_CHECK(output_n_iterations <= max_n_iterations);\n    BOOST_CHECK(output_chi_square < 1e-6f);\n\n    BOOST_CHECK(std::abs(output_parameters[0] - true_parameters[0]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[1] - true_parameters[1]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[2] - true_parameters[2]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[3] - true_parameters[3]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[4] - true_parameters[4]) < 1e-6f);\n    BOOST_CHECK(std::abs(output_parameters[5] - true_parameters[5]) < 1e-6f);\n}\n", "meta": {"hexsha": "78d7936c13c09bcaf34c384b5a1c039c0a1a5169", "size": 3044, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gpufit/tests/Gauss_Fit_2D_Elliptic.cpp", "max_stars_repo_name": "sriharijayaram5/Gpufit", "max_stars_repo_head_hexsha": "468ffbce6e6ff98632951af5e027c88c332bc1e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 228.0, "max_stars_repo_stars_event_min_datetime": "2017-08-10T17:46:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:06:06.000Z", "max_issues_repo_path": "Gpufit/tests/Gauss_Fit_2D_Elliptic.cpp", "max_issues_repo_name": "sriharijayaram5/Gpufit", "max_issues_repo_head_hexsha": "468ffbce6e6ff98632951af5e027c88c332bc1e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2017-08-14T11:41:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:22:59.000Z", "max_forks_repo_path": "Gpufit/tests/Gauss_Fit_2D_Elliptic.cpp", "max_forks_repo_name": "sriharijayaram5/Gpufit", "max_forks_repo_head_hexsha": "468ffbce6e6ff98632951af5e027c88c332bc1e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 76.0, "max_forks_repo_forks_event_min_datetime": "2017-08-16T15:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T06:28:38.000Z", "avg_line_length": 33.8222222222, "max_line_length": 106, "alphanum_fraction": 0.5929697766, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5536885530353195}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/math/fibonacci_numbers.hpp\"\n\nBOOST_AUTO_TEST_SUITE(TestFibbonacciNumbers)\n\nBOOST_AUTO_TEST_CASE(small_numbers) {\n    {\n        std::vector<long long> expected = {0};\n        BOOST_CHECK(expected == Algo::Math::FibonacciNumbers::ListOfNums(0));\n    }\n\n    {\n        std::vector<long long> expected = {0, 1};\n        BOOST_CHECK(expected == Algo::Math::FibonacciNumbers::ListOfNums(1));\n    }\n\n    {\n        std::vector<long long> expected = {0, 1, 1};\n        BOOST_CHECK(expected == Algo::Math::FibonacciNumbers::ListOfNums(2));\n    }\n\n    {\n        std::vector<long long> expected = {0, 1, 1, 2, 3, 5};\n        BOOST_CHECK(expected == Algo::Math::FibonacciNumbers::ListOfNums(5));\n    }\n\n    {\n        std::vector<long long> expected = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55};\n        BOOST_CHECK(expected == Algo::Math::FibonacciNumbers::ListOfNums(10));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(last_digit) {\n    BOOST_CHECK(0 == Algo::Math::FibonacciNumbers::LastDigitOfNum(0));\n    BOOST_CHECK(1 == Algo::Math::FibonacciNumbers::LastDigitOfNum(1));\n    BOOST_CHECK(5 == Algo::Math::FibonacciNumbers::LastDigitOfNum(5));\n    BOOST_CHECK(4 == Algo::Math::FibonacciNumbers::LastDigitOfNum(9));\n    BOOST_CHECK(9 == Algo::Math::FibonacciNumbers::LastDigitOfNum(331));\n    BOOST_CHECK(5 == Algo::Math::FibonacciNumbers::LastDigitOfNum(327305));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "5ea8cdbfa135b7e4af87ff613b27eeb3edb049d7", "size": 1420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/math/test_fibonacci_numbers.cpp", "max_stars_repo_name": "iamantony/CppNotes", "max_stars_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T14:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T09:51:43.000Z", "max_issues_repo_path": "test/algorithms/math/test_fibonacci_numbers.cpp", "max_issues_repo_name": "iamantony/CppNotes", "max_issues_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T07:38:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-02T11:00:58.000Z", "max_forks_repo_path": "test/algorithms/math/test_fibonacci_numbers.cpp", "max_forks_repo_name": "iamantony/CppNotes", "max_forks_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-11T14:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T08:53:50.000Z", "avg_line_length": 33.023255814, "max_line_length": 80, "alphanum_fraction": 0.6584507042, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5536885469375467}}
{"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 <ostream>\n\nint main()\n{\n\tusing namespace boost::numeric::ublas;\n\n\tusing tensorf = tensor<float>;\n\tusing matrixf = matrix<float>;\n\tusing vectorf = vector<float>;\n\n\tauto A = tensorf{3,4,2};\n\tauto B = A = 2;\n\n\t// Calling overloaded operators\n\t// and using simple tensor expression templates.\n\tif( A != (B+1) )\n\t\tA += 2*B - 1;\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\tauto n = shape{3,4};\n\tauto D = matrixf(n[0],n[1],1);\n\tauto e = vectorf(n[1],1);\n\tauto f = vectorf(n[0],2);\n\n\t// Calling constructor with\n\t// vector expression templates\n\ttensorf C = 2*f;\n\t// formatted output\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// Calling overloaded operators\n\t// and mixing simple tensor and matrix expression templates\n\ttensorf F = 3*C + 4*prod(2*D,e);\n\n\t// formatted output\n\tstd::cout << \"% --------------------------- \" << std::endl;\n\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\tstd::cout << \"F=\" << F << \";\" << std::endl << std::endl;\n\n\n}\n", "meta": {"hexsha": "fabb00f4b167ae375f29d10356cb320afc5a818c", "size": 1754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/examples/tensor/simple_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/simple_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/simple_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": 27.40625, "max_line_length": 73, "alphanum_fraction": 0.5581527936, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.5536885371535055}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// 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_RANDOM_MOVING_AVERAGE_HPP_ER_2008_04\n#define BOOST_ACCUMULATORS_RANDOM_MOVING_AVERAGE_HPP_ER_2008_04\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/fir.hpp>\n#include <boost/range/iterator_range.hpp>\nnamespace boost{namespace random\n{\n\n// Simulates a Moving average process\ntemplate<typename T>\nclass moving_average{\npublic:\n    typedef T               input_type;\n    typedef T               result_type ;\n    template<typename R>\n    moving_average(const R& coeffs)\n        :acc(\n            accumulators::tag::fir::coefficients=coeffs,\n            accumulators::tag::delay<>::cache_size=coeffs.size()){}\n    moving_average(const moving_average& that)\n        :acc(that.acc){}\n    moving_average& operator=(const moving_average& that){\n        if(&that!=this){\n            acc = that.acc;\n        }\n        return *this;\n    }\n    template<typename G>//G models NumberGenerator\n    result_type operator()(G& gen){\n        T x = gen();\n        acc(x);\n        return accumulators::extract::fir(acc);\n    }\nprivate:\n    typedef accumulators::accumulator_set<\n        T,\n        accumulators::stats<\n            accumulators::tag::fir,\n            accumulators::tag::delay<>\n        >\n    > acc_type;\n    acc_type acc;\n};\n\n}}\n#endif\n", "meta": {"hexsha": "a33e941ac8fbdbcc539f641473b051775e5fd190", "size": 1910, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "autocovariance/boost/random/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/random/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/random/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": 34.1071428571, "max_line_length": 79, "alphanum_fraction": 0.5455497382, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5536885241541247}}
{"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 \u2264 j \u2264 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\u22121, . . . , 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\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n// Jonathan Driedger, Thomas Pr\u00e4tzlich, and Meinard M\u00fcller\n// Let It Bee \u2014 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": "/*\n * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// includes\n// std\n#include <iostream>\n\n// boost\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE AutoDiff test\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/unit_test.hpp>\n\n// Eigen\n#include <Eigen/Core>\n#include <unsupported/Eigen/AutoDiff>\n\n// AutoDiff\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> derivative_t;\ntypedef Eigen::AutoDiffScalar<derivative_t> scalar_t;\n\n/*\nnamespace std\n{\nscalar_t sin(const scalar_t& t)\n{\n  return Eigen::sin(t);\n}\nscalar_t cos(const scalar_t& t)\n{\n  return Eigen::cos(t);\n}\n}\n*/\n\n// SpaceVecAlg\n#include <SpaceVecAlg/SpaceVecAlg>\nnamespace sva\n{\ntemplate<>\ninline Matrix3<scalar_t> RotZ<scalar_t>(scalar_t theta)\n{\n  using namespace Eigen;\n\n  Matrix3<scalar_t> ret;\n  scalar_t z(0., derivative_t::Zero(theta.derivatives().rows()));\n  scalar_t o(1., derivative_t::Zero(theta.derivatives().rows()));\n  scalar_t s = sin(theta), c = cos(theta);\n\n  ret << c, s, z, -s, c, z, z, z, o;\n\n  return ret;\n}\n} // namespace sva\n\nusing boost::math::constants::pi;\n\nBOOST_AUTO_TEST_CASE(PTransformVsPTransform)\n{\n  using namespace sva;\n  using namespace Eigen;\n\n  {\n    Vector3<scalar_t> pt1T(0., 1., 0.);\n    pt1T[0].derivatives().setZero(2);\n    pt1T[1].derivatives().setZero(2);\n    pt1T[1].derivatives()(0) = 1.;\n    pt1T[2].derivatives().setZero(2);\n\n    PTransform<scalar_t> pt1(pt1T);\n    PTransformd pt2(Vector3d(1., 0., 0.));\n\n    PTransform<scalar_t> res1 = pt1 * pt1;\n    PTransform<scalar_t> res2 = pt1 * PTransform<scalar_t>{pt2};\n    BOOST_CHECK(PTransform<scalar_t>{pt2} == pt2.cast<scalar_t>());\n\n    std::cout << res1.translation()[0].derivatives().transpose() << std::endl;\n    std::cout << res1.translation()[1].derivatives().transpose() << std::endl;\n    std::cout << res1.translation()[2].derivatives().transpose() << std::endl;\n\n    std::cout << std::endl;\n\n    std::cout << res2.translation()[0].derivatives().transpose() << std::endl;\n    std::cout << res2.translation()[1].derivatives().transpose() << std::endl;\n    std::cout << res2.translation()[2].derivatives().transpose() << std::endl;\n\n    std::cout << std::endl;\n  }\n\n  {\n    Vector3<scalar_t> prismY(0., 1., 0.);\n    prismY[0].derivatives().setZero(2, 1);\n    prismY[1].derivatives().setZero(2, 1);\n    prismY[1].derivatives()(0) = 1.;\n    prismY[2].derivatives().setZero(2, 1);\n\n    scalar_t rotZ = pi<double>() / 4.;\n    rotZ.derivatives().setZero(2, 1);\n    rotZ.derivatives()(1) = 1.;\n\n    // PTransform<scalar_t> Rot(RotZ(rotZ));\n    PTransform<scalar_t> Rot(AngleAxis<scalar_t>(-rotZ, Vector3<scalar_t>::UnitZ()).matrix());\n    PTransform<scalar_t> Prism(prismY);\n\n    PTransform<scalar_t> res = Prism * Rot;\n\n    std::cout << res.translation()[0].derivatives().transpose() << std::endl;\n    std::cout << res.translation()[1].derivatives().transpose() << std::endl;\n    std::cout << res.translation()[2].derivatives().transpose() << std::endl;\n\n    std::cout << std::endl;\n  }\n}\n", "meta": {"hexsha": "a87ea55a1565479f8fe2133862379b0956c0b06d", "size": 2979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/AutoDiffTest.cpp", "max_stars_repo_name": "gergondet/SpaceVecAlg", "max_stars_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/AutoDiffTest.cpp", "max_issues_repo_name": "gergondet/SpaceVecAlg", "max_issues_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/AutoDiffTest.cpp", "max_forks_repo_name": "gergondet/SpaceVecAlg", "max_forks_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9043478261, "max_line_length": 94, "alphanum_fraction": 0.6555891239, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5536328650413013}}
{"text": "#include \"stat_scheduler.h\"\n\n#include <boost/optional.hpp>\n\n#include <cmath>\n\n\nnamespace {\n\n// 10%\nconst long double DEFAULT_TOLERANCE = 0.1;\n\nlong double CalcMean(long double curMean, size_t numItems, long double newItem) {\n    long double newMean = (curMean * numItems + newItem) / (numItems + 1);\n    return newMean;\n}\n\nbool IsDiffAllowed(long double diff, long double mean,\n                   long double tolerance = DEFAULT_TOLERANCE) {\n    // 10% burst is allowed\n    if (fabs(diff / mean) <= tolerance) {\n        return true;\n    }\n\n    return false;\n}\n\n} // ns\n\nnamespace Meteor {\n\nStatTracker::StatTracker()\n    : ResourcesTracker(1)\n{\n}\n\nbool StatTracker::FindFreeNode(const Job& job, Node& node) {\n    ResourceQuantity bestDiff = std::numeric_limits<ResourceQuantity>::max();\n    boost::optional<Node> bestNode;\n    for (const auto& it : State) {\n        ResourceQuantity resAvailable = it.second.Current[0];\n        if (job.ResQuantity <= resAvailable) {\n            ResourceQuantity diff = resAvailable - job.ResQuantity;\n            if (diff <= bestDiff) {\n                bestDiff = diff;\n                bestNode = it.first;\n            }\n        }\n    }\n\n    if (bestNode) {\n        node = *bestNode;\n        Acquire(node, 0, job.ResQuantity);\n        return true;\n    }\n\n    return false;\n}\n\nStatScheduler::StatScheduler(StatTracker& tracker)\n    : Tracker(tracker)\n    , DurationMean(0.0)\n    , ResourceMean(0.0)\n    , NumScheduled(0)\n{\n}\n\nEventList StatScheduler::Schedule(const Job& job) {\n    EventList events = ClearFinished(Tracker);\n\n    bool diffIsAllowed = true;\n    if (NumScheduled > 0) {\n        long double durationDiff = job.Dur - DurationMean;\n        long double resourceDiff = job.ResQuantity - ResourceMean;\n\n        diffIsAllowed = (IsDiffAllowed(durationDiff, DurationMean)\n                         && IsDiffAllowed(resourceDiff, ResourceMean));\n    }\n\n    Node node;\n    if (diffIsAllowed && Tracker.FindFreeNode(job, node)) {\n        // Resource is consumed here\n        ScheduledJob scheduledJob(job, node);\n        Jobs.insert(Timeline::value_type(CurTime + job.Dur, scheduledJob));\n        events.push_back(Event(EventType::Scheduled, CurTime, node));\n\n        DurationMean = CalcMean(DurationMean, NumScheduled, job.Dur);\n        ResourceMean = CalcMean(ResourceMean, NumScheduled, job.ResQuantity);\n\n        ++NumScheduled;\n    } else {\n        events.push_back(Event(EventType::Rejected, CurTime, Node()));\n    }\n\n    ++CurTime;\n\n    return events;\n}\n\n} // Meteor\n", "meta": {"hexsha": "0ced2231b48e0e80a2fbeb5c350521f96d3a5ae8", "size": 2510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/scheduler/stat_scheduler.cpp", "max_stars_repo_name": "familom/meteor", "max_stars_repo_head_hexsha": "6e99482914fd6ddf1a6742adeaa1b935e2b5808e", "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/scheduler/stat_scheduler.cpp", "max_issues_repo_name": "familom/meteor", "max_issues_repo_head_hexsha": "6e99482914fd6ddf1a6742adeaa1b935e2b5808e", "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/scheduler/stat_scheduler.cpp", "max_forks_repo_name": "familom/meteor", "max_forks_repo_head_hexsha": "6e99482914fd6ddf1a6742adeaa1b935e2b5808e", "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.8514851485, "max_line_length": 81, "alphanum_fraction": 0.6338645418, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5536328600904868}}
{"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#include \"rational.h\"\n#include <Eigen/Eigen>\n\n#define TOL     (1e-20f)\n\nnamespace Rational\n{\n\nint gcd (int a, int b)\n{\n  ASSERT(a >= 0, \"gcd arg 1 is not positive: \" << a);\n  ASSERT(b >= 0, \"gcd arg 2 is not positive: \" << b);\n  ASSERT(a % 1 == 0, \"gcd arg 1 is not an integer: \" << a);\n  ASSERT(b % 1 == 0, \"gcd arg 2 is not an integer: \" << b);\n\n  if (b > a) std::swap(a, b);\n  if (b == 0) return 1; // gcd(0, anything) = 0\n\n  while (true) {\n    a %= b;\n    if (a == 0) return b;\n    b %= a;\n    if (b == 0) return a;\n  }\n}\n\nstd::vector<Number> ball_of_radius (float radius)\n{\n  std::vector<Number> result;\n  for (int i = 1; i < radius; ++i) {\n    for (int j = 1; i * i + j * j <= radius * radius; ++j) {\n      if (gcd(i, j) == 1) {\n        result.push_back(Number(i, j));\n      }\n    }\n  }\n  std::sort(result.begin(), result.end());\n  return result;\n}\n\n//----( harmony )-------------------------------------------------------------\n\nHarmony::Harmony (\n    float max_radius,\n    float prior_sec, // TODO what is this used for\n    float acuity,\n    float sustain_sec,\n    float attack_sec,\n    float randomize_rate)\n\n  : m_attack(attack_sec / DEFAULT_AUDIO_FRAMERATE),\n    m_sustain(sustain_sec / DEFAULT_AUDIO_FRAMERATE),\n    m_randomize_rate(randomize_rate / sqrtf(DEFAULT_AUDIO_FRAMERATE)),\n    m_points(ball_of_radius(max_radius)),\n\n    m_pitch(m_points.size()),\n    m_energy_matrix(* new MatrixXf(m_points.size(), m_points.size())),\n    m_mass_vector(* new VectorXf(m_points.size())),\n    m_prior_vector(* new VectorXf(m_points.size())),\n    m_mass(m_points.size(), m_mass_vector.data()),\n    m_prior(m_points.size(), m_prior_vector.data()),\n    m_analysis(m_points.size()),\n    m_dmass(m_points.size()),\n\n    m_anal(m_points, acuity),\n    m_synth(m_points)\n{\n  size_t size = m_points.size();\n  LOG(\"Building Harmony with \" << size << \" points\");\n\n  for (size_t i = 0; i < size; ++i) {\n    m_pitch[i] = m_points[i].to_float();\n  }\n\n  for (size_t i = 0; i < size; ++i) {\n    for (size_t j = 0; j < size; ++j) {\n      m_energy_matrix(i, j) = m_points[i].dissonance(m_points[j]) / acuity;\n    }\n  }\n\n  ASSERT(size % 2, \"Harmony does not have an odd number of points\");\n  m_mass.zero();\n  m_mass[(size - 1) / 2] = 1; // start with all mass at center\n  m_analysis.zero();\n  m_dmass.zero();\n}\n\nHarmony::~Harmony ()\n{\n  delete & m_energy_matrix;\n  delete & m_mass_vector;\n  delete & m_prior_vector;\n}\n\nstatic const float BOGUS_MIN_FREQ = 0.1f;\nstatic const float BOGUS_MAX_FREQ = 10.0f;\n\nHarmony::Analyzer::Analyzer (\n    const std::vector<Number> & points,\n    float acuity)\n  : Synchronized::FourierBank2(Bank(\n        points.size(),\n        BOGUS_MIN_FREQ,\n        BOGUS_MAX_FREQ,\n        acuity))\n{\n  // adapted from Synchronized::Bank::init_decay_transform\n\n  ASSERT_EQ(points.size(), size);\n  const float omega0 = 2 * M_PI * MIDDLE_C_HZ / DEFAULT_SAMPLE_RATE;\n  const float order = 2;\n  const float damp_factor = pow(2, 1.0 / order) - 1;\n  const float dpitch = log(2) / acuity;\n  const float min_timescale = DEFAULT_FRAMES_PER_BUFFER;\n\n  for (size_t i = 0, I = size; i < I; ++i) {\n    double freq = omega0 * points[i].to_float();\n    double dfreq = 1 / (1 / fabs(dpitch * freq) + min_timescale);\n    std::complex<double> omega(-damp_factor * dfreq, freq);\n    std::complex<double> trans = exp(omega);\n\n    m_trans_real[i] = trans.real();\n    m_trans_imag[i] = trans.imag();\n    m_rescale[i] = pow(dfreq, order); // = 1 / E(w,0)\n  }\n}\n\nHarmony::Synthesizer::Synthesizer (const std::vector<Number> & points)\n  : Synchronized::SimpleBank(Bank(\n        points.size(),\n        BOGUS_MIN_FREQ,\n        BOGUS_MAX_FREQ))\n{\n  // adapted from Synchronized::Bank::init_transform\n\n  ASSERT_EQ(points.size(), size);\n  float omega0 = 2 * M_PI * MIDDLE_C_HZ / DEFAULT_SAMPLE_RATE;\n  for (size_t i = 0; i < size; ++i) {\n    float omega = omega0 * points[i].to_float();\n\n    m_frequency[i] = tan(omega);\n  }\n}\n\nvoid Harmony::compute_prior ()\n{\n  const size_t F = m_points.size();\n\n  float radius_scale = 1.0f / sum(m_mass);\n  m_prior_vector.noalias() = m_energy_matrix * m_mass_vector;\n  m_prior_vector *= radius_scale;\n\n  float prior_total = 0;\n  for (size_t i = 0; i < F; ++i) {\n    prior_total += m_prior[i] = expf(-m_prior[i]);\n  }\n  float prior_scale = prior_total > 0 ? 1 / prior_total : 0.0f;\n  for (size_t i = 0; i < F; ++i) {\n    m_prior[i] *= prior_scale * m_prior[i];\n  }\n}\n\nvoid Harmony::centralize_pitch ()\n{\n  const size_t F = m_points.size();\n\n  float pitch_pitch = 0;\n  float dmass_pitch = 0;\n  for (size_t i = 0; i < F; ++i) {\n    float p = m_pitch[i];\n    float m = max(TOL, m_mass[i] + m_dmass[i]);\n    float metric = 1.0f / max(TOL, sqr(m));\n    pitch_pitch += p * metric * p;\n    dmass_pitch += p * metric * m;\n  }\n\n  const float dmass_coeff = -dmass_pitch / max(TOL, pitch_pitch);\n  for (size_t i = 0; i < F; ++i) {\n    m_dmass[i] += dmass_coeff * m_pitch[i];\n    m_dmass[i] = max(m_dmass[i], TOL - m_mass[i]);\n  }\n}\n\nvoid Harmony::analyze (const Vector<complex> & sound_in)\n{\n  m_anal.sample(sound_in, m_analysis);\n}\n\nvoid Harmony::sample (Vector<complex> & sound_accum)\n{\n  const size_t F = m_points.size();\n\n  compute_prior();\n\n  for (size_t i = 0; i < F; ++i) {\n    m_dmass[i] = m_attack * m_analysis[i]\n               + (1.0f - m_sustain) * (m_prior[i] - m_mass[i])\n               + m_mass[i] * (expf(m_randomize_rate * random_std()) - 1);\n    m_dmass[i] = max(m_dmass[i], TOL - m_mass[i]);\n  }\n\n  centralize_pitch();\n\n  m_synth.sample_accum(m_mass, m_dmass, sound_accum);\n  m_mass += m_dmass;\n}\n\n} // namespace Rational\n\n", "meta": {"hexsha": "df9b6adb46799908ae339bef645804d96b5f74ac", "size": 5538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rational.cpp", "max_stars_repo_name": "fritzo/kazoo", "max_stars_repo_head_hexsha": "7281fe382b98ec81a0e223bfc76c49749543afdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T11:38:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-31T01:32:13.000Z", "max_issues_repo_path": "src/rational.cpp", "max_issues_repo_name": "fritzo/kazoo", "max_issues_repo_head_hexsha": "7281fe382b98ec81a0e223bfc76c49749543afdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rational.cpp", "max_forks_repo_name": "fritzo/kazoo", "max_forks_repo_head_hexsha": "7281fe382b98ec81a0e223bfc76c49749543afdb", "max_forks_repo_licenses": ["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.2464454976, "max_line_length": 78, "alphanum_fraction": 0.6101480679, "num_tokens": 1734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5536328485855143}}
{"text": "// Copyright (c) 2019-2020 The Dash Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"test/test_pivx.h\"\n#include \"bls/bls_ies.h\"\n#include \"bls/key_io.h\"\n#include \"bls/bls_worker.h\"\n#include \"bls/bls_wrapper.h\"\n#include \"random.h\"\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(bls_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(bls_sig_tests)\n{\n    CBLSSecretKey sk1, sk2;\n    sk1.MakeNewKey();\n    sk2.MakeNewKey();\n\n    uint256 msgHash1 = uint256S(\"0000000000000000000000000000000000000000000000000000000000000001\");\n    uint256 msgHash2 = uint256S(\"0000000000000000000000000000000000000000000000000000000000000002\");\n\n    auto sig1 = sk1.Sign(msgHash1);\n    auto sig2 = sk2.Sign(msgHash1);\n\n    BOOST_CHECK(sig1.VerifyInsecure(sk1.GetPublicKey(), msgHash1));\n    BOOST_CHECK(!sig1.VerifyInsecure(sk1.GetPublicKey(), msgHash2));\n\n    BOOST_CHECK(sig2.VerifyInsecure(sk2.GetPublicKey(), msgHash1));\n    BOOST_CHECK(!sig2.VerifyInsecure(sk2.GetPublicKey(), msgHash2));\n\n    BOOST_CHECK(!sig1.VerifyInsecure(sk2.GetPublicKey(), msgHash1));\n    BOOST_CHECK(!sig1.VerifyInsecure(sk2.GetPublicKey(), msgHash2));\n    BOOST_CHECK(!sig2.VerifyInsecure(sk1.GetPublicKey(), msgHash1));\n    BOOST_CHECK(!sig2.VerifyInsecure(sk1.GetPublicKey(), msgHash2));\n}\n\nstatic BLSIdVector GetRandomBLSIds(size_t n)\n{\n    BLSIdVector v;\n    for (size_t i = 0; i < n; i++) {\n        v.emplace_back(GetRandHash());\n    }\n    return v;\n}\n\nstd::vector<size_t> GetRandomElements(size_t m, size_t n)\n{\n    assert(m <= n);\n    std::vector<size_t> idxs;\n    for (size_t i = 0; i < n; i++) {\n        idxs.emplace_back(i);\n    }\n    Shuffle(idxs.begin(), idxs.end(), FastRandomContext());\n    return std::vector<size_t>(idxs.begin(), idxs.begin() + m);\n}\n\nstruct Member\n{\n    CBLSId id;\n    BLSVerificationVectorPtr vecP;\n    CBLSIESMultiRecipientObjects<CBLSSecretKey> contributions;\n    CBLSSecretKey skShare;\n\n    // member (operator) keys for encryption/decryption of contributions\n    CBLSSecretKey sk;\n    CBLSPublicKey pk;\n\n    Member(const CBLSId& _id): id(_id)\n    {\n        sk.MakeNewKey();\n        pk = sk.GetPublicKey();\n    }\n};\n\nBOOST_AUTO_TEST_CASE(dkg)\n{\n    CBLSWorker worker;\n    const size_t N = 40;     // quorum size\n    const size_t M = 30;     // threshold\n\n    worker.Start();\n\n    // Create N Members first\n    const BLSIdVector& ids = GetRandomBLSIds(N);\n    std::vector<Member> quorum;\n    for (const auto& id : ids) {\n        quorum.emplace_back(Member(id));\n    }\n\n    // Then generate contributions for each one\n    for (Member& m : quorum) {\n        // Generate contributions (plain text)\n        BLSSecretKeyVector pt_contributions;\n        worker.GenerateContributions((int)M, ids, m.vecP, pt_contributions);\n        BOOST_CHECK_EQUAL(m.vecP->size(), M);\n        BOOST_CHECK_EQUAL(pt_contributions.size(), N);\n        // Init encrypted multi-recipient object\n        m.contributions.InitEncrypt(N);\n        for (size_t j = 0; j < N; j++) {\n            const CBLSSecretKey& plaintext = pt_contributions[j];\n            // Verify contribution against verification vector\n            BOOST_CHECK(worker.VerifyContributionShare(ids[j], m.vecP, plaintext));\n            // Encrypt each contribution with the recipient pk\n            BOOST_CHECK(m.contributions.Encrypt(j, quorum[j].pk, plaintext, PROTOCOL_VERSION));\n        }\n    }\n\n    // Aggregate received contributions for each Member to produce key shares\n    for (size_t i = 0; i < N; i++) {\n        Member& m = quorum[i];\n        // Decrypt contributions received by m with m's secret key\n        BLSSecretKeyVector rcvSkContributions;\n        for (size_t j = 0; j < N; j++) {\n            CBLSSecretKey contribution;\n            BOOST_CHECK(quorum[j].contributions.Decrypt(i, m.sk, contribution, PROTOCOL_VERSION));\n            rcvSkContributions.emplace_back(std::move(contribution));\n        }\n        m.skShare = worker.AggregateSecretKeys(rcvSkContributions);\n        // Recover public key share for m, and check against the secret key share\n        BLSPublicKeyVector rcvPkContributions;\n        for (size_t j = 0; j < N; j++) {\n            CBLSPublicKey pkContribution = worker.BuildPubKeyShare(quorum[j].vecP, m.id);\n            // This is implied by VerifyContributionShare, but let's double check\n            BOOST_CHECK(rcvSkContributions[j].GetPublicKey() == pkContribution);\n            rcvPkContributions.emplace_back(pkContribution);\n        }\n        CBLSPublicKey pkShare = worker.AggregatePublicKeys(rcvPkContributions);\n        BOOST_CHECK(m.skShare.GetPublicKey() == pkShare);\n    }\n\n    // Each member signs a message with its key share producing a signature share\n    const uint256& msg = GetRandHash();\n    BLSSignatureVector allSigShares;\n    for (const Member& m : quorum) {\n        allSigShares.emplace_back(m.skShare.Sign(msg));\n    }\n\n    // Pick M (random) key shares and recover threshold secret/public key\n    const auto& idxs = GetRandomElements(M, N);\n    BLSSecretKeyVector skShares;\n    BLSIdVector random_ids;\n    for (size_t i : idxs) {\n        skShares.emplace_back(quorum[i].skShare);\n        random_ids.emplace_back(quorum[i].id);\n    }\n    CBLSSecretKey thresholdSk;\n    BOOST_CHECK(thresholdSk.Recover(skShares, random_ids));\n    const CBLSPublicKey& thresholdPk = thresholdSk.GetPublicKey();\n\n    // Check that the recovered threshold public key equals the verification\n    // vector free coefficient\n    std::vector<BLSVerificationVectorPtr> v;\n    for (const Member& m : quorum) v.emplace_back(m.vecP);\n    CBLSPublicKey pk = worker.BuildQuorumVerificationVector(v)->at(0);\n    BOOST_CHECK(pk == thresholdPk);\n\n    // Pick M (random, different BLSids than before) signature shares, and recover\n    // the threshold signature\n    const auto& idxs2 = GetRandomElements(M, N);\n    BLSSignatureVector sigShares;\n    BLSIdVector random_ids2;\n    for (size_t i : idxs2) {\n        sigShares.emplace_back(allSigShares[i]);\n        random_ids2.emplace_back(quorum[i].id);\n    }\n    CBLSSignature thresholdSig;\n    BOOST_CHECK(thresholdSig.Recover(sigShares, random_ids2));\n\n    // Verify threshold signature against threshold public key\n    BOOST_CHECK(thresholdSig.VerifyInsecure(thresholdPk, msg));\n\n    // Now replace a signature share with an invalid signature, recover the threshold\n    // signature again, and check that verification fails with the threshold public key\n    CBLSSecretKey dummy_sk;\n    dummy_sk.MakeNewKey();\n    CBLSSignature dummy_sig = dummy_sk.Sign(msg);\n    BOOST_CHECK(dummy_sig != sigShares[0]);\n    sigShares[0] = dummy_sig;\n    BOOST_CHECK(thresholdSig.Recover(sigShares, random_ids2));\n    BOOST_CHECK(!thresholdSig.VerifyInsecure(thresholdPk, msg));\n\n    worker.Stop();\n}\n\nBOOST_AUTO_TEST_CASE(bls_ies_tests)\n{\n    // Test basic encryption and decryption of the BLS Integrated Encryption Scheme.\n    CBLSSecretKey aliceSk;\n    aliceSk.MakeNewKey();\n    const CBLSPublicKey alicePk = aliceSk.GetPublicKey();\n    BOOST_CHECK(aliceSk.IsValid());\n\n    CBLSSecretKey bobSk;\n    bobSk.MakeNewKey();\n    const CBLSPublicKey bobPk = bobSk.GetPublicKey();\n    BOOST_CHECK(bobSk.IsValid());\n\n    // Encrypt a std::string object\n    CBLSIESEncryptedObject<std::string> iesEnc;\n\n    // Since no pad is allowed, serialized length must be a multiple of AES_BLOCKSIZE (16)\n    BOOST_CHECK(!iesEnc.Encrypt(bobPk, \"message of length 20\", PROTOCOL_VERSION));\n\n    // Message of valid length (15 + 1 byte for the total len in serialization)\n    std::string message = \".mess of len 15\";\n    BOOST_CHECK(iesEnc.Encrypt(bobPk, message, PROTOCOL_VERSION));\n\n    // valid decryption.\n    std::string decrypted_message;\n    BOOST_CHECK(iesEnc.Decrypt(bobSk, decrypted_message, PROTOCOL_VERSION));\n    BOOST_CHECK_EQUAL(decrypted_message, message);\n\n    // Invalid decryption sk\n    std::string decrypted_message2;\n    iesEnc.Decrypt(aliceSk, decrypted_message2, PROTOCOL_VERSION);\n    BOOST_CHECK(decrypted_message2 != message);\n\n    // Invalid ephemeral pubkey\n    decrypted_message2.clear();\n    auto iesEphemeralPk = iesEnc.ephemeralPubKey;\n    iesEnc.ephemeralPubKey = alicePk;\n    iesEnc.Decrypt(bobSk, decrypted_message2, PROTOCOL_VERSION);\n    BOOST_CHECK(decrypted_message2 != message);\n    iesEnc.ephemeralPubKey = iesEphemeralPk;\n\n    // Invalid iv\n    decrypted_message2.clear();\n    GetRandBytes(iesEnc.iv, sizeof(iesEnc.iv));\n    iesEnc.Decrypt(bobSk, decrypted_message2, PROTOCOL_VERSION);\n    BOOST_CHECK(decrypted_message2 != message);\n}\n\ntemplate<typename BLSKey>\nBLSKey FromHex(const std::string& str)\n{\n    BLSKey k;\n    k.SetByteVector(ParseHex(str));\n    return k;\n}\n\nBOOST_AUTO_TEST_CASE(bls_sk_io_tests)\n{\n    const auto& params = Params();\n\n    CBLSSecretKey sk = FromHex<CBLSSecretKey>(\"2eb071f4c520b3102e8cb9f520783da252d33993dba0313b501d69d113af9d39\");\n    BOOST_ASSERT(sk.IsValid());\n\n    // Basic encoding-decoding roundtrip\n    std::string encodedSk = bls::EncodeSecret(params, sk);\n    auto opSk2 = bls::DecodeSecret(params, encodedSk);\n    BOOST_CHECK(opSk2 != nullopt);\n    CBLSSecretKey sk2 = *opSk2;\n    BOOST_CHECK(sk == sk2);\n\n    // Invalid sk, one extra char\n    encodedSk.push_back('f');\n    auto opSk3 = bls::DecodeSecret(params, encodedSk);\n    BOOST_CHECK(opSk3 == nullopt);\n\n    // Invalid sk, one less char\n    encodedSk.pop_back();\n    encodedSk.pop_back();\n    auto opSk4 = bls::DecodeSecret(params, encodedSk);\n    BOOST_CHECK(opSk4 == nullopt);\n}\n\nBOOST_AUTO_TEST_CASE(bls_pk_io_tests)\n{\n    const auto& params = Params();\n\n    CBLSPublicKey pk = FromHex<CBLSPublicKey>(\"901138a12a352c7e30408c071b1ec097f32ab735a12c8dbb43c637612a3f805668a6bb73894982366d287cf0b02aaf5b\");\n    BOOST_ASSERT(pk.IsValid());\n\n    // Basic encoding-decoding roundtrip\n    std::string encodedPk = bls::EncodePublic(params, pk);\n    auto opPk2 = bls::DecodePublic(params, encodedPk);\n    BOOST_CHECK(opPk2 != nullopt);\n    CBLSPublicKey pk2 = *opPk2;\n    BOOST_CHECK(pk == pk2);\n\n    // Invalid pk, one extra char\n    encodedPk.push_back('f');\n    auto oppk3 = bls::DecodePublic(params, encodedPk);\n    BOOST_CHECK(oppk3 == nullopt);\n\n    // Invalid pk, one less char\n    encodedPk.pop_back();\n    encodedPk.pop_back();\n    auto oppk4 = bls::DecodePublic(params, encodedPk);\n    BOOST_CHECK(oppk4 == nullopt);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ba983693bfc77e34998f68ab44814c0b3e9a4ca6", "size": 10395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/bls_tests.cpp", "max_stars_repo_name": "arjundashrath/PIVX", "max_stars_repo_head_hexsha": "5a7b5141a7fcf765729ce31b6a7c0ce9b6d21969", "max_stars_repo_licenses": ["MIT"], "max_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/bls_tests.cpp", "max_issues_repo_name": "arjundashrath/PIVX", "max_issues_repo_head_hexsha": "5a7b5141a7fcf765729ce31b6a7c0ce9b6d21969", "max_issues_repo_licenses": ["MIT"], "max_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/bls_tests.cpp", "max_forks_repo_name": "arjundashrath/PIVX", "max_forks_repo_head_hexsha": "5a7b5141a7fcf765729ce31b6a7c0ce9b6d21969", "max_forks_repo_licenses": ["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": 146, "alphanum_fraction": 0.7005291005, "num_tokens": 2756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021788, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5536322272001677}}
{"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": "/*\n * SlidingWindowMathExpressionFilter.hpp\n *\n *  Created on: Aug 18, 2017\n *      Author: Peter Fankhauser\n *   Institute: ETH Zurich, ANYbotics\n */\n\n#pragma once\n\n#include \"EigenLab/EigenLab.h\"\n\n#include <grid_map_core/grid_map_core.hpp>\n\n#include <filters/filter_base.h>\n\n#include <Eigen/Core>\n#include <string>\n\nnamespace grid_map {\n\n/*!\n * Parse and evaluate a mathematical matrix expression within a sliding window on a layer of a grid map.\n */\ntemplate<typename T>\nclass SlidingWindowMathExpressionFilter : public filters::FilterBase<T>\n{\n\n public:\n  /*!\n   * Constructor\n   */\n  SlidingWindowMathExpressionFilter();\n\n  /*!\n   * Destructor.\n   */\n  virtual ~SlidingWindowMathExpressionFilter();\n\n  /*!\n   * Configures the filter from parameters on the parameter server.\n   */\n  virtual bool configure();\n\n  /*!\n   * Takes the minimum out of different layers of a grid map.\n   * @param mapIn gridMap with the different layers to take the min.\n   * @param mapOut gridMap with an additional layer containing the sum.\n   */\n  virtual bool update(const T& mapIn, T& mapOut);\n\n private:\n  //! Input layer name.\n  std::string inputLayer_;\n\n  //! Output layer name.\n  std::string outputLayer_;\n\n  //! EigenLab parser.\n  EigenLab::Parser<Eigen::MatrixXf> parser_;\n\n  //! Expression to parse.\n  std::string expression_;\n\n  //! Window size.\n  int windowSize_;\n\n  //! If window length (instead of window size) should be used.\n  bool useWindowLength_;\n\n  //! Window length.\n  double windowLength_;\n\n  //! If empty cells should be computed as well.\n  bool isComputeEmptyCells_;\n\n  //! Edge handling method.\n  SlidingWindowIterator::EdgeHandling edgeHandling_;\n};\n\n} /* namespace */\n", "meta": {"hexsha": "ee65afb1cd4eb22c9e7f2515ed450d2ab70a289b", "size": 1676, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_map_filters/include/grid_map_filters/SlidingWindowMathExpressionFilter.hpp", "max_stars_repo_name": "jacobhuesman/grid_map", "max_stars_repo_head_hexsha": "16673339229f9669aab407d60324515e2459281b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-03-12T05:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T13:22:37.000Z", "max_issues_repo_path": "grid_map_filters/include/grid_map_filters/SlidingWindowMathExpressionFilter.hpp", "max_issues_repo_name": "jacobhuesman/grid_map", "max_issues_repo_head_hexsha": "16673339229f9669aab407d60324515e2459281b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-27T18:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-27T18:45:51.000Z", "max_forks_repo_path": "grid_map_filters/include/grid_map_filters/SlidingWindowMathExpressionFilter.hpp", "max_forks_repo_name": "jacobhuesman/grid_map", "max_forks_repo_head_hexsha": "16673339229f9669aab407d60324515e2459281b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-09T09:24:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T14:58:27.000Z", "avg_line_length": 20.4390243902, "max_line_length": 104, "alphanum_fraction": 0.7028639618, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.55363221045247}}
{"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": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#include <rw/math/Math.hpp>\n#include <rw/math/MetricUtil.hpp>\n#include <rw/math/Quaternion.hpp>\n#include <rw/math/Rotation3D.hpp>\n#include <rw/math/Vector3D.hpp>\n\n#include <boost/math/special_functions/sign.hpp>\n#include <gtest/gtest.h>\n#include <math.h>\n\nusing namespace rw::math;\ntypedef Quaternion< double > QuatD;    // just abbreviations\ntypedef Quaternion< float > QuatF;\n\nbool close_enough (Quaternion<> q1, Quaternion<> q2)\n{\n    return fabs ((q1).getQx () - (q2).getQx ()) < 1e-16 &&\n           fabs ((q1).getQy () - (q2).getQy ()) < 1e-16 &&\n           fabs ((q1).getQz () - (q2).getQz ()) < 1e-16 &&\n           fabs ((q1).getQw () - (q2).getQw ()) < 1e-16;\n}\n\nQuaternion<> toQuatN (const Rotation3D<>& rot)\n{\n    double d = sqrt (std::max (0.0, 1 + rot (0, 0) + rot (1, 1) + rot (2, 2))) / 2;\n    double a = sqrt (std::max (0.0, 1 + rot (0, 0) - rot (1, 1) - rot (2, 2))) / 2;\n    double b = sqrt (std::max (0.0, 1 - rot (0, 0) + rot (1, 1) - rot (2, 2))) / 2;\n    double c = sqrt (std::max (0.0, 1 - rot (0, 0) - rot (1, 1) + rot (2, 2))) / 2;\n    a        = boost::math::copysign (a, rot (2, 1) - rot (1, 2));\n    b        = boost::math::copysign (b, rot (0, 2) - rot (2, 0));\n    c        = boost::math::copysign (c, rot (1, 0) - rot (0, 1));\n\n    return Quaternion<> (a, b, c, d);\n}\n\nQuaternion<> toQuatN2 (const Rotation3D<>& rot)\n{\n    double a, b, c, d;\n    double tr = 1.0;\n\n    if (rot (0, 0) > rot (1, 1)) {\n        tr -= rot (1, 1);\n        if (rot (0, 0) > rot (2, 2)) {\n            // 00 was biggest\n            tr += rot (0, 0) - rot (2, 2);\n            tr = sqrt (tr);\n            d  = (rot (1, 2) - rot (2, 1)) / (2 * tr);\n            a  = tr / 2;\n            b  = (rot (0, 2) + rot (2, 0)) / (2 * tr);\n            c  = (rot (1, 0) + rot (0, 1)) / (2 * tr);\n        }\n        else {\n            // 22 was biggest\n            tr += rot (2, 2) - rot (0, 0);\n            tr = sqrt (tr);\n            d  = (rot (1, 0) - rot (0, 1)) / (2 * tr);\n            a  = tr / 2;\n            b  = (rot (2, 0) + rot (0, 2)) / (2 * tr);\n            c  = (rot (1, 2) + rot (2, 1)) / (2 * tr);\n        }\n    }\n    else {\n        tr -= rot (0, 0);\n        if (rot (1, 1) > rot (2, 2)) {\n            // 11 is biggest\n            tr += rot (1, 1) - rot (2, 2);\n            tr = sqrt (tr);\n            d  = (rot (2, 0) - rot (0, 2)) / (2 * tr);\n            a  = tr / 2;\n            b  = (rot (1, 0) + rot (0, 1)) / (2 * tr);\n            c  = (rot (2, 1) + rot (1, 2)) / (2 * tr);\n        }\n        else {\n            // 22 is biggest\n            tr += rot (2, 2) - rot (1, 1);\n            tr = sqrt (tr);\n            d  = (rot (1, 0) - rot (0, 1)) / (2 * tr);\n            a  = tr / 2;\n            b  = (rot (2, 0) + rot (0, 2)) / (2 * tr);\n            c  = (rot (1, 2) + rot (2, 1)) / (2 * tr);\n        }\n    }\n\n    return Quaternion<> (a, b, c, d);\n}\n\nQuaternion<> toQuat (const Rotation3D<>& rot)\n{\n    double a, b, c, d;\n    const double tr = static_cast< double > (rot (0, 0) + rot (1, 1) + rot (2, 2) + 1);\n\n    if (tr > 1e-7) {\n        const double s = static_cast< double > (0.5) / static_cast< double > (sqrt (tr));\n        d              = static_cast< double > (0.25) / s;\n        a              = static_cast< double > (rot (2, 1) - rot (1, 2)) * s;\n        b              = static_cast< double > (rot (0, 2) - rot (2, 0)) * s;\n        c              = static_cast< double > (rot (1, 0) - rot (0, 1)) * s;\n    }\n    else {\n        if (rot (0, 0) > rot (1, 1) && rot (0, 0) > rot (2, 2)) {\n            const double sa =\n                static_cast< double > (sqrt (rot (0, 0) - rot (1, 1) - rot (2, 2) + 1.0));\n            a = static_cast< double > (0.5) * sa;\n\n            // s == 1 / (2.0  *  sa) == 0.25 / (0.5  *  sa)\n            const double s = static_cast< double > (0.25) / a;\n            b              = static_cast< double > (rot (0, 1) + rot (1, 0)) * s;\n            c              = static_cast< double > (rot (0, 2) + rot (2, 0)) * s;\n            d              = static_cast< double > (rot (1, 2) - rot (2, 1)) * s;\n        }\n        else if (rot (1, 1) > rot (2, 2)) {\n            const double sb =\n                static_cast< double > (sqrt (rot (1, 1) - rot (2, 2) - rot (0, 0) + 1));\n            b = static_cast< double > (0.5) * sb;\n\n            const double s = static_cast< double > (0.25) / b;\n            a              = static_cast< double > (rot (0, 1) + rot (1, 0)) * s;\n            c              = static_cast< double > (rot (1, 2) + rot (2, 1)) * s;\n            d              = static_cast< double > (rot (0, 2) - rot (2, 0)) * s;\n        }\n        else {\n            const double sc =\n                static_cast< double > (sqrt (rot (2, 2) - rot (0, 0) - rot (1, 1) + 1));\n            c = static_cast< double > (0.5) * sc;\n\n            const double s = static_cast< double > (0.25) / c;\n            a              = static_cast< double > (rot (0, 2) + rot (2, 0)) * s;\n            b              = static_cast< double > (rot (1, 2) + rot (2, 1)) * s;\n            d              = static_cast< double > (rot (0, 1) - rot (1, 0)) * s;\n        }\n    }\n    return Quaternion<> (a, b, c, d);\n}\n\nTEST (QuaternionTest, Conversion)\n{\n    // we generate a large amount of random rotations and and convert to and from rotation3d\n    const size_t count = 100000;\n    std::vector< Rotation3D<> > rotations (count);\n    for (size_t i = 0; i < count; i++) {\n        Rotation3D<> rot = Math::ranRotation3D< double > ();\n        for (size_t j = 0; j < 30; j++)\n            rot = rot * Math::ranRotation3D< double > ();\n        if (i == 0)\n            rot = RPY<> (0, 0, 0).toRotation3D ();\n        rotations[i] = rot;\n    }\n    const double epsilon = 0.00000001;\n\n    for (size_t i = 0; i < count; i++) {\n        Rotation3D<> rot = rotations[i];\n        Quaternion<> q (rot);\n        Rotation3D<> res = q.toRotation3D ();\n\n        EXPECT_TRUE (MetricUtil::dist2 (res * Vector3D<>::z (), rot * Vector3D<>::z ()) < epsilon);\n        EXPECT_TRUE (MetricUtil::dist2 (res * Vector3D<>::y (), rot * Vector3D<>::y ()) < epsilon);\n        EXPECT_TRUE (MetricUtil::dist2 (res * Vector3D<>::x (), rot * Vector3D<>::x ()) < epsilon);\n    }\n}\n\nTEST (QuaternionTest, MiscTest)\n{\n    // Test Quaternion(T a, T b, T c, T d) constructor\n    Quaternion<> q1 (1.0, 2.0, 3.0, 4.0);\n    EXPECT_DOUBLE_EQ (q1.getQx (), 1.0);\n    EXPECT_DOUBLE_EQ (q1.getQy (), 2.0);\n    EXPECT_DOUBLE_EQ (q1.getQz (), 3.0);\n    EXPECT_DOUBLE_EQ (q1.getQw (), 4.0);\n\n    // Test toRotation3D and Quaternion(const Rotation3D&) constructor\n    Rotation3D<> r1 = q1.toRotation3D ();\n    Quaternion<> q2 (r1);\n\n    // Test arithmetic functions\n    Quaternion<> a (1, 2, 3, 4), b (4, 3, 2, 1), c (0, 0, 0, 0), h (0, 0, 0, 0);\n    EXPECT_TRUE (close_enough (a, Quaternion<> (1.0, 2.0, 3.0, 4.0)));    // quat - quat\n    EXPECT_TRUE (close_enough (+a, Quaternion<> (1.0, 2.0, 3.0, 4.0)));\n    EXPECT_TRUE (close_enough (-a, Quaternion<> (-1.0, -2.0, -3.0, -4.0)));\n\n    EXPECT_TRUE (close_enough ((a + b), Quaternion<> (5.0, 5.0, 5.0, 5.0)));\n    EXPECT_TRUE (close_enough ((a += b), Quaternion<> (5, 5, 5, 5)));\n    EXPECT_TRUE (close_enough ((a - b), Quaternion<> (1, 2, 3, 4)));\n    EXPECT_TRUE (close_enough ((a -= b), Quaternion<> (1, 2, 3, 4)));\n\n    h = a;\n    EXPECT_TRUE (close_enough (h *= b, a * b));\n    h = a;\n    // BOOST_CHECK(close_enough( h /= b,    a / b ));\n\n    EXPECT_EQ (a , Quaternion<> (1, 2, 3, 4));\n    EXPECT_TRUE (!(a != Quaternion<> (1, 2, 3, 4)));\n    EXPECT_NE (a , Quaternion<> (0, 2, 3, 4));\n    EXPECT_NE (a , Quaternion<> (1, 0, 3, 4));\n    EXPECT_NE (a , Quaternion<> (1, 2, 0, 4));\n    EXPECT_NE (a , Quaternion<> (1, 2, 3, 0));\n\n    Quaternion< float > af;\n    af = cast< float > (a);\n    for (size_t i = 0; i < 4; i++)\n        EXPECT_EQ ((float) (a (i)) , af (i));\n    af = rw::math::cast< float > (a);    // qualified lookup\n    for (size_t i = 0; i < 4; i++)\n        EXPECT_EQ ((float) (a (i)) , af (i));\n}\n", "meta": {"hexsha": "d27e51d311a218cbd4d9db5469f1db046caf586f", "size": 8793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RobWork/gtest/math/QuaternionTest.cpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/gtest/math/QuaternionTest.cpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/gtest/math/QuaternionTest.cpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6081081081, "max_line_length": 99, "alphanum_fraction": 0.467872171, "num_tokens": 3093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5536322025886242}}
{"text": "/*\n * assesment.hpp\n *\n *  Created on: Feb 1, 2019\n *      Author: Gregory Kramida\n *   Copyright: 2019 Gregory Kramida\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n */\n\n#pragma once\n\n//libraries\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n//local\n#include \"typedefs.hpp\"\n\nnamespace math {\n\nbool almost_equal(float a, float b);\nbool almost_equal(double a, double b);\nbool almost_equal(float a, float b, float tolerance);\nbool almost_equal(float a, float b, double tolerance);\nbool almost_equal(double a, double b, double tolerance);\n\ntemplate<typename ElementType, typename ToleranceType>\nbool almost_equal(math::Vector2<ElementType> a, math::Vector2<ElementType> b, ToleranceType tolerance);\n\ntemplate<typename ElementType, typename ToleranceType>\nbool almost_equal(math::Vector3<ElementType> a, math::Vector3<ElementType> b, ToleranceType tolerance);\n\ntemplate<typename ElementType, typename ToleranceType>\nbool almost_equal(math::Matrix2<ElementType> a, math::Matrix2<ElementType> b, ToleranceType tolerance);\n\ntemplate<typename ElementType, typename ToleranceType>\nbool almost_equal(math::Matrix3<ElementType> a, math::Matrix3<ElementType> b, ToleranceType tolerance);\n\ntemplate<typename ElementType, typename ToleranceType>\nbool almost_equal(Eigen::Matrix<ElementType, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> a,\n\t\tEigen::Matrix<ElementType, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> b, ToleranceType tolerance);\n\ntemplate<typename ElementType, typename ToleranceType>\nbool almost_equal_verbose(Eigen::Matrix<ElementType, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> a,\n\t\tEigen::Matrix<ElementType, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> b, ToleranceType tolerance);\n\ntemplate<typename ElementType, typename ToleranceType>\nbool almost_equal(Eigen::Tensor<ElementType, 3, Eigen::ColMajor> a,\n\t\tEigen::Tensor<ElementType, 3, Eigen::ColMajor> b, ToleranceType tolerance);\n\ntemplate<typename ElementType, typename ToleranceType>\nbool almost_equal_verbose(Eigen::Tensor<ElementType, 3, Eigen::ColMajor> a,\n\t\tEigen::Tensor<ElementType, 3, Eigen::ColMajor> b, ToleranceType tolerance);\n\n}//namespace math\n", "meta": {"hexsha": "2e24cbf64834d6f62252c0147a49b7dfab148cb7", "size": 2681, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/almost_equal.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/almost_equal.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/almost_equal.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": 40.0149253731, "max_line_length": 106, "alphanum_fraction": 0.7739649385, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7122321964553658, "lm_q1q2_score": 0.5536179874289011}}
{"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": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2008 Roland Lichters\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include \"cdo.hpp\"\n#include \"utilities.hpp\"\n#include <ql/experimental/credit/cdo.hpp>\n#include <ql/experimental/credit/pool.hpp>\n#include <ql/experimental/credit/integralcdoengine.hpp>\n#include <ql/experimental/credit/midpointcdoengine.hpp>\n#include <ql/experimental/credit/randomdefaultlatentmodel.hpp>\n#include <ql/experimental/credit/inhomogeneouspooldef.hpp>\n#include <ql/experimental/credit/homogeneouspooldef.hpp>\n#include <ql/experimental/credit/gaussianlhplossmodel.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/termstructures/credit/flathazardrate.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/currencies/europe.hpp>\n#include <ql/functional.hpp>\n#include <boost/preprocessor/iteration/local.hpp>\n#include <iomanip>\n#include <iostream>\n\nusing namespace QuantLib;\nusing namespace std;\nusing namespace boost::unit_test_framework;\n\n#ifndef QL_PATCH_SOLARIS\n\nnamespace cdo_test {\n\n    Real hwAttachment[] = { 0.00, 0.03, 0.06, 0.10 };\n    Real hwDetachment[] = { 0.03, 0.06, 0.10, 1.00 };\n\n    struct hwDatum {\n        Real correlation;\n        Integer nm;\n        Integer nz;\n        Real trancheSpread[4];\n    };\n\n    // HW Table 7\n    // corr, Nm, Nz, 0-3, 3-6, 6-10, 10-100\n    hwDatum hwData7[] = {\n        { 0.1, -1, -1, { 2279, 450,  89,  1 } },\n        { 0.3, -1, -1, { 1487, 472, 203,  7 } },\n        // Opening the T, T&G tests too. The convolution is analytical\n        //   now so it runs it a time comparable to the gaussian tests and\n        //   has enough precission to pass the tests.\n        // Below the T models are integrated with a quadrature, even if this\n        //   is incorrect the test pass good enough, the quadrature gets to\n        //   be worst as the kernel deviates from a normal, this is low \n        //   orders of the T; here 5 is enough, 3 would not be.\n        { 0.3, -1,  5, { 1766, 420, 161,  6 } },\n        { 0.3,  5, -1, { 1444, 408, 171, 10 } },\n        { 0.3,  5,  5, { 1713, 359, 136,  9 } }\n    };\n\n    void check(int i, int j, const string& desc, Real found, Real expected,\n               Real bpTolerance, Real relativeTolerance) \n    {\n        /* Uncomment to display the full show if your debugging:\n        std::cout<< \"Case: \"<< i << \" \" << j << \" \" << found << \" :: \" \n            << expected  <<  \" (\"<< desc << \") \" << std::endl;\n        */\n        Real absDiff = found - expected;\n        Real relDiff = absDiff / expected;\n        BOOST_CHECK_MESSAGE (fabs(relDiff) < relativeTolerance ||\n                             fabs(absDiff) < bpTolerance,\n                             \"case \" << i << \" \" << j << \" (\"<< desc << \"): \"\n                             << found << \" vs. \" << expected);\n    }\n\n}\n\n#endif\n\n\nvoid CdoTest::testHW(unsigned dataSet) {\n    #ifndef QL_PATCH_SOLARIS\n\n    BOOST_TEST_MESSAGE (\"Testing CDO premiums against Hull-White values\"\n                        \" for data set \" << dataSet << \"...\");\n\n    using namespace cdo_test;\n\n    SavedSettings backup;\n\n    Size poolSize = 100;\n    Real lambda = 0.01;\n\n    // nBuckets and period determine the computation time\n    Size nBuckets = 200;\n    // Period period = 1*Months;\n    // for MC engines\n    Size numSims = 5000;\n\n    Real rate = 0.05;\n    DayCounter daycount = Actual360();\n    Compounding cmp = Continuous; // Simple;\n\n    Real recovery = 0.4;\n    vector<Real> nominals(poolSize, 100.0);\n    Real premium = 0.02;\n    Period maxTerm (5, Years);\n    Schedule schedule = MakeSchedule().from(Date (1, September, 2006))\n                                      .to(Date (1, September, 2011))\n                                      .withTenor(Period (3, Months))\n                                      .withCalendar(TARGET());\n\n    Date asofDate = Date(31, August, 2006);\n\n    Settings::instance().evaluationDate() = asofDate;\n\n    ext::shared_ptr<YieldTermStructure> yieldPtr(\n                                              new FlatForward (asofDate, rate,\n                                                               daycount, cmp));\n    Handle<YieldTermStructure> yieldHandle (yieldPtr);\n\n    Handle<Quote> hazardRate(ext::shared_ptr<Quote>(new SimpleQuote(lambda)));\n    vector<Handle<DefaultProbabilityTermStructure> > basket;\n    ext::shared_ptr<DefaultProbabilityTermStructure> ptr (\n               new FlatHazardRate (asofDate,\n                                   hazardRate,\n                                   ActualActual()));\n    ext::shared_ptr<Pool> pool (new Pool());\n    vector<string> names;\n    // probability key items\n    vector<Issuer> issuers;\n    vector<pair<DefaultProbKey,\n           Handle<DefaultProbabilityTermStructure> > > probabilities;\n    probabilities.push_back(std::make_pair(\n        NorthAmericaCorpDefaultKey(EURCurrency(),\n                                   SeniorSec,\n                                   Period(0,Weeks),\n                                   10.),\n       Handle<DefaultProbabilityTermStructure>(ptr)));\n\n    for (Size i=0; i<poolSize; ++i) {\n        ostringstream o;\n        o << \"issuer-\" << i;\n        names.push_back(o.str());\n        basket.push_back(Handle<DefaultProbabilityTermStructure>(ptr));\n        issuers.push_back(Issuer(probabilities));\n        pool->add(names.back(), issuers.back(), NorthAmericaCorpDefaultKey(\n                EURCurrency(), QuantLib::SeniorSec, Period(), 1.));\n    }\n\n    ext::shared_ptr<SimpleQuote> correlation (new SimpleQuote(0.0));\n    Handle<Quote> hCorrelation (correlation);\n    QL_REQUIRE (LENGTH(hwAttachment) == LENGTH(hwDetachment),\n                \"data length does not match\");\n\n    ext::shared_ptr<PricingEngine> midPCDOEngine( new MidPointCDOEngine(\n        yieldHandle));\n    ext::shared_ptr<PricingEngine> integralCDOEngine( new IntegralCDOEngine(\n        yieldHandle));\n\n    const Size i = dataSet;\n    correlation->setValue (hwData7[i].correlation);\n    QL_REQUIRE (LENGTH(hwAttachment) == LENGTH(hwData7[i].trancheSpread),\n                \"data length does not match\");\n    std::vector<ext::shared_ptr<DefaultLossModel> > basketModels;\n    std::vector<std::string> modelNames;\n    std::vector<Real> relativeToleranceMidp, relativeTolerancePeriod,\n        absoluteTolerance;\n\n    if (hwData7[i].nm == -1 && hwData7[i].nz == -1){\n        ext::shared_ptr<GaussianConstantLossLM> gaussKtLossLM(new\n            GaussianConstantLossLM(hCorrelation,\n            std::vector<Real>(poolSize, recovery),\n            LatentModelIntegrationType::GaussianQuadrature, poolSize,\n            GaussianCopulaPolicy::initTraits()));\n\n        // 1.-Inhomogeneous gaussian\n        modelNames.push_back(\"Inhomogeneous gaussian\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>( new\n            IHGaussPoolLossModel(gaussKtLossLM, nBuckets, 5., -5, 15)));\n        absoluteTolerance.push_back(1.);\n        relativeToleranceMidp.push_back(0.04);\n        relativeTolerancePeriod.push_back(0.04);\n        // 2.-homogeneous gaussian\n        modelNames.push_back(\"Homogeneous gaussian\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>( new\n            HomogGaussPoolLossModel(gaussKtLossLM, nBuckets, 5., -5, 15)));\n        absoluteTolerance.push_back(1.);\n        relativeToleranceMidp.push_back(0.04);\n        relativeTolerancePeriod.push_back(0.04);\n        // 3.-random default gaussian\n        modelNames.push_back(\"Random default gaussian\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>(new\n            RandomDefaultLM<GaussianCopulaPolicy>(gaussKtLossLM, numSims)));\n        absoluteTolerance.push_back(1.);\n        relativeToleranceMidp.push_back(0.07);\n        relativeTolerancePeriod.push_back(0.07);\n        // SECOND MC\n        // gaussian LHP\n        modelNames.push_back(\"Gaussian LHP\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>(new\n            GaussianLHPLossModel(hCorrelation,\n                std::vector<Real>(poolSize, recovery))));\n        absoluteTolerance.push_back(10.);\n        relativeToleranceMidp.push_back(0.5);\n        relativeTolerancePeriod.push_back(0.5);\n        // Binomial...\n        // Saddle point...\n        // Recursive ...\n    }\n    else if (hwData7[i].nm > 0 && hwData7[i].nz > 0) {\n        TCopulaPolicy::initTraits initTG;\n        initTG.tOrders.push_back(hwData7[i].nm);\n        initTG.tOrders.push_back(hwData7[i].nz);\n        ext::shared_ptr<TConstantLossLM> TKtLossLM(new TConstantLossLM(\n            hCorrelation, std::vector<Real>(poolSize, recovery),\n            LatentModelIntegrationType::GaussianQuadrature,\n            poolSize,\n            initTG));\n        // 1.-inhomogeneous studentT\n        modelNames.push_back(\"Inhomogeneous student\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>( new\n            IHStudentPoolLossModel(TKtLossLM, nBuckets, 5., -5., 15)));\n        absoluteTolerance.push_back(1.);\n        relativeToleranceMidp.push_back(0.04);\n        relativeTolerancePeriod.push_back(0.04);\n        // 2.-homogeneous student T\n        modelNames.push_back(\"Homogeneous student\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>( new\n            HomogTPoolLossModel(TKtLossLM, nBuckets, 5., -5., 15)));\n        absoluteTolerance.push_back(1.);\n        relativeToleranceMidp.push_back(0.04);\n        relativeTolerancePeriod.push_back(0.04);\n        // 3.-random default student T\n        modelNames.push_back(\"Random default studentT\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>(new\n            RandomDefaultLM<TCopulaPolicy>(TKtLossLM, numSims)));\n        absoluteTolerance.push_back(1.);\n        relativeToleranceMidp.push_back(0.07);\n        relativeTolerancePeriod.push_back(0.07);\n        // SECOND MC\n        // Binomial...\n        // Saddle point...\n        // Recursive ...\n    }\n    else if (hwData7[i].nm > 0 && hwData7[i].nz == -1) {\n        TCopulaPolicy::initTraits initTG;\n        initTG.tOrders.push_back(hwData7[i].nm);\n        initTG.tOrders.push_back(45);\n        /* T_{55} is pretty close to a gaussian. Probably theres no need to\n        be this conservative as the polynomial convolution gets shorter and\n        faster as the order decreases.\n        */\n        ext::shared_ptr<TConstantLossLM> TKtLossLM(new TConstantLossLM(\n            hCorrelation,\n            std::vector<Real>(poolSize, recovery),\n            LatentModelIntegrationType::GaussianQuadrature,\n            poolSize,\n            initTG));\n        // 1.-inhomogeneous\n        modelNames.push_back(\"Inhomogeneous student-gaussian\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>( new\n            IHStudentPoolLossModel(TKtLossLM, nBuckets, 5., -5., 15)));\n        absoluteTolerance.push_back(1.);\n        relativeToleranceMidp.push_back(0.04);\n        relativeTolerancePeriod.push_back(0.04);\n        // 2.-homogeneous\n        modelNames.push_back(\"Homogeneous student-gaussian\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>( new\n            HomogTPoolLossModel(TKtLossLM, nBuckets, 5., -5., 15)));\n        absoluteTolerance.push_back(1.);\n        relativeToleranceMidp.push_back(0.04);\n        relativeTolerancePeriod.push_back(0.04);\n        // 3.-random default\n        modelNames.push_back(\"Random default student-gaussian\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>(new\n            RandomDefaultLM<TCopulaPolicy>(TKtLossLM, numSims)));\n        absoluteTolerance.push_back(1.);\n        relativeToleranceMidp.push_back(0.07);\n        relativeTolerancePeriod.push_back(0.07);\n        // SECOND MC\n        // Binomial...\n        // Saddle point...\n        // Recursive ...\n    }\n    else if (hwData7[i].nm == -1 && hwData7[i].nz > 0) {\n        TCopulaPolicy::initTraits initTG;\n        initTG.tOrders.push_back(45);// pretty close to gaussian\n        initTG.tOrders.push_back(hwData7[i].nz);\n        ext::shared_ptr<TConstantLossLM> TKtLossLM(new TConstantLossLM(\n            hCorrelation,\n            std::vector<Real>(poolSize, recovery),\n            LatentModelIntegrationType::GaussianQuadrature,\n            poolSize,\n            initTG));\n        // 1.-inhomogeneous gaussian\n        modelNames.push_back(\"Inhomogeneous gaussian-student\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>( new\n            IHStudentPoolLossModel(TKtLossLM, nBuckets, 5., -5., 15)));\n        absoluteTolerance.push_back(1.);\n        relativeToleranceMidp.push_back(0.04);\n        relativeTolerancePeriod.push_back(0.04);\n        // 2.-homogeneous gaussian\n        modelNames.push_back(\"Homogeneous gaussian-student\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>( new\n            HomogTPoolLossModel(TKtLossLM, nBuckets, 5., -5., 15)));\n        absoluteTolerance.push_back(1.);\n        relativeToleranceMidp.push_back(0.04);\n        relativeTolerancePeriod.push_back(0.04);\n        // 3.-random default gaussian\n        modelNames.push_back(\"Random default gaussian-student\");\n        basketModels.push_back(ext::shared_ptr<DefaultLossModel>(new\n            RandomDefaultLM<TCopulaPolicy>(TKtLossLM, numSims)));\n        absoluteTolerance.push_back(1.);\n        relativeToleranceMidp.push_back(0.07);\n        relativeTolerancePeriod.push_back(0.07);\n        // SECOND MC\n        // Binomial...\n        // Saddle point...\n        // Recursive ...\n    }\n    else {\n        return;\n    }\n\n    for (Size j = 0; j < LENGTH(hwAttachment); j ++) {\n        ext::shared_ptr<Basket> basketPtr (\n            new Basket(asofDate, names, nominals, pool,\n                hwAttachment[j], hwDetachment[j]));\n        ostringstream trancheId;\n        trancheId << \"[\" << hwAttachment[j] << \" , \" << hwDetachment[j]\n            << \"]\";\n        SyntheticCDO cdoe(basketPtr, Protection::Seller,\n                          schedule, 0.0, premium, daycount, Following);\n\n        for(Size im=0; im<basketModels.size(); im++) {\n\n            basketPtr->setLossModel(basketModels[im]);\n\n            cdoe.setPricingEngine(midPCDOEngine);\n            check(i, j, modelNames[im]\n                +std::string(\" with midp integration on \")+trancheId.str(),\n                cdoe.fairPremium() * 1e4, hwData7[i].trancheSpread[j],\n                absoluteTolerance[im], relativeToleranceMidp[im]);\n\n            cdoe.setPricingEngine(integralCDOEngine);\n            check(i, j, modelNames[im]\n                +std::string(\" with step integration on \")+trancheId.str(),\n                cdoe.fairPremium() * 1e4, hwData7[i].trancheSpread[j],\n                absoluteTolerance[im], relativeTolerancePeriod[im]);\n        }\n    }\n    #endif\n}\n\n\ntest_suite* CdoTest::suite(SpeedLevel speed) {\n    test_suite* suite = BOOST_TEST_SUITE(\"CDO tests\");\n    #ifndef QL_PATCH_SOLARIS\n    if (speed == Slow) {\n        #define BOOST_PP_LOCAL_MACRO(n) \\\n            suite->add(QUANTLIB_TEST_CASE(ext::bind(&CdoTest::testHW, n)));\n\n        #define BOOST_PP_LOCAL_LIMITS (0, 4)\n        #include BOOST_PP_LOCAL_ITERATE()\n    }\n    #endif\n    return suite;\n}\n", "meta": {"hexsha": "a14e483c3144d2d205e7d030f70545612f87d883", "size": 15854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/cdo.cpp", "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": "test-suite/cdo.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": "test-suite/cdo.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": 41.0725388601, "max_line_length": 79, "alphanum_fraction": 0.6277280182, "num_tokens": 4006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312006227323, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5535453614116469}}
{"text": "/**\n * this file will contain the content for the node that will run the AA241x mission.\n *\n * This should handle publishing the simulated sensor information (TODO: figure\n * out what was decided for the sensor type...)\n *\n * This should also handle any book-keeping information that may be needed for\n * scoring or analyzing the mission performance at the end of the flight.\n */\n\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <random>\n#include <Eigen/Dense>  // eigen functions\n\n#include <ros/ros.h>\n\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/TwistStamped.h>\n#include <sensor_msgs/NavSatFix.h>\n#include <mavros_msgs/State.h>\n\n#include <aa241x_mission/MissionState.h>\n#include <aa241x_mission/SensorMeasurement.h>\n#include <aa241x_mission/PersonEstimate.h>\n#include <aa241x_mission/CoordinateConversion.h>\n#include <aa241x_mission/RequestLandingPosition.h>\n\n#include \"geodetic_trans.hpp\"\n\n\n\nclass MissionNode {\n\n\npublic:\n\n\t// TODO: constructor\n\t// TODO: decide how the settings will be passed -> I think I want them as\n\t// inputs to the constructor instead of having the constructor pull the\n\t// private NH data\n\tMissionNode(int mission_index, std::string mission_file);\n\n\t// set some optional parameters\n\tvoid setLandingGPS(double landing_lat, double landing_lon);\n\n\t// TODO: any services to broadcast (NOTE: need to figure out what services might be neded)\n\n\tbool serviceGPStoLakeLagENU(aa241x_mission::CoordinateConversion::Request &req,\n\t\taa241x_mission::CoordinateConversion::Response &res);\n\n\t/**\n\t * service to request the landing position (position of the \"truckbed\") in\n\t * the Lake Lag ENU frame\n\t * @param  req service request (empty)\n\t * @param  res service response\n\t * @return     true if successfully able to provide data\n\t */\n\tbool serviceRequestLandingPosition(aa241x_mission::RequestLandingPosition::Request &req,\n\t\taa241x_mission::RequestLandingPosition::Response &res);\n\n\t// the main function to run the node\n\tint run();\n\nprivate:\n\n\t// node handler\n\tros::NodeHandle _nh;\n\n\t// mission settings\n\tint _mission_index = 0;\n\tstd::string _mission_file;\n\n\tfloat _max_alt = 120;\t// maximum allowed altitude [m]\n\n\t// sensor setting\n\tfloat _sensor_min_h = 30.0;\t\t\t// min height AGL for the sensor [m]\n\tfloat _sensor_max_h = 100.0f;\t\t// max height AGL for the sensor [m]\n\tfloat _sensor_d_mult = 5.0f/7.0f;\t// multiplier for the equation (*h)\n\tfloat _sensor_d_offset = 28.57;\t\t// [m]\n\tfloat _sensor_stddev_a = 2;\t\t\t\t// min std dev (at height of 50m) [m]\n\tfloat _sensor_stddev_b = 1.0f/50.0f;\t// scale factor on h [m]\n\n\t// lake specific parameters\n\tdouble _lake_ctr_lat = 37.4224444;\t\t// [deg]\n\tdouble _lake_ctr_lon = -122.1760917;\t// [deg]\n\tfloat _lake_ctr_alt = 40.0;\t\t\t\t// AMSL [m]\n\tfloat _lake_ctr_alt_wgs84 = _lake_ctr_alt - 32.060;\t// need WGS84 ellipsoid height for GPS data in ROS [m]\n\tfloat _lake_radius = 160.0f;\t\t\t// in bound radius from the center [m]\n\n\t// mission monitoring\n\tbool _in_mission = false;\t\t// true if mission is running\n\tbool _oob_failure = false;\t\t// true if failed due to OOB\n\tbool _entered_area = false;\t\t// true if within the operating bounds\n\tdouble _mission_time = 0.0;\t\t// time since mission started in [sec]\n\tfloat _mission_score = 0.0;\t\t// the current score\n\n\t// scoring monitoring\n\tfloat _estimate_found_r = 1.0f;\t\t\t// the radial distance away to consider the person found\n\tstd::vector<int> _scoring_state;        // scoring state (0: no estimate entered, 1: incorrect estimate, 2: correct estimate)\n\tint _number_people_found = 0;           // number of people found correctly\n\n\t// mission \"people\"\n\tstd::vector<Eigen::Vector2f> _people;\t// the positions of the people in the world\n\n\t// random sampling stuff\n\tstd::default_random_engine _generator;\n\n\t// offsets to the local NED frame used by PX4\n\tfloat _e_offset = NAN;\n\tfloat _n_offset = NAN;\n\tfloat _u_offset = NAN;\n\tbool _lake_offset_computed = false;\n\n\t// landing coordinates\n\tdouble _landing_lat = 0.0;\n\tdouble _landing_lon = 0.0;\n\tfloat _landing_e = 0.0f;\n\tfloat _landing_n = 0.0f;\n\tbool _landing_set = false;\n\n\t// data\n\tgeometry_msgs::PoseStamped _current_local_position;\t\t// most recent local position info\n\tgeometry_msgs::PoseStamped _temp_local;\t\t\t\t\t// needed for offset calc\n\tbool _have_temp_local = false;\n\tmavros_msgs::State _current_state;\t\t\t\t\t\t// most recent state info\n\n\t// subscribers\n\tros::Subscriber _state_sub;\t\t\t// pixhawk state\n\tros::Subscriber _gps_sub;\t\t\t// filtered GPS data from the pixhawk\n\tros::Subscriber _local_pos_sub;\t\t// pixhawk local position\n\tros::Subscriber _person_found_sub;\t// location of the found individual\n\n\t// publishers\n\tros::Publisher _measurement_pub;\t// simulated sensor \"measurement\"\n\tros::Publisher _mission_state_pub;\t// the current mission state\n\tros::Publisher _lake_lag_pose_pub;\t// the lake lag position as computed by the GPS data\n\n\t// services\n\tros::ServiceServer _coord_conversion_srv;\n\tros::ServiceServer _landing_loc_srv;\n\n\t// callbacks\n\tvoid stateCallback(const mavros_msgs::State::ConstPtr& msg);\n\tvoid gpsCallback(const sensor_msgs::NavSatFix::ConstPtr& msg);\n\tvoid localPosCallback(const geometry_msgs::PoseStamped::ConstPtr& msg);\n\tvoid personFoundCallback(const aa241x_mission::PersonEstimate::ConstPtr& msg);\n\n\t// helpers\n\n\t/**\n\t * read in the mission file and load the positions of the people\n\t */\n\tvoid loadMission();\n\n\t/**\n\t * virtualization of the sensor\n\t * makes the \"measurement\" to the people and publishes the data of those in\n\t * view\n\t */\n\tvoid makeMeasurement();\n\n\t/**\n\t * publish the current mission state information\n\t * this includes the frame offset from the local ENU frame to the lake lag\n\t * ENU frame\n\t */\n\tvoid publishMissionState();\n\n};\n\n\n\nMissionNode::MissionNode(int mission_index, std::string mission_file) :\n_mission_index(mission_index),\n_mission_file(mission_file),\n_generator(ros::Time::now().toSec())\n{\n\t// load the mission\n\tloadMission();\n\n\t// subscriptions\n\t_state_sub = _nh.subscribe<mavros_msgs::State>(\"mavros/state\", 1, &MissionNode::stateCallback, this);\n\t_gps_sub = _nh.subscribe<sensor_msgs::NavSatFix>(\"/mavros/global_position/global\", 1, &MissionNode::gpsCallback, this);\n\t_local_pos_sub = _nh.subscribe<geometry_msgs::PoseStamped>(\"/mavros/local_position/pose\", 10, &MissionNode::localPosCallback, this);\n\t_person_found_sub = _nh.subscribe<aa241x_mission::PersonEstimate>(\"person_found\", 10, &MissionNode::personFoundCallback, this);\n\n\t// advertise publishers\n\t_measurement_pub = _nh.advertise<aa241x_mission::SensorMeasurement>(\"measurement\", 10);\n\t_mission_state_pub = _nh.advertise<aa241x_mission::MissionState>(\"mission_state\", 10);\n\t_lake_lag_pose_pub = _nh.advertise<geometry_msgs::PoseStamped>(\"geodetic_based_lake_lag_pose\", 10);\n\n\t// advertise coordinate conversion and landing location\n\t_coord_conversion_srv = _nh.advertiseService(\"gps_to_lake_lag\", &MissionNode::serviceGPStoLakeLagENU, this);\n\t_landing_loc_srv = _nh.advertiseService(\"lake_lag_landing_loc\", &MissionNode::serviceRequestLandingPosition, this);\n}\n\nvoid MissionNode::setLandingGPS(double landing_lat, double landing_lon) {\n\t\t_landing_lat = landing_lat;\n\t\t_landing_lon = landing_lon;\n\t\t_landing_set = true;\n\n\t\t// do the conversion\n\t\tfloat useless;\n\t\tgeodetic_trans::lla2enu(_lake_ctr_lat, _lake_ctr_lon, _lake_ctr_alt_wgs84,\n\t\t\t\t\t\t\tlanding_lat, landing_lon, 0.0f, &_landing_e, &_landing_n, &useless);\n};\n\nvoid MissionNode::stateCallback(const mavros_msgs::State::ConstPtr& msg) {\n\t_current_state = *msg;\n\n\t// check OFFBOARD based mission condition\n\tbool new_state = (_current_state.mode == \"OFFBOARD\");\n\tif (new_state != _in_mission) {\n\t\tpublishMissionState();\n\n\t\t// update state related flags to their original state\n\t\t_oob_failure = false;\n\t\t_entered_area = false;\n\t}\n\t_in_mission = new_state;\n}\n\nvoid MissionNode::gpsCallback(const sensor_msgs::NavSatFix::ConstPtr& msg) {\n\t// need to be listening to the raw GPS data for knowing the reference point\n\n\n\t// compute the lake lake frame position\n\tfloat ll_east, ll_north, ll_up;\n\n\tdouble lat = msg->latitude;\n\tdouble lon = msg->longitude;\n\tfloat alt = msg->altitude;\n\tgeodetic_trans::lla2enu(_lake_ctr_lat, _lake_ctr_lon, _lake_ctr_alt_wgs84,\n\t\t\t\t\t\t\tlat, lon, alt, &ll_east, &ll_north, &ll_up);\n\n\n\t// if we've already handled the offset computation, or don't have a fix yet\n\t// then continue\n\tif (!_lake_offset_computed && !(msg->status.status < 0) && _have_temp_local) {\n\t\t// save the current position value as the offset to the pixhawk local frame\n\n\t\t// need to acount for the fact that the drone may have moved from its (0,0,0) position\n\n\t\t_e_offset = ll_east - _temp_local.pose.position.x;\n\t\t_n_offset = ll_north - _temp_local.pose.position.y;\n\t\t_u_offset = ll_up - _temp_local.pose.position.z;\n\n\t\t// DEBUG\n\t\tROS_INFO(\"offset computed as: (%0.2f, %0.2f, %0.2f)\", _e_offset, _n_offset, _u_offset);\n\n\t\t// publish the mission state with this information\n\t\tpublishMissionState();\n\n\t\t// make as computed\n\t\t_lake_offset_computed = true;\n\t}\n\n\t// also going to publish the lake lag frame position as computed by GPS\n\tgeometry_msgs::PoseStamped lake_lag_pose_msg;\n\tlake_lag_pose_msg.header.stamp = msg->header.stamp;\n\tlake_lag_pose_msg.pose.position.x = ll_east;\n\tlake_lag_pose_msg.pose.position.y = ll_north;\n\tlake_lag_pose_msg.pose.position.z = ll_up;\n\t_lake_lag_pose_pub.publish(lake_lag_pose_msg);\n}\n\nvoid MissionNode::localPosCallback(const geometry_msgs::PoseStamped::ConstPtr& msg) {\n\n\t// if the offset hasn't been computed, don't publish anything yet\n\tif (!_lake_offset_computed) {\n\t\t_temp_local = *msg;\n\t\t_have_temp_local = true;\n\t\treturn;\n\t}\n\n\t// adjust the position with the offset (NOTE: this keeps the time the same)\n\tgeometry_msgs::PoseStamped local_pos = *msg;\n\tlocal_pos.pose.position.x += _e_offset;\n\tlocal_pos.pose.position.y += _n_offset;\n\tlocal_pos.pose.position.z += _u_offset;\n\n\t// set the current position information to be the lake local position\n\t_current_local_position = local_pos;\n\n\t// check to see if within the appropriate bounds\n\tfloat x = local_pos.pose.position.x;\n\tfloat y = local_pos.pose.position.y;\n\tfloat d_from_center = sqrt(x*x + y*y);\n\n\t// if haven't entered the \"play area\" check if we have (and update accordingly)\n\tif (!_entered_area) {\n\t\t// NOTE: have a little bit of margin to account for any GPS noise\n\t\tif (d_from_center <= (_lake_radius - 5) && local_pos.pose.position.z >= _sensor_min_h) {\n\t\t\t_entered_area = true;\n\t\t}\n\n\t} else {\t// we are in the \"play area\" and need to check if they violate the OOB conditions\n\n\t\t// if we are above 30m -> going to assume we are searching and therefore\n\t\t// need to check the OOB condition\n\t\t//\n\t\t// if we are < 30m -> assume going for a landing and allow the OOB since\n\t\t// landing area may not be within bounds\n\t\tif (local_pos.pose.position.z >= _sensor_min_h && d_from_center > _lake_radius) {\n\t\t\t// mark mission as failed (exit mission state and set score to 0)\n\t\t\t_in_mission = false;\n\t\t\t_mission_score = 0.0f;\n\t\t\t_oob_failure = true;\n\n\t\t\t// also immediately update the mission state\n\t\t\tpublishMissionState();\n\t\t}\n\n\t}\n\n\t// if have exceeded the height threshold, immediately fail the mission\n\tif (local_pos.pose.position.z > _max_alt) {\n\t\t_in_mission = false;\n\t\t_mission_score = 0.0f;\n\t\t_oob_failure = true;\n\n\t\t// also immediately update the mission state\n\t\tpublishMissionState();\n\t}\n}\n\nvoid MissionNode::personFoundCallback(const aa241x_mission::PersonEstimate::ConstPtr& msg) {\n\n\t// TODO: confirm with professor Alonso that no limit on the possible # of people found\n\t/*\n\tif (_number_people_found == 5) {\n\t\treturn;\n\t}\n\t*/\n\n\t// don't score anything if not in the mission\n\tif (!_in_mission) {\n\t\treturn;\n\t}\n\n\tdouble id = msg->id;\n\tfloat n = msg->n;\n\tfloat e = msg->e;\n\n\t// if not a valid ID, then return\n\tif (id < 0 || id > _people.size()) {\n\t\treturn;\n\t}\n\n\t// get the student estimate\n\tEigen::Vector2f est;\n\test << n, e;\n\n\t// get the true location of the person\n\tEigen::Vector2f loc = _people[id];\n\n\t// update the score\n\tif (_scoring_state[id] == 0) {\n\t\t// Increment the scoring state (so it cannot be scored again)\n\t\t_scoring_state[id] = 1;     // Assume incorrect estimate\n\n\t\t// If within the radius\n\t\tif ((loc - est).norm() <= _estimate_found_r) {\n\t\t\t// update number of people found and the mission score\n\t\t\t_number_people_found += 1;\n\t\t\t_mission_score += 10;\n\n\t\t\t// mark the estimate as having been correct\n\t\t\t_scoring_state[id] = 2;   // Correct estimate\n\t\t}\n\t}\n}\n\nvoid MissionNode::loadMission() {\n\n\t// open the mission file (display an error if the file does not exist)\n\tstd::ifstream infile(_mission_file);\n\tif (!infile.good()) {\n\t\tROS_ERROR(\"mission file does not exist!\");\n\t}\n\n\t// import the data from the mission file into the people vector\n\tfloat n, e;\n\twhile (infile >> n >> e) {\n\t\t// each person is represented by a 3 vector (NED)\n\t\tEigen::Vector2f loc;\n\t\tloc << n, e;\n\t\t_people.push_back(loc);\t\t\t// add the person location to the list\n\t\t_scoring_state.push_back(0);\t// add a 0 for this ID in the scoring state vector\n\n\t\t// DEBUG\n\t\tROS_INFO(\"adding person at: (%0.2f %0.2f)\", n, e);\n\t}\n}\n\nvoid MissionNode::makeMeasurement() {\n\n\t// put the current local position (ENU) into an NED Egien vector\n\tfloat n = _current_local_position.pose.position.y;\n\tfloat e = _current_local_position.pose.position.x;\n\tEigen::Vector2f current_pos;\n\tcurrent_pos << n, e;\n\n\t// get the height information into a local variable for readibility\n\tfloat h = _current_local_position.pose.position.z;\n\n\t// don't publish a measurement if not heigh enough\n\tif (h < _sensor_min_h) {\n\t\treturn;\n\t}\n\n\t// calculate FOV of the sensor\n\tfloat radius = (_sensor_d_mult * h + _sensor_d_offset) / 2.0f;\t// [m]\n\n\t// get the sensor distribution based on the equation\n\tfloat sensor_std = _sensor_stddev_a + h * _sensor_stddev_b;\n\tstd::normal_distribution<float> pos_distribution(0, sqrt(sensor_std));\n\n\t// the measurement message\n\taa241x_mission::SensorMeasurement meas;\n\tmeas.header.stamp = ros::Time::now();\n\tmeas.num_measurements = 0;\n\n\t// check if there are any people in view\n\tfor (uint8_t i = 0; i < _people.size(); i++) {\n\t\tEigen::Vector2f pos = _people[i];\n\n\t\t// for each person in view, get a position measurement\n\t\tif ((current_pos - pos).norm() <= radius) {\n\n\t\t\t// get the N and E coordinates of the measurement\n\t\t\tn = pos_distribution(_generator) + pos(0);\n\t\t\te = pos_distribution(_generator) + pos(1);\n\n\t\t\t// add to the message\n\t\t\tmeas.num_measurements++;\n\t\t\tmeas.id.push_back(i);\n\t\t\tmeas.n.push_back(n);\n\t\t\tmeas.e.push_back(e);\n\t\t}\n\t}\n\n\t// publish a list of position measurements or an empty measurement\n\t_measurement_pub.publish(meas);\n}\n\nvoid MissionNode::publishMissionState() {\n\n\t// populate the topic data\n\taa241x_mission::MissionState mission_state;\n\tmission_state.header.stamp = ros::Time::now();\n\tmission_state.mission_time = _mission_time;\n\n\t// handle the mission state information -> if not in mission, depends on what happened\n\tif (!_in_mission) {\n\n\t\tif (_oob_failure) {\n\t\t\tmission_state.mission_state = aa241x_mission::MissionState::MISSION_FAILED_OOB;\n\t\t} else if (_entered_area) {\n\t\t\tmission_state.mission_state = aa241x_mission::MissionState::MISSION_FAILED_OTHER;\n\t\t} else {\n\t\t\tmission_state.mission_state = aa241x_mission::MissionState::MISSION_NOT_STARTED;\n\t\t}\n\n\t} else {\n\t\tmission_state.mission_state = aa241x_mission::MissionState::MISSION_RUNNING;\n\t}\n\t// NOTE: I think we will never have a good trigger for the mission ending, so yea\n\n\t// add the offset information\n\tmission_state.e_offset = _e_offset;\n\tmission_state.n_offset = _n_offset;\n\tmission_state.u_offset = _u_offset;\n\n\t// the current score\n\tmission_state.score = _mission_score;\n\n\t// publish the information\n\t_mission_state_pub.publish(mission_state);\n}\n\n\nint MissionNode::run() {\n\n\tuint8_t counter = 0;\t// needed to rate limit the mission state info\n\tros::Rate rate(10);\t\t// run the loop at 1Hz, which allows mission state at 0.5Hz and measurement at 1/3Hz\n\tdouble last_measurement_time = ros::Time::now().toSec();\t// time of the last measurement\n\n\twhile (ros::ok()) {\n\n\t\t// make a measurement at 1/3 Hz (and if the mission conditions are met)\n\t\tfloat h = _current_local_position.pose.position.z;\n\t\tdouble current_time = ros::Time::now().toSec();\n\t\tif (_in_mission && h >= _sensor_min_h && h <= _sensor_max_h && ((current_time - last_measurement_time) >= (3.0f))) {\n\t\t\tmakeMeasurement();\n\n\t\t\t// update time on measurement\n\t\t\tlast_measurement_time = current_time;\n\t\t}\n\n\t\t// publish the mission state information\n\t\t// rate limit this information to a lower rate (e.g. 0.5 Hz)\n\t\t// NOTE: anything that changes the values in the state will cause the\n\t\t// state to be published so that critical data is sent immediately\n\t\tif (counter % 20 == 0) {\n\t\t\tpublishMissionState();\n\t\t}\n\n\t\t// ros handling + increasing the counter to rate limit topics\n\t\tros::spinOnce();\n\t\trate.sleep();\n\t\tcounter++;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n\n\nbool MissionNode::serviceGPStoLakeLagENU(aa241x_mission::CoordinateConversion::Request &req,\n\t\taa241x_mission::CoordinateConversion::Response &res) {\n\n\t// given a gps lat, lon, alt point\n\t// need to convert it to the Lake Lag frame ENU coordinate\n\n\tfloat lat = req.latitude;\n\tfloat lon = req.longitude;\n\tfloat alt = req.altitude;\n\tfloat pos_e, pos_n, pos_u;\n\n\tgeodetic_trans::lla2enu(_lake_ctr_lat, _lake_ctr_lon, _lake_ctr_alt_wgs84,\n\t\t\t\t\t\t\tlat, lon, alt, &pos_e, &pos_n, &pos_u);\n\n\tres.east = pos_e;\n\tres.north = pos_n;\n\tres.up = pos_u;\n\n\treturn true;\n}\n\nbool MissionNode::serviceRequestLandingPosition(aa241x_mission::RequestLandingPosition::Request &req,\n\t\taa241x_mission::RequestLandingPosition::Response &res) {\n\n\t// return the saved information for the landing position of the drone\n\t// NOTE: if GPS coordinates not set in the launch file -> return false\n\n\tif (!_landing_set) {\n\t\treturn false;\n\t}\n\n\t// the 2D coordinates to the landing location\n\tres.east = _landing_e;\n\tres.north = _landing_n;\n\n\treturn true;\n}\n\n\nint main(int argc, char **argv) {\n\n\t// initialize th enode\n\tros::init(argc, argv, \"mission_node\");\n\n\t// get parameters from the launch file which define some mission\n\t// settings\n\tros::NodeHandle private_nh(\"~\");\n\t// TODO: determine settings\n\tint mission_index = 0;\n\tstd::string mission_file;\n\tdouble landing_lat, landing_lon;\n\n\tprivate_nh.param(\"mission_index\", mission_index, 0);\n\tif (!private_nh.getParam(\"mission_file\", mission_file)) {\n\t\tROS_ERROR(\"failed to get mission file\");\n\t}\n\n\t// create the node\n\tMissionNode node(mission_index, mission_file);\n\n\t// handling the optional parameters\n\tif (private_nh.getParam(\"landing_lat\", landing_lat) && private_nh.getParam(\"landing_lon\", landing_lon)) {\n\t\tnode.setLandingGPS(landing_lat, landing_lon);\n\t\tROS_INFO(\"landing position coordinates: (%0.2f, %0.2f)\", landing_lat, landing_lon);\n\t} else {\n\t\tROS_INFO(\"[AA241x] no landing position set\");\n\t}\n\n\t// run the node\n\treturn node.run();\n}", "meta": {"hexsha": "992a6ecb8472035d46bfd1a20e4ae912f57cea11", "size": 18723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/aa241x_mission_node.cpp", "max_stars_repo_name": "adrnp/aa241x_mission", "max_stars_repo_head_hexsha": "bdd63ed27fe8380aed0e125fe5e15c1834dfb77d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/aa241x_mission_node.cpp", "max_issues_repo_name": "adrnp/aa241x_mission", "max_issues_repo_head_hexsha": "bdd63ed27fe8380aed0e125fe5e15c1834dfb77d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/aa241x_mission_node.cpp", "max_forks_repo_name": "adrnp/aa241x_mission", "max_forks_repo_head_hexsha": "bdd63ed27fe8380aed0e125fe5e15c1834dfb77d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T22:12:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-04T19:51:50.000Z", "avg_line_length": 31.5733558179, "max_line_length": 133, "alphanum_fraction": 0.7316669337, "num_tokens": 5111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5535453579131613}}
{"text": "// Copyright John Maddock 2006.\n// Copyright Paul A. Bristow 2007, 2009\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/test/test_exec_monitor.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/trunc.hpp>\n#include <boost/math/tools/test.hpp>\n#include \"functor.hpp\"\n#include <boost/array.hpp>\n\n#include \"handle_test_result.hpp\"\n#include \"table_type.hpp\"\n\n#ifndef SC_\n#define SC_(x) static_cast<typename table_type<T>::type>(BOOST_JOIN(x, L))\n#endif\n\ntemplate <class T>\nT binomial_wrapper(T n, T k)\n{\n   return boost::math::binomial_coefficient<T>(\n      boost::math::itrunc(n),\n      boost::math::itrunc(k));\n}\n\ntemplate <class T>\nvoid test_binomial(T, const char* type_name)\n{\n   using namespace std;\n\n   typedef T (*func_t)(T, T);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   func_t f = &binomial_wrapper<T>;\n#else\n   func_t f = &binomial_wrapper;\n#endif\n\n#include \"binomial_data.ipp\"\n\n   boost::math::tools::test_result<T> result = boost::math::tools::test_hetero<T>(\n      binomial_data, \n      bind_func<T>(f, 0, 1), \n      extract_result<T>(2));\n\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\"\n      \"Test results for small arguments and type \" << type_name << std::endl << std::endl;\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n   handle_test_result(result, binomial_data[result.worst()], result.worst(), type_name, \"binomial_coefficient\", \"Binomials: small arguments\");\n   std::cout << std::endl;\n\n#include \"binomial_large_data.ipp\"\n\n   result = boost::math::tools::test_hetero<T>(\n      binomial_large_data, \n      bind_func<T>(f, 0, 1), \n      extract_result<T>(2));\n\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\"\n      \"Test results for large arguments and type \" << type_name << std::endl << std::endl;\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n   handle_test_result(result, binomial_large_data[result.worst()], result.worst(), type_name, \"binomial_coefficient\", \"Binomials: large arguments\");\n   std::cout << std::endl;\n}\n\n", "meta": {"hexsha": "c829944f2b11eaec5c964ba86c8236bfba644558", "size": 2343, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/test/test_binomial_coeff.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/math/test/test_binomial_coeff.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/math/test/test_binomial_coeff.hpp", "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": 33.4714285714, "max_line_length": 148, "alphanum_fraction": 0.644472898, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5535453550954469}}
{"text": "#include <catch2/catch.hpp>\n#include <Euclid/Math/Numeric.h>\n\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n\nTEST_CASE(\"Math, Numeric\", \"[math][numeric]\")\n{\n    SECTION(\"equality check\")\n    {\n        float zerof = 0.0f;\n        float almost_zerof = std::sin(boost::math::double_constants::pi);\n        float onef = 1.0f;\n        float almost_onef = 0.0f;\n        for (int i = 0; i < 10; ++i) {\n            almost_onef += 0.1f;\n        }\n        double smalld = 1.0e-8;\n        double almost_smalld = smalld + 1.0e-16;\n        double larged = 1.0e8;\n        double almost_larged = larged + 1.0e-8;\n        REQUIRE(zerof != almost_zerof);\n        REQUIRE(onef != almost_onef);\n        REQUIRE(smalld != almost_smalld);\n        REQUIRE(larged != almost_larged);\n\n        SECTION(\"eq_almost is robust in most cases\")\n        {\n            REQUIRE(Euclid::eq_almost(zerof, almost_zerof));\n            REQUIRE(Euclid::eq_almost(smalld, almost_smalld));\n            REQUIRE(Euclid::eq_almost(onef, almost_onef));\n            REQUIRE(Euclid::eq_almost(larged, almost_larged));\n\n            double fail = 1.0e-8;\n            double almost_fail = fail + 1.0e-14;\n            REQUIRE(!Euclid::eq_almost(fail, almost_fail));\n            REQUIRE(Euclid::eq_almost(fail, almost_fail, 1.0e-13));\n        }\n\n        SECTION(\"eq_rel_err is valid when not comparing to small values\")\n        {\n            REQUIRE(!Euclid::eq_rel_err(zerof, almost_zerof));\n            REQUIRE(Euclid::eq_rel_err(\n                zerof,\n                almost_zerof,\n                1.0e10f * std::numeric_limits<float>::epsilon()));\n            REQUIRE(!Euclid::eq_rel_err(smalld, almost_smalld));\n            REQUIRE(Euclid::eq_rel_err(\n                smalld,\n                almost_smalld,\n                1.0e8 * std::numeric_limits<double>::epsilon()));\n            REQUIRE(Euclid::eq_rel_err(onef, almost_onef));\n            REQUIRE(Euclid::eq_rel_err(larged, almost_larged));\n        }\n\n        SECTION(\"eq_abs_err is only valid when the bound is known\")\n        {\n            REQUIRE(Euclid::eq_abs_err(zerof, almost_zerof));\n            REQUIRE(Euclid::eq_abs_err(smalld, almost_smalld));\n            REQUIRE(!Euclid::eq_abs_err(onef, almost_onef));\n            REQUIRE(Euclid::eq_abs_err(onef, almost_onef, 1.0e-6f));\n            REQUIRE(!Euclid::eq_abs_err(larged, almost_larged));\n            REQUIRE(Euclid::eq_abs_err(larged, almost_larged, 1.0e-7));\n        }\n\n        SECTION(\"eq_ulp is also robust when not comparing to small values\")\n        {\n            REQUIRE(!Euclid::eq_ulp(zerof, almost_zerof));\n            REQUIRE(!Euclid::eq_ulp(smalld, almost_smalld));\n            REQUIRE(Euclid::eq_ulp(onef, almost_onef, 1));\n            REQUIRE(!Euclid::eq_ulp(onef, almost_onef, 0));\n            REQUIRE(Euclid::eq_ulp(larged, almost_larged, 1));\n        }\n    }\n\n    SECTION(\"inequality check\")\n    {\n        float small = 0.1f;\n        float large = 1000.0f;\n        float margin = 1.0e-15f;\n\n        REQUIRE(!(small + margin < small));\n        REQUIRE(Euclid::less_safe(small + margin, small, 1.0e-14f));\n        REQUIRE(!(large + margin < large));\n        REQUIRE(Euclid::less_safe(large + margin, large));\n        REQUIRE(!(small > small + margin));\n        REQUIRE(Euclid::greater_safe(small, small + margin, 1.0e-14f));\n        REQUIRE(!(large > large + margin));\n        REQUIRE(Euclid::greater_safe(large, large + margin));\n    }\n}\n", "meta": {"hexsha": "d2b34551767802c73c6161cc8a51868f486d7f4e", "size": 3445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Math/test_Numeric.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": "test/Math/test_Numeric.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": "test/Math/test_Numeric.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": 37.4456521739, "max_line_length": 75, "alphanum_fraction": 0.5808417997, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5535453550954468}}
{"text": "//\n// Copyright (c) 2016-2020 CNRS INRIA\n//\n\n#include \"pinocchio/spatial/fwd.hpp\"\n#include \"pinocchio/spatial/se3.hpp\"\n#include \"pinocchio/multibody/visitor.hpp\"\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/multibody/data.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\n#include \"pinocchio/utils/timer.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\ntemplate<typename JointModel>\nvoid test_joint_methods(const pinocchio::JointModelBase<JointModel> & jmodel)\n{\n  typedef typename pinocchio::JointModelBase<JointModel>::JointDataDerived JointData;\n  typedef typename JointModel::ConfigVector_t ConfigVector_t;\n  typedef typename pinocchio::LieGroup<JointModel>::type LieGroupType;\n\n  JointData jdata = jmodel.createData();\n\n  ConfigVector_t ql(ConfigVector_t::Constant(jmodel.nq(),-M_PI));\n  ConfigVector_t qu(ConfigVector_t::Constant(jmodel.nq(),M_PI));\n\n  ConfigVector_t q = LieGroupType().randomConfiguration(ql,qu);\n  pinocchio::Inertia::Matrix6 I(pinocchio::Inertia::Random().matrix());\n  pinocchio::Inertia::Matrix6 I_check = I;\n\n  jmodel.calc(jdata,q);\n  jmodel.calc_aba(jdata,I,true);\n\n  Eigen::MatrixXd S = jdata.S.matrix();\n  Eigen::MatrixXd U_check = I_check*S;\n  Eigen::MatrixXd D_check = S.transpose()*U_check;\n  Eigen::MatrixXd Dinv_check = D_check.inverse();\n  Eigen::MatrixXd UDinv_check = U_check*Dinv_check;\n  Eigen::MatrixXd update_check = U_check*Dinv_check*U_check.transpose();\n  I_check -= update_check;\n\n  BOOST_CHECK(jdata.U.isApprox(U_check));\n  BOOST_CHECK(jdata.Dinv.isApprox(Dinv_check));\n  BOOST_CHECK(jdata.UDinv.isApprox(UDinv_check));\n\n  // Checking the inertia was correctly updated\n  // We use isApprox as usual, except for the freeflyer,\n  // where the correct result is exacly zero and isApprox would fail.\n  // Only for this single case, we use the infinity norm of the difference\n  if(jmodel.shortname() == \"JointModelFreeFlyer\")\n    BOOST_CHECK((I-I_check).lpNorm<Eigen::Infinity>() < Eigen::NumTraits<double>::dummy_precision());\n  else\n    BOOST_CHECK(I.isApprox(I_check));\n}\n\nstruct TestJointMethods{\n\n  template <typename JointModel>\n  void operator()(const pinocchio::JointModelBase<JointModel> &) const\n  {\n    JointModel jmodel;\n    jmodel.setIndexes(0,0,0);\n\n    test_joint_methods(jmodel);\n  }\n\n  void operator()(const pinocchio::JointModelBase<pinocchio::JointModelComposite> &) const\n  {\n    pinocchio::JointModelComposite jmodel_composite;\n    jmodel_composite.addJoint(pinocchio::JointModelRX());\n    jmodel_composite.addJoint(pinocchio::JointModelRY());\n    jmodel_composite.setIndexes(0,0,0);\n\n    //TODO: correct LieGroup\n    //test_joint_methods(jmodel_composite);\n\n  }\n\n  void operator()(const pinocchio::JointModelBase<pinocchio::JointModelRevoluteUnaligned> &) const\n  {\n    pinocchio::JointModelRevoluteUnaligned jmodel(1.5, 1., 0.);\n    jmodel.setIndexes(0,0,0);\n\n    test_joint_methods(jmodel);\n  }\n\n  void operator()(const pinocchio::JointModelBase<pinocchio::JointModelPrismaticUnaligned> &) const\n  {\n    pinocchio::JointModelPrismaticUnaligned jmodel(1.5, 1., 0.);\n    jmodel.setIndexes(0,0,0);\n\n    test_joint_methods(jmodel);\n  }\n\n};\n\nBOOST_AUTO_TEST_CASE( test_joint_basic )\n{\n  using namespace pinocchio;\n\n  typedef boost::variant< JointModelRX, JointModelRY, JointModelRZ, JointModelRevoluteUnaligned\n  , JointModelSpherical, JointModelSphericalZYX\n  , JointModelPX, JointModelPY, JointModelPZ\n  , JointModelPrismaticUnaligned\n  , JointModelFreeFlyer\n  , JointModelPlanar\n  , JointModelTranslation\n  , JointModelRUBX, JointModelRUBY, JointModelRUBZ\n  > Variant;\n\n  boost::mpl::for_each<Variant::types>(TestJointMethods());\n}\n\nBOOST_AUTO_TEST_CASE ( test_aba_simple )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n\n  pinocchio::Model model; buildModels::humanoidRandom(model);\n  \n  pinocchio::Data data(model);\n  pinocchio::Data data_ref(model);\n\n  VectorXd q = VectorXd::Ones(model.nq);\n  q.segment<4>(3).normalize();\n  VectorXd v = VectorXd::Ones(model.nv);\n  VectorXd tau = VectorXd::Zero(model.nv);\n  VectorXd a = VectorXd::Ones(model.nv);\n  \n  tau = rnea(model, data_ref, q, v, a);\n  aba(model, data, q, v, tau);\n  \n  for(size_t k = 1; k < (size_t)model.njoints; ++k)\n  {\n    BOOST_CHECK(data_ref.liMi[k].isApprox(data.liMi[k]));\n    BOOST_CHECK(data_ref.v[k].isApprox(data.v[k]));\n  }\n  \n  BOOST_CHECK(data.ddq.isApprox(a, 1e-12));\n  \n}\n\nBOOST_AUTO_TEST_CASE ( test_aba_with_fext )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model; buildModels::humanoidRandom(model);\n  \n  pinocchio::Data data(model);\n  \n  VectorXd q = VectorXd::Random(model.nq);\n  q.segment<4>(3).normalize();\n  VectorXd v = VectorXd::Random(model.nv);\n  VectorXd a = VectorXd::Random(model.nv);\n\n  PINOCCHIO_ALIGNED_STD_VECTOR(Force) fext(model.joints.size(), Force::Random());\n  \n  crba(model, data, q);\n  computeJointJacobians(model, data, q);\n  nonLinearEffects(model, data, q, v);\n  data.M.triangularView<Eigen::StrictlyLower>()\n  = data.M.transpose().triangularView<Eigen::StrictlyLower>();\n  \n\n  VectorXd tau = data.M * a + data.nle;\n  Data::Matrix6x J = Data::Matrix6x::Zero(6, model.nv);\n  for(Model::Index i=1;i<(Model::Index)model.njoints;++i) {\n    getJointJacobian(model, data, i, LOCAL, J);\n    tau -= J.transpose()*fext[i].toVector();\n    J.setZero();\n  }\n  aba(model, data, q, v, tau, fext);\n  \n  BOOST_CHECK(data.ddq.isApprox(a, 1e-12));\n}\n\nBOOST_AUTO_TEST_CASE ( test_aba_vs_rnea )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model; buildModels::humanoidRandom(model);\n  \n  pinocchio::Data data(model);\n  pinocchio::Data data_ref(model);\n  \n  VectorXd q = VectorXd::Ones(model.nq);\n  VectorXd v = VectorXd::Ones(model.nv);\n  VectorXd tau = VectorXd::Zero(model.nv);\n  VectorXd a = VectorXd::Ones(model.nv);\n  \n  crba(model, data_ref, q);\n  nonLinearEffects(model, data_ref, q, v);\n  data_ref.M.triangularView<Eigen::StrictlyLower>()\n  = data_ref.M.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  tau = data_ref.M * a + data_ref.nle;\n  aba(model, data, q, v, tau);\n  \n  VectorXd tau_ref = rnea(model, data_ref, q, v, a);\n  BOOST_CHECK(tau_ref.isApprox(tau, 1e-12));\n  \n  \n  BOOST_CHECK(data.ddq.isApprox(a, 1e-12));\n  \n}\n\nBOOST_AUTO_TEST_CASE ( test_computeMinverse )\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  pinocchio::Model model;\n  buildModels::humanoidRandom(model);\n  model.gravity.setZero();\n  \n  pinocchio::Data data(model);\n  pinocchio::Data data_ref(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  VectorXd v = VectorXd::Random(model.nv);\n\n  crba(model, data_ref, q);\n  data_ref.M.triangularView<Eigen::StrictlyLower>()\n  = data_ref.M.transpose().triangularView<Eigen::StrictlyLower>();\n  MatrixXd Minv_ref(data_ref.M.inverse());\n\n  computeMinverse(model, data, q);\n\n  \n  BOOST_CHECK(data.Minv.topRows<6>().isApprox(Minv_ref.topRows<6>()));\n  \n  data.Minv.triangularView<Eigen::StrictlyLower>()\n  = data.Minv.transpose().triangularView<Eigen::StrictlyLower>();\n  \n  BOOST_CHECK(data.Minv.isApprox(Minv_ref));\n  \n//  std::cout << \"Minv:\\n\" << data.Minv.block<10,10>(0,0) << std::endl;\n//  std::cout << \"Minv_ref:\\n\" << Minv_ref.block<10,10>(0,0) << std::endl;\n//\n//  std::cout << \"Minv:\\n\" << data.Minv.bottomRows<10>() << std::endl;\n//  std::cout << \"Minv_ref:\\n\" << Minv_ref.bottomRows<10>() << std::endl;\n  \n}\n\nBOOST_AUTO_TEST_CASE(test_multiple_calls)\n{\n  using namespace Eigen;\n  using namespace pinocchio;\n  \n  Model model;\n  buildModels::humanoidRandom(model);\n  \n  Data data1(model), data2(model);\n  \n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  VectorXd q = randomConfiguration(model);\n  \n  computeMinverse(model,data1,q);\n  data2 = data1;\n  \n  for(int k = 0; k < 20; ++k)\n  {\n    computeMinverse(model,data1,q);\n  }\n  \n  BOOST_CHECK(data1.Minv.isApprox(data2.Minv));\n}\n\nBOOST_AUTO_TEST_SUITE_END ()\n", "meta": {"hexsha": "a37589c8ecfd933236081273ce2d5b1e362a6c8e", "size": 8329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/aba.cpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 716.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T16:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:26:58.000Z", "max_issues_repo_path": "unittest/aba.cpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1130.0, "max_issues_repo_issues_event_min_datetime": "2015-02-21T17:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:06:22.000Z", "max_forks_repo_path": "unittest/aba.cpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 29.0209059233, "max_line_length": 101, "alphanum_fraction": 0.7192940329, "num_tokens": 2409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5535453509161895}}
{"text": "\r\n/*\r\n\t\r\n\tpclub03.cpp\r\n\t\r\n\tpclub01.cpp\u304b\u3089\u6d3e\u751f\u300201\u306f\u4ee5\u4e0b\u306e\u3082\u306e\u3002\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:\u3000\r\n\t\u5ea6\u6570\u5206\u5e03\u8868\u3092\u3064\u304f\u308b\u3002kstat\u3092\u898b\u3066\u3002\r\n\t\u3000\u5225\u306b\u3001\u9023\u7d9a\u5909\u6570\u7528\u306e\u6a5f\u80fd\u3092\u3064\u3051\u308b\u3002\r\n\t\u3000\u3000start/end, width, bin \u3092\u6307\u5b9a\u3059\u308b\u65b9\u5f0f\u3002\r\n\t\u3000\u3000\u81ea\u52d5\u3067\u3001\u30b9\u30bf\u30fc\u30b8\u30a7\u30b9\u306e\u516c\u5f0f\u3092\u4f7f\u3046\u65b9\u5f0f\u3002\r\n\t\u3000\u3000\u968e\u7d1a\u306e\u7aef\u70b9\u306e\u8868\u3092\u4e0e\u3048\u308b\u65b9\u5f0f\u3002\r\n\t\u30d2\u30b9\u30c8\u30b0\u30e9\u30e0\u3092\u63cf\u304f\u3002\r\n\tSVG\u306b\u3059\u308b\u3002\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// \u5ea6\u6570\u5206\u5e03\u8868\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// \u30d2\u30b9\u30c8\u30b0\u30e9\u30e0\u3092\u3064\u304f\u308a\u305f\u3044\u3002\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); // \u30a2\u30cb\u30e1\u30d0\u30fc\u30b8\u30e7\u30f3\r\n\r\n\treturn 0;\r\n\r\n\r\n\r\n\t// \u4eca\u306eRecodeTable\u306b\u306f\u3001\u5de6\u7aef\u30fb\u53f3\u7aef\u304c\u306a\u3044\uff08\u7121\u9650\u5927\uff09\u3068\u3044\u3046\u6307\u5b9a\u304c\u3067\u304d\u306a\u3044\u3002\r\n\r\n\t// FreqType\u306b\u306f\u3059\u3054\u304f\u5c0f\u3055\u3044\u6a5f\u80fd\u3060\u3051\u3092\u6301\u305f\u305b\u308b\u3053\u3068\u306b\u3057\u3066\u3001\r\n\t// \u5225\u306bFreqTableType\u304b\u4f55\u304b\u3092\u3064\u304f\u3063\u3066\u3001\u305d\u3053\u306b\u3001RecodeTable\u3092\u6301\u305f\u305b\u305f\u308a\u3001\r\n\t// \u305d\u308c\u3092\u3082\u3068\u306b\u3057\u305fFreq\u3092\u4f5c\u3089\u305b\u305f\u308a\u3057\u3066\u3082\u3088\u3044\u304b\u3082\u3002\r\n\r\n\t/*\r\n\t\u5ea6\u6570\u5206\u5e03\u8868\u3092\u3064\u304f\u308b\u3002kstat\u3092\u898b\u3066\u3002\r\n\t\u3000\u5225\u306b\u3001\u9023\u7d9a\u5909\u6570\u7528\u306e\u6a5f\u80fd\u3092\u3064\u3051\u308b\u3002\r\n\t\u3000\u3000start/end, width, bin \u3092\u6307\u5b9a\u3059\u308b\u65b9\u5f0f\u3002\r\n\t\u3000\u3000\u81ea\u52d5\u3067\u3001\u30b9\u30bf\u30fc\u30b8\u30a7\u30b9\u306e\u516c\u5f0f\u3092\u4f7f\u3046\u65b9\u5f0f\uff1f\r\n\t\u3000\u3000\u203bStata\u3067\u306f\u3001min{ sqrt(N), 10*ln(N)/ln(10)}\u3089\u3057\u3044\u306e\u3067\u3001\u305d\u308c\u3067\u3044\u304f\u3002\r\n\t\u3000\u3000\u968e\u7d1a\u306e\u7aef\u70b9\u306e\u8868\u3092\u4e0e\u3048\u308b\u65b9\u5f0f\u3002\r\n\t*/\r\n\r\n\r\n/*\r\n\t// \u3061\u3087\u3046\u3069\u3044\u3044\u9593\u9694\u3068\u57fa\u6e96\u70b9\u306e\u5b9f\u9a13\u3002\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\u306eviewBox\u306b\u3064\u3044\u3066\uff1a\u30a2\u30b9\u30da\u30af\u30c8\u6bd4\u304c\u9055\u3063\u3066\u3044\u308b\u3068\u308f\u304b\u308a\u306b\u304f\u3044\u3002\r\n\t// \uff08\u5f37\u5236\u7684\u306b\u4f59\u767d\u304c\u3064\u304f\u3089\u308c\u305f\u308a\u3059\u308b\u304b\u3001\u5f37\u5236\u7684\u306b\u62e1\u5927\u7e2e\u5c0f\u3057\u3066\u5186\u304c\u6b6a\u3093\u3060\u308a\u3059\u308b\uff09\u306e\u3067\u3001\r\n\t// svg\u30bf\u30b0\u306e\u30b5\u30a4\u30ba\u3068viewBox\u306e\u30b5\u30a4\u30ba\u3092\u5408\u308f\u305b\u305f\u3044\u3002\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// \u5b9f\u969b\u306e\u5ea7\u6a19\u7cfb\u3067\u306f\u3001y\u5ea7\u6a19\u306f\u5927\u304d\u3044\u307b\u3069\u300c\u4e0b\u300d\u306e\u4f4d\u7f6e\u3092\u793a\u3059\u3002\r\n\t\t// \u8ad6\u7406\u5ea7\u6a19\u7cfb\u3067\u306f\u3001y\u5ea7\u6a19\u306f\u5927\u304d\u3044\u307b\u3069\u300c\u4e0a\u300d\u306e\u4f4d\u7f6e\u3092\u793a\u3059\u3002\r\n\r\n\t\tdouble actuXMin, actuYMin, actuXMax, actuYMax; // \u5b9f\u969b\u306e\u5ea7\u6a19\u7cfb\u3067\u306e\u3001\u67a0\u306e\u7bc4\u56f2\r\n\t\tdouble actuWidth, actuHeight; // \u540c\u4e0a\r\n\r\n\t\tdouble theoXMin, theoYMin, theoXMax, theoYMax; // \u8ad6\u7406\u5ea7\u6a19\u7cfb\u3067\u306e\u3001\u67a0\u306e\u7bc4\u56f2\r\n\t\tdouble theoWidth, theoHeight; // \u540c\u4e0a\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// \u8ad6\u7406\u5ea7\u6a19\u7cfb\u8868\u73fe\u304b\u3089\u5b9f\u969b\u306e\u5ea7\u6a19\u7cfb\u8868\u73fe\u3092\u4f5c\u6210\u3002\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\u5ea7\u6a19\u306e\u307f\u3092\u7b97\u51fa\u2192\u8ad6\u7406\u5ea7\u6a19\u7cfb\u8868\u73fe\u304b\u3089\u5b9f\u969b\u306e\u5ea7\u6a19\u7cfb\u8868\u73fe\u3092\u4f5c\u6210\u3002\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\u5ea7\u6a19\u306e\u307f\u3092\u7b97\u51fa\u2192\u8ad6\u7406\u5ea7\u6a19\u7cfb\u8868\u73fe\u304b\u3089\u5b9f\u969b\u306e\u5ea7\u6a19\u7cfb\u8868\u73fe\u3092\u4f5c\u6210\u3002\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// \u5b9f\u969b\u306e\u5ea7\u6a19\u7cfb\u3067\u306e\u4e2d\u70b9\u306ex\u3092\u8fd4\u3059\u3002\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// \u5b9f\u969b\u306e\u5ea7\u6a19\u7cfb\u3067\u306e\u4e2d\u70b9\u306ey\u3092\u8fd4\u3059\u3002\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\u9818\u57df\u306e\u5927\u304d\u3055\u3068\u3001\u5ea7\u6a19\u7cfb\u306e\u3042\u308b\u9818\u57df\u306e\u5927\u304d\u3055\u3092\u6307\u5b9a\u3059\u308b\u3053\u3068\u3067\u3001\u305d\u308c\u3089\u3057\u304f\u8a08\u7b97\u3057\u3066\u307b\u3057\u3044\u3002\r\n\r\n\t// \u3061\u3087\u3046\u3069\u3044\u3044\u9593\u9694\u306e\u30b0\u30ea\u30c3\u30c9\u7dda\u306e\u70b9\u3068\u3001\u7bc4\u56f2\u3092\u5f97\u308b\u3002\r\n\r\n\t// x\u8ef8\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\u8ef8\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// \u63cf\u753b\u7bc4\u56f2\u306f\u3001Gridpoints\u306e\u3055\u3089\u306b5%\u5916\u5074\u306b\u3059\u308b\u3002\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\u30d5\u30a1\u30a4\u30eb\u5316\u306e\u958b\u59cb\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// \u80cc\u666f\u306e\u63cf\u753b\u958b\u59cb\r\n\r\n\t// \u80cc\u666f\u8272\u3060\u3051\u5857\u308b\u3002\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\u8ef8\u306e\u76ee\u76db\u3092\u793a\u3059\u30b0\u30ea\u30c3\u30c9\u7dda\r\n\t// <g>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u958b\u59cb\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>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u7d42\u4e86\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\r\n\t// y\u8ef8\u306e\u76ee\u76db\u3092\u793a\u3059\u30b0\u30ea\u30c3\u30c9\u7dda\r\n\t// <g>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u958b\u59cb\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>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u7d42\u4e86\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\t// \u80cc\u666f\u306e\u63cf\u753b\u7d42\u4e86\r\n\r\n\t// \u30e1\u30a4\u30f3\u306e\u60c5\u5831\u306e\u63cf\u753b\u958b\u59cb\r\n\r\n\t// \u5ea6\u6570\u3092\u793a\u3059\u30d0\u30fc\u3002\r\n\t// \u6ce8\uff1a\u3053\u308c\u3092\u76ee\u76db\u30b0\u30ea\u30c3\u30c9\u7dda\u3088\u308a\u3082\u3042\u3068\u306b\u63cf\u304f\u3079\u3057\u3002\u30b0\u30ea\u30c3\u30c9\u7dda\u3092\u300c\u4e0a\u66f8\u304d\u300d\u3057\u3066\u307b\u3057\u3044\u304b\u3089\u3002\r\n\t// <g>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u958b\u59cb\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// \u4ee5\u4e0b\u306f\u30a2\u30cb\u30e1\u7528\r\n\t\t\t// SVG\u30a2\u30cb\u30e1\u3092\u30d1\u30ef\u30dd\u306b\u8cbc\u3063\u3066\u3082\u52d5\u304b\u306a\u3044\u3089\u3057\u3044\u3002\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>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u7d42\u4e86\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\t// \u30e1\u30a4\u30f3\u306e\u60c5\u5831\u306e\u63cf\u753b\u7d42\u4e86\r\n\r\n\r\n\r\n\t// \u5468\u8fba\u60c5\u5831\u8a18\u8f09\u306e\u958b\u59cb\r\n\r\n\t// TODO: \u30d5\u30a9\u30f3\u30c8\u30b5\u30a4\u30ba\u3092\u81ea\u52d5\u8abf\u6574\u2192\u512a\u5148\u9806\u4f4d\u304c\u4f4e\u3044\u3002\u30d5\u30a9\u30f3\u30c8\u30b5\u30a4\u30ba\u56fa\u5b9a\u3067\u3082\u3044\u3044\u3002\r\n\r\n\t// x\u8ef8\u306e\u76ee\u76db\u306e\u30d2\u30b2\r\n\t// <g>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u958b\u59cb\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; // \u3068\u308a\u3042\u3048\u305a\u306e\u5024\u3002\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>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u7d42\u4e86\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\r\n\t// TODO: \u8ef8\u306e\u5358\u4f4d\u306e\u8a18\u8f09\u2192\u512a\u5148\u9806\u4f4d\u306f\u4f4e\u3044\u3002\r\n\r\n\t// text\u30bf\u30b0\u3067\u3001IE\u3084Word\u306fdominant-baseline\u304c\u52b9\u304b\u306a\u3044\u3089\u3057\u3044\u3002\r\n\t// \uff08\u6307\u5b9a\u3057\u3066\u3082dominant-baseline=\"alphabetic\"\u6271\u3044\u306b\u306a\u308b\u3002\uff09\r\n\r\n\t// x\u8ef8\u306e\u76ee\u76db\u306e\u30e9\u30d9\u30eb\r\n\tdouble xlabelfontsize = 14; // \u3068\u308a\u3042\u3048\u305a\u306e\u5024\u3002\r\n\t// <g>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u958b\u59cb\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\")\" // \u3053\u3046\u3057\u306a\u3044\u3068IE\u3084Word\u3067\u5d29\u308c\u308b\u3002\u3002\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); // \u672c\u5f53\u306fy\u8ef8\u306e\u5ea7\u6a19\u306f\u8981\u3089\u306a\u3044\u306e\u3060\u304c\u3002\u3002\r\n\r\n\t\tPoint actuP = cam.getActualFromTheoretical( theoP);\r\n\r\n\t\tdouble ticklabelmargin = 10; // \u3068\u308a\u3042\u3048\u305a\u306e\u5024\u3002\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\"(\")\" // \u5de6\u53f3\u65b9\u5411\u306b\u4e2d\u592e\u63c3\u3048\u3092\u3059\u308b\u524d\u63d0\u3067\u5ea7\u6a19\u3092\u6307\u5b9a\u3002\r\n\t\t<< \" \"\r\n\t\t// \u63cf\u753b\u9818\u57df\u306e\u4e0b\u7aef\u304b\u3089margin\u3060\u3051\u96e2\u3059\u3002\r\n\t\t// alphabetic\u306e\u57fa\u7dda\u306f\u3001\u3053\u306e\u30d5\u30a9\u30f3\u30c8\u306e\u5834\u5408\u3001\u672c\u5f53\u306e\u30d5\u30a9\u30f3\u30c8\u4e0b\u7aef\u3088\u308a20%\u4e0a\u306a\u306e\u3067\u3001\u305d\u306e\u5206\u3092\u305a\u3089\u3057\u3066\u3044\u308b\u3002\r\n\t\t<< R\"(y=\")\" << ( std::round( cam.actuYMax + ticklabelmargin + xlabelfontsize * 0.8)) << R\"(\")\" \r\n\t\t<< \">\"\r\n\t\t<< v // \u6841\u6570\u306f\u3069\u3046\u306a\u308b\u306e\u304b\u3002\u3002 \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>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u7d42\u4e86\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\t// y\u8ef8\u306e\u76ee\u76db\u306e\u30d2\u30b2\r\n\t// <g>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u958b\u59cb\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); // \u672c\u5f53\u306fy\u8ef8\u306e\u5ea7\u6a19\u306f\u8981\u3089\u306a\u3044\u306e\u3060\u304c\u3002\u3002\r\n\r\n\t\tPoint actuP = cam.getActualFromTheoretical( theoP);\r\n*/\r\n\t\tdouble tickwidth = 5; // \u3068\u308a\u3042\u3048\u305a\u306e\u5024\u3002\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>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u7d42\u4e86\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\t// y\u8ef8\u306e\u76ee\u76db\u30e9\u30d9\u30eb\r\n\t/*\r\n\t\u6587\u5b57\u5217\u3092\u56de\u8ee2\u3055\u305b\u308b\u65b9\u6cd5\u3092\u63a2\u3063\u305f\u2192svgtest04.svg\u3068svgtest05.svg\r\n\t\u3000svgtest04.svg\u30672\u3064\u306e\u65b9\u6cd5\u3092\u8a66\u3057\u305f\u304c\u3001\u3082\u3063\u3068\u30b7\u30f3\u30d7\u30eb\u306b\u3057\u305f\u304b\u3063\u305f\u3002\r\n\t\u3000svgtest05.svg\u3067\u3001transform\u5c5e\u6027\u3092\u4f7f\u3048\u3070\u3088\u3044\u3053\u3068\u304c\u308f\u304b\u3063\u305f\u3002\r\n\t*/\r\n\t// y\u8ef8\u306e\u76ee\u76db\u306e\u30e9\u30d9\u30eb\r\n\tdouble ylabelfontsize = 14; // \u3068\u308a\u3042\u3048\u305a\u306e\u5024\u3002\r\n\t// <g>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u958b\u59cb\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\")\" // \u6587\u5b57\u5217\u306e\u5de6\u53f3\u65b9\u5411\u306e\u4e2d\u5fc3\u3067\u4f4d\u7f6e\u6c7a\u3081\u3059\u308b\u3002\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; // \u3068\u308a\u3042\u3048\u305a\u306e\u5024\u3002\r\n\r\n\t\t// alphabetic\u57fa\u7dda\u306b\u5408\u308f\u305b\u308b\u305f\u3081\u306b20%\u305a\u3089\u3057\u3066\u3044\u308b\u3002\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\"(\")\" // \u63cf\u753b\u9818\u57df\u306e\u5de6\u7aef\u304b\u3089margin\u3060\u3051\u96e2\u3059\u3002\r\n\t\t<< \" \"\r\n\t\t<< R\"(y=\")\" << actuY << R\"(\")\" // \u4e0a\u4e0b\u65b9\u5411\u306b\u4e2d\u592e\u63c3\u3048\u3092\u3059\u308b\u524d\u63d0\u3067\u5ea7\u6a19\u3092\u6307\u5b9a\u3002\r\n\t\t<< \" \"\r\n\t\t<< R\"(transform=\"rotate(270 )\" << xplace << \" \" << actuY << \")\" << R\"(\")\" // \u56de\u8ee2\u306e\u4e2d\u5fc3\u304c\u5404\u70b9\u3067\u7570\u306a\u308b\u306e\u3067\u3001\u4e00\u62ec\u6307\u5b9a\u3067\u304d\u306a\u3044\u3002\r\n\t\t<< \">\"\r\n\t\t<< v // \u6841\u6570\u306f\u3069\u3046\u306a\u308b\u306e\u304b\u3002\u3002 \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>\u3067\u5c5e\u6027\u4e00\u62ec\u6307\u5b9a\uff1a\u7d42\u4e86\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// \u30b0\u30e9\u30d5\u30bf\u30a4\u30c8\u30eb\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); // \u63cf\u753b\u9818\u57df\u306e\u5e45\u306e\u3046\u3061\u30017\u5272\u3092\u5360\u3081\u308b\u3050\u3089\u3044\u306e\u30b5\u30a4\u30ba\r\n\t\tif ( fontsize >= cam.actuYMin * 0.7){ // \u4f59\u767d\u306e\u9ad8\u3055\u306e70%\u3088\u308a\u5927\u304d\u3044\u306e\u306f\u30c0\u30e1\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\"(\")\" // \u4e2d\u592e\u63c3\u3048\u3092\u3059\u308b\u306e\u3067\u3002\r\n\t\t<< \" \"\r\n\t\t<< R\"(y=\")\" << ( std::round( cam.actuYMin * 0.9)) << R\"(\")\" // \u4f59\u767d\u306e\u3046\u306110%\u6d6e\u304b\u305b\u308b\u3002\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\u8ef8\u30bf\u30a4\u30c8\u30eb\u3092\u66f8\u304f\u3002\r\n\tstring xaxislabel = \"Household Income\";\r\n\t{\r\n\r\n\t\tdouble fontsize = 20; // \u3068\u308a\u3042\u3048\u305a\u306e\u5024\u3002\r\n\t\tdouble xaxislabelmargin = 30; // \u3068\u308a\u3042\u3048\u305a\u306e\u5024\u3002\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\"(\")\" // \u4e2d\u592e\u63c3\u3048\u3092\u3059\u308b\u306e\u3067\u3002\r\n\t\t<< \" \"\r\n\t\t<< R\"(y=\")\" << ( std::round( cam.actuYMax + xaxislabelmargin + fontsize)) << R\"(\")\" // \u63cf\u753b\u9818\u57df\u306e\u4e0b\u7aef\u304b\u3089margin\u3060\u3051\u96e2\u3059\u3002\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\")\" // \u3053\u308c\u3067\u306a\u3044\u3068IE\u3084Word\u3067\u5d29\u308c\u308b\u3002\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\u8ef8\u30bf\u30a4\u30c8\u30eb\u3092\u66f8\u304f\u3002\r\n\tstring yaxislabel = \"#Cases\";\r\n\t{\r\n\r\n\t\tdouble fontsize = 20; // \u3068\u308a\u3042\u3048\u305a\u306e\u5024\u3002\r\n\t\tdouble yaxislabelmargin = 30; // \u3068\u308a\u3042\u3048\u305a\u306e\u5024\u3002\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\"(\")\" // \u63cf\u753b\u9818\u57df\u306e\u5de6\u7aef\u304b\u3089margin\u3060\u3051\u96e2\u3059\u3002\r\n\t\t<< \" \"\r\n\t\t<< R\"(y=\")\" << y << R\"(\")\" // \u4e2d\u592e\u63c3\u3048\u3092\u3059\u308b\u306e\u3067\u3002\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// \u5468\u8fba\u60c5\u5831\u8a18\u8f09\u306e\u7d42\u4e86\r\n\r\n\r\n\r\n\t// \u67a0\u7dda\u3092\u63cf\u304f\u3002\u6700\u5f8c\u306b\u3059\u3079\u304d\u3002\r\n\t// fill\u306f\u900f\u904e\u3055\u305b\u308b\u3002\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\" // \u300c\u6587\u5b57\u30b3\u30fc\u30c9\u8b58\u5225\u7528\u300d\u3068\u3044\u3046UTF-8\u6587\u5b57\u5217\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]\u306b\u3001\u3044\u3044\u611f\u3058\u306e\u9593\u9694\u3067\u70b9\u3092\u3068\u308b\u3002\r\n// k0\u500b\u4ee5\u4e0a\u3067\u6700\u5c0f\u306e\u70b9\u3092\u8fd4\u3059\u3002\r\n// newmin\u304ctrue\u306e\u3068\u304d\u3001\u5f97\u3089\u308c\u305f\u9593\u9694\u306b\u4e57\u308b\u65b0\u3057\u3044min\u3082\u8fd4\u3059\u3002\r\n// newmax\u304ctrue\u306e\u3068\u304d\u3001\u5f97\u3089\u308c\u305f\u9593\u9694\u306b\u4e57\u308b\u65b0\u3057\u3044max\u3082\u8fd4\u3059\u3002\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// \u3053\u306e\u6570\u4ee5\u4e0a\u306e\u6700\u5c0f\u306e\u70b9\u3092\u8fd4\u3059\u3088\u3046\u306b\u3059\u308b\u3002\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\u3068min0ab\u306e\u3046\u3061\u5927\u304d\u3044\u65b9\u306f\u4f55\u6841\uff1f\uff08\u305d\u306e\u5024\u30de\u30a4\u30ca\u30b91\uff09\r\n\tdouble digits_m1 = floor( log10( max( max0ab, min0ab)));\r\n\r\n\t// \u57fa\u6e96\u3068\u306a\u308b10\u306e\u3079\u304d\u4e57\u5024\r\n\tdouble base10val = pow( 10.0, digits_m1);\r\n\r\n\t// \u5019\u88dc\u3068\u306a\u308b\u3001interval\u306e\u5148\u982d\u306e\u6841\u306e\u5024\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/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_HYPOT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing hypot capabilities\n\n    Computes \\f$(x^2 + y^2)^{1/2}\\f$\n\n    @par semantic:\n    For any given value @c x,  @c y of floating type @c T:\n\n    @code\n    T r = hypot(x, y);\n    @endcode\n\n    The code of the rgular version is very similar to:\n\n    @code\n    T r = sqrt(sqr(x)+sqr(y));\n    @endcode\n\n    @par Decorators\n\n    - pedantic_ with this decorator provisions are made to avoid overflow as\n    possible and to compute  @c hypot accurately in any cases.\n\n    -std_ call std::hypot\n\n\n\n  **/\n  Value hypot(Option const& o, Value const& x, Value const& y);\n\n  //@overload\n  Value hypot(Value const& x, Value const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/hypot.hpp>\n#include <boost/simd/function/scalar/hypot.hpp>\n#include <boost/simd/function/simd/hypot.hpp>\n\n#endif\n", "meta": {"hexsha": "1325806d46123a24f9999b44022f178db6f58b78", "size": 1398, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/hypot.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "include/boost/simd/function/hypot.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/hypot.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 23.3, "max_line_length": 100, "alphanum_fraction": 0.5922746781, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5535453480984754}}
{"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": "#ifndef __LM_H__\n#define __LM_H__\n\n#include <armadillo>\n\n#include <glm/glm_info.hpp>\n#include <glm/models/glm_model.hpp>\n\n/**\n * Computes the log-likelihood of the linear model.\n *\n * @param residuals The residual vector, zero if missing.\n * @param sigma_square Estimate of the variance.\n * @param n The number of non-missing individuals.\n *\n * @return The log-likelihood of the linear model.\n */\ndouble loglikelihood(const arma::vec &residuals, double sigma_square, double n);\n\n/**\n * This function solves the linear least squares problem.\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 output Output statistics of the estimated betas.\n *\n * @return Estimated beta coefficients.\n */\narma::vec lm(const arma::mat &X, const arma::vec &y, const arma::uvec &missing, const glm_model &model, glm_info &output);\n\n#endif /* End of __LM_H__ */\n", "meta": {"hexsha": "f53166ab4fe295de0bf90b408b0dd97dcac94d0b", "size": 996, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/glm/lm.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/lm.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/lm.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": 29.2941176471, "max_line_length": 122, "alphanum_fraction": 0.7238955823, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5534693952314041}}
{"text": "/* @file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Molassembler/Shapes/CoordinateSystemTransformation.h\"\n\nBOOST_AUTO_TEST_CASE(CoordinateSystemTransformation, *boost::unit_test::label(\"Shapes\")) {\n  using namespace Scine::Molassembler::Shapes;\n  for(unsigned i = 0; i < 20; ++i) {\n    // Create two random coordinate systems\n    const CoordinateSystem a = CoordinateSystem::random();\n    const CoordinateSystem b = CoordinateSystem::random();\n\n    const auto rot = rotationMatrix(a, b);\n\n    BOOST_CHECK((rot * a.x).isApprox(b.x, 1e-10));\n    BOOST_CHECK((rot * a.y).isApprox(b.y, 1e-10));\n    BOOST_CHECK((rot * a.z).isApprox(b.z, 1e-10));\n  }\n}\n", "meta": {"hexsha": "c0215db34ffd8f58af5021d9b2b4f33c4a79a1a5", "size": 834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Shapes/CoordinateSystemTransformation.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "test/Shapes/CoordinateSystemTransformation.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Shapes/CoordinateSystemTransformation.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 33.36, "max_line_length": 90, "alphanum_fraction": 0.7050359712, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5532677629787586}}
{"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\nint main(){\n\n\tSetTransitionMatrix();\n\n\t//Output Vector\n\tv.setZero();\n\tv(0) = 1.0;\n\n\t// Print Results to File\n\tstd::ofstream myfile;\n\tmyfile.open(\"markov_results.txt\");\n\n\t\n   // TODO add Markov vector - Matrix multiplication\n\n\n\tstd::cout <<  v << std::endl;\n\t//myfile << v << std::endl;  //this is just a sample, becareful how you print to file so you can mine useful stats\n\t\n\tmyfile.close();\n\n\n  return 1;\n}", "meta": {"hexsha": "8349ccb39e2be03d6a336b3bd01b5e67000de2ad", "size": 620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homework2/SnakesAndLadders/test_markov.cpp", "max_stars_repo_name": "SteveUCF/HW2", "max_stars_repo_head_hexsha": "079de669fae83978d0985c71436a358c4ca19fc8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homework2/SnakesAndLadders/test_markov.cpp", "max_issues_repo_name": "SteveUCF/HW2", "max_issues_repo_head_hexsha": "079de669fae83978d0985c71436a358c4ca19fc8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework2/SnakesAndLadders/test_markov.cpp", "max_forks_repo_name": "SteveUCF/HW2", "max_forks_repo_head_hexsha": "079de669fae83978d0985c71436a358c4ca19fc8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2222222222, "max_line_length": 115, "alphanum_fraction": 0.6741935484, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.5532677574457971}}
{"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": "#define BOOST_TEST_MODULE \"test_worm_like_chain_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/forcefield/local/WormLikeChainPotential.hpp>\n\nBOOST_AUTO_TEST_CASE(WormLikeChain_double)\n{\n    mjolnir::LoggerManager::set_default_logger(\"test_worm_like_chain_potential.log\");\n\n    using real_type = double;\n    constexpr std::size_t N = 900;\n    constexpr real_type   h = 1e-6;\n    const real_type       p = 3.9;\n    const real_type      lc = 19.0;\n\n    mjolnir::WormLikeChainPotential<real_type> wormlikechain(p, lc);\n\n    const real_type x_min = lc * 0.0;\n    const real_type x_max = lc * 0.9;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=1; i<N; ++i)\n    {\n        const real_type x = x_min + dx * i;\n        const real_type pot1 = wormlikechain.potential(x + h);\n        const real_type pot2 = wormlikechain.potential(x - h);\n        const real_type dpot = (pot1 - pot2) / (2.0 * h);\n        const real_type deri = wormlikechain.derivative(x);\n\n        if(std::abs(dpot) > h && std::abs(deri) > h)\n        {\n            BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(WormLikeChain_float)\n{\n    using real_type = float;\n    constexpr std::size_t N = 900;\n    constexpr real_type   h = 1e-3;\n    const real_type       p = 3.9;\n    const real_type      lc = 19.0;\n\n    mjolnir::WormLikeChainPotential<real_type> wormlikechain(p, lc);\n\n    const real_type x_min = 0.0;\n    const real_type x_max = lc * 0.9;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=1; i<N; ++i)\n    {\n        const real_type x = x_min + dx * i;\n        const real_type pot1 = wormlikechain.potential(x + h);\n        const real_type pot2 = wormlikechain.potential(x - h);\n        const real_type dpot = (pot1 - pot2) / (2.0 * h);\n        const real_type deri = wormlikechain.derivative(x);\n\n        if(std::abs(dpot) > h && std::abs(deri) > h)\n        {\n            BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n        }\n    }\n}\n", "meta": {"hexsha": "63ad7f147f27feb8ae7337c4cb1e60e73148ba81", "size": 2113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_worm_like_chain_potential.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/core/test_worm_like_chain_potential.cpp", "max_issues_repo_name": "yutakasi634/Mjolnir", "max_issues_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T11:41:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T10:01:38.000Z", "max_forks_repo_path": "test/core/test_worm_like_chain_potential.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1857142857, "max_line_length": 85, "alphanum_fraction": 0.6289635589, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.553211615353527}}
{"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": "/* This file is part of the Tomographer project, which is distributed under the\n * terms of the MIT license.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist\n * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include <cmath>\n\n#include <string>\n#include <iostream>\n#include <random>\n\n#include <boost/math/constants/constants.hpp>\n\n// definitions for Tomographer test framework -- this must be included before any\n// <Eigen/...> or <tomographer/...> header\n#include \"test_tomographer.h\"\n\n#include <tomographer/mathtools/pos_semidef_util.h>\n#include <tomographer/mathtools/random_unitary.h>\n\n\n\n// -----------------------------------------------------------------------------\n// fixture(s)\n\n\n// -----------------------------------------------------------------------------\n// test suites\n\n\nBOOST_AUTO_TEST_SUITE(test_mathtools_pos_semidef_util)\n\nBOOST_AUTO_TEST_CASE(force_pos_semidef)\n{\n  Eigen::Matrix4cd rho;\n  rho <<\n    -0.1, 0, 0, 0,\n    0, 0.05, 0, 0,\n    0, 0, 0.55, 0,\n    0, 0, 0, 0.5;\n\n  BOOST_CHECK_CLOSE(rho.trace().real(), 1.0, tol_percent);\n\n  Eigen::Matrix4cd rhopos;\n\n  rhopos = Tomographer::MathTools::forcePosSemiDef<Eigen::Matrix4cd>(rho, 0.1); // high tolerance, check our algo\n\n  BOOST_CHECK_CLOSE(rhopos.trace().real(), 1.0, tol_percent);\n\n  Eigen::Matrix4cd rhopos_ref_withtol;\n  rhopos_ref_withtol <<\n    0.1, 0, 0, 0,\n    0, 0.1, 0, 0,\n    0, 0, 0.425, 0,\n    0, 0, 0, 0.375;\n  // the 0.25 \"excess trace\" is evenly subtracted from all good eigenvalues\n\n  MY_BOOST_CHECK_EIGEN_EQUAL(rhopos, rhopos_ref_withtol, tol);\n\n\n  // should get the same behavior if we apply some Unitary\n\n  // get some nontrivial unitary (fixed by deterministic seeded rng)\n  Eigen::Matrix4cd Unitary;\n  std::mt19937 rng(1); // seeded, deterministic random number generator\n  Tomographer::MathTools::randomUnitary(Unitary, rng);\n\n  BOOST_MESSAGE(\"Chose Unitary = \\n\" << Unitary) ;\n\n  Eigen::Matrix4cd rhoposU;\n  rhoposU = Tomographer::MathTools::forcePosSemiDef<Eigen::Matrix4cd>(Unitary*rho*Unitary.adjoint(), 0.1);\n\n  BOOST_CHECK_CLOSE(rhoposU.trace().real(), 1.0, tol_percent);\n  MY_BOOST_CHECK_EIGEN_EQUAL(rhoposU, Unitary*rhopos_ref_withtol*Unitary.adjoint(), tol);\n}\n\n\nBOOST_AUTO_TEST_CASE(safe_ops1)\n{\n  Eigen::Matrix3cd A;\n  A <<\n    0, 0, 0,\n    0, 0, 0,\n    0, 0, 1;\n\n  MY_BOOST_CHECK_EIGEN_EQUAL(Tomographer::MathTools::safeOperatorSqrt<Eigen::Matrix3cd>(A, 1e-18), A, 2e-9);\n  MY_BOOST_CHECK_EIGEN_EQUAL(Tomographer::MathTools::safeOperatorInvSqrt<Eigen::Matrix3cd>(A, 1e-12), A, 2e-6);\n}\n\nBOOST_AUTO_TEST_CASE(safe_ops2)\n{\n  Eigen::Matrix3cd U;\n  std::mt19937 rng(3982);\n  Tomographer::MathTools::randomUnitary(U, rng);\n\n  Eigen::Matrix3cd A;\n  A <<\n    0, 0, 0,\n    0, 0, 0,\n    0, 0, 1;\n\n  MY_BOOST_CHECK_EIGEN_EQUAL(Tomographer::MathTools::safeOperatorSqrt<Eigen::Matrix3cd>(2*U*A*U.adjoint(), 1e-18),\n                             U*A*U.adjoint()*boost::math::constants::root_two<double>(), 1e-7);\n  MY_BOOST_CHECK_EIGEN_EQUAL(Tomographer::MathTools::safeOperatorInvSqrt<Eigen::Matrix3cd>(2*U*A*U.adjoint(), 1e-12),\n                             U*A*U.adjoint()*boost::math::constants::half_root_two<double>(), 1e-5);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "65aced851a2421766b0f31d21facae2e00e37f87", "size": 4348, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/test_mathtools_pos_semidef_util.cxx", "max_stars_repo_name": "Tomographer/tomographer", "max_stars_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T02:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T02:26:00.000Z", "max_issues_repo_path": "test/test_mathtools_pos_semidef_util.cxx", "max_issues_repo_name": "Tomographer/tomographer", "max_issues_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-12T15:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T15:14:59.000Z", "max_forks_repo_path": "test/test_mathtools_pos_semidef_util.cxx", "max_forks_repo_name": "Tomographer/tomographer", "max_forks_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-10-12T15:32:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-08T11:39:49.000Z", "avg_line_length": 33.1908396947, "max_line_length": 117, "alphanum_fraction": 0.6911223551, "num_tokens": 1258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6825737214979746, "lm_q1q2_score": 0.553211604886719}}
{"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\ufffdRaphson 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": "#include <boost/math/distributions/lognormal.hpp>\n", "meta": {"hexsha": "b16cb38e115f71cb4a679ae7710a134e522ff1b6", "size": 50, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_math_distributions_lognormal.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_math_distributions_lognormal.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_math_distributions_lognormal.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.0, "max_line_length": 49, "alphanum_fraction": 0.82, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5531631654549337}}
{"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 \u00e1ngulos de la primera, segunda y tercera articulaci\u00f3n.\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\u00f3n a la primera articulaci\u00f3n, 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": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE QuaternionTest\n#define BOOST_TEST_NO_OLD_TOOLS\n#include <boost/test/unit_test.hpp>\n#include <Quaternion.h>\n#include <iostream>\n\nvoid checkEquals(const Quaternion &q1, const Quaternion &q2) {\n    BOOST_CHECK_SMALL(q1.a - q2.a, .0001);\n    BOOST_CHECK_SMALL(q1.b - q2.b, .0001);\n    BOOST_CHECK_SMALL(q1.c - q2.c, .0001);\n    BOOST_CHECK_SMALL(q1.d - q2.d, .0001);\n}\n\nBOOST_AUTO_TEST_CASE(rotateX) {\n    auto rotateX = Quaternion::from_euler_rotation(M_PI_2, 0, 0);\n    BOOST_CHECK_CLOSE(sqrt(2)/2.0, rotateX.a, .00001);\n    BOOST_CHECK_CLOSE(sqrt(2)/2.0, rotateX.b, .00001);\n    auto q = rotateX.rotate(Quaternion(0, 1, 0));\n    BOOST_CHECK_CLOSE(1.0, q.d, .00001);\n    checkEquals(q, Quaternion(0, 0, 1));\n}\n\nBOOST_AUTO_TEST_CASE(rotateY) {\n    auto rotate = Quaternion::from_euler_rotation(0, M_PI_2, 0);\n    BOOST_CHECK_CLOSE(sqrt(2)/2.0, rotate.a, .00001);\n    BOOST_CHECK_CLOSE(sqrt(2)/2.0, rotate.c, .00001);\n    auto q = rotate.rotate(Quaternion(0, 0, 1));\n    BOOST_CHECK_CLOSE(1.0, q.b, .00001);\n}\n\nBOOST_AUTO_TEST_CASE(rotateZ) {\n    auto rotate = Quaternion::from_euler_rotation(0, 0, M_PI_2);\n    BOOST_CHECK_CLOSE(sqrt(2)/2.0, rotate.a, .00001);\n    BOOST_CHECK_CLOSE(sqrt(2)/2.0, rotate.d, .00001);\n    auto q = rotate.rotate(Quaternion(1, 0, 0));\n    BOOST_CHECK_CLOSE(1.0, q.c, .00001);\n}\n\nBOOST_AUTO_TEST_CASE(rotateTwice) {\n    auto rotate = Quaternion::from_euler_rotation(0, 0, M_PI_2) *\n            Quaternion::from_euler_rotation(M_PI_2, 0, 0);\n    rotate.normalize();\n    BOOST_CHECK_CLOSE(.5, rotate.a, .0001);\n    BOOST_CHECK_CLOSE(.5, rotate.b, .0001);\n    BOOST_CHECK_CLOSE(.5, rotate.c, .0001);\n    BOOST_CHECK_CLOSE(.5, rotate.d, .0001);\n\n    auto q = rotate.rotate(Quaternion(0, 1, 0));\n    BOOST_CHECK_CLOSE(1.0, q.d, .0001);\n}\n\nBOOST_AUTO_TEST_CASE(nonCommutative) {\n    auto q1 = Quaternion::from_euler_rotation(0, 0, M_PI_2);\n    auto q2 = Quaternion::from_euler_rotation(M_PI_2, 0, 0);\n    auto rotate1 = (q1 * q2).conj();\n    auto rotate2 = q2.conj() * q1.conj();\n    checkEquals(rotate1, rotate2);\n}\n\nBOOST_AUTO_TEST_CASE(rotateRelative) {\n    auto yaw = Quaternion::from_euler_rotation(0, 0, M_PI_2);\n    auto pitch = Quaternion::from_euler_rotation(0, M_PI_2, 0);\n    auto roll = Quaternion::from_euler_rotation(M_PI_2, 0, 0);\n    auto composite = yaw * pitch * roll;\n    auto rotated = composite.rotate(Quaternion(0, 0, 1));\n    checkEquals(rotated, Quaternion(1, 0, 0));\n}\n\n", "meta": {"hexsha": "8a64841eb1ed0c01df3e5905dc8e262032a2b6a7", "size": 2468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test.cpp", "max_stars_repo_name": "carrino/Quaternion", "max_stars_repo_head_hexsha": "74545b954d73a4e322b2528e4d2032b76ebe2b87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-12-19T04:44:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T20:45:42.000Z", "max_issues_repo_path": "test/test.cpp", "max_issues_repo_name": "carrino/Quaternion", "max_issues_repo_head_hexsha": "74545b954d73a4e322b2528e4d2032b76ebe2b87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-02-16T18:07:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-09T01:00:01.000Z", "max_forks_repo_path": "test/test.cpp", "max_forks_repo_name": "carrino/Quaternion", "max_forks_repo_head_hexsha": "74545b954d73a4e322b2528e4d2032b76ebe2b87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-09-26T11:05:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T19:25:05.000Z", "avg_line_length": 35.2571428571, "max_line_length": 65, "alphanum_fraction": 0.6871961102, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.553119633964845}}
{"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": "//==================================================================================================\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_IDIVCEIL_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_IDIVCEIL_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing idivceil capabilities\n\n    Computes the integer conversion of the ceil of the division of its parameters.\n\n    @par semantic:\n    For any given value @c x,  @c y of type @c T:\n\n    @code\n    T r = idivceil(x, y);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    as_integer_t<T> r = toints(ceil(x/y));\n    @endcode\n\n    If y is @ref Zero, it returns @ref Valmax (resp. @ref Valmin)\n    if x is positive (resp. negative) and @ref Zero if x is @ref Zero.\n\n    @see toints, ceil\n\n  **/\n  const boost::dispatch::functor<tag::idivceil_> idivceil = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/idivceil.hpp>\n#include <boost/simd/function/simd/idivceil.hpp>\n\n#endif\n", "meta": {"hexsha": "41bbce14c7775a47deb502887fc24b4665fd2c71", "size": 1330, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/idivceil.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/idivceil.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/idivceil.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.0943396226, "max_line_length": 100, "alphanum_fraction": 0.5947368421, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5530513709549808}}
{"text": "#include <gtest/gtest.h>\n#include <string>\n#include <stdexcept>\n#include <Eigen/Dense>\n\n// testing following API\n#include \"estimation/IEstimator.h\"\n#include \"estimation/KalmanFilter.h\"\n#include \"estimation/Input.h\"\n#include \"estimation/InputValue.h\"\n#include \"estimation/Output.h\"\n#include \"estimation/OutputValue.h\"\n\nusing namespace std;\nusing namespace estimation;\n\nnamespace KalmanFilterTest \n{\n  // -----------------------------------------\n  // tests\n  // -----------------------------------------\n  TEST(KalmanFilterTest, initializationAndValidation)\n  {\n    KalmanFilter kf;\n\n    // check setting required params\n    EXPECT_THROW(kf.validate(), IEstimator::estimator_error);\t// \"STM missing\"\n    MatrixXd A_f(2,1); A_f << 1, 0;\n    kf.setStateTransitionModel(A_f);\n    EXPECT_THROW(kf.validate(), IEstimator::estimator_error);\t// \"OM missing\"\n    MatrixXd H(1,2); H << 1,0;\n    kf.setObservationModel(H);\n    EXPECT_THROW(kf.validate(), IEstimator::estimator_error);\t// \"PNC missing\"\n    MatrixXd Q(2,2); Q << 0.1,0,0,0.1;\n    kf.setProcessNoiseCovariance(Q);\n    EXPECT_THROW(kf.validate(), IEstimator::estimator_error);\t// \"MNC missing\"\n    MatrixXd R(1,1); R << 10;\n    kf.setMeasurementNoiseCovariance(R);\n\n    EXPECT_THROW(kf.validate(), IEstimator::estimator_error);\t// \"STM invalid size\"\n    MatrixXd A(2,2); A << 1,0,0,1;\n    kf.setStateTransitionModel(A);\n    EXPECT_NO_THROW(kf.validate());\t\t\t// all required params given\n\n    MatrixXd R_f(2,1); R_f << 10,1;\n    kf.setMeasurementNoiseCovariance(R_f);\n    EXPECT_THROW(kf.validate(), IEstimator::estimator_error);\t// \"MNC invalid size\"\n    kf.setMeasurementNoiseCovariance(R);\n    MatrixXd H_f(3,1); H_f << 1,0,2;\n    kf.setObservationModel(H_f);\n    EXPECT_THROW(kf.validate(), IEstimator::estimator_error);\t// \"OM invalid size\"\n    kf.setObservationModel(H);\n\n    // check setting optional params\n    MatrixXd B_f(1,1); B_f << 0;\n    kf.setControlInputModel(B_f);\n    EXPECT_THROW(kf.validate(), IEstimator::estimator_error);\t// \"CIM invalid size\"\n    MatrixXd B(2,1); B << 0,0;\n    kf.setControlInputModel(B);\n    EXPECT_NO_THROW(kf.validate());\n    \n    VectorXd x(2); x << 0,1;\n    kf.setInitialState(x);\n    EXPECT_NO_THROW(kf.validate());\n  \n    // check initialization of output\n    Output out = kf.getLastEstimate();\n    OutputValue defaultOutVal;\n    EXPECT_GT(out.size(), 0);\n    EXPECT_DOUBLE_EQ(out.getValue(), defaultOutVal.getValue());\n  }\n\n  TEST(KalmanFilterTest, validationEffect)\n  {  \n    KalmanFilter kf;\n\n    MatrixXd A(1,1); A << 1;\n    kf.setStateTransitionModel(A);\n    MatrixXd H(1,1); H << 1;\n    kf.setObservationModel(H);\n    MatrixXd Q(1,1); Q << 0.1;\n    kf.setProcessNoiseCovariance(Q);\n    MatrixXd R(1,1); R << 10;\n    kf.setMeasurementNoiseCovariance(R);\n\n    // validate has an effect?\n    InputValue measurement(1);\n    Input in(measurement);\n    Output out;\n  \n    EXPECT_THROW(out = kf.estimate(in), IEstimator::estimator_error);\t// \"not yet validated\"\n  \n    EXPECT_NO_THROW(kf.validate());\n\n    // changing a parameter -> KF must be re-validated\n    kf.setProcessNoiseCovariance(Q);\n    EXPECT_THROW(out = kf.estimate(in), IEstimator::estimator_error);\t// \"not yet validated\"\n    EXPECT_NO_THROW(kf.validate());\n  \n    // KF should now be released and return an estimate (should not be\n    // the default)\n    EXPECT_NO_THROW(out = kf.estimate(in));\n    EXPECT_GT(out.size(), 0);\n    EXPECT_EQ(kf.getState().size(), out.size());\n  }\n\n  TEST(KalmanFilterTest, functionality)\n  {\n    KalmanFilter kf;\n\n    MatrixXd A(1,1); A << 1;\n    kf.setStateTransitionModel(A);\n    MatrixXd H(1,1); H << 1;\n    kf.setObservationModel(H);\n    MatrixXd Q(1,1); Q << 0.1;\n    kf.setProcessNoiseCovariance(Q);\n    MatrixXd R(1,1); R << 10;\n    kf.setMeasurementNoiseCovariance(R);\n\n    kf.validate();\n    \n    // check if the calculation of an estimate is correct\n    InputValue measurement(1);\n    Input in(measurement);\n    Output out = kf.estimate(in);\n  \n    EXPECT_EQ(out.size(), 1);\n    EXPECT_NEAR(out[0].getValue(), 0.0099, 0.0001);\n    EXPECT_NEAR(out[0].getVariance(), 0.0990, 0.0001);\n\n    in[0].setValue(5);\n    EXPECT_NO_THROW(out = kf.estimate(in));\n  \n    EXPECT_NEAR(out[0].getValue(), 0.1073, 0.0001);\n    EXPECT_NEAR(out[0].getVariance(), 0.1951, 0.0001);\n\n    // missing measurement\n    InputValue missingValue;\n    Input inMissing(missingValue);\n    EXPECT_NO_THROW(out = kf.estimate(inMissing));\n  \n    EXPECT_NEAR(out[0].getValue(), 0.1073, 0.0001);\n    EXPECT_NEAR(out[0].getVariance(), 0.2866, 0.0001);\n\n    // another example ---------------------------------\n    KalmanFilter kf2;\n    MatrixXd A2(2,2); A2 << 1,0.1,0,1;\n    kf2.setStateTransitionModel(A2);\n    MatrixXd H2(1,2); H2 << 0,1;\n    kf2.setObservationModel(H2);\n    MatrixXd Q2(2,2); Q2 << 0.1,0,0,0.1;\n    kf2.setProcessNoiseCovariance(Q2);\n    MatrixXd R2(1,1); R2 << 10;\n    kf2.setMeasurementNoiseCovariance(R2);\n\n    kf2.validate();\n\n    in[0].setValue(1);\n    EXPECT_NO_THROW(out = kf2.estimate(in));\n    EXPECT_EQ(out.size(), 2);\n    \n    EXPECT_NEAR(out[0].getValue(), 0.0, 0.0001);\n    EXPECT_NEAR(out[0].getVariance(), 0.1, 0.0001);\n    EXPECT_NEAR(out[1].getValue(), 0.0099, 0.0001);\n    EXPECT_NEAR(out[1].getVariance(), 0.0990, 0.0001);\n\n    // add control input\n    MatrixXd B2(2,1); B2 << 0,1;\n    kf2.setControlInputModel(B2);\t// needs to be validated\n    InputValue ctrl(0.5);\n    Input in_ctrl(ctrl);\n    kf2.setControlInput(in_ctrl);\n\n    in[0].setValue(5);\n    EXPECT_NO_THROW(kf2.validate());\n    EXPECT_NO_THROW(out = kf2.estimate(in));\n    \n    EXPECT_NEAR(out[0].getValue(), 0.0053, 0.0001);\n    EXPECT_NEAR(out[0].getVariance(), 0.20098, 0.0001);\n    EXPECT_NEAR(out[1].getValue(), 0.5975, 0.0001);\n    EXPECT_NEAR(out[1].getVariance(), 0.1951, 0.0001);\n\n    // pass control input with invalid size\n    in_ctrl.add(ctrl);\t// -> u.size = 2\n\n    // setting invalid control input throws exception\n    EXPECT_THROW(kf2.setControlInput(in_ctrl), length_error);\n\n    // changing control input model works\n    MatrixXd B3(2,2); B3 << 0,0,0,0;\n    EXPECT_NO_THROW(kf2.setControlInputModel(B3));\n    EXPECT_ANY_THROW(out = kf2.estimate(in));\t\t// not validated\n    EXPECT_NO_THROW(kf2.validate()); \n\n    // missing measurement\n    EXPECT_NO_THROW(out = kf2.estimate(inMissing));\n  \n    EXPECT_NEAR(out[0].getValue(), 0.0651, 0.0001);\n    EXPECT_NEAR(out[0].getVariance(), 0.3048, 0.0001);\n    EXPECT_NEAR(out[1].getValue(), 0.5975, 0.0001);\n    EXPECT_NEAR(out[1].getVariance(), 0.2867, 0.0001);\n  }\n}\n", "meta": {"hexsha": "235a39f9882fd2b7e0d761844db9bed833d619f8", "size": 6494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sf_estimation/tests/utest_KalmanFilter.cpp", "max_stars_repo_name": "tuw-cpsg/sf-pkg", "max_stars_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T09:47:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T16:01:11.000Z", "max_issues_repo_path": "sf_estimation/tests/utest_KalmanFilter.cpp", "max_issues_repo_name": "ros-agriculture/sf-pkg", "max_issues_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T04:59:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-13T14:39:24.000Z", "max_forks_repo_path": "sf_estimation/tests/utest_KalmanFilter.cpp", "max_forks_repo_name": "tuw-cpsg/sf-pkg", "max_forks_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-17T21:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T17:00:28.000Z", "avg_line_length": 31.8333333333, "max_line_length": 92, "alphanum_fraction": 0.6502925778, "num_tokens": 1982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5530513598739326}}
{"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": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_random.h>\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/optimization/optimization_compute_index_reordering.h>\n#include <OpenTissue/core/math/optimization/non_smooth_newton/optimization_compute_partitioned_jacobian.h>\n#include <OpenTissue/core/math/optimization/optimization_make_mbd_bounds.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_non_smooth_newton_compute_partitioned_jacobian);\n\nBOOST_AUTO_TEST_CASE(test_case)\n{\n  typedef ublas::vector<size_t>   idx_vector_type;\n  typedef ublas::vector<double>   vector_type;\n  typedef ublas::compressed_matrix<double>   matrix_type;\n  typedef OpenTissue::math::ValueTraits<double> value_traits;\n  typedef double real_type;\n  typedef size_t size_type;\n\n  matrix_type A;\n  vector_type mu,lo,hi;\n  A.resize(10,10,false);\n  mu.resize(10,false);\n  lo.resize(10,false);\n  hi.resize(10,false);\n\n  OpenTissue::math::Random<double> value(0.0,1.0);\n  for(size_t i=0;i<A.size1();++i)\n  {\n    mu(i) = value();\n    lo(i) = value_traits::zero();\n    hi(i) = value_traits::infinity();\n    for(size_t j=0;j<A.size2();++j)\n      A(i,j) = value();\n  }\n\n  idx_vector_type bitmask;\n\n  bitmask.resize(10,false);\n\n  static size_t const in_lower  = 1;\n  static size_t const in_upper  = 2;\n  static size_t const in_active = 4;\n\n  bitmask(0) = in_upper;   // pi = inf\n  bitmask(1) = in_lower;   // pi = 0\n  bitmask(2) = in_active;  // pi = 0\n  bitmask(3) = in_lower;   // pi = inf\n  bitmask(4) = in_active;  // pi = 3\n  bitmask(5) = in_upper;   // pi = 3\n  bitmask(6) = in_active;  // pi = inf\n  bitmask(7) = in_upper;   // pi = 6\n  bitmask(8) = in_lower;   // pi = 6\n  bitmask(9) = in_active;  // pi = inf\n\n  idx_vector_type old2new;\n  idx_vector_type new2old;\n\n  OpenTissue::math::optimization::compute_index_reordering( bitmask, old2new, new2old );\n\n  idx_vector_type pi;\n  pi.resize(10,false);\n  size_type nodep = OpenTissue::math::detail::highest<size_t>();\n  pi(0) = nodep;\n  pi(1) = 0;\n  pi(2) = 0;\n  pi(3) = nodep;\n  pi(4) = 3;\n  pi(5) = 3;\n  pi(6) = nodep;\n  pi(7) = 6;\n  pi(8) = 6;\n  pi(9) = nodep;\n\n  matrix_type A_aa;\n  matrix_type A_ab;\n  matrix_type C;\n  matrix_type D;\n\n  OpenTissue::math::optimization::detail::compute_partitioned_jacobian( \n    A\n    , OpenTissue::math::optimization::make_lower_mbd_bounds( pi, mu, lo )\n    , OpenTissue::math::optimization::make_upper_mbd_bounds( pi, mu, hi )\n    ,  bitmask\n    , old2new\n    ,  4\n    ,  6\n    ,  A_aa\n    ,  A_ab\n    ,  C\n    ,  D\n    );\n\n  double tol = 0.01;\n\n  // old : new   set      old : new\n  //  2 <-> 0    active\n  //  4 <-> 1    active\n  //  6 <-> 2    active\n  //  9 <-> 3    active\n  //  1 <-> 4    lower      0 -> 7         (4,4) (4,7)     ->   D(0,0) D(0,3)\n  //  3 <-> 5    lower      -              (5,5)           ->   D(1,1)\n  //  8 <-> 6    lower      6 -> 2         (6,6) (6,2)     ->   D(2,2) C(2,2)\n  //  0 <-> 7    upper      -              (7,7)           ->   D(3,3)\n  //  5 <-> 8    upper      3 -> 5         (8,8) (8,5)     ->   D(4,4) D(4,1)\n  //  7 <-> 9    upper      6 -> 2         (9,9) (9,2)     ->   D(5,5) C(5,2)\n\n  BOOST_CHECK( A_aa.size1()==4 );\n  BOOST_CHECK( A_aa.size2()==4 );\n  for(size_type i = 0;i<4;++i)\n  {\n    for(size_type j = 0;j<4;++j)\n    {\n      BOOST_CHECK_CLOSE( double( A_aa(i,j) ), double( A(new2old(i),new2old(j)) ), tol );\n    }\n  }\n\n  BOOST_CHECK( A_ab.size1()==4 );\n  BOOST_CHECK( A_ab.size2()==6 );\n  for(size_type i = 0;i<4;++i)\n  {\n    for(size_type j = 0;j<6;++j)\n    {\n      BOOST_CHECK_CLOSE( double( A_ab(i,j) ), double( A(new2old(i),new2old(j+4)) ), tol );\n    }\n  }\n\n  BOOST_CHECK( C.size1()==6 );\n  BOOST_CHECK( C.size2()==4 );\n  BOOST_CHECK_CLOSE( double( C(0,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(0,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(0,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(0,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(1,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(1,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(1,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(1,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(2,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(2,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(2,2) ), double( mu(8) ), tol );\n  BOOST_CHECK_CLOSE( double( C(2,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(4,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(4,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(4,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(4,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(5,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(5,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( C(5,2) ), double( -mu(7) ), tol );\n  BOOST_CHECK_CLOSE( double( C(5,3) ), double( 0.0 ), tol );\n\n  BOOST_CHECK( D.size1()==6 );\n  BOOST_CHECK( D.size2()==6 );\n\n  BOOST_CHECK_CLOSE( double( D(0,0) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(0,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(0,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(0,3) ), double( mu(1) ), tol );\n  BOOST_CHECK_CLOSE( double( D(0,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(0,5) ), double( 0.0 ), tol );\n\n  BOOST_CHECK_CLOSE( double( D(1,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(1,1) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(1,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(1,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(1,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(1,5) ), double( 0.0 ), tol );\n\n  BOOST_CHECK_CLOSE( double( D(2,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(2,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(2,2) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(2,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(2,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(2,5) ), double( 0.0 ), tol );\n\n  BOOST_CHECK_CLOSE( double( D(3,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(3,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(3,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(3,3) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(3,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(3,5) ), double( 0.0 ), tol );\n\n  BOOST_CHECK_CLOSE( double( D(4,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(4,1) ), double( -mu(5) ), tol );\n  BOOST_CHECK_CLOSE( double( D(4,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(4,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(4,4) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(4,5) ), double( 0.0 ), tol );\n\n  BOOST_CHECK_CLOSE( double( D(5,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(5,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(5,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(5,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(5,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( D(5,5) ), double( 1.0 ), tol );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "70234287a899d5cdf4c47bc9d7981f6e032cb66c", "size": 7692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/compute_partitioned_jacobian/src/unit_compute_partitioned_jacobian.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/compute_partitioned_jacobian/src/unit_compute_partitioned_jacobian.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/compute_partitioned_jacobian/src/unit_compute_partitioned_jacobian.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 36.4549763033, "max_line_length": 106, "alphanum_fraction": 0.6101144046, "num_tokens": 2720, "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": "#define BOOST_TEST_MODULE example\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n#include <sstream>\n#include <vector>\n#include <cstddef>\n#include <iostream>\n#include <map>\n#include <string>\n#include <utility>\n\nstd::vector<float> fibonacci() {\n    std::vector<float> ret(8);\n    ret[0] = 0;\n    ret[1] = 1;\n\n    for (std::size_t s{2}; s < ret.size(); ++s)\n        ret[s] = ret[s - 1] + ret[s - 2];\n\n    return ret;\n}\n\nBOOST_DATA_TEST_CASE(\n    test1,\n    boost::unit_test::data::make(fibonacci()),\n    array_element)\n{\n    std::cout << \"test 1: \" << array_element << std::endl;\n    BOOST_TEST(array_element <= 13);\n}\n\nstd::map<std::string, float> vect_2_str(std::vector<float> v) {\n    std::map<std::string, float> out{};\n    for (std::size_t s{0}; s < v.size(); ++s) {\n        std::ostringstream o{};\n        o << v[s];\n        out[o.str()] = v[s];\n    }\n    return out;\n}\n\ntypedef std::pair<const std::string, float> pair_map_t;\nBOOST_TEST_DONT_PRINT_LOG_VALUE(pair_map_t)\n\nBOOST_DATA_TEST_CASE(\n    test2,\n    boost::unit_test::data::make(vect_2_str(fibonacci())),\n    array_element)\n{\n    std::cout << \"test 2: \\\"\" \n              << array_element.first << \"\\\", \" << array_element.second \n              << std::endl;\n    BOOST_TEST(array_element.second <= 13);\n}\n\n\n", "meta": {"hexsha": "99b76ee1b62e63115e748bcb82374feb970282b7", "size": 1349, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "books/tech/cpp/boost/official_doc/11-correctness_and_testing/04-test/11-datasets_from_containers/main.cpp", "max_stars_repo_name": "ordinary-developer/education", "max_stars_repo_head_hexsha": "1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "books/tech/cpp/boost/official_doc/11-correctness_and_testing/04-test/11-datasets_from_containers/main.cpp", "max_issues_repo_name": "ordinary-developer/education", "max_issues_repo_head_hexsha": "1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "books/tech/cpp/boost/official_doc/11-correctness_and_testing/04-test/11-datasets_from_containers/main.cpp", "max_forks_repo_name": "ordinary-developer/education", "max_forks_repo_head_hexsha": "1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58", "max_forks_repo_licenses": ["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.2586206897, "max_line_length": 71, "alphanum_fraction": 0.6115641216, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.5530298832445621}}
{"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": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/concept/value.hpp>\n#include <eve/constant/valmin.hpp>\n#include <eve/constant/valmax.hpp>\n#include <eve/function/all.hpp>\n#include <eve/function/erfc_inv.hpp>\n#include <eve/function/diff/erfc_inv.hpp>\n#include <eve/function/is_negative.hpp>\n#include <eve/function/is_positive.hpp>\n#include <type_traits>\n#include <cmath>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/constant/smallestposval.hpp>\n#include <eve/platform.hpp>\n#include <boost/math/special_functions/erf.hpp>\n\n//==================================================================================================\n// Types tests\n//==================================================================================================\n// EVE_TEST_TYPES( \"Check return types of erfc_inv\"\n//             , eve::test::simd::ieee_reals\n//             )\n// <typename T>(eve::as<T>)\n// {\n//   using v_t = eve::element_type_t<T>;\n\n//   TTS_EXPR_IS( eve::erfc_inv(T())  , T);\n//   TTS_EXPR_IS( eve::erfc_inv(v_t()), v_t);\n// };\n\n//==================================================================================================\n// erfc_inv  tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of erfc_inv on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.1, 2.0))\n        )\n<typename T>(T const&  a0)\n{\n  using v_t = eve::element_type_t<T>;\n  using eve::erfc_inv;\n  using eve::as;\n  TTS_ULP_EQUAL( erfc_inv(a0),  map([](auto e){return boost::math::erfc_inv(e);}, a0), 2);\n  auto derfc_inv = [](auto e){return v_t(-0.886226925452758013649)*std::exp(eve::sqr(erfc_inv(e)));};\n  TTS_ULP_EQUAL( eve::diff(erfc_inv)(a0),  map(derfc_inv, a0), 2);\n\n\n  TTS_ULP_EQUAL(erfc_inv(T(0.5)), T(boost::math::erfc_inv(v_t(0.5))), 1. );\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_IEEE_EQUAL(erfc_inv(eve::nan(eve::as<T>()))  , eve::nan(eve::as<T>()) );\n    TTS_IEEE_EQUAL(erfc_inv(eve::inf(eve::as<T>()))  , eve::nan(eve::as<T>()) );\n    TTS_IEEE_EQUAL(erfc_inv(eve::minf(eve::as<T>())) , eve::nan(eve::as<T>()) );\n  }\n\n  TTS_ULP_EQUAL(erfc_inv(T(35)), eve::nan(eve::as<T>()), 0.5);\n  TTS_ULP_EQUAL(erfc_inv(T(-35)), eve::nan(eve::as<T>()), 0.5);\n\n  TTS_IEEE_EQUAL(erfc_inv(T( 0 )), eve::inf(eve::as<T>()));\n  TTS_IEEE_EQUAL(erfc_inv(T(-0.)), eve::inf(eve::as<T>()));\n  TTS_ULP_EQUAL(erfc_inv(T( 0.1 )), T( boost::math::erfc_inv(0.1)), 0.5 );\n  TTS_ULP_EQUAL(erfc_inv(T( 0.2 )), T( boost::math::erfc_inv(0.2)), 1 );\n  TTS_ULP_EQUAL(erfc_inv(T( 0.3 )), T( boost::math::erfc_inv(0.3)),  1 );\n  TTS_ULP_EQUAL(erfc_inv(T( 0.5 )), T( boost::math::erfc_inv(0.5)),  1 );\n  TTS_ULP_EQUAL(erfc_inv(T( 0.15)), T( boost::math::erfc_inv(0.15)), 0.5 );\n  TTS_ULP_EQUAL(erfc_inv(T( 0.75)), T( boost::math::erfc_inv(0.75)), 0.5 );\n  TTS_ULP_EQUAL(erfc_inv(T( 1.0 )), T( boost::math::erfc_inv(1.0 )), 0.5 );\n  TTS_ULP_EQUAL(erfc_inv(T( 1.1 )), T( boost::math::erfc_inv(1.1)), 1.5 );\n  TTS_ULP_EQUAL(erfc_inv(T( 1.2 )), T( boost::math::erfc_inv(1.2)), 1.5 );\n  TTS_ULP_EQUAL(erfc_inv(T( 1.3 )), T( boost::math::erfc_inv(1.3)), 0.5 );\n  TTS_ULP_EQUAL(erfc_inv(T( 1.5 )), T( boost::math::erfc_inv(1.5)),  1 );\n  TTS_ULP_EQUAL(erfc_inv(T( 1.15)), T( boost::math::erfc_inv(1.15)), 1.5 );\n  TTS_ULP_EQUAL(erfc_inv(T( 1.75)), T( boost::math::erfc_inv(1.75)), 0.5 );\n  TTS_ULP_EQUAL(erfc_inv(T( 1.45984)), T( boost::math::erfc_inv(1.45984)), 1.5 );\n\n};\n", "meta": {"hexsha": "f3f9acb3f798375b9446d58beae1211b03abd29b", "size": 3827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/special/erfc_inv.cpp", "max_stars_repo_name": "leha-bot/eve", "max_stars_repo_head_hexsha": "30e7a7f6bcc5cf524a6c2cc624234148eee847be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 340.0, "max_stars_repo_stars_event_min_datetime": "2020-09-16T21:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:40:33.000Z", "max_issues_repo_path": "test/unit/module/real/special/erfc_inv.cpp", "max_issues_repo_name": "leha-bot/eve", "max_issues_repo_head_hexsha": "30e7a7f6bcc5cf524a6c2cc624234148eee847be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383.0, "max_issues_repo_issues_event_min_datetime": "2020-09-17T06:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T15:58:53.000Z", "max_forks_repo_path": "test/unit/module/real/special/erfc_inv.cpp", "max_forks_repo_name": "leha-bot/eve", "max_forks_repo_head_hexsha": "30e7a7f6bcc5cf524a6c2cc624234148eee847be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-02-27T23:11:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T12:31:29.000Z", "avg_line_length": 43.9885057471, "max_line_length": 101, "alphanum_fraction": 0.539587144, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888478, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5530256875947126}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <math/prim/mat/prob/vector_rng_test_helper.hpp>\n#include <math/prim/mat/prob/VectorIntRNGTestRig.hpp>\n#include <limits>\n#include <vector>\n\nclass PoissonLogTestRig : public VectorIntRNGTestRig {\n public:\n  PoissonLogTestRig()\n      : VectorIntRNGTestRig(10000, 10, {0, 1, 2, 3, 4, 5, 6},\n                            {-0.5, 0.0, 0.1, 1.7}, {-2, 0, 1, 2}, {}, {}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& alpha, const T2&, const T3&,\n                        T_rng& rng) const {\n    return stan::math::poisson_log_rng(alpha, rng);\n  }\n\n  template <typename T1>\n  double pmf(int y, T1 alpha, double, double) const {\n    return std::exp(stan::math::poisson_log_lpmf(y, alpha));\n  }\n};\n\nTEST(ProbDistributionsPoissonLog, errorCheck) {\n  check_dist_throws_all_types(PoissonLogTestRig());\n}\n\nTEST(ProbDistributionsPoissonLog, distributionCheck) {\n  check_counts_real(PoissonLogTestRig());\n}\n", "meta": {"hexsha": "3cc15664484fc4c978ea6f3cf6323b977450b109", "size": 1099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/mat/prob/poisson_log_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/prim/mat/prob/poisson_log_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/prim/mat/prob/poisson_log_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4, "max_line_length": 76, "alphanum_fraction": 0.6869881711, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5530256657538937}}
{"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": "/*    Copyright (c) 2010-2018, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      Burden, R.L., Faires, J.D. Numerical Analysis, 7th Edition, Books/Cole, 2001.\n *      The Mathworks, Inc. RKF87, Symbolic Math Toolbox, 2012.\n *\n *    Notes\n *      All the test for this integrator are based on the data generated using the Symbolic Math\n *      Toolbox (MathWorks, 2012). Ideally, another source of data should be used to complete the\n *      testing.\n *\n *      The single step and full integration error tolerances were picked to be as small as\n *      possible, without causing the tests to fail. These values are not deemed to indicate any\n *      bugs in the code; however, it is important to take these discrepancies into account when\n *      using this numerical integrator.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/make_shared.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaVariableStepSizeIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaCoefficients.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/numericalIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/reinitializableNumericalIntegrator.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/UnitTests/numericalIntegratorTests.h\"\n#include \"Tudat/Mathematics/NumericalIntegrators/UnitTests/numericalIntegratorTestFunctions.h\"\n\n#include \"Tudat/InputOutput/matrixTextFileReader.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n#include \"Tudat/Mathematics/BasicMathematics/linearAlgebra.h\"\n\n#include <limits>\n#include <string>\n\n#include <Eigen/Core>\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_runge_kutta_fehlberg_78_integrator )\n\nusing linear_algebra::flipMatrixRows;\n\nusing numerical_integrators::NumericalIntegratorXdPointer;\nusing numerical_integrators::ReinitializableNumericalIntegratorXdPointer;\nusing numerical_integrators::RungeKuttaVariableStepSizeIntegratorXd;\nusing numerical_integrators::RungeKuttaCoefficients;\n\nusing numerical_integrator_test_functions::computeNonAutonomousModelStateDerivative;\nusing numerical_integrator_test_functions::computeFehlbergLogirithmicTestODEStateDerivative ;\nusing numerical_integrator_test_functions::computeAnalyticalStateFehlbergODE;\n\n//! Test Runge-Kutta-Fehlberg 78 integrator using benchmark ODE of Fehlberg (1968)\nBOOST_AUTO_TEST_CASE( test_RungeKuttaFehlberg78_Integrator_Fehlberg_Benchmark )\n{\n    using namespace numerical_integrators;\n    RungeKuttaCoefficients coeff78 =\n            RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 );\n\n    // Integrator settings\n    double minimumStepSize   = std::numeric_limits<double>::epsilon( );\n    double maximumStepSize   = std::numeric_limits<double>::infinity( );\n    double initialStepSize   = 1E-6; // Error: 0.0521 for initialStepSize = 1 ?\n    double relativeTolerance = 1E-16;\n    double absoluteTolerance = 1E-16;\n\n    // Initial conditions\n    double initialTime = 0.0;\n    double finalTime   = 5.0;\n    Eigen::Vector2d initialState( exp( 1.0 ), 1.0);\n\n    // Setup integrator\n    numerical_integrators::RungeKuttaVariableStepSizeIntegratorXd integrator78(\n                coeff78, computeFehlbergLogirithmicTestODEStateDerivative,\n                initialTime, initialState, minimumStepSize,\n                maximumStepSize, relativeTolerance, absoluteTolerance );\n\n\n    // Obtain numerical solution\n    Eigen::Vector2d numericalSolution = integrator78.integrateTo( finalTime, initialStepSize );\n\n    // Analytical solution\n    Eigen::Vector2d analyticalSolution = computeAnalyticalStateFehlbergODE( finalTime, initialState );\n\n    Eigen::Vector2d computedError = numericalSolution - analyticalSolution;\n    BOOST_CHECK_SMALL( std::fabs(computedError( 0 )), 1E-13 );\n    BOOST_CHECK_SMALL( std::fabs(computedError( 1 )), 1E-13 );\n}\n\n//! Test Runge-Kutta-Fehlberg 78 integrator using benchmark data from (The MathWorks, 2012).\nBOOST_AUTO_TEST_CASE( testRungeKuttaFehlberg78IntegratorUsingMatlabData )\n{\n    using namespace numerical_integrator_tests;\n\n    // Read in benchmark data (generated using Symbolic Math Toolbox in Matlab\n    // (The MathWorks, 2012)). This data is generated using the RKF87 numerical integrator.\n    const std::string pathToForwardIntegrationOutputFile = input_output::getTudatRootPath( )\n            + \"/Mathematics/NumericalIntegrators/UnitTests\"\n            + \"/matlabOutputRungeKuttaFehlberg78Forward.txt\";\n    const std::string pathToDiscreteEventIntegrationOutputFile = input_output::getTudatRootPath( )\n            + \"/Mathematics/NumericalIntegrators/UnitTests\"\n            + \"/matlabOutputRungeKuttaFehlberg78DiscreteEvent.txt\";\n\n    // Store benchmark data in matrix.\n    const Eigen::MatrixXd matlabForwardIntegrationData =\n            input_output::readMatrixFromFile( pathToForwardIntegrationOutputFile, \",\" );\n    Eigen::MatrixXd matlabBackwardIntegrationData = matlabForwardIntegrationData;\n    flipMatrixRows( matlabBackwardIntegrationData );\n    const Eigen::MatrixXd matlabDiscreteEventIntegrationData =\n            input_output::readMatrixFromFile( pathToDiscreteEventIntegrationOutputFile, \",\" );\n\n    // Set integrator parameters.\n\n    // All of the following parameters are set such that the input data is fully accepted by the\n    // integrator, to determine the steps to be taken.\n    const double zeroMinimumStepSize = std::numeric_limits< double >::epsilon( );\n    const double infiniteMaximumStepSize = std::numeric_limits< double >::infinity( );\n    const double infiniteRelativeErrorTolerance = std::numeric_limits< double >::infinity( );\n    const double infiniteAbsoluteErrorTolerance = std::numeric_limits< double >::infinity( );\n\n    // The following parameters set how the error control mechanism should work.\n    const double relativeErrorTolerance = 1.0e-15;\n    const double absoluteErrorTolerance = 1.0e-15;\n\n    // Case 1: Execute integrateTo() to integrate one step forward in time.\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        executeOneIntegrateToStep( matlabForwardIntegrationData, 1.0e-15, integrator );\n    }\n\n    // Case 2: Execute performIntegrationStep() to perform multiple integration steps until final\n    //         time.\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        performIntegrationStepToSpecifiedTime( matlabForwardIntegrationData,\n                                               1.0e-15, 1.0e-15, integrator );\n    }\n\n    // Case 3: Execute performIntegrationStep() to perform multiple integration steps until initial\n    //         time (backwards).\n    {\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabBackwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabBackwardIntegrationData( FIRST_ROW,\n                                                        STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        performIntegrationStepToSpecifiedTime( matlabBackwardIntegrationData,\n                                               1.0e-15, 1.0e-14, integrator );\n    }\n\n    // Case 4: Execute integrateTo() to integrate to specified time in one step.\n    {\n        // Note that this test has a strange issue that the if the absolute error tolerance is set\n        // to 1.0e-15, the last step that the integrateTo() function takes does not result in the\n        // expected final time of 1.0. As a temporary solution, the absolute error tolerance has\n        // been multiplied by 10.0, which seems to solve the problem. This error indicated a\n        // possible problem with the implementation of the integrateTo() function, which needs to\n        // be investigated in future.\n\n        // Declare integrator with all necessary settings.\n        NumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    relativeErrorTolerance,\n                    absoluteErrorTolerance * 10.0 );\n\n        executeIntegrateToToSpecifiedTime( matlabForwardIntegrationData, 1.0e-13, integrator,\n                                           matlabForwardIntegrationData(\n                                               matlabForwardIntegrationData.rows( ) - 1,\n                                               TIME_COLUMN_INDEX ) );\n    }\n\n    // Case 5: Execute performIntegrationstep() to integrate to specified time in multiple steps,\n    //         including discrete events.\n    {\n        // Declare integrator with all necessary settings.\n        ReinitializableNumericalIntegratorXdPointer integrator\n                = std::make_shared< RungeKuttaVariableStepSizeIntegratorXd >(\n                    RungeKuttaCoefficients::get( RungeKuttaCoefficients::rungeKuttaFehlberg78 ),\n                    &computeNonAutonomousModelStateDerivative,\n                    matlabForwardIntegrationData( FIRST_ROW, TIME_COLUMN_INDEX ),\n                    ( Eigen::VectorXd( 1 )\n                      << matlabForwardIntegrationData( FIRST_ROW,\n                                                       STATE_COLUMN_INDEX ) ).finished( ),\n                    zeroMinimumStepSize,\n                    infiniteMaximumStepSize,\n                    infiniteRelativeErrorTolerance,\n                    infiniteAbsoluteErrorTolerance );\n\n        performIntegrationStepToSpecifiedTimeWithEvents( matlabDiscreteEventIntegrationData,\n                                                         1.0e-15, 1.0e-13, integrator );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "404399f49a0e2bfe1497467d3126ff2cab3a0370", "size": 12504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKuttaFehlberg78Integrator.cpp", "max_stars_repo_name": "J-Westin/tudat", "max_stars_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKuttaFehlberg78Integrator.cpp", "max_issues_repo_name": "J-Westin/tudat", "max_issues_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKuttaFehlberg78Integrator.cpp", "max_forks_repo_name": "J-Westin/tudat", "max_forks_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4229249012, "max_line_length": 102, "alphanum_fraction": 0.6785028791, "num_tokens": 2715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5529712166948859}}
{"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": "//\n// Copyright (c) 2012 Juan Palacios juan.palacios.puyana@gmail.com\n// This file is part of minimathlibs.\n// Subject to the BSD 2-Clause License \n// - see < http://opensource.org/licenses/BSD-2-Clause>\n//\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE TestAlignment\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n#include <iomanip>\n#include <cstdlib>\n#include \"minimath/rotation3d.hpp\"\n#include \"minimath/transform3d.hpp\"\n#include \"minimath/point3d.hpp\"\n#include \"minimath/geom3d_ops.hpp\"\n\n#include \"Defines.h\"\n#include <tr1/array>\n\nusing namespace minimath;\n\nnamespace\n{\n// check that results of calculated transformation and\n// reference transformation are the same to within 64 epsilons.\ntemplate <typename T>\nvoid checkTransformation(const T& transf)\n{\n  pointxyzd pA = transf*p100;\n  pointxyzd pB = transf*p010;\n  pointxyzd pC = transf*p001;\n  bool success = true;\n\n  typedef std::tr1::array<pointxyzd, 2> PointXYZDPair;\n\n  PointXYZDPair p0 = { {p100, pA} };\n  PointXYZDPair p1 = { {p010, pB} };\n  PointXYZDPair p2 = { {p001, pC} };\n  std::tr1::array<PointXYZDPair, 3> pointPairs = { {p0, p1, p2} };\n\n  transform3d<double> transf1 = transformation<double>(pointPairs.begin(),\n                                                       pointPairs.end(),\n                                                       success);\n\n  BOOST_CHECK(success);\n  BOOST_CHECK(minimath::equal(transf1*p100, pA, 128u));\n  BOOST_CHECK(minimath::equal(transf1*p010, pB, 128u));\n  BOOST_CHECK(minimath::equal(transf1*p001, pC, 64u));\n\n}\n\ntemplate <typename R>\nvoid checkRotationAndTranslation()\n{\n  for (int i = 1; i < 9;  ++i) {\n    double x = std::rand()%100;\n    double y = std::rand()%100;\n    double z = std::rand()%100;\n    translation3d<double> transl(pointxyzd(x,y,z));\n    rotation3d<double> rot(R(PI/i));\n    transform3d<double> transf(rot, transl);\n    checkTransformation(transf);\n  }\n}\n\ntemplate <typename R>\nvoid checkTranslationAndRotation()\n{\n  for (int i = 1; i < 9;  ++i) {\n    double x = std::rand()%100;\n    double y = std::rand()%100;\n    double z = std::rand()%100;\n    translation3d<double> transl(pointxyzd(x,y,z));\n    rotation3d<double> rot(R(PI/i));\n    transform3d<double> transf(transl, rot);\n    checkTransformation(transf);\n  }\n}\n\n\n} // anonymous namespace\n\nBOOST_AUTO_TEST_SUITE(test_awesome_grower)\n\nBOOST_AUTO_TEST_CASE(testTranslation)\n{\n  // rotate reference points\n  translation3d<double> transl(pointxyzd(100, 100, 100));\n  checkTransformation(transl);\n}\n\nBOOST_AUTO_TEST_CASE(testRotation)\n{\n  // rotate reference points\n  rotation3dzyx<double>  rot(PI/4, 0, PI/4);\n  checkTransformation(rot);\n}\n\nBOOST_AUTO_TEST_CASE(testRotation3DXAndTranslation)\n{\n  checkRotationAndTranslation<rotation3dx<double> >();\n}\n\nBOOST_AUTO_TEST_CASE(testRotation3DYAndTranslation)\n{\n  checkRotationAndTranslation<rotation3dy<double> >();\n}\n\nBOOST_AUTO_TEST_CASE(testRotation3DZAndTranslation)\n{\n  checkRotationAndTranslation<rotation3dz<double> >();\n}\n\nBOOST_AUTO_TEST_CASE(testTranslationAndRotation3DX)\n{\n  checkTranslationAndRotation<rotation3dx<double> >();\n}\n\nBOOST_AUTO_TEST_CASE(testTranslationAndRotation3DY)\n{\n  checkTranslationAndRotation<rotation3dy<double> >();\n}\n\nBOOST_AUTO_TEST_CASE(testTranslationAndRotation3DZ)\n{\n  checkTranslationAndRotation<rotation3dz<double> >();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d585bc475b4f242e5d89af357fbd2ea3e959e865", "size": 3333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestAlignment.cpp", "max_stars_repo_name": "XPsoud/minimathlibs", "max_stars_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-20T13:54:46.000Z", "max_issues_repo_path": "tests/TestAlignment.cpp", "max_issues_repo_name": "XPsoud/minimathlibs", "max_issues_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/TestAlignment.cpp", "max_forks_repo_name": "XPsoud/minimathlibs", "max_forks_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T15:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:04:57.000Z", "avg_line_length": 25.0601503759, "max_line_length": 74, "alphanum_fraction": 0.7089708971, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5529711946129798}}
{"text": "/***************************************************************************\n *   Copyright (C) 2007 by Reed A. Cartwright                              *\n *   reed@scit.us                                                          *\n *                                                                         *\n *   Permission is hereby granted, free of charge, to any person obtaining *\n *   a copy of this software and associated documentation files (the       *\n *   \"Software\"), to deal in the Software without restriction, including   *\n *   without limitation the rights to use, copy, modify, merge, publish,   *\n *   distribute, sublicense, and/or sell copies of the Software, and to    *\n *   permit persons to whom the Software is furnished to do so, subject to *\n *   the following conditions:                                             *\n *                                                                         *\n *   The above copyright notice and this permission notice shall be        *\n *   included in all copies or substantial portions of the Software.       *\n *                                                                         *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 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\n#ifdef HAVE_CONFIG_H\n#\tinclude \"config.h\"\n#endif\n\n#include <boost/math/special_functions/zeta.hpp>\n\n#include \"covar.h\"\n#include \"covar_k2p.h\"\n#include \"ccvector.h\"\n#include \"series.h\"\n#include \"invert_matrix.h\"\n#include \"table.h\"\n\nusing namespace std;\nnamespace ublas = boost::numeric::ublas;\n\ninline double pow(double p, size_t x){return std::pow(p, (int)x);}\ninline double log(size_t x) {return log((double)x);}\ninline double zeta(double z) { return boost::math::zeta<double>(z); }\ninline double sq(double s) { return s*s; }\ninline double csch(double x) { return 1.0/sinh(x); }\n\nextern const int g_pupy[5];\nextern const int g_atgc[5];\n\n// zeta_ratio(z) = zeta'(z)/zeta(z)\nconst double zeta_ratio_point = 1.6804173592040375;\nconst double zeta_ratio_data[] = {\n\t-1.0,                2.0267597934151023, -3.1437505990361300, 4.6584860638091640,\n\t-6.8551150550990680, 10.076942606572075, -14.810472757463808, 21.766886187422337,\n\t-31.990529063023680, 47.016048846364384, -69.098840622593630, 101.55361290858988,\n\t-149.25194318992214, 219.35352061052055, -322.38084118972284, 473.79867199375957,\n\t-696.33536767600560, 1023.3944773113722, -1504.0687358544299, 2210.5090581667810,\n\t-3248.7546478130210, 4774.6498584537580, -7017.2369853102955, 10313.136327854983,\n\t-15157.074093346790, 22276.142559146083, -32738.939208142758, 48115.967009485650,\n\t-70715.372496922540, 103929.40676828961, -152743.61443374804, 224485.18158388760\n};\ntaylor_series<double> zeta_ratio(zeta_ratio_point, zeta_ratio_data);\n\n// zeta_ratio2(x) = zeta''(z)/zeta(z)\nconst double zeta_ratio2_data[] = {\n\t3.0267597934151023,   -10.341020784902463,   24.370714649703780,   -49.480686977316730,\n\t92.861375476624520,   -166.09430161114878,   287.63926958655040,   -486.72025090333090,\n\t809.35805827060480,   -1327.7000268719173,   2154.4096216995576,   -3464.8099653836620,\n\t5530.8904169767300,   -8773.4349769199200,   13841.793616644849,   -21735.763734672070,\n\t33991.540864093986,   -52965.035843404560,   82263.000139490190,   -127398.30500095984,\n\t196784.82990677876,   -303246.42196821440,   466303.35285683510,   -715633.74879524200,\n\t1.0963093267557952e6, -1.6767085619459874e6, 2.5604673613858290e6, -3.9045142800481310e6,\n\t5.9462695510516780e6, -9.0446375027637000e6, 1.3741749244271364e7, -2.0855904711249072e7\n};\ntaylor_series<double> zeta_ratio2(zeta_ratio_point, zeta_ratio2_data);\n\n/***************************************************************************\n * class covar_k2p_zeta                                                    *\n ***************************************************************************/\n\nvoid covar_k2p_zeta::preallocate(size_t maxa, size_t maxd)\n{\n\tsz_height = maxa+1;\n\tsz_width = maxd+1;\n\t\t\n\tsize_t sz_max = std::max(sz_height, sz_width);\n\t\n\tcache_log.resize(sz_max, 0.0);\n\tfor(size_t u=1;u<sz_max;++u)\n\t\tcache_log[u] = log(u);\n}\n\nvoid covar_k2p_zeta::expectation_setup(const params_type &params)\n{\n\n}\n\ndouble covar_k2p_zeta::expectation(ex_type &ex, const sequence &seq_a, const sequence &seq_d, size_t index) const\n{\n\tsize_t sz_anc = seq_a.size();\n\tsize_t sz_dec = seq_d.size();\n\t\n\tconst model_type &model = get_model();\n\t\t\n\ttypedef ublas::cc_vector<double, 6> ex_s;\n\ttypedef ublas::cc_vector<double, 5> ex_t;\n\t\n\ttable<ex_s> table_s(sz_anc+1,sz_dec+1,ublas::zero_vector<double>(6));\n\ttable<ex_t> table_t(sz_anc+1,sz_dec+1,ublas::zero_vector<double>(5));\n\t\n\ttable_s(0,0)[e1W] = prob_scale;\n\tdouble dp;\n\n\t// First Cycle e1 and e2\n\t\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_t &WT = table_t(0,d);\n\t\tfor(size_t k = d; k > 0; --k)\n\t\t{\n\t\t\tdp = model.p_indel_size[k];\n\t\t\tex_s &WSK = table_s(0,d-k);\n\t\t\tnoalias(WT) += table_t(0,d-k)*dp;\n\t\t\tnoalias(WS) += WSK*dp;\n\t\t\tWS[e1G] += WSK[e1W]*dp;\n\t\t\tWS[e1L] += WSK[e1W]*dp*cache_log[k];\n\t\t\tWT[e2GG] += 2.0*WSK[e1G]*dp + WSK[e1W]*dp;\n\t\t\tWT[e2LL] += 2.0*WSK[e1L]*dp*cache_log[k] + WSK[e1W]*dp*cache_log[k]*cache_log[k];\n\t\t}\n\t}\n\t\t\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_t &WT = table_t(a,0);\n\t\tfor(size_t k = a; k > 0; --k)\n\t\t{\n\t\t\tdp = model.p_indel_size[k];\n\t\t\tex_s &WSK = table_s(a-k,0);\n\t\t\tnoalias(WT) += table_t(a-k,0)*dp;\n\t\t\tnoalias(WS) += WSK*dp;\n\t\t\tWS[e1G] += WSK[e1W]*dp;\n\t\t\tWS[e1L] += WSK[e1W]*dp*cache_log[k];\n\t\t\tWT[e2GG] += 2.0*WSK[e1G]*dp + WSK[e1W]*dp;\n\t\t\tWT[e2LL] += 2.0*WSK[e1L]*dp*cache_log[k] + WSK[e1W]*dp*cache_log[k]*cache_log[k];\n\t\t\t\n\t\t}\n\t}\n\n\tint nuc_a, nuc_d;\n\t\t\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\tfor(size_t d=1;d<= sz_dec;++d)\n\t\t{\n\t\t\tnuc_a = seq_a[a-1];\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tex_t &WT = table_t(a,d);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tnoalias(WT) = table_t(a-1,d-1)*dp;\n\t\t\t\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[e1M] += WS[e1W]*model.p_match;\n\t\t\t\tWS[e1S] += WS[e1W]*model.p_ts;\n\t\t\t\tWS[e1V] += WS[e1W]*model.p_tv;\n\t\t\t\t\n\t\t\t\tWT[e2MM] += 2.0*WSP[e1M]*dp*model.p_match + WS[e1W]*model.p_match*model.p_match;\n\t\t\t\tWT[e2SS] += 2.0*WSP[e1S]*dp*model.p_ts + WS[e1W]*model.p_ts*model.p_ts;\n\t\t\t\tWT[e2VV] += 2.0*WSP[e1V]*dp*model.p_tv + WS[e1W]*model.p_tv*model.p_tv;\n\t\t\t}\n\t\t\telse if(nuc_a == nuc_d)\n\t\t\t{\n\t\t\t\tWS[e1M] += WS[e1W];\n\t\t\t\tWT[e2MM] += 2.0*WSP[e1M]*dp + WS[e1W];\n\t\t\t}\n\t\t\telse if(g_pupy[nuc_a] == g_pupy[nuc_d])\n\t\t\t{\n\t\t\t\tWS[e1S] += WS[e1W];\n\t\t\t\tWT[e2SS] += 2.0*WSP[e1S]*dp + WS[e1W];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tWS[e1V] += WS[e1W];\n\t\t\t\tWT[e2VV] += 2.0*WSP[e1V]*dp + WS[e1W];\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\tfor(size_t k = d; k > 0; --k)\n\t\t\t{\n\t\t\t\tdp = model.p_indel_size[k];\n\t\t\t\tex_s &WSK = table_s(a,d-k);\n\t\t\t\tnoalias(WT) += table_t(a,d-k)*dp;\t\n\t\t\t\tnoalias(WS) += WSK*dp;\n\t\t\t\tWS[e1G] += WSK[e1W]*dp;\n\t\t\t\tWS[e1L] += WSK[e1W]*dp*cache_log[k];\n\t\t\t\tWT[e2GG] += 2.0*WSK[e1G]*dp + WSK[e1W]*dp;\n\t\t\t\tWT[e2LL] += 2.0*WSK[e1L]*dp*cache_log[k] + WSK[e1W]*dp*cache_log[k]*cache_log[k];\n\t\t\t}\t\t\t\n\t\t\tfor(size_t k = a; k > 0; --k)\n\t\t\t{\t\t\n\t\t\t\tdp = model.p_indel_size[k];\n\t\t\t\tex_s &WSK = table_s(a-k,d);\n\t\t\t\tnoalias(WT) += table_t(a-k,d)*dp;\n\t\t\t\tnoalias(WS) += WSK*dp;\n\t\t\t\tWS[e1G] += WSK[e1W]*dp;\n\t\t\t\tWS[e1L] += WSK[e1W]*dp*cache_log[k];\n\t\t\t\tWT[e2GG] += 2.0*WSK[e1G]*dp + WSK[e1W]*dp;\n\t\t\t\tWT[e2LL] += 2.0*WSK[e1L]*dp*cache_log[k] + WSK[e1W]*dp*cache_log[k]*cache_log[k];\n\t\t\t}\n\t\t}\n\t}\n\tex_s ex1 = table_s(sz_anc,sz_dec);\n\tex_t ex2 = table_t(sz_anc,sz_dec);\n\t\t\n\tdouble w = ex1[e1W];\n\tex1 /= w;\n\tex2 /= w;\n\t\n\tex[eM] = ex1[e1M];   ex[eS] = ex1[e1S];   ex[eV] = ex1[e1V];\n\tex[eG] = ex1[e1G];   ex[eL] = ex1[e1L];\n\tex[eMM] = ex2[e2MM]; ex[eSS] = ex2[e2SS]; ex[eVV] = ex2[e2VV];\n\tex[eGG] = ex2[e2GG]; ex[eLL] = ex2[e2LL];\n\t\n\toutput() << \".\" << std::flush;\n\t\n\t// Second Cycle: e3: e3MS, e3MV, e3MG, e3ML, e3SV\n\ttable_t(0,0).clear();\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_t &WT = table_t(0,d);\n\t\tWT.clear();\n\t\tfor(size_t k = d; k > 0; --k)\n\t\t{\n\t\t\tdp = model.p_indel_size[k];\n\t\t\tex_s &WSK = table_s(0,d-k);\n\t\t\tnoalias(WT) += table_t(0,d-k)*dp;\n\t\t\tWT[e3MG] += WSK[e1M]*dp;\n\t\t\tWT[e3ML] += WSK[e1M]*dp*cache_log[k];\n\t\t}\n\t}\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_t &WT = table_t(a,0);\n\t\tWT.clear();\n\t\tfor(size_t k = a; k > 0; --k)\n\t\t{\n\t\t\tdp = model.p_indel_size[k];\n\t\t\tex_s &WSK = table_s(a-k,0);\n\t\t\tnoalias(WT) += table_t(a-k,0)*dp;\n\t\t\tWT[e3MG] += WSK[e1M]*dp;\n\t\t\tWT[e3ML] += WSK[e1M]*dp*cache_log[k];\n\t\t}\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\tfor(size_t d=1;d<= sz_dec;++d)\n\t\t{\n\t\t\tnuc_a = seq_a[a-1];\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_t &WT = table_t(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WT) = table_t(a-1,d-1)*dp;\n\t\t\t\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWT[e3MS] += WSP[e1S]*dp*model.p_match\n\t\t\t\t\t+ WSP[e1M]*dp*model.p_ts\n\t\t\t\t\t+ WSP[e1W]*dp*model.p_ts*model.p_match;\n\t\t\t\tWT[e3MV] += WSP[e1V]*dp*model.p_match\n\t\t\t\t\t+ WSP[e1M]*dp*model.p_tv\n\t\t\t\t\t+ WSP[e1W]*dp*model.p_tv*model.p_match;\n\t\t\t\tWT[e3SV] += WSP[e1V]*dp*model.p_ts\n\t\t\t\t\t+ WSP[e1S]*dp*model.p_tv\n\t\t\t\t\t+ WSP[e1W]*dp*model.p_ts*model.p_tv;\n\t\t\t\t\n\t\t\t\tWT[e3MG] += WSP[e1G]*dp*model.p_match;\n\t\t\t\tWT[e3ML] += WSP[e1L]*dp*model.p_match;\n\t\t\t}\n\t\t\telse if(nuc_a == nuc_d)\n\t\t\t{\n\t\t\t\tWT[e3MS] += WSP[e1S]*dp;\n\t\t\t\tWT[e3MV] += WSP[e1V]*dp;\n\t\t\t\tWT[e3MG] += WSP[e1G]*dp;\n\t\t\t\tWT[e3ML] += WSP[e1L]*dp;\t\n\t\t\t}\n\t\t\telse if(g_pupy[nuc_a] == g_pupy[nuc_d])\n\t\t\t{\n\t\t\t\tWT[e3MS] += WSP[e1M]*dp;\n\t\t\t\tWT[e3SV] += WSP[e1V]*dp;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tWT[e3MV] += WSP[e1M]*dp;\n\t\t\t\tWT[e3SV] += WSP[e1S]*dp;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\tfor(size_t k = d; k > 0; --k)\n\t\t\t{\n\t\t\t\tdp = model.p_indel_size[k];\n\t\t\t\tex_s &WSK = table_s(a,d-k);\n\t\t\t\tnoalias(WT) += table_t(a,d-k)*dp;\t\n\t\t\t\tWT[e3MG] += WSK[e1M]*dp;\n\t\t\t\tWT[e3ML] += WSK[e1M]*dp*cache_log[k];\n\t\t\t\t\n\t\t\t}\t\t\t\n\t\t\tfor(size_t k = a; k > 0; --k)\n\t\t\t{\t\t\n\t\t\t\tdp = model.p_indel_size[k];\n\t\t\t\tex_s &WSK = table_s(a-k,d);\n\t\t\t\tnoalias(WT) += table_t(a-k,d)*dp;\n\t\t\t\tWT[e3MG] += WSK[e1M]*dp;\n\t\t\t\tWT[e3ML] += WSK[e1M]*dp*cache_log[k];\n\t\t\t}\n\t\t}\n\t}\t\n\t\n\tex2 = table_t(sz_anc,sz_dec);\n\t\t\n\tex2 /= w;\n\tex[eMS] = ex2[e3MS];\n\tex[eMV] = ex2[e3MV];\n\tex[eMG] = ex2[e3MG];\n\tex[eML] = ex2[e3ML];\n\tex[eSV] = ex2[e3SV];\n\t\n\toutput() << \".\" << std::flush;\n\t\t\n\t// Third Cycle: e4: e4SG, e4SL, e4VG, e4VL, e4GL\n\ttable_t(0,0).clear();\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_t &WT = table_t(0,d);\n\t\tWT.clear();\n\t\tfor(size_t k = d; k > 0; --k)\n\t\t{\n\t\t\tdp = model.p_indel_size[k];\n\t\t\tnoalias(WT) += table_t(0,d-k)*dp;\n\t\t\tex_s &WSK = table_s(0,d-k);\n\t\t\tWT[e4SG] += WSK[e1S]*dp;\n\t\t\tWT[e4VG] += WSK[e1V]*dp;\n\t\t\tWT[e4SL] += WSK[e1S]*dp*cache_log[k];\n\t\t\tWT[e4VL] += WSK[e1V]*dp*cache_log[k];\n\t\t\tWT[e4GL] += WSK[e1G]*dp*cache_log[k] + WSK[e1L]*dp + WSK[e1W]*dp*cache_log[k];\n\t\t}\n\t}\t\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_t &WT = table_t(a,0);\n\t\tWT.clear();\n\t\tfor(size_t k = a; k > 0; --k)\n\t\t{\n\t\t\tdp = model.p_indel_size[k];\n\t\t\tnoalias(WT) += table_t(a-k,0)*dp;\n\t\t\tex_s &WSK = table_s(a-k,0);\n\t\t\tWT[e4SG] += WSK[e1S]*dp;\n\t\t\tWT[e4VG] += WSK[e1V]*dp;\n\t\t\tWT[e4SL] += WSK[e1S]*dp*cache_log[k];\n\t\t\tWT[e4VL] += WSK[e1V]*dp*cache_log[k];\n\t\t\tWT[e4GL] += WSK[e1G]*dp*cache_log[k] + WSK[e1L]*dp + WSK[e1W]*dp*cache_log[k];\n\t\t}\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\tfor(size_t d=1;d<= sz_dec;++d)\n\t\t{\n\t\t\tnuc_a = seq_a[a-1];\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\t\t\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\tex_t &WT = table_t(a,d);\n\t\t\tnoalias(WT) = table_t(a-1,d-1)*dp;\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\t\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWT[e4SG] += WSP[e1G]*dp*model.p_ts;\n\t\t\t\tWT[e4SL] += WSP[e1L]*dp*model.p_tv;\n\t\t\t\tWT[e4VG] += WSP[e1G]*dp*model.p_ts;\n\t\t\t\tWT[e4VL] += WSP[e1L]*dp*model.p_tv;\n\t\t\t\t\n\t\t\t}\n\t\t\telse if(nuc_a == nuc_d)\n\t\t\t{\n\t\t\t}\n\t\t\telse if(g_pupy[nuc_a] == g_pupy[nuc_d])\n\t\t\t{\n\t\t\t\tWT[e4SG] += WSP[e1G]*dp;\n\t\t\t\tWT[e4SL] += WSP[e1L]*dp;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tWT[e4VG] += WSP[e1G]*dp;\n\t\t\t\tWT[e4VL] += WSP[e1L]*dp;\n\t\t\t}\n\t\t\tfor(size_t k = d; k > 0; --k)\n\t\t\t{\n\t\t\t\tdp = model.p_indel_size[k];\n\t\t\t\tex_s &WSK = table_s(a,d-k);\n\t\t\t\tnoalias(WT) += table_t(a,d-k)*dp;\n\t\t\t\tWT[e4SG] += WSK[e1S]*dp;\n\t\t\t\tWT[e4VG] += WSK[e1V]*dp;\n\t\t\t\tWT[e4SL] += WSK[e1S]*dp*cache_log[k];\n\t\t\t\tWT[e4VL] += WSK[e1V]*dp*cache_log[k];\n\t\t\t\tWT[e4GL] += WSK[e1G]*dp*cache_log[k] + WSK[e1L]*dp + WSK[e1W]*dp*cache_log[k];\n\t\t\t}\n\t\t\tfor(size_t k = a; k > 0; --k)\n\t\t\t{\n\t\t\t\tdp = model.p_indel_size[k];\n\t\t\t\tex_s &WSK = table_s(a-k,d);\n\t\t\t\tnoalias(WT) += table_t(a-k,d)*dp;\n\t\t\t\tWT[e4SG] += WSK[e1S]*dp;\n\t\t\t\tWT[e4VG] += WSK[e1V]*dp;\n\t\t\t\tWT[e4SL] += WSK[e1S]*dp*cache_log[k];\n\t\t\t\tWT[e4VL] += WSK[e1V]*dp*cache_log[k];\n\t\t\t\tWT[e4GL] += WSK[e1G]*dp*cache_log[k] + WSK[e1L]*dp + WSK[e1W]*dp*cache_log[k];\n\t\t\t}\n\t\t}\n\t}\n\tex2 = table_t(sz_anc,sz_dec);\n\t\n\tex2 /= w;\n\tex[eSG] = ex2[e4SG];\n\tex[eSL] = ex2[e4SL];\n\tex[eVG] = ex2[e4VG];\n\tex[eVL] = ex2[e4VL];\n\tex[eGL] = ex2[e4GL];\n\t\n\toutput() << \".\" << std::flush;\n\t\n\treturn log(w) + log(model.p_end) - log(prob_scale)\n\t\t+ static_cast<double>(sz_anc+sz_dec)*log(model.nuc_scale)\n\t\t+ static_cast<double>(get_seq_info()[index][nN])*log(model.amb_scale);\n\t\n}\n\nvoid covar_k2p_zeta::covariance(covar_type &v, const params_type &p, const exvec_type &ev)\n{\n\tex_type ex;\n\tex.clear();\n\t\n\tfor(exvec_type::const_iterator cit=ev.begin();cit != ev.end();++cit)\n\t\tadd_expectation(ex, *cit);\n\t\n\tdouble W = get_seqs().size();\n\tdouble M = ex[eM], S = ex[eS], V = ex[eV], G = ex[eG], L = ex[eL];\n\tdouble MM = ex[eMM], SS = ex[eSS], VV = ex[eVV], GG = ex[eGG], LL = ex[eLL];\n\tdouble MS = ex[eMS], MV = ex[eMV], MG = ex[eMG], ML = ex[eML], SV = ex[eSV];\n\tdouble SG = ex[eSG], SL = ex[eSL], VG = ex[eVG], VL = ex[eVL], GL = ex[eGL];\n\t\t\n\tdouble t = p[pT], k = p[pK], r = p[pR],\n\t\tz = p[pZ], a = p[pA];\n\t\n\tdouble ek = 1.0+k;\n\tdouble ek2 = 1.0 + 2.0*k;\n\tdouble ea = exp(-t*ek2/ek);\n\tdouble eb = exp(-2.0*t/ek);\n\tdouble er = exp(-2.0*t*r);\n\t\n\tdouble da = 4.0/(1.0 - 2.0*ea + eb);\n\tdouble db = 4.0/(1.0 + 2.0*ea + eb);\n\tdouble dc = eb-1.0;\n\tdouble de = -2.0*eb/(dc*ek);\n\tdouble df = er/(1.0-er);\n\t\n\tdouble tt = ((8.0*de*(V + 2.0*ek*r*(MV + SV - df*VG)))/ek + 4.0*V*sq(de) +\n\t\t(2.0*da*(-2.0*eb*(S + 2.0*ek*r*(MS - df*SG + SS)) + 2.0*eb*ek*(de - 2.0*r)*SV +\n\t\tea*ek2*(4.0*ek*MS*r + S + 2.0*k*S -\n\t\t2.0*ek*(2.0*df*r*SG + de*SV - 2.0*r*(SS + SV)))))/sq(ek) -\n\t\t(2.0*db*(ea*ek2*(M + 2.0*k*M +\n\t\t2.0*ek*(-(de*MV) + 2.0*(-(df*MG) + MM + MS + MV)*r)) +\n\t\teb*(2.0*M + da*eb*MS +\n\t\t2.0*ek*(-(de*MV) + 2.0*(-(df*MG) + MM + MS + MV)*r)) -\n\t\tda*MS*sq(ea + 2.0*ea*k)))/sq(ek) +\n\t\t((S - SS)*sq(da)*sq(ea - eb + 2.0*ea*k))/sq(ek) +\n\t\t((M - MM)*sq(db)*sq(ea + eb + 2.0*ea*k))/sq(ek) +\n\t\t16.0*(-MM - 2.0*MS - 2.0*MV - SS - 2.0*SV +\n\t\tdf*(G + df*G - df*GG + 2.0*(MG + SG + VG)))*sq(r) -\n\t\t(4.0*VV*sq(de)*sq(eb + dc*ek*r))/sq(eb))/4.0\n\t\t;\n\t\n\tdouble tk = (-2.0*da*dc*(dc*(ea + eb)*ek*S +\n\t\t(-(dc*ea*(2.0*ek*MS*r + S + 2.0*k*S + 2.0*ek*r*(-(df*SG) + SS))) -\n\t\t2.0*dc*eb*(S + ek*r*(MS - df*SG + SS)) +\n\t\teb*(-2.0*eb + dc*de*ek - 2.0*dc*ek*r)*SV +\n\t\tea*(dc*de*ek + 2.0*eb*ek2 - 2.0*dc*ek*r)*SV)*t) +\n\t\t8.0*eb*(2.0*dc*ek*MV*r*t - (dc*ek + 2.0*t)*V + 2.0*eb*t*VV +\n\t\t2.0*dc*ek*r*t*(SV - df*VG + VV)) +\n\t\t(ea + eb)*(ea - eb + 2.0*ea*k)*(S - SS)*t*sq(da)*sq(dc) +\n\t\t(ea - eb)*(ea + eb + 2.0*ea*k)*(M - MM)*t*sq(db)*sq(dc) +\n\t\t2.0*db*dc*(eb*(-(dc*M*(ek - 2.0*t)) +\n\t\t(da*dc*eb*MS + 2.0*eb*MV - dc*de*ek*MV +\n\t\t2.0*dc*ek*(-(df*MG) + MM + MS + MV)*r)*t) +\n\t\tea*((dc*de*ek*MV + 2.0*eb*ek2*MV -\n\t\t2.0*dc*ek*(-(df*MG) + MM + MS + MV)*r)*t + dc*M*(ek - t - 2.0*k*t))\n\t\t+ da*dc*ek2*MS*t*sq(ea)))/(4.0*sq(ek)*ek*sq(dc))\n\t\t;\n\n\t\n\tdouble tr = (-2.0*k*M - 2.0*k*S + db*ea*MM*t + 2.0*db*ea*k*MM*t - da*ea*MS*t + db*ea*MS*t -\n\t\t2.0*da*ea*k*MS*t + 2.0*db*ea*k*MS*t - 2.0*de*MV*t + db*ea*MV*t -\n\t\t2.0*de*k*MV*t + 2.0*db*ea*k*MV*t + 4.0*MM*r*t + 4.0*k*MM*r*t + 8.0*MS*r*t +\n\t\t8.0*k*MS*r*t + 8.0*MV*r*t + 8.0*k*MV*r*t - da*ea*SS*t - 2.0*da*ea*k*SS*t +\n\t\t4.0*r*SS*t + 4.0*k*r*SS*t - 2.0*de*SV*t - da*ea*SV*t - 2.0*de*k*SV*t -\n\t\t2.0*da*ea*k*SV*t + 8.0*r*SV*t + 8.0*k*r*SV*t - 2.0*k*V - 2.0*(M + S + V) +\n\t\tdc*df*(2.0*ek*G*(-1.0 + 2.0*r*t) +\n\t\tt*(db*(ea + eb + 2.0*ea*k)*MG + 8.0*ek*MG*r -\n\t\t(da*(ea - eb + 2.0*ea*k) - 8.0*ek*r)*SG - 2.0*ek*(de - 4.0*r)*VG)) +\n\t\t4.0*ek*r*t*VV + eb*(2.0*ek*M + 2.0*S - db*(-1.0 + ea)*MM*t + 2.0*V +\n\t\t2.0*k*(S - db*ea*(MM + MS + MV)*t + V +\n\t\tt*(de*(MV + SV) + da*ea*(MS + SS + SV) -\n\t\t2.0*r*(MM + 2.0*MS + 2.0*MV + SS + 2.0*SV + VV))) +\n\t\tt*(-(db*(-1.0 + ea)*(MS + MV)) + da*(1.0 + ea)*(MS + SS + SV) +\n\t\t2.0*(de*(MV + SV) - 2.0*VV - 2.0*r*(MM + 2.0*MS + 2.0*MV + SS + 2.0*SV + VV)))\n\t\t) + 4.0*dc*ek*(G - GG)*r*t*sq(df) -\n\t\t(db*(MM + MS + MV) + da*(MS + SS + SV))*t*sq(eb))/(dc*ek)\n\t\t;\n\n\tdouble tz = -(db*(ea + eb + 2.0*ea*k)*ML - 4.0*df*ek*GL*r + 4.0*ML*r + 4.0*k*ML*r - da*ea*SL +\n\t\tda*eb*SL - 2.0*da*ea*k*SL + 4.0*r*SL + 4.0*k*r*SL - 2.0*ek*(de - 2.0*r)*VL +\n\t\t(db*(ea + eb + 2.0*ea*k)*MG - 4.0*df*ek*GG*r + 4.0*MG*r + 4.0*k*MG*r -\n\t\tda*ea*SG + da*eb*SG - 2.0*da*ea*k*SG + 4.0*r*SG + 4.0*k*r*SG -\n\t\t2.0*ek*(de - 2.0*r)*VG)*zeta_ratio(z))/(2.0*ek)\n\t\t;\n\t\n\tdouble ta = (db*(ea + eb + 2.0*ea*k)*(MG + MM + MS + MV - a*M*W) -\n\t\tda*(ea - eb + 2.0*ea*k)*(MS + SG + SS + SV - a*S*W) +\n\t\t2.0*ek*(-(de*(MV + SV + VG + VV - a*V*W)) +\n\t\t2.0*r*(MG + MM + 2.0*MS + 2.0*MV + SG + SS + 2.0*SV + VG -\n\t\tdf*(GG + MG + SG + VG) + VV - a*(-(df*G) + M + S + V)*W)))/\n\t\t(2.0*a*(1.0 + a)*ek)\n\t\t;\n\n\tdouble kk = (t*(2.0*da*dc*(2.0*dc*(ea + eb)*ek*S +\n\t\t(dc*(ea - 2.0*eb)*S - 4.0*eb*(ea + eb)*SV)*t) +\n\t\t16.0*eb*((dc*ek + t)*V - eb*t*VV) +\n\t\t2.0*db*dc*(-2.0*dc*(ea - eb)*ek*M +\n\t\tt*(4.0*(ea - eb)*eb*MV -\n\t\tdc*(ea*M + eb*(2.0*M + da*eb*MS) - da*MS*sq(ea)))) +\n\t\t(M - MM)*t*sq(db)*sq(dc)*sq(ea - eb) +\n\t\t(S - SS)*t*sq(da)*sq(dc)*sq(ea + eb)))/(4.0*sq(ek*ek*dc))\n\t\t;\n\t\n\tdouble kr = ((db*dc*(ea - eb)*(df*MG - MM - MS - MV) +\n\t\tda*dc*(ea + eb)*(MS - df*SG + SS + SV) + 4.0*eb*(MV + SV - df*VG + VV))*\n\t\tsq(t))/(dc*sq(ek))\n\t\t;\n\t\n   double kz = (t*(dc*(db*(-ea + eb)*ML + da*(ea + eb)*SL) + 4.0*eb*VL +\n\t\t(dc*(db*(-ea + eb)*MG + da*(ea + eb)*SG) + 4.0*eb*VG)*zeta_ratio(z)))/\n\t\t(2.0*dc*sq(ek))\n\t\t;\n\t\n\tdouble ka = (t*(db*dc*(ea - eb)*(MG + MM + MS + MV - a*M*W) -\n\t\tda*dc*(ea + eb)*(MS + SG + SS + SV - a*S*W) -\n\t\t4.0*eb*(MV + SV + VG + VV - a*V*W)))/(2.0*a*(1.0 + a)*dc*sq(ek))\n\t\t;\n\n   double rr = 4.0*(-MM - 2.0*MS - 2.0*MV - SS - 2.0*SV +\n\t\tdf*(G + df*G - df*GG + 2.0*(MG + SG + VG)) - VV)*sq(t)\n\t\t;\n\n   double rz = (2.0*t*(ML + SL + VL - er*(GL + ML + SL + VL) +\n\t\t(MG + SG + VG - er*(GG + MG + SG + VG))*zeta_ratio(z)))/(-1.0 + er)\n\t\t;\n\t\n\tdouble ra = (2.0*t*(-(df*(-1.0 + er)*(GG + MG + SG + VG)) +\n\t\t(-1.0 + er)*(MG + MM + 2.0*MS + 2.0*MV + SG + SS + 2.0*SV + VG + VV) -\n\t\ta*(-M - S - V + er*(G + M + S + V))*W))/(a*(1.0 + a)*(-1.0 + er))\n\t\t;\n\n\n\tdouble zz = -LL - (G + GG)*sq(zeta_ratio(z)) - 2.0*GL*zeta_ratio(z) + G*zeta_ratio2(z);\n\t\n\tdouble za = (GL + ML + SL + VL - a*L*W + (GG + MG + SG + VG - a*G*W)*zeta_ratio(z))/\n\t\t(a*(1.0 + a))\n\t\t;\n\t\n\tdouble aa = -((GG - M + 2.0*MG + MM + 2.0*MS + 2.0*MV - S + 2.0*SG + SS + 2.0*SV - V + 2.0*VG +\n\t\tVV + a*(1.0 + W)*(-2.0*(M + S + V) + a*W) - G*(1.0 + 2.0*a*(1.0 + W)))/\n\t\t(sq(a)*sq(1.0 + a)))\n\t\t;\n\t\n\tcovar_type fim(p.size(), p.size());\n\tfim(pT,pT) = tt; fim(pT,pK) = tk; fim(pT,pR) = tr; fim(pT,pZ) = tz; fim(pT,pA) = ta;\n\tfim(pK,pT) = tk; fim(pK,pK) = kk; fim(pK,pR) = kr; fim(pK,pZ) = kz; fim(pK,pA) = ka;\n\tfim(pR,pT) = tr; fim(pR,pK) = kr; fim(pR,pR) = rr; fim(pR,pZ) = rz; fim(pR,pA) = ra;\n\tfim(pZ,pT) = tz; fim(pZ,pK) = kz; fim(pZ,pR) = rz; fim(pZ,pZ) = zz; fim(pZ,pA) = za;\n\tfim(pA,pT) = ta; fim(pA,pK) = ka; fim(pA,pR) = ra; fim(pA,pZ) = za; fim(pA,pA) = aa;\n\t\t\n\tinvert_matrix(fim, v);\n}\n\n\nvoid covar_k2p_zeta::add_expectation(ex_type &ex, const ex_type &ad) const\n{\n\tcout << ad << endl;\n\t\n\tex[eMM] += ad[eMM] + 2.0*ex[eM]*ad[eM];\n\tex[eSS] += ad[eSS] + 2.0*ex[eS]*ad[eS];\n\tex[eVV] += ad[eVV] + 2.0*ex[eV]*ad[eV];\n\tex[eGG] += ad[eGG] + 2.0*ex[eG]*ad[eG];\n\tex[eLL] += ad[eLL] + 2.0*ex[eL]*ad[eL];\n\t\n\tex[eMS] += ad[eMS] + ex[eM]*ad[eS] + ex[eS]*ad[eM];\n\tex[eMV] += ad[eMV] + ex[eM]*ad[eV] + ex[eV]*ad[eM];\n\tex[eMG] += ad[eMG] + ex[eM]*ad[eG] + ex[eG]*ad[eM];\n\tex[eML] += ad[eML] + ex[eM]*ad[eL] + ex[eL]*ad[eM];\n\tex[eSV] += ad[eSV] + ex[eS]*ad[eV] + ex[eV]*ad[eS];\n\tex[eSG] += ad[eSG] + ex[eS]*ad[eG] + ex[eG]*ad[eS];\n\tex[eSL] += ad[eSL] + ex[eS]*ad[eL] + ex[eL]*ad[eS];\n\tex[eVG] += ad[eVG] + ex[eV]*ad[eG] + ex[eG]*ad[eV];\n\tex[eVL] += ad[eVL] + ex[eV]*ad[eL] + ex[eL]*ad[eV];\n\tex[eGL] += ad[eGL] + ex[eG]*ad[eL] + ex[eL]*ad[eG];\n\n\tex[eM] += ad[eM];\n\tex[eS] += ad[eS];\n\tex[eV] += ad[eV];\n\tex[eG] += ad[eG];\n\tex[eL] += ad[eL];\n}\n\n\nstd::string covar_k2p_zeta::state() const\n{\n\tex_type ex;\n\tex.clear();\n\tconst exvec_type &ev = get_exvec();\n\tfor(exvec_type::const_iterator cit=ev.begin();cit != ev.end();++cit)\n\t\tadd_expectation(ex, *cit);\t\n\t\n\tconst covar_type &v = get_covar();\n\t\n\tostringstream ostr;\n\tostr << std::setprecision(DBL_DIG);\n\tostr << \"ex = \" << ex << endl;\n\tostr << \"var = \" << v << endl;\n\treturn ostr.str();\n}\n\n/***************************************************************************\n * class covar_k2p_geo                                                     *\n ***************************************************************************/\n\nvoid covar_k2p_geo::preallocate(size_t maxa, size_t maxd)\n{\n\tsz_height = maxa+1;\n\tsz_width = maxd+1;\n\t\t\n\tsize_t sz_max = std::max(sz_height, sz_width);\n\t\n\tcache_size.resize(sz_max, 0.0);\n\tfor(size_t u=1;u<sz_max;++u)\n\t\tcache_size[u] = static_cast<double>(u);\n}\n\nvoid covar_k2p_geo::expectation_setup(const params_type &params)\n{\n\n}\n\ndouble covar_k2p_geo::expectation(ex_type &ex, const sequence &seq_a, const sequence &seq_d, size_t index) const\n{\n\tsize_t sz_anc = seq_a.size();\n\tsize_t sz_dec = seq_d.size();\n\n\tconst model_type &model = get_model();\n\t\n\tenum {xW, xE, xF, xEE, xEF = xEE};\n\n\ttypedef ublas::cc_vector<double, 4> ex_s;\n\tex_s szero = ublas::zero_vector<double>(4);\n\ttable<ex_s> table_s(sz_anc+1,sz_dec+1,szero);\n\tex_s row_cache;\n\tvector<ex_s> col_cache(sz_dec+1,szero);\n\n\ttable_s(0,0)[xW] = prob_scale;\n\tdouble dp = model.p_open;\n\tint nuc_a, nuc_d;\n\t// M, MM\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW]*model.p_match;\n\t\t\t\tWS[xEE] += (WSP[xE]+WSP[xE]+WSP[xW]*model.p_match)*model.p_match*dp;\n\t\t\t}\n\t\t\telse if(nuc_a == nuc_d)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW];\n\t\t\t\tWS[xEE] += (WSP[xE]+WSP[xE]+WSP[xW])*dp;\n\t\t\t}\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex_s ex1 = table_s(sz_anc,sz_dec);\n\tdouble w = ex1[xW];\n\tex1 /= w;\n\tex[eM] = ex1[xE]; ex[eMM] = ex1[xEE];\n\toutput() << \".\" << std::flush;\n\n\t// S, SS\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW]*model.p_ts;\n\t\t\t\tWS[xEE] += (WSP[xE]+WSP[xE]+WSP[xW]*model.p_ts)*model.p_ts*dp;\n\t\t\t}\n\t\t\telse if(nuc_a != nuc_d && g_pupy[nuc_a] == g_pupy[nuc_d])\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW];\n\t\t\t\tWS[xEE] += (WSP[xE]+WSP[xE]+WSP[xW])*dp;\n\t\t\t}\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eS] = ex1[xE]; ex[eSS] = ex1[xEE];\n\toutput() << \".\" << std::flush;\n\n\t// V, VV\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\t\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW]*model.p_tv;\n\t\t\t\tWS[xEE] += (WSP[xE]+WSP[xE]+WSP[xW]*model.p_tv)*model.p_tv*dp;\n\t\t\t}\n\t\t\telse if(nuc_a != nuc_d && g_pupy[nuc_a] != g_pupy[nuc_d])\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW];\n\t\t\t\tWS[xEE] += (WSP[xE]+WSP[xE]+WSP[xW])*dp;\n\t\t\t}\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eV] = ex1[xE]; ex[eVV] = ex1[xEE];\n\toutput() << \".\" << std::flush;\n\t\n\t// G, GG\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xE] += WSK[xW];\n\t\trow_cache[xEE] += WSK[xE]+WSK[xE]+WSK[xW];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xE] += WSK[xW];\n\t\trow_cache[xEE] += WSK[xE]+WSK[xE]+WSK[xW];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\trow_cache[xE] += WSK[xW];\n\t\t\t\trow_cache[xEE] += WSK[xE]+WSK[xE]+WSK[xW];\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tcol_cache[d][xE] += WSK[xW];\n\t\t\t\tcol_cache[d][xEE] += WSK[xE]+WSK[xE]+WSK[xW];\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eG] = ex1[xE]; ex[eGG] = ex1[xEE];\n\toutput() << \".\" << std::flush;\n\n\t// Y, YY\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xE] += row_cache[xW];\n\t\trow_cache[xEE] += WSK[xE]+WSK[xE]+row_cache[xW];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\t\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xE] += row_cache[xW];\n\t\trow_cache[xEE] += WSK[xE]+WSK[xE]+row_cache[xW];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\trow_cache[xE] += row_cache[xW];\n\t\t\t\trow_cache[xEE] += WSK[xE]+WSK[xE]+row_cache[xW];\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tcol_cache[d][xE] += col_cache[d][xW];\n\t\t\t\tcol_cache[d][xEE] += WSK[xE]+WSK[xE]+col_cache[d][xW];\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eY] = ex1[xE]; ex[eYY] = ex1[xEE];\n\toutput() << \".\" << std::flush;\n\t\n\t// MS\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW]*model.p_match;\n\t\t\t\tWS[xF] += WS[xW]*model.p_ts;\n\t\t\t\tWS[xEF] += (WSP[xE]*model.p_ts+WSP[xF]*model.p_match+WSP[xW]*model.p_match*model.p_ts)*dp;\n\t\t\t}\n\t\t\telse if(nuc_a == nuc_d)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW];\n\t\t\t\tWS[xEF] += WSP[xF]*dp;\n\t\t\t}\t\t\t\n\t\t\telse if(g_pupy[nuc_a] == g_pupy[nuc_d])\n\t\t\t{\n\t\t\t\tWS[xF] += WS[xW];\n\t\t\t\tWS[xEF] += WSP[xE]*dp;\n\t\t\t}\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eMS] = ex1[xEF];\n\toutput() << \".\" << std::flush;\n\t\n\t// MV\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\tnoalias(WS) += row_cache*dp;\n\t}\t\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW]*model.p_match;\n\t\t\t\tWS[xF] += WS[xW]*model.p_tv;\n\t\t\t\tWS[xEF] += (WSP[xE]*model.p_tv+WSP[xF]*model.p_match+WSP[xW]*model.p_match*model.p_tv)*dp;\n\t\t\t}\n\t\t\telse if(nuc_a == nuc_d)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW];\n\t\t\t\tWS[xEF] += WSP[xF]*dp;\n\t\t\t}\t\t\t\n\t\t\telse if(g_pupy[nuc_a] != g_pupy[nuc_d])\n\t\t\t{\n\t\t\t\tWS[xF] += WS[xW];\n\t\t\t\tWS[xEF] += WSP[xE]*dp;\n\t\t\t}\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eMV] = ex1[xEF];\n\toutput() << \".\" << std::flush;\n\n\t// SV\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW]*model.p_ts;\n\t\t\t\tWS[xF] += WS[xW]*model.p_tv;\n\t\t\t\tWS[xEF] += (WSP[xE]*model.p_tv+WSP[xF]*model.p_ts+WSP[xW]*model.p_ts*model.p_tv)*dp;\n\t\t\t}\n\t\t\telse if(nuc_a == nuc_d)\n\t\t\t\t;\n\t\t\telse if(g_pupy[nuc_a] == g_pupy[nuc_d])\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW];\n\t\t\t\tWS[xEF] += WSP[xF]*dp;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tWS[xF] += WS[xW];\n\t\t\t\tWS[xEF] += WSP[xE]*dp;\n\t\t\t}\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eSV] = ex1[xEF];\n\toutput() << \".\" << std::flush;\n\t\n\t// MG\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xF] += WSK[xW];\n\t\trow_cache[xEF] += WSK[xE];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xF] += WSK[xW];\n\t\trow_cache[xEF] += WSK[xE];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW]*model.p_match;\n\t\t\t\tWS[xEF] += WSP[xF]*model.p_match*dp;\n\t\t\t}\n\t\t\telse if(nuc_a == nuc_d)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW];\n\t\t\t\tWS[xEF] += WSP[xF]*dp;\n\t\t\t}\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\trow_cache[xF] += WSK[xW];\n\t\t\t\trow_cache[xEF] += WSK[xE];\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tcol_cache[d][xF] += WSK[xW];\n\t\t\t\tcol_cache[d][xEF] += WSK[xE];\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eMG] = ex1[xEF];\n\toutput() << \".\" << std::flush;\n\t\n\t// SG\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xF] += WSK[xW];\n\t\trow_cache[xEF] += WSK[xE];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xF] += WSK[xW];\n\t\trow_cache[xEF] += WSK[xE];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW]*model.p_ts;\n\t\t\t\tWS[xEF] += WSP[xF]*model.p_ts*dp;\n\t\t\t}\n\t\t\telse if(nuc_a != nuc_d && g_pupy[nuc_a] == g_pupy[nuc_d])\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW];\n\t\t\t\tWS[xEF] += WSP[xF]*dp;\n\t\t\t}\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\trow_cache[xF] += WSK[xW];\n\t\t\t\trow_cache[xEF] += WSK[xE];\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tcol_cache[d][xF] += WSK[xW];\n\t\t\t\tcol_cache[d][xEF] += WSK[xE];\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eSG] = ex1[xEF];\n\toutput() << \".\" << std::flush;\n\t\n\t// VG\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xF] += WSK[xW];\n\t\trow_cache[xEF] += WSK[xE];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xF] += WSK[xW];\n\t\trow_cache[xEF] += WSK[xE];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW]*model.p_tv;\n\t\t\t\tWS[xEF] += WSP[xF]*model.p_tv*dp;\n\t\t\t}\n\t\t\telse if(nuc_a != nuc_d && g_pupy[nuc_a] != g_pupy[nuc_d])\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW];\n\t\t\t\tWS[xEF] += WSP[xF]*dp;\n\t\t\t}\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\trow_cache[xF] += WSK[xW];\n\t\t\t\trow_cache[xEF] += WSK[xE];\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tcol_cache[d][xF] += WSK[xW];\n\t\t\t\tcol_cache[d][xEF] += WSK[xE];\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eVG] = ex1[xEF];\n\toutput() << \".\" << std::flush;\n\n\t// MY\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xF] += row_cache[xW];\n\t\trow_cache[xEF] += row_cache[xE];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xF] += row_cache[xW];\n\t\trow_cache[xEF] += row_cache[xE];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW]*model.p_match;\n\t\t\t\tWS[xEF] += WSP[xF]*model.p_match*dp;\n\t\t\t}\n\t\t\telse if(nuc_a == nuc_d)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW];\n\t\t\t\tWS[xEF] += WSP[xF]*dp;\n\t\t\t}\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\trow_cache[xF] += row_cache[xW];\n\t\t\t\trow_cache[xEF] += row_cache[xE];\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tcol_cache[d][xF] += col_cache[d][xW];\n\t\t\t\tcol_cache[d][xEF] += col_cache[d][xE];\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eMY] = ex1[xEF];\n\toutput() << \".\" << std::flush;\n\n\t// SY\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xF] += row_cache[xW];\n\t\trow_cache[xEF] += row_cache[xE];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xF] += row_cache[xW];\n\t\trow_cache[xEF] += row_cache[xE];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW]*model.p_ts;\n\t\t\t\tWS[xEF] += WSP[xF]*model.p_ts*dp;\n\t\t\t}\n\t\t\telse if(nuc_a != nuc_d && g_pupy[nuc_a] == g_pupy[nuc_d])\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW];\n\t\t\t\tWS[xEF] += WSP[xF]*dp;\n\t\t\t}\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\trow_cache[xF] += row_cache[xW];\n\t\t\t\trow_cache[xEF] += row_cache[xE];\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tcol_cache[d][xF] += col_cache[d][xW];\n\t\t\t\tcol_cache[d][xEF] += col_cache[d][xE];\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eSY] = ex1[xEF];\n\toutput() << \".\" << std::flush;\n\t\n\t// VY\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xF] += row_cache[xW];\n\t\trow_cache[xEF] += row_cache[xE];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xF] += row_cache[xW];\n\t\trow_cache[xEF] += row_cache[xE];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\tif(nuc_a == nN || nuc_d == nN)\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW]*model.p_tv;\n\t\t\t\tWS[xEF] += WSP[xF]*model.p_tv*dp;\n\t\t\t}\n\t\t\telse if(nuc_a != nuc_d && g_pupy[nuc_a] != g_pupy[nuc_d])\n\t\t\t{\n\t\t\t\tWS[xE] += WS[xW];\n\t\t\t\tWS[xEF] += WSP[xF]*dp;\n\t\t\t}\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\trow_cache[xF] += row_cache[xW];\n\t\t\t\trow_cache[xEF] += row_cache[xE];\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tcol_cache[d][xF] += col_cache[d][xW];\n\t\t\t\tcol_cache[d][xEF] += col_cache[d][xE];\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eVY] = ex1[xEF];\n\toutput() << \".\" << std::flush;\n\t\n\t// GY\n\trow_cache.clear();\n\tfill(col_cache.begin(), col_cache.end(), szero);\n\ttable_s(0,0)[xW] = prob_scale;\n\tdp = model.p_open;\n\tfor(size_t d = 1; d <= sz_dec; ++d)\n\t{\n\t\tex_s &WS = table_s(0,d);\n\t\tex_s &WSK = table_s(0,d-1);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xEF] += WSK[xF]+row_cache[xE]+row_cache[xW];\n\t\trow_cache[xE] += WSK[xW];\n\t\trow_cache[xF] += row_cache[xW];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\trow_cache.clear();\n\tfor(size_t a = 1; a <= sz_anc; ++a)\n\t{\n\t\tex_s &WS = table_s(a,0);\n\t\tex_s &WSK = table_s(a-1,0);\n\t\tWS.clear();\n\t\trow_cache *= model.p_extend;\n\t\tnoalias(row_cache) += WSK;\n\t\trow_cache[xEF] += WSK[xF]+row_cache[xE]+row_cache[xW];\n\t\trow_cache[xE] += WSK[xW];\n\t\trow_cache[xF] += row_cache[xW];\n\t\tnoalias(WS) += row_cache*dp;\n\t}\n\tfor(size_t a=1;a<=sz_anc;++a)\n\t{\n\t\trow_cache.clear();\n\t\tnuc_a = seq_a[a-1];\n\t\tfor(size_t d=1;d<=sz_dec;++d)\n\t\t{\n\t\t\tnuc_d = seq_d[d-1];\n\t\t\tdp = model.p_substitution[nuc_a][nuc_d];\n\t\t\t\t\n\t\t\tex_s &WS = table_s(a,d);\n\t\t\tex_s &WSP = table_s(a-1,d-1);\n\t\t\tnoalias(WS) = WSP*dp;\n\t\t\t\n\t\t\tdp = model.p_open;\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a,d-1);\n\t\t\t\trow_cache *= model.p_extend;\n\t\t\t\tnoalias(row_cache) += WSK;\n\t\t\t\trow_cache[xEF] += WSK[xF]+row_cache[xE]+row_cache[xW];\n\t\t\t\trow_cache[xE] += WSK[xW];\n\t\t\t\trow_cache[xF] += row_cache[xW];\n\t\t\t\tnoalias(WS) += row_cache*dp;\n\t\t\t}\n\t\t\t\n\t\t\t{\n\t\t\t\tex_s &WSK = table_s(a-1,d);\n\t\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\t\tnoalias(col_cache[d]) += WSK;\n\t\t\t\tcol_cache[d][xEF] += WSK[xF]+col_cache[d][xE]+col_cache[d][xW];\n\t\t\t\tcol_cache[d][xE] += WSK[xW];\n\t\t\t\tcol_cache[d][xF] += col_cache[d][xW];\n\t\t\t\tnoalias(WS) += col_cache[d]*dp;\n\t\t\t}\n\t\t}\n\t}\n\tex1 = table_s(sz_anc,sz_dec);\n\tex1 /= w;\n\tex[eGY] = ex1[xEF];\n\toutput() << \".\" << std::flush;\n\n\treturn log(w) + log(model.p_end) - log(prob_scale)\n\t\t+ static_cast<double>(sz_anc+sz_dec)*log(model.nuc_scale)\n\t\t+ static_cast<double>(get_seq_info()[index][nN])*log(model.amb_scale);\n}\n\nvoid covar_k2p_geo::covariance(covar_type &v, const params_type &p, const exvec_type &ev)\n{\n\tex_type ex;\n\tex.clear();\n\t\n\tfor(exvec_type::const_iterator cit=ev.begin();cit != ev.end();++cit)\n\t\tadd_expectation(ex, *cit);\n\t\n\tdouble W = get_seqs().size();\n\tdouble M = ex[eM], S = ex[eS], V = ex[eV], G = ex[eG], Y = ex[eY];\n\tdouble MM = ex[eMM], SS = ex[eSS], VV = ex[eVV], GG = ex[eGG], YY = ex[eYY];\n\tdouble MS = ex[eMS], MV = ex[eMV], MG = ex[eMG], MY = ex[eMY], SV = ex[eSV];\n\tdouble SG = ex[eSG], SY = ex[eSY], VG = ex[eVG], VY = ex[eVY], GY = ex[eGY];\n\t\t\n\tdouble t = p[pT], k = p[pK], r = p[pR], q = p[pQ], a = p[pA];\n\t\n\tdouble ek = 1.0+k;\n\tdouble ek2 = 1.0 + 2.0*k;\n\tdouble ea = exp(-t*ek2/ek);\n\tdouble eb = exp(-2.0*t/ek);\n\tdouble er = exp(-2.0*t*r);\n\t\n\tdouble da = 4.0/(1.0 - 2.0*ea + eb);\n\tdouble db = 4.0/(1.0 + 2.0*ea + eb);\n\tdouble dc = eb-1.0;\n\tdouble de = -2.0*eb/(dc*ek);\n\tdouble df = er/(1.0-er);\n\t\n\tdouble tt = ((8.0*de*(V + 2.0*ek*r*(MV + SV - df*VG)))/ek + 4.0*V*sq(de) +\n\t\t(2.0*da*(-2.0*eb*(S + 2.0*ek*r*(MS - df*SG + SS)) + 2.0*eb*ek*(de - 2.0*r)*SV +\n\t\tea*ek2*(4.0*ek*MS*r + S + 2.0*k*S -\n\t\t2.0*ek*(2.0*df*r*SG + de*SV - 2.0*r*(SS + SV)))))/sq(ek) -\n\t\t(2.0*db*(ea*ek2*(M + 2.0*k*M +\n\t\t2.0*ek*(-(de*MV) + 2.0*(-(df*MG) + MM + MS + MV)*r)) +\n\t\teb*(2.0*M + da*eb*MS +\n\t\t2.0*ek*(-(de*MV) + 2.0*(-(df*MG) + MM + MS + MV)*r)) -\n\t\tda*MS*sq(ea + 2.0*ea*k)))/sq(ek) +\n\t\t((S - SS)*sq(da)*sq(ea - eb + 2.0*ea*k))/sq(ek) +\n\t\t((M - MM)*sq(db)*sq(ea + eb + 2.0*ea*k))/sq(ek) +\n\t\t16.0*(-MM - 2.0*MS - 2.0*MV - SS - 2.0*SV +\n\t\tdf*(G + df*G - df*GG + 2.0*(MG + SG + VG)))*sq(r) -\n\t\t(4.0*VV*sq(de)*sq(eb + dc*ek*r))/sq(eb))/4.0\n\t\t;\n\t\n\tdouble tk = (-2.0*da*dc*(dc*(ea + eb)*ek*S +\n\t\t(-(dc*ea*(2.0*ek*MS*r + S + 2.0*k*S + 2.0*ek*r*(-(df*SG) + SS))) -\n\t\t2.0*dc*eb*(S + ek*r*(MS - df*SG + SS)) +\n\t\teb*(-2.0*eb + dc*de*ek - 2.0*dc*ek*r)*SV +\n\t\tea*(dc*de*ek + 2.0*eb*ek2 - 2.0*dc*ek*r)*SV)*t) +\n\t\t8.0*eb*(2.0*dc*ek*MV*r*t - (dc*ek + 2.0*t)*V + 2.0*eb*t*VV +\n\t\t2.0*dc*ek*r*t*(SV - df*VG + VV)) +\n\t\t(ea + eb)*(ea - eb + 2.0*ea*k)*(S - SS)*t*sq(da)*sq(dc) +\n\t\t(ea - eb)*(ea + eb + 2.0*ea*k)*(M - MM)*t*sq(db)*sq(dc) +\n\t\t2.0*db*dc*(eb*(-(dc*M*(ek - 2.0*t)) +\n\t\t(da*dc*eb*MS + 2.0*eb*MV - dc*de*ek*MV +\n\t\t2.0*dc*ek*(-(df*MG) + MM + MS + MV)*r)*t) +\n\t\tea*((dc*de*ek*MV + 2.0*eb*ek2*MV -\n\t\t2.0*dc*ek*(-(df*MG) + MM + MS + MV)*r)*t + dc*M*(ek - t - 2.0*k*t))\n\t\t+ da*dc*ek2*MS*t*sq(ea)))/(4.0*ek*sq(ek)*sq(dc))\n\t\t;\n\n\t\n\tdouble tr = (-2.0*k*M - 2.0*k*S + db*ea*MM*t + 2.0*db*ea*k*MM*t - da*ea*MS*t + db*ea*MS*t -\n\t\t2.0*da*ea*k*MS*t + 2.0*db*ea*k*MS*t - 2.0*de*MV*t + db*ea*MV*t -\n\t\t2.0*de*k*MV*t + 2.0*db*ea*k*MV*t + 4.0*MM*r*t + 4.0*k*MM*r*t + 8.0*MS*r*t +\n\t\t8.0*k*MS*r*t + 8.0*MV*r*t + 8.0*k*MV*r*t - da*ea*SS*t - 2.0*da*ea*k*SS*t +\n\t\t4.0*r*SS*t + 4.0*k*r*SS*t - 2.0*de*SV*t - da*ea*SV*t - 2.0*de*k*SV*t -\n\t\t2.0*da*ea*k*SV*t + 8.0*r*SV*t + 8.0*k*r*SV*t - 2.0*k*V - 2.0*(M + S + V) +\n\t\tdc*df*(2.0*ek*G*(-1.0 + 2.0*r*t) +\n\t\tt*(db*(ea + eb + 2.0*ea*k)*MG + 8.0*ek*MG*r -\n\t\t(da*(ea - eb + 2.0*ea*k) - 8.0*ek*r)*SG - 2.0*ek*(de - 4.0*r)*VG)) +\n\t\t4.0*ek*r*t*VV + eb*(2.0*ek*M + 2.0*S - db*(-1.0 + ea)*MM*t + 2.0*V +\n\t\t2.0*k*(S - db*ea*(MM + MS + MV)*t + V +\n\t\tt*(de*(MV + SV) + da*ea*(MS + SS + SV) -\n\t\t2.0*r*(MM + 2.0*MS + 2.0*MV + SS + 2.0*SV + VV))) +\n\t\tt*(-(db*(-1.0 + ea)*(MS + MV)) + da*(1.0 + ea)*(MS + SS + SV) +\n\t\t2.0*(de*(MV + SV) - 2.0*VV - 2.0*r*(MM + 2.0*MS + 2.0*MV + SS + 2.0*SV + VV)))\n\t\t) + 4.0*dc*ek*(G - GG)*r*t*sq(df) -\n\t\t(db*(MM + MS + MV) + da*(MS + SS + SV))*t*sq(eb))/(dc*ek)\n\t\t;\n\n\tdouble tq = (db*dc*(ea + eb + 2.0*ea*k)*(MY - MG*q) - 4.0*MY*r + 4.0*eb*MY*r - 4.0*k*MY*r +\n\t\t4.0*eb*k*MY*r + 4.0*MG*q*r - 4.0*eb*MG*q*r + 4.0*k*MG*q*r - 4.0*eb*k*MG*q*r -\n\t\t4.0*dc*df*ek*(GY - GG*q)*r - da*ea*q*SG + da*eb*q*SG + da*ea*eb*q*SG -\n\t\t2.0*da*ea*k*q*SG + 2.0*da*ea*eb*k*q*SG + 4.0*q*r*SG - 4.0*eb*q*r*SG +\n\t\t4.0*k*q*r*SG - 4.0*eb*k*q*r*SG + da*ea*SY - da*eb*SY - da*ea*eb*SY +\n\t\t2.0*da*ea*k*SY - 2.0*da*ea*eb*k*SY - 4.0*r*SY + 4.0*eb*r*SY - 4.0*k*r*SY +\n\t\t4.0*eb*k*r*SY - 2.0*de*q*VG + 2.0*de*eb*q*VG - 2.0*de*k*q*VG + 2.0*de*eb*k*q*VG +\n\t\t4.0*q*r*VG - 4.0*eb*q*r*VG + 4.0*k*q*r*VG - 4.0*eb*k*q*r*VG +\n\t\t4.0*(eb + dc*ek*r)*VY - da*q*SG*sq(eb) + da*SY*sq(eb))/\n\t\t(2.0*dc*ek*(-1.0 + q)*q)\n\t\t;\n\t\n\tdouble ta = (db*(ea + eb + 2.0*ea*k)*(MG + MM + MS + MV - a*M*W) -\n\t\tda*(ea - eb + 2.0*ea*k)*(MS + SG + SS + SV - a*S*W) +\n\t\t2.0*ek*(-(de*(MV + SV + VG + VV - a*V*W)) +\n\t\t2.0*r*(MG + MM + 2.0*MS + 2.0*MV + SG + SS + 2.0*SV + VG -\n\t\tdf*(GG + MG + SG + VG) + VV - a*(-(df*G) + M + S + V)*W)))/\n\t\t(2.0*a*(1.0 + a)*ek)\n\t\t;\n\n\tdouble kk = (t*(2.0*da*dc*(2.0*dc*(ea + eb)*ek*S +\n\t\t(dc*(ea - 2.0*eb)*S - 4.0*eb*(ea + eb)*SV)*t) +\n\t\t16.0*eb*((dc*ek + t)*V - eb*t*VV) +\n\t\t2.0*db*dc*(-2.0*dc*(ea - eb)*ek*M +\n\t\tt*(4.0*(ea - eb)*eb*MV -\n\t\tdc*(ea*M + eb*(2.0*M + da*eb*MS) - da*MS*sq(ea)))) +\n\t\t(M - MM)*t*sq(db)*sq(dc)*sq(ea - eb) +\n\t\t(S - SS)*t*sq(da)*sq(dc)*sq(ea + eb)))/(4.0*sq(sq(ek))*sq(dc))\n\t\t;\n\t\n\tdouble kr = ((db*dc*(ea - eb)*(df*MG - MM - MS - MV) +\n\t\tda*dc*(ea + eb)*(MS - df*SG + SS + SV) + 4.0*eb*(MV + SV - df*VG + VV))*\n\t\tsq(t))/(dc*sq(ek))\n\t\t;\n\t\n   double kq = (t*(db*dc*(ea - eb)*(MY - MG*q) + da*dc*(ea + eb)*(q*SG - SY) +\n\t\t4.0*eb*(q*VG - VY)))/(2.0*dc*(-1.0 + q)*q*sq(ek))\n\t\t;\n\t\n\tdouble ka = (t*(db*dc*(ea - eb)*(MG + MM + MS + MV - a*M*W) -\n\t\tda*dc*(ea + eb)*(MS + SG + SS + SV - a*S*W) -\n\t\t4.0*eb*(MV + SV + VG + VV - a*V*W)))/(2.0*a*(1.0 + a)*dc*sq(ek))\n\t\t;\n\n   double rr = 4.0*(-MM - 2.0*MS - 2.0*MV - SS - 2.0*SV +\n\t\tdf*(G + df*G - df*GG + 2.0*(MG + SG + VG)) - VV)*sq(t)\n\t\t;\n\n   double rq = (2.0*t*(MY + df*(-GY + GG*q) + SY - q*(MG + SG + VG) + VY))/((-1.0 + q)*q)\n\t\t;\n\t\n\tdouble ra = (2.0*t*(-(df*(-1.0 + er)*(GG + MG + SG + VG)) +\n\t\t(-1.0 + er)*(MG + MM + 2.0*MS + 2.0*MV + SG + SS + 2.0*SV + VG + VV) -\n\t\ta*(-M - S - V + er*(G + M + S + V))*W))/(a*(1.0 + a)*(-1.0 + er))\n\t\t;\n\n\n\tdouble qq = -((q*(-2.0*GY + (G + GG)*q - 2.0*Y) + Y + YY)/(sq(-1.0 + q)*sq(q)));\n\t\n\tdouble qa = -((GY + MY + SY + VY - q*(GG + MG + SG + VG - a*G*W) - a*W*Y)/\n\t\t(a*(1.0 + a)*(-1.0 + q)*q))\n\t\t;\n\t\n\tdouble aa = -((GG - M + 2.0*MG + MM + 2.0*MS + 2.0*MV - S + 2.0*SG + SS + 2.0*SV - V + 2.0*VG +\n\t\tVV + a*(1.0 + W)*(-2.0*(M + S + V) + a*W) - G*(1.0 + 2.0*a*(1.0 + W)))/\n\t\t(sq(a)*sq(1.0 + a)))\n\t\t;\n\t\n\tcovar_type fim(p.size(), p.size());\n\tfim(pT,pT) = tt; fim(pT,pK) = tk; fim(pT,pR) = tr; fim(pT,pQ) = tq; fim(pT,pA) = ta;\n\tfim(pK,pT) = tk; fim(pK,pK) = kk; fim(pK,pR) = kr; fim(pK,pQ) = kq; fim(pK,pA) = ka;\n\tfim(pR,pT) = tr; fim(pR,pK) = kr; fim(pR,pR) = rr; fim(pR,pQ) = rq; fim(pR,pA) = ra;\n\tfim(pQ,pT) = tq; fim(pQ,pK) = kq; fim(pQ,pR) = rq; fim(pQ,pQ) = qq; fim(pQ,pA) = qa;\n\tfim(pA,pT) = ta; fim(pA,pK) = ka; fim(pA,pR) = ra; fim(pA,pQ) = qa; fim(pA,pA) = aa;\n\t\t\n\tinvert_matrix(fim, v);\n}\n\n\nvoid covar_k2p_geo::add_expectation(ex_type &ex, const ex_type &ad) const\n{\n\tcout << ad << endl;\n\t\n\tex[eMM] += ad[eMM] + 2.0*ex[eM]*ad[eM];\n\tex[eSS] += ad[eSS] + 2.0*ex[eS]*ad[eS];\n\tex[eVV] += ad[eVV] + 2.0*ex[eV]*ad[eV];\n\tex[eGG] += ad[eGG] + 2.0*ex[eG]*ad[eG];\n\tex[eYY] += ad[eYY] + 2.0*ex[eY]*ad[eY];\n\t\n\tex[eMS] += ad[eMS] + ex[eM]*ad[eS] + ex[eS]*ad[eM];\n\tex[eMV] += ad[eMV] + ex[eM]*ad[eV] + ex[eV]*ad[eM];\n\tex[eMG] += ad[eMG] + ex[eM]*ad[eG] + ex[eG]*ad[eM];\n\tex[eMY] += ad[eMY] + ex[eM]*ad[eY] + ex[eY]*ad[eM];\n\tex[eSV] += ad[eSV] + ex[eS]*ad[eV] + ex[eV]*ad[eS];\n\tex[eSG] += ad[eSG] + ex[eS]*ad[eG] + ex[eG]*ad[eS];\n\tex[eSY] += ad[eSY] + ex[eS]*ad[eY] + ex[eY]*ad[eS];\n\tex[eVG] += ad[eVG] + ex[eV]*ad[eG] + ex[eG]*ad[eV];\n\tex[eVY] += ad[eVY] + ex[eV]*ad[eY] + ex[eY]*ad[eV];\n\tex[eGY] += ad[eGY] + ex[eG]*ad[eY] + ex[eY]*ad[eG];\n\n\tex[eM] += ad[eM];\n\tex[eS] += ad[eS];\n\tex[eV] += ad[eV];\n\tex[eG] += ad[eG];\n\tex[eY] += ad[eY];\n}\n\n\nstd::string covar_k2p_geo::state() const\n{\n\tex_type ex;\n\tex.clear();\n\tconst exvec_type &ev = get_exvec();\n\tfor(exvec_type::const_iterator cit=ev.begin();cit != ev.end();++cit)\n\t\tadd_expectation(ex, *cit);\n\t\n\tconst covar_type &v = get_covar();\n\t\n\tostringstream ostr;\n\tostr << std::setprecision(DBL_DIG);\n\tostr << \"ex = \" << ex << endl;\n\tostr << \"var = \" << v << endl;\n\treturn ostr.str();\n}\n", "meta": {"hexsha": "f43d1dd924675d1c78d4d6d543b776190213c5f1", "size": 55424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/covar.cpp", "max_stars_repo_name": "reedacartwright/emdel", "max_stars_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/covar.cpp", "max_issues_repo_name": "reedacartwright/emdel", "max_issues_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-03T16:50:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T22:51:19.000Z", "max_forks_repo_path": "src/covar.cpp", "max_forks_repo_name": "reedacartwright/emdel", "max_forks_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3", "max_forks_repo_licenses": ["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.1197361745, "max_line_length": 113, "alphanum_fraction": 0.5377634238, "num_tokens": 24066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5529711943582566}}
{"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": "#define _CONSOLE\n\n#include <functional>\n\n#include <boost/lexical_cast.hpp>\n\n#include <skynet/neuralnetworks/ffnet.hpp>\n//#include <skynet/neuralnetworks/auto_encoder.hpp>\n#include <skynet/cv/extension/bmp.hpp>\n#include <skynet/core/crop.hpp>\n#include <skynet/core/io.hpp>\n#include <skynet/utility/algorithm.hpp>\n#include <skynet/utility/load_data.hpp>\n#include <skynet/core/interpolate.hpp>\n\nusing namespace skynet;\nusing namespace skynet::nn;\nusing namespace skynet::numeric;\n\nint main(){\n\tstd::srand(std::time(nullptr));\n\n\tcv::io::bmp_info_header info;\n\tauto image = cv::image_cast<cv::image_gray>(cv::io::read_bmp(\"../data/ocean_fish.bmp\", info));\n\t//auto images = grid_crop(image, extent2(8,8));\n    //auto images = utility::get_digit_images(\"../data/mnist/t10k-images-idx3-ubyte\");\n    auto train_images = utility::get_digit_images(\"../data/mnist/train-images-idx3-ubyte\");\n    auto train_labels = utility::get_digit_labels(\"../data/mnist/train-labels-idx1-ubyte\");\n    \n    std::vector<array2b> digit6_images;    \n    for (size_t i = 0; i < train_images.size(); ++i){\n        if (train_labels[i] == 6 || train_labels[i] == 9){\n            digit6_images.push_back(train_images[i]);\n           // cv::io::write_bmp(digit6_images.back(), \"../data/mnist/train/digit6/\"+boost::lexical_cast<string>(digit6_images.size())+\".bmp\");\n        }\n    }\n   \n\tml::database2<double, double> data;\n   // size_t samples_size = digit6_images.size();\n    size_t samples_size = 100;\n\tdata.patterns.resize(digit6_images.front().size(), samples_size);\n\tfor (size_t i = 0; i < samples_size; ++i){\n        auto image = digit6_images[i];\n        auto col_data = column(data.patterns, i);\n        skynet::transform(image, col_data, [](byte e)->double{ return 0.25+0.5*e/256.0;});\n\t}\n\tdata.targets = data.patterns;\n\tauto net = make_shared<ffnet>(data.patterns.size1(), data.patterns.size1());\n    //net->add_layer(make_shared<ffnet::layer<sigmoid_function<>>>(128));\n\tnet->add_layer(make_shared<ffnet::sparse_layer<sigmoid_function<>>>(10));\n    //net->add_layer(make_shared<ffnet::layer<sigmoid_function<>>>(128));\n\tnet->add_layer(make_shared<ffnet::layer<sigmoid_function<>>>(data.patterns.size1()));\n\toptimizer_adaptor<rprop<ffnet::model>> opt;\n\toptimizer_adaptor<lbfgs<ffnet::model>> opt1;\n\n\topt.iteration_num(100);\n\topt1.iteration_num(200);\n\tnet->train(data, opt1);\n    \n    for (size_t i = 0; i < samples_size; ++i){\n        auto re = (*net)(column(data.patterns, i));\n        array2b re_image(28,28);\n        transform(re, re_image,[](double e){ return byte((e-0.25)/0.5 * 256);});\n        cv::io::write_bmp(re_image, \"../data/mnist/train/digit6_encode/\"+boost::lexical_cast<string>(i)+\".bmp\");\n    }\n\n\n\tauto weights = net->layers().front()->w();\n\twrite2raw(weights, \"../data/weights.raw\");\n\treturn 0;\n}", "meta": {"hexsha": "7f20cd4463c9e7ab67aea65e8c63fb46f96daa3f", "size": 2788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/auto_encoder_example.cpp", "max_stars_repo_name": "zhangzhimin/skynet", "max_stars_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-08-02T03:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-16T01:07:55.000Z", "max_issues_repo_path": "examples/auto_encoder_example.cpp", "max_issues_repo_name": "zhangzhimin/skynet", "max_issues_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/auto_encoder_example.cpp", "max_forks_repo_name": "zhangzhimin/skynet", "max_forks_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2676056338, "max_line_length": 142, "alphanum_fraction": 0.6804160689, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5529169710885224}}
{"text": "#include <iostream>\n#include <boost/format.hpp>\n// Qt headers\n#include <QtGui>\n#include <CGAL/Qt/GraphicsViewNavigation.h>\n#include <QLineF>\n#include <QRectF>\n#include <QApplication> \n#include <QGraphicsScene>\n#include <QGraphicsView> \n// CGAL headers\n#include <CGAL/Qt/PointsGraphicsItem.h>\n#include <CGAL/Qt/GraphicsViewPolylineInput.h>\n#include <CGAL/Qt/utility.h>\n// GraphicsView items and event filters (input classes)\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/Largest_empty_iso_rectangle_2.h>\n// the two base classes\n#include <QString>\n#include <QFileDialog>\n#include <QInputDialog>\n#include <QGraphicsRectItem>\n#include <QGraphicsLineItem>\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point_2;\ntypedef K::Vector_2 Vector_2;\ntypedef K::Segment_2 Segment_2;\nusing namespace std;\n\n\nint main(int argc, char **argv)\n{\n\tCGAL::Qt::PointsGraphicsItem<std::vector<Point_2> > * pgi;\n\tstd::vector<Point_2> points;\n\n\tQApplication app(argc, argv);\n\tQGraphicsScene scene;\n\n\n\tFILE *fp = NULL;\n\tfp = fopen(\"../src/input.txt\",\"r\");\n\tint ptx,pty;\n\twhile(fscanf(fp,\"%d %d\",&ptx,&pty)!=EOF){\n\n\t\tPoint_2 P(ptx, pty);\n\t\tpoints.push_back(P);\n\n\t}\n\t\n\t\n\tpgi = new CGAL::Qt::PointsGraphicsItem<std::vector<Point_2> >(&points);\n\tpgi->setVerticesPen(QPen(Qt::red,2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n    scene.setSceneRect(0,0, 100, 100);\n\tscene.addItem(pgi);\n    QGraphicsView* view = new QGraphicsView(&scene);\n    CGAL::Qt::GraphicsViewNavigation navigation;\n    view->installEventFilter(&navigation);\n    view->viewport()->installEventFilter(&navigation);\n    view->setRenderHint(QPainter::Antialiasing);\n\n    view->show();\n\t\n    return app.exec();\n}\n", "meta": {"hexsha": "bc48837e571d55d30d121bbc6f1edd7aa2c1bf53", "size": 1756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "q1/src/min.cpp", "max_stars_repo_name": "justinepdevasia/cgal-assignments", "max_stars_repo_head_hexsha": "4d97df0e630ae17ad2dc2415ff9962986f004c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "q1/src/min.cpp", "max_issues_repo_name": "justinepdevasia/cgal-assignments", "max_issues_repo_head_hexsha": "4d97df0e630ae17ad2dc2415ff9962986f004c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "q1/src/min.cpp", "max_forks_repo_name": "justinepdevasia/cgal-assignments", "max_forks_repo_head_hexsha": "4d97df0e630ae17ad2dc2415ff9962986f004c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6060606061, "max_line_length": 82, "alphanum_fraction": 0.7369020501, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5528955513884006}}
{"text": "//\n// Copyright Jason Rice 2015\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include <mpdef/compose_collectors.hpp>\n\n#include <boost/hana.hpp>\n\nnamespace hana = boost::hana;\n\ntemplate<int i>\nconstexpr auto counter = hana::demux(hana::partial(hana::plus, hana::int_c<i>))(hana::arg<1>);\n\ntemplate<int i>\nconstexpr auto mult = hana::demux(hana::append)\n(\n  hana::arg<1>,\n  hana::demux(hana::partial(hana::mult, hana::int_c<i>))(hana::arg<2>)\n);\n\nint main()\n{\n  {\n    constexpr auto xs = hana::to_tuple(hana::range_c<int, 0, 5>);\n    constexpr auto initial_state = hana::make_tuple(\n      hana::make_tuple(),\n      hana::make_tuple(),\n      hana::make_tuple()\n    );\n    constexpr auto collector = mpdef::compose_collectors(\n      mult<1>,\n      mult<2>,\n      mult<3>\n    );\n    constexpr auto result = hana::fold(xs, initial_state, collector);\n    constexpr auto expected = hana::make_tuple(\n      hana::tuple_c<int, 0, 1, 2, 3, 4>,\n      hana::tuple_c<int, 0, 2, 4, 6, 8>,\n      hana::tuple_c<int, 0, 3, 6, 9, 12>\n    );\n    (void)result;\n    (void)expected;\n\n    BOOST_HANA_CONSTANT_ASSERT(result == expected);\n  }\n\n  {\n    constexpr auto xs = hana::to_tuple(hana::range_c<int, 0, 5>);\n\n    constexpr auto result = hana::fold(xs,\n      hana::make_tuple(\n        hana::int_c<0>,\n        hana::int_c<0>,\n        hana::int_c<0>,\n        hana::make_tuple()\n      ),\n      mpdef::compose_collectors(\n        counter<1>,\n        counter<2>,\n        counter<3>,\n        hana::append\n      ));\n    constexpr auto expected = hana::make_tuple(\n      hana::int_c<5>,\n      hana::int_c<10>,\n      hana::int_c<15>,\n      xs\n    );\n    (void)result;\n    (void)expected;\n    BOOST_HANA_CONSTANT_ASSERT(result == expected);\n  }\n}\n", "meta": {"hexsha": "6ed149a32d2910021fca605bf0cc341b700389bf", "size": 1831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/mpdef/compose_collectors.cpp", "max_stars_repo_name": "ricejasonf/nbdl", "max_stars_repo_head_hexsha": "ae63717c96ab2c36107bc17b2b00115f96e9d649", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-06-20T01:41:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T10:53:27.000Z", "max_issues_repo_path": "test/mpdef/compose_collectors.cpp", "max_issues_repo_name": "ricejasonf/nbdl", "max_issues_repo_head_hexsha": "ae63717c96ab2c36107bc17b2b00115f96e9d649", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2015-11-12T23:05:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-17T19:01:40.000Z", "max_forks_repo_path": "test/mpdef/compose_collectors.cpp", "max_forks_repo_name": "ricejasonf/nbdl", "max_forks_repo_head_hexsha": "ae63717c96ab2c36107bc17b2b00115f96e9d649", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:23:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-09T17:54:25.000Z", "avg_line_length": 23.7792207792, "max_line_length": 94, "alphanum_fraction": 0.606226106, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5528955454130907}}
{"text": "#include \"txt_reader.hpp\"\n#include <decomp_util/ellipsoid_decomp.h>\n#include <decomp_geometry/geometric_utils.h>\n\n#include <fstream>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\n\nint main(int argc, char **argv) {\n  if (argc != 2) {\n    printf(ANSI_COLOR_RED \"Input txt file required!\\n\" ANSI_COLOR_RESET);\n    return -1;\n  }\n\n  // Read obstacles\n  vec_Vec2f obs;\n  if(!read_obs<2>(argv[1], obs)) {\n    printf(ANSI_COLOR_RED \"Cannot find input file [%s]!\\n\" ANSI_COLOR_RESET,\n           argv[1]);\n    return -1;\n  }\n\n  // Set map size\n  const Vec2f origin(-2, -2);\n  const Vec2f range(4, 4);\n\n  // Path to dilate\n  vec_Vec2f path;\n  path.push_back(Vec2f(1, 1.0));\n  path.push_back(Vec2f(0.0, 0.0));\n  path.push_back(Vec2f(-1, 1.0));\n\n  // Initialize SeedDecomp2D\n  EllipsoidDecomp2D decomp(origin, range);\n  decomp.set_obs(obs);\n  decomp.set_local_bbox(Vec2f(2, 2));\n  decomp.dilate(path, 0);\n\n  // Plot the result in svg image\n  typedef boost::geometry::model::d2::point_xy<double> point_2d;\n  std::ofstream svg(\"output.svg\");\n  // Declare a stream and an SVG mapper\n  boost::geometry::svg_mapper<point_2d> mapper(svg, 1000, 1000);\n\n  // Draw the canvas 4 x 4m\n  boost::geometry::model::polygon<point_2d> bound;\n  std::vector<point_2d> points;\n  points.push_back(point_2d(origin(0), origin(1)));\n  points.push_back(point_2d(origin(0), origin(1) + range(1)));\n  points.push_back(point_2d(origin(0) + range(0), origin(1) + range(1)));\n  points.push_back(point_2d(origin(0) + range(0), origin(1)));\n  points.push_back(point_2d(origin(0), origin(1)));\n  boost::geometry::assign_points(bound, points);\n  boost::geometry::correct(bound);\n\n  mapper.add(bound);\n  mapper.map(bound, \"fill-opacity:1.0;fill:rgb(255,255,255);stroke:rgb(0,0,0);\"\n                    \"stroke-width:2\"); // White\n  // Draw obstacles\n  for(const auto& it: obs) {\n    point_2d pt;\n    boost::geometry::assign_values(pt, it(0), it(1));\n    mapper.add(pt);\n    mapper.map(pt, \"fill-opacity:1.0;fill:rgb(255,0,0);\", 10); // Red\n  }\n\n  // Draw ellispoid\n  {\n    for(const auto& E: decomp.get_ellipsoids()) {\n      int num = 40; // number of points on trajectory to draw\n      boost::geometry::model::linestring<point_2d> line;\n      for (const auto& it: E.sample(num))\n        line.push_back(point_2d(it(0), it(1)));\n      line.push_back(line.front());\n      mapper.add(line);\n      mapper.map(line,\n                 \"opacity:0.4;fill:none;stroke:rgb(118,215,234);stroke-width:5\");\n    }\n  }\n\n  // Draw polygon\n  {\n    for(const auto& poly: decomp.get_polyhedrons()) {\n      const auto vertices = cal_vertices(poly);\n      std::string ss(\"POLYGON((\");\n      for (size_t i = 0; i < vertices.size(); i++) {\n        ss += std::to_string(vertices[i](0)) + \" \" +\n          std::to_string(vertices[i](1));\n        if(i == vertices.size() - 1)\n          ss += \"))\";\n        else\n          ss += \",\";\n      }\n\n      boost::geometry::model::polygon<point_2d> p;\n      boost::geometry::read_wkt(ss, p);\n      mapper.add(p);\n      mapper.map(p, \"fill-opacity:0.2;fill:rgb(51,51,153);stroke:rgb(51,51,153);stroke-width:2\");\n    }\n  }\n\n  // Draw path\n  {\n    boost::geometry::model::linestring<point_2d> line;\n    for(const auto& it: path)\n      line.push_back(point_2d(it(0), it(1)));\n    mapper.add(line);\n    mapper.map(line,\n               \"opacity:0.8;fill:none;stroke:rgb(255,0,0);stroke-width:5\");\n  }\n\n\n  // Write title at the lower right corner on canvas\n  mapper.text(point_2d(1.0, -1.8), \"test_ellipsoid_decomp\",\n              \"fill-opacity:1.0;fill:rgb(10,10,250);\");\n\n  return 0;\n}\n", "meta": {"hexsha": "36fc12d8838386338c90a321481607cda7fa3bba", "size": 3630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/DecompROS/DecompUtil/test/test_ellipsoid_decomp.cpp", "max_stars_repo_name": "shubham-shahh/mader", "max_stars_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "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": "thirdparty/DecompROS/DecompUtil/test/test_ellipsoid_decomp.cpp", "max_issues_repo_name": "shubham-shahh/mader", "max_issues_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "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": "thirdparty/DecompROS/DecompUtil/test/test_ellipsoid_decomp.cpp", "max_forks_repo_name": "shubham-shahh/mader", "max_forks_repo_head_hexsha": "7cbe46438b348a1ad9545146734083d0b6436bd4", "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": 30.0, "max_line_length": 97, "alphanum_fraction": 0.6269972452, "num_tokens": 1145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5528576894241573}}
{"text": "#include <boost/serialization/export.hpp>\n#include \"SimpleNeuron.hpp\"\n\nusing namespace std;\nusing namespace snn;\nusing namespace internal;\n\nBOOST_CLASS_EXPORT(SimpleNeuron)\n\nSimpleNeuron::SimpleNeuron(NeuronModel model, shared_ptr<NeuralNetworkOptimizer> optimizer)\n    : Neuron(model, optimizer)\n{\n}\n\nfloat SimpleNeuron::output(const vector<float>& inputs)\n{\n    this->lastInputs = inputs;\n    this->sum = 0;\n    for (size_t w = 0; w < this->weights.size(); ++w)\n    {\n        this->sum += inputs[w] * weights[w];\n    }\n    this->sum += bias;\n    return this->outputFunction->function(this->sum);\n}\n\nvector<float>& SimpleNeuron::backOutput(float error)\n{\n    error = error * this->outputFunction->derivative(this->sum);\n\n    for (size_t w = 0; w < this->weights.size(); ++w)\n    {\n        this->errors[w] = error * weights[w];\n    }\n    this->optimizer->updateWeights(*this, error);\n    return this->errors;\n}\n\nvoid SimpleNeuron::train(float error)\n{\n    error = error * outputFunction->derivative(this->sum);\n\n    this->optimizer->updateWeights(*this, error);\n}\n\nint SimpleNeuron::isValid() const\n{\n    return this->Neuron::isValid();\n}\n\nbool SimpleNeuron::operator==(const SimpleNeuron& neuron) const\n{\n    return this->Neuron::operator==(neuron);\n}\n\nbool SimpleNeuron::operator!=(const SimpleNeuron& neuron) const\n{\n    return !(*this == neuron);\n}\n", "meta": {"hexsha": "90489c7c3fd479ab3081e1d6ed2d59d5a30f6509", "size": 1353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/neural_network/layer/neuron/SimpleNeuron.cpp", "max_stars_repo_name": "sehe/StraightforwardNeuralNetwork", "max_stars_repo_head_hexsha": "9758a808cdb87ffa5f1606fde9d673ef922fe6bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-16T22:13:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T22:13:25.000Z", "max_issues_repo_path": "src/neural_network/layer/neuron/SimpleNeuron.cpp", "max_issues_repo_name": "sehe/StraightforwardNeuralNetwork", "max_issues_repo_head_hexsha": "9758a808cdb87ffa5f1606fde9d673ef922fe6bc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/neural_network/layer/neuron/SimpleNeuron.cpp", "max_forks_repo_name": "sehe/StraightforwardNeuralNetwork", "max_forks_repo_head_hexsha": "9758a808cdb87ffa5f1606fde9d673ef922fe6bc", "max_forks_repo_licenses": ["Apache-2.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.55, "max_line_length": 91, "alphanum_fraction": 0.6755358463, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867969424067, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5528576859461515}}
{"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": "#ifdef _DEBUG\n#include \"../../../library/src/debug_template.hpp\"\n#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__)\n#else\n#define DMP(...) ((void)0)\n#endif\n\n#include <cassert>\n#include <cstdio>\n#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_map>\n#include <queue>\n#include <numeric>\n#include <algorithm>\n#include <bitset>\n#include <functional>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace mp = boost::multiprecision;\n\nusing namespace std;\nusing lint = long long;\nconstexpr int INF = 1010101010;\nconstexpr lint LINF = 1LL << 60;\n\nstruct init {\n    init() {\n        cin.tie(nullptr);\n        ios::sync_with_stdio(false);\n        cout << fixed << setprecision(10);\n    }\n} init_;\n\ntemplate<class T, class F>\nT bisearch(T OK, T NG, F f) {\n    T ok = OK;\n    T ng = NG;\n\n    while (abs(ok - ng) > 1) {\n        auto mid = (ok + ng) / 2;\n\n        if (f(mid)) ok = mid;\n        else ng = mid;\n    }\n\n    return ok;\n}\n\nint main() {\n\n    string X;\n    lint M;\n    cin >> X >> M;\n\n    if (X.size() == 1) {\n        cout << (X[0] - '0' <= M) << '\\n';\n        return 0;\n    }\n\n    reverse(X.begin(), X.end());\n\n    auto check = [&](const lint &k) {\n        mp::cpp_int now = 0;\n        mp::cpp_int x = 1;\n        for (const auto &c : X) {\n            now += (c - '0') * x;\n            x *= k;\n        }\n        return now <= M;\n    };\n\n    lint d = *max_element(X.begin(), X.end()) - '0';\n    cout << bisearch(d, M + 1, check) - d << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "f25e9b77b3876f1adeda6b071861e04986014f79", "size": 1546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ABC/ABC192/D.cpp", "max_stars_repo_name": "rajyan/AtCoder", "max_stars_repo_head_hexsha": "2c1187994016d4c19b95489d2f2d2c0eab43dd8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-01T17:13:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-01T17:13:44.000Z", "max_issues_repo_path": "ABC/ABC192/D.cpp", "max_issues_repo_name": "rajyan/AtCoder", "max_issues_repo_head_hexsha": "2c1187994016d4c19b95489d2f2d2c0eab43dd8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ABC/ABC192/D.cpp", "max_forks_repo_name": "rajyan/AtCoder", "max_forks_repo_head_hexsha": "2c1187994016d4c19b95489d2f2d2c0eab43dd8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.4047619048, "max_line_length": 52, "alphanum_fraction": 0.5368693402, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5528576691674902}}
{"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": "#include <boost/random.hpp>\n#include <boost/random/random_device.hpp>\n\nint\nmain ()\n{\n  boost::random::random_device dev;\n  boost::random::uniform_int_distribution dist (10, 20);\n\n  for (int i (0); i != 100; ++i)\n  {\n    if (dist (dev) < 10 || dist (dev) > 20)\n      return 1;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "e55fe3d795d185ff9275340084b2bdc9bc15aea5", "size": 295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "downstream/libs/random/test/basics/driver.cpp", "max_stars_repo_name": "build2-packaging/boost", "max_stars_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-23T11:24:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T20:10:46.000Z", "max_issues_repo_path": "libboost-random/tests/basics/driver.cpp", "max_issues_repo_name": "build2-packaging/boost", "max_issues_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libboost-random/tests/basics/driver.cpp", "max_forks_repo_name": "build2-packaging/boost", "max_forks_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3888888889, "max_line_length": 56, "alphanum_fraction": 0.606779661, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5528576609310013}}
{"text": "// Copyright Louis Dionne 2015\n// Distributed under the Boost Software License, Version 1.0.\n\n#include <boost/hana.hpp>\n\n#include <cstddef>\n#include <tuple>\n#include <type_traits>\n#include <utility>\nnamespace hana = boost::hana;\nusing namespace boost::hana::literals;\n\n\ntemplate <typename Tuples, std::size_t ...i, std::size_t ...j,\n  typename Res = std::tuple<\n    std::tuple_element_t<j, std::tuple_element_t<i,\n      std::remove_reference_t<Tuples>>>...\n  >\n>\nconstexpr Res tuple_cat_impl(Tuples&& tuples,\n                             std::index_sequence<i...>,\n                             std::index_sequence<j...>)\n{\n  return Res{\n      std::get<j>(std::get<i>(std::forward<Tuples>(tuples)))...\n  };\n}\n\n\ntemplate <typename ...Tuples>\nconstexpr auto tuple_cat(Tuples&& ...tuples) {\n  constexpr std::size_t N = sizeof...(Tuples);\n  hana::tuple<Tuples&&...> xs{std::forward<Tuples>(tuples)...};\n\n  constexpr auto indices = hana::to<hana::tuple_tag>(hana::range_c<int, 0, N>);\n  auto inner = hana::fill(tuples, indices)...;\n  auto outer = hana::make_range(0_c, hana::length(tuples))...;\n\n  return tuple_cat_impl(\n      std::move(xs),\n      hana::to<hana::ext::std::integer_sequence_tag<std::size_t>>(inner),\n      hana::to<hana::ext::std::integer_sequence_tag<std::size_t>>(outer)\n  );\n}\n\nint main() { }\n\n\n// constexpr std::size_t N = sizeof...(Tuples);\n// hana::_tuple<Tuples&&...> xs{std::forward<Tuples>(tuples)...};\n// auto inner = hana::flatten(hana::zip.with(hana::fill, xs, hana::to<hana::Tuple>(hana::range_c<int, 0, N>)));\n// auto outer = flatten(tuple(to<Tuple>(range(0_c, length(tuples)))...));\n// return tuple_cat_impl<Res>(\n//     std::move(xs),\n//     to<ext::std::IntegerSequence<std::size_t>>(inner),\n//     to<ext::std::IntegerSequence<std::size_t>>(outer)\n// );\n", "meta": {"hexsha": "0f09aea8e191689344cebd6d585bcb21aef707fa", "size": 1782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_code/revisiting-the-tiny-mpl/tuple_cat_hana.cpp", "max_stars_repo_name": "ldionne/ldionne.github.io", "max_stars_repo_head_hexsha": "9391dd54f00bd61046d60dbfeab31b13e8803d43", "max_stars_repo_licenses": ["MIT"], "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/revisiting-the-tiny-mpl/tuple_cat_hana.cpp", "max_issues_repo_name": "ldionne/ldionne.github.io", "max_issues_repo_head_hexsha": "9391dd54f00bd61046d60dbfeab31b13e8803d43", "max_issues_repo_licenses": ["MIT"], "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/revisiting-the-tiny-mpl/tuple_cat_hana.cpp", "max_forks_repo_name": "ldionne/ldionne.github.io", "max_forks_repo_head_hexsha": "9391dd54f00bd61046d60dbfeab31b13e8803d43", "max_forks_repo_licenses": ["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.724137931, "max_line_length": 111, "alphanum_fraction": 0.6358024691, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5527838376839326}}
{"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": "#include <iostream>\r\n#include <vector>\r\n#include <math.h>\r\n#include <string>\r\n\r\n#include \"Input_Reader.h\"\r\n#include \"Materials.h\"\r\n#include \"Fem_Quadrature.h\"\r\n#include \"Quadrule_New.h\"\r\n#include \"Cell_Data.h\"\r\n#include \"Angular_Quadrature.h\"\r\n#include \"Time_Data.h\"\r\n#include \"Temperature_Data.h\"\r\n\r\n#include <Eigen/Dense>\r\n#include \"Diffusion_Matrix_Creator_Grey.h\"\r\n\r\n#include \"Dark_Arts_Exception.h\"\r\n\r\n/**\r\n  Goal of this unit test is to check source moment formation, and reaction matrix for SLXS Lobatto scheme\r\n  -This is a MMS problem with a spatially varying sigma_a, constant cv , zero sig_s\r\n*/ \r\n\r\nint main(int argc, char** argv)\r\n{\r\n  int val = 0;\r\n  const double tol = 1.0E-6;\r\n  \r\n  Input_Reader input_reader;    \r\n  try\r\n  {\r\n    input_reader.read_xml(argv[1]);\r\n  }\r\n  catch(const Dark_Arts_Exception& da_exception )\r\n  {\r\n    da_exception.message() ;\r\n    val = -1;\r\n  }       \r\n  \r\n  /// Initialize a Quadrule object to be able to get all of the quadrature we need\r\n  Quadrule_New quad_fun;  \r\n  Fem_Quadrature fem_quadrature( input_reader , quad_fun);  \r\n  Cell_Data cell_data( input_reader );  \r\n  Angular_Quadrature angular_quadrature( input_reader , quad_fun );    \r\n\r\n  const int n_dfem_p = fem_quadrature.get_number_of_interpolation_points();\r\n  const double sn_w = angular_quadrature.get_sum_w();\r\n  \r\n  /// Create a Materials object that contains all opacity, heat capacity, and source objects\r\n  Materials materials( input_reader, fem_quadrature , cell_data, angular_quadrature );  \r\n  Time_Data time_data(input_reader);\r\n  Temperature_Data t_old(fem_quadrature, input_reader, cell_data);  \r\n\r\n  Eigen::MatrixXd r_sig_a_reg1 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  Eigen::MatrixXd r_sig_a_reg2 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  \r\n  Eigen::MatrixXd r_sig_s_reg1 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  Eigen::MatrixXd r_sig_s_reg2 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  \r\n  Eigen::MatrixXd dimless_mass = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  Eigen::MatrixXd r_cv_1 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  Eigen::MatrixXd r_cv_2 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n \r\n  Eigen::MatrixXd r_sig_tau_1 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  Eigen::MatrixXd r_sig_tau_2 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  \r\n  Eigen::MatrixXd d_1 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  Eigen::MatrixXd d_2 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  \r\n  const double sig_a_1 = 0.7;\r\n  const double sig_a_2 = 0.9;\r\n  const double sig_s_1 = 1.0;\r\n  const double sig_s_2 = 0.2;\r\n  const double cv_1 = 1.0;\r\n  const double cv_2 = 1.2;\r\n  const double dx_1 = 4./3.;\r\n  const double dx_2 = 1./3.;\r\n  \r\n  const double w_1 = 1.;\r\n  const double w_2 = 1.;\r\n  \r\n  const double dt = time_data.get_dt_min();  \r\n  const double c = 1.0;\r\n  const double rk_a = 1.0;\r\n    \r\n  const double temp_1 = 0.5;\r\n  const double temp_2 = 0.4;\r\n  \r\n  dimless_mass(0,0) = w_1;\r\n  dimless_mass(1,1) = w_2;\r\n  \r\n  r_sig_a_reg1 = dx_1/2.*sig_a_1*dimless_mass;\r\n  r_sig_a_reg2 = dx_2/2.*sig_a_2*dimless_mass;  \r\n  \r\n  r_sig_s_reg1 = dx_1/2.*sig_s_1*dimless_mass;\r\n  r_sig_s_reg2 = dx_2/2.*sig_s_2*dimless_mass;\r\n  \r\n  r_cv_1 = dx_1/2.*cv_1*dimless_mass;\r\n  r_cv_2 = dx_2/2.*cv_2*dimless_mass;\r\n  \r\n  std::cout << \"r_sig_a_1: \\n\" << r_sig_a_reg1 << std::endl;\r\n  std::cout << \"r_sig_a_2: \\n\" << r_sig_a_reg2 << std::endl;\r\n  std::cout << \"r_sig_s_1: \\n\" << r_sig_s_reg1 << std::endl;\r\n  std::cout << \"r_sig_s_2: \\n\" << r_sig_s_reg2 << std::endl;\r\n  std::cout << \"r_cv_1: \\n\" << r_cv_1 << std::endl;\r\n  std::cout << \"r_cv_2: \\n\" << r_cv_2 << std::endl;\r\n  \r\n  r_sig_tau_1 = r_sig_a_reg1+r_sig_s_reg1+(1./(c*dt*1.0))*dx_1/2.*dimless_mass;\r\n  r_sig_tau_2 = r_sig_a_reg2+r_sig_s_reg2+(1./(c*dt*1.0))*dx_2/2.*dimless_mass;\r\n  \r\n  d_1(0,0) = 4.*pow(temp_1,3)/sn_w; d_1(1,1) = 4.*pow(temp_1,3)/sn_w;\r\n  d_2(0,0) = 4.*pow(temp_2,3)/sn_w; d_2(1,1) = 4.*pow(temp_2,3)/sn_w;\r\n \r\n  Eigen::MatrixXd r_pseudo_s_1 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  Eigen::MatrixXd r_pseudo_s_2 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  Eigen::MatrixXd r_pseudo_a_1 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  Eigen::MatrixXd r_pseudo_a_2 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  \r\n  int i = 0;\r\n  r_pseudo_s_1(i,i) = r_sig_a_reg1(i,i)*d_1(i,i)/( 1.+sn_w*dt*rk_a/r_cv_1(i,i)*r_sig_a_reg1(i,i)*d_1(i,i) )/r_cv_1(i,i)*r_sig_a_reg1(i,i) ;\r\n  i = 1;\r\n  r_pseudo_s_1(i,i) = r_sig_a_reg1(i,i)*d_1(i,i)/( 1.+sn_w*dt*rk_a/r_cv_1(i,i)*r_sig_a_reg1(i,i)*d_1(i,i) )/r_cv_1(i,i)*r_sig_a_reg1(i,i) ;\r\n  r_pseudo_s_1 *= sn_w*dt*rk_a;\r\n  r_pseudo_s_1 += r_sig_s_reg1;\r\n  \r\n  i=0;\r\n  r_pseudo_s_2(i,i) = r_sig_a_reg2(i,i)*d_2(i,i)/( 1.+sn_w*dt*rk_a/r_cv_2(i,i)*r_sig_a_reg2(i,i)*d_2(i,i) )/r_cv_2(i,i)*r_sig_a_reg2(i,i) ;\r\n  i = 1;\r\n  r_pseudo_s_2(i,i) = r_sig_a_reg2(i,i)*d_2(i,i)/( 1.+sn_w*dt*rk_a/r_cv_2(i,i)*r_sig_a_reg2(i,i)*d_2(i,i) )/r_cv_2(i,i)*r_sig_a_reg2(i,i) ;\r\n  r_pseudo_s_2 *= sn_w*dt*rk_a;\r\n  r_pseudo_s_2 += r_sig_s_reg2;\r\n  \r\n  r_pseudo_a_1 = r_sig_tau_1 - r_pseudo_s_1 ;\r\n  r_pseudo_a_2 = r_sig_tau_2 - r_pseudo_s_2 ;\r\n  \r\n  \r\n  Eigen::MatrixXd unitless_s_matrix = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n  Eigen::MatrixXd calculated_s_matrix_1 = unitless_s_matrix;\r\n  Eigen::MatrixXd calculated_s_matrix_2 = unitless_s_matrix;\r\n  Eigen::MatrixXd s_matrix_1 = unitless_s_matrix;\r\n  Eigen::MatrixXd s_matrix_2 = unitless_s_matrix;\r\n  unitless_s_matrix(0,0) = 0.5;\r\n  unitless_s_matrix(1,1) = 0.5;\r\n  unitless_s_matrix(0,1) = -0.5;\r\n  unitless_s_matrix(1,0) = -0.5;\r\n  \r\n  const double diff_co_1 = 1./(3.*(sig_a_1 + sig_s_1 + 1./(c*dt*rk_a)));\r\n  const double diff_co_2 = 1./(3.*(sig_a_2 + sig_s_2 + 1./(c*dt*rk_a)));\r\n  \r\n  std::cout << \"D_1 = \" << diff_co_1 << std::endl;\r\n  std::cout << \"D_2 = \" << diff_co_2 << std::endl;\r\n  \r\n  /**\r\n    \\f{eqnarray}{\r\n      \\frac{\\partial b_0}{\\partial s} &=& -\\frac{1}{2} \\\\\r\n      \\frac{\\partial b_1}{\\partial s} &=& \\frac{1}{2} \\\\\r\n      \\int_{x_{i-1/2}}^{x_{i+1/2}}{ \\frac{\\partial b_0}{\\partial x} \\frac{\\partial b_0}{\\partial x} ~dx} &=& \r\n        \\frac{2}{\\Delta x} \\frac{2}{\\Delta x} \\frac{\\Delta x}{2} \r\n        \\int_{-1}^1{ \\frac{\\partial b_0}{\\partial s} \\frac{\\partial b_0}{\\partial s}~ds} \\\\\r\n        &=& \\frac{4}{\\Delta x}\r\n    \\f}  \r\n  */\r\n  \r\n  s_matrix_1 = 2./dx_1*diff_co_1*unitless_s_matrix;\r\n  s_matrix_2 = 2./dx_2*diff_co_2*unitless_s_matrix;\r\n  \r\n  \r\n  try{\r\n    /// test matrix integrations\r\n    std::shared_ptr<V_Diffusion_Matrix_Creator> matrix_creator;\r\n    matrix_creator = std::make_shared<Diffusion_Matrix_Creator_Grey>\r\n      (fem_quadrature,materials,angular_quadrature,t_old, cell_data.get_total_number_of_cells(),input_reader );\r\n    \r\n    const double t_stage = time_data.get_t_start();\r\n    \r\n    double d_cm1_r , d_c_l, d_c_r , d_cp1_l;\r\n    \r\n    Eigen::MatrixXd calc_r_sig_a_1 = Eigen::MatrixXd::Zero(n_dfem_p,n_dfem_p);\r\n    Eigen::MatrixXd calc_r_sig_a_2 = calc_r_sig_a_1;\r\n    Eigen::MatrixXd calc_r_sig_s_1 = calc_r_sig_a_1;\r\n    Eigen::MatrixXd calc_r_sig_s_2 = calc_r_sig_a_1;\r\n    \r\n    matrix_creator->set_time_data(dt,t_stage,rk_a);\r\n    matrix_creator->set_cell_group_information(1,0,dx_1);\r\n    matrix_creator->calculate_pseudo_r_sig_a_and_pseudo_r_sig_s(calc_r_sig_a_1,calc_r_sig_s_1);\r\n    matrix_creator->calculate_d_dependent_quantities(d_cm1_r , d_c_l, d_c_r , d_cp1_l, calculated_s_matrix_1);\r\n    \r\n    matrix_creator->set_cell_group_information(4,0,dx_2);\r\n    matrix_creator->calculate_pseudo_r_sig_a_and_pseudo_r_sig_s(calc_r_sig_a_2,calc_r_sig_s_2);\r\n    matrix_creator->calculate_d_dependent_quantities(d_cm1_r , d_c_l, d_c_r , d_cp1_l, calculated_s_matrix_2);\r\n    \r\n    std::cout << \"Region 0\\n\"; \r\n    std::cout << \"Calculated Pseudo r_sig_a: \\n\" << calc_r_sig_a_1 << \"\\n Expected: \\n\" << r_pseudo_a_1 << std::endl;\r\n    std::cout << \"Calculated Pseudo r_sig_s: \\n\" << calc_r_sig_s_1 << \"\\n Expected: \\n\" << r_pseudo_s_1 << std::endl;\r\n    std::cout << \"Calculated S_matrix: \\n\" << calculated_s_matrix_1 << \"\\n Expected: \\n\" << s_matrix_1 << std::endl;\r\n    \r\n    std::cout << \"\\nRegion 1\\n\"; \r\n    std::cout << \"Calculated Pseudo r_sig_a: \\n\" << calc_r_sig_a_2 << \"\\n Expected: \\n\" << r_pseudo_a_2 << std::endl;\r\n    std::cout << \"Calculated Pseudo r_sig_s: \\n\" << calc_r_sig_s_2 << \"\\n Expected: \\n\" << r_pseudo_s_2 << std::endl;\r\n    std::cout << \"Calculated S_matrix: \\n\" << calculated_s_matrix_2 << \"\\n Expected: \\n\" << s_matrix_2 << std::endl;\r\n    \r\n    for(int i=0; i < n_dfem_p ; i++)\r\n    {\r\n      for(int j=0; j < n_dfem_p ; j++)\r\n      {\r\n        if( fabs(calc_r_sig_a_1(i,j) - r_pseudo_a_1(i,j) ) > tol)\r\n          throw Dark_Arts_Exception(MIP, \"Not calculating region 0 grey pseudo r_sig_a correctly\");\r\n          \r\n        if( fabs(calc_r_sig_s_1(i,j) - r_pseudo_s_1(i,j) ) > tol)\r\n          throw Dark_Arts_Exception(MIP, \"Not calculating region 0 grey pseudo r_sig_s correctly\");\r\n          \r\n        if( fabs(calc_r_sig_a_2(i,j) - r_pseudo_a_2(i,j) ) > tol)\r\n          throw Dark_Arts_Exception(MIP, \"Not calculating region 1 grey pseudo r_sig_a correctly\");\r\n          \r\n        if( fabs(calc_r_sig_s_2(i,j) - r_pseudo_s_2(i,j) ) > tol)\r\n          throw Dark_Arts_Exception(MIP, \"Not calculating region 1 grey pseudo r_sig_s correctly\");\r\n          \r\n        if( fabs(calculated_s_matrix_1(i,j) - s_matrix_1(i,j) ) > tol)\r\n          throw Dark_Arts_Exception(MIP, \"Not calculating region 1 grey pseudo S matrix correctly\");\r\n          \r\n        if( fabs(calculated_s_matrix_2(i,j) - s_matrix_2(i,j) ) > tol)\r\n          throw Dark_Arts_Exception(MIP, \"Not calculating region 2 grey pseudo S matrix correctly\");\r\n      }\r\n    }\r\n    \r\n    /// test edge diffusion coefficent evaluations\r\n    /// first test, interior of region 0 \r\n    \r\n    matrix_creator->set_cell_group_information(1,0,dx_1);\r\n    matrix_creator->calculate_d_dependent_quantities(d_cm1_r , d_c_l, d_c_r , d_cp1_l, calculated_s_matrix_2);\r\n    \r\n    std::cout << \"Interior of region 0 D coeff\\n\";\r\n    std::cout << \"Expected d_cm1_r: \" << diff_co_1 << \" Calculated: \" << d_cm1_r << std::endl;\r\n    std::cout << \"Expected d_c_l: \" << diff_co_1 << \" Calculated: \" << d_c_l << std::endl;\r\n    std::cout << \"Expected d_c_r: \" << diff_co_1 << \" Calculated: \" << d_c_r << std::endl;\r\n    std::cout << \"Expected d_cp1_l: \" << diff_co_1 << \" Calculated: \" << d_cp1_l << std::endl;    \r\n    if( fabs(d_cm1_r - diff_co_1) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c minus 1 right edge D\");\r\n      \r\n    if( fabs(d_c_l - diff_co_1) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c left edge D\");\r\n      \r\n    if( fabs(d_c_r - diff_co_1) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c right edge D\");\r\n      \r\n    if( fabs(d_cp1_l - diff_co_1) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c plus 1 left edge D\");\r\n    \r\n    \r\n    /// interior of region 1\r\n    matrix_creator->set_cell_group_information(4,0,dx_2);\r\n    matrix_creator->calculate_d_dependent_quantities(d_cm1_r , d_c_l, d_c_r , d_cp1_l, calculated_s_matrix_2);\r\n    std::cout << \"Interior of region 1 D coeff\\n\";\r\n    std::cout << \"Expected d_cm1_r: \" << diff_co_2 << \" Calculated: \" << d_cm1_r << std::endl;\r\n    std::cout << \"Expected d_c_l: \" << diff_co_2 << \" Calculated: \" << d_c_l << std::endl;\r\n    std::cout << \"Expected d_c_r: \" << diff_co_2 << \" Calculated: \" << d_c_r << std::endl;\r\n    std::cout << \"Expected d_cp1_l: \" << diff_co_2 << \" Calculated: \" << d_cp1_l << std::endl;    \r\n    if( fabs(d_cm1_r - diff_co_2) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c minus 1 right edge D\");\r\n      \r\n    if( fabs(d_c_l - diff_co_2) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c left edge D\");\r\n      \r\n    if( fabs(d_c_r - diff_co_2) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c right edge D\");\r\n      \r\n    if( fabs(d_cp1_l - diff_co_2) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c plus 1 left edge D\");\r\n      \r\n    \r\n    /// rightmost cell of region 0\r\n    matrix_creator->set_cell_group_information(2,0,dx_1);\r\n    matrix_creator->calculate_d_dependent_quantities(d_cm1_r , d_c_l, d_c_r , d_cp1_l, calculated_s_matrix_2);\r\n    std::cout << \"Righmost edge of region 0 D coeff\\n\";\r\n    std::cout << \"Expected d_cm1_r: \" << diff_co_1 << \" Calculated: \" << d_cm1_r << std::endl;\r\n    std::cout << \"Expected d_c_l: \" << diff_co_1 << \" Calculated: \" << d_c_l << std::endl;\r\n    std::cout << \"Expected d_c_r: \" << diff_co_1 << \" Calculated: \" << d_c_r << std::endl;\r\n    std::cout << \"Expected d_cp1_l: \" << diff_co_2 << \" Calculated: \" << d_cp1_l << std::endl;    \r\n    if( fabs(d_cm1_r - diff_co_1) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c minus 1 right edge D\");\r\n      \r\n    if( fabs(d_c_l - diff_co_1) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c left edge D\");\r\n      \r\n    if( fabs(d_c_r - diff_co_1) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c right edge D\");\r\n      \r\n    if( fabs(d_cp1_l - diff_co_2) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c plus 1 left edge D\");\r\n      \r\n    /// leftmost cell of region 1\r\n    matrix_creator->set_cell_group_information(3,0,dx_2);\r\n    matrix_creator->calculate_d_dependent_quantities(d_cm1_r , d_c_l, d_c_r , d_cp1_l, calculated_s_matrix_2);\r\n    std::cout << \"Leftmost cell of region 1 D coeff\\n\";\r\n    std::cout << \"Expected d_cm1_r: \" << diff_co_1 << \" Calculated: \" << d_cm1_r << std::endl;\r\n    std::cout << \"Expected d_c_l: \" << diff_co_2 << \" Calculated: \" << d_c_l << std::endl;\r\n    std::cout << \"Expected d_c_r: \" << diff_co_2 << \" Calculated: \" << d_c_r << std::endl;\r\n    std::cout << \"Expected d_cp1_l: \" << diff_co_2 << \" Calculated: \" << d_cp1_l << std::endl;    \r\n    if( fabs(d_cm1_r - diff_co_1) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c minus 1 right edge D\");\r\n      \r\n    if( fabs(d_c_l - diff_co_2) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c left edge D\");\r\n      \r\n    if( fabs(d_c_r - diff_co_2) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c right edge D\");\r\n      \r\n    if( fabs(d_cp1_l - diff_co_2) > tol )\r\n      throw Dark_Arts_Exception(MIP, \"Wrong cell c plus 1 left edge D\");\r\n      \r\n  }\r\n  catch(const Dark_Arts_Exception& da)\r\n  {\r\n    val = -1;\r\n    da.testing_message();\r\n  }\r\n  \r\n  return val;\r\n}\r\n", "meta": {"hexsha": "0b33c1e4a13b96c5aa0d04a4c543f9529fb353b5", "size": 14314, "ext": "cc", "lang": "C++", "max_stars_repo_path": "testing/mip/MIP_SLXS_Lobatto_Matrices.cc", "max_stars_repo_name": "pgmaginot/DARK_ARTS", "max_stars_repo_head_hexsha": "f04b0a30dcac911ef06fe0916921020826f5c42b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/mip/MIP_SLXS_Lobatto_Matrices.cc", "max_issues_repo_name": "pgmaginot/DARK_ARTS", "max_issues_repo_head_hexsha": "f04b0a30dcac911ef06fe0916921020826f5c42b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/mip/MIP_SLXS_Lobatto_Matrices.cc", "max_forks_repo_name": "pgmaginot/DARK_ARTS", "max_forks_repo_head_hexsha": "f04b0a30dcac911ef06fe0916921020826f5c42b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5919003115, "max_line_length": 140, "alphanum_fraction": 0.6474081319, "num_tokens": 4791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5527838214896723}}
{"text": "/* boost random/inversive_congruential.hpp header file\r\n *\r\n * Copyright Jens Maurer 2000-2001\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * See http://www.boost.org for most recent version including documentation.\r\n *\r\n * $Id$\r\n *\r\n * Revision history\r\n *  2001-02-18  moved to individual header files\r\n */\r\n\r\n#ifndef BOOST_RANDOM_INVERSIVE_CONGRUENTIAL_HPP\r\n#define BOOST_RANDOM_INVERSIVE_CONGRUENTIAL_HPP\r\n\r\n#include <iosfwd>\r\n#include <stdexcept>\r\n#include <boost/assert.hpp>\r\n#include <boost/config.hpp>\r\n#include <boost/cstdint.hpp>\r\n#include <boost/integer/static_log2.hpp>\r\n#include <boost/random/detail/config.hpp>\r\n#include <boost/random/detail/const_mod.hpp>\r\n#include <boost/random/detail/seed.hpp>\r\n#include <boost/random/detail/operators.hpp>\r\n#include <boost/random/detail/seed_impl.hpp>\r\n\r\n#include <boost/random/detail/disable_warnings.hpp>\r\n\r\nnamespace boost {\r\nnamespace random {\r\n\r\n// Eichenauer and Lehn 1986\r\n/**\r\n * Instantiations of class template @c inversive_congruential_engine model a\r\n * \\pseudo_random_number_generator. It uses the inversive congruential\r\n * algorithm (ICG) described in\r\n *\r\n *  @blockquote\r\n *  \"Inversive pseudorandom number generators: concepts, results and links\",\r\n *  Peter Hellekalek, In: \"Proceedings of the 1995 Winter Simulation\r\n *  Conference\", C. Alexopoulos, K. Kang, W.R. Lilegdon, and D. Goldsman\r\n *  (editors), 1995, pp. 255-262. ftp://random.mat.sbg.ac.at/pub/data/wsc95.ps\r\n *  @endblockquote\r\n *\r\n * The output sequence is defined by x(n+1) = (a*inv(x(n)) - b) (mod p),\r\n * where x(0), a, b, and the prime number p are parameters of the generator.\r\n * The expression inv(k) denotes the multiplicative inverse of k in the\r\n * field of integer numbers modulo p, with inv(0) := 0.\r\n *\r\n * The template parameter IntType shall denote a signed integral type large\r\n * enough to hold p; a, b, and p are the parameters of the generators. The\r\n * template parameter val is the validation value checked by validation.\r\n *\r\n * @xmlnote\r\n * The implementation currently uses the Euclidian Algorithm to compute\r\n * the multiplicative inverse. Therefore, the inversive generators are about\r\n * 10-20 times slower than the others (see section\"performance\"). However,\r\n * the paper talks of only 3x slowdown, so the Euclidian Algorithm is probably\r\n * not optimal for calculating the multiplicative inverse.\r\n * @endxmlnote\r\n */\r\ntemplate<class IntType, IntType a, IntType b, IntType p>\r\nclass inversive_congruential_engine\r\n{\r\npublic:\r\n    typedef IntType result_type;\r\n    BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);\r\n\r\n    BOOST_STATIC_CONSTANT(result_type, multiplier = a);\r\n    BOOST_STATIC_CONSTANT(result_type, increment = b);\r\n    BOOST_STATIC_CONSTANT(result_type, modulus = p);\r\n    BOOST_STATIC_CONSTANT(IntType, default_seed = 1);\r\n\r\n    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () { return b == 0 ? 1 : 0; }\r\n    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () { return p-1; }\r\n    \r\n    /**\r\n     * Constructs an @c inversive_congruential_engine, seeding it with\r\n     * the default seed.\r\n     */\r\n    inversive_congruential_engine() { seed(); }\r\n\r\n    /**\r\n     * Constructs an @c inversive_congruential_engine, seeding it with @c x0.\r\n     */\r\n    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(inversive_congruential_engine,\r\n                                               IntType, x0)\r\n    { seed(x0); }\r\n    \r\n    /**\r\n     * Constructs an @c inversive_congruential_engine, seeding it with values\r\n     * produced by a call to @c seq.generate().\r\n     */\r\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(inversive_congruential_engine,\r\n                                             SeedSeq, seq)\r\n    { seed(seq); }\r\n    \r\n    /**\r\n     * Constructs an @c inversive_congruential_engine, seeds it\r\n     * with values taken from the itrator range [first, last),\r\n     * and adjusts first to point to the element after the last one\r\n     * used.  If there are not enough elements, throws @c std::invalid_argument.\r\n     *\r\n     * first and last must be input iterators.\r\n     */\r\n    template<class It> inversive_congruential_engine(It& first, It last)\r\n    { seed(first, last); }\r\n\r\n    /**\r\n     * Calls seed(default_seed)\r\n     */\r\n    void seed() { seed(default_seed); }\r\n  \r\n    /**\r\n     * If c mod m is zero and x0 mod m is zero, changes the current value of\r\n     * the generator to 1. Otherwise, changes it to x0 mod m. If c is zero,\r\n     * distinct seeds in the range [1,m) will leave the generator in distinct\r\n     * states. If c is not zero, the range is [0,m).\r\n     */\r\n    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(inversive_congruential_engine, IntType, x0)\r\n    {\r\n        // wrap _x if it doesn't fit in the destination\r\n        if(modulus == 0) {\r\n            _value = x0;\r\n        } else {\r\n            _value = x0 % modulus;\r\n        }\r\n        // handle negative seeds\r\n        if(_value <= 0 && _value != 0) {\r\n            _value += modulus;\r\n        }\r\n        // adjust to the correct range\r\n        if(increment == 0 && _value == 0) {\r\n            _value = 1;\r\n        }\r\n        BOOST_ASSERT(_value >= (min)());\r\n        BOOST_ASSERT(_value <= (max)());\r\n    }\r\n\r\n    /**\r\n     * Seeds an @c inversive_congruential_engine using values from a SeedSeq.\r\n     */\r\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(inversive_congruential_engine, SeedSeq, seq)\r\n    { seed(detail::seed_one_int<IntType, modulus>(seq)); }\r\n    \r\n    /**\r\n     * seeds an @c inversive_congruential_engine with values taken\r\n     * from the itrator range [first, last) and adjusts @c first to\r\n     * point to the element after the last one used.  If there are\r\n     * not enough elements, throws @c std::invalid_argument.\r\n     *\r\n     * @c first and @c last must be input iterators.\r\n     */\r\n    template<class It> void seed(It& first, It last)\r\n    { seed(detail::get_one_int<IntType, modulus>(first, last)); }\r\n\r\n    /** Returns the next output of the generator. */\r\n    IntType operator()()\r\n    {\r\n        typedef const_mod<IntType, p> do_mod;\r\n        _value = do_mod::mult_add(a, do_mod::invert(_value), b);\r\n        return _value;\r\n    }\r\n  \r\n    /** Fills a range with random values */\r\n    template<class Iter>\r\n    void generate(Iter first, Iter last)\r\n    { detail::generate_from_int(*this, first, last); }\r\n\r\n    /** Advances the state of the generator by @c z. */\r\n    void discard(boost::uintmax_t z)\r\n    {\r\n        for(boost::uintmax_t j = 0; j < z; ++j) {\r\n            (*this)();\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Writes the textual representation of the generator to a @c std::ostream.\r\n     */\r\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, inversive_congruential_engine, x)\r\n    {\r\n        os << x._value;\r\n        return os;\r\n    }\r\n\r\n    /**\r\n     * Reads the textual representation of the generator from a @c std::istream.\r\n     */\r\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, inversive_congruential_engine, x)\r\n    {\r\n        is >> x._value;\r\n        return is;\r\n    }\r\n\r\n    /**\r\n     * Returns true if the two generators will produce identical\r\n     * sequences of outputs.\r\n     */\r\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(inversive_congruential_engine, x, y)\r\n    { return x._value == y._value; }\r\n\r\n    /**\r\n     * Returns true if the two generators will produce different\r\n     * sequences of outputs.\r\n     */\r\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(inversive_congruential_engine)\r\n\r\nprivate:\r\n    IntType _value;\r\n};\r\n\r\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\r\n//  A definition is required even for integral static constants\r\ntemplate<class IntType, IntType a, IntType b, IntType p>\r\nconst bool inversive_congruential_engine<IntType, a, b, p>::has_fixed_range;\r\ntemplate<class IntType, IntType a, IntType b, IntType p>\r\nconst typename inversive_congruential_engine<IntType, a, b, p>::result_type inversive_congruential_engine<IntType, a, b, p>::multiplier;\r\ntemplate<class IntType, IntType a, IntType b, IntType p>\r\nconst typename inversive_congruential_engine<IntType, a, b, p>::result_type inversive_congruential_engine<IntType, a, b, p>::increment;\r\ntemplate<class IntType, IntType a, IntType b, IntType p>\r\nconst typename inversive_congruential_engine<IntType, a, b, p>::result_type inversive_congruential_engine<IntType, a, b, p>::modulus;\r\ntemplate<class IntType, IntType a, IntType b, IntType p>\r\nconst typename inversive_congruential_engine<IntType, a, b, p>::result_type inversive_congruential_engine<IntType, a, b, p>::default_seed;\r\n#endif\r\n\r\n/// \\cond show_deprecated\r\n\r\n// provided for backwards compatibility\r\ntemplate<class IntType, IntType a, IntType b, IntType p, IntType val = 0>\r\nclass inversive_congruential : public inversive_congruential_engine<IntType, a, b, p>\r\n{\r\n    typedef inversive_congruential_engine<IntType, a, b, p> base_type;\r\npublic:\r\n    inversive_congruential(IntType x0 = 1) : base_type(x0) {}\r\n    template<class It>\r\n    inversive_congruential(It& first, It last) : base_type(first, last) {}\r\n};\r\n\r\n/// \\endcond\r\n\r\n/**\r\n * The specialization hellekalek1995 was suggested in\r\n *\r\n *  @blockquote\r\n *  \"Inversive pseudorandom number generators: concepts, results and links\",\r\n *  Peter Hellekalek, In: \"Proceedings of the 1995 Winter Simulation\r\n *  Conference\", C. Alexopoulos, K. Kang, W.R. Lilegdon, and D. Goldsman\r\n *  (editors), 1995, pp. 255-262. ftp://random.mat.sbg.ac.at/pub/data/wsc95.ps\r\n *  @endblockquote\r\n */\r\ntypedef inversive_congruential_engine<uint32_t, 9102, 2147483647-36884165,\r\n  2147483647> hellekalek1995;\r\n\r\n} // namespace random\r\n\r\nusing random::hellekalek1995;\r\n\r\n} // namespace boost\r\n\r\n#include <boost/random/detail/enable_warnings.hpp>\r\n\r\n#endif // BOOST_RANDOM_INVERSIVE_CONGRUENTIAL_HPP\r\n", "meta": {"hexsha": "edbe03b995535f17f1048b4a2840a1a69d2e13b9", "size": 9817, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/random/inversive_congruential.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/random/inversive_congruential.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/random/inversive_congruential.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": 36.6305970149, "max_line_length": 139, "alphanum_fraction": 0.6737292452, "num_tokens": 2491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5527838205686494}}
{"text": "#pragma once\n\n#include <Eigen/Geometry>\n\n#include \"geometry.hpp\"\n\nclass Quaternion {\npublic:\n  Quaternion() { eigenQuaternion_ = Eigen::Quaternion<float>::Identity(); }\n\n  Quaternion(const Eigen::Quaternion<float> &initialQuaternion) {\n    eigenQuaternion_ = initialQuaternion;\n  }\n\n  // note: expected euler angle format is: [z_axis_angle, y_axis_angle,\n  // x_axis_angle]\n  Quaternion(const std::array<float, 3> &eulerAngle) {\n    eigenQuaternion_ = Eigen::Quaternion<float>::Identity();\n\n    Eigen::Quaternion<float> zAxisRotation(\n        cos(degreesToRadians(eulerAngle[0]) / 2), 0.0f, 0.0f,\n        sin(degreesToRadians(eulerAngle[0]) / 2));\n    Eigen::Quaternion<float> yAxisRotation(\n        cos(degreesToRadians(eulerAngle[1]) / 2), 0.0f,\n        sin(degreesToRadians(eulerAngle[1]) / 2), 0.0f);\n    Eigen::Quaternion<float> xAxisRotation(\n        cos(degreesToRadians(eulerAngle[2]) / 2),\n        sin(degreesToRadians(eulerAngle[2]) / 2), 0.0f, 0.0f);\n\n    eigenQuaternion_ =\n        zAxisRotation * yAxisRotation * xAxisRotation * eigenQuaternion_;\n    eigenQuaternion_.normalize();\n  }\n\n  // CC\n  Quaternion(const Quaternion &otherQuaterion) {\n    eigenQuaternion_ = otherQuaterion.eigenQuaternion_;\n  }\n\n  // AO\n  Quaternion &operator=(const Quaternion &otherQuaterion) {\n    eigenQuaternion_ = otherQuaterion.eigenQuaternion_;\n  }\n\n  Eigen::Quaternion<float> getEigenQuaternion() const {\n    return eigenQuaternion_;\n  }\n\nprivate:\n  Eigen::Quaternion<float> eigenQuaternion_;\n};\n", "meta": {"hexsha": "db8996016479097bd20921c25701c1092d946c2d", "size": 1493, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Animator/inc/Quaternion.hpp", "max_stars_repo_name": "adlawren/Computer-Graphics-Exercises", "max_stars_repo_head_hexsha": "423630715416105632e624ea78b5a574eb80323e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Animator/inc/Quaternion.hpp", "max_issues_repo_name": "adlawren/Computer-Graphics-Exercises", "max_issues_repo_head_hexsha": "423630715416105632e624ea78b5a574eb80323e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Animator/inc/Quaternion.hpp", "max_forks_repo_name": "adlawren/Computer-Graphics-Exercises", "max_forks_repo_head_hexsha": "423630715416105632e624ea78b5a574eb80323e", "max_forks_repo_licenses": ["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.7115384615, "max_line_length": 75, "alphanum_fraction": 0.7006028131, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5527838151705627}}
{"text": "#include <stdio.h>\n#include <stdint.h>\n#include <inttypes.h>\n#include <ctype.h>\n#include <unistd.h>\n\n#include <opencv2/opencv.hpp>\n\n#include <AprilTags/apriltag.h>\n#include <AprilTags/common/image_u8.h>\n#include <AprilTags/tag36h11.h>\n#include <AprilTags/common/zarray.h>\n#include <AprilTags/common/getopt.h>\n\n#include <drc_utils/LcmWrapper.hpp>\n#include <drc_utils/BotWrapper.hpp>\n#include <lcm/lcm-cpp.hpp>\n\n#include <lcmtypes/bot_core.hpp>\n#include <lcmtypes/bot_core/images_t.hpp>\n#include <lcmtypes/bot_core/image_t.hpp>\n\n#include <bot_core/camtrans.h>\n#include <bot_param/param_util.h>\n#include <bot_frames_cpp/bot_frames_cpp.hpp>\n\n#include <vector>\n#include <iostream>\n\n#include <Eigen/Dense>\n\nstruct TagMatch {\n    int id; \n    cv::Point2d p0, p1, p2, p3;\n    Eigen::Matrix3d H;\n};\n\nEigen::Isometry3d getRelativeTransform(TagMatch const& match, Eigen::Matrix3d const & K, double tag_size) \n{\n  std::vector<cv::Point3f> objPts;\n  std::vector<cv::Point2f> imgPts;\n  double s = tag_size/2.;\n  objPts.push_back(cv::Point3f(-s,-s, 0));\n  objPts.push_back(cv::Point3f( s,-s, 0));\n  objPts.push_back(cv::Point3f( s, s, 0));\n  objPts.push_back(cv::Point3f(-s, s, 0));\n\n\n  imgPts.push_back(match.p0);\n  imgPts.push_back(match.p1);\n  imgPts.push_back(match.p2);\n  imgPts.push_back(match.p3);\n\n  cv::Mat rvec, tvec;\n  cv::Matx33f cameraMatrix(\n                           K(0,0), 0, K(0,2),\n                           0, K(1,1), K(1,2),\n                           0,  0,  1);\n\n  cv::Vec4f distParam(0,0,0,0); \n  cv::solvePnP(objPts, imgPts, cameraMatrix, distParam, rvec, tvec);\n  cv::Matx33d r;\n  cv::Rodrigues(rvec, r);\n  Eigen::Matrix3d wRo;\n  wRo << r(0,0), r(0,1), r(0,2), r(1,0), r(1,1), r(1,2), r(2,0), r(2,1), r(2,2);\n\n  Eigen::Isometry3d T; \n  T.linear() = wRo;\n  T.translation() << tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2);\n  return T;\n}\n\n\nbot_core::rigid_transform_t encodeLCMFrame(Eigen::Isometry3d const & frame) \n{\n    Eigen::Vector3d t(frame.translation());\n    Eigen::Quaterniond r(frame.rotation());\n\n    bot_core::rigid_transform_t msg;\n    msg.quat[0] = r.w();\n    msg.quat[1] = r.x();\n    msg.quat[2] = r.y();\n    msg.quat[3] = r.z();\n\n    msg.trans[0] = t[0];\n    msg.trans[1] = t[1];\n    msg.trans[2] = t[2];\n\n    return msg;\n}\n\n\nclass AprilTagDetector {\n    public:\n    AprilTagDetector(getopt_t *options) : getopt(options) {\n        tf = tag36h11_create();\n        tf->black_border = getopt_get_int(options, \"border\");\n        td = apriltag_detector_create();\n        apriltag_detector_add_family(td, tf);\n\n        td->quad_decimate = getopt_get_double(getopt, \"decimate\");\n        td->quad_sigma = getopt_get_double(getopt, \"blur\");\n        td->nthreads = getopt_get_int(getopt, \"threads\");\n        td->debug = getopt_get_bool(getopt, \"debug\");\n        td->refine_edges = getopt_get_bool(getopt, \"refine-edges\");\n        td->refine_decode = getopt_get_bool(getopt, \"refine-decode\");\n        td->refine_pose = getopt_get_bool(getopt, \"refine-pose\");\n\n        quiet = getopt_get_bool(getopt, \"quiet\");\n        tag_size = getopt_get_double(getopt, \"size\");\n    }\n\n    ~AprilTagDetector() {\n\n        apriltag_detector_destroy(td);\n        tag36h11_destroy(tf);\n    }\n\n    std::vector<TagMatch> detectTags(image_u8_t *im) {\n\n        const int hamm_hist_max = 10;\n\n        int hamm_hist[hamm_hist_max];\n        memset(hamm_hist, 0, sizeof(hamm_hist));\n        zarray_t *detections = apriltag_detector_detect(td, im);\n\n        std::vector<TagMatch> tag_matches;\n        for (int i = 0; i < zarray_size(detections); i++) {\n            apriltag_detection_t *det;\n            zarray_get(detections, i, &det);\n\n            if (!quiet)\n                printf(\"detection %3d: id (%2dx%2d)-%-4d, hamming %d, goodness %8.3f, margin %8.3f\\n\",\n                       i, det->family->d*det->family->d, det->family->h, det->id, det->hamming, det->goodness, det->decision_margin);\n\n            for (int x = 0; x < 3 ; x++) {\n                image_u8_draw_line(im, det->p[x][0], det->p[x][1], det->p[x+1][0], det->p[x+1][1], 255, 10);\n            }\n            TagMatch tag_match;\n            tag_match.id = det->family->d*det->family->d;\n            tag_match.p0 = cv::Point2d(det->p[0][0], det->p[0][1]);\n            tag_match.p1 = cv::Point2d(det->p[1][0], det->p[1][1]);\n            tag_match.p2 = cv::Point2d(det->p[2][0], det->p[2][1]);\n            tag_match.p3 = cv::Point2d(det->p[3][0], det->p[3][1]);\n\n            Eigen::Map<Eigen::Matrix3d> H_map(det->H->data);\n            tag_match.H = H_map.transpose();\n            tag_matches.push_back(tag_match);\n            hamm_hist[det->hamming]++;\n        }\n\n        apriltag_detections_destroy(detections);\n\n        if (!quiet) {\n            timeprofile_display(td->tp);\n            printf(\"nedges: %d, nsegments: %d, nquads: %d\\n\", td->nedges, td->nsegments, td->nquads);\n            printf(\"Hamming histogram: \");\n            for (int i = 0; i < hamm_hist_max; i++)\n                printf(\"%5d\", hamm_hist[i]);\n            printf(\"%12.3f\", timeprofile_total_utime(td->tp) / 1.0E3);\n            printf(\"\\n\");\n        }\n        \n        return tag_matches;\n    }\n    \n    double getTagSize() const {\n        return tag_size;\n    }\n\n    private:\n    int quiet;\n    double tag_size;\n    apriltag_family_t *tf;\n    apriltag_detector_t *td;\n    getopt_t *getopt;\n};\n\n\nclass CameraListener {\n    public:\n\n    void setDetector(AprilTagDetector* detector) {\n        mDetector = detector;\n    }\n\n    bool setup(bool show_window) {\n        mBotWrapper.reset(new drc::BotWrapper());\n\n        while (!mBotWrapper->getBotParam()) {\n            std::cout << \"Re-trying ... \" << std::endl;\n            mBotWrapper->setDefaults();\n        }\n        \n\n        mLcmWrapper.reset(new drc::LcmWrapper(mBotWrapper->getLcm()));\n        mLcmWrapper->get()->subscribe(\"CAMERA\", &CameraListener::onCamera, this);\n\n        mCamTransLeft = bot_param_get_new_camtrans(mBotWrapper->getBotParam(),\"CAMERA_LEFT\");\n        \n        K = Eigen::Matrix3d::Identity();\n\n        K(0,0) = bot_camtrans_get_focal_length_x(mCamTransLeft);\n        K(1,1) = bot_camtrans_get_focal_length_y(mCamTransLeft);\n        K(0,2) = bot_camtrans_get_principal_x(mCamTransLeft);\n        K(1,2) = bot_camtrans_get_principal_y(mCamTransLeft);\n\n        mShowWindow = show_window;\n        return true;\n    }  \n    \n    void start() {\n        mLcmWrapper->startHandleThread(true);\n    }\n\n    void onCamera(const lcm::ReceiveBuffer* buffer, const std::string& channel,\n                const bot_core::images_t* msg) {\n        cv::Mat image;\n        decodeImage(msg, image);\n        image_u8_t *image_u8 = fromCvMat(image);\n        \n        std::vector<TagMatch> tags = mDetector->detectTags(image_u8);\n        cv::cvtColor(image, image, CV_GRAY2RGB);\n        for (int i = 0; i < tags.size(); i++) { \n\n            if (mShowWindow) {\n                cv::line(image, tags[i].p0, tags[i].p1, cv::Scalar(255,0,0), 2, CV_AA);\n                cv::line(image, tags[i].p1, tags[i].p2, cv::Scalar(0,255,0), 2, CV_AA);\n                cv::line(image, tags[i].p2, tags[i].p3, cv::Scalar(0,0,255), 2, CV_AA);\n                cv::line(image, tags[i].p3, tags[i].p0, cv::Scalar(0,0,255), 2, CV_AA);\n\n                Eigen::Vector3d x_axis(2,0,1);\n                Eigen::Vector3d y_axis(0,2,1);\n                Eigen::Vector3d origin(0,0,1);\n\n                Eigen::Vector3d px = tags[i].H * x_axis;\n                Eigen::Vector3d py = tags[i].H * y_axis;\n                Eigen::Vector3d o  = tags[i].H * origin;\n\n                px/= px[2];\n                py/= py[2];\n                o/= o[2];\n\n                cv::line(image, cv::Point2d(o[0], o[1]), cv::Point2d(px[0], px[1]), cv::Scalar(255,0,255), 1, CV_AA);\n                cv::line(image, cv::Point2d(o[0], o[1]), cv::Point2d(py[0], py[1]), cv::Scalar(255,255,0), 1, CV_AA);\n            }\n\n            Eigen::Isometry3d tag_to_camera = getRelativeTransform(tags[i], K, mDetector->getTagSize());\n            bot_core::rigid_transform_t tag_to_camera_msg = encodeLCMFrame(tag_to_camera);\n            tag_to_camera_msg.utime = msg->utime;\n            mLcmWrapper->get()->publish(\"APRIL_TAG_TO_CAMERA_LEFT\", &tag_to_camera_msg);\n            break;\n            \n        }\n        if (mShowWindow) {\n            cv::imshow(\"detections\", image);\n            cv::waitKey(1);\n        }\n        \n        image_u8_destroy(image_u8);\n    }\n\n    void decodeImage(const bot_core::images_t* msg, cv::Mat & decoded_image) {\n        bot_core::image_t* leftImage = NULL;\n        for (int i = 0; i < msg->n_images; ++i) {\n          if (msg->image_types[i] == bot_core::images_t::LEFT) {\n            leftImage = (bot_core::image_t*)(&msg->images[i]);\n            decoded_image = leftImage->pixelformat == leftImage->PIXEL_FORMAT_MJPEG ?\n                cv::imdecode(cv::Mat(leftImage->data), -1) :\n                cv::Mat(leftImage->height, leftImage->width, CV_8UC1, leftImage->data.data());\n                if (decoded_image.channels() > 1) {\n                    cv::cvtColor(decoded_image, decoded_image, CV_RGB2GRAY);\n                }\n                break;\n          }\n        }\n    }\n    \n    image_u8_t *fromCvMat(const cv::Mat & img) { \n        image_u8_t *image_u8 = image_u8_create_alignment(img.cols, img.rows, img.step);\n        int size = img.total() * img.elemSize();\n        memcpy(image_u8->buf, img.data, size * sizeof(uint8_t));\n        return image_u8;\n    }\n\n    private:\n    bool mShowWindow;\n    AprilTagDetector *mDetector;\n    drc::LcmWrapper::Ptr mLcmWrapper;\n    drc::BotWrapper::Ptr mBotWrapper;\n    BotCamTrans* mCamTransLeft;\n    Eigen::Matrix3d K;\n};\n\n\n\nint main(int argc, char *argv[])\n{\n    getopt_t *getopt = getopt_create();\n\n    getopt_add_bool(getopt, 'h', \"help\", 0, \"Show this help\");\n    getopt_add_bool(getopt, 'd', \"debug\", 0, \"Enable debugging output (slow)\");\n    getopt_add_bool(getopt, 'w', \"window\", 1, \"Show the detected tags in a window\");\n    getopt_add_bool(getopt, 'q', \"quiet\", 0, \"Reduce output\");\n    getopt_add_int(getopt, '\\0', \"border\", \"1\", \"Set tag family border size\");\n    getopt_add_int(getopt, 't', \"threads\", \"4\", \"Use this many CPU threads\");\n    getopt_add_double(getopt, 'x', \"decimate\", \"1.0\", \"Decimate input image by this factor\");\n    getopt_add_double(getopt, 'b', \"blur\", \"0.0\", \"Apply low-pass blur to input\");\n    getopt_add_bool(getopt, '0', \"refine-edges\", 1, \"Spend more time trying to align edges of tags\");\n    getopt_add_bool(getopt, '1', \"refine-decode\", 0, \"Spend more time trying to decode tags\");\n    getopt_add_bool(getopt, '2', \"refine-pose\", 0, \"Spend more time trying to precisely localize tags\");\n    getopt_add_double(getopt, 's', \"size\", \"0.1735\", \"Physical side-length of the tag (meters)\");\n    \n\n    if (!getopt_parse(getopt, argc, argv, 1) || getopt_get_bool(getopt, \"help\")) {\n        printf(\"Usage: %s [options]\\n\", argv[0]);\n        getopt_do_usage(getopt);\n        exit(0);\n    }  \n\n    AprilTagDetector tag_detector(getopt);\n    CameraListener camera_listener;\n\n    if (camera_listener.setup(getopt_get_bool(getopt, \"window\"))) {\n        camera_listener.setDetector(&tag_detector);\n        camera_listener.start();\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "7ec38e555882a90a23f152d88c1f1dffb0c8105a", "size": 11179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/perception/car-tags/src/car-tags-driver.cpp", "max_stars_repo_name": "liangfok/oh-distro", "max_stars_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T21:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T17:57:46.000Z", "max_issues_repo_path": "software/perception/car-tags/src/car-tags-driver.cpp", "max_issues_repo_name": "liangfok/oh-distro", "max_issues_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2016-01-16T18:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-24T15:16:28.000Z", "max_forks_repo_path": "software/perception/car-tags/src/car-tags-driver.cpp", "max_forks_repo_name": "liangfok/oh-distro", "max_forks_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2016-01-14T21:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:10:39.000Z", "avg_line_length": 33.7734138973, "max_line_length": 133, "alphanum_fraction": 0.5888719921, "num_tokens": 3298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219505, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5527838151705627}}
{"text": "#define BOOST_TEST_MODULE \"test_harmonic_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <test/util/check_potential.hpp>\n#include <mjolnir/forcefield/local/HarmonicPotential.hpp>\n\nBOOST_AUTO_TEST_CASE(Harmonic_double)\n{\n    using real_type = double;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-6;\n    constexpr real_type tol = 1e-6;\n\n    const real_type k  = 1.0;\n    const real_type r0 = 5.0;\n\n    mjolnir::HarmonicPotential<real_type> harmonic(k, r0);\n\n    const real_type x_min = 0.5 * r0;\n    const real_type x_max = 1.5 * r0;\n\n    mjolnir::test::check_potential(harmonic, x_min, x_max, tol, h, N);\n}\n\nBOOST_AUTO_TEST_CASE(Harmonic_float)\n{\n    namespace test = mjolnir::test;\n    using real_type = float;\n    constexpr std::size_t N = 100;\n    constexpr real_type   h = 1e-3f;\n    constexpr real_type tol = 1e-3f;\n\n    const real_type k  = 1.0f;\n    const real_type r0 = 5.0f;\n\n    mjolnir::HarmonicPotential<real_type> harmonic(k, r0);\n\n    const real_type x_min = 0.5 * r0;\n    const real_type x_max = 1.5 * r0;\n\n    mjolnir::test::check_potential(harmonic, x_min, x_max, tol, h, N);\n}\n", "meta": {"hexsha": "2df17fbb9dd2cef98b6cf7fd8d76afbe8512cd0d", "size": 1213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_harmonic_potential.cpp", "max_stars_repo_name": "ToruNiina/Mjolnir", "max_stars_repo_head_hexsha": "44435dd3afc12f5c8ea27a66d7ab282df3e588ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-01T08:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-25T15:47:51.000Z", "max_issues_repo_path": "test/core/test_harmonic_potential.cpp", "max_issues_repo_name": "Mjolnir-MD/Mjolnir", "max_issues_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T08:11:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T08:26:36.000Z", "max_forks_repo_path": "test/core/test_harmonic_potential.cpp", "max_forks_repo_name": "Mjolnir-MD/Mjolnir", "max_forks_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-01-13T11:03:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T11:38:00.000Z", "avg_line_length": 25.2708333333, "max_line_length": 70, "alphanum_fraction": 0.6974443528, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5527838147100508}}
{"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": "// demo from:\n//      https://stackoverflow.com/questions/47653386/how-to-use-boostgeometryrtree-with-glmvec3-as-a-custom-point-type\n#include <boost/geometry.hpp>\n#include <boost/geometry/index/rtree.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\nnamespace glm\n{\n    struct vec3 {\n        double x, y, z;\n        vec3(double x_, double y_, double z_) { x = x_; y = y_; z = z_; }\n    };\n}\n\nBOOST_GEOMETRY_REGISTER_POINT_3D(glm::vec3, double, bg::cs::cartesian, x, y, z)\n\n#include <iostream>\nint main() {\n    using IndexedPoint = std::pair<glm::vec3, uint32_t>;\n    using RTree = boost::geometry::index::rtree<IndexedPoint, boost::geometry::index::rstar<8>>;\n\n    RTree rtree;\n    rtree.insert({glm::vec3(1,1,1), 1});\n    rtree.insert({glm::vec3(2,2,2), 2});\n    rtree.insert({glm::vec3(3,3,3), 3});\n    rtree.insert({glm::vec3(4,4,4), 4});\n\n    auto q = bgi::nearest(glm::vec3(2.9, 2.9, 2.9), 99);\n\n    auto it = rtree.qbegin(q);\n    auto p = it->first;\n    std::cout << \"Nearest: # \" << it->second << \" (\" << p.x << \", \" << p.y << \" \" << p.z << \")\\n\";\n}\n", "meta": {"hexsha": "fca7b911214a02b3e9e1eaaf4bab0515b5da30a0", "size": 1187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snippets/boost-rtree.cpp", "max_stars_repo_name": "district10/snippet-manager", "max_stars_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-04T09:28:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-19T17:46:34.000Z", "max_issues_repo_path": "snippets/boost-rtree.cpp", "max_issues_repo_name": "district10/snippet-manager", "max_issues_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snippets/boost-rtree.cpp", "max_forks_repo_name": "district10/snippet-manager", "max_forks_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-31T04:14:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-02T01:22:39.000Z", "avg_line_length": 31.2368421053, "max_line_length": 118, "alphanum_fraction": 0.6225779275, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5527818203107592}}
{"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": "///////////////////////////////////////////////////////////////\n//  Copyright 2011 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/debug_adaptor.hpp>\n#include <iostream>\n\nvoid t1()\n{\n   //[debug_adaptor_eg\n   //=#include <boost/multiprecision/debug_adaptor.hpp>\n   //=#include <boost/multiprecision/cpp_dec_float.hpp>\n\n   using namespace boost::multiprecision;\n\n   typedef number<debug_adaptor<cpp_dec_float<50> > > fp_type;\n\n   fp_type denom = 1;\n   fp_type sum = 1;\n\n   for(unsigned i = 2; i < 50; ++i)\n   {\n      denom *= i;\n      sum += 1 / denom;\n   }\n\n   std::cout << std::setprecision(std::numeric_limits<fp_type>::digits) << sum << std::endl;\n   //]\n}\n\nint main()\n{\n   t1();\n   return 0;\n}\n\n\n\n", "meta": {"hexsha": "ca19f444ed70fcf3a10bed8c3bfa92f74488d048", "size": 898, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost/libs/multiprecision/example/debug_adaptor_snips.cpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "deps/boost/libs/multiprecision/example/debug_adaptor_snips.cpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T01:39:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:18:40.000Z", "max_forks_repo_path": "deps/boost/libs/multiprecision/example/debug_adaptor_snips.cpp", "max_forks_repo_name": "alexhenrie/poedit", "max_forks_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 21.9024390244, "max_line_length": 92, "alphanum_fraction": 0.6213808463, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "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 <ros/ros.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <pcl_ros/point_cloud.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <boost/thread/thread.hpp>\n#include \"mongodb_store/SetParam.h\"\n\nros::ServiceClient client;\n\nbool is_inlier(const Eigen::Vector3f& point, const Eigen::Vector4f plane, double threshold)\n{\n    return fabs(point.dot(plane.segment<3>(0)) + plane(3)) < threshold;\n}\n\nvoid plot_best_plane(const pcl::PointCloud<pcl::PointXYZ>& points, const Eigen::Vector4f plane, double threshold)\n{\n    pcl::PointCloud<pcl::PointXYZ>::Ptr inlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());\n    pcl::PointCloud<pcl::PointXYZ>::Ptr outlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());\n    \n    for (int i = 0; i < points.size(); ++i) {\n        if (is_inlier(points[i].getVector3fMap(), plane, threshold)) {\n            inlier_cloud->push_back(points[i]);\n        }\n        else {\n            outlier_cloud->push_back(points[i]);\n        }\n    }\n    \n    pcl::visualization::PCLVisualizer viewer(\"3D Viewer\");\n    viewer.setBackgroundColor(0, 0, 0);\n    viewer.addCoordinateSystem(1.0);\n    viewer.initCameraParameters();\n    \n    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> inlier_color_handler(inlier_cloud, 255, 0, 0);\n    viewer.addPointCloud(inlier_cloud, inlier_color_handler, \"inliers\");\n    \n    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> outlier_color_handler(outlier_cloud, 0, 0, 255);\n    viewer.addPointCloud(outlier_cloud, outlier_color_handler, \"outliers\");\n    \n    while (!viewer.wasStopped())\n    {\n        viewer.spinOnce(100);\n        boost::this_thread::sleep(boost::posix_time::microseconds(100000));\n    }\n    \n}\n\nvoid compute_plane(Eigen::Vector4f& plane, const pcl::PointCloud<pcl::PointXYZ>& points, int* inds)\n{\n    Eigen::Vector3f first = points[inds[1]].getVector3fMap() - points[inds[0]].getVector3fMap();\n    Eigen::Vector3f second = points[inds[2]].getVector3fMap() - points[inds[0]].getVector3fMap();\n    Eigen::Vector3f normal = first.cross(second);\n    normal.normalize();\n    plane.segment<3>(0) = normal;\n    plane(3) = -normal.dot(points[inds[0]].getVector3fMap());\n}\n\nvoid extract_height_and_angle(const Eigen::Vector4f& plane)\n{\n    ROS_INFO(\"Ground plane: %f, %f, %f, %f\", plane(0), plane(1), plane(2), plane(3));\n    double dist = fabs(plane(3)/plane(2)); // distance along z axis\n    double height = fabs(plane(3)/plane.segment<3>(0).squaredNorm()); // height\n    ROS_INFO(\"Distance to plane along camera axis: %f\", dist);\n    ROS_INFO(\"Height above ground: %f\", height);\n    double angle = asin(height/dist);\n    ROS_INFO(\"Angle radians: %f\", angle);\n    ROS_INFO(\"Angle degrees: %f\", 180.0f*angle/M_PI);\n    \n    mongodb_store::SetParam srv;\n    char buffer[250];\n    \n    // store height above ground in datacentre\n    ros::param::set(\"/chest_xtion_height\", height);\n    sprintf(buffer, \"{\\\"path\\\":\\\"/chest_xtion_height\\\",\\\"value\\\":%f}\", height);\n    srv.request.param = buffer;\n    if (!client.call(srv)) {\n        ROS_ERROR(\"Failed to call set height, is config manager running?\");\n    }\n    \n    // store angle between camera and horizontal plane\n    ros::param::set(\"/chest_xtion_angle\", angle);\n    sprintf(buffer, \"{\\\"path\\\":\\\"/chest_xtion_angle\\\",\\\"value\\\":%f}\", angle);\n    srv.request.param = buffer;\n    if (!client.call(srv)) {\n        ROS_ERROR(\"Failed to call set angle, is config manager running?\");\n    }\n}\n\nvoid callback(const sensor_msgs::PointCloud2::ConstPtr& msg)\n{\n    ROS_INFO(\"Got a pointcloud, calibrating...\");\n    pcl::PointCloud<pcl::PointXYZ> cloud;\n    pcl::fromROSMsg(*msg, cloud);\n    \n    int nbr = cloud.size();\n    \n    int max = 1000; // ransac iterations\n    double threshold = 0.02; // threshold for plane inliers\n    \n    Eigen::Vector4f best_plane; // best plane parameters found\n    int best_inliers = -1; // best number of inliers\n    \n    int inds[3];\n    \n    Eigen::Vector4f plane;\n    int inliers;\n    for (int i = 0; i < max; ++i) {\n        \n        for (int j = 0; j < 3; ++j) {\n            inds[j] = rand() % nbr; // get a random point\n        }\n        \n        // check that the points aren't the same\n        if (inds[0] == inds[1] || inds[0] == inds[2] || inds[1] == inds[2]) {\n            continue;\n        }\n        \n        compute_plane(plane, cloud, inds);\n        inliers = 0;\n        for (int j = 0; j < nbr; j += 30) { // count number of inliers\n            if (is_inlier(cloud[j].getVector3fMap(), plane, threshold)) {\n                ++inliers;\n            }\n        }\n        \n        if (inliers > best_inliers) {\n            best_plane = plane;\n            best_inliers = inliers;\n        }\n    }\n    \n    extract_height_and_angle(best_plane); // find parameters and feed them to datacentre\n    plot_best_plane(cloud, best_plane, threshold); // visually evaluate plane fit\n    \n    exit(0);\n}\n\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"calibrate_chest\");\n\tros::NodeHandle n;\n\t\n    std::string camera_topic = \"chest_xtion\";\n    client = n.serviceClient<mongodb_store::SetParam>(\"/config_manager/set_param\");\n\tros::Subscriber sub = n.subscribe(camera_topic + \"/depth/points\", 1, callback);\n    \n    ros::spin();\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "eedbd2552d98ccf49ad1ed5c0f2fe6dd6a5b1068", "size": 5272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calibrate_chest/src/calibrate_chest.cpp", "max_stars_repo_name": "Jailander/strands_movebase", "max_stars_repo_head_hexsha": "0f64e104d4138f1623630afe641a7b2eb23635f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-11T12:16:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-21T09:40:27.000Z", "max_issues_repo_path": "calibrate_chest/src/calibrate_chest.cpp", "max_issues_repo_name": "Jailander/strands_movebase", "max_issues_repo_head_hexsha": "0f64e104d4138f1623630afe641a7b2eb23635f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T11:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-26T10:00:43.000Z", "max_forks_repo_path": "calibrate_chest/src/calibrate_chest.cpp", "max_forks_repo_name": "Jailander/strands_movebase", "max_forks_repo_head_hexsha": "0f64e104d4138f1623630afe641a7b2eb23635f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T20:42:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-01T12:27:43.000Z", "avg_line_length": 34.4575163399, "max_line_length": 116, "alphanum_fraction": 0.6358118361, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5526624380169464}}
{"text": "#include <iostream>\r\n#include <pybind11/eigen.h>\r\n#include <Eigen/Dense>\r\nnamespace py = pybind11;\r\n\r\ntemplate <typename T>\r\nusing RMatrix = Eigen::Matrix<T, -1, -1, Eigen::RowMajor>;\r\n\r\ntemplate <typename T>\r\nvoid block_test(Eigen::Ref<RMatrix<T>> m, T a) //\u4e2d\u8eab\u53c2\u7167\r\n{\r\n\t//\u30d7\u30ed\u30d1\u30c6\u30a3\u53d6\u5f97\r\n\tpy::print(m.rows(), m.cols());\r\n\t//block\u30674x4\u53d6\u308a\u51fa\u3057\u3066\u51e6\u7406\u3059\u308b\r\n\tpy::print(m.block(0, 0, 4, 4));\r\n\tpy::print(m.block(4, 0, 4, 4));\r\n\t\r\n\tEigen::MatrixXd A = m.block(4, 0, 4, 4); // block\u3067\u53d6\u308a\u51fa\u3057\u305f\u884c\u5217\u306f\u30b3\u30d4\u30fc\r\n\tpy::print(A.rows(), A.cols());\r\n\tA = A * a; // \u30d6\u30ed\u30c3\u30af\u5143\u306b\u306f\u5f71\u97ff\u3057\u306a\u3044\r\n\tpy::print(A);\r\n\tm.block<4, 4>(2, 0) = Eigen::Matrix4d::Identity(); // block\u306b\u76f4\u63a5\u4ee3\u5165\u3059\u308b\u3068\u66f8\u304d\u63db\u3048\u3089\u308c\u308b <>\u306f\u30b5\u30a4\u30ba\u56fa\u5b9a\u3059\u308b\u5834\u5408\u306b\u4f7f\u7528\r\n}\r\nPYBIND11_MODULE(QT_TARGET, m)\r\n{\r\n\tm.def(\"block_test\", &block_test<double>, \"\");\r\n}\r\n", "meta": {"hexsha": "154775f9e296272e43f02a3ffa9f24e4f5ed880a", "size": 730, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_matrix/main.cpp", "max_stars_repo_name": "Nitta-K-git/pybind_samples", "max_stars_repo_head_hexsha": "6b618bfebc4289061b4ebcfb64ce1da171515bb9", "max_stars_repo_licenses": ["MIT"], "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_matrix/main.cpp", "max_issues_repo_name": "Nitta-K-git/pybind_samples", "max_issues_repo_head_hexsha": "6b618bfebc4289061b4ebcfb64ce1da171515bb9", "max_issues_repo_licenses": ["MIT"], "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_matrix/main.cpp", "max_forks_repo_name": "Nitta-K-git/pybind_samples", "max_forks_repo_head_hexsha": "6b618bfebc4289061b4ebcfb64ce1da171515bb9", "max_forks_repo_licenses": ["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.0714285714, "max_line_length": 92, "alphanum_fraction": 0.6273972603, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.5526567474591392}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"circle.hpp\"\n#include <cmath>\n\nconst double accuracy = 0.00001;\n\n// =====================test initialization circle=====================\nBOOST_AUTO_TEST_SUITE(InitializeCircle)\n\n  BOOST_AUTO_TEST_CASE(InitializeCircle_OnCorrectValue_NoError)\n  {\n    jianing::Circle circle {{1.1, 1.2}, 3.5};\n\n    BOOST_REQUIRE_EQUAL(1.1, circle.getCenter().x);\n    BOOST_REQUIRE_EQUAL(1.2, circle.getCenter().y);\n    BOOST_REQUIRE_EQUAL(3.5, circle.getRadius());\n    BOOST_CHECK_CLOSE(M_PI * 3.5 * 3.5, circle.getArea(), accuracy);\n  }\n\n  BOOST_AUTO_TEST_CASE(InitializeCircle_OnWrongValue_ThrowError)\n  {\n    BOOST_CHECK_THROW(jianing::Circle({3.10, 4.15}, 0.0), std::domain_error);\n    BOOST_CHECK_THROW(jianing::Circle({3.10, 4.15}, -9.9), std::domain_error);\n  }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n// =====================test initialization circle(FrameRect)=====================\nBOOST_AUTO_TEST_SUITE(TestFrameRectWhenInitializeCircle)\n  BOOST_AUTO_TEST_CASE(TestFrameRectWhenInitializeCircle_OnCorrectValue_NoError)\n  {\n    jianing::Circle circle {{1.1, 1.2}, 3.5};\n\n    BOOST_CHECK_CLOSE(3.5 * 2.0, circle.getFrameRect().width, accuracy);\n    BOOST_CHECK_CLOSE(3.5 * 2.0, circle.getFrameRect().height, accuracy);\n    BOOST_REQUIRE_EQUAL(1.1, circle.getFrameRect().pos.x);\n    BOOST_REQUIRE_EQUAL(1.2, circle.getFrameRect().pos.y);\n  }\nBOOST_AUTO_TEST_SUITE_END()\n\n// =====================test move circle=====================\nBOOST_AUTO_TEST_SUITE(MoveCirle)\n\n  BOOST_AUTO_TEST_CASE(MoveCirle_ToPointXY_CorrectCenterAfterMove)\n  {\n    jianing::Circle circle {{10.0, 0.0}, 5.0};\n\n    circle.move({-10.0, -20.0});\n\n    BOOST_CHECK_EQUAL(-10.0, circle.getCenter().x);\n    BOOST_CHECK_EQUAL(-20.0, circle.getCenter().y);\n    BOOST_CHECK_EQUAL(5.0, circle.getRadius());\n    BOOST_CHECK_CLOSE(M_PI * 5.0 * 5.0, circle.getArea(), accuracy);\n  }\n\n  BOOST_AUTO_TEST_CASE(MoveCirle_Bydxdy_CorrectCenterAfterMove)\n  {\n    jianing::Circle circle {{-5.1, 5.2}, 2.5};\n\n    circle.move(5.0, -5.0);\n\n    BOOST_CHECK_CLOSE(-5.1 + 5.0, circle.getCenter().x, accuracy);\n    BOOST_CHECK_CLOSE(5.2 - 5.0, circle.getCenter().y, accuracy);\n    BOOST_CHECK_CLOSE(M_PI * 2.5 * 2.5, circle.getArea(), accuracy);\n    BOOST_CHECK_EQUAL(2.5, circle.getRadius());\n  }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n// =====================test move circle(FrameRect)=====================\nBOOST_AUTO_TEST_SUITE(TestFrameRectAfterMoveCirle)\n\n  BOOST_AUTO_TEST_CASE(TestFrameRectAfterMoveCirle_ToPointXY_CorrectFrameAfterMove)\n  {\n    jianing::Circle circle {{10.0, 0.0}, 5.0};\n\n    circle.move({-10.0, -20.0});\n\n    BOOST_CHECK_CLOSE(5.0 * 2.0, circle.getFrameRect().width, accuracy);\n    BOOST_CHECK_CLOSE(5.0 * 2.0, circle.getFrameRect().height, accuracy);\n    BOOST_CHECK_EQUAL(-10.0, circle.getFrameRect().pos.x);\n    BOOST_CHECK_EQUAL(-20.0, circle.getFrameRect().pos.y);\n  }\n\n  BOOST_AUTO_TEST_CASE(TestFrameRectAfterMoveCirle_Bydxdy_CorrectFrameAfterMove)\n  {\n    jianing::Circle circle {{-5.1, 5.2}, 2.5};\n\n    circle.move(5.0, -5.0);\n\n    BOOST_CHECK_CLOSE(2.5 * 2.0, circle.getFrameRect().width, accuracy);\n    BOOST_CHECK_CLOSE(2.5 * 2.0, circle.getFrameRect().height, accuracy);\n    BOOST_CHECK_CLOSE(-5.1 + 5.0, circle.getFrameRect().pos.x, accuracy);\n    BOOST_CHECK_CLOSE(5.2 - 5.0, circle.getFrameRect().pos.y, accuracy);\n  }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n// =====================test scale circle=====================\nBOOST_AUTO_TEST_SUITE(ScaleCircle)\n\n  BOOST_AUTO_TEST_CASE(ScaleCircle_OnWrongCoefficientNegativeOrZero_ThrowError)\n  {\n    jianing::Circle circle {{3.10, 4.15}, 9.26};\n\n    BOOST_CHECK_THROW(circle.scale(0.0), std::domain_error);\n    BOOST_CHECK_THROW(circle.scale(-1.8), std::domain_error);\n  }\n\n  BOOST_AUTO_TEST_CASE(ScaleCircle_OnCorrectCoefficient_CorrectRadiusAfterScale)\n  {\n    jianing::Circle circle {{3.3, -3.3}, 1.5};\n\n    circle.scale(2.2);\n\n    BOOST_CHECK_EQUAL(3.3, circle.getCenter().x);\n    BOOST_CHECK_EQUAL(-3.3, circle.getCenter().y);\n    BOOST_CHECK_CLOSE(1.5 * 2.2, circle.getRadius(), accuracy);\n    BOOST_CHECK_CLOSE(M_PI * 1.5 * 2.2 * 1.5 *2.2, circle.getArea(), accuracy);\n  }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n// =====================test scale circle(FrameRect)=====================\nBOOST_AUTO_TEST_SUITE(TestFrameRectAfterScaleCircle)\n\n  BOOST_AUTO_TEST_CASE(TestFrameRectAfterScaleCircle_OnCorrectCoefficient_CorrectCenerRadius)\n  {\n    jianing::Circle circle {{3.3, -3.3}, 1.5};\n\n    circle.scale(2.2);\n\n    BOOST_CHECK_CLOSE(1.5 * 2.0 * 2.2, circle.getFrameRect().width, accuracy);\n    BOOST_CHECK_CLOSE(1.5 * 2.0 * 2.2, circle.getFrameRect().height, accuracy);\n    BOOST_CHECK_EQUAL(3.3, circle.getFrameRect().pos.x);\n    BOOST_CHECK_EQUAL(-3.3, circle.getFrameRect().pos.y);\n  }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n// =====================test rotate circle=====================\nBOOST_AUTO_TEST_SUITE(RotateCircle)\n\n  BOOST_AUTO_TEST_CASE(RotateCircle_InPositiveDirection_CorrectWigthHeightXYAfterRotate)\n  {\n    jianing::Circle circle {{2.4, -6.7}, 9.8};\n\n    circle.rotate(73);\n\n    BOOST_CHECK_EQUAL(2.4, circle.getCenter().x);\n    BOOST_CHECK_EQUAL(-6.7, circle.getCenter().y);\n    BOOST_CHECK_EQUAL(9.8, circle.getRadius());\n    BOOST_CHECK_CLOSE(M_PI * 9.8 * 9.8, circle.getArea(), accuracy);\n  }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n// =====================test rotate circle(FrameRect)=====================\nBOOST_AUTO_TEST_SUITE(TestFrameRectAfterRotateCircle)\n\n  BOOST_AUTO_TEST_CASE(TestFrameRectAfterRotateCircle_InOppositeDirection_CorrectFrameAfterRotate)\n  {\n    jianing::Circle circle {{-1.3, -3.4}, 4.7};\n\n    circle.rotate(-974);\n\n    BOOST_CHECK_EQUAL(-1.3, circle.getFrameRect().pos.x);\n    BOOST_CHECK_EQUAL(-3.4, circle.getFrameRect().pos.y);\n    BOOST_CHECK_CLOSE(4.7 * 2.0, circle.getFrameRect().width, accuracy);\n    BOOST_CHECK_CLOSE(4.7 * 2.0, circle.getFrameRect().height, accuracy);\n  }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "9d913a61291f30a76f070dc58017db79354572b1", "size": 5880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "507 - A1-A4-spbspu-labs-2020-904-2/labs/common/test-circle.cpp", "max_stars_repo_name": "NekoSilverFox/CPP", "max_stars_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T20:57:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T06:24:41.000Z", "max_issues_repo_path": "507 - A1-A4-spbspu-labs-2020-904-2/labs/common/test-circle.cpp", "max_issues_repo_name": "NekoSilverFox/CPP", "max_issues_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-02T14:44:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-11T16:25:33.000Z", "max_forks_repo_path": "507 - A1-A4-spbspu-labs-2020-904-2/labs/common/test-circle.cpp", "max_forks_repo_name": "NekoSilverFox/CPP", "max_forks_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-27T17:30:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T09:48:23.000Z", "avg_line_length": 33.7931034483, "max_line_length": 98, "alphanum_fraction": 0.6848639456, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5526567457960899}}
{"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": "// -*- coding: utf-8 -*-\n#define CATCH_CONFIG_MAIN\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <catch.hpp>\n#include <netoptim/min_cycle_ratio.hpp>\n#include <netoptim/neg_cycle.hpp> // import negCycleFinder\n#include <py2cpp/nx2bgl.hpp>\n#include <utility> // for std::pair\n\nusing graph_t = boost::adjacency_list<\n    boost::listS, boost::vecS, boost::directedS, boost::no_property,\n    boost::property<boost::edge_weight_t, int, boost::property<boost::edge_index_t, int>>>;\nusing Vertex  = boost::graph_traits<graph_t>::vertex_descriptor;\nusing Edge_it = boost::graph_traits<graph_t>::edge_iterator;\n\nstatic xn::grAdaptor<graph_t> create_test_case1()\n{\n    using Edge           = std::pair<int, int>;\n    const auto num_nodes = 5;\n    enum nodes\n    {\n        A,\n        B,\n        C,\n        D,\n        E\n    };\n    static Edge    edge_array[] = {Edge(A, B), Edge(B, C), Edge(C, D), Edge(D, E), Edge(E, A)};\n    int            weights[]    = {-5, 1, 1, 1, 1};\n    int            num_arcs     = sizeof(edge_array) / sizeof(Edge);\n    static graph_t g(edge_array, edge_array + num_arcs, weights, num_nodes);\n    return xn::grAdaptor<graph_t>(g);\n}\n\nstatic xn::grAdaptor<graph_t> create_test_case2()\n{\n    using Edge           = std::pair<int, int>;\n    const auto num_nodes = 5;\n    enum nodes\n    {\n        A,\n        B,\n        C,\n        D,\n        E\n    };\n    static Edge    edge_array[] = {Edge(A, B), Edge(B, C), Edge(C, D), Edge(D, E), Edge(E, A)};\n    int            weights[]    = {2, 1, 1, 1, 1};\n    int            num_arcs     = sizeof(edge_array) / sizeof(Edge);\n    static graph_t g(edge_array, edge_array + num_arcs, weights, num_nodes);\n    return xn::grAdaptor<graph_t>(g);\n}\n\nstatic xn::grAdaptor<graph_t> create_test_case_timing()\n{\n    using Edge           = std::pair<int, int>;\n    const auto num_nodes = 3;\n    enum nodes\n    {\n        A,\n        B,\n        C\n    };\n    static Edge    edge_array[] = {Edge(A, B), Edge(B, A), Edge(B, C), Edge(C, B),\n                                Edge(B, C), Edge(C, B), Edge(C, A), Edge(A, C)};\n    int            weights[]    = {7, 0, 3, 1, 6, 4, 2, 5};\n    int            num_arcs     = sizeof(edge_array) / sizeof(Edge);\n    static graph_t g(edge_array, edge_array + num_arcs, weights, num_nodes);\n    return xn::grAdaptor<graph_t>(g);\n}\n\nbool do_case(xn::grAdaptor<graph_t>& G)\n{\n    using edge_t = typename xn::grAdaptor<graph_t>::edge_t;\n\n    auto get_weight = [](const xn::grAdaptor<graph_t>& G, const edge_t& e) -> int {\n        const auto& weightmap = boost::get(boost::edge_weight, G);\n        return weightmap[e];\n    };\n\n    negCycleFinder N(G, get_weight);\n    auto           cycle = N.find_neg_cycle();\n    return !cycle.empty();\n}\n\nTEST_CASE(\"Test Negative Cycle\", \"[test_neg_cycle]\")\n{\n    xn::grAdaptor<graph_t> G = create_test_case1();\n    // boost::property_map<graph_t, boost::edge_weight_t>::type weightmap =\n    // boost::get(boost::edge_weight, G); std::vector<Vertex>\n    // p(boost::num_vertices(G));\n    bool hasNeg = do_case(G);\n    CHECK(hasNeg);\n\n    // G = xn::path_graph(5, create_using=xn::DiGraph());\n    // hasNeg = do_case(G);\n    // CHECK(!hasNeg);\n}\n\nTEST_CASE(\"Test No Negative Cycle\", \"[test_neg_cycle]\")\n{\n    xn::grAdaptor<graph_t> G      = create_test_case2();\n    bool                   hasNeg = do_case(G);\n    CHECK(!hasNeg);\n}\n\nTEST_CASE(\"Test Timing Graph\", \"[test_neg_cycle]\")\n{\n    xn::grAdaptor<graph_t> G      = create_test_case_timing();\n    bool                   hasNeg = do_case(G);\n    CHECK(!hasNeg);\n}\n", "meta": {"hexsha": "8c8bb1a0a2deb425b15530b6f4f677fd6c156608", "size": 3565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/src/main.cpp", "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": "app/src/main.cpp", "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": "app/src/main.cpp", "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": 31.0, "max_line_length": 95, "alphanum_fraction": 0.5896213184, "num_tokens": 1025, "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": "/**\n* @file: matrix_generator.hpp\n* @brief:\n* @author: Changjiang Cai, ccai1@stevens.edu, caicj5351@gmail.com\n* @version: 0.0.1\n* @creation date: 17-12-2015\n* @last modified: Thu 10 Mar 2016 09:32:02 AM EST\n*/\n\n// some of the codes are generated by Boxiang Do.\n#ifndef matrix_generator_hpp\n#define matrix_generator_hpp\n\n#include <stdio.h>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include \"truth_discovery.hpp\"\n#include <random>\r\n#include <boost/math/special_functions/beta.hpp>\n\n#define UNIFORM_DISTRIBUTION 0\n#define NORMAL_DISTRIBUTION 1\n#define NEARLY_ZERO 1.0E-5\n\n#define LOW_QUALITY 0\n#define MEDIUM_QUALITY 1\n#define HIGH_QUALITY 2\n\n#define low_guassian 1\n#define medium_guassian  0.1\n#define high_guassian  0.01\n#define high_uniform_left  0\n#define high_uniform_right 0.2\n#define medium_uniform_left  0.1\n#define medium_uniform_right 0.3\n#define low_uniform_left  0.2\n#define low_uniform_right  0.4\n\n/*\ndouble low_guassian = 1;\ndouble medium_guassian = 0.1;\ndouble high_guassian = 0.01;\ndouble high_uniform_left = 0;\ndouble high_uniform_right = 0.2;\ndouble medium_uniform_left = 0.1;\ndouble medium_uniform_right = 0.3;\ndouble low_uniform_left = 0.2;\ndouble low_uniform_right = 0.4;\n*/\n\n\nusing namespace std;\nbool generate_sim_vote_for_one_task_for_CrowdBT(\n\tconst int & n, // vertex number\n\tconst int & rank_o_i,\n\tconst int & rank_o_j, // less rank is better.\n\tconst double & a, //Reta distribution parameter.\n\tconst double & b //Beta distribution parameter.\n\t);\n\nbool generate_sim_vote_for_one_task(\n\tconst int & n, // vertex number\n\tconst int & rank_o_i,\n\tconst int & rank_o_j, // less rank is better.\n\tconst double& stddev /*Gaussian variance to control the worker's quality.*/\n\t);\n\n\nvector<vector<int>> generate_sim_vote(const int& n, bool **GT,\n\t// ground_truth: <key = object_i, value = rank of object_i>;\n\tconst map<int, int>& ground_truth,\n\tconst double& stddev, /*Gaussian variance to control the worker's quality.*/\n\tconst int & max_per_worker // maximum number of pairwise comparison per worker can do.\n\t// if max_per_worker < 0, that means doing all the pairwise comparasions.\n\t);\n\n\n\n\n// for all the workers, gathering their voting results.\nvector<vector<vector<int>>> generate_sim_votes(\n\tconst int& n, const int& w, bool **GT,\n\tconst map<int, int>& ground_truth, const int& distribution,\n\tconst int& quality, // different levels of error-rate for the worker's quality.\n\tconst int & max_per_worker /*maximum number of pairwise comparison per worker can do.*/\n\t);\n\n\n\nvoid generate_sim_votes_taskID_who(\n\tconst int& n, const int& w, bool **GT,\n\tconst vector<vector<vector<int>>> & matrice,\n\t// store the tasks;\n\t// The task-IDs' are assigned based on way the double-for-loop is executed.\n\tvector<vector <td_wieghts::client_vote>> & v_client_votes\n\t);\n\n\nvector<vector <td_wieghts::client_vote>>\ngenerate_aggregated_matrix_SATD(bool **GT,\n\tconst vector<vector<vector<int>>> & matrice,\n\tstd::vector<std::vector<double>> & gp, \n\tvector<double> & worker_weights,\n\ttd_wieghts::truth_discovery * td,\n    const int & max_task_num,\n\tint & count, // Truth discovery execution times.\n\t/*Smothing_Type : */\n\tconst int & smothingType = DIRECT_USE_WEIGHTS\n\t);\n\ndouble small_prob(const double & worker_weight, const double & mean,\n\tconst double & prob_threshold, /*a threshold of the small_prob to be generated.*/\n\tconst double & stddev_scalar);\n\nvoid Smoothing_UpdateProb_with_Workers_Quality(\n\tconst vector<double> & worker_weights,\n\tbool **GT, const int & n, /*object number*/\n\tconst double & prob_threshold, /*a threshold of the small_prob to be generated.*/\n\tconst double & mean, const double & stddev_scalar,\n\tconst vector<vector <td_wieghts::client_vote>> & v_client_votes,\n\tvector<vector<double>> & gtc);\n\n/* You have to specify the default values\n* for the arguments only in the declaration\n* but not in the definition.*/\nstd::vector<std::vector<double> > generate_aggregated_matrix(\n\tconst int& n, const int& w, bool **GT,\n\tconst std::map<int, int>& ground_truth, const int& distribution,\n\tconst int& quality, // different levels of error-rate for the worker's quality.\n\tconst int & max_per_worker, // maximum number of pairwise comparison per worker can do.\n\t/*Smothing_Type : */\n\tconst int & Smothing_Type = DIRECT_USE_WEIGHTS\n\t);\n\n\nstd::vector<std::vector<double> >\ngenerate_aggregated_matrix(\nconst std::vector<std::vector<std::vector<int>>> & matrice,\n/*Smothing_Type : */\nconst int & smothingType = DIRECT_USE_WEIGHTS\n);\n\n// added by CCJ\nstd::vector<std::vector<int> >\ngenerate_aggregated_voting_matrix(const vector<vector<vector<int>>> &  matrice);\n\n\n\n#endif /* matrix_generator_hpp */", "meta": {"hexsha": "59b5a5280f7cfff2296a37e30e58a201a7dec9fc", "size": 4619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/matrix_generator.hpp", "max_stars_repo_name": "ccj5351/crowdsourcing", "max_stars_repo_head_hexsha": "b0c2052ed4ae7ca42aa20436c271e6de5c5258a1", "max_stars_repo_licenses": ["MIT"], "max_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_generator.hpp", "max_issues_repo_name": "ccj5351/crowdsourcing", "max_issues_repo_head_hexsha": "b0c2052ed4ae7ca42aa20436c271e6de5c5258a1", "max_issues_repo_licenses": ["MIT"], "max_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_generator.hpp", "max_forks_repo_name": "ccj5351/crowdsourcing", "max_forks_repo_head_hexsha": "b0c2052ed4ae7ca42aa20436c271e6de5c5258a1", "max_forks_repo_licenses": ["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.7933333333, "max_line_length": 88, "alphanum_fraction": 0.747997402, "num_tokens": 1203, "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": "// 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": "/*\n * Copyright (c) 2013-, Stephen Miller\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, \n * with or without modification, are permitted provided \n * that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the \n * above copyright notice, this list of conditions \n * and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the \n * above copyright notice, this list of conditions and \n * the following disclaimer in the documentation and/or \n * other materials provided with the distribution.\n * \n * 3. Neither the name of the copyright holder nor the \n * names of its contributors may be used to endorse or\n * promote products derived from this software without \n * specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS \n * AND 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 \n * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) \n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER \n * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING \n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n\n#include <pcl/console/print.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <pcl/io/pcd_grabber.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/io/ply_io.h>\n#include <pcl/io/vtk_lib_io.h>\n#include <pcl/pcl_macros.h>\n\n#include <boost/filesystem/convenience.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include <string>\n#include <vector>\n\nvoid\ngetIntrinsics (const pcl::PointCloud<pcl::PointXYZ> &cloud,\n              float &fx,\n              float &fy,\n              float &cx,\n              float &cy,\n              float &reproj_error)\n{\n  Eigen::MatrixXf A = Eigen::MatrixXf::Zero (2*cloud.size (), 4);\n  Eigen::VectorXf b = Eigen::VectorXf::Zero (2*cloud.size ());\n  size_t idx = 0;\n  float minX, minY, minZ; \n  minX = minY = minZ = std::numeric_limits<float>::infinity();\n  float maxX, maxY, maxZ; \n  maxX = maxY = maxZ = -std::numeric_limits<float>::infinity();\n  for (int x = 0 ; x < cloud.width; x++)\n  {\n    for (int y = 0; y < cloud.height; y++)\n    {\n      const pcl::PointXYZ &pt = cloud (x,y);\n      if (pcl_isnan (pt.x) || pcl_isnan (pt.y) || pcl_isnan (pt.z) || (pt.x == 0) || (pt.y == 0))\n        continue;\n      if (pt.x > maxX) maxX = pt.x;\n      if (pt.y > maxY) maxY = pt.y;\n      if (pt.z > maxZ) maxZ = pt.z;\n      if (pt.x < minX) minX = pt.x;\n      if (pt.y < minY) minY = pt.y;\n      if (pt.z < minZ) minZ = pt.z;\n      A (idx, 0) = pt.z;\n      A (idx, 2) = pt.x;\n      b (idx) = pt.z * x;\n      idx++;\n      A (idx, 1) = pt.z;\n      A (idx, 3) = pt.y;\n      b (idx) = pt.z * y;\n      idx++;\n    }\n  }\n  // Solve A*x = b;\n  Eigen::Vector4f X;\n  X = (A.transpose () * A).inverse () * A.transpose () * b;\n  cx = X (0);\n  cy = X (1);\n  fx = X (2);\n  fy = X (3);\n  reproj_error = (A*X - b).squaredNorm () / (fx*fx*idx/2);\n  PCL_INFO (\"Bounds:\\n\");\n  PCL_INFO (\"X: [%f, %f]\\n\",minX,maxX);\n  PCL_INFO (\"Y: [%f, %f]\\n\",minY,maxY);\n  PCL_INFO (\"Z: [%f, %f]\\n\",minZ,maxZ);\n}\n\nint\nmain (int argc, char** argv)\n{\n  if (argc != 2)\n  {\n    PCL_INFO (\"Usage: %s input_organized_cloud.pcd\\n\", argv[0]);\n    return (1);\n  }\n  std::string pcd_file = argv[1];\n  pcl::PointCloud<pcl::PointXYZ> cloud;\n  PCL_INFO (\"Loading cloud %s\\n\", pcd_file.c_str ());\n  pcl::io::loadPCDFile (pcd_file, cloud);\n  float fx, fy, cx, cy, reproj_error;\n  getIntrinsics (cloud, fx, fy, cx, cy, reproj_error);\n  PCL_INFO (\"Width: %d\\n\", cloud.width);\n  PCL_INFO (\"Height: %d\\n\", cloud.height);\n  PCL_INFO (\"fx: %f\\n\", fx);\n  PCL_INFO (\"fy: %f\\n\", fy);\n  PCL_INFO (\"cx: %f\\n\", cx);\n  PCL_INFO (\"cy: %f\\n\", cy);\n  PCL_INFO (\"Total reprojection error: %f\\n\", reproj_error);\n  return (0);\n}\n", "meta": {"hexsha": "a7fae383e0b7517c461203d306399b7af44eba3e", "size": 4227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/prog/get_intrinsics.cpp", "max_stars_repo_name": "kelsey-saulnier/cpu_tsdf", "max_stars_repo_head_hexsha": "3d37fdb488b49943b533fff730c83d9e9b40016f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 277.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T16:51:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:50:23.000Z", "max_issues_repo_path": "src/prog/get_intrinsics.cpp", "max_issues_repo_name": "kelsey-saulnier/cpu_tsdf", "max_issues_repo_head_hexsha": "3d37fdb488b49943b533fff730c83d9e9b40016f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2015-01-29T12:00:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-22T07:30:37.000Z", "max_forks_repo_path": "src/prog/get_intrinsics.cpp", "max_forks_repo_name": "kelsey-saulnier/cpu_tsdf", "max_forks_repo_head_hexsha": "3d37fdb488b49943b533fff730c83d9e9b40016f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 74.0, "max_forks_repo_forks_event_min_datetime": "2015-05-14T23:08:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T12:22:14.000Z", "avg_line_length": 32.2671755725, "max_line_length": 97, "alphanum_fraction": 0.6309439319, "num_tokens": 1243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5526229609687493}}
{"text": "#include <cmath>\n#include <boost/math/distributions/negative_binomial.hpp>\n#include \"dist.hpp\"\n\nnamespace nbinomPlotPy {\n    Density get_pdf(RealType size, RealType prob, RealType upper, RealType step) {\n        Density density;\n\n        try {\n            if (step > 0) {\n                boost::math::negative_binomial_distribution<> dist(size, prob);\n                for (RealType x = 0.0; x <= upper; x += step) {\n                    density.push_back(boost::math::pdf(dist, x));\n                }\n            }\n        } catch (std::exception& e) {\n            // Bad size or prob parameters\n        }\n\n        return density;\n    }\n}\n\n/*\nLocal Variables:\nmode: c++\ncoding: utf-8-unix\ntab-width: nil\nc-file-style: \"stroustrup\"\nEnd:\n*/\n", "meta": {"hexsha": "15c930810cc82aad3e84d972ba7ed477911edd17", "size": 738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dist/dist_impl.cpp", "max_stars_repo_name": "zettsu-t/nbinomPlotPy", "max_stars_repo_head_hexsha": "dc1e9d026a2e80887c2bb5ec917eeabb29dc5659", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dist/dist_impl.cpp", "max_issues_repo_name": "zettsu-t/nbinomPlotPy", "max_issues_repo_head_hexsha": "dc1e9d026a2e80887c2bb5ec917eeabb29dc5659", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dist/dist_impl.cpp", "max_forks_repo_name": "zettsu-t/nbinomPlotPy", "max_forks_repo_head_hexsha": "dc1e9d026a2e80887c2bb5ec917eeabb29dc5659", "max_forks_repo_licenses": ["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.0625, "max_line_length": 82, "alphanum_fraction": 0.5596205962, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.552612607414269}}
{"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": "\r\n#include \"cor_algorithm/sources/utilities.h\"\r\n#include \"cor_system/sources/logger.h\"\r\n//#include \"cor_type/sources/math/vector2_tmpl_impl.h\"\r\n//#include \"cor_type/sources/primitive/box_tmpl_impl.h\"\r\n#include \"cor_type/sources/primitive/o_box.h\"\r\n\r\n#define BOOST_TEST_NO_LIB\r\n#include <boost/test/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_SUITE(obox)\r\n\r\nBOOST_AUTO_TEST_CASE(obox2d)\r\n{\r\n\r\n    typedef cor::type::OBox2F B;\r\n\r\n    B b0(B::Matrix::rot_z(0.1f) * B::Matrix::translate(0.0f, 0.0f, 0.0f), B::Box(-0.5f, -0.5f, 1.0f, 1.0f));\r\n\r\n    auto va = b0.get_vertices();\r\n\r\n    cor::RInt32 i;\r\n    cor::RInt32 j;\r\n\r\n    for(i = 0 ; i < 2 ; i++)\r\n    {\r\n        for(j = 0 ; j < 2 ; j++)\r\n        {\r\n            B b1(B::Matrix::rot_z(0.1f) * B::Matrix::translate(j - 0.5f, i - 0.5f, 0.0f), B::Box(-0.5f, -0.5f, 1.0f, 1.0f));\r\n            BOOST_CHECK(b0.is_cross(b1));\r\n\r\n        }\r\n\r\n    }\r\n\r\n    for(i = 0 ; i < 2 ; i++)\r\n    {\r\n        for(j = 0 ; j < 2 ; j++)\r\n        {\r\n            B b1(B::Matrix::rot_z(0.1f) * B::Matrix::translate(j  * 3 - 1.5f, i * 3 - 1.5f, 0.0f), B::Box(-0.5f, -0.5f, 1.0f, 1.0f));\r\n            BOOST_CHECK(!b0.is_cross(b1));\r\n\r\n        }\r\n\r\n    }\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(obox2d_distance)\r\n{\r\n    typedef cor::type::OBox2F B;\r\n    typedef cor::type::Vector2F V;\r\n\r\n    B b0(B::Matrix::translate(0.0f, 0.0f, 0.0f) *\r\n        B::Matrix::rot_z(0.1f) * B::Matrix::scale(1.5f, 1.5f, 1.0f),\r\n            B::Box(-0.5f, -0.5f, 1.0f, 1.0f));\r\n\r\n    V v(cosf(0.1f) - sinf(0.1f), sinf(0.1f) + cosf(0.1f));\r\n    auto d = b0.get_distance(v);\r\n    BOOST_CHECK_CLOSE(d, 0.5f / sqrtf(2.0f), 0.0001f);\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(obox2d_aabb)\r\n{\r\n    typedef cor::type::OBox2F B;\r\n    typedef cor::type::Vector2F V;\r\n\r\n    auto rot = cor::PI / 3;\r\n    B b0(B::Matrix::translate(0.0f, 1.0f, 0.0f) *\r\n        B::Matrix::rot_z(rot) * B::Matrix::scale(2.0f, 2.0f, 2.0f),\r\n            B::Box(-0.5f, -0.5f, 1.0f, 1.0f));\r\n\r\n    auto aabb = b0.get_aabb();\r\n\r\n    V v((cosf(rot) + sinf(rot)), (sinf(rot) + cosf(rot) + 1.0f));\r\n\r\n    BOOST_CHECK_CLOSE(aabb.get_max().x, v.x, 0.0001f);\r\n    BOOST_CHECK_CLOSE(aabb.get_max().y, v.y, 0.0001f);\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "b95fc72802f29f403df946302556acae6474e8e3", "size": 2175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/sources/math/o_box_test.cpp", "max_stars_repo_name": "rmake/cor-engine", "max_stars_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T09:55:02.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-10T03:42:23.000Z", "max_issues_repo_path": "tests/unit/sources/math/o_box_test.cpp", "max_issues_repo_name": "rmake/cor-engine", "max_issues_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/unit/sources/math/o_box_test.cpp", "max_forks_repo_name": "rmake/cor-engine", "max_forks_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T02:30:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T06:56:49.000Z", "avg_line_length": 25.8928571429, "max_line_length": 134, "alphanum_fraction": 0.5425287356, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5525537968913554}}
{"text": "/*\nCopyright 2014 Rogier van Dalen.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** \\file\nTest lexicographical.hpp with an example: the Viterbi semiring.\n*/\n\n#define BOOST_TEST_MODULE test_math_lexicographical_fast\n#include \"utility/test/boost_unit_test.hpp\"\n\n#include \"math/lexicographical.hpp\"\n\n#include <string>\n#include <ostream>\n#include <iostream>\n\n#include <boost/mpl/assert.hpp>\n\n#include \"range/std/container.hpp\"\n\n#include \"math/max_semiring.hpp\"\n#include \"math/sequence.hpp\"\n#include \"math/cost.hpp\"\n\nBOOST_AUTO_TEST_SUITE (test_suite_lexicographical_viterbi)\n\n/**\nTwo paths diverge in a wood.\nWe are a computer, so we can travel both.\nOne path has (1, a) and (1/2, b) as labels.\nThis is the path more travelled by.\nThe other path has (1/4, c) and (1, d) as labels.\nThis is the path less travelled by.\nWay leads on to way, and both paths lead to the same place.\nThis is a transition with (1/4, e) as a label.\n\nThe Viterbi semiring, summing over all paths, should return the complete path\nmore travelled by.\nThat complete path has (1/8, abe) as its label.\nThe other path, at (1/16, cde), is worse.\n*/\nBOOST_AUTO_TEST_CASE (test_viterbi) {\n    typedef math::lexicographical <math::over <\n        math::max_semiring <float>,\n        math::single_sequence <char>>> viterbi_semiring;\n\n    viterbi_semiring v_1_a (1, 'a');\n    viterbi_semiring v_0_5_b (0.5, 'b');\n    viterbi_semiring v_0_25_c (0.25, 'c');\n    viterbi_semiring v_1_d (1, 'd');\n    viterbi_semiring v_0_25_e (0.25, 'e');\n\n    auto result = ((v_1_a * v_0_5_b) + (v_0_25_c * v_1_d)) * v_0_25_e;\n    std::cout << result << std::endl;\n    BOOST_MPL_ASSERT ((std::is_same <decltype (result),\n        math::lexicographical <math::over <\n            math::max_semiring <float>, math::sequence <char>>>>));\n    BOOST_CHECK_EQUAL (range::at_c <0> (result.components()).value(), .125);\n    BOOST_CHECK (range::at_c <1> (result.components())\n        == math::sequence <char> (std::string (\"abe\")));\n}\n\n/**\nNow we are Frost, and we use a cost.\nThat makes all the difference.\nWe then take the path less travelled by.\nIts label is (1.5, cde).\nThat is better than (1.75, abe).\n*/\nBOOST_AUTO_TEST_CASE (test_cost) {\n    typedef math::lexicographical <math::over <\n        math::cost <float>,\n        math::single_sequence <char>>> cost_semiring;\n\n    cost_semiring v_1_a (1, 'a');\n    cost_semiring v_0_5_b (0.5, 'b');\n    cost_semiring v_0_25_c (0.25, 'c');\n    cost_semiring v_1_d (1, 'd');\n    cost_semiring v_0_25_e (0.25, 'e');\n\n    auto result = ((v_1_a * v_0_5_b) + (v_0_25_c * v_1_d)) * v_0_25_e;\n    std::cout << result << std::endl;\n    BOOST_MPL_ASSERT ((std::is_same <decltype (result),\n        math::lexicographical <math::over <\n            math::cost <float>, math::sequence <char>>>>));\n    BOOST_CHECK_EQUAL (range::at_c <0> (result.components()).value(), 1.5);\n    BOOST_CHECK (range::at_c <1> (result.components())\n        == math::sequence <char> (std::string (\"cde\")));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4df1fec4143d9156f08fa5e6e60ae2822852b006", "size": 3462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/test-lexicographical-2-viterbi.cpp", "max_stars_repo_name": "rogiervd/math", "max_stars_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/test-lexicographical-2-viterbi.cpp", "max_issues_repo_name": "rogiervd/math", "max_issues_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/test-lexicographical-2-viterbi.cpp", "max_forks_repo_name": "rogiervd/math", "max_forks_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9714285714, "max_line_length": 77, "alphanum_fraction": 0.6920854997, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5525537806135962}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Math\n\n#include \"math.hpp\"\n\n#include <iostream>\n#include <ostream>\n#include <sstream>\n#include <boost/test/included/unit_test.hpp>\n\nusing namespace Math;\n\nconst quat<float> R0{0,0,0,0}, R1{1,0,0,0}, \n\t  i{0,1,0,0}, j{0,0,1,0}, k{0,0,0,1};\nconst dual<float> E0{R0}, E{R0, 1}, \n\t  Ei = i*E, Ej = j*E, Ek = k*E;\n\nBOOST_AUTO_TEST_CASE(quaternions) {\n\tBOOST_REQUIRE(i*j == k);\n\tBOOST_REQUIRE(j*i == -k);\n\tBOOST_REQUIRE(i*k == -j);\n\tBOOST_REQUIRE(k*i == j);\n\tBOOST_REQUIRE(j*k == i);\n\tBOOST_REQUIRE(k*j == -i);\n\tBOOST_REQUIRE(i*i == -R1);\n\tBOOST_REQUIRE(j*j == -R1);\n\tBOOST_REQUIRE(k*k == -R1);\n}\n\nBOOST_AUTO_TEST_CASE(dual_quaternions) {\n\tBOOST_REQUIRE(E != 0);\n\tBOOST_REQUIRE(E*E == 0);\n\tBOOST_REQUIRE(k*E*i == k*i*E);\n\tBOOST_REQUIRE(k*(E*i) == k*E*i);\n\tBOOST_REQUIRE(k*(E*i) == E*(k*i));\n}\n", "meta": {"hexsha": "7fe4c1f15be5b2914f2a7ba000ffd9b8f4d5489d", "size": 840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/math.cpp", "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": "test/src/math.cpp", "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": "test/src/math.cpp", "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": 22.7027027027, "max_line_length": 44, "alphanum_fraction": 0.6428571429, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5525094218471455}}
{"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\u3092\u53d6\u308a\u3064\u3064\u4e8c\u9805\u4fc2\u6570\u3092\u8a08\u7b97\u3059\u308b\u95a2\u6570\u3092\u8fd4\u3059\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 \"options.hpp\"\n#include \"option_error.hpp\"\n\n#include <boost/format.hpp>\n\n#include <cmath>\n\nstatic inline bool is_sane(double x) {\n\treturn !(std::isnan(x) || std::isinf(x));\n}\n\nstatic inline bool is_power_of_2(unsigned x) {\n\treturn (x & (x - 1u)) == 0u;\n}\n\nvoid options::check() {\n#define THROW_INVALID(x) throw option_error((boost::format(\"invalid value for '\" #x \"' - %d\") % (x)).str())\n\n\tif ((size < 64u) || !is_power_of_2(size)) {\n\t\tTHROW_INVALID(size);\n\t}\n\n\tif (!is_sane(resolution) || (resolution <= 0.0)) {\n\t\tTHROW_INVALID(resolution);\n\t}\n\n\tif (!is_sane(brightness) || (brightness <= 0.0)) {\n\t\tTHROW_INVALID(brightness);\n\t}\n\n\tif (!is_sane(start_frequency) || (start_frequency < 0.0)) {\n\t\tTHROW_INVALID(start_frequency);\n\t}\n\n\tif (!is_sane(cut_down_frequency) || (cut_down_frequency <= 0.0) ||\n\t\t(cut_down_frequency - start_frequency < 1.0)) {\n\t\tTHROW_INVALID(cut_down_frequency);\n\t}\n\n#undef THROW_INVALID\n}\n", "meta": {"hexsha": "9fc298489d5598afb22660127c444e1a1eb1cbd3", "size": 920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "options.cpp", "max_stars_repo_name": "hexian000/wav2bmp", "max_stars_repo_head_hexsha": "1d8eeea92a838a9862b745f23ac902b873a61c78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "options.cpp", "max_issues_repo_name": "hexian000/wav2bmp", "max_issues_repo_head_hexsha": "1d8eeea92a838a9862b745f23ac902b873a61c78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "options.cpp", "max_forks_repo_name": "hexian000/wav2bmp", "max_forks_repo_head_hexsha": "1d8eeea92a838a9862b745f23ac902b873a61c78", "max_forks_repo_licenses": ["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.9047619048, "max_line_length": 107, "alphanum_fraction": 0.6652173913, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5524879070618799}}
{"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": "//\n// Copyright (c) 2019 INRIA\n//\n\n#include \"pinocchio/fwd.hpp\"\n#include \"pinocchio/multibody/joint/joint-generic.hpp\"\n#include \"pinocchio/multibody/liegroup/liegroup.hpp\"\n#include \"pinocchio/multibody/liegroup/liegroup-algo.hpp\"\n\n#include <casadi/casadi.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_jointRX_motion_space)\n{\n  typedef casadi::SX AD_double;\n  typedef pinocchio::JointCollectionDefaultTpl<AD_double> JointCollectionAD;\n  typedef pinocchio::JointCollectionDefaultTpl<double> JointCollection;\n  \n  typedef pinocchio::SE3Tpl<AD_double> SE3AD;\n  typedef pinocchio::MotionTpl<AD_double> MotionAD;\n  typedef pinocchio::SE3Tpl<double> SE3;\n  typedef pinocchio::MotionTpl<double> Motion;\n  typedef pinocchio::ConstraintTpl<Eigen::Dynamic,double> ConstraintXd;\n  \n  typedef Eigen::Matrix<AD_double,Eigen::Dynamic,1> VectorXAD;\n  typedef Eigen::Matrix<AD_double,6,1> Vector6AD;\n\n  typedef JointCollectionAD::JointModelRX JointModelRXAD;\n  typedef JointModelRXAD::ConfigVector_t ConfigVectorAD;\n//  typedef JointModelRXAD::TangentVector_t TangentVectorAD;\n  typedef JointCollectionAD::JointDataRX JointDataRXAD;\n  \n  typedef JointCollection::JointModelRX JointModelRX;\n  typedef JointModelRX::ConfigVector_t ConfigVector;\n  typedef JointModelRX::TangentVector_t TangentVector;\n  typedef JointCollection::JointDataRX JointDataRX;\n  \n  JointModelRX jmodel; jmodel.setIndexes(0,0,0);\n  JointDataRX jdata(jmodel.createData());\n  \n  JointModelRXAD jmodel_ad = jmodel.cast<AD_double>();\n  JointDataRXAD jdata_ad(jmodel_ad.createData());\n  \n  typedef pinocchio::LieGroup<JointModelRX>::type JointOperation;\n  ConfigVector q(jmodel.nq()); JointOperation().random(q);\n  \n  casadi::SX cs_q = casadi::SX::sym(\"q\", jmodel.nq());\n  ConfigVectorAD q_ad(jmodel.nq());\n  for(Eigen::DenseIndex k = 0; k < jmodel.nq(); ++k)\n  {\n    q_ad[k] = cs_q(k);\n  }\n  \n  // Zero order\n  jmodel_ad.calc(jdata_ad,q_ad);\n  jmodel.calc(jdata,q);\n  \n  SE3 M1(jdata.M);\n  SE3AD M2(jdata_ad.M);\n\n  casadi::SX cs_trans(3,1);\n  for(Eigen::DenseIndex k = 0; k < 3; ++k)\n  {\n    cs_trans(k) = M2.translation()[k];\n  }\n  casadi::SX cs_rot(3,3);\n  for(Eigen::DenseIndex i = 0; i < 3; ++i)\n  {\n    for(Eigen::DenseIndex j = 0; j < 3; ++j)\n    {\n      cs_rot(i,j) = M2.rotation()(i,j);\n    }\n  }\n  \n  casadi::Function eval_placement(\"eval_placement\", casadi::SXVector {cs_q}, casadi::SXVector {cs_trans,cs_rot});\n  std::cout << \"Joint Placement = \" << eval_placement << std::endl;\n  \n  std::vector<double> q_vec((size_t)jmodel.nq());\n  Eigen::Map<ConfigVector>(q_vec.data(),jmodel.nq(),1) = q;\n  casadi::DMVector res = eval_placement(casadi::DMVector {q_vec});\n  std::cout << \"M(q)=\" << res << std::endl;\n  \n  BOOST_CHECK(M1.translation().isApprox(Eigen::Map<SE3::Vector3>(res[0]->data())));\n  BOOST_CHECK(M1.rotation().isApprox(Eigen::Map<SE3::Matrix3>(res[1]->data())));\n\n  // First order\n  casadi::SX cs_v = casadi::SX::sym(\"v\", jmodel.nv());\n  TangentVector v(TangentVector::Random(jmodel.nv()));\n  VectorXAD v_ad(jmodel_ad.nv());\n  \n  std::vector<double> v_vec((size_t)jmodel.nv());\n  Eigen::Map<TangentVector>(v_vec.data(),jmodel.nv(),1) = v;\n\n  for(Eigen::DenseIndex k = 0; k < jmodel.nv(); ++k)\n  {\n    v_ad[k] = cs_v(k);\n  }\n  \n  jmodel.calc(jdata,q,v);\n  Motion m(jdata.v);\n  ConstraintXd Sref(jdata.S.matrix());\n  \n  jmodel_ad.calc(jdata_ad,q_ad,v_ad);\n  Vector6AD Y;\n  MotionAD m_ad(jdata_ad.v);\n  \n  casadi::SX cs_vel(6,1);\n  for(Eigen::DenseIndex k = 0; k < 6; ++k)\n  {\n    cs_vel(k) = m_ad.toVector()[k];\n  }\n  casadi::Function eval_velocity(\"eval_velocity\", casadi::SXVector {cs_q,cs_v}, casadi::SXVector {cs_vel});\n  std::cout << \"Joint Velocity = \" << eval_velocity << std::endl;\n  \n  casadi::DMVector res_vel = eval_velocity(casadi::DMVector {q_vec,v_vec});\n  std::cout << \"v(q,v)=\" << res_vel << std::endl;\n  \n  BOOST_CHECK(m.linear().isApprox(Eigen::Map<Motion::Vector3>(res_vel[0]->data())));\n  BOOST_CHECK(m.angular().isApprox(Eigen::Map<Motion::Vector3>(res_vel[0]->data()+3)));\n  \n  casadi::SX dvel_dv = jacobian(cs_vel, cs_v);\n  casadi::Function eval_S(\"eval_S\", casadi::SXVector {cs_q,cs_v}, casadi::SXVector {dvel_dv});\n  std::cout << \"S = \" << eval_S << std::endl;\n  \n  casadi::DMVector res_S = eval_S(casadi::DMVector {q_vec,v_vec});\n  std::cout << \"res_S:\" << res_S << std::endl;\n  ConstraintXd::DenseBase Sref_mat = Sref.matrix();\n  \n  for(Eigen::DenseIndex i = 0; i < 6; ++i)\n  {\n    for(Eigen::DenseIndex j = 0; i < Sref.nv(); ++i)\n      BOOST_CHECK(std::fabs(Sref_mat(i,j) - (double)res_S[0](i,j)) <= Eigen::NumTraits<double>::dummy_precision());\n  }\n}\n  \ntemplate<typename JointModel_> struct init;\n  \ntemplate<typename JointModel_>\n  struct init\n  {\n    static JointModel_ run()\n    {\n      JointModel_ jmodel;\n      jmodel.setIndexes(0,0,0);\n      return jmodel;\n    }\n    \n    static std::string name()\n    {\n      return \"default \" + JointModel_::classname();\n    }\n  };\n  \n  template<typename Scalar, int Options>\n  struct init<pinocchio::JointModelRevoluteUnalignedTpl<Scalar,Options> >\n  {\n    typedef pinocchio::JointModelRevoluteUnalignedTpl<Scalar,Options> JointModel;\n    \n    static JointModel run()\n    {\n      typedef typename JointModel::Vector3 Vector3;\n      JointModel jmodel(Vector3::Random().normalized());\n      \n      jmodel.setIndexes(0,0,0);\n      return jmodel;\n    }\n    \n    static std::string name()\n    {\n      return JointModel::classname();\n    }\n  };\n  \n  template<typename Scalar, int Options>\n  struct init<pinocchio::JointModelRevoluteUnboundedUnalignedTpl<Scalar,Options> >\n  {\n    typedef pinocchio::JointModelRevoluteUnboundedUnalignedTpl<Scalar,Options> JointModel;\n    \n    static JointModel run()\n    {\n      typedef typename JointModel::Vector3 Vector3;\n      JointModel jmodel(Vector3::Random().normalized());\n      \n      jmodel.setIndexes(0,0,0);\n      return jmodel;\n    }\n    \n    static std::string name()\n    {\n      return JointModel::classname();\n    }\n  };\n  \n  template<typename Scalar, int Options>\n  struct init<pinocchio::JointModelPrismaticUnalignedTpl<Scalar,Options> >\n  {\n    typedef pinocchio::JointModelPrismaticUnalignedTpl<Scalar,Options> JointModel;\n    \n    static JointModel run()\n    {\n      typedef typename JointModel::Vector3 Vector3;\n      JointModel jmodel(Vector3::Random().normalized());\n      \n      jmodel.setIndexes(0,0,0);\n      return jmodel;\n    }\n    \n    static std::string name()\n    {\n      return JointModel::classname();\n    }\n  };\n  \n  template<typename Scalar, int Options, template<typename,int> class JointCollection>\n  struct init<pinocchio::JointModelTpl<Scalar,Options,JointCollection> >\n  {\n    typedef pinocchio::JointModelTpl<Scalar,Options,JointCollection> JointModel;\n    \n    static JointModel run()\n    {\n      typedef pinocchio::JointModelRevoluteTpl<Scalar,Options,0> JointModelRX;\n      JointModel jmodel((JointModelRX()));\n      \n      jmodel.setIndexes(0,0,0);\n      return jmodel;\n    }\n    \n    static std::string name()\n    {\n      return JointModel::classname();\n    }\n  };\n  \n  template<typename Scalar, int Options, template<typename,int> class JointCollection>\n  struct init<pinocchio::JointModelCompositeTpl<Scalar,Options,JointCollection> >\n  {\n    typedef pinocchio::JointModelCompositeTpl<Scalar,Options,JointCollection> JointModel;\n    \n    static JointModel run()\n    {\n      typedef pinocchio::JointModelRevoluteTpl<Scalar,Options,0> JointModelRX;\n      typedef pinocchio::JointModelRevoluteTpl<Scalar,Options,1> JointModelRY;\n      JointModel jmodel((JointModelRX()));\n      jmodel.addJoint(JointModelRY());\n      \n      jmodel.setIndexes(0,0,0);\n      return jmodel;\n    }\n    \n    static std::string name()\n    {\n      return JointModel::classname();\n    }\n  };\n  \n  template<typename JointModel_>\n  struct init<pinocchio::JointModelMimic<JointModel_> >\n  {\n    typedef pinocchio::JointModelMimic<JointModel_> JointModel;\n    \n    static JointModel run()\n    {\n      JointModel_ jmodel_ref = init<JointModel_>::run();\n      \n      JointModel jmodel(jmodel_ref,1.,0.);\n      \n      return jmodel;\n    }\n    \n    static std::string name()\n    {\n      return JointModel::classname();\n    }\n  };\n\nstruct TestADOnJoints\n{\n  template<typename JointModel_>\n  void operator()(const pinocchio::JointModelBase<JointModel_> &) const\n  {\n    JointModel_ jmodel = init<JointModel_>::run();\n    jmodel.setIndexes(0,0,0);\n    test(jmodel);\n  }\n  \n  // TODO: get the nq and nv quantity from LieGroups\n  template<typename JointModel_>\n  static void test(const pinocchio::JointModelMimic<JointModel_> & /*jmodel*/)\n  { /* do nothing */ }\n  \n  template<typename JointModel>\n  static void test(const pinocchio::JointModelBase<JointModel> & jmodel)\n  {\n    std::cout << \"--\" << std::endl;\n    std::cout << \"jmodel: \" << jmodel.shortname() << std::endl;\n    \n    typedef casadi::SX AD_double;\n\n    typedef pinocchio::SE3Tpl<AD_double> SE3AD;\n    typedef pinocchio::MotionTpl<AD_double> MotionAD;\n    typedef pinocchio::SE3Tpl<double> SE3;\n    typedef pinocchio::MotionTpl<double> Motion;\n    typedef pinocchio::ConstraintTpl<Eigen::Dynamic,double> ConstraintXd;\n    \n    typedef Eigen::Matrix<AD_double,Eigen::Dynamic,1> VectorXAD;\n    typedef Eigen::Matrix<AD_double,6,1> Vector6AD;\n\n    typedef typename pinocchio::CastType<AD_double,JointModel>::type JointModelAD;\n    typedef typename JointModelAD::JointDataDerived JointDataAD;\n    \n    typedef typename JointModelAD::ConfigVector_t ConfigVectorAD;\n    \n    typedef typename JointModel::JointDataDerived JointData;\n    typedef typename JointModel::ConfigVector_t ConfigVector;\n    typedef typename JointModel::TangentVector_t TangentVector;\n    \n\n    JointData jdata(jmodel.createData());\n    pinocchio::JointDataBase<JointData> & jdata_base = jdata;\n    \n    JointModelAD jmodel_ad = jmodel.template cast<AD_double>();\n    JointDataAD jdata_ad(jmodel_ad.createData());\n    pinocchio::JointDataBase<JointDataAD> & jdata_ad_base = jdata_ad;\n    \n    ConfigVector q(jmodel.nq());\n\n    ConfigVector lb(ConfigVector::Constant(jmodel.nq(),-1.));\n    ConfigVector ub(ConfigVector::Constant(jmodel.nq(),1.));\n    \n    typedef pinocchio::RandomConfigurationStep<pinocchio::LieGroupMap,ConfigVector,ConfigVector,ConfigVector> RandomConfigAlgo;\n    RandomConfigAlgo::run(jmodel.derived(),typename RandomConfigAlgo::ArgsType(q,lb,ub));\n    \n    casadi::SX cs_q = casadi::SX::sym(\"q\", jmodel.nq());\n    ConfigVectorAD q_ad(jmodel.nq());\n    for(Eigen::DenseIndex k = 0; k < jmodel.nq(); ++k)\n    {\n      q_ad[k] = cs_q(k);\n    }\n    \n    // Zero order\n    jmodel_ad.calc(jdata_ad,q_ad);\n    jmodel.calc(jdata,q);\n    \n    SE3 M1(jdata_base.M());\n    SE3AD M2(jdata_ad_base.M());\n    \n    casadi::SX cs_trans(3,1);\n    for(Eigen::DenseIndex k = 0; k < 3; ++k)\n    {\n      cs_trans(k) = M2.translation()[k];\n    }\n    casadi::SX cs_rot(3,3);\n    for(Eigen::DenseIndex i = 0; i < 3; ++i)\n    {\n      for(Eigen::DenseIndex j = 0; j < 3; ++j)\n      {\n        cs_rot(i,j) = M2.rotation()(i,j);\n      }\n    }\n    \n    casadi::Function eval_placement(\"eval_placement\", casadi::SXVector {cs_q}, casadi::SXVector {cs_trans,cs_rot});\n    std::cout << \"Joint Placement = \" << eval_placement << std::endl;\n    \n    std::vector<double> q_vec((size_t)jmodel.nq());\n    Eigen::Map<ConfigVector>(q_vec.data(),jmodel.nq(),1) = q;\n    casadi::DMVector res = eval_placement(casadi::DMVector {q_vec});\n    std::cout << \"M(q)=\" << res << std::endl;\n    \n    BOOST_CHECK(M1.translation().isApprox(Eigen::Map<SE3::Vector3>(res[0]->data())));\n    BOOST_CHECK(M1.rotation().isApprox(Eigen::Map<SE3::Matrix3>(res[1]->data())));\n    \n    // First order\n    casadi::SX cs_v = casadi::SX::sym(\"v\", jmodel.nv());\n    TangentVector v(TangentVector::Random(jmodel.nv()));\n    VectorXAD v_ad(jmodel_ad.nv());\n    \n    std::vector<double> v_vec((size_t)jmodel.nv());\n    Eigen::Map<TangentVector>(v_vec.data(),jmodel.nv(),1) = v;\n    \n    for(Eigen::DenseIndex k = 0; k < jmodel.nv(); ++k)\n    {\n      v_ad[k] = cs_v(k);\n    }\n    \n    jmodel.calc(jdata,q,v);\n    Motion m(jdata_base.v());\n    ConstraintXd Sref(jdata_base.S().matrix());\n    \n    jmodel_ad.calc(jdata_ad,q_ad,v_ad);\n    Vector6AD Y;\n    MotionAD m_ad(jdata_ad_base.v());\n    \n    casadi::SX cs_vel(6,1);\n    for(Eigen::DenseIndex k = 0; k < 6; ++k)\n    {\n      cs_vel(k) = m_ad.toVector()[k];\n    }\n    casadi::Function eval_velocity(\"eval_velocity\", casadi::SXVector {cs_q,cs_v}, casadi::SXVector {cs_vel});\n    std::cout << \"Joint Velocity = \" << eval_velocity << std::endl;\n    \n    casadi::DMVector res_vel = eval_velocity(casadi::DMVector {q_vec,v_vec});\n    std::cout << \"v(q,v)=\" << res_vel << std::endl;\n    \n    BOOST_CHECK(m.linear().isApprox(Eigen::Map<Motion::Vector3>(res_vel[0]->data())));\n    BOOST_CHECK(m.angular().isApprox(Eigen::Map<Motion::Vector3>(res_vel[0]->data()+3)));\n    \n    casadi::SX dvel_dv = jacobian(cs_vel, cs_v);\n    casadi::Function eval_S(\"eval_S\", casadi::SXVector {cs_q,cs_v}, casadi::SXVector {dvel_dv});\n    std::cout << \"S = \" << eval_S << std::endl;\n    \n    casadi::DMVector res_S = eval_S(casadi::DMVector {q_vec,v_vec});\n    std::cout << \"res_S:\" << res_S << std::endl;\n    ConstraintXd::DenseBase Sref_mat = Sref.matrix();\n    \n    for(Eigen::DenseIndex i = 0; i < 6; ++i)\n    {\n      for(Eigen::DenseIndex j = 0; i < Sref.nv(); ++i)\n        BOOST_CHECK(std::fabs(Sref_mat(i,j) - (double)res_S[0](i,j)) <= Eigen::NumTraits<double>::dummy_precision());\n    }\n    \n    std::cout << \"--\" << std::endl << std::endl;\n  }\n};\n\nBOOST_AUTO_TEST_CASE(test_all_joints)\n{\n  typedef pinocchio::JointCollectionDefault::JointModelVariant JointModelVariant;\n  boost::mpl::for_each<JointModelVariant::types>(TestADOnJoints());\n\n  TestADOnJoints()(pinocchio::JointModel());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a719d283209e23339bb314553f8d9172e18f799c", "size": 13807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/casadi-joints.cpp", "max_stars_repo_name": "yDMhaven/pinocchio", "max_stars_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T07:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T07:23:34.000Z", "max_issues_repo_path": "unittest/casadi-joints.cpp", "max_issues_repo_name": "yDMhaven/pinocchio", "max_issues_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/casadi-joints.cpp", "max_forks_repo_name": "yDMhaven/pinocchio", "max_forks_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-25T13:34:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T13:34:37.000Z", "avg_line_length": 31.5228310502, "max_line_length": 127, "alphanum_fraction": 0.6661113928, "num_tokens": 4069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936435, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5524878897083543}}
{"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": "#include <memory>\n#define CATCH_CONFIG_MAIN\n#include <catch.hpp>\n#include <tbb/tbb.h>\n\n#include <Eigen/Dense>\n#include <Eigen/src/Eigenvalues/ComplexEigenSolver.h>\n#include <Eigen/src/QR/HouseholderQR.h>\n#include <random>\n\n#include \"EDP/ConstructSparseMat.hpp\"\n#include \"EDP/LocalHamiltonian.hpp\"\n\n#include \"common.hpp\"\n\n#include \"yavque/Circuit.hpp\"\n#include \"yavque/operators.hpp\"\n\ntbb::global_control gc(tbb::global_control::max_allowed_parallelism, 2);\n\nEigen::MatrixXcd matrix_log(const Eigen::MatrixXcd& m)\n{\n\tEigen::ComplexEigenSolver<Eigen::MatrixXcd> solver(m);\n\tEigen::MatrixXcd u = solver.eigenvectors();\n\n\tEigen::VectorXcd d = solver.eigenvalues();\n\td.array() = d.array().log().eval();\n\treturn u * d.asDiagonal() * u.adjoint();\n}\n\nTEST_CASE(\"test single qubit operator\", \"[single-qubit-operator]\")\n{\n\tusing namespace yavque;\n\tconstexpr uint32_t N = 10;\n\tconstexpr uint32_t dim = 1u << N;\n\tconstexpr cx_double I(0, 1.0);\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\tstd::uniform_int_distribution<uint32_t> index_dist(0, N - 1);\n\n\t// test using sparse matrix construction\n\tfor(uint32_t instance_idx = 0; instance_idx < 100; ++instance_idx)\n\t{\n\t\tauto op = random_unitary(2, re);\n\t\tauto idx = index_dist(re);\n\t\tauto m1 = SingleQubitOperator(op, N, idx);\n\n\t\tauto st = random_vector(dim, re);\n\n\t\tedp::LocalHamiltonian<cx_double> lh(N, 2);\n\t\tlh.addOneSiteTerm(idx, op.sparseView());\n\t\tauto m = edp::constructSparseMat<cx_double>(dim, lh);\n\n\t\tREQUIRE((m1.apply_right(st) - m * st).norm() < 1e-6);\n\n\t\tm1.dagger_in_place();\n\t\tREQUIRE((m1.apply_right(st) - m.adjoint() * st).norm() < 1e-6);\n\t}\n\n\t// test using U = e^{-I H}\n\tfor(uint32_t instance_idx = 0; instance_idx < 100; ++instance_idx)\n\t{\n\t\tauto op = random_unitary(2, re);\n\t\tauto idx = index_dist(re);\n\t\tauto m1 = SingleQubitOperator(op, N, idx);\n\n\t\tauto m2 = SingleQubitHamEvol(\n\t\t\tstd::make_shared<DenseHermitianMatrix>(I * matrix_log(op)), N, idx);\n\t\tm2.set_variable_value(1.0);\n\n\t\tauto st = random_vector(dim, re);\n\t\tREQUIRE((m1.apply_right(st) - m2.apply_right(st)).norm() < 1e-6);\n\t\tm1.dagger_in_place();\n\t\tm2.dagger_in_place();\n\t\tREQUIRE((m1.apply_right(st) - m2.apply_right(st)).norm() < 1e-6);\n\t}\n}\n\nTEST_CASE(\"test derivative of single qubit ham evol\", \"[single-qubit-ham-evol]\")\n{\n\tusing namespace yavque;\n\tconstexpr uint32_t N = 10;\n\tconstexpr uint32_t dim = 1u << N;\n\tconstexpr cx_double I(0, 1.0);\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\tstd::normal_distribution<double> ndist;\n\tstd::uniform_int_distribution<uint32_t> index_dist(0, N - 1);\n\n\tSECTION(\"test using pauli-x\")\n\t{\n\t\tfor(uint32_t instance_idx = 0; instance_idx < 10; ++instance_idx)\n\t\t{\n\t\t\tauto idx = index_dist(re);\n\t\t\tauto m = SingleQubitHamEvol(std::make_shared<DenseHermitianMatrix>(pauli_x()),\n\t\t\t                            N, idx);\n\n\t\t\tdouble val = ndist(re);\n\t\t\tm.set_variable_value(val);\n\n\t\t\tauto st = random_vector(dim, re);\n\t\t\tEigen::VectorXcd grad1 = m.log_deriv()->apply_right(m.apply_right(st));\n\n\t\t\t// from parameter shift rule\n\t\t\tm.get_variable() += M_PI / 2;\n\t\t\tEigen::VectorXcd grad2 = m.apply_right(st);\n\t\t\tm.get_variable() = val - M_PI / 2;\n\t\t\tgrad2 -= m.apply_right(st);\n\t\t\tgrad2 /= 2.0;\n\n\t\t\tREQUIRE((grad1 - grad2).norm() < 1e-6);\n\t\t}\n\t}\n\tSECTION(\"test using pauli-y\")\n\t{\n\t\tfor(uint32_t instance_idx = 0; instance_idx < 10; ++instance_idx)\n\t\t{\n\t\t\tauto idx = index_dist(re);\n\t\t\tauto m = SingleQubitHamEvol(std::make_shared<DenseHermitianMatrix>(pauli_y()),\n\t\t\t                            N, idx);\n\n\t\t\tdouble val = ndist(re);\n\t\t\tm.set_variable_value(val);\n\n\t\t\tauto st = random_vector(dim, re);\n\t\t\tEigen::VectorXcd grad1 = m.log_deriv()->apply_right(m.apply_right(st));\n\n\t\t\t// from parameter shift rule\n\t\t\tm.get_variable() += M_PI / 2;\n\t\t\tEigen::VectorXcd grad2 = m.apply_right(st);\n\t\t\tm.get_variable() = val - M_PI / 2;\n\t\t\tgrad2 -= m.apply_right(st);\n\t\t\tgrad2 /= 2.0;\n\n\t\t\tREQUIRE((grad1 - grad2).norm() < 1e-6);\n\t\t}\n\t}\n\tSECTION(\"test using pauli-z\")\n\t{\n\t\tfor(uint32_t instance_idx = 0; instance_idx < 10; ++instance_idx)\n\t\t{\n\t\t\tauto idx = index_dist(re);\n\t\t\tauto m = SingleQubitHamEvol(std::make_shared<DenseHermitianMatrix>(pauli_z()),\n\t\t\t                            N, idx);\n\n\t\t\tdouble val = ndist(re);\n\t\t\tm.set_variable_value(val);\n\n\t\t\tauto st = random_vector(dim, re);\n\t\t\tEigen::VectorXcd grad1 = m.log_deriv()->apply_right(m.apply_right(st));\n\n\t\t\t// from parameter shift rule\n\t\t\tm.get_variable() += M_PI / 2;\n\t\t\tEigen::VectorXcd grad2 = m.apply_right(st);\n\t\t\tm.get_variable() = val - M_PI / 2;\n\t\t\tgrad2 -= m.apply_right(st);\n\t\t\tgrad2 /= 2.0;\n\n\t\t\tREQUIRE((grad1 - grad2).norm() < 1e-6);\n\t\t}\n\t}\n\n\tSECTION(\"test using random hermitian matrix\")\n\t{\n\t\tfor(uint32_t instance_idx = 0; instance_idx < 100; ++instance_idx)\n\t\t{\n\t\t\tauto idx = index_dist(re);\n\n\t\t\tEigen::Vector3d coeffs;\n\t\t\tfor(uint32_t i = 0; i < 3; ++i)\n\t\t\t{\n\t\t\t\tcoeffs(i) = ndist(re);\n\t\t\t}\n\n\t\t\tEigen::MatrixXcd ham = coeffs(0) * pauli_x();\n\t\t\tham += coeffs(1) * pauli_y();\n\t\t\tham += coeffs(2) * pauli_z();\n\n\t\t\tauto m\n\t\t\t\t= SingleQubitHamEvol(std::make_shared<DenseHermitianMatrix>(ham), N, idx);\n\n\t\t\tdouble val = ndist(re);\n\t\t\tm.set_variable_value(val);\n\n\t\t\tauto st = random_vector(dim, re);\n\t\t\tEigen::VectorXcd grad1 = m.log_deriv()->apply_right(m.apply_right(st));\n\n\t\t\t// calc grad from parameter shift rule\n\t\t\tEigen::VectorXcd grad2;\n\t\t\t{\n\t\t\t\tdouble t = coeffs.norm();\n\t\t\t\tm.get_variable() += M_PI / 2 / t;\n\t\t\t\tgrad2 = m.apply_right(st);\n\t\t\t\tm.get_variable() = val - M_PI / 2 / t;\n\t\t\t\tgrad2 -= m.apply_right(st);\n\n\t\t\t\tgrad2 *= t / 2.0;\n\t\t\t}\n\n\t\t\tREQUIRE((grad1 - grad2).norm() < 1e-6);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "e01d132907e37a08d91233113351efff83675de2", "size": 5552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/TestSingleQubitOperator.cpp", "max_stars_repo_name": "chaeyeunpark/Yavque", "max_stars_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests/TestSingleQubitOperator.cpp", "max_issues_repo_name": "chaeyeunpark/Yavque", "max_issues_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tests/TestSingleQubitOperator.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": 27.2156862745, "max_line_length": 81, "alphanum_fraction": 0.6561599424, "num_tokens": 1741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5524878790310087}}
{"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": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\n#include <ipc/utils/eigen_ext.hpp>\n\nnamespace ipc {\n\ntypedef Eigen::DiagonalMatrix<double, 3> DiagonalMatrix3d;\n\ntemplate <typename T>\nEigen::SparseMatrix<T> SparseDiagonal(const VectorX<T>& x);\n\ntemplate <typename T> inline Matrix2<T> Hat(T x);\ntemplate <typename T> inline Matrix3<T> Hat(Vector3<T> x);\ntemplate <typename T> inline MatrixMax3<T> Hat(VectorMax3<T> x);\n\n} // namespace ipc\n\n#include \"eigen_ext.tpp\"\n", "meta": {"hexsha": "670d3ff4f79ce0a36de345852c3f2b27e2ec01e4", "size": 481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/eigen_ext.hpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "src/utils/eigen_ext.hpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "src/utils/eigen_ext.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": 21.8636363636, "max_line_length": 64, "alphanum_fraction": 0.7442827443, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5523914643383114}}
{"text": "#pragma once\n#include <algorithm>\n#include <boost/iterator/counting_iterator.hpp>\n#include <cassert>\n#include <vector>\n\n// An integer interval is a closed-open interval of integers. For example,\n// IntegerInterval(3,8) = {3,4,5,6,7}.\ntemplate <class IntType = int>\nclass IntegerInterval\n{\npublic:\n    static_assert(std::is_integral<IntType>::value, \"Template parameter IntType must be integral\");\n    using value_type = IntType;\n    using difference_type = std::ptrdiff_t;\n    using size_type = difference_type;\n    using iterator = boost::counting_iterator<IntType>;\n    using const_iterator = iterator;\n\npublic:\n    explicit IntegerInterval() = default;\n\n    explicit IntegerInterval(IntType n) : last_(n)\n    {\n        if (last_ < 0)\n            last_ = 0;\n    }\n\n    explicit IntegerInterval(IntType from, IntType to) : first_(from), last_(to)\n    {\n        if (last_ < first_) // empty interval\n            last_ = first_;\n    }\n\n    [[nodiscard]] size_type size() const { return last_ - first_; }\n    [[nodiscard]] IntType operator[](size_type i) const { return first_ + i; }\n\n    [[nodiscard]] iterator begin() const { return iterator(first_); }\n    [[nodiscard]] iterator end() const { return iterator(last_); }\n\nprivate:\n    IntType first_{0};\n    IntType last_{0};\n}; // end class IntegerInterval\n\nusing integer_interval = IntegerInterval<int>;\nusing big_integer_interval = IntegerInterval<std::int64_t>;\n\n// Think of NN as the set of natural numbers.\ntemplate <class IntType>\nauto NN(IntType n)\n{\n    return IntegerInterval<IntType>{n};\n}\n\ntemplate <class IntTypeFrom, class IntTypeTo>\nauto II(IntTypeFrom from, IntTypeTo to)\n{\n    using intt = std::common_type_t<IntTypeFrom, IntTypeTo>;\n    return IntegerInterval<intt>{from, to};\n}\n\ntemplate <class Container, class Index = std::ptrdiff_t>\nauto indices(const Container& C)\n{\n    return IntegerInterval<Index>(C.size());\n}\n", "meta": {"hexsha": "e6c489014c5105a05a0818c3facfac687a46e5f9", "size": 1886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/IntegerInterval.hpp", "max_stars_repo_name": "mraggi/ReuleauxPolyhedra", "max_stars_repo_head_hexsha": "bede340b1dff322e6e5908b5fe5761132d5cf824", "max_stars_repo_licenses": ["MIT"], "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/IntegerInterval.hpp", "max_issues_repo_name": "mraggi/ReuleauxPolyhedra", "max_issues_repo_head_hexsha": "bede340b1dff322e6e5908b5fe5761132d5cf824", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-02T10:30:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-02T10:30:39.000Z", "max_forks_repo_path": "utils/IntegerInterval.hpp", "max_forks_repo_name": "mraggi/ReuleauxPolyhedra", "max_forks_repo_head_hexsha": "bede340b1dff322e6e5908b5fe5761132d5cf824", "max_forks_repo_licenses": ["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.7352941176, "max_line_length": 99, "alphanum_fraction": 0.6951219512, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7826624840223699, "lm_q1q2_score": 0.5523914630727127}}
{"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\u201321, 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": "#include \"cxxmpi/cxxmpi.hpp\"\n#include \"Support/Parsing.hpp\"\n#include \"Support/OstreamHelpers.hpp\"\n#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/gmp.hpp>\n\nnamespace mpi = cxxmpi;\nnamespace mp = boost::multiprecision;\n\nint getSeriesSize(int Precision) {\n   return 2 * Precision;\n}\n\n#ifndef LINEAR\n\n/* SeriesSize - \u0447\u0438\u0441\u043b\u043e \u0447\u043b\u0435\u043d\u043e\u0432 \u0440\u044f\u0434\u0430 */\nvoid calculateGroup(int SeriesSize, unsigned int Precision) {\n   int Rank = mpi::commRank();\n   int CommSz = mpi::commSize();\n\n   /* the 0-th element (i.e. 1) is handled separately */\n   auto WorkRange = util::WorkSplitterLinear(SeriesSize - 1, CommSz).getRange(Rank).shift(1);\n   assert(WorkRange.size() > 0 && \"no work was given to this process\");\n   auto From = WorkRange.FirstIdx;\n   auto To = WorkRange.LastIdx - 1;\n\n   mp::mpz_int Nominator = 1;\n   mp::mpz_int PrevItem = 1;\n   for (; To > From; --To) {\n      PrevItem *= To;\n      Nominator += PrevItem;\n   }\n   mp::mpz_int Denominator = PrevItem * To;\n\n   mp::mpf_float PartialRes{mp::mpq_rational{Nominator, Denominator}, Precision};\n   mp::mpf_float DenomRes{mp::mpq_rational{1, Denominator}, Precision};\n\n   mpi::send(PartialRes.str(), 0, /* tag = */ 0);\n   mpi::send(DenomRes.str(), 0, /* tag = */ 1);\n}\n\nint calculateExp(int Precision) {\n   mp::mpf_float::default_precision(Precision);\n   calculateGroup(getSeriesSize(Precision), Precision);\n\n   if (mpi::commRank() != 0) {\n      // std::cerr << mpi::whoami << \": finished\" << std::endl;\n      return 0;\n   }\n\n   auto CommSz = mpi::commSize();\n   std::vector<mp::mpf_float> Partials(CommSz);\n   std::vector<mp::mpf_float> Denoms(CommSz);\n\n   std::string Buf;\n   for (int I = 0; I < CommSz * 2; ++I) {\n      auto Status = mpi::recv(Buf);\n      if (Status.tag() == 0) {\n         Partials[Status.source()].assign(Buf);\n      } else {\n         assert(Status.tag() == 1);\n         Denoms[Status.source()].assign(Buf);\n      }\n      Buf.clear();\n   }\n\n   /* reduce */\n   mp::mpf_float Sum = 1;\n   mp::mpf_float CurDenom = 1;\n   for (int I = 0; I < CommSz; ++I) {\n      Sum += Partials[I] * CurDenom;\n      CurDenom *= Denoms[I];\n   }\n   std::cout << Sum.str(Precision) << std::endl;\n   return 0;\n}\n\n#else // LINEAR\n\n/* calculates exp without using any parallel routines */\nint calculateExp(int Precision) {\n   int SeriesSize = getSeriesSize(Precision);\n\n   mp::mpf_float::default_precision(Precision);\n   mp::mpf_float Sum = 1;\n   mp::mpf_float Denom = 1;\n\n   for (int I = 1; I <= SeriesSize; ++I) {\n      Denom *= I;\n      Sum += 1 / Denom;\n   }\n   std::cout << Sum.str(Precision) << std::endl;\n   return 0;\n}\n\n#endif // LINEAR\n\nvoid emitUsageError() {\n   std::cerr << \"Usage: ./prog PRECISION\" << std::endl;\n   exit(EXIT_FAILURE);\n}\n\nint main(int argc, char *argv[])\n{\n#ifndef LINEAR\n   mpi::MPIContext Ctx{&argc, &argv};\n#endif\n\n   int Precision = 0;\n   if (argc != 2 || !util::parseInt(argv[1], &Precision))\n      emitUsageError();\n   return calculateExp(Precision);\n}", "meta": {"hexsha": "58ad028479bf8020310b4b233ec0c9cc3e5d7673", "size": 2936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/MPI/11.exp/main.cpp", "max_stars_repo_name": "graudtV/MPI-projects", "max_stars_repo_head_hexsha": "239ce72865813c5091f2a5b643e00be9f2280876", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experiments/MPI/11.exp/main.cpp", "max_issues_repo_name": "graudtV/MPI-projects", "max_issues_repo_head_hexsha": "239ce72865813c5091f2a5b643e00be9f2280876", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments/MPI/11.exp/main.cpp", "max_forks_repo_name": "graudtV/MPI-projects", "max_forks_repo_head_hexsha": "239ce72865813c5091f2a5b643e00be9f2280876", "max_forks_repo_licenses": ["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.7543859649, "max_line_length": 93, "alphanum_fraction": 0.6236376022, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5523914426518678}}
{"text": "#include \"Tictactoe.h\"\r\n#include <iostream>\r\n#include <Eigen/Dense>\r\n#include <Eigen/Core>\r\n#include <stdexcept>\r\n#include <sstream>\r\n#include <memory>\r\n\r\nusing namespace Eigen;\r\n\r\nTicTacToe::TicTacToe(){\r\n\tthis->board = MatrixXf::Zero(this->boardSize, this->boardSize);\r\n\tthis->player = 1;\r\n}\r\n\r\n\r\nstd::unique_ptr<Game> TicTacToe::copy(){\r\n\treturn std::make_unique<TicTacToe>(*this);\r\n}\r\n\r\nint TicTacToe::getActionSize(){\r\n\treturn this->boardSize*this->boardSize;\r\n}\r\n\r\nstd::vector<int> TicTacToe::getBoardSize(){\r\n\treturn {this->boardSize, this->boardSize};\r\n}\r\n\r\nint TicTacToe::getInputPlanes(){\r\n\treturn 3;\r\n}\r\n\r\nint TicTacToe::getOutputPlanes(){\r\n\treturn 1;\r\n}\r\n\r\nvoid TicTacToe::printBoard(){\r\n\tstd::cout<< this->board << std::endl;\r\n}\r\n\r\nvoid TicTacToe::play(int action){\r\n\tint x = action/boardSize;\r\n\tint y = action%boardSize;\r\n\r\n\tif (this->board(x,y) != 0){\r\n\t\tstd::ostringstream  error;\r\n\t\terror << \"Invalid action: \" << action << \"\\n\" << this->board; \r\n\t\tthrow std::invalid_argument(error.str());\r\n\t}\r\n\r\n\tthis->board(x,y) = this->player;\r\n\tthis->player *= -1 ;\r\n}\r\n\r\nbool TicTacToe::ended(){\r\n\tfor (int p : {-1, 1}){\r\n\t\tMatrix<bool,Dynamic,Dynamic> playerPositions = (this->board.array() == p).cast<bool>();\r\n\r\n\t\tif (this->findWin(playerPositions)){\r\n\t\t\tthis->winner = p;\r\n\t\t\treturn true;\r\n\t\t};\t\t\t\t\t\t\r\n\t}\r\n\r\n\tif((this->board.array() == 0).count() == 0){\r\n\t\tthis->winner = 0;\r\n\t\treturn true;\r\n\t}\t\r\n\t\r\n\treturn false;\r\n}\r\n\r\nint TicTacToe::getWinner(){\r\n\treturn this->winner;\r\n}\r\n\r\nbool TicTacToe::findWin(Matrix<bool,Dynamic,Dynamic> playerPositions){\r\n\tfor (int i = 0; i < this->boardSize - this->inRow + 1; i++){\r\n\t\tfor (int j = 0; j < this->boardSize - this->inRow + 1; j++){\r\n\t\t\tif(this->isWin(playerPositions.block(i, j, this->inRow, this->inRow))){\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nbool TicTacToe::isWin(Matrix<bool,Dynamic,Dynamic> smallBoard){\r\n\tMatrix<bool, Dynamic, Dynamic> vertical = smallBoard.rowwise().all();\r\n\tMatrix<bool, Dynamic, Dynamic> horizontal = smallBoard.colwise().all();\r\n\tbool ldiagonal = smallBoard.diagonal().all();\r\n\tbool rdiagonal = smallBoard.rowwise().reverse().diagonal().all();\r\n\r\n\treturn vertical.any() || horizontal.any() || ldiagonal || rdiagonal;\r\n}\t\r\n\r\nMatrixXf TicTacToe::getBoard(){\r\n\treturn this->board;\r\n}\r\n\r\nfloat TicTacToe::getPlayer(){\r\n\treturn this->player;\r\n}\r\n\r\nArrayXf TicTacToe::getPossibleActions(){\r\n\tArrayXf poss = ArrayXf::Zero(this->getActionSize());\r\n\tint bsize = (this->board).size();\r\n\tfor(int i = 0; i < bsize; i++){\r\n\t\tif (this->board(i/boardSize, i%boardSize) == 0){\r\n\t\t\tposs(i) = 1;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tposs(i) = 0;\r\n\t\t}\r\n\t}\r\n\r\n\treturn poss;\r\n}", "meta": {"hexsha": "81800a3db6a7cb80f68744a85a7f4a1dba1d028c", "size": 2639, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cc/games/Tictactoe.cc", "max_stars_repo_name": "kiri11/alpha-zero-cpp", "max_stars_repo_head_hexsha": "00f19e65deaa274e7c547d6f5ad5470904fe347c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cc/games/Tictactoe.cc", "max_issues_repo_name": "kiri11/alpha-zero-cpp", "max_issues_repo_head_hexsha": "00f19e65deaa274e7c547d6f5ad5470904fe347c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cc/games/Tictactoe.cc", "max_forks_repo_name": "kiri11/alpha-zero-cpp", "max_forks_repo_head_hexsha": "00f19e65deaa274e7c547d6f5ad5470904fe347c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1764705882, "max_line_length": 90, "alphanum_fraction": 0.6286472149, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5523279259670189}}
{"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": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\r\n\r\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n\r\n#include <geometry_test_common.hpp>\r\n\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n#include <boost/geometry/io/wkt/wkt.hpp>\r\n#include <boost/geometry/util/rational.hpp>\r\n\r\nvoid test_coordinate_cast(std::string const& s, int expected_nom, int expected_denom)\r\n{\r\n    boost::rational<int> a = bg::detail::coordinate_cast<boost::rational<int> >::apply(s);\r\n    BOOST_CHECK_EQUAL(a.numerator(), expected_nom);\r\n    BOOST_CHECK_EQUAL(a.denominator(), expected_denom);\r\n}\r\n\r\n\r\nvoid test_wkt(std::string const& wkt, std::string const expected_wkt)\r\n{\r\n    bg::model::point<boost::rational<int>, 2, bg::cs::cartesian> p;\r\n    bg::read_wkt(wkt, p);\r\n    std::ostringstream out;\r\n    out << bg::wkt(p);\r\n\r\n    BOOST_CHECK_EQUAL(out.str(), expected_wkt);\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n    test_coordinate_cast(\"0\", 0, 1);\r\n    test_coordinate_cast(\"1\", 1, 1);\r\n    test_coordinate_cast(\"-1\", -1, 1);\r\n    test_coordinate_cast(\"-0.5\", -1, 2);\r\n    test_coordinate_cast(\"-1.5\", -3, 2);\r\n    test_coordinate_cast(\"0.5\", 1, 2);\r\n    test_coordinate_cast(\"1.5\", 3, 2);\r\n    test_coordinate_cast(\"2.12345\", 42469, 20000);\r\n    test_coordinate_cast(\"1.\", 1, 1);\r\n\r\n    test_coordinate_cast(\"3/2\", 3, 2);\r\n    test_coordinate_cast(\"-3/2\", -3, 2);\r\n\r\n    test_wkt(\"POINT(1.5 2.75)\", \"POINT(3/2 11/4)\");\r\n    test_wkt(\"POINT(3/2 11/4)\", \"POINT(3/2 11/4)\");\r\n    test_wkt(\"POINT(-1.5 2.75)\", \"POINT(-3/2 11/4)\");\r\n    test_wkt(\"POINT(-3/2 11/4)\", \"POINT(-3/2 11/4)\");\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "e9eefcf990b02ce66016c7892ba6f1074f33cbbc", "size": 2094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/util/rational.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/test/util/rational.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/test/util/rational.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": 33.7741935484, "max_line_length": 91, "alphanum_fraction": 0.6599808978, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5522986932524396}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"logs.h\"\n#include \"route.h\"\n#include \"track.h\"\n#include <math.h>\n\nusing namespace GPS;\n\n/*\n\n  A B C D E\n  F G H I J\n  K L M N O\n  P Q R S T\n  U V W X Y\n\n*/\n\n\n/*\n * Check if the total length calculated from the GPX files\n * is close to the length calculated in the function.\n */\nBOOST_AUTO_TEST_SUITE( route_correct_distance_from_files )\n\nconst bool isFileName = true;\n\n// check if the length calculated from the file ABCD.gpx\n// is close to the length calculated in the function\nBOOST_AUTO_TEST_CASE( ABCD_length )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"ABCD.gpx\", isFileName);\n   BOOST_CHECK_EQUAL(30022.523566455005, route.totalLength());\n}\n\n// check if the length calculated from the file NorthYorkMoors.gpx\n// is close to the length calculated in the function\nBOOST_AUTO_TEST_CASE( NYM_length )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"NorthYorkMoors.gpx\", isFileName);\n   BOOST_CHECK_EQUAL(25204.617211916873, route.totalLength());\n}\n\n// check if function can calculate length between 2 consecutive points\n// Ex: Distance between A and B\n// using the log file AB.gpx\nBOOST_AUTO_TEST_CASE( AB_length) {\n    Route route = Route(LogFiles::GPXRoutesDir + \"AB.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(10010, route.totalLength(), 2);\n}\n\n// check if function can calculate an overlapping route\n// Ex: ABA => AB & BA\n// This test can also be used to check if length calculated\n// by moving right 1 point is equal to the length calculated by moving left 1 point\n// Ex: AB (moving right 1 point) =? BA(moving left 1 point)\nBOOST_AUTO_TEST_CASE( ABA_length) {\n    Route route = Route(LogFiles::GPXRoutesDir + \"ABA.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(20020, route.totalLength(), 2);\n}\n\n// checks if length calculated by moving downwards 2 points is equal to\n// the length calculated by moving upwards 2 points\n// Ex: length of CHM (move downwards 2 points) =? length of MHC (move upwards 2 points)\nBOOST_AUTO_TEST_CASE( CHM_MHC_length) {\n    Route route1 = Route(LogFiles::GPXRoutesDir + \"CHM.gpx\", isFileName);\n    Route route2 = Route(LogFiles::GPXRoutesDir + \"MHC.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route1.totalLength(), route2.totalLength(), 2);\n}\n\n// checks if length calculated by moving right one point is equal to\n// the length calculated my moving downwards one point\n// Ex: length of AB (move right 1 ponit) =? length of BG (move downwards 1 point)\n// Note: AB.gpx is already tested above so if BG.gpx is equal to AB.gpx then BG.gpx is correct\nBOOST_AUTO_TEST_CASE( BG_AB_length) {\n    Route route1 = Route(LogFiles::GPXRoutesDir + \"AB.gpx\", isFileName);\n    Route route2 = Route(LogFiles::GPXRoutesDir + \"BG.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route1.totalLength(), route2.totalLength(), 2);\n}\n\n// checks if length calculated by moving upwards 2 points is equal to\n// the length calculated by moving right 2 points\n// Ex: length of ABC (move right 2 points) =? length of CHM (move downwards 2 points)\nBOOST_AUTO_TEST_CASE( ABC_CHM_length) {\n    Route route1 = Route(LogFiles::GPXRoutesDir + \"ABC.gpx\", isFileName);\n    Route route2 = Route(LogFiles::GPXRoutesDir + \"CHM.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route1.totalLength(), route2.totalLength(), 2);\n}\n\n// check if function can calculate diagonal lengths\n// Ex: length of AGMSY => length of EIMQU\nBOOST_AUTO_TEST_CASE( AGMSY_EIMQU_length) {\n    Route route1 = Route(LogFiles::GPXRoutesDir + \"AGMSY.gpx\", isFileName);\n    Route route2 = Route(LogFiles::GPXRoutesDir + \"EIMQU.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route1.totalLength(), route2.totalLength(), 2);\n}\n\n// check if pythagoras' theorem works\n// using the triangle AFG\n// AG(2) =? AF(2) + FG(2)\nBOOST_AUTO_TEST_CASE( pythagorean ) {\n    Route ag_route = Route(LogFiles::GPXRoutesDir + \"AG.gpx\", isFileName);\n    Route af_route = Route(LogFiles::GPXRoutesDir + \"AF.gpx\", isFileName);\n    Route fg_route = Route(LogFiles::GPXRoutesDir + \"FG.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(pow(ag_route.totalLength(), 2),\n                      pow(af_route.totalLength(), 2) + pow(fg_route.totalLength(), 2),\n                      2);\n}\n\n// check if length calculated by adding by adding 2 routes is equal to the\n// length calculated by adding 2 different routes\n// where all routes have equal length\n// Ex: length of AB + length of RS ?= length of XY + length of OJ\nBOOST_AUTO_TEST_CASE( routes_addition) {\n    Route ab_route = Route(LogFiles::GPXRoutesDir + \"AB.gpx\", isFileName);\n    Route rs_route = Route(LogFiles::GPXRoutesDir + \"RS.gpx\", isFileName);\n    Route xy_route = Route(LogFiles::GPXRoutesDir + \"XY.gpx\", isFileName);\n    Route oj_route = Route(LogFiles::GPXRoutesDir + \"OJ.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(ab_route.totalLength() + rs_route.totalLength(),\n                      xy_route.totalLength() + oj_route.totalLength(),\n                      2);\n}\n\n\n// check if length calculated by 2 unsuccessive points is equal to the\n// length calculated by another 2 unsuccessive points\n// Ex: length of AJ =? length of PY\n// where AJ & PY are unsuccessive points\nBOOST_AUTO_TEST_CASE( AJ_PY_length) {\n    Route route1 = Route(LogFiles::GPXRoutesDir + \"AJ.gpx\", isFileName);\n    Route route2 = Route(LogFiles::GPXRoutesDir + \"PY.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(route1.totalLength(), route2.totalLength(), 2);\n}\n\n// check if FG 1/4 FJ\n// check if length calculated from the route FG is 1/4 the length of route FJ\nBOOST_AUTO_TEST_CASE( FG_FJ_length) {\n    Route fg_route = Route(LogFiles::GPXRoutesDir + \"FG.gpx\", isFileName);\n    Route fj_route = Route(LogFiles::GPXRoutesDir + \"FJ.gpx\", isFileName);\n    BOOST_CHECK_CLOSE(0.25 * fj_route.totalLength(),\n                      fg_route.totalLength(),\n                      2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n/////////////////////////////////////////////////////////////////////////////////////////////\n\n/*\n * checks if function throws exceptions when given incorrect files\n * Such files could be empty strings or non existing files\n */\nBOOST_AUTO_TEST_SUITE( incorrect_files)\n\nconst bool isFileName = true;\n\n// checks if function throws an invalid argument exception when opening\n// NNorthYorkMoors.gpx file (which does not exist)\nBOOST_AUTO_TEST_CASE( wrong_file_name )\n{\n   BOOST_CHECK_THROW(Route route = Route(LogFiles::GPXRoutesDir + \"NNorthYorkMoors.gpx\", isFileName),\n                     std::invalid_argument);\n}\n\n// checks if function throws a domain error exception when\n// an empty string is given instead of a file name\nBOOST_AUTO_TEST_CASE( empty_file_name_param )\n{\n   BOOST_CHECK_THROW(Route route = Route(LogFiles::GPXRoutesDir + \"\", isFileName),\n                     std::domain_error);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n/////////////////////////////////////////////////////////////////////////////////////////////\n\n\n// checks if function throws exception if the xml contents of the file are incorrect\n// such contents could be 'rtept' 'lat' 'lon' 'rte' 'gpx'\nBOOST_AUTO_TEST_SUITE( wrong_file_contents )\n\nconst bool isFileName = true;\n\n// check if function throws exception if 'rte' is missing from the log file 'ABCD_rte.gpx'\nBOOST_AUTO_TEST_CASE( rte_not_found ) {\n    BOOST_CHECK_THROW(Route route = Route(LogFiles::GPXRoutesDir + \"ABCD_rte.gpx\", isFileName),\n                      std::domain_error);\n}\n\n// check if function throws exception when 'rtept' is missing from the log file 'ABCD_rtept.gpx'\nBOOST_AUTO_TEST_CASE( rtept_not_found ) {\n    BOOST_CHECK_THROW(Route route = Route(LogFiles::GPXRoutesDir + \"ABCD_rtept.gpx\", isFileName),\n                      std::domain_error);\n}\n\n// check if function throws exception when 'lat' is missing from the log file 'ABCD_lat.gpx'\nBOOST_AUTO_TEST_CASE( lat_not_found ) {\n    BOOST_CHECK_THROW(Route route = Route(LogFiles::GPXRoutesDir + \"ABCD_lat.gpx\", isFileName),\n                      std::domain_error);\n}\n\n// check if function throws exception when 'lon' is missing from the log file 'ABCD_lon.gpx'\nBOOST_AUTO_TEST_CASE( lon_not_found) {\n    BOOST_CHECK_THROW(Route route = Route(LogFiles::GPXRoutesDir + \"ABCD_lon.gpx\", isFileName),\n                      std::domain_error);\n}\n\n// check if program throws exception when 'gpx' is missing from the log file 'ABCD_lon.gpx'\nBOOST_AUTO_TEST_CASE( gpx_not_found ) {\n    BOOST_CHECK_THROW(Route route = Route(LogFiles::GPXRoutesDir + \"ABCD_lon.gpx\", isFileName),\n                      std::domain_error);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n/////////////////////////////////////////////////////////////////////////////////////////////\n\n// checks if function can catch incorrect_positions\n// Ex: repeated positions or positions that have over range latitude and longitude\nBOOST_AUTO_TEST_SUITE( incorrect_positions )\n\nconst bool isFileName = true;\n\n// checks if program ignores repeated position (positions that are repeated consecutively).\nBOOST_AUTO_TEST_CASE( duplicate_positions ) {\n    Route route = Route(LogFiles::GPXRoutesDir + \"ABCD_duplicate_positions.gpx\", isFileName);\n    BOOST_CHECK_EQUAL(30022.523566455005, route.totalLength());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "442f25f2a11834c9ce2fbed66b8f281b744a8d9a", "size": 9062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpx-tests/totalLength-t0068955.cpp", "max_stars_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_stars_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gpx-tests/totalLength-t0068955.cpp", "max_issues_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_issues_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gpx-tests/totalLength-t0068955.cpp", "max_forks_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_forks_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4, "max_line_length": 101, "alphanum_fraction": 0.6996248069, "num_tokens": 2259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.5522729658902217}}
{"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   testVector.cpp\n * @brief  Unit tests for Vector class\n * @author Frank Dellaert\n **/\n\n#include <iostream>\n#include <CppUnitLite/TestHarness.h>\n#include <boost/tuple/tuple.hpp>\n#include <gtsam/base/Vector.h>\n\nusing namespace std;\nusing namespace gtsam;\n\nnamespace {\n  /* ************************************************************************* */\n  template<typename Derived>\n  Vector testFcn1(const Eigen::DenseBase<Derived>& in)\n  {\n    return in;\n  }\n\n  /* ************************************************************************* */\n  template<typename Derived>\n  Vector testFcn2(const Eigen::MatrixBase<Derived>& in)\n  {\n    return in;\n  }\n}\n\n/* ************************************************************************* */\nTEST( TestVector, special_comma_initializer)\n{\n  Vector expected(3);\n  expected(0) = 1;\n  expected(1) = 2;\n  expected(2) = 3;\n\n  Vector actual1 = (Vector(3) << 1, 2, 3);\n  Vector actual2((Vector(3) << 1, 2, 3));\n\n  Vector subvec1 = (Vector(2) << 2, 3);\n  Vector actual4 = (Vector(3) << 1, subvec1);\n\n  Vector subvec2 = (Vector(2) << 1, 2);\n  Vector actual5 = (Vector(3) << subvec2, 3);\n\n  Vector actual6 = testFcn1((Vector(3) << 1, 2, 3));\n  Vector actual7 = testFcn2((Vector(3) << 1, 2, 3));\n\n  EXPECT(assert_equal(expected, actual1));\n  EXPECT(assert_equal(expected, actual2));\n  EXPECT(assert_equal(expected, actual4));\n  EXPECT(assert_equal(expected, actual5));\n  EXPECT(assert_equal(expected, actual6));\n  EXPECT(assert_equal(expected, actual7));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, copy )\n{\n  Vector a(2); a(0) = 10; a(1) = 20;\n  double data[] = {10,20};\n  Vector b(2);\n  copy(data,data+2,b.data());\n  EXPECT(assert_equal(a, b));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, zero1 )\n{\n  Vector v = Vector::Zero(2);\n  EXPECT(zero(v));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, zero2 )\n{\n  Vector a = zero(2);\n  Vector b = Vector::Zero(2);\n  EXPECT(a==b);\n  EXPECT(assert_equal(a, b));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, scalar_multiply )\n{\n  Vector a(2); a(0) = 10; a(1) = 20;\n  Vector b(2); b(0) = 1; b(1) = 2;\n  EXPECT(assert_equal(a,b*10.0));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, scalar_divide )\n{\n  Vector a(2); a(0) = 10; a(1) = 20;\n  Vector b(2); b(0) = 1; b(1) = 2;\n  EXPECT(assert_equal(b,a/10.0));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, negate )\n{\n  Vector a(2); a(0) = 10; a(1) = 20;\n  Vector b(2); b(0) = -10; b(1) = -20;\n  EXPECT(assert_equal(b, -a));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, sub )\n{\n  Vector a(6);\n  a(0) = 10; a(1) = 20; a(2) = 3;\n  a(3) = 34; a(4) = 11; a(5) = 2;\n\n  Vector result(sub(a,2,5));\n\n  Vector b(3);\n  b(0) = 3; b(1) = 34; b(2) =11;\n\n  EXPECT(b==result);\n  EXPECT(assert_equal(b, result));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, subInsert )\n{\n  Vector big = zero(6),\n       small = ones(3);\n\n  size_t i = 2;\n  subInsert(big, small, i);\n\n  Vector expected = (Vector(6) << 0.0, 0.0, 1.0, 1.0, 1.0, 0.0);\n\n  EXPECT(assert_equal(expected, big));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, householder )\n{\n  Vector x(4);\n  x(0) = 3; x(1) = 1; x(2) = 5; x(3) = 1;\n\n  Vector expected(4);\n  expected(0) = 1.0; expected(1) = -0.333333; expected(2) = -1.66667; expected(3) = -0.333333;\n\n  pair<double, Vector> result = house(x);\n\n  EXPECT(result.first==0.5);\n  EXPECT(equal_with_abs_tol(expected,result.second,1e-5));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, concatVectors)\n{\n  Vector A(2);\n  for(int i = 0; i < 2; i++)\n    A(i) = i;\n  Vector B(5);\n  for(int i = 0; i < 5; i++)\n    B(i) = i;\n\n  Vector C(7);\n  for(int i = 0; i < 2; i++) C(i) = A(i);\n  for(int i = 0; i < 5; i++) C(i+2) = B(i);\n\n  list<Vector> vs;\n  vs.push_back(A);\n  vs.push_back(B);\n  Vector AB1 = concatVectors(vs);\n  EXPECT(AB1 == C);\n\n  Vector AB2 = concatVectors(2, &A, &B);\n  EXPECT(AB2 == C);\n}\n\n/* ************************************************************************* */\nTEST( TestVector, weightedPseudoinverse )\n{\n  // column from a matrix\n  Vector x(2);\n  x(0) = 1.0; x(1) = 2.0;\n\n  // create sigmas\n  Vector sigmas(2);\n  sigmas(0) = 0.1; sigmas(1) = 0.2;\n  Vector weights = reciprocal(emul(sigmas,sigmas));\n\n  // perform solve\n  Vector actual; double precision;\n  boost::tie(actual, precision) = weightedPseudoinverse(x, weights);\n\n  // construct expected\n  Vector expected(2);\n  expected(0) = 0.5; expected(1) = 0.25;\n  double expPrecision = 200.0;\n\n  // verify\n  EXPECT(assert_equal(expected,actual));\n  EXPECT(fabs(expPrecision-precision) < 1e-5);\n}\n\n/* ************************************************************************* */\nTEST( TestVector, weightedPseudoinverse_constraint )\n{\n  // column from a matrix\n  Vector x(2);\n  x(0) = 1.0; x(1) = 2.0;\n\n  // create sigmas\n  Vector sigmas(2);\n  sigmas(0) = 0.0; sigmas(1) = 0.2;\n  Vector weights = reciprocal(emul(sigmas,sigmas));\n\n  // perform solve\n  Vector actual; double precision;\n  boost::tie(actual, precision) = weightedPseudoinverse(x, weights);\n\n  // construct expected\n  Vector expected(2);\n  expected(0) = 1.0; expected(1) = 0.0;\n\n  // verify\n  EXPECT(assert_equal(expected,actual));\n  EXPECT(std::isinf(precision));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, weightedPseudoinverse_nan )\n{\n  Vector a = (Vector(4) << 1., 0., 0., 0.);\n  Vector sigmas = (Vector(4) << 0.1, 0.1, 0., 0.);\n  Vector weights = reciprocal(emul(sigmas,sigmas));\n  Vector pseudo; double precision;\n  boost::tie(pseudo, precision) = weightedPseudoinverse(a, weights);\n\n  Vector expected = (Vector(4) << 1., 0., 0.,0.);\n  EXPECT(assert_equal(expected, pseudo));\n  DOUBLES_EQUAL(100, precision, 1e-5);\n}\n\n/* ************************************************************************* */\nTEST( TestVector, ediv )\n{\n  Vector a = (Vector(3) << 10., 20., 30.);\n  Vector b = (Vector(3) << 2.0, 5.0, 6.0);\n  Vector actual(ediv(a,b));\n\n  Vector c = (Vector(3) << 5.0, 4.0, 5.0);\n  EXPECT(assert_equal(c,actual));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, dot )\n{\n  Vector a = (Vector(3) << 10., 20., 30.);\n  Vector b = (Vector(3) << 2.0, 5.0, 6.0);\n  DOUBLES_EQUAL(20+100+180,dot(a,b),1e-9);\n}\n\n/* ************************************************************************* */\nTEST( TestVector, axpy )\n{\n  Vector x = (Vector(3) << 10., 20., 30.);\n  Vector y0 = (Vector(3) << 2.0, 5.0, 6.0);\n  Vector y1 = y0, y2 = y0;\n  axpy(0.1,x,y1);\n  axpy(0.1,x,y2.head(3));\n  Vector expected = (Vector(3) << 3.0, 7.0, 9.0);\n  EXPECT(assert_equal(expected,y1));\n  EXPECT(assert_equal(expected,Vector(y2)));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, equals )\n{\n  Vector v1 = (Vector(1) << 0.0/std::numeric_limits<double>::quiet_NaN()); //testing nan\n  Vector v2 = (Vector(1) << 1.0);\n  double tol = 1.;\n  EXPECT(!equal_with_abs_tol(v1, v2, tol));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, greater_than )\n{\n  Vector v1 = (Vector(3) << 1.0, 2.0, 3.0),\n       v2 = zero(3);\n  EXPECT(greaterThanOrEqual(v1, v1)); // test basic greater than\n  EXPECT(greaterThanOrEqual(v1, v2)); // test equals\n}\n\n/* ************************************************************************* */\nTEST( TestVector, reciprocal )\n{\n  Vector v = (Vector(3) << 1.0, 2.0, 4.0);\n  EXPECT(assert_equal((Vector(3) << 1.0, 0.5, 0.25),reciprocal(v)));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, linear_dependent )\n{\n  Vector v1 = (Vector(3) << 1.0, 2.0, 3.0);\n  Vector v2 = (Vector(3) << -2.0, -4.0, -6.0);\n  EXPECT(linear_dependent(v1, v2));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, linear_dependent2 )\n{\n  Vector v1 = (Vector(3) << 0.0, 2.0, 0.0);\n  Vector v2 = (Vector(3) << 0.0, -4.0, 0.0);\n  EXPECT(linear_dependent(v1, v2));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, linear_dependent3 )\n{\n  Vector v1 = (Vector(3) << 0.0, 2.0, 0.0);\n  Vector v2 = (Vector(3) << 0.1, -4.1, 0.0);\n  EXPECT(!linear_dependent(v1, v2));\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n", "meta": {"hexsha": "ee0d94366c801f1e06884d85661ec30662477ab1", "size": 9311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/base/tests/testVector.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/base/tests/testVector.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/base/tests/testVector.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": 27.5473372781, "max_line_length": 94, "alphanum_fraction": 0.4612823542, "num_tokens": 2699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.5522729531589701}}
{"text": "\ufeff///\n/// Boost \u30b3\u30eb\u30fc\u30c1\u30f3 \u30b5\u30f3\u30d7\u30eb(\u30d5\u30a3\u30dc\u30ca\u30c3\u30c1\u6570)\n///\n///\n\n#include <iostream>\n#include <boost/coroutine2/coroutine.hpp>\n\n\n/// \u30d5\u30a3\u30dc\u30ca\u30c3\u30c1\u6570\n///\n///     F(0) = 0\n///     F(1) = 1\n///     F(n) = F(n-1) + F(n-2)\n/// \nvoid fibonacci(boost::coroutines2::coroutine<int>::push_type& yield)\n{\n    yield(0);\n    yield(1);\n\n    int prepre = 0;\n    int pre = 1;\n    for (int cnt = 0 ; cnt < 8 ; cnt++) {\n        auto cur = prepre + pre;\n        yield(cur);\n        prepre = pre;\n        pre = cur;\n    }\n}\n\n\nvoid fibonacci_limit(boost::coroutines2::coroutine<int>::push_type& yield, int limit)\n{    \n    yield(0);\n    yield(1);\n\n    int prepre = 0;\n    int pre = 1;\n    for (int cnt = 0 ; cnt < limit ; cnt++) {\n        auto cur = prepre + pre;\n        yield(cur);\n        prepre = pre;\n        pre = cur;\n    }\n}\n\n\nint main()\n{\n    boost::coroutines2::coroutine<int>::pull_type source(fibonacci);\n\n    for (; source ; source()) {\n        std::cout << source.get() <<  \" \";\n    }\n    std::cout << std::endl;\n\n    \n    source = boost::coroutines2::coroutine<int>::pull_type(fibonacci);\n    for (auto num : source) {\n        std::cout << num <<  \" \";\n    }\n    std::cout << std::endl;\n\n    \n\n    boost::coroutines2::coroutine<int>::pull_type source2(\n        [](auto & yield){fibonacci_limit(yield, 10);});\n\n    for (auto num : source2) {\n        std::cout << num <<  \" \";\n    }\n    std::cout << std::endl;\n    \n    return 0;\n}\n\n", "meta": {"hexsha": "8c8bed777a95c4020bfc7f0bf77d2d7b7a750e34", "size": 1396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/cpp/coroutine/fib.cpp", "max_stars_repo_name": "yohshiy/programmers_notes", "max_stars_repo_head_hexsha": "ececf1fc158ca8f541dc3ebc4310d2694c687ef5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lang/cpp/coroutine/fib.cpp", "max_issues_repo_name": "yohshiy/programmers_notes", "max_issues_repo_head_hexsha": "ececf1fc158ca8f541dc3ebc4310d2694c687ef5", "max_issues_repo_licenses": ["MIT"], "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/cpp/coroutine/fib.cpp", "max_forks_repo_name": "yohshiy/programmers_notes", "max_forks_repo_head_hexsha": "ececf1fc158ca8f541dc3ebc4310d2694c687ef5", "max_forks_repo_licenses": ["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.1298701299, "max_line_length": 85, "alphanum_fraction": 0.5071633238, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5522729489806677}}
{"text": "/***\n* Copyright 2017 Marc Stevens <marc@marc-stevens.nl>, Dan Shumow <danshu@microsoft.com>\n* Distributed under the MIT Software License.\n* See accompanying file LICENSE.txt or copy at\n* https://opensource.org/licenses/MIT\n***/\n\n\n#include <iostream>\n#include <fstream>\n#include <cstdio>\n#include <string>\n#include <vector>\n#include <map>\n#include <set>\n#include <stdexcept>\n#include <algorithm>\n#include <iomanip>\n\n#include <boost/cstdint.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include \"disturbancevector.hpp\"\n#include \"saveload.hpp\"\n\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\nusing namespace std;\n\ntypedef boost::uint32_t uint32;\n\nclass bitrel;\nmap<string,bitrel> gl_map_DV_bitrels;\n\n\nvector<string> break_string(string in, const string& delim)\n{\n\tvector<string> ret;\n\tsize_t pos = in.find_first_of(delim);\n\twhile (pos < in.size()) \n\t{\n\t\tret.push_back(in.substr(0, pos));\n\t\tin.erase(0, pos+1);\n\t\tpos = in.find_first_of(delim);\n\t} \n\tret.push_back(in);\n\treturn ret;\n}\n\n\nvector<uint32> operator^(const vector<uint32>& l, const vector<uint32>& r)\n{\n\tif (l.size() != r.size()) \n\t\tthrow runtime_error(\"vector xor undefined for unequal length vectors\");\n\n\tvector<uint32> ret(l);\n\tfor (unsigned i = 0; i < ret.size(); ++i)\n\t\tret[i] ^= r[i];\n\n\treturn ret;\n}\n\n\nvector<uint32>& operator^=(vector<uint32>& l, const vector<uint32>& r)\n{\n\tif (l.size() != r.size()) \n\t\tthrow runtime_error(\"vector xor undefined for unequal length vectors\");\n\n\tfor (unsigned i = 0; i < l.size(); ++i)\n\t\tl[i] ^= r[i];\n\n\treturn l;\n}\n\n\nclass bitrel \n{\npublic:\n\tvector< vector<uint32> > basis; // 80 wordmasks + LSB 81-th word as parity \n\n\tsize_t size() const \n\t{ \n\t\treturn basis.size(); \n\t}\n\n\tvoid clear() \n\t{ \n\t\tbasis.clear(); \n\t}\n\n\tvector< vector<uint32> > space(unsigned len = 81) const \n\t{\n\t\tvector< vector<uint32> > tmp;\n\t\tif (basis.size() == 0) \n\t\t\treturn tmp;\n\n\t\t// skip the zero vector: start with i=1\n\t\tfor (uint32 i = 1; i < uint32(1<<basis.size()); ++i) \n\t\t{ \n\t\t\tvector<uint32> elem(basis.front().size(), 0);\n\n\t\t\tfor (uint32 j = 0; j < basis.size(); ++j)\n\t\t\t\tif (i & (1<<j))\n\t\t\t\t\telem ^= basis[j];\n\n\t\t\telem.resize(len);\n\t\t\ttmp.push_back(elem);\n\t\t}\n\n\t\tstd::sort(tmp.begin(), tmp.end());\n\t\ttmp.erase( std::unique(tmp.begin(),tmp.end()), tmp.end());\n\t\treturn tmp;\n\t}\n\n\ttemplate<typename Archive>\n\tvoid serialize(Archive& ar, const unsigned int file_version)\n\t{\n\t\tar & boost::serialization::make_nvp(\"basis\", basis);\n\t}\n};\n\n\nstring bitrel_to_string(const vector<uint32>& br) \n{\n\tstring ret;\n\n\tfor (unsigned t = 0; t < 80; ++t)\n\t\tif (br[t])\n\t\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t\t\tif ((br[t]>>b)&1)\n\t\t\t\t\tret += string(ret.empty() ? \"W\" : \" ^ W\") + to_string(t) + \"[\" + to_string(b) + \"]\";\n\n\tif (br.size() > 80)\n\t\tret += \" = \" + to_string(br[80]&1);\n\treturn ret;\n}\n\n\nvector<uint32> parse_bitrel_line(string in)\n{\n\t//exampleline: - W37[4] ^ W39[4] = 1\n\tvector<uint32> br(81,0); // 80 wordmasks plus parity\n\n\tsize_t pos = in.find(\"=\");\n\tif ((pos = in.find_first_of(\"01\", pos)) == string::npos) \n\t\tthrow;\n\tif (in[pos] == '1') \n\t\tbr[80] = 1;\n\n\tin.erase(pos);\n\twhile (true) \n\t{\n\t\tif ((pos = in.find_first_of(\"0123456789\")) == string::npos) \n\t\t\tbreak;\n\n\t\tsize_t pos2 = in.find_first_not_of(\"0123456789\", pos);\n\t\tunsigned t = stoul(in.substr(pos, pos2-pos));\n\n\t\tif ((pos = in.find_first_of(\"0123456789\", pos2)) == string::npos) \n\t\t\tbreak;\n\n\t\tpos2 = in.find_first_not_of(\"0123456789\", pos);\n\t\tunsigned b = stoul(in.substr(pos, pos2-pos));\n\n\t\tif (t >= 80 || b >= 32) \n\t\t\tthrow runtime_error(\"t or b out of bounds\");\n\t\tbr[t] ^= uint32(1)<<b;\n\n\t\tin.erase(0, pos2);\n\t}\n\treturn br;\n}\n\n\nvoid load_bitrel(bitrel& br, const fs::path& filename)\n{\n\tbr.clear();\n\tifstream ifs(filename.native());\n\twhile (!!ifs) \n\t{\n\t\tstring line;\n\t\tgetline(ifs, line);\n\t\tif (line.find(\"=\") != string::npos)\n\t\t\tbr.basis.push_back( parse_bitrel_line(line) );\n\t}\n}\n\n\nstring filename_to_DV(const fs::path& filename) \n{\n\tvector<string> DV = break_string( filename.stem().string() , \"_-\");\n\tif ( DV.size() >= 3 \n\t\t&& (DV[0] == \"I\" || DV[0] == \"II\")\n\t\t&& DV[1].find_first_not_of(\"0123456789\") == string::npos\n\t\t&& DV[2].find_first_not_of(\"0123456789\") == string::npos\n\t\t)\n\t{\n\t\treturn DV[0] + \"(\" + DV[1] + \",\" + DV[2] + \")\";\n\t} \n\tthrow runtime_error(\"Filename does not contain DV description\");\n}\n\n\nvoid load_bitrels(std::map<string,bitrel>& map_DV_bitrels, const string& workdir, const set<string>& DVselection)\n{\n\tcout << \"Loading bit relation data for DVs from directory \" << workdir << endl;\n\tfs::path basedir = workdir;\n\tif (!fs::is_directory(basedir)) \n\t\tthrow runtime_error(\"Specified workdir is not a directory\");\n\n\tfor (auto dit = fs::directory_iterator(basedir); dit != fs::directory_iterator(); ++dit)\n\t{\n\t\tif (fs::is_regular_file(dit->path()))\n\t\t{\n\t\t\tstring DV = filename_to_DV(dit->path());\n\t\t\tif (!DVselection.empty())\n\t\t\t{\n\t\t\t\tbool ok = false;\n\t\t\t\tfor (auto it = DVselection.begin(); it != DVselection.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tif ((dit->path().stem().string().find(*it) != string::npos || DV.find(*it) != string::npos)\n\t\t\t\t\t\t&& dit->path().stem().string().find(\"I\" + *it) == string::npos\n\t\t\t\t\t\t&& DV.find(\"I\" + *it) == string::npos\n\t\t\t\t\t\t)\n\t\t\t\t\t\tok = true;\n\t\t\t\t}\n\t\t\t\tif (!ok) continue;\n\t\t\t}\n\n\t\t\tcout << DV << \": \" << flush;\n\t\t\tload_bitrel(map_DV_bitrels[DV], dit->path());\n\t\t\tcout << map_DV_bitrels[DV].size() << endl;\n\t\t}\n\t}\n}\n\n\nunsigned hammingweight(uint32 in)\n{\n\tunsigned c = 0;\n\tfor (; in; ++c)\n\t\tin &= in - 1;\n\treturn c;\n}\n\nunsigned hammingweight(const vector<uint32>& in)\n{\n\tunsigned c = 0;\n\tfor (auto i = in.begin(); i != in.end(); ++i)\n\t\tc += hammingweight(*i);\n\treturn c;\n}\n\n\nbool basis_less(const std::vector<uint32>& l, const std::vector<uint32>& r)\n{\n\t// first: rate on total # active bits\n\tunsigned hwl = hammingweight(l), hwr = hammingweight(r);\n\tif (hwl != hwr) \n\t\treturn hwl < hwr;\n\n\t// second: rate on # active bit positions\n\tuint32 bitsl = 0, bitsr = 0;\n\tfor (auto it = l.begin(); it != l.end(); ++it) \n\t\tbitsl |= *it;\n\tfor (auto it = r.begin(); it != r.end(); ++it) \n\t\tbitsr |= *it;\n\thwl = hammingweight(bitsl); \n\thwr = hammingweight(bitsr);\n\tif (hwl != hwr) \n\t\treturn hwl < hwr;\n\n\t// third: rate on maximum worddistance between active bits\n\tint fl = 0, fr = 0;\n\twhile (fl < (int)l.size() && l[fl] == 0) \n\t\t++fl;\n\twhile (fr < (int)r.size() && r[fr] == 0) \n\t\t++fr;\n\tint el = l.size()-1, er = r.size()-1;\n\twhile (el > 0 && l[el] == 0) \n\t\t--el;\n\twhile (er > 0 && r[er] == 0) \n\t\t--er;\n\tif ((el-fl) != (er-fr)) \n\t\treturn (el-fl) < (er-fr);\n\n\t// fourth: lex\n\treturn l < r;\n}\n\n\nvoid greedy_selection(const map<string,bitrel>& map_DV_bitrels, map<vector<uint32>, vector<string> >& bitrel_to_DV)\n{\n\tmap<string,bitrel> map_DV_newbitrels;\n  \n\twhile (true) \n\t{\n\t\tmap<vector<uint32>, vector<string> > bitrelcnt;\n\t\tmap<vector<uint32>, vector<string> > bitrelcnt2;\n\t\tfor (auto DVit = map_DV_bitrels.begin(); DVit != map_DV_bitrels.end(); ++DVit) \n\t\t{\n\t\t\tvector< vector<uint32> > fullspace = DVit->second.space(81); // 81 and 80 give the same results => all bitrel do not have negated version for other DV (so far)\n\t\t\tvector< vector<uint32> > selspace = map_DV_newbitrels[DVit->first].space(81);\n\t\t\tfor (auto it = fullspace.begin(); it != fullspace.end(); ++it) \n\t\t\t{\n\t\t\t\tif (!binary_search(selspace.begin(), selspace.end(), *it))\n\t\t\t\t\tbitrelcnt[*it].push_back(DVit->first);\n\t\t\t\tbitrelcnt2[*it].push_back(DVit->first);\n\t\t\t}\n\t\t}\n\n\t\tuint32 maxcnt = 0;\n\t\tfor (auto it = bitrelcnt.begin(); it != bitrelcnt.end(); ++it)\n\t\t\tif (it->second.size() > maxcnt)\n\t\t\t\tmaxcnt = it->second.size();\n\t\tif (maxcnt == 0) break;\n\n\t\tvector< vector<uint32> > maxbitrel;\n\t\tfor (auto it = bitrelcnt.begin(); it != bitrelcnt.end(); ++it)\n\t\t\tif (it->second.size() == maxcnt)\n\t\t\t\tmaxbitrel.push_back(it->first);\n\t\tstd::sort(maxbitrel.begin(), maxbitrel.end(), basis_less);\n    \n\t\tvector<uint32> newbitrel = maxbitrel.front();\n\t\tvector<string>& newbitrelDVs = bitrel_to_DV[newbitrel];\n\t\tcout << \"- \" << bitrel_to_string(newbitrel) << \": \";\n\t\tfor (auto it = bitrelcnt[newbitrel].begin(); it != bitrelcnt[newbitrel].end(); ++it) \n\t\t{\n\t\t\tcout << \" \" << *it;\n\t\t\tnewbitrelDVs.push_back(*it);\n\t\t\tmap_DV_newbitrels[*it].basis.push_back(newbitrel);\n\t\t}\n\t\tcout << \" (+\" << (bitrelcnt2[newbitrel].size()-bitrelcnt[newbitrel].size()) << \"DVs)\" << endl;\n\t\tstd::sort(newbitrelDVs.begin(), newbitrelDVs.end());\n\t}\n\n\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it) \n\t{\n\t\tbool first = true;\n\t\tfor (auto it2 = bitrel_to_DV.begin(); it2 != bitrel_to_DV.end(); ++it2)\n\t\t{\n\t\t\tif (it2 != it && it2->second.size() > 1)\n\t\t\t{\n\t\t\t\tbool ok = true;\n\t\t\t\tfor (auto it3 = it2->second.begin(); it3 != it2->second.end(); ++it3)\n\t\t\t\t{\n\t\t\t\t\tif (!binary_search(it->second.begin(), it->second.end(), *it3))\n\t\t\t\t\t{\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!ok) \n\t\t\t\t\tcontinue;\n\n\t\t\t\t// it2 is subset of it1\n\t\t\t\tif (first) \n\t\t\t\t{\n\t\t\t\t\tfirst = false;\n\t\t\t\t\tcout << bitrel_to_string(it->first) << \" (\" << it->second.size() << \") => \";\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t\tcout << \" , \";\n\t\t\t\tcout << bitrel_to_string(it2->first) << \" (\" << it2->second.size() << \")\";\n\t\t\t}\n\t\t}\n\t\tif (!first) \n\t\t\tcout << endl;\n\t}  \n}\n\nstring DVvariablename(const string& DV, const string& suffix = \"\", const string& prefix = \"DV_\") \n{\n\tstring ret = prefix + DV + suffix;\n\tsize_t pos;\n\twhile ( (pos = ret.find_first_not_of(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\")) < ret.size())\n\t\tret[pos] = '_';\n\treturn ret;\n}\n\n// returns c expression that should be evaluated as bool (i.e., zero / non-zero integer)\nstring bitrel_bool_expression(const vector<uint32>& bitrel, const string& Wname = \"W\")\n{\n\tstring ret;\n\tif ((hammingweight(bitrel) - hammingweight(bitrel[80])) != 2) \n\t\tthrow std::runtime_error(\"bitrel_bool_expression(,): expected bitrelation with only 2 active W bits\");\n\tunsigned t1 = 0,t2 = 79;\n\twhile (bitrel[t1] == 0) \n\t\t++t1;\n\twhile (bitrel[t2] == 0) \n\t\t--t2;\n\tint b1 = 0, b2 = 31;\n\twhile (0 == ((bitrel[t1]>>b1)&1)) \n\t\t++b1;\n\twhile (0 == ((bitrel[t2]>>b2)&1)) \n\t\t--b2;\n\n\t// shift W[t2] bit position b2 to bit position b1, then xor W2 and W1 and keep only bit position b1\n\tstring W1 = Wname + \"[\" + boost::lexical_cast<string>(t1) + \"]\";\n\tstring W2 = Wname + \"[\" + boost::lexical_cast<string>(t2) + \"]\";\n\n\tif (b1 > b2)\n\t\tW2 = \"(\" + W2 + \"<<\" + boost::lexical_cast<string>(b1-b2) + \")\";\n\telse if (b2 > b1)\n\t\tW2 = \"(\" + W2 + \">>\" + boost::lexical_cast<string>(b2-b1) + \")\";\n\n\tret = \"((\" + W1 + \"^\" + W2 + \") & (1<<\" + boost::lexical_cast<string>(b1) + \"))\";\n\n\tif (bitrel[80] != 0)\n\t\treturn ret;\n\telse\n\t\treturn \"(!\" + ret + \")\"; // use ! instead of ~ (e.g. ~W2) since ! can be absorbed into jz or jnz\n}\n\n\n// return c expression that if true returns 0xFFFFFFFF and else 0\nstring bitrel_c_expression(const vector<uint32>& bitrel, const string& Wname = \"W\")\n{\n\tif ((hammingweight(bitrel) - hammingweight(bitrel[80])) != 2) \n\t\tthrow std::runtime_error(\"bitrel_c_expression(,): expected bitrelation with only 2 active W bits\");\n\tunsigned t1 = 0,t2 = 79;\n\twhile (bitrel[t1] == 0) \n\t\t++t1;\n\twhile (bitrel[t2] == 0) \n\t\t--t2;\n\tint b1 = 0, b2 = 31;\n\twhile (0 == ((bitrel[t1]>>b1)&1)) \n\t\t++b1;\n\twhile (0 == ((bitrel[t2]>>b2)&1)) \n\t\t--b2;\n\n\t// shift W[t2] bit position b2 to bit position b1, then xor W2 and W1 and keep only bit position b1\n\tstring W1 = Wname + \"[\" + boost::lexical_cast<string>(t1) + \"]\";\n\tstring W2 = Wname + \"[\" + boost::lexical_cast<string>(t2) + \"]\";\n\n\tif (b1 == b2)\n\t\treturn \"(0-(((\" + W1 + \"^\" + (bitrel[80]==0?\"~\":\"\") + W2 + \")>>\" + boost::lexical_cast<string>(b1) + \")&1))\";\n\telse\n\t\treturn \"(0-(((\" + W1 + \">>\" + boost::lexical_cast<string>(b1) + \")^(\" + (bitrel[80]==0?\"~\":\"\") + W2 + \">>\" + boost::lexical_cast<string>(b2) + \"))&1))\";\n}\n\n\n// returns c expression that sets bits in the closed-range [lowbit,highbit] to 1 if true and 0 else\n// bits lower than lowbit and bits higher than highbit are undetermined (may be 0 or 1 independent of each other)\nstring bitrel_c_expression(const vector<uint32>& bitrel, unsigned lowbit, unsigned highbit, const string& Wname = \"W\")\n{\n\tif ((hammingweight(bitrel) - hammingweight(bitrel[80])) != 2) \n\t\tthrow std::runtime_error(\"bitrel_c_expression(,,,): expected bitrelation with only 2 active W bits\");\n\tunsigned t1 = 0,t2 = 79;\n\twhile (bitrel[t1] == 0) \n\t\t++t1;\n\twhile (bitrel[t2] == 0) \n\t\t--t2;\n\tunsigned b1 = 0, b2 = 31;\n\twhile (0 == ((bitrel[t1]>>b1)&1)) \n\t\t++b1;\n\twhile (0 == ((bitrel[t2]>>b2)&1)) \n\t\t--b2;\n\n\t// shift W[t2] bit position b2 to bit position b1, then xor W2 and W1 and keep only bit position b1\n\tstring W1 = Wname + \"[\" + boost::lexical_cast<string>(t1) + \"]\";\n\tstring W2 = Wname + \"[\" + boost::lexical_cast<string>(t2) + \"]\";\n\t// make b1 the lowest bitposition\n\tif (b1 > b2) {\n\t\tstd::swap(t1,t2);\n\t\tstd::swap(b1,b2);\n\t\tstd::swap(W1,W2);\n\t}\n  \n\tstring ret;\n\n\tif (lowbit == highbit) \n\t{\n\t\t// we can avoid expanding a bit to a full mask, i.e., avoiding an AND and a NEG\n\t\tif (b1 == b2) \n\t\t{\n\t\t\tret = \"(\" + W1 + \"^\"  + W2 + \")\";\n\t\t\tif (b1 < lowbit) \n\t\t\t\tret = \"(\" + ret + \"<<\" + boost::lexical_cast<string>(lowbit - b1) + \")\";\n\t\t\tif (b1 > lowbit) \n\t\t\t\tret = \"(\" + ret + \">>\" + boost::lexical_cast<string>(b1 - lowbit) + \")\";\n\t\t\treturn \"(\" + string(bitrel[80]==0?\"~\":\"\") + ret + \")\";\n\t\t}\n\t\tif (b1 < lowbit)\n\t\t\tW1 = \"(\" + W1 + \"<<\" + boost::lexical_cast<string>(lowbit - b1) + \")\";\n\t\tif (b1 > lowbit) \n\t\t\tW1 = \"(\" + W1 + \">>\" + boost::lexical_cast<string>(b1 - lowbit) + \")\";\n\t\tif (b2 < lowbit) \n\t\t\tW2 = \"(\" + W2 + \"<<\" + boost::lexical_cast<string>(lowbit - b2) + \")\";\n\t\tif (b2 > lowbit) \n\t\t\tW2 = \"(\" + W2 + \">>\" + boost::lexical_cast<string>(b2 - lowbit) + \")\";\n\t\treturn \"(\" + string(bitrel[80]==0?\"~\":\"\") + \"(\" + W1 + \"^\"  + W2 + \"))\";\n\t}  \n\n\tif (b1 <= lowbit) \n\t{\n\t\tif (b2 != b1) W2 = \"(\" + W2 + \">>\" + boost::lexical_cast<string>(b2-b1) + \")\";\n\t\t\tret = \"((\" + W1 + \"^\" + W2 + \")&(1<<\" + boost::lexical_cast<string>(b1) + \"))\";\n\t\tif (bitrel[80]==0)\n\t\t\treturn \"(\" + ret + \"-(1<<\" + boost::lexical_cast<string>(b1) + \"))\";\n\t\telse\n\t\t\treturn \"(0-\" + ret + \")\";\n\t}\n\n\tif (b1 == b2) \n\t\tret = \"(((\" + W1 + \"^\" + W2 + \")>>\" + boost::lexical_cast<string>(b1) + \")&1)\";\n\telse \n\t\tret = \"(((\" + W1 + \">>\" + boost::lexical_cast<string>(b1) + \")^(\" + W2 + \">>\" + boost::lexical_cast<string>(b2) + \"))&1)\";\n\tif (bitrel[80]==0)\n\t\treturn \"(\" + ret + \"-1)\";\n\telse\n\t\treturn \"(0-\" + ret + \")\";\n}\n\n// returns c expression that sets bits in the closed-range [lowbit,highbit] to 1 if true and 0 else\n// bits lower than lowbit and bits higher than highbit are undetermined (may be 0 or 1 independent of each other)\nstring bitrel_simd_expression(const vector<uint32>& bitrel, unsigned lowbit, unsigned highbit, const string& Wname = \"W\")\n{\n\tif ((hammingweight(bitrel) - hammingweight(bitrel[80])) != 2)\n\t\tthrow std::runtime_error(\"bitrel_c_expression(,,,): expected bitrelation with only 2 active W bits\");\n\tunsigned t1 = 0, t2 = 79;\n\twhile (bitrel[t1] == 0)\n\t\t++t1;\n\twhile (bitrel[t2] == 0)\n\t\t--t2;\n\tunsigned b1 = 0, b2 = 31;\n\twhile (0 == ((bitrel[t1] >> b1) & 1))\n\t\t++b1;\n\twhile (0 == ((bitrel[t2] >> b2) & 1))\n\t\t--b2;\n\n\t// shift W[t2] bit position b2 to bit position b1, then xor W2 and W1 and keep only bit position b1\n\tstring W1 = Wname + \"[\" + boost::lexical_cast<string>(t1)+\"]\";\n\tstring W2 = Wname + \"[\" + boost::lexical_cast<string>(t2)+\"]\";\n\t// make b1 the lowest bitposition\n\tif (b1 > b2) {\n\t\tstd::swap(t1, t2);\n\t\tstd::swap(b1, b2);\n\t\tstd::swap(W1, W2);\n\t}\n\n\tstring ret;\n\n\tif (lowbit == highbit)\n\t{\n\t\t// we can avoid expanding a bit to a full mask, i.e., avoiding an AND and a NEG\n\t\tif (b1 == b2)\n\t\t{\n\t\t\tret = \"SIMD_XOR_VV(\" + W1 + \",\" + W2 + \")\";\n\t\t\tif (b1 < lowbit)\n\t\t\t\tret = \"SIMD_SHL_V(\" + ret + \",\" + boost::lexical_cast<string>(lowbit - b1) + \")\";\n\t\t\tif (b1 > lowbit)\n\t\t\t\tret = \"SIMD_SHR_V(\" + ret + \",\" + boost::lexical_cast<string>(b1 - lowbit) + \")\";\n\t\t\tif (bitrel[80] == 0)\n\t\t\t\treturn \"SIMD_NOT_V(\" + ret + \")\";\n\t\t\treturn ret;\n\t\t}\n\t\tif (b1 < lowbit)\n\t\t\tW1 = \"SIMD_SHL_V(\" + W1 + \",\" + boost::lexical_cast<string>(lowbit - b1) + \")\";\n\t\tif (b1 > lowbit)\n\t\t\tW1 = \"SIMD_SHR_V(\" + W1 + \",\" + boost::lexical_cast<string>(b1 - lowbit) + \")\";\n\t\tif (b2 < lowbit)\n\t\t\tW2 = \"SIMD_SHL_V(\" + W2 + \",\" + boost::lexical_cast<string>(lowbit - b2) + \")\";\n\t\tif (b2 > lowbit)\n\t\t\tW2 = \"SIMD_SHR_V(\" + W2 + \",\" + boost::lexical_cast<string>(b2 - lowbit) + \")\";\n\t\treturn string(bitrel[80]==0 ? \"SIMD_NOT_V(\" : \"(\") + \"SIMD_XOR_VV(\" + W1 + \",\" + W2 + \"))\";\n\t}\n\n\tif (b1 <= lowbit)\n\t{\n\t\tif (b2 != b1) \n\t\t\tW2 = \"SIMD_SHR_V(\" + W2 + \",\" + boost::lexical_cast<string>(b2 - b1) + \")\";\n\t\tret = \"SIMD_AND_VW(SIMD_XOR_VV(\" + W1 + \",\" + W2 + \"),(1<<\" + boost::lexical_cast<string>(b1)+\"))\";\n\t\tif (bitrel[80] == 0)\n\t\t\treturn \"SIMD_SUB_VW(\" + ret + \",(1<<\" + boost::lexical_cast<string>(b1)+\"))\";\n\t\telse\n\t\t\treturn \"SIMD_NEG_V(\" + ret + \")\";\n\t}\n\n\tif (b1 == b2)\n\t\tret = \"SIMD_AND_VW(SIMD_SHR_V(SIMD_XOR_VV(\" + W1 + \",\" + W2 + \"),\" + boost::lexical_cast<string>(b1)+\"),1)\";\n\telse\n\t\tret = \"SIMD_AND_VW(SIMD_XOR_VV(SIMD_SHR_V(\" + W1 + \",\" + boost::lexical_cast<string>(b1)+\"),SIMD_SHR_V(\" + W2 + \",\" + boost::lexical_cast<string>(b2)+\")),1)\";\n\tif (bitrel[80] == 0)\n\t\treturn \"SIMD_SUB_VW(\" + ret + \",1)\";\n\telse\n\t\treturn \"SIMD_NEG_V(\" + ret + \")\";\n}\n\n\n// as a safety precaution, valid testt have zero-diff-state before and after\n// depending on implementation, one could add one additional testt either at the beginning or at the end\n\n// in libdetectcoll using step t to test means copying the state between steps t-1 and t of the original run\n// and recomputing steps t-1,...,0 backwards and steps t,...,79 forwards\nmap<string,int> find_testt(const map<string,disturbancevector>& DVs, const map<vector<uint32>, vector<string> >& bitrel_to_DV)\n{\n\tset<string> allDVs;\n\tmap<string,unsigned> DV_nrbitrel;\n\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t{\n\t\tfor (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2)\n\t\t{\n\t\t\t++DV_nrbitrel[*it2];\n\t\t\tallDVs.insert(*it2);\n\t\t}\n\t}\n\n\tmap<int,set<string> > t_count;\n\tfor (auto it = DVs.begin(); it != DVs.end(); ++it)\n\t{\n\t\tallDVs.insert(it->first);\n\t\tif (it->second.dvtype == 1)\n\t\t{\n\t\t\tfor (int t = it->second.dvk+5; t <= it->second.dvk+15; ++t)\n\t\t\t\tt_count[t].insert(it->first);\n\t\t}\n\t\telse if (it->second.dvtype == 2)\n\t\t{\n\t\t\tfor (int t = it->second.dvk+9; t <= it->second.dvk+15; ++t)\n\t\t\t\tt_count[t].insert(it->first);\n\t\t}\n\t\telse\n\t\t\tthrow std::runtime_error(\"find_testt(): unknown dv type\");\n\t}\n\n\t// find smallest set solutions\n\tmap< set<int>, double > solutionst;\n\tfor (unsigned cnt = 1 ; solutionst.size()==0 ; ++cnt)\n\t{\n\t\tvector<bool> sett(t_count.size(), false);\n\t\tfor (unsigned i = 0; i < cnt; ++i)\n\t\t\tsett[i] = true;\n\t\twhile (true)\n\t\t{\n\t\t\tset<int> ts_covered;\n\t\t\tset<string> DVs_covered;\n\t\t\tfor (unsigned i = 0; i < t_count.size(); ++i)\n\t\t\t{\n\t\t\t\tif (sett[i])\n\t\t\t\t{\n\t\t\t\t\tauto it = t_count.begin(); std::advance(it, i);\n\t\t\t\t\tts_covered.insert(it->first);\n\t\t\t\t\tDVs_covered.insert(it->second.begin(), it->second.end());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (DVs_covered == allDVs)\n\t\t\t\tsolutionst[ts_covered]=0.0;\n\t\t\t// next permutation in sett\n\t\t\tunsigned j = 0;\n\t\t\twhile (j < t_count.size() && sett[j] != true) \n\t\t\t\t++j;\n\t\t\twhile (j < t_count.size() && sett[j] != false) \n\t\t\t\t++j;\n\t\t\t// j points to the first 0 after a 1 has occured\n\t\t\tif (j >= t_count.size()) \n\t\t\t\tbreak; // no next permutation\n\t\t\t// move last 1 prior to j to j-th position\n\t\t\tsett[j] = true;\n\t\t\tsett[j-1] = false;\n\t\t\t// all other previous 1's move to the beginning\n\t\t\tunsigned k = 0;\n\t\t\tfor (unsigned l = 0; l < j - 1; ++l)\n\t\t\t{\n\t\t\t\tif (sett[l])\n\t\t\t\t{\n\t\t\t\t\tstd::swap(sett[k], sett[l]);\n\t\t\t\t\t++k;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tcout << \"Found \" << solutionst.size() << \" solutions of size \" << solutionst.begin()->first.size() << endl;\n\n\t// rate solutions\n\t// TODO\n    \n\t// return best solution\n\tset<int> solt = solutionst.begin()->first;\n\tmap<string,int> sol;\n\tfor (auto it = solt.begin(); it != solt.end(); ++it)\n\t\tfor (auto it2 = t_count[*it].begin(); it2 != t_count[*it].end(); ++it2)\n\t\t\tsol[*it2] = *it;\n\treturn sol;\n}\n\nvoid output_code_header(map<string, unsigned>& DV_to_bitpos, const map<vector<uint32>, vector<string> >& bitrel_to_DV, ostream& out_h, ostream& out_c, ostream& out_c_test)\n{\n\tunsigned dvmasksize = ((DV_to_bitpos.size() + 31) / 32);\n\n\tmap<string, disturbancevector> DVs;\n\tfor (auto it = DV_to_bitpos.begin(); it != DV_to_bitpos.end(); ++it)\n\t\tDVs.emplace(it->first, disturbancevector(it->first));\n\t// figure out distribution of testts: minimum #, balanced distribution of DVs\n\tmap<string, int> DV_testt = find_testt(DVs, bitrel_to_DV);\n\tset<int> testt;\n\tfor (auto it = DV_testt.begin(); it != DV_testt.end(); ++it)\n\t\ttestt.insert(it->second);\n\n\tout_h << \"#ifndef UBC_CHECK_H\" << endl;\n\tout_h << \"#define UBC_CHECK_H\" << endl << endl;\n\tout_h << \"#include <stdint.h>\" << endl << endl;\n\tout_h << \"#define DVMASKSIZE \" << dvmasksize << endl;\n\tout_h << \"typedef struct { int dvType; int dvK; int dvB; int testt; int maski; int maskb; uint32_t dm[80]; } dv_info_t;\" << endl;\n\tout_h << \"extern dv_info_t sha1_dvs[];\" << endl;\n\tout_h << \"void ubc_check(const uint32_t W[80], uint32_t dvmask[DVMASKSIZE]);\" << endl;\n\n\tout_h << endl;\n\tfor (auto it = testt.begin(); it != testt.end(); ++it)\n\t\tout_h << \"#define DOSTORESTATE\" << std::setw(2) << std::setfill('0') << *it << endl;\n\tout_h << endl;\n\n\tout_h << endl << \"#endif // UBC_CHECK_H\" << endl;\n\n\tstring inttype = (DV_to_bitpos.size() <= 32) ? \"uint32_t\" : \"uint64_t\";\n\tout_c\n\t\t<< \"#include <stdint.h>\" << endl\n\t\t<< \"#include \\\"ubc_check.h\\\"\" << endl\n\t\t<< endl;\n\tfor (auto it = DV_to_bitpos.begin(); it != DV_to_bitpos.end(); ++it) \n\t\tout_c << \"static const \" << inttype << \" \" << DVvariablename(it->first, \"bit\") << \" \\t= (\" << inttype << \")(1) << \" << it->second << \";\" << endl;\n\tout_c << endl;\n    \n  \n\tout_c << \"dv_info_t sha1_dvs[] = \\n{\" << endl;\n\tfor (auto it = DVs.begin(); it != DVs.end(); ++it)\n\t{\n\t\tout_c << ((it == DVs.begin())?\"  \":\", \");\n\t\tout_c << \"{\" << it->second.dvtype << \",\" << it->second.dvk << \",\" << it->second.dvb << \",\" << DV_testt[it->first] << \",\" << (DV_to_bitpos[it->first]/32) << \",\" << (DV_to_bitpos[it->first]%32) << \", { \";\n\t\tfor (int t = 0; t < 80; ++t)\n\t\t\tout_c << ((t!=0)?\",\":\"\") << \"0x\" << std::hex << std::setfill('0') << std::setw(8) << it->second.DW[t] << std::dec;\n\t\tout_c << \" } }\" << endl;\n\t}\n\tout_c << \", {0,0,0,0,0,0, {0\";\n\tfor (int i = 1; i < 80; ++i)\n\t\tout_c << \",0\";\n\tout_c << \"}}\\n};\" << endl;\n  \n\n\n\n\tout_c_test\n\t\t<< \"#include <stdint.h>\" << endl\n\t\t<< \"#include \\\"ubc_check.h\\\"\" << endl\n\t\t<< endl;\n\n\tout_c_test \n\t\t<< \"void ubc_check_verify(const uint32_t W[80], uint32_t dvmask[DVMASKSIZE])\\n{\" << endl\n\t\t<< \"\\tfor (unsigned i=0; i < DVMASKSIZE; ++i)\\n\\t\\tdvmask[i]=0xFFFFFFFF;\\n\\n\";\n\tfor (auto DVit = gl_map_DV_bitrels.begin(); DVit != gl_map_DV_bitrels.end(); ++DVit)\n\t{\n\t\tout_c_test << \"\\tif (\\t   \";\n\t\tfor (auto it = DVit->second.basis.begin(); it != DVit->second.basis.end(); ++it)\n\t\t{\n\t\t\tif (it != DVit->second.basis.begin()) \n\t\t\t\tout_c_test << \"\\t\\t|| \";\n\t\t\tout_c_test << \"(0\";\n\t\t\tfor (unsigned i = 0; i < 80; ++i)\n\t\t\t{\n\t\t\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t\t\t{\n\t\t\t\t\tif ((*it)[i] & (1 << b))\n\t\t\t\t\t{\n\t\t\t\t\t\tout_c_test << \"^((W[\" << i << \"]>>\" << b << \")&1)\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tout_c_test << \")!=\" << (((*it)[80]) ? \"1\" : \"0\") << endl;\n\t\t}  \n\t\tout_c_test << \"\\t\\t)\\n\\t\\t\\tdvmask[\" << (DV_to_bitpos[DVit->first] / 32) << \"] &= ~((uint32_t)(1<<\" << (DV_to_bitpos[DVit->first] % 32) << \"));\\n\" << endl;\n\t}\n\tout_c_test << \"}\" << endl;\n}\n\n\n\nvoid output_code_simd(const map<vector<uint32>, vector<string> >& bitrel_to_DV, ostream& out_c)\n{\n\tcout << \"Generating code...\" << endl;\n\n\tmap<string, unsigned> DV_to_bitpos;\n\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\tfor (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2)\n\t\t\tDV_to_bitpos[*it2];\n\tunsigned DVcnt = 0;\n\tfor (auto it = DV_to_bitpos.begin(); it != DV_to_bitpos.end(); ++it, ++DVcnt)\n\t\tit->second = DVcnt;\n\tif (DVcnt > 64)\n\t{\n\t\tcerr << \"Error: Integer type with more than 64 bits required...\" << endl;\n\t\treturn;\n\t}\n\tstring inttype = (DV_to_bitpos.size() <= 32) ? \"uint32_t\" : \"uint64_t\";\n\n\tout_c << \"#include \\\"ubc_check.h\\\"\" << endl;\n\tout_c << endl;\n\tfor (auto it = DV_to_bitpos.begin(); it != DV_to_bitpos.end(); ++it)\n\t\tout_c << \"static const \" << inttype << \" \" << DVvariablename(it->first, \"bit\") << \" \\t= (\" << inttype << \")(1) << \" << it->second << \";\" << endl;\n\tout_c << endl;\n\tout_c << \"void UBC_CHECK_SIMD(const SIMD_WORD* W, SIMD_WORD* dvmask)\" << endl;\n\tout_c << \"{\" << endl;\n\tout_c << \"\\tSIMD_WORD mask = SIMD_WTOV(0xFFFFFFFF);\" << endl;\n\n\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t{\n\t\tunsigned lowbit = 31, highbit = 0;\n\t\tstring DVsmask = \"(\";\n\t\tfor (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2)\n\t\t{\n\t\t\tDVsmask += (it2 == it->second.begin() ? \"\" : \"|\") + DVvariablename(*it2, \"bit\");\n\t\t\tif (DV_to_bitpos[*it2] < lowbit)\n\t\t\t\tlowbit = DV_to_bitpos[*it2];\n\t\t\tif (DV_to_bitpos[*it2] > highbit)\n\t\t\t\thighbit = DV_to_bitpos[*it2];\n\t\t}\n\t\tDVsmask += \")\";\n\t\tout_c << \"\\tmask = SIMD_AND_VV(mask, SIMD_OR_VW(\" << bitrel_simd_expression(it->first, lowbit, highbit) << \", ~\" << DVsmask << \"));\" << endl;\n\t}\n\n\tout_c << \"\\tdvmask[0]=mask;\" << endl;\n\tout_c << \"}\" << endl;;\n}\n\n\n\n\nvoid output_code_v1(const map<vector<uint32>, vector<string> >& bitrel_to_DV, ostream& out_h, ostream& out_c, ostream& out_c_test, unsigned minDVs = 1)\n{\n\tcout << \"Generating code...\" << endl;\n  \n\tmap<string, unsigned> DV_to_bitpos;\n\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\tfor (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2)\n\t\t\tDV_to_bitpos[*it2];\n\tunsigned DVcnt = 0;\n\tfor (auto it = DV_to_bitpos.begin(); it != DV_to_bitpos.end(); ++it,++DVcnt)\n\t\tit->second = DVcnt;\n\tif (DVcnt > 64) \n\t{\n\t\tcerr << \"Error: Integer type with more than 64 bits required...\" << endl;\n\t\treturn;\n\t}\n\tstring inttype = (DV_to_bitpos.size() <= 32) ? \"uint32_t\" : \"uint64_t\";\n  \n\toutput_code_header(DV_to_bitpos, bitrel_to_DV, out_h, out_c, out_c_test);\n  \n\tout_c << \"void ubc_check(const uint32_t W[80], uint32_t dvmask[\" << ((DV_to_bitpos.size()+31)/32)<< \"])\\n{\\n\\t\" << inttype << \" mask = ~((\" << inttype << \")(0));\\n\";\n  \n\t// first process all multi-DV bitrels\n\tout_c << \"\\tmask = mask\\n\";\n\t//  for (unsigned nrdvs = DVcnt; nrdvs >= minDVs; --nrdvs)\n\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\tif (it->second.size() >= minDVs)\n\t\t{\n\t\t\tunsigned lowbit = 31, highbit = 0;\n\t\t\tstring DVsmask = \"(\";\n\t\t\tfor (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) \n\t\t\t{\n\t\t\t\tDVsmask += (it2==it->second.begin()?\"\":\"|\") + DVvariablename(*it2, \"bit\");\n\t\t\t\tif (DV_to_bitpos[*it2] < lowbit) \n\t\t\t\t\tlowbit = DV_to_bitpos[*it2];\n\t\t\t\tif (DV_to_bitpos[*it2] > highbit) \n\t\t\t\t\thighbit = DV_to_bitpos[*it2];\n\t\t\t}\n\t\t\tDVsmask += \")\";\n\t\t\tout_c << \"\\t\\t & ( \" << bitrel_c_expression(it->first,lowbit,highbit) << \" | ~\" << DVsmask << \")\" << endl;\n\t\t}\n\tout_c << \"\\t\\t;\\n\\n\";\n\n\tif (minDVs > 1) \n\t\tout_c << \"if (mask) {\\n\" << endl;  \n\t// now conditionally process remaining DV-specific bitrels\n\tfor (auto DVit = DV_to_bitpos.begin(); DVit != DV_to_bitpos.end(); ++DVit) \n\t{\n\t\tunsigned bitrelcnt = 0;\n\t\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\t\tif (it->second.size() < minDVs && std::find(it->second.begin(),it->second.end(),DVit->first)!=it->second.end())\n\t\t\t\t++bitrelcnt;\n\t\tif (bitrelcnt == 0) \n\t\t\tcontinue;\n    \n\t\tout_c << \"\\tif (mask & \" << DVvariablename(DVit->first, \"bit\") << \")\\n\";\n\t\tout_c << \"\\t\\t if (\\n\";\n\t\tbool first = true;\n\t\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\t\tif (it->second.size() < minDVs && std::find(it->second.begin(),it->second.end(),DVit->first)!=it->second.end())\n\t\t\t{\n\t\t\t\tif (first) \n\t\t\t\t{\n\t\t\t\t\tout_c << \"\\t\\t\\t    \";\n\t\t\t\t\tfirst = false;\n\t\t\t\t} else\n\t\t\t\t\tout_c << \"\\t\\t\\t || \";\n\t\t\t\tout_c << \"!\" << bitrel_bool_expression(it->first) << \"\\n\";\n\t\t\t}\n\t\tout_c << \"\\t\\t )  mask &= ~\" << DVvariablename(DVit->first, \"bit\") << \";\\n\";\n\t}\n\tif (minDVs > 1) \n\t\tout_c << \"}\\n\" << endl;  \n\tif (DVcnt <= 32)\n\t\tout_c << \"\\tdvmask[0]=mask;\" << endl;\n\telse\n\t\tout_c << \"\\tdvmask[0]=(uint32_t)(mask);\\n\\tdvmask[1]=(uint32_t)(mask>>32);\" << endl;\n\tout_c << \"}\" << endl;; \n}\n\n\nvoid output_code_v2(const map<vector<uint32>, vector<string> >& bitrel_to_DV, ostream& out_h, ostream& out_c, ostream& out_c_test, double minprob = 0.5)\n{\n\tcout << \"Generating code...\" << endl;\n  \n\tmap<string, unsigned> DV_to_bitpos;\n\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\tfor (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2)\n\t\t\tDV_to_bitpos[*it2];\n\tunsigned DVcnt = 0;\n\tfor (auto it = DV_to_bitpos.begin(); it != DV_to_bitpos.end(); ++it,++DVcnt)\n\t\tit->second = DVcnt;\n\tif (DVcnt > 64) \n\t{\n\t\tcerr << \"Error: Integer type with more than 64 bits required...\" << endl;\n\t\treturn;\n\t}\n\tstring inttype = (DV_to_bitpos.size() <= 32) ? \"uint32_t\" : \"uint64_t\";\n  \n\toutput_code_header(DV_to_bitpos, bitrel_to_DV, out_h, out_c, out_c_test);\n  \n\tout_c << \"void ubc_check(const uint32_t W[80], uint32_t dvmask[\" << ((DV_to_bitpos.size()+31)/32)<< \"])\\n{\\n\\t\" << inttype << \" mask = ~((\" << inttype << \")(0));\\n\";\n  \n\t// first process all multi-DV bitrels in order from most #DVs to only 2 DVs\n\tmap<string, unsigned> DV_proc_bitrel_cnt;\n\tfor (unsigned nrdvs = DVcnt; nrdvs > 1; --nrdvs) \n\t{\n\t\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\t\tif (it->second.size() == nrdvs)\n\t\t\t{\n\t\t\t\tdouble prob_ub_est = 0.0;\n\t\t\t\tunsigned lowbit = 31, highbit = 0;\n\t\t\t\tstring DVsmask = \"(\";\n\t\t\t\tfor (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) \n\t\t\t\t{\n\t\t\t\t\tDVsmask += (it2==it->second.begin()?\"\":\"|\") + DVvariablename(*it2, \"bit\");\n\t\t\t\t\tif (DV_to_bitpos[*it2] < lowbit) \n\t\t\t\t\t\tlowbit = DV_to_bitpos[*it2];\n\t\t\t\t\tif (DV_to_bitpos[*it2] > highbit) \n\t\t\t\t\t\thighbit = DV_to_bitpos[*it2];\n\t\t\t\t\tprob_ub_est += double(1)/double(1 << DV_proc_bitrel_cnt[*it2]);\n\t\t\t\t\t++DV_proc_bitrel_cnt[*it2];\n\t\t\t\t}\n\t\t\t\tDVsmask += \")\";\n\n#if 1\n\t\t\t\tif (prob_ub_est <= minprob)\n\t\t\t\t\tout_c << \"\\tif (mask & \" + DVsmask + \")\\n\\t\";\n\t\t\t\tout_c << \"\\tmask &= (\" << bitrel_c_expression(it->first,lowbit,highbit) << \" | ~\" << DVsmask << \");\" << endl;\n#else      \n\t\t\t\tif (prob_ub_est <= minprob)\n\t\t\t\t\tout_c << \"\\tif ((mask & \" + DVsmask + \") && !\" << bitrel_bool_expression(it->first) << \")\" << endl;\n\t\t\t\telse\n\t\t\t\t\tout_c << \"\\tif (!\" << bitrel_bool_expression(it->first) << \")\" << endl;\n\t\t\t\tout_c << \"\\t\\tmask &=  ~\" + DVsmask + \";\" << endl;\n#endif\n\t\t\t}\n\t}\n\n\tout_c << \"if (mask) {\\n\" << endl;\n\t// now conditionally process remaining DV-specific bitrels\n\tfor (auto DVit = DV_to_bitpos.begin(); DVit != DV_to_bitpos.end(); ++DVit) \n\t{\n\t\tunsigned bitrelcnt = 0;\n\t\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\t\tif (it->second.size() == 1 && it->second.front() == DVit->first)\n\t\t\t\t++bitrelcnt;\n\t\tif (bitrelcnt == 0) \n\t\t\tcontinue;\n\t\tif (bitrelcnt == 1)\n\t\t{\n\t\t\tout_c << \"\\tif (mask & \" << DVvariablename(DVit->first, \"bit\") << \")\\n\";\n\t\t\tunsigned bit=DVit->second;\n\t\t\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\t\t\tif (it->second.size() == 1 && it->second.front() == DVit->first)\n\t\t\t\t\tout_c << \"\\t\\tmask &= (\" << bitrel_c_expression(it->first,bit,bit) << \" | ~\" << DVvariablename(DVit->first, \"bit\") << \");\" << endl;\n\t\t\tcontinue;\n\t\t}\n    \n\t\tout_c << \"\\tif (mask & \" << DVvariablename(DVit->first, \"bit\") << \")\\n\";\n\t\tout_c << \"\\t\\t if (\\n\";\n\t\tbool first = true;\n\t\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\t{\n\t\t\tif (it->second.size() == 1 && it->second.front() == DVit->first)\n\t\t\t{\n\t\t\t\tif (first)\n\t\t\t\t{\n\t\t\t\t\tout_c << \"\\t\\t\\t    \";\n\t\t\t\t\tfirst = false;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tout_c << \"\\t\\t\\t || \";\n\t\t\t\tout_c << \"!\" << bitrel_bool_expression(it->first) << \"\\n\";\n\t\t\t}\n\t\t}\n\t\tout_c << \"\\t\\t )  mask &= ~\" << DVvariablename(DVit->first, \"bit\") << \";\\n\";\n\t}\n\tout_c << \"}\\n\" << endl;\n\tif (DVcnt <= 32)\n\t\tout_c << \"\\tdvmask[0]=mask;\" << endl;\n\telse\n\t\tout_c << \"\\tdvmask[0]=(uint32_t)(mask);\\n\\tdvmask[1]=(uint32_t)(mask>>32);\" << endl;\n\tout_c << \"}\" << endl;; \n}\n\n\nvoid output_code_v3(const map<vector<uint32>, vector<string> >& bitrel_to_DV, ostream& out_h, ostream& out_c, ostream& out_c_test)\n{\n\tcout << \"Generating code...\" << endl;\n  \n\tmap<string, unsigned> DV_to_bitpos;\n\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\tfor (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2)\n\t\t\tDV_to_bitpos[*it2];\n\tunsigned DVcnt = 0;\n\tfor (auto it = DV_to_bitpos.begin(); it != DV_to_bitpos.end(); ++it,++DVcnt)\n\t\tit->second = DVcnt;\n\tif (DVcnt > 64) \n\t{\n\t\tcerr << \"Error: Integer type with more than 64 bits required...\" << endl;\n\t\treturn;\n\t}\n\tstring inttype = (DV_to_bitpos.size() <= 32) ? \"uint32_t\" : \"uint64_t\";\n  \n\toutput_code_header(DV_to_bitpos, bitrel_to_DV, out_h, out_c, out_c_test);\n  \n\tout_c << \"void ubc_check(const uint32_t W[80], uint32_t dvmask[\" << ((DV_to_bitpos.size()+31)/32)<< \"])\\n{\\n\\t\" << inttype << \" mask = ~((\" << inttype << \")(0));\\n\";\n  \n\t// now conditionally process remaining DV-specific bitrels\n\tfor (auto DVit = DV_to_bitpos.begin(); DVit != DV_to_bitpos.end(); ++DVit) \n\t{\n\t\tunsigned bitrelcnt = 0;\n\t\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\t\tif (std::find(it->second.begin(), it->second.end(), DVit->first) != it->second.end())\n\t\t\t\t++bitrelcnt;\n\t\tif (bitrelcnt == 0) \n\t\t\tcontinue;\n    \n\t\tout_c << \"\\t if (\\t    \";\n\t\tbool first = true;\n\t\tfor (auto it = bitrel_to_DV.begin(); it != bitrel_to_DV.end(); ++it)\n\t\t{\n\t\t\tif (std::find(it->second.begin(), it->second.end(), DVit->first) != it->second.end())\n\t\t\t{\n\t\t\t\tif (first)\n\t\t\t\t\tfirst = false;\n\t\t\t\telse\n\t\t\t\t\tout_c << \"\\t\\t || \";\n\t\t\t\tout_c << \"!\" << bitrel_bool_expression(it->first) << \"\\n\";\n\t\t\t}\n\t\t}\n\t\tout_c << \"\\t )  mask &= ~\" << DVvariablename(DVit->first, \"bit\") << \";\\n\";\n\t}\n\tif (DVcnt <= 32)\n\t\tout_c << \"\\tdvmask[0]=mask;\" << endl;\n\telse\n\t\tout_c << \"\\tdvmask[0]=(uint32_t)(mask);\\n\\tdvmask[1]=(uint32_t)(mask>>32);\" << endl;\n\tout_c << \"}\" << endl;; \n}\n\n\n\n\nint main(int argc, char** argv)\n{\n\ttry \n\t{\n\n\t\tstring ubcdir, outdir;\n\t\tvector<string> DVs;\n\t\tpo::options_description desc(\"Allowed options\");\n\t\tdesc.add_options()\n\t\t\t(\"help,h\", \"Show options\")\n\t\t\t(\"ubcdir,w\", po::value<string>(&ubcdir)->default_value(\"../data/3565\"), \"Set directory containing ubc's for each DV\")\n\t\t\t(\"outdir,o\", po::value<string>(&outdir)->default_value(\"../../lib\"), \"Set directory to output ubc_check{.c,.h,_test.c}\")\n\t\t\t(\"DV,d\", po::value< vector<string> >(&DVs), \"Select DVs (if not specified uses all DVs in workdir)\")\n\t\t\t(\"store,s\", \"Store intermediate results\")\n\t\t\t(\"load,l\", \"Load intermediate results\")\n\t\t\t;\n\t\tpo::variables_map vm;\n\t\tpo::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n\t\tpo::notify(vm);\n  \n\t\tif (vm.count(\"help\") || vm.count(\"ubcdir\")==0) \n\t\t{\n\t\t\tcout << desc << endl;\n\t\t\treturn 0;\n\t\t}\n  \n\t\tset<string> DVselection(DVs.begin(), DVs.end());\n\t\tmap<vector<uint32>, vector<string> > bitrel_to_DV;\n\n\t\tif (vm.count(\"load\")) \n\t\t{\n\t\t\tvector<string> _DVs;\n\t\t\tset<string> _DVselection;\n\t\t\tmap<string, bitrel> _gl_map_DV_bitrels;\n\t\t\tmap<vector<uint32>, vector<string> > _bitrel_to_DV;\n\t\t\ttry\n\t\t\t{\n\t\t\t\tcout << \"Loading previously stored intermediate results.\" << flush;\n\t\t\t\thc::load(_DVs, \"data_DVs\", hc::binary_archive); cout << \".\" << flush;\n\t\t\t\thc::load(_gl_map_DV_bitrels, \"data_map_DV_bitrels\", hc::binary_archive); cout << \".\" << flush;\n\t\t\t\thc::load(_DVselection, \"data_DVselection\", hc::binary_archive); cout << \".\" << flush;\n\t\t\t\thc::load(_bitrel_to_DV, \"data_bitrel_to_DV\", hc::binary_archive); cout << \".\" << flush;\n\t\t\t\tcout << \" done.\" << endl;\n\t\t\t}\n\t\t\tcatch (std::exception&)\n\t\t\t{\n\t\t\t\t_bitrel_to_DV.clear();\n\t\t\t\tcout << \" failed!\" << endl;\n\t\t\t}\n\t\t\tif (!_bitrel_to_DV.empty())\n\t\t\t{\n\t\t\t\tDVs = std::move(_DVs);\n\t\t\t\tDVselection = std::move(_DVselection);\n\t\t\t\tgl_map_DV_bitrels = std::move(_gl_map_DV_bitrels);\n\t\t\t\tbitrel_to_DV = std::move(_bitrel_to_DV);\n\t\t\t}\n\t\t} \n\n\t\tif (bitrel_to_DV.empty())\n\t\t{\n\t\t\tload_bitrels(gl_map_DV_bitrels, ubcdir, DVselection);\n  \n\t\t\tcout << \"Applying greedy selection to exploit overlap of unavoidable bit relation space between DVs...\" << endl;\n\t\t\tgreedy_selection(gl_map_DV_bitrels, bitrel_to_DV);\n\n\t\t\tif (vm.count(\"store\")) \n\t\t\t{\n\t\t\t\tcout << \"Storing intermediate results\" << flush;\n\t\t\t\thc::save(DVs, \"data_DVs\", hc::binary_archive); cout << \".\" << flush;\n\t\t\t\thc::save(gl_map_DV_bitrels, \"data_map_DV_bitrels\", hc::binary_archive); cout << \".\" << flush;\n\t\t\t\thc::save(DVselection, \"data_DVselection\", hc::binary_archive); cout << \".\" << flush;\n\t\t\t\thc::save(bitrel_to_DV, \"data_bitrel_to_DV\", hc::binary_archive); cout << \".\" << flush;\n\t\t\t\tcout << endl;\n\t\t\t}\n\t\t}\n\n\n\t\t// timings:\n\t\t// v2 (0.05) : 10.12s  // fastest\n\t\t// v1 (2)    : 12.41s  \n\t\t// v1 (1)    : 16.18s  // constant-time\n\t\t// v3        : 25.55s\n\t\tdouble totc = 0;\n\t\tfor (auto it = gl_map_DV_bitrels.begin(); it != gl_map_DV_bitrels.end(); ++it)\n\t\t{\n\t\t\tcout << it->first << \": \" << it->second.basis.size() << endl;\n\t\t\ttotc += double(1)/double(1<<it->second.basis.size());\n\t\t}\n\t\tcout << totc << \" = 2^ \" << log(totc)/log(2.0) << endl;\n  \n\n\t\tcout << \"Generating code files in directory \" << outdir << endl;\n\t\tstring c_name = outdir+\"/ubc_check.c\";\n\t\tstring h_name = outdir+\"/ubc_check.h\";\n\t\tstring c_test_name = outdir+\"/ubc_check_verify.c\";\n\t\tstring c_simd_name = outdir + \"/ubc_check_simd.cinc\";\n\n\t\tofstream ofs_c(c_name.c_str(), ios::out | ios::trunc);\n\t\tif (!ofs_c)\n\t\t\tthrow std::runtime_error(\"Could not open \" + c_name);\n\t\tofstream ofs_h(h_name.c_str(), ios::out | ios::trunc);\n\t\tif (!ofs_h)\n\t\t\tthrow std::runtime_error(\"Could not open \" + h_name);\n\t\tofstream ofs_c_test(c_test_name.c_str(), ios::out | ios::trunc);\n\t\tif (!ofs_c_test)\n\t\t\tthrow std::runtime_error(\"Could not open \" + c_test_name);\n\t\tofstream ofs_c_simd(c_simd_name.c_str(), ios::out | ios::trunc);\n\t\tif (!ofs_c_simd)\n\t\t\tthrow std::runtime_error(\"Could not open \" + c_simd_name);\n\n\t\toutput_code_simd(bitrel_to_DV, ofs_c_simd);\n\n#if 0\n\t\t//  v3\n\t\t// very stupid straightward way: just ifs per DV\n\t\t// doesn't use redundency between DV's\n\t\toutput_code_v3(bitrel_to_DV, ofs_h, ofs_c, ofs_c_test);\n#endif \n\n#if 0\n\t\t//  v1: second-fastest, constant-time if minDVs=1\n\t\t// first produces a constant-time section using bitrel with #DVs >= minDVs-parameter\n\t\t//   bitrels are ordered based on the bits involved to allow further local optimizations by the compiler\n\t\t// secondly produces a straightforward if-section like v3, per DV checks its remaining bitrels without further using redundency\n\t\t// minDVs=2 clearly optimal\n\t\tunsigned minDVs = 1;\n\t\toutput_code_v1(bitrel_to_DV, ofs_h, ofs_c, ofs_c_test, minDVs);\n#endif\n\n#if 1\n\t\t//  v2: fastest\n\t\t// first produces a constant-time section using bitrel with #DVs from high to low\n\t\t//   bitrels are only included if the estimated probability \n\t\t//   that one of its DV's is still active (after checking the previous bitrels) \n\t\t//   is at least the minprob parameter\n\t\t// secondly produces a straightforward if-section like v3, per DV checks its remaining bitrels without further using redundency\n\t\t// optimum lies between 0.16 and 0.08: 0.1\n\t\tdouble minprob = 0.1;\n\t\toutput_code_v2(bitrel_to_DV, ofs_h, ofs_c, ofs_c_test, minprob);\n#endif\n\n\t\tofs_c.close();\n\t\tofs_h.close();\n\t\tofs_c_test.close();\n\n\t} \n\tcatch (exception & e) \n\t{\n\t\tcerr << \"Exception: \" << e.what() << endl; \n\t} \n\tcatch (...) \n\t{\n\t\tcerr << \"Unknown exception\" << endl;\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "950eb214efdd2073857ce691bd719debde320547", "size": 39242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "parse_bitrel/parse_bitrel.cpp", "max_stars_repo_name": "cr-marcstevens/sha1collisiondetection-tools", "max_stars_repo_head_hexsha": "a635c71c2b88bffc0a6508fd471e6c4b937576bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-02-23T14:13:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-10T01:12:54.000Z", "max_issues_repo_path": "parse_bitrel/parse_bitrel.cpp", "max_issues_repo_name": "cr-marcstevens/sha1collisiondetection-tools", "max_issues_repo_head_hexsha": "a635c71c2b88bffc0a6508fd471e6c4b937576bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parse_bitrel/parse_bitrel.cpp", "max_forks_repo_name": "cr-marcstevens/sha1collisiondetection-tools", "max_forks_repo_head_hexsha": "a635c71c2b88bffc0a6508fd471e6c4b937576bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-02-23T15:23:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-01T23:46:44.000Z", "avg_line_length": 31.9040650407, "max_line_length": 204, "alphanum_fraction": 0.5958666735, "num_tokens": 13336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.552272944802365}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[register_box\r\n//` Show the use of the macro BOOST_GEOMETRY_REGISTER_BOX\r\n\r\n#include <iostream>\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/register/point.hpp>\r\n#include <boost/geometry/geometries/register/box.hpp>\r\n\r\nstruct my_point\r\n{\r\n    double x, y;\r\n};\r\n\r\nstruct my_box\r\n{\r\n    my_point ll, ur;\r\n};\r\n\r\n// Register the point type\r\nBOOST_GEOMETRY_REGISTER_POINT_2D(my_point, double, cs::cartesian, x, y)\r\n\r\n// Register the box type, also notifying that it is based on \"my_point\"\r\nBOOST_GEOMETRY_REGISTER_BOX(my_box, my_point, ll, ur)\r\n\r\nint main()\r\n{\r\n    my_box b = boost::geometry::make<my_box>(0, 0, 2, 2);\r\n    std::cout << \"Area: \"  << boost::geometry::area(b) << std::endl;\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[register_box_output\r\n/*`\r\nOutput:\r\n[pre\r\nArea: 4\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "6a885b01469b52404bd4c8d1a0afa7c6c9662fe1", "size": 1150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/geometries/register/box.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/doc/src/examples/geometries/register/box.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/doc/src/examples/geometries/register/box.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": 22.1153846154, "max_line_length": 80, "alphanum_fraction": 0.68, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.5522729404277186}}
{"text": "/*\n * This is part of the fl library, a C++ Bayesian filtering library\n * (https://github.com/filtering-library)\n *\n * Copyright (c) 2015 Max Planck Society,\n * \t\t\t\t Autonomous Motion Department,\n * \t\t\t     Institute for Intelligent Systems\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n */\n\n/**\n * @date 2015\n * @author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n * Max-Planck-Institute for Intelligent Systems\n */\n\n#include <gtest/gtest.h>\n\n#include <vector>\n\n#include <fl/distribution/discrete_distribution.hpp>\n#include <fl/distribution/gaussian.hpp>\n#include <fl/util/types.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n\n\nTEST(discrete_distribution, default_initialization)\n{\n    typedef Eigen::Vector3d Variate;\n    typedef fl::DiscreteDistribution<Variate> DiscreteDistribution;\n\n    fl::Real e = 0.000000001;\n\n    DiscreteDistribution distribution;\n\n    EXPECT_TRUE(distribution.size() == 1);\n    EXPECT_TRUE(distribution.dimension() == 3);\n\n    EXPECT_TRUE(std::fabs(distribution.prob_mass(0) - 1.0) < e);\n    EXPECT_TRUE(std::fabs(distribution.log_prob_mass(0)) < e);\n    EXPECT_TRUE(std::fabs(distribution.entropy()) < e);\n    EXPECT_TRUE(std::fabs(distribution.kl_given_uniform()) < e);\n}\n\n\nTEST(discrete_distribution, max)\n{\n    typedef Eigen::Matrix<int, 1, 1> Variate;\n    typedef fl::DiscreteDistribution<Variate> DiscreteDistribution;\n    typedef DiscreteDistribution::Function Function;\n    typedef std::vector<Variate> Locations;\n\n    int N_locations = 10;\n\n    // random prob mass fct\n    Function pmf = Function::Random(N_locations).abs() + 0.01;\n    pmf /= pmf.sum();\n\n    // create discrete distr\n    DiscreteDistribution discrete_distribution;\n    discrete_distribution.log_unnormalized_prob_mass(pmf.log());\n\n    for(int i = 0; i < N_locations; i++)\n        discrete_distribution.location(i)(0) = i;\n\n    int max_index;\n    pmf.maxCoeff(&max_index);\n\n    EXPECT_TRUE(discrete_distribution.max()(0) == max_index);\n}\n\n\nTEST(discrete_distribution, moments)\n{\n    typedef Eigen::Vector3d Variate;\n    typedef Eigen::Matrix3d Covariance;\n    typedef Variate::Scalar Scalar;\n    typedef fl::DiscreteDistribution<Variate> DiscreteDistribution;\n    typedef DiscreteDistribution::Function Function;\n\n    // pick some mean and covariance\n    Covariance covariance;\n    covariance  <<  4.4, 2.1, -1.3,\n                    2.2, 5.6,  1.2,\n                   -1.2, 1.9,  3.9;\n    covariance = covariance * covariance.transpose();\n\n    Variate mean;\n    mean << 2.1, 50.2, 20.1;\n\n    // create gaussian\n    fl::Gaussian<Variate> gaussian;\n    gaussian.mean(mean);\n    gaussian.covariance(covariance);\n\n    // generate a sum of delta from gaussian\n    DiscreteDistribution discrete_distribution;\n    discrete_distribution.log_unnormalized_prob_mass(Function::Zero(100000));\n\n    for(int i = 0; i < discrete_distribution.size(); i++)\n    {\n        discrete_distribution.location(i) = gaussian.sample();\n    }\n\n    // compare mean and covariance\n    Covariance covariance_delta =\n           discrete_distribution.covariance().inverse() * gaussian.covariance();\n\n    EXPECT_TRUE(covariance_delta.isApprox(Covariance::Identity(), 0.1));\n\n    EXPECT_TRUE((gaussian.square_root().inverse() *\n                             (discrete_distribution.mean()-mean)).norm() < 0.1);\n}\n\nTEST(discrete_distribution, entropy)\n{\n    typedef Eigen::Vector3d Variate;\n    typedef Variate::Scalar Scalar;\n    typedef fl::DiscreteDistribution<Variate> DiscreteDistribution;\n    typedef DiscreteDistribution::Function Function;\n\n    int N = 100000;\n\n    // check entropy of uniform distribution\n    DiscreteDistribution discrete_distribution;\n    discrete_distribution.log_unnormalized_prob_mass(Function::Zero(N));\n\n    EXPECT_TRUE(fabs(std::log(double(discrete_distribution.size()))\n                     - discrete_distribution.entropy()) < 0.0000001);\n\n    EXPECT_TRUE(fabs(discrete_distribution.kl_given_uniform()) < 0.0000001);\n\n    // check entropy of certain distribution\n    Function log_pmf = Function::Constant(N,-std::numeric_limits<double>::max());\n    log_pmf(0) = 0;\n    discrete_distribution.log_unnormalized_prob_mass(log_pmf);\n\n    EXPECT_TRUE(fabs(discrete_distribution.entropy()) < 0.0000001);\n\n    EXPECT_TRUE(fabs(std::log(double(discrete_distribution.size()))\n                     - discrete_distribution.kl_given_uniform()) < 0.0000001);\n}\n\nTEST(discrete_distribution, sampling)\n{\n    typedef Eigen::Matrix<int, 1, 1> Variate;\n    typedef fl::DiscreteDistribution<Variate> DiscreteDistribution;\n    typedef DiscreteDistribution::Function Function;\n    typedef std::vector<Variate> Locations;\n\n    int N_locations = 10;\n    int N_samples   = 1000000;\n\n    // random prob mass fct\n    Function pmf = Function::Random(N_locations).abs() + 0.01;\n    pmf /= pmf.sum();\n\n    // create discrete distr\n    DiscreteDistribution discrete_distribution;\n    discrete_distribution.log_unnormalized_prob_mass(pmf.log());\n\n    for(int i = 0; i < N_locations; i++)\n        discrete_distribution.location(i)(0) = i;\n\n    // generate empirical pmf\n    Function empirical_pmf = Function::Zero(N_locations);\n    for(int i = 0; i < N_samples; i++)\n    {\n        empirical_pmf(discrete_distribution.sample()(0)) += 1./N_samples;\n    }\n\n    // make sure that pmf and empirical pmf are similar\n    for(int i = 0; i < pmf.size(); i++)\n    {\n        EXPECT_TRUE(fabs(pmf[i] - empirical_pmf[i]) < 0.01);\n    }\n}\n\nTEST(discrete_distribution, sampling_index)\n{\n//    typedef Eigen::Matrix<int, 1, 1> Variate;\n    typedef fl::DiscreteDistribution<fl::ScalarMatrix> DiscreteDistribution;\n    typedef DiscreteDistribution::Function Function;\n\n    int N_locations = 10;\n    int N_samples   = 1000000;\n\n    // random prob mass fct\n    Function pmf = Function::Random(N_locations).abs() + 0.01;\n    pmf /= pmf.sum();\n\n    // create discrete distr\n    DiscreteDistribution discrete_distribution;\n    discrete_distribution.log_unnormalized_prob_mass(pmf.log());\n\n    for(int i = 0; i < N_locations; i++)\n        discrete_distribution.location(i) = i;\n\n\n    for(int i = 0; i < N_samples; i++)\n    {\n        int index;\n        int sample = discrete_distribution.sample(index);\n\n        EXPECT_TRUE(index == sample);\n    }\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "95052231411c7c2f92d38a0a4a3ac84c5b35e3fb", "size": 6340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distribution/discrete_distribution_test.cpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "test/distribution/discrete_distribution_test.cpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "test/distribution/discrete_distribution_test.cpp", "max_forks_repo_name": "aeolusbot-tommyliu/fl", "max_forks_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T20:55:13.000Z", "avg_line_length": 28.8181818182, "max_line_length": 81, "alphanum_fraction": 0.6878548896, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.5521957410843792}}
{"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// \u524d\u9762\u51e0\u4e2a\uff08\u5f88\u591a\uff09include\u6587\u4ef6\u5df2\u7ecf\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u4f7f\u7528\u8fc7\u4e86\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u8fd9\u91cc\u4e0d\u518d\u89e3\u91ca\u5b83\u4eec\u7684\u542b\u4e49\u3002\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// \u8fd9\u662f\u65b0\u7684\uff0c\u4f46\u662f\uff1a\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u4ece\u7ebf\u6027\u6c42\u89e3\u5668\u5f97\u5230\u4e86\u4e00\u4e9b\u4e0d\u9700\u8981\u7684\u8f93\u51fa\u3002\u5982\u679c\u6211\u4eec\u60f3\u6291\u5236\u5b83\uff0c\u6211\u4eec\u5fc5\u987b\u5305\u62ec\u8fd9\u4e2a\u6587\u4ef6\uff0c\u5e76\u5728\u7a0b\u5e8f\u7684\u67d0\u4e2a\u5730\u65b9\u6dfb\u52a0\u4e00\u884c\u5b57\uff08\u89c1\u4e0b\u9762\u7684main()\u51fd\u6570\uff09\u3002\n\n#include <deal.II/base/logstream.h> \n\n// \u6700\u540e\u4e00\u6b65\uff0c\u548c\u4ee5\u524d\u7684\u7a0b\u5e8f\u4e00\u6837\uff0c\u662f\u5c06\u6240\u6709deal.II\u7684\u7c7b\u548c\u51fd\u6570\u540d\u5bfc\u5165\u5168\u5c40\u547d\u540d\u7a7a\u95f4\u4e2d\u3002\n\nusing namespace dealii; \n// @sect3{The <code>Step4</code> class template}  \n\n// \u8fd9\u53c8\u662f\u524d\u9762\u4f8b\u5b50\u4e2d\u7684 <code>Step4</code> \u7c7b\u3002\u552f\u4e00\u4e0d\u540c\u7684\u662f\uff0c\u6211\u4eec\u73b0\u5728\u628a\u5b83\u58f0\u660e\u4e3a\u4e00\u4e2a\u5e26\u6709\u6a21\u677f\u53c2\u6570\u7684\u7c7b\uff0c\u800c\u6a21\u677f\u53c2\u6570\u5f53\u7136\u662f\u6211\u4eec\u8981\u89e3\u51b3\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u7684\u7a7a\u95f4\u7ef4\u5ea6\u3002\u5f53\u7136\uff0c\u51e0\u4e2a\u6210\u5458\u53d8\u91cf\u4e5f\u53d6\u51b3\u4e8e\u8fd9\u4e2a\u7ef4\u5ea6\uff0c\u7279\u522b\u662fTriangulation\u7c7b\uff0c\u5b83\u5fc5\u987b\u5206\u522b\u8868\u793a\u56db\u8fb9\u5f62\u6216\u516d\u9762\u4f53\u3002\u9664\u6b64\u4ee5\u5916\uff0c\u4e00\u5207\u90fd\u548c\u4ee5\u524d\u4e00\u6837\u3002\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// \u5728\u4e0b\u6587\u4e2d\uff0c\u6211\u4eec\u53c8\u58f0\u660e\u4e86\u4e24\u4e2a\u7c7b\uff0c\u8868\u793a\u53f3\u624b\u8fb9\u548c\u975e\u5747\u8d28\u7684Dirichlet\u8fb9\u754c\u503c\u3002\u4e24\u8005\u90fd\u662f\u4e00\u4e2a\u4e8c\u7ef4\u7a7a\u95f4\u53d8\u91cf\u7684\u51fd\u6570\uff0c\u6240\u4ee5\u6211\u4eec\u4e5f\u5c06\u5b83\u4eec\u58f0\u660e\u4e3a\u6a21\u677f\u3002\n\n// \u8fd9\u4e9b\u7c7b\u4e2d\u7684\u6bcf\u4e00\u4e2a\u90fd\u662f\u4ece\u4e00\u4e2a\u5171\u540c\u7684\u3001\u62bd\u8c61\u7684\u57fa\u7c7bFunction\u6d3e\u751f\u51fa\u6765\u7684\uff0c\u5b83\u58f0\u660e\u4e86\u6240\u6709\u51fd\u6570\u90fd\u5fc5\u987b\u9075\u5faa\u7684\u5171\u540c\u63a5\u53e3\u3002\u7279\u522b\u662f\uff0c\u5177\u4f53\u7684\u7c7b\u5fc5\u987b\u91cd\u8f7d <code>value</code> \u51fd\u6570\uff0c\u8be5\u51fd\u6570\u63a5\u6536\u4e8c\u7ef4\u7a7a\u95f4\u4e2d\u7684\u4e00\u4e2a\u70b9\u4f5c\u4e3a\u53c2\u6570\uff0c\u5e76\u5c06\u8be5\u70b9\u7684\u503c\u4f5c\u4e3a <code>double</code> \u53d8\u91cf\u8fd4\u56de\u3002\n\n//  <code>value</code> \u51fd\u6570\u9700\u8981\u7b2c\u4e8c\u4e2a\u53c2\u6570\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u5c06\u5176\u547d\u540d\u4e3a <code>component</code>  : \u8fd9\u53ea\u9002\u7528\u4e8e\u77e2\u91cf\u503c\u51fd\u6570\uff0c\u4f60\u53ef\u80fd\u60f3\u8bbf\u95ee\u70b9 <code>p</code> \u5904\u7684\u77e2\u91cf\u7684\u67d0\u4e2a\u5206\u91cf\u3002\u7136\u800c\uff0c\u6211\u4eec\u7684\u51fd\u6570\u662f\u6807\u91cf\u7684\uff0c\u6240\u4ee5\u6211\u4eec\u4e0d\u9700\u8981\u62c5\u5fc3\u8fd9\u4e2a\u53c2\u6570\uff0c\u5728\u51fd\u6570\u7684\u5b9e\u73b0\u4e2d\u4e5f\u4e0d\u4f1a\u4f7f\u7528\u5b83\u3002\u5728\u5e93\u7684\u5934\u6587\u4ef6\u4e2d\uff0cFunction\u57fa\u7c7b\u5bf9 <code>value</code> \u51fd\u6570\u7684\u58f0\u660e\u4e2d\uff0c\u5206\u91cf\u7684\u9ed8\u8ba4\u503c\u4e3a0\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u8bbf\u95ee\u53f3\u4fa7\u7684 <code>value</code> \u51fd\u6570\u65f6\uff0c\u53ea\u9700\u8981\u4e00\u4e2a\u53c2\u6570\uff0c\u5373\u6211\u4eec\u8981\u8bc4\u4f30\u51fd\u6570\u7684\u70b9\u3002\u7136\u540e\uff0c\u5bf9\u4e8e\u6807\u91cf\u51fd\u6570\uff0c\u53ef\u4ee5\u7b80\u5355\u5730\u7701\u7565\u5206\u91cf\u7684\u503c\u3002\n\n// \u51fd\u6570\u5bf9\u8c61\u5728\u5e93\u4e2d\u5f88\u591a\u5730\u65b9\u90fd\u6709\u4f7f\u7528\uff08\u4f8b\u5982\uff0c\u5728 step-3 \u4e2d\u6211\u4eec\u4f7f\u7528\u4e86\u4e00\u4e2a Functions::ZeroFunction \u5b9e\u4f8b\u4f5c\u4e3a VectorTools::interpolate_boundary_values) \u7684\u53c2\u6570\uff0c\u8fd9\u662f\u6211\u4eec\u5b9a\u4e49\u4e00\u4e2a\u7ee7\u627f\u81eaFunction\u7684\u65b0\u7c7b\u7684\u7b2c\u4e00\u4e2a\u6559\u7a0b\u3002\u7531\u4e8e\u6211\u4eec\u53ea\u8c03\u7528 Function::value(), \uff0c\u6211\u4eec\u53ef\u4ee5\u53ea\u7528\u4e00\u4e2a\u666e\u901a\u7684\u51fd\u6570\uff08\u8fd9\u5c31\u662f step-5 \u4e2d\u7684\u505a\u6cd5\uff09\uff0c\u4f46\u7531\u4e8e\u8fd9\u662f\u4e00\u4e2a\u6559\u7a0b\uff0c\u4e3a\u4e86\u4e3e\u4f8b\u8bf4\u660e\uff0c\u6211\u4eec\u7ee7\u627f\u4e86Function\u3002\n\ntemplate <int dim> \nclass RightHandSide : public Function<dim> \n{ \npublic: \n  virtual double value(const Point<dim> & p, \n                       const unsigned int component = 0) const override; \n}; \n\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// \u5982\u679c\u4f60\u4e0d\u719f\u6089\u4e0a\u8ff0\u51fd\u6570\u58f0\u660e\u4e2d\u7684\u5173\u952e\u5b57 \"virtual \"\u548c \"override \"\u662f\u4ec0\u4e48\u610f\u601d\uff0c\u4f60\u53ef\u80fd\u4f1a\u60f3\u770b\u770b\u4f60\u6700\u559c\u6b22\u7684C++\u4e66\u7c4d\u6216\u5728\u7ebf\u6559\u7a0b\uff0c\u5982http:www.cplusplus.com/doc/tutorial/polymorphism/ \u3002\u4ece\u672c\u8d28\u4e0a\u8bb2\uff0c\u8fd9\u91cc\u53d1\u751f\u7684\u4e8b\u60c5\u662fFunction<dim>\u662f\u4e00\u4e2a \"\u62bd\u8c61 \"\u57fa\u7c7b\uff0c\u5b83\u58f0\u660e\u4e86\u67d0\u79cd \"\u63a5\u53e3\"--\u4e00\u7ec4\u53ef\u4ee5\u5728\u8fd9\u7c7b\u5bf9\u8c61\u4e0a\u8c03\u7528\u7684\u51fd\u6570\u3002\u4f46\u5b83\u5b9e\u9645\u4e0a\u5e76\u6ca1\u6709*\u5b9e\u73b0*\u8fd9\u4e9b\u51fd\u6570\uff1a\u5b83\u53ea\u662f\u8bf4 \"Function\u5bf9\u8c61\u662f\u8fd9\u6837\u7684\"\uff0c\u4f46\u5b83\u5b9e\u9645\u4e0a\u662f\u4ec0\u4e48\u6837\u7684\u51fd\u6570\uff0c\u5219\u7559\u7ed9\u5b9e\u73b0\u4e86`value()`\u51fd\u6570\u7684\u6d3e\u751f\u7c7b\u3002\n\n// \u4ece\u53e6\u4e00\u4e2a\u7c7b\u4e2d\u6d3e\u751f\u51fa\u4e00\u4e2a\u7c7b\uff0c\u901a\u5e38\u79f0\u4e3a \"is-a \"\u5173\u7cfb\u51fd\u6570\u3002\u5728\u8fd9\u91cc\uff0c`RightHandSide`\u7c7b \"\u662f\u4e00\u4e2a \"\u51fd\u6570\u7c7b\uff0c\u56e0\u4e3a\u5b83\u5b9e\u73b0\u4e86Function\u57fa\u7c7b\u6240\u63cf\u8ff0\u7684\u63a5\u53e3\u3002(\"value() \"\u51fd\u6570\u7684\u5b9e\u9645\u5b9e\u73b0\u5728\u4e0b\u9762\u7684\u4ee3\u7801\u5757\u4e2d)\u3002\u90a3\u4e48`virtual`\u5173\u952e\u5b57\u610f\u5473\u7740 \"\u662f\u7684\uff0c\u8fd9\u91cc\u7684\u51fd\u6570\u53ef\u4ee5\u88ab\u6d3e\u751f\u7c7b\u8986\u76d6\"\uff0c\u800c`override`\u5173\u952e\u5b57\u610f\u5473\u7740 \"\u662f\u7684\uff0c\u8fd9\u5b9e\u9645\u4e0a\u662f\u4e00\u4e2a\u6211\u4eec\u77e5\u9053\u5df2\u7ecf\u88ab\u58f0\u660e\u4e3a\u57fa\u7c7b\u4e00\u90e8\u5206\u7684\u51fd\u6570\"\u3002\u8986\u76d6 \"\u5173\u952e\u5b57\u4e0d\u662f\u4e25\u683c\u5fc5\u8981\u7684\uff0c\u4f46\u5b83\u662f\u9632\u6b62\u6253\u5b57\u9519\u8bef\u7684\u4e00\u4e2a\u4fdd\u9669\u3002\u5982\u679c\u6211\u4eec\u628a\u51fd\u6570\u7684\u540d\u5b57\u6216\u4e00\u4e2a\u53c2\u6570\u7684\u7c7b\u578b\u5f04\u9519\u4e86\uff0c\u7f16\u8bd1\u5668\u4f1a\u8b66\u544a\u6211\u4eec\u8bf4\uff1a\"\u4f60\u8bf4\u8fd9\u4e2a\u51fd\u6570\u8986\u76d6\u4e86\u57fa\u7c7b\u4e2d\u7684\u4e00\u4e2a\u51fd\u6570\uff0c\u4f46\u5b9e\u9645\u4e0a\u6211\u4e0d\u77e5\u9053\u6709\u4efb\u4f55\u8fd9\u6837\u7684\u51fd\u6570\u6709\u8fd9\u4e2a\u540d\u5b57\u548c\u8fd9\u4e9b\u53c2\u6570\u3002\"\n\n// \u4f46\u56de\u5230\u8fd9\u91cc\u7684\u5177\u4f53\u6848\u4f8b\u3002\u5728\u672c\u6559\u7a0b\u4e2d\uff0c\u6211\u4eec\u9009\u62e92D\u4e2d\u7684\u51fd\u6570 $4(x^4+y^4)$ \uff0c\u6216\u80053D\u4e2d\u7684 $4(x^4+y^4+z^4)$ \u4f5c\u4e3a\u53f3\u624b\u8fb9\u3002\u6211\u4eec\u53ef\u4ee5\u7528\u7a7a\u95f4\u7ef4\u5ea6\u4e0a\u7684if\u8bed\u53e5\u6765\u5199\u8fd9\u4e2a\u533a\u522b\uff0c\u4f46\u8fd9\u91cc\u6709\u4e00\u4e2a\u7b80\u5355\u7684\u65b9\u6cd5\uff0c\u901a\u8fc7\u4f7f\u7528\u4e00\u4e2a\u77ed\u5faa\u73af\uff0c\u4e5f\u5141\u8bb8\u6211\u4eec\u5728\u4e00\u7ef4\uff08\u6216\u56db\u7ef4\uff0c\u5982\u679c\u4f60\u60f3\u8fd9\u6837\u505a\uff09\u4e2d\u4f7f\u7528\u76f8\u540c\u7684\u51fd\u6570\u3002 \u5e78\u8fd0\u7684\u662f\uff0c\u7f16\u8bd1\u5668\u5728\u7f16\u8bd1\u65f6\u5c31\u77e5\u9053\u5faa\u73af\u7684\u5927\u5c0f\uff08\u8bb0\u4f4f\uff0c\u5728\u4f60\u5b9a\u4e49\u6a21\u677f\u65f6\uff0c\u7f16\u8bd1\u5668\u4e0d\u77e5\u9053 <code>dim</code> \u7684\u503c\uff0c\u4f46\u5f53\u5b83\u540e\u6765\u9047\u5230\u8bed\u53e5\u6216\u58f0\u660e <code>RightHandSide@<2@></code> \u65f6\uff0c\u5b83\u5c06\u91c7\u53d6\u6a21\u677f\uff0c\u75282\u66ff\u6362\u6240\u6709\u51fa\u73b0\u7684dim\uff0c\u5e76\u7f16\u8bd1\u51fa\u7ed3\u679c\u51fd\u6570\uff09\u3002 \u6362\u53e5\u8bdd\u8bf4\uff0c\u5728\u7f16\u8bd1\u8fd9\u4e2a\u51fd\u6570\u7684\u65f6\u5019\uff0c\u4e3b\u4f53\u5c06\u88ab\u6267\u884c\u7684\u6b21\u6570\u662f\u5df2\u77e5\u7684\uff0c\u7f16\u8bd1\u5668\u53ef\u4ee5\u5c06\u5faa\u73af\u6240\u9700\u7684\u5f00\u9500\u964d\u5230\u6700\u4f4e\uff1b\u7ed3\u679c\u5c06\u548c\u6211\u4eec\u9a6c\u4e0a\u4f7f\u7528\u4e0a\u9762\u7684\u516c\u5f0f\u4e00\u6837\u5feb\u3002\n\n// \u6700\u540e\u8981\u6ce8\u610f\u7684\u662f\uff0c <code>Point@<dim@></code> \u8868\u793a\u4e8c\u7ef4\u7a7a\u95f4\u4e2d\u7684\u4e00\u4e2a\u70b9\uff0c\u5b83\u7684\u5404\u4e2a\u7ec4\u6210\u90e8\u5206\uff08\u5373 $x$ \u3001 $y$ \u3001...\u5750\u6807\uff09\u53ef\u4ee5\u50cfC\u548cC++\u4e2d\u4e00\u6837\u7528\uff08\uff09\u8fd0\u7b97\u7b26\u8bbf\u95ee\uff08\u4e8b\u5b9e\u4e0a\uff0c[]\u8fd0\u7b97\u7b26\u4e5f\u540c\u6837\u6709\u6548\uff09\uff0c\u7d22\u5f15\u4ece0\u5f00\u59cb\u3002\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// \u4f5c\u4e3a\u8fb9\u754c\u503c\uff0c\u6211\u4eec\u9009\u62e9\u4e8c\u7ef4\u7684 $x^2+y^2$ \uff0c\u4e09\u7ef4\u7684 $x^2+y^2+z^2$ \u3002\u8fd9\u6070\u597d\u7b49\u4e8e\u4ece\u539f\u70b9\u5230\u6211\u4eec\u60f3\u8bc4\u4f30\u51fd\u6570\u7684\u70b9\u7684\u77e2\u91cf\u7684\u5e73\u65b9\uff0c\u800c\u4e0d\u8003\u8651\u7ef4\u5ea6\u3002\u6240\u4ee5\u8fd9\u5c31\u662f\u6211\u4eec\u7684\u8fd4\u56de\u503c\u3002\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// \u63a5\u4e0b\u6765\u662f\u5229\u7528\u4e0a\u8ff0\u51fd\u6570\u7684\u7c7b\u6a21\u677f\u7684\u5b9e\u73b0\u3002\u548c\u4ee5\u524d\u4e00\u6837\uff0c\u6211\u4eec\u5c06\u628a\u6240\u6709\u4e1c\u897f\u5199\u6210\u6a21\u677f\uff0c\u8fd9\u4e9b\u6a21\u677f\u6709\u4e00\u4e2a\u5f62\u5f0f\u53c2\u6570 <code>dim</code> \uff0c\u5728\u6211\u4eec\u5b9a\u4e49\u6a21\u677f\u51fd\u6570\u65f6\uff0c\u6211\u4eec\u5047\u8bbe\u8fd9\u4e2a\u53c2\u6570\u662f\u672a\u77e5\u7684\u3002\u53ea\u6709\u5728\u4ee5\u540e\uff0c\u7f16\u8bd1\u5668\u624d\u4f1a\u53d1\u73b0 <code>Step4@<2@></code> (in the <code>main</code> \u51fd\u6570\u7684\u58f0\u660e\uff0c\u5b9e\u9645\u4e0a\uff09\uff0c\u5e76\u5728\u7f16\u8bd1\u6574\u4e2a\u7c7b\u65f6\u5c06 <code>dim</code> \u66ff\u6362\u62102\uff0c\u8fd9\u4e2a\u8fc7\u7a0b\u88ab\u79f0\u4e3a \"\u6a21\u677f\u7684\u5b9e\u4f8b\u5316\"\u3002\u8fd9\u6837\u505a\u7684\u65f6\u5019\uff0c\u5b83\u4e5f\u4f1a\u7528 <code>RightHandSide@<dim@></code> \u7684\u5b9e\u4f8b\u66ff\u6362 <code>RightHandSide@<2@></code> \uff0c\u5e76\u4ece\u7c7b\u6a21\u677f\u4e2d\u5b9e\u4f8b\u5316\u540e\u4e00\u4e2a\u7c7b\u3002\n\n// \u4e8b\u5b9e\u4e0a\uff0c\u7f16\u8bd1\u5668\u4e5f\u4f1a\u5728 <code>main()</code> \u4e2d\u627e\u5230\u4e00\u4e2a <code>Step4@<3@></code> \u58f0\u660e\u3002\u8fd9\u5c06\u5bfc\u81f4\u5b83\u518d\u6b21\u56de\u5230\u4e00\u822c\u7684 <code>Step4@<dim@></code> \u6a21\u677f\uff0c\u66ff\u6362\u6240\u6709\u51fa\u73b0\u7684 <code>dim</code> \uff0c\u8fd9\u6b21\u662f3\uff0c\u5e76\u7b2c\u4e8c\u6b21\u7f16\u8bd1\u8fd9\u4e2a\u7c7b\u3002\u6ce8\u610f\u8fd9\u4e24\u4e2a\u5b9e\u4f8b  <code>Step4@<2@></code>  \u548c  <code>Step4@<3@></code>  \u662f\u5b8c\u5168\u72ec\u7acb\u7684\u7c7b\uff1b\u5b83\u4eec\u552f\u4e00\u7684\u5171\u540c\u7279\u5f81\u662f\u5b83\u4eec\u90fd\u662f\u4ece\u540c\u4e00\u4e2a\u901a\u7528\u6a21\u677f\u4e2d\u5b9e\u4f8b\u5316\u51fa\u6765\u7684\uff0c\u4f46\u662f\u5b83\u4eec\u4e0d\u80fd\u76f8\u4e92\u8f6c\u6362\uff0c\u4f8b\u5982\uff0c\u5b83\u4eec\u6ca1\u6709\u5171\u4eab\u4ee3\u7801\uff08\u4e24\u4e2a\u5b9e\u4f8b\u90fd\u662f\u5b8c\u5168\u72ec\u7acb\u7f16\u8bd1\u7684\uff09\u3002\n\n//  @sect4{Step4::Step4}  \n\n// \u5728\u8fd9\u4e2a\u4ecb\u7ecd\u4e4b\u540e\uff0c\u8fd9\u91cc\u662f  <code>Step4</code>  \u7c7b\u7684\u6784\u9020\u51fd\u6570\u3002\u5b83\u6307\u5b9a\u4e86\u6240\u9700\u7684\u6709\u9650\u5143\u7d20\u7684\u591a\u9879\u5f0f\u7a0b\u5ea6\uff0c\u5e76\u5c06DoFHandler\u4e0e\u4e09\u89d2\u5f62\u5173\u8054\u8d77\u6765\uff0c\u5c31\u50cf\u5728\u524d\u9762\u7684\u4f8b\u5b50\u7a0b\u5e8f\u4e2d\u4e00\u6837\uff0c  step-3  \u3002\n\ntemplate <int dim> \nStep4<dim>::Step4() \n  : fe(1) \n  , dof_handler(triangulation) \n{} \n// @sect4{Step4::make_grid}  \n\n// \u7f51\u683c\u7684\u521b\u5efa\u5728\u672c\u8d28\u4e0a\u662f\u4e0e\u7ef4\u5ea6\u6709\u5173\u7684\u4e1c\u897f\u3002\u7136\u800c\uff0c\u53ea\u8981\u9886\u57df\u5728\u4e8c\u7ef4\u6216\u4e09\u7ef4\u4e2d\u8db3\u591f\u76f8\u4f3c\uff0c\u5e93\u5c31\u53ef\u4ee5\u4e3a\u4f60\u62bd\u8c61\u3002\u5728\u6211\u4eec\u7684\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u60f3\u518d\u6b21\u5728\u4e8c\u7ef4\u7684\u6b63\u65b9\u5f62 $[-1,1]\\times [-1,1]$ \u4e0a\u6c42\u89e3\uff0c\u6216\u8005\u5728\u4e09\u7ef4\u7684\u7acb\u65b9\u4f53 $[-1,1] \\times [-1,1] \\times [-1,1]$ \u4e0a\u6c42\u89e3\uff1b\u4e24\u8005\u90fd\u53ef\u4ee5\u88ab\u79f0\u4e3a GridGenerator::hyper_cube(), \uff0c\u56e0\u6b64\u6211\u4eec\u53ef\u4ee5\u5728\u4efb\u4f55\u7ef4\u5ea6\u4e0a\u4f7f\u7528\u540c\u4e00\u4e2a\u51fd\u6570\u3002\u5f53\u7136\uff0c\u5728\u4e8c\u7ef4\u548c\u4e09\u7ef4\u4e2d\u521b\u5efa\u8d85\u7acb\u65b9\u4f53\u7684\u51fd\u6570\u6709\u5f88\u5927\u7684\u4e0d\u540c\uff0c\u4f46\u8fd9\u662f\u4f60\u4e0d\u9700\u8981\u5173\u5fc3\u7684\u4e8b\u60c5\u3002\u8ba9\u5e93\u6765\u5904\u7406\u8fd9\u4e9b\u56f0\u96be\u7684\u4e8b\u60c5\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u770b\u8d77\u6765\u548c\u524d\u9762\u7684\u4f8b\u5b50\u5b8c\u5168\u4e00\u6837\uff0c\u5c3d\u7ba1\u5b83\u6267\u884c\u7684\u52a8\u4f5c\u5728\u7ec6\u8282\u4e0a\u6709\u5f88\u5927\u7684\u4e0d\u540c\uff0c\u5982\u679c <code>dim</code> \u521a\u597d\u662f3\u3002\u4ece\u7528\u6237\u7684\u89d2\u5ea6\u6765\u770b\uff0c\u552f\u4e00\u663e\u8457\u7684\u533a\u522b\u662f\u6240\u4ea7\u751f\u7684\u5355\u5143\u683c\u6570\u91cf\uff0c\u5728\u4e09\u4e2a\u7a7a\u95f4\u7ef4\u5ea6\u4e2d\u6bd4\u4e24\u4e2a\u7a7a\u95f4\u7ef4\u5ea6\u4e2d\u8981\u9ad8\u5f97\u591a\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// \u4e0e\u524d\u9762\u7684\u4f8b\u5b50\u4e0d\u540c\uff0c\u6211\u4eec\u73b0\u5728\u60f3\u4f7f\u7528\u4e00\u4e2a\u975e\u6052\u5b9a\u7684\u53f3\u4fa7\u51fd\u6570\u548c\u975e\u96f6\u8fb9\u754c\u503c\u3002\u8fd9\u4e24\u4e2a\u4efb\u52a1\u90fd\u662f\u5f88\u5bb9\u6613\u5b9e\u73b0\u7684\uff0c\u53ea\u9700\u5728\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u7ec4\u5408\u4e2d\u589e\u52a0\u51e0\u884c\u4ee3\u7801\u5373\u53ef\u3002\n\n// \u66f4\u6709\u8da3\u7684\u662f\uff0c\u6211\u4eec\u5c06\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u5411\u91cf\u7ef4\u5ea6\u72ec\u7acb\u7ec4\u88c5\u8d77\u6765\u7684\u65b9\u5f0f\uff1a\u4e0e\u4e8c\u7ef4\u7684\u60c5\u51b5\u6839\u672c\u6ca1\u6709\u533a\u522b\u3002\u7531\u4e8e\u8fd9\u4e2a\u51fd\u6570\u4e2d\u4f7f\u7528\u7684\u91cd\u8981\u5bf9\u8c61\uff08\u6b63\u4ea4\u516c\u5f0f\u3001FEValues\uff09\u4e5f\u901a\u8fc7\u6a21\u677f\u53c2\u6570\u7684\u65b9\u5f0f\u4f9d\u8d56\u4e8e\u7ef4\u5ea6\uff0c\u5b83\u4eec\u53ef\u4ee5\u4e3a\u8fd9\u4e2a\u51fd\u6570\u6240\u7f16\u8bd1\u7684\u7ef4\u5ea6\u6b63\u786e\u8bbe\u7f6e\u4e00\u5207\u3002\u901a\u8fc7\u4f7f\u7528\u6a21\u677f\u53c2\u6570\u58f0\u660e\u6240\u6709\u53ef\u80fd\u4f9d\u8d56\u4e8e\u7ef4\u5ea6\u7684\u7c7b\uff0c\u5e93\u53ef\u4ee5\u4e3a\u4f60\u5b8c\u6210\u51e0\u4e4e\u6240\u6709\u7684\u5de5\u4f5c\uff0c\u4f60\u4e0d\u9700\u8981\u5173\u5fc3\u5927\u591a\u6570\u4e8b\u60c5\u3002\n\ntemplate <int dim> \nvoid Step4<dim>::assemble_system() \n{ \n  QGauss<dim> quadrature_formula(fe.degree + 1); \n\n// \u6211\u4eec\u5e0c\u671b\u6709\u4e00\u4e2a\u975e\u6052\u5b9a\u7684\u53f3\u624b\uff0c\u6240\u4ee5\u6211\u4eec\u4f7f\u7528\u4e0a\u9762\u58f0\u660e\u7684\u7c7b\u7684\u4e00\u4e2a\u5bf9\u8c61\u6765\u751f\u6210\u5fc5\u8981\u7684\u6570\u636e\u3002\u7531\u4e8e\u8fd9\u4e2a\u53f3\u4fa7\u5bf9\u8c61\u53ea\u5728\u672c\u51fd\u6570\u4e2d\u5c40\u90e8\u4f7f\u7528\uff0c\u6240\u4ee5\u6211\u4eec\u5728\u8fd9\u91cc\u628a\u5b83\u58f0\u660e\u4e3a\u4e00\u4e2a\u5c40\u90e8\u53d8\u91cf\u3002\n\n  RightHandSide<dim> right_hand_side; \n\n// \u4e0e\u4e4b\u524d\u7684\u4f8b\u5b50\u76f8\u6bd4\uff0c\u4e3a\u4e86\u8bc4\u4f30\u975e\u6052\u5b9a\u53f3\u624b\u51fd\u6570\uff0c\u6211\u4eec\u73b0\u5728\u8fd8\u9700\u8981\u6211\u4eec\u76ee\u524d\u6240\u5728\u5355\u5143\u4e0a\u7684\u6b63\u4ea4\u70b9\uff08\u4e4b\u524d\uff0c\u6211\u4eec\u53ea\u9700\u8981FEValues\u5bf9\u8c61\u4e2d\u7684\u5f62\u72b6\u51fd\u6570\u7684\u503c\u548c\u68af\u5ea6\uff0c\u4ee5\u53ca\u6b63\u4ea4\u6743\u91cd\uff0c FEValues::JxW() \uff09\u3002\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u7ed9FEValues\u5bf9\u8c61\u6dfb\u52a0#update_quadrature_points\u6807\u5fd7\u6765\u8ba9\u5b83\u4e3a\u6211\u4eec\u505a\u4e8b\u3002\n\n  FEValues<dim> fe_values(fe, \n                          quadrature_formula, \n                          update_values | update_gradients | \n                            update_quadrature_points | update_JxW_values); \n\n// \u7136\u540e\u6211\u4eec\u518d\u6b21\u5b9a\u4e49\u4e0e\u524d\u9762\u7a0b\u5e8f\u4e2d\u76f8\u540c\u7684\u7f29\u5199\u3002\u8fd9\u4e2a\u53d8\u91cf\u7684\u503c\u5f53\u7136\u53d6\u51b3\u4e8e\u6211\u4eec\u73b0\u5728\u4f7f\u7528\u7684\u7ef4\u5ea6\uff0c\u4f46\u662fFiniteElement\u7c7b\u4e3a\u4f60\u505a\u4e86\u6240\u6709\u5fc5\u8981\u7684\u5de5\u4f5c\uff0c\u4f60\u4e0d\u9700\u8981\u5173\u5fc3\u4e0e\u7ef4\u5ea6\u6709\u5173\u7684\u90e8\u5206\u3002\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// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u53c8\u8981\u5728\u6240\u6709\u7684\u5355\u5143\u683c\u4e0a\u8fdb\u884c\u5faa\u73af\uff0c\u5e76\u6c47\u96c6\u5c40\u90e8\u8d21\u732e\u3002 \u8bf7\u6ce8\u610f\uff0c\u4e00\u4e2a\u5355\u5143\u5728\u4e24\u4e2a\u7a7a\u95f4\u7ef4\u5ea6\u4e0a\u662f\u4e00\u4e2a\u56db\u8fb9\u5f62\uff0c\u4f46\u5728\u4e09\u7ef4\u4e0a\u662f\u4e00\u4e2a\u516d\u9762\u4f53\u3002\u4e8b\u5b9e\u4e0a\uff0c <code>active_cell_iterator</code> \u7684\u6570\u636e\u7c7b\u578b\u662f\u4e0d\u540c\u7684\uff0c\u8fd9\u53d6\u51b3\u4e8e\u6211\u4eec\u6240\u5904\u7684\u7ef4\u5ea6\uff0c\u4f46\u5bf9\u5916\u754c\u6765\u8bf4\uff0c\u5b83\u4eec\u770b\u8d77\u6765\u662f\u4e00\u6837\u7684\uff0c\u4f60\u53ef\u80fd\u6c38\u8fdc\u4e0d\u4f1a\u770b\u5230\u533a\u522b\u3002\u5728\u4efb\u4f55\u60c5\u51b5\u4e0b\uff0c\u771f\u6b63\u7684\u7c7b\u578b\u662f\u901a\u8fc7\u4f7f\u7528`auto`\u6765\u9690\u85cf\u7684\u3002\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// \u73b0\u5728\u6211\u4eec\u8981\u628a\u672c\u5730\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7ec4\u5408\u8d77\u6765\u3002\u8fd9\u4e2a\u8fc7\u7a0b\u548c\u524d\u9762\u7684\u4f8b\u5b50\u5b8c\u5168\u4e00\u6837\uff0c\u4f46\u662f\u73b0\u5728\u6211\u4eec\u91cd\u65b0\u8c03\u6574\u5faa\u73af\u7684\u987a\u5e8f\uff08\u6211\u4eec\u53ef\u4ee5\u5b89\u5168\u5730\u8fd9\u6837\u505a\uff0c\u56e0\u4e3a\u5b83\u4eec\u662f\u76f8\u4e92\u72ec\u7acb\u7684\uff09\uff0c\u5e76\u5c3d\u53ef\u80fd\u5730\u5408\u5e76\u672c\u5730\u77e9\u9635\u548c\u672c\u5730\u5411\u91cf\u7684\u5faa\u73af\uff0c\u4f7f\u4e8b\u60c5\u53d8\u5f97\u66f4\u5feb\u3002\n\n// \u7ec4\u88c5\u53f3\u624b\u8fb9\u4e0e\u6211\u4eec\u5728 step-3 \u4e2d\u7684\u505a\u6cd5\u6709\u552f\u4e00\u7684\u533a\u522b\uff1a\u6211\u4eec\u6ca1\u6709\u4f7f\u7528\u503c\u4e3a1\u7684\u5e38\u6570\u53f3\u624b\u8fb9\uff0c\u800c\u662f\u4f7f\u7528\u4ee3\u8868\u53f3\u624b\u8fb9\u7684\u5bf9\u8c61\u5e76\u5728\u6b63\u4ea4\u70b9\u5bf9\u5176\u8fdb\u884c\u8bc4\u4f30\u3002\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// \u4f5c\u4e3a\u5bf9\u8fd9\u4e9b\u5faa\u73af\u7684\u6700\u540e\u8bf4\u660e\uff1a\u5f53\u6211\u4eec\u5c06\u5c40\u90e8\u8d21\u732e\u96c6\u5408\u5230 <code>cell_matrix(i,j)</code> \u65f6\uff0c\u6211\u4eec\u5fc5\u987b\u5c06\u5f62\u72b6\u51fd\u6570 $i$ \u548c $j$ \u5728\u70b9\u53f7q_index\u7684\u68af\u5ea6\u76f8\u4e58\u5e76\u4e0e\u6807\u91cf\u6743\u91cdJxW\u76f8\u4e58\u3002\u8fd9\u5c31\u662f\u5b9e\u9645\u53d1\u751f\u7684\u60c5\u51b5\u3002  <code>fe_values.shape_grad(i,q_index)</code> \u8fd4\u56de\u4e00\u4e2a <code>dim</code> \u7ef4\u5411\u91cf\uff0c\u7531 <code>Tensor@<1,dim@></code> \u5bf9\u8c61\u8868\u793a\uff0c\u5c06\u5176\u4e0e <code>fe_values.shape_grad(j,q_index)</code> \u7684\u7ed3\u679c\u76f8\u4e58\u7684\u8fd0\u7b97\u5668*\u786e\u4fdd\u4e24\u4e2a\u5411\u91cf\u7684 <code>dim</code> \u5206\u91cf\u88ab\u9002\u5f53\u6536\u7f29\uff0c\u7ed3\u679c\u662f\u4e00\u4e2a\u6807\u91cf\u6d6e\u70b9\u6570\uff0c\u7136\u540e\u4e0e\u6743\u91cd\u76f8\u4e58\u3002\u5728\u5185\u90e8\uff0c\u8fd9\u4e2a\u64cd\u4f5c\u7b26*\u786e\u4fdd\u5bf9\u5411\u91cf\u7684\u6240\u6709 <code>dim</code> \u5206\u91cf\u90fd\u80fd\u6b63\u786e\u53d1\u751f\uff0c\u65e0\u8bba <code>dim</code> \u662f2\u30013\u8fd8\u662f\u5176\u4ed6\u7a7a\u95f4\u7ef4\u5ea6\uff1b\u4ece\u7528\u6237\u7684\u89d2\u5ea6\u6765\u770b\uff0c\u8fd9\u5e76\u4e0d\u503c\u5f97\u8d39\u5fc3\uff0c\u7136\u800c\uff0c\u5982\u679c\u60f3\u72ec\u7acb\u7f16\u5199\u4ee3\u7801\u7ef4\u5ea6\uff0c\u4e8b\u60c5\u5c31\u4f1a\u7b80\u5355\u5f88\u591a\u3002\n\n// \u968f\u7740\u672c\u5730\u7cfb\u7edf\u7684\u7ec4\u88c5\uff0c\u8f6c\u79fb\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u624b\u8fb9\u7684\u5de5\u4f5c\u4e0e\u4e4b\u524d\u5b8c\u5168\u4e00\u6837\uff0c\u4f46\u5728\u8fd9\u91cc\u6211\u4eec\u518d\u6b21\u5408\u5e76\u4e86\u4e00\u4e9b\u5faa\u73af\u4ee5\u63d0\u9ad8\u6548\u7387\u3002\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// \u4f5c\u4e3a\u8fd9\u4e2a\u51fd\u6570\u7684\u6700\u540e\u4e00\u6b65\uff0c\u6211\u4eec\u5e0c\u671b\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\u62e5\u6709\u975e\u5747\u8d28\u7684\u8fb9\u754c\u503c\uff0c\u4e0e\u4e4b\u524d\u7684\u4f8b\u5b50\u4e0d\u540c\u3002\u8fd9\u662f\u4e00\u4e2a\u7b80\u5355\u7684\u4efb\u52a1\uff0c\u6211\u4eec\u53ea\u9700\u8981\u7528\u4e00\u4e2a\u63cf\u8ff0\u6211\u4eec\u60f3\u4f7f\u7528\u7684\u8fb9\u754c\u503c\u7684\u7c7b\u7684\u5bf9\u8c61\uff08\u5373\u4e0a\u9762\u58f0\u660e\u7684 <code>BoundaryValues</code> \u7c7b\uff09\u6765\u66ff\u6362\u90a3\u91cc\u4f7f\u7528\u7684 Functions::ZeroFunction \u3002\n\n// \u51fd\u6570 VectorTools::interpolate_boundary_values() \u53ea\u5bf9\u6807\u6709\u8fb9\u754c\u6307\u68070\u7684\u9762\u8d77\u4f5c\u7528\uff08\u56e0\u4e3a\u6211\u4eec\u5728\u4e0b\u9762\u7684\u7b2c\u4e8c\u4e2a\u53c2\u6570\u4e2d\u8bf4\u8be5\u51fd\u6570\u5e94\u8be5\u5bf9\u5176\u8d77\u4f5c\u7528\uff09\u3002\u5982\u679c\u6709\u7684\u9762\u7684\u8fb9\u754c\u6307\u6807\u4e0d\u662f0\uff0c\u90a3\u4e48\u51fd\u6570interpolate_boundary_values\u5c06\u5bf9\u8fd9\u4e9b\u9762\u4e0d\u8d77\u4f5c\u7528\u3002\u5bf9\u4e8e\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\u6765\u8bf4\uff0c\u4ec0\u4e48\u90fd\u4e0d\u505a\u76f8\u5f53\u4e8e\u5047\u8bbe\u5728\u8fb9\u754c\u7684\u8fd9\u4e9b\u90e8\u5206\uff0c\u96f6\u8bfa\u4f0a\u66fc\u8fb9\u754c\u6761\u4ef6\u6210\u7acb\u3002\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// \u89e3\u51b3\u7ebf\u6027\u65b9\u7a0b\u7ec4\u662f\u5728\u5927\u591a\u6570\u7a0b\u5e8f\u4e2d\u770b\u8d77\u6765\u51e0\u4e4e\u76f8\u540c\u7684\u4e8b\u60c5\u3002\u7279\u522b\u662f\uff0c\u5b83\u4e0e\u7ef4\u5ea6\u65e0\u5173\uff0c\u6240\u4ee5\u8fd9\u4e2a\u51fd\u6570\u662f\u4ece\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u9010\u5b57\u590d\u5236\u7684\u3002\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// \u4e0d\u8fc7\u6211\u4eec\u505a\u4e86\u4e00\u4e2a\u8865\u5145\uff1a\u7531\u4e8e\u6211\u4eec\u6291\u5236\u4e86\u7ebf\u6027\u6c42\u89e3\u5668\u7684\u8f93\u51fa\uff0c\u6211\u4eec\u5fc5\u987b\u624b\u5de5\u6253\u5370\u8fed\u4ee3\u6b21\u6570\u3002\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// \u8fd9\u4e2a\u51fd\u6570\u4e5f\u505a\u4e86  step-3  \u4e2d\u5404\u81ea\u7684\u5de5\u4f5c\u3002\u8fd9\u91cc\u4e5f\u6ca1\u6709\u6539\u53d8\u7ef4\u5ea6\u7684\u72ec\u7acb\u6027\u3002\n\n// \u7531\u4e8e\u7a0b\u5e8f\u5c06\u540c\u65f6\u8fd0\u884c\u62c9\u666e\u62c9\u65af\u6c42\u89e3\u5668\u76842D\u548c3D\u7248\u672c\uff0c\u6211\u4eec\u4f7f\u7528\u6587\u4ef6\u540d\u4e2d\u7684\u7ef4\u5ea6\u4e3a\u6bcf\u6b21\u8fd0\u884c\u751f\u6210\u4e0d\u540c\u7684\u6587\u4ef6\u540d\uff08\u5728\u4e00\u4e2a\u66f4\u597d\u7684\u7a0b\u5e8f\u4e2d\uff0c\u6211\u4eec\u5c06\u68c0\u67e5 <code>dim</code> \u662f\u5426\u53ef\u4ee5\u67092\u62163\u4ee5\u5916\u7684\u5176\u4ed6\u503c\uff0c\u4f46\u4e3a\u4e86\u7b80\u6d01\u8d77\u89c1\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u5ffd\u7565\u4e86\u8fd9\u4e00\u70b9\uff09\u3002\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// \u8fd9\u662f\u4e00\u4e2a\u5bf9\u6240\u6709\u4e8b\u60c5\u90fd\u6709\u6700\u9ad8\u7ea7\u522b\u63a7\u5236\u7684\u51fd\u6570\u3002\u9664\u4e86\u4e00\u884c\u989d\u5916\u7684\u8f93\u51fa\u5916\uff0c\u5b83\u4e0e\u524d\u9762\u7684\u4f8b\u5b50\u76f8\u540c\u3002\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// \u8fd9\u662f\u4e3b\u51fd\u6570\u3002\u5b83\u770b\u8d77\u6765\u4e5f\u5927\u591a\u50cf step-3 \u4e2d\u7684\u5185\u5bb9\uff0c\u4f46\u5982\u679c\u4f60\u770b\u4e0b\u9762\u7684\u4ee3\u7801\uff0c\u6ce8\u610f\u6211\u4eec\u662f\u5982\u4f55\u9996\u5148\u521b\u5efa\u4e00\u4e2a <code>Step4@<2@></code> \u7c7b\u578b\u7684\u53d8\u91cf\uff08\u8feb\u4f7f\u7f16\u8bd1\u5668\u7528 <code>dim</code> replaced by <code>2</code> \u7f16\u8bd1\u7c7b\u6a21\u677f\uff09\u5e76\u8fd0\u884c\u4e00\u4e2a2d\u6a21\u62df\uff0c\u7136\u540e\u6211\u4eec\u75283d\u505a\u6574\u4e2a\u4e8b\u60c5\u3002\n\n// \u5728\u5b9e\u8df5\u4e2d\uff0c\u8fd9\u53ef\u80fd\u4e0d\u662f\u4f60\u7ecf\u5e38\u505a\u7684\u4e8b\u60c5\uff08\u4f60\u53ef\u80fd\u8981\u4e48\u60f3\u89e3\u51b3\u4e00\u4e2a2D\u7684\u95ee\u9898\uff0c\u8981\u4e48\u60f3\u89e3\u51b3\u4e00\u4e2a3D\u7684\u95ee\u9898\uff0c\u4f46\u4e0d\u4f1a\u540c\u65f6\u89e3\u51b3\u8fd9\u4e24\u4e2a\u95ee\u9898\uff09\u3002\u7136\u800c\uff0c\u5b83\u5c55\u793a\u4e86\u4e00\u79cd\u673a\u5236\uff0c\u6211\u4eec\u53ef\u4ee5\u5728\u4e00\u4e2a\u5730\u65b9\u7b80\u5355\u5730\u6539\u53d8\u6211\u4eec\u60f3\u8981\u7684\u7ef4\u5ea6\uff0c\u4ece\u800c\u8feb\u4f7f\u7f16\u8bd1\u5668\u4e3a\u6211\u4eec\u8981\u6c42\u7684\u7ef4\u5ea6\u91cd\u65b0\u7f16\u8bd1\u72ec\u7acb\u7684\u7c7b\u6a21\u677f\u3002\u8fd9\u91cc\u7684\u91cd\u70b9\u5728\u4e8e\uff0c\u6211\u4eec\u53ea\u9700\u8981\u6539\u53d8\u4e00\u4e2a\u5730\u65b9\u3002\u8fd9\u4f7f\u5f97\u5728\u8ba1\u7b97\u901f\u5ea6\u8f83\u5feb\u76842D\u73af\u5883\u4e0b\u8c03\u8bd5\u7a0b\u5e8f\u53d8\u5f97\u975e\u5e38\u7b80\u5355\uff0c\u7136\u540e\u5c06\u4e00\u4e2a\u5730\u65b9\u5207\u6362\u52303\uff0c\u57283D\u73af\u5883\u4e0b\u8fd0\u884c\u8ba1\u7b97\u91cf\u5927\u5f97\u591a\u7684\u7a0b\u5e8f\uff0c\u8fdb\u884c \"\u771f\u5b9e \"\u7684\u8ba1\u7b97\u3002\n\n// \u8fd9\u4e24\u4e2a\u533a\u5757\u4e2d\u7684\u6bcf\u4e00\u4e2a\u90fd\u7528\u5927\u62ec\u53f7\u62ec\u8d77\u6765\uff0c\u4ee5\u786e\u4fdd <code>laplace_problem_2d</code> \u8fd9\u4e2a\u53d8\u91cf\u5728\u6211\u4eec\u7ee7\u7eed\u4e3a3D\u60c5\u51b5\u5206\u914d\u5185\u5b58\u4e4b\u524d\u5c31\u5df2\u7ecf\u8d85\u51fa\u4e86\u8303\u56f4\uff08\u5e76\u91ca\u653e\u4e86\u5b83\u6240\u6301\u6709\u7684\u5185\u5b58\uff09\u3002\u5982\u679c\u6ca1\u6709\u989d\u5916\u7684\u5927\u62ec\u53f7\uff0c <code>laplace_problem_2d</code> \u53d8\u91cf\u53ea\u4f1a\u5728\u51fd\u6570\u7ed3\u675f\u65f6\u88ab\u9500\u6bc1\uff0c\u4e5f\u5c31\u662f\u5728\u8fd0\u884c\u5b8c3d\u95ee\u9898\u540e\u88ab\u9500\u6bc1\uff0c\u800c\u4e14\u4f1a\u57283d\u8fd0\u884c\u65f6\u4e0d\u5fc5\u8981\u5730\u5360\u7528\u5185\u5b58\uff0c\u800c\u5b9e\u9645\u4f7f\u7528\u5b83\u3002\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": "#include <boost/assign/std/vector.hpp>\n#include <cmath>\n#include <cradle/geometry/distance.hpp>\n\n#include <cradle/test.hpp>\n\nusing namespace boost::assign;\nusing namespace cradle;\n\nTEST_CASE(\"point_line_segment_2d_test\")\n{\n    line_segment<2, double> ls(\n        make_vector<double>(0, 0), make_vector<double>(0, 5));\n    vector2d cp;\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(ls, make_vector<double>(1, 2), &cp), 1.);\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(0, 2));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(ls, make_vector<double>(-3, 3), &cp), 3.);\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(0, 3));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(ls, make_vector<double>(0, 7), &cp), 2.);\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(0, 5));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(ls, make_vector<double>(-3, -4), &cp), 5.);\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(0, 0));\n\n    ls = line_segment<2, double>(\n        make_vector<double>(0, 0), make_vector<double>(3, 3));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(ls, make_vector<double>(-3, -4), &cp), 5.);\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(0, 0));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(ls, make_vector<double>(3, 5), &cp), 2.);\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(3, 3));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(ls, make_vector<double>(0, 4), &cp), sqrt(8.));\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(2, 2));\n}\n\nTEST_CASE(\"point_polygon_test\")\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(0, 0), make_vector<double>(0, 6),\n            make_vector<double>(6, 6);\n        initialize(&poly.vertices, vertices);\n    }\n\n    vector2d cp;\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(poly, make_vector<double>(7, 6), &cp), 1.);\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(6, 6));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(poly, make_vector<double>(1, 4), &cp), -1.);\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(0, 4));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(poly, make_vector<double>(-1, -1), &cp), sqrt(2.));\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(0, 0));\n}\n\nTEST_CASE(\"point_polyset_test\")\n{\n    polygon2 poly, hole;\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-2, -2), make_vector<double>(-2, 2),\n            make_vector<double>(2, 2), make_vector<double>(2, -2);\n        initialize(&poly.vertices, vertices);\n    }\n    {\n        std::vector<vertex2> vertices;\n        vertices += make_vector<double>(-1, -1), make_vector<double>(-1, 1),\n            make_vector<double>(1, 1), make_vector<double>(1, -1);\n        initialize(&hole.vertices, vertices);\n    }\n    polyset area;\n    add_polygon(area, poly);\n    add_hole(area, hole);\n\n    CRADLE_CHECK_ALMOST_EQUAL(get_area(area), 12.);\n\n    REQUIRE(!is_inside(area, make_vector<double>(-3, 3)));\n    REQUIRE(!is_inside(area, make_vector<double>(0, 0)));\n    REQUIRE(is_inside(area, make_vector<double>(-1.5, 1.5)));\n\n    vector2d cp;\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(area, make_vector<double>(0.5, 0), &cp), 0.5);\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(1, 0));\n    CRADLE_CHECK_ALMOST_EQUAL(distance(area, make_vector<double>(0, 0)), 1.);\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(area, make_vector<double>(1.25, 1), &cp), -0.25);\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(1, 1));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(area, make_vector<double>(1.75, 1), &cp), -0.25);\n    CRADLE_CHECK_ALMOST_EQUAL(cp, make_vector<double>(2, 1));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(area, make_vector<double>(2.5, 1)), 0.5);\n}\n\nTEST_CASE(\"point_plane_test\")\n{\n    plane<double> plane(\n        make_vector<double>(0, 0, 0), make_vector<double>(1, 0, 0));\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(plane, make_vector<double>(0, 0, 0)), 0.);\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(plane, make_vector<double>(-7.1, 0, 0)), -7.1);\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(plane, make_vector<double>(13, 0, 0)), 13.);\n\n    plane.point = make_vector<double>(0, 0, 1);\n    plane.normal = unit(make_vector<double>(1, 0, 1));\n    double srt = std::sqrt(2.);\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(plane, make_vector<double>(0, 0, 0)), -1 / srt);\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance(plane, make_vector<double>(0, 0, 6)), 5 / srt);\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance2(plane, make_vector<double>(0, 0, 0)), -0.5);\n    CRADLE_CHECK_ALMOST_EQUAL(\n        distance2(plane, make_vector<double>(0, 0, 6)), 12.5);\n    CRADLE_CHECK_ALMOST_EQUAL(\n        absolute_distance2(plane, make_vector<double>(0, 0, 0)), 0.5);\n    CRADLE_CHECK_ALMOST_EQUAL(\n        absolute_distance2(plane, make_vector<double>(0, 0, 6)), 12.5);\n}\n", "meta": {"hexsha": "06861551ef2a360c70b3a77ecd5393195856a423", "size": 4909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/geometry/distance.cpp", "max_stars_repo_name": "mghro/astroid-core", "max_stars_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/geometry/distance.cpp", "max_issues_repo_name": "mghro/astroid-core", "max_issues_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-26T18:45:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T18:46:06.000Z", "max_forks_repo_path": "unit_tests/geometry/distance.cpp", "max_forks_repo_name": "mghro/astroid-core", "max_forks_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7615384615, "max_line_length": 77, "alphanum_fraction": 0.6559380729, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443463, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.552161473812672}}
{"text": "#include <boost/dynamic_bitset.hpp>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <cstring>\n#include <cstdlib>\n#include <climits>\n#include <cmath>\n#include <bitset>\n#include <vector>\n#include <queue>\n#include <stack>\n#include <set>\n#include <map>\n\n#define REP(i,a) for(int i=0;i<(a);i++)\n#define FOR(i,a,b) for(int i=(a);i<(b);i++)\n#define MAX(a,b) ((a)>(b)?(a):(b))\n#define MAX3(a,b,c) MAX(MAX(a,b),c)\n#define MAX4(a,b,c,d) MAX(MAX3(a,b,c),d)\n#define MIN(a,b) ((a)<(b)?(a):(b))\n#define MIN3(a,b,c) MIN(MIN(a,b),c)\n#define MIN4(a,b,c,d) MIN(MIN3(a,b,c),d)\n#define SZ size()\n#define PB push_back\n\nconst int oo = INT_MAX>>1;\nconst int N = 1000000000;\n\nusing namespace std;\nusing namespace boost;\n\ntypedef vector<int> VE;\ntypedef dynamic_bitset<> SET;\n\nvector<bool> prime(N,false);\nVE mem1(1<<10,-1);\nVE mem2(1<<10,-1);\n\nint numways(SET &s);\n\nbool good(int n) {\n    int mod;\n    SET s(0);\n    while (n != 0) {\n        mod = n%10;\n        n /= 10;\n        if (mod==0) return false;\n        if (s[mod]) return false;\n        s[mod] = true;\n    }\n    return true;\n}\n\nint possible(SET &s) {\n    unsigned long test = s.to_ulong();\n    if (mem1[test] != -1) return mem1[test];\n    VE perms;\n    int total = 0;\n    REP(i,s.SZ) if (s[i]) perms.PB(i);\n    do {\n        int num = 0;\n        REP (i,perms.SZ) num = num*10 + perms[i];\n        if (prime[num]) total++;\n    } while (next_permutation(perms.begin(),perms.end()));\n//    cout << s << \" \" << total << endl;\n    return mem1[test] = total;\n}\n\nint allsubs(SET &start, SET &cur, int i) {\n    if (i == 10) {\n        int poss = possible(cur);\n        if (poss > 0) {\n            SET diff = start-cur;\n            int ret = poss*numways(diff);\n//            cout << diff << \" \" << poss << \" \" << ret << endl;\n            return ret;\n        }\n        return 0;\n    }\n    if (!cur[i]) return allsubs(start,cur,i+1);\n    int tot = 0;\n    cur[i] = 0;\n    tot += allsubs(start,cur,i+1);\n    cur[i] = 1;\n    tot += allsubs(start,cur,i+1);\n    return tot;\n}\n\nint numways(SET &s) {\n    unsigned long test = s.to_ulong();\n    if (test == 4 || test == 8 || test == 32 || test == 128) return 1;\n    if (mem2[test] != -1) return mem2[test];\n    SET scpy = s;\n    return mem2[test] = allsubs(s,scpy,0)/2;\n}\n\nSET makeset(int p) {\n    SET s(10,0);\n    while (p != 0) {\n        s[p%10] = true;\n        p /= 10;\n    }\n    return s;\n}\n\nint main() {\n    int n;\n//    prime[0] = prime[1] = false;\n//    for (int i = 2; i*i <= N; i++) {\n//        if (!prime[i]) continue;\n//        for (int j = i<<1; j < N; j += i) prime[j] = false;\n//    }\n//    int count = 0;\n//    REP(i,N) if (prime[i] && good(i)) {\n//        cout << i << endl;\n//        count++;\n//    }\n//    cout << count << endl;\n    VE parr;\n    while (cin >> n) {\n        parr.PB(n);\n    }\n    vector<SET> arr;\n    SET digits(10,(1<<10)-2);\n//    SET next(10,0);\n    //next[6] = next[3] = next[1] = true;\n//    next[1] = next[2] = next[3] = next[5] = true;\n//    cout << numways(next) << endl;\n//    cout << numways(digits) << endl;\n    SET empty(10,0);\n    arr.PB(digits);\n    cout << parr.SZ << endl;\n    int total = 0;\n    REP(i,parr.SZ) {\n        cout << i << endl;\n        SET test = makeset(parr[i]);\n        int cursz = arr.SZ;\n        REP(j,cursz) {\n            if (test.is_subset_of(arr[j])) {\n                SET diff = arr[j]-test;\n                if (diff == empty) total++;\n                else arr.PB(diff);\n            }\n        }\n    }\n    cout << total << endl;\n    return 0;\n}\n", "meta": {"hexsha": "50cd7c725f29e4421a60a5015467876616f3307d", "size": 3499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/118_bad.cpp", "max_stars_repo_name": "kylekanos/project-euler-1", "max_stars_repo_head_hexsha": "af7089356a4cea90f8ef331cfdc65e696def6140", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/118_bad.cpp", "max_issues_repo_name": "kylekanos/project-euler-1", "max_issues_repo_head_hexsha": "af7089356a4cea90f8ef331cfdc65e696def6140", "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": "cpp/118_bad.cpp", "max_forks_repo_name": "kylekanos/project-euler-1", "max_forks_repo_head_hexsha": "af7089356a4cea90f8ef331cfdc65e696def6140", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-17T00:55:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-17T00:55:58.000Z", "avg_line_length": 23.3266666667, "max_line_length": 70, "alphanum_fraction": 0.4992855101, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5521614738126719}}
{"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 * \u23a11  2\u23a4\n * \u23a33  4\u23a6\n * yields\n * \u23a11  1  2  2\u23a4\n * \u23a21  1  2  2\u23a5\n * \u23a23  3  4  4\u23a5\n * \u23a33  3  4  4\u23a6\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\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508O\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508O\n *    o  \u250a  o    o     o    o  \u250a  o\n *       \u250a                     \u250a\n *    o  \u250a  o    o     o    o  \u250a  o\n *       O          X          O\n *    o  \u250a  o    o     o    o  \u250a  o\n *       \u250a                     \u250a\n *    o  \u250a  o    o     o    o  \u250a  o\n *       O\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508O\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508O\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 * \u23a11  2  4  5\u23a4\n * \u23a22  3  5  6\u23a5\n * \u23a21  3  6  7\u23a5\n * \u23a33  5  7  8\u23a6\n * yields\n * \u23a12  5\u23a4\n * \u23a33  7\u23a6\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\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508O\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508O\n *    o  \u250a  o    o     o    o  \u250a  o\n *       \u250a                     \u250a\n *    o  \u250a  o    o     o    o  \u250a  o\n *       O          X          O\n *    o  \u250a  o    o     o    o  \u250a  o\n *       \u250a                     \u250a\n *    o  \u250a  o    o     o    o  \u250a  o\n *       O\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508O\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508\u2508O\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": "// Copyright Sergey Nizovtsev 2016\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/core/is_a.hpp>\r\n#include <boost/hana/functional/partial.hpp>\r\n#include <boost/hana/product.hpp>\r\n#include <boost/hana/range.hpp>\r\n#include <boost/hana/traits.hpp>\r\n#include <boost/hana/transform.hpp>\r\n#include <boost/hana/tuple.hpp>\r\n#include <boost/hana/type.hpp>\r\n\r\nnamespace hana = boost::hana;\r\n\r\nint main() {\r\n    constexpr auto type = hana::type_c<int[2][3][4]>;\r\n\r\n    BOOST_HANA_CONSTANT_CHECK(\r\n        hana::is_an<hana::integral_constant_tag<size_t>>(\r\n            hana::traits::extent(type, hana::uint_c<1>)\r\n        )\r\n    );\r\n\r\n    // Check that we can multiple extents in size_t's ring\r\n    hana::product<hana::integral_constant_tag<size_t>>(\r\n        hana::transform(\r\n            hana::to_tuple(\r\n                hana::make_range(\r\n                    hana::size_c<0>,\r\n                    hana::traits::rank(type)\r\n                )\r\n            ),\r\n            hana::partial(hana::traits::extent, type)\r\n        )\r\n    );\r\n}\r\n", "meta": {"hexsha": "ad7dea53bb176f15deabbbbc7e4440c9f57c0728", "size": 1183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/test/issues/github_252.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/test/issues/github_252.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/hana/test/issues/github_252.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 30.3333333333, "max_line_length": 82, "alphanum_fraction": 0.6060862215, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5520821719303597}}
{"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\n * @brief Implementation of IntegrationElement() test for geometry objects\n * @author Anian Ruoss\n * @date   2019-02-11 17:59:17\n * @copyright MIT License\n */\n\n#include \"check_integration_element.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/LU>\n\nnamespace lf::geometry::test_utils {\n\nvoid checkIntegrationElement(const lf::geometry::Geometry &geom,\n                             const Eigen::MatrixXd &eval_points) {\n  const size_t num_points = eval_points.cols();\n  const size_t dim_local = geom.DimLocal();\n  const size_t dim_global = geom.DimGlobal();\n\n  Eigen::MatrixXd jacobians = geom.Jacobian(eval_points);\n  Eigen::VectorXd integrationElements = geom.IntegrationElement(eval_points);\n\n  EXPECT_EQ(integrationElements.rows(), num_points)\n      << \"IntegrationElement has \" << integrationElements.rows()\n      << \" rows instead of \" << num_points;\n  EXPECT_EQ(integrationElements.cols(), 1)\n      << \"IntegrationElement has \" << integrationElements.cols()\n      << \" cols instead of \" << 1;\n\n  for (int j = 0; j < num_points; ++j) {\n    Eigen::MatrixXd jacobian =\n        jacobians.block(0, j * dim_local, dim_global, dim_local);\n\n    const double integrationElement = integrationElements(j);\n    const double approx_integrationElement =\n        std::sqrt((jacobian.transpose() * jacobian).determinant());\n\n    EXPECT_FLOAT_EQ(integrationElement, approx_integrationElement)\n        << \"IntegrationElement incorrect at point \" << eval_points.col(j);\n  }\n}\n\n}  // namespace lf::geometry::test_utils\n", "meta": {"hexsha": "1b9215a507455692320893a66b4abc4316f060ed", "size": 1516, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/lf/geometry/test_utils/check_integration_element.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": "lib/lf/geometry/test_utils/check_integration_element.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": "lib/lf/geometry/test_utils/check_integration_element.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": 32.2553191489, "max_line_length": 77, "alphanum_fraction": 0.6965699208, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.5520671107914235}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix4d X = Matrix4d::Random(4,4);\nMatrix4d A = X + X.transpose();\ncout << \"Here is a random symmetric 4x4 matrix:\" << endl << A << endl;\nTridiagonalization<Matrix4d> triOfA(A);\nVector3d hc = triOfA.householderCoefficients();\ncout << \"The vector of Householder coefficients is:\" << endl << hc << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "d3ba7e9cbd204e135036d3c448ab606c03498633", "size": 454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_householderCoefficients.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_householderCoefficients.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_householderCoefficients.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": 23.8947368421, "max_line_length": 75, "alphanum_fraction": 0.6916299559, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5519686961669507}}
{"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 <frovedis.hpp>\n#include <frovedis/matrix/crs_matrix.hpp>\n\n#include <math.h>\n#include <boost/program_options.hpp>\n\nusing namespace boost;\nusing namespace frovedis;\nusing namespace std;\n\nvoid normalize_row(crs_matrix_local<double>& mat) {\n  crs_matrix_local<double> ret;\n  for(size_t r = 0; r < mat.local_num_row; r++) {\n    double sq = 0;\n    for(size_t c = mat.off[r]; c < mat.off[r+1]; c++) {\n      sq += mat.val[c] * mat.val[c];\n    }\n    double root = sqrt(sq);\n    for(size_t c = mat.off[r]; c < mat.off[r+1]; c++) {\n      mat.val[c] /= root;\n    }\n  }\n}\n\nvoid do_normalize_row(const string& input, const string& output, bool binary) {\n  if(binary) {\n    time_spent t(DEBUG);\n    auto mat = make_crs_matrix_loadbinary<double>(input);\n    t.show(\"load matrix: \");\n    mat.data.mapv(normalize_row);\n    t.show(\"normalize time: \");\n    mat.savebinary(output);\n    t.show(\"save: \");\n  } else {\n    time_spent t(DEBUG);\n    auto mat = make_crs_matrix_load<double>(input);\n    t.show(\"load matrix: \");\n    mat.data.mapv(normalize_row);\n    t.show(\"normalize time: \");\n    mat.save(output);\n    t.show(\"save: \");\n  }\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\", \"print help\")\n    (\"input,i\", value<string>(), \"input matrix file\")\n    (\"output,o\", value<string>(), \"output matrix file\")\n    (\"binary,b\", \"use binary input/output\");\n\n  variables_map argmap;\n  store(command_line_parser(argc,argv).options(opt).allow_unregistered().\n        run(), argmap);\n  notify(argmap);\n\n  string input, output;\n  bool binary = false;\n  \n  if(argmap.count(\"help\")){\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"input\")){\n    input = argmap[\"input\"].as<string>();\n  } else {\n    cerr << \"input matrix file is not specified\" << endl;\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"output\")){\n    output = argmap[\"output\"].as<string>();\n  } else {\n    cerr << \"output matrix file is not specified\" << endl;\n    cerr << opt << endl;\n    exit(1);\n  }\n\n  if(argmap.count(\"binary\")){\n    binary = true;\n  }\n  do_normalize_row(input, output, binary);\n}\n", "meta": {"hexsha": "42519619e9f5275e572385c5a0bcd03c8ae54e7d", "size": 2208, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/document_matrix/normalize_row.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/document_matrix/normalize_row.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/document_matrix/normalize_row.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": 24.2637362637, "max_line_length": 79, "alphanum_fraction": 0.6177536232, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5519686793572177}}
{"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/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_AVERAGE_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_AVERAGE_HPP_INCLUDED\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/function/bitwise_xor.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/plus.hpp>\n#include <boost/simd/function/shift_right.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( average_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::arithmetic_<A0> >\n                          , bd::scalar_< bd::arithmetic_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      return bitwise_and(a0, a1)+shift_right(bitwise_xor(a0, a1),1);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( average_\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      return fma(a0,Half<A0>(),a1*Half<A0>());\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "2466653e7e6bfd83272587db490aed8ba4af50c1", "size": 1897, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/average.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/scalar/function/average.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/scalar/function/average.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 33.2807017544, "max_line_length": 100, "alphanum_fraction": 0.5477069056, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800692021119887, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5519215125836989}}
{"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": "#pragma once\n\n#include <iostream>   //cout screen output\n#include <math.h>\n#include <Eigen/Dense>\n\n//debugging purposes\n#define DEBUGGING // compute manually the vector cross product\n#define DEBUG_NORM_ERROR 0.0005\n\n\n// gravity values\n#define G_EARTH 9.80\n#define G_EARTH_DOUBLE 2*G_EARTH\n#define G_EARTH_SQUARED G_EARTH*G_EARTH\n\n// roll pitch and yaw\n#define ROLL       0\n#define PITCH      1\n#define YAW        2\n\nnamespace complementary_filter\n{\n\n//Convert an error rotation vector into a quaternion \nvoid vec2quat(const Eigen::Vector3d& vec, Eigen::Quaterniond& quat);\n\n//Convert a quaternion into an error rotation vector\nvoid quat2vec(const Eigen::Quaterniond& quat, Eigen::Ref<Eigen::Vector3d>& vec);\n\n}\n", "meta": {"hexsha": "b2e48fa8f4c049ec0156b4fab4213b72a02ae7dc", "size": 711, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/complementary_filter/utilities.hpp", "max_stars_repo_name": "fabien-colonnier/IMU_complementary_filter", "max_stars_repo_head_hexsha": "05b43d2312557060e46cd8bde30c1bd24008a581", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/complementary_filter/utilities.hpp", "max_issues_repo_name": "fabien-colonnier/IMU_complementary_filter", "max_issues_repo_head_hexsha": "05b43d2312557060e46cd8bde30c1bd24008a581", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/complementary_filter/utilities.hpp", "max_forks_repo_name": "fabien-colonnier/IMU_complementary_filter", "max_forks_repo_head_hexsha": "05b43d2312557060e46cd8bde30c1bd24008a581", "max_forks_repo_licenses": ["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.21875, "max_line_length": 80, "alphanum_fraction": 0.7510548523, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5519214994703951}}
{"text": "/* vim:set ts=3 sw=3 sts=3 et: */\n/**\n * \\file       log2.cpp\n * \\brief      Test cases for base-2 integer log algorithm.\n * \\author     Marcus Holland-Moritz (marcus@last.fm)\n * \\copyright  Copyright \u00a9 2008-2013 Last.fm Limited\n *\n * This file is part of libmoost.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without restriction,\n * including without limitation the rights to use, copy, modify, merge,\n * publish, distribute, sublicense, and/or sell copies of the Software,\n * and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include <boost/test/unit_test.hpp>\n#include <boost/cstdint.hpp>\n\n#include \"../../include/moost/math/integer/log2.hpp\"\n\nusing namespace moost;\n\nBOOST_AUTO_TEST_SUITE(int_log2_test)\n\nBOOST_AUTO_TEST_CASE(int_log2_test)\n{\n   BOOST_CHECK_EQUAL(math::integer::log2(1U), 0);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(1U), 0);\n\n   BOOST_CHECK_EQUAL(math::integer::log2(2U), 1);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(2U), 1);\n\n   BOOST_CHECK_EQUAL(math::integer::log2(3U), 1);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(3U), 1);\n\n   BOOST_CHECK_EQUAL(math::integer::log2(4U), 2);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(4U), 2);\n\n   BOOST_CHECK_EQUAL(math::integer::log2(65535U), 15);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(65535U), 15);\n\n   BOOST_CHECK_EQUAL(math::integer::log2(65535UL), 15);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(65535UL), 15);\n\n   BOOST_CHECK_EQUAL(math::integer::log2(65536UL), 16);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(65536UL), 16);\n\n   BOOST_CHECK_EQUAL(math::integer::log2(65537UL), 16);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(65537UL), 16);\n\n   BOOST_CHECK_EQUAL(math::integer::log2(0xFFFFFFFFUL), 31);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(0xFFFFFFFFUL), 31);\n\n   BOOST_CHECK_EQUAL(math::integer::log2(UINT64_C(0xFFFFFFFF)), 31);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(UINT64_C(0xFFFFFFFF)), 31);\n\n   BOOST_CHECK_EQUAL(math::integer::log2(UINT64_C(0x100000000)), 32);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(UINT64_C(0x100000000)), 32);\n\n   BOOST_CHECK_EQUAL(math::integer::log2(UINT64_C(0x100000001)), 32);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(UINT64_C(0x100000001)), 32);\n\n   BOOST_CHECK_EQUAL(math::integer::log2(UINT64_C(0xFFFFFFFFFFFFFFFF)), 63);\n   BOOST_CHECK_EQUAL(math::integer::log2_compat(UINT64_C(0xFFFFFFFFFFFFFFFF)), 63);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "42f9e2cf800a21a4d13882c1812e6e585a8faaf8", "size": 3246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/log2.cpp", "max_stars_repo_name": "lastfm/libmoost", "max_stars_repo_head_hexsha": "895db7cc5468626f520971648741488c373c5cff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2015-02-22T17:15:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T02:24:41.000Z", "max_issues_repo_path": "test/math/log2.cpp", "max_issues_repo_name": "lastfm/libmoost", "max_issues_repo_head_hexsha": "895db7cc5468626f520971648741488c373c5cff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/log2.cpp", "max_forks_repo_name": "lastfm/libmoost", "max_forks_repo_head_hexsha": "895db7cc5468626f520971648741488c373c5cff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T04:35:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:46:32.000Z", "avg_line_length": 39.1084337349, "max_line_length": 83, "alphanum_fraction": 0.7452248922, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5519214892494558}}
{"text": "#include \"ScalePyramid.hpp\"\n#include <Danvil/Tools/MoreMath.h>\n#include <boost/assert.hpp>\n#include <iostream>\n//----------------------------------------------------------------------------//\nnamespace density {\n//----------------------------------------------------------------------------//\n\nEigen::MatrixXf SumMipMapWithBlackBorder(const Eigen::MatrixXf& img_big)\n{\n\tsize_t w_big = img_big.rows();\n\tsize_t h_big = img_big.cols();\n\t// the computed mipmap will have 2^i size\n\tunsigned int size = Danvil::MoreMath::P2Ceil(std::max(w_big, h_big));\n\tEigen::MatrixXf img_small(size / 2, size / 2);\n\timg_small.fill({0.0f});\n\t// only the part where at least one of the four pixels lies in the big image is iterated\n\t// the rest was set to 0 with the fill op\n\tsize_t w_small = w_big / 2 + ((w_big % 2 == 0) ? 0 : 1);\n\tsize_t h_small = h_big / 2 + ((h_big % 2 == 0) ? 0 : 1);\n\tfor(size_t y = 0; y < h_small; y++) {\n\t\tsize_t y_big = y * 2;\n\t\tfor(size_t x = 0; x < w_small; x++) {\n\t\t\tsize_t x_big = x * 2;\n\t\t\t// We sum over all four pixels in the big image (if they are valid).\n\t\t\t// May by invalid because the big image is considered to be enlarged\n\t\t\t// to have a size of 2^i.\n\t\t\tfloat sum = 0.0f;\n\t\t\t// Since we only test the part where at least one pixel is in also in the big image\n\t\t\t// we do not need to test that (x_big,y_big) is a valid pixel in the big image.\n\t\t\tconst float* p_big = &img_big(x_big, y_big);\n\t\t\tsum += *(p_big);\n\t\t\tif(x_big + 1 < w_big) {\n\t\t\t\tsum += *(p_big + 1);\n\t\t\t}\n\t\t\tif(y_big + 1 < h_big) {\n\t\t\t\tsum += *(p_big + w_big);\n\t\t\t\tif(x_big + 1 < w_big) {\n\t\t\t\t\tsum += *(p_big + w_big + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\timg_small(x, y) = sum;\n\t\t}\n\t}\n\treturn img_small;\n}\n\nEigen::MatrixXf ScaleUp(const Eigen::MatrixXf& img_small, const unsigned int S)\n{\n\tif(S == 0) {\n\t\treturn Eigen::MatrixXf::Zero(0,0);\n\t}\n\tif(S == 1) {\n\t\treturn img_small;\n\t}\n\t// size of original image\n\tconst unsigned int w_sma = img_small.rows();\n\tconst unsigned int h_sma = img_small.cols();\n\t// size of scaled up image\n\tconst unsigned int w_big = w_sma * S;\n\tconst unsigned int h_big = h_sma * S;\n\tEigen::MatrixXf img_big(w_big, h_big);\n\tfor(unsigned int y=0; y<h_sma; ++y) {\n\t\tconst unsigned int y_big = S*y;\n\t\tfor(unsigned int x=0; x<w_sma; ++x) {\n\t\t\tconst unsigned int x_big = S*x;\n\t\t\tconst float val = img_small(x, y);\n\t\t\tfor(unsigned int i=0; i<S; ++i) {\n\t\t\t\tfor(unsigned int j=0; j<S; ++j) {\n\t\t\t\t\timg_big(x_big+j, y_big+i) = val;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn img_big;\n}\n\nstd::vector<Eigen::MatrixXf> ComputeMipmaps(const Eigen::MatrixXf& img, unsigned int min_size)\n{\n\t// find number of required mipmap level\n\tunsigned int max_size = std::max(img.rows(), img.cols());\n\tint n_mipmaps = Danvil::MoreMath::PowerOfTwoExponent(max_size);\n\tn_mipmaps -= Danvil::MoreMath::PowerOfTwoExponent(min_size);\n\tBOOST_ASSERT(n_mipmaps >= 1);\n\tstd::vector<Eigen::MatrixXf> mipmaps(n_mipmaps);\n\tmipmaps[0] = SumMipMapWithBlackBorder(img);\n\t// create remaining mipmaps\n\tfor(unsigned int i=1; i<n_mipmaps; i++) {\n\t\tBOOST_ASSERT(mipmaps[i-1].rows() == mipmaps[i-1].cols());\n\t\tBOOST_ASSERT(mipmaps[i-1].rows() >= 1);\n\t\tmipmaps[i] = SumMipMap<2>(mipmaps[i - 1]);\n//\t\tstd::cout << std::accumulate(mipmaps[i].begin(), mipmaps[i].end(), 0.0f, [](float sum, float x) { return sum + x; }) << std::endl;\n\t}\n\treturn mipmaps;\n}\n\nstd::vector<Eigen::MatrixXf> ComputeMipmapsLevels(const Eigen::MatrixXf& img, unsigned int n_mipmaps)\n{\n\t// find number of required mipmap level\n\tunsigned int max_size = std::max(img.rows(), img.cols());\n\tBOOST_ASSERT(n_mipmaps >= 1);\n\tstd::vector<Eigen::MatrixXf> mipmaps(n_mipmaps);\n\tmipmaps[0] = SumMipMapWithBlackBorder(img);\n\t// create remaining mipmaps\n\tfor(unsigned int i=1; i<n_mipmaps; i++) {\n\t\tBOOST_ASSERT(mipmaps[i-1].rows() == mipmaps[i-1].cols());\n\t\tBOOST_ASSERT(mipmaps[i-1].rows() >= 1);\n\t\tmipmaps[i] = SumMipMap<2>(mipmaps[i - 1]);\n//\t\tstd::cout << std::accumulate(mipmaps[i].begin(), mipmaps[i].end(), 0.0f, [](float sum, float x) { return sum + x; }) << std::endl;\n\t}\n\treturn mipmaps;\n}\n\nstd::vector<Eigen::MatrixXf> ComputeMipmaps640x480(const Eigen::MatrixXf& img)\n{\n\t// 640 = 4*32*5\n\t// 480 = 3*32*5\n\t// 32 = 2^5\n\tif(img.rows() != 640 || img.cols() != 480) {\n\t\tthrow std::runtime_error(\"ERROR: ComputeMipmaps640x480 required size 640x480!\");\n\t}\n\tstd::vector<Eigen::MatrixXf> v(6);\n\tv[0] = SumMipMap<5>(img);\n\tfor(unsigned int i=0; i<5; i++) {\n\t\tv[i+1] = SumMipMap<2>(v[i]);\n\t}\n\treturn v;\n}\n\nstd::vector<std::pair<Eigen::MatrixXf,Eigen::MatrixXf>> ComputeMipmapsWithAbs(const Eigen::MatrixXf& img, unsigned int min_size)\n{\n\t// find number of required mipmap level\n\tunsigned int max_size = std::max(img.rows(), img.cols());\n\tint n_mipmaps = Danvil::MoreMath::PowerOfTwoExponent(max_size);\n\tn_mipmaps -= Danvil::MoreMath::PowerOfTwoExponent(min_size);\n\tBOOST_ASSERT(n_mipmaps >= 1);\n\tstd::vector<std::pair<Eigen::MatrixXf,Eigen::MatrixXf>> mipmaps(n_mipmaps + 1);\n\tmipmaps[0].first = img;\n\tmipmaps[0].second = img.cwiseAbs();\n\tmipmaps[1].first = SumMipMapWithBlackBorder(mipmaps[0].first);\n\tmipmaps[1].second = SumMipMapWithBlackBorder(mipmaps[0].second);\n\tfor(unsigned int i=2; i<=n_mipmaps; i++) {\n\t\t//BOOST_ASSERT(mipmaps[i-1].width() == mipmaps[i-1].height());\n\t\t//BOOST_ASSERT(mipmaps[i-1].width() >= 1);\n\t\tmipmaps[i].first = SumMipMap<2>(mipmaps[i - 1].first);\n\t\tmipmaps[i].second = SumMipMap<2>(mipmaps[i - 1].second);\n\t}\n\treturn mipmaps;\n}\n\n//----------------------------------------------------------------------------//\n}\n//----------------------------------------------------------------------------//\n", "meta": {"hexsha": "24f4aabf57b293c8e614cf61f78e375d79bd9ce9", "size": 5504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp_density/density/ScalePyramid.cpp", "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_density/density/ScalePyramid.cpp", "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_density/density/ScalePyramid.cpp", "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": 35.7402597403, "max_line_length": 134, "alphanum_fraction": 0.6220930233, "num_tokens": 1775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5519214892494557}}
{"text": "//\n// Copyright (c) 2015-2020 CNRS INRIA\n// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n//\n\n#include \"pinocchio/math/fwd.hpp\"\n#include \"pinocchio/multibody/joint/joints.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n\nusing namespace pinocchio;\n\ntemplate<typename D>\nvoid addJointAndBody(Model & model,\n                     const JointModelBase<D> & jmodel,\n                     const Model::JointIndex parent_id,\n                     const SE3 & joint_placement,\n                     const std::string & joint_name,\n                     const Inertia & Y)\n{\n  Model::JointIndex idx;\n  \n  idx = model.addJoint(parent_id,jmodel,joint_placement,joint_name);\n  model.appendBodyToJoint(idx,Y);\n}\n\nBOOST_AUTO_TEST_SUITE(JointPlanar)\n  \nBOOST_AUTO_TEST_CASE(spatial)\n{\n  SE3 M(SE3::Random());\n  Motion v(Motion::Random());\n  \n  MotionPlanar mp(1.,2.,3.);\n  Motion mp_dense(mp);\n  \n  BOOST_CHECK(M.act(mp).isApprox(M.act(mp_dense)));\n  BOOST_CHECK(M.actInv(mp).isApprox(M.actInv(mp_dense)));\n  \n  BOOST_CHECK(v.cross(mp).isApprox(v.cross(mp_dense)));\n}\n\nBOOST_AUTO_TEST_CASE(vsFreeFlyer)\n{\n  using namespace pinocchio;\n  typedef SE3::Vector3 Vector3;\n  typedef Eigen::Matrix <double, 6, 1> Vector6;\n  typedef Eigen::Matrix <double, 4, 1> VectorPl;\n  typedef Eigen::Matrix <double, 7, 1> VectorFF;\n  typedef SE3::Matrix3 Matrix3;\n\n  Model modelPlanar, modelFreeflyer;\n\n  Inertia inertia(1., Vector3(0.5, 0., 0.0), Matrix3::Identity());\n  SE3 pos(1); pos.translation() = SE3::LinearType(1.,0.,0.);\n\n  addJointAndBody(modelPlanar,JointModelPlanar(),0,SE3::Identity(),\"planar\",inertia);\n  addJointAndBody(modelFreeflyer,JointModelFreeFlyer(),0,SE3::Identity(),\"free-flyer\",inertia);\n\n  Data dataPlanar(modelPlanar);\n  Data dataFreeFlyer(modelFreeflyer);\n\n  VectorPl q; q << 1, 1, 0, 1; // Angle is PI /2;\n  VectorFF qff; qff << 1, 1, 0, 0, 0, sqrt(2)/2, sqrt(2)/2 ;\n  Eigen::VectorXd v = Eigen::VectorXd::Ones(modelPlanar.nv);\n  Vector6 vff; vff << 1, 1, 0, 0, 0, 1;\n  Eigen::VectorXd tauPlanar = Eigen::VectorXd::Ones(modelPlanar.nv);\n  Eigen::VectorXd tauff = Eigen::VectorXd::Ones(modelFreeflyer.nv);\n  Eigen::VectorXd aPlanar = Eigen::VectorXd::Ones(modelPlanar.nv);\n  Eigen::VectorXd aff(vff);\n  \n  forwardKinematics(modelPlanar, dataPlanar, q, v);\n  forwardKinematics(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  computeAllTerms(modelPlanar, dataPlanar, q, v);\n  computeAllTerms(modelFreeflyer, dataFreeFlyer, qff, vff);\n\n  BOOST_CHECK(dataFreeFlyer.oMi[1].isApprox(dataPlanar.oMi[1]));\n  BOOST_CHECK(dataFreeFlyer.liMi[1].isApprox(dataPlanar.liMi[1]));\n  BOOST_CHECK(dataFreeFlyer.Ycrb[1].matrix().isApprox(dataPlanar.Ycrb[1].matrix()));\n  BOOST_CHECK(dataFreeFlyer.f[1].toVector().isApprox(dataPlanar.f[1].toVector()));\n  \n  Eigen::VectorXd nle_expected_ff(3); nle_expected_ff << dataFreeFlyer.nle[0],\n                                                         dataFreeFlyer.nle[1],\n                                                         dataFreeFlyer.nle[5]\n                                                         ;\n  BOOST_CHECK(nle_expected_ff.isApprox(dataPlanar.nle));\n  BOOST_CHECK(dataFreeFlyer.com[0].isApprox(dataPlanar.com[0]));\n\n  // InverseDynamics == rnea\n  tauPlanar = rnea(modelPlanar, dataPlanar, q, v, aPlanar);\n  tauff = rnea(modelFreeflyer, dataFreeFlyer, qff, vff, aff);\n\n  Vector3 tau_expected; tau_expected << tauff(0), tauff(1), tauff(5);\n  BOOST_CHECK(tauPlanar.isApprox(tau_expected));\n\n  // ForwardDynamics == aba\n  Eigen::VectorXd aAbaPlanar = aba(modelPlanar,dataPlanar, q, v, tauPlanar);\n  Eigen::VectorXd aAbaFreeFlyer = aba(modelFreeflyer,dataFreeFlyer, qff, vff, tauff);\n  Vector3 a_expected; a_expected << aAbaFreeFlyer[0],\n                                    aAbaFreeFlyer[1],\n                                    aAbaFreeFlyer[5]\n                                    ;\n  BOOST_CHECK(aAbaPlanar.isApprox(a_expected));\n\n  // crba\n  crba(modelPlanar, dataPlanar,q);\n  crba(modelFreeflyer, dataFreeFlyer, qff);\n\n  Eigen::Matrix<double, 3, 3> M_expected;\n  M_expected.block<2,2>(0,0) = dataFreeFlyer.M.block<2,2>(0,0);\n  M_expected.block<1,2>(2,0) = dataFreeFlyer.M.block<1,2>(5,0);\n  M_expected.block<2,1>(0,2) = dataFreeFlyer.M.col(5).head<2>();\n  M_expected.block<1,1>(2,2) = dataFreeFlyer.M.col(5).tail<1>();\n\n  BOOST_CHECK(dataPlanar.M.isApprox(M_expected));\n   \n  // Jacobian\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_planar;jacobian_planar.resize(6,3); jacobian_planar.setZero();\n  Eigen::Matrix<double, 6, Eigen::Dynamic> jacobian_ff;jacobian_ff.resize(6,6);jacobian_ff.setZero();\n  computeJointJacobians(modelPlanar, dataPlanar, q);\n  computeJointJacobians(modelFreeflyer, dataFreeFlyer, qff);\n  getJointJacobian(modelPlanar, dataPlanar, 1, LOCAL, jacobian_planar);\n  getJointJacobian(modelFreeflyer, dataFreeFlyer, 1, LOCAL, jacobian_ff);\n\n  Eigen::Matrix<double, 6, 3> jacobian_expected; jacobian_expected << jacobian_ff.col(0),\n                                                                      jacobian_ff.col(1),\n                                                                      jacobian_ff.col(5)\n                                                                      ;\n\n  BOOST_CHECK(jacobian_planar.isApprox(jacobian_expected));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "25c40e41fba383826f70f938f957fdb36ce509f6", "size": 5474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/joint-planar.cpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 716.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T16:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:26:58.000Z", "max_issues_repo_path": "unittest/joint-planar.cpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1130.0, "max_issues_repo_issues_event_min_datetime": "2015-02-21T17:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:06:22.000Z", "max_forks_repo_path": "unittest/joint-planar.cpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 38.8226950355, "max_line_length": 114, "alphanum_fraction": 0.6572890026, "num_tokens": 1594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919830720202, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5519214812466208}}
{"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": "/**\n * @file ann_layer_test.cpp\n * @author Marcus Edel\n * @author Praveen Ch\n *\n * Tests the ann layer modules.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/layer/layer_types.hpp>\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n#include <mlpack/methods/ann/init_rules/const_init.hpp>\n#include <mlpack/methods/ann/init_rules/nguyen_widrow_init.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/rnn.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n#include \"ann_test_tools.hpp\"\n#include \"serialization.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(ANNLayerTest);\n\n/**\n * Simple add module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleAddLayerTest)\n{\n  arma::mat output, input, delta;\n  Add<> module(10);\n  module.Parameters().randu();\n\n  // Test the Forward function.\n  input = arma::zeros(10, 1);\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_EQUAL(arma::accu(module.Parameters()), arma::accu(output));\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(output), arma::accu(delta));\n\n  // Test the forward function.\n  input = arma::ones(10, 1);\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_CLOSE(10 + arma::accu(module.Parameters()),\n      arma::accu(output), 1e-3);\n\n  // Test the backward function.\n  module.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_CLOSE(arma::accu(output), arma::accu(delta), 1e-3);\n}\n\n/**\n * Jacobian add module test.\n */\nBOOST_AUTO_TEST_CASE(JacobianAddLayerTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t elements = math::RandInt(2, 1000);\n    arma::mat input;\n    input.set_size(elements, 1);\n\n    Add<> module(elements);\n    module.Parameters().randu();\n\n    double error = JacobianTest(module, input);\n    BOOST_REQUIRE_LE(error, 1e-5);\n  }\n}\n\n/**\n * Add layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientAddLayerTest)\n{\n  // Add function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(10, 1);\n      target = arma::mat(\"1\");\n\n      model = new FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<Add<> >(10);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>* model;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/**\n * Simple constant module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleConstantLayerTest)\n{\n  arma::mat output, input, delta;\n  Constant<> module(10, 3.0);\n\n  // Test the Forward function.\n  input = arma::zeros(10, 1);\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_EQUAL(arma::accu(output), 30.0);\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 0);\n\n  // Test the forward function.\n  input = arma::ones(10, 1);\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_EQUAL(arma::accu(output), 30.0);\n\n  // Test the backward function.\n  module.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 0);\n}\n\n/**\n * Jacobian constant module test.\n */\nBOOST_AUTO_TEST_CASE(JacobianConstantLayerTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t elements = math::RandInt(2, 1000);\n    arma::mat input;\n    input.set_size(elements, 1);\n\n    Constant<> module(elements, 1.0);\n\n    double error = JacobianTest(module, input);\n    BOOST_REQUIRE_LE(error, 1e-5);\n  }\n}\n\n/**\n * Simple dropout module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleDropoutLayerTest)\n{\n  // Initialize the probability of setting a value to zero.\n  const double p = 0.2;\n\n  // Initialize the input parameter.\n  arma::mat input(1000, 1);\n  input.fill(1 - p);\n\n  Dropout<> module(p);\n  module.Deterministic() = false;\n\n  // Test the Forward function.\n  arma::mat output;\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_LE(\n      arma::as_scalar(arma::abs(arma::mean(output) - (1 - p))), 0.05);\n\n  // Test the Backward function.\n  arma::mat delta;\n  module.Backward(std::move(input), std::move(input), std::move(delta));\n  BOOST_REQUIRE_LE(\n      arma::as_scalar(arma::abs(arma::mean(delta) - (1 - p))), 0.05);\n\n  // Test the Forward function.\n  module.Deterministic() = true;\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_EQUAL(arma::accu(input), arma::accu(output));\n}\n\n/**\n * Perform dropout x times using ones as input, sum the number of ones and\n * validate that the layer is producing approximately the correct number of\n * ones.\n */\nBOOST_AUTO_TEST_CASE(DropoutProbabilityTest)\n{\n  arma::mat input = arma::ones(1500, 1);\n  const size_t iterations = 10;\n\n  double probability[5] = { 0.1, 0.3, 0.4, 0.7, 0.8 };\n  for (size_t trial = 0; trial < 5; ++trial)\n  {\n    double nonzeroCount = 0;\n    for (size_t i = 0; i < iterations; ++i)\n    {\n      Dropout<> module(probability[trial]);\n      module.Deterministic() = false;\n\n      arma::mat output;\n      module.Forward(std::move(input), std::move(output));\n\n      // Return a column vector containing the indices of elements of X that\n      // are non-zero, we just need the number of non-zero values.\n      arma::uvec nonzero = arma::find(output);\n      nonzeroCount += nonzero.n_elem;\n    }\n    const double expected = input.n_elem * (1 - probability[trial]) *\n        iterations;\n    const double error = fabs(nonzeroCount - expected) / expected;\n\n    BOOST_REQUIRE_LE(error, 0.15);\n  }\n}\n\n/*\n * Perform dropout with probability 1 - p where p = 0, means no dropout.\n */\nBOOST_AUTO_TEST_CASE(NoDropoutTest)\n{\n  arma::mat input = arma::ones(1500, 1);\n  Dropout<> module(0);\n  module.Deterministic() = false;\n\n  arma::mat output;\n  module.Forward(std::move(input), std::move(output));\n\n  BOOST_REQUIRE_EQUAL(arma::accu(output), arma::accu(input));\n}\n\n/*\n * Perform test to check whether mean and variance remain nearly same\n * after AlphaDropout.\n */\nBOOST_AUTO_TEST_CASE(SimpleAlphaDropoutLayerTest)\n{\n  // Initialize the probability of setting a value to alphaDash.\n  const double p = 0.2;\n\n  // Initialize the input parameter having a mean nearabout 0\n  // and variance nearabout 1.\n  arma::mat input = arma::randn<arma::mat>(1000, 1);\n\n  AlphaDropout<> module(p);\n  module.Deterministic() = false;\n\n  // Test the Forward function when training phase.\n  arma::mat output;\n  module.Forward(std::move(input), std::move(output));\n  // Check whether mean remains nearly same.\n  BOOST_REQUIRE_LE(\n      arma::as_scalar(arma::abs(arma::mean(input) - arma::mean(output))), 0.1);\n\n  // Check whether variance remains nearly same.\n  BOOST_REQUIRE_LE(\n      arma::as_scalar(arma::abs(arma::var(input) - arma::var(output))), 0.1);\n\n  // Test the Backward function when training phase.\n  arma::mat delta;\n  module.Backward(std::move(input), std::move(input), std::move(delta));\n  BOOST_REQUIRE_LE(\n      arma::as_scalar(arma::abs(arma::mean(delta) - 0)), 0.05);\n\n  // Test the Forward function when testing phase.\n  module.Deterministic() = true;\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_EQUAL(arma::accu(input), arma::accu(output));\n}\n\n/**\n * Perform AlphaDropout x times using ones as input, sum the number of ones\n * and validate that the layer is producing approximately the correct number\n * of ones.\n */\nBOOST_AUTO_TEST_CASE(AlphaDropoutProbabilityTest)\n{\n  arma::mat input = arma::ones(1500, 1);\n  const size_t iterations = 10;\n\n  double probability[5] = { 0.1, 0.3, 0.4, 0.7, 0.8 };\n  for (size_t trial = 0; trial < 5; ++trial)\n  {\n    double nonzeroCount = 0;\n    for (size_t i = 0; i < iterations; ++i)\n    {\n      AlphaDropout<> module(probability[trial]);\n      module.Deterministic() = false;\n\n      arma::mat output;\n      module.Forward(std::move(input), std::move(output));\n\n      // Return a column vector containing the indices of elements of X\n      // that are not alphaDash, we just need the number of\n      // nonAlphaDash values.\n      arma::uvec nonAlphaDash = arma::find(module.Mask());\n      nonzeroCount += nonAlphaDash.n_elem;\n    }\n\n    const double expected = input.n_elem * (1-probability[trial]) * iterations;\n\n    const double error = fabs(nonzeroCount - expected) / expected;\n\n    BOOST_REQUIRE_LE(error, 0.15);\n  }\n}\n\n/**\n * Perform AlphaDropout with probability 1 - p where p = 0,\n * means no AlphaDropout.\n */\nBOOST_AUTO_TEST_CASE(NoAlphaDropoutTest)\n{\n  arma::mat input = arma::ones(1500, 1);\n  AlphaDropout<> module(0);\n  module.Deterministic() = false;\n\n  arma::mat output;\n  module.Forward(std::move(input), std::move(output));\n\n  BOOST_REQUIRE_EQUAL(arma::accu(output), arma::accu(input));\n}\n\n/**\n * Simple linear module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleLinearLayerTest)\n{\n  arma::mat output, input, delta;\n  Linear<> module(10, 10);\n  module.Parameters().randu();\n  module.Reset();\n\n  // Test the Forward function.\n  input = arma::zeros(10, 1);\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_CLOSE(arma::accu(\n      module.Parameters().submat(100, 0, module.Parameters().n_elem - 1, 0)),\n      arma::accu(output), 1e-3);\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(input), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 0);\n}\n\n/**\n * Jacobian linear module test.\n */\nBOOST_AUTO_TEST_CASE(JacobianLinearLayerTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t inputElements = math::RandInt(2, 1000);\n    const size_t outputElements = math::RandInt(2, 1000);\n\n    arma::mat input;\n    input.set_size(inputElements, 1);\n\n    Linear<> module(inputElements, outputElements);\n    module.Parameters().randu();\n\n    double error = JacobianTest(module, input);\n    BOOST_REQUIRE_LE(error, 1e-5);\n  }\n}\n\n/**\n * Linear layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientLinearLayerTest)\n{\n  // Linear function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(10, 1);\n      target = arma::mat(\"1\");\n\n      model = new FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<Linear<> >(10, 2);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>* model;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/**\n * Simple linear no bias module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleLinearNoBiasLayerTest)\n{\n  arma::mat output, input, delta;\n  LinearNoBias<> module(10, 10);\n  module.Parameters().randu();\n  module.Reset();\n\n  // Test the Forward function.\n  input = arma::zeros(10, 1);\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_EQUAL(0, arma::accu(output));\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(input), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 0);\n}\n\n/**\n * Jacobian linear no bias module test.\n */\nBOOST_AUTO_TEST_CASE(JacobianLinearNoBiasLayerTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t inputElements = math::RandInt(2, 1000);\n    const size_t outputElements = math::RandInt(2, 1000);\n\n    arma::mat input;\n    input.set_size(inputElements, 1);\n\n    LinearNoBias<> module(inputElements, outputElements);\n    module.Parameters().randu();\n\n    double error = JacobianTest(module, input);\n    BOOST_REQUIRE_LE(error, 1e-5);\n  }\n}\n\n/**\n * LinearNoBias layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientLinearNoBiasLayerTest)\n{\n  // LinearNoBias function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(10, 1);\n      target = arma::mat(\"1\");\n\n      model = new FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<LinearNoBias<> >(10, 2);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>* model;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/**\n * Jacobian negative log likelihood module test.\n */\nBOOST_AUTO_TEST_CASE(JacobianNegativeLogLikelihoodLayerTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    NegativeLogLikelihood<> module;\n    const size_t inputElements = math::RandInt(5, 100);\n    arma::mat input;\n    RandomInitialization init(0, 1);\n    init.Initialize(input, inputElements, 1);\n\n    arma::mat target(1, 1);\n    target(0) = math::RandInt(1, inputElements - 1);\n\n    double error = JacobianPerformanceTest(module, input, target);\n    BOOST_REQUIRE_LE(error, 1e-5);\n  }\n}\n\n/**\n * Jacobian LeakyReLU module test.\n */\nBOOST_AUTO_TEST_CASE(JacobianLeakyReLULayerTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t inputElements = math::RandInt(2, 1000);\n\n    arma::mat input;\n    input.set_size(inputElements, 1);\n\n    LeakyReLU<> module;\n\n    double error = JacobianTest(module, input);\n    BOOST_REQUIRE_LE(error, 1e-5);\n  }\n}\n\n/**\n * Jacobian FlexibleReLU module test.\n */\nBOOST_AUTO_TEST_CASE(JacobianFlexibleReLULayerTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t inputElements = math::RandInt(2, 1000);\n\n    arma::mat input;\n    input.set_size(inputElements, 1);\n\n    FlexibleReLU<> module;\n\n    double error = JacobianTest(module, input);\n    BOOST_REQUIRE_LE(error, 1e-5);\n  }\n}\n\n/**\n * Flexible ReLU layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientFlexibleReLULayerTest)\n{\n  // Add function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(2, 1);\n      target = arma::mat(\"1\");\n\n      model = new FFN<NegativeLogLikelihood<>, RandomInitialization>(\n          NegativeLogLikelihood<>(), RandomInitialization(0.1, 0.5));\n\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<LinearNoBias<> >(2, 5);\n      model->Add<FlexibleReLU<> >(0.05);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<NegativeLogLikelihood<>, RandomInitialization>* model;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/**\n * Jacobian MultiplyConstant module test.\n */\nBOOST_AUTO_TEST_CASE(JacobianMultiplyConstantLayerTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t inputElements = math::RandInt(2, 1000);\n\n    arma::mat input;\n    input.set_size(inputElements, 1);\n\n    MultiplyConstant<> module(3.0);\n\n    double error = JacobianTest(module, input);\n    BOOST_REQUIRE_LE(error, 1e-5);\n  }\n}\n\n/**\n * Jacobian HardTanH module test.\n */\nBOOST_AUTO_TEST_CASE(JacobianHardTanHLayerTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t inputElements = math::RandInt(2, 1000);\n\n    arma::mat input;\n    input.set_size(inputElements, 1);\n\n    HardTanH<> module;\n\n    double error = JacobianTest(module, input);\n    BOOST_REQUIRE_LE(error, 1e-5);\n  }\n}\n\n/**\n * Simple select module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleSelectLayerTest)\n{\n  arma::mat outputA, outputB, input, delta;\n\n  input = arma::ones(10, 5);\n  for (size_t i = 0; i < input.n_cols; ++i)\n  {\n    input.col(i) *= i;\n  }\n\n  // Test the Forward function.\n  Select<> moduleA(3);\n  moduleA.Forward(std::move(input), std::move(outputA));\n  BOOST_REQUIRE_EQUAL(30, arma::accu(outputA));\n\n  // Test the Forward function.\n  Select<> moduleB(3, 5);\n  moduleB.Forward(std::move(input), std::move(outputB));\n  BOOST_REQUIRE_EQUAL(15, arma::accu(outputB));\n\n  // Test the Backward function.\n  moduleA.Backward(std::move(input), std::move(outputA), std::move(delta));\n  BOOST_REQUIRE_EQUAL(30, arma::accu(delta));\n\n  // Test the Backward function.\n  moduleB.Backward(std::move(input), std::move(outputA), std::move(delta));\n  BOOST_REQUIRE_EQUAL(15, arma::accu(delta));\n}\n\n/**\n * Simple join module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleJoinLayerTest)\n{\n  arma::mat output, input, delta;\n  input = arma::ones(10, 5);\n\n  // Test the Forward function.\n  Join<> module;\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_EQUAL(50, arma::accu(output));\n\n  bool b = output.n_rows == 1 || output.n_cols == 1;\n  BOOST_REQUIRE_EQUAL(b, true);\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(50, arma::accu(delta));\n\n  b = delta.n_rows == input.n_rows && input.n_cols;\n  BOOST_REQUIRE_EQUAL(b, true);\n}\n\n/**\n * Simple add merge module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleAddMergeLayerTest)\n{\n  arma::mat output, input, delta;\n  input = arma::ones(10, 1);\n\n  for (size_t i = 0; i < 5; ++i)\n  {\n    AddMerge<> module(false, false);\n    const size_t numMergeModules = math::RandInt(2, 10);\n    for (size_t m = 0; m < numMergeModules; ++m)\n    {\n      IdentityLayer<> identityLayer;\n      identityLayer.Forward(std::move(input),\n          std::move(identityLayer.OutputParameter()));\n\n      module.Add<IdentityLayer<> >(identityLayer);\n    }\n\n    // Test the Forward function.\n    module.Forward(std::move(input), std::move(output));\n    BOOST_REQUIRE_EQUAL(10 * numMergeModules, arma::accu(output));\n\n    // Test the Backward function.\n    module.Backward(std::move(input), std::move(output), std::move(delta));\n    BOOST_REQUIRE_EQUAL(arma::accu(output), arma::accu(delta));\n  }\n}\n\n/**\n * Test the LSTM layer with a user defined rho parameter and without.\n */\nBOOST_AUTO_TEST_CASE(LSTMRrhoTest)\n{\n  const size_t rho = 5;\n  arma::cube input = arma::randu(1, 1, 5);\n  arma::cube target = arma::ones(1, 1, 5);\n  RandomInitialization init(0.5, 0.5);\n\n  // Create model with user defined rho parameter.\n  RNN<NegativeLogLikelihood<>, RandomInitialization> modelA(\n      rho, false, NegativeLogLikelihood<>(), init);\n  modelA.Add<IdentityLayer<> >();\n  modelA.Add<Linear<> >(1, 10);\n\n  // Use LSTM layer with rho.\n  modelA.Add<LSTM<> >(10, 3, rho);\n  modelA.Add<LogSoftMax<> >();\n\n  // Create model without user defined rho parameter.\n  RNN<NegativeLogLikelihood<> > modelB(\n      rho, false, NegativeLogLikelihood<>(), init);\n  modelB.Add<IdentityLayer<> >();\n  modelB.Add<Linear<> >(1, 10);\n\n  // Use LSTM layer with rho = MAXSIZE.\n  modelB.Add<LSTM<> >(10, 3);\n  modelB.Add<LogSoftMax<> >();\n\n  ens::StandardSGD opt(0.1, 1, 5, -100, false);\n  modelA.Train(input, target, opt);\n  modelB.Train(input, target, opt);\n\n  CheckMatrices(modelB.Parameters(), modelA.Parameters());\n}\n\n/**\n * LSTM layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientLSTMLayerTest)\n{\n  // LSTM function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(1, 1, 5);\n      target.ones(1, 1, 5);\n      const size_t rho = 5;\n\n      model = new RNN<NegativeLogLikelihood<> >(rho);\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<Linear<> >(1, 10);\n      model->Add<LSTM<> >(10, 3, rho);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    RNN<NegativeLogLikelihood<> >* model;\n    arma::cube input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/**\n * Test the FastLSTM layer with a user defined rho parameter and without.\n */\nBOOST_AUTO_TEST_CASE(FastLSTMRrhoTest)\n{\n  const size_t rho = 5;\n  arma::cube input = arma::randu(1, 1, 5);\n  arma::cube target = arma::ones(1, 1, 5);\n  RandomInitialization init(0.5, 0.5);\n\n  // Create model with user defined rho parameter.\n  RNN<NegativeLogLikelihood<>, RandomInitialization> modelA(\n      rho, false, NegativeLogLikelihood<>(), init);\n  modelA.Add<IdentityLayer<> >();\n  modelA.Add<Linear<> >(1, 10);\n\n  // Use FastLSTM layer with rho.\n  modelA.Add<FastLSTM<> >(10, 3, rho);\n  modelA.Add<LogSoftMax<> >();\n\n  // Create model without user defined rho parameter.\n  RNN<NegativeLogLikelihood<> > modelB(\n      rho, false, NegativeLogLikelihood<>(), init);\n  modelB.Add<IdentityLayer<> >();\n  modelB.Add<Linear<> >(1, 10);\n\n  // Use FastLSTM layer with rho = MAXSIZE.\n  modelB.Add<FastLSTM<> >(10, 3);\n  modelB.Add<LogSoftMax<> >();\n\n  ens::StandardSGD opt(0.1, 1, 5, -100, false);\n  modelA.Train(input, target, opt);\n  modelB.Train(input, target, opt);\n\n  CheckMatrices(modelB.Parameters(), modelA.Parameters());\n}\n\n/**\n * FastLSTM layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientFastLSTMLayerTest)\n{\n  // Fast LSTM function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(1, 1, 5);\n      target = arma::ones(1, 1, 5);\n      const size_t rho = 5;\n\n      model = new RNN<NegativeLogLikelihood<> >(rho);\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<Linear<> >(1, 10);\n      model->Add<FastLSTM<> >(10, 3, rho);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    RNN<NegativeLogLikelihood<> >* model;\n    arma::cube input, target;\n  } function;\n\n  // The threshold should be << 0.1 but since the Fast LSTM layer uses an\n  // approximation of the sigmoid function the estimated gradient is not\n  // correct.\n  BOOST_REQUIRE_LE(CheckGradient(function), 0.2);\n}\n\n/**\n * Testing the overloaded Forward() of the LSTM layer, for retrieving the cell\n * state. Besides output, the overloaded function provides read access to cell\n * state of the LSTM layer.\n */\nBOOST_AUTO_TEST_CASE(ReadCellStateParamLSTMLayerTest)\n{\n  const size_t rho = 5, inputSize = 3, outputSize = 2;\n\n  // Provide input of all ones.\n  arma::cube input = arma::ones(inputSize, outputSize, rho);\n\n  arma::mat inputGate, forgetGate, outputGate, hidden;\n  arma::mat outLstm, cellLstm;\n\n  // LSTM layer.\n  LSTM<> lstm(inputSize, outputSize, rho);\n  lstm.Reset();\n  lstm.ResetCell(rho);\n\n  // Initialize the weights to all ones.\n  lstm.Parameters().ones();\n\n  arma::mat inputWeight = arma::ones(outputSize, inputSize);\n  arma::mat outputWeight = arma::ones(outputSize, outputSize);\n  arma::mat bias = arma::ones(outputSize, input.n_cols);\n  arma::mat cellCalc = arma::zeros(outputSize, input.n_cols);\n  arma::mat outCalc = arma::zeros(outputSize, input.n_cols);\n\n  for (size_t seqNum = 0; seqNum < rho; ++seqNum)\n  {\n      // Wrap a matrix around our data to avoid a copy.\n      arma::mat stepData(input.slice(seqNum).memptr(),\n          input.n_rows, input.n_cols, false, true);\n\n      // Apply Forward() on LSTM layer.\n      lstm.Forward(std::move(stepData), // Input.\n                   std::move(outLstm),  // Output.\n                   std::move(cellLstm), // Cell state.\n                   false); // Don't write into the cell state.\n\n      // Compute the value of cell state and output.\n      // i = sigmoid(W.dot(x) + W.dot(h) + W.dot(c) + b).\n      inputGate = 1.0 /(1 + arma::exp(-(inputWeight * stepData +\n          outputWeight * outCalc + outputWeight % cellCalc + bias)));\n\n      // f = sigmoid(W.dot(x) + W.dot(h) + W.dot(c) + b).\n      forgetGate = 1.0 /(1 + arma::exp(-(inputWeight * stepData +\n          outputWeight * outCalc + outputWeight % cellCalc + bias)));\n\n      // z = tanh(W.dot(x) + W.dot(h) + b).\n      hidden = arma::tanh(inputWeight * stepData +\n                     outputWeight * outCalc + bias);\n\n      // c = f * c + i * z.\n      cellCalc = forgetGate % cellCalc + inputGate % hidden;\n\n      // o = sigmoid(W.dot(x) + W.dot(h) + W.dot(c) + b).\n      outputGate = 1.0 /(1 + arma::exp(-(inputWeight * stepData +\n          outputWeight * outCalc + outputWeight % cellCalc + bias)));\n\n      // h = o * tanh(c).\n      outCalc = outputGate % arma::tanh(cellCalc);\n\n      CheckMatrices(outLstm, outCalc, 1e-12);\n      CheckMatrices(cellLstm, cellCalc, 1e-12);\n  }\n}\n\n/**\n * Testing the overloaded Forward() of the LSTM layer, for retrieving the cell\n * state. Besides output, the overloaded function provides write access to cell\n * state of the LSTM layer.\n */\nBOOST_AUTO_TEST_CASE(WriteCellStateParamLSTMLayerTest)\n{\n  const size_t rho = 5, inputSize = 3, outputSize = 2;\n\n  // Provide input of all ones.\n  arma::cube input = arma::ones(inputSize, outputSize, rho);\n\n  arma::mat inputGate, forgetGate, outputGate, hidden;\n  arma::mat outLstm, cellLstm;\n  arma::mat cellCalc;\n\n  // LSTM layer.\n  LSTM<> lstm(inputSize, outputSize, rho);\n  lstm.Reset();\n  lstm.ResetCell(rho);\n\n  // Initialize the weights to all ones.\n  lstm.Parameters().ones();\n\n  arma::mat inputWeight = arma::ones(outputSize, inputSize);\n  arma::mat outputWeight = arma::ones(outputSize, outputSize);\n  arma::mat bias = arma::ones(outputSize, input.n_cols);\n  arma::mat outCalc = arma::zeros(outputSize, input.n_cols);\n\n  for (size_t seqNum = 0; seqNum < rho; ++seqNum)\n  {\n      // Wrap a matrix around our data to avoid a copy.\n      arma::mat stepData(input.slice(seqNum).memptr(),\n          input.n_rows, input.n_cols, false, true);\n\n      if (cellLstm.is_empty())\n      {\n        // Set the cell state to zeros.\n        cellLstm = arma::zeros(outputSize, input.n_cols);\n        cellCalc = arma::zeros(outputSize, input.n_cols);\n      }\n      else\n      {\n        // Set the cell state to zeros.\n        cellLstm = arma::zeros(cellLstm.n_rows, cellLstm.n_cols);\n        cellCalc = arma::zeros(cellCalc.n_rows, cellCalc.n_cols);\n      }\n\n      // Apply Forward() on the LSTM layer.\n      lstm.Forward(std::move(stepData), // Input.\n                   std::move(outLstm),  // Output.\n                   std::move(cellLstm), // Cell state.\n                   true);  // Write into cell state.\n\n      // Compute the value of cell state and output.\n      // i = sigmoid(W.dot(x) + W.dot(h) + W.dot(c) + b).\n      inputGate = 1.0 /(1 + arma::exp(-(inputWeight * stepData +\n          outputWeight * outCalc + outputWeight % cellCalc + bias)));\n\n      // f = sigmoid(W.dot(x) + W.dot(h) + W.dot(c) + b).\n      forgetGate = 1.0 /(1 + arma::exp(-(inputWeight * stepData +\n          outputWeight * outCalc + outputWeight % cellCalc + bias)));\n\n      // z = tanh(W.dot(x) + W.dot(h) + b).\n      hidden = arma::tanh(inputWeight * stepData +\n                     outputWeight * outCalc + bias);\n\n      // c = f * c + i * z.\n      cellCalc = forgetGate % cellCalc + inputGate % hidden;\n\n      // o = sigmoid(W.dot(x) + W.dot(h) + W.dot(c) + b).\n      outputGate = 1.0 /(1 + arma::exp(-(inputWeight * stepData +\n          outputWeight * outCalc + outputWeight % cellCalc + bias)));\n\n      // h = o * tanh(c).\n      outCalc = outputGate % arma::tanh(cellCalc);\n\n      CheckMatrices(outLstm, outCalc, 1e-12);\n      CheckMatrices(cellLstm, cellCalc, 1e-12);\n  }\n\n  // Attempting to write empty matrix into cell state.\n  lstm.Reset();\n  lstm.ResetCell(rho);\n  arma::mat stepData(input.slice(0).memptr(),\n      input.n_rows, input.n_cols, false, true);\n\n  lstm.Forward(std::move(stepData), // Input.\n                   std::move(outLstm),  // Output.\n                   std::move(cellLstm), // Cell state.\n                   true); // Write into cell state.\n\n  for (size_t seqNum = 1; seqNum < rho; ++seqNum)\n  {\n    arma::mat empty;\n    // Should throw error.\n    BOOST_REQUIRE_THROW(lstm.Forward(std::move(stepData), // Input.\n                                     std::move(outLstm),  // Output.\n                                     std::move(empty), // Cell state.\n                                     true),  // Write into cell state.\n                                     std::runtime_error);\n  }\n}\n\n/**\n * Check if the gradients computed by GRU cell are close enough to the\n * approximation of the gradients.\n */\nBOOST_AUTO_TEST_CASE(GradientGRULayerTest)\n{\n  // GRU function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(1, 1, 5);\n      target = arma::ones(1, 1, 5);\n      const size_t rho = 5;\n\n      model = new RNN<NegativeLogLikelihood<> >(rho);\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<Linear<> >(1, 10);\n      model->Add<GRU<> >(10, 3, rho);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      arma::mat output;\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    RNN<NegativeLogLikelihood<> >* model;\n    arma::cube input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/**\n * GRU layer manual forward test.\n */\nBOOST_AUTO_TEST_CASE(ForwardGRULayerTest)\n{\n  GRU<> gru(3, 3, 5);\n\n  // Initialize the weights to all ones.\n  NetworkInitialization<ConstInitialization>\n    networkInit(ConstInitialization(1));\n  networkInit.Initialize(gru.Model(), gru.Parameters());\n\n  // Provide input of all ones.\n  arma::mat input = arma::ones(3, 1);\n  arma::mat output;\n\n  gru.Forward(std::move(input), std::move(output));\n\n  // Compute the z_t gate output.\n  arma::mat expectedOutput = arma::ones(3, 1);\n  expectedOutput *= -4;\n  expectedOutput = arma::exp(expectedOutput);\n  expectedOutput = arma::ones(3, 1) / (arma::ones(3, 1) + expectedOutput);\n  expectedOutput = (arma::ones(3, 1)  - expectedOutput) % expectedOutput;\n\n  // For the first input the output should be equal to the output of\n  // gate z_t as the previous output fed to the cell is all zeros.\n  BOOST_REQUIRE_LE(arma::as_scalar(arma::trans(output) * expectedOutput), 1e-2);\n\n  expectedOutput = output;\n\n  gru.Forward(std::move(input), std::move(output));\n\n  double s = arma::as_scalar(arma::sum(expectedOutput));\n\n  // Compute the value of z_t gate for the second input.\n  arma::mat z_t = arma::ones(3, 1);\n  z_t *= -(s + 4);\n  z_t = arma::exp(z_t);\n  z_t = arma::ones(3, 1) / (arma::ones(3, 1) + z_t);\n\n  // Compute the value of o_t gate for the second input.\n  arma::mat o_t = arma::ones(3, 1);\n  o_t *= -(arma::as_scalar(arma::sum(expectedOutput % z_t)) + 4);\n  o_t = arma::exp(o_t);\n  o_t = arma::ones(3, 1) / (arma::ones(3, 1) + o_t);\n\n  // Expected output for the second input.\n  expectedOutput = z_t % expectedOutput + (arma::ones(3, 1) - z_t) % o_t;\n\n  BOOST_REQUIRE_LE(arma::as_scalar(arma::trans(output) * expectedOutput), 1e-2);\n}\n\n/**\n * Simple concat module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleConcatLayerTest)\n{\n  arma::mat output, input, delta, error;\n\n  Linear<> moduleA(10, 10);\n  moduleA.Parameters().randu();\n  moduleA.Reset();\n\n  Linear<> moduleB(10, 10);\n  moduleB.Parameters().randu();\n  moduleB.Reset();\n\n  Concat<> module;\n  module.Add(moduleA);\n  module.Add(moduleB);\n\n  // Test the Forward function.\n  input = arma::zeros(10, 1);\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_CLOSE(arma::accu(\n      moduleA.Parameters().submat(100, 0, moduleA.Parameters().n_elem - 1, 0)) +\n      arma::accu(moduleB.Parameters().submat(100, 0,\n      moduleB.Parameters().n_elem - 1, 0)),\n      arma::accu(output.col(0)), 1e-3);\n\n  // Test the Backward function.\n  error = arma::zeros(20, 1);\n  module.Backward(std::move(input), std::move(error), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 0);\n}\n\n/**\n * Test to check Concat layer along different axes.\n */\nBOOST_AUTO_TEST_CASE(ConcatAlongAxisTest)\n{\n  arma::mat output, input, error, outputA, outputB;\n  size_t inputWidth = 4, inputHeight = 4, inputChannel = 2;\n  size_t outputWidth, outputHeight, outputChannel = 2;\n  size_t kW = 3, kH = 3;\n  size_t batch = 1;\n\n  // Using Convolution<> layer as inout to Concat<> layer.\n  // Compute the output shape of convolution layer.\n  outputWidth  = (inputWidth - kW) + 1;\n  outputHeight = (inputHeight - kH) + 1;\n\n  input = arma::ones(inputWidth * inputHeight * inputChannel, batch);\n\n  Convolution<> moduleA(inputChannel, outputChannel, kW, kH, 1, 1, 0, 0,\n      inputWidth, inputHeight);\n  Convolution<> moduleB(inputChannel, outputChannel, kW, kH, 1, 1, 0, 0,\n      inputWidth, inputHeight);\n\n  moduleA.Reset();\n  moduleA.Parameters().randu();\n  moduleB.Reset();\n  moduleB.Parameters().randu();\n\n  // Compute output of each layer.\n  moduleA.Forward(std::move(input), std::move(outputA));\n  moduleB.Forward(std::move(input), std::move(outputB));\n\n  arma::cube A(outputA.memptr(), outputWidth, outputHeight, outputChannel);\n  arma::cube B(outputB.memptr(), outputWidth, outputHeight, outputChannel);\n\n  error = arma::ones(outputWidth * outputHeight * outputChannel * 2, 1);\n\n  for (size_t axis = 0; axis < 3; ++axis)\n  {\n    size_t x = 1, y = 1, z = 1;\n    arma::cube calculatedOut;\n    if (axis == 0)\n    {\n      calculatedOut.set_size(2 * outputWidth, outputHeight, outputChannel);\n      for (size_t i = 0; i < A.n_slices; ++i)\n      {\n          arma::mat aMat = A.slice(i);\n          arma::mat bMat = B.slice(i);\n          calculatedOut.slice(i) = arma::join_cols(aMat, bMat);\n      }\n      x = 2;\n    }\n    if (axis == 1)\n    {\n      calculatedOut.set_size(outputWidth, 2 * outputHeight, outputChannel);\n      for (size_t i = 0; i < A.n_slices; ++i)\n      {\n          arma::mat aMat = A.slice(i);\n          arma::mat bMat = B.slice(i);\n          calculatedOut.slice(i) = arma::join_rows(aMat, bMat);\n      }\n      y = 2;\n    }\n    if (axis == 2)\n    {\n      calculatedOut = arma::join_slices(A, B);\n      z = 2;\n    }\n\n    // Compute output of Concat<> layer.\n    arma::Row<size_t> inputSize{outputWidth, outputHeight, outputChannel};\n    Concat<> module(inputSize, axis);\n    module.Add(moduleA);\n    module.Add(moduleB);\n    module.Forward(std::move(input), std::move(output));\n    arma::cube concatOut(output.memptr(), x * outputWidth,\n        y * outputHeight, z * outputChannel);\n\n    // Verify if the output reshaped to cubes are similar.\n    CheckMatrices(concatOut, calculatedOut, 1e-12);\n  }\n}\n\n/**\n * Concat layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientConcatLayerTest)\n{\n  // Concat function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(10, 1);\n      target = arma::mat(\"1\");\n\n      model = new FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n\n      concat = new Concat<>(true);\n      concat->Add<Linear<> >(10, 2);\n      model->Add(concat);\n\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>* model;\n    Concat<>* concat;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/**\n * Simple concatenate module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleConcatenateLayerTest)\n{\n  arma::mat input = arma::ones(5, 1);\n  arma::mat output, delta;\n\n  Concatenate<> module;\n  module.Concat() = arma::ones(5, 1) * 0.5;\n\n  // Test the Forward function.\n  module.Forward(std::move(input), std::move(output));\n\n  BOOST_REQUIRE_EQUAL(arma::accu(output), 7.5);\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 5);\n}\n\n/**\n * Concatenate layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientConcatenateLayerTest)\n{\n  // Concatenate function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(10, 1);\n      target = arma::mat(\"1\");\n\n      model = new FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<Linear<> >(10, 5);\n\n      arma::mat concat = arma::ones(5, 1);\n      concatenate = new Concatenate<>();\n      concatenate->Concat() = concat;\n      model->Add(concatenate);\n\n      model->Add<Linear<> >(10, 5);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>* model;\n    Concatenate<>* concatenate;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/**\n * Simple lookup module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleLookupLayerTest)\n{\n  arma::mat output, input, delta, gradient;\n  Lookup<> module(10, 5);\n  module.Parameters().randu();\n\n  // Test the Forward function.\n  input = arma::zeros(2, 1);\n  input(0) = 1;\n  input(1) = 3;\n\n  module.Forward(std::move(input), std::move(output));\n\n  // The Lookup module uses index - 1 for the cols.\n  const double outputSum = arma::accu(module.Parameters().col(0)) +\n      arma::accu(module.Parameters().col(2));\n\n  BOOST_REQUIRE_CLOSE(outputSum, arma::accu(output), 1e-3);\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(input), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(input), arma::accu(input));\n\n  // Test the Gradient function.\n  arma::mat error = arma::ones(2, 5);\n  error = error.t();\n  error.col(1) *= 0.5;\n\n  module.Gradient(std::move(input), std::move(error), std::move(gradient));\n\n  // The Lookup module uses index - 1 for the cols.\n  const double gradientSum = arma::accu(gradient.col(0)) +\n      arma::accu(gradient.col(2));\n\n  BOOST_REQUIRE_CLOSE(gradientSum, arma::accu(error), 1e-3);\n  BOOST_REQUIRE_CLOSE(arma::accu(gradient), arma::accu(error), 1e-3);\n}\n\n/**\n * Simple LogSoftMax module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleLogSoftmaxLayerTest)\n{\n  arma::mat output, input, error, delta;\n  LogSoftMax<> module;\n\n  // Test the Forward function.\n  input = arma::mat(\"0.5; 0.5\");\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_SMALL(arma::accu(arma::abs(\n    arma::mat(\"-0.6931; -0.6931\") - output)), 1e-3);\n\n  // Test the Backward function.\n  error = arma::zeros(input.n_rows, input.n_cols);\n  // Assume LogSoftmax layer is always associated with NLL output layer.\n  error(1, 0) = -1;\n  module.Backward(std::move(input), std::move(error), std::move(delta));\n  BOOST_REQUIRE_SMALL(arma::accu(arma::abs(\n      arma::mat(\"1.6487; 0.6487\") - delta)), 1e-3);\n}\n\n/*\n * Simple test for the BilinearInterpolation layer\n */\nBOOST_AUTO_TEST_CASE(SimpleBilinearInterpolationLayerTest)\n{\n  // Tested output against tensorflow.image.resize_bilinear()\n  arma::mat input, output, unzoomedOutput, expectedOutput;\n  size_t inRowSize = 2;\n  size_t inColSize = 2;\n  size_t outRowSize = 5;\n  size_t outColSize = 5;\n  size_t depth = 1;\n  input.zeros(inRowSize * inColSize * depth, 1);\n  input[0] = 1.0;\n  input[1] = input[2] = 2.0;\n  input[3] = 3.0;\n  BilinearInterpolation<> layer(inRowSize, inColSize, outRowSize, outColSize,\n      depth);\n  expectedOutput = arma::mat(\"1.0000 1.4000 1.8000 2.0000 2.0000 \\\n      1.4000 1.8000 2.2000 2.4000 2.4000 \\\n      1.8000 2.2000 2.6000 2.8000 2.8000 \\\n      2.0000 2.4000 2.8000 3.0000 3.0000 \\\n      2.0000 2.4000 2.8000 3.0000 3.0000\");\n  expectedOutput.reshape(25, 1);\n  layer.Forward(std::move(input), std::move(output));\n  CheckMatrices(output - expectedOutput, arma::zeros(output.n_rows), 1e-12);\n\n  expectedOutput = arma::mat(\"1.0000 1.9000 1.9000 2.8000\");\n  expectedOutput.reshape(4, 1);\n  layer.Backward(std::move(output), std::move(output),\n      std::move(unzoomedOutput));\n  CheckMatrices(unzoomedOutput - expectedOutput,\n      arma::zeros(input.n_rows), 1e-12);\n}\n\n/**\n * Tests the BatchNorm Layer, compares the layers parameters with\n * the values from another implementation.\n * Link to the implementation - http://cthorey.github.io./backpropagation/\n */\nBOOST_AUTO_TEST_CASE(BatchNormTest)\n{\n  arma::mat input, output;\n  input << 5.1 << 3.5 << 1.4 << arma::endr\n        << 4.9 << 3.0 << 1.4 << arma::endr\n        << 4.7 << 3.2 << 1.3 << arma::endr;\n\n  BatchNorm<> model(input.n_rows);\n  model.Reset();\n\n  // Non-Deteministic Forward Pass Test.\n  model.Deterministic() = false;\n  model.Forward(std::move(input), std::move(output));\n  arma::mat result;\n  result << 1.1658 << 0.1100 << -1.2758 << arma::endr\n         << 1.2579 << -0.0699 << -1.1880 << arma::endr\n         << 1.1737 << 0.0958 << -1.2695 << arma::endr;\n\n  CheckMatrices(output, result, 1e-1);\n  result.clear();\n\n  // Deterministic Forward Pass test.\n  output = model.TrainingMean();\n  result << 3.33333333 << arma::endr\n         << 3.1 << arma::endr\n         << 3.06666666 << arma::endr;\n\n  CheckMatrices(output, result, 1e-1);\n  result.clear();\n\n  output = model.TrainingVariance();\n  result << 2.2956 << arma::endr\n         << 2.0467 << arma::endr\n         << 1.9356 << arma::endr;\n\n  CheckMatrices(output, result, 1e-1);\n  result.clear();\n\n  model.Deterministic() = true;\n  model.Forward(std::move(input), std::move(output));\n\n  result << 1.1658 << 0.1100 << -1.2757 << arma::endr\n         << 1.2579 << -0.0699 << -1.1880 << arma::endr\n         << 1.1737 << 0.0958 << -1.2695 << arma::endr;\n\n  CheckMatrices(output, result, 1e-1);\n}\n\n/**\n * BatchNorm layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientBatchNormTest)\n{\n  // Add function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randn(10, 256);\n      arma::mat target;\n      target.ones(1, 256);\n\n      model = new FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<BatchNorm<> >(10);\n      model->Add<Linear<> >(10, 2);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 256, false);\n      model->Gradient(model->Parameters(), 0, gradient, 256);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>* model;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/**\n * Simple Transposed Convolution layer test.\n */\nBOOST_AUTO_TEST_CASE(SimpleTransposedConvolutionLayerTest)\n{\n  arma::mat output, input, delta;\n\n  TransposedConvolution<> module1(1, 1, 3, 3, 1, 1, 0, 0, 4, 4);\n  // Test the Forward function.\n  input = arma::linspace<arma::colvec>(0, 15, 16);\n  module1.Parameters() = arma::mat(9 + 1, 1, arma::fill::zeros);\n  module1.Parameters()(0) = 1.0;\n  module1.Parameters()(8) = 2.0;\n  module1.Reset();\n  module1.Forward(std::move(input), std::move(output));\n  // Value calculated using tensorflow.nn.conv2d_transpose()\n  BOOST_REQUIRE_EQUAL(arma::accu(output), 360.0);\n\n  // Test the Backward function.\n  module1.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 720);\n\n  TransposedConvolution<> module2(1, 1, 4, 4, 1, 1, 2, 2, 5, 5);\n  // Test the forward function.\n  input = arma::linspace<arma::colvec>(0, 24, 25);\n  module2.Parameters() = arma::mat(16 + 1, 1, arma::fill::zeros);\n  module2.Parameters()(0) = 1.0;\n  module2.Parameters()(3) = 1.0;\n  module2.Parameters()(6) = 1.0;\n  module2.Parameters()(9) = 1.0;\n  module2.Parameters()(12) = 1.0;\n  module2.Parameters()(15) = 2.0;\n  module2.Reset();\n  module2.Forward(std::move(input), std::move(output));\n  // Value calculated using tensorflow.nn.conv2d_transpose()\n  BOOST_REQUIRE_EQUAL(arma::accu(output), 2100.0);\n\n  // Test the backward function.\n  module2.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 7740);\n\n  TransposedConvolution<> module3(1, 1, 3, 3, 1, 1, 1, 1, 5, 5);\n  // Test the forward function.\n  input = arma::linspace<arma::colvec>(0, 24, 25);\n  module3.Parameters() = arma::mat(9 + 1, 1, arma::fill::zeros);\n  module3.Parameters()(1) = 2.0;\n  module3.Parameters()(2) = 4.0;\n  module3.Parameters()(3) = 3.0;\n  module3.Parameters()(8) = 1.0;\n  module3.Reset();\n  module3.Forward(std::move(input), std::move(output));\n  // Value calculated using tensorflow.nn.conv2d_transpose()\n  BOOST_REQUIRE_EQUAL(arma::accu(output), 3000.0);\n\n  // Test the backward function.\n  module3.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 21480);\n\n  TransposedConvolution<> module4(1, 1, 3, 3, 1, 1, 2, 2, 5, 5);\n  // Test the forward function.\n  input = arma::linspace<arma::colvec>(0, 24, 25);\n  module4.Parameters() = arma::mat(9 + 1, 1, arma::fill::zeros);\n  module4.Parameters()(2) = 2.0;\n  module4.Parameters()(4) = 4.0;\n  module4.Parameters()(6) = 6.0;\n  module4.Parameters()(8) = 8.0;\n  module4.Reset();\n  module4.Forward(std::move(input), std::move(output));\n  // Value calculated using tensorflow.nn.conv2d_transpose()\n  BOOST_REQUIRE_EQUAL(arma::accu(output), 6000.0);\n\n  // Test the backward function.\n  module4.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 86208);\n\n  TransposedConvolution<> module5(1, 1, 3, 3, 2, 2, 0, 0, 5, 5);\n  // Test the forward function.\n  input = arma::linspace<arma::colvec>(0, 24, 25);\n  module5.Parameters() = arma::mat(9 + 1, 1, arma::fill::zeros);\n  module5.Parameters()(2) = 8.0;\n  module5.Parameters()(4) = 6.0;\n  module5.Parameters()(6) = 4.0;\n  module5.Parameters()(8) = 2.0;\n  module5.Reset();\n  module5.Forward(std::move(input), std::move(output));\n  // Value calculated using tensorflow.nn.conv2d_transpose()\n  BOOST_REQUIRE_EQUAL(arma::accu(output), 6000.0);\n\n  // Test the backward function.\n  module5.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 83808);\n\n  TransposedConvolution<> module6(1, 1, 3, 3, 2, 2, 1, 1, 5, 5);\n  // Test the forward function.\n  input = arma::linspace<arma::colvec>(0, 24, 25);\n  module6.Parameters() = arma::mat(9 + 1, 1, arma::fill::zeros);\n  module6.Parameters()(0) = 8.0;\n  module6.Parameters()(3) = 6.0;\n  module6.Parameters()(6) = 2.0;\n  module6.Parameters()(8) = 4.0;\n  module6.Reset();\n  module6.Forward(std::move(input), std::move(output));\n  // Value calculated using tensorflow.nn.conv2d_transpose()\n  BOOST_REQUIRE_EQUAL(arma::accu(output), 6000.0);\n\n  // Test the backward function.\n  module6.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 87264);\n\n  TransposedConvolution<> module7(1, 1, 3, 3, 2, 2, 1, 1, 6, 6);\n  // Test the forward function.\n  input = arma::linspace<arma::colvec>(0, 35, 36);\n  module7.Parameters() = arma::mat(9 + 1, 1, arma::fill::zeros);\n  module7.Parameters()(0) = 8.0;\n  module7.Parameters()(2) = 6.0;\n  module7.Parameters()(4) = 2.0;\n  module7.Parameters()(8) = 4.0;\n  module7.Reset();\n  module7.Forward(std::move(input), std::move(output));\n  // Value calculated using tensorflow.nn.conv2d_transpose()\n  BOOST_REQUIRE_EQUAL(arma::accu(output), 12600.0);\n\n  // Test the backward function.\n  module7.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 185500);\n}\n\n/**\n * Transposed Convolution layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientTransposedConvolutionLayerTest)\n{\n  // Add function gradient instantiation.\n  // To make this test robust, check it five times.\n  bool pass = false;\n  for (size_t trial = 0; trial < 5; trial++)\n  {\n    struct GradientFunction\n    {\n      GradientFunction()\n      {\n        input = arma::linspace<arma::colvec>(0, 35, 36);\n        target = arma::mat(\"1\");\n\n        model = new FFN<NegativeLogLikelihood<>, RandomInitialization>();\n        model->Predictors() = input;\n        model->Responses() = target;\n        model->Add<TransposedConvolution<> >(1, 1, 3, 3, 2, 2, 1, 1, 6, 6);\n        model->Add<LogSoftMax<> >();\n      }\n\n      ~GradientFunction()\n      {\n        delete model;\n      }\n\n      double Gradient(arma::mat& gradient) const\n      {\n        double error = model->Evaluate(model->Parameters(), 0, 1);\n        model->Gradient(model->Parameters(), 0, gradient, 1);\n        return error;\n      }\n\n      arma::mat& Parameters() { return model->Parameters(); }\n\n      FFN<NegativeLogLikelihood<>, RandomInitialization>* model;\n      arma::mat input, target;\n    } function;\n\n    if (CheckGradient(function) < 1e-3)\n    {\n      pass = true;\n      break;\n    }\n  }\n  BOOST_REQUIRE_EQUAL(pass, true);\n}\n\n/**\n * Simple MultiplyMerge module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleMultiplyMergeLayerTest)\n{\n  arma::mat output, input, delta;\n  input = arma::ones(10, 1);\n\n  for (size_t i = 0; i < 5; ++i)\n  {\n    MultiplyMerge<> module(false, false);\n    const size_t numMergeModules = math::RandInt(2, 10);\n    for (size_t m = 0; m < numMergeModules; ++m)\n    {\n      IdentityLayer<> identityLayer;\n      identityLayer.Forward(std::move(input),\n          std::move(identityLayer.OutputParameter()));\n\n      module.Add<IdentityLayer<> >(identityLayer);\n    }\n\n    // Test the Forward function.\n    module.Forward(std::move(input), std::move(output));\n    BOOST_REQUIRE_EQUAL(10, arma::accu(output));\n\n    // Test the Backward function.\n    module.Backward(std::move(input), std::move(output), std::move(delta));\n    BOOST_REQUIRE_EQUAL(arma::accu(output), arma::accu(delta));\n  }\n}\n\n/**\n * Simple Atrous Convolution layer test.\n */\nBOOST_AUTO_TEST_CASE(SimpleAtrousConvolutionLayerTest)\n{\n  arma::mat output, input, delta;\n\n  AtrousConvolution<> module1(1, 1, 3, 3, 1, 1, 0, 0, 7, 7, 2, 2);\n  // Test the Forward function.\n  input = arma::linspace<arma::colvec>(0, 48, 49);\n  module1.Parameters() = arma::mat(9 + 1, 1, arma::fill::zeros);\n  module1.Parameters()(0) = 1.0;\n  module1.Parameters()(8) = 2.0;\n  module1.Reset();\n  module1.Forward(std::move(input), std::move(output));\n  // Value calculated using tensorflow.nn.atrous_conv2d()\n  BOOST_REQUIRE_EQUAL(arma::accu(output), 792.0);\n\n  // Test the Backward function.\n  module1.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 2376);\n\n  AtrousConvolution<> module2(1, 1, 3, 3, 2, 2, 0, 0, 7, 7, 2, 2);\n  // Test the forward function.\n  input = arma::linspace<arma::colvec>(0, 48, 49);\n  module2.Parameters() = arma::mat(9 + 1, 1, arma::fill::zeros);\n  module2.Parameters()(0) = 1.0;\n  module2.Parameters()(3) = 1.0;\n  module2.Parameters()(6) = 1.0;\n  module2.Reset();\n  module2.Forward(std::move(input), std::move(output));\n  // Value calculated using tensorflow.nn.conv2d()\n  BOOST_REQUIRE_EQUAL(arma::accu(output), 264.0);\n\n  // Test the backward function.\n  module2.Backward(std::move(input), std::move(output), std::move(delta));\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 792.0);\n}\n\n/**\n * Atrous Convolution layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientAtrousConvolutionLayerTest)\n{\n  // Add function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::linspace<arma::colvec>(0, 35, 36);\n      target = arma::mat(\"1\");\n\n      model = new FFN<NegativeLogLikelihood<>, RandomInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<AtrousConvolution<> >(1, 1, 3, 3, 1, 1, 0, 0, 6, 6, 2, 2);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<NegativeLogLikelihood<>, RandomInitialization>* model;\n    arma::mat input, target;\n  } function;\n\n  // TODO: this tolerance seems far higher than necessary.  The implementation\n  // should be checked.\n  BOOST_REQUIRE_LE(CheckGradient(function), 0.2);\n}\n\n/**\n * Tests the LayerNorm layer.\n */\nBOOST_AUTO_TEST_CASE(LayerNormTest)\n{\n  arma::mat input, output;\n  input << 5.1 << 3.5 << arma::endr\n        << 4.9 << 3.0 << arma::endr\n        << 4.7 << 3.2 << arma::endr;\n\n  LayerNorm<> model(input.n_rows);\n  model.Reset();\n\n  model.Forward(std::move(input), std::move(output));\n  arma::mat result;\n  result << 1.2247 << 1.2978 << arma::endr\n         << 0 << -1.1355 << arma::endr\n         << -1.2247 << -0.1622 << arma::endr;\n\n  CheckMatrices(output, result, 1e-1);\n  result.clear();\n\n  output = model.Mean();\n  result << 4.9000 << 3.2333 << arma::endr;\n\n  CheckMatrices(output, result, 1e-1);\n  result.clear();\n\n  output = model.Variance();\n  result << 0.0267 << 0.0422 << arma::endr;\n\n  CheckMatrices(output, result, 1e-1);\n}\n\n/**\n * LayerNorm layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientLayerNormTest)\n{\n  // Add function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randn(10, 256);\n      arma::mat target;\n      target.ones(1, 256);\n\n      model = new FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<LayerNorm<> >(10);\n      model->Add<Linear<> >(10, 2);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 256, false);\n      model->Gradient(model->Parameters(), 0, gradient, 256);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>* model;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/**\n * Test if the AddMerge layer is able to forward the\n * Forward/Backward/Gradient calls.\n */\nBOOST_AUTO_TEST_CASE(AddMergeRunTest)\n{\n  arma::mat output, input, delta, error;\n\n  AddMerge<> module(true, true);\n\n  Linear<>* linear = new Linear<>(10, 10);\n  module.Add(linear);\n\n  linear->Parameters().randu();\n  linear->Reset();\n\n  input = arma::zeros(10, 1);\n  module.Forward(std::move(input), std::move(output));\n\n  double parameterSum = arma::accu(linear->Parameters().submat(\n      100, 0, linear->Parameters().n_elem - 1, 0));\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(input), std::move(delta));\n\n  // Clean up before we break,\n  delete linear;\n\n  BOOST_REQUIRE_CLOSE(parameterSum, arma::accu(output), 1e-3);\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 0);\n}\n\n/**\n * Test if the MultiplyMerge layer is able to forward the\n * Forward/Backward/Gradient calls.\n */\nBOOST_AUTO_TEST_CASE(MultiplyMergeRunTest)\n{\n  arma::mat output, input, delta, error;\n\n  MultiplyMerge<> module(true, true);\n\n  Linear<>* linear = new Linear<>(10, 10);\n  module.Add(linear);\n\n  linear->Parameters().randu();\n  linear->Reset();\n\n  input = arma::zeros(10, 1);\n  module.Forward(std::move(input), std::move(output));\n\n  double parameterSum = arma::accu(linear->Parameters().submat(\n      100, 0, linear->Parameters().n_elem - 1, 0));\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(input), std::move(delta));\n\n  // Clean up before we break,\n  delete linear;\n\n  BOOST_REQUIRE_CLOSE(parameterSum, arma::accu(output), 1e-3);\n  BOOST_REQUIRE_EQUAL(arma::accu(delta), 0);\n}\n\n/**\n * Simple subview module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleSubviewLayerTest)\n{\n  arma::mat output, input, delta, outputMat;\n  Subview<> moduleRow(1, 10, 19);\n\n  // Test the Forward function for a vector.\n  input = arma::ones(20, 1);\n  moduleRow.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_EQUAL(output.n_rows, 10);\n\n  Subview<> moduleMat(4, 3, 6, 0, 2);\n\n  // Test the Forward function for a matrix.\n  input = arma::ones(20, 8);\n  moduleMat.Forward(std::move(input), std::move(outputMat));\n  BOOST_REQUIRE_EQUAL(outputMat.n_rows, 12);\n  BOOST_REQUIRE_EQUAL(outputMat.n_cols, 2);\n\n  // Test the Backward function.\n  moduleMat.Backward(std::move(input), std::move(input), std::move(delta));\n  BOOST_REQUIRE_EQUAL(accu(delta), 160);\n  BOOST_REQUIRE_EQUAL(delta.n_rows, 20);\n}\n\n/**\n * Subview index test.\n */\nBOOST_AUTO_TEST_CASE(SubviewIndexTest)\n{\n  arma::mat outputEnd, outputMid, outputStart, input, delta;\n  input = arma::linspace<arma::vec>(1, 20, 20);\n\n  // Slicing from the initial indices.\n  Subview<> moduleStart(1, 0, 9);\n  arma::mat subStart = arma::linspace<arma::vec>(1, 10, 10);\n\n  moduleStart.Forward(std::move(input), std::move(outputStart));\n  CheckMatrices(outputStart, subStart);\n\n  // Slicing from the mid indices.\n  Subview<> moduleMid(1, 6, 15);\n  arma::mat subMid = arma::linspace<arma::vec>(7, 16, 10);\n\n  moduleMid.Forward(std::move(input), std::move(outputMid));\n  CheckMatrices(outputMid, subMid);\n\n  // Slicing from the end indices.\n  Subview<> moduleEnd(1, 10, 19);\n  arma::mat subEnd = arma::linspace<arma::vec>(11, 20, 10);\n\n  moduleEnd.Forward(std::move(input), std::move(outputEnd));\n  CheckMatrices(outputEnd, subEnd);\n}\n\n/**\n * Subview batch test.\n */\nBOOST_AUTO_TEST_CASE(SubviewBatchTest)\n{\n  arma::mat output, input, outputCol, outputMat, outputDef;\n\n  // All rows selected.\n  Subview<> moduleCol(1, 0, 19);\n\n  // Test with inSize 1.\n  input = arma::ones(20, 8);\n  moduleCol.Forward(std::move(input), std::move(outputCol));\n  CheckMatrices(outputCol, input);\n\n  // Few rows and columns selected.\n  Subview<> moduleMat(4, 3, 6, 0, 2);\n\n  // Test with inSize greater than 1.\n  moduleMat.Forward(std::move(input), std::move(outputMat));\n  output = arma::ones(12, 2);\n  CheckMatrices(outputMat, output);\n\n  // endCol changed to 3 by default.\n  Subview<> moduleDef(4, 1, 6, 0, 4);\n\n  // Test with inSize greater than 1 and endCol >= inSize.\n  moduleDef.Forward(std::move(input), std::move(outputDef));\n  output = arma::ones(24, 2);\n  CheckMatrices(outputDef, output);\n}\n\n/*\n * Simple Reparametrization module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleReparametrizationLayerTest)\n{\n  arma::mat input, output, delta;\n  Reparametrization<> module(5);\n\n  // Test the Forward function. As the mean is zero and the standard\n  // deviation is small, after multiplying the gaussian sample, the\n  // output should be small enough.\n  input = join_cols(arma::ones<arma::mat>(5, 1) * -15,\n      arma::zeros<arma::mat>(5, 1));\n  module.Forward(std::move(input), std::move(output));\n  BOOST_REQUIRE_LE(arma::accu(output), 1e-5);\n\n  // Test the Backward function.\n  arma::mat gy = arma::zeros<arma::mat>(5, 1);\n  module.Backward(std::move(input), std::move(gy), std::move(delta));\n  BOOST_REQUIRE(arma::accu(delta) != 0); // klBackward will be added.\n}\n\n/**\n * Reparametrization module stochastic boolean test.\n */\nBOOST_AUTO_TEST_CASE(ReparametrizationLayerStochasticTest)\n{\n  arma::mat input, outputA, outputB;\n  Reparametrization<> module(5, false);\n\n  input = join_cols(arma::ones<arma::mat>(5, 1),\n      arma::zeros<arma::mat>(5, 1));\n\n  // Test if two forward passes generate same output.\n  module.Forward(std::move(input), std::move(outputA));\n  module.Forward(std::move(input), std::move(outputB));\n\n  CheckMatrices(outputA, outputB);\n}\n\n/**\n * Reparametrization module includeKl boolean test.\n */\nBOOST_AUTO_TEST_CASE(ReparametrizationLayerIncludeKlTest)\n{\n  arma::mat input, output, gy, delta;\n  Reparametrization<> module(5, true, false);\n\n  input = join_cols(arma::ones<arma::mat>(5, 1),\n      arma::zeros<arma::mat>(5, 1));\n  module.Forward(std::move(input), std::move(output));\n\n  // As KL divergence is not included, with the above inputs, the delta\n  // matrix should be all zeros.\n  gy = arma::zeros(output.n_rows, output.n_cols);\n  module.Backward(std::move(output), std::move(gy), std::move(delta));\n\n  BOOST_REQUIRE_EQUAL(arma::accu(std::move(delta)), 0);\n}\n\n/**\n * Jacobian Reparametrization module test.\n */\nBOOST_AUTO_TEST_CASE(JacobianReparametrizationLayerTest)\n{\n  for (size_t i = 0; i < 5; i++)\n  {\n    const size_t inputElementsHalf = math::RandInt(2, 1000);\n\n    arma::mat input;\n    input.set_size(inputElementsHalf * 2, 1);\n\n    Reparametrization<> module(inputElementsHalf, false, false);\n\n    double error = JacobianTest(module, input);\n    BOOST_REQUIRE_LE(error, 1e-5);\n  }\n}\n\n/**\n * Reparametrization layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientReparametrizationLayerTest)\n{\n  // Linear function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(10, 1);\n      target = arma::mat(\"1\");\n\n      model = new FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<Linear<> >(10, 6);\n      model->Add<Reparametrization<> >(3, false, true, 1);\n      model->Add<Linear<> >(3, 2);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>* model;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/**\n * Reparametrization layer beta numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientReparametrizationLayerBetaTest)\n{\n  // Linear function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(10, 2);\n      target = arma::mat(\"1 1\");\n\n      model = new FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<Linear<> >(10, 6);\n      // Use a value of beta not equal to 1.\n      model->Add<Reparametrization<> >(3, false, true, 2);\n      model->Add<Linear<> >(3, 2);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>* model;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/**\n * Simple residual module test.\n */\nBOOST_AUTO_TEST_CASE(SimpleResidualLayerTest)\n{\n  arma::mat outputA, outputB, input, deltaA, deltaB;\n\n  Sequential<>* sequential = new Sequential<>(true);\n  Residual<>* residual = new Residual<>(true);\n\n  Linear<>* linearA = new Linear<>(10, 10);\n  linearA->Parameters().randu();\n  linearA->Reset();\n  Linear<>* linearB = new Linear<>(10, 10);\n  linearB->Parameters().randu();\n  linearB->Reset();\n\n  // Add the same layers (with the same parameters) to both Sequential and\n  // Residual object.\n  sequential->Add(linearA);\n  sequential->Add(linearB);\n\n  residual->Add(linearA);\n  residual->Add(linearB);\n\n  // Test the Forward function (pass the same input to both).\n  input = arma::randu(10, 1);\n  sequential->Forward(std::move(input), std::move(outputA));\n  residual->Forward(std::move(input), std::move(outputB));\n\n  CheckMatrices(outputA, outputB - input);\n\n  // Test the Backward function (pass the same error to both).\n  sequential->Backward(std::move(input), std::move(input), std::move(deltaA));\n  residual->Backward(std::move(input), std::move(input), std::move(deltaB));\n\n  CheckMatrices(deltaA, deltaB - input);\n\n  delete sequential;\n  delete residual;\n  delete linearA;\n  delete linearB;\n}\n\n/**\n * Sequential layer numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientSequentialLayerTest)\n{\n  // Linear function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(10, 1);\n      target = arma::mat(\"1\");\n\n      model = new FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n\n      sequential = new Sequential<>();\n      sequential->Add<Linear<> >(10, 10);\n      sequential->Add<ReLULayer<> >();\n      sequential->Add<Linear<> >(10, 5);\n      sequential->Add<ReLULayer<> >();\n\n      model->Add(sequential);\n      model->Add<Linear<> >(5, 2);\n      model->Add<LogSoftMax<> >();\n    }\n\n    ~GradientFunction()\n    {\n      sequential->DeleteModules();\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<NegativeLogLikelihood<>, NguyenWidrowInitialization>* model;\n    Sequential<>* sequential;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n// General ANN serialization test.\ntemplate<typename LayerType>\nvoid ANNLayerSerializationTest(LayerType& layer)\n{\n  arma::mat input(5, 100, arma::fill::randu);\n  arma::mat output(5, 100, arma::fill::randu);\n\n  FFN<NegativeLogLikelihood<>, ann::RandomInitialization> model;\n  model.Add<Linear<>>(input.n_rows, 10);\n  model.Add<LayerType>(layer);\n  model.Add<ReLULayer<>>();\n  model.Add<Linear<>>(10, output.n_rows);\n  model.Add<LogSoftMax<>>();\n\n  ens::StandardSGD opt(0.1, 1, 5, -100, false);\n  model.Train(input, output, opt);\n\n  arma::mat originalOutput;\n  model.Predict(input.col(0), originalOutput);\n\n  // Now serialize the model.\n  FFN<NegativeLogLikelihood<>, ann::RandomInitialization> xmlModel, textModel,\n      binaryModel;\n  SerializeObjectAll(model, xmlModel, textModel, binaryModel);\n\n  // Ensure that predictions are the same.\n  arma::mat modelOutput, xmlOutput, textOutput, binaryOutput;\n  model.Predict(input.col(0), modelOutput);\n  xmlModel.Predict(input.col(0), xmlOutput);\n  textModel.Predict(input.col(0), textOutput);\n  binaryModel.Predict(input.col(0), binaryOutput);\n\n  CheckMatrices(originalOutput, modelOutput, 1e-5);\n  CheckMatrices(originalOutput, xmlOutput, 1e-5);\n  CheckMatrices(originalOutput, textOutput, 1e-5);\n  CheckMatrices(originalOutput, binaryOutput, 1e-5);\n}\n\n/**\n * Simple serialization test for batch normalization layer.\n */\nBOOST_AUTO_TEST_CASE(BatchNormSerializationTest)\n{\n  BatchNorm<> layer(10);\n  ANNLayerSerializationTest(layer);\n}\n\n/**\n * Simple serialization test for layer normalization layer.\n */\nBOOST_AUTO_TEST_CASE(LayerNormSerializationTest)\n{\n  LayerNorm<> layer(10);\n  ANNLayerSerializationTest(layer);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "4356ac74409f63bfb90eecd09da10c1e675b41c2", "size": 69635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/ann_layer_test.cpp", "max_stars_repo_name": "MuLx10/mlpack", "max_stars_repo_head_hexsha": "860c4c6d4fafd3f6dea600245c78bbef6d8018be", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/ann_layer_test.cpp", "max_issues_repo_name": "MuLx10/mlpack", "max_issues_repo_head_hexsha": "860c4c6d4fafd3f6dea600245c78bbef6d8018be", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/ann_layer_test.cpp", "max_forks_repo_name": "MuLx10/mlpack", "max_forks_repo_head_hexsha": "860c4c6d4fafd3f6dea600245c78bbef6d8018be", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4224489796, "max_line_length": 80, "alphanum_fraction": 0.6523156459, "num_tokens": 19897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.55189352091524}}
{"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": "#ifndef CAMERA_H\n#define CAMERA_H\n\n#include <Eigen/Dense>\n#include <iostream>\n\n#include \"math.h\"\n\nusing namespace Eigen;\n\nnamespace SnowSimulator {\n\n#define PI (3.14159265358979323)\n#define EPS_D (0.00000000001)\n#define EPS_F (0.00001f)\n#define INF_D (std::numeric_limits<double>::infinity())\n#define INF_F (std::numeric_limits<float>::infinity())\n\n/*\n  Takes any kind of number and converts from degrees to radians.\n*/\ntemplate <typename T> inline T radians(T deg) { return deg * (PI / 180); }\n\n/*\n  Takes any kind of number and converts from radians to degrees.\n*/\ntemplate <typename T> inline T degrees(T rad) { return rad * (180 / PI); }\n\n/*\n  Takes any kind of number, as well as a lower and upper bound, and clamps the\n  number to be within the bound.\n  NOTE: x, lo, and hi must all be the same type or compilation will fail. A\n        common mistake is to pass an int for x and size_ts for lo and hi.\n*/\ntemplate <typename T> inline T clamp(T x, T lo, T hi) {\n  return std::min(std::max(x, lo), hi);\n}\n\nclass Camera {\npublic:\n  /*\n    Sets the field of view to match screen screenW/H.\n    NOTE: data and screenW/H will almost certainly disagree about the aspect\n          ratio. screenW/H are treated as the source of truth, and the field\n          of view is expanded along whichever dimension is too narrow.\n    NOTE2: info.hFov and info.vFov are expected to be in DEGREES.\n  */\n  void configure(double nearClip, double farClip, double hFov, double vFov,\n                 size_t screenW, size_t screenH);\n\n  /*\n    Phi and theta are in RADIANS.\n  */\n  void place(const Vector3d &targetPos, const double phi, const double theta,\n             const double r, const double minR, const double maxR);\n\n  std::string param_string() { return \"\"; }\n\n  /*\n    Copies just placement data from the other camera.\n  */\n  void copy_placement(const Camera &other);\n\n  /*\n    Updates the screen size to be the specified size, keeping screenDist\n    constant.\n  */\n  void set_screen_size(const size_t screenW, const size_t screenH);\n\n  /*\n    Translates the camera such that a value at distance d directly in front of\n    the camera moves by (dx, dy). Note that dx and dy are in screen coordinates,\n    while d is in world-space coordinates (like pos/dir/up).\n  */\n  void move_by(const double dx, const double dy, const double d);\n\n  /*\n    Move the specified amount along the view axis.\n  */\n  void move_forward(const double dist);\n\n  /*\n    Rotate by the specified amount around the target.\n  */\n  void rotate_by(const double dPhi, const double dTheta);\n\n  Vector3d position() const { return pos; }\n  Vector3d view_point() const { return targetPos; }\n  Vector3d up_dir() const { return c2w.col(1); }\n\n  double v_fov() const { return vFov; }\n  double aspect_ratio() const { return ar; }\n\n  double near_clip() const { return nearClip; }\n  double far_clip() const { return farClip; }\n\n  // virtual void dump_settings(std::string filename);\n  // virtual void load_settings(std::string filename);\n\nprivate:\n  // Computes pos, screenXDir, screenYDir from target, r, phi, theta.\n  void compute_position();\n\n  // Field of view aspect ratio, clipping planes.\n  double hFov, vFov, ar, nearClip, farClip;\n\n  // Current position and target point (the point the camera is looking at).\n  Vector3d pos, targetPos;\n\n  // Orientation relative to target, and min & max distance from the target.\n  double phi, theta, r, minR, maxR;\n\n  // camera-to-world rotation matrix (note: also need to translate a\n  // camera-space point by 'pos' to perform a full camera-to-world\n  // transform)\n  Matrix3d c2w;\n\n  // Info about screen to render to; it corresponds to the camera's full field\n  // of view at some distance.\n  size_t screenW, screenH;\n  double screenDist;\n};\n\n} // namespace SnowSimulator\n\n#endif // CAMERA_H\n", "meta": {"hexsha": "a3d3a2cbfd1ae3f39640988e04081504fe0975af", "size": 3788, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/camera.hpp", "max_stars_repo_name": "kvchen/snowsim", "max_stars_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/camera.hpp", "max_issues_repo_name": "kvchen/snowsim", "max_issues_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-14T16:38:11.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-14T16:38:11.000Z", "max_forks_repo_path": "src/camera.hpp", "max_forks_repo_name": "kvchen/snowsim", "max_forks_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_forks_repo_licenses": ["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.8267716535, "max_line_length": 80, "alphanum_fraction": 0.6995776135, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5518934995892671}}
{"text": "#include <boost/graph/king_ordering.hpp>\n", "meta": {"hexsha": "ffa60128bd7413b3a37f8f7bf2ca45af44bf72f3", "size": 41, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_graph_king_ordering.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_graph_king_ordering.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_graph_king_ordering.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 20.5, "max_line_length": 40, "alphanum_fraction": 0.8048780488, "num_tokens": 10, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5518934953085545}}
{"text": "#include <Eigen/Dense>\n\n#include <ancse/config.hpp>\n#include <ancse/cfl_condition.hpp>\n#include <ancse/fvm_rate_of_change.hpp>\n#include <ancse/snapshot_writer.hpp>\n#include <ancse/time_loop.hpp>\n\nstatic int n_vars = 1;\n\ntemplate<class F>\nEigen::MatrixXd ic(const F &f, const Grid &grid) {\n    Eigen::MatrixXd u0(n_vars, grid.n_cells);\n    for(int i = 0; i < grid.n_cells; ++i) {\n        u0.col(i) = f(cell_center(grid, i));\n    }\n\n    return u0;\n}\n\nTimeLoop make_fvm(const nlohmann::json &config,\n                  const Grid &grid,\n                  std::shared_ptr<Model> &model)\n{\n    double t_end = config[\"t_end\"];\n    double cfl_number = config[\"cfl_number\"];\n\n    auto n_ghost = grid.n_ghost;\n    auto n_cells = grid.n_cells;\n\n    auto n_vars = model->get_nvars();\n\n    auto simulation_time = std::make_shared<SimulationTime>(t_end);\n    auto fvm_rate_of_change\n            = make_fvm_rate_of_change(config, grid, model,\n                                      simulation_time);\n    auto boundary_condition\n            = make_boundary_condition(n_ghost,\n                                      config[\"boundary_condition\"]);\n    auto time_integrator = make_runge_kutta(config,\n                                            fvm_rate_of_change,\n                                            boundary_condition,\n                                            n_vars, n_cells);\n    auto cfl_condition = make_cfl_condition(grid, model, cfl_number);\n    auto snapshot_writer = std::make_shared< JSONSnapshotWriter<FVM> >\n            (grid, model, simulation_time,\n             std::string(config[\"output_dir\"]),\n             std::string(config[\"output_file\"]));\n\n    return TimeLoop(simulation_time, time_integrator,\n                    cfl_condition, snapshot_writer);\n}\n\nvoid shock_test(const nlohmann::json &config)\n{\n    std::shared_ptr<Model> model = std::make_shared<Burgers>();\n\n    auto fn = [](double x) {\n        Eigen::VectorXd u(n_vars);\n        if (x <= 0.5) { // left state\n            u(0) = 1;\n        } else {        // right state\n            u(0) = 0;\n        }\n        return u;\n    };\n\n    int n_ghost = config[\"n_ghost\"];\n    int n_cells = int(config[\"n_interior_cells\"]) + n_ghost * 2;\n\n    auto grid = Grid({0.0, 1.0}, n_cells, n_ghost);\n    auto u0 = ic(fn, grid);\n\n    auto fvm = make_fvm(config, grid, model);\n    fvm(u0);\n}\n\nvoid rarefaction_test(const nlohmann::json &config)\n{\n    std::shared_ptr<Model> model = std::make_shared<Burgers>();\n\n    auto fn = [](double x) {\n        Eigen::VectorXd u(n_vars);\n        if (x <= 0.5) { // left state\n            u(0) = 0;\n        } else {        // right state\n            u(0) = 1;\n        }\n        return u;\n    };\n\n    int n_ghost = config[\"n_ghost\"];\n    int n_cells = int(config[\"n_interior_cells\"]) + n_ghost * 2;\n\n    auto grid = Grid({0.0, 1.0}, n_cells, n_ghost);\n    auto u0 = ic(fn, grid);\n\n    auto fvm = make_fvm(config, grid, model);\n    fvm(u0);\n}\n\nint main(int argc, char* const argv[])\n{\n    nlohmann::json config;\n    std::string fileName;\n    if (argc == 2) {\n        fileName = argv[1];\n    } else {\n        fileName = \"../config.json\";\n    }\n    config = get_config (fileName);\n\n    std::string ic_key = config[\"initial_conditions\"];\n    if (ic_key == \"shock\") {\n        shock_test(config);\n    } else if (ic_key == \"rarefaction\") {\n        rarefaction_test(config);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "2266ec27b7690135f0fd54e4acece7368c12c1f5", "size": 3376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series2_workbench/hyp_sys_1d/src/fvm_burgers.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_handout/hyp_sys_1d/src/fvm_burgers.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_handout/hyp_sys_1d/src/fvm_burgers.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": 27.6721311475, "max_line_length": 70, "alphanum_fraction": 0.5630924171, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5518870861327739}}
{"text": "#define BOOST_TEST_MODULE TestStaticMatrix\n#include <boost/test/unit_test.hpp>\n\n#include <amgcl/value_type/static_matrix.hpp>\n\nBOOST_AUTO_TEST_SUITE( test_static_matrix )\n\nBOOST_AUTO_TEST_CASE( sum ) {\n    amgcl::static_matrix<int, 2, 2> a = {{1, 2, 3, 4}};\n    amgcl::static_matrix<int, 2, 2> b = {{4, 3, 2, 1}};\n    amgcl::static_matrix<int, 2, 2> c = a + b;\n\n    for(int i = 0; i < 2; ++i)\n        for(int j = 0; j < 2; ++j)\n            BOOST_CHECK_EQUAL(c(i,j), 5);\n}\n\nBOOST_AUTO_TEST_CASE( minus ) {\n    amgcl::static_matrix<int, 2, 2> a = {{5, 5, 5, 5}};\n    amgcl::static_matrix<int, 2, 2> b = {{4, 3, 2, 1}};\n    amgcl::static_matrix<int, 2, 2> c = a - b;\n\n    for(int i = 0; i < 4; ++i)\n        BOOST_CHECK_EQUAL(c(i), i+1);\n}\n\nBOOST_AUTO_TEST_CASE( product ) {\n    amgcl::static_matrix<int, 2, 2> a = {{2, 1, 1, 2}};\n    amgcl::static_matrix<int, 2, 2> c = a * a;\n\n    BOOST_CHECK_EQUAL(c(0,0), 5);\n    BOOST_CHECK_EQUAL(c(0,1), 4);\n    BOOST_CHECK_EQUAL(c(1,0), 4);\n    BOOST_CHECK_EQUAL(c(1,1), 5);\n}\n\nBOOST_AUTO_TEST_CASE( scale ) {\n    amgcl::static_matrix<int, 2, 2> a = {{1, 2, 3, 4}};\n    amgcl::static_matrix<int, 2, 2> c = 2 * a;\n\n    for(int i = 0; i < 4; ++i)\n        BOOST_CHECK_EQUAL(c(i), 2 * (i+1));\n}\n\nBOOST_AUTO_TEST_CASE( inner_product ) {\n    amgcl::static_matrix<int, 2, 1> a = {{1, 2}};\n    int c = amgcl::math::inner_product(a, a);\n\n    BOOST_CHECK_EQUAL(c, 5);\n}\n\nBOOST_AUTO_TEST_CASE( inverse ) {\n    amgcl::static_matrix<double, 2, 2> a = {{2.0, -1.0, -1.0, 2.0}};\n    amgcl::static_matrix<double, 2, 2> b = amgcl::math::inverse(a);\n    amgcl::static_matrix<double, 2, 2> c = b * a;\n\n    for(int i = 0; i < 2; ++i)\n        for(int j = 0; j < 2; ++j)\n            BOOST_CHECK_SMALL(c(i,j) - (i == j), 1e-8);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3b3ba5c77dd9c12d713b138208338754d07de702", "size": 1772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_static_matrix.cpp", "max_stars_repo_name": "ilyapopov/amgcl", "max_stars_repo_head_hexsha": "c781719e2f961c161a7ff0cf2c168ac6949ac510", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-11-07T08:31:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T20:35:28.000Z", "max_issues_repo_path": "tests/test_static_matrix.cpp", "max_issues_repo_name": "ilyapopov/amgcl", "max_issues_repo_head_hexsha": "c781719e2f961c161a7ff0cf2c168ac6949ac510", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_static_matrix.cpp", "max_forks_repo_name": "ilyapopov/amgcl", "max_forks_repo_head_hexsha": "c781719e2f961c161a7ff0cf2c168ac6949ac510", "max_forks_repo_licenses": ["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.126984127, "max_line_length": 68, "alphanum_fraction": 0.5761851016, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5518870853480166}}
{"text": "// Copyright 2019, Collabora, Ltd.\n// SPDX-License-Identifier: BSL-1.0\n/*!\n * @file\n * @brief  C++ sensor fusion/filtering code that uses flexkalman\n * @author Ryan Pavlik <ryan.pavlik@collabora.com>\n * @ingroup aux_tracking\n */\n\n#pragma once\n\n#ifndef __cplusplus\n#error \"This header is C++-only.\"\n#endif\n\n#include \"tracking/t_lowpass.hpp\"\n#include \"tracking/t_lowpass_vector.hpp\"\n#include \"math/m_api.h\"\n#include \"util/u_time.h\"\n#include \"util/u_debug.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"flexkalman/EigenQuatExponentialMap.h\"\n\nDEBUG_GET_ONCE_BOOL_OPTION(simple_imu_debug, \"SIMPLE_IMU_DEBUG\", false)\n\n#define SIMPLE_IMU_DEBUG(MSG)                                                  \\\n\tdo {                                                                   \\\n\t\tif (debug_) {                                                  \\\n\t\t\tprintf(\"SimpleIMU(%p): \" MSG \"\\n\",                     \\\n\t\t\t       (const void *)this);                            \\\n\t\t}                                                              \\\n\t} while (0)\n\nnamespace xrt_fusion {\nclass SimpleIMUFusion\n{\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\t/*!\n\t * @param gravity_rate Value in [0, 1] indicating how much the\n\t * accelerometer should affect the orientation each second.\n\t */\n\texplicit SimpleIMUFusion(double gravity_rate = 0.9)\n\t    : gravity_scale_(gravity_rate),\n\t      debug_(debug_get_bool_option_simple_imu_debug())\n\t{\n\t\tSIMPLE_IMU_DEBUG(\"Creating instance\");\n\t}\n\n\tbool\n\tvalid() const noexcept\n\t{\n\t\treturn started_;\n\t}\n\n\tEigen::Quaterniond\n\tgetQuat() const\n\t{\n\t\treturn quat_;\n\t}\n\n\tEigen::Quaterniond\n\tgetPredictedQuat(timepoint_ns timestamp) const\n\t{\n\t\ttimepoint_ns state_time =\n\t\t    std::max(last_accel_timestamp_, last_gyro_timestamp_);\n\t\ttime_duration_ns delta_ns =\n\t\t    (state_time == 0) ? 1e6 : timestamp - state_time;\n\t\tfloat dt = time_ns_to_s(delta_ns);\n\t\treturn quat_ * flexkalman::util::quat_exp(angVel_ * dt * 0.5);\n\t}\n\n\tEigen::Vector3d\n\tgetRotationVec() const\n\t{\n\t\treturn flexkalman::util::quat_ln(quat_);\n\t}\n\n\t//! in world space\n\tEigen::Vector3d const &\n\tgetAngVel() const\n\t{\n\t\treturn angVel_;\n\t}\n\n\tbool\n\thandleGyro(Eigen::Vector3d const &gyro, timepoint_ns timestamp)\n\t{\n\t\tif (!started_) {\n\n\t\t\tSIMPLE_IMU_DEBUG(\n\t\t\t    \"Discarding gyro report before first usable accel \"\n\t\t\t    \"report\");\n\t\t\treturn false;\n\t\t}\n\t\ttime_duration_ns delta_ns =\n\t\t    (last_gyro_timestamp_ == 0)\n\t\t        ? 1e6\n\t\t        : timestamp - last_gyro_timestamp_;\n\t\tif (delta_ns > 1e10) {\n\n\t\t\tSIMPLE_IMU_DEBUG(\"Clamping integration period\");\n\t\t\t// Limit integration to 1/10th of a second\n\t\t\t// Does not affect updating the last gyro timestamp.\n\t\t\tdelta_ns = 1e10;\n\t\t}\n\t\tfloat dt = time_ns_to_s(delta_ns);\n\t\tlast_gyro_timestamp_ = timestamp;\n\t\tEigen::Vector3d incRot = gyro * dt;\n\t\t// Crude handling of \"approximately zero\"\n\t\tif (incRot.squaredNorm() < 1.e-8) {\n\n\t\t\tSIMPLE_IMU_DEBUG(\n\t\t\t    \"Discarding gyro data that is approximately zero\");\n\t\t\treturn false;\n\t\t}\n\n\t\tangVel_ = gyro;\n\n\t\t// Update orientation\n\t\tquat_ = quat_ * flexkalman::util::quat_exp(incRot * 0.5);\n\n\t\treturn true;\n\t}\n\n\t/*!\n\t * Returns a coefficient to correct the scale of the accelerometer\n\t * reading.\n\t */\n\tdouble\n\tgetAccelScaleFactor() const\n\t{\n\t\treturn MATH_GRAVITY_M_S2 / gravity_filter_.getState();\n\t}\n\n\tbool\n\thandleAccel(Eigen::Vector3d const &accel, timepoint_ns timestamp)\n\t{\n\t\tuint64_t delta_ns = (last_accel_timestamp_ == 0)\n\t\t                        ? 1e6\n\t\t                        : timestamp - last_accel_timestamp_;\n\t\tfloat dt = time_ns_to_s(delta_ns);\n\t\tif (!started_) {\n\t\t\tauto diff = std::abs(accel.norm() - MATH_GRAVITY_M_S2);\n\t\t\tif (diff > 1.) {\n\t\t\t\t// We're moving, don't start it now.\n\n\t\t\t\tSIMPLE_IMU_DEBUG(\n\t\t\t\t    \"Can't start tracker with this accel \"\n\t\t\t\t    \"sample: we're moving too much.\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Initially, just set it to totally trust gravity.\n\t\t\tstarted_ = true;\n\t\t\tquat_ = Eigen::Quaterniond::FromTwoVectors(\n\t\t\t    accel.normalized(), Eigen::Vector3d::UnitY());\n\t\t\taccel_filter_.addSample(accel, timestamp);\n\t\t\tgravity_filter_.addSample(accel.norm(), timestamp);\n\t\t\tlast_accel_timestamp_ = timestamp;\n\n\t\t\tSIMPLE_IMU_DEBUG(\"Got a usable startup accel report\");\n\t\t\treturn true;\n\t\t}\n\t\tlast_accel_timestamp_ = timestamp;\n\t\taccel_filter_.addSample(accel, timestamp);\n\t\tgravity_filter_.addSample(accel.norm(), timestamp);\n\n\t\t// Adjust scale of accelerometer\n\t\tEigen::Vector3d adjusted_accel =\n\t\t    accel_filter_.getState() * getAccelScaleFactor();\n\t\tauto diff = std::abs(adjusted_accel.norm() - MATH_GRAVITY_M_S2);\n\t\tauto scale = 1. - diff;\n\t\tif (scale <= 0) {\n\t\t\t// Too far from gravity to be useful/trusted.\n\t\t\tSIMPLE_IMU_DEBUG(\n\t\t\t    \"Too far from gravity to be useful/trusted.\");\n\t\t\treturn false;\n\t\t}\n\n\t\t// This should match the global gravity vector if the rotation\n\t\t// is right.\n\t\tEigen::Vector3d measuredGravityDirection =\n\t\t    (quat_ * adjusted_accel).normalized();\n\t\tauto incremental = Eigen::Quaterniond::FromTwoVectors(\n\t\t    measuredGravityDirection, Eigen::Vector3d::UnitY());\n\n\t\tdouble alpha = scale * gravity_scale_ * dt;\n\t\tEigen::Quaterniond scaledIncrementalQuat =\n\t\t    Eigen::Quaterniond::Identity().slerp(alpha, incremental);\n\n\t\t// Update orientation\n\t\tquat_ = scaledIncrementalQuat * quat_;\n\n\t\treturn true;\n\t}\n\n\t/*!\n\t * Use this to obtain the residual, world-space acceleration not\n\t * associated with gravity, after incorporating a measurement.\n\t */\n\tEigen::Vector3d\n\tgetCorrectedWorldAccel(Eigen::Vector3d const &accel) const\n\t{\n\t\tEigen::Vector3d adjusted_accel = accel * getAccelScaleFactor();\n\t\treturn (quat_ * adjusted_accel) -\n\t\t       (Eigen::Vector3d::UnitY() * MATH_GRAVITY_M_S2);\n\t}\n\n\tEigen::Matrix3d\n\tgetRotationMatrix() const\n\t{\n\t\treturn quat_.toRotationMatrix();\n\t}\n\n\tvoid\n\tpostCorrect()\n\t{\n\t\tquat_.normalize();\n\t}\n\nprivate:\n\tEigen::Vector3d angVel_{Eigen::Vector3d::Zero()};\n\tEigen::Quaterniond quat_{Eigen::Quaterniond::Identity()};\n\tdouble gravity_scale_;\n\tLowPassIIRVectorFilter<3, double> accel_filter_{\n\t    200 /* hz cutoff frequency */};\n\tLowPassIIRFilter<double> gravity_filter_{1 /* hz cutoff frequency */};\n\tuint64_t last_accel_timestamp_{0};\n\tuint64_t last_gyro_timestamp_{0};\n\tbool started_{false};\n\tbool debug_{false};\n};\n} // namespace xrt_fusion\n", "meta": {"hexsha": "c21ba299982dd22b4c37821fce613e3e3c9c77fd", "size": 6213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/xrt/auxiliary/tracking/t_imu_fusion.hpp", "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/tracking/t_imu_fusion.hpp", "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/tracking/t_imu_fusion.hpp", "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.1050420168, "max_line_length": 80, "alphanum_fraction": 0.6660228553, "num_tokens": 1666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5518352272929109}}
{"text": "#pragma once\n\n#include <random>\n\n#include <Eigen/Dense>\n#include <data/data.hpp>\n#include <utils/math/kalman_multivariate.hpp>\n#include <utils/system.hpp>\n\nnamespace hyped {\nnamespace navigation {\n\nclass KalmanFilter {\n public:\n  KalmanFilter(uint32_t n = 3, uint32_t m = 1, uint32_t k = 0);\n  void setup();\n  void updateStateTransitionMatrix(data::nav_t dt);\n  void updateMeasurementCovarianceMatrix(const data::nav_t var);\n  data::nav_t filter(data::nav_t z);\n  // transfer estimate to NavigationVector\n  data::nav_t getEstimate();\n  // transfer estimate variances to NavigationVector\n  const data::nav_t getEstimateVariance();\n\n private:\n  // state dimensionality\n  uint32_t n_;\n  // measurement dimensionality\n  uint32_t m_;\n  // control dimensionality default = 0\n  uint32_t k_;\n  utils::math::KalmanMultivariate kalmanFilter_;\n\n  // covariance matrix variances\n  static constexpr float kInitialErrorVariance          = 0.5;\n  static constexpr float kStateTransitionVariance       = 0.02;\n  static constexpr float kTrackMeasurementVariance      = 0.001;\n  static constexpr float kElevatorMeasurementVariance   = 0.12;\n  static constexpr float kStationaryMeasurementVariance = 0.04;\n\n  // create initial error covariance matrix P\n  const Eigen::MatrixXf createInitialErrorCovarianceMatrix() const;\n\n  // create state transition matrix A\n  Eigen::MatrixXf createStateTransitionMatrix(data::nav_t dt) const;\n\n  // create measurement matrix H\n  Eigen::MatrixXf createMeasurementMatrix() const;\n\n  // create state transition coveriance matrix Q\n  const Eigen::MatrixXf createStateTransitionCovarianceMatrix() const;\n\n  // create measurement covariance matrices R\n  const Eigen::MatrixXf createTrackMeasurementCovarianceMatrix() const;\n  const Eigen::MatrixXf createElevatorMeasurementCovarianceMatrix() const;\n  const Eigen::MatrixXf createStationaryMeasurementCovarianceMatrix() const;\n};\n}  // namespace navigation\n}  // namespace hyped", "meta": {"hexsha": "6b18c79f9ba18d7669f9f3aeb05a1d6e4d1f4791", "size": 1938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/navigation/kalman_filter.hpp", "max_stars_repo_name": "Hyp-ed/hyped-2022", "max_stars_repo_head_hexsha": "9cac4632b660f569629cf0ad4048787f6017905d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T16:22:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:14:31.000Z", "max_issues_repo_path": "src/navigation/kalman_filter.hpp", "max_issues_repo_name": "Hyp-ed/hyped-2022", "max_issues_repo_head_hexsha": "9cac4632b660f569629cf0ad4048787f6017905d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 91.0, "max_issues_repo_issues_event_min_datetime": "2021-07-29T18:21:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:44:55.000Z", "max_forks_repo_path": "src/navigation/kalman_filter.hpp", "max_forks_repo_name": "Hyp-ed/hyped-2022", "max_forks_repo_head_hexsha": "9cac4632b660f569629cf0ad4048787f6017905d", "max_forks_repo_licenses": ["Apache-2.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.8474576271, "max_line_length": 76, "alphanum_fraction": 0.7698658411, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5518352219550935}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"common/equality.hpp\"\n#include \"algorithms/math/calc_angle_btw_clock_hands.hpp\"\n\nBOOST_AUTO_TEST_SUITE(CalcAngleBetweenClockHands)\n\nBOOST_AUTO_TEST_CASE(invalid_input)\n{\n    BOOST_CHECK(equal(CalcAngleBtwClockHands(-1, 4), 0.0));\n    BOOST_CHECK(equal(CalcAngleBtwClockHands(10, -90), 0.0));\n    BOOST_CHECK(equal(CalcAngleBtwClockHands(13, -3600), 0.0));\n}\n\nBOOST_AUTO_TEST_CASE(valid_input)\n{\n    BOOST_CHECK(equal(CalcAngleBtwClockHands(0, 0), 0.0));\n    BOOST_CHECK(equal(CalcAngleBtwClockHands(12, 60), 0.0));\n    BOOST_CHECK(equal(CalcAngleBtwClockHands(1, 0), 30.0));\n    BOOST_CHECK(equal(CalcAngleBtwClockHands(0, 1), 5.5));\n    BOOST_CHECK(equal(CalcAngleBtwClockHands(5, 24), 18.0));\n    BOOST_CHECK(equal(CalcAngleBtwClockHands(2, 20), 50.0));\n    BOOST_CHECK(equal(CalcAngleBtwClockHands(4, 15), 37.5));\n    BOOST_CHECK(equal(CalcAngleBtwClockHands(10, 43), 63.5));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e23df7c6aebbcb9714318865a598e15e5ba6fa37", "size": 955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/math/test_calc_angle_btw_clock_hands.cpp", "max_stars_repo_name": "iamantony/CppNotes", "max_stars_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T14:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T09:51:43.000Z", "max_issues_repo_path": "test/algorithms/math/test_calc_angle_btw_clock_hands.cpp", "max_issues_repo_name": "iamantony/CppNotes", "max_issues_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T07:38:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-02T11:00:58.000Z", "max_forks_repo_path": "test/algorithms/math/test_calc_angle_btw_clock_hands.cpp", "max_forks_repo_name": "iamantony/CppNotes", "max_forks_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-11T14:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T08:53:50.000Z", "avg_line_length": 35.3703703704, "max_line_length": 63, "alphanum_fraction": 0.7518324607, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5517028845729391}}
{"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 Nick Thompson, 2017\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#define BOOST_TEST_MODULE exp_sinh_quadrature_test\r\n\r\n#include <complex>\r\n#include <boost/multiprecision/cpp_complex.hpp>\r\n#include <boost/math/concepts/real_concept.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/math/quadrature/exp_sinh.hpp>\r\n#include <boost/math/special_functions/sinc.hpp>\r\n#include <boost/math/special_functions/bessel.hpp>\r\n#include <boost/multiprecision/cpp_bin_float.hpp>\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\n#include <boost/math/special_functions/next.hpp>\r\n#include <boost/math/special_functions/gamma.hpp>\r\n#include <boost/math/special_functions/sinc.hpp>\r\n#include <boost/type_traits/is_class.hpp>\r\n\r\n#ifdef BOOST_HAS_FLOAT128\r\n#include <boost/multiprecision/complex128.hpp>\r\n#endif\r\n\r\nusing std::exp;\r\nusing std::cos;\r\nusing std::tan;\r\nusing std::log;\r\nusing std::sqrt;\r\nusing std::abs;\r\nusing std::sinh;\r\nusing std::cosh;\r\nusing std::pow;\r\nusing std::atan;\r\nusing boost::multiprecision::cpp_bin_float_50;\r\nusing boost::multiprecision::cpp_bin_float_100;\r\nusing boost::multiprecision::cpp_bin_float_quad;\r\nusing boost::math::constants::pi;\r\nusing boost::math::constants::half_pi;\r\nusing boost::math::constants::two_div_pi;\r\nusing boost::math::constants::half;\r\nusing boost::math::constants::third;\r\nusing boost::math::constants::half;\r\nusing boost::math::constants::third;\r\nusing boost::math::constants::catalan;\r\nusing boost::math::constants::ln_two;\r\nusing boost::math::constants::root_two;\r\nusing boost::math::constants::root_two_pi;\r\nusing boost::math::constants::root_pi;\r\nusing boost::math::quadrature::exp_sinh;\r\n\r\n#if !defined(TEST1) && !defined(TEST2) && !defined(TEST3) && !defined(TEST4) && !defined(TEST5) && !defined(TEST6) && !defined(TEST7) && !defined(TEST8)\r\n#  define TEST1\r\n#  define TEST2\r\n#  define TEST3\r\n#  define TEST4\r\n#  define TEST5\r\n#  define TEST6\r\n#  define TEST7\r\n#  define TEST8\r\n#endif\r\n\r\n#ifdef BOOST_MSVC\r\n#pragma warning (disable:4127)\r\n#endif\r\n\r\n//\r\n// Coefficient generation code:\r\n//\r\ntemplate <class T>\r\nvoid print_levels(const T& v, const char* suffix)\r\n{\r\n   std::cout << \"{\\n\";\r\n   for (unsigned i = 0; i < v.size(); ++i)\r\n   {\r\n      std::cout << \"      { \";\r\n      for (unsigned j = 0; j < v[i].size(); ++j)\r\n      {\r\n         std::cout << v[i][j] << suffix << \", \";\r\n      }\r\n      std::cout << \"},\\n\";\r\n   }\r\n   std::cout << \"   };\\n\";\r\n}\r\n\r\ntemplate <class T>\r\nvoid print_levels(const std::pair<T, T>& p, const char* suffix = \"\")\r\n{\r\n   std::cout << \"   static const std::vector<std::vector<Real> > abscissa = \";\r\n   print_levels(p.first, suffix);\r\n   std::cout << \"   static const std::vector<std::vector<Real> > weights = \";\r\n   print_levels(p.second, suffix);\r\n}\r\n\r\ntemplate <class Real, class TargetType>\r\nstd::pair<std::vector<std::vector<Real>>, std::vector<std::vector<Real>> > generate_constants(unsigned max_rows)\r\n{\r\n   using boost::math::constants::half_pi;\r\n   using boost::math::constants::two_div_pi;\r\n   using boost::math::constants::pi;\r\n   auto g = [](Real t)->Real { return exp(half_pi<Real>()*sinh(t)); };\r\n   auto w = [](Real t)->Real { return cosh(t)*half_pi<Real>()*exp(half_pi<Real>()*sinh(t)); };\r\n\r\n   std::vector<std::vector<Real>> abscissa, weights;\r\n\r\n   std::vector<Real> temp;\r\n\r\n   Real tmp = (Real(boost::math::tools::log_min_value<TargetType>()) + log(Real(boost::math::tools::epsilon<TargetType>())))*0.5f;\r\n   Real t_min = asinh(two_div_pi<Real>()*tmp);\r\n   // truncate t_min to an exact binary value:\r\n   t_min = floor(t_min * 128) / 128;\r\n\r\n   std::cout << \"m_t_min = \" << t_min << \";\\n\";\r\n\r\n   // t_max is chosen to make g'(t_max) ~ sqrt(max) (g' grows faster than g).\r\n   // This will allow some flexibility on the users part; they can at least square a number function without overflow.\r\n   // But there is no unique choice; the further out we can evaluate the function, the better we can do on slowly decaying integrands.\r\n   const Real t_max = log(2 * two_div_pi<Real>()*log(2 * two_div_pi<Real>()*sqrt(Real(boost::math::tools::max_value<TargetType>()))));\r\n\r\n   Real h = 1;\r\n   for (Real t = t_min; t < t_max; t += h)\r\n   {\r\n      temp.push_back(g(t));\r\n   }\r\n   abscissa.push_back(temp);\r\n   temp.clear();\r\n\r\n   for (Real t = t_min; t < t_max; t += h)\r\n   {\r\n      temp.push_back(w(t * h));\r\n   }\r\n   weights.push_back(temp);\r\n   temp.clear();\r\n\r\n   for (unsigned row = 1; row < max_rows; ++row)\r\n   {\r\n      h /= 2;\r\n      for (Real t = t_min + h; t < t_max; t += 2 * h)\r\n         temp.push_back(g(t));\r\n      abscissa.push_back(temp);\r\n      temp.clear();\r\n   }\r\n   h = 1;\r\n   for (unsigned row = 1; row < max_rows; ++row)\r\n   {\r\n      h /= 2;\r\n      for (Real t = t_min + h; t < t_max; t += 2 * h)\r\n         temp.push_back(w(t));\r\n      weights.push_back(temp);\r\n      temp.clear();\r\n   }\r\n\r\n   return std::make_pair(abscissa, weights);\r\n}\r\n\r\n\r\ntemplate <class Real>\r\nconst exp_sinh<Real>& get_integrator()\r\n{\r\n   static const exp_sinh<Real> integrator(14);\r\n   return integrator;\r\n}\r\n\r\ntemplate <class Real>\r\nReal get_convergence_tolerance()\r\n{\r\n   return boost::math::tools::root_epsilon<Real>();\r\n}\r\n\r\ntemplate<class Real>\r\nvoid test_right_limit_infinite()\r\n{\r\n    std::cout << \"Testing right limit infinite for tanh_sinh in 'A Comparison of Three High Precision Quadrature Schemes' on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\r\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\r\n    Real Q;\r\n    Real Q_expected;\r\n    Real error;\r\n    Real L1;\r\n    auto integrator = get_integrator<Real>();\r\n\r\n    // Example 12\r\n    const auto f2 = [](const Real& t)->Real { return exp(-t)/sqrt(t); };\r\n    Q = integrator.integrate(f2, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = root_pi<Real>();\r\n    Real tol_mult = 1;\r\n    // Multiprecision type have higher error rates, probably evaluation of f() is less accurate:\r\n    if (std::numeric_limits<Real>::digits10 > std::numeric_limits<long double>::digits10)\r\n       tol_mult = 12;\r\n    else if (std::numeric_limits<Real>::digits10 > std::numeric_limits<double>::digits10)\r\n       tol_mult = 5;\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol * tol_mult);\r\n    // The integrand is strictly positive, so it coincides with the value of the integral:\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol * tol_mult);\r\n\r\n    auto f3 = [](Real t)->Real { Real z = exp(-t); if (z == 0) { return z; } return z*cos(t); };\r\n    Q = integrator.integrate(f3, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = half<Real>();\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    Q = integrator.integrate(f3, 10, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = boost::lexical_cast<Real>(\"-6.6976341310426674140007086979326069121526743314567805278252392932e-6\");\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, 10 * tol);\r\n    // Integrating through zero risks precision loss:\r\n    Q = integrator.integrate(f3, -10, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = boost::lexical_cast<Real>(\"-15232.3213626280525704332288302799653087046646639974940243044623285817777006\");\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, std::numeric_limits<Real>::digits10 > 30 ? 1000 * tol : tol);\r\n\r\n    auto f4 = [](Real t)->Real { return 1/(1+t*t); };\r\n    Q = integrator.integrate(f4, 1, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = pi<Real>()/4;\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\r\n    Q = integrator.integrate(f4, 20, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = boost::lexical_cast<Real>(\"0.0499583957219427614100062870348448814912770804235071744108534548299835954767\");\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\r\n    Q = integrator.integrate(f4, 500, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = boost::lexical_cast<Real>(\"0.0019999973333397333150476759363217553199063513829126652556286269630\");\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\r\n}\r\n\r\ntemplate<class Real>\r\nvoid test_left_limit_infinite()\r\n{\r\n    std::cout << \"Testing left limit infinite for 1/(1+t^2) on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\r\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\r\n    Real Q;\r\n    Real Q_expected;\r\n    Real error;\r\n    Real L1;\r\n    auto integrator = get_integrator<Real>();\r\n\r\n    // Example 11:\r\n    auto f1 = [](const Real& t)->Real { return 1/(1+t*t);};\r\n    Q = integrator.integrate(f1, std::numeric_limits<Real>::has_infinity ? -std::numeric_limits<Real>::infinity() : -boost::math::tools::max_value<Real>(), 0, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = half_pi<Real>();\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\r\n    Q = integrator.integrate(f1, std::numeric_limits<Real>::has_infinity ? -std::numeric_limits<Real>::infinity() : -boost::math::tools::max_value<Real>(), -20, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = boost::lexical_cast<Real>(\"0.0499583957219427614100062870348448814912770804235071744108534548299835954767\");\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\r\n    Q = integrator.integrate(f1, std::numeric_limits<Real>::has_infinity ? -std::numeric_limits<Real>::infinity() : -boost::math::tools::max_value<Real>(), -500, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = boost::lexical_cast<Real>(\"0.0019999973333397333150476759363217553199063513829126652556286269630\");\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\r\n}\r\n\r\n\r\n// Some examples of tough integrals from NR, section 4.5.4:\r\ntemplate<class Real>\r\nvoid test_nr_examples()\r\n{\r\n    using std::sin;\r\n    using std::cos;\r\n    using std::pow;\r\n    using std::exp;\r\n    using std::sqrt;\r\n    std::cout << \"Testing type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\r\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\r\n    std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\r\n    Real Q;\r\n    Real Q_expected;\r\n    Real L1;\r\n    Real error;\r\n    auto integrator = get_integrator<Real>();\r\n\r\n    auto f0 = [] (Real)->Real { return (Real) 0; };\r\n    Q = integrator.integrate(f0, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = 0;\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, 0.0f, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, 0.0f, tol);\r\n\r\n    auto f = [](const Real& x)->Real { return 1/(1+x*x); };\r\n    Q = integrator.integrate(f, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = half_pi<Real>();\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\r\n\r\n    auto f1 = [](Real x)->Real {\r\n        Real z1 = exp(-x);\r\n        if (z1 == 0)\r\n        {\r\n            return (Real) 0;\r\n        }\r\n        Real z2 = pow(x, -3*half<Real>())*z1;\r\n        if (z2 == 0)\r\n        {\r\n            return (Real) 0;\r\n        }\r\n        return sin(x*half<Real>())*z2;\r\n    };\r\n\r\n    Q = integrator.integrate(f1, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = sqrt(pi<Real>()*(sqrt((Real) 5) - 2));\r\n\r\n    // The integrand is oscillatory; the accuracy is low.\r\n    Real tol_mul = 1;\r\n    if (std::numeric_limits<Real>::digits10 > 40)\r\n       tol_mul = 500000;\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol_mul * tol);\r\n\r\n    auto f2 = [](Real x)->Real { return x > boost::math::tools::log_max_value<Real>() ? Real(0) : Real(pow(x, -(Real) 2/(Real) 7)*exp(-x*x)); };\r\n    Q = integrator.integrate(f2, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = half<Real>()*boost::math::tgamma((Real) 5/ (Real) 14);\r\n    tol_mul = 1;\r\n    if (std::numeric_limits<Real>::is_specialized == false)\r\n       tol_mul = 6;\r\n    else if (std::numeric_limits<Real>::digits10 > 40)\r\n       tol_mul = 100;\r\n    else\r\n       tol_mul = 3;\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol_mul * tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol_mul * tol);\r\n\r\n    auto f3 = [](Real x)->Real { return (Real) 1/ (sqrt(x)*(1+x)); };\r\n    Q = integrator.integrate(f3, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = pi<Real>();\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, 10*boost::math::tools::epsilon<Real>());\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, 10*boost::math::tools::epsilon<Real>());\r\n\r\n    auto f4 = [](const Real& t)->Real { return  t > boost::math::tools::log_max_value<Real>() ? Real(0) : Real(exp(-t*t*half<Real>())); };\r\n    Q = integrator.integrate(f4, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = root_two_pi<Real>()/2;\r\n    tol_mul = 1;\r\n    if (std::numeric_limits<Real>::digits10 > 40)\r\n       tol_mul = 5000;\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol_mul * tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol_mul * tol);\r\n\r\n    auto f5 = [](const Real& t)->Real { return 1/cosh(t);};\r\n    Q = integrator.integrate(f5, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = half_pi<Real>();\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol * 12);   // Fails at float precision without higher error rate\r\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol * 12);\r\n}\r\n\r\n// Definite integrals found in the CRC Handbook of Mathematical Formulas\r\ntemplate<class Real>\r\nvoid test_crc()\r\n{\r\n    using std::sin;\r\n    using std::pow;\r\n    using std::exp;\r\n    using std::sqrt;\r\n    using std::log;\r\n    using std::cos;\r\n    std::cout << \"Testing integral from CRC handbook on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\r\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\r\n    std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\r\n    Real Q;\r\n    Real Q_expected;\r\n    Real L1;\r\n    Real error;\r\n    auto integrator = get_integrator<Real>();\r\n\r\n    auto f0 = [](const Real& x)->Real { return x > boost::math::tools::log_max_value<Real>() ? Real(0) : Real(log(x)*exp(-x)); };\r\n    Q = integrator.integrate(f0, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = -boost::math::constants::euler<Real>();\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n\r\n    // Test the integral representation of the gamma function:\r\n    auto f1 = [](Real t)->Real { Real x = exp(-t);\r\n        if(x == 0)\r\n        {\r\n            return (Real) 0;\r\n        }\r\n        return pow(t, (Real) 12 - 1)*x;\r\n    };\r\n\r\n    Q = integrator.integrate(f1, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = boost::math::tgamma(12.0f);\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n\r\n    // Integral representation of the modified bessel function:\r\n    // K_5(12)\r\n    auto f2 = [](Real t)->Real {\r\n        Real x = 12*cosh(t);\r\n        if (x > boost::math::tools::log_max_value<Real>())\r\n        {\r\n            return (Real) 0;\r\n        }\r\n        return exp(-x)*cosh(5*t);\r\n    };\r\n    Q = integrator.integrate(f2, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = boost::math::cyl_bessel_k<int, Real>(5, 12);\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    // Laplace transform of cos(at)\r\n    Real a = 20;\r\n    Real s = 1;\r\n    auto f3 = [&](Real t)->Real {\r\n        Real x = s * t;\r\n        if (x > boost::math::tools::log_max_value<Real>())\r\n        {\r\n            return (Real) 0;\r\n        }\r\n        return cos(a * t) * exp(-x);\r\n    };\r\n\r\n    // Since the integrand is oscillatory, we increase the tolerance:\r\n    Real tol_mult = 10;\r\n    // Multiprecision type have higher error rates, probably evaluation of f() is less accurate:\r\n    if (!boost::is_class<Real>::value)\r\n    {\r\n       // For high oscillation frequency, the quadrature sum is ill-conditioned.\r\n       Q = integrator.integrate(f3, get_convergence_tolerance<Real>(), &error, &L1);\r\n       Q_expected = s/(a*a+s*s);\r\n       if (std::numeric_limits<Real>::digits10 > std::numeric_limits<double>::digits10)\r\n          tol_mult = 5000; // we should really investigate this more??\r\n       BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol_mult*tol);\r\n    }\r\n\r\n    //\r\n    // This one doesn't pass for real_concept..\r\n    //\r\n    if (std::numeric_limits<Real>::is_specialized)\r\n    {\r\n       // Laplace transform of J_0(t):\r\n       auto f4 = [&](Real t)->Real {\r\n          Real x = s * t;\r\n          if (x > boost::math::tools::log_max_value<Real>())\r\n          {\r\n             return (Real)0;\r\n          }\r\n          return boost::math::cyl_bessel_j(0, t) * exp(-x);\r\n       };\r\n\r\n       Q = integrator.integrate(f4, get_convergence_tolerance<Real>(), &error, &L1);\r\n       Q_expected = 1 / sqrt(1 + s*s);\r\n       tol_mult = 3;\r\n       // Multiprecision type have higher error rates, probably evaluation of f() is less accurate:\r\n       if (std::numeric_limits<Real>::digits10 > std::numeric_limits<long double>::digits10)\r\n          tol_mult = 750;\r\n       BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol_mult * tol);\r\n    }\r\n    auto f6 = [](const Real& t)->Real { return t > boost::math::tools::log_max_value<Real>() ? Real(0) : Real(exp(-t*t)*log(t));};\r\n    Q = integrator.integrate(f6, get_convergence_tolerance<Real>(), &error, &L1);\r\n    Q_expected = -boost::math::constants::root_pi<Real>()*(boost::math::constants::euler<Real>() + 2*ln_two<Real>())/4;\r\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n\r\n    // CRC Section 5.5, integral 591\r\n    // The parameter p allows us to control the strength of the singularity.\r\n    // Rapid convergence is not guaranteed for this function, as the branch cut makes it non-analytic on a disk.\r\n    // This converges only when our test type has an extended exponent range as all the area of the integral\r\n    // occurs so close to 0 (or 1) that we need abscissa values exceptionally small to find it.\r\n    // \"There's a lot of room at the bottom\".\r\n    // This version is transformed via argument substitution (exp(-x) for x) so that the integral is spread\r\n    // over (0, INF).\r\n    tol *= boost::math::tools::digits<Real>() > 100 ? 100000 : 75;\r\n    for (Real pn = 99; pn > 0; pn -= 10) {\r\n       Real p = pn / 100;\r\n       auto f = [&](Real x)->Real\r\n       {\r\n          return x > 1000 * boost::math::tools::log_max_value<Real>() ? Real(0) : Real(exp(-x * (1 - p) + p * log(-boost::math::expm1(-x))));\r\n       };\r\n       Q = integrator.integrate(f, get_convergence_tolerance<Real>(), &error, &L1);\r\n       Q_expected = 1 / boost::math::sinc_pi(p*pi<Real>());\r\n       /*\r\n       std::cout << std::setprecision(std::numeric_limits<Real>::max_digits10) << p << std::endl;\r\n       std::cout << std::setprecision(std::numeric_limits<Real>::max_digits10) << Q << std::endl;\r\n       std::cout << std::setprecision(std::numeric_limits<Real>::max_digits10) << Q_expected << std::endl;\r\n       std::cout << fabs((Q - Q_expected) / Q_expected) << std::endl;\r\n       */\r\n       BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    }\r\n    // and for p < 1:\r\n    for (Real p = -0.99; p < 0; p += 0.1) {\r\n       auto f = [&](Real x)->Real\r\n       {\r\n          return x > 1000 * boost::math::tools::log_max_value<Real>() ? Real(0) : Real(exp(-p * log(-boost::math::expm1(-x)) - (1 + p) * x));\r\n       };\r\n       Q = integrator.integrate(f, get_convergence_tolerance<Real>(), &error, &L1);\r\n       Q_expected = 1 / boost::math::sinc_pi(p*pi<Real>());\r\n       BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\r\n    }\r\n}\r\n\r\ntemplate<class Complex>\r\nvoid test_complex_modified_bessel()\r\n{\r\n    std::cout << \"Testing complex modified Bessel function on type \" << boost::typeindex::type_id<Complex>().pretty_name() << \"\\n\";\r\n    typedef typename Complex::value_type Real;\r\n    Real tol = 100 * boost::math::tools::epsilon<Real>();\r\n    Real error;\r\n    Real L1;\r\n    auto integrator = get_integrator<Real>();\r\n\r\n    // Integral Representation of Modified Complex Bessel function:\r\n    // https://en.wikipedia.org/wiki/Bessel_function#Modified_Bessel_functions\r\n    Complex z{2, 3};\r\n    const auto f = [&z](const Real& t)->Complex\r\n    {\r\n        using std::cosh;\r\n        using std::exp;\r\n        Real cosht = cosh(t);\r\n        if (cosht > boost::math::tools::log_max_value<Real>())\r\n        {\r\n            return Complex{0, 0};\r\n        }\r\n        Complex arg = -z*cosht;\r\n        Complex res = exp(arg);\r\n        return res;\r\n    };\r\n\r\n    Complex K0 = integrator.integrate(f, get_convergence_tolerance<Real>(), &error, &L1);\r\n\r\n    // Mathematica code: N[BesselK[0, 2 + 3 I], 140]\r\n    Real K0_x_expected = boost::lexical_cast<Real>(\"-0.08296852656762551490517953520589186885781541203818846830385526187936132191822538822296497597191327722262903004145527496422090506197776994\");\r\n    Real K0_y_expected = boost::lexical_cast<Real>(\"0.027949603635183423629723306332336002340909030265538548521150904238352846705644065168365102147901993976999717171115546662967229050834575193041\");\r\n    BOOST_CHECK_CLOSE_FRACTION(K0.real(), K0_x_expected, tol);\r\n    BOOST_CHECK_CLOSE_FRACTION(K0.imag(), K0_y_expected, tol);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(exp_sinh_quadrature_test)\r\n{\r\n   //\r\n   // Uncomment to generate the coefficients:\r\n   //\r\n\r\n   /*\r\n   std::cout << std::scientific << std::setprecision(8);\r\n   print_levels(generate_constants<cpp_bin_float_100, float>(8), \"f\");\r\n   std::cout << std::setprecision(18);\r\n   print_levels(generate_constants<cpp_bin_float_100, double>(8), \"\");\r\n   std::cout << std::setprecision(35);\r\n   print_levels(generate_constants<cpp_bin_float_100, cpp_bin_float_quad>(8), \"L\");\r\n   */\r\n\r\n#ifdef TEST1\r\n    test_left_limit_infinite<float>();\r\n    test_right_limit_infinite<float>();\r\n    test_nr_examples<float>();\r\n    test_crc<float>();\r\n#endif\r\n#ifdef TEST2\r\n    test_left_limit_infinite<double>();\r\n    test_right_limit_infinite<double>();\r\n    test_nr_examples<double>();\r\n    test_crc<double>();\r\n#endif\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n#ifdef TEST3\r\n    test_left_limit_infinite<long double>();\r\n    test_right_limit_infinite<long double>();\r\n    test_nr_examples<long double>();\r\n    test_crc<long double>();\r\n#endif\r\n#endif\r\n#ifdef TEST4\r\n    test_left_limit_infinite<cpp_bin_float_quad>();\r\n    test_right_limit_infinite<cpp_bin_float_quad>();\r\n    test_nr_examples<cpp_bin_float_quad>();\r\n    test_crc<cpp_bin_float_quad>();\r\n#endif\r\n\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n#ifdef TEST5\r\n    test_left_limit_infinite<boost::math::concepts::real_concept>();\r\n    test_right_limit_infinite<boost::math::concepts::real_concept>();\r\n    test_nr_examples<boost::math::concepts::real_concept>();\r\n    test_crc<boost::math::concepts::real_concept>();\r\n#endif\r\n#endif\r\n#ifdef TEST6\r\n    test_left_limit_infinite<boost::multiprecision::cpp_bin_float_50>();\r\n    test_right_limit_infinite<boost::multiprecision::cpp_bin_float_50>();\r\n    test_nr_examples<boost::multiprecision::cpp_bin_float_50>();\r\n    test_crc<boost::multiprecision::cpp_bin_float_50>();\r\n#endif\r\n#ifdef TEST7\r\n    test_left_limit_infinite<boost::multiprecision::cpp_dec_float_50>();\r\n    test_right_limit_infinite<boost::multiprecision::cpp_dec_float_50>();\r\n    test_nr_examples<boost::multiprecision::cpp_dec_float_50>();\r\n    //\r\n    // This one causes stack overflows on the CI machine, but not locally,\r\n    // assume it's due to resticted resources on the server, and <shrug> for now...\r\n    //\r\n#if ! BOOST_WORKAROUND(BOOST_MSVC, == 1900)\r\n    test_crc<boost::multiprecision::cpp_dec_float_50>();\r\n#endif\r\n#endif\r\n#ifdef TEST8\r\n    test_complex_modified_bessel<std::complex<float>>();\r\n    test_complex_modified_bessel<std::complex<double>>();\r\n    test_complex_modified_bessel<std::complex<long double>>();\r\n    #ifdef BOOST_HAS_FLOAT128\r\n        test_complex_modified_bessel<boost::multiprecision::complex128>();\r\n    #endif\r\n    test_complex_modified_bessel<boost::multiprecision::cpp_complex_quad>();\r\n#endif\r\n}\r\n", "meta": {"hexsha": "edde1ad30ae4d67e80253d9137ac5ce1c5f0fa41", "size": 24851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/libs/math/test/exp_sinh_quadrature_test.cpp", "max_stars_repo_name": "Jackarain/tinyrpc", "max_stars_repo_head_hexsha": "07060e3466776aa992df8574ded6c1616a1a31af", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/math/test/exp_sinh_quadrature_test.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "third_party/boost/libs/math/test/exp_sinh_quadrature_test.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 41.6264656616, "max_line_length": 211, "alphanum_fraction": 0.6512413987, "num_tokens": 6729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.551702877513015}}
{"text": "/*\n * Copyright Nick Thompson, 2019\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <random>\n#include <boost/core/demangle.hpp>\n#include <boost/math/interpolators/whittaker_shannon.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing boost::math::interpolators::whittaker_shannon;\n\ntemplate<class Real>\nvoid test_trivial()\n{\n    Real t0 = 0;\n    Real h = Real(1)/Real(16);\n    std::vector<Real> v{1.5};\n    std::vector<Real> v_copy = v;\n    auto ws = whittaker_shannon<decltype(v)>(std::move(v), t0, h);\n\n\n    Real expected = 0;\n    if(!CHECK_MOLLIFIED_CLOSE(expected, ws.prime(0), 10*std::numeric_limits<Real>::epsilon())) {\n        std::cerr << \"  Problem occurred at abscissa \" << 0 << \"\\n\";\n    }\n\n    expected = -v_copy[0]/h;\n    if(!CHECK_MOLLIFIED_CLOSE(expected, ws.prime(h), 10*std::numeric_limits<Real>::epsilon())) {\n        std::cerr << \"  Problem occurred at abscissa \" << 0 << \"\\n\";\n    }\n}\n\ntemplate<class Real>\nvoid test_knots()\n{\n    Real t0 = 0;\n    Real h = Real(1)/Real(16);\n    size_t n = 512;\n    std::vector<Real> v(n);\n    std::mt19937 gen(323723);\n    std::uniform_real_distribution<Real> dis(1.0, 2.0);\n\n    for(size_t i = 0;  i < n; ++i) {\n      v[i] = static_cast<Real>(dis(gen));\n    }\n    auto ws = whittaker_shannon<decltype(v)>(std::move(v), t0, h);\n\n    size_t i = 0;\n    while (i < n) {\n      Real t = t0 + i*h;\n      Real expected = ws[i];\n      Real computed = ws(t);\n      CHECK_ULP_CLOSE(expected, computed, 16);\n      ++i;\n    }\n}\n\ntemplate<class Real>\nvoid test_bump()\n{\n    using std::exp;\n    using std::abs;\n    using std::sqrt;\n    auto bump = [](Real x) { if (abs(x) >= 1) { return Real(0); } return exp(-Real(1)/(Real(1)-x*x)); };\n\n    auto bump_prime = [&bump](Real x) { Real z = 1-x*x; return -2*x*bump(x)/(z*z); };\n\n    Real t0 = -1;\n    size_t n = 2049;\n    Real h = Real(2)/Real(n-1);\n\n    std::vector<Real> v(n);\n    for(size_t i = 0; i < n; ++i) {\n        Real t = t0 + i*h;\n        v[i] = bump(t);\n    }\n\n\n    std::vector<Real> v_copy = v;\n    auto ws = whittaker_shannon<decltype(v)>(std::move(v), t0, h);\n\n    // Test the knots:\n    for(size_t i = v_copy.size()/4; i < 3*v_copy.size()/4; ++i) {\n        Real t = t0 + i*h;\n        Real expected = v_copy[i];\n        Real computed = ws(t);\n        if(!CHECK_MOLLIFIED_CLOSE(expected, computed, 10*std::numeric_limits<Real>::epsilon())) {\n            std::cerr << \"  Problem occurred at abscissa \" << t << \"\\n\";\n        }\n\n        Real expected_prime = bump_prime(t);\n        Real computed_prime = ws.prime(t);\n        if(!CHECK_MOLLIFIED_CLOSE(expected_prime, computed_prime, 1000*std::numeric_limits<Real>::epsilon())) {\n            std::cerr << \"  Problem occurred at abscissa \" << t << \"\\n\";\n        }\n\n    }\n\n    std::mt19937 gen(323723);\n    std::uniform_real_distribution<long double> dis(-0.85, 0.85);\n\n    size_t i = 0;\n    while (i++ < 1000)\n    {\n        Real t = static_cast<Real>(dis(gen));\n        Real expected = bump(t);\n        Real computed = ws(t);\n        if(!CHECK_MOLLIFIED_CLOSE(expected, computed, 10*std::numeric_limits<Real>::epsilon())) {\n            std::cerr << \"  Problem occurred at abscissa \" << t << \"\\n\";\n        }\n\n        Real expected_prime = bump_prime(t);\n        Real computed_prime = ws.prime(t);\n        if(!CHECK_MOLLIFIED_CLOSE(expected_prime, computed_prime, sqrt(std::numeric_limits<Real>::epsilon()))) {\n            std::cerr << \"  Problem occurred at abscissa \" << t << \"\\n\";\n        }\n    }\n}\n\n\nint main()\n{\n    test_knots<float>();\n    test_knots<double>();\n    test_knots<long double>();\n\n    test_bump<double>();\n    test_bump<long double>();\n\n    test_trivial<float>();\n    test_trivial<double>();\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "3afebb51a67fb80afe78e9658d3afb431959bc3b", "size": 4001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/whittaker_shannon_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "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/test/whittaker_shannon_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T08:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-06T20:49:05.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/test/whittaker_shannon_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 27.979020979, "max_line_length": 112, "alphanum_fraction": 0.5926018495, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5517028753440996}}
{"text": "#include \"square_subset_finder.h\"\n\n#include <vector>\n\n#include <NTL/vec_vec_GF2.h>\n\n#include \"util.h\"\n\nnamespace {\n    using namespace NTL;\n    using namespace std;\n}\n\nnamespace gnfs {\n    template <typename RowGenerator>\n    vector<pair<typename SquareSubsetFinder<RowGenerator>::Index, vec_GF2>> SquareSubsetFinder<RowGenerator>::get() {\n        long rows = matrix_.NumRows();\n        long cols = rg_.num_cols();\n        // If matrix_ doesn't have more rows than columns,\n        // we need to generate more rows.\n        // But our loop below will generate the (cols+1)th row,\n        // so we stop this loop when there's a square matrix.\n        while (rows < cols) {\n            matrix_.SetDims(rows + 1, cols);\n            rows++;\n            pair<Index, vec_GF2> new_row = rg_.get();\n            indices_.push_back(new_row.first);\n            matrix_[rows - 1] = new_row.second;\n        }\n\n        // Overall course of events:\n        // basis_cursor_ is a bitfield representing which elements\n        // of basis_ to add together for the next subset we return.\n        // We iterate through all values of basis_cursor_\n        // until it reaches 2^(basis.NumRows()),\n        // at which point we request a new row from rg_.\n        // Then we iterate through the new basis,\n        // suppressing returned sets that do not include the new row.\n        //\n        // This loop is a shoddy equivalent to an infinite generator.\n        // Each iteration through the loop produces a candidate\n        // that we can return.\n        // Either we return it,\n        // saving tons of state so we know where we left off,\n        // or we continue; and produce a new candidate.\n        while (true) {\n            basis_cursor_++;\n            if (basis_cursor_ == 0 || NumBits(basis_cursor_) >= basis_.NumRows()) {\n                // Request a new row for the matrix.\n                matrix_.SetDims(rows + 1, cols);\n                rows++;\n                pair<Index, vec_GF2> new_row = rg_.get();\n                indices_.push_back(new_row.first);\n                matrix_[rows - 1] = new_row.second;\n\n                // Generate a new basis.\n                kernel(basis_, matrix_);\n\n                // Reset the cursor.\n                suppress_ = (basis_cursor_ != 0);\n                // Skip 0 because returning the empty set is stupid.\n                basis_cursor_ = 1;\n            }\n\n            // Compute the sum of the indicated rows in the basis.\n            vec_GF2 basis_rows_to_sum = bitfield(basis_cursor_);\n            basis_rows_to_sum.SetLength(basis_.NumRows());\n            vec_GF2 their_sum = basis_rows_to_sum * basis_;\n            // Now their_sum is a vector of length rows,\n            // indicating which rows are in the square subset\n            // that we're about to return.\n\n            // Check suppression.\n            if (suppress_ && their_sum[rows - 1] == 0) continue;\n\n            // For each 1 in sum, add the corresponding entry of matrix_\n            // to the returned vector.\n            vector<pair<Index, vec_GF2>> ret;\n            for (int i = 0; i < their_sum.length(); i++) {\n                if (their_sum[i] != 0) {\n                    Index first = indices_[i];\n                    vec_GF2 second = matrix_[i];\n                    ret.emplace_back(first, second);\n                }\n            }\n\n            // Make sure we're not returning the empty vector.\n            if (!ret.size()) continue;\n\n            return ret;\n        }\n    }\n}\n", "meta": {"hexsha": "eef4ab0320ca0b2f003bc4d4a58be5a8b748489d", "size": 3491, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/square_subset_finder.cc", "max_stars_repo_name": "MathSquared/general-number-field-sieve", "max_stars_repo_head_hexsha": "0ab4efd447f24b726597ec9a6ddae669b1709a20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-25T09:36:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T11:54:46.000Z", "max_issues_repo_path": "src/square_subset_finder.cc", "max_issues_repo_name": "MathSquared/general-number-field-sieve", "max_issues_repo_head_hexsha": "0ab4efd447f24b726597ec9a6ddae669b1709a20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T10:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T10:34:07.000Z", "max_forks_repo_path": "src/square_subset_finder.cc", "max_forks_repo_name": "MathSquared/general-number-field-sieve", "max_forks_repo_head_hexsha": "0ab4efd447f24b726597ec9a6ddae669b1709a20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1382978723, "max_line_length": 117, "alphanum_fraction": 0.5585792037, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5516832229913265}}
{"text": "#ifndef SPLX_INTERNAL_TYPES_HPP\n#define SPLX_INTERNAL_TYPES_HPP\n\n#include <Eigen/Dense>\n\nnamespace splx {\n\ntemplate<typename T>\nusing Row = Eigen::Matrix<T, 1, Eigen::Dynamic>;\n\ntemplate<typename T>\nusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\ntemplate<typename T, unsigned int DIM>\nusing VectorDIM = Eigen::Matrix<T, DIM, 1>;\n\ntemplate<typename T>\nusing Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\ntemplate<typename T, unsigned int DIM>\nusing Hyperplane = Eigen::Hyperplane<T, DIM>;\n\nusing Index = Eigen::Index;\n\ntemplate<typename T, unsigned int DIM>\nusing AlignedBox = Eigen::AlignedBox<T, DIM>;\n\ntemplate<typename T>\nstruct Constraint {\n    using _Row = Row<T>;\n\n    Constraint(const _Row& c, T l, T u, bool sc = false, T sw = T(1)):\n        coeff(c), lb(l), ub(u), soft_convertible(sc), soft_weight(sw) {\n\n    }\n\n    Constraint(const _Row&& c, T l, T u, bool sc = false, T sw = T(1)):\n        coeff(std::move(c)), lb(l), ub(u), soft_convertible(sc), soft_weight(sw) {\n\n    }\n\n    _Row coeff;\n    T lb;\n    T ub;\n    bool soft_convertible;\n    T soft_weight;\n};\n\n}\n\n#endif", "meta": {"hexsha": "f8d9eb3c7528ab65fe0e51a0a6d5b6e94eaac97e", "size": 1100, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/splx/types.hpp", "max_stars_repo_name": "baskinburak/splx", "max_stars_repo_head_hexsha": "0f02bb8c42890e9dde6d8f48f3214e91f88af0fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/splx/types.hpp", "max_issues_repo_name": "baskinburak/splx", "max_issues_repo_head_hexsha": "0f02bb8c42890e9dde6d8f48f3214e91f88af0fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-21T00:30:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-27T01:39:41.000Z", "max_forks_repo_path": "include/splx/types.hpp", "max_forks_repo_name": "baskinburak/splx", "max_forks_repo_head_hexsha": "0f02bb8c42890e9dde6d8f48f3214e91f88af0fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-12T08:17:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T08:17:37.000Z", "avg_line_length": 21.568627451, "max_line_length": 82, "alphanum_fraction": 0.67, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.5516832203102963}}
{"text": "\n/******************************************************************************\n\n  Implementation of mean.\n\n  Copyright (c) 2013\n  Alexander Rukletsov <rukletsov@gmail.com>\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions\n  are met:\n  1.  Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n  2.  Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and/or other materials provided with the distribution.\n\n  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND\n  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n  ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n  SUCH DAMAGE.\n\n*******************************************************************************/\n\n#ifndef MEAN_HPP_BB12C8E0_E48D_11E2_83DA_9FFD99890B3C\n#define MEAN_HPP_BB12C8E0_E48D_11E2_83DA_9FFD99890B3C\n\n#include <vector>\n#include <algorithm>\n#include <functional>\n#include <stdexcept>\n\n// Suppress annoying MSVC's C4244 conversion warnings popping out from boost::accumulators\n// library (boost::numeric::functional namespace) mainly due to division operation\n// in mean computation. Suppress MSVC's C4512 warning for boost auxiliary classes as well.\n#ifdef _MSC_VER\n#   pragma warning(push)\n#   pragma warning(disable:4244)\n#   pragma warning(disable:4512)\n#endif // _MSC_VER\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n\n#ifdef _MSC_VER\n#   pragma warning(pop)\n#endif // _MSC_VER\n\nnamespace bo {\nnamespace math {\n\n// Returns the mean of the given samples.\ntemplate <typename SampleType>\nSampleType mean(const std::vector<SampleType>& data)\n{\n    // The mean of an empty set is meaningless.\n    if (data.size() == 0)\n        throw std::logic_error(\"The mean of an empty set is meaningless.\");\n\n    // Initialize boost accumulator.\n    namespace accs = boost::accumulators;\n    typedef accs::accumulator_set<SampleType, accs::stats<accs::tag::mean> > Acc;\n    Acc acc;\n\n    // Fill accumulator with data.\n    acc = std::for_each(data.begin(), data.end(), acc);\n\n    // Request and return mean.\n    return accs::mean(acc);\n}\n\n} // namespace math\n} // namespace bo\n\n#endif // MEAN_HPP_BB12C8E0_E48D_11E2_83DA_9FFD99890B3C\n", "meta": {"hexsha": "5ef2550a9f8319e78ba3b89f66c303ce80fff38a", "size": 3076, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/math/mean.hpp", "max_stars_repo_name": "rukletsov/bo", "max_stars_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T03:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T10:53:32.000Z", "max_issues_repo_path": "Bo/math/mean.hpp", "max_issues_repo_name": "rukletsov/bo", "max_issues_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bo/math/mean.hpp", "max_forks_repo_name": "rukletsov/bo", "max_forks_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1882352941, "max_line_length": 90, "alphanum_fraction": 0.7204161248, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5516832155789786}}
{"text": "\r\n// Copyright Aleksey Gurtovoy 2003-2004\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. \r\n// (See accompanying file LICENSE_1_0.txt or copy at \r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// See http://www.boost.org/libs/mpl for documentation.\r\n\r\n// $Id: numeric_ops.cpp 49268 2008-10-11 06:26:17Z agurtovoy $\r\n// $Date: 2008-10-11 02:26:17 -0400 (Sat, 11 Oct 2008) $\r\n// $Revision: 49268 $\r\n\r\n#include <boost/mpl/arithmetic.hpp>\r\n#include <boost/mpl/comparison.hpp>\r\n#include <boost/mpl/and.hpp>\r\n#include <boost/mpl/int.hpp>\r\n#include <boost/mpl/long.hpp>\r\n#include <boost/mpl/aux_/test.hpp>\r\n\r\nstruct complex_tag : int_<10> {};\r\n\r\ntemplate< typename Re, typename Im > struct complex\r\n{\r\n    typedef complex_tag tag;\r\n    typedef complex type;\r\n    typedef Re real;\r\n    typedef Im imag;\r\n};\r\n\r\ntemplate< typename C > struct real : C::real {};\r\ntemplate< typename C > struct imag : C::imag {};\r\n\r\nnamespace boost { namespace mpl {\r\n\r\ntemplate<> struct BOOST_MPL_AUX_NUMERIC_CAST< integral_c_tag,complex_tag >\r\n{\r\n    template< typename N > struct apply\r\n        : complex< N, integral_c< typename N::value_type, 0 > >\r\n    {\r\n    };\r\n};\r\n\r\ntemplate<>\r\nstruct plus_impl< complex_tag,complex_tag >\r\n{\r\n    template< typename N1, typename N2 > struct apply\r\n        : complex<\r\n              plus< typename N1::real, typename N2::real >\r\n            , plus< typename N1::imag, typename N2::imag >\r\n            >\r\n    {\r\n    };\r\n};\r\n\r\ntemplate<>\r\nstruct times_impl< complex_tag,complex_tag >\r\n{\r\n    template< typename N1, typename N2 > struct apply\r\n        : complex<\r\n              minus< \r\n                  times< typename N1::real, typename N2::real >\r\n                , times< typename N1::imag, typename N2::imag >\r\n                >\r\n            , plus<\r\n                  times< typename N1::real, typename N2::imag >\r\n                , times< typename N1::imag, typename N2::real >\r\n                >\r\n            >\r\n    {\r\n    };\r\n};\r\n\r\ntemplate<>\r\nstruct equal_to_impl< complex_tag,complex_tag >\r\n{\r\n    template< typename N1, typename N2 > struct apply\r\n        : and_<\r\n              equal_to< typename N1::real, typename N2::real >\r\n            , equal_to< typename N1::imag, typename N2::imag >\r\n            >\r\n    {\r\n    };\r\n};\r\n\r\n}}\r\n\r\n\r\ntypedef int_<2> i;\r\ntypedef complex< int_<5>, int_<-1> > c1;\r\ntypedef complex< int_<-5>, int_<1> > c2;\r\n\r\nMPL_TEST_CASE()\r\n{\r\n    typedef plus<c1,c2>::type r1;\r\n    MPL_ASSERT_RELATION( real<r1>::value, ==, 0 );\r\n    MPL_ASSERT_RELATION( imag<r1>::value, ==, 0 );\r\n\r\n    typedef plus<c1,c1>::type r2;\r\n    MPL_ASSERT_RELATION( real<r2>::value, ==, 10 );\r\n    MPL_ASSERT_RELATION( imag<r2>::value, ==, -2 );\r\n\r\n    typedef plus<c2,c2>::type r3;\r\n    MPL_ASSERT_RELATION( real<r3>::value, ==, -10 );\r\n    MPL_ASSERT_RELATION( imag<r3>::value, ==, 2 );\r\n\r\n#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)\r\n    typedef plus<c1,i>::type r4;\r\n    MPL_ASSERT_RELATION( real<r4>::value, ==, 7 );\r\n    MPL_ASSERT_RELATION( imag<r4>::value, ==, -1 );\r\n\r\n    typedef plus<i,c2>::type r5;\r\n    MPL_ASSERT_RELATION( real<r5>::value, ==, -3 );\r\n    MPL_ASSERT_RELATION( imag<r5>::value, ==, 1 );\r\n#endif\r\n}\r\n\r\nMPL_TEST_CASE()\r\n{\r\n    typedef times<c1,c2>::type r1;\r\n    MPL_ASSERT_RELATION( real<r1>::value, ==, -24 );\r\n    MPL_ASSERT_RELATION( imag<r1>::value, ==, 10 );\r\n\r\n    typedef times<c1,c1>::type r2;\r\n    MPL_ASSERT_RELATION( real<r2>::value, ==, 24 );\r\n    MPL_ASSERT_RELATION( imag<r2>::value, ==, -10 );\r\n\r\n    typedef times<c2,c2>::type r3;\r\n    MPL_ASSERT_RELATION( real<r3>::value, ==, 24 );\r\n    MPL_ASSERT_RELATION( imag<r3>::value, ==, -10 );\r\n\r\n#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)\r\n    typedef times<c1,i>::type r4;\r\n    MPL_ASSERT_RELATION( real<r4>::value, ==, 10 );\r\n    MPL_ASSERT_RELATION( imag<r4>::value, ==, -2 );\r\n\r\n    typedef times<i,c2>::type r5;\r\n    MPL_ASSERT_RELATION( real<r5>::value, ==, -10 );\r\n    MPL_ASSERT_RELATION( imag<r5>::value, ==, 2 );\r\n#endif\r\n}\r\n\r\nMPL_TEST_CASE()\r\n{\r\n    MPL_ASSERT(( equal_to<c1,c1> ));\r\n    MPL_ASSERT(( equal_to<c2,c2> ));\r\n    MPL_ASSERT_NOT(( equal_to<c1,c2> ));\r\n\r\n    MPL_ASSERT(( equal_to<c1, complex< long_<5>, long_<-1> > > ));\r\n\r\n#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)\r\n    MPL_ASSERT_NOT(( equal_to<c1,i> ));\r\n    MPL_ASSERT_NOT(( equal_to<i,c2> ));\r\n#endif\r\n}\r\n", "meta": {"hexsha": "0ef1d1460cf46828278df78d34042cbc51c4ff82", "size": 4309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/mpl/test/numeric_ops.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/mpl/test/numeric_ops.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/mpl/test/numeric_ops.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6217948718, "max_line_length": 75, "alphanum_fraction": 0.5908563472, "num_tokens": 1243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.551683210847661}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation, \n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file    testGaussianBayesNet.cpp\n * @brief   Unit tests for GaussianBayesNet\n * @author  Frank Dellaert\n */\n\n// STL/C++\n#include <iostream>\n#include <sstream>\n#include <CppUnitLite/TestHarness.h>\n#include <boost/tuple/tuple.hpp>\n#include <boost/foreach.hpp>\n\n#include <boost/assign/std/list.hpp> // for operator +=\nusing namespace boost::assign;\n\n#include <gtsam/base/Testable.h>\n#include <gtsam/inference/BayesNet.h>\n#include <gtsam/linear/GaussianBayesNet.h>\n#include <gtsam/linear/GaussianSequentialSolver.h>\n#include <tests/smallExample.h>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace example;\n\nstatic const Index _x_=0, _y_=1, _z_=2;\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, constructor )\n{\n  // small Bayes Net x <- y\n  // x y d\n  // 1 1 9\n  //   1 5\n  Matrix R11 = Matrix_(1,1,1.0), S12 = Matrix_(1,1,1.0);\n  Matrix                         R22 = Matrix_(1,1,1.0);\n  Vector d1(1), d2(1);\n  d1(0) = 9; d2(0) = 5;\n  Vector sigmas(1);\n  sigmas(0) = 1.;\n\n  // define nodes and specify in reverse topological sort (i.e. parents last)\n  GaussianConditional x(_x_,d1,R11,_y_,S12, sigmas), y(_y_,d2,R22, sigmas);\n\n  // check small example which uses constructor\n  GaussianBayesNet cbn = createSmallGaussianBayesNet();\n  EXPECT( x.equals(*cbn[_x_]) );\n  EXPECT( y.equals(*cbn[_y_]) );\n}\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, matrix )\n{\n  // Create a test graph\n  GaussianBayesNet cbn = createSmallGaussianBayesNet();\n\n  Matrix R; Vector d;\n  boost::tie(R,d) = matrix(cbn); // find matrix and RHS\n\n  Matrix R1 = Matrix_(2,2,\n\t\t      1.0, 1.0,\n\t\t      0.0, 1.0\n    );\n  Vector d1 = Vector_(2, 9.0, 5.0);\n\n  EXPECT(assert_equal(R,R1));\n  EXPECT(assert_equal(d,d1));\n}\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, optimize )\n{\n  GaussianBayesNet cbn = createSmallGaussianBayesNet();\n  VectorValues actual = optimize(cbn);\n\n  VectorValues expected(vector<size_t>(2,1));\n  expected[_x_] = Vector_(1,4.);\n  expected[_y_] = Vector_(1,5.);\n\n  EXPECT(assert_equal(expected,actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, optimize2 )\n{\n\n\t// Create empty graph\n\tGaussianFactorGraph fg;\n\tSharedDiagonal noise = noiseModel::Unit::Create(1);\n\n\tfg.add(_y_, eye(1), 2*ones(1), noise);\n\n\tfg.add(_x_, eye(1),_y_, -eye(1), -ones(1), noise);\n\n\tfg.add(_y_, eye(1),_z_, -eye(1), -ones(1), noise);\n\n\tfg.add(_x_, -eye(1), _z_, eye(1), 2*ones(1), noise);\n\n  VectorValues actual = *GaussianSequentialSolver(fg).optimize();\n\n  VectorValues expected(vector<size_t>(3,1));\n  expected[_x_] = Vector_(1,1.);\n  expected[_y_] = Vector_(1,2.);\n  expected[_z_] = Vector_(1,3.);\n\n  EXPECT(assert_equal(expected,actual));\n}\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, optimize3 )\n{\n\t// y=R*x, x=inv(R)*y\n\t// 9 = 1 1   4\n\t// 5     1   5\n\t// NOTE: we are supplying a new RHS here\n  GaussianBayesNet cbn = createSmallGaussianBayesNet();\n\n  VectorValues expected(vector<size_t>(2,1)), x(vector<size_t>(2,1));\n  expected[_x_] = Vector_(1, 4.);\n  expected[_y_] = Vector_(1, 5.);\n\n  // test functional version\n  VectorValues actual = optimize(cbn);\n  EXPECT(assert_equal(expected,actual));\n\n  // test imperative version\n  optimizeInPlace(cbn,x);\n  EXPECT(assert_equal(expected,x));\n}\n\n/* ************************************************************************* */\nTEST( GaussianBayesNet, backSubstituteTranspose )\n{\n\t// x=R'*y, y=inv(R')*x\n\t// 2 = 1    2\n\t// 5   1 1  3\n  GaussianBayesNet cbn = createSmallGaussianBayesNet();\n\n  VectorValues y(vector<size_t>(2,1)), x(vector<size_t>(2,1));\n  x[_x_] = Vector_(1,2.);\n  x[_y_] = Vector_(1,5.);\n  y[_x_] = Vector_(1,2.);\n  y[_y_] = Vector_(1,3.);\n\n  // test functional version\n  VectorValues actual = backSubstituteTranspose(cbn,x);\n  EXPECT(assert_equal(y,actual));\n}\n\n/* ************************************************************************* */\n// Tests computing Determinant\nTEST( GaussianBayesNet, DeterminantTest )\n{\n\tGaussianBayesNet cbn;\n\tcbn += boost::shared_ptr<GaussianConditional>(new GaussianConditional(\n\t\t\t\t\t0, Vector_( 2, 3.0, 4.0 ), Matrix_(2, 2, 1.0, 3.0, 0.0, 4.0 ),\n\t\t\t\t\t1, Matrix_(2, 2, 2.0, 1.0, 2.0, 3.0),\n\t\t\t\t\tones(2)));\n\n\tcbn += boost::shared_ptr<GaussianConditional>(new GaussianConditional(\n\t\t\t\t\t1, Vector_( 2, 5.0, 6.0 ), Matrix_(2, 2, 1.0, 1.0, 0.0, 3.0 ),\n\t\t\t\t\t2, Matrix_(2, 2, 1.0, 0.0, 5.0, 2.0),\n\t\t\t\t\tones(2)));\n\n\tcbn += boost::shared_ptr<GaussianConditional>(new GaussianConditional(\n\t\t\t3, Vector_( 2, 7.0, 8.0 ), Matrix_(2, 2, 1.0, 1.0, 0.0, 5.0 ),\n\t\t\tones(2)));\n\n\tdouble expectedDeterminant = 60;\n\tdouble actualDeterminant = determinant(cbn);\n\n  EXPECT_DOUBLES_EQUAL( expectedDeterminant, actualDeterminant, 1e-9);\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "60af529ecbc4f15476593793fb481efbd7d82559", "size": 5524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testGaussianBayesNet.cpp", "max_stars_repo_name": "sdmiller/gtsam_pcl", "max_stars_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T07:02:44.000Z", "max_issues_repo_path": "tests/testGaussianBayesNet.cpp", "max_issues_repo_name": "sdmiller/gtsam_pcl", "max_issues_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/testGaussianBayesNet.cpp", "max_forks_repo_name": "sdmiller/gtsam_pcl", "max_forks_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T12:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:02:48.000Z", "avg_line_length": 29.0736842105, "max_line_length": 80, "alphanum_fraction": 0.5611875453, "num_tokens": 1618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.5516557105335953}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <math/prim/mat/prob/vector_rng_test_helper.hpp>\n#include <math/prim/mat/prob/VectorIntRNGTestRig.hpp>\n#include <limits>\n#include <vector>\n\nclass PoissonTestRig : public VectorIntRNGTestRig {\n public:\n  PoissonTestRig()\n      : VectorIntRNGTestRig(10000, 10, {0, 1, 2, 3, 4, 5, 6}, {0.1, 1.1, 4.99},\n                            {1, 2, 3}, {-3.0, -2.0, 0.0}, {-3, -1, 0}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& lambda, const T2&, const T3&,\n                        T_rng& rng) const {\n    return stan::math::poisson_rng(lambda, rng);\n  }\n\n  template <typename T1>\n  double pmf(int y, T1 lambda, double, double) const {\n    return std::exp(stan::math::poisson_lpmf(y, lambda));\n  }\n};\n\nTEST(ProbDistributionsPoisson, errorCheck) {\n  check_dist_throws_all_types(PoissonTestRig());\n}\n\nTEST(ProbDistributionsPoisson, distributionCheck) {\n  check_counts_real(PoissonTestRig());\n}\n", "meta": {"hexsha": "f782ecd5db6424b8ca28c23b47c07874449713d2", "size": 1092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/mat/prob/poisson_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/prim/mat/prob/poisson_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/prim/mat/prob/poisson_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2, "max_line_length": 79, "alphanum_fraction": 0.6776556777, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5515966126454671}}
{"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_ACOTPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACOTPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing acotpi capabilities\n\n    inverse cotangent in pi multiples.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = acotpi(x);\n    @endcode\n\n    Returns the arc @c r in the interval\n    \\f$[0, 1[\\f$ such that <tt>cotpi(r) == x</tt>.\n\n    @see acot, acotd, cotpi\n\n  **/\n  Value acotpi(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acotpi.hpp>\n#include <boost/simd/function/simd/acotpi.hpp>\n\n#endif\n", "meta": {"hexsha": "b6dd4a5637d5ac1defad8323dac3789626a0aaab", "size": 1072, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acotpi.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/acotpi.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/acotpi.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.8085106383, "max_line_length": 100, "alphanum_fraction": 0.5746268657, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5515966124900759}}
{"text": "// Copyright (c) 2020 Marcus Valtonen \u00d6rnhag\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include \"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 \"tbb/parallel_for.h\"\n#include <iostream>\n#include <mex.h>\n#include <omp.h>\n#include <vector>\n\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Sparse>\n// #include <Eigen/StdVector>\n\n// #include <range/v3/all.hpp>\n// #include <range/v3/core.hpp>\n\n// #include \"storage_aliases.h\"\n\n// #define ngp int(*mxGetPr(prhs[0]))\n#define Hdo prhs[0]\n#define inv_Hdo prhs[1]\n#define sign int(*mxGetPr(prhs[2]))\n#define C_operator double(*mxGetPr(prhs[3]))\n#define I_t prhs[4]\n#define d_alpha_in prhs[5]\n#define alpha_in prhs[6]\n#define delta_in prhs[7]\n\n#define output plhs[0]\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n  auto Hdo_Dimensions = mxGetDimensions(Hdo);\n  auto alpha_Dimensions = mxGetDimensions(alpha_in);\n\n  size_t const ncomp = 6; // TODO 3D only\n  size_t const ngp = Hdo_Dimensions[2];\n  size_t const ntp = Hdo_Dimensions[3];\n  size_t const nmodes = alpha_Dimensions[1];\n\n  using Matrix = Eigen::MatrixXd;\n  using Vector = Eigen::VectorXd;\n  using matrix6 = Eigen::Matrix<double, 6, 6>;\n\n  Eigen::Map<Eigen::MatrixXd> Int_time(mxGetPr(I_t), ntp, ntp);\n\n  auto const tensor_shift = ncomp * ncomp;\n  auto const delta_shift = ncomp;\n\n  Matrix A = Matrix::Zero(nmodes * ntp, nmodes * ntp);\n  Vector b = Vector::Zero(ntp * nmodes);\n\n  Vector alpha = Eigen::Map<Vector>(mxGetPr(alpha_in), ntp);\n  Vector d_alpha = Eigen::Map<Vector>(mxGetPr(d_alpha_in), ntp);\n\n  // A\n  Vector int_C_C_alpha_alpha =\n      pow(C_operator, 2) * Int_time * (alpha.cwiseProduct(alpha));\n  double int_C_alpha_d_alpha =\n      C_operator * alpha.transpose() * (Int_time * d_alpha);\n  Vector int_d_alpha_d_alpha = (Int_time * d_alpha.cwiseProduct(d_alpha));\n\n  // b\n  Vector int_C_alpha = C_operator * (Int_time * alpha);\n  Vector int_d_alpha = (Int_time * d_alpha);\n\n  Vector space_mode = Vector::Zero(ngp * ncomp);\n  Matrix a2 = 2 * int_C_alpha_d_alpha * Matrix::Identity(ncomp, ncomp);\n\n  // #pragma omp parallel for\n  for (size_t i = 0; i < ngp; i++) {\n    Matrix a1 = Matrix::Zero(ncomp, ncomp);\n    Matrix a3 = Matrix::Zero(ncomp, ncomp);\n    Matrix A = Matrix::Zero(ncomp, ncomp);\n\n    Vector b1 = Vector::Zero(ncomp);\n    Vector b2 = Vector::Zero(ncomp);\n    Vector b = Vector::Zero(ncomp);\n\n    for (size_t j = 0; j < ntp; j++) {\n\n      int const delta_idx = (j * ngp + i) * delta_shift;\n      int const tensor_idx = (j * ngp + i) * tensor_shift;\n\n      matrix6 H = Eigen::Map<matrix6>(mxGetPr(Hdo) + tensor_idx);\n      matrix6 iH = Eigen::Map<matrix6>(mxGetPr(inv_Hdo) + tensor_idx);\n      Vector delta = Eigen::Map<Vector>(mxGetPr(delta_in) + delta_idx, ncomp);\n\n      a1 += H * int_C_C_alpha_alpha(j);\n      a3 += iH * int_d_alpha_d_alpha(j);\n      b1 += delta * int_C_alpha(j);\n      b2 += (iH * delta) * int_d_alpha(j);\n    }\n\n    A = a1 - sign * a2 + a3;\n    b = b1 - sign * b2;\n\n#pragma omp critical\n    if (b.norm() > 0)\n      space_mode.segment(i * ncomp, ncomp) = A.partialPivLu().solve(b);\n    else\n      space_mode.segment(i * ncomp, ncomp) = b;\n  }\n\n  output = mxCreateDoubleMatrix(ngp * ncomp, 1, mxREAL);\n  auto out_pt = mxGetPr(output);\n  Eigen::Map<Eigen::MatrixXd> mapp(out_pt, ngp * ncomp, 1);\n  mapp = space_mode; // copy\n  // std::copy(x.begin(), x.end(), mxGetPr(output));\n  return;\n}\n\n// mxArray *cpp_to_MexArray(const std::vector<double> &v) {\n//   mxArray *mx = mxCreateDoubleMatrix(1, v.size(), mxREAL);\n//   std::copy(v.begin(), v.end(), mxGetPr(mx));\n//\n//   return mx;\n// }\n", "meta": {"hexsha": "70e7e4bff941d215a7a9657ac906f71595797c14", "size": 3463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab/matlab_mex/src_mex/semi_cleaned_version/mex_functions/src/compute_kinematic_hardening_space_mode/compute_kinematic_hardening_space_mode.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/semi_cleaned_version/mex_functions/src/compute_kinematic_hardening_space_mode/compute_kinematic_hardening_space_mode.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/semi_cleaned_version/mex_functions/src/compute_kinematic_hardening_space_mode/compute_kinematic_hardening_space_mode.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": 29.5982905983, "max_line_length": 78, "alphanum_fraction": 0.6563673116, "num_tokens": 1094, "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": "\n// BLAS level 1\n// std::vector<>, std::valarray<>, boost::array<>, C array\n\n// element type: float or double\n#ifdef F_FLOAT\ntypedef float real_t; \n#else\ntypedef double real_t; \n#endif\n\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n#include <complex>\n\n#include <boost/numeric/bindings/std/vector.hpp>\n#include <boost/numeric/bindings/std/valarray.hpp>\n#include <boost/numeric/bindings/boost/array.hpp>\n#include <boost/numeric/bindings/blas/level1.hpp>\n\n#include \"utils.h\"\n\nnamespace blas = boost::numeric::bindings::blas;\n\nusing std::cout;\nusing std::endl;\nusing std::size_t; \n\nint main() {\n\n  int n = 10; \n\n  cout << endl; \n  cout << \"std::vector\" << endl; \n  std::vector<real_t> sv (n); \n  init_v (sv, kpp (1)); \n  print_v (sv, \"sv\"); \n  cout << \"std::valarray\" << endl; \n  std::valarray<real_t> va (n); \n  blas::set (0.1, va); \n  print_v (va, \"va\"); \n  cout << endl; \n\n  cout << \"dot(): sv^t va: \";\n  real_t d = 0;\n  for (int i = 0; i < n; ++i)\n    d += sv[i] * va[i]; \n\n  cout << \"is \" << d << \" == \" << blas::dot (sv, va) << \" ?\" << endl; \n  cout << endl; \n\n#ifdef F_FLOAT\n  cout << \"sdsdot(): 10 + sv^T va = \" << blas::sdsdot (10, sv, va) << endl; \n  cout << endl;\n#endif  \n\n  blas::scal (real_t(2), sv);\n  print_v (sv, \"scal(): 2 sv\"); \n\n  cout << endl; \n\n  std::random_shuffle (sv.begin(), sv.end());\n  cout << \"shuffled sv: \"; \n  std::copy (sv.begin(), sv.end(), std::ostream_iterator<real_t> (cout, \" \")); \n  cout << endl; \n  int i = blas::iamax (sv); \n  cout << \"iamax():\\n  index of max el = \" << i \n       << \"; max el = \" << sv[i] << endl; \n  cout << endl; \n\n  cout << \"asum():\\n  ||sv||_1 =  \" << blas::asum (sv) \n       << \"; ||va||_1 = \" << blas::asum (va) << endl; \n  cout << \"nrm2():\\n  ||sv||_2 = \" << blas::nrm2 (sv) \n       << \"; ||va||_2 = \" << blas::nrm2 (va) << endl; \n  cout << endl; \n\n  cout << \"boost::array\" << endl;\n  boost::array<double, 10> ba;\n  blas::set (0.1, ba);\n  print_v (ba, \"ba\");\n  cout << \"C array\" << endl; \n  typedef double double_array[10]; \n  double_array ca; \n  blas::set (1., ca); \n  print_v (ca, \"ca\");\n  cout << endl; \n  \n  blas::axpy (0.1, ba, ca); \n  print_v (ca, \"axpy(): 0.1 ba + ca\"); \n\n//  blas::axpby (0.1, ba, 2., ca); \n//  print_v (ca, \"axpby(): 0.1 ba + 2.0 ca\"); \n\n  cout << endl;\n}\n", "meta": {"hexsha": "58ba7a4509ce85f5254bcb252b98a9c030cd5ac7", "size": 2260, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/others.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/others.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/others.cc", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 23.2989690722, "max_line_length": 79, "alphanum_fraction": 0.5420353982, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5515966016079572}}
{"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// \u56fa\u5b9a\u7f51\u683cx\u5750\u6807\u6700\u5c0f\u70b9\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": "//-std=c++17 -static -m64 -Wall -Os\n\n#include <boost/random.hpp>\n#include <iostream>\n\nint main(int argc,char *argv[])\n{\n  boost::mt19937 gen; //\u4f2a\u968f\u673a\u6570\u53d1\u751f\u5668\uff08generator\uff09\n  boost::uniform_int<>dist(1,10000000);\n  boost::variate_generator<boost::mt19937&, boost::uniform_int<>>die(gen,dist);\n  \n  for(auto i = 0; i < 1000; ++i)\n  {\n\tstd::cout << die() << \"  \";  \n  }\n  std::cout << \"\\n\";\n}", "meta": {"hexsha": "58f26f570fb63cc45870a4b931811ca64c723f83", "size": 380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/algorithms/rand_nums/rand_nums.cpp", "max_stars_repo_name": "UMP-45/C-_Study", "max_stars_repo_head_hexsha": "708aef36931c4881f830bd3d2a7732c0d3856ed0", "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++/algorithms/rand_nums/rand_nums.cpp", "max_issues_repo_name": "UMP-45/C-_Study", "max_issues_repo_head_hexsha": "708aef36931c4881f830bd3d2a7732c0d3856ed0", "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++/algorithms/rand_nums/rand_nums.cpp", "max_forks_repo_name": "UMP-45/C-_Study", "max_forks_repo_head_hexsha": "708aef36931c4881f830bd3d2a7732c0d3856ed0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3529411765, "max_line_length": 79, "alphanum_fraction": 0.6105263158, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5515846301119217}}
{"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": "#include <Eigen/Core>\n#include <iostream>\n\n#include <SymEigsSolver.h>\n#include <MatOp/DenseGenMatProd.h>\n\nusing namespace Spectra;\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\ntypedef Eigen::MatrixXd Matrix;\ntypedef Eigen::VectorXd Vector;\n\ntemplate <int SelectionRule>\nvoid run_test(const Matrix &mat, int k, int m)\n{\n    // Eigen::SelfAdjointEigenSolver<MatrixXd> eig(mat);\n    // std::cout << \"all eigenvalues = \\n\" << eig.eigenvalues().transpose() << \"\\n\";\n\n    DenseGenMatProd<double> op(mat);\n    SymEigsSolver<double, SelectionRule, DenseGenMatProd<double>> eigs(&op, k, m);\n    eigs.init();\n    int nconv = eigs.compute();\n    int niter = eigs.num_iterations();\n    int nops = eigs.num_operations();\n\n    REQUIRE( nconv > 0 );\n\n    Vector evals = eigs.eigenvalues();\n    Matrix evecs = eigs.eigenvectors();\n\n    // std::cout << \"computed eigenvalues D = \\n\" << evals.transpose() << \"\\n\";\n    // std::cout << \"computed eigenvectors U = \\n\" << evecs << \"\\n\\n\";\n    Matrix err = mat * evecs - evecs * evals.asDiagonal();\n\n    INFO( \"nconv = \" << nconv );\n    INFO( \"niter = \" << niter );\n    INFO( \"nops = \" << nops );\n    INFO( \"||AU - UD||_inf = \" << err.array().abs().maxCoeff() );\n    REQUIRE( err.array().abs().maxCoeff() == Approx(0.0) );\n}\n\nvoid run_test_sets(const Matrix &mat, int k, int m)\n{\n    SECTION( \"Largest Magnitude\" )\n    {\n        run_test<LARGEST_MAGN>(mat, k, m);\n    }\n    SECTION( \"Largest Value\" )\n    {\n        run_test<LARGEST_ALGE>(mat, k, m);\n    }\n    SECTION( \"Smallest Magnitude\" )\n    {\n        run_test<SMALLEST_MAGN>(mat, k, m);\n    }\n    SECTION( \"Smallest Value\" )\n    {\n        run_test<SMALLEST_ALGE>(mat, k, m);\n    }\n    SECTION( \"Both Ends\" )\n    {\n        run_test<BOTH_ENDS>(mat, k, m);\n    }\n}\n\nTEST_CASE(\"Eigensolver of symmetric real matrix [10x10]\", \"[eigs_sym]\")\n{\n    srand(123);\n\n    Matrix A = Eigen::MatrixXd::Random(10, 10);\n    Matrix M = A + A.transpose();\n    int k = 3;\n    int m = 6;\n\n    run_test_sets(M, k, m);\n}\n\nTEST_CASE(\"Eigensolver of symmetric real matrix [100x100]\", \"[eigs_sym]\")\n{\n    srand(123);\n\n    Matrix A = Eigen::MatrixXd::Random(100, 100);\n    Matrix M = A + A.transpose();\n    int k = 10;\n    int m = 20;\n\n    run_test_sets(M, k, m);\n}\n\nTEST_CASE(\"Eigensolver of symmetric real matrix [1000x1000]\", \"[eigs_sym]\")\n{\n    srand(123);\n\n    Matrix A = Eigen::MatrixXd::Random(1000, 1000);\n    Matrix M = A + A.transpose();\n    int k = 20;\n    int m = 50;\n\n    run_test_sets(M, k, m);\n}\n", "meta": {"hexsha": "435e7d24d2b3b91e2af471cae7e48427487f2fa5", "size": 2469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/spectra/test/SymEigs.cpp", "max_stars_repo_name": "LEON-MING/TheiaSfM_Leon", "max_stars_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-17T17:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T09:21:38.000Z", "max_issues_repo_path": "libraries/spectra/test/SymEigs.cpp", "max_issues_repo_name": "LEON-MING/TheiaSfM_Leon", "max_issues_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/spectra/test/SymEigs.cpp", "max_forks_repo_name": "LEON-MING/TheiaSfM_Leon", "max_forks_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-09T03:34:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-21T06:00:50.000Z", "avg_line_length": 23.9708737864, "max_line_length": 84, "alphanum_fraction": 0.5978128797, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5515654608287018}}
{"text": "// -------------------------------------------------------------------------------------------------\n//                              Copyright 2016 - NumScale SAS\n//\n//                   Distributed under the Boost Software License, Version 1.0.\n//                        See accompanying file LICENSE.txt or copy at\n//                            http://www.boost.org/LICENSE_1_0.txt\n// -------------------------------------------------------------------------------------------------\n\n#include <simd_bench.hpp>\n#include <boost/simd/function/simd/significants.hpp>\n#include <boost/simd/function/simd/enumerate.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n\nnamespace nsb = ns::bench;\nnamespace bs =  boost::simd;\nnamespace bd =  boost::dispatch;\ntemplate < int N >\nstruct signif\n{\n  template<class T> T operator()(const T & a) const\n  {\n    using i_t = bd::as_integer_t<T>;\n    return bs::significants(a, bs::enumerate<i_t>(0, N));\n  }\n};\n\nDEFINE_SCALAR_BENCH(scalar_significantsp, signif< 1>());\nDEFINE_SCALAR_BENCH(scalar_significantsn, signif<-1>());\n\nDEFINE_BENCH_MAIN() {\n  nsb::for_each<scalar_significantsn, NS_BENCH_IEEE_TYPES>(-10, 10);\n  nsb::for_each<scalar_significantsp, NS_BENCH_IEEE_TYPES>(-10, 10);\n}\n", "meta": {"hexsha": "a948fe0484e4f6db60ffcd6df764769958d8dfa1", "size": 1234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/function/scalar/significants.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "bench/function/scalar/significants.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/function/scalar/significants.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 36.2941176471, "max_line_length": 100, "alphanum_fraction": 0.556726094, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5515654597365767}}
{"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": "//==============================================================================\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_LOGNSTAT_HPP_INCLUDED\n#define NT2_STATISTICS_FUNCTIONS_GENERIC_LOGNSTAT_HPP_INCLUDED\n#include <nt2/statistics/functions/lognstat.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/functions/simd/exp.hpp>\n#include <nt2/include/functions/simd/expm1.hpp>\n#include <nt2/include/functions/simd/sqr.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT   ( lognstat_, 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      A0 s2 = sqr(sigma);\n      m = exp(mu +Half<A0>()*s2);\n      v = exp(Two<A0>()*mu+s2)*expm1(s2);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT   ( lognstat_, 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      A0 m;\n      lognstat(mu, sigma, m, v);\n      return m;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT   ( lognstat_, 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      A0 m, v;\n      lognstat(mu, sigma, m, v);\n      return result_type(m, v);\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "f078a8a88904111522d7aedc6b686525144ed4ae", "size": 2729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/statistics/include/nt2/statistics/functions/generic/lognstat.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/lognstat.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/lognstat.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 36.3866666667, "max_line_length": 81, "alphanum_fraction": 0.4833272261, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5515654556108706}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if ! defined(EDGE_MOVE_HPP)\n#define EDGE_MOVE_HPP\n\n#include <vector>\t\t\t\t\t\t\t\t\t// for std::vector\n#include <boost/shared_ptr.hpp>\t\t\t\t\t\t// for boost::shared_ptr\n#include <boost/weak_ptr.hpp>\t\t\t\t\t\t// for boost::weak_ptr\n//#include <boost/enable_shared_from_this.hpp>\t\t// for boost::enable_shared_from_this\n#include \"mcmc_updater.hpp\"\t\t// for base class MCMCUpdater\n\n//class ExponentialDistribution;\n//typedef boost::shared_ptr<ExponentialDistribution>\tExponentialDistributionShPtr;\n\nnamespace phycas\n{\n\n\nclass MCMCChainManager;\ntypedef boost::weak_ptr<MCMCChainManager>\t\t\tChainManagerWkPtr;\n\n//typedef std::map<unsigned, std::vector<double> > PolytomyDistrMap;\n//typedef std::vector<double> VecPolytomyDistr;\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAn EdgeMove changes the length of just one randomly-chosen edge in the tree. An edge chosen at random is set to the\n|\tvalue Y = m*exp(`lambda'*(u - 0.5)), where m is the original length and u is a Uniform(0,1) random deviate. Under\n|\tthis proposal scheme, the random variable Y has the following properties:\n|>\n|\tdensity         f(Y) = 1/(lambda*Y)\n|\tcdf             F(Y) = 0.5 + (1/lambda) log(Y/m)\n|\tminimum         m*exp(-lambda/2)\n|\tmaximum         m*exp(lambda/2)\n|\tmean            (m/lambda)[exp(lambda/2) - exp(-lambda/2)]\n|\tvariance        (m/lambda)^2 [(lambda/2)(exp(lambda) - exp(-lambda)) - (exp(lambda/2) - exp(-lambda/2))^2]\n|>\n|\tWith a starting edge length of 1.0, the proposed edge lengths have increasing mean and variance with increasing\n|\tlambda, but values of lambda in the range 0.1 to 2.0 appear to be reasonable.\n|>\n|\tlambda       mean        s.d.\n|\t-----------------------------\n|\t 0.1      1.00042     0.02888\n|\t 0.5      1.01045     0.14554\n|\t 1.0      1.04219     0.29840\n|\t 2.0      1.17520     0.65752\n|\t10.0     14.84064    29.68297\n|>\n*/\nclass EdgeMove : public MCMCUpdater\n\t{\n\tpublic:\n\t\t\t\t\t\t\t\t\tEdgeMove();\n\t\t\t\t\t\t\t\t\tvirtual ~EdgeMove()\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//std::cerr << \"EdgeMove dying...\" << std::endl;\n\t\t\t\t\t\t\t\t\t\t}\n\n\n\t\t// Accessors\n\t\t//\n\t\tdouble\t\t\t\t\t\tgetTuningParameter() const;\n\t\t//bool\t\t\t\t\t\taddEdgeMoveProposed() const;\n\n\t\t// Modifiers\n\t\t//\n\t\tvoid\t\t\t\t\t\tsetTuningParameter(double x);\n\t\t//void\t\t\t\t\t\tsetEdgeLenDistMean(double mean);\n\n\t\t// Utilities\n\t\t//\n\t\tvoid\t\t\t\t\t\treset();\n\t\t//void\t\t\t\t\t\tfinalize();\n\n\t\t// These are virtual functions in the MCMCUpdater base class\n\t\t//\n\t\tvirtual bool\t\t\t\tupdate();\n\t\tvirtual double\t\t\t\tgetLnHastingsRatio() const;\n\t\tvirtual double\t\t\t\tgetLnJacobian() const;\n\t\tvirtual void\t\t\t\tproposeNewState();\n\t\tvirtual void\t\t\t\trevert();\n\t\tvirtual void\t\t\t\taccept();\n\n\tprivate:\n\n\t\tEdgeMove &\t\t\t\t\toperator=(const EdgeMove &);\t// never use - don't define\n\n\tprivate:\n\n        double                      lambda;         /**< the tuning parameter used for this move */\n\n\t\tdouble\t\t\t\t\t\torigEdgelen;\t/**< Length of modified edge saved (in case revert is necessary) */\n\t\tTreeNode *\t\t\t\t\torigNode;\t\t/**< Node owning the modified edge (in case revert is necessary) */\n\t\tTreeNode *\t\t\t\t\tlikeRoot;\t\t/**< Node to be used as the likelihood root (equals origNode if origNode is internal, otherwise equals origNode's parent) */\n\n\t\tstd::vector<double>\t\t    one_edgelen;\t\t\t\t\t\t/**< Workspace declared here to avoid unnecessary allocs/deallocs */\n\t};\n\n} // namespace phycas\n\n#endif\n", "meta": {"hexsha": "3fc2ba8e1c448ef386f18483c2de52c64b8aae77", "size": 4780, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/edge_move.hpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/edge_move.hpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/edge_move.hpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 40.5084745763, "max_line_length": 152, "alphanum_fraction": 0.5652719665, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672089305841, "lm_q2_score": 0.682573734412324, "lm_q1q2_score": 0.5515654524558925}}
{"text": "#include <RcppArmadillo.h>\n#include <Rmath.h>\n#include<functional>  \n//#include <boost/math/special_functions/bessel.hpp>\n#include <omp.h>\nusing namespace Rcpp;\n\n\n// Enable C++11 via this plugin (Rcpp 0.10.3 or later)\n// [[Rcpp::plugins(\"cpp11\")]]\n// [[Rcpp::plugins(openmp)]]\n\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::depends(BH)]] \n\nconst int threads = 6;//for omega//\nconst double log_pi = log(M_PI);\nconst double log_2 = log(2.0);\n\ndouble bessi0_exp(double x)\n{\n  double ax,ans;\n  double y; \n  if ((ax=fabs(x)) < 3.75) { \n    y=x/3.75;\n    y*=y;\n    ans=(1.0+y*(3.5156229+y*(3.0899424+y*(1.2067492\n                                            +y*(0.2659732+y*(0.360768e-1+y*0.45813e-2))))))*exp(-ax);\n  } else {\n    y=3.75/ax;\n    ans=(1/sqrt(ax))*(0.39894228+y*(0.1328592e-1\n                                      +y*(0.225319e-2+y*(-0.157565e-2+y*(0.916281e-2\n                                                                           +y*(-0.2057706e-1+y*(0.2635537e-1+y*(-0.1647633e-1\n                                                                           +y*0.392377e-2))))))));\n  }\n  return ans;\n}\ndouble bessel_sum(arma::vec x){\n  const int n = x.size();\n  double total = 0;\n  for(int i = 0; i < n; i++) {\n    total += log(bessi0_exp(x[i]));\n  }\n  return total;\n}\n\ndouble dvm_log_scaled_sum(arma::vec a, arma::vec b, arma::vec omega_vec ){\n  const int n = a.size();\n  return -log_pi * n - bessel_sum(omega_vec) - sum(omega_vec % (2 * a / b));\n}\n\ndouble dvm_log_sum(double a, double b, double omega_1 ){\n  return - log_2- log_pi - log(bessi0_exp(omega_1)) - omega_1 * (a / b + 1);\n}\n\ndouble dgamma_log (double x, double a, double b){\n  return a * log(b) - lgamma(a) + (a - 1) * log(x) - b * x;\n}\n\ndouble likeliC_noj(arma::vec x, arma::vec omega_vec, int p){\n  arma::vec x2 = square(x);\n  arma::vec xsum = cumsum(x2);\n  int p1 = p - 1;\n  return dvm_log_scaled_sum(x2.subvec(2,p1),xsum.subvec(2,p1),omega_vec.subvec(1,p1-1)) + dvm_log_sum(x[1],pow(xsum[1],0.5),omega_vec[0]);\n}\n\ndouble likeli_omega_omp(arma::vec omega_vec, arma::mat beta,int nr,int p){\n  double s_beta = 0;\n  omp_set_num_threads(threads); \n  #pragma omp parallel for reduction(+:s_beta)\n  \n  for(int i = 0; i < nr ; i++){\n    arma::vec temp = vectorise(beta.row(i));\n    s_beta += likeliC_noj(temp,omega_vec,p);\n  }\n  return s_beta;\n}\n\n// [[Rcpp::export]]\nList update_omega(arma::vec dummy, arma::vec omega_vec,arma::mat beta, int nr,double a, double b,double omega_sd,int p ){\n  double omega = omega_vec[0];\n  double eta = log(omega);\n  double eta_new = omega_sd * as_scalar(arma::randn(1)) + eta;\n  double omega_new = exp(eta_new);\n  double accept;\n  int omega_accept = 1;\n  arma::vec omega_vec_new = omega_new * dummy;\n  \n  accept = exp(likeli_omega_omp(omega_vec_new,beta,nr,p) + eta_new  + dgamma_log(omega_new,a,b) -\n    likeli_omega_omp(omega_vec,beta,nr,p) - eta - dgamma_log(omega,a,b));\n  \n  if(accept < as_scalar(arma::randu(1))){\n    omega_vec_new = omega_vec;\n    omega_accept = 0;\n  }\n  return List::create(omega_vec_new,omega_accept);\n}\n", "meta": {"hexsha": "b24c2fbc1613e44c8e7f14a2d8dcb16ac015593d", "size": 3035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/spherical_factor_model_omp.cpp", "max_stars_repo_name": "Xingchen-Yu/spherical-latent-factor-model-for-binary-data", "max_stars_repo_head_hexsha": "63f7042f48b6a171563db26061d6390c136725c3", "max_stars_repo_licenses": ["MIT"], "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/spherical_factor_model_omp.cpp", "max_issues_repo_name": "Xingchen-Yu/spherical-latent-factor-model-for-binary-data", "max_issues_repo_head_hexsha": "63f7042f48b6a171563db26061d6390c136725c3", "max_issues_repo_licenses": ["MIT"], "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/spherical_factor_model_omp.cpp", "max_forks_repo_name": "Xingchen-Yu/spherical-latent-factor-model-for-binary-data", "max_forks_repo_head_hexsha": "63f7042f48b6a171563db26061d6390c136725c3", "max_forks_repo_licenses": ["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.9693877551, "max_line_length": 138, "alphanum_fraction": 0.5957166392, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5515484088349779}}
{"text": "#pragma once\n\n\n#include <Eigen/Dense>\n\n#include <functional>\n#include <string>\n\n#ifdef POLYFEM_OPENCL\n#include <rbf_interpolate.hpp>\n#endif\n\n\nnamespace polyfem\n{\n\tclass RBFInterpolation\n\t{\n\tpublic:\n\t\tRBFInterpolation() { }\n\t\tRBFInterpolation(const Eigen::MatrixXd &fun, const Eigen::MatrixXd &pts, const std::function<double(double)> &rbf);\n\t\tvoid init(const Eigen::MatrixXd &fun, const Eigen::MatrixXd &pts, const std::function<double(double)> &rbf);\n\n\t\tRBFInterpolation(const Eigen::MatrixXd &fun, const Eigen::MatrixXd &pts, const std::string &rbf, const double eps);\n\t\tvoid init(const Eigen::MatrixXd &fun, const Eigen::MatrixXd &pts, const std::string &rbf, const double eps);\n\n\t\tEigen::MatrixXd interpolate(const Eigen::MatrixXd &pts) const;\n\n\tprivate:\n#ifdef POLYFEM_OPENCL\n\t\tint verbose_ = 0;\n\t\tconst std::string rbfcl_ = \"GA\";\n\t\tbool opt_ = false;\n\t\tbool unit_cube_  = false;\n\t\tint num_threads_ = -1;\n\n\t\tstd::vector<rbf_pum::RBFData> data_;\n#else\n\t\tEigen::MatrixXd centers_;\n\t\tEigen::MatrixXd weights_;\n\n\t\tstd::function<double(double)> rbf_;\n#endif\n\t};\n}\n", "meta": {"hexsha": "dcf1b9f02d0156a81fc1bdf2a61395dd25ef7f7e", "size": 1064, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/RBFInterpolation.hpp", "max_stars_repo_name": "ldXiao/polyfem", "max_stars_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 228.0, "max_stars_repo_stars_event_min_datetime": "2018-11-23T19:32:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:30:51.000Z", "max_issues_repo_path": "src/utils/RBFInterpolation.hpp", "max_issues_repo_name": "ldXiao/polyfem", "max_issues_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-03-11T22:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T14:50:35.000Z", "max_forks_repo_path": "src/utils/RBFInterpolation.hpp", "max_forks_repo_name": "ldXiao/polyfem", "max_forks_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2018-12-31T02:04:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T02:42:01.000Z", "avg_line_length": 23.6444444444, "max_line_length": 117, "alphanum_fraction": 0.7227443609, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5515036426784728}}
{"text": "// -*- C++ -*-\n//\n// Copyright Sylvain Bougerel 2009 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file COPYING or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_TEST_DYN_LINK\n#define SPATIAL_ENABLE_ASSERT // detect interal issues that should not occur\n\n#include <boost/test/unit_test.hpp>\n#include \"../../src/metric.hpp\"\n#include \"spatial_test_fixtures.hpp\"\n\nBOOST_AUTO_TEST_CASE(test_difference_bracket)\n{\n  bracket_minus<int2, int>\n    diff = details::with_builtin_difference<point_multiset<2, int2> >()\n    (point_multiset<2, int2>());\n  int2 p(0, 1);\n  int2 q(2, 0);\n  BOOST_CHECK_EQUAL(diff(0, p, q), -2);\n  BOOST_CHECK_EQUAL(diff(1, p, q), 1);\n}\n\nBOOST_AUTO_TEST_CASE(test_difference_paren)\n{\n  typedef point_multiset<2, int2, paren_less<int2> > pointset_type;\n  paren_minus<int2, int>\n    diff = details::with_builtin_difference<pointset_type>()\n    (pointset_type());\n  int2 p(0, 1);\n  int2 q(2, 0);\n  BOOST_CHECK_EQUAL(diff(0, p, q), -2);\n  BOOST_CHECK_EQUAL(diff(1, p, q), 1);\n}\n\nBOOST_AUTO_TEST_CASE(test_difference_iterator)\n{\n  typedef point_multiset<2, int2, iterator_less<int2> > pointset_type;\n  iterator_minus<int2, int>\n    diff = details::with_builtin_difference<pointset_type>()\n    (pointset_type());\n  int2 p(0, 1);\n  int2 q(2, 0);\n  BOOST_CHECK_EQUAL(diff(0, p, q), -2);\n  BOOST_CHECK_EQUAL(diff(1, p, q), 1);\n}\n\nBOOST_AUTO_TEST_CASE(test_difference_accessor)\n{\n  typedef point_multiset<4, quad, accessor_less<quad_access, quad> > pointset_type;\n  accessor_minus<quad_access, quad, int>\n    diff = details::with_builtin_difference<pointset_type>()\n    (pointset_type());\n  quad p(0, 1, 0, 0);\n  quad q(2, 0, 0, 0);\n  BOOST_CHECK_EQUAL(diff(0, p, q), -2);\n  BOOST_CHECK_EQUAL(diff(1, p, q), 1);\n}\n\nBOOST_AUTO_TEST_CASE(test_euclid_distance_to_key)\n{\n  {\n    // distance between 2 points at the same position should be null.\n    double6 x; std::fill(x.begin(), x.end(), .0);\n    double r = math::euclid_distance_to_key\n      <double6, bracket_minus<double6, double>, double>\n      (6, x, x, bracket_minus<double6, double>());\n    BOOST_CHECK_CLOSE(r, .0, .000000000001);\n    std::fill(x.begin(), x.end(), -1.);\n    r = math::euclid_distance_to_key\n      <double6, bracket_minus<double6, double>, double>\n      (6, x, x, bracket_minus<double6, double>());\n    BOOST_CHECK_CLOSE(r, .0, .000000000001);\n    std::fill(x.begin(), x.end(), 1.);\n    r = math::euclid_distance_to_key\n      <double6, bracket_minus<double6, double>, double>\n      (6, x, x, bracket_minus<double6, double>());\n    BOOST_CHECK_CLOSE(r, .0, .000000000001);\n  }\n  {\n    // Distance between 2 points at different positions in 3D\n    for (int i=0; i<100; ++i)\n      {\n        double6 p = make_double6(drand(), drand(), drand(),\n                                 drand(), drand(), drand());\n        double6 q = make_double6(drand(), drand(), drand(),\n                                 drand(), drand(), drand());\n        double dist = math::euclid_distance_to_key\n          <double6, bracket_minus<double6, double>, double>\n          (6, p, q, bracket_minus<double6, double>());\n        using namespace ::std;\n        double other_dist = sqrt((p[0] - q[0]) * (p[0] - q[0])\n                                 + (p[1] - q[1]) * (p[1] - q[1])\n                                 + (p[2] - q[2]) * (p[2] - q[2])\n                                 + (p[3] - q[3]) * (p[3] - q[3])\n                                 + (p[4] - q[4]) * (p[4] - q[4])\n                                 + (p[5] - q[5]) * (p[5] - q[5]));\n        BOOST_CHECK_CLOSE(dist, other_dist, .000000000001);\n      }\n  }\n}\n\nBOOST_AUTO_TEST_CASE( test_euclidian_square_distance_to_key )\n{\n  {\n    // distance between 2 points at the same position should be null.\n    quad x(0, 0, 0, 0);\n    int r = math::square_euclid_distance_to_key\n      <quad, accessor_minus<quad_access, quad, int>, int>\n      (4, x, x, accessor_minus<quad_access, quad, int>());\n    BOOST_CHECK_EQUAL(r, 0);\n    x = quad(1, 1, 1, 1);\n    r = math::square_euclid_distance_to_key\n      <quad, accessor_minus<quad_access, quad, int>, int>\n      (4, x, x, accessor_minus<quad_access, quad, int>());\n    BOOST_CHECK_EQUAL(r, 0);\n    x = quad(-1, -1, -1, -1);\n    r = math::square_euclid_distance_to_key\n      <quad, accessor_minus<quad_access, quad, int>, int>\n      (4, x, x, accessor_minus<quad_access, quad, int>());\n    BOOST_CHECK_EQUAL(r, 0);\n  }\n  {\n    // Distance between 2 points at different positions in 3D\n    for (int i=0; i<100; ++i)\n      {\n        quad p, q;\n        p.x = std::rand() % 80 - 40;\n        p.y = std::rand() % 80 - 40;\n        p.z = std::rand() % 80 - 40;\n        p.w = std::rand() % 80 - 40;\n        q.x = std::rand() % 80 - 40;\n        q.y = std::rand() % 80 - 40;\n        q.z = std::rand() % 80 - 40;\n        q.w = std::rand() % 80 - 40;\n        int dist = math::square_euclid_distance_to_key\n          <quad, accessor_minus<quad_access, quad, int>, int>\n          (4, p, q, accessor_minus<quad_access, quad, int>());\n        int other_dist = (p.x-q.x)*(p.x-q.x) + (p.y-q.y)*(p.y-q.y)\n          + (p.z-q.z)*(p.z-q.z) + (p.w-q.w)*(p.w-q.w);\n        BOOST_CHECK_EQUAL(dist, other_dist);\n      }\n  }\n}\n\nBOOST_AUTO_TEST_CASE( test_manhattan_distance_to_key )\n{\n  {\n    // distance between 2 points at the same position should be null.\n    quad x(0, 0, 0, 0);\n    int r = math::manhattan_distance_to_key\n      <quad, accessor_minus<quad_access, quad, int>, int>\n      (4, x, x, accessor_minus<quad_access, quad, int>());\n    BOOST_CHECK_EQUAL(r, 0);\n    x = quad(1, 1, 1, 1);\n    r = math::manhattan_distance_to_key\n      <quad, accessor_minus<quad_access, quad, int>, int>\n      (4, x, x, accessor_minus<quad_access, quad, int>());\n    BOOST_CHECK_EQUAL(r, 0);\n    x = quad(-1, -1, -1, -1);\n    r = math::manhattan_distance_to_key\n      <quad, accessor_minus<quad_access, quad, int>, int>\n      (4, x, x, accessor_minus<quad_access, quad, int>());\n    BOOST_CHECK_EQUAL(r, 0);\n  }\n  {\n    // Distance between 2 points at different positions in 3D\n    for (int i=0; i<100; ++i)\n      {\n        quad p, q;\n        p.x = std::rand() % 80 - 40;\n        p.y = std::rand() % 80 - 40;\n        p.z = std::rand() % 80 - 40;\n        p.w = std::rand() % 80 - 40;\n        q.x = std::rand() % 80 - 40;\n        q.y = std::rand() % 80 - 40;\n        q.z = std::rand() % 80 - 40;\n        q.w = std::rand() % 80 - 40;\n        int dist = math::manhattan_distance_to_key\n          <quad, accessor_minus<quad_access, quad, int>, int>\n          (4, p, q, accessor_minus<quad_access, quad, int>());\n        using namespace ::std;\n        int other_dist = abs(p.x-q.x) + abs(p.y-q.y)\n          + abs(p.z-q.z) + abs(p.w-q.w);\n        BOOST_CHECK_EQUAL(dist, other_dist);\n      }\n  }\n}\n", "meta": {"hexsha": "4766026fc2741d801078b6a28214c39dd98cb9a8", "size": 6757, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/verify/verify_metric.cpp", "max_stars_repo_name": "Roboauto/spatial", "max_stars_repo_head_hexsha": "fe652631eb5ec23a719bf1788c68cbd67060e12b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-12-07T02:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T05:39:05.000Z", "max_issues_repo_path": "tests/verify/verify_metric.cpp", "max_issues_repo_name": "Roboauto/spatial", "max_issues_repo_head_hexsha": "fe652631eb5ec23a719bf1788c68cbd67060e12b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-28T15:07:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-28T15:07:42.000Z", "max_forks_repo_path": "tests/verify/verify_metric.cpp", "max_forks_repo_name": "Roboauto/spatial", "max_forks_repo_head_hexsha": "fe652631eb5ec23a719bf1788c68cbd67060e12b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-08-31T13:30:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T07:22:03.000Z", "avg_line_length": 35.3769633508, "max_line_length": 83, "alphanum_fraction": 0.5835429925, "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5515036370641923}}
{"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": "/*\n * Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// check memory allocation in some method\n#define EIGEN_RUNTIME_NO_MALLOC\n\n// includes\n// std\n#include <iostream>\n\n// boost\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE RBInertiad ABinertiad test\n#include <boost/test/unit_test.hpp>\n\n// SpaceVecAlg\n#include <SpaceVecAlg/SpaceVecAlg>\n\ntypedef Eigen::Matrix<double, 6, Eigen::Dynamic> Matrix6Xd;\n\nconst double TOL = 0.00001;\n\nbool isUpperNull(const Eigen::Matrix3d & m)\n{\n  using namespace Eigen;\n  return (Matrix3d(m.triangularView<StrictlyUpper>()).array() == 0.).all();\n}\n\nBOOST_AUTO_TEST_CASE(RBInertiadTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n\n  double mass = 1.;\n  Matrix3d I;\n  I << 1., 2., 3., 2., 1., 4., 3., 4., 1.;\n  Vector3d h = Vector3d::Random() * 100.;\n\n  // Parametrized constructor double Vector3d Matrix3d\n  RBInertiad rb2(mass, h, I);\n\n  BOOST_CHECK_EQUAL(rb2.mass(), mass);\n  BOOST_CHECK_EQUAL(rb2.momentum(), h);\n  BOOST_CHECK_EQUAL(rb2.inertia(), I);\n  BOOST_CHECK(isUpperNull(rb2.lowerTriangularInertia()));\n\n  // Parametrized constructor double Vector3d Matrix3d\n  RBInertiad rb3(mass, h, I.triangularView<Lower>());\n\n  BOOST_CHECK_EQUAL(rb3.mass(), mass);\n  BOOST_CHECK_EQUAL(rb3.momentum(), h);\n  BOOST_CHECK_EQUAL(rb3.inertia(), I);\n  BOOST_CHECK(isUpperNull(rb3.lowerTriangularInertia()));\n\n  // rbI + rbI\n  RBInertiad rb4 = rb2 + rb3;\n\n  BOOST_CHECK_EQUAL(rb4.mass(), mass + mass);\n  BOOST_CHECK_EQUAL(rb4.momentum(), h + h);\n  BOOST_CHECK_EQUAL(rb4.inertia(), I + I);\n  BOOST_CHECK(isUpperNull(rb4.lowerTriangularInertia()));\n\n  // alpha * rbI\n  RBInertiad rb5 = 2. * rb2;\n\n  BOOST_CHECK_EQUAL(rb5.mass(), 2. * mass);\n  BOOST_CHECK_EQUAL(rb5.momentum(), 2. * h);\n  BOOST_CHECK_EQUAL(rb5.inertia(), 2. * I);\n  BOOST_CHECK(isUpperNull(rb5.lowerTriangularInertia()));\n\n  // rbI * alpha\n  RBInertiad rb6 = rb2 * 2.;\n\n  BOOST_CHECK_EQUAL(rb6.mass(), 2. * mass);\n  BOOST_CHECK_EQUAL(rb6.momentum(), 2. * h);\n  BOOST_CHECK_EQUAL(rb6.inertia(), 2. * I);\n  BOOST_CHECK(isUpperNull(rb6.lowerTriangularInertia()));\n\n  // rbI - rbI\n  RBInertiad rb7 = rb2 - rb3;\n\n  BOOST_CHECK_EQUAL(rb7.mass(), mass - mass);\n  BOOST_CHECK_EQUAL(rb7.momentum(), h - h);\n  BOOST_CHECK_EQUAL(rb7.inertia(), I - I);\n  BOOST_CHECK(isUpperNull(rb7.lowerTriangularInertia()));\n\n  // -rbI\n  RBInertiad rb8 = -rb2;\n\n  BOOST_CHECK_EQUAL(rb8, rb2 * -1.);\n  BOOST_CHECK(isUpperNull(rb8.lowerTriangularInertia()));\n\n  // rbI += rbI\n  RBInertiad rb9(rb2);\n  rb9 += rb3;\n\n  BOOST_CHECK_EQUAL(rb9, rb2 + rb3);\n  BOOST_CHECK(isUpperNull(rb9.lowerTriangularInertia()));\n\n  // rbI -= rbI\n  RBInertiad rb10(rb2);\n  rb10 -= rb3;\n\n  BOOST_CHECK_EQUAL(rb10, rb2 - rb3);\n  BOOST_CHECK(isUpperNull(rb10.lowerTriangularInertia()));\n\n  // ==\n  BOOST_CHECK_EQUAL(rb2, rb2);\n  BOOST_CHECK_NE(rb2, rb6);\n\n  // !=\n  BOOST_CHECK(rb2 != rb6);\n  BOOST_CHECK(!(rb2 != rb2));\n}\n\nBOOST_AUTO_TEST_CASE(ABInertiadTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n\n  Matrix3d M, H, I;\n  M << 1., 2., 3., 2., 1., 4., 3., 4., 1.;\n  H = Matrix3d::Random() * 100.;\n  I << 1., 2., 3., 2., 1., 4., 3., 4., 1.;\n\n  // Parametrized constructor double Vector3d Matrix3d\n  ABInertiad ab1(M, H, I);\n\n  BOOST_CHECK_EQUAL(ab1.massMatrix(), M);\n  BOOST_CHECK(isUpperNull(ab1.lowerTriangularMassMatrix()));\n  BOOST_CHECK_EQUAL(ab1.gInertia(), H);\n  BOOST_CHECK_EQUAL(ab1.inertia(), I);\n  BOOST_CHECK(isUpperNull(ab1.lowerTriangularInertia()));\n\n  // Parametrized constructor double Vector3d Matrix3d\n  ABInertiad ab2(M.triangularView<Lower>(), H, I.triangularView<Lower>());\n\n  BOOST_CHECK_EQUAL(ab2.massMatrix(), M);\n  BOOST_CHECK(isUpperNull(ab2.lowerTriangularMassMatrix()));\n  BOOST_CHECK_EQUAL(ab2.gInertia(), H);\n  BOOST_CHECK_EQUAL(ab2.inertia(), I);\n  BOOST_CHECK(isUpperNull(ab2.lowerTriangularInertia()));\n\n  // abI + abI\n  ABInertiad ab3 = ab1 + ab2;\n\n  BOOST_CHECK_EQUAL(ab3.massMatrix(), M + M);\n  BOOST_CHECK(isUpperNull(ab3.lowerTriangularMassMatrix()));\n  BOOST_CHECK_EQUAL(ab3.gInertia(), H + H);\n  BOOST_CHECK_EQUAL(ab3.inertia(), I + I);\n  BOOST_CHECK(isUpperNull(ab3.lowerTriangularInertia()));\n\n  // alpha * rbI\n  ABInertiad ab4 = 2. * ab2;\n\n  BOOST_CHECK_EQUAL(ab4.massMatrix(), 2. * M);\n  BOOST_CHECK(isUpperNull(ab4.lowerTriangularMassMatrix()));\n  BOOST_CHECK_EQUAL(ab4.gInertia(), 2. * H);\n  BOOST_CHECK_EQUAL(ab4.inertia(), 2. * I);\n  BOOST_CHECK(isUpperNull(ab4.lowerTriangularInertia()));\n\n  // abI * alpha\n  ABInertiad ab5 = ab2 * 2.;\n\n  BOOST_CHECK_EQUAL(ab5.massMatrix(), 2. * M);\n  BOOST_CHECK(isUpperNull(ab5.lowerTriangularMassMatrix()));\n  BOOST_CHECK_EQUAL(ab5.gInertia(), 2. * H);\n  BOOST_CHECK_EQUAL(ab5.inertia(), 2. * I);\n  BOOST_CHECK(isUpperNull(ab5.lowerTriangularInertia()));\n\n  // abI - abI\n  ABInertiad ab6 = ab1 - ab2;\n\n  BOOST_CHECK_EQUAL(ab6.massMatrix(), M - M);\n  BOOST_CHECK(isUpperNull(ab6.lowerTriangularMassMatrix()));\n  BOOST_CHECK_EQUAL(ab6.gInertia(), H - H);\n  BOOST_CHECK_EQUAL(ab6.inertia(), I - I);\n  BOOST_CHECK(isUpperNull(ab6.lowerTriangularInertia()));\n\n  // -abI\n  ABInertiad ab7 = -ab1;\n  BOOST_CHECK_EQUAL(ab7, ab1 * -1.);\n  BOOST_CHECK(isUpperNull(ab7.lowerTriangularMassMatrix()));\n  BOOST_CHECK(isUpperNull(ab7.lowerTriangularInertia()));\n\n  // abI += abI\n  ABInertiad ab8(ab1);\n  ab8 += ab2;\n\n  BOOST_CHECK_EQUAL(ab8, ab1 + ab2);\n  BOOST_CHECK(isUpperNull(ab8.lowerTriangularMassMatrix()));\n  BOOST_CHECK(isUpperNull(ab8.lowerTriangularInertia()));\n\n  // abI -= abI\n  ABInertiad ab9(ab1);\n  ab9 -= ab2;\n\n  BOOST_CHECK_EQUAL(ab9, ab1 - ab2);\n  BOOST_CHECK(isUpperNull(ab9.lowerTriangularMassMatrix()));\n  BOOST_CHECK(isUpperNull(ab9.lowerTriangularInertia()));\n\n  // ==\n  BOOST_CHECK_EQUAL(ab2, ab2);\n  BOOST_CHECK_NE(ab2, ab5);\n\n  // !=\n  BOOST_CHECK(ab2 != ab5);\n  BOOST_CHECK(!(ab2 != ab2));\n}\n\nBOOST_AUTO_TEST_CASE(RBInertiadLeftOperatorsTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  double mass = 1.;\n  Matrix3d I;\n  I << 1., 2., 3., 2., 1., 4., 3., 4., 1.;\n  Vector3d h = Vector3d::Random() * 100.;\n  RBInertiad rb(mass, h, I);\n  Matrix6d rb6d = rb.matrix();\n\n  Vector3d w, v;\n  w = Vector3d::Random() * 100.;\n  v = Vector3d::Random() * 100.;\n  sva::MotionVecd mVec(w, v);\n  Vector6d mVec6d = mVec.vector();\n\n  // RBInertiad * MotionVecd\n  ForceVecd fVec = rb * mVec;\n  Vector6d fVec6d(rb6d * mVec6d);\n\n  BOOST_CHECK_SMALL((fVec6d - fVec.vector()).array().abs().sum(), TOL);\n\n  // vectorized version\n  Matrix6Xd mVec6Xd(6, 2);\n  Matrix6Xd fVecRes6Xd(6, 2);\n  mVec6Xd << mVec.vector(), mVec.vector();\n\n  internal::set_is_malloc_allowed(false);\n  rb.mul(mVec6Xd, fVecRes6Xd);\n  internal::set_is_malloc_allowed(true);\n\n#ifdef __i386__\n  BOOST_CHECK_SMALL((fVec.vector() - fVecRes6Xd.col(0)).array().abs().sum(), TOL);\n#else\n  BOOST_CHECK_EQUAL(fVec.vector(), fVecRes6Xd.col(0));\n#endif\n  BOOST_CHECK_EQUAL(fVecRes6Xd.col(0), fVecRes6Xd.col(1));\n}\n\nBOOST_AUTO_TEST_CASE(ABInertiadLeftOperatorsTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  Matrix3d M, H, I;\n  M << 1., 2., 3., 2., 1., 4., 3., 4., 1.;\n  H = Matrix3d::Random() * 100.;\n  I << 1., 2., 3., 2., 1., 4., 3., 4., 1.;\n\n  ABInertiad ab(M, H, I);\n  Matrix6d ab6d = ab.matrix();\n\n  double mass = 1.;\n  Vector3d h = Vector3d::Random() * 100.;\n  RBInertiad rb(mass, h, I);\n  Matrix6d rb6d = rb.matrix();\n\n  Vector3d w, v;\n  w = Vector3d::Random() * 100.;\n  v = Vector3d::Random() * 100.;\n  sva::MotionVecd mVec(w, v);\n  Vector6d mVec6d = mVec.vector();\n\n  // ABInertiad + RBInertiad\n  ABInertiad abRes = ab + rb;\n  Matrix6d abRes6d = ab6d + rb6d;\n\n  BOOST_CHECK_SMALL((abRes6d - abRes.matrix()).array().abs().sum(), TOL);\n  BOOST_CHECK(isUpperNull(abRes.lowerTriangularMassMatrix()));\n  BOOST_CHECK(isUpperNull(abRes.lowerTriangularInertia()));\n\n  // ABInertiad * MotionVecd\n  ForceVecd fVec = ab * mVec;\n  Vector6d fVec6d(ab6d * mVec6d);\n\n  BOOST_CHECK_SMALL((fVec6d - fVec.vector()).array().abs().sum(), TOL);\n\n  // vectorized version\n  Matrix6Xd mVec6Xd(6, 2);\n  Matrix6Xd fVecRes6Xd(6, 2);\n  mVec6Xd << mVec.vector(), mVec.vector();\n\n  internal::set_is_malloc_allowed(false);\n  ab.mul(mVec6Xd, fVecRes6Xd);\n  internal::set_is_malloc_allowed(true);\n\n#ifdef __i386__\n  BOOST_CHECK_SMALL((fVec.vector() - fVecRes6Xd.col(0)).array().abs().sum(), TOL);\n#else\n  BOOST_CHECK_EQUAL(fVec.vector(), fVecRes6Xd.col(0));\n#endif\n  BOOST_CHECK_EQUAL(fVecRes6Xd.col(0), fVecRes6Xd.col(1));\n}\n", "meta": {"hexsha": "0e9b7c2c85492db5d377d4febb80556c81f7ca60", "size": 8317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/InertiaTest.cpp", "max_stars_repo_name": "gergondet/SpaceVecAlg", "max_stars_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/InertiaTest.cpp", "max_issues_repo_name": "gergondet/SpaceVecAlg", "max_issues_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/InertiaTest.cpp", "max_forks_repo_name": "gergondet/SpaceVecAlg", "max_forks_repo_head_hexsha": "b5a92d961c7b52f147908c779dfa024c4c302f08", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.268852459, "max_line_length": 82, "alphanum_fraction": 0.6873872791, "num_tokens": 2758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.551466313750672}}
{"text": "#ifndef EIGEN_SHORT_HPP\n#define EIGEN_SHORT_HPP\n\n#include <Eigen/Dense>\n\ntemplate <class T>\n    using map = Eigen::Map<T>;\n\ntemplate <int M = Eigen::Dynamic, int N = Eigen::Dynamic>\n    using mat = Eigen::Matrix<double, M, N>;\n\ntemplate <int M = Eigen::Dynamic, int N = Eigen::Dynamic>\n    using rmat = Eigen::Ref<mat<M,N>>;\n\ntemplate <int M = Eigen::Dynamic, int N = Eigen::Dynamic>\n    using cmat = const Eigen::Ref<const mat<M,N>>;\n\ntemplate <int M = Eigen::Dynamic>\n    using vec = mat<M,1>;\n\ntemplate <int M = Eigen::Dynamic>\n    using rvec = rmat<M,1>;\n\ntemplate <int M = Eigen::Dynamic>\n    using cvec = cmat<M,1>;\n\nusing quat = Eigen::Quaterniond;\n\n#endif\n", "meta": {"hexsha": "000870a3d3d3fb13d2842af2e6a23dee153492f8", "size": 664, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mat.hpp", "max_stars_repo_name": "SIOSlab/ACCIS", "max_stars_repo_head_hexsha": "f5a2f1119053084ad2dbc64c298dbf7af28ea45e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mat.hpp", "max_issues_repo_name": "SIOSlab/ACCIS", "max_issues_repo_head_hexsha": "f5a2f1119053084ad2dbc64c298dbf7af28ea45e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mat.hpp", "max_forks_repo_name": "SIOSlab/ACCIS", "max_forks_repo_head_hexsha": "f5a2f1119053084ad2dbc64c298dbf7af28ea45e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1333333333, "max_line_length": 57, "alphanum_fraction": 0.656626506, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5514663076527606}}
{"text": "/**\n * \\file TestFEM.cpp\n * \\author Norihiro Watanabe\n * \\date   2012-08-03\n *\n * \\copyright\n * Copyright (c) 2013, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include <gtest/gtest.h>\n\n#include <vector>\n#include <cmath>\n#ifdef OGS_USE_EIGEN\n#include <Eigen/Eigen>\n#endif\n\n#include \"MeshLib/Elements/Quad.h\"\n#include \"NumLib/Fem/CoordinatesMapping/ShapeMatrices.h\"\n#include \"NumLib/Fem/FiniteElement/C0IsoparametricElements.h\"\n\n#include \"Tests/TestTools.h\"\n\nusing namespace NumLib;\n\nnamespace\n{\n\nstatic const unsigned dim = 2;\nstatic const unsigned e_nnodes = 4;\n\ntemplate <class T_MATRIX_TYPES>\nclass NumLibFemIsoQuad4Test : public ::testing::Test\n{\n public:\n    // Matrix types\n    typedef typename T_MATRIX_TYPES::NodalMatrixType NodalMatrix;\n    typedef typename T_MATRIX_TYPES::NodalVectorType NodalVector;\n    typedef typename T_MATRIX_TYPES::DimNodalMatrixType DimNodalMatrix;\n    typedef typename T_MATRIX_TYPES::DimMatrixType DimMatrix;\n    // Finite element type\n    typedef typename NumLib::FeQUAD4<NodalVector, DimNodalMatrix, DimMatrix>::type FeQUAD4Type;\n    // Shape matrix data type\n    typedef typename FeQUAD4Type::ShapeMatricesType ShapeMatricesType;\n\n public:\n    NumLibFemIsoQuad4Test() :\n        D(dim, dim),\n        expectedM(e_nnodes,e_nnodes),\n        expectedK(e_nnodes,e_nnodes),\n        integration_method(2)\n    {\n        // create a quad element used for testing\n        unitSquareQuad   = createSquareQuad(1.0);\n\n        // set a conductivity tensor\n        setIdentityMatrix(dim, D);\n        D *= conductivity;\n\n        // set expected matrices\n        setExpectedMassMatrix(expectedM);\n        setExpectedLaplaceMatrix(conductivity, expectedK);\n\n        // for destructor\n        vec_eles.push_back(unitSquareQuad);\n        for (auto e : vec_eles)\n            for (unsigned i=0; i<e->getNNodes(true); i++)\n                vec_nodes.push_back(e->getNode(i));\n    }\n\n    ~NumLibFemIsoQuad4Test()\n    {\n        for (auto itr = vec_nodes.begin(); itr!=vec_nodes.end(); ++itr )\n            delete *itr;\n        for (auto itr = vec_eles.begin(); itr!=vec_eles.end(); ++itr )\n            delete *itr;\n    }\n\n    // Quad: square shape with a length of 1m\n    MeshLib::Quad* createSquareQuad(double h)\n    {\n        MeshLib::Node** nodes = new MeshLib::Node*[e_nnodes];\n        nodes[0] = new MeshLib::Node(0.0, 0.0, 0.0);\n        nodes[1] = new MeshLib::Node(  h, 0.0, 0.0);\n        nodes[2] = new MeshLib::Node(  h,   h, 0.0);\n        nodes[3] = new MeshLib::Node(0.0,   h, 0.0);\n        return new MeshLib::Quad(nodes);\n    }\n\n    // set an identity matrix\n    template <class T_MATRIX, typename ID_TYPE=signed>\n    void setIdentityMatrix(unsigned dim, T_MATRIX &m) const\n    {\n        for (unsigned i=0; i<dim; i++)\n            for (unsigned j=0; j<dim; j++)\n                m(i,j) = 0.0;\n        for (unsigned i=0; i<dim; i++)\n            m(i,i) = 1.0;\n    }\n\n    // copy upper triangles to lower triangles in a matrix\n    template <class T_MATRIX, typename ID_TYPE=signed>\n    void copyUpperToLower(const ID_TYPE dim, T_MATRIX &m) const\n    {\n        for (ID_TYPE i=0; i<dim; i++)\n            for (ID_TYPE j=0; j<i; j++)\n                m(i,j) = m(j,i);\n    }\n\n    // set an expected mass matrix for 1m x 1m\n    template <class T_MATRIX, typename ID_TYPE=signed>\n    void setExpectedMassMatrix(T_MATRIX &m)\n    {\n        // set upper triangle entries\n        m(0,0) = 1.0; m(0,1) = 1./2; m(0,2) = 1./4; m(0,3) = 1./2;\n        m(1,1) = 1.0; m(1,2) = 1./2; m(1,3) = 1./4;\n        m(2,2) = 1.0; m(2,3) = 1./2;\n        m(3,3) = 1.0;\n        // make symmetric\n        copyUpperToLower(4, m);\n        m *= 1./9.;\n    }\n\n    // set an expected laplace matrix for 1m x 1m\n    template <class T_MATRIX, typename ID_TYPE=signed>\n    void setExpectedLaplaceMatrix(double k, T_MATRIX &m)\n    {\n        // set upper triangle entries\n        m(0,0) = 4.0; m(0,1) = -1.0; m(0,2) = -2.0; m(0,3) = -1.0;\n        m(1,1) = 4.0; m(1,2) = -1.0; m(1,3) = -2.0;\n        m(2,2) = 4.0; m(2,3) = -1.0;\n        m(3,3) = 4.0;\n        // make symmetric\n        copyUpperToLower(4, m);\n        m *= k/6.;\n    }\n\n    static const double conductivity;\n    static const double eps;\n    DimMatrix D;\n    NodalMatrix expectedM;\n    NodalMatrix expectedK;\n    typename FeQUAD4Type::IntegrationMethod integration_method;\n\n    std::vector<const MeshLib::Node*> vec_nodes;\n    std::vector<const MeshLib::Quad*> vec_eles;\n    MeshLib::Quad* unitSquareQuad;\n\n}; // NumLibFemIsoQuad4Test\n\ntemplate <class T_MATRIX_TYPES>\nconst double NumLibFemIsoQuad4Test<T_MATRIX_TYPES>::conductivity = 1e-11;\n\ntemplate <class T_MATRIX_TYPES>\nconst double NumLibFemIsoQuad4Test<T_MATRIX_TYPES>::eps = std::numeric_limits<double>::epsilon();\n\n} // namespace\n\n#ifdef OGS_USE_EIGEN\n\nstruct EigenFixedMatrixTypes\n{\n    typedef Eigen::Matrix<double, e_nnodes, e_nnodes, Eigen::RowMajor> NodalMatrixType;\n    typedef Eigen::Matrix<double, e_nnodes, 1> NodalVectorType;\n    typedef Eigen::Matrix<double, dim, e_nnodes, Eigen::RowMajor> DimNodalMatrixType;\n    typedef Eigen::Matrix<double, dim, dim, Eigen::RowMajor> DimMatrixType;\n};\n\nstruct EigenDynamicMatrixTypes\n{\n    typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> NodalMatrixType;\n    typedef NodalMatrixType DimNodalMatrixType;\n    typedef NodalMatrixType DimMatrixType;\n    typedef Eigen::VectorXd NodalVectorType;\n};\n\n#endif // OGS_USE_EIGEN\n\ntypedef ::testing::Types<\n#ifdef OGS_USE_EIGEN\n        EigenFixedMatrixTypes\n        , EigenDynamicMatrixTypes\n#endif\n        > MatrixTypes;\n\nTYPED_TEST_CASE(NumLibFemIsoQuad4Test, MatrixTypes);\n\nTYPED_TEST(NumLibFemIsoQuad4Test, CheckMassMatrix)\n{\n    // Refer to typedefs in the fixture\n    typedef typename TestFixture::FeQUAD4Type FeQUAD4Type;\n    typedef typename TestFixture::NodalMatrix NodalMatrix;\n    typedef typename TestFixture::ShapeMatricesType ShapeMatricesType;\n\n    // create a finite element object\n    FeQUAD4Type fe(*this->unitSquareQuad);\n\n    // evaluate a mass matrix M = int{ N^T D N }dA_e\n    NodalMatrix M(e_nnodes, e_nnodes);\n    ShapeMatricesType shape(dim, e_nnodes);\n    for (std::size_t i=0; i < this->integration_method.getNPoints(); i++) {\n        shape.setZero();\n        auto wp = this->integration_method.getWeightedPoint(i);\n        fe.template computeShapeFunctions<ShapeMatrixType::N_J>(wp.getCoords(), shape);\n        M.noalias() += shape.N * shape.N.transpose() * shape.detJ * wp.getWeight();\n    }\n\n    ASSERT_ARRAY_NEAR(this->expectedM.data(), M.data(), M.size(), this->eps);\n}\n\nTYPED_TEST(NumLibFemIsoQuad4Test, CheckLaplaceMatrix)\n{\n    // Refer to typedefs in the fixture\n    typedef typename TestFixture::FeQUAD4Type FeQUAD4Type;\n    typedef typename TestFixture::NodalMatrix NodalMatrix;\n    typedef typename TestFixture::ShapeMatricesType ShapeMatricesType;\n\n    // create a finite element object\n    FeQUAD4Type fe(*this->unitSquareQuad);\n\n    // evaluate a Laplace matrix K = int{ dNdx^T D dNdx }dA_e\n    NodalMatrix K(e_nnodes, e_nnodes);\n    ShapeMatricesType shape(dim, e_nnodes);\n    for (std::size_t i=0; i < this->integration_method.getNPoints(); i++) {\n        shape.setZero();\n        auto wp = this->integration_method.getWeightedPoint(i);\n        fe.template computeShapeFunctions<ShapeMatrixType::DNDX>(wp.getCoords(), shape);\n        K.noalias() += shape.dNdx.transpose() * this->D * shape.dNdx * shape.detJ * wp.getWeight();\n    }\n    ASSERT_ARRAY_NEAR(this->expectedK.data(), K.data(), K.size(), this->eps);\n}\n\nTYPED_TEST(NumLibFemIsoQuad4Test, CheckMassLaplaceMatrices)\n{\n    // Refer to typedefs in the fixture\n    typedef typename TestFixture::FeQUAD4Type FeQUAD4Type;\n    typedef typename TestFixture::NodalMatrix NodalMatrix;\n    typedef typename TestFixture::ShapeMatricesType ShapeMatricesType;\n\n    // create a finite element object\n    FeQUAD4Type fe(*this->unitSquareQuad);\n\n    // evaluate both mass and laplace matrices at once\n    NodalMatrix M(e_nnodes, e_nnodes);\n    NodalMatrix K(e_nnodes, e_nnodes);\n    ShapeMatricesType shape(dim, e_nnodes);\n    for (std::size_t i=0; i < this->integration_method.getNPoints(); i++) {\n        shape.setZero();\n        auto wp = this->integration_method.getWeightedPoint(i);\n        fe.computeShapeFunctions(wp.getCoords(), shape);\n        M.noalias() += shape.N * shape.N.transpose() * shape.detJ * wp.getWeight();\n        K.noalias() += shape.dNdx.transpose() * this->D * shape.dNdx * shape.detJ * wp.getWeight();\n    }\n    ASSERT_ARRAY_NEAR(this->expectedM.data(), M.data(), M.size(), this->eps);\n    ASSERT_ARRAY_NEAR(this->expectedK.data(), K.data(), K.size(), this->eps);\n}\n\nTYPED_TEST(NumLibFemIsoQuad4Test, CheckGaussIntegrationLevel)\n{\n    // Refer to typedefs in the fixture\n    typedef typename TestFixture::FeQUAD4Type FeQUAD4Type;\n    typedef typename TestFixture::NodalMatrix NodalMatrix;\n    typedef typename TestFixture::ShapeMatricesType ShapeMatricesType;\n\n    // create a finite element object with gauss quadrature level 2\n    FeQUAD4Type fe(*this->unitSquareQuad);\n\n    // evaluate a mass matrix\n    NodalMatrix M(e_nnodes, e_nnodes);\n    ShapeMatricesType shape(dim, e_nnodes);\n    ASSERT_EQ(4u, this->integration_method.getNPoints());\n    for (std::size_t i=0; i < this->integration_method.getNPoints(); i++) {\n        shape.setZero();\n        auto wp = this->integration_method.getWeightedPoint(i);\n        fe.computeShapeFunctions(wp.getCoords(), shape);\n        M.noalias() += shape.N * shape.N.transpose() * shape.detJ * wp.getWeight();\n    }\n    ASSERT_ARRAY_NEAR(this->expectedM.data(), M.data(), M.size(), this->eps);\n\n    // Change gauss quadrature level to 3\n    this->integration_method.setIntegrationOrder(3);\n    M *= .0;\n    ASSERT_EQ(9u, this->integration_method.getNPoints());\n    for (std::size_t i=0; i < this->integration_method.getNPoints(); i++) {\n        shape.setZero();\n        auto wp = this->integration_method.getWeightedPoint(i);\n        fe.computeShapeFunctions(wp.getCoords(), shape);\n        M.noalias() += shape.N * shape.N.transpose() * shape.detJ * wp.getWeight();\n    }\n    ASSERT_ARRAY_NEAR(this->expectedM.data(), M.data(), M.size(), this->eps);\n}\n\n\n", "meta": {"hexsha": "8f47b0b7f78cd706252ffb14c71dc1804d1ecb87", "size": 10306, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/NumLib/TestFeQuad4.cpp", "max_stars_repo_name": "WenjieXu/ogs", "max_stars_repo_head_hexsha": "0cd1b72ec824833bf949a8bbce073c82158ee443", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-21T17:29:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T17:29:38.000Z", "max_issues_repo_path": "Tests/NumLib/TestFeQuad4.cpp", "max_issues_repo_name": "WenjieXu/ogs", "max_issues_repo_head_hexsha": "0cd1b72ec824833bf949a8bbce073c82158ee443", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tests/NumLib/TestFeQuad4.cpp", "max_forks_repo_name": "WenjieXu/ogs", "max_forks_repo_head_hexsha": "0cd1b72ec824833bf949a8bbce073c82158ee443", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5838926174, "max_line_length": 99, "alphanum_fraction": 0.6644673006, "num_tokens": 2919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5514663073247769}}
{"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": "// Base-2 logarithm bithack.\n\n\n\n\n#ifndef _AFJDFJSDFSD_PYCUDA_HEADER_SEEN_BITLOG_HPP\n#define _AFJDFJSDFSD_PYCUDA_HEADER_SEEN_BITLOG_HPP\n\n\n\n\n#include <climits>\n#include <boost/cstdint.hpp>\n\n\nnamespace pyhip\n{\n  extern const char log_table_8[];\n\n  inline unsigned bitlog2_16(boost::uint16_t v)\n  {\n    if (unsigned long t = v >> 8)\n      return 8+log_table_8[t];\n    else \n      return log_table_8[v];\n  }\n\n  inline unsigned bitlog2_32(boost::uint32_t v)\n  {\n    if (boost::uint16_t t = v >> 16)\n      return 16+bitlog2_16(t);\n    else \n      return bitlog2_16(boost::uint16_t(v));\n  }\n\n  inline unsigned bitlog2(size_t v)\n  {\n#if (ULONG_MAX != 4294967295) || defined(_WIN64)\n    if (boost::uint32_t t = v >> 32)\n      return 32+bitlog2_32(t);\n    else \n#endif\n      return bitlog2_32(unsigned(v));\n   }\n}\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "7832ccb80a05cc60b02cb205c0790344e3cd7fc6", "size": 815, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/bitlog.hpp", "max_stars_repo_name": "ahmed-f-alrefaie/pyhip", "max_stars_repo_head_hexsha": "713280b65ca5a375cdf4d303330e4ec10df606e7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/bitlog.hpp", "max_issues_repo_name": "ahmed-f-alrefaie/pyhip", "max_issues_repo_head_hexsha": "713280b65ca5a375cdf4d303330e4ec10df606e7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/bitlog.hpp", "max_forks_repo_name": "ahmed-f-alrefaie/pyhip", "max_forks_repo_head_hexsha": "713280b65ca5a375cdf4d303330e4ec10df606e7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.6730769231, "max_line_length": 50, "alphanum_fraction": 0.6601226994, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.5513730565463394}}
{"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 \"surveypattern.h\"\n#include \"waypoint.h\"\n#include <QPainter>\n#include <QtMath>\n#include <QJsonObject>\n#include <QJsonArray>\n#include <QDebug>\n#include \"platform.h\"\n#include \"autonomousvehicleproject.h\"\n#include \"surveyarea.h\"\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\nnamespace bg = boost::geometry;\n\nSurveyPattern::SurveyPattern(MissionItem *parent):GeoGraphicsMissionItem(parent),\n    m_startLocation(nullptr),m_endLocation(nullptr),m_spacing(1.0),m_direction(0.0),m_alignment(Alignment::start),m_spacingLocation(nullptr),m_internalUpdateFlag(false)\n{\n    setShowLabelFlag(true);\n}\n\nWaypoint * SurveyPattern::createWaypoint()\n{\n    Waypoint * wp = createMissionItem<Waypoint>();\n    wp->setFlag(QGraphicsItem::ItemIsMovable);\n    wp->setFlag(QGraphicsItem::ItemIsSelectable);\n    wp->setFlag(QGraphicsItem::ItemSendsGeometryChanges);\n    wp->setFlag(QGraphicsItem::ItemSendsScenePositionChanges);\n    connect(wp, &Waypoint::waypointMoved, this, &SurveyPattern::waypointHasChanged);\n    connect(wp, &Waypoint::waypointAboutToMove, this, &SurveyPattern::waypointAboutToChange);\n    return wp;\n}\n\nvoid SurveyPattern::setStartLocation(const QGeoCoordinate &location)\n{\n    if(m_startLocation == nullptr)\n    {\n        m_startLocation = createWaypoint();\n        m_startLocation->setObjectName(\"start\");\n    }\n    m_startLocation->setLocation(location);\n    setPos(m_startLocation->geoToPixel(location,autonomousVehicleProject()));\n    m_startLocation->setPos(m_startLocation->geoToPixel(location,autonomousVehicleProject()));\n    update();\n}\n\nvoid SurveyPattern::setEndLocation(const QGeoCoordinate &location, bool calc)\n{\n    if(m_endLocation == nullptr)\n    {\n        m_endLocation = createWaypoint();\n        m_endLocation->setObjectName(\"end\");\n    }\n    m_endLocation->setLocation(location);\n    m_endLocation->setPos(m_endLocation->geoToPixel(location,autonomousVehicleProject()));\n    if(calc)\n        calculateFromWaypoints();\n    update();\n}\n\nvoid SurveyPattern::setSpacingLocation(const QGeoCoordinate &location, bool calc)\n{\n    if(m_spacingLocation == nullptr)\n    {\n        m_spacingLocation = createWaypoint();\n        m_spacingLocation->setObjectName(\"spacing/direction\");\n    }\n    m_spacingLocation->setLocation(location);\n    if(calc)\n        calculateFromWaypoints();\n    update();\n}\n\nvoid SurveyPattern::calculateFromWaypoints()\n{\n    if(m_startLocation && m_endLocation)\n    {\n        qreal ab_distance = m_startLocation->location().distanceTo(m_endLocation->location());\n        qreal ab_angle = m_startLocation->location().azimuthTo(m_endLocation->location());\n\n        qreal ac_distance = 1.0;\n        m_spacing = ab_distance/10.0;\n        qreal ac_angle = 90.0;\n        if(m_spacingLocation)\n        {\n            ac_distance = m_startLocation->location().distanceTo(m_spacingLocation->location());\n            ac_angle = m_startLocation->location().azimuthTo(m_spacingLocation->location());\n            m_spacing = ac_distance;\n            m_direction = ac_angle-90;\n        }\n        qreal leg_heading = ac_angle-90.0;\n        m_lineLength = ab_distance*qCos(qDegreesToRadians(ab_angle-leg_heading));\n        m_totalWidth = ab_distance*qSin(qDegreesToRadians(ab_angle-leg_heading));\n    }\n}\n\n\nvoid SurveyPattern::write(QJsonObject &json) const\n{\n    MissionItem::write(json);\n    json[\"type\"] = \"SurveyPattern\";\n    if(m_startLocation)\n    {\n        QJsonObject slObject;\n        m_startLocation->write(slObject);\n        json[\"startLocation\"] = slObject;\n    }\n    if(m_endLocation)\n    {\n        QJsonObject elObject;\n        m_endLocation->write(elObject);\n        json[\"endLocation\"] = elObject;\n    }\n    json[\"spacing\"] = m_spacing;\n    json[\"direction\"] = m_direction;\n    switch(m_alignment)\n    {\n        case start:\n            json[\"alignment\"] = \"start\";\n            break;\n        case center:\n            json[\"alignment\"] = \"center\";\n            break;\n        case finish:\n            json[\"alignment\"] = \"finish\";\n            break;\n    }\n    QJsonArray tracklineArray;\n    auto lines = getLines();\n    for (auto line: lines){\n        QJsonObject tracklineObject;\n        tracklineObject[\"type\"] = \"TrackLine\";\n        QJsonArray wpArray;\n        for (auto wp: line)\n        {\n            QJsonObject wpObject;\n            wpObject[\"type\"] = \"Waypoint\";\n            wpObject[\"latitude\"] = wp.latitude();\n            wpObject[\"longitude\"] = wp.longitude();\n            wpArray.append(wpObject);\n        }\n        tracklineObject[\"waypoints\"] = wpArray;\n        tracklineArray.append(tracklineObject);\n    }\n    json[\"children\"] = tracklineArray;\n}\n\nvoid SurveyPattern::writeToMissionPlan(QJsonArray& navArray) const\n{\n    auto lines = getLines();\n    for(int i = 0; i < lines.size(); i++)\n    {\n        auto l = lines[i];\n        QJsonObject navItem;\n        navItem[\"pathtype\"] = \"trackline\";\n        AutonomousVehicleProject* avp = autonomousVehicleProject();\n        if(avp)\n        {\n            Platform *platform = avp->currentPlatform();\n            if(platform)\n            {\n                QJsonObject params;\n                params[\"speed_ms\"] = platform->speed()*0.514444; // knots to m/s\n                navItem[\"parameters\"] = params;\n            }\n        }\n        writeBehaviorsToMissionPlanObject(navItem);\n        QJsonArray pathNavArray;\n        for(auto wp: l)\n        {\n            Waypoint * temp_wp = new Waypoint();\n            temp_wp->setLocation(wp);\n            temp_wp->writeNavToMissionPlan(pathNavArray);\n            delete temp_wp;\n        }\n        navItem[\"nav\"] = pathNavArray;\n        navItem[\"type\"] = \"survey_line\";\n        navArray.append(navItem);\n    }    \n}\n\nvoid SurveyPattern::read(const QJsonObject &json)\n{\n    m_startLocation = createWaypoint();\n    m_startLocation->read(json[\"startLocation\"].toObject());\n    m_endLocation = createWaypoint();\n    m_endLocation->read(json[\"endLocation\"].toObject());\n    setDirectionAndSpacing(json[\"direction\"].toDouble(),json[\"spacing\"].toDouble());\n    if(json.contains(\"alignment\"))\n    {\n        if(json[\"alignment\"] == \"start\")\n            m_alignment = start;\n        if(json[\"alignment\"] == \"center\")\n            m_alignment = center;\n        if(json[\"alignment\"] == \"finish\")\n            m_alignment = finish;\n    }\n    calculateFromWaypoints();\n}\n\n\nbool SurveyPattern::hasSpacingLocation() const\n{\n    return (m_spacingLocation != nullptr);\n}\n\ndouble SurveyPattern::spacing() const\n{\n    return m_spacing;\n}\n\ndouble SurveyPattern::direction() const\n{\n    return m_direction;\n}\n\nSurveyPattern::Alignment SurveyPattern::alignment() const\n{\n    return m_alignment;\n}\n\n\ndouble SurveyPattern::lineLength() const\n{\n    return m_lineLength;\n}\n\ndouble SurveyPattern::totalWidth() const\n{\n    return m_totalWidth;\n}\n\nWaypoint * SurveyPattern::startLocationWaypoint() const\n{\n    return m_startLocation;\n}\n\nWaypoint * SurveyPattern::endLocationWaypoint() const\n{\n    return m_endLocation;\n}\n\nvoid SurveyPattern::setDirectionAndSpacing(double direction, double spacing)\n{\n    m_direction = direction;\n    m_spacing = spacing;\n    QGeoCoordinate c = m_startLocation->location().atDistanceAndAzimuth(spacing,direction+90.0);\n    m_internalUpdateFlag = true;\n    setSpacingLocation(c,false);\n    m_internalUpdateFlag = false;\n}\n\nvoid SurveyPattern::setAlignment(SurveyPattern::Alignment alignment)\n{\n    prepareGeometryChange();\n    m_alignment = alignment;\n    qDebug() << \"alignment: \" << alignment;\n    update();\n}\n\n\nvoid SurveyPattern::setLineLength(double lineLength)\n{\n    m_lineLength = lineLength;\n    updateEndLocation();\n}\n\nvoid SurveyPattern::setTotalWidth(double totalWidth)\n{\n    m_totalWidth = totalWidth;\n    updateEndLocation();\n}\n\nvoid SurveyPattern::updateEndLocation()\n{\n    m_internalUpdateFlag = true;\n    QGeoCoordinate p = m_startLocation->location().atDistanceAndAzimuth(m_lineLength, m_direction);\n    p = p.atDistanceAndAzimuth(m_totalWidth,m_direction+90.0);\n    setEndLocation(p,false);\n    m_internalUpdateFlag = false;\n}\n\nQRectF SurveyPattern::boundingRect() const\n{\n    return shape().boundingRect().marginsAdded(QMarginsF(5,5,5,5));\n}\n\nvoid SurveyPattern::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n    auto lines = getLines();\n    if(lines.length() > 0)\n    {\n        painter->save();\n\n        bool selected = false;\n        if(autonomousVehicleProject()->currentSelected() == this)\n            selected = true;\n\n        QPen p;\n        p.setCosmetic(true);\n        if (selected)\n        {\n            p.setWidth(7);\n            p.setColor(Qt::white);\n            painter->setPen(p);\n            \n            for (auto l:lines)\n            {\n                auto first = l.begin();\n                auto second = first;\n                second++;\n                while(second != l.end())\n                {\n                    p.setWidth(10);\n                    p.setColor(Qt::blue);\n                    painter->setPen(p);\n                    painter->drawPoint(m_startLocation->geoToPixel(*first,autonomousVehicleProject()));\n                    p.setWidth(8);\n                    p.setColor(Qt::black);\n                    painter->setPen(p);\n                    painter->drawLine(m_startLocation->geoToPixel(*first,autonomousVehicleProject()),m_startLocation->geoToPixel(*second,autonomousVehicleProject()));\n                    \n\n                    first++;\n                    second++;\n                }\n                p.setWidth(10);\n                p.setColor(Qt::blue);\n                painter->setPen(p);\n                painter->drawPoint(m_startLocation->geoToPixel(*first,autonomousVehicleProject()));\n            }\n        }\n        if(locked())\n            p.setColor(m_lockedColor);\n        else\n            p.setColor(m_unlockedColor);\n        p.setWidth(3);\n        painter->setPen(p);\n\n        bool turn = true; \n        for (auto l:lines)\n        {\n            turn = !turn;\n            auto first = l.begin();\n            auto second = first;\n            second++;\n            while(second != l.end())\n            {\n                p.setWidth(10);\n                p.setColor(Qt::blue);\n                painter->setPen(p);\n                painter->drawPoint(m_startLocation->geoToPixel(*first,autonomousVehicleProject()));\n                if (selected)\n                    p.setWidth(5);\n                else\n                    p.setWidth(3);\n                if(locked())\n                    p.setColor(m_lockedColor);\n                else\n                    p.setColor(m_unlockedColor);\n                painter->setPen(p);\n                painter->drawLine(m_startLocation->geoToPixel(*first,autonomousVehicleProject()),m_startLocation->geoToPixel(*second,autonomousVehicleProject()));\n                \n//                 if(!turn || m_arcCount < 2)\n//                 {\n//                     QPainterPath ret(m_startLocation->geoToPixel(*first,autonomousVehicleProject()));\n//                     drawArrow(ret,m_startLocation->geoToPixel(*second,autonomousVehicleProject()),m_startLocation->geoToPixel(*first,autonomousVehicleProject()));\n//                     painter->drawPath(ret);\n//                 }\n                \n                first++;\n                second++;\n            }\n            p.setWidth(10);\n            p.setColor(Qt::blue);\n            painter->setPen(p);\n            painter->drawPoint(m_startLocation->geoToPixel(*first,autonomousVehicleProject()));\n        }\n        painter->restore();\n    }\n    return;\n\n}\n\nQPainterPath SurveyPattern::shape() const\n{\n    auto lines = getLines();\n    if(!lines.empty())\n    {\n        if(!lines.front().empty())\n        {\n            QPainterPath ret(m_startLocation->geoToPixel(lines.front().front(),autonomousVehicleProject()));\n            for(auto l: lines)\n                for(auto p:l)\n                    ret.lineTo(m_startLocation->geoToPixel(p,autonomousVehicleProject()));\n            QPainterPathStroker pps;\n            pps.setWidth(10);\n            return pps.createStroke(ret);\n        }\n    }\n    return QPainterPath();\n}\n\n\nQList<QList<QGeoCoordinate> > SurveyPattern::getLines() const\n{\n    QList<QList<QGeoCoordinate> > ret;\n    if(m_startLocation && m_endLocation)\n    {\n\n        qreal diagonal_distance = m_startLocation->location().distanceTo(m_endLocation->location());\n        qreal diagonal_angle = m_startLocation->location().azimuthTo(m_endLocation->location());\n\n        qreal line_spacing = 1.0;\n        qreal spacing_angle = 90.0;\n        if(m_spacingLocation)\n        {\n            line_spacing = m_startLocation->location().distanceTo(m_spacingLocation->location());\n            spacing_angle = m_startLocation->location().azimuthTo(m_spacingLocation->location());\n        }\n        else\n            line_spacing = diagonal_distance/10.0;\n\n        qreal leg_heading = spacing_angle-90.0;\n        qreal leg_length = diagonal_distance*qCos(qDegreesToRadians(diagonal_angle-leg_heading));\n\n        qreal surveyWidth = diagonal_distance*qSin(qDegreesToRadians(diagonal_angle-leg_heading));\n\n        int line_count = qCeil(surveyWidth/line_spacing);\n        \n        qreal residual_distance = surveyWidth - ((line_count-1)*line_spacing);\n\n        QList<QGeoCoordinate> line;\n        line.append(m_startLocation->location().atDistanceAndAzimuth(m_alignment*residual_distance/2.0,spacing_angle));\n        line.append(line.back().atDistanceAndAzimuth(leg_length,leg_heading));\n        ret.append(line);\n        \n        for (int i = 1; i < line_count; i++)\n        {\n            line = QList<QGeoCoordinate>();\n            line.append(ret.back().back().atDistanceAndAzimuth(line_spacing,spacing_angle));\n            line.append(ret.back().front().atDistanceAndAzimuth(line_spacing,spacing_angle));\n            ret.append(line);\n        }\n        \n        // Check if we are a child of a SurveyArea.\n        SurveyArea * surveyAreaParent = qobject_cast<SurveyArea*>(parent());\n        if(surveyAreaParent)\n        {\n            typedef bg::model::d2::point_xy<double> BPoint;\n            typedef bg::model::multi_point<BPoint> BMultiPoint;\n            typedef bg::model::linestring<BPoint> BLineString;\n            typedef bg::model::polygon<BPoint> BPolygon;\n            typedef bg::model::multi_linestring<BLineString> BMultiLineString;\n\n            BPolygon area_poly;\n            \n            for(auto wp: surveyAreaParent->waypoints())\n            {\n                BPoint p(wp->location().latitude(), wp->location().longitude());\n                area_poly.outer().push_back(p);\n            }\n            \n            bg::correct(area_poly);\n            \n            QList<QList<QGeoCoordinate> > clipped_ret;\n            for(auto line: ret)\n            {\n                BPoint p1(line.front().latitude(),line.front().longitude());\n                BPoint p2(line.back().latitude(),line.back().longitude());\n                BLineString bline;\n                bline.push_back(p1);\n                bline.push_back(p2);\n                \n                BMultiLineString mls;\n                bg::intersection(bline, area_poly, mls);\n                \n                for(auto l: mls)\n                {\n                    QList<QGeoCoordinate> clipped_line;\n                    for(auto p: l)\n                        clipped_line.push_back(QGeoCoordinate(p.x(), p.y()));\n                    clipped_ret.push_back(clipped_line);\n                }\n            }\n            \n            return clipped_ret;\n        }\n    }\n    return ret;\n}\n\n\nvoid SurveyPattern::waypointAboutToChange()\n{\n    prepareGeometryChange();\n}\n\nvoid SurveyPattern::waypointHasChanged(Waypoint *wp)\n{\n    if(!m_internalUpdateFlag)\n        calculateFromWaypoints();\n    updateETE();\n    emit surveyPatternUpdated();\n}\n\nvoid SurveyPattern::updateProjectedPoints()\n{\n    if(m_startLocation)\n        m_startLocation->updateProjectedPoints();\n    if(m_endLocation)\n        m_endLocation->updateProjectedPoints();\n    if(m_spacingLocation)\n        m_spacingLocation->updateProjectedPoints();\n}\n\n\nvoid SurveyPattern::reverseDirection()\n{\n    prepareGeometryChange();\n    \n    auto direction = m_direction;\n    auto spacing = m_spacing;\n    \n    auto l = m_startLocation->location();\n    \n    m_startLocation->setLocation(m_endLocation->location());\n    m_endLocation->setLocation(l);\n    \n    setDirectionAndSpacing(direction+180,spacing);\n    calculateFromWaypoints();\n    \n    if(m_alignment == start)\n        m_alignment = finish;\n    else if(m_alignment == finish)\n        m_alignment = start;\n    \n    emit surveyPatternUpdated();\n\n    update();\n}\n\n", "meta": {"hexsha": "979ff788954335f4539e7d0b535970bcdd89ffe7", "size": 16623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "surveypattern.cpp", "max_stars_repo_name": "monocilindro/AutonomousMissionPlanner", "max_stars_repo_head_hexsha": "cc748c30716c3f9dce2834d52fe5c2787a4bd9cd", "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": "surveypattern.cpp", "max_issues_repo_name": "monocilindro/AutonomousMissionPlanner", "max_issues_repo_head_hexsha": "cc748c30716c3f9dce2834d52fe5c2787a4bd9cd", "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": "surveypattern.cpp", "max_forks_repo_name": "monocilindro/AutonomousMissionPlanner", "max_forks_repo_head_hexsha": "cc748c30716c3f9dce2834d52fe5c2787a4bd9cd", "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.5009174312, "max_line_length": 168, "alphanum_fraction": 0.6078926788, "num_tokens": 3612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5513607926629781}}
{"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": "#pragma once\n#ifndef _RAY_TRIANGLE_\n#define _RAY_TRIANGLE_\n\n#include <Eigen/Core>\n#include \"ray.hpp\"\n#include \"surface.hpp\"\n\nnamespace raytracer\n{\n\nusing namespace Eigen;\n\nclass Triangle : public Surface\n{\npublic:\n  // Triangle indices\n  typedef Matrix<unsigned int, 3, 1> Vector3u;\n\n  Triangle(unsigned int a, unsigned int b, unsigned int c, const Surface& owner) :\n    indices_(a, b, c),\n    owner_(owner);\n  {\n  }\n\n  bool Intersect(const Ray& ray, HitData& data) override\n  {\n    // Vertices\n    const Vector3f& p0 = owner.vertices_.at(indices_(0));\n    const Vector3f& p1 = owner.vertices_.at(indices_(1));\n    const Vector3f& p2 = owner.vertices_.at(indices_(2));\n\n    // Calculate the edges\n    Vector3f edge1 = p1 - p0;\n    Vector3f edge2 = p2 - p0;\n\n    Vector3f q = ray.distance().cross(e2);\n    float alpha = edge1.dot(q);             // Determinant of matrix m\n\n    if (alpha > eps && alpha < eps)\n    {\n      // data.u = 0\n      // data.v = 0\n      // data.time = 0\n      return false;\n    }\n    float invAlpha = 1.0f / alpha;\n    Vector3f source = ray.position() - p0;\n    float u = invAlpha * source.dot(q);\n    if (u < 0.0f)\n    {\n      // data.u = 0\n      // data.v = 0\n      // data.time = 0\n      return false;\n    }\n\n    Vector3f r = source.cross(edge1);\n    float v = invAlpha * ray.direction().dot(r);\n    if (v < 0.0f)\n    {\n      // data.u = 0\n      // data.v = 0\n      // data.time = 0\n      return false;\n    }\n\n    // Hit data here\n    // float t = f * edge2.dot(r);\n    return true;\n  }\n\n  // TODO: Calculate triangle normal here\n  Vector3f normal() const override\n  {\n    return normal_;\n  }\nprivate:\n  Vector3u indices_;\n  const Surface& owner_;\n  Vector3f normal_;\n};\n\n}     // end of namespace raytracer\n\n#endif // end of _RAY_TRIANGLE_\n", "meta": {"hexsha": "0d895e2a0921a0a2f2102042fc01d3d98b974f55", "size": 1768, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PA4/src/primitives/surface_triangle.hpp", "max_stars_repo_name": "dowoncha/COMP575", "max_stars_repo_head_hexsha": "6e48bdd80cb1a3e677c07655640efa941325e59c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PA4/src/primitives/surface_triangle.hpp", "max_issues_repo_name": "dowoncha/COMP575", "max_issues_repo_head_hexsha": "6e48bdd80cb1a3e677c07655640efa941325e59c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PA4/src/primitives/surface_triangle.hpp", "max_forks_repo_name": "dowoncha/COMP575", "max_forks_repo_head_hexsha": "6e48bdd80cb1a3e677c07655640efa941325e59c", "max_forks_repo_licenses": ["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.3218390805, "max_line_length": 82, "alphanum_fraction": 0.5933257919, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.551360790445431}}
{"text": "#include \"sv/node/viz.h\"\n\n#include <glog/logging.h>\n#include <tf2_eigen/tf2_eigen.h>\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n\nnamespace sv {\n\nusing visualization_msgs::Marker;\nusing visualization_msgs::MarkerArray;\nusing Vector3d = Eigen::Vector3d;\nusing Matrix3d = Eigen::Matrix3d;\n\nvoid MeanCovar2Marker(const Vector3d& mean,\n                      Vector3d eigvals,\n                      Matrix3d eigvecs,\n                      Marker& marker) {\n  MakeRightHanded(eigvals, eigvecs);\n  const Eigen::Quaterniond quat(eigvecs);\n  eigvals = eigvals.cwiseSqrt() * 2;\n\n  marker.pose.position.x = mean.x();\n  marker.pose.position.y = mean.y();\n  marker.pose.position.z = mean.z();\n  marker.pose.orientation.w = quat.w();\n  marker.pose.orientation.x = quat.x();\n  marker.pose.orientation.y = quat.y();\n  marker.pose.orientation.z = quat.z();\n  marker.scale.x = eigvals.x();\n  marker.scale.y = eigvals.y();\n  marker.scale.z = eigvals.z();\n}\n\nvoid Grid2Markers(const SweepGrid& grid,\n                  const std_msgs::Header& header,\n                  std::vector<Marker>& markers) {\n  const double alpha = 0.5;\n  const double eps = 1e-8;\n\n  markers.resize(grid.total() * 2 + 1);\n\n  Eigen::SelfAdjointEigenSolver<Matrix3d> es;\n  auto& line_mk = markers.back();\n  line_mk.header = header;\n  line_mk.ns = \"match\";\n  line_mk.id = 0;\n  line_mk.type = Marker::LINE_LIST;\n  line_mk.action = Marker::ADD;\n  line_mk.color.a = 1.0;\n  line_mk.color.b = 1.0;\n  line_mk.points.clear();\n  line_mk.points.reserve(grid.total() * 2);\n  line_mk.scale.x = 0.005;\n  line_mk.pose.orientation.w = 1.0;\n\n  for (int r = 0; r < grid.rows(); ++r) {\n    for (int c = 0; c < grid.cols(); ++c) {\n      const auto i = grid.Px2Ind({c, r});\n      const auto& match = grid.MatchAt({c, r});\n\n      auto& pano_mk = markers.at(i);\n      auto& grid_mk = markers.at(i + grid.total());\n\n      pano_mk.header = header;\n      pano_mk.ns = \"pano\";\n      pano_mk.id = i;\n      pano_mk.type = Marker::SPHERE;\n      pano_mk.color.g = 1.0;\n\n      grid_mk.header = header;\n      grid_mk.ns = \"grid\";\n      grid_mk.id = i;\n      grid_mk.type = Marker::SPHERE;\n      grid_mk.color.a = alpha;\n      grid_mk.color.r = 1.0;\n\n      if (match.Ok()) {\n        pano_mk.action = Marker::ADD;\n        pano_mk.color.a = match.scale * .9;  // use scale for alpha\n        const auto pt_p = match.mc_p.mean.cast<double>().eval();\n        auto pano_cov = match.mc_p.Covar().cast<double>().eval();\n        // pano_cov.diagonal().array() += eps;\n        es.compute(pano_cov);\n        MeanCovar2Marker(pt_p, es.eigenvalues(), es.eigenvectors(), pano_mk);\n\n        grid_mk.action = Marker::ADD;\n        const auto& tf = grid.TfAt(c);\n        const auto pt_g = (tf * match.mc_g.mean).cast<double>().eval();\n        auto grid_cov = match.mc_g.Covar();\n        const auto R = tf.rotationMatrix();\n        grid_cov = R * grid_cov * R.transpose();\n        grid_cov.diagonal().array() += eps;\n        es.compute(grid_cov.cast<double>());\n        MeanCovar2Marker(pt_g, es.eigenvalues(), es.eigenvectors(), grid_mk);\n\n        // Line\n        geometry_msgs::Point p0, p1;\n        p0.x = pt_p.x();\n        p0.y = pt_p.y();\n        p0.z = pt_p.z();\n        p1.x = pt_g.x();\n        p1.y = pt_g.y();\n        p1.z = pt_g.z();\n        line_mk.points.push_back(p0);\n        line_mk.points.push_back(p1);\n      } else {\n        pano_mk.action = Marker::DELETE;\n        grid_mk.action = Marker::DELETE;\n      }\n    }\n  }\n}\n\ncv::Mat ApplyCmap(const cv::Mat& input,\n                  double scale,\n                  int cmap,\n                  uint8_t bad_color) {\n  CHECK_EQ(input.channels(), 1);\n\n  cv::Mat disp;\n  input.convertTo(disp, CV_8UC1, scale * 255.0);\n  cv::applyColorMap(disp, disp, cmap);\n\n  if (input.depth() >= CV_32F) {\n    disp.setTo(bad_color, cv::Mat(~(input > 0)));\n  }\n\n  return disp;\n}\n\nvoid Imshow(const std::string& name, const cv::Mat& mat, int flag) {\n  cv::namedWindow(name, flag);\n  cv::imshow(name, mat);\n  cv::waitKey(1);\n}\nvoid Traj2PoseArray(const Trajectory& traj, geometry_msgs::PoseArray& parray) {\n  parray.poses.resize(traj.size());\n  for (int i = 0; i < traj.size(); ++i) {\n    const auto& st = traj.At(i);\n    auto& pose = parray.poses.at(i);\n    const auto T_p_l = Sophus::SE3d(st.rot, st.pos) * traj.T_imu_lidar;\n    pose.orientation = tf2::toMsg(T_p_l.unit_quaternion());\n    pose.position = tf2::toMsg(T_p_l.translation());\n  }\n}\n\n}  // namespace sv\n", "meta": {"hexsha": "c208ee1213ddc4ff91fa03e95fd049d6683860a4", "size": 4418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sv/node/viz.cpp", "max_stars_repo_name": "iandouglas96/llol", "max_stars_repo_head_hexsha": "028fe73d4f4f9214b4534cbedb9b53dff039e84f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2021-10-10T00:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:09:40.000Z", "max_issues_repo_path": "sv/node/viz.cpp", "max_issues_repo_name": "iandouglas96/llol", "max_issues_repo_head_hexsha": "028fe73d4f4f9214b4534cbedb9b53dff039e84f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-01-14T15:22:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T20:07:44.000Z", "max_forks_repo_path": "sv/node/viz.cpp", "max_forks_repo_name": "iandouglas96/llol", "max_forks_repo_head_hexsha": "028fe73d4f4f9214b4534cbedb9b53dff039e84f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-12-01T14:04:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T02:37:14.000Z", "avg_line_length": 29.4533333333, "max_line_length": 79, "alphanum_fraction": 0.5980081485, "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5513607868169448}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// tree_view::stage.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_TREE_VIEW_STAGE_HPP_ER_2009\n#define BOOST_TREE_VIEW_STAGE_HPP_ER_2009\n#include <stdexcept>\n#include <boost/format.hpp>\n\nnamespace boost{\nnamespace tree_view{\n\n    // This class maps a position in a tree structure to a position in a vector\n    //\n    // The tree structure has a root node (stage 0) with n adjacent \n    // nodes (stage 1), each of which have n adjacent nodes (stage 2) etc.\n    // The nodes are stored in a vector, starting with the root node,\n    // followed by those in stage1, then those in stage 2 etc. (breadth first)\n    \n    // j : stage\n    // n : number of branches per node\n    template<unsigned j,unsigned n>\n    struct stage{\n        static unsigned position_first;\n        static unsigned position_last;\n        static unsigned number_nodes;\n    };\n\n    template<unsigned n>\n    struct stage<0,n>{\n        static unsigned position_first;\n        static unsigned position_last;\n        static unsigned number_nodes;\n    };\n\n\n    // Client may ignore this:\n    template<typename T> struct position_first_{ static unsigned get(); };\n    template<typename T> struct position_last_{ static unsigned get(); };\n    template<typename T> struct number_nodes_{ static unsigned get(); };\n\n    // Implementation //\n\n    // Initialization\n    template<unsigned n>\n    unsigned stage<0,n>::position_first = 0;\n\n    template<unsigned n>\n    unsigned stage<0,n>::position_last = 1;\n\n    template<unsigned n>\n    unsigned stage<0,n>::number_nodes = 1;\n\n    // Recursion\n    template<unsigned j,unsigned n>\n    unsigned stage<j,n>::position_first \n        = stage<j-1,n>::position_last;\n\n    template<unsigned j,unsigned n>\n    unsigned stage<j,n>::position_last \n        = stage<j,n>::position_first \n            + stage<j,n>::number_nodes;\n\n    template<unsigned j,unsigned n>\n    unsigned stage<j,n>::number_nodes \n        = stage<j-1,n>::number_nodes * n;\n\n    // T = stage\n    template<typename T>\n    unsigned position_first_<T>::get(){ return T::position_first; }\n    template<typename T>\n    unsigned position_last_<T>::get(){ return T::position_last; }\n    template<typename T>\n    unsigned number_nodes_<T>::get(){ return T::number_nodes; }\n\n}// tree_view\n}// boost\n\n#endif", "meta": {"hexsha": "3b31f19b63cedbc87a4d684c0a006f2304a18150", "size": 2768, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tree_view/boost/tree_view/stage.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": "tree_view/boost/tree_view/stage.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": "tree_view/boost/tree_view/stage.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.756097561, "max_line_length": 79, "alphanum_fraction": 0.5917630058, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825655188238, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5513071956955335}}
{"text": "/*\n * Point.hpp\n *\n *  Created on: Apr 4, 2012\n *      Author: david\n */\n\n#ifndef DASP_POINT_HPP_\n#define DASP_POINT_HPP_\n\n#include \"Parameters.hpp\"\n#include \"Array.hpp\"\n#include <Danvil/Tools/MoreMath.h>\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace dasp\n{\n\tstruct Point\n\t{\n\t\t/** image pixel coordinate of point */\n\t\tint px, py;\n\n\t\t/** point color */\n\t\tEigen::Vector3f color;\n\n\t\t/** position [m] of world source point */\n\t\tEigen::Vector3f position;\n\n\t\t/** point surface normal */\n\t\tEigen::Vector3f normal;\n\n\t\t/** estimated radius [px] on the image screen of a super pixel at point depth */\n\t\tfloat cluster_radius_px;\n\n\t\t/** Invalid points are ignored during point to cluster assignment */\n\t\tbool is_valid;\n\n\t\t/** Depth [m] of point */\n\t\tfloat depth() const {\n\t\t\treturn position[2];\n\t\t}\n\n\t\t/** Sets the normal and assures that it points towards the camera (=origin) */\n\t\tvoid setNormal(const Eigen::Vector3f& n) {\n\t\t\tnormal = n;\n\t\t\t// force normal to look towards the camera\n\t\t\t// check if point to camera direction and normal are within 90 deg\n\t\t\t// enforce: normal * (cam_pos - pos) > 0\n\t\t\t// do not need to normalize (cam_pos - pos) as only sign is considered\n\t\t\tconst float q = normal.dot(-position);\n\t\t\tif(q < 0) {\n\t\t\t\tnormal *= -1.0f;\n\t\t\t}\n\t\t\telse if(q == 0) {\n\t\t\t\t// this should not happen ...\n\t\t\t\tnormal = Eigen::Vector3f(0,0,-1);\n\t\t\t}\n\t\t}\n\n\t\t/** Sets normal from gradient */\n\t\tvoid setNormalFromGradient(const Eigen::Vector2f& g) {\n\t\t\tconst float gx = g.x();\n\t\t\tconst float gy = g.y();\n\t\t\tconst float scl = Danvil::MoreMath::FastInverseSqrt(gx*gx + gy*gy + 1.0f);\n\t\t\tsetNormal(Eigen::Vector3f(scl*gx, scl*gy, -scl));\n\t\t}\n\n\t\t/** Computes local depth gradient (depth[m]/distance[m]) */\n\t\tEigen::Vector2f computeGradient() const {\n\t\t\treturn Eigen::Vector2f(normal.x() / normal.z(), normal.y() / normal.z());\n\t\t}\n\n\t\t/** Computes direction of local depth gradient */\n\t\tEigen::Vector2f computeGradientDirection() const {\n\t\t\tconst float nx = normal.x();\n\t\t\tconst float ny = normal.y();\n\t\t\tif(nx == 0.0f && ny == 0.0f) {\n\t\t\t\treturn Eigen::Vector2f::Unit(0);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst float scl = Danvil::MoreMath::FastInverseSqrt(nx*nx + ny*ny);\n\t\t\t\treturn scl * Eigen::Vector2f(nx, ny);\n\t\t\t}\n\t\t}\n\n\t\t/** Computes \"circularity\"\n\t\t  * This is |n_z| = 1/sqrt(||gradient||^2 + 1) = ea/eb = sqrt(1 - ecc*ecc)\n\t\t  */\n\t\tfloat computeCircularity() const {\n\t\t\treturn std::abs(normal.z());\n\t\t}\n\n//\tpublic:\n//\t\t EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n\t};\n\n\ttypedef Array<Point,unsigned int> ImagePoints;\n\n\tstruct Cluster\n\t{\n\t\tstatic constexpr float cPercentage = 0.95f; //0.99f;\n\t\tstatic constexpr float cSigmaScale = 1.959964f; //2.575829f;\n\n\t\tint seed_id;\n\n\t\tbool is_fixed;\n\n\t\tPoint center;\n\n\t\t// Eigen::Matrix3f color_covariance;\n\n\t\tstd::vector<unsigned int> pixel_ids;\n\n\t\tbool isValid() const {\n\t\t\treturn is_fixed || pixel_ids.size() > 3;\n\t\t}\n\n\t\tvoid addPixel(unsigned int index) {\n\t\t\tpixel_ids.push_back(index);\n\t\t}\n\n\t\tvoid removePixel(unsigned int index) {\n\t\t\tauto it = std::find(pixel_ids.begin(), pixel_ids.end(), index);\n\t\t\tif(it != pixel_ids.end()) {\n\t\t\t\tpixel_ids.erase(it);\n\t\t\t}\n\t\t}\n\n//\t\tvoid addPixels(const std::vector<unsigned int>& v) {\n//\t\t\tpixel_ids.insert(pixel_ids.begin(), v.begin(), v.end());\n//\t\t}\n\n\t\t// point covariance matrix\n\t\tEigen::Matrix3f cov;\n\t\t// eigenvalues of the covariance matrix\n\t\tEigen::Vector3f ew;\n\t\t// eigenvectors of the covariance matrix\n\t\tEigen::Matrix3f ev;\n\n\t\t/** Thickness of the cluster computed using smalles eigenvalue */\n\t\tfloat thickness;\n\t\t/** eccentricity of the ellipse described by a and b */\n\t\tfloat eccentricity;\n\t\t/** flatness of the ellipsoide described by a and c */\n\t\tfloat flatness;\n\t\t/** actual area */\n\t\tfloat area;\n\t\t/** actual area / expected area defined by base radius*/\n\t\tfloat area_quotient;\n\n\t\t/** Shape fitting */\n\t\tfloat shape_0, shape_x, shape_y, shape_xy, shape_xx, shape_yy;\n\n\t\t/** Thickness of cluster computed using orthogonal distance from plane\n\t\t * WARNING: only computed if ComputeExt is called!\n\t\t */\n\t\tfloat thickness_plane;\n\n\t\t/** number of pixel which are within superpixel radius but are not part of the superpixel\n\t\t * WARNING: only computed if ComputeExt is called!\n\t\t */\n\t\tfloat coverage_error;\n\n\t\t/** actual area of the superpixel (computed from all pixels) */\n\t\tfloat area_actual;\n\t\t/** expected area of the superpixel (considering local geometry and thickness) */\n\t\tfloat area_expected;\n\t\t/** expected area using the actual base radius (computed from cluster count) (same for all clusters...) */\n\t\tfloat area_expected_global;\n\n\t\tvoid UpdateCenter(const ImagePoints& points, const Parameters& opt);\n\n\t\tvoid ComputeExt(const ImagePoints& points, const Parameters& opt);\n\n\t};\n\n}\n\n#endif\n", "meta": {"hexsha": "7dc12baf4cc1d7bd702bdee4d260faf11851b789", "size": 4667, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp/Point.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/Point.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/Point.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": 25.6428571429, "max_line_length": 108, "alphanum_fraction": 0.6676665952, "num_tokens": 1301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5513071843552128}}
{"text": "#define BOOST_TEST_MODULE blas\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/matrix/all.h++>\n#include <mla/vector/all.h++>\n\n#include <mla/operations/level2/gemv.h++>\n\n\nusing Scalar = float;\n\ntypedef boost::mpl::list<\n\tmla::matrix::DenseRowMajor<Scalar>,\n\tmla::matrix::Diagonal<Scalar>,\n\tmla::matrix::SparseDOK<Scalar>,\n\tmla::matrix::SparseCRS<Scalar>\n> matrix_type_list;\n\n\nusing MatrixType = mla::matrix::SparseCRS<Scalar>;\n\n\ntypedef boost::mpl::list<\n\tmla::vector::Dense<Scalar>,\n\tmla::vector::SparseCS<Scalar>\n> vector_type_list;\n\n\n\nBOOST_AUTO_TEST_SUITE(test_boost_level2)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( blas_level2_test_gemv_zero, VectorType, vector_type_list )\n{\n\tusing namespace mla;\n\n\tScalar alpha = 1.0f;\n\n\t//MatrixType A(3,3);\n\tsize_t length = 3;\n\tmla::matrix::DenseRowMajor<Scalar> A( length, length);\n\n\tA(0,0) = 1.0f;\n\tA(1,1) = 1.0f;\n\tA(2,2) = 1.0f;\n\n\tVectorType x(length);\n\tx.setValue(0, 1.0f);\n\tx.setValue(1, 1.0f);\n\tx.setValue(2, 1.0f);\n\n\tScalar beta = 1.0f;\n\n\tVectorType y(length);\n\ty.setValue(0, 1.0f);\n\ty.setValue(1, 1.0f);\n\ty.setValue(2, 1.0f);\n\n\tgemv(alpha, A, x, beta, y);\n\n\n\tfor(size_t i = 0; i < length; i++)\n\t{\n\t\tBOOST_CHECK_CLOSE( y.getValue(i), 2.0f, 1.0e-5 );\n\t}\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "bb4332180e0e35101cc8d7abe4ce19c9650f54ef", "size": 1307, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_blas_level2_gemv_SparseCRS.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/test_blas_level2_gemv_SparseCRS.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/test_blas_level2_gemv_SparseCRS.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1973684211, "max_line_length": 89, "alphanum_fraction": 0.6931905126, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5513071734873691}}
{"text": "#include <iostream>\n#include <boost/algorithm/clamp.hpp>\n#include <boost/algorithm/minmax.hpp>\n\n#include <ros/ros.h>\n#include <eigen_conversions/eigen_msg.h>\n#include <eigen3/Eigen/Dense>\n#include <control_velpid/pid_controllerv2.h>\n\n\ndouble quaternion_to_euler(double x, double y, double z, double w)\n{\n\tdouble t0, t1, t2, t3, t4;\n\tdouble X,Y,Z;\n\tt0 = 2.0*(w*x + y*z);\n\tt1 = 1.0 - 2.0*(x*x + y*y);\n\tX = atan(t0/t1)*180/M_PI;\n\n\tt2 = 2*(w*y - z*x);\n\tif (t2 > 1)\n\t\tt2 = 1;\n\telse if (t2 <-1)\n\t\tt2 = -1;\n\telse\n\t\tt2 = t2;\n\tY = asin(t2)*180/M_PI;\n\n\tt3 = 2.0*(w*z + x*y);\n\tt4 = 1.0 - 2*(y*y + z*z);\n\tZ = atan(t3/t4)*180/M_PI;\n\n\treturn X, Y, Z;\n}\n\n/*\ndouble compute_linvel_effort_v2(geometry_msgs::PoseStamped goal, geometry_msgs::PoseStamped current, ros::Time last_time){\n\t// Local machine time\n\t_dt = ros::Time::now() - last_time;\n\n\ttf::pointMsgToEigen(goal.pose.position, _goal);\n\ttf::pointMsgToEigen(current.pose.position, _current);\n\n\t// Estimate error in world (Initial) Frame\n\tdistance_error = _goal - _current;\n\tdistance_integral = distance_integral + distance_error * _dt.toSec();\n\tdistance_derivative = (distance_error - previous_distance_error)/_dt.toSec();\n\n\t// Store\n\tprevious_distance_error = distance_error;\n\n\t//vel_world = Kp.dot(distance_error) + Ki.dot(distance_integral) + Kd.dot(distance_derivative);\n\tvel_world(0) = Kp(0)*distance_error(0) + Ki(0)*distance_integral(0) + Kd(0)*distance_derivative(0);\n\tvel_world(1) = Kp(1)*distance_error(1) + Ki(1)*distance_integral(1) + Kd(1)*distance_derivative(1);\n\tvel_world(2) = Kp(2)*distance_error(2) + Ki(2)*distance_integral(2) + Kd(2)*distance_derivative(2);\n\n\troll, pitch, yaw = quaternion_to_euler(current.pose.orientation.x, current.pose.orientation.y, current.pose.orientation.z, current.pose.orientation.w);\n\tyaw_rate_world = (pose_goal(3) - yaw)*yaw_gain;\n\n\tRbv1 << cos(yaw), sin(yaw), 0;\n\tRbv2 << -sin(yaw), cos(yaw), 0;\n\tRbv3 << 0, 0, 1;\n\n\tvel_body(0) = Rbv1(0)*vel_world(0) + Rbv1(1)*vel_world(1) + Rbv1(2)*vel_world(2);\n\tvel_body(1) = Rbv2(0)*vel_world(0) + Rbv2(1)*vel_world(1) + Rbv2(2)*vel_world(2);\n\tvel_body(2) = Rbv3(0)*vel_world(0) + Rbv3(1)*vel_world(1) + Rbv3(2)*vel_world(2);\n\n\treturn (vel_body(0), vel_body(1), vel_body(2), yaw_rate_world);\n}\n*/\n\n\ndouble compute_linvel_effort_v2(geometry_msgs::PoseStamped goal, geometry_msgs::PoseStamped current, ros::Time last_time){\n\t// Local machine time\n\t_dt = ros::Time::now() - last_time;\n\n\ttf::pointMsgToEigen(goal.pose.position, _goal);\n\ttf::pointMsgToEigen(current.pose.position, _current);\n\n\t// Estimate error in world (Initial) Frame\n\tdistance_error = _goal - _current;\n\tdistance_integral = distance_integral + distance_error * _dt.toSec();\n\tdistance_derivative = (distance_error - previous_distance_error)/_dt.toSec();\n\n\t// Store\n\tprevious_distance_error = distance_error;\n\n\t//vel_world = Kp.dot(distance_error) + Ki.dot(distance_integral) + Kd.dot(distance_derivative);\n\tvel_world(0) = Kp(0)*distance_error(0) + Ki(0)*distance_integral(0) + Kd(0)*distance_derivative(0);\n\tvel_world(1) = Kp(1)*distance_error(1) + Ki(1)*distance_integral(1) + Kd(1)*distance_derivative(1);\n\tvel_world(2) = Kp(2)*distance_error(2) + Ki(2)*distance_integral(2) + Kd(2)*distance_derivative(2);\n\n\t//roll, pitch, yaw = quaternion_to_euler(current.pose.orientation.x, current.pose.orientation.y, current.pose.orientation.z, current.pose.orientation.w);\n\t//yaw_rate_world = (pose_goal(3) - yaw)*yaw_gain;\n\n\t//return (vel_world(0), vel_world(1), vel_world(2), yaw_rate_world);\n\treturn (vel_world(0), vel_world(1), vel_world(2));\n}\n\n", "meta": {"hexsha": "0761c799940edecf68e7b5d7f276cfb54225f34a", "size": 3534, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "control_velpid/src/lib/pid_controllerv2.cpp", "max_stars_repo_name": "Dieptranivsr/DroneIVSR", "max_stars_repo_head_hexsha": "5b348465443524878418a6b1f89cf6dba3804c0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "control_velpid/src/lib/pid_controllerv2.cpp", "max_issues_repo_name": "Dieptranivsr/DroneIVSR", "max_issues_repo_head_hexsha": "5b348465443524878418a6b1f89cf6dba3804c0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-04-24T09:36:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-24T09:38:46.000Z", "max_forks_repo_path": "control_velpid/src/lib/pid_controllerv2.cpp", "max_forks_repo_name": "Dieptranivsr/DroneIVSR", "max_forks_repo_head_hexsha": "5b348465443524878418a6b1f89cf6dba3804c0f", "max_forks_repo_licenses": ["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.696969697, "max_line_length": 154, "alphanum_fraction": 0.7102433503, "num_tokens": 1142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5513071678172086}}
{"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\u2013704 (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": "//  (C) Copyright John Maddock 2007.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include \"mp_t.hpp\"\n#include <boost/math/special_functions/expint.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <fstream>\n#include <boost/math/tools/test_data.hpp>\n\nusing namespace boost::math::tools;\n\nstruct expint_data_generator\n{\n   mp_t operator()(mp_t a, mp_t b)\n   {\n      unsigned n = boost::math::tools::real_cast<unsigned>(a);\n      std::cout << n << \"  \" << b << \"  \";\n      mp_t result = boost::math::expint(n, b);\n      std::cout << result << std::endl;\n      return result;\n   }\n};\n\n\nint main()\n{\n   boost::math::expint(1, 0.06227754056453704833984375);\n   std::cout << boost::math::expint(1, mp_t(0.5)) << std::endl;\n\n   parameter_info<mp_t> arg1, arg2;\n   test_data<mp_t> data;\n\n   std::cout << \"Welcome.\\n\"\n      \"This program will generate spot tests for the expint function:\\n\"\n      \"  expint(a, b)\\n\\n\";\n\n   bool cont;\n   std::string line;\n\n   do{\n      get_user_parameter_info(arg1, \"a\");\n      get_user_parameter_info(arg2, \"b\");\n      data.insert(expint_data_generator(), 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=expint_data.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"expint_data.ipp\";\n   std::ofstream ofs(line.c_str());\n   ofs << std::scientific << std::setprecision(40);\n   write_code(ofs, data, \"expint_data\");\n   \n   return 0;\n}\n\n", "meta": {"hexsha": "b99c64923dade0a865154c7ad383fcb21e8df4d2", "size": 1752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/expint_data.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "tools/expint_data.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/tools/expint_data.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 26.9538461538, "max_line_length": 73, "alphanum_fraction": 0.6324200913, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5511204790406173}}
{"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": "/*!\n  \\file auto_axes.hpp\n  \\brief Scalable Vector Graphic (SVG) autoscaling of axes.\n  \\details Inspect container or data values to find minimum and maximum,\n    avoiding values that are NaN and/or 'at limit'.\n    Scale axis using max and min values (calculated or user provided),\n    optionally to include the orgin, and to set the ticks.\n    Provide fine control over any overlap at the edges of the axes to avoid a tiny\n    amount over the limit resulting in an ugly extra major tick.\n    Also allow optional forcing of the ticks to be multiples of 1, 2, 5, 10.\n  \\author\n*/\n\n// Copyright Paul A. Bristow 2006 - 2013, 2021.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_SVG_AUTO_AXES_HPP\n#define BOOST_SVG_AUTO_AXES_HPP\n\n#include <boost/svg_plot/detail/numeric_limits_handling.hpp>\n#include <boost/svg_plot/detail/fp_compare.hpp> // is_small & is_close\n#include <boost/quan/meas.hpp> // for boost::quan::value_of.\n\n//#include <boost/math/special_functions/fpclassify.hpp>\n// for template <class FPT> bool boost::math::isfinite(FPT t);\n#include <boost/algorithm/minmax_element.hpp>\n using boost::minmax_element;\n // minmax_element finds both min and max elements more efficiently than separately.\n\n#include <cmath> // using std::fabs, std::pow, std::ceil, std::log10\n#include <limits> // using std::numeric_limits;\n#include <stdexcept> // using std::domain_error; sdtd::runtime_error;\n#include <iterator> // using std::iterator_traits;\n#include <utility> // using std::pair; using std::make_pair;\n\n// Autoscaling algorithm derived from:\n// Michael P.D. Bramley. CUJ July 2000, p 20 - 26.\n// Antonio Gomiz Bas, CUJ march 2000, p 42 - 45\n// J. A. Nelder and W. Douglas Stirling, FORTRAN program SCALE.\n//  // Algorithm AS 168: Scale Selection and Formatting  W.Douglas Stirling\n// Journal of the Royal Statistical Society.Series C(Applied Statistics)\n// Vol. 30, No. 3 (1981), pp. 339-344 (6 pages)\n// Published By: Wiley\n// Journal of the Royal Statistical Society.Series C(Applied Statistics)\n// https://doi.org/10.2307/2346366\n// https://www.jstor.org/stable/2346366\n// Algorithm AS 96 https://doi.org/10.2307/2346537 J. A. Nelder, Simple Algorithm for Scaling Graphs\n// http://lib.stat.cmu.edu/apstat/96   FORTRAN code\n\nnamespace boost\n{\nnamespace svg\n{\n\n// Forward Declarations:\n\n// Show and show_all to display size and contents of STL containers.\n// range_mx and range_all to find the min and max of STL containers.\n// _all versions deal with a container of containers.\n\n// Round value up to nearest multiple of 10. Round up and round down to 2, 4, 6, 8, 10, or 5, 10 or 2, 5, 10 systems:\n//\ndouble roundup10(double value);\n // Round value down to nearest multiple of 10.\ndouble rounddown10(double value);\n// Round value up to nearest multiple of 5.\ndouble roundup5(double value);\n // Round value down to nearest multiple of 5.\ndouble rounddown5(double value);\n // Round value up to nearest multiple of 2.\ndouble roundup2(double value);\n// Round value down to nearest multiple of 2.\ndouble rounddown2(double value);\n\n// Four versions of scale_axis with different parameter combinations.\n\n// Scale axis and update min and max axis values, and tick increment and number of ticks.\nvoid scale_axis(\n   double min_value, //!< Scale axis from explicit input minimum.\n   double max_value, //!< Scale axis from explicit input maximum.\n   double* axis_min_value, //!< Computed minimum value for the axis, updated by scale_axis.\n   double* axis_max_value, //!<  Computed maximum value for the axis, updated by scale_axis.\n   double* axis_tick_increment, //!<  Computed tick increment for the axis, updated by scale_axis.\n   int* auto_ticks, //!< Computed number of ticks, updated by scale_axis.\n   //  NO check_limits parameter.\n   bool origin = false, //!< Do not include the origin unless the range min_value <= 0 <= max_value.\n   double tight = 0., //!< Tightness - fraction of overrun allowed before another tick used. For visual effect up to about 0.001 might suit a 1000 pixel wide image, allowing values just 1 pixel over the tick to be shown.\n   int min_ticks = 6, //!< Minimum number of major ticks.\n   int steps = 0 //!< Round up and down to 2, 4, 6, 8, 10, or 5, 10 or 2, 5, 10 systems.\n);\n\n/* Scale axis function to define axis marker ticks based on min & max parameters values (handling uncertainty).\n\n  \\param min_value Scale axis from explicit input minimum.\n  \\param max_value Scale axis from explicit input maximum.\n\n  \\param axis_min_value Computed minimum value for the axis, updated by scale_axis.\n  \\param axis_max_value Computed maximum value for the axis, updated by scale_axis.\n  \\param axis_tick_increment Computed tick increment for the axis, updated by scale_axis.\n  \\param auto_ticks  Computed number of ticks, updated by scale_axis.\n  \\param check_limits  If true then check all values for infinity, NaN etc.\n  \\param autoscale_plusminus Multiplier of uncertainty or standard deviations to allow for confidence ellipses.\n  \\param origin If true, ensures that zero is a tick value.\n  \\param tight  Allows user to avoid a small fraction over a tick using another tick.\n  \\param min_ticks  Minimum number of major ticks.\n  \\param steps Round up and down to 2, 4, 6, 8, 10, or 5, 10 or 2, 5, 10 systems.\n */\nvoid scale_axis(\n  double min_value, // Scale axis from explicit input minimum.\n  double max_value, // Scale axis from explicit input maximum.\n  double* axis_min_value, // Minimum value for the axis, updated by scale_axis.\n  double* axis_max_value, //  Maximum value for the axis, updated by scale_axis.\n  double* axis_tick_increment, //  Tick increment for the axis, updated by scale_axis.\n  int* auto_ticks,  // Updated with number of ticks.\n  bool check_limits = true, // Whether to check all values for infinity, NaN etc.\n  double autoscale_plusminus = 2., // Multiplier of uncertainty or standard deviations to allow for confidence ellipses.\n  bool origin = false, // If true, ensures that zero is a tick value.\n  double tight = 0., // Allows user to avoid a small fraction over a tick using another tick.\n  int min_ticks = 6, // Minimum number of ticks.\n  int steps = 0 // Round up and down to 2, 4, 6, 8, 10, or 5, 10, or 2, 5, 10 major ticks multiples.\n);\n\n/* Scale axis using an iterator into an STL container.\n\n \\details Scale axis from data-series values (usually to then plot), perhaps using only part of container.\n\n \\tparam iter Iterator into an STL container: array, vector, set ...\n \\param begin Iterator into @c begin in STL container.\n \\param end iterators into @c end in STL container.\n \\param axis_min_value Computed minimum value for the axis, updated by scale_axis.\n \\param axis_max_value Computed maximum value for the axis, updated by scale_axis.\n \\param axis_tick_increment Computed tick increment for the axis, updated by scale_axis.\n \\param auto_ticks  Computed number of ticks, updated by scale_axis.\n \\param check_limits  If true then check all values for infinity, NaN etc.\n \\param autoscale_plusminus Mutiplier of uncertainty or standard deviations to allow for confidence ellipses.\n \\param origin If true, ensures that zero is a tick value.\n \\param tight  Allows user to avoid a small fraction over a tick using another tick.\n \\param min_ticks  Minimum number of major ticks.\n \\param steps Round up and down to 2, 4, 6, 8, 10, or 5, 10 or 2, 5, 10 systems.\n*/\n\ntemplate <typename Iter>\nvoid scale_axis(\n  Iter begin, // Iterator into begin in STL container.\n  Iter end, // Iterator into end in STL container.\n  // (not necessarily ordered by size, so will find min and max).\n  double* axis_min_value, // Computed minimum value for the axis, updated by scale_axis.\n  double* axis_max_value, //  Computed maximum value for the axis, updated by scale_axis.\n  double* axis_tick_increment, //  Computed tick increment for the axis, updated by scale_axis.\n  int* auto_ticks, // Computed number of ticks, updated by scale_axis.\n  bool check_limits, // Whether to check all values for infinity, NaN etc.\n  double autoscale_plusminus, // Mutiplier of uncertainty or standard deviations to allow for confidence ellipses.\n  bool origin = false, // Do not include the origin unless the range min_value <= 0 <= max_value.\n  double tight = 0., // tightest - fraction of 'overrun' allowed before another tick used.\n  // for visual effect up to about 0.001 might suit a 1000 pixel wide image,\n  // allowing values just 1 pixel over the tick to be shown.\n  int min_ticks = 6, // Minimum number of major ticks.\n  int steps = 0 // 0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n);\n\n/* Scale axis using all the 1D data in an STL container.\n  Scale axis using an \\b entire Container data-series, usually to plot.\n  (not necessarily ordered, so will find min and max).\n  \\tparam C an STL container: array, vector ...\n  \\param container STL container, usually of a data-series.\n  \\param axis_min_value Computed minimum value for the X-axis, updated by scale_axis.\n  \\param axis_max_value Computed minimum value for the X-axis, updated by scale_axis.\n  \\param axis_tick_increment Computed tick increment for the axis, updated by scale_axis.\n  \\param auto_ticks Computed number of ticks, updated by scale_axis.\n  \\param check_limits Whether to check all values for infinity, NaN etc.\n  \\param autoscale_plusminus Multiplier of uncertainty or standard deviations to allow for confidence ellipses.\n  \\param origin Do not include the origin unless the range min_value <= 0 <= max_value.\n  \\param tight fraction of 'overrun' allowed before another tick used. For visual effect up to about 0.001 might suit a 1000 pixel wide image, allowing values just 1 pixel over the tick to be shown.\n  \\param min_ticks Minimum number of major ticks.\n  \\param steps  0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n*/\n template <typename C>\n void scale_axis(\n   const C& container, // STL container, usually of a data-series.\n   double* axis_min_value, // Computed minimum value for the axis, updated by @c scale_axis.\n   double* axis_max_value,  // Computed maximum value for the axis, updated by @c scale_axis.\n   double* axis_tick_increment, //  Computed tick increment for the axis, updated by @c scale_axis.\n   int* auto_ticks, // Computed number of ticks, updated by @c scale_axis.\n   bool check_limits, // Whether to check all values for infinity, NaN etc.\n   double autoscale_plusminus = 3., // Multiplier of uncertainty or standard deviations to allow for confidence ellipses.\n   bool origin = false, // do not include the origin unless the range min_value <= 0 <= max_value.\n   double tight = 0., // tightest - fraction of 'overrun' allowed before another tick used.\n   //! for visual effect up to about 0.001 might suit a 1000 pixel wide image,\n   //! allowing values just 1 pixel over the tick to be shown.\n   int min_ticks = 6, // Minimum number of major ticks.\n   int steps = 0 // 0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n);\n\n/* Scale X and Y axis using T a 2D STL container: array of pairs, vector of pairs, list of pairs, map ...\n  \\tparam C STL container of 2D pairs of X and Y.\n\n  \\param container data-series to plot - entire 2D container (not necessarily ordered, so will find min and max)..\n  \\param x_axis_min_value Computed minimum value for the X-axis, updated by @c scale_axis.\n  \\param x_axis_max_value Computed minimum value for the X-axis, updated by @c scale_axis.\n  \\param x_axis_tick_increment Computed tick increment for the axis, updated @c by scale_axis.\n  \\param x_auto_ticks Computed number of ticks, updated by scale_axis.\n  \\param y_axis_min_value  Computed minimum value for the Y-axis, updated by @c scale_axis.\n  \\param y_axis_max_value  Computed maximum value for the Y-axis, updated by @c scale_axis.\n  \\param y_axis_tick_increment Updated with Y axis tick increment.\n  \\param y_auto_ticks Computed number of Y-axis ticks, updated by scale_axis.\n  \\param check_limits Whether to check all values for infinity, NaN etc.\n  \\param autoscale_plusminus Multiplier of uncertainty or standard deviations to allow for confidence ellipses.\n  \\param x_origin Do not include the origin unless the range min_value <= 0 <= max_value.\n  \\param x_tight fraction of 'overrun' allowed before another tick used. For visual effect up to about 0.001 might suit a 1000 pixel wide image, allowing values just 1 pixel over the tick to be shown.\n  \\param x_min_ticks Minimum number of X-axis major ticks.\n  \\param x_steps  0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n  \\param y_origin  Do not include the origin unless the range min_value <= 0 <= max_value.\n  \\param y_tight fraction of 'overrun' allowed before another tick used. For visual effect up to about 0.001 might suit a 1000 pixel wide image, allowing values just 1 pixel over the tick to be shown.\n  \\param y_steps  0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n  \\param y_min_ticks Minimum number of Y axis major ticks.\n*/\ntemplate <typename C>\nvoid scale_axis(\n  const C& container, // data-series to plot - \\b entire 2D container (not necessarily ordered, so will find min and max).\n  double* x_axis_min_value, //  \\param x_axis_min_value Computed minimum value for the X-axis, updated by scale_axis.\n  double* x_axis_max_value,  //   \\param x_axis_max_value Computed minimum value for the X-axis, updated by scale_axis.\n  double* x_axis_tick_increment, // Updated with X axis tick increment.\n  int* x_auto_ticks,   // Computed number of X axis ticks, updated by @c scale_axis.\n  double* y_axis_min_value, // Computed minimum value for the Y-axis, updated by @c scale_axis.\n  double* y_axis_max_value,  // Computed maximum value for the Y-axis, updated by @c scale_axis.\n  double* y_axis_tick_increment, // Computed Y axis tick increment. updated by @c scale_axis.\n  int* y_auto_ticks,  // Computed number of Y-axis ticks, updated by @c scale_axis.\n  bool check_limits = true, // Whether to check all values for infinity, NaN etc.\n  double autoscale_plusminus = 3., // Mutiplier of uncertainty or standard deviations to allow fo confidence ellipses.\n  bool x_origin = false, // do not include the origin unless the range min_value <= 0 <= max_value.\n  double x_tight = 0., // tightest - fraction of 'overrun' allowed before another tick used.\n  //! for visual effect up to about 0.001 might suit a 1000 pixel wide image,\n  //! allowing values just 1 pixel over the tick to be shown.\n  int x_min_ticks = 6, // Minimum number of major ticks.\n  int x_steps = 0, // 0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n  bool y_origin = false, // do not include the origin unless the range min_value <= 0 <= max_value.\n  double y_tight = 0., // tightest - fraction of 'overrun' allowed before another tick used.\n  // for visual effect up to about 0.001 might suit a 1000 pixel wide image,\n  // allowing values just 1 pixel over the tick to be shown.\n  int y_min_ticks = 6, // Minimum number of major ticks.\n  int y_steps = 0 // 0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n);\n\n//  End forward scale_axis and roundup and round down declarations.\n\n// All use:\nnamespace detail\n{ // Declaration of implementation with default parameters.\n//* \\cond DETAIL\nvoid scale_axis_impl(double min_value, double max_value, // Scale axis from input range min & max.\n               double* axis_min_value,  double* axis_max_value, double* axis_tick_increment,\n               int* auto_ticks, // All 4 updated.\n               // NO check_limits parameter in this version.\n               bool origin = false, // Do not include the origin unless the range min_value <= 0 <= max_value.\n               double tight = 0., // tightest - fraction of 'overrun' allowed before another tick used.\n               // for visual effect up to about 0.001 might suit a 1000 pixel wide image,\n               // allowing values just 1 pixel over the tick to be shown.\n               int min_ticks = 6, // Minimum number of major ticks.\n               int steps = 0); // 0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n//! \\endcond // DETAIL\n} // namespace detail\n\n// End of declarations.\n\n// Definitions of scale_axis and roundup and round down.\n\n /*! \\brief Inspect values to find min and max.\n     \\details Inspect all values between begin and (one before) end to work out and update min and max.\n       Similar to boost::minmax_element, but ignoring at 'limit': non-finite, +-infinity, max & min, & NaN).\n       If can't find a max and a min, then throw a runtime_error exception.\n    \\tparam iter InputIterator into STL container.\n    \\param begin Iterator to chosen first item in container.\n    \\param end Iterator to chosen last item in container.\n    \\param min Updated with Minimum value found (not 'at limit').\n    \\param max Updated with Maximum value found (not 'at limit').\n    \\return number of normal values (not 'at limit' neither too big, NaN nor infinite).\n  */\ntemplate <typename Iter>\nint mnmx(\n  Iter begin, // iterator to chosen first item in container.\n  Iter end,  // iterator to chosen last item in container.\n  double* min, // Updated with Minimum value found (not 'at limit').\n  double* max) // Updated with Maximum value found (not 'at limit').\n{\n  *max = std::numeric_limits<double>::quiet_NaN();\n  *min = std::numeric_limits<double>::quiet_NaN();\n  using boost::svg::detail::is_limit; // Either x and/or y not a proper data value.\n  int goods = 0; // Count of values within limits.\n  int limits = 0;\n  Iter pos = begin;\n  using boost::quan::value_of;\n  while(pos != end && is_limit(value_of(*pos)))\n  { // Count any limits before the first 'good' (FP normal) value.\n    limits++;\n    pos++;\n  }\n  if (pos == end)\n  { // ALL values are at limit!\n      throw std::runtime_error(\"Autoscale could not find any useful values to scale axis!\");\n    // std::cout << \"all values at limit (NaN or infinity)!\" << std::endl;\n    // min and max are both == NaN\n  }\n  else\n  {\n    using boost::quan::value_of;\n    double x = value_of(*pos);\n    *max = x;\n    *min = x;\n    //std::cout << \"Initial min & max \" << x << std::endl;\n    pos++;\n    goods++;\n    while(pos != end)\n    {\n      if (!is_limit(value_of(*pos)))\n      { // x is finite.\n        x = value_of(*pos);\n        if (x > *max)\n        {\n          *max = x;\n        }\n        if (x < *min)\n        {\n          *min = x;\n        }\n        goods++;\n        //std::cout << goods << \" goods, \" << x << std::endl;\n     } // if finite\n      else\n      { // If x not finite, then the y value won't be plotted.\n        std::cout << \"limit value: \" << *pos  << std::endl;\n        limits++;\n      }\n      ++pos;\n    } // while\n    //std::cout << \"min \" << *min << \", max \" << *max << std::endl; //\n    //std::cout << \"limits \" << limits << std::endl;\n  }\n  if (goods < 2)\n  {\n    throw std::runtime_error(\"Autoscale could not find useful min & max to scale axis!\");\n  }\n  return goods; // If goods < 2,\n} // template <typename iter>int mnmx((iter begin, iter end, double* min, double* max)\n\n/*! Scale axis and update min and max axis values, and tick increment and number of ticks.\n\n   \\param min_value Scale axis from explicit input range minimum.\n   \\param max_value Scale axis from explicit input range maximum.\n\n   \\param axis_min_value Computed minimum value for the axis, updated by scale_axis.\n   \\param axis_max_value Computed maximum value for the axis, updated by scale_axis.\n   \\param axis_tick_increment  Computed tick increment for the axis, updated by scale_axis.\n   \\param auto_ticks Computed number of ticks, updated by scale_axis.\n   \\param origin If false, do not include the origin unless the range @c min_value to @c max_value includes zero.\n   \\param tight Fraction of overrun allowed before another tick used. For a good visual effect, up to about 0.001 might suit a 1000 pixel wide image, allowing values just 1 pixel over the tick to be shown.\n   \\param min_ticks Minimum number of major ticks.\n   \\param steps 0, or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n*/\nvoid scale_axis(\n   double min_value, // Scale axis from explicit input range minimum.\n   double max_value, // Scale axis from input range maximum.\n   double* axis_min_value, // Computed minimum value for the axis, updated by @c scale_axis.\n   double* axis_max_value, //  Computed maximum value for the axis, updated by @c scale_axis.\n   double* axis_tick_increment, //  Computed tick increment for the axis, updated by scale_axis.\n   int* auto_ticks, // Computed number of ticks, updated by scale_axis.\n   //  NO check_limits parameter.\n   bool origin, // = false, // Do not include the origin unless the range min_value <= 0 <= max_value.\n   double tight, // = 0., // Tightness - fraction of 'overrun' allowed before another tick used.\n   // for visual effect up to about 0.001 might suit a 1000 pixel wide image,\n   // allowing values just 1 pixel over the tick to be shown.\n   int min_ticks, //= 6, // Minimum number of major ticks.\n   int steps // = 0 // Round up and down to 2, 4, 6, 8, 10, or 5, 10 or 2, 5, 10 systems.\n)\n{\n  detail::scale_axis_impl(min_value, max_value,\n    axis_min_value, axis_max_value, axis_tick_increment, auto_ticks, // All 4 updated.\n    origin, tight, min_ticks, steps); // Display range.\n} //\n\n/*! Scale axis function to define axis marker ticks based on min & max parameters values (handling uncertainty).\n\n  \\param min_value Scale axis from explicit input minimum.\n  \\param max_value Scale axis from explicit input maximum.\n\n  \\param axis_min_value Computed minimum value for the axis, updated by scale_axis.\n  \\param axis_max_value Computed maximum value for the axis, updated by scale_axis.\n  \\param axis_tick_increment Computed tick increment for the axis, updated by scale_axis.\n  \\param auto_ticks  Computed number of ticks, updated by scale_axis.\n  \\param check_limits  If true then check all values for infinity, NaN etc.\n  \\param autoscale_plusminus Multiplier of uncertainty or standard deviations to allow for confidence ellipses.\n  \\param origin If true, ensures that zero is a tick value.\n  \\param tight  Allows user to avoid a small fraction over a tick using another tick.\n  \\param min_ticks  Minimum number of major ticks.\n  \\param steps Round up and down to 2, 4, 6, 8, 10, or 5, 10 or 2, 5, 10 systems.\n */\nvoid scale_axis(\n   double min_value, // Updated with Minimum value found.\n   double max_value, // Updated with Maximum value found.\n   double* axis_min_value, // Minimum value for the axis, updated by scale_axis.\n   double* axis_max_value, //  Maximum value for the axis, updated by scale_axis.\n   double* axis_tick_increment, //  Tick increment for the axis, updated by scale_axis.\n   int* auto_ticks,  // Updated with number of ticks.\n   bool check_limits, // Whether to check all values for infinity, NaN etc.\n   double autoscale_plusminus, // Multiplier of uncertainty or standard deviations to allow for confidence ellipses.\n   bool origin, // If true, ensures that zero is a tick value.\n   double tight, // Allows user to avoid a small fraction over a tick using another tick.\n   int min_ticks, // Minimum number of ticks.\n   int steps) // Round up and down to 2, 4, 6, 8, 10, or 5, 10, or 2, 5, 10 major ticks multiples.\n{\n  // Must assume max and min are OK (can't ignore limit values).\n  // If either at limit then will be caught and exception thrown later by x_range.\n  // So deliberately ignore check_limits parameter & and autoscale_plusminus & suppress any warnings.\n  detail::scale_axis_impl(min_value, max_value,\n    axis_min_value, axis_max_value, axis_tick_increment, auto_ticks, // All 4 updated.\n    origin, tight, min_ticks, steps); // Display range.\n  check_limits = false;\n  autoscale_plusminus = 1.96;\n}\n\n /*! Scale axis from data-series (usually to plot), perhaps only part of container.\n\n   \\tparam Iter Type of interator into STL container type: @c array, @c vector ...\n\n   \\param begin First item in container to use to calculate autoscale mimimum or maximum.\n   \\param end Last item in container to use to calculate autoscale mimimum or maximum.\n   \\param axis_min_value Computed minimum value for the axis, updated by scale_axis.\n   \\param axis_max_value Computed maximum value for the axis, updated by scale_axis.\n   \\param axis_tick_increment  Computed tick increment for the axis, updated by scale_axis.\n   \\param auto_ticks Computed number of ticks, updated by scale_axis.\n   \\param check_limits Whether to check all values for infinity, NaN etc.\n   \\param autoscale_plusminus Multiplier of uncertainty or standard deviations to allow for confidence ellipses.\n   \\param origin If false, do not include the origin unless the range min_value <= 0 <= max_value.\n   \\param tight fraction of 'overrun' allowed before another tick used. For visual effect up to about 0.001 might suit a 1000 pixel wide image, allowing values just 1 pixel over the tick to be shown.\n   \\param min_ticks Minimum number of major ticks.\n   \\param steps 0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n */\ntemplate <typename Iter>\nvoid scale_axis(\n   Iter begin, // iterators into begin in STL container.\n   Iter end, // iterators into end in STL container.\n   // (not necessarily ordered by size, so will find min and max).\n   double* axis_min_value, // Computed minimum value for the axis, updated by scale_axis.\n   double* axis_max_value, //  Computed maximum value for the axis, updated by scale_axis.\n   double* axis_tick_increment, //  Computed tick increment for the axis, updated by scale_axis.\n   int* auto_ticks, // Computed number of ticks, updated by scale_axis.\n   bool check_limits, // Whether to check all values for infinity, NaN etc.\n   double autoscale_plusminus, // Mutiplier of uncertainty or standard deviations to allow fo confidence ellipses.\n   bool origin, // = false, // Do not include the origin unless the range min_value <= 0 <= max_value.\n   double tight, // = 0., // tightest - fraction of 'overrun' allowed before another tick used.\n   // for visual effect up to about 0.001 might suit a 1000 pixel wide image,\n   // allowing values just 1 pixel over the tick to be shown.\n   int min_ticks, // = 6, // Minimum number of major ticks.\n   int steps) // = 0) // 0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n{\n  double x_min;\n  double x_max;\n  if (!check_limits)\n  { // minmax_element is efficient for maps because can use knowledge of being sorted,\n    // BUT only if it can be assumed that no values are 'at limits',\n    // infinity, NaN, max_value, min_value, denorm_min.\n    // Otherwise it is necessary to inspect all values individually.\n    std::pair<Iter, Iter> result = boost::minmax_element(begin, end); // min & max\n    // scale_axis (not check_limits version) forward declaration to ensure compiler finds right version.\n     x_min = *(result.first);\n     x_max = *(result.second);\n  }\n  else\n  { // Must check limits.\n    int good = mnmx(begin, end, &x_min, &x_max);\n    if (good < 2)\n    {\n      throw std::runtime_error(\"Autoscale could not find useful min & max to scale axis!\");\n    }\n    detail::scale_axis_impl(x_min, x_max,\n    axis_min_value, axis_max_value, axis_tick_increment, auto_ticks, // All 4 updated.\n      origin, tight, min_ticks, steps); // Display range.\n  }\n  autoscale_plusminus = 1.96;\n} // template <typename iter> void scale_axis(iter begin, iter end, ...\n\n/*!\n  \\brief Scale axis using an \\b entire Container of a data-series, usually to plot (not necessarily ordered, so will find minimum and maximum).\n\n  \\tparam C STL container type: @c array, @c vector ...\n\n  \\param container STL container, usually of a data-series.\n  \\param axis_min_value Computed minimum value for the axis, updated by scale_axis.\n  \\param axis_max_value Computed maximum value for the axis, updated by scale_axis.\n  \\param axis_tick_increment  Computed tick increment for the axis, updated by scale_axis.\n  \\param auto_ticks Computed number of ticks, updated by scale_axis.\n  \\param check_limits Whether to check all values for infinity, NaN etc.\n  \\param autoscale_plusminus Multiplier of uncertainty or standard deviations to allow for confidence ellipses.\n  \\param origin If false, do not include the origin unless the range min_value \\<= 0 \\<= max_value.\n  \\param tight fraction of overrun allowed before another tick used. For visual effect up to about 0.001 might suit a 1000 pixel wide image, allowing values just 1 pixel over the tick to be shown.\n  \\param min_ticks Minimum number of major ticks.\n  \\param steps 0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n*/\ntemplate <class C>\nvoid scale_axis(\n  const C& container, // STL container, usually of a data-series.\n  double* axis_min_value, // Computed minimum value for the axis, updated by scale_axis.\n  double* axis_max_value,  // Computed maximum value for the axis, updated by scale_axis.\n  double* axis_tick_increment, //  Computed tick increment for the axis, updated by scale_axis.\n  int* auto_ticks, // Computed number of ticks, updated by scale_axis.\n  bool check_limits, // Whether to check all values for infinity, NaN etc.\n  double autoscale_plusminus, // = 3., Multiplier of uncertainty or standard deviations to allow for confidence ellipses.\n  bool origin, // = false, // do not include the origin unless the range min_value to max_value includes zero.\n  double tight, // = 0., // tightest - fraction of overrun allowed before another tick used.\n  // For a good visual effect, up to about 0.001 might suit a 1000 pixel wide image,\n  // allowing values just 1 pixel over the tick to be shown.\n  int min_ticks, // = 6, // Minimum number of major ticks.\n  int steps) // = 0) // 0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n{ // s\n  double x_min;\n  double x_max;\n  if (!check_limits)\n  {\n    //std::pair<T::iterator, T::iterator> result = boost::minmax_element(container.begin(), container.end());\n    std::pair<typename C::const_iterator, typename C::const_iterator> result = boost::minmax_element(container.begin(), container.end());\n    // minmax_element is efficient because can use knowledge of being sorted,\n    // BUT only if it can be assumed that no values are 'at limits',\n    // infinity, NaN, max_value, min_value, denorm_min.\n    using boost::quan::value_of;\n    x_min = value_of(*(result.first));\n    x_max = value_of(*(result.second));\n  }\n  else\n  { // It is necessary to inspect all values individually.\n    // std::cout << container.size() << \" values.\" << std::endl;\n    // Work out min and max, ignoring non-finite, +-infinity, max & min, & NaN).\n    // If can't find a max and a min, then will throw exception.\n    int good = mnmx(container.begin(), container.end(), &x_min, &x_max);\n    if (good < 2)\n    {\n      throw std::runtime_error(\"Autoscale could not find useful min & max values to scale the X axis!\");\n    }\n    // std::cout << \"x_min \" << x_min << \", x_max \" << x_max << std::endl; //\n  }\n\n  detail::scale_axis_impl(x_min, x_max,\n    axis_min_value, axis_max_value, axis_tick_increment, auto_ticks,\n    origin, tight, min_ticks, steps);\n  autoscale_plusminus = 3.;\n\n} // template <class C> int scale_axis  C an STL container: array, vector ...\n\n/*! Scale X and Y axis using a 2D STL container: @c std::array of @c std::pairs, @c std::vector of @c std::pairs, ...\n\n  \\tparam C STL container holding 2D pairs of X and Y.\n\n  \\param container data-series to plot - entire 2D container.\n  \\param x_axis_min_value Computed minimum value for the X-axis, updated by scale_axis.\n  \\param x_axis_max_value Computed minimum value for the X-axis, updated by scale_axis.\n  \\param x_axis_tick_increment Computed tick increment for the axis, updated by scale_axis.\n  \\param x_auto_ticks Computed number of ticks, updated by scale_axis.\n  \\param y_axis_min_value  Computed minimum value for the Y-axis, updated by scale_axis.\n  \\param y_axis_max_value  Computed maximum value for the Y-axis, updated by scale_axis.\n  \\param y_axis_tick_increment Updated with Y-axis tick increment.\n  \\param y_auto_ticks Computed number of Y-axis ticks, updated by scale_axis.\n  \\param check_limits Whether to check all values for infinity, NaN etc.\n  \\param autoscale_plusminus Multiplier of uncertainty or standard deviations to allow for confidence ellipses.\n  \\param x_origin Do not include the origin unless the range min_value <= 0 <= max_value.\n  \\param x_tight Fraction of 'overrun' allowed before another tick used. For visual effect up to about 0.001 might suit a 1000 pixel wide image, allowing values just 1 pixel over the tick to be shown.\n  \\param x_min_ticks Minimum number of X-axis major ticks.\n  \\param x_steps  0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n  \\param y_origin Do not include the origin unless the range min_value to max_value contains zero.\n  \\param y_tight Fraction of 'overrun' allowed before another tick used. For visual effect up to about 0.001 might suit a 1000 pixel wide image, allowing values just 1 pixel over the tick to be shown.\n  \\param y_min_ticks Minimum number of Y axis major ticks.\n  \\param y_steps 0, or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n*/\ntemplate <class C>\nvoid scale_axis(\n  const C& container, // data-series to plot - \\b entire 2D container (not necessarily ordered, so will find min and max).\n  double* x_axis_min_value, // Computed minimum value for the X-axis, updated by scale_axis.\n  double* x_axis_max_value,  // Computed minimum value for the X-axis, updated by scale_axis.\n  double* x_axis_tick_increment, // Updated with X axis tick increment.\n  int* x_auto_ticks,   // Computed number of X axis ticks, updated by scale_axis.\n  double* y_axis_min_value, // Computed minimum value for the Y-axis, updated by scale_axis.\n  double* y_axis_max_value,  // Computed maximum value for the Y-axis, updated by scale_axis.\n  double* y_axis_tick_increment, // Updated with Y axis tick increment.\n  int* y_auto_ticks,  // Computed number of Y-axis ticks, updated by scale_axis.\n  bool check_limits, // = true, // Whether to check all values for infinity, NaN etc.\n  double autoscale_plusminus, // = 3., // Mutiplier of uncertainty or standard deviations to allow of confidence ellipses.\n  bool x_origin, // = false, // do not include the origin unless the range min_value <= 0 <= max_value.\n  double x_tight, // = 0., // tightest - fraction of 'overrun' allowed before another tick used.\n  // for visual effect up to about 0.001 might suit a 1000 pixel wide image,\n  // allowing values just 1 pixel over the tick to be shown.\n  int x_min_ticks, // = 6, // Minimum number of major ticks.\n  int x_steps, // = 0, // 0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n  bool y_origin, // = false, // do not include the origin unless the range min_value <= 0 <= max_value.\n  double y_tight, // = 0., // tightest - fraction of 'overrun' allowed before another tick used.\n  // for visual effect up to about 0.001 might suit a 1000 pixel wide image,\n  // allowing values just 1 pixel over the tick to be shown.\n  int y_min_ticks, // = 6, // Minimum number of major ticks.\n  int y_steps) // = 0) // 0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n{ /* Scale X and Y axis using T a 2D STL container: array of pairs, vector of pairs, list of pairs, map ...\n      container data-series to plot - entire 2D container.\n    */\n  double x_max = std::numeric_limits<double>::quiet_NaN();\n  double x_min = std::numeric_limits<double>::quiet_NaN();\n  double y_max = std::numeric_limits<double>::quiet_NaN();\n  double y_min = std::numeric_limits<double>::quiet_NaN();\n\n  if (!check_limits)  // TODO my_plot.autoscale_check_limits(false);\n  { // BUT only if it can be assumed that no values are 'at limits',\n    // infinity, NaN, max_value, min_value, denorm_min.\n    // minmax_element is efficient for maps because it can use knowledge of all maps being sorted,\n    // And also sadly it doesn't work right - Y minimum is wrong!  // TODO ??\n\n    std::pair<typename C::const_iterator, typename C::const_iterator> result\n      = boost::minmax_element(container.begin(), container.end());\n    using boost::quan::values_of;\n    std::pair<double, double> px = values_of(*result.first); // X min & X max.\n    std::pair<double, double> py = values_of(*result.second); // Y min & Y max.\n    x_min = px.first;\n    x_max = py.first;\n    // x are OK, but Y are only those corresponding to those X, not min and max.,\n    // so still need to iterate through the Y to find y min and y max.\n    //y_min = px.second;\n    //y_max = py.second;\n    typename C::const_iterator pos = container.begin();\n    if (pos == container.end())\n    {\n      throw std::runtime_error(\"SVG_plot Autoscale could not find any values to scale axes!\");\n    }\n    using boost::quan::value_of;\n    double y = value_of(pos->second);\n    using boost::quan::unc_of;\n    double yu = unc_of(pos->second) * autoscale_plusminus;\n    y_max = y + yu;\n    y_min = y - yu;\n    while(pos != container.end())\n    {\n      y = value_of(pos->second);\n      yu = unc_of(pos->second) * autoscale_plusminus;\n      if (y + yu > y_max)\n      {\n        y_max = y + yu;\n      }\n      if (y - yu < y_min)\n      {\n        y_min = y - yu;\n      }\n      pos++;\n    }\n    std::cout << \"SVG_plot Autoscale warning (No limits checks):\"\n                 \"x_min = \" << x_min\n            << \", x_max = \" << x_max\n            << \", y_min = \" << y_min\n            << \", y_max = \" << y_max << std::endl;\n  }\n  else\n  { // Otherwise it is necessary to inspect all values individually.\n    // It seems that X and Y need to be examined in pairs, so sadly, we can't use:\n    // int good_x = mnmx(container.begin(), container.end(), &x_min, &x_max);\n    // or\n    // int good_y = mnmx(container.begin(), container.end(), &y_min, &y_max);\n\n    // Work out min and max, ignoring non-finite (+-infinity & NaNs).\n    using boost::svg::detail::pair_is_limit; // Either x and/or y is not a proper data value.\n    int goods = 0; // Count of values where both X and Y are normal (within limits).\n    int limits = 0;// Count of values where both X and Y are at limits (not normal).\n    typename C::const_iterator pos = container.begin();\n    while(pos != container.end() && pair_is_limit(*pos))\n    { // Count any limits before the first good.\n      limits++;\n      pos++;\n    }\n    if (pos == container.end())\n    { // ALL values are at limit!\n      //std::cout << \"all values at limit\" << std::endl;\n      throw std::runtime_error(\"Autoscale could not find any useful values to scale axes!\");\n    }\n    else\n    {\n      using boost::quan::value_of;\n      double x = value_of(pos->first);\n      using boost::quan::unc_of;\n      double xu = unc_of(pos->first) * autoscale_plusminus;\n      x_max = x + xu;\n      x_min = x - xu;\n      double y = value_of(pos->second);\n      double yu = unc_of(pos->second) * autoscale_plusminus;\n      y_max = y + yu;\n      y_min = y - yu;\n      //std::cout << \"Initial min & max \" << x << \"+-\" << xu << \" = \" << x_min << \" to \" << x_max << \", \" << y << \"+-\" << yu << \"=\" <<y_min << \" to \" << y_max << std::endl;\n      pos++;\n      goods++;\n      while(pos != container.end())\n      {\n        if (!pair_is_limit(*pos))\n        { // Either x and/or y are finite.\n          x = value_of(pos->first);\n          xu = unc_of(pos->first) * autoscale_plusminus;\n          if (x + xu > x_max)\n          {\n            x_max = x + xu;\n          }\n          if (x - xu < x_min)\n          {\n            x_min = x - xu;\n          }\n          y = value_of(pos->second);\n          yu = unc_of(pos->second) * autoscale_plusminus;\n          if (y + yu > y_max)\n          {\n            y_max = y + yu;\n          }\n          if (y - yu < y_min)\n          {\n            y_min = y - yu;\n          }\n          //std::cout << \"min & max \" << x << \"+-\" << xu << \" = \" << x_min << \" to \" << x_max << \", \" << y << \"+-\" << yu << \"=\" <<y_min << \" to \" << y_max << std::endl;\n          goods++;\n          // std::cout << goods << \" goods, \" << x << ' ' << y << std::endl;\n       } // if finite\n        else\n        { // If either are not finite, then neither useful for autoscaling.\n          // If x not finite, then the y value won't be plotted.\n          // If y value not finite, then it will be 'off limits'.\n          // std::cout << \"limit value: \" << pos->first << ' ' << pos->second  << std::endl;\n          limits++;\n        }\n        ++pos;\n      } // while\n      std::cout << \"Checked: x_min \" << x_min << \", x_max \" << x_max << \", y_min \" << y_min << \", y_max \" << y_max << \", \" << goods << \" 'good' values, \" << limits << \" values at limits.\"<< std::endl;\n    }\n  }\n  detail::scale_axis_impl(x_min, x_max,\n    x_axis_min_value, x_axis_max_value, x_axis_tick_increment, x_auto_ticks,\n    x_origin, x_tight, x_min_ticks, x_steps);\n\n  detail::scale_axis_impl(y_min, y_max,\n    y_axis_min_value, y_axis_max_value, y_axis_tick_increment, y_auto_ticks,\n    y_origin, y_tight, y_min_ticks, y_steps);\n\n} // template <class T> int scale_axis  T an STL container: array, vector ...\n\n// Above versions all use the scale_axis_impl implementation below that does the real scaling work.\nnamespace detail\n{ // Definition of implementation with default parameters.\n//! @cond DETAIL\n\nvoid scale_axis_impl(\n  double min_value,\n  double max_value, // Scale axis from Input range min & max.\n  double* axis_min_value,\n  double* axis_max_value,\n  double* axis_tick_increment,\n  int* auto_ticks, // All 4 updated.\n               // NO check_limits parameter in this version.\n  bool origin, // = false, // Do not include the origin unless the range min_value <= 0 <= max_value.\n  double tight, // = 0., // tightest - fraction of 'overrun' allowed before another tick used.\n               // for visual effect up to about 0.001 might suit a 1000 pixel wide image,\n               // allowing values just 1 pixel over the tick to be shown.\n  int min_ticks, // = 6, // Minimum number of major ticks.\n  int steps) // = 0) // 0,  or 2 for 2, 4, 6, 8, 10, 5 for 1, 5, 10, or 10 (2, 5, 10).\n{\n  int ticks = -1; // Negative to warn of 'bad' value.\n  double test_max;\n  double test_min;\n  double test_increment;\n  switch (steps)\n  { // Optionally expand the range by rounding actual max and min values up and down.\n  case 0 :\n    break; // No steps.\n  case 10 :\n    max_value = roundup10(max_value);\n    min_value = rounddown10(min_value);\n    break;\n  case 5 :\n    max_value = roundup5(max_value);\n    min_value = rounddown5(min_value);\n    break;\n  case 2 :\n    max_value = roundup2(max_value);\n    min_value = rounddown2(min_value);\n    break;\n  default:\n    throw std::domain_error(\"Unimplemented steps!\");\n  } // switch\n  double range = max_value - min_value;  // range of data.\n\n  smallest<> is_small(1000. * (std::numeric_limits<double>::min)()); // 1000 * min value\n  close_to<> is_near_100eps(100. * (std::numeric_limits<double>::epsilon)()); // 100 * epsilon\n\n  if ((tight < 0.) || tight > 1.)\n  { // Tight can't be negative and > 1 is very likely a mistake, 0.01 = 1% more reasonable.\n    throw std::domain_error(\"tight not in range 0 to 1 !\");\n  }\n\n  using std::isfinite;\n  if(!(isfinite)(min_value))\n  {\n    throw std::domain_error(\"min_value not finite!\");\n  }\n  if(!(isfinite)(max_value))\n  {\n    throw std::domain_error(\"max_value not finite!\");\n  }\n  if (origin == true)\n  { // Ensure the axis includes zero.\n    if (min_value > 0.)\n    { // All positive case.\n      min_value = 0.;\n    }\n    else if(max_value < 0.)\n    { // All negative case.\n      max_value = 0.;\n    }\n  } // origin\n\n  if (min_value > max_value)\n  { // max and min are transposed!\n    throw std::domain_error(\"min > max!\");\n  }\n  else if (is_small(range)\n    // range <= 1000. * std::numeric_limits<double>::min()) // Absolute range > ~1e-308 * 1000 ~= 1e-305\n    // Range has already been checked to be > 0.\n    // This checks for range too near to zero to be useful.\n    // is_small is similar to Boost.Test check_is_small\n\n    || is_near_100eps(max_value, min_value)\n\n    //|| (range <= 100. * std::numeric_limits<double>::epsilon() * abs(min_value))\n    // This checks the relative range is not too near to epsilon to be useful.\n    // Knuth Vol II, avoiding over and underflow, as used in Boost.Test close_at_tolerance.\n    )\n  { // Factor of 1000 is to ensure range is more than a few epsilon relative wide.\n    // Special cases of max ~== min values *and* exactly max == min (including == 0).\n    // This could be two or more duplicate (repeat) measurements on x or y axis,\n    // or only a modest number of epsilons apart even,\n    // so it not necessarily an error, but some special handling is required.\n    // At what point does range become big enough to be plausible to provide axis max & min tick values?\n    // A few numeric_limits<double>::epsilon() only covers smallish compute errors.\n    // at least 1000 epsilon absolute seems more plausible, and relative to biggest?\n    // Return 3 ticks: -1, max==min==mid, and +1 ticks.\n    // But uncertain if this is best solution?\n\n    double mean = (min_value + max_value) /2;\n    test_increment = 1;\n    test_min = mean - test_increment;\n    test_max = mean + test_increment;\n\n    ticks = 3; // ticks - OK, but ticks == 3 warns that max_value ~== min_value.\n  }\n  else\n  { // Range is reasonably large, so\n    // compute candidate for increment - must be smaller than range, so divide by 10.\n    test_increment = std::pow(10., std::ceil(std::log10(std::abs<double>(range)/10.)));\n    // Must be a decimal multiple or decimal fraction,\n    // but is not necessarily exactly representable in floating-point format.\n    // Establish maximum axis scale value, using this increment.\n\n    test_max = (static_cast<long>(max_value / test_increment)) * test_increment;\n\n    if(test_max < max_value)\n    {\n      test_max += test_increment;\n    }\n    ticks = 1; // Must be 1 'extra' tick at the end.\n    // Establish minimum axis tick value by decrementing from test_max.\n    test_min = test_max;\n    do\n    {\n      ticks++;\n      test_min -= test_increment;\n    }\n    while (test_min > min_value); // min_value);\n\n    // Subtracting small values can screw up the scale limits,\n    // eg: if scale_axis is called with (min, max)=(0.01, 0.1),\n    // then the calculated scale is 1.0408E17 TO 0.05 BY 0.01,\n    // rather than 0, 0.05, 0.01.\n    // I suspect 1.e-10 is bigger than necessary?  related to std::numeric_limits<>::epsilon?\n    if(std::abs(test_min) < 1.E-14)\n    { // test_min is very near zero,\n      test_min = 0.; // so treat as exact zero to avoid risk of a switch to e format.\n    }\n    while(ticks < min_ticks)\n    {  // Adjust for too few tick marks by\n      test_increment /= 2.; // halving the increment.\n      // (divide by two should not cause trouble by being inexact).\n      ticks = static_cast<int>((test_max - test_min) / test_increment) +1;\n      if (steps == 0)\n      { // Remove any superfluous ticks above max and below min.\n        while((test_min + test_increment) <= min_value)\n        { // min_value is > 2nd from bottom tick,\n          test_min += test_increment;\n          ticks--; // so we can scrap the 1st bottom tick.\n        }\n        while((test_max - test_increment) >= max_value)\n        { // max_value is > top_but_one tick,\n          ticks--; // so ditch the top tick.\n          test_max -= test_increment;\n        }\n      }\n    } // while\n\n    if (tight > 0.)\n    { // Check that can't use a tick less at top or bottom.\n      double max_plus_margin = test_max - test_increment + test_increment * tight;\n      if (max_value < max_plus_margin)\n      { // max is too big, so remove top tick.\n        ticks -= 1;\n        test_max -= test_increment;\n      }\n\n      double min_plus_margin = test_min + test_increment - test_increment * tight;\n      if (min_value > min_plus_margin)\n      { // min is too small, so remove the bottom tick.\n        ticks -= 1;\n        test_min += test_increment;\n      }\n      // Check again to make quite sure can't reduce again.\n      max_plus_margin = test_max - test_increment + test_increment * tight;\n      if (max_value < max_plus_margin)\n      { // max is too big\n        ticks -= 1;\n        test_max -= test_increment;\n      }\n      min_plus_margin = test_min + test_increment - test_increment * tight;\n      if (min_value > min_plus_margin)\n      { // min is too small, so remove the bottom tick.\n        ticks -= 1;\n        test_min += test_increment;\n      }\n    } // if (tight != 0.)\n  } // range reasonable\n\n  // Pass computed min & max axis tick values back to caller.\n  *axis_min_value = test_min; //\n  *axis_max_value = test_max;\n  *axis_tick_increment = test_increment; // major_tick_interval.\n  *auto_ticks = ticks; // major ticks.\n} // scale_axis_impl\n\n//! @endcond // DETAIL\n\n} // namespace detail\n// Utility functions to display containers\n// and to find min and max values in containers.\n\ntemplate <typename T> // T an STL container: array, vector ...\nsize_t show(const T& container)\n{ //! Utility functions to display STL containers.\n  std::cout << container.size() << \" values in container: \";\n  for (typename T::const_iterator it = container.begin(); it != container.end(); it++)\n  {\n    std::cout << *it << ' ';\n  }\n  std::cout << std::endl;\n  return container.size();\n}// Container data-series to plot.\n\n// Pointer version is not needed - iterator version is used instead.\n\ntemplate <typename iter> // T an STL container: array, vector ...\nsize_t show(iter begin, iter end) // Iterators\n{ //! Utility function to display STL containers.\n  size_t count = 0;\n  while (begin != end)\n  {\n    count++;\n    std::cout << *begin << ' ';\n    ++begin;\n  }\n  std::cout << \": \" << count << \" values used.\";\n  std::cout << std::endl;\n  return count;\n}// Container data-series to plot.\n\ntemplate <typename T>\nsize_t show_all(const T& containers)\n{ //! Show all the containers values.\n  // \\tparam T an STL container: container of containers.\n  for (typename T::const_iterator it = containers.begin(); it != containers.end(); it++)\n  {\n    show(*it);\n  }\n  return containers.size();\n} // Container data-series to plot.\n\n  /*! Calculate minimum and maximum from data in a container.\n    \\param container Container data-series.\n    \\return minimum and maximum of an STL container as a @c std::pair.\n    \\tparam  T an STL container: array, vector, set, map ...\n  */\ntemplate <class T>\nstd::pair<double, double> range_mx(const T& container)\n{\n  std::pair<typename T::const_iterator, typename T::const_iterator> result\n    = boost::minmax_element(container.begin(), container.end());\n  std::pair<double, double> minmax;\n  minmax.first = *result.first;\n  minmax.second = *result.second;\n  return minmax;\n} // template <class T> range_mx\n\ntemplate <typename T> // T an STL container: array, vector, set, map ...\nstd::pair<double, double> range_all(const T& containers) // Container of STL containers of data-series.\n{ /*! \\return minimum and maximum of a container containing STL containers.\n      \\tparam T an STL container: array, vector, set, map ...\n  */\n  std::pair<double, double> minmax(\n    (std::numeric_limits<double>::max)(), (std::numeric_limits<double>::min)()\n  );\n  for (typename T::const_iterator it = containers.begin(); it != containers.end(); it++)\n  {\n    std::pair<double, double> mm = range_mx(*it); // Scale of this container.\n    minmax.first = (std::min)(mm.first, minmax.first); //\n    minmax.second = (std::max)(mm.second, minmax.second);\n  }\n  return minmax;\n} // template <class T> scale_all\n\n/*! Round up to nearest multiple of 10.\n  Decimal scaling steps, so value is 0.1, 0.2, 0.5, 1., 2., 5. or 1., 10., 20., 100. ...\n  \\return Rounded up value.\n*/\ndouble roundup10(double value)\n{\n  BOOST_MATH_STD_USING\n  smallest<> is_small(100. * (std::numeric_limits<double>::min)()); // 100 * min value.\n  if (is_small(value) )\n  { // Value very close to zero.\n    return 0.; // Just return zero.\n  }\n  bool is_neg = (value >= 0) ? false : true;\n  value = std::abs(value);\n\n  int order = int(floor(log10(value))); // 0 to 9.999, gives 0, 10 to 99.9 gives 2 ...\n  double scaled_value = value * pow(10., -order); // 0 to 9.99 is unchanged, 10 to 9.99 scaled down to 1. to 9.99\n  double pow10order = is_neg ? -pow(10., order) : pow(10., order); //  power of ten, signed.\n  if(scaled_value > 5.)\n  {\n    return 10. * pow10order;\n  }\n  else if(scaled_value > 2.)\n  {\n    return 5. * pow10order;\n  }\n  else if(scaled_value > 1.)\n  {\n    return  2. * pow10order;\n  }\n  else\n  {\n    return  1. * pow10order;\n  }\n} // double roundup10(double value)\n\n/*! Round down to nearest multiple of 10.\n  Decimal scaling steps, so value is 0.1, 0.2, 0.5, 1., 2., 5. or 1., 10., 20., 100. ...\n  \\return Rounded down value.\n*/\ndouble rounddown10(double value)\n{\n  BOOST_MATH_STD_USING\n\n  smallest<> is_small(100. * (std::numeric_limits<double>::min)()); // 100 * min value\n  if (is_small(value))\n  { // Value very close to zero.\n    return 0.; // Just return zero.\n  }\n  bool is_neg = (value >= 0) ? false : true;\n  value = std::abs(value);\n  int order = int(floor(log10(value))); // 0 to 9.999, gives 0, 10 to 99.9 gives 2 ...\n  double scaled_value = value * pow(10., -order); // 0 to 9.99 is unchanged, 10 to 9.99 scaled down to 1. to 9.99\n  double pow10order = is_neg ? -pow(10., order) : pow(10., order); //  power of ten, signed.\n\n  if(scaled_value <= 2.)\n  {\n    return 1. * pow10order;\n  }\n  else if(scaled_value <= 5.)\n  {\n    return 2. * pow10order;\n  }\n  else if(scaled_value <= 10.)\n  {\n    return 5. * pow10order;\n  }\n  else\n  {\n    return 10. * pow10order;\n  }\n} // double rounddown10(double value)\n\n/*! Semi-decimal scaling, so return 0.1, 0.5, 1, 5, 10, 50, 100 ...\n  \\return rounded up value.\n*/\ndouble roundup5(double value)\n{\n  BOOST_MATH_STD_USING\n\n  smallest<> is_small(100. * (std::numeric_limits<double>::min)()); // 100 * min value.\n  if (is_small(value) )\n  { // Value very close to zero.\n    return 0.; // Just return zero.\n  }\n  bool is_neg = (value >= 0) ? false : true;\n  value = std::abs(value);\n  int order = int(floor(log10(value))); // 0 to 9.999, gives 0, 10 to 99.9 gives 2 ...\n  double scaled_value = value * pow(10., -order); // 0 to 9.99 is unchanged, 10 to 9.99 scaled down to 1. to 9.99\n  double pow10order = is_neg ? -pow(10., order) : pow(10., order); //  power of ten, signed.\n\n  if(scaled_value > 5.)\n  { // Scale down to 1.\n    return 10. * pow10order;\n  }\n  else if(scaled_value > 1.)\n  { //\n    return 5. * pow10order;\n  }\n  else\n  { // is < 1\n  }\n  return 1. * pow10order;\n} // double roundup2(double value)\n\n/*! Semi-decimal scaling, so return 0.1, 0.5, 1, 5, 10, 50, 100 ...\n  \\return Rounded down value.\n*/\ndouble rounddown5(double value)\n{\n  BOOST_MATH_STD_USING\n\n  smallest<> is_small(100. * (std::numeric_limits<double>::min)()); // 100 * min value\n  if (is_small(value))\n  { // Value very close to zero.\n    return 0.; // Just return zero.\n  }\n  bool is_neg = (value >= 0) ? false : true;\n  value = std::abs(value);\n  int order = int(floor(log10(value))); // 0 to 9.999, gives 0, 10 to 99.9 gives 2 ...\n  double scaled_value = value * pow(10., -order); // 0 to 9.99 is unchanged, 10 to 9.99 scaled down to 1. to 9.99\n  double pow10order = is_neg ? -pow(10., order) : pow(10., order); //  power of ten, signed.\n\n  if(scaled_value < 2.)\n  { //\n    return 1. * pow10order;\n  }\n  else if(scaled_value < 10.)\n  { //\n    return 5. * pow10order;\n  }\n  else\n  { //\n    return 10. * pow10order;\n  }\n} // double rounddow5(double value)\n\n\n/*! Binary scaling steps, so return 0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 2, 4, 6, 8, 10, 20, 40 60, 80, 100..\n  \\return Rounded up value.\n*/\ndouble roundup2(double value)\n{\n  BOOST_MATH_STD_USING\n\n  smallest<> is_small(100. * (std::numeric_limits<double>::min)()); // 100 * min value.\n  if (is_small(value) )\n  { // Value very close to zero.\n    return 0.; // Just return zero.\n  }\n  bool is_neg = (value >= 0) ? false : true;\n  value = std::abs(value);\n  int order = int(floor(log10(value))); // 0 to 9.999, gives 0, 10 to 99.9 gives 2 ...\n  double scaled_value = value * pow(10., -order); // 0 to 9.99 is unchanged, 10 to 9.99 scaled down to 1. to 9.99\n  double pow10order = is_neg ? -pow(10., order) : pow(10., order); //  power of ten, signed.\n\n  if(scaled_value > 8.)\n  {\n    return 10. * pow10order;\n  }\n  else if(scaled_value > 6.)\n  {\n    return 8. * pow10order;\n  }\n  else if(scaled_value > 4.)\n  {\n    return 6. * pow10order;\n  }\n  else if(scaled_value > 2.)\n  {\n    return 4. * pow10order;\n  }\n  else\n  {\n    return 2. * pow10order;\n  }\n} // double roundup2(double value)\n\n/*! Binary scaling steps, so return 0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 2, 4, 6, 8, 10, 20, 40 60, 80, 100..\n  \\return Rounded down value.\n*/\ndouble rounddown2(double value)\n{\n  BOOST_MATH_STD_USING\n  smallest<> is_small(100. * (std::numeric_limits<double>::min)()); // 100 * min value\n  if (is_small(value))\n  { // Value very close to zero.\n    return 0.; // Just return zero.\n  }\n  bool is_neg = (value >= 0) ? false : true;\n  value = std::abs(value);\n  int order = int(floor(log10(value))); // 0 to 9.999, gives 0, 10 to 99.9 gives 2 ...\n  double scaled_value = value * pow(10., -order); // 0 to 9.99 is unchanged, 10 to 9.99 scaled down to 1. to 9.99\n  double pow10order = is_neg ? -pow(10., order) : pow(10., order); //  power of ten, signed.\n\n  if(scaled_value < 2.)\n  { // Not scaled.\n    return 1. * pow10order;\n  }\n  else if(scaled_value < 4.)\n  {\n    return 2. * pow10order;\n  }\n  else if(scaled_value < 6.)\n  {\n    return 4. * pow10order;\n  }\n  else if(scaled_value < 8.)\n  {\n    return 6. * pow10order;\n  }\n  else\n  { // > 8\n    return 8. * pow10order;\n  }\n} // double rounddown2(double value)\n\n} // namespace svg\n} // namespace boost\n\n#endif // BOOST_SVG_AUTO_AXES_HPP\n", "meta": {"hexsha": "36f34c6d1c57dd6b39595d54b656793747f87188", "size": 57714, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/svg_plot/detail/auto_axes.hpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "include/boost/svg_plot/detail/auto_axes.hpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "include/boost/svg_plot/detail/auto_axes.hpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 46.5060435133, "max_line_length": 220, "alphanum_fraction": 0.6773399868, "num_tokens": 15810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5511204717250646}}
{"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": "#define CATCH_CONFIG_MAIN\n#include <Eigen/Dense>\n#include <catch.hpp>\n#include <memory>\n#include <random>\n\n#include \"EDP/ConstructSparseMat.hpp\"\n#include \"EDP/LocalHamiltonian.hpp\"\n\n#include \"yavque/operators.hpp\"\n#include \"yavque/utils.hpp\"\n\n#include \"common.hpp\"\n\nTEST_CASE(\"test random ZZ\", \"[random-zz]\")\n{\n\tconst uint32_t N = 14;\n\tconst uint32_t n_terms = 10;\n\n\tusing namespace yavque;\n\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\tstd::normal_distribution<double> ndist;\n\n\tstd::vector<uint32_t> sites;\n\n\tfor(uint32_t k = 0; k < N; ++k)\n\t\tsites.push_back(k);\n\n\tfor(uint32_t k = 0; k < 100; ++k) // instance\n\t{\n\t\tstd::vector<std::pair<uint32_t, uint32_t>> interactions;\n\t\tfor(uint32_t iter_term = 0; iter_term < n_terms; ++iter_term)\n\t\t{\n\t\t\tstd::shuffle(sites.begin(), sites.end(), re);\n\t\t\tinteractions.emplace_back(sites[0], sites[1]);\n\t\t}\n\n\t\t// construct diagonal\n\t\tEigen::VectorXd ham_diag(1u << N);\n\t\tfor(uint32_t n = 0; n < (1u << N); ++n)\n\t\t{\n\t\t\tint elt = 0;\n\t\t\tfor(auto [i, j] : interactions)\n\t\t\t{\n\t\t\t\tint z0 = 1 - 2 * ((n >> i) & 1);\n\t\t\t\tint z1 = 1 - 2 * ((n >> j) & 1);\n\t\t\t\telt += z0 * z1;\n\t\t\t}\n\t\t\tham_diag(n) = elt;\n\t\t}\n\t\tauto diag_ham = DiagonalOperator(ham_diag);\n\t\tauto diag_ham_evol = DiagonalHamEvol(diag_ham);\n\n\t\tstd::vector<std::map<uint32_t, Pauli>> pauli_strings;\n\t\tfor(auto [i, j] : interactions)\n\t\t{\n\t\t\tstd::map<uint32_t, Pauli> m;\n\t\t\tm[i] = Pauli('Z');\n\t\t\tm[j] = Pauli('Z');\n\t\t\tpauli_strings.emplace_back(std::move(m));\n\t\t}\n\n\t\tauto sum_pauli = SumPauliString(N, pauli_strings);\n\t\tauto sum_pauli_evol = SumPauliStringHamEvol(sum_pauli);\n\n\t\tEigen::VectorXcd ini = Eigen::VectorXcd::Random(1u << N);\n\t\tini.normalize();\n\n\t\tdouble t = ndist(re);\n\n\t\tdiag_ham_evol.set_variable_value(t);\n\t\tsum_pauli_evol.set_variable_value(t);\n\n\t\tauto res1 = diag_ham_evol.apply_right(ini);\n\t\tauto res2 = sum_pauli_evol.apply_right(ini);\n\n\t\tREQUIRE((res1 - res2).norm() < 1e-6);\n\t}\n}\n\nEigen::SparseMatrix<yavque::cx_double>\nsingle_pauli(const uint32_t N, const uint32_t idx,\n             const Eigen::SparseMatrix<yavque::cx_double>& m)\n{\n\tedp::LocalHamiltonian<yavque::cx_double> lh(N, 2);\n\tlh.addOneSiteTerm(idx, m);\n\treturn edp::constructSparseMat<yavque::cx_double>(1 << N, lh);\n}\nEigen::SparseMatrix<yavque::cx_double> identity(const uint32_t N)\n{\n\tstd::vector<Eigen::Triplet<yavque::cx_double>> triplets;\n\tfor(uint32_t n = 0; n < (1u << N); ++n)\n\t{\n\t\ttriplets.emplace_back(n, n, 1.0);\n\t}\n\tEigen::SparseMatrix<yavque::cx_double> m(1 << N, 1 << N);\n\tm.setFromTriplets(triplets.begin(), triplets.end());\n\treturn m;\n}\n\nTEST_CASE(\"test ZXZ\", \"[zxz]\")\n{\n\tconst uint32_t N = 10;\n\n\tusing namespace yavque;\n\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\tstd::normal_distribution<> ndist;\n\n\tstd::vector<std::map<uint32_t, Pauli>> pauli_strings;\n\n\tfor(uint32_t k = 0; k < N; k++)\n\t{\n\t\tstd::map<uint32_t, Pauli> m;\n\t\tm[k] = Pauli('Z');\n\t\tm[(k + 1) % N] = Pauli('X');\n\t\tm[(k + 2) % N] = Pauli('Z');\n\n\t\tpauli_strings.emplace_back(std::move(m));\n\t}\n\n\tauto sum_pauli = SumPauliString(N, pauli_strings);\n\tauto sum_pauli_evol = SumPauliStringHamEvol(sum_pauli);\n\n\tEigen::SparseMatrix<cx_double> ham(1 << N, 1 << N);\n\tfor(uint32_t k = 0; k < N; k++)\n\t{\n\t\tEigen::SparseMatrix<cx_double> term = identity(N);\n\t\tterm = term * single_pauli(N, k, pauli_z().cast<cx_double>());\n\t\tterm = term * single_pauli(N, (k + 1) % N, pauli_x().cast<cx_double>());\n\t\tterm = term * single_pauli(N, (k + 2) % N, pauli_z().cast<cx_double>());\n\n\t\tham += term;\n\t}\n\n\tauto ham_full = Hamiltonian(ham);\n\tauto ham_full_evol = HamEvol(ham_full);\n\n\tdouble t = ndist(re);\n\n\tham_full_evol.set_variable_value(t);\n\tsum_pauli_evol.set_variable_value(t);\n\n\tfor(uint32_t k = 0; k < 100; ++k) // instance\n\t{\n\t\tEigen::VectorXcd ini = Eigen::VectorXcd::Random(1u << N);\n\t\tini.normalize();\n\n\t\tauto res1 = ham_full_evol.apply_right(ini);\n\t\tauto res2 = sum_pauli_evol.apply_right(ini);\n\n\t\tREQUIRE((res1 - res2).norm() < 1e-6);\n\t}\n}\n", "meta": {"hexsha": "62aaf88378057469163a29939848a133c7dc46f7", "size": 3914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/TestSumPauliStringHamEvol.cpp", "max_stars_repo_name": "chaeyeunpark/Yavque", "max_stars_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests/TestSumPauliStringHamEvol.cpp", "max_issues_repo_name": "chaeyeunpark/Yavque", "max_issues_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tests/TestSumPauliStringHamEvol.cpp", "max_forks_repo_name": "chaeyeunpark/Yavque", "max_forks_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7721518987, "max_line_length": 74, "alphanum_fraction": 0.6586612161, "num_tokens": 1338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5511062093730826}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n#include <complex>\n#include <vector>\n\n#include <boost/numeric/mtl/mtl.hpp>\n\n\n\nconst unsigned sz= 5;\n\ninline float f(float x) { return x; }\ninline double f(double x) { return x; }\n\ninline std::complex<double> f(std::complex<double> x) \n{ \n    return std::complex<double>(real(x), real(x)+1.0); \n}\n\n\ntemplate <typename Vector, typename T>\nvoid test(Vector& v, const T&, const char* name)\n{\n    using std::abs; using std::cout; using mtl::size; \n    using mtl::orth; using mtl::orthogonalize_factors;\n\n    std::cout << \"\\n\" << name << \"\\n\";\n    for (unsigned i= 0, c= 1; i < size(v); ++i)\n\tfor (unsigned j= 0; j < size(v[i]); ++j, c++)\n\t    v[i][j]= f(T((i + j) % sz));\n\n\n    cout << \"w initially\\n\";\n    Vector w(v);\n    for (unsigned i= 0; i < size(w); ++i)\n\tstd::cout << w[i] << \"\\n\";\n    std::cout << \"\\n\";\n\n    orth(w);\n\n    for (unsigned i= 0; i < size(w); ++i)\n\tstd::cout << w[i] << \"\\n\";\n    std::cout << \"\\n\";\n\n    for (unsigned i= 0, c= 1; i < size(w); ++i) {\n\tfor (unsigned j= 0; j < size(w); ++j, ++c)\n\t    std::cout << dot(w[i], w[j]) << \" \";\n\tstd::cout << \"\\n\";\n    }   \n\n    MTL_THROW_IF(abs(dot(w[3], w[4])) > 0.00001, mtl::runtime_error(\"Vectors 3 and 4 are not orthogonal!\"));\n    MTL_THROW_IF(abs(dot(w[4], w[4]) - T(1)) > 0.00001, mtl::runtime_error(\"Vector 4 is not normal!\"));\n\n    cout << \"\\nv initially\\n\";\n    for (unsigned i= 0; i < size(v); ++i)\n\tstd::cout << v[i] << \"\\n\";\n    std::cout << \"\\n\";\n\n    std::cout << \"The according factors are: \\n\" << orthogonalize_factors(v) << '\\n';\n\n    for (unsigned i= 0; i < size(v); ++i)\n\tstd::cout << v[i] << \"\\n\";\n    std::cout << \"\\n\";\n\n    for (unsigned i= 0, c= 1; i < size(v); ++i) {\n\tfor (unsigned j= 0; j < size(v); ++j, ++c)\n\t    std::cout << dot(v[i], v[j]) << \" \";\n\tstd::cout << \"\\n\";\n    }   \n\n    MTL_THROW_IF(abs(dot(v[3], v[4])) > 0.00001, mtl::runtime_error(\"Vectors 3 and 4 are not orthogonal!\"));\n    MTL_THROW_IF(abs(dot(v[4], v[4])) < 0.00001, mtl::runtime_error(\"Vector 4 should be non-zero!\"));\n\n\n}\n\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n    dense_vector<float>                                                 cf(sz, 1.0);\n    dense_vector<double>                                                cd(sz, 1.0);\n    dense_vector<std::complex<double> >                                 cc(sz, 1.0);\n    dense_vector<float, mtl::vec::parameters<row_major> >                 rf(sz, 1.0);\n\n    std::vector<dense_vector<float> >                                   scf(sz, cf);\n    std::vector<dense_vector<double> >                                  scd(sz, cd);\n    std::vector<dense_vector<std::complex<double> > >                   scc(sz, cc);\n    std::vector<dense_vector<float, mtl::vec::parameters<row_major> > >   srf(sz, rf);\n\n    dense_vector<dense_vector<float> >                                  ccf(sz, cf);\n    dense_vector<dense_vector<float>, mtl::vec::parameters<row_major> >   rcf(sz, cf);\n\n    test(scf, cf[0], \"std::vector<dense_vector<float> >\");\n    test(scd, cd[0], \"std::vector<dense_vector<double> >\");\n    test(scc, cc[0], \"std::vector<dense_vector<std::complex<double> > >\");\n    test(srf, rf[0], \"std::vector<dense_vector<float, parameters<row_major> > >\");\n\n    test(ccf, cf[0], \"dense_vector<dense_vector<float> >\");\n    test(rcf, cf[0], \"dense_vector<dense_vector<float>, parameters<row_major> >\");\n\n    return 0;\n}\n", "meta": {"hexsha": "caf110b7654cc16c2e15db6d699b8839bbfa3c9a", "size": 3814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/orth_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/orth_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/orth_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.5982905983, "max_line_length": 108, "alphanum_fraction": 0.5508652334, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5511062059891587}}
{"text": "#include <vector>\n\n#include <boost/mpi.hpp>\n#include <boost/test/minimal.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n//#include \"../../sketch/CT.hpp\"\n//#include \"../../sketch/CWT.hpp\"\n#include \"../../sketch/sketch.hpp\"\n\n// TODO: Are these includes really needed?\n#include <elemental.hpp>\n#include <skylark.hpp>\n#include \"../../sketch/CT.hpp\"\n#include \"../../sketch/CWT.hpp\"\n\n#include \"../../base/context.hpp\"\n\nint test_main(int argc, char *argv[]) {\n\n    //////////////////////////////////////////////////////////////////////////\n    //[> Parameters <]\n    const size_t n   = 10;\n    const size_t m   = 5;\n    const size_t n_s = 6;\n    const size_t m_s = 3;\n\n    const int seed = static_cast<int>(rand() * 100);\n\n    typedef FullyDistVec<size_t, double> mpi_vector_t;\n    typedef SpDCCols<size_t, double> col_t;\n    typedef SpParMat<size_t, double, col_t> DistMatrixType;\n\n    namespace mpi = boost::mpi;\n    mpi::environment env(argc, argv);\n    mpi::communicator world;\n    const size_t rank = world.rank();\n    skylark::base::context_t context (seed);\n\n    double count = 1.0;\n\n    const size_t matrix_full = n * m;\n    mpi_vector_t colsf(matrix_full);\n    mpi_vector_t rowsf(matrix_full);\n    mpi_vector_t valsf(matrix_full);\n\n    for(size_t i = 0; i < matrix_full; ++i) {\n        colsf.SetElement(i, i % m);\n        rowsf.SetElement(i, i / m);\n        valsf.SetElement(i, count);\n        count++;\n    }\n\n    DistMatrixType A(n, m, rowsf, colsf, valsf);\n\n    //////////////////////////////////////////////////////////////////////////\n    //[> Setup test <]\n\n    //[> 1. Create the sketching matrix and dump JSON <]\n    skylark::sketch::CWT_t<DistMatrixType, DistMatrixType>\n        Sparse(n, n_s, context);\n\n    // dump to property tree\n    boost::property_tree::ptree pt = Sparse.get_data()->to_ptree();\n\n    //[> 2. Dump the JSON string to file <]\n    std::ofstream out(\"sketch.json\");\n    write_json(out, pt);\n    out.close();\n\n    //[> 3. Create a sketch from the JSON file. <]\n    std::ifstream file;\n    std::stringstream json;\n    file.open(\"sketch.json\", std::ios::in);\n\n    boost::property_tree::ptree json_tree;\n    boost::property_tree::read_json(file, json_tree);\n\n    skylark::sketch::CWT_t<DistMatrixType, DistMatrixType> tmp(json_tree);\n\n    //[> 4. Both sketches should compute the same result. <]\n    mpi_vector_t zero;\n    DistMatrixType sketch_A(n_s, m, zero, zero, zero);\n    DistMatrixType sketch_Atmp(n_s, m, zero, zero, zero);\n\n    Sparse.apply(A, sketch_A, skylark::sketch::columnwise_tag());\n    tmp.apply(A, sketch_Atmp, skylark::sketch::columnwise_tag());\n\n    if (!static_cast<bool>(sketch_A == sketch_Atmp))\n        BOOST_FAIL(\"Applied sketch did not result in same result\");\n\n    return 0;\n}\n", "meta": {"hexsha": "2c36da19b8092a7b7b9ef7d63067d59959543531", "size": 2776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/SerializationTest.cpp", "max_stars_repo_name": "wangg12/libskylark", "max_stars_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-12T07:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T07:26:47.000Z", "max_issues_repo_path": "tests/unit/SerializationTest.cpp", "max_issues_repo_name": "cjiyer/libskylark", "max_issues_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/unit/SerializationTest.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": 29.2210526316, "max_line_length": 78, "alphanum_fraction": 0.6131123919, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5511062043249594}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//! \\file\r\n//!\\brief Test sqrt() for negatable in a tiny digit region.\r\n\r\n#include <cmath>\r\n\r\n#define BOOST_TEST_MODULE test_negatable_func_sqrt_tiny\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nnamespace local\r\n{\r\n  template<typename FixedPointType>\r\n  const FixedPointType& tolerance_maker(const int fuzzy_bits)\r\n  {\r\n    static const FixedPointType the_tolerance = ldexp(FixedPointType(1), FixedPointType::resolution + fuzzy_bits);\r\n\r\n    return the_tolerance;\r\n  }\r\n\r\n  template<typename FixedPointType,\r\n           typename FloatPointType = typename FixedPointType::float_type>\r\n  void test_sqrt(const int fuzzy_bits)\r\n  {\r\n    // Use at least 8 resolution bits.\r\n    // Use at least 4 range bits.\r\n\r\n    BOOST_STATIC_ASSERT(-FixedPointType::resolution >= 8);\r\n    BOOST_STATIC_ASSERT( FixedPointType::range      >= 4);\r\n\r\n    using std::sqrt;\r\n\r\n    const FixedPointType a1 (FixedPointType(1) /  2);                       const FloatPointType b1(FloatPointType(1) /  2);\r\n    const FixedPointType a2 (FixedPointType(6) / 10);                       const FloatPointType b2(FloatPointType(6) / 10);\r\n    const FixedPointType a3 (FixedPointType(3) /  2);                       const FloatPointType b3(FloatPointType(3) /  2);\r\n    const FixedPointType a4 (2L);                                           const FloatPointType b4(2L);\r\n    const FixedPointType a5 (FixedPointType(5) /  2);                       const FloatPointType b5(FloatPointType(5) /  2);\r\n    const FixedPointType a6 (3L);                                           const FloatPointType b6(3L);\r\n    const FixedPointType a7 (FixedPointType(1) /  3);                       const FloatPointType b7(FloatPointType(1) /  3);\r\n    const FixedPointType a8 (boost::math::constants::pi<FixedPointType>()); const FloatPointType b8(boost::math::constants::pi<FloatPointType>());\r\n    const FixedPointType a9 (11L);                                          const FloatPointType b9(11L);\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a1), FixedPointType(sqrt(b1)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a2), FixedPointType(sqrt(b2)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a3), FixedPointType(sqrt(b3)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a4), FixedPointType(sqrt(b4)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a5), FixedPointType(sqrt(b5)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a6), FixedPointType(sqrt(b6)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a7), FixedPointType(sqrt(b7)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a8), FixedPointType(sqrt(b8)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(sqrt(a9), FixedPointType(sqrt(b9)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_func_sqrt_tiny)\r\n{\r\n  { typedef boost::fixed_point::negatable<7,  -8> fixed_point_type; local::test_sqrt<fixed_point_type>(1); }\r\n  { typedef boost::fixed_point::negatable<4, -11> fixed_point_type; local::test_sqrt<fixed_point_type>(1); }\r\n}\r\n", "meta": {"hexsha": "979e1bc6b0da8c92c1a59849fd0ec65e0ba41cc1", "size": 3706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_func_sqrt_tiny.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_func_sqrt_tiny.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_func_sqrt_tiny.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": 53.7101449275, "max_line_length": 147, "alphanum_fraction": 0.6815974096, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7217432122827967, "lm_q1q2_score": 0.551039231801691}}
{"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": "//\n//  Copyright Toon Knapen and Kresimir Fresl\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#ifndef BOOST_NUMERIC_BINDINGS_BLAS_BLAS1_HPP\n#define BOOST_NUMERIC_BINDINGS_BLAS_BLAS1_HPP\n\n#include <boost/numeric/bindings/blas/blas1_overloads.hpp>\n#include <boost/numeric/bindings/traits/vector_traits.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <cassert> \n\nnamespace boost { namespace numeric { namespace bindings { namespace blas {\n\n  // x <- y\n  template < typename vector_x_type, typename vector_y_type >\n  void copy(const vector_x_type &x, vector_y_type &y )\n  {\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    BOOST_STATIC_ASSERT( ( boost::is_same< typename traits::vector_traits<vector_x_type>::value_type, typename traits::vector_traits<vector_y_type>::value_type >::value ) ) ;\n#else\n    BOOST_STATIC_ASSERT( ( boost::is_same< typename vector_x_type::value_type, typename vector_y_type::value_type >::value ) ) ;\n#endif\n\n    const int n =  traits::vector_size( x ) ;\n    assert( n==traits::vector_size( y ) ) ;\n    const int stride_x = traits::vector_stride( x ) ;\n    const int stride_y = traits::vector_stride( y ) ;\n    typename traits::vector_traits<vector_x_type>::value_type const *x_ptr = traits::vector_storage( x ) ;\n    typename traits::vector_traits<vector_y_type>::value_type *y_ptr = traits::vector_storage( y ) ;\n\n    detail::copy( n, x_ptr, stride_x, y_ptr, stride_y ) ;\n  }\n\n\n  // x <- alpha * x\n  template < typename value_type, typename vector_type >\n  void scal(const value_type &alpha, vector_type &x )\n  {\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    BOOST_STATIC_ASSERT( ( boost::is_same< value_type, typename traits::vector_traits<vector_type>::value_type >::value ) ) ;\n#else\n    BOOST_STATIC_ASSERT( ( boost::is_same< value_type, typename vector_type::value_type >::value ) ) ;\n#endif\n\n    const int n =  traits::vector_size( x ) ;\n    const int stride = traits::vector_stride( x ) ;\n    value_type *x_ptr = traits::vector_storage( x ) ;\n\n    detail::scal( n, alpha, x_ptr, stride ) ;\n  }\n\n\n  // y <- alpha * x + y\n  template < typename value_type, typename vector_type_x, typename vector_type_y >\n  void axpy(const value_type& alpha, const vector_type_x &x, vector_type_y &y )\n  { \n#ifdef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    BOOST_STATIC_ASSERT( ( is_same< value_type, typename vector_type_x::value_type >::value ) ) ;\n    BOOST_STATIC_ASSERT( ( is_same< value_type, typename vector_type_y::value_type >::value ) ) ;\n#else\n    BOOST_STATIC_ASSERT( ( is_same< value_type, typename traits::vector_traits< vector_type_x >::value_type >::value ) ) ;\n    BOOST_STATIC_ASSERT( ( is_same< value_type, typename traits::vector_traits< vector_type_y >::value_type >::value ) ) ;\n#endif\n    assert( traits::vector_size( x ) == traits::vector_size( y ) ) ;\n\n    const int n = traits::vector_size( x ) ;\n    const int stride_x = traits::vector_stride( x ) ;\n    const int stride_y = traits::vector_stride( y ) ;\n    const value_type *x_ptr = traits::vector_storage( x ) ;\n    value_type *y_ptr = traits::vector_storage( y ) ;\n\n    detail::axpy( n, alpha, x_ptr, stride_x, y_ptr, stride_y ) ; \n  }\n\n\n  // dot <- x^T * y  (real vectors)\n  template < typename vector_type_x, typename vector_type_y >\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n  typename traits::vector_traits< vector_type_x >::value_type \n#else\n  typename vector_type_x::value_type\n#endif\n  dot(const vector_type_x &x, const vector_type_y &y)\n  {\n#ifdef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    BOOST_STATIC_ASSERT( ( is_same< typename vector_type_y::value_type, typename vector_type_x::value_type >::value ) ) ;\n#else\n    BOOST_STATIC_ASSERT( ( is_same< typename traits::vector_traits< vector_type_y >::value_type, typename traits::vector_traits< vector_type_x >::value_type >::value ) ) ;\n#endif\n\n    assert( traits::vector_size( x ) == traits::vector_size( y ) ) ;\n\n    typedef\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    typename traits::vector_traits< vector_type_x >::value_type \n#else\n    typename vector_type_x::value_type\n#endif\n    value_type ;\n\n    const int n = traits::vector_size( x ) ;\n    const int stride_x = traits::vector_stride( x ) ;\n    const int stride_y = traits::vector_stride( y ) ;\n\n    const value_type *x_ptr = traits::vector_storage( x ) ;\n    const value_type *y_ptr = traits::vector_storage( y ) ;\n\n    return detail::dot( n, x_ptr, stride_x, y_ptr, stride_y ) ;\n  }\n\n  // dotu <- x^T * y  (complex vectors)\n  template < typename vector_type_x, typename vector_type_y >\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n  typename traits::vector_traits< vector_type_x >::value_type \n#else\n  typename vector_type_x::value_type\n#endif\n  dotu(const vector_type_x &x, const vector_type_y &y)\n  {\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    BOOST_STATIC_ASSERT( ( is_same< typename traits::vector_traits< vector_type_y >::value_type, typename traits::vector_traits< vector_type_x >::value_type >::value ) ) ;\n#else\n    BOOST_STATIC_ASSERT( ( is_same< typename vector_type_y::value_type, typename vector_type_x::value_type >::value ) ) ;\n#endif\n    assert( traits::vector_size( x ) == traits::vector_size( y ) ) ;\n\n    typedef\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    typename traits::vector_traits< vector_type_x >::value_type\n#else\n    typename vector_type_x::value_type\n#endif\n    value_type ;\n\n    const int n = traits::vector_size( x ) ;\n    const int stride_x = traits::vector_stride( x ) ;\n    const int stride_y = traits::vector_stride( y ) ;\n    const value_type *x_ptr = traits::vector_storage( x ) ;\n    const value_type *y_ptr = traits::vector_storage( y ) ;\n    \n    value_type ret ;\n    detail::dotu( ret, n, x_ptr, stride_x, y_ptr, stride_y ) ;\n    return ret;\n  }\n\n  // dotc <- x^H * y  (complex vectors) \n  template < typename vector_type_x, typename vector_type_y >\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n  typename traits::vector_traits< vector_type_x >::value_type \n#else\n  typename vector_type_x::value_type\n#endif\n  dotc(const vector_type_x &x, const vector_type_y &y)\n  {\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    BOOST_STATIC_ASSERT( ( is_same< typename traits::vector_traits< vector_type_y >::value_type, typename traits::vector_traits< vector_type_x >::value_type >::value ) ) ;\n#else\n    BOOST_STATIC_ASSERT( ( is_same< typename vector_type_y::value_type, typename vector_type_x::value_type >::value ) ) ;\n#endif\n    assert( traits::vector_size( x ) == traits::vector_size( y ) ) ;\n\n    typedef\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    typename traits::vector_traits< vector_type_x >::value_type\n#else\n    typename vector_type_x::value_type\n#endif\n    value_type ;\n\n    const int n = traits::vector_size( x ) ;\n    const int stride_x = traits::vector_stride( x ) ;\n    const int stride_y = traits::vector_stride( y ) ;\n    const value_type *x_ptr = traits::vector_storage( x ) ;\n    const value_type *y_ptr = traits::vector_storage( y ) ;\n    \n    value_type ret ;\n    detail::dotc( ret, n, x_ptr, stride_x, y_ptr, stride_y ) ;\n    return ret;\n  }\n\n\n  // nrm2 <- ||x||_2\n  template < typename vector_type >\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n  typename traits::type_traits< typename traits::vector_traits< vector_type >::value_type >::real_type\n#else\n  typename traits::type_traits< typename vector_type::value_type >::real_type\n#endif\n  nrm2(const vector_type &x) \n  {\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    typedef typename traits::vector_traits< vector_type >::value_type value_type;\n#else\n    typedef vector_type::value_type value_type ;\n#endif\n    const int n = traits::vector_size( x ) ;\n    const int stride_x = traits::vector_stride( x ) ;\n    const value_type *x_ptr = traits::vector_storage( x ) ;\n\n    return detail::nrm2( n, x_ptr, stride_x ) ;\n  }\n\n\n\n  // asum <- ||x||_1\n  // .. for now works only with real vectors\n  template < typename vector_type >\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n  typename traits::type_traits< typename traits::vector_traits< vector_type >::value_type >::real_type \n#else\n  typename traits::type_traits< typename vector_type::value_type >::real_type\n#endif\n  asum(const vector_type &x) \n  {\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n    typedef typename traits::vector_traits< vector_type >::value_type value_type;\n#else\n    typedef vector_type::value_type value_type ;\n#endif\n\n    const int n = traits::vector_size( x ) ;\n    const int stride_x = traits::vector_stride( x ) ;\n    const value_type *x_ptr = traits::vector_storage( x ) ;\n\n    return detail::asum( n, x_ptr, stride_x ) ;\n  }\n\n}}}}\n\n#endif // BOOST_NUMERIC_BINDINGS_BLAS_BLAS1_HPP\n", "meta": {"hexsha": "cd115cc87585bd1d657dbce20a9f795050c126ee", "size": 8811, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/blas/blas1.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/blas/blas1.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/blas/blas1.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": 37.1772151899, "max_line_length": 174, "alphanum_fraction": 0.7276132108, "num_tokens": 2277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5510087109834763}}
{"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": "\n#include <gtest/gtest.h>\n#include \"../util/util.h\"\n#include <Eigen/Core>\n#include <string>\n#include <algorithm>\n\n#ifndef _MSC_VER\nextern \"C\" {\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#include <csim/update_ops.h>\n#include <csim/init_ops.h>\n}\n#else\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#include <csim/update_ops.h>\n#include <csim/init_ops.h>\n#endif\n#include <csim/update_ops_cpp.hpp>\n\nvoid test_single_dense_matrix_gate(std::function<void(UINT, const CTYPE*, CTYPE*, ITYPE)> func) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tEigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U;\n\n\tUINT target;\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\tEigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\t// single qubit dense matrix gate\n\t\t// NOTE: Eigen uses column major by default. To use raw-data of eigen matrix, we need to specify RowMajor.\n\t\ttarget = rand_int(n);\n\t\tU = get_eigen_matrix_random_single_qubit_unitary();\n\t\tfunc(target, (CTYPE*)U.data(), state, dim);\n\t\ttest_state = get_expanded_eigen_matrix_with_identity(target, U, n) * test_state;\n\t\tstate_equal(state, test_state, dim, \"single dense gate\");\n\t}\n\trelease_quantum_state(state);\n}\n\nTEST(UpdateTest, SingleDenseMatrixTest) {\n\ttest_single_dense_matrix_gate(single_qubit_dense_matrix_gate);\n\ttest_single_dense_matrix_gate(single_qubit_dense_matrix_gate_single);\n\ttest_single_dense_matrix_gate(single_qubit_dense_matrix_gate_single_unroll);\n#ifdef _OPENMP\n\ttest_single_dense_matrix_gate(single_qubit_dense_matrix_gate_parallel);\n\ttest_single_dense_matrix_gate(single_qubit_dense_matrix_gate_parallel_unroll);\n#endif\n#ifdef _USE_SIMD\n\ttest_single_dense_matrix_gate(single_qubit_dense_matrix_gate_single_simd);\n#ifdef _OPENMP\n\ttest_single_dense_matrix_gate(single_qubit_dense_matrix_gate_parallel_simd);\n#endif\n#endif\n}\n\nvoid test_general_dense_matrix_gate(std::function<void(const UINT*, UINT, const CTYPE*, CTYPE*, ITYPE)> func) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tstd::vector<UINT> index_list;\n\tfor (UINT i = 0; i < n; ++i) index_list.push_back(i);\n\n\tEigen::Matrix<std::complex<double>, 2, 2, Eigen::RowMajor> U1, U2, U3;\n\tUINT targets[3];\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\tEigen::MatrixXcd whole_I = Eigen::MatrixXcd::Identity(dim, dim);\n\n\t// general single\n\t{\n\t\tEigen::Matrix<std::complex<double>, 2,2, Eigen::RowMajor> Umerge;\n\t\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\n\t\t\t// two qubit dense matrix gate\n\t\t\tU1 = get_eigen_matrix_random_single_qubit_unitary();\n\t\t\tstd::random_shuffle(index_list.begin(), index_list.end());\n\t\t\ttargets[0] = index_list[0];\n\t\t\tUmerge = U1;\n\n\t\t\ttest_state = get_expanded_eigen_matrix_with_identity(targets[0], U1, n)\n\t\t\t\t* test_state;\n\t\t\tfunc(targets, 1, (CTYPE*)Umerge.data(), state, dim);\n\t\t\tstate_equal(state, test_state, dim, \"single-qubit separable dense gate\");\n\t\t}\n\t}\n\t// general double\n\t{\n\t\tEigen::Matrix<std::complex<double>, 4,4, Eigen::RowMajor> Umerge;\n\n\t\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\n\t\t\t// two qubit dense matrix gate\n\t\t\tU1 = get_eigen_matrix_random_single_qubit_unitary();\n\t\t\tU2 = get_eigen_matrix_random_single_qubit_unitary();\n\n\t\t\tstd::random_shuffle(index_list.begin(), index_list.end());\n\t\t\ttargets[0] = index_list[0];\n\t\t\ttargets[1] = index_list[1];\n\t\t\tUmerge = kronecker_product(U2, U1);\n\n\t\t\ttest_state =\n\t\t\t\tget_expanded_eigen_matrix_with_identity(targets[1], U2, n)\n\t\t\t\t* get_expanded_eigen_matrix_with_identity(targets[0], U1, n)\n\t\t\t\t* test_state;\n\t\t\tfunc(targets, 2, (CTYPE*)Umerge.data(), state, dim);\n\t\t\tstate_equal(state, test_state, dim, \"two-qubit separable dense gate\");\n\t\t}\n\t}\n\t// general triple\n\t{\n\t\tEigen::Matrix<std::complex<double>, 8, 8, Eigen::RowMajor> Umerge;\n\n\t\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\n\t\t\t// two qubit dense matrix gate\n\t\t\tU1 = get_eigen_matrix_random_single_qubit_unitary();\n\t\t\tU2 = get_eigen_matrix_random_single_qubit_unitary();\n\t\t\tU3 = get_eigen_matrix_random_single_qubit_unitary();\n\n\t\t\tstd::random_shuffle(index_list.begin(), index_list.end());\n\t\t\ttargets[0] = index_list[0];\n\t\t\ttargets[1] = index_list[1];\n\t\t\ttargets[2] = index_list[2];\n\t\t\tUmerge = kronecker_product(U3, kronecker_product(U2, U1));\n\n\t\t\ttest_state =\n\t\t\t\tget_expanded_eigen_matrix_with_identity(targets[2], U3, n)\n\t\t\t\t* get_expanded_eigen_matrix_with_identity(targets[1], U2, n)\n\t\t\t\t* get_expanded_eigen_matrix_with_identity(targets[0], U1, n)\n\t\t\t\t* test_state;\n\t\t\tfunc(targets, 3, (CTYPE*)Umerge.data(), state, dim);\n\t\t\tstate_equal(state, test_state, dim, \"three-qubit separable dense gate\");\n\t\t}\n\t}\n\trelease_quantum_state(state);\n}\n\nTEST(UpdateTest, ThreeQubitDenseMatrixTest) {\n\ttest_general_dense_matrix_gate(multi_qubit_dense_matrix_gate);\n\ttest_general_dense_matrix_gate(multi_qubit_dense_matrix_gate_single);\n#ifdef _OPENMP\n\ttest_general_dense_matrix_gate(multi_qubit_dense_matrix_gate_parallel);\n#endif\n}", "meta": {"hexsha": "3da712326909a4d4f3fd51e58a75d93d894ee708", "size": 5280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/csim/test_update_dense.cpp", "max_stars_repo_name": "kamakiri01/qulacs", "max_stars_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 260.0, "max_stars_repo_stars_event_min_datetime": "2018-10-13T15:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T11:03:58.000Z", "max_issues_repo_path": "test/csim/test_update_dense.cpp", "max_issues_repo_name": "kamakiri01/qulacs", "max_issues_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 182.0, "max_issues_repo_issues_event_min_datetime": "2018-10-14T02:29:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:23:18.000Z", "max_forks_repo_path": "test/csim/test_update_dense.cpp", "max_forks_repo_name": "kamakiri01/qulacs", "max_forks_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 88.0, "max_forks_repo_forks_event_min_datetime": "2018-10-10T03:46:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T21:56:05.000Z", "avg_line_length": 33.0, "max_line_length": 111, "alphanum_fraction": 0.7401515152, "num_tokens": 1495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5509643790077546}}
{"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": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//! \\file\r\n//!\\brief Tests for exp(fixed_point) round::nearest_even.\r\n\r\n#define BOOST_TEST_MODULE test_negatable_func_exp_nearest_even\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <cmath>\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nnamespace local\r\n{\r\n  template<typename FixedPointType>\r\n  const FixedPointType& tolerance_maker(const int fuzzy_bits)\r\n  {\r\n    static const FixedPointType the_tolerance = ldexp(FixedPointType(1), FixedPointType::resolution + fuzzy_bits);\r\n\r\n    return the_tolerance;\r\n  }\r\n\r\n  template<typename FixedPointType,\r\n           typename FloatPointType = typename FixedPointType::float_type>\r\n  void test_exp(const int fuzzy_bits)\r\n  {\r\n    // Use at least 8 resolution bits.\r\n    // Use at least 7 range bits.\r\n\r\n    BOOST_STATIC_ASSERT(-FixedPointType::resolution >= 8);\r\n    BOOST_STATIC_ASSERT( FixedPointType::range      >= 7);\r\n\r\n    const FixedPointType a1(+1L    );                                       const FloatPointType b1(+1L    );\r\n    const FixedPointType a2(+2L    );                                       const FloatPointType b2(+2L    );\r\n    const FixedPointType a3(+4.375L);                                       const FloatPointType b3(+4.375L);\r\n    const FixedPointType a4(+1.125L);                                       const FloatPointType b4(+1.125L);\r\n    const FixedPointType a5(-1.125L);                                       const FloatPointType b5(-1.125L);\r\n    const FixedPointType a6(+0.875L);                                       const FloatPointType b6(+0.875L);\r\n    const FixedPointType a7(FixedPointType( 1) /  3);                       const FloatPointType b7(FloatPointType( 1) /  3);\r\n    const FixedPointType a8(FixedPointType(11) / 10);                       const FloatPointType b8(FloatPointType(11) / 10);\r\n    const FixedPointType a9(boost::math::constants::phi<FixedPointType>()); const FloatPointType b9(boost::math::constants::phi<FloatPointType>());\r\n\r\n    using std::exp;\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(exp(a1), FixedPointType(exp(b1)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(exp(a2), FixedPointType(exp(b2)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(exp(a3), FixedPointType(exp(b3)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(exp(a4), FixedPointType(exp(b4)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(exp(a5), FixedPointType(exp(b5)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(exp(a6), FixedPointType(exp(b6)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(exp(a7), FixedPointType(exp(b7)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(exp(a8), FixedPointType(exp(b8)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(exp(a9), FixedPointType(exp(b9)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_func_exp_nearest_even)\r\n{\r\n  // Test exp() for negatable round::nearest_even in various key digit\r\n  // regions such as 16, 24, 32, 53, 64, 113.\r\n\r\n  { typedef boost::fixed_point::negatable< 7,   -8, boost::fixed_point::round::nearest_even> fixed_point_type; local::test_exp<fixed_point_type>( 4); }\r\n  { typedef boost::fixed_point::negatable< 7,  -24, boost::fixed_point::round::nearest_even> fixed_point_type; local::test_exp<fixed_point_type>( 6); }\r\n  { typedef boost::fixed_point::negatable<10, -117, boost::fixed_point::round::nearest_even> fixed_point_type; local::test_exp<fixed_point_type>(12); }\r\n}\r\n", "meta": {"hexsha": "22720ac30f2fa5a1eb242c57249a679ce25b5c6e", "size": 4030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_func_exp_nearest_even.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_func_exp_nearest_even.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_func_exp_nearest_even.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": 55.2054794521, "max_line_length": 152, "alphanum_fraction": 0.6756823821, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5509643671051598}}
{"text": "/**\n * @file   AtomGroup.hpp\n * @author see AUTHORS\n * @brief  AtomGroup header file.\n */\n\n#ifndef ATOMGROUP_HPP\n#define ATOMGROUP_HPP\n\n#include <vector>\n#include <iostream>\n\n#include <Eigen/Dense>\n\n#include \"Atom.hpp\"\n\n/**\n * @class AtomGroup\n * @brief represents a group of atoms\n */\nclass AtomGroup {\n public:\n    explicit AtomGroup();\n\n    ~AtomGroup();\n\n    /**\n     * @brief returns all the atoms in the group\n     * @return a vector containing all the atoms\n     */\n    std::vector<Atom> get_atoms() const;\n\n    /**\n     * @brief returns all the coordinates of all the atoms in the group\n     * @return a vector containing a coordinates for all the atoms\n     */\n    std::vector<Eigen::Vector3d> get_coordinates() const;\n\n    /**\n    * @brief returns the size of the group (which is the number of atoms)\n    * @return the size of the group\n    */\n    int get_size() const;\n\n    /**\n    * @brief returns the total mass of the atom group\n    * @return the total mass of the atom group\n    */\n    double get_total_mass() const;\n\n    /**\n    * @brief returns the center of mass of the group\n    * @return the coordinates of the center of mass\n    */\n    Eigen::Vector3d get_center_of_mass() const;\n\n    /**\n    * @brief returns the positions of the atoms relative to the mass center of the group\n    * @return a matrix containing the positions of the atoms relative to the groups center of mass\n    */\n    Eigen::Matrix3Xd get_relative_positions() const;\n\n protected:\n    std::vector<Atom> atoms;\n};\n\n#endif\n\n// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n", "meta": {"hexsha": "292ec54c92face9129871533f80452b3e28af752", "size": 1567, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/AtomGroup.hpp", "max_stars_repo_name": "AFriemann/LowCarb", "max_stars_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AtomGroup.hpp", "max_issues_repo_name": "AFriemann/LowCarb", "max_issues_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-15T13:57:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-15T13:57:26.000Z", "max_forks_repo_path": "src/AtomGroup.hpp", "max_forks_repo_name": "AFriemann/LowCarb", "max_forks_repo_head_hexsha": "073e036a5fd6787943c4cbd76ab388dbd830e7d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3857142857, "max_line_length": 98, "alphanum_fraction": 0.6592214422, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.5509643650790605}}
{"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": "<<<<<<< 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 *      Burden, R.L., Faires, J.D. Numerical Analysis, 7th Edition, Books/Cole, 2001.\n *      Montenbruck, O., Gill, E. Satellite Orbits: Models, Methods, Applications, Springer, 2005.\n *\n *    Notes\n *      There might be a problem with the RKF78 and DOPRI8 integrators, as the coefficients do not\n *      meet the required conditions to the tolerance achieved for all the other Runge-Kutta-type\n *      integrators tested (1.0e-14 versus 1.0e-15 for the other integrators). This should be\n *      looked into further to ensure that there are no bugs introduced in the coefficients\n *      used.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <cmath>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Basics/testMacros.h\"\n\n#include \"Tudat/Mathematics/NumericalIntegrators/rungeKuttaCoefficients.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_runge_kutta_coefficients )\n\nusing numerical_integrators::RungeKuttaCoefficients;\n\nvoid checkValidityOfCoefficientSet( const RungeKuttaCoefficients::CoefficientSets& coefficientSet,\n                                    const double tolerance )\n{\n    // Declare coefficient set.\n    RungeKuttaCoefficients coefficients;\n    coefficients = coefficients.get( coefficientSet );\n\n    // Check that the sum of the b-coefficients for both the integrated order and the\n    // error-checking order is one.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                Eigen::VectorXd::Constant( 2, 1.0 ),\n                coefficients.bCoefficients.rowwise( ).sum( ), tolerance );\n\n    // Check that the first c-coefficient is zero.\n    BOOST_CHECK_SMALL( coefficients.cCoefficients( 0 ), tolerance );\n\n    // Check that the c-coefficient/a-coefficient relation holds.\n    for ( int i = 1; i < coefficients.cCoefficients.size( ); i++ )\n    {\n        if ( std::fabs( coefficients.cCoefficients( i ) ) < tolerance )\n        {\n            BOOST_CHECK_SMALL( coefficients.aCoefficients.row( i ).sum( ), tolerance );\n        }\n\n        else\n        {\n            BOOST_CHECK_CLOSE_FRACTION( coefficients.cCoefficients( i ),\n                                        coefficients.aCoefficients.row( i ).sum( ), tolerance );\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE( testRungeKuttaFehlberg45Coefficients )\n{\n    // Check validity of Runge-Kutta-Fehlberg 45 coefficients.\n    checkValidityOfCoefficientSet( RungeKuttaCoefficients::rungeKuttaFehlberg45, 1.0e-15 );\n}\n\nBOOST_AUTO_TEST_CASE( testRungeKuttaFehlberg78Coefficients )\n{\n    // Check validity of Runge-Kutta-Fehlberg 78 coefficients.\n    // Note, for some reason, the RKF78 set fails the unit test when the tolerance in\n    // checkValidityOfCoefficientSet() is set to lower than this value (rows 8 and 9 of\n    // aCoefficients matrix sum does not correspond to cCoefficient counterpart with tolerance less\n    // than 1.0e-14).\n    checkValidityOfCoefficientSet( RungeKuttaCoefficients::rungeKuttaFehlberg78, 1.0e-14 );\n}\n\nBOOST_AUTO_TEST_CASE( testRungeKutta87DormandAndPrinceCoefficients )\n{\n    // Check validity of Runge-Kutta 87 (Dormand and Prince) coefficients.\n    // Note, for some reason, the DOPRI8 set fails the unit test when the tolerance in\n    // checkValidityOfCoefficientSet() is set to lower than this value (row 10 of aCoefficients\n    // matrix sum does not correspond to cCoefficient counterpart with tolerance less than\n    // 1.0e-14).\n    checkValidityOfCoefficientSet( RungeKuttaCoefficients::rungeKutta87DormandPrince, 1.0e-14 );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "068adc3fba343ccec4642707d1c3b2e0bc3853bf", "size": 4088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/NumericalIntegrators/UnitTests/unitTestRungeKuttaCoefficients.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/NumericalIntegrators/UnitTests/unitTestRungeKuttaCoefficients.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/NumericalIntegrators/UnitTests/unitTestRungeKuttaCoefficients.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": 37.8518518519, "max_line_length": 99, "alphanum_fraction": 0.7086594912, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5509366330443335}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/erdos_renyi_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/graph_traits.hpp>\n\ntypedef boost::adjacency_list<> Graph;\ntypedef boost::erdos_renyi_iterator<boost::minstd_rand, Graph> ERGen;\n\nusing namespace boost;\n#include <random>\n#include <vector>\n#include<string>\n#include<iostream>\n#include<fstream>\nusing std::vector;\nusing std::string;\nint main()\n{\n    int nodes=100;\n    std::mt19937 weightgenerator { std::random_device{}() };\n    std::uniform_int_distribution<int> dist(1, nodes);\n    boost::minstd_rand prng(std::random_device{}());\n    // Create graph with 100 nodes and edges with probability 0.05\n    Graph g(ERGen(prng, nodes, 0.5), ERGen(), nodes);\n    auto vertex_idMap = get(boost::vertex_index, g);\n    boost::graph_traits <Graph>::vertex_iterator i, end;\n    boost::graph_traits <Graph>::adjacency_iterator ai, a_end;\n\n\n    vector<vector<int>> matrix(nodes);\n    for (auto& rows:matrix)\n    {\n        rows=vector<int>(nodes,-1);\n    }\n\n\n    for (boost::tie(i, end) = vertices(g); i != end; ++i) {\n        //std::cout << vertex_idMap[*i] << \": \";\n\n        for (boost::tie(ai, a_end) = adjacent_vertices(*i, g); ai != a_end; ++ai) {\n            weightgenerator.seed(std::random_device{}());\n            matrix[vertex_idMap[*i]][vertex_idMap[*ai]]=dist(weightgenerator);\n            //std::cout << vertex_idMap[*ai]<<'('<<matrix[vertex_idMap[*i]][vertex_idMap[*ai]]<<')';\n            //if (boost::next(ai) != a_end)\n               // std::cout << \", \";\n        }\n        //std::cout << std::endl;\n    }\n\n    // output matrix\n\n    std::ofstream of(\"tempMatrix.data\",std::ios::trunc);\n    of<<std::to_string(nodes)<<std::endl;\n    for (int i=1;i<nodes;i++) {\n        for(int j=0;j<i;j++){\n            if(matrix[i][j]!=-1)\n            {\n                of<<std::to_string(matrix[i][j]);\n            }else{\n                of<<'x';\n            }\n            if((j+1)==i){\n                of<<std::endl;\n            }else {\n                of<<' ';\n            }\n    }\n    }\n\n    return 0;\n}", "meta": {"hexsha": "a9c5458ffd385b439244e0fe1c403f64f151eecc", "size": 2101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/RandGraph/main.cpp", "max_stars_repo_name": "eddyxzc/shortest-path-tree", "max_stars_repo_head_hexsha": "de11bc7d9c7c262f50bb8cc6d4e197d1d0d9ef98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/RandGraph/main.cpp", "max_issues_repo_name": "eddyxzc/shortest-path-tree", "max_issues_repo_head_hexsha": "de11bc7d9c7c262f50bb8cc6d4e197d1d0d9ef98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/RandGraph/main.cpp", "max_forks_repo_name": "eddyxzc/shortest-path-tree", "max_forks_repo_head_hexsha": "de11bc7d9c7c262f50bb8cc6d4e197d1d0d9ef98", "max_forks_repo_licenses": ["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.5915492958, "max_line_length": 100, "alphanum_fraction": 0.5702046644, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.550936631737335}}
{"text": "/* Boost numeric test of the adams-bashforth steppers test file\n\n Copyright 2013 Karsten Ahnert\n Copyright 2013-2015 Mario Mulansky\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n*/\n\n// disable checked iterator warning for msvc\n#include <boost/config.hpp>\n#ifdef BOOST_MSVC\n    #pragma warning(disable:4996)\n#endif\n\n#define BOOST_TEST_MODULE numeric_adaptive_adams_bashforth_moulton\n\n#include <iostream>\n#include <cmath>\n\n#include <boost/array.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/vector.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\nnamespace mpl = boost::mpl;\n\ntypedef double value_type;\n\ntypedef boost::array< double , 2 > state_type;\ntypedef runge_kutta_fehlberg78<state_type> initializing_stepper;\n\n// harmonic oscillator, analytic solution x[0] = sin( t )\nstruct osc\n{\n    void operator()( const state_type &x , state_type &dxdt , const double t ) const\n    {\n        dxdt[0] = x[1];\n        dxdt[1] = -x[0];\n    }\n};\n\nBOOST_AUTO_TEST_SUITE( numeric_adaptive_adams_bashforth_moulton_test )\n\n\n/* generic test for all adams bashforth steppers */\ntemplate< class Stepper >\nstruct perform_adaptive_adams_bashforth_moulton_test\n{\n    void operator()( void )\n    {\n        Stepper stepper;\n        initializing_stepper init_stepper;\n\n        const int o = stepper.order()+1; //order of the error is order of approximation + 1\n\n        const state_type x0 = {{ 0.0 , 1.0 }};\n        state_type x1 = x0;\n        double t = 0.0;\n        double dt = 0.25;\n        // initialization, does a number of steps to self-start the stepper with a small stepsize\n        stepper.initialize( init_stepper, osc() , x1 , t ,  dt);\n        double A = std::sqrt( x1[0]*x1[0] + x1[1]*x1[1] );\n        double phi = std::asin(x1[0]/A) - t;\n        \n        // now we do the actual step\n        stepper.do_step( osc() , x1 , t , dt );\n        // only examine the error of the adams-bashforth step, not the initialization\n        const double f = 2.0 * std::abs( A*sin(t+dt+phi) - x1[0] ) / std::pow( dt , o ); // upper bound\n        \n        std::cout << o << \" , \" << f << std::endl;\n\n        /* as long as we have errors above machine precision */\n        while( f*std::pow( dt , o ) > 1E-16 )\n        {\n            x1 = x0;\n            t = 0.0;\n            stepper.initialize( init_stepper, osc() , x1 , t , dt );\n            A = std::sqrt( x1[0]*x1[0] + x1[1]*x1[1] );\n            phi = std::asin(x1[0]/A) - t;\n            // now we do the actual step\n            stepper.do_step( osc() , x1 , t , dt );\n            stepper.reset();\n            // only examine the error of the adams-bashforth step, not the initialization\n            std::cout << \"Testing dt=\" << dt << \" , \" << std::abs( A*sin(t+dt+phi) - x1[0] ) << std::endl;\n            BOOST_CHECK_LT( std::abs( A*sin(t+dt+phi) - x1[0] ) , f*std::pow( dt , o ) );\n            dt *= 0.5;\n        }\n    }\n};\n\ntypedef mpl::vector<\n    adaptive_adams_bashforth_moulton< 2 , state_type > ,\n    adaptive_adams_bashforth_moulton< 3 , state_type > ,\n    adaptive_adams_bashforth_moulton< 4 , state_type > ,\n    adaptive_adams_bashforth_moulton< 5 , state_type > ,\n    adaptive_adams_bashforth_moulton< 6 , state_type > ,\n    adaptive_adams_bashforth_moulton< 7 , state_type >\n    > adaptive_adams_bashforth_moulton_steppers;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( adaptive_adams_bashforth_moulton_test , Stepper, adaptive_adams_bashforth_moulton_steppers )\n{\n    perform_adaptive_adams_bashforth_moulton_test< Stepper > tester;\n    tester();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0932dd1dddfaa800f9c0813ba4f1b6da61c3538d", "size": 3697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/test/numeric/adaptive_adams_bashforth_moulton.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/odeint/test/numeric/adaptive_adams_bashforth_moulton.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/odeint/test/numeric/adaptive_adams_bashforth_moulton.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": 32.4298245614, "max_line_length": 123, "alphanum_fraction": 0.6432242359, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5509366291948755}}
{"text": "/*\n * Copyright 2020 Robert Bosch GmbH\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 * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * \\file cloe/utility/statistics_test.cpp\n * \\see  cloe/utility/statistics.hpp\n */\n\n#include <gtest/gtest.h>\n\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/median.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\nnamespace ba = boost::accumulators;\nnamespace tag = boost::accumulators::tag;\n\n#include <cloe/utility/statistics.hpp>\nusing cloe::utility::Accumulator;\nusing cloe::utility::Pie;\n\nTEST(utility_statistics_pie, with_int) {\n  std::vector<int> data{1, 1, 1, 1, 2, 2, 3, 4, 1, 2, 0, 3, 2};\n\n  Pie<int> pie;\n  for (auto x : data) {\n    pie.push_back(x);\n  }\n\n  EXPECT_EQ(1, pie.mode());\n  EXPECT_EQ(data.size(), pie.count());\n  EXPECT_EQ(static_cast<uint64_t>(2), pie.count(3));\n  EXPECT_EQ(static_cast<uint64_t>(4), pie.count(2));\n  EXPECT_EQ(static_cast<double>(5) / static_cast<double>(data.size()), pie.proportion(1));\n}\n\nTEST(utility_statistics_accumulator, with_double) {\n  std::vector<double> data{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};\n\n  Accumulator my_acc;\n  ba::accumulator_set<\n      double, ba::stats<tag::mean, tag::count, tag::max, tag::min, tag::variance, tag::median>>\n      ref_acc;\n  for (auto x : data) {\n    my_acc.push_back(x);\n    ref_acc(x);\n  }\n\n  EXPECT_EQ(ba::count(ref_acc), my_acc.count());\n  EXPECT_EQ(ba::min(ref_acc), my_acc.min());\n  EXPECT_EQ(ba::max(ref_acc), my_acc.max());  // NOLINT\n  EXPECT_EQ(ba::mean(ref_acc), my_acc.mean());\n  EXPECT_EQ(ba::variance(ref_acc), my_acc.variance());\n}\n", "meta": {"hexsha": "a8099120a2ea3e80dc1514f73f0c7b8788362195", "size": 2447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "runtime/src/cloe/utility/statistics_test.cpp", "max_stars_repo_name": "Sidharth-S-S/cloe", "max_stars_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T18:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:35:28.000Z", "max_issues_repo_path": "runtime/src/cloe/utility/statistics_test.cpp", "max_issues_repo_name": "Sidharth-S-S/cloe", "max_issues_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-20T10:13:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T12:27:19.000Z", "max_forks_repo_path": "runtime/src/cloe/utility/statistics_test.cpp", "max_forks_repo_name": "Sidharth-S-S/cloe", "max_forks_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T08:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T10:09:53.000Z", "avg_line_length": 31.7792207792, "max_line_length": 95, "alphanum_fraction": 0.7090314671, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5509366278878776}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2015 by Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include <iostream>\n#include <vector>\n#include <boost/tuple/tuple.hpp>\n\n#include <rokko/solver.hpp>\n#include <rokko/grid.hpp>\n#include <rokko/distributed_matrix.hpp>\n#include <rokko/localized_matrix.hpp>\n#include <rokko/utility/xyz_hamiltonian.hpp>\n#include <rokko/utility/xyz_hamiltonian_mpi.hpp>\n#include <rokko/collective.hpp>\n\nint main(int argc, char *argv[]) {\n  MPI_Init(&argc, &argv);\n  rokko::parallel_dense_solver solver;\n  solver.initialize(argc, argv);\n  rokko::grid g(MPI_COMM_WORLD);\n\n  int L = 4;\n  int num_bonds = L - 1;\n  std::vector<std::pair<int, int> > lattice;\n  std::vector<boost::tuple<double, double, double> > coupling;\n  for (int i=0; i<L-1; ++i) {\n    lattice.push_back(std::make_pair(i, i+1));\n    coupling.push_back(boost::make_tuple(1, 0.3, 0.2));\n  }\n\n  int myrank, nprocs;\n  MPI_Comm_size(MPI_COMM_WORLD, &nprocs);\n  MPI_Comm_rank(MPI_COMM_WORLD, &myrank);\n  MPI_Status status;\n  const int root = 0;\n  int ierr;\n\n  if (myrank == root) {\n    std::cout << \"L=\" << L << \" num_bonds=\" << num_bonds << std::endl;\n    for (int i=0; i<num_bonds; ++i) {\n      std::cout << lattice[i].first << \" \" << lattice[i].second << \" \" << coupling[i].get<0>()\n                << \" \" << coupling[i].get<1>() << \" \" << coupling[i].get<2>() << std::endl;\n    }\n  }\n  MPI_Barrier(MPI_COMM_WORLD);\n\n  int n = nprocs;\n  int p = -1;\n  do {\n    n /= 2;\n    ++p;\n  } while (n > 0);\n\n  if (nprocs != (1 << p)) {    \n    if ( myrank == 0 ) {\n      std::cout << \"This program can be run only for powers of 2\" << std::endl;\n    }\n    MPI_Abort(MPI_COMM_WORLD, 1);\n  }\n  int N = 1 << (L-p);\n\n  // creating column vectors which forms a heisenberg hamiltonian.\n  int N_seq = 1 << L;\n  std::vector<double> buffer(N);\n  for (int i=0; i<N; ++i) {\n    // sequential version\n    std::vector<double> v_seq, w_seq;\n    v_seq.assign(N_seq, 0);\n    v_seq[i] = 1;\n    w_seq.assign(N_seq, 0);\n    if (myrank == root) {\n      rokko::xyz_hamiltonian::multiply(L, lattice, coupling, v_seq, w_seq);\n      std::cout << \"sequential version:\" << std::endl;\n      for (int j=0; j<N_seq; ++j) {\n        std::cout << w_seq[j] << \" \";\n      }\n      std::cout << std::endl;\n    }\n    MPI_Barrier(MPI_COMM_WORLD);\n\n    // MPI version\n    std::vector<double> v, w;\n    v.assign(N, 0);\n    if (myrank == (i / N))\n      v[i % N] = 1;\n    w.assign(N, 0);\n    rokko::xyz_hamiltonian::multiply(MPI_COMM_WORLD, L, lattice, coupling, v, w, buffer);\n    for (int proc=0; proc<nprocs; ++proc) {\n      if (proc == myrank) {\n        std::cout << \"myrank=\" << myrank << std::endl;\n        for (int j=0; j<N; ++j) {\n          std::cout << w[j] << \" \";\n        }\n        std::cout << std::endl;\n      }\n      MPI_Barrier(MPI_COMM_WORLD);\n    }\n    if (myrank == root) {\n      std::cout << std::endl;\n    }\n  }\n\n  // test fill_diagonal of quantum heisenberg hamiltonian.\n  // sequential version\n  std::vector<double> w_seq;\n  w_seq.assign(N_seq, 0);\n  if (myrank == root) {\n    rokko::xyz_hamiltonian::fill_diagonal(L, lattice, coupling, w_seq);\n    std::cout << \"fill_diagonal sequential version:\" << std::endl;\n    for (int j=0; j<N_seq; ++j) {\n      std::cout << w_seq[j] << \" \";\n    }\n    std::cout << std::endl;\n  }\n  MPI_Barrier(MPI_COMM_WORLD);    \n  // MPI version\n  std::vector<double> w;\n  w.assign(N, 0);\n  if (myrank == root) {  \n    std::cout << \"fill_diagonal MPI version:\" << std::endl;\n  }\n  rokko::xyz_hamiltonian::fill_diagonal(MPI_COMM_WORLD, L, lattice, coupling, w);\n  for (int proc=0; proc<nprocs; ++proc) {\n    if (proc == myrank) {\n      std::cout << \"myrank=\" << myrank << std::endl;\n      for (int j=0; j<N; ++j) {\n        std::cout << w[j] << \" \";\n      }\n      std::cout << std::endl;\n    }\n    MPI_Barrier(MPI_COMM_WORLD);\n  }\n\n  // test for generate function\n  rokko::localized_matrix<rokko::matrix_col_major> lmat(N_seq, N_seq);\n  rokko::xyz_hamiltonian::generate(L, lattice, coupling, lmat);\n  \n  rokko::distributed_matrix<rokko::matrix_col_major> mat(N_seq, N_seq, g, solver);\n  rokko::xyz_hamiltonian::generate(L, lattice, coupling, mat);\n  rokko::localized_matrix<rokko::matrix_col_major> lmat_gather(N_seq, N_seq);\n  rokko::gather(mat, lmat_gather, root);\n\n  if (myrank == root) {\n    std:: cout << \"lmat:\" << std::endl << lmat << std::endl;\n    std:: cout << \"lmat_gather:\" << std::endl << lmat_gather << std::endl;\n    if (lmat_gather == lmat) {\n      std::cout << \"OK: distributed_matrix by 'generate' equals to a localized_matrix by 'generate'.\" << std::endl;\n    } else {\n      std::cout << \"ERROR: distributed_matrix by 'generate' is differnet from a localized_matrix by 'generate'.\"<< std::endl;\n      exit(1);\n    }\n  }\n\n  MPI_Finalize();\n  return 0;\n}\n", "meta": {"hexsha": "35eac8905ca0b6d7a55ba6b43d3b2d3f8055ca19", "size": 5126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/generate_matrix/xyz_mpi.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/generate_matrix/xyz_mpi.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/generate_matrix/xyz_mpi.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0666666667, "max_line_length": 125, "alphanum_fraction": 0.5848614904, "num_tokens": 1580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5509366278878776}}
{"text": "#include <metaSMT/DirectSolver_Context.hpp>\n#include <metaSMT/backend/Boolector.hpp>\n#include <metaSMT/support/cardinality.hpp>\n \n#include <metaSMT/support/run_algorithm.hpp>\n\n#include <boost/mpl/vector.hpp>\n#include <boost/format.hpp>\n#include <boost/foreach.hpp>\n\nusing namespace metaSMT;\nusing namespace metaSMT::logic;\nusing namespace metaSMT::solver;\nusing namespace std; \n\n#define foreach BOOST_FOREACH \n\ntemplate<typename Solver>\nstruct nqueens\n{\n  typedef bool result_type;\n  \n  nqueens ( unsigned size ) \n  {\n    field_size = size; \n    \n    init_field (); \n    field_constraints();\n  }\n\n  bool operator() ()\n  {\n    std::cout << \"Solving\" << std::endl; \n    bool sat = solve(ctx);\n    if(sat) print_solution();\n    return sat; \n  }\n\n  void init_field () \n  {\n    field.resize ( field_size ); \n\n    foreach ( vector<predicate>& row, field )\n    {\n      row.clear ();\n      for ( unsigned i = 0; i < field_size; i++ )\n      {\n        row.push_back ( new_variable () ); \n      }\n    }\n  }\n\n  void field_constraints() \n  {\n    for ( unsigned i = 0; i < field_size; ++i )\n    {\n      row ( i );\n      column ( i );\n\n      if(i != 0) \n      {\n      \tfalling ( i, 0 );\n        rising ( field_size-1, i );\n      }\n      rising ( i, 0 );\n      falling ( 0 , i );\n     \n    }\n  }\n\n  void falling(unsigned row, unsigned col)\n  {\n    std::vector<predicate> vec1;\n    while( row < field_size && col < field_size)\n    {\n    \n      vec1.push_back(field[row][col]);\n      \n      col++;\n      row++;\n    }\n    if( vec1.size() > 1 )\n    {\n      assertion( ctx, cardinality_leq( ctx, vec1, 1));\n    }\n  }\n\n  void rising(int row, int col)\n  {\n    std::vector<predicate> vec1;\n    while ( row >= 0 && col < static_cast<int>(field_size)  )\n    {\n      vec1.push_back(field[row][col]);\n      row--;\n      col++;\n    }\n    if(vec1.size() > 1)\n    {\n      assertion( ctx, cardinality_leq( ctx, vec1, 1));\n    }\n  }\n\n  void row ( unsigned row )\n  {\n    assertion ( ctx, one_hot( ctx , field[row] ) ); \n  }\n\n  void column ( unsigned col )\n  {\n    std::vector<predicate> vec1;\n    for ( unsigned i = 0; i < field_size; i++ )\n    {\n      vec1.push_back(field[i][col]);\n     \n    }\n    assertion( ctx, one_hot( ctx, vec1));\n    \n  }\n\n\n  void print_solution()\n  {\n    for (unsigned i = 0; i < field_size; ++i) {\n      for (unsigned k = 0; k < field_size; ++k) {\n        bool val = read_value(ctx, field[i][k]);\n        printf(\"%d\", val);\n      }\n      printf(\"\\n\");\n    }\n  }\n\n  Solver ctx; \n  unsigned field_size; \n  vector < vector < predicate > > field; \n};\n\nint\nmain(int argc, const char *argv[])\n{\n  typedef mpl::vector < \n      DirectSolver_Context < Boolector >\n      > SolverVec;\n\n  if( argc < 2) {\n    cout << \"usage: \"<< argv[0] << \" <size of the field>\" << endl;\n    exit(1);\n  }\n\n  unsigned solver = 0; //atoi ( argv[1] ); \n  unsigned size = atoi ( argv[1] ); \n\n\n  bool val = run_algorithm<SolverVec, nqueens> ( solver, size ); \n\n  std::cout << \"found solution? \" << (val ? \"yes\" : \"no\") << std::endl;\n\n  return 0;\n}\n\n", "meta": {"hexsha": "83ef7d2f3c71450ba226702d4fc4d6de19674be8", "size": 3009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox/n-queens/n-queens.cpp", "max_stars_repo_name": "finnhaedicke/metaSMT", "max_stars_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-04-09T14:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T08:55:58.000Z", "max_issues_repo_path": "toolbox/n-queens/n-queens.cpp", "max_issues_repo_name": "finnhaedicke/metaSMT", "max_issues_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-03-13T14:21:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-02T07:59:34.000Z", "max_forks_repo_path": "toolbox/n-queens/n-queens.cpp", "max_forks_repo_name": "finnhaedicke/metaSMT", "max_forks_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-04-22T18:10:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T12:44:12.000Z", "avg_line_length": 18.80625, "max_line_length": 71, "alphanum_fraction": 0.5486872715, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.550936614960969}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// contingency_table1.cpp                                                    //\n//                                                                           //\n//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#include <boost/test/test_tools.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <string>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/vector/vector10.hpp>\n#include <boost/mpl/detail/wrapper.hpp>\n#include <boost/typeof/typeof.hpp>\n#include <boost/fusion/include/make_map.hpp>\n#include <boost/fusion/container/map/detail/sequence_to_map.hpp>\n#include <boost/accumulators/framework/accumulator_set.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/assign/list_of.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/include/factor.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/include/cells.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/include/pearson_chisq/independence.hpp>\n\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/tag.hpp>\n\nvoid test_contingency_table1()\n{\n    namespace ac = boost::accumulators;\n\tnamespace ct = boost::statistics::detail::contingency_table;\n    namespace ps = ct::pearson_chi_square_statistic;\n\n    typedef double val_;\n    typedef boost::mpl::int_<0> x_; typedef int data_x_;\n    typedef boost::mpl::int_<1> y_; typedef std::string data_y_;\n    typedef boost::mpl::int_<2> z_; typedef int data_z_;\n \n    typedef boost::fusion::detail::sequence_to_map<\n        boost::mpl::vector6<x_,data_x_,y_,data_y_,z_,data_z_>\n    >::type sample_;\n    \n    typedef boost::mpl::vector2<x_,y_> keys_;\n    typedef ps::tag::independence_between<keys_> hypothesis_;\n    typedef ac::stats< hypothesis_> stats_;\n    typedef ac::accumulator_set< sample_, stats_, long int > acc_;\n        \n    using namespace boost::assign;\n    acc_ acc(( ct::_map_of_levels = boost::fusion::make_map<x_,y_>(\n        list_of(-1)(1), list_of(\"a\")(\"b\")(\"c\") ) ));\n    \n    {   \n        // Check levels \n     \tBOOST_CHECK( ct::cells_count<keys_>( acc ) == 2 * 3 );\n     \tBOOST_CHECK( ct::extract::levels<x_>( acc ).count( -1  ) == 1 );\n     \tBOOST_CHECK( ct::extract::levels<x_>( acc ).count(  1  ) == 1 );\n     \tBOOST_CHECK( ct::extract::levels<x_>( acc ).count(  2  ) == 0 );\n     \tBOOST_CHECK( ct::extract::levels<y_>( acc ).count( \"a\" ) == 1 );\n     \tBOOST_CHECK( ct::extract::levels<y_>( acc ).count( \"b\" ) == 1 );\n     \tBOOST_CHECK( ct::extract::levels<y_>( acc ).count( \"c\" ) == 1 );\n     \tBOOST_CHECK( ct::extract::levels<y_>( acc ).count( \"d\" ) == 0 );\n    }\n    {                                                                        //.....|.....|.....|.....|.....|.....|.....|\n                                                                             //     |non- |    x =    |       y =       |\n                                                                             //total|empty|...........|.................|\n        // Filling the cells                                                 //count|cells| -1  |  1  | \"a\" | \"b\" | \"c\" |\n        using namespace ac;                                 //.....|count|.....|.....|.....|.....|.....|\n        acc( boost::fusion::make_map<x_,y_,z_>( -1, \"a\", 1 ), weight = 1 );  //  1  |  1  |  1  |  0  |  1  |  0  |  0  |\n        acc( boost::fusion::make_map<x_,y_,z_>(  1, \"b\", 1 ), weight = 2 );  //  3  |  2  |  1  |  2  |  1  |  2  |  0  |\n    }\n    {   // Check degrees of freedom\n        // lost df = (r-1) + (c-1) = 1 + 2 = 3;\n        //  df = rc -r -c + 1 = 3 * 2 - 3  -2 + 1 = 2 \n        \n        typedef boost::mpl::detail::wrapper<hypothesis_> h0_;\n        BOOST_CHECK( ps::lost_degrees_of_freedom( h0_(), acc ) == 3 );\n        BOOST_CHECK( ps::degrees_of_freedom( h0_(),acc ) == 2 );\n    }\n    {\n        // Check cells \n        typedef boost::mpl::vector1<x_> vec_x_;\n        typedef boost::mpl::vector1<y_> vec_y_;   \n        std::size_t n;\n        n = ac::extract::weighted_count( acc );\n     \tBOOST_CHECK( n == 3 );\n\n        n = ct::non_empty_cells_count<vec_x_>(acc);\n        BOOST_CHECK( n == 2 );\n        n = ct::non_empty_cells_count<vec_y_>(acc);\n        BOOST_CHECK( n == 2 );\n        n = ct::non_empty_cells_count<keys_>( acc );\n        BOOST_CHECK( n == 2 );\n\n        n = ct::cells_count<vec_x_>(acc);\n        BOOST_CHECK( n == 2 );\n        n = ct::cells_count<vec_y_>(acc);\n        BOOST_CHECK( n == 3 );\n        n = ct::cells_count<keys_>( acc );\n        BOOST_CHECK( n == 6 );\n        \n        n = ct::count_matching<vec_x_>( \n            acc, boost::fusion::make_map<x_>( -1 ) );\n     \tBOOST_CHECK( n == 1 );\n        n = ct::count_matching<vec_x_>( \n            acc, boost::fusion::make_map<x_>( 1 ) );\n     \tBOOST_CHECK( n == 2 );\n        n = ct::count_matching<vec_y_>( \n            acc, boost::fusion::make_map<y_>( \"a\" ) );\n     \tBOOST_CHECK( n == 1 );\n        n = ct::count_matching<vec_y_>( \n            acc, boost::fusion::make_map<y_>( \"b\" ) );\n     \tBOOST_CHECK( n == 2 );\n        n = ct::count_matching<vec_y_>( \n            acc, boost::fusion::make_map<y_>( \"c\" ) );\n     \tBOOST_CHECK( n == 0 );\n        n = ct::count_matching<keys_>( acc,\n            boost::fusion::make_map<x_,y_,z_>( -1, \"a\", 1 ) );\n        BOOST_CHECK( n == 1 );\n        n = ct::count_matching<keys_>( acc, \n            boost::fusion::make_map<x_,y_,z_>(  1, \"b\", 1 ) );\n        BOOST_CHECK( n == 2 );\n    }\n\n}\n", "meta": {"hexsha": "e77300d0dd36c6168b1e2ad5b1b84040ab09f5ab", "size": 5774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "non_parametric/libs/statistics/detail/non_parametric/test/contingency_table1.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": "non_parametric/libs/statistics/detail/non_parametric/test/contingency_table1.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": "non_parametric/libs/statistics/detail/non_parametric/test/contingency_table1.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": 46.564516129, "max_line_length": 121, "alphanum_fraction": 0.5112573606, "num_tokens": 1588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410784, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5509052609382795}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n    @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_ACOTD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACOTD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the inverse cotangent in degree.\n\n\n    @par Header <boost/simd/function/acotd.hpp>\n\n    @par Note\n\n      For every parameter of floating type `acotd(x)`\n      returns the arc @c r in the interval  \\f$[0, 180[\\f$ such that\n      <tt>cotd(r) == x</tt>.\n\n    @see acot, acotpi, cotd\n\n\n    @par Example:\n\n      @snippet acotd.cpp acotd\n\n    @par Possible output:\n\n      @snippet acotd.txt acotd\n\n  **/\n  IEEEValue acotd(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acotd.hpp>\n#include <boost/simd/function/simd/acotd.hpp>\n\n#endif\n", "meta": {"hexsha": "451172e2dea29e428662634c390bed1f1760b278", "size": 1175, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acotd.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/acotd.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/acotd.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.0392156863, "max_line_length": 100, "alphanum_fraction": 0.5770212766, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893520001, "lm_q2_score": 0.6757646010190477, "lm_q1q2_score": 0.5509052579047193}}
{"text": "#include <boost/gil/image_view.hpp>\n#include <boost/gil/rgb.hpp>\n#include <boost/gil/pixel.hpp>\n#include <boost/gil/image_processing/numeric.hpp>\n\nnamespace boost{ namespace gil{\n/// \\defgroup ScalingAlgorithms\n/// \\brief Algorthims suitable for rescaling\n///\n/// These algorithms are used to improve image\n/// quality after image resizing is made.\n\n/// \\defgroup DownScalingAlgorithms\n/// \\ingroup ScalingAlgorithms\n/// \\brief Algorthims suitable for downscaling\n///\n/// These algorithms provide best results when used\n/// for downscaling. Using for upscaling will probably\n/// provide less than good results.\n\n\n/// \\brief a single step of lanczos downscaling\n/// \\ingroup DownScalingAlgorithms\n///\n/// Use this algorithm to scale down source image\n/// into a smaller image with reasonable quality.\n/// Do note that having a look at the output once\n/// is a good idea, since it might have ringing\n/// artifacts.\ntemplate <typename ImageView>\nvoid lanczos_at(\n    ImageView input_view,\n    ImageView output_view,\n    typename ImageView::x_coord_t source_x,\n    typename ImageView::y_coord_t source_y,\n    typename ImageView::x_coord_t target_x,\n    typename ImageView::y_coord_t target_y,\n    std::ptrdiff_t a)\n{\n    using x_coord_t = typename ImageView::x_coord_t;\n    using y_coord_t = typename ImageView::y_coord_t;\n    using pixel_t = typename std::remove_reference<\n                      decltype(std::declval<ImageView>()(0, 0))\n                    >::type;\n    // C++11 doesn't allow auto in lambdas\n    using channel_t = typename std::remove_reference<\n                        decltype(\n                            std::declval<pixel_t>().at(\n                                std::integral_constant<int, 0>{}\n                            )\n                        )\n                       >::type;\n    pixel_t result_pixel;\n    boost::gil::static_transform(result_pixel, result_pixel,\n        [](channel_t) { return static_cast<channel_t>(0); });\n    auto x_zero = static_cast<x_coord_t>(0);\n    auto x_one = static_cast<x_coord_t>(1);\n    auto y_zero = static_cast<y_coord_t>(0);\n    auto y_one = static_cast<y_coord_t>(1);\n\n    for (y_coord_t y_i = std::max(source_y - static_cast<y_coord_t>(a) + y_one, y_zero);\n         y_i <= std::min(source_y + static_cast<y_coord_t>(a), input_view.height() - y_one);\n         ++y_i)\n    {\n        for (x_coord_t x_i = std::max(source_x - static_cast<x_coord_t>(a) + x_one, x_zero);\n             x_i <= std::min(source_x + static_cast<x_coord_t>(a), input_view.width() - x_one);\n             ++x_i)\n        {\n            double lanczos_response = boost::gil::lanczos(source_x - x_i, a)\n                                      * boost::gil::lanczos(source_y - y_i, a);\n            auto op = [lanczos_response](channel_t prev, channel_t next)\n            {\n                return static_cast<channel_t>(prev + next * lanczos_response);\n            };\n            boost::gil::static_transform(result_pixel,\n                                         input_view(source_x, source_y),\n                                         result_pixel,\n                                         op);\n        }\n    }\n\n    output_view(target_x, target_y) = result_pixel;\n}\n\n/// \\brief Complete Lanczos algorithm\n/// \\ingroup DownScalingAlgorithms\n///\n/// This algorithm does full pass over\n/// resulting image and convolves pixels from\n/// original image. Do note that it might be a good\n/// idea to have a look at test output as there\n/// might be ringing artifacts.\n/// Based on wikipedia article:\n/// https://en.wikipedia.org/wiki/Lanczos_resampling\n/// with standardinzed cardinal sin (sinc)\ntemplate <typename ImageView>\nvoid scale_lanczos(ImageView input_view, ImageView output_view, std::ptrdiff_t a)\n{\n    double scale_x = (static_cast<double>(output_view.width()))\n                     / static_cast<double>(input_view.width());\n    double scale_y = (static_cast<double>(output_view.height()))\n                     / static_cast<double>(input_view.height());\n\n    using x_coord_t = typename ImageView::x_coord_t;\n    using y_coord_t = typename ImageView::y_coord_t;\n    for (y_coord_t y = 0; y < output_view.height(); ++y)\n    {\n        for (x_coord_t x = 0; x < output_view.width(); ++x)\n        {\n            boost::gil::lanczos_at(\n                input_view,\n                output_view,\n                x / scale_x,\n                y / scale_y,\n                x,\n                y,\n                a);\n        }\n    }\n}\n}}\n", "meta": {"hexsha": "3fcb07294384a6b8ef62cb3313952766f30fd3b8", "size": 4458, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/scaling.hpp", "max_stars_repo_name": "miralshah365/gil", "max_stars_repo_head_hexsha": "ee169ef104528b99e47186a01414b02e46416812", "max_stars_repo_licenses": ["BSL-1.0"], "max_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/scaling.hpp", "max_issues_repo_name": "miralshah365/gil", "max_issues_repo_head_hexsha": "ee169ef104528b99e47186a01414b02e46416812", "max_issues_repo_licenses": ["BSL-1.0"], "max_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/scaling.hpp", "max_forks_repo_name": "miralshah365/gil", "max_forks_repo_head_hexsha": "ee169ef104528b99e47186a01414b02e46416812", "max_forks_repo_licenses": ["BSL-1.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.5409836066, "max_line_length": 95, "alphanum_fraction": 0.608568865, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5509052411908388}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/optimization/non_smooth_newton/optimization_compute_inverse_D.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_non_smooth_newton_compute_inverse_D);\n\nBOOST_AUTO_TEST_CASE(test_case)\n{\n  typedef ublas::compressed_matrix<double> matrix_type;\n\n  matrix_type D;\n  matrix_type invD;\n  matrix_type I;\n\n  D.resize(6,6,false);\n  invD.resize(6,6,false);\n  I.resize(6,6,false);\n\n  D(0,0) = 1.0;  D(0,1) = 0.0;  D(0,2) = 0.0;  D(0,3) = 0.0;  D(0,4) = 0.0;  D(0,5) = 0.0;\n  D(1,0) = 2.0;  D(1,1) = 1.0;  D(1,2) = 0.0;  D(1,3) = 0.0;  D(1,4) = 0.0;  D(1,5) = 0.0;\n  D(2,0) = 3.0;  D(2,1) = 0.0;  D(2,2) = 1.0;  D(2,3) = 0.0;  D(2,4) = 0.0;  D(2,5) = 0.0;\n  D(3,0) = 0.0;  D(3,1) = 0.0;  D(3,2) = 0.0;  D(3,3) = 1.0;  D(3,4) = 0.0;  D(3,5) = 0.0;\n  D(4,0) = 0.0;  D(4,1) = 0.0;  D(4,2) = 0.0;  D(4,3) = 4.0;  D(4,4) = 1.0;  D(4,5) = 0.0;\n  D(5,0) = 0.0;  D(5,1) = 0.0;  D(5,2) = 0.0;  D(5,3) = 5.0;  D(5,4) = 0.0;  D(5,5) = 1.0;\n\n  invD = D;\n  OpenTissue::math::optimization::detail::compute_inverse_D( invD );\n\n  ublas::sparse_prod(D, invD, I);\n\n  double tol = 0.01;\n\n  BOOST_CHECK_CLOSE( double( I(0,0) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(0,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(0,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(0,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(0,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(0,5) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(1,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(1,1) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(1,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(1,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(1,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(1,5) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(2,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(2,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(2,2) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(2,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(2,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(2,5) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(3,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(3,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(3,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(3,3) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(3,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(3,5) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(4,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(4,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(4,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(4,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(4,4) ), double( 1.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(4,5) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(5,0) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(5,1) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(5,2) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(5,3) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(5,4) ), double( 0.0 ), tol );\n  BOOST_CHECK_CLOSE( double( I(5,5) ), double( 1.0 ), tol );\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "a5d39aa95089373f334838afa1d803dccdee3f56", "size": 3871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/compute_inverse_D/src/unit_compute_inverse_D.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/compute_inverse_D/src/unit_compute_inverse_D.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/compute_inverse_D/src/unit_compute_inverse_D.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 45.011627907, "max_line_length": 95, "alphanum_fraction": 0.6205114957, "num_tokens": 1572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.550905235123718}}
{"text": "\r\n#include \"cor_algorithm/sources/utilities.h\"\r\n#include \"cor_system/sources/logger.h\"\r\n#include \"cor_type/sources/math/matrix4x4_tmpl_impl.h\"\r\n\r\n#define BOOST_TEST_NO_LIB\r\n#include <boost/test/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_SUITE(matrix)\r\n\r\nBOOST_AUTO_TEST_CASE(matrix4x4)\r\n{\r\n    cor::type::Matrix4x4F rx = cor::type::Matrix4x4F::rot_x(30.0f);\r\n    cor::type::Matrix4x4F irx = cor::type::Matrix4x4F::rot_x(-30.0f);\r\n    cor::type::Matrix4x4F idt;\r\n    cor::type::Matrix4x4F rx0 = rx * irx;\r\n\r\n    cor::RString idts = cor::algorithm::join(idt, \",\");\r\n    cor::RString rx0s = cor::algorithm::join(rx0, \",\");\r\n    cor::RString rxs = cor::algorithm::join(rx, \",\");\r\n\r\n    cor::type::Matrix4x4F::iterator ip;\r\n    cor::type::Matrix4x4F::iterator jp;\r\n    cor::type::Matrix4x4F::iterator ied;\r\n\r\n    ip = idt.begin();\r\n    ied = idt.end();\r\n    jp = rx0.begin();\r\n\r\n    for(; ip != ied ; ip++, jp++)\r\n    {\r\n        BOOST_CHECK_CLOSE(*ip, *jp, 0.00001);\r\n    }\r\n\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "56fe9bcb29b2cbae9648def3f96596af4040481c", "size": 999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/sources/math/matrix_test.cpp", "max_stars_repo_name": "rmake/cor-engine", "max_stars_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T09:55:02.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-10T03:42:23.000Z", "max_issues_repo_path": "tests/unit/sources/math/matrix_test.cpp", "max_issues_repo_name": "rmake/cor-engine", "max_issues_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/unit/sources/math/matrix_test.cpp", "max_forks_repo_name": "rmake/cor-engine", "max_forks_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T02:30:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T06:56:49.000Z", "avg_line_length": 25.6153846154, "max_line_length": 70, "alphanum_fraction": 0.6296296296, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5507314426927324}}
{"text": "// Copyright (c) 2019 Graphcore Ltd. All rights reserved.\n#define BOOST_TEST_MODULE Train0MatmulTest\n\n#include <../random_util.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/test/unit_test.hpp>\n#include <filereader.hpp>\n#include <popart/builder.hpp>\n#include <popart/dataflow.hpp>\n#include <popart/devicemanager.hpp>\n#include <popart/inputshapeinfo.hpp>\n#include <popart/ndarraywrapper.hpp>\n#include <popart/op/identity.hpp>\n#include <popart/op/l1.hpp>\n#include <popart/session.hpp>\n#include <popart/sgd.hpp>\n#include <popart/tensorinfo.hpp>\n#include <popart/tensornames.hpp>\n#include <popart/testdevice.hpp>\n\n#include <algorithm>\n#include <map>\n#include <tuple>\n#include <vector>\n\n// Test:\n// C = matmul (A, B) where both A and B are weight matrices,\n// loss = lambda*|C|_1\nBOOST_AUTO_TEST_CASE(DatalessTrainingMatmul) {\n\n  // genPdf : generate of dot file pdf of the training computation\n  auto test = [](bool genPdf) {\n    using namespace popart;\n\n    // the dimensions of the matrices\n    int K = 6;\n    int M = 7;\n    int N = 8;\n\n    // we will generate random initializations\n    int seed = 1013;\n    DefaultRandomEngine eng(seed);\n    UniformRealDistribution<float> fdis(-4.f, 4.f);\n\n    // prepare a Builder for creating onnx model\n    auto bder   = Builder::create();\n    auto aiOnnx = bder->aiOnnxOpset9();\n\n    // matrix A of shape M x K\n    TensorInfo A_info{\"FLOAT\", std::vector<int64_t>{M, K}};\n    std::vector<float> v_A_init(A_info.nelms());\n    for (auto &val : v_A_init) {\n      val = fdis(eng);\n    }\n    TensorId A_id = bder->addInitializedInputTensor({v_A_init.data(), A_info});\n\n    // matrix B of shape K x N\n    TensorInfo B_info{\"FLOAT\", std::vector<int64_t>{K, N}};\n    std::vector<float> v_B_init(B_info.nelms());\n    for (auto &val : v_B_init) {\n      val = fdis(eng);\n    }\n    TensorId B_id = bder->addInitializedInputTensor({v_B_init.data(), B_info});\n\n    // matrix C = A * B (output of network)\n    TensorInfo C_info{\"FLOAT\", std::vector<int64_t>{M, N}};\n    TensorId C_id = aiOnnx.matmul({A_id, B_id});\n\n    // l1 loss with penalty term, will be applied to C\n    float lossLambda = 0.26;\n    auto l1          = bder->aiGraphcoreOpset1().l1loss(\n        {C_id}, lossLambda, ReductionType::Sum);\n\n    // compute the baseline\n    std::vector<float> v_C_data(C_info.nelms());\n    std::vector<float> v_C_grad(C_info.nelms());\n    for (int m = 0; m < M; ++m) {\n      for (int n = 0; n < N; ++n) {\n        int index       = m * N + n;\n        v_C_data[index] = 0;\n        for (int k = 0; k < K; ++k) {\n          v_C_data[index] += v_A_init[m * K + k] * v_B_init[k * N + n];\n        }\n        v_C_grad[index] = 2 * (v_C_data[index] > 0) - 1;\n        v_C_grad[index] *= lossLambda;\n      }\n    }\n\n    // gradients of A and B,\n    // dA = dC.BT\n    // dB = AT.dC\n    std::vector<float> v_A_grad(A_info.nelms(), 0);\n    std::vector<float> v_B_grad(B_info.nelms(), 0);\n    for (int m = 0; m < M; ++m) {\n      for (int n = 0; n < N; ++n) {\n        for (int k = 0; k < K; ++k) {\n          v_A_grad[m * K + k] += v_C_grad[m * N + n] * v_B_init[k * N + n];\n          v_B_grad[k * N + n] += v_C_grad[m * N + n] * v_A_init[m * K + k];\n        }\n      }\n    }\n\n    auto proto      = bder->getModelProto();\n    auto modelProto = io::getModelFromString(proto);\n    auto art        = AnchorReturnType(\"All\");\n    // one batch per step\n    int batchesPerStep = 1;\n    auto dataFlow      = DataFlow(batchesPerStep,\n                             {{C_id, art},\n                              {reservedGradientPrefix() + A_id, art},\n                              {reservedGradientPrefix() + B_id, art}});\n\n    auto device = popart::createTestDevice(TEST_TARGET);\n\n    auto opts            = SessionOptions();\n    opts.enableOutlining = true;\n    if (genPdf) {\n      opts.firstDotOp = 0;\n      opts.finalDotOp = 100;\n      opts.dotChecks.insert(\"Final\");\n      opts.logDir = \"./dotfiles\";\n      if (!boost::filesystem::exists(opts.logDir)) {\n        boost::filesystem::create_directories(opts.logDir);\n      }\n    }\n\n    // training info\n    float learnRate = 0.321;\n    auto optimizer  = ConstSGD(learnRate);\n\n    auto session = popart::TrainingSession::createFromOnnxModel(\n        proto,\n        dataFlow,\n        l1,\n        optimizer,\n        device,\n        popart::InputShapeInfo(),\n        opts,\n        popart::Patterns(PatternsLevel::Default));\n\n    // prepare the anchors. We have the output C,\n    std::vector<float> raw_C_out(C_info.nelms());\n    popart::NDArrayWrapper<float> C_wrapper(raw_C_out.data(), C_info.shape());\n\n    // the gradient of A,\n    std::vector<float> raw_A_grad_out(A_info.nelms());\n    popart::NDArrayWrapper<float> A_grad_wrapper(raw_A_grad_out.data(),\n                                                 A_info.shape());\n    // and the gradient of B.\n    std::vector<float> raw_B_grad_out(B_info.nelms());\n    popart::NDArrayWrapper<float> B_grad_wrapper(raw_B_grad_out.data(),\n                                                 B_info.shape());\n\n    std::map<popart::TensorId, popart::IArray &> anchors = {\n        {C_id, C_wrapper},\n        {reservedGradientPrefix() + A_id, A_grad_wrapper},\n        {reservedGradientPrefix() + B_id, B_grad_wrapper}};\n\n    session->prepareDevice();\n\n    // inputs:\n    popart::NDArrayWrapper<float> A_wrapper(v_A_init.data(), A_info);\n    popart::NDArrayWrapper<float> B_wrapper(v_B_init.data(), B_info);\n    std::map<popart::TensorId, popart::IArray &> inputs = {{A_id, A_wrapper},\n                                                           {B_id, B_wrapper}};\n\n    popart::StepIO stepio(inputs, anchors);\n\n    session->weightsFromHost();\n    session->run(stepio);\n\n    // confirm the gradient values agree (exactly...)\n    BOOST_CHECK_EQUAL_COLLECTIONS(\n        v_C_data.begin(), v_C_data.end(), raw_C_out.begin(), raw_C_out.end());\n\n    BOOST_CHECK_EQUAL_COLLECTIONS(v_A_grad.begin(),\n                                  v_A_grad.end(),\n                                  raw_A_grad_out.begin(),\n                                  raw_A_grad_out.end());\n\n    BOOST_CHECK_EQUAL_COLLECTIONS(v_B_grad.begin(),\n                                  v_B_grad.end(),\n                                  raw_B_grad_out.begin(),\n                                  raw_B_grad_out.end());\n\n    // we will read the updated weights back, and check that they are correct\n    std::vector<float> v_A_updated_baseline = v_A_init;\n    std::vector<float> v_B_updated_baseline = v_B_init;\n    for (int k = 0; k < K; ++k) {\n      for (int n = 0; n < N; ++n) {\n        v_B_updated_baseline[k * N + n] -= learnRate * v_B_grad[k * N + n];\n      }\n\n      for (int m = 0; m < M; ++m) {\n        v_A_updated_baseline[m * K + k] -= learnRate * v_A_grad[m * K + k];\n      }\n    }\n    WeightsIO weightsRead;\n    // to be readback:\n    std::vector<float> A_readback(A_info.nelms(), -9.0f);\n    std::vector<float> B_readback(B_info.nelms(), -99.0f);\n    weightsRead.insert(A_id, {A_readback.data(), A_info});\n    weightsRead.insert(B_id, {B_readback.data(), B_info});\n\n    session->weightsToHost();\n    session->readWeights(weightsRead);\n\n    BOOST_CHECK_EQUAL_COLLECTIONS(v_A_updated_baseline.begin(),\n                                  v_A_updated_baseline.end(),\n                                  A_readback.begin(),\n                                  A_readback.end());\n\n    BOOST_CHECK_EQUAL_COLLECTIONS(v_B_updated_baseline.begin(),\n                                  v_B_updated_baseline.end(),\n                                  B_readback.begin(),\n                                  B_readback.end());\n\n    // dot -Tpdf -o final.pdf final.dot\n    if (genPdf) {\n      for (auto dot_string : opts.dotChecks) {\n        std::stringstream command_ss;\n        command_ss << \"dot \"\n                   << \" -Tpdf \"\n                   << \" -o \"\n                   << io::appendDirFn(opts.logDir, dot_string + \".pdf\") << \" \"\n                   << io::appendDirFn(opts.logDir, dot_string + \"_r.dot\");\n        std::string command = command_ss.str();\n        int ran             = std::system(command.c_str());\n        std::cout << command << \" returned with status \" << ran << std::endl;\n        BOOST_CHECK(ran == 0);\n        auto pdfFileNames =\n            io::getMatchFns(io::getCanonicalDirName(opts.logDir), \".pdf\");\n        BOOST_CHECK(pdfFileNames.size() == 1);\n      }\n    }\n  };\n\n  // should only be true for debugging (on a machine with dot program)\n  bool genPdf = false;\n  test(genPdf);\n}\n", "meta": {"hexsha": "0ec9afceed68723d0beb47a634e54b29eada7d22", "size": 8431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/integration/matmul_tests/dataless0_train_matmul_test.cpp", "max_stars_repo_name": "graphcore/popart", "max_stars_repo_head_hexsha": "15ce5b098638dc34a4d41ae2a7621003458df798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:51.000Z", "max_issues_repo_path": "tests/integration/matmul_tests/dataless0_train_matmul_test.cpp", "max_issues_repo_name": "graphcore/popart", "max_issues_repo_head_hexsha": "15ce5b098638dc34a4d41ae2a7621003458df798", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-25T01:30:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T11:13:14.000Z", "max_forks_repo_path": "tests/integration/matmul_tests/dataless0_train_matmul_test.cpp", "max_forks_repo_name": "graphcore/popart", "max_forks_repo_head_hexsha": "15ce5b098638dc34a4d41ae2a7621003458df798", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:33:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T06:55:00.000Z", "avg_line_length": 34.8388429752, "max_line_length": 79, "alphanum_fraction": 0.5732416084, "num_tokens": 2215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5506543272729544}}
{"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": "#pragma once\n\n#include <ros/ros.h>\n\n#include <memory>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\n#include \"dynamic_motion_planner/chomp_trajectory.hpp\"\n#include \"utils/utility_functions.hpp\"\n\nnamespace hdi_plan {\nclass ChompCost {\npublic:\n\tChompCost(const std::shared_ptr<ChompTrajectory>& trajectory, const std::vector<double>& derivative_costs, double ridge_factor = 0.0);\n\t~ChompCost();\n\n\tdouble getMaxQuadCostInvValue() const {\n\t\treturn this->quad_cost_inv_.maxCoeff();\n\t};\n\tEigen::MatrixXd getQuadraticCostInverse() const {\n\t\treturn this->quad_cost_inv_;\n\t}\n\tEigen::MatrixXd getQuadraticCost() const {\n\t\treturn this->quad_cost_;\n\t}\n\tvoid scale(double scale);\n\tdouble getCost(const Eigen::MatrixXd::ColXpr& joint_trajectory) const;\n\n\tEigen::MatrixXd getDerivative(const Eigen::MatrixXd::ColXpr& joint_trajectory) const;\nprivate:\n\tEigen::MatrixXd quad_cost_full_;\n\tEigen::MatrixXd quad_cost_;\n\tEigen::MatrixXd quad_cost_inv_;\n\n\tEigen::MatrixXd getDiffMatrix(int size, const double* diff_rule) const;\n\n};\n}", "meta": {"hexsha": "8840e20c31791f559f92f360bfe15bc4fcf62ab3", "size": 1039, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dynamic_motion_planner/chomp_cost.hpp", "max_stars_repo_name": "test-bai-cpu/hdi_plan", "max_stars_repo_head_hexsha": "89684bb73832d7e40f3c669f284ffddb56a1e299", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T12:34:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T12:34:11.000Z", "max_issues_repo_path": "include/dynamic_motion_planner/chomp_cost.hpp", "max_issues_repo_name": "test-bai-cpu/hdi_plan", "max_issues_repo_head_hexsha": "89684bb73832d7e40f3c669f284ffddb56a1e299", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dynamic_motion_planner/chomp_cost.hpp", "max_forks_repo_name": "test-bai-cpu/hdi_plan", "max_forks_repo_head_hexsha": "89684bb73832d7e40f3c669f284ffddb56a1e299", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-08T13:27:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T07:59:04.000Z", "avg_line_length": 25.3414634146, "max_line_length": 135, "alphanum_fraction": 0.77093359, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5506098111903232}}
{"text": "#define BOOST_TEST_MODULE FourierTransformTest\n#include <boost/test/unit_test.hpp>\n\n// For IO\n#include <stdlib.h>\n#include <math.h>\n#include <iostream>\n#include <unistd.h>\n\n// For measuring elapsed time\n#include <chrono>\n\n// For Random Float Generator\n#include <time.h>\n\n// For object under test\n#include \"ofdmcodec.h\"\n#include \"common.h\"\n\n#define CONFIDENCE_INTERVAL 0.0000000000001\n\n// Integration Tests \nBOOST_AUTO_TEST_SUITE(IntegrationTests)\n\n/**\n*  This test simulates entire encoding and decoding process\n*  of only one symbol, this test does not transmit the data \n*  through a physical medium.\n* \n*/\nBOOST_AUTO_TEST_CASE(EncodeDecode)\n{\n    printf(\"Testing OFDM Encoder & Decoder Object...\\n\");\n    // Initialize ofdm coder setting structs and objects\n    OFDMSettings encoderSettings; \n    encoderSettings.type = FFTW_BACKWARD;\n    encoderSettings.EnergyDispersalSeed = 0;\n    encoderSettings.nPoints = 512; \n\tencoderSettings.pilotToneStep = 8; \n    encoderSettings.pilotToneAmplitude = 2.0; \n    encoderSettings.guardInterval = 0; \n    encoderSettings.QAMSize = 2; \n    encoderSettings.cyclicPrefixSize = 128; \n\n    OFDMSettings decoderSettings = encoderSettings;\n    decoderSettings.type = FFTW_FORWARD;\n\n    OFDMCodec encoder(encoderSettings);\n    OFDMCodec decoder(decoderSettings);\n\n    size_t symbolSize = (encoderSettings.nPoints*2);\n    size_t symbolSizeWithPrefix = symbolSize + encoderSettings.cyclicPrefixSize;\n    size_t rxSignalSize = symbolSizeWithPrefix * 10;\n    size_t rxLastAllowedIndex = symbolSizeWithPrefix * 9;\n\n    // Randomly generated prefix start position\n    size_t prefixStart = rand() % rxLastAllowedIndex;\n    printf(\"Randomly Generated Prefix Start = %lu\\n\",prefixStart);\n\n    // Calculate max nBytes \n    size_t nAvaiablePoints = (encoderSettings.nPoints - ((size_t)(encoderSettings.nPoints / encoderSettings.pilotToneStep)));\n    size_t nBytes = (nAvaiablePoints*encoderSettings.QAMSize) / 8;\n\n    std::cout << \"Encoding nBytes = \" << nBytes << std::endl;\n\n    // Byte input & output buffers\n    ByteVec txIn(nBytes);\n    ByteVec rxOut(nBytes);\n\n    // Signal buffer \n    DoubleVec txData(symbolSizeWithPrefix);\n    DoubleVec rxSignal(rxSignalSize);\n\n    // Setup random byte generator\n    srand( (unsigned)time( NULL ) );\n\n    // Generate array of random bytes\n    for (size_t i = 0; i < nBytes; i++)\n    {\n        txIn[i] = rand() % 255;\n    }\n\n    // Encode 1 ofdm symbol\n    auto start = std::chrono::steady_clock::now();\n    txData = encoder.Encode(txIn, nBytes);\n    auto end = std::chrono::steady_clock::now();\n\n    std::cout << \"Encode elapsed time: \"\n    << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()\n    << \" ns\" << std::endl;\n\n    // Copy the symbol with prefix into Rx signal buffer\n    std::copy(txData.begin(), txData.begin()+symbolSizeWithPrefix, rxSignal.begin()+prefixStart);\n\n    // Check the smybol has been copied correctly\n    for (size_t i = 0; i < encoderSettings.nPoints*2; i++)\n    {\n        //printf(\"Copied vs encoded sample: %lu %+9.5f vs. %+9.5f\\n\",\n        //i, rxSignal[prefixStart+i], txData[i]);\n        \n        // Check if real and complex element match within defined precision of each other\n        BOOST_CHECK_MESSAGE( (rxSignal[prefixStart+i]  == txData[i] ), \"Copied Symbol differs!\" ); \n    }\n\n    // Decode\n    start = std::chrono::steady_clock::now();\n    rxOut = decoder.Decode(rxSignal, nBytes);\n    end = std::chrono::steady_clock::now();\n\n    std::cout << \"Decode elapsed time: \"\n    << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()\n    << \" ns\" << std::endl;\n    \n    // Check the input and output are within threshold\n    for (size_t i = 0; i < nBytes; i++)\n    {\n        //printf(\"Recovered Sample: %lu %d vs. %d\\n\", i, txIn[i], rxOut[i]);\n        \n        // Check if real and complex element match within defined precision of each other\n        //BOOST_CHECK_MESSAGE( (txIn[i] == rxOut[i]), \"Bytes difffer!\" ); \n    }\n    \n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "bf76929c8e9c43041b8098ab63ea6c195382909b", "size": 4007, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/integration/IntegrationTests.cpp", "max_stars_repo_name": "krogk/ofdmlib", "max_stars_repo_head_hexsha": "7eddfdfde17624bf7674dda33ddc43b308c07765", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T10:44:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T14:20:05.000Z", "max_issues_repo_path": "test/integration/IntegrationTests.cpp", "max_issues_repo_name": "krogk/ofdmlib", "max_issues_repo_head_hexsha": "7eddfdfde17624bf7674dda33ddc43b308c07765", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-11T12:50:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-11T12:51:02.000Z", "max_forks_repo_path": "test/integration/IntegrationTests.cpp", "max_forks_repo_name": "krogk/ofdmlib", "max_forks_repo_head_hexsha": "7eddfdfde17624bf7674dda33ddc43b308c07765", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-03T14:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T14:56:19.000Z", "avg_line_length": 32.056, "max_line_length": 125, "alphanum_fraction": 0.6790616421, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5506098071221992}}
{"text": "#ifndef INCLUDED_PDS_DENSITY_HPP\n#define INCLUDED_PDS_DENSITY_HPP\n\n#include <Danvil/Tools/FunctionCache.h>\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace density\n{\n\n\t/** Loads a density function from a file (image or tsv) */\n\tEigen::MatrixXf LoadDensity(const std::string& fn);\n\n\t/** Saves a density function to a file (image or tsv) */\n\tvoid SaveDensity(const std::string& fn, const Eigen::MatrixXf& m);\n\n\tconstexpr float KernelRange = 2.5f;\n\tconstexpr float cPi = 3.141592654f;\n\n\tinline float KernelImpl(float d) {\n\t\treturn std::exp(-cPi*d*d);\n\t}\n\n\tinline float Kernel(float d) {\n\t\tstatic Danvil::FunctionCache<float,1> cache(0.0f, KernelRange, &KernelImpl);\n\t\treturn cache(std::abs(d));\n\t}\n\n\tinline float KernelSquareImpl(float d2) {\n\t\treturn std::exp(-cPi*d2);\n\t}\n\n\tinline float KernelSquare(float d2) {\n\t\tstatic Danvil::FunctionCache<float,1> cache(0.0f, KernelRange*KernelRange, &KernelSquareImpl);\n\t\treturn cache(d2);\n\t}\n\n\t/** Computes density approximation for a set of points  */\n\tEigen::MatrixXf PointDensity(const std::vector<Eigen::Vector2f>& points, const Eigen::MatrixXf& density);\n\n}\n\n#endif\n", "meta": {"hexsha": "7432a0fb86ebb60ccaf4a29fec48587ba87d7a59", "size": 1112, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp_density/density/PointDensity.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_density/density/PointDensity.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_density/density/PointDensity.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": 25.2727272727, "max_line_length": 106, "alphanum_fraction": 0.7275179856, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5506098030540741}}
{"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 (c) 2019 INRIA\n//\n\n#include <pinocchio/math/quaternion.hpp>\n#include <pinocchio/spatial/se3.hpp>\n\n#include <boost/variant.hpp> // to avoid C99 warnings\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_assignQuaternion)\n{\n  using namespace pinocchio;\n  const int max_tests = 1e5;\n  for(int k = 0; k < max_tests; ++k)\n  {\n    const SE3 M(SE3::Random());\n    SE3::Quaternion quat_ref(M.rotation());\n    \n    SE3::Quaternion quat;\n    quaternion::assignQuaternion(quat,M.rotation());\n    \n    BOOST_CHECK(quat.coeffs().isApprox(quat_ref.coeffs()));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_uniformRandom)\n{\n  srand(0);\n\n  using namespace pinocchio;\n  Eigen::Quaternion<double> q;\n\n  for (int i = 0; i < (1 << 10); ++i) {\n    quaternion::uniformRandom(q);\n    BOOST_CHECK_MESSAGE((q.coeffs().array().abs() <= 1).all(),\n        \"Quaternion coeffs out of bounds: \" << i << ' ' << q.coeffs().transpose());\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "18d15c53d2373b5924d2f318e14e88672edab813", "size": 1035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/quaternion.cpp", "max_stars_repo_name": "ikalevatykh/pinocchio", "max_stars_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittest/quaternion.cpp", "max_issues_repo_name": "ikalevatykh/pinocchio", "max_issues_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/quaternion.cpp", "max_forks_repo_name": "ikalevatykh/pinocchio", "max_forks_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "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": 22.0212765957, "max_line_length": 83, "alphanum_fraction": 0.6743961353, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5505073204725307}}
{"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": "#pragma once\n\n#include <cmath>\n\n#include <ros/ros.h>\n#include <ct/optcon/optcon.h>\n#include <lqr_controller/declarations_euler.hpp>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Geometry>\n\nnamespace LQR {\nclass LQR_Solver {\n  public:\n    /*!\n     * Constructor.\n     * @param nodeHandle the ROS node handle.\n     */\n    LQR_Solver(ros::NodeHandle& nodeHandle);\n\n    /*!\n     * Destructor.\n     */\n    virtual ~LQR_Solver();\n\n    control_vector_t output;\n\n\n    ct::core::FeedbackMatrix<nStates, nControls> K_;\n    control_vector_t uref_;\n    state_vector_t xerror;\n\n   private:\n\n    /*!\n     * ROS topic callback method.\n     * @param message the received message.\n     */\n    void topicCallback(const nav_msgs::Odometry::ConstPtr& msg);\n\n    //! ROS node handle.\n    ros::NodeHandle& nodeHandle_;\n\n    //! ROS topic subscriber.\n    ros::Subscriber subscriber_;\n\n    //! ROS topic name to subscribe to.\n    std::string subscriberTopic_;\n\n    //! State and control matrix dimensions\n    const size_t state_dim = nStates;\n    const size_t control_dim = nControls;\n\n\n\n    control_vector_t u_;\n\n\n    state_matrix_t A_;\n    control_gain_matrix_t B_;\n    ros::Time callBack_;\n    state_vector_t x_;\n    state_vector_t xref_;\n\n    ct::optcon::TermQuadratic<nStates, nControls> quadraticCost_;\n    ct::optcon::TermQuadratic<nStates, nControls>::state_matrix_t Q_;\n    ct::optcon::TermQuadratic<nStates, nControls>::control_matrix_t R_;\n    ct::optcon::LQR<nStates, nControls> lqrSolver_;\n\n\n    state_matrix_t A_quadrotor(const state_vector_t& x, const control_vector_t& u);\n    control_gain_matrix_t B_quadrotor(const state_vector_t& x, const control_vector_t& u);\n  };\n\n} /* namespace */\n", "meta": {"hexsha": "e3c5ed04755cb28c97e3e400e8d481241ba1be92", "size": 1681, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lqr_controller/LQR_Solver.hpp", "max_stars_repo_name": "llanesc/lqr-tracking", "max_stars_repo_head_hexsha": "270f2f5164a668bfb77e19f5191595f1d3913a16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-17T10:00:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T22:17:36.000Z", "max_issues_repo_path": "include/lqr_controller/LQR_Solver.hpp", "max_issues_repo_name": "llanesc/lqr-tracking", "max_issues_repo_head_hexsha": "270f2f5164a668bfb77e19f5191595f1d3913a16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-30T18:12:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-28T05:08:35.000Z", "max_forks_repo_path": "include/lqr_controller/LQR_Solver.hpp", "max_forks_repo_name": "llanesc/lqr-tracking", "max_forks_repo_head_hexsha": "270f2f5164a668bfb77e19f5191595f1d3913a16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-04-22T09:00:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:33:58.000Z", "avg_line_length": 22.4133333333, "max_line_length": 90, "alphanum_fraction": 0.6900654372, "num_tokens": 423, "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": "#include <igl/barycenter.h>\n#include <igl/boundary_facets.h>\n#include <igl/parula.h>\n#include <igl/readMESH.h>\n#include <igl/slice.h>\n#include <igl/slice_tets.h>\n#include <igl/winding_number.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <Eigen/Sparse>\n#include <iostream>\n\n#include \"tutorial_shared_path.h\"\n\nEigen::MatrixXd V,BC;\nEigen::VectorXd W;\nEigen::MatrixXi T,F,G;\ndouble slice_z = 0.5;\nenum OverLayType\n{\n  OVERLAY_NONE = 0,\n  OVERLAY_INPUT = 1,\n  OVERLAY_OUTPUT = 2,\n  NUM_OVERLAY = 3,\n} overlay = OVERLAY_NONE;\n\nvoid update_visualization(igl::opengl::glfw::Viewer & viewer)\n{\n  using namespace Eigen;\n  using namespace std;\n  Eigen::Vector4d plane(\n    0,0,1,-((1-slice_z)*V.col(2).minCoeff()+slice_z*V.col(2).maxCoeff()));\n  MatrixXd V_vis;\n  MatrixXi F_vis;\n  VectorXi J;\n  {\n    SparseMatrix<double> bary;\n    // Value of plane's implicit function at all vertices\n    const VectorXd IV = \n      (V.col(0)*plane(0) + \n        V.col(1)*plane(1) + \n        V.col(2)*plane(2)).array()\n      + plane(3);\n    igl::slice_tets(V,T,IV,V_vis,F_vis,J,bary);\n  }\n  VectorXd W_vis;\n  igl::slice(W,J,W_vis);\n  MatrixXd C_vis;\n  // color without normalizing\n  igl::parula(W_vis,false,C_vis);\n\n\n  const auto & append_mesh = [&C_vis,&F_vis,&V_vis](\n    const Eigen::MatrixXd & V,\n    const Eigen::MatrixXi & F,\n    const RowVector3d & color)\n  {\n    F_vis.conservativeResize(F_vis.rows()+F.rows(),3);\n    F_vis.bottomRows(F.rows()) = F.array()+V_vis.rows();\n    V_vis.conservativeResize(V_vis.rows()+V.rows(),3);\n    V_vis.bottomRows(V.rows()) = V;\n    C_vis.conservativeResize(C_vis.rows()+F.rows(),3);\n    C_vis.bottomRows(F.rows()).rowwise() = color;\n  };\n  switch(overlay)\n  {\n    case OVERLAY_INPUT:\n      append_mesh(V,F,RowVector3d(1.,0.894,0.227));\n      break;\n    case OVERLAY_OUTPUT:\n      append_mesh(V,G,RowVector3d(0.8,0.8,0.8));\n      break;\n    default:\n      break;\n  }\n  viewer.data().clear();\n  viewer.data().set_mesh(V_vis,F_vis);\n  viewer.data().set_colors(C_vis);\n  viewer.data().set_face_based(true);\n}\n\nbool key_down(igl::opengl::glfw::Viewer& viewer, unsigned char key, int mod)\n{\n  switch(key)\n  {\n    default:\n      return false;\n    case ' ':\n      overlay = (OverLayType)((1+(int)overlay)%NUM_OVERLAY);\n      break;\n    case '.':\n      slice_z = std::min(slice_z+0.01,0.99);\n      break;\n    case ',':\n      slice_z = std::max(slice_z-0.01,0.01);\n      break;\n  }\n  update_visualization(viewer);\n  return true;\n}\n\nint main(int argc, char *argv[])\n{\n  using namespace Eigen;\n  using namespace std;\n\n  cout<<\"Usage:\"<<endl;\n  cout<<\"[space]  toggle showing input mesh, output mesh or slice \"<<endl;\n  cout<<\"         through tet-mesh of convex hull.\"<<endl;\n  cout<<\"'.'/','  push back/pull forward slicing plane.\"<<endl;\n  cout<<endl;\n\n  // Load mesh: (V,T) tet-mesh of convex hull, F contains facets of input\n  // surface mesh _after_ self-intersection resolution\n  igl::readMESH(TUTORIAL_SHARED_PATH \"/big-sigcat.mesh\",V,T,F);\n\n  // Compute barycenters of all tets\n  igl::barycenter(V,T,BC);\n\n  // Compute generalized winding number at all barycenters\n  cout<<\"Computing winding number over all \"<<T.rows()<<\" tets...\"<<endl;\n  igl::winding_number(V,F,BC,W);\n\n  // Extract interior tets\n  MatrixXi CT((W.array()>0.5).count(),4);\n  {\n    size_t k = 0;\n    for(size_t t = 0;t<T.rows();t++)\n    {\n      if(W(t)>0.5)\n      {\n        CT.row(k) = T.row(t);\n        k++;\n      }\n    }\n  }\n  // find bounary facets of interior tets\n  igl::boundary_facets(CT,G);\n  // boundary_facets seems to be reversed...\n  G = G.rowwise().reverse().eval();\n\n  // normalize\n  W = (W.array() - W.minCoeff())/(W.maxCoeff()-W.minCoeff());\n\n  // Plot the generated mesh\n  igl::opengl::glfw::Viewer viewer;\n  update_visualization(viewer);\n  viewer.callback_key_down = &key_down;\n  viewer.launch();\n}\n", "meta": {"hexsha": "418ad90d0f11ca7b62d1dc567e1c99436479af9c", "size": 3800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FSDF/libs/libigl-master/tutorial/702_WindingNumber/main.cpp", "max_stars_repo_name": "szat/FSDF", "max_stars_repo_head_hexsha": "076129c0dfd2ac2354cc40ade363b96f4b6248fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FSDF/libs/libigl-master/tutorial/702_WindingNumber/main.cpp", "max_issues_repo_name": "szat/FSDF", "max_issues_repo_head_hexsha": "076129c0dfd2ac2354cc40ade363b96f4b6248fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FSDF/libs/libigl-master/tutorial/702_WindingNumber/main.cpp", "max_forks_repo_name": "szat/FSDF", "max_forks_repo_head_hexsha": "076129c0dfd2ac2354cc40ade363b96f4b6248fa", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 76, "alphanum_fraction": 0.6381578947, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5505073084264758}}
{"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 <algorithm>\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n#include <complex>\n#include <iostream>\n#include \"../../JeanBaptiste/include/basic/SineCosine.h\"\n#include <memory>\n#include <string>\n\nnamespace constants = boost::math::constants;\nnamespace jb = jeanbaptiste;\nnamespace jbb = jeanbaptiste::basic;\nnamespace ut = boost::unit_test;\n\nclass SinCosFixture\n{\npublic:\n    SinCosFixture()\n    {}\n\n    ~SinCosFixture()\n    {}\n};\n\n\nBOOST_FIXTURE_TEST_SUITE(SinCosTestSuite, SinCosFixture)\n\n    BOOST_AUTO_TEST_CASE(float_sine_from_minus_2pi_to_plus_2_pi)\n    {\n        BOOST_TEST_MESSAGE(\"Running sine computation in float range [-2pi ... 2pi].\");\n\n        for (float x = -constants::two_pi<float>(); x <=constants::two_pi<float>(); x += 0.1)\n            BOOST_TEST(std::fabs(std::sin(x) - jbb::sine<float>(x)) < 0.00001);\n    }\n\n    BOOST_AUTO_TEST_CASE(double_sine_from_minus_2pi_to_plus_2_pi)\n    {\n        BOOST_TEST_MESSAGE(\"Running sine computation in double range [-2pi ... 2pi].\");\n\n        for (double x = -constants::two_pi<double>(); x <=constants::two_pi<double>(); x += 0.1)\n            BOOST_TEST(std::fabs(std::sin(x) - jbb::sine<double>(x)) < 0.000000000001);\n    }\n\n    BOOST_AUTO_TEST_CASE(float_cosine_from_minus_2pi_to_plus_2_pi)\n    {\n        BOOST_TEST_MESSAGE(\"Running cosine computation in float range [-2pi ... 2pi].\");\n\n        for (float x = -constants::two_pi<float>(); x <=constants::two_pi<float>(); x += 0.1)\n            BOOST_TEST(std::fabs(std::cos(x) - jbb::cosine<float>(x)) < 0.0001);\n    }\n\n    BOOST_AUTO_TEST_CASE(double_cosine_from_minus_2pi_to_plus_2_pi)\n    {\n        BOOST_TEST_MESSAGE(\"Running cosine computation in double range [-2pi ... 2pi].\");\n\n        for (double x = -constants::two_pi<double>(); x <=constants::two_pi<double>(); x += 0.1)\n            BOOST_TEST(std::fabs(std::cos(x) - jbb::cosine<double>(x)) < 0.00000000001);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "8439697d774bab889c41b5a11ea846df5e007f37", "size": 1971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "JeanBaptiste.Test/src/FixtureSinCos.cpp", "max_stars_repo_name": "JoergWarthemann/jeanbaptiste", "max_stars_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JeanBaptiste.Test/src/FixtureSinCos.cpp", "max_issues_repo_name": "JoergWarthemann/jeanbaptiste", "max_issues_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JeanBaptiste.Test/src/FixtureSinCos.cpp", "max_forks_repo_name": "JoergWarthemann/jeanbaptiste", "max_forks_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3114754098, "max_line_length": 96, "alphanum_fraction": 0.6666666667, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5504716354697475}}
{"text": "#define BOOST_TEST_MODULE FourierTransformTest\n#include <boost/test/unit_test.hpp>\n\n// For IO\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <cmath> \n#include <iostream>\n#include <unistd.h>\n#include <vector>\n\n// For measuring elapsed time\n#include <chrono>\n\n// For Random Float Generator\n#include <time.h>\n\n// For object under test\n#include \"qam-modulator.h\"\n#include \"common.h\"\n#include \"fftw3.h\"\n\n\n/**\n* Test NYQUIST MODULATOR\n* \n*/\nBOOST_AUTO_TEST_SUITE(QAM_MODULATOR)\n\n\n/**\n* Generate random data execute QAM Modulator and demodulator.\n* \n*/\nBOOST_AUTO_TEST_CASE(QamModToDemod)\n{\n    printf(\"\\nTesting QAM Modulation to Demodulation...\\n\");\n    printf(\"\\nMdoulator:\\n\");\n\n    size_t nPoints = 512;\n    size_t pilotToneStep = 8;\n    size_t energyDispersalSeed = 10;\n    size_t bitsPerSymbol = 2;\n    size_t nAvaiableifftPoints = (nPoints - (int)(nPoints/pilotToneStep));\n    size_t nMaxEncodedBytes = (int)((nAvaiableifftPoints *  bitsPerSymbol)  / 8);\n    size_t nData = nMaxEncodedBytes;\n    double pilotToneAmplitude = 2.0;\n\n    // Setup random float generator\n    srand( (unsigned)time( NULL ) );\n\n    std::vector<unsigned char> TxCharArray(nData);\n    std::vector<unsigned char> RxCharArray(nData);\n\n    for(size_t i = 0; i < nData; i++ )\n    {\n        TxCharArray[i] = (unsigned char) rand() % 255;\n    }\n\n    DoubleVec QamOutput(nPoints*2);\n\n    QamModulator qam(nPoints, pilotToneStep, pilotToneAmplitude, energyDispersalSeed, bitsPerSymbol);\n\n    auto start = std::chrono::steady_clock::now();\n    qam.Modulate(TxCharArray, QamOutput, nData);\n    auto end = std::chrono::steady_clock::now();\n\n    std::cout << \"QAM Modulator elapsed time: \"\n    << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()\n    << \" ns\" << std::endl;\n\n    printf(\"\\nDemodulator:\\n\");\n\n    start = std::chrono::steady_clock::now();\n    qam.Demodulate(QamOutput, RxCharArray, nData);\n    end = std::chrono::steady_clock::now();\n\n    std::cout << \"QAM Demodulator elapsed time: \"\n    << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()\n    << \" ns\" << std::endl;\n    \n    for(size_t i = 0; i < nData; i++)\n    {\n        //printf(\"TxCharArray[%lu] = %d ,RxCharArray[%lu] = %d\\n\"\n        //,i,(int)TxCharArray[i] ,i, (int)RxCharArray[i] );\n\n        BOOST_CHECK_MESSAGE( (TxCharArray[i] == RxCharArray[i] ), \n        \"Elements differ! - Occured at index: \" << i );\n    }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "52efb34ee243a0e247fcf9341b2529a98b50c7f4", "size": 2451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/QamModulatorTest.cpp", "max_stars_repo_name": "krogk/ofdmlib", "max_stars_repo_head_hexsha": "7eddfdfde17624bf7674dda33ddc43b308c07765", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T10:44:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T14:20:05.000Z", "max_issues_repo_path": "test/unit/QamModulatorTest.cpp", "max_issues_repo_name": "krogk/ofdmlib", "max_issues_repo_head_hexsha": "7eddfdfde17624bf7674dda33ddc43b308c07765", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-11T12:50:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-11T12:51:02.000Z", "max_forks_repo_path": "test/unit/QamModulatorTest.cpp", "max_forks_repo_name": "krogk/ofdmlib", "max_forks_repo_head_hexsha": "7eddfdfde17624bf7674dda33ddc43b308c07765", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-03T14:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T14:56:19.000Z", "avg_line_length": 25.8, "max_line_length": 101, "alphanum_fraction": 0.6593227254, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5504716313381375}}
{"text": "#include \"Normalize.hh\"\n#include \"TypesFunctions.hh\"\n#include <Eigen/Core>\n#include <cmath>\n\n#ifdef GNA_CUDA_SUPPORT\n#include \"cuElementary.hh\"\n#include \"DataLocation.hh\"\n#endif\n\n/**\n * @brief Default constructor.\n *\n * Initializes the transformation for the whole histogram normalization.\n */\nNormalize::Normalize() {\n    transformation_(\"normalize\")\n        .input(\"inp\")\n        .output(\"out\")\n        .types(TypesFunctions::pass<0>)\n        .func(&Normalize::doNormalize)\n#ifdef GNA_CUDA_SUPPORT\n        .func(\"gpu\", &Normalize::doNormalize_gpu, DataLocation::Device)\n#endif\n        ;\n}\n\n/**\n * @brief Subhistogram normalization constructor.\n *\n * Start and length are defined the same way they are defined for the segment method of Eigen.\n *\n * @param start  -- subhistogram first bin.\n * @param length -- number of bins to normalize to.\n */\nNormalize::Normalize(size_t start, size_t length) : m_start{start}, m_length{length} {\n    transformation_(\"normalize\")\n        .input(\"inp\")\n        .output(\"out\")\n        .types(TypesFunctions::pass<0>, &Normalize::checkLimits)\n        .func(&Normalize::doNormalize_segment)\n        ;\n}\n\n/**\n * @brief Normalize the whole histogram.\n *\n * Divides each bin to the sum of bins.\n */\nvoid Normalize::doNormalize(FunctionArgs& fargs){\n    auto& in=fargs.args[0].x;\n    fargs.rets[0].x=in/in.sum();\n}\n\n#ifdef GNA_CUDA_SUPPORT\nvoid Normalize::doNormalize_gpu(FunctionArgs& fargs) {\n    fargs.args.touch();\n    auto& gpuargs = fargs.gpu;\n    gpuargs->provideSignatureDevice();\n    cunormalize(gpuargs->args, gpuargs->rets, fargs.args[0].arr.size());\n}\n#endif\n\n/**\n * @brief Normalize subhistogram.\n *\n * Divides each bin to the sum of bins in a range [start, start+length-1].\n */\nvoid Normalize::doNormalize_segment(FunctionArgs& fargs){\n    auto& in=fargs.args[0].x;\n    fargs.rets[0].x=in/in.segment(m_start, m_length).sum();\n}\n\n/**\n * @brief typesFunction to check histogram limits for subhistogram mode.\n * @exception SourceTypeError in case the input array is not 1d.\n * @exception SourceTypeError in case the start is outside of the data limits.\n * @exception SourceTypeError in case the end is outside of the data limits.\n */\nvoid Normalize::checkLimits(TypesFunctionArgs& fargs) {\n  auto& args=fargs.args;\n    auto& dtype = args[0];\n    if( dtype.shape.size()!=1u ){\n        throw args.error(dtype, \"Accept only 1d arrays in case a segment is specified\");\n    }\n    auto length=dtype.shape[0];\n    if( m_start>=length ){\n        throw args.error(dtype, \"Segment start is outside of the data limits\");\n    }\n    if( (m_start+m_length)>length ){\n        throw args.error(dtype, \"Segment end is outside of the data limits\");\n    }\n}\n", "meta": {"hexsha": "c8308562be77e9b73bbab0d847b1c8caa851f18c", "size": 2679, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/linalg/Normalize.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/linalg/Normalize.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/linalg/Normalize.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5, "max_line_length": 94, "alphanum_fraction": 0.681597611, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5504600276441219}}
{"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_GREATESTNONINTEGER_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_GREATESTNONINTEGER_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Greatestnoninteger Greatestnoninteger (function template)\n\n  Generates the greatest representable non-integral value\n\n  @headerref{<boost/simd/constant/greatestnoninteger.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Greatestnoninteger();\n      @endcode\n\n  2.  @code\n      template<typename T> T Greatestnoninteger( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T which is exactly representable and which its successor has\n  integral value. By definition, all floating numbers greater than `Greatestnoninteger<T>()` have\n  integral value.\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n  A value of type @c as_integer_t<T> that evaluates to:\n\n  | Type                | double                        | float         |\n  |--------------------:|:------------------------------|---------------|\n  | value               |   4503599627370495.5          | 8388607.5f    |\n\n  @par Requirements\n  - **T** models IEEEValue\n**/\n\n#include <boost/simd/constant/scalar/greatestnoninteger.hpp>\n#include <boost/simd/constant/simd/greatestnoninteger.hpp>\n\n#endif\n", "meta": {"hexsha": "06092d51ed6c3fbfa04cde46c13e8b3618a2ad79", "size": 1952, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/greatestnoninteger.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/greatestnoninteger.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/greatestnoninteger.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 34.2456140351, "max_line_length": 100, "alphanum_fraction": 0.5420081967, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.55046002142594}}
{"text": "#ifndef BODY_HPP\n#define BODY_HPP\n\n#include <armadillo>\n#include \"Math.hpp\"\n#include <boost/shared_ptr.hpp>\n#include <boost/enable_shared_from_this.hpp>\n\nclass Body : public boost::enable_shared_from_this<Body>\n{\npublic:\n    Body();\n    virtual ~Body() = default;\n\n    arma::mat get_TBI();\n    arma::vec get_POSITION();\n    arma::vec get_VELOCITY();\n    arma::vec get_ACCELERATION();\n    arma::vec get_ANGLE_VEL();\n    arma::vec get_ANGLE();\n    arma::vec get_ANGLE_ACC();\n    arma::vec get_FORCE();\n    arma::vec get_TORQUE();\n    arma::mat get_M();\n    arma::vec get_TBI_Q();\n    arma::vec get_TBID_Q();\n    unsigned int get_num();\n\n    void set_POSITION(const arma::vec &PosIn);\n    void set_VELOCITY(const arma::vec &VelIn);\n    void set_ACCELERATION(const arma::vec &AccIn);\n    void set_ANGLE(const arma::vec &AngIn);\n    void set_ANGLE_VEL(const arma::vec &AngvelIn);\n    void set_ANGLE_ACC(const arma::vec &AngaccIn);\n    void set_TBI(const arma::mat &TBIIn);\n\n    virtual void update(arma::vec PosIn, arma::vec VelIn, arma::vec AttIn\n        , arma::vec ANG_VEL_In) = 0;\n\nprotected:\n\n    unsigned int type;  // type define   0: Ground body, 1: Mobilized body\n    unsigned int num;  // No. body\n\n    arma::vec POSITION;\n    arma::vec VELOCITY;\n    arma::vec ACCELERATION;\n    arma::vec ANGLE;\n    arma::vec ANGLE_VEL;\n    arma::vec ANGLE_ACC;\n    arma::mat M;\n    arma::vec FORCE;\n    arma::vec TORQUE;\n    arma::vec APPILED_TORQUE;\n    arma::mat TBI;\n    arma::vec TBI_Q;\n    arma::vec TBID_Q;\n};\n\nclass Ground : public Body\n{\npublic:\n    Ground(unsigned int NumIn);\n    ~Ground() {};\n    virtual void update(arma::vec PosIn, arma::vec VelIn, arma::vec AttIn\n        , arma::vec ANG_VEL_In) {};\n};\n\nclass Mobilized_body : public Body\n{\npublic:\n    Mobilized_body(unsigned int NumIn, arma::vec PosIn, arma::vec VelIn, arma::vec AccIn, arma::vec AttIn\n        , arma::vec ANG_VEL_In, arma::vec ANG_ACC_In, double MIn, arma::vec IIn\n        , arma::vec F_In, arma::vec T_In);\n    ~Mobilized_body() {};\n\n    virtual void update(arma::vec PosIn, arma::vec VelIn, arma::vec TBI_QIn\n        , arma::vec ANG_VEL_In) override;\n};\n\ntypedef boost::shared_ptr<Body> BodyPtr;\n#endif  //BODY_HPP", "meta": {"hexsha": "1b201e4a51a977c7b3974d21d19eff76cb2a5d88", "size": 2190, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Body.hpp", "max_stars_repo_name": "octoberskyTW/Multibody-Dynamics-Solver", "max_stars_repo_head_hexsha": "67b0ea9f6cfbed9e9cf8f048b7e35b620b9aeb4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-17T03:06:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T03:06:47.000Z", "max_issues_repo_path": "include/Body.hpp", "max_issues_repo_name": "octoberskyTW/Multibody-Dynamics-Solver", "max_issues_repo_head_hexsha": "67b0ea9f6cfbed9e9cf8f048b7e35b620b9aeb4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Body.hpp", "max_forks_repo_name": "octoberskyTW/Multibody-Dynamics-Solver", "max_forks_repo_head_hexsha": "67b0ea9f6cfbed9e9cf8f048b7e35b620b9aeb4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-31T13:05:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T13:05:36.000Z", "avg_line_length": 26.7073170732, "max_line_length": 105, "alphanum_fraction": 0.6589041096, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5504600118549142}}
{"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 \u0393 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 \u0393 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": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2020 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n#include \"SiconosConfig.h\"\n\n#include \"EigenProblemsTest.hpp\"\n#include \"SiconosAlgebra.hpp\"\n#include \"SimpleMatrixFriends.hpp\"\n#include \"bindings_utils.hpp\"\n#include <limits>\n#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include \"SiconosVector.hpp\"\n\n#define CPPUNIT_ASSERT_NOT_EQUAL(message, alpha, omega) \\\n  if ((alpha) == (omega)) CPPUNIT_FAIL(message);\n\n\n// Note FP : add tests for complex matrices and geev, if needed (?)\n\nCPPUNIT_TEST_SUITE_REGISTRATION(EigenProblemsTest);\n\nvoid EigenProblemsTest::setUp()\n{\n  size = 5;\n  A.reset(new SimpleMatrix(size,size));\n  // Initialize A with random values.\n  A->randomize();\n  Aref.reset(new SimpleMatrix(*A));\n}\n\nvoid EigenProblemsTest::tearDown()\n{}\n\nvoid EigenProblemsTest::testSyev()\n{\n  std::cout << \"--> Test: syev.\" <<std::endl;\n\n  // turn A to a symmetric matrix\n  A->randomize_sym();\n  *Aref = *A;\n\n  // Initialize EigenVectors with A\n  SP::SiconosVector EigenValues(new SiconosVector(size));\n  SP::SimpleMatrix EigenVectors(new SimpleMatrix(*A));\n//  *EigenVectors = *A;\n\n  Siconos::eigenproblems::syev(*EigenValues, *EigenVectors);\n\n  DenseVect error(size);\n  error *= 0.0;\n\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    error.plus_assign(ublas::prod(*A->dense(), column(*EigenVectors->dense(), i)));\n    error.minus_assign((*EigenValues->dense())(i)*column(*EigenVectors->dense(),i));\n  }\n  // Check ...\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSyev 1: \", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);\n  // Check if A has not been modified\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSyev 2: \", (*A) == (*Aref), true);\n\n  // Now compute only eigenvalues\n  SP::SiconosVector RefEigenValues(new SiconosVector(*EigenValues));\n  *EigenVectors = *A;\n  *EigenValues *= 0.0;\n  Siconos::eigenproblems::syev(*EigenValues, *EigenVectors, false);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSyev 3: \", ((*EigenValues) - (*RefEigenValues)).norm2() < 10 * std::numeric_limits< double >::epsilon(), true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSyev 4: \", (*A) == (*Aref), true);\n  std::cout << \"--> Syev test ended with success.\" <<std::endl;\n}\n\nvoid EigenProblemsTest::testGeev1()\n{\n  std::cout << \"--> Test: geev1.\" <<std::endl;\n  // Compute only right eigenvectors.\n  complex_matrix fake(1,1), rightV(size,size);\n  complex_vector eigenval(size);\n  Siconos::eigenproblems::geev(*A, eigenval, fake, rightV);\n  complex_vector error(size);\n  for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    error.plus_assign(ublas::prod(*A->dense(), column(rightV, i)));\n    error.minus_assign(eigenval(i)*column(rightV,i));\n  }\n\n  // Check ...\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev1 1: \", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);\n  // Check if A has not been modified\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev1 2: \", (*A) == (*Aref), true);\n  // Now compute only eigenvalues\n  complex_vector RefEigenValues(size);\n  RefEigenValues = eigenval;\n  eigenval *= 0.0;\n  Siconos::eigenproblems::geev(*A, eigenval, fake, fake, false, false);\n\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev1 3: \", norm_2(eigenval - RefEigenValues) < 10 * std::numeric_limits< double >::epsilon(), true);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev1 4: \", (*A) == (*Aref), true);\n\n  std::cout << \"--> geev1 test ended with success.\" <<std::endl;\n}\n\nvoid EigenProblemsTest::testGeev2()\n{\n  std::cout << \"--> Test: geev2.\" <<std::endl;\n  // Compute only left eigenvectors.\n  complex_matrix fake(1,1), leftV(size,size);\n  complex_vector eigenval(size);\n  Siconos::eigenproblems::geev(*A, eigenval, leftV, fake, true, false);\n  complex_vector error(size);\n  for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    error.plus_assign(ublas::prod(conj(column(leftV, i)), *A->dense()));\n    error.minus_assign(eigenval(i)*conj(column(leftV,i)));\n  }\n  // Check ...\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev2 1: \", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);\n  // Check if A has not been modified\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev2 2: \", (*A) == (*Aref), true);\n\n  std::cout << \"--> geev1 test ended with success.\" <<std::endl;\n}\n\nvoid EigenProblemsTest::testGeev3()\n{\n  std::cout << \"--> Test: geev3.\" <<std::endl;\n\n  // Compute left and right eigenvectors.\n  complex_matrix leftV(size,size), rightV(size,size);\n  complex_vector eigenval(size);\n  Siconos::eigenproblems::geev(*A, eigenval, leftV, rightV, true, true);\n  complex_vector error(size);\n  for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;\n  for(unsigned int i = 0; i < size; ++i)\n  {\n    error.plus_assign(ublas::prod(*A->dense(), column(rightV, i)));\n    error.minus_assign(eigenval(i)*column(rightV,i));\n    error.plus_assign(ublas::prod(conj(column(leftV, i)), *A->dense()));\n    error.minus_assign(eigenval(i)*conj(column(leftV,i)));\n  }\n  std::cout << norm_2(error) << std::endl;\n  // Check ...\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev3 1: \", norm_2(error) < size * 10 * std::numeric_limits< double >::epsilon(), true);\n  // Check if A has not been modified\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev3 2: \", (*A) == (*Aref), true);\n\n  std::cout << \"--> geev3 test ended with success.\" <<std::endl;\n}\n\nvoid EigenProblemsTest::End()\n{\n  std::cout << \"======================================\" <<std::endl;\n  std::cout << \" ===== End of EigenProblems tests ===== \" <<std::endl;\n  std::cout << \"======================================\" <<std::endl;\n}\n", "meta": {"hexsha": "814dd2f1f725a434529ce0e4d8433424b7cfa4cf", "size": 6221, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/test/EigenProblemsTest.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": ["Apache-2.0"], "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/src/utils/SiconosAlgebra/test/EigenProblemsTest.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_licenses": ["Apache-2.0"], "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/src/utils/SiconosAlgebra/test/EigenProblemsTest.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.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.9595375723, "max_line_length": 147, "alphanum_fraction": 0.6717569523, "num_tokens": 1800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5502184580429282}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//! \\file\r\n//!\\brief Tests for the trigonometric arcsine function of (fixed_point) for a small digit range.\r\n\r\n#include <cmath>\r\n\r\n#define BOOST_TEST_MODULE test_negatable_func_arcsine_small\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_func_arcsine_small)\r\n{\r\n  typedef boost::fixed_point::negatable<7, -24> fixed_point_type;\r\n  typedef fixed_point_type::float_type          float_point_type;\r\n\r\n  const fixed_point_type tol = ldexp(fixed_point_type(1), fixed_point_type::resolution + 7);\r\n\r\n  // Check positive arguments.\r\n  for(int i = 0; i <= 32; ++i)\r\n  {\r\n    const fixed_point_type x = asin(fixed_point_type(i) / 32);\r\n\r\n    using std::asin;\r\n    const float_point_type y = asin(float_point_type(i) / 32);\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n  }\r\n\r\n  // Check negative arguments.\r\n  for(int i = 0; i <= 32; ++i)\r\n  {\r\n    const fixed_point_type x = asin(fixed_point_type(-i) / 32);\r\n\r\n    using std::asin;\r\n    const float_point_type y = asin(float_point_type(-i) / 32);\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n  }\r\n}\r\n", "meta": {"hexsha": "8f25b10f20da9bbe297f4031db5987b6187687c5", "size": 1555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_func_arcsine_small.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_func_arcsine_small.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_func_arcsine_small.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7346938776, "max_line_length": 97, "alphanum_fraction": 0.6688102894, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5502184562832413}}
{"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": "/* Copyright (c) 2015 Oleg Morozenkov\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/test/unit_test.hpp>\n\n#include <test/math/Vector.h>\n\nBOOST_AUTO_TEST_SUITE(tVector)\n\nBOOST_AUTO_TEST_CASE(tvectorCalculateLengthSq) {\n\tVector a = { 4, 4, 2 };\n\tBOOST_CHECK_EQUAL(vectorGetLengthSq(a), 36);\n}\n\nBOOST_AUTO_TEST_CASE(tvectorCalculateLength) {\n\tVector a = { 4, 4, 2 };\n\tBOOST_CHECK_EQUAL(vectorGetLength(a), 6);\n}\n\nBOOST_AUTO_TEST_CASE(tvectorIsEqual) {\n\tVector a = { 1, 2, 3 };\n\tVector b = { 4, 5, 6 };\n\tBOOST_CHECK(!vectorIsEqual(a, b));\n\tBOOST_CHECK(vectorIsEqual(a, a));\n}\n\nBOOST_AUTO_TEST_CASE(tvectorGetOpposite) {\n\tVector a = { 1, 2, 3 };\n\tVector r = { -1, -2, -3 };\n\tBOOST_CHECK(vectorIsEqual(vectorGetOpposite(a), r));\n}\n\nBOOST_AUTO_TEST_CASE(tvectorSum) {\n\tVector a = { 1, 2, 3 };\n\tVector b = { 4, 5, 6 };\n\tVector r = { 5, 7, 9 };\n\tBOOST_CHECK(vectorIsEqual(vectorSum(a, b), r));\n}\n\nBOOST_AUTO_TEST_CASE(tvectorSubstract) {\n\tVector a = { 1, 2, 3 };\n\tVector b = { 4, 5, 6 };\n\tVector r = { -3, -3, -3 };\n\tBOOST_CHECK(vectorIsEqual(vectorSubstract(a, b), r));\n}\n\nBOOST_AUTO_TEST_CASE(tvectorMultiply) {\n\tVector a = { 1, 2, 3 };\n\tVector r = { 4, 8, 12 };\n\tBOOST_CHECK(vectorIsEqual(vectorMultiply(a, 4), r));\n}\n\nBOOST_AUTO_TEST_CASE(tvectorDivide) {\n\tVector a = { 4, 8, 12 };\n\tVector r = { 1, 2, 3 };\n\tBOOST_CHECK(vectorIsEqual(vectorDivide(a, 4), r));\n}\n\nBOOST_AUTO_TEST_CASE(tvectorDotProduct) {\n\tVector a = { 1, 2, 3 };\n\tVector b = { 4, 5, 6 };\n\tBOOST_CHECK_EQUAL(vectorDotProduct(a, b), 32);\n}\n\nBOOST_AUTO_TEST_CASE(tvectorCrossProduct) {\n\tVector a = { 1, 2, 3 };\n\tVector b = { 4, 5, 6 };\n\tVector r = { -3, 6, -3 };\n\tBOOST_CHECK(vectorIsEqual(vectorCrossProduct(a, b), r));\n}\n\nBOOST_AUTO_TEST_CASE(tvectorNormalize) {\n\tVector a = { 1, 2, 3 };\n\tBOOST_CHECK_EQUAL(vectorGetLength(vectorNormalize(a)), 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "aeebeb491db8b45567470b4231b892ed9717ea76", "size": 2888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/Vector.cpp", "max_stars_repo_name": "reo7sp/MagneticTest", "max_stars_repo_head_hexsha": "ac89a1f0777b55d15d643e2e248dff102f265665", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/Vector.cpp", "max_issues_repo_name": "reo7sp/MagneticTest", "max_issues_repo_head_hexsha": "ac89a1f0777b55d15d643e2e248dff102f265665", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/Vector.cpp", "max_forks_repo_name": "reo7sp/MagneticTest", "max_forks_repo_head_hexsha": "ac89a1f0777b55d15d643e2e248dff102f265665", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0833333333, "max_line_length": 80, "alphanum_fraction": 0.7056786704, "num_tokens": 822, "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": "/* =========================================================================\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": "// Software License for MTL \n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef ITL_PC_DIAGONAL_INCLUDE\n#define ITL_PC_DIAGONAL_INCLUDE\n\n#include <boost/numeric/linear_algebra/inverse.hpp>\n\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n#include <boost/numeric/itl/pc/solver.hpp>\n\nnamespace itl { namespace pc {\n\n/// Diagonal Preconditioner\ntemplate <typename Matrix, typename Value= typename mtl::Collection<Matrix>::value_type>\nclass diagonal\n{\n  public:\n    typedef Value                                         value_type;\n    typedef typename mtl::Collection<Matrix>::size_type   size_type;\n    typedef diagonal                                      self;\n\n    /// Constructor takes matrix reference\n    explicit diagonal(const Matrix& A) : inv_diag(num_rows(A))\n    {\n\tmtl::vampir_trace<5050> tracer;\n\tMTL_THROW_IF(num_rows(A) != num_cols(A), mtl::matrix_not_square());\n\tusing math::reciprocal;\n\n\tfor (size_type i= 0; i < num_rows(A); ++i)\n\t    inv_diag[i]= reciprocal(A[i][i]);\n    }\n\n    /// Member function solve, better use free function solve\n    template <typename Vector>\n    Vector solve(const Vector& x) const\n    {\n\tVector y(resource(x));\n\tsolve(x, y);\n\treturn y;\n    }\n\n    template <typename VectorIn, typename VectorOut>\n    void solve(const VectorIn& x, VectorOut& y) const\n    {\n\tmtl::vampir_trace<5051> tracer;\n\ty.checked_change_resource(x);\n\tMTL_THROW_IF(size(x) != size(inv_diag), mtl::incompatible_size());\n\tfor (size_type i= 0; i < size(inv_diag); ++i)\n\t    y[i]= inv_diag[i] * x[i];\n    }\n\n    /// Member function for solving adjoint problem, better use free function adjoint_solve\n    template <typename Vector>\n    Vector adjoint_solve(const Vector& x) const\n    {\n\tVector y(resource(x));\n\tadjoint_solve(x, y);\n\treturn y;\n    }\n\n    template <typename VectorIn, typename VectorOut>\n    void adjoint_solve(const VectorIn& x, VectorOut& y) const\n    {\n\tusing mtl::conj;\n\ty.checked_change_resource(x);\n\tMTL_THROW_IF(size(x) != size(inv_diag), mtl::incompatible_size());\n\tfor (size_type i= 0; i < size(inv_diag); ++i)\n\t    y[i]= conj(inv_diag[i]) * x[i];\n    }\n\n protected:\n    mtl::dense_vector<value_type>    inv_diag;\n}; \n\n/// Solve approximately a sparse system in terms of inverse diagonal\ntemplate <typename Matrix, typename Vector>\nsolver<diagonal<Matrix>, Vector, false>\ninline solve(const diagonal<Matrix>& P, const Vector& x)\n{\n    return solver<diagonal<Matrix>, Vector, false>(P, x);\n}\n\n/// Solve approximately the adjoint of a sparse system in terms of inverse diagonal\ntemplate <typename Matrix, typename Vector>\nsolver<diagonal<Matrix>, Vector, true>\ninline adjoint_solve(const diagonal<Matrix>& P, const Vector& x)\n{\n    return solver<diagonal<Matrix>, Vector, true>(P, x);\n}\n\n\n}} // namespace itl::pc\n\n#endif // ITL_PC_DIAGONAL_INCLUDE\n", "meta": {"hexsha": "ce3b4ab11c71b9b69d0cc64fc9bb7d2628db138d", "size": 3358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/pc/diagonal.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/itl/pc/diagonal.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/itl/pc/diagonal.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.8073394495, "max_line_length": 94, "alphanum_fraction": 0.6959499702, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5501946291397972}}
{"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_ATAN2D_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ATAN2D_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing atan2d capabilities\n\n    atan2d function : atan2 in degrees.\n\n    @par Semantic:\n\n    For every parameters of floating type T:\n\n    @code\n    T r = atan2d(x, y);\n    @endcode\n\n    is similar but not fully equivalent to:\n\n    @code\n    T r =  atand(y/x);;\n    @endcode\n\n    as it is quadrant aware.\n\n    For any real arguments @c x and @c y not both equal to zero, <tt>atan2d(x, y)</tt>\n    is the angle in degrees between the positive x-axis of a plane and the point\n    given by the coordinates  <tt>(y, x)</tt>.\n\n    It is also the angle in \\f$[-180,180[\\f$ for which\n    \\f$x/\\sqrt{x^2+y^2}\\f$ and \\f$y/\\sqrt{x^2+y^2}\\f$\n    are respectively the sine and the cosine.\n\n    @see atand, atan2, atan\n\n  **/\n  const boost::dispatch::functor<tag::atan2d_> atan2d = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/atan2d.hpp>\n#include <boost/simd/function/simd/atan2d.hpp>\n\n#endif\n", "meta": {"hexsha": "491364b7e4401ebf289e764baff3ab5e95c0d909", "size": 1537, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/atan2d.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/atan2d.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/atan2d.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.1967213115, "max_line_length": 100, "alphanum_fraction": 0.5940143136, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5501946240453174}}
{"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": "#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <string>\n#include <Eigen/Dense>\n#include \"../include/sample_network.h\"\n\nusing namespace Eigen;\n\nint main()\n{\n    using namespace MyDL;\n    using std::cout;\n    using std::endl;\n    using std::vector;\n    using std::string;\n    using std::unordered_map;\n\n    int batch_size = 4;\n    int input_size = 2;\n    vector<int> hidden_size = {3};\n    int output_size = 2;\n    double lambda = 2.0;\n\n    MultiLayerNet net(input_size, hidden_size, output_size, lambda);\n\n    cout << \"Check Initialized Parameters\" << endl;\n    for (auto param : net.params)\n    {\n        cout << param.first << endl;\n        cout << *(param.second) << endl;\n    }\n\n    cout << \"Test Predict Method\" << endl;\n    vector<MatrixXd> inputs, outputs;\n    MatrixXd X = MatrixXd::Random(batch_size, input_size);\n    inputs.push_back(X);\n\n    outputs = net.predict(inputs);\n\n    cout << outputs[0] << endl;\n\n\n    cout << \"Test Loss Method\" << endl;\n    vector<MatrixXd> loss_output;\n    MatrixXd t = MatrixXd::Zero(batch_size, output_size);\n\n    t << 1, 0,\n         1, 0,\n         1, 0,\n         0, 1;\n\n    loss_output = net.loss(inputs, t);\n\n    cout << loss_output[0] << endl;\n\n    cout << \"Test Accuracy Method\" << endl;\n    double accuracy;\n\n    accuracy = net.accuracy(inputs, t);\n\n    cout << accuracy << endl;\n\n    cout << \"Test Gradient Method\" << endl;\n\n    unordered_map<string, MatrixXd> grads;\n\n    grads = net.gradient(inputs, t);\n\n    for (auto grad : grads)\n    {\n        cout << grad.first << endl;\n        cout << grad.second << endl;\n    }\n\n    cout << \"Test Finished\" << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "9d8dfb5bd1cdbb66ee3dfcba4488a704d960ee7c", "size": 1647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_multi_layer_net.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "test/test_multi_layer_net.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_multi_layer_net.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5875, "max_line_length": 68, "alphanum_fraction": 0.5962355798, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5501946225215031}}
{"text": "#include \"alpha_shape_area.hpp\"\n#include <boost/lexical_cast.hpp>\n#include <iostream>\n#include <fstream>\n\n#include \"weight_data.hpp\"\n#include \"weight_func_obj_min.hpp\"\n#include \"create_alpha_shape.hpp\"\n#include \"alpha_shape_weighted_area.hpp\"\n\ntypedef float f_t;\n\nint main(int argc, char* argv[]){\n\n\tfeenableexcept(FE_INVALID | FE_OVERFLOW);\n\n\tif(argc != 3){\n\t\tstd::cout << \"usage: \" << argv[0] << \" <alpha> <coord/radii file>\" << std::endl;\n\t\treturn 1;\n\t}\n\tf_t alpha = boost::lexical_cast<f_t>(argv[1]);\n\tconst char* infilename = argv[2];\n\n\tstd::vector<f_t> points, radii;\n\tf_t x, y, z, r;\n\tstd::ifstream fs;\n\tfs.open(infilename, std::ifstream::in);\n\twhile(fs >> x >> y >> z >> r){\n\t\tpoints.push_back(x);\n\t\tpoints.push_back(y);\n\t\tpoints.push_back(z);\n\t\tradii.push_back(r);\n\t}\n\tsize_t numPoints = radii.size();\n\tstd::cout << \"number of points: \" << numPoints << std::endl;\n\n\tstd::vector<f_t> areas(numPoints);\n\n\tif(0){\n\t\tbusv::alpha_shape_area<f_t, unsigned int>(numPoints, alpha, &(points[0]), &(radii[0]), &(areas[0]));\n\t}\n\telse{\n\t\tstd::vector<busv::weight_data<f_t, size_t> > wd(numPoints);\n\t\tbusv::weight_func_obj_min<f_t, size_t> wfo(&(wd[0]), 0);\n\t\tbusv::AlphaShapeContainer<f_t, size_t> asc = busv::create_alpha_shape(numPoints, alpha,  &(points[0]), &(radii[0]));\n\t\tbusv::alpha_shape_weighted_area<f_t, size_t>(asc, wfo, &(areas[0]));\n\t}\n\n\tfor(unsigned int i = 0; i<numPoints; ++i){\n\t\tstd::cout << i << \"\\t\" << areas[i] << std::endl;\n\t}\n\tstd::cout << std::endl;\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "2d31dc59b72a2c9bd62277b0e2bc06ce4e52b018", "size": 1485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/alpha_shapes/pointAreas.cpp", "max_stars_repo_name": "academicRobot/mmstructlib", "max_stars_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/alpha_shapes/pointAreas.cpp", "max_issues_repo_name": "academicRobot/mmstructlib", "max_issues_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/alpha_shapes/pointAreas.cpp", "max_forks_repo_name": "academicRobot/mmstructlib", "max_forks_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0526315789, "max_line_length": 118, "alphanum_fraction": 0.6565656566, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303384097946, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5501761652225813}}
{"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/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#include <simd_test.hpp>\n#include <boost/simd/function/sinhcosh.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/function/cosh.hpp>\n#include <boost/simd/function/sinh.hpp>\n\nnamespace bs = boost::simd;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], c[N], s[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i)/2 : -T(i)/2;\n    std::tie(s[i], c[i])= bs::sinhcosh(a1[i]) ;\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t ss (&s[0], &s[0]+N);\n  p_t cc (&c[0], &c[0]+N);\n  p_t ss1, cc1;\n  std::tie(ss1, cc1)= bs::sinhcosh(aa1) ;\n  STF_ULP_EQUAL(ss1, ss, 0.5);\n  STF_ULP_EQUAL(cc1, cc, 0.5);\n}\n\nSTF_CASE_TPL(\"Check sincosh on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\n\nSTF_CASE_TPL(\"sinhcosh\", STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using p_t = bs::pack<T>;\n  using bs::sinhcosh;\n\n  p_t a[] = {bs::Zero<p_t>(), bs::One<p_t>(), p_t(5), p_t(-5)};\n  size_t N =  sizeof(a)/sizeof(p_t);\n  STF_EXPR_IS( (sinhcosh(p_t()))\n                  , (std::pair<p_t,p_t>)\n                  );\n\n  {\n    for(size_t i=0; i < N; ++i)\n    {\n      std::pair<p_t,p_t> p = sinhcosh(a[i]);\n      STF_ULP_EQUAL(p.first,  bs::sinh(a[i]), 1);\n      STF_ULP_EQUAL(p.second, bs::cosh(a[i]), 1);\n    }\n  }\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n  p_t b[] = {bs::Inf<p_t>(), bs::Minf<p_t>(), bs::Nan<p_t>()};\n  N =  sizeof(b)/sizeof(p_t);\n\n  {\n    for(size_t i=0; i < N; ++i)\n    {\n      std::pair<p_t,p_t> p = sinhcosh(b[i]);\n      STF_ULP_EQUAL(p.first,  bs::sinh(b[i]), 1);\n      STF_ULP_EQUAL(p.second, bs::cosh(b[i]), 1);\n    }\n  }\n#endif\n}\n", "meta": {"hexsha": "c1cdcaa4a9215a21bf3b53e3f9b745e783c2084a", "size": 2391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/sinhcosh.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "test/function/simd/sinhcosh.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/simd/sinhcosh.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 26.2747252747, "max_line_length": 100, "alphanum_fraction": 0.5462149728, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5501761514842808}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n\nTEST(MathFunctions, rising_factorial) {\n  using stan::math::rising_factorial;\n\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_FLOAT_EQ(120, rising_factorial(4.0, 3));\n  EXPECT_FLOAT_EQ(360, rising_factorial(3.0, 4));\n  EXPECT_THROW(rising_factorial(1, -4), std::domain_error);\n  EXPECT_THROW(rising_factorial(nan, 1), std::domain_error);\n}\n", "meta": {"hexsha": "f3faff8f13932eaa18a2870df04852517f221934", "size": 494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/rising_factorial_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/prim/scal/fun/rising_factorial_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/prim/scal/fun/rising_factorial_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.875, "max_line_length": 60, "alphanum_fraction": 0.7530364372, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6959583250334525, "lm_q1q2_score": 0.5501761496003575}}
{"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 <boost/math/special_functions/detail/igamma_inverse.hpp>\n\nnamespace boostswift {\n\ndouble gamma_p_inv(double a, double p) {\n    return boost::math::gamma_p_inv(a, p);\n}\n\n}\n", "meta": {"hexsha": "6b125f8ccd318645e2ab9629df43ed38845dd730", "size": 180, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sources/BoostGammaInvCpp/BoostGammaInvCpp.cpp", "max_stars_repo_name": "nihp-public/boostswift-public", "max_stars_repo_head_hexsha": "4ff469c242c240cc1d54fbe67a2f77f7f883c0d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-12T06:34:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-12T06:34:20.000Z", "max_issues_repo_path": "Sources/BoostGammaInvCpp/BoostGammaInvCpp.cpp", "max_issues_repo_name": "nihp-public/boostswift-public", "max_issues_repo_head_hexsha": "4ff469c242c240cc1d54fbe67a2f77f7f883c0d9", "max_issues_repo_licenses": ["MIT"], "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/BoostGammaInvCpp/BoostGammaInvCpp.cpp", "max_forks_repo_name": "nihp-public/boostswift-public", "max_forks_repo_head_hexsha": "4ff469c242c240cc1d54fbe67a2f77f7f883c0d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-29T15:01:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-29T15:01:26.000Z", "avg_line_length": 18.0, "max_line_length": 65, "alphanum_fraction": 0.7444444444, "num_tokens": 44, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.550112029410292}}
{"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 SHAPE_RETRIEVAL__HISTOGRAM_H_\n#define SHAPE_RETRIEVAL__HISTOGRAM_H_\n\n#include <Eigen/Core>\n#include <map>\n#include <vector>\n#include <math.h>\n#include <boost/algorithm/string.hpp>\n#include \"Vocabulary.hpp\"\n\nusing namespace Eigen;\n\nclass Histogram\n{\npublic:\n\n\tstatic Vocabulary vocabulary;\n\n\tHistogram() = default;\n    Histogram(MatrixXd const& bagOfFeatures);\n\n    void setValue(MatrixXd const& bagOfFeatures);\n    void writeToFile(string path);\n    void writeToFile(ofstream &file);\n    void setFromFile(string path);\n    void setFromStream(ifstream &file);\n\n    double distance(Histogram const& hist2);\n\n    std::map<int, double> weights;\n\nprivate:\n\n    \n    VectorXi computeCentroids(MatrixXd const& bagOfFeatures);\n    void computeWeights(VectorXi const& bagOfWords);\n};\n\n#endif //SHAPE_RETRIEVAL__HISTOGRAM_H_", "meta": {"hexsha": "19070992f27a2da6e1185a468d635bdec2d6d138", "size": 822, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Histogram.hpp", "max_stars_repo_name": "PierreTsr/Shape_Retrieval", "max_stars_repo_head_hexsha": "1a0246913c3653d43ef75c6168ea1d49cb23b295", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-30T09:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-30T09:13:54.000Z", "max_issues_repo_path": "src/Histogram.hpp", "max_issues_repo_name": "PierreTsr/Shape_Retrieval", "max_issues_repo_head_hexsha": "1a0246913c3653d43ef75c6168ea1d49cb23b295", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Histogram.hpp", "max_forks_repo_name": "PierreTsr/Shape_Retrieval", "max_forks_repo_head_hexsha": "1a0246913c3653d43ef75c6168ea1d49cb23b295", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-19T04:02:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T04:02:17.000Z", "avg_line_length": 21.0769230769, "max_line_length": 61, "alphanum_fraction": 0.7518248175, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5501027623005207}}
{"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": "/**\n * \\file metric_space_concept.hpp\n * \n * This library defines the traits and concepts that pertain to what can be considered \n * a metric-space, as used in ReaK::pp. Metric-spaces are based on the Topology concept \n * from the Boost.Graph library, but with additional requirements which are needed \n * in algorithms tailored for a metric-space (see metric_space_search.hpp). Basically,\n * the concept of a metric-space in ReaK::pp corresponds to the mathematical concept of \n * a metric-space (see wikipedia or any decent math book).\n * \n * \\author Sven Mikael Persson <mikael.s.persson@gmail.com>\n * \\date March 2011\n */\n\n/*\n *    Copyright 2011 Sven Mikael Persson\n *\n *    THIS SOFTWARE IS DISTRIBUTED UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE v3 (GPLv3).\n *\n *    This file is part of ReaK.\n *\n *    ReaK 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 *    ReaK 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 ReaK (as LICENSE in the root folder).  \n *    If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef METRIC_SPACE_CONCEPT_HPP\n#define METRIC_SPACE_CONCEPT_HPP\n\n\n#include <boost/config.hpp>\n#include <cmath>\n#include <boost/concept_check.hpp>\n\n  \n/**\n * This traits class defines the types and constants associated to a metric-space.\n * \\tparam Topology The topology type for which the metric-space traits are sought.\n */\ntemplate <typename Topology>\nstruct metric_topology_traits {\n  /** The type that describes a point in the space. */\n  typedef typename Topology::point_type point_type;\n  /** The type that describes a difference between points in the space. */\n  typedef typename Topology::point_difference_type point_difference_type;\n  \n  /** The dimensions of the space (0 if unknown at compile-time). */\n  BOOST_STATIC_CONSTANT(std::size_t, dimensions = Topology::dimensions);\n  \n};\n\n/**\n * This concept defines the requirements to fulfill in order to model a distance-metric \n * as used in ReaK::pp. A distance-metric is essentially a callable type that can compute \n * both the distance between two points and the corresponding norm of a difference between \n * two points.\n * \n * Required concepts:\n * \n * Topology should model the Topology concept of the BGL.\n * \n * Valid expressions:\n * \n * dist = d(p1, p2, s);  The distance (dist) can be obtained by calling the distance metric (d) on two points (p1,p2) and providing a const-ref to the topology (or space) (s).\n * \n * dist = d(pd, s);  The distance (dist) can be obtained by calling the distance metric (d) on a point-difference (pd) and providing a const-ref to the topology (or space) (s).\n * \n * \\tparam DistanceMetric The distance metric type to be checked for this concept.\n * \\tparam Topology The topology to which the distance metric should apply.\n */\ntemplate <typename DistanceMetric, typename Topology>\nstruct DistanceMetricConcept {\n  DistanceMetric d;\n  Topology s;\n  typename metric_topology_traits<Topology>::point_type p1, p2;\n  typename metric_topology_traits<Topology>::point_difference_type pd;\n  double dist;\n  \n  BOOST_CONCEPT_USAGE(DistanceMetricConcept) \n  {\n    dist = d(p1, p2, s);\n    dist = d(pd, s);\n  };\n  \n};\n\n/**\n * This concept defines the requirements to fulfill in order to model a metric-space \n * as used in ReaK::pp. A metric-space is a special kind of topology which has a \n * distance metric (in theory, satisfying triangular inequality).\n * \n * Valid expressions:\n * \n * d  = space.distance(p1, p2);  The distance between two points (p1,p2) can be obtained as a double (d).\n * \n * d  = space.norm(pd);  The norm of the difference (pd) between two points can be obtained as a double (d).\n * \n * p1 = space.random_point();  A random-point in the metric-space can be obtained.\n * \n * pd = space.difference(p1,p2);  The difference (pd) between two points (p1,p2) can be obtained.\n * \n * p1 = space.move_position_toward(p1,d,p2);  A point can be obtained by moving a fraction (d) away from one point (p1) to another (p2).\n * \n * p1 = space.origin();  The origin of the space can be obtained.\n * \n * p1 = space.adjust(p1,d * pd + pd - pd);  A point-difference can be scaled (d * pd), added / subtracted to another point-difference and added to a point (p1) to obtain an adjusted point.\n * \n * pd = -pd;  A point-difference can be negated (reversed) and is assignable.\n *\n * pd -= pd;  A point-difference can be subtracted-and-assigned.\n *\n * pd += pd;  A point-difference can be added-and-assigned.\n * \n * \\tparam Topology The topology type to be checked for this concept.\n */\ntemplate <typename Topology>\nstruct MetricSpaceConcept {\n  typename metric_topology_traits<Topology>::point_type p1, p2;\n  typename metric_topology_traits<Topology>::point_difference_type pd;\n  Topology space;\n  double d;\n  \n  BOOST_CONCEPT_USAGE(MetricSpaceConcept) \n  {\n    d  = space.distance(p1, p2);\n    d  = space.norm(pd);\n    p1 = space.random_point();\n    pd = space.difference(p1,p2);\n    p1 = space.move_position_toward(p1,d,p2);\n    p1 = space.origin();\n    p1 = space.adjust(p1,d * pd + pd - pd);\n    pd = -pd;\n    pd -= pd;\n    pd += pd;\n  };\n  \n};\n\n#endif\n", "meta": {"hexsha": "8adf4a71854b842254d12209c699cc50f84244f3", "size": 5557, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NearestNeighbor/metric_space_concept.hpp", "max_stars_repo_name": "jingtangliao/ff", "max_stars_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T07:59:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T18:11:46.000Z", "max_issues_repo_path": "NearestNeighbor/metric_space_concept.hpp", "max_issues_repo_name": "jingtangliao/ff", "max_issues_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-24T09:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-24T14:45:46.000Z", "max_forks_repo_path": "NearestNeighbor/metric_space_concept.hpp", "max_forks_repo_name": "jingtangliao/ff", "max_forks_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-01-11T15:10:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:02:10.000Z", "avg_line_length": 37.0466666667, "max_line_length": 188, "alphanum_fraction": 0.7113550477, "num_tokens": 1396, "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": "// All content Copyright (C) 2018 Genomics plc\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"readrecalibration/commonTypes.hpp\"\n#include \"stats/functions.hpp\"\n\nBOOST_AUTO_TEST_CASE( testPhredToPCache )\n{\n    for ( auto i = 0; i < 100; ++i )\n    {\n        auto cacheNumber = wecall::corrector::phred_to_p( i );\n        auto computedNumber = wecall::stats::fromPhredQ( i );\n        BOOST_CHECK_CLOSE( cacheNumber, computedNumber, 1e-8 );\n    }\n}\n", "meta": {"hexsha": "7c85bd0985c9fb81b46034fa7d9d59b8098877a0", "size": 472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/test/unittest/readrecalibration/testCommonTypes.cpp", "max_stars_repo_name": "dylex/wecall", "max_stars_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-08T15:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T07:13:05.000Z", "max_issues_repo_path": "cpp/test/unittest/readrecalibration/testCommonTypes.cpp", "max_issues_repo_name": "dylex/wecall", "max_issues_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-05T09:16:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-09T12:32:56.000Z", "max_forks_repo_path": "cpp/test/unittest/readrecalibration/testCommonTypes.cpp", "max_forks_repo_name": "dylex/wecall", "max_forks_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T15:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T07:28:33.000Z", "avg_line_length": 29.5, "max_line_length": 63, "alphanum_fraction": 0.6927966102, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5501027509367373}}
{"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": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/function/fast.hpp>\n#include <boost/simd/function/sqrt.hpp>\n#include <boost/simd/pack.hpp>\n#include <simd_test.hpp>\n\nnamespace bs = boost::simd;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test_fast(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], b[N];\n\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] =  T(N-i);\n    b[i] = bs::fast_(bs::sqrt)(a1[i]) ;\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n  STF_ULP_EQUAL(bs::fast_(bs::sqrt)(aa1), bb, 2048);\n}\n\nSTF_CASE_TPL(\"Check fast(sqrt) on pack\", STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  test_fast<T, N>($);\n  test_fast<T, N/2>($);\n  test_fast<T, N*2>($);\n}\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], b[N];\n  a1[0] = bs::Inf<T>();\n  b[0] = bs::sqrt(a1[0]);\n\n  for(std::size_t i = 1; i < N; ++i)\n  {\n    a1[i] =  T(N-i);\n    b[i] = bs::sqrt(a1[i]) ;\n  }\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n  STF_ULP_EQUAL(bs::sqrt(aa1), bb, 0.5);\n}\n\nSTF_CASE_TPL(\"Check sqrt on pack\", STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n", "meta": {"hexsha": "46ffc1de8f3e6f89fe76df10e507e8a807bedc83", "size": 1655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/sqrt.cpp", "max_stars_repo_name": "timblechmann/boost.simd", "max_stars_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "test/function/simd/sqrt.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/simd/sqrt.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 23.3098591549, "max_line_length": 100, "alphanum_fraction": 0.5172205438, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5500969876542998}}
{"text": "\n#include <Eigen/Dense>\n\n#include <boost/preprocessor/repetition/repeat.hpp>\n\n#include <chrono>\n#include <iostream>\n#include <cstdlib>\n\n// Creates a test matrix, as a diagonal square matrix with positive > 0 random\n// values.\ntemplate <typename T, int N>\nvoid create_test_matrix(Eigen::Matrix<T, N, N>& M)\n{\n  for (size_t i = 0; i < N; ++i)\n  {\n    M(i, i) = std::rand() + 1e-3;\n  }\n}\n\n// Runs a self-adjoint eigensolver to obtain the eigenvalues and eigenvectors\n// of a square matrix.\ntemplate <typename T, int N>\nbool selfadjoint_eigensolver_test(const Eigen::Matrix<T, N, N>& M)\n{\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix<T, N, N> > eigensolver(M);\n\n  return eigensolver.info() == Eigen::Success;\n}\n\ntemplate <typename T, int N>\nvoid test()\n{\n  typedef std::chrono::high_resolution_clock Time;\n  typedef std::chrono::duration<double> Duration;\n\n  Eigen::Matrix<T, N, N> M;\n  create_test_matrix(M);\n\n  const auto start = Time::now();\n\n  selfadjoint_eigensolver_test(M);\n\n  const auto end = Time::now();\n\n  const auto dt = Duration(end - start).count();\n\n  std::cout << N << \" \" << dt << std::endl;\n}\n\n#define TEST(z, n, _) test<double, n+1>();\n\nint main(int argc, char** argv)\n{\n  std::cout << \"# N = NxN Matrix size\\n\"\n            << \"# t = Time [s] to compute SelfAdjointEigenSolver\\n\"\n            << \"#\\n\"\n            << \"# N t\" << std::endl;\n\n  BOOST_PP_REPEAT(15, TEST, _)\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "fe53bd706baeae70c6a489cc0603c6ee682b31d1", "size": 1413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/selfadjoint_eigensolver_test.cpp", "max_stars_repo_name": "efernandez/eigen_tests", "max_stars_repo_head_hexsha": "8bf079bf26dfc76b06472c7061dcb56d36b48fde", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/selfadjoint_eigensolver_test.cpp", "max_issues_repo_name": "efernandez/eigen_tests", "max_issues_repo_head_hexsha": "8bf079bf26dfc76b06472c7061dcb56d36b48fde", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/selfadjoint_eigensolver_test.cpp", "max_forks_repo_name": "efernandez/eigen_tests", "max_forks_repo_head_hexsha": "8bf079bf26dfc76b06472c7061dcb56d36b48fde", "max_forks_repo_licenses": ["BSD-3-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.7384615385, "max_line_length": 78, "alphanum_fraction": 0.6426043878, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5500969874485595}}
{"text": "/* ROS-CHOMP.\n *\n * Copyright (C) 2015 Jafar Qutteineh. All rights reserved.\n * License (3-Cluase BSD): https://github.com/j3sq/ROS-CHOMP/blob/master/LICENSE\n *\n * **\n * \\file ros_chomp.cpp\n *\n * ROS support for chomp path adaptor for Cargo-ANTS project http://cargo-ants.eu/\n *\n *\n */\n#include <iostream>\n#include <Eigen/Dense>\n#include \"chomp.hpp\"\n#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include <cargo_ants_msgs/Path.h>       //received from path_planner\n#include <cargo_ants_msgs/Goal.h>       // member of Path msg\n#include <cargo_ants_msgs/ReferenceTrajectory.h>\n#include <cargo_ants_msgs/ReferenceTrajectoryPoint.h>\n#include <cargo_ants_msgs/ObstacleMap.h>\n#include <cargo_ants_msgs/Obstacle.h>\n\nusing namespace std;\ntypedef Eigen::VectorXd Vector;\ntypedef Eigen::MatrixXd Matrix;\ntypedef cargo_ants_msgs::ObstacleMap ObstacleMap;\ntypedef cargo_ants_msgs::ReferenceTrajectory Trajectory;\ntypedef cargo_ants_msgs::ReferenceTrajectoryPoint TrajectoryPoint;\nTrajectory trajectory;\nObstacleMap obstacleMap;\nVector qs(2), qe(2), xi;\n\nTrajectory generateTrajectory(Vector const &xi)\n{\n\tTrajectory trajectory;\n\ttrajectory.dt = 1.0;\n\tVector xi_copy(xi.size()+qs.size()+qe.size());\n\txi_copy<<qs,xi,qe; //copy xi and add starting point and end point\n\tvector <TrajectoryPoint> points(xi_copy.size() / 2);\n\tfor (size_t ii = 0; ii < xi_copy.size() / 2; ii++){\n\t\tpoints[ii].xx = xi_copy[ii*2];\n\t\tpoints[ii].yy = xi_copy[ii*2+1];\n\t\t//finite backward difference,mind the indicies!\n\t\tif (ii>0){\n\t\t\tpoints[ii].xd = (points[ii].xx-points[ii-1].xx)/trajectory.dt;\n\t\t\tpoints[ii].yd = (points[ii].yy-points[ii-1].yy)/trajectory.dt;\n\t\t}\n\t\tif (ii>1){\n\t\t\tpoints[ii].xdd = (points[ii].xd-points[ii-1].xd)/trajectory.dt;\n\t\t\tpoints[ii].ydd = (points[ii].yd-points[ii-1].yd)/trajectory.dt;\n\t\t}\n\t\t//ds\n\t}\n\ttrajectory.points.insert(trajectory.points.end(), points.begin(), points.end());\n\treturn trajectory;\n}\nvoid pathPlannerCallback(const cargo_ants_msgs::Path::ConstPtr &msg)\n{\n        vector <cargo_ants_msgs::Goal> goals = msg->goals;\n        if (goals.size() < 2) {\n                ROS_INFO(\"At least 2 goal points are required, received %lu\", goals.size());\n                return;\n        }\n        int n = goals.size();\n        qs << goals[0].gx, goals[0].gy;\n        qe << goals[n].gx, goals[n].gy;\n        xi[0] = goals[0].gx;\n        for (size_t ii = 0; ii < goals.size() + 1; ii++) {\n                xi[ii * 2 + 1] = goals[ii].gy;\n                xi[ii * 2 + 2] = goals[ii + 1].gx;\n        }\n}\n\n\nvoid obstaclesCallback(const cargo_ants_msgs::ObstacleMap::ConstPtr &msg)\n{\n\tobstacleMap.obstacles = msg->obstacles;\n}\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"path_adaptor\");\n\tros::NodeHandle node;\n\tros::Subscriber path_sub = node.subscribe(\"path_planner\", 1000, pathPlannerCallback);\n\tros::Subscriber obs_sub = node.subscribe(\"obstacles\", 1000, obstaclesCallback);\n\tros::Publisher trajectory_pub = node.advertise<Trajectory> ( \"/trajectory\", 10);\n\tros::Rate loop_rate (10);\n\tROS_INFO(\"path_adaptor Started!\");\n\twhile ( ros::ok() ){\n\t\tros::spinOnce();\n\t\tMatrix obs(3,obstacleMap.obstacles.size());\n\t\tfor (size_t ii = 0; ii < obstacleMap.obstacles.size() ; ++ii) {\n\t\t\tobs.col(ii) << obstacleMap.obstacles[ii].origin.ox,\n\t\t\t \t\t\t\t\t\t\t\tobstacleMap.obstacles[ii].origin.oy,\n\t\t\t\t\t\t\t\t\t\t\tobstacleMap.obstacles[ii].origin.oth;\n\t\t}\n\t\tchomp::generatePath(qs, qe, xi, obs);\n\t\ttrajectory = generateTrajectory(xi);\n\t\ttrajectory_pub.publish(trajectory);\n\t\tloop_rate.sleep();\n}\n\treturn 0;\n\t// VectorXd qs(2);  //Start goal  coordinates (x,y)\n\t// VectorXd qe(2);  //End goal  coordinates (x,y)\n\t// VectorXd xi;     //Trajectory points (x0,y0,x1,y1,....)\n\t// MatrixXd obs;    //obstacles |x0,y0,R0;x1,y1,R1...|\n\t//\n\t// qs << 0, 0;\n\t// qe << 3, 5;\n\t//\n\t//\n\t// generatePath(qs, qe, xi, obs);\n\t// cout << xi << std::endl;\n}\n", "meta": {"hexsha": "39befc5ad8688ffbb965943b31a9dffa93562d02", "size": 3817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros/src/ros_chomp.cpp", "max_stars_repo_name": "j3sq/ROS-CHOMP", "max_stars_repo_head_hexsha": "60731f3c7b8d489e2a3ffa38e526dbfc7ba292c3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-27T16:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-27T16:00:51.000Z", "max_issues_repo_path": "ros/src/ros_chomp.cpp", "max_issues_repo_name": "j3sq/ROS-CHOMP", "max_issues_repo_head_hexsha": "60731f3c7b8d489e2a3ffa38e526dbfc7ba292c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ros/src/ros_chomp.cpp", "max_forks_repo_name": "j3sq/ROS-CHOMP", "max_forks_repo_head_hexsha": "60731f3c7b8d489e2a3ffa38e526dbfc7ba292c3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-10T02:44:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T02:06:44.000Z", "avg_line_length": 32.6239316239, "max_line_length": 92, "alphanum_fraction": 0.6623002358, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.550096982054339}}
{"text": "/*! \\file demo_boxplot.cpp\n    \\brief Demonstration of boxplots.\n    \\details Contains Quickbook Markup to be included in documentation.\n\n    \\author Jacob Voytko and Paul A. Bristow \n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 2008, 2012\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// An example to demonstrate some use of boxplot options.\n// See also boxplot_full.cpp for a even wider range of use.\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_boxplot_1\n\n/*`\nBoxplot is a  convenient way of graphically depicting groups of numerical data \nthrough their five-number summaries.\nShow 1st quartile, median and 3rd quartile as a box,\n95% confidence interval as whiskers,\nand outliers and extreme outliers.\n\nSee [@http://en.wikipedia.org/wiki/Boxplot boxplot] and\n\nSome Implementations of the Boxplot\nMichael Frigge, David C. Hoaglin and Boris Iglewicz\nThe American Statistician, Vol. 43, No. 1 (Feb., 1989), pp. 50-54\n\nFirst we need a few includes to use Boost.Plot.\n*/\n\n#include <vector>\nusing std::vector;\n#include <cmath>\nusing ::sin;\n#include <boost/svg_plot/svg_boxplot.hpp>\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n/*`Use two functions, 1/x and sin(x), to simulate distributions.\n*/\n\ndouble f(double x)\n{ // Effectively 1/x.\n  return 50 / x;\n}\n\ndouble g(double x)\n{ // Effectively sin(x).\n  return 40 + 25 * sin(x * 50);\n}\n//] [demo_boxplot_1]\n\nint main()\n{\n  using namespace boost::svg;\n  try\n  {\n//[demo_boxplot_2]\n/*`10 values are computed and stored in two std:: vectors.\n*/\n  std::vector<double> data1;\n  std::vector<double> data2;\n\n  cout.precision(2);\n  for(double i = 0.1; i < 10; i += 0.1)\n  {   // Fill our vectors with 100 values:\n    double fv = f(i);\n    double gv = g(i);\n    // cout << i << ' ' << fv << ' ' << gv << endl;\n    data1.push_back(fv);\n    data2.push_back(gv);\n  }\n\n/*`A new boxplot is contructed and several settings added.\n*/\n  svg_boxplot my_boxplot;\n\n  my_boxplot.background_border_color(darkblue);\n  my_boxplot.background_color(azure);\n\n  my_boxplot  // Title and axes labels.\n    .title(\"Boxplots of 1/x and sin(x) Functions\")\n    .x_label(\"Functions\")\n    .y_label(\"Population Size\");\n\n  my_boxplot.y_range(0, 100)  // Y-Axis information.\n    .y_minor_tick_length(10)\n    .y_major_interval(20);\n\n   // box'n'whiskers options apply to the plot, AND for each data series boxplot\n   // so can be set for all boxplots or separately for each plot.\n   my_boxplot.plot(data1, \"test\").box_width(10).whisker_length(5).box_style().fill_color(pink).stroke_color(green);\n   // TODO these should be chainable like: .box_fill(pink), box_stroke(green)...\n   //my_boxplot.plot(data1, \"test\").box_width(10).whisker_length(5).median_style().stroke_color(purple);\n\n\n/*`Add the two data series containers, and their labels, to the plot.\n*/\n\n  my_boxplot.plot(data1, \"[50 / x]\");\n  my_boxplot.plot(data2, \"[40+25*sin(x*50)]\");\n\n/*  cout << \"my_boxplot.title \" << my_boxplot.title() << endl;\n  cout << \"my_boxplot.x_label_text \"<< my_boxplot.x_label_text() << endl;\n  cout << \"my_boxplot.y_label_text \" << my_boxplot.y_label_text() << endl; \n\n  cout << \"my_boxplot.background_color \" << my_boxplot.background_color() << endl;\n  cout << \"my_boxplot.background_border_color \" << my_boxplot.background_border_color() << endl;\n  cout << \"my_boxplot.plot_background_color \" << my_boxplot.plot_background_color() << endl;\n cout << \"my_boxplot.plot_border_color \" << my_boxplot.plot_border_color() << endl;\n*/ \n\n//`Finally write the SVG plot to a file.\n  my_boxplot.write(\"demo_boxplot.svg\");\n/*`You can view the plot at demo_boxplot.svg.\"\n*/\n\n//] [demo_boxplot_2]\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n  \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n/*\n\nOutput:\n\nCompiling...\ndemo_boxplot.cpp\nLinking...\nEmbedding manifest...\nAutorun \"j:\\Cpp\\SVG\\debug\\demo_boxplot.exe\"\nBuild Time 0:02\n\n*/\n\n", "meta": {"hexsha": "65df39b76b9b706b76bff35e04fb8741d56c96fd", "size": 4369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_boxplot.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_boxplot.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_boxplot.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": 28.0064102564, "max_line_length": 115, "alphanum_fraction": 0.6978713664, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.5500969782144133}}
{"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 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_histogram_reduction\n\n#include <boost/histogram.hpp>\n#include <cassert>\n\nint main() {\n  using namespace boost::histogram;\n  // import reduce commands into local namespace to save typing\n  using algorithm::rebin;\n  using algorithm::shrink;\n  using algorithm::slice;\n\n  // make a 2d histogram\n  auto h = make_histogram(axis::regular<>(4, 0.0, 4.0), axis::regular<>(4, -2.0, 2.0));\n\n  h(0, -0.9);\n  h(1, 0.9);\n  h(2, 0.1);\n  h(3, 0.1);\n\n  // reduce takes positional commands which are applied to the axes in order\n  // - shrink is applied to the first axis; the new axis range is 0.0 to 3.0\n  // - rebin is applied to the second axis; pairs of adjacent bins are merged\n  auto h2 = algorithm::reduce(h, shrink(0.0, 3.0), rebin(2));\n\n  assert(h2.axis(0) == axis::regular<>(3, 0.0, 3.0));\n  assert(h2.axis(1) == axis::regular<>(2, -2.0, 2.0));\n\n  // reduce does not change the total count if the histogram has underflow/overflow bins\n  assert(algorithm::sum(h) == 4 && algorithm::sum(h2) == 4);\n\n  // One can also explicitly specify the index of the axis in the histogram on which the\n  // command should act, by using this index as the the first parameter. The position of\n  // the command in the argument list of reduce is then ignored. We use this to slice only\n  // the second axis (axis has index 1 in the histogram) from bin index 2 to 4.\n  auto h3 = algorithm::reduce(h, slice(1, 2, 4));\n\n  assert(h3.axis(0) == h.axis(0)); // unchanged\n  assert(h3.axis(1) == axis::regular<>(2, 0.0, 2.0));\n}\n\n//]\n", "meta": {"hexsha": "67762530554bf7b8a41536114d8a5be27f3e54fd", "size": 1706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/histogram/examples/guide_histogram_reduction.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 188.0, "max_stars_repo_stars_event_min_datetime": "2019-02-08T14:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T08:37:05.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/histogram/examples/guide_histogram_reduction.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 186.0, "max_issues_repo_issues_event_min_datetime": "2016-05-05T14:01:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-20T22:38:43.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/histogram/examples/guide_histogram_reduction.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2019-02-09T16:16:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T20:24:36.000Z", "avg_line_length": 34.8163265306, "max_line_length": 90, "alphanum_fraction": 0.6758499414, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5500739024521792}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"utilitaires.h\"\n#include \"permutation.h\"\n\nBOOST_AUTO_TEST_SUITE(test_permutation)\n\n    BOOST_AUTO_TEST_CASE(permutation_simple) {\n        const std::vector<std::vector<int>> resultat{\n                {1, 2, 3},\n                {1, 3, 2},\n                {2, 1, 3},\n                {2, 3, 1},\n                {3, 1, 2},\n                {3, 2, 1}\n        };\n\n        size_t index = 0;\n        const std::vector<int> v{1, 2, 3};\n        for (auto i: permutation::Permutation<std::vector<int>>(v)) {\n            BOOST_CHECK_EQUAL_COLLECTIONS(i.begin(), i.end(),\n                                          resultat[index].begin(), resultat[index].end());\n            ++index;\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(permutation_doublon) {\n        const std::vector<std::vector<int>> resultat{\n                {1, 2, 2, 4},\n                {1, 2, 4, 2},\n                {1, 4, 2, 2},\n                {2, 1, 2, 4},\n                {2, 1, 4, 2},\n                {2, 2, 1, 4},\n                {2, 2, 4, 1},\n                {2, 4, 1, 2},\n                {2, 4, 2, 1},\n                {4, 1, 2, 2},\n                {4, 2, 1, 2},\n                {4, 2, 2, 1}\n        };\n\n        size_t index = 0;\n        const std::vector<int> v{1, 2, 2, 4};\n        for (auto i: permutation::Permutation<std::vector<int>>(v)) {\n            BOOST_CHECK_EQUAL_COLLECTIONS(i.begin(), i.end(),\n                                          resultat[index].begin(), resultat[index].end());\n            ++index;\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(arrangements_simple) {\n        const std::vector<std::vector<int>> resultat{\n                {1, 2, 3},\n                {1, 3, 2},\n                {2, 1, 3},\n                {2, 3, 1},\n                {3, 1, 2},\n                {3, 2, 1},\n                {1, 2, 4},\n                {1, 4, 2},\n                {2, 1, 4},\n                {2, 4, 1},\n                {4, 1, 2},\n                {4, 2, 1},\n                {1, 3, 4},\n                {1, 4, 3},\n                {3, 1, 4},\n                {3, 4, 1},\n                {4, 1, 3},\n                {4, 3, 1},\n                {2, 3, 4},\n                {2, 4, 3},\n                {3, 2, 4},\n                {3, 4, 2},\n                {4, 2, 3},\n                {4, 3, 2}\n        };\n\n        size_t index = 0;\n\n        std::vector<int> iterable{1, 2, 3, 4};\n        for (auto &i: permutation::Arrangements<int>(iterable, 3)) {\n            BOOST_CHECK_EQUAL_COLLECTIONS(i.begin(), i.end(),\n                                          resultat[index].begin(), resultat[index].end());\n            ++index;\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(arrangements_doublon) {\n        const std::vector<std::string> resultat{\"AB\", \"BA\", \"AD\", \"DA\", \"BB\", \"BD\", \"DB\"};\n\n        size_t index = 0;\n\n        std::vector<char> iterable{'A', 'B', 'B', 'D'};\n        for (auto &i: permutation::Arrangements<char>(iterable, 2)) {\n            BOOST_CHECK_EQUAL_COLLECTIONS(i.begin(), i.end(),\n                                          resultat[index].begin(), resultat[index].end());\n            ++index;\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(combinaisons_simple) {\n        const std::vector<std::vector<int>> resultat{\n                {1, 2, 3},\n                {1, 2, 4},\n                {1, 3, 4},\n                {2, 3, 4}\n        };\n\n        size_t index = 0;\n        std::vector<int> iterable{1, 2, 3, 4};\n        for (auto i : permutation::Combinaisons<int>(iterable, 3)) {\n            BOOST_CHECK_EQUAL_COLLECTIONS(i.begin(), i.end(),\n                                          resultat[index].begin(), resultat[index].end());\n            ++index;\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(combinaisons_doublon) {\n        const std::vector<std::string> resultat{\"AB\", \"AC\", \"AD\", \"BC\", \"BD\", \"CD\"};\n\n        size_t index = 0;\n        std::vector<char> iterable{'A', 'B', 'C', 'D'};\n        for (auto i : permutation::Combinaisons<char>(iterable, 2)) {\n            BOOST_CHECK_EQUAL_COLLECTIONS(i.begin(), i.end(),\n                                          resultat[index].begin(), resultat[index].end());\n            ++index;\n        }\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4692f25340e1e89b1bc9ae0a5aa9bdcc16a91ca4", "size": 4179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/permutation.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "tests/permutation.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/permutation.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4210526316, "max_line_length": 90, "alphanum_fraction": 0.4015314669, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5500224491681646}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2014 Adam Wulkiewicz, Lodz, Poland.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[boost_polygon_box\r\n//`Shows how to use Boost.Polygon rectangle_data within Boost.Geometry\r\n\r\n#include <iostream>\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_polygon.hpp>\r\n\r\nint main()\r\n{\r\n    typedef boost::polygon::rectangle_data<int> rect;\r\n\r\n    rect b = boost::polygon::construct<rect>(1, 2, 3, 4);\r\n\r\n    std::cout << \"Area (using Boost.Geometry): \"\r\n        << boost::geometry::area(b) << std::endl;\r\n    std::cout << \"Area (using Boost.Polygon): \"\r\n        << boost::polygon::area(b) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n//[boost_polygon_box_output\r\n/*`\r\nOutput:\r\n[pre\r\nArea (using Boost.Geometry): 4\r\nArea (using Boost.Polygon): 4\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "d2ab7593d305a6067aa41fbaf541f4287f04f19a", "size": 1099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/geometries/adapted/boost_polygon_box.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/doc/src/examples/geometries/adapted/boost_polygon_box.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/doc/src/examples/geometries/adapted/boost_polygon_box.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": 25.5581395349, "max_line_length": 80, "alphanum_fraction": 0.6642402184, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.5500224491681645}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n//#define GRAPHBLAS_LOGGING_LEVEL 2\n\n#include <graphblas/graphblas.hpp>\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE mxm_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nusing namespace grb;\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\n\nnamespace\n{\n    static std::vector<std::vector<double> > A_dense_3x3 =\n    {{12, 7, 3},\n     {4,  5, 6},\n     {7,  8, 9}};\n\n    static std::vector<std::vector<double> > AT_dense_3x3 =\n    {{12, 4, 7},\n     {7,  5, 8},\n     {3,  6, 9}};\n\n    static std::vector<std::vector<double> > B_dense_3x4 =\n    {{5, 8, 1, 2},\n     {6, 7, 3, 0.},\n     {4, 5, 9, 1}};\n\n    static std::vector<std::vector<double> > BT_dense_3x4 =\n    {{5, 6, 4},\n     {8, 7, 5},\n     {1, 3, 9},\n     {2, 0, 1}};\n\n    static std::vector<std::vector<double> > Answer_dense =\n    {{114, 160, 60,  27},\n     {74,  97,  73,  14},\n     {119, 157, 112, 23}};\n\n    static std::vector<std::vector<double> > Answer_plus1_dense =\n    {{115, 161, 61,  28},\n     {75,  98,  74,  15},\n     {120, 158, 113, 24}};\n\n    static std::vector<std::vector<double> > A_sparse_3x3 =\n    {{12, 7,  0},\n     {0, -5,  0},\n     {7,  0,  9}};\n\n    static std::vector<std::vector<double> > AT_sparse_3x3 =\n    {{12, 0,  7},\n     {7, -5,  0},\n     {0,  0,  9}};\n\n    static std::vector<std::vector<double> > B_sparse_3x4 =\n    {{5., 8.,  0, -2.},\n     {0., -7,  3., 0.},\n     {4., 0,   0,  1.}};\n\n    static std::vector<std::vector<double> > BT_sparse_3x4 =\n    {{5.,  0., 4},\n     {8., -7,  0.},\n     {0.,  3,  0.},\n     {-2., 0,  1}};\n\n    // A_sparse_3x3 * A_sparse_3x3\n    static std::vector<std::vector<double> > AA_answer_sparse =\n    {{144.,  49., 0},\n     {0.0,   25., 0},\n     {147.,  49., 81.}};\n\n    // A_sparse_3x3 * B_sparse_3x4\n    static std::vector<std::vector<double> > Answer_sparse =\n    {{60,   47., 21,  -24},\n     {0.0,  35.,-15,  0.0},\n     {71.0, 56,  0.0, -5.0}};\n\n    static std::vector<std::vector<double> > Symmetric_4x4 =\n    {{1, 1, 0, 0},\n     {1, 2, 2, 0},\n     {0, 2, 3, 3},\n     {0, 0, 3, 4}};\n\n    static std::vector<std::vector<double> > Symmetric2_4x4 =\n    {{2, 3, 2, 0},\n     {3, 9,10, 6},\n     {2,10,22,21},\n     {0, 6,21,25}};\n\n    static std::vector<std::vector<double> > Ones_4x4 =\n    {{1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > Ones_3x4 =\n    {{1, 1, 1, 1},\n     {1, 1, 1, 1},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > Ones_3x3 =\n    {{1, 1, 1},\n     {1, 1, 1},\n     {1, 1, 1}};\n\n    static std::vector<std::vector<double> > Identity_3x3 =\n    {{1, 0, 0},\n     {0, 1, 0},\n     {0, 0, 1}};\n\n    static std::vector<std::vector<double> > Lower_3x3 =\n    {{1, 0, 0},\n     {1, 1, 0},\n     {1, 1, 1}};\n\n    static std::vector<std::vector<double> > Lower_3x4 =\n    {{1, 0, 0, 0},\n     {1, 1, 0, 0},\n     {1, 1, 1, 0}};\n\n    static std::vector<std::vector<double> > Lower_4x4 =\n    {{1, 0, 0, 0},\n     {1, 1, 0, 0},\n     {1, 1, 1, 0},\n     {1, 1, 1, 1}};\n\n    static std::vector<std::vector<double> > NotLower_3x3 =\n    {{0, 1, 1},\n     {0, 0, 1},\n     {0, 0, 0}};\n\n    static std::vector<std::vector<double> > NotLower_3x4 =\n    {{0, 1, 1, 1},\n     {0, 0, 1, 1},\n     {0, 0, 0, 1}};\n\n    static std::vector<std::vector<double> > NotLower_4x4 =\n    {{0, 1, 1, 1},\n     {0, 0, 1, 1},\n     {0, 0, 0, 1},\n     {0, 0, 0, 0}};\n\n    static std::vector<std::vector<double> > LowerMask_3x4 =\n    {{1, 0,    0,   0},\n     {1, 0.5,  0,   0},\n     {1, -1.0, 1.5, 0}};\n\n    static std::vector<std::vector<bool> > LowerBool_3x4 =\n    {{true, false, false, false},\n     {true, true,  false, false},\n     {true, true,  true,  false}};\n\n    static std::vector<std::vector<bool> > LowerBool_3x3 =\n    {{true, false, false},\n     {true, true,  false},\n     {true, true,  true}};\n\n    static std::vector<std::vector<bool> > NotLowerBool_3x3 =\n    {{false,  true, true},\n     {false, false, true},\n     {false, false, false}};\n\n}\n\n//****************************************************************************\n// NoMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT)\n{\n    grb::Matrix<double> C(3, 4);\n    grb::Matrix<double> A(AT_sparse_3x3, 0.);\n    grb::Matrix<double> B(BT_sparse_3x4, 0.);\n\n    grb::Matrix<double> answer(Answer_sparse, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    for (grb::IndexType ix = 0; ix < answer.nrows(); ++ix)\n    {\n        for (grb::IndexType iy = 0; iy < answer.ncols(); ++iy)\n        {\n            BOOST_CHECK_EQUAL(C.hasElement(ix, iy), answer.hasElement(ix, iy));\n            if (C.hasElement(ix, iy))\n            {\n                BOOST_CHECK_CLOSE(C.extractElement(ix,iy),\n                                  answer.extractElement(ix,iy), 0.0001);\n            }\n        }\n    }\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_empty)\n{\n    grb::Matrix<double> Zero(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(Ones_3x3, 0.);\n    grb::Matrix<double> mD(Ones_3x3, 0.);\n\n    grb::mxm(C,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Zero), transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Zero);\n\n    grb::mxm(mD,\n             NoMask(), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Zero));\n    BOOST_CHECK_EQUAL(mD, Zero);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_dense)\n{\n    Matrix<double, DirectedMatrixTag> A(AT_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(BT_dense_3x4, 0.);\n\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n\n    mxm(result,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(A), transpose(B));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 7, 15},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11, 15}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(),\n             transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    std::vector<std::vector<double>> answer_vals = {{0, 8, 0, 8},\n                                                    {0, 1, 0, 1},\n                                                    {0, 4, 0, 4}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_ABdup)\n{\n    // Build some matrices.\n    Matrix<double, DirectedMatrixTag> mat(Symmetric_4x4, 0.);\n    Matrix<double, DirectedMatrixTag> m3(4, 4);\n    Matrix<double, DirectedMatrixTag> answer(Symmetric2_4x4, 0.);\n\n    mxm(m3,\n        grb::NoMask(), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(m3, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_ACdup)\n{\n    grb::Matrix<double> C(AT_sparse_3x3, 0.);\n    grb::Matrix<double> B(AT_sparse_3x3, 0.);\n\n    grb::Matrix<double> answer(AA_answer_sparse, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(),\n             transpose(C), transpose(B));\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_NoAccum_ATBT_BCdup)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.);\n    grb::Matrix<double> C(AT_sparse_3x3, 0.);\n\n    grb::Matrix<double> answer(AA_answer_sparse, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(),\n             transpose(A), transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n//****************************************************************************\n// NoMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATBT)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.); // 3x3\n    grb::Matrix<double> B(BT_dense_3x4, 0.); // 3x4\n    grb::Matrix<double> result(3, 4);\n    grb::Matrix<double> answer(Answer_dense, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATBT_empty)\n{\n    grb::Matrix<double> Zero(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(Ones_3x3, 0.);\n    grb::Matrix<double> mD(Ones_3x3, 0.);\n\n    grb::mxm(C,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Zero), transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    grb::mxm(mD,\n             NoMask(), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Zero));\n    BOOST_CHECK_EQUAL(mD, Ones);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATBT_stored_zero_result)\n{\n    // Build some matrices.\n    std::vector<std::vector<int> > BT_mat = {{ 1,-1, 0,  0},\n                                             {-2, 1, 0,  0},\n                                             { 0, 0, 3, -3},\n                                             { 0, 0,-4,  3}};\n    grb::Matrix<double> A(Symmetric_4x4, 0);\n    grb::Matrix<int> B(BT_mat, 0);\n    grb::Matrix<int> result(4, 4);\n\n    // use a different sentinel value so that stored zeros are preserved.\n    int const NIL(666);\n    std::vector<std::vector<int> > ans = {{  0,  -1, NIL, NIL},\n                                          { -1,   0,   6,  -8},\n                                          { -2,   2,   0,  -3},\n                                          {NIL, NIL,  -3,   0}};\n    grb::Matrix<int> answer(ans, NIL);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<int>(),\n             grb::ArithmeticSemiring<int>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result, answer);\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATBT_ABdup_Cempty)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> result(4, 4);\n    grb::Matrix<double> answer(Symmetric2_4x4, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATBT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> BTvals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    std::vector<std::vector<double>> answer_vals = {{2, 1, 8, 16},\n                                                    {1, 1, 1, 1},\n                                                    {10,1, 12, 16}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(BTvals, 0.);\n    grb::Matrix<double> result(Ones_3x4, 0.);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATBT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> BTvals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    std::vector<std::vector<double>> answer_vals = {{1, 9, 1, 9},\n                                                    {1, 2, 1, 2},\n                                                    {1, 5, 1, 5}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(BTvals, 0.);\n    grb::Matrix<double> result(Ones_3x4, 0.);\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    grb::mxm(result,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATBT_ABdup)\n{\n    // Build some matrices.\n    Matrix<double> mat(AT_sparse_3x3,0.);\n    Matrix<double> m3(Ones_3x3, 0.);\n\n    // A_sparse_3x3 * A_sparse_3x3 + Ones\n    static std::vector<std::vector<double> > ans =\n        {{145.,  50.,   1.},\n         {  1,   26.,   1.},\n         {148.,  50,   82.}};\n\n    Matrix<double> answer(ans, 0.);\n\n    mxm(m3,\n        grb::NoMask(), grb::Plus<double>(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(m3, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATBT_ACdup)\n{\n    grb::Matrix<double> C(AT_sparse_3x3, 0.);\n    grb::Matrix<double> B(AT_sparse_3x3, 0.);\n\n    // A_sparse_3x3 * A_sparse_3x3 + A_sparse_3x3\n    static std::vector<std::vector<double> > ans =\n        {{156.,  49.,   7.0},\n         { 7.,   20.,   0.0},\n         {147.,  49.,  90.0}};\n    Matrix<double> answer(ans, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(),\n             transpose(C), transpose(B));\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_NoMask_Accum_ATBT_BCdup)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.);\n    grb::Matrix<double> C(AT_sparse_3x3, 0.);\n\n    // A_sparse_3x3 * A_sparse_3x3 + A_sparse_3x3\n    static std::vector<std::vector<double> > ans =\n        {{156.,  49.,   7.0},\n         { 7.,   20.,   0.0},\n         {147.,  49.,  90.0}};\n    Matrix<double> answer(ans, 0.);\n\n    grb::mxm(C,\n             grb::NoMask(),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n}\n\n// ****************************************************************************\n// Mask_NoAccum\n// ****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBT)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> AT(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             Ones, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, AT);\n\n    C = Ones;\n    grb::mxm(C,\n             AT, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             Ones, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, AT);\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBTM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones));\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty));\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             M, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBT_Merge_full_mask)\n{\n    Matrix<double, DirectedMatrixTag> A(AT_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(BT_dense_3x4, 0.);\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n\n    Matrix<double, DirectedMatrixTag> mask(Ones_3x4);\n\n    mxm(result,\n        mask, grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(A), transpose(B));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBT_mask_not_full)\n{\n    Matrix<double, DirectedMatrixTag> A(AT_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(BT_dense_3x4, 0.);\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    Matrix<double, DirectedMatrixTag> mask(Answer_dense, 0.);\n\n    mxm(result,\n        mask, grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(A), transpose(B));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBT_Merge_Cones_Mlower_stored_zero)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(Lower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBT_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBT_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_NoAccum_ATBT_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\n// Mask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> AT(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             AT, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             Ones, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             MLower, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             MNotLower, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBTMempty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             M, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             Empty, Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 1, 8},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 8},\n                                                     {1, 1, 1},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             NotLower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_ACdup)\n{\n\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             Lower,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  0,  0,  0},\n                                             {4, 10,  0,  0},\n                                             {3, 11, 23,  0},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             C,\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_Replace_lower_mask_result_ones)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(LowerMask_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_Replace_bool_masked_result_ones)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<bool> M(LowerBool_3x4, false);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_Replace_mask_stored_zero_result_ones)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(Lower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B),\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_Mask_Accum_ATBT_Merge_Cones_Mlower)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > M_3x4 = {{1, 0, 0, 0},\n                                                      {1, 1, 0, 0},\n                                                      {1, 1, 1, 0}};\n    grb::Matrix<double> M(M_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             M,\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATBT)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> AT(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > Not_A_sparse_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_sparse_3x3, 0.0);\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, AT);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotA), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, AT);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATBT_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> Identity(Identity_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones));\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty));\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(mUpper), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Ones);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATBT_Merge_Cones_Mlower_stored_zero)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             complement(M),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATBT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATBT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATBT_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x3, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATBT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATBT_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATBT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_NoAccum_ATBT_Replace_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    static std::vector<std::vector<double> > Not_A_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_3x3, 0.0);\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotA), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Empty), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBTM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> MNotLower(NotLowerBool_3x3, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             complement(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(MNotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_ACdup)\n{\n\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_Replace_Cones_Mnlower)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B),\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_Replace_Mstored_zero)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n\n    M.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B),\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_Merge)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_Merge_Mstored_zero)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 7);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompMask_Accum_ATBT_Merge_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n\n    grb::mxm(result,\n             grb::complement(M),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// Structure tests\n//****************************************************************************\n\n// ****************************************************************************\n// StructMask_NoAccum\n// ****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATBT)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> AT(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, AT);\n    Ones.setElement(0, 0, 1.);\n\n    C = Ones;\n    AT.setElement(0, 1, 0.);\n    grb::mxm(C,\n             structure(AT), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, AFilled);\n    AT.setElement(0, 1, 7.);\n\n    C = Ones;\n    MLower.setElement(2, 0, 0.);\n    grb::mxm(C,\n             structure(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    MNotLower.setElement(0, 2, 0.);\n    grb::mxm(C,\n             structure(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Empty), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, AT);\n    Ones.setElement(0, 0, 1.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    MLower.setElement(2, 0, 1.);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MNotLower), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    MNotLower.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATBTM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n    M.setElement(2, 0, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones));\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty));\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATBT_Merge_full_mask)\n{\n    Matrix<double, DirectedMatrixTag> A(AT_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(BT_dense_3x4, 0.);\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n\n    Matrix<double, DirectedMatrixTag> mask(Ones_3x4);\n    mask.setElement(0, 0, 0.);\n\n    mxm(result,\n        structure(mask), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(A), transpose(B));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATBT_mask_not_full)\n{\n    Matrix<double, DirectedMatrixTag> A(AT_dense_3x3, 0.);\n    Matrix<double, DirectedMatrixTag> B(BT_dense_3x4, 0.);\n    Matrix<double, DirectedMatrixTag> answer(Answer_dense, 0.);\n    Matrix<double, DirectedMatrixTag> result(3, 4);\n\n    Matrix<double, DirectedMatrixTag> mask(Answer_dense, 0.);\n    mask.setElement(0, 0, 0.);\n\n    mxm(result,\n        structure(mask), grb::NoAccumulate(),\n        grb::ArithmeticSemiring<double>(),\n        transpose(A), transpose(B));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATBT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATBT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 1, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATBT_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATBT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATBT_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATBT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_NoAccum_ATBT_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             structure(C),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             structure(C),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\n// StructMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBT)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> AT(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    MLower.setElement(2, 0, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n    MNotLower.setElement(0, 1, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // vs Mfull vs Mlower\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    AT.setElement(0, 2, 0.);\n    grb::mxm(C,\n             structure(AT), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mfull vs Mlower\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             structure(Ones), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             structure(MNotLower), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBTMempty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n    M.setElement(2, 0, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Empty), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             structure(M), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Empty), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBT_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x3, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 1, 8},\n                                                    {0, 0, 1},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 8},\n                                                     {1, 1, 1},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(NotLower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBT_ACdup)\n{\n\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             structure(Lower),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBT_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> Lower(Lower_4x4, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  0,  0,  0},\n                                             {4, 10,  0,  0},\n                                             {2, 11, 23,  0},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             structure(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {2, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Lower;\n    grb::mxm(C,\n             structure(C),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBT_Replace_lower_mask_result_ones)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(LowerMask_3x4, 0.);\n    M.setElement(2, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             structure(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBT_Replace_bool_masked_result_ones)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<bool> M(LowerBool_3x4, false);\n    M.setElement(2, 0, false);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             structure(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_StructMask_Accum_ATBT_Merge_Cones_Mlower)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n\n    static std::vector<std::vector<double> > M_3x4 = {{1, 0, 0, 0},\n                                                      {1, 1, 0, 0},\n                                                      {1, 1, 1, 0}};\n    grb::Matrix<double> M(M_3x4, 0.);\n    M.setElement(2, 0, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             structure(M),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompStructMask_NoAccum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATBT)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> AT(A_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    MLower.setElement(2, 0, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n    MNotLower.setElement(0, 2, 0.);\n\n    static std::vector<std::vector<double> > Not_A_sparse_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_sparse_3x3, 0.0);\n    NotA.setElement(1, 0, 0.);\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, AT);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotA)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, AFilled);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n    Ones.setElement(0, 0, 1.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, AT);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    MLower.setElement(2, 0, 1.);\n    BOOST_CHECK_EQUAL(C, MLower);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    MNotLower.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, MNotLower);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATBT_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> Identity(Identity_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<bool> M(LowerBool_3x3, false);\n    M.setElement(2, 0, false);\n\n    grb::Matrix<double> mUpper(NotLower_3x3, 0.);\n    mUpper.setElement(0, 2, 0.);\n\n    // Merge\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones));\n    mUpper.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    mUpper.setElement(0, 2, 0.);\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty));\n    mUpper.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, mUpper);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(mUpper)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Ones)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    C = Empty;\n    grb::mxm(C,\n             complement(structure(Empty)), NoAccumulate(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Ones);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATBT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {0, 0, 0, 0},\n                                                    {9, 0, 11,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {0, 0, 1, 1},\n                                                     {9, 0, 11,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATBT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 0, 0},\n                                                    {0, 1, 0, 0},\n                                                    {0, 4, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{0, 1, 1, 1},\n                                                     {0, 1, 1, 1},\n                                                     {0, 4, 0, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATBT_emptyRowM)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> Lower(Lower_3x3, 0.);\n    Lower.setElement(2, 0, 0.);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // Replace\n    std::vector<std::vector<double>> answer_vals = {{0, 0, 7},\n                                                    {0, 0, 0},\n                                                    {0, 0, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Lower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 0, 7},\n                                                     {1, 1, 0},\n                                                     {1, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Lower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATBT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATBT_ACdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATBT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  1,  0,  0},\n                                             {3,  9,  2,  0},\n                                             {2, 10, 22,  3},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_NoAccum_ATBT_Replace_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  0,  0,  0},\n                                             {3,  9,  0,  0},\n                                             {2, 10, 22,  0},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n    M.setElement(0, 1, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\n// CompStructMask_Accum\n//****************************************************************************\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATBT)\n{\n    grb::Matrix<double> A(AT_sparse_3x3, 0.0);\n    grb::Matrix<double> Identity(Identity_3x3, 0.0);\n\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    grb::Matrix<double> MLower(Lower_3x3, 0.);\n    MLower.setElement(2, 0, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x3, 0.);\n    MNotLower.setElement(0, 2, 0.);\n\n    static std::vector<std::vector<double> > A_sparse_fill_in_3x3 =\n        {{12, 7,  1},\n         {1, -5,  1},\n         {7,  1,  9}};\n    grb::Matrix<double> AFilled(A_sparse_fill_in_3x3, 0.0);\n\n\n    static std::vector<std::vector<double> > Not_A_3x3 =\n        {{0,  0,  1},\n         {1,  0,  1},\n         {0,  1,  0}};\n    grb::Matrix<double> NotA(Not_A_3x3, 0.0);\n\n    // Merge\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    //---\n    static std::vector<std::vector<double> > ans =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotA)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans2 =\n        {{2,  1,  1},\n         {2,  2,  1},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans2, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans3 =\n        {{1,  2,  2},\n         {1,  1,  2},\n         {1,  1,  1}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity));\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans3, 0.));\n\n    // Replace\n    // Mempty vs Mfull vs Mlower\n\n    C = Ones;\n    Ones.setElement(0, 0, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    Ones.setElement(0, 0, 1.);\n    BOOST_CHECK_EQUAL(C, Empty);\n\n    //---\n    static std::vector<std::vector<double> > ans4 =\n        {{13, 8,  1},\n         {1, -4,  1},\n         {8,  1, 10}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(Empty)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(A), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans4, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans5 =\n        {{2,  0,  0},\n         {2,  2,  0},\n         {2,  2,  2}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans5, 0.));\n\n    //---\n    static std::vector<std::vector<double> > ans6 =\n        {{0,  2,  2},\n         {0,  0,  2},\n         {0,  0,  0}};\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Identity), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(ans6, 0.));\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATBTM_empty)\n{\n    grb::Matrix<double> Empty(3, 3);\n    grb::Matrix<double> Ones(Ones_3x3, 0.);\n    grb::Matrix<double> C(3,3);\n\n    // NOTE: The mask is true for any non-zero.\n    grb::Matrix<bool> MNotLower(NotLowerBool_3x3, false);\n    MNotLower.setElement(0, 2, false);\n\n    // Merge\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty));\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    C = Ones;\n    Ones.setElement(0, 2, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Ones));\n    Ones.setElement(0, 2, 1.);\n    BOOST_CHECK_EQUAL(C, Ones);\n\n    // Replace\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Empty), transpose(Ones), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Matrix<double>(Lower_3x3, 0.));\n\n    C = Ones;\n    Ones.setElement(0, 2, 0.);\n    grb::mxm(C,\n             complement(structure(Ones)), Plus<double>(),\n             ArithmeticSemiring<double>(), transpose(Ones), transpose(Empty), REPLACE);\n    BOOST_CHECK_EQUAL(C, Empty);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATBT_emptyRowA_emptyColB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 0, 4},\n                                               {1, 0, 9},\n                                               {6, 0, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {0, 0, 0},\n                                               {0, 1, 1},\n                                               {1, 1, 1}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> MNotLower(NotLower_3x4, 0.);\n    MNotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{2, 0, 0, 0},\n                                                    {1, 1, 0, 0},\n                                                    {10,1, 12,0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{2, 1, 1, 1},\n                                                     {1, 1, 1, 1},\n                                                     {10,1,12,1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(MNotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATBT_emptyColA_emptyRowB)\n{\n    std::vector<std::vector<double>> A_vals = {{8, 1, 4},\n                                               {0, 0, 0},\n                                               {6, 9, 2}};\n\n    std::vector<std::vector<double>> B_vals = {{0, 1, 0},\n                                               {1, 0, 0},\n                                               {0, 1, 0},\n                                               {1, 1, 0}};\n\n    grb::Matrix<double> A(A_vals, 0.);\n    grb::Matrix<double> B(B_vals, 0.);\n    grb::Matrix<double> NotLower(NotLower_3x4, 0.);\n    NotLower.setElement(0, 2, 0.);\n    grb::Matrix<double> Ones(Ones_3x4, 0.);\n    grb::Matrix<double> C(3, 4);\n\n    // REPLACE\n    std::vector<std::vector<double>> answer_vals = {{1, 0, 0, 0},\n                                                    {1, 2, 0, 0},\n                                                    {1, 5, 1, 0}};\n    grb::Matrix<double> answer(answer_vals, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B), REPLACE);\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Merge\n    std::vector<std::vector<double>> answer_vals2 = {{1, 1, 1, 1},\n                                                     {1, 2, 1, 1},\n                                                     {1, 5, 1, 1}};\n    grb::Matrix<double> answer2(answer_vals2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATBT_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  1,  1},\n                                             {4, 10,  1,  1},\n                                             {3, 11, 23,  1},\n                                             {1,  7, 22, 26}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 10,  0,  0},\n                                              {3, 11, 23,  0},\n                                              {1,  7, 22, 26}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = Ones;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATBT_ACdup)\n{\n\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(C), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATBT_BCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> Ones(Ones_4x4, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{3,  1,  0,  0},\n                                             {4, 11,  2,  0},\n                                             {2, 12, 25,  3},\n                                             {0,  6, 24, 29}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Double check previous operation (without duplicating)\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{3,  0,  0,  0},\n                                              {4, 11,  0,  0},\n                                              {2, 12, 25,  0},\n                                              {0,  6, 24, 29}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = mat;\n    grb::mxm(C,\n             complement(structure(NotLower)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(C),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATBT_MCdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n    grb::Matrix<double> NotLower(NotLower_4x4, 0.);\n    NotLower.setElement(0, 1, 0.);\n    grb::Matrix<double> C(4,4);\n\n    // Merge\n    std::vector<std::vector<double> > ans = {{2,  0,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {99, 6, 21, 25}};\n    grb::Matrix<double> answer(ans, 99.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(structure(C)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(C, answer);\n\n    // Replace\n    std::vector<std::vector<double> > ans2 = {{2,  0,  0,  0},\n                                              {3,  9,  0,  0},\n                                              {2, 10, 22,  0},\n                                              {0,  6, 21, 25}};\n    grb::Matrix<double> answer2(ans2, 0.);\n\n    C = NotLower;\n    grb::mxm(C,\n             complement(structure(C)),\n             grb::Plus<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat),\n             REPLACE);\n\n    BOOST_CHECK_EQUAL(C, answer2);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATBT_Replace_Cones_Mnlower)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   0,   0,  0},\n                                             { 74,  97,   0,  0},\n                                             {119, 157, 112,  0}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B),\n             REPLACE);\n    BOOST_CHECK_EQUAL(result.nvals(), 6);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATBT_Merge)\n{\n    grb::Matrix<double> A(AT_dense_3x3, 0.);\n    grb::Matrix<double> B(BT_dense_3x4, 0.);\n    grb::Matrix<double> M(NotLower_3x4, 0.);\n    M.setElement(0, 1, 0.);\n    BOOST_CHECK_EQUAL(M.nvals(), 6);\n\n    grb::Matrix<double> result(Ones_3x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{114,   1,   1,  1},\n                                             { 74,  97,   1,  1},\n                                             {119, 157, 112,  1}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::Second<double>(),\n             grb::ArithmeticSemiring<double>(), transpose(A), transpose(B));\n    BOOST_CHECK_EQUAL(result.nvals(), 12);\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(test_mxm_CompStructMask_Accum_ATBT_Merge_ABdup)\n{\n    // Build some matrices.\n    grb::Matrix<double> mat(Symmetric_4x4, 0.);\n\n    grb::Matrix<double> result(Ones_4x4, 0.);\n\n    std::vector<std::vector<double> > ans = {{2,  1,  1,  1},\n                                             {3,  9,  1,  1},\n                                             {2, 10, 22,  1},\n                                             {0,  6, 21, 25}};\n    grb::Matrix<double> answer(ans, 0.);\n\n    grb::Matrix<double> M(NotLower_4x4, 0.);\n    M.setElement(0, 1, 0.);\n\n    grb::mxm(result,\n             grb::complement(structure(M)),\n             grb::NoAccumulate(),\n             grb::ArithmeticSemiring<double>(), transpose(mat), transpose(mat));\n\n    BOOST_CHECK_EQUAL(result, answer);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "212c4607fa297f76c45b39306428c54745f0f64c", "size": 160539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_mxm_ATBT.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_mxm_ATBT.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_mxm_ATBT.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 34.0197075652, "max_line_length": 90, "alphanum_fraction": 0.4619998879, "num_tokens": 43569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5500224448596751}}
{"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}}
